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;
38 import com.stevesoft.pat.Regex;
41 * Parse a new hanpshire style tree Caveats: NHX files are NOT supported and the
42 * tree distances and topology are unreliable when they are parsed. TODO: on
43 * this: NHX codes are appended in comments beginning with &&NHX. The codes are
44 * given below (from http://www.phylosoft.org/forester/NHX.html): Element Type
45 * Description Corresponding phyloXML element (parent element in parentheses) no
46 * tag string name of this node/clade (MUST BE FIRST, IF ASSIGNED)
47 * <name>(<clade>) : decimal branch length to parent node (MUST BE SECOND, IF
48 * ASSIGNED) <branch_length>(<clade>) :GN= string gene name <name>(<sequence>)
49 * :AC= string sequence accession <accession>(<sequence>) :ND= string node
50 * identifier - if this is being used, it has to be unique within each phylogeny
51 * <node_id>(<clade>) :B= decimal confidence value for parent branch
52 * <confidence>(<clade>) :D= 'T', 'F', or '?' 'T' if this node represents a
53 * duplication event - 'F' if this node represents a speciation event, '?' if
54 * this node represents an unknown event (D= tag should be replaced by Ev= tag)
55 * n/a :Ev=duplications>speciations>gene losses>event type>duplication type int
56 * int int string string event (replaces the =D tag), number of duplication,
57 * speciation, and gene loss events, type of event (transfer, fusion, root,
58 * unknown, other, speciation_duplication_loss, unassigned) <events>(<clade>)
59 * :E= string EC number at this node <annotation>(<sequence>) :Fu= string
60 * function at this node <annotation>(<sequence>)
61 * :DS=protein-length>from>to>support>name>from>... int int int double string
62 * int ... domain structure at this node <domain_architecture>(<sequence>) :S=
63 * string species name of the species/phylum at this node <taxonomy>(<clade>)
64 * :T= integer taxonomy ID of the species/phylum at this node <id>(<taxonomy>)
65 * :W= integer width of parent branch <width>(<clade>) :C=rrr.ggg.bbb
66 * integer.integer.integer color of parent branch <color>(<clade>) :Co= 'Y' or
67 * 'N' collapse this node when drawing the tree (default is not to collapse) n/a
68 * :XB= string custom data associated with a branch <property>(<clade>) :XN=
69 * string custom data associated with a node <property>(<clade>) :O= integer
70 * orthologous to this external node n/a :SN= integer subtree neighbors n/a :SO=
71 * integer super orthologous (no duplications on paths) to this external node
77 public class NewickFile extends FileParse
81 private boolean HasBootstrap = false;
83 private boolean HasDistances = false;
85 private boolean RootHasDistance = false;
88 boolean ReplaceUnderscores = false;
90 boolean printRootInfo = true;
92 private Regex[] NodeSafeName = new Regex[] {
93 new Regex().perlCode("m/[\\[,:'()]/"), // test for
96 new Regex().perlCode("s/'/''/"), // escaping quote
98 new Regex().perlCode("s/\\/w/_/") // unqoted whitespace
102 char QuoteChar = '\'';
105 * Creates a new NewickFile object.
110 * @throws IOException
113 public NewickFile(String inStr) throws IOException
115 super(inStr, DataSourceType.PASTE);
119 * Creates a new NewickFile object.
126 * @throws IOException
129 public NewickFile(String inFile, DataSourceType protocol)
132 super(inFile, protocol);
135 public NewickFile(FileParse source) throws IOException
141 * Creates a new NewickFile object.
146 public NewickFile(SequenceNode newtree)
152 * Creates a new NewickFile object.
159 public NewickFile(SequenceNode newtree, boolean bootstrap)
161 HasBootstrap = bootstrap;
166 * Creates a new NewickFile object.
175 public NewickFile(SequenceNode newtree, boolean bootstrap,
179 HasBootstrap = bootstrap;
180 HasDistances = distances;
184 * Creates a new NewickFile object.
192 * @param rootdistance
195 public NewickFile(SequenceNode newtree, boolean bootstrap,
196 boolean distances, boolean rootdistance)
199 HasBootstrap = bootstrap;
200 HasDistances = distances;
201 RootHasDistance = rootdistance;
218 * @return DOCUMENT ME!
220 private String ErrorStringrange(String Error, String Er, int r, int p,
223 return ((Error == null) ? "" : Error) + Er + " at position " + p + " ( "
224 + s.substring(((p - r) < 0) ? 0 : (p - r),
225 ((p + r) > s.length()) ? s.length() : (p + r))
230 // These are set automatically by the reader
231 public boolean HasBootstrap()
239 * @return DOCUMENT ME!
241 public boolean HasDistances()
246 public boolean HasRootDistance()
248 return RootHasDistance;
252 * parse the filesource as a newick file (new hampshire and/or extended)
254 * @throws IOException
255 * with a line number and character position for badly formatted NH
258 public void parse() throws IOException
262 { // fill nf with complete tree file
264 StringBuffer file = new StringBuffer();
266 while ((nf = nextLine()) != null)
271 nf = file.toString();
274 root = new SequenceNode();
276 SequenceNode realroot = null;
277 SequenceNode c = root;
281 // int flen = nf.length();
284 String nodename = null;
285 String commentString2 = null; // comments after simple node props
287 float DefDistance = (float) 0.001; // @param Default distance for a node -
289 int DefBootstrap = -1; // @param Default bootstrap for a node
291 float distance = DefDistance;
292 int bootstrap = DefBootstrap;
294 boolean ascending = false; // flag indicating that we are leaving the
297 Regex majorsyms = new Regex(
302 boolean parsednodename = false;
303 while (majorsyms.searchFrom(nf, cp) && (Error == null))
305 int fcp = majorsyms.matchedFrom();
307 switch (schar = nf.charAt(fcp))
311 // ascending should not be set
315 Error = ErrorStringrange(Error, "Unexpected '('", 7, fcp, nf);
323 if (c.right() == null)
325 c.setRight(new SequenceNode(null, c, null, DefDistance,
326 DefBootstrap, false));
327 c = (SequenceNode) c.right();
331 if (c.left() != null)
333 // Dummy node for polytomy - keeps c.left free for new node
334 SequenceNode tmpn = new SequenceNode(null, c, null, 0, 0, true);
335 tmpn.SetChildren(c.left(), c.right());
339 c.setLeft(new SequenceNode(null, c, null, DefDistance,
340 DefBootstrap, false));
341 c = (SequenceNode) c.left();
344 if (realroot == null)
350 distance = DefDistance;
351 bootstrap = DefBootstrap;
356 // Deal with quoted fields
359 Regex qnodename = new Regex(
362 if (qnodename.searchFrom(nf, fcp))
364 int nl = qnodename.stringMatched().length();
365 nodename = new String(
366 qnodename.stringMatched().substring(1, nl - 1));
367 // unpack any escaped colons
368 Regex xpandquotes = Regex
369 .perlCode("s/''/'/");
370 String widernodename = xpandquotes.replaceAll(nodename);
371 nodename = widernodename;
372 // jump to after end of quoted nodename
373 nextcp = fcp + nl + 1;
374 parsednodename = true;
378 Error = ErrorStringrange(Error,
379 "Unterminated quotes for nodename", 7, fcp, nf);
389 Error = ErrorStringrange(Error,
390 "Wayward semicolon (depth=" + d + ")", 7, fcp, nf);
392 // cp advanced at the end of default
396 // node string contains Comment or structured/extended NH format info
398 * if ((fcp-cp>1 && nf.substring(cp,fcp).trim().length()>1)) { // will
399 * process in remains System.err.println("skipped text:
400 * '"+nf.substring(cp,fcp)+"'"); }
402 // verify termination.
403 Regex comment = new Regex(
405 if (comment.searchFrom(nf, fcp))
407 // Skip the comment field
408 nextcp = comment.matchedFrom() + 1;
409 warningMessage = "Tree file contained comments which may confuse input algorithm.";
412 // cp advanced at the end of default to nextcp, ncp is unchanged so
413 // any node info can be read.
417 Error = ErrorStringrange(Error, "Unterminated comment", 3, fcp,
423 // Parse simpler field strings
424 String fstring = nf.substring(ncp, fcp);
425 // remove any comments before we parse the node info
426 // TODO: test newick file with quoted square brackets in node name (is
428 while (fstring.indexOf(']') > -1)
430 int cstart = fstring.indexOf('[');
431 int cend = fstring.indexOf(']');
432 commentString2 = fstring.substring(cstart + 1, cend);
433 fstring = fstring.substring(0, cstart)
434 + fstring.substring(cend + 1);
437 Regex uqnodename = new Regex(
438 "\\b([^' :;\\](),]+)");
439 Regex nbootstrap = new Regex(
440 "\\s*([0-9+]+)\\s*:");
441 Regex ndist = new Regex(
444 if (!parsednodename && uqnodename.search(fstring)
445 && ((uqnodename.matchedFrom(1) == 0) || (fstring
446 .charAt(uqnodename.matchedFrom(1) - 1) != ':'))) // JBPNote
449 if (nodename == null)
451 if (ReplaceUnderscores)
453 nodename = uqnodename.stringMatched(1).replace('_', ' ');
457 nodename = uqnodename.stringMatched(1);
462 Error = ErrorStringrange(Error,
463 "File has broken algorithm - overwritten nodename", 10,
467 // get comment bootstraps
469 if (nbootstrap.search(fstring))
471 if (nbootstrap.stringMatched(1)
472 .equals(uqnodename.stringMatched(1)))
474 nodename = null; // no nodename here.
476 if (nodename == null || nodename.length() == 0
477 || nbootstrap.matchedFrom(1) > (uqnodename.matchedFrom(1)
478 + uqnodename.stringMatched().length()))
482 bootstrap = (new Integer(nbootstrap.stringMatched(1)))
485 } catch (Exception e)
487 Error = ErrorStringrange(Error, "Can't parse bootstrap value",
488 4, ncp + nbootstrap.matchedFrom(), nf);
493 boolean nodehasdistance = false;
495 if (ndist.search(fstring))
499 distance = (new Float(ndist.stringMatched(1))).floatValue();
501 nodehasdistance = true;
502 } catch (Exception e)
504 Error = ErrorStringrange(Error,
505 "Can't parse node distance value", 7,
506 ncp + ndist.matchedFrom(), nf);
512 // Write node info here
514 // Trees without distances still need a render distance
515 c.dist = (HasDistances) ? distance : DefDistance;
516 // be consistent for internal bootstrap defaults too
517 c.setBootstrap((HasBootstrap) ? bootstrap : DefBootstrap);
520 RootHasDistance = nodehasdistance; // JBPNote This is really
521 // UGLY!!! Ensure root node gets
522 // its given distance
524 parseNHXNodeProps(c, commentString2);
525 commentString2 = null;
529 // Find a place to put the leaf
530 SequenceNode newnode = new SequenceNode(null, c, nodename,
531 (HasDistances) ? distance : DefDistance,
532 (HasBootstrap) ? bootstrap : DefBootstrap, false);
533 parseNHXNodeProps(c, commentString2);
534 commentString2 = null;
536 if (c.right() == null)
542 if (c.left() == null)
548 // Insert a dummy node for polytomy
549 // dummy nodes have distances
550 SequenceNode newdummy = new SequenceNode(null, c, null,
551 (HasDistances ? 0 : DefDistance), 0, true);
552 newdummy.SetChildren(c.left(), newnode);
560 // move back up the tree from preceding closure
563 if ((d > -1) && (c == null))
565 Error = ErrorStringrange(Error,
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(
616 MessageManager.formatMessage("exception.newfile", new String[]
617 { Error.toString() })));
621 throw (new IOException(
622 MessageManager.formatMessage("exception.newfile", new String[]
623 { MessageManager.getString("label.no_tree_read_in") })));
625 // THe next line is failing for topali trees - not sure why yet. if
626 // (root.right()!=null && root.isDummy())
627 root = (SequenceNode) root.right().detach(); // remove the imaginary root.
629 if (!RootHasDistance)
631 root.dist = (HasDistances) ? 0 : DefDistance;
636 * parse NHX codes in comment strings and update NewickFile state flags for
637 * distances and bootstraps, and add any additional properties onto the node.
640 * @param commentString
641 * @param commentString2
643 private void parseNHXNodeProps(SequenceNode c, String commentString)
645 // TODO: store raw comment on the sequenceNode so it can be recovered when
647 if (commentString != null && commentString.startsWith("&&NHX"))
649 StringTokenizer st = new StringTokenizer(commentString.substring(5),
651 while (st.hasMoreTokens())
653 String tok = st.nextToken();
654 int colpos = tok.indexOf("=");
658 String code = tok.substring(0, colpos);
659 String value = tok.substring(colpos + 1);
662 // parse out code/value pairs
663 if (code.toLowerCase().equals("b"))
666 Float iv = new Float(value);
667 v = iv.intValue(); // jalview only does integer bootstraps
673 } catch (Exception e)
676 "Couldn't parse code '" + code + "' = '" + value + "'");
677 e.printStackTrace(System.err);
688 * @return DOCUMENT ME!
690 public SequenceNode getTree()
696 * Generate a newick format tree according to internal flags for bootstraps,
697 * distances and root distances.
699 * @return new hampshire tree in a single line
701 public String print()
705 StringBuffer tf = new StringBuffer();
708 return (tf.append(";").toString());
715 * Generate a newick format tree according to internal flags for distances and
716 * root distances and user specificied writing of bootstraps.
718 * @param withbootstraps
719 * controls if bootstrap values are explicitly written.
721 * @return new hampshire tree in a single line
723 public String print(boolean withbootstraps)
727 boolean boots = this.HasBootstrap;
728 this.HasBootstrap = withbootstraps;
731 this.HasBootstrap = boots;
739 * Generate newick format tree according to internal flags for writing root
742 * @param withbootstraps
743 * explicitly write bootstrap values
745 * explicitly write distances
747 * @return new hampshire tree in a single line
749 public String print(boolean withbootstraps, boolean withdists)
753 boolean dists = this.HasDistances;
754 this.HasDistances = withdists;
756 String rv = print(withbootstraps);
757 this.HasDistances = dists;
764 * Generate newick format tree according to user specified flags
766 * @param withbootstraps
767 * explicitly write bootstrap values
769 * explicitly write distances
770 * @param printRootInfo
771 * explicitly write root distance
773 * @return new hampshire tree in a single line
775 public String print(boolean withbootstraps, boolean withdists,
776 boolean printRootInfo)
780 boolean rootinfo = printRootInfo;
781 this.printRootInfo = printRootInfo;
783 String rv = print(withbootstraps, withdists);
784 this.printRootInfo = rootinfo;
793 * @return DOCUMENT ME!
806 * @return DOCUMENT ME!
808 char setQuoteChar(char c)
810 char old = QuoteChar;
822 * @return DOCUMENT ME!
824 private String nodeName(String name)
826 if (NodeSafeName[0].search(name))
828 return QuoteChar + NodeSafeName[1].replaceAll(name) + QuoteChar;
832 return NodeSafeName[2].replaceAll(name);
842 * @return DOCUMENT ME!
844 private String printNodeField(SequenceNode c)
846 return ((c.getName() == null) ? "" : nodeName(c.getName()))
847 + ((HasBootstrap) ? ((c.getBootstrap() > -1)
848 ? ((c.getName() != null ? " " : "") + c.getBootstrap())
850 + ((HasDistances) ? (":" + c.dist) : "");
859 * @return DOCUMENT ME!
861 private String printRootField(SequenceNode root)
863 return (printRootInfo)
864 ? (((root.getName() == null) ? "" : nodeName(root.getName()))
866 ? ((root.getBootstrap() > -1)
867 ? ((root.getName() != null ? " " : "")
868 + +root.getBootstrap())
871 + ((RootHasDistance) ? (":" + root.dist) : ""))
875 // Non recursive call deals with root node properties
876 public void print(StringBuffer tf, SequenceNode root)
880 if (root.isLeaf() && printRootInfo)
882 tf.append(printRootField(root));
888 _print(tf, (SequenceNode) root.right());
889 _print(tf, (SequenceNode) root.left());
894 _print(tf, (SequenceNode) root.right());
896 if (root.left() != null)
901 _print(tf, (SequenceNode) root.left());
902 tf.append(")" + printRootField(root));
908 // Recursive call for non-root nodes
909 public void _print(StringBuffer tf, SequenceNode c)
915 tf.append(printNodeField(c));
921 _print(tf, (SequenceNode) c.left());
922 if (c.left() != null)
926 _print(tf, (SequenceNode) c.right());
931 _print(tf, (SequenceNode) c.right());
933 if (c.left() != null)
938 _print(tf, (SequenceNode) c.left());
939 tf.append(")" + printNodeField(c));
946 public static void main(String[] args)
950 if (args == null || args.length != 1)
953 "Takes one argument - file name of a newick tree file.");
957 File fn = new File(args[0]);
959 StringBuffer newickfile = new StringBuffer();
960 BufferedReader treefile = new BufferedReader(new FileReader(fn));
963 while ((l = treefile.readLine()) != null)
965 newickfile.append(l);
969 System.out.println("Read file :\n");
971 NewickFile trf = new NewickFile(args[0], DataSourceType.FILE);
973 System.out.println("Original file :\n");
975 Regex nonl = new Regex("\n+", "");
976 System.out.println(nonl.replaceAll(newickfile.toString()) + "\n");
978 System.out.println("Parsed file.\n");
979 System.out.println("Default output type for original input.\n");
980 System.out.println(trf.print());
981 System.out.println("Without bootstraps.\n");
982 System.out.println(trf.print(false));
983 System.out.println("Without distances.\n");
984 System.out.println(trf.print(true, false));
985 System.out.println("Without bootstraps but with distanecs.\n");
986 System.out.println(trf.print(false, true));
987 System.out.println("Without bootstraps or distanecs.\n");
988 System.out.println(trf.print(false, false));
989 System.out.println("With bootstraps and with distances.\n");
990 System.out.println(trf.print(true, true));
991 } catch (java.io.IOException e)
993 System.err.println("Exception\n" + e);