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;
31 import jalview.util.Platform;
33 import java.io.BufferedReader;
35 import java.io.FileReader;
36 import java.io.IOException;
37 import java.util.StringTokenizer;
39 import com.stevesoft.pat.Regex;
41 // TODO This class does not conform to Java standards for field name capitalization.
44 * Parse a new hanpshire style tree Caveats: NHX files are NOT supported and the
45 * tree distances and topology are unreliable when they are parsed. TODO: on
46 * this: NHX codes are appended in comments beginning with &&NHX. The codes are
47 * given below (from http://www.phylosoft.org/forester/NHX.html): Element Type
48 * Description Corresponding phyloXML element (parent element in parentheses) no
49 * tag string name of this node/clade (MUST BE FIRST, IF ASSIGNED)
50 * <name>(<clade>) : decimal branch length to parent node (MUST BE SECOND, IF
51 * ASSIGNED) <branch_length>(<clade>) :GN= string gene name <name>(<sequence>)
52 * :AC= string sequence accession <accession>(<sequence>) :ND= string node
53 * identifier - if this is being used, it has to be unique within each phylogeny
54 * <node_id>(<clade>) :B= decimal confidence value for parent branch
55 * <confidence>(<clade>) :D= 'T', 'F', or '?' 'T' if this node represents a
56 * duplication event - 'F' if this node represents a speciation event, '?' if
57 * this node represents an unknown event (D= tag should be replaced by Ev= tag)
58 * n/a :Ev=duplications>speciations>gene losses>event type>duplication type int
59 * int int string string event (replaces the =D tag), number of duplication,
60 * speciation, and gene loss events, type of event (transfer, fusion, root,
61 * unknown, other, speciation_duplication_loss, unassigned) <events>(<clade>)
62 * :E= string EC number at this node <annotation>(<sequence>) :Fu= string
63 * function at this node <annotation>(<sequence>)
64 * :DS=protein-length>from>to>support>name>from>... int int int double string
65 * int ... domain structure at this node <domain_architecture>(<sequence>) :S=
66 * string species name of the species/phylum at this node <taxonomy>(<clade>)
67 * :T= integer taxonomy ID of the species/phylum at this node <id>(<taxonomy>)
68 * :W= integer width of parent branch <width>(<clade>) :C=rrr.ggg.bbb
69 * integer.integer.integer color of parent branch <color>(<clade>) :Co= 'Y' or
70 * 'N' collapse this node when drawing the tree (default is not to collapse) n/a
71 * :XB= string custom data associated with a branch <property>(<clade>) :XN=
72 * string custom data associated with a node <property>(<clade>) :O= integer
73 * orthologous to this external node n/a :SN= integer subtree neighbors n/a :SO=
74 * integer super orthologous (no duplications on paths) to this external node
80 public class NewickFile extends FileParse
82 private SequenceNode root;
84 private boolean HasBootstrap = false;
86 private boolean HasDistances = false;
88 private boolean RootHasDistance = false;
91 private boolean ReplaceUnderscores = false;
93 private boolean printRootInfo = true;
95 private static final int REGEX_PERL_NODE_REQUIRE_QUOTE = 0;
97 private static final int REGEX_PERL_NODE_ESCAPE_QUOTE = 1;
99 private static final int REGEX_PERL_NODE_UNQUOTED_WHITESPACE = 2;
101 private static final int REGEX_MAJOR_SYMS = 3;
103 private static final int REGEX_QNODE_NAME = 4;
105 private static final int REGEX_COMMENT = 5;
107 private static final int REGEX_UQNODE_NAME = 6;
109 private static final int REGEX_NBOOTSTRAP = 7;
111 private static final int REGEX_NDIST = 8;
113 private static final int REGEX_NO_LINES = 9;
115 private static final int REGEX_PERL_EXPAND_QUOTES = 10;
117 private static final int REGEX_MAX = 11;
119 private static final Regex[] REGEX = new Regex[REGEX_MAX];
121 private static Regex getRegex(int id)
123 if (REGEX[id] == null)
127 String codePerl = null;
130 case REGEX_PERL_NODE_REQUIRE_QUOTE:
131 codePerl = "m/[\\[,:'()]/";
133 case REGEX_PERL_NODE_ESCAPE_QUOTE:
134 codePerl = "s/'/''/";
136 case REGEX_PERL_NODE_UNQUOTED_WHITESPACE:
137 codePerl = "s/\\/w/_/";
139 case REGEX_PERL_EXPAND_QUOTES:
140 codePerl = "s/''/'/";
142 case REGEX_MAJOR_SYMS:
145 case REGEX_QNODE_NAME:
146 code = "'([^']|'')+'";
151 case REGEX_UQNODE_NAME:
152 code = "\\b([^' :;\\](),]+)";
154 case REGEX_NBOOTSTRAP:
155 code = "\\s*([0-9+]+)\\s*:";
158 code = ":([-0-9Ee.+]+)";
167 return codePerl == null ? Platform.newRegex(code, code2)
168 : Platform.newRegexPerl(codePerl);
174 private char quoteChar = '\'';
177 * Creates a new NewickFile object.
182 * @throws IOException
185 public NewickFile(String inStr) throws IOException
187 super(inStr, DataSourceType.PASTE);
191 * Creates a new NewickFile object.
198 * @throws IOException
201 public NewickFile(String inFile, DataSourceType protocol)
204 super(inFile, protocol);
207 public NewickFile(FileParse source) throws IOException
213 * Creates a new NewickFile object.
218 public NewickFile(SequenceNode newtree)
224 * Creates a new NewickFile object.
231 public NewickFile(SequenceNode newtree, boolean bootstrap)
233 HasBootstrap = bootstrap;
238 * Creates a new NewickFile object.
247 public NewickFile(SequenceNode newtree, boolean bootstrap,
251 HasBootstrap = bootstrap;
252 HasDistances = distances;
256 * Creates a new NewickFile object.
264 * @param rootdistance
267 public NewickFile(SequenceNode newtree, boolean bootstrap,
268 boolean distances, boolean rootdistance)
271 HasBootstrap = bootstrap;
272 HasDistances = distances;
273 RootHasDistance = rootdistance;
290 * @return DOCUMENT ME!
292 private String ErrorStringrange(String Error, String Er, int r, int p,
295 return ((Error == null) ? "" : Error) + Er + " at position " + p + " ( "
296 + s.substring(((p - r) < 0) ? 0 : (p - r),
297 ((p + r) > s.length()) ? s.length() : (p + r))
302 // These are set automatically by the reader
303 public boolean HasBootstrap()
311 * @return DOCUMENT ME!
313 public boolean HasDistances()
318 public boolean HasRootDistance()
320 return RootHasDistance;
324 * parse the filesource as a newick file (new hampshire and/or extended)
326 * @throws IOException
327 * with a line number and character position for badly formatted NH
330 public void parse() throws IOException
332 Platform.ensureRegex();
335 { // fill nf with complete tree file
337 StringBuffer file = new StringBuffer();
339 while ((nf = nextLine()) != null)
344 nf = file.toString();
347 root = new SequenceNode();
349 SequenceNode realroot = null;
350 SequenceNode c = root;
354 // int flen = nf.length();
357 String nodename = null;
358 String commentString2 = null; // comments after simple node props
360 float DefDistance = (float) 0.001; // @param Default distance for a node -
362 int DefBootstrap = -1; // @param Default bootstrap for a node
364 float distance = DefDistance;
365 int bootstrap = DefBootstrap;
367 boolean ascending = false; // flag indicating that we are leaving the
370 Regex majorsyms = getRegex(REGEX_MAJOR_SYMS); // "[(\\['),;]"
374 boolean parsednodename = false;
375 while (majorsyms.searchFrom(nf, cp) && (Error == null))
377 int fcp = majorsyms.matchedFrom();
379 switch (schar = nf.charAt(fcp))
383 // ascending should not be set
387 Error = ErrorStringrange(Error, "Unexpected '('", 7, fcp, nf);
393 if (c.right() == null)
395 c.setRight(new SequenceNode(null, c, null, DefDistance,
396 DefBootstrap, false));
397 c = (SequenceNode) c.right();
401 if (c.left() != null)
403 // Dummy node for polytomy - keeps c.left free for new node
404 SequenceNode tmpn = new SequenceNode(null, c, null, 0, 0, true);
405 tmpn.SetChildren(c.left(), c.right());
409 c.setLeft(new SequenceNode(null, c, null, DefDistance,
410 DefBootstrap, false));
411 c = (SequenceNode) c.left();
414 if (realroot == null)
420 distance = DefDistance;
421 bootstrap = DefBootstrap;
426 // Deal with quoted fields
429 Regex qnodename = getRegex(REGEX_QNODE_NAME);// "'([^']|'')+'");
431 if (qnodename.searchFrom(nf, fcp))
433 int nl = qnodename.stringMatched().length();
434 nodename = new String(
435 qnodename.stringMatched().substring(1, nl - 1));
436 // unpack any escaped colons
437 Regex xpandquotes = getRegex(REGEX_PERL_EXPAND_QUOTES);
438 String widernodename = xpandquotes.replaceAll(nodename);
439 nodename = widernodename;
440 // jump to after end of quoted nodename
441 nextcp = fcp + nl + 1;
442 parsednodename = true;
446 Error = ErrorStringrange(Error,
447 "Unterminated quotes for nodename", 7, fcp, nf);
457 Error = ErrorStringrange(Error,
458 "Wayward semicolon (depth=" + d + ")", 7, fcp, nf);
460 // cp advanced at the end of default
464 // node string contains Comment or structured/extended NH format info
466 * if ((fcp-cp>1 && nf.substring(cp,fcp).trim().length()>1)) { // will
467 * process in remains System.err.println("skipped text:
468 * '"+nf.substring(cp,fcp)+"'"); }
470 // verify termination.
471 Regex comment = getRegex(REGEX_COMMENT); // "]"
472 if (comment.searchFrom(nf, fcp))
474 // Skip the comment field
475 nextcp = comment.matchedFrom() + 1;
476 warningMessage = "Tree file contained comments which may confuse input algorithm.";
479 // cp advanced at the end of default to nextcp, ncp is unchanged so
480 // any node info can be read.
484 Error = ErrorStringrange(Error, "Unterminated comment", 3, fcp,
488 // Parse simpler field strings
489 String fstring = nf.substring(ncp, fcp);
490 // remove any comments before we parse the node info
491 // TODO: test newick file with quoted square brackets in node name (is
493 while (fstring.indexOf(']') > -1)
495 int cstart = fstring.indexOf('[');
496 int cend = fstring.indexOf(']');
497 commentString2 = fstring.substring(cstart + 1, cend);
498 fstring = fstring.substring(0, cstart)
499 + fstring.substring(cend + 1);
502 Regex uqnodename = getRegex(REGEX_UQNODE_NAME);// "\\b([^' :;\\](),]+)"
503 Regex nbootstrap = getRegex(REGEX_NBOOTSTRAP);// "\\s*([0-9+]+)\\s*:");
504 Regex ndist = getRegex(REGEX_NDIST);// ":([-0-9Ee.+]+)");
506 if (!parsednodename && uqnodename.search(fstring)
507 && ((uqnodename.matchedFrom(1) == 0) || (fstring
508 .charAt(uqnodename.matchedFrom(1) - 1) != ':'))) // JBPNote
511 if (nodename == null)
513 if (ReplaceUnderscores)
515 nodename = uqnodename.stringMatched(1).replace('_', ' ');
519 nodename = uqnodename.stringMatched(1);
524 Error = ErrorStringrange(Error,
525 "File has broken algorithm - overwritten nodename", 10,
529 // get comment bootstraps
531 if (nbootstrap.search(fstring))
533 if (nbootstrap.stringMatched(1)
534 .equals(uqnodename.stringMatched(1)))
536 nodename = null; // no nodename here.
538 if (nodename == null || nodename.length() == 0
539 || nbootstrap.matchedFrom(1) > (uqnodename.matchedFrom(1)
540 + uqnodename.stringMatched().length()))
544 bootstrap = (Integer.valueOf(nbootstrap.stringMatched(1)))
547 } catch (Exception e)
549 Error = ErrorStringrange(Error, "Can't parse bootstrap value",
550 4, ncp + nbootstrap.matchedFrom(), nf);
555 boolean nodehasdistance = false;
557 if (ndist.search(fstring))
561 distance = (Float.valueOf(ndist.stringMatched(1))).floatValue();
563 nodehasdistance = true;
564 } catch (Exception e)
566 Error = ErrorStringrange(Error,
567 "Can't parse node distance value", 7,
568 ncp + ndist.matchedFrom(), nf);
574 // Write node info here
576 // Trees without distances still need a render distance
577 c.dist = (HasDistances) ? distance : DefDistance;
578 // be consistent for internal bootstrap defaults too
579 c.setBootstrap((HasBootstrap) ? bootstrap : DefBootstrap);
582 RootHasDistance = nodehasdistance; // JBPNote This is really
583 // UGLY!!! Ensure root node gets
584 // its given distance
586 parseNHXNodeProps(c, commentString2);
587 commentString2 = null;
591 // Find a place to put the leaf
592 SequenceNode newnode = new SequenceNode(null, c, nodename,
593 (HasDistances) ? distance : DefDistance,
594 (HasBootstrap) ? bootstrap : DefBootstrap, false);
595 parseNHXNodeProps(c, commentString2);
596 commentString2 = null;
598 if (c.right() == null)
604 if (c.left() == null)
610 // Insert a dummy node for polytomy
611 // dummy nodes have distances
612 SequenceNode newdummy = new SequenceNode(null, c, null,
613 (HasDistances ? 0 : DefDistance), 0, true);
614 newdummy.SetChildren(c.left(), newnode);
622 // move back up the tree from preceding closure
625 if ((d > -1) && (c == null))
627 Error = ErrorStringrange(Error,
628 "File broke algorithm: Lost place in tree (is there an extra ')' ?)",
633 if (nf.charAt(fcp) == ')')
640 if (nf.charAt(fcp) == ',')
648 // Just advance focus, if we need to
649 if ((c.left() != null) && (!c.left().isLeaf()))
651 c = (SequenceNode) c.left();
657 // Reset new node properties to obvious fakes
659 distance = DefDistance;
660 bootstrap = DefBootstrap;
661 commentString2 = null;
662 parsednodename = false;
677 throw (new IOException(
678 MessageManager.formatMessage("exception.newfile", new String[]
679 { Error.toString() })));
683 throw (new IOException(
684 MessageManager.formatMessage("exception.newfile", new String[]
685 { MessageManager.getString("label.no_tree_read_in") })));
687 // THe next line is failing for topali trees - not sure why yet. if
688 // (root.right()!=null && root.isDummy())
689 root = (SequenceNode) root.right().detach(); // remove the imaginary root.
691 if (!RootHasDistance)
693 root.dist = (HasDistances) ? 0 : DefDistance;
698 * parse NHX codes in comment strings and update NewickFile state flags for
699 * distances and bootstraps, and add any additional properties onto the node.
702 * @param commentString
703 * @param commentString2
705 private void parseNHXNodeProps(SequenceNode c, String commentString)
707 // TODO: store raw comment on the sequenceNode so it can be recovered when
709 if (commentString != null && commentString.startsWith("&&NHX"))
711 StringTokenizer st = new StringTokenizer(commentString.substring(5),
713 while (st.hasMoreTokens())
715 String tok = st.nextToken();
716 int colpos = tok.indexOf("=");
720 String code = tok.substring(0, colpos);
721 String value = tok.substring(colpos + 1);
724 // parse out code/value pairs
725 if (code.toLowerCase().equals("b"))
728 Float iv = Float.valueOf(value);
729 v = iv.intValue(); // jalview only does integer bootstraps
735 } catch (Exception e)
738 "Couldn't parse code '" + code + "' = '" + value + "'");
739 e.printStackTrace(System.err);
750 * @return DOCUMENT ME!
752 public SequenceNode getTree()
758 * Generate a newick format tree according to internal flags for bootstraps,
759 * distances and root distances.
761 * @return new hampshire tree in a single line
763 public String print()
767 StringBuffer tf = new StringBuffer();
770 return (tf.append(";").toString());
777 * Generate a newick format tree according to internal flags for distances and
778 * root distances and user specificied writing of bootstraps.
780 * @param withbootstraps
781 * controls if bootstrap values are explicitly written.
783 * @return new hampshire tree in a single line
785 public String print(boolean withbootstraps)
789 boolean boots = this.HasBootstrap;
790 this.HasBootstrap = withbootstraps;
793 this.HasBootstrap = boots;
801 * Generate newick format tree according to internal flags for writing root
804 * @param withbootstraps
805 * explicitly write bootstrap values
807 * explicitly write distances
809 * @return new hampshire tree in a single line
811 public String print(boolean withbootstraps, boolean withdists)
815 boolean dists = this.HasDistances;
816 this.HasDistances = withdists;
818 String rv = print(withbootstraps);
819 this.HasDistances = dists;
826 * Generate newick format tree according to user specified flags
828 * @param withbootstraps
829 * explicitly write bootstrap values
831 * explicitly write distances
832 * @param printRootInfo
833 * explicitly write root distance
835 * @return new hampshire tree in a single line
837 public String print(boolean withbootstraps, boolean withdists,
838 boolean printRootInfo)
842 boolean rootinfo = printRootInfo;
843 this.printRootInfo = printRootInfo;
845 String rv = print(withbootstraps, withdists);
846 this.printRootInfo = rootinfo;
855 * @return DOCUMENT ME!
868 * @return DOCUMENT ME!
870 char setQuoteChar(char c)
872 char old = quoteChar;
884 * @return DOCUMENT ME!
886 private String nodeName(String name)
888 if (getRegex(REGEX_PERL_NODE_REQUIRE_QUOTE).search(name))
891 + getRegex(REGEX_PERL_NODE_ESCAPE_QUOTE).replaceAll(name)
896 return getRegex(REGEX_PERL_NODE_UNQUOTED_WHITESPACE).replaceAll(name);
906 * @return DOCUMENT ME!
908 private String printNodeField(SequenceNode c)
910 return ((c.getName() == null) ? "" : nodeName(c.getName()))
911 + ((HasBootstrap) ? ((c.getBootstrap() > -1)
912 ? ((c.getName() != null ? " " : "") + c.getBootstrap())
914 + ((HasDistances) ? (":" + c.dist) : "");
923 * @return DOCUMENT ME!
925 private String printRootField(SequenceNode root)
927 return (printRootInfo)
928 ? (((root.getName() == null) ? "" : nodeName(root.getName()))
930 ? ((root.getBootstrap() > -1)
931 ? ((root.getName() != null ? " " : "")
932 + +root.getBootstrap())
935 + ((RootHasDistance) ? (":" + root.dist) : ""))
939 // Non recursive call deals with root node properties
940 public void print(StringBuffer tf, SequenceNode root)
944 if (root.isLeaf() && printRootInfo)
946 tf.append(printRootField(root));
952 _print(tf, (SequenceNode) root.right());
953 _print(tf, (SequenceNode) root.left());
958 _print(tf, (SequenceNode) root.right());
960 if (root.left() != null)
965 _print(tf, (SequenceNode) root.left());
966 tf.append(")" + printRootField(root));
972 // Recursive call for non-root nodes
973 public void _print(StringBuffer tf, SequenceNode c)
979 tf.append(printNodeField(c));
985 _print(tf, (SequenceNode) c.left());
986 if (c.left() != null)
990 _print(tf, (SequenceNode) c.right());
995 _print(tf, (SequenceNode) c.right());
997 if (c.left() != null)
1002 _print(tf, (SequenceNode) c.left());
1003 tf.append(")" + printNodeField(c));
1014 public static void main(String[] args)
1018 if (args == null || args.length != 1)
1021 "Takes one argument - file name of a newick tree file.");
1025 File fn = new File(args[0]);
1027 StringBuffer newickfile = new StringBuffer();
1028 BufferedReader treefile = new BufferedReader(new FileReader(fn));
1031 while ((l = treefile.readLine()) != null)
1033 newickfile.append(l);
1037 System.out.println("Read file :\n");
1039 NewickFile trf = new NewickFile(args[0], DataSourceType.FILE);
1041 System.out.println("Original file :\n");
1043 Regex nonl = getRegex(REGEX_NO_LINES);// "\n+", "");
1044 System.out.println(nonl.replaceAll(newickfile.toString()) + "\n");
1046 System.out.println("Parsed file.\n");
1047 System.out.println("Default output type for original input.\n");
1048 System.out.println(trf.print());
1049 System.out.println("Without bootstraps.\n");
1050 System.out.println(trf.print(false));
1051 System.out.println("Without distances.\n");
1052 System.out.println(trf.print(true, false));
1053 System.out.println("Without bootstraps but with distanecs.\n");
1054 System.out.println(trf.print(false, true));
1055 System.out.println("Without bootstraps or distanecs.\n");
1056 System.out.println(trf.print(false, false));
1057 System.out.println("With bootstraps and with distances.\n");
1058 System.out.println(trf.print(true, true));
1059 } catch (java.io.IOException e)
1061 System.err.println("Exception\n" + e);
1062 e.printStackTrace();