82817e93bdb42494d7d1aa572aa062b9d89669c3
[jalview.git] / forester / java / src / org / forester / application / support_transfer.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.application;
27
28 import java.io.File;
29 import java.io.IOException;
30 import java.util.List;
31
32 import org.forester.io.parsers.PhylogenyParser;
33 import org.forester.io.parsers.nhx.NHXParser;
34 import org.forester.io.parsers.util.ParserUtils;
35 import org.forester.io.writers.PhylogenyWriter;
36 import org.forester.phylogeny.Phylogeny;
37 import org.forester.phylogeny.PhylogenyMethods;
38 import org.forester.phylogeny.PhylogenyNode;
39 import org.forester.phylogeny.data.Confidence;
40 import org.forester.phylogeny.factories.ParserBasedPhylogenyFactory;
41 import org.forester.phylogeny.factories.PhylogenyFactory;
42 import org.forester.phylogeny.iterators.PhylogenyNodeIterator;
43
44 public final class support_transfer {
45
46     /**
47      * Transfers branch length values from one Phylogeny to another. It is
48      * mainly a "main method" for method "copyBranchLengthValuesFrom( Phylogeny )"
49      * of org.forester.phylogeny.Phylogeny, to be used in other (Perl) programs.
50      * 
51      * @param args[0]
52      *            Filename (String) for Phylogeny which has correct branch
53      *            length values
54      * @param args[1]
55      *            String Filename (String) for Phylogeny to which the branch
56      *            lengths of the first Phylogeny are to be copied, both Trees
57      *            must only differ in their branch length values, i.e. topology
58      *            and sequence names, etc. must be the same
59      * @param args[2]
60      *            String Filename (String) for outputfile
61      * @param args[3]
62      *            String [number of tree with correct bl to use in case treefile contains more than one, default 0]            
63      
64      */
65     public static void main( final String args[] ) {
66         Phylogeny phylogeny_w_bl = null; // Has correct branch lengths
67         Phylogeny phylogeny_w_support_vals = null; // Has bootsrap in the b.l.
68         // field (will be
69         // transferred
70         // to the bootstrap field by the Phylogeny constructor) or
71         // has regular boostraps (NHX, :B=...).
72         File infile_bl = null;
73         File infile_support_vals = null;
74         File outfile = null;
75         int index_of_tree_w_bl = 0;
76         if ( ( args.length != 3 ) && ( args.length != 4 ) ) {
77             System.err.println( "SupportTransfer: Wrong number" + " of arguments. Usage: \"java transfersBranchLenghts"
78                     + " <treefile with correct b.l.> <treefile with bootstraps>" + "<outputfile> "
79                     + "[number of tree with correct bl to use in case treefile contains more than one, default 0]\"" );
80             System.exit( -1 );
81         }
82         if ( args.length == 4 ) {
83             index_of_tree_w_bl = ( new Integer( args[ 3 ] ) ).intValue();
84         }
85         try {
86             infile_bl = new File( args[ 0 ] );
87             infile_support_vals = new File( args[ 1 ] );
88             outfile = new File( args[ 2 ] );
89             if ( outfile.exists() ) {
90                 System.out.println( "transfersBranchLenghts: " + outfile.getAbsolutePath() + " does already exist." );
91                 System.exit( -1 );
92             }
93             final PhylogenyFactory factory = ParserBasedPhylogenyFactory.getInstance();
94             final PhylogenyParser pp_bl = ParserUtils.createParserDependingOnFileType( infile_bl, true );
95             final PhylogenyParser pp_s = ParserUtils.createParserDependingOnFileType( infile_support_vals, true );
96             if ( pp_bl instanceof NHXParser ) {
97                 ( ( NHXParser ) pp_bl ).setTaxonomyExtraction( PhylogenyMethods.TAXONOMY_EXTRACTION.YES );
98             }
99             phylogeny_w_bl = factory.create( infile_bl, pp_bl )[ index_of_tree_w_bl ];
100             phylogeny_w_support_vals = factory.create( infile_support_vals, pp_s )[ 0 ];
101         }
102         catch ( final IOException e ) {
103             System.out.println( "SupportTransfer: Could not read tree(s): " + e );
104             System.exit( -1 );
105         }
106         try {
107             final double max_bs = PhylogenyMethods.getMaximumConfidenceValue( phylogeny_w_support_vals );
108             PhylogenyMethods.normalizeBootstrapValues( phylogeny_w_support_vals, max_bs, 100 );
109             support_transfer.transferSupportValues( phylogeny_w_support_vals, phylogeny_w_bl );
110         }
111         catch ( final IllegalArgumentException e ) {
112             System.out.println( e.getMessage() );
113             System.exit( -1 );
114         }
115         try {
116             final PhylogenyWriter writer = new PhylogenyWriter();
117             writer.toPhyloXML( outfile, phylogeny_w_bl, 0 );
118         }
119         catch ( final IOException e ) {
120             System.out.println( "Failure to write phylogeny \'" + outfile + "\" [" + e.getMessage() + "]" );
121             System.exit( -1 );
122         }
123     }
124
125     /**
126      * Moves the values in the branch length field to the bootstrap field, for
127      * each PhylogenyNode of this Phylogeny. Converts a Phylogeny originating
128      * from a phylip treefile after bootstrapping and which therefore has its
129      * bootstrap values where the branch lenghts would be.
130      */
131     public final static void moveBranchLengthsToBootstrap( final Phylogeny p ) {
132         for( final PhylogenyNodeIterator iter = p.iteratorPreorder(); iter.hasNext(); ) {
133             final PhylogenyNode node = iter.next();
134             if ( node.isInternal() && ( node.getDistanceToParent() > 0 ) ) {
135                 PhylogenyMethods.setBootstrapConfidence( node, node.getDistanceToParent() );
136             }
137             else {
138                 PhylogenyMethods.setBootstrapConfidence( node, Confidence.CONFIDENCE_DEFAULT_VALUE );
139             }
140             node.setDistanceToParent( PhylogenyNode.DISTANCE_DEFAULT );
141         }
142     } // moveBranchLengthsToBootstrap()
143
144     /**
145      * Modifies Phylogeny to with the support values from Phylogeny from.
146      * Important (but obvious): The topology of both trees needs to be the same.
147      * The method is not robust, and might produce wrong results if the internal
148      * topology differs or if the external node names are not unique.
149      * 
150      * @param from
151      *            the Phylogeny to copy the support values from
152      * @param to
153      *            the Phylogeny to copy the support values to
154      */
155     public final static void transferSupportValues( final Phylogeny from, final Phylogeny to ) {
156         to: for( final PhylogenyNodeIterator it_to = to.iteratorPostorder(); it_to.hasNext(); ) {
157             final PhylogenyNode node_to = it_to.next();
158             if ( !node_to.isExternal() ) {
159                 final List<String> ext_children_to = node_to.getAllExternalDescendantsNames();
160                 for( final PhylogenyNodeIterator it_from = from.iteratorPostorder(); it_from.hasNext(); ) {
161                     final PhylogenyNode node_from = it_from.next();
162                     final List<String> ext_children_from = node_from.getAllExternalDescendantsNames();
163                     if ( ( ext_children_from.size() == ext_children_to.size() )
164                             && ext_children_from.containsAll( ext_children_to ) ) {
165                         PhylogenyMethods.setBootstrapConfidence( node_to,
166                                                                  PhylogenyMethods.getConfidenceValue( node_from ) );
167                         continue to;
168                     }
169                 }
170                 final String message = "Attempt to transfer support values from nonidentical topologies";
171                 throw new IllegalArgumentException( message );
172             }
173         }
174     }
175 }