2 * Jalview - A Sequence Alignment Editor and Viewer (Version 2.8.0b1)
3 * Copyright (C) 2014 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 of the License, or (at your option) any later version.
11 * Jalview is distributed in the hope that it will be useful, but
12 * WITHOUT ANY WARRANTY; without even the implied warranty
13 * of MERCHANTABILITY or FITNESS FOR A PARTICULAR
14 * PURPOSE. See the GNU General Public License for more details.
16 * You should have received a copy of the GNU General Public License along with Jalview. If not, see <http://www.gnu.org/licenses/>.
17 * The Jalview Authors are detailed in the 'AUTHORS' file.
21 // http://evolution.genetics.washington.edu/phylip/newick_doc.html
22 // TODO: Implement Basic NHX tag parsing and preservation
23 // TODO: http://evolution.genetics.wustl.edu/eddy/forester/NHX.html
24 // TODO: Extended SequenceNodeI to hold parsed NHX strings
28 import java.util.StringTokenizer;
30 import jalview.datamodel.*;
33 * Parse a new hanpshire style tree Caveats: NHX files are NOT supported and the
34 * tree distances and topology are unreliable when they are parsed. TODO: on
35 * this: NHX codes are appended in comments beginning with &&NHX. The codes are
36 * given below (from http://www.phylosoft.org/forester/NHX.html): Element Type
37 * Description Corresponding phyloXML element (parent element in parentheses) no
38 * tag string name of this node/clade (MUST BE FIRST, IF ASSIGNED)
39 * <name>(<clade>) : decimal branch length to parent node (MUST BE SECOND, IF
40 * ASSIGNED) <branch_length>(<clade>) :GN= string gene name <name>(<sequence>)
41 * :AC= string sequence accession <accession>(<sequence>) :ND= string node
42 * identifier - if this is being used, it has to be unique within each phylogeny
43 * <node_id>(<clade>) :B= decimal confidence value for parent branch
44 * <confidence>(<clade>) :D= 'T', 'F', or '?' 'T' if this node represents a
45 * duplication event - 'F' if this node represents a speciation event, '?' if
46 * this node represents an unknown event (D= tag should be replaced by Ev= tag)
47 * n/a :Ev=duplications>speciations>gene losses>event type>duplication type int
48 * int int string string event (replaces the =D tag), number of duplication,
49 * speciation, and gene loss events, type of event (transfer, fusion, root,
50 * unknown, other, speciation_duplication_loss, unassigned) <events>(<clade>)
51 * :E= string EC number at this node <annotation>(<sequence>) :Fu= string
52 * function at this node <annotation>(<sequence>)
53 * :DS=protein-length>from>to>support>name>from>... int int int double string
54 * int ... domain structure at this node <domain_architecture>(<sequence>) :S=
55 * string species name of the species/phylum at this node <taxonomy>(<clade>)
56 * :T= integer taxonomy ID of the species/phylum at this node <id>(<taxonomy>)
57 * :W= integer width of parent branch <width>(<clade>) :C=rrr.ggg.bbb
58 * integer.integer.integer color of parent branch <color>(<clade>) :Co= 'Y' or
59 * 'N' collapse this node when drawing the tree (default is not to collapse) n/a
60 * :XB= string custom data associated with a branch <property>(<clade>) :XN=
61 * string custom data associated with a node <property>(<clade>) :O= integer
62 * orthologous to this external node n/a :SN= integer subtree neighbors n/a :SO=
63 * integer super orthologous (no duplications on paths) to this external node
69 public class NewickFile extends FileParse
73 private boolean HasBootstrap = false;
75 private boolean HasDistances = false;
77 private boolean RootHasDistance = false;
80 boolean ReplaceUnderscores = false;
82 boolean printRootInfo = true;
84 private com.stevesoft.pat.Regex[] NodeSafeName = new com.stevesoft.pat.Regex[]
85 { new com.stevesoft.pat.Regex().perlCode("m/[\\[,:'()]/"), // test for
88 new com.stevesoft.pat.Regex().perlCode("s/'/''/"), // escaping quote
90 new com.stevesoft.pat.Regex().perlCode("s/\\/w/_/") // unqoted whitespace
94 char QuoteChar = '\'';
97 * Creates a new NewickFile object.
102 * @throws IOException
105 public NewickFile(String inStr) throws IOException
107 super(inStr, "Paste");
111 * Creates a new NewickFile object.
118 * @throws IOException
121 public NewickFile(String inFile, String type) throws IOException
126 public NewickFile(FileParse source) throws IOException
132 * Creates a new NewickFile object.
137 public NewickFile(SequenceNode newtree)
143 * Creates a new NewickFile object.
150 public NewickFile(SequenceNode newtree, boolean bootstrap)
152 HasBootstrap = bootstrap;
157 * Creates a new NewickFile object.
166 public NewickFile(SequenceNode newtree, boolean bootstrap,
170 HasBootstrap = bootstrap;
171 HasDistances = distances;
175 * Creates a new NewickFile object.
183 * @param rootdistance
186 public NewickFile(SequenceNode newtree, boolean bootstrap,
187 boolean distances, boolean rootdistance)
190 HasBootstrap = bootstrap;
191 HasDistances = distances;
192 RootHasDistance = rootdistance;
209 * @return DOCUMENT ME!
211 private String ErrorStringrange(String Error, String Er, int r, int p,
214 return ((Error == null) ? "" : Error)
219 + s.substring(((p - r) < 0) ? 0 : (p - r),
220 ((p + r) > s.length()) ? s.length() : (p + r)) + " )\n";
224 // These are set automatically by the reader
225 public boolean HasBootstrap()
233 * @return DOCUMENT ME!
235 public boolean HasDistances()
240 public boolean HasRootDistance()
242 return RootHasDistance;
246 * parse the filesource as a newick file (new hampshire and/or extended)
248 * @throws IOException
249 * with a line number and character position for badly formatted NH
252 public void parse() throws IOException
256 { // fill nf with complete tree file
258 StringBuffer file = new StringBuffer();
260 while ((nf = nextLine()) != null)
265 nf = file.toString();
268 root = new SequenceNode();
270 SequenceNode realroot = null;
271 SequenceNode c = root;
275 // int flen = nf.length();
278 String nodename = null;
279 String commentString2 = null; // comments after simple node props
281 float DefDistance = (float) 0.001; // @param Default distance for a node -
283 int DefBootstrap = -1; // @param Default bootstrap for a node
285 float distance = DefDistance;
286 int bootstrap = DefBootstrap;
288 boolean ascending = false; // flag indicating that we are leaving the
291 com.stevesoft.pat.Regex majorsyms = new com.stevesoft.pat.Regex(
296 boolean parsednodename=false;
297 while (majorsyms.searchFrom(nf, cp) && (Error == null))
299 int fcp = majorsyms.matchedFrom();
301 switch (schar = nf.charAt(fcp))
305 // ascending should not be set
309 Error = ErrorStringrange(Error, "Unexpected '('", 7, fcp, nf);
317 if (c.right() == null)
319 c.setRight(new SequenceNode(null, c, null, DefDistance,
320 DefBootstrap, false));
321 c = (SequenceNode) c.right();
325 if (c.left() != null)
327 // Dummy node for polytomy - keeps c.left free for new node
328 SequenceNode tmpn = new SequenceNode(null, c, null, 0, 0, true);
329 tmpn.SetChildren(c.left(), c.right());
333 c.setLeft(new SequenceNode(null, c, null, DefDistance,
334 DefBootstrap, false));
335 c = (SequenceNode) c.left();
338 if (realroot == null)
344 distance = DefDistance;
345 bootstrap = DefBootstrap;
350 // Deal with quoted fields
353 com.stevesoft.pat.Regex qnodename = new com.stevesoft.pat.Regex(
356 if (qnodename.searchFrom(nf, fcp))
358 int nl = qnodename.stringMatched().length();
359 nodename = new String(qnodename.stringMatched().substring(1,
361 // unpack any escaped colons
362 com.stevesoft.pat.Regex xpandquotes = com.stevesoft.pat.Regex.perlCode("s/''/'/");
363 String widernodename = xpandquotes.replaceAll(nodename);
364 nodename=widernodename;
365 // jump to after end of quoted nodename
366 nextcp = fcp + nl + 1;
371 Error = ErrorStringrange(Error,
372 "Unterminated quotes for nodename", 7, fcp, nf);
382 Error = ErrorStringrange(Error, "Wayward semicolon (depth=" + d
385 // cp advanced at the end of default
389 // node string contains Comment or structured/extended NH format info
391 * if ((fcp-cp>1 && nf.substring(cp,fcp).trim().length()>1)) { // will
392 * process in remains System.err.println("skipped text:
393 * '"+nf.substring(cp,fcp)+"'"); }
395 // verify termination.
396 com.stevesoft.pat.Regex comment = new com.stevesoft.pat.Regex("]");
397 if (comment.searchFrom(nf, fcp))
399 // Skip the comment field
400 nextcp = comment.matchedFrom() + 1;
401 warningMessage = "Tree file contained comments which may confuse input algorithm.";
404 // cp advanced at the end of default to nextcp, ncp is unchanged so
405 // any node info can be read.
409 Error = ErrorStringrange(Error, "Unterminated comment", 3, fcp,
415 // Parse simpler field strings
416 String fstring = nf.substring(ncp, fcp);
417 // remove any comments before we parse the node info
418 // TODO: test newick file with quoted square brackets in node name (is
420 while (fstring.indexOf(']') > -1)
422 int cstart = fstring.indexOf('[');
423 int cend = fstring.indexOf(']');
424 commentString2 = fstring.substring(cstart + 1, cend);
425 fstring = fstring.substring(0, cstart)
426 + fstring.substring(cend + 1);
429 com.stevesoft.pat.Regex uqnodename = new com.stevesoft.pat.Regex(
430 "\\b([^' :;\\](),]+)");
431 com.stevesoft.pat.Regex nbootstrap = new com.stevesoft.pat.Regex(
432 "\\s*([0-9+]+)\\s*:");
433 com.stevesoft.pat.Regex ndist = new com.stevesoft.pat.Regex(
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).equals(
464 uqnodename.stringMatched(1)))
466 nodename = null; // no nodename here.
469 || nodename.length() == 0
470 || nbootstrap.matchedFrom(1) > (uqnodename.matchedFrom(1) + uqnodename
471 .stringMatched().length()))
475 bootstrap = (new Integer(nbootstrap.stringMatched(1)))
478 } catch (Exception e)
480 Error = ErrorStringrange(Error,
481 "Can't parse bootstrap value", 4,
482 ncp + nbootstrap.matchedFrom(), nf);
487 boolean nodehasdistance = false;
489 if (ndist.search(fstring))
493 distance = (new Float(ndist.stringMatched(1))).floatValue();
495 nodehasdistance = true;
496 } catch (Exception e)
498 Error = ErrorStringrange(Error,
499 "Can't parse node distance value", 7,
500 ncp + ndist.matchedFrom(), nf);
506 // Write node info here
508 // Trees without distances still need a render distance
509 c.dist = (HasDistances) ? distance : DefDistance;
510 // be consistent for internal bootstrap defaults too
511 c.setBootstrap((HasBootstrap) ? bootstrap : DefBootstrap);
514 RootHasDistance = nodehasdistance; // JBPNote This is really
515 // UGLY!!! Ensure root node gets
516 // its given distance
518 parseNHXNodeProps(c, commentString2);
519 commentString2 = null;
523 // Find a place to put the leaf
524 SequenceNode newnode = new SequenceNode(null, c, nodename,
525 (HasDistances) ? distance : DefDistance,
526 (HasBootstrap) ? bootstrap : DefBootstrap, false);
527 parseNHXNodeProps(c, commentString2);
528 commentString2 = null;
530 if (c.right() == null)
536 if (c.left() == null)
542 // Insert a dummy node for polytomy
543 // dummy nodes have distances
544 SequenceNode newdummy = new SequenceNode(null, c, null,
545 (HasDistances ? 0 : DefDistance), 0, true);
546 newdummy.SetChildren(c.left(), newnode);
554 // move back up the tree from preceding closure
557 if ((d > -1) && (c == null))
559 Error = ErrorStringrange(
561 "File broke algorithm: Lost place in tree (is there an extra ')' ?)",
566 if (nf.charAt(fcp) == ')')
573 if (nf.charAt(fcp) == ',')
581 // Just advance focus, if we need to
582 if ((c.left() != null) && (!c.left().isLeaf()))
584 c = (SequenceNode) c.left();
590 // Reset new node properties to obvious fakes
592 distance = DefDistance;
593 bootstrap = DefBootstrap;
594 commentString2 = null;
595 parsednodename=false;
610 throw (new IOException("NewickFile: " + Error + "\n"));
614 throw (new IOException("NewickFile: No Tree read in\n"));
616 // THe next line is failing for topali trees - not sure why yet. if
617 // (root.right()!=null && root.isDummy())
618 root = (SequenceNode) root.right().detach(); // remove the imaginary root.
620 if (!RootHasDistance)
622 root.dist = (HasDistances) ? 0 : DefDistance;
627 * parse NHX codes in comment strings and update NewickFile state flags for
628 * distances and bootstraps, and add any additional properties onto the node.
631 * @param commentString
632 * @param commentString2
634 private void parseNHXNodeProps(SequenceNode c, String commentString)
636 // TODO: store raw comment on the sequenceNode so it can be recovered when
638 if (commentString != null && commentString.startsWith("&&NHX"))
640 StringTokenizer st = new StringTokenizer(commentString.substring(5),
642 while (st.hasMoreTokens())
644 String tok = st.nextToken();
645 int colpos = tok.indexOf("=");
649 String code = tok.substring(0, colpos);
650 String value = tok.substring(colpos + 1);
653 // parse out code/value pairs
654 if (code.toLowerCase().equals("b"))
657 Float iv = new Float(value);
658 v = iv.intValue(); // jalview only does integer bootstraps
664 } catch (Exception e)
666 System.err.println("Couldn't parse code '" + code + "' = '"
668 e.printStackTrace(System.err);
679 * @return DOCUMENT ME!
681 public SequenceNode getTree()
687 * Generate a newick format tree according to internal flags for bootstraps,
688 * distances and root distances.
690 * @return new hampshire tree in a single line
692 public String print()
696 StringBuffer tf = new StringBuffer();
699 return (tf.append(";").toString());
706 * Generate a newick format tree according to internal flags for distances and
707 * root distances and user specificied writing of bootstraps.
709 * @param withbootstraps
710 * controls if bootstrap values are explicitly written.
712 * @return new hampshire tree in a single line
714 public String print(boolean withbootstraps)
718 boolean boots = this.HasBootstrap;
719 this.HasBootstrap = withbootstraps;
722 this.HasBootstrap = boots;
730 * Generate newick format tree according to internal flags for writing root
733 * @param withbootstraps
734 * explicitly write bootstrap values
736 * explicitly write distances
738 * @return new hampshire tree in a single line
740 public String print(boolean withbootstraps, boolean withdists)
744 boolean dists = this.HasDistances;
745 this.HasDistances = withdists;
747 String rv = print(withbootstraps);
748 this.HasDistances = dists;
755 * Generate newick format tree according to user specified flags
757 * @param withbootstraps
758 * explicitly write bootstrap values
760 * explicitly write distances
761 * @param printRootInfo
762 * explicitly write root distance
764 * @return new hampshire tree in a single line
766 public String print(boolean withbootstraps, boolean withdists,
767 boolean printRootInfo)
771 boolean rootinfo = printRootInfo;
772 this.printRootInfo = printRootInfo;
774 String rv = print(withbootstraps, withdists);
775 this.printRootInfo = rootinfo;
784 * @return DOCUMENT ME!
797 * @return DOCUMENT ME!
799 char setQuoteChar(char c)
801 char old = QuoteChar;
813 * @return DOCUMENT ME!
815 private String nodeName(String name)
817 if (NodeSafeName[0].search(name))
819 return QuoteChar + NodeSafeName[1].replaceAll(name) + QuoteChar;
823 return NodeSafeName[2].replaceAll(name);
833 * @return DOCUMENT ME!
835 private String printNodeField(SequenceNode c)
837 return ((c.getName() == null) ? "" : nodeName(c.getName()))
838 + ((HasBootstrap) ? ((c.getBootstrap() > -1) ? ((c.getName() != null ? " "
839 : "") + c.getBootstrap())
841 : "") + ((HasDistances) ? (":" + c.dist) : "");
850 * @return DOCUMENT ME!
852 private String printRootField(SequenceNode root)
854 return (printRootInfo) ? (((root.getName() == null) ? ""
855 : nodeName(root.getName()))
856 + ((HasBootstrap) ? ((root.getBootstrap() > -1) ? ((root
857 .getName() != null ? " " : "") + +root.getBootstrap())
858 : "") : "") + ((RootHasDistance) ? (":" + root.dist)
862 // Non recursive call deals with root node properties
863 public void print(StringBuffer tf, SequenceNode root)
867 if (root.isLeaf() && printRootInfo)
869 tf.append(printRootField(root));
875 _print(tf, (SequenceNode) root.right());
876 _print(tf, (SequenceNode) root.left());
881 _print(tf, (SequenceNode) root.right());
883 if (root.left() != null)
888 _print(tf, (SequenceNode) root.left());
889 tf.append(")" + printRootField(root));
895 // Recursive call for non-root nodes
896 public void _print(StringBuffer tf, SequenceNode c)
902 tf.append(printNodeField(c));
908 _print(tf, (SequenceNode) c.left());
909 if (c.left() != null)
913 _print(tf, (SequenceNode) c.right());
918 _print(tf, (SequenceNode) c.right());
920 if (c.left() != null)
925 _print(tf, (SequenceNode) c.left());
926 tf.append(")" + printNodeField(c));
933 public static void main(String[] args)
937 if (args == null || args.length != 1)
940 .println("Takes one argument - file name of a newick tree file.");
944 File fn = new File(args[0]);
946 StringBuffer newickfile = new StringBuffer();
947 BufferedReader treefile = new BufferedReader(new FileReader(fn));
950 while ((l = treefile.readLine()) != null)
952 newickfile.append(l);
956 System.out.println("Read file :\n");
958 NewickFile trf = new NewickFile(args[0], "File");
960 System.out.println("Original file :\n");
962 com.stevesoft.pat.Regex nonl = new com.stevesoft.pat.Regex("\n+", "");
963 System.out.println(nonl.replaceAll(newickfile.toString()) + "\n");
965 System.out.println("Parsed file.\n");
966 System.out.println("Default output type for original input.\n");
967 System.out.println(trf.print());
968 System.out.println("Without bootstraps.\n");
969 System.out.println(trf.print(false));
970 System.out.println("Without distances.\n");
971 System.out.println(trf.print(true, false));
972 System.out.println("Without bootstraps but with distanecs.\n");
973 System.out.println(trf.print(false, true));
974 System.out.println("Without bootstraps or distanecs.\n");
975 System.out.println(trf.print(false, false));
976 System.out.println("With bootstraps and with distances.\n");
977 System.out.println(trf.print(true, true));
978 } catch (java.io.IOException e)
980 System.err.println("Exception\n" + e);