Debian Codegraph @

src/dr/evolution/alignment/SimpleAlignment.java

raw symbols SCIP
1 /*
2 * SimpleAlignment.java
3 *
4 * Copyright (c) 2002-2015 Alexei Drummond, Andrew Rambaut and Marc Suchard
5 *
6 * This file is part of BEAST.
7 * See the NOTICE file distributed with this work for additional
8 * information regarding copyright ownership and licensing.
9 *
10 * BEAST is free software; you can redistribute it and/or modify
11 * it under the terms of the GNU Lesser General Public License as
12 * published by the Free Software Foundation; either version 2
13 * of the License, or (at your option) any later version.
14 *
15 * BEAST is distributed in the hope that it will be useful,
16 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 * GNU Lesser General Public License for more details.
19 *
20 * You should have received a copy of the GNU Lesser General Public
21 * License along with BEAST; if not, write to the
22 * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
23 * Boston, MA 02110-1301 USA
24 */
25
26 package dr.evolution.alignment;
27
28 import dr.app.bss.XMLExporter;
29 import dr.app.tools.NexusExporter;
30 import dr.evolution.datatype.Codons;
31 import dr.evolution.datatype.DataType;
32 import dr.evolution.datatype.GeneralDataType;
33 import dr.evolution.sequence.Sequence;
34 import dr.evolution.sequence.Sequences;
35 import dr.evolution.sequence.UncertainSequence;
36 import dr.evolution.util.Taxon;
37 import dr.evolution.util.TaxonList;
38 import dr.util.NumberFormatter;
39
40 import java.io.File;
41 import java.io.IOException;
42 import java.io.PrintStream;
43 import java.util.Arrays;
44 import java.util.Collections;
45 import java.util.List;
46
47 /**
48 * A simple alignment class that implements gaps by characters in the sequences.
49 *
50 * @author Andrew Rambaut
51 * @author Alexei Drummond
52 * @version $Id: SimpleAlignment.java,v 1.46 2005/06/21 16:25:15 beth Exp $
53 */
54 @SuppressWarnings("serial")
55 public class SimpleAlignment extends Sequences implements Alignment, dr.util.XHTMLable {
56
57 // **************************************************************
58 // INSTANCE VARIABLES
59 // **************************************************************
60
61 private OutputType outputType = OutputType.FASTA;
62 private DataType dataType = null;
63 private int siteCount = 0;
64 private boolean siteCountKnown = false;
65 private boolean countStatistics = !(dataType instanceof Codons) && !(dataType instanceof GeneralDataType);
66
67 // **************************************************************
68 // SimpleAlignment METHODS
69 // **************************************************************
70
71 /**
72 * parameterless constructor.
73 */
74 public SimpleAlignment() {
75 }
76
77 /**
78 * Constructs a sub alignment based on the provided taxa.
79 *
80 * @param a
81 * @param taxa
82 */
83 public SimpleAlignment(Alignment a, TaxonList taxa) {
84
85 for (int i = 0; i < taxa.getTaxonCount(); i++) {
86 Taxon taxon = taxa.getTaxon(i);
87
88 Sequence sequence = a.getSequence(a.getTaxonIndex(taxon));
89 addSequence(sequence);
90 }
91 }
92
93 public void setOutputType(OutputType out) {
94 outputType = out;
95 }
96
97 public List<Sequence> getSequences() {
98 return Collections.unmodifiableList(sequences);
99 }
100
101 /**
102 * Calculates the siteCount by finding the longest sequence.
103 */
104 public void updateSiteCount() {
105 siteCount = 0;
106 int i, len, n = getSequenceCount();
107
108 for (i = 0; i < n; i++) {
109 len = getSequence(i).getLength();
110 if (len > siteCount)
111 siteCount = len;
112 }
113
114 siteCountKnown = true;
115 }
116
117 // **************************************************************
118 // Alignment IMPLEMENTATION
119 // **************************************************************
120
121 /**
122 * Sets the dataType of this alignment. This should be the same as
123 * the sequences.
124 */
125 public void setDataType(DataType dataType) {
126 this.dataType = dataType;
127 }
128
129 /**
130 * @return number of sites
131 */
132 public int getSiteCount(DataType dataType) {
133 return getSiteCount();
134 }
135
136 /**
137 * sequence character at (sequence, site)
138 */
139 public char getChar(int sequenceIndex, int siteIndex) {
140 return getSequence(sequenceIndex).getChar(siteIndex);
141 }
142
143 /**
144 * Returns string representation of single sequence in
145 * alignment with gap characters included.
146 */
147 public String getAlignedSequenceString(int sequenceIndex) {
148 return getSequence(sequenceIndex).getSequenceString();
149 }
150
151
152 /**
153 * Returns string representation of single sequence in
154 * alignment with gap characters excluded.
155 */
156 public String getUnalignedSequenceString(int sequenceIndex) {
157
158 StringBuffer unaligned = new StringBuffer();
159 for (int i = 0, n = getSiteCount(); i < n; i++) {
160
161 int state = getState(sequenceIndex, i);
162 if (!dataType.isGapState(state)) {
163 unaligned.append(dataType.getChar(state));
164 }
165 }
166
167 return unaligned.toString();
168 }
169
170 // **************************************************************
171 // Sequences METHODS
172 // **************************************************************
173
174 /**
175 * Add a sequence to the sequence list
176 */
177 public void addSequence(Sequence sequence) {
178 if (dataType == null) {
179 if (sequence.getDataType() == null) {
180 dataType = sequence.guessDataType();
181 sequence.setDataType(dataType);
182 } else {
183 setDataType(sequence.getDataType());
184 }
185 } else if (sequence.getDataType() == null) {
186 sequence.setDataType(dataType);
187 } else if (dataType != sequence.getDataType()) {
188 throw new IllegalArgumentException("Sequence's dataType does not match the alignment's");
189 }
190
191 int invalidCharAt = sequence.getInvalidChar();
192 if (invalidCharAt >= 0)
193 throw new IllegalArgumentException("Sequence of " + sequence.getTaxon().getId()
194 + " contains invalid char \'" + sequence.getChar(invalidCharAt) + "\' at index " + invalidCharAt);
195
196 super.addSequence(sequence);
197 updateSiteCount();
198 }
199
200 /**
201 * Insert a sequence to the sequence list at position
202 */
203 public void insertSequence(int position, Sequence sequence) {
204 if (dataType == null) {
205 if (sequence.getDataType() == null) {
206 dataType = sequence.guessDataType();
207 sequence.setDataType(dataType);
208 } else {
209 setDataType(sequence.getDataType());
210 }
211 } else if (sequence.getDataType() == null) {
212 sequence.setDataType(dataType);
213 } else if (dataType != sequence.getDataType()) {
214 throw new IllegalArgumentException("Sequence's dataType does not match the alignment's");
215 }
216
217 int invalidCharAt = sequence.getInvalidChar();
218 if (invalidCharAt >= 0)
219 throw new IllegalArgumentException("Sequence of " + sequence.getTaxon().getId()
220 + " contains invalid char \'" + sequence.getChar(invalidCharAt) + "\' at index " + invalidCharAt);
221
222 super.insertSequence(position, sequence);
223 }
224
225 // **************************************************************
226 // SiteList IMPLEMENTATION
227 // **************************************************************
228
229 /**
230 * @return number of sites
231 */
232 public int getSiteCount() {
233 if (!siteCountKnown)
234 updateSiteCount();
235 return siteCount;
236 }
237
238 /**
239 * Gets the pattern of site as an array of state numbers (one per sequence)
240 *
241 * @return the site pattern at siteIndex
242 */
243 public int[] getSitePattern(int siteIndex) {
244 Sequence seq;
245 int i, n = getSequenceCount();
246
247 int[] pattern = new int[n];
248
249 for (i = 0; i < n; i++) {
250 seq = getSequence(i);
251
252 if (siteIndex >= seq.getLength())
253 pattern[i] = dataType.getGapState();
254 else
255 pattern[i] = seq.getState(siteIndex);
256 }
257
258 return pattern;
259 }
260
261 @Override
262 public double[][] getUncertainSitePattern(int siteIndex) {
263 if (areUncertain()) {
264
265 double[][] pattern = new double[getSequenceCount()][];
266 for (int i = 0; i < getSequenceCount(); ++i) {
267
268 Sequence seq = getSequence(i);
269 if (siteIndex > seq.getLength()) {
270 pattern[i] = new double[dataType.getStateCount()];
271 Arrays.fill(pattern[i], 1.0);
272 } else {
273 if (seq instanceof UncertainSequence) {
274 pattern[i] = ((UncertainSequence) seq).getUncertainPattern(siteIndex);
275 } else {
276 pattern[i] = new double[dataType.getStateCount()];
277 int[] states = dataType.getStates(seq.getState(siteIndex));
278 for (int state : states) {
279 pattern[i][state] = 1.0;
280 }
281 }
282 }
283 }
284
285 return pattern;
286 } else {
287 throw new UnsupportedOperationException("getUncertainSitePattern not implemented yet");
288 }
289 }
290
291 /**
292 * Gets the pattern index at a particular site
293 *
294 * @return the patternIndex
295 */
296 public int getPatternIndex(int siteIndex) {
297 return siteIndex;
298 }
299
300 /**
301 * @return the sequence state at (taxon, site)
302 */
303 public int getState(int taxonIndex, int siteIndex) {
304
305 Sequence seq = getSequence(taxonIndex);
306
307 if (siteIndex >= seq.getLength()) {
308 return dataType.getGapState();
309 }
310
311 return seq.getState(siteIndex);
312 }
313
314 @Override
315 public double[] getUncertainState(int taxonIndex, int siteIndex) {
316 throw new UnsupportedOperationException("getUncertainState not implemented yet");
317 }
318
319 /**
320 */
321 public void setState(int taxonIndex, int siteIndex, int state) {
322
323 Sequence seq = getSequence(taxonIndex);
324
325 if (siteIndex >= seq.getLength()) {
326 throw new IllegalArgumentException();
327 }
328
329 seq.setState(siteIndex, state);
330 }
331
332 // **************************************************************
333 // PatternList IMPLEMENTATION
334 // **************************************************************
335
336 /**
337 * @return number of patterns
338 */
339 public int getPatternCount() {
340 return getSiteCount();
341 }
342
343 /**
344 * @return number of invariant sites
345 */
346 public int getInvariantCount() {
347 int invariantSites = 0;
348 for (int i = 0; i < getSiteCount(); i++) {
349 int[] pattern = getSitePattern(i);
350 if (Patterns.isInvariant(pattern)) {
351 invariantSites++;
352 }
353 }
354 return invariantSites;
355 }
356
357 public int getUniquePatternCount() {
358 Patterns patterns = new Patterns(this);
359 return patterns.getPatternCount();
360 }
361
362 public int getInformativeCount() {
363 Patterns patterns = new Patterns(this);
364 int informativeCount = 0;
365
366 for (int i = 0; i < patterns.getPatternCount(); i++) {
367 int[] pattern = patterns.getPattern(i);
368
369 if (isInformative(pattern)) {
370 informativeCount += patterns.getPatternWeight(i);
371 }
372 }
373
374 return informativeCount;
375 }
376
377 public int getSingletonCount() {
378 Patterns patterns = new Patterns(this);
379 int singletonCount = 0;
380
381 for (int i = 0; i < patterns.getPatternCount(); i++) {
382 int[] pattern = patterns.getPattern(i);
383
384 if (!Patterns.isInvariant(pattern) && !isInformative(pattern)) {
385 singletonCount += patterns.getPatternWeight(i);
386 }
387 }
388
389 return singletonCount;
390 }
391
392 private boolean isInformative(int[] pattern) {
393 int[] stateCounts = new int[getStateCount()];
394 for (int j = 0; j < pattern.length; j++) {
395 stateCounts[pattern[j]]++;
396 }
397
398 boolean oneStateGreaterThanOne = false;
399 boolean secondStateGreaterThanOne = false;
400 for (int j = 0; j < stateCounts.length; j++) {
401 if (stateCounts[j] > 1) {
402 if (!oneStateGreaterThanOne) {
403 oneStateGreaterThanOne = true;
404 } else {
405 secondStateGreaterThanOne = true;
406 }
407
408 }
409 }
410
411 return secondStateGreaterThanOne;
412 }
413
414 /**
415 * @return number of states for this siteList
416 */
417 public int getStateCount() {
418 return getDataType().getStateCount();
419 }
420
421 /**
422 * Gets the length of the pattern strings which will usually be the
423 * same as the number of taxa
424 *
425 * @return the length of patterns
426 */
427 public int getPatternLength() {
428 return getSequenceCount();
429 }
430
431 /**
432 * Gets the pattern as an array of state numbers (one per sequence)
433 *
434 * @return the pattern at patternIndex
435 */
436 public int[] getPattern(int patternIndex) {
437 return getSitePattern(patternIndex);
438 }
439
440 @Override
441 public double[][] getUncertainPattern(int patternIndex) {
442 throw new UnsupportedOperationException("getUncertainPattern not implemented yet");
443 }
444
445 /**
446 * @return state at (taxonIndex, patternIndex)
447 */
448 public int getPatternState(int taxonIndex, int patternIndex) {
449 return getState(taxonIndex, patternIndex);
450 }
451
452 @Override
453 public double[] getUncertainPatternState(int taxonIndex, int patternIndex) {
454 throw new UnsupportedOperationException("getUncertainPatternState not implemented yet");
455 }
456
457 /**
458 * Gets the weight of a site pattern (always 1.0)
459 */
460 public double getPatternWeight(int patternIndex) {
461 return 1.0;
462 }
463
464 /**
465 * @return the array of pattern weights
466 */
467 public double[] getPatternWeights() {
468 double[] weights = new double[siteCount];
469 for (int i = 0; i < siteCount; i++)
470 weights[i] = 1.0;
471 return weights;
472 }
473
474 /**
475 * @return the DataType of this siteList
476 */
477 public DataType getDataType() {
478 return dataType;
479 }
480
481 /**
482 * @return the frequency of each state
483 */
484 public double[] getStateFrequencies() {
485 return PatternList.Utils.empiricalStateFrequencies(this);
486 }
487
488 @Override
489 public boolean areUnique() {
490 return false;
491 }
492
493 @Override
494 public boolean areUncertain() {
495
496 for (Sequence seq : sequences) {
497 if (seq instanceof UncertainSequence) {
498 return true;
499 }
500 }
501 return false;
502 }
503
504 public void setReportCountStatistics(boolean report) {
505 countStatistics = report;
506 }
507
508 public String toString() {
509 return outputType.makeOutputString(this); // generic delegation to ease extensibility
510 }// END: toString
511
512 public String toXHTML() {
513 String xhtml = "<p><em>Alignment</em> data type = ";
514 xhtml += getDataType().getDescription();
515 xhtml += ", no. taxa = ";
516 xhtml += getTaxonCount();
517 xhtml += ", no. sites = ";
518 xhtml += getSiteCount();
519 xhtml += "</p>";
520
521 xhtml += "<pre>";
522
523 int length, maxLength = 0;
524 for (int i = 0; i < getTaxonCount(); i++) {
525 length = getTaxonId(i).length();
526 if (length > maxLength)
527 maxLength = length;
528 }
529
530 for (int i = 0; i < getTaxonCount(); i++) {
531 length = getTaxonId(i).length();
532 xhtml += getTaxonId(i);
533 for (int j = length; j <= maxLength; j++)
534 xhtml += " ";
535 xhtml += getAlignedSequenceString(i) + "\n";
536 }
537 xhtml += "</pre>";
538 return xhtml;
539 }
540
541 public enum OutputType {
542 FASTA("fasta", "fsa") {
543 @Override
544 public String makeOutputString(SimpleAlignment alignment) {
545
546 NumberFormatter formatter = new NumberFormatter(6);
547 StringBuffer buffer = new StringBuffer();
548
549 if (alignment.countStatistics) {
550 buffer.append("Site count = ").append(alignment.getSiteCount()).append("\n");
551 buffer.append("Invariant sites = ").append(alignment.getInvariantCount()).append("\n");
552 buffer.append("Singleton sites = ").append(alignment.getSingletonCount()).append("\n");
553 buffer.append("Parsimony informative sites = ").append(alignment.getInformativeCount()).append("\n");
554 buffer.append("Unique site patterns = ").append(alignment.getUniquePatternCount()).append("\n\n");
555 }
556
557 for (int i = 0; i < alignment.getSequenceCount(); i++) {
558 String name = formatter.formatToFieldWidth(alignment.getTaxonId(i), 10);
559 buffer.append(">" + name + "\n");
560 buffer.append(alignment.getAlignedSequenceString(i) + "\n");
561 }
562
563 return buffer.toString();
564 }
565 },
566
567 NEXUS("nexus", "nxs") {
568 @Override
569 public String makeOutputString(SimpleAlignment alignment) {
570
571 StringBuffer buffer = new StringBuffer();
572
573 try {
574
575 File tmp = File.createTempFile("tempfile", ".tmp");
576 PrintStream ps = new PrintStream(tmp);
577
578 NexusExporter nexusExporter = new NexusExporter(ps);
579 buffer.append(nexusExporter.exportAlignment(alignment));
580
581 } catch (IllegalArgumentException e) {
582 e.printStackTrace();
583 } catch (IOException e) {
584 e.printStackTrace();
585 }
586
587 return buffer.toString();
588 }// END: makeOutputString
589 },
590 XML("xml", "xml") {
591 @Override
592 public String makeOutputString(SimpleAlignment alignment) {
593
594 StringBuffer buffer = new StringBuffer();
595
596 try {
597
598 XMLExporter xmlExporter = new XMLExporter();
599 buffer.append(xmlExporter.exportAlignment(alignment));
600
601 } catch (IllegalArgumentException e) {
602 e.printStackTrace();
603 } catch (IOException e) {
604 e.printStackTrace();
605 }
606
607 return buffer.toString();
608 }// END: makeOutputString
609 };
610
611 // public static OutputType getValue(String str) {
612 // if (FASTA.name().equalsIgnoreCase(str)) {
613 // return FASTA;
614 // } else if (NEXUS.name().equalsIgnoreCase(str)) {
615 // return NEXUS;
616 // } else if (XML.name().equalsIgnoreCase(str)) {
617 // return XML;
618 // }
619 // return null;
620 // }// END: getValue
621 //
622 // public static Enum[] getValues() {
623 //
624 // Enum values[] = new Enum[values().length];
625 //
626 // int i = 0;
627 // for(Enum value : OutputType.values()) {
628 //
629 // values[i] = getValue(value.toString());// value;
630 // i++;
631 //
632 // }
633 //
634 // return values;
635 // }
636
637 private final String text;
638 private final String extension;
639
640 private OutputType(String text, String extension) {
641 this.text = text;
642 this.extension = extension;
643 }
644
645 public String getText() {
646 return text;
647 }
648
649 public String getExtension() {
650 return extension;
651 }
652
653 public abstract String makeOutputString(SimpleAlignment alignment);
654
655 public static OutputType parseFromString(String text) {
656 for (OutputType type : OutputType.values()) {
657 if (type.getText().compareToIgnoreCase(text) == 0) {
658 return type;
659 }
660 }
661 return null;
662 }
663
664 public static OutputType parseFromExtension(String extension) {
665 for (OutputType type : OutputType.values()) {
666 if (type.getExtension().compareToIgnoreCase(extension) == 0) {
667 return type;
668 }
669 }
670 return null;
671 }
672 }
673 }// END: class