blib/conf/plugins/Spectrogram.pm untested

filter: Statementstmt 0.0% 0 / 253 Branchbran 0.0% 0 / 52 Conditioncond 0.0% 0 / 46 MC/DCmcdc n/a Subroutinesub 0.0% 0 / 31 Podpod 0.0% 0 / 17 totaltotal 0.0% 0 / 399 CC 27 SCAR 52.9
CC
27
Cov
0%
annotate
506.0
make_numeric
30.0
configure_form
6.0
CRAP 199.1
1 # $Id: Spectrogram.pm,v 1.9 2009-01-08 16:42:29 lstein Exp $
2 # bioperl module for Bio::Graphics::Browser2::Plugin::Spectrogram
3 # cared for by Sheldon McKay mckays@cshl.edu
4 # Copyright (c) 2006 Cold Spring Harbor Laboratory.
5  
6 =head1 NAME
7  
8 Bio::Graphics::Browser2::Plugin::Spectrogram
9  
10 =head1 SYNOPSIS
11  
12 This module is not used directly. It is an 'annotator'
13 plugin for tehe Generic Genome Browser.
14  
15 =head1 DESCRIPTION
16  
17 The Spectrogram plugin builds up a spectrogram for
18 digitized DNA sequence using the short-time fourier
19 transform (STFT) method, adapted from classical digital signal
20 processing methods. A sliding window of variable size and overlap
21 is used to calculate each "column" of the spectrogram, where the column
22 width is equal to the step, or overlap between windows.
23  
24 For each window, we:
25  
26 1) digitize the DNA by creating four binary indicator
27 sequences:
28  
29 G A T C C T C T G A T T C C A A
30 G 1 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0
31 A 0 1 0 0 0 0 0 0 0 1 0 0 0 0 1 1
32 T 0 0 1 0 0 1 0 1 0 0 1 1 0 0 0 0
33 C 0 0 0 1 1 0 1 0 0 0 0 0 1 1 0 0
34  
35 2) take the discrete fourier transform (DFT) for each of the
36 four indicator sequences and square the values to get
37 the magnitude.
38  
39 3) create a Bio::Graphics::Feature object that contains
40 the spectrogram data as attributes. The features are passed
41 back to gbrowse as parts of a Bio::Graphics::Featurefile object.
42  
43 The calculations for the real DFT are handled by
44 the xs module Math::FFT. The actual algorithm
45 used is the fast fourier transfrom (FFT), which is much
46 faster than the original DFT algorithm but is limited in that
47 only base2 numbers (128, 256, 512, etc) can be used for window
48 sizes. This is necessary to make the spectrogram calculation
49 fast enough for real-time use. It should be noted, however,
50 that calculating spectrograms dynamically is computationally
51 intensive and will increase latency when the spectrogram
52 track is turned on in gbrowse.
53  
54 The graphical rendering of the spectrogram depends on the
55 glyph module Bio::Graphics::Glyph::spectrogram.
56  
57 The plugin is discussed in more detail in the plugin's help
58 links.
59  
60 =head1 FEEDBACK
61  
62 See the GMOD website for information on bug submission http://www.gmod.org.
63  
64 =head1 AUTHOR - Sheldon McKay
65  
66 Email E<lt>mckays@cshl.eduE<gt>
67  
68 =cut
69 ;
70  
71 package Bio::Graphics::Browser2::Plugin::Spectrogram;
72 use strict;
73 use Bio::Graphics::Browser2::Plugin;
74 use Bio::Graphics::Browser2::Util qw/error/;
75 use CGI ':standard';
76 use CGI::Carp 'fatalsToBrowser';
77 use CGI::Toggle;
78 use GD;
79  
80 use Math::FFT;
81 use Statistics::Descriptive;
82 use List::Util qw/shuffle max/;
83  
84 use Data::Dumper;
85  
86 use vars qw/@ISA $CONFIG $VERSION/;
87  
88 use constant IMAGE_DIR => '/gbrowse2/images/help';
89 use constant BUTTONS_DIR => '/gbrowse2/images/buttons';
90  
91 $VERSION = 1.1;
92 @ISA = qw/ Bio::Graphics::Browser2::Plugin /;
93  
94 sub init {
95 my $self = shift;
96 $CONFIG = $self->browser_config;
97 }
98  
99 sub name {
100 'DNA spectrogram';
101 }
102  
103 sub type {
104 'annotator';
105 }
106  
107 sub verb {
108 'Draw';
109 }
110  
111 sub mime_type {
112 'text/html';
113 }
114  
115 sub config_defaults {
116 { win => 512,
117 inc => 256,
118 binsize => 1,
119 y_unit => 1,
120 quantile => 99.99,
121 filter_01 => 1,
122 min => 2,
123 max => 4,
124 type => 'period'}
125 }
126  
127 sub reconfigure {
128 my $self = shift;
129 my $conf = $self->configuration;
130 $conf->{win} = $self->config_param('win');
131 $conf->{inc} = $self->config_param('inc');
132 $conf->{min} = $self->config_param('min') || 0;
133 $conf->{max} = $self->config_param('max') || $conf->{win} - 1;
134 $conf->{type} = $self->config_param('measure');
135 $conf->{filter_01} = $self->config_param('filter_01');
136 $conf->{quantile} = $self->config_param('quantile') || 99.99;
137 $conf->{y_unit} = $self->config_param('y_unit') || 1;
138 $self->configuration($conf);
139 }
140  
141 sub annotate {
142 my $self = shift;
143 my $segment = shift or die "No segment";
144 my $conf = $self->configuration;
145  
146 my $win = $conf->{win};
147 my $inc = $conf->{inc};
148 my $ltype = $conf->{ltype};
149  
150 # sanity check for window size
151 if ($inc >= $win) {
152 error("Spectrogram.pm error: window size must be greater than the overlap");
153 return;
154 }
155
156 # and for maximum period or frequency
157 if ($conf->{max} && $conf->{max} > $win) {
158 error("maximum $conf->{type} can not exceed ".
159 " the window size: resetting to $win.");
160 $conf->{max} = $win;
161 }
162  
163 my $slide_offset = 0;
164 my $db = $segment->factory;
165 unless ($segment->start == 1) {
166 my $original_start = $segment->start;
167 ($segment) = $db->segment( $segment->ref, ($segment->start - $win), ($segment->end + $win) );
168 $slide_offset = $original_start - $segment->start - $inc;
169 }
170 else {
171 ($segment) = $db->segment( $segment->ref, $segment->start, ($segment->end + $win) );
172 }
173  
174 my $seq_obj = $segment->seq;
175 my $seq;
176 if ($seq_obj && ref $seq_obj) {
177 $seq = lc eval{$seq_obj->seq};
178 }
179 elsif ($seq_obj) {
180 $seq = lc $seq_obj;
181 }
182 $seq || die "No sequence found for $segment $@";
183  
184 my $offset = $segment->start;
185 my $end = $segment->length;
186
187 my (@g,@a,@t,@c,@offsets,@meta_array,@coords);
188  
189 my ($min_f,$max_f);
190 if ( $conf->{min} || $conf->{max} ) {
191 my $max = $conf->{max} || $win;
192 my $min = $conf->{min} || 0;
193 my $type = $conf->{type};
194  
195 if ($type eq 'period') {
196 $min_f = $min && $max && $max > 1 ? int(2*$win/($max)) - 1 : $win - 1;
197 $max_f = $min ? int(2*$win/($min)) - 1 : $win - 1;
198 }
199 else {
200 unless (int $min == $min) {
201 error("minimum frequency value should be an integer between",
202 "0 and ".($win-2));
203 return;
204 }
205 unless (int $max == $max) {
206 error("maximum frequency value should be an integer between",
207 "1 and ".($win-1));
208 return;
209 }
210 $min_f = $min;
211 $max_f = $max || $win-1;
212 }
213 }
214 else {
215 $min_f = 0;
216 $max_f = $win-1;
217 }
218  
219 $min_f-- unless $min_f == 0;
220 $max_f++ unless $max_f == $win-1;
221  
222 my $key = join('; ',"window size $win", "overlap $inc",
223 "saturation $conf->{quantile}th percentile");
224 if ($conf->{min}) {
225 $key .= "; $conf->{type} range $conf->{min}-$conf->{max}";
226 }
227 if ($conf->{filter_01}) {
228 $key .="; 0-1 Hz filter ON";
229 }
230  
231 my $feature_list = $self->new_feature_list;
232 my $link = sub { shift->url || 0 };
233 $feature_list->add_type( spectrogram => { glyph => 'spectrogram',
234 bump => 0, # must be zero
235 height => $conf->{y_unit} * ($max_f - $min_f + 1),
236 key => $key,
237 win => $win,
238 link => $link } );
239  
240 my $start = 0;
241  
242 my $skipped;
243  
244 until ( $start > ( $end - $win ) ) {
245 my $sub_seq = substr $seq, $start, $win;
246  
247 # runs of N's will screw things up.
248 $sub_seq =~ s/[^gatcGATC]/N/g;
249 my $has_Ns = $sub_seq =~ tr/N/a/;
250  
251 unless ( $has_Ns > $win/10 ) {
252 # Digitize the DNA
253 my ($g,$a,$t,$c) = make_numeric($sub_seq);
254  
255 # take the magnitude of the DFT
256 dft(\$_) for ($g,$a,$t,$c);
257  
258 # get rid of DC 'component'
259 if ($conf->{filter_01} ) {
260 for ($g,$a,$t,$c) {
261 $_->[0] = 0;
262 $_->[1] = 0;
263 }
264 }
265
266 push @g, [@{$g}[$min_f..$max_f]];
267 push @a, [@{$a}[$min_f..$max_f]];
268 push @t, [@{$t}[$min_f..$max_f]];
269 push @c, [@{$c}[$min_f..$max_f]];
270 push @coords, [$start + $offset + 1, $start + $offset + $inc];
271 }
272 else {
273 $skipped++;
274 }
275  
276 $start += $inc;
277 }
278  
279  
280 # warn if there are a lot of 'N's
281 if ($skipped) {
282 error("Spectrogram: blank areas correspond to ambiguous sequence regions with > 10% 'N's");
283 }
284  
285  
286 # max out the intensity range at the nth
287 # percentile to avoid saturation of color intensity
288 my $stat = Statistics::Descriptive::Full->new;
289 my @data = grep {defined $_} map {@$_} @g,@a,@t,@c;
290  
291 $stat->add_data(@data);
292 my $max = $stat->percentile($conf->{quantile});
293 my @labels = $min_f .. $max_f;
294 @labels = map {$_ ? 2*$win/$_ : $win} @labels if $conf->{type} eq 'period';
295 my $first = 1;
296 for my $coords (@coords) {
297 my ($start, $end) = @$coords;
298
299 # make a link for zooming in
300 (my $url = self_url) =~ s/\?.+//;;
301 my $pad = int $segment->length/20;
302 my $z_start = $start - $pad;
303 my $z_stop = $end + $pad;
304 my $name = $segment->ref .":$z_start..$z_stop";
305 $url .= "?name=$name";
306
307 my $G = shift @g;
308 my $A = shift @a;
309 my $T = shift @t;
310 my $C = shift @c;
311
312 my $atts = { g => $G,
313 a => $A,
314 t => $T,
315 c => $C,
316 max => $max };
317
318 # y-axis labels for first column
319 if ($first) {
320 $atts->{labels} = [$conf->{type},@labels];
321 $first = 0;
322 }
323
324 # create a column for the spectrogram. Offset the seuquence
325 # coordinates so that features in the specrogam are directly below
326 # the corresponding DNA
327 my $sf = Bio::Graphics::Feature->new( -type => 'spectrogram',
328 -source => 'calculated',
329 -start => $start + $slide_offset,
330 -end => $end + $slide_offset,
331 -ref => $segment->ref,
332 -url => $url,
333 -attributes => $atts );
334
335 $feature_list->add_feature($sf);
336
337 }
338
339 return $feature_list;
340 }
341  
342 sub configure_form {
343 my $self = shift;
344 my $conf = $self->configuration;
345 my $segment = ($self->segments)[0];
346  
347 my $state = { on => 0, override => 1 };
348 my $description = p(
349 $self->_help_message($state,
350 span({-class=>'searchtitle'},
351 'What is a DNA spectrogram?'),
352 $self->long_description)
353 );
354  
355 my $form = $description;
356
357 my $msg = $self->_help_message( $state, 'Sliding window size', split "NL", <<'END;');
358 Window size is the number of bases to include in each calculation.NL
359 Overlap is the increment by which the window slides (amount of overlap).NL
360 <font color=red>Note: </font>larger window sizes and/or smaller
361 overlaps increase computation time.
362 END;
363  
364 $form .= h4({-class => 'searchtitle'}, $msg) .
365 p( 'Window: size ',
366 popup_menu( -name => $self->config_name('win'),
367 -values => [8,16,32,64,128,256,512,1024,2048,4096,8192],
368 -default => $conf->{win} ),
369 ' bp' . br. br . ' overlap ',
370 textfield( -name => $self->config_name('inc'),
371 -value => $conf->{inc},
372 -size => 4 ),
373 'bp' );
374
375 $msg = $self->_help_message( $state, 'Display options', split "NL", <<'END;');
376 The allowed range of periods or frequencies controls spectrogram height
377 and calculation time.NL
378 period = size (bp) of structure or repeat unit, calculated as
379 2*(window size)/frequency.NL
380 row height = the height (pixels) of each frequency row in the spectrogram.
381 END;
382
383 $form .= br . h4({-class => 'searchtitle'}, $msg) .
384 p( 'Restrict ',
385 popup_menu( -name => $self->config_name('measure'),
386 -values => [qw/period frequency/],
387 -default => $conf->{type} ),
388 ' to between ',
389 textfield( -name => $self->config_name('min'),
390 -value => $conf->{min},
391 -size => 4 ),
392 ' and ',
393 textfield( -name => $self->config_name('max'),
394 -value => $conf->{max},
395 -size => 4 ),
396 br . br . 'Row height',
397 textfield( -name => $self->config_name('y_unit'),
398 -value => $conf->{y_unit},
399 -size => 2 ),
400 ' px ' );
401  
402  
403 $msg = $self->_help_message( $state, 'Image saturation', split "NL", <<'END;');
404 Lowering the saturation value will reduce the dominance of very bright
405 colors on the spectrogram by setting an arbitrary maximum value
406 (expressed as a percentile rank).NL
407 Setting a lower saturation will reduce the effects of very high
408 amplitude signals elsewhere in the spectrogram and help to
409 emphasize less intense features.NL
410 The higher the saturation value is set, the darker the "background"
411 of the spectrogram.NL
412 There is a very large amplitude signal at frequency 0 Hz
413 (the very top of the spectrogram), with some bleed over to 1 Hz.NL
414 Filtering out these frequencies will help make the fainter
415 spots more visible by decreasing the overall range of signal
416 magnitudes.
417 END;
418  
419 $form .= br . h4({-class => 'searchtitle'}, $msg) .
420 p( 'Saturate color intensity at the ',
421 textfield( -name => $self->config_name('quantile'),
422 -value => $conf->{quantile},
423 -size => 5 ),
424 'th percentile' );
425  
426 my @checked = (checked => 'checked') if $conf->{filter_01};
427 $form .= p( checkbox( -name => $self->config_name('filter_01'),
428 @checked,
429 -label => 'Filter out 0-1 Hz' ));
430  
431 return $form;
432 }
433  
434 sub _help_message {
435 my $self = shift;
436 my $state = shift;
437 my $section = shift;
438 my @items = map li($_).br, @_;
439
440 my $details = table( {-width => 800},
441 Tr( td( {-class => 'databody'}, ul(@items))));
442
443 $self->toggle( $state, $section, $details );
444 }
445
446 sub make_numeric {
447 my $seq = lc shift;
448 my @seq = split q{}, $seq;
449  
450 my @G = map { $_ eq 'g' ? 1 : 0 } @seq;
451 my @A = map { $_ eq 'a' ? 1 : 0 } @seq;
452 my @T = map { $_ eq 't' ? 1 : 0 } @seq;
453 my @C = map { $_ eq 'c' ? 1 : 0 } @seq;
454  
455 return (\@G,\@A,\@T,\@C);
456 }
457  
458 sub dft {
459 # my $self = shift;
460 # my $conf = $self->configuration;
461 # my $remove_DC = $conf->{remove_DC};
462 my $array = shift;
463 my $fft = Math::FFT->new($$array);
464  
465 # this is a call to the 'real' DFT (no imaginary numbers)
466 # algorithm, which is actually implented via the FFT
467 # algorithm
468 my $dft = $fft->rdft;
469 $dft = magnitude(@$dft);
470 $$array = $dft;
471 }
472  
473 sub magnitude {
474 $_ = $_**2 for @_;
475 return \@_;
476 }
477  
478 sub _process_msg {
479 my $msg = shift;
480 $msg =~ s/\\n|\n\n/BREAK/gm;
481 $msg =~ s/\n/ /gm;
482 $msg =~ s/BREAK/\\n/g;
483 $msg;
484 }
485  
486 sub description {
487 my $self = shift;
488 return p(<<END);
489 The DNA Spectrogram plugin builds a spectrogram for digitized DNA sequence using
490 the short-time fourier transform (STFT) method. The plugin was written by
491 Sheldon McKay (mckays\@cshl.edu).
492 END
493 }
494  
495 sub long_description {
496 my $image_dir = IMAGE_DIR;
497 return table( {-width => 800}, Tr( td({-class => 'databody'},
498 p(<<END) .
499 The Spectrogram plugin builds up a spectrogram for digitized DNA sequence using the short-time fourier transform (STFT) method,
500 adapted from classical digital signal processing.
501 Spectrogram analysis of DNA can help uncover non-random structures in DNA sequences, some examples of which are coding DNA
502 and repeats (For example, see <a href="http://www.hindawi.com/GetPDF.aspx?doi=10.1155/S1110865704310048"> this article</a>).
503 </p>
504 <h3>Coding DNA examples</h3>
505 <p>
506 This is an example of a spectrogram of a genic region of yeast chromosome I. Note the linear feature at period 3 (codon size).
507 <img border=1 src="$image_dir/yeast_I_genes_spec.png">
508 </p>
509 <br>
510 <p>
511 This is an example of a portion of <i>C. elegans</i> predicted gene Y38C1AB.4. Note the differences between exons and introns.
512 <img border=1 src="$image_dir/worm_exons_spec.png">
513 </p>
514  
515 <h3>Repeats</h3>
516 <p>
517 Repeats cause a ladder-like series of horizontal lines. Short repeats, such as telomeric repeats, are most visible with small
518 window sizes. Longer repeats, such as minisatellites, are best seen with larger window sizes.
519 </p>
520 <p>
521 This is an example of telomeric repeats on <i>C. elegans</i> chromosome I.
522 <img border=1 src="$image_dir/worm_telomeric_spec.png">
523 </p>
524 END
525  
526 p(<<END) .
527 <h3>How is the DNA spectrogram calculated?</h3>
528 <p>
529 A sliding window of variable size and overlap is used to calculate the spectrogram, which is displayed graphically as a track in the
530 genome browser. Each window is a subsegment of DNA and corresponds to a 'column' in the graphical display of the spectrogram. The
531 window slides along the sequence, from left to right, at a set increment, which corresponds to the column width.
532 </p>
533 <p>
534 The spectrogram refers collectively to all of the rows and columns seen in the graphical display.
535 </p>
536 <p>
537 The spectrogram has <i>n</i> rows, where <i>n</i> is the number of bases in the window. Each row corresponds
538 to a discrete 'frequency' from 0 -> <i>n</i>-1.
539 </p>
540 <p>
541 An arguably more intuitive way to relate this to DNA sequence to calculate the 'period' (<i>n</i>/frequency*2).
542 If we see a feature in the spectrogram at period <i>x</i>, there is a non-random structure
543 with a periodicity of <i>x</i> nucleotides. The chief example of this would be coding DNA at period 3.
544 </p>
545 <br>
546 The DNA sequence is converted from analog to digital by creating four binary indicator sequences:
547  
548 <pre>
549 G A T C C T C T G A T T C C A A
550 G 1 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0
551 A 0 1 0 0 0 0 0 0 0 1 0 0 0 0 1 1
552 T 0 0 1 0 0 1 0 1 0 0 1 1 0 0 0 0
553 C 0 0 0 1 1 0 1 0 0 0 0 0 1 1 0 0
554 </pre>
555 <br>
556 <p>
557 The magnitude of the discrete fourier transform (DFT) is calculated seperately for each of the four indicator sequences.
558 The algorithm used is the fast fourier transfrom (FFT; via Math::FFT), which is much faster than the original DFT algorithm
559 but is limited in that only base2 numbers (128, 256, 512, etc) can be used for window sizes. This is necessary to make the
560 spectrogram calculation fast enough for real-time use.
561 </p>
562  
563 <p>
564 For graphical rendering, each transformed sequence is assigned a color (A=blue; T=red; C=green; G=yellow). The colors for each
565 base are superimposed on the image. In a given spot on the spectrogram, the brightness corresponds to the magnitide (signal intensity)
566 and the color corresponds to the dominant base at that frequency/period. If no single base predominates, an intermediate color
567 is calculated based on the relative magnitudes.
568 </p>
569 <p>
570 The spectrogram is visible as a track in the generic genome browser. Please note that the calculations and graphical rendering are computationally
571 intensive, so the image will take a while to load, especially with larger sequence regions and/or small increments for the sliding
572 window.
573 </p>
574 <p>
575 After you have launched this plugin, the spectrogram will continue to be calculated in the main gbrowse display until you turn off the 'Spectrogram' track.
576 </p>
577 END
578  
579 p("The plugin was written by Sheldon McKay (mckays\@cshl.edu)"))));
580  
581 }
582  
583 sub toggle {
584 my $self = shift;
585 my ($state,$section_head,@body) = @_;
586 my $buttons_dir = $CONFIG->globals->button_url || BUTTONS_DIR;
587 $state ||= {};
588 $state->{plus_img} = "$buttons_dir/query.png";
589 $state->{minus_img} = "$buttons_dir/minus12.png";
590  
591 my ($label) = $self->language->tr($section_head) || $section_head;
592 return toggle_section($state,$label,b($label),@body);
593 }
594  
595 1;
596