ProtoGene.pl 58.5 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
15
16
17
18
use File::Which qw(which);                 # Locate external executable programs in the PATH
use Time::localtime;                       # Use localtime+PID for a pseudo-uniq temp file name
use Getopt::Long;                          # Options specifications
use File::Copy qw(move);                   # Avoid external 'mv' command usage
use LWP::Simple;                           # To test gigablaster availability
Sebastien Moretti's avatar
Sebastien Moretti committed
19

20
use Mail::Send;                            # Send warnings and errors files by e-mail ==> only if the $userEMail variable is defined
Sebastien Moretti's avatar
Sebastien Moretti committed
21

Sebastien Moretti's avatar
Sebastien Moretti committed
22
23
use FindBin qw( $RealBin );
use lib "$RealBin/lib";                    # Local path for ProtoGene's own perl modules
24
25
26
use Exonerate;                             # Exonerate runner, parser, ...
use Views;                                 # Non-text outputs, e.g. HTML/CSS
#use CheckOutput;                         # Check output for cds consistancy with query
Sebastien Moretti's avatar
Sebastien Moretti committed
27
28
29



30
################## CONFIGURATION ##################
Sebastien Moretti's avatar
Sebastien Moretti committed
31
32
my $cachePath        = '/scratch/cabernet/monthly/ProtoGene_Cache';   # Cache directory
my $cacheStorageTime = 15;                                            # Do not update sequences younger than X days
33

Sebastien Moretti's avatar
Sebastien Moretti committed
34
my $eutilsEmail      = quotemeta('tcoffee@vital-it.ch');              # Put your e-mail for NCBI eutils requests
Sebastien Moretti's avatar
Sebastien Moretti committed
35
36
my $eutilsTool       = 'ProtoGene';
my $eutilsAPIKey     = '2fc650885ef3f15ca562083e6332e7103c08';
Sebastien Moretti's avatar
Sebastien Moretti committed
37
my $userEMail        = 'moretti.sebastien@gmail.com';                 # To receive e-mails with encountered problems; leave blank to inactive
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52

### BLAST parameters ###
my $blast_param = { 'evalue'    => 0.05,
                    'matrix'    => 'BLOSUM62',
                    'filter'    => 'Off',
                    'species'   => 'All_organisms',

                    'db1'       => 'refseq_protein', # NCBI RefSeq protein
                    'identity1' => 100,
                    'cover1'    => 100,
                    'db2'       => 'nr', # NCBI nr protein
                    'identity2' =>  95,
                    'cover2'    =>  95,

                    'nbesthits' => 10,
53
                    'core'      => 1, # TODO really used ?
54
                  };
55
###################################################
Sebastien Moretti's avatar
Sebastien Moretti committed
56
57


58
my $VERSION  = '4.2.2';
Sebastien Moretti's avatar
Sebastien Moretti committed
59

Sebastien Moretti's avatar
Sebastien Moretti committed
60
my $webblast_exe  = "$RealBin/utils/webblast.pl";
61
62
my $blast_exe     = 'blastall';        # Or wu-blastall for Wu-BLAST; for local blast usage
my $exonerate_exe = 'exonerate';       # Exonerate 1.0 because current parser only works with this version
63
64
65


################## Option management
66
my ($msa, $revtrans, $pep, $hideBOJ, $run_name, $template, $lim) = ('', 0, 0, 0, '', '', 0);
Sebastien Moretti's avatar
Sebastien Moretti committed
67
my ($cache, $cleancache)                                         = ('update', 'update');#TODO Finish to implement
68
69
my ($debug, $tmp)                                                = (0, 0);
my ($db, $species, $local, $giga)                                = ($blast_param->{'db1'}, $blast_param->{'species'}, 0, 0);
Sebastien Moretti's avatar
Sebastien Moretti committed
70
my %opts = ('msa|in=s'        => \$msa,        # Input sequences
71
            'revtrans:s'      => \$revtrans,   # Use to reverse-translate sequences with no match
Sebastien Moretti's avatar
Sebastien Moretti committed
72
73
74
75
76
            '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
77
78
            'cachedir=s'      => \$cache,      # Cache directory
            'cacheclean=s'    => \$cleancache, # Cache behavior
Sebastien Moretti's avatar
Sebastien Moretti committed
79
80
81

            'orgm|species=s'  => \$species,    # Organism(s) to blast against
            'db|database=s'   => \$db,         # Database to blast against
82
            'local'           => \$local,      # Use to specify a local db query, defined in $local_db
Sebastien Moretti's avatar
Sebastien Moretti committed
83
84
85
86
87
88
89
90
91
92
            '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
93
           );
Sebastien Moretti's avatar
Sebastien Moretti committed
94
my $test_option_values = Getopt::Long::GetOptions(%opts);
95
#$revtrans = 1  if ( $revtrans eq '' ); # Allow revtrans to be a boolean or a string option (for tcoffee web server)
Sebastien Moretti's avatar
Sebastien Moretti committed
96

97
98

################## Short help message
99
if ( !$test_option_values || ($msa eq '' && $cleancache ne 'empty' && $cleancache ne 'old') ){
100
101
102
    print {*STDERR} "\n\tCannot open the MSA file in FASTA format
\tTry:  $0 --msa=path_of_the_fasta_msa_file [Options]

103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
\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 '$blast_param->{'species'}'
\t         --db        =nr, pdb, swissprot, refseq_protein
\t                      default is '$blast_param->{'db1'}'
\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   reverse-translates sequences with no
\t                      blast hit, in IUB (IUPAC) depiction code
\t                      They are removed from the alignement by default
\t         --pep        adds the original peptide query beneath the
\t                      back-translated sequence
\t         --cachedir  ='own_PATH_directory'
\t                      (default is '$cachePath')
\t         --cacheclean=none, update, use, old, empty
\t                      to select the cache behavior (default is 'update')\n
\t         --debug      prints extra information when running
\t         --version    prints version information
\t         --help       prints a full help message\n\n";
127
    exit(1);
Sebastien Moretti's avatar
Sebastien Moretti committed
128
}
129
130


131
################## Check cache directory accessibility
Sebastien Moretti's avatar
Sebastien Moretti committed
132
133
134
if ( -d $cache ){
    $cachePath = $cache;
}
135
checkCacheAccessibility($cachePath);
136

137
138
# Cache management
$cache = cacheManagement($cache, $cachePath, 0) || '.';
139

140
141
# Remove old files from the cache directory everytime ProtoGene is running
cacheManagement('old', $cachePath, 1);
142
143


144
145

################## Check external software in the PATH
146
checkExternalSoftware($webblast_exe, $exonerate_exe);
147
148
if ( $local ){
    checkExternalSoftware($blast_exe);
Sebastien Moretti's avatar
Sebastien Moretti committed
149
150
151
152
}



153
154
155
################## Check input files
# Open and check template file
my ($template_NT, $template_AA, $template_SEQ);
156
#TODO: template is fasta only now
157
158
($template_NT, $template_AA, $template_SEQ) = checkTemplate($template) if ( $template );

Sebastien Moretti's avatar
Sebastien Moretti committed
159

Sebastien Moretti's avatar
Sebastien Moretti committed
160
161
162
163
164
# 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
165

166
my $fasta_checker = -1;
167
my (@original_names, @original_seq); #Use 2 lists in parallel : original_names, seq
Sebastien Moretti's avatar
Sebastien Moretti committed
168
169
open( my $MSA, '<', "$msa" ) or die "\n\tCannot open your MSA file\n\n";
READ_MSA:
170
while(<$MSA>){
Sebastien Moretti's avatar
Sebastien Moretti committed
171
172
    next READ_MSA if ( $_ =~ /^#/ );

173
    if ( $_ =~ /^>/ ){
174
175
        $fasta_checker++;
        my $name = $_;
Sebastien Moretti's avatar
Sebastien Moretti committed
176
177
178
        $name    =~ s{\r\n}{}g; #Remove return lines from windows OS '^M'
        $name    =~ s{\r}{\n}g;
        $name    =~ s{^>[ \t]+}{>};
179
        chomp($name);
Sebastien Moretti's avatar
Sebastien Moretti committed
180
181

        push @original_names, $name;
Sebastien Moretti's avatar
Sebastien Moretti committed
182
    }
Sebastien Moretti's avatar
Sebastien Moretti committed
183
184
185
186
187
188
189
190
191
192
    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
193
        #fasta sequence on 1 line
194
        if ( !exists($original_seq[$fasta_checker]) ){
Sebastien Moretti's avatar
Sebastien Moretti committed
195
            push @original_seq, $sequence;
196
197
        }
        else {
Sebastien Moretti's avatar
Sebastien Moretti committed
198
            $original_seq[$fasta_checker] .= $sequence;
199
        }
Sebastien Moretti's avatar
Sebastien Moretti committed
200
201
    }
}
202
close $MSA;
Sebastien Moretti's avatar
Sebastien Moretti committed
203
204

#Are there FASTA sequences ?
205
if ( $fasta_checker == -1 ){
Sebastien Moretti's avatar
Sebastien Moretti committed
206
    failure();
Sebastien Moretti's avatar
Sebastien Moretti committed
207
208
    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";
209
    exit(1);
Sebastien Moretti's avatar
Sebastien Moretti committed
210
}
211
elsif ( $lim >0 && $fasta_checker > $lim ){
Sebastien Moretti's avatar
Sebastien Moretti committed
212
    failure();
213
    print {*STDERR} "\tThe FASTA file is too large, try with less than $lim sequences\n\tor split your file\n\n";
214
215
    exit(1);
}
216
elsif ( exists( $original_seq[0] ) && $original_seq[0] =~ /[acgtu]/i ){
217
    my $first_seq = $original_seq[0];
Sebastien Moretti's avatar
Sebastien Moretti committed
218
219
220
221
222
223
    #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;
224
    if ( ($a+$c+$g+$t) >= (($a+$c+$g+$t+$non)*80/100) ){
Sebastien Moretti's avatar
Sebastien Moretti committed
225
        failure();
Sebastien Moretti's avatar
Sebastien Moretti committed
226
227
        print {*STDERR} "\tYour sequences look already to be nucleotides
\tThe goal of this program is to turn AMINO ACID alignments into CDS nucleotide alignments\n\n";
228
229
        exit(1);
    }
Sebastien Moretti's avatar
Sebastien Moretti committed
230
231
232
233
}
undef $fasta_checker;


Sebastien Moretti's avatar
Sebastien Moretti committed
234
# Check GigaBlaster status if used
235
if ( $giga==1 ){
236
    $local = 0;
Sebastien Moretti's avatar
Sebastien Moretti committed
237
    $local = 2  if ( head('http://www.igs.cnrs-mrs.fr/public_g/remoteblast.cgi') );
238
239
}

Sebastien Moretti's avatar
Sebastien Moretti committed
240

Sebastien Moretti's avatar
Sebastien Moretti committed
241
# Temporary file extension
242
my $date = sprintf("%d-%02d-%02d_%02dh%02d", localtime->year() + 1900, localtime->mon() + 1, localtime->mday(), localtime->hour, localtime->min);
Sebastien Moretti's avatar
Sebastien Moretti committed
243
244


245

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

249
open(my $EXONERATEISHERE, "$exonerate_exe --version |");
250
my $IsExonerateHere = <$EXONERATEISHERE>;
251
close $EXONERATEISHERE;
Sebastien Moretti's avatar
Sebastien Moretti committed
252
253
print "\t   $IsExonerateHere\n";
undef $IsExonerateHere;
254
undef $VERSION;
255

Sebastien Moretti's avatar
Sebastien Moretti committed
256
for(my $m=0; $m<=$#original_names; $m++){
257
    printf("\t>%-3s  is  %s\n", $m, $original_names[$m]);
Sebastien Moretti's avatar
Sebastien Moretti committed
258
}
Sebastien Moretti's avatar
Sebastien Moretti committed
259
$date .= "_$$"; #Add PID to be more uniq
Sebastien Moretti's avatar
Sebastien Moretti committed
260
261
262
263



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

266
267
unlink("$originalMSA.cds", "$originalMSA.cdsP", "$originalMSA.cdsP.html",
       "$originalMSA.out", "$originalMSA.boj",  "$originalMSA.log");
Sebastien Moretti's avatar
Sebastien Moretti committed
268
269


270
# Build the sequences, from the alignment, to perform blast search
271
EACH_SEQ:
272
273
274
275
276
277
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

Sebastien Moretti's avatar
Sebastien Moretti committed
278

Sebastien Moretti's avatar
Sebastien Moretti committed
279
    my @equivalent_blast_hits; #Multiple BLAST hits with the same highest e-value/score
280
281

    if ( exists($template_NT->{$short_name}) && $template_NT->{$short_name} ne '' ){
Sebastien Moretti's avatar
Sebastien Moretti committed
282
283
284
        # 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
285
    }
286
    elsif ( exists($template_AA->{$short_name}) && $template_AA->{$short_name} ne '' ){
Sebastien Moretti's avatar
Sebastien Moretti committed
287
288
289
        # 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
290
291
    }
    else{
292
    # else send them to webblast
Sebastien Moretti's avatar
Sebastien Moretti committed
293
294
295
296
297
298
299
        # Prepare sequence $r for BLAST
        open(my $READY2BLAST, '>', "$cache/$date.seq2blast.fas.$r");
        my $noGap = $original_seq[$r];
        $noGap    =~ s{\-}{}g; #remove gaps
        print {$READY2BLAST} ">$r\n$noGap\n";
        close $READY2BLAST;

300
301
302
303
304
        if ($r==0){
            # Show BLAST parameters only for the first BLAST run
            display_blast_param();
        }
        run_BLAST("$cache/$date.seq2blast.fas.$r", $local, $blast_param->{'db1'}, $blast_exe, "$cache/$date.blastp.$r");
Sebastien Moretti's avatar
Sebastien Moretti committed
305

306
307
308

        # Get the BLASTp hit(s)  acc number
        open(my $BLASTP, '<', "$cache/$date.blastp.$r");
309
        while(<$BLASTP>){
310
            push @equivalent_blast_hits, $1  if ( $_ =~ /^>.+?\@.+?__(\S+).*$/ ); #Warning: double '_'
311
312
        }
        close $BLASTP;
313
        unlink("$cache/$date.blastp.$r", "$cache/$date.seq2blast.fas.$r")  if ( $tmp == 0 || exists($equivalent_blast_hits[0]) );
Sebastien Moretti's avatar
Sebastien Moretti committed
314
        if ( !exists($equivalent_blast_hits[0]) ){
315
            print "\n$r ...\tNo blast result found above thresholds for $fasta_header\n\n";
316
            buildFailureOutputFiles($r, 'No_BLASTp_Result', 'Not_searched');
317
318
319
320
            undef $original_seq[$r];
            undef $original_names[$r];
            next EACH_SEQ;
        }
Sebastien Moretti's avatar
Sebastien Moretti committed
321
322
323
324
    }



325
    #When multiple equivalent blast hits  ==> use, and add, every hits
326
    my ($resultPOS, $resultBOJ) = ('', '');
327
    my @failureStatus = (''); # To always have $failureStatus[0] defined
328
    my @intronStatus  = ('');
329
    HIT_LINK:
Sebastien Moretti's avatar
Sebastien Moretti committed
330
331
    for(my $qq=0; $qq<=$#equivalent_blast_hits; $qq++){
        print "\n$fasta_header  -->  [$equivalent_blast_hits[$qq]]\n";
332
333
334
335


        my @nt_GIs;
        my $intronStep = 0;
336
337
338
        # Get Nt sequence from template
        if ( exists($template_NT->{$short_name}) && $template_NT->{$short_name} ne '' ){
            if ( $template_NT->{$short_name} !~ /^My_Seq$/i ){
339
                download_seq($cache, '', '', $template_NT->{$short_name});
340
341
342
343
344
345
346
347
                @nt_GIs = $template_NT->{$short_name};
            }
            else {
                open(my $MYSEQ, '>', "$cache/My_Seq-$$.fas");
                print {$MYSEQ} ">My_Seq-$$ for $short_name\n".$template_SEQ->{$short_name}."\n";
                close $MYSEQ;
                @nt_GIs = "My_Seq-$$";
            }
348
        }
349
        # Get Nt sequence through prot acc -> prot gi -> nt linked gi -> nt acc
350
        else{
Sebastien Moretti's avatar
Sebastien Moretti committed
351
            # Prot ACC -> PUID
Sebastien Moretti's avatar
Sebastien Moretti committed
352
            my $protGI = blastPAcc2PGI($equivalent_blast_hits[$qq]);
353
            if ( $protGI eq '' ){
Sebastien Moretti's avatar
Sebastien Moretti committed
354
355
                print "\tNo protein (prot GI) link found for $equivalent_blast_hits[$qq] in $fasta_header\n\n";
                @failureStatus = ('PUI_unavailable', $equivalent_blast_hits[$qq]);
356
                next HIT_LINK;
357
            }
Sebastien Moretti's avatar
Sebastien Moretti committed
358

Sebastien Moretti's avatar
Sebastien Moretti committed
359
            # PUID -> nt GIs & GeneID
Sebastien Moretti's avatar
Sebastien Moretti committed
360
            my ($ntGIs, $geneID) = protGI2NTGIs($protGI, $equivalent_blast_hits[$qq]);
361
            if ( $ntGIs eq '' && $geneID eq '' ){
Sebastien Moretti's avatar
Sebastien Moretti committed
362
363
                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]);
364
                next HIT_LINK;
365
366
367
368
            }
            print " linked with [$ntGIs $geneID]\n";


Sebastien Moretti's avatar
Sebastien Moretti committed
369
            # Get transcript and contig seq
Sebastien Moretti's avatar
Sebastien Moretti committed
370
            if ( $ntGIs ne '' ){
Sebastien Moretti's avatar
Sebastien Moretti committed
371
                @nt_GIs = split(/,/, $ntGIs);
Sebastien Moretti's avatar
Sebastien Moretti committed
372
373
                downloadSeqFromGIs($cache, '', '', @nt_GIs);
            }
374

Sebastien Moretti's avatar
Sebastien Moretti committed
375
            # GeneID -> Chr
376
377
378
379
380
381
382
            if ( $geneID ne '' ){
                my @geneIDs = split(/,/, $geneID);
                while(<@geneIDs>){
                    my $geneID = $_;
                    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 '');

Sebastien Moretti's avatar
Sebastien Moretti committed
383
                    # Get Chr seq
384
385
                    if ( $chr ne '' ){
                        download_seq($cache, $amont, $aval, $chr);
Sebastien Moretti's avatar
Sebastien Moretti committed
386
                        $intronStep = 1;
387

388
                        unshift(@nt_GIs, "$chr--$amont-$aval");
389
                    }
390
391
392
393
394
                }
            }
        }


Sebastien Moretti's avatar
Sebastien Moretti committed
395
396
        # Align Nt seq with our protein query seq
        my ($POS, $BOJ) = runExonerate($cache, $date, $r, $original_seq[$r], $fasta_header, @nt_GIs);
397
        next HIT_LINK if ( !defined $POS );
398

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

402
403
        @intronStatus = ($POS->{0}, $equivalent_blast_hits[$qq], '')              if ( $intronStep==1 && exists($POS->{0}) && $POS->{0} =~ /\:/ );
        @intronStatus = ($POS->{0}, $equivalent_blast_hits[$qq], $bestNucleotide) if ( $intronStep==0 && $bestNucleotide =~ /^NA[CTWZGS]_/ );
404
405
406

        my ($intronLess, $nameLess) = ('', '');
        $intronLess = $POS->{0}       if ( %$BOJ eq 0 && exists($POS->{0}) && $POS->{0} ne '' );
407
        $nameLess   = $bestNucleotide if ( %$BOJ eq 0 && $intronStep==0 && $bestNucleotide =~ /^NA[CTWZGS]_/ );
Sebastien Moretti's avatar
Sebastien Moretti committed
408
        my ($BOJresult, $bestGenomic) = prepareResults4BOJ($BOJ, $equivalent_blast_hits[$qq], $original_seq[$r], $fasta_header, $intronLess, $nameLess);
409
        $resultBOJ .= $BOJresult      if ( $bestGenomic ne '' && $BOJresult ne '' && $resultBOJ !~ /_G_$bestGenomic[ \-]/ );
Sebastien Moretti's avatar
Sebastien Moretti committed
410
411
412
    }


413
    if ( $resultPOS eq '' ){
414
        if ( $failureStatus[0] ne '' ){
415
            buildFailureOutputFiles($r, $failureStatus[1],         $failureStatus[0]);
416
417
        }
        else {
418
            buildFailureOutputFiles($r, $equivalent_blast_hits[0], 'Alignment_failure');
419
        }
420
        next EACH_SEQ;
Sebastien Moretti's avatar
Sebastien Moretti committed
421
    }
422
423
    elsif ( $resultBOJ eq '' ){
        if ( $failureStatus[0] eq 'PUI_unavailable' || $failureStatus[0] eq 'No_nt_link' ){
424
            buildFailureBOJOutputFile($failureStatus[1], $failureStatus[0], $fasta_header, $original_seq[$r]);
425
426
        }
        elsif ( $failureStatus[0] eq '' && $intronStatus[0] ne '' ){
427
            buildIntronlessBOJOutputFile($intronStatus[1], $intronStatus[0], $intronStatus[2], $fasta_header, $original_seq[$r]);
428
429
        }
        else{
Sebastien Moretti's avatar
Sebastien Moretti committed
430
            buildFailureBOJOutputFile($equivalent_blast_hits[0], 'Unavailable', $fasta_header, $original_seq[$r]);
431
        }
432
        createCDSOutputFile($resultPOS, $original_seq[$r], $fasta_header);
Sebastien Moretti's avatar
Sebastien Moretti committed
433
434
    }
    else {
435
        createCDSOutputFile($resultPOS, $original_seq[$r], $fasta_header);
436
        createBOJOutputFile($resultBOJ);
Sebastien Moretti's avatar
Sebastien Moretti committed
437
438
439
440
441
442
443
444
    }


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


445
checkAndCleanStderrFiles("$cache/$date.ExonerateError")  if ( -e "$cache/$date.ExonerateError" );
Sebastien Moretti's avatar
Sebastien Moretti committed
446
checkOutputFiles();
447
unlink("$msa")  if ( $converted==1 );
448
unlink 'blast_result.txt';
Sebastien Moretti's avatar
Sebastien Moretti committed
449
my @tmpFiles = glob($cache."/$date*");
Sebastien Moretti's avatar
Sebastien Moretti committed
450
if ( exists($tmpFiles[0]) ){
Sebastien Moretti's avatar
Sebastien Moretti committed
451
    mkdir("$cache/$date.TMP");
452
    move("$_", "$cache/$date.TMP")  while(<@tmpFiles>);
Sebastien Moretti's avatar
Sebastien Moretti committed
453
454
455
456
457
458
459
}


#Ouput Checker


#STDOUT Log output for our server
Sebastien Moretti's avatar
Sebastien Moretti committed
460
if ( -s "$originalMSA.cds" || -s "$originalMSA.out" ){
Sebastien Moretti's avatar
Sebastien Moretti committed
461
    print "\n\nTERMINATION STATUS: SUCCESS\n";
462
    print 'OUTPUT RESULTS', "\n";
463
    print "    #### File Type=        MSA Format= fasta_CDS Name= $originalMSA.cds\n"
464
        if ( -s "$originalMSA.cds" );
465
    print "    #### File Type=        MSA Format= fasta_CDS+Query Name= $originalMSA.cdsP\n"
466
        if ( -s "$originalMSA.cdsP" );
467
    print "    #### File Type=        MSA Format= colored_fasta_CDS Name= $originalMSA.cdsP.html\n"
468
        if ( Views::Html("$originalMSA.cdsP") && -s "$originalMSA.cdsP.html" );
469
    print "    #### File Type=        MSA Format= Rejected_seq Name= $originalMSA.out\n"
470
        if ( -s "$originalMSA.out" );
471
    print "    #### File Type=        MSA Format= fasta_Exon-Boundaries Name= $originalMSA.boj\n"
472
        if ( -s "$originalMSA.boj" && -s "$originalMSA.cds" && $hideBOJ==0 );
Sebastien Moretti's avatar
Sebastien Moretti committed
473
474

    unlink "$cache/web_tempo.result";
Sebastien Moretti's avatar
Sebastien Moretti committed
475
476
}
else{
Sebastien Moretti's avatar
Sebastien Moretti committed
477
    failure();
478
    exit(1);
Sebastien Moretti's avatar
Sebastien Moretti committed
479
480
}

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


=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

514
515
516
517
518
519
520
=item I<--cachedir>=your_own_path_directory

=item cachedir sets cache directory

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

=item cacheclean manages cache behavior
Sebastien Moretti's avatar
Sebastien Moretti committed
521
522
523
524
525
526
527
528
529

=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 old: remove the old files in the cache directory

530
=item empty: empty completely the cache directory
Sebastien Moretti's avatar
Sebastien Moretti committed
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551

=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 !

552
=item Standard Perl modules B<lib>, B<strict>,  B<warnings>,  B<diagnostics> are required
Sebastien Moretti's avatar
Sebastien Moretti committed
553

554
=item as well as some other current ones : B<Getopt::Long>,  B<File::Which>,  B<File::Copy>, B<Mail::Send>, B<Time::localtime>, B<LWP::Simple>
Sebastien Moretti's avatar
Sebastien Moretti committed
555
556
557

=item -

558
=item I<exonerate> version 2 from http://www.ebi.ac.uk/about/vertebrate-genomics/software/exonerate
Sebastien Moretti's avatar
Sebastien Moretti committed
559

560
=item I<blast> from ftp://ftp.ncbi.nih.gov/blast/executables/
Sebastien Moretti's avatar
Sebastien Moretti committed
561
562
563
564
565
566
567

=back

=head1 VERSION

=over 8

568
=item version 4.2.2
Sebastien Moretti's avatar
Sebastien Moretti committed
569

570
=item on Sep 09th, 2016
Sebastien Moretti's avatar
Sebastien Moretti committed
571
572
573
574
575
576
577
578
579

=back

=head1 AUTHORS

=over 8

=item Sebastien MORETTI

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

582
=item Vital-IT computing center
Sebastien Moretti's avatar
Sebastien Moretti committed
583

Sebastien Moretti's avatar
Sebastien Moretti committed
584
=item SIB Swiss Institute of Bioinformatics
Sebastien Moretti's avatar
Sebastien Moretti committed
585

586
=item Lausanne, Switzerland
Sebastien Moretti's avatar
Sebastien Moretti committed
587

Sebastien Moretti's avatar
Sebastien Moretti committed
588
=item https://www.vital-it.ch/
Sebastien Moretti's avatar
Sebastien Moretti committed
589
590
591
592
593
594
595
596

=back

=cut


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

597
# Failure declaration
Sebastien Moretti's avatar
Sebastien Moretti committed
598
sub failure {
599
600
601
    print {*STDERR} "\n\nFATAL\n\nTERMINATION STATUS: FAILURE\n\n";
    return;
}
Sebastien Moretti's avatar
Sebastien Moretti committed
602

Sebastien Moretti's avatar
Sebastien Moretti committed
603
# Check external programs presence in the PATH
604
sub checkExternalSoftware {
Sebastien Moretti's avatar
Sebastien Moretti committed
605
    for my $exe ( @_ ){
606
        if ( ! which($exe) && !-x $exe ){
Sebastien Moretti's avatar
Sebastien Moretti committed
607
608
609
610
            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
611
    }
Sebastien Moretti's avatar
Sebastien Moretti committed
612
    return;
Sebastien Moretti's avatar
Sebastien Moretti committed
613
614
}

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

619
    if ( -d "$cacheDir/" && -w "$cacheDir/" && -x "$cacheDir/" && -r "$cacheDir/" ){
620
        # Good
Sebastien Moretti's avatar
Sebastien Moretti committed
621
    }
622
623
624
    elsif ( -d "$cacheDir/" ){
        if ( -o "$cacheDir/" ){
            chmod 0754, "$cacheDir/";
625
        }
626
        else{
627
628
629
            failure();
            print {*STDERR} "\tPermissions do NOT seem to be valid for the '$cacheDir' cache directory\n\n";
            exit(2);
630
        }
Sebastien Moretti's avatar
Sebastien Moretti committed
631
632
    }
    else{
633
        mkdir "$cacheDir/"; # FIXME: mkdir is not recursive !
634
        if ( -o "$cacheDir/" ){
635
            chmod 0754, "$cacheDir/"; #0754 is in octal, so 754 or '0754' are not good !
636
637
        }
        else{
638
639
640
            failure();
            print {*STDERR} "\tPermissions do NOT seem to be valid for the '$cacheDir' cache directory\n\n";
            exit(2);
641
        }
Sebastien Moretti's avatar
Sebastien Moretti committed
642
    }
643

644
    return;
Sebastien Moretti's avatar
Sebastien Moretti committed
645
646
}

647
# Cache Behavior Management
Sebastien Moretti's avatar
Sebastien Moretti committed
648
sub cacheManagement{
649
    my ($cache, $cacheDir, $inScript) = @_;
650

651
    if ( $cache eq 'empty' ){
652
        unlink <$cacheDir/*.fas>;
Sebastien Moretti's avatar
Sebastien Moretti committed
653
        unlink <$cacheDir/*.ExonerateError>;
654
655
        unlink("$cacheDir/webblast.log", "$cacheDir/web_tempo.result", "$cacheDir/debug.tempo");
        print "\n\tcache directory [$cacheDir] is empty\n\n";
656
        exit 0;
Sebastien Moretti's avatar
Sebastien Moretti committed
657
    }
658
    elsif ( $cache eq 'old' ){
659
660
661
662
663
        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;
664
        }
Sebastien Moretti's avatar
Sebastien Moretti committed
665
    }
666
    elsif ( $cache eq 'update' || $cache eq 'use' ){
667
668
        # DEFAULT: Limit cached files to less than $cacheStorageTime days old ones for 'update'
        $cache = $cacheDir;
Sebastien Moretti's avatar
Sebastien Moretti committed
669
    }
670
    elsif ( $cache eq 'none' ){
671
        # Do not use cache
Sebastien Moretti's avatar
Sebastien Moretti committed
672
    }
673
674
675
676
    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
677
678
    }
    else {
679
680
681
        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
682
683
684
685
686
687
688
689
690
691
    }

    return($cache);
}

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


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

Sebastien Moretti's avatar
Sebastien Moretti committed
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
# 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;
707
        }
Sebastien Moretti's avatar
Sebastien Moretti committed
708
709
    }
    else {
Sebastien Moretti's avatar
Sebastien Moretti committed
710
        failure();
711
712
        print {*STDERR} "\tThe file \'$msa\' doesn't not seem to be reachable\n\n";
        exit(1);
Sebastien Moretti's avatar
Sebastien Moretti committed
713
714
    }

Sebastien Moretti's avatar
Sebastien Moretti committed
715
    return($msa, $converted);
Sebastien Moretti's avatar
Sebastien Moretti committed
716
717
718
719
}

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

722
    $QueryName =~ s{  +}{ }g;
723
    my ($acc, $desc) = ($QueryName, $QueryName);
724
725
    $acc  =~ s{^ *([^ ]*) .*$}{$1};
    $acc  =~ s{\s+$}{}g;
726
727
    $acc  =  $acc.'_G_@@';

728
729
730
    $desc =~ s{^ *[^ ]* *(.*)$}{$1};
    $desc =~ s{^[\| \.]+}{};
    $desc =~ s{[\|\. ]+$}{};
731
732

    return($acc.$desc);
Sebastien Moretti's avatar
Sebastien Moretti committed
733
734
735
736
}

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

    #Get annotation from nucleotide file header
Sebastien Moretti's avatar
Sebastien Moretti committed
740
741
    open(my $BEST, '<', "$cache/$bestTarget.fas");
    my $annot = <$BEST> || '';
742
    close $BEST;
Sebastien Moretti's avatar
Sebastien Moretti committed
743

Sebastien Moretti's avatar
Sebastien Moretti committed
744
    chomp($annot);
745
746
747
748
    $annot =~ s{^ *[^ ]* }{};
    $annot =~ s{[\. ]*$}{};
    $annot =~ s{^ *}{};
    $annot =~ s{  +}{ }g;
Sebastien Moretti's avatar
Sebastien Moretti committed
749
750
751
752
753
754
755
756
757
758
759

    return($annot);
}

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


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

#Direct Reverse translation
sub reverse_trad{
760
    my ($aa) = @_;
Sebastien Moretti's avatar
Sebastien Moretti committed
761

762
763
764
765
766
767
    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
Sebastien Moretti's avatar
Sebastien Moretti committed
768

769
    my $triplet = 'nnn';
770
    while( my ($x, $y) = each(%reverse_code) ){
771
772
773
774
        if ( uc($aa) eq $x ){
            $triplet = $y;
            last;
        }
Sebastien Moretti's avatar
Sebastien Moretti committed
775
776
777
778
779
780
781
782
783
    }

    return($triplet);
}

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


####################### webblast #######################
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
sub display_blast_param {
    print "
             Program :                   BLASTp
             Evalue threshold :          $blast_param->{'evalue'}
             Matrix :                    $blast_param->{'matrix'}
             Filter :                    $blast_param->{'filter'}
             Equivalent best hits used : $blast_param->{'nbesthits'}

             Database:                   NCBI $blast_param->{'db1'}
             Blast_identity_threshold :  $blast_param->{'identity1'}
             Cover threshold :           $blast_param->{'cover1'}
          if no match
             Database:                   NCBI $blast_param->{'db2'}
             Blast_identity_threshold :   $blast_param->{'identity2'}
             Cover threshold :            $blast_param->{'cover2'}
\n";
    return;
}

sub run_BLAST{
    my ($infile, $whatBlast, $db, $blast_exe, $outfile) = @_;

    my $blast_at = $whatBlast==2  ? '-gigablast=yes'
                 : $whatBlast==1  ? "-blast_dir=$blast_exe"
                 :                  '';

    # BLAST run 1
    system("$webblast_exe -program=blastp -database=$db $blast_at -infile=$infile -matrix=$blast_param->{'matrix'} -evalue=$blast_param->{'evalue'} -method=geneid -filter=$blast_param->{'filter'} -organism=$species -identity=$blast_param->{'identity1'} -cover=$blast_param->{'cover1'} -hits=$blast_param->{'nbesthits'} -quiet=on -outfile=$outfile");


    if ( -z "$outfile" ){
    # BLAST run 2 if no hit with 100% identity and coverage: refseq100 -> nr95  OR  nr100 -> nr95
Sebastien Moretti's avatar
Sebastien Moretti committed
816
        print "run BLAST.. against $blast_param->{'db2'} because there was no acceptable hit against $blast_param->{'db1'}\n"
817
            if ( $whatBlast != 1 && $db ne 'nr' );
Sebastien Moretti's avatar
Sebastien Moretti committed
818
        print "run BLAST.. again, with decreased thresholds, because there was no acceptable hit against $db\n"
819
            if ( $whatBlast == 1 || $db eq 'nr' );
820
821

        system("$webblast_exe -program=blastp -database=$blast_param->{'db2'} $blast_at -infile=$infile -matrix=$blast_param->{'matrix'} -evalue=$blast_param->{'evalue'} -method=geneid -filter=$blast_param->{'filter'} -organism=$species -identity=$blast_param->{'identity2'} -cover=$blast_param->{'cover2'} -hits=$blast_param->{'nbesthits'} -quiet=on -outfile=$outfile");
Sebastien Moretti's avatar
Sebastien Moretti committed
822
823
    }

824
825
826
827
828
829
830
    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
831

832
    return;
Sebastien Moretti's avatar
Sebastien Moretti committed
833
834
835
836
837
838
839
}


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


##################### NCBI requests #####################
840
841
842
sub fetch {
    my ($url) = @_;

843
    XML:
844
845
    for (my $tries=0; $tries <20; $tries++ ){
        my $content = get($url);
846
        print {*STDERR} "[$content]\n\n" if ($debug);
847
        if ( defined $content ){
848
            next XML  if ( $content =~ /<ERROR>/i && $content !~ /<ERROR>Can not find description/i );
849
850
            return $content;
        }
851
    }
Sebastien Moretti's avatar
Sebastien Moretti committed
852
    print {*STDERR} "\n\tERROR: Problem with NCBI eutils, please try again later\n";
853
    print {*STDOUT} "\n\tERROR: Problem with NCBI eutils, please try again later\n";
Sebastien Moretti's avatar
Sebastien Moretti committed
854
    exit(4);
855
}
856

857
858
859
sub fetch_fasta {
    my ($url, $outfile) = @_;

860
    return 1 if ( -s "$outfile" && $cache eq 'update' && -M "$outfile" <= $cacheStorageTime );
861

862
863
864
865
866
867
868
869
870
871
872
    GET_FASTA:
    for (my $tries=0; $tries <20; $tries++ ){
        my $HTTP_status = getstore($url, $outfile);
        if ( is_error($HTTP_status) ){
            next GET_FASTA;
        }
        else {
            open(my $FASTA, '<', "$outfile");
            my $counter = 0;
            my $lines   = 0;
            while(<$FASTA>){
873
#                $lines++              if ( $_ !~ /^>/ ); #Allow download of entries with only fasta header and no sequence associated
874
875
876
877
878
                $counter = $counter+2 if ( $counter==1 && $_ !~ /^\w/ && $lines==1 && $_ !~ /^>/ );
                $counter++            if ( $_ =~ /^>/ );
                $counter = $counter+2 if ( $_ !~ /^>/ && ($_ =~ /Error:/ || $_ =~ /[<>]/) );
            }
            close $FASTA;
879

880
881
882
            return 1 if ( $counter == 1 );
        }
    }
883
    print {*STDERR} "[[$url]]\n" if ( $debug );
884
    unlink("$outfile");
Sebastien Moretti's avatar
Sebastien Moretti committed
885
    print {*STDERR} "\n\tERROR: Problem with NCBI eutils, please try again later.\n";
886
    print {*STDOUT} "\n\tERROR: Problem with NCBI eutils, please try again later.\n";
Sebastien Moretti's avatar
Sebastien Moretti committed
887
    exit(5);
888
889
}

Sebastien Moretti's avatar
Sebastien Moretti committed
890
891
892

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

895
    my $protGI = '';
896
    #FIXME: should be ${blastHit}[pacc] but something is broken at NCBI
Sebastien Moretti's avatar
Sebastien Moretti committed
897
    my $content = fetch("https://eutils.ncbi.nlm.nih.gov/entrez/eutils/esearch.fcgi?db=protein&term=$blastHit&retmode=xml&tool=$eutilsTool&email=$eutilsEmail&api_key=$eutilsAPIKey");
898
899
    if ( $content =~ /<Id>(\d+)<\/Id>/ ){
        $protGI = $1;
Sebastien Moretti's avatar
Sebastien Moretti committed
900
901
902
903
904
905
906
    }

    return($protGI);
}

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

909
910
    my $ntGIs  = '';
    my $geneID = '';
Sebastien Moretti's avatar
Sebastien Moretti committed
911
    my $content = fetch("https://eutils.ncbi.nlm.nih.gov/entrez/eutils/elink.fcgi?dbfrom=protein&db=nuccore,gene&id=$protGI&retmode=xml&tool=$eutilsTool&email=$eutilsEmail&api_key=$eutilsAPIKey");
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928

    my @xml  = split("\n", $content);
    my $flag = 0;
    for my $line (@xml){
        if (    $line =~ /<LinkName>protein_nuc[a-z]+<\/LinkName>/ ){ #for nuccleotide and nuccore
            $flag = 1;
        }
        elsif ( $line =~ /<LinkName>protein_gene<\/LinkName>/ ){
            $flag  = 2;
        }
        elsif ( $flag==1 && $line =~ /^.*<Id>(\d+)<\/Id>.*$/ ){
            my $match = $1;
            $ntGIs  .= "$match,$match,";
        }
        elsif ( $flag==2 && $line =~ /^.*<Id>(\d+)<\/Id>.*$/ ){
            my $match = $1;
            $geneID .= "$match,$match,";
929
        }
Sebastien Moretti's avatar
Sebastien Moretti committed
930
931
    }

932
    #Remove redundancy if any
933
    chop $ntGIs; #Remove last ','
934
935
936
937
938
939
    my %hash_NT = split(',', $ntGIs);
    $ntGIs      = join(',',  keys(%hash_NT) );
    chop $geneID;
    my %hash_GE = split(',', $geneID);
    $geneID     = join(',',  keys(%hash_GE) );

940
    return($ntGIs, $geneID);
Sebastien Moretti's avatar
Sebastien Moretti committed
941
942
943
}

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

946
947
    my $chr   = '';
    my ($amont, $aval) = ('', '');
Sebastien Moretti's avatar
Sebastien Moretti committed
948
949
#   my $content = fetch("https://eutils.ncbi.nlm.nih.gov/entrez/eutils/efetch.fcgi?db=gene&id=$geneID&retmode=xml&tool=$eutilsTool&email=$eutilsEmail&api_key=$eutilsAPIKey");
    my $content = fetch("https://eutils.ncbi.nlm.nih.gov/entrez/eutils/esummary.fcgi?db=gene&id=$geneID&retmode=xml&tool=$eutilsTool&email=$eutilsEmail&api_key=$eutilsAPIKey");
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968

    my @xml  = split("\n", $content);
    my $flag = 0;
    GENE_INFO:
    for my $line (@xml){
        if ( $flag==0    && $line =~ /<Item Name="GenomicInfoType" Type="Structure">/ ){
            $flag = 1;
        }
        elsif ( $flag==1 && $line =~ /<Item Name="ChrAccVer" Type="String">([^<]+?)\.?\d*<\/Item>/ ){
            $chr   = $1;
            $flag  = 3;
        }
        elsif ( $flag==3 && $line =~ /<Item Name="ChrStart" Type="Integer">(\d+)<\/Item>/ ){
            $amont = $1;
            $flag  = 4;
        }
        elsif ( $flag==4 && $line =~ /<Item Name="ChrStop" Type="Integer">(\d+)<\/Item>/ ){
            $aval  = $1;
            last GENE_INFO;
969
        }
Sebastien Moretti's avatar
Sebastien Moretti committed
970
    }
971

972
973
    if ( $amont eq '' || $aval eq '' ){
        $amont = '';
974
        $aval  = '';
Sebastien Moretti's avatar
Sebastien Moretti committed
975
    }
976
977
    elsif ( $amont ne '' && $aval ne '' ){
        if ( $amont > $aval ){
978
979
            $amont = $amont + 5000;
            $aval  = $aval  - 5000;
980
981
        }
        else{
982
983
            $amont = $amont - 5000;
            $aval  = $aval  + 5000;
984
        }
Sebastien Moretti's avatar
Sebastien Moretti committed
985
    }
986
    $amont = 1 if ( $amont ne '' && $amont <= 0 );
987
    $aval  = 1 if ( $aval  ne '' && $aval  <= 0 );
Sebastien Moretti's avatar
Sebastien Moretti committed
988

989
    return($chr, $amont, $aval);
Sebastien Moretti's avatar
Sebastien Moretti committed
990
991
992
}

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