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