c0792a4c10289ea56729b0dd09d4c686b1f29c5f
[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) 2014 Christian M. Zmasek
6 // All rights reserved
7 //
8 // This library is free software; you can redistribute it and/or
9 // modify it under the terms of the GNU Lesser General Public
10 // License as published by the Free Software Foundation; either
11 // version 2.1 of the License, or (at your option) any later version.
12 //
13 // This library is distributed in the hope that it will be useful,
14 // but WITHOUT ANY WARRANTY; without even the implied warranty of
15 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 // Lesser General Public License for more details.
17 //
18 // You should have received a copy of the GNU Lesser General Public
19 // License along with this library; if not, write to the Free Software
20 // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
21 //
22 // Contact: phylosoft @ gmail . com
23 // WWW: https://sites.google.com/site/cmzmasek/home/software/forester
24
25 package org.forester.evoinference.distance;
26
27 import java.math.RoundingMode;
28 import java.text.DecimalFormat;
29 import java.util.ArrayList;
30 import java.util.List;
31
32 import org.forester.evoinference.matrix.distance.BasicSymmetricalDistanceMatrix;
33 import org.forester.phylogeny.Phylogeny;
34 import org.forester.phylogeny.PhylogenyNode;
35 import org.forester.util.ForesterUtil;
36
37 public final class NeighborJoining {
38
39     private BasicSymmetricalDistanceMatrix _d;
40     private double[][]                     _d_values;
41     private final DecimalFormat            _df;
42     private PhylogenyNode[]                _external_nodes;
43     private double[][]                     _m_values;
44     private int[]                          _mappings;
45     private int                            _n;
46     private double[]                       _r;
47     private final boolean                  _verbose;
48
49     private NeighborJoining() {
50         _verbose = false;
51         _df = null;
52     }
53
54     private NeighborJoining( final boolean verbose, final int maximum_fraction_digits_for_distances ) {
55         if ( ( maximum_fraction_digits_for_distances < 1 ) || ( maximum_fraction_digits_for_distances > 9 ) ) {
56             throw new IllegalArgumentException( "maximum fraction digits for distances is out of range: "
57                     + maximum_fraction_digits_for_distances );
58         }
59         _verbose = verbose;
60         _df = new DecimalFormat();
61         _df.setMaximumFractionDigits( maximum_fraction_digits_for_distances );
62         _df.setRoundingMode( RoundingMode.HALF_UP );
63     }
64
65     public final Phylogeny execute( final BasicSymmetricalDistanceMatrix distance ) {
66         reset( distance );
67         final Phylogeny phylogeny = new Phylogeny();
68         while ( _n > 2 ) {
69             updateM();
70             // Calculates the minimal distance.
71             // If more than one minimal distances, always the first found is used
72             // could randomize this, so that any would be returned in a randomized fashion...
73             double minimum = _m_values[ 0 ][ 1 ];
74             int otu1 = 0;
75             int otu2 = 1;
76             for( int j = 1; j < _n; ++j ) {
77                 for( int i = 0; i < j; ++i ) {
78                     if ( _m_values[ i ][ j ] < minimum ) {
79                         minimum = _m_values[ i ][ j ];
80                         otu1 = i;
81                         otu2 = j;
82                     }
83                 }
84             }
85             // It is a condition that otu1 < otu2.
86             final PhylogenyNode node = new PhylogenyNode();
87             final double d = _d_values[ _mappings[ otu1 ] ][ _mappings[ otu2 ] ];
88             final double d1 = ( d / 2 ) + ( ( _r[ otu1 ] - _r[ otu2 ] ) / ( 2 * ( _n - 2 ) ) );
89             final double d2 = d - d1;
90             if ( _df == null ) {
91                 getExternalPhylogenyNode( otu1 ).setDistanceToParent( d1 );
92                 getExternalPhylogenyNode( otu2 ).setDistanceToParent( d2 );
93             }
94             else {
95                 // yes, yes, slow but only grows with n (and not n^2 or worse)...
96                 getExternalPhylogenyNode( otu1 ).setDistanceToParent( Double.parseDouble( _df.format( d1 ) ) );
97                 getExternalPhylogenyNode( otu2 ).setDistanceToParent( Double.parseDouble( _df.format( d2 ) ) );
98             }
99             node.addAsChild( getExternalPhylogenyNode( otu1 ) );
100             node.addAsChild( getExternalPhylogenyNode( otu2 ) );
101             if ( _verbose ) {
102                 printProgress( otu1, otu2 );
103             }
104             calculateDistancesFromNewNode( otu1, otu2, d );
105             _external_nodes[ _mappings[ otu1 ] ] = node;
106             updateMappings( otu2 );
107             --_n;
108         }
109         final double d = _d_values[ _mappings[ 0 ] ][ _mappings[ 1 ] ] / 2;
110         if ( _df == null ) {
111             getExternalPhylogenyNode( 0 ).setDistanceToParent( d );
112             getExternalPhylogenyNode( 1 ).setDistanceToParent( d );
113         }
114         else {
115             final double dd = Double.parseDouble( _df.format( d ) );
116             getExternalPhylogenyNode( 0 ).setDistanceToParent( dd );
117             getExternalPhylogenyNode( 1 ).setDistanceToParent( dd );
118         }
119         final PhylogenyNode root = new PhylogenyNode();
120         root.addAsChild( getExternalPhylogenyNode( 0 ) );
121         root.addAsChild( getExternalPhylogenyNode( 1 ) );
122         if ( _verbose ) {
123             printProgress( 0, 1 );
124         }
125         phylogeny.setRoot( root );
126         phylogeny.setRooted( false );
127         return phylogeny;
128     }
129
130     public final List<Phylogeny> execute( final List<BasicSymmetricalDistanceMatrix> distances_list ) {
131         final List<Phylogeny> pl = new ArrayList<Phylogeny>();
132         for( final BasicSymmetricalDistanceMatrix distances : distances_list ) {
133             pl.add( execute( distances ) );
134         }
135         return pl;
136     }
137
138     private final void calculateDistancesFromNewNode( final int otu1, final int otu2, final double d ) {
139         final int m_otu1 = _mappings[ otu1 ];
140         final int m_otu2 = _mappings[ otu2 ];
141         for( int i = 0; i < _n; ++i ) {
142             if ( ( i == otu1 ) || ( i == otu2 ) ) {
143                 continue;
144             }
145             final int m_i = _mappings[ i ];
146             if ( otu1 < i ) {
147                 if ( otu2 > i ) {
148                     _d_values[ m_otu1 ][ m_i ] = ( _d_values[ m_otu1 ][ m_i ] + _d_values[ m_i ][ m_otu2 ] - d ) / 2;
149                 }
150                 else {
151                     _d_values[ m_otu1 ][ m_i ] = ( _d_values[ m_otu1 ][ m_i ] + _d_values[ m_otu2 ][ m_i ] - d ) / 2;
152                 }
153             }
154             else {
155                 if ( otu2 > i ) {
156                     _d_values[ m_i ][ m_otu1 ] = ( _d_values[ m_i ][ m_otu1 ] + _d_values[ m_i ][ m_otu2 ] - d ) / 2;
157                 }
158                 else {
159                     _d_values[ m_i ][ m_otu1 ] = ( _d_values[ m_i ][ m_otu1 ] + _d_values[ m_otu2 ][ m_i ] - d ) / 2;
160                 }
161             }
162         }
163     }
164
165     private final void calculateNetDivergences() {
166         double d;
167         for( int i = 0; i < _n; ++i ) {
168             d = 0;
169             final int m_i = _mappings[ i ];
170             for( int n = 0; n < _n; ++n ) {
171                 if ( i != n ) {
172                     if ( i > n ) {
173                         d += _d_values[ _mappings[ n ] ][ m_i ];
174                     }
175                     else {
176                         d += _d_values[ m_i ][ _mappings[ n ] ];
177                     }
178                 }
179             }
180             _r[ i ] = d;
181         }
182     }
183
184     private final PhylogenyNode getExternalPhylogenyNode( final int i ) {
185         return _external_nodes[ _mappings[ i ] ];
186     }
187
188     private final void initExternalNodes() {
189         _external_nodes = new PhylogenyNode[ _n ];
190         String id;
191         for( int i = 0; i < _n; ++i ) {
192             _external_nodes[ i ] = new PhylogenyNode();
193             id = _d.getIdentifier( i );
194             if ( id != null ) {
195                 _external_nodes[ i ].setName( id );
196             }
197             else {
198                 _external_nodes[ i ].setName( Integer.toString( i ) );
199             }
200             _mappings[ i ] = i;
201         }
202     }
203
204     private final void printProgress( final int otu1, final int otu2 ) {
205         final PhylogenyNode n1 = getExternalPhylogenyNode( otu1 );
206         final PhylogenyNode n2 = getExternalPhylogenyNode( otu2 );
207         System.out.println( "Node " + ( ForesterUtil.isEmpty( n1.getName() ) ? n1.getId() : n1.getName() ) + " joins "
208                 + ( ForesterUtil.isEmpty( n2.getName() ) ? n2.getId() : n2.getName() ) );
209     }
210
211     // only the values in the lower triangle are used.
212     // !matrix values will be changed!
213     private final void reset( final BasicSymmetricalDistanceMatrix distances ) {
214         _n = distances.getSize();
215         _d = distances;
216         _r = new double[ _n ];
217         _mappings = new int[ _n ];
218         _d_values = _d.getValues();
219         _m_values = new double[ _n ][ _n ];
220         initExternalNodes();
221     }
222
223     private final void updateM() {
224         calculateNetDivergences();
225         final int n_minus_2 = _n - 2;
226         for( int j = 1; j < _n; ++j ) {
227             final double r_j = _r[ j ];
228             final int m_j = _mappings[ j ];
229             for( int i = 0; i < j; ++i ) {
230                 _m_values[ i ][ j ] = _d_values[ _mappings[ i ] ][ m_j ] - ( ( _r[ i ] + r_j ) / n_minus_2 );
231             }
232         }
233     }
234
235     // otu2 will, in effect, be "deleted" from the matrix.
236     private final void updateMappings( final int otu2 ) {
237         for( int i = otu2; i < ( _mappings.length - 1 ); ++i ) {
238             _mappings[ i ] = _mappings[ i + 1 ];
239         }
240     }
241
242     public final static NeighborJoining createInstance() {
243         return new NeighborJoining();
244     }
245
246     public final static NeighborJoining createInstance( final boolean verbose,
247                                                         final int maximum_fraction_digits_for_distances ) {
248         return new NeighborJoining( verbose, maximum_fraction_digits_for_distances );
249     }
250 }