2 * Jalview - A Sequence Alignment Editor and Viewer (Version 2.8.2)
3 * Copyright (C) 2014 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.*;
35 * Parse a new hanpshire style tree Caveats: NHX files are NOT supported and the
36 * tree distances and topology are unreliable when they are parsed. TODO: on
37 * this: NHX codes are appended in comments beginning with &&NHX. The codes are
38 * given below (from http://www.phylosoft.org/forester/NHX.html): Element Type
39 * Description Corresponding phyloXML element (parent element in parentheses) no
40 * tag string name of this node/clade (MUST BE FIRST, IF ASSIGNED)
41 * <name>(<clade>) : decimal branch length to parent node (MUST BE SECOND, IF
42 * ASSIGNED) <branch_length>(<clade>) :GN= string gene name <name>(<sequence>)
43 * :AC= string sequence accession <accession>(<sequence>) :ND= string node
44 * identifier - if this is being used, it has to be unique within each phylogeny
45 * <node_id>(<clade>) :B= decimal confidence value for parent branch
46 * <confidence>(<clade>) :D= 'T', 'F', or '?' 'T' if this node represents a
47 * duplication event - 'F' if this node represents a speciation event, '?' if
48 * this node represents an unknown event (D= tag should be replaced by Ev= tag)
49 * n/a :Ev=duplications>speciations>gene losses>event type>duplication type int
50 * int int string string event (replaces the =D tag), number of duplication,
51 * speciation, and gene loss events, type of event (transfer, fusion, root,
52 * unknown, other, speciation_duplication_loss, unassigned) <events>(<clade>)
53 * :E= string EC number at this node <annotation>(<sequence>) :Fu= string
54 * function at this node <annotation>(<sequence>)
55 * :DS=protein-length>from>to>support>name>from>... int int int double string
56 * int ... domain structure at this node <domain_architecture>(<sequence>) :S=
57 * string species name of the species/phylum at this node <taxonomy>(<clade>)
58 * :T= integer taxonomy ID of the species/phylum at this node <id>(<taxonomy>)
59 * :W= integer width of parent branch <width>(<clade>) :C=rrr.ggg.bbb
60 * integer.integer.integer color of parent branch <color>(<clade>) :Co= 'Y' or
61 * 'N' collapse this node when drawing the tree (default is not to collapse) n/a
62 * :XB= string custom data associated with a branch <property>(<clade>) :XN=
63 * string custom data associated with a node <property>(<clade>) :O= integer
64 * orthologous to this external node n/a :SN= integer subtree neighbors n/a :SO=
65 * integer super orthologous (no duplications on paths) to this external node
71 public class NewickFile extends FileParse
75 private boolean HasBootstrap = false;
77 private boolean HasDistances = false;
79 private boolean RootHasDistance = false;
82 boolean ReplaceUnderscores = false;
84 boolean printRootInfo = true;
86 private com.stevesoft.pat.Regex[] NodeSafeName = new com.stevesoft.pat.Regex[]
87 { new com.stevesoft.pat.Regex().perlCode("m/[\\[,:'()]/"), // test for
90 new com.stevesoft.pat.Regex().perlCode("s/'/''/"), // escaping quote
92 new com.stevesoft.pat.Regex().perlCode("s/\\/w/_/") // unqoted whitespace
96 char QuoteChar = '\'';
99 * Creates a new NewickFile object.
104 * @throws IOException
107 public NewickFile(String inStr) throws IOException
109 super(inStr, "Paste");
113 * Creates a new NewickFile object.
120 * @throws IOException
123 public NewickFile(String inFile, String type) throws IOException
128 public NewickFile(FileParse source) throws IOException
134 * Creates a new NewickFile object.
139 public NewickFile(SequenceNode newtree)
145 * Creates a new NewickFile object.
152 public NewickFile(SequenceNode newtree, boolean bootstrap)
154 HasBootstrap = bootstrap;
159 * Creates a new NewickFile object.
168 public NewickFile(SequenceNode newtree, boolean bootstrap,
172 HasBootstrap = bootstrap;
173 HasDistances = distances;
177 * Creates a new NewickFile object.
185 * @param rootdistance
188 public NewickFile(SequenceNode newtree, boolean bootstrap,
189 boolean distances, boolean rootdistance)
192 HasBootstrap = bootstrap;
193 HasDistances = distances;
194 RootHasDistance = rootdistance;
211 * @return DOCUMENT ME!
213 private String ErrorStringrange(String Error, String Er, int r, int p,
216 return ((Error == null) ? "" : Error)
221 + s.substring(((p - r) < 0) ? 0 : (p - r),
222 ((p + r) > s.length()) ? s.length() : (p + r)) + " )\n";
226 // These are set automatically by the reader
227 public boolean HasBootstrap()
235 * @return DOCUMENT ME!
237 public boolean HasDistances()
242 public boolean HasRootDistance()
244 return RootHasDistance;
248 * parse the filesource as a newick file (new hampshire and/or extended)
250 * @throws IOException
251 * with a line number and character position for badly formatted NH
254 public void parse() throws IOException
258 { // fill nf with complete tree file
260 StringBuffer file = new StringBuffer();
262 while ((nf = nextLine()) != null)
267 nf = file.toString();
270 root = new SequenceNode();
272 SequenceNode realroot = null;
273 SequenceNode c = root;
277 // int flen = nf.length();
280 String nodename = null;
281 String commentString2 = null; // comments after simple node props
283 float DefDistance = (float) 0.001; // @param Default distance for a node -
285 int DefBootstrap = -1; // @param Default bootstrap for a node
287 float distance = DefDistance;
288 int bootstrap = DefBootstrap;
290 boolean ascending = false; // flag indicating that we are leaving the
293 com.stevesoft.pat.Regex majorsyms = new com.stevesoft.pat.Regex(
298 boolean parsednodename = false;
299 while (majorsyms.searchFrom(nf, cp) && (Error == null))
301 int fcp = majorsyms.matchedFrom();
303 switch (schar = nf.charAt(fcp))
307 // ascending should not be set
311 Error = ErrorStringrange(Error, "Unexpected '('", 7, fcp, nf);
319 if (c.right() == null)
321 c.setRight(new SequenceNode(null, c, null, DefDistance,
322 DefBootstrap, false));
323 c = (SequenceNode) c.right();
327 if (c.left() != null)
329 // Dummy node for polytomy - keeps c.left free for new node
330 SequenceNode tmpn = new SequenceNode(null, c, null, 0, 0, true);
331 tmpn.SetChildren(c.left(), c.right());
335 c.setLeft(new SequenceNode(null, c, null, DefDistance,
336 DefBootstrap, false));
337 c = (SequenceNode) c.left();
340 if (realroot == null)
346 distance = DefDistance;
347 bootstrap = DefBootstrap;
352 // Deal with quoted fields
355 com.stevesoft.pat.Regex qnodename = new com.stevesoft.pat.Regex(
358 if (qnodename.searchFrom(nf, fcp))
360 int nl = qnodename.stringMatched().length();
361 nodename = new String(qnodename.stringMatched().substring(1,
363 // unpack any escaped colons
364 com.stevesoft.pat.Regex xpandquotes = com.stevesoft.pat.Regex
365 .perlCode("s/''/'/");
366 String widernodename = xpandquotes.replaceAll(nodename);
367 nodename = widernodename;
368 // jump to after end of quoted nodename
369 nextcp = fcp + nl + 1;
370 parsednodename = true;
374 Error = ErrorStringrange(Error,
375 "Unterminated quotes for nodename", 7, fcp, nf);
385 Error = ErrorStringrange(Error, "Wayward semicolon (depth=" + d
388 // cp advanced at the end of default
392 // node string contains Comment or structured/extended NH format info
394 * if ((fcp-cp>1 && nf.substring(cp,fcp).trim().length()>1)) { // will
395 * process in remains System.err.println("skipped text:
396 * '"+nf.substring(cp,fcp)+"'"); }
398 // verify termination.
399 com.stevesoft.pat.Regex comment = new com.stevesoft.pat.Regex("]");
400 if (comment.searchFrom(nf, fcp))
402 // Skip the comment field
403 nextcp = comment.matchedFrom() + 1;
404 warningMessage = "Tree file contained comments which may confuse input algorithm.";
407 // cp advanced at the end of default to nextcp, ncp is unchanged so
408 // any node info can be read.
412 Error = ErrorStringrange(Error, "Unterminated comment", 3, fcp,
418 // Parse simpler field strings
419 String fstring = nf.substring(ncp, fcp);
420 // remove any comments before we parse the node info
421 // TODO: test newick file with quoted square brackets in node name (is
423 while (fstring.indexOf(']') > -1)
425 int cstart = fstring.indexOf('[');
426 int cend = fstring.indexOf(']');
427 commentString2 = fstring.substring(cstart + 1, cend);
428 fstring = fstring.substring(0, cstart)
429 + fstring.substring(cend + 1);
432 com.stevesoft.pat.Regex uqnodename = new com.stevesoft.pat.Regex(
433 "\\b([^' :;\\](),]+)");
434 com.stevesoft.pat.Regex nbootstrap = new com.stevesoft.pat.Regex(
435 "\\s*([0-9+]+)\\s*:");
436 com.stevesoft.pat.Regex ndist = new com.stevesoft.pat.Regex(
440 && uqnodename.search(fstring)
441 && ((uqnodename.matchedFrom(1) == 0) || (fstring
442 .charAt(uqnodename.matchedFrom(1) - 1) != ':'))) // JBPNote
445 if (nodename == null)
447 if (ReplaceUnderscores)
449 nodename = uqnodename.stringMatched(1).replace('_', ' ');
453 nodename = uqnodename.stringMatched(1);
458 Error = ErrorStringrange(Error,
459 "File has broken algorithm - overwritten nodename", 10,
463 // get comment bootstraps
465 if (nbootstrap.search(fstring))
467 if (nbootstrap.stringMatched(1).equals(
468 uqnodename.stringMatched(1)))
470 nodename = null; // no nodename here.
473 || nodename.length() == 0
474 || nbootstrap.matchedFrom(1) > (uqnodename.matchedFrom(1) + uqnodename
475 .stringMatched().length()))
479 bootstrap = (new Integer(nbootstrap.stringMatched(1)))
482 } catch (Exception e)
484 Error = ErrorStringrange(Error,
485 "Can't parse bootstrap value", 4,
486 ncp + nbootstrap.matchedFrom(), nf);
491 boolean nodehasdistance = false;
493 if (ndist.search(fstring))
497 distance = (new Float(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(
565 "File broke algorithm: Lost place in tree (is there an extra ')' ?)",
570 if (nf.charAt(fcp) == ')')
577 if (nf.charAt(fcp) == ',')
585 // Just advance focus, if we need to
586 if ((c.left() != null) && (!c.left().isLeaf()))
588 c = (SequenceNode) c.left();
594 // Reset new node properties to obvious fakes
596 distance = DefDistance;
597 bootstrap = DefBootstrap;
598 commentString2 = null;
599 parsednodename = false;
614 throw (new IOException("NewickFile: " + Error + "\n"));
618 throw (new IOException("NewickFile: No Tree read in\n"));
620 // THe next line is failing for topali trees - not sure why yet. if
621 // (root.right()!=null && root.isDummy())
622 root = (SequenceNode) root.right().detach(); // remove the imaginary root.
624 if (!RootHasDistance)
626 root.dist = (HasDistances) ? 0 : DefDistance;
631 * parse NHX codes in comment strings and update NewickFile state flags for
632 * distances and bootstraps, and add any additional properties onto the node.
635 * @param commentString
636 * @param commentString2
638 private void parseNHXNodeProps(SequenceNode c, String commentString)
640 // TODO: store raw comment on the sequenceNode so it can be recovered when
642 if (commentString != null && commentString.startsWith("&&NHX"))
644 StringTokenizer st = new StringTokenizer(commentString.substring(5),
646 while (st.hasMoreTokens())
648 String tok = st.nextToken();
649 int colpos = tok.indexOf("=");
653 String code = tok.substring(0, colpos);
654 String value = tok.substring(colpos + 1);
657 // parse out code/value pairs
658 if (code.toLowerCase().equals("b"))
661 Float iv = new Float(value);
662 v = iv.intValue(); // jalview only does integer bootstraps
668 } catch (Exception e)
670 System.err.println("Couldn't parse code '" + code + "' = '"
672 e.printStackTrace(System.err);
683 * @return DOCUMENT ME!
685 public SequenceNode getTree()
691 * Generate a newick format tree according to internal flags for bootstraps,
692 * distances and root distances.
694 * @return new hampshire tree in a single line
696 public String print()
700 StringBuffer tf = new StringBuffer();
703 return (tf.append(";").toString());
710 * Generate a newick format tree according to internal flags for distances and
711 * root distances and user specificied writing of bootstraps.
713 * @param withbootstraps
714 * controls if bootstrap values are explicitly written.
716 * @return new hampshire tree in a single line
718 public String print(boolean withbootstraps)
722 boolean boots = this.HasBootstrap;
723 this.HasBootstrap = withbootstraps;
726 this.HasBootstrap = boots;
734 * Generate newick format tree according to internal flags for writing root
737 * @param withbootstraps
738 * explicitly write bootstrap values
740 * explicitly write distances
742 * @return new hampshire tree in a single line
744 public String print(boolean withbootstraps, boolean withdists)
748 boolean dists = this.HasDistances;
749 this.HasDistances = withdists;
751 String rv = print(withbootstraps);
752 this.HasDistances = dists;
759 * Generate newick format tree according to user specified flags
761 * @param withbootstraps
762 * explicitly write bootstrap values
764 * explicitly write distances
765 * @param printRootInfo
766 * explicitly write root distance
768 * @return new hampshire tree in a single line
770 public String print(boolean withbootstraps, boolean withdists,
771 boolean printRootInfo)
775 boolean rootinfo = printRootInfo;
776 this.printRootInfo = printRootInfo;
778 String rv = print(withbootstraps, withdists);
779 this.printRootInfo = rootinfo;
788 * @return DOCUMENT ME!
801 * @return DOCUMENT ME!
803 char setQuoteChar(char c)
805 char old = QuoteChar;
817 * @return DOCUMENT ME!
819 private String nodeName(String name)
821 if (NodeSafeName[0].search(name))
823 return QuoteChar + NodeSafeName[1].replaceAll(name) + QuoteChar;
827 return NodeSafeName[2].replaceAll(name);
837 * @return DOCUMENT ME!
839 private String printNodeField(SequenceNode c)
841 return ((c.getName() == null) ? "" : nodeName(c.getName()))
842 + ((HasBootstrap) ? ((c.getBootstrap() > -1) ? ((c.getName() != null ? " "
843 : "") + c.getBootstrap())
845 : "") + ((HasDistances) ? (":" + c.dist) : "");
854 * @return DOCUMENT ME!
856 private String printRootField(SequenceNode root)
858 return (printRootInfo) ? (((root.getName() == null) ? ""
859 : nodeName(root.getName()))
860 + ((HasBootstrap) ? ((root.getBootstrap() > -1) ? ((root
861 .getName() != null ? " " : "") + +root.getBootstrap())
862 : "") : "") + ((RootHasDistance) ? (":" + root.dist)
866 // Non recursive call deals with root node properties
867 public void print(StringBuffer tf, SequenceNode root)
871 if (root.isLeaf() && printRootInfo)
873 tf.append(printRootField(root));
879 _print(tf, (SequenceNode) root.right());
880 _print(tf, (SequenceNode) root.left());
885 _print(tf, (SequenceNode) root.right());
887 if (root.left() != null)
892 _print(tf, (SequenceNode) root.left());
893 tf.append(")" + printRootField(root));
899 // Recursive call for non-root nodes
900 public void _print(StringBuffer tf, SequenceNode c)
906 tf.append(printNodeField(c));
912 _print(tf, (SequenceNode) c.left());
913 if (c.left() != null)
917 _print(tf, (SequenceNode) c.right());
922 _print(tf, (SequenceNode) c.right());
924 if (c.left() != null)
929 _print(tf, (SequenceNode) c.left());
930 tf.append(")" + printNodeField(c));
937 public static void main(String[] args)
941 if (args == null || args.length != 1)
944 .println("Takes one argument - file name of a newick tree file.");
948 File fn = new File(args[0]);
950 StringBuffer newickfile = new StringBuffer();
951 BufferedReader treefile = new BufferedReader(new FileReader(fn));
954 while ((l = treefile.readLine()) != null)
956 newickfile.append(l);
960 System.out.println("Read file :\n");
962 NewickFile trf = new NewickFile(args[0], "File");
964 System.out.println("Original file :\n");
966 com.stevesoft.pat.Regex nonl = new com.stevesoft.pat.Regex("\n+", "");
967 System.out.println(nonl.replaceAll(newickfile.toString()) + "\n");
969 System.out.println("Parsed file.\n");
970 System.out.println("Default output type for original input.\n");
971 System.out.println(trf.print());
972 System.out.println("Without bootstraps.\n");
973 System.out.println(trf.print(false));
974 System.out.println("Without distances.\n");
975 System.out.println(trf.print(true, false));
976 System.out.println("Without bootstraps but with distanecs.\n");
977 System.out.println(trf.print(false, true));
978 System.out.println("Without bootstraps or distanecs.\n");
979 System.out.println(trf.print(false, false));
980 System.out.println("With bootstraps and with distances.\n");
981 System.out.println(trf.print(true, true));
982 } catch (java.io.IOException e)
984 System.err.println("Exception\n" + e);