"rio" work
[jalview.git] / forester / java / src / org / forester / rio / RIO.java
1 // $Id:
2 // FORESTER -- software libraries and applications
3 // for evolutionary biology research and applications.
4 //
5 // Copyright (C) 2008-2009 Christian M. Zmasek
6 // Copyright (C) 2008-2009 Burnham Institute for Medical Research
7 // Copyright (C) 2000-2001 Washington University School of Medicine
8 // and Howard Hughes Medical Institute
9 // All rights reserved
10 //
11 // This library is free software; you can redistribute it and/or
12 // modify it under the terms of the GNU Lesser General Public
13 // License as published by the Free Software Foundation; either
14 // version 2.1 of the License, or (at your option) any later version.
15 //
16 // This library is distributed in the hope that it will be useful,
17 // but WITHOUT ANY WARRANTY; without even the implied warranty of
18 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
19 // Lesser General Public License for more details.
20 //
21 // You should have received a copy of the GNU Lesser General Public
22 // License along with this library; if not, write to the Free Software
23 // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
24 //
25 // Contact: phylosoft @ gmail . com
26 // WWW: www.phylosoft.org/forester
27
28 package org.forester.rio;
29
30 import java.io.File;
31 import java.io.FileNotFoundException;
32 import java.io.IOException;
33 import java.util.ArrayList;
34 import java.util.Arrays;
35 import java.util.Collections;
36 import java.util.HashMap;
37 import java.util.HashSet;
38 import java.util.List;
39 import java.util.Set;
40
41 import org.forester.datastructures.IntMatrix;
42 import org.forester.io.parsers.PhylogenyParser;
43 import org.forester.io.parsers.nhx.NHXParser;
44 import org.forester.io.parsers.util.ParserUtils;
45 import org.forester.phylogeny.Phylogeny;
46 import org.forester.phylogeny.PhylogenyMethods;
47 import org.forester.phylogeny.PhylogenyNode;
48 import org.forester.phylogeny.factories.ParserBasedPhylogenyFactory;
49 import org.forester.phylogeny.factories.PhylogenyFactory;
50 import org.forester.phylogeny.iterators.PhylogenyNodeIterator;
51 import org.forester.sdi.GSDIR;
52 import org.forester.sdi.SDI;
53 import org.forester.sdi.SDIException;
54 import org.forester.sdi.SDIR;
55 import org.forester.util.ForesterUtil;
56
57 public final class RIO {
58
59     private final static boolean                      ROOT_BY_MINIMIZING_SUM_OF_DUPS = true;
60     private final static boolean                      ROOT_BY_MINIMIZING_TREE_HEIGHT = true;
61     private Phylogeny[]                               _analyzed_gene_trees;
62     private HashMap<String, HashMap<String, Integer>> _o_maps;
63     private HashMap<String, HashMap<String, Integer>> _so_maps;
64     private HashMap<String, HashMap<String, Integer>> _up_maps;
65     private List<String>                              _seq_names;
66     private List<PhylogenyNode>                       _removed_gene_tree_nodes;
67     private int                                       _samples;
68     private int                                       _ext_nodes;
69
70     /**
71      * Default constructor.
72      * @throws SDIException 
73      * @throws IOException 
74      * @throws RIOException 
75      */
76     public RIO( final File gene_trees_file,
77                 final Phylogeny species_tree,
78                 final String query,
79                 final SDI.ALGORITHM algorithm ) throws IOException, SDIException, RIOException {
80         if ( ForesterUtil.isEmpty( query ) ) {
81             throw new IllegalArgumentException( "query is empty" );
82         }
83         init();
84         inferOrthologs( gene_trees_file, species_tree, query, algorithm );
85     }
86
87     public RIO( final File gene_trees_file, final Phylogeny species_tree, final SDI.ALGORITHM algorithm )
88             throws IOException, SDIException, RIOException {
89         init();
90         inferOrthologs( gene_trees_file, species_tree, null, algorithm );
91     }
92
93     public final Phylogeny[] getAnalyzedGeneTrees() {
94         return _analyzed_gene_trees;
95     }
96
97     /**
98      * Returns the numbers of number of ext nodes in gene trees analyzed (after
99      * stripping).
100      * 
101      * @return number of ext nodes in gene trees analyzed (after stripping)
102      */
103     public final int getExtNodesOfAnalyzedGeneTrees() {
104         return _ext_nodes;
105     }
106
107     /**
108      * Returns a HashMap containing the inferred "ultra paralogs" of the
109      * external gene tree node with the sequence name seq_name. Sequence names
110      * are the keys (String), numbers of observations are the values (Int).
111      * "ultra paralogs" are to be inferred by method "inferOrthologs". Throws an
112      * exception if seq_name is not found. 
113      * 
114      * @param seq_name
115      *            sequence name of a external node of the gene trees
116      * @return HashMap containing the inferred ultra paralogs
117      *         (name(String)->value(Int))
118      */
119     public final HashMap<String, Integer> getInferredUltraParalogs( final String seq_name ) {
120         if ( _up_maps == null ) {
121             return null;
122         }
123         return _up_maps.get( seq_name );
124     }
125
126     public final int getNumberOfSamples() {
127         return _samples;
128     }
129
130     /**
131      * Returns a String containg the names of orthologs of the PhylogenyNode
132      * with seq name query_name. The String also contains how many times a
133      * particular ortholog has been observed.
134      * <p>
135      * <ul>
136      * The output order is (per line): Name, Ortholog, Subtree neighbor, Super
137      * ortholog, Distance
138      * </ul>
139      * <p>
140      * The sort priority of this is determined by sort in the following manner:
141      * <ul>
142      * <li>0 : Ortholog
143      * <li>1 : Ortholog, Super ortholog
144      * <li>2 : Super ortholog, Ortholog
145      * </ul>
146      * <p>
147      * Returns "-" if no putative orthologs have been found (given
148      * threshold_orthologs).
149      * <p>
150      * Orthologs are to be inferred by method "inferOrthologs".
151      * <p>
152      * (Last modified: 05/08/01)
153      * 
154      * @param query_name
155      *            sequence name of a external node of the gene trees
156      * @param sort
157      *            order and sort priority
158      * @param threshold_orthologs
159      *            the minimal number of observations for a a sequence to be
160      *            reported as orthologous, in percents (0.0-100.0%)
161      * @param threshold_subtreeneighborings
162      *            the minimal number of observations for a a sequence to be
163      *            reported as orthologous, in percents (0.0-100.0%)
164      * @return String containing the inferred orthologs, String containing "-"
165      *         if no orthologs have been found null in case of error
166      */
167     public final StringBuffer inferredOrthologsToString( final String query_name, int sort, double threshold_orthologs ) {
168         HashMap<String, Integer> o_hashmap = null;
169         HashMap<String, Integer> s_hashmap = null;
170         String name = "";
171         double o = 0.0; // Orthologs.
172         double s = 0.0; // Super orthologs.
173         double value1 = 0.0;
174         double value2 = 0.0;
175         final ArrayList<ResultLine> nv = new ArrayList<ResultLine>();
176         if ( ( _o_maps == null ) || ( _so_maps == null ) ) {
177             throw new RuntimeException( "orthologs have not been calculated (successfully)" );
178         }
179         if ( ( sort < 0 ) || ( sort > 2 ) ) {
180             sort = 1;
181         }
182         if ( threshold_orthologs < 0.0 ) {
183             threshold_orthologs = 0.0;
184         }
185         else if ( threshold_orthologs > 100.0 ) {
186             threshold_orthologs = 100.0;
187         }
188         o_hashmap = getInferredOrthologs( query_name );
189         s_hashmap = getInferredSuperOrthologs( query_name );
190         if ( ( o_hashmap == null ) || ( s_hashmap == null ) ) {
191             throw new RuntimeException( "Orthologs for " + query_name + " were not established" );
192         }
193         final StringBuffer orthologs = new StringBuffer();
194         if ( _seq_names.size() > 0 ) {
195             I: for( int i = 0; i < _seq_names.size(); ++i ) {
196                 name = _seq_names.get( i );
197                 if ( name.equals( query_name ) ) {
198                     continue I;
199                 }
200                 o = getBootstrapValueFromHash( o_hashmap, name );
201                 if ( o < threshold_orthologs ) {
202                     continue I;
203                 }
204                 s = getBootstrapValueFromHash( s_hashmap, name );
205                 switch ( sort ) {
206                     case 0:
207                         nv.add( new ResultLine( name, o, 5 ) );
208                         break;
209                     case 1:
210                         nv.add( new ResultLine( name, o, s, 5 ) );
211                         break;
212                     case 2:
213                         nv.add( new ResultLine( name, s, o, 5 ) );
214                         break;
215                     default:
216                         nv.add( new ResultLine( name, o, 5 ) );
217                 }
218             } // End of I for loop.
219             if ( ( nv != null ) && ( nv.size() > 0 ) ) {
220                 orthologs.append( "seq name\t\tortho\ts-ortho" + ForesterUtil.LINE_SEPARATOR );
221                 final ResultLine[] nv_array = new ResultLine[ nv.size() ];
222                 for( int j = 0; j < nv.size(); ++j ) {
223                     nv_array[ j ] = nv.get( j );
224                 }
225                 Arrays.sort( nv_array );
226                 for( final ResultLine element : nv_array ) {
227                     name = element.getKey();
228                     value1 = element.getValue1();
229                     value2 = element.getValue2();
230                     orthologs.append( addNameAndValues( name, value1, value2, sort ) );
231                 }
232             }
233         }
234         // No orthologs found.
235         if ( ( orthologs == null ) || ( orthologs.length() < 1 ) ) {
236             orthologs.append( "-" );
237         }
238         return orthologs;
239     }
240
241     /**
242      * Returns a String containg the names of orthologs of the PhylogenyNode
243      * with seq name query_name. The String also contains how many times a
244      * particular ortholog has been observed. Returns "-" if no putative
245      * orthologs have been found (given threshold_orthologs).
246      * <p>
247      * Orthologs are to be inferred by method "inferOrthologs".
248      * 
249      * @param query_name
250      *            sequence name of a external node of the gene trees
251      * @param return_dists
252      * @param threshold_ultra_paralogs
253      *            between 1 and 100
254      * @return String containing the inferred orthologs, String containing "-"
255      *         if no orthologs have been found null in case of error
256      */
257     public final String inferredUltraParalogsToString( final String query_name, double threshold_ultra_paralogs ) {
258         HashMap<String, Integer> sp_hashmap = null;
259         String name = "", ultra_paralogs = "";
260         int sort = 0;
261         double sp = 0.0;
262         double value1 = 0.0;
263         double value2 = 0.0;
264         final List<ResultLine> nv = new ArrayList<ResultLine>();
265         if ( threshold_ultra_paralogs < 1.0 ) {
266             threshold_ultra_paralogs = 1.0;
267         }
268         else if ( threshold_ultra_paralogs > 100.0 ) {
269             threshold_ultra_paralogs = 100.0;
270         }
271         if ( _up_maps == null ) {
272             throw new RuntimeException( "Ultra paralogs have not been calculated (successfully)." );
273         }
274         sp_hashmap = getInferredUltraParalogs( query_name );
275         if ( sp_hashmap == null ) {
276             throw new RuntimeException( "Ultra paralogs for " + query_name + " were not established" );
277         }
278         if ( _seq_names.size() > 0 ) {
279             I: for( int i = 0; i < _seq_names.size(); ++i ) {
280                 name = _seq_names.get( i );
281                 if ( name.equals( query_name ) ) {
282                     continue I;
283                 }
284                 sp = getBootstrapValueFromHash( sp_hashmap, name );
285                 if ( sp < threshold_ultra_paralogs ) {
286                     continue I;
287                 }
288                 nv.add( new ResultLine( name, sp, 5 ) );
289             } // End of I for loop.
290             if ( ( nv != null ) && ( nv.size() > 0 ) ) {
291                 final ResultLine[] nv_array = new ResultLine[ nv.size() ];
292                 for( int j = 0; j < nv.size(); ++j ) {
293                     nv_array[ j ] = nv.get( j );
294                 }
295                 Arrays.sort( nv_array );
296                 sort = 90;
297                 for( final ResultLine element : nv_array ) {
298                     name = element.getKey();
299                     value1 = element.getValue1();
300                     value2 = element.getValue2();
301                     ultra_paralogs += addNameAndValues( name, value1, value2, sort );
302                 }
303             }
304         }
305         // No ultra paralogs found.
306         if ( ( ultra_paralogs == null ) || ( ultra_paralogs.length() < 1 ) ) {
307             ultra_paralogs = "-";
308         }
309         return ultra_paralogs;
310     }
311
312     // Helper method for inferredOrthologsToString.
313     // inferredOrthologsToArrayList,
314     // and inferredUltraParalogsToString.
315     private final double getBootstrapValueFromHash( final HashMap<String, Integer> h, final String name ) {
316         if ( !h.containsKey( name ) ) {
317             return 0.0;
318         }
319         final int i = h.get( name );
320         return ( ( i * 100.0 ) / getNumberOfSamples() );
321     }
322
323     /**
324      * Returns a HashMap containing the inferred orthologs of the external gene
325      * tree node with the sequence name seq_name. Sequence names are the keys
326      * (String), numbers of observations are the values (Int). Orthologs are to
327      * be inferred by method "inferOrthologs". Throws an exception if seq_name
328      * is not found.
329      * 
330      * @param seq_name
331      *            sequence name of a external node of the gene trees
332      * @return HashMap containing the inferred orthologs
333      *         (name(String)->value(Int))
334      */
335     private final HashMap<String, Integer> getInferredOrthologs( final String seq_name ) {
336         if ( _o_maps == null ) {
337             return null;
338         }
339         return _o_maps.get( seq_name );
340     }
341
342     /**
343      * Returns a HashMap containing the inferred "super orthologs" of the
344      * external gene tree node with the sequence name seq_name. Sequence names
345      * are the keys (String), numbers of observations are the values (Int).
346      * Super orthologs are to be inferred by method "inferOrthologs". Throws an
347      * exception if seq_name is not found.
348      * 
349      * @param seq_name
350      *            sequence name of a external node of the gene trees
351      * @return HashMap containing the inferred super orthologs
352      *         (name(String)->value(Int))
353      */
354     private final HashMap<String, Integer> getInferredSuperOrthologs( final String seq_name ) {
355         if ( _so_maps == null ) {
356             return null;
357         }
358         return _so_maps.get( seq_name );
359     }
360
361     /**
362      * Infers the orthologs (as well the "super orthologs", the "subtree
363      * neighbors", and the "ultra paralogs") for each external node of the gene
364      * Trees in multiple tree File gene_trees_file (=output of PHYLIP NEIGHBOR,
365      * for example). Tallies how many times each sequence is (super-)
366      * orthologous towards the query. Tallies how many times each sequence is
367      * ultra paralogous towards the query. Tallies how many times each sequence
368      * is a subtree neighbor of the query. Gene duplications are inferred using
369      * SDI. Modifies its argument species_tree. Is a little faster than
370      * "inferOrthologs(File,Phylogeny)" since orthologs are only inferred for
371      * query.
372      * <p>
373      * To obtain the results use the methods listed below.
374      * 
375      * @param gene_trees_file
376      *            a File containing gene Trees in NH format, which is the result
377      *            of performing a bootstrap analysis in PHYLIP
378      * @param species_tree
379      *            a species Phylogeny, which has species names in its species
380      *            fields
381      * @param query
382      *            the sequence name of the squence whose orthologs are to be
383      *            inferred
384      * @throws SDIException 
385      * @throws RIOException 
386      * @throws IOException 
387      * @throws FileNotFoundException 
388      */
389     private final void inferOrthologs( final File gene_trees_file,
390                                        final Phylogeny species_tree,
391                                        final String query,
392                                        final SDI.ALGORITHM algorithm ) throws SDIException, RIOException,
393             FileNotFoundException, IOException {
394         // Read in first tree to get its sequence names
395         // and strip species_tree.
396         final PhylogenyFactory factory = ParserBasedPhylogenyFactory.getInstance();
397         final PhylogenyParser p = ParserUtils.createParserDependingOnFileType( gene_trees_file, true );
398         if ( p instanceof NHXParser ) {
399             final NHXParser nhx = ( NHXParser ) p;
400             nhx.setReplaceUnderscores( false );
401             nhx.setIgnoreQuotes( true );
402             nhx.setTaxonomyExtraction( NHXParser.TAXONOMY_EXTRACTION.YES );
403         }
404         final Phylogeny[] gene_trees = factory.create( gene_trees_file, p );
405         // Removes from species_tree all species not found in gene_tree.
406         final List<PhylogenyNode> _removed_gene_tree_nodes = PhylogenyMethods
407                 .taxonomyBasedDeletionOfExternalNodes( gene_trees[ 0 ], species_tree );
408         if ( species_tree.isEmpty() ) {
409             throw new RIOException( "failed to establish species based mapping between gene and species trees" );
410         }
411         if ( !ForesterUtil.isEmpty( query ) ) {
412             PhylogenyMethods.taxonomyBasedDeletionOfExternalNodes( species_tree, gene_trees[ 0 ] );
413             if ( gene_trees[ 0 ].isEmpty() ) {
414                 throw new RIOException( "failed to establish species based mapping between gene and species trees" );
415             }
416             _seq_names = getAllExternalSequenceNames( gene_trees[ 0 ] );
417             if ( ( _seq_names == null ) || ( _seq_names.size() < 1 ) ) {
418                 throw new RIOException( "could not get sequence names" );
419             }
420             _o_maps = new HashMap<String, HashMap<String, Integer>>();
421             _so_maps = new HashMap<String, HashMap<String, Integer>>();
422             _up_maps = new HashMap<String, HashMap<String, Integer>>();
423             _o_maps.put( query, new HashMap<String, Integer>( _seq_names.size() ) );
424             _so_maps.put( query, new HashMap<String, Integer>( _seq_names.size() ) );
425             _up_maps.put( query, new HashMap<String, Integer>( _seq_names.size() ) );
426         }
427         _analyzed_gene_trees = new Phylogeny[ gene_trees.length ];
428         int c = 0;
429         int gene_tree_ext_nodes = 0;
430         for( final Phylogeny gt : gene_trees ) {
431             // Removes from gene_tree all species not found in species_tree.
432             PhylogenyMethods.taxonomyBasedDeletionOfExternalNodes( species_tree, gt );
433             if ( gt.isEmpty() ) {
434                 throw new RIOException( "failed to establish species based mapping between gene and species trees" );
435             }
436             if ( c == 0 ) {
437                 gene_tree_ext_nodes = gt.getNumberOfExternalNodes();
438             }
439             else if ( gene_tree_ext_nodes != gt.getNumberOfExternalNodes() ) {
440                 throw new RIOException( "(cleaned up) gene tree #" + ( c + 1 )
441                         + " has a different number of external nodes (" + gt.getNumberOfExternalNodes()
442                         + ") than those gene trees preceding it (" + gene_tree_ext_nodes + ")" );
443             }
444             _analyzed_gene_trees[ c++ ] = performOrthologInference( gt, species_tree, query, algorithm );
445         }
446         setNumberOfSamples( gene_trees.length );
447     }
448
449     private final Phylogeny performOrthologInference( final Phylogeny gene_tree,
450                                                       final Phylogeny species_tree,
451                                                       final String query,
452                                                       final SDI.ALGORITHM algorithm ) throws SDIException, RIOException {
453         final Phylogeny assigned_tree;
454         switch ( algorithm ) {
455             case SDIR: {
456                 final SDIR sdir = new SDIR();
457                 assigned_tree = sdir.infer( gene_tree,
458                                             species_tree,
459                                             false,
460                                             RIO.ROOT_BY_MINIMIZING_SUM_OF_DUPS,
461                                             RIO.ROOT_BY_MINIMIZING_TREE_HEIGHT,
462                                             true,
463                                             1 )[ 0 ];
464                 break;
465             }
466             case GSDIR: {
467                 final GSDIR gsdir = new GSDIR( gene_tree, species_tree, true, 1 );
468                 assigned_tree = gsdir.getMinDuplicationsSumGeneTrees().get( 1 );
469                 break;
470             }
471             default: {
472                 throw new IllegalArgumentException( "illegal algorithm: " + algorithm );
473             }
474         }
475         setExtNodesOfAnalyzedGeneTrees( assigned_tree.getNumberOfExternalNodes() );
476         if ( !ForesterUtil.isEmpty( query ) ) {
477             final List<PhylogenyNode> nodes = getNodesViaSequenceName( assigned_tree, query );
478             if ( nodes.size() > 1 ) {
479                 throw new RIOException( "node named [" + query + "] not unique" );
480             }
481             else if ( nodes.isEmpty() ) {
482                 throw new RIOException( "no node containing a sequence named [" + query + "] found" );
483             }
484             final PhylogenyNode query_node = nodes.get( 0 );
485             updateCounts( _o_maps, query, PhylogenyMethods.getOrthologousNodes( assigned_tree, query_node ) );
486             updateCounts( _so_maps, query, PhylogenyMethods.getSuperOrthologousNodes( query_node ) );
487             updateCounts( _up_maps, query, PhylogenyMethods.getUltraParalogousNodes( query_node ) );
488         }
489         return assigned_tree;
490     }
491
492     private final void init() {
493         _o_maps = null;
494         _so_maps = null;
495         _up_maps = null;
496         _seq_names = null;
497         _samples = 1;
498         _ext_nodes = 0;
499     }
500
501     private final void setExtNodesOfAnalyzedGeneTrees( final int i ) {
502         _ext_nodes = i;
503     }
504
505     private final void setNumberOfSamples( int i ) {
506         if ( i < 1 ) {
507             i = 1;
508         }
509         _samples = i;
510     }
511
512     // Helper for doInferOrthologs( Phylogeny, Phylogeny, String )
513     // and doInferOrthologs( Phylogeny, Phylogeny ).
514     private final void updateCounts( final HashMap<String, HashMap<String, Integer>> counter_map,
515                                      final String query_seq_name,
516                                      final List<PhylogenyNode> nodes ) {
517         final HashMap<String, Integer> hash_map = counter_map.get( query_seq_name );
518         if ( hash_map == null ) {
519             throw new RuntimeException( "unexpected error in updateCounts" );
520         }
521         for( int j = 0; j < nodes.size(); ++j ) {
522             String seq_name;
523             if ( ( nodes.get( j ) ).getNodeData().isHasSequence()
524                     && !ForesterUtil.isEmpty( ( nodes.get( j ) ).getNodeData().getSequence().getName() ) ) {
525                 seq_name = ( nodes.get( j ) ).getNodeData().getSequence().getName();
526             }
527             else {
528                 seq_name = ( nodes.get( j ) ).getName();
529             }
530             if ( hash_map.containsKey( seq_name ) ) {
531                 hash_map.put( seq_name, hash_map.get( seq_name ) + 1 );
532             }
533             else {
534                 hash_map.put( seq_name, 1 );
535             }
536         }
537     }
538
539     public final static IntMatrix calculateOrthologTable( final Phylogeny[] analyzed_gene_trees, final boolean sort )
540             throws RIOException {
541         final List<String> labels = new ArrayList<String>();
542         final Set<String> labels_set = new HashSet<String>();
543         String label;
544         for( final PhylogenyNode n : analyzed_gene_trees[ 0 ].getExternalNodes() ) {
545             if ( n.getNodeData().isHasSequence() && !ForesterUtil.isEmpty( n.getNodeData().getSequence().getName() ) ) {
546                 label = n.getNodeData().getSequence().getName();
547             }
548             else if ( n.getNodeData().isHasSequence()
549                     && !ForesterUtil.isEmpty( n.getNodeData().getSequence().getSymbol() ) ) {
550                 label = n.getNodeData().getSequence().getSymbol();
551             }
552             else if ( !ForesterUtil.isEmpty( n.getName() ) ) {
553                 label = n.getName();
554             }
555             else {
556                 throw new IllegalArgumentException( "node " + n + " has no appropriate label" );
557             }
558             if ( labels_set.contains( label ) ) {
559                 throw new IllegalArgumentException( "label " + label + " is not unique" );
560             }
561             labels_set.add( label );
562             labels.add( label );
563         }
564         if ( sort ) {
565             Collections.sort( labels );
566         }
567         final IntMatrix m = new IntMatrix( labels );
568         int counter = 0;
569         for( final Phylogeny gt : analyzed_gene_trees ) {
570             counter++;
571             PhylogenyMethods.preOrderReId( gt );
572             final HashMap<String, PhylogenyNode> map = PhylogenyMethods.createNameToExtNodeMap( gt );
573             for( int x = 0; x < m.size(); ++x ) {
574                 final String mx = m.getLabel( x );
575                 final PhylogenyNode nx = map.get( mx );
576                 if ( nx == null ) {
577                     throw new RIOException( "node \"" + mx + "\" not present in gene tree #" + counter );
578                 }
579                 String my;
580                 PhylogenyNode ny;
581                 for( int y = 0; y < m.size(); ++y ) {
582                     my = m.getLabel( y );
583                     ny = map.get( my );
584                     if ( ny == null ) {
585                         throw new RIOException( "node \"" + my + "\" not present in gene tree #" + counter );
586                     }
587                     if ( !PhylogenyMethods.calculateLCAonTreeWithIdsInPreOrder( nx, ny ).isDuplication() ) {
588                         m.inreaseByOne( x, y );
589                     }
590                 }
591             }
592         }
593         return m;
594     }
595
596     /**
597      * Returns the order in which ortholog (o), "super ortholog" (s) and
598      * distance (d) are returned and sorted (priority of sort always goes from
599      * left to right), given sort. For the meaning of sort
600      * 
601      * @see #inferredOrthologsToString(String,int,double,double)
602      *      
603      * @param sort
604      *            determines order and sort priority
605      * @return String indicating the order
606      */
607     public final static String getOrder( final int sort ) {
608         String order = "";
609         switch ( sort ) {
610             case 0:
611                 order = "orthologies";
612                 break;
613             case 1:
614                 order = "orthologies > super orthologies";
615                 break;
616             case 2:
617                 order = "super orthologies > orthologies";
618                 break;
619             default:
620                 order = "orthologies";
621                 break;
622         }
623         return order;
624     }
625
626     public final static StringBuffer getOrderHelp() {
627         final StringBuffer sb = new StringBuffer();
628         sb.append( "  0: orthologies" + ForesterUtil.LINE_SEPARATOR );
629         sb.append( "  1: orthologies > super orthologies" + ForesterUtil.LINE_SEPARATOR );
630         sb.append( "  2: super orthologies > orthologies" + ForesterUtil.LINE_SEPARATOR );
631         return sb;
632     }
633
634     // Helper method for inferredOrthologsToString
635     // and inferredUltraParalogsToString.
636     private final static String addNameAndValues( final String name,
637                                                   final double value1,
638                                                   final double value2,
639                                                   final int sort ) {
640         final java.text.DecimalFormat df = new java.text.DecimalFormat( "0.#####" );
641         df.setDecimalSeparatorAlwaysShown( false );
642         String line = "";
643         if ( name.length() < 8 ) {
644             line += ( name + "\t\t\t" );
645         }
646         else if ( name.length() < 16 ) {
647             line += ( name + "\t\t" );
648         }
649         else {
650             line += ( name + "\t" );
651         }
652         switch ( sort ) {
653             case 0:
654                 line += addToLine( value1, df );
655                 line += "-\t";
656                 break;
657             case 1:
658                 line += addToLine( value1, df );
659                 line += addToLine( value2, df );
660                 break;
661             case 2:
662                 line += addToLine( value2, df );
663                 line += addToLine( value1, df );
664                 break;
665             case 90:
666                 line += addToLine( value1, df );
667                 line += "-\t";
668                 break;
669             case 91:
670                 line += addToLine( value1, df );
671                 line += addToLine( value2, df );
672                 break;
673         }
674         line += ForesterUtil.LINE_SEPARATOR;
675         return line;
676     }
677
678     // Helper for addNameAndValues.
679     private final static String addToLine( final double value, final java.text.DecimalFormat df ) {
680         String s = "";
681         if ( value != ResultLine.DEFAULT ) {
682             s = df.format( value ) + "\t";
683         }
684         else {
685             s = "-\t";
686         }
687         return s;
688     }
689
690     private final static List<String> getAllExternalSequenceNames( final Phylogeny phy ) throws RIOException {
691         final List<String> names = new ArrayList<String>();
692         for( final PhylogenyNodeIterator iter = phy.iteratorExternalForward(); iter.hasNext(); ) {
693             final PhylogenyNode n = iter.next();
694             if ( n.getNodeData().isHasSequence() && !ForesterUtil.isEmpty( n.getNodeData().getSequence().getName() ) ) {
695                 names.add( n.getNodeData().getSequence().getName() );
696             }
697             else if ( !ForesterUtil.isEmpty( n.getName() ) ) {
698                 names.add( n.getName() );
699             }
700             else {
701                 throw new RIOException( "node has no (sequence) name: " + n );
702             }
703         }
704         return names;
705     }
706
707     private final static List<PhylogenyNode> getNodesViaSequenceName( final Phylogeny phy, final String seq_name ) {
708         final List<PhylogenyNode> nodes = new ArrayList<PhylogenyNode>();
709         for( final PhylogenyNodeIterator iter = phy.iteratorPreorder(); iter.hasNext(); ) {
710             final PhylogenyNode n = iter.next();
711             if ( n.getNodeData().isHasSequence() && n.getNodeData().getSequence().getName().equals( seq_name ) ) {
712                 nodes.add( n );
713             }
714             if ( !n.getNodeData().isHasSequence() && n.getName().equals( seq_name ) ) {
715                 nodes.add( n );
716             }
717         }
718         return nodes;
719     }
720
721     public final List<PhylogenyNode> getRemovedGeneTreeNodes() {
722         return _removed_gene_tree_nodes;
723     }
724
725     private final class ResultLine implements Comparable<ResultLine> {
726
727         public static final int DEFAULT = -999;
728         private final String    _key;
729         private final double    _value1;
730         private final double    _value2;
731         private int[]           _p;
732
733         ResultLine( final String name, final double value1, final double value2, final int c ) {
734             setSigns();
735             _key = name;
736             _value1 = value1;
737             _value2 = value2;
738             if ( ( c >= 0 ) && ( c <= 2 ) ) {
739                 _p[ c ] = -1;
740             }
741         }
742
743         ResultLine( final String name, final double value1, final int c ) {
744             setSigns();
745             _key = name;
746             _value1 = value1;
747             _value2 = ResultLine.DEFAULT;
748             if ( c == 0 ) {
749                 _p[ 0 ] = -1;
750             }
751         }
752
753         @Override
754         public int compareTo( final ResultLine n ) {
755             if ( ( getValue1() != ResultLine.DEFAULT ) && ( n.getValue1() != ResultLine.DEFAULT ) ) {
756                 if ( getValue1() < n.getValue1() ) {
757                     return _p[ 0 ];
758                 }
759                 if ( getValue1() > n.getValue1() ) {
760                     return ( -_p[ 0 ] );
761                 }
762             }
763             if ( ( getValue2() != ResultLine.DEFAULT ) && ( n.getValue2() != ResultLine.DEFAULT ) ) {
764                 if ( getValue2() < n.getValue2() ) {
765                     return _p[ 1 ];
766                 }
767                 if ( getValue2() > n.getValue2() ) {
768                     return ( -_p[ 1 ] );
769                 }
770             }
771             return ( getKey().compareTo( n.getKey() ) );
772         }
773
774         String getKey() {
775             return _key;
776         }
777
778         double getValue1() {
779             return _value1;
780         }
781
782         double getValue2() {
783             return _value2;
784         }
785
786         private void setSigns() {
787             _p = new int[ 2 ];
788             _p[ 0 ] = _p[ 1 ] = +1;
789         }
790     } // ResultLine
791 }