2 * Jalview - A Sequence Alignment Editor and Viewer (Version 2.8.0b1)
3 * Copyright (C) 2014 The Jalview Authors
5 * This file is part of Jalview.
7 * Jalview is free software: you can redistribute it and/or
8 * modify it under the terms of the GNU General Public License
9 * as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
11 * Jalview is distributed in the hope that it will be useful, but
12 * WITHOUT ANY WARRANTY; without even the implied warranty
13 * of MERCHANTABILITY or FITNESS FOR A PARTICULAR
14 * PURPOSE. See the GNU General Public License for more details.
16 * You should have received a copy of the GNU General Public License along with Jalview. If not, see <http://www.gnu.org/licenses/>.
17 * The Jalview Authors are detailed in the 'AUTHORS' file.
21 import jalview.datamodel.AlignmentI;
22 import jalview.datamodel.Sequence;
23 import jalview.datamodel.SequenceI;
25 import java.io.IOException;
26 import java.util.LinkedHashMap;
28 import java.util.Map.Entry;
32 * A parser for input or output of MEGA format files. <br>
34 * Tamura K, Stecher G, Peterson D, Filipski A, and Kumar S (2013) MEGA6:
35 * Molecular Evolutionary Genetics Analysis Version 6.0. Molecular Biology and
36 * Evolution 30: 2725-2729. <br>
39 * MEGA file format is supported as described in
40 * http://www.megasoftware.net/manual.pdf <br>
43 * <li>nested comments (marked by [ ]) are accepted but not preserved</li>
44 * <li>to be completed</li>
47 * @see http://www.megasoftware.net/
49 public class MegaFile extends AlignFile
51 private static final int DEFAULT_LINE_LENGTH = 60;
53 private static final String INDENT = " ";
55 private static final String N_SITES = "NSites";
57 private static final String N_SEQS = "NSeqs";
59 private static final String MISSING = "Missing";
61 private static final String IDENTICAL = "Identical";
63 private static final String INDEL = "Indel";
65 private static final String CODETABLE = "CodeTable";
67 private static final String PROTEIN = "Protein";
69 private static final String NUCLEOTIDE = "Nucleotide";
71 private static final String DATATYPE = "DataType";
73 private static final char COMMENT_START = '[';
75 private static final char COMMENT_END = ']';
77 private static final String HASHSIGN = "#";
79 private static final String SEMICOLON = ";";
81 private static final String BANG = "!";
83 private static final String EQUALS = "=";
85 private static final String MEGA_ID = HASHSIGN + "MEGA";
87 private static final String TITLE = "Title";
89 private static final String FORMAT = "Format";
91 private static final String DESCRIPTION = "Description";
93 private static final String GENE = "Gene";
95 private static final String DOMAIN = "Domain";
98 * names of properties to save to the alignment (may affect eventual output
101 static final String PROP_TITLE = "MEGA_TITLE";
103 static final String PROP_INTERLEAVED = "MEGA_INTERLEAVED";
105 static final String PROP_DESCRIPTION = "MEGA_DESCRIPTION";
107 static final String PROP_CODETABLE = "MEGA_CODETABLE";
109 static final String PROP_IDENTITY = "MEGA_IDENTITY";
111 static final String PROP_MISSING = "MEGA_MISSING";
113 static final String PROP_DATATYPE = "MEGA_DATATYPE";
115 // number of bases per line of file (value is inferred)
116 static final String PROP_LINELENGTH = "MEGA_LINELENGTH";
118 // TODO: need a controlled name for Gene as a feature if we want to be able to
119 // output the MEGA file with !Gene headers
120 // WTF do we do if the sequences get realigned?
122 // initial size for sequence data buffer
123 private static final int SEQBUFFERSIZE = 256;
125 private static final String SPACE = " ";
128 * number of sequence positions output per line
130 private int positionsPerLine;
132 private String title;
134 // gap character may be explicitly declared, if not we infer it
135 private Character gapCharacter;
137 // identity character if declared
138 private char identityCharacter = 0;
140 // this can be True, False or null (meaning not asserted in file)
141 private Boolean nucleotide;
143 // set once we have seen one block of interleaved data
144 private boolean firstDataBlockRead = false;
146 // this can be True, False or null (meaning we don't know yet)
147 private Boolean interleaved;
149 // write end of line positions as a comment
150 private boolean writePositionNumbers = true;
156 public MegaFile(String inFile, String type) throws IOException
161 public MegaFile(FileParse source) throws IOException
167 * Parse the input stream.
170 public void parse() throws IOException
173 * Read and process MEGA and Title/Format/Description headers if present.
174 * Returns the first data line following the headers.
176 String dataLine = parseHeaderLines();
179 * Temporary store of {sequenceId, positionData} while parsing interleaved
180 * sequences; sequences are maintained in the order in which they are added
181 * i.e. read in the file
183 Map<String, StringBuilder> seqData = new LinkedHashMap<String, StringBuilder>();
186 * The id of the sequence being read (for non-interleaved)
188 String currentId = "";
190 while (dataLine != null)
192 dataLine = dataLine.trim();
193 if (dataLine.length() > 0)
195 if (dataLine.startsWith(BANG + GENE))
199 else if (dataLine.startsWith(BANG + DOMAIN))
201 parseDomain(dataLine);
205 currentId = parseDataLine(dataLine, seqData, currentId);
208 else if (!seqData.isEmpty())
211 * Blank line after processing some data...
213 this.firstDataBlockRead = true;
215 dataLine = nextNonCommentLine();
218 // remember the (longest) line length read in, so we can output the same
219 setAlignmentProperty(PROP_LINELENGTH, String.valueOf(positionsPerLine));
221 setSequences(seqData);
225 * Parse a !Gene command line
229 protected void parseGene(String dataLine)
234 * Parse a !Domain command line
238 private void parseDomain(String dataLine)
243 * Returns the next line that is not a comment, or null at end of file.
244 * Comments in MEGA are within [ ] brackets, and may be nested.
247 * @throws IOException
249 protected String nextNonCommentLine() throws IOException
251 return nextNonCommentLine(0);
255 * Returns the next non-comment line (or part line), or null at end of file.
256 * Comments in MEGA are within [ ] brackets, and may be nested. They may occur
257 * anywhere within a line (for example at the end with position numbers); this
258 * method returns the line with any comments removed.
261 * current depth of nesting of comments while parsing
263 * @throws IOException
265 protected String nextNonCommentLine(final int depth) throws IOException
273 System.err.println("Warning: unterminated comment in data file");
279 * If we are in a (possibly nested) comment after parsing this line, keep
280 * reading recursively until the comment has unwound
282 int newDepth = commentDepth(data, depth);
285 return nextNonCommentLine(newDepth);
290 * not in a comment by end of this line; return what is left
292 String nonCommentPart = getNonCommentContent(data, depth);
293 return nonCommentPart;
298 * Returns what is left of the input data after removing any comments, whether
299 * 'in progress' from preceding lines, or embedded in the current line
304 * nested depth of comments pending termination
306 * @throws FileFormatException
308 protected static String getNonCommentContent(String data, int depth)
309 throws FileFormatException
311 int len = data.length();
312 StringBuilder result = new StringBuilder(len);
313 for (int i = 0; i < len; i++)
315 char c = data.charAt(i);
340 return result.toString();
344 * Calculates new depth of comment after parsing an input line i.e. the excess
345 * of opening '[' over closing ']' characters. Any excess ']' are ignored (not
346 * treated as comment delimiters).
351 * current comment nested depth before parsing the line
352 * @return new depth after parsing the line
354 protected static int commentDepth(CharSequence data, int depth)
356 int newDepth = depth;
357 int len = data.length();
358 for (int i = 0; i < len; i++)
360 char c = data.charAt(i);
361 if (c == COMMENT_START)
365 else if (c == COMMENT_END && newDepth > 0)
374 * Convert the parsed sequence strings to objects and store them in the model.
378 protected void setSequences(Map<String, StringBuilder> seqData)
380 Set<Entry<String, StringBuilder>> datasets = seqData.entrySet();
382 for (Entry<String, StringBuilder> dataset : datasets)
384 String sequenceId = dataset.getKey();
385 StringBuilder characters = dataset.getValue();
386 SequenceI s = new Sequence(sequenceId, new String(characters));
387 this.seqs.addElement(s);
392 * Process one line of sequence data. If it has no sequence identifier, append
393 * to the current id's sequence. Else parse out the sequence id and append the
394 * data (if any) to that id's sequence. Returns the sequence id (implicit or
395 * explicit) for this line.
401 * @throws IOException
403 protected String parseDataLine(String dataLine,
404 Map<String, StringBuilder> seqData, String currentId)
407 String seqId = getSequenceId(dataLine);
411 * Just character data
413 parseNoninterleavedDataLine(dataLine, seqData, currentId);
416 else if ((HASHSIGN + seqId).trim().equals(dataLine.trim()))
419 * Sequence id only - header line for noninterleaved data
426 * Sequence id followed by data
428 parseInterleavedDataLine(dataLine, seqData, seqId);
434 * Add a line of sequence data to the buffer for the given sequence id. Start
435 * a new one if we haven't seen it before.
440 * @throws IOException
442 protected void parseNoninterleavedDataLine(String dataLine,
443 Map<String, StringBuilder> seqData, String currentId)
446 if (currentId == null)
449 * Oops. Data but no sequence id context.
451 throw new IOException("No sequence id context at: " + dataLine);
454 assertInterleaved(false, dataLine);
456 StringBuilder sb = getSequenceDataBuffer(seqData, currentId);
458 dataLine = reformatSequenceData(dataLine, sb.length(), seqData);
461 setPositionsPerLine(Math.max(positionsPerLine, dataLine.length()));
465 * Get the sequence data for this sequence id, starting a new one if
472 protected StringBuilder getSequenceDataBuffer(
473 Map<String, StringBuilder> seqData, String currentId)
475 StringBuilder sb = seqData.get(currentId);
478 // first data met for this sequence id, start a new buffer
479 sb = new StringBuilder(SEQBUFFERSIZE);
480 seqData.put(currentId, sb);
486 * Parse one line of interleaved data e.g.
489 * #TheSeqId CGATCGCATGCA
495 * @throws IOException
497 protected void parseInterleavedDataLine(String dataLine,
498 Map<String, StringBuilder> seqData, String seqId)
502 * New sequence found in second or later data block - error.
504 if (this.firstDataBlockRead && !seqData.containsKey(seqId))
506 throw new IOException(
507 "Parse error: misplaced new sequence starting at " + dataLine);
510 StringBuilder sb = getSequenceDataBuffer(seqData, seqId);
511 String data = dataLine.substring(seqId.length() + 1).trim();
514 * Do nothing if this line is _only_ a sequence id with no data following.
516 * Remove any internal spaces
518 if (data != null && data.length() > 0)
520 data = reformatSequenceData(data, sb.length(), seqData);
522 setPositionsPerLine(Math.max(positionsPerLine, data.length()));
523 assertInterleaved(true, dataLine);
528 * Reformat input sequence data by removing any internal formatting spaces,
529 * and converting any 'identity' characters to the corresponding position in
530 * the first sequence.
534 * the sequence position (base 0) of the start of the data
538 protected String reformatSequenceData(String data, int startPos, Map<String, StringBuilder> seqData)
540 String formatted = data.replace(SPACE, "");
541 if (formatted.indexOf(identityCharacter) > -1)
544 * sequence contains '.' or other identity symbol; replace these with the
545 * same position from the first (reference) sequence
547 StringBuilder referenceSequence = seqData.values().iterator().next();
548 StringBuilder sb = new StringBuilder(formatted.length());
549 for (int i = 0 ; i < formatted.length() ; i++) {
550 char nextChar = formatted.charAt(i);
551 if (nextChar != identityCharacter) {
554 sb.append(referenceSequence.charAt(startPos + i));
557 formatted = sb.toString();
563 * If the line begins with (e.g.) "#abcde " then returns "abcde" as the
564 * identifier. Else returns null.
569 public static String getSequenceId(String dataLine)
571 // TODO refactor to a StringUtils type class
572 if (dataLine != null)
574 if (dataLine.startsWith(HASHSIGN))
576 int spacePos = dataLine.indexOf(" ");
577 return (spacePos == -1 ? dataLine.substring(1) : dataLine
578 .substring(1, spacePos));
585 * Read the #MEGA and Title/Format/Description header lines (if present).
587 * Save as alignment properties in case useful.
589 * @return the next non-blank line following the header lines.
590 * @throws IOException
592 protected String parseHeaderLines() throws IOException
594 String inputLine = null;
595 while ((inputLine = nextNonCommentLine()) != null)
597 inputLine = inputLine.trim();
602 if (inputLine.length() == 0)
607 if (inputLine.toUpperCase().startsWith(MEGA_ID))
612 if (isTitle(inputLine))
614 this.title = getValue(inputLine);
615 setAlignmentProperty(PROP_TITLE, title);
617 else if (inputLine.startsWith(BANG + DESCRIPTION))
619 parseDescription(inputLine);
622 else if (inputLine.startsWith(BANG + FORMAT))
624 parseFormat(inputLine);
626 else if (!inputLine.toUpperCase().startsWith(MEGA_ID))
630 * Return the first 'data line' i.e. one that is not blank, #MEGA or
640 * Parse a !Format statement. This may be multiline, and is ended by a
644 * @throws IOException
646 protected void parseFormat(String inputLine) throws IOException
648 while (inputLine != null)
650 parseFormatLine(inputLine);
651 if (inputLine.endsWith(SEMICOLON))
655 inputLine = nextNonCommentLine();
660 * Parse one line of a !Format statement. This may contain one or more
661 * keyword=value pairs.
664 * @throws FileFormatException
666 protected void parseFormatLine(String inputLine)
667 throws FileFormatException
669 if (inputLine.startsWith(BANG + FORMAT))
671 inputLine = inputLine.substring((BANG + FORMAT).length());
673 if (inputLine.endsWith(SEMICOLON))
675 inputLine = inputLine.substring(0, inputLine.length() - 1);
677 if (inputLine.length() == 0)
681 String[] tokens = inputLine.trim().split("\\s"); // any whitespace
682 for (String token : tokens)
684 parseFormatKeyword(token);
689 * Parse a Keyword=Value token. Possible keywords are
691 * <li>DataType= DNA, RNA, Nucleotide, Protein</li>
692 * <li>DataFormat= Interleaved, ?</li>
693 * <li>NSeqs= number of sequences (synonym NTaxa)</li>
694 * <li>NSites= number of bases / residues</li>
695 * <li>Property= Exon (or Coding), Intron (or Noncoding), End (of domain)</li>
696 * <li>Indel= gap character</li>
697 * <li>Identical= identity character (to first sequence) (synonym MatchChar)</li>
698 * <li>Missing= missing data character</li>
699 * <li>CodeTable= Standard, other (MEGA supports various)</li>
703 * @throws FileFormatException
704 * if an unrecognised keyword or value is encountered
706 protected void parseFormatKeyword(String token)
707 throws FileFormatException
709 String msg = "Unrecognised Format command: " + token;
710 String[] bits = token.split(EQUALS);
711 if (bits.length != 2)
713 throw new FileFormatException(msg);
715 String keyword = bits[0];
716 String value = bits[1];
719 * Jalview will work out whether nucleotide or not anyway
721 if (keyword.equalsIgnoreCase(DATATYPE))
723 if (value.equalsIgnoreCase("DNA") || value.equalsIgnoreCase("RNA")
724 || value.equalsIgnoreCase("Nucleotide"))
726 this.nucleotide = true;
727 // alignment computes whether or not it is nucleotide when created
729 else if (value.equalsIgnoreCase(PROTEIN))
731 this.nucleotide = false;
735 throw new FileFormatException(msg);
737 setAlignmentProperty(PROP_DATATYPE, value);
741 * accept non-Standard code table but save in case we want to disable
742 * 'translate as cDNA'
744 else if (keyword.equalsIgnoreCase(CODETABLE))
746 setAlignmentProperty(PROP_CODETABLE, value);
750 * save gap char to set later on alignment once created
752 else if (keyword.equalsIgnoreCase(INDEL))
754 this.gapCharacter = value.charAt(0);
757 else if (keyword.equalsIgnoreCase(IDENTICAL)
758 || keyword.equalsIgnoreCase("MatchChar"))
760 setAlignmentProperty(PROP_IDENTITY, value);
761 this.identityCharacter = value.charAt(0);
762 if (!".".equals(value))
764 System.err.println("Warning: " + token
765 + " not supported, Jalview uses '.' for identity");
769 else if (keyword.equalsIgnoreCase(MISSING))
771 setAlignmentProperty(PROP_MISSING, value);
772 System.err.println("Warning: " + token + " not supported");
775 else if (keyword.equalsIgnoreCase("Property"))
777 // TODO: figure out what to do with this
778 // can it appear more than once in a file?
779 setAlignmentProperty(PROP_MISSING, value);
782 else if (!keyword.equalsIgnoreCase(N_SEQS)
783 && !keyword.equalsIgnoreCase(N_SITES))
785 System.err.println("Warning: " + msg);
790 * Returns the trimmed data on the line following either whitespace or '=',
791 * with any trailing semi-colon removed<br>
794 * <li>Hello World</li>
795 * <li>!Hello: \tWorld;</li>
796 * <li>!Hello=World</li>
798 * should all return "World"
803 protected static String getValue(String inputLine)
805 if (inputLine == null)
810 String s = inputLine.replaceAll("\t", " ").trim();
813 * KEYWORD = VALUE should return VALUE
815 int equalsPos = s.indexOf("=");
818 value = s.substring(equalsPos + 1);
822 int spacePos = s.indexOf(' ');
823 value = spacePos == -1 ? "" : s.substring(spacePos + 1);
825 value = value.trim();
826 if (value.endsWith(SEMICOLON))
828 value = value.substring(0, value.length() - 1).trim();
834 * Returns true if the input line starts with "TITLE" or "!TITLE" (not case
835 * sensitive). The latter is the official format, some older data file
836 * examples have it without the !.
841 protected static boolean isTitle(String inputLine)
843 if (inputLine == null)
847 String upper = inputLine.toUpperCase();
848 return (upper.startsWith(TITLE.toUpperCase()) || upper.startsWith(BANG
849 + TITLE.toUpperCase()));
853 * Reads lines until terminated by semicolon, appending each to the
854 * Description property value.
856 * @throws IOException
858 protected void parseDescription(String firstDescriptionLine)
861 StringBuilder desc = new StringBuilder(256);
862 String line = getValue(firstDescriptionLine);
865 if (line.endsWith(SEMICOLON))
867 desc.append(line.substring(0, line.length() - 1));
870 else if (line.length() > 0)
872 desc.append(line).append(newline);
874 line = nextNonCommentLine();
876 setAlignmentProperty(PROP_DESCRIPTION, desc.toString());
880 * Returns the alignment sequences in Mega format.
883 public String print()
885 return MEGA_ID + newline + print(getSeqsAsArray());
889 * Write out the alignment sequences in Mega format - interleaved unless
890 * explicitly noninterleaved.
892 protected String print(SequenceI[] s)
895 if (this.interleaved != null && !this.interleaved)
897 result = printNonInterleaved(s);
901 result = printInterleaved(s);
907 * Print to string in Interleaved format - blocks of next N characters of each
912 protected String printInterleaved(SequenceI[] s)
914 int maxIdLength = getMaxIdLength(s);
915 int maxSequenceLength = getMaxSequenceLength(s);
916 int numLines = maxSequenceLength / positionsPerLine + 3; // approx
918 int numDataBlocks = (maxSequenceLength - 1) / positionsPerLine + 1;
919 int spaceEvery = this.nucleotide != null && this.nucleotide ? 3 : 10;
920 int chunksPerLine = (positionsPerLine + spaceEvery - 1) / spaceEvery;
923 * Roughly size a buffer to hold the whole output
925 StringBuilder sb = new StringBuilder(numLines
926 * (maxIdLength + positionsPerLine + chunksPerLine + 10));
929 * Output as: #Seqid CGT AGC ACT ... or blocks of 10 for peptide
932 for (int i = 0; i < numDataBlocks; i++)
935 boolean first = true;
937 for (SequenceI seq : s)
940 String seqId = String.format("#%-" + maxIdLength + "s",
944 * output next line for this sequence
947 int lastPos = seqFrom + positionsPerLine; // exclusive
948 for (int j = 0; j < chunksPerLine; j++)
950 char[] subSequence = seq.getSequence(seqFrom,
951 Math.min(lastPos, seqFrom + spaceEvery));
952 if (subSequence.length > 0)
954 sb.append(SPACE).append(subSequence);
956 seqFrom += subSequence.length;
959 // all sequences should be the same length in MEGA
960 advancedBy += subSequence.length;
963 // write last position as a comment
964 if (writePositionNumbers)
966 sb.append(SPACE).append(COMMENT_START).append(from + advancedBy)
967 .append(COMMENT_END);
975 return new String(sb);
979 * Outputs to string the MEGA header and any other known and relevant
980 * alignment properties
984 protected String printHeaders(AlignmentI al)
986 StringBuilder sb = new StringBuilder(128);
987 sb.append(MEGA_ID).append(newline);
988 String propertyValue = (String) al.getProperty(PROP_TITLE);
989 if (propertyValue != null)
991 sb.append(BANG).append(TITLE).append(SPACE)
992 .append(propertyValue)
996 propertyValue = (String) al.getProperty(PROP_DESCRIPTION);
997 if (propertyValue != null)
999 sb.append(BANG).append(DESCRIPTION).append(newline)
1000 .append(propertyValue).append(SEMICOLON)
1005 * !Format DataType CodeTable
1007 sb.append(BANG).append(FORMAT).append(newline);
1008 String dataType = (String) al.getProperty(PROP_DATATYPE);
1009 if (dataType == null)
1011 dataType = al.isNucleotide() ? NUCLEOTIDE : PROTEIN;
1013 sb.append(INDENT).append(DATATYPE).append(EQUALS).append(dataType);
1014 String codeTable = (String) al.getProperty(PROP_CODETABLE);
1015 sb.append(SPACE).append(CODETABLE).append(EQUALS)
1016 .append(codeTable == null ? "Standard" : codeTable)
1020 * !Format NSeqs NSites
1021 * NSites the length of any sequence (they should all be the same), excluding
1024 sb.append(INDENT).append(N_SEQS).append(EQUALS).append(al.getHeight());
1025 SequenceI seq = al.getSequenceAt(0);
1026 sb.append(SPACE).append(N_SITES).append(EQUALS)
1027 .append(seq.getEnd() - seq.getStart() + 1);
1031 * !Format Indel Identical Missing
1034 sb.append(INDEL).append(EQUALS).append(al.getGapCharacter());
1035 String identity = (String) al.getProperty(PROP_IDENTITY);
1036 if (identity != null)
1038 sb.append(SPACE).append(IDENTICAL).append(EQUALS).append(identity);
1040 String missing = (String) al.getProperty(PROP_MISSING);
1041 if (missing != null)
1043 sb.append(SPACE).append(MISSING).append(EQUALS).append(missing);
1045 sb.append(SEMICOLON).append(newline);
1047 return sb.toString();
1051 * Get the longest sequence id (to allow aligned printout).
1056 protected static int getMaxIdLength(SequenceI[] s)
1058 // TODO pull up for reuse
1060 for (SequenceI seq : s)
1062 int len = seq.getName().length();
1063 if (len > maxLength)
1072 * Get the longest sequence length
1077 protected static int getMaxSequenceLength(SequenceI[] s)
1079 // TODO pull up for reuse
1081 for (SequenceI seq : s)
1083 int len = seq.getLength();
1084 if (len > maxLength)
1093 * Print to string in noninterleaved format - all of each sequence in turn, in
1094 * blocks of 50 characters.
1099 protected String printNonInterleaved(SequenceI[] s)
1101 int maxSequenceLength = getMaxSequenceLength(s);
1103 int numLines = maxSequenceLength / positionsPerLine + 2 + s.length;
1106 * Roughly size a buffer to hold the whole output
1108 StringBuilder sb = new StringBuilder(numLines * positionsPerLine);
1110 int spaceEvery = this.nucleotide != null && this.nucleotide ? 3 : 10;
1111 int chunksPerLine = positionsPerLine / spaceEvery;
1112 for (SequenceI seq : s)
1115 sb.append(HASHSIGN + seq.getName()).append(newline);
1117 while (startPos < seq.getLength())
1119 boolean firstChunk = true;
1121 * print next line for this sequence
1123 int lastPos = startPos + positionsPerLine; // exclusive
1124 for (int j = 0; j < chunksPerLine; j++)
1126 char[] subSequence = seq.getSequence(startPos,
1127 Math.min(lastPos, startPos + positionsPerLine));
1128 if (subSequence.length > 0)
1134 sb.append(subSequence);
1137 startPos += subSequence.length;
1143 return new String(sb);
1147 * Flag this file as interleaved or not, based on data format. Throws an
1148 * exception if has previously been determined to be otherwise.
1152 * @throws IOException
1154 protected void assertInterleaved(boolean isIt, String dataLine)
1155 throws FileFormatException
1157 if (this.interleaved != null && isIt != this.interleaved.booleanValue())
1159 throw new FileFormatException(
1160 "Parse error: mix of interleaved and noninterleaved detected, at line: "
1163 this.interleaved = new Boolean(isIt);
1164 setAlignmentProperty(PROP_INTERLEAVED, interleaved.toString());
1167 public boolean isInterleaved()
1169 return this.interleaved == null ? false : this.interleaved
1174 * Adds saved parsed values either as alignment properties, or (in some cases)
1175 * as specific member fields of the alignment
1178 public void addProperties(AlignmentI al)
1180 super.addProperties(al);
1181 if (this.gapCharacter != null)
1183 al.setGapCharacter(gapCharacter);
1187 * warn if e.g. DataType=DNA but data is protein (or vice versa)
1189 if (this.nucleotide != null && this.nucleotide != al.isNucleotide()) {
1190 System.err.println("Warning: " + this.title + " declared "
1191 + (nucleotide ? "" : " not ") + "nucleotide but it is"
1192 + (nucleotide ? " not" : ""));
1197 * Print the given alignment in MEGA format. If the alignment was created by
1198 * parsing a MEGA file, it should have properties set (e.g. Title) which can
1199 * influence the output.
1202 public String print(AlignmentI al)
1204 this.nucleotide = al.isNucleotide();
1206 String lineLength = (String) al.getProperty(PROP_LINELENGTH);
1207 this.positionsPerLine = lineLength == null ? DEFAULT_LINE_LENGTH : Integer
1208 .parseInt(lineLength);
1210 String interleave = (String) al.getProperty(PROP_INTERLEAVED);
1211 if (interleave != null)
1213 this.interleaved = Boolean.valueOf(interleave);
1216 String headers = printHeaders(al);
1217 return headers + print(al.getSequencesArray());
1221 * Returns the number of sequence positions output per line
1225 public int getPositionsPerLine()
1227 return positionsPerLine;
1231 * Sets the number of sequence positions output per line. Note these will be
1232 * formatted in blocks of 3 (nucleotide) or 10 (peptide).
1236 public void setPositionsPerLine(int p)
1238 this.positionsPerLine = p;