blib/lib/Bio/Graphics/Glyph/segments.pm untested

filter: Statementstmt 0.0% 0 / 597 Branchbran 0.0% 0 / 292 Conditioncond 0.0% 0 / 200 MC/DCmcdc n/a Subroutinesub 0.0% 0 / 39 Podpod 0.0% 0 / 27 totaltotal 0.0% 0 / 1155 CC 147 SCAR 74.5
CC
147
Cov
0%
draw_multiple_alignment
4556.0
draw_component
506.0
_split_on_cigar
72.0
CRAP 1725.7
1 package Bio::Graphics::Glyph::segments;
2  
3 use strict;
4 use Bio::Location::Simple;
5  
6 use constant RAGGED_START_FUZZ => 25; # will show ragged ends of alignments
7 # up to this many bp.
8 use constant DEBUG => 0;
9  
10 # These are just offsets into an array data structure
11 use constant TARGET => 0;
12 use constant SRC_START => 1;
13 use constant SRC_END => 2;
14 use constant TGT_START => 3;
15 use constant TGT_END => 4;
16  
17 eval { require Bio::Graphics::Browser2::Realign; 1; } || eval { require Bio::Graphics::Browser::Realign; };
18  
19 use base qw(Bio::Graphics::Glyph::segmented_keyglyph Bio::Graphics::Glyph::generic);
20  
21 my %complement = (g=>'c',a=>'t',t=>'a',c=>'g',n=>'n',
22 G=>'C',A=>'T',T=>'A',C=>'G',N=>'N');
23  
24 sub my_description {
25 return <<END;
26 This glyph draws multipart genomic features as a series of rectangles connected
27 by solid lines. If the feature is attached to a DNA sequence, then the glyph will
28 draw the sequence when magnification is high enough to show individual base pairs.
29 The glyph is also capable of drawing genomic alignments, and performing protein
30 translations.
31 END
32 }
33 sub my_options {
34 {
35 draw_target => [
36 'boolean',
37 undef,
38 'If true, draw the dna residues of the TARGET (aligned) sequence when the',
39 'magnification level allows.',
40 'See L<Bio::Graphics::Glyph::segments/"Displaying Alignments">.'
41 ],
42 draw_protein_target => [
43 'boolean',
44 undef,
45 'If true, draw the protein residues of the TARGET (aligned) sequence when the',
46 'magnification level allows.',
47 'See L<Bio::Graphics::Glyph::segments/"Displaying Alignments">.'],
48 ragged_extra => [
49 'boolean',
50 undef,
51 'When combined with -draw_target, draw extra bases beyond the end',
52 'of the alignment. The value is the maximum number of extra bases.',
53 'See L<Bio::Graphics::Glyph::segments/"Displaying Alignments">.'],
54 show_mismatch => [
55 'integer',
56 undef,
57 'When combined with -draw_target, highlights mismatched bases in',
58 'the mismatch color. A value of 0 or undef never shows mismatches.',
59 'A value of 1 shows mismatches at the base pair alignment level, but',
60 'not at magnifications too low to allow the DNA to be displayed.',
61 'Any other positive integer will show mismatches when the track is showing',
62 'a region less than or equal to the specified value.',
63 'See L<Bio::Graphics::Glyph::segments/"Displaying Alignments">.'],
64 mismatch_color => [
65 'color',
66 'lightgrey',
67 'The color to use for mismatched bases when displaying alignments.',
68 'See L<Bio::Graphics::Glyph::segments/"Displaying Alignments">.'],
69 indel_color => [
70 'color',
71 'lightgrey',
72 'The color to use for indels when displaying alignments.'],
73 insertion_color => [
74 'color',
75 'green',
76 'The color to use for insertions when displaying alignments; overrides indel_color'],
77 deletion_color => [
78 'color',
79 'red',
80 'The color to use for deletions when displaying alignments; overrides indel_color'],
81 mismatch_only => [
82 'boolean',
83 undef,
84 'If true, only print mismatched bases when displaying alignments.'],
85 true_target => [
86 'boolean',
87 undef,
88 'Show the target DNA in its native (plus strand) orientation, even',
89 'if the alignment is to the minus strand.',
90 'See L<Bio::Graphics::Glyph::segments/"Displaying Alignments">.'],
91 split_on_cigar => [
92 'boolean',
93 undef,
94 'If true, and if the feature contains a CIGAR string as the value of the Gap',
95 'tag, then split the feature into subparts based on the CIGAR.'],
96 realign => [
97 'boolean',
98 undef,
99 'Attempt to realign sequences at high magnification to account',
100 'for indels.',
101 'See L<Bio::Graphics::Glyph::segments/"Displaying Alignments">.'],
102 }
103 }
104  
105 sub mismatch_color {
106 my $self = shift;
107 my $c = $self->option('mismatch_color') || 'lightgrey';
108 return $self->translate_color($c);
109 }
110  
111 sub indel_color {
112 my $self = shift;
113 my $c = $self->option('indel_color');
114 return $self->mismatch_color unless $c;
115 return $self->translate_color($c);
116 }
117  
118 sub insertion_color {
119 my $self = shift;
120 my $c = $self->option('insertion_color');
121 $c ||= $self->option('indel_color');
122 $c ||= $self->my_options->{insertion_color}[1];
123 return $self->translate_color($c);
124 }
125  
126 sub deletion_color {
127 my $self = shift;
128 my $c = $self->option('deletion_color');
129 $c ||= $self->option('indel_color');
130 $c ||= $self->my_options->{deletion_color}[1];
131 return $self->translate_color($c);
132 }
133  
134 sub show_mismatch {
135 my $self = shift;
136 my $smm = $self->option('show_mismatch');
137 $smm ||= 1 if $self->option('mismatch_only');
138 return unless $smm;
139 return 1 if $smm == 1 && $self->dna_fits;
140 return 1 if $smm >= $self->panel->length;
141 }
142  
143 sub mismatch_only { shift->option('mismatch_only') }
144  
145  
146 sub pad_left {
147 my $self = shift;
148 return $self->SUPER::pad_left unless $self->level > 0;
149 my $ragged = $self->option('ragged_start')
150 ? RAGGED_START_FUZZ
151 : $self->option('ragged_extra');
152  
153 return $self->SUPER::pad_left
154 unless $self->draw_target && $ragged && $self->dna_fits;
155 my $extra = 0;
156 my $target = eval {$self->feature->hit} or return $self->SUPER::pad_left + $extra;
157 return $self->SUPER::pad_left + $extra unless $target->start<$target->end && $target->start < $ragged;
158 return ($target->start-1) * $self->scale + $extra;
159 }
160  
161 sub pad_right {
162 my $self = shift;
163 return $self->SUPER::pad_right unless $self->level > 0;
164 my $ragged = $self->option('ragged_start')
165 ? RAGGED_START_FUZZ
166 : $self->option('ragged_extra');
167 return $self->SUPER::pad_right
168 unless $self->draw_target && $ragged && $self->dna_fits;
169 my $target = eval {$self->feature->hit} or return $self->SUPER::pad_right;
170 return $self->SUPER::pad_right unless $target->end < $target->start && $target->start < $ragged;
171 return ($target->end-1) * $self->scale;
172 }
173  
174 sub labelwidth {
175 my $self = shift;
176 return $self->SUPER::labelwidth unless $self->draw_target && $self->dna_fits && $self->label_position eq 'left';
177 return $self->{labelwidth} ||= (length($self->label||'')+1) * $self->mono_font->width;
178 }
179 sub draw_target {
180 my $self = shift;
181 return if $self->option('draw_dna');
182 return $self->option('draw_target');
183 }
184  
185 sub draw_protein_target {
186 my $self = shift;
187 return if $self->option('draw_protein');
188 return $self->option('draw_protein_target');
189 return $self->option('draw_target');
190 }
191  
192 sub height {
193 my $self = shift;
194 my $height = $self->SUPER::height;
195 return $height unless $self->draw_target || $self->draw_protein_target;
196 if ($self->draw_target) {
197 return $height unless $self->dna_fits;
198 }
199 if ($self->draw_protein_target) {
200 return $height unless $self->protein_fits;
201 }
202 my $fontheight = $self->mono_font->height;
203 return $fontheight if $fontheight > $height;
204 }
205  
206 # group sets connector to 'solid'
207 sub connector {
208 my $self = shift;
209 return $self->SUPER::connector(@_) if $self->all_callbacks;
210 return ($self->SUPER::connector(@_) || 'solid');
211 }
212  
213 # never allow our components to bump
214 sub bump {
215 my $self = shift;
216 my $bump = $self->SUPER::bump(@_);
217 return $bump if $self->all_callbacks;
218 return $self->parts_overlap ? $bump : 0;
219 }
220  
221 sub maxdepth {
222 my $self = shift;
223 my $md = $self->Bio::Graphics::Glyph::maxdepth;
224 return $md if defined $md;
225 return 1;
226 }
227  
228 # this was willfully confusing
229 #sub fontcolor {
230 # my $self = shift;
231 # return $self->SUPER::fontcolor unless $self->draw_target;# || $self->option('draw_dna');
232 # return $self->SUPER::fontcolor unless $self->dna_fits;
233 # return $self->bgcolor;
234 #}
235  
236 # Override _subfeat() method to make it appear that a top-level feature that
237 # has no subfeatures appears as a feature that has a single subfeature.
238 # Otherwise at high mags gaps will be drawn as components rather than
239 # as connectors. Because of differing representations of split features
240 # in Bio::DB::GFF::Feature and Bio::SeqFeature::Generic, there is
241 # some breakage of encapsulation here.
242 sub _subfeat {
243 my $self = shift;
244 my $feature = shift;
245  
246 my @subfeat = $self->SUPER::_subfeat($feature);
247  
248 if (!@subfeat && $self->option('split_on_cigar')) {
249 my $cigar = $self->_get_cigar($feature);
250 if ($cigar && @$cigar) {
251 return $self->_split_on_cigar($feature,$cigar);
252 }
253 }
254  
255 return @subfeat if @subfeat;
256 if ($self->level == 0 && !@subfeat && !$self->feature_has_subparts) {
257 return $self->feature;
258 } else {
259 return;
260 }
261 }
262  
263 sub _split_on_cigar {
264 my $self = shift;
265 my ($feature,$cigar) = @_;
266  
267 my $source_start = $feature->start;
268 my $source_end = $feature->end;
269 my $ss = $feature->strand;
270 my $ts = $feature->hit->strand;
271 my $target_start = eval {$feature->hit->start} || return $feature;
272  
273 my (@parts);
274  
275 # BUG: we handle +/+ and -/+ alignments, but not +/- or -/-
276 # (i.e. the target has got to have forward strand coordinates)
277  
278 # forward strand
279 if ($ss >= 0) {
280 for my $event (@$cigar) {
281 my ($op,$count) = @$event;
282 if ($op eq 'I' || $op eq 'S' || $op eq 'H') {
283 $target_start += $count;
284 }
285 elsif ($op eq 'D' || $op eq 'N') {
286 $source_start += $count;
287 }
288 elsif ($op eq 'P') {
289 # Do NOTHING for pads. Irrelevant for pairwise
290 # alignments, since we cannot show the pad in
291 # the reference sequence
292 } else { # everything else is assumed to be a match -- revisit
293 push @parts,[$source_start,$source_start+$count-1,
294 $target_start,$target_start+$count-1];
295 $source_start += $count;
296 $target_start += $count;
297 }
298 }
299  
300 # minus strand
301 } else {
302 for my $event (@$cigar) {
303 my ($op,$count) = @$event;
304 if ($op eq 'I' || $op eq 'S' || $op eq 'H') {
305 $target_start += $count;
306 }
307 elsif ($op eq 'D' || $op eq 'N') {
308 $source_end -= $count;
309 }
310 elsif ($op eq 'P') {
311 # do nothing for pads
312 } else { # everything else is assumed to be a match -- revisit
313 push @parts,[$source_end-$count+1,$source_end,
314 $target_start,$target_start+$count-1];
315 $source_end -= $count;
316 $target_start += $count;
317 }
318 }
319
320 }
321  
322 my $id = $feature->seq_id;
323 my $tid = $feature->hit->seq_id;
324 my @result = map {
325 my ($s1,$s2,$t1,$t2) = @$_;
326 my $s = Bio::Graphics::Feature->new(-seq_id=> $id,
327 -start => $s1,
328 -end => $s2,
329 -strand => $ss,
330 );
331 my $h = Bio::Graphics::Feature->new(-seq_id=> $tid,
332 -start => $t1,
333 -end => $t2,
334 -strand => $ts,
335 );
336 $s->add_hit($h);
337 $s;
338 } @parts;
339 return @result;
340 }
341  
342 sub draw {
343 my $self = shift;
344  
345 my $draw_target = $self->draw_target && $self->dna_fits && eval {$self->feature->hit->seq};
346
347 $self->SUPER::draw(@_);
348  
349 return if $self->feature_has_subparts;
350 return unless $draw_target;
351  
352 my $drew_sequence;
353 $drew_sequence = $self->draw_multiple_alignment(@_);
354  
355 my ($gd,$x,$y) = @_;
356 $y += $self->top + $self->pad_top if $drew_sequence; # something is wrong - this is a hack/workaround
357 my $connector = $self->connector;
358 $self->draw_connectors($gd,$x,$y)
359 if $connector && $connector ne 'none' && $self->level == 0;
360 }
361  
362 sub draw_component {
363 my $self = shift;
364 my ($gd,$left,$top,$partno,$total_parts) = @_;
365 my ($x1,$y1,$x2,$y2) = $self->bounds($left,$top);
366  
367 my $draw_target;
368 my $strand = $self->feature->strand;
369  
370 if ($self->draw_target && $self->dna_fits) {
371 $draw_target++;
372 my $stranded = $self->stranded;
373 my $bgcolor = $self->bgcolor;
374 if ($stranded) {
375 $x1 -= 6 if $strand < 0 && $x1 >= $self->panel->left;
376 $x2 += 6 if $strand > 0 && $x2 <= $self->panel->right;
377 $self->filled_arrow($gd,$strand,$x1,$y1,$x2,$y2)
378 } else {
379 $self->filled_box($gd,$x1,$y1,$x2,$y2,$bgcolor,$bgcolor);
380 }
381 } else {
382 $self->SUPER::draw_component(@_);
383 }
384  
385 return unless $self->show_mismatch;
386 my $mismatch_color = $self->mismatch_color;
387 my $feature = $self->feature;
388 my $start = $self->feature->start;
389 my $end = $feature->end;
390 my (@mismatch_positions,@del_positions,@in_positions);
391  
392 if (my ($src,$matchstr,$tgt) = eval{$feature->padded_alignment}) {
393 my @src = split '',$src;
394 my @match = split '',$matchstr;
395 my @tgt = split '',$tgt;
396 my $pos = $start;
397  
398 # skip over src padding (probably soft clipped)
399 while ($src[0] eq '-') {
400 shift @src;
401 shift @tgt;
402 }
403 while ($src[-1] eq '-') {
404 pop @src;
405 pop @tgt;
406 }
407  
408 for (my $i=0;$i<@src;$i++) {
409 if ($src[$i] eq '-') {
410 push @in_positions,$pos;
411 }
412 elsif ($tgt[$i] eq '-') {
413 push @del_positions,$pos;
414 $pos++;
415 } elsif ($src[$i] ne $tgt[$i]) {
416 push @mismatch_positions,$pos;
417 $pos++;
418 } else {
419 $pos++;
420 }
421 }
422 }
423  
424 else {
425 my $sdna = eval {$feature->dna};
426 my $tdna = eval {$feature->target->dna}; # works with GFF files
427  
428 return unless $sdna =~ /[gatc]/i;
429 return unless $tdna =~ /[gatc]/i;
430  
431 my @src = split '',$sdna;
432 my @tgt = split '',$tdna;
433 for (my $i=0;$i<@src;$i++) {
434 next if $src[$i] eq $tgt[$i];
435 warn "$src[$i] eq $tgt[$i], strand=$strand";
436 my $pos = $strand >= 0 ? $i+$start : $end-$i;
437 push @mismatch_positions,$pos;
438 }
439 }
440  
441 my $pixels_per_base = $self->scale;
442 my $panel_right = $self->panel->right;
443
444 for my $a ([\@mismatch_positions,$self->mismatch_color],
445 [\@del_positions,$self->deletion_color],
446 [\@in_positions,$self->insertion_color,0.5,0.5]
447 ) {
448  
449 my $color = $a->[1];
450 my $offset = $a->[2]||0;
451 my $width = $a->[3]||1;
452 my @pixel_positions = $self->map_no_trunc(@{$a->[0]});
453  
454 foreach (@pixel_positions) {
455 next if $_ < $x1;
456 next if $_ > $x2;
457 next if $_ >= $panel_right;
458 my $left = $_ - $pixels_per_base*$offset;
459 my $right = $left+($width*$pixels_per_base);
460 my $top = $y1+1;
461 my $bottom= $y2-1;
462 my $middle= ($y1+$y2)/2;
463 if ($self->stranded && $left <= $x1+$pixels_per_base-1 && $self->strand < 0) {
464 $self->filled_arrow($gd,$self->strand,
465 $draw_target ? ($left-4):$left+2,
466 $top,
467 $draw_target ? $right:$right+5,$bottom,$color,$color,1);
468 } elsif ($self->stranded && $right >= $x2-$pixels_per_base+1 && $self->strand > 0) {
469 $self->filled_arrow($gd,$self->strand,
470 $left,$top,$draw_target ? ($right+4): $right-2,$bottom,$color,$color,1);
471 } else {
472 $self->filled_box($gd,
473 $left,
474 $top,
475 $right,
476 $bottom,
477 $color,$color);
478 }
479 }
480 }
481 }
482  
483 # BUG: this horrible subroutine has grown without control and needs
484 # to be broken down into manageable subrutines.
485 sub draw_multiple_alignment {
486 my $self = shift;
487 my $gd = shift;
488 my ($left,$top,$partno,$total_parts) = @_;
489  
490 my $flipped = $self->flip;
491 my $ragged_extra = $self->option('ragged_start')
492 ? RAGGED_START_FUZZ : $self->option('ragged_extra');
493 my $true_target = $self->option('true_target');
494 my $show_mismatch = $self->show_mismatch;
495 my $do_realign = $self->option('realign');
496  
497 my $pixels_per_base = $self->scale;
498 my $feature = $self->feature;
499  
500 my $panel = $self->panel;
501 my ($abs_start,$abs_end) = ($feature->start,$feature->end);
502 my ($tgt_start,$tgt_end) = ($feature->hit->start,$feature->hit->end);
503 my ($panel_start,$panel_end) = ($self->panel->start,$self->panel->end);
504 my $strand = $feature->strand;
505 my $panel_left = $self->panel->left;
506 my $panel_right = $self->panel->right;
507 my $bgcolor = $self->bgcolor;
508  
509 my $drew_sequence;
510  
511 if ($tgt_start > $tgt_end) { #correct for data problems
512 $strand = -1;
513 ($tgt_start,$tgt_end) = ($tgt_end,$tgt_start);
514 }
515  
516 warn "TGT_START..TGT_END = $tgt_start..$tgt_end" if DEBUG;
517  
518 my ($bl,$bt,$br,$bb) = $self->bounds($left,$top);
519 $top = $bt;
520  
521 my $stranded = $self->stranded;
522  
523 my @s = $self->_subfeat($feature);
524  
525 # FIX ME
526 # workaround for features in which top level feature does not have a hit but
527 # subfeatures do. There is total breakage of encapsulation here because sometimes
528 # a chado alignment places the aligned segment in the top-level feature, and sometimes
529 # in the child feature.
530 unless (@s) { # || $feature->isa('Bio::DB::GFF::Feature')) {
531 @s = ($feature);
532 }
533  
534 my $can_realign;
535 if (Bio::Graphics::Browser2::Realign->can('align_segs')) {
536 $can_realign = \&Bio::Graphics::Browser2::Realign::align_segs;
537 } elsif (Bio::Graphics::Browser::Realign->can('align_segs')) {
538 $can_realign = \&Bio::Graphics::Browser::Realign::align_segs;
539 }
540  
541 my (@segments,%strands);
542 my ($ref_dna,$tgt_dna);
543  
544 for my $s (@s) {
545  
546 my $target = $s->hit;
547 my ($src_start,$src_end) = ($s->start,$s->end);
548 # next unless $src_start <= $panel_end && $src_end >= $panel_start;
549  
550 my ($tgt_start,$tgt_end) = ($target->start,$target->end);
551  
552 my $strand_bug;
553 unless (exists $strands{$target}) {
554 my $strand = $feature->strand;
555 if ($tgt_start > $tgt_end) { #correct for data problems
556 $strand = -1;
557 ($tgt_start,$tgt_end) = ($tgt_end,$tgt_start);
558 $strand_bug++;
559 }
560 $strands{$target} = $strand;
561 }
562  
563 my $cigar = $self->_get_cigar($s);
564 if ($cigar || ($can_realign && $do_realign)) {
565 ($ref_dna,$tgt_dna) = ($s->dna,$target->dna);
566 warn "$s: ",$s->seq_id,":",$s->start,'..',$s->end if DEBUG;
567 warn "ref/tgt" if DEBUG;
568 warn "$ref_dna\n$tgt_dna" if DEBUG;
569
570 my @exact_segments;
571  
572 if ($cigar) {
573 warn "Segmenting [$target,$src_start,$src_end,$tgt_start,$tgt_end] via $cigar.\n" if DEBUG;
574 @exact_segments = $self->_gapped_alignment_to_segments($cigar,$ref_dna,$tgt_dna);
575 }
576 else {
577 warn "Realigning [$target,$src_start,$src_end,$tgt_start,$tgt_end].\n" if DEBUG;
578 @exact_segments = $can_realign->($ref_dna,$tgt_dna);
579 }
580  
581 foreach (@exact_segments) {
582 warn "=========> [$target,@$_]\n" if DEBUG;
583 my $a = $strands{$target} >= 0
584 ? [$target,$_->[0]+$src_start,$_->[1]+$src_start,$_->[2]+$tgt_start,$_->[3]+$tgt_start]
585 : [$target,$src_end-$_->[1],$src_end-$_->[0],$_->[2]+$tgt_start,$_->[3]+$tgt_start];
586 warn "[$target,$_->[0]+$src_start,$_->[1]+$src_start,$tgt_end-$_->[3],$tgt_end-$_->[2]]" if DEBUG;
587 warn "=========> [@$a]\n" if DEBUG;
588 warn substr($ref_dna, $_->[0],$_->[1]-$_->[0]+1),"\n" if DEBUG;
589 warn substr($tgt_dna,$_->[2],$_->[3]-$_->[2]+1),"\n" if DEBUG;
590 push @segments,$a;
591 }
592 }
593 else {
594 push @segments,[$target,$src_start,$src_end,$tgt_start,$tgt_end];
595 }
596 }
597  
598 # get 'em in the right order so that we don't have to worry about
599 # where the beginning and end are.
600 @segments = sort {$a->[TGT_START]<=>$b->[TGT_START]} @segments;
601
602 # adjust for ragged (nonaligned) ends
603 my ($offset_left,$offset_right) = (0,0);
604 if ($ragged_extra && $ragged_extra > 0) {
605  
606 # add a little rag to the left end
607 $offset_left = $segments[0]->[TGT_START] > $ragged_extra ? $ragged_extra : $segments[0]->[TGT_START]-1;
608 if ($strand >= 0) {
609 $offset_left = $segments[0]->[SRC_START]-1 if $segments[0]->[SRC_START] - $offset_left < 1;
610 $abs_start -= $offset_left;
611 $tgt_start -= $offset_left;
612 $segments[0]->[SRC_START] -= $offset_left;
613 $segments[0]->[TGT_START] -= $offset_left;
614 } else {
615 $abs_end += $offset_left;
616 $tgt_start -= $offset_left;
617 $segments[0]->[SRC_END] += $offset_left;
618 $segments[0]->[TGT_START] -= $offset_left;
619 }
620  
621 # add a little rag to the right end - this is complicated because
622 # we don't know what the length of the underlying dna is, so we
623 # use the subfeat method to find out
624 my $current_end = $segments[-1]->[TGT_END];
625 $offset_right = length $segments[-1]->[TARGET]->subseq($current_end+1,$current_end+$ragged_extra)->seq;
626 if ($strand >= 0) {
627 $abs_end += $offset_right;
628 $tgt_end += $offset_left;
629 $segments[-1]->[TGT_END] += $offset_right;
630 $segments[-1]->[SRC_END] += $offset_right;
631 } else {
632 $abs_start -= $offset_right;
633 $tgt_end += $offset_left;
634 $segments[-1]->[TGT_END] += $offset_right;
635 $segments[-1]->[SRC_START] -= $offset_right;
636 }
637 }
638  
639 # get the DNAs now - a little complicated by the necessity of using
640 # the subseq() method
641 $ref_dna ||= $feature->subseq(1-$offset_left,$feature->length+$offset_right)->seq;
642  
643 # this may not be right if the alignment involves only a portion of the target DNA
644 $tgt_dna ||= $feature->hit->dna;
645  
646 # none of these seem to be working properly with BAM alignments
647 # my $tgt_len = abs($segments[-1]->[TGT_END] - $segments[0]->[TGT_START]) + 1;
648 # my $tgt_dna = $feature->hit->subseq(1-$offset_left,$feature->length+$offset_right)->seq;
649 # my $tgt_dna = $feature->hit->subseq(1-$offset_left,$tgt_len+$offset_right)->seq;
650  
651 # work around changes in the API
652 $ref_dna = $ref_dna->seq if ref $ref_dna and $ref_dna->can('seq');
653 $tgt_dna = $tgt_dna->seq if ref $tgt_dna and $tgt_dna->can('seq');
654  
655 $ref_dna = lc $ref_dna;
656 $tgt_dna = lc $tgt_dna;
657  
658 # sanity check. Let's see if they look like they're lining up
659 warn "$feature dna sanity check:\n$ref_dna\n$tgt_dna\n" if DEBUG;
660  
661 # now we're all lined up, and we're going to adjust everything to fall within the bounds
662 # of the left and right panel coordinates
663 my %clip;
664 for my $seg (@segments) {
665  
666 my $target = $seg->[TARGET];
667 warn "preclip [@$seg]\n" if DEBUG;
668  
669 # left clipping
670 if ( (my $delta = $seg->[SRC_START] - $panel_start) < 0 ) {
671 warn "clip left delta = $delta" if DEBUG;
672 $seg->[SRC_START] = $panel_start;
673 if ($strand >= 0) {
674 $seg->[TGT_START] -= $delta;
675 }
676 }
677  
678 # right clipping
679 if ( (my $delta = $panel_end - $seg->[SRC_END]) < 0) {
680 warn "clip right delta = $delta" if DEBUG;
681 $seg->[SRC_END] = $panel_end;
682 if ($strand < 0) {
683 $seg->[TGT_START] -= $delta;
684 }
685 }
686  
687 my $length = $seg->[SRC_END]-$seg->[SRC_START]+1;
688 $seg->[TGT_END] = $seg->[TGT_START]+$length-1;
689  
690 warn "Clipping gives [@$seg], tgt_start = $tgt_start\n" if DEBUG;
691 }
692  
693 # remove segments that got clipped out of existence
694 # no longer doing this because it interferes with ability to
695 # detect insertions in the target
696 # @segments = grep { $_->[SRC_START]<=$_->[SRC_END] } @segments;
697  
698 # relativize coordinates
699 if ($strand < 0) {
700 # breaks BAM, but probably needed for non-BAM features
701 $ref_dna = $self->reversec($ref_dna) unless eval { $feature->reversed } ;
702 $tgt_dna = $self->reversec($tgt_dna);
703 }
704  
705 my ($red,$green,$blue) = $self->panel->rgb($bgcolor);
706 my $avg = ($red+$green+$blue)/3;
707 my $color = $self->translate_color($avg > 128 ? 'black' : 'white');
708 my $font = $self->mono_font;
709 my $lineheight = $font->height;
710 my $fontwidth = $font->width;
711  
712 my $mismatch = $self->mismatch_color;
713 my $insertion= $self->insertion_color;
714 my $deletion = $self->deletion_color;
715 my $grey = $self->translate_color('gray');
716 my $mismatch_font_color = eval {
717 my ($r,$g,$b) = $self->panel->rgb($mismatch);
718 $self->translate_color(($r+$g+$b)>128 ? 'black' : 'white');
719 };
720 my $insertion_font_color = eval {
721 my ($r,$g,$b) = $self->panel->rgb($insertion);
722 $self->translate_color(($r+$g+$b)>128 ? 'black' : 'white');
723 };
724 my $deletion_font_color = eval {
725 my ($r,$g,$b) = $self->panel->rgb($deletion);
726 $self->translate_color(($r+$g+$b)>128 ? 'black' : 'white');
727 };
728  
729  
730 unless (@segments) { # this will happen if entire region is a target gap
731 for (my $i = $bl;$i<$br-$self->scale;$i+=$self->scale) {
732 $gd->char($font,$self->flip ? $i+$self->scale-4 : $i+2,$top,'-',$deletion_font_color);
733 }
734 return;
735 }
736
737 for my $seg (@segments) {
738 $seg->[SRC_START] -= $abs_start - 1;
739 $seg->[SRC_END] -= $abs_start - 1;
740 $seg->[TGT_START] -= $tgt_start - 1;
741 $seg->[TGT_END] -= $tgt_start - 1;
742  
743 if ($strand < 0) {
744 ($seg->[TGT_START],$seg->[TGT_END]) = (length($tgt_dna)-$seg->[TGT_END]+1,length($tgt_dna)-$seg->[TGT_START]+1);
745 }
746 if (DEBUG) {
747 warn "$feature: relativized coordinates = [@$seg]\n";
748 warn $self->_subsequence($ref_dna,$seg->[SRC_START],$seg->[SRC_END]),"\n";
749 warn $self->_subsequence($tgt_dna,$seg->[TGT_START],$seg->[TGT_END]),"\n";
750 }
751 }
752  
753 # draw
754 my $base2pixel =
755 $self->flip ?
756 sub {
757 my ($src,$tgt) = @_;
758 my $a = $fontwidth + ($abs_start + $src-$panel_start-1 + $tgt) * $pixels_per_base - 1;
759 $panel_right - $a;
760 }
761 : sub {
762 my ($src,$tgt) = @_;
763 $fontwidth/2 + $left + ($abs_start + $src-$panel_start-1 + $tgt) * $pixels_per_base - 1;
764 };
765  
766 my $mismatch_only = $self->mismatch_only;
767 my ($tgt_last_end,$src_last_end,$leftmost,$rightmost,$gaps);
768  
769 my $segment = 0;
770  
771 for my $seg (sort {$a->[SRC_START]<=>$b->[SRC_START]} @segments) {
772 my $y = $top-1;
773 my $end = $seg->[SRC_END]-$seg->[SRC_START];
774  
775 for (my $i=0; $i<$end+1; $i++) {
776 my $src_base = $self->_subsequence($ref_dna,$seg->[SRC_START]+$i,$seg->[SRC_START]+$i);
777 my $tgt_base = $self->_subsequence($tgt_dna,$seg->[TGT_START]+$i,$seg->[TGT_START]+$i);
778 my $x = $base2pixel->($seg->[SRC_START],$i);
779 $leftmost = $x if !defined $leftmost || $leftmost > $x;
780 $rightmost= $x if !defined $rightmost || $rightmost < $x;
781  
782 next unless $tgt_base && $x >= $panel_left && $x <= $panel_right;
783  
784 my $is_mismatch = $show_mismatch && $tgt_base && $src_base ne $tgt_base && $tgt_base !~ /[nN]/;
785 $tgt_base = $complement{$tgt_base} if $true_target && $strand < 0;
786 $gd->char($font,$x,$y,$tgt_base,$tgt_base =~ /[nN]/ ? $grey
787 :$is_mismatch ? $mismatch_font_color
788 :$color)
789 unless $mismatch_only && !$is_mismatch;
790  
791 $drew_sequence++;
792 }
793  
794 # deal with gaps in the alignment
795 if (defined $src_last_end && (my $delta = $seg->[SRC_START] - $src_last_end) > 1) {
796 for (my $i=0;$i<$delta-1;$i++) {
797 my $x = $base2pixel->($src_last_end,$i+1);
798 next if $x > $panel_right;
799 next if $x < $panel_left;
800 $gd->char($font,$x,$y,'-',$deletion_font_color);
801 }
802 $gaps = $delta-1;
803 }
804  
805 # indicate the presence of insertions in the target
806 $gaps ||= 0;
807 my $pos = $src_last_end + $gaps;
808 my $delta = $seg->[TGT_START] - $tgt_last_end;
809 my $src_delta = $seg->[SRC_START] - $src_last_end;
810  
811 if ($segment && $delta && ($delta > $src_delta-$gaps)) { # an insertion in the target relative to the source
812 my $gap_left = $base2pixel->($pos+0.5,0);
813 my $gap_right = $base2pixel->($seg->[SRC_START],0);
814 ($gap_left,$gap_right) = ($gap_right+$fontwidth,$gap_left-$fontwidth) if $self->flip;
815 warn "delta=$delta, gap_left=$gap_left, gap_right=$gap_right" if DEBUG;
816  
817 next if $gap_left <= $panel_left || $gap_right >= $panel_right;
818
819 my $length = $delta-1;
820 $length = 1 if $length <= 0; # workaround
821 my $gap_distance = $gap_right - $gap_left;
822 my $pixels_per_inserted_base = $gap_distance/$length;
823  
824 if ($pixels_per_inserted_base >= $fontwidth) { # Squeeze the insertion in
825 for (my $i = 0; $i<$delta-1; $i++) {
826 my $x = $gap_left + $pixels_per_inserted_base * $i;
827 my $bp = $self->_subsequence($tgt_dna,$tgt_last_end+$i+1,$tgt_last_end+$i+1);
828 next if $x < $panel_left;
829 $gd->char($font,$x,$y,$bp,$color);
830 }
831 } else { #here's where we insert the insertion length
832 if ($gap_distance >= $fontwidth*length($length)) {
833 $gd->string($font,$gap_left,$y,$length,$color);
834 }
835 }
836 }
837  
838 } continue {
839 $tgt_last_end = $seg->[TGT_END];
840 $src_last_end = $seg->[SRC_END];
841 $segment++;
842 }
843  
844 return $drew_sequence;
845 }
846  
847 sub _gapped_alignment_to_segments {
848 my $self = shift;
849 my ($cigar,$sdna,$tdna) = @_;
850 my ($pad_source,$pad_target,$pad_match);
851 warn "_gapped_alignment_to_segments\n$sdna\n$tdna" if DEBUG;
852  
853 for my $event (@$cigar) {
854 my ($op,$count) = @$event;
855 warn "op=$op, count=$count" if DEBUG;
856 if ($op eq 'I') {
857 $pad_source .= '-' x $count;
858 $pad_target .= substr($tdna,0,$count,'');
859 $pad_match .= ' ' x $count;
860 }
861 elsif ($op eq 'D' || $op eq 'N') {
862 $pad_source .= substr($sdna,0,$count,'');
863 $pad_target .= '-' x $count;
864 $pad_match .= ' ' x $count;
865 }
866 elsif ($op eq 'S') {
867 $pad_source .= '-' x $count;
868 $pad_target .= substr($tdna,0,$count,'');
869 $pad_match .= ' ' x $count;
870  
871 }
872 elsif ($op eq 'H' || $op eq 'P') {
873 # Nothing to do. This is simply an informational operation.
874 } else { # everything else is assumed to be a match -- revisit
875 $pad_source .= substr($sdna,0,$count,'');
876 $pad_target .= substr($tdna,0,$count,'');
877 $pad_match .= '|' x $count;
878 }
879 }
880  
881 warn "pads:\n$pad_source\n$pad_match\n$pad_target" if DEBUG;
882  
883 return $self->pads_to_segments($pad_source,$pad_match,$pad_target);
884 }
885  
886 sub pads_to_segments {
887 my $self = shift;
888 my ($gap1,$align,$gap2) = @_;
889 warn "pads_to_segments" if DEBUG;
890 warn "$gap1\n$align\n$gap2\n" if DEBUG;
891  
892 # create arrays that map residue positions to gap positions
893 my @maps;
894 for my $seq ($gap1,$gap2) {
895 my @seq = split '',$seq;
896 my @map;
897 my $residue = 0;
898 for (my $i=0;$i<@seq;$i++) {
899 $map[$i] = $residue;
900 $residue++ if $seq[$i] ne '-';
901 }
902 push @maps,\@map;
903 }
904  
905 my @result;
906 while ($align =~ /(\S+)/g) {
907 my $align_end = pos($align) - 1;
908 my $align_start = $align_end - length($1) + 1;
909 push @result,[@{$maps[0]}[$align_start,$align_end],
910 @{$maps[1]}[$align_start,$align_end]];
911 }
912 return wantarray ? @result : \@result;
913 }
914  
915 sub _get_cigar {
916 my $self = shift;
917 my $feat = shift;
918
919 # some features have this built in
920 if ($feat->can('cigar_array')) {
921 my $cigar = $feat->cigar_array;
922 @$cigar = reverse @$cigar if $feat->strand < 0;
923 return $cigar;
924 }
925  
926 my ($cigar) = $feat->get_tag_values('Gap');
927 return unless $cigar;
928  
929 my @arry;
930 my $regexp = $cigar =~ /^\d+/ ? '(\d+)([A-Z])'
931 : '([A-Z])(\d+)';
932 if ($cigar =~ /^\d+/) {
933 while ($cigar =~ /(\d+)([A-Z])/g) {
934 my ($count,$op) = ($1,$2);
935 push @arry,[$op,$count];
936 }
937 } else {
938 while ($cigar =~ /([A-Z])(\d+)/g) {
939 my ($op,$count) = ($1,$2);
940 push @arry,[$op,$count];
941 }
942 }
943 return \@arry;
944 }
945  
946 sub _subsequence {
947 my $self = shift;
948 my ($seq,$start,$end,$strand) = @_;
949 my $sub;
950 if ((defined $strand && $strand < 0)) {
951 my $piece = substr($seq,length($seq)-$end,$end-$start+1);
952 $sub = $self->reversec($piece);
953 } else {
954 $sub = substr($seq,$start-1,$end-$start+1);
955 }
956 return $self->flip ? $complement{$sub} : $sub;
957 }
958  
959 # draw the classic "i-beam" icon to indicate that an insertion fits between
960 # two bases
961 # sub _draw_insertion_point {
962 # my $self = shift;
963 # my ($gd,$x,$y,$color) = @_;
964 # my $top = $y;
965 # $x--;
966 # my $bottom = $y + $self->font->height - 4;
967 # $gd->line($x,$top+2, $x,$bottom-2,$color);
968 # $gd->setPixel($x+1, $top+1,$color);
969 # $gd->setPixel($x+$_, $top,$color) for (2..3);
970 # $gd->setPixel($x-1, $top+1,$color);
971 # $gd->setPixel($x-$_, $top,$color) for (2..3);
972  
973 # $gd->setPixel($x+1, $bottom-1,$color);
974 # $gd->setPixel($x+$_, $bottom, $color) for (2..3);
975 # $gd->setPixel($x-1, $bottom-1,$color);
976 # $gd->setPixel($x-$_, $bottom, $color) for (2..3);
977 # }
978  
979 # don't like that -- try drawing carets
980 sub _draw_insertion_point {
981 my $self = shift;
982 my ($gd,$left,$right,$top,$bottom,$color) = @_;
983  
984 my $poly = GD::Polygon->new();
985 $poly->addPt($left-3,$top+1);
986 $poly->addPt($right+2,$top+1);
987 $poly->addPt(($left+$right)/2-1,$top+3);
988 $gd->filledPolygon($poly,$color);
989  
990 $poly = GD::Polygon->new();
991 $poly->addPt($left-3,$bottom);
992 $poly->addPt($right+2,$bottom);
993 $poly->addPt(($left+$right)/2-1,$bottom-2);
994 $gd->filledPolygon($poly,$color);
995 }
996  
997 1;
998  
999 __END__