372690983598af0aceb00f5ce0442d657883e102
[jalview.git] / src / jalview / io / NewickFile.java
1 /*
2  * Jalview - A Sequence Alignment Editor and Viewer (Development Version 2.4.1)
3  * Copyright (C) 2009 AM Waterhouse, J Procter, G Barton, M Clamp, S Searle
4  * 
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.
9  * 
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.
14  * 
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
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) <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
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), ((p + r) > s
220                     .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
250    *                 formatted NH 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     while (majorsyms.searchFrom(nf, cp) && (Error == null))
297     {
298       int fcp = majorsyms.matchedFrom();
299       char schar;
300       switch (schar = nf.charAt(fcp))
301       {
302       case '(':
303
304         // ascending should not be set
305         // New Internal node
306         if (ascending)
307         {
308           Error = ErrorStringrange(Error, "Unexpected '('", 7, fcp, nf);
309
310           continue;
311         }
312
313         ;
314         d++;
315
316         if (c.right() == null)
317         {
318           c.setRight(new SequenceNode(null, c, null, DefDistance,
319                   DefBootstrap, false));
320           c = (SequenceNode) c.right();
321         }
322         else
323         {
324           if (c.left() != null)
325           {
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());
329             c.setRight(tmpn);
330           }
331
332           c.setLeft(new SequenceNode(null, c, null, DefDistance,
333                   DefBootstrap, false));
334           c = (SequenceNode) c.left();
335         }
336
337         if (realroot == null)
338         {
339           realroot = c;
340         }
341
342         nodename = null;
343         distance = DefDistance;
344         bootstrap = DefBootstrap;
345         cp = fcp + 1;
346
347         break;
348
349       // Deal with quoted fields
350       case '\'':
351
352         com.stevesoft.pat.Regex qnodename = new com.stevesoft.pat.Regex(
353                 "([^']|'')+'");
354
355         if (qnodename.searchFrom(nf, fcp))
356         {
357           int nl = qnodename.stringMatched().length();
358           nodename = new String(qnodename.stringMatched().substring(0,
359                   nl - 1));
360           cp = fcp + nl + 1;
361         }
362         else
363         {
364           Error = ErrorStringrange(Error,
365                   "Unterminated quotes for nodename", 7, fcp, nf);
366         }
367
368         break;
369
370       default:
371         if (schar == ';')
372         {
373           if (d != -1)
374           {
375             Error = ErrorStringrange(Error, "Wayward semicolon (depth=" + d
376                     + ")", 7, fcp, nf);
377           }
378           // cp advanced at the end of default
379         }
380         if (schar == '[')
381         {
382           // node string contains Comment or structured/extended NH format info
383           /*
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)+"'"); }
387            */
388           // verify termination.
389           com.stevesoft.pat.Regex comment = new com.stevesoft.pat.Regex("]");
390           if (comment.searchFrom(nf, fcp))
391           {
392             // Skip the comment field
393             nextcp = comment.matchedFrom() + 1;
394             warningMessage = "Tree file contained comments which may confuse input algorithm.";
395             break;
396
397             // cp advanced at the end of default to nextcp, ncp is unchanged so
398             // any node info can be read.
399           }
400           else
401           {
402             Error = ErrorStringrange(Error, "Unterminated comment", 3, fcp,
403                     nf);
404           }
405
406           ;
407         }
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
412         // this allowed?)
413         while (fstring.indexOf(']') > -1)
414         {
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);
420
421         }
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(
427                 ":([-0-9Ee.+]+)");
428
429         if (uqnodename.search(fstring)
430                 && ((uqnodename.matchedFrom(1) == 0) || (fstring
431                         .charAt(uqnodename.matchedFrom(1) - 1) != ':'))) // JBPNote
432         // HACK!
433         {
434           if (nodename == null)
435           {
436             if (ReplaceUnderscores)
437             {
438               nodename = uqnodename.stringMatched(1).replace('_', ' ');
439             }
440             else
441             {
442               nodename = uqnodename.stringMatched(1);
443             }
444           }
445           else
446           {
447             Error = ErrorStringrange(Error,
448                     "File has broken algorithm - overwritten nodename", 10,
449                     fcp, nf);
450           }
451         }
452         // get comment bootstraps
453
454         if (nbootstrap.search(fstring))
455         {
456           if (nbootstrap.stringMatched(1).equals(
457                   uqnodename.stringMatched(1)))
458           {
459             nodename = null; // no nodename here.
460           }
461           if (nodename == null
462                   || nodename.length() == 0
463                   || nbootstrap.matchedFrom(1) > (uqnodename.matchedFrom(1) + uqnodename
464                           .stringMatched().length()))
465           {
466             try
467             {
468               bootstrap = (new Integer(nbootstrap.stringMatched(1)))
469                       .intValue();
470               HasBootstrap = true;
471             } catch (Exception e)
472             {
473               Error = ErrorStringrange(Error,
474                       "Can't parse bootstrap value", 4, ncp
475                               + nbootstrap.matchedFrom(), nf);
476             }
477           }
478         }
479
480         boolean nodehasdistance = false;
481
482         if (ndist.search(fstring))
483         {
484           try
485           {
486             distance = (new Float(ndist.stringMatched(1))).floatValue();
487             HasDistances = true;
488             nodehasdistance = true;
489           } catch (Exception e)
490           {
491             Error = ErrorStringrange(Error,
492                     "Can't parse node distance value", 7, ncp
493                             + ndist.matchedFrom(), nf);
494           }
495         }
496
497         if (ascending)
498         {
499           // Write node info here
500           c.setName(nodename);
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);
505           if (c == realroot)
506           {
507             RootHasDistance = nodehasdistance; // JBPNote This is really
508             // UGLY!!! Ensure root node gets
509             // its given distance
510           }
511           parseNHXNodeProps(c, commentString2);
512           commentString2 = null;
513         }
514         else
515         {
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;
522
523           if (c.right() == null)
524           {
525             c.setRight(newnode);
526           }
527           else
528           {
529             if (c.left() == null)
530             {
531               c.setLeft(newnode);
532             }
533             else
534             {
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);
540               c.setLeft(newdummy);
541             }
542           }
543         }
544
545         if (ascending)
546         {
547           // move back up the tree from preceding closure
548           c = c.AscendTree();
549
550           if ((d > -1) && (c == null))
551           {
552             Error = ErrorStringrange(
553                     Error,
554                     "File broke algorithm: Lost place in tree (is there an extra ')' ?)",
555                     7, fcp, nf);
556           }
557         }
558
559         if (nf.charAt(fcp) == ')')
560         {
561           d--;
562           ascending = true;
563         }
564         else
565         {
566           if (nf.charAt(fcp) == ',')
567           {
568             if (ascending)
569             {
570               ascending = false;
571             }
572             else
573             {
574               // Just advance focus, if we need to
575               if ((c.left() != null) && (!c.left().isLeaf()))
576               {
577                 c = (SequenceNode) c.left();
578               }
579             }
580           }
581         }
582
583         // Reset new node properties to obvious fakes
584         nodename = null;
585         distance = DefDistance;
586         bootstrap = DefBootstrap;
587         commentString2 = null;
588       }
589       if (nextcp == 0)
590       {
591         ncp = cp = fcp + 1;
592       }
593       else
594       {
595         cp = nextcp;
596         nextcp = 0;
597       }
598     }
599
600     if (Error != null)
601     {
602       throw (new IOException("NewickFile: " + Error + "\n"));
603     }
604     if (root == null)
605     {
606       throw (new IOException("NewickFile: No Tree read in\n"));
607     }
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.
611
612     if (!RootHasDistance)
613     {
614       root.dist = (HasDistances) ? 0 : DefDistance;
615     }
616   }
617
618   /**
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.
621    * 
622    * @param c
623    * @param commentString
624    * @param commentString2
625    */
626   private void parseNHXNodeProps(SequenceNode c, String commentString)
627   {
628     // TODO: store raw comment on the sequenceNode so it can be recovered when
629     // tree is output
630     if (commentString != null && commentString.startsWith("&&NHX"))
631     {
632       StringTokenizer st = new StringTokenizer(commentString.substring(5),
633               ":");
634       while (st.hasMoreTokens())
635       {
636         String tok = st.nextToken();
637         int colpos = tok.indexOf("=");
638
639         if (colpos > -1)
640         {
641           String code = tok.substring(0, colpos);
642           String value = tok.substring(colpos + 1);
643           try
644           {
645             // parse out code/value pairs
646             if (code.toLowerCase().equals("b"))
647             {
648               int v = -1;
649               Float iv = new Float(value);
650               v = iv.intValue(); // jalview only does integer bootstraps
651               // currently
652               c.setBootstrap(v);
653               HasBootstrap = true;
654             }
655             // more codes here.
656           } catch (Exception e)
657           {
658             System.err.println("Couldn't parse code '" + code + "' = '"
659                     + value + "'");
660             e.printStackTrace(System.err);
661           }
662         }
663       }
664     }
665
666   }
667
668   /**
669    * DOCUMENT ME!
670    * 
671    * @return DOCUMENT ME!
672    */
673   public SequenceNode getTree()
674   {
675     return root;
676   }
677
678   /**
679    * Generate a newick format tree according to internal flags for bootstraps,
680    * distances and root distances.
681    * 
682    * @return new hampshire tree in a single line
683    */
684   public String print()
685   {
686     synchronized (this)
687     {
688       StringBuffer tf = new StringBuffer();
689       print(tf, root);
690
691       return (tf.append(";").toString());
692     }
693   }
694
695   /**
696    * 
697    * 
698    * Generate a newick format tree according to internal flags for distances and
699    * root distances and user specificied writing of bootstraps.
700    * 
701    * @param withbootstraps
702    *                controls if bootstrap values are explicitly written.
703    * 
704    * @return new hampshire tree in a single line
705    */
706   public String print(boolean withbootstraps)
707   {
708     synchronized (this)
709     {
710       boolean boots = this.HasBootstrap;
711       this.HasBootstrap = withbootstraps;
712
713       String rv = print();
714       this.HasBootstrap = boots;
715
716       return rv;
717     }
718   }
719
720   /**
721    * 
722    * Generate newick format tree according to internal flags for writing root
723    * node distances.
724    * 
725    * @param withbootstraps
726    *                explicitly write bootstrap values
727    * @param withdists
728    *                explicitly write distances
729    * 
730    * @return new hampshire tree in a single line
731    */
732   public String print(boolean withbootstraps, boolean withdists)
733   {
734     synchronized (this)
735     {
736       boolean dists = this.HasDistances;
737       this.HasDistances = withdists;
738
739       String rv = print(withbootstraps);
740       this.HasDistances = dists;
741
742       return rv;
743     }
744   }
745
746   /**
747    * Generate newick format tree according to user specified flags
748    * 
749    * @param withbootstraps
750    *                explicitly write bootstrap values
751    * @param withdists
752    *                explicitly write distances
753    * @param printRootInfo
754    *                explicitly write root distance
755    * 
756    * @return new hampshire tree in a single line
757    */
758   public String print(boolean withbootstraps, boolean withdists,
759           boolean printRootInfo)
760   {
761     synchronized (this)
762     {
763       boolean rootinfo = printRootInfo;
764       this.printRootInfo = printRootInfo;
765
766       String rv = print(withbootstraps, withdists);
767       this.printRootInfo = rootinfo;
768
769       return rv;
770     }
771   }
772
773   /**
774    * DOCUMENT ME!
775    * 
776    * @return DOCUMENT ME!
777    */
778   char getQuoteChar()
779   {
780     return QuoteChar;
781   }
782
783   /**
784    * DOCUMENT ME!
785    * 
786    * @param c
787    *                DOCUMENT ME!
788    * 
789    * @return DOCUMENT ME!
790    */
791   char setQuoteChar(char c)
792   {
793     char old = QuoteChar;
794     QuoteChar = c;
795
796     return old;
797   }
798
799   /**
800    * DOCUMENT ME!
801    * 
802    * @param name
803    *                DOCUMENT ME!
804    * 
805    * @return DOCUMENT ME!
806    */
807   private String nodeName(String name)
808   {
809     if (NodeSafeName[0].search(name))
810     {
811       return QuoteChar + NodeSafeName[1].replaceAll(name) + QuoteChar;
812     }
813     else
814     {
815       return NodeSafeName[2].replaceAll(name);
816     }
817   }
818
819   /**
820    * DOCUMENT ME!
821    * 
822    * @param c
823    *                DOCUMENT ME!
824    * 
825    * @return DOCUMENT ME!
826    */
827   private String printNodeField(SequenceNode c)
828   {
829     return ((c.getName() == null) ? "" : nodeName(c.getName()))
830             + ((HasBootstrap) ? ((c.getBootstrap() > -1) ? ((c.getName() != null ? " "
831                     : "") + c.getBootstrap())
832                     : "")
833                     : "") + ((HasDistances) ? (":" + c.dist) : "");
834   }
835
836   /**
837    * DOCUMENT ME!
838    * 
839    * @param root
840    *                DOCUMENT ME!
841    * 
842    * @return DOCUMENT ME!
843    */
844   private String printRootField(SequenceNode root)
845   {
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)
851             : "")) : "";
852   }
853
854   // Non recursive call deals with root node properties
855   public void print(StringBuffer tf, SequenceNode root)
856   {
857     if (root != null)
858     {
859       if (root.isLeaf() && printRootInfo)
860       {
861         tf.append(printRootField(root));
862       }
863       else
864       {
865         if (root.isDummy())
866         {
867           _print(tf, (SequenceNode) root.right());
868           _print(tf, (SequenceNode) root.left());
869         }
870         else
871         {
872           tf.append("(");
873           _print(tf, (SequenceNode) root.right());
874
875           if (root.left() != null)
876           {
877             tf.append(",");
878           }
879
880           _print(tf, (SequenceNode) root.left());
881           tf.append(")" + printRootField(root));
882         }
883       }
884     }
885   }
886
887   // Recursive call for non-root nodes
888   public void _print(StringBuffer tf, SequenceNode c)
889   {
890     if (c != null)
891     {
892       if (c.isLeaf())
893       {
894         tf.append(printNodeField(c));
895       }
896       else
897       {
898         if (c.isDummy())
899         {
900           _print(tf, (SequenceNode) c.left());
901           if (c.left() != null)
902           {
903             tf.append(",");
904           }
905           _print(tf, (SequenceNode) c.right());
906         }
907         else
908         {
909           tf.append("(");
910           _print(tf, (SequenceNode) c.right());
911
912           if (c.left() != null)
913           {
914             tf.append(",");
915           }
916
917           _print(tf, (SequenceNode) c.left());
918           tf.append(")" + printNodeField(c));
919         }
920       }
921     }
922   }
923
924   // Test
925   public static void main(String[] args)
926   {
927     try
928     {
929       if (args == null || args.length != 1)
930       {
931         System.err
932                 .println("Takes one argument - file name of a newick tree file.");
933         System.exit(0);
934       }
935
936       File fn = new File(args[0]);
937
938       StringBuffer newickfile = new StringBuffer();
939       BufferedReader treefile = new BufferedReader(new FileReader(fn));
940       String l;
941
942       while ((l = treefile.readLine()) != null)
943       {
944         newickfile.append(l);
945       }
946
947       treefile.close();
948       System.out.println("Read file :\n");
949
950       NewickFile trf = new NewickFile(args[0], "File");
951       trf.parse();
952       System.out.println("Original file :\n");
953
954       com.stevesoft.pat.Regex nonl = new com.stevesoft.pat.Regex("\n+", "");
955       System.out.println(nonl.replaceAll(newickfile.toString()) + "\n");
956
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)
971     {
972       System.err.println("Exception\n" + e);
973       e.printStackTrace();
974     }
975   }
976 }