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.SequenceFeature;
24 import jalview.datamodel.SequenceI;
26 import java.io.IOException;
27 import java.util.ArrayList;
28 import java.util.HashMap;
29 import java.util.Iterator;
30 import java.util.LinkedHashMap;
31 import java.util.List;
33 import java.util.Map.Entry;
37 * A parser for input or output of MEGA format files. <br>
39 * Tamura K, Stecher G, Peterson D, Filipski A, and Kumar S (2013) MEGA6:
40 * Molecular Evolutionary Genetics Analysis Version 6.0. Molecular Biology and
41 * Evolution 30: 2725-2729. <br>
44 * MEGA file format is supported as described in
45 * http://www.megasoftware.net/manual.pdf <br>
48 * <li>nested comments (marked by [ ]) are accepted but not preserved</li>
49 * <li>to be completed</li>
52 * @see http://www.megasoftware.net/
54 public class MegaFile extends AlignFile
56 private static final String WHITESPACE = "\\s+";
58 private static final int DEFAULT_LINE_LENGTH = 60;
60 private static final String INDENT = " ";
62 private static final String N_SITES = "NSites";
64 private static final String N_SEQS = "NSeqs";
66 private static final String MISSING = "Missing";
68 private static final String IDENTICAL = "Identical";
70 private static final String INDEL = "Indel";
72 private static final String CODETABLE = "CodeTable";
74 private static final String PROTEIN = "Protein";
76 private static final String NUCLEOTIDE = "Nucleotide";
78 private static final String DATATYPE = "DataType";
80 private static final char COMMENT_START = '[';
82 private static final char COMMENT_END = ']';
84 private static final String HASHSIGN = "#";
86 private static final String SEMICOLON = ";";
88 private static final String BANG = "!";
90 private static final String EQUALS = "=";
92 private static final String MEGA_ID = HASHSIGN + "MEGA";
94 private static final String TITLE = "Title";
96 private static final String FORMAT = "Format";
98 private static final String DESCRIPTION = "Description";
100 private static final String GENE = "Gene";
102 private static final String DOMAIN = "Domain";
104 private static final String PROPERTY = "Property";
106 private static final String CODONSTART = "CodonStart";
108 private static final String LABEL = "Label";
111 * names of properties to save to the alignment (may affect eventual output
114 static final String PROP_TITLE = "MEGA_TITLE";
116 static final String PROP_INTERLEAVED = "MEGA_INTERLEAVED";
118 static final String PROP_DESCRIPTION = "MEGA_DESCRIPTION";
120 static final String PROP_CODETABLE = "MEGA_CODETABLE";
122 static final String PROP_IDENTITY = "MEGA_IDENTITY";
124 static final String PROP_MISSING = "MEGA_MISSING";
126 static final String PROP_DATATYPE = "MEGA_DATATYPE";
128 // number of bases per line of file (value is inferred)
129 static final String PROP_LINELENGTH = "MEGA_LINELENGTH";
131 // TODO: need a controlled name for Gene as a feature if we want to be able to
132 // output the MEGA file with !Gene headers
133 // WTF do we do if the sequences get realigned?
135 // initial size for sequence data buffer
136 private static final int SEQBUFFERSIZE = 256;
138 private static final String SPACE = " ";
141 * number of sequence positions output per line
143 private int positionsPerLine;
145 private String title;
147 // gap character may be explicitly declared, default is -
148 private char gapCharacter = '-';
150 // identity character if declared
151 private char identityCharacter = 0;
153 // this can be True, False or null (meaning not asserted in file)
154 private Boolean nucleotide;
156 // set once we have seen one block of interleaved data
157 private boolean firstDataBlockRead = false;
159 // this can be True, False or null (meaning we don't know yet)
160 private Boolean interleaved;
162 // write end of line positions as a comment
163 private boolean writePositionNumbers = true;
165 // id of sequence being processed
166 private String currentSequenceId;
169 * Temporary store of {sequenceId, positionData} while parsing interleaved
170 * sequences; sequences are maintained in the order in which they are added
171 * i.e. read in the file
173 Map<String, StringBuilder> seqData;
175 // number of residues read (so far) per sequence
176 Map<String, Integer> residuesRead;
178 // current Gene if any we are parsing
179 private String currentGene;
181 // start residue (base 1) per sequence of current gene
182 Map<String, Integer> geneStart;
184 // current Domain if any we are parsing
185 private String currentDomain;
187 // start residue (base 1) per sequence of current domain
188 Map<String, Integer> domainStart;
190 // map of SequenceFeature's by sequence id
191 Map<String, List<SequenceFeature>> sequenceFeatures;
197 public MegaFile(String inFile, String type) throws IOException
202 public MegaFile(FileParse source) throws IOException
208 * Parse the input stream.
211 public void parse() throws IOException
214 sequenceFeatures = new HashMap<String, List<SequenceFeature>>();
215 geneStart = new HashMap<String, Integer>();
216 domainStart = new HashMap<String, Integer>();
217 residuesRead = new HashMap<String, Integer>();
220 * Read and process MEGA and Title/Format/Description headers if present.
221 * Returns the first data line following the headers.
223 String dataLine = parseHeaderLines();
226 * order-preserving map to hold sequences by id as they are built up during
229 seqData = new LinkedHashMap<String, StringBuilder>();
232 * The id of the sequence being read (for non-interleaved)
234 currentSequenceId = "";
236 while (dataLine != null)
238 dataLine = dataLine.trim();
239 if (dataLine.length() > 0)
241 if (dataLine.startsWith(BANG + GENE)
242 || dataLine.startsWith(BANG + DOMAIN))
244 parseGeneOrDomain(dataLine);
246 else if (dataLine.startsWith(BANG + LABEL))
248 parseLabel(dataLine);
252 currentSequenceId = parseDataLine(dataLine);
255 else if (!seqData.isEmpty())
258 * Blank line after processing some data...
262 dataLine = nextNonCommentLine();
266 * close off any features currently being parsed
268 createFeature(GENE, currentGene, geneStart);
269 createFeature(DOMAIN, currentDomain, domainStart);
271 // remember the (longest) line length read in, so we can output the same
272 setAlignmentProperty(PROP_LINELENGTH, String.valueOf(positionsPerLine));
282 protected void parseLabel(String dataLine)
284 // TODO Auto-generated method stub
289 * Post-processing after reading one block of interleaved data
291 protected void endOfDataBlock()
293 this.firstDataBlockRead = true;
295 // (initialise and) populate arrays of sequence length so far (excluding
297 // On change or end of a denoted Gene or Domain, add sequence features for
302 * Parse a !Gene or !Domain command line. MEGA accepts
304 * <li>!Gene=name;</li>
305 * <li>!Gene=name Property=Coding/Noncoding CodonStart=1/2/3;</li>
306 * <li>!Gene=genename Domain=domainname Property= etc</li>
307 * <li>!Domain=domainname Gene=genename Property= etc</li>
308 * <li>!Domain=domainname Property= etc</li>
309 * <li>!domain=domainname property=domainend</li>
311 * Properly, a Gene should be composed of Domain segments, but MEGA accepts
312 * without. Note that keywords don't seem to be case sensitive.
315 * @throws FileFormatException
317 protected void parseGeneOrDomain(String dataLine)
318 throws FileFormatException
320 String domain = null;
322 String property = null;
323 String codonStart = null;
324 String errorMsg = "Unrecognized format: " + dataLine;
326 if (!dataLine.startsWith(BANG) || !dataLine.endsWith(SEMICOLON))
328 throw new FileFormatException(errorMsg);
330 String trimmed = dataLine.substring(1, dataLine.length() - 1).trim();
331 String[] tokens = trimmed.split(WHITESPACE);
332 for (String token : tokens)
334 String[] keyValue = token.split("=");
335 if (keyValue.length != 2)
337 throw new FileFormatException(errorMsg);
339 String key = keyValue[0];
340 if (GENE.equalsIgnoreCase(key))
344 else if (DOMAIN.equalsIgnoreCase(key))
346 domain = keyValue[1];
348 else if (PROPERTY.equalsIgnoreCase(key))
350 property = keyValue[1];
352 else if (CODONSTART.equalsIgnoreCase(key))
354 codonStart = keyValue[1];
358 System.err.println("Unrecognised token: '" + key + "; in "
363 processGeneOrDomain(gene, domain, property, codonStart);
367 * Process a statement containing one or both of Gene and Domain, and
368 * optionally Property or CodonStart commands.
371 * the Gene name if specified, else null
373 * the Domain name if specified, else null
375 * the Property value if specified, else null
377 * the CodonStart value if specified, else null
379 protected void processGeneOrDomain(String gene, String domain,
380 String property, String codonStart)
383 * the order of processing below ensures that we correctly capture where a
384 * domain is in the context of an enclosing gene
386 processDomainEnd(domain, property);
388 processGeneEnd(gene);
390 processGeneStart(gene);
392 processDomainStart(domain, property);
394 // TODO save codonStart if we plan to involve it in 'translate as cDNA'
398 * If we have declared a domain, and it is not continuing, start a sequence
404 protected void processDomainStart(String domain, String property)
406 if ("domainend".equalsIgnoreCase(property))
408 currentDomain = null;
412 if (domain != null && !domain.equals(currentDomain))
414 String verboseDomain = makeVerboseDomainName(domain, property);
415 startSequenceFeature(domainStart);
417 currentDomain = verboseDomain;
422 * If we have declared a gene, and it is not continuing, start a sequence
427 protected void processGeneStart(String gene)
429 if (gene != null && !gene.equals(currentGene))
431 startSequenceFeature(geneStart);
437 * If we have been processing a domain, and it is not being continued, then
438 * make a sequence feature for the domain just ended
442 * @return true if a feature is created, else false
444 protected boolean processDomainEnd(String domain, String property)
446 String verboseDomain = makeVerboseDomainName(domain, property);
447 if (this.currentDomain != null)
449 boolean domainEnded = "domainend".equalsIgnoreCase(property);
450 if (!this.currentDomain.equals(verboseDomain) || domainEnded)
452 createFeature(DOMAIN, currentDomain, domainStart);
460 * If we have been processing a gene, and it is not being continued, then make
461 * a sequence feature for the gene just ended
464 * @return true if a feature is created, else false
466 protected boolean processGeneEnd(String gene)
468 boolean created = false;
470 * If we were processing a gene and now have either another, or none, create
471 * a sequence feature for that gene
473 if (this.currentGene != null && !this.currentGene.equals(gene))
475 createFeature(GENE, currentGene, geneStart);
483 * Makes an expanded descriptive name for Domain if possible e.g.
484 * "Intron1 (Adh Coding)". Currently incorporates the current gene name (if
485 * any) and the Coding/Noncoding property value (if given).
491 protected String makeVerboseDomainName(String domain, String property)
493 String verboseDomain = domain;
497 if ("Exon".equalsIgnoreCase(property)
498 || "Coding".equalsIgnoreCase(property))
502 else if ("Intron".equalsIgnoreCase(property)
503 || "Noncoding".equalsIgnoreCase(property))
505 coding = " Noncoding";
507 verboseDomain = domain
508 + (currentGene == null ? "" : " (" + currentGene + coding
511 return verboseDomain;
515 * Start processing a new feature
517 * @param startPositions
519 protected void startSequenceFeature(Map<String, Integer> startPositions)
522 * If the feature declaration precedes all sequences, we will know in
523 * createFeature that it started with residue 1; otherwise note now where it
524 * starts in each sequence
526 if (!residuesRead.isEmpty())
528 for (Entry<String, Integer> entry : residuesRead.entrySet())
530 String seqId = entry.getKey();
531 Integer nextResidue = entry.getValue() + 1;
532 startPositions.put(seqId, nextResidue);
538 * Add a SequenceFeature to each sequence, using the given start/end values
542 * @param featureValue
543 * @param featureStartResidues
545 protected void createFeature(String featureType, String featureValue,
546 Map<String, Integer> featureStartResidues)
548 if (featureValue == null)
553 Iterator<String> seqids = this.seqData.keySet().iterator();
554 while (seqids.hasNext())
556 String seqid = seqids.next();
557 Integer startAt = featureStartResidues.get(seqid);
558 int sfstart = startAt == null ? 1 : startAt.intValue();
559 int sfend = residuesRead.get(seqid);
560 if (sfend >= sfstart)
563 * don't add feature if entirely gapped in the sequence
565 // TODO: type="Gene" (but then all coloured the same) or
567 SequenceFeature sf = new SequenceFeature(featureValue, featureType,
568 sfstart, sfend, 0f, null);
569 sequenceFeatures.get(seqid).add(sf);
575 * Returns the next line that is not a comment, or null at end of file.
576 * Comments in MEGA are within [ ] brackets, and may be nested.
579 * @throws IOException
581 protected String nextNonCommentLine() throws IOException
583 return nextNonCommentLine(0);
587 * Returns the next non-comment line (or part line), or null at end of file.
588 * Comments in MEGA are within [ ] brackets, and may be nested. They may occur
589 * anywhere within a line (for example at the end with position numbers); this
590 * method returns the line with any comments removed.
593 * current depth of nesting of comments while parsing
595 * @throws IOException
597 protected String nextNonCommentLine(final int depth) throws IOException
605 System.err.println("Warning: unterminated comment in data file");
611 * If we are in a (possibly nested) comment after parsing this line, keep
612 * reading recursively until the comment has unwound
614 int newDepth = commentDepth(data, depth);
617 return nextNonCommentLine(newDepth);
622 * not in a comment by end of this line; return what is left
624 String nonCommentPart = getNonCommentContent(data, depth);
625 return nonCommentPart;
630 * Returns what is left of the input data after removing any comments, whether
631 * 'in progress' from preceding lines, or embedded in the current line
636 * nested depth of comments pending termination
638 * @throws FileFormatException
640 protected static String getNonCommentContent(String data, int depth)
641 throws FileFormatException
643 int len = data.length();
644 StringBuilder result = new StringBuilder(len);
645 for (int i = 0; i < len; i++)
647 char c = data.charAt(i);
672 return result.toString();
676 * Calculates new depth of comment after parsing an input line i.e. the excess
677 * of opening '[' over closing ']' characters. Any excess ']' are ignored (not
678 * treated as comment delimiters).
683 * current comment nested depth before parsing the line
684 * @return new depth after parsing the line
686 protected static int commentDepth(CharSequence data, int depth)
688 int newDepth = depth;
689 int len = data.length();
690 for (int i = 0; i < len; i++)
692 char c = data.charAt(i);
693 if (c == COMMENT_START)
697 else if (c == COMMENT_END && newDepth > 0)
706 * Convert the parsed sequence strings to objects and store them in the model.
708 protected void deriveSequences()
710 Set<Entry<String, StringBuilder>> datasets = seqData.entrySet();
712 for (Entry<String, StringBuilder> dataset : datasets)
714 String sequenceId = dataset.getKey();
715 StringBuilder characters = dataset.getValue();
716 SequenceI s = new Sequence(sequenceId, new String(characters));
717 this.seqs.addElement(s);
720 * and add any derived sequence features to the sequence
722 for (SequenceFeature sf : sequenceFeatures.get(sequenceId))
724 s.addSequenceFeature(sf);
730 * Process one line of sequence data. If it has no sequence identifier, append
731 * to the current id's sequence. Else parse out the sequence id and append the
732 * data (if any) to that id's sequence. Returns the sequence id (implicit or
733 * explicit) for this line.
737 * @throws IOException
739 protected String parseDataLine(String dataLine)
742 String seqId = getSequenceId(dataLine);
746 * Just character data
748 parseNoninterleavedDataLine(dataLine);
749 return currentSequenceId;
751 else if ((HASHSIGN + seqId).trim().equals(dataLine.trim()))
754 * Sequence id only - header line for noninterleaved data
761 * Sequence id followed by data
763 parseInterleavedDataLine(dataLine, seqId);
769 * Add a line of sequence data to the buffer for the given sequence id. Start
770 * a new one if we haven't seen it before.
773 * @throws IOException
775 protected void parseNoninterleavedDataLine(String dataLine)
778 if (currentSequenceId == null)
781 * Oops. Data but no sequence id context.
783 throw new IOException("No sequence id context at: " + dataLine);
786 assertInterleaved(false, dataLine);
788 dataLine = addSequenceData(currentSequenceId, dataLine);
790 setPositionsPerLine(Math.max(positionsPerLine, dataLine.length()));
794 * Get the sequence data for this sequence id, starting a new one if
800 protected StringBuilder getSequenceDataBuffer(String currentId)
802 StringBuilder sb = seqData.get(currentId);
805 // first data met for this sequence id, start a new buffer
806 sb = new StringBuilder(SEQBUFFERSIZE);
807 seqData.put(currentId, sb);
809 // and a placeholder for any SequenceFeature found
810 sequenceFeatures.put(currentId, new ArrayList<SequenceFeature>());
816 * Parse one line of interleaved data e.g.
819 * #TheSeqId CGATCGCATGCA
824 * @throws FileFormatException
826 protected void parseInterleavedDataLine(String dataLine, String seqId)
827 throws FileFormatException
830 * New sequence found in second or later data block - error.
832 if (this.firstDataBlockRead && !seqData.containsKey(seqId))
834 throw new FileFormatException(
835 "Parse error: misplaced new sequence starting at " + dataLine);
838 String data = dataLine.substring(seqId.length() + 1).trim();
841 * Do nothing if this line is _only_ a sequence id with no data following.
843 if (data != null && data.length() > 0)
845 data = addSequenceData(seqId, data);
846 setPositionsPerLine(Math.max(positionsPerLine, data.length()));
847 assertInterleaved(true, dataLine);
852 * Remove spaces, and replace identity symbol, before appending the sequence
853 * data to the buffer for the sequence id. Returns the reformatted added data.
854 * Also updates a count of residues read for the sequence.
860 protected String addSequenceData(String seqId, String data)
862 StringBuilder sb = getSequenceDataBuffer(seqId);
863 int len = sb.length();
864 String formatted = data.replace(SPACE, "");
867 * If sequence contains '.' or other identity symbol; replace these with the
868 * same position from the first (reference) sequence
871 StringBuilder referenceSequence = seqData.values().iterator().next();
872 StringBuilder sb1 = new StringBuilder(formatted.length());
873 for (int i = 0; i < formatted.length(); i++)
875 char nextChar = formatted.charAt(i);
876 if (nextChar != gapCharacter)
880 if (nextChar == identityCharacter
881 && len + i < referenceSequence.length())
883 sb1.append(referenceSequence.charAt(len + i));
887 sb1.append(nextChar);
890 formatted = sb1.toString();
896 * increment residue count for the sequence
900 Integer residueCount = residuesRead.get(seqId);
901 residuesRead.put(seqId, nonGapped
902 + (residueCount == null ? 0 : residueCount));
909 * If the line begins with (e.g.) "#abcde " then returns "abcde" as the
910 * identifier. Else returns null.
915 public static String getSequenceId(String dataLine)
917 // TODO refactor to a StringUtils type class
918 if (dataLine != null)
920 if (dataLine.startsWith(HASHSIGN))
922 int spacePos = dataLine.indexOf(" ");
923 return (spacePos == -1 ? dataLine.substring(1) : dataLine
924 .substring(1, spacePos));
931 * Read the #MEGA and Title/Format/Description header lines (if present).
933 * Save as alignment properties in case useful.
935 * @return the next non-blank line following the header lines.
936 * @throws IOException
938 protected String parseHeaderLines() throws IOException
940 String inputLine = null;
941 while ((inputLine = nextNonCommentLine()) != null)
943 inputLine = inputLine.trim();
948 if (inputLine.length() == 0)
953 if (inputLine.toUpperCase().startsWith(MEGA_ID))
958 if (isTitle(inputLine))
960 this.title = getValue(inputLine);
961 setAlignmentProperty(PROP_TITLE, title);
963 else if (inputLine.startsWith(BANG + DESCRIPTION))
965 parseDescription(inputLine);
968 else if (inputLine.startsWith(BANG + FORMAT))
970 parseFormat(inputLine);
972 else if (!inputLine.toUpperCase().startsWith(MEGA_ID))
976 * Return the first 'data line' i.e. one that is not blank, #MEGA or
986 * Parse a !Format statement. This may be multiline, and is ended by a
990 * @throws IOException
992 protected void parseFormat(String inputLine) throws IOException
994 while (inputLine != null)
996 parseFormatLine(inputLine);
997 if (inputLine.endsWith(SEMICOLON))
1001 inputLine = nextNonCommentLine();
1006 * Parse one line of a !Format statement. This may contain one or more
1007 * keyword=value pairs.
1010 * @throws FileFormatException
1012 protected void parseFormatLine(String inputLine)
1013 throws FileFormatException
1015 if (inputLine.startsWith(BANG + FORMAT))
1017 inputLine = inputLine.substring((BANG + FORMAT).length());
1019 if (inputLine.endsWith(SEMICOLON))
1021 inputLine = inputLine.substring(0, inputLine.length() - 1);
1023 if (inputLine.length() == 0)
1027 String[] tokens = inputLine.trim().split(WHITESPACE);
1028 for (String token : tokens)
1030 parseFormatKeyword(token);
1035 * Parse a Keyword=Value token. Possible keywords are
1037 * <li>DataType= DNA, RNA, Nucleotide, Protein</li>
1038 * <li>DataFormat= Interleaved, ?</li>
1039 * <li>NSeqs= number of sequences (synonym NTaxa)</li>
1040 * <li>NSites= number of bases / residues</li>
1041 * <li>Property= Exon (or Coding), Intron (or Noncoding), End (of domain)</li>
1042 * <li>Indel= gap character</li>
1043 * <li>Identical= identity character (to first sequence) (synonym MatchChar)</li>
1044 * <li>Missing= missing data character</li>
1045 * <li>CodeTable= Standard, other (MEGA supports various)</li>
1049 * @throws FileFormatException
1050 * if an unrecognised keyword or value is encountered
1052 protected void parseFormatKeyword(String token)
1053 throws FileFormatException
1055 String msg = "Unrecognised Format command: " + token;
1056 String[] bits = token.split(EQUALS);
1057 if (bits.length != 2)
1059 throw new FileFormatException(msg);
1061 String keyword = bits[0];
1062 String value = bits[1];
1065 * Jalview will work out whether nucleotide or not anyway
1067 if (keyword.equalsIgnoreCase(DATATYPE))
1069 if (value.equalsIgnoreCase("DNA") || value.equalsIgnoreCase("RNA")
1070 || value.equalsIgnoreCase("Nucleotide"))
1072 this.nucleotide = true;
1073 // alignment computes whether or not it is nucleotide when created
1075 else if (value.equalsIgnoreCase(PROTEIN))
1077 this.nucleotide = false;
1081 throw new FileFormatException(msg);
1083 setAlignmentProperty(PROP_DATATYPE, value);
1087 * accept non-Standard code table but save in case we want to disable
1088 * 'translate as cDNA'
1090 else if (keyword.equalsIgnoreCase(CODETABLE))
1092 setAlignmentProperty(PROP_CODETABLE, value);
1096 * save gap char to set later on alignment once created
1098 else if (keyword.equalsIgnoreCase(INDEL))
1100 this.gapCharacter = value.charAt(0);
1103 else if (keyword.equalsIgnoreCase(IDENTICAL)
1104 || keyword.equalsIgnoreCase("MatchChar"))
1106 setAlignmentProperty(PROP_IDENTITY, value);
1107 this.identityCharacter = value.charAt(0);
1108 if (!".".equals(value))
1110 System.err.println("Warning: " + token
1111 + " not supported, Jalview uses '.' for identity");
1115 else if (keyword.equalsIgnoreCase(MISSING))
1117 setAlignmentProperty(PROP_MISSING, value);
1118 System.err.println("Warning: " + token + " not supported");
1121 else if (keyword.equalsIgnoreCase(PROPERTY))
1123 // TODO: can Property appear in a Format command?
1124 // suspect this is a mistake in the manual
1127 else if (!keyword.equalsIgnoreCase(N_SEQS)
1128 && !keyword.equalsIgnoreCase("NTaxa")
1129 && !keyword.equalsIgnoreCase(N_SITES))
1131 System.err.println("Warning: " + msg);
1136 * Returns the trimmed data on the line following either whitespace or '=',
1137 * with any trailing semi-colon removed<br>
1140 * <li>Hello World</li>
1141 * <li>!Hello: \tWorld;</li>
1142 * <li>!Hello=World</li>
1144 * should all return "World"
1149 protected static String getValue(String inputLine)
1151 if (inputLine == null)
1155 String value = null;
1156 String s = inputLine.replaceAll("\t", " ").trim();
1159 * KEYWORD = VALUE should return VALUE
1161 int equalsPos = s.indexOf("=");
1164 value = s.substring(equalsPos + 1);
1168 int spacePos = s.indexOf(' ');
1169 value = spacePos == -1 ? "" : s.substring(spacePos + 1);
1171 value = value.trim();
1172 if (value.endsWith(SEMICOLON))
1174 value = value.substring(0, value.length() - 1).trim();
1180 * Returns true if the input line starts with "TITLE" or "!TITLE" (not case
1181 * sensitive). The latter is the official format, some older data file
1182 * examples have it without the !.
1187 protected static boolean isTitle(String inputLine)
1189 if (inputLine == null)
1193 String upper = inputLine.toUpperCase();
1194 return (upper.startsWith(TITLE.toUpperCase()) || upper.startsWith(BANG
1195 + TITLE.toUpperCase()));
1199 * Reads lines until terminated by semicolon, appending each to the
1200 * Description property value.
1202 * @throws IOException
1204 protected void parseDescription(String firstDescriptionLine)
1207 StringBuilder desc = new StringBuilder(256);
1208 desc.append(getValue(firstDescriptionLine));
1209 if (!firstDescriptionLine.endsWith(SEMICOLON))
1211 String line = nextNonCommentLine();
1212 while (line != null)
1214 if (line.endsWith(SEMICOLON))
1216 desc.append(line.substring(0, line.length() - 1));
1219 else if (line.length() > 0)
1221 desc.append(line).append(newline);
1223 line = nextNonCommentLine();
1226 setAlignmentProperty(PROP_DESCRIPTION, desc.toString());
1230 * Returns the alignment sequences in Mega format.
1233 public String print()
1235 return MEGA_ID + newline + print(getSeqsAsArray());
1239 * Write out the alignment sequences in Mega format - interleaved unless
1240 * explicitly noninterleaved.
1242 protected String print(SequenceI[] s)
1245 if (this.interleaved != null && !this.interleaved)
1247 result = printNonInterleaved(s);
1251 result = printInterleaved(s);
1257 * Print to string in Interleaved format - blocks of next N characters of each
1262 protected String printInterleaved(SequenceI[] s)
1264 int maxIdLength = getMaxIdLength(s);
1265 int maxSequenceLength = getMaxSequenceLength(s);
1266 int numLines = maxSequenceLength / positionsPerLine + 3; // approx
1268 int numDataBlocks = (maxSequenceLength - 1) / positionsPerLine + 1;
1269 int spaceEvery = this.nucleotide != null && this.nucleotide ? 3 : 10;
1270 int chunksPerLine = (positionsPerLine + spaceEvery - 1) / spaceEvery;
1273 * Roughly size a buffer to hold the whole output
1275 StringBuilder sb = new StringBuilder(numLines
1276 * (maxIdLength + positionsPerLine + chunksPerLine + 10));
1279 * Output as: #Seqid CGT AGC ACT ... or blocks of 10 for peptide
1282 for (int i = 0; i < numDataBlocks; i++)
1285 boolean first = true;
1287 for (SequenceI seq : s)
1290 String seqId = String.format("#%-" + maxIdLength + "s",
1294 * output next line for this sequence
1297 int lastPos = seqFrom + positionsPerLine; // exclusive
1298 for (int j = 0; j < chunksPerLine; j++)
1300 char[] subSequence = seq.getSequence(seqFrom,
1301 Math.min(lastPos, seqFrom + spaceEvery));
1302 if (subSequence.length > 0)
1304 sb.append(SPACE).append(subSequence);
1306 seqFrom += subSequence.length;
1309 // all sequences should be the same length in MEGA
1310 advancedBy += subSequence.length;
1313 // write last position as a comment
1314 if (writePositionNumbers)
1316 sb.append(SPACE).append(COMMENT_START).append(from + advancedBy)
1317 .append(COMMENT_END);
1325 return new String(sb);
1329 * Outputs to string the MEGA header and any other known and relevant
1330 * alignment properties
1334 protected String printHeaders(AlignmentI al)
1336 StringBuilder sb = new StringBuilder(128);
1337 sb.append(MEGA_ID).append(newline);
1338 String propertyValue = (String) al.getProperty(PROP_TITLE);
1339 if (propertyValue != null)
1341 sb.append(BANG).append(TITLE).append(SPACE).append(propertyValue)
1342 .append(SEMICOLON).append(newline);
1344 propertyValue = (String) al.getProperty(PROP_DESCRIPTION);
1345 if (propertyValue != null)
1347 sb.append(BANG).append(DESCRIPTION).append(newline)
1348 .append(propertyValue).append(SEMICOLON)
1353 * !Format DataType CodeTable
1355 sb.append(BANG).append(FORMAT).append(newline);
1356 String dataType = (String) al.getProperty(PROP_DATATYPE);
1357 if (dataType == null)
1359 dataType = al.isNucleotide() ? NUCLEOTIDE : PROTEIN;
1361 sb.append(INDENT).append(DATATYPE).append(EQUALS).append(dataType);
1362 String codeTable = (String) al.getProperty(PROP_CODETABLE);
1363 sb.append(SPACE).append(CODETABLE).append(EQUALS)
1364 .append(codeTable == null ? "Standard" : codeTable)
1368 * !Format NSeqs NSites (the length of sequences - they should all be the
1369 * same - including gaps)
1371 sb.append(INDENT).append(N_SEQS).append(EQUALS).append(al.getHeight());
1372 sb.append(SPACE).append(N_SITES).append(EQUALS)
1373 .append(String.valueOf(al.getWidth()));
1377 * !Format Indel Identical Missing
1380 sb.append(INDEL).append(EQUALS).append(al.getGapCharacter());
1381 String identity = (String) al.getProperty(PROP_IDENTITY);
1382 if (identity != null)
1384 sb.append(SPACE).append(IDENTICAL).append(EQUALS).append(identity);
1386 String missing = (String) al.getProperty(PROP_MISSING);
1387 if (missing != null)
1389 sb.append(SPACE).append(MISSING).append(EQUALS).append(missing);
1391 sb.append(SEMICOLON).append(newline);
1393 return sb.toString();
1397 * Get the longest sequence id (to allow aligned printout).
1402 protected static int getMaxIdLength(SequenceI[] s)
1404 // TODO pull up for reuse
1406 for (SequenceI seq : s)
1408 int len = seq.getName().length();
1409 if (len > maxLength)
1418 * Get the longest sequence length
1423 protected static int getMaxSequenceLength(SequenceI[] s)
1425 // TODO pull up for reuse
1427 for (SequenceI seq : s)
1429 int len = seq.getLength();
1430 if (len > maxLength)
1439 * Print to string in noninterleaved format - all of each sequence in turn, in
1440 * blocks of 50 characters.
1445 protected String printNonInterleaved(SequenceI[] s)
1447 int maxSequenceLength = getMaxSequenceLength(s);
1449 int numLines = maxSequenceLength / positionsPerLine + 2 + s.length;
1452 * Roughly size a buffer to hold the whole output
1454 StringBuilder sb = new StringBuilder(numLines * positionsPerLine);
1456 int spaceEvery = this.nucleotide != null && this.nucleotide ? 3 : 10;
1457 int chunksPerLine = positionsPerLine / spaceEvery;
1458 for (SequenceI seq : s)
1461 sb.append(HASHSIGN + seq.getName()).append(newline);
1463 while (startPos < seq.getLength())
1465 boolean firstChunk = true;
1467 * print next line for this sequence
1469 int lastPos = startPos + positionsPerLine; // exclusive
1470 for (int j = 0; j < chunksPerLine; j++)
1472 char[] subSequence = seq.getSequence(startPos,
1473 Math.min(lastPos, startPos + positionsPerLine));
1474 if (subSequence.length > 0)
1480 sb.append(subSequence);
1483 startPos += subSequence.length;
1489 return new String(sb);
1493 * Flag this file as interleaved or not, based on data format. Throws an
1494 * exception if has previously been determined to be otherwise.
1498 * @throws IOException
1500 protected void assertInterleaved(boolean isIt, String dataLine)
1501 throws FileFormatException
1503 if (this.interleaved != null && isIt != this.interleaved.booleanValue())
1505 throw new FileFormatException("Parse error: interleaved was " + !isIt
1506 + " but now seems to be " + isIt + ", at line: " + dataLine);
1508 this.interleaved = new Boolean(isIt);
1509 setAlignmentProperty(PROP_INTERLEAVED, interleaved.toString());
1512 public boolean isInterleaved()
1514 return this.interleaved == null ? false : this.interleaved
1519 * Adds saved parsed values either as alignment properties, or (in some cases)
1520 * as specific member fields of the alignment
1523 public void addProperties(AlignmentI al)
1525 super.addProperties(al);
1526 al.setGapCharacter(gapCharacter);
1529 * warn if e.g. DataType=DNA but data is protein (or vice versa)
1531 if (this.nucleotide != null && this.nucleotide != al.isNucleotide()) {
1532 System.err.println("Warning: " + this.title + " declared "
1533 + (nucleotide ? "" : " not ") + "nucleotide but it is"
1534 + (nucleotide ? " not" : ""));
1539 * Print the given alignment in MEGA format. If the alignment was created by
1540 * parsing a MEGA file, it should have properties set (e.g. Title) which can
1541 * influence the output.
1544 public String print(AlignmentI al)
1546 this.nucleotide = al.isNucleotide();
1548 String lineLength = (String) al.getProperty(PROP_LINELENGTH);
1549 this.positionsPerLine = lineLength == null ? DEFAULT_LINE_LENGTH : Integer
1550 .parseInt(lineLength);
1553 * round down to a multiple of 3 positions per line for nucleotide
1557 positionsPerLine = positionsPerLine - (positionsPerLine % 3);
1560 String interleave = (String) al.getProperty(PROP_INTERLEAVED);
1561 if (interleave != null)
1563 this.interleaved = Boolean.valueOf(interleave);
1566 String headers = printHeaders(al);
1567 return headers + print(al.getSequencesArray());
1571 * Returns the number of sequence positions output per line
1575 public int getPositionsPerLine()
1577 return positionsPerLine;
1581 * Sets the number of sequence positions output per line. Note these will be
1582 * formatted in blocks of 3 (nucleotide) or 10 (peptide).
1586 public void setPositionsPerLine(int p)
1588 this.positionsPerLine = p;