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