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.perlCode("s/''/'/");
365 String widernodename = xpandquotes.replaceAll(nodename);
366 nodename=widernodename;
367 // jump to after end of quoted nodename
368 nextcp = fcp + nl + 1;
373 Error = ErrorStringrange(Error,
374 "Unterminated quotes for nodename", 7, fcp, nf);
384 Error = ErrorStringrange(Error, "Wayward semicolon (depth=" + d
387 // cp advanced at the end of default
391 // node string contains Comment or structured/extended NH format info
393 * if ((fcp-cp>1 && nf.substring(cp,fcp).trim().length()>1)) { // will
394 * process in remains System.err.println("skipped text:
395 * '"+nf.substring(cp,fcp)+"'"); }
397 // verify termination.
398 com.stevesoft.pat.Regex comment = new com.stevesoft.pat.Regex("]");
399 if (comment.searchFrom(nf, fcp))
401 // Skip the comment field
402 nextcp = comment.matchedFrom() + 1;
403 warningMessage = "Tree file contained comments which may confuse input algorithm.";
406 // cp advanced at the end of default to nextcp, ncp is unchanged so
407 // any node info can be read.
411 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 com.stevesoft.pat.Regex uqnodename = new com.stevesoft.pat.Regex(
432 "\\b([^' :;\\](),]+)");
433 com.stevesoft.pat.Regex nbootstrap = new com.stevesoft.pat.Regex(
434 "\\s*([0-9+]+)\\s*:");
435 com.stevesoft.pat.Regex ndist = new com.stevesoft.pat.Regex(
438 if (!parsednodename && uqnodename.search(fstring)
439 && ((uqnodename.matchedFrom(1) == 0) || (fstring
440 .charAt(uqnodename.matchedFrom(1) - 1) != ':'))) // JBPNote
443 if (nodename == null)
445 if (ReplaceUnderscores)
447 nodename = uqnodename.stringMatched(1).replace('_', ' ');
451 nodename = uqnodename.stringMatched(1);
456 Error = ErrorStringrange(Error,
457 "File has broken algorithm - overwritten nodename", 10,
461 // get comment bootstraps
463 if (nbootstrap.search(fstring))
465 if (nbootstrap.stringMatched(1).equals(
466 uqnodename.stringMatched(1)))
468 nodename = null; // no nodename here.
471 || nodename.length() == 0
472 || nbootstrap.matchedFrom(1) > (uqnodename.matchedFrom(1) + uqnodename
473 .stringMatched().length()))
477 bootstrap = (new Integer(nbootstrap.stringMatched(1)))
480 } catch (Exception e)
482 Error = ErrorStringrange(Error,
483 "Can't parse bootstrap value", 4,
484 ncp + nbootstrap.matchedFrom(), nf);
489 boolean nodehasdistance = false;
491 if (ndist.search(fstring))
495 distance = (new Float(ndist.stringMatched(1))).floatValue();
497 nodehasdistance = true;
498 } catch (Exception e)
500 Error = ErrorStringrange(Error,
501 "Can't parse node distance value", 7,
502 ncp + ndist.matchedFrom(), nf);
508 // Write node info here
510 // Trees without distances still need a render distance
511 c.dist = (HasDistances) ? distance : DefDistance;
512 // be consistent for internal bootstrap defaults too
513 c.setBootstrap((HasBootstrap) ? bootstrap : DefBootstrap);
516 RootHasDistance = nodehasdistance; // JBPNote This is really
517 // UGLY!!! Ensure root node gets
518 // its given distance
520 parseNHXNodeProps(c, commentString2);
521 commentString2 = null;
525 // Find a place to put the leaf
526 SequenceNode newnode = new SequenceNode(null, c, nodename,
527 (HasDistances) ? distance : DefDistance,
528 (HasBootstrap) ? bootstrap : DefBootstrap, false);
529 parseNHXNodeProps(c, commentString2);
530 commentString2 = null;
532 if (c.right() == null)
538 if (c.left() == null)
544 // Insert a dummy node for polytomy
545 // dummy nodes have distances
546 SequenceNode newdummy = new SequenceNode(null, c, null,
547 (HasDistances ? 0 : DefDistance), 0, true);
548 newdummy.SetChildren(c.left(), newnode);
556 // move back up the tree from preceding closure
559 if ((d > -1) && (c == null))
561 Error = ErrorStringrange(
563 "File broke algorithm: Lost place in tree (is there an extra ')' ?)",
568 if (nf.charAt(fcp) == ')')
575 if (nf.charAt(fcp) == ',')
583 // Just advance focus, if we need to
584 if ((c.left() != null) && (!c.left().isLeaf()))
586 c = (SequenceNode) c.left();
592 // Reset new node properties to obvious fakes
594 distance = DefDistance;
595 bootstrap = DefBootstrap;
596 commentString2 = null;
597 parsednodename=false;
612 throw (new IOException("NewickFile: " + Error + "\n"));
616 throw (new IOException("NewickFile: No Tree read in\n"));
618 // THe next line is failing for topali trees - not sure why yet. if
619 // (root.right()!=null && root.isDummy())
620 root = (SequenceNode) root.right().detach(); // remove the imaginary root.
622 if (!RootHasDistance)
624 root.dist = (HasDistances) ? 0 : DefDistance;
629 * parse NHX codes in comment strings and update NewickFile state flags for
630 * distances and bootstraps, and add any additional properties onto the node.
633 * @param commentString
634 * @param commentString2
636 private void parseNHXNodeProps(SequenceNode c, String commentString)
638 // TODO: store raw comment on the sequenceNode so it can be recovered when
640 if (commentString != null && commentString.startsWith("&&NHX"))
642 StringTokenizer st = new StringTokenizer(commentString.substring(5),
644 while (st.hasMoreTokens())
646 String tok = st.nextToken();
647 int colpos = tok.indexOf("=");
651 String code = tok.substring(0, colpos);
652 String value = tok.substring(colpos + 1);
655 // parse out code/value pairs
656 if (code.toLowerCase().equals("b"))
659 Float iv = new Float(value);
660 v = iv.intValue(); // jalview only does integer bootstraps
666 } catch (Exception e)
668 System.err.println("Couldn't parse code '" + code + "' = '"
670 e.printStackTrace(System.err);
681 * @return DOCUMENT ME!
683 public SequenceNode getTree()
689 * Generate a newick format tree according to internal flags for bootstraps,
690 * distances and root distances.
692 * @return new hampshire tree in a single line
694 public String print()
698 StringBuffer tf = new StringBuffer();
701 return (tf.append(";").toString());
708 * Generate a newick format tree according to internal flags for distances and
709 * root distances and user specificied writing of bootstraps.
711 * @param withbootstraps
712 * controls if bootstrap values are explicitly written.
714 * @return new hampshire tree in a single line
716 public String print(boolean withbootstraps)
720 boolean boots = this.HasBootstrap;
721 this.HasBootstrap = withbootstraps;
724 this.HasBootstrap = boots;
732 * Generate newick format tree according to internal flags for writing root
735 * @param withbootstraps
736 * explicitly write bootstrap values
738 * explicitly write distances
740 * @return new hampshire tree in a single line
742 public String print(boolean withbootstraps, boolean withdists)
746 boolean dists = this.HasDistances;
747 this.HasDistances = withdists;
749 String rv = print(withbootstraps);
750 this.HasDistances = dists;
757 * Generate newick format tree according to user specified flags
759 * @param withbootstraps
760 * explicitly write bootstrap values
762 * explicitly write distances
763 * @param printRootInfo
764 * explicitly write root distance
766 * @return new hampshire tree in a single line
768 public String print(boolean withbootstraps, boolean withdists,
769 boolean printRootInfo)
773 boolean rootinfo = printRootInfo;
774 this.printRootInfo = printRootInfo;
776 String rv = print(withbootstraps, withdists);
777 this.printRootInfo = rootinfo;
786 * @return DOCUMENT ME!
799 * @return DOCUMENT ME!
801 char setQuoteChar(char c)
803 char old = QuoteChar;
815 * @return DOCUMENT ME!
817 private String nodeName(String name)
819 if (NodeSafeName[0].search(name))
821 return QuoteChar + NodeSafeName[1].replaceAll(name) + QuoteChar;
825 return NodeSafeName[2].replaceAll(name);
835 * @return DOCUMENT ME!
837 private String printNodeField(SequenceNode c)
839 return ((c.getName() == null) ? "" : nodeName(c.getName()))
840 + ((HasBootstrap) ? ((c.getBootstrap() > -1) ? ((c.getName() != null ? " "
841 : "") + c.getBootstrap())
843 : "") + ((HasDistances) ? (":" + c.dist) : "");
852 * @return DOCUMENT ME!
854 private String printRootField(SequenceNode root)
856 return (printRootInfo) ? (((root.getName() == null) ? ""
857 : nodeName(root.getName()))
858 + ((HasBootstrap) ? ((root.getBootstrap() > -1) ? ((root
859 .getName() != null ? " " : "") + +root.getBootstrap())
860 : "") : "") + ((RootHasDistance) ? (":" + root.dist)
864 // Non recursive call deals with root node properties
865 public void print(StringBuffer tf, SequenceNode root)
869 if (root.isLeaf() && printRootInfo)
871 tf.append(printRootField(root));
877 _print(tf, (SequenceNode) root.right());
878 _print(tf, (SequenceNode) root.left());
883 _print(tf, (SequenceNode) root.right());
885 if (root.left() != null)
890 _print(tf, (SequenceNode) root.left());
891 tf.append(")" + printRootField(root));
897 // Recursive call for non-root nodes
898 public void _print(StringBuffer tf, SequenceNode c)
904 tf.append(printNodeField(c));
910 _print(tf, (SequenceNode) c.left());
911 if (c.left() != null)
915 _print(tf, (SequenceNode) c.right());
920 _print(tf, (SequenceNode) c.right());
922 if (c.left() != null)
927 _print(tf, (SequenceNode) c.left());
928 tf.append(")" + printNodeField(c));
935 public static void main(String[] args)
939 if (args == null || args.length != 1)
942 .println("Takes one argument - file name of a newick tree file.");
946 File fn = new File(args[0]);
948 StringBuffer newickfile = new StringBuffer();
949 BufferedReader treefile = new BufferedReader(new FileReader(fn));
952 while ((l = treefile.readLine()) != null)
954 newickfile.append(l);
958 System.out.println("Read file :\n");
960 NewickFile trf = new NewickFile(args[0], "File");
962 System.out.println("Original file :\n");
964 com.stevesoft.pat.Regex nonl = new com.stevesoft.pat.Regex("\n+", "");
965 System.out.println(nonl.replaceAll(newickfile.toString()) + "\n");
967 System.out.println("Parsed file.\n");
968 System.out.println("Default output type for original input.\n");
969 System.out.println(trf.print());
970 System.out.println("Without bootstraps.\n");
971 System.out.println(trf.print(false));
972 System.out.println("Without distances.\n");
973 System.out.println(trf.print(true, false));
974 System.out.println("Without bootstraps but with distanecs.\n");
975 System.out.println(trf.print(false, true));
976 System.out.println("Without bootstraps or distanecs.\n");
977 System.out.println(trf.print(false, false));
978 System.out.println("With bootstraps and with distances.\n");
979 System.out.println(trf.print(true, true));
980 } catch (java.io.IOException e)
982 System.err.println("Exception\n" + e);