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 // jump to after end of quoted nodename
361 nextcp = fcp + nl + 1;
366 Error = ErrorStringrange(Error,
367 "Unterminated quotes for nodename", 7, fcp, nf);
377 Error = ErrorStringrange(Error, "Wayward semicolon (depth=" + d
380 // cp advanced at the end of default
384 // node string contains Comment or structured/extended NH format info
386 * if ((fcp-cp>1 && nf.substring(cp,fcp).trim().length()>1)) { // will
387 * process in remains System.err.println("skipped text:
388 * '"+nf.substring(cp,fcp)+"'"); }
390 // verify termination.
391 com.stevesoft.pat.Regex comment = new com.stevesoft.pat.Regex("]");
392 if (comment.searchFrom(nf, fcp))
394 // Skip the comment field
395 nextcp = comment.matchedFrom() + 1;
396 warningMessage = "Tree file contained comments which may confuse input algorithm.";
399 // cp advanced at the end of default to nextcp, ncp is unchanged so
400 // any node info can be read.
404 Error = ErrorStringrange(Error, "Unterminated comment", 3, fcp,
410 // Parse simpler field strings
411 String fstring = nf.substring(ncp, fcp);
412 // remove any comments before we parse the node info
413 // TODO: test newick file with quoted square brackets in node name (is
415 while (fstring.indexOf(']') > -1)
417 int cstart = fstring.indexOf('[');
418 int cend = fstring.indexOf(']');
419 commentString2 = fstring.substring(cstart + 1, cend);
420 fstring = fstring.substring(0, cstart)
421 + fstring.substring(cend + 1);
424 com.stevesoft.pat.Regex uqnodename = new com.stevesoft.pat.Regex(
425 "\\b([^' :;\\](),]+)");
426 com.stevesoft.pat.Regex nbootstrap = new com.stevesoft.pat.Regex(
427 "\\s*([0-9+]+)\\s*:");
428 com.stevesoft.pat.Regex ndist = new com.stevesoft.pat.Regex(
431 if (!parsednodename && uqnodename.search(fstring)
432 && ((uqnodename.matchedFrom(1) == 0) || (fstring
433 .charAt(uqnodename.matchedFrom(1) - 1) != ':'))) // JBPNote
436 if (nodename == null)
438 if (ReplaceUnderscores)
440 nodename = uqnodename.stringMatched(1).replace('_', ' ');
444 nodename = uqnodename.stringMatched(1);
449 Error = ErrorStringrange(Error,
450 "File has broken algorithm - overwritten nodename", 10,
454 // get comment bootstraps
456 if (nbootstrap.search(fstring))
458 if (nbootstrap.stringMatched(1).equals(
459 uqnodename.stringMatched(1)))
461 nodename = null; // no nodename here.
464 || nodename.length() == 0
465 || nbootstrap.matchedFrom(1) > (uqnodename.matchedFrom(1) + uqnodename
466 .stringMatched().length()))
470 bootstrap = (new Integer(nbootstrap.stringMatched(1)))
473 } catch (Exception e)
475 Error = ErrorStringrange(Error,
476 "Can't parse bootstrap value", 4,
477 ncp + nbootstrap.matchedFrom(), nf);
482 boolean nodehasdistance = false;
484 if (ndist.search(fstring))
488 distance = (new Float(ndist.stringMatched(1))).floatValue();
490 nodehasdistance = true;
491 } catch (Exception e)
493 Error = ErrorStringrange(Error,
494 "Can't parse node distance value", 7,
495 ncp + ndist.matchedFrom(), nf);
501 // Write node info here
503 // Trees without distances still need a render distance
504 c.dist = (HasDistances) ? distance : DefDistance;
505 // be consistent for internal bootstrap defaults too
506 c.setBootstrap((HasBootstrap) ? bootstrap : DefBootstrap);
509 RootHasDistance = nodehasdistance; // JBPNote This is really
510 // UGLY!!! Ensure root node gets
511 // its given distance
513 parseNHXNodeProps(c, commentString2);
514 commentString2 = null;
518 // Find a place to put the leaf
519 SequenceNode newnode = new SequenceNode(null, c, nodename,
520 (HasDistances) ? distance : DefDistance,
521 (HasBootstrap) ? bootstrap : DefBootstrap, false);
522 parseNHXNodeProps(c, commentString2);
523 commentString2 = null;
525 if (c.right() == null)
531 if (c.left() == null)
537 // Insert a dummy node for polytomy
538 // dummy nodes have distances
539 SequenceNode newdummy = new SequenceNode(null, c, null,
540 (HasDistances ? 0 : DefDistance), 0, true);
541 newdummy.SetChildren(c.left(), newnode);
549 // move back up the tree from preceding closure
552 if ((d > -1) && (c == null))
554 Error = ErrorStringrange(
556 "File broke algorithm: Lost place in tree (is there an extra ')' ?)",
561 if (nf.charAt(fcp) == ')')
568 if (nf.charAt(fcp) == ',')
576 // Just advance focus, if we need to
577 if ((c.left() != null) && (!c.left().isLeaf()))
579 c = (SequenceNode) c.left();
585 // Reset new node properties to obvious fakes
587 distance = DefDistance;
588 bootstrap = DefBootstrap;
589 commentString2 = null;
590 parsednodename=false;
605 throw (new IOException("NewickFile: " + Error + "\n"));
609 throw (new IOException("NewickFile: No Tree read in\n"));
611 // THe next line is failing for topali trees - not sure why yet. if
612 // (root.right()!=null && root.isDummy())
613 root = (SequenceNode) root.right().detach(); // remove the imaginary root.
615 if (!RootHasDistance)
617 root.dist = (HasDistances) ? 0 : DefDistance;
622 * parse NHX codes in comment strings and update NewickFile state flags for
623 * distances and bootstraps, and add any additional properties onto the node.
626 * @param commentString
627 * @param commentString2
629 private void parseNHXNodeProps(SequenceNode c, String commentString)
631 // TODO: store raw comment on the sequenceNode so it can be recovered when
633 if (commentString != null && commentString.startsWith("&&NHX"))
635 StringTokenizer st = new StringTokenizer(commentString.substring(5),
637 while (st.hasMoreTokens())
639 String tok = st.nextToken();
640 int colpos = tok.indexOf("=");
644 String code = tok.substring(0, colpos);
645 String value = tok.substring(colpos + 1);
648 // parse out code/value pairs
649 if (code.toLowerCase().equals("b"))
652 Float iv = new Float(value);
653 v = iv.intValue(); // jalview only does integer bootstraps
659 } catch (Exception e)
661 System.err.println("Couldn't parse code '" + code + "' = '"
663 e.printStackTrace(System.err);
674 * @return DOCUMENT ME!
676 public SequenceNode getTree()
682 * Generate a newick format tree according to internal flags for bootstraps,
683 * distances and root distances.
685 * @return new hampshire tree in a single line
687 public String print()
691 StringBuffer tf = new StringBuffer();
694 return (tf.append(";").toString());
701 * Generate a newick format tree according to internal flags for distances and
702 * root distances and user specificied writing of bootstraps.
704 * @param withbootstraps
705 * controls if bootstrap values are explicitly written.
707 * @return new hampshire tree in a single line
709 public String print(boolean withbootstraps)
713 boolean boots = this.HasBootstrap;
714 this.HasBootstrap = withbootstraps;
717 this.HasBootstrap = boots;
725 * Generate newick format tree according to internal flags for writing root
728 * @param withbootstraps
729 * explicitly write bootstrap values
731 * explicitly write distances
733 * @return new hampshire tree in a single line
735 public String print(boolean withbootstraps, boolean withdists)
739 boolean dists = this.HasDistances;
740 this.HasDistances = withdists;
742 String rv = print(withbootstraps);
743 this.HasDistances = dists;
750 * Generate newick format tree according to user specified flags
752 * @param withbootstraps
753 * explicitly write bootstrap values
755 * explicitly write distances
756 * @param printRootInfo
757 * explicitly write root distance
759 * @return new hampshire tree in a single line
761 public String print(boolean withbootstraps, boolean withdists,
762 boolean printRootInfo)
766 boolean rootinfo = printRootInfo;
767 this.printRootInfo = printRootInfo;
769 String rv = print(withbootstraps, withdists);
770 this.printRootInfo = rootinfo;
779 * @return DOCUMENT ME!
792 * @return DOCUMENT ME!
794 char setQuoteChar(char c)
796 char old = QuoteChar;
808 * @return DOCUMENT ME!
810 private String nodeName(String name)
812 if (NodeSafeName[0].search(name))
814 return QuoteChar + NodeSafeName[1].replaceAll(name) + QuoteChar;
818 return NodeSafeName[2].replaceAll(name);
828 * @return DOCUMENT ME!
830 private String printNodeField(SequenceNode c)
832 return ((c.getName() == null) ? "" : nodeName(c.getName()))
833 + ((HasBootstrap) ? ((c.getBootstrap() > -1) ? ((c.getName() != null ? " "
834 : "") + c.getBootstrap())
836 : "") + ((HasDistances) ? (":" + c.dist) : "");
845 * @return DOCUMENT ME!
847 private String printRootField(SequenceNode root)
849 return (printRootInfo) ? (((root.getName() == null) ? ""
850 : nodeName(root.getName()))
851 + ((HasBootstrap) ? ((root.getBootstrap() > -1) ? ((root
852 .getName() != null ? " " : "") + +root.getBootstrap())
853 : "") : "") + ((RootHasDistance) ? (":" + root.dist)
857 // Non recursive call deals with root node properties
858 public void print(StringBuffer tf, SequenceNode root)
862 if (root.isLeaf() && printRootInfo)
864 tf.append(printRootField(root));
870 _print(tf, (SequenceNode) root.right());
871 _print(tf, (SequenceNode) root.left());
876 _print(tf, (SequenceNode) root.right());
878 if (root.left() != null)
883 _print(tf, (SequenceNode) root.left());
884 tf.append(")" + printRootField(root));
890 // Recursive call for non-root nodes
891 public void _print(StringBuffer tf, SequenceNode c)
897 tf.append(printNodeField(c));
903 _print(tf, (SequenceNode) c.left());
904 if (c.left() != null)
908 _print(tf, (SequenceNode) c.right());
913 _print(tf, (SequenceNode) c.right());
915 if (c.left() != null)
920 _print(tf, (SequenceNode) c.left());
921 tf.append(")" + printNodeField(c));
928 public static void main(String[] args)
932 if (args == null || args.length != 1)
935 .println("Takes one argument - file name of a newick tree file.");
939 File fn = new File(args[0]);
941 StringBuffer newickfile = new StringBuffer();
942 BufferedReader treefile = new BufferedReader(new FileReader(fn));
945 while ((l = treefile.readLine()) != null)
947 newickfile.append(l);
951 System.out.println("Read file :\n");
953 NewickFile trf = new NewickFile(args[0], "File");
955 System.out.println("Original file :\n");
957 com.stevesoft.pat.Regex nonl = new com.stevesoft.pat.Regex("\n+", "");
958 System.out.println(nonl.replaceAll(newickfile.toString()) + "\n");
960 System.out.println("Parsed file.\n");
961 System.out.println("Default output type for original input.\n");
962 System.out.println(trf.print());
963 System.out.println("Without bootstraps.\n");
964 System.out.println(trf.print(false));
965 System.out.println("Without distances.\n");
966 System.out.println(trf.print(true, false));
967 System.out.println("Without bootstraps but with distanecs.\n");
968 System.out.println(trf.print(false, true));
969 System.out.println("Without bootstraps or distanecs.\n");
970 System.out.println(trf.print(false, false));
971 System.out.println("With bootstraps and with distances.\n");
972 System.out.println(trf.print(true, true));
973 } catch (java.io.IOException e)
975 System.err.println("Exception\n" + e);