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