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