blib/lib/Bio/App/SELEX/Stockholm.pm untested

filter: Statementstmt 0.0% 0 / 481 Branchbran 0.0% 0 / 164 Conditioncond 0.0% 0 / 38 MC/DCmcdc 0.0% 0 / 24 Subroutinesub 0.0% 0 / 38 Podpod 0.0% 0 / 34 totaltotal 0.0% 0 / 779 CC 83 SCAR 42.5
CC
83
Cov
0%
AUTOLOAD
210.0
parse_input_line
182.0
concatenate
132.0
CRAP 69.8
1 #!/usr/bin/env perl
2  
3 =head1 NAME
4  
5 Stockholm.pm
6  
7 =head1 SYNOPSIS
8  
9 Lightweight Perl module encapsulating a Stockholm multiple alignment.
10  
11 Author: Ian Holmes with minor modifications by Christopher Bottoms
12  
13 (This is modified from the original Stockholm.pm from the DART suite, see
14 https://github.com/ihh/dart/blob/master/perl/Stockholm.pm. Modifications
15 allowed for passing a generic consensus annotation to the constructor.)
16  
17 For more detail on Stockholm format itself, see the following URL:
18  
19 http://biowiki.org/StockholmFormat
20  
21 =head1 METHODS
22  
23 =cut
24  
25 package Bio::App::SELEX::Stockholm;
26  
27 use strict;
28 use warnings;
29 use vars '@ISA';
30  
31 use Carp qw(carp cluck croak);
32  
33 # define the gap alphabet
34 my $gapChars = '-._';
35 my $gapCharsRegexp = '\-\._';
36 sub gapCharsRegexp { return $gapCharsRegexp }
37  
38 =head2 new
39  
40 my $stock = Stockholm->new();
41  
42 Creates an empty Stockholm object.
43  
44 =cut
45  
46 # constructor
47 sub new {
48 my ($class, %opts) = @_;
49 my $self = {
50 'seqname' => [], # order of sequences
51 'seqdata' => {},
52 'gf' => {}, # Generic File annotation (freeform)
53 'gc' => $opts{gc} || {}, # Generic Consensus annotation (by-column)
54 'gs' => {}, # Generic Sequence annotation (by-sequence, freeform)
55 'gr' => {}, # Generic by-Row annotation (by-sequence, by-column)
56 'gfOrder' => [] # order of GF lines
57 };
58 bless $self, ref($class) || $class;
59 return $self;
60 }
61  
62 =head2 from_file
63  
64 my $stock = Stockholm->from_file ($filename);
65  
66 Creates a new Stockholm object and reads it from a file.
67  
68 =cut
69  
70 # from_file method
71 sub from_file {
72 my ( $class, $filename ) = @_;
73  
74 local *FILE;
75 open FILE, "<$filename" or croak "Couldn't open $filename: $!";
76 my $self = $class->from_filehandle( \*FILE );
77 close FILE;
78  
79 return $self;
80 }
81  
82 =head2 from_filehandle
83  
84 my $stock = Stockholm->from_filehandle ($filehandle);
85  
86 Creates a new Stockholm object and reads it from a filehandle.
87  
88 =cut
89  
90 # from_filehandle method
91 sub from_filehandle {
92 my ( $class, $filehandle ) = @_;
93  
94 my $self = $class->new;
95 local $_;
96 while (<$filehandle>) {
97 last if $self->parse_input_line($_);
98 }
99 carp "Warning: alignment is not flush" unless $self->is_flush();
100  
101 return $self;
102 }
103  
104 =head2 to_file
105  
106 $stock->to_file ($filename);
107  
108 Writes a Stockholm object to a file.
109  
110 =cut
111  
112 # to_file method
113 sub to_file {
114 my ( $self, $filename, $maxcols ) = @_;
115  
116 local *FILE;
117 open FILE, ">$filename"
118 or croak "Couldn't open '$filename' for writing: $!";
119 print FILE $self->to_string($maxcols);
120 close FILE or croak "Couldn't close '$filename': $!";
121  
122 return $filename;
123 }
124  
125 =head2 to_string
126  
127 print $stock->to_string ($maxcols)
128 print $stock->to_string ($maxcols, ARG1=>VAL1, ARG2=>VAL2 ...)
129 print $stock->to_string (MAXCOLS=>$maxcols, ARG1=>VAL1, ARG2=>VAL2 ...)
130  
131 Returns the object as a Stockholm-formatted string.
132  
133 ARGs can include...
134 MAXCOLS -- limit maximum number of columns (can also be specified as a single scalar arg)
135 NOSEQDATA -- don\'t print any sequence data (can be used this to compress output)
136  
137 =cut
138  
139 # to_string method
140 # Usage:
141 # $stock->to_string ($maxcols)
142 # $stock->to_string ($maxcols, ARG1=>VAL1, ARG2=>VAL2 ...)
143 # $stock->to_string (MAXCOLS=>$maxcols, ARG1=>VAL1, ARG2=>VAL2 ...)
144 # Args:
145 # MAXCOLS -- limit maximum number of columns (can also be specified as a single scalar arg)
146 # NOSEQDATA -- don't print any sequence data ("windowlicker.pl" uses this to compress output)
147 sub to_string {
148 my ( $self, @args ) = @_;
149 my ( %args, $maxcols );
150 if ( @args % 2 == 1 ) {
151 $maxcols = shift @args;
152 %args = @args;
153 }
154 else {
155 %args = @args;
156 $maxcols = $args{'MAXCOLS'};
157 }
158 $maxcols = 80 unless defined $maxcols; # default 80-column output
159  
160 # init output array
161 my @out;
162 push @out, "# STOCKHOLM 1.0";
163  
164 # determine alignment columns, legend columns & effective columns per line
165 my $acols = $self->columns;
166 my $lcols = $self->lcols;
167 my $colstep = $maxcols < 1 ? $acols : $maxcols - $lcols - 1;
168 $colstep = $maxcols
169 if $colstep < 1; # protect against negative and 0 colstep...
170  
171 # GF lines
172 # check for gfOrder (insane, fragile Stockholm line ordering strikes again)
173 if ( @{ $self->gfOrder } == map { (@$_) } values %{ $self->gf } )
174 { # gfOrder same number of lines as #=GF block?
175 my %gfCursor = map ( ( $_ => 0 ), keys %{ $self->gf } );
176 foreach my $feature ( @{ $self->gfOrder } ) {
177 push @out,
178 $self->prettify(
179 $lcols,
180 "#=GF $feature",
181 $self->gf_($feature)->[ $gfCursor{$feature}++ ]
182 );
183 }
184 }
185 else {
186 @{ $self->gfOrder } = (); # gfOrder is useless, so flush it
187 foreach my $feature ( sort { $a cmp $b } keys %{ $self->gf } ) {
188 push @out,
189 $self->prettify(
190 $lcols,
191 "#=GF $feature",
192 @{ $self->gf_($feature) }
193 );
194 }
195 }
196  
197 # GS lines
198 my @gs_seqname = @{ $self->seqname };
199 my %gs_seqname_hash = map ( ( $_ => 1 ),
200 grep ( !exists $self->seqdata->{$_},
201 map ( keys( %{ $self->gs_($_) } ), keys %{ $self->gs } ) ) );
202 push @gs_seqname, keys %gs_seqname_hash;
203 foreach my $feature ( sort { $a cmp $b } keys %{ $self->gs } ) {
204 my $hash = $self->gs_($feature);
205 foreach my $seqname ( grep ( exists( $hash->{$_} ), @gs_seqname ) ) {
206 push @out,
207 $self->prettify(
208 $lcols,
209 "#=GS $seqname $feature",
210 @{ $hash->{$seqname} }
211 );
212 }
213 }
214  
215 my @gcfeat = sort { $a cmp $b } keys %{ $self->gc };
216 my @gr_seqname = @{ $self->seqname };
217 my %gr_seqname_hash = map ( ( $_ => 1 ),
218 grep ( !exists $self->seqdata->{$_},
219 map ( keys( %{ $self->gr_($_) } ), keys %{ $self->gr } ) ) );
220 push @gr_seqname, keys %gr_seqname_hash;
221  
222 # Loop over columns
223 for ( my $col = 0 ; $col < $acols ; $col += $colstep ) {
224  
225 # GC lines
226 foreach my $feature (@gcfeat) {
227 push @out,
228 $self->prettify(
229 $lcols,
230 "#=GC $feature",
231 safe_substr( $self->gc_($feature), $col, $colstep )
232 );
233 }
234 for ( my $i = 0 ; $i < @gr_seqname ; ++$i ) {
235 my $seqname = $gr_seqname[$i];
236  
237 # Sequences
238 # warn "Writing cols $col+$colstep for $seqname";
239 push @out,
240 $self->prettify( $lcols, $seqname,
241 safe_substr( $self->seqdata->{$seqname}, $col, $colstep ) )
242 if exists $self->seqdata->{$seqname}
243 && !$args{'NOSEQDATA'};
244  
245 # GR lines
246 foreach my $feature (
247 grep ( exists( $self->gr->{$_}->{$seqname} ),
248 keys %{ $self->gr } ) )
249 {
250  
251 # warn "Writing cols $col+$colstep for $seqname $feature";
252 push @out,
253 $self->prettify(
254 $lcols,
255 "#=GR $seqname $feature",
256 safe_substr(
257 $self->gr_($feature)->{$seqname},
258 $col, $colstep
259 )
260 );
261 }
262 }
263 push @out, "";
264 }
265  
266 # alignment separator
267 push @out, "//";
268  
269 # convert output array to string & return
270 return join( "", map ( "$_\n", @out ) );
271 }
272  
273 =head2 copy
274  
275 my $newStock = $stock->copy();
276  
277 Does a deep-copy, duplicating all information.
278  
279 =cut
280  
281 # deep-copy constructor
282 sub copy {
283 my ($self) = @_;
284 my $stock = Stockholm->new;
285  
286 # Sequence names & data
287 @{$stock->seqname} = @{$self->seqname};
288 %{$stock->seqdata} = %{$self->seqdata};
289  
290 #=GF
291 while (my ($feature, $arrayRef) = each %{$self->gf}) {
292 $stock->gf->{$feature} = [@$arrayRef];
293 }
294 @{$stock->gfOrder} = @{$self->gfOrder};
295  
296 #=GC
297 while (my ($feature, $string) = each %{$self->gc}) {
298 $stock->gc->{$feature} = $string;
299 }
300  
301 #=GR
302 while (my ($feature, $seqHash) = each %{$self->gr}) {
303 $stock->gr->{$feature} = {%$seqHash};
304 }
305  
306 #=GS
307 while (my ($feature, $seqHash) = each %{$self->gs}) {
308 $stock->gs->{$feature} = {%$seqHash};
309 }
310  
311 # Return
312 return $stock;
313 }
314  
315 =head2 columns
316  
317 my $cols = $stock->columns()
318  
319 Returns the number of columns in this alignment.
320  
321 =cut
322  
323 # Number of columns
324 sub columns {
325 my ($self) = @_;
326  
327 return max(map(length($_),
328 values(%{$self->seqdata}),
329 values(%{$self->gc}),
330 map(values(%$_), values(%{$self->gr}))));
331 }
332  
333 =head2 sequences
334  
335 my $rows = $stock->sequences()
336  
337 Returns the number of sequences (i.e. rows) in this alignment.
338  
339 =cut
340  
341 # Number of sequences (i.e. rows)
342 sub sequences {
343 my ($self) = @_;
344 return @{$self->seqname} + 0;
345 }
346  
347 =head2 seqname
348  
349 my $rowName = $stock->seqname->[$rowIndex];
350  
351 Returns a reference to an array of sequence names.
352  
353 =head2 seqdata
354  
355 my $row = $stock->seqdata->{$rowName};
356  
357 Returns a reference to a hash of alignment rows, keyed by sequence name.
358  
359 =head2 gf
360  
361 my @gf = @{$stock->gf->{FEATURE}};
362 my @gf = @{$stock->gf_FEATURE};
363  
364 Returns a reference to an array of all the lines beginning '#=GF FEATURE ...'
365  
366 =head2 gc
367  
368 my $gc = $stock->gc->{FEATURE};
369 my $gc = $stock->gc_FEATURE;
370  
371 Returns the line beginning '#=GC FEATURE ...'
372  
373 =head2 gs
374  
375 my @gs = @{$stock->gs->{FEATURE}->{SEQNAME}};
376 my @gs = @{$stock->gs_FEATURE->{SEQNAME}};
377  
378 Returns a reference to an array of all the lines beginning '#=GS SEQNAME FEATURE ...'
379  
380 =head2 gr
381  
382 my $gr = $stock->gr->{FEATURE}->{SEQNAME};
383 my $gr = $stock->gr_FEATURE->{SEQNAME};
384  
385 Returns the line beginning '#=GR SEQNAME FEATURE ...'
386  
387 =cut
388  
389  
390 # catch all methods by default
391 sub AUTOLOAD {
392 my ($self, @args) = @_;
393 my $sub = our $AUTOLOAD;
394 $sub =~ s/.*:://;
395  
396 # check for DESTROY
397 return if $sub eq "DESTROY";
398  
399 # check for GF, GC, GS, GR tag_feature accessors
400 # e.g. $self->GF_ID
401 # can also use $self->GF_('ID')
402 if ($sub =~ /^(gf|gc|gs|gr)_(\S*)$/i) {
403 my ($tag, $feature) = ($1, $2);
404 $tag = lc $tag;
405 $feature = shift(@args) unless length $feature;
406 my $hash = $self->{$tag};
407 if (@args) {
408 $hash->{$feature} = shift(@args); # TODO: check ref-type of arg
409 }
410 cluck "Warning: ignoring extra arguments to ${tag}_$feature"
411 if @args > 0;
412 if (!defined $hash->{$feature}) {
413 $hash->{$feature} =
414 $tag eq "gf" ? [] :
415 $tag eq "gc" ? "" :
416 $tag eq "gs" ? {} :
417 $tag eq "gr" ? {} :
418 croak "Unreachable";
419 }
420 return $hash->{$feature};
421 }
422  
423 # check for ordinary accessors
424 if (exists $self->{$sub}) {
425 croak "Usage: $sub() or $sub(newValue)" if @args > 1;
426 return
427 @args
428 ? $self->{$sub} = $args[0]
429 : $self->{$sub};
430 }
431  
432 # croak
433 croak "Unsupported method: $sub";
434 }
435  
436  
437 # pretty print line(s)
438 sub prettify {
439 my ($self, $lcols, $legend, @data) = @_;
440 # This horribly inefficient/redundant series of transformations comes out with something I like (IH, 7/24/07)
441 # Trim it down? pah! Like I have nothing better to do
442 $legend = sprintf ("% ${lcols}s", $legend);
443 $legend =~ s/^(\s+)(\#=\S\S)(\s+\S+)$/$2$1$3/;
444 $legend =~ s/^(\s+)(\#=\S\S\s+\S+)(\s+\S+)$/$2$1$3/;
445 $legend =~ s/^(\s\s\s\s\s)(\s+)([^\#]\S+)/$1$3$2/;
446 return map ("$legend $_", @data);
447 # (pukes into cold coffee cup)
448 }
449  
450 # legend width (subtract this from maxcols-1 to get number of columns available for sequence display)
451 sub lcols {
452 my ($self) = @_;
453 my $lcols = max ($self->maxNameLen,
454 map(length("#=GF $_"), keys(%{$self->gf})),
455 map(length("#=GC $_"), keys(%{$self->gc})));
456 while (my ($gr_key, $gr_hash) = each %{$self->gr}) {
457 $lcols = max ($lcols, map(length("#=GR $gr_key $_"), keys(%$gr_hash)));
458 }
459 while (my ($gs_key, $gs_hash) = each %{$self->gs}) {
460 $lcols = max ($lcols, map(length("#=GS $gs_key $_"), keys(%$gs_hash)));
461 }
462 return $lcols;
463 }
464  
465 # safer version of substr (doesn't complain if startpoint outside of string)
466 sub safe_substr {
467 my ($string, $start, $len) = @_;
468 return "" if !defined($string) || $start > length $string;
469 if (defined $len) {
470 return substr ($string, $start, $len);
471 } else {
472 return substr ($string, $start); # print from $start to end if no length specified
473 }
474 }
475  
476 =head2 add_gf
477  
478 $stock->add_gf (FEATURE, $line)
479 $stock->add_gf (FEATURE, $line1, $line2, ...)
480 $stock->add_gf (FEATURE, @lines)
481 $stock->add_gf (FEATURE, "$line1\n$line2\n$...")
482  
483 Add '#=GF FEATURE' annotation, preserving the order of the '#=GF' lines
484 (damn those crazy context-sensitive Stockholm semantics!)
485  
486 Each list entry gets printed on its own line.
487  
488 =cut
489  
490 # Add #=GF annotation, preserving the order of the #=GF lines
491 # (damn those crazy context-sensitive Stockholm semantics!)
492 #
493 # Usage:
494 # $stock->add_gf ($gfFeature, $line);
495 # $stock->add_gf ($gfFeature, $line1, $line2, ...);
496 # $stock->add_gf ($gfFeature, @lines);
497 # $stock->add_gf ($gfFeature, "$line1\n$line2\n$...");
498 #
499 # Each list entry gets printed on its own line.
500 #
501 sub add_gf {
502 my ($self, $feature, @data) = @_;
503 unless (@data > 0) {
504 carp "Missing parameters to 'add_gf'; nothing will be done";
505 return;
506 }
507  
508 foreach my $line (map {$_ eq '' ? '' : split ("\n", $_, -1)} @data) {
509 push @{$self->gf_($feature)}, $line;
510 push @{$self->gfOrder}, $feature;
511 }
512 }
513  
514 =head2 set_gf
515  
516 $stock->set_gf (FEATURE, $line)
517 $stock->set_gf (FEATURE, $line1, $line2, ...)
518 $stock->set_gf (FEATURE, @lines)
519 $stock->set_gf (FEATURE, "$line1\n$line2\n$...")
520  
521 Set a '#=GF FEATURE ...' annotation.
522 The difference between this and 'add_gf' is that here, if this sequence and
523 feature have an annotation already, it will be overwritten instead of appended to.
524  
525 As with add_gf, each list entry gets printed on its own line.
526  
527 =cut
528  
529 # Set a #=GF annotation.
530 # The difference between this and 'add_gf' is that here, if this sequence and
531 # feature have an annotation already, it will be overwritten instead of appended to.
532 #
533 # Usage:
534 # $stock->set_gf ($gfFeature, $line);
535 # $stock->set_gf ($gfFeature, $line1, $line2, ...);
536 # $stock->set_gf ($gfFeature, @lines);
537 # $stock->add_gf ($gfFeature, "$line1\n$line2\n$...");
538 #
539 # Each list entry gets printed on its own line.
540 sub set_gf {
541 my ($self, $feature, @data) = @_;
542 unless (defined $self->{gf}->{$feature}) {
543 carp "No #=GF feature '$feature' to set, creating new";
544 $self->add_gf ($feature, @data);
545 return;
546 }
547 @data = map {$_ eq '' ? '' : split ("\n", $_, -1)} @data;
548  
549 ### go to insane lengths to preserve original line ordering
550  
551 my %gfCursor = map {$_ => 0} keys %{$self->{gf}};
552 my (%new_gfFeature, @new_gfOrder);
553  
554 foreach my $curFeat (@{$self->{gfOrder}}) {
555 $new_gfFeature{$curFeat} = [] unless defined $new_gfFeature{$curFeat};
556  
557 if ($curFeat eq $feature) {
558 if (@data) {
559 push (@{$new_gfFeature{$curFeat}}, shift @data);
560 push (@new_gfOrder, $curFeat);
561 }
562 }
563 else {
564 push (@{$new_gfFeature{$curFeat}},
565 $self->{gf}->{$curFeat}->[$gfCursor{$curFeat}++]);
566 push (@new_gfOrder, $curFeat);
567 }
568 }
569  
570 # still have lines left, insert them after last occurence of feature tag
571 if (@data) {
572 my $insertAt = $#new_gfOrder;
573 $insertAt-- while $new_gfOrder[$insertAt] ne $feature;
574 splice (@new_gfOrder, ++$insertAt, 0, map {$feature} @data);
575 push (@{$new_gfFeature{$feature}}, @data);
576 }
577  
578 $self->{gf} = {%new_gfFeature};
579 $self->{gfOrder} = [@new_gfOrder];
580 }
581  
582 =head2 get_gf
583  
584 my $gf = $stock->get_gf (FEATURE)
585  
586 Concatenates and returns all lines beginning '#=GF FEATURE ...'
587  
588 =cut
589  
590 # Get a #=GF annotation.
591 #
592 sub get_gf {
593 my ($self, $feature) = @_;
594 if (defined $self->{gf}->{$feature}) {
595 return join ("\n", @{$self->{gf}->{$feature}});
596 }
597 else {
598 #carp "No #=GF feature '$feature' in Stockholm object, returning undef";
599 return undef;
600 }
601 }
602  
603 =head2 add_gs
604  
605 $stock->add_gs (SEQNAME, FEATURE, $line)
606 $stock->add_gs (SEQNAME, FEATURE, $line1, $line2, ...)
607 $stock->add_gs (SEQNAME, FEATURE, @lines)
608 $stock->add_gs (SEQNAME, FEATURE, "$line1\n$line2\n$...")
609  
610 Add a GS annotation: '#=GS SEQNAME FEATURE ...'
611  
612 If such a line already exists for this sequence and feature, append to it.
613  
614 Each list entry gets printed on its own line.
615  
616 =cut
617  
618 # Add a GS annotation: #=GS <sequence> <feature> <free text>
619 # If one already exists for this sequence and feature, append to it.
620 #
621 # Usage:
622 # $stock->add_gs ($seq, $gsFeature, $line);
623 # $stock->add_gs ($seq, $gsFeature, $line1, $line2, ...);
624 # $stock->add_gs ($seq, $gsFeature, @lines);
625 # $stock->add_gs ($seq, $gsFeature, "$line1\n$line2\n$...");
626 #
627 # Each list entry gets printed on its own line.
628 #
629 sub add_gs {
630 my ($self, $seq, $feature, @text) = @_;
631 unless (@text > 0) {
632 carp "Missing parameters to 'add_gs' method; nothing will be done";
633 return;
634 }
635 @text = map {$_ eq '' ? '' : split ("\n", $_, -1)} @text;
636 push (@{$self->{gs}->{$feature}->{$seq}}, @text);
637 }
638  
639 =head2 set_gs
640  
641 $stock->set_gs (SEQNAME, FEATURE, $line)
642 $stock->set_gs (SEQNAME, FEATURE, $line1, $line2, ...)
643 $stock->set_gs (SEQNAME, FEATURE, @lines)
644 $stock->set_gs (SEQNAME, FEATURE, "$line1\n$line2\n$...")
645  
646 Set a GS annotation: '#=GS SEQNAME FEATURE ...'
647  
648 The difference between this and 'add_gs' is that here, if this sequence and
649 feature have an annotation already, it will be overwritten instead of appended to.
650  
651 Each list entry gets printed on its own line.
652  
653 =cut
654  
655 # Set a #=GS annotation.
656 # The difference between this and 'add_gs' is that here, if this sequence and
657 # feature have an annotation already, it will be overwritten instead of appended to.
658 #
659 # Usage:
660 # $stock->set_gs ($seq, $gsFeature, $line);
661 # $stock->set_gs ($seq, $gsFeature, $line1, $line2, ...);
662 # $stock->set_gs ($seq, $gsFeature, @lines);
663 # $stock->set_gs ($seq, $gsFeature, "$line1\n$line2\n$...");
664 #
665 # Each list entry gets printed on its own line.
666 #
667 sub set_gs {
668 my ($self, $seq, $feature, @text) = @_;
669 unless (@text > 0) {
670 carp "Missing parameters to 'set_gs' method; nothing will be done";
671 return;
672 }
673 @text = map {$_ eq '' ? '' : split ("\n", $_, -1)} @text;
674 $self->{gs}->{$feature}->{$seq} = [@text];
675 }
676  
677 =head2 get_gs
678  
679 my $gs = $stock->get_gs (SEQNAME, FEATURE)
680  
681 Concatenates and returns all lines beginning '#=GS SEQNAME FEATURE ...'
682  
683 =cut
684  
685 # Get a #=GS annotation.
686 #
687 sub get_gs {
688 my ($self, $seq, $feature) = @_;
689 unless (defined $feature) {
690 carp "Missing parameters to 'get_gs' method; nothing will be done";
691 return undef;
692 }
693 if (defined $self->{gs}->{$feature}->{$seq}) {
694 return join ("\n", @{$self->{gs}->{$feature}->{$seq}});
695 }
696 else {
697 #carp "Annotation for sequence $seq, feature $feature not found; returning empty string";
698 return undef;
699 }
700 }
701  
702 =head2 drop_columns
703  
704 my $success = $stock->drop_columns (@columns)
705  
706 Drops a set of columns from the alignment and the GC and GR annotations. Note
707 that this may break annotations where the column annotations are not
708 independent (e.g. you might drop one base in an RNA base pair, but not the
709 other). The caller is responsible for making sure the set of columns passed
710 in does not mess up the annoation.
711  
712 Arguments: a list of scalar, zero-based column indices to drop.
713  
714 Returns success of operation (1 for success, 0 for failure)
715  
716 =cut
717  
718 # Drops a set of columns from the alignment and the GC and GR annotations. Note
719 # that this may break annotations where the column annotations are not
720 # independent (e.g. you might drop one base in an RNA base pair, but not the
721 # other). The caller is responsible for making sure the set of columns passed
722 # in does not mess up the annoation.
723 #
724 # Arguments: a list of scalar, zero-based column indices to drop.
725 #
726 # Returns success of operation (1 for success, 0 for failure)
727 #
728 sub drop_columns {
729 my ($self, @columns) = @_;
730  
731 unless ($self->is_flush()) {
732 carp "File is not flush; cannot (should not) drop columns";
733 return 0;
734 }
735  
736 # drop from sequences and per-column annotations
737 foreach my $seq_or_annot ($self->{seqdata}, $self->{gc})
738 {
739 # for each sequence or annotation string
740 foreach my $key (keys %$seq_or_annot)
741 {
742 # convert string to array form
743 my @data = split (//, $seq_or_annot->{$key});
744 foreach my $col (@columns)
745 {
746 if ( ($col < 0) or ($col >= @data) ) {
747 carp "Column $col is out of range [1, ", scalar(@data),
748 "] in $key; can't drop, skipping";
749 }
750 else {
751 # blank out the column that should get dropped
752 $data[$col] = '';
753 }
754 }
755 # re-assemble back to string
756 $seq_or_annot->{$key} = join ('', @data);
757 }
758 }
759  
760 # drop from per-column/per-sequence annotations
761 foreach my $feat_key (keys %{$self->{gr}})
762 {
763 foreach my $seq_key (keys %{$self->{gr}->{$feat_key}})
764 {
765 my @data = split (//, $self->{gr}->{$feat_key}->{$seq_key});
766 foreach my $col (@columns)
767 {
768 if ( ($col < 0) or ($col >= @data) ) {
769 carp "Column $col is out of range [1, ", scalar(@data),
770 "] in $feat_key, $seq_key; can't drop, skipping";
771 }
772 else {
773 # blank out the column that should get dropped
774 $data[$col] = '';
775 }
776 }
777 # re-assemble back to string
778 $self->{gr}->{$feat_key}->{$seq_key} = join ('', @data);
779 }
780 }
781  
782 return 1;
783 }
784  
785 # parse line of Stockholm format file
786 # returns true if it finds a separator
787 sub parse_input_line {
788 my ($self, $line) = @_;
789 $line = $_ unless defined $line;
790  
791 # "#=GF [feature] [data]" line
792 if ($line =~ /^\s*\#=GF\s+(\S+)\s+(\S.*)\s*$/)
793 {
794 my ($feature, $data) = ($1, $2);
795 $self->add_gf ($feature, $data); # preserve order of #=GF lines, for crazy context-sensitive Stockholm semantics
796 }
797  
798 # "#=GC [feature] [data]" line
799 elsif ($line =~ /^\s*\#=GC\s+(\S+)\s+(\S+)\s*$/)
800 {
801 my ($feature, $data) = ($1, $2, $3);
802 $self->gc->{$feature} .= $data;
803 }
804  
805 # "#=GS [seqname] [feature] [data]" line
806 elsif ($line =~ /^\s*\#=GS\s+(\S+)\s+(\S+)\s+(\S.*)\s*$/)
807 {
808 my ($seqname, $feature, $data) = ($1, $2, $3);
809 my $gs = $self->gs_($feature);
810 $gs->{$seqname} = [] unless exists $gs->{$seqname};
811 push @{$gs->{$seqname}}, $data;
812 }
813  
814 # "#=GR [seqname] [feature] [data]" line
815 elsif ($line =~ /^\s*\#=GR\s+(\S+)\s+(\S+)\s+(\S+)\s*$/)
816 {
817 my ($seqname, $feature, $data) = ($1, $2, $3);
818 my $gr = $self->gr_($feature);
819 $gr->{$seqname} = "" unless exists $gr->{$seqname};
820 $gr->{$seqname} .= $data;
821 }
822  
823 # Unrecognised "#" line
824 elsif ($line =~ /^\s*\#.*$/) {
825 # warn "Comment line $line";
826 }
827  
828 # Alignment separator: return true to indicate loop exit
829 elsif ($line =~ /^\s*\/\/\s*$/)
830 {
831 return 1;
832 }
833  
834 # Sequence line
835 elsif ($line =~ /^\s*(\S+)\s*(\S*)\s*$/) { # allows empty sequence lines
836 my ($seqname, $data) = ($1, $2);
837 unless (defined $self->seqdata->{$seqname}) {
838 $self->seqdata->{$seqname} = "";
839 push @{$self->seqname}, $seqname; # preserve sequence order, for tidiness
840 }
841 $self->seqdata->{$seqname} .= $data;
842 }
843  
844 elsif ($line =~ /\S/)
845 {
846 carp "Ignoring line: $_";
847 }
848  
849 # This line wasn't a alignment separator: return false
850 return 0;
851 }
852  
853 =head2 empty
854  
855 my $isEmpty = $stock->empty
856  
857 Returns true if the alignment is empty (i.e. there are no sequences).
858  
859 =cut
860  
861 # empty?
862 sub empty {
863 my ($self) = @_;
864 return @{$self->seqname} == 0;
865 }
866  
867 =head2 subseq
868  
869 my $subseq = $stock->subseq (SEQNAME, $startPos)
870 my $subseq = $stock->subseq (SEQNAME, $startPos, $length)
871  
872 Returns a subsequence of the named alignment row.
873  
874 Note that the co-ordinates are with respect to the alignment columns (starting at zero), NOT sequence positions.
875 That is, gaps are counted.
876  
877 If $length is omitted, this call returns the subsequence from $startPos to the end of the row.
878  
879 =cut
880  
881 # Returns a subsequence.
882 #
883 # Arguments:
884 # $name - name/identifier of sequence
885 # $start - 0-based index of the starting nuc
886 # $len - length of subsequence (if not specified, returns subseq from $start to the end)
887 #
888 sub subseq {
889 my ($self, $name, $start, $len) = @_;
890  
891 my $seq = $self->{seqdata}->{$name};
892  
893 unless ($seq) {
894 carp "No sequence, returning empty string for subsequence of '$name'\n";
895 return '';
896 }
897  
898 my $seqlength = length $seq;
899  
900 if ( ($start > $seqlength) or ($start < 0) ) {
901 carp
902 "Subsequence start nuc $start is outside of sequence bounds ",
903 "[0, " . $seqlength-1 . "]; returning empty string for subsequence of $name\n";
904 return '';
905 }
906  
907 if (defined $len) {
908 carp "Specified length $len is < 1... are you sure you want this?\n" if $len < 1;
909 return substr ($seq, $start, $len);
910 }
911 else {
912 return substr ($seq, $start);
913 }
914 }
915  
916 =head2 get_column
917  
918 my $column = $stock->get_column ($colNum)
919  
920 Extracts the specified column and returns it as a string.
921  
922 The column number $colNum uses zero-based indexing.
923  
924 =cut
925  
926 # Extracts the specified column and returns it as a string.
927 #
928 # Arguments:
929 # $col - the column number
930 #
931 sub get_column {
932 my ($self, $col_num) = @_;
933 my $col_as_string;
934  
935 unless ($self->is_flush()) {
936 carp "File is not flush; cannot (should not) get column";
937 return 0;
938 }
939  
940 my $align_length = $self->columns();
941  
942 if ( ($col_num >= $align_length) or ($col_num < 0) ) {
943 carp
944 "Column index $col_num is outside of alignment bounds ",
945 "[1, $align_length]; returning empty string for column $col_num\n";
946 return '';
947 }
948 else {
949 foreach my $seq (@{$self->{seqname}}) {
950 $col_as_string .= substr ($self->{seqdata}->{$seq}, $col_num, 1);
951 }
952 return $col_as_string;
953 }
954 }
955  
956 =head2 map_align_to_seq_coords
957  
958 my ($start, $end) = $stock->map_align_to_seq_coords ($colStart, $colEnd, $seqName);
959 die "Failed" unless defined ($start);
960  
961 my ($start, $end) = $stock->map_align_to_seq_coords ($colStart, $colEnd, $seqName, $seqStart);
962 die "Failed" unless defined ($start);
963  
964 Given a range of column indices ($colStart, $colEnd), returns the coordinates
965 of sequence $seqName contained within that range, accounting for gaps.
966  
967 Returns start and end coordinates as a 2-ple list, or returns the empty list
968 if there is no sequence in the given range (i.e. range contains all gaps in
969 $seqName).
970  
971 You can provide $seqStart, which is the coordinate of the first non-gap
972 character in $seqName. If you don\'t, the default is that the sequence starts
973 at 1.
974  
975 =cut
976  
977 # Given a range of column indices ($colStart, $colEnd), returns the coordinates
978 # of sequence $seqName contained within that range, accounting for gaps.
979 #
980 # Returns start and end coordinates as a 2-ple list, or returns the empty list
981 # if there is no sequence in the given range (i.e. range contains all gaps in
982 # $seqName).
983 #
984 # You can provide $seqStart, which is the coordinate of the first non-gap
985 # character in $seqName. If you don't, the default is that the sequence starts
986 # at 1.
987 #
988 sub map_align_to_seq_coords {
989 my ($self, $colStart, $colEnd, $seqName, $seqStart) = @_;
990 $seqStart = 1 unless defined $seqStart;
991  
992 my $seq = $self->subseq ($seqName, $colStart, ($colEnd - $colStart + 1));
993  
994 if (my @seq = $seq =~ /[^$gapCharsRegexp]/g)
995 {
996 my $rangeStart;
997  
998 if ($colStart == 0) {
999 # special case: range starts in the first column
1000 $rangeStart = $seqStart;
1001 }
1002 else {
1003 my $prefix = $self->subseq ($seqName, 0, $colStart);
1004 $rangeStart = $seqStart + length (join ('', ($prefix =~ /[^$gapCharsRegexp]/g)));
1005 }
1006  
1007 return ($rangeStart, ($rangeStart + @seq - 1));
1008 }
1009 else {
1010 # no sequence in desired range (i.e. all gaps)
1011 return ();
1012 }
1013 }
1014  
1015 =head2 is_gap
1016  
1017 my $isGap = $stock->is_gap (SEQNAME, $colNum)
1018  
1019 Return true if a given (SEQNAME,column) co-ordinate is a gap.
1020  
1021 =cut
1022  
1023 # Return true if a given (rowname,column) co-ordinate is a gap
1024 sub is_gap {
1025 my ($self, $row_name, $col) = @_;
1026 my $s = $self->seqdata->{$row_name};
1027 my $c = substr ($s, $col, 1);
1028 return $c =~ /[$gapCharsRegexp]/;
1029 }
1030  
1031 =head2 subalign
1032  
1033 my $substock = $stock->subalign ($start, $len)
1034 my $substock = $stock->subalign ($start, $len, $strand)
1035  
1036 Returns a Stockholm object representing a sub-alignment of the current alignment,
1037 starting at column $start (zero-based) and containing $len columns.
1038  
1039 If $strand is supplied and is equal to '-', then the sub-alignment will be reverse-complemented.
1040  
1041 =cut
1042  
1043  
1044 # subalignment accessor
1045 sub subalign {
1046 my ($self, $start, $len, $strand) = @_;
1047 $strand = '+' unless defined $strand;
1048 my $stock = $self->copy;
1049  
1050 # Sequence data
1051 foreach my $seqname (@{$stock->seqname}) {
1052 $stock->seqdata->{$seqname} = safe_substr ($stock->seqdata->{$seqname}, $start, $len);
1053 if ($strand eq '-') {
1054 $stock->seqdata->{$seqname} = revcomp ($stock->seqdata->{$seqname});
1055 }
1056 }
1057  
1058 # GC lines
1059 foreach my $tag (keys %{$stock->gc}) {
1060 $stock->gc->{$tag} = safe_substr ($stock->gc->{$tag}, $start, $len);
1061 if ($strand eq '-') {
1062 $stock->gc->{$tag} = reverse $stock->gc->{$tag};
1063 }
1064 }
1065  
1066 # GR lines
1067 foreach my $tag (keys %{$stock->gr}) {
1068 foreach my $seqname (keys %{$stock->gr->{$tag}}) {
1069 $stock->gr->{$tag}->{$seqname} = safe_substr ($stock->gr->{$tag}->{$seqname}, $start, $len);
1070 if ($strand eq '-') {
1071 $stock->gr->{$tag}->{$seqname} = reverse ($stock->gr->{$tag}->{$seqname});
1072 }
1073 }
1074 }
1075  
1076 return $stock;
1077 }
1078  
1079 =head2 concatenate
1080  
1081 $stock->concatenate ($stock2)
1082  
1083 Concatenates another alignment onto the end of this one.
1084  
1085 =cut
1086  
1087 # concatenate another alignment onto the end of this one
1088 sub concatenate {
1089 my ($self, $stock) = @_;
1090  
1091 # get widths
1092 my $cols = $self->columns;
1093 my $catcols = $stock->columns;
1094  
1095 # Sequence data
1096 foreach my $seqname (@{$stock->seqname}) {
1097 if (exists $self->seqdata->{$seqname}) {
1098 $self->seqdata->{$seqname} .= $stock->seqdata->{$seqname};
1099 } else {
1100 push @{$self->seqname}, $seqname;
1101 $self->seqdata->{$seqname} = "." x $cols . $stock->seqdata->{$seqname};
1102 }
1103 }
1104 foreach my $seqname (@{$self->seqname}) {
1105 unless (exists $stock->seqdata->{$seqname}) {
1106 $self->seqdata->{$seqname} .= "." x $catcols;
1107 }
1108 }
1109  
1110 # GC lines
1111 foreach my $tag (keys %{$stock->gc}) {
1112 if (exists $self->gc->{$tag}) {
1113 $self->gc->{$tag} .= $stock->gc->{$tag};
1114 } else {
1115 $self->gc->{$tag} = "." x $cols . $stock->gc->{$tag};
1116 }
1117 }
1118 foreach my $tag (keys %{$self->gc}) {
1119 unless (exists $stock->gc->{$tag}) {
1120 $self->gc->{$tag} .= "." x $catcols;
1121 }
1122 }
1123  
1124 # GR lines
1125 foreach my $tag (keys %{$stock->gr}) {
1126 if (exists $self->gr->{$tag}) {
1127 foreach my $seqname (keys %{$stock->gr->{$tag}}) {
1128 if (exists $self->gr->{$tag}->{$seqname}) {
1129 $self->gr->{$tag}->{$seqname} .= $stock->gr->{$tag}->{$seqname};
1130 } else {
1131 $self->gr->{$tag}->{$seqname} = "." x $cols . $stock->gr->{$tag}->{$seqname};
1132 }
1133 }
1134 } else {
1135 $self->gr->{$tag} = {};
1136 foreach my $seqname (keys %{$stock->gr->{$tag}}) {
1137 $self->gr->{$tag}->{$seqname} = "." x $cols . $stock->gr->{$tag}->{$seqname};
1138 }
1139 }
1140 }
1141 foreach my $tag (keys %{$self->gr}) {
1142 foreach my $seqname (keys %{$self->gr->{$tag}}) {
1143 unless (exists $stock->gr->{$tag} && exists $stock->gr->{$tag}->{$seqname}) {
1144 $self->gr->{$tag}->{$seqname} .= "." x $catcols;
1145 }
1146 }
1147 }
1148  
1149 # GF and GS lines
1150 foreach my $tag (keys %{$stock->gf}) {
1151 $self->gf->{$tag} = [] unless exists $self->gf->{$tag};
1152 push @{$self->gf->{$tag}}, @{$stock->gf->{$tag}};
1153 }
1154  
1155 foreach my $tag (keys %{$stock->gs}) {
1156 $self->gs->{$tag} = {} unless exists $self->gs->{$tag};
1157 foreach my $seqname (keys %{$stock->gs->{$tag}}) {
1158 $self->gs->{$tag}->{$seqname} = [] unless exists $self->gs->{$tag}->{$seqname};
1159 push @{$self->gs->{$tag}->{$seqname}}, @{$stock->gs->{$tag}->{$seqname}};
1160 }
1161 }
1162 }
1163  
1164 # Reverse complement a sequence
1165 sub revcomp {
1166 my ($arg0, $arg1) = @_;
1167 my $seq;
1168  
1169 if (defined ($arg1)) { # must have been called externally (as method or package sub)
1170 $seq = $arg1;
1171 } else {
1172 $seq = $arg0;
1173 }
1174  
1175 $seq =~ tr/acgtuACGTU/tgcaaTGCAA/;
1176 $seq = reverse $seq;
1177 return $seq;
1178 }
1179  
1180 # Determine maximum sequence name length
1181 sub maxNameLen {
1182 my ($self) = @_;
1183 return max(map(length($_), @{$self->seqname}));
1184 }
1185  
1186 =head2 is_flush
1187  
1188 my $flush = $stock->is_flush()
1189  
1190 Returns true if the alignment is "flush", i.e. all sequence and annotation lines have the same length.
1191  
1192 =cut
1193  
1194 # Is the file flush? (i.e., are all sequences and annotations the same length?)
1195 #
1196 sub is_flush {
1197 my ($self) = @_;
1198 my $columns = $self->columns();
1199  
1200 # do stuff that has one key
1201  
1202 map {
1203 if (length($self->{seqdata}->{$_}) != $columns) {
1204 carp "Sequence $_ is not flush!";
1205 return 0;
1206 }
1207 } keys %{$self->{seqdata}};
1208  
1209 map {
1210 if (length($self->{gc}->{$_}) != $columns) {
1211 carp "#=GC annotation for feature $_ is not flush!";
1212 return 0;
1213 }
1214 } keys %{$self->{gc}};
1215  
1216 # do stuff that has two keys
1217  
1218 # map {
1219 # if (length($_) != $columns) {
1220 # carp "#=GR annotation is not flush! ($_)";
1221 # return 0;
1222 # }
1223 # } map { values %{$self->{gr}->{$_}} } keys %{$self->{gr}};
1224  
1225 return 1; # if we got this far, everything must be flush
1226 }
1227  
1228 # Determine the list maximum value.
1229 sub max {
1230 my ($x, @y) = @_;
1231 foreach my $y (@y)
1232 {
1233 $x = $y if !defined($x) || (defined($y) && $y > $x)
1234 }
1235 return $x;
1236 }
1237  
1238 # Get/set the New Hampshire tree
1239 sub NH {
1240 my ($self, $newval) = @_;
1241 if (defined $newval) {
1242 @{$self->gf_NH} = ($newval);
1243 }
1244 return join ("", @{$self->gf_NH});
1245 }
1246  
1247  
1248 =head2 add_row
1249  
1250 my $new_row_index = $stock->add_row ($seqname, $rowdata);
1251  
1252 Adds a new row to a Stockholm alignment.
1253  
1254 =cut
1255  
1256 # add_row method
1257 sub add_row {
1258 my ($self, $seqname, $rowdata) = @_;
1259 die "Attempt to add duplicate row" if exists $self->seqdata->{$seqname};
1260 push @{$self->seqname}, $seqname;
1261 $self->seqdata->{$seqname} = $rowdata;
1262 return @{$self->seqname} - 1; # new row index
1263 }
1264  
1265 1;
1266  
1267 =license
1268 GNU GENERAL PUBLIC LICENSE
1269 Version 2, June 1991
1270  
1271 Copyright (C) 1989, 1991 Free Software Foundation, Inc.
1272 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
1273 Everyone is permitted to copy and distribute verbatim copies
1274 of this license document, but changing it is not allowed.
1275  
1276 Preamble
1277  
1278 The licenses for most software are designed to take away your
1279 freedom to share and change it. By contrast, the GNU General Public
1280 License is intended to guarantee your freedom to share and change free
1281 software--to make sure the software is free for all its users. This
1282 General Public License applies to most of the Free Software
1283 Foundation's software and to any other program whose authors commit to
1284 using it. (Some other Free Software Foundation software is covered by
1285 the GNU Library General Public License instead.) You can apply it to
1286 your programs, too.
1287  
1288 When we speak of free software, we are referring to freedom, not
1289 price. Our General Public Licenses are designed to make sure that you
1290 have the freedom to distribute copies of free software (and charge for
1291 this service if you wish), that you receive source code or can get it
1292 if you want it, that you can change the software or use pieces of it
1293 in new free programs; and that you know you can do these things.
1294  
1295 To protect your rights, we need to make restrictions that forbid
1296 anyone to deny you these rights or to ask you to surrender the rights.
1297 These restrictions translate to certain responsibilities for you if you
1298 distribute copies of the software, or if you modify it.
1299  
1300 For example, if you distribute copies of such a program, whether
1301 gratis or for a fee, you must give the recipients all the rights that
1302 you have. You must make sure that they, too, receive or can get the
1303 source code. And you must show them these terms so they know their
1304 rights.
1305  
1306 We protect your rights with two steps: (1) copyright the software, and
1307 (2) offer you this license which gives you legal permission to copy,
1308 distribute and/or modify the software.
1309  
1310 Also, for each author's protection and ours, we want to make certain
1311 that everyone understands that there is no warranty for this free
1312 software. If the software is modified by someone else and passed on, we
1313 want its recipients to know that what they have is not the original, so
1314 that any problems introduced by others will not reflect on the original
1315 authors' reputations.
1316  
1317 Finally, any free program is threatened constantly by software
1318 patents. We wish to avoid the danger that redistributors of a free
1319 program will individually obtain patent licenses, in effect making the
1320 program proprietary. To prevent this, we have made it clear that any
1321 patent must be licensed for everyone's free use or not licensed at all.
1322  
1323 The precise terms and conditions for copying, distribution and
1324 modification follow.
1325
1326 GNU GENERAL PUBLIC LICENSE
1327 TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
1328  
1329 0. This License applies to any program or other work which contains
1330 a notice placed by the copyright holder saying it may be distributed
1331 under the terms of this General Public License. The "Program", below,
1332 refers to any such program or work, and a "work based on the Program"
1333 means either the Program or any derivative work under copyright law:
1334 that is to say, a work containing the Program or a portion of it,
1335 either verbatim or with modifications and/or translated into another
1336 language. (Hereinafter, translation is included without limitation in
1337 the term "modification".) Each licensee is addressed as "you".
1338  
1339 Activities other than copying, distribution and modification are not
1340 covered by this License; they are outside its scope. The act of
1341 running the Program is not restricted, and the output from the Program
1342 is covered only if its contents constitute a work based on the
1343 Program (independent of having been made by running the Program).
1344 Whether that is true depends on what the Program does.
1345  
1346 1. You may copy and distribute verbatim copies of the Program's
1347 source code as you receive it, in any medium, provided that you
1348 conspicuously and appropriately publish on each copy an appropriate
1349 copyright notice and disclaimer of warranty; keep intact all the
1350 notices that refer to this License and to the absence of any warranty;
1351 and give any other recipients of the Program a copy of this License
1352 along with the Program.
1353  
1354 You may charge a fee for the physical act of transferring a copy, and
1355 you may at your option offer warranty protection in exchange for a fee.
1356  
1357 2. You may modify your copy or copies of the Program or any portion
1358 of it, thus forming a work based on the Program, and copy and
1359 distribute such modifications or work under the terms of Section 1
1360 above, provided that you also meet all of these conditions:
1361  
1362 a) You must cause the modified files to carry prominent notices
1363 stating that you changed the files and the date of any change.
1364  
1365 b) You must cause any work that you distribute or publish, that in
1366 whole or in part contains or is derived from the Program or any
1367 part thereof, to be licensed as a whole at no charge to all third
1368 parties under the terms of this License.
1369  
1370 c) If the modified program normally reads commands interactively
1371 when run, you must cause it, when started running for such
1372 interactive use in the most ordinary way, to print or display an
1373 announcement including an appropriate copyright notice and a
1374 notice that there is no warranty (or else, saying that you provide
1375 a warranty) and that users may redistribute the program under
1376 these conditions, and telling the user how to view a copy of this
1377 License. (Exception: if the Program itself is interactive but
1378 does not normally print such an announcement, your work based on
1379 the Program is not required to print an announcement.)
1380
1381 These requirements apply to the modified work as a whole. If
1382 identifiable sections of that work are not derived from the Program,
1383 and can be reasonably considered independent and separate works in
1384 themselves, then this License, and its terms, do not apply to those
1385 sections when you distribute them as separate works. But when you
1386 distribute the same sections as part of a whole which is a work based
1387 on the Program, the distribution of the whole must be on the terms of
1388 this License, whose permissions for other licensees extend to the
1389 entire whole, and thus to each and every part regardless of who wrote it.
1390  
1391 Thus, it is not the intent of this section to claim rights or contest
1392 your rights to work written entirely by you; rather, the intent is to
1393 exercise the right to control the distribution of derivative or
1394 collective works based on the Program.
1395  
1396 In addition, mere aggregation of another work not based on the Program
1397 with the Program (or with a work based on the Program) on a volume of
1398 a storage or distribution medium does not bring the other work under
1399 the scope of this License.
1400  
1401 3. You may copy and distribute the Program (or a work based on it,
1402 under Section 2) in object code or executable form under the terms of
1403 Sections 1 and 2 above provided that you also do one of the following:
1404  
1405 a) Accompany it with the complete corresponding machine-readable
1406 source code, which must be distributed under the terms of Sections
1407 1 and 2 above on a medium customarily used for software interchange; or,
1408  
1409 b) Accompany it with a written offer, valid for at least three
1410 years, to give any third party, for a charge no more than your
1411 cost of physically performing source distribution, a complete
1412 machine-readable copy of the corresponding source code, to be
1413 distributed under the terms of Sections 1 and 2 above on a medium
1414 customarily used for software interchange; or,
1415  
1416 c) Accompany it with the information you received as to the offer
1417 to distribute corresponding source code. (This alternative is
1418 allowed only for noncommercial distribution and only if you
1419 received the program in object code or executable form with such
1420 an offer, in accord with Subsection b above.)
1421  
1422 The source code for a work means the preferred form of the work for
1423 making modifications to it. For an executable work, complete source
1424 code means all the source code for all modules it contains, plus any
1425 associated interface definition files, plus the scripts used to
1426 control compilation and installation of the executable. However, as a
1427 special exception, the source code distributed need not include
1428 anything that is normally distributed (in either source or binary
1429 form) with the major components (compiler, kernel, and so on) of the
1430 operating system on which the executable runs, unless that component
1431 itself accompanies the executable.
1432  
1433 If distribution of executable or object code is made by offering
1434 access to copy from a designated place, then offering equivalent
1435 access to copy the source code from the same place counts as
1436 distribution of the source code, even though third parties are not
1437 compelled to copy the source along with the object code.
1438
1439 4. You may not copy, modify, sublicense, or distribute the Program
1440 except as expressly provided under this License. Any attempt
1441 otherwise to copy, modify, sublicense or distribute the Program is
1442 void, and will automatically terminate your rights under this License.
1443 However, parties who have received copies, or rights, from you under
1444 this License will not have their licenses terminated so long as such
1445 parties remain in full compliance.
1446  
1447 5. You are not required to accept this License, since you have not
1448 signed it. However, nothing else grants you permission to modify or
1449 distribute the Program or its derivative works. These actions are
1450 prohibited by law if you do not accept this License. Therefore, by
1451 modifying or distributing the Program (or any work based on the
1452 Program), you indicate your acceptance of this License to do so, and
1453 all its terms and conditions for copying, distributing or modifying
1454 the Program or works based on it.
1455  
1456 6. Each time you redistribute the Program (or any work based on the
1457 Program), the recipient automatically receives a license from the
1458 original licensor to copy, distribute or modify the Program subject to
1459 these terms and conditions. You may not impose any further
1460 restrictions on the recipients' exercise of the rights granted herein.
1461 You are not responsible for enforcing compliance by third parties to
1462 this License.
1463  
1464 7. If, as a consequence of a court judgment or allegation of patent
1465 infringement or for any other reason (not limited to patent issues),
1466 conditions are imposed on you (whether by court order, agreement or
1467 otherwise) that contradict the conditions of this License, they do not
1468 excuse you from the conditions of this License. If you cannot
1469 distribute so as to satisfy simultaneously your obligations under this
1470 License and any other pertinent obligations, then as a consequence you
1471 may not distribute the Program at all. For example, if a patent
1472 license would not permit royalty-free redistribution of the Program by
1473 all those who receive copies directly or indirectly through you, then
1474 the only way you could satisfy both it and this License would be to
1475 refrain entirely from distribution of the Program.
1476  
1477 If any portion of this section is held invalid or unenforceable under
1478 any particular circumstance, the balance of the section is intended to
1479 apply and the section as a whole is intended to apply in other
1480 circumstances.
1481  
1482 It is not the purpose of this section to induce you to infringe any
1483 patents or other property right claims or to contest validity of any
1484 such claims; this section has the sole purpose of protecting the
1485 integrity of the free software distribution system, which is
1486 implemented by public license practices. Many people have made
1487 generous contributions to the wide range of software distributed
1488 through that system in reliance on consistent application of that
1489 system; it is up to the author/donor to decide if he or she is willing
1490 to distribute software through any other system and a licensee cannot
1491 impose that choice.
1492  
1493 This section is intended to make thoroughly clear what is believed to
1494 be a consequence of the rest of this License.
1495
1496 8. If the distribution and/or use of the Program is restricted in
1497 certain countries either by patents or by copyrighted interfaces, the
1498 original copyright holder who places the Program under this License
1499 may add an explicit geographical distribution limitation excluding
1500 those countries, so that distribution is permitted only in or among
1501 countries not thus excluded. In such case, this License incorporates
1502 the limitation as if written in the body of this License.
1503  
1504 9. The Free Software Foundation may publish revised and/or new versions
1505 of the General Public License from time to time. Such new versions will
1506 be similar in spirit to the present version, but may differ in detail to
1507 address new problems or concerns.
1508  
1509 Each version is given a distinguishing version number. If the Program
1510 specifies a version number of this License which applies to it and "any
1511 later version", you have the option of following the terms and conditions
1512 either of that version or of any later version published by the Free
1513 Software Foundation. If the Program does not specify a version number of
1514 this License, you may choose any version ever published by the Free Software
1515 Foundation.
1516  
1517 10. If you wish to incorporate parts of the Program into other free
1518 programs whose distribution conditions are different, write to the author
1519 to ask for permission. For software which is copyrighted by the Free
1520 Software Foundation, write to the Free Software Foundation; we sometimes
1521 make exceptions for this. Our decision will be guided by the two goals
1522 of preserving the free status of all derivatives of our free software and
1523 of promoting the sharing and reuse of software generally.
1524  
1525 NO WARRANTY
1526  
1527 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
1528 FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
1529 OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
1530 PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
1531 OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
1532 MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS
1533 TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE
1534 PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
1535 REPAIR OR CORRECTION.
1536  
1537 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
1538 WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
1539 REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
1540 INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
1541 OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
1542 TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
1543 YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
1544 PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
1545 POSSIBILITY OF SUCH DAMAGES.
1546  
1547 END OF TERMS AND CONDITIONS
1548
1549 How to Apply These Terms to Your New Programs
1550  
1551 If you develop a new program, and you want it to be of the greatest
1552 possible use to the public, the best way to achieve this is to make it
1553 free software which everyone can redistribute and change under these terms.
1554  
1555 To do so, attach the following notices to the program. It is safest
1556 to attach them to the start of each source file to most effectively
1557 convey the exclusion of warranty; and each file should have at least
1558 the "copyright" line and a pointer to where the full notice is found.
1559  
1560 <one line to give the program's name and a brief idea of what it does.>
1561 Copyright (C) <year> <name of author>
1562  
1563 This program is free software; you can redistribute it and/or modify
1564 it under the terms of the GNU General Public License as published by
1565 the Free Software Foundation; either version 2 of the License, or
1566 (at your option) any later version.
1567  
1568 This program is distributed in the hope that it will be useful,
1569 but WITHOUT ANY WARRANTY; without even the implied warranty of
1570 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
1571 GNU General Public License for more details.
1572  
1573 You should have received a copy of the GNU General Public License
1574 along with this program; if not, write to the Free Software
1575 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
1576  
1577  
1578 Also add information on how to contact you by electronic and paper mail.
1579  
1580 If the program is interactive, make it output a short notice like this
1581 when it starts in an interactive mode:
1582  
1583 Gnomovision version 69, Copyright (C) year name of author
1584 Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
1585 This is free software, and you are welcome to redistribute it
1586 under certain conditions; type `show c' for details.
1587  
1588 The hypothetical commands `show w' and `show c' should show the appropriate
1589 parts of the General Public License. Of course, the commands you use may
1590 be called something other than `show w' and `show c'; they could even be
1591 mouse-clicks or menu items--whatever suits your program.
1592  
1593 You should also get your employer (if you work as a programmer) or your
1594 school, if any, to sign a "copyright disclaimer" for the program, if
1595 necessary. Here is a sample; alter the names:
1596  
1597 Yoyodyne, Inc., hereby disclaims all copyright interest in the program
1598 `Gnomovision' (which makes passes at compilers) written by James Hacker.
1599  
1600 <signature of Ty Coon>, 1 April 1989
1601 Ty Coon, President of Vice
1602  
1603 This General Public License does not permit incorporating your program into
1604 proprietary programs. If your program is a subroutine library, you may
1605 consider it more useful to permit linking proprietary applications with the
1606 library. If this is what you want to do, use the GNU Library General
1607 Public License instead of this License.
1608  
1609 =cut
1610