2 * Jalview - A Sequence Alignment Editor and Viewer
3 * Copyright (C) 2005 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
\r
25 import jalview.datamodel.*;
\r
36 * @version $Revision$
\r
38 public class NewickFile extends FileParse
\r
41 private boolean HasBootstrap = false;
\r
42 private boolean HasDistances = false;
\r
43 private boolean RootHasDistance = false;
\r
46 boolean ReplaceUnderscores = false;
\r
47 boolean printRootInfo = false;
\r
48 private com.stevesoft.pat.Regex[] NodeSafeName = new com.stevesoft.pat.Regex[]
\r
50 new com.stevesoft.pat.Regex().perlCode("m/[\\[,:'()]/"), // test for requiring quotes
\r
51 new com.stevesoft.pat.Regex().perlCode("s/'/''/"), // escaping quote characters
\r
52 new com.stevesoft.pat.Regex().perlCode("s/\\/w/_/") // unqoted whitespace transformation
\r
54 char QuoteChar = '\'';
\r
57 * Creates a new NewickFile object.
\r
59 * @param inStr DOCUMENT ME!
\r
61 * @throws IOException DOCUMENT ME!
\r
63 public NewickFile(String inStr) throws IOException
\r
65 super(inStr, "Paste");
\r
69 * Creates a new NewickFile object.
\r
71 * @param inFile DOCUMENT ME!
\r
72 * @param type DOCUMENT ME!
\r
74 * @throws IOException DOCUMENT ME!
\r
76 public NewickFile(String inFile, String type) throws IOException
\r
78 super(inFile, type);
\r
82 * Creates a new NewickFile object.
\r
84 * @param newtree DOCUMENT ME!
\r
86 public NewickFile(SequenceNode newtree)
\r
92 * Creates a new NewickFile object.
\r
94 * @param newtree DOCUMENT ME!
\r
95 * @param bootstrap DOCUMENT ME!
\r
97 public NewickFile(SequenceNode newtree, boolean bootstrap)
\r
99 HasBootstrap = bootstrap;
\r
104 * Creates a new NewickFile object.
\r
106 * @param newtree DOCUMENT ME!
\r
107 * @param bootstrap DOCUMENT ME!
\r
108 * @param distances DOCUMENT ME!
\r
110 public NewickFile(SequenceNode newtree, boolean bootstrap, boolean distances)
\r
113 HasBootstrap = bootstrap;
\r
114 HasDistances = distances;
\r
118 * Creates a new NewickFile object.
\r
120 * @param newtree DOCUMENT ME!
\r
121 * @param bootstrap DOCUMENT ME!
\r
122 * @param distances DOCUMENT ME!
\r
123 * @param rootdistance DOCUMENT ME!
\r
125 public NewickFile(SequenceNode newtree, boolean bootstrap,
\r
126 boolean distances, boolean rootdistance)
\r
129 HasBootstrap = bootstrap;
\r
130 HasDistances = distances;
\r
131 RootHasDistance = rootdistance;
\r
137 * @param Error DOCUMENT ME!
\r
138 * @param Er DOCUMENT ME!
\r
139 * @param r DOCUMENT ME!
\r
140 * @param p DOCUMENT ME!
\r
141 * @param s DOCUMENT ME!
\r
143 * @return DOCUMENT ME!
\r
145 private String ErrorStringrange(String Error, String Er, int r, int p,
\r
148 return ((Error == null) ? "" : Error) + Er + " at position " + p +
\r
150 s.substring(((p - r) < 0) ? 0 : (p - r),
\r
151 ((p + r) > s.length()) ? s.length() : (p + r)) + " )\n";
\r
154 // @tree annotations
\r
155 // These are set automatically by the reader
\r
156 public boolean HasBootstrap()
\r
158 return HasBootstrap;
\r
164 * @return DOCUMENT ME!
\r
166 public boolean HasDistances()
\r
168 return HasDistances;
\r
174 * @throws IOException DOCUMENT ME!
\r
176 public void parse() throws IOException
\r
180 { // fill nf with complete tree file
\r
182 StringBuffer file = new StringBuffer();
\r
184 while ((nf = nextLine()) != null)
\r
189 nf = file.toString();
\r
192 root = new SequenceNode();
\r
194 SequenceNode realroot = null;
\r
195 SequenceNode c = root;
\r
199 int flen = nf.length();
\r
201 String Error = null;
\r
202 String nodename = null;
\r
204 float DefDistance = (float) 0.00001; // @param Default distance for a node - very very small
\r
205 int DefBootstrap = 0; // @param Default bootstrap for a node
\r
207 float distance = DefDistance;
\r
208 int bootstrap = DefBootstrap;
\r
210 boolean ascending = false; // flag indicating that we are leaving the current node
\r
212 com.stevesoft.pat.Regex majorsyms = new com.stevesoft.pat.Regex(
\r
215 while (majorsyms.searchFrom(nf, cp) && (Error == null))
\r
217 int fcp = majorsyms.matchedFrom();
\r
219 switch (nf.charAt(fcp))
\r
221 case '[': // Comment or structured/extended NH format info
\r
223 com.stevesoft.pat.Regex comment = new com.stevesoft.pat.Regex(
\r
226 if (comment.searchFrom(nf, fcp))
\r
228 // Skip the comment field
\r
229 cp = 1 + comment.matchedFrom();
\r
233 Error = ErrorStringrange(Error, "Unterminated comment", 3,
\r
243 // ascending should not be set
\r
244 // New Internal node
\r
247 Error = ErrorStringrange(Error, "Unexpected '('", 7, fcp, nf);
\r
255 if (c.right() == null)
\r
257 c.setRight(new SequenceNode(null, c, null, DefDistance,
\r
258 DefBootstrap, false));
\r
259 c = (SequenceNode) c.right();
\r
263 if (c.left() != null)
\r
265 // Dummy node for polytomy - keeps c.left free for new node
\r
266 SequenceNode tmpn = new SequenceNode(null, c, null, 0,
\r
268 tmpn.SetChildren(c.left(), c.right());
\r
272 c.setLeft(new SequenceNode(null, c, null, DefDistance,
\r
273 DefBootstrap, false));
\r
274 c = (SequenceNode) c.left();
\r
277 if (realroot == null)
\r
283 distance = DefDistance;
\r
284 bootstrap = DefBootstrap;
\r
289 // Deal with quoted fields
\r
292 com.stevesoft.pat.Regex qnodename = new com.stevesoft.pat.Regex(
\r
295 if (qnodename.searchFrom(nf, fcp))
\r
297 int nl = qnodename.stringMatched().length();
\r
298 nodename = new String(qnodename.stringMatched().substring(0,
\r
304 Error = ErrorStringrange(Error,
\r
305 "Unterminated quotes for nodename", 7, fcp, nf);
\r
314 Error = ErrorStringrange(Error,
\r
315 "Wayward semicolon (depth=" + d + ")", 7, fcp, nf);
\r
318 // cp advanced at the end of default
\r
321 // Parse simpler field strings
\r
322 String fstring = nf.substring(cp, fcp);
\r
323 com.stevesoft.pat.Regex uqnodename = new com.stevesoft.pat.Regex(
\r
324 "\\b([^' :;\\](),]+)");
\r
325 com.stevesoft.pat.Regex nbootstrap = new com.stevesoft.pat.Regex(
\r
326 "\\S+([0-9+]+)\\S*:");
\r
327 com.stevesoft.pat.Regex ndist = new com.stevesoft.pat.Regex(
\r
330 if (uqnodename.search(fstring) &&
\r
331 ((uqnodename.matchedFrom(1) == 0) ||
\r
332 (fstring.charAt(uqnodename.matchedFrom(1) - 1) != ':'))) // JBPNote HACK!
\r
334 if (nodename == null)
\r
336 if (ReplaceUnderscores)
\r
338 nodename = uqnodename.stringMatched(1).replace('_',
\r
343 nodename = uqnodename.stringMatched(1);
\r
348 Error = ErrorStringrange(Error,
\r
349 "File has broken algorithm - overwritten nodename",
\r
354 if (nbootstrap.search(fstring) &&
\r
355 (nbootstrap.matchedFrom(1) > (uqnodename.matchedFrom(1) +
\r
356 uqnodename.stringMatched().length())))
\r
360 bootstrap = (new Integer(nbootstrap.stringMatched(1))).intValue();
\r
361 HasBootstrap = true;
\r
363 catch (Exception e)
\r
365 Error = ErrorStringrange(Error,
\r
366 "Can't parse bootstrap value", 4,
\r
367 cp + nbootstrap.matchedFrom(), nf);
\r
371 boolean nodehasdistance = false;
\r
373 if (ndist.search(fstring))
\r
377 distance = (new Float(ndist.stringMatched(1))).floatValue();
\r
378 HasDistances = true;
\r
379 nodehasdistance = true;
\r
381 catch (Exception e)
\r
383 Error = ErrorStringrange(Error,
\r
384 "Can't parse node distance value", 7,
\r
385 cp + ndist.matchedFrom(), nf);
\r
391 // Write node info here
\r
392 c.setName(nodename);
\r
393 c.dist = (HasDistances) ? distance : 0;
\r
394 c.setBootstrap((HasBootstrap) ? bootstrap : 0);
\r
398 RootHasDistance = nodehasdistance; // JBPNote This is really UGLY!!!
\r
403 // Find a place to put the leaf
\r
404 SequenceNode newnode = new SequenceNode(null, c, nodename,
\r
405 (HasDistances) ? distance : DefDistance,
\r
406 (HasBootstrap) ? bootstrap : DefBootstrap, false);
\r
408 if (c.right() == null)
\r
410 c.setRight(newnode);
\r
414 if (c.left() == null)
\r
416 c.setLeft(newnode);
\r
420 // Insert a dummy node for polytomy
\r
421 SequenceNode newdummy = new SequenceNode(null, c,
\r
423 newdummy.SetChildren(c.left(), newnode);
\r
424 c.setLeft(newdummy);
\r
431 // move back up the tree from preceding closure
\r
432 c = c.AscendTree();
\r
434 if ((d > -1) && (c == null))
\r
436 Error = ErrorStringrange(Error,
\r
437 "File broke algorithm: Lost place in tree (is there an extra ')' ?)",
\r
442 if (nf.charAt(fcp) == ')')
\r
449 if (nf.charAt(fcp) == ',')
\r
457 // Just advance focus, if we need to
\r
458 if ((c.left() != null) && (!c.left().isLeaf()))
\r
460 c = (SequenceNode) c.left();
\r
465 // else : We do nothing if ';' is encountered.
\r
468 // Reset new node properties to obvious fakes
\r
470 distance = DefDistance;
\r
471 bootstrap = DefBootstrap;
\r
479 throw (new IOException("NewickFile: " + Error + "\n"));
\r
482 root = (SequenceNode) root.right().detach(); // remove the imaginary root.
\r
484 if (!RootHasDistance)
\r
493 * @return DOCUMENT ME!
\r
495 public SequenceNode getTree()
\r
503 * @return DOCUMENT ME!
\r
505 public String print()
\r
507 synchronized (this)
\r
509 StringBuffer tf = new StringBuffer();
\r
512 return (tf.append(";").toString());
\r
519 * @param withbootstraps DOCUMENT ME!
\r
521 * @return DOCUMENT ME!
\r
523 public String print(boolean withbootstraps)
\r
525 synchronized (this)
\r
527 boolean boots = this.HasBootstrap;
\r
528 this.HasBootstrap = withbootstraps;
\r
530 String rv = print();
\r
531 this.HasBootstrap = boots;
\r
540 * @param withbootstraps DOCUMENT ME!
\r
541 * @param withdists DOCUMENT ME!
\r
543 * @return DOCUMENT ME!
\r
545 public String print(boolean withbootstraps, boolean withdists)
\r
547 synchronized (this)
\r
549 boolean dists = this.HasDistances;
\r
550 this.HasDistances = withdists;
\r
552 String rv = print(withbootstraps);
\r
553 this.HasDistances = dists;
\r
562 * @param withbootstraps DOCUMENT ME!
\r
563 * @param withdists DOCUMENT ME!
\r
564 * @param printRootInfo DOCUMENT ME!
\r
566 * @return DOCUMENT ME!
\r
568 public String print(boolean withbootstraps, boolean withdists,
\r
569 boolean printRootInfo)
\r
571 synchronized (this)
\r
573 boolean rootinfo = printRootInfo;
\r
574 this.printRootInfo = printRootInfo;
\r
576 String rv = print(withbootstraps, withdists);
\r
577 this.printRootInfo = rootinfo;
\r
586 * @return DOCUMENT ME!
\r
588 char getQuoteChar()
\r
596 * @param c DOCUMENT ME!
\r
598 * @return DOCUMENT ME!
\r
600 char setQuoteChar(char c)
\r
602 char old = QuoteChar;
\r
611 * @param name DOCUMENT ME!
\r
613 * @return DOCUMENT ME!
\r
615 private String nodeName(String name)
\r
617 if (NodeSafeName[0].search(name))
\r
619 return QuoteChar + NodeSafeName[1].replaceAll(name) + QuoteChar;
\r
623 return NodeSafeName[2].replaceAll(name);
\r
630 * @param c DOCUMENT ME!
\r
632 * @return DOCUMENT ME!
\r
634 private String printNodeField(SequenceNode c)
\r
636 return ((c.getName() == null) ? "" : nodeName(c.getName())) +
\r
638 ? ((c.getBootstrap() > -1) ? (" " + c.getBootstrap()) : "") : "") +
\r
639 ((HasDistances) ? (":" + c.dist) : "");
\r
645 * @param root DOCUMENT ME!
\r
647 * @return DOCUMENT ME!
\r
649 private String printRootField(SequenceNode root)
\r
651 return (printRootInfo)
\r
652 ? (((root.getName() == null) ? "" : nodeName(root.getName())) +
\r
654 ? ((root.getBootstrap() > -1) ? (" " + root.getBootstrap()) : "") : "") +
\r
655 ((RootHasDistance) ? (":" + root.dist) : "")) : "";
\r
658 // Non recursive call deals with root node properties
\r
659 public void print(StringBuffer tf, SequenceNode root)
\r
663 if (root.isLeaf() && printRootInfo)
\r
665 tf.append(printRootField(root));
\r
669 if (root.isDummy())
\r
671 _print(tf, (SequenceNode) root.right());
\r
672 _print(tf, (SequenceNode) root.left());
\r
677 _print(tf, (SequenceNode) root.right());
\r
679 if (root.left() != null)
\r
684 _print(tf, (SequenceNode) root.left());
\r
685 tf.append(")" + printRootField(root));
\r
691 // Recursive call for non-root nodes
\r
692 public void _print(StringBuffer tf, SequenceNode c)
\r
698 tf.append(printNodeField(c));
\r
704 _print(tf, (SequenceNode) c.right());
\r
705 _print(tf, (SequenceNode) c.left());
\r
710 _print(tf, (SequenceNode) c.right());
\r
712 if (c.left() != null)
\r
717 _print(tf, (SequenceNode) c.left());
\r
718 tf.append(")" + printNodeField(c));
\r
725 public static void main(String[] args)
\r
729 File fn = new File(args[0]);
\r
731 StringBuffer newickfile = new StringBuffer();
\r
732 BufferedReader treefile = new BufferedReader(new FileReader(fn));
\r
735 while ((l = treefile.readLine()) != null)
\r
737 newickfile.append(l);
\r
741 System.out.println("Read file :\n");
\r
743 NewickFile trf = new NewickFile(args[0], "File");
\r
745 System.out.println("Original file :\n");
\r
747 com.stevesoft.pat.Regex nonl = new com.stevesoft.pat.Regex("\n+", "");
\r
748 System.out.println(nonl.replaceAll(newickfile.toString()) + "\n");
\r
750 System.out.println("Parsed file.\n");
\r
751 System.out.println("Default output type for original input.\n");
\r
752 System.out.println(trf.print());
\r
753 System.out.println("Without bootstraps.\n");
\r
754 System.out.println(trf.print(false));
\r
755 System.out.println("Without distances.\n");
\r
756 System.out.println(trf.print(true, false));
\r
757 System.out.println("Without bootstraps but with distanecs.\n");
\r
758 System.out.println(trf.print(false, true));
\r
759 System.out.println("Without bootstraps or distanecs.\n");
\r
760 System.out.println(trf.print(false, false));
\r
761 System.out.println("With bootstraps and with distances.\n");
\r
762 System.out.println(trf.print(true, true));
\r
764 catch (java.io.IOException e)
\r
766 System.err.println("Exception\n" + e);
\r
767 e.printStackTrace();
\r