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