2 * Jalview - A Sequence Alignment Editor and Viewer
\r
3 * Copyright (C) 2006 AM Waterhouse, J Procter, G Barton, M Clamp, S Searle
\r
5 * This program is free software; you can redistribute it and/or
\r
6 * modify it under the terms of the GNU General Public License
\r
7 * as published by the Free Software Foundation; either version 2
\r
8 * of the License, or (at your option) any later version.
\r
10 * This program is distributed in the hope that it will be useful,
\r
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
\r
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
\r
13 * GNU General Public License for more details.
\r
15 * You should have received a copy of the GNU General Public License
\r
16 * along with this program; if not, write to the Free Software
\r
17 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
\r
22 // http://evolution.genetics.washington.edu/phylip/newick_doc.html
\r
23 // TODO: Implement Basic NHX tag parsing and preservation
\r
24 // TODO: http://evolution.genetics.wustl.edu/eddy/forester/NHX.html
\r
25 // TODO: Extended SequenceNodeI to hold parsed NHX strings
\r
28 import jalview.datamodel.*;
\r
37 * @version $Revision$
\r
39 public class NewickFile extends FileParse
\r
42 private boolean HasBootstrap = false;
\r
43 private boolean HasDistances = false;
\r
44 private boolean RootHasDistance = false;
\r
47 boolean ReplaceUnderscores = false;
\r
48 boolean printRootInfo = false;
\r
49 private com.stevesoft.pat.Regex[] NodeSafeName = new com.stevesoft.pat.Regex[]
\r
51 new com.stevesoft.pat.Regex().perlCode("m/[\\[,:'()]/"), // test for requiring quotes
\r
52 new com.stevesoft.pat.Regex().perlCode("s/'/''/"), // escaping quote characters
\r
53 new com.stevesoft.pat.Regex().perlCode("s/\\/w/_/") // unqoted whitespace transformation
\r
55 char QuoteChar = '\'';
\r
58 * Creates a new NewickFile object.
\r
60 * @param inStr DOCUMENT ME!
\r
62 * @throws IOException DOCUMENT ME!
\r
64 public NewickFile(String inStr) throws IOException
\r
66 super(inStr, "Paste");
\r
70 * Creates a new NewickFile object.
\r
72 * @param inFile DOCUMENT ME!
\r
73 * @param type DOCUMENT ME!
\r
75 * @throws IOException DOCUMENT ME!
\r
77 public NewickFile(String inFile, String type) throws IOException
\r
79 super(inFile, type);
\r
83 * Creates a new NewickFile object.
\r
85 * @param newtree DOCUMENT ME!
\r
87 public NewickFile(SequenceNode newtree)
\r
93 * Creates a new NewickFile object.
\r
95 * @param newtree DOCUMENT ME!
\r
96 * @param bootstrap DOCUMENT ME!
\r
98 public NewickFile(SequenceNode newtree, boolean bootstrap)
\r
100 HasBootstrap = bootstrap;
\r
105 * Creates a new NewickFile object.
\r
107 * @param newtree DOCUMENT ME!
\r
108 * @param bootstrap DOCUMENT ME!
\r
109 * @param distances DOCUMENT ME!
\r
111 public NewickFile(SequenceNode newtree, boolean bootstrap, boolean distances)
\r
114 HasBootstrap = bootstrap;
\r
115 HasDistances = distances;
\r
119 * Creates a new NewickFile object.
\r
121 * @param newtree DOCUMENT ME!
\r
122 * @param bootstrap DOCUMENT ME!
\r
123 * @param distances DOCUMENT ME!
\r
124 * @param rootdistance DOCUMENT ME!
\r
126 public NewickFile(SequenceNode newtree, boolean bootstrap,
\r
127 boolean distances, boolean rootdistance)
\r
130 HasBootstrap = bootstrap;
\r
131 HasDistances = distances;
\r
132 RootHasDistance = rootdistance;
\r
138 * @param Error DOCUMENT ME!
\r
139 * @param Er DOCUMENT ME!
\r
140 * @param r DOCUMENT ME!
\r
141 * @param p DOCUMENT ME!
\r
142 * @param s DOCUMENT ME!
\r
144 * @return DOCUMENT ME!
\r
146 private String ErrorStringrange(String Error, String Er, int r, int p,
\r
149 return ((Error == null) ? "" : Error) + Er + " at position " + p +
\r
151 s.substring(((p - r) < 0) ? 0 : (p - r),
\r
152 ((p + r) > s.length()) ? s.length() : (p + r)) + " )\n";
\r
155 // @tree annotations
\r
156 // These are set automatically by the reader
\r
157 public boolean HasBootstrap()
\r
159 return HasBootstrap;
\r
165 * @return DOCUMENT ME!
\r
167 public boolean HasDistances()
\r
169 return HasDistances;
\r
172 public boolean HasRootDistance()
\r
174 return RootHasDistance;
\r
179 * @throws IOException DOCUMENT ME!
\r
181 public void parse() throws IOException
\r
185 { // fill nf with complete tree file
\r
187 StringBuffer file = new StringBuffer();
\r
189 while ((nf = nextLine()) != null)
\r
194 nf = file.toString();
\r
197 root = new SequenceNode();
\r
199 SequenceNode realroot = null;
\r
200 SequenceNode c = root;
\r
204 //int flen = nf.length();
\r
206 String Error = null;
\r
207 String nodename = null;
\r
209 float DefDistance = (float) 0.001; // @param Default distance for a node - very very small
\r
210 int DefBootstrap = 0; // @param Default bootstrap for a node
\r
212 float distance = DefDistance;
\r
213 int bootstrap = DefBootstrap;
\r
215 boolean ascending = false; // flag indicating that we are leaving the current node
\r
217 com.stevesoft.pat.Regex majorsyms = new com.stevesoft.pat.Regex(
\r
220 while (majorsyms.searchFrom(nf, cp) && (Error == null))
\r
222 int fcp = majorsyms.matchedFrom();
\r
224 switch (nf.charAt(fcp))
\r
226 case '[': // Comment or structured/extended NH format info
\r
228 com.stevesoft.pat.Regex comment = new com.stevesoft.pat.Regex(
\r
231 if (comment.searchFrom(nf, fcp))
\r
233 // Skip the comment field
\r
234 cp = 1 + comment.matchedFrom();
\r
238 Error = ErrorStringrange(Error, "Unterminated comment", 3,
\r
248 // ascending should not be set
\r
249 // New Internal node
\r
252 Error = ErrorStringrange(Error, "Unexpected '('", 7, fcp, nf);
\r
260 if (c.right() == null)
\r
262 c.setRight(new SequenceNode(null, c, null, DefDistance,
\r
263 DefBootstrap, false));
\r
264 c = (SequenceNode) c.right();
\r
268 if (c.left() != null)
\r
270 // Dummy node for polytomy - keeps c.left free for new node
\r
271 SequenceNode tmpn = new SequenceNode(null, c, null, 0,
\r
273 tmpn.SetChildren(c.left(), c.right());
\r
277 c.setLeft(new SequenceNode(null, c, null, DefDistance,
\r
278 DefBootstrap, false));
\r
279 c = (SequenceNode) c.left();
\r
282 if (realroot == null)
\r
288 distance = DefDistance;
\r
289 bootstrap = DefBootstrap;
\r
294 // Deal with quoted fields
\r
297 com.stevesoft.pat.Regex qnodename = new com.stevesoft.pat.Regex(
\r
300 if (qnodename.searchFrom(nf, fcp))
\r
302 int nl = qnodename.stringMatched().length();
\r
303 nodename = new String(qnodename.stringMatched().substring(0,
\r
309 Error = ErrorStringrange(Error,
\r
310 "Unterminated quotes for nodename", 7, fcp, nf);
\r
319 Error = ErrorStringrange(Error,
\r
320 "Wayward semicolon (depth=" + d + ")", 7, fcp, nf);
\r
323 // cp advanced at the end of default
\r
326 // Parse simpler field strings
\r
327 String fstring = nf.substring(cp, fcp);
\r
328 com.stevesoft.pat.Regex uqnodename = new com.stevesoft.pat.Regex(
\r
329 "\\b([^' :;\\](),]+)");
\r
330 com.stevesoft.pat.Regex nbootstrap = new com.stevesoft.pat.Regex(
\r
331 "\\S+([0-9+]+)\\S*:");
\r
332 com.stevesoft.pat.Regex ndist = new com.stevesoft.pat.Regex(
\r
335 if (uqnodename.search(fstring) &&
\r
336 ((uqnodename.matchedFrom(1) == 0) ||
\r
337 (fstring.charAt(uqnodename.matchedFrom(1) - 1) != ':'))) // JBPNote HACK!
\r
339 if (nodename == null)
\r
341 if (ReplaceUnderscores)
\r
343 nodename = uqnodename.stringMatched(1).replace('_',
\r
348 nodename = uqnodename.stringMatched(1);
\r
353 Error = ErrorStringrange(Error,
\r
354 "File has broken algorithm - overwritten nodename",
\r
359 if (nbootstrap.search(fstring) &&
\r
360 (nbootstrap.matchedFrom(1) > (uqnodename.matchedFrom(1) +
\r
361 uqnodename.stringMatched().length())))
\r
365 bootstrap = (new Integer(nbootstrap.stringMatched(1))).intValue();
\r
366 HasBootstrap = true;
\r
368 catch (Exception e)
\r
370 Error = ErrorStringrange(Error,
\r
371 "Can't parse bootstrap value", 4,
\r
372 cp + nbootstrap.matchedFrom(), nf);
\r
376 boolean nodehasdistance = false;
\r
378 if (ndist.search(fstring))
\r
382 distance = (new Float(ndist.stringMatched(1))).floatValue();
\r
383 HasDistances = true;
\r
384 nodehasdistance = true;
\r
386 catch (Exception e)
\r
388 Error = ErrorStringrange(Error,
\r
389 "Can't parse node distance value", 7,
\r
390 cp + ndist.matchedFrom(), nf);
\r
396 // Write node info here
\r
397 c.setName(nodename);
\r
398 // Trees without distances still need a render distance
\r
399 c.dist = (HasDistances) ? distance : DefDistance;
\r
400 // be consistent for internal bootstrap defaults too
\r
401 c.setBootstrap((HasBootstrap) ? bootstrap : DefBootstrap);
\r
404 RootHasDistance = nodehasdistance; // JBPNote This is really UGLY!!! Ensure root node gets its given distance
\r
409 // Find a place to put the leaf
\r
410 SequenceNode newnode = new SequenceNode(null, c, nodename,
\r
411 (HasDistances) ? distance : DefDistance,
\r
412 (HasBootstrap) ? bootstrap : DefBootstrap, false);
\r
414 if (c.right() == null)
\r
416 c.setRight(newnode);
\r
420 if (c.left() == null)
\r
422 c.setLeft(newnode);
\r
426 // Insert a dummy node for polytomy
\r
427 // dummy nodes have distances
\r
428 SequenceNode newdummy = new SequenceNode(null, c,
\r
429 null, (HasDistances ? 0 : DefDistance), 0, true);
\r
430 newdummy.SetChildren(c.left(), newnode);
\r
431 c.setLeft(newdummy);
\r
438 // move back up the tree from preceding closure
\r
439 c = c.AscendTree();
\r
441 if ((d > -1) && (c == null))
\r
443 Error = ErrorStringrange(Error,
\r
444 "File broke algorithm: Lost place in tree (is there an extra ')' ?)",
\r
449 if (nf.charAt(fcp) == ')')
\r
456 if (nf.charAt(fcp) == ',')
\r
464 // Just advance focus, if we need to
\r
465 if ((c.left() != null) && (!c.left().isLeaf()))
\r
467 c = (SequenceNode) c.left();
\r
472 // else : We do nothing if ';' is encountered.
\r
475 // Reset new node properties to obvious fakes
\r
477 distance = DefDistance;
\r
478 bootstrap = DefBootstrap;
\r
486 throw (new IOException("NewickFile: " + Error + "\n"));
\r
489 root = (SequenceNode) root.right().detach(); // remove the imaginary root.
\r
491 if (!RootHasDistance)
\r
493 root.dist = (HasDistances) ? 0 : DefDistance;
\r
500 * @return DOCUMENT ME!
\r
502 public SequenceNode getTree()
\r
508 * Generate a newick format tree according to internal flags
\r
509 * for bootstraps, distances and root distances.
\r
511 * @return new hampshire tree in a single line
\r
513 public String print()
\r
515 synchronized (this)
\r
517 StringBuffer tf = new StringBuffer();
\r
520 return (tf.append(";").toString());
\r
527 * Generate a newick format tree according to internal flags
\r
528 * for distances and root distances and user specificied writing of
\r
530 * @param withbootstraps controls if bootstrap values are explicitly written.
\r
532 * @return new hampshire tree in a single line
\r
534 public String print(boolean withbootstraps)
\r
536 synchronized (this)
\r
538 boolean boots = this.HasBootstrap;
\r
539 this.HasBootstrap = withbootstraps;
\r
541 String rv = print();
\r
542 this.HasBootstrap = boots;
\r
550 * Generate newick format tree according to internal flags
\r
551 * for writing root node distances.
\r
553 * @param withbootstraps explicitly write bootstrap values
\r
554 * @param withdists explicitly write distances
\r
556 * @return new hampshire tree in a single line
\r
558 public String print(boolean withbootstraps, boolean withdists)
\r
560 synchronized (this)
\r
562 boolean dists = this.HasDistances;
\r
563 this.HasDistances = withdists;
\r
565 String rv = print(withbootstraps);
\r
566 this.HasDistances = dists;
\r
573 * Generate newick format tree according to user specified flags
\r
575 * @param withbootstraps explicitly write bootstrap values
\r
576 * @param withdists explicitly write distances
\r
577 * @param printRootInfo explicitly write root distance
\r
579 * @return new hampshire tree in a single line
\r
581 public String print(boolean withbootstraps, boolean withdists,
\r
582 boolean printRootInfo)
\r
584 synchronized (this)
\r
586 boolean rootinfo = printRootInfo;
\r
587 this.printRootInfo = printRootInfo;
\r
589 String rv = print(withbootstraps, withdists);
\r
590 this.printRootInfo = rootinfo;
\r
599 * @return DOCUMENT ME!
\r
601 char getQuoteChar()
\r
609 * @param c DOCUMENT ME!
\r
611 * @return DOCUMENT ME!
\r
613 char setQuoteChar(char c)
\r
615 char old = QuoteChar;
\r
624 * @param name DOCUMENT ME!
\r
626 * @return DOCUMENT ME!
\r
628 private String nodeName(String name)
\r
630 if (NodeSafeName[0].search(name))
\r
632 return QuoteChar + NodeSafeName[1].replaceAll(name) + QuoteChar;
\r
636 return NodeSafeName[2].replaceAll(name);
\r
643 * @param c DOCUMENT ME!
\r
645 * @return DOCUMENT ME!
\r
647 private String printNodeField(SequenceNode c)
\r
649 return ((c.getName() == null) ? "" : nodeName(c.getName())) +
\r
651 ? ((c.getBootstrap() > -1) ? (" " + c.getBootstrap()) : "") : "") +
\r
652 ((HasDistances) ? (":" + c.dist) : "");
\r
658 * @param root DOCUMENT ME!
\r
660 * @return DOCUMENT ME!
\r
662 private String printRootField(SequenceNode root)
\r
664 return (printRootInfo)
\r
665 ? (((root.getName() == null) ? "" : nodeName(root.getName())) +
\r
667 ? ((root.getBootstrap() > -1) ? (" " + root.getBootstrap()) : "") : "") +
\r
668 ((RootHasDistance) ? (":" + root.dist) : "")) : "";
\r
671 // Non recursive call deals with root node properties
\r
672 public void print(StringBuffer tf, SequenceNode root)
\r
676 if (root.isLeaf() && printRootInfo)
\r
678 tf.append(printRootField(root));
\r
682 if (root.isDummy())
\r
684 _print(tf, (SequenceNode) root.right());
\r
685 _print(tf, (SequenceNode) root.left());
\r
690 _print(tf, (SequenceNode) root.right());
\r
692 if (root.left() != null)
\r
697 _print(tf, (SequenceNode) root.left());
\r
698 tf.append(")" + printRootField(root));
\r
704 // Recursive call for non-root nodes
\r
705 public void _print(StringBuffer tf, SequenceNode c)
\r
711 tf.append(printNodeField(c));
\r
717 _print(tf, (SequenceNode) c.left());
\r
718 if (c.left() != null)
\r
722 _print(tf, (SequenceNode) c.right());
\r
727 _print(tf, (SequenceNode) c.right());
\r
729 if (c.left() != null)
\r
734 _print(tf, (SequenceNode) c.left());
\r
735 tf.append(")" + printNodeField(c));
\r
742 public static void main(String[] args)
\r
746 if (args==null || args.length!=1) {
\r
747 System.err.println("Takes one argument - file name of a newick tree file.");
\r
751 File fn = new File(args[0]);
\r
753 StringBuffer newickfile = new StringBuffer();
\r
754 BufferedReader treefile = new BufferedReader(new FileReader(fn));
\r
757 while ((l = treefile.readLine()) != null)
\r
759 newickfile.append(l);
\r
763 System.out.println("Read file :\n");
\r
765 NewickFile trf = new NewickFile(args[0], "File");
\r
767 System.out.println("Original file :\n");
\r
769 com.stevesoft.pat.Regex nonl = new com.stevesoft.pat.Regex("\n+", "");
\r
770 System.out.println(nonl.replaceAll(newickfile.toString()) + "\n");
\r
772 System.out.println("Parsed file.\n");
\r
773 System.out.println("Default output type for original input.\n");
\r
774 System.out.println(trf.print());
\r
775 System.out.println("Without bootstraps.\n");
\r
776 System.out.println(trf.print(false));
\r
777 System.out.println("Without distances.\n");
\r
778 System.out.println(trf.print(true, false));
\r
779 System.out.println("Without bootstraps but with distanecs.\n");
\r
780 System.out.println(trf.print(false, true));
\r
781 System.out.println("Without bootstraps or distanecs.\n");
\r
782 System.out.println(trf.print(false, false));
\r
783 System.out.println("With bootstraps and with distances.\n");
\r
784 System.out.println(trf.print(true, true));
\r
786 catch (java.io.IOException e)
\r
788 System.err.println("Exception\n" + e);
\r
789 e.printStackTrace();
\r