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
30 import java.util.StringTokenizer;
32 import jalview.datamodel.*;
33 import jalview.util.MessageManager;
36 * Parse a new hanpshire style tree Caveats: NHX files are NOT supported and the
37 * tree distances and topology are unreliable when they are parsed. TODO: on
38 * this: NHX codes are appended in comments beginning with &&NHX. The codes are
39 * given below (from http://www.phylosoft.org/forester/NHX.html): Element Type
40 * Description Corresponding phyloXML element (parent element in parentheses) no
41 * tag string name of this node/clade (MUST BE FIRST, IF ASSIGNED)
42 * <name>(<clade>) : decimal branch length to parent node (MUST BE SECOND, IF
43 * ASSIGNED) <branch_length>(<clade>) :GN= string gene name <name>(<sequence>)
44 * :AC= string sequence accession <accession>(<sequence>) :ND= string node
45 * identifier - if this is being used, it has to be unique within each phylogeny
46 * <node_id>(<clade>) :B= decimal confidence value for parent branch
47 * <confidence>(<clade>) :D= 'T', 'F', or '?' 'T' if this node represents a
48 * duplication event - 'F' if this node represents a speciation event, '?' if
49 * this node represents an unknown event (D= tag should be replaced by Ev= tag)
50 * n/a :Ev=duplications>speciations>gene losses>event type>duplication type int
51 * int int string string event (replaces the =D tag), number of duplication,
52 * speciation, and gene loss events, type of event (transfer, fusion, root,
53 * unknown, other, speciation_duplication_loss, unassigned) <events>(<clade>)
54 * :E= string EC number at this node <annotation>(<sequence>) :Fu= string
55 * function at this node <annotation>(<sequence>)
56 * :DS=protein-length>from>to>support>name>from>... int int int double string
57 * int ... domain structure at this node <domain_architecture>(<sequence>) :S=
58 * string species name of the species/phylum at this node <taxonomy>(<clade>)
59 * :T= integer taxonomy ID of the species/phylum at this node <id>(<taxonomy>)
60 * :W= integer width of parent branch <width>(<clade>) :C=rrr.ggg.bbb
61 * integer.integer.integer color of parent branch <color>(<clade>) :Co= 'Y' or
62 * 'N' collapse this node when drawing the tree (default is not to collapse) n/a
63 * :XB= string custom data associated with a branch <property>(<clade>) :XN=
64 * string custom data associated with a node <property>(<clade>) :O= integer
65 * orthologous to this external node n/a :SN= integer subtree neighbors n/a :SO=
66 * integer super orthologous (no duplications on paths) to this external node
72 public class NewickFile extends FileParse
76 private boolean HasBootstrap = false;
78 private boolean HasDistances = false;
80 private boolean RootHasDistance = false;
83 boolean ReplaceUnderscores = false;
85 boolean printRootInfo = true;
87 private com.stevesoft.pat.Regex[] NodeSafeName = new com.stevesoft.pat.Regex[]
88 { new com.stevesoft.pat.Regex().perlCode("m/[\\[,:'()]/"), // test for
91 new com.stevesoft.pat.Regex().perlCode("s/'/''/"), // escaping quote
93 new com.stevesoft.pat.Regex().perlCode("s/\\/w/_/") // unqoted whitespace
97 char QuoteChar = '\'';
100 * Creates a new NewickFile object.
105 * @throws IOException
108 public NewickFile(String inStr) throws IOException
110 super(inStr, "Paste");
114 * Creates a new NewickFile object.
121 * @throws IOException
124 public NewickFile(String inFile, String type) throws IOException
129 public NewickFile(FileParse source) throws IOException
135 * Creates a new NewickFile object.
140 public NewickFile(SequenceNode newtree)
146 * Creates a new NewickFile object.
153 public NewickFile(SequenceNode newtree, boolean bootstrap)
155 HasBootstrap = bootstrap;
160 * Creates a new NewickFile object.
169 public NewickFile(SequenceNode newtree, boolean bootstrap,
173 HasBootstrap = bootstrap;
174 HasDistances = distances;
178 * Creates a new NewickFile object.
186 * @param rootdistance
189 public NewickFile(SequenceNode newtree, boolean bootstrap,
190 boolean distances, boolean rootdistance)
193 HasBootstrap = bootstrap;
194 HasDistances = distances;
195 RootHasDistance = rootdistance;
212 * @return DOCUMENT ME!
214 private String ErrorStringrange(String Error, String Er, int r, int p,
217 return ((Error == null) ? "" : Error)
222 + s.substring(((p - r) < 0) ? 0 : (p - r),
223 ((p + r) > s.length()) ? s.length() : (p + r)) + " )\n";
227 // These are set automatically by the reader
228 public boolean HasBootstrap()
236 * @return DOCUMENT ME!
238 public boolean HasDistances()
243 public boolean HasRootDistance()
245 return RootHasDistance;
249 * parse the filesource as a newick file (new hampshire and/or extended)
251 * @throws IOException
252 * with a line number and character position for badly formatted NH
255 public void parse() throws IOException
259 { // fill nf with complete tree file
261 StringBuffer file = new StringBuffer();
263 while ((nf = nextLine()) != null)
268 nf = file.toString();
271 root = new SequenceNode();
273 SequenceNode realroot = null;
274 SequenceNode c = root;
278 // int flen = nf.length();
281 String nodename = null;
282 String commentString2 = null; // comments after simple node props
284 float DefDistance = (float) 0.001; // @param Default distance for a node -
286 int DefBootstrap = -1; // @param Default bootstrap for a node
288 float distance = DefDistance;
289 int bootstrap = DefBootstrap;
291 boolean ascending = false; // flag indicating that we are leaving the
294 com.stevesoft.pat.Regex majorsyms = new com.stevesoft.pat.Regex(
299 boolean parsednodename = false;
300 while (majorsyms.searchFrom(nf, cp) && (Error == null))
302 int fcp = majorsyms.matchedFrom();
304 switch (schar = nf.charAt(fcp))
308 // ascending should not be set
312 Error = ErrorStringrange(Error, "Unexpected '('", 7, fcp, nf);
320 if (c.right() == null)
322 c.setRight(new SequenceNode(null, c, null, DefDistance,
323 DefBootstrap, false));
324 c = (SequenceNode) c.right();
328 if (c.left() != null)
330 // Dummy node for polytomy - keeps c.left free for new node
331 SequenceNode tmpn = new SequenceNode(null, c, null, 0, 0, true);
332 tmpn.SetChildren(c.left(), c.right());
336 c.setLeft(new SequenceNode(null, c, null, DefDistance,
337 DefBootstrap, false));
338 c = (SequenceNode) c.left();
341 if (realroot == null)
347 distance = DefDistance;
348 bootstrap = DefBootstrap;
353 // Deal with quoted fields
356 com.stevesoft.pat.Regex qnodename = new com.stevesoft.pat.Regex(
359 if (qnodename.searchFrom(nf, fcp))
361 int nl = qnodename.stringMatched().length();
362 nodename = new String(qnodename.stringMatched().substring(1,
364 // unpack any escaped colons
365 com.stevesoft.pat.Regex xpandquotes = com.stevesoft.pat.Regex
366 .perlCode("s/''/'/");
367 String widernodename = xpandquotes.replaceAll(nodename);
368 nodename = widernodename;
369 // jump to after end of quoted nodename
370 nextcp = fcp + nl + 1;
371 parsednodename = true;
375 Error = ErrorStringrange(Error,
376 "Unterminated quotes for nodename", 7, fcp, nf);
386 Error = ErrorStringrange(Error, "Wayward semicolon (depth=" + d
389 // cp advanced at the end of default
393 // node string contains Comment or structured/extended NH format info
395 * if ((fcp-cp>1 && nf.substring(cp,fcp).trim().length()>1)) { // will
396 * process in remains System.err.println("skipped text:
397 * '"+nf.substring(cp,fcp)+"'"); }
399 // verify termination.
400 com.stevesoft.pat.Regex comment = new com.stevesoft.pat.Regex("]");
401 if (comment.searchFrom(nf, fcp))
403 // Skip the comment field
404 nextcp = comment.matchedFrom() + 1;
405 warningMessage = "Tree file contained comments which may confuse input algorithm.";
408 // cp advanced at the end of default to nextcp, ncp is unchanged so
409 // any node info can be read.
413 Error = ErrorStringrange(Error, "Unterminated comment", 3, fcp,
419 // Parse simpler field strings
420 String fstring = nf.substring(ncp, fcp);
421 // remove any comments before we parse the node info
422 // TODO: test newick file with quoted square brackets in node name (is
424 while (fstring.indexOf(']') > -1)
426 int cstart = fstring.indexOf('[');
427 int cend = fstring.indexOf(']');
428 commentString2 = fstring.substring(cstart + 1, cend);
429 fstring = fstring.substring(0, cstart)
430 + fstring.substring(cend + 1);
433 com.stevesoft.pat.Regex uqnodename = new com.stevesoft.pat.Regex(
434 "\\b([^' :;\\](),]+)");
435 com.stevesoft.pat.Regex nbootstrap = new com.stevesoft.pat.Regex(
436 "\\s*([0-9+]+)\\s*:");
437 com.stevesoft.pat.Regex ndist = new com.stevesoft.pat.Regex(
441 && uqnodename.search(fstring)
442 && ((uqnodename.matchedFrom(1) == 0) || (fstring
443 .charAt(uqnodename.matchedFrom(1) - 1) != ':'))) // JBPNote
446 if (nodename == null)
448 if (ReplaceUnderscores)
450 nodename = uqnodename.stringMatched(1).replace('_', ' ');
454 nodename = uqnodename.stringMatched(1);
459 Error = ErrorStringrange(Error,
460 "File has broken algorithm - overwritten nodename", 10,
464 // get comment bootstraps
466 if (nbootstrap.search(fstring))
468 if (nbootstrap.stringMatched(1).equals(
469 uqnodename.stringMatched(1)))
471 nodename = null; // no nodename here.
474 || nodename.length() == 0
475 || nbootstrap.matchedFrom(1) > (uqnodename.matchedFrom(1) + uqnodename
476 .stringMatched().length()))
480 bootstrap = (new Integer(nbootstrap.stringMatched(1)))
483 } catch (Exception e)
485 Error = ErrorStringrange(Error,
486 "Can't parse bootstrap value", 4,
487 ncp + nbootstrap.matchedFrom(), nf);
492 boolean nodehasdistance = false;
494 if (ndist.search(fstring))
498 distance = (new Float(ndist.stringMatched(1))).floatValue();
500 nodehasdistance = true;
501 } catch (Exception e)
503 Error = ErrorStringrange(Error,
504 "Can't parse node distance value", 7,
505 ncp + ndist.matchedFrom(), nf);
511 // Write node info here
513 // Trees without distances still need a render distance
514 c.dist = (HasDistances) ? distance : DefDistance;
515 // be consistent for internal bootstrap defaults too
516 c.setBootstrap((HasBootstrap) ? bootstrap : DefBootstrap);
519 RootHasDistance = nodehasdistance; // JBPNote This is really
520 // UGLY!!! Ensure root node gets
521 // its given distance
523 parseNHXNodeProps(c, commentString2);
524 commentString2 = null;
528 // Find a place to put the leaf
529 SequenceNode newnode = new SequenceNode(null, c, nodename,
530 (HasDistances) ? distance : DefDistance,
531 (HasBootstrap) ? bootstrap : DefBootstrap, false);
532 parseNHXNodeProps(c, commentString2);
533 commentString2 = null;
535 if (c.right() == null)
541 if (c.left() == null)
547 // Insert a dummy node for polytomy
548 // dummy nodes have distances
549 SequenceNode newdummy = new SequenceNode(null, c, null,
550 (HasDistances ? 0 : DefDistance), 0, true);
551 newdummy.SetChildren(c.left(), newnode);
559 // move back up the tree from preceding closure
562 if ((d > -1) && (c == null))
564 Error = ErrorStringrange(
566 "File broke algorithm: Lost place in tree (is there an extra ')' ?)",
571 if (nf.charAt(fcp) == ')')
578 if (nf.charAt(fcp) == ',')
586 // Just advance focus, if we need to
587 if ((c.left() != null) && (!c.left().isLeaf()))
589 c = (SequenceNode) c.left();
595 // Reset new node properties to obvious fakes
597 distance = DefDistance;
598 bootstrap = DefBootstrap;
599 commentString2 = null;
600 parsednodename = false;
615 throw (new IOException(MessageManager.formatMessage("exception.newfile", new String[]{Error.toString()})));
619 throw (new IOException(MessageManager.formatMessage("exception.newfile", new String[]{MessageManager.getString("label.no_tree_read_in")})));
621 // THe next line is failing for topali trees - not sure why yet. if
622 // (root.right()!=null && root.isDummy())
623 root = (SequenceNode) root.right().detach(); // remove the imaginary root.
625 if (!RootHasDistance)
627 root.dist = (HasDistances) ? 0 : DefDistance;
632 * parse NHX codes in comment strings and update NewickFile state flags for
633 * distances and bootstraps, and add any additional properties onto the node.
636 * @param commentString
637 * @param commentString2
639 private void parseNHXNodeProps(SequenceNode c, String commentString)
641 // TODO: store raw comment on the sequenceNode so it can be recovered when
643 if (commentString != null && commentString.startsWith("&&NHX"))
645 StringTokenizer st = new StringTokenizer(commentString.substring(5),
647 while (st.hasMoreTokens())
649 String tok = st.nextToken();
650 int colpos = tok.indexOf("=");
654 String code = tok.substring(0, colpos);
655 String value = tok.substring(colpos + 1);
658 // parse out code/value pairs
659 if (code.toLowerCase().equals("b"))
662 Float iv = new Float(value);
663 v = iv.intValue(); // jalview only does integer bootstraps
669 } catch (Exception e)
671 System.err.println("Couldn't parse code '" + code + "' = '"
673 e.printStackTrace(System.err);
684 * @return DOCUMENT ME!
686 public SequenceNode getTree()
692 * Generate a newick format tree according to internal flags for bootstraps,
693 * distances and root distances.
695 * @return new hampshire tree in a single line
697 public String print()
701 StringBuffer tf = new StringBuffer();
704 return (tf.append(";").toString());
711 * Generate a newick format tree according to internal flags for distances and
712 * root distances and user specificied writing of bootstraps.
714 * @param withbootstraps
715 * controls if bootstrap values are explicitly written.
717 * @return new hampshire tree in a single line
719 public String print(boolean withbootstraps)
723 boolean boots = this.HasBootstrap;
724 this.HasBootstrap = withbootstraps;
727 this.HasBootstrap = boots;
735 * Generate newick format tree according to internal flags for writing root
738 * @param withbootstraps
739 * explicitly write bootstrap values
741 * explicitly write distances
743 * @return new hampshire tree in a single line
745 public String print(boolean withbootstraps, boolean withdists)
749 boolean dists = this.HasDistances;
750 this.HasDistances = withdists;
752 String rv = print(withbootstraps);
753 this.HasDistances = dists;
760 * Generate newick format tree according to user specified flags
762 * @param withbootstraps
763 * explicitly write bootstrap values
765 * explicitly write distances
766 * @param printRootInfo
767 * explicitly write root distance
769 * @return new hampshire tree in a single line
771 public String print(boolean withbootstraps, boolean withdists,
772 boolean printRootInfo)
776 boolean rootinfo = printRootInfo;
777 this.printRootInfo = printRootInfo;
779 String rv = print(withbootstraps, withdists);
780 this.printRootInfo = rootinfo;
789 * @return DOCUMENT ME!
802 * @return DOCUMENT ME!
804 char setQuoteChar(char c)
806 char old = QuoteChar;
818 * @return DOCUMENT ME!
820 private String nodeName(String name)
822 if (NodeSafeName[0].search(name))
824 return QuoteChar + NodeSafeName[1].replaceAll(name) + QuoteChar;
828 return NodeSafeName[2].replaceAll(name);
838 * @return DOCUMENT ME!
840 private String printNodeField(SequenceNode c)
842 return ((c.getName() == null) ? "" : nodeName(c.getName()))
843 + ((HasBootstrap) ? ((c.getBootstrap() > -1) ? ((c.getName() != null ? " "
844 : "") + c.getBootstrap())
846 : "") + ((HasDistances) ? (":" + c.dist) : "");
855 * @return DOCUMENT ME!
857 private String printRootField(SequenceNode root)
859 return (printRootInfo) ? (((root.getName() == null) ? ""
860 : nodeName(root.getName()))
861 + ((HasBootstrap) ? ((root.getBootstrap() > -1) ? ((root
862 .getName() != null ? " " : "") + +root.getBootstrap())
863 : "") : "") + ((RootHasDistance) ? (":" + root.dist)
867 // Non recursive call deals with root node properties
868 public void print(StringBuffer tf, SequenceNode root)
872 if (root.isLeaf() && printRootInfo)
874 tf.append(printRootField(root));
880 _print(tf, (SequenceNode) root.right());
881 _print(tf, (SequenceNode) root.left());
886 _print(tf, (SequenceNode) root.right());
888 if (root.left() != null)
893 _print(tf, (SequenceNode) root.left());
894 tf.append(")" + printRootField(root));
900 // Recursive call for non-root nodes
901 public void _print(StringBuffer tf, SequenceNode c)
907 tf.append(printNodeField(c));
913 _print(tf, (SequenceNode) c.left());
914 if (c.left() != null)
918 _print(tf, (SequenceNode) c.right());
923 _print(tf, (SequenceNode) c.right());
925 if (c.left() != null)
930 _print(tf, (SequenceNode) c.left());
931 tf.append(")" + printNodeField(c));
938 public static void main(String[] args)
942 if (args == null || args.length != 1)
945 .println("Takes one argument - file name of a newick tree file.");
949 File fn = new File(args[0]);
951 StringBuffer newickfile = new StringBuffer();
952 BufferedReader treefile = new BufferedReader(new FileReader(fn));
955 while ((l = treefile.readLine()) != null)
957 newickfile.append(l);
961 System.out.println("Read file :\n");
963 NewickFile trf = new NewickFile(args[0], "File");
965 System.out.println("Original file :\n");
967 com.stevesoft.pat.Regex nonl = new com.stevesoft.pat.Regex("\n+", "");
968 System.out.println(nonl.replaceAll(newickfile.toString()) + "\n");
970 System.out.println("Parsed file.\n");
971 System.out.println("Default output type for original input.\n");
972 System.out.println(trf.print());
973 System.out.println("Without bootstraps.\n");
974 System.out.println(trf.print(false));
975 System.out.println("Without distances.\n");
976 System.out.println(trf.print(true, false));
977 System.out.println("Without bootstraps but with distanecs.\n");
978 System.out.println(trf.print(false, true));
979 System.out.println("Without bootstraps or distanecs.\n");
980 System.out.println(trf.print(false, false));
981 System.out.println("With bootstraps and with distances.\n");
982 System.out.println(trf.print(true, true));
983 } catch (java.io.IOException e)
985 System.err.println("Exception\n" + e);