clean up
[jalview.git] / forester / java / src / org / forester / evoinference / parsimony / FitchParsimony.java
1 // $Id:
2 //
3 // FORESTER -- software libraries and applications
4 // for evolutionary biology research and applications.
5 //
6 // Copyright (C) 2008-2009 Christian M. Zmasek
7 // Copyright (C) 2008-2009 Burnham Institute for Medical Research
8 // All rights reserved
9 //
10 // This library is free software; you can redistribute it and/or
11 // modify it under the terms of the GNU Lesser General Public
12 // License as published by the Free Software Foundation; either
13 // version 2.1 of the License, or (at your option) any later version.
14 //
15 // This library is distributed in the hope that it will be useful,
16 // but WITHOUT ANY WARRANTY; without even the implied warranty of
17 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
18 // Lesser General Public License for more details.
19 //
20 // You should have received a copy of the GNU Lesser General Public
21 // License along with this library; if not, write to the Free Software
22 // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
23 //
24 // Contact: phylosoft @ gmail . com
25 // WWW: www.phylosoft.org/forester
26
27 package org.forester.evoinference.parsimony;
28
29 import java.util.ArrayList;
30 import java.util.HashMap;
31 import java.util.Iterator;
32 import java.util.List;
33 import java.util.Map;
34 import java.util.Random;
35 import java.util.SortedSet;
36 import java.util.TreeSet;
37
38 import org.forester.evoinference.matrix.character.BasicCharacterStateMatrix;
39 import org.forester.evoinference.matrix.character.CharacterStateMatrix;
40 import org.forester.evoinference.matrix.character.CharacterStateMatrix.BinaryStates;
41 import org.forester.evoinference.matrix.character.CharacterStateMatrix.GainLossStates;
42 import org.forester.phylogeny.Phylogeny;
43 import org.forester.phylogeny.PhylogenyNode;
44 import org.forester.phylogeny.iterators.PhylogenyNodeIterator;
45 import org.forester.util.FailedConditionCheckException;
46 import org.forester.util.ForesterUtil;
47
48 public class FitchParsimony<STATE_TYPE> {
49
50     final static private BinaryStates              PRESENT                         = BinaryStates.PRESENT;
51     final static private BinaryStates              ABSENT                          = BinaryStates.ABSENT;
52     final static private GainLossStates            LOSS                            = GainLossStates.LOSS;
53     final static private GainLossStates            GAIN                            = GainLossStates.GAIN;
54     final static private GainLossStates            UNCHANGED_PRESENT               = GainLossStates.UNCHANGED_PRESENT;
55     final static private GainLossStates            UNCHANGED_ABSENT                = GainLossStates.UNCHANGED_ABSENT;
56     private static final boolean                   RETURN_INTERNAL_STATES_DEFAULT  = false;
57     private static final boolean                   RETURN_GAIN_LOSS_MATRIX_DEFAULT = false;
58     private static final boolean                   RANDOMIZE_DEFAULT               = false;
59     private static final long                      RANDOM_NUMBER_SEED_DEFAULT      = 21;
60     private static final boolean                   USE_LAST_DEFAULT                = false;
61     private boolean                                _return_internal_states         = false;
62     private boolean                                _return_gain_loss               = false;
63     private int                                    _total_gains;
64     private int                                    _total_losses;
65     private int                                    _total_unchanged;
66     private CharacterStateMatrix<List<STATE_TYPE>> _internal_states_matrix_prior_to_traceback;
67     private CharacterStateMatrix<STATE_TYPE>       _internal_states_matrix_after_traceback;
68     private CharacterStateMatrix<GainLossStates>   _gain_loss_matrix;
69     private boolean                                _randomize;
70     private boolean                                _use_last;
71     private int                                    _cost;
72     private long                                   _random_number_seed;
73     private Random                                 _random_generator;
74
75     public FitchParsimony() {
76         init();
77     }
78
79     private int determineIndex( final SortedSet<STATE_TYPE> current_node_states, int i ) {
80         if ( isRandomize() ) {
81             i = getRandomGenerator().nextInt( current_node_states.size() );
82         }
83         else if ( isUseLast() ) {
84             i = current_node_states.size() - 1;
85         }
86         return i;
87     }
88
89     public void execute( final Phylogeny p, final CharacterStateMatrix<STATE_TYPE> external_node_states_matrix ) {
90         if ( !p.isRooted() ) {
91             throw new IllegalArgumentException( "attempt to execute Fitch parsimony on unroored phylogeny" );
92         }
93         if ( external_node_states_matrix.isEmpty() ) {
94             throw new IllegalArgumentException( "character matrix is empty" );
95         }
96         if ( external_node_states_matrix.getNumberOfIdentifiers() != p.getNumberOfExternalNodes() ) {
97             throw new IllegalArgumentException( "number of external nodes in phylogeny ["
98                     + p.getNumberOfExternalNodes() + "] and number of indentifiers ["
99                     + external_node_states_matrix.getNumberOfIdentifiers() + "] in matrix are not equal" );
100         }
101         reset();
102         if ( isReturnInternalStates() ) {
103             initializeInternalStates( p, external_node_states_matrix );
104         }
105         if ( isReturnGainLossMatrix() ) {
106             initializeGainLossMatrix( p, external_node_states_matrix );
107         }
108         for( int character_index = 0; character_index < external_node_states_matrix.getNumberOfCharacters(); ++character_index ) {
109             executeForOneCharacter( p,
110                                     getStatesForCharacter( p, external_node_states_matrix, character_index ),
111                                     getStatesForCharacterForTraceback( p, external_node_states_matrix, character_index ),
112                                     character_index );
113         }
114         if ( external_node_states_matrix.getState( 0, 0 ) instanceof BinaryStates ) {
115             if ( ( external_node_states_matrix.getNumberOfCharacters() * p.getNumberOfBranches() ) != ( getTotalGains()
116                     + getTotalLosses() + getTotalUnchanged() ) ) {
117                 throw new FailedConditionCheckException( "this should not have happened: something is deeply wrong with Fitch parsimony implementation" );
118             }
119         }
120     }
121
122     private void executeForOneCharacter( final Phylogeny p,
123                                          final Map<PhylogenyNode, SortedSet<STATE_TYPE>> states,
124                                          final Map<PhylogenyNode, STATE_TYPE> traceback_states,
125                                          final int character_state_column ) {
126         postOrderTraversal( p, states );
127         preOrderTraversal( p, states, traceback_states, character_state_column );
128     }
129
130     public int getCost() {
131         return _cost;
132     }
133
134     public CharacterStateMatrix<CharacterStateMatrix.GainLossStates> getGainLossMatrix() {
135         if ( !isReturnGainLossMatrix() ) {
136             throw new RuntimeException( "creation of gain-loss matrix has not been enabled" );
137         }
138         return _gain_loss_matrix;
139     }
140
141     public CharacterStateMatrix<STATE_TYPE> getInternalStatesMatrix() {
142         if ( !isReturnInternalStates() ) {
143             throw new RuntimeException( "creation of internal state matrix has not been enabled" );
144         }
145         return _internal_states_matrix_after_traceback;
146     }
147
148     /**
149      * Returns a view of the internal states prior to trace-back.
150      * 
151      * @return
152      */
153     public CharacterStateMatrix<List<STATE_TYPE>> getInternalStatesMatrixPriorToTraceback() {
154         if ( !isReturnInternalStates() ) {
155             throw new RuntimeException( "creation of internal state matrix has not been enabled" );
156         }
157         return _internal_states_matrix_prior_to_traceback;
158     }
159
160     private SortedSet<STATE_TYPE> getIntersectionOfStatesOfChildNodes( final Map<PhylogenyNode, SortedSet<STATE_TYPE>> states,
161                                                                        final PhylogenyNode node ) throws AssertionError {
162         final SortedSet<STATE_TYPE> states_in_child_nodes = new TreeSet<STATE_TYPE>();
163         for( int i = 0; i < node.getNumberOfDescendants(); ++i ) {
164             final PhylogenyNode node_child = node.getChildNode( i );
165             if ( !states.containsKey( node_child ) ) {
166                 throw new AssertionError( "this should not have happened: node [" + node_child.getName()
167                         + "] not found in node state map" );
168             }
169             if ( i == 0 ) {
170                 states_in_child_nodes.addAll( states.get( node_child ) );
171             }
172             else {
173                 states_in_child_nodes.retainAll( states.get( node_child ) );
174             }
175         }
176         return states_in_child_nodes;
177     }
178
179     private Random getRandomGenerator() {
180         return _random_generator;
181     }
182
183     private long getRandomNumberSeed() {
184         return _random_number_seed;
185     }
186
187     private STATE_TYPE getStateAt( final int i, final SortedSet<STATE_TYPE> states ) {
188         final Iterator<STATE_TYPE> it = states.iterator();
189         for( int j = 0; j < i; ++j ) {
190             it.next();
191         }
192         return it.next();
193     }
194
195     private Map<PhylogenyNode, SortedSet<STATE_TYPE>> getStatesForCharacter( final Phylogeny p,
196                                                                              final CharacterStateMatrix<STATE_TYPE> matrix,
197                                                                              final int character_index ) {
198         final Map<PhylogenyNode, SortedSet<STATE_TYPE>> states = new HashMap<PhylogenyNode, SortedSet<STATE_TYPE>>( matrix
199                 .getNumberOfIdentifiers() );
200         for( int indentifier_index = 0; indentifier_index < matrix.getNumberOfIdentifiers(); ++indentifier_index ) {
201             final STATE_TYPE state = matrix.getState( indentifier_index, character_index );
202             if ( state == null ) {
203                 throw new IllegalArgumentException( "value at [" + indentifier_index + ", " + character_index
204                         + "] is null" );
205             }
206             final SortedSet<STATE_TYPE> l = new TreeSet<STATE_TYPE>();
207             l.add( state );
208             states.put( p.getNode( matrix.getIdentifier( indentifier_index ) ), l );
209         }
210         return states;
211     }
212
213     private Map<PhylogenyNode, STATE_TYPE> getStatesForCharacterForTraceback( final Phylogeny p,
214                                                                               final CharacterStateMatrix<STATE_TYPE> matrix,
215                                                                               final int character_index ) {
216         final Map<PhylogenyNode, STATE_TYPE> states = new HashMap<PhylogenyNode, STATE_TYPE>( matrix.getNumberOfIdentifiers() );
217         for( int indentifier_index = 0; indentifier_index < matrix.getNumberOfIdentifiers(); ++indentifier_index ) {
218             final STATE_TYPE state = matrix.getState( indentifier_index, character_index );
219             if ( state == null ) {
220                 throw new IllegalArgumentException( "value at [" + indentifier_index + ", " + character_index
221                         + "] is null" );
222             }
223             states.put( p.getNode( matrix.getIdentifier( indentifier_index ) ), state );
224         }
225         return states;
226     }
227
228     public int getTotalGains() {
229         return _total_gains;
230     }
231
232     public int getTotalLosses() {
233         return _total_losses;
234     }
235
236     public int getTotalUnchanged() {
237         return _total_unchanged;
238     }
239
240     private SortedSet<STATE_TYPE> getUnionOfStatesOfChildNodes( final Map<PhylogenyNode, SortedSet<STATE_TYPE>> states,
241                                                                 final PhylogenyNode node ) throws AssertionError {
242         final SortedSet<STATE_TYPE> states_in_child_nodes = new TreeSet<STATE_TYPE>();
243         for( int i = 0; i < node.getNumberOfDescendants(); ++i ) {
244             final PhylogenyNode node_child = node.getChildNode( i );
245             if ( !states.containsKey( node_child ) ) {
246                 throw new AssertionError( "this should not have happened: node [" + node_child.getName()
247                         + "] not found in node state map" );
248             }
249             states_in_child_nodes.addAll( states.get( node_child ) );
250         }
251         return states_in_child_nodes;
252     }
253
254     private void increaseCost() {
255         ++_cost;
256     }
257
258     private void init() {
259         setReturnInternalStates( RETURN_INTERNAL_STATES_DEFAULT );
260         setReturnGainLossMatrix( RETURN_GAIN_LOSS_MATRIX_DEFAULT );
261         setRandomize( RANDOMIZE_DEFAULT );
262         setUseLast( USE_LAST_DEFAULT );
263         _random_number_seed = RANDOM_NUMBER_SEED_DEFAULT;
264         reset();
265     }
266
267     private void initializeGainLossMatrix( final Phylogeny p,
268                                            final CharacterStateMatrix<STATE_TYPE> external_node_states_matrix ) {
269         final List<PhylogenyNode> nodes = new ArrayList<PhylogenyNode>();
270         for( final PhylogenyNodeIterator postorder = p.iteratorPostorder(); postorder.hasNext(); ) {
271             nodes.add( postorder.next() );
272         }
273         setGainLossMatrix( new BasicCharacterStateMatrix<CharacterStateMatrix.GainLossStates>( nodes.size(),
274                                                                                                external_node_states_matrix
275                                                                                                        .getNumberOfCharacters() ) );
276         int identifier_index = 0;
277         for( final PhylogenyNode node : nodes ) {
278             getGainLossMatrix().setIdentifier( identifier_index++,
279                                                ForesterUtil.isEmpty( node.getName() ) ? node.getId() + "" : node
280                                                        .getName() );
281         }
282         for( int character_index = 0; character_index < external_node_states_matrix.getNumberOfCharacters(); ++character_index ) {
283             getGainLossMatrix().setCharacter( character_index,
284                                               external_node_states_matrix.getCharacter( character_index ) );
285         }
286     }
287
288     private void initializeInternalStates( final Phylogeny p,
289                                            final CharacterStateMatrix<STATE_TYPE> external_node_states_matrix ) {
290         final List<PhylogenyNode> internal_nodes = new ArrayList<PhylogenyNode>();
291         for( final PhylogenyNodeIterator postorder = p.iteratorPostorder(); postorder.hasNext(); ) {
292             final PhylogenyNode node = postorder.next();
293             if ( node.isInternal() ) {
294                 internal_nodes.add( node );
295             }
296         }
297         setInternalStatesMatrixPriorToTraceback( new BasicCharacterStateMatrix<List<STATE_TYPE>>( internal_nodes.size(),
298                                                                                                   external_node_states_matrix
299                                                                                                           .getNumberOfCharacters() ) );
300         setInternalStatesMatrixTraceback( new BasicCharacterStateMatrix<STATE_TYPE>( internal_nodes.size(),
301                                                                                      external_node_states_matrix
302                                                                                              .getNumberOfCharacters() ) );
303         int identifier_index = 0;
304         for( final PhylogenyNode node : internal_nodes ) {
305             getInternalStatesMatrix().setIdentifier( identifier_index,
306                                                      ForesterUtil.isEmpty( node.getName() ) ? node.getId() + "" : node
307                                                              .getName() );
308             getInternalStatesMatrixPriorToTraceback().setIdentifier( identifier_index,
309                                                                      ForesterUtil.isEmpty( node.getName() ) ? node
310                                                                              .getId() + "" : node.getName() );
311             ++identifier_index;
312         }
313         for( int character_index = 0; character_index < external_node_states_matrix.getNumberOfCharacters(); ++character_index ) {
314             getInternalStatesMatrix().setCharacter( character_index,
315                                                     external_node_states_matrix.getCharacter( character_index ) );
316             getInternalStatesMatrixPriorToTraceback().setCharacter( character_index,
317                                                                     external_node_states_matrix
318                                                                             .getCharacter( character_index ) );
319         }
320     }
321
322     private boolean isRandomize() {
323         return _randomize;
324     }
325
326     private boolean isReturnGainLossMatrix() {
327         return _return_gain_loss;
328     }
329
330     private boolean isReturnInternalStates() {
331         return _return_internal_states;
332     }
333
334     private boolean isUseLast() {
335         return _use_last;
336     }
337
338     private void postOrderTraversal( final Phylogeny p, final Map<PhylogenyNode, SortedSet<STATE_TYPE>> states )
339             throws AssertionError {
340         for( final PhylogenyNodeIterator postorder = p.iteratorPostorder(); postorder.hasNext(); ) {
341             final PhylogenyNode node = postorder.next();
342             if ( !node.isExternal() ) {
343                 SortedSet<STATE_TYPE> states_in_children = getIntersectionOfStatesOfChildNodes( states, node );
344                 if ( states_in_children.isEmpty() ) {
345                     states_in_children = getUnionOfStatesOfChildNodes( states, node );
346                 }
347                 states.put( node, states_in_children );
348             }
349         }
350     }
351
352     private void preOrderTraversal( final Phylogeny p,
353                                     final Map<PhylogenyNode, SortedSet<STATE_TYPE>> states,
354                                     final Map<PhylogenyNode, STATE_TYPE> traceback_states,
355                                     final int character_state_column ) throws AssertionError {
356         for( final PhylogenyNodeIterator preorder = p.iteratorPreorder(); preorder.hasNext(); ) {
357             final PhylogenyNode current_node = preorder.next();
358             final SortedSet<STATE_TYPE> current_node_states = states.get( current_node );
359             STATE_TYPE parent_state = null;
360             if ( current_node.isRoot() ) {
361                 int i = 0;
362                 i = determineIndex( current_node_states, i );
363                 traceback_states.put( current_node, getStateAt( i, current_node_states ) );
364             }
365             else {
366                 parent_state = traceback_states.get( current_node.getParent() );
367                 if ( current_node_states.contains( parent_state ) ) {
368                     traceback_states.put( current_node, parent_state );
369                 }
370                 else {
371                     increaseCost();
372                     int i = 0;
373                     i = determineIndex( current_node_states, i );
374                     traceback_states.put( current_node, getStateAt( i, current_node_states ) );
375                 }
376             }
377             if ( isReturnInternalStates() ) {
378                 if ( !current_node.isExternal() ) {
379                     setInternalNodeStatePriorToTraceback( states, character_state_column, current_node );
380                     setInternalNodeState( traceback_states, character_state_column, current_node );
381                 }
382             }
383             if ( isReturnGainLossMatrix() && !current_node.isRoot() ) {
384                 if ( !( parent_state instanceof BinaryStates ) ) {
385                     throw new RuntimeException( "attempt to create gain loss matrix for not binary states" );
386                 }
387                 final BinaryStates parent_binary_state = ( BinaryStates ) parent_state;
388                 final BinaryStates current_binary_state = ( BinaryStates ) traceback_states.get( current_node );
389                 if ( ( parent_binary_state == PRESENT ) && ( current_binary_state == ABSENT ) ) {
390                     ++_total_losses;
391                     setGainLossState( character_state_column, current_node, LOSS );
392                 }
393                 else if ( ( ( parent_binary_state == ABSENT ) || ( parent_binary_state == null ) )
394                         && ( current_binary_state == PRESENT ) ) {
395                     ++_total_gains;
396                     setGainLossState( character_state_column, current_node, GAIN );
397                 }
398                 else {
399                     ++_total_unchanged;
400                     if ( current_binary_state == PRESENT ) {
401                         setGainLossState( character_state_column, current_node, UNCHANGED_PRESENT );
402                     }
403                     else if ( current_binary_state == ABSENT ) {
404                         setGainLossState( character_state_column, current_node, UNCHANGED_ABSENT );
405                     }
406                 }
407             }
408             else if ( isReturnGainLossMatrix() && current_node.isRoot() ) {
409                 final BinaryStates current_binary_state = ( BinaryStates ) traceback_states.get( current_node );
410                 ++_total_unchanged; //new
411                 if ( current_binary_state == PRESENT ) {//new
412                     setGainLossState( character_state_column, current_node, UNCHANGED_PRESENT );//new
413                 }//new
414                 else if ( current_binary_state == ABSENT ) {//new
415                     setGainLossState( character_state_column, current_node, UNCHANGED_ABSENT );//new
416                 }//new
417                  // setGainLossState( character_state_column, current_node, UNKNOWN_GAIN_LOSS );
418             }
419         }
420     }
421
422     private void reset() {
423         setCost( 0 );
424         setTotalLosses( 0 );
425         setTotalGains( 0 );
426         setTotalUnchanged( 0 );
427         setRandomGenerator( new Random( getRandomNumberSeed() ) );
428     }
429
430     private void setCost( final int cost ) {
431         _cost = cost;
432     }
433
434     private void setGainLossMatrix( final CharacterStateMatrix<GainLossStates> gain_loss_matrix ) {
435         _gain_loss_matrix = gain_loss_matrix;
436     }
437
438     private void setGainLossState( final int character_state_column,
439                                    final PhylogenyNode node,
440                                    final GainLossStates state ) {
441         getGainLossMatrix().setState( ForesterUtil.isEmpty( node.getName() ) ? node.getId() + "" : node.getName(),
442                                       character_state_column,
443                                       state );
444     }
445
446     private void setInternalNodeState( final Map<PhylogenyNode, STATE_TYPE> states,
447                                        final int character_state_column,
448                                        final PhylogenyNode node ) {
449         getInternalStatesMatrix()
450                 .setState( ForesterUtil.isEmpty( node.getName() ) ? node.getId() + "" : node.getName(),
451                            character_state_column,
452                            states.get( node ) );
453     }
454
455     private void setInternalNodeStatePriorToTraceback( final Map<PhylogenyNode, SortedSet<STATE_TYPE>> states,
456                                                        final int character_state_column,
457                                                        final PhylogenyNode node ) {
458         getInternalStatesMatrixPriorToTraceback().setState( ForesterUtil.isEmpty( node.getName() ) ? node.getId() + ""
459                                                                     : node.getName(),
460                                                             character_state_column,
461                                                             toListSorted( states.get( node ) ) );
462     }
463
464     private void setInternalStatesMatrixPriorToTraceback( final CharacterStateMatrix<List<STATE_TYPE>> internal_states_matrix_prior_to_traceback ) {
465         _internal_states_matrix_prior_to_traceback = internal_states_matrix_prior_to_traceback;
466     }
467
468     private void setInternalStatesMatrixTraceback( final CharacterStateMatrix<STATE_TYPE> internal_states_matrix_after_traceback ) {
469         _internal_states_matrix_after_traceback = internal_states_matrix_after_traceback;
470     }
471
472     private void setRandomGenerator( final Random random_generator ) {
473         _random_generator = random_generator;
474     }
475
476     public void setRandomize( final boolean randomize ) {
477         if ( randomize && isUseLast() ) {
478             throw new IllegalArgumentException( "attempt to allways use last state (ordered) if more than one choices and randomization at the same time" );
479         }
480         _randomize = randomize;
481     }
482
483     public void setRandomNumberSeed( final long random_number_seed ) {
484         if ( !isRandomize() ) {
485             throw new IllegalArgumentException( "attempt to set random number generator seed without randomization enabled" );
486         }
487         _random_number_seed = random_number_seed;
488     }
489
490     public void setReturnGainLossMatrix( final boolean return_gain_loss ) {
491         _return_gain_loss = return_gain_loss;
492     }
493
494     public void setReturnInternalStates( final boolean return_internal_states ) {
495         _return_internal_states = return_internal_states;
496     }
497
498     private void setTotalGains( final int total_gains ) {
499         _total_gains = total_gains;
500     }
501
502     private void setTotalLosses( final int total_losses ) {
503         _total_losses = total_losses;
504     }
505
506     private void setTotalUnchanged( final int total_unchanged ) {
507         _total_unchanged = total_unchanged;
508     }
509
510     /**
511      * This sets whether to use the first or last state in the sorted
512      * states at the undecided internal nodes.
513      * For randomized choices set randomize to true (and this to false).
514      * 
515      * Note. It might be advisable to set this to false
516      * for BinaryStates if absence at the root is preferred
517      * (given the enum BinaryStates sorts in the following order: 
518      * ABSENT, UNKNOWN, PRESENT).
519      * 
520      * 
521      * @param use_last
522      */
523     public void setUseLast( final boolean use_last ) {
524         if ( use_last && isRandomize() ) {
525             throw new IllegalArgumentException( "attempt to allways use last state (ordered) if more than one choices and randomization at the same time" );
526         }
527         _use_last = use_last;
528     }
529
530     private List<STATE_TYPE> toListSorted( final SortedSet<STATE_TYPE> states ) {
531         final List<STATE_TYPE> l = new ArrayList<STATE_TYPE>( states.size() );
532         for( final STATE_TYPE state : states ) {
533             l.add( state );
534         }
535         return l;
536     }
537 }