blib/lib/Bio/AutomatedAnnotation/Prokka.pm untested

filter: Statementstmt 0.0% 0 / 622 Branchbran 0.0% 0 / 180 Conditioncond 0.0% 0 / 98 MC/DCmcdc n/a Subroutinesub 0.0% 0 / 27 Podpod 0.0% 0 / 11 totaltotal 0.0% 0 / 938 CC 91 SCAR 85.4
CC
91
Cov
0%
annotate
7140.0
cleanup_product
20.0
msg
12.0
CRAP 5127.7
1 package Bio::AutomatedAnnotation::Prokka;
2  
3 # ABSTRACT: Prokka class for bacterial annotation
4  
5  
6 # Copyright (C) 2012 Torsten Seemann
7 #
8 # This program is free software: you can redistribute it and/or modify
9 # it under the terms of the GNU General Public License as published by
10 # the Free Software Foundation, either version 3 of the License, or
11 # (at your option) any later version.
12 #
13 # This program is distributed in the hope that it will be useful,
14 # but WITHOUT ANY WARRANTY; without even the implied warranty of
15 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 # GNU General Public License for more details.
17 #
18 # You should have received a copy of the GNU General Public License
19 # along with this program. If not, see <http://www.gnu.org/licenses/>.
20  
21 use Moose;
22 use File::Copy;
23 use warnings;
24 use Time::Piece;
25 use Time::Seconds;
26 use XML::Simple;
27 use List::Util qw(min max sum);
28 use Scalar::Util qw(openhandle);
29 use Bio::SeqIO;
30 use Bio::SearchIO;
31 use Bio::Seq;
32 use Bio::SeqFeature::Generic;
33 use FindBin;
34 use POSIX;
35  
36 use Bio::AutomatedAnnotation::External::Cmscan;
37  
38 has 'assembly_file' => ( is => 'ro', isa => 'Str', required => 1 );
39  
40 has 'quiet' => ( is => 'rw', isa => 'Bool', default => 1 );
41 has 'outdir' => ( is => 'ro', isa => 'Str', default => '' );
42 has 'dbdir' => ( is => 'ro', isa => 'Str', default => '/tmp/prokka' );
43 has 'force' => ( is => 'ro', isa => 'Bool', default => 0 );
44 has 'prefix' => ( is => 'ro', isa => 'Str', default => '' );
45 has 'addgenes' => ( is => 'ro', isa => 'Bool', default => 0 );
46 has 'locustag' => ( is => 'ro', isa => 'Str', lazy => 1, builder => '_build_locustag' );
47 has 'increment' => ( is => 'ro', isa => 'Int', default => 1 );
48 has 'gffver' => ( is => 'ro', isa => 'Int', default => 3 );
49 has 'centre' => ( is => 'ro', isa => 'Str', default => 'VBC' );
50 has 'genus' => ( is => 'rw', isa => 'Str', default => 'Genus' );
51 has 'species' => ( is => 'ro', isa => 'Str', default => 'species' );
52 has 'strain' => ( is => 'ro', isa => 'Str', default => 'strain' );
53 has 'contig_uniq_id' => ( is => 'ro', isa => 'Str', default => 'gnl' );
54 has 'kingdom' => ( is => 'rw', isa => 'Str', default => 'Bacteria' );
55 has 'gcode' => ( is => 'ro', isa => 'Int', default => 11 );
56 has 'gram' => ( is => 'ro', isa => 'Str', default => '' );
57 has 'usegenus' => ( is => 'rw', isa => 'Bool', default => 0 );
58 has 'proteins' => ( is => 'ro', isa => 'Str', default => '' );
59 has 'fast' => ( is => 'ro', isa => 'Bool', default => 0 );
60 has 'cpus' => ( is => 'ro', isa => 'Int', default => 0 );
61 has 'mincontig' => ( is => 'ro', isa => 'Int', default => 200 );
62 has 'evalue' => ( is => 'ro', isa => 'Num', default => 1E-6 );
63 has 'rfam' => ( is => 'ro', isa => 'Bool', default => 0 );
64 has 'files_per_chunk' => ( is => 'ro', isa => 'Int', default => 100 );
65 has 'tempdir' => ( is => 'ro', isa => 'Str', default => '/tmp' );
66 has 'cleanup_prod' => ( is => 'ro', isa => 'Bool', default => 1 );
67 has 'keep_original_order_and_names' => ( is => 'ro', isa => 'Bool', default => 0 );
68  
69 has 'exe' => ( is => 'ro', isa => 'Str', default => 'PROKKA' );
70 has 'version' => ( is => 'ro', isa => 'Str', default => '1.5' );
71 has 'author' => ( is => 'ro', isa => 'Str', default => 'Torsten Seemann <torsten.seemann@monash.edu>' );
72 has 'url' => ( is => 'ro', isa => 'Str', default => 'http://www.vicbioinformatics.com' );
73 has 'hypo' => ( is => 'ro', isa => 'Str', default => 'hypothetical protein' );
74 has 'unann' => ( is => 'ro', isa => 'Str', default => 'unannotated protein' );
75 has 'blastcmd' => (
76 is => 'ro',
77 isa => 'Str',
78 default =>
79 "blastp -query %i -db %d -evalue %e -num_threads 1 -out %o -num_descriptions 1 -num_alignments 1 2>/dev/null"
80 );
81 has 'hmmer3cmd' =>
82 ( is => 'ro', isa => 'Str', default => "hmmscan --noali --notextw --acc -E %e --cpu 1 -o %o %d %i 2>/dev/null" );
83 has 'infernalcmd' =>
84 ( is => 'ro', isa => 'Str', default => "cmscan --noali --notextw --acc -E %e --cpu 1 -o %o %d %i 2>/dev/null" );
85 has 'starttime' => (
86 is => 'ro',
87 isa => 'Time::Piece',
88 lazy => 1,
89 builder => '_build_starttime'
90 );
91  
92 sub _build_starttime {
93 my ($self) = @_;
94 return localtime;
95 }
96  
97 sub _build_locustag {
98 my ($self) = @_;
99 return $self->exe;
100 }
101  
102 sub annotate {
103 my ($self) = @_;
104 my $AUTHOR = $self->author;
105 my $BLASTPCMD = $self->blastcmd;
106 my $EXE = $self->exe;
107 my $HMMER3CMD = $self->hmmer3cmd;
108 my $HYPO = $self->hypo;
109 my $INFERNALCMD = $self->infernalcmd;
110 my $UNANN = $self->unann;
111 my $URL = $self->url;
112 my $VERSION = $self->version;
113 my $addgenes = $self->addgenes;
114 my $centre = $self->centre;
115 my $contig_uniq_id = $self->contig_uniq_id;
116 my $cpus = $self->cpus;
117 my $dbdir = $self->dbdir;
118 my $evalue = $self->evalue;
119 my $fast = $self->fast;
120 my $files_per_chunk = $self->files_per_chunk;
121 my $force = $self->force;
122 my $gcode = $self->gcode;
123 my $genus = $self->genus;
124 my $gffver = $self->gffver;
125 my $gram = $self->gram;
126 my $increment = $self->increment;
127 my $kingdom = $self->kingdom;
128 my $locustag = $self->locustag;
129 my $mincontig = $self->mincontig;
130 my $outdir = $self->outdir;
131 my $prefix = $self->prefix;
132 my $proteins = $self->proteins;
133 my $quiet = $self->quiet;
134 my $rfam = $self->rfam;
135 my $species = $self->species;
136 my $starttime = $self->starttime;
137 my $strain = $self->strain;
138 my $tempdir = $self->tempdir;
139 my $usegenus = $self->usegenus;
140  
141 my %seq;
142  
143 # . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
144 # welcome message
145  
146 $self->msg("This is $EXE $VERSION");
147 $self->msg("$AUTHOR");
148 $self->msg("Victorian Bioinformatics Consortium - $URL");
149 $self->msg("Local time is $starttime");
150  
151 # . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
152 # set up options based on --mode
153  
154 if ( $kingdom =~ m/bac|prok/i ) {
155 $kingdom = 'Bacteria';
156 $gcode ||= 11;
157 }
158 elsif ( $kingdom =~ m/arch/i ) {
159 $kingdom = 'Archaea';
160 $gcode ||= 11;
161 $gram = '';
162 }
163 elsif ( $kingdom =~ m/vir/i ) {
164 $kingdom = 'Viruses';
165 $gcode ||= 1; # std
166 $gram = '';
167 }
168 else {
169 $self->err("Can't parse --mode '$kingdom'. Choose from: Bacteria Archaea Virus");
170 }
171 $self->msg("Annotating as >>> $kingdom <<<");
172  
173 # . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
174 # check options
175  
176 ( $gcode < 1 or $gcode > 24 ) and $self->err("Invalid genetic code, must be 1..24");
177 $evalue >= 0 or $self->err("Invalid --evalue, must be >= 0");
178  
179 #($coverage >= 0 and $coverage <= 100) or $self->err("Invalid --coverage, must be 0..100");
180 $increment >= 1 or $self->err("Invalid --increment, must be >= 1");
181 $locustag ||= uc($EXE);
182  
183 # http://www.ncbi.nlm.nih.gov/genomes/static/Annotation_pipeline_README.txt
184 $prefix ||= $locustag . '_' . ( localtime->mdy('') ); # NCBI wants US format, ech.
185 $outdir ||= $prefix;
186 if ( -d $outdir ) {
187 if ($force) {
188 $self->msg("Re-using existing --outdir $outdir");
189 }
190 else {
191 $self->err("Folder '$outdir' already exists! Please change --outdir or use --force");
192 }
193 }
194 else {
195 $self->msg("Creating new output folder: $outdir");
196 $self->runcmd("mkdir -p \Q$outdir\E");
197 }
198 $self->msg("Using filename prefix: $prefix.XXX");
199  
200 # canonical names
201 $genus = ucfirst( lc($genus) ) if $genus;
202 $species = lc($species) if $strain;
203  
204 # . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
205 # set up log file
206  
207 my $logfile = "$outdir/$prefix.log";
208 $self->msg("Writing log to: $logfile");
209 open LOG, '>', $logfile or $self->err("Can't open logfile");
210  
211 # . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
212 # check dependencies
213  
214 for my $exe (
215 qw(less grep egrep sed find tbl2asn makeblastdb blastp
216 aragorn prodigal rnammer parallel hmmscan cmscan)
217 )
218 {
219 my $fp = $self->require_exe($exe);
220 $fp ? $self->msg("Need '$exe' - using $fp") : $self->err("Can't find $exe in your \$PATH");
221 }
222  
223 # Heikki discovered moreutils.deb contains a really old 'parallel' tool....
224 my ($pout) = qx(parallel -V 2> /dev/null);
225 if ( $pout !~ m/GNU/ ) {
226 $self->err("You don't have GNU 'parallel' installed, you have a different tool with that name.");
227 }
228  
229 # . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
230 # get versions of tools
231 # FIXME - put these in a hash with regexps!
232  
233 my %tools = (
234 'aragorn' => {
235 GETVER => "aragorn -h 2>&1 | grep -i '^ARAGORN v'",
236 REGEXP => qr/([\d\.]+)/,
237 VERSION => "1.2",
238 },
239 'rnammer' => {
240 GETVER => "rnammer -V 2>&1 | grep -i 'rnammer [0-9]'",
241 REGEXP => qr/([\d\.]+)/,
242 VERSION => "1.2",
243 },
244 'prodigal' => {
245 GETVER => "prodigal -v 2>&1 | grep -i '^Prodigal V'",
246 REGEXP => qr/([\d\.]+)/,
247 VERSION => "2.6",
248 },
249 'signalp' => {
250  
251 # this is so long-winded as -v changed meaning (3.0=version, 4.0=verbose !?)
252 GETVER => "signalp -v < /dev/null 2>&1 | egrep ',|# SignalP' | sed 's/^# SignalP-//'",
253 REGEXP => qr/^(.*?)[,\s]/,
254 VERSION => "4.0",
255 },
256 'infernal' => {
257 GETVER => "cmscan -h | grep '^# INFERNAL'",
258 REGEXP => qr/INFERNAL ([\d\.]+)/,
259 VERSION => "1.0",
260 },
261 );
262  
263 for my $toolname ( keys %tools ) {
264 my $t = $tools{$toolname};
265 my ($s) = qx($t->{GETVER});
266 if ( defined $s ) {
267 $s =~ $t->{REGEXP};
268 $t->{VERSION} = $1 if defined $1;
269 }
270 else {
271 $self->msg("Could not determine version of $toolname ...");
272 }
273 $self->msg("Determined $toolname version is $t->{VERSION}");
274 }
275  
276 if ( $rfam and $tools{infernal}{VERSION} < 1.1 ) {
277 $self->err("This script only supports --rfam with Infernal (ie. cmscan) version 1.1 or higher");
278 }
279  
280 $gcode ||= 1;
281 $self->msg("Using genetic code table $gcode.");
282  
283 # . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
284 # read in sequences; remove small contigs; replace ambig with N
285  
286 my $in = $self->assembly_file;
287 $self->msg("Loading and checking input file: $in");
288 my $fin = Bio::SeqIO->new( -file => $in, -format => 'fasta' );
289 my $fout = Bio::SeqIO->new( -file => ">$outdir/$prefix.fna", -format => 'fasta' );
290 my $ncontig = 0;
291 while ( my $seq = $fin->next_seq ) {
292 if ( $seq->length < $mincontig ) {
293 $self->msg( "Skipping short (<$mincontig bp) contig:", $seq->display_id );
294 next;
295 }
296 $ncontig++;
297 my $id;
298 # http://www.ncbi.nlm.nih.gov/genomes/static/Annotation_pipeline_README.txt
299 if($self->keep_original_order_and_names)
300 {
301 $id = $seq->display_id;
302 }
303 else
304 {
305 $id = sprintf "contig%06d", $ncontig;
306 $id = "$contig_uniq_id|$centre|$id" if $centre;
307 $seq->display_id($id);
308 }
309
310 my $s = $seq->seq;
311 $s = uc($s);
312 $s =~ s/[^ACTG]/N/g;
313 $seq->seq($s);
314 $seq->desc(undef);
315 $fout->write_seq($seq);
316 $seq{$id}{DNA} = $seq;
317 $seq{$id}{order} = $ncontig;
318 }
319 $self->msg("Wrote $ncontig contigs");
320  
321 #$self->msg(sort keys %seq); exit;
322  
323 # . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
324 # tRNA + tmRNA
325  
326 $self->msg("Predicting tRNAs and tmRNAs");
327 my $cmd = "aragorn -gc$gcode -w $outdir/$prefix.fna"; # -t/-m
328 $self->msg("Running: $cmd");
329 my $num_trna = 0;
330 open TRNA, "$cmd |";
331 my $sid;
332 while (<TRNA>) {
333 chomp;
334 if (m/^>end/) {
335 last;
336 }
337
338 if (m/^>(\S+)/) {
339 $sid = $1;
340 next;
341 }
342 my @x = split m/\s+/;
343 next unless @x == 5 and $x[0] =~ m/^\d+$/;
344  
345 # and $x[4] =~ m/^\([ATCG]{3}\)$/i;
346 #$self->msg($_);
347 $self->msg("@x");
348 $x[2] =~ m/(c)?\[(\d+),(\d+)\]/;
349 my ( $revcom, $start, $end ) = ( $1, $2, $3 );
350  
351 # bug fix for aragorn when revcom trna ends at start of contig!
352 # if (defined $revcom and $start > $end) {
353 # $self->msg("Activating kludge for Aragorn bug for tRNA end at contig start");
354 # $start = 1;
355 # }
356 if ( $start > $end ) {
357 $self->msg("tRNA $x[2] has start($start) > end ($end) - skipping.");
358 next;
359 }
360 if ( abs( $end - $start ) > 500 ) {
361 $self->msg("tRNA/tmRNA $x[2] is too big (>500bp) - skipping.");
362 next;
363 }
364  
365 # end kludge
366 $num_trna++;
367  
368 my $ftype = 'tRNA';
369 my $product = $x[1] . $x[4];
370 my @gene = ();
371 if ( $x[1] eq 'tmRNA' ) {
372 $ftype = $x[1];
373 $product = "transfer-messenger RNA, SsrA";
374 @gene = ( 'gene' => 'ssrA' );
375 }
376  
377 my $tool = "Aragorn:" . $tools{aragorn}->{VERSION};
378 push @{ $seq{$sid}{FEATURE} }, Bio::SeqFeature::Generic->new(
379 -primary => $ftype, # tRNA or tmRNA
380 -seq_id => $sid,
381 -source => $tool,
382 -start => $start,
383 -end => $end,
384 -strand => ( defined $revcom ? -1 : +1 ),
385 -score => undef,
386 -frame => 0,
387 -tag => {
388 'product' => $product,
389 'inference' => "COORDINATES:profile:$tool",
390 @gene,
391 }
392 );
393 }
394 $self->msg("Found $num_trna tRNAs");
395  
396 # . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
397 # rRNA
398  
399 if ( $kingdom ne 'Viruses' ) {
400 $self->msg("Predicting Ribosomal RNAs");
401 my $rnammerfn = "$outdir/rnammer.xml";
402 my $num_rrna = 0;
403 my $rnammer_opt = $cpus != 1 ? "-multi" : "";
404 $self->runcmd("rnammer -S bac $rnammer_opt -xml $rnammerfn $outdir/$prefix.fna");
405 my $xml = XML::Simple->new( ForceArray => 1 );
406 my $data = $xml->XMLin($rnammerfn);
407 for my $entry ( @{ $data->{entries}[0]->{entry} } ) {
408 my $sid = $entry->{sequenceEntry}[0];
409 next unless exists $seq{$sid};
410 my $desc = $entry->{mol}[0];
411 $desc =~ s/s_r/S ribosomal /i; # make it English '23S_rRNA => 23S ribosomal RNA'
412 $num_rrna++;
413 my $tool = "RNAmmer:" . $tools{rnammer}->{VERSION};
414 push @{ $seq{$sid}{FEATURE} }, Bio::SeqFeature::Generic->new(
415 -primary => 'rRNA',
416 -seq_id => $sid,
417 -source => $tool, # $data->{predictor}[0]
418 -start => $entry->{start}[0],
419 -end => $entry->{stop}[0],
420 -strand => $entry->{direction}[0],
421 -score => undef, # $entry->{score}[0],
422 -frame => 0,
423 -tag => {
424 'product' => $desc,
425 'inference' => "COORDINATES:profile:$tool", # FIXME version
426 }
427 );
428 $self->msg(
429 join "\t", $num_rrna, $desc, $sid,
430 $entry->{start}[0],
431 $entry->{stop}[0],
432 $entry->{direction}[0]
433 );
434 }
435 $self->delfile($rnammerfn);
436 $self->msg("Found $num_rrna rRNAs");
437 }
438 else {
439 $self->msg("Disabling rRNA search for $kingdom.");
440 }
441  
442 # . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
443 # ncRNA via Rfam + Infernal
444  
445 my $cmdb = "$dbdir/cm/$kingdom";
446 if ( $rfam and -r "$cmdb.i1m" ) {
447 $self->msg("Scanning for ncRNAs... please be patient.");
448  
449 my $cmscan_obj = Bio::AutomatedAnnotation::External::Cmscan->new(
450 cmdb => $cmdb,
451 input_file => "$outdir/$prefix.fna",
452 exec => 'cmscan',
453 version => $tools{infernal}->{VERSION},
454 cpus => $cpus,
455 evalue => $evalue,
456 );
457 $cmscan_obj->add_features_to_prokka_structure(\%seq);
458
459 $self->msg("Found ".$cmscan_obj->number_of_features." ncRNAs.");
460 }
461 else {
462 $self->msg("Disabling ncRNA search, can't find $cmdb file.");
463 }
464  
465 # . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
466 # Tally all the RNA features so we can exclude overlaps with CDS
467  
468 my @allrna;
469 for my $sid ( sort keys %seq ) {
470 push @allrna, ( grep { $_->primary_tag =~ m/RNA/ } @{ $seq{$sid}{FEATURE} } );
471 }
472 $self->msg( "Total of", scalar(@allrna), "RNA features" );
473  
474 # . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
475 # CDS
476  
477 $self->msg("Predicting coding sequences");
478 my $totalbp = sum( map { $seq{$_}{DNA}->length } keys %seq );
479 my $prodigal_mode = $totalbp >= 100000 ? 'single' : 'meta';
480 $self->msg("Contigs total $totalbp bp, so using $prodigal_mode mode");
481 my $num_cds = 0;
482 $cmd = "prodigal -i $outdir/$prefix.fna -c -m -g $gcode -p $prodigal_mode -f sco -q";
483 $self->msg("Running: $cmd");
484 open CDS, "$cmd |";
485 while (<CDS>) {
486  
487 if (m/seqhdr="([^\s\"]+)"/) {
488 $sid = $1;
489  
490 # $self->msg("CDS $sid");
491 next;
492 }
493 elsif (m/^>\d+_(\d+)_(\d+)_([+-])$/) {
494 my $tool = "Prodigal:" . $tools{prodigal}->{VERSION};
495 my $cds = Bio::SeqFeature::Generic->new(
496 -primary => 'CDS',
497 -seq_id => $sid,
498 -source => $tool,
499 -start => $1,
500 -end => $2,
501 -strand => ( $3 eq '+' ? +1 : -1 ),
502 -score => undef,
503 -frame => 0,
504 -tag => {
505 'inference' => "ab initio prediction:$tool",
506 }
507 );
508 my $overlap;
509 for my $rna (@allrna) {
510  
511 # same contig, overlapping (could check same strand too? not sure)
512 if ( $rna->seq_id eq $sid and $cds->overlaps($rna) ) {
513 $overlap = $rna;
514 last;
515 }
516 }
517 if ($overlap) {
518 $self->msg("Not including CDS which overlaps existing RNA at $sid:$1..$2 on $3 strand");
519 }
520 else {
521 $num_cds++;
522 push @{ $seq{$sid}{FEATURE} }, $cds;
523 }
524 }
525 }
526 $self->msg("Found $num_cds CDS");
527  
528 # . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
529 # Connect features to their parent sequences
530  
531 $self->msg("Connecting features back to sequences");
532 for my $sid ( sort keys %seq ) {
533 for my $f ( @{ $seq{$sid}{FEATURE} } ) {
534 $f->attach_seq( $seq{$sid}{DNA} );
535 }
536 }
537  
538 # . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
539 # Find signal peptide leader sequences
540  
541 my $sigpver = substr $tools{signalp}{VERSION}, 0, 1; # first char, expect 3 or 4
542  
543 if ( $kingdom eq 'Bacteria' and $sigpver == 3 || $sigpver == 4 ) {
544 if ($gram) {
545 $gram = $gram =~ m/\+|[posl]/i ? 'gram+' : 'gram-';
546 $self->msg("Looking for signal peptides at start of predicted proteins");
547 $self->msg("Treating $kingdom as $gram");
548 my $spoutfn = "$outdir/signalp.faa";
549 my $spout = Bio::SeqIO->new( -file => ">$spoutfn", -format => 'fasta' );
550 my %cds;
551 my $count = 0;
552 for my $sid ( sort keys %seq ) {
553  
554 for my $f ( @{ $seq{$sid}{FEATURE} } ) {
555 next unless $f->primary_tag eq 'CDS';
556 $cds{ ++$count } = $f;
557 my $seq = $f->seq->translate;
558 $seq->display_id($count);
559 $spout->write_seq($seq);
560 }
561 }
562 my $opts = $sigpver == 3 ? '-m hmm' : '';
563 my $cmd = "signalp -t $gram -f short $opts $spoutfn 2> /dev/null";
564  
565 $self->msg("Running: $cmd");
566 my $tool = "SignalP:" . $tools{signalp}->{VERSION};
567 my $num_sigpep = 0;
568 open SIGNALP, "$cmd |";
569 while (<SIGNALP>) {
570 my @x = split m/\s+/;
571 if ( $sigpver == 3 ) {
572 next unless @x == 7 and $x[6] eq 'Y'; # has sig_pep
573 my $parent = $cds{ $x[0] };
574 my $prob = $x[5];
575 my $cleave = $x[3];
576 my $start = $parent->strand > 0 ? $parent->start : $parent->end;
577 my $end = $start + $parent->strand * ( $cleave - 1 );
578 my $sigpep = Bio::SeqFeature::Generic->new(
579 -seq_id => $parent->seq_id,
580 -source_tag => $tool,
581 -primary => 'sig_peptide',
582 -start => min( $start, $end ),
583 -end => max( $start, $end ),
584 -strand => $parent->strand,
585 -frame => 0, # PHASE: compulsory for peptides, can't be '.'
586 -tag => {
587  
588 # 'ID' => $ID,
589 # 'Parent' => $x[0], # don't have proper IDs yet....
590 'product' => "putative signal peptide",
591 'inference' => "ab initio prediction:$tool",
592 'note' => "predicted cleavage at residue $x[3] with probability $prob",
593 }
594 );
595 push @{ $seq{ $parent->seq_id }{FEATURE} }, $sigpep;
596 $num_sigpep++;
597 }
598 else {
599 # $self->msg("sigp$sigpver: @x");
600 next unless @x == 12 and $x[9] eq 'Y'; # has sig_pep
601 my $parent = $cds{ $x[0] };
602 my $cleave = $x[2];
603 my $start = $parent->strand > 0 ? $parent->start : $parent->end;
604 my $end = $start + $parent->strand * ( $cleave - 1 );
605 my $sigpep = Bio::SeqFeature::Generic->new(
606 -seq_id => $parent->seq_id,
607 -source_tag => $tool,
608 -primary => 'sig_peptide',
609 -start => min( $start, $end ),
610 -end => max( $start, $end ),
611 -strand => $parent->strand,
612 -frame => 0, # PHASE: compulsory for peptides, can't be '.'
613 -tag => {
614  
615 # 'ID' => $ID,
616 # 'Parent' => $x[0], # don't have proper IDs yet....
617 'product' => "putative signal peptide",
618 'inference' => "ab initio prediction:$tool",
619 'note' => "predicted cleavage at residue $x[2]",
620 }
621 );
622 push @{ $seq{ $parent->seq_id }{FEATURE} }, $sigpep;
623 $num_sigpep++;
624 }
625 }
626 $self->msg("Found $num_sigpep signal peptides");
627 $self->delfile($spoutfn);
628 }
629 else {
630 $self->msg("Option --gram not specified, will NOT check for signal peptides.");
631 }
632 }
633  
634 # . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
635 # Annotate CDS
636  
637 #my %dbof = ( 'PF'=>'Pfam', 'TIGR'=>'TIGRFAMs', 'PRK'=>'Cdd', 'COG'=>'COG' );
638  
639 # primary data source is a curated subset of uniprot (evidence <= 1 per Phylum)
640 my @database = (
641 {
642 DB => "$dbdir/kingdom/$kingdom/sprot",
643 SRC => 'similar to AA sequence:UniProtKB:',
644 FMT => 'blast',
645 CMD => $BLASTPCMD,
646 },
647 );
648  
649 # secondary sources are a series of HMMs
650 unless ( $kingdom eq 'Viruses' ) {
651 for my $name (qw(CLUSTERS Cdd TIGRFAMs Pfam)) {
652 push @database,
653 {
654 DB => "$dbdir/hmm/$name.hmm",
655 SRC => "protein motif:$name:",
656 FMT => 'hmmer',
657 VERSION => 3,
658 CMD => $HMMER3CMD,
659 };
660 }
661 }
662  
663 # if --usegenus is enabled
664 # AND user supplies a genus, and we have a custom file (from GenBank) do it first!
665 if ($usegenus) {
666 if ( $genus and -r "$dbdir/genus/$genus.pin" ) {
667 my $blastdb = "$dbdir/genus/$genus";
668 $self->msg("Using custom $genus database for annotation");
669 unshift @database,
670 {
671 DB => $blastdb,
672 SRC => 'similar to AA sequence:RefSeq:',
673 FMT => 'blast',
674 CMD => $BLASTPCMD,
675 };
676 }
677 else {
678 $self->msg("Skipping genus-specific proteins as can't see $dbdir/$genus");
679 }
680 }
681 else {
682 $self->msg("Not using genus-specific database. Try --usegenus to enable it.");
683 }
684  
685 # if user supplies a trusted set of proteins, we try these first!
686 if ( -r $proteins ) {
687 $self->msg("Preparing user-supplied primary annotation source: $proteins");
688 $self->runcmd("makeblastdb -dbtype prot -in '$proteins' -out $outdir/proteins -logfile /dev/null");
689 unshift @database,
690 {
691 DB => "$outdir/proteins",
692 SRC => 'similar to AA sequence:RefSeq:',
693 FMT => 'blast',
694 CMD => $BLASTPCMD,
695 };
696 }
697  
698 if ($fast) {
699 $self->msg("Option --fast enabled, so skipping CDS similarity searches");
700 }
701 else {
702 $self->msg("Annotating CDS, please be patient.");
703  
704 my $paropts = $cpus > 0 ? " -j $cpus" : "";
705 $self->msg( "Will use", ( $cpus > 0 ? $cpus : 'all available' ), "CPUs for similarity searching." );
706  
707 my $num_cleaned = 0;
708 my %cds;
709 my $count = 0;
710  
711 for my $sid ( sort keys %seq ) {
712 for my $f ( @{ $seq{$sid}{FEATURE} } ) {
713 next unless $f->primary_tag eq 'CDS';
714 next if $f->has_tag('product');
715 $cds{ ++$count } = $f;
716 }
717 }
718  
719 if ( $count > 0 ) {
720  
721 # Minimise the number of files created at a time. Tradeoff with efficiency of parallelisation.
722 # This creates X files per CPU.
723 my $slice_size = ( ( $cpus > 0 ) ? $cpus : 1 ) * ( ( $files_per_chunk <= 0 ) ? 10 : $files_per_chunk );
724 my @cds_counter = sort( keys %cds );
725 for ( my $i = 0 ; $i < ceil( (@cds_counter) / $slice_size ) ; $i++ ) {
726 for ( my $j = $slice_size * $i ; $j < @cds_counter && $j < $slice_size * ( $i + 1 ) ; $j++ ) {
727 $self->create_cds_sequences_in_file( $tempdir, $cds_counter[$j], $cds{ $cds_counter[$j] } );
728 }
729  
730 for my $db (@database) {
731 my $cmd = $db->{CMD};
732 $cmd =~ s/%i/{}/g;
733 $cmd =~ s/%o/{}.out/g;
734 $cmd =~ s/%e/$evalue/g;
735 $cmd =~ s,%d,$db->{DB},g;
736 $self->msg( $db->{FMT}, "$count (of $num_cds) proteins against", $db->{DB} );
737  
738 $self->runcmd("nice parallel$paropts $cmd ::: $tempdir/*.seq");
739  
740 for ( my $j = $slice_size * $i ; $j < @cds_counter && $j < $slice_size * ( $i + 1 ) ; $j++ ) {
741 my $pid = $cds_counter[$j];
742 my $bls = Bio::SearchIO->new( -file => "$tempdir/$pid.seq.out", -format => $db->{FMT}, -version => $db->{VERSION} );
743 my $res = $bls->next_result or next;
744 my $hit = $res->next_hit or next;
745 my ( $prod, $gene, $EC ) = ( $hit->description, '', '' );
746 if ( $prod =~ m/~~~/ ) {
747 ( $EC, $gene, $prod ) = split m/~~~/, $prod;
748 $EC =~ s/n\d+/-/g; # collapse transitionary EC numbers
749 }
750 my $cleanprod = $prod;
751  
752 if ( $self->cleanup_prod ) {
753 $cleanprod = $self->cleanup_product($prod);
754 if ( $cleanprod ne $prod ) {
755 $self->msg("Modify product: $prod => $cleanprod");
756 if ( $cleanprod eq $HYPO ) {
757 $cds{$pid}->add_tag_value( 'note', $prod );
758 $cds{$pid}->remove_tag('gene') if $cds{$pid}->has_tag('gene');
759 $cds{$pid}->remove_tag('EC_number') if $cds{$pid}->has_tag('EC_number');
760 }
761 $num_cleaned++;
762 }
763 }
764 $cds{$pid}->add_tag_value( 'product', $cleanprod );
765 $cds{$pid}->add_tag_value( 'EC_number', $EC ) if $EC;
766  
767 if ( defined($gene) && $gene ne "" && !$cds{$pid}->has_tag('gene') ) {
768 $cds{$pid}->add_tag_value( 'gene', $gene );
769 }
770 $cds{$pid}->add_tag_value( 'inference', $db->{SRC} . $hit->name );
771  
772 unlink "$tempdir/$pid.seq.out";
773 }
774 }
775 unlink map { "$tempdir/$_.seq" } keys %cds;
776 unlink map { "$tempdir/$_.seq.out" } keys %cds;
777 }
778  
779 unlink map { "$tempdir/$_.seq" } keys %cds;
780 unlink map { "$tempdir/$_.seq.out" } keys %cds;
781  
782 $self->msg("Cleaned $num_cleaned /product names") if $num_cleaned > 0;
783 }
784 }
785  
786 if ($proteins) {
787 $self->delfile( map { "$outdir/proteins.$_" } qw(psq phr pin) );
788 }
789  
790 # . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
791 # Label unannotated proteins as 'hypothetical protein'
792  
793 my $empty_label = $fast ? 'unannotated protein' : $HYPO;
794 my $num_hypo = 0;
795 for my $sid ( sort keys %seq ) {
796 for my $f ( @{ $seq{$sid}{FEATURE} } ) {
797 if ( $f->primary_tag eq 'CDS' and not $f->has_tag('product') ) {
798 $f->add_tag_value( 'product', $empty_label );
799 $num_hypo++;
800 }
801 }
802 }
803 $self->msg("Labelling remaining $num_hypo proteins as '$empty_label'") if $num_hypo > 0;
804  
805 # . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
806 # Look for possible /pseudo genes - adjacent with same annotation
807  
808 for my $sid ( sort keys %seq ) {
809 my $prev = '';
810 for my $f ( grep { $_->primary_tag eq 'CDS' } @{ $seq{$sid}{FEATURE} } ) {
811 my $this = $self->tag( $f, 'product' );
812 if ( $this eq $prev and $this ne $HYPO and $this ne $UNANN ) {
813 $self->msg( "Possible /pseudo '$prev' at", $f->seq_id, 'position', $f->start );
814 }
815 $prev = $this;
816 $this = '';
817 }
818 }
819  
820 # . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
821 # Fix colliding /gene names in CDS (before we add 'gene' features)
822 # (this could be written as such a nice map/map/grep one day...)
823  
824 my %collide;
825  
826 for my $sid ( sort keys %seq ) {
827 for my $f ( sort { $a->start <=> $b->start } @{ $seq{$sid}{FEATURE} } ) {
828 next unless $f->primary_tag eq 'CDS';
829 my $gene = $self->tag( $f, 'gene' ) or next;
830 push @{ $collide{$gene} }, $f;
831 }
832 }
833 $self->msg( "Found", scalar( keys(%collide) ), "unique /gene codes." );
834  
835 my $num_collide = 0;
836 for my $gene ( keys %collide ) {
837 my @cds = @{ $collide{$gene} };
838 next unless @cds > 1;
839 my $n = 0;
840 for my $f (@cds) {
841 $f->remove_tag('gene');
842 $n++;
843 $f->add_tag_value( 'gene', "${gene}_${n}" );
844 }
845 $num_collide++;
846 }
847 $self->msg("Fixed $num_collide colliding /gene names.");
848  
849 # . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
850 # Add locus_tags and protein_id[CDS only] (and Parent genes if asked)
851  
852 my $num_lt = 0;
853 for my $sid ( sort keys %seq ) {
854 for my $f ( sort { $a->start <=> $b->start } @{ $seq{$sid}{FEATURE} } ) {
855 next unless $f->primary_tag =~ m/CDS|RNA/;
856 $num_lt++;
857 my $ID = sprintf( "${locustag}_%05d", $num_lt * $increment );
858 $f->add_tag_value( 'ID', $ID );
859 $f->add_tag_value( 'locus_tag', $ID );
860 $f->add_tag_value( 'protein_id', "gnl|$centre|$ID" ) if $f->primary_tag eq 'CDS';
861 if ($addgenes) {
862 my $g = $f->clone;
863 $g->primary_tag('gene');
864 $g->source_tag($EXE);
865 $g->remove_tag($_) for $g->get_all_tags;
866 $g->add_tag_value( 'locus_tag', $ID );
867 if ( my $gENE = $self->tag( $f, 'gene' ) ) {
868 $g->add_tag_value( 'gene', $gENE );
869 }
870 push @{ $seq{$sid}{FEATURE} }, $g;
871 }
872 }
873 }
874 $self->msg("Assigned $num_lt locus_tags to CDS and RNA features.");
875  
876 # . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
877 # Write it all out!
878  
879 $self->msg("Writing outputs to $outdir/");
880 open my $gff_fh, '>', "$outdir/$prefix.gff";
881 my $faa_fh = Bio::SeqIO->new( -file => ">$outdir/$prefix.faa", -format => 'fasta' );
882 my $ffn_fh = Bio::SeqIO->new( -file => ">$outdir/$prefix.ffn", -format => 'fasta' );
883 open my $tbl_fh, '>', "$outdir/$prefix.tbl";
884 my $fsa_fh = Bio::SeqIO->new( -file => ">$outdir/$prefix.fsa", -format => 'fasta' );
885  
886 my $gff_factory = Bio::Tools::GFF->new( -gff_version => $gffver );
887 print $gff_fh "##gff-version $gffver\n";
888 for my $id ( sort keys %seq ) {
889 print $gff_fh "##sequence-region $id 1 ", $seq{$id}{DNA}->length, "\n";
890 }
891  
892 my $fsa_desc = "[gcode=$gcode] [organism=$genus $species] [strain=$strain]";
893  
894 for my $sid ( sort keys %seq ) {
895 my $ctg = $seq{$sid}{DNA};
896 $ctg->desc($fsa_desc);
897 $fsa_fh->write_seq($ctg);
898 $ctg->desc(undef);
899 print $tbl_fh ">Feature $sid\n";
900 for my $f ( sort { $a->start <=> $b->start } @{ $seq{$sid}{FEATURE} } ) {
901 if ( $f->primary_tag eq 'CDS' and not $f->has_tag('product') ) {
902 $f->add_tag_value( 'product', $HYPO );
903 }
904  
905 print $gff_fh $f->gff_string($gff_factory), "\n";
906  
907 my ( $L, $R ) = ( $f->strand >= 0 ) ? ( $f->start, $f->end ) : ( $f->end, $f->start );
908 print {$tbl_fh} "$L\t$R\t", $f->primary_tag, "\n";
909 for my $tag ( $f->get_all_tags ) {
910 next if $tag =~ m/^(ID|Alias)$/; # remove GFF specific tags
911 for my $value ( $f->get_tag_values($tag) ) {
912 print {$tbl_fh} "\t\t\t$tag\t$value\n";
913 }
914 }
915  
916 my $p = $seq{$sid}{DNA}->trunc( $f->location );
917 $p->display_id( $self->tag( $f, 'locus_tag' ) );
918 $p->desc( $self->tag( $f, 'product' ) ) if $f->has_tag('product');
919 unless ( $addgenes and $f->primary_tag eq 'gene' ) {
920 $ffn_fh->write_seq($p);
921 }
922 if ( $f->primary_tag eq 'CDS' ) {
923 $faa_fh->write_seq( $p->translate( -codontable_id => $gcode ) );
924 }
925 }
926 }
927  
928 if ( scalar keys %seq ) {
929 print $gff_fh "##FASTA\n";
930 my $seqio = Bio::SeqIO->new( -fh => $gff_fh, -format => 'fasta' );
931
932 if($self->keep_original_order_and_names)
933 {
934 for my $sid ( sort {$seq{$a}{order} <=> $seq{$b}{order} } keys %seq ) {
935 $seqio->write_seq( $seq{$sid}{DNA} );
936 }
937 }
938 else
939 {
940 for my $sid ( sort keys %seq ) {
941 $seqio->write_seq( $seq{$sid}{DNA} );
942 }
943 }
944 }
945  
946 # . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
947 # Use tbl2asn tool to make .gbk and .sqn for us
948  
949 $self->msg("Generating Genbank and Sequin files");
950 $self->runcmd(
951 "tbl2asn -N 1 -y 'Annotated using $EXE $VERSION from $URL' -Z $outdir/$prefix.err -M n -V b -i $outdir/$prefix.fsa -f $outdir/$prefix.tbl 2> /dev/null"
952 );
953 $self->delfile("$outdir/errorsummary.val");
954 $self->delfile( map { "$outdir/$prefix.$_" } qw(dr fixedproducts ecn val) );
955 move( "$outdir/$prefix.gbf", "$outdir/$prefix.gbk" ); # rename XXX.gbf to XXX.gbk
956  
957 # . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
958 # Some final log output
959  
960 $self->msg("Output files:");
961 foreach (qx(find $outdir -type f -name "$prefix.*")) {
962 chomp;
963 $self->msg($_);
964 }
965 my $endtime = localtime;
966 my $walltime = $endtime - $starttime;
967  
968 #$self->msg("Walltime used:", $walltime->pretty); # Heikki says this method only came with 1.20
969 my $pretty = sprintf "%.2f minutes", $walltime->minutes;
970 $self->msg("Walltime used: $pretty");
971 $self->msg( $walltime % 2 ? "Share and enjoy!" : "Thank you, come again." );
972  
973 #EXIT
974  
975 }
976  
977 sub cleanup_product {
978 my ( $self, $p ) = @_;
979 return $self->hypo if $p =~ m/DUF\d|UPF\d|conserved|domain of unknown|[CN].term|homolog|paralog/i;
980 return $self->hypo if $p !~ m/[a-z]/;
981  
982 $p =~ s/\((EC|COG).*?\)//;
983 $p =~ s/\s*\w+\d{4,}//; # remove possible locus tags
984 $p =~ s/ and (inactivated|related) \w+//;
985  
986 $p =~ s/^(possible|probable|predicted|uncharacteri.ed)/putative/i;
987 if ( $p =~ m/(domain|family|binding|fold|like)\s*$/i and $p !~ m/,/ ) {
988 $p .= " protein";
989 }
990 return $p;
991 }
992  
993 sub tag {
994 my ( $self, $f, $tag ) = @_;
995 return unless $f->has_tag($tag);
996 return ( $f->get_tag_values($tag) )[0];
997 }
998  
999 sub require_exe {
1000 my ( $self, $bin ) = @_;
1001 for my $dir ( File::Spec->path ) {
1002 my $exe = File::Spec->catfile( $dir, $bin );
1003 return $exe if -x $exe;
1004 }
1005 return;
1006 }
1007  
1008 sub msg {
1009 my ( $self, @message ) = @_;
1010 my $t = localtime;
1011 my $line = "[" . $t->hms . "] @message\n";
1012 print LOG $line if openhandle( \*LOG );
1013 print STDERR $line unless $self->quiet;
1014 }
1015  
1016 sub err {
1017 my ( $self, @message ) = @_;
1018 $self->quiet(0);
1019 $self->msg(@message);
1020 exit(2);
1021 }
1022  
1023 sub runcmd {
1024 my ( $self, @command_to_run ) = @_;
1025 $self->msg( "Running:", @command_to_run );
1026 system(@command_to_run) == 0 or $self->err( "Could not run command:", @command_to_run );
1027 }
1028  
1029 sub delfile {
1030 my ( $self, @files_to_delete ) = @_;
1031 for my $file (@files_to_delete) {
1032 $self->msg( "Deleting temporary file:", $file );
1033 unlink $file;
1034 }
1035 }
1036  
1037 sub create_cds_sequences_in_file {
1038 my ( $self, $outdir, $count, $feature ) = @_;
1039 open my $fout, '>', "$outdir/$count.seq";
1040 print $fout ">$count\n", $feature->seq->translate->seq, "\n";
1041 close $fout;
1042 }
1043  
1044 no Moose;
1045 __PACKAGE__->meta->make_immutable;
1046  
1047 1;
1048  
1049 __END__
1050  
1051 =pod
1052  
1053 =encoding UTF-8
1054  
1055 =head1 NAME
1056  
1057 Bio::AutomatedAnnotation::Prokka - Prokka class for bacterial annotation
1058  
1059 =head1 VERSION
1060  
1061 version 1.182680
1062  
1063 =head1 SYNOPSIS
1064  
1065 Modified prokka from a command line script to a Moose class - Bacterial annotation done fast and NCBI compliant (mostly).
1066 http://www.vicbioinformatics.com/software.prokka.shtml
1067
1068 If you use Prokka in your work, please cite:
1069  
1070 Seemann T (2012)
1071 Prokka: Prokaryotic Genome Annotation System
1072 http://vicbioinformatics.com/
1073  
1074 =head1 AUTHOR
1075  
1076 Andrew J. Page <ap13@sanger.ac.uk>
1077  
1078 =head1 COPYRIGHT AND LICENSE
1079  
1080 This software is Copyright (c) 2013 by Wellcome Trust Sanger Institute.
1081  
1082 This is free software, licensed under:
1083  
1084 The GNU General Public License, Version 3, June 2007
1085  
1086 =cut