-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcrispr-plotr.pl
executable file
·2407 lines (2122 loc) · 95.7 KB
/
crispr-plotr.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
use warnings;
use strict;
use Pod::Usage;
use Getopt::Long;
use File::Basename;
=pod
=head1 NAME
crispr-plotr - Software to plot deletions and insertions from a CRISPR resequencing experiment
=head1 SYNOPSIS
crispr-plotr.pl [--ref_seq ref_seq.fa] [--label Sample31] --input crispr.bam --output Sampel31.pdf
=head1 DESCRIPTION
Briefly, this software takes a bam file with overlapping paired-end (PE) reads and call insertions
and deletions with respect to the reference sequence on the overlap.
From the input set of PE reads, it will filter out any pair where:
=over 8
=item * any of the reads does not map
=item * any of the reads is too short
=item * the reads do not overlap significantly
=item * have mutations or indels before or after the overlap
=item * have more than just a deletion or just an insertion in the overlap
=back
The output is a series of plots with overall stats on the number of PE reads that pass or not the
filters; the proportion of WT, insertions and deletions; the list of most common events; the
distributions of insertion and deletion sizes as well as the distribution of the locations of these
events; a scatter plot showing the relationship between both and one last plot with the frequency
of deletions per bp.
These plots are generated with R. The R script required to generate the plots is also stored in
the output folder and can be edited by the user to modify the plots if needed.
=head1 OPTIONS
Please note that options names may be abbreviated to uniqueness, case does not matter, and a
single dash is sufficient
=over 8
=item B<-h>|B<--help>
Prints the full help.
=item B<-i>|B<--input crispr.bam>
The BAM filename with the CRISPR aligned PE reads.
=item B<-o>|B<--output FILE.pdf>
By default, the output is PDF file. Other output are available and the filename will the same as
this one, but with the required extension.
=item B<--label LABEL>
Use this as the sample name for labelling the plots.
=item B<--guide-seq> guide_seq.fa>
This is a simple FASTA file (header is optional) with one sequence only (typically a very short one)
corresponding to the guide sequence. It must match perfectly the reference sequence.
You can either provide the full path to the file or simply the name of the file if it is located
in the INPUT_DIR.
Example:
---------------------------------------
AGGAGGTCCTA
---------------------------------------
=item B<--min-overlap 10>
Minimum overlap between the PE reads. Pairs that do not overlap by at least this length will be
filtered out.
=item B<--min-length 80>
Minimum length of the reads. If either read is shorter, the pair is filtered out
=item B<--allow-indels>
Do not filter out PE read that have indels in their flanking region, where the flanking region is
the region outside of the overlap, i.e. covered by one of the reads only.
=item B<--allow-muts>
Do not filter out PE read that have mutations in their flanking region, where the flanking region is
the region outside of the overlap, i.e. covered by one of the reads only.
=item B<--allow-any>
Sets the B<allow-indels> and B<allow-muts> flags to true.
=item B<--ref-seq>|B<--wt-seq> ref_seq.fa>
This is a simple FASTA file with one sequence only (typically a short one) corresponding to the expected
wild-type sequence, before editing has ocurred.
Example:
---------------------------------------
>sample_amplicon1_ref_123456
AACAGTGGGTCTTCGGGAACCAAGCAGCAGCCATGGGAGGTCTGGCTGTGTTCAGGCT
CTGCTCGTGTAGATTCACAGCGCGCTCTGAACCCCCGCTGAGCTACCGATGGAAGAGG
AGGAGGTCCTACAGTCGGAGATTCACAGCGCGCTCTGAACCACTTTCAGGAGACTCGA
CTATTATGACTTATACGCGATA
---------------------------------------
If not provided, the list of most common events is not displayed.
=item B<--plot-pdf>|B<--pdf> or B<--noplot-pdf>|B<--nopdf>
Enable or disable the PDF output.
Default: PDF output is enabled.
=item B<--plot-png>|B<--png> or B<--plot-nopng>|B<--nopng>
Enable or disable the PNG output.
Default: PNG output is disabled.
=item B<--plot-svg>|B<--svg> or B<--noplot-svg>|B<--nosvg>
Enable or disable the SVG output.
Default: SVG output is disabled.
=item B<--force-plots>
This options controls whether you want to obtain always the same number of plots or not. By default,
crispr-plotr skips the plots for which there is no data. For instance, the plot for insertions will
not be generated if there are no insertions in the input BAM file.
By using this option, you are requesting to always get an image even if there are no data.
Typically the plot will contain a simple message like "No insertions". This is useful if you wish
to embed the images in an automatically generated report for instance.
=back
=head1 Requirements
=over 8
=item B<R>: http://www.r-project.org
=back
=head1 INTERNAL METHODS
The rest of the documentation refers to the internal methods within this software and is
intended for developers only.
=cut
my $help;
my $label;
my $input_bam_file;
my $output_pdf_file;
my $debug;
my $ref_seq_file;
my $guide_seq_file;
my $min_overlap = 10;
my $min_length = 80;
my $allow_indels = 0;
my $allow_muts = 0;
my $allow_any = 0;
my $plot_pdf = 1;
my $plot_png = 0;
my $plot_svg = 0;
my $plot_all = 0;
my $force_plots = 0;
my $test = 0;
my $STAT_NO_ALIGNMENT = "No alignment";
my $STAT_SHORT_READ = "Short read";
my $STAT_NO_OVERLAP = "No overlap";
my $STAT_INDEL_5_PRIME = "5' indel";
my $STAT_MUTATION_5_PRIME = "5' mut";
my $STAT_INDEL_3_PRIME = "3' indel";
my $STAT_MUTATION_3_PRIME = "3' mut";
my $STAT_READ_MISMATCH = "Reads differ";
my $STAT_OTHER_MISMATCHES = "Other mismatches";
my $STAT_OK_WILD_TYPE = "WT";
my $STAT_OK_DELETION = "DEL";
my $STAT_OK_INSERTION = "INS";
my $STAT_OK_COMPLEX = "COM";
my @STAT_ORDER = (
$STAT_NO_ALIGNMENT,
$STAT_SHORT_READ,
$STAT_NO_OVERLAP,
$STAT_INDEL_5_PRIME,
$STAT_MUTATION_5_PRIME,
$STAT_INDEL_3_PRIME,
$STAT_MUTATION_3_PRIME,
$STAT_READ_MISMATCH,
$STAT_OTHER_MISMATCHES,
$STAT_OK_WILD_TYPE,
$STAT_OK_DELETION,
$STAT_OK_INSERTION,
$STAT_OK_COMPLEX,
);
my $COLOR_DELETION = "cyan3";
my $COLOR_INSERTION = "darkorchid3";
my $COLOR_COMPLEX = "#4d80cd";
my $STAT_COLOR = {
"$STAT_NO_ALIGNMENT" => "lightgrey",
"$STAT_SHORT_READ" => "grey",
"$STAT_NO_OVERLAP" => "darkgrey",
"$STAT_INDEL_5_PRIME" => "goldenrod1",
"$STAT_MUTATION_5_PRIME" => "goldenrod2",
"$STAT_INDEL_3_PRIME" => "goldenrod3",
"$STAT_MUTATION_3_PRIME" => "goldenrod4",
"$STAT_READ_MISMATCH" => "coral2",
"$STAT_OTHER_MISMATCHES" => "coral3",
"$STAT_OK_WILD_TYPE" => "white",
"$STAT_OK_DELETION" => $COLOR_DELETION,
"$STAT_OK_INSERTION" => $COLOR_INSERTION,
"$STAT_OK_COMPLEX" => $COLOR_COMPLEX,
};
GetOptions(
"help" => \$help,
"debug" => \$debug,
"test" => \$test,
"label=s" => \$label,
"input_file|input-file=s" => \$input_bam_file,
"output_file|output-file=s" => \$output_pdf_file,
"ref_seq|ref-seq|wt_file|wt-file|wt_seq|wt-seq=s" => \$ref_seq_file,
"guide_seq|guide-seq=s" => \$guide_seq_file,
"min_overlap|min-overlap=i" => \$min_overlap,
"min_length|min-length=i" => \$min_length,
"allow_indels|allow-indels|indels!" => \$allow_indels,
"allow_muts|allow-muts|muts!" => \$allow_muts,
"allow_any|allow-any|any!" => \$allow_any,
"plot_pdf|plot-pdf|pdf!" => \$plot_pdf,
"plot_png|plot-png|png!" => \$plot_png,
"plot_svg|plot-svg|svg!" => \$plot_svg,
"plot_all|plot-all!" => \$plot_all,
"force_plots|force-plots!" => \$force_plots,
);
if ($test) {
use Test::More;
test_merge_reads();
done_testing();
exit(0);
}
if ($help) {
pod2usage(-verbose=>2);
}
if (!$input_bam_file or !$output_pdf_file) {
pod2usage(-verbose=>1);
}
if (!$label) {
$label = $input_bam_file;
}
if ($allow_any) {
$allow_indels = 1;
$allow_muts = 1;
}
if ($plot_all) {
$plot_pdf = 1;
$plot_png = 1;
$plot_svg = 1;
}
my ($data_file, $stats) = parse_bam_file($input_bam_file);
my $total = 0;
foreach my $key (@STAT_ORDER) {
my $value = ($stats->{$key} or 0);
print "$key: $value\n";
$total += $value;
}
print "TOTAL: $total\n";
my $top_sequences = [];
my $ref_seq = "";
my $guide_seq = "";
if ($ref_seq_file) {
$ref_seq = read_fasta_seq($ref_seq_file);
if ($guide_seq_file) {
$guide_seq = read_fasta_seq($guide_seq_file);
}
my $wt = ($stats->{$STAT_OK_WILD_TYPE} or 0);
$top_sequences = get_top_sequences($ref_seq, $guide_seq, $data_file, $wt);
}
my $R_script = write_R_script($label, $data_file, $ref_seq, $guide_seq, $top_sequences, $stats, $output_pdf_file);
print qx"Rscript $R_script";
exit(0);
=head2 read_fasta_seq
Arg[1] : string $fasta_file
Example : my $seq = read_fasta_seq($fasta_file);
Description : Reads the sequence in the FASTA file $fasta_file
Returns : string $seq
Exceptions : Dies if any filename is not found.
=cut
sub read_fasta_seq {
my ($fasta_file) = @_;
my $seq;
open(FASTA, $fasta_file) or die "Cannot open FASTA file <$fasta_file>\n";
while (<FASTA>) {
chomp;
next if (/^>/);
$seq .= uc($_);
}
return $seq;
}
=head2 get_top_sequences
Arg[1] : string $ref_seq
Arg[2] : string $guide_seq
Arg[3] : string $data_filename
Arg[4] : integer $num_of_wild_type_seqs
Example : my $top_sequences = get_top_sequences($ref_seq, $guide_seq, $data_file, 1213);
Description : Reads from the $data_file the most common deletions and insertions (up to 10) and
aligns them to the wild-type sequence. Highlights the guide seq if provided.
Returns : arrayref of strings
Exceptions : prints WARNING if $guide_seq does not match $ref_seq
=cut
sub get_top_sequences {
my ($ref_seq, $guide_seq, $data_file, $wt) = @_;
my $top_sequences = [];
## ------------------------------------------------------------------------------
## Highlight the guide sequence (if provided) as uppercase vs lowercase
## ------------------------------------------------------------------------------
my $guide_start;
if ($guide_seq) {
$guide_start = index($ref_seq, $guide_seq);
if ($guide_start >= 0) {
substr($ref_seq, 0, $guide_start) = lc(substr($ref_seq, 0, $guide_start));
substr($ref_seq, $guide_start+length($guide_seq)) = lc(substr($ref_seq, $guide_start+length($guide_seq)));
print $ref_seq,"\n";
} else {
my $revcom_guide_seq = revcom($guide_seq);
$guide_start = index($ref_seq, $revcom_guide_seq);
if ($guide_start >= 0) {
substr($ref_seq, 0, $guide_start) = lc(substr($ref_seq, 0, $guide_start));
substr($ref_seq, $guide_start+length($guide_seq)) = lc(substr($ref_seq, $guide_start+length($guide_seq)));
print $ref_seq,"\n";
} else {
print STDERR "======================================================================\n";
print STDERR "WARNING: guide sequence ('$guide_seq') not found in amplicon sequence\n";
print STDERR "WARNING: guide sequence ('$revcom_guide_seq') not found in amplicon sequence\n";
print STDERR "======================================================================\n";
}
}
}
## ------------------------------------------------------------------------------
## Reads and extract stats on most common deletions and insertions:
## ------------------------------------------------------------------------------
my @del_lines = qx"more $data_file | awk '\$2 == \"DEL\" { print \$3, \$4, \$7}' | sort | uniq -c | sort -rn";
my @ins_lines = qx"more $data_file | awk '\$2 == \"INS\" { print \$3, \$4, \$7}' | sort | uniq -c | sort -rn";
my @com_lines = qx"more $data_file | awk '\$2 == \"COM\" { print \$3, \$4, \$7}' | sort | uniq -c | sort -rn";
## ------------------------------------------------------------------------------
## Calculates the region of the REF sequence to display
## ------------------------------------------------------------------------------
my $min_from;
my $max_to;
my $longest_seq = 0;
# Include the guide sequence if available
if ($guide_start) {
$min_from = $guide_start + 1;
$max_to = $guide_start + length($guide_seq);
}
# Expand as necessary to cover all deletion and complex cases
foreach my $this_line (@del_lines, @com_lines) {
my ($num, $del_length, $from, $seq) = $this_line =~ /(\d+)\s(\-?\d+)\s(\d+)\s(\w+)/;
$min_from = $from if (!$min_from or $from < $min_from);
$max_to = $from+$del_length if (!$max_to or $from+$del_length > $max_to);
$longest_seq = length($seq) if ($longest_seq < length($seq));
}
# Same for insertions (except that insertions are of length 0 in ref coordinates)
foreach my $this_line (@ins_lines) {
my ($num, $ins_length, $from, $seq) = $this_line =~ /(\d+)\s(\-?\d+)\s(\d+)\s(\w+)/;
$min_from = $from - 1 if (!$min_from or $from - 1 < $min_from);
$max_to = $from if (!$max_to or $from > $max_to);
$longest_seq = length($seq) + 2 if ($longest_seq < length($seq) + 2);
}
# Just in case there are no guide sequence nor deletions nor insertions
if (!defined($max_to)) {
$max_to = int(length($ref_seq) / 2) + 10;
$min_from = $max_to - 10;
}
# Expand the sequence a little further to give more context
$min_from -= 20;
$min_from = 1 if ($min_from < 1);
$max_to += 19;
## ------------------------------------------------------------------------------
## Sets the output format (using whitespaces to be nicely printed in R afterewards)
## ------------------------------------------------------------------------------
my $format = "\%-".($max_to - $min_from + 1)."s \%7s \%-4s \%3s \%6s \%-${longest_seq}s";
## ------------------------------------------------------------------------------
## Header and WT sequence
## ------------------------------------------------------------------------------
my $header = sprintf($format, "Sequence" , "Num", "TYPE", "L", "POS", "Diff");
my $wt_sequence = sprintf($format, substr($ref_seq, $min_from - 1, $max_to - $min_from), $wt, "WT", 0, "NA", "");
$top_sequences = [$header, "", $wt_sequence, ""];
## ------------------------------------------------------------------------------
## Most common deletions
## ------------------------------------------------------------------------------
my $del_sequences_hash = {};
foreach my $this_line (@del_lines) {
my ($num, $del_length, $from, $seq) = $this_line =~ /(\d+)\s(\-?\d+)\s(\d+)\s(\w+)/;
my $aligned_seq = substr($ref_seq, ($min_from - 1), ($from - $min_from)) .
'-' x $del_length .
substr($ref_seq, ($from + $del_length - 1), $max_to - ($from + $del_length - 1));
my $resulting_seq = substr($ref_seq, ($min_from - 1), ($from - $min_from)) .
substr($ref_seq, ($from + $del_length - 1), $max_to - ($from + $del_length - 1));
if ($del_sequences_hash->{$resulting_seq}) {
$del_sequences_hash->{$resulting_seq}->{num} += $num;
} else {
$del_sequences_hash->{$resulting_seq}->{aligned_seq} = $aligned_seq;
$del_sequences_hash->{$resulting_seq}->{num} = $num;
$del_sequences_hash->{$resulting_seq}->{del_length} = $del_length;
$del_sequences_hash->{$resulting_seq}->{from} = $from;
$del_sequences_hash->{$resulting_seq}->{seq} = $seq;
}
}
my @del_sequences = map {
sprintf($format, $del_sequences_hash->{$_}->{aligned_seq}, $del_sequences_hash->{$_}->{num},
"DEL", $del_sequences_hash->{$_}->{del_length}, $del_sequences_hash->{$_}->{from},
">".$del_sequences_hash->{$_}->{seq}."<")
} (sort {$del_sequences_hash->{$b}->{num} <=> $del_sequences_hash->{$a}->{num} ||
$del_sequences_hash->{$a}->{del_length} <=> $del_sequences_hash->{$b}->{del_length}
} keys $del_sequences_hash);
my $deletions_file = $data_file;
$deletions_file =~ s/\.txt$/.del.txt/;
open(DEL, ">$deletions_file") or die;
print DEL join("\n", $header, $wt_sequence, "", @del_sequences, "");
close(DEL);
push(@$top_sequences, splice(@del_sequences, 0, 18));
## ------------------------------------------------------------------------------
## Separation line
## ------------------------------------------------------------------------------
push(@$top_sequences, "");
## ------------------------------------------------------------------------------
## Most common insertions
## ------------------------------------------------------------------------------
my $ins_sequences_hash = {};
foreach my $this_line (@ins_lines) {
my ($num, $ins_length, $from, $seq) = $this_line =~ /(\d+)\s(\-?\d+)\s(\d+)\s(\w+)/;
my $aligned_seq = substr($ref_seq, $min_from - 1, $max_to - $min_from + 1);
substr($aligned_seq, $from - $min_from - 1, 2, "><");
my $resulting_seq = substr($ref_seq, $min_from - 1, $max_to - $min_from + 1);
substr($resulting_seq, $from - $min_from, 0, $seq);
if ($ins_sequences_hash->{$resulting_seq}) {
$ins_sequences_hash->{$resulting_seq}->{num} += $num;
} else {
$ins_sequences_hash->{$resulting_seq}->{aligned_seq} = $aligned_seq;
$ins_sequences_hash->{$resulting_seq}->{num} = $num;
$ins_sequences_hash->{$resulting_seq}->{ins_length} = $ins_length;
$ins_sequences_hash->{$resulting_seq}->{from} = $from;
$ins_sequences_hash->{$resulting_seq}->{seq} = $seq;
}
}
my @ins_sequences = map {
sprintf($format, $ins_sequences_hash->{$_}->{aligned_seq}, $ins_sequences_hash->{$_}->{num},
"INS", $ins_sequences_hash->{$_}->{ins_length}, $ins_sequences_hash->{$_}->{from},
">".$ins_sequences_hash->{$_}->{seq}."<")
} (sort {$ins_sequences_hash->{$b}->{num} <=> $ins_sequences_hash->{$a}->{num} ||
$ins_sequences_hash->{$a}->{ins_length} <=> $ins_sequences_hash->{$b}->{ins_length}
} keys $ins_sequences_hash);
my $insertions_file = $data_file;
$insertions_file =~ s/\.txt$/.ins.txt/;
open(INS, ">$insertions_file") or die;
print INS join("\n", $header, $wt_sequence, "", @ins_sequences, "");
close(INS);
push(@$top_sequences, splice(@ins_sequences, 0, 18));
## ------------------------------------------------------------------------------
## Separation line
## ------------------------------------------------------------------------------
push(@$top_sequences, "");
## ------------------------------------------------------------------------------
## Most common complex cases
## ------------------------------------------------------------------------------
my $com_sequences_hash = {};
foreach my $this_line (@com_lines) {
my ($num, $com_length, $from, $seq) = $this_line =~ /(\d+)\s(\-?\d+)\s(\d+)\s(\w+)/;
my $aligned_seq = substr($ref_seq, $min_from - 1, $max_to - $min_from + 1);
substr($aligned_seq, $from - $min_from - 1, $com_length + 2, ">" . ("-" x $com_length) . "<");
my $resulting_seq = substr($ref_seq, $min_from - 1, $max_to - $min_from + 1);
substr($resulting_seq, $from - $min_from, $com_length, $seq);
if ($com_sequences_hash->{$resulting_seq}) {
$com_sequences_hash->{$resulting_seq}->{num} += $num;
} else {
$com_sequences_hash->{$resulting_seq}->{aligned_seq} = $aligned_seq;
$com_sequences_hash->{$resulting_seq}->{num} = $num;
$com_sequences_hash->{$resulting_seq}->{com_length} = $com_length;
$com_sequences_hash->{$resulting_seq}->{from} = $from;
$com_sequences_hash->{$resulting_seq}->{seq} = $seq;
}
}
my @com_sequences = map {
sprintf($format, $com_sequences_hash->{$_}->{aligned_seq}, $com_sequences_hash->{$_}->{num},
"COM", $com_sequences_hash->{$_}->{com_length}, $com_sequences_hash->{$_}->{from},
">".$com_sequences_hash->{$_}->{seq}."<")
} (sort {$com_sequences_hash->{$b}->{num} <=> $com_sequences_hash->{$a}->{num} ||
$com_sequences_hash->{$a}->{com_length} <=> $com_sequences_hash->{$b}->{com_length}
} keys $com_sequences_hash);
my $complex_file = $data_file;
$complex_file =~ s/\.txt$/.com.txt/;
open(COM, ">$complex_file") or die;
print COM join("\n", $header, $wt_sequence, "", @com_sequences, "");
close(COM);
push(@$top_sequences, splice(@com_sequences, 0, 18));
# Print this on the standard output
print "\n", join("\n", @$top_sequences), "\n";
# Return the lines (as an arrayref)
return $top_sequences;
}
=head2 parse_bam_file
Arg[1] : string $bam_filename
Example : my ($data_filename, $stats) = parse_bam_file($bam_file);
Description : Extracts from the $bam_file all the PE reads that match all the criteria (aligned,
> min_length, good overlap, no indel or mismatch before or after the overlap,
perfect match between both reads and just a single insertion or deletion (but no
mismatches) w.r.t. the ref sequence in the overlap
Returns : array of $data_filename and $stats. These are:
- string with the filename where the resulting insertion and deletions have been
stored
- hashref of keys (event) and values (number of these events)
Exceptions : Dies if it cannot open the file with samtools
=cut
sub parse_bam_file {
my ($bam_file) = @_;
my $stats;
open(SAM, "samtools view $bam_file |") or die;
my $data_file = "$bam_file.data.txt";
open(DATA, ">$data_file");
print DATA join("\t", "read", "event", "event_length", "from", "to", "midpoint", "seq"), "\n";
while (<SAM>) {
## ------------------------------------------------------------------------------
## Read both lines (assuming unsorted BAM file)
## ------------------------------------------------------------------------------
chomp;
my ($qname1, $flag1, $rname1, $pos1, $mapq1, $cigar1, $rnext1, $pnext1, $tlen1, $seq1, $qual1, @others1) = split("\t", $_);
$_ = <SAM>;
chomp;
my ($qname2, $flag2, $rname2, $pos2, $mapq2, $cigar2, $rnext2, $pnext2, $tlen2, $seq2, $qual2, @others2) = split("\t", $_);
my $md1 = (grep {/^MD:Z:/} @others1)[0];
my $md2 = (grep {/^MD:Z:/} @others2)[0];
my $end1 = $pos1 + length($seq1);
my $end2 = $pos2 + length($seq2);
if ($debug) {
print join("\t", $qname1, $flag1, $rname1, $pos1, $mapq1, $cigar1, $rnext1, $pnext1, $tlen1), "\n";
print join("\t", $qname2, $flag2, $rname2, $pos2, $mapq2, $cigar2, $rnext2, $pnext2, $tlen2), "\n";
}
my $read1 = {
'seq' => $seq1,
'qual' => $qual1,
'start' => $pos1,
'cigar' => $cigar1,
'md' => $md1};
my $read2 = {
'seq' => $seq2,
'qual' => $qual2,
'start' => $pos2,
'cigar' => $cigar2,
'md' => $md2};
## ------------------------------------------------------------------------------
## Check that both lines refer to the same read
## ------------------------------------------------------------------------------
if ($qname1 ne $qname2) {
die "SAM file sorted or not for PE reads\n";
}
die "SAM file seems to have been sorted in some way. PE reads are not consecutive\n" if ($rname1 ne $rname2);
## ------------------------------------------------------------------------------
## Check that both reads align (i.e., they have a cigar string)
## ------------------------------------------------------------------------------
if ($cigar1 eq "*" or $cigar2 eq "*") {
$stats->{$STAT_NO_ALIGNMENT}++;
next;
}
## ------------------------------------------------------------------------------
## Check that both reads are long enough
## ------------------------------------------------------------------------------
if (length($seq1) < $min_length or length($seq2) < $min_length) {
$stats->{$STAT_SHORT_READ}++;
next;
}
## ------------------------------------------------------------------------------
## Merge the reads and check for exceptions
## ------------------------------------------------------------------------------
my $merged_read = merge_reads($read1, $read2);
if (exists($merged_read->{'error'})) {
$stats->{$merged_read->{'error'}}++;
next;
}
if (!$allow_indels and $merged_read->{'5prime'}{'cigar'} !~ /^\d+M$/) {
$stats->{$STAT_INDEL_5_PRIME}++;
next;
}
if (!$allow_muts and $merged_read->{'5prime'}{'md'} !~ /^MD:Z:\d+$/) {
$stats->{$STAT_MUTATION_5_PRIME}++;
next;
}
if (!$allow_indels and $merged_read->{'3prime'}{'cigar'} !~ /^\d+M$/) {
$stats->{$STAT_INDEL_3_PRIME}++;
next;
}
if (!$allow_muts and $merged_read->{'3prime'}{'md'} !~ /^MD:Z:\d+$/) {
$stats->{$STAT_MUTATION_3_PRIME}++;
next;
}
my $cigar_overlap = $merged_read->{'overlap'}{'cigar'};
my $md_overlap = $merged_read->{'overlap'}{'md'};
if ($md_overlap =~ /^MD:Z:\d+\^[A-Z]+\d+$/ and $cigar_overlap =~ /^(\d+M)?\d+D(\d+M)?$/) {
$stats->{$STAT_OK_DELETION}++;
my ($deletion_start) = ($cigar_overlap =~ /^(\d+)M/);
my ($deletion_length) = $cigar_overlap =~ /(\d+)D/;
my ($deletion_seq) = $md_overlap =~ /^MD:Z:\d+\^([A-Z]+)\d+$/;
my $from = $merged_read->{'overlap'}{'start'} + ($deletion_start or 0);
my $to = $from + $deletion_length - 1;
my $midpoint = $from + ($deletion_length - 1)/2;
print DATA join("\t", $qname1, "DEL", $deletion_length, $from, $to, $midpoint, $deletion_seq), "\n";
} elsif ($md_overlap =~ /^MD:Z:\d+$/ and $cigar_overlap =~ /^\d+M\d*I\d+M$/) {
$stats->{$STAT_OK_INSERTION}++;
my ($insertion_start) = $cigar_overlap =~ /^(\d+)M/;
my ($insertion_length) = $cigar_overlap =~ /(\d+)I/;
my $from = $merged_read->{'overlap'}{'start'} + ($insertion_start or 0);
my $to = $from - 1;
my $midpoint = $from - 1/2;
my $insertion_seq = substr($merged_read->{'overlap'}{'seq'}, ($insertion_start or 0), $insertion_length);
print DATA join("\t", $qname1, "INS", $insertion_length, $from, $to, $midpoint, $insertion_seq), "\n";
} elsif ($md_overlap =~ /^MD:Z:\d+$/ and $cigar_overlap =~ /^\d+M$/) {
$stats->{$STAT_OK_WILD_TYPE}++;
} elsif ($cigar_overlap !~ /^\d+M$/) {
$stats->{$STAT_OK_COMPLEX}++;
my ($event_5prime_md) = ($md_overlap =~ /^MD:Z:(\d+)/);
$event_5prime_md ||= 0;
my ($event_5prime_cigar) = ($cigar_overlap =~ /^(\d+)M/);
$event_5prime_cigar ||= 0;
# $event_5prime_length is the length of the sequence in the overlap that is identical to the WT seq
my $event_5prime_length = $event_5prime_md>$event_5prime_cigar?$event_5prime_cigar:$event_5prime_md;
my ($event_3prime_md) = ($md_overlap =~ /(\d+)$/);
$event_3prime_md ||= 0;
my ($event_3prime_cigar) = ($cigar_overlap =~ /(\d+)M$/);
$event_3prime_cigar ||= 0;
# $event_3prime_length is the length of the sequence in the overlap that is identical to the WT seq
my $event_3prime_length = $event_3prime_md>$event_3prime_cigar?$event_3prime_cigar:$event_3prime_md;
my $from = $merged_read->{'overlap'}{'start'} + $event_5prime_length;
my $to = $merged_read->{'overlap'}{'end'} - $event_3prime_length;
my $midpoint = ($from + $to)/2;
my $complex_seq = $merged_read->{'overlap'}{'seq'};
substr($complex_seq, 0, $event_5prime_length, "");
substr($complex_seq, -$event_3prime_length, $event_3prime_length, "");
print DATA join("\t", $qname1, "COM", ($to - $from + 1), $from, $to, $midpoint, $complex_seq), "\n";
# print "$cigar_overlap $md_overlap $event_5prime_length-$event_3prime_length $complex_seq\n";
# <STDIN>;
}
}
close(SAM);
close(DATA);
return ($data_file, $stats);
}
sub revcom {
my ($seq) = @_;
$seq = reverse($seq);
$seq =~ tr/ACTG/TGAC/;
return $seq;
}
sub get_cigar_expanded_string {
my ($cigar_compact_string) = @_;
my $cigar_expanded_string = "";
my @cigars = ($cigar_compact_string =~ /(\d*)(\w)/g);
for (my $i=0; $i < @cigars; $i+=2) {
$cigar_expanded_string .= $cigars[$i+1] x $cigars[$i];
}
return $cigar_expanded_string;
}
sub get_cigar_compact_string {
my ($cigar_expanded_string) = @_;
my $cigar_compact_string = "";
while ($cigar_expanded_string =~ /^((.)\g2*)/) {
$cigar_compact_string .= length($1).substr($1,0,1);
$cigar_expanded_string =~ s/^$1//;
}
return $cigar_compact_string;
}
sub get_md_expanded_string {
my ($md_compact_string) = @_;
my $md_expanded_string = "";
$md_compact_string =~ s/^MD:Z://;
my @mds = grep {$_} split(/(\d+)/, $md_compact_string);
foreach my $md_bit (@mds) {
if ($md_bit =~ /^\d+$/) {
# Matches: write dots
$md_expanded_string .= "." x $md_bit;
} elsif ($md_bit =~ /^[A-Z]+$/) {
# Mismatches: write lowercase
$md_expanded_string .= lc($md_bit);
} elsif ($md_bit =~ /^\^[A-Z]+$/) {
# Deletions: write uppercase
$md_expanded_string .= substr($md_bit, 1);
} else {
die "Cannot understand MD:Z flag.\n";
}
}
$md_expanded_string =~ s/n/./g;
return $md_expanded_string;
}
sub get_md_compact_string {
my ($md_expanded_string) = @_;
my $md_compact_string = "MD:Z:";
my $last_md_bit_mode = "";
while ($md_expanded_string =~ /^(\^?(.)\g2*)/) {
my $md_bit = $1;
if ($md_bit =~ /^\.+$/) {
$md_compact_string .= length($md_bit);
$last_md_bit_mode = "match";
} elsif ($md_bit =~ /^[a-z]+$/) {
if ($last_md_bit_mode eq "deletion") {
$md_compact_string .= "0";
}
$md_compact_string .= join("0", split("", uc($md_bit)));
$last_md_bit_mode = "mismatch";
} elsif ($md_bit =~ /^[A-Z]+$/) {
$md_compact_string .= ($last_md_bit_mode ne "deletion"?"^":"").$md_bit;
$last_md_bit_mode = "deletion";
} else {
die "Cannot understand MD:Z flag: $md_expanded_string.\n";
}
$md_expanded_string =~ s/^$md_bit//;
}
return $md_compact_string;
}
sub merge_reads {
my ($read1, $read2) = @_;
## ------------------------------------------------------------------------
## Extract values from structure
## ------------------------------------------------------------------------
my $start1 = $read1->{start};
my $cigar1 = $read1->{cigar};
my $md1 = $read1->{md};
my $seq1 = $read1->{seq};
my $qual1 = $read1->{qual};
my $start2 = $read2->{start};
my $cigar2 = $read2->{cigar};
my $md2 = $read2->{md};
my $seq2 = $read2->{seq};
my $qual2 = $read2->{qual};
## ------------------------------------------------------------------------
## Swap read1 and read2 if necessary
## ------------------------------------------------------------------------
if ($start2 < $start1) {
($start1, $start2) = ($start2, $start1);
($cigar1, $cigar2) = ($cigar2, $cigar1);
($md1, $md2) = ($md2, $md1);
($seq1, $seq2) = ($seq2, $seq1);
($qual1, $qual2) = ($qual2, $qual1);
}
## ------------------------------------------------------------------------
## Get expanded cigar and md strings
## ------------------------------------------------------------------------
my $cigar_str1 = get_cigar_expanded_string($cigar1);
my $cigar_str2 = get_cigar_expanded_string($cigar2);
my $md_str1 = get_md_expanded_string($md1);
my $md_str2 = get_md_expanded_string($md2);
## ------------------------------------------------------------------------
## Get some coordinates for unique and overlapping sequence
## ------------------------------------------------------------------------
my $end1 = $start1 + length($seq1) - ($cigar_str1 =~ tr/I/I/) + ($cigar_str1 =~ tr/D/D/) - 1;
my $end2 = $start2 + length($seq2) - ($cigar_str2 =~ tr/I/I/) + ($cigar_str2 =~ tr/D/D/) - 1;
my $ref_length_5prime_unique = $start2 - $start1;
my $ref_length_3prime_unique = $end2 - $end1;
my $ref_start_overlap = $start2;
my $ref_end_overlap = $end1;
my $ref_length_overlap = $end1 - $start2 + 1;
if ($debug) {
print "\n\n###########################################################################\n";
print join("\n", "$start1-$end1 in ref coordinates", $seq1, $qual1, $cigar_str1." ($cigar1)", $md_str1." ($md1)"), "\n";
print "###########################################################################\n";
print join("\n", "$start2-$end2 in ref coordinates", $seq2, $qual2, $cigar_str2." ($cigar2)", $md_str2." ($md2)"), "\n";
print "###########################################################################\n\n";
}
if ($end1 - $start2 + 1 < $min_overlap) {
# Reads don't overlap.
return {'error' => $STAT_NO_OVERLAP};
}
if ($end1 > $end2) {
# Read2 fully included in read1: skip this odd pair.
return {'error' => $STAT_NO_OVERLAP};
}
## ------------------------------------------------------------------------
## Get info for the 5' unique sequence
## ------------------------------------------------------------------------
my ($cigar_5prime_unique) = ($cigar_str1 =~ /^((?:I*[MD]){$ref_length_5prime_unique}I*)/);
my $seq_length_5prime_unique = ($cigar_5prime_unique =~ tr/MI/MI/);
## If overlap starts in an insertion:
my $length_insertion_end_5prime_unique = length(($cigar_5prime_unique =~ /(I*)$/)[0]);
my $length_insertion_start_read2 = length(($cigar_str2 =~ /^(I*)/)[0]);
if ($length_insertion_end_5prime_unique > 0 and $length_insertion_start_read2 > 0) {
if ($debug) {
print " -- Trimming end of 5' unique required: ${length_insertion_end_5prime_unique}I vs ${length_insertion_start_read2}I\n";
}
if ($length_insertion_end_5prime_unique >= $length_insertion_start_read2) {
# Insertion in 5' unique is the same or longer: just trim it to remove the overlapping sequence
$cigar_5prime_unique =~ s/I{$length_insertion_start_read2}$//;
$seq_length_5prime_unique -= $length_insertion_start_read2;
} else {
return {'error' => $STAT_READ_MISMATCH};
}
}
my ($seq_5prime_unique) = substr($seq1, 0, $seq_length_5prime_unique);
my ($qual_5prime_unique) = substr($qual1, 0, $seq_length_5prime_unique);
my $md_length_5prime_unique = ($cigar_5prime_unique =~ tr/MD/MD/);
my ($md_5prime_unique) = substr($md_str1, 0, $md_length_5prime_unique);
if ($debug) {
print "5' sequence:\n$seq_5prime_unique\n$qual_5prime_unique\n$cigar_5prime_unique\n$md_5prime_unique\n\n";
}
## ------------------------------------------------------------------------
## Get info for the 3' unique sequence
## ------------------------------------------------------------------------
my ($cigar_3prime_unique) = ($cigar_str2 =~ /(I*(?:I*[MD]){$ref_length_3prime_unique})$/);
my $seq_length_3prime_unique = ($cigar_3prime_unique =~ tr/MI/MI/);
## If overlap ends in an insertion:
my $length_insertion_start_3prime_unique = length(($cigar_3prime_unique =~ /^(I*)/)[0]);
my $length_insertion_end_read1 = length(($cigar_str1 =~ /(I*)$/)[0]);
if ($length_insertion_start_3prime_unique > 0 and $length_insertion_end_read1 > 0) {
if ($debug) {
print " -- Trimming start of 3' unique required: ${length_insertion_start_3prime_unique}I vs ${length_insertion_end_read1}I\n";
}
if ($length_insertion_start_3prime_unique >= $length_insertion_end_read1) {
# Insertion in 3' unique is the same or longer: just trim it to remove the overlapping sequence
$cigar_3prime_unique =~ s/^I{$length_insertion_end_read1}//;
$seq_length_3prime_unique -= $length_insertion_end_read1;
} else {
return {'error' => $STAT_READ_MISMATCH};
}
}
my ($seq_3prime_unique) = substr($seq2, -$seq_length_3prime_unique);
my ($qual_3prime_unique) = substr($qual2, -$seq_length_3prime_unique);
my $md_length_3prime_unique = ($cigar_3prime_unique =~ tr/MD/MD/);
my ($md_3prime_unique) = substr($md_str2, -$md_length_3prime_unique);
if ($debug) {
print "3' sequence:\n$seq_3prime_unique\n$qual_3prime_unique\n$cigar_3prime_unique\n$md_3prime_unique\n\n";
}
## ------------------------------------------------------------------------
## Get info for the overlapping sequence
## ------------------------------------------------------------------------
my $seq_length_overlapping_sequence1 = length($seq1) - $seq_length_5prime_unique;
my $seq_length_overlapping_sequence2 = length($seq2) - $seq_length_3prime_unique;
my $seq_overlap1 = substr($seq1, $seq_length_5prime_unique);
my $seq_overlap2 = substr($seq2, 0, -$seq_length_3prime_unique);
my $qual_overlap1 = substr($qual1, $seq_length_5prime_unique);
my $qual_overlap2 = substr($qual2, 0, -$seq_length_3prime_unique);
my $cigar_overlap1 = $cigar_str1;
$cigar_overlap1 =~ s/^$cigar_5prime_unique//;
my $cigar_overlap2 = $cigar_str2;
$cigar_overlap2 =~ s/$cigar_3prime_unique$//;
my $md_overlap1 = $md_str1;
$md_overlap1 =~ s/^$md_5prime_unique//;
my $md_overlap2 = $md_str2;
$md_overlap2 =~ s/$md_3prime_unique$//;
if ($debug) {
print "overlapping sequence:\n$seq_overlap1\n$seq_overlap2\n",
"$qual_overlap1\n$qual_overlap2\n",
"$cigar_overlap1\n$cigar_overlap2\n",
"$md_overlap1\n$md_overlap2\n",
;
}
# if ($cigar_overlap1 ne $cigar_overlap2) {
# print "Cigar strings don't match\n";
# }
# if ($md_overlap1 ne $md_overlap2) {
# print "MD strings don't match\n";
# }
# if ($seq_length_overlapping_sequence1 != $seq_length_overlapping_sequence2) {
# print "Error parsing sequences. Overlapping sequence lengths do not match\n";
# <STDIN>;
# return {'error' => "Overlapping sequences do not match"};
# }
if ($debug and