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