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";
109 * names of properties to save to the alignment (may affect eventual output
112 static final String PROP_TITLE = "MEGA_TITLE";
114 static final String PROP_INTERLEAVED = "MEGA_INTERLEAVED";
116 static final String PROP_DESCRIPTION = "MEGA_DESCRIPTION";
118 static final String PROP_CODETABLE = "MEGA_CODETABLE";
120 static final String PROP_IDENTITY = "MEGA_IDENTITY";
122 static final String PROP_MISSING = "MEGA_MISSING";
124 static final String PROP_DATATYPE = "MEGA_DATATYPE";
126 // number of bases per line of file (value is inferred)
127 static final String PROP_LINELENGTH = "MEGA_LINELENGTH";
129 // TODO: need a controlled name for Gene as a feature if we want to be able to
130 // output the MEGA file with !Gene headers
131 // WTF do we do if the sequences get realigned?
133 // initial size for sequence data buffer
134 private static final int SEQBUFFERSIZE = 256;
136 private static final String SPACE = " ";
139 * number of sequence positions output per line
141 private int positionsPerLine;
143 private String title;
145 // gap character may be explicitly declared, default is -
146 private char gapCharacter = '-';
148 // identity character if declared
149 private char identityCharacter = 0;
151 // this can be True, False or null (meaning not asserted in file)
152 private Boolean nucleotide;
154 // set once we have seen one block of interleaved data
155 private boolean firstDataBlockRead = false;
157 // this can be True, False or null (meaning we don't know yet)
158 private Boolean interleaved;
160 // write end of line positions as a comment
161 private boolean writePositionNumbers = true;
163 // id of sequence being processed
164 private String currentSequenceId;
167 * Temporary store of {sequenceId, positionData} while parsing interleaved
168 * sequences; sequences are maintained in the order in which they are added
169 * i.e. read in the file
171 Map<String, StringBuilder> seqData;
173 // number of residues read (so far) per sequence
174 Map<String, Integer> residuesRead;
176 // current Gene if any we are parsing
177 private String currentGene;
179 // start residue (base 1) per sequence of current gene
180 Map<String, Integer> geneStart;
182 // current Domain if any we are parsing
183 private String currentDomain;
185 // start residue (base 1) per sequence of current domain
186 Map<String, Integer> domainStart;
188 // map of SequenceFeature's by sequence id
189 Map<String, List<SequenceFeature>> sequenceFeatures;
195 public MegaFile(String inFile, String type) throws IOException
200 public MegaFile(FileParse source) throws IOException
206 * Parse the input stream.
209 public void parse() throws IOException
212 sequenceFeatures = new HashMap<String, List<SequenceFeature>>();
213 geneStart = new HashMap<String, Integer>();
214 domainStart = new HashMap<String, Integer>();
215 residuesRead = new HashMap<String, Integer>();
218 * Read and process MEGA and Title/Format/Description headers if present.
219 * Returns the first data line following the headers.
221 String dataLine = parseHeaderLines();
224 * order-preserving map to hold sequences by id as they are built up during
227 seqData = new LinkedHashMap<String, StringBuilder>();
230 * The id of the sequence being read (for non-interleaved)
232 currentSequenceId = "";
234 while (dataLine != null)
236 dataLine = dataLine.trim();
237 if (dataLine.length() > 0)
239 if (dataLine.startsWith(BANG + GENE)
240 || dataLine.startsWith(BANG + DOMAIN))
242 parseGeneOrDomain(dataLine);
246 currentSequenceId = parseDataLine(dataLine);
249 else if (!seqData.isEmpty())
252 * Blank line after processing some data...
256 dataLine = nextNonCommentLine();
260 * close off any features currently being parsed
262 createFeature(GENE, currentGene, geneStart);
263 createFeature(DOMAIN, currentDomain, domainStart);
265 // remember the (longest) line length read in, so we can output the same
266 setAlignmentProperty(PROP_LINELENGTH, String.valueOf(positionsPerLine));
272 * Post-processing after reading one block of interleaved data
274 protected void endOfDataBlock()
276 this.firstDataBlockRead = true;
278 // (initialise and) populate arrays of sequence length so far (excluding
280 // On change or end of a denoted Gene or Domain, add sequence features for
285 * Parse a !Gene or !Domain command line. MEGA accepts
287 * <li>!Gene=name;</li>
288 * <li>!Gene=name Property=Coding/Noncoding CodonStart=1/2/3;</li>
289 * <li>!Gene=genename Domain=domainname Property= etc</li>
290 * <li>!Domain=domainname Gene=genename Property= etc</li>
291 * <li>!Domain=domainname Property= etc</li>
292 * <li>!domain=domainname property=domainend</li>
294 * Properly, a Gene should be composed of Domain segments, but MEGA accepts
295 * without. Note that keywords don't seem to be case sensitive.
298 * @throws FileFormatException
300 protected void parseGeneOrDomain(String dataLine)
301 throws FileFormatException
303 String domain = null;
305 String property = null;
306 String codonStart = null;
307 String errorMsg = "Unrecognized format: " + dataLine;
309 if (!dataLine.startsWith(BANG) || !dataLine.endsWith(SEMICOLON))
311 throw new FileFormatException(errorMsg);
313 String trimmed = dataLine.substring(1, dataLine.length() - 1).trim();
314 String[] tokens = trimmed.split(WHITESPACE);
315 for (String token : tokens)
317 String[] keyValue = token.split("=");
318 if (keyValue.length != 2)
320 throw new FileFormatException(errorMsg);
322 String key = keyValue[0];
323 if (GENE.equalsIgnoreCase(key))
327 else if (DOMAIN.equalsIgnoreCase(key))
329 domain = keyValue[1];
331 else if (PROPERTY.equalsIgnoreCase(key))
333 property = keyValue[1];
335 else if (CODONSTART.equalsIgnoreCase(key))
337 codonStart = keyValue[1];
341 System.err.println("Unrecognised token: '" + key + "; in "
346 processGeneOrDomain(gene, domain, property, codonStart);
350 * Process a statement containing one or both of Gene and Domain, and
351 * optionally Property or CodonStart commands.
354 * the Gene name if specified, else null
356 * the Domain name if specified, else null
358 * the Property value if specified, else null
360 * the CodonStart value if specified, else null
362 protected void processGeneOrDomain(String gene, String domain,
363 String property, String codonStart)
366 * If we have been processing a Gene or Domain, and this does not continue
367 * it, then close it off (generate sequence features for it)
369 if (this.currentGene != null && !this.currentGene.equals(gene))
371 createFeature(GENE, currentGene, geneStart);
373 if (this.currentDomain != null)
375 if (!this.currentDomain.equals(domain)
376 || "domainend".equalsIgnoreCase(property))
378 createFeature(DOMAIN, currentDomain, domainStart);
383 * and if we have declared a Gene or Domain which does not continue the
384 * current one, then record its start positions per sequence
386 if (gene != null && !gene.equals(currentGene))
388 startSequenceFeature(geneStart);
390 if (domain != null && !domain.equals(currentDomain))
392 startSequenceFeature(domainStart);
396 currentDomain = domain;
400 * Start processing a new feature
402 * @param startPositions
404 protected void startSequenceFeature(Map<String, Integer> startPositions)
407 * If the feature declaration precedes all sequences, we will know in
408 * createFeature that it started with residue 1; otherwise note now where it
409 * starts in each sequence
411 if (!residuesRead.isEmpty())
413 for (Entry<String, Integer> entry : residuesRead.entrySet())
415 String seqId = entry.getKey();
416 Integer nextResidue = entry.getValue() + 1;
417 startPositions.put(seqId, nextResidue);
423 * Add a SequenceFeature to each sequence, using the given start/end values
427 * @param featureValue
428 * @param featureStartResidues
430 protected void createFeature(String featureType, String featureValue,
431 Map<String, Integer> featureStartResidues)
433 if (featureValue == null)
438 Iterator<String> seqids = this.seqData.keySet().iterator();
439 while (seqids.hasNext())
441 String seqid = seqids.next();
442 Integer startAt = featureStartResidues.get(seqid);
443 int sfstart = startAt == null ? 1 : startAt.intValue();
444 int sfend = residuesRead.get(seqid);
445 if (sfend >= sfstart)
448 * don't add feature if entirely gapped in the sequence
450 // TODO: type="Gene" (but then all coloured the same) or
452 SequenceFeature sf = new SequenceFeature(featureValue, featureType,
453 sfstart, sfend, 0f, null);
454 sequenceFeatures.get(seqid).add(sf);
460 * Returns the next line that is not a comment, or null at end of file.
461 * Comments in MEGA are within [ ] brackets, and may be nested.
464 * @throws IOException
466 protected String nextNonCommentLine() throws IOException
468 return nextNonCommentLine(0);
472 * Returns the next non-comment line (or part line), or null at end of file.
473 * Comments in MEGA are within [ ] brackets, and may be nested. They may occur
474 * anywhere within a line (for example at the end with position numbers); this
475 * method returns the line with any comments removed.
478 * current depth of nesting of comments while parsing
480 * @throws IOException
482 protected String nextNonCommentLine(final int depth) throws IOException
490 System.err.println("Warning: unterminated comment in data file");
496 * If we are in a (possibly nested) comment after parsing this line, keep
497 * reading recursively until the comment has unwound
499 int newDepth = commentDepth(data, depth);
502 return nextNonCommentLine(newDepth);
507 * not in a comment by end of this line; return what is left
509 String nonCommentPart = getNonCommentContent(data, depth);
510 return nonCommentPart;
515 * Returns what is left of the input data after removing any comments, whether
516 * 'in progress' from preceding lines, or embedded in the current line
521 * nested depth of comments pending termination
523 * @throws FileFormatException
525 protected static String getNonCommentContent(String data, int depth)
526 throws FileFormatException
528 int len = data.length();
529 StringBuilder result = new StringBuilder(len);
530 for (int i = 0; i < len; i++)
532 char c = data.charAt(i);
557 return result.toString();
561 * Calculates new depth of comment after parsing an input line i.e. the excess
562 * of opening '[' over closing ']' characters. Any excess ']' are ignored (not
563 * treated as comment delimiters).
568 * current comment nested depth before parsing the line
569 * @return new depth after parsing the line
571 protected static int commentDepth(CharSequence data, int depth)
573 int newDepth = depth;
574 int len = data.length();
575 for (int i = 0; i < len; i++)
577 char c = data.charAt(i);
578 if (c == COMMENT_START)
582 else if (c == COMMENT_END && newDepth > 0)
591 * Convert the parsed sequence strings to objects and store them in the model.
593 protected void deriveSequences()
595 Set<Entry<String, StringBuilder>> datasets = seqData.entrySet();
597 for (Entry<String, StringBuilder> dataset : datasets)
599 String sequenceId = dataset.getKey();
600 StringBuilder characters = dataset.getValue();
601 SequenceI s = new Sequence(sequenceId, new String(characters));
602 this.seqs.addElement(s);
605 * and add any derived sequence features to the sequence
607 for (SequenceFeature sf : sequenceFeatures.get(sequenceId))
609 s.addSequenceFeature(sf);
615 * Process one line of sequence data. If it has no sequence identifier, append
616 * to the current id's sequence. Else parse out the sequence id and append the
617 * data (if any) to that id's sequence. Returns the sequence id (implicit or
618 * explicit) for this line.
622 * @throws IOException
624 protected String parseDataLine(String dataLine)
627 String seqId = getSequenceId(dataLine);
631 * Just character data
633 parseNoninterleavedDataLine(dataLine);
634 return currentSequenceId;
636 else if ((HASHSIGN + seqId).trim().equals(dataLine.trim()))
639 * Sequence id only - header line for noninterleaved data
646 * Sequence id followed by data
648 parseInterleavedDataLine(dataLine, seqId);
654 * Add a line of sequence data to the buffer for the given sequence id. Start
655 * a new one if we haven't seen it before.
658 * @throws IOException
660 protected void parseNoninterleavedDataLine(String dataLine)
663 if (currentSequenceId == null)
666 * Oops. Data but no sequence id context.
668 throw new IOException("No sequence id context at: " + dataLine);
671 assertInterleaved(false, dataLine);
673 dataLine = addSequenceData(currentSequenceId, dataLine);
675 setPositionsPerLine(Math.max(positionsPerLine, dataLine.length()));
679 * Get the sequence data for this sequence id, starting a new one if
685 protected StringBuilder getSequenceDataBuffer(String currentId)
687 StringBuilder sb = seqData.get(currentId);
690 // first data met for this sequence id, start a new buffer
691 sb = new StringBuilder(SEQBUFFERSIZE);
692 seqData.put(currentId, sb);
694 // and a placeholder for any SequenceFeature found
695 sequenceFeatures.put(currentId, new ArrayList<SequenceFeature>());
701 * Parse one line of interleaved data e.g.
704 * #TheSeqId CGATCGCATGCA
709 * @throws FileFormatException
711 protected void parseInterleavedDataLine(String dataLine, String seqId)
712 throws FileFormatException
715 * New sequence found in second or later data block - error.
717 if (this.firstDataBlockRead && !seqData.containsKey(seqId))
719 throw new FileFormatException(
720 "Parse error: misplaced new sequence starting at " + dataLine);
723 String data = dataLine.substring(seqId.length() + 1).trim();
726 * Do nothing if this line is _only_ a sequence id with no data following.
728 if (data != null && data.length() > 0)
730 data = addSequenceData(seqId, data);
731 setPositionsPerLine(Math.max(positionsPerLine, data.length()));
732 assertInterleaved(true, dataLine);
737 * Remove spaces, and replace identity symbol, before appending the sequence
738 * data to the buffer for the sequence id. Returns the reformatted added data.
739 * Also updates a count of residues read for the sequence.
745 protected String addSequenceData(String seqId, String data)
747 StringBuilder sb = getSequenceDataBuffer(seqId);
748 int len = sb.length();
749 String formatted = data.replace(SPACE, "");
752 * If sequence contains '.' or other identity symbol; replace these with the
753 * same position from the first (reference) sequence
756 StringBuilder referenceSequence = seqData.values().iterator().next();
757 StringBuilder sb1 = new StringBuilder(formatted.length());
758 for (int i = 0; i < formatted.length(); i++)
760 char nextChar = formatted.charAt(i);
761 if (nextChar != gapCharacter)
765 if (nextChar == identityCharacter
766 && len + i < referenceSequence.length())
768 sb1.append(referenceSequence.charAt(len + i));
772 sb1.append(nextChar);
775 formatted = sb1.toString();
781 * increment residue count for the sequence
785 Integer residueCount = residuesRead.get(seqId);
786 residuesRead.put(seqId, nonGapped
787 + (residueCount == null ? 0 : residueCount));
794 * If the line begins with (e.g.) "#abcde " then returns "abcde" as the
795 * identifier. Else returns null.
800 public static String getSequenceId(String dataLine)
802 // TODO refactor to a StringUtils type class
803 if (dataLine != null)
805 if (dataLine.startsWith(HASHSIGN))
807 int spacePos = dataLine.indexOf(" ");
808 return (spacePos == -1 ? dataLine.substring(1) : dataLine
809 .substring(1, spacePos));
816 * Read the #MEGA and Title/Format/Description header lines (if present).
818 * Save as alignment properties in case useful.
820 * @return the next non-blank line following the header lines.
821 * @throws IOException
823 protected String parseHeaderLines() throws IOException
825 String inputLine = null;
826 while ((inputLine = nextNonCommentLine()) != null)
828 inputLine = inputLine.trim();
833 if (inputLine.length() == 0)
838 if (inputLine.toUpperCase().startsWith(MEGA_ID))
843 if (isTitle(inputLine))
845 this.title = getValue(inputLine);
846 setAlignmentProperty(PROP_TITLE, title);
848 else if (inputLine.startsWith(BANG + DESCRIPTION))
850 parseDescription(inputLine);
853 else if (inputLine.startsWith(BANG + FORMAT))
855 parseFormat(inputLine);
857 else if (!inputLine.toUpperCase().startsWith(MEGA_ID))
861 * Return the first 'data line' i.e. one that is not blank, #MEGA or
871 * Parse a !Format statement. This may be multiline, and is ended by a
875 * @throws IOException
877 protected void parseFormat(String inputLine) throws IOException
879 while (inputLine != null)
881 parseFormatLine(inputLine);
882 if (inputLine.endsWith(SEMICOLON))
886 inputLine = nextNonCommentLine();
891 * Parse one line of a !Format statement. This may contain one or more
892 * keyword=value pairs.
895 * @throws FileFormatException
897 protected void parseFormatLine(String inputLine)
898 throws FileFormatException
900 if (inputLine.startsWith(BANG + FORMAT))
902 inputLine = inputLine.substring((BANG + FORMAT).length());
904 if (inputLine.endsWith(SEMICOLON))
906 inputLine = inputLine.substring(0, inputLine.length() - 1);
908 if (inputLine.length() == 0)
912 String[] tokens = inputLine.trim().split(WHITESPACE);
913 for (String token : tokens)
915 parseFormatKeyword(token);
920 * Parse a Keyword=Value token. Possible keywords are
922 * <li>DataType= DNA, RNA, Nucleotide, Protein</li>
923 * <li>DataFormat= Interleaved, ?</li>
924 * <li>NSeqs= number of sequences (synonym NTaxa)</li>
925 * <li>NSites= number of bases / residues</li>
926 * <li>Property= Exon (or Coding), Intron (or Noncoding), End (of domain)</li>
927 * <li>Indel= gap character</li>
928 * <li>Identical= identity character (to first sequence) (synonym MatchChar)</li>
929 * <li>Missing= missing data character</li>
930 * <li>CodeTable= Standard, other (MEGA supports various)</li>
934 * @throws FileFormatException
935 * if an unrecognised keyword or value is encountered
937 protected void parseFormatKeyword(String token)
938 throws FileFormatException
940 String msg = "Unrecognised Format command: " + token;
941 String[] bits = token.split(EQUALS);
942 if (bits.length != 2)
944 throw new FileFormatException(msg);
946 String keyword = bits[0];
947 String value = bits[1];
950 * Jalview will work out whether nucleotide or not anyway
952 if (keyword.equalsIgnoreCase(DATATYPE))
954 if (value.equalsIgnoreCase("DNA") || value.equalsIgnoreCase("RNA")
955 || value.equalsIgnoreCase("Nucleotide"))
957 this.nucleotide = true;
958 // alignment computes whether or not it is nucleotide when created
960 else if (value.equalsIgnoreCase(PROTEIN))
962 this.nucleotide = false;
966 throw new FileFormatException(msg);
968 setAlignmentProperty(PROP_DATATYPE, value);
972 * accept non-Standard code table but save in case we want to disable
973 * 'translate as cDNA'
975 else if (keyword.equalsIgnoreCase(CODETABLE))
977 setAlignmentProperty(PROP_CODETABLE, value);
981 * save gap char to set later on alignment once created
983 else if (keyword.equalsIgnoreCase(INDEL))
985 this.gapCharacter = value.charAt(0);
988 else if (keyword.equalsIgnoreCase(IDENTICAL)
989 || keyword.equalsIgnoreCase("MatchChar"))
991 setAlignmentProperty(PROP_IDENTITY, value);
992 this.identityCharacter = value.charAt(0);
993 if (!".".equals(value))
995 System.err.println("Warning: " + token
996 + " not supported, Jalview uses '.' for identity");
1000 else if (keyword.equalsIgnoreCase(MISSING))
1002 setAlignmentProperty(PROP_MISSING, value);
1003 System.err.println("Warning: " + token + " not supported");
1006 else if (keyword.equalsIgnoreCase(PROPERTY))
1008 // TODO: can Property appear in a Format command?
1009 // suspect this is a mistake in the manual
1012 else if (!keyword.equalsIgnoreCase(N_SEQS)
1013 && !keyword.equalsIgnoreCase("NTaxa")
1014 && !keyword.equalsIgnoreCase(N_SITES))
1016 System.err.println("Warning: " + msg);
1021 * Returns the trimmed data on the line following either whitespace or '=',
1022 * with any trailing semi-colon removed<br>
1025 * <li>Hello World</li>
1026 * <li>!Hello: \tWorld;</li>
1027 * <li>!Hello=World</li>
1029 * should all return "World"
1034 protected static String getValue(String inputLine)
1036 if (inputLine == null)
1040 String value = null;
1041 String s = inputLine.replaceAll("\t", " ").trim();
1044 * KEYWORD = VALUE should return VALUE
1046 int equalsPos = s.indexOf("=");
1049 value = s.substring(equalsPos + 1);
1053 int spacePos = s.indexOf(' ');
1054 value = spacePos == -1 ? "" : s.substring(spacePos + 1);
1056 value = value.trim();
1057 if (value.endsWith(SEMICOLON))
1059 value = value.substring(0, value.length() - 1).trim();
1065 * Returns true if the input line starts with "TITLE" or "!TITLE" (not case
1066 * sensitive). The latter is the official format, some older data file
1067 * examples have it without the !.
1072 protected static boolean isTitle(String inputLine)
1074 if (inputLine == null)
1078 String upper = inputLine.toUpperCase();
1079 return (upper.startsWith(TITLE.toUpperCase()) || upper.startsWith(BANG
1080 + TITLE.toUpperCase()));
1084 * Reads lines until terminated by semicolon, appending each to the
1085 * Description property value.
1087 * @throws IOException
1089 protected void parseDescription(String firstDescriptionLine)
1092 StringBuilder desc = new StringBuilder(256);
1093 desc.append(getValue(firstDescriptionLine));
1094 if (!firstDescriptionLine.endsWith(SEMICOLON))
1096 String line = nextNonCommentLine();
1097 while (line != null)
1099 if (line.endsWith(SEMICOLON))
1101 desc.append(line.substring(0, line.length() - 1));
1104 else if (line.length() > 0)
1106 desc.append(line).append(newline);
1108 line = nextNonCommentLine();
1111 setAlignmentProperty(PROP_DESCRIPTION, desc.toString());
1115 * Returns the alignment sequences in Mega format.
1118 public String print()
1120 return MEGA_ID + newline + print(getSeqsAsArray());
1124 * Write out the alignment sequences in Mega format - interleaved unless
1125 * explicitly noninterleaved.
1127 protected String print(SequenceI[] s)
1130 if (this.interleaved != null && !this.interleaved)
1132 result = printNonInterleaved(s);
1136 result = printInterleaved(s);
1142 * Print to string in Interleaved format - blocks of next N characters of each
1147 protected String printInterleaved(SequenceI[] s)
1149 int maxIdLength = getMaxIdLength(s);
1150 int maxSequenceLength = getMaxSequenceLength(s);
1151 int numLines = maxSequenceLength / positionsPerLine + 3; // approx
1153 int numDataBlocks = (maxSequenceLength - 1) / positionsPerLine + 1;
1154 int spaceEvery = this.nucleotide != null && this.nucleotide ? 3 : 10;
1155 int chunksPerLine = (positionsPerLine + spaceEvery - 1) / spaceEvery;
1158 * Roughly size a buffer to hold the whole output
1160 StringBuilder sb = new StringBuilder(numLines
1161 * (maxIdLength + positionsPerLine + chunksPerLine + 10));
1164 * Output as: #Seqid CGT AGC ACT ... or blocks of 10 for peptide
1167 for (int i = 0; i < numDataBlocks; i++)
1170 boolean first = true;
1172 for (SequenceI seq : s)
1175 String seqId = String.format("#%-" + maxIdLength + "s",
1179 * output next line for this sequence
1182 int lastPos = seqFrom + positionsPerLine; // exclusive
1183 for (int j = 0; j < chunksPerLine; j++)
1185 char[] subSequence = seq.getSequence(seqFrom,
1186 Math.min(lastPos, seqFrom + spaceEvery));
1187 if (subSequence.length > 0)
1189 sb.append(SPACE).append(subSequence);
1191 seqFrom += subSequence.length;
1194 // all sequences should be the same length in MEGA
1195 advancedBy += subSequence.length;
1198 // write last position as a comment
1199 if (writePositionNumbers)
1201 sb.append(SPACE).append(COMMENT_START).append(from + advancedBy)
1202 .append(COMMENT_END);
1210 return new String(sb);
1214 * Outputs to string the MEGA header and any other known and relevant
1215 * alignment properties
1219 protected String printHeaders(AlignmentI al)
1221 StringBuilder sb = new StringBuilder(128);
1222 sb.append(MEGA_ID).append(newline);
1223 String propertyValue = (String) al.getProperty(PROP_TITLE);
1224 if (propertyValue != null)
1226 sb.append(BANG).append(TITLE).append(SPACE).append(propertyValue)
1227 .append(SEMICOLON).append(newline);
1229 propertyValue = (String) al.getProperty(PROP_DESCRIPTION);
1230 if (propertyValue != null)
1232 sb.append(BANG).append(DESCRIPTION).append(newline)
1233 .append(propertyValue).append(SEMICOLON)
1238 * !Format DataType CodeTable
1240 sb.append(BANG).append(FORMAT).append(newline);
1241 String dataType = (String) al.getProperty(PROP_DATATYPE);
1242 if (dataType == null)
1244 dataType = al.isNucleotide() ? NUCLEOTIDE : PROTEIN;
1246 sb.append(INDENT).append(DATATYPE).append(EQUALS).append(dataType);
1247 String codeTable = (String) al.getProperty(PROP_CODETABLE);
1248 sb.append(SPACE).append(CODETABLE).append(EQUALS)
1249 .append(codeTable == null ? "Standard" : codeTable)
1253 * !Format NSeqs NSites (the length of sequences - they should all be the
1254 * same - including gaps)
1256 sb.append(INDENT).append(N_SEQS).append(EQUALS).append(al.getHeight());
1257 sb.append(SPACE).append(N_SITES).append(EQUALS)
1258 .append(String.valueOf(al.getWidth()));
1262 * !Format Indel Identical Missing
1265 sb.append(INDEL).append(EQUALS).append(al.getGapCharacter());
1266 String identity = (String) al.getProperty(PROP_IDENTITY);
1267 if (identity != null)
1269 sb.append(SPACE).append(IDENTICAL).append(EQUALS).append(identity);
1271 String missing = (String) al.getProperty(PROP_MISSING);
1272 if (missing != null)
1274 sb.append(SPACE).append(MISSING).append(EQUALS).append(missing);
1276 sb.append(SEMICOLON).append(newline);
1278 return sb.toString();
1282 * Get the longest sequence id (to allow aligned printout).
1287 protected static int getMaxIdLength(SequenceI[] s)
1289 // TODO pull up for reuse
1291 for (SequenceI seq : s)
1293 int len = seq.getName().length();
1294 if (len > maxLength)
1303 * Get the longest sequence length
1308 protected static int getMaxSequenceLength(SequenceI[] s)
1310 // TODO pull up for reuse
1312 for (SequenceI seq : s)
1314 int len = seq.getLength();
1315 if (len > maxLength)
1324 * Print to string in noninterleaved format - all of each sequence in turn, in
1325 * blocks of 50 characters.
1330 protected String printNonInterleaved(SequenceI[] s)
1332 int maxSequenceLength = getMaxSequenceLength(s);
1334 int numLines = maxSequenceLength / positionsPerLine + 2 + s.length;
1337 * Roughly size a buffer to hold the whole output
1339 StringBuilder sb = new StringBuilder(numLines * positionsPerLine);
1341 int spaceEvery = this.nucleotide != null && this.nucleotide ? 3 : 10;
1342 int chunksPerLine = positionsPerLine / spaceEvery;
1343 for (SequenceI seq : s)
1346 sb.append(HASHSIGN + seq.getName()).append(newline);
1348 while (startPos < seq.getLength())
1350 boolean firstChunk = true;
1352 * print next line for this sequence
1354 int lastPos = startPos + positionsPerLine; // exclusive
1355 for (int j = 0; j < chunksPerLine; j++)
1357 char[] subSequence = seq.getSequence(startPos,
1358 Math.min(lastPos, startPos + positionsPerLine));
1359 if (subSequence.length > 0)
1365 sb.append(subSequence);
1368 startPos += subSequence.length;
1374 return new String(sb);
1378 * Flag this file as interleaved or not, based on data format. Throws an
1379 * exception if has previously been determined to be otherwise.
1383 * @throws IOException
1385 protected void assertInterleaved(boolean isIt, String dataLine)
1386 throws FileFormatException
1388 if (this.interleaved != null && isIt != this.interleaved.booleanValue())
1390 throw new FileFormatException(
1391 "Parse error: mix of interleaved and noninterleaved detected, at line: "
1394 this.interleaved = new Boolean(isIt);
1395 setAlignmentProperty(PROP_INTERLEAVED, interleaved.toString());
1398 public boolean isInterleaved()
1400 return this.interleaved == null ? false : this.interleaved
1405 * Adds saved parsed values either as alignment properties, or (in some cases)
1406 * as specific member fields of the alignment
1409 public void addProperties(AlignmentI al)
1411 super.addProperties(al);
1412 al.setGapCharacter(gapCharacter);
1415 * warn if e.g. DataType=DNA but data is protein (or vice versa)
1417 if (this.nucleotide != null && this.nucleotide != al.isNucleotide()) {
1418 System.err.println("Warning: " + this.title + " declared "
1419 + (nucleotide ? "" : " not ") + "nucleotide but it is"
1420 + (nucleotide ? " not" : ""));
1425 * Print the given alignment in MEGA format. If the alignment was created by
1426 * parsing a MEGA file, it should have properties set (e.g. Title) which can
1427 * influence the output.
1430 public String print(AlignmentI al)
1432 this.nucleotide = al.isNucleotide();
1434 String lineLength = (String) al.getProperty(PROP_LINELENGTH);
1435 this.positionsPerLine = lineLength == null ? DEFAULT_LINE_LENGTH : Integer
1436 .parseInt(lineLength);
1439 * round down to a multiple of 3 positions per line for nucleotide
1443 positionsPerLine = positionsPerLine - (positionsPerLine % 3);
1446 String interleave = (String) al.getProperty(PROP_INTERLEAVED);
1447 if (interleave != null)
1449 this.interleaved = Boolean.valueOf(interleave);
1452 String headers = printHeaders(al);
1453 return headers + print(al.getSequencesArray());
1457 * Returns the number of sequence positions output per line
1461 public int getPositionsPerLine()
1463 return positionsPerLine;
1467 * Sets the number of sequence positions output per line. Note these will be
1468 * formatted in blocks of 3 (nucleotide) or 10 (peptide).
1472 public void setPositionsPerLine(int p)
1474 this.positionsPerLine = p;