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 jalview.datamodel.SequenceNode;
30 import jalview.util.MessageManager;
32 import java.io.BufferedReader;
34 import java.io.FileReader;
35 import java.io.IOException;
36 import java.util.StringTokenizer;
39 * Parse a new hanpshire style tree Caveats: NHX files are NOT supported and the
40 * tree distances and topology are unreliable when they are parsed. TODO: on
41 * this: NHX codes are appended in comments beginning with &&NHX. The codes are
42 * given below (from http://www.phylosoft.org/forester/NHX.html): Element Type
43 * Description Corresponding phyloXML element (parent element in parentheses) no
44 * tag string name of this node/clade (MUST BE FIRST, IF ASSIGNED)
45 * <name>(<clade>) : decimal branch length to parent node (MUST BE SECOND, IF
46 * ASSIGNED) <branch_length>(<clade>) :GN= string gene name <name>(<sequence>)
47 * :AC= string sequence accession <accession>(<sequence>) :ND= string node
48 * identifier - if this is being used, it has to be unique within each phylogeny
49 * <node_id>(<clade>) :B= decimal confidence value for parent branch
50 * <confidence>(<clade>) :D= 'T', 'F', or '?' 'T' if this node represents a
51 * duplication event - 'F' if this node represents a speciation event, '?' if
52 * this node represents an unknown event (D= tag should be replaced by Ev= tag)
53 * n/a :Ev=duplications>speciations>gene losses>event type>duplication type int
54 * int int string string event (replaces the =D tag), number of duplication,
55 * speciation, and gene loss events, type of event (transfer, fusion, root,
56 * unknown, other, speciation_duplication_loss, unassigned) <events>(<clade>)
57 * :E= string EC number at this node <annotation>(<sequence>) :Fu= string
58 * function at this node <annotation>(<sequence>)
59 * :DS=protein-length>from>to>support>name>from>... int int int double string
60 * int ... domain structure at this node <domain_architecture>(<sequence>) :S=
61 * string species name of the species/phylum at this node <taxonomy>(<clade>)
62 * :T= integer taxonomy ID of the species/phylum at this node <id>(<taxonomy>)
63 * :W= integer width of parent branch <width>(<clade>) :C=rrr.ggg.bbb
64 * integer.integer.integer color of parent branch <color>(<clade>) :Co= 'Y' or
65 * 'N' collapse this node when drawing the tree (default is not to collapse) n/a
66 * :XB= string custom data associated with a branch <property>(<clade>) :XN=
67 * string custom data associated with a node <property>(<clade>) :O= integer
68 * orthologous to this external node n/a :SN= integer subtree neighbors n/a :SO=
69 * integer super orthologous (no duplications on paths) to this external node
75 public class NewickFile extends FileParse
79 private boolean HasBootstrap = false;
81 private boolean HasDistances = false;
83 private boolean RootHasDistance = false;
86 boolean ReplaceUnderscores = false;
88 boolean printRootInfo = true;
90 private com.stevesoft.pat.Regex[] NodeSafeName = new com.stevesoft.pat.Regex[] {
91 new com.stevesoft.pat.Regex().perlCode("m/[\\[,:'()]/"), // test for
94 new com.stevesoft.pat.Regex().perlCode("s/'/''/"), // escaping quote
96 new com.stevesoft.pat.Regex().perlCode("s/\\/w/_/") // unqoted whitespace
100 char QuoteChar = '\'';
103 * Creates a new NewickFile object.
108 * @throws IOException
111 public NewickFile(String inStr) throws IOException
113 super(inStr, DataSourceType.PASTE);
117 * Creates a new NewickFile object.
124 * @throws IOException
127 public NewickFile(String inFile, DataSourceType protocol)
130 super(inFile, protocol);
133 public NewickFile(FileParse source) throws IOException
139 * Creates a new NewickFile object.
144 public NewickFile(SequenceNode newtree)
150 * Creates a new NewickFile object.
157 public NewickFile(SequenceNode newtree, boolean bootstrap)
159 HasBootstrap = bootstrap;
164 * Creates a new NewickFile object.
173 public NewickFile(SequenceNode newtree, boolean bootstrap,
177 HasBootstrap = bootstrap;
178 HasDistances = distances;
182 * Creates a new NewickFile object.
190 * @param rootdistance
193 public NewickFile(SequenceNode newtree, boolean bootstrap,
194 boolean distances, boolean rootdistance)
197 HasBootstrap = bootstrap;
198 HasDistances = distances;
199 RootHasDistance = rootdistance;
216 * @return DOCUMENT ME!
218 private String ErrorStringrange(String Error, String Er, int r, int p,
221 return ((Error == null) ? "" : Error) + Er + " at position " + p + " ( "
222 + s.substring(((p - r) < 0) ? 0 : (p - r),
223 ((p + r) > s.length()) ? s.length() : (p + r))
228 // These are set automatically by the reader
229 public boolean HasBootstrap()
237 * @return DOCUMENT ME!
239 public boolean HasDistances()
244 public boolean HasRootDistance()
246 return RootHasDistance;
250 * parse the filesource as a newick file (new hampshire and/or extended)
252 * @throws IOException
253 * with a line number and character position for badly formatted NH
256 public void parse() throws IOException
260 { // fill nf with complete tree file
262 StringBuffer file = new StringBuffer();
264 while ((nf = nextLine()) != null)
269 nf = file.toString();
272 root = new SequenceNode();
274 SequenceNode realroot = null;
275 SequenceNode c = root;
279 // int flen = nf.length();
282 String nodename = null;
283 String commentString2 = null; // comments after simple node props
285 float DefDistance = (float) 0.001; // @param Default distance for a node -
287 int DefBootstrap = -1; // @param Default bootstrap for a node
289 float distance = DefDistance;
290 int bootstrap = DefBootstrap;
292 boolean ascending = false; // flag indicating that we are leaving the
295 com.stevesoft.pat.Regex majorsyms = new com.stevesoft.pat.Regex(
300 boolean parsednodename = false;
301 while (majorsyms.searchFrom(nf, cp) && (Error == null))
303 int fcp = majorsyms.matchedFrom();
305 switch (schar = nf.charAt(fcp))
309 // ascending should not be set
313 Error = ErrorStringrange(Error, "Unexpected '('", 7, fcp, nf);
321 if (c.right() == null)
323 c.setRight(new SequenceNode(null, c, null, DefDistance,
324 DefBootstrap, false));
325 c = (SequenceNode) c.right();
329 if (c.left() != null)
331 // Dummy node for polytomy - keeps c.left free for new node
332 SequenceNode tmpn = new SequenceNode(null, c, null, 0, 0, true);
333 tmpn.SetChildren(c.left(), c.right());
337 c.setLeft(new SequenceNode(null, c, null, DefDistance,
338 DefBootstrap, false));
339 c = (SequenceNode) c.left();
342 if (realroot == null)
348 distance = DefDistance;
349 bootstrap = DefBootstrap;
354 // Deal with quoted fields
357 com.stevesoft.pat.Regex qnodename = new com.stevesoft.pat.Regex(
360 if (qnodename.searchFrom(nf, fcp))
362 int nl = qnodename.stringMatched().length();
363 nodename = new String(
364 qnodename.stringMatched().substring(1, nl - 1));
365 // unpack any escaped colons
366 com.stevesoft.pat.Regex xpandquotes = com.stevesoft.pat.Regex
367 .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 System.err.println("skipped text:
398 * '"+nf.substring(cp,fcp)+"'"); }
400 // verify termination.
401 com.stevesoft.pat.Regex comment = new com.stevesoft.pat.Regex(
403 if (comment.searchFrom(nf, fcp))
405 // Skip the comment field
406 nextcp = comment.matchedFrom() + 1;
407 warningMessage = "Tree file contained comments which may confuse input algorithm.";
410 // cp advanced at the end of default to nextcp, ncp is unchanged so
411 // any node info can be read.
415 Error = ErrorStringrange(Error, "Unterminated comment", 3, fcp,
421 // Parse simpler field strings
422 String fstring = nf.substring(ncp, fcp);
423 // remove any comments before we parse the node info
424 // TODO: test newick file with quoted square brackets in node name (is
426 while (fstring.indexOf(']') > -1)
428 int cstart = fstring.indexOf('[');
429 int cend = fstring.indexOf(']');
430 commentString2 = fstring.substring(cstart + 1, cend);
431 fstring = fstring.substring(0, cstart)
432 + fstring.substring(cend + 1);
435 com.stevesoft.pat.Regex uqnodename = new com.stevesoft.pat.Regex(
436 "\\b([^' :;\\](),]+)");
437 com.stevesoft.pat.Regex nbootstrap = new com.stevesoft.pat.Regex(
438 "\\s*([0-9+]+)\\s*:");
439 com.stevesoft.pat.Regex ndist = new com.stevesoft.pat.Regex(
442 if (!parsednodename && uqnodename.search(fstring)
443 && ((uqnodename.matchedFrom(1) == 0) || (fstring
444 .charAt(uqnodename.matchedFrom(1) - 1) != ':'))) // JBPNote
447 if (nodename == null)
449 if (ReplaceUnderscores)
451 nodename = uqnodename.stringMatched(1).replace('_', ' ');
455 nodename = uqnodename.stringMatched(1);
460 Error = ErrorStringrange(Error,
461 "File has broken algorithm - overwritten nodename", 10,
465 // get comment bootstraps
467 if (nbootstrap.search(fstring))
469 if (nbootstrap.stringMatched(1)
470 .equals(uqnodename.stringMatched(1)))
472 nodename = null; // no nodename here.
474 if (nodename == null || nodename.length() == 0
475 || nbootstrap.matchedFrom(1) > (uqnodename.matchedFrom(1)
476 + uqnodename.stringMatched().length()))
480 bootstrap = (Integer.valueOf(nbootstrap.stringMatched(1)))
483 } catch (Exception e)
485 Error = ErrorStringrange(Error, "Can't parse bootstrap value",
486 4, ncp + nbootstrap.matchedFrom(), nf);
491 boolean nodehasdistance = false;
493 if (ndist.search(fstring))
497 distance = (Float.valueOf(ndist.stringMatched(1))).floatValue();
499 nodehasdistance = true;
500 } catch (Exception e)
502 Error = ErrorStringrange(Error,
503 "Can't parse node distance value", 7,
504 ncp + ndist.matchedFrom(), nf);
510 // Write node info here
512 // Trees without distances still need a render distance
513 c.dist = (HasDistances) ? distance : DefDistance;
514 // be consistent for internal bootstrap defaults too
515 c.setBootstrap((HasBootstrap) ? bootstrap : DefBootstrap);
518 RootHasDistance = nodehasdistance; // JBPNote This is really
519 // UGLY!!! Ensure root node gets
520 // its given distance
522 parseNHXNodeProps(c, commentString2);
523 commentString2 = null;
527 // Find a place to put the leaf
528 SequenceNode newnode = new SequenceNode(null, c, nodename,
529 (HasDistances) ? distance : DefDistance,
530 (HasBootstrap) ? bootstrap : DefBootstrap, false);
531 parseNHXNodeProps(c, commentString2);
532 commentString2 = null;
534 if (c.right() == null)
540 if (c.left() == null)
546 // Insert a dummy node for polytomy
547 // dummy nodes have distances
548 SequenceNode newdummy = new SequenceNode(null, c, null,
549 (HasDistances ? 0 : DefDistance), 0, true);
550 newdummy.SetChildren(c.left(), newnode);
558 // move back up the tree from preceding closure
561 if ((d > -1) && (c == null))
563 Error = ErrorStringrange(Error,
564 "File broke algorithm: Lost place in tree (is there an extra ')' ?)",
569 if (nf.charAt(fcp) == ')')
576 if (nf.charAt(fcp) == ',')
584 // Just advance focus, if we need to
585 if ((c.left() != null) && (!c.left().isLeaf()))
587 c = (SequenceNode) c.left();
593 // Reset new node properties to obvious fakes
595 distance = DefDistance;
596 bootstrap = DefBootstrap;
597 commentString2 = null;
598 parsednodename = false;
613 throw (new IOException(
614 MessageManager.formatMessage("exception.newfile", new String[]
615 { Error.toString() })));
619 throw (new IOException(
620 MessageManager.formatMessage("exception.newfile", new String[]
621 { MessageManager.getString("label.no_tree_read_in") })));
623 // THe next line is failing for topali trees - not sure why yet. if
624 // (root.right()!=null && root.isDummy())
625 root = (SequenceNode) root.right().detach(); // remove the imaginary root.
627 if (!RootHasDistance)
629 root.dist = (HasDistances) ? 0 : DefDistance;
634 * parse NHX codes in comment strings and update NewickFile state flags for
635 * distances and bootstraps, and add any additional properties onto the node.
638 * @param commentString
639 * @param commentString2
641 private void parseNHXNodeProps(SequenceNode c, String commentString)
643 // TODO: store raw comment on the sequenceNode so it can be recovered when
645 if (commentString != null && commentString.startsWith("&&NHX"))
647 StringTokenizer st = new StringTokenizer(commentString.substring(5),
649 while (st.hasMoreTokens())
651 String tok = st.nextToken();
652 int colpos = tok.indexOf("=");
656 String code = tok.substring(0, colpos);
657 String value = tok.substring(colpos + 1);
660 // parse out code/value pairs
661 if (code.toLowerCase().equals("b"))
664 Float iv = Float.valueOf(value);
665 v = iv.intValue(); // jalview only does integer bootstraps
671 } catch (Exception e)
674 "Couldn't parse code '" + code + "' = '" + value + "'");
675 e.printStackTrace(System.err);
686 * @return DOCUMENT ME!
688 public SequenceNode getTree()
694 * Generate a newick format tree according to internal flags for bootstraps,
695 * distances and root distances.
697 * @return new hampshire tree in a single line
699 public String print()
703 StringBuffer tf = new StringBuffer();
706 return (tf.append(";").toString());
713 * Generate a newick format tree according to internal flags for distances and
714 * root distances and user specificied writing of bootstraps.
716 * @param withbootstraps
717 * controls if bootstrap values are explicitly written.
719 * @return new hampshire tree in a single line
721 public String print(boolean withbootstraps)
725 boolean boots = this.HasBootstrap;
726 this.HasBootstrap = withbootstraps;
729 this.HasBootstrap = boots;
737 * Generate newick format tree according to internal flags for writing root
740 * @param withbootstraps
741 * explicitly write bootstrap values
743 * explicitly write distances
745 * @return new hampshire tree in a single line
747 public String print(boolean withbootstraps, boolean withdists)
751 boolean dists = this.HasDistances;
752 this.HasDistances = withdists;
754 String rv = print(withbootstraps);
755 this.HasDistances = dists;
762 * Generate newick format tree according to user specified flags
764 * @param withbootstraps
765 * explicitly write bootstrap values
767 * explicitly write distances
768 * @param printRootInfo
769 * explicitly write root distance
771 * @return new hampshire tree in a single line
773 public String print(boolean withbootstraps, boolean withdists,
774 boolean printRootInfo)
778 boolean rootinfo = printRootInfo;
779 this.printRootInfo = printRootInfo;
781 String rv = print(withbootstraps, withdists);
782 this.printRootInfo = rootinfo;
791 * @return DOCUMENT ME!
804 * @return DOCUMENT ME!
806 char setQuoteChar(char c)
808 char old = QuoteChar;
820 * @return DOCUMENT ME!
822 private String nodeName(String name)
824 if (NodeSafeName[0].search(name))
826 return QuoteChar + NodeSafeName[1].replaceAll(name) + QuoteChar;
830 return NodeSafeName[2].replaceAll(name);
840 * @return DOCUMENT ME!
842 private String printNodeField(SequenceNode c)
844 return ((c.getName() == null) ? "" : nodeName(c.getName()))
845 + ((HasBootstrap) ? ((c.getBootstrap() > -1)
846 ? ((c.getName() != null ? " " : "") + c.getBootstrap())
848 + ((HasDistances) ? (":" + c.dist) : "");
857 * @return DOCUMENT ME!
859 private String printRootField(SequenceNode root)
861 return (printRootInfo)
862 ? (((root.getName() == null) ? "" : nodeName(root.getName()))
864 ? ((root.getBootstrap() > -1)
865 ? ((root.getName() != null ? " " : "")
866 + +root.getBootstrap())
869 + ((RootHasDistance) ? (":" + root.dist) : ""))
873 // Non recursive call deals with root node properties
874 public void print(StringBuffer tf, SequenceNode root)
878 if (root.isLeaf() && printRootInfo)
880 tf.append(printRootField(root));
886 _print(tf, (SequenceNode) root.right());
887 _print(tf, (SequenceNode) root.left());
892 _print(tf, (SequenceNode) root.right());
894 if (root.left() != null)
899 _print(tf, (SequenceNode) root.left());
900 tf.append(")" + printRootField(root));
906 // Recursive call for non-root nodes
907 public void _print(StringBuffer tf, SequenceNode c)
913 tf.append(printNodeField(c));
919 _print(tf, (SequenceNode) c.left());
920 if (c.left() != null)
924 _print(tf, (SequenceNode) c.right());
929 _print(tf, (SequenceNode) c.right());
931 if (c.left() != null)
936 _print(tf, (SequenceNode) c.left());
937 tf.append(")" + printNodeField(c));
944 public static void main(String[] args)
948 if (args == null || args.length != 1)
951 "Takes one argument - file name of a newick tree file.");
955 File fn = new File(args[0]);
957 StringBuffer newickfile = new StringBuffer();
958 BufferedReader treefile = new BufferedReader(new FileReader(fn));
961 while ((l = treefile.readLine()) != null)
963 newickfile.append(l);
967 System.out.println("Read file :\n");
969 NewickFile trf = new NewickFile(args[0], DataSourceType.FILE);
971 System.out.println("Original file :\n");
973 com.stevesoft.pat.Regex nonl = new com.stevesoft.pat.Regex("\n+", "");
974 System.out.println(nonl.replaceAll(newickfile.toString()) + "\n");
976 System.out.println("Parsed file.\n");
977 System.out.println("Default output type for original input.\n");
978 System.out.println(trf.print());
979 System.out.println("Without bootstraps.\n");
980 System.out.println(trf.print(false));
981 System.out.println("Without distances.\n");
982 System.out.println(trf.print(true, false));
983 System.out.println("Without bootstraps but with distanecs.\n");
984 System.out.println(trf.print(false, true));
985 System.out.println("Without bootstraps or distanecs.\n");
986 System.out.println(trf.print(false, false));
987 System.out.println("With bootstraps and with distances.\n");
988 System.out.println(trf.print(true, true));
989 } catch (java.io.IOException e)
991 System.err.println("Exception\n" + e);