JAL-1432 updated copyright notices
[jalview.git] / src / jalview / io / NewickFile.java
1 /*
2  * Jalview - A Sequence Alignment Editor and Viewer (Version 2.8.0b1)
3  * Copyright (C) 2014 The Jalview Authors
4  * 
5  * This file is part of Jalview.
6  * 
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 of the License, or (at your option) any later version.
10  *  
11  * Jalview is distributed in the hope that it will be useful, but 
12  * WITHOUT ANY WARRANTY; without even the implied warranty 
13  * of MERCHANTABILITY or FITNESS FOR A PARTICULAR 
14  * PURPOSE.  See the GNU General Public License for more details.
15  * 
16  * You should have received a copy of the GNU General Public License along with Jalview.  If not, see <http://www.gnu.org/licenses/>.
17  * The Jalview Authors are detailed in the 'AUTHORS' file.
18  */
19 // NewickFile.java
20 // Tree I/O
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
25 package jalview.io;
26
27 import java.io.*;
28 import java.util.StringTokenizer;
29
30 import jalview.datamodel.*;
31
32 /**
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)
39  * <name>(<clade>) : decimal branch length to parent node (MUST BE SECOND, IF
40  * ASSIGNED) <branch_length>(<clade>) :GN= string gene name <name>(<sequence>)
41  * :AC= 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
64  * n/a
65  * 
66  * @author Jim Procter
67  * @version $Revision$
68  */
69 public class NewickFile extends FileParse
70 {
71   SequenceNode root;
72
73   private boolean HasBootstrap = false;
74
75   private boolean HasDistances = false;
76
77   private boolean RootHasDistance = false;
78
79   // File IO Flags
80   boolean ReplaceUnderscores = false;
81
82   boolean printRootInfo = true;
83
84   private com.stevesoft.pat.Regex[] NodeSafeName = new com.stevesoft.pat.Regex[]
85   { new com.stevesoft.pat.Regex().perlCode("m/[\\[,:'()]/"), // test for
86       // requiring
87       // quotes
88       new com.stevesoft.pat.Regex().perlCode("s/'/''/"), // escaping quote
89       // characters
90       new com.stevesoft.pat.Regex().perlCode("s/\\/w/_/") // unqoted whitespace
91   // transformation
92   };
93
94   char QuoteChar = '\'';
95
96   /**
97    * Creates a new NewickFile object.
98    * 
99    * @param inStr
100    *          DOCUMENT ME!
101    * 
102    * @throws IOException
103    *           DOCUMENT ME!
104    */
105   public NewickFile(String inStr) throws IOException
106   {
107     super(inStr, "Paste");
108   }
109
110   /**
111    * Creates a new NewickFile object.
112    * 
113    * @param inFile
114    *          DOCUMENT ME!
115    * @param type
116    *          DOCUMENT ME!
117    * 
118    * @throws IOException
119    *           DOCUMENT ME!
120    */
121   public NewickFile(String inFile, String type) throws IOException
122   {
123     super(inFile, type);
124   }
125
126   public NewickFile(FileParse source) throws IOException
127   {
128     super(source);
129   }
130
131   /**
132    * Creates a new NewickFile object.
133    * 
134    * @param newtree
135    *          DOCUMENT ME!
136    */
137   public NewickFile(SequenceNode newtree)
138   {
139     root = newtree;
140   }
141
142   /**
143    * Creates a new NewickFile object.
144    * 
145    * @param newtree
146    *          DOCUMENT ME!
147    * @param bootstrap
148    *          DOCUMENT ME!
149    */
150   public NewickFile(SequenceNode newtree, boolean bootstrap)
151   {
152     HasBootstrap = bootstrap;
153     root = newtree;
154   }
155
156   /**
157    * Creates a new NewickFile object.
158    * 
159    * @param newtree
160    *          DOCUMENT ME!
161    * @param bootstrap
162    *          DOCUMENT ME!
163    * @param distances
164    *          DOCUMENT ME!
165    */
166   public NewickFile(SequenceNode newtree, boolean bootstrap,
167           boolean distances)
168   {
169     root = newtree;
170     HasBootstrap = bootstrap;
171     HasDistances = distances;
172   }
173
174   /**
175    * Creates a new NewickFile object.
176    * 
177    * @param newtree
178    *          DOCUMENT ME!
179    * @param bootstrap
180    *          DOCUMENT ME!
181    * @param distances
182    *          DOCUMENT ME!
183    * @param rootdistance
184    *          DOCUMENT ME!
185    */
186   public NewickFile(SequenceNode newtree, boolean bootstrap,
187           boolean distances, boolean rootdistance)
188   {
189     root = newtree;
190     HasBootstrap = bootstrap;
191     HasDistances = distances;
192     RootHasDistance = rootdistance;
193   }
194
195   /**
196    * DOCUMENT ME!
197    * 
198    * @param Error
199    *          DOCUMENT ME!
200    * @param Er
201    *          DOCUMENT ME!
202    * @param r
203    *          DOCUMENT ME!
204    * @param p
205    *          DOCUMENT ME!
206    * @param s
207    *          DOCUMENT ME!
208    * 
209    * @return DOCUMENT ME!
210    */
211   private String ErrorStringrange(String Error, String Er, int r, int p,
212           String s)
213   {
214     return ((Error == null) ? "" : Error)
215             + Er
216             + " at position "
217             + p
218             + " ( "
219             + s.substring(((p - r) < 0) ? 0 : (p - r),
220                     ((p + r) > s.length()) ? s.length() : (p + r)) + " )\n";
221   }
222
223   // @tree annotations
224   // These are set automatically by the reader
225   public boolean HasBootstrap()
226   {
227     return HasBootstrap;
228   }
229
230   /**
231    * DOCUMENT ME!
232    * 
233    * @return DOCUMENT ME!
234    */
235   public boolean HasDistances()
236   {
237     return HasDistances;
238   }
239
240   public boolean HasRootDistance()
241   {
242     return RootHasDistance;
243   }
244
245   /**
246    * parse the filesource as a newick file (new hampshire and/or extended)
247    * 
248    * @throws IOException
249    *           with a line number and character position for badly formatted NH
250    *           strings
251    */
252   public void parse() throws IOException
253   {
254     String nf;
255
256     { // fill nf with complete tree file
257
258       StringBuffer file = new StringBuffer();
259
260       while ((nf = nextLine()) != null)
261       {
262         file.append(nf);
263       }
264
265       nf = file.toString();
266     }
267
268     root = new SequenceNode();
269
270     SequenceNode realroot = null;
271     SequenceNode c = root;
272
273     int d = -1;
274     int cp = 0;
275     // int flen = nf.length();
276
277     String Error = null;
278     String nodename = null;
279     String commentString2 = null; // comments after simple node props
280
281     float DefDistance = (float) 0.001; // @param Default distance for a node -
282     // very very small
283     int DefBootstrap = -1; // @param Default bootstrap for a node
284
285     float distance = DefDistance;
286     int bootstrap = DefBootstrap;
287
288     boolean ascending = false; // flag indicating that we are leaving the
289     // current node
290
291     com.stevesoft.pat.Regex majorsyms = new com.stevesoft.pat.Regex(
292             "[(\\['),;]");
293
294     int nextcp = 0;
295     int ncp = cp;
296     boolean parsednodename=false;
297     while (majorsyms.searchFrom(nf, cp) && (Error == null))
298     {
299       int fcp = majorsyms.matchedFrom();
300       char schar;
301       switch (schar = nf.charAt(fcp))
302       {
303       case '(':
304
305         // ascending should not be set
306         // New Internal node
307         if (ascending)
308         {
309           Error = ErrorStringrange(Error, "Unexpected '('", 7, fcp, nf);
310
311           continue;
312         }
313
314         ;
315         d++;
316
317         if (c.right() == null)
318         {
319           c.setRight(new SequenceNode(null, c, null, DefDistance,
320                   DefBootstrap, false));
321           c = (SequenceNode) c.right();
322         }
323         else
324         {
325           if (c.left() != null)
326           {
327             // Dummy node for polytomy - keeps c.left free for new node
328             SequenceNode tmpn = new SequenceNode(null, c, null, 0, 0, true);
329             tmpn.SetChildren(c.left(), c.right());
330             c.setRight(tmpn);
331           }
332
333           c.setLeft(new SequenceNode(null, c, null, DefDistance,
334                   DefBootstrap, false));
335           c = (SequenceNode) c.left();
336         }
337
338         if (realroot == null)
339         {
340           realroot = c;
341         }
342
343         nodename = null;
344         distance = DefDistance;
345         bootstrap = DefBootstrap;
346         cp = fcp + 1;
347
348         break;
349
350       // Deal with quoted fields
351       case '\'':
352
353         com.stevesoft.pat.Regex qnodename = new com.stevesoft.pat.Regex(
354                 "'([^']|'')+'");
355
356         if (qnodename.searchFrom(nf, fcp))
357         {
358           int nl = qnodename.stringMatched().length();
359           nodename = new String(qnodename.stringMatched().substring(1,
360                   nl - 1));
361           // unpack any escaped colons
362           com.stevesoft.pat.Regex xpandquotes = com.stevesoft.pat.Regex.perlCode("s/''/'/");
363           String widernodename = xpandquotes.replaceAll(nodename);
364           nodename=widernodename;
365           // jump to after end of quoted nodename
366           nextcp = fcp + nl + 1;
367           parsednodename=true;
368         }
369         else
370         {
371           Error = ErrorStringrange(Error,
372                   "Unterminated quotes for nodename", 7, fcp, nf);
373         }
374
375         break;
376
377       default:
378         if (schar == ';')
379         {
380           if (d != -1)
381           {
382             Error = ErrorStringrange(Error, "Wayward semicolon (depth=" + d
383                     + ")", 7, fcp, nf);
384           }
385           // cp advanced at the end of default
386         }
387         if (schar == '[')
388         {
389           // node string contains Comment or structured/extended NH format info
390           /*
391            * if ((fcp-cp>1 && nf.substring(cp,fcp).trim().length()>1)) { // will
392            * process in remains System.err.println("skipped text:
393            * '"+nf.substring(cp,fcp)+"'"); }
394            */
395           // verify termination.
396           com.stevesoft.pat.Regex comment = new com.stevesoft.pat.Regex("]");
397           if (comment.searchFrom(nf, fcp))
398           {
399             // Skip the comment field
400             nextcp = comment.matchedFrom() + 1;
401             warningMessage = "Tree file contained comments which may confuse input algorithm.";
402             break;
403
404             // cp advanced at the end of default to nextcp, ncp is unchanged so
405             // any node info can be read.
406           }
407           else
408           {
409             Error = ErrorStringrange(Error, "Unterminated comment", 3, fcp,
410                     nf);
411           }
412
413           ;
414         }
415         // Parse simpler field strings
416         String fstring = nf.substring(ncp, fcp);
417         // remove any comments before we parse the node info
418         // TODO: test newick file with quoted square brackets in node name (is
419         // this allowed?)
420         while (fstring.indexOf(']') > -1)
421         {
422           int cstart = fstring.indexOf('[');
423           int cend = fstring.indexOf(']');
424           commentString2 = fstring.substring(cstart + 1, cend);
425           fstring = fstring.substring(0, cstart)
426                   + fstring.substring(cend + 1);
427
428         }
429         com.stevesoft.pat.Regex uqnodename = new com.stevesoft.pat.Regex(
430                 "\\b([^' :;\\](),]+)");
431         com.stevesoft.pat.Regex nbootstrap = new com.stevesoft.pat.Regex(
432                 "\\s*([0-9+]+)\\s*:");
433         com.stevesoft.pat.Regex ndist = new com.stevesoft.pat.Regex(
434                 ":([-0-9Ee.+]+)");
435
436         if (!parsednodename && uqnodename.search(fstring)
437                 && ((uqnodename.matchedFrom(1) == 0) || (fstring
438                         .charAt(uqnodename.matchedFrom(1) - 1) != ':'))) // JBPNote
439         // HACK!
440         {
441           if (nodename == null)
442           {
443             if (ReplaceUnderscores)
444             {
445               nodename = uqnodename.stringMatched(1).replace('_', ' ');
446             }
447             else
448             {
449               nodename = uqnodename.stringMatched(1);
450             }
451           }
452           else
453           {
454             Error = ErrorStringrange(Error,
455                     "File has broken algorithm - overwritten nodename", 10,
456                     fcp, nf);
457           }
458         }
459         // get comment bootstraps
460
461         if (nbootstrap.search(fstring))
462         {
463           if (nbootstrap.stringMatched(1).equals(
464                   uqnodename.stringMatched(1)))
465           {
466             nodename = null; // no nodename here.
467           }
468           if (nodename == null
469                   || nodename.length() == 0
470                   || nbootstrap.matchedFrom(1) > (uqnodename.matchedFrom(1) + uqnodename
471                           .stringMatched().length()))
472           {
473             try
474             {
475               bootstrap = (new Integer(nbootstrap.stringMatched(1)))
476                       .intValue();
477               HasBootstrap = true;
478             } catch (Exception e)
479             {
480               Error = ErrorStringrange(Error,
481                       "Can't parse bootstrap value", 4,
482                       ncp + nbootstrap.matchedFrom(), nf);
483             }
484           }
485         }
486
487         boolean nodehasdistance = false;
488
489         if (ndist.search(fstring))
490         {
491           try
492           {
493             distance = (new Float(ndist.stringMatched(1))).floatValue();
494             HasDistances = true;
495             nodehasdistance = true;
496           } catch (Exception e)
497           {
498             Error = ErrorStringrange(Error,
499                     "Can't parse node distance value", 7,
500                     ncp + ndist.matchedFrom(), nf);
501           }
502         }
503
504         if (ascending)
505         {
506           // Write node info here
507           c.setName(nodename);
508           // Trees without distances still need a render distance
509           c.dist = (HasDistances) ? distance : DefDistance;
510           // be consistent for internal bootstrap defaults too
511           c.setBootstrap((HasBootstrap) ? bootstrap : DefBootstrap);
512           if (c == realroot)
513           {
514             RootHasDistance = nodehasdistance; // JBPNote This is really
515             // UGLY!!! Ensure root node gets
516             // its given distance
517           }
518           parseNHXNodeProps(c, commentString2);
519           commentString2 = null;
520         }
521         else
522         {
523           // Find a place to put the leaf
524           SequenceNode newnode = new SequenceNode(null, c, nodename,
525                   (HasDistances) ? distance : DefDistance,
526                   (HasBootstrap) ? bootstrap : DefBootstrap, false);
527           parseNHXNodeProps(c, commentString2);
528           commentString2 = null;
529
530           if (c.right() == null)
531           {
532             c.setRight(newnode);
533           }
534           else
535           {
536             if (c.left() == null)
537             {
538               c.setLeft(newnode);
539             }
540             else
541             {
542               // Insert a dummy node for polytomy
543               // dummy nodes have distances
544               SequenceNode newdummy = new SequenceNode(null, c, null,
545                       (HasDistances ? 0 : DefDistance), 0, true);
546               newdummy.SetChildren(c.left(), newnode);
547               c.setLeft(newdummy);
548             }
549           }
550         }
551
552         if (ascending)
553         {
554           // move back up the tree from preceding closure
555           c = c.AscendTree();
556
557           if ((d > -1) && (c == null))
558           {
559             Error = ErrorStringrange(
560                     Error,
561                     "File broke algorithm: Lost place in tree (is there an extra ')' ?)",
562                     7, fcp, nf);
563           }
564         }
565
566         if (nf.charAt(fcp) == ')')
567         {
568           d--;
569           ascending = true;
570         }
571         else
572         {
573           if (nf.charAt(fcp) == ',')
574           {
575             if (ascending)
576             {
577               ascending = false;
578             }
579             else
580             {
581               // Just advance focus, if we need to
582               if ((c.left() != null) && (!c.left().isLeaf()))
583               {
584                 c = (SequenceNode) c.left();
585               }
586             }
587           }
588         }
589
590         // Reset new node properties to obvious fakes
591         nodename = null;
592         distance = DefDistance;
593         bootstrap = DefBootstrap;
594         commentString2 = null;
595         parsednodename=false;
596       }
597       if (nextcp == 0)
598       {
599         ncp = cp = fcp + 1;
600       }
601       else
602       {
603         cp = nextcp;
604         nextcp = 0;
605       }
606     }
607
608     if (Error != null)
609     {
610       throw (new IOException("NewickFile: " + Error + "\n"));
611     }
612     if (root == null)
613     {
614       throw (new IOException("NewickFile: No Tree read in\n"));
615     }
616     // THe next line is failing for topali trees - not sure why yet. if
617     // (root.right()!=null && root.isDummy())
618     root = (SequenceNode) root.right().detach(); // remove the imaginary root.
619
620     if (!RootHasDistance)
621     {
622       root.dist = (HasDistances) ? 0 : DefDistance;
623     }
624   }
625
626   /**
627    * parse NHX codes in comment strings and update NewickFile state flags for
628    * distances and bootstraps, and add any additional properties onto the node.
629    * 
630    * @param c
631    * @param commentString
632    * @param commentString2
633    */
634   private void parseNHXNodeProps(SequenceNode c, String commentString)
635   {
636     // TODO: store raw comment on the sequenceNode so it can be recovered when
637     // tree is output
638     if (commentString != null && commentString.startsWith("&&NHX"))
639     {
640       StringTokenizer st = new StringTokenizer(commentString.substring(5),
641               ":");
642       while (st.hasMoreTokens())
643       {
644         String tok = st.nextToken();
645         int colpos = tok.indexOf("=");
646
647         if (colpos > -1)
648         {
649           String code = tok.substring(0, colpos);
650           String value = tok.substring(colpos + 1);
651           try
652           {
653             // parse out code/value pairs
654             if (code.toLowerCase().equals("b"))
655             {
656               int v = -1;
657               Float iv = new Float(value);
658               v = iv.intValue(); // jalview only does integer bootstraps
659               // currently
660               c.setBootstrap(v);
661               HasBootstrap = true;
662             }
663             // more codes here.
664           } catch (Exception e)
665           {
666             System.err.println("Couldn't parse code '" + code + "' = '"
667                     + value + "'");
668             e.printStackTrace(System.err);
669           }
670         }
671       }
672     }
673
674   }
675
676   /**
677    * DOCUMENT ME!
678    * 
679    * @return DOCUMENT ME!
680    */
681   public SequenceNode getTree()
682   {
683     return root;
684   }
685
686   /**
687    * Generate a newick format tree according to internal flags for bootstraps,
688    * distances and root distances.
689    * 
690    * @return new hampshire tree in a single line
691    */
692   public String print()
693   {
694     synchronized (this)
695     {
696       StringBuffer tf = new StringBuffer();
697       print(tf, root);
698
699       return (tf.append(";").toString());
700     }
701   }
702
703   /**
704    * 
705    * 
706    * Generate a newick format tree according to internal flags for distances and
707    * root distances and user specificied writing of bootstraps.
708    * 
709    * @param withbootstraps
710    *          controls if bootstrap values are explicitly written.
711    * 
712    * @return new hampshire tree in a single line
713    */
714   public String print(boolean withbootstraps)
715   {
716     synchronized (this)
717     {
718       boolean boots = this.HasBootstrap;
719       this.HasBootstrap = withbootstraps;
720
721       String rv = print();
722       this.HasBootstrap = boots;
723
724       return rv;
725     }
726   }
727
728   /**
729    * 
730    * Generate newick format tree according to internal flags for writing root
731    * node distances.
732    * 
733    * @param withbootstraps
734    *          explicitly write bootstrap values
735    * @param withdists
736    *          explicitly write distances
737    * 
738    * @return new hampshire tree in a single line
739    */
740   public String print(boolean withbootstraps, boolean withdists)
741   {
742     synchronized (this)
743     {
744       boolean dists = this.HasDistances;
745       this.HasDistances = withdists;
746
747       String rv = print(withbootstraps);
748       this.HasDistances = dists;
749
750       return rv;
751     }
752   }
753
754   /**
755    * Generate newick format tree according to user specified flags
756    * 
757    * @param withbootstraps
758    *          explicitly write bootstrap values
759    * @param withdists
760    *          explicitly write distances
761    * @param printRootInfo
762    *          explicitly write root distance
763    * 
764    * @return new hampshire tree in a single line
765    */
766   public String print(boolean withbootstraps, boolean withdists,
767           boolean printRootInfo)
768   {
769     synchronized (this)
770     {
771       boolean rootinfo = printRootInfo;
772       this.printRootInfo = printRootInfo;
773
774       String rv = print(withbootstraps, withdists);
775       this.printRootInfo = rootinfo;
776
777       return rv;
778     }
779   }
780
781   /**
782    * DOCUMENT ME!
783    * 
784    * @return DOCUMENT ME!
785    */
786   char getQuoteChar()
787   {
788     return QuoteChar;
789   }
790
791   /**
792    * DOCUMENT ME!
793    * 
794    * @param c
795    *          DOCUMENT ME!
796    * 
797    * @return DOCUMENT ME!
798    */
799   char setQuoteChar(char c)
800   {
801     char old = QuoteChar;
802     QuoteChar = c;
803
804     return old;
805   }
806
807   /**
808    * DOCUMENT ME!
809    * 
810    * @param name
811    *          DOCUMENT ME!
812    * 
813    * @return DOCUMENT ME!
814    */
815   private String nodeName(String name)
816   {
817     if (NodeSafeName[0].search(name))
818     {
819       return QuoteChar + NodeSafeName[1].replaceAll(name) + QuoteChar;
820     }
821     else
822     {
823       return NodeSafeName[2].replaceAll(name);
824     }
825   }
826
827   /**
828    * DOCUMENT ME!
829    * 
830    * @param c
831    *          DOCUMENT ME!
832    * 
833    * @return DOCUMENT ME!
834    */
835   private String printNodeField(SequenceNode c)
836   {
837     return ((c.getName() == null) ? "" : nodeName(c.getName()))
838             + ((HasBootstrap) ? ((c.getBootstrap() > -1) ? ((c.getName() != null ? " "
839                     : "") + c.getBootstrap())
840                     : "")
841                     : "") + ((HasDistances) ? (":" + c.dist) : "");
842   }
843
844   /**
845    * DOCUMENT ME!
846    * 
847    * @param root
848    *          DOCUMENT ME!
849    * 
850    * @return DOCUMENT ME!
851    */
852   private String printRootField(SequenceNode root)
853   {
854     return (printRootInfo) ? (((root.getName() == null) ? ""
855             : nodeName(root.getName()))
856             + ((HasBootstrap) ? ((root.getBootstrap() > -1) ? ((root
857                     .getName() != null ? " " : "") + +root.getBootstrap())
858                     : "") : "") + ((RootHasDistance) ? (":" + root.dist)
859             : "")) : "";
860   }
861
862   // Non recursive call deals with root node properties
863   public void print(StringBuffer tf, SequenceNode root)
864   {
865     if (root != null)
866     {
867       if (root.isLeaf() && printRootInfo)
868       {
869         tf.append(printRootField(root));
870       }
871       else
872       {
873         if (root.isDummy())
874         {
875           _print(tf, (SequenceNode) root.right());
876           _print(tf, (SequenceNode) root.left());
877         }
878         else
879         {
880           tf.append("(");
881           _print(tf, (SequenceNode) root.right());
882
883           if (root.left() != null)
884           {
885             tf.append(",");
886           }
887
888           _print(tf, (SequenceNode) root.left());
889           tf.append(")" + printRootField(root));
890         }
891       }
892     }
893   }
894
895   // Recursive call for non-root nodes
896   public void _print(StringBuffer tf, SequenceNode c)
897   {
898     if (c != null)
899     {
900       if (c.isLeaf())
901       {
902         tf.append(printNodeField(c));
903       }
904       else
905       {
906         if (c.isDummy())
907         {
908           _print(tf, (SequenceNode) c.left());
909           if (c.left() != null)
910           {
911             tf.append(",");
912           }
913           _print(tf, (SequenceNode) c.right());
914         }
915         else
916         {
917           tf.append("(");
918           _print(tf, (SequenceNode) c.right());
919
920           if (c.left() != null)
921           {
922             tf.append(",");
923           }
924
925           _print(tf, (SequenceNode) c.left());
926           tf.append(")" + printNodeField(c));
927         }
928       }
929     }
930   }
931
932   // Test
933   public static void main(String[] args)
934   {
935     try
936     {
937       if (args == null || args.length != 1)
938       {
939         System.err
940                 .println("Takes one argument - file name of a newick tree file.");
941         System.exit(0);
942       }
943
944       File fn = new File(args[0]);
945
946       StringBuffer newickfile = new StringBuffer();
947       BufferedReader treefile = new BufferedReader(new FileReader(fn));
948       String l;
949
950       while ((l = treefile.readLine()) != null)
951       {
952         newickfile.append(l);
953       }
954
955       treefile.close();
956       System.out.println("Read file :\n");
957
958       NewickFile trf = new NewickFile(args[0], "File");
959       trf.parse();
960       System.out.println("Original file :\n");
961
962       com.stevesoft.pat.Regex nonl = new com.stevesoft.pat.Regex("\n+", "");
963       System.out.println(nonl.replaceAll(newickfile.toString()) + "\n");
964
965       System.out.println("Parsed file.\n");
966       System.out.println("Default output type for original input.\n");
967       System.out.println(trf.print());
968       System.out.println("Without bootstraps.\n");
969       System.out.println(trf.print(false));
970       System.out.println("Without distances.\n");
971       System.out.println(trf.print(true, false));
972       System.out.println("Without bootstraps but with distanecs.\n");
973       System.out.println(trf.print(false, true));
974       System.out.println("Without bootstraps or distanecs.\n");
975       System.out.println(trf.print(false, false));
976       System.out.println("With bootstraps and with distances.\n");
977       System.out.println(trf.print(true, true));
978     } catch (java.io.IOException e)
979     {
980       System.err.println("Exception\n" + e);
981       e.printStackTrace();
982     }
983   }
984 }