inprogress
[jalview.git] / forester / java / src / org / forester / evoinference / distance / NeighborJoiningR.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 import java.util.Map.Entry;
32 import java.util.SortedSet;
33
34 import org.forester.evoinference.matrix.distance.BasicSymmetricalDistanceMatrix;
35 import org.forester.phylogeny.Phylogeny;
36 import org.forester.phylogeny.PhylogenyNode;
37 import org.forester.util.ForesterUtil;
38
39 public final class NeighborJoiningR {
40
41     private final static DecimalFormat     DF = new DecimalFormat( "0.00" );
42     private BasicSymmetricalDistanceMatrix _d;
43     private double[][]                     _d_values;
44     private final DecimalFormat            _df;
45     private PhylogenyNode[]                _external_nodes;
46     private int[]                          _mappings;
47     private int                            _n;
48     private double[]                       _r;
49     private final boolean                  _verbose;
50     private int                            _min_i;
51     private int                            _min_j;
52     private S                              _s;
53     private double                         _d_min;                          //TODO remove me
54
55     private NeighborJoiningR() {
56         _verbose = false;
57         _df = null;
58     }
59
60     private NeighborJoiningR( final boolean verbose, final int maximum_fraction_digits_for_distances ) {
61         if ( ( maximum_fraction_digits_for_distances < 1 ) || ( maximum_fraction_digits_for_distances > 9 ) ) {
62             throw new IllegalArgumentException( "maximum fraction digits for distances is out of range: "
63                     + maximum_fraction_digits_for_distances );
64         }
65         _verbose = verbose;
66         _df = new DecimalFormat();
67         _df.setMaximumFractionDigits( maximum_fraction_digits_for_distances );
68         _df.setRoundingMode( RoundingMode.HALF_UP );
69     }
70
71     public final Phylogeny execute( final BasicSymmetricalDistanceMatrix distance ) {
72         reset( distance );
73         final Phylogeny phylogeny = new Phylogeny();
74         while ( _n > 2 ) {
75             System.out.println( "N=" + _n );
76             System.out.println();
77             // Calculates the minimal distance.
78             // If more than one minimal distances, always the first found is used
79             final double m = updateM();
80             final int otu1 = _min_i;
81             final int otu2 = _min_j;
82             System.out.println( _min_i + " " + _min_j + " => " + DF.format( m ) + " (" + DF.format( _d_min ) + ")" );
83             // It is a condition that otu1 < otu2.
84             //for( int j = 0; j < _s.size(); ++j ) {
85             _s.removePairing( _d_min, _min_i, 1 );
86             // }
87             final PhylogenyNode node = new PhylogenyNode();
88             final double d = getDvalue( otu1, otu2 );
89             final double d1 = ( d / 2 ) + ( ( _r[ otu1 ] - _r[ otu2 ] ) / ( 2 * ( _n - 2 ) ) );
90             final double d2 = d - d1;
91             if ( _df == null ) {
92                 getExternalPhylogenyNode( otu1 ).setDistanceToParent( d1 );
93                 getExternalPhylogenyNode( otu2 ).setDistanceToParent( d2 );
94             }
95             else {
96                 // yes, yes, slow but only grows with n (and not n^2 or worse)...
97                 getExternalPhylogenyNode( otu1 ).setDistanceToParent( Double.parseDouble( _df.format( d1 ) ) );
98                 getExternalPhylogenyNode( otu2 ).setDistanceToParent( Double.parseDouble( _df.format( d2 ) ) );
99             }
100             node.addAsChild( getExternalPhylogenyNode( otu1 ) );
101             node.addAsChild( getExternalPhylogenyNode( otu2 ) );
102             if ( _verbose ) {
103                 printProgress( otu1, otu2 );
104             }
105             calculateDistancesFromNewNode( otu1, otu2, d );
106             _external_nodes[ _mappings[ otu1 ] ] = node;
107             updateMappings( otu2 );
108             --_n;
109             System.out.println( "-------------------------------------------------------------" );
110             System.out.println( "" );
111         }
112         final double d = getDvalue( 0, 1 ) / 2;
113         if ( _df == null ) {
114             getExternalPhylogenyNode( 0 ).setDistanceToParent( d );
115             getExternalPhylogenyNode( 1 ).setDistanceToParent( d );
116         }
117         else {
118             final double dd = Double.parseDouble( _df.format( d ) );
119             getExternalPhylogenyNode( 0 ).setDistanceToParent( dd );
120             getExternalPhylogenyNode( 1 ).setDistanceToParent( dd );
121         }
122         final PhylogenyNode root = new PhylogenyNode();
123         root.addAsChild( getExternalPhylogenyNode( 0 ) );
124         root.addAsChild( getExternalPhylogenyNode( 1 ) );
125         if ( _verbose ) {
126             printProgress( 0, 1 );
127         }
128         phylogeny.setRoot( root );
129         phylogeny.setRooted( false );
130         return phylogeny;
131     }
132
133     public final List<Phylogeny> execute( final List<BasicSymmetricalDistanceMatrix> distances_list ) {
134         final List<Phylogeny> pl = new ArrayList<Phylogeny>();
135         for( final BasicSymmetricalDistanceMatrix distances : distances_list ) {
136             pl.add( execute( distances ) );
137         }
138         return pl;
139     }
140
141     private final void calculateDistancesFromNewNode( final int otu1, final int otu2, final double d ) {
142         for( int i = 0; i < _n; ++i ) {
143             if ( ( i == otu1 ) || ( i == otu2 ) ) {
144                 continue;
145             }
146             updateDvalue( otu1, otu2, i, d );
147         }
148     }
149
150     private final void updateDvalue( final int otu1, final int otu2, final int i, final double d ) {
151         final double new_d = ( getDvalue( otu1, i ) + getDvalue( i, otu2 ) - d ) / 2;
152         _s.addPairing( new_d, otu1, i );
153         setDvalue( otu1, i, new_d );
154     }
155
156     private void setDvalue( final int i, final int j, final double d ) {
157         if ( i < j ) {
158             _d_values[ _mappings[ i ] ][ _mappings[ j ] ] = d;
159         }
160         _d_values[ _mappings[ j ] ][ _mappings[ i ] ] = d;
161     }
162
163     private double getDvalue( final int i, final int j ) {
164         if ( i < j ) {
165             return _d_values[ _mappings[ i ] ][ _mappings[ j ] ];
166         }
167         return _d_values[ _mappings[ j ] ][ _mappings[ i ] ];
168     }
169
170     private double getDvalueUnmapped( final int i, final int j ) {
171         if ( i < j ) {
172             return _d_values[ i ][ j ];
173         }
174         return _d_values[ j ][ i ];
175     }
176
177     private final void calculateNetDivergences() {
178         for( int i = 0; i < _n; ++i ) {
179             _r[ i ] = calculateNetDivergence( i );
180         }
181     }
182
183     private double calculateNetDivergence( final int i ) {
184         double d = 0;
185         for( int n = 0; n < _n; ++n ) {
186             if ( i != n ) {
187                 d += getDvalue( n, i );
188             }
189         }
190         return d;
191     }
192
193     private final PhylogenyNode getExternalPhylogenyNode( final int i ) {
194         return _external_nodes[ _mappings[ i ] ];
195     }
196
197     private final void initExternalNodes() {
198         _external_nodes = new PhylogenyNode[ _n ];
199         String id;
200         for( int i = 0; i < _n; ++i ) {
201             _external_nodes[ i ] = new PhylogenyNode();
202             id = _d.getIdentifier( i );
203             if ( id != null ) {
204                 _external_nodes[ i ].setName( id );
205             }
206             else {
207                 _external_nodes[ i ].setName( Integer.toString( i ) );
208             }
209             _mappings[ i ] = i;
210         }
211     }
212
213     private final void printProgress( final int otu1, final int otu2 ) {
214         System.out.println( "Node " + printProgressNodeToString( getExternalPhylogenyNode( otu1 ) ) + " joins "
215                 + ( printProgressNodeToString( getExternalPhylogenyNode( otu2 ) ) ) );
216     }
217
218     private final String printProgressNodeToString( final PhylogenyNode n ) {
219         if ( n.isExternal() ) {
220             if ( ForesterUtil.isEmpty( n.getName() ) ) {
221                 return Long.toString( n.getId() );
222             }
223             return n.getName();
224         }
225         return n.getId()
226                 + " ("
227                 + ( ForesterUtil.isEmpty( n.getChildNode1().getName() ) ? n.getChildNode1().getId() : n.getChildNode1()
228                         .getName() )
229                 + "+"
230                 + ( ForesterUtil.isEmpty( n.getChildNode2().getName() ) ? n.getChildNode2().getId() : n.getChildNode2()
231                         .getName() ) + ")";
232     }
233
234     // only the values in the lower triangle are used.
235     // !matrix values will be changed!
236     private final void reset( final BasicSymmetricalDistanceMatrix distances ) {
237         _n = distances.getSize();
238         _d = distances;
239         _r = new double[ _n ];
240         _mappings = new int[ _n ];
241         _d_values = _d.getValues();
242         _s = new S();
243         _s.initialize( distances );
244         initExternalNodes();
245         printM();
246     }
247
248     final private void printM() {
249         for( int j = 1; j < _n; ++j ) {
250             for( int i = 0; i < _n; ++i ) {
251                 System.out.print( DF.format( _d_values[ _mappings[ i ] ][ _mappings[ j ] ] ) );
252                 System.out.print( " " );
253             }
254             System.out.print( "    " );
255             for( final Entry<Integer, SortedSet<Integer>> entry : _s.getSentrySet( _mappings[ j ] ) ) {
256                 final double key = entry.getKey();
257                 final SortedSet<Integer> value = entry.getValue();
258                 System.out.print( DF.format( key / S.FACTOR ) + "=" );
259                 boolean first = true;
260                 for( final Integer v : value ) {
261                     if ( !first ) {
262                         System.out.print( "," );
263                     }
264                     first = false;
265                     System.out.print( v );
266                 }
267                 System.out.print( "  " );
268             }
269             System.out.println();
270         }
271     }
272
273     private final double updateM() {
274         printM();
275         calculateNetDivergences();
276         Double min = Double.MAX_VALUE;
277         _min_i = -1;
278         _min_j = -1;
279         final int n_minus_2 = _n - 2;
280         for( int j = 1; j < _n; ++j ) {
281             final double r_j = _r[ j ];
282             final int m_j = _mappings[ j ];
283             int counter = 0;
284             int counter_all = 0;
285             for( final Entry<Integer, SortedSet<Integer>> entry : _s.getSentrySet( m_j ) ) {
286                 for( final int sorted_i : entry.getValue() ) {
287                     //if ( counter_all >= j ) {
288                     //    break X;
289                     //}
290                     if ( _mappings[ counter ] == counter_all ) {
291                         System.out.print( sorted_i + " " );
292                         System.out.print( "(" + DF.format( getDvalue( sorted_i, j ) ) + ") " );
293                         final double m = getDvalue( sorted_i, j ) - ( ( _r[ sorted_i ] + r_j ) / n_minus_2 );
294                         if ( ( m < min ) && ( sorted_i != j ) ) {
295                             _d_min = getDvalue( sorted_i, j );
296                             min = m;
297                             _min_i = sorted_i;
298                             _min_j = j;
299                         }
300                         ++counter;
301                     }
302                     ++counter_all;
303                 }
304             }
305             System.out.println();
306             /*
307             for( int i = 0; i < j; ++i ) {
308                 final double m = getDvalue( i, j ) - ( ( _r[ i ] + r_j ) / n_minus_2 );
309                 if ( m < min ) {
310                     min = m;
311                     _d_min = getDvalue( i, j );
312                     _min_i = i;
313                     _min_j = j;
314                 }
315             }*/
316         }
317         System.out.println();
318         return min;
319     }
320
321     // otu2 will, in effect, be "deleted" from the matrix.
322     private final void updateMappings( final int otu2 ) {
323         for( int i = otu2; i < ( _mappings.length - 1 ); ++i ) {
324             _mappings[ i ] = _mappings[ i + 1 ];
325         }
326     }
327
328     public final static NeighborJoiningR createInstance() {
329         return new NeighborJoiningR();
330     }
331
332     public final static NeighborJoiningR createInstance( final boolean verbose,
333                                                          final int maximum_fraction_digits_for_distances ) {
334         return new NeighborJoiningR( verbose, maximum_fraction_digits_for_distances );
335     }
336 }