FAST/Bio/UnivAln.pm untested

filter: Statementstmt 0.0% 0 / 1068 Branchbran 0.0% 0 / 290 Conditioncond 0.0% 0 / 117 MC/DCmcdc 0.0% 0 / 72 Subroutinesub 0.0% 0 / 102 Podpod 0.0% 0 / 91 totaltotal 0.0% 0 / 1740 CC 146 SCAR 36.1
CC
146
Cov
0%
_colbounds
210.0
_seqs
132.0
_rowbounds
110.0
CRAP 36.8
1  
2 # WHEN IN DOUBT, ALWAYS CHECK THE FOLLOWING URL FOR THE NEWEST VERSION:
3 # http://www.techfak.uni-bielefeld.de/bcd/Perl/Bio/welcome.html
4  
5 package FAST::Bio::UnivAln;
6 use strict;
7  
8 use vars qw ($VERSION $Revision);
9  
10 $VERSION = 1.010; # bio.perl.org Version;
11 $Revision = '$Id: UnivAln.pm,v 1.9.2.1 2001/03/02 22:47:54 heikki Exp $';
12  
13 # Disclaimer from Georg Fuellen:
14 # UnivAln is now under the CVS system. Georg Fuellen is currently
15 # not working on it, nor is he responsible for the version
16 # distributed via bio.perl.org. This version is nearly identical
17 # to Georg's latest version 1.009.
18  
19 # Revision History: see the end of the POD, under the header `REVISION HISTORY'
20 # Last important change in Version 1.008 on 13 May 1998 :
21 # readseq is now used to parse files that have been processed
22 # as ``raw'' before; now ``raw'' format is recognized using the
23 # expression /^[A-Z_0-9$_GAP_SYMBOL$_UNKN_SYMBOL\s]+$/im,
24 # i.e. the file may only have alphanumerical characters,
25 # gap and unknown-symbol, and whitespace. If commata, etc,
26 # are detected, readseq is used for parsing. Readseq itself
27 # seems to be unable to detect ``raw'' format in some cases.
28  
29 # Copyright (c) 1996, 1997, 1998 Georg Fuellen.
30 # Some pieces of the code were contributed by Steven E. Brenner,
31 # Richard Resnick and Chris Dagdigian. Thanks !!!!
32 # This module is free software; you can redistribute it and/or modify
33 # it under the same terms as Perl itself.
34  
35 =head1 NAME
36  
37 FAST::Bio::UnivAln - Bioperl alignment object
38  
39 =head1 SYNOPSIS
40  
41 This Perl module is intended to simplify the handling of biosequence alignments.
42 When in doubt, always check our Homepage for the newest version, contact emails,
43 help files, etc: http://www.techfak.uni-bielefeld.de/bcd/Perl/Bio/welcome.html
44  
45 See the L<REVISION HISTORY> for recent bugfixes and enhancements.
46  
47 =head2 Object Creation in a Nutshell
48  
49 use FAST::Bio::UnivAln;
50  
51 my $aln = FAST::Bio::UnivAln->new('t/alnfile.fasta');
52 $aln = FAST::Bio::UnivAln->new(-file=>'t/alnfile.aa',
53 -desc=>'Sample alignment',
54 -type=>'amino',
55 -ffmt=>'raw' # 1 line in file -> 1 sequence
56 );
57 $aln = FAST::Bio::UnivAln->new(-seqs=>"TCCCGCGTCAACTG\nTGGTGCTTCAACCG\nACTTG--TCAACTG");
58 $aln = FAST::Bio::UnivAln->new(-seqs=>[$sequence_strg,\@character_list,$bioSeqObject]);
59 $aln = FAST::Bio::UnivAln->new(-seqs=> ['ACCCGCGTCAACTG',
60 ['A','G','G','G','G','C','T','T','C','A','A','C','C','G'],
61 FAST::Bio::Seq->new(-seq=>'ACTTG--TCAACTG')
62 ]);
63 $aln = FAST::Bio::UnivAln->new($file,$seqs,$id,$desc,$names,$row_ids,$col_ids,
64 $row_descs,$col_descs,$numbering,$type,$ffmt,$descffmt,$inplace);
65  
66 =head2 Object Manipulation in a Nutshell
67  
68 OUTPUT
69  
70 $aln->ffmt('fasta'); # set default output format
71 print "\n aln in default format:\n", $aln->layout();
72 print "\n aln in raw format:\n", $aln->layout("raw");
73 print "\n aln in fasta format:\n", $aln->layout("fasta"), "\n";
74 print "\n aln in MSF format (via readseq):\n", $aln->layout("MSF"), "\n";
75  
76 SLICING
77  
78 my $alnSlice = $aln->seqs(1,3,1,2); # multiline string of rows 1-3, columns 1-2
79 print $alnSlice, "\n";
80 my @alnSlice = $aln->seqs([1..3], [1,4]); # multidimensional array
81 # of rows 1-3, columns 1+4
82 for $aref ( @alnSlice ) { print @$aref, "\n"; }
83 $alnSlice = $aln->seqs([3,2,3,1], [1,3..5]); # rows 3,2,3,1, cols 1,3..5
84  
85 ADVANCED SLICING
86  
87 sub has_purine {
88 my $str = join "", @{ $_[0] };
89 if ($str =~ /[AaGgRr]+/) {return 1;} else {return 0;}
90 }
91 @alnSlice = $aln->seqs([1,2,3], \&has_purine); # rows 1-3, and from these
92 # only the entries of columns for which has_purine returns 1
93 $alnSlice = $aln->seqs({ids=>'SeqA SeqB'},{ids=>'ColA ColB ColC'});
94 $aln->inplace(1); $aln->seqs({ids=>'A B'},[1..6]); $aln->inplace(0);
95 # manipulates the object itself, assigning the slice internally
96  
97 MAPPING
98  
99 @resSlice = $aln->map_r(\&has_purine, [1..3]); # 1,0,1 if row 1+3 has purine
100 @resSlice = $aln->map_c(\&has_purine, [1,4]); # 1,0 if column 1 has purine
101  
102 UTILITIES
103  
104 $resSlice = $aln->consensus(); # 75% majority needed for consensus letter
105 $resSlice = $aln->consensus(0.6, [1,3]); # 60% majority, columns 1+3 only
106 $resSlice = $aln->var_sites(); # no columns that are invariable ...
107 $indices = $aln->var_inds(); # ... and their indices
108 $resSlice = $aln->invar_sites(); # only columns that are invariable
109 $indices = $aln->invar_inds(); # (..inds() is available for most utilities)
110 $resSlice = $aln->var_sites(0.6); # no columns with >= 60% maj. of 1 letter
111 $resSlice = $aln->invar_sites(0.6); # only columns with >= 60% majority
112 $resSlice = $aln->gap_free_sites();
113 $resSlice = $aln->no_allgap_sites(); # exclude sites that only have gaps
114 $resSlice = $aln->reverse([1,3]); # reverse of rows 1+3 only
115 $resSlice = $aln->complement([1,3]); # dna/rna complement of rows 1+3 only
116 $resSlice = $aln->revcom([1,3]); # reverse complement, rows 1+3 only
117 $resSlice = $aln->remove_gaps(); # original sequences without gaps
118  
119 =head1 INSTALLATION
120  
121 This module is included with the central Bioperl distribution:
122  
123 http://bio.perl.org/Core/Latest
124 ftp://bio.perl.org/pub/DIST
125  
126 Follow the installation instructions included in the README file.
127  
128 The following are the installation instructions from the original UnivAlign
129 distribution for installing UnivAlign.pm by itself. These are not necessary if
130 installing from the central Bioperl distribution. Note that the central
131 distribution does not currently run the more extensive univaln.t2
132 test harness.
133  
134 The original installation package is available from:
135  
136 http://www.techfak.uni-bielefeld.de/bcd/Perl/Bio/#univaln
137  
138 To install, untar it and run the following commands in the module directory
139 created by tar:
140  
141 % perl Makefile.PL
142 % make
143 % make test
144 % make install
145  
146 For intensive testing, see t/univaln.t2. Run that script via
147  
148 % perl t/univaln.t2 > t/my_univaln
149  
150 and compare the output with the file t/univaln.o .
151 Expected error messages can be found in t/univaln2_expected_errors .
152  
153 If you do not have superuser installation privileges, or to install
154 in a different directory, you can do one of two things:
155  
156 1) Either copy the UnivAln.pm module into the ``Bio'' subdirectory of
157 an accessible Perl module directory (e.g. /my/perl/lib/Bio/).
158 (One possible ``accessible Perl module directory'' is your current working
159 directory; there you can create a subdirectory named ``Bio'' and place
160 UnivAln.pm in that subdirectory. Then, you can start scripts using
161 FAST::Bio::UnivAln from your current working directory.)
162  
163 2) Or, run the above commands but specify an alternate location for
164 the module by supplying a PREFIX argument to the first command:
165  
166 % perl Makefile.PL PREFIX=/my/perl/stuff
167  
168 This will place the module into '/my/perl/stuff/lib/site_lib/'. To
169 specify a directory for the module file, set the $INSTALLSITELIB
170 variable in Makefile.PL (e.g., $INSTALLSITELIB = '/my/perl/lib');
171  
172 The make install command may report problems with creating documentation
173 files (pod2man/perllocal.pod); please find the documentation in
174 UnivAln.pm.html instead.
175  
176 If you have FAST::Bio::Seq installed and want to test FAST::Bio::Seq usage by
177 FAST::Bio::UnivAln, you need enable the line
178 ``use FAST::Bio::Seq;'' at the beginning of t/univaln.t2;
179 FAST::Bio::Seq can be found via http://www.techfak.uni-bielefeld.de/bcd/Perl/Bio/ .
180 Note that the test script will also test error handling; you can expect the
181 error messages included in the file univaln.t2_expected_errors -- these are OK.
182  
183 If you wish that the module uses Don Gilbert's readseq package for sequence
184 format conversion (Version 1 Feb 1993), you can set the environment variable
185 `READSEQ_DIR'" appropriately. (Currently, only ``fasta'' and ``raw'' format
186 are supported directly by UnivAln.pm.)
187 Then, the program detects and uses `readseq' automatically, if it is in the
188 specified directory (the default directory is ``./''). Modifying the
189 environment variable `READSEQ' changes the expected name of the executable.
190 For example, $ENV{READSEQ_DIR} may be ``/vol/biotools/bin/'' and $ENV{READSEQ}
191 ``readseq2.0''. Readseq will give you support for PIR/CODATA, MSF/GCG and
192 PAUP/NEXUS formats; ASN.1 does not seem to work reliably.
193 (URLs: http://iubio.bio.indiana.edu/IUBio-Software+Data/molbio/readseq/
194 http://dot.imgen.bcm.tmc.edu:9331/seq-util/Help/readseq.html
195 http://bimas.dcrt.nih.gov/molbio/readseq/formats.html )
196  
197 Similar support for conversion from Clustal format, using Clustal as
198 a converter, is implemented, but not properly tested and documented.
199 The relevant environment variables are `CLUSTAL_DIR' and `CLUSTAL'.
200 (URL: http://www-igbmc.u-strasbg.fr/BioInfo/ClustalW/Top.html )
201  
202 (Thanks to Steve A. Chervitz for his help with bundling the module !)
203  
204 =head1 DESCRIPTION
205  
206 This module is the FAST::Bio::UnivAln alignment object which is part of
207 the Bioperl project. Currently it has some nice methods for accessing
208 an alignment after reading it in from certain formats, incl. utilities
209 like consensus and reverse complement. FAST::Bio::Seq (single sequences)
210 is only needed if you explicitly want to use these.
211  
212 (Most examples below are taken from the test script(s) that can
213 be found in directory ``t'' of the FAST::Bio::UnivAln distribution.
214 There you will also find a CGI script producing some graphics,
215 which is currently in alpha status: I suspect it needs some
216 refitting to run on a different server. If you'd like to know more about
217 multiple alignments, in theory and practice, check out the tutorial at
218 http://www.techfak.uni-bielefeld.de/bcd/Curric/MulAli/mulali.html )
219  
220 =head2 CREATION OF ALIGNMENTS
221  
222 Alignments can be constructed from files, (multi-line) strings,
223 arrays and FAST::Bio::Seq objects. Files need to be in a standard format,
224 as described below, under the header L<ALIGNMENT FORMATS>.
225  
226 my $aln = FAST::Bio::UnivAln->new('t/alnfile.fasta');
227  
228 The first parameter is regarded as a file name; if you pass
229 additional parameters, they will overwrite the parameters read in
230 from the file. You can use named parameters; take a look at
231 the documentation on the new() method in the appendix for a list of all
232 parameters, and their names. In the following example, description,
233 sequence type, and file format are provided. The file format will
234 relieve FAST::Bio::UnivAln from guessing it; however, there are no guarantees if
235 you bypass FAST::Bio::UnivAln's guessing _and_ provide an incorrect file format.
236  
237 $aln = FAST::Bio::UnivAln->new(-file=>'t/alnfile.aa',
238 -desc=>'Sample alignment',
239 -type=>'amino',
240 -ffmt=>'raw' # 1 line in file -> 1 sequence
241 );
242  
243 If no description (``-desc'') is given, a default one will be based on the
244 file name. The format type is also the default format for output; if both
245 differ, you need to specify the input format when you construct the $aln
246 object, and then use the accessor ffmt() to set the default output format.
247 FAST::Bio::UnivAln can be passed the aligned sequences directly, using the
248 named parameter ``-seqs''. It takes a multi-line string, or any mix of
249 strings, array references, and FAST::Bio::Seq objects:
250  
251 $aln = FAST::Bio::UnivAln->new(-seqs=>"TCCCGCGTCAACTG\nTGGTGCTTCAACCG\nACTTG--TCAACTG");
252 $aln = FAST::Bio::UnivAln->new(-seqs=>[$sequence_strg,\@character_list,$bioSeqObject]);
253 $aln = FAST::Bio::UnivAln->new(-seqs=> ['ACCCGCGTCAACTG',
254 ['A','G','G','G','G','C','T','T','C','A','A','C','C','G'],
255 FAST::Bio::Seq->new(-seq=>'ACTTG--TCAACTG')
256 ]);
257  
258 =head2 ACCESS TO THE DATA, AND MANIPULATION
259  
260 The layout() method returns the sequence in a specified format;
261 supported formats are listed under the header L<ALIGNMENT FORMATS>.
262  
263 $aln->ffmt('fasta'); # set default output format
264 print "\n aln in default format:\n", $aln->layout();
265 print "\n aln in raw format:\n", $aln->layout("raw");
266 print "\n aln in fasta format:\n", $aln->layout("fasta"), "\n";
267 print "\n aln in MSF format (via readseq):\n", $aln->layout("MSF"), "\n";
268  
269 =head2 Access by Specifying Boundaries
270  
271 You can calculate slices of alignments in a very flexible way;
272 interval slices like the intersection of rows 1-3 and columns 1-2 are
273 calculated using seqs(). Here, intersection means that those
274 elements are returned that are both in rows 1-3 and in columns 1-2.
275  
276 $alnSlice = $aln->seqs(1,3,1,2); # rows 1-3, columns 1-2
277 $alnSlice = $aln->seqs(); # returns the whole alignment
278  
279 Here's a diagram illustrating the general case, intersecting rows
280 $y_lo to $y_hi, and columns $x_lo to $x_hi.
281  
282 $x_lo $x_hi
283 : :
284 .. $y_lo ...:...........:.................
285 :::::::::::::
286 :: SELECTED :
287 ::: PART ::::
288 :::::::::::::
289 .. $y_hi ...:::::::::::::.................
290 : :
291 Fig.1
292  
293 Maximal intervals will be assumed if no parameters are provided.
294 Per default, the first row (sequence) has index 1 (not 0), and the first
295 column has index 1 (not 0). The latter can be modified using numbering().
296  
297 =head2 Access by Index Lists
298  
299 If you desire non-consecutive row / column elements,
300 you can specify the indices as lists, one list of desired row indices
301 and one list of desired column indices.
302  
303 $alnSlice = $aln->seqs([1..3], [1,4]); # rows 1-3, columns 1+4
304  
305 Here, letters in columns 2+3 will not be returned. Another example:
306  
307 $alnSlice = $aln->seqs([3,2,3,1], [1,3..5]); # rows 3,2,3,1, cols 1,3..5
308  
309 If you specify the empty list (``[]''), all rows/columns will be returned.
310 The following diagram shows the case where the list of row indices
311 is [$r1,$r2,$r3,$r4], and the list of column indices is [$c1,$c2,$c3].
312  
313 : : :
314 : : :
315 ............*....*..........*............. $r1
316 : : :
317 ............*....*..........*............. $r2
318 ............*....*..........*............. $r3
319 : : :
320 ............*....*..........*............. $r4
321 : : :
322 : : :
323 $c1 $c2 $c3 Fig.2
324  
325 Again, an element is selected for the slice if and only if it lies
326 in the intersection of a row and a column which are both desired
327 according to the index lists.
328  
329 =head2 Return Values
330  
331 In the examples above, a string (scalar) is returned; the standard
332 sequence accessor seqs() always returns a (multi-line)
333 string in a scalar context. In a list context, it returns an array;
334 each element of such an array is a reference to another array holding
335 the letters of one sequence, i.e. one single row.
336  
337 @alnSlice = $aln->seqs([1..3], [1,4]); # rows 1-3, columns 1+4
338 for $aref ( @alnSlice ) { print @$aref, "\n"; }
339  
340 If you use the result of an accessor or a utility function in the ``-seqs''
341 slot of new(), you may need to force that result into a scalar
342 context, because the accessor, etc, returns a list in a list context,
343 and the constructor naturally provides such a list context since it expects a
344 list of parameters.
345  
346 $aln = new FAST::Bio::UnivAln(-seqs=>scalar($aln2->seqs()));
347  
348 In the example above, the list-context return value of
349 C<$aln2-E<gt>seqs()>, i.e. the list of rows of $aln2,
350 would be fed one by one as additional parameters into the constructor,
351 if you didn't ``protect'' it by scalar(). You will be warned about the problem
352 because FAST::Bio::UnivAln detects any named parameters that it can't use.
353  
354 =head2 Access by Id
355  
356 (The following access method is currently in alpha status, it may need
357 some revision until the code is fully released.)
358  
359 Any list of desired row/column indices can be replaced by a hash of desired
360 ids, which are recognized if they are in the object's own list of row or column
361 ids. You need to pass a reference to a hash that has one key, ``ids'',
362 and one value, which is a string containing the ids seperated by `` ''(blank) :
363  
364 $alnSlice = $aln->seqs({ids=>'SeqA SeqB'},{ids=>'ColA ColB ColC'});
365  
366 Row (sequence) ids are automatically extracted when reading fasta files and
367 FAST::Bio::Seq objects. Otherwise, they are set to the default numerical index list,
368 like (1..20) if the alignment has 20 rows. Since there's currently no way
369 to extract column (site) ids (none of the supported formats has this feature),
370 these always hold the default numerical indices. However, both lists
371 may be set using the accessors row_ids() and col_ids(). Note that arbitrary
372 numbering schemes can be supported this way.
373  
374 =head2 Access by Selector Function
375  
376 Finally, you can specify a function such that seqs() returns exactly
377 those letters which lie in a row (or column) for which your function returns
378 true. E.g. has_purine() returns true if the row/column contains A, a, T, t, R,
379 or r; the following $alnSlice will contain only columns that have
380 one of these letters in them.
381  
382 sub has_purine {
383 my $str = join "", @{ $_[0] };
384 if ($str =~ /[AaGgRr]+/) {return 1;} else {return 0;}
385 }
386 $alnSlice = $aln->seqs([1..3], \&has_purine); # rows 1-3, and from these
387 # only the columns for which has_purine returns 1
388  
389 Similarly, the list of row indices, [1..3], could be replaced by a
390 function, which is then used to designate the desired rows. (It has the
391 same role that the expression EXPR has in the Perl code template
392 B<grep EXPR, LIST>, see the perlfunc manpage. FAST::Bio::UnivAln also provides
393 the equivalent to B<map EXPR, LIST>; this ``Mapping'' will be discussed soon.)
394  
395 In other words, any list of indices can be replaced by the reference to a
396 function r or c. The function then selects those elements (*) that lie in
397 a row or column which meets a criterion, returning true if the criterion
398 is met, and false otherwise.
399 If both lists of indices are replaced by functions, the picture is like this:
400  
401 : : :
402 : : :
403 ............*....*..........*............. r(row) = true
404 : : :
405 ............*....*..........*............. r(row) = true
406 ............*....*..........*............. r(row) = true
407 : : :
408 ............*....*..........*............. r(row) = true
409 : : :
410 : : :
411 c(column) c(column) c(column)
412 = true = true = true Fig.3
413  
414 The function out_fasta observes all types of selectors that seqs() does,
415 and returns the result in fasta format :
416  
417 print "\n aln in fasta format:\n", $aln->out_fasta([1..3],\&has_purine), "\n";
418  
419 =head2 Mapping functions onto Sequences and Columns
420  
421 You can map a function onto selected rows or columns, and receive the
422 results as a list:
423  
424 @resSlice = $aln->map_r(\&has_purine, [1..3]); # 1,0,1 if row 1+3 has purine
425 @resSlice = $aln->map_c(\&has_purine, [1,4]); # 1,0 if column 1 has purine
426  
427 As you may expect, maximal index lists (i.e, all rows / all columns) will be
428 assumed if no second parameter is provided. In the same way as before,
429 any one if the index lists may be replaced by a hash of ids, or a selector
430 function. In the section on L<User-defined Utility Functions>, map_r() and
431 map_c() are used to implement user-defined consensus, reverse, complement, etc.
432  
433 By the way, the following map is the same as @alnSlice = $aln-E<gt>seqs([1..3])
434 since mapping the identity function ``sub id { return @_ }''
435 to desired row/column subsets and collecting the result is just like slicing.
436  
437 @alnSlice = $aln->map_r(\&id, [ 1..3 ]);
438  
439 The number of rows/columns of an alignment can be obtained by using
440 height() and width() respectively. Ids and descriptions of rows (sequences)
441 and columns (sites) can be manipulated using row_ids(), col_ids(),
442 row_descs() and col_descs(). Be B<warned> that these accessors just return
443 a reference to the array of ids/descriptions; if you'd like to process
444 the array without changing the object's data, you need to create your
445 own copy. This decision was taken because especially the result of col_ids()
446 can be huge, and for a lot of applications a deep copy is unnecessary.
447  
448 =head2 Inplace Manipulation
449  
450 Slices can be applied to the object itself, replacing the old alignment
451 by a new one that is sliced from the old ('inplace' manipulation).
452 This is particularly useful is the alignment is large. The row (sequence)
453 and column (site) ids are taken over from the old alignment. They are
454 used as the lookup tables for L<Access by Id>, and available via row_ids()
455 and col_ids().
456  
457 The following code sets the ``inplace'' flag, and overwrites the current
458 alignment with the rows named A and B, and columns 1-6:
459  
460 $aln->inplace(1);
461 $aln->seqs({ids=>'A B'},[1..6]);
462 $aln->inplace(0);
463  
464 'inplace' manipulation is also available for most utility functions below,
465 with the notable exception of consensus(). A full list is given in the
466 description of inplace(), see the Appendix.
467  
468 =head2 UTILITY FUNCTIONS LIKE CONSENSUS, AND REVERSE COMPLEMENT
469  
470 In the following paragraph, FAST::Bio::UnivAln's direct support for utility
471 functions like consensus, (in)variable sites, gap-free sites, reverse,
472 complement, and reverse complement is explained.
473  
474 $resSlice = $aln->consensus();
475  
476 calculates the consensus of the columns, i.e. those columns for which there
477 exists a letter which has an absolute majority of 75% or more. The letter
478 '!' designates the case that no consensus is given.
479 To bypass the default threshold, write
480  
481 $resSlice = $aln->consensus(0.6);
482  
483 Note that for values smaller or equal to 0.5, two letters may have an equal
484 (relative) majority, and the tie is currently broken arbitrarily.
485 Thresholds larger than or equal to 1 imply that the site that has a
486 consensus letter must be invariant.
487  
488 $resSlice = $aln->consensus(1, [1..10]);
489  
490 Just like seqs() and map_c()/map_r(), consensus() can be passed a reference
491 to a hash of desired column ids, a function that selects the columns,
492 or the desired column indices themselves. (Here, it's columns 1 to 10.
493 Internally, map_c() is used to implement consensus().)
494  
495 The methods var_sites() and invar_sites() are using consensus(),
496 just checking whether there is a consensus letter ('invariable'),
497 or not ('variable'). Naturally, the default threshold is 1, i.e.
498 sites must be truly invariable (100% majority of 1 letter),
499 or truly variable (strictly less than 100% majority). Per default,
500 var_sites() and invar_sites() return a B<multiline string of rows> (sequences),
501 with elements from the desired columns (sites) only. They do B<not>
502 return the alignment in a column-by-column fashion ! Also, don't be confused
503 by the possibilty to specify a list of desired row indices / ids, or
504 a selector function: It just constrains the output further, without
505 influencing which columns are selected. (Internally, seqs() is used to
506 implement these functions; it is passed a row selector, and a function
507 that returns true if there is a consensus letter.)
508  
509 $resSlice = $aln->var_sites();
510 $resSlice = $aln->invar_sites();
511 $resSlice = $aln->var_sites(0.6, [1,3]); # no columns with >= 60% majority
512 # of one letter; also, print rows 1+3 only
513 $resSlice = $aln->invar_sites(0.6, [1,3]); # only columns with >= 60% maj.
514 $resSlice = $aln->no_allgap_sites([1,3]); # exclude sites that only have gaps
515 $resSlice = $aln->gap_free_sites([1,3]); # exclude sites that have >= 1 gaps
516  
517 In a similar fashion, the last example selects gap-free columns, and from
518 those only prints the elements that happen to be in rows 1+3.
519 All these utilities support L<Inplace Manipulation>:
520  
521 $aln->inplace(1);
522 $aln->var_sites(0.6, {ids=>'1 2'});
523 $aln->inplace(0);
524  
525 The utilities reverse(), complement(), and revcom() also allow
526 for L<Inplace Manipulation>, and again you can
527 specify the rows which shall form the new alignment by overwriting the
528 old, or be returned as reverse'd, complement'ed, or reverse complement'ed :
529  
530 $resSlice = $aln->reverse([1,3]);
531 $resSlice = $aln->complement([1,3]);
532 $resSlice = $aln->revcom([1,3]);
533  
534 If an inplace manipulation reverses column order, e.g. in the case of
535 reverse(), this will be reflected in the column ids available via col_ids().
536 Note that complement is defined according to the IUPAC code,
537 using the same substitutions that FAST::Bio::Seq uses, such that results
538 obtained for e.g. Amino Acid sequences are probably nonsensical.
539  
540 For all functions that have ``sites'' in their name, a corresponding
541 ``inds'' function is available that returns the relevant array of indices
542 instead of the sites themselves:
543  
544 $indices = $aln->var_inds(); # array of indices of the variable sites
545 $indices = $aln->no_allgap_inds([1,3]);
546  
547 Finally, the original sequences (without gaps) are available via remove_gaps().
548  
549 $some_original_sequences = $aln->remove_gaps([1,3]);
550  
551 In a list context, all these utility functions return an array of array
552 references, just like seqs(); the exception is consensus(), which then returns
553 a simple array of consensus letters.
554  
555 =head2 ALIGNMENT FORMATS
556  
557 The directly supported formats are fasta and raw (1 line in file -E<gt> 1 sequence,
558 where "\n" (newline) is the delimiter.) If available (see L<INSTALLATION>),
559 readseq is used to parse and write PIR/CODATA, MSF/GCG and PAUP/NEXUS
560 formats; ASN.1 does not seem to work reliably. Clustal is used to parse
561 in clustal format, if available.
562  
563 =head2 ADVANCED STUFF
564  
565 An exhaustive list of accessors and methods is given in the appendix.
566 E.g., Alignments may be copied using copy(), and compared for equality modulo
567 gaps with equal_nogaps().
568  
569 FAST::Bio::UnivAln doesn't really care whether the sequences passed in are indeed
570 from an alignment (i.e. have the same length); sequence bags (i.e. multisets
571 of sequences where the same element may occur more than once) are
572 therefore handled, too. However, you need to be careful with some
573 methods (e.g. the accessor seqs(), and width()) because their default
574 behavior may depend on inspecting the first sequence only (or the first
575 requested sequence, if this information is available -- new feature in 1.006) :
576 If you use seqs() on a sequence bag, and don't provide the number of columns
577 explicitly, you may be surprised to find out that the length of
578 the first sequence is used as the default length, and not the length
579 of the longest sequence. width() uses the same heuristic.
580  
581 You can add gap symbols to the elements of a multiset so that
582 each element takes the length of the longest sequence by calling
583 equalize_length(); you can even pad more gap characters by specifying
584 the new width yourself, as an argument to equalize_length().
585  
586 If you need to have the alignment in an intermediate form, i.e.
587 neither an array of array references, nor a single multiline string, but
588 an array of strings, just request the output as a multiline string, and split
589 it on "\n". For example, to just extract a single column, you can do
590  
591 @col = split "\n", $aln->seqs([],[$colindex]);
592  
593 Checking an alignment for characters that should not be there according
594 to the Alignment Type is currently not well-supported; see alphabet_check()
595 for a _preliminary_ way of doing manual checkup, though.
596  
597 The hash referenced by $names stores {loc,name}
598 pairs of other database locations and corresponding names where
599 the alignment is located.
600 Currently, loc and name must both be set as text, and must consist
601 entirely of a string matching the regexp /^[A-Za-z]\w*$/. That is, they must
602 be a single "word" of at least one character, without a leading underscore.
603 This restriction is not enforced, but code which deviates is subject to
604 break in future releases. Note also that the object may place any other
605 sort of items in the name string, so users of this hash should not rely on
606 accessing entries conforming the requirements above.
607  
608 =head2 Alignment Types
609  
610 The supported sequence types and corresponding alphabets are the same
611 as reported in the documentation of the FAST::Bio::Seq object: ``dna'', ``rna'',
612 and ``amino''. They are carried along without much checking, etc.
613  
614 =head2 User-defined Utility Functions
615  
616 Here are some user-defined auxiliary functions which can be applied to
617 rows and columns of an alignment; this technique can be used if
618 no appropriate built-in functions are available, or if you don't want
619 to use them.
620  
621 maj_dominance returns false if all letters in a column/row are the same.
622  
623 sub maj_dominance {
624 my $str = join "", @{ $_[0] };
625 my $first_res = @{ $_[0] }[0];
626 $str =~ s/$first_res//g;
627 if ($str) {return 0;} else {return 1;}
628 }
629  
630 consensus returns the letter that has the (relative) majority among all
631 residues, if it exceeds a certain threshold. (For simplicity, the threshold
632 is hard-wired.)
633  
634 sub consensus {
635 my @chars = @{ $_[0] };
636 my %temp = ();
637 my $threshold = 0.34; # more than 1/3
638 my @list = sort { $temp{$a}<=>$temp{$b} }
639 grep ++$temp{$_} >= $threshold * ($#chars+1), @chars;
640 # In case of a tie, it's not specified which residue is in $list[-1]
641 return (defined($list[-1]) ? $list[-1] : '!');
642 }
643  
644 reverse_ and complement implement reversing a sequence (note the
645 underscore; I'm looking for better ways to implement function passing),
646 and complementing it according to IUPAC conventions.
647  
648 sub reverse_ {
649 return [ reverse @{ $_[0] } ];
650 }
651 sub complement {
652 my $str = join "", @{ $_[0] };
653 $str =~ tr/acgtrymkswhbvdnxACGTRYMKSWHBVDNX/tgcayrkmswdvbhnxTGCAYRKMSWDVBHNX/;
654 return [ split "", $str ];
655 }
656  
657 Here, the functions above are applied:
658  
659 @resSlice = $aln->map_c(\&maj_dominance);
660 print "\nDominated sites:\n", @resSlice, "\n";
661  
662 @resSlice = $aln->map_c(\&consensus);
663 @resSlice = $aln->map_c(\&consensus, \&has_purine);
664 print "\nConsensus of the columns that have purine\n", @resSlice, "\n";
665  
666 @resSlice = $aln->map_r(\&reverse_);
667  
668 @resSlice = $aln->map_r(\&complement);
669  
670 You can also parametrize your functions by using ``closures'' (See
671 ``Programming Perl'', 2nd Ed., p.253). Basically, you set up a function
672 that has the parameter built into it, and pass around the reference to
673 that function. Here's a function that does the set-up:
674  
675 sub _setup_consensus_with_threshold {
676 my $threshold = shift;
677 return sub {
678 my @chars = @{ $_[0] };
679 my %temp = ();
680 my @list = sort { $temp{$a}<=>$temp{$b} }
681 grep ++$temp{$_} >= $threshold * ($#chars+1), @chars;
682 # In case of a tie, it's not specified which residue is in $list[-1]
683 return (defined($list[-1]) ? $list[-1] : 'N');
684 }
685 }
686  
687 Here, you create an instance of the function, incl. the parameter.
688 $consensus holds a reference to the new instance.
689  
690 my $consensus = _setup_consensus_with_threshold(0.75);
691  
692 and finally, you pass the reference to the function around, e.g. to map_c().
693  
694 @resSlice = $aln->map_c(\&$consensus);
695  
696 (You can do pretty cute tricks using closures, e.g. you can set a counter
697 to 1 in the setup function, and increment it in the ``real'' function.)
698  
699 =head1 FAST::Bio::UnivAln Guts
700  
701 Currently, the object hash has the following keys. This may be subject
702 to change; in particular the alignment data may at some point be stored
703 more efficiently in a PDL (Perl Data Language) array.
704  
705 $self->{'seqs'} : An array of array references, each of which holds
706 one sequence of the alignment
707 $self->{'id'} : String specifying the ID; shall be in \w+ (i.e. composed
708 of characters in [a-zA-Z_0-9]; only \S+ is enforced, though)
709 $self->{'desc'} : String giving a description, (later) to be formatted
710 according to $descffmt
711 $self->{'names'} : A reference to a hash which stores {loc,name} pairs of
712 other database locations and corresponding names where
713 the alignment is located.
714 $self->{'row_ids'}: A reference to an array which stores row (sequence) ids
715 $self->{'col_ids'}: Same as $self->{'row_ids'}, for the columns (sites)
716 $self->{'row_descs'}: A reference to an array which stores row (sequence)
717 descriptions
718 $self->{'col_descs'}: Same as $self->{'row_descs'}, for the columns (sites)
719 $self->{'numbering'}: The offset of the first column, an integer
720 $self->{'type'} : The type of the alignment, concatenated from the molecule
721 type (see L<Alignment Types>) and a flag that is not
722 currently used, but intended to flag sequence bags
723 $self->{'ffmt'} : alignment format, see L<ALIGNMENT FORMATS>.
724 $self->{'descffmt'}: format of $desc; right now this should be ``raw''
725 or ``fasta'' which just implies that no specific
726 format is being followed, any text is allowed
727 excluding ``\n''(newline). More support is planned.
728 $self->{'inplace'}: Flag which is set to true if accessors (and utility
729 functions) should make the modification to the object
730 itself, and just return true on success. (See inplace().)
731  
732  
733 Some more helpful comments...
734 In Perl, false is 0 or "", true is everything else.
735 Not all internal functions have a POD/HTML documentation.
736 If you read the code of this module, you need to be familiar with
737 map and grep...
738  
739 =head1 TO-DO
740  
741 Soon:
742  
743 Better handling of access, copying and slicing of C<$self-E<gt>{'row_ids'}>, etc.
744 Add pointer to a UnivAln demo page based on the draft at
745 http://www.techfak.uni-bielefeld.de/bcd/Perl/Bio/Docs/phylosnapshot.html.
746 Fix alphabet_check() (current workaround cannot be generalized),
747 Fix UnivAlnAlph{UnivAlnType{"unknown"}} (current setting is not so nice;
748 what's the easiest way to set it to all word characters ?),
749 Support more formats, especially Nexus,
750 Improved sequence alphabet support; not just providing a function
751 alphabet_check() for manual checking.
752 Then, maybe use strings to represent alphabets.
753 Test and document aln() for returning a slice as an alignment.
754  
755 Later:
756  
757 Validity marker for correctly initialized/manipulated objects.
758 Assign _unique_ IDs if none are provided.
759 Functions like has_seqs(), etc.
760 Using `undef' during initialization, and functions for regaining such a state.
761 Use Perl Data Language ?!
762  
763 =head1 DISCLAIMER
764  
765 How is this for a maximum of disclaiming warranty ? In short, I'm developing
766 this module in my spare time and it's for free, don't sue me :-)
767  
768 IN NO EVENT SHALL THE GLOBEWIDE NETWORK ACADEMY, THE VIRTUAL SCHOOL OF NATURAL
769 SCIENCES, THE AUTHOR OR THE UNIVERSITY OF BIELEFELD BE LIABLE TO ANY PARTY
770 FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING
771 OUT OF THE USE OF THIS CODE, EVEN IF THE GLOBEWIDE NETWORK ACADEMY,
772 THE VIRTUAL SCHOOL OF NATURAL SCIENCES, THE AUTHOR OR THE UNIVERSITY OF
773 BIELEFELD HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
774  
775 THE GLOBEWIDE NETWORK ACADEMY, THE VIRTUAL SCHOOL OF NATURAL SCIENCES, THE
776 AUTHOR AND THE UNIVERSITY OF BIELEFELD SPECIFICALLY DISCLAIM ANY WARRANTIES,
777 INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
778 AND FITNESS FOR A PARTICULAR PURPOSE. THE CODE PROVIDED HEREUNDER IS ON AN
779 "AS IS" BASIS, AND THERE IS NO OBLIGATION WHATSOEVER TO PROVIDE MAINTENANCEE,
780 SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
781  
782 =head1 COPYRIGHT
783  
784 This module is free software; you can redistribute it and/or modify
785 it under the same terms as Perl itself.
786  
787 Copyright (c) 1996, 1997, 1998 Georg Fuellen. All Rights Reserved.
788 Some pieces of the code were contributed by Steven E. Brenner,
789 Richard Resnick and Chris Dagdigian. Thanks !!!!
790  
791  
792 =head1 FEEDBACK
793  
794 =head2 Mailing Lists
795  
796 User feedback is an integral part of the evolution of this and other Bioperl modules.
797 Send your comments and suggestions preferably to one of the Bioperl mailing lists.
798 Your participation is much appreciated.
799  
800 bioperl-l@bioperl.org - General discussion
801 http://bio.perl.org/MailList.html - About the mailing lists
802  
803 =head2 Reporting Bugs
804  
805 Report bugs to the Bioperl bug tracking system to help us keep track the bugs and
806 their resolution. Bug reports can be submitted via email or the web:
807  
808 bioperl-bugs@bio.perl.org
809 http://bio.perl.org/bioperl-bugs/
810  
811 =head1 AUTHOR
812  
813 Georg Fuellen
814  
815 Technische Fakultaet - AG Praktische Informatik,
816 Universitaet Bielefeld,
817 D-33501 Bielefeld,
818 Germany,
819 georg.fuellen@uni-bielefeld.de
820  
821 http://www.techfak.uni-bielefeld.de/~fuellen/
822  
823 =head1 ACKNOWLEDGEMENTS
824  
825 Steven E. Brenner, Steve A. Chervitz, Michael Constant, Richard Resnick,
826 Chris Dagdigian, Lew Gramer [more to follow]
827  
828 =head1 SEE ALSO
829  
830 FAST::Bio::Seq.pm - The biosequence object
831  
832 http://bio.perl.org/Projects/modules.html - Online module documentation
833 http://bio.perl.org/Projects/SeqAlign/ - Bioperl sequence alignment project
834 http://bio.perl.org/ - Bioperl Project Homepage
835  
836 =head1 REFERENCES
837  
838 If you'd like to acknowledge use of FAST::Bio::UnivAln in your work, please cite
839  
840 Fuellen, G. (1997). FAST::Bio::UnivAln - bioperl alignment object [WWW-Document].
841 URL http://www.techfak.uni-bielefeld.de/bcd/Perl/Bio/welcome.html
842  
843 And please drop me a note :-)
844 An article for the Perl Journal is planned. The page is mirrored at
845  
846 http://merlin.mbcr.bcm.tmc.edu:8001/bcd/Perl/Bio/welcome.html
847 http://www.biotech.ist.unige.it/bcd/Perl/Bio/welcome.html
848  
849 =head1 REVISION HISTORY
850  
851 Version 1.000 on 12 Feb 1997.
852  
853 Version 1.001 on 19 Feb 1997. Fixed a bug that
854 triggered _rowbounds() and _colbounds() to use maximal index lists
855 whenever the first index in an index list was 0. New example in POD:
856  
857 $aln = new FAST::Bio::UnivAln(-seqs=>scalar($aln2->var_sites()));
858  
859 Internal: Now avoiding any global parameter passing by using closures,
860 for the utility functions.
861  
862 Version 1.002 on 21 Feb 1997. Renamed the module to UnivAln, see the
863 discussion (Feb 1997) in the vsns-bcd-perl mailing list archive.
864 Fixed hopefully all problems in out_graph(), all of them triggered by
865 bugs/features of PGPLOT.
866  
867 Version 1.003 on 25 Feb 1997. Added POD on using closures.
868 Moved out_graph() into the cgi-script t/univaln.cgi (this is alpha-code !)
869 so that ``use PGPLOT'' is no longer required.
870  
871 Version 1.004 on 13 Mar 1997. Fixed bug with reading fasta files.
872 Changed file format identifiers ``Fasta'' and ``Raw'' to ``fasta'' and ``raw''.
873 Added support for arbitrary numeration schemes by providing access by name/id
874 for rows (sequences) and columns (sites).
875 Made _arys() and _strs() accept same row/column designations like seqs().
876 Added 'inplace' manipulation for slicing and most utilities.
877 Improved speed a little. Deriving default description string from file name,
878 if available.
879  
880 Version 1.005 on 18 Jun 1997. Using simple filename (``basename'') as default
881 decription. Changed type identifiers ``Unknown'', ``Dna'', ``Rna'', ``Amino''
882 to ``unknown'', ``dna'', ``rna'', ``amino''. The old acronyms should still
883 be supported for the forseeable future.
884  
885 Version 1.006 on 15 Dec 1997. Added function no_allgap_sites(); out_fasta()
886 now accepts same row/column designations like seqs(). For advanced users:
887 the width() of sequence bags can now be controlled by supplying the index of
888 the row whose width is taken -- by default the width of the first row is used.
889  
890 Version 1.007 on 15 Mar 1998.
891 * Added functions that return indices instead of actual sequence data:
892 var_inds(), invar_inds(), gap_free_inds(), unknown_free_inds(),
893 special_free_inds() and no_allgap_inds() return the indices of
894 (in)variable, gap-free, unknown-free, gap+unknown-free and non-gap-only
895 columns; they are the counterparts of var_sites(), etc.
896 * Added remove_gaps() to return ungapped (original) sequence data
897 * Added equal_no_gaps() to check for equality ignoring gaps
898 * Added equalize_lengths() for padding a sequence bag with gaps
899 such that all rows have equal length (current procedure is slow)
900 * The default id is now ``_'' (was: ``No_Id_Given'')
901 * Internal functions _rowbounds() and _colbounds() now return indices
902 from the user's perspective, but WITHOUT substracting offset. Instead,
903 all functions subtract offset after applying _rowbounds()/_colbounds()
904  
905 Version 1.008 on 13 May 1998.
906 * Added readseq conversion support, making it possible to read and write
907 the following formats: MSF, Paup, PIR/Codata, ASN.1. (ASN.1 was not
908 parsed successfully: readseq seems to be unable to read in its own ASN.1
909 output). Technically, readseq is now used to parse files that have been
910 processed as ``raw'' before; now ``raw'' format is recognized using the
911 expression /^[A-Z_0-9$_GAP_SYMBOL$_UNKN_SYMBOL\s]+$/im, i.e. the file
912 may only have alphanumerical characters, gap and unknown-symbol, and
913 whitespace. If commata, etc, are detected, readseq is used for parsing.
914 Readseq itself seems to be unable to detect ``raw'' format in some cases,
915 causing weird results.
916 * Added Clustal support for parsing; still to be tested and documented.
917  
918 Version 1.009 on 25 May 1998.
919 * The module can now be ``built'' in the standard way (perl Makefile.PL, etc).
920  
921 =head1 APPENDIX
922  
923 Please note that functions starting with an underscore (``_'') are
924 intended for internal use only: Use them only if you know what you're
925 doing :-)
926  
927 =cut
928  
929 #"
930  
931 use Exporter;
932 use vars qw( @ISA @EXPORT @EXPORT_OK );
933 @ISA = qw(Exporter);
934 @EXPORT = qw();
935 @EXPORT_OK = qw($VERSION %UnivAlnType @UnivAlnType
936 %UnivAlnForm @UnivAlnForm %UnivAlnAlphs @UnivAlnAlphs);
937 require 5.002;
938 use Carp;
939 #if ($] < 5.005) {carp "Not tested for Perl 5.002 or 5.003";}
940 use POSIX;
941 use File::Basename;
942  
943 use vars qw($_NOFILE_FLAG $_GAP_SYMBOL $_UNKN_SYMBOL $_UNKN_SYMBOL2 $_NO_CONSENSUS_SYMBOL $_NaN $_MAX_SIZE_TAXANAME $_READSEQ $_CLUSTAL);
944 $_NOFILE_FLAG='_undef';
945 $_GAP_SYMBOL ='-';
946 $_UNKN_SYMBOL='\?'; # the backslash seems to be needed to be able to write
947 # ($str =~ /$_UNKN_SYMBOL/) ??!!
948 $_UNKN_SYMBOL2='N'; # ONLY USED IN UNDOCUMENTED FUNCTION special_free_seqs()
949 $_NO_CONSENSUS_SYMBOL='!';
950 $_NaN = POSIX::INT_MAX; #anything better ?
951 $_MAX_SIZE_TAXANAME=20;
952 $_READSEQ = "";
953 $_CLUSTAL = "";
954 $ENV{READSEQ} = "readseq";
955 # name of the readseq executable to be found in
956 # $ENV{READSEQ_DIR} or "\.". Set this to "" if readseq is
957 # installed, but shall be ignored
958 $ENV{CLUSTAL} = "clustal";
959 # name of the clustal executable to be found in
960 # $ENV{CLUSTAL_DIR} or "\.". Set this to "" if clustal is
961 # installed, but shall be ignored
962  
963 use vars qw(%UnivAlnType %TypeUnivAln @TypeUnivAln %UnivAlnForm %FormUnivAln @FormUnivAln);
964  
965 # List of recognized alignment types
966 $UnivAlnType{unknown} = 0;
967 $UnivAlnType{dna} = 1;
968 $UnivAlnType{rna} = 2;
969 $UnivAlnType{amino} = 3;
970 $UnivAlnType{otherseq} = 4; # type is explicitly NOT dna/rna/amino/etc, but
971 # nothing more is known
972 # Future support for the following 4 acronyms is doubtful:
973 $UnivAlnType{Unknown} = 0;
974 $UnivAlnType{Dna} = 1;
975 $UnivAlnType{Rna} = 2;
976 $UnivAlnType{Amino} = 3;
977 # %TypeUnivAln = reverse %UnivAlnType; # TypeUnivAln is inverse of %UnivAlnType
978 # i.e. keys and values are exchanged
979 @TypeUnivAln = ('unknown','dna','rna','amino','otherseq');
980  
981 # List of recognized file formats
982 $UnivAlnForm{unknown} = 0;
983 $UnivAlnForm{raw} = 13;
984 $UnivAlnForm{raw2} = 14;
985 $UnivAlnForm{fasta} = 7;
986 # Future support for the following 3 acronyms is doubtful:
987 $UnivAlnForm{Unknown} = 0;
988 $UnivAlnForm{Raw} = 13;
989 $UnivAlnForm{Raw2} = 14;
990 $UnivAlnForm{Fasta} = 7;
991 # %FormUnivAln = reverse %UnivAlnForm; # FormUnivAln is inverse of %UnivAlnForm
992 # i.e. keys and values are exchanged
993 @FormUnivAln = ('unknown',undef,undef,undef,undef,undef,undef,
994 'raw','raw2',undef,undef,undef,undef,'fasta');
995  
996 use vars qw(%FuncParse %FuncOut %UnivAlnAlphs);
997  
998 # %FuncParse and %FuncOut are for internal use ONLY
999 # %FuncParse is an array of (<ffmt>,<_parse_meth>), where <ffmt>
1000 # is the file format code (e.g., 0 for "unknown", 7 for 'fasta', etc.), and
1001 # <_parse_meth> is the method which parses strings in that file
1002 # format. %FuncParse{$i} is mostly set to \&_parse_bad right now,
1003 # since we don't have many file formats supported yet.
1004  
1005 my %FuncParse =
1006 ($UnivAlnForm{"unknown"} => \&_parse_unknown,
1007 $UnivAlnForm{'fasta'} => \&_parse_fasta,
1008 $UnivAlnForm{'raw'} => \&_parse_raw,
1009 );
1010 # Set all other formats to call &_parse_bad, so that currently unsupported
1011 # formats don't crash the software.
1012 grep {$FuncParse{$_} ||= \&_parse_bad} values %UnivAlnForm;
1013  
1014 # array of implemented outputting routines, built in analogy to "%FuncParse"
1015 my %FuncOut =
1016 ($UnivAlnForm{"unknown"} => \&out_fasta, #fasta is the default output !
1017 $UnivAlnForm{'fasta'} => \&out_fasta,
1018 $UnivAlnForm{'raw'} => \&out_raw,
1019 $UnivAlnForm{'raw2'} => \&out_raw2,
1020 );
1021 grep {$FuncOut{$_} ||= \&out_bad} values %UnivAlnForm;
1022  
1023 %UnivAlnAlphs =
1024 ($UnivAlnType{unknown} => [ 'A','C','G','T' ], #better alternative ???
1025 $UnivAlnType{dna} => [ 'A','C','G','T',$_GAP_SYMBOL ],
1026 $UnivAlnType{rna} => [ 'A','C','G','U',$_GAP_SYMBOL ],
1027 $UnivAlnType{amino} => [ 'A','R','N','D','C','Q','E','G','H','I','L','K','M','F',
1028 'P','S','T','W','Y','V',$_GAP_SYMBOL ],
1029 $UnivAlnType{otherseq} => [ ], #better alternative ???
1030 );
1031 #create alphabets like ``1Mg''= $UnivAlnType{dna}Mg
1032 # = [ 'A','C','G','T',$_GAP_SYMBOL,$_UNKN_SYMBOL ],
1033 #where $_GAP_SYMBOL denotes the character for missing nucleotide data.
1034 grep {$UnivAlnAlphs{$_.'Mg'} ||= [ @{ $UnivAlnAlphs{$_} },$_UNKN_SYMBOL ] } keys %UnivAlnAlphs;
1035  
1036 # the following PODs should always have a blank at the beginning (i.e.
1037 # `` Usage'', not ``Usage'' !!) so that pod2html works fine !
1038 =head2 new()
1039  
1040 Usage : $myAln = FAST::Bio::UnivAln->new($file,$seqs,$id,$desc,$names,
1041 $row_ids,$col_ids,$row_descs,$col_descs,$numbering,$type,
1042 $ffmt,$descffmt,$inplace);
1043 - or -
1044 $myAln = FAST::Bio::UnivAln->new(-file=$file,
1045 -seqs=>$seqs,
1046 -id=>$id,
1047 -desc=>$desc,
1048 -names=>$names,
1049 -row_ids=>$row_ids,
1050 -col_ids=>$col_ids,
1051 -row_descs=>$row_descs,
1052 -col_descs=>$col_descs,
1053 -numbering=>$numbering,
1054 -type=>$type,
1055 -ffmt=>$ffmt,
1056 -descffmt=>$descffmt,
1057 -inplace=>$inplace);
1058 Function : The constructor for this class, returns a new object.
1059 Returns : FAST::Bio::UnivAln object
1060 Argument : $file: file from which the alignment data can be read; all
1061 the other arguments will overwrite the data read in.
1062 (see ``Alignment Formats'')
1063 $seqs: EITHER a reference to a list of either FAST::Bio::Seq objects, or
1064 arrays of letters, or strings, or any mix of these,
1065 OR a single (multi-line) string
1066 $id: String specifying the ID.
1067 $desc: String giving a description, (later) to be formatted
1068 according to $descffmt
1069 $names:A reference to a hash which stores {loc,name} pairs of
1070 other database locations and corresponding names where
1071 the alignment is located. (See L<ADVANCED STUFF>).
1072 $row_ids :A reference to an array which stores row (sequence) ids.
1073 $row_descs:A reference to an array which stores row (sequence)
1074 descriptions
1075 $col_ids: Same as $self->{'row_ids'}, for the columns (sites)
1076 $col_descs:Same as $self->{'row_descs'}, for the columns (sites)
1077 $numbering: The offset of the first column
1078 $type: The type of the alignment, see ``Alignment Types''.
1079 $ffmt: alignment format, see ``Alignment Formats''.
1080 $descffmt: format of $desc; right now this should be ``raw''
1081 or ``fasta'' which just implies that no specific
1082 format is being followed, any text is allowed
1083 excluding ``\n''(newline).
1084 $inplace: Flag which is set to true if accessors and utility
1085 functions should make the modification to the object
1086 itself, and just return true on success. See inplace().
1087  
1088 =cut
1089  
1090 sub new {
1091 my($this) = shift;
1092 my($class,$self);
1093 $class = ref($this) || $this; # See the ``Perl Module List'' general section
1094 $self = {};
1095 bless $self, $class;
1096 $self->_initialize(@_);
1097 return $self;
1098 }
1099  
1100  
1101 =head2 _initialize()
1102  
1103 Usage : n/a (internal function)
1104 Function : Assigns initial parameters to a blessed object.
1105 Returns : 1 on success
1106 Argument : As FAST::Bio::UnivAln->new, allows for named or listed parameters.
1107 See ->new for the legal types of these values.
1108  
1109 =cut
1110  
1111 sub _initialize {
1112 my($self,@p) = @_;
1113  
1114 my $readseq = $ENV{READSEQ_DIR} || "./";
1115 $readseq .= ($readseq =~ /\/$/) ? "$ENV{READSEQ}" : "/$ENV{READSEQ}";
1116 if ((-x $readseq) && !(-d $readseq)) {
1117 $_READSEQ = $readseq;
1118 # carp "Using Don Gilbert's readseq program to convert sequence formats";
1119 } else {
1120 # carp "readseq not defined-- if installed, you can use its conversion
1121 # abilities by either providing an executable `readseq' in the script's
1122 # homedirectory, or by setting the environment variable `READSEQ_DIR'";
1123 }
1124  
1125 my $clustal = $ENV{CLUSTAL_DIR} || "./";
1126 $clustal .= ($clustal =~ /\/$/) ? "$ENV{CLUSTAL}" : "/$ENV{CLUSTAL}";
1127 if ((-x $clustal) && !(-d $clustal)) {
1128 $_CLUSTAL = $clustal;
1129 # carp "Using clustal to convert clustal sequence formats";
1130 } else {
1131 # carp "clustal not defined-- if installed, you can use its conversion
1132 # abilities by either providing an executable `clustal' in the script's
1133 # homedirectory, or by setting the environment variable `CLUSTAL_DIR'";
1134 }
1135  
1136 # Set default values that need not be inferred later
1137 $self->{'seqs'} = ( );
1138 $self->{'id'} = "_";
1139 $self->{'desc'} = "No Description Given"; # only preliminary!
1140 $self->{'names'} = { };
1141 $self->{'numbering'} = 1;
1142 $self->{'type'} = [$UnivAlnType{"unknown"},"unknown"];
1143 $self->{'ffmt'} = $UnivAlnForm{"unknown"};
1144 $self->{'descffmt'} = $UnivAlnForm{"unknown"};
1145 $self->{'inplace'} = 0;
1146  
1147 if ( ! @p ) {
1148 return undef;
1149 }
1150 # some operations will not work on ``empty'' placeholder objects
1151  
1152 my($file,$seqs,$id,$desc,$names,$row_ids,$col_ids,$row_descs,$col_descs,$numbering,$type,$ffmt,$descffmt,$inplace) =
1153 $self->_rearrange(['FILE',
1154 'SEQS',
1155 'ID',
1156 'DESC',
1157 'NAMES',
1158 'ROW_IDS',
1159 'COL_IDS',
1160 'ROW_DESCS',
1161 'COL_DESCS',
1162 'NUMBERING',
1163 'TYPE',
1164 'FFMT',
1165 'DESCFFMT',
1166 'INPLACE'],
1167 @p);
1168  
1169 $self->{'desc'} = defined($file) ? basename($file)
1170 : "No Description Given"; #cf File::Basename
1171  
1172 # Overwrite with values from file
1173 if ((defined($file)) && ($file ne $_NOFILE_FLAG) && ($file ne '')) {
1174 $self->_file_read($file,$ffmt);
1175 }
1176  
1177 # Overwrite with values from @_
1178 $self->_seqs($seqs);
1179 $self->id($id);
1180 $self->desc($desc);
1181 $self->names($names);
1182 $self->row_ids($row_ids);
1183 $self->col_ids($col_ids);
1184 $self->row_descs($row_descs);
1185 $self->col_descs($col_descs);
1186 $self->numbering($numbering);
1187 $self->_type($type);
1188 $self->ffmt($ffmt);
1189 $self->descffmt($descffmt);
1190 $self->inplace($inplace);
1191  
1192 # set default ids for the sequences (rows)
1193 $self->{'row_ids'} ||= [1..$self->height()];
1194 # set default ids for the columns
1195 $self->{'col_ids'} ||= [$self->numbering..$self->width()+$self->numbering-1]
1196 if (defined($self->width()) && $self->width() > 0);
1197 $self->{'row_descs'} ||= [];
1198 $self->{'col_descs'} ||= [];
1199  
1200 return 1;
1201 }
1202  
1203  
1204  
1205 =head2 _rearrange()
1206  
1207 Usage : n/a (internal function)
1208 Function : Rearranges named parameters to requested order.
1209 Returns : @params - an array of parameters in the requested order.
1210 Argument : $order : a reference to an array which describes the desired
1211 order of the named parameters.
1212 @param : an array of parameters, either as a list (in
1213 which case the function simply returns the list),
1214 or as an associative array (in which case the
1215 function sorts the values according to @{$order}
1216 and returns that new array.
1217  
1218 =cut
1219  
1220 sub _rearrange {
1221 # This function was taken from CGI.pm, written by Dr. Lincoln
1222 # Stein, and adapted for use in FAST::Bio::Seq by Richard Resnick.
1223 my($self,$order,@param) = @_;
1224  
1225 # If there are no parameters, we simply wish to return
1226 # an empty array which is the size of the @{$order} array.
1227 return ('') x $#{$order} unless @param;
1228  
1229 # If we've got parameters, we need to check to see whether
1230 # they are named or simply listed. If they are listed, we
1231 # can just return them.
1232 return @param unless (defined($param[0]) && $param[0]=~/^-/);
1233  
1234 # Now we've got to do some work on the named parameters.
1235 # The next few lines strip out the '-' characters which
1236 # preceed the keys, and capitalizes them.
1237 my $i;
1238 for ($i=0;$i<@param;$i+=2) {
1239 $param[$i]=~s/^\-//;
1240 $param[$i]=~tr/a-z/A-Z/;
1241 }
1242  
1243 # Now we'll convert the @params variable into an associative array.
1244 my(%param) = @param;
1245  
1246 my(@return_array);
1247  
1248 # What we intend to do is loop through the @{$order} variable,
1249 # and for each value, we use that as a key into our associative
1250 # array, pushing the value at that key onto our return array.
1251 my($key);
1252  
1253 foreach $key (@{$order}) {
1254 my($value) = $param{$key};
1255 delete $param{$key};
1256 push(@return_array,$value);
1257 }
1258  
1259 # catch user misspellings resulting in unrecognized names
1260 my(@restkeys) = keys %param;
1261 if (scalar(@restkeys) > 0) {
1262 carp("@restkeys not processed in _rearrange(), did you use a
1263 non-recognized parameter name ? ");
1264 }
1265  
1266 return (@return_array);
1267 }
1268  
1269 # helper functions used by seqs(), etc
1270  
1271 =head2 _rowbounds()
1272  
1273 Usage : $corrected_bounds = $aln->_rowbounds($uncorrected_bounds);
1274 Function : create default row index list if necessary,
1275 create row index list if specified by a hash of ids or
1276 by a selector function that acts on rows and returns true/false,
1277 check row index list for bounds errors,
1278 NO LONGER DONE IN VERSION 1.007 AND HIGHER: substract offset of 1.
1279 Returns : reference to corrected row index list
1280 Argument : reference to uncorrected row index list
1281  
1282 =cut
1283  
1284 sub _rowbounds {
1285 my($self) = shift;
1286 my $rowindices = shift;
1287 my $rowindices2;
1288  
1289 my $firstindx = 1; # currently, it's assumed the first row is row no. 1,
1290 # and other conventions aren't supported.
1291  
1292 if ( !defined($rowindices) ) {
1293 # create default row index list if necessary
1294 $rowindices2 = [$firstindx .. $self->height() - 1 + $firstindx];
1295 # cleaner??!! $rowindices2 = [];
1296 }
1297  
1298 if (ref($rowindices) eq 'ARRAY') {
1299 if (scalar(@$rowindices) == 0) {
1300 $rowindices2 = [$firstindx .. $self->height() - 1 + $firstindx];
1301 } else {
1302 $rowindices2 = [@$rowindices];
1303 }
1304 }
1305  
1306 if (ref($rowindices) eq 'HASH') {
1307 my @row_ids = split /\s/, $rowindices->{'ids'};
1308 my($ii,@rows,$row_id);
1309 $ii=0;
1310 my %all_row_ids_hash = map {($_,$ii++)} @{$self->{'row_ids'}};
1311 foreach $row_id (@row_ids) {
1312 if (exists $all_row_ids_hash{$row_id}) {
1313 push @rows, $all_row_ids_hash{$row_id} + $firstindx;
1314 delete $all_row_ids_hash{$row_id};
1315 } else {
1316 carp("Requested row named $row_id not found, or duplicate");
1317 }
1318 }
1319 $rowindices2 = \@rows;
1320 }
1321  
1322 if (ref($rowindices) eq 'CODE') {
1323 my $ctr = $firstindx - 1;
1324 $rowindices2 = [ grep {$_ != $_NaN}
1325 # filter out $_NaN-value indexes, see next comment
1326 map {($ctr++,$_) ? $ctr : $_NaN}
1327 # convert list of function values into list of indices
1328 # in canonical order, except that false values trigger an
1329 # index of $_NaN, e.g. (1,$_NaN,3,$_NaN,5) is the result
1330 # of map {($ctr++,$_) ? $ctr : $_NaN} ("A","","B",0,"C")
1331 # note that the comma operator evaluates the first
1332 # argument and throws the result away, and then
1333 # evaluates the second argument; the side effect
1334 # of the first evaluation is the increment of $ctr.
1335 $self->map_r($rowindices) ];
1336 }
1337  
1338 my($ii);
1339 for $ii (0 .. $#{$rowindices2}) {
1340 if ($rowindices2->[$ii] < $firstindx) {
1341 carp "Requested row $rowindices2->[$ii] of an alignment where $firstindx is the first row";
1342 }
1343 if (($rowindices2->[$ii] - $firstindx + 1) > scalar(@{ $self->{'seqs'} })) {
1344 carp "Requested row $rowindices2->[$ii] of an alignment with fewer rows";
1345 }
1346 }
1347 return $rowindices2;
1348 #return $self->_rownorm($rowindices2);
1349 }
1350  
1351  
1352 =head2 _colbounds()
1353  
1354 Usage : $corrected_bounds = $aln->_colbounds($uncorrected_bounds);
1355 Function : create default column index list if necessary,
1356 create column index list if specified by a hash of ids or
1357 by a selector function that acts on columns and returns true/false,
1358 check column index list for bounds errors,
1359 NOT IN 1.007 and higher: substract offset (according to numbering scheme).
1360 Returns : reference to corrected column index list
1361 Argument : reference to uncorrected column index list
1362 reference to row index list: its first row is used to
1363 provide the width of the alignment considered, which matters
1364 if the alignment is really a sequence bag
1365  
1366 =cut
1367  
1368 sub _colbounds {
1369 my($self) = shift;
1370 my $colindices = shift;
1371 my $rowindices = shift || [0];
1372 my $colindices2;
1373 my $firstindx2 = 1; # currently, it's assumed the first row is row no. 1,
1374 # and other conventions aren't supported.
1375 my $width;
1376 if (scalar(@$rowindices) != 0) {
1377 $width = $self->width($rowindices->[0]+$firstindx2);
1378 } else {
1379 return [];
1380 }
1381 my $firstindx = $self->numbering;
1382  
1383 if ( !defined($colindices) ) {
1384 # create default col index list if necessary
1385 $colindices2 = [$firstindx .. $width - 1 + $firstindx]
1386 if (defined($width) && $width > 0);
1387 #??!! $colindices2 = [];
1388 }
1389  
1390 if (ref($colindices) eq 'ARRAY') {
1391 if (scalar(@$colindices) == 0) {
1392 $colindices2 = [$firstindx .. $width - 1 + $firstindx]
1393 if (defined($width) && $width > 0);
1394 } else {
1395 $colindices2 = [@$colindices];
1396 }
1397 }
1398  
1399 if (ref($colindices) eq 'HASH') {
1400 my @col_ids = split /\s/, $colindices->{'ids'};
1401 my($ii,@cols);
1402 my %col_ids_hash = map {($_,"")} @col_ids;
1403 foreach $ii (0..$#{$self->{'col_ids'}}) {
1404 my $col_id = $self->{'col_ids'}[$ii];
1405 if (exists $col_ids_hash{$col_id}) {
1406 push @cols, $ii+$firstindx;
1407 delete $col_ids_hash{$col_id};
1408 }
1409 }
1410 my(@restkeys) = keys %col_ids_hash;
1411 if (scalar(@restkeys) > 0) {
1412 carp("Requested columns named @restkeys not found");
1413 }
1414 $colindices2 = \@cols;
1415 }
1416  
1417 if (ref($colindices) eq 'CODE') {
1418 my $ctr = $firstindx - 1;
1419 $colindices2 = [ grep {$_ != $_NaN}
1420 # see _rowbounds()
1421 map {($ctr++,$_) ? $ctr : $_NaN}
1422 $self->map_c($colindices) ];
1423 }
1424  
1425 my($ii);
1426 for $ii (0 .. ($#{$colindices2})) {
1427 if ($colindices2->[$ii] < $firstindx) {
1428 carp "Requested column $colindices2->[$ii] of an alignment starting at $firstindx";
1429 }
1430 if (($colindices2->[$ii] - $firstindx + 1) > $width) {
1431 carp "Requested column $colindices2->[$ii] is beyond the end of the alignment";
1432 }
1433 }
1434 return $colindices2;
1435 #return $self->_colnorm($colindices2);
1436 }
1437  
1438  
1439 # normalize by substracting the first row index (offset)
1440 sub _rownorm {
1441 my($self) = shift;
1442 my $rowindices = [@{$_[0]}];
1443  
1444 my $firstindx = 1; # currently, it's assumed the first row is row no. 1,
1445 # and other conventions aren't supported.
1446  
1447 return [ map {$_ -= $firstindx} @$rowindices ];
1448 }
1449  
1450 # normalize by substracting the first column index (offset)
1451 sub _colnorm {
1452 my($self) = shift;
1453 my $colindices = [@{$_[0]}];
1454  
1455 my $firstindx = $self->numbering;
1456  
1457 return [ map {$_ -= $firstindx} @$colindices ];
1458 }
1459  
1460 =head2 _fixbounds()
1461  
1462 Usage : ($corrected_rowbounds,$corrected_colbounds) =
1463 $aln->_fixbounds($uncorrected_rowbounds,$uncorrected_colbounds);
1464 OR
1465 ($corrected_rowbounds,$corrected_colbounds) =
1466 $aln->_fixbounds($firstpos1,$lastpos1,$firstpos2,$lastpos2)
1467 Function : Convert unfixed index list information into the standard internal
1468 one, allowing as input either max. 2 references or max. 4 boundary
1469 coordinates (2 coord. for row indices and 2 for column indices).
1470 Call functions to create maximal default index lists if needed,
1471 to create index lists if specified by a hash of ids or by a selector
1472 function that acts on rows/columns and returns true/false,
1473 to check index lists for bounds errors, and to substract offsets.
1474 Returns : 2 references to corrected index lists
1475 Argument : EITHER max. 2 references to uncorrected index lists,
1476 OR max. 4 boundary coordinates (integers)
1477  
1478 =cut
1479  
1480 sub _fixbounds {
1481 my($self) = shift;
1482 my($rrowsel2,$rcolsel2);
1483 my($ii);
1484  
1485 if (!(defined($_[0])) || (ref($_[0]) =~ /ARRAY|CODE|HASH/)) {
1486 my($rrowsel,$rcolsel) = @_;
1487 $rrowsel2 = $self->_rownorm($self->_rowbounds($rrowsel));
1488 $rcolsel2 = $self->_colnorm($self->_colbounds($rcolsel,$rrowsel2));
1489 } else {
1490 # unfortunately, @{[undef..undef]} is ``0'', and not ``undef'', so we
1491 # need to create valid bounds right here
1492 my($firstpos1,$lastpos1,$firstpos2,$lastpos2) = @_;
1493 my $firstindx1 = 1;
1494 my $firstindx2 = $self->numbering;
1495  
1496 if (!defined($firstpos1)) {
1497 $firstpos1 = $firstindx1;
1498 }
1499 if (!defined($lastpos1)) {
1500 $lastpos1 = $self->height() - 1 + $firstindx1;
1501 }
1502 if (!defined($firstpos2)) {
1503 $firstpos2 = $firstindx2;
1504 }
1505 if (!defined($lastpos2)) {
1506 $lastpos2 = $self->width() - 1 + $firstindx2;
1507 }
1508 $rrowsel2 = $self->_rownorm($self->_rowbounds([$firstpos1..$lastpos1]));
1509 $rcolsel2 = $self->_colnorm($self->_colbounds([$firstpos2..$lastpos2]));
1510 }
1511  
1512 return ($rrowsel2,$rcolsel2);
1513 }
1514  
1515 =head2 _select()
1516  
1517 Usage : @alnSlice = $aln->_select($rrowsel2,$rcolsel2);
1518 Function : select elements from the 2-dimensional array $self->{'seqs'}
1519 using index lists
1520 Returns : array of references to array of characters
1521 Argument : 2 index lists, one for the rows and one for the columns,
1522 Comment : Here's a diagram of dependencies of some methods relying on _select:
1523  
1524 seqs()
1525 / |
1526 |/_ \|/
1527 _arys() <-- _strs()
1528 |
1529 \|/
1530 _select()
1531  
1532 =cut
1533  
1534 #'
1535 sub _select {
1536 my $self = shift;
1537 my $array = $self->{'seqs'};
1538 my $rrowsel = shift; # right row selector; function or index array
1539 my $rcolsel = shift; # right column selector; function or index array
1540 my @slice = map [ @$_[ @$rcolsel ] ], map $array->[$_], @$rrowsel ;
1541 if ($self->{'inplace'}) {
1542 $self->{'seqs'} = [@slice];
1543 $self->{'id'} = $self->{'id'}.'_';
1544 $self->{'desc'} = "from ".$self->{'id'}.",".$self->{'desc'};
1545  
1546 $self->{'row_ids'} = [ @{ $self->{'row_ids'} }[@$rrowsel] ]
1547 unless ($#{$self->{'row_ids'}}+1 == 0);
1548 $self->{'row_descs'} = [ @{ $self->{'row_descs'} }[@$rrowsel] ]
1549 unless ($#{$self->{'row_descs'}}+1 == 0);
1550 $self->{'col_ids'} = [ @{ $self->{'col_ids'} }[@$rcolsel] ]
1551 unless ($#{$self->{'col_ids'}}+1 == 0);
1552 $self->{'col_descs'} = [ @{ $self->{'col_descs'} }[@$rcolsel] ]
1553 unless ($#{$self->{'col_descs'}}+1 == 0);
1554 return (1);
1555 } else {
1556 return @slice;
1557 }
1558 }
1559  
1560 =head2 _arys()
1561  
1562 Usage : @alnSlice = $aln->_arys([$row1,$row2,$rowx],[col1,$col2,$colx])
1563 (other usages see seqs())
1564 Function : Same as seqs(), except that an array is returned always
1565 Returns : array of references to array of characters
1566 Argument : Same as seqs()
1567  
1568 =cut
1569  
1570 # friendly frontend to _select()
1571 sub _arys {
1572 my $self = shift;
1573 my($rrowsel,$rcolsel) = $self->_fixbounds(@_);
1574  
1575 return $self->_select($rrowsel,$rcolsel);
1576 }
1577  
1578  
1579 # convert (array of references to arrays of characters) into (multiline string)
1580 sub _stringify_spaced {
1581 my ($seqref,$seqs);
1582 $seqs="";
1583  
1584 foreach $seqref (@_) {
1585 if (!($seqref && (ref($seqref) eq 'ARRAY'))) {
1586 carp "Cannot _stringify_spaced $seqref";
1587 next;
1588 }
1589 $seqs.=join(" ",@$seqref);
1590 $seqs.="\n";
1591 }
1592 return $seqs;
1593 }
1594  
1595 # convert (array of references to arrays of characters) into (multiline string)
1596 sub _stringify {
1597 my ($seqref,$seqs);
1598 $seqs="";
1599  
1600 foreach $seqref (@_) {
1601 if (!($seqref && (ref($seqref) eq 'ARRAY'))) {
1602 carp "Cannot _stringify $seqref";
1603 next;
1604 }
1605 $seqs.=join("",@$seqref);
1606 $seqs.="\n";
1607 }
1608 return $seqs;
1609 }
1610  
1611  
1612 =head2 _strs()
1613  
1614 Usage : $alnSlice = $aln->_strs([$row1,$row2,$rowx],[col1,$col2,$colx])
1615 (other usages see seqs())
1616 Function : Same as seqs(), except that a multiline string is returned always
1617 Returns : multiline string (including newline characters)
1618 Argument : Same as seqs()
1619  
1620 =cut
1621  
1622 # friendly frontend to _select(), via _arys()
1623 sub _strs {
1624 my($self) = shift;
1625 return _stringify($self->_arys(@_));
1626 }
1627  
1628  
1629 =head2 seqs()
1630  
1631 Usage : (1) $alnSlice = $aln->seqs($firstpos1,$lastpos1,$firstpos2,$lastpos2)
1632 (2) $alnSlice = $aln->seqs([$row1,$row2,$rowx],[col1,$col2,$colx])
1633 (3) $alnSlice = $aln->seqs(\&function_of_row,\&function_of_column)
1634 (4) $alnSlice = $aln->seqs({ids=>'r1 r2 r3'},{ids=>'c1 c2 c3'})
1635 [ (2),(3) and (4) can be intermixed ]
1636 Function : (1) Returns part of an alignment, from row $firstpos1 to row
1637 $lastpos1, and from column $firstpos2 to column $lastpos2
1638 Missing parameters are replaced by default (maximal possible)
1639 values, where the length of the first row of the _returned_ (*)
1640 `alignment' determines the default length in case the alignment is
1641 really a sequence bag. ((*) is a new feature in 1.006.)
1642 (2) Returns part of an alignment, i.e. those elements that lie
1643 in a row designated by an index from the first list
1644 ([$row1,$row2,$rowx]), and at the same time lie in a column
1645 designated in the second list ([col1,$col2,$colx]).
1646 The empty list (``[]'') is replaced by default (maximal possible)
1647 values, where the length of the first row of the _returned_
1648 `alignment' determines the default length in case the alignment is
1649 really a sequence bag. (Note that the first element
1650 of rows/columns has index 1 per default.)
1651 (3) Instead of an index list, a function acting on a row / column
1652 may be supplied; whenever the function returns true, the
1653 row / column is designated.
1654 (4) Instead of an index list, a hash of ids may be supplied;
1655 the ids are looked up in the alignment's list of row (sequence)
1656 ids / list of column (site) ids. The former list may be set
1657 during the construction of the alignment (e.g. it may be read
1658 from the fasta file, or the FAST::Bio::Seq objects), or it may be
1659 manipulated using row_ids(). col_ids() sets the the latter list.
1660 Returns : in a scalar context: multiline string (including newline characters)
1661 in an array context: array of references to arrays of characters
1662 Argument : (1) $firstpos1,$lastpos1,$firstpos2,$lastpos2 (all integers; note
1663 that the first element of rows/columns has index 1 per default.)
1664 (2-4) 2 selectors, one for the rows and one for the columns,
1665 each of which may be a reference to a list of indices, or a
1666 reference to a hash that has the format ``{ids=>'id1 id2 idx'}''
1667 where ids is the mandatory key, and the value is a string
1668 containing the desired ids, seperated by `` '' (space), or a
1669 function that acts on a list and returns true/false.
1670  
1671 =cut
1672  
1673 sub seqs {
1674 my $self = shift;
1675  
1676 if ($self->{'inplace'}) {
1677 return $self->_arys(@_);
1678 } else {
1679 return wantarray ? $self->_arys(@_) : $self->_strs(@_);
1680 }
1681 }
1682  
1683 sub aln {
1684 my($self) = shift;
1685 my(%copy);
1686  
1687 my($rrowsel,$rcolsel) = $self->_fixbounds(@_);
1688 $copy{'seqs'} = [$self->_select($rrowsel,$rcolsel)];
1689 $copy{'id'} = $self->{'id'}.'_';
1690 #$copy{'id'} = $self->{'id'}.'_'.join('_',split(/\s/,_stringify(\@_)));
1691 $copy{'desc'} = "sliced copy of ".$self->{'id'}.",".$self->{'desc'};
1692 foreach (keys %{$self->{'names'}}) {
1693 $copy{'names'}{$_} = $self->{'names'}{$_};
1694 }
1695 if ($#{$self->{'row_ids'}}+1 != 0) {
1696 $copy{'row_ids'} = [ @{ $self->{'row_ids'} }[@$rrowsel] ]
1697 } else {
1698 $copy{'row_ids'} = [];
1699 }
1700 if ($#{$self->{'row_descs'}}+1 != 0) {
1701 $copy{'row_descs'} = [ @{ $self->{'row_descs'} }[@$rrowsel] ]
1702 } else {
1703 $copy{'row_descs'} = [];
1704 }
1705 if ($#{$self->{'col_ids'}}+1 != 0) {
1706 $copy{'col_ids'} = [ @{ $self->{'col_ids'} }[@$rcolsel] ]
1707 } else {
1708 $copy{'col_ids'} = [];
1709 }
1710 if ($#{$self->{'col_descs'}}+1 != 0) {
1711 $copy{'col_descs'} = [ @{ $self->{'col_descs'} }[@$rcolsel] ]
1712 } else {
1713 $copy{'col_descs'} = [];
1714 }
1715  
1716 $copy{'numbering'} = $self->{'numbering'};
1717 $copy{'type'} = [ @{ $self->{'type'} } ];
1718 $copy{'ffmt'} = $self->{'ffmt'};
1719 $copy{'descffmt'}= $self->{'descffmt'};
1720 $copy{'inplace'}= $self->{'inplace'};
1721  
1722 return bless \%copy, ref($self);
1723 }
1724  
1725  
1726 =head2 _map_r()
1727  
1728 Usage : n/a (internal function)
1729 Function : apply a row function to selected rows,
1730 then return the list of all return values
1731 Returns : list of all return values
1732 Argument : $rowf: Reference to the function that is applied to selected rows,
1733 its results are put into a list and returned.
1734 $rrowsel: Reference to the selector designating the rows
1735 to which rowf is applied, as in cases (2)-(4) in seqs().
1736  
1737 =cut
1738  
1739 sub _map_r {
1740 # Developed from an expression from Michael Constant
1741 my($self) = shift;
1742 my ($rowf,$rrowsel) = @_;
1743 my $array = $self->{'seqs'};
1744 my (@results);
1745 if (defined($rrowsel)) {
1746 push @results, map {
1747 &$rowf($_)
1748 } ref($rrowsel) eq 'CODE'
1749 ? grep &$rrowsel($_), @{$array}
1750 : map $array->[$_], @$rrowsel
1751 ;
1752 }
1753 return @results;
1754 }
1755  
1756  
1757 =head2 _map_c()
1758  
1759 Usage : n/a (internal function)
1760 Function : apply a column function to selected columns,
1761 then return the list of all return values
1762 Returns : list of all return values
1763 Argument : analogous to _map_r()
1764  
1765 =cut
1766  
1767 sub _map_c {
1768 # Developed from an expression from Michael Constant
1769 my($self) = shift;
1770 my ($colf,$rcolsel) = @_;
1771 my ($colnr,@colnums, $colnum);
1772 my $array = $self->{'seqs'};
1773 my (@results);
1774 if (defined($rcolsel)) {
1775 push @results, map {
1776 $colnr=$_;
1777 &$colf([ map { ${$_}[$colnr] } @{ $self->{'seqs'} } ])
1778 # Basically, &$colf([ map { ... } ]) is calculated; [ ] creates
1779 # the reference so that call-by-reference can be done.
1780 # In the outer map, $colnr=$_ loops thru all indices in @$rcolsel
1781 # In the inner map, $_ loops thru all rows _and_ from each row
1782 # the element row[$colnr] is taken. The inner map assembles these
1783 # elements into a list which is passed to &$colf.
1784 } ref($rcolsel) eq 'CODE'
1785 ? @colnums = @colnums
1786 ? @colnums
1787 : grep {
1788 $colnum=$_,
1789 &$rcolsel( [ map ${$_}[$colnum], @{$array} ] )
1790 } 0..$#{$array->[0]}
1791 : @$rcolsel;
1792 # The outmost map processes each desired column, one at time, selected
1793 # by either the last grep, or the list of indices, $rcolsel.
1794 # For each column, if ref($rcolsel) eq 'CODE' DOES hold,
1795 # desired column numbers are those for which &$rcolsel
1796 # returns true; @colnums is used as a cache so that they are only
1797 # calculated once. If the cache is empty, all column indices
1798 # (that is, 0..$#{$array[0]}) are processed by a grep which first
1799 # notes the column index ($colnum memorizes the running variable $_)
1800 # and then calls $rcolsel with an argument that evaluates to a reference
1801 # (note the ``[..]'') to the current column. This current column is
1802 # obtained by presenting each array row to the innermost map, and
1803 # extracting just one element: ${$_}[$colnum], where $_ is the array row,
1804 # and ${$_}[$colnum] is the row's element belonging to the current column.
1805 # The single elements are then put into an array, and passed to $rcolsel
1806 }
1807 return @results;
1808 }
1809  
1810  
1811 =head2 map_r()
1812  
1813 Usage : @resSlice = $aln->map_r($rowf,$rrowsel);
1814 Function : apply a function to selected rows,
1815 then return the list of all return values
1816 Returns : list of all return values
1817 Argument : $rowf: Reference to the function that is applied to selected rows,
1818 its results are put into a list and returned.
1819 $rrowsel: Reference to the selector designating the rows
1820 to which rowf is applied, as in cases (2)-(4) in seqs().
1821  
1822 =cut
1823  
1824 sub map_r {
1825 my($self,$rowf,$rrowsel) = @_;
1826 my($rrowsel2);
1827  
1828 if (defined($rowf)) {
1829 $rrowsel2 = ref($rrowsel) eq 'CODE'
1830 ? $rrowsel
1831 : $self->_rownorm($self->_rowbounds($rrowsel));
1832 }
1833  
1834 return $self->_map_r($rowf,$rrowsel2);
1835 }
1836  
1837 =head2 map_c()
1838  
1839 Usage : @resSlice = $aln->map_c($colf,$rcolsel,$rrowsel);
1840 Function : apply a function to selected columns,
1841 then return the list of all return values
1842 Returns : list of all return values
1843 Argument : $colf: Reference to the function that is applied to selected
1844 columns, its results are put into a list and returned.
1845 $rcolsel: Reference to the selector designating the columns
1846 to which colf is applied, as in cases (2)-(4) in seqs().
1847 $rrowsel: NOT used as a selector, but as a hint for
1848 determining the width of a sequence bag if $rcolsel is undef:
1849 The last index of the first row specified by $rrowsel is
1850 taken as the maximum column index.
1851  
1852 =cut
1853  
1854 sub map_c {
1855 my($self,$colf,$rcolsel,$rrowsel) = @_;
1856 my($rcolsel2);
1857  
1858 if (defined($colf)) {
1859 $rcolsel2 = ref($rcolsel) eq 'CODE'
1860 ? $rcolsel
1861 : $self->_colnorm($self->_colbounds($rcolsel,$rrowsel));
1862 }
1863  
1864 return $self->_map_c($colf,$rcolsel2);
1865 }
1866  
1867  
1868 # Using closures; The following functions are the templates.
1869  
1870 sub _c_consensus_of_array {
1871 my $threshold = shift;
1872 return sub {
1873 my %temp = ();
1874 my @chars = @{ $_[0] };
1875 my @list = sort { $temp{$a}<=>$temp{$b} }
1876 #sort { $a cmp $b } #!!!??? Not OK, since next sort scrambles it
1877 grep ++$temp{$_} >= $threshold * ($#chars+1),
1878 @chars;
1879 # In case of a tie, it's not specified which residue is in $list[-1]
1880  
1881 return (defined($list[-1]) ? $list[-1] : $_NO_CONSENSUS_SYMBOL);
1882 };
1883 }
1884  
1885 sub _c_consensus_doesnt_exist {
1886 my $threshold = shift;
1887 my $_consensus_of_array = _c_consensus_of_array($threshold);
1888 return sub {
1889 return ((&$_consensus_of_array(@_) eq $_NO_CONSENSUS_SYMBOL)) ? 1 : 0;
1890 }
1891 }
1892  
1893 sub _c_consensus_exists {
1894 my $threshold = shift;
1895 my $_consensus_of_array = _c_consensus_of_array($threshold);
1896 return sub {
1897 return ((&$_consensus_of_array(@_) ne $_NO_CONSENSUS_SYMBOL)) ? 1 : 0;
1898 }
1899 }
1900  
1901 =head2 consensus()
1902  
1903 Usage : $cons_letters = $aln->consensus($threshold,$rcolsel);
1904 Function : return the consensus of a (subset of) the columns; the letter '!'
1905 ($_NO_CONSENSUS_SYMBOL) indicates that no consensus letter exists
1906 Returns : in a scalar context: string of consensus letters
1907 in an array context: array of consensus letters
1908 Argument : $threshold: A letter is considered consensus of a column
1909 if the fraction of the letters in the column that form a
1910 (relative) majority is >= $threshold. Ties between 2 letters with
1911 an equal relative majority are broken arbitrarily.
1912 The default value is 0.75.
1913 $rcolsel: Reference to the selector designating the columns
1914 of which the consensus is calculated, as in cases (2)-(4) in seqs().
1915  
1916 =cut
1917  
1918 sub consensus {
1919 my $self = shift;
1920 my($threshold,$rcolsel) = @_;
1921 $threshold = 0.75 unless defined($threshold);
1922 my $_consensus_of_array = _c_consensus_of_array($threshold);
1923 my @consensus = $self->map_c(\&$_consensus_of_array,$rcolsel);
1924 return wantarray ? @consensus : join("",@consensus);
1925 }
1926  
1927 =head2 var_sites()
1928  
1929 Usage : $resSlice = $aln->var_sites($threshold,$rrowsel);
1930 Function : return the variable sites of an alignment
1931 Returns : in a scalar context: multiline string (including newline characters)
1932 in an array context: array of references to arrays of characters
1933 Argument : $threshold: A column is considered variable
1934 if the fraction of the letters in the column that form a
1935 (relative) majority is NOT >= $threshold.
1936 The default $threshold is 1, i.e. only constant, INvariable columns
1937 are excluded.
1938 $rrowsel: Reference to the selector designating the rows
1939 of which in turn the letters in the variable columns are printed,
1940 as in cases (2)-(4) in seqs(). $rrowsel DOES NOT influence the
1941 calculation of the variable sites, it just constrains the output
1942 further !
1943  
1944 =cut
1945  
1946 sub var_sites {
1947 my $self = shift;
1948 my($threshold,$rrowsel) = @_;
1949 $threshold = 1 unless defined($threshold);
1950 my $_consensus_doesnt_exist = _c_consensus_doesnt_exist($threshold);
1951 return $self->seqs($rrowsel,\&$_consensus_doesnt_exist);
1952 }
1953  
1954 =head2 var_inds()
1955  
1956 Usage : $indices = $aln->var_inds($threshold,$rrowsel);
1957 Function : return the _indices_ of the variable sites of an alignment
1958 Returns : reference to array of indices
1959 Argument : $threshold: A column is considered variable
1960 if the fraction of the letters in the column that form a
1961 (relative) majority is NOT >= $threshold.
1962 The default $threshold is 1, i.e. only constant, INvariable columns
1963 are excluded.
1964 $rrowsel: the first row in $rrowsel is used for
1965 determining the width of a sequence bag. In other words,
1966 the last index of the first row specified by $rrowsel is
1967 taken as the maximum column index.
1968  
1969 =cut
1970  
1971 sub var_inds {
1972 my $self = shift;
1973 my($threshold,$rrowsel) = @_;
1974 $threshold = 1 unless defined($threshold);
1975 my $_consensus_doesnt_exist = _c_consensus_doesnt_exist($threshold);
1976 # here, rrowsel is just used as a hint to compute sequence bag width !!
1977 # The last index of the first row specified by $rrowsel is
1978 # taken as the maximum column index.
1979 $rrowsel = $self->_rowbounds($rrowsel);
1980 my $res = $self->_colbounds(\&$_consensus_doesnt_exist,$rrowsel);
1981 return $res; #causes weird errors: wantarray ? @$res : join("$,",@$res);
1982 }
1983  
1984 =head2 invar_sites()
1985  
1986 Usage : $resSlice = $aln->invar_sites($threshold,$rrowsel);
1987 Function : return the INvariable columns of an alignment
1988 Returns : in a scalar context: multiline string (including newline characters)
1989 in an array context: array of references to arrays of characters
1990 Argument : $threshold: A column is considered INvariable
1991 if the fraction of the letters in the column that form a
1992 (relative) majority is >= $threshold.
1993 The default $threshold is 1, i.e. no variability is allowed.
1994 $rrowsel: see var_sites()
1995  
1996 =cut
1997  
1998 sub invar_sites {
1999 my $self = shift;
2000 my($threshold,$rrowsel) = @_;
2001 $threshold = 1 unless defined($threshold);
2002 my $_consensus_exists = _c_consensus_exists($threshold);
2003 return $self->seqs($rrowsel,\&$_consensus_exists);
2004 }
2005  
2006 =head2 invar_inds()
2007  
2008 Comment : This is the indices-returning version of invar_sites(),
2009 cf. var_sites() and var_inds().
2010  
2011 =cut
2012  
2013 sub invar_inds {
2014 my $self = shift;
2015 my($threshold,$rrowsel) = @_;
2016 $threshold = 1 unless defined($threshold);
2017 my $_consensus_exists = _c_consensus_exists($threshold);
2018 # here, rrowsel is just used as a hint to compute sequence bag width !!
2019 # The last index of the first row specified by $rrowsel is
2020 # taken as the maximum column index.
2021 $rrowsel = $self->_rowbounds($rrowsel);
2022 my $res = $self->_colbounds(\&$_consensus_exists,$rrowsel);
2023 return $res; #causes weird errors: wantarray ? @$res : join("$,",@$res);
2024 }
2025  
2026 sub _gap_free {
2027 my $str = join "", @{ $_[0] };
2028 if ($str =~ /$_GAP_SYMBOL/) {return 0;} else {return 1;}
2029 }
2030  
2031 =head2 gap_free_sites()
2032  
2033 Usage : $resSlice = $aln->gap_free_sites($rrowsel);
2034 Function : return the gap-free columns of an alignment.
2035 Returns : in a scalar context: multiline string (including newline characters)
2036 in an array context: array of references to arrays of characters
2037 Argument : $rrowsel: see var_sites()
2038  
2039 =cut
2040  
2041 sub gap_free_sites {
2042 my $self = shift;
2043 my($rrowsel) = shift;
2044 return $self->seqs($rrowsel,\&_gap_free);
2045 }
2046 sub gap_free_cols {
2047 my $self = shift;
2048 carp "gap_free_cols deprecated -- use the equivalent gap_free_sites";
2049 $self->gap_free_sites(@_);
2050 }
2051  
2052 =head2 gap_free_inds()
2053  
2054 Comment : This is the indices-returning version of gap_free_sites(),
2055 cf. var_sites() and var_inds().
2056  
2057 =cut
2058  
2059 sub gap_free_inds {
2060 my $self = shift;
2061 my($rrowsel) = shift;
2062 # here, rrowsel is just used as a hint to compute sequence bag width !!
2063 # The last index of the first row specified by $rrowsel is
2064 # taken as the maximum column index.
2065 $rrowsel = $self->_rowbounds($rrowsel);
2066 my $res = $self->_colbounds(\&_gap_free,$rrowsel);
2067 return $res; #causes weird errors: wantarray ? @$res : join("$,",@$res);
2068 }
2069  
2070 sub _unknown_free {
2071 my $str = join "", @{ $_[0] };
2072 if (($str =~ /$_UNKN_SYMBOL/) ||
2073 ($str =~ /$_UNKN_SYMBOL2/)) {return 0;} else {return 1;}
2074 }
2075  
2076 =head2 unknown_free_sites()
2077  
2078 Usage : $resSlice = $aln->unknown_free_sites($rrowsel);
2079 Function : return the unknown-free columns of an alignment.
2080 Returns : in a scalar context: multiline string (including newline characters)
2081 in an array context: array of references to arrays of characters
2082 Argument : $rrowsel: see var_sites()
2083  
2084 =cut
2085  
2086 sub unknown_free_sites {
2087 my $self = shift;
2088 my($rrowsel) = shift;
2089 return $self->seqs($rrowsel,\&_unknown_free);
2090 }
2091  
2092 =head2 unknown_free_inds()
2093  
2094 Comment : This is the indices-returning version of unknown_free_sites(),
2095 cf. var_sites() and var_inds().
2096  
2097 =cut
2098  
2099 sub unknown_free_inds {
2100 my $self = shift;
2101 my($rrowsel) = shift;
2102 # here, rrowsel is just used as a hint to compute sequence bag width !!
2103 # The last index of the first row specified by $rrowsel is
2104 # taken as the maximum column index.
2105 $rrowsel = $self->_rowbounds($rrowsel);
2106 my $res = $self->_colbounds(\&_unknown_free,$rrowsel);
2107 return $res; #causes weird errors: wantarray ? @$res : join("$,",@$res);
2108 }
2109  
2110 sub _no_allgap {
2111 my $str = join "", @{ $_[0] };
2112 if ($str =~ /^$_GAP_SYMBOL*$/) {return 0;} else {return 1;}
2113 }
2114  
2115 =head2 no_allgap_sites()
2116  
2117 Usage : $resSlice = $aln->no_allgap_sites($rrowsel);
2118 Function : return the columns which do not have gaps only, of an alignment.
2119 Returns : in a scalar context: multiline string (including newline characters)
2120 in an array context: array of references to arrays of characters
2121 Argument : $rrowsel: see var_sites()
2122  
2123 =cut
2124  
2125 sub no_allgap_sites {
2126 my $self = shift;
2127 my($rrowsel) = shift;
2128 return $self->seqs($rrowsel,\&_no_allgap);
2129 }
2130  
2131 =head2 no_allgap_inds()
2132  
2133 Comment : This is the indices-returning version of no_allgap_sites(),
2134 cf. var_sites() and var_inds().
2135  
2136 =cut
2137  
2138 sub no_allgap_inds {
2139 my $self = shift;
2140 my($rrowsel) = shift;
2141 # here, rrowsel is just used as a hint to compute sequence bag width !!
2142 # The last index of the first row specified by $rrowsel is
2143 # taken as the maximum column index.
2144 $rrowsel = $self->_rowbounds($rrowsel);
2145 my $res = $self->_colbounds(\&_no_allgap,$rrowsel);
2146 return $res; #causes weird errors: wantarray ? @$res : join("$,",@$res);
2147 }
2148  
2149 #sub gap_free_seqs {
2150 #my $self = shift;
2151 #my($rcolsel) = shift;
2152 #return $self->seqs(\&_gap_free,$rcolsel);
2153 #}
2154 #sub gap_free_rows {
2155 #my $self = shift;
2156 #$self->gap_free_seqs(@_);
2157 #}
2158  
2159 sub _special_free {
2160 my $str = join "", @{ $_[0] };
2161 if (($str =~ /$_UNKN_SYMBOL/) ||
2162 ($str =~ /$_UNKN_SYMBOL2/) ||
2163 ($str =~ /$_GAP_SYMBOL/)) {return 0;} else {return 1;}
2164 }
2165  
2166 =head2 special_free_sites()
2167  
2168 Usage : $resSlice = $aln->special_free_sites($rrowsel);
2169 Function : return the special-free (neither gap nor unknown-symbols) columns
2170 of an alignment.
2171 Returns : in a scalar context: multiline string (including newline characters)
2172 in an array context: array of references to arrays of characters
2173 Argument : $rrowsel: see var_sites()
2174  
2175 =cut
2176  
2177 sub special_free_sites {
2178 my $self = shift;
2179 my($rrowsel) = shift;
2180 return $self->seqs($rrowsel,\&_special_free);
2181 }
2182  
2183 =head2 special_free_inds()
2184  
2185 Comment : This is the indices-returning version of special_free_sites(),
2186 cf. var_sites() and var_inds().
2187  
2188 =cut
2189  
2190 sub special_free_inds {
2191 my $self = shift;
2192 my($rrowsel) = shift;
2193 # here, rrowsel is just used as a hint to compute sequence bag width !!
2194 # The last index of the first row specified by $rrowsel is
2195 # taken as the maximum column index.
2196 $rrowsel = $self->_rowbounds($rrowsel);
2197 my $res = $self->_colbounds(\&_special_free,$rrowsel);
2198 return $res; #causes weird errors: wantarray ? @$res : join("$,",@$res);
2199 }
2200  
2201 sub _reverse {
2202 return [ reverse @{ $_[0] } ];
2203 }
2204  
2205 =head2 reverse()
2206  
2207 Usage : $resSlice = $aln->reverse($rrowsel);
2208 Function : return the rows of an alignment, in reversed form (right->left)
2209 Returns : in a scalar context: multiline string (including newline characters)
2210 in an array context: array of references to arrays of characters
2211 Argument : $rrowsel: Reference to the selector designating the rows
2212 which are returned in reversed form, as in cases (2)-(4) in seqs().
2213  
2214 =cut
2215  
2216 sub reverse {
2217 my $self = shift;
2218 my($rrowsel) = shift;
2219 my @rows = $self->map_r(\&_reverse,$rrowsel);
2220 if ($self->{'inplace'}) {
2221 my $rrowsel2 = $self->_rownorm($self->_rowbounds($rrowsel));
2222 $self->{'seqs'} = [@rows];
2223 $self->{'row_ids'} = [ @{ $self->{'row_ids'} }[@$rrowsel2] ];
2224 $self->{'row_descs'} = [ @{ $self->{'row_descs'} }[@$rrowsel2] ];
2225 $self->{'col_ids'} = [ reverse @{ $self->{'col_ids'} } ];
2226 $self->{'col_descs'} = [ reverse @{ $self->{'col_descs'} } ];
2227 return wantarray ? (1) : 1;
2228 } else {
2229 return wantarray ? @rows : _stringify(@rows);
2230 }
2231 }
2232  
2233 sub _remove_gaps {
2234 my $row = join("",@{ $_[0] });
2235 $row =~ s/$_GAP_SYMBOL//g;
2236 return [ split("", $row) ];
2237 }
2238  
2239 =head2 remove_gaps()
2240  
2241 Usage : $resSlice = $aln->remove_gaps($rrowsel);
2242 Function : return the rows of an alignment, gaps removed (i.e. the original
2243 sequences)
2244 Returns : in a scalar context: multiline string (including newline characters)
2245 in an array context: array of references to arrays of characters
2246 Argument : $rrowsel: Reference to the selector designating the rows
2247 which are returned without gaps, as in cases (2)-(4) in seqs().
2248  
2249 =cut
2250  
2251 sub remove_gaps {
2252 my $self = shift;
2253 my($rrowsel) = shift;
2254 my @rows = $self->map_r(\&_remove_gaps,$rrowsel);
2255 if ($self->{'inplace'}) {
2256 my $rrowsel2 = $self->_rownorm($self->_rowbounds($rrowsel));
2257 $self->{'seqs'} = [@rows];
2258 $self->{'row_ids'} = [ @{ $self->{'row_ids'} }[@$rrowsel2] ];
2259 $self->{'row_descs'} = [ @{ $self->{'row_descs'} }[@$rrowsel2] ];
2260 $self->{'col_ids'} = [ ];
2261 $self->{'col_descs'} = [ ];
2262 return wantarray ? (1) : 1;
2263 } else {
2264 return wantarray ? @rows : _stringify(@rows);
2265 }
2266 }
2267  
2268 #sub _extend_col_ids_if_padded {
2269 # my $chars = shift;
2270 # if (join("",@$chars) =~ /^$_GAP_SYMBOL+$/) {
2271 # return $_GAP_SYMBOL;
2272 # } else {
2273 # return shift @{$self->{'col_ids'}};
2274 # }
2275 #}
2276 #
2277 #sub extend_col_ids_if_padded {
2278 # my $self = shift;
2279 # my $col_ids = $self->map_c(\&__extend_col_ids_if_padded);
2280 # $self->{'col_ids'} = $col_ids;
2281 #}
2282  
2283 sub _complement_of_array {
2284 my $str = join "", @{ $_[0] };
2285 $str =~ tr/acgtrymkswhbvdnxACGTRYMKSWHBVDNX/tgcayrkmswdvbhnxTGCAYRKMSWDVBHNX/;
2286 return [ split "", $str ];
2287 }
2288  
2289 sub _rev_complement_of_array {
2290 my $str = join "", @{ $_[0] };
2291 $str =~ tr/acgtrymkswhbvdnxACGTRYMKSWHBVDNX/tgcayrkmswdvbhnxTGCAYRKMSWDVBHNX/;
2292 return [ CORE::reverse split "", $str ];
2293 }
2294  
2295 =head2 complement()
2296  
2297 Usage : $resSlice = $aln->complement($rrowsel);
2298 Function : return the rows of an alignment, in complemented form
2299 In the case of dna/rna, the complement is given according to the
2300 IUPAC code; in other cases the result is currently calculated in the
2301 same way and probably meaningless
2302 Returns : in a scalar context: multiline string (including newline characters)
2303 in an array context: array of references to arrays of characters
2304 Argument : $rrowsel: see reverse()
2305  
2306 =cut
2307  
2308 sub complement {
2309 my $self = shift;
2310 my($rrowsel) = shift;
2311 my $type = $self->type();
2312 if (defined($type) && ($type !~ /rna|dna|unknown|Rna|Dna|Unknown/i)) {
2313 carp ("Warning: complement'ing an alignment of type $type;
2314 maybe that's not a good thing to do ?");
2315 }
2316 my @rows = $self->map_r(\&_complement_of_array,$rrowsel);
2317 if ($self->{'inplace'}) {
2318 my $rrowsel2 = $self->_rownorm($self->_rowbounds($rrowsel));
2319 $self->{'seqs'} = [@rows];
2320 $self->{'row_ids'} = [ @{ $self->{'row_ids'} }[@$rrowsel2] ];
2321 $self->{'row_descs'} = [ @{ $self->{'row_descs'} }[@$rrowsel2] ];
2322 return wantarray ? (1) : 1;
2323 } else {
2324 return wantarray ? @rows : _stringify(@rows);
2325 }
2326 }
2327  
2328 =head2 revcom()
2329  
2330 Usage : $aln->revcom($rrowsel);
2331 Function : return the rows of an alignment, in reversed complement form
2332 In the case of dna/rna, the complement is given according to the
2333 IUPAC code; otherwise the result is currently calculated in the
2334 same way and probably nonsensical.
2335 Returns : in a scalar context: multiline string (including newline characters)
2336 in an array context: array of references to arrays of characters
2337 Argument : $rrowsel: see reverse()
2338  
2339 =cut
2340  
2341 sub revcom {
2342 my $self = shift;
2343 my($rrowsel) = shift;
2344 my $type = $self->type();
2345 if (defined($type) && ($type !~ /rna|dna|unknown|Rna|Dna|Unknown/i)) {
2346 carp ("Warning: complement'ing an alignment of type $type;
2347 maybe that's not a good thing to do ?");
2348 }
2349 my @rows = $self->map_r(\&_rev_complement_of_array,$rrowsel);
2350 if ($self->{'inplace'}) {
2351 my $rrowsel2 = $self->_rownorm($self->_rowbounds($rrowsel));
2352 $self->{'seqs'} = [@rows];
2353 $self->{'row_ids'} = [ @{ $self->{'row_ids'} }[@$rrowsel2] ];
2354 $self->{'row_descs'} = [ @{ $self->{'row_descs'} }[@$rrowsel2] ];
2355 $self->{'col_ids'} = [ CORE::reverse @{ $self->{'col_ids'} } ];
2356 $self->{'col_descs'} = [ CORE::reverse @{ $self->{'col_descs'} } ];
2357 return wantarray ? (1) : 1;
2358 } else {
2359 return wantarray ? @rows : _stringify(@rows);
2360 }
2361 }
2362  
2363 =head2 equal_nogaps()
2364  
2365 Usage : $aln->equal_nogaps($other_aln);
2366 Function : checks whether two alignments have the same original sequences
2367 (i.e. gaps are removed and the rows are compared for equality)
2368 Returns : 1 if alignments are equal modulo gaps, 0 otherwise
2369 Argument : $other_aln: the other alignment
2370  
2371 =cut
2372  
2373 sub equal_nogaps {
2374 my $self = shift;
2375 my($other_aln) = shift;
2376 if ($self->height() != $other_aln->height()) {
2377 return 0;
2378 }
2379 my $row_index;
2380 foreach $row_index (1..$self->height()) {
2381 my $row_gap_free = $self->seqs([$row_index]);
2382 $row_gap_free =~ s/$_GAP_SYMBOL//g;
2383 my $other_row_gap_free = $other_aln->seqs([$row_index]);
2384 $other_row_gap_free =~ s/$_GAP_SYMBOL//g;
2385 if ($row_gap_free ne $other_row_gap_free) {
2386 print STDERR "Not equal: in row $row_index, $row_gap_free and $other_row_gap_free";
2387 return 0;
2388 }
2389 }
2390 return 1;
2391 }
2392  
2393 =head2 equalize_lengths()
2394  
2395 Usage : $aln->equalize_lengths($width);
2396 Function : modifies the alignment / sequence bag such that all rows
2397 have length $width; in the case of sequence bags, this
2398 is a primitive way to obtain a true alignment with
2399 rows of equal length
2400 * The current procedure is straightforward but slow *
2401 Returns : 1 if alignments are equal modulo gaps, 0 otherwise
2402 Argument : $width: the length until which sequences should be padded;
2403 per default the length of the longest row is taken
2404  
2405 =cut
2406  
2407 sub equalize_lengths {
2408 my $self = shift;
2409 my $width = shift;
2410 my $row;
2411 if (!defined($width)) {
2412 $width = 0;
2413 foreach $row (@{$self->{'seqs'}}) {
2414 $width = ($#$row+1) > $width ? ($#$row+1) : $width;
2415 }
2416 }
2417 foreach $row (@{$self->{'seqs'}}) {
2418 map {$row->[$_] ||= "$_GAP_SYMBOL"} (0..$width-1); #slow!
2419 }
2420 }
2421  
2422 # Accessor functions
2423  
2424 =head2 _seqs()
2425  
2426 Usage : @oldSeqs = $aln->_seqs(@sequences,$start)
2427 @oldSeqs = $aln->_seqs($sequences,$start)
2428 Function : to APPEND/OVERWRITE sequences to an alignment
2429 Returns : old list of sequences, i.e. ($self->{'seqs'})
2430 Argument : 1. EITHER a reference to a list of either FAST::Bio::Seq objects, or
2431 arrays of letters, or strings, or any mix of these,
2432 OR a single (multi-line) string
2433 2. $rrowsel: Reference to the selector designating the rows
2434 which shall be appended/overwritten (feature in alpha status)
2435  
2436 =cut
2437  
2438 sub _seqs {
2439 my $self = shift;
2440 my $nseqs = shift;
2441 my $rrowsel = shift;
2442 my $rrowsel2 = [];
2443 if (defined($rrowsel)) {
2444 $rrowsel2 = $self->_rownorm($self->_rowbounds($rrowsel));
2445 }
2446  
2447 my $oseqs = $self->{'seqs'};
2448 if (defined $nseqs) {
2449 my ($seq, @seq, $counter);
2450 $counter = 0; my $index;
2451 if (ref($nseqs) eq 'ARRAY') {
2452 foreach $seq (@$nseqs) {
2453 $index = defined($rrowsel2->[$counter]) ?
2454 $rrowsel2->[$counter] : $counter;
2455 if (ref($seq) eq 'ARRAY') {
2456 ##print "\nWriting array[$rrowsel2->[$counter] || $counter] ", @$seq;
2457 $self->{'seqs'}[$index] = $seq;
2458 } elsif (ref($seq) eq "") { #a string???
2459 ##print "\nWriting string[$rrowsel2->[$counter] || $counter] $seq";
2460 @seq = split("", $seq);
2461 $self->{'seqs'}[$index] = [ @seq ];
2462 } elsif (ref($seq) =~ /Seq/) {
2463 # Currently, there doesn't seem to be another way to find out
2464 # whether we've been passed a usable object.
2465 # However, with Perl 5.004, we'll use can() provided
2466 # by class ``UNIVERSAL'' to test whether
2467 # the object passed to us is usable, i.e. has methods ary(), etc
2468 ##print "\nWriting sequence[$rrowsel2->[$counter] || $counter] ",$seq->ary;
2469 $self->{'seqs'}[$index] = [ split(//, $seq->seq()) ];
2470 $self->{'row_ids'}[$index] = $seq->id();
2471 $self->{'row_descs'}[$index] = $seq->desc();
2472 } else {
2473 carp("sequence nr. $index could not be extracted from input parameter ``-seqs''");
2474 }
2475 $counter++;
2476 }
2477 } elsif (ref($nseqs) eq "") { #a string???
2478 foreach $seq (split("\n", $nseqs)) {
2479 $index = defined($rrowsel2->[$counter]) ?
2480 $rrowsel2->[$counter] : $counter;
2481 @seq = split("", $seq);
2482 $self->{'seqs'}[$index] = [ @seq ];
2483 $counter++;
2484 }
2485 } else {
2486 $index = defined($rrowsel2->[$counter]) ?
2487 $rrowsel2->[$counter] : $counter;
2488 $self->{'seqs'}[$index] = [ ];
2489 $counter++;
2490 carp("alignment sequences could not be extracted from input parameter ``-seqs''");
2491 }
2492 }
2493 return $oseqs;
2494 }
2495  
2496  
2497  
2498  
2499 =head2 id()
2500  
2501 Usage : $aln_id = $aln->id();
2502 $aln->id($id_string);
2503 Function : Accessor, also sets field if an ID is passed in.
2504 Returns : (original) ID value
2505 Argument : sequence string with no whitespace
2506  
2507 =cut
2508  
2509  
2510 sub id {
2511 my($self) = shift;
2512 my($nid) = @_;
2513  
2514 my $oid = $self->{'id'};
2515 if (defined($nid)) {
2516 $self->{'id'} = $nid;
2517 $self->{'id'} = undef if $nid eq "-undef";
2518 if ($nid =~ /\s/) {
2519 carp("identifier $nid has illegal whitespace");
2520 }
2521 }
2522  
2523 return $oid;
2524 }
2525  
2526  
2527 =head2 desc()
2528  
2529 Usage : $aln_desc = $aln->desc();
2530 $aln->desc($desc_string);
2531 Function : Accessor, also sets field if a description string is passed in.
2532 Returns : (original) description value
2533 Argument : sequence string
2534  
2535 =cut
2536  
2537  
2538 sub desc {
2539 my($self) = shift;
2540 my($ndesc) = @_;
2541  
2542 my $odesc = $self->{'desc'};
2543 $self->{'desc'} = $ndesc if defined($ndesc);
2544  
2545 return $odesc;
2546 }
2547  
2548  
2549  
2550 =head2 names()
2551  
2552 Usage : %names = $aln->names;
2553 $aln->names($hash_ref)
2554 Function : Accessor, also sets field if names hash is passed in.
2555 The names hash is 'human-readable' data; each key is a
2556 location (whether it be URL, database, database query, etc.)
2557 and each value is the id at that location.
2558 Returns : (original) names hash value
2559 Argument : reference to a hash
2560  
2561 =cut
2562  
2563 sub names {
2564 my($self) = shift;
2565 my($nnames) = @_;
2566  
2567 my $onames = $self->{'names'};
2568 if (defined $nnames) {
2569 if (ref($nnames) ne 'HASH') {
2570 carp "Not a reference to a hash";
2571 } else {
2572 $self->{'names'} = {};
2573 foreach (keys %$nnames) {
2574 $self->{'names'}{$_} = $nnames->{$_};
2575 }
2576 }
2577 }
2578  
2579 return $onames;
2580 }
2581  
2582  
2583 =head2 row_ids()
2584  
2585 Usage : $row_ids = $aln->row_ids();
2586 $aln->row_ids($row_ids);
2587 Function : Accessor, also sets field.
2588 Returns : A reference to the (original) array of row (sequence) ids
2589 Argument : A reference to an array of row (sequence) ids
2590  
2591 =cut
2592  
2593 sub row_ids {
2594 my($self) = shift;
2595 my($nrow_ids) = @_;
2596  
2597 my $orow_ids = $self->{'row_ids'};
2598 $self->{'row_ids'} = $nrow_ids if defined($nrow_ids);
2599  
2600 return $orow_ids;
2601 }
2602  
2603 =head2 col_ids()
2604  
2605 Usage : $col_ids = $aln->col_ids();
2606 $aln->col_ids($col_ids);
2607 Function : Accessor, also sets field.
2608 Returns : A reference to the (original) array of column (site) ids
2609 Argument : A reference to an array of column (site) ids
2610  
2611 =cut
2612  
2613 sub col_ids {
2614 my($self) = shift;
2615 my($ncol_ids) = @_;
2616  
2617 my $ocol_ids = $self->{'col_ids'};
2618 $self->{'col_ids'} = $ncol_ids if defined($ncol_ids);
2619  
2620 return $ocol_ids;
2621 }
2622  
2623 =head2 row_descs()
2624  
2625 Usage : $row_descs = $aln->row_descs();
2626 $aln->row_descs($row_descs);
2627 Function : Accessor, also sets field.
2628 Returns : A reference to the (original) array of row (sequence) descriptions
2629 Argument : A reference to an array of row (sequence) descriptions
2630  
2631 =cut
2632  
2633 sub row_descs {
2634 my($self) = shift;
2635 my($nrow_descs) = @_;
2636  
2637 my $orow_descs = $self->{'row_descs'};
2638 $self->{'row_descs'} = $nrow_descs if defined($nrow_descs);
2639  
2640 return $orow_descs;
2641 }
2642  
2643 =head2 col_descs()
2644  
2645 Usage : $col_descs = $aln->col_descs();
2646 $aln->col_descs($col_descs);
2647 Function : Accessor, also sets field.
2648 Returns : A reference to the (original) array of column (site) descriptions
2649 Argument : A reference to an array of column (site) descriptions
2650  
2651 =cut
2652  
2653 sub col_descs {
2654 my($self) = shift;
2655 my($ncol_descs) = @_;
2656  
2657 my $ocol_descs = $self->{'col_descs'};
2658 $self->{'col_descs'} = $ncol_descs if defined($ncol_descs);
2659  
2660 return $ocol_descs;
2661 }
2662  
2663 =head2 numbering()
2664  
2665 Usage : $num_start = $aln->numbering;
2666 $aln->numbering($value);
2667 Function : Accessor, also sets field if a new numbering scheme is passed in.
2668 Returns : (original) numbering value
2669 Argument : number that is used as the offset of the first column
2670  
2671 =cut
2672  
2673 sub numbering {
2674 my($self) = shift;
2675 my($nnumbering) = @_;
2676  
2677 my $onumbering = $self->{'numbering'};
2678 $self->{'numbering'} = $nnumbering if defined($nnumbering);
2679  
2680 # $self->{'col_ids'} ||=
2681 # [$self->numbering()..$self->width()+$self->numbering()-1];
2682  
2683 return $onumbering;
2684 }
2685  
2686  
2687 sub _type {
2688 my($self) = shift;
2689 my($ntype) = @_;
2690  
2691 my $otype = $self->{'type'};
2692 if (defined($ntype)) {
2693 my($monomer,$samelength);
2694 $samelength = "unknown";
2695 if (defined($UnivAlnType{$ntype})) {
2696 $monomer = $UnivAlnType{$ntype} ;
2697 } else {
2698 $monomer = $UnivAlnType{"unknown"};
2699 carp("Unrecognized alignment type: $ntype");
2700 }
2701 $self->{'type'} = [$monomer,$samelength];
2702 }
2703  
2704 return @{$otype};
2705 }
2706  
2707  
2708 sub samelength {
2709 my($self) = shift;
2710 my($ntype) = @_;
2711  
2712 my $otype = $self->{'type'}[1];
2713 $self->{'type'}[1] = $ntype if defined($ntype);
2714  
2715 return $otype;
2716 }
2717  
2718  
2719 =head2 type()
2720  
2721 Usage : $aln_type = $aln->type;
2722 $aln->type($value); # May be dangerous !
2723 Function : Accessor, also sets field if a new type is passed in.
2724 The latter is considered dangerous !
2725 Returns : (original) type value
2726 Argument : new type, see the list %UnivAlnTypes in the code
2727 (currently, ``dna'', ``rna'', ``amino'')
2728  
2729 =cut
2730  
2731 sub type {
2732 my($self) = shift;
2733 my($ntype) = @_;
2734  
2735 my $otype = $self->{'type'}[0];
2736 $self->{'type'}[0] = $ntype if defined($ntype);
2737  
2738 return (defined($TypeUnivAln[$otype])) ? $TypeUnivAln[$otype] : 'undef';
2739 }
2740  
2741 =head2 ffmt()
2742  
2743 Usage : $ffmt = $aln->ffmt;
2744 $aln->ffmt($value);
2745 Function : Accessor, also sets field if a new format acronym is passed in.
2746 This can be done before reading from a file, so that
2747 the presumably correct parsing routine is called, or
2748 the value can be set before writing the object using
2749 layout(), so that layout uses a specified default format.
2750 Returns : (original) format acronym
2751 Argument : string describing the format, see ``Alignment Formats''
2752  
2753 =cut
2754  
2755  
2756 sub ffmt {
2757 my($self) = shift;
2758 my($nffmt) = @_;
2759  
2760 my $offmt = $self->{'ffmt'};
2761 if (defined($nffmt)) {
2762 if (defined($UnivAlnForm{$nffmt})) {
2763 $self->{'ffmt'} = $UnivAlnForm{$nffmt};
2764 }
2765 else {
2766 carp("Can't set to unrecognized sequence format: $nffmt");
2767 }
2768 }
2769  
2770 return $FormUnivAln[$offmt]; # return acronym, not number code
2771 }
2772  
2773  
2774 sub descffmt {
2775 my($self) = shift;
2776 my($ndescffmt) = @_;
2777  
2778 my $odescffmt = $self->{'descffmt'};
2779 if (defined($ndescffmt)) {
2780 if (defined($UnivAlnForm{$ndescffmt})) {
2781 $self->{'descffmt'} = $UnivAlnForm{$ndescffmt};
2782 }
2783 else {
2784 carp("Unrecognized description format: $ndescffmt");
2785 }
2786 }
2787  
2788 return $FormUnivAln[$odescffmt]; # return acronym, not number code
2789 }
2790  
2791  
2792 =head2 inplace()
2793  
2794 Usage : $inplace = $aln->inplace();
2795 $aln->inplace($value);
2796 Function : Accessor, also sets field if a value is passed in.
2797 'inplace' is a flag which is set to true if accessors and
2798 functions should make the modification to the object itself,
2799 and just return true on success. Currently, inplace manipulation
2800 is supported for seqs(), _arys(), _strs(), remove_gaps(),
2801 var_sites(), invar_sites(), gap_free_sites(), no_allgap_sites(),
2802 reverse(), complement(), and revcom() (reverse complement).
2803 Returns : (original) inplace value
2804 Argument : currently 0 or 1
2805  
2806 =cut
2807  
2808 sub inplace {
2809 my($self) = shift;
2810 my($ninplace) = @_;
2811  
2812 my $oinplace = $self->{'inplace'};
2813 $self->{'inplace'} = $ninplace if defined($ninplace);
2814  
2815 return $oinplace;
2816 }
2817  
2818  
2819 =head2 width()
2820  
2821 Usage : $width = $aln->width();
2822 Function : number of columns (of the first row per default)
2823 Returns : number of columns (of the first row per default)
2824 Argument : row
2825  
2826 =cut
2827  
2828 sub width {
2829 my($self) = shift;
2830 my($row) = shift || 1;
2831 my $firstindx = 1; # currently, it's assumed the first row is row no. 1,
2832 # and other conventions aren't supported.
2833 $row -= $firstindx;
2834 if (defined($self->{'seqs'}[$row])) {
2835 return scalar( @{ $self->{'seqs'}[$row] });
2836 }
2837 }
2838  
2839  
2840 =head2 height()
2841  
2842 Usage : $height = $aln->height();
2843 Function : number of rows (sequences)
2844 Returns : number of rows (sequences)
2845 Argument : ./.
2846  
2847 =cut
2848  
2849 sub height {
2850 my($self) = shift;
2851 if (defined($self->{'seqs'}[0])) { # ``[0]'' on purpose, I hope this is ok.
2852 return scalar( @{ $self->{'seqs'} });
2853 }
2854 }
2855  
2856  
2857 # Functions having to do with file formats, parsing,
2858 # formatting, and so on.
2859  
2860 sub _alphabet_check_array {
2861 my @chars = @{ $_[0] };
2862 my $chars = join("", @chars);
2863 my @alph = @FAST::Bio::UnivAln::alph;
2864 my $letter;
2865  
2866 #print "Sequence being checked =$chars.\n";
2867 #print " Alphabet being checked =";
2868 #my $aref;
2869 #for $aref (@alph) { print $aref; }; print ".\n";
2870  
2871 for $letter (@alph) { #There must be a better way ???
2872 if ($letter =~ /\w|-/) {
2873 $chars =~ s/$letter//gi;
2874 } else {
2875 $chars =~ s/\{$letter}//gi;
2876 }
2877 }
2878 return $chars;
2879 }
2880  
2881 =head2 alphabet_check()
2882  
2883 Usage : @offendig_characters = $aln->alphabet_check($rowsel);
2884 Function : Check rows of the alignment for ``offending characters'', i.e.
2885 characters that are not (currently) expected to be found in the
2886 aligned sequences, because they're not in the default alphabet
2887 that belongs to the specified L<Alignment Type>.
2888 Currently, the Alignment Type can only be set explicitly
2889 via the constructor, or accessor. Since the default alphabet
2890 is not the IUPAC code (e.g. just A,C,G,T,-,? in case of DNA),
2891 this is just a proof of concept.
2892 Returns : an array containing the offending characters, one string per row
2893 Argument : $rrowsel: Reference to the selector designating the rows
2894 to which the check is applied, as in cases (2)-(4) in seqs().
2895  
2896 =cut
2897  
2898 #'
2899 sub alphabet_check {
2900 my $self = shift;
2901 my $rrowsel = shift;
2902  
2903 @FAST::Bio::UnivAln::alph = @{$UnivAlnAlphs{$UnivAlnType{$self->type()}."Mg"}};
2904 return $self->map_r(\&_alphabet_check_array,$rrowsel);
2905 }
2906  
2907  
2908 =head2 _file_read()
2909  
2910 Usage : n/a (internal function)
2911 Function : Read data from file, and call the parsing system to store data
2912 into the object fields
2913 Returns : 1 on success
2914 Argument : filename, and (optionally) the format if known.
2915  
2916 =cut
2917  
2918 sub _file_read {
2919 my($self, $filename, $ffmt) = @_;
2920 my($ent);
2921 if (!(-e $filename)) {
2922 carp("File $filename not found");
2923 }
2924 if (!(-r $filename)) {
2925 carp("File $filename not readable");
2926 }
2927 open(UnivAln::INPUT, $filename);
2928 $ent = join("",<UnivAln::INPUT>);
2929 close(UnivAln::INPUT);
2930 _parse($self, $ent, $ffmt);
2931  
2932 return 1;
2933 }
2934  
2935 sub parse {
2936 my($self) = shift;
2937 carp "You've called a parsing routine that may be removed in future versions
2938 of FAST::Bio::UnivAln; currently the only long-term supported method for
2939 reading in files is via the new() constructor; revision of the parsing
2940 system should be finalized in mid-1997 ";
2941 $self->_parse(@_);
2942 }
2943 sub parse_unknown {
2944 my($self) = shift;
2945 carp "You've called a parsing routine that may be removed in future versions
2946 of FAST::Bio::UnivAln; currently the only long-term supported method for
2947 reading in files is via the new() constructor; revision of the parsing
2948 system should be finalized in mid-1997 ";
2949 $self->_parse_unknown(@_);
2950 }
2951 sub parse_fasta {
2952 my($self) = shift;
2953 carp "You've called a parsing routine that may be removed in future versions
2954 of FAST::Bio::UnivAln; currently the only long-term supported method for
2955 reading in files is via the new() constructor; revision of the parsing
2956 system should be finalized in mid-1997 ";
2957 $self->_parse_fasta(@_);
2958 }
2959 sub parse_raw {
2960 my($self) = shift;
2961 carp "You've called a parsing routine that may be removed in future versions
2962 of FAST::Bio::UnivAln; currently the only long-term supported method for
2963 reading in files is via the new() constructor; revision of the parsing
2964 system should be finalized in mid-1997 ";
2965 $self->_parse_raw(@_);
2966 }
2967 sub parse_bad {
2968 my($self) = shift;
2969 carp "You've called a parsing routine that may be removed in future versions
2970 of FAST::Bio::UnivAln; currently the only long-term supported method for
2971 reading in files is via the new() constructor; revision of the parsing
2972 system should be finalized in mid-1997 ";
2973 $self->_parse_bad(@_);
2974 }
2975  
2976  
2977 =head2 _parse()
2978  
2979 Usage : $aln->_parse($ent,[$ffmt]);
2980 Function : Parses $ent into the object fields, according to
2981 $ffmt or $self->{'ffmt'}.
2982 Returns : 1 on success
2983 Argument : the prospective alignment to be parsed,
2984 and optionally its format so that it doesn't need to be estimated
2985 Note that ``raw'' is not estimated in a reliable way by readseq
2986 if readseq is installed; I presume it is then estimated only if
2987 the sequence(s) are longer than 111 basepairs
2988  
2989 =cut
2990  
2991 #'
2992 sub _parse {
2993 my($self, $ent, $ffmt) = @_;
2994  
2995 if (defined($ffmt) && defined($UnivAlnForm{$ffmt})) {
2996 $ffmt=$UnivAlnForm{$ffmt};
2997 } else {
2998 #warn("Unrecognized or undefined alignment format, using built-in ");
2999 # no carp->focussed debugging
3000 # We later assume that self->{'ffmt'} in a key in $UnivAlnForm if it is defined
3001 $ffmt=$self->{'ffmt'};
3002 }
3003  
3004 # We simply need to call the appropriate parsing function, based
3005 # on the value of $ffmt. Since we've set up the %FuncParse
3006 # associative array to contain all of the necessary function calls
3007 # based on the 'ffmt' value, this is rather straightforward.
3008  
3009 if (defined($ffmt) && (exists $FuncParse{$ffmt})) {
3010 &{$FuncParse{$ffmt}}($self,$ent);
3011 } else {
3012 &{$FuncParse{$UnivAlnForm{"unknown"}}}($self,$ent);
3013 }
3014  
3015 return 1;
3016 }
3017  
3018  
3019 =head2 _parse_unknown()
3020  
3021 Usage : $aln->_parse_unknown($ent);
3022 Function : tries to figure out the format of $ent and then
3023 calls the appropriate function to parse it into $self->{'seqs'}.
3024 Returns : 1 on success
3025 Argument : $ent : the rough multi-line string to be parsed
3026  
3027 =cut
3028  
3029 sub _parse_unknown {
3030 my($self, $ent) = @_;
3031  
3032 if ($ent =~ /^>[ \t]*\S*[ \t]*.*?\n(?:\n|.)*?(?=\n>|\Z)/mg) {
3033 # >[ \t]*\S* : The ``>''-sign, space or tab, and the id;
3034 # [ \t]*.*?\n : space or tab again, the description (arbitrary
3035 # letters until the next newline, so use non-greedy
3036 # regexp (``.*?''), ``.*'' would gobble up everthing);
3037 # (?:\n|.)*? : now arbitrary text including newlines, non-greedy,
3038 # ``(?:...)'' just groups ``...'' together;
3039 # (?=\n>|\Z) : up until either a newline followed by the ``>''-sign,
3040 # or the end of the multiline string (so-called positive
3041 # lookahead)
3042 $self->_parse_fasta($ent);
3043 } elsif ($ent =~ /^[A-Z_0-9$_GAP_SYMBOL$_UNKN_SYMBOL\s]+$/ig) {
3044 # currently in raw format, all letters+numbers+gap+missing
3045 # symbol is accepted...
3046 $self->_parse_raw($ent);
3047 } elsif (($ent =~ /\s*^CLUSTAL/g) && ($_CLUSTAL ne "")) {
3048 $self->_parse_clustal($ent);
3049 } elsif ($_READSEQ ne "") {
3050 $self->_parse_readseq($ent);
3051 } else {
3052 # some other weird format, so we call _parse_bad.
3053 $self->_parse_bad($ent);
3054 }
3055  
3056 return 1;
3057 }
3058  
3059  
3060  
3061 =head2 _parse_bad()
3062  
3063 Usage : $aln->_parse_bad;
3064 Function : Carp on the bad data that the user gave us.
3065 Returns : undef
3066 Argument : (multiline) string that cannot be parsed
3067  
3068 =cut
3069  
3070 sub _parse_bad {
3071 my($self,$ent) = @_;
3072  
3073 carp "Can't parse unknown alignment format:\n$ent";
3074 return undef
3075 }
3076  
3077 =head2 _parse_readseq()
3078  
3079  
3080 Usage : $aln->_parse_readseq;
3081 Function : Try readseq to parse data.
3082 Returns : 1 on success
3083 Argument : $ent : the rough multi-line string to be parsed
3084  
3085  
3086 =cut
3087  
3088 sub _parse_readseq {
3089 my($self,$ent) = @_;
3090  
3091 my $tmp1 = POSIX::tmpnam;
3092 open(TMP1,">$tmp1") or carp "Unable to sucessfully open file for readseq";
3093 print TMP1 $ent;
3094 close TMP1;
3095 open(READSEQ,"$_READSEQ $tmp1 -pipe -format=Fasta |") or
3096 carp "Unable to sucessfully open pipe to readseq due to $!";
3097 $ent = join("\n",<READSEQ>);
3098 close(READSEQ);
3099 #going thru fasta format to preserve id/desc
3100 $self->_parse_fasta($ent);
3101  
3102 return 1;
3103 }
3104  
3105 sub _parse_clustal {
3106 my($self,$ent) = @_;
3107  
3108 my $tmp1 = POSIX::tmpnam;
3109 open(TMP1,">$tmp1") or carp "Unable to sucessfully open file for CLUSTAL";
3110 print TMP1 $ent;
3111 close TMP1;
3112 my $tmp2 = POSIX::tmpnam;
3113 open(CLUSTAL,"$_CLUSTAL -infile=$tmp1 -outfile=$tmp2 -convert -output=GDE|") or
3114 carp "Unable to sucessfully open pipe to CLUSTAL";
3115 my $msg = join("\n",<CLUSTAL>);
3116 close(CLUSTAL);
3117 open(TMP2,"$tmp2") or carp "Unable to sucessfully open file for CLUSTAL";
3118 $ent = join("\n",<TMP2>);
3119 close TMP2;
3120 $ent =~ s/^#/>/mg;
3121 $ent =~ s/^%/>/mg;
3122 $self->_parse_fasta($ent);
3123  
3124 return $msg;
3125 }
3126  
3127  
3128 =head2 _parse_raw()
3129  
3130 Usage : $aln->_parse_raw;
3131 Function : parses $ent into the $self->{'seqs'} field, using raw
3132 file format.
3133 Returns : 1 on success
3134 Argument : (multiline) string to be parsed
3135  
3136 =cut
3137  
3138 sub _parse_raw {
3139 my ($self) = shift;
3140 my ($seqs) = @_;
3141  
3142 $self->_seqs($seqs);
3143 $self->ffmt('raw');
3144 $self->descffmt('raw');
3145  
3146 return 1;
3147 }
3148  
3149  
3150  
3151 =head2 _parse_fasta()
3152  
3153 Usage : $aln->_parse_fasta;
3154 Function : parses $ent into the 'seqs' field, using fasta
3155 file format.
3156 Returns : 1 on success
3157 Argument : (multiline) string to be parsed
3158  
3159 =cut
3160  
3161 sub _parse_fasta {
3162 my ($self) = shift;
3163 my ($ent) = @_;
3164 my (@lines,$line,@seqs);
3165  
3166 @lines = split("\n", $ent);
3167  
3168 my $counter = -1;
3169 foreach $line (@lines) {
3170 if ($line =~ /^>[ \t]*(\S*)[ \t]*(.*)$/) {
3171 $counter++;
3172 if (defined($1)) {
3173 my $id = $1;
3174 $id =~ s/,//;
3175 $self->{'row_ids'}[$counter] = $id;
3176 }
3177 if (defined($2)) {
3178 $self->{'row_descs'}[$counter] = $2;
3179 }
3180 $seqs[$counter] = "";
3181 }
3182 elsif ($line =~ /^(.+)$/) {
3183 if (defined($1)) {
3184 $seqs[$counter] .= $1;
3185 }
3186 }
3187 else{ next; }
3188 }
3189  
3190 $self->_seqs([ @seqs ]);
3191 $self->ffmt('fasta');
3192 $self->descffmt('fasta');
3193 return 1;
3194 }
3195  
3196 # Functions having to do with file formats, and OUTPUT
3197  
3198  
3199 =head2 copy()
3200  
3201 Usage : $copyOfObj = $myUnivAln->copy;
3202 Function : Returns an identical copy of the object.
3203 Returns : FAST::Bio::UnivAln
3204 Argument : n/a
3205  
3206 =cut
3207  
3208 sub copy {
3209 my($self) = shift;
3210 my(%copy);
3211 my($ii);
3212  
3213 $copy{'seqs'} = [$self->_arys()]; #SLOW!!
3214 $copy{'id'} = $self->{'id'};
3215 $copy{'desc'} = $self->{'desc'};
3216 foreach (keys %{$self->{'names'}}) {
3217 $copy{'names'}{$_} = $self->{'names'}{$_};
3218 }
3219 $copy{'row_ids'} = [ @{ $self->{'row_ids'} } ];
3220 $copy{'row_descs'} = [ @{ $self->{'row_descs'} } ];
3221 $copy{'col_ids'} = [ @{ $self->{'col_ids'} } ];
3222 $copy{'col_descs'} = [ @{ $self->{'col_descs'} } ];
3223 $copy{'numbering'} = $self->{'numbering'};
3224 $copy{'type'} = [ @{ $self->{'type'} } ];
3225 $copy{'ffmt'} = $self->{'ffmt'};
3226 $copy{'descffmt'}= $self->{'descffmt'};
3227 $copy{'inplace'}= $self->{'inplace'};
3228  
3229 return bless \%copy, ref($self);
3230 }
3231  
3232 =head2 layout()
3233  
3234 Usage : $aln->layout($format);
3235 Function : Returns the alignment in whichever format the user specifies,
3236 or according to the "ffmt" field if the user does not specify
3237 a format.
3238 Returns : varies; "" if unsuccessful
3239 Argument : $format (one of the formats as defined in $UnivAlnForm).
3240  
3241 =cut
3242  
3243 sub layout {
3244 my($self,$ffmt) = @_;
3245  
3246 $ffmt ||= $self->{"ffmt"};
3247  
3248 # replace internally handled formats by number code
3249 if (defined($ffmt) && defined($UnivAlnForm{$ffmt})) {
3250 $ffmt = $UnivAlnForm{$ffmt};
3251 }
3252  
3253 if (defined($ffmt) && (exists $FuncOut{$ffmt})) {
3254 return &{$FuncOut{$ffmt}}($self);
3255 } elsif ($_READSEQ ne "") {
3256 return $self->out_readseq($ffmt);
3257 } else {
3258 carp "Can't find routine to write format $ffmt";
3259 return "";
3260 }
3261 }
3262  
3263  
3264  
3265 =head2 out_bad()
3266  
3267 Usage : $aln->out_bad;
3268 Function : Carp if we don't know the output format.
3269 Returns : undef
3270 Argument : n/a
3271  
3272 =cut
3273  
3274 #'
3275 sub out_bad {
3276 my($self) = shift;
3277  
3278 carp "Can't write alignment format $self->{\"ffmt\"}";
3279 return undef;
3280 }
3281  
3282  
3283  
3284  
3285 =head2 out_raw()
3286  
3287 Usage : $aln->out_raw;
3288 Function : Returns the alignment in raw format.
3289 Returns : multiline string
3290 Argument : n/a
3291  
3292 =cut
3293  
3294 sub out_readseq {
3295 my $self = shift;
3296 my $ffmt = shift;
3297 my $seqs = $self->out_fasta();
3298 # The following sometimes causes seg-faults if $ffmt is PAUP or PIR,
3299 # but seem to work nicely for MSF :-(
3300 # Example:
3301 # % cat fastafile | /vol/biotools/bin/readseq -pipe -format=MSF > AAA
3302 # % cat fastafile | /vol/biotools/bin/readseq -pipe -format=PAUP > AAA
3303 # Segmentation fault
3304 # % /vol/biotools/bin/readseq fastafile -pipe -format=PAUP > AAA
3305 # open(READSEQ,"echo \"$seqs\" | $_READSEQ -pipe -format=$ffmt |") ||
3306 # carp "Unable to sucessfully open pipe to readseq due to $!";
3307  
3308 # Therefore, better use tmp files:
3309 my $tmp1 = POSIX::tmpnam;
3310 open(TMP1,">$tmp1") or carp "Unable to sucessfully open file for readseq";
3311 print TMP1 $seqs;
3312 close TMP1;
3313 open(READSEQ,"$_READSEQ $tmp1 -pipe -format=$ffmt |") ||
3314 carp "Unable to sucessfully open pipe to readseq due to $!";
3315 $seqs = join("",<READSEQ>);
3316 close(READSEQ);
3317 return $seqs;
3318 }
3319  
3320 sub out_raw {
3321 my($self) = shift;
3322 # The raw format is just a multiline string
3323 return $self->_strs();
3324 }
3325  
3326 # UNTESTED AND UNDOCUMENTED PRETTY-PRINTING ROUTINE
3327 sub out_raw2 {
3328 my($self) = shift;
3329 my($seq,$row,$id,$desc);
3330  
3331 my($rrowsel,$rcolsel) = $self->_fixbounds(@_);
3332 my $seqs = "Aln ".$self->id()." (#=".scalar(@{$self->no_allgap_inds()})
3333 .",var=".scalar(@{$self->var_inds()})."), ".$self->desc()."\n";
3334  
3335 foreach $row (@$rrowsel) {
3336 $id = $self->{'row_ids'}[$row] || $row;
3337 my $format = "%".$_MAX_SIZE_TAXANAME."s";
3338 $seqs .= sprintf("$format",$id);
3339 $seqs.=" ";
3340 my $tmp = $self->{'inplace'};
3341 $self->{'inplace'} = 0; # The user does not want/expect inplace to be acting
3342 # in the out_fasta function !
3343 $seq = [$self->_select([$row],$rcolsel)];
3344 $self->{'inplace'} = $tmp;
3345 $seqs.=join("",@{$seq->[0]}); #one row only, it's no. 0 !!!
3346 $seqs.="\n";
3347 }
3348 #carp "? matched" if ($seqs =~ /\?/); #??!!
3349 return $seqs;
3350 }
3351  
3352  
3353 =head2 out_fasta()
3354  
3355 Usage : $aln->out_fasta;
3356 Function : Returns the alignment as a string in fasta format.
3357 Returns : multiline string
3358 Argument : Same as seqs()
3359 Comment : The old ``out_fasta()'' function with no arguments
3360 is slightly faster and simpler; still available as out_fasta2().
3361  
3362 =cut
3363  
3364 sub out_fasta2 {
3365 my($self) = shift;
3366 my $seqs = "";
3367 my($seq,$id,$desc);
3368  
3369 my $counter = -1;
3370 foreach $seq (@{ $self->{'seqs'} }) {
3371 $counter++;
3372 $seqs.='> ';
3373 $id = $self->{'row_ids'}[$counter];
3374 if (defined($id)) {
3375 $seqs.=$id;
3376 }
3377 $seqs.=" ";
3378 $desc = $self->{'row_descs'}[$counter];
3379 if (defined($desc)) {
3380 $seqs.=$desc;
3381 }
3382 $seqs.="\n";
3383 $seqs.=join("",@$seq);
3384 $seqs.="\n";
3385 }
3386 return $seqs;
3387 }
3388  
3389 sub out_fasta {
3390 my($self) = shift;
3391 my($seq,$row,$id,$desc);
3392  
3393 my($rrowsel,$rcolsel) = $self->_fixbounds(@_);
3394 my $seqs = "";
3395  
3396 foreach $row (@$rrowsel) {
3397 $seqs.='> ';
3398 $id = $self->{'row_ids'}[$row];
3399 if (defined($id)) {
3400 $seqs.=$id;
3401 }
3402 $seqs.=" ";
3403 $desc = $self->{'row_descs'}[$row];
3404 if (defined($desc)) {
3405 $seqs.=$desc;
3406 }
3407 $seqs.="\n";
3408 my $tmp = $self->{'inplace'};
3409 $self->{'inplace'} = 0; # The user does not want/expect inplace to be acting
3410 # in the out_fasta function !
3411 $seq = [$self->_select([$row],$rcolsel)];
3412 $self->{'inplace'} = $tmp;;
3413 $seqs.=join("",@{$seq->[0]}); #one row only, it's no. 0 !!!
3414 $seqs.="\n";
3415 }
3416 #carp "? matched" if ($seqs =~ /\?/); #??!!
3417 return $seqs;
3418 }
3419  
3420  
3421 sub catch {
3422 print "Caught internal error";
3423 }
3424  
3425 1;
3426 __END__