ProtoGene.pl 62 KB
Newer Older
Sebastien Moretti's avatar
Sebastien Moretti committed
1
2
3
4
5
6
7
8
9
10
11
12
#!/usr/bin/env perl

########################################################
#                                                      #
# ProtoGene : Bona-Fide Back Translation of Protein    #
#             Multiple Sequence Alignments             #
#                                                      #
########################################################

use strict;
use warnings;
use diagnostics;
Sebastien Moretti's avatar
Sebastien Moretti committed
13
14
use Carp;

Sebastien Moretti's avatar
Sebastien Moretti committed
15
use File::Which qw(which);                 # Locate external executable programs in the PATH
16
17
18
use Time::localtime;                       # Use localtime+PID for a pseudo-uniq temp file name
use Getopt::Long;                          # Options specifications

Sebastien Moretti's avatar
Sebastien Moretti committed
19

Sebastien Moretti's avatar
Sebastien Moretti committed
20
use File::Copy qw(move);                   # Avoid external 'mv' command usage
21
use LWP::Simple;                           # To test gigablaster availability
Sebastien Moretti's avatar
Sebastien Moretti committed
22
23
24

use Mail::Send;                            # Send warnings and errors files by e-mail ==> only if the $userEMail variable is defined

25
26
use lib '/mnt/common/share/ProtoGene/';    # Local path for ProtoGene's own perl modules
###use lib '/mnt/local/lib/tcoffee_perl/';
Sebastien Moretti's avatar
Sebastien Moretti committed
27
use Exonerate;                             # Exonerate runner, parser, ...
28
use Views;                                 # Non-text outputs, e.g. HTML/CSS
29
#use CheckOutput;                         # Check output for cds consistancy with query
Sebastien Moretti's avatar
Sebastien Moretti committed
30
31
32



33
################## CONFIGURATION ##################
Sebastien Moretti's avatar
Sebastien Moretti committed
34
$ENV{'PATH'}        .= ':/mnt/local/bin/:./';                               # Additional path for executables
35
36

my $cachePath        = '/scratch/cluster/monthly/t_coffee/ProtoGene_Cache'; # Cache directory
37
$cachePath = '/Users/smoretti/Documents/ProtoGene/TTMMPP'; #FIXME
38
39
40
41
my $cacheStorageTime = 15;                                                  # Do not update sequences younger than X days

my $userEMail        = 'moretti.sebastien@gmail.com';                       # To receive e-mails with encountered problems; leave blank to inactive
###################################################
Sebastien Moretti's avatar
Sebastien Moretti committed
42
43


44
my $VERSION  = '4.0.0';
Sebastien Moretti's avatar
Sebastien Moretti committed
45

Sebastien Moretti's avatar
Sebastien Moretti committed
46
my $webblast_exe  = 'webblast.pl';
47
my $blast_exe     = 'blastall';            # Or wu-blastall for Wu-BLAST; for local blast usage
Sebastien Moretti's avatar
Sebastien Moretti committed
48
my $exonerate_exe = 'exonerate-1.0';       # Exonerate 1.0 because current parser only works with this version
49
50
51
52
53
54


################## Option management
my ($msa, $revtrans, $pep, $hideBOJ, $run_name, $template, $lim, $cache) = ('', 0, 0, 0, '', '', 0, 'update');
my ($debug, $tmp)                                                        = (0, 0);
my ($db, $species, $local, $giga)                                        = ('refseq_protein', 'All_organisms', 0, 0);
Sebastien Moretti's avatar
Sebastien Moretti committed
55
56
57
58
59
60
61
62
63
64
65
my %opts = ('msa|in=s'        => \$msa,        # Input sequences
            'revtrans'        => \$revtrans,   # Use to reverse-translate sequences with no match
            'pep'             => \$pep,        # Add the original peptide query beneath the related CDS seq
            'hideBOJ'         => \$hideBOJ,    # Hide BOJ output
            'run_name=s'      => \$run_name,   # Use another name, instead of input seq name, for result files
            'template=s'      => \$template,   # Use a template file
            'lim=i'           => \$lim,        # Limit number of input query sequences
            'cache=s'         => \$cache,      # Cache behavior

            'orgm|species=s'  => \$species,    # Organism(s) to blast against
            'db|database=s'   => \$db,         # Database to blast against
66
            'local'           => \$local,      # Use to specify a local db query, defined in $local_db
Sebastien Moretti's avatar
Sebastien Moretti committed
67
68
69
70
71
72
73
74
75
76
            'giga'            => \$giga,       # Use GigaBlaster server

            'version|V'       => sub { print "\n\tPROTOGENE : Bona-Fide Back Translation of Protein Multiple Sequence Alignments\n\tversion   : $VERSION\n\n";
                                       exit 0;
                                 },            # Print version information
            'help|H|?'        => sub { system('perldoc', "$0")==0 || print {*STDERR} "\n\tCannot open the documentation with 'perldoc'\n\n";
                                       exit 0;
                                     },        # Print full help message
            'debug'           => \$debug,      # Verbose output
            'tmp'             => \$tmp,        # To keep traces of fake intermediate files like fake xml from NCBI, fake aln, ...
Sebastien Moretti's avatar
Sebastien Moretti committed
77
           );
Sebastien Moretti's avatar
Sebastien Moretti committed
78
79
my $test_option_values = Getopt::Long::GetOptions(%opts);

80
81

################## Short help message
82
83
if ( !$test_option_values || ($msa eq '' && $cache ne 'empty' && $cache ne 'old') ){
#|| $species eq '' || $db eq '' ){
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
    print {*STDERR} "\n\tCannot open the MSA file in FASTA format
\tTry:  $0 --msa=path_of_the_fasta_msa_file [Options]

\tOptions: --orgm=All_organisms, Bacteria, Viruses, Vertebrata,
\t                Eukaryota, Mammalia, Primates, Homo_sapiens,
\t                Gallus_gallus, Bos_taurus, Escherichia_coli,
\t                Arabidopsis_thaliana, Mus_musculus,
\t                Drosophila_Melanogaster, ...
\t                default is 'All_organisms'
\t         --db=nr, pdb, swissprot, refseq_protein
\t                default is 'refseq_protein'
\t         --local to execute a local BLAST query with
\t                --db=path_for_a_local_db_blast_formated\n
\t         --template to provide your own nucleotidic sequences
\t                following the cds file format
\t         --revtrans to reverse-translate sequences with no
\t                blast hit, in IUB (IUPAC) depiction code
\t                They are removed from the alignement by default
\t         --pep  to add the original peptide query beneath the
\t                back-translated sequence
\t         --cache=none, update, use, 'own_PATH_directory', old, empty
\t                to select the cache mode
\t                default is 'update'\n
\t         --version to print version information
\t         --help    to print a full help message\n\n";
109
    exit(1);
Sebastien Moretti's avatar
Sebastien Moretti committed
110
}
111
112


113
114
################## Check cache directory accessibility
checkCacheAccessibility($cachePath);
115

116
117
# Cache management
$cache = cacheManagement($cache, $cachePath, 0) || '.';
118

119
120
# Remove old files from the cache directory everytime ProtoGene is running
cacheManagement('old', $cachePath, 1);
121
122


123
124

################## Check external software in the PATH
Sebastien Moretti's avatar
Sebastien Moretti committed
125
126
#TODO: remove that for production
#checkExternalSoftware($webblast_exe, $exonerate_exe);
127
128
if ( $local ){
    checkExternalSoftware($blast_exe);
Sebastien Moretti's avatar
Sebastien Moretti committed
129
130
131
132
}



133
134
135
################## Check input files
# Open and check template file
my ($template_NT, $template_AA, $template_SEQ);
136
#TODO: template is fasta only now
137
138
($template_NT, $template_AA, $template_SEQ) = checkTemplate($template) if ( $template );

Sebastien Moretti's avatar
Sebastien Moretti committed
139

Sebastien Moretti's avatar
Sebastien Moretti committed
140
141
142
143
144
# Open and Check the input fasta file
my $originalMSA    = $msa;
my $converted      = 0; # Accept only fasta format
#TODO: Do a better file converter and identifier is msa is not fasta
#($msa, $converted) = isFastaFile($msa, $converted);
Sebastien Moretti's avatar
Sebastien Moretti committed
145

146
my $fasta_checker = -1;
147
my (@original_names, @original_seq); #Use 2 lists in parallel : original_names, seq
Sebastien Moretti's avatar
Sebastien Moretti committed
148
149
open( my $MSA, '<', "$msa" ) or die "\n\tCannot open your MSA file\n\n";
READ_MSA:
150
while(<$MSA>){
Sebastien Moretti's avatar
Sebastien Moretti committed
151
152
    next READ_MSA if ( $_ =~ /^#/ );

153
    if ( $_ =~ /^>/ ){
154
155
        $fasta_checker++;
        my $name = $_;
Sebastien Moretti's avatar
Sebastien Moretti committed
156
157
158
        $name    =~ s{\r\n}{}g; #Remove return lines from windows OS '^M'
        $name    =~ s{\r}{\n}g;
        $name    =~ s{^>[ \t]+}{>};
159
        chomp($name);
Sebastien Moretti's avatar
Sebastien Moretti committed
160
161

        push @original_names, $name;
Sebastien Moretti's avatar
Sebastien Moretti committed
162
    }
Sebastien Moretti's avatar
Sebastien Moretti committed
163
164
165
166
167
168
169
170
171
172
    elsif ( $_ =~ /[A-Z\-\.]/i ){
        my $sequence = $_;
        $sequence    =~ s{\r\n}{}g;
        $sequence    =~ s{\r}{\n}g;
        $sequence    =~ s{\.}{-}g; #for msa with '.' as gap
        #TODO because exonerate cannot work with selenocystein
        $sequence    =~ s{[BJOUZ]}{X}ig; #U here for selenocystein
        $sequence    =~ s{[^A-Za-z\-\*\n]}{}g; #Remove all the non-gap or non-alphabetic characters from the seq
        chomp($sequence);

Sebastien Moretti's avatar
Sebastien Moretti committed
173
        #fasta sequence on 1 line
174
        if ( !exists($original_seq[$fasta_checker]) ){
Sebastien Moretti's avatar
Sebastien Moretti committed
175
            push @original_seq, $sequence;
176
177
        }
        else {
Sebastien Moretti's avatar
Sebastien Moretti committed
178
            $original_seq[$fasta_checker] .= $sequence;
179
        }
Sebastien Moretti's avatar
Sebastien Moretti committed
180
181
    }
}
182
close $MSA;
Sebastien Moretti's avatar
Sebastien Moretti committed
183
184

#Are there FASTA sequences ?
185
if ( $fasta_checker == -1 ){
Sebastien Moretti's avatar
Sebastien Moretti committed
186
    failure();
Sebastien Moretti's avatar
Sebastien Moretti committed
187
188
    print {*STDERR} "\tThe MSA file does NOT seem to be a protein FASTA format
\tSee an example of FASTA format <a href='http://en.wikipedia.org/wiki/FASTA_format' target='_blank'>here</a>\n\n";
189
    exit(1);
Sebastien Moretti's avatar
Sebastien Moretti committed
190
}
191
elsif ( $lim >0 && $fasta_checker > $lim ){
Sebastien Moretti's avatar
Sebastien Moretti committed
192
    failure();
193
    print {*STDERR} "\tThe FASTA file is too large, try with less than $lim sequences\n\tor split your file\n\n";
194
195
    exit(1);
}
196
elsif ( exists( $original_seq[0] ) && $original_seq[0] =~ /[acgtu]/i ){
197
    my $first_seq = $original_seq[0];
Sebastien Moretti's avatar
Sebastien Moretti committed
198
199
200
201
202
203
    #Check if sequences are amino acids and not nucleotides ONLY on the 1st sequence
    my $a         = ($first_seq =~ s{[aA]}{}g)               || 0;
    my $c         = ($first_seq =~ s{[cC]}{}g)               || 0;
    my $g         = ($first_seq =~ s{[gG]}{}g)               || 0;
    my $t         = ($first_seq =~ s{[tTuU]}{}g)             || 0;
    my $non       = ($first_seq =~ s{[^aAcCgGtTuUXxNn-]}{}g) || 0;
204
    if ( ($a+$c+$g+$t) >= (($a+$c+$g+$t+$non)*80/100) ){
Sebastien Moretti's avatar
Sebastien Moretti committed
205
        failure();
Sebastien Moretti's avatar
Sebastien Moretti committed
206
207
        print {*STDERR} "\tYour sequences seem already to be nucleotides
\tthe goal of this program is to turn AMINO ACID alignments into CDS nucleotide alignments\n\n";
208
209
        exit(1);
    }
Sebastien Moretti's avatar
Sebastien Moretti committed
210
211
212
213
}
undef $fasta_checker;


Sebastien Moretti's avatar
Sebastien Moretti committed
214
# Check GigaBlaster status if used
215
if ( $giga==1 ){
216
217
    $local = 0;
    $local = 2 if ( head('http://www.igs.cnrs-mrs.fr/Giga2/~database/remoteblast.cgi') );
218
219
}

Sebastien Moretti's avatar
Sebastien Moretti committed
220

Sebastien Moretti's avatar
Sebastien Moretti committed
221
# Temporary file extension
222
my $date = sprintf("%d-%02d-%02d_%02dh%02d", localtime->year() + 1900, localtime->mon(), localtime->mday(), localtime->hour, localtime->min);
Sebastien Moretti's avatar
Sebastien Moretti committed
223
224


225

Sebastien Moretti's avatar
Sebastien Moretti committed
226
#Start main program with version # of programs and list original queries
227
print "\n\t   Protogene\t$VERSION\t$date\n\n";
228

229
open(my $EXONERATEISHERE, "$exonerate_exe --version |");
230
my $IsExonerateHere = <$EXONERATEISHERE>;
231
close $EXONERATEISHERE;
Sebastien Moretti's avatar
Sebastien Moretti committed
232
233
print "\t   $IsExonerateHere\n";
undef $IsExonerateHere;
234
undef $VERSION;
235

Sebastien Moretti's avatar
Sebastien Moretti committed
236
for(my $m=0; $m<=$#original_names; $m++){
237
    printf("\t>$m is %s\n", $m, $original_names[$m]);
Sebastien Moretti's avatar
Sebastien Moretti committed
238
}
Sebastien Moretti's avatar
Sebastien Moretti committed
239
$date .= "_$$"; #Add PID to be more uniq
Sebastien Moretti's avatar
Sebastien Moretti committed
240
241
242
243



# run_name implementation for web server
244
$originalMSA = $run_name if ( $run_name ne '' );
Sebastien Moretti's avatar
Sebastien Moretti committed
245

246
247
unlink("$originalMSA.cds", "$originalMSA.cdsP", "$originalMSA.cdsP.html",
       "$originalMSA.out", "$originalMSA.boj",  "$originalMSA.log");
Sebastien Moretti's avatar
Sebastien Moretti committed
248
249


250
# Build the sequences, from the alignment, to perform blast search
251
252
my $quiet = '';
EACH_SEQ:
253
254
255
256
257
258
259
260
for(my $r=0; $r<=$#original_names; $r++){
    my $fasta_header = $original_names[$r];
    my $short_name   = $original_names[$r];
    $fasta_header    =~ s{^>}{};               # Full FASTA header
    $short_name      =~ s{^([^\s\t]+).*$}{$1}; # Short name without description

    # Prepare sequence $r for BLAST
    open(my $READY2BLAST, '>', "$cache/$date.seq2blast.fas.$r");
261
    my $noGap = $original_seq[$r];
262
263
    $noGap    =~ s{\-}{}g; #remove gaps
    print {$READY2BLAST} ">$r\n$noGap\n";
264
    close $READY2BLAST;
Sebastien Moretti's avatar
Sebastien Moretti committed
265
266
267
    undef $noGap;


Sebastien Moretti's avatar
Sebastien Moretti committed
268
    my @equivalent_blast_hits; #Multiple BLAST hits with the same highest e-value/score
269
270

    if ( exists($template_NT->{$short_name}) && $template_NT->{$short_name} ne '' ){
Sebastien Moretti's avatar
Sebastien Moretti committed
271
272
273
        # First try nucleotide template
        push @equivalent_blast_hits, 'My_own_seq';
        print "\n\n$r done\n\nNucleotide template for $r:\t$template_NT->{$short_name}\n\n*******************************************************************\n\n";
Sebastien Moretti's avatar
Sebastien Moretti committed
274
    }
275
    elsif ( exists($template_AA->{$short_name}) && $template_AA->{$short_name} ne '' ){
Sebastien Moretti's avatar
Sebastien Moretti committed
276
277
278
        # Second try amino acid/BLASTp template
        push @equivalent_blast_hits, $template_AA->{$short_name};
        print "\n\n$r done\n\nBlastP template for $r:\t$template_AA->{$short_name}\n\n*******************************************************************\n\n";
Sebastien Moretti's avatar
Sebastien Moretti committed
279
280
    }
    else{
Sebastien Moretti's avatar
Sebastien Moretti committed
281
    ## else send them to webblast
282
        $quiet = '-quiet=on ' if ( $r>0 ); #Show webblast parameters only for the first webblast run
283
        launchWebblast("$cache/$date.seq2blast.fas.$r", $quiet, $local, $db, $species, $blast_exe, "$cache/$date.blastp${r}");
Sebastien Moretti's avatar
Sebastien Moretti committed
284

285
    ##Get the BLASTp hit(s)  acc number
286
        open(my $BLASTP, '<', "$cache/$date.blastp${r}");
287
        while(<$BLASTP>){
Sebastien Moretti's avatar
Sebastien Moretti committed
288
            @equivalent_blast_hits = (@equivalent_blast_hits, $1) if ( $_ =~ /^>\s*\d+@?\w?\w?\w?__([^\s\|\.]+).*$/ ); #Warning: double '_'
289
290
        }
        close $BLASTP;
Sebastien Moretti's avatar
Sebastien Moretti committed
291
292
        unlink("$cache/$date.blastp${r}", "$cache/$date.seq2blast.fas.$r") if ( $tmp == 0 || exists($equivalent_blast_hits[0]) );
        if ( !exists($equivalent_blast_hits[0]) ){
293
            print "\n$r ...\tNo blast result found above filter thresholds for $fasta_header\n\n";
Sebastien Moretti's avatar
Sebastien Moretti committed
294
            buildFailureOutputFiles($r, 'No_BLASTp_Result', 'Unavailable', '');
295
296
297
298
            undef $original_seq[$r];
            undef $original_names[$r];
            next EACH_SEQ;
        }
Sebastien Moretti's avatar
Sebastien Moretti committed
299
300
301
302
303
    }



    #When multiple equal blast hits  ==> use, and add, every hits
304
305
306
    my ($resultPOS, $resultBOJ) = ('', '');
    my @failureStatus = ('');
    my @intronStatus  = ('');
Sebastien Moretti's avatar
Sebastien Moretti committed
307
308
    for(my $qq=0; $qq<=$#equivalent_blast_hits; $qq++){
        print "\n$fasta_header  -->  [$equivalent_blast_hits[$qq]]\n";
309
310
311
312


        my @nt_GIs;
        my $intronStep = 0;
313
314
315
        if ( exists($template_NT->{$short_name}) && $template_NT->{$short_name} ne '' && $template_NT->{$short_name} !~ /^My_Seq$/i ){
            downloadSeq($cache, $date, '', '', $template_NT->{$short_name});
            @nt_GIs = $template_NT->{$short_name};
316
        }
317
        elsif ( exists($template_NT->{$short_name}) && $template_NT->{$short_name} ne '' && $template_NT->{$short_name} =~ /^My_Seq$/i ){
318
            open(my $MYSEQ, '>', "$cache/My_Seq-$$.fas");
319
            print {$MYSEQ} ">My_Seq-$$ for $short_name\n".$template_SEQ->{$short_name}."\n";
320
321
322
323
324
            close $MYSEQ;
            @nt_GIs = "My_Seq-$$";
        }
        else{
        #Prot ACC -> PUID
Sebastien Moretti's avatar
Sebastien Moretti committed
325
            my $protGI = blastPAcc2PGI($equivalent_blast_hits[$qq]);
326
            if ( $protGI eq '' ){
Sebastien Moretti's avatar
Sebastien Moretti committed
327
328
                print "\tNo protein (prot GI) link found for $equivalent_blast_hits[$qq] in $fasta_header\n\n";
                @failureStatus = ('PUI_unavailable', $equivalent_blast_hits[$qq]);
329
330
                next;
            }
Sebastien Moretti's avatar
Sebastien Moretti committed
331
332
#           print "\t$protGI\n";

333
        #PUID -> nt GIs & GeneID
Sebastien Moretti's avatar
Sebastien Moretti committed
334
            my ($ntGIs, $geneID) = protGI2NTGIs($protGI, $equivalent_blast_hits[$qq]);
335
            if ( $ntGIs eq '' && $geneID eq '' ){
Sebastien Moretti's avatar
Sebastien Moretti committed
336
337
                print "\tNo nucleotide (nt GIs) link found for $equivalent_blast_hits[$qq] in $fasta_header\n\n";
                @failureStatus = ('No_nt_link', $equivalent_blast_hits[$qq]);
338
339
340
341
342
343
344
                next;
            }
            print " linked with [$ntGIs $geneID]\n";


        #Get transcript and contig seq
            @nt_GIs = split(/,/, $ntGIs);
Sebastien Moretti's avatar
Sebastien Moretti committed
345
            downloadSeqFromGIs($cache, $date, '', '', @nt_GIs);
346
347
348
349
        #GeneID -> Chr
            my @geneIDs = split(/,/, $geneID);
            while(<@geneIDs>){
                my $geneID = $_;
Sebastien Moretti's avatar
Sebastien Moretti committed
350
351
                my ($chr, $amont, $aval) = geneID2Chr($geneID, $equivalent_blast_hits[$qq]);
                print "\n\tNo gene locus found for $equivalent_blast_hits[$qq] with $geneID in $fasta_header\n\n" if ($chr eq '' and $geneID ne '');
352
353
354

                if ( $chr ne '' ){
            #Get Chr seq
Sebastien Moretti's avatar
Sebastien Moretti committed
355
                    downloadSeq($cache, $date, $amont, $aval, $chr);
356
357
358
359
360
361
362
363
364
                    $intronStep = 1;

                    @nt_GIs = ("$chr:$amont-$aval", @nt_GIs);
                }
            }
        }


    #Align Nt seq with our protein query seq
Sebastien Moretti's avatar
Sebastien Moretti committed
365
        my ($POS, $BOJ) = runExonerate($exonerate_exe, $cache, $date, $r, $original_seq[$r], $fasta_header, $equivalent_blast_hits[$qq], $r, @nt_GIs);
366

Sebastien Moretti's avatar
Sebastien Moretti committed
367
        my ($POSresult, $bestNucleotide) = prepareResults4CDS($POS, $equivalent_blast_hits[$qq], $original_seq[$r], $fasta_header);
368
369
        $resultPOS .= $POSresult if ( $bestNucleotide ne '' && $POSresult ne '' && $resultPOS !~ /_G_$bestNucleotide/ );

Sebastien Moretti's avatar
Sebastien Moretti committed
370
371
        @intronStatus = ($POS->{0}, ${equivalent_blast_hits[$qq]}, '')              if ( $intronStep==1 && exists($POS->{0}) && $POS->{0} ne '' && $POS->{0} =~ /\:/ );
        @intronStatus = ($POS->{0}, ${equivalent_blast_hits[$qq]}, $bestNucleotide) if ( $intronStep==0 && ($bestNucleotide =~ /^N[CTWZG]_/ || $bestNucleotide =~ /^AC_/) );
372
373
374
375

        my ($intronLess, $nameLess) = ('', '');
        $intronLess = $POS->{0}       if ( %$BOJ eq 0 && exists($POS->{0}) && $POS->{0} ne '' );
        $nameLess   = $bestNucleotide if ( %$BOJ eq 0 && $intronStep==0 && ($bestNucleotide =~ /^N[CTWZG]_/ || $bestNucleotide =~ /^AC_/) );
Sebastien Moretti's avatar
Sebastien Moretti committed
376
        my ($BOJresult, $bestGenomic) = prepareResults4BOJ($BOJ, $equivalent_blast_hits[$qq], $original_seq[$r], $fasta_header, $intronLess, $nameLess);
377
        $resultBOJ .= $BOJresult      if ( $bestGenomic ne '' && $BOJresult ne '' && $resultBOJ !~ /_G_$bestGenomic[ \-]/ );
378
#    print " $intronStep $POS->{0} [@intronStatus] {$BOJresult} $bestNucleotide - $bestGenomic \t $BOJ->{0}\n";
Sebastien Moretti's avatar
Sebastien Moretti committed
379
380
381
    }


382
    if ( $resultPOS eq '' ){
Sebastien Moretti's avatar
Sebastien Moretti committed
383
        buildFailureOutputFiles($r, $failureStatus[1], $failureStatus[0], '')     if ( $failureStatus[0] ne '' );
Sebastien Moretti's avatar
Sebastien Moretti committed
384
        buildFailureOutputFiles($r, $equivalent_blast_hits[0], 'Failed_Aln', '') if ( $failureStatus[0] eq '' );
385
        next;
Sebastien Moretti's avatar
Sebastien Moretti committed
386
    }
387
388
    elsif ( $resultBOJ eq '' ){
        if ( $failureStatus[0] eq 'PUI_unavailable' || $failureStatus[0] eq 'No_nt_link' ){
389
            buildFailureBOJOutputFile($failureStatus[1], $failureStatus[0], $fasta_header, $original_seq[$r]);
390
391
        }
        elsif ( $failureStatus[0] eq '' && $intronStatus[0] ne '' ){
392
            buildIntronlessBOJOutputFile($intronStatus[1], $intronStatus[0], $intronStatus[2], $fasta_header, $original_seq[$r]);
393
394
        }
        else{
Sebastien Moretti's avatar
Sebastien Moretti committed
395
            buildFailureBOJOutputFile($equivalent_blast_hits[0], 'Unavailable', $fasta_header, $original_seq[$r]);
396
        }
397
        createCDSOutputFile($resultPOS, $original_seq[$r], $fasta_header);
Sebastien Moretti's avatar
Sebastien Moretti committed
398
399
    }
    else {
400
        createCDSOutputFile($resultPOS, $original_seq[$r], $fasta_header);
Sebastien Moretti's avatar
Sebastien Moretti committed
401
        createBOJOutputFile($resultBOJ, ${original_seq[$r]});
Sebastien Moretti's avatar
Sebastien Moretti committed
402
403
404
405
406
407
408
409
    }


    undef $original_seq[$r];
    undef $original_names[$r];
}


Sebastien Moretti's avatar
Sebastien Moretti committed
410
411
checkAndCleanStderrFiles("$cache/${date}_ExonerateError") if ( -e "$cache/${date}_ExonerateError" );
checkOutputFiles();
Sebastien Moretti's avatar
Sebastien Moretti committed
412
unlink("$msa") if ( $converted==1 );
413
my @tmpFiles = glob($cache."/${date}*");
Sebastien Moretti's avatar
Sebastien Moretti committed
414
415
if ( exists($tmpFiles[0]) ){
    mkdir("$cache/${date}_TMP");
416
    move("$_", "$cache/${date}_TMP") while(<@tmpFiles>);
Sebastien Moretti's avatar
Sebastien Moretti committed
417
418
419
420
421
422
423
}


#Ouput Checker


#STDOUT Log output for our server
424
if ( -s "${originalMSA}.cds" || -s "${originalMSA}.out"){
Sebastien Moretti's avatar
Sebastien Moretti committed
425
426
    print "\n\nTERMINATION STATUS: SUCCESS\n";
    print "OUTPUT RESULTS\n";
Sebastien Moretti's avatar
Sebastien Moretti committed
427
428
429
430
431
    print "    #### File Type=        MSA Format= fasta_CDS Name= ${originalMSA}.cds\n" 
        if ( -s "${originalMSA}.cds");
    print "    #### File Type=        MSA Format= fasta_CDS+Query Name= ${originalMSA}.cdsP\n" 
        if ( -s "${originalMSA}.cdsP");
    print "    #### File Type=        MSA Format= colored_fasta_CDS Name= ${originalMSA}.cdsP.html\n" 
Sebastien Moretti's avatar
Sebastien Moretti committed
432
        if ( Views::Html("${originalMSA}.cdsP") && -s "${originalMSA}.cdsP.html");
Sebastien Moretti's avatar
Sebastien Moretti committed
433
434
435
436
    print "    #### File Type=        MSA Format= Rejected_seq Name= ${originalMSA}.out\n" 
        if ( -s "${originalMSA}.out");
    print "    #### File Type=        MSA Format= fasta_Exon-Boundaries Name= ${originalMSA}.boj\n" 
        if ( -s "${originalMSA}.boj" && -s "${originalMSA}.cds" && $hideBOJ==0);
Sebastien Moretti's avatar
Sebastien Moretti committed
437
438
}
else{
Sebastien Moretti's avatar
Sebastien Moretti committed
439
    failure();
440
    exit(1);
Sebastien Moretti's avatar
Sebastien Moretti committed
441
442
}

443
exit(0);
Sebastien Moretti's avatar
Sebastien Moretti committed
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


=head1 NAME

ProtoGene.pl - Converts a peptidic alignment to a nucleotidic alignment through database search

=head1 SYNOPSIS

B<ProtoGene.pl> --msa=path_of_the_fasta_msa_file [options]

with these options available:

=over 4

=item I<--orgm>=targeted species in the database search

=item All_organisms [default], Bacteria, Viruses, Vertebrata, Eukaryota, Mammalia, Primates, Homo_sapiens, Gallus_gallus, Bos_taurus, Escherichia_coli, Arabidopsis_thaliana, Mus_musculus, Drosophila_Melanogaster, ...

=item I<--db>=targeted database in the database search

=item nr, pdb, swissprot, refseq_protein [default]

=item I<--local> to execute a local BLAST query with  --db=path_for_a_local_db_blast_formated

=item I<--template> to provide your own nucleotidic sequences following the cds file format

=item I<--revtrans> to reverse-translate sequences with no blast hit, in IUB (IUPAC) depiction code

=item They are removed from the alignement by default

=item I<--pep> to add the original peptide query beneath the back-translated sequence

=item I<--cache>=none, update, use, own_path_directory, old, empty

=item none: no cache usage, none temporary files are stored

=item update: use cache but update old files [default]

=item use: force use cache, whatever the age of files

=item own_path_directory: use my own directory, and its files

=item old: remove the old files in the cache directory

488
=item empty: empty completely the cache directory
Sebastien Moretti's avatar
Sebastien Moretti committed
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

=item I<--version> to print version information

=item I<--help> to print this help message

=back

=head1 DESCRIPTION

PROTOGENE : Bona-Fide Back Translation of Protein Multiple Sequence Alignments
It converts a peptidic alignment to a nucleotidic alignment through database search.
Blast queries allow to get nucleotidic sequences from where peptidic sequences come from.
Exonerate aligns nucleotidic and peptidic sequences together.
PROTOGENE re-builds the original alignment with nucleotidic information it has gotten.

=head1 REQUIREMENT

=over 4

=item B<Perl 5.6 or better> is required !

=item Standard Perl modules B<lib>, B<strict>,  B<warnings>,  B<diagnostics>, B<Env> are required

=item and some other current ones : B<Getopt::Long>,  B<File::Which>,  B<File::Copy>, B<Mail::Send>

=item -

=item I<exonerate> from http://www.ebi.ac.uk/~guy/exonerate/

=item I<blast> from http://www.ncbi.nlm.nih.gov/BLAST/download.shtml or http://blast.wustl.edu/

=back

=head1 VERSION

=over 8

526
=item version 4.0.0
Sebastien Moretti's avatar
Sebastien Moretti committed
527

528
=item on Apr 02nd, 2011
Sebastien Moretti's avatar
Sebastien Moretti committed
529
530
531
532
533
534
535
536
537

=back

=head1 AUTHORS

=over 8

=item Sebastien MORETTI

Sebastien Moretti's avatar
Sebastien Moretti committed
538
=item moretti.sebastien [AT] gmail.com
Sebastien Moretti's avatar
Sebastien Moretti committed
539

540
=item Vital-IT computing center
Sebastien Moretti's avatar
Sebastien Moretti committed
541

542
=item Swiss Institute of Bioinformatics
Sebastien Moretti's avatar
Sebastien Moretti committed
543

544
=item Lausanne, Switzerland
Sebastien Moretti's avatar
Sebastien Moretti committed
545

546
=item http://www.vital-it.ch/
Sebastien Moretti's avatar
Sebastien Moretti committed
547
548
549
550
551
552
553
554

=back

=cut


######################  Management  ######################

555
# Failure declaration
Sebastien Moretti's avatar
Sebastien Moretti committed
556
sub failure {
557
558
559
    print {*STDERR} "\n\nFATAL\n\nTERMINATION STATUS: FAILURE\n\n";
    return;
}
Sebastien Moretti's avatar
Sebastien Moretti committed
560

Sebastien Moretti's avatar
Sebastien Moretti committed
561
# Check external programs presence in the PATH
562
sub checkExternalSoftware {
Sebastien Moretti's avatar
Sebastien Moretti committed
563
564
565
566
567
568
    for my $exe ( @_ ){
        if ( ! which($exe) ){
            failure();
            print {*STDERR} "\t'$exe' program is not reachable\n\tIt could not be in your PATH or not installed\n\n";
            exit(1);
        }
Sebastien Moretti's avatar
Sebastien Moretti committed
569
    }
Sebastien Moretti's avatar
Sebastien Moretti committed
570
    return;
Sebastien Moretti's avatar
Sebastien Moretti committed
571
572
}

573
574
# Check cache directory accessibility: Test and change rights, if required, of the cache directory
sub checkCacheAccessibility {
575
    my ($cacheDir) = @_;
Sebastien Moretti's avatar
Sebastien Moretti committed
576

577
    if ( -d "$cacheDir/" && -w "$cacheDir/" && -x "$cacheDir/" && -r "$cacheDir/" ){
578
        # Good
Sebastien Moretti's avatar
Sebastien Moretti committed
579
    }
580
581
582
    elsif ( -d "$cacheDir/" ){
        if ( -o "$cacheDir/" ){
            chmod 0754, "$cacheDir/";
583
        }
584
        else{
585
586
587
            failure();
            print {*STDERR} "\tPermissions do NOT seem to be valid for the '$cacheDir' cache directory\n\n";
            exit(2);
588
        }
Sebastien Moretti's avatar
Sebastien Moretti committed
589
590
    }
    else{
591
        mkdir "$cacheDir/"; # FIXME: mkdir is not recursive !
592
        if ( -o "$cacheDir/" ){
593
            chmod 0754, "$cacheDir/"; #0754 is in octal, so 754 or '0754' are not good !
594
595
        }
        else{
596
597
598
            failure();
            print {*STDERR} "\tPermissions do NOT seem to be valid for the '$cacheDir' cache directory\n\n";
            exit(2);
599
        }
Sebastien Moretti's avatar
Sebastien Moretti committed
600
    }
601

602
    return;
Sebastien Moretti's avatar
Sebastien Moretti committed
603
604
}

605
# Cache Behavior Management
Sebastien Moretti's avatar
Sebastien Moretti committed
606
sub cacheManagement{
607
    my ($cache, $cacheDir, $inScript) = @_;
608

609
    if ( $cache eq 'empty' ){
610
611
        unlink <$cacheDir/*.fas>;
        unlink <$cacheDir/*_ExonerateError>;
612
613
        unlink("$cacheDir/webblast.log", "$cacheDir/web_tempo.result", "$cacheDir/debug.tempo");
        print "\n\tcache directory [$cacheDir] is empty\n\n";
614
        exit 0;
Sebastien Moretti's avatar
Sebastien Moretti committed
615
    }
616
    elsif ( $cache eq 'old' ){
617
618
619
620
621
        unlink    grep { -M $_ > $cacheStorageTime }    glob($cacheDir.'/*.fas'); # Grep list only with $cacheStorageTime days old files

        if ( $inScript==0 ){
            print "\n\tcache directory [$cacheDir] is empty of its old files\n\n";
            exit 0;
622
        }
Sebastien Moretti's avatar
Sebastien Moretti committed
623
    }
624
    elsif ( $cache eq 'update' || $cache eq 'use' ){
625
626
        # DEFAULT: Limit cached files to less than $cacheStorageTime days old ones for 'update'
        $cache = $cacheDir;
Sebastien Moretti's avatar
Sebastien Moretti committed
627
    }
628
    elsif ( $cache eq 'none' ){
629
        # Do not use cache
Sebastien Moretti's avatar
Sebastien Moretti committed
630
    }
631
632
633
634
    elsif ( -d $cache ){
        die "\n\tProtoGene cannot access to your directory\n\n"  if ( ! -x $cache );
        die "\n\tProtoGene cannot write into your directory\n\n" if ( ! -w $cache );
        die "\n\tProtoGene cannot read into your directory\n\n"  if ( ! -r $cache );
Sebastien Moretti's avatar
Sebastien Moretti committed
635
636
    }
    else {
637
638
639
        failure();
        print {*STDERR} "\n\tWrong cache argument, or your cache folder '$cacheDir' doesn't seem to exist\n\n";
        exit(3);
Sebastien Moretti's avatar
Sebastien Moretti committed
640
641
642
643
644
645
646
647
648
649
    }

    return($cache);
}

##########################################################


######################    Fasta    ######################

Sebastien Moretti's avatar
Sebastien Moretti committed
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
# Check input aln format
sub isFastaFile{
    my ($msa, $converted) = @_;

    if ( -s "$msa" ){ # Check is the file exists and is not empty
        # Is FASTA format ?
        my $firstLine = `head $msa`;
        return($msa, 0) if ( $firstLine =~ /^>/ );

        # Convert no fasta format to fasta with readseq
        my $reformat = which('readseq') || '';
        if ( $reformat ne '' ){
            system("$reformat -a -f8 $msa > $msa.007")==0 or do {failure(); print {*STDERR} "\n\tEnable to convert your file to fasta format\n\n";};
            $msa      .= '.007';
            $converted = 1;
665
        }
Sebastien Moretti's avatar
Sebastien Moretti committed
666
667
    }
    else {
Sebastien Moretti's avatar
Sebastien Moretti committed
668
        failure();
669
670
        print {*STDERR} "\tThe file \'$msa\' doesn't not seem to be reachable\n\n";
        exit(1);
Sebastien Moretti's avatar
Sebastien Moretti committed
671
672
    }

Sebastien Moretti's avatar
Sebastien Moretti committed
673
    return($msa, $converted);
Sebastien Moretti's avatar
Sebastien Moretti committed
674
675
676
677
}

#Prepare Fasta Header of the query name to incorporate our annotations
sub fastaHeaders4ProtoGene{
678
    my ($QueryName) = @_;
Sebastien Moretti's avatar
Sebastien Moretti committed
679
680

    $QueryName =~ s/  +/ /g;
681
682
683
684
    my ($cqacc, $cqdesc) = ($QueryName, $QueryName);
    $cqacc  =~ s/^ *([^ ]*) .*$/$1/;
    $cqacc  =~ s/[\s\t]*$//g;
    $cqacc  =  $cqacc.'_G_@@';
Sebastien Moretti's avatar
Sebastien Moretti committed
685
686
687
688
    $cqdesc =~ s/^ *[^ ]* *(.*)$/$1/;
    $cqdesc =~ s/^[\| \.]*//;
    $cqdesc =~ s/[\|\. ]*$//;

689
    $QueryName = $cqacc.$cqdesc;
Sebastien Moretti's avatar
Sebastien Moretti committed
690
691
692
693
694
    return($QueryName);
}

#Prepare Fasta Header to put it on the fasta header of the result outputs
sub getFastaHeaderAnnot{
695
    my ($bestTarget) = @_;
Sebastien Moretti's avatar
Sebastien Moretti committed
696
697

    #Get annotation from nucleotide file header
698
699
700
    open(my $BEST, '<', "$cache/${bestTarget}.fas");
    my $annot=<$BEST> || '';
    close $BEST;
Sebastien Moretti's avatar
Sebastien Moretti committed
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
    chomp($annot);
    $annot =~ s/^ *[^ ]* //;
    $annot =~ s/[\. ]*$//;
    $annot =~ s/^ *//;
    $annot =~ s/  +/ /g;

    return($annot);
}

#########################################################


###################### Translation ######################

#Direct Reverse translation
sub reverse_trad{
717
    my ($aa) = @_;
Sebastien Moretti's avatar
Sebastien Moretti committed
718
719
720
721
722
723
724

    my %reverse_code=('A' => 'GCN', 'F' => 'TTy', 'K' => 'AAr', 'P' => 'CCN', 'T' => 'ACN',
                      'C' => 'TGy', 'G' => 'GGN', 'L' => 'yTN', 'Q' => 'CAr', 'V' => 'GTN',
                      'D' => 'GAy', 'H' => 'CAy', 'M' => 'ATG', 'R' => 'mGN', 'W' => 'TGG',
                      'E' => 'GAr', 'I' => 'ATh', 'N' => 'AAy', 'S' => 'wsN', 'Y' => 'TAy',
                      'X' => 'NNN', '-' => '---', '*' => 'Trr'); # '*' is for stop codon

725
726
727
728
729
730
    my $triplet = 'nnn';
    while( my ($x,$y) =each(%reverse_code) ){
        if ( uc($aa) eq $x ){
            $triplet = $y;
            last;
        }
Sebastien Moretti's avatar
Sebastien Moretti committed
731
732
733
734
735
736
737
738
739
740
    }

    return($triplet);
}

#########################################################


####################### webblast #######################
sub launchWebblast{
741
742
    my ($infile, $quiet, $whatBlast, $db, $species, $blast_exe, $outfile) = @_;
    my $blast_at = '';
Sebastien Moretti's avatar
Sebastien Moretti committed
743

744
745
746
    $blast_at    = "-database=$db"                         if ( $whatBlast==0 );
    $blast_at    = "-database=$db -blast_dir=${blast_exe}" if ( $whatBlast==1 );
    $blast_at    = "-database=$db -gigablast=yes"          if ( $whatBlast==2 );
Sebastien Moretti's avatar
Sebastien Moretti committed
747
748
749
750
751
752
753
754
755
756
757
758
759

#    print "             Evalue treshold : 0.05
#             Matrix : BLOSUM62
#             Filter : F
#             **********************
#             For RefSeq Protein db:
#             Blast_identity_threshold : 100
#             Cover threshold : 100
#             **********************
#             For NR Protein db:
#             Blast_identity_threshold : 95
#             Cover threshold : 95";

760
    system("$webblast_exe -program=blastp ${blast_at} -infile=$infile -matrix=BLOSUM62 -evalue=0.05 -method=geneid -filter=Off -organism=$species -identity=100 -cover=100 -hits=10 $quiet -outfile=$outfile");
Sebastien Moretti's avatar
Sebastien Moretti committed
761
762


763
764
765
766
767
768
769
    if ( -z "$outfile" ){ #Another blastP query if no hit with refseq and db was not nr !
        $quiet = '-quiet=on';
        print {*STDERR} "run BLAST.. against NR because there was no acceptable hit against $db\n"
            if ( $whatBlast != 1 && $db ne 'nr' );
        print {*STDERR} "run BLAST.. again, with decreased thresholds, because there was no acceptable hit against $db\n"
            if ( $whatBlast == 1 || $db eq 'nr' );
        $blast_at =~ s/-database=[^\s]*/-database=nr/ if ( $whatBlast != 1 );
770
        system("$webblast_exe -program=blastp ${blast_at} -infile=$infile -matrix=BLOSUM62 -evalue=0.05 -method=geneid -filter=Off -organism=$species -identity=95 -cover=95 -hits=10 $quiet -outfile=$outfile");
Sebastien Moretti's avatar
Sebastien Moretti committed
771
772
    }

773
774
775
776
777
778
779
    move('webblast.log',     "$cache"); #Move temporary webblast.pl files
    move('web_tempo.result', "$cache");
    move('debug.tempo',      "$cache");

    unlink("$cache/webblast.log")     if ( -z "$cache/webblast.log" );
    unlink("$cache/web_tempo.result") if ( -z "$cache/web_tempo.result" );
    unlink("$cache/debug.tempo")      if ( -z "$cache/debug.tempo" );
Sebastien Moretti's avatar
Sebastien Moretti committed
780

781
    return;
Sebastien Moretti's avatar
Sebastien Moretti committed
782
783
784
785
786
787
788
789
790
791
}


########################################################


##################### NCBI requests #####################

#Prot ACC -> PUID
sub blastPAcc2PGI{
792
    my ($blastHit) = @_;
Sebastien Moretti's avatar
Sebastien Moretti committed
793

794
795
796
    my $protGI = '';
    my $count  = 0;
    GET_PUI:
Sebastien Moretti's avatar
Sebastien Moretti committed
797
    for(my $rep=0;$rep <= 4; $rep++){
798
        $count++;
799
800
#        system("wget -q -O $cache/${date}_${blastHit}protGi.tmp 'http://eutils.ncbi.nlm.nih.gov/entrez/eutils/esearch.fcgi?db=protein&term=${blastHit}[pacc]&retmode=xml&tool=ProtoGene&email=smoretti\@unil.ch'");
        system("wget -q -O $cache/${date}_${blastHit}protGi.tmp 'http://eutils.ncbi.nlm.nih.gov/entrez/eutils/esearch.fcgi?db=protein&term=${blastHit}&retmode=xml&tool=ProtoGene&email=smoretti\@unil.ch'");
801
802
803
        open(my $GIP, '<', "$cache/${date}_${blastHit}protGi.tmp");
        PROT_GI:
        while(<$GIP>){
804
            if ( $_ =~ /^.*<Id>(\d+)<\/Id>.*$/ ){
805
806
807
808
809
810
811
                $protGI = $1;
                last PROT_GI; #OK if only one PUID
            }
        }
        close $GIP;
        $rep = $rep-15 if ( -z "$cache/${date}_${blastHit}protGi.tmp" && $count==1 );
        last GET_PUI if ( $protGI =~ /^\d+$/ );
Sebastien Moretti's avatar
Sebastien Moretti committed
812
    }
813
    unlink("$cache/${date}_${blastHit}protGi.tmp") if ( $tmp == 0 || $protGI ne '' );
Sebastien Moretti's avatar
Sebastien Moretti committed
814
815
816
817
818
819

    return($protGI);
}

#PUID -> nt GIs
sub protGI2NTGIs{
820
    my ($protGI, $blastHit) = @_;
Sebastien Moretti's avatar
Sebastien Moretti committed
821

822
823
824
825
    my $ntGIs  = '';
    my $geneID = '';
    my $count  = 0;
    GET_NTUI:
Sebastien Moretti's avatar
Sebastien Moretti committed
826
    for(my $rep=0;$rep <= 4; $rep++){
827
        $count++;
Sebastien Moretti's avatar
Sebastien Moretti committed
828
        #nt GIs
829
        system("wget -q -O $cache/${date}_${blastHit}nucleo.tmp 'http://eutils.ncbi.nlm.nih.gov/entrez/eutils/elink.fcgi?dbfrom=protein&db=nuccore,nucleotide,gene&id=$protGI&retmode=xml&tool=ProtoGene&email=smoretti\@unil.ch'");
830
831
832
833
834
835
836
837
838
839
840
        open(my $GIN, '<', "$cache/${date}_${blastHit}nucleo.tmp");
        my $flag = 0;
        NT_GI:
        while(<$GIN>){
            if ( $_   =~ /<LinkName>protein_nuc[a-z]+<\/LinkName>/ ){ #for nuccleotide and nuccore
                $flag = 1;
            }
            elsif ( $_ =~ /\<LinkName\>protein_gene\<\/LinkName\>/ ){
                $flag  = 2;
            }
            elsif ( $flag==1 && $_ =~ /^.*\<Id\>(\d+)\<\/Id\>.*$/ ){
841
842
843
                my $match = $1;
                $ntGIs  .= ",$match" if ( $ntGIs  ne '' && $ntGIs  !~ /,$match,/ && $ntGIs  !~ /^$match,/ );
                $ntGIs   = $match    if ( $ntGIs  eq '' );
844
845
            }
            elsif ( $flag==2 && $_ =~ /^.*\<Id\>(\d+)\<\/Id\>.*$/ ){
846
847
848
                my $match = $1;
                $geneID .= ",$match" if ( $geneID ne '' && $geneID !~ /,$match,/ && $geneID !~ /^$match,/ );
                $geneID  = $match    if ( $geneID eq '' );
849
850
851
852
853
            }
        }
        close $GIN;
        $rep = $rep-15 if ( -z "$cache/${date}_${blastHit}nucleo.tmp" && $count==1 );
        last GET_NTUI if ( $ntGIs ne '' || $geneID ne '' );
Sebastien Moretti's avatar
Sebastien Moretti committed
854
    }
855
    unlink("$cache/${date}_${blastHit}nucleo.tmp") if ( $tmp==0 || ($ntGIs ne '' || $geneID ne '') );
Sebastien Moretti's avatar
Sebastien Moretti committed
856

857
    return($ntGIs, $geneID);
Sebastien Moretti's avatar
Sebastien Moretti committed
858
859
860
}

sub geneID2Chr{
861
    my ($geneID, $blastHit) = @_;
Sebastien Moretti's avatar
Sebastien Moretti committed
862

863
864
865
866
    my $chr   = '';
    my ($amont, $aval) = ('', '');
    my $count = 0;
    GET_CHR:
Sebastien Moretti's avatar
Sebastien Moretti committed
867
    for(my $rep=0;$rep <= 8; $rep++){
868
        $count++;
Sebastien Moretti's avatar
Sebastien Moretti committed
869
        #Gene Acc
870
871
#        system("wget -q -O $cache/${date}_${blastHit}gene.tmp 'http://eutils.ncbi.nlm.nih.gov/entrez/eutils/efetch.fcgi?db=gene&id=$geneID&retmode=xml&tool=ProtoGene&email=smoretti\@unil.ch'");
        system("wget -q -O $cache/${date}_${blastHit}gene.tmp 'http://eutils.ncbi.nlm.nih.gov/entrez/eutils/esummary.fcgi?db=gene&id=$geneID&retmode=xml&tool=ProtoGene&email=smoretti\@unil.ch'");
872
873
874
875
876
877
878
        open(my $GACC, '<', "$cache/${date}_${blastHit}gene.tmp");
        my $flag = 0;
        GENE_CHR:
        while(<$GACC>){
            if ( $_  =~ /\<ERROR\>Empty id list \- nothing todo\<\/ERROR\>/ && $flag==0 ){
                $rep = $rep-15 if ( $count==1 );
            }
879
880
881
#            if ( $_   =~ /\<Entrezgene_locus\>/ && $flag==0 ){
            if ( $_   =~ /<Item Name="GenomicInfoType" Type="Structure">/ && $flag==0 ){
               $flag = 1;
882
            }
883
884
885
886
887
888
889
#            elsif ( $_ =~ /\<Gene-commentary_type value=\"genomic\"\>/ && $flag==1 ){
#                $flag  = 2;
#            }
#            elsif ( $_ =~ /\<Gene-commentary_type value=/ && $flag==2 ){
#                last GENE_CHR;
#            }
#            elsif ( $_ =~ /\<Gene-commentary_accession\>([\w\_\-\.]+)\<\/Gene-commentary_accession\>/ && $flag==2 ){
Sebastien Moretti's avatar
Sebastien Moretti committed
890
            elsif ( $_ =~ /<Item Name="ChrAccVer" Type="String">([^<]+?)\.?\d*<\/Item>/ && $flag==1 ){
891
892
893
                $chr   = $1;
                $flag  = 3;
            }
894
895
#            elsif ( $_ =~ /\<Seq-interval_from\>(\d+)\<\/Seq-interval_from\>/ && $flag==3 ){
            elsif ( $_ =~ /<Item Name="ChrStart" Type="Integer">(\d+)<\/Item>/ && $flag==3 ){
896
897
898
                $amont = $1;
                $flag  = 4;
            }
899
900
#            elsif ( $_ =~ /\<Seq-interval_to\>(\d+)\<\/Seq-interval_to\>/ && $flag==4 ){
            elsif ( $_ =~ /<Item Name="ChrStop" Type="Integer">(\d+)<\/Item>/ && $flag==4 ){
901
902
903
904
905
906
907
                $aval  = $1;
                last GENE_CHR;
            }
        }
        close $GACC;
        $rep = $rep-15 if ( -z "$cache/${date}_${blastHit}gene.tmp" && $count==1 );
        last GET_CHR   if ( $chr ne '' && $amont =~ /^\d+$/ && $aval =~ /^\d+$/ );
Sebastien Moretti's avatar
Sebastien Moretti committed
908
    }
909
910
911
912
    unlink("$cache/${date}_${blastHit}gene.tmp") if ( $tmp == 0 || $chr ne '' );
    if ( $amont eq '' || $aval eq '' ){
        $amont = '';
        $aval = '';
Sebastien Moretti's avatar
Sebastien Moretti committed
913
    }
914
915
916
917
918
919
920
921
922
    elsif ( $amont ne '' && $aval ne '' ){
        if ( $amont > $aval ){
            $amont = $amont+5000;
            $aval  = $aval-5000;
        }
        else{
            $amont = $amont-5000;
            $aval  = $aval+5000;
        }
Sebastien Moretti's avatar
Sebastien Moretti committed
923
    }
924
925
    $amont = 1 if ( $amont ne '' && $amont <= 0 );
    $aval  = 1 if ( $aval ne ''  && $aval <= 0 );
Sebastien Moretti's avatar
Sebastien Moretti committed
926

927
    return($chr, $amont, $aval);
Sebastien Moretti's avatar
Sebastien Moretti committed
928
929
930
}

sub downloadSeqFromGIs{
931
    my ($cache, $date, $amont, $aval, @acc) = @_;
Sebastien Moretti's avatar
Sebastien Moretti committed
932

933
    GET_SEQ:
Sebastien Moretti's avatar
Sebastien Moretti committed
934
    for(my $a=0; $a<=$#acc; $a++){
935
936
937
938
        my $whatNumber = 0;
        if ( $amont =~ /^\d+$/ && $aval =~ /^\d+$/ ){
            GET_CHR_SEQ:
            for(my $rep=0;$rep <= 4; $rep++){
939
                system("wget -q -O $cache/${acc[$a]}-${amont}.fas 'http://eutils.ncbi.nlm.nih.gov/entrez/eutils/efetch.fcgi?db=nucleotide&id=${acc[$a]}&rettype=fasta&retmode=text&from=$amont&to=$aval&tool=ProtoGene&email=smoretti\@unil.ch'") if ( !-e "$cache/${acc[$a]}-${amont}.fas" || -z "$cache/${acc[$a]}-${amont}.fas" || $cache eq 'none' || ($cache eq 'update' && -M "$cache/${acc[$a]}-${amont}.fas" > $cacheStorageTime ) );
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
                open(my $CIBLE, '<', "$cache/${acc[$a]}-${amont}.fas");
                my $counter = 0;
                my $lines   = 0;
                CHECK_CHR_SEQ:
                while(<$CIBLE>){
                    $lines++              if ( $_ !~ /^>/ );
                    $counter = $counter+2 if ( $counter==1 && $_ !~ /^\w/ && $lines==1 && $_ !~ /^>/ );
                    $counter++            if ( $_ =~ /^>/ );
                    $counter = $counter+2 if ( $_ !~ /^>/ && ($_ =~ /Error:/ || $_ =~ /[<>]/) );
#                   last CHECK_CHR_SEQ    if ( $_ !~ /^>/ && $counter==1 && $_ =~ /^\w/ );
                }
                close $CIBLE;
                $whatNumber++;
                last GET_CHR_SEQ if ( $whatNumber==20 );
                if ( $counter != 1 ){
                    $rep = $rep-1;
                    unlink("$cache/${acc[$a]}-${amont}.fas");
                }
            }
        }
        else{
            GET_OTHER_SEQ:
            for(my $rep=0;$rep <= 4; $rep++){
963
                system("wget -q -O $cache/${acc[$a]}.fas 'http://eutils.ncbi.nlm.nih.gov/entrez/eutils/efetch.fcgi?db=nucleotide&id=${acc[$a]}&rettype=fasta&retmode=text&tool=ProtoGene&email=smoretti\@unil.ch'") if ( !-e "$cache/${acc[$a]}.fas" || -z "$cache/${acc[$a]}.fas" || $cache eq 'none' || ($cache eq 'update' && -M "$cache/${acc[$a]}.fas" > $cacheStorageTime ) );
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
                open(my $CIBLE, '<', "$cache/${acc[$a]}.fas");
                my $counter = 0;
                my $lines   = 0;
                CHECK_OTHER_SEQ:
                while(<$CIBLE>){
                    $lines++              if ( $_ !~ /^>/ );
                    $counter = $counter+2 if ( $counter==1 && $_ !~ /^\w/ && $lines==1 && $_ !~ /^>/ );
                    $counter++            if ( $_ =~ /^>/ );
                    $counter = $counter+2 if ( $_ !~ /^>/ && ($_ =~ /Error:/ || $_ =~ /[<>]/) );
                }
                close $CIBLE;
                $whatNumber++;
                last GET_OTHER_SEQ if ( $whatNumber==20 );
                if ( $counter != 1 ){
                    $rep=$rep-1;
                    unlink("$cache/${acc[$a]}.fas");
                }
            }
        }
Sebastien Moretti's avatar
Sebastien Moretti committed
983
    }
984
985

    return;
Sebastien Moretti's avatar
Sebastien Moretti committed
986
987
988
}

sub downloadSeq{
989
    my ($cache, $date, $amont, $aval, @acc) = @_;
Sebastien Moretti's avatar
Sebastien Moretti committed
990

991
992
993
994
    my $cp   = 0;
    my $from = $amont;
    my $to   = $aval;
    DOWNL_SEQ:
Sebastien Moretti's avatar
Sebastien Moretti committed
995
    for(my $a=0; $a<=$#acc; $a++){
996
997
998
        my $pacc2puid = $acc[$a];
        if ( $pacc2puid !~ /^[NAX][CGTWZM]_/ ){
        #pacc = primary acc NOT prot acc !   #265666 -> S55551
999
            system("wget -q -O $cache/${date}_${acc[$a]}.gui 'http://eutils.ncbi.nlm.nih.gov/entrez/eutils/esearch.fcgi?&db=nucleotide&term=${pacc2puid}[pacc]&tool=ProtoGene&email=smoretti\@unil.ch'");
1000
            open(my $GUI, '<', "$cache/${date}_${acc[$a]}.gui");