in progress
[jalview.git] / forester / java / src / org / forester / io / writers / PhylogenyWriter.java
1 // $Id:
2 // FORESTER -- software libraries and applications
3 // for evolutionary biology research and applications.
4 //
5 // Copyright (C) 2008-2009 Christian M. Zmasek
6 // Copyright (C) 2008-2009 Burnham Institute for Medical Research
7 // All rights reserved
8 //
9 // This library is free software; you can redistribute it and/or
10 // modify it under the terms of the GNU Lesser General Public
11 // License as published by the Free Software Foundation; either
12 // version 2.1 of the License, or (at your option) any later version.
13 //
14 // This library is distributed in the hope that it will be useful,
15 // but WITHOUT ANY WARRANTY; without even the implied warranty of
16 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
17 // Lesser General Public License for more details.
18 //
19 // You should have received a copy of the GNU Lesser General Public
20 // License along with this library; if not, write to the Free Software
21 // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
22 //
23 // Contact: phylosoft @ gmail . com
24 // WWW: www.phylosoft.org/forester
25
26 package org.forester.io.writers;
27
28 import java.io.BufferedWriter;
29 import java.io.File;
30 import java.io.FileWriter;
31 import java.io.IOException;
32 import java.io.PrintWriter;
33 import java.io.StringWriter;
34 import java.io.Writer;
35 import java.util.ArrayList;
36 import java.util.Iterator;
37 import java.util.List;
38 import java.util.Stack;
39
40 import org.forester.io.parsers.nexus.NexusConstants;
41 import org.forester.io.parsers.phyloxml.PhyloXmlMapping;
42 import org.forester.phylogeny.Phylogeny;
43 import org.forester.phylogeny.PhylogenyNode;
44 import org.forester.phylogeny.data.PhylogenyDataUtil;
45 import org.forester.phylogeny.iterators.PhylogenyNodeIterator;
46 import org.forester.phylogeny.iterators.PostOrderStackObject;
47 import org.forester.util.ForesterConstants;
48 import org.forester.util.ForesterUtil;
49
50 public final class PhylogenyWriter {
51
52     public final static boolean         INDENT_PHYLOXML_DEAFULT         = true;
53     public final static String          PHYLO_XML_INTENDATION_BASE      = "  ";
54     public final static String          PHYLO_XML_VERSION_ENCODING_LINE = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>";
55     public final static String          PHYLO_XML_NAMESPACE_LINE        = "<phyloxml xmlns:xsi=\""
56                                                                                 + ForesterConstants.XML_SCHEMA_INSTANCE
57                                                                                 + "\" xsi:schemaLocation=\""
58                                                                                 + ForesterConstants.PHYLO_XML_LOCATION
59                                                                                 + " "
60                                                                                 + ForesterConstants.PHYLO_XML_LOCATION
61                                                                                 + "/"
62                                                                                 + ForesterConstants.PHYLO_XML_VERSION
63                                                                                 + "/" + ForesterConstants.PHYLO_XML_XSD
64                                                                                 + "\" " + "xmlns=\""
65                                                                                 + ForesterConstants.PHYLO_XML_LOCATION
66                                                                                 + "\">";
67     public final static String          PHYLO_XML_END                   = "</phyloxml>";
68     private boolean                     _saw_comma;
69     private StringBuffer                _buffer;
70     private Writer                      _writer;
71     private PhylogenyNode               _root;
72     private boolean                     _has_next;
73     private Stack<PostOrderStackObject> _stack;
74     private boolean                     _simple_nh;
75     private boolean                     _nh_write_distance_to_parent;
76     private boolean                     _write_conf_values_in_branckets_in_nh;
77     private boolean                     _indent_phyloxml;
78     private int                         _node_level;
79     private int                         _phyloxml_level;
80     private FORMAT                      _format;
81
82     public PhylogenyWriter() {
83         setIndentPhyloxml( INDENT_PHYLOXML_DEAFULT );
84         setWriteConfidenceValuesInBracketsInNH( false );
85     }
86
87     private void appendPhylogenyLevelPhyloXml( final Writer writer, final Phylogeny tree ) throws IOException {
88         final String indentation = new String();
89         if ( !ForesterUtil.isEmpty( tree.getName() ) ) {
90             PhylogenyDataUtil.appendElement( writer, PhyloXmlMapping.PHYLOGENY_NAME, tree.getName(), indentation );
91         }
92         if ( tree.getIdentifier() != null ) {
93             if ( ForesterUtil.isEmpty( tree.getIdentifier().getProvider() ) ) {
94                 PhylogenyDataUtil.appendElement( writer,
95                                                  PhyloXmlMapping.IDENTIFIER,
96                                                  tree.getIdentifier().getValue(),
97                                                  indentation );
98             }
99             PhylogenyDataUtil.appendElement( writer,
100                                              PhyloXmlMapping.IDENTIFIER,
101                                              tree.getIdentifier().getValue(),
102                                              PhyloXmlMapping.IDENTIFIER_PROVIDER_ATTR,
103                                              tree.getIdentifier().getProvider(),
104                                              indentation );
105         }
106         if ( !ForesterUtil.isEmpty( tree.getDescription() ) ) {
107             PhylogenyDataUtil.appendElement( writer,
108                                              PhyloXmlMapping.PHYLOGENY_DESCRIPTION,
109                                              tree.getDescription(),
110                                              indentation );
111         }
112         if ( tree.getConfidence() != null ) {
113             if ( ForesterUtil.isEmpty( tree.getConfidence().getType() ) ) {
114                 PhylogenyDataUtil.appendElement( writer, PhyloXmlMapping.CONFIDENCE, tree.getConfidence().getValue()
115                         + "", indentation );
116             }
117             PhylogenyDataUtil.appendElement( writer,
118                                              PhyloXmlMapping.CONFIDENCE,
119                                              tree.getConfidence().getValue() + "",
120                                              PhyloXmlMapping.CONFIDENCE_TYPE_ATTR,
121                                              tree.getConfidence().getType(),
122                                              indentation );
123         }
124     }
125
126     private StringBuffer createIndentation() {
127         if ( !isIndentPhyloxml() ) {
128             return null;
129         }
130         final StringBuffer sb = new StringBuffer( getNodeLevel() * 2 );
131         for( int i = 0; i < getNodeLevel(); ++i ) {
132             sb.append( PhylogenyWriter.PHYLO_XML_INTENDATION_BASE );
133         }
134         return sb;
135     }
136
137     private void decreaseNodeLevel() {
138         --_node_level;
139     }
140
141     private StringBuffer getBuffer() {
142         return _buffer;
143     }
144
145     private int getNodeLevel() {
146         return _node_level;
147     }
148
149     private StringBuffer getOutput( final Phylogeny tree ) throws IOException {
150         if ( getOutputFormt() == FORMAT.PHYLO_XML ) {
151             throw new RuntimeException( "method inappropriately called" );
152         }
153         if ( tree != null ) {
154             reset( tree );
155             while ( isHasNext() ) {
156                 next();
157             }
158             if ( getOutputFormt() == FORMAT.NH ) {
159                 getBuffer().append( ';' );
160             }
161             return getBuffer();
162         }
163         else {
164             return new StringBuffer( 0 );
165         }
166     }
167
168     private FORMAT getOutputFormt() {
169         return _format;
170     }
171
172     private int getPhyloXmlLevel() {
173         return _phyloxml_level;
174     }
175
176     private PhylogenyNode getRoot() {
177         return _root;
178     }
179
180     private Stack<PostOrderStackObject> getStack() {
181         return _stack;
182     }
183
184     private Writer getWriter() {
185         return _writer;
186     }
187
188     private void increaseNodeLevel() {
189         ++_node_level;
190     }
191
192     private boolean isHasNext() {
193         return _has_next;
194     }
195
196     private boolean isIndentPhyloxml() {
197         return _indent_phyloxml;
198     }
199
200     private boolean isSawComma() {
201         return _saw_comma;
202     }
203
204     private boolean isSimpleNH() {
205         return _simple_nh;
206     }
207
208     private boolean isWriteDistanceToParentInNH() {
209         return _nh_write_distance_to_parent;
210     }
211
212     private void next() throws IOException {
213         while ( true ) {
214             final PostOrderStackObject si = getStack().pop();
215             final PhylogenyNode node = si.getNode();
216             final int phase = si.getPhase();
217             if ( phase > node.getNumberOfDescendants() ) {
218                 setHasNext( node != getRoot() );
219                 if ( ( getOutputFormt() != FORMAT.PHYLO_XML ) || node.isExternal() ) {
220                     if ( !node.isRoot() && node.isFirstChildNode() ) {
221                         increaseNodeLevel();
222                     }
223                     if ( getOutputFormt() == FORMAT.PHYLO_XML ) {
224                         writeNode( node, createIndentation() );
225                     }
226                     else {
227                         writeNode( node, null );
228                     }
229                 }
230                 if ( !node.isRoot() ) {
231                     if ( !node.isLastChildNode() ) {
232                         writeCladeSeparator();
233                     }
234                     else {
235                         writeCloseClade();
236                     }
237                 }
238                 return;
239             }
240             else {
241                 getStack().push( new PostOrderStackObject( node, ( phase + 1 ) ) );
242                 if ( node.isInternal() ) {
243                     getStack().push( new PostOrderStackObject( node.getChildNode( phase - 1 ), 1 ) );
244                     writeOpenClade( node );
245                     if ( getOutputFormt() == FORMAT.PHYLO_XML ) {
246                         if ( phase == 1 ) {
247                             writeNode( node, createIndentation() );
248                         }
249                     }
250                 }
251             }
252         }
253     }
254
255     private void reset( final Phylogeny tree ) {
256         setBuffer( new StringBuffer() );
257         setWriter( null );
258         setSawComma( false );
259         setHasNext( true );
260         setRoot( tree.getRoot() );
261         setStack( new Stack<PostOrderStackObject>() );
262         getStack().push( new PostOrderStackObject( tree.getRoot(), 1 ) );
263         setNodeLevel( 1 );
264     }
265
266     private void reset( final Writer writer, final Phylogeny tree ) {
267         setBuffer( null );
268         setWriter( writer );
269         setSawComma( false );
270         setHasNext( true );
271         setRoot( tree.getRoot() );
272         setStack( new Stack<PostOrderStackObject>() );
273         getStack().push( new PostOrderStackObject( tree.getRoot(), 1 ) );
274         setNodeLevel( 1 );
275     }
276
277     private void setBuffer( final StringBuffer buffer ) {
278         _buffer = buffer;
279     }
280
281     private void setHasNext( final boolean has_next ) {
282         _has_next = has_next;
283     }
284
285     public void setIndentPhyloxml( final boolean indent_phyloxml ) {
286         _indent_phyloxml = indent_phyloxml;
287     }
288
289     private void setNodeLevel( final int level ) {
290         _node_level = level;
291     }
292
293     private void setOutputFormt( final FORMAT format ) {
294         _format = format;
295     }
296
297     private void setPhyloXmlLevel( final int phyloxml_level ) {
298         _phyloxml_level = phyloxml_level;
299     }
300
301     private void setRoot( final PhylogenyNode root ) {
302         _root = root;
303     }
304
305     private void setSawComma( final boolean saw_comma ) {
306         _saw_comma = saw_comma;
307     }
308
309     private void setSimpleNH( final boolean simple_nh ) {
310         _simple_nh = simple_nh;
311     }
312
313     private void setStack( final Stack<PostOrderStackObject> stack ) {
314         _stack = stack;
315     }
316
317     private void setWriteDistanceToParentInNH( final boolean nh_write_distance_to_parent ) {
318         _nh_write_distance_to_parent = nh_write_distance_to_parent;
319     }
320
321     private void setWriter( final Writer writer ) {
322         _writer = writer;
323     }
324
325     public void toNewHampshire( final List<Phylogeny> trees,
326                                 final boolean simple_nh,
327                                 final boolean write_distance_to_parent,
328                                 final File out_file,
329                                 final String separator ) throws IOException {
330         final Iterator<Phylogeny> it = trees.iterator();
331         final StringBuffer sb = new StringBuffer();
332         while ( it.hasNext() ) {
333             sb.append( toNewHampshire( it.next(), simple_nh, write_distance_to_parent ) );
334             sb.append( separator );
335         }
336         writeToFile( sb, out_file );
337     }
338
339     public StringBuffer toNewHampshire( final Phylogeny tree,
340                                         final boolean simple_nh,
341                                         final boolean nh_write_distance_to_parent,
342                                         final boolean write_conf_values_in_branckets_in_nh ) throws IOException {
343         setOutputFormt( FORMAT.NH );
344         setWriteConfidenceValuesInBracketsInNH( write_conf_values_in_branckets_in_nh );
345         setSimpleNH( simple_nh );
346         setWriteDistanceToParentInNH( nh_write_distance_to_parent );
347         return getOutput( tree );
348     }
349
350     public StringBuffer toNewHampshire( final Phylogeny tree,
351                                         final boolean simple_nh,
352                                         final boolean nh_write_distance_to_parent ) throws IOException {
353         setOutputFormt( FORMAT.NH );
354         setSimpleNH( simple_nh );
355         setWriteDistanceToParentInNH( nh_write_distance_to_parent );
356         return getOutput( tree );
357     }
358
359     public void toNewHampshire( final Phylogeny tree,
360                                 final boolean simple_nh,
361                                 final boolean write_distance_to_parent,
362                                 final File out_file ) throws IOException {
363         writeToFile( toNewHampshire( tree, simple_nh, write_distance_to_parent ), out_file );
364     }
365
366     public void toNewHampshire( final Phylogeny tree,
367                                 final boolean simple_nh,
368                                 final boolean write_distance_to_parent,
369                                 final boolean use_brackets_for_confidence,
370                                 final File out_file ) throws IOException {
371         writeToFile( toNewHampshire( tree, simple_nh, write_distance_to_parent, use_brackets_for_confidence ), out_file );
372     }
373
374     public void toNewHampshire( final Phylogeny[] trees,
375                                 final boolean simple_nh,
376                                 final boolean write_distance_to_parent,
377                                 final File out_file,
378                                 final String separator ) throws IOException {
379         final StringBuffer sb = new StringBuffer();
380         for( final Phylogeny element : trees ) {
381             sb.append( toNewHampshire( element, simple_nh, write_distance_to_parent ) );
382             sb.append( separator );
383         }
384         writeToFile( sb, out_file );
385     }
386
387     public void toNewHampshireX( final List<Phylogeny> trees, final File out_file, final String separator )
388             throws IOException {
389         final Iterator<Phylogeny> it = trees.iterator();
390         final StringBuffer sb = new StringBuffer();
391         while ( it.hasNext() ) {
392             sb.append( toNewHampshireX( it.next() ) );
393             sb.append( separator );
394         }
395         writeToFile( sb, out_file );
396     }
397
398     public StringBuffer toNewHampshireX( final Phylogeny tree ) throws IOException {
399         setOutputFormt( FORMAT.NHX );
400         return getOutput( tree );
401     }
402
403     public void toNewHampshireX( final Phylogeny tree, final File out_file ) throws IOException {
404         writeToFile( toNewHampshireX( tree ), out_file );
405     }
406
407     public void toNewHampshireX( final Phylogeny[] trees, final File out_file, final String separator )
408             throws IOException {
409         final StringBuffer sb = new StringBuffer();
410         for( final Phylogeny element : trees ) {
411             sb.append( toNewHampshireX( element ) );
412             sb.append( separator );
413         }
414         writeToFile( sb, out_file );
415     }
416
417     public void toNexus( final File out_file, final Phylogeny tree, final boolean write_conf_values_in_branckets_in_nh )
418             throws IOException {
419         final Writer writer = new BufferedWriter( new PrintWriter( out_file ) );
420         final List<Phylogeny> trees = new ArrayList<Phylogeny>( 1 );
421         trees.add( tree );
422         writeNexusStart( writer );
423         writeNexusTaxaBlock( writer, tree );
424         writeNexusTreesBlock( writer, trees, write_conf_values_in_branckets_in_nh );
425         writer.flush();
426         writer.close();
427     }
428
429     public StringBuffer toNexus( final Phylogeny tree, final boolean write_conf_values_in_branckets_in_nh )
430             throws IOException {
431         final StringWriter string_writer = new StringWriter();
432         final Writer writer = new BufferedWriter( string_writer );
433         final List<Phylogeny> trees = new ArrayList<Phylogeny>( 1 );
434         trees.add( tree );
435         writeNexusStart( writer );
436         writeNexusTaxaBlock( writer, tree );
437         writeNexusTreesBlock( writer, trees, write_conf_values_in_branckets_in_nh );
438         writer.flush();
439         writer.close();
440         return string_writer.getBuffer();
441     }
442
443     public void toPhyloXML( final File out_file,
444                             final List<Phylogeny> trees,
445                             final int phyloxml_level,
446                             final String separator ) throws IOException {
447         final Writer writer = new BufferedWriter( new PrintWriter( out_file ) );
448         toPhyloXML( writer, trees, phyloxml_level, separator );
449         writer.flush();
450         writer.close();
451     }
452
453     public void toPhyloXML( final File out_file, final Phylogeny tree, final int phyloxml_level ) throws IOException {
454         final Writer writer = new BufferedWriter( new PrintWriter( out_file ) );
455         writePhyloXmlStart( writer );
456         toPhyloXMLNoPhyloXmlSource( writer, tree, phyloxml_level );
457         writePhyloXmlEnd( writer );
458         writer.flush();
459         writer.close();
460     }
461
462     public StringBuffer toPhyloXML( final Phylogeny tree, final int phyloxml_level ) throws IOException {
463         final StringWriter string_writer = new StringWriter();
464         final Writer writer = new BufferedWriter( string_writer );
465         setPhyloXmlLevel( phyloxml_level );
466         setOutputFormt( FORMAT.PHYLO_XML );
467         writePhyloXmlStart( writer );
468         writeOutput( writer, tree );
469         writePhyloXmlEnd( writer );
470         writer.flush();
471         writer.close();
472         return string_writer.getBuffer();
473     }
474
475     public void toPhyloXML( final Phylogeny[] trees,
476                             final int phyloxml_level,
477                             final File out_file,
478                             final String separator ) throws IOException {
479         final Writer writer = new BufferedWriter( new PrintWriter( out_file ) );
480         toPhyloXML( writer, trees, phyloxml_level, separator );
481         writer.flush();
482         writer.close();
483     }
484
485     public void toPhyloXML( final Writer writer,
486                             final List<Phylogeny> trees,
487                             final int phyloxml_level,
488                             final String separator ) throws IOException {
489         writePhyloXmlStart( writer );
490         final Iterator<Phylogeny> it = trees.iterator();
491         while ( it.hasNext() ) {
492             toPhyloXMLNoPhyloXmlSource( writer, it.next(), phyloxml_level );
493             writer.write( separator );
494         }
495         writePhyloXmlEnd( writer );
496     }
497
498     public void toPhyloXML( final Writer writer, final Phylogeny tree, final int phyloxml_level ) throws IOException {
499         setPhyloXmlLevel( phyloxml_level );
500         setOutputFormt( FORMAT.PHYLO_XML );
501         writePhyloXmlStart( writer );
502         writeOutput( writer, tree );
503         writePhyloXmlEnd( writer );
504     }
505
506     public void toPhyloXML( final Writer writer,
507                             final Phylogeny[] trees,
508                             final int phyloxml_level,
509                             final String separator ) throws IOException {
510         writePhyloXmlStart( writer );
511         for( final Phylogeny phylogeny : trees ) {
512             toPhyloXMLNoPhyloXmlSource( writer, phylogeny, phyloxml_level );
513             writer.write( separator );
514         }
515         writePhyloXmlEnd( writer );
516     }
517
518     private void toPhyloXMLNoPhyloXmlSource( final Writer writer, final Phylogeny tree, final int phyloxml_level )
519             throws IOException {
520         setPhyloXmlLevel( phyloxml_level );
521         setOutputFormt( FORMAT.PHYLO_XML );
522         writeOutput( writer, tree );
523     }
524
525     private void writeCladeSeparator() {
526         setSawComma( true );
527         if ( ( getOutputFormt() == FORMAT.NHX ) || ( getOutputFormt() == FORMAT.NH ) ) {
528             getBuffer().append( "," );
529         }
530     }
531
532     private void writeCloseClade() throws IOException {
533         decreaseNodeLevel();
534         if ( getOutputFormt() == FORMAT.PHYLO_XML ) {
535             getWriter().write( ForesterUtil.LINE_SEPARATOR );
536             if ( isIndentPhyloxml() ) {
537                 getWriter().write( createIndentation().toString() );
538             }
539             PhylogenyDataUtil.appendClose( getWriter(), PhyloXmlMapping.CLADE );
540         }
541         else if ( ( getOutputFormt() == FORMAT.NHX ) || ( getOutputFormt() == FORMAT.NH ) ) {
542             getBuffer().append( ")" );
543         }
544     }
545
546     private void writeNode( final PhylogenyNode node, final StringBuffer indentation ) throws IOException {
547         if ( getOutputFormt() == FORMAT.PHYLO_XML ) {
548             if ( node.isExternal() ) {
549                 getWriter().write( ForesterUtil.LINE_SEPARATOR );
550                 if ( indentation != null ) {
551                     getWriter().write( indentation.toString() );
552                 }
553                 PhylogenyDataUtil.appendOpen( getWriter(), PhyloXmlMapping.CLADE );
554             }
555             if ( indentation != null ) {
556                 PhyloXmlNodeWriter.toPhyloXml( getWriter(), node, getPhyloXmlLevel(), indentation.toString() );
557             }
558             else {
559                 PhyloXmlNodeWriter.toPhyloXml( getWriter(), node, getPhyloXmlLevel(), "" );
560             }
561             if ( node.isExternal() ) {
562                 getWriter().write( ForesterUtil.LINE_SEPARATOR );
563                 if ( indentation != null ) {
564                     getWriter().write( indentation.toString() );
565                 }
566                 PhylogenyDataUtil.appendClose( getWriter(), PhyloXmlMapping.CLADE );
567             }
568         }
569         else if ( getOutputFormt() == FORMAT.NHX ) {
570             getBuffer().append( node.toNewHampshireX() );
571         }
572         else if ( getOutputFormt() == FORMAT.NH ) {
573             getBuffer().append( node.toNewHampshire( isSimpleNH(),
574                                                      isWriteDistanceToParentInNH(),
575                                                      isWriteConfidenceValuesInBracketsInNH() ) );
576         }
577     }
578
579     private boolean isWriteConfidenceValuesInBracketsInNH() {
580         return _write_conf_values_in_branckets_in_nh;
581     }
582
583     private void setWriteConfidenceValuesInBracketsInNH( final boolean write_conf_values_in_branckets_in_nh ) {
584         _write_conf_values_in_branckets_in_nh = write_conf_values_in_branckets_in_nh;
585     }
586
587     private void writeOpenClade( final PhylogenyNode node ) throws IOException {
588         if ( !isSawComma() ) {
589             if ( !node.isRoot() && node.isFirstChildNode() ) {
590                 increaseNodeLevel();
591             }
592             if ( getOutputFormt() == FORMAT.PHYLO_XML ) {
593                 getWriter().write( ForesterUtil.LINE_SEPARATOR );
594                 if ( isIndentPhyloxml() ) {
595                     getWriter().write( createIndentation().toString() );
596                 }
597                 PhylogenyDataUtil.appendOpen( getWriter(), PhyloXmlMapping.CLADE );
598             }
599             else if ( ( getOutputFormt() == FORMAT.NHX ) || ( getOutputFormt() == FORMAT.NH ) ) {
600                 getBuffer().append( "(" );
601             }
602         }
603         setSawComma( false );
604     }
605
606     private void writeOutput( final Writer writer, final Phylogeny tree ) throws IOException {
607         if ( getOutputFormt() != FORMAT.PHYLO_XML ) {
608             throw new RuntimeException( "method inappropriately called" );
609         }
610         if ( tree != null ) {
611             reset( writer, tree );
612             boolean rerootable = true;
613             String unit = "";
614             String type = "";
615             String rooted = "false";
616             if ( tree.isRooted() ) {
617                 rooted = "true";
618             }
619             if ( !tree.isRerootable() ) {
620                 rerootable = false;
621             }
622             if ( !ForesterUtil.isEmpty( tree.getDistanceUnit() ) ) {
623                 unit = tree.getDistanceUnit();
624             }
625             if ( !ForesterUtil.isEmpty( tree.getType() ) ) {
626                 type = tree.getType();
627             }
628             if ( rerootable ) {
629                 PhylogenyDataUtil.appendOpen( writer,
630                                               PhyloXmlMapping.PHYLOGENY,
631                                               PhyloXmlMapping.PHYLOGENY_IS_ROOTED_ATTR,
632                                               rooted,
633                                               PhyloXmlMapping.PHYLOGENY_BRANCHLENGTH_UNIT_ATTR,
634                                               unit,
635                                               PhyloXmlMapping.PHYLOGENY_TYPE_ATTR,
636                                               type );
637             }
638             else {
639                 PhylogenyDataUtil.appendOpen( writer,
640                                               PhyloXmlMapping.PHYLOGENY,
641                                               PhyloXmlMapping.PHYLOGENY_IS_ROOTED_ATTR,
642                                               rooted,
643                                               PhyloXmlMapping.PHYLOGENY_BRANCHLENGTH_UNIT_ATTR,
644                                               unit,
645                                               PhyloXmlMapping.PHYLOGENY_TYPE_ATTR,
646                                               type,
647                                               PhyloXmlMapping.PHYLOGENY_IS_REROOTABLE_ATTR,
648                                               "false" );
649             }
650             appendPhylogenyLevelPhyloXml( writer, tree );
651             while ( isHasNext() ) {
652                 next();
653             }
654             writer.write( ForesterUtil.LINE_SEPARATOR );
655             PhylogenyDataUtil.appendClose( writer, PhyloXmlMapping.PHYLOGENY );
656         }
657     }
658
659     private void writeToFile( final StringBuffer sb, final File out_file ) throws IOException {
660         if ( out_file.exists() ) {
661             throw new IOException( "attempt to overwrite existing file \"" + out_file.getAbsolutePath() + "\"" );
662         }
663         final PrintWriter out = new PrintWriter( new FileWriter( out_file ), true );
664         if ( getOutputFormt() == FORMAT.PHYLO_XML ) {
665             out.print( PHYLO_XML_VERSION_ENCODING_LINE );
666             out.print( ForesterUtil.LINE_SEPARATOR );
667             out.print( PHYLO_XML_NAMESPACE_LINE );
668             out.print( ForesterUtil.LINE_SEPARATOR );
669         }
670         out.print( sb );
671         if ( getOutputFormt() == FORMAT.PHYLO_XML ) {
672             out.print( ForesterUtil.LINE_SEPARATOR );
673             out.print( PHYLO_XML_END );
674         }
675         out.flush();
676         out.close();
677     }
678
679     public static PhylogenyWriter createPhylogenyWriter() {
680         return new PhylogenyWriter();
681     }
682
683     private static void writeNexusStart( final Writer writer ) throws IOException {
684         writer.write( NexusConstants.NEXUS );
685         writer.write( ForesterUtil.LINE_SEPARATOR );
686     }
687
688     public static void writeNexusTaxaBlock( final Writer writer, final Phylogeny tree ) throws IOException {
689         writer.write( NexusConstants.BEGIN_TAXA );
690         writer.write( ForesterUtil.LINE_SEPARATOR );
691         writer.write( " " );
692         writer.write( NexusConstants.DIMENSIONS );
693         writer.write( " " );
694         writer.write( NexusConstants.NTAX );
695         writer.write( "=" );
696         writer.write( String.valueOf( tree.getNumberOfExternalNodes() ) );
697         writer.write( ";" );
698         writer.write( ForesterUtil.LINE_SEPARATOR );
699         writer.write( " " );
700         writer.write( NexusConstants.TAXLABELS );
701         for( final PhylogenyNodeIterator it = tree.iteratorExternalForward(); it.hasNext(); ) {
702             final PhylogenyNode node = it.next();
703             writer.write( " " );
704             String data = "";
705             if ( !ForesterUtil.isEmpty( node.getName() ) ) {
706                 data = node.getName();
707             }
708             else if ( node.getNodeData().isHasTaxonomy() ) {
709                 if ( !ForesterUtil.isEmpty( node.getNodeData().getTaxonomy().getTaxonomyCode() ) ) {
710                     data = node.getNodeData().getTaxonomy().getTaxonomyCode();
711                 }
712                 else if ( !ForesterUtil.isEmpty( node.getNodeData().getTaxonomy().getScientificName() ) ) {
713                     data = node.getNodeData().getTaxonomy().getScientificName();
714                 }
715                 else if ( !ForesterUtil.isEmpty( node.getNodeData().getTaxonomy().getCommonName() ) ) {
716                     data = node.getNodeData().getTaxonomy().getCommonName();
717                 }
718                 else if ( node.getNodeData().getTaxonomy().getTaxonomyCode() != null ) {
719                     data = node.getNodeData().getTaxonomy().getTaxonomyCode();
720                 }
721             }
722             else if ( node.getNodeData().isHasSequence() ) {
723                 if ( !ForesterUtil.isEmpty( node.getNodeData().getSequence().getName() ) ) {
724                     data = node.getNodeData().getSequence().getName();
725                 }
726             }
727             if ( data.length() > 0 ) {
728                 data = data.replaceAll( " ", "_" );
729             }
730             writer.write( data );
731         }
732         writer.write( ";" );
733         writer.write( ForesterUtil.LINE_SEPARATOR );
734         writer.write( NexusConstants.END );
735         writer.write( ForesterUtil.LINE_SEPARATOR );
736     }
737
738     public static void writeNexusTreesBlock( final Writer writer,
739                                              final List<Phylogeny> trees,
740                                              final boolean write_conf_values_in_branckets_in_nh ) throws IOException {
741         writer.write( NexusConstants.BEGIN_TREES );
742         writer.write( ForesterUtil.LINE_SEPARATOR );
743         int i = 1;
744         for( final Phylogeny phylogeny : trees ) {
745             writer.write( " " );
746             writer.write( NexusConstants.TREE );
747             writer.write( " " );
748             if ( !ForesterUtil.isEmpty( phylogeny.getName() ) ) {
749                 writer.write( "\'" );
750                 writer.write( phylogeny.getName() );
751                 writer.write( "\'" );
752             }
753             else {
754                 writer.write( "tree" );
755                 writer.write( String.valueOf( i ) );
756             }
757             writer.write( "=" );
758             if ( phylogeny.isRooted() ) {
759                 writer.write( "[&R]" );
760             }
761             else {
762                 writer.write( "[&U]" );
763             }
764             writer.write( phylogeny.toNewHampshire( false, write_conf_values_in_branckets_in_nh ) );
765             writer.write( ForesterUtil.LINE_SEPARATOR );
766             i++;
767         }
768         writer.write( NexusConstants.END );
769         writer.write( ForesterUtil.LINE_SEPARATOR );
770     }
771
772     private static void writePhyloXmlEnd( final Writer writer ) throws IOException {
773         writer.write( ForesterUtil.LINE_SEPARATOR );
774         writer.write( PhylogenyWriter.PHYLO_XML_END );
775     }
776
777     private static void writePhyloXmlStart( final Writer writer ) throws IOException {
778         writer.write( PhylogenyWriter.PHYLO_XML_VERSION_ENCODING_LINE );
779         writer.write( ForesterUtil.LINE_SEPARATOR );
780         writer.write( PhylogenyWriter.PHYLO_XML_NAMESPACE_LINE );
781         writer.write( ForesterUtil.LINE_SEPARATOR );
782     }
783
784     public static enum FORMAT {
785         NH, NHX, PHYLO_XML, NEXUS;
786     }
787 }