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