2a851b5364691ebc6f13a6f78b3683a7235ed8fa
[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             final PhylogenyNode node = new PhylogenyNode();
85             final double d = getDvalue( otu1, otu2 );
86             final double d1 = ( d / 2 ) + ( ( _r[ otu1 ] - _r[ otu2 ] ) / ( 2 * ( _n - 2 ) ) );
87             final double d2 = d - d1;
88             if ( _df == null ) {
89                 getExternalPhylogenyNode( otu1 ).setDistanceToParent( d1 );
90                 getExternalPhylogenyNode( otu2 ).setDistanceToParent( d2 );
91             }
92             else {
93                 // yes, yes, slow but only grows with n (and not n^2 or worse)...
94                 getExternalPhylogenyNode( otu1 ).setDistanceToParent( Double.parseDouble( _df.format( d1 ) ) );
95                 getExternalPhylogenyNode( otu2 ).setDistanceToParent( Double.parseDouble( _df.format( d2 ) ) );
96             }
97             node.addAsChild( getExternalPhylogenyNode( otu1 ) );
98             node.addAsChild( getExternalPhylogenyNode( otu2 ) );
99             if ( _verbose ) {
100                 printProgress( otu1, otu2 );
101             }
102             calculateDistancesFromNewNode( otu1, otu2, d );
103             _external_nodes[ _mappings[ otu1 ] ] = node;
104             updateMappings( otu2 );
105             --_n;
106             System.out.println( "-------------------------------------------------------------" );
107             System.out.println( "" );
108         }
109         final double d = getDvalue( 0, 1 ) / 2;
110         if ( _df == null ) {
111             getExternalPhylogenyNode( 0 ).setDistanceToParent( d );
112             getExternalPhylogenyNode( 1 ).setDistanceToParent( d );
113         }
114         else {
115             final double dd = Double.parseDouble( _df.format( d ) );
116             getExternalPhylogenyNode( 0 ).setDistanceToParent( dd );
117             getExternalPhylogenyNode( 1 ).setDistanceToParent( dd );
118         }
119         final PhylogenyNode root = new PhylogenyNode();
120         root.addAsChild( getExternalPhylogenyNode( 0 ) );
121         root.addAsChild( getExternalPhylogenyNode( 1 ) );
122         if ( _verbose ) {
123             printProgress( 0, 1 );
124         }
125         phylogeny.setRoot( root );
126         phylogeny.setRooted( false );
127         return phylogeny;
128     }
129
130     public final List<Phylogeny> execute( final List<BasicSymmetricalDistanceMatrix> distances_list ) {
131         final List<Phylogeny> pl = new ArrayList<Phylogeny>();
132         for( final BasicSymmetricalDistanceMatrix distances : distances_list ) {
133             pl.add( execute( distances ) );
134         }
135         return pl;
136     }
137
138     private final void calculateDistancesFromNewNode( final int otu1, final int otu2, final double d ) {
139         for( int i = 0; i < _n; ++i ) {
140             if ( ( i == otu1 ) || ( i == otu2 ) ) {
141                 continue;
142             }
143             updateDvalue( otu1, otu2, i, d );
144         }
145     }
146
147     private final void updateDvalue( final int otu1, final int otu2, final int i, final double d ) {
148         setDvalue( otu1, i, ( getDvalue( otu1, i ) + getDvalue( i, otu2 ) - d ) / 2 );
149     }
150
151     private void setDvalue( final int i, final int j, final double d ) {
152         if ( i < j ) {
153             _d_values[ _mappings[ i ] ][ _mappings[ j ] ] = d;
154         }
155         _d_values[ _mappings[ j ] ][ _mappings[ i ] ] = d;
156     }
157
158     private double getDvalue( final int i, final int j ) {
159         if ( i < j ) {
160             return _d_values[ _mappings[ i ] ][ _mappings[ j ] ];
161         }
162         return _d_values[ _mappings[ j ] ][ _mappings[ i ] ];
163     }
164
165     private double getDvalueUnmapped( final int i, final int j ) {
166         if ( i < j ) {
167             return _d_values[ i ][ j ];
168         }
169         return _d_values[ j ][ i ];
170     }
171
172     private final void calculateNetDivergences() {
173         for( int i = 0; i < _n; ++i ) {
174             _r[ i ] = calculateNetDivergence( i );
175         }
176     }
177
178     private double calculateNetDivergence( final int i ) {
179         double d = 0;
180         for( int n = 0; n < _n; ++n ) {
181             if ( i != n ) {
182                 d += getDvalue( n, i );
183             }
184         }
185         return d;
186     }
187
188     private final PhylogenyNode getExternalPhylogenyNode( final int i ) {
189         return _external_nodes[ _mappings[ i ] ];
190     }
191
192     private final void initExternalNodes() {
193         _external_nodes = new PhylogenyNode[ _n ];
194         String id;
195         for( int i = 0; i < _n; ++i ) {
196             _external_nodes[ i ] = new PhylogenyNode();
197             id = _d.getIdentifier( i );
198             if ( id != null ) {
199                 _external_nodes[ i ].setName( id );
200             }
201             else {
202                 _external_nodes[ i ].setName( Integer.toString( i ) );
203             }
204             _mappings[ i ] = i;
205         }
206     }
207
208     private final void printProgress( final int otu1, final int otu2 ) {
209         System.out.println( "Node " + printProgressNodeToString( getExternalPhylogenyNode( otu1 ) ) + " joins "
210                 + ( printProgressNodeToString( getExternalPhylogenyNode( otu2 ) ) ) );
211     }
212
213     private final String printProgressNodeToString( final PhylogenyNode n ) {
214         if ( n.isExternal() ) {
215             if ( ForesterUtil.isEmpty( n.getName() ) ) {
216                 return Long.toString( n.getId() );
217             }
218             return n.getName();
219         }
220         return n.getId()
221                 + " ("
222                 + ( ForesterUtil.isEmpty( n.getChildNode1().getName() ) ? n.getChildNode1().getId() : n.getChildNode1()
223                         .getName() )
224                 + "+"
225                 + ( ForesterUtil.isEmpty( n.getChildNode2().getName() ) ? n.getChildNode2().getId() : n.getChildNode2()
226                         .getName() ) + ")";
227     }
228
229     // only the values in the lower triangle are used.
230     // !matrix values will be changed!
231     private final void reset( final BasicSymmetricalDistanceMatrix distances ) {
232         _n = distances.getSize();
233         _d = distances;
234         _r = new double[ _n ];
235         _mappings = new int[ _n ];
236         _d_values = _d.getValues();
237         _s = new S();
238         _s.initialize( distances );
239         initExternalNodes();
240         printM();
241     }
242
243     final private void printM() {
244         for( int j = 1; j < _n; ++j ) {
245             for( int i = 0; i < _n; ++i ) {
246                 System.out.print( DF.format( _d_values[ _mappings[ i ] ][ _mappings[ j ] ] ) );
247                 System.out.print( " " );
248             }
249             System.out.print( "    " );
250             for( final Entry<Double, SortedSet<Integer>> entry : _s.getSentrySet( _mappings[ j ] ) ) {
251                 final double key = entry.getKey();
252                 final SortedSet<Integer> value = entry.getValue();
253                 System.out.print( DF.format( key ) + "=" );
254                 boolean first = true;
255                 for( final Integer v : value ) {
256                     if ( !first ) {
257                         System.out.print( "," );
258                     }
259                     first = false;
260                     System.out.print( v );
261                 }
262                 System.out.print( "  " );
263             }
264             System.out.println();
265         }
266     }
267
268     private final double updateM() {
269         printM();
270         calculateNetDivergences();
271         Double min = Double.MAX_VALUE;
272         _min_i = -1;
273         _min_j = -1;
274         final int n_minus_2 = _n - 2;
275         for( int j = 1; j < _n; ++j ) {
276             final double r_j = _r[ j ];
277             final int m_j = _mappings[ j ];
278             int counter = 0;
279             int counter_all = 0;
280             X: for( final Entry<Double, SortedSet<Integer>> entry : _s.getSentrySet( m_j ) ) {
281                 for( final int sorted_i : entry.getValue() ) {
282                     //if ( counter_all >= j ) {
283                     //    break X;
284                     //}
285                     if ( _mappings[ counter ] == counter_all ) {
286                         System.out.print( sorted_i + " " );
287                         System.out.print( "(" + DF.format( getDvalueUnmapped( sorted_i, m_j ) ) + ") " );
288                         final double m = getDvalueUnmapped( sorted_i, m_j ) - ( ( _r[ sorted_i ] + r_j ) / n_minus_2 );
289                         if ( m < min ) {
290                             _d_min = getDvalueUnmapped( sorted_i, m_j );
291                             min = m;
292                             _min_i = sorted_i;
293                             _min_j = j;
294                         }
295                         ++counter;
296                     }
297                     ++counter_all;
298                 }
299             }
300             System.out.println();
301             /*
302             for( int i = 0; i < j; ++i ) {
303                 final double m = getDvalue( i, j ) - ( ( _r[ i ] + r_j ) / n_minus_2 );
304                 if ( m < min ) {
305                     min = m;
306                     _d_min = getDvalue( i, j );
307                     _min_i = i;
308                     _min_j = j;
309                 }
310             }*/
311         }
312         System.out.println();
313         return min;
314     }
315
316     // otu2 will, in effect, be "deleted" from the matrix.
317     private final void updateMappings( final int otu2 ) {
318         for( int i = otu2; i < ( _mappings.length - 1 ); ++i ) {
319             _mappings[ i ] = _mappings[ i + 1 ];
320         }
321     }
322
323     public final static NeighborJoiningR createInstance() {
324         return new NeighborJoiningR();
325     }
326
327     public final static NeighborJoiningR createInstance( final boolean verbose,
328                                                          final int maximum_fraction_digits_for_distances ) {
329         return new NeighborJoiningR( verbose, maximum_fraction_digits_for_distances );
330     }
331 }