2 * Jalview - A Sequence Alignment Editor and Viewer
3 * Copyright (C) 2007 AM Waterhouse, J Procter, G Barton, M Clamp, S Searle
5 * This program is free software; you can redistribute it and/or
6 * modify it under the terms of the GNU General Public License
7 * as published by the Free Software Foundation; either version 2
8 * of the License, or (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License
16 * along with this program; if not, write to the Free Software
17 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
22 // http://evolution.genetics.washington.edu/phylip/newick_doc.html
23 // TODO: Implement Basic NHX tag parsing and preservation
24 // TODO: http://evolution.genetics.wustl.edu/eddy/forester/NHX.html
25 // TODO: Extended SequenceNodeI to hold parsed NHX strings
30 import jalview.datamodel.*;
33 * Parse a new hanpshire style tree
34 * Caveats: NHX files are NOT supported and the tree distances and topology are unreliable when they are parsed.
38 public class NewickFile
42 private boolean HasBootstrap = false;
43 private boolean HasDistances = false;
44 private boolean RootHasDistance = false;
47 boolean ReplaceUnderscores = false;
48 boolean printRootInfo = false;
49 private com.stevesoft.pat.Regex[] NodeSafeName = new com.stevesoft.pat.Regex[]
51 new com.stevesoft.pat.Regex().perlCode("m/[\\[,:'()]/"), // test for requiring quotes
52 new com.stevesoft.pat.Regex().perlCode("s/'/''/"), // escaping quote characters
53 new com.stevesoft.pat.Regex().perlCode("s/\\/w/_/") // unqoted whitespace transformation
55 char QuoteChar = '\'';
58 * Creates a new NewickFile object.
60 * @param inStr DOCUMENT ME!
62 * @throws IOException DOCUMENT ME!
64 public NewickFile(String inStr)
67 super(inStr, "Paste");
71 * Creates a new NewickFile object.
73 * @param inFile DOCUMENT ME!
74 * @param type DOCUMENT ME!
76 * @throws IOException DOCUMENT ME!
78 public NewickFile(String inFile, String type)
85 * Creates a new NewickFile object.
87 * @param newtree DOCUMENT ME!
89 public NewickFile(SequenceNode newtree)
95 * Creates a new NewickFile object.
97 * @param newtree DOCUMENT ME!
98 * @param bootstrap DOCUMENT ME!
100 public NewickFile(SequenceNode newtree, boolean bootstrap)
102 HasBootstrap = bootstrap;
107 * Creates a new NewickFile object.
109 * @param newtree DOCUMENT ME!
110 * @param bootstrap DOCUMENT ME!
111 * @param distances DOCUMENT ME!
113 public NewickFile(SequenceNode newtree, boolean bootstrap, boolean distances)
116 HasBootstrap = bootstrap;
117 HasDistances = distances;
121 * Creates a new NewickFile object.
123 * @param newtree DOCUMENT ME!
124 * @param bootstrap DOCUMENT ME!
125 * @param distances DOCUMENT ME!
126 * @param rootdistance DOCUMENT ME!
128 public NewickFile(SequenceNode newtree, boolean bootstrap,
129 boolean distances, boolean rootdistance)
132 HasBootstrap = bootstrap;
133 HasDistances = distances;
134 RootHasDistance = rootdistance;
140 * @param Error DOCUMENT ME!
141 * @param Er DOCUMENT ME!
142 * @param r DOCUMENT ME!
143 * @param p DOCUMENT ME!
144 * @param s DOCUMENT ME!
146 * @return DOCUMENT ME!
148 private String ErrorStringrange(String Error, String Er, int r, int p,
151 return ( (Error == null) ? "" : Error) + Er + " at position " + p +
153 s.substring( ( (p - r) < 0) ? 0 : (p - r),
154 ( (p + r) > s.length()) ? s.length() : (p + r)) + " )\n";
158 // These are set automatically by the reader
159 public boolean HasBootstrap()
167 * @return DOCUMENT ME!
169 public boolean HasDistances()
174 public boolean HasRootDistance()
176 return RootHasDistance;
180 * parse the filesource as a newick file (new hampshire and/or extended)
182 * @throws IOException with a line number and character position for badly formatted NH strings
189 { // fill nf with complete tree file
191 StringBuffer file = new StringBuffer();
193 while ( (nf = nextLine()) != null)
198 nf = file.toString();
201 root = new SequenceNode();
203 SequenceNode realroot = null;
204 SequenceNode c = root;
208 //int flen = nf.length();
211 String nodename = null;
213 float DefDistance = (float) 0.001; // @param Default distance for a node - very very small
214 int DefBootstrap = 0; // @param Default bootstrap for a node
216 float distance = DefDistance;
217 int bootstrap = DefBootstrap;
219 boolean ascending = false; // flag indicating that we are leaving the current node
221 com.stevesoft.pat.Regex majorsyms = new com.stevesoft.pat.Regex(
224 while (majorsyms.searchFrom(nf, cp) && (Error == null))
226 int fcp = majorsyms.matchedFrom();
228 switch (schar=nf.charAt(fcp))
232 // ascending should not be set
236 Error = ErrorStringrange(Error, "Unexpected '('", 7, fcp, nf);
244 if (c.right() == null)
246 c.setRight(new SequenceNode(null, c, null, DefDistance,
247 DefBootstrap, false));
248 c = (SequenceNode) c.right();
252 if (c.left() != null)
254 // Dummy node for polytomy - keeps c.left free for new node
255 SequenceNode tmpn = new SequenceNode(null, c, null, 0,
257 tmpn.SetChildren(c.left(), c.right());
261 c.setLeft(new SequenceNode(null, c, null, DefDistance,
262 DefBootstrap, false));
263 c = (SequenceNode) c.left();
266 if (realroot == null)
272 distance = DefDistance;
273 bootstrap = DefBootstrap;
278 // Deal with quoted fields
281 com.stevesoft.pat.Regex qnodename = new com.stevesoft.pat.Regex(
284 if (qnodename.searchFrom(nf, fcp))
286 int nl = qnodename.stringMatched().length();
287 nodename = new String(qnodename.stringMatched().substring(0,
293 Error = ErrorStringrange(Error,
294 "Unterminated quotes for nodename", 7, fcp,
305 Error = ErrorStringrange(Error,
306 "Wayward semicolon (depth=" + d + ")", 7,
309 // cp advanced at the end of default
314 // node string contains Comment or structured/extended NH format info
315 /* if ((fcp-cp>1 && nf.substring(cp,fcp).trim().length()>1))
317 // will process in remains System.err.println("skipped text: '"+nf.substring(cp,fcp)+"'");
320 // verify termination.
321 com.stevesoft.pat.Regex comment = new com.stevesoft.pat.Regex(
323 if (comment.searchFrom(nf, fcp))
325 // Skip the comment field
326 nextcp=comment.matchedFrom()+1;
327 warningMessage = "Tree file contained comments which may confuse input algorithm.";
328 // Skip the comment field
329 // should advance fcp too here
331 // schar = nf.charAt(nextcp+1);
333 // cp advanced at the end of default to nextcp
337 Error = ErrorStringrange(Error, "Unterminated comment", 3,
343 // Parse simpler field strings
344 String fstring = nf.substring(cp, fcp);
345 com.stevesoft.pat.Regex uqnodename = new com.stevesoft.pat.Regex(
346 "\\b([^' :;\\](),]+)");
347 com.stevesoft.pat.Regex nbootstrap = new com.stevesoft.pat.Regex(
348 "\\S+([0-9+]+)\\S*:");
349 com.stevesoft.pat.Regex ndist = new com.stevesoft.pat.Regex(
352 if (uqnodename.search(fstring) &&
353 ( (uqnodename.matchedFrom(1) == 0) ||
354 (fstring.charAt(uqnodename.matchedFrom(1) - 1) != ':'))) // JBPNote HACK!
356 if (nodename == null)
358 if (ReplaceUnderscores)
360 nodename = uqnodename.stringMatched(1).replace('_',
365 nodename = uqnodename.stringMatched(1);
370 Error = ErrorStringrange(Error,
371 "File has broken algorithm - overwritten nodename",
376 if (nbootstrap.search(fstring) &&
377 (nbootstrap.matchedFrom(1) > (uqnodename.matchedFrom(1) +
378 uqnodename.stringMatched().length())))
382 bootstrap = (new Integer(nbootstrap.stringMatched(1))).intValue();
387 Error = ErrorStringrange(Error,
388 "Can't parse bootstrap value", 4,
389 cp + nbootstrap.matchedFrom(), nf);
393 boolean nodehasdistance = false;
395 if (ndist.search(fstring))
399 distance = (new Float(ndist.stringMatched(1))).floatValue();
401 nodehasdistance = true;
405 Error = ErrorStringrange(Error,
406 "Can't parse node distance value", 7,
407 cp + ndist.matchedFrom(), nf);
413 // Write node info here
415 // Trees without distances still need a render distance
416 c.dist = (HasDistances) ? distance : DefDistance;
417 // be consistent for internal bootstrap defaults too
418 c.setBootstrap( (HasBootstrap) ? bootstrap : DefBootstrap);
421 RootHasDistance = nodehasdistance; // JBPNote This is really UGLY!!! Ensure root node gets its given distance
426 // Find a place to put the leaf
427 SequenceNode newnode = new SequenceNode(null, c, nodename,
428 (HasDistances) ? distance : DefDistance,
429 (HasBootstrap) ? bootstrap : DefBootstrap, false);
431 if (c.right() == null)
437 if (c.left() == null)
443 // Insert a dummy node for polytomy
444 // dummy nodes have distances
445 SequenceNode newdummy = new SequenceNode(null, c,
446 null, (HasDistances ? 0 : DefDistance), 0, true);
447 newdummy.SetChildren(c.left(), newnode);
455 // move back up the tree from preceding closure
458 if ( (d > -1) && (c == null))
460 Error = ErrorStringrange(Error,
461 "File broke algorithm: Lost place in tree (is there an extra ')' ?)",
466 if (nf.charAt(fcp) == ')')
473 if (nf.charAt(fcp) == ',')
481 // Just advance focus, if we need to
482 if ( (c.left() != null) && (!c.left().isLeaf()))
484 c = (SequenceNode) c.left();
490 if (nf.charAt(fcp)=='[') {
494 // else : We do nothing if ';' is encountered.
498 // Reset new node properties to obvious fakes
500 distance = DefDistance;
501 bootstrap = DefBootstrap;
512 throw (new IOException("NewickFile: " + Error + "\n"));
516 throw (new IOException("NewickFile: No Tree read in\n"));
518 // THe next line is failing for topali trees - not sure why yet. if (root.right()!=null && root.isDummy())
519 root = (SequenceNode) root.right().detach(); // remove the imaginary root.
521 if (!RootHasDistance)
523 root.dist = (HasDistances) ? 0 : DefDistance;
530 * @return DOCUMENT ME!
532 public SequenceNode getTree()
538 * Generate a newick format tree according to internal flags
539 * for bootstraps, distances and root distances.
541 * @return new hampshire tree in a single line
543 public String print()
547 StringBuffer tf = new StringBuffer();
550 return (tf.append(";").toString());
557 * Generate a newick format tree according to internal flags
558 * for distances and root distances and user specificied writing of
560 * @param withbootstraps controls if bootstrap values are explicitly written.
562 * @return new hampshire tree in a single line
564 public String print(boolean withbootstraps)
568 boolean boots = this.HasBootstrap;
569 this.HasBootstrap = withbootstraps;
572 this.HasBootstrap = boots;
580 * Generate newick format tree according to internal flags
581 * for writing root node distances.
583 * @param withbootstraps explicitly write bootstrap values
584 * @param withdists explicitly write distances
586 * @return new hampshire tree in a single line
588 public String print(boolean withbootstraps, boolean withdists)
592 boolean dists = this.HasDistances;
593 this.HasDistances = withdists;
595 String rv = print(withbootstraps);
596 this.HasDistances = dists;
603 * Generate newick format tree according to user specified flags
605 * @param withbootstraps explicitly write bootstrap values
606 * @param withdists explicitly write distances
607 * @param printRootInfo explicitly write root distance
609 * @return new hampshire tree in a single line
611 public String print(boolean withbootstraps, boolean withdists,
612 boolean printRootInfo)
616 boolean rootinfo = printRootInfo;
617 this.printRootInfo = printRootInfo;
619 String rv = print(withbootstraps, withdists);
620 this.printRootInfo = rootinfo;
629 * @return DOCUMENT ME!
639 * @param c DOCUMENT ME!
641 * @return DOCUMENT ME!
643 char setQuoteChar(char c)
645 char old = QuoteChar;
654 * @param name DOCUMENT ME!
656 * @return DOCUMENT ME!
658 private String nodeName(String name)
660 if (NodeSafeName[0].search(name))
662 return QuoteChar + NodeSafeName[1].replaceAll(name) + QuoteChar;
666 return NodeSafeName[2].replaceAll(name);
673 * @param c DOCUMENT ME!
675 * @return DOCUMENT ME!
677 private String printNodeField(SequenceNode c)
679 return ( (c.getName() == null) ? "" : nodeName(c.getName())) +
681 ? ( (c.getBootstrap() > -1) ? (" " + c.getBootstrap()) : "") : "") +
682 ( (HasDistances) ? (":" + c.dist) : "");
688 * @param root DOCUMENT ME!
690 * @return DOCUMENT ME!
692 private String printRootField(SequenceNode root)
694 return (printRootInfo)
695 ? ( ( (root.getName() == null) ? "" : nodeName(root.getName())) +
697 ? ( (root.getBootstrap() > -1) ? (" " + root.getBootstrap()) : "") :
699 ( (RootHasDistance) ? (":" + root.dist) : "")) : "";
702 // Non recursive call deals with root node properties
703 public void print(StringBuffer tf, SequenceNode root)
707 if (root.isLeaf() && printRootInfo)
709 tf.append(printRootField(root));
715 _print(tf, (SequenceNode) root.right());
716 _print(tf, (SequenceNode) root.left());
721 _print(tf, (SequenceNode) root.right());
723 if (root.left() != null)
728 _print(tf, (SequenceNode) root.left());
729 tf.append(")" + printRootField(root));
735 // Recursive call for non-root nodes
736 public void _print(StringBuffer tf, SequenceNode c)
742 tf.append(printNodeField(c));
748 _print(tf, (SequenceNode) c.left());
749 if (c.left() != null)
753 _print(tf, (SequenceNode) c.right());
758 _print(tf, (SequenceNode) c.right());
760 if (c.left() != null)
765 _print(tf, (SequenceNode) c.left());
766 tf.append(")" + printNodeField(c));
773 public static void main(String[] args)
777 if (args == null || args.length != 1)
780 "Takes one argument - file name of a newick tree file.");
784 File fn = new File(args[0]);
786 StringBuffer newickfile = new StringBuffer();
787 BufferedReader treefile = new BufferedReader(new FileReader(fn));
790 while ( (l = treefile.readLine()) != null)
792 newickfile.append(l);
796 System.out.println("Read file :\n");
798 NewickFile trf = new NewickFile(args[0], "File");
800 System.out.println("Original file :\n");
802 com.stevesoft.pat.Regex nonl = new com.stevesoft.pat.Regex("\n+", "");
803 System.out.println(nonl.replaceAll(newickfile.toString()) + "\n");
805 System.out.println("Parsed file.\n");
806 System.out.println("Default output type for original input.\n");
807 System.out.println(trf.print());
808 System.out.println("Without bootstraps.\n");
809 System.out.println(trf.print(false));
810 System.out.println("Without distances.\n");
811 System.out.println(trf.print(true, false));
812 System.out.println("Without bootstraps but with distanecs.\n");
813 System.out.println(trf.print(false, true));
814 System.out.println("Without bootstraps or distanecs.\n");
815 System.out.println(trf.print(false, false));
816 System.out.println("With bootstraps and with distances.\n");
817 System.out.println(trf.print(true, true));
819 catch (java.io.IOException e)
821 System.err.println("Exception\n" + e);