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, "Paste");
119 * Creates a new NewickFile object.
126 * @throws IOException
129 public NewickFile(String inFile, String type) throws IOException
134 public NewickFile(FileParse source) throws IOException
140 * Creates a new NewickFile object.
145 public NewickFile(SequenceNode newtree)
151 * Creates a new NewickFile object.
158 public NewickFile(SequenceNode newtree, boolean bootstrap)
160 HasBootstrap = bootstrap;
165 * Creates a new NewickFile object.
174 public NewickFile(SequenceNode newtree, boolean bootstrap,
178 HasBootstrap = bootstrap;
179 HasDistances = distances;
183 * Creates a new NewickFile object.
191 * @param rootdistance
194 public NewickFile(SequenceNode newtree, boolean bootstrap,
195 boolean distances, boolean rootdistance)
198 HasBootstrap = bootstrap;
199 HasDistances = distances;
200 RootHasDistance = rootdistance;
217 * @return DOCUMENT ME!
219 private String ErrorStringrange(String Error, String Er, int r, int p,
222 return ((Error == null) ? "" : Error)
227 + s.substring(((p - r) < 0) ? 0 : (p - r),
228 ((p + r) > s.length()) ? s.length() : (p + r)) + " )\n";
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 float DefDistance = (float) 0.001; // @param Default distance for a node -
291 int DefBootstrap = -1; // @param Default bootstrap for a node
293 float distance = DefDistance;
294 int bootstrap = DefBootstrap;
296 boolean ascending = false; // flag indicating that we are leaving the
299 Regex majorsyms = new Regex(
304 boolean parsednodename = false;
305 while (majorsyms.searchFrom(nf, cp) && (Error == null))
307 int fcp = majorsyms.matchedFrom();
309 switch (schar = nf.charAt(fcp))
313 // ascending should not be set
317 Error = ErrorStringrange(Error, "Unexpected '('", 7, fcp, nf);
325 if (c.right() == null)
327 c.setRight(new SequenceNode(null, c, null, DefDistance,
328 DefBootstrap, false));
329 c = (SequenceNode) c.right();
333 if (c.left() != null)
335 // Dummy node for polytomy - keeps c.left free for new node
336 SequenceNode tmpn = new SequenceNode(null, c, null, 0, 0, true);
337 tmpn.SetChildren(c.left(), c.right());
341 c.setLeft(new SequenceNode(null, c, null, DefDistance,
342 DefBootstrap, false));
343 c = (SequenceNode) c.left();
346 if (realroot == null)
352 distance = DefDistance;
353 bootstrap = DefBootstrap;
358 // Deal with quoted fields
361 Regex qnodename = new Regex(
364 if (qnodename.searchFrom(nf, fcp))
366 int nl = qnodename.stringMatched().length();
367 nodename = new String(qnodename.stringMatched().substring(1,
369 // unpack any escaped colons
370 Regex xpandquotes = Regex
371 .perlCode("s/''/'/");
372 String widernodename = xpandquotes.replaceAll(nodename);
373 nodename = widernodename;
374 // jump to after end of quoted nodename
375 nextcp = fcp + nl + 1;
376 parsednodename = true;
380 Error = ErrorStringrange(Error,
381 "Unterminated quotes for nodename", 7, fcp, nf);
391 Error = ErrorStringrange(Error, "Wayward semicolon (depth=" + d
394 // cp advanced at the end of default
398 // node string contains Comment or structured/extended NH format info
400 * if ((fcp-cp>1 && nf.substring(cp,fcp).trim().length()>1)) { // will
401 * process in remains System.err.println("skipped text:
402 * '"+nf.substring(cp,fcp)+"'"); }
404 // verify termination.
405 Regex comment = new Regex("]");
406 if (comment.searchFrom(nf, fcp))
408 // Skip the comment field
409 nextcp = comment.matchedFrom() + 1;
410 warningMessage = "Tree file contained comments which may confuse input algorithm.";
413 // cp advanced at the end of default to nextcp, ncp is unchanged so
414 // any node info can be read.
418 Error = ErrorStringrange(Error, "Unterminated comment", 3, fcp,
424 // Parse simpler field strings
425 String fstring = nf.substring(ncp, fcp);
426 // remove any comments before we parse the node info
427 // TODO: test newick file with quoted square brackets in node name (is
429 while (fstring.indexOf(']') > -1)
431 int cstart = fstring.indexOf('[');
432 int cend = fstring.indexOf(']');
433 commentString2 = fstring.substring(cstart + 1, cend);
434 fstring = fstring.substring(0, cstart)
435 + fstring.substring(cend + 1);
438 Regex uqnodename = new Regex(
439 "\\b([^' :;\\](),]+)");
440 Regex nbootstrap = new Regex(
441 "\\s*([0-9+]+)\\s*:");
442 Regex ndist = new Regex(
446 && uqnodename.search(fstring)
447 && ((uqnodename.matchedFrom(1) == 0) || (fstring
448 .charAt(uqnodename.matchedFrom(1) - 1) != ':'))) // JBPNote
451 if (nodename == null)
453 if (ReplaceUnderscores)
455 nodename = uqnodename.stringMatched(1).replace('_', ' ');
459 nodename = uqnodename.stringMatched(1);
464 Error = ErrorStringrange(Error,
465 "File has broken algorithm - overwritten nodename", 10,
469 // get comment bootstraps
471 if (nbootstrap.search(fstring))
473 if (nbootstrap.stringMatched(1).equals(
474 uqnodename.stringMatched(1)))
476 nodename = null; // no nodename here.
479 || nodename.length() == 0
480 || nbootstrap.matchedFrom(1) > (uqnodename.matchedFrom(1) + uqnodename
481 .stringMatched().length()))
485 bootstrap = (new Integer(nbootstrap.stringMatched(1)))
488 } catch (Exception e)
490 Error = ErrorStringrange(Error,
491 "Can't parse bootstrap value", 4,
492 ncp + nbootstrap.matchedFrom(), nf);
497 boolean nodehasdistance = false;
499 if (ndist.search(fstring))
503 distance = (new Float(ndist.stringMatched(1))).floatValue();
505 nodehasdistance = true;
506 } catch (Exception e)
508 Error = ErrorStringrange(Error,
509 "Can't parse node distance value", 7,
510 ncp + ndist.matchedFrom(), nf);
516 // Write node info here
518 // Trees without distances still need a render distance
519 c.dist = (HasDistances) ? distance : DefDistance;
520 // be consistent for internal bootstrap defaults too
521 c.setBootstrap((HasBootstrap) ? bootstrap : DefBootstrap);
524 RootHasDistance = nodehasdistance; // JBPNote This is really
525 // UGLY!!! Ensure root node gets
526 // its given distance
528 parseNHXNodeProps(c, commentString2);
529 commentString2 = null;
533 // Find a place to put the leaf
534 SequenceNode newnode = new SequenceNode(null, c, nodename,
535 (HasDistances) ? distance : DefDistance,
536 (HasBootstrap) ? bootstrap : DefBootstrap, false);
537 parseNHXNodeProps(c, commentString2);
538 commentString2 = null;
540 if (c.right() == null)
546 if (c.left() == null)
552 // Insert a dummy node for polytomy
553 // dummy nodes have distances
554 SequenceNode newdummy = new SequenceNode(null, c, null,
555 (HasDistances ? 0 : DefDistance), 0, true);
556 newdummy.SetChildren(c.left(), newnode);
564 // move back up the tree from preceding closure
567 if ((d > -1) && (c == null))
569 Error = ErrorStringrange(
571 "File broke algorithm: Lost place in tree (is there an extra ')' ?)",
576 if (nf.charAt(fcp) == ')')
583 if (nf.charAt(fcp) == ',')
591 // Just advance focus, if we need to
592 if ((c.left() != null) && (!c.left().isLeaf()))
594 c = (SequenceNode) c.left();
600 // Reset new node properties to obvious fakes
602 distance = DefDistance;
603 bootstrap = DefBootstrap;
604 commentString2 = null;
605 parsednodename = false;
620 throw (new IOException(MessageManager.formatMessage("exception.newfile", new String[]{Error.toString()})));
624 throw (new IOException(MessageManager.formatMessage("exception.newfile", new String[]{MessageManager.getString("label.no_tree_read_in")})));
626 // THe next line is failing for topali trees - not sure why yet. if
627 // (root.right()!=null && root.isDummy())
628 root = (SequenceNode) root.right().detach(); // remove the imaginary root.
630 if (!RootHasDistance)
632 root.dist = (HasDistances) ? 0 : DefDistance;
637 * parse NHX codes in comment strings and update NewickFile state flags for
638 * distances and bootstraps, and add any additional properties onto the node.
641 * @param commentString
642 * @param commentString2
644 private void parseNHXNodeProps(SequenceNode c, String commentString)
646 // TODO: store raw comment on the sequenceNode so it can be recovered when
648 if (commentString != null && commentString.startsWith("&&NHX"))
650 StringTokenizer st = new StringTokenizer(commentString.substring(5),
652 while (st.hasMoreTokens())
654 String tok = st.nextToken();
655 int colpos = tok.indexOf("=");
659 String code = tok.substring(0, colpos);
660 String value = tok.substring(colpos + 1);
663 // parse out code/value pairs
664 if (code.toLowerCase().equals("b"))
667 Float iv = new Float(value);
668 v = iv.intValue(); // jalview only does integer bootstraps
674 } catch (Exception e)
676 System.err.println("Couldn't parse code '" + code + "' = '"
678 e.printStackTrace(System.err);
689 * @return DOCUMENT ME!
691 public SequenceNode getTree()
697 * Generate a newick format tree according to internal flags for bootstraps,
698 * distances and root distances.
700 * @return new hampshire tree in a single line
702 public String print()
706 StringBuffer tf = new StringBuffer();
709 return (tf.append(";").toString());
716 * Generate a newick format tree according to internal flags for distances and
717 * root distances and user specificied writing of bootstraps.
719 * @param withbootstraps
720 * controls if bootstrap values are explicitly written.
722 * @return new hampshire tree in a single line
724 public String print(boolean withbootstraps)
728 boolean boots = this.HasBootstrap;
729 this.HasBootstrap = withbootstraps;
732 this.HasBootstrap = boots;
740 * Generate newick format tree according to internal flags for writing root
743 * @param withbootstraps
744 * explicitly write bootstrap values
746 * explicitly write distances
748 * @return new hampshire tree in a single line
750 public String print(boolean withbootstraps, boolean withdists)
754 boolean dists = this.HasDistances;
755 this.HasDistances = withdists;
757 String rv = print(withbootstraps);
758 this.HasDistances = dists;
765 * Generate newick format tree according to user specified flags
767 * @param withbootstraps
768 * explicitly write bootstrap values
770 * explicitly write distances
771 * @param printRootInfo
772 * explicitly write root distance
774 * @return new hampshire tree in a single line
776 public String print(boolean withbootstraps, boolean withdists,
777 boolean printRootInfo)
781 boolean rootinfo = printRootInfo;
782 this.printRootInfo = printRootInfo;
784 String rv = print(withbootstraps, withdists);
785 this.printRootInfo = rootinfo;
794 * @return DOCUMENT ME!
807 * @return DOCUMENT ME!
809 char setQuoteChar(char c)
811 char old = QuoteChar;
823 * @return DOCUMENT ME!
825 private String nodeName(String name)
827 if (NodeSafeName[0].search(name))
829 return QuoteChar + NodeSafeName[1].replaceAll(name) + QuoteChar;
833 return NodeSafeName[2].replaceAll(name);
843 * @return DOCUMENT ME!
845 private String printNodeField(SequenceNode c)
847 return ((c.getName() == null) ? "" : nodeName(c.getName()))
848 + ((HasBootstrap) ? ((c.getBootstrap() > -1) ? ((c.getName() != null ? " "
849 : "") + c.getBootstrap())
851 : "") + ((HasDistances) ? (":" + c.dist) : "");
860 * @return DOCUMENT ME!
862 private String printRootField(SequenceNode root)
864 return (printRootInfo) ? (((root.getName() == null) ? ""
865 : nodeName(root.getName()))
866 + ((HasBootstrap) ? ((root.getBootstrap() > -1) ? ((root
867 .getName() != null ? " " : "") + +root.getBootstrap())
868 : "") : "") + ((RootHasDistance) ? (":" + root.dist)
872 // Non recursive call deals with root node properties
873 public void print(StringBuffer tf, SequenceNode root)
877 if (root.isLeaf() && printRootInfo)
879 tf.append(printRootField(root));
885 _print(tf, (SequenceNode) root.right());
886 _print(tf, (SequenceNode) root.left());
891 _print(tf, (SequenceNode) root.right());
893 if (root.left() != null)
898 _print(tf, (SequenceNode) root.left());
899 tf.append(")" + printRootField(root));
905 // Recursive call for non-root nodes
906 public void _print(StringBuffer tf, SequenceNode c)
912 tf.append(printNodeField(c));
918 _print(tf, (SequenceNode) c.left());
919 if (c.left() != null)
923 _print(tf, (SequenceNode) c.right());
928 _print(tf, (SequenceNode) c.right());
930 if (c.left() != null)
935 _print(tf, (SequenceNode) c.left());
936 tf.append(")" + printNodeField(c));
943 public static void main(String[] args)
947 if (args == null || args.length != 1)
950 .println("Takes one argument - file name of a newick tree file.");
954 File fn = new File(args[0]);
956 StringBuffer newickfile = new StringBuffer();
957 BufferedReader treefile = new BufferedReader(new FileReader(fn));
960 while ((l = treefile.readLine()) != null)
962 newickfile.append(l);
966 System.out.println("Read file :\n");
968 NewickFile trf = new NewickFile(args[0], "File");
970 System.out.println("Original file :\n");
972 Regex nonl = new Regex("\n+", "");
973 System.out.println(nonl.replaceAll(newickfile.toString()) + "\n");
975 System.out.println("Parsed file.\n");
976 System.out.println("Default output type for original input.\n");
977 System.out.println(trf.print());
978 System.out.println("Without bootstraps.\n");
979 System.out.println(trf.print(false));
980 System.out.println("Without distances.\n");
981 System.out.println(trf.print(true, false));
982 System.out.println("Without bootstraps but with distanecs.\n");
983 System.out.println(trf.print(false, true));
984 System.out.println("Without bootstraps or distanecs.\n");
985 System.out.println(trf.print(false, false));
986 System.out.println("With bootstraps and with distances.\n");
987 System.out.println(trf.print(true, true));
988 } catch (java.io.IOException e)
990 System.err.println("Exception\n" + e);