2 * Jalview - A Sequence Alignment Editor and Viewer (Version 2.8)
3 * Copyright (C) 2012 J Procter, AM Waterhouse, LM Lui, J Engelhardt, G Barton, M Clamp, S Searle
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/>.
20 // http://evolution.genetics.washington.edu/phylip/newick_doc.html
21 // TODO: Implement Basic NHX tag parsing and preservation
22 // TODO: http://evolution.genetics.wustl.edu/eddy/forester/NHX.html
23 // TODO: Extended SequenceNodeI to hold parsed NHX strings
27 import java.util.StringTokenizer;
29 import jalview.datamodel.*;
32 * Parse a new hanpshire style tree Caveats: NHX files are NOT supported and the
33 * tree distances and topology are unreliable when they are parsed. TODO: on
34 * this: NHX codes are appended in comments beginning with &&NHX. The codes are
35 * given below (from http://www.phylosoft.org/forester/NHX.html): Element Type
36 * Description Corresponding phyloXML element (parent element in parentheses) no
37 * tag string name of this node/clade (MUST BE FIRST, IF ASSIGNED)
38 * <name>(<clade>) : decimal branch length to parent node (MUST BE SECOND, IF
39 * ASSIGNED) <branch_length>(<clade>) :GN= string gene name <name>(<sequence>)
40 * :AC= string sequence accession <accession>(<sequence>) :ND= string node
41 * identifier - if this is being used, it has to be unique within each phylogeny
42 * <node_id>(<clade>) :B= decimal confidence value for parent branch
43 * <confidence>(<clade>) :D= 'T', 'F', or '?' 'T' if this node represents a
44 * duplication event - 'F' if this node represents a speciation event, '?' if
45 * this node represents an unknown event (D= tag should be replaced by Ev= tag)
46 * n/a :Ev=duplications>speciations>gene losses>event type>duplication type int
47 * int int string string event (replaces the =D tag), number of duplication,
48 * speciation, and gene loss events, type of event (transfer, fusion, root,
49 * unknown, other, speciation_duplication_loss, unassigned) <events>(<clade>)
50 * :E= string EC number at this node <annotation>(<sequence>) :Fu= string
51 * function at this node <annotation>(<sequence>)
52 * :DS=protein-length>from>to>support>name>from>... int int int double string
53 * int ... domain structure at this node <domain_architecture>(<sequence>) :S=
54 * string species name of the species/phylum at this node <taxonomy>(<clade>)
55 * :T= integer taxonomy ID of the species/phylum at this node <id>(<taxonomy>)
56 * :W= integer width of parent branch <width>(<clade>) :C=rrr.ggg.bbb
57 * integer.integer.integer color of parent branch <color>(<clade>) :Co= 'Y' or
58 * 'N' collapse this node when drawing the tree (default is not to collapse) n/a
59 * :XB= string custom data associated with a branch <property>(<clade>) :XN=
60 * string custom data associated with a node <property>(<clade>) :O= integer
61 * orthologous to this external node n/a :SN= integer subtree neighbors n/a :SO=
62 * integer super orthologous (no duplications on paths) to this external node
68 public class NewickFile extends FileParse
72 private boolean HasBootstrap = false;
74 private boolean HasDistances = false;
76 private boolean RootHasDistance = false;
79 boolean ReplaceUnderscores = false;
81 boolean printRootInfo = true;
83 private com.stevesoft.pat.Regex[] NodeSafeName = new com.stevesoft.pat.Regex[]
84 { new com.stevesoft.pat.Regex().perlCode("m/[\\[,:'()]/"), // test for
87 new com.stevesoft.pat.Regex().perlCode("s/'/''/"), // escaping quote
89 new com.stevesoft.pat.Regex().perlCode("s/\\/w/_/") // unqoted whitespace
93 char QuoteChar = '\'';
96 * Creates a new NewickFile object.
101 * @throws IOException
104 public NewickFile(String inStr) throws IOException
106 super(inStr, "Paste");
110 * Creates a new NewickFile object.
117 * @throws IOException
120 public NewickFile(String inFile, String type) throws IOException
125 public NewickFile(FileParse source) throws IOException
131 * Creates a new NewickFile object.
136 public NewickFile(SequenceNode newtree)
142 * Creates a new NewickFile object.
149 public NewickFile(SequenceNode newtree, boolean bootstrap)
151 HasBootstrap = bootstrap;
156 * Creates a new NewickFile object.
165 public NewickFile(SequenceNode newtree, boolean bootstrap,
169 HasBootstrap = bootstrap;
170 HasDistances = distances;
174 * Creates a new NewickFile object.
182 * @param rootdistance
185 public NewickFile(SequenceNode newtree, boolean bootstrap,
186 boolean distances, boolean rootdistance)
189 HasBootstrap = bootstrap;
190 HasDistances = distances;
191 RootHasDistance = rootdistance;
208 * @return DOCUMENT ME!
210 private String ErrorStringrange(String Error, String Er, int r, int p,
213 return ((Error == null) ? "" : Error)
218 + s.substring(((p - r) < 0) ? 0 : (p - r),
219 ((p + r) > s.length()) ? s.length() : (p + r)) + " )\n";
223 // These are set automatically by the reader
224 public boolean HasBootstrap()
232 * @return DOCUMENT ME!
234 public boolean HasDistances()
239 public boolean HasRootDistance()
241 return RootHasDistance;
245 * parse the filesource as a newick file (new hampshire and/or extended)
247 * @throws IOException
248 * with a line number and character position for badly formatted NH
251 public void parse() throws IOException
255 { // fill nf with complete tree file
257 StringBuffer file = new StringBuffer();
259 while ((nf = nextLine()) != null)
264 nf = file.toString();
267 root = new SequenceNode();
269 SequenceNode realroot = null;
270 SequenceNode c = root;
274 // int flen = nf.length();
277 String nodename = null;
278 String commentString2 = null; // comments after simple node props
280 float DefDistance = (float) 0.001; // @param Default distance for a node -
282 int DefBootstrap = -1; // @param Default bootstrap for a node
284 float distance = DefDistance;
285 int bootstrap = DefBootstrap;
287 boolean ascending = false; // flag indicating that we are leaving the
290 com.stevesoft.pat.Regex majorsyms = new com.stevesoft.pat.Regex(
295 boolean parsednodename=false;
296 while (majorsyms.searchFrom(nf, cp) && (Error == null))
298 int fcp = majorsyms.matchedFrom();
300 switch (schar = nf.charAt(fcp))
304 // ascending should not be set
308 Error = ErrorStringrange(Error, "Unexpected '('", 7, fcp, nf);
316 if (c.right() == null)
318 c.setRight(new SequenceNode(null, c, null, DefDistance,
319 DefBootstrap, false));
320 c = (SequenceNode) c.right();
324 if (c.left() != null)
326 // Dummy node for polytomy - keeps c.left free for new node
327 SequenceNode tmpn = new SequenceNode(null, c, null, 0, 0, true);
328 tmpn.SetChildren(c.left(), c.right());
332 c.setLeft(new SequenceNode(null, c, null, DefDistance,
333 DefBootstrap, false));
334 c = (SequenceNode) c.left();
337 if (realroot == null)
343 distance = DefDistance;
344 bootstrap = DefBootstrap;
349 // Deal with quoted fields
352 com.stevesoft.pat.Regex qnodename = new com.stevesoft.pat.Regex(
355 if (qnodename.searchFrom(nf, fcp))
357 int nl = qnodename.stringMatched().length();
358 nodename = new String(qnodename.stringMatched().substring(1,
360 // unpack any escaped colons
361 com.stevesoft.pat.Regex xpandquotes = com.stevesoft.pat.Regex.perlCode("s/''/'/");
362 String widernodename = xpandquotes.replaceAll(nodename);
363 nodename=widernodename;
364 // jump to after end of quoted nodename
365 nextcp = fcp + nl + 1;
370 Error = ErrorStringrange(Error,
371 "Unterminated quotes for nodename", 7, fcp, nf);
381 Error = ErrorStringrange(Error, "Wayward semicolon (depth=" + d
384 // cp advanced at the end of default
388 // node string contains Comment or structured/extended NH format info
390 * if ((fcp-cp>1 && nf.substring(cp,fcp).trim().length()>1)) { // will
391 * process in remains System.err.println("skipped text:
392 * '"+nf.substring(cp,fcp)+"'"); }
394 // verify termination.
395 com.stevesoft.pat.Regex comment = new com.stevesoft.pat.Regex("]");
396 if (comment.searchFrom(nf, fcp))
398 // Skip the comment field
399 nextcp = comment.matchedFrom() + 1;
400 warningMessage = "Tree file contained comments which may confuse input algorithm.";
403 // cp advanced at the end of default to nextcp, ncp is unchanged so
404 // any node info can be read.
408 Error = ErrorStringrange(Error, "Unterminated comment", 3, fcp,
414 // Parse simpler field strings
415 String fstring = nf.substring(ncp, fcp);
416 // remove any comments before we parse the node info
417 // TODO: test newick file with quoted square brackets in node name (is
419 while (fstring.indexOf(']') > -1)
421 int cstart = fstring.indexOf('[');
422 int cend = fstring.indexOf(']');
423 commentString2 = fstring.substring(cstart + 1, cend);
424 fstring = fstring.substring(0, cstart)
425 + fstring.substring(cend + 1);
428 com.stevesoft.pat.Regex uqnodename = new com.stevesoft.pat.Regex(
429 "\\b([^' :;\\](),]+)");
430 com.stevesoft.pat.Regex nbootstrap = new com.stevesoft.pat.Regex(
431 "\\s*([0-9+]+)\\s*:");
432 com.stevesoft.pat.Regex ndist = new com.stevesoft.pat.Regex(
435 if (!parsednodename && uqnodename.search(fstring)
436 && ((uqnodename.matchedFrom(1) == 0) || (fstring
437 .charAt(uqnodename.matchedFrom(1) - 1) != ':'))) // JBPNote
440 if (nodename == null)
442 if (ReplaceUnderscores)
444 nodename = uqnodename.stringMatched(1).replace('_', ' ');
448 nodename = uqnodename.stringMatched(1);
453 Error = ErrorStringrange(Error,
454 "File has broken algorithm - overwritten nodename", 10,
458 // get comment bootstraps
460 if (nbootstrap.search(fstring))
462 if (nbootstrap.stringMatched(1).equals(
463 uqnodename.stringMatched(1)))
465 nodename = null; // no nodename here.
468 || nodename.length() == 0
469 || nbootstrap.matchedFrom(1) > (uqnodename.matchedFrom(1) + uqnodename
470 .stringMatched().length()))
474 bootstrap = (new Integer(nbootstrap.stringMatched(1)))
477 } catch (Exception e)
479 Error = ErrorStringrange(Error,
480 "Can't parse bootstrap value", 4,
481 ncp + nbootstrap.matchedFrom(), nf);
486 boolean nodehasdistance = false;
488 if (ndist.search(fstring))
492 distance = (new Float(ndist.stringMatched(1))).floatValue();
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 SequenceNode 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 SequenceNode 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(
560 "File broke algorithm: Lost place in tree (is there an extra ')' ?)",
565 if (nf.charAt(fcp) == ')')
572 if (nf.charAt(fcp) == ',')
580 // Just advance focus, if we need to
581 if ((c.left() != null) && (!c.left().isLeaf()))
583 c = (SequenceNode) c.left();
589 // Reset new node properties to obvious fakes
591 distance = DefDistance;
592 bootstrap = DefBootstrap;
593 commentString2 = null;
594 parsednodename=false;
609 throw (new IOException("NewickFile: " + Error + "\n"));
613 throw (new IOException("NewickFile: No Tree read in\n"));
615 // THe next line is failing for topali trees - not sure why yet. if
616 // (root.right()!=null && root.isDummy())
617 root = (SequenceNode) root.right().detach(); // remove the imaginary root.
619 if (!RootHasDistance)
621 root.dist = (HasDistances) ? 0 : DefDistance;
626 * parse NHX codes in comment strings and update NewickFile state flags for
627 * distances and bootstraps, and add any additional properties onto the node.
630 * @param commentString
631 * @param commentString2
633 private void parseNHXNodeProps(SequenceNode c, String commentString)
635 // TODO: store raw comment on the sequenceNode so it can be recovered when
637 if (commentString != null && commentString.startsWith("&&NHX"))
639 StringTokenizer st = new StringTokenizer(commentString.substring(5),
641 while (st.hasMoreTokens())
643 String tok = st.nextToken();
644 int colpos = tok.indexOf("=");
648 String code = tok.substring(0, colpos);
649 String value = tok.substring(colpos + 1);
652 // parse out code/value pairs
653 if (code.toLowerCase().equals("b"))
656 Float iv = new Float(value);
657 v = iv.intValue(); // jalview only does integer bootstraps
663 } catch (Exception e)
665 System.err.println("Couldn't parse code '" + code + "' = '"
667 e.printStackTrace(System.err);
678 * @return DOCUMENT ME!
680 public SequenceNode getTree()
686 * Generate a newick format tree according to internal flags for bootstraps,
687 * distances and root distances.
689 * @return new hampshire tree in a single line
691 public String print()
695 StringBuffer tf = new StringBuffer();
698 return (tf.append(";").toString());
705 * Generate a newick format tree according to internal flags for distances and
706 * root distances and user specificied writing of bootstraps.
708 * @param withbootstraps
709 * controls if bootstrap values are explicitly written.
711 * @return new hampshire tree in a single line
713 public String print(boolean withbootstraps)
717 boolean boots = this.HasBootstrap;
718 this.HasBootstrap = withbootstraps;
721 this.HasBootstrap = boots;
729 * Generate newick format tree according to internal flags for writing root
732 * @param withbootstraps
733 * explicitly write bootstrap values
735 * explicitly write distances
737 * @return new hampshire tree in a single line
739 public String print(boolean withbootstraps, boolean withdists)
743 boolean dists = this.HasDistances;
744 this.HasDistances = withdists;
746 String rv = print(withbootstraps);
747 this.HasDistances = dists;
754 * Generate newick format tree according to user specified flags
756 * @param withbootstraps
757 * explicitly write bootstrap values
759 * explicitly write distances
760 * @param printRootInfo
761 * explicitly write root distance
763 * @return new hampshire tree in a single line
765 public String print(boolean withbootstraps, boolean withdists,
766 boolean printRootInfo)
770 boolean rootinfo = printRootInfo;
771 this.printRootInfo = printRootInfo;
773 String rv = print(withbootstraps, withdists);
774 this.printRootInfo = rootinfo;
783 * @return DOCUMENT ME!
796 * @return DOCUMENT ME!
798 char setQuoteChar(char c)
800 char old = QuoteChar;
812 * @return DOCUMENT ME!
814 private String nodeName(String name)
816 if (NodeSafeName[0].search(name))
818 return QuoteChar + NodeSafeName[1].replaceAll(name) + QuoteChar;
822 return NodeSafeName[2].replaceAll(name);
832 * @return DOCUMENT ME!
834 private String printNodeField(SequenceNode c)
836 return ((c.getName() == null) ? "" : nodeName(c.getName()))
837 + ((HasBootstrap) ? ((c.getBootstrap() > -1) ? ((c.getName() != null ? " "
838 : "") + c.getBootstrap())
840 : "") + ((HasDistances) ? (":" + c.dist) : "");
849 * @return DOCUMENT ME!
851 private String printRootField(SequenceNode root)
853 return (printRootInfo) ? (((root.getName() == null) ? ""
854 : nodeName(root.getName()))
855 + ((HasBootstrap) ? ((root.getBootstrap() > -1) ? ((root
856 .getName() != null ? " " : "") + +root.getBootstrap())
857 : "") : "") + ((RootHasDistance) ? (":" + root.dist)
861 // Non recursive call deals with root node properties
862 public void print(StringBuffer tf, SequenceNode root)
866 if (root.isLeaf() && printRootInfo)
868 tf.append(printRootField(root));
874 _print(tf, (SequenceNode) root.right());
875 _print(tf, (SequenceNode) root.left());
880 _print(tf, (SequenceNode) root.right());
882 if (root.left() != null)
887 _print(tf, (SequenceNode) root.left());
888 tf.append(")" + printRootField(root));
894 // Recursive call for non-root nodes
895 public void _print(StringBuffer tf, SequenceNode c)
901 tf.append(printNodeField(c));
907 _print(tf, (SequenceNode) c.left());
908 if (c.left() != null)
912 _print(tf, (SequenceNode) c.right());
917 _print(tf, (SequenceNode) c.right());
919 if (c.left() != null)
924 _print(tf, (SequenceNode) c.left());
925 tf.append(")" + printNodeField(c));
932 public static void main(String[] args)
936 if (args == null || args.length != 1)
939 .println("Takes one argument - file name of a newick tree file.");
943 File fn = new File(args[0]);
945 StringBuffer newickfile = new StringBuffer();
946 BufferedReader treefile = new BufferedReader(new FileReader(fn));
949 while ((l = treefile.readLine()) != null)
951 newickfile.append(l);
955 System.out.println("Read file :\n");
957 NewickFile trf = new NewickFile(args[0], "File");
959 System.out.println("Original file :\n");
961 com.stevesoft.pat.Regex nonl = new com.stevesoft.pat.Regex("\n+", "");
962 System.out.println(nonl.replaceAll(newickfile.toString()) + "\n");
964 System.out.println("Parsed file.\n");
965 System.out.println("Default output type for original input.\n");
966 System.out.println(trf.print());
967 System.out.println("Without bootstraps.\n");
968 System.out.println(trf.print(false));
969 System.out.println("Without distances.\n");
970 System.out.println(trf.print(true, false));
971 System.out.println("Without bootstraps but with distanecs.\n");
972 System.out.println(trf.print(false, true));
973 System.out.println("Without bootstraps or distanecs.\n");
974 System.out.println(trf.print(false, false));
975 System.out.println("With bootstraps and with distances.\n");
976 System.out.println(trf.print(true, true));
977 } catch (java.io.IOException e)
979 System.err.println("Exception\n" + e);