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) 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 final static DecimalFormat     DF = new DecimalFormat( "0.00000" );
40     private BasicSymmetricalDistanceMatrix _d;
41     private double[][]                     _d_values;
42     private final DecimalFormat            _df;
43     private PhylogenyNode[]                _external_nodes;
44     private int[]                          _mappings;
45     private int                            _n;
46     private double[]                       _r;
47     private final boolean                  _verbose;
48     private int                            _min_i;
49     private int                            _min_j;
50
51     private NeighborJoining() {
52         _verbose = false;
53         _df = null;
54     }
55
56     private NeighborJoining( final boolean verbose, final int maximum_fraction_digits_for_distances ) {
57         if ( ( maximum_fraction_digits_for_distances < 1 ) || ( maximum_fraction_digits_for_distances > 9 ) ) {
58             throw new IllegalArgumentException( "maximum fraction digits for distances is out of range: "
59                     + maximum_fraction_digits_for_distances );
60         }
61         _verbose = verbose;
62         _df = new DecimalFormat();
63         _df.setMaximumFractionDigits( maximum_fraction_digits_for_distances );
64         _df.setRoundingMode( RoundingMode.HALF_UP );
65     }
66
67     public final Phylogeny execute( final BasicSymmetricalDistanceMatrix distance ) {
68         reset( distance );
69         final Phylogeny phylogeny = new Phylogeny();
70         while ( _n > 2 ) {
71             // Calculates the minimal distance.
72             // If more than one minimal distances, always the first found is used
73             updateM();
74             final int otu1 = _min_i;
75             final int otu2 = _min_j;
76             System.out.println( _min_i + " " + _min_j );
77             // It is a condition that otu1 < otu2.
78             final PhylogenyNode node = new PhylogenyNode();
79             final double d = _d_values[ _mappings[ otu1 ] ][ _mappings[ otu2 ] ];
80             final double d1 = ( d / 2 ) + ( ( _r[ otu1 ] - _r[ otu2 ] ) / ( 2 * ( _n - 2 ) ) );
81             final double d2 = d - d1;
82             if ( _df == null ) {
83                 getExternalPhylogenyNode( otu1 ).setDistanceToParent( d1 );
84                 getExternalPhylogenyNode( otu2 ).setDistanceToParent( d2 );
85             }
86             else {
87                 // yes, yes, slow but only grows with n (and not n^2 or worse)...
88                 getExternalPhylogenyNode( otu1 ).setDistanceToParent( Double.parseDouble( _df.format( d1 ) ) );
89                 getExternalPhylogenyNode( otu2 ).setDistanceToParent( Double.parseDouble( _df.format( d2 ) ) );
90             }
91             node.addAsChild( getExternalPhylogenyNode( otu1 ) );
92             node.addAsChild( getExternalPhylogenyNode( otu2 ) );
93             if ( _verbose ) {
94                 printProgress( otu1, otu2 );
95             }
96             calculateDistancesFromNewNode( otu1, otu2, d );
97             _external_nodes[ _mappings[ otu1 ] ] = node;
98             updateMappings( otu2 );
99             --_n;
100         }
101         final double d = _d_values[ _mappings[ 0 ] ][ _mappings[ 1 ] ] / 2;
102         if ( _df == null ) {
103             getExternalPhylogenyNode( 0 ).setDistanceToParent( d );
104             getExternalPhylogenyNode( 1 ).setDistanceToParent( d );
105         }
106         else {
107             final double dd = Double.parseDouble( _df.format( d ) );
108             getExternalPhylogenyNode( 0 ).setDistanceToParent( dd );
109             getExternalPhylogenyNode( 1 ).setDistanceToParent( dd );
110         }
111         final PhylogenyNode root = new PhylogenyNode();
112         root.addAsChild( getExternalPhylogenyNode( 0 ) );
113         root.addAsChild( getExternalPhylogenyNode( 1 ) );
114         if ( _verbose ) {
115             printProgress( 0, 1 );
116         }
117         phylogeny.setRoot( root );
118         phylogeny.setRooted( false );
119         return phylogeny;
120     }
121
122     public final List<Phylogeny> execute( final List<BasicSymmetricalDistanceMatrix> distances_list ) {
123         final List<Phylogeny> pl = new ArrayList<Phylogeny>();
124         for( final BasicSymmetricalDistanceMatrix distances : distances_list ) {
125             pl.add( execute( distances ) );
126         }
127         return pl;
128     }
129
130     private final void calculateDistancesFromNewNode( final int otu1, final int otu2, final double d ) {
131         final int m_otu1 = _mappings[ otu1 ];
132         final int m_otu2 = _mappings[ otu2 ];
133         for( int i = 0; i < _n; ++i ) {
134             if ( ( i == otu1 ) || ( i == otu2 ) ) {
135                 continue;
136             }
137             final int m_i = _mappings[ i ];
138             if ( otu1 < i ) {
139                 if ( otu2 > i ) {
140                     _d_values[ m_otu1 ][ m_i ] = ( _d_values[ m_otu1 ][ m_i ] + _d_values[ m_i ][ m_otu2 ] - d ) / 2;
141                 }
142                 else {
143                     _d_values[ m_otu1 ][ m_i ] = ( _d_values[ m_otu1 ][ m_i ] + _d_values[ m_otu2 ][ m_i ] - d ) / 2;
144                 }
145             }
146             else {
147                 if ( otu2 > i ) {
148                     _d_values[ m_i ][ m_otu1 ] = ( _d_values[ m_i ][ m_otu1 ] + _d_values[ m_i ][ m_otu2 ] - d ) / 2;
149                 }
150                 else {
151                     _d_values[ m_i ][ m_otu1 ] = ( _d_values[ m_i ][ m_otu1 ] + _d_values[ m_otu2 ][ m_i ] - d ) / 2;
152                 }
153             }
154         }
155     }
156
157     private final void calculateNetDivergences() {
158         double d;
159         for( int i = 0; i < _n; ++i ) {
160             d = 0;
161             final int m_i = _mappings[ i ];
162             for( int n = 0; n < _n; ++n ) {
163                 if ( i != n ) {
164                     if ( i > n ) {
165                         d += _d_values[ _mappings[ n ] ][ m_i ];
166                     }
167                     else {
168                         d += _d_values[ m_i ][ _mappings[ n ] ];
169                     }
170                 }
171             }
172             _r[ i ] = d;
173         }
174     }
175
176     private final PhylogenyNode getExternalPhylogenyNode( final int i ) {
177         return _external_nodes[ _mappings[ i ] ];
178     }
179
180     private final void initExternalNodes() {
181         _external_nodes = new PhylogenyNode[ _n ];
182         String id;
183         for( int i = 0; i < _n; ++i ) {
184             _external_nodes[ i ] = new PhylogenyNode();
185             id = _d.getIdentifier( i );
186             if ( id != null ) {
187                 _external_nodes[ i ].setName( id );
188             }
189             else {
190                 _external_nodes[ i ].setName( Integer.toString( i ) );
191             }
192             _mappings[ i ] = i;
193         }
194     }
195
196     private final void printProgress( final int otu1, final int otu2 ) {
197         System.out.println( "Node " + printProgressNodeToString( getExternalPhylogenyNode( otu1 ) ) + " joins "
198                 + ( printProgressNodeToString( getExternalPhylogenyNode( otu2 ) ) ) );
199     }
200
201     private final String printProgressNodeToString( final PhylogenyNode n ) {
202         if ( n.isExternal() ) {
203             if ( ForesterUtil.isEmpty( n.getName() ) ) {
204                 return Long.toString( n.getId() );
205             }
206             return n.getName();
207         }
208         return n.getId()
209                 + " ("
210                 + ( ForesterUtil.isEmpty( n.getChildNode1().getName() ) ? n.getChildNode1().getId() : n.getChildNode1()
211                         .getName() )
212                 + "+"
213                 + ( ForesterUtil.isEmpty( n.getChildNode2().getName() ) ? n.getChildNode2().getId() : n.getChildNode2()
214                         .getName() ) + ")";
215     }
216
217     // only the values in the lower triangle are used.
218     // !matrix values will be changed!
219     private final void reset( final BasicSymmetricalDistanceMatrix distances ) {
220         _n = distances.getSize();
221         _d = distances;
222         _r = new double[ _n ];
223         _mappings = new int[ _n ];
224         _d_values = _d.getValues();
225         initExternalNodes();
226     }
227
228     private final void updateM() {
229         calculateNetDivergences();
230         Double min = Double.MAX_VALUE;
231         _min_i = -1;
232         _min_j = -1;
233         final int n_minus_2 = _n - 2;
234         for( int j = 1; j < _n; ++j ) {
235             final double r_j = _r[ j ];
236             final int m_j = _mappings[ j ];
237             for( int i = 0; i < j; ++i ) {
238                 final double m = _d_values[ _mappings[ i ] ][ m_j ] - ( ( _r[ i ] + r_j ) / n_minus_2 );
239                 if ( m < min ) {
240                     min = m;
241                     _min_i = i;
242                     _min_j = j;
243                 }
244             }
245         }
246         for( int j = 1; j < _n; ++j ) {
247             final double r_j = _r[ j ];
248             final int m_j = _mappings[ j ];
249             for( int i = 0; i < j; ++i ) {
250                 System.out.print( i );
251                 System.out.print( "->" );
252                 System.out.print( DF.format( _r[ i ] ) );
253                 System.out.print( "  " );
254             }
255             System.out.println();
256         }
257     }
258
259     // otu2 will, in effect, be "deleted" from the matrix.
260     private final void updateMappings( final int otu2 ) {
261         for( int i = otu2; i < ( _mappings.length - 1 ); ++i ) {
262             System.out.print( _mappings[ i ] );
263             _mappings[ i ] = _mappings[ i + 1 ];
264             System.out.println( "----->" + _mappings[ i ] );
265         }
266         for( int i = 0; i < _mappings.length; ++i ) {
267             System.out.println( i + "-->" + _mappings[ i ] );
268         }
269     }
270
271     public final static NeighborJoining createInstance() {
272         return new NeighborJoining();
273     }
274
275     public final static NeighborJoining createInstance( final boolean verbose,
276                                                         final int maximum_fraction_digits_for_distances ) {
277         return new NeighborJoining( verbose, maximum_fraction_digits_for_distances );
278     }
279 }