inprogress
[jalview.git] / forester / java / src / org / forester / evoinference / distance / NeighborJoining.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: https://sites.google.com/site/cmzmasek/home/software/forester
25
26 package org.forester.evoinference.distance;
27
28 import java.math.RoundingMode;
29 import java.text.DecimalFormat;
30 import java.util.ArrayList;
31 import java.util.List;
32
33 import org.forester.evoinference.matrix.distance.BasicSymmetricalDistanceMatrix;
34 import org.forester.phylogeny.Phylogeny;
35 import org.forester.phylogeny.PhylogenyNode;
36 import org.forester.util.ForesterUtil;
37
38 public final class NeighborJoining {
39
40     private BasicSymmetricalDistanceMatrix _d;
41     private double[][]                     _d_values;
42     private double[][]                     _m_values;
43     private double[]                       _r;
44     private int                            _n;
45     private PhylogenyNode[]                _external_nodes;
46     private int[]                          _mappings;
47     private final boolean                  _verbose;
48     private final DecimalFormat            _df;
49
50     private NeighborJoining() {
51         _verbose = false;
52         _df = null;
53     }
54
55     private NeighborJoining( final boolean verbose, final int maximum_fraction_digits_for_distances ) {
56         if ( ( maximum_fraction_digits_for_distances < 1 ) || ( maximum_fraction_digits_for_distances > 9 ) ) {
57             throw new IllegalArgumentException( "maximum fraction digits for distances is out of range: "
58                     + maximum_fraction_digits_for_distances );
59         }
60         _verbose = verbose;
61         _df = new DecimalFormat();
62         _df.setMaximumFractionDigits( maximum_fraction_digits_for_distances );
63         _df.setRoundingMode( RoundingMode.HALF_UP );
64     }
65
66     private final void printM() {
67         System.out.println( "M:" );
68         for( final double[] _m_value : _m_values ) {
69             for( int j = 0; j < _m_values.length; j++ ) {
70                 System.out.print( _m_value[ j ] );
71                 System.out.print( " " );
72             }
73             System.out.println();
74         }
75         System.out.println();
76     }
77
78     private final void printD() {
79         System.out.println( "D:" );
80         for( final double[] _d_value : _d_values ) {
81             for( int j = 0; j < _d_values.length; j++ ) {
82                 System.out.print( _d_value[ j ] );
83                 System.out.print( " " );
84             }
85             System.out.println();
86         }
87         System.out.println();
88     }
89
90     private final void calculateDistancesFromNewNode( final int otu1, final int otu2, final double d ) {
91         // final int otu1_m = _mappings[ otu1 ];
92         // final int otu2_m = _mappings[ otu2 ];
93         //  int i_m;
94         for( int i = 0; i < _n; ++i ) {
95             if ( ( i == otu1 ) || ( i == otu2 ) ) {
96                 continue;
97             }
98             if ( otu1 < i ) {
99                 _d_values[ _mappings[ otu1 ] ][ _mappings[ i ] ] = ( getValueFromD( otu1, i ) + getValueFromD( i, otu2 ) - d ) / 2;
100             }
101             else {
102                 _d_values[ _mappings[ i ] ][ _mappings[ otu1 ] ] = ( getValueFromD( otu1, i ) + getValueFromD( i, otu2 ) - d ) / 2;
103             }
104             //i_m = _mappings[ i ];
105             //_d_values[ otu1_m ][ i_m ] = ( ( _d_values[ otu1_m ][ i_m ] + _d_values[ i_m ][ otu2_m ] ) - 2 ) / 2;
106         }
107     }
108
109     private final void calculateNetDivergences() {
110         double d;
111         //  int i_m;
112         for( int i = 0; i < _n; ++i ) {
113             d = 0;
114             //i_m = _mappings[ i ];
115             for( int n = 0; n < _n; ++n ) {
116                 //d += _d_values[ i_m ][ _mappings[ n ] ];
117                 if ( i != n ) {
118                     d += getValueFromD( i, n );
119                 }
120             }
121             _r[ i ] = d;
122         }
123     }
124
125     public final Phylogeny execute( final BasicSymmetricalDistanceMatrix distance ) {
126         reset( distance );
127         final Phylogeny phylogeny = new Phylogeny();
128         while ( _n > 2 ) {
129             updateM();
130             // Calculates the minimal distance.
131             // If more than one minimal distances, always the first found is used
132             // could randomize this, so that any would be returned in a randomized fashion...
133             double minimum = _m_values[ 0 ][ 1 ];
134             int otu1 = 0;
135             int otu2 = 1;
136             for( int j = 1; j < _n; ++j ) {
137                 for( int i = 0; i < j; ++i ) {
138                     if ( _m_values[ i ][ j ] < minimum ) {
139                         minimum = _m_values[ i ][ j ];
140                         otu1 = i;
141                         otu2 = j;
142                     }
143                 }
144             }
145             // It is a condition that otu1 < otu2.
146             final PhylogenyNode node = new PhylogenyNode();
147             final double d = getValueFromD( otu1, otu2 );
148             final double d1 = ( d / 2 ) + ( ( _r[ otu1 ] - _r[ otu2 ] ) / ( 2 * ( _n - 2 ) ) );
149             final double d2 = d - d1;
150             if ( _df == null ) {
151                 getExternalPhylogenyNode( otu1 ).setDistanceToParent( d1 );
152                 getExternalPhylogenyNode( otu2 ).setDistanceToParent( d2 );
153             }
154             else {
155                 // yes, yes, slow but only grows with n (and not n^2 or worse)...
156                 getExternalPhylogenyNode( otu1 ).setDistanceToParent( Double.parseDouble( _df.format( d1 ) ) );
157                 getExternalPhylogenyNode( otu2 ).setDistanceToParent( Double.parseDouble( _df.format( d2 ) ) );
158             }
159             node.addAsChild( getExternalPhylogenyNode( otu1 ) );
160             node.addAsChild( getExternalPhylogenyNode( otu2 ) );
161             if ( _verbose ) {
162                 printProgress( otu1, otu2 );
163             }
164             calculateDistancesFromNewNode( otu1, otu2, d );
165             _external_nodes[ _mappings[ otu1 ] ] = node;
166             updateMappings( otu2 );
167             --_n;
168         }
169         final double d = getValueFromD( 0, 1 ) / 2;
170         if ( _df == null ) {
171             getExternalPhylogenyNode( 0 ).setDistanceToParent( d );
172             getExternalPhylogenyNode( 1 ).setDistanceToParent( d );
173         }
174         else {
175             final double dd = Double.parseDouble( _df.format( d ) );
176             getExternalPhylogenyNode( 0 ).setDistanceToParent( dd );
177             getExternalPhylogenyNode( 1 ).setDistanceToParent( dd );
178         }
179         final PhylogenyNode root = new PhylogenyNode();
180         root.addAsChild( getExternalPhylogenyNode( 0 ) );
181         root.addAsChild( getExternalPhylogenyNode( 1 ) );
182         if ( _verbose ) {
183             printProgress( 0, 1 );
184         }
185         phylogeny.setRoot( root );
186         phylogeny.setRooted( false );
187         return phylogeny;
188     }
189
190     public final List<Phylogeny> execute( final List<BasicSymmetricalDistanceMatrix> distances_list ) {
191         final List<Phylogeny> pl = new ArrayList<Phylogeny>();
192         for( final BasicSymmetricalDistanceMatrix distances : distances_list ) {
193             pl.add( execute( distances ) );
194         }
195         return pl;
196     }
197
198     private final PhylogenyNode getExternalPhylogenyNode( final int i ) {
199         return _external_nodes[ _mappings[ i ] ];
200     }
201
202     private final double getValueFromD( final int otu1, final int otu2 ) {
203         if ( otu1 > otu2 ) {
204             return _d_values[ _mappings[ otu2 ] ][ _mappings[ otu1 ] ];
205         }
206         return _d_values[ _mappings[ otu1 ] ][ _mappings[ otu2 ] ];
207     }
208
209     private final void initExternalNodes() {
210         _external_nodes = new PhylogenyNode[ _n ];
211         String id;
212         for( int i = 0; i < _n; ++i ) {
213             _external_nodes[ i ] = new PhylogenyNode();
214             id = _d.getIdentifier( i );
215             if ( id != null ) {
216                 _external_nodes[ i ].setName( id );
217             }
218             else {
219                 _external_nodes[ i ].setName( "" + i );
220             }
221             _mappings[ i ] = i;
222         }
223     }
224
225     private final void printProgress( final int otu1, final int otu2 ) {
226         final PhylogenyNode n1 = getExternalPhylogenyNode( otu1 );
227         final PhylogenyNode n2 = getExternalPhylogenyNode( otu2 );
228         System.out.println( "Node " + ( ForesterUtil.isEmpty( n1.getName() ) ? n1.getId() : n1.getName() ) + " joins "
229                 + ( ForesterUtil.isEmpty( n2.getName() ) ? n2.getId() : n2.getName() ) );
230     }
231
232     // only the values in the lower triangle are used.
233     // !matrix values will be changed!
234     private final void reset( final BasicSymmetricalDistanceMatrix distances ) {
235         _n = distances.getSize();
236         _d = distances;
237         _r = new double[ _n ];
238         _mappings = new int[ _n ];
239         _d_values = _d.getValues();
240         _m_values = new double[ _n ][ _n ];
241         initExternalNodes();
242     }
243
244     private final void updateM() {
245         calculateNetDivergences();
246         final double r_j;
247         final int j_m;
248         final int _n_2 = _n - 2;
249         for( int j = 1; j < _n; ++j ) {
250             //r_j = _r[ j ];
251             // j_m = _mappings[ j ];
252             for( int i = 0; i < j; ++i ) {
253                 _m_values[ i ][ j ] = getValueFromD( i, j ) - ( ( _r[ i ] + _r[ j ] ) / ( _n - 2 ) );
254                 //_m_values[ i ][ j ] = _d_values[ _mappings[ i ] ][ j_m ] - ( ( _r[ i ] + r_j ) / ( _n_2 ) );
255             }
256         }
257     }
258
259     // otu2 will, in effect, be "deleted" from the matrix.
260     private final void updateMappings( final int otu2 ) {
261         for( int i = otu2; i < ( _mappings.length - 1 ); ++i ) {
262             _mappings[ i ] = _mappings[ i + 1 ];
263         }
264     }
265
266     public final static NeighborJoining createInstance() {
267         return new NeighborJoining();
268     }
269
270     public final static NeighborJoining createInstance( final boolean verbose,
271                                                         final int maximum_fraction_digits_for_distances ) {
272         return new NeighborJoining( verbose, maximum_fraction_digits_for_distances );
273     }
274 }