in progress
[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: www.phylosoft.org/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 = false;
48
49     private NeighborJoining( final boolean verbose ) {
50         _verbose = verbose;
51     }
52
53     private final void calculateDistancesFromNewNode( final int otu1, final int otu2, final double d ) {
54         final int otu1_m = _mappings[ otu1 ];
55         final int otu2_m = _mappings[ otu2 ];
56         int i_m;
57         for( int i = 0; i < _n; ++i ) {
58             if ( ( i == otu1 ) || ( i == otu2 ) ) {
59                 continue;
60             }
61             //  _d_values[ _mappings[ otu1 ] ][ _mappings[ i ] ] = ( getValueFromD( otu1, i ) + getValueFromD( i, otu2 ) - d ) / 2;
62             i_m = _mappings[ i ];
63             _d_values[ otu1_m ][ i_m ] = ( _d_values[ otu1_m ][ i_m ] + _d_values[ i_m ][ otu2_m ] - 2 ) / 2;
64         }
65     }
66
67     private final void calculateNetDivergences() {
68         double d;
69         int i_m;
70         for( int i = 0; i < _n; ++i ) {
71             d = 0;
72             i_m = _mappings[ i ];
73             for( int n = 0; n < _n; ++n ) {
74                 d += _d_values[ i_m ][ _mappings[ n ] ];
75                 //d += getValueFromD( i, n );
76             }
77             _r[ i ] = d;
78         }
79     }
80
81     public final Phylogeny execute( final BasicSymmetricalDistanceMatrix distance ) {
82         reset( distance );
83         final Phylogeny phylogeny = new Phylogeny();
84         while ( _n > 2 ) {
85             updateM();
86             // Calculates the minimal distance.
87             // If more than one minimal distances, always the first found is used
88             // could randomize this, so that any would be returned in a randomized fashion...
89             double minimum = Double.MAX_VALUE;
90             int otu1 = -1;
91             int otu2 = -1;
92             for( int j = 1; j < _n; ++j ) {
93                 for( int i = 0; i < j; ++i ) {
94                     if ( _m_values[ i ][ j ] < minimum ) {
95                         minimum = _m_values[ i ][ j ];
96                         otu1 = i;
97                         otu2 = j;
98                     }
99                 }
100             }
101             // It is a condition that otu1 < otu2.
102             if ( DEBUG ) {
103                 if ( otu1 > otu2 ) {
104                     throw new RuntimeException( "NJ code is faulty: otu1 > otu2" );
105                 }
106             }
107             final PhylogenyNode node = new PhylogenyNode();
108             final double d = getValueFromD( otu1, otu2 );
109             final double d1 = ( d / 2 ) + ( ( _r[ otu1 ] - _r[ otu2 ] ) / ( 2 * ( _n - 2 ) ) );
110             final double d2 = d - d1;
111             getExternalPhylogenyNode( otu1 ).setDistanceToParent( d1 );
112             getExternalPhylogenyNode( otu2 ).setDistanceToParent( d2 );
113             node.addAsChild( getExternalPhylogenyNode( otu1 ) );
114             node.addAsChild( getExternalPhylogenyNode( otu2 ) );
115             if ( _verbose ) {
116                 printProgress( otu1, otu2 );
117             }
118             calculateDistancesFromNewNode( otu1, otu2, d );
119             _external_nodes[ _mappings[ otu1 ] ] = node;
120             updateMappings( otu2 );
121             --_n;
122         }
123         final double d = getValueFromD( 0, 1 ) / 2;
124         getExternalPhylogenyNode( 0 ).setDistanceToParent( d );
125         getExternalPhylogenyNode( 1 ).setDistanceToParent( d );
126         final PhylogenyNode root = new PhylogenyNode();
127         root.addAsChild( getExternalPhylogenyNode( 0 ) );
128         root.addAsChild( getExternalPhylogenyNode( 1 ) );
129         if ( _verbose ) {
130             printProgress( 0, 1 );
131         }
132         phylogeny.setRoot( root );
133         phylogeny.setRooted( false );
134         return phylogeny;
135     }
136
137     public final List<Phylogeny> execute( final List<BasicSymmetricalDistanceMatrix> distances_list ) {
138         final List<Phylogeny> pl = new ArrayList<Phylogeny>();
139         for( final BasicSymmetricalDistanceMatrix distances : distances_list ) {
140             pl.add( execute( distances ) );
141         }
142         return pl;
143     }
144
145     private final PhylogenyNode getExternalPhylogenyNode( final int i ) {
146         return _external_nodes[ _mappings[ i ] ];
147     }
148
149     private final double getValueFromD( final int otu1, final int otu2 ) {
150         return _d_values[ _mappings[ otu1 ] ][ _mappings[ otu2 ] ];
151     }
152
153     private final void initExternalNodes() {
154         _external_nodes = new PhylogenyNode[ _n ];
155         String id;
156         for( int i = 0; i < _n; ++i ) {
157             _external_nodes[ i ] = new PhylogenyNode();
158             id = _d.getIdentifier( i );
159             if ( id != null ) {
160                 _external_nodes[ i ].setName( id );
161             }
162             else {
163                 _external_nodes[ i ].setName( "" + i );
164             }
165             _mappings[ i ] = i;
166         }
167     }
168
169     private final void printProgress( final int otu1, final int otu2 ) {
170         final PhylogenyNode n1 = getExternalPhylogenyNode( otu1 );
171         final PhylogenyNode n2 = getExternalPhylogenyNode( otu2 );
172         System.out.println( "Node " + ( ForesterUtil.isEmpty( n1.getName() ) ? n1.getId() : n1.getName() ) + " joins "
173                 + ( ForesterUtil.isEmpty( n2.getName() ) ? n2.getId() : n2.getName() ) );
174     }
175
176     // only the values in the lower triangle are used.
177     // !matrix values will be changed!
178     private final void reset( final BasicSymmetricalDistanceMatrix distances ) {
179         _n = distances.getSize();
180         _d = distances;
181         _r = new double[ _n ];
182         _mappings = new int[ _n ];
183         _d_values = _d.getValues();
184         _m_values = new double[ _n ][ _n ];
185         initExternalNodes();
186     }
187
188     private final void updateM() {
189         calculateNetDivergences();
190         double r_j;
191         int j_m;
192         final int _n_2 = _n - 2;
193         for( int j = 1; j < _n; ++j ) {
194             r_j = _r[ j ];
195             j_m = _mappings[ j ];
196             for( int i = 0; i < j; ++i ) {
197                 //  _m_values[ i ][ j ] = getValueFromD( i, j ) - ( _r[ i ] + r_j ) / ( _n - 2 );
198                 _m_values[ i ][ j ] = _d_values[ _mappings[ i ] ][ j_m ] - ( _r[ i ] + r_j ) / ( _n_2 );
199             }
200         }
201     }
202
203     // otu2 will, in effect, be "deleted" from the matrix.
204     private final void updateMappings( final int otu2 ) {
205         for( int i = otu2; i < _mappings.length - 1; ++i ) {
206             _mappings[ i ] = _mappings[ i + 1 ];
207         }
208     }
209
210     public final static NeighborJoining createInstance() {
211         return new NeighborJoining( false );
212     }
213
214     public final static NeighborJoining createInstance( final boolean verbose ) {
215         return new NeighborJoining( verbose );
216     }
217 }