ProtoGene.pl 51.3 KB
Newer Older
Sebastien Moretti's avatar
Sebastien Moretti committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env perl

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

use strict;
use warnings;
use diagnostics;
use Env qw(HOME);                          # Use only environmental (shell) HOME variable
use File::Basename;
use File::Copy qw(move);                   # Avoid external 'mv' command usage

use lib '/mnt/common/share/ProtoGene-3.0.1/';    # Local path for ProtoGene's own perl modules
use lib '/mnt/local/lib/tcoffee_perl/';
use Getopt::Long;                          # For options specifications
use File::Which qw(which);                 # Locate external executable programs in the PATH
#use Time::Format qw(%time);               # Use local time for part of pseudo-uniq temp file name
use Mail::Send;                            # Send warnings and errors files by e-mail ==> only if the $userEMail variable is defined

use loci_from_Exonerate;                   # Exonerate parser
#use output_checker;                       # Check output for cds consistancy with query



############## Specific to our server
#L'installer doit creer $HOME/.PACMAN/ and $HOME/.PACMAN/.perllib/
#et mettre les differents modules dans $HOME/.PACMAN/.perllib/
$ENV{'PATH'} .= ':/mnt/local/bin/'; # additional path for executable on the server
##############



my $Version='3.0.1';
my $uct=15;                                            # UpdateCacheThreshold: number of days before update
my $cachedir='/scratch/frt/tcoffee/ProtoGene_Cache';   # Cache directory
##### User settings ####################################
my $userEMail='moretti@igs.cnrs-mrs.fr';               # To receive an e-mail with encountered problems; leave blank to inactive this option
my $webblast_exe=which('webblast.pl') || '';           #
my $blast_prog='blastall';                             # Or wu-blastall for Wu-BLAST; for local blast usage
my $exonerate=which('exonerate-1.0') || '';            #
########################################################
my $blast_exe=which($blast_prog) || '';
my $doc=which('perldoc') || '';
#my $date=$time{'yy-mm-dd_hh\hmm-ss.mmm'}; #Used to get a unique file
my $date=`/usr/bin/env date +%y-%m-%d_%T`; #Used to get a unique file
chomp($date);
$date =~ s/\:/\-/g;

&checkProgramsPresence($webblast_exe,$exonerate); # Check external programs presence in the PATH
$blast_exe =~ s/${blast_prog}$//;

&checkCacheAccessibility($cachedir); # Check cache directory accessibility



##Options management
my ($msa,$species,$db,$athome,$revtrans,$pep,$hideBOJ)=('','All_organisms','refseq_protein',0,0,0,0);
my ($version,$help,${run_name},$Cache,$template,$lim,$tmp)=(0,0,'','update','',0,0);
my $giga=0;
GetOptions("msa|in=s"       => \$msa,        #Input sequences
           "orgm|species=s" => \$species,    #Organism(s) to blast against
           "db|database=s"  => \$db,         #Database to blast against
           "local"          => \$athome,     #Use to specify a local db query, definied in $local_db
           "giga"           => \$giga,       #Use GigaBlaster server
           "revtrans"       => \$revtrans,   #Use to reverse-translate sequences with no match
           "pep"            => \$pep,        #Add the original peptide query beneath the linked nt seq
           "version|v"      => \$version,    #Print version information
           "help|h"         => \$help,       #Print full help message
           "run_name=s"     => \${run_name}, #Use another name, instead of input seq name, for result files
           "cache=s"        => \$Cache,      #Specify what cache parameter
           "hideBOJ"        => \$hideBOJ,    
           "template=s"     => \$template,   #Use a template file
           "lim=i"          => \$lim,        #Limite number of input query sequences
           "tmp"            => \$tmp         #To keep traces of fake intermediate files like fake xml from NCBI, fake aln, ...
           );
$athome=2 if ($giga==1);
if ($version==1){
    print "\n\tPROTOGENE : Bona-Fide Back Translation of Protein Multiple Sequence Alignments\n\tversion   : $Version\n\n";
    exit;
}
if ($help==1){
    if ($doc ne ''){
	system("$doc $0");
    }
    else{
	print STDERR "\n\tperldoc command doesn't seem to be available\n\tto see the documentation in pod format\n\n";
    }
    exit;
}
if ($blast_exe eq '' and $version==0 and $help==0){
    print STDERR "\n\t$blast_prog program is not reachable\n\tIt could not be in your PATH or not installed\n\tIt is required only for local blast searches\n\n";
}

#Cache management
my $cache=&cacheManagement($Cache) || '.';


#Open and check template file
my ($templG,$templP,$templSeq);
($templG,$templP,$templSeq)=&checkTemplate($template) if ($template);


#Short help message
if ($msa eq '' or $species eq '' or $db eq '' or $cache eq ''){
    my $appli=basename($0);
    print STDERR "\n\tCannot open the MSA file in fasta format
\tTry:  $appli --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
\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'
\t         --version to print version information
\t         --help to print a full help message\n\n";
    exit;
}



##Open and Check the fasta file
my $originalMSA=$msa;
my $change=0;
($msa,$change)=&checkFastaFile($msa,$change);
my $fasta_checker=-1;
my (@input_order,@original_names,@original_seq); #Use 3 lists in parallel : original_names, seq, order(1->n)
open(MSA,"$msa") if ( -e "$msa" );
while(<MSA>){
    if ($_ =~ /^>/){
	$fasta_checker++;
	my $name=$_;
	$name =~ s/\r\n//g; #Remove return lines from windows OS '^M'
	chomp($name);
	@original_names=(@original_names,$name);
	@input_order=(@input_order,$fasta_checker);
    }
    elsif ($_ !~ /^>/){
	my $seqq=$_;
	$seqq =~ s/\r\n//g;
	$seqq =~ s/\./-/g; #for msa with '.' as gap
	$seqq =~ s/[^A-Za-z\-\*\n\r]//g; #Remove all the non-gap or non-alphabetic characters from the seq
	chomp($seqq);
        #fasta sequence on 1 line
	if ( ! exists( $original_seq[$fasta_checker] )){
	    @original_seq=(@original_seq,$seqq);
	}
	else {
	    $original_seq[$fasta_checker]=$original_seq[$fasta_checker].$seqq;
	}
    }
}
close MSA;
if ($fasta_checker == -1){
    &failure;
    print STDERR "\tThe MSA file does NOT seem to be a protein fasta format\n\n";
    exit;
}
elsif ($lim >0 and $fasta_checker > $lim){
    &failure;
    print STDERR "\tThe fasta file is too large, try with less than $lim sequences\n\n";
    exit;
}
undef $fasta_checker;



#Start main program with version # of programs and list original queries
print "\n\t   Protogene\t$Version\t$date\n\n";
open(EXONERATEISHERE,"$exonerate --version |");
my $IsExonerateHere=<EXONERATEISHERE>;
close EXONERATEISHERE;
print "\t   $IsExonerateHere\n";
undef $IsExonerateHere;
undef $Version;
for(my $m=0; $m<=$#original_names; $m++){
    print "\t$original_names[$m]\n";
}
$date.="_$$"; #Add PID



# run_name implementation for web server
${originalMSA}=${run_name} if (${run_name} ne '');

unlink("${originalMSA}.cds");
unlink("${originalMSA}.cdsP");
unlink("${originalMSA}.out");
unlink("${originalMSA}.boj");



# Remove old files from the cache directory
&cacheManagement('old','1'); #everytime ProtoGene is running




##Build the sequences, from the alignment, to perform webblast
my $quiet='';
for(my $r=0; $r<=$#input_order; $r++){
    my $right_name=$original_names[$r];
    my $templ_name=$original_names[$r];
    $right_name =~ s/^>//;
    $templ_name =~ s/^([^\s\t]+).*$/$1/;

    open(READY2BLAST,">$cache/${date}_seq2blast.fas${r}");
    my $noGap=$original_seq[$r];
    $noGap =~ s/[\.-]//g; #remove gaps
    print READY2BLAST ">$input_order[$r]\n$noGap\n";
    close READY2BLAST;
    undef $noGap;




    my @multipleequalblasthits;
    if ( exists($templG->{$templ_name}) and $templG->{$templ_name} ne ''){
	@multipleequalblasthits=(@multipleequalblasthits,'My_own_seq'); #To change for ?
	print "\n\n$r done\n\nNucleotidic template for $r:\t$templG->{$templ_name}\n\n**********************************************************************\n\n";
    }
    elsif ( exists($templP->{$templ_name}) and $templP->{$templ_name} ne ''){
	@multipleequalblasthits=(@multipleequalblasthits,$templP->{$templ_name});
	print "\n\n$r done\n\nBlastP template for $r:\t$templP->{$templ_name}\n\n**********************************************************************\n\n";
    }
    else{
	##   --> send them to webblast
	$quiet='-quiet=on ' if ($r>0); #Show webblast parameters only for the first webblast run
	&launchWebblast("$cache/${date}_seq2blast.fas${r}",$quiet,$athome,$db,$species,${blast_exe},"$cache/${date}.blastp${r}");

	##Get the BLASTp hit(s)  acc number
	open(BLASTP,"${cache}/${date}.blastp${r}");
	while(<BLASTP>){
	    @multipleequalblasthits=(@multipleequalblasthits,$1) if ($_ =~ /^>\s*\d+@?\w?\w?\w?__([^\s\|\.]+).*$/); #Warning: double '_'
	}
	close BLASTP;
	unlink("$cache/${date}.blastp${r}","${cache}/${date}_seq2blast.fas${r}") if ($tmp == 0 or exists($multipleequalblasthits[0]) );
	if ( ! exists($multipleequalblasthits[0]) ){
	    print "\n$input_order[$r] ...\tNo blast result found above filter thresholds for $right_name\n\n";
	    &buildFailureOutputFiles($r,'No_BLASTp_Result','Unavailable','');
	    undef $original_seq[$r];
	    undef $original_names[$r];
	    undef $input_order[$r];
	    next;
	}
    }



    #When multiple equal blast hits  ==> use, and add, every hits
    my ($resultPOS,$resultBOJ)=('','');
    my @failureStatus=('');
    my @intronStatus=('');
    for(my $qq=0; $qq<=$#multipleequalblasthits; $qq++){
	print "\n${right_name}  -->  [${multipleequalblasthits[$qq]}]\n";


	my @nt_GIs;
	my $intronStep=0;
	if ( exists($templG->{$templ_name}) and $templG->{$templ_name} ne '' and $templG->{$templ_name} !~ /^My_Seq$/i){
	    &downloadSeq($cache,$date,'','',$templG->{$templ_name});
	    @nt_GIs=$templG->{$templ_name};
	}
	elsif ( exists($templG->{$templ_name}) and $templG->{$templ_name} ne '' and $templG->{$templ_name} =~ /^My_Seq$/i){
	    open(MYSEQ,">$cache/My_Seq-$$.fas");
	    print MYSEQ ">My_Seq-$$ for $templ_name\n".$templSeq->{$templ_name}."\n";
	    close MYSEQ;
	    @nt_GIs="My_Seq-$$";
	}
	else{
	    #Prot ACC -> PUID
	    my $protGI=&blastPAcc2PGI($multipleequalblasthits[$qq]);
	    if ($protGI eq ''){
		print "\tNo protein (prot GI) link found for ${multipleequalblasthits[$qq]} in $right_name\n\n";
		@failureStatus=('PUI_unavailable',${multipleequalblasthits[$qq]});
		next;
	    }
#           print "\t$protGI\n";

	    #PUID -> nt GIs & GeneID
	    my ($ntGIs,$geneID)=&protGI2NTGIs($protGI,$multipleequalblasthits[$qq]);
	    if ($ntGIs eq '' and $geneID eq ''){
		print "\tNo nucleotide (nt GIs) link found for ${multipleequalblasthits[$qq]} in $right_name\n\n";
		@failureStatus=('No_nt_link',${multipleequalblasthits[$qq]});
		next;
	    }
	    print " linked with [$ntGIs $geneID]\n";


	    #Get transcript and contig seq
	    @nt_GIs=split(/,/,$ntGIs);
	    &downloadSeqFromGIs($cache,$date,'','',@nt_GIs);
	    #GeneID -> Chr
	    my @geneIDs=split(/,/,$geneID);
	    while(<@geneIDs>){
		my $geneID=$_;
		my ($chr,$amont,$aval)=&geneID2Chr($geneID,$multipleequalblasthits[$qq]);
		print "\n\tNo gene locus found for ${multipleequalblasthits[$qq]} with $geneID in $right_name\n\n" if ($chr eq '' and $geneID ne '');

		if ($chr ne ''){
		    #Get Chr seq
		    &downloadSeq($cache,$date,$amont,$aval,$chr);
		    $intronStep=1;

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


	#Align Nt seq with our protein query seq
	my ($POS,$BOJ)=&runExonerate($exonerate,$cache,$date,${input_order[$r]},${original_seq[$r]},${right_name},$multipleequalblasthits[$qq],$r,@nt_GIs);

	my ($POSresult,$bestNucleotide)=&prepareResults4CDS($POS,$multipleequalblasthits[$qq],${original_seq[$r]},${right_name});
	$resultPOS.=$POSresult if ($bestNucleotide ne '' and $POSresult ne '' and $resultPOS !~ /_G_$bestNucleotide/);

	@intronStatus=($POS->{0},${multipleequalblasthits[$qq]},'') if ($intronStep==1 and exists($POS->{0}) and $POS->{0} ne '' and $POS->{0} =~ /\:/);
        @intronStatus=($POS->{0},${multipleequalblasthits[$qq]},$bestNucleotide) if ($intronStep==0 and ($bestNucleotide =~ /^N[CTWZG]_/ or $bestNucleotide =~ /^AC_/));

	my ($intronLess,$nameLess)=('','');
	$intronLess=$POS->{0} if (%$BOJ eq 0 and exists($POS->{0}) and $POS->{0} ne '');
	$nameLess=$bestNucleotide if (%$BOJ eq 0 and $intronStep==0 and ($bestNucleotide =~ /^N[CTWZG]_/ or $bestNucleotide =~ /^AC_/));
	my ($BOJresult,$bestGenomic)=&prepareResults4BOJ($BOJ,$multipleequalblasthits[$qq],${original_seq[$r]},${right_name},$intronLess,$nameLess);
	$resultBOJ.=$BOJresult if ($bestGenomic ne '' and $BOJresult ne '' and $resultBOJ !~ /_G_$bestGenomic[ \-]/);
#	print " $intronStep $POS->{0} [@intronStatus] {$BOJresult} $bestNucleotide - $bestGenomic \t $BOJ->{0}\n";
    }


    if ($resultPOS eq ''){
	&buildFailureOutputFiles($r,$failureStatus[1],$failureStatus[0],'') if ($failureStatus[0] ne '');
	&buildFailureOutputFiles($r,$multipleequalblasthits[0],'Failed_Aln','') if ($failureStatus[0] eq '');
	next;
    }
    elsif ($resultBOJ eq ''){
	if ($failureStatus[0] eq 'PUI_unavailable' or $failureStatus[0] eq 'No_nt_link'){
	    &buildFailureBOJOutputFile($failureStatus[1],$failureStatus[0],${right_name},${original_seq[$r]});
	}
	elsif ($failureStatus[0] eq '' and $intronStatus[0] ne ''){
	    &buildIntronlessBOJOutputFile($intronStatus[1],$intronStatus[0],$intronStatus[2],${right_name},${original_seq[$r]});
	}
	else{
	    &buildFailureBOJOutputFile($multipleequalblasthits[0],'Unavailable',${right_name},${original_seq[$r]});
	}
	&createCDSOutputFile($resultPOS,${original_seq[$r]},${right_name});
    }
    else {
	&createCDSOutputFile($resultPOS,${original_seq[$r]},${right_name});
	&createBOJOutputFile($resultBOJ,${original_seq[$r]});
    }


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


&checkAndCleanStderrFiles("$cache/${date}_ExonerateError") if ( -e "$cache/${date}_ExonerateError" );
&checkOutputFiles();
unlink("$msa") if ($change==1);
my @tmpFiles=glob($cache."/${date}*");
if ( exists($tmpFiles[0]) ){
    mkdir("$cache/${date}_TMP");
    move("$_","$cache/${date}_TMP") while(<@tmpFiles>);
}


#Ouput Checker


#STDOUT Log output for our server
if ( -s "${originalMSA}.cds" or -s "${originalMSA}.out"){
    print "\n\nTERMINATION STATUS: SUCCESS\n";
    print "OUTPUT RESULTS\n";
    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= 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" and -s "${originalMSA}.cds" and $hideBOJ==0);
}
else{
    &failure;
    exit;
}

exit;


=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

=item empty: empty the whole cache directory $HOME/.ProtoGene/

=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

=item version 3.0.1

=item on Sept 26th, 2006

=back

=head1 AUTHORS

=over 8

=item Sebastien MORETTI

=item Sebastien.Moretti@igs.cnrs-mrs.fr

=item Frederic REINIER

=item Frederic.Reinier@igs.cnrs-mrs.fr

=item Lab. Information Genomique et Structurale - IGS

=item CNRS - Life Sciences

=item Marseille, France

=item http://www.igs.cnrs-mrs.fr/

=back

=cut


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

#Failure declaration
    sub failure{
	print STDERR "\n\nFATAL\n\nTERMINATION STATUS: FAILURE\n\n";
    }

#Check external programs presence in the PATH
sub checkProgramsPresence{
    my ($webblast_exe,$exonerate)=@_;

    if ($webblast_exe eq ''){
	&failure;
	print STDERR "\twebblast.pl program is not reachable\n\tIt could not be in your PATH or not installed\n\n";
	exit;
    }
    if ($exonerate eq ''){
	&failure;
	print STDERR "\texonerate program is not reachable\n\tIt could not be in your PATH or not installed\n\n";
	exit;
    }
}

#Check cache directory accessibility: Test and change rights, if needs, of the $HOME/.ProtoGene/ cache directory
sub checkCacheAccessibility{
    my ($cachedir)=@_;

    if ( -d "$cachedir/" and -w "$cachedir/" and -x "$cachedir/" and -r "$cachedir/" ){
    }
    elsif ( -d "$cachedir/" ){
	if ( -o "$cachedir/" ){
	    chmod 0754, "$cachedir/";
	}
	else{
	    print STDERR "\n\t** Warning ** :\n\tPermissions do NOT seem to be valide for the current cache directory\n\n";
	}
    }
    else{
	mkdir "$cachedir/";
	if ( -o "$cachedir/" ){
	    chmod 0754, "$cachedir/"; #0754 est en octal, donc 754 ou '0754' ne sont pas bons !
	}
	else{
	    print STDERR "\n\t** Warning ** :\n\tPermissions do NOT seem to be valide for the current cache directory\n\n";
	}
    }
}

#Cache Management
sub cacheManagement{
    my ($Cache,$inScript)=@_;
    $inScript=0 if ( !defined $inScript);

    if ($Cache eq 'empty'){
	my @temp_files=glob($cachedir.'/*.fas');
	if ( exists ($temp_files[0]) ){
	    unlink $_ while(<@temp_files>);
	}
	@temp_files=glob($cachedir.'/*_ExonerateError');
	if ( exists ($temp_files[0]) ){
	    unlink $_ while(<@temp_files>);
	}
	unlink("$cachedir/webblast.log","$cachedir/web_tempo.result","$cachedir/debug.tempo");
	print "\n\tcache directory [$cachedir] is empty\n\n";
	exit;
    }
    elsif ($Cache eq 'old'){
	my @temp_files=glob($cachedir.'/*.fas');
	my @tempFiles=grep { -M $_ > $uct } @temp_files; #Sort list only with $uct days old files
	if ( exists ($tempFiles[0]) ){
	    unlink $_ while(<@tempFiles>);
	}
	print "\n\tcache directory [$cachedir] is empty of its old files\n\n" if ($inScript==0);
	exit if ($inScript==0);
    }
    elsif ($Cache eq 'update' or $Cache eq 'use'){
	$cache=$cachedir; #Limit cache files to less than $uct days old ones for 'update'
    }
    elsif ($Cache eq 'none'){
    }
    elsif ( -d $Cache ){
	die "\n\tPACMAN cannot access to your directory\n\n" if ( ! -x $Cache );
	die "\n\tPACMAN cannot write into your directory\n\n" if ( ! -w $Cache );
	die "\n\tPACMAN cannot read into your directory\n\n" if ( ! -r $Cache );
	$cache=$Cache;
    }
    else {
	die "\n\tWrong cache argument, or your cache folder doesn't seem to exist\n\n";
    }

    return($cache);
}

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


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

#Check input aln
sub checkFastaFile{
    my ($msa,$change)=@_;

    if ( -e "$msa"){
    #Convert no fasta format to fasta with seq_reformat if available
	my $seqreformat=which('t_coffeeX') || ''; #desactive tant que t_coffee seq_reformat pose prob
	if ($seqreformat ne ''){
	    my @formatType=`$seqreformat -other_pg seq_reformat -in $msa -print_format`;
	    my $format='';
	    while(<@formatType>){
		if ($_ =~ /FORMAT:/){
		    $format=$_;
		    chomp($format);
		    last;
		}
	    }
	    if ($format ne '' and $format !~ /FORMAT:fasta_/){
		system("$seqreformat -other_pg seq_reformat -in $msa -output fasta_aln -out=${msa}.007") if ($format =~ /_aln *$/);
		system("$seqreformat -other_pg seq_reformat -in $msa -output fasta_seq -out=${msa}.007") if ($format =~ /_seq *$/);
		$msa.='.007';
		$change=1;
	    }
	}

    }
    else {
	&failure;
	print STDERR "\tThe file \'$msa\' doesn't not seem to be reachable\n\n";
	exit;
    }

    return($msa,$change);
}

#Prepare Fasta Header of the query name to incorporate our annotations
sub fastaHeaders4ProtoGene{
    my ($QueryName)=@_;

    $QueryName =~ s/  +/ /g;
    my ($cqacc,$cqdesc)=($QueryName,$QueryName);
    $cqacc =~ s/^ *([^ ]*) .*$/$1/;
    $cqacc =~ s/[\s\t]*$//g;
    $cqacc=$cqacc.'_G_@@';
    $cqdesc =~ s/^ *[^ ]* *(.*)$/$1/;
    $cqdesc =~ s/^[\| \.]*//;
    $cqdesc =~ s/[\|\. ]*$//;

    $QueryName=$cqacc.$cqdesc;
    return($QueryName);
}

#Prepare Fasta Header to put it on the fasta header of the result outputs
sub getFastaHeaderAnnot{
    my ($bestTarget)=@_;

    #Get annotation from nucleotide file header
    open(BEST,"$cache/${bestTarget}.fas");
    my $annot=<BEST> || '';
    close BEST;
    chomp($annot);
    $annot =~ s/^ *[^ ]* //;
    $annot =~ s/[\. ]*$//;
    $annot =~ s/^ *//;
    $annot =~ s/  +/ /g;

    return($annot);
}

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


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

#Direct Reverse translation
sub reverse_trad{
    my ($aa)=@_;

    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

    my $triplet='nnn';
    while(my ($x,$y) =each(%reverse_code)){
	if (uc($aa) eq $x){
	    $triplet=$y;
	    last;
	}
    }

    return($triplet);
}

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


####################### webblast #######################
sub launchWebblast{
    my ($infile,$quiet,$whatBlast,$db,$species,${blast_exe},$outfile)=@_;
    my $blast_at='';

    $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);

#    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";

    system("$webblast_exe -program=blastp ${blast_at} -infile=$infile -matrix=BLOSUM62 -evalue=0.05 -method=geneid -filter=Off -organism=$species -identity=100 -cover=100 $quiet -outfile=$outfile");


    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 and $db ne 'nr');
	print STDERR "run BLAST.. again, with decreased thresholds, because there was no acceptable hit against $db\n" if ($whatBlast == 1 or $db eq 'nr');
	$blast_at =~ s/-database=[^\s]*/-database=nr/ if ($whatBlast != 1);
	system("$webblast_exe -program=blastp ${blast_at} -infile=$infile -matrix=BLOSUM62 -evalue=0.05 -method=geneid -filter=Off -organism=$species -identity=95 -cover=95 $quiet -outfile=$outfile");
    }

    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");
}


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


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

#Prot ACC -> PUID
sub blastPAcc2PGI{
    my ($blastHit)=@_;

    my $protGI='';
    my $count=0;
    for(my $rep=0;$rep <= 4; $rep++){
	$count++;
	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'");
	open(GIP,"$cache/${date}_${blastHit}protGi.tmp");
	while(<GIP>){
	    if ($_ =~ /^.*\<Id\>(\d+)\<\/Id\>.*$/){
		$protGI=$1;
		last;		#OK if only one PUID
	    }
	}
	close GIP;
	$rep=$rep-15 if ( -z "$cache/${date}_${blastHit}protGi.tmp" and $count==1);
	last if ($protGI =~ /^\d+$/);
    }
    unlink("$cache/${date}_${blastHit}protGi.tmp") if ($tmp == 0 or $protGI ne '');

    return($protGI);
}

#PUID -> nt GIs
sub protGI2NTGIs{
    my ($protGI,$blastHit)=@_;

    my $ntGIs='';
    my $geneID='';
    my $count=0;
    for(my $rep=0;$rep <= 4; $rep++){
	$count++;
        #nt GIs
	system("wget -q -O $cache/${date}_${blastHit}nucleo.tmp 'http://eutils.ncbi.nlm.nih.gov/entrez/eutils/elink.fcgi?dbfrom=protein&db=nucleotide,gene&id=$protGI&retmode=xml'");
	open(GIN,"$cache/${date}_${blastHit}nucleo.tmp");
	my $flag=0;
	while(<GIN>){
	    if ($_ =~ /\<LinkName\>protein_nucleotide\<\/LinkName\>/){
		$flag=1;
	    }
	    elsif ($_ =~ /\<LinkName\>protein_gene\<\/LinkName\>/){
		$flag=2;
	    }
	    elsif ($flag==1 and $_ =~ /^.*\<Id\>(\d+)\<\/Id\>.*$/){
		$ntGIs.=",$1" if ($ntGIs ne '');
		$ntGIs=$1 if ($ntGIs eq '');
	    }
	    elsif ($flag==2 and $_ =~ /^.*\<Id\>(\d+)\<\/Id\>.*$/){
		$geneID.=",$1" if ($geneID ne '');
		$geneID=$1 if ($geneID eq '');
	    }
	}
	close GIN;
	$rep=$rep-15 if ( -z "$cache/${date}_${blastHit}nucleo.tmp" and $count==1);
	last if ($ntGIs ne '' or $geneID ne '');
    }
    unlink("$cache/${date}_${blastHit}nucleo.tmp") if ($tmp == 0 or ($ntGIs ne '' or $geneID ne ''));

    return($ntGIs,$geneID);
}

sub geneID2Chr{
    my ($geneID,$blastHit)=@_;

    my $chr='';
    my ($amont,$aval)=('','');
    my $count=0;
    for(my $rep=0;$rep <= 8; $rep++){
	$count++;
        #Gene Acc
	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'");
	open(GACC,"$cache/${date}_${blastHit}gene.tmp");
	my $flag=0;
	while(<GACC>){
	    if ($_ =~ /\<ERROR\>Empty id list \- nothing todo\<\/ERROR\>/ and $flag==0){
		$rep=$rep-15 if ($count==1);
	    }
	    if ($_ =~ /\<Entrezgene_locus\>/ and $flag==0){
		$flag=1;
	    }
	    elsif ($_ =~ /\<Gene-commentary_type value=\"genomic\"\>/ and $flag==1){
		$flag=2;
	    }
	    elsif ($_ =~ /\<Gene-commentary_type value=/ and $flag==2){
		last;
	    }
	    elsif ($_ =~ /\<Gene-commentary_accession\>([\w\_\-\.]+)\<\/Gene-commentary_accession\>/ and $flag==2){
		$chr=$1;
		$flag=3;
	    }
	    elsif ($_ =~ /\<Seq-interval_from\>(\d+)\<\/Seq-interval_from\>/ and $flag==3){
		$amont=$1;
		$flag=4;
	    }
	    elsif ($_ =~ /\<Seq-interval_to\>(\d+)\<\/Seq-interval_to\>/ and $flag==4){
		$aval=$1;
		last;
	    }
	}
	close GACC;
	$rep=$rep-15 if ( -z "$cache/${date}_${blastHit}gene.tmp" and $count==1);
	last if ($chr ne '' and $amont =~ /^\d+$/ and $aval =~ /^\d+$/);
    }
    unlink("$cache/${date}_${blastHit}gene.tmp") if ($tmp == 0 or $chr ne '');
    if ($amont eq '' or $aval eq ''){
	$amont='';
	$aval='';
    }
    elsif ($amont ne '' and $aval ne ''){
	if ($amont > $aval){
	    $amont=$amont+5000;
	    $aval=$aval-5000;
	}
	else{
	    $amont=$amont-5000;
	    $aval=$aval+5000;
	}
    }
    $amont=1 if ($amont ne '' and $amont <= 0);
    $aval=1 if ($aval ne '' and $aval <= 0);

    return($chr,$amont,$aval);
}

sub downloadSeqFromGIs{
    my ($cache,$date,$amont,$aval,@acc)=@_;

    for(my $a=0; $a<=$#acc; $a++){
	my $whatNumber=0;
	if ($amont =~ /^\d+$/ and $aval =~ /^\d+$/){
	    for(my $rep=0;$rep <= 4; $rep++){
		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'") if ( ! -e "$cache/${acc[$a]}-${amont}.fas" or -z "$cache/${acc[$a]}-${amont}.fas" or $Cache eq 'none' or ($Cache eq 'update' and -M "$cache/${acc[$a]}-${amont}.fas" > $uct ));
		open(CIBLE,"$cache/${acc[$a]}-${amont}.fas");
		my $counter=0;
		my $lines=0;
		while(<CIBLE>){
		    $lines++ if ($_ !~ /^>/);
		    $counter=$counter+2 if ($counter==1 and $_ !~ /^\w/ and $lines==1 and $_ !~ /^>/);
		    $counter++ if ($_ =~ /^>/);
		    $counter=$counter+2 if ($_ !~ /^>/ and ($_ =~ /Error:/ or $_ =~ /[<>]/) );
#		    last if ($_ !~ /^>/ and $counter==1 and $_ =~ /^\w/);
		}
		close CIBLE;
		$whatNumber++;
		last if ($whatNumber==20);
		if ($counter != 1){
		    $rep=$rep-1;
		    unlink("$cache/${acc[$a]}-${amont}.fas");
		}
	    }
	}
	else {
	    for(my $rep=0;$rep <= 4; $rep++){
		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'") if ( ! -e "$cache/${acc[$a]}.fas" or -z "$cache/${acc[$a]}.fas" or $Cache eq 'none' or ($Cache eq 'update' and -M "$cache/${acc[$a]}.fas" > $uct ));
		open(CIBLE,"$cache/${acc[$a]}.fas");
		my $counter=0;
		my $lines=0;
		while(<CIBLE>){
		    $lines++ if ($_ !~ /^>/);
		    $counter=$counter+2 if ($counter==1 and $_ !~ /^\w/ and $lines==1 and $_ !~ /^>/);
		    $counter++ if ($_ =~ /^>/);
		    $counter=$counter+2 if ($_ !~ /^>/ and ($_ =~ /Error:/ or $_ =~ /[<>]/) );
		}
		close CIBLE;
		$whatNumber++;
		last if ($whatNumber==20);
		if ($counter != 1){
		    $rep=$rep-1;
		    unlink("$cache/${acc[$a]}.fas");
		}
	    }
	}
    }
}

sub downloadSeq{
    my ($cache,$date,$amont,$aval,@acc)=@_;

    my $cp=0;
    my $from=$amont;
    my $to=$aval;
    for(my $a=0; $a<=$#acc; $a++){
	my $pacc2puid=$acc[$a];
	if ($pacc2puid !~ /^[NAX][CGTWZM]_/){
            #pacc = primary acc NOT prot acc !   #265666 -> S55551
	    system("wget -q -O $cache/${date}_${acc[$a]}.gui 'http://eutils.ncbi.nlm.nih.gov/entrez/eutils/esearch.fcgi?&db=nucleotide&term=${pacc2puid}[pacc]'");
	    open(GUI,"$cache/${date}_${acc[$a]}.gui");
	    while(<GUI>){
		if ($_ =~ /\<Id\>(\d+)\<\/Id\>/){
		    $pacc2puid=$1;
		    last;
		}
	    }
	    close GUI;
	    unlink("$cache/${date}_${acc[$a]}.gui") if ($tmp == 0 or $pacc2puid =~ /^\d+$/);
	}
	my $whatNumber=0;
	if ($amont =~ /^\d+$/ and $aval =~ /^\d+$/){
	    for(my $rep=0;$rep <= 4; $rep++){
		system("wget -q -O $cache/${acc[$a]}:${from}-${to}.fas 'http://eutils.ncbi.nlm.nih.gov/entrez/eutils/efetch.fcgi?db=nucleotide&id=${pacc2puid}&rettype=fasta&retmode=text&from=$amont&to=$aval'") if ( ! -e "$cache/${acc[$a]}:${from}-${to}.fas" or -z "$cache/${acc[$a]}:${from}-${to}.fas" or $Cache eq 'none' or ($Cache eq 'update' and -M "$cache/${acc[$a]}:${from}-${to}.fas" > $uct ));
		open(CIBLE,"$cache/${acc[$a]}:${amont}-${aval}.fas");
		my $counter=0;
		my $lines=0;
		while(<CIBLE>){
		    $lines++ if ($_ !~ /^>/);
		    $counter=$counter+2 if ($counter==1 and $_ !~ /^\w/ and $lines==1 and $_ !~ /^>/);
		    $counter++ if ($_ =~ /^>/);
		    $counter=$counter+2 if ($_ !~ /^>/ and ($_ =~ /Error:/ or $_ =~ /[<>]/) );
		}
		close CIBLE;
		$whatNumber++;
		last if ($whatNumber==20);
		if ($counter != 1){
		    $rep=$rep-1;
		    unlink("$cache/${acc[$a]}:${amont}-${aval}.fas");
		}
	    }
	}
	else {
	    for(my $rep=0;$rep <= 4; $rep++){
		system("wget -q -O $cache/${acc[$a]}.fas 'http://eutils.ncbi.nlm.nih.gov/entrez/eutils/efetch.fcgi?db=nucleotide&id=${pacc2puid}&rettype=fasta&retmode=text'") if ( ! -e "$cache/${acc[$a]}.fas" or -z "$cache/${acc[$a]}.fas" or $Cache eq 'none' or ($Cache eq 'update' and -M "$cache/${acc[$a]}.fas" > $uct ));
		open(CIBLE,"$cache/${acc[$a]}.fas");
		my $counter=0;
		my $lines=0;
		while(<CIBLE>){
		    $lines++ if ($_ !~ /^>/);
		    $counter=$counter+2 if ($counter==1 and $_ !~ /^\w/ and $lines==1 and $_ !~ /^>/);
		    $counter++ if ($_ =~ /^>/);
		    $counter=$counter+2 if ($_ !~ /^>/ and ($_ =~ /Error:/ or $_ =~ /[<>]/) );
		}
		close CIBLE;
		$whatNumber++;
		last if ($whatNumber==20);
		if ($counter != 1){
		    $rep=$rep-1;
		    unlink("$cache/${acc[$a]}.fas");
		}
	    }
	}