-
Notifications
You must be signed in to change notification settings - Fork 2
/
mQC.pl
2999 lines (2577 loc) · 116 KB
/
mQC.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/env perl
$|=1;
#####################################
## mQC (MappingQC): ribosome profiling mapping quality control tool
## Author: S. Verbruggen
## Supervised by: G. Menschaert
##
## Copyright (C) 2017 S. Verbruggen & G. Menschaert
##
## 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 <http://www.gnu.org/licenses/>.
##
## For more (contact) information visit https://github.com/Biobix/mQC
#####################################
use strict;
use warnings;
use DBI;
use Data::Dumper;
use Getopt::Long;
use v5.10;
use Parallel::ForkManager;
use Cwd;
##############
##Command-line
##############
# nohup perl ./mQC.pl --experiment_name test --samfile untreat.sam --cores 20 --species mouse --ens_db ENS_mmu_86.db --ens_v 86 --offset plastid > nohup_mappingqc.txt &
my($work_dir,$exp_name,$sam,$original_bam,$cores,$species,$version,$tmpfolder,$unique,$mapper,$maxmultimap,$ens_db,$offset_option,$offset_file,$cst_3prime_offset,$min_cst_3prime_offset,$max_cst_3prime_offset,$bam,$tool_dir,$plotrpftool,$min_length_plastid,$max_length_plastid,$min_length_gd,$max_length_gd,$outfolder,$outhtml,$outzip,$galaxy,$galaxysam,$galaxytest,$comp_logo);
my $help;
GetOptions(
"work_dir:s" => \$work_dir, # The working directory Optional argument (default: CWD)
"experiment_name=s" => \$exp_name, # The experiment name Mandatory argument
"samfile=s"=>\$sam, # The samfile/bamfile to do the analysis on Mandatory argument
"cores=i"=>\$cores, # The amount of cores to use Optional argument (default: 5)
"species=s"=>\$species, # The species Mandatory argument (mouse, human, fruitfly, zebrafish, yeast, SL1344, c.elegans, MYC_ABS_ATCC_19977)
"ens_v=i"=>\$version, # The Ensembl version Mandatory argument
"tmp:s"=>\$tmpfolder, # The tmp folder Optional argument (default: CWD/tmp)
"unique:s"=>\$unique, # Consider only unique reads (Y/N) Optional argument (default: Y)
"mapper:s"=>\$mapper, # The mapper used to generate the SAM file Optional argument (default: STAR)
"maxmultimap=i"=>\$maxmultimap, # The maximum multimapped positions for parsing Optional argument (default: 16)
"ens_db=s"=>\$ens_db, # The Ensembl db for annotation Mandatory argument
#If this argument is set to 'get', ENS_db will be downloaded first
"offset:s" =>\$offset_option, # The offset source for parsing alignments Optional argument (default: standard)
"offset_file:s" =>\$offset_file, # The offsets input file Mandatory if offset option equals 'from_file'
"plastid_bam:s" =>\$bam, # The corresponding bam file Optional and only used for plastid when offset option equals 'plastid'
# This file will be needed for plastid offset generation. Default bam file will be 'convert' and the bam file will be converted out of the sam file
"min_length_plastid=i" =>\$min_length_plastid, # Minimum RPF length for plastid offset generation Optional argument (default: 22), only used when offset option equals 'plastid'
"max_length_plastid=i" =>\$max_length_plastid, # Maximum RPF length for plastid offset gene Optional argument (default: 34), only used when offset option equals 'plastid'
"cst_3prime_offset=i" =>\$cst_3prime_offset, # The value of the constant 3' offset (only used with cst_3prime offset option) Optional argument (default: 15)
"min_cst_3prime_offset=i" =>\$min_cst_3prime_offset, # Minimum RPF length with cst 3' offset Optional argument (default: 22)
"max_cst_3prime_offset=i" =>\$max_cst_3prime_offset, # Maximum RPF length with cst 3' offset Optional argument (default: 40)
"min_length_gd=i" =>\$min_length_gd, # Minimum RPF length for gene distribution and metagenic classification Optional argument (default: 26)
"max_length_gd=i" =>\$max_length_gd, # Maximum RPF length for gene distribution and metagenic classification Optional argument (default: 34)
"tool_dir:s" => \$tool_dir, # The directory with all necessary tools Optional argument (default: conda default installation location)
"plotrpftool:s" => \$plotrpftool, # The module that will be used for plotting the RPF-phase figure
#grouped2D: use Seaborn to plot a grouped 2D bar chart (default)
#pyplot3D: use mplot3d to plot a 3D bar chart (Suffers sometimes from Escher effects)
#mayavi: use the mayavi package to plot a 3D bar chart (only on systems with graphics cards)
"outfolder:s" => \$outfolder, # The folder for storing output figures Optional argument (default: workdir/mQC_output)
"outhtml:s" => \$outhtml, # The output HTML file Optional argument (default: workdir/mQC_exp_name.html)
"outzip:s" => \$outzip, # The output zip file Optional argument (default: workdir/mQC_exp_name.zip)
"galaxy:s" => \$galaxy, # Run through galaxy or not (Y/N) Optional argument (default: N)
"galaxysam:s" => \$galaxysam, # Parameter needed for galaxy version Optional argument (default: Y)
"galaxytest:s" => \$galaxytest, # Parameter needed for galaxy version (to run tests) Optional argument (default: N)
"comp_logo:s" => \$comp_logo,
"help" => \$help # Help text option
);
if ($help){
print_help_text();
exit;
}
###########################################################################
#Check all input variable and/or get default values and set extra variables
###########################################################################
my $CWD = getcwd;
# comment on these
if ($work_dir){
print "Working directory : $work_dir\n";
} else {
$work_dir = $CWD;
print "Working directory : $work_dir\n";
}
my $TMP = ($ENV{'TMP'}) ? $ENV{'TMP'} : ($tmpfolder) ? $tmpfolder : "$CWD/tmp"; # (1) get the TMP environment variable, (2) get the $tmpfolder variable, (3) get current_working_dir/tmp
print "The following tmpfolder is used : $TMP\n";
if ($galaxy){
if ($galaxy ne 'N' && $galaxy ne 'Y'){
print "ERROR: galaxy option should be Y or N!\n";
die;
}
if ($galaxysam ne 'N' && $galaxysam ne 'Y'){
print "ERROR: galaxysam option should be Y or N!\n";
die;
}
if ($galaxytest ne 'N' && $galaxytest ne 'Y'){
print "ERROR: galaxytest option should be Y or N!\n";
die;
} elsif (uc($species) ne "HUMAN"&& uc($species) ne "MOUSE" && uc($species) ne "FRUITFLY" && uc($species) ne "ZEBRAFISH" && uc($species) ne "C.ELEGANS") {
print "ERROR: galaxy test can only run on human, mouse, fruitfly, c.elegans or zebrafish!\n";
die;
}
} else {
$galaxy = 'N';
$galaxysam = 'Y';
$galaxytest = 'N';
}
#Check if tmpfolder exists, if not create it...
if (!-e "$TMP") {
system ("mkdir ". $TMP);
}
if ($exp_name){
print "The experiment name : $exp_name\n";
} else {
print_help_text();
print "\n\n\n";
die "ERROR: do not forget the experiment name!\n";
}
#Check the extension of the input file
my $ext = "";
if($sam =~ m/\.([^.]+)$/){
$ext = $1;
if ($ext eq "sam"){
if ($sam){
print "the input sam file : $sam\n";
} else {
die "\nDon't forget to pass the bam/sam file!\n\n";
}
} elsif ($ext eq "bam"){
if ($sam){
print "the input bam file : $sam\n";
#Convert input bam file to sam format
system("samtools view -h ".$sam." > ".$TMP."/input.sam");
$original_bam = $sam;
$sam = $TMP."/input.sam";
} else {
die "\nDon't forget to pass the bam/sam file!\n\n";
}
} elsif ($galaxy eq 'Y' && $galaxysam eq 'Y'){
$ext="sam";
print "the input sam file : $sam\n";
} elsif ($galaxy eq 'Y' && $galaxysam eq 'N'){
$ext="bam";
print "the input bam file : $sam\n";
system("samtools view -h ".$sam." > ".$TMP."/input.sam");
$original_bam = $sam;
$sam = $TMP."/input.sam";
} else {
die "The input file should be in bam/sam format!\n\n";
}
} else {
die "Could not match the extension of the input data file $sam !\n\n";
}
if ($species){
if (uc($species) eq "HUMAN" || uc($species) eq "MOUSE" || uc($species) eq "FRUITFLY" || uc($species) eq "ZEBRAFISH" || uc($species) eq "YEAST" || uc($species) eq "SL1344" || uc($species) eq "MYC_ABS_ATCC_19977" || uc($species) eq "C.ELEGANS"){
print "Species : $species\n";
} else {
die "ERROR: species should be 'human', 'mouse', 'zebrafish', 'yeast', 'SL1344', 'MYC_ABS_ATCC_19977', 'c.elegans' or 'fruifly'!";
}
} else {
die "Do not forget the species argument!";
}
if ($unique){
if ($unique ne "Y" && $unique ne "N"){
die "ERROR: unique option should be 'Y' or 'N'!";
}
print "Consider unique reads: : $unique\n";
} else {
$unique = "Y";
print "Consider unique reads: : $unique\n";
}
if ($mapper){
if ($mapper ne "STAR" && $mapper ne "TopHat2" && $mapper ne "HiSat2"){
die "ERROR: mapper should be 'STAR' or 'TopHat2' or 'HiSat2'";
}
print "Mapper used to generate SAM file: : $mapper\n";
} else {
$mapper = "STAR";
print "Mapper used to generate SAM file: : $mapper\n";
}
#Conversion for species terminolo
my $spec = (uc($species) eq "MOUSE") ? "Mus_musculus" : (uc($species) eq "HUMAN") ? "Homo_sapiens" : (uc($species) eq "MYC_ABS_ATCC_19977") ? "mycobacterium_abscessus_atcc_19977" : (uc($species) eq "SL1344") ? "SL1344" : uc($species) eq "C.ELEGANS" ? "Caenorhabditis_elegans" : (uc($species) eq "ZEBRAFISH") ? "Danio_rerio" : (uc($species) eq "YEAST") ? "Saccharomyces_cerevisiae" : (uc($species) eq "FRUITFLY") ? "Drosophila_melanogaster" : "";
my $spec_short = (uc($species) eq "MOUSE") ? "mmu" : (uc($species) eq "HUMAN") ? "hsa" : (uc($species) eq "ZEBRAFISH") ? "dre" : (uc($species) eq "YEAST") ? "sce" : uc($species) eq "C.ELEGANS" ? "cel" : (uc($species) eq "FRUITFLY") ? "dme" : (uc($species) eq "SL1344") ? "sl1344" : (uc($species) eq "MYCAB") ? "mycab" : "";
#Old mouse assembly = NCBIM37, new one is GRCm38. Old human assembly = GRCh37, the new one is GRCh38
my $assembly = (uc($species) eq "MOUSE" && $version >= 70 ) ? "GRCm38"
: (uc($species) eq "MOUSE" && $version < 70 ) ? "NCBIM37"
: (uc($species) eq "HUMAN" && $version >= 76) ? "GRCh38"
: (uc($species) eq "HUMAN" && $version < 76) ? "GRCh37"
: (uc($species) eq "ZEBRAFISH") ? "GRCz10"
: (uc($species) eq "SL1344") ? "ASM21085v2"
: (uc($species) eq "MYC_ABS_ATCC_19977") ? "ASM6918v1"
: (uc($species) eq "YEAST") ? "R64-1-1"
: (uc($species) eq "C.ELEGANS") ? "WBcel235"
: (uc($species) eq "FRUITFLY" && $version < 79) ? "BDGP5"
: (uc($species) eq "FRUITFLY" && $version >= 79) ? "BDGP6" : "";
#UCSC code
my $ucsc;
if ($assembly eq "GRCh38"){
$ucsc = "hg38";
} elsif ($assembly eq "GRCh37") {
$ucsc = "hg19";
} elsif ($assembly eq "GRCm38") {
$ucsc = "mm10";
} elsif ($assembly eq "NCBIM37") {
$ucsc = "mm9";
} elsif ($assembly eq "BDGP6") {
$ucsc = "dm6";
} elsif ($assembly eq "GRCz10") {
$ucsc = "danRer10";
} elsif ($assembly eq "WBcel235") {
$ucsc = "ce10";
} elsif ($assembly eq "R64-1-1"){
$ucsc = "sacCer3";
}
#Folder arguments
if ($tool_dir){
print "The tool directory is set to : $tool_dir\n";
} else {
#Get the conda environment location
my $env_file = "envs.txt";
system("conda info -e > ".$env_file);
my $conda_env = "";
open(my $fh, "<", $env_file) or die "Could not open conda environments information file!";
while(my $line = <$fh>){
chomp($line);
if($line =~ m/\*\s*(\/.+)$/){
$conda_env = $1;
}
}
close($fh);
system("rm -rf ".$env_file);
if($conda_env eq "" || $conda_env eq "/bin/mqc_tools/"){
print "Could not find conda environment for default tool directory allocation!\n";
die;
}
$tool_dir = $conda_env."/bin/mqc_tools/";
print "The conda mqc tool directory is automatically set to : $tool_dir\n";
}
#Check the scripts you need
if (!-e $tool_dir."/mQC.py"){
print "Could not find the python mappingQC plotting script mQC.py!\n";
die;
}
if (!-e $tool_dir."/metagenic_piecharts.R"){
print "Could not find the R metagenic distribution plotting script metagenic_piecharts.R!\n";
die;
}
if (!-e $tool_dir."/quality_plots.R"){
print "Could not find the R quality plotting script quality_plots.R!\n";
die;
}
if ($outfolder){
print "The figure output folder is : $outfolder\n";
} else {
$outfolder = $work_dir."/mQC_output/";
print "The figure output folder is : $outfolder\n";
}
if ($plotrpftool){
if ($plotrpftool eq "grouped2D" || $plotrpftool eq "pyplot3D" || $plotrpftool eq "mayavi"){
print "RPF phase plotting tool: : $plotrpftool\n";
if ($plotrpftool eq "pyplot3D"){
#Check the installation of the pyplot 3D mod
print "\n\nChecking the installation of pyplot 3D plotting mod\n";
if (!-e $tool_dir."/install_pyplot3D_mod.py"){
print "Could not find the python pyplot 3D installation module!\n";
die;
}
system("python ".$tool_dir."/install_pyplot3D_mod.py");
print "\n\n";
}
} else {
die "The plotrpftool option should be 'grouped2D', 'pyplot3D' or 'mayavi'!\n";
}
} else {
$plotrpftool = "grouped2D";
print "RPF phase plotting tool: : $plotrpftool\n";
}
if ($outhtml){
print "The output HTML file is : $outhtml\n";
} else {
$outhtml = $work_dir."/mQC_".$exp_name.".html";
print "The output HTML file is : $outhtml\n";
}
if ($outzip){
print "The output zip file is : $outzip\n";
} else {
$outzip = $work_dir."/mQC_".$exp_name.".zip";
print "The output zip file is : $outzip\n";
}
unless ($comp_logo) {
$comp_logo = 'biobix';
}
#Ensembl options
if ($version){
print "Ensembl version : $version\n";
if(uc($species) eq "SL1344" || uc($species) eq "MYC_ABS_ATCC_19977"){
if($version>40){
print "Error: latest Ensembl Bacteria version is 40!\n";
die;
}
} else {
if($version>89){
print "Error: latest Ensembl version is 92!\n";
die;
}
}
} else {
die "Do not forget the Ensembl version!";
}
if ($ens_db){
if ($ens_db eq "get"){
#Download ensembl db
print "Download Ensembl DB: ".$species." (version ".$version.")\n";
system("python ".$tool_dir."/ENS_db.py -v ".$version." -s ".$species);
$ens_db = "ENS_".$spec_short."_".$version.".db";
#Move ensembl db to tmp folder
system("mv ".$ens_db." ".$TMP);
$ens_db = $TMP."/".$ens_db;
}
print "the Ensembl DB : $ens_db\n";
} else {
die "\nDon't forget to pass the Ensembl DB!\n\n";
}
if ($maxmultimap){
print "Maximun number of loci for reads to be acceptable : $maxmultimap\n";
} else {
$maxmultimap = 16;
print "Maximun number of loci for reads to be acceptable : $maxmultimap\n";
}
if ($offset_option) {
if ($offset_option eq "standard" || $offset_option eq "from_file" || $offset_option eq "plastid" || $offset_option eq "cst_3prime") {
print "Offset source : $offset_option\n";
} else {
die "Offset argument needs to be \" standard\", \"from_file\", \"cst_3prime\" or \"plastid\"!";
}
} else {
$offset_option = "standard";
print "Offset source : $offset_option\n";
}
if ($offset_option eq "from_file"){
if ($offset_file) {
print "Offset input file : $offset_file\n";
} else {
die "Do not forget the offset input file if offset argument is \"from_file\"!";
}
} else {
$offset_file = "";
}
if ($offset_option eq "plastid"){
if ($bam){
if ($bam eq "convert"){
print "Bam file for plastid offset generation will be converted out of sam file\n";
} else {
print "Bam file for plastid offset generation : $bam\n";
}
} else {
$bam = "convert";
print "Bam file for plastid offset generation will be converted out of sam file\n";
}
if ($min_length_plastid){
print "Minimum length for plastid offset generation : $min_length_plastid\n";
} else {
$min_length_plastid = 22;
print "Minimum length for plastid offset generation : $min_length_plastid\n";
}
if ($max_length_plastid){
print "Maximum length for plastid offset generation : $max_length_plastid\n";
} else {
$max_length_plastid = 34;
print "Maximum length for plastid offset generation : $max_length_plastid\n";
}
}
unless ($cst_3prime_offset) {
$cst_3prime_offset = 15; #Default value
}
unless ($min_cst_3prime_offset) {
$min_cst_3prime_offset = 22 #Default
}
unless ($max_cst_3prime_offset) {
$max_cst_3prime_offset = 40 #Default
}
if ($offset_option eq "cst_3prime"){
print "Constant 3' offset: : $cst_3prime_offset\n";
print "Minimum RPF length for constant 3' offset: : $min_cst_3prime_offset\n";
print "Maximum RPF length for constant 3' offset: : $max_cst_3prime_offset\n";
}
if ($min_length_gd){
print "Minimum length for gene distribution and metagene analysis : $min_length_gd\n";
} else {
$min_length_gd = 26;
print "Minimum length for gene distribution and metagene analysis : $min_length_gd\n";
}
if ($max_length_gd){
print "Maximum length for gene distribution and metagene analysis : $max_length_gd\n";
} else {
$max_length_gd = 34;
print "Maximum length for gene distribution and metagene analysis : $max_length_gd\n";
}
if ($cores) {
print "Number of cores to use for analysis : $cores\n";
} else {
$cores = 5;
print "Number of cores to use for analysis : $cores\n";
}
#Download ChromInfo.txt (cfr. get_igenomes.py script PROTEOFORMER)
if (! -e $TMP."/ChromInfo.txt"){
download_chrominfo($TMP, $ucsc);
} else {
print "Chromosomal info file already present\n";
}
# Get chromosomes and correct coord_system_id
print "Get chromosomes and coord_system_id...\n";
my $chromosome_sizes; my $coord_system_id; my @ch;
$chromosome_sizes = $TMP."/ChromInfo.txt";
my %chr_sizes = %{get_chr_sizes($chromosome_sizes)};
$coord_system_id = get_coord_system_id($ens_db,$assembly);
#Test on galaxy should run only on Y chromosome
if($galaxytest eq 'Y'){
my %chr_sizesY;
$chr_sizesY{'Y'} = $chr_sizes{'Y'};
%chr_sizes = %chr_sizesY;
}
#Download chromosome sequences
if (! -e $TMP."/Chromosomes"){
system("mkdir ".$TMP."/Chromosomes");
}
if (! -e $TMP."/Chromosomes_BIN"){
system("mkdir ".$TMP."/Chromosomes_BIN");
}
my $chrom_dir = $TMP."/Chromosomes";
my $BIN_chrom_dir = $TMP."/Chromosomes_BIN";
print "Get/check chromosome fasta files\n";
my $cores_download; #Max 15
if ($cores>15){
$cores_download = 15;
} else {
$cores_download = $cores;
}
my $pm_download = new Parallel::ForkManager($cores_download);
print " Using ".$cores_download." core(s) (max 15)\n ----------------------\n";
foreach my $chr (keys %chr_sizes){
### Start parallel process
$pm_download->start and next;
### Download chromosome per process
if (! -e $TMP."/Chromosomes/".$chr.".fa"){
downloadChromosomeFasta($chr, $spec, $version, $assembly);
} else {
print "\t\t*) Chromosome ".$chr." already present\n";
}
### Finish
$pm_download->finish;
}
$pm_download->wait_all_children;
print "\n";
########
# MAIN #
########
# Start time
my $start = time;
## Get chromosomes based on seq_region_id ##
# Sqlite Ensembl
my $db_ENS = $ens_db;
my $dsn_ENS = "DBI:SQLite:dbname=$db_ENS";
my $us_ENS = "";
my $pw_ENS = "";
my $chrs = get_chrs($dsn_ENS,$us_ENS,$pw_ENS,\%chr_sizes,$assembly);
#Test on galaxy should run only on Y chromosome
if ($galaxytest eq 'Y') {
my $chrsY = {};
$chrsY->{'Y'}->{'seq_region_id'} = $chrs->{'Y'}->{'seq_region_id'};
$chrs = $chrsY;
}
# Create binary chromosomes if they don't exist
print "\nChecking/Creating binary chrom files ...\n";
create_BIN_chromosomes($BIN_chrom_dir,$cores,$chrs,$work_dir,$TMP);
#Sam file splitting
print "\n";
if (! -e $TMP."/mappingqc"){
system("mkdir ".$TMP."/mappingqc");
}
my @splitsam = split(/\//, $sam );
my $samFileName = $splitsam[$#splitsam];
@splitsam = split(/\./,$samFileName);
$samFileName = $splitsam[0];
my $samfilechr1 = "";
if(uc($species) eq "SL1344" || uc($species) eq "MYC_ABS_ATCC_19977"){
$samfilechr1 = $TMP."/mappingqc/".$samFileName."_Chromosome.sam";
} else {
$samfilechr1 = $TMP."/mappingqc/".$samFileName."_1.sam";
}
if (-e $samfilechr1){
print "Splitted sam files already exist\n";
} else {
print "Splitting genomic mapping per chromosome\n";
split_SAM_per_chr(\%chr_sizes,$work_dir,$sam, $unique, $mapper);
}
# Construct p offset hash
print "\n";
my $offset_hash = {};
if($offset_option eq "plastid"){
$offset_hash = run_plastid($bam, $TMP, $version, $spec, $assembly, $exp_name, $min_length_plastid, $max_length_plastid);
} elsif($offset_option eq "from_file"){
#Init
$offset_hash->{"min"} = 1000;
$offset_hash->{"max"} = 0;
#Read in file
open(my $FR, $offset_file) or die "Could not open $offset_file";
#Parse
while(my $line = <$FR>){
if($line =~ /^(\d+)\s+(\d+)$/){
my $length = $1;
my $offset = $2;
$offset_hash->{$length} = $offset;
if($length<$offset_hash->{"min"}){
$offset_hash->{"min"} = $length;
}
if($length>$offset_hash->{"max"}){
$offset_hash->{"max"} = $length;
}
}
}
} elsif($offset_option eq "cst_3prime"){
#Translate constant 3 prime offsets into 5 prime offsets
$offset_hash->{"min"} = $min_cst_3prime_offset;
$offset_hash->{"max"} = $max_cst_3prime_offset;
for(my $rpf = $offset_hash->{"min"}; $rpf<=$offset_hash->{"max"}; $rpf++){
$offset_hash->{$rpf} = $rpf - $cst_3prime_offset - 1
}
} else {
#Standard P site offset options from Ingolia paper (2012) (cfr. suppl methods in that paper)
if(uc($species) eq 'FRUITFLY'){
$offset_hash->{25} = 12;
}
$offset_hash->{26} = 12;
$offset_hash->{27} = 12;
$offset_hash->{28} = 12;
$offset_hash->{29} = 12;
$offset_hash->{30} = 12;
$offset_hash->{31} = 13;
$offset_hash->{32} = 13;
$offset_hash->{33} = 13;
$offset_hash->{34} = 14;
#Boundaries
if(uc($species) eq 'FRUITFLY'){
$offset_hash->{"min"} = 25;
} else {
$offset_hash->{"min"} = 26;
}
$offset_hash->{"max"} = 34;
}
#Write offsets to csv for output html file
print "Save offsets to csv\n";
offsets_to_csv($offset_hash, $TMP);
print "\n\n";
if ((!-e $TMP."/mappingqc/rpf_phase.csv") || (!-e $TMP."/mappingqc/pos_table_all.csv") || (!-e $TMP."/mappingqc/total_triplet.csv") || (!-e $TMP."/mappingqc/rankedgenes.png") || (!-e $TMP."/mappingqc/cumulative.png") || (!-e $TMP."/mappingqc/density.png") || (!-e $TMP."/mappingqc/annotation_coding.png") || (!-e $TMP."/mappingqc/annotation_noncoding.png")){
print "RIBOSOMAL PARSING\n";
system("mkdir ".$TMP."/counts");
# Init multi core
my $pm = new Parallel::ForkManager($cores);
print " Using ".$cores." core(s)\n ---------------\n";
foreach my $chr (keys %chr_sizes){
### Start parallel process
$pm->start and next;
### RIBO parsing
RIBO_parsing_genomic_per_chr($work_dir,$sam,$chr,$ens_db,$coord_system_id, $offset_hash, $min_length_gd, $max_length_gd);
### Finish
print "* Finished chromosome ".$chr."\n";
$pm->finish;
}
# Finish all subprocesses
$pm->wait_all_children;
print "\n\n";
print "PREPARE DATA FOR PLOTTING MODULES\n";
## RPF PHASE TABLE ##
print "\tRPF phase table\n";
#Count rpf phase table of all chromosomes together
my $temp_csv_rpf_phase = $TMP."/mappingqc/rpf_phase.csv";
system("touch ".$temp_csv_rpf_phase);
my $rpf_phase = {};
for (my $i=$offset_hash->{'min'};$i<=$offset_hash->{'max'};$i++){
for (my $j=0;$j<=2;$j++){
$rpf_phase->{$i}->{$j} = 0;
}
}
foreach my $chr (keys %chr_sizes){
my $infile = $TMP."/mappingqc/rpf_phase_".$chr.".csv";
open(IN,"<".$infile) or die $!;
while(my $line = <IN>){
my @linesplit = split(',',$line);
$rpf_phase->{$linesplit[0]}->{0} = $rpf_phase->{$linesplit[0]}->{0} + $linesplit[1];
$rpf_phase->{$linesplit[0]}->{1} = $rpf_phase->{$linesplit[0]}->{1} + $linesplit[2];
$rpf_phase->{$linesplit[0]}->{2} = $rpf_phase->{$linesplit[0]}->{2} + $linesplit[3];
}
close(IN);
system("rm -rf ".$infile);
}
#Write rpf phase table to temp csv
open(OUT_PHASE, "+>>".$temp_csv_rpf_phase);
foreach my $rpf (keys %{$rpf_phase}){
print OUT_PHASE $rpf.",".$rpf_phase->{$rpf}->{0}.",".$rpf_phase->{$rpf}->{1}.",".$rpf_phase->{$rpf}->{2}."\n";
}
close(OUT_PHASE);
## PHASE RELATIVE POSITION DISTRIBUTION
print "\tPhase - relative position distribution\n";
#Cat phase-position tmp files
my $temp_csv_all_pos = $TMP."/mappingqc/pos_table_all.csv";
system("touch ".$temp_csv_all_pos);
foreach my $chr (keys %chr_sizes){
my $temp_csv_chr_pos = $TMP."/mappingqc/phase_position_".$chr.".csv";
system("cat ".$temp_csv_chr_pos." >> ".$temp_csv_all_pos);
system("rm -rf ".$temp_csv_chr_pos);
}
## TRIPLET IDENTITY PHASE FILE
print "\tTriplet identity distributions\n";
my $all_codons = all_codons();
my $all_phases = ['0', '1', '2'];
#Read in chr tmp files
#Init hash
my $triplet_phase = {};
foreach my $triplet (@$all_codons){
foreach my $phase (@$all_phases){
$triplet_phase->{$triplet}->{$phase} = 0;
}
}
foreach my $chr (keys %chr_sizes){
my $infile = $TMP."/mappingqc/triplet_phase_".$chr.".csv";
open(IN, "< ".$infile) or die $!;
while(my $line = <IN>){
chomp($line);
my @linesplit = split(',',$line);
my $triplet = $linesplit[0];
my $phase = $linesplit[1];
my $count = $linesplit[2];
$triplet_phase->{$triplet}->{$phase} = $triplet_phase->{$triplet}->{$phase} + $count;
}
close(IN);
system("rm -rf ".$infile);
}
#Write total file for triplet identity
my $temp_total_triplet = $TMP."/mappingqc/total_triplet.csv";
open(OUT_TOTAL_TRIPLET, "+>> ".$temp_total_triplet);
foreach my $triplet (keys %{$triplet_phase}){
foreach my $phase (keys %{$triplet_phase->{$triplet}}){
print OUT_TOTAL_TRIPLET $triplet.",".$phase.",".$triplet_phase->{$triplet}->{$phase}."\n";
}
}
close(OUT_TOTAL_TRIPLET);
## NORMALIZED TRIPLET COUNTS FILE
print "\tNormalized triplet counts";
#Cat norm triplet count file
#Init hash
my $total_norm_triplet = {};
foreach my $triplet (@$all_codons){
$total_norm_triplet->{$triplet} = 0;
}
foreach my $chr (keys %chr_sizes){
my $infile = $TMP."/mappingqc/triplet_phase_norm_".$chr.".csv";
open(IN, "< ".$infile) or die $!;
while(my $line = <IN>){
chomp($line);
my @linesplit = split(',', $line);
my $triplet = $linesplit[0];
my $norm_count = $linesplit[1];
$total_norm_triplet->{$triplet} = $total_norm_triplet->{$triplet} + $norm_count;
}
close(IN);
}
#Write total file for norm triplet counts
my $temp_total_norm_triplet = $TMP."/mappingqc/norm_triplet.csv";
open(OUT_NORM_TRIPLET, "+>> ".$temp_total_norm_triplet);
foreach my $triplet (keys %{$total_norm_triplet}){
print OUT_NORM_TRIPLET $triplet.",".$total_norm_triplet->{$triplet}."\n";
}
close(OUT_NORM_TRIPLET);
} else {
print "Ribosomal parsing already done\n"
}
###########
## Gene distributions
###########
if((!-e $TMP."/mappingqc/rankedgenes.png") || (!-e $TMP."/mappingqc/cumulative.png") || (!-e $TMP."/mappingqc/density.png")){
print "\nGene distribution\n";
gene_distribution($db_ENS, $us_ENS, $pw_ENS, \%chr_sizes, $cores, $coord_system_id, $tool_dir);
} else {
print "\nGene distribution already constructed\n";
}
###########
## Metagenic classification
###########
if((!-e $TMP."/mappingqc/annotation_coding.png") || (!-e $TMP."/mappingqc/annotation_noncoding.png")){
print "\nMetagenic classification\n";
metagenic_analysis($db_ENS, $us_ENS, $pw_ENS, \%chr_sizes, $cores, $coord_system_id, $tool_dir);
} else {
print "\nMetagenic classification already done\n";
}
#Run python plotting script
print "\n\n\n\n";
print "Run python plotting script\n";
if ($ext eq "bam"){
$sam = $original_bam;
}
my $python_command = "python ".$tool_dir."/mQC.py -g ".$galaxy." -a ".$galaxysam." -y ".$galaxytest." -t ".$TMP." -s ".$sam." -n ".$exp_name." -c ".$comp_logo." -o ".$outfolder." -h ".$outhtml." -z ".$outzip." -p \"".$offset_option."\" -e ".$ens_db." -d ".$species." -v ".$version." -u ".$unique." -x ".$plotrpftool;
if ($offset_option eq "plastid"){
my $offset_img = $TMP."/plastid/".$exp_name."_p_offsets.png";
$python_command = $python_command." -i ".$offset_img;
}
print "Python command:\n\t";
print $python_command."\n";
system($python_command);
# End time
print " DONE! \n";
my $end = time - $start;
printf("Runtime: %02d:%02d:%02d\n\n",int($end/3600), int(($end % 3600)/60), int($end % 60));
############
# THE SUBS #
############
## Gene distribution for each chromosome ##
sub gene_distribution_chr{
#Catch
my $db_ens = $_[0];
my $us_ens = $_[1];
my $pw_ens = $_[2];
my $chr = $_[3];
my $coord_system_id = $_[4];
#Open files
my $out_chr_table = $TMP."/mappingqc/genedistribution_".$chr.".txt";
open OUT_CHR_GD,"+>>".$out_chr_table or die $!;
#Connect to ensembl db
my $dsn_ens = "DBI:SQLite:dbname=".$db_ens;
my $dbh = dbh($dsn_ens, $us_ens, $pw_ens);
#Get seq region id
my $seq_region = get_seq_region_id($dbh, $chr, $coord_system_id);
#Get all genes with start and stop position
my $query1 = "SELECT stable_id,seq_region_start,seq_region_end,seq_region_strand FROM gene WHERE seq_region_id = '$seq_region'";
my $execute1 = $dbh->prepare($query1);
$execute1->execute();
my %genes;
while(my @result1 = $execute1->fetchrow_array()){
#$result1[0]: gene stable_id
#$result1[1]: gene seq_region_start
#$result1[2]: gene seq_region_end
#$result1[3]: gene seq_region_strand
$genes{$chr.":".$result1[3]}{$result1[0]} = [$result1[1],$result1[2]];
}
$execute1->finish();
#Disconnect from ensembl
$dbh->disconnect();
#Make lists of genes (forward and reverse) sorted based on coordinates
my %for_genes = %{$genes{$chr.":1"}};
my %rev_genes = %{$genes{$chr.":-1"}};
my(@genes_for,@genes_rev);
foreach my $gene_id (sort { $genes{$chr.":1"}{$a}[0] <=> $genes{$chr.":1"}{$b}[0] } keys(%for_genes)){
push(@genes_for,$gene_id);
}
foreach my $gene_id (sort { $genes{$chr.":-1"}{$a}[0] <=> $genes{$chr.":-1"}{$b}[0] } keys(%rev_genes)){
push(@genes_rev,$gene_id);
}
##############
## RIBO-SEQ -> READs (~A-site position): determine gene distribution
##############
print "\t\tAnnotating ribo-seq reads of chr ".$chr."\n";
# Get ribo-seq reads, split per strand
my ($ribo_for, $pos_for) = get_reads($chr,1);
my ($ribo_rev, $pos_rev) = get_reads($chr,-1);
#Init
my %gene_count;
my $intergenic_count;
# Loop over forward ribo-seq reads
my @window_genes_for = (); # Init window with genes
foreach my $pos (@{$pos_for}){
#Push all genes into window where start<window_pos
my $last_added_index_g = -1;
foreach my $gene_id (@genes_for){
if($genes{$chr.":1"}{$gene_id}[0] <= $pos){
$last_added_index_g++;
push(@window_genes_for,$gene_id);
}else{
#Don't unnecessarily loop over all genes
last;
}
}
#Get rid of gene ids in gene list already in the window
splice(@genes_for, 0, $last_added_index_g+1);
#Get rid of gene ids in window where end coordinate < window position
@window_genes_for = grep {$genes{$chr.":1"}{$_}[1] >= $pos} @window_genes_for;
#Annotate read count for all genes in the window
my $def = 0;
foreach my $gene_id (@window_genes_for){
$def++; #defined in genes
$gene_count{$gene_id} += $ribo_for->{$pos}{'count'};
}
if($def==0){
$intergenic_count += $ribo_for->{$pos}{'count'};
}
}#Close forward loop
my @window_genes_rev = ();
#Loop over reverse ribo-seq reads
foreach my $pos (@{$pos_rev}){
#Push all genes into window where start<window_pos
my $last_added_index_g = -1;
foreach my $gene_id (@genes_rev){
if($genes{$chr.":-1"}{$gene_id}[0] <= $pos){
$last_added_index_g++;
push(@window_genes_rev,$gene_id);
}else{
#Don't unnecessarily loop over all genes
last;
}
}
#Get rid of gene ids in gene list already in the window
splice(@genes_rev, 0, $last_added_index_g+1);
#Get rid of gene ids in window where end coordinate < window position
@window_genes_rev = grep {$genes{$chr.":-1"}{$_}[1] >= $pos} @window_genes_rev;
#Annotate read count for all genes in the window
my $def = 0;
foreach my $gene_id (@window_genes_rev){
$def++; #defined in genes
$gene_count{$gene_id} += $ribo_rev->{$pos}{'count'};
}
if($def==0){
$intergenic_count += $ribo_rev->{$pos}{'count'};
}
}#Close reverse loop
##############
## RESULTS: Make table
##############
foreach my $id (keys(%gene_count)){
print OUT_CHR_GD $id."\t".$gene_count{$id}."\n";
}
close(OUT_CHR_GD);
print "\t*) Finished gene distribution construction for chromosome ".$chr."\n";
return;
}
## Gene distribution ##
sub gene_distribution{
#Catch
my $db_ens = $_[0];
my $us_ens = $_[1];
my $pw_ens = $_[2];
my %chr_sizes = %{$_[3]};
my $cores = $_[4];
my $coord_system_id = $_[5];
my $tool_dir = $_[6];
# Open files
my $out_table = $TMP."/mappingqc/genedistribution.txt";
system("rm -rf ".$out_table);
system("touch ".$out_table);
open(OUT_GD,"+>>".$out_table);
print OUT_GD "GeneID\tread_count\n";
close(OUT_GD);
#Init multi core
my $processes = $cores; # Nr of processes
my $pm = new Parallel::ForkManager($processes); # Open fork
# Loop through chromosomes
foreach my $chr(keys(%chr_sizes)){
print "\tStarting analysis for chr ".$chr."...\n";
# Start parallel process
$pm->start and next;
#Chromosomal gene distribution construction
gene_distribution_chr($db_ens, $us_ens, $pw_ens, $chr, $coord_system_id);
# Close process
$pm->finish;
}
# Finish forking
$pm->wait_all_children;
#Concatenate all chromosomal out tables
foreach my $chr(keys(%chr_sizes)){
my $chr_out_table = $TMP."/mappingqc/genedistribution_".$chr.".txt";
my $tmp_file = $TMP."/mappingqc/tmp.txt";
system("cat ".$out_table." ".$chr_out_table." > ".$tmp_file);
system("mv ".$tmp_file." ".$out_table);