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 java.io.BufferedReader;
31 import java.io.FileReader;
32 import java.io.IOException;
33 import java.util.Locale;
34 import java.util.StringTokenizer;
36 import com.stevesoft.pat.Regex;
38 import jalview.bin.Jalview;
39 import jalview.datamodel.SequenceNode;
40 import jalview.util.MessageManager;
43 * Parse a new hanpshire style tree Caveats: NHX files are NOT supported and the
44 * tree distances and topology are unreliable when they are parsed. TODO: on
45 * this: NHX codes are appended in comments beginning with &&NHX. The codes are
46 * given below (from http://www.phylosoft.org/forester/NHX.html): Element Type
47 * Description Corresponding phyloXML element (parent element in parentheses) no
48 * tag string name of this node/clade (MUST BE FIRST, IF ASSIGNED)
49 * <name>(<clade>) : decimal branch length to parent node (MUST BE SECOND, IF
50 * ASSIGNED) <branch_length>(<clade>) :GN= string gene name <name>(<sequence>)
51 * :AC= string sequence accession <accession>(<sequence>) :ND= string node
52 * identifier - if this is being used, it has to be unique within each phylogeny
53 * <node_id>(<clade>) :B= decimal confidence value for parent branch
54 * <confidence>(<clade>) :D= 'T', 'F', or '?' 'T' if this node represents a
55 * duplication event - 'F' if this node represents a speciation event, '?' if
56 * this node represents an unknown event (D= tag should be replaced by Ev= tag)
57 * n/a :Ev=duplications>speciations>gene losses>event type>duplication type int
58 * int int string string event (replaces the =D tag), number of duplication,
59 * speciation, and gene loss events, type of event (transfer, fusion, root,
60 * unknown, other, speciation_duplication_loss, unassigned) <events>(<clade>)
61 * :E= string EC number at this node <annotation>(<sequence>) :Fu= string
62 * function at this node <annotation>(<sequence>)
63 * :DS=protein-length>from>to>support>name>from>... int int int double string
64 * int ... domain structure at this node <domain_architecture>(<sequence>) :S=
65 * string species name of the species/phylum at this node <taxonomy>(<clade>)
66 * :T= integer taxonomy ID of the species/phylum at this node <id>(<taxonomy>)
67 * :W= integer width of parent branch <width>(<clade>) :C=rrr.ggg.bbb
68 * integer.integer.integer color of parent branch <color>(<clade>) :Co= 'Y' or
69 * 'N' collapse this node when drawing the tree (default is not to collapse) n/a
70 * :XB= string custom data associated with a branch <property>(<clade>) :XN=
71 * string custom data associated with a node <property>(<clade>) :O= integer
72 * orthologous to this external node n/a :SN= integer subtree neighbors n/a :SO=
73 * integer super orthologous (no duplications on paths) to this external node
79 public class NewickFile extends FileParse
83 private boolean HasBootstrap = false;
85 private boolean HasDistances = false;
87 private boolean RootHasDistance = false;
90 boolean ReplaceUnderscores = false;
92 boolean printRootInfo = true;
94 private Regex[] NodeSafeName = new Regex[] {
95 new Regex().perlCode("m/[\\[,:'()]/"), // test for
98 new Regex().perlCode("s/'/''/"), // escaping quote
100 new Regex().perlCode("s/\\/w/_/") // unqoted whitespace
104 char QuoteChar = '\'';
107 * Creates a new NewickFile object.
112 * @throws IOException
115 public NewickFile(String inStr) throws IOException
117 super(inStr, DataSourceType.PASTE);
121 * Creates a new NewickFile object.
128 * @throws IOException
131 public NewickFile(String inFile, DataSourceType protocol)
134 super(inFile, protocol);
137 public NewickFile(FileParse source) throws IOException
143 * Creates a new NewickFile object.
148 public NewickFile(SequenceNode newtree)
154 * Creates a new NewickFile object.
161 public NewickFile(SequenceNode newtree, boolean bootstrap)
163 HasBootstrap = bootstrap;
168 * Creates a new NewickFile object.
177 public NewickFile(SequenceNode newtree, boolean bootstrap,
181 HasBootstrap = bootstrap;
182 HasDistances = distances;
186 * Creates a new NewickFile object.
194 * @param rootdistance
197 public NewickFile(SequenceNode newtree, boolean bootstrap,
198 boolean distances, boolean rootdistance)
201 HasBootstrap = bootstrap;
202 HasDistances = distances;
203 RootHasDistance = rootdistance;
220 * @return DOCUMENT ME!
222 private String ErrorStringrange(String Error, String Er, int r, int p,
225 return ((Error == null) ? "" : Error) + Er + " at position " + p + " ( "
226 + s.substring(((p - r) < 0) ? 0 : (p - r),
227 ((p + r) > s.length()) ? s.length() : (p + r))
232 // These are set automatically by the reader
233 public boolean HasBootstrap()
241 * @return DOCUMENT ME!
243 public boolean HasDistances()
248 public boolean HasRootDistance()
250 return RootHasDistance;
254 * parse the filesource as a newick file (new hampshire and/or extended)
256 * @throws IOException
257 * with a line number and character position for badly formatted NH
260 public void parse() throws IOException
264 { // fill nf with complete tree file
266 StringBuffer file = new StringBuffer();
268 while ((nf = nextLine()) != null)
273 nf = file.toString();
276 root = new SequenceNode();
278 SequenceNode realroot = null;
279 SequenceNode c = root;
283 // int flen = nf.length();
286 String nodename = null;
287 String commentString2 = null; // comments after simple node props
289 double DefDistance = (float) 0.001; // @param Default distance for a node -
291 int DefBootstrap = -1; // @param Default bootstrap for a node
293 double distance = DefDistance;
294 int bootstrap = DefBootstrap;
296 boolean ascending = false; // flag indicating that we are leaving the
299 Regex majorsyms = new Regex("[(\\['),;]");
303 boolean parsednodename = false;
304 while (majorsyms.searchFrom(nf, cp) && (Error == null))
306 int fcp = majorsyms.matchedFrom();
308 switch (schar = nf.charAt(fcp))
312 // ascending should not be set
316 Error = ErrorStringrange(Error, "Unexpected '('", 7, fcp, nf);
322 if (c.right() == null)
324 c.setRight(new SequenceNode(null, c, null, DefDistance,
325 DefBootstrap, false));
326 c = (SequenceNode) c.right();
330 if (c.left() != null)
332 // Dummy node for polytomy - keeps c.left free for new node
333 SequenceNode tmpn = new SequenceNode(null, c, null, 0, 0, true);
334 tmpn.SetChildren(c.left(), c.right());
338 c.setLeft(new SequenceNode(null, c, null, DefDistance,
339 DefBootstrap, false));
340 c = (SequenceNode) c.left();
343 if (realroot == null)
349 distance = DefDistance;
350 bootstrap = DefBootstrap;
355 // Deal with quoted fields
358 Regex qnodename = new 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 Regex xpandquotes = Regex.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,
387 "Wayward semicolon (depth=" + d + ")", 7, fcp, nf);
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 Regex comment = new 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,
417 // Parse simpler field strings
418 String fstring = nf.substring(ncp, fcp);
419 // remove any comments before we parse the node info
420 // TODO: test newick file with quoted square brackets in node name (is
422 while (fstring.indexOf(']') > -1)
424 int cstart = fstring.indexOf('[');
425 int cend = fstring.indexOf(']');
426 commentString2 = fstring.substring(cstart + 1, cend);
427 fstring = fstring.substring(0, cstart)
428 + fstring.substring(cend + 1);
431 Regex uqnodename = new Regex("\\b([^' :;\\](),]+)");
432 Regex nbootstrap = new Regex("\\s*([0-9+]+)\\s*:");
433 Regex ndist = new Regex(":([-0-9Ee.+]+)");
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)
463 .equals(uqnodename.stringMatched(1)))
465 nodename = null; // no nodename here.
467 if (nodename == null || nodename.length() == 0
468 || nbootstrap.matchedFrom(1) > (uqnodename.matchedFrom(1)
469 + uqnodename.stringMatched().length()))
473 bootstrap = (Integer.valueOf(nbootstrap.stringMatched(1)))
476 } catch (Exception e)
478 Error = ErrorStringrange(Error, "Can't parse bootstrap value",
479 4, ncp + nbootstrap.matchedFrom(), nf);
484 boolean nodehasdistance = false;
486 if (ndist.search(fstring))
490 distance = (Double.valueOf(ndist.stringMatched(1)))
493 nodehasdistance = true;
494 } catch (Exception e)
496 Error = ErrorStringrange(Error,
497 "Can't parse node distance value", 7,
498 ncp + ndist.matchedFrom(), nf);
504 // Write node info here
506 // Trees without distances still need a render distance
507 c.dist = (HasDistances) ? distance : DefDistance;
508 // be consistent for internal bootstrap defaults too
509 c.setBootstrap((HasBootstrap) ? bootstrap : DefBootstrap);
512 RootHasDistance = nodehasdistance; // JBPNote This is really
513 // UGLY!!! Ensure root node gets
514 // its given distance
516 parseNHXNodeProps(c, commentString2);
517 commentString2 = null;
521 // Find a place to put the leaf
522 SequenceNode newnode = new SequenceNode(null, c, nodename,
523 (HasDistances) ? distance : DefDistance,
524 (HasBootstrap) ? bootstrap : DefBootstrap, false);
525 parseNHXNodeProps(c, commentString2);
526 commentString2 = null;
528 if (c.right() == null)
534 if (c.left() == null)
540 // Insert a dummy node for polytomy
541 // dummy nodes have distances
542 SequenceNode newdummy = new SequenceNode(null, c, null,
543 (HasDistances ? 0 : DefDistance), 0, true);
544 newdummy.SetChildren(c.left(), newnode);
552 // move back up the tree from preceding closure
555 if ((d > -1) && (c == null))
557 Error = ErrorStringrange(Error,
558 "File broke algorithm: Lost place in tree (is there an extra ')' ?)",
563 if (nf.charAt(fcp) == ')')
570 if (nf.charAt(fcp) == ',')
578 // Just advance focus, if we need to
579 if ((c.left() != null) && (!c.left().isLeaf()))
581 c = (SequenceNode) c.left();
587 // Reset new node properties to obvious fakes
589 distance = DefDistance;
590 bootstrap = DefBootstrap;
591 commentString2 = null;
592 parsednodename = false;
607 throw (new IOException(
608 MessageManager.formatMessage("exception.newfile", new String[]
609 { Error.toString() })));
613 throw (new IOException(
614 MessageManager.formatMessage("exception.newfile", new String[]
615 { MessageManager.getString("label.no_tree_read_in") })));
617 // THe next line is failing for topali trees - not sure why yet. if
618 // (root.right()!=null && root.isDummy())
619 root = (SequenceNode) root.right().detach(); // remove the imaginary root.
621 if (!RootHasDistance)
623 root.dist = (HasDistances) ? 0 : DefDistance;
628 * parse NHX codes in comment strings and update NewickFile state flags for
629 * distances and bootstraps, and add any additional properties onto the node.
632 * @param commentString
633 * @param commentString2
635 private void parseNHXNodeProps(SequenceNode c, String commentString)
637 // TODO: store raw comment on the sequenceNode so it can be recovered when
639 if (commentString != null && commentString.startsWith("&&NHX"))
641 StringTokenizer st = new StringTokenizer(commentString.substring(5),
643 while (st.hasMoreTokens())
645 String tok = st.nextToken();
646 int colpos = tok.indexOf("=");
650 String code = tok.substring(0, colpos);
651 String value = tok.substring(colpos + 1);
654 // parse out code/value pairs
655 if (code.toLowerCase(Locale.ROOT).equals("b"))
658 Float iv = Float.valueOf(value);
659 v = iv.intValue(); // jalview only does integer bootstraps
665 } catch (Exception e)
668 "Couldn't parse code '" + code + "' = '" + value + "'");
669 e.printStackTrace(System.err);
680 * @return DOCUMENT ME!
682 public SequenceNode getTree()
688 * Generate a newick format tree according to internal flags for bootstraps,
689 * distances and root distances.
691 * @return new hampshire tree in a single line
693 public String print()
697 StringBuffer tf = new StringBuffer();
700 return (tf.append(";").toString());
707 * Generate a newick format tree according to internal flags for distances and
708 * root distances and user specificied writing of bootstraps.
710 * @param withbootstraps
711 * controls if bootstrap values are explicitly written.
713 * @return new hampshire tree in a single line
715 public String print(boolean withbootstraps)
719 boolean boots = this.HasBootstrap;
720 this.HasBootstrap = withbootstraps;
723 this.HasBootstrap = boots;
731 * Generate newick format tree according to internal flags for writing root
734 * @param withbootstraps
735 * explicitly write bootstrap values
737 * explicitly write distances
739 * @return new hampshire tree in a single line
741 public String print(boolean withbootstraps, boolean withdists)
745 boolean dists = this.HasDistances;
746 this.HasDistances = withdists;
748 String rv = print(withbootstraps);
749 this.HasDistances = dists;
756 * Generate newick format tree according to user specified flags
758 * @param withbootstraps
759 * explicitly write bootstrap values
761 * explicitly write distances
762 * @param printRootInfo
763 * explicitly write root distance
765 * @return new hampshire tree in a single line
767 public String print(boolean withbootstraps, boolean withdists,
768 boolean printRootInfo)
772 boolean rootinfo = printRootInfo;
773 this.printRootInfo = printRootInfo;
775 String rv = print(withbootstraps, withdists);
776 this.printRootInfo = rootinfo;
785 * @return DOCUMENT ME!
798 * @return DOCUMENT ME!
800 char setQuoteChar(char c)
802 char old = QuoteChar;
814 * @return DOCUMENT ME!
816 private String nodeName(String name)
818 if (NodeSafeName[0].search(name))
820 return QuoteChar + NodeSafeName[1].replaceAll(name) + QuoteChar;
824 return NodeSafeName[2].replaceAll(name);
834 * @return DOCUMENT ME!
836 private String printNodeField(SequenceNode c)
838 return ((c.getName() == null) ? "" : nodeName(c.getName()))
839 + ((HasBootstrap) ? ((c.getBootstrap() > -1)
840 ? ((c.getName() != null ? " " : "") + c.getBootstrap())
842 + ((HasDistances) ? (":" + c.dist) : "");
851 * @return DOCUMENT ME!
853 private String printRootField(SequenceNode root)
855 return (printRootInfo)
856 ? (((root.getName() == null) ? "" : nodeName(root.getName()))
858 ? ((root.getBootstrap() > -1)
859 ? ((root.getName() != null ? " " : "")
860 + +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));
942 public static void main(String[] args)
946 if (args == null || args.length != 1)
949 "Takes one argument - file name of a newick tree file.", 0);
952 File fn = new File(args[0]);
954 StringBuffer newickfile = new StringBuffer();
955 BufferedReader treefile = new BufferedReader(new FileReader(fn));
958 while ((l = treefile.readLine()) != null)
960 newickfile.append(l);
964 System.out.println("Read file :\n");
966 NewickFile trf = new NewickFile(args[0], DataSourceType.FILE);
968 System.out.println("Original file :\n");
970 Regex nonl = new Regex("\n+", "");
971 System.out.println(nonl.replaceAll(newickfile.toString()) + "\n");
973 System.out.println("Parsed file.\n");
974 System.out.println("Default output type for original input.\n");
975 System.out.println(trf.print());
976 System.out.println("Without bootstraps.\n");
977 System.out.println(trf.print(false));
978 System.out.println("Without distances.\n");
979 System.out.println(trf.print(true, false));
980 System.out.println("Without bootstraps but with distanecs.\n");
981 System.out.println(trf.print(false, true));
982 System.out.println("Without bootstraps or distanecs.\n");
983 System.out.println(trf.print(false, false));
984 System.out.println("With bootstraps and with distances.\n");
985 System.out.println(trf.print(true, true));
986 } catch (java.io.IOException e)
988 System.err.println("Exception\n" + e);