-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBamKit.pm
More file actions
executable file
·2656 lines (2378 loc) · 85.4 KB
/
BamKit.pm
File metadata and controls
executable file
·2656 lines (2378 loc) · 85.4 KB
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
# POD documentation - main docs before the code
=head1 NAME
FuhaoPerl5Lib::BamKit
=head1 SYNOPSIS
use samtools to index, extract, merge, rehead BAM files
=head1 Requirements
Perl Modules:
Cwd;
Bio::DB::Sam;
FuhaoPerl5Lib::CmdKit;
FuhaoPerl5Lib::FileKit;
FuhaoPerl5Lib::MiscKit;
=head1 DESCRIPTION
=over 2
=item Bam2FastQ ($bamin, $fastqout, map_code, MAPQ_code, [path_samtools])
* Convert bam files into fastq
* Map_code: 0=all 1=mapped_only 2=unmapped_only
* MAPQ_code: any alignment less than MAPQ would be ignored
* Return: 1=Sucesss 0=Failure
=item Bam2FastqProg($BAM, $fastq_prefix, $path_bam2fastq)
* Convert BAM to FASTQ using bam2fastq program (https://github.com/jts/bam2fastq)
* Return (1/0, \%hash=('R1' => $fastqR1, 'R2' => $fastqR2, 'M' => $fastqUnpaired)
=item BamAtacShift($in.bam, $out.bam)
* Modify BAM file to adjust 9 bp for ATAC-seq: forward strand start +4 and reverse strans start -5
* Require: samtools
* Output: Default BAMin.ATAC9shift.bam if not specified
* Return: 1=Success 0= Failure
=item BamExtractReadsUsingBed($inputbam, $file_region, $outreadname[, $path_samtools])
* Extract reads in a BAM file using specified region
* $file_region: region file format:
seq_ID\tstart\tend
seqID
seqID:Num1-Num2
* Note: bed format is half open, start is less 1 than real start
* Return: 1=Sucesss 0=Failure
=item BamFilterReadsByNames($inputbam, $file_readnames, $filter_code, $outbam[, $path_samtools])
* Filter BAM reads by a file of read name list
* $file_readnames: per readname per line
* $filter_code: 1=filter 0=filter_out
* Return: 1=Sucesss 0=Failure
=item BamKeepBothMates ($input.R1.bam, $input.R2.bam, $paired.R1.bam, $paired.R2.bam, [$unpaired.R1.bam], [$unpaired.R2.bam], [path_samtools])
* Keep alignments that have both mates mapped
* Return: 1=Success 0=Failure
=item BamKeepNumAlignemnts(In.name-sorted.bam, $k [default:1], out.bam)
* Remove alignment >k mapping times from BAM
* Require: samtools
* Note: need to double times for paired end, so k2 means unique for paired reads
* Return: 1=Success 0=Failure
=item BamMarkPairs ($input.R1.bam, $input.R2.bam, $output.R1.bam, $output.R2.bam, [path_samtools])
* Mark separately mapped FLAG to R1 67 R2 131
* Return: 1=Success 0=Failure
=item BamRestoreSplit($bamin, $bed, $bamout, [$path_samtools])
* Restore BAM coordintes due to splited reference
* Return: 1=Success 0= Failure
* BED file 6 columns:
chr1A_part1 0 471304005 chr1A 0 471304005
chr1A_part2 0 122798051 chr1A 471304005 594102056
chr1B_part1 0 438720154 chr1B 0 438720154
chr1B_part2 0 251131716 chr1B 438720154 689851870
chr1D_part1 0 452179604 chr1D 0 452179604
chr1D_part2 0 43273582 chr1D 452179604 495453186
=item CalCigarRefLength (CIGAR)
* Calculate reference length based cigar
* Return the reference length of that BAM alignment
=item CalCigarReadLength (CIGAR)
* Calculate read length based cigar
* Return the read length of that BAM alignment
=item CalcFPKM(BAMin, $total_mapped_reads, readgroup aware(0/1), [$CFpath_samtools])
=item ExpressFpkm($EFref, $EFfrag_len_mean, $EFfrag_len_stddev, $EFmax_read_len, \@EFsamfiles, \@seq_ids, [path_express])
* For special
=item ExtactBam($input.bam, $seqid_string, $out.bam, [$samtools_path])
* Return: 1=Sucesss 0=Failure
=item ExtractMultimapping (in.bam, reads.out.names, refs.out.names)
* Evaluate multi-mapping by counting mapping times, output multi-mapped reads and their refs
* Dependency: samtools
* Return: 1=Success 0= Failure
=item GetBamMate (BAM_FLAG_value)
* Get Mate info from a BAM FLAG
* Return: 0=NOT_paired; 1=R1 in pair; 2=R2 in pair
=item GetListForSecondMapping (BAM_list_file, CHR_Keep_list_file, CHR_exclude_list_file, readnames_out_file, ref_out_file)
* Get reads names aligned to CHR_Keep_list_file and exclude reads names aligned to CHR_exclude_list_file, and then get all the refs that the remaining reads aligned to, for the second alignment
* Return: 1=Sucesss 0=Failure
=item IndexBam($baminput, $path_samtools)
* Return: 1=Sucesss 0=Failure
=item ReadSam($file.sam,$ref,fa, ReturnCode(1/2/3))
* Dependancy: Bio::DB::Sam
* ReturnCode: 1=Bio::DB::Sam objective; 2=reference name array, 3=to be defined
* Return: (0/1, $CodeAssigned)
=item SamCleanHeader($input.bam, $out.bam, [out.noRG.bam], [\@seqids], [path2samtools])
* Return: 1=Sucesss 0=Failure
* [\@seqids] could be a reference to a constant or array
* [\@seqids] could be a string delimited by space or comma
=item SortBam($input.bam, $out.bam, [$samtools_path], [$samtools_sort_options])
* 1=Sucesss 0=Failure
* samtools_sort_options: -n, -l Num, -@ Num
=item SplitCigar(SamCigar)
* Return: double array ((2, M), (5, D), ....)
=item VerifyCigarLength ($CIGAR, $READLENGTH)
* Verify Cigar length == readlength
* Return: 1=equal 0=NOTequal
=back
=head1 FEEDBACK
=head2 Support
Please send you questions or bug reports to Email:
I<lufuhao@gmail.com>
=head1 AUTHORS - Fu-Hao Lu
Email: lufuhao@gmail.com (Always)
Fu-Hao.Lu@jic.ac.uk (2012-2016)
=head1 CONTRIBUTORS
None
=head1 APPENDIX
Fight against Bioinformatics with Perl ^_^
=cut
#Coding starts
package FuhaoPerl5Lib::BamKit;
use strict;
use warnings;
use Cwd;
use Exporter;
use FuhaoPerl5Lib::CmdKit qw(exec_cmd_return);
use Bio::DB::Sam;
use FuhaoPerl5Lib::FileKit;
use FuhaoPerl5Lib::MiscKit qw(IsReference);
use Data::Dumper qw /Dumper/;
use vars qw($VERSION @ISA @EXPORT @EXPORT_OK %EXPORT_TAGS);
$VERSION = '20180911';
@ISA = qw(Exporter);
@EXPORT = qw();
@EXPORT_OK = qw(IndexBam ExtactBam SplitCigar SamCleanHeader Bam2FastQ SortBam CalcFPKM ReduceReadNameLength ReadSam Bam2FastqProg VerifyCigarLength CalCigarRefLength BamFilterReadsByNames BamExtractReadsUsingBed BamKeepBothMates BamMarkPairs BamKeepNumAlignemnts BamAtacShift BamRestoreSplit GetListForSecondMapping GetBamMate ExtractMultimapping);
%EXPORT_TAGS = ( DEFAULT => [qw(IndexBam ExtactBam SplitCigar SamCleanHeader Bam2FastQ SortBam CalcFPKM ReduceReadNameLength ReadSam Bam2FastqProg VerifyCigarLength CalCigarRefLength BamFilterReadsByNames BamExtractReadsUsingBed BamKeepBothMates BamMarkPairs BamKeepNumAlignemnts BamAtacShift BamRestoreSplit GetListForSecondMapping GetBamMate ExtractMultimapping)],
Both => [qw(IndexBam ExtactBam SplitCigar SamCleanHeader Bam2FastQ SortBam CalcFPKM ReduceReadNameLength ReadSam Bam2FastqProg VerifyCigarLength CalCigarRefLength BamFilterReadsByNames BamExtractReadsUsingBed BamKeepBothMates BamMarkPairs BamKeepNumAlignemnts BamAtacShift BamRestoreSplit GetListForSecondMapping GetBamMate ExtractMultimapping)]);
my $BamKit_success=1;
my $BamKit_failure=0;
my $BamKit_debug=0;
### Get Mate info from a BAM FLAG
### GetBamMate (BAM_FLAG_value)
### Global:
### Dependency:
### Note:
### Return: 0=NOT_paired; 1=R1 in pair; 2=R2 in pair
sub GetBamMate {
my $GBMflag=shift @_;
my $GBMmate=0;
if ($GBMflag & 0x0040) {
$GBMmate=1;
}
elsif ($GBMflag & 0x0080) {
$GBMmate=2;
}
return $GBMmate;
}
### samtools index sorted BAM
### IndexBam($baminput, $path_samtools)
### Global: $BamKit_success; $BamKit_failure;
### Dependency: &exec_cmd_return
### Note:
sub IndexBam {
my ($IBbamin, $IBpath_samtools)=@_;
my $CFsubinfo='SUB(BamKit::IndexBam)';
$IBpath_samtools='samtools' unless (defined $IBpath_samtools);
unless (defined $IBbamin and -s $IBbamin) {
print STDERR $CFsubinfo, "Error: invalid BAM input\n";
return $BamKit_failure;
}
unlink "$IBbamin.bai" if (-e "$IBbamin.bai");
if (! &exec_cmd_return("$IBpath_samtools index $IBbamin")) {
print STDERR $CFsubinfo, "Error: SAMtools index running error\n";
return $BamKit_failure;
}
elsif (! -s "$IBbamin.bai") {
print STDERR $CFsubinfo, "Error: SAMtools index output error\n";
return $BamKit_failure;
}
return $BamKit_success;
}
### Extract subsets from BAM
### &ExtactBam($input.bam, $seqid_string, $out.bam, [$samtools_path])
### Global:
### Dependency: &exec_cmd_return
### Note:
sub ExtractBam {
my ($EBbamin, $EBseqids, $EBbamout, $EBpath_samtools)=@_;
my $EBsubinfo='SUB(BamKit::ExtractBam)';
$EBpath_samtools='samtools' unless (defined $EBpath_samtools);
my $EBcmd="";
unless (defined $EBbamin and -s $EBbamin) {
print STDERR $EBsubinfo, "Error: invalid BAM input\n";
return $BamKit_failure;
}
unless (defined $EBseqids and $EBseqids !~/^\s*$/) {
print STDERR $EBsubinfo, "Error: invalid seqids\n";
return $BamKit_failure;
}
unless (defined $EBbamout) {
print STDERR $EBsubinfo, "Error: invalid BAM output\n";
return $BamKit_failure;
}
unlink $EBbamout if (-e $EBbamout);
if ($EBbamin=~/\.sam$/i) {
$EBcmd="$EBpath_samtools view -b -h -S ";
}
elsif ($EBbamin=~/\.bam$/i) {
$EBcmd="$EBpath_samtools view -b -h ";
}
else {
print STDERR $EBsubinfo, "Error: unknown input BAM/SAM extension \n";
return $BamKit_failure;
}
unless (-s "$EBbamin.bai") {
unless (&IndexBam($EBbamin)) {
print STDERR $EBsubinfo, "Error: can not Index BAM: $EBbamin\n";
return $BamKit_failure;
}
}
if (! &exec_cmd_return("$EBcmd $EBbamin $EBseqids > $EBbamout")) {
print STDERR $EBsubinfo, "Error: BAM extract failed\n";
return $BamKit_failure;
}
else {
return $BamKit_success;
}
}
### Sort bams
### &SortBam($input.bam, $out.bam, [$samtools_path], [$samtools_sort_options])
### Global: $BamKit_failure;
### Dependency: &exec_cmd_return
### Note:
sub SortBam {
my ($SBbamin, $SBbamout, $SBpath_samtools, $SBsamtools_options)=@_;
my $SBsubinfo='SUB(BamKit::SortBam)';
$SBpath_samtools='samtools' unless (defined $SBpath_samtools);
$SBsamtools_options=' ' unless (defined $SBsamtools_options);
(my $SBbamout_prefix=$SBbamout)=~s/\.bam$//i;
my $SBcmd='';
unless (defined $SBbamin and -s $SBbamin) {
print STDERR $SBsubinfo, "Error: invalid BAM input\n";
return $BamKit_failure;
}
unless (defined $SBbamout and $SBbamout=~/^\S+$/) {
print STDERR $SBsubinfo, "Error: invalid BAM output\n";
return $BamKit_failure;
}
else {
unlink $SBbamout if (-e $SBbamout);
unlink "$SBbamout.bai" if (-e "$SBbamout.bai");
}
if ($SBbamin=~/\.sam$/i) {
$SBcmd="$SBpath_samtools view -b -h -S $SBbamin | $SBpath_samtools sort $SBsamtools_options - $SBbamout_prefix";
}
elsif ($SBbamin=~/\.bam$/i) {
$SBcmd="$SBpath_samtools sort $SBsamtools_options $SBbamin $SBbamout_prefix";
}
else {
print STDERR ${SBsubinfo}, "Error: unknown input BAM/SAM extension \n";
return $BamKit_failure;
}
# if (! -s "$SBbamin.bai") { ### Index BAM
# if (! &IndexBam($SBbamin)) {
# print STDERR "${SBsubinfo}Error: can not Index BAM: $SBbamin\n";
# return $BamKit_failure;
# }
# }
unless (exec_cmd_return("$SBcmd")) {
print STDERR $SBsubinfo, "Error: BAM sort failed\n";
return $BamKit_failure;
}
return $BamKit_success;
}
### extract batch of sequence alignment from Bams, and index
### &ExtactBam(bam_arr, sequence_arr, out.bam, [out.no_RG.bam], [samtools_path])
### Global:
### Dependency: bam_clean_header.pl &exec_cmd_return
### Note:
sub ExtractBam_old {
my ($EBfiles_bam_index, $EBseq_obj, $EBoutput, $EBoutnogroup, $EBpath_samtools)=@_;
my $CFsubinfo='SUB(BamKit::ExtractBam)';
$EBpath_samtools='samtools' unless (defined $EBpath_samtools);
my $EBi=0;
my @EBtemp_bams=();
my $EBsam_seq='';
my $test_outnogroup=0;
if (scalar(@{$EBseq_obj})<1) {###return error if no sequences
print STDERR "${CFsubinfo}Error: fasta ID array empty to be extracted to extract\n";
return $BamKit_failure;
}
else {
$EBsam_seq=join (' ', @{$EBseq_obj});
if ($EBsam_seq=~/^\s*$/) {
print STDERR "${CFsubinfo}Error: empty fasta ID list to extract\n";
return $BamKit_failure;
}
}
unlink $EBoutput if (-e $EBoutput);
unlink "$EBoutput.bai" if (-e "$EBoutput.bai");
if (defined $EBoutnogroup) {
$test_outnogroup=1;
unlink $EBoutnogroup if (-e $EBoutnogroup);
unlink "$EBoutnogroup.bai" if ( -e "$EBoutnogroup.bai");
}
##COMMENT: extract bam from each
# print STDERR "SUB(ExtractBam)Info: sequence to be extracted: $EBsam_seq\n";###for test###
foreach my $EBind_bam (@{$EBfiles_bam_index}) {
$EBi++;
my $EBcmd="$EBpath_samtools view -bh $EBind_bam $EBsam_seq > $EBoutput.$EBi.bam";
if (! &exec_cmd_return($EBcmd)) {
print STDERR "${CFsubinfo}Error: bam extract $EBsam_seq from $EBind_bam failed\n";
return $BamKit_failure;
}
else {
push (@EBtemp_bams, "$EBoutput.$EBi.bam");
}
}
##COMMENT: merge bams
my $EBmerge_bams=join(' ', @EBtemp_bams);
my $EBcmd2="$EBpath_samtools merge $EBoutput.multihead.bam $EBmerge_bams";
if (! &exec_cmd_return($EBcmd2)) {
print STDERR "${CFsubinfo}Error: bam merge from $EBmerge_bams failed\n";
return $BamKit_failure;
}
else {
if (-s "$EBoutput.multihead.bam") {
map {unlink($_)} @EBtemp_bams;###delete temporary files ### For test ###
}
else{
print STDERR "${CFsubinfo}Error: bam merge from $EBmerge_bams not found\n";
return $BamKit_failure;
}
}
my $EBcmd4="bam_clean_header.pl -i $EBoutput.multihead.bam -o $EBoutput -n $EBoutnogroup";
if (! &exec_cmd_return($EBcmd4)) {
print STDERR "${CFsubinfo}Error: bam header clean from $EBmerge_bams failed\n";
return $BamKit_failure;
}
else {
if ( -s $EBoutput and -s $EBoutnogroup) {
unlink ("$EBoutput.multihead.bam") if (-s "$EBoutput.multihead.bam");
if (&IndexBam($EBoutput)) {
print STDERR "${CFsubinfo}Error: bam index from $EBmerge_bams failed\n";
return $BamKit_failure;
}
if (&IndexBam($EBoutnogroup)) {
print STDERR "${CFsubinfo}Error: bam index2 from $EBmerge_bams failed\n";
return $BamKit_failure;
}
}
else{
print STDERR "${CFsubinfo}Error: bam headerclean output from $EBmerge_bams not found\n";
return $BamKit_failure;
}
}
return $BamKit_success;
}
### Clean those sequences in header but not exist in alignments
### SamCleanHeader($input.bam, $out.bam, [out.noRG.bam], [\@seqids], [path2samtools])
### Global:
### Dependency:
### Note:
sub SamCleanHeader {
my ($SCHbam_input, $SCHbam_withrg, $SCHbam_norg, $SCHseq_obj, $SCHpathsamtools)=@_;
local *SCHBAMINPUT1; local *SCHBAMINPUT2; local *SCHBAMOUTPUT;
my $SCHsubinfo='SUB(BamKit::SamCleanHeader)';
my $SCHnew_readgroup=0;
my %SCHreahgroup=();
my $BamKit_debug=0;
$SCHpathsamtools='samtools' unless (defined $SCHpathsamtools);
my %SCHseqID=();
my $SCHgetseqids_from_bam=1;
unless (defined $SCHbam_input and -s $SCHbam_input) {
print STDERR $SCHsubinfo, "Error: BAM input file not found\n";
return $BamKit_failure;
}
unless (defined $SCHbam_withrg and $SCHbam_withrg ne '' and $SCHbam_withrg !~ m/\s+/) {
my $SCHbam_prefix=&RetrvNoExt($SCHbam_input);
$SCHbam_withrg=$SCHbam_prefix.".CleanHeader.bam";
}
unlink ($SCHbam_withrg) if (-e $SCHbam_withrg);
my $SCHtest_norg=0;
if (defined $SCHbam_norg) {
$SCHtest_norg=1;
unlink $SCHbam_norg if (-e $SCHbam_norg);
unlink "$SCHbam_norg.bai" if (-e "$SCHbam_norg.bai");
}
if (defined $SCHseq_obj) {
my @SCHids=();
my $SCHtest_id_reference=&IsReference($SCHseq_obj);
if ($SCHtest_id_reference>0) {
if ($SCHtest_id_reference==1) {
push (@SCHids, ${$SCHseq_obj});
}
elsif ($SCHtest_id_reference==2) {
@SCHids=@{$SCHseq_obj;};
}
else {
print STDERR $SCHsubinfo, "Error: unknown seqids reference type\n";
return $BamKit_failure;
}
}
elsif ($SCHtest_id_reference==0) {
@SCHids=split(/\s+|,/, $SCHseq_obj);
}
# undef $SCHseq_obj;
foreach (@SCHids){
if (/^\S+$/) {
$SCHseqID{$_}++;
$SCHgetseqids_from_bam=0;
}
}
}
##COMMENT: read bam/sam
close SCHBAMINPUT1 if (defined fileno(SCHBAMINPUT1));
if ($SCHbam_input=~/\.sam$/i) {
unless (open (SCHBAMINPUT1, "$SCHpathsamtools view -S $SCHbam_input|")) {
print STDERR $SCHsubinfo, "Error: sam open error\n";
return $BamKit_failure;
}
}
elsif ($SCHbam_input=~/\.bam$/i) {
unless (open (SCHBAMINPUT1, "$SCHpathsamtools view $SCHbam_input|")) {
print STDERR $SCHsubinfo, "Error: bam open error\n";
return $BamKit_failure;
}
}
else {
print STDERR $SCHsubinfo, "Error: unknown BAM format\n";
return $BamKit_failure;
}
while (my $SCHline1=<SCHBAMINPUT1>) {
my @SCHarr1=split(/\t/, $SCHline1);
$SCHseqID{$SCHarr1[2]}++;
if ($SCHline1=~/RG:Z:(\S*)/) {
# print $1."\n";###For test###
if (defined $1 and $1 ne '') {
$SCHnew_readgroup=1;
$SCHreahgroup{$1}++;
}
}
}
close SCHBAMINPUT1;
print STDERR $SCHsubinfo, "Info: total of ".scalar(keys %SCHseqID)." REF sequences detected\n" if ($BamKit_debug);
print STDERR $SCHsubinfo, "Info: total of ".scalar(keys %SCHreahgroup)." readgroups detected\n" if ($BamKit_debug);
unless (scalar(keys %SCHseqID)>=1) {### For BAMs without alignments ###
print STDERR $SCHsubinfo, "Error: no alignments\n";
return 2;
}
##COMMENT: write output
if ($SCHbam_input=~/\.sam$/i) {
unless (open (SCHBAMINPUT2, "$SCHpathsamtools view -h -S $SCHbam_input|")) {
print STDERR $SCHsubinfo, "Error: sam open error\n";
return $BamKit_failure;
}
}
elsif ($SCHbam_input=~/\.bam$/i) {
unless (open (SCHBAMINPUT2, "$SCHpathsamtools view -h $SCHbam_input|")) {
print STDERR $SCHsubinfo, "Error: bam open error\n";
return $BamKit_failure;
}
}
unless (open (SCHBAMOUTPUT, "| $SCHpathsamtools view -bS - > $SCHbam_withrg")) {
print STDERR $SCHsubinfo, "Error: bam write error\n";
return $BamKit_failure;
}
if ($SCHtest_norg==1) {
unless (open (SCHBAMOUTNOGROUP, "| $SCHpathsamtools view -bS - > $SCHbam_norg")) {
print STDERR $SCHsubinfo, "Error: bam2 write error\n";
return $BamKit_failure;
}
}
while (my $SCHline=<SCHBAMINPUT2>) {
if ($SCHline=~m/^\@/) {
##COMMENT: clean header
if ($SCHline=~m/^\@SQ\s+SN:(\S+)\s+LN:\d+/) {
if (! exists $SCHseqID{$1}) {
print STDERR $SCHsubinfo, "Info: ignore $SCHline\n" if ($BamKit_debug);
next;
}
print SCHBAMOUTPUT $SCHline;
print SCHBAMOUTNOGROUP $SCHline if ($SCHtest_norg==1);
}
##Remove RG in header
elsif ($SCHline=~m/^\@RG/) {
if (scalar(keys %SCHreahgroup) >0) {
if ($SCHnew_readgroup==1) {
foreach (keys %SCHreahgroup) {
print SCHBAMOUTPUT '@RG'."\tID:$_\tSM:$_\tPL:Illumina\tLB:$_\n";
}
$SCHnew_readgroup=0;
}
}
else {
print SCHBAMOUTPUT $SCHline;
}
next;
}
else {
print SCHBAMOUTPUT $SCHline;
print SCHBAMOUTNOGROUP $SCHline if ($SCHtest_norg==1);
}
}
else {
print SCHBAMOUTPUT $SCHline;
if ($SCHtest_norg==1) {
$SCHline=~s/\tRG:Z:\S+//g;
print SCHBAMOUTNOGROUP $SCHline;
}
}
}
close SCHBAMOUTPUT;
close SCHBAMINPUT2;
close SCHBAMOUTNOGROUP if (defined $SCHbam_norg);
return $BamKit_success;
}
### split cigar into double array ((2, M), (5, D), ....)
### SplitCigar(SamCigar)
### Global:
### Dependancy:
### Note:
sub SplitCigar {
my $SCcigar_string = shift;
my @SCreturn_cigar_arr=();
while ($SCcigar_string =~ /(\d+)([MIDNSHP=X])/g) {
my @SCoperation=($1, $2);
push @SCreturn_cigar_arr, \@SCoperation;
}
return \@SCreturn_cigar_arr;
}
### Verify Cigar length == readlength
### VerifyCigarLength ($CIGAR, $READLENGTH);
### Global: None
### Dependancy:
### Note:
sub VerifyCigarLength {
my ($VCLcigar, $VCLlength)=@_;
my $VCLsubinfo='SUB(BamKit::VerifyCigarLength)';
my $VCLcigarOperations = &SplitCigar($VCLcigar);
my $VCLcigar_cal_length=0;
foreach (@{$VCLcigarOperations}){#calcular cigar length
unless (defined $_->[0] and defined $_->[1]) {
print STDERR $VCLsubinfo, "Warnings: invalid cigar: $VCLcigar\n";
return 0;
}
if ($_->[1] =~/^[MZIS=X]{1}$/) {
$VCLcigar_cal_length+=$_->[0];
}
}
if ($VCLcigar_cal_length == $VCLlength) {
return 1;
}
else {
print STDERR $VCLsubinfo, "Warnings: cigar: $VCLcigar length != read length $VCLcigar\n";
return 0;
}
}
### calculate reference length based cigar
### CalCigarRefLength (CIGAR)
### Global: None
### Dependancy:
### Return the reference length of that alignment in BAM
sub CalCigarRefLength {
my $CCRLcigar=shift;
my $CCRLsubinfo='SUB(BamKit::CalCigarRefLength)';
my $CCRLcigarOperations = &SplitCigar($CCRLcigar);
my $CCRLcigar_cal_length=0;
foreach (@{$CCRLcigarOperations}){#calcular cigar length
unless (defined $_->[0] and defined $_->[1]) {
print STDERR $CCRLsubinfo, "Warnings: invalid cigar: $CCRLcigar\n";
return 0;
}
if ($_->[1] =~/^[MD=N]{1}$/) {
$CCRLcigar_cal_length+=$_->[0];
}
}
return $CCRLcigar_cal_length;
}
### calculate read length based cigar
### CalCigarReadLength (CIGAR)
### Global: None
### Dependancy:
### Return the read length of that BAM alignment
sub CalCigarReadLength {
my $CCRLcigar=shift;
my $CCRLsubinfo='SUB(BamKit::CalCigarReadLength)';
my $CCRLcigarOperations = &SplitCigar($CCRLcigar);
my $CCRLcigar_cal_length=0;
foreach (@{$CCRLcigarOperations}){#calcular cigar length
unless (defined $_->[0] and defined $_->[1]) {
print STDERR $CCRLsubinfo, "Warnings: invalid cigar: $CCRLcigar\n";
return 0;
}
if ($_->[1] =~/^[MIS=X]{1}$/) {
$CCRLcigar_cal_length+=$_->[0];
}
}
return $CCRLcigar_cal_length;
}
### convert bam files into fastq
### Bam2FastQ ($bamin, $fastqout, map_code, MAPQ_code, [path_samtools])
### Global:
### Dependency:
### Note: map_code (0=all, 1=mapped, 2=unmapped)
sub Bam2FastQ {
my ($BFQbamin, $BFQfqout, $BFQmapcode, $BFQmapq, $BFQpath_samtools)=@_;
local *BAMIN; local *FQOUT;
my $BFQsubinfo='SUB(BamKit::Bam2FastQ)';
$BFQpath_samtools='samtools' unless (defined $BFQpath_samtools);
$BFQmapcode=0 unless (defined $BFQmapcode);
$BFQmapq=0 unless (defined $BFQmapq);
unless (defined $BFQbamin and -s $BFQbamin) {
print STDERR "${BFQsubinfo}Error: invalid BAM input\n";
return $BamKit_failure;
}
if (! defined $BFQfqout) {
print STDERR "${BFQsubinfo}Error: undefined Fastq output\n";
return $BamKit_failure;
}
else {
unlink $BFQfqout if (-e $BFQfqout);
}
close BAMIN if (defined fileno(BAMIN));
unless (open (BAMIN, "$BFQpath_samtools view $BFQbamin | ")) {
print STDERR "${BFQsubinfo}Error: open BAM: $BFQbamin \n";
return $BamKit_failure;
}
close FQOUT if (defined fileno(FQOUT));
unless (open (FQOUT, ">$BFQfqout")) {
print STDERR "${BFQsubinfo}Error: write FQ: $BFQfqout \n";
return $BamKit_failure;
}
my $BFQnumline=0;
while (my $BFQline1=<BAMIN>) {
$BFQnumline++;
chomp $BFQline1;
my @BFQarr=split(/\t/, $BFQline1);
#Check column number
if (scalar(@BFQarr)<11) {
print STDERR "${BFQsubinfo}Warnings: col<11 at line $BFQnumline (Readid: $BFQarr[0]) in BAM $BFQbamin\n";
next;
}
#check if mapped
if ($BFQmapcode==1) {
next if ($BFQarr[1] & 0x0004);
}
elsif ($BFQmapcode==2) {
next unless ($BFQarr[1] & 0x0004);
}
##check if MAPQ threshold
next unless (defined $BFQarr[4] and $BFQarr[4]>=$BFQmapq);
##check if mapped to reverse strand
my $BFQread_id=$BFQarr[0];
my $BFQreadseq=$BFQarr[9];
my $BFQreadqual=$BFQarr[10];
if ($BFQarr[1] & 0x0010) {###0x0010 = reverse strand
$BFQreadseq=reverse ($BFQreadseq);
$BFQreadseq=~tr/ATCGatcg/TAGCtagc/;
$BFQreadqual=reverse ($BFQreadqual);
}
##check if one of pair and check R1 or R2
if ($BFQarr[1] & 0x0001) {
if ($BFQarr[1] & 0x0040) {
$BFQread_id='@'.$BFQread_id.'/1';
print FQOUT "$BFQread_id\n$BFQreadseq\n+\n$BFQreadqual\n";
}
elsif ($BFQarr[1] & 0x0080) {
$BFQread_id='@'.$BFQread_id.'/2';
print FQOUT "$BFQread_id\n$BFQreadseq\n+\n$BFQreadqual\n";
}
else {
print STDERR "${BFQsubinfo}Warnings: unknown R1 or R2 (FLAG: $BFQarr[1]) at line $BFQnumline (Readid: $BFQarr[0]) in BAM $BFQbamin\n";
next;
}
}
else {
$BFQread_id='@'.$BFQread_id;
print FQOUT "$BFQread_id\n$BFQreadseq\n+\n$BFQreadqual\n";
}
}
close BAMIN;
close FQOUT;
return $BamKit_success;
}
### convert BAM to FASTQ using bam2fastq program
### Bam2FastqProg($BAM, $fastq_prefix, $path_bam2fastq)
### Global: $BamKit_success $BamKit_failure
### Dependency:
### Note:
### Return (1/0, \%hash=('R1' => $fastqR1, 'R2' => $fastqR2, 'M' => $fastqUnpaired)
sub Bam2FastqProg {
my ($BFPbamfile, $BFPprefix, $BFPpath_bam2fastq)=@_;
my $BFPsubinfo='SUB(Bam2FastqProg)';
$BFPpath_bam2fastq='bam2fastq' unless (defined $BFPpath_bam2fastq);
$BFPprefix="MyFastq" unless (defined $BFPprefix and $BFPprefix=~/^\S+$/);
my %BFQfastqfiles=();
my $BFPtestout=0;
unless (defined $BFPbamfile and -s $BFPbamfile) {
print STDERR $BFPsubinfo, "Error: invalid BAM file for fastq: $BFPbamfile\n";
return $BamKit_failure;
}
unless (exec_cmd_return("$BFPpath_bam2fastq -o $BFPprefix.R#.fq --quiet --aligned $BFPbamfile")) {
print STDERR $BFPsubinfo, "Error: bam2fastq running error\n";
return $BamKit_failure;
}
if (-s "$BFPprefix.R_1.fq") {
$BFPtestout++;
$BFQfastqfiles{'R1'}="$BFPprefix.R_1.fq";
}
elsif (-e "$BFPprefix.R_1.fq") {
unlink "$BFPprefix.R_1.fq";
}
if (-s "$BFPprefix.R_2.fq") {
$BFPtestout++;
$BFQfastqfiles{'R2'}="$BFPprefix.R_2.fq";
}
elsif (-e "$BFPprefix.R_2.fq") {
unlink "$BFPprefix.R_2.fq";
}
if (-s "$BFPprefix.R_M.fq") {
$BFPtestout++;
$BFQfastqfiles{'M'}="$BFPprefix.R_M.fq";
}
elsif (-e "$BFPprefix.R_M.fq") {
unlink "$BFPprefix.R_M.fq";
}
unless ($BFPtestout >0) {
print STDERR $BFPsubinfo, "Error: bam2fastq output error\n";
return $BamKit_failure;
}
return ($BamKit_success, \%BFQfastqfiles);
}
### Express RPKM
### ExpressFpkm($EFref, $EFfrag_len_mean, $EFfrag_len_stddev, $EFmax_read_len, \@EFsamfiles, \@seq_ids, [path_express])
### Global: $BamKit_debug
### Dependancy: exec_cmd_return, FileKit::RetrieveBasename, FileKit::DeletePath
### Note: bamfiles should be the intact to get the total number of reads
sub ExpressFpkm {
my ($EFref, $EFfrag_len_mean, $EFfrag_len_stddev, $EFmax_read_len, $EFsamfiles_index, $EFcluster_seqids_arrindex, $EFpath_express)=@_;
local *FPKM;
my $EFsubinfo='SUB(BamKitExpressFpkm)';
my @EFfpkms=();
my $EFi=0;
$EFpath_express='express' unless (defined $EFpath_express);
#Format: @return_arr=(AABBDD(1/0), AABB(1/0), AA(1/0), DD(1/0))
my @return_arr=();
my $EFcurdir=getcwd;
if (scalar(@{$EFcluster_seqids_arrindex}) <1) {
print STDERR "${EFsubinfo}Error: empty cluster IDs\n";
return $BamKit_failure;
}
if (scalar(@{$EFsamfiles_index}) < 1) {
print STDERR "${EFsubinfo}Error: empty bam files\n";
return $BamKit_failure;
}
unless (-d "$EFcurdir/Express") {
unless (mkdir ("$EFcurdir/Express", 0766)) {
print STDERR "${EFsubinfo}Error: can not create folder $EFcurdir/Express\n";
return $BamKit_failure;
}
}
unlink glob "$EFcurdir/Express/*";
#@EFsamfiles=(bam_AABBDD, bam_AABB, bam_AA, bam_DD) in this order
foreach my $EFbamfile (@{$EFsamfiles_index}) {
my $EFbamfile_base=RetrieveBasename($EFbamfile);
DeletePath("$EFcurdir/Express/$EFbamfile_base") if (-d "$EFcurdir/Express/$EFbamfile_base");
unless (mkdir ("$EFcurdir/Express/$EFbamfile_base", 0766)) {
print STDERR "${EFsubinfo}Error: can not create folder $EFcurdir/Express/$EFbamfile_base\n";
return $BamKit_failure;
}
# unlink glob "$EFcurdir/Express/$EFbamfile_base/*.xprs";###delete last-run files
if (-s $EFbamfile) {
my $EFcmd="$EFpath_express --frag-len-mean $EFfrag_len_mean --frag-len-stddev $EFfrag_len_stddev --max-read-len $EFmax_read_len --output-dir $EFcurdir/Express/$EFbamfile_base $EFref $EFbamfile 2> /dev/stderr";
if (! &exec_cmd_return($EFcmd)) {
return $BamKit_failure;
}
elsif (! -s "$EFcurdir/Express/$EFbamfile_base/results.xprs") {
return $BamKit_failure;
}
close FPKM if (defined fileno(FPKM));
unless (open (FPKM, "$EFcurdir/Express/$EFbamfile_base/results.xprs")) {
print STDERR "${EFsubinfo}Error: can not open file $EFcurdir/Express/$EFbamfile_base/results.xprs\n";
return $BamKit_failure;
}
my $EFline=<FPKM>;###firstline is header
my $EFtest_expressed=0;
while ($EFline=<FPKM>) {
chomp $EFline;
my @arr=split(/\t/, $EFline);
#$arr[1] is reference sequence ID
#$arr[10] is the estimated relative abundance in units of fragments per kilobase per million mapped
if ($arr[10]>0) {###express if any reference FPKM >0 in this cluster
$EFtest_expressed=1;
}
${$EFfpkms[$EFi]}{$arr[1]}=$arr[10];
}
close FPKM;
push (@return_arr, $EFtest_expressed);
DeletePath("$EFcurdir/Express/$EFbamfile_base") if (-d "$EFcurdir/Express/$EFbamfile_base");#delete last-run files
#unlink glob "$EFbamfile_base/*.xprs";###delete last-run files
####Delete directory###PAUSE
$EFi++;
}
else {
print STDERR "${EFsubinfo}Error: bam file $EFbamfile empty or non-exists\n";
return $BamKit_failure;
}
}
#Check if each cluster_seqids have a FPKM value, 0 if not;
#Output FPKM to $fpkm_log file
foreach my $EFseqid (@{$EFcluster_seqids_arrindex}) {
my $EFfpkm_logprint=$EFseqid;
for (my $i=0; $i<scalar(@EFfpkms); $i++) {
if (! exists ${$EFfpkms[$i]}{$EFseqid}) {
${$EFfpkms[$i]}{$EFseqid}=0;
}
$EFfpkm_logprint.="\t".${$EFfpkms[$i]}{$EFseqid};
print "${EFsubinfo}Test: Bam ${$EFsamfiles_index}[$i]: Ref $EFseqid: ${$EFfpkms[$i]}{$EFseqid}\n" if ($BamKit_debug); ###Test###
}
# print FPKMLOG $EFfpkm_logprint."\n";
}
#Return format
#@EFfpkms=(
# (ref1 => fpkm1, ref2 => fpkm2, ...),
# (ref1 => fpkm1, ref2 => fpkm2, ...),
# ...)
#$EFfpkms[$ith]->{reference_id}=fpkm
unless (scalar(@{$EFsamfiles_index}) == scalar(@return_arr)) {
print STDERR "${EFsubinfo}Error: unequal list\n";
return $BamKit_failure;
}
return ($BamKit_success, \@return_arr);
}
### Calculate FPKM
### CalcFPKM(BAMin, $total_mapped_reads, readgroup aware(0/1), [$CFpath_samtools])
### Global:
### Dependency:
### Note:
sub CalcFPKM {
my ($CFbamin, $CFtotalmapreads, $CFrg_aware, $CFpath_samtools)=@_;
local *FPKMIN;
my $CFsubinfo='SUB(BamKit::CalcFPKM)';
$CFpath_samtools='samtools' unless (defined $CFpath_samtools);
unless (defined $CFbamin and -s $CFbamin) {
print STDERR "${CFsubinfo}Error: invalid BAM input\n";
return $BamKit_failure;
}