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 = true;
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 = -1; // @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(
226 while (majorsyms.searchFrom(nf, cp) && (Error == null))
228 int fcp = majorsyms.matchedFrom();
230 switch (schar=nf.charAt(fcp))
234 // ascending should not be set
238 Error = ErrorStringrange(Error, "Unexpected '('", 7, fcp, nf);
246 if (c.right() == null)
248 c.setRight(new SequenceNode(null, c, null, DefDistance,
249 DefBootstrap, false));
250 c = (SequenceNode) c.right();
254 if (c.left() != null)
256 // Dummy node for polytomy - keeps c.left free for new node
257 SequenceNode tmpn = new SequenceNode(null, c, null, 0,
259 tmpn.SetChildren(c.left(), c.right());
263 c.setLeft(new SequenceNode(null, c, null, DefDistance,
264 DefBootstrap, false));
265 c = (SequenceNode) c.left();
268 if (realroot == null)
274 distance = DefDistance;
275 bootstrap = DefBootstrap;
280 // Deal with quoted fields
283 com.stevesoft.pat.Regex qnodename = new com.stevesoft.pat.Regex(
286 if (qnodename.searchFrom(nf, fcp))
288 int nl = qnodename.stringMatched().length();
289 nodename = new String(qnodename.stringMatched().substring(0,
295 Error = ErrorStringrange(Error,
296 "Unterminated quotes for nodename", 7, fcp,
307 Error = ErrorStringrange(Error,
308 "Wayward semicolon (depth=" + d + ")", 7,
311 // cp advanced at the end of default
315 // node string contains Comment or structured/extended NH format info
316 /* if ((fcp-cp>1 && nf.substring(cp,fcp).trim().length()>1))
318 // will process in remains System.err.println("skipped text: '"+nf.substring(cp,fcp)+"'");
321 // verify termination.
322 com.stevesoft.pat.Regex comment = new com.stevesoft.pat.Regex(
324 if (comment.searchFrom(nf, fcp))
326 // Skip the comment field
327 nextcp=comment.matchedFrom()+1;
328 warningMessage = "Tree file contained comments which may confuse input algorithm.";
331 // cp advanced at the end of default to nextcp, ncp is unchanged so any node info can be read.
335 Error = ErrorStringrange(Error, "Unterminated comment", 3,
341 // Parse simpler field strings
342 String fstring = nf.substring(ncp, fcp);
343 // remove any comments before we parse the node info
344 // TODO: test newick file with quoted square brackets in node name (is this allowed?)
345 while (fstring.indexOf(']')>-1)
347 int cstart=fstring.indexOf('[');
348 int cend=fstring.indexOf(']');
349 String comment = fstring.substring(cstart+1,cend);
350 fstring = fstring.substring(0, cstart)+fstring.substring(cend+1);
353 com.stevesoft.pat.Regex uqnodename = new com.stevesoft.pat.Regex(
354 "\\b([^' :;\\](),]+)");
355 com.stevesoft.pat.Regex nbootstrap = new com.stevesoft.pat.Regex(
356 "\\s*([0-9+]+)\\s*:");
357 com.stevesoft.pat.Regex ndist = new com.stevesoft.pat.Regex(
360 if (uqnodename.search(fstring) &&
361 ( (uqnodename.matchedFrom(1) == 0) ||
362 (fstring.charAt(uqnodename.matchedFrom(1) - 1) != ':'))) // JBPNote HACK!
364 if (nodename == null)
366 if (ReplaceUnderscores)
368 nodename = uqnodename.stringMatched(1).replace('_',
373 nodename = uqnodename.stringMatched(1);
378 Error = ErrorStringrange(Error,
379 "File has broken algorithm - overwritten nodename",
384 if (nbootstrap.search(fstring))
386 if (nbootstrap.stringMatched(1).equals(uqnodename.stringMatched(1)))
388 nodename=null; // no nodename here.
390 if (nodename==null || nodename.length()==0 || nbootstrap.matchedFrom(1) > (uqnodename.matchedFrom(1) +
391 uqnodename.stringMatched().length()))
395 bootstrap = (new Integer(nbootstrap.stringMatched(1))).intValue();
400 Error = ErrorStringrange(Error,
401 "Can't parse bootstrap value", 4,
402 ncp + nbootstrap.matchedFrom(), nf);
407 boolean nodehasdistance = false;
409 if (ndist.search(fstring))
413 distance = (new Float(ndist.stringMatched(1))).floatValue();
415 nodehasdistance = true;
419 Error = ErrorStringrange(Error,
420 "Can't parse node distance value", 7,
421 ncp + ndist.matchedFrom(), nf);
427 // Write node info here
429 // Trees without distances still need a render distance
430 c.dist = (HasDistances) ? distance : DefDistance;
431 // be consistent for internal bootstrap defaults too
432 c.setBootstrap( (HasBootstrap) ? bootstrap : DefBootstrap);
435 RootHasDistance = nodehasdistance; // JBPNote This is really UGLY!!! Ensure root node gets its given distance
440 // Find a place to put the leaf
441 SequenceNode newnode = new SequenceNode(null, c, nodename,
442 (HasDistances) ? distance : DefDistance,
443 (HasBootstrap) ? bootstrap : DefBootstrap, false);
445 if (c.right() == null)
451 if (c.left() == null)
457 // Insert a dummy node for polytomy
458 // dummy nodes have distances
459 SequenceNode newdummy = new SequenceNode(null, c,
460 null, (HasDistances ? 0 : DefDistance), 0, true);
461 newdummy.SetChildren(c.left(), newnode);
469 // move back up the tree from preceding closure
472 if ( (d > -1) && (c == null))
474 Error = ErrorStringrange(Error,
475 "File broke algorithm: Lost place in tree (is there an extra ')' ?)",
480 if (nf.charAt(fcp) == ')')
487 if (nf.charAt(fcp) == ',')
495 // Just advance focus, if we need to
496 if ( (c.left() != null) && (!c.left().isLeaf()))
498 c = (SequenceNode) c.left();
504 // Reset new node properties to obvious fakes
506 distance = DefDistance;
507 bootstrap = DefBootstrap;
521 throw (new IOException("NewickFile: " + Error + "\n"));
525 throw (new IOException("NewickFile: No Tree read in\n"));
527 // THe next line is failing for topali trees - not sure why yet. if (root.right()!=null && root.isDummy())
528 root = (SequenceNode) root.right().detach(); // remove the imaginary root.
530 if (!RootHasDistance)
532 root.dist = (HasDistances) ? 0 : DefDistance;
539 * @return DOCUMENT ME!
541 public SequenceNode getTree()
547 * Generate a newick format tree according to internal flags
548 * for bootstraps, distances and root distances.
550 * @return new hampshire tree in a single line
552 public String print()
556 StringBuffer tf = new StringBuffer();
559 return (tf.append(";").toString());
566 * Generate a newick format tree according to internal flags
567 * for distances and root distances and user specificied writing of
569 * @param withbootstraps controls if bootstrap values are explicitly written.
571 * @return new hampshire tree in a single line
573 public String print(boolean withbootstraps)
577 boolean boots = this.HasBootstrap;
578 this.HasBootstrap = withbootstraps;
581 this.HasBootstrap = boots;
589 * Generate newick format tree according to internal flags
590 * for writing root node distances.
592 * @param withbootstraps explicitly write bootstrap values
593 * @param withdists explicitly write distances
595 * @return new hampshire tree in a single line
597 public String print(boolean withbootstraps, boolean withdists)
601 boolean dists = this.HasDistances;
602 this.HasDistances = withdists;
604 String rv = print(withbootstraps);
605 this.HasDistances = dists;
612 * Generate newick format tree according to user specified flags
614 * @param withbootstraps explicitly write bootstrap values
615 * @param withdists explicitly write distances
616 * @param printRootInfo explicitly write root distance
618 * @return new hampshire tree in a single line
620 public String print(boolean withbootstraps, boolean withdists,
621 boolean printRootInfo)
625 boolean rootinfo = printRootInfo;
626 this.printRootInfo = printRootInfo;
628 String rv = print(withbootstraps, withdists);
629 this.printRootInfo = rootinfo;
638 * @return DOCUMENT ME!
648 * @param c DOCUMENT ME!
650 * @return DOCUMENT ME!
652 char setQuoteChar(char c)
654 char old = QuoteChar;
663 * @param name DOCUMENT ME!
665 * @return DOCUMENT ME!
667 private String nodeName(String name)
669 if (NodeSafeName[0].search(name))
671 return QuoteChar + NodeSafeName[1].replaceAll(name) + QuoteChar;
675 return NodeSafeName[2].replaceAll(name);
682 * @param c DOCUMENT ME!
684 * @return DOCUMENT ME!
686 private String printNodeField(SequenceNode c)
688 return ( (c.getName() == null) ? "" : nodeName(c.getName())) +
690 ? ( (c.getBootstrap() > -1) ? ((c.getName()!=null ? " " : "")+ c.getBootstrap()) : "") : "") +
691 ( (HasDistances) ? (":" + c.dist) : "");
697 * @param root DOCUMENT ME!
699 * @return DOCUMENT ME!
701 private String printRootField(SequenceNode root)
703 return (printRootInfo)
704 ? ( ( (root.getName() == null) ? "" : nodeName(root.getName())) +
706 ? ( (root.getBootstrap() > -1) ? ((root.getName()!=null ? " " : "")+
707 + root.getBootstrap()) : "") :
709 ( (RootHasDistance) ? (":" + root.dist) : "")) : "";
712 // Non recursive call deals with root node properties
713 public void print(StringBuffer tf, SequenceNode root)
717 if (root.isLeaf() && printRootInfo)
719 tf.append(printRootField(root));
725 _print(tf, (SequenceNode) root.right());
726 _print(tf, (SequenceNode) root.left());
731 _print(tf, (SequenceNode) root.right());
733 if (root.left() != null)
738 _print(tf, (SequenceNode) root.left());
739 tf.append(")" + printRootField(root));
745 // Recursive call for non-root nodes
746 public void _print(StringBuffer tf, SequenceNode c)
752 tf.append(printNodeField(c));
758 _print(tf, (SequenceNode) c.left());
759 if (c.left() != null)
763 _print(tf, (SequenceNode) c.right());
768 _print(tf, (SequenceNode) c.right());
770 if (c.left() != null)
775 _print(tf, (SequenceNode) c.left());
776 tf.append(")" + printNodeField(c));
783 public static void main(String[] args)
787 if (args == null || args.length != 1)
790 "Takes one argument - file name of a newick tree file.");
794 File fn = new File(args[0]);
796 StringBuffer newickfile = new StringBuffer();
797 BufferedReader treefile = new BufferedReader(new FileReader(fn));
800 while ( (l = treefile.readLine()) != null)
802 newickfile.append(l);
806 System.out.println("Read file :\n");
808 NewickFile trf = new NewickFile(args[0], "File");
810 System.out.println("Original file :\n");
812 com.stevesoft.pat.Regex nonl = new com.stevesoft.pat.Regex("\n+", "");
813 System.out.println(nonl.replaceAll(newickfile.toString()) + "\n");
815 System.out.println("Parsed file.\n");
816 System.out.println("Default output type for original input.\n");
817 System.out.println(trf.print());
818 System.out.println("Without bootstraps.\n");
819 System.out.println(trf.print(false));
820 System.out.println("Without distances.\n");
821 System.out.println(trf.print(true, false));
822 System.out.println("Without bootstraps but with distanecs.\n");
823 System.out.println(trf.print(false, true));
824 System.out.println("Without bootstraps or distanecs.\n");
825 System.out.println(trf.print(false, false));
826 System.out.println("With bootstraps and with distances.\n");
827 System.out.println(trf.print(true, true));
829 catch (java.io.IOException e)
831 System.err.println("Exception\n" + e);