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