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