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