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