2 * Jalview - A Sequence Alignment Editor and Viewer ($$Version-Rel$$)
3 * Copyright (C) $$Year-Rel$$ 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
10 * of the License, or (at your option) any later version.
12 * Jalview is distributed in the hope that it will be useful, but
13 * WITHOUT ANY WARRANTY; without even the implied warranty
14 * of MERCHANTABILITY or FITNESS FOR A PARTICULAR
15 * PURPOSE. See the GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License
18 * along with Jalview. If not, see <http://www.gnu.org/licenses/>.
19 * The Jalview Authors are detailed in the 'AUTHORS' file.
23 // http://evolution.genetics.washington.edu/phylip/newick_doc.html
24 // TODO: Implement Basic NHX tag parsing and preservation
25 // TODO: http://evolution.genetics.wustl.edu/eddy/forester/NHX.html
26 // TODO: Extended SequenceNodeI to hold parsed NHX strings
29 import java.io.BufferedReader;
31 import java.io.FileReader;
32 import java.io.IOException;
33 import java.util.Locale;
34 import java.util.StringTokenizer;
36 import com.stevesoft.pat.Regex;
38 import jalview.bin.Jalview;
39 import jalview.datamodel.BinaryNode;
40 import jalview.datamodel.SequenceNode;
41 import jalview.util.MessageManager;
44 * Parse a new hanpshire style tree Caveats: NHX files are NOT supported and the
45 * tree distances and topology are unreliable when they are parsed. TODO: on
46 * this: NHX codes are appended in comments beginning with &&NHX. The codes are
47 * given below (from http://www.phylosoft.org/forester/NHX.html): Element Type
48 * Description Corresponding phyloXML element (parent element in parentheses) no
49 * tag string name of this node/clade (MUST BE FIRST, IF ASSIGNED)
50 * <name>(<clade>) : decimal branch length to parent node (MUST BE SECOND, IF
51 * ASSIGNED) <branch_length>(<clade>) :GN= string gene name <name>(<sequence>)
52 * :AC= string sequence accession <accession>(<sequence>) :ND= string node
53 * identifier - if this is being used, it has to be unique within each phylogeny
54 * <node_id>(<clade>) :B= decimal confidence value for parent branch
55 * <confidence>(<clade>) :D= 'T', 'F', or '?' 'T' if this node represents a
56 * duplication event - 'F' if this node represents a speciation event, '?' if
57 * this node represents an unknown event (D= tag should be replaced by Ev= tag)
58 * n/a :Ev=duplications>speciations>gene losses>event type>duplication type int
59 * int int string string event (replaces the =D tag), number of duplication,
60 * speciation, and gene loss events, type of event (transfer, fusion, root,
61 * unknown, other, speciation_duplication_loss, unassigned) <events>(<clade>)
62 * :E= string EC number at this node <annotation>(<sequence>) :Fu= string
63 * function at this node <annotation>(<sequence>)
64 * :DS=protein-length>from>to>support>name>from>... int int int double string
65 * int ... domain structure at this node <domain_architecture>(<sequence>) :S=
66 * string species name of the species/phylum at this node <taxonomy>(<clade>)
67 * :T= integer taxonomy ID of the species/phylum at this node <id>(<taxonomy>)
68 * :W= integer width of parent branch <width>(<clade>) :C=rrr.ggg.bbb
69 * integer.integer.integer color of parent branch <color>(<clade>) :Co= 'Y' or
70 * 'N' collapse this node when drawing the tree (default is not to collapse) n/a
71 * :XB= string custom data associated with a branch <property>(<clade>) :XN=
72 * string custom data associated with a node <property>(<clade>) :O= integer
73 * orthologous to this external node n/a :SN= integer subtree neighbors n/a :SO=
74 * integer super orthologous (no duplications on paths) to this external node
80 public class NewickFile extends FileParse
84 private boolean HasBootstrap = false;
86 private boolean HasDistances = false;
88 private boolean RootHasDistance = false;
91 boolean ReplaceUnderscores = false;
93 boolean printRootInfo = true;
95 private Regex[] NodeSafeName = new Regex[] {
96 new Regex().perlCode("m/[\\[,:'()]/"), // test for
99 new Regex().perlCode("s/'/''/"), // escaping quote
101 new Regex().perlCode("s/\\/w/_/") // unqoted whitespace
105 char QuoteChar = '\'';
108 * Creates a new NewickFile object.
113 * @throws IOException
116 public NewickFile(String inStr) throws IOException
118 super(inStr, DataSourceType.PASTE);
122 * Creates a new NewickFile object.
129 * @throws IOException
132 public NewickFile(String inFile, DataSourceType protocol)
135 super(inFile, protocol);
138 public NewickFile(FileParse source) throws IOException
144 * Creates a new NewickFile object.
149 public NewickFile(BinaryNode newtree)
155 * Creates a new NewickFile object.
162 public NewickFile(SequenceNode newtree, boolean bootstrap)
164 HasBootstrap = bootstrap;
169 * Creates a new NewickFile object.
178 public NewickFile(BinaryNode newtree, boolean bootstrap,
182 HasBootstrap = bootstrap;
183 HasDistances = distances;
187 * Creates a new NewickFile object.
195 * @param rootdistance
198 public NewickFile(BinaryNode newtree, boolean bootstrap,
199 boolean distances, boolean rootdistance)
202 HasBootstrap = bootstrap;
203 HasDistances = distances;
204 RootHasDistance = rootdistance;
221 * @return DOCUMENT ME!
223 private String ErrorStringrange(String Error, String Er, int r, int p,
226 return ((Error == null) ? "" : Error) + Er + " at position " + p + " ( "
227 + s.substring(((p - r) < 0) ? 0 : (p - r),
228 ((p + r) > s.length()) ? s.length() : (p + r))
233 // These are set automatically by the reader
234 public boolean HasBootstrap()
242 * @return DOCUMENT ME!
244 public boolean HasDistances()
249 public boolean HasRootDistance()
251 return RootHasDistance;
255 * parse the filesource as a newick file (new hampshire and/or extended)
257 * @throws IOException
258 * with a line number and character position for badly formatted NH
261 public void parse() throws IOException
265 { // fill nf with complete tree file
267 StringBuffer file = new StringBuffer();
269 while ((nf = nextLine()) != null)
274 nf = file.toString();
277 root = new SequenceNode();
279 BinaryNode realroot = null;
284 // int flen = nf.length();
287 String nodename = null;
288 String commentString2 = null; // comments after simple node props
290 double DefDistance = (float) 0.001; // @param Default distance for a node -
292 int DefBootstrap = -1; // @param Default bootstrap for a node
294 double distance = DefDistance;
295 int bootstrap = DefBootstrap;
297 boolean ascending = false; // flag indicating that we are leaving the
300 Regex majorsyms = new Regex("[(\\['),;]");
304 boolean parsednodename = false;
305 while (majorsyms.searchFrom(nf, cp) && (Error == null))
307 int fcp = majorsyms.matchedFrom();
309 switch (schar = nf.charAt(fcp))
313 // ascending should not be set
317 Error = ErrorStringrange(Error, "Unexpected '('", 7, fcp, nf);
323 if (c.right() == null)
325 c.setRight(new SequenceNode(null, c, null, DefDistance,
326 DefBootstrap, false));
327 c = (BinaryNode) c.right();
331 if (c.left() != null)
333 // Dummy node for polytomy - keeps c.left free for new node
334 BinaryNode tmpn = new SequenceNode(null, c, null, 0, 0, true);
335 tmpn.SetChildren(c.left(), c.right());
339 c.setLeft(new SequenceNode(null, c, null, DefDistance,
340 DefBootstrap, false));
341 c = (BinaryNode) c.left();
344 if (realroot == null)
350 distance = DefDistance;
351 bootstrap = DefBootstrap;
356 // Deal with quoted fields
359 Regex qnodename = new Regex("'([^']|'')+'");
361 if (qnodename.searchFrom(nf, fcp))
363 int nl = qnodename.stringMatched().length();
364 nodename = new String(
365 qnodename.stringMatched().substring(1, nl - 1));
366 // unpack any escaped colons
367 Regex xpandquotes = Regex.perlCode("s/''/'/");
368 String widernodename = xpandquotes.replaceAll(nodename);
369 nodename = widernodename;
370 // jump to after end of quoted nodename
371 nextcp = fcp + nl + 1;
372 parsednodename = true;
376 Error = ErrorStringrange(Error,
377 "Unterminated quotes for nodename", 7, fcp, nf);
387 Error = ErrorStringrange(Error,
388 "Wayward semicolon (depth=" + d + ")", 7, fcp, nf);
390 // cp advanced at the end of default
394 // node string contains Comment or structured/extended NH format info
396 * if ((fcp-cp>1 && nf.substring(cp,fcp).trim().length()>1)) { // will
397 * process in remains jalview.bin.Console.errPrintln("skipped text:
398 * '"+nf.substring(cp,fcp)+"'"); }
400 // verify termination.
401 Regex comment = new Regex("]");
402 if (comment.searchFrom(nf, fcp))
404 // Skip the comment field
405 nextcp = comment.matchedFrom() + 1;
406 warningMessage = "Tree file contained comments which may confuse input algorithm.";
409 // cp advanced at the end of default to nextcp, ncp is unchanged so
410 // any node info can be read.
414 Error = ErrorStringrange(Error, "Unterminated comment", 3, fcp,
418 // Parse simpler field strings
419 String fstring = nf.substring(ncp, fcp);
420 // remove any comments before we parse the node info
421 // TODO: test newick file with quoted square brackets in node name (is
423 while (fstring.indexOf(']') > -1)
425 int cstart = fstring.indexOf('[');
426 int cend = fstring.indexOf(']');
427 commentString2 = fstring.substring(cstart + 1, cend);
428 fstring = fstring.substring(0, cstart)
429 + fstring.substring(cend + 1);
432 Regex uqnodename = new Regex("\\b([^' :;\\](),]+)");
433 Regex nbootstrap = new Regex("\\s*([0-9+]+)\\s*:");
434 Regex ndist = new Regex(":([-0-9Ee.+]+)");
436 if (!parsednodename && uqnodename.search(fstring)
437 && ((uqnodename.matchedFrom(1) == 0) || (fstring
438 .charAt(uqnodename.matchedFrom(1) - 1) != ':'))) // JBPNote
441 if (nodename == null)
443 if (ReplaceUnderscores)
445 nodename = uqnodename.stringMatched(1).replace('_', ' ');
449 nodename = uqnodename.stringMatched(1);
454 Error = ErrorStringrange(Error,
455 "File has broken algorithm - overwritten nodename", 10,
459 // get comment bootstraps
461 if (nbootstrap.search(fstring))
463 if (nbootstrap.stringMatched(1)
464 .equals(uqnodename.stringMatched(1)))
466 nodename = null; // no nodename here.
468 if (nodename == null || nodename.length() == 0
469 || nbootstrap.matchedFrom(1) > (uqnodename.matchedFrom(1)
470 + uqnodename.stringMatched().length()))
474 bootstrap = (Integer.valueOf(nbootstrap.stringMatched(1)))
477 } catch (Exception e)
479 Error = ErrorStringrange(Error, "Can't parse bootstrap value",
480 4, ncp + nbootstrap.matchedFrom(), nf);
485 boolean nodehasdistance = false;
487 if (ndist.search(fstring))
491 distance = (Double.valueOf(ndist.stringMatched(1)))
494 nodehasdistance = true;
495 } catch (Exception e)
497 Error = ErrorStringrange(Error,
498 "Can't parse node distance value", 7,
499 ncp + ndist.matchedFrom(), nf);
505 // Write node info here
507 // Trees without distances still need a render distance
508 c.dist = (HasDistances) ? distance : DefDistance;
509 // be consistent for internal bootstrap defaults too
510 c.setBootstrap((HasBootstrap) ? bootstrap : DefBootstrap);
513 RootHasDistance = nodehasdistance; // JBPNote This is really
514 // UGLY!!! Ensure root node gets
515 // its given distance
517 parseNHXNodeProps(c, commentString2);
518 commentString2 = null;
522 // Find a place to put the leaf
523 BinaryNode newnode = new SequenceNode(null, c, nodename,
524 (HasDistances) ? distance : DefDistance,
525 (HasBootstrap) ? bootstrap : DefBootstrap, false);
526 parseNHXNodeProps(c, commentString2);
527 commentString2 = null;
529 if (c.right() == null)
535 if (c.left() == null)
541 // Insert a dummy node for polytomy
542 // dummy nodes have distances
543 BinaryNode newdummy = new SequenceNode(null, c, null,
544 (HasDistances ? 0 : DefDistance), 0, true);
545 newdummy.SetChildren(c.left(), newnode);
553 // move back up the tree from preceding closure
556 if ((d > -1) && (c == null))
558 Error = ErrorStringrange(Error,
559 "File broke algorithm: Lost place in tree (is there an extra ')' ?)",
564 if (nf.charAt(fcp) == ')')
571 if (nf.charAt(fcp) == ',')
579 // Just advance focus, if we need to
580 if ((c.left() != null) && (!c.left().isLeaf()))
582 c = (BinaryNode) c.left();
588 // Reset new node properties to obvious fakes
590 distance = DefDistance;
591 bootstrap = DefBootstrap;
592 commentString2 = null;
593 parsednodename = false;
608 throw (new IOException(
609 MessageManager.formatMessage("exception.newfile", new String[]
610 { Error.toString() })));
614 throw (new IOException(
615 MessageManager.formatMessage("exception.newfile", new String[]
616 { MessageManager.getString("label.no_tree_read_in") })));
618 // THe next line is failing for topali trees - not sure why yet. if
619 // (root.right()!=null && root.isDummy())
620 root = (SequenceNode) root.right().detach(); // remove the imaginary root.
622 if (!RootHasDistance)
624 root.dist = (HasDistances) ? 0 : DefDistance;
629 * parse NHX codes in comment strings and update NewickFile state flags for
630 * distances and bootstraps, and add any additional properties onto the node.
633 * @param commentString
634 * @param commentString2
636 private void parseNHXNodeProps(BinaryNode c, String commentString)
638 // TODO: store raw comment on the sequenceNode so it can be recovered when
640 if (commentString != null && commentString.startsWith("&&NHX"))
642 StringTokenizer st = new StringTokenizer(commentString.substring(5),
644 while (st.hasMoreTokens())
646 String tok = st.nextToken();
647 int colpos = tok.indexOf("=");
651 String code = tok.substring(0, colpos);
652 String value = tok.substring(colpos + 1);
655 // parse out code/value pairs
656 if (code.toLowerCase(Locale.ROOT).equals("b"))
659 Float iv = Float.valueOf(value);
660 v = iv.intValue(); // jalview only does integer bootstraps
666 } catch (Exception e)
668 jalview.bin.Console.errPrintln(
669 "Couldn't parse code '" + code + "' = '" + value + "'");
670 e.printStackTrace(System.err);
681 * @return DOCUMENT ME!
683 public BinaryNode getTree()
689 * Generate a newick format tree according to internal flags for bootstraps,
690 * distances and root distances.
692 * @return new hampshire tree in a single line
694 public String print()
698 StringBuffer tf = new StringBuffer();
701 return (tf.append(";").toString());
708 * Generate a newick format tree according to internal flags for distances and
709 * root distances and user specificied writing of bootstraps.
711 * @param withbootstraps
712 * controls if bootstrap values are explicitly written.
714 * @return new hampshire tree in a single line
716 public String print(boolean withbootstraps)
720 boolean boots = this.HasBootstrap;
721 this.HasBootstrap = withbootstraps;
724 this.HasBootstrap = boots;
732 * Generate newick format tree according to internal flags for writing root
735 * @param withbootstraps
736 * explicitly write bootstrap values
738 * explicitly write distances
740 * @return new hampshire tree in a single line
742 public String print(boolean withbootstraps, boolean withdists)
746 boolean dists = this.HasDistances;
747 this.HasDistances = withdists;
749 String rv = print(withbootstraps);
750 this.HasDistances = dists;
757 * Generate newick format tree according to user specified flags
759 * @param withbootstraps
760 * explicitly write bootstrap values
762 * explicitly write distances
763 * @param printRootInfo
764 * explicitly write root distance
766 * @return new hampshire tree in a single line
768 public String print(boolean withbootstraps, boolean withdists,
769 boolean printRootInfo)
773 boolean rootinfo = printRootInfo;
774 this.printRootInfo = printRootInfo;
776 String rv = print(withbootstraps, withdists);
777 this.printRootInfo = rootinfo;
786 * @return DOCUMENT ME!
799 * @return DOCUMENT ME!
801 char setQuoteChar(char c)
803 char old = QuoteChar;
815 * @return DOCUMENT ME!
817 private String nodeName(String name)
819 if (NodeSafeName[0].search(name))
821 return QuoteChar + NodeSafeName[1].replaceAll(name) + QuoteChar;
825 return NodeSafeName[2].replaceAll(name);
835 * @return DOCUMENT ME!
837 private String printNodeField(BinaryNode c)
839 return ((c.getName() == null) ? "" : nodeName(c.getName()))
840 + ((HasBootstrap) ? ((c.getBootstrap() > -1)
841 ? ((c.getName() != null ? " " : "") + c.getBootstrap())
843 + ((HasDistances) ? (":" + c.dist) : "");
852 * @return DOCUMENT ME!
854 private String printRootField(BinaryNode root)
856 return (printRootInfo)
857 ? (((root.getName() == null) ? "" : nodeName(root.getName()))
859 ? ((root.getBootstrap() > -1)
860 ? ((root.getName() != null ? " " : "")
861 + +root.getBootstrap())
864 + ((RootHasDistance) ? (":" + root.dist) : ""))
868 // Non recursive call deals with root node properties
869 public void print(StringBuffer tf, BinaryNode root)
873 if (root.isLeaf() && printRootInfo)
875 tf.append(printRootField(root));
881 _print(tf, root.right());
882 _print(tf, root.left());
887 _print(tf, root.right());
889 if (root.left() != null)
894 _print(tf, root.left());
895 tf.append(")" + printRootField(root));
901 // Recursive call for non-root nodes
902 public void _print(StringBuffer tf, BinaryNode c)
908 tf.append(printNodeField(c));
914 _print(tf, c.left());
915 if (c.left() != null)
919 _print(tf, c.right());
924 _print(tf, c.right());
926 if (c.left() != null)
931 _print(tf, c.left());
932 tf.append(")" + printNodeField(c));
943 public static void main(String[] args)
947 if (args == null || args.length != 1)
950 "Takes one argument - file name of a newick tree file.", 0);
953 File fn = new File(args[0]);
955 StringBuffer newickfile = new StringBuffer();
956 BufferedReader treefile = new BufferedReader(new FileReader(fn));
959 while ((l = treefile.readLine()) != null)
961 newickfile.append(l);
965 jalview.bin.Console.outPrintln("Read file :\n");
967 NewickFile trf = new NewickFile(args[0], DataSourceType.FILE);
969 jalview.bin.Console.outPrintln("Original file :\n");
971 Regex nonl = new Regex("\n+", "");
972 jalview.bin.Console.outPrintln(nonl.replaceAll(newickfile.toString()) + "\n");
974 jalview.bin.Console.outPrintln("Parsed file.\n");
975 jalview.bin.Console.outPrintln("Default output type for original input.\n");
976 jalview.bin.Console.outPrintln(trf.print());
977 jalview.bin.Console.outPrintln("Without bootstraps.\n");
978 jalview.bin.Console.outPrintln(trf.print(false));
979 jalview.bin.Console.outPrintln("Without distances.\n");
980 jalview.bin.Console.outPrintln(trf.print(true, false));
981 jalview.bin.Console.outPrintln("Without bootstraps but with distanecs.\n");
982 jalview.bin.Console.outPrintln(trf.print(false, true));
983 jalview.bin.Console.outPrintln("Without bootstraps or distanecs.\n");
984 jalview.bin.Console.outPrintln(trf.print(false, false));
985 jalview.bin.Console.outPrintln("With bootstraps and with distances.\n");
986 jalview.bin.Console.outPrintln(trf.print(true, true));
987 } catch (java.io.IOException e)
989 jalview.bin.Console.errPrintln("Exception\n" + e);