-
Notifications
You must be signed in to change notification settings - Fork 0
/
MGmapper_SE.pl
executable file
·2455 lines (2157 loc) · 62.5 KB
/
MGmapper_SE.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
my $version = "SE_2.24";
BEGIN{
if (exists $ENV{MGmap_HOME}) {
push(@INC, $ENV{MGmap_HOME} . '/modules');
} else {
die "Environment variable MGmap_HOME does not exists. Make it point to MGmapper's home.\n";
}
*LOG=*STDERR;
}
umask 0022;
my $command="$0 ";
my $i=0;
while (defined($ARGV[$i])){
$command .= "$ARGV[$i] ";
$i++;
}
#use warnings;
use Getopt::Std;
use Time::HiRes;
use Cwd;
use strict;
use Parallel::ChildManager;
use MGmapper::MGmapper;
my $origDir = cwd();
#
# Process command line
#
getopts('hi:f:d:kKq:m:F:C:c:t:Te:EpSn:ws:a:vP:Q:B:RA:VMN:r:U:D:L:1:')||Usage();
if (defined($Getopt::Std::opt_V)){
print "$version\n";
exit;
}
#
# program calls
#
my $prog_xlsWrite = "$ENV{MGmap_HOME}/scripts/MGcsv2xls.py";
my $prog_pileup2fasta = "$ENV{MGmap_HOME}/scripts/pileup2fasta.pl";
my $prog_mpileup2stat = "$ENV{MGmap_HOME}/scripts/mpileup2stat.pl";
my $prog_filterBam = "$ENV{MGmap_HOME}/scripts/filter_bam.pl";
my $prog_MGmapper_classify = "$ENV{MGmap_HOME}/MGmapper_classify.pl";
if (! -e $prog_xlsWrite){
die "Program not found: $prog_xlsWrite\n";
}
if (! -e $prog_pileup2fasta){
die "Program not found: $prog_pileup2fasta\n";
}
if (! -e $prog_mpileup2stat){
die "Program not found: $prog_mpileup2stat\n";
}
if (! -e $prog_filterBam){
die "Program not found: $prog_filterBam\n";
}
#
# parameter files
#
my $parameterFile = "$ENV{MGmap_HOME}/databases.txt";
my $parameterFile_adapter = "$ENV{MGmap_HOME}/adapter.txt";
#
# third-party programs
#
my $prog_python = &MGmapper::find_program('MGmap_PYTHON', "python");
my $prog_bwa = &MGmapper::find_program('MGmap_BWA', "bwa");
my $prog_samtools = &MGmapper::find_program('MGmap_SAMTOOLS', "samtools");
#my $prog_samtools = "/services/tools/samtools/0.1.18/bin/samtools";
my $prog_bedtools = &MGmapper::find_program('MGmap_BEDTOOLS', "bedtools");
my $prog_pigz = &MGmapper::find_program('MGmap_PIGZ', "pigz");
my $prog_cutadapt = &MGmapper::find_program('MGmap_CUTADAPT', "cutadapt");
{
my $st = `$prog_samtools 2>&1`;
my @tmp = split(m/\n/, $st);
@tmp = grep(m/^Version/, @tmp);
push(@tmp, "Version: no version");
$tmp[0] =~ m/^Version:\s+(\S+)/;
die "Samtools $prog_samtools must be version 1.6\n" unless $1 eq '1.6';
}
my $datestring;
my $databaseCounter=0;
my %databaseNames=();
my %db_version=();
my @dbNames=();
my %idx=();
my %databaseCount=();
my %countEntries=();
my %runningMode=();
my %info=();
&readParameterFile;
#
# Default parameters
#
my $cm;
$i=0;
my $wwwMode=0;
my $workDir = "mapper_$$";
my $cleanFile;
my $redo=0;
my $commonName;
my $qualityCut = 30;
my $minLen = 30;
my $cores = 1;
my $matchRatio = 0.8;
my $matchRatioFlag = 1;
my $absoluteMatchCount = $minLen;
my $absoluteMatchCountFlag = 0;
my $mapNotPhiXReads=0;
my $sampleName = 'sample';
my $SNP_threshold=4;
my $QUALITY_BASE = 33;
my $alignment_score_min=30;
my $max_edit_distance=5;
#
# parameters for MGmapper_classify.pl
#
my $min_relative_abundance=0.01;
my $min_readCount = 20;
my $min_coverage=0;
my $min_readCountUniq_ratio=0.005;
my $max_mismatch_ratio=0.15;
my $unix_cmd1='';
#
# Total number of reads that are ok either from the start or after cutadapt
#
my $biological_relevant_reads=0;
my @databases_fullmode=();
my @databases_chainmode=();
my @databases_all=();
my @markdup_all=();
my $markdup_count=0;
my %abundance=();
my %fastaOut=();
my @rmFiles;
my $verbose=1;
my $cleanup=1;
my $cleanupCutadapt=1;
my $noclean="$workDir/noclean";
my $slimMode=0;
my $remove_PCR_duplicates=0;
#
# Usage
#
if (defined($Getopt::Std::opt_h)||defined($Getopt::Std::opt_h)){
# Print help message
Usage();
}
sub Usage {
print ("Usage: $0 [-h] [-P parameter file] [-Q parameter file] [-i fastq file] [-f fastq file list] [-d outDir] [-q number] [-m number] [-F num serarate with comma] [-C numbers separate with comma] [-c cores] [-t number] [-T] [-e integer] [-E] [-p] [-s number] [-k] [-K] [-S] [-x] [-n name] [-A number] [-N number] [-M] [-r number] [-U number] [-D number] [-L number] [-V] [-1 unix_command]\n");
print ("Description:\n");
print ("$0 - Map SE reads against genomic sequence databases\n");
print ("\n");
print ("Options:\n");
print (" -h : display this message\n");
print (" -V : show version \($version\) and exit\n");
print (" -P : parameter file with reference to database [$parameterFile]\n");
print (" -Q : parameter file with adapters removed by cutadapt [$parameterFile_adapter]\n");
print (" -c : cores to use [$cores]\n");
print (" Input files:\n");
print (" -i : input fastq file\n");
print (" -f : input list with fastq file names\n");
print (" Parameters to filter bwa mem hits for a single read:\n");
print (" -t : true hits have a Match/readLen >= fraction [$matchRatio]\n");
print (" -T : option -t is active [on]\n");
print (" -e : minimum number of Matches+Mismatches for a valid read [$absoluteMatchCount] - only active if -E is defined\n");
print (" -E : option -e is active [off]\n");
print (" -A : minumum alignment score for a read [$alignment_score_min]\n");
print (" -N : maximum edit distance\n");
print (" -p : remove PCR duplicates [off]\n");
print (" Parameters for post-processing of reads assigned to a specific strain or species:\n");
print (" -r : minimum size normalized abundance [$min_relative_abundance]\n");
print (" -U : minimum read count [$min_readCount]\n");
print (" -D : minimum Reads_uniq/Reads ratio [$min_readCountUniq_ratio]\n");
print (" -L : maximum Edit_distance/Nucleotides ratio [$max_mismatch_ratio] i.e. max nucleotide mis-match ratio\n");
print (" Cutadapt parameters:\n");
print (" -S : skip cutadapt [off]\n");
print (" -m : minimum read length in cutadapt [$minLen]\n");
print (" -q : Quality q cutoff in cutadapt [$qualityCut]\n");
print (" -B : QUALITY_BASE, quality values are encoded as ascii(quality + QUALITY_BASE) [$QUALITY_BASE]\n");
print (" Mapping mode and database selections:\n");
print (" -F : map reads in Full mode against these databases - comma separated numbers\n");
print (" -C : map reads in Best mode against these databases - comma separated numbers - the order matters\n");
print (" Output files\/directory\n");
print (" -d : output directory [$workDir]\n");
print (" -n : Sample name [$sampleName]\n");
print (" Assembled fasta files and parameters:\n");
print (" -a : make assembled fasta files for reads mapping to these databases - comma separated numbers - order dont matter ex.'1,2'\n");
print (" -s : Min number of occurences to accept a variation in contig fasta file [$SNP_threshold]\n");
print (" -R : make Read count matrices [off]\n");
print (" -k : keep all files [off]\n");
print (" -K : keep all cutadapt files [off]\n");
print (" -M : slim mode i.e. remove all bam and unmapped.fq [off]\n");
print (" Command to be executed after everything else has finished:\n");
print (" -1 : unix command\n");
print ("---Databases---\n");
for (my $i=1;$i<=$databaseCounter;$i++){
printf (" $i\t%-20s$idx{desc}{$i}\n",$databaseNames{$i});
}
exit;
} # Usage
&parseOptions;
###############################################################################
#
# Main program start
#
###############################################################################
my $thisDir=cwd();
$datestring = localtime();
#
# save running time for most system calls
#
my $fh_runtime=\*RUNTIME;
MGmapper::init_runtime_file($fh_runtime, "$workDir/log/runtime.log", $datestring);
my $fh_total_time= \*TIME;
my $fh_filestat=\*FILESTAT;
if ($wwwMode){
#
# save a simple file with start and end times for running MGmapper - only used in www-mode
#
MGmapper::init_time_file($fh_total_time, "$workDir/misc/time.tab", $workDir, $datestring);
#
# A file with readcount statistics - only used in www-mode
#
MGmapper::init_filestat($fh_filestat, "$workDir/misc/filestat.tab");
}
my $start_time1 = [Time::HiRes::gettimeofday()];
my ($user1, $system1, $child_user1, $child_system1) = times;
MGmapper::make_run_info_file($workDir, $version, $command, $datestring);
my $fh_stat = \*STAT;
MGmapper::init_MGmapper_summary($fh_stat, "$workDir/log/MGmapper.summary", $thisDir, $command);
my $cmd;
my %readCount=();
my $readCountFile = "$workDir/misc/readCount.txt";
my $sumReadsBefore=0;
my $sumReadsAfter=0;
my $fastqFiles=0;
if (! defined($Getopt::Std::opt_S)){
if ($wwwMode){
print $fh_filestat "#Counter\tFileName\tReads in\tReads after trimming\n";
}
}
else{
if ($wwwMode){
print $fh_filestat "#Counter\tFileName\tReads in\n";
}
print $fh_stat "Counter\tFileName\tReads\n";
}
my $cleanFileFlag=0;
if (-e "$workDir/bam/cleaned.nophiX.bam"){
$cleanFileFlag=1;
if (! exists($readCount{$cleanFile})){
$biological_relevant_reads = &bamCountReads($cleanFile);
}
}
if (-e $readCountFile){
open(COUNT,"<$readCountFile");
while (defined($_=<COUNT>)){
chomp;
my @w=split(/\t+/);
my $file = $w[0];
my $reads = $w[1];
$readCount{$file}=$reads;
print LOG "# Reading from $readCountFile: $_\n" if ($verbose);
}
close(COUNT);
}
my %readsBefore=();
my %readsAfter=();
my %cutadaptFile=();
my @fileHolder=();
my $cutFile = "$workDir/misc/cutadapt.all.fq";
if (defined($Getopt::Std::opt_i)){
push(@fileHolder,$Getopt::Std::opt_i);
}
elsif (defined($Getopt::Std::opt_f)){
@fileHolder = MGmapper::readFastqList($Getopt::Std::opt_f);
}
foreach my $file (@fileHolder){
if (exists($readCount{$file})){
$readsBefore{$file}=$readCount{$file};
}
else{
open(COUNT,">>$readCountFile");
$readsBefore{$file}=MGmapper::countReads($file,\*LOG, $verbose);
print COUNT "$file\t$readsBefore{$file}\n";
close(COUNT);
}
$sumReadsBefore += $readsBefore{$file};
}
if (! defined($Getopt::Std::opt_S)){
&run_cutadapt();
}
else{
foreach my $file (@fileHolder){
$fastqFiles++;
if ($wwwMode){
my @FS=split(/\//,$file);
print $fh_filestat "$fastqFiles\t$FS[-1]\t$readsBefore{$file}\n";
}
print $fh_filestat "$fastqFiles\t$file\t$readsBefore{$file}\n";
}
}
if (-e $cleanFile){
&mapping($cleanFile);
}
elsif ($#fileHolder >= 0){
#
# many input fastq files
#
if (! -e $cutFile){
foreach my $file (@fileHolder){
if (-e $cutadaptFile{$file}){
if (($cutadaptFile{$file} =~/\.gz$/) || ($cutadaptFile{$file}=~/\.Z$/)){
$cmd="gunzip -c $cutadaptFile{$file} >> $cutFile";
}
else{
$cmd="cat $cutadaptFile{$file} >> $cutFile";
}
}
elsif (($file =~/\.gz$/) || ($file=~/\.Z$/)){
$cmd = "gunzip -c $file >> $cutFile";
}
else{
$cmd = "cat $file >> $cutFile";
}
print LOG "# Doing: $cmd\n" if ($verbose);
system("$cmd");
}
}
system"gzip $cutFile";
$cutFile="$cutFile.gz";
if (($cleanupCutadapt) || ($slimMode)){
push(@rmFiles, $cutFile);
}
if (! defined($Getopt::Std::opt_S)){
print $fh_stat "Total\tFastq files\tReads read\tReads after trimming\tAfter cleaning\n";
print $fh_stat "Total\t$fastqFiles\t$sumReadsBefore\t$sumReadsAfter\n";
}
else{
print $fh_stat "Total\tFastq files\tReads read\n";
print $fh_stat "Total\t$fastqFiles\t$sumReadsBefore\n";
}
if ($wwwMode){
open(FILESTAT2,">$workDir/misc/filestat2.tab");
if (! defined($Getopt::Std::opt_S)){
print FILESTAT2 "#Fastq files\tReads read\tReads after trimming\tAfter cleaning\n";
print FILESTAT2 "$fastqFiles\t$sumReadsBefore\t$sumReadsAfter\t";
}
else{
print FILESTAT2 "#Fastq files\tReads read\tAfter cleaning\n";
print FILESTAT2 "$fastqFiles\t$sumReadsBefore\t";
}
}
&mapping($cutFile);
}
else{
print LOG "Empty fileholders - I die now\n";
print LOG "Done!\n";
die;
}
############################################################################
#
# Make overall abundance statistics
#
############################################################################
open(DBCount,">$workDir/misc/dbCount.tab");
print DBCount "#Database\tVersion\tNo of sequence\tNo of nucleotides\n";
print $fh_stat "# All mapped reads\n";
print LOG "mapNotPhiXReads = $biological_relevant_reads used as reference to max possible reads that can map to a database\n" if ($verbose);
my $version_databases="$workDir/misc/version.databases";;
open(VERSION_DATABASES,">$version_databases");
my $file;
my $reads;
foreach my $key (@databases_all){
if (exists($db_version{$key})){
print VERSION_DATABASES "$key\t$db_version{$key}\n";
}
print DBCount "$key\t$db_version{$key}\t$countEntries{$key}{sequences}\t$countEntries{$key}{nuc}\n";
}
close(VERSION_DATABASES);
close(DBCount);
#
# add annotations to stat files
#
#
# KyotoCabinet not installed on cge, so use grep instead
#
#&add_taxonomy;
&add_taxonomy;
#
# Join nucleotide statistics file with read abundance statistics file
#
my $xlsWrite_cmd = "$prog_python $prog_xlsWrite $workDir/$sampleName.xlsx $workDir/abundance.databases.txt";
my $xlsWrite_negative_cmd = "$prog_python $prog_xlsWrite $workDir/$sampleName.negative.xlsx ";
&excel_and_post_processing();
my $unmappedBam = "$workDir/bam/unmapped.bam";
&unmapped_SE();
my $unmapped=&bamCountReads($unmappedBam);
push(@rmFiles, $unmappedBam);
#
# printout unmapped bam file
#
&printout_unmapped();
#
# make abundance.databases.txt
#
my $overall_abundance="$workDir/abundance.databases.txt";
open(AB,">$overall_abundance");
&print_overall_abundance(\*AB, $unmapped);
close(AB);
#
# Also print abundance databases info to STAT (log/MGmapper.summary);
# the STAT filehandle is already open
&print_overall_abundance($fh_stat, $unmapped);
if ($wwwMode){
open(FILESTAT3,">$workDir/misc/filestat3.tab");
print FILESTAT3 "#Mapping mode\tDatabase\tPercent mapped\tNo reads\n";
&print_overall_abundance(\*FILESTAT3, $unmapped);
close(FILESTAT3);
#
# Make snippet files with only 5 best abundances for all databases - only at strain level
# For historical reasons outputFile Chainmode.tab is kept allthougt it is Bestmode
#
if ($#databases_chainmode >=0){
MGmapper::make_www_tables($workDir, "$workDir/misc/Chainmode.tab", @databases_chainmode);
}
if ($#databases_fullmode >=0){
MGmapper::make_www_tables($workDir, "$workDir/misc/Fullmode.tab", @databases_fullmode);
}
}
print LOG "\n# $xlsWrite_cmd\n" if ($verbose);
print LOG "\n# $xlsWrite_negative_cmd\n" if ($verbose);
if (-e "$workDir/$sampleName.xlsx"){
system("rm $workDir/$sampleName.xlsx");
}
if (-e "$workDir/$sampleName.negative_hits.xlsx"){
system("rm $workDir/$sampleName.negative_hits.xlsx");
}
$datestring = localtime();
print $fh_runtime "$datestring\n";
print $fh_runtime "# $xlsWrite_cmd\n";
print $fh_runtime "# $xlsWrite_negative_cmd\n";
system("$xlsWrite_cmd");
system("$xlsWrite_negative_cmd");
#
# Make a header file that explains columns in $database.summary files
#
MGmapper::print_README("$workDir/Readme", $Getopt::Std::opt_R);
&cleanup_files();
#
# gzip all fastq files
#
$cmd="$prog_pigz -p $cores $workDir/misc/*.fq $workDir/cutadapt/*.cutadapt";
print LOG "Doing: $cmd\n" if ($verbose);
system("$cmd");
$datestring = localtime();
if ($wwwMode){
print TIME "$datestring\n";
close(TIME);
}
print $fh_stat "## Local date and time $datestring - done\n";
if ($remove_PCR_duplicates){
print $fh_stat ("PCR duplicates - excluded from unmapped fastq files(s): $markdup_count\n");
}
print $fh_stat "$datestring\n";
print $fh_stat "End main programe\n";
close($fh_stat);
print $fh_runtime "$datestring\n";
print $fh_runtime "End main programe\n";
close($fh_runtime);
if ($wwwMode){
print STDERR "Done!\n";
}
if (defined($Getopt::Std::opt_1)){
print LOG "Executing unix command: '$unix_cmd1'\n" if ($verbose);
system("$unix_cmd1");
}
if ($verbose){
close(LOG);
}
exit(0);
###############################################################################
#
# Main program end
#
###############################################################################
sub run_cutadapt{
my $first=1;
my @commands=();
my $command;
my $command_part1 = &make_cutadapt_command();
my $command_part2;
foreach my $file (@fileHolder){
if ($first){
$datestring = localtime();
print $fh_stat "## Local date and time $datestring - cutadapt start\n";
$first=0;
}
$command_part2 = &cutadapt_SE($file);
$command = "$command_part1" . "$command_part2";
if ($command =~ m/-o (\S+) /){
$cutadaptFile{$file}=$1;
}
else{
print LOG "problem extracting output name from cutadapt command:\n$command\n";
exit;
}
if (-e "${cutadaptFile{$file}}.gz"){
$cutadaptFile{$file}= "${cutadaptFile{$file}}.gz";
}
if ($command ne ''){
if ((! -e $cutadaptFile{$file}) || (-z $cutadaptFile{$file})){
push(@commands,$command);
}
}
}
if (! -e $cleanFile){
foreach my $command (@commands){
print LOG "$command\n" if ($verbose);
$cm->start("$command");
}
#
# Wait for all jobs to finish
#
$cm->wait_all_children;
print $fh_runtime "Commands run in parallel:\n";
foreach my $id (@commands){
print $fh_runtime "$id\n";
}
$datestring = localtime();
print $fh_runtime "$datestring\n";
}
foreach my $file (@fileHolder){
$fastqFiles++;
if (exists($readCount{$cutadaptFile{$file}})){
$readsAfter{$file}=$readCount{$cutadaptFile{$file}};
}
else{
open(COUNT,">>$readCountFile");
$readsAfter{$file}=MGmapper::countReads($cutadaptFile{$file}, \*LOG, $verbose);
print COUNT "$cutadaptFile{$file}\t$readsAfter{$file}\n";
close(COUNT);
}
$sumReadsAfter += $readsAfter{$file};
if ($wwwMode){
my @FS=split(/\//,$file);
print $fh_filestat "$fastqFiles\t$FS[-1]\t$readsBefore{$file}\t$readsAfter{$file}\n";
}
print $fh_stat "$fastqFiles\t$file\t$readsBefore{$file}\t$readsAfter{$file}\n";
}
return(0);
}
sub make_cutadapt_command{
my $cutadapt_cmd = "$prog_cutadapt --quality-base=$QUALITY_BASE -f fastq -q $qualityCut -m $minLen";
if (! -e "$parameterFile_adapter"){
print LOG "can't open file $parameterFile_adapter\n";
print LOG "Done!\n";
die;
}
open(ADAPTER,"<$parameterFile_adapter") || die ("can't open file $parameterFile_adapter: $!");
print LOG "Adapters removed by cutadapt:\n" if ($verbose);
my $i=0;
my $adapter;
while (defined($_=<ADAPTER>)){
if (/^\#/){
next;
}
chomp;
if (m/(\S+)/){
$adapter = $1;
}
else{
next;
}
my $len=length($adapter);
if ($len >1){
$i++;
print LOG "$i\t$adapter\n" if ($verbose);
$cutadapt_cmd .= " -b $adapter";
}
}
$cutadapt_cmd .= ' ';
print LOG "\n" if ($verbose);
close(ADAPTER);
return($cutadapt_cmd);
}
sub printout_unmapped{
if ((! $slimMode) && ($unmapped >0)){
my $readsUnmapped = "$workDir/misc/unmapped.fq";
my $cmd = "$prog_bedtools bamtofastq -i $unmappedBam -fq $readsUnmapped";
print LOG "# Doing: $cmd\n";
system($cmd);
print $fh_stat ("File with unmapped reads : $readsUnmapped\n");
system("gzip $readsUnmapped");
print $fh_stat ("Number of unmapped reads : $unmapped\n\n");
}
return(0);
}
sub excel_and_post_processing{
foreach my $db (@databases_all){
my $annot = "$workDir/misc/stat.$db.annot";
my $strain_positive = "$workDir/stat/positive.strain.$db.txt";
my $strain_negative = "$workDir/stat/negative.strain.$db.txt";
my $strain_positive_noHeader = "$workDir/misc/positive.strain.$db.txt";
my $strain_negative_noHeader = "$workDir/misc/negative.strain.$db.txt";
my $strain_log = "$workDir/stat/classify.strain.$db.log";
my $species_positive = "$workDir/stat/positive.species.$db.txt";
my $species_negative = "$workDir/stat/negative.species.$db.txt";
my $species_positive_noHeader = "$workDir/misc/positive.species.$db.txt";
my $species_negative_noHeader = "$workDir/misc/negative.species.$db.txt";
my $species_log = "$workDir/stat/classify.species.$db.log";
$cmd = "$prog_MGmapper_classify -i $annot -c strain -a $min_relative_abundance -r $min_readCountUniq_ratio -m $max_mismatch_ratio -n $min_readCount -g $min_coverage -o $strain_positive -f $strain_negative -v -l $strain_log -s -H -N $biological_relevant_reads";
print LOG "Doing: $cmd\n" if ($verbose);
print $fh_runtime "# $cmd\n";
system("$cmd");
#
# Remove header for the excel sheet
#
system("grep -v '^#' $strain_positive > $strain_positive_noHeader");
system("grep -v '^#' $strain_negative > $strain_negative_noHeader");
if (-z $strain_positive_noHeader){
print LOG "removing empty file: $strain_positive\n" if ($verbose);
push(@rmFiles,$strain_positive);
}
push(@rmFiles,$strain_positive_noHeader);
if (-z $strain_negative_noHeader){
print LOG "removing empty file: $strain_negative\n" if ($verbose);
push(@rmFiles,$strain_negative);
}
push(@rmFiles,$strain_negative_noHeader);
$cmd = "$prog_MGmapper_classify -i $annot -c species -a $min_relative_abundance -r $min_readCountUniq_ratio -m $max_mismatch_ratio -n $min_readCount -g $min_coverage -o $species_positive -v -l $species_log -s -H -f $species_negative -N $biological_relevant_reads";
print LOG "Doing: $cmd\n" if ($verbose);
print $fh_runtime "# $cmd\n";
system("$cmd");
#
# now find the lowest accepted abundance and rerun
#
my $new_lowest_abundance = $min_relative_abundance;
open(TMP,"<$species_log");
my $species_count=0;
while (defined ($_=<TMP>)){
chomp;
if (/^# Minimum accepted abundance value=/){
my @w=split(/\t/);
$new_lowest_abundance = $w[1];
}
if (/# Number of hits accepted:/){
my @w=split(/\t/);
$species_count= $w[1];
}
}
close(TMP);
#
# if any species was found with default parameters as above, then rerun with -a = lowest abundance among those hits and no uniq_read_ratio i.e. -r 0
# This will find more species with abundance higher than what was previoiusly found, but no uniq_read_ratio criteria
#
if ($species_count >0){
#
# not pretty to subtract the very small number, but needed due to rounding off problems
#
$new_lowest_abundance -= 0.0000000001;
$cmd = "$prog_MGmapper_classify -i $annot -c species -a $new_lowest_abundance -r 0 -m $max_mismatch_ratio -n $min_readCount -g $min_coverage -o $species_positive -f $species_negative -v -l $species_log -s -H -N $biological_relevant_reads";
print LOG "Doing: $cmd\n" if ($verbose);
print $fh_runtime "# $cmd\n";
system("$cmd");
}
#
# Remove header for the excel sheet
#
system("grep -v '^#' $species_positive > $species_positive_noHeader");
system("grep -v '^#' $species_negative > $species_negative_noHeader");
if (-z $species_positive_noHeader){
print LOG "removing empty file: $species_positive\n" if ($verbose);
push(@rmFiles,$species_positive);
}
push(@rmFiles,$species_positive_noHeader);
if (-z $species_negative_noHeader){
print LOG "removing empty file: $species_negative\n" if ($verbose);
push(@rmFiles,$species_negative);
}
push(@rmFiles,$species_negative_noHeader);
if ((! -z $strain_positive_noHeader) && (-e $strain_positive_noHeader)){
$xlsWrite_cmd .= " $strain_positive_noHeader";
}
if ((! -z $species_positive_noHeader) && (-e $species_positive_noHeader)){
$xlsWrite_cmd .= " $species_positive_noHeader";
}
if ((! -z $strain_negative_noHeader) && (-e $strain_negative_noHeader)){
$xlsWrite_negative_cmd .= " $strain_negative_noHeader";
}
if ((! -z $species_negative_noHeader) && (-e $species_negative_noHeader)){
$xlsWrite_negative_cmd .= " $species_negative_noHeader";
}
}
return(0);
}
sub print_overall_abundance{
my ($fh, $unmapped) = @_;
printf $fh "Fullmode\tnotPhiX\t100.00\t%d\n",$biological_relevant_reads;
my $file;
my $reads;
my $perc;
foreach my $key (@databases_all){
$file = "$workDir/bam/mapTo.$key.bam";
$reads = &bamCountReads($file);
$perc = $reads*100/$biological_relevant_reads;
printf $fh "%s\t%s\t%7.3f\t%d\n",$runningMode{$key},$key,$perc,$reads;
}
my $str="Unmapped";
$perc = $unmapped*100/$biological_relevant_reads;
printf $fh "-\t%s\t%7.3f\t%d\n",$str,$perc,$unmapped;
return(0);
}
sub cleanup_files{
if ($cleanupCutadapt){
system("rm -r $workDir/cutadapt");
}
if ($cleanup){
my $cmd;
if (! -e "$noclean"){
foreach my $id (@rmFiles){
if (-e $id){
$cmd = "rm $id";
print LOG "Doing: $cmd\n" if ($verbose);
system("$cmd");
}
}
}
}
return(0);
}
sub unmapped_SE{
my %rec=();
my $str;
my $revcomp;
my $hash_str_F;
my $hash_str_R;
my @w=();
my $characterLen=30;
foreach my $db (@databases_all){
my $file = "$workDir/bam/mapTo.$db.bam";
open (FILE,"$prog_samtools view $file | cut -f1,10 |");
while (defined($_=<FILE>)){
chomp;
@w=split(/\s+/);
$str=$w[1];
$revcomp = reverse($str);
$revcomp =~ tr/ACGTacgt/TGCAtgca/;
$hash_str_F = $w[0] . $str;
$hash_str_R = $w[0] . $revcomp;
$rec{$hash_str_F}=1;
$rec{$hash_str_R}=1;
}
close(FILE);
}
if ($remove_PCR_duplicates){
foreach my $file (@markdup_all){
open (FILE,"$prog_samtools view $file | cut -f1,10 |");
while (defined($_=<FILE>)){
chomp;
@w=split(/\s+/);
$str=$w[1];
$revcomp = reverse($str);
$revcomp =~ tr/ACGTacgt/TGCAtgca/;
$hash_str_F = $w[0] . $str;
$hash_str_R = $w[0] . $revcomp;
$rec{$hash_str_F}=2;
$rec{$hash_str_R}=2;
$markdup_count++;
}
close(FILE);
}
print LOG "Total number of PCR duplicates: $markdup_count\n";
}
open(BamIn,"$prog_samtools view $cleanFile |");
open(BamOut,"| $prog_samtools view -h -Sb - > $unmappedBam");
while (defined($_=<BamIn>)){
@w=split(/\s+/);
$str=$w[9];
$revcomp = reverse($str);
$revcomp =~ tr/ACGTacgt/TGCAtgca/;
$hash_str_F = $w[0] . $str;
$hash_str_R = $w[0] . $revcomp;
if ((! exists($rec{$hash_str_F})) && (! exists($rec{$hash_str_R}))){
print BamOut "$_";
}
}
close(BamIn);
close(BamOut);
return(0);
}
sub check_program{
my ($program, @possible_path) = @_;
foreach my $id (@possible_path){
if (-e "$id/$program"){
return("$id/$program");
}
}
print STDERR "can not find program: '$program'\n";
print STDERR "checked these locations: '@possible_path'\n";
die;
}
sub parseOptions{
if (defined($Getopt::Std::opt_Q)){
$parameterFile_adapter = $Getopt::Std::opt_Q;
}
if (defined($Getopt::Std::opt_p)){
$remove_PCR_duplicates = 1;
}
#
# execute a unix command after everything else has finished
#
if (defined($Getopt::Std::opt_1)){
$unix_cmd1=$Getopt::Std::opt_1;
}
if (defined($Getopt::Std::opt_D)){
$min_readCountUniq_ratio = $Getopt::Std::opt_D;
}
if (defined($Getopt::Std::opt_L)){
$max_mismatch_ratio = $Getopt::Std::opt_L;
}
#
# A working directory for all output files
#
if (defined($Getopt::Std::opt_d)){
$workDir = $Getopt::Std::opt_d;
}
if (! -d $workDir){
system ("mkdir -p $workDir; chmod 0755 $workDir");
}
if (! -d "$workDir/bam"){
system("mkdir -p $workDir/bam; chmod 0755 $workDir/bam");
}
if (! -d "$workDir/log"){
system("mkdir -p $workDir/log; chmod 0755 $workDir/log");
}
if (! -d "$workDir/misc"){
system("mkdir -p $workDir/misc; chmod 0755 $workDir/misc");
}
if (! -d "$workDir/stat"){
system("mkdir -p $workDir/stat; chmod 0755 $workDir/stat");
}
if (defined($Getopt::Std::opt_A)){
$alignment_score_min = $Getopt::Std::opt_A;
}
if (defined($Getopt::Std::opt_N)){
$max_edit_distance = $Getopt::Std::opt_N;
}
if (defined($Getopt::Std::opt_r)){
$min_relative_abundance = $Getopt::Std::opt_r;
}
if (defined($Getopt::Std::opt_U)){
$min_readCount = $Getopt::Std::opt_U;
}
if ($verbose){
open(LOG,">$workDir/log/MGmapper.log");
}
if (defined($Getopt::Std::opt_w)){
$wwwMode=1;
}
if (defined($Getopt::Std::opt_s)){
$SNP_threshold=$Getopt::Std::opt_s;
}
if (defined($Getopt::Std::opt_n)){
$sampleName=$Getopt::Std::opt_n;
}
if (defined($Getopt::Std::opt_c)){
$cores = $Getopt::Std::opt_c;
}
if (defined($Getopt::Std::opt_M)){
$slimMode = 1;
}
$cm = new ChildManager($cores);
if (defined($Getopt::Std::opt_i)){
if (! -e $Getopt::Std::opt_i){
print LOG "File not found: $Getopt::Std::opt_i\n";
print STDERR "File not found: $iGetopt::Std::opt_i\nDone!\n";