forked from dcouvin/getSequenceInfo
-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathgetSequenceInfo.pl
1653 lines (1358 loc) · 49.2 KB
/
getSequenceInfo.pl
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/perl
################################################################################
## "Copyright 2019 Vincent Moco and David Couvin"
## licence GPL-3.0-or-later
## This program is free software: you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by
## the Free Software Foundation, either version 3 of the License, or
## (at your option) any later version.
## This program is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
## GNU General Public License for more details.
## You should have received a copy of the GNU General Public License
## along with this program. If not, see <https://www.gnu.org/licenses/>.
################################################################################
use strict;
use warnings;
my $version = "1.0.1"; # version
#my $number = 50;
# Date and time of the current day (Beginning)
#my ($start_year,$start_month,$start_day, $start_hour,$start_min,$start_sec) = Today_and_Now();
my $start = time();
print "##################################################################\n";
print "## ---> Welcome to $0 (version $version)!\n";
#print "## Start Date (yyyy-mm-dd, hh:min:sec): $start_year-$start_month-$start_day, $start_hour:$start_min:$start_sec\n";
print "##################################################################\n\n";
#BioPerl, Date::Calc, File::Log, have been removed from the @modules
my @modules = qw(
Archive::Tar
Bio::SeqIO
Bio::Species
File::Copy
File::Path
Net::FTP
IO::Uncompress::Gunzip
LWP::Simple
POSIX
);
foreach my $module (@modules) {
if (isModuleInstalled($module)) {
print "$module is.................installed!\n";
}
else {
print "$module is not installed. Please install it and try again.\n";
print "You can reinstall the $0 as shown on the README page or use the following command to install the module:\n";
print "cpan -i -f $module\n";
#system("cpan -i -f $module");
exit 1;
}
}
print "\n";
use Archive::Tar;
use Bio::SeqIO;
use Bio::Species;
#use Date::Calc qw(:all);
use File::Copy qw(cp move);
use File::Path qw(rmtree);
use Net::FTP;
use IO::Uncompress::Gunzip qw(gunzip $GunzipError);
use LWP::Simple qw(get);
use POSIX qw(floor);
#use File::Log;
####################################################################################################
## A Perl script allowing to get sequence information from GenBank, RefSeq or ENA repositories.
##
####################################################################################################
### main program
### parameters
my $directory = "genbank";
my $kingdom = ""; # kingdom of organism
my $releaseDate = "0000-00-00"; # sequences are downloaded from this release date
my $components; # components of the assembly
my $species = ""; # species name
my $getSummaries; # indicates if a new assembly summary is required
my $assemblyLevel = "Complete Genome,Chromosome,Scaffold,Contig"; # assembly level of the genome
my $quantity; # limit number of assemblies to download
my $sequenceID;
my $ftpServor = "ftp.ncbi.nlm.nih.gov";
my $enaFtpServor = "ftp.sra.ebi.ac.uk";
my $fldSep = "/"; # folder seperation change by OS
my @availableKingdoms = (
"archaea",
"bacteria",
"fungi",
"invertebrate",
"plant",
"protozoa",
"vertebrate_mammalian",
"vertebrate_other",
"viral"
); # list of available kingdoms
my $actualOS = "Unix"; # OS of the computer
my $mainFolder; # folder in which the assemblies results are stored
my $assemblyTaxid = ""; # taxid for assembly
my $sraID; # SRA sequence ID
my $assemblyPrjID; # assembly or prj ID
my $log; # log
#my $v
if (@ARGV<1) {
help_user_simple($0);
exit 0;
}
if ($ARGV[0] eq "-help" || $ARGV[0] eq "-h") {
help_user_advance($0);
exit 0;
}
if ($ARGV[0] eq "-version" || $ARGV[0] eq "-v") {
program_version($0);
exit 0;
}
##requirements
for (my $i = 0; $i <= $#ARGV; $i++) {
if ($ARGV[$i]=~/-kingdom/i or $ARGV[$i]=~/-k/i) {
$kingdom = $ARGV[$i+1];
}
elsif ($ARGV[$i]=~/-directory/i or $ARGV[$i]=~/-dir/i) {
$directory = $ARGV[$i+1];
}
elsif ($ARGV[$i]=~/-date/i) {
$releaseDate = $ARGV[$i+1];
}
elsif ($ARGV[$i]=~/-getSummaries/i or $ARGV[$i]=~/-get/i) {
$getSummaries = $ARGV[$i+1];
}
elsif ($ARGV[$i]=~/-species/i or $ARGV[$i]=~/-s/i) {
$species = $ARGV[$i+1];
}
elsif ($ARGV[$i]=~/-level/i or $ARGV[$i]=~/-le/i) {
$assemblyLevel = $ARGV[$i+1];
}
elsif ($ARGV[$i]=~/-components/i or $ARGV[$i]=~/-c/i) {
$components = $ARGV[$i+1];
}
elsif ($ARGV[$i]=~/-quantity/i or $ARGV[$i]=~/-q/i or $ARGV[$i]=~/-number/i or $ARGV[$i]=~/-n/i) {
$quantity = int($ARGV[$i+1]);
}
elsif ($ARGV[$i]=~/-ena/i) {
$sequenceID = $ARGV[$i+1];
}
elsif ($ARGV[$i]=~/-output/i or $ARGV[$i]=~/-o/i) {
$mainFolder = $ARGV[$i+1];
}
elsif ($ARGV[$i]=~/-taxid/i) {
$assemblyTaxid = $ARGV[$i+1];
}
elsif ($ARGV[$i]=~/-fastq/i) {
$sraID = $ARGV[$i+1];
}
elsif ($ARGV[$i]=~/-assembly_or_project/i) {
$assemblyPrjID = $ARGV[$i+1];
}
elsif ($ARGV[$i]=~/-log/i) {
$log = 1;
# $log = File::Log->new({
# debug => 4,
# logFileName => 'myLogFile.log',
# logFileMode => '>',
# dateTimeStamp => 1,
# stderrRedirect => 1,
# defaultFile => 0,
# logFileDateTime => 1,
# appName => 'getSequenceInfo',
# PIDstamp => 0,
# storeExpText => 1,
# msgprepend => '',
# say => 1,
# });
}
}
#define folder separator and OS
if ($^O =~ /MSWin32/) {
$fldSep = "\\";
$actualOS = "MSWin32";
}
#LOG file
if ($log) { open (LOG, "log.txt") or die " error open log.txt $!:"; }
print "Working ...\n";
if ($kingdom eq "viruses") { $kingdom = "viral"; }
if (grep(/^$kingdom$/i, @availableKingdoms)) {
my @patternParametersList;
my @levelList = split /,/, $assemblyLevel;
if ($species ne "") {
my @speciesList = split(/,/, $species);
foreach my $actualSpecies (@speciesList) {
get_assembly_summary_species( $quantity, $releaseDate, $directory,$kingdom, $actualSpecies,
\@levelList, $fldSep, $actualOS, $mainFolder, $assemblyTaxid, $log,
$getSummaries, $components, $ftpServor);
}
}
elsif ($assemblyTaxid ne "") {
my @taxidList = split(/,/, $assemblyTaxid);
foreach my $actualID (@taxidList) {
get_assembly_summary_species($quantity, $releaseDate, $directory,$kingdom,$species,
\@levelList, $fldSep, $actualOS, $mainFolder, $actualID, $log,
$getSummaries, $components, $ftpServor);
}
}
else {
get_assembly_summary_species($quantity, $releaseDate, $directory,$kingdom,$species,
\@levelList, $fldSep, $actualOS, $mainFolder, $assemblyTaxid, $log,
$getSummaries, $components, $ftpServor);
}
}
if ($sequenceID) {
my @sequenceIDList = split /,/, $sequenceID;
foreach my $enaID (@sequenceIDList) {
sequence_ena($enaID, $log);
}
}
if ($sraID) {
my @sraIDList = split /,/, $sraID;
foreach my $sra (@sraIDList) {
download_ena_fastq($enaFtpServor, $sra, $log);
}
}
if ($assemblyPrjID) {
download_assembly_or_project($assemblyPrjID, $ftpServor, $fldSep, $directory, $log);
}
#my ($end_year,$end_month,$end_day, $end_hour,$end_min,$end_sec) = Today_and_Now();
#my ($D_y,$D_m,$D_d, $Dh,$Dm,$Ds) =
# Delta_YMDHMS($start_year,$start_month,$start_day, $start_hour, $start_min, $start_sec,
# $end_year, $end_month, $end_day, $end_hour,$end_min,$end_sec);
#print "End Date: $end_year-$end_month-$end_day, $end_hour:$end_min:$end_sec\n";
print "Thank you for using $0!\n";
#print "Execution time: $D_y years, $D_m months, $D_d days, $Dh:$Dm:$Ds (hours:minutes:seconds)\n";
my $end = time();
my $total = $end - $start;
my $min = $total / 60;
my $hrs = $min / 60;
print "Total time: $total seconds OR $min minutes OR $hrs hours ! \n";
### subroutine
# display global help document
sub help_user_simple {
my $programme = shift @_;
print STDERR "Usage : perl $programme [options] \n";
print "Type perl $programme -version or perl $programme -v to get the current version\n";
print "Type perl $programme -help or perl $programme -h to get full help\n";
}
#------------------------------------------------------------------------------
# display full help document
sub help_user_advance {
print <<HEREDOC;
Name:
$0
Synopsis:
A Perl script allowing to get sequence information from GenBank RefSeq or ENA repositories.
Usage:
perl $0 [options]
examples:
perl $0 -k bacteria -s "Helicobacter pylori" -le "Complete Genome" -date 2019-06-01
perl $0 -k viruses -n 5 -date 2019-06-01
perl $0 -k "bacteria" -taxid 9,24 -n 10 -c plasmid -dir genbank -o Results
perl $0 -ena BN000065
perl $0 -fastq ERR818002
perl $0 -fastq ERR818002,ERR818004
Kingdoms:
archaea
bacteria
fungi
invertebrate
plant
protozoa
vertebrate_mammalian
vertebrate_other
viral
Assembly levels:
"Complete Genome"
Chromosome
Scaffold
Contig
General:
-help or -h displays this help
-version or -v displays the current version of the program
Options ([XXX] represents the expected value):
-directory or -dir [XXX] allows to indicate the NCBI's nucleotide sequences repository (default: $directory)
-get or -getSummaries [XXX] allows to obtain a new assembly summary file in function of given kingdoms (bacteria,fungi,protozoa...)
-k or -kingdom [XXX] allows to indicate kingdom of the organism (see the examples above)
-s or -species [XXX] allows to indicate the species (must be combined with -k option)
-taxid [XXX] allows to indicate a specific taxid (must be combined with -k option)
-assembly_or_project [XXX] allows to indicate a specific assembly accession or bioproject (must be combined with -k option)
-date [XXX] indicates the release date (with format yyyy-mm-dd) from which sequence information are available
-le or -level [XXX] allows to select a specific assembly level (e.g. "Complete Genome")
-o or -output [XXX] allows users to name the output result folder
-n or -number [XXX] allows to limit the total number of assemblies to be downloaded
-c or -components [XXX] allows to select specific components of the assembly (e.g. plasmid, chromosome, ...)
-ena [XXX] allows to download report and fasta file given a ENA sequence ID
-fastq [XXX] allows to download FASTQ sequences from ENA given a run accession (https://ena-docs.readthedocs.io/en/latest/faq/archive-generated-files.html)
-log allows to create a log file
HEREDOC
}
#------------------------------------------------------------------------------
# display program version
sub program_version {
my $programme = shift @_;
print "\n $programme, version : $version\n";
print "\n A perl script to get sequences informations\n";
}
#------------------------------------------------------------------------------
sub get_assembly_summary_species {
my ($quantity, $releaseDate, $directory, $kingdom, $species, $levelList, $fldSep,
$actualOS, $mainFolder, $assemblyTaxid, $log, $getSummaries, $components, $ftpServor) = @_;
# assembly_summary.txt file from NCBI FTP site
#my $assemblySummary = get_summaries($ftpServor, $kingdom, $getSummaries, $directory);
my $assemblySummary = download_summaries($directory, $kingdom, $ftpServor, $fldSep, $getSummaries);
#lineage folder
# my $lineage_file = "/pub/taxonomy/new_taxdump/new_taxdump.tar.gz";
# allow to check old summary download
my $oldKingdom = "";
# start of output file
if ($log) {
print LOG "...Downloading assembly_summary.txt...\n";
}
# if ($actualOS =~ /Unix/i) {
#initialiaze tar manipulation
# my $tar = Archive::Tar->new;
#download taxdump folder
# download_file($ftpServor, $lineage_file);
# $tar->read("new_taxdump.tar.gz");
# $tar->extract_file("rankedlineage.dmp");
# }
#my $kingdomRep = $kingdom."_".$start_year."_".$start_month."_".$start_day;
my $kingdomRep = $kingdom."_folder";
if ($mainFolder) { $kingdomRep = $mainFolder; }
mkdir $kingdomRep unless -d $kingdomRep;
# Repository for request
#my $repositoryAssembly = "assembly_repository_".$assemblyTaxid;
my $repositoryAssembly = "result";
mkdir $repositoryAssembly unless -d $repositoryAssembly;
my $oldAssemblyRep = "." . $fldSep . $kingdomRep . $fldSep . $repositoryAssembly;
if (-d $oldAssemblyRep) { rmtree($oldAssemblyRep) }
# Repository for fna file
my $repositoryFNA = "Assembly";
mkdir $repositoryFNA unless -e $repositoryFNA;
# Repository for genbank file
my $repositoryGenbank = "GenBank";
mkdir $repositoryGenbank unless -e $repositoryGenbank;
# Reposotiry for report file
my $repositoryReport = "Report";
mkdir $repositoryReport unless -e $repositoryReport ;
# Repositories for required components
my %componentsRepHash;
if ($components) {
for my $component (split /,/, $components) {
my $specificRep = $component."_folder";
#my $specificRep = $component."_".$species."_".$kingdom."_".$start_year."_".$start_month."_".$start_day;
mkdir $specificRep unless -d $specificRep;
$componentsRepHash{$component} = $specificRep;
}
}
if ($log) {
print LOG "...Create kingdom and components repository...\n";
}
my %assemblyReportList;
my @assemblyRepresentationList = qw/Full Partial/;
my @levelList = @{$levelList};
my $checkCompleteGenome = grep(/complete genome/i, @levelList);
if ($checkCompleteGenome > 0) {@assemblyRepresentationList = qw/Full/;}
if (-e $assemblySummary) {
# Read file
open (SUM, $assemblySummary) or die " error open assembly_summary.txt $!:";
while(<SUM>) {
chomp;
if ($_ !~ m/^#/) {
my @infoList = split /\t/, $_;
my $foundAssemRep = grep (/$infoList[13]/i, @assemblyRepresentationList);
my $checkLevel = grep(/$infoList[11]/i, @levelList);
if ($foundAssemRep > 0 && $checkLevel > 0) {
my $indexInfo = 0;
my $searchPattern = "";
my $regex = "";
if ($species !~ /^$/) {
$indexInfo = 7;
$searchPattern = $species;
$regex = qr/$searchPattern/i;
}
elsif ($assemblyTaxid !~ /^$/) {
$indexInfo = 5;
$searchPattern = $assemblyTaxid;
$regex = qr/^$searchPattern$/i;
}
if (($infoList[$indexInfo] =~ $regex) or ($kingdom !~ /^$/ && $searchPattern =~ /^$/)) {
my @gcfInfo = split(/\//, $infoList[19]);
my $gcfName = pop(@gcfInfo);
my $realDate = $infoList[14];
$realDate =~ s/\//-/g;
my $genbankFile = $infoList[19] . "/" . $gcfName . "_genomic.gbff.gz";
my $dnaFile = $infoList[19] . "/" . $gcfName . "_genomic.fna.gz";
my $assemblyReport = $infoList[19] . "/" . $gcfName . "_assembly_report.txt";
if ($realDate gt $releaseDate) {
$dnaFile = obtain_file($ftpServor, $dnaFile);
$genbankFile = obtain_file($ftpServor, $genbankFile);
$assemblyReport = obtain_file($ftpServor, $assemblyReport);
download_file($ftpServor, $dnaFile);
download_file($ftpServor, $genbankFile);
download_file($ftpServor, $assemblyReport);
if ($log) {
print LOG "...download FASTA and GenBank report files...\n";
}
# download sequences and check number of "N" characters
my $fileFasta = $gcfName."_genomic.fna.gz";
my $ucpFasta = $gcfName."_genomic.fna";
if (-e $fileFasta) {
gunzip $fileFasta => $ucpFasta or die "gunzip failed: $GunzipError\n";
move($ucpFasta, $repositoryFNA) or die "move failed: $!";
}
if ($log) {
print LOG "...Unzip FASTA file named $fileFasta ...\n";
}
# download genome report
my $fileReport = $gcfName."_assembly_report.txt";
if (-e $fileReport) {
my $fileInformations = $gcfName."_informations.xls";
move($fileReport, $repositoryReport) or die "move failed: $!";
}
# download genbank files
my $fileGenbank = $gcfName."_genomic.gbff.gz";
my $ucpGenbank = $gcfName."_genomic.gbff";
if (-e $fileGenbank) {
gunzip $fileGenbank => $ucpGenbank or die "gunzip failed: $GunzipError\n";
move($ucpGenbank, $repositoryGenbank) or die "move failed: $!";
}
if ($log) {
print LOG "...Unzip GenBank file $fileGenbank ...\n";
}
# association report and fasta
my $fileFastaGenbank = $ucpFasta . "," . $ucpGenbank;
$assemblyReportList{$fileReport} = $fileFastaGenbank;
if ($quantity) { $quantity -= 1; }
}
}
}
}
if (defined $quantity && $quantity == 0) {
$quantity = undef;
last;
}
}
close(SUM) or die "close file error : $!";
if (!keys %assemblyReportList) {
print "##################################################################\n";
print "No results were found for the following query:\n";
print "perl $0 @ARGV\n";
print "##################################################################\n\n";
if ($actualOS =~ /unix/i) { unlink glob "*.dmp *.gz" or die "An error occurred while trying to remove the *.dmp and *.gz files $!:"; }
if (empty_folder($kingdomRep)) { rmdir $kingdomRep or die "fail remove directory $!:"; }
rmdir $repositoryAssembly or die "failed to remove directory $!:";
rmdir $repositoryFNA or die "failed to remove directory $!:";
rmdir $repositoryGenbank or die "failed to remove directory $!:";
rmdir $repositoryReport or die "failed to remove directory $!:";
if ($components) {
for my $componentRep (values %componentsRepHash) {
rmdir $componentRep or die "failed to remove directory $!:";
}
}
if ($log) {
print LOG "...No results were found for the following query: ";
print LOG "perl $0 @ARGV \n";
}
}
else {
if ($log) {
print LOG "...Results were found for the following query: ";
print LOG "perl $0 @ARGV \n";
}
# write summary files
my %componentsSumHash;
my @keysList = keys %assemblyReportList;
my $summary = "summary.xls";
my $htmlSummary = "summary.html";
if ($components) {
for my $component (split /,/, $components) {
my $specificSummary = $component. "_summary.xls";
$componentsSumHash{$component} = $specificSummary;
}
}
my $fileReport = "." . $fldSep. $repositoryReport . $fldSep . $keysList[0];
my @header = ();
open(FILE, $fileReport) or die "error open file : $!";
while(<FILE>) {
chomp;
if($_ =~ /:/){
$_ =~ s/^#*//;
my @ligne = split /:/, $_;
push(@header, $ligne[0]);
}
}
close(FILE) or die "error close file : $!";
open(HEAD, ">", $summary) or die " error open file : $!";
foreach(@header) {
print HEAD $_ . "\t";
}
print HEAD "Pubmed\tNucleScore\tClassification\t";
print HEAD "Country\tHost\tIsolation source\tA percent\t";
print HEAD "T percent\tG percent\tC percent\tN percent\tGC percent\t";
print HEAD "ATGC ratio\tLength\tShape\n";
close(HEAD) or die "error close file : $!";
if ($components) {
foreach my $componentSummary (values %componentsSumHash) {
open(SUM, ">>", $componentSummary) or die "error open file : $!";
print SUM "Id\tAssembly\tDescription\tLength\tStatus\tLevel\t";
print SUM "GC percent\tA percent\tT percent\tG percent\tC percent\n";
close(SUM) or die "error close file : $!";
}
}
for my $file (@keysList) {
my $reportFile = $repositoryReport . $fldSep . $file;
my @fastaGenbank = split /,/, $assemblyReportList{$file};
my $extFasta = $fastaGenbank[0];
my $extGenbank = $fastaGenbank[1];
my $fnaFile = $repositoryFNA . $fldSep . $extFasta;
my $genbankFile = $repositoryGenbank . $fldSep . $extGenbank;
write_assembly($reportFile, $fnaFile, $genbankFile, $summary, $repositoryAssembly,
\%componentsSumHash, $kingdom, $actualOS, \@header, $log);
if ($log) {
print LOG "...Call write_assembly subroutine...\n";
}
}
write_html_summary($summary);
if ($log) {
print LOG "...Call write_html_summary subroutine...\n";
}
if ($components) {
my @componentList = keys %componentsSumHash;
my %componentFastaHash = create_component_sequence_file($fldSep, $repositoryFNA, \@componentList);
if (keys %componentFastaHash && $log) { $log->msg(1,"call create_component_sequence_file subroutine");}
foreach my $component (keys %componentFastaHash) {
move($componentFastaHash{$component}, $componentsRepHash{$component}) or die "move failed: $!";
}
}
move($summary, $repositoryAssembly) or die "move failed: $!";
move($htmlSummary, $repositoryAssembly) or die "move failed: $!";
move($repositoryFNA, $repositoryAssembly . $fldSep . $repositoryFNA) or die "move failed: $!";
move($repositoryGenbank, $repositoryAssembly . $fldSep . $repositoryGenbank) or die "move failed: $!";
move($repositoryReport , $repositoryAssembly . $fldSep . $repositoryReport) or die "move failed: $!";
if ($log) {
print LOG "...move fasta, genbank and report to query folder \n";
}
if ($components) {
for my $component (keys %componentsSumHash) {
move($componentsSumHash{$component}, $componentsRepHash{$component}) or die "move failed: $!";
move($componentsRepHash{$component}, $repositoryAssembly . $fldSep . $componentsRepHash{$component}) or die "move failed: $!"
}
if ($log) {
print LOG "...move component files to folders\n";
}
}
move($repositoryAssembly, $kingdomRep . $fldSep . $repositoryAssembly) or die "move failed: $!";
if ($log) {
print LOG "...move query folder to main folder\n";
}
# if ($actualOS =~ /unix/i) { unlink glob "*.dmp" or die "for file *.dmp $!:"; }
unlink glob "*.gz sequence.txt" or die "$!: An error occurred while trying to remove the *.gz files";
}
}
}
#write general assembly file
sub write_assembly {
my ($reportFile, $fnaFile, $genbankFile, $summary, $repositoryAssembly,
$componentsSumHashRef, $kingdom, $actualOS, $headerRef, $log) = @_;
my %componentsSumHash = %{$componentsSumHashRef};
my @header = @{$headerRef};
my %hashInformations = ();
my $seq = "";
my $genomeName = "";
my $country = "na";
my $GCpercent = -1;
my $taxId = "na";
my $assemblyLine;
my $pubmedId = "na";
my $host = "na";
my $isoSource = "na";
# my $species = "na";
# my $genus = "na";
# my $family = "na";
# my $order = "na";
# my $class = "na";
# my $phylum = "na";
my $shape = "na";
my $geneNumber = "na";
open(REP, "<", $reportFile) or die "error open file $!:";
while (<REP>) {
chomp;
$_ =~ s/^#*//;
if ($_ =~ /assembled-molecule/i) { $assemblyLine = $_; }
if ($_ =~ /:/) {
my @line = split /:/, $_;
if ($line[1]) { $hashInformations{$line[0]} = trim($line[1]); }
}
}
close(REP) or die "error close file $!:";
open(SUM, ">>", $summary) or die "error open file $!:";
foreach my $k(@header) {
if (grep $_ eq $k, keys %hashInformations) {
my $information = $hashInformations{$k};
if ($k =~ /Assembly name/i) { $genomeName = $information; }
if ($information =~ /^\s*$/) {
print SUM "na\t";
} else {
print SUM $information . "\t";
}
} else {
print SUM "na\t";
}
}
close(SUM) or die "error close file $!:";
open(FNA, "<", $fnaFile) or die "Could not open $!:";
while (<FNA>) {
chomp;
if ($_ !~ /^>/) { $seq .= $_; }
}
close(FNA) or die "error close file :$!";
foreach my $summaryKey (keys %hashInformations) {
if ($summaryKey =~ /taxid/i) {
$taxId = $hashInformations{$summaryKey};
}
}
my $classification = get_taxonomic_rank_genbank($genbankFile);
if ($log) {
print LOG "...get taxonomic rank from genbank file\n";
}
$GCpercent = gc_percent($seq);
my ($ade, $thy, $gua, $cyt, $n, $length) = number_nuc_length_seq($fnaFile);
my ($aPercent, $tPercent, $gPercent, $cPercent, $nPercent) = nucleotid_percent($ade, $thy, $gua, $cyt, $n, $length);
my $atgcRatio = atgc_ratio($ade, $thy, $gua, $cyt);
my @percentList = ($aPercent, $tPercent, $gPercent, $cPercent, $nPercent);
my $variance = shift_data_variance(@percentList);
my $nucleScore = nucle_score($variance, $GCpercent, $atgcRatio, $length);
if ($log) {
print LOG "compute GC percent nucleotid percent ATGC ratio NucleScore\n";
}
open(GBFF, "<", $genbankFile) or die "Error open file $!:";
while(<GBFF>) {
chomp;
if ($_ =~ /\/country="(.*)"/) { $country = trim($1); }
if ($_ =~ /PUBMED(.*)/) { $pubmedId = trim($1); }
if ($_ =~ /\/host="(.*)"/) { $host = trim($1); }
if ($_ =~ /\/isolation_source="(.*)"/) { $isoSource = trim($1); }
if ($_ =~ /\(Genes \(total\)\s+::(.*)/) { $geneNumber = trim($1); }
if ($_ =~ /LOCUS.*\s+([a-z]{1,})\s+[a-z]{1,}\s+[0-9]{2,}-[a-z]{1,}-[0-9]{4,}$/i) { $shape = trim($1); }
}
close(GBFF) or die "error close file $!:";
open(SUM, ">>", $summary) or die "error open file $!:";
print SUM $pubmedId . "\t" . $nucleScore . "\t" . $classification ."\t" ;
print SUM $country . "\t" . $host . "\t" . $isoSource . "\t" . $aPercent . "\t" ;
print SUM $tPercent . "\t" . $gPercent . "\t" . $cPercent ."\t" . $nPercent . "\t";
print SUM $GCpercent ."\t". $atgcRatio ."\t". $length . "\t". $shape."\n";
close(SUM) or die "error close file: $!";
if (%componentsSumHash) {
write_assembly_component($fnaFile, $genomeName, \%componentsSumHash, $log);
}
}
#------------------------------------------------------------------------------
# get assembly component
sub write_assembly_component {
my($fnaFile, $genomeName, $componentsSumHashRef, $log) = @_;
my %componentsSumHash = %{$componentsSumHashRef};
my $status = "na";
my $level = "na";
my $gcpercent;
my $tmp_fasta_file = "sequence.txt";
my @desc = ();
# check each sequence from (multi-)fasta file
my ($seq, $inputfile);
if ($log) {
print LOG "...search specific components\n";
}
# extract sequence details
my $seqIO = Bio::SeqIO->new(-format=>'Fasta', -file=>$fnaFile);
while ($seq = $seqIO->next_seq()) {
my $seqID = $seq->id; # ID of sequence
my $seqDesc = $seq->desc; # Description of sequence
my $globalSeq = $seq->seq;
my $seqLength = $seq->length();
open(TSEQ, ">", $tmp_fasta_file) or die "Error open file: $!";
print TSEQ $globalSeq;
close(TSEQ);
my ($ade, $thy, $gua, $cyt, $n, $length) = number_nuc_length_seq($tmp_fasta_file);
my ($aPercent, $tPercent, $gPercent, $cPercent, $nPercent) = nucleotid_percent($ade, $thy, $gua, $cyt, $n, $length);
$gcpercent = gc_percent($globalSeq);
@desc = split /,/, $seqDesc;
if ($desc[1]) { $level = $desc[1]; }
foreach my $component (keys %componentsSumHash) {
if ($desc[0] =~ /$component/) {
$status = $component;
my $info = $seqID . "\t" . $genomeName ."\t" . $seqDesc . "\t" . $seqLength . "\t" . $status . "\t" . $level ."\t";
$info.= $gcpercent."\t". $aPercent ."\t". $tPercent ."\t". $gPercent ."\t". $cPercent . "\n";
add_to_file($componentsSumHash{$component}, $info);
if ($log) {
print LOG "...found component $component \n";
}
}
}
}
}
#------------------------------------------------------------------------------
# download fasta sequence and report on ENA with assembly ID
sub get_fasta_and_report_sequence_ena_assembly {
my($sequenceID) = @_;
my $tmp_file = "fichier.txt";
my @id_list = ();
my $id_chain = "";
my $fasta_file = "";
my $report_file = "";
my $url = "https://www.ebi.ac.uk/ena/data/view/$sequenceID&display=xml";
my $output = get($url);
open(TMP, ">", $tmp_file) or die("could not open $!");
print TMP $output;
close(TMP) or die("could not close $!");
open(TMP, "<", $tmp_file) or die("could not open $!");
while(<TMP>){
if($_ =~ /<CHROMOSOME accession="(.*)">/){
push(@id_list, $1)
}
}
close(TMP) or die("could not close $!");
$id_chain = join(",", @id_list);
$url = "https://www.ebi.ac.uk/ena/data/view/$id_chain&display=fasta";
$output = get($url);
$fasta_file = $sequenceID . ".fasta";
open(FILE, ">", $fasta_file) or die("could not open $!");
print FILE $output;
close(FILE) or die("could not close $!");
$report_file = $sequenceID . "_report.txt";
for my $id (@id_list) {
$url = "https://www.ebi.ac.uk/ena/data/view/$id&display=text&header=true";
$output = get($url);
open(FILE, ">>", $report_file) or die("could not open $!");
print FILE $output;
print FILE "##########################################################################\n\n";
close(FILE) or die("could not close $!");
}
unlink "fichier.txt" or die "error delete file :$!";
return ($fasta_file, $report_file);
}
#------------------------------------------------------------------------------
# download ENA
sub sequence_ena {
my($sequenceID, $log) = @_;
#my $assemblyRep = $sequenceID . "_folder";
my $fastaFile;
my $reportFile;
#if(-d $assemblyRep) { rmtree($assemblyRep); }
#mkdir $assemblyRep;
if ($log) {
print LOG "...ENA sequence downloading ...\n";
}
#if ($log) {$log->msg(1, "Creation of repository: $assemblyRep\n");}
if($sequenceID =~ /^GCA_.*/){
($fastaFile, $reportFile) = get_fasta_and_report_sequence_ena_assembly($sequenceID);
}
else {
($fastaFile, $reportFile) = get_fasta_and_report_sequence_ena_other($sequenceID);
}
if ($log) {
print LOG "...Downloading of ENA FASTA and report files for sequence: $sequenceID\n";
}
#move($fastaFile, $assemblyRep) or die "move failed: $!";
#move($reportFile, $assemblyRep) or die "move failed: $!";
if ($log) {
print LOG "...Move fasta and report files to folder\n";
}
}
#------------------------------------------------------------------------------
# download fasta sequence and report on ENA with ENA ID
sub get_fasta_and_report_sequence_ena_other {
my($sequenceID) = @_;
my $fasta_file = "";
my $report_file = "";
my $url;
my $output;
$url = "https://www.ebi.ac.uk/ena/data/view/$sequenceID&display=fasta";
#if($actualOS eq "MSWin32"){
$output = get($url);
$fasta_file = $sequenceID . ".fasta";
open(FILE, ">", $fasta_file) or die("could not open $!");
print FILE $output;
close(FILE) or die "could not close $!";
#}
#else{
# system("wget $url");
#}
$output = "";
$url = "https://www.ebi.ac.uk/ena/data/view/$sequenceID&display=text&header=true";
#if($actualOS eq "MSWin32"){
$output = get($url); # replace by wget????
$report_file = $sequenceID . "_report.txt";
open(FILE, ">>", $report_file) or die "could not open: $!";
print FILE $output;
close(FILE) or die "could not close $!";
#}
#else{
# system("wget $url");
#}
return ($fasta_file, $report_file);
}
#------------------------------------------------------------------------------
# add information to file
sub add_to_file {
my ($file, $info) = @_;
open(FILE, ">>", $file) or die ("Could not open $!");
print FILE $info;
close(FILE);
}
#------------------------------------------------------------------------------
# return taxonomic rank of species by tax id
sub get_taxonomic_rank {
my($tax_id, $taxonomic_file) = @_;
my $species = "na";
my $genus = "na";
my $family = "na";
my $order = "na";
my $class = "na";
my $phylum = "na";
# my ($species,$genus,$family,$order,$class,$phylum);
my @tmp_array = ($species, $genus, $family, $order, $class, $phylum);
open(TFILE, "<", $taxonomic_file) or
die("Could not open $taxonomic_file: $!");
while(<TFILE>) {
chomp;
my @tax_info = split(/\|/, $_);