2 * Jalview - A Sequence Alignment Editor and Viewer (Version 2.4)
3 * Copyright (C) 2008 AM Waterhouse, J Procter, G Barton, M Clamp, S Searle
5 * This program is free software; you can redistribute it and/or
6 * modify it under the terms of the GNU General Public License
7 * as published by the Free Software Foundation; either version 2
8 * of the License, or (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License
16 * along with this program; if not, write to the Free Software
17 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
21 // http://evolution.genetics.washington.edu/phylip/newick_doc.html
22 // TODO: Implement Basic NHX tag parsing and preservation
23 // TODO: http://evolution.genetics.wustl.edu/eddy/forester/NHX.html
24 // TODO: Extended SequenceNodeI to hold parsed NHX strings
28 import java.util.StringTokenizer;
30 import jalview.datamodel.*;
33 * Parse a new hanpshire style tree Caveats: NHX files are NOT supported and the
34 * tree distances and topology are unreliable when they are parsed. TODO: on
35 * this: NHX codes are appended in comments beginning with &&NHX. The codes are
36 * given below (from http://www.phylosoft.org/forester/NHX.html): Element Type
37 * Description Corresponding phyloXML element (parent element in parentheses) no
38 * tag string name of this node/clade (MUST BE FIRST, IF ASSIGNED) <name>(<clade>) :
39 * decimal branch length to parent node (MUST BE SECOND, IF ASSIGNED)
40 * <branch_length>(<clade>) :GN= string gene name <name>(<sequence>) :AC=
41 * string sequence accession <accession>(<sequence>) :ND= string node
42 * identifier - if this is being used, it has to be unique within each phylogeny
43 * <node_id>(<clade>) :B= decimal confidence value for parent branch
44 * <confidence>(<clade>) :D= 'T', 'F', or '?' 'T' if this node represents a
45 * duplication event - 'F' if this node represents a speciation event, '?' if
46 * this node represents an unknown event (D= tag should be replaced by Ev= tag)
47 * n/a :Ev=duplications>speciations>gene losses>event type>duplication type int
48 * int int string string event (replaces the =D tag), number of duplication,
49 * speciation, and gene loss events, type of event (transfer, fusion, root,
50 * unknown, other, speciation_duplication_loss, unassigned) <events>(<clade>)
51 * :E= string EC number at this node <annotation>(<sequence>) :Fu= string
52 * function at this node <annotation>(<sequence>)
53 * :DS=protein-length>from>to>support>name>from>... int int int double string
54 * int ... domain structure at this node <domain_architecture>(<sequence>) :S=
55 * string species name of the species/phylum at this node <taxonomy>(<clade>)
56 * :T= integer taxonomy ID of the species/phylum at this node <id>(<taxonomy>)
57 * :W= integer width of parent branch <width>(<clade>) :C=rrr.ggg.bbb
58 * integer.integer.integer color of parent branch <color>(<clade>) :Co= 'Y' or
59 * 'N' collapse this node when drawing the tree (default is not to collapse) n/a
60 * :XB= string custom data associated with a branch <property>(<clade>) :XN=
61 * string custom data associated with a node <property>(<clade>) :O= integer
62 * orthologous to this external node n/a :SN= integer subtree neighbors n/a :SO=
63 * integer super orthologous (no duplications on paths) to this external node
69 public class NewickFile extends FileParse
73 private boolean HasBootstrap = false;
75 private boolean HasDistances = false;
77 private boolean RootHasDistance = false;
80 boolean ReplaceUnderscores = false;
82 boolean printRootInfo = true;
84 private com.stevesoft.pat.Regex[] NodeSafeName = new com.stevesoft.pat.Regex[]
85 { new com.stevesoft.pat.Regex().perlCode("m/[\\[,:'()]/"), // test for
88 new com.stevesoft.pat.Regex().perlCode("s/'/''/"), // escaping quote
90 new com.stevesoft.pat.Regex().perlCode("s/\\/w/_/") // unqoted whitespace
94 char QuoteChar = '\'';
97 * Creates a new NewickFile object.
102 * @throws IOException
105 public NewickFile(String inStr) throws IOException
107 super(inStr, "Paste");
111 * Creates a new NewickFile object.
118 * @throws IOException
121 public NewickFile(String inFile, String type) throws IOException
126 public NewickFile(FileParse source) throws IOException
132 * Creates a new NewickFile object.
137 public NewickFile(SequenceNode newtree)
143 * Creates a new NewickFile object.
150 public NewickFile(SequenceNode newtree, boolean bootstrap)
152 HasBootstrap = bootstrap;
157 * Creates a new NewickFile object.
166 public NewickFile(SequenceNode newtree, boolean bootstrap,
170 HasBootstrap = bootstrap;
171 HasDistances = distances;
175 * Creates a new NewickFile object.
183 * @param rootdistance
186 public NewickFile(SequenceNode newtree, boolean bootstrap,
187 boolean distances, boolean rootdistance)
190 HasBootstrap = bootstrap;
191 HasDistances = distances;
192 RootHasDistance = rootdistance;
209 * @return DOCUMENT ME!
211 private String ErrorStringrange(String Error, String Er, int r, int p,
214 return ((Error == null) ? "" : Error)
219 + s.substring(((p - r) < 0) ? 0 : (p - r), ((p + r) > s
220 .length()) ? s.length() : (p + r)) + " )\n";
224 // These are set automatically by the reader
225 public boolean HasBootstrap()
233 * @return DOCUMENT ME!
235 public boolean HasDistances()
240 public boolean HasRootDistance()
242 return RootHasDistance;
246 * parse the filesource as a newick file (new hampshire and/or extended)
248 * @throws IOException
249 * with a line number and character position for badly
250 * formatted NH strings
252 public void parse() throws IOException
256 { // fill nf with complete tree file
258 StringBuffer file = new StringBuffer();
260 while ((nf = nextLine()) != null)
265 nf = file.toString();
268 root = new SequenceNode();
270 SequenceNode realroot = null;
271 SequenceNode c = root;
275 // int flen = nf.length();
278 String nodename = null;
279 String commentString2 = null; // comments after simple node props
281 float DefDistance = (float) 0.001; // @param Default distance for a node -
283 int DefBootstrap = -1; // @param Default bootstrap for a node
285 float distance = DefDistance;
286 int bootstrap = DefBootstrap;
288 boolean ascending = false; // flag indicating that we are leaving the
291 com.stevesoft.pat.Regex majorsyms = new com.stevesoft.pat.Regex(
296 while (majorsyms.searchFrom(nf, cp) && (Error == null))
298 int fcp = majorsyms.matchedFrom();
300 switch (schar = nf.charAt(fcp))
304 // ascending should not be set
308 Error = ErrorStringrange(Error, "Unexpected '('", 7, fcp, nf);
316 if (c.right() == null)
318 c.setRight(new SequenceNode(null, c, null, DefDistance,
319 DefBootstrap, false));
320 c = (SequenceNode) c.right();
324 if (c.left() != null)
326 // Dummy node for polytomy - keeps c.left free for new node
327 SequenceNode tmpn = new SequenceNode(null, c, null, 0, 0, true);
328 tmpn.SetChildren(c.left(), c.right());
332 c.setLeft(new SequenceNode(null, c, null, DefDistance,
333 DefBootstrap, false));
334 c = (SequenceNode) c.left();
337 if (realroot == null)
343 distance = DefDistance;
344 bootstrap = DefBootstrap;
349 // Deal with quoted fields
352 com.stevesoft.pat.Regex qnodename = new com.stevesoft.pat.Regex(
355 if (qnodename.searchFrom(nf, fcp))
357 int nl = qnodename.stringMatched().length();
358 nodename = new String(qnodename.stringMatched().substring(0,
364 Error = ErrorStringrange(Error,
365 "Unterminated quotes for nodename", 7, fcp, nf);
375 Error = ErrorStringrange(Error, "Wayward semicolon (depth=" + d
378 // cp advanced at the end of default
382 // node string contains Comment or structured/extended NH format info
384 * if ((fcp-cp>1 && nf.substring(cp,fcp).trim().length()>1)) { // will
385 * process in remains System.err.println("skipped text:
386 * '"+nf.substring(cp,fcp)+"'"); }
388 // verify termination.
389 com.stevesoft.pat.Regex comment = new com.stevesoft.pat.Regex("]");
390 if (comment.searchFrom(nf, fcp))
392 // Skip the comment field
393 nextcp = comment.matchedFrom() + 1;
394 warningMessage = "Tree file contained comments which may confuse input algorithm.";
397 // cp advanced at the end of default to nextcp, ncp is unchanged so
398 // any node info can be read.
402 Error = ErrorStringrange(Error, "Unterminated comment", 3, fcp,
408 // Parse simpler field strings
409 String fstring = nf.substring(ncp, fcp);
410 // remove any comments before we parse the node info
411 // TODO: test newick file with quoted square brackets in node name (is
413 while (fstring.indexOf(']') > -1)
415 int cstart = fstring.indexOf('[');
416 int cend = fstring.indexOf(']');
417 commentString2 = fstring.substring(cstart + 1, cend);
418 fstring = fstring.substring(0, cstart)
419 + fstring.substring(cend + 1);
422 com.stevesoft.pat.Regex uqnodename = new com.stevesoft.pat.Regex(
423 "\\b([^' :;\\](),]+)");
424 com.stevesoft.pat.Regex nbootstrap = new com.stevesoft.pat.Regex(
425 "\\s*([0-9+]+)\\s*:");
426 com.stevesoft.pat.Regex ndist = new com.stevesoft.pat.Regex(
429 if (uqnodename.search(fstring)
430 && ((uqnodename.matchedFrom(1) == 0) || (fstring
431 .charAt(uqnodename.matchedFrom(1) - 1) != ':'))) // JBPNote
434 if (nodename == null)
436 if (ReplaceUnderscores)
438 nodename = uqnodename.stringMatched(1).replace('_', ' ');
442 nodename = uqnodename.stringMatched(1);
447 Error = ErrorStringrange(Error,
448 "File has broken algorithm - overwritten nodename", 10,
452 // get comment bootstraps
454 if (nbootstrap.search(fstring))
456 if (nbootstrap.stringMatched(1).equals(
457 uqnodename.stringMatched(1)))
459 nodename = null; // no nodename here.
462 || nodename.length() == 0
463 || nbootstrap.matchedFrom(1) > (uqnodename.matchedFrom(1) + uqnodename
464 .stringMatched().length()))
468 bootstrap = (new Integer(nbootstrap.stringMatched(1)))
471 } catch (Exception e)
473 Error = ErrorStringrange(Error,
474 "Can't parse bootstrap value", 4, ncp
475 + nbootstrap.matchedFrom(), nf);
480 boolean nodehasdistance = false;
482 if (ndist.search(fstring))
486 distance = (new Float(ndist.stringMatched(1))).floatValue();
488 nodehasdistance = true;
489 } catch (Exception e)
491 Error = ErrorStringrange(Error,
492 "Can't parse node distance value", 7, ncp
493 + ndist.matchedFrom(), nf);
499 // Write node info here
501 // Trees without distances still need a render distance
502 c.dist = (HasDistances) ? distance : DefDistance;
503 // be consistent for internal bootstrap defaults too
504 c.setBootstrap((HasBootstrap) ? bootstrap : DefBootstrap);
507 RootHasDistance = nodehasdistance; // JBPNote This is really
508 // UGLY!!! Ensure root node gets
509 // its given distance
511 parseNHXNodeProps(c, commentString2);
512 commentString2 = null;
516 // Find a place to put the leaf
517 SequenceNode newnode = new SequenceNode(null, c, nodename,
518 (HasDistances) ? distance : DefDistance,
519 (HasBootstrap) ? bootstrap : DefBootstrap, false);
520 parseNHXNodeProps(c, commentString2);
521 commentString2 = null;
523 if (c.right() == null)
529 if (c.left() == null)
535 // Insert a dummy node for polytomy
536 // dummy nodes have distances
537 SequenceNode newdummy = new SequenceNode(null, c, null,
538 (HasDistances ? 0 : DefDistance), 0, true);
539 newdummy.SetChildren(c.left(), newnode);
547 // move back up the tree from preceding closure
550 if ((d > -1) && (c == null))
552 Error = ErrorStringrange(
554 "File broke algorithm: Lost place in tree (is there an extra ')' ?)",
559 if (nf.charAt(fcp) == ')')
566 if (nf.charAt(fcp) == ',')
574 // Just advance focus, if we need to
575 if ((c.left() != null) && (!c.left().isLeaf()))
577 c = (SequenceNode) c.left();
583 // Reset new node properties to obvious fakes
585 distance = DefDistance;
586 bootstrap = DefBootstrap;
587 commentString2 = null;
602 throw (new IOException("NewickFile: " + Error + "\n"));
606 throw (new IOException("NewickFile: No Tree read in\n"));
608 // THe next line is failing for topali trees - not sure why yet. if
609 // (root.right()!=null && root.isDummy())
610 root = (SequenceNode) root.right().detach(); // remove the imaginary root.
612 if (!RootHasDistance)
614 root.dist = (HasDistances) ? 0 : DefDistance;
619 * parse NHX codes in comment strings and update NewickFile state flags for
620 * distances and bootstraps, and add any additional properties onto the node.
623 * @param commentString
624 * @param commentString2
626 private void parseNHXNodeProps(SequenceNode c, String commentString)
628 // TODO: store raw comment on the sequenceNode so it can be recovered when
630 if (commentString != null && commentString.startsWith("&&NHX"))
632 StringTokenizer st = new StringTokenizer(commentString.substring(5),
634 while (st.hasMoreTokens())
636 String tok = st.nextToken();
637 int colpos = tok.indexOf("=");
641 String code = tok.substring(0, colpos);
642 String value = tok.substring(colpos + 1);
645 // parse out code/value pairs
646 if (code.toLowerCase().equals("b"))
649 Float iv = new Float(value);
650 v = iv.intValue(); // jalview only does integer bootstraps
656 } catch (Exception e)
658 System.err.println("Couldn't parse code '" + code + "' = '"
660 e.printStackTrace(System.err);
671 * @return DOCUMENT ME!
673 public SequenceNode getTree()
679 * Generate a newick format tree according to internal flags for bootstraps,
680 * distances and root distances.
682 * @return new hampshire tree in a single line
684 public String print()
688 StringBuffer tf = new StringBuffer();
691 return (tf.append(";").toString());
698 * Generate a newick format tree according to internal flags for distances and
699 * root distances and user specificied writing of bootstraps.
701 * @param withbootstraps
702 * controls if bootstrap values are explicitly written.
704 * @return new hampshire tree in a single line
706 public String print(boolean withbootstraps)
710 boolean boots = this.HasBootstrap;
711 this.HasBootstrap = withbootstraps;
714 this.HasBootstrap = boots;
722 * Generate newick format tree according to internal flags for writing root
725 * @param withbootstraps
726 * explicitly write bootstrap values
728 * explicitly write distances
730 * @return new hampshire tree in a single line
732 public String print(boolean withbootstraps, boolean withdists)
736 boolean dists = this.HasDistances;
737 this.HasDistances = withdists;
739 String rv = print(withbootstraps);
740 this.HasDistances = dists;
747 * Generate newick format tree according to user specified flags
749 * @param withbootstraps
750 * explicitly write bootstrap values
752 * explicitly write distances
753 * @param printRootInfo
754 * explicitly write root distance
756 * @return new hampshire tree in a single line
758 public String print(boolean withbootstraps, boolean withdists,
759 boolean printRootInfo)
763 boolean rootinfo = printRootInfo;
764 this.printRootInfo = printRootInfo;
766 String rv = print(withbootstraps, withdists);
767 this.printRootInfo = rootinfo;
776 * @return DOCUMENT ME!
789 * @return DOCUMENT ME!
791 char setQuoteChar(char c)
793 char old = QuoteChar;
805 * @return DOCUMENT ME!
807 private String nodeName(String name)
809 if (NodeSafeName[0].search(name))
811 return QuoteChar + NodeSafeName[1].replaceAll(name) + QuoteChar;
815 return NodeSafeName[2].replaceAll(name);
825 * @return DOCUMENT ME!
827 private String printNodeField(SequenceNode c)
829 return ((c.getName() == null) ? "" : nodeName(c.getName()))
830 + ((HasBootstrap) ? ((c.getBootstrap() > -1) ? ((c.getName() != null ? " "
831 : "") + c.getBootstrap())
833 : "") + ((HasDistances) ? (":" + c.dist) : "");
842 * @return DOCUMENT ME!
844 private String printRootField(SequenceNode root)
846 return (printRootInfo) ? (((root.getName() == null) ? ""
847 : nodeName(root.getName()))
848 + ((HasBootstrap) ? ((root.getBootstrap() > -1) ? ((root
849 .getName() != null ? " " : "") + +root.getBootstrap())
850 : "") : "") + ((RootHasDistance) ? (":" + root.dist)
854 // Non recursive call deals with root node properties
855 public void print(StringBuffer tf, SequenceNode root)
859 if (root.isLeaf() && printRootInfo)
861 tf.append(printRootField(root));
867 _print(tf, (SequenceNode) root.right());
868 _print(tf, (SequenceNode) root.left());
873 _print(tf, (SequenceNode) root.right());
875 if (root.left() != null)
880 _print(tf, (SequenceNode) root.left());
881 tf.append(")" + printRootField(root));
887 // Recursive call for non-root nodes
888 public void _print(StringBuffer tf, SequenceNode c)
894 tf.append(printNodeField(c));
900 _print(tf, (SequenceNode) c.left());
901 if (c.left() != null)
905 _print(tf, (SequenceNode) c.right());
910 _print(tf, (SequenceNode) c.right());
912 if (c.left() != null)
917 _print(tf, (SequenceNode) c.left());
918 tf.append(")" + printNodeField(c));
925 public static void main(String[] args)
929 if (args == null || args.length != 1)
932 .println("Takes one argument - file name of a newick tree file.");
936 File fn = new File(args[0]);
938 StringBuffer newickfile = new StringBuffer();
939 BufferedReader treefile = new BufferedReader(new FileReader(fn));
942 while ((l = treefile.readLine()) != null)
944 newickfile.append(l);
948 System.out.println("Read file :\n");
950 NewickFile trf = new NewickFile(args[0], "File");
952 System.out.println("Original file :\n");
954 com.stevesoft.pat.Regex nonl = new com.stevesoft.pat.Regex("\n+", "");
955 System.out.println(nonl.replaceAll(newickfile.toString()) + "\n");
957 System.out.println("Parsed file.\n");
958 System.out.println("Default output type for original input.\n");
959 System.out.println(trf.print());
960 System.out.println("Without bootstraps.\n");
961 System.out.println(trf.print(false));
962 System.out.println("Without distances.\n");
963 System.out.println(trf.print(true, false));
964 System.out.println("Without bootstraps but with distanecs.\n");
965 System.out.println(trf.print(false, true));
966 System.out.println("Without bootstraps or distanecs.\n");
967 System.out.println(trf.print(false, false));
968 System.out.println("With bootstraps and with distances.\n");
969 System.out.println(trf.print(true, true));
970 } catch (java.io.IOException e)
972 System.err.println("Exception\n" + e);