e646ba4b40603d395cb35d555a05043896180e58
[jalview.git] / forester / java / src / org / forester / surfacing / SurfacingUtil.java
1 // $Id:
2 //
3 // FORESTER -- software libraries and applications
4 // for evolutionary biology research and applications.
5 //
6 // Copyright (C) 2008-2009 Christian M. Zmasek
7 // Copyright (C) 2008-2009 Burnham Institute for Medical Research
8 // All rights reserved
9 //
10 // This library is free software; you can redistribute it and/or
11 // modify it under the terms of the GNU Lesser General Public
12 // License as published by the Free Software Foundation; either
13 // version 2.1 of the License, or (at your option) any later version.
14 //
15 // This library is distributed in the hope that it will be useful,
16 // but WITHOUT ANY WARRANTY; without even the implied warranty of
17 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
18 // Lesser General Public License for more details.
19 //
20 // You should have received a copy of the GNU Lesser General Public
21 // License along with this library; if not, write to the Free Software
22 // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
23 //
24 // Contact: phylosoft @ gmail . com
25 // WWW: https://sites.google.com/site/cmzmasek/home/software/forester
26
27 package org.forester.surfacing;
28
29 import java.awt.Color;
30 import java.io.BufferedWriter;
31 import java.io.File;
32 import java.io.FileWriter;
33 import java.io.IOException;
34 import java.io.Writer;
35 import java.text.DecimalFormat;
36 import java.text.NumberFormat;
37 import java.util.ArrayList;
38 import java.util.Arrays;
39 import java.util.Collections;
40 import java.util.Comparator;
41 import java.util.HashMap;
42 import java.util.HashSet;
43 import java.util.Iterator;
44 import java.util.List;
45 import java.util.Map;
46 import java.util.Map.Entry;
47 import java.util.PriorityQueue;
48 import java.util.Set;
49 import java.util.SortedMap;
50 import java.util.SortedSet;
51 import java.util.TreeMap;
52 import java.util.TreeSet;
53 import java.util.regex.Matcher;
54 import java.util.regex.Pattern;
55
56 import org.forester.application.surfacing;
57 import org.forester.evoinference.distance.NeighborJoining;
58 import org.forester.evoinference.matrix.character.BasicCharacterStateMatrix;
59 import org.forester.evoinference.matrix.character.CharacterStateMatrix;
60 import org.forester.evoinference.matrix.character.CharacterStateMatrix.BinaryStates;
61 import org.forester.evoinference.matrix.character.CharacterStateMatrix.Format;
62 import org.forester.evoinference.matrix.character.CharacterStateMatrix.GainLossStates;
63 import org.forester.evoinference.matrix.distance.BasicSymmetricalDistanceMatrix;
64 import org.forester.evoinference.matrix.distance.DistanceMatrix;
65 import org.forester.go.GoId;
66 import org.forester.go.GoNameSpace;
67 import org.forester.go.GoTerm;
68 import org.forester.go.PfamToGoMapping;
69 import org.forester.io.parsers.nexus.NexusConstants;
70 import org.forester.io.parsers.phyloxml.PhyloXmlUtil;
71 import org.forester.io.parsers.util.ParserUtils;
72 import org.forester.io.writers.PhylogenyWriter;
73 import org.forester.phylogeny.Phylogeny;
74 import org.forester.phylogeny.PhylogenyMethods;
75 import org.forester.phylogeny.PhylogenyNode;
76 import org.forester.phylogeny.PhylogenyNode.NH_CONVERSION_SUPPORT_VALUE_STYLE;
77 import org.forester.phylogeny.data.BinaryCharacters;
78 import org.forester.phylogeny.data.Confidence;
79 import org.forester.phylogeny.data.Taxonomy;
80 import org.forester.phylogeny.factories.ParserBasedPhylogenyFactory;
81 import org.forester.phylogeny.iterators.PhylogenyNodeIterator;
82 import org.forester.protein.BasicDomain;
83 import org.forester.protein.BasicProtein;
84 import org.forester.protein.BinaryDomainCombination;
85 import org.forester.protein.Domain;
86 import org.forester.protein.Protein;
87 import org.forester.species.Species;
88 import org.forester.surfacing.DomainSimilarity.PRINT_OPTION;
89 import org.forester.surfacing.DomainSimilarityCalculator.Detailedness;
90 import org.forester.surfacing.GenomeWideCombinableDomains.GenomeWideCombinableDomainsSortOrder;
91 import org.forester.util.AsciiHistogram;
92 import org.forester.util.BasicDescriptiveStatistics;
93 import org.forester.util.BasicTable;
94 import org.forester.util.BasicTableParser;
95 import org.forester.util.CommandLineArguments;
96 import org.forester.util.DescriptiveStatistics;
97 import org.forester.util.ForesterUtil;
98 import org.forester.util.TaxonomyColors;
99
100 public final class SurfacingUtil {
101
102     public final static Pattern              PATTERN_SP_STYLE_TAXONOMY        = Pattern.compile( "^[A-Z0-9]{3,5}$" );
103     private final static Map<String, String> _TAXCODE_HEXCOLORSTRING_MAP      = new HashMap<String, String>();
104     private final static Map<String, String> _TAXCODE_TAXGROUP_MAP            = new HashMap<String, String>();
105     private static final Comparator<Domain>  ASCENDING_CONFIDENCE_VALUE_ORDER = new Comparator<Domain>() {
106
107                                                                                   @Override
108                                                                                   public int compare( final Domain d1,
109                                                                                                       final Domain d2 ) {
110                                                                                       if ( d1.getPerDomainEvalue() < d2
111                                                                                               .getPerDomainEvalue() ) {
112                                                                                           return -1;
113                                                                                       }
114                                                                                       else if ( d1.getPerDomainEvalue() > d2
115                                                                                               .getPerDomainEvalue() ) {
116                                                                                           return 1;
117                                                                                       }
118                                                                                       else {
119                                                                                           return d1.compareTo( d2 );
120                                                                                       }
121                                                                                   }
122                                                                               };
123     private final static NumberFormat        FORMATTER_3                      = new DecimalFormat( "0.000" );
124
125     private SurfacingUtil() {
126         // Hidden constructor.
127     }
128
129     public static void addAllBinaryDomainCombinationToSet( final GenomeWideCombinableDomains genome,
130                                                            final SortedSet<BinaryDomainCombination> binary_domain_combinations ) {
131         final SortedMap<String, CombinableDomains> all_cd = genome.getAllCombinableDomainsIds();
132         for( final String domain_id : all_cd.keySet() ) {
133             binary_domain_combinations.addAll( all_cd.get( domain_id ).toBinaryDomainCombinations() );
134         }
135     }
136
137     public static void addAllDomainIdsToSet( final GenomeWideCombinableDomains genome,
138                                              final SortedSet<String> domain_ids ) {
139         final SortedSet<String> domains = genome.getAllDomainIds();
140         for( final String domain : domains ) {
141             domain_ids.add( domain );
142         }
143     }
144
145     public static DescriptiveStatistics calculateDescriptiveStatisticsForMeanValues( final Set<DomainSimilarity> similarities ) {
146         final DescriptiveStatistics stats = new BasicDescriptiveStatistics();
147         for( final DomainSimilarity similarity : similarities ) {
148             stats.addValue( similarity.getMeanSimilarityScore() );
149         }
150         return stats;
151     }
152
153     public static void checkForOutputFileWriteability( final File outfile ) {
154         final String error = ForesterUtil.isWritableFile( outfile );
155         if ( !ForesterUtil.isEmpty( error ) ) {
156             ForesterUtil.fatalError( surfacing.PRG_NAME, error );
157         }
158     }
159
160     public static void checkWriteabilityForPairwiseComparisons( final DomainSimilarity.PRINT_OPTION domain_similarity_print_option,
161                                                                 final String[][] input_file_properties,
162                                                                 final String automated_pairwise_comparison_suffix,
163                                                                 final File outdir ) {
164         for( int i = 0; i < input_file_properties.length; ++i ) {
165             for( int j = 0; j < i; ++j ) {
166                 final String species_i = input_file_properties[ i ][ 1 ];
167                 final String species_j = input_file_properties[ j ][ 1 ];
168                 String pairwise_similarities_output_file_str = surfacing.PAIRWISE_DOMAIN_COMPARISONS_PREFIX + species_i
169                         + "_" + species_j + automated_pairwise_comparison_suffix;
170                 switch ( domain_similarity_print_option ) {
171                     case HTML:
172                         if ( !pairwise_similarities_output_file_str.endsWith( ".html" ) ) {
173                             pairwise_similarities_output_file_str += ".html";
174                         }
175                         break;
176                 }
177                 final String error = ForesterUtil
178                         .isWritableFile( new File( outdir == null ? pairwise_similarities_output_file_str : outdir
179                                 + ForesterUtil.FILE_SEPARATOR + pairwise_similarities_output_file_str ) );
180                 if ( !ForesterUtil.isEmpty( error ) ) {
181                     ForesterUtil.fatalError( surfacing.PRG_NAME, error );
182                 }
183             }
184         }
185     }
186
187     public static void collectChangedDomainCombinationsFromBinaryStatesMatrixAsListToFile( final CharacterStateMatrix<CharacterStateMatrix.GainLossStates> matrix,
188                                                                                            final BinaryDomainCombination.DomainCombinationType dc_type,
189                                                                                            final List<BinaryDomainCombination> all_binary_domains_combination_gained,
190                                                                                            final boolean get_gains ) {
191         final SortedSet<String> sorted_ids = new TreeSet<String>();
192         for( int i = 0; i < matrix.getNumberOfIdentifiers(); ++i ) {
193             sorted_ids.add( matrix.getIdentifier( i ) );
194         }
195         for( final String id : sorted_ids ) {
196             for( int c = 0; c < matrix.getNumberOfCharacters(); ++c ) {
197                 if ( ( get_gains && ( matrix.getState( id, c ) == CharacterStateMatrix.GainLossStates.GAIN ) )
198                         || ( !get_gains && ( matrix.getState( id, c ) == CharacterStateMatrix.GainLossStates.LOSS ) ) ) {
199                     if ( dc_type == BinaryDomainCombination.DomainCombinationType.DIRECTED_ADJACTANT ) {
200                         all_binary_domains_combination_gained.add( AdjactantDirectedBinaryDomainCombination
201                                 .obtainInstance( matrix.getCharacter( c ) ) );
202                     }
203                     else if ( dc_type == BinaryDomainCombination.DomainCombinationType.DIRECTED ) {
204                         all_binary_domains_combination_gained.add( DirectedBinaryDomainCombination
205                                 .obtainInstance( matrix.getCharacter( c ) ) );
206                     }
207                     else {
208                         all_binary_domains_combination_gained.add( BasicBinaryDomainCombination.obtainInstance( matrix
209                                 .getCharacter( c ) ) );
210                     }
211                 }
212             }
213         }
214     }
215
216     public static Map<String, List<GoId>> createDomainIdToGoIdMap( final List<PfamToGoMapping> pfam_to_go_mappings ) {
217         final Map<String, List<GoId>> domain_id_to_go_ids_map = new HashMap<String, List<GoId>>( pfam_to_go_mappings.size() );
218         for( final PfamToGoMapping pfam_to_go : pfam_to_go_mappings ) {
219             if ( !domain_id_to_go_ids_map.containsKey( pfam_to_go.getKey() ) ) {
220                 domain_id_to_go_ids_map.put( pfam_to_go.getKey(), new ArrayList<GoId>() );
221             }
222             domain_id_to_go_ids_map.get( pfam_to_go.getKey() ).add( pfam_to_go.getValue() );
223         }
224         return domain_id_to_go_ids_map;
225     }
226
227     public static Map<String, Set<String>> createDomainIdToSecondaryFeaturesMap( final File secondary_features_map_file )
228             throws IOException {
229         final BasicTable<String> primary_table = BasicTableParser.parse( secondary_features_map_file, '\t' );
230         final Map<String, Set<String>> map = new TreeMap<String, Set<String>>();
231         for( int r = 0; r < primary_table.getNumberOfRows(); ++r ) {
232             final String domain_id = primary_table.getValue( 0, r );
233             if ( !map.containsKey( domain_id ) ) {
234                 map.put( domain_id, new HashSet<String>() );
235             }
236             map.get( domain_id ).add( primary_table.getValue( 1, r ) );
237         }
238         return map;
239     }
240
241     public static Phylogeny createNjTreeBasedOnMatrixToFile( final File nj_tree_outfile, final DistanceMatrix distance ) {
242         checkForOutputFileWriteability( nj_tree_outfile );
243         final NeighborJoining nj = NeighborJoining.createInstance();
244         final Phylogeny phylogeny = nj.execute( ( BasicSymmetricalDistanceMatrix ) distance );
245         phylogeny.setName( nj_tree_outfile.getName() );
246         writePhylogenyToFile( phylogeny, nj_tree_outfile.toString() );
247         return phylogeny;
248     }
249
250     public static StringBuilder createParametersAsString( final boolean ignore_dufs,
251                                                           final double ie_value_max,
252                                                           final double fs_e_value_max,
253                                                           final int max_allowed_overlap,
254                                                           final boolean no_engulfing_overlaps,
255                                                           final File cutoff_scores_file,
256                                                           final BinaryDomainCombination.DomainCombinationType dc_type ) {
257         final StringBuilder parameters_sb = new StringBuilder();
258         parameters_sb.append( "iE-value: " + ie_value_max );
259         parameters_sb.append( ", FS E-value: " + fs_e_value_max );
260         if ( cutoff_scores_file != null ) {
261             parameters_sb.append( ", Cutoff-scores-file: " + cutoff_scores_file );
262         }
263         else {
264             parameters_sb.append( ", Cutoff-scores-file: not-set" );
265         }
266         if ( max_allowed_overlap != surfacing.MAX_ALLOWED_OVERLAP_DEFAULT ) {
267             parameters_sb.append( ", Max-overlap: " + max_allowed_overlap );
268         }
269         else {
270             parameters_sb.append( ", Max-overlap: not-set" );
271         }
272         if ( no_engulfing_overlaps ) {
273             parameters_sb.append( ", Engulfing-overlaps: not-allowed" );
274         }
275         else {
276             parameters_sb.append( ", Engulfing-overlaps: allowed" );
277         }
278         if ( ignore_dufs ) {
279             parameters_sb.append( ", Ignore-dufs: true" );
280         }
281         else {
282             parameters_sb.append( ", Ignore-dufs: false" );
283         }
284         parameters_sb.append( ", DC type (if applicable): " + dc_type );
285         return parameters_sb;
286     }
287
288     public static void createSplitWriters( final File out_dir,
289                                            final String my_outfile,
290                                            final Map<Character, Writer> split_writers ) throws IOException {
291         split_writers.put( 'a', new BufferedWriter( new FileWriter( out_dir + ForesterUtil.FILE_SEPARATOR + my_outfile
292                 + "_domains_A.html" ) ) );
293         split_writers.put( 'b', new BufferedWriter( new FileWriter( out_dir + ForesterUtil.FILE_SEPARATOR + my_outfile
294                 + "_domains_B.html" ) ) );
295         split_writers.put( 'c', new BufferedWriter( new FileWriter( out_dir + ForesterUtil.FILE_SEPARATOR + my_outfile
296                 + "_domains_C.html" ) ) );
297         split_writers.put( 'd', new BufferedWriter( new FileWriter( out_dir + ForesterUtil.FILE_SEPARATOR + my_outfile
298                 + "_domains_D.html" ) ) );
299         split_writers.put( 'e', new BufferedWriter( new FileWriter( out_dir + ForesterUtil.FILE_SEPARATOR + my_outfile
300                 + "_domains_E.html" ) ) );
301         split_writers.put( 'f', new BufferedWriter( new FileWriter( out_dir + ForesterUtil.FILE_SEPARATOR + my_outfile
302                 + "_domains_F.html" ) ) );
303         split_writers.put( 'g', new BufferedWriter( new FileWriter( out_dir + ForesterUtil.FILE_SEPARATOR + my_outfile
304                 + "_domains_G.html" ) ) );
305         split_writers.put( 'h', new BufferedWriter( new FileWriter( out_dir + ForesterUtil.FILE_SEPARATOR + my_outfile
306                 + "_domains_H.html" ) ) );
307         split_writers.put( 'i', new BufferedWriter( new FileWriter( out_dir + ForesterUtil.FILE_SEPARATOR + my_outfile
308                 + "_domains_I.html" ) ) );
309         split_writers.put( 'j', new BufferedWriter( new FileWriter( out_dir + ForesterUtil.FILE_SEPARATOR + my_outfile
310                 + "_domains_J.html" ) ) );
311         split_writers.put( 'k', new BufferedWriter( new FileWriter( out_dir + ForesterUtil.FILE_SEPARATOR + my_outfile
312                 + "_domains_K.html" ) ) );
313         split_writers.put( 'l', new BufferedWriter( new FileWriter( out_dir + ForesterUtil.FILE_SEPARATOR + my_outfile
314                 + "_domains_L.html" ) ) );
315         split_writers.put( 'm', new BufferedWriter( new FileWriter( out_dir + ForesterUtil.FILE_SEPARATOR + my_outfile
316                 + "_domains_M.html" ) ) );
317         split_writers.put( 'n', new BufferedWriter( new FileWriter( out_dir + ForesterUtil.FILE_SEPARATOR + my_outfile
318                 + "_domains_N.html" ) ) );
319         split_writers.put( 'o', new BufferedWriter( new FileWriter( out_dir + ForesterUtil.FILE_SEPARATOR + my_outfile
320                 + "_domains_O.html" ) ) );
321         split_writers.put( 'p', new BufferedWriter( new FileWriter( out_dir + ForesterUtil.FILE_SEPARATOR + my_outfile
322                 + "_domains_P.html" ) ) );
323         split_writers.put( 'q', new BufferedWriter( new FileWriter( out_dir + ForesterUtil.FILE_SEPARATOR + my_outfile
324                 + "_domains_Q.html" ) ) );
325         split_writers.put( 'r', new BufferedWriter( new FileWriter( out_dir + ForesterUtil.FILE_SEPARATOR + my_outfile
326                 + "_domains_R.html" ) ) );
327         split_writers.put( 's', new BufferedWriter( new FileWriter( out_dir + ForesterUtil.FILE_SEPARATOR + my_outfile
328                 + "_domains_S.html" ) ) );
329         split_writers.put( 't', new BufferedWriter( new FileWriter( out_dir + ForesterUtil.FILE_SEPARATOR + my_outfile
330                 + "_domains_T.html" ) ) );
331         split_writers.put( 'u', new BufferedWriter( new FileWriter( out_dir + ForesterUtil.FILE_SEPARATOR + my_outfile
332                 + "_domains_U.html" ) ) );
333         split_writers.put( 'v', new BufferedWriter( new FileWriter( out_dir + ForesterUtil.FILE_SEPARATOR + my_outfile
334                 + "_domains_V.html" ) ) );
335         split_writers.put( 'w', new BufferedWriter( new FileWriter( out_dir + ForesterUtil.FILE_SEPARATOR + my_outfile
336                 + "_domains_W.html" ) ) );
337         split_writers.put( 'x', new BufferedWriter( new FileWriter( out_dir + ForesterUtil.FILE_SEPARATOR + my_outfile
338                 + "_domains_X.html" ) ) );
339         split_writers.put( 'y', new BufferedWriter( new FileWriter( out_dir + ForesterUtil.FILE_SEPARATOR + my_outfile
340                 + "_domains_Y.html" ) ) );
341         split_writers.put( 'z', new BufferedWriter( new FileWriter( out_dir + ForesterUtil.FILE_SEPARATOR + my_outfile
342                 + "_domains_Z.html" ) ) );
343         split_writers.put( '0', new BufferedWriter( new FileWriter( out_dir + ForesterUtil.FILE_SEPARATOR + my_outfile
344                 + "_domains_0.html" ) ) );
345     }
346
347     public static Map<String, Integer> createTaxCodeToIdMap( final Phylogeny phy ) {
348         final Map<String, Integer> m = new HashMap<String, Integer>();
349         for( final PhylogenyNodeIterator iter = phy.iteratorExternalForward(); iter.hasNext(); ) {
350             final PhylogenyNode n = iter.next();
351             if ( n.getNodeData().isHasTaxonomy() ) {
352                 final Taxonomy t = n.getNodeData().getTaxonomy();
353                 final String c = t.getTaxonomyCode();
354                 if ( !ForesterUtil.isEmpty( c ) ) {
355                     if ( n.getNodeData().getTaxonomy() == null ) {
356                         ForesterUtil.fatalError( surfacing.PRG_NAME, "no taxonomy id for node " + n );
357                     }
358                     final String id = n.getNodeData().getTaxonomy().getIdentifier().getValue();
359                     if ( ForesterUtil.isEmpty( id ) ) {
360                         ForesterUtil.fatalError( surfacing.PRG_NAME, "no taxonomy id for node " + n );
361                     }
362                     if ( m.containsKey( c ) ) {
363                         ForesterUtil.fatalError( surfacing.PRG_NAME, "taxonomy code " + c + " is not unique" );
364                     }
365                     final int iid = Integer.valueOf( id );
366                     if ( m.containsValue( iid ) ) {
367                         ForesterUtil.fatalError( surfacing.PRG_NAME, "taxonomy id " + iid + " is not unique" );
368                     }
369                     m.put( c, iid );
370                 }
371             }
372             else {
373                 ForesterUtil.fatalError( surfacing.PRG_NAME, "no taxonomy for node " + n );
374             }
375         }
376         return m;
377     }
378
379     public static void decoratePrintableDomainSimilarities( final SortedSet<DomainSimilarity> domain_similarities,
380                                                             final Detailedness detailedness ) {
381         for( final DomainSimilarity domain_similarity : domain_similarities ) {
382             if ( domain_similarity instanceof DomainSimilarity ) {
383                 final DomainSimilarity printable_domain_similarity = domain_similarity;
384                 printable_domain_similarity.setDetailedness( detailedness );
385             }
386         }
387     }
388
389     public static void doit( final List<Protein> proteins,
390                              final List<String> query_domain_ids_nc_order,
391                              final Writer out,
392                              final String separator,
393                              final String limit_to_species,
394                              final Map<String, List<Integer>> average_protein_lengths_by_dc ) throws IOException {
395         for( final Protein protein : proteins ) {
396             if ( ForesterUtil.isEmpty( limit_to_species )
397                     || protein.getSpecies().getSpeciesId().equalsIgnoreCase( limit_to_species ) ) {
398                 if ( protein.contains( query_domain_ids_nc_order, true ) ) {
399                     out.write( protein.getSpecies().getSpeciesId() );
400                     out.write( separator );
401                     out.write( protein.getProteinId().getId() );
402                     out.write( separator );
403                     out.write( "[" );
404                     final Set<String> visited_domain_ids = new HashSet<String>();
405                     boolean first = true;
406                     for( final Domain domain : protein.getProteinDomains() ) {
407                         if ( !visited_domain_ids.contains( domain.getDomainId() ) ) {
408                             visited_domain_ids.add( domain.getDomainId() );
409                             if ( first ) {
410                                 first = false;
411                             }
412                             else {
413                                 out.write( " " );
414                             }
415                             out.write( domain.getDomainId() );
416                             out.write( " {" );
417                             out.write( "" + domain.getTotalCount() );
418                             out.write( "}" );
419                         }
420                     }
421                     out.write( "]" );
422                     out.write( separator );
423                     if ( !( ForesterUtil.isEmpty( protein.getDescription() ) || protein.getDescription()
424                             .equals( SurfacingConstants.NONE ) ) ) {
425                         out.write( protein.getDescription() );
426                     }
427                     out.write( separator );
428                     if ( !( ForesterUtil.isEmpty( protein.getAccession() ) || protein.getAccession()
429                             .equals( SurfacingConstants.NONE ) ) ) {
430                         out.write( protein.getAccession() );
431                     }
432                     out.write( SurfacingConstants.NL );
433                 }
434             }
435         }
436         out.flush();
437     }
438
439     public static void domainsPerProteinsStatistics( final String genome,
440                                                      final List<Protein> protein_list,
441                                                      final DescriptiveStatistics all_genomes_domains_per_potein_stats,
442                                                      final SortedMap<Integer, Integer> all_genomes_domains_per_potein_histo,
443                                                      final SortedSet<String> domains_which_are_always_single,
444                                                      final SortedSet<String> domains_which_are_sometimes_single_sometimes_not,
445                                                      final SortedSet<String> domains_which_never_single,
446                                                      final Writer writer ) {
447         final DescriptiveStatistics stats = new BasicDescriptiveStatistics();
448         for( final Protein protein : protein_list ) {
449             final int domains = protein.getNumberOfProteinDomains();
450             //System.out.println( domains );
451             stats.addValue( domains );
452             all_genomes_domains_per_potein_stats.addValue( domains );
453             if ( !all_genomes_domains_per_potein_histo.containsKey( domains ) ) {
454                 all_genomes_domains_per_potein_histo.put( domains, 1 );
455             }
456             else {
457                 all_genomes_domains_per_potein_histo.put( domains,
458                                                           1 + all_genomes_domains_per_potein_histo.get( domains ) );
459             }
460             if ( domains == 1 ) {
461                 final String domain = protein.getProteinDomain( 0 ).getDomainId();
462                 if ( !domains_which_are_sometimes_single_sometimes_not.contains( domain ) ) {
463                     if ( domains_which_never_single.contains( domain ) ) {
464                         domains_which_never_single.remove( domain );
465                         domains_which_are_sometimes_single_sometimes_not.add( domain );
466                     }
467                     else {
468                         domains_which_are_always_single.add( domain );
469                     }
470                 }
471             }
472             else if ( domains > 1 ) {
473                 for( final Domain d : protein.getProteinDomains() ) {
474                     final String domain = d.getDomainId();
475                     // System.out.println( domain );
476                     if ( !domains_which_are_sometimes_single_sometimes_not.contains( domain ) ) {
477                         if ( domains_which_are_always_single.contains( domain ) ) {
478                             domains_which_are_always_single.remove( domain );
479                             domains_which_are_sometimes_single_sometimes_not.add( domain );
480                         }
481                         else {
482                             domains_which_never_single.add( domain );
483                         }
484                     }
485                 }
486             }
487         }
488         try {
489             writer.write( genome );
490             writer.write( "\t" );
491             if ( stats.getN() >= 1 ) {
492                 writer.write( stats.arithmeticMean() + "" );
493                 writer.write( "\t" );
494                 if ( stats.getN() >= 2 ) {
495                     writer.write( stats.sampleStandardDeviation() + "" );
496                 }
497                 else {
498                     writer.write( "" );
499                 }
500                 writer.write( "\t" );
501                 writer.write( stats.median() + "" );
502                 writer.write( "\t" );
503                 writer.write( stats.getN() + "" );
504                 writer.write( "\t" );
505                 writer.write( stats.getMin() + "" );
506                 writer.write( "\t" );
507                 writer.write( stats.getMax() + "" );
508             }
509             else {
510                 writer.write( "\t" );
511                 writer.write( "\t" );
512                 writer.write( "\t" );
513                 writer.write( "0" );
514                 writer.write( "\t" );
515                 writer.write( "\t" );
516             }
517             writer.write( "\n" );
518         }
519         catch ( final IOException e ) {
520             e.printStackTrace();
521         }
522     }
523
524     public static void executeDomainLengthAnalysis( final String[][] input_file_properties,
525                                                     final int number_of_genomes,
526                                                     final DomainLengthsTable domain_lengths_table,
527                                                     final File outfile ) throws IOException {
528         final DecimalFormat df = new DecimalFormat( "#.00" );
529         checkForOutputFileWriteability( outfile );
530         final BufferedWriter out = new BufferedWriter( new FileWriter( outfile ) );
531         out.write( "MEAN BASED STATISTICS PER SPECIES" );
532         out.write( ForesterUtil.LINE_SEPARATOR );
533         out.write( domain_lengths_table.createMeanBasedStatisticsPerSpeciesTable().toString() );
534         out.write( ForesterUtil.LINE_SEPARATOR );
535         out.write( ForesterUtil.LINE_SEPARATOR );
536         final List<DomainLengths> domain_lengths_list = domain_lengths_table.getDomainLengthsList();
537         out.write( "OUTLIER SPECIES PER DOMAIN (Z>=1.5)" );
538         out.write( ForesterUtil.LINE_SEPARATOR );
539         for( final DomainLengths domain_lengths : domain_lengths_list ) {
540             final List<Species> species_list = domain_lengths.getMeanBasedOutlierSpecies( 1.5 );
541             if ( species_list.size() > 0 ) {
542                 out.write( domain_lengths.getDomainId() + "\t" );
543                 for( final Species species : species_list ) {
544                     out.write( species + "\t" );
545                 }
546                 out.write( ForesterUtil.LINE_SEPARATOR );
547             }
548         }
549         out.write( ForesterUtil.LINE_SEPARATOR );
550         out.write( ForesterUtil.LINE_SEPARATOR );
551         out.write( "OUTLIER SPECIES (Z 1.0)" );
552         out.write( ForesterUtil.LINE_SEPARATOR );
553         final DescriptiveStatistics stats_for_all_species = domain_lengths_table
554                 .calculateMeanBasedStatisticsForAllSpecies();
555         out.write( stats_for_all_species.asSummary() );
556         out.write( ForesterUtil.LINE_SEPARATOR );
557         final AsciiHistogram histo = new AsciiHistogram( stats_for_all_species );
558         out.write( histo.toStringBuffer( 40, '=', 60, 4 ).toString() );
559         out.write( ForesterUtil.LINE_SEPARATOR );
560         final double population_sd = stats_for_all_species.sampleStandardDeviation();
561         final double population_mean = stats_for_all_species.arithmeticMean();
562         for( final Species species : domain_lengths_table.getSpecies() ) {
563             final double x = domain_lengths_table.calculateMeanBasedStatisticsForSpecies( species ).arithmeticMean();
564             final double z = ( x - population_mean ) / population_sd;
565             out.write( species + "\t" + z );
566             out.write( ForesterUtil.LINE_SEPARATOR );
567         }
568         out.write( ForesterUtil.LINE_SEPARATOR );
569         for( final Species species : domain_lengths_table.getSpecies() ) {
570             final DescriptiveStatistics stats_for_species = domain_lengths_table
571                     .calculateMeanBasedStatisticsForSpecies( species );
572             final double x = stats_for_species.arithmeticMean();
573             final double z = ( x - population_mean ) / population_sd;
574             if ( ( z <= -1.0 ) || ( z >= 1.0 ) ) {
575                 out.write( species + "\t" + df.format( z ) + "\t" + stats_for_species.asSummary() );
576                 out.write( ForesterUtil.LINE_SEPARATOR );
577             }
578         }
579         out.close();
580         System.gc();
581     }
582
583     /**
584      * Warning: This side-effects 'all_bin_domain_combinations_encountered'!
585      * 
586      * 
587      * @param output_file
588      * @param all_bin_domain_combinations_changed
589      * @param sum_of_all_domains_encountered
590      * @param all_bin_domain_combinations_encountered
591      * @param is_gains_analysis
592      * @param protein_length_stats_by_dc 
593      * @throws IOException
594      */
595     public static void executeFitchGainsAnalysis( final File output_file,
596                                                   final List<BinaryDomainCombination> all_bin_domain_combinations_changed,
597                                                   final int sum_of_all_domains_encountered,
598                                                   final SortedSet<BinaryDomainCombination> all_bin_domain_combinations_encountered,
599                                                   final boolean is_gains_analysis ) throws IOException {
600         checkForOutputFileWriteability( output_file );
601         final Writer out = ForesterUtil.createBufferedWriter( output_file );
602         final SortedMap<Object, Integer> bdc_to_counts = ForesterUtil
603                 .listToSortedCountsMap( all_bin_domain_combinations_changed );
604         final SortedSet<String> all_domains_in_combination_changed_more_than_once = new TreeSet<String>();
605         final SortedSet<String> all_domains_in_combination_changed_only_once = new TreeSet<String>();
606         int above_one = 0;
607         int one = 0;
608         for( final Object bdc_object : bdc_to_counts.keySet() ) {
609             final BinaryDomainCombination bdc = ( BinaryDomainCombination ) bdc_object;
610             final int count = bdc_to_counts.get( bdc_object );
611             if ( count < 1 ) {
612                 ForesterUtil.unexpectedFatalError( surfacing.PRG_NAME, "count < 1 " );
613             }
614             out.write( bdc + "\t" + count + ForesterUtil.LINE_SEPARATOR );
615             if ( count > 1 ) {
616                 all_domains_in_combination_changed_more_than_once.add( bdc.getId0() );
617                 all_domains_in_combination_changed_more_than_once.add( bdc.getId1() );
618                 above_one++;
619             }
620             else if ( count == 1 ) {
621                 all_domains_in_combination_changed_only_once.add( bdc.getId0() );
622                 all_domains_in_combination_changed_only_once.add( bdc.getId1() );
623                 one++;
624             }
625         }
626         final int all = all_bin_domain_combinations_encountered.size();
627         int never_lost = -1;
628         if ( !is_gains_analysis ) {
629             all_bin_domain_combinations_encountered.removeAll( all_bin_domain_combinations_changed );
630             never_lost = all_bin_domain_combinations_encountered.size();
631             for( final BinaryDomainCombination bdc : all_bin_domain_combinations_encountered ) {
632                 out.write( bdc + "\t" + "0" + ForesterUtil.LINE_SEPARATOR );
633             }
634         }
635         if ( is_gains_analysis ) {
636             out.write( "Sum of all distinct domain combinations appearing once               : " + one
637                     + ForesterUtil.LINE_SEPARATOR );
638             out.write( "Sum of all distinct domain combinations appearing more than once     : " + above_one
639                     + ForesterUtil.LINE_SEPARATOR );
640             out.write( "Sum of all distinct domains in combinations apppearing only once     : "
641                     + all_domains_in_combination_changed_only_once.size() + ForesterUtil.LINE_SEPARATOR );
642             out.write( "Sum of all distinct domains in combinations apppearing more than once: "
643                     + all_domains_in_combination_changed_more_than_once.size() + ForesterUtil.LINE_SEPARATOR );
644         }
645         else {
646             out.write( "Sum of all distinct domain combinations never lost                   : " + never_lost
647                     + ForesterUtil.LINE_SEPARATOR );
648             out.write( "Sum of all distinct domain combinations lost once                    : " + one
649                     + ForesterUtil.LINE_SEPARATOR );
650             out.write( "Sum of all distinct domain combinations lost more than once          : " + above_one
651                     + ForesterUtil.LINE_SEPARATOR );
652             out.write( "Sum of all distinct domains in combinations lost only once           : "
653                     + all_domains_in_combination_changed_only_once.size() + ForesterUtil.LINE_SEPARATOR );
654             out.write( "Sum of all distinct domains in combinations lost more than once: "
655                     + all_domains_in_combination_changed_more_than_once.size() + ForesterUtil.LINE_SEPARATOR );
656         }
657         out.write( "All binary combinations                                              : " + all
658                 + ForesterUtil.LINE_SEPARATOR );
659         out.write( "All domains                                                          : "
660                 + sum_of_all_domains_encountered );
661         out.close();
662         ForesterUtil.programMessage( surfacing.PRG_NAME,
663                                      "Wrote fitch domain combination dynamics counts analysis to \"" + output_file
664                                              + "\"" );
665     }
666
667     /**
668      * 
669      * @param all_binary_domains_combination_lost_fitch 
670      * @param use_last_in_fitch_parsimony 
671      * @param perform_dc_fich 
672      * @param consider_directedness_and_adjacency_for_bin_combinations 
673      * @param all_binary_domains_combination_gained if null ignored, otherwise this is to list all binary domain combinations
674      * which were gained under unweighted (Fitch) parsimony.
675      */
676     public static void executeParsimonyAnalysis( final long random_number_seed_for_fitch_parsimony,
677                                                  final boolean radomize_fitch_parsimony,
678                                                  final String outfile_name,
679                                                  final DomainParsimonyCalculator domain_parsimony,
680                                                  final Phylogeny phylogeny,
681                                                  final Map<String, List<GoId>> domain_id_to_go_ids_map,
682                                                  final Map<GoId, GoTerm> go_id_to_term_map,
683                                                  final GoNameSpace go_namespace_limit,
684                                                  final String parameters_str,
685                                                  final Map<String, Set<String>>[] domain_id_to_secondary_features_maps,
686                                                  final SortedSet<String> positive_filter,
687                                                  final boolean output_binary_domain_combinations_for_graphs,
688                                                  final List<BinaryDomainCombination> all_binary_domains_combination_gained_fitch,
689                                                  final List<BinaryDomainCombination> all_binary_domains_combination_lost_fitch,
690                                                  final BinaryDomainCombination.DomainCombinationType dc_type,
691                                                  final Map<String, DescriptiveStatistics> protein_length_stats_by_dc,
692                                                  final Map<String, DescriptiveStatistics> domain_number_stats_by_dc,
693                                                  final Map<String, DescriptiveStatistics> domain_length_stats_by_domain,
694                                                  final Map<String, Integer> tax_code_to_id_map,
695                                                  final boolean write_to_nexus,
696                                                  final boolean use_last_in_fitch_parsimony,
697                                                  final boolean perform_dc_fich ) {
698         final String sep = ForesterUtil.LINE_SEPARATOR + "###################" + ForesterUtil.LINE_SEPARATOR;
699         final String date_time = ForesterUtil.getCurrentDateTime();
700         final SortedSet<String> all_pfams_encountered = new TreeSet<String>();
701         final SortedSet<String> all_pfams_gained_as_domains = new TreeSet<String>();
702         final SortedSet<String> all_pfams_lost_as_domains = new TreeSet<String>();
703         final SortedSet<String> all_pfams_gained_as_dom_combinations = new TreeSet<String>();
704         final SortedSet<String> all_pfams_lost_as_dom_combinations = new TreeSet<String>();
705         if ( write_to_nexus ) {
706             writeToNexus( outfile_name, domain_parsimony, phylogeny );
707         }
708         // DOLLO DOMAINS
709         // -------------
710         Phylogeny local_phylogeny_l = phylogeny.copy();
711         if ( ( positive_filter != null ) && ( positive_filter.size() > 0 ) ) {
712             domain_parsimony.executeDolloParsimonyOnDomainPresence( positive_filter );
713         }
714         else {
715             domain_parsimony.executeDolloParsimonyOnDomainPresence();
716         }
717         SurfacingUtil.writeMatrixToFile( domain_parsimony.getGainLossMatrix(), outfile_name
718                 + surfacing.PARSIMONY_OUTPUT_GL_SUFFIX_DOLLO_DOMAINS, Format.FORESTER );
719         SurfacingUtil.writeMatrixToFile( domain_parsimony.getGainLossCountsMatrix(), outfile_name
720                 + surfacing.PARSIMONY_OUTPUT_GL_COUNTS_SUFFIX_DOLLO_DOMAINS, Format.FORESTER );
721         SurfacingUtil.writeBinaryStatesMatrixAsListToFile( domain_parsimony.getGainLossMatrix(),
722                                                            CharacterStateMatrix.GainLossStates.GAIN,
723                                                            outfile_name + surfacing.PARSIMONY_OUTPUT_DOLLO_GAINS_D,
724                                                            sep,
725                                                            ForesterUtil.LINE_SEPARATOR,
726                                                            null );
727         SurfacingUtil.writeBinaryStatesMatrixAsListToFile( domain_parsimony.getGainLossMatrix(),
728                                                            CharacterStateMatrix.GainLossStates.LOSS,
729                                                            outfile_name + surfacing.PARSIMONY_OUTPUT_DOLLO_LOSSES_D,
730                                                            sep,
731                                                            ForesterUtil.LINE_SEPARATOR,
732                                                            null );
733         SurfacingUtil.writeBinaryStatesMatrixAsListToFile( domain_parsimony.getGainLossMatrix(), null, outfile_name
734                 + surfacing.PARSIMONY_OUTPUT_DOLLO_PRESENT_D, sep, ForesterUtil.LINE_SEPARATOR, null );
735         //HTML:
736         writeBinaryStatesMatrixToList( domain_id_to_go_ids_map,
737                                        go_id_to_term_map,
738                                        go_namespace_limit,
739                                        false,
740                                        domain_parsimony.getGainLossMatrix(),
741                                        CharacterStateMatrix.GainLossStates.GAIN,
742                                        outfile_name + surfacing.PARSIMONY_OUTPUT_DOLLO_GAINS_HTML_D,
743                                        sep,
744                                        ForesterUtil.LINE_SEPARATOR,
745                                        "Dollo Parsimony | Gains | Domains",
746                                        "+",
747                                        domain_id_to_secondary_features_maps,
748                                        all_pfams_encountered,
749                                        all_pfams_gained_as_domains,
750                                        "_dollo_gains_d",
751                                        tax_code_to_id_map );
752         writeBinaryStatesMatrixToList( domain_id_to_go_ids_map,
753                                        go_id_to_term_map,
754                                        go_namespace_limit,
755                                        false,
756                                        domain_parsimony.getGainLossMatrix(),
757                                        CharacterStateMatrix.GainLossStates.LOSS,
758                                        outfile_name + surfacing.PARSIMONY_OUTPUT_DOLLO_LOSSES_HTML_D,
759                                        sep,
760                                        ForesterUtil.LINE_SEPARATOR,
761                                        "Dollo Parsimony | Losses | Domains",
762                                        "-",
763                                        domain_id_to_secondary_features_maps,
764                                        all_pfams_encountered,
765                                        all_pfams_lost_as_domains,
766                                        "_dollo_losses_d",
767                                        tax_code_to_id_map );
768         //        writeBinaryStatesMatrixToList( domain_id_to_go_ids_map,
769         //                                       go_id_to_term_map,
770         //                                       go_namespace_limit,
771         //                                       false,
772         //                                       domain_parsimony.getGainLossMatrix(),
773         //                                       null,
774         //                                       outfile_name + surfacing.PARSIMONY_OUTPUT_DOLLO_PRESENT_HTML_D,
775         //                                       sep,
776         //                                       ForesterUtil.LINE_SEPARATOR,
777         //                                       "Dollo Parsimony | Present | Domains",
778         //                                       "",
779         //                                       domain_id_to_secondary_features_maps,
780         //                                       all_pfams_encountered,
781         //                                       null,
782         //                                       "_dollo_present_d",
783         //                                       tax_code_to_id_map );
784         preparePhylogeny( local_phylogeny_l,
785                           domain_parsimony,
786                           date_time,
787                           "Dollo parsimony on domain presence/absence",
788                           "dollo_on_domains_" + outfile_name,
789                           parameters_str );
790         SurfacingUtil.writePhylogenyToFile( local_phylogeny_l, outfile_name
791                 + surfacing.DOMAINS_PARSIMONY_TREE_OUTPUT_SUFFIX_DOLLO );
792         try {
793             writeAllDomainsChangedOnAllSubtrees( local_phylogeny_l, true, outfile_name, "_dollo_all_gains_d" );
794             writeAllDomainsChangedOnAllSubtrees( local_phylogeny_l, false, outfile_name, "_dollo_all_losses_d" );
795         }
796         catch ( final IOException e ) {
797             e.printStackTrace();
798             ForesterUtil.fatalError( surfacing.PRG_NAME, e.getLocalizedMessage() );
799         }
800         if ( perform_dc_fich && ( domain_parsimony.calculateNumberOfBinaryDomainCombination() > 0 ) ) {
801             // FITCH DOMAIN COMBINATIONS
802             // -------------------------
803             local_phylogeny_l = phylogeny.copy();
804             String randomization = "no";
805             if ( radomize_fitch_parsimony ) {
806                 domain_parsimony.executeFitchParsimonyOnBinaryDomainCombintion( random_number_seed_for_fitch_parsimony );
807                 randomization = "yes, seed = " + random_number_seed_for_fitch_parsimony;
808             }
809             else {
810                 domain_parsimony.executeFitchParsimonyOnBinaryDomainCombintion( use_last_in_fitch_parsimony );
811             }
812             SurfacingUtil.writeMatrixToFile( domain_parsimony.getGainLossMatrix(), outfile_name
813                     + surfacing.PARSIMONY_OUTPUT_GL_SUFFIX_FITCH_BINARY_COMBINATIONS, Format.FORESTER );
814             SurfacingUtil.writeMatrixToFile( domain_parsimony.getGainLossCountsMatrix(), outfile_name
815                     + surfacing.PARSIMONY_OUTPUT_GL_COUNTS_SUFFIX_FITCH_BINARY_COMBINATIONS, Format.FORESTER );
816             SurfacingUtil
817                     .writeBinaryStatesMatrixAsListToFile( domain_parsimony.getGainLossMatrix(),
818                                                           CharacterStateMatrix.GainLossStates.GAIN,
819                                                           outfile_name + surfacing.PARSIMONY_OUTPUT_FITCH_GAINS_BC,
820                                                           sep,
821                                                           ForesterUtil.LINE_SEPARATOR,
822                                                           null );
823             SurfacingUtil.writeBinaryStatesMatrixAsListToFile( domain_parsimony.getGainLossMatrix(),
824                                                                CharacterStateMatrix.GainLossStates.LOSS,
825                                                                outfile_name
826                                                                        + surfacing.PARSIMONY_OUTPUT_FITCH_LOSSES_BC,
827                                                                sep,
828                                                                ForesterUtil.LINE_SEPARATOR,
829                                                                null );
830             SurfacingUtil.writeBinaryStatesMatrixAsListToFile( domain_parsimony.getGainLossMatrix(), null, outfile_name
831                     + surfacing.PARSIMONY_OUTPUT_FITCH_PRESENT_BC, sep, ForesterUtil.LINE_SEPARATOR, null );
832             if ( all_binary_domains_combination_gained_fitch != null ) {
833                 collectChangedDomainCombinationsFromBinaryStatesMatrixAsListToFile( domain_parsimony.getGainLossMatrix(),
834                                                                                     dc_type,
835                                                                                     all_binary_domains_combination_gained_fitch,
836                                                                                     true );
837             }
838             if ( all_binary_domains_combination_lost_fitch != null ) {
839                 collectChangedDomainCombinationsFromBinaryStatesMatrixAsListToFile( domain_parsimony.getGainLossMatrix(),
840                                                                                     dc_type,
841                                                                                     all_binary_domains_combination_lost_fitch,
842                                                                                     false );
843             }
844             if ( output_binary_domain_combinations_for_graphs ) {
845                 SurfacingUtil
846                         .writeBinaryStatesMatrixAsListToFileForBinaryCombinationsForGraphAnalysis( domain_parsimony
847                                                                                                            .getGainLossMatrix(),
848                                                                                                    null,
849                                                                                                    outfile_name
850                                                                                                            + surfacing.PARSIMONY_OUTPUT_FITCH_PRESENT_BC_OUTPUTFILE_SUFFIX_FOR_GRAPH_ANALYSIS,
851                                                                                                    sep,
852                                                                                                    ForesterUtil.LINE_SEPARATOR,
853                                                                                                    BinaryDomainCombination.OutputFormat.DOT );
854             }
855             // HTML:
856             writeBinaryStatesMatrixToList( domain_id_to_go_ids_map,
857                                            go_id_to_term_map,
858                                            go_namespace_limit,
859                                            true,
860                                            domain_parsimony.getGainLossMatrix(),
861                                            CharacterStateMatrix.GainLossStates.GAIN,
862                                            outfile_name + surfacing.PARSIMONY_OUTPUT_FITCH_GAINS_HTML_BC,
863                                            sep,
864                                            ForesterUtil.LINE_SEPARATOR,
865                                            "Fitch Parsimony | Gains | Domain Combinations",
866                                            "+",
867                                            null,
868                                            all_pfams_encountered,
869                                            all_pfams_gained_as_dom_combinations,
870                                            "_fitch_gains_dc",
871                                            tax_code_to_id_map );
872             writeBinaryStatesMatrixToList( domain_id_to_go_ids_map,
873                                            go_id_to_term_map,
874                                            go_namespace_limit,
875                                            true,
876                                            domain_parsimony.getGainLossMatrix(),
877                                            CharacterStateMatrix.GainLossStates.LOSS,
878                                            outfile_name + surfacing.PARSIMONY_OUTPUT_FITCH_LOSSES_HTML_BC,
879                                            sep,
880                                            ForesterUtil.LINE_SEPARATOR,
881                                            "Fitch Parsimony | Losses | Domain Combinations",
882                                            "-",
883                                            null,
884                                            all_pfams_encountered,
885                                            all_pfams_lost_as_dom_combinations,
886                                            "_fitch_losses_dc",
887                                            tax_code_to_id_map );
888             //            writeBinaryStatesMatrixToList( domain_id_to_go_ids_map,
889             //                                           go_id_to_term_map,
890             //                                           go_namespace_limit,
891             //                                           true,
892             //                                           domain_parsimony.getGainLossMatrix(),
893             //                                           null,
894             //                                           outfile_name + surfacing.PARSIMONY_OUTPUT_FITCH_PRESENT_HTML_BC,
895             //                                           sep,
896             //                                           ForesterUtil.LINE_SEPARATOR,
897             //                                           "Fitch Parsimony | Present | Domain Combinations",
898             //                                           "",
899             //                                           null,
900             //                                           all_pfams_encountered,
901             //                                           null,
902             //                                           "_fitch_present_dc",
903             //                                           tax_code_to_id_map );
904             writeAllEncounteredPfamsToFile( domain_id_to_go_ids_map,
905                                             go_id_to_term_map,
906                                             outfile_name,
907                                             all_pfams_encountered );
908             writePfamsToFile( outfile_name + surfacing.ALL_PFAMS_GAINED_AS_DOMAINS_SUFFIX, all_pfams_gained_as_domains );
909             writePfamsToFile( outfile_name + surfacing.ALL_PFAMS_LOST_AS_DOMAINS_SUFFIX, all_pfams_lost_as_domains );
910             writePfamsToFile( outfile_name + surfacing.ALL_PFAMS_GAINED_AS_DC_SUFFIX,
911                               all_pfams_gained_as_dom_combinations );
912             writePfamsToFile( outfile_name + surfacing.ALL_PFAMS_LOST_AS_DC_SUFFIX, all_pfams_lost_as_dom_combinations );
913             preparePhylogeny( local_phylogeny_l,
914                               domain_parsimony,
915                               date_time,
916                               "Fitch parsimony on binary domain combination presence/absence randomization: "
917                                       + randomization,
918                               "fitch_on_binary_domain_combinations_" + outfile_name,
919                               parameters_str );
920             SurfacingUtil.writePhylogenyToFile( local_phylogeny_l, outfile_name
921                     + surfacing.BINARY_DOMAIN_COMBINATIONS_PARSIMONY_TREE_OUTPUT_SUFFIX_FITCH );
922             calculateIndependentDomainCombinationGains( local_phylogeny_l,
923                                                         outfile_name
924                                                                 + surfacing.INDEPENDENT_DC_GAINS_FITCH_PARS_COUNTS_OUTPUT_SUFFIX,
925                                                         outfile_name
926                                                                 + surfacing.INDEPENDENT_DC_GAINS_FITCH_PARS_DC_OUTPUT_SUFFIX,
927                                                         outfile_name
928                                                                 + surfacing.INDEPENDENT_DC_GAINS_FITCH_PARS_DC_FOR_GO_MAPPING_OUTPUT_SUFFIX,
929                                                         outfile_name
930                                                                 + surfacing.INDEPENDENT_DC_GAINS_FITCH_PARS_DC_FOR_GO_MAPPING_OUTPUT_UNIQUE_SUFFIX,
931                                                         outfile_name + "_indep_dc_gains_fitch_lca_ranks.txt",
932                                                         outfile_name + "_indep_dc_gains_fitch_lca_taxonomies.txt",
933                                                         outfile_name + "_indep_dc_gains_fitch_protein_statistics.txt",
934                                                         protein_length_stats_by_dc,
935                                                         domain_number_stats_by_dc,
936                                                         domain_length_stats_by_domain );
937         }
938     }
939
940     public static void executeParsimonyAnalysisForSecondaryFeatures( final String outfile_name,
941                                                                      final DomainParsimonyCalculator secondary_features_parsimony,
942                                                                      final Phylogeny phylogeny,
943                                                                      final String parameters_str,
944                                                                      final Map<Species, MappingResults> mapping_results_map,
945                                                                      final boolean use_last_in_fitch_parsimony ) {
946         final String sep = ForesterUtil.LINE_SEPARATOR + "###################" + ForesterUtil.LINE_SEPARATOR;
947         final String date_time = ForesterUtil.getCurrentDateTime();
948         System.out.println();
949         writeToNexus( outfile_name + surfacing.NEXUS_SECONDARY_FEATURES,
950                       secondary_features_parsimony.createMatrixOfSecondaryFeaturePresenceOrAbsence( null ),
951                       phylogeny );
952         Phylogeny local_phylogeny_copy = phylogeny.copy();
953         secondary_features_parsimony.executeDolloParsimonyOnSecondaryFeatures( mapping_results_map );
954         SurfacingUtil.writeMatrixToFile( secondary_features_parsimony.getGainLossMatrix(), outfile_name
955                 + surfacing.PARSIMONY_OUTPUT_GL_SUFFIX_DOLLO_SECONDARY_FEATURES, Format.FORESTER );
956         SurfacingUtil.writeMatrixToFile( secondary_features_parsimony.getGainLossCountsMatrix(), outfile_name
957                 + surfacing.PARSIMONY_OUTPUT_GL_COUNTS_SUFFIX_DOLLO_SECONDARY_FEATURES, Format.FORESTER );
958         SurfacingUtil
959                 .writeBinaryStatesMatrixAsListToFile( secondary_features_parsimony.getGainLossMatrix(),
960                                                       CharacterStateMatrix.GainLossStates.GAIN,
961                                                       outfile_name
962                                                               + surfacing.PARSIMONY_OUTPUT_DOLLO_GAINS_SECONDARY_FEATURES,
963                                                       sep,
964                                                       ForesterUtil.LINE_SEPARATOR,
965                                                       null );
966         SurfacingUtil
967                 .writeBinaryStatesMatrixAsListToFile( secondary_features_parsimony.getGainLossMatrix(),
968                                                       CharacterStateMatrix.GainLossStates.LOSS,
969                                                       outfile_name
970                                                               + surfacing.PARSIMONY_OUTPUT_DOLLO_LOSSES_SECONDARY_FEATURES,
971                                                       sep,
972                                                       ForesterUtil.LINE_SEPARATOR,
973                                                       null );
974         SurfacingUtil
975                 .writeBinaryStatesMatrixAsListToFile( secondary_features_parsimony.getGainLossMatrix(),
976                                                       null,
977                                                       outfile_name
978                                                               + surfacing.PARSIMONY_OUTPUT_DOLLO_PRESENT_SECONDARY_FEATURES,
979                                                       sep,
980                                                       ForesterUtil.LINE_SEPARATOR,
981                                                       null );
982         preparePhylogeny( local_phylogeny_copy,
983                           secondary_features_parsimony,
984                           date_time,
985                           "Dollo parsimony on secondary feature presence/absence",
986                           "dollo_on_secondary_features_" + outfile_name,
987                           parameters_str );
988         SurfacingUtil.writePhylogenyToFile( local_phylogeny_copy, outfile_name
989                 + surfacing.SECONDARY_FEATURES_PARSIMONY_TREE_OUTPUT_SUFFIX_DOLLO );
990         // FITCH DOMAIN COMBINATIONS
991         // -------------------------
992         local_phylogeny_copy = phylogeny.copy();
993         final String randomization = "no";
994         secondary_features_parsimony
995                 .executeFitchParsimonyOnBinaryDomainCombintionOnSecondaryFeatures( use_last_in_fitch_parsimony );
996         preparePhylogeny( local_phylogeny_copy,
997                           secondary_features_parsimony,
998                           date_time,
999                           "Fitch parsimony on secondary binary domain combination presence/absence randomization: "
1000                                   + randomization,
1001                           "fitch_on_binary_domain_combinations_" + outfile_name,
1002                           parameters_str );
1003         SurfacingUtil.writePhylogenyToFile( local_phylogeny_copy, outfile_name
1004                 + surfacing.BINARY_DOMAIN_COMBINATIONS_PARSIMONY_TREE_OUTPUT_SUFFIX_FITCH_MAPPED );
1005         calculateIndependentDomainCombinationGains( local_phylogeny_copy, outfile_name
1006                 + surfacing.INDEPENDENT_DC_GAINS_FITCH_PARS_COUNTS_MAPPED_OUTPUT_SUFFIX, outfile_name
1007                 + surfacing.INDEPENDENT_DC_GAINS_FITCH_PARS_DC_MAPPED_OUTPUT_SUFFIX, outfile_name
1008                 + surfacing.INDEPENDENT_DC_GAINS_FITCH_PARS_DC_FOR_GO_MAPPING_MAPPED_OUTPUT_SUFFIX, outfile_name
1009                 + surfacing.INDEPENDENT_DC_GAINS_FITCH_PARS_DC_FOR_GO_MAPPING_MAPPED_OUTPUT_UNIQUE_SUFFIX, outfile_name
1010                 + "_MAPPED_indep_dc_gains_fitch_lca_ranks.txt", outfile_name
1011                 + "_MAPPED_indep_dc_gains_fitch_lca_taxonomies.txt", null, null, null, null );
1012     }
1013
1014     public static void executePlusMinusAnalysis( final File output_file,
1015                                                  final List<String> plus_minus_analysis_high_copy_base,
1016                                                  final List<String> plus_minus_analysis_high_copy_target,
1017                                                  final List<String> plus_minus_analysis_low_copy,
1018                                                  final List<GenomeWideCombinableDomains> gwcd_list,
1019                                                  final SortedMap<Species, List<Protein>> protein_lists_per_species,
1020                                                  final Map<String, List<GoId>> domain_id_to_go_ids_map,
1021                                                  final Map<GoId, GoTerm> go_id_to_term_map,
1022                                                  final List<Object> plus_minus_analysis_numbers ) {
1023         final Set<String> all_spec = new HashSet<String>();
1024         for( final GenomeWideCombinableDomains gwcd : gwcd_list ) {
1025             all_spec.add( gwcd.getSpecies().getSpeciesId() );
1026         }
1027         final File html_out_dom = new File( output_file + surfacing.PLUS_MINUS_DOM_SUFFIX_HTML );
1028         final File plain_out_dom = new File( output_file + surfacing.PLUS_MINUS_DOM_SUFFIX );
1029         final File html_out_dc = new File( output_file + surfacing.PLUS_MINUS_DC_SUFFIX_HTML );
1030         final File all_domains_go_ids_out_dom = new File( output_file + surfacing.PLUS_MINUS_ALL_GO_IDS_DOM_SUFFIX );
1031         final File passing_domains_go_ids_out_dom = new File( output_file
1032                 + surfacing.PLUS_MINUS_PASSING_GO_IDS_DOM_SUFFIX );
1033         final File proteins_file_base = new File( output_file + "" );
1034         final int min_diff = ( ( Integer ) plus_minus_analysis_numbers.get( 0 ) ).intValue();
1035         final double factor = ( ( Double ) plus_minus_analysis_numbers.get( 1 ) ).doubleValue();
1036         try {
1037             DomainCountsDifferenceUtil.calculateCopyNumberDifferences( gwcd_list,
1038                                                                        protein_lists_per_species,
1039                                                                        plus_minus_analysis_high_copy_base,
1040                                                                        plus_minus_analysis_high_copy_target,
1041                                                                        plus_minus_analysis_low_copy,
1042                                                                        min_diff,
1043                                                                        factor,
1044                                                                        plain_out_dom,
1045                                                                        html_out_dom,
1046                                                                        html_out_dc,
1047                                                                        domain_id_to_go_ids_map,
1048                                                                        go_id_to_term_map,
1049                                                                        all_domains_go_ids_out_dom,
1050                                                                        passing_domains_go_ids_out_dom,
1051                                                                        proteins_file_base );
1052         }
1053         catch ( final IOException e ) {
1054             ForesterUtil.fatalError( surfacing.PRG_NAME, e.getLocalizedMessage() );
1055         }
1056         ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote plus minus domain analysis results to \""
1057                 + html_out_dom + "\"" );
1058         ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote plus minus domain analysis results to \""
1059                 + plain_out_dom + "\"" );
1060         ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote plus minus domain analysis results to \"" + html_out_dc
1061                 + "\"" );
1062         ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote plus minus domain analysis based passing GO ids to \""
1063                 + passing_domains_go_ids_out_dom + "\"" );
1064         ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote plus minus domain analysis based all GO ids to \""
1065                 + all_domains_go_ids_out_dom + "\"" );
1066     }
1067
1068     public static void extractProteinNames( final List<Protein> proteins,
1069                                             final List<String> query_domain_ids_nc_order,
1070                                             final Writer out,
1071                                             final String separator,
1072                                             final String limit_to_species ) throws IOException {
1073         for( final Protein protein : proteins ) {
1074             if ( ForesterUtil.isEmpty( limit_to_species )
1075                     || protein.getSpecies().getSpeciesId().equalsIgnoreCase( limit_to_species ) ) {
1076                 if ( protein.contains( query_domain_ids_nc_order, true ) ) {
1077                     out.write( protein.getSpecies().getSpeciesId() );
1078                     out.write( separator );
1079                     out.write( protein.getProteinId().getId() );
1080                     out.write( separator );
1081                     out.write( "[" );
1082                     final Set<String> visited_domain_ids = new HashSet<String>();
1083                     boolean first = true;
1084                     for( final Domain domain : protein.getProteinDomains() ) {
1085                         if ( !visited_domain_ids.contains( domain.getDomainId() ) ) {
1086                             visited_domain_ids.add( domain.getDomainId() );
1087                             if ( first ) {
1088                                 first = false;
1089                             }
1090                             else {
1091                                 out.write( " " );
1092                             }
1093                             out.write( domain.getDomainId() );
1094                             out.write( " {" );
1095                             out.write( "" + domain.getTotalCount() );
1096                             out.write( "}" );
1097                         }
1098                     }
1099                     out.write( "]" );
1100                     out.write( separator );
1101                     if ( !( ForesterUtil.isEmpty( protein.getDescription() ) || protein.getDescription()
1102                             .equals( SurfacingConstants.NONE ) ) ) {
1103                         out.write( protein.getDescription() );
1104                     }
1105                     out.write( separator );
1106                     if ( !( ForesterUtil.isEmpty( protein.getAccession() ) || protein.getAccession()
1107                             .equals( SurfacingConstants.NONE ) ) ) {
1108                         out.write( protein.getAccession() );
1109                     }
1110                     out.write( SurfacingConstants.NL );
1111                 }
1112             }
1113         }
1114         out.flush();
1115     }
1116
1117     public static void extractProteinNames( final SortedMap<Species, List<Protein>> protein_lists_per_species,
1118                                             final String domain_id,
1119                                             final Writer out,
1120                                             final String separator,
1121                                             final String limit_to_species,
1122                                             final double domain_e_cutoff ) throws IOException {
1123         //System.out.println( "Per domain E-value: " + domain_e_cutoff );
1124         for( final Species species : protein_lists_per_species.keySet() ) {
1125             //System.out.println( species + ":" );
1126             for( final Protein protein : protein_lists_per_species.get( species ) ) {
1127                 if ( ForesterUtil.isEmpty( limit_to_species )
1128                         || protein.getSpecies().getSpeciesId().equalsIgnoreCase( limit_to_species ) ) {
1129                     final List<Domain> domains = protein.getProteinDomains( domain_id );
1130                     if ( domains.size() > 0 ) {
1131                         out.write( protein.getSpecies().getSpeciesId() );
1132                         out.write( separator );
1133                         out.write( protein.getProteinId().getId() );
1134                         out.write( separator );
1135                         out.write( domain_id.toString() );
1136                         out.write( separator );
1137                         int prev_to = -1;
1138                         for( final Domain domain : domains ) {
1139                             if ( ( domain_e_cutoff < 0 ) || ( domain.getPerDomainEvalue() <= domain_e_cutoff ) ) {
1140                                 out.write( "/" );
1141                                 out.write( domain.getFrom() + "-" + domain.getTo() );
1142                                 if ( prev_to >= 0 ) {
1143                                     final int l = domain.getFrom() - prev_to;
1144                                     // System.out.println( l );
1145                                 }
1146                                 prev_to = domain.getTo();
1147                             }
1148                         }
1149                         out.write( "/" );
1150                         out.write( separator );
1151                         final List<Domain> domain_list = new ArrayList<Domain>();
1152                         for( final Domain domain : protein.getProteinDomains() ) {
1153                             if ( ( domain_e_cutoff < 0 ) || ( domain.getPerDomainEvalue() <= domain_e_cutoff ) ) {
1154                                 domain_list.add( domain );
1155                             }
1156                         }
1157                         final Domain domain_ary[] = new Domain[ domain_list.size() ];
1158                         for( int i = 0; i < domain_list.size(); ++i ) {
1159                             domain_ary[ i ] = domain_list.get( i );
1160                         }
1161                         Arrays.sort( domain_ary, new DomainComparator( true ) );
1162                         out.write( "{" );
1163                         boolean first = true;
1164                         for( final Domain domain : domain_ary ) {
1165                             if ( first ) {
1166                                 first = false;
1167                             }
1168                             else {
1169                                 out.write( "," );
1170                             }
1171                             out.write( domain.getDomainId().toString() );
1172                             out.write( ":" + domain.getFrom() + "-" + domain.getTo() );
1173                             out.write( ":" + domain.getPerDomainEvalue() );
1174                         }
1175                         out.write( "}" );
1176                         if ( !( ForesterUtil.isEmpty( protein.getDescription() ) || protein.getDescription()
1177                                 .equals( SurfacingConstants.NONE ) ) ) {
1178                             out.write( protein.getDescription() );
1179                         }
1180                         out.write( separator );
1181                         if ( !( ForesterUtil.isEmpty( protein.getAccession() ) || protein.getAccession()
1182                                 .equals( SurfacingConstants.NONE ) ) ) {
1183                             out.write( protein.getAccession() );
1184                         }
1185                         out.write( SurfacingConstants.NL );
1186                     }
1187                 }
1188             }
1189         }
1190         out.flush();
1191     }
1192
1193     public static SortedSet<String> getAllDomainIds( final List<GenomeWideCombinableDomains> gwcd_list ) {
1194         final SortedSet<String> all_domains_ids = new TreeSet<String>();
1195         for( final GenomeWideCombinableDomains gwcd : gwcd_list ) {
1196             final Set<String> all_domains = gwcd.getAllDomainIds();
1197             //    for( final Domain domain : all_domains ) {
1198             all_domains_ids.addAll( all_domains );
1199             //    }
1200         }
1201         return all_domains_ids;
1202     }
1203
1204     public static SortedMap<String, Integer> getDomainCounts( final List<Protein> protein_domain_collections ) {
1205         final SortedMap<String, Integer> map = new TreeMap<String, Integer>();
1206         for( final Protein protein_domain_collection : protein_domain_collections ) {
1207             for( final Object name : protein_domain_collection.getProteinDomains() ) {
1208                 final BasicDomain protein_domain = ( BasicDomain ) name;
1209                 final String id = protein_domain.getDomainId();
1210                 if ( map.containsKey( id ) ) {
1211                     map.put( id, map.get( id ) + 1 );
1212                 }
1213                 else {
1214                     map.put( id, 1 );
1215                 }
1216             }
1217         }
1218         return map;
1219     }
1220
1221     public static int getNumberOfNodesLackingName( final Phylogeny p, final StringBuilder names ) {
1222         final PhylogenyNodeIterator it = p.iteratorPostorder();
1223         int c = 0;
1224         while ( it.hasNext() ) {
1225             final PhylogenyNode n = it.next();
1226             if ( ForesterUtil.isEmpty( n.getName() )
1227                     && ( !n.getNodeData().isHasTaxonomy() || ForesterUtil.isEmpty( n.getNodeData().getTaxonomy()
1228                             .getScientificName() ) )
1229                     && ( !n.getNodeData().isHasTaxonomy() || ForesterUtil.isEmpty( n.getNodeData().getTaxonomy()
1230                             .getCommonName() ) ) ) {
1231                 if ( n.getParent() != null ) {
1232                     names.append( " " );
1233                     names.append( n.getParent().getName() );
1234                 }
1235                 final List l = n.getAllExternalDescendants();
1236                 for( final Object object : l ) {
1237                     System.out.println( l.toString() );
1238                 }
1239                 ++c;
1240             }
1241         }
1242         return c;
1243     }
1244
1245     public static void log( final String msg, final Writer w ) {
1246         try {
1247             w.write( msg );
1248             w.write( ForesterUtil.LINE_SEPARATOR );
1249         }
1250         catch ( final IOException e ) {
1251             ForesterUtil.fatalError( surfacing.PRG_NAME, e.getLocalizedMessage() );
1252         }
1253     }
1254
1255     public static Phylogeny[] obtainAndPreProcessIntrees( final File[] intree_files,
1256                                                           final int number_of_genomes,
1257                                                           final String[][] input_file_properties ) {
1258         final Phylogeny[] intrees = new Phylogeny[ intree_files.length ];
1259         int i = 0;
1260         for( final File intree_file : intree_files ) {
1261             Phylogeny intree = null;
1262             final String error = ForesterUtil.isReadableFile( intree_file );
1263             if ( !ForesterUtil.isEmpty( error ) ) {
1264                 ForesterUtil.fatalError( surfacing.PRG_NAME, "cannot read input tree file [" + intree_file + "]: "
1265                         + error );
1266             }
1267             try {
1268                 final Phylogeny[] p_array = ParserBasedPhylogenyFactory.getInstance()
1269                         .create( intree_file, ParserUtils.createParserDependingOnFileType( intree_file, true ) );
1270                 if ( p_array.length < 1 ) {
1271                     ForesterUtil.fatalError( surfacing.PRG_NAME, "file [" + intree_file
1272                             + "] does not contain any phylogeny in phyloXML format" );
1273                 }
1274                 else if ( p_array.length > 1 ) {
1275                     ForesterUtil.fatalError( surfacing.PRG_NAME, "file [" + intree_file
1276                             + "] contains more than one phylogeny in phyloXML format" );
1277                 }
1278                 intree = p_array[ 0 ];
1279             }
1280             catch ( final Exception e ) {
1281                 ForesterUtil.fatalError( surfacing.PRG_NAME, "failed to read input tree from file [" + intree_file
1282                         + "]: " + error );
1283             }
1284             if ( ( intree == null ) || intree.isEmpty() ) {
1285                 ForesterUtil.fatalError( surfacing.PRG_NAME, "input tree [" + intree_file + "] is empty" );
1286             }
1287             if ( !intree.isRooted() ) {
1288                 ForesterUtil.fatalError( surfacing.PRG_NAME, "input tree [" + intree_file + "] is not rooted" );
1289             }
1290             if ( intree.getNumberOfExternalNodes() < number_of_genomes ) {
1291                 ForesterUtil.fatalError( surfacing.PRG_NAME,
1292                                          "number of external nodes [" + intree.getNumberOfExternalNodes()
1293                                                  + "] of input tree [" + intree_file
1294                                                  + "] is smaller than the number of genomes the be analyzed ["
1295                                                  + number_of_genomes + "]" );
1296             }
1297             final StringBuilder parent_names = new StringBuilder();
1298             final int nodes_lacking_name = getNumberOfNodesLackingName( intree, parent_names );
1299             if ( nodes_lacking_name > 0 ) {
1300                 ForesterUtil.fatalError( surfacing.PRG_NAME, "input tree [" + intree_file + "] has "
1301                         + nodes_lacking_name + " node(s) lacking a name [parent names:" + parent_names + "]" );
1302             }
1303             preparePhylogenyForParsimonyAnalyses( intree, input_file_properties );
1304             if ( !intree.isCompletelyBinary() ) {
1305                 ForesterUtil.printWarningMessage( surfacing.PRG_NAME, "input tree [" + intree_file
1306                         + "] is not completely binary" );
1307             }
1308             intrees[ i++ ] = intree;
1309         }
1310         return intrees;
1311     }
1312
1313     public static Phylogeny obtainFirstIntree( final File intree_file ) {
1314         Phylogeny intree = null;
1315         final String error = ForesterUtil.isReadableFile( intree_file );
1316         if ( !ForesterUtil.isEmpty( error ) ) {
1317             ForesterUtil.fatalError( surfacing.PRG_NAME, "cannot read input tree file [" + intree_file + "]: " + error );
1318         }
1319         try {
1320             final Phylogeny[] phys = ParserBasedPhylogenyFactory.getInstance()
1321                     .create( intree_file, ParserUtils.createParserDependingOnFileType( intree_file, true ) );
1322             if ( phys.length < 1 ) {
1323                 ForesterUtil.fatalError( surfacing.PRG_NAME, "file [" + intree_file
1324                         + "] does not contain any phylogeny in phyloXML format" );
1325             }
1326             else if ( phys.length > 1 ) {
1327                 ForesterUtil.fatalError( surfacing.PRG_NAME, "file [" + intree_file
1328                         + "] contains more than one phylogeny in phyloXML format" );
1329             }
1330             intree = phys[ 0 ];
1331         }
1332         catch ( final Exception e ) {
1333             ForesterUtil.fatalError( surfacing.PRG_NAME, "failed to read input tree from file [" + intree_file + "]: "
1334                     + error );
1335         }
1336         if ( ( intree == null ) || intree.isEmpty() ) {
1337             ForesterUtil.fatalError( surfacing.PRG_NAME, "input tree [" + intree_file + "] is empty" );
1338         }
1339         if ( !intree.isRooted() ) {
1340             ForesterUtil.fatalError( surfacing.PRG_NAME, "input tree [" + intree_file + "] is not rooted" );
1341         }
1342         return intree;
1343     }
1344
1345     public static String obtainHexColorStringDependingOnTaxonomyGroup( final String tax_code, final Phylogeny phy )
1346             throws IllegalArgumentException {
1347         if ( !_TAXCODE_HEXCOLORSTRING_MAP.containsKey( tax_code ) ) {
1348             if ( ( phy != null ) && !phy.isEmpty() ) {
1349                 //                final List<PhylogenyNode> nodes = phy.getNodesViaTaxonomyCode( tax_code );
1350                 //                Color c = null;
1351                 //                if ( ( nodes == null ) || nodes.isEmpty() ) {
1352                 //                    throw new IllegalArgumentException( "code " + tax_code + " is not found" );
1353                 //                }
1354                 //                if ( nodes.size() != 1 ) {
1355                 //                    throw new IllegalArgumentException( "code " + tax_code + " is not unique" );
1356                 //                }
1357                 //                PhylogenyNode n = nodes.get( 0 );
1358                 //                while ( n != null ) {
1359                 //                    if ( n.getNodeData().isHasTaxonomy()
1360                 //                            && !ForesterUtil.isEmpty( n.getNodeData().getTaxonomy().getScientificName() ) ) {
1361                 //                        c = ForesterUtil.obtainColorDependingOnTaxonomyGroup( n.getNodeData().getTaxonomy()
1362                 //                                .getScientificName(), tax_code );
1363                 //                    }
1364                 //                    if ( ( c == null ) && !ForesterUtil.isEmpty( n.getName() ) ) {
1365                 //                        c = ForesterUtil.obtainColorDependingOnTaxonomyGroup( n.getName(), tax_code );
1366                 //                    }
1367                 //                    if ( c != null ) {
1368                 //                        break;
1369                 //                    }
1370                 //                    n = n.getParent();
1371                 //                }
1372                 final String group = obtainTaxonomyGroup( tax_code, phy );
1373                 final Color c = ForesterUtil.obtainColorDependingOnTaxonomyGroup( group );
1374                 if ( c == null ) {
1375                     throw new IllegalArgumentException( "no color found for taxonomy group \"" + group
1376                             + "\" for code \"" + tax_code + "\"" );
1377                 }
1378                 final String hex = String.format( "#%02x%02x%02x", c.getRed(), c.getGreen(), c.getBlue() );
1379                 _TAXCODE_HEXCOLORSTRING_MAP.put( tax_code, hex );
1380             }
1381             else {
1382                 throw new IllegalArgumentException( "unable to obtain color for code " + tax_code
1383                         + " (tree is null or empty and code is not in map)" );
1384             }
1385         }
1386         return _TAXCODE_HEXCOLORSTRING_MAP.get( tax_code );
1387     }
1388
1389     public static String obtainTaxonomyGroup( final String tax_code, final Phylogeny species_tree )
1390             throws IllegalArgumentException {
1391         if ( !_TAXCODE_TAXGROUP_MAP.containsKey( tax_code ) ) {
1392             if ( ( species_tree != null ) && !species_tree.isEmpty() ) {
1393                 final List<PhylogenyNode> nodes = species_tree.getNodesViaTaxonomyCode( tax_code );
1394                 if ( ( nodes == null ) || nodes.isEmpty() ) {
1395                     throw new IllegalArgumentException( "code " + tax_code + " is not found" );
1396                 }
1397                 if ( nodes.size() != 1 ) {
1398                     throw new IllegalArgumentException( "code " + tax_code + " is not unique" );
1399                 }
1400                 PhylogenyNode n = nodes.get( 0 );
1401                 String group = null;
1402                 while ( n != null ) {
1403                     if ( n.getNodeData().isHasTaxonomy()
1404                             && !ForesterUtil.isEmpty( n.getNodeData().getTaxonomy().getScientificName() ) ) {
1405                         group = ForesterUtil.obtainNormalizedTaxonomyGroup( n.getNodeData().getTaxonomy()
1406                                 .getScientificName() );
1407                     }
1408                     if ( ForesterUtil.isEmpty( group ) && !ForesterUtil.isEmpty( n.getName() ) ) {
1409                         group = ForesterUtil.obtainNormalizedTaxonomyGroup( n.getName() );
1410                     }
1411                     if ( !ForesterUtil.isEmpty( group ) ) {
1412                         break;
1413                     }
1414                     n = n.getParent();
1415                 }
1416                 if ( ForesterUtil.isEmpty( group ) ) {
1417                     throw new IllegalArgumentException( "no group found for taxonomy code \"" + tax_code + "\"" );
1418                 }
1419                 _TAXCODE_TAXGROUP_MAP.put( tax_code, group );
1420             }
1421             else {
1422                 throw new IllegalArgumentException( "unable to obtain group for code " + tax_code
1423                         + " (tree is null or empty and code is not in map)" );
1424             }
1425         }
1426         return _TAXCODE_TAXGROUP_MAP.get( tax_code );
1427     }
1428
1429     public static void performDomainArchitectureAnalysis( final SortedMap<String, Set<String>> domain_architecutures,
1430                                                           final SortedMap<String, Integer> domain_architecuture_counts,
1431                                                           final int min_count,
1432                                                           final File da_counts_outfile,
1433                                                           final File unique_da_outfile ) {
1434         checkForOutputFileWriteability( da_counts_outfile );
1435         checkForOutputFileWriteability( unique_da_outfile );
1436         try {
1437             final BufferedWriter da_counts_out = new BufferedWriter( new FileWriter( da_counts_outfile ) );
1438             final BufferedWriter unique_da_out = new BufferedWriter( new FileWriter( unique_da_outfile ) );
1439             final Iterator<Entry<String, Integer>> it = domain_architecuture_counts.entrySet().iterator();
1440             while ( it.hasNext() ) {
1441                 final Map.Entry<String, Integer> e = it.next();
1442                 final String da = e.getKey();
1443                 final int count = e.getValue();
1444                 if ( count >= min_count ) {
1445                     da_counts_out.write( da );
1446                     da_counts_out.write( "\t" );
1447                     da_counts_out.write( String.valueOf( count ) );
1448                     da_counts_out.write( ForesterUtil.LINE_SEPARATOR );
1449                 }
1450                 if ( count == 1 ) {
1451                     final Iterator<Entry<String, Set<String>>> it2 = domain_architecutures.entrySet().iterator();
1452                     while ( it2.hasNext() ) {
1453                         final Map.Entry<String, Set<String>> e2 = it2.next();
1454                         final String genome = e2.getKey();
1455                         final Set<String> das = e2.getValue();
1456                         if ( das.contains( da ) ) {
1457                             unique_da_out.write( genome );
1458                             unique_da_out.write( "\t" );
1459                             unique_da_out.write( da );
1460                             unique_da_out.write( ForesterUtil.LINE_SEPARATOR );
1461                         }
1462                     }
1463                 }
1464             }
1465             unique_da_out.close();
1466             da_counts_out.close();
1467         }
1468         catch ( final IOException e ) {
1469             ForesterUtil.fatalError( surfacing.PRG_NAME, e.getMessage() );
1470         }
1471         ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote distance matrices to \"" + da_counts_outfile + "\"" );
1472         ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote distance matrices to \"" + unique_da_outfile + "\"" );
1473         //
1474     }
1475
1476     public static void preparePhylogeny( final Phylogeny p,
1477                                          final DomainParsimonyCalculator domain_parsimony,
1478                                          final String date_time,
1479                                          final String method,
1480                                          final String name,
1481                                          final String parameters_str ) {
1482         domain_parsimony.decoratePhylogenyWithDomains( p );
1483         final StringBuilder desc = new StringBuilder();
1484         desc.append( "[Method: " + method + "] [Date: " + date_time + "] " );
1485         desc.append( "[Cost: " + domain_parsimony.getCost() + "] " );
1486         desc.append( "[Gains: " + domain_parsimony.getTotalGains() + "] " );
1487         desc.append( "[Losses: " + domain_parsimony.getTotalLosses() + "] " );
1488         desc.append( "[Unchanged: " + domain_parsimony.getTotalUnchanged() + "] " );
1489         desc.append( "[Parameters: " + parameters_str + "]" );
1490         p.setName( name );
1491         p.setDescription( desc.toString() );
1492         p.setConfidence( new Confidence( domain_parsimony.getCost(), "parsimony" ) );
1493         p.setRerootable( false );
1494         p.setRooted( true );
1495     }
1496
1497     public static void preparePhylogenyForParsimonyAnalyses( final Phylogeny intree,
1498                                                              final String[][] input_file_properties ) {
1499         final String[] genomes = new String[ input_file_properties.length ];
1500         for( int i = 0; i < input_file_properties.length; ++i ) {
1501             if ( intree.getNodes( input_file_properties[ i ][ 1 ] ).size() > 1 ) {
1502                 ForesterUtil.fatalError( surfacing.PRG_NAME, "node named [" + input_file_properties[ i ][ 1 ]
1503                         + "] is not unique in input tree " + intree.getName() );
1504             }
1505             genomes[ i ] = input_file_properties[ i ][ 1 ];
1506         }
1507         //
1508         final PhylogenyNodeIterator it = intree.iteratorPostorder();
1509         while ( it.hasNext() ) {
1510             final PhylogenyNode n = it.next();
1511             if ( ForesterUtil.isEmpty( n.getName() ) ) {
1512                 if ( n.getNodeData().isHasTaxonomy()
1513                         && !ForesterUtil.isEmpty( n.getNodeData().getTaxonomy().getTaxonomyCode() ) ) {
1514                     n.setName( n.getNodeData().getTaxonomy().getTaxonomyCode() );
1515                 }
1516                 else if ( n.getNodeData().isHasTaxonomy()
1517                         && !ForesterUtil.isEmpty( n.getNodeData().getTaxonomy().getScientificName() ) ) {
1518                     n.setName( n.getNodeData().getTaxonomy().getScientificName() );
1519                 }
1520                 else if ( n.getNodeData().isHasTaxonomy()
1521                         && !ForesterUtil.isEmpty( n.getNodeData().getTaxonomy().getCommonName() ) ) {
1522                     n.setName( n.getNodeData().getTaxonomy().getCommonName() );
1523                 }
1524                 else {
1525                     ForesterUtil
1526                             .fatalError( surfacing.PRG_NAME,
1527                                          "node with no name, scientific name, common name, or taxonomy code present" );
1528                 }
1529             }
1530         }
1531         //
1532         final List<String> igns = PhylogenyMethods.deleteExternalNodesPositiveSelection( genomes, intree );
1533         if ( igns.size() > 0 ) {
1534             System.out.println( "Not using the following " + igns.size() + " nodes:" );
1535             for( int i = 0; i < igns.size(); ++i ) {
1536                 System.out.println( " " + i + ": " + igns.get( i ) );
1537             }
1538             System.out.println( "--" );
1539         }
1540         for( final String[] input_file_propertie : input_file_properties ) {
1541             try {
1542                 intree.getNode( input_file_propertie[ 1 ] );
1543             }
1544             catch ( final IllegalArgumentException e ) {
1545                 ForesterUtil.fatalError( surfacing.PRG_NAME, "node named [" + input_file_propertie[ 1 ]
1546                         + "] not present/not unique in input tree" );
1547             }
1548         }
1549     }
1550
1551     public static void printOutPercentageOfMultidomainProteins( final SortedMap<Integer, Integer> all_genomes_domains_per_potein_histo,
1552                                                                 final Writer log_writer ) {
1553         int sum = 0;
1554         for( final Entry<Integer, Integer> entry : all_genomes_domains_per_potein_histo.entrySet() ) {
1555             sum += entry.getValue();
1556         }
1557         final double percentage = ( 100.0 * ( sum - all_genomes_domains_per_potein_histo.get( 1 ) ) ) / sum;
1558         ForesterUtil.programMessage( surfacing.PRG_NAME, "Percentage of multidomain proteins: " + percentage + "%" );
1559         log( "Percentage of multidomain proteins:            : " + percentage + "%", log_writer );
1560     }
1561
1562     public static void processFilter( final File filter_file, final SortedSet<String> filter ) {
1563         SortedSet<String> filter_str = null;
1564         try {
1565             filter_str = ForesterUtil.file2set( filter_file );
1566         }
1567         catch ( final IOException e ) {
1568             ForesterUtil.fatalError( surfacing.PRG_NAME, e.getMessage() );
1569         }
1570         if ( filter_str != null ) {
1571             for( final String string : filter_str ) {
1572                 filter.add( string );
1573             }
1574         }
1575         if ( surfacing.VERBOSE ) {
1576             System.out.println( "Filter:" );
1577             for( final String domainId : filter ) {
1578                 System.out.println( domainId );
1579             }
1580         }
1581     }
1582
1583     public static String[][] processInputGenomesFile( final File input_genomes ) {
1584         String[][] input_file_properties = null;
1585         try {
1586             input_file_properties = ForesterUtil.file22dArray( input_genomes );
1587         }
1588         catch ( final IOException e ) {
1589             ForesterUtil.fatalError( surfacing.PRG_NAME,
1590                                      "genomes files is to be in the following format \"<hmmpfam output file> <species>\": "
1591                                              + e.getLocalizedMessage() );
1592         }
1593         final Set<String> specs = new HashSet<String>();
1594         final Set<String> paths = new HashSet<String>();
1595         for( int i = 0; i < input_file_properties.length; ++i ) {
1596             if ( !PhyloXmlUtil.TAXOMONY_CODE_PATTERN.matcher( input_file_properties[ i ][ 1 ] ).matches() ) {
1597                 ForesterUtil.fatalError( surfacing.PRG_NAME, "illegal format for species code: "
1598                         + input_file_properties[ i ][ 1 ] );
1599             }
1600             if ( specs.contains( input_file_properties[ i ][ 1 ] ) ) {
1601                 ForesterUtil.fatalError( surfacing.PRG_NAME, "species code " + input_file_properties[ i ][ 1 ]
1602                         + " is not unique" );
1603             }
1604             specs.add( input_file_properties[ i ][ 1 ] );
1605             if ( paths.contains( input_file_properties[ i ][ 0 ] ) ) {
1606                 ForesterUtil.fatalError( surfacing.PRG_NAME, "path " + input_file_properties[ i ][ 0 ]
1607                         + " is not unique" );
1608             }
1609             paths.add( input_file_properties[ i ][ 0 ] );
1610             final String error = ForesterUtil.isReadableFile( new File( input_file_properties[ i ][ 0 ] ) );
1611             if ( !ForesterUtil.isEmpty( error ) ) {
1612                 ForesterUtil.fatalError( surfacing.PRG_NAME, error );
1613             }
1614         }
1615         return input_file_properties;
1616     }
1617
1618     public static void processPlusMinusAnalysisOption( final CommandLineArguments cla,
1619                                                        final List<String> high_copy_base,
1620                                                        final List<String> high_copy_target,
1621                                                        final List<String> low_copy,
1622                                                        final List<Object> numbers ) {
1623         if ( cla.isOptionSet( surfacing.PLUS_MINUS_ANALYSIS_OPTION ) ) {
1624             if ( !cla.isOptionValueSet( surfacing.PLUS_MINUS_ANALYSIS_OPTION ) ) {
1625                 ForesterUtil.fatalError( surfacing.PRG_NAME, "no value for 'plus-minus' file: -"
1626                         + surfacing.PLUS_MINUS_ANALYSIS_OPTION + "=<file>" );
1627             }
1628             final File plus_minus_file = new File( cla.getOptionValue( surfacing.PLUS_MINUS_ANALYSIS_OPTION ) );
1629             final String msg = ForesterUtil.isReadableFile( plus_minus_file );
1630             if ( !ForesterUtil.isEmpty( msg ) ) {
1631                 ForesterUtil.fatalError( surfacing.PRG_NAME, "can not read from \"" + plus_minus_file + "\": " + msg );
1632             }
1633             processPlusMinusFile( plus_minus_file, high_copy_base, high_copy_target, low_copy, numbers );
1634         }
1635     }
1636
1637     // First numbers is minimal difference, second is factor.
1638     public static void processPlusMinusFile( final File plus_minus_file,
1639                                              final List<String> high_copy_base,
1640                                              final List<String> high_copy_target,
1641                                              final List<String> low_copy,
1642                                              final List<Object> numbers ) {
1643         Set<String> species_set = null;
1644         int min_diff = surfacing.PLUS_MINUS_ANALYSIS_MIN_DIFF_DEFAULT;
1645         double factor = surfacing.PLUS_MINUS_ANALYSIS_FACTOR_DEFAULT;
1646         try {
1647             species_set = ForesterUtil.file2set( plus_minus_file );
1648         }
1649         catch ( final IOException e ) {
1650             ForesterUtil.fatalError( surfacing.PRG_NAME, e.getMessage() );
1651         }
1652         if ( species_set != null ) {
1653             for( final String species : species_set ) {
1654                 final String species_trimmed = species.substring( 1 );
1655                 if ( species.startsWith( "+" ) ) {
1656                     if ( low_copy.contains( species_trimmed ) ) {
1657                         ForesterUtil.fatalError( surfacing.PRG_NAME,
1658                                                  "species/genome names can not appear with both '+' and '-' suffix, as appears the case for: \""
1659                                                          + species_trimmed + "\"" );
1660                     }
1661                     high_copy_base.add( species_trimmed );
1662                 }
1663                 else if ( species.startsWith( "*" ) ) {
1664                     if ( low_copy.contains( species_trimmed ) ) {
1665                         ForesterUtil.fatalError( surfacing.PRG_NAME,
1666                                                  "species/genome names can not appear with both '*' and '-' suffix, as appears the case for: \""
1667                                                          + species_trimmed + "\"" );
1668                     }
1669                     high_copy_target.add( species_trimmed );
1670                 }
1671                 else if ( species.startsWith( "-" ) ) {
1672                     if ( high_copy_base.contains( species_trimmed ) || high_copy_target.contains( species_trimmed ) ) {
1673                         ForesterUtil.fatalError( surfacing.PRG_NAME,
1674                                                  "species/genome names can not appear with both '+' or '*' and '-' suffix, as appears the case for: \""
1675                                                          + species_trimmed + "\"" );
1676                     }
1677                     low_copy.add( species_trimmed );
1678                 }
1679                 else if ( species.startsWith( "$D" ) ) {
1680                     try {
1681                         min_diff = Integer.parseInt( species.substring( 3 ) );
1682                     }
1683                     catch ( final NumberFormatException e ) {
1684                         ForesterUtil.fatalError( surfacing.PRG_NAME,
1685                                                  "could not parse integer value for minimal difference from: \""
1686                                                          + species.substring( 3 ) + "\"" );
1687                     }
1688                 }
1689                 else if ( species.startsWith( "$F" ) ) {
1690                     try {
1691                         factor = Double.parseDouble( species.substring( 3 ) );
1692                     }
1693                     catch ( final NumberFormatException e ) {
1694                         ForesterUtil.fatalError( surfacing.PRG_NAME, "could not parse double value for factor from: \""
1695                                 + species.substring( 3 ) + "\"" );
1696                     }
1697                 }
1698                 else if ( species.startsWith( "#" ) ) {
1699                     // Comment, ignore.
1700                 }
1701                 else {
1702                     ForesterUtil
1703                             .fatalError( surfacing.PRG_NAME,
1704                                          "species/genome names in 'plus minus' file must begin with '*' (high copy target genome), '+' (high copy base genomes), '-' (low copy genomes), '$D=<integer>' minimal Difference (default is 1), '$F=<double>' factor (default is 1.0), double), or '#' (ignore) suffix, encountered: \""
1705                                                  + species + "\"" );
1706                 }
1707                 numbers.add( new Integer( min_diff + "" ) );
1708                 numbers.add( new Double( factor + "" ) );
1709             }
1710         }
1711         else {
1712             ForesterUtil.fatalError( surfacing.PRG_NAME, "'plus minus' file [" + plus_minus_file + "] appears empty" );
1713         }
1714     }
1715
1716     /*
1717      * species | protein id | n-terminal domain | c-terminal domain | n-terminal domain per domain E-value | c-terminal domain per domain E-value
1718      * 
1719      * 
1720      */
1721     static public StringBuffer proteinToDomainCombinations( final Protein protein,
1722                                                             final String protein_id,
1723                                                             final String separator ) {
1724         final StringBuffer sb = new StringBuffer();
1725         if ( protein.getSpecies() == null ) {
1726             throw new IllegalArgumentException( "species must not be null" );
1727         }
1728         if ( ForesterUtil.isEmpty( protein.getSpecies().getSpeciesId() ) ) {
1729             throw new IllegalArgumentException( "species id must not be empty" );
1730         }
1731         final List<Domain> domains = protein.getProteinDomains();
1732         if ( domains.size() > 1 ) {
1733             final Map<String, Integer> counts = new HashMap<String, Integer>();
1734             for( final Domain domain : domains ) {
1735                 final String id = domain.getDomainId();
1736                 if ( counts.containsKey( id ) ) {
1737                     counts.put( id, counts.get( id ) + 1 );
1738                 }
1739                 else {
1740                     counts.put( id, 1 );
1741                 }
1742             }
1743             final Set<String> dcs = new HashSet<String>();
1744             for( int i = 1; i < domains.size(); ++i ) {
1745                 for( int j = 0; j < i; ++j ) {
1746                     Domain domain_n = domains.get( i );
1747                     Domain domain_c = domains.get( j );
1748                     if ( domain_n.getFrom() > domain_c.getFrom() ) {
1749                         domain_n = domains.get( j );
1750                         domain_c = domains.get( i );
1751                     }
1752                     final String dc = domain_n.getDomainId() + domain_c.getDomainId();
1753                     if ( !dcs.contains( dc ) ) {
1754                         dcs.add( dc );
1755                         sb.append( protein.getSpecies() );
1756                         sb.append( separator );
1757                         sb.append( protein_id );
1758                         sb.append( separator );
1759                         sb.append( domain_n.getDomainId() );
1760                         sb.append( separator );
1761                         sb.append( domain_c.getDomainId() );
1762                         sb.append( separator );
1763                         sb.append( domain_n.getPerDomainEvalue() );
1764                         sb.append( separator );
1765                         sb.append( domain_c.getPerDomainEvalue() );
1766                         sb.append( separator );
1767                         sb.append( counts.get( domain_n.getDomainId() ) );
1768                         sb.append( separator );
1769                         sb.append( counts.get( domain_c.getDomainId() ) );
1770                         sb.append( ForesterUtil.LINE_SEPARATOR );
1771                     }
1772                 }
1773             }
1774         }
1775         else if ( domains.size() == 1 ) {
1776             sb.append( protein.getSpecies() );
1777             sb.append( separator );
1778             sb.append( protein_id );
1779             sb.append( separator );
1780             sb.append( domains.get( 0 ).getDomainId() );
1781             sb.append( separator );
1782             sb.append( separator );
1783             sb.append( domains.get( 0 ).getPerDomainEvalue() );
1784             sb.append( separator );
1785             sb.append( separator );
1786             sb.append( 1 );
1787             sb.append( separator );
1788             sb.append( ForesterUtil.LINE_SEPARATOR );
1789         }
1790         else {
1791             sb.append( protein.getSpecies() );
1792             sb.append( separator );
1793             sb.append( protein_id );
1794             sb.append( separator );
1795             sb.append( separator );
1796             sb.append( separator );
1797             sb.append( separator );
1798             sb.append( separator );
1799             sb.append( separator );
1800             sb.append( ForesterUtil.LINE_SEPARATOR );
1801         }
1802         return sb;
1803     }
1804
1805     public static List<Domain> sortDomainsWithAscendingConfidenceValues( final Protein protein ) {
1806         final List<Domain> domains = new ArrayList<Domain>();
1807         for( final Domain d : protein.getProteinDomains() ) {
1808             domains.add( d );
1809         }
1810         Collections.sort( domains, SurfacingUtil.ASCENDING_CONFIDENCE_VALUE_ORDER );
1811         return domains;
1812     }
1813
1814     public static int storeDomainArchitectures( final String genome,
1815                                                 final SortedMap<String, Set<String>> domain_architecutures,
1816                                                 final List<Protein> protein_list,
1817                                                 final Map<String, Integer> distinct_domain_architecuture_counts ) {
1818         final Set<String> da = new HashSet<String>();
1819         domain_architecutures.put( genome, da );
1820         for( final Protein protein : protein_list ) {
1821             final String da_str = ( ( BasicProtein ) protein ).toDomainArchitectureString( "~", 3, "=" );
1822             if ( !da.contains( da_str ) ) {
1823                 if ( !distinct_domain_architecuture_counts.containsKey( da_str ) ) {
1824                     distinct_domain_architecuture_counts.put( da_str, 1 );
1825                 }
1826                 else {
1827                     distinct_domain_architecuture_counts.put( da_str,
1828                                                               distinct_domain_architecuture_counts.get( da_str ) + 1 );
1829                 }
1830                 da.add( da_str );
1831             }
1832         }
1833         return da.size();
1834     }
1835
1836     public static void writeAllDomainsChangedOnAllSubtrees( final Phylogeny p,
1837                                                             final boolean get_gains,
1838                                                             final String outdir,
1839                                                             final String suffix_for_filename ) throws IOException {
1840         CharacterStateMatrix.GainLossStates state = CharacterStateMatrix.GainLossStates.GAIN;
1841         if ( !get_gains ) {
1842             state = CharacterStateMatrix.GainLossStates.LOSS;
1843         }
1844         final File base_dir = createBaseDirForPerNodeDomainFiles( surfacing.BASE_DIRECTORY_PER_SUBTREE_DOMAIN_GAIN_LOSS_FILES,
1845                                                                   false,
1846                                                                   state,
1847                                                                   outdir );
1848         for( final PhylogenyNodeIterator it = p.iteratorPostorder(); it.hasNext(); ) {
1849             final PhylogenyNode node = it.next();
1850             if ( !node.isExternal() ) {
1851                 final SortedSet<String> domains = collectAllDomainsChangedOnSubtree( node, get_gains );
1852                 if ( domains.size() > 0 ) {
1853                     final Writer writer = ForesterUtil.createBufferedWriter( base_dir + ForesterUtil.FILE_SEPARATOR
1854                             + node.getName() + suffix_for_filename );
1855                     for( final String domain : domains ) {
1856                         writer.write( domain );
1857                         writer.write( ForesterUtil.LINE_SEPARATOR );
1858                     }
1859                     writer.close();
1860                 }
1861             }
1862         }
1863     }
1864
1865     public static void writeBinaryDomainCombinationsFileForGraphAnalysis( final String[][] input_file_properties,
1866                                                                           final File output_dir,
1867                                                                           final GenomeWideCombinableDomains gwcd,
1868                                                                           final int i,
1869                                                                           final GenomeWideCombinableDomainsSortOrder dc_sort_order ) {
1870         File dc_outfile_dot = new File( input_file_properties[ i ][ 1 ]
1871                 + surfacing.DOMAIN_COMBINITONS_OUTPUTFILE_SUFFIX_FOR_GRAPH_ANALYSIS );
1872         if ( output_dir != null ) {
1873             dc_outfile_dot = new File( output_dir + ForesterUtil.FILE_SEPARATOR + dc_outfile_dot );
1874         }
1875         checkForOutputFileWriteability( dc_outfile_dot );
1876         final SortedSet<BinaryDomainCombination> binary_combinations = createSetOfAllBinaryDomainCombinationsPerGenome( gwcd );
1877         try {
1878             final BufferedWriter out_dot = new BufferedWriter( new FileWriter( dc_outfile_dot ) );
1879             for( final BinaryDomainCombination bdc : binary_combinations ) {
1880                 out_dot.write( bdc.toGraphDescribingLanguage( BinaryDomainCombination.OutputFormat.DOT, null, null )
1881                         .toString() );
1882                 out_dot.write( SurfacingConstants.NL );
1883             }
1884             out_dot.close();
1885         }
1886         catch ( final IOException e ) {
1887             ForesterUtil.fatalError( surfacing.PRG_NAME, e.getMessage() );
1888         }
1889         if ( input_file_properties[ i ].length == 3 ) {
1890             ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote binary domain combination for \""
1891                     + input_file_properties[ i ][ 0 ] + "\" (" + input_file_properties[ i ][ 1 ] + ", "
1892                     + input_file_properties[ i ][ 2 ] + ") to: \"" + dc_outfile_dot + "\"" );
1893         }
1894         else {
1895             ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote binary domain combination for \""
1896                     + input_file_properties[ i ][ 0 ] + "\" (" + input_file_properties[ i ][ 1 ] + ") to: \""
1897                     + dc_outfile_dot + "\"" );
1898         }
1899     }
1900
1901     public static void writeBinaryStatesMatrixAsListToFile( final CharacterStateMatrix<CharacterStateMatrix.GainLossStates> matrix,
1902                                                             final CharacterStateMatrix.GainLossStates state,
1903                                                             final String filename,
1904                                                             final String indentifier_characters_separator,
1905                                                             final String character_separator,
1906                                                             final Map<String, String> descriptions ) {
1907         final File outfile = new File( filename );
1908         checkForOutputFileWriteability( outfile );
1909         final SortedSet<String> sorted_ids = new TreeSet<String>();
1910         for( int i = 0; i < matrix.getNumberOfIdentifiers(); ++i ) {
1911             sorted_ids.add( matrix.getIdentifier( i ) );
1912         }
1913         try {
1914             final BufferedWriter out = new BufferedWriter( new FileWriter( outfile ) );
1915             for( final String id : sorted_ids ) {
1916                 out.write( indentifier_characters_separator );
1917                 out.write( "#" + id );
1918                 out.write( indentifier_characters_separator );
1919                 for( int c = 0; c < matrix.getNumberOfCharacters(); ++c ) {
1920                     // Not nice:
1921                     // using null to indicate either UNCHANGED_PRESENT or GAIN.
1922                     if ( ( matrix.getState( id, c ) == state )
1923                             || ( ( state == null ) && ( ( matrix.getState( id, c ) == CharacterStateMatrix.GainLossStates.GAIN ) || ( matrix
1924                                     .getState( id, c ) == CharacterStateMatrix.GainLossStates.UNCHANGED_PRESENT ) ) ) ) {
1925                         out.write( matrix.getCharacter( c ) );
1926                         if ( ( descriptions != null ) && !descriptions.isEmpty()
1927                                 && descriptions.containsKey( matrix.getCharacter( c ) ) ) {
1928                             out.write( "\t" );
1929                             out.write( descriptions.get( matrix.getCharacter( c ) ) );
1930                         }
1931                         out.write( character_separator );
1932                     }
1933                 }
1934             }
1935             out.flush();
1936             out.close();
1937         }
1938         catch ( final IOException e ) {
1939             ForesterUtil.fatalError( surfacing.PRG_NAME, e.getMessage() );
1940         }
1941         ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote characters list: \"" + filename + "\"" );
1942     }
1943
1944     public static void writeBinaryStatesMatrixAsListToFileForBinaryCombinationsForGraphAnalysis( final CharacterStateMatrix<CharacterStateMatrix.GainLossStates> matrix,
1945                                                                                                  final CharacterStateMatrix.GainLossStates state,
1946                                                                                                  final String filename,
1947                                                                                                  final String indentifier_characters_separator,
1948                                                                                                  final String character_separator,
1949                                                                                                  final BinaryDomainCombination.OutputFormat bc_output_format ) {
1950         final File outfile = new File( filename );
1951         checkForOutputFileWriteability( outfile );
1952         final SortedSet<String> sorted_ids = new TreeSet<String>();
1953         for( int i = 0; i < matrix.getNumberOfIdentifiers(); ++i ) {
1954             sorted_ids.add( matrix.getIdentifier( i ) );
1955         }
1956         try {
1957             final BufferedWriter out = new BufferedWriter( new FileWriter( outfile ) );
1958             for( final String id : sorted_ids ) {
1959                 out.write( indentifier_characters_separator );
1960                 out.write( "#" + id );
1961                 out.write( indentifier_characters_separator );
1962                 for( int c = 0; c < matrix.getNumberOfCharacters(); ++c ) {
1963                     // Not nice:
1964                     // using null to indicate either UNCHANGED_PRESENT or GAIN.
1965                     if ( ( matrix.getState( id, c ) == state )
1966                             || ( ( state == null ) && ( ( matrix.getState( id, c ) == CharacterStateMatrix.GainLossStates.GAIN ) || ( matrix
1967                                     .getState( id, c ) == CharacterStateMatrix.GainLossStates.UNCHANGED_PRESENT ) ) ) ) {
1968                         BinaryDomainCombination bdc = null;
1969                         try {
1970                             bdc = BasicBinaryDomainCombination.obtainInstance( matrix.getCharacter( c ) );
1971                         }
1972                         catch ( final Exception e ) {
1973                             ForesterUtil.fatalError( surfacing.PRG_NAME, e.getLocalizedMessage() );
1974                         }
1975                         out.write( bdc.toGraphDescribingLanguage( bc_output_format, null, null ).toString() );
1976                         out.write( character_separator );
1977                     }
1978                 }
1979             }
1980             out.flush();
1981             out.close();
1982         }
1983         catch ( final IOException e ) {
1984             ForesterUtil.fatalError( surfacing.PRG_NAME, e.getMessage() );
1985         }
1986         ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote characters list: \"" + filename + "\"" );
1987     }
1988
1989     public static void writeBinaryStatesMatrixToList( final Map<String, List<GoId>> domain_id_to_go_ids_map,
1990                                                       final Map<GoId, GoTerm> go_id_to_term_map,
1991                                                       final GoNameSpace go_namespace_limit,
1992                                                       final boolean domain_combinations,
1993                                                       final CharacterStateMatrix<CharacterStateMatrix.GainLossStates> matrix,
1994                                                       final CharacterStateMatrix.GainLossStates state,
1995                                                       final String filename,
1996                                                       final String indentifier_characters_separator,
1997                                                       final String character_separator,
1998                                                       final String title_for_html,
1999                                                       final String prefix_for_html,
2000                                                       final Map<String, Set<String>>[] domain_id_to_secondary_features_maps,
2001                                                       final SortedSet<String> all_pfams_encountered,
2002                                                       final SortedSet<String> pfams_gained_or_lost,
2003                                                       final String suffix_for_per_node_events_file,
2004                                                       final Map<String, Integer> tax_code_to_id_map ) {
2005         if ( ( go_namespace_limit != null ) && ( ( go_id_to_term_map == null ) || ( go_id_to_term_map.size() < 1 ) ) ) {
2006             throw new IllegalArgumentException( "attempt to use GO namespace limit without a GO-id to term map" );
2007         }
2008         else if ( ( ( domain_id_to_go_ids_map == null ) || ( domain_id_to_go_ids_map.size() < 1 ) ) ) {
2009             throw new IllegalArgumentException( "attempt to output detailed HTML without a Pfam to GO map" );
2010         }
2011         else if ( ( ( go_id_to_term_map == null ) || ( go_id_to_term_map.size() < 1 ) ) ) {
2012             throw new IllegalArgumentException( "attempt to output detailed HTML without a GO-id to term map" );
2013         }
2014         final File outfile = new File( filename );
2015         checkForOutputFileWriteability( outfile );
2016         final SortedSet<String> sorted_ids = new TreeSet<String>();
2017         for( int i = 0; i < matrix.getNumberOfIdentifiers(); ++i ) {
2018             sorted_ids.add( matrix.getIdentifier( i ) );
2019         }
2020         try {
2021             final Writer out = new BufferedWriter( new FileWriter( outfile ) );
2022             final File per_node_go_mapped_domain_gain_loss_files_base_dir = createBaseDirForPerNodeDomainFiles( surfacing.BASE_DIRECTORY_PER_NODE_DOMAIN_GAIN_LOSS_FILES,
2023                                                                                                                 domain_combinations,
2024                                                                                                                 state,
2025                                                                                                                 filename );
2026             Writer per_node_go_mapped_domain_gain_loss_outfile_writer = null;
2027             File per_node_go_mapped_domain_gain_loss_outfile = null;
2028             int per_node_counter = 0;
2029             out.write( "<html>" );
2030             out.write( SurfacingConstants.NL );
2031             writeHtmlHead( out, title_for_html );
2032             out.write( SurfacingConstants.NL );
2033             out.write( "<body>" );
2034             out.write( SurfacingConstants.NL );
2035             out.write( "<h1>" );
2036             out.write( SurfacingConstants.NL );
2037             out.write( title_for_html );
2038             out.write( SurfacingConstants.NL );
2039             out.write( "</h1>" );
2040             out.write( SurfacingConstants.NL );
2041             out.write( "<table>" );
2042             out.write( SurfacingConstants.NL );
2043             for( final String id : sorted_ids ) {
2044                 final Matcher matcher = PATTERN_SP_STYLE_TAXONOMY.matcher( id );
2045                 if ( matcher.matches() ) {
2046                     continue;
2047                 }
2048                 out.write( "<tr>" );
2049                 out.write( "<td>" );
2050                 out.write( "<a href=\"#" + id + "\">" + id + "</a>" );
2051                 out.write( "</td>" );
2052                 out.write( "</tr>" );
2053                 out.write( SurfacingConstants.NL );
2054             }
2055             out.write( "</table>" );
2056             out.write( SurfacingConstants.NL );
2057             for( final String id : sorted_ids ) {
2058                 final Matcher matcher = PATTERN_SP_STYLE_TAXONOMY.matcher( id );
2059                 if ( matcher.matches() ) {
2060                     continue;
2061                 }
2062                 out.write( SurfacingConstants.NL );
2063                 out.write( "<h2>" );
2064                 out.write( "<a name=\"" + id + "\">" + id + "</a>" );
2065                 writeTaxonomyLinks( out, id, tax_code_to_id_map );
2066                 out.write( "</h2>" );
2067                 out.write( SurfacingConstants.NL );
2068                 out.write( "<table>" );
2069                 out.write( SurfacingConstants.NL );
2070                 out.write( "<tr>" );
2071                 out.write( "<td><b>" );
2072                 out.write( "Pfam domain(s)" );
2073                 out.write( "</b></td><td><b>" );
2074                 out.write( "GO term acc" );
2075                 out.write( "</b></td><td><b>" );
2076                 out.write( "GO term" );
2077                 out.write( "</b></td><td><b>" );
2078                 out.write( "GO namespace" );
2079                 out.write( "</b></td>" );
2080                 out.write( "</tr>" );
2081                 out.write( SurfacingConstants.NL );
2082                 out.write( "</tr>" );
2083                 out.write( SurfacingConstants.NL );
2084                 per_node_counter = 0;
2085                 if ( matrix.getNumberOfCharacters() > 0 ) {
2086                     per_node_go_mapped_domain_gain_loss_outfile = new File( per_node_go_mapped_domain_gain_loss_files_base_dir
2087                             + ForesterUtil.FILE_SEPARATOR + id + suffix_for_per_node_events_file );
2088                     SurfacingUtil.checkForOutputFileWriteability( per_node_go_mapped_domain_gain_loss_outfile );
2089                     per_node_go_mapped_domain_gain_loss_outfile_writer = ForesterUtil
2090                             .createBufferedWriter( per_node_go_mapped_domain_gain_loss_outfile );
2091                 }
2092                 else {
2093                     per_node_go_mapped_domain_gain_loss_outfile = null;
2094                     per_node_go_mapped_domain_gain_loss_outfile_writer = null;
2095                 }
2096                 for( int c = 0; c < matrix.getNumberOfCharacters(); ++c ) {
2097                     // Not nice:
2098                     // using null to indicate either UNCHANGED_PRESENT or GAIN.
2099                     if ( ( matrix.getState( id, c ) == state )
2100                             || ( ( state == null ) && ( ( matrix.getState( id, c ) == CharacterStateMatrix.GainLossStates.UNCHANGED_PRESENT ) || ( matrix
2101                                     .getState( id, c ) == CharacterStateMatrix.GainLossStates.GAIN ) ) ) ) {
2102                         final String character = matrix.getCharacter( c );
2103                         String domain_0 = "";
2104                         String domain_1 = "";
2105                         if ( character.indexOf( BinaryDomainCombination.SEPARATOR ) > 0 ) {
2106                             final String[] s = character.split( BinaryDomainCombination.SEPARATOR );
2107                             if ( s.length != 2 ) {
2108                                 throw new AssertionError( "this should not have happened: unexpected format for domain combination: ["
2109                                         + character + "]" );
2110                             }
2111                             domain_0 = s[ 0 ];
2112                             domain_1 = s[ 1 ];
2113                         }
2114                         else {
2115                             domain_0 = character;
2116                         }
2117                         writeDomainData( domain_id_to_go_ids_map,
2118                                          go_id_to_term_map,
2119                                          go_namespace_limit,
2120                                          out,
2121                                          domain_0,
2122                                          domain_1,
2123                                          prefix_for_html,
2124                                          character_separator,
2125                                          domain_id_to_secondary_features_maps,
2126                                          null );
2127                         all_pfams_encountered.add( domain_0 );
2128                         if ( pfams_gained_or_lost != null ) {
2129                             pfams_gained_or_lost.add( domain_0 );
2130                         }
2131                         if ( !ForesterUtil.isEmpty( domain_1 ) ) {
2132                             all_pfams_encountered.add( domain_1 );
2133                             if ( pfams_gained_or_lost != null ) {
2134                                 pfams_gained_or_lost.add( domain_1 );
2135                             }
2136                         }
2137                         if ( per_node_go_mapped_domain_gain_loss_outfile_writer != null ) {
2138                             writeDomainsToIndividualFilePerTreeNode( per_node_go_mapped_domain_gain_loss_outfile_writer,
2139                                                                      domain_0,
2140                                                                      domain_1 );
2141                             per_node_counter++;
2142                         }
2143                     }
2144                 }
2145                 if ( per_node_go_mapped_domain_gain_loss_outfile_writer != null ) {
2146                     per_node_go_mapped_domain_gain_loss_outfile_writer.close();
2147                     if ( per_node_counter < 1 ) {
2148                         per_node_go_mapped_domain_gain_loss_outfile.delete();
2149                     }
2150                     per_node_counter = 0;
2151                 }
2152                 out.write( "</table>" );
2153                 out.write( SurfacingConstants.NL );
2154                 out.write( "<hr>" );
2155                 out.write( SurfacingConstants.NL );
2156             } // for( final String id : sorted_ids ) {  
2157             out.write( "</body>" );
2158             out.write( SurfacingConstants.NL );
2159             out.write( "</html>" );
2160             out.write( SurfacingConstants.NL );
2161             out.flush();
2162             out.close();
2163         }
2164         catch ( final IOException e ) {
2165             ForesterUtil.fatalError( surfacing.PRG_NAME, e.getMessage() );
2166         }
2167         ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote characters detailed HTML list: \"" + filename + "\"" );
2168     }
2169
2170     public static void writeDomainCombinationsCountsFile( final String[][] input_file_properties,
2171                                                           final File output_dir,
2172                                                           final Writer per_genome_domain_promiscuity_statistics_writer,
2173                                                           final GenomeWideCombinableDomains gwcd,
2174                                                           final int i,
2175                                                           final GenomeWideCombinableDomains.GenomeWideCombinableDomainsSortOrder dc_sort_order ) {
2176         File dc_outfile = new File( input_file_properties[ i ][ 1 ]
2177                 + surfacing.DOMAIN_COMBINITON_COUNTS_OUTPUTFILE_SUFFIX );
2178         if ( output_dir != null ) {
2179             dc_outfile = new File( output_dir + ForesterUtil.FILE_SEPARATOR + dc_outfile );
2180         }
2181         checkForOutputFileWriteability( dc_outfile );
2182         try {
2183             final BufferedWriter out = new BufferedWriter( new FileWriter( dc_outfile ) );
2184             out.write( gwcd.toStringBuilder( dc_sort_order ).toString() );
2185             out.close();
2186         }
2187         catch ( final IOException e ) {
2188             ForesterUtil.fatalError( surfacing.PRG_NAME, e.getMessage() );
2189         }
2190         final DescriptiveStatistics stats = gwcd.getPerGenomeDomainPromiscuityStatistics();
2191         try {
2192             per_genome_domain_promiscuity_statistics_writer.write( input_file_properties[ i ][ 1 ] + "\t" );
2193             per_genome_domain_promiscuity_statistics_writer.write( FORMATTER_3.format( stats.arithmeticMean() ) + "\t" );
2194             if ( stats.getN() < 2 ) {
2195                 per_genome_domain_promiscuity_statistics_writer.write( "n/a" + "\t" );
2196             }
2197             else {
2198                 per_genome_domain_promiscuity_statistics_writer.write( FORMATTER_3.format( stats
2199                         .sampleStandardDeviation() ) + "\t" );
2200             }
2201             per_genome_domain_promiscuity_statistics_writer.write( FORMATTER_3.format( stats.median() ) + "\t" );
2202             per_genome_domain_promiscuity_statistics_writer.write( ( int ) stats.getMin() + "\t" );
2203             per_genome_domain_promiscuity_statistics_writer.write( ( int ) stats.getMax() + "\t" );
2204             per_genome_domain_promiscuity_statistics_writer.write( stats.getN() + "\t" );
2205             final SortedSet<String> mpds = gwcd.getMostPromiscuosDomain();
2206             for( final String mpd : mpds ) {
2207                 per_genome_domain_promiscuity_statistics_writer.write( mpd + " " );
2208             }
2209             per_genome_domain_promiscuity_statistics_writer.write( ForesterUtil.LINE_SEPARATOR );
2210         }
2211         catch ( final IOException e ) {
2212             ForesterUtil.fatalError( surfacing.PRG_NAME, e.getMessage() );
2213         }
2214         if ( input_file_properties[ i ].length == 3 ) {
2215             ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote domain combination counts for \""
2216                     + input_file_properties[ i ][ 0 ] + "\" (" + input_file_properties[ i ][ 1 ] + ", "
2217                     + input_file_properties[ i ][ 2 ] + ") to: \"" + dc_outfile + "\"" );
2218         }
2219         else {
2220             ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote domain combination counts for \""
2221                     + input_file_properties[ i ][ 0 ] + "\" (" + input_file_properties[ i ][ 1 ] + ") to: \""
2222                     + dc_outfile + "\"" );
2223         }
2224     }
2225
2226     public static void writeDomainSimilaritiesToFile( final StringBuilder html_desc,
2227                                                       final StringBuilder html_title,
2228                                                       final Writer simple_tab_writer,
2229                                                       final Writer single_writer,
2230                                                       Map<Character, Writer> split_writers,
2231                                                       final SortedSet<DomainSimilarity> similarities,
2232                                                       final boolean treat_as_binary,
2233                                                       final List<Species> species_order,
2234                                                       final DomainSimilarity.PRINT_OPTION print_option,
2235                                                       final DomainSimilarity.DomainSimilarityScoring scoring,
2236                                                       final boolean verbose,
2237                                                       final Map<String, Integer> tax_code_to_id_map,
2238                                                       final Phylogeny phy,
2239                                                       final Set<String> pos_filter_doms ) throws IOException {
2240         if ( ( single_writer != null ) && ( ( split_writers == null ) || split_writers.isEmpty() ) ) {
2241             split_writers = new HashMap<Character, Writer>();
2242             split_writers.put( '_', single_writer );
2243         }
2244         switch ( print_option ) {
2245             case SIMPLE_TAB_DELIMITED:
2246                 break;
2247             case HTML:
2248                 for( final Character key : split_writers.keySet() ) {
2249                     final Writer w = split_writers.get( key );
2250                     w.write( "<html>" );
2251                     w.write( SurfacingConstants.NL );
2252                     if ( key != '_' ) {
2253                         writeHtmlHead( w, "DC analysis (" + html_title + ") " + key.toString().toUpperCase() );
2254                     }
2255                     else {
2256                         writeHtmlHead( w, "DC analysis (" + html_title + ")" );
2257                     }
2258                     w.write( SurfacingConstants.NL );
2259                     w.write( "<body>" );
2260                     w.write( SurfacingConstants.NL );
2261                     w.write( html_desc.toString() );
2262                     w.write( SurfacingConstants.NL );
2263                     w.write( "<hr>" );
2264                     w.write( SurfacingConstants.NL );
2265                     w.write( "<br>" );
2266                     w.write( SurfacingConstants.NL );
2267                     w.write( "<table>" );
2268                     w.write( SurfacingConstants.NL );
2269                     w.write( "<tr><td><b>Domains:</b></td></tr>" );
2270                     w.write( SurfacingConstants.NL );
2271                 }
2272                 break;
2273         }
2274         //
2275         for( final DomainSimilarity similarity : similarities ) {
2276             if ( ( species_order != null ) && !species_order.isEmpty() ) {
2277                 ( similarity ).setSpeciesOrder( species_order );
2278             }
2279             if ( single_writer != null ) {
2280                 if ( !ForesterUtil.isEmpty( pos_filter_doms ) && pos_filter_doms.contains( similarity.getDomainId() ) ) {
2281                     single_writer.write( "<tr><td><b><a href=\"#" + similarity.getDomainId()
2282                             + "\"><span style=\"color:#00ff00\">" + similarity.getDomainId()
2283                             + "</span></a></b></td></tr>" );
2284                 }
2285                 else {
2286                     single_writer.write( "<tr><td><b><a href=\"#" + similarity.getDomainId() + "\">"
2287                             + similarity.getDomainId() + "</a></b></td></tr>" );
2288                 }
2289                 single_writer.write( SurfacingConstants.NL );
2290             }
2291             else {
2292                 Writer local_writer = split_writers.get( ( similarity.getDomainId().charAt( 0 ) + "" ).toLowerCase()
2293                         .charAt( 0 ) );
2294                 if ( local_writer == null ) {
2295                     local_writer = split_writers.get( '0' );
2296                 }
2297                 if ( !ForesterUtil.isEmpty( pos_filter_doms ) && pos_filter_doms.contains( similarity.getDomainId() ) ) {
2298                     local_writer.write( "<tr><td><b><a href=\"#" + similarity.getDomainId()
2299                             + "\"><span style=\"color:#00ff00\">" + similarity.getDomainId()
2300                             + "</span></a></b></td></tr>" );
2301                 }
2302                 else {
2303                     local_writer.write( "<tr><td><b><a href=\"#" + similarity.getDomainId() + "\">"
2304                             + similarity.getDomainId() + "</a></b></td></tr>" );
2305                 }
2306                 local_writer.write( SurfacingConstants.NL );
2307             }
2308         }
2309         for( final Writer w : split_writers.values() ) {
2310             w.write( "</table>" );
2311             w.write( SurfacingConstants.NL );
2312             w.write( "<hr>" );
2313             w.write( SurfacingConstants.NL );
2314             //
2315             w.write( "<table>" );
2316             w.write( SurfacingConstants.NL );
2317             w.write( "<tr><td><b>" );
2318             w.write( "Species group colors:" );
2319             w.write( "</b></td></tr>" );
2320             w.write( SurfacingConstants.NL );
2321             writeColorLabels( "Deuterostomia", TaxonomyColors.DEUTEROSTOMIA_COLOR, w );
2322             writeColorLabels( "Protostomia", TaxonomyColors.PROTOSTOMIA_COLOR, w );
2323             writeColorLabels( "Cnidaria", TaxonomyColors.CNIDARIA_COLOR, w );
2324             writeColorLabels( "Placozoa", TaxonomyColors.PLACOZOA_COLOR, w );
2325             writeColorLabels( "Ctenophora (comb jellies)", TaxonomyColors.CTENOPHORA_COLOR, w );
2326             writeColorLabels( "Porifera (sponges)", TaxonomyColors.PORIFERA_COLOR, w );
2327             writeColorLabels( "Choanoflagellida", TaxonomyColors.CHOANOFLAGELLIDA, w );
2328             writeColorLabels( "Ichthyosporea & Filasterea", TaxonomyColors.ICHTHYOSPOREA_AND_FILASTEREA, w );
2329             writeColorLabels( "Dikarya (Ascomycota & Basidiomycota, so-called \"higher fungi\")",
2330                               TaxonomyColors.DIKARYA_COLOR,
2331                               w );
2332             writeColorLabels( "other Fungi", TaxonomyColors.OTHER_FUNGI_COLOR, w );
2333             writeColorLabels( "Nucleariidae and Fonticula group",
2334                               TaxonomyColors.NUCLEARIIDAE_AND_FONTICULA_GROUP_COLOR,
2335                               w );
2336             writeColorLabels( "Amoebozoa", TaxonomyColors.AMOEBOZOA_COLOR, w );
2337             writeColorLabels( "Embryophyta (plants)", TaxonomyColors.EMBRYOPHYTA_COLOR, w );
2338             writeColorLabels( "Chlorophyta (green algae)", TaxonomyColors.CHLOROPHYTA_COLOR, w );
2339             writeColorLabels( "Rhodophyta (red algae)", TaxonomyColors.RHODOPHYTA_COLOR, w );
2340             writeColorLabels( "Glaucocystophyce (Glaucophyta)", TaxonomyColors.GLAUCOPHYTA_COLOR, w );
2341             writeColorLabels( "Hacrobia (Cryptophyta & Haptophyceae & Centroheliozoa)",
2342                               TaxonomyColors.HACROBIA_COLOR,
2343                               w );
2344             writeColorLabels( "Stramenopiles (Chromophyta, heterokonts)", TaxonomyColors.STRAMENOPILES_COLOR, w );
2345             writeColorLabels( "Alveolata", TaxonomyColors.ALVEOLATA_COLOR, w );
2346             writeColorLabels( "Rhizaria", TaxonomyColors.RHIZARIA_COLOR, w );
2347             writeColorLabels( "Excavata", TaxonomyColors.EXCAVATA_COLOR, w );
2348             writeColorLabels( "Apusozoa", TaxonomyColors.APUSOZOA_COLOR, w );
2349             writeColorLabels( "Archaea", TaxonomyColors.ARCHAEA_COLOR, w );
2350             writeColorLabels( "Bacteria", TaxonomyColors.BACTERIA_COLOR, w );
2351             w.write( "</table>" );
2352             w.write( SurfacingConstants.NL );
2353             //
2354             w.write( "<hr>" );
2355             w.write( SurfacingConstants.NL );
2356             w.write( "<table>" );
2357             w.write( SurfacingConstants.NL );
2358         }
2359         //
2360         for( final DomainSimilarity similarity : similarities ) {
2361             if ( ( species_order != null ) && !species_order.isEmpty() ) {
2362                 ( similarity ).setSpeciesOrder( species_order );
2363             }
2364             if ( simple_tab_writer != null ) {
2365                 simple_tab_writer.write( similarity.toStringBuffer( PRINT_OPTION.SIMPLE_TAB_DELIMITED,
2366                                                                     tax_code_to_id_map,
2367                                                                     null ).toString() );
2368             }
2369             if ( single_writer != null ) {
2370                 single_writer.write( similarity.toStringBuffer( print_option, tax_code_to_id_map, phy ).toString() );
2371                 single_writer.write( SurfacingConstants.NL );
2372             }
2373             else {
2374                 Writer local_writer = split_writers.get( ( similarity.getDomainId().charAt( 0 ) + "" ).toLowerCase()
2375                         .charAt( 0 ) );
2376                 if ( local_writer == null ) {
2377                     local_writer = split_writers.get( '0' );
2378                 }
2379                 local_writer.write( similarity.toStringBuffer( print_option, tax_code_to_id_map, phy ).toString() );
2380                 local_writer.write( SurfacingConstants.NL );
2381             }
2382         }
2383         switch ( print_option ) {
2384             case HTML:
2385                 for( final Writer w : split_writers.values() ) {
2386                     w.write( SurfacingConstants.NL );
2387                     w.write( "</table>" );
2388                     w.write( SurfacingConstants.NL );
2389                     w.write( "</font>" );
2390                     w.write( SurfacingConstants.NL );
2391                     w.write( "</body>" );
2392                     w.write( SurfacingConstants.NL );
2393                     w.write( "</html>" );
2394                     w.write( SurfacingConstants.NL );
2395                 }
2396                 break;
2397             default:
2398                 break;
2399         }
2400         for( final Writer w : split_writers.values() ) {
2401             w.close();
2402         }
2403     }
2404
2405     public static void writeHtmlHead( final Writer w, final String title ) throws IOException {
2406         w.write( SurfacingConstants.NL );
2407         w.write( "<head>" );
2408         w.write( "<title>" );
2409         w.write( title );
2410         w.write( "</title>" );
2411         w.write( SurfacingConstants.NL );
2412         w.write( "<style>" );
2413         w.write( SurfacingConstants.NL );
2414         w.write( "a:visited { color : #000066; text-decoration : none; }" );
2415         w.write( SurfacingConstants.NL );
2416         w.write( "a:link { color : #000066; text-decoration : none; }" );
2417         w.write( SurfacingConstants.NL );
2418         w.write( "a:active { color : ##000066; text-decoration : none; }" );
2419         w.write( SurfacingConstants.NL );
2420         w.write( "a:hover { color : #FFFFFF; background-color : #000000; text-decoration : none; }" );
2421         w.write( SurfacingConstants.NL );
2422         //
2423         w.write( "a.pl:visited { color : #505050; text-decoration : none; font-size: 7px;}" );
2424         w.write( SurfacingConstants.NL );
2425         w.write( "a.pl:link { color : #505050; text-decoration : none; font-size: 7px;}" );
2426         w.write( SurfacingConstants.NL );
2427         w.write( "a.pl:active { color : #505050; text-decoration : none; font-size: 7px;}" );
2428         w.write( SurfacingConstants.NL );
2429         w.write( "a.pl:hover { color : #FFFFFF; background-color : #000000; text-decoration : none; font-size: 7px;}" );
2430         w.write( SurfacingConstants.NL );
2431         //
2432         w.write( "a.ps:visited { color : #707070; text-decoration : none; font-size: 7px;}" );
2433         w.write( SurfacingConstants.NL );
2434         w.write( "a.ps:link { color : #707070; text-decoration : none; font-size: 7px;}" );
2435         w.write( SurfacingConstants.NL );
2436         w.write( "a.ps:active { color : #707070; text-decoration : none; font-size: 7px;}" );
2437         w.write( SurfacingConstants.NL );
2438         w.write( "a.ps:hover { color : #FFFFFF; background-color : #000000; text-decoration : none; font-size: 7px;}" );
2439         w.write( SurfacingConstants.NL );
2440         //
2441         w.write( "td { text-align: left; vertical-align: top; font-family: Verdana, Arial, Helvetica; font-size: 8pt}" );
2442         w.write( SurfacingConstants.NL );
2443         w.write( "h1 { color : #0000FF; font-family: Verdana, Arial, Helvetica; font-size: 18pt; font-weight: bold }" );
2444         w.write( SurfacingConstants.NL );
2445         w.write( "h2 { color : #0000FF; font-family: Verdana, Arial, Helvetica; font-size: 16pt; font-weight: bold }" );
2446         w.write( SurfacingConstants.NL );
2447         w.write( "</style>" );
2448         w.write( SurfacingConstants.NL );
2449         w.write( "</head>" );
2450         w.write( SurfacingConstants.NL );
2451     }
2452
2453     public static void writeMatrixToFile( final CharacterStateMatrix<?> matrix,
2454                                           final String filename,
2455                                           final Format format ) {
2456         final File outfile = new File( filename );
2457         checkForOutputFileWriteability( outfile );
2458         try {
2459             final BufferedWriter out = new BufferedWriter( new FileWriter( outfile ) );
2460             matrix.toWriter( out, format );
2461             out.flush();
2462             out.close();
2463         }
2464         catch ( final IOException e ) {
2465             ForesterUtil.fatalError( surfacing.PRG_NAME, e.getMessage() );
2466         }
2467         ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote matrix: \"" + filename + "\"" );
2468     }
2469
2470     public static void writeMatrixToFile( final File matrix_outfile, final List<DistanceMatrix> matrices ) {
2471         checkForOutputFileWriteability( matrix_outfile );
2472         try {
2473             final BufferedWriter out = new BufferedWriter( new FileWriter( matrix_outfile ) );
2474             for( final DistanceMatrix distance_matrix : matrices ) {
2475                 out.write( distance_matrix.toStringBuffer( DistanceMatrix.Format.PHYLIP ).toString() );
2476                 out.write( ForesterUtil.LINE_SEPARATOR );
2477                 out.flush();
2478             }
2479             out.close();
2480         }
2481         catch ( final IOException e ) {
2482             ForesterUtil.fatalError( surfacing.PRG_NAME, e.getMessage() );
2483         }
2484         ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote distance matrices to \"" + matrix_outfile + "\"" );
2485     }
2486
2487     public static void writePhylogenyToFile( final Phylogeny phylogeny, final String filename ) {
2488         final PhylogenyWriter writer = new PhylogenyWriter();
2489         try {
2490             writer.toPhyloXML( new File( filename ), phylogeny, 1 );
2491         }
2492         catch ( final IOException e ) {
2493             ForesterUtil.printWarningMessage( surfacing.PRG_NAME, "failed to write phylogeny to \"" + filename + "\": "
2494                     + e );
2495         }
2496         ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote phylogeny to \"" + filename + "\"" );
2497     }
2498
2499     public static void writePresentToNexus( final File output_file,
2500                                             final File positive_filter_file,
2501                                             final SortedSet<String> filter,
2502                                             final List<GenomeWideCombinableDomains> gwcd_list ) {
2503         try {
2504             writeMatrixToFile( DomainParsimonyCalculator.createMatrixOfDomainPresenceOrAbsence( gwcd_list,
2505                                                                                                 positive_filter_file == null ? null
2506                                                                                                         : filter ),
2507                                output_file + surfacing.DOMAINS_PRESENT_NEXUS,
2508                                Format.NEXUS_BINARY );
2509             writeMatrixToFile( DomainParsimonyCalculator.createMatrixOfBinaryDomainCombinationPresenceOrAbsence( gwcd_list ),
2510                                output_file + surfacing.BDC_PRESENT_NEXUS,
2511                                Format.NEXUS_BINARY );
2512         }
2513         catch ( final Exception e ) {
2514             ForesterUtil.fatalError( surfacing.PRG_NAME, e.getLocalizedMessage() );
2515         }
2516     }
2517
2518     public static void writeProteinListsForAllSpecies( final File output_dir,
2519                                                        final SortedMap<Species, List<Protein>> protein_lists_per_species,
2520                                                        final List<GenomeWideCombinableDomains> gwcd_list,
2521                                                        final double domain_e_cutoff,
2522                                                        final Set<String> pos_filter_doms ) {
2523         final SortedSet<String> all_domains = new TreeSet<String>();
2524         for( final GenomeWideCombinableDomains gwcd : gwcd_list ) {
2525             all_domains.addAll( gwcd.getAllDomainIds() );
2526         }
2527         for( final String domain : all_domains ) {
2528             if ( !ForesterUtil.isEmpty( pos_filter_doms ) && !pos_filter_doms.contains( domain ) ) {
2529                 continue;
2530             }
2531             final File out = new File( output_dir + ForesterUtil.FILE_SEPARATOR + domain + surfacing.SEQ_EXTRACT_SUFFIX );
2532             checkForOutputFileWriteability( out );
2533             try {
2534                 final Writer proteins_file_writer = new BufferedWriter( new FileWriter( out ) );
2535                 extractProteinNames( protein_lists_per_species,
2536                                      domain,
2537                                      proteins_file_writer,
2538                                      "\t",
2539                                      surfacing.LIMIT_SPEC_FOR_PROT_EX,
2540                                      domain_e_cutoff );
2541                 proteins_file_writer.close();
2542             }
2543             catch ( final IOException e ) {
2544                 ForesterUtil.fatalError( surfacing.PRG_NAME, e.getLocalizedMessage() );
2545             }
2546             ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote proteins list to \"" + out + "\"" );
2547         }
2548     }
2549
2550     public static void writeTaxonomyLinks( final Writer writer,
2551                                            final String species,
2552                                            final Map<String, Integer> tax_code_to_id_map ) throws IOException {
2553         if ( ( species.length() > 1 ) && ( species.indexOf( '_' ) < 1 ) ) {
2554             writer.write( " [" );
2555             if ( ( tax_code_to_id_map != null ) && tax_code_to_id_map.containsKey( species ) ) {
2556                 writer.write( "<a href=\"" + SurfacingConstants.UNIPROT_TAXONOMY_ID_LINK
2557                         + tax_code_to_id_map.get( species ) + "\" target=\"taxonomy_window\">uniprot</a>" );
2558             }
2559             else {
2560                 writer.write( "<a href=\"" + SurfacingConstants.EOL_LINK + species
2561                         + "\" target=\"taxonomy_window\">eol</a>" );
2562                 writer.write( "|" );
2563                 writer.write( "<a href=\"" + SurfacingConstants.GOOGLE_SCHOLAR_SEARCH + species
2564                         + "\" target=\"taxonomy_window\">scholar</a>" );
2565                 writer.write( "|" );
2566                 writer.write( "<a href=\"" + SurfacingConstants.GOOGLE_WEB_SEARCH_LINK + species
2567                         + "\" target=\"taxonomy_window\">google</a>" );
2568             }
2569             writer.write( "]" );
2570         }
2571     }
2572
2573     private final static void addToCountMap( final Map<String, Integer> map, final String s ) {
2574         if ( map.containsKey( s ) ) {
2575             map.put( s, map.get( s ) + 1 );
2576         }
2577         else {
2578             map.put( s, 1 );
2579         }
2580     }
2581
2582     private static void calculateIndependentDomainCombinationGains( final Phylogeny local_phylogeny_l,
2583                                                                     final String outfilename_for_counts,
2584                                                                     final String outfilename_for_dc,
2585                                                                     final String outfilename_for_dc_for_go_mapping,
2586                                                                     final String outfilename_for_dc_for_go_mapping_unique,
2587                                                                     final String outfilename_for_rank_counts,
2588                                                                     final String outfilename_for_ancestor_species_counts,
2589                                                                     final String outfilename_for_protein_stats,
2590                                                                     final Map<String, DescriptiveStatistics> protein_length_stats_by_dc,
2591                                                                     final Map<String, DescriptiveStatistics> domain_number_stats_by_dc,
2592                                                                     final Map<String, DescriptiveStatistics> domain_length_stats_by_domain ) {
2593         try {
2594             //
2595             //            if ( protein_length_stats_by_dc != null ) {
2596             //                for( final Entry<?, DescriptiveStatistics> entry : protein_length_stats_by_dc.entrySet() ) {
2597             //                    System.out.print( entry.getKey().toString() );
2598             //                    System.out.print( ": " );
2599             //                    double[] a = entry.getValue().getDataAsDoubleArray();
2600             //                    for( int i = 0; i < a.length; i++ ) {
2601             //                        System.out.print( a[ i ] + " " );
2602             //                    }
2603             //                    System.out.println();
2604             //                }
2605             //            }
2606             //            if ( domain_number_stats_by_dc != null ) {
2607             //                for( final Entry<?, DescriptiveStatistics> entry : domain_number_stats_by_dc.entrySet() ) {
2608             //                    System.out.print( entry.getKey().toString() );
2609             //                    System.out.print( ": " );
2610             //                    double[] a = entry.getValue().getDataAsDoubleArray();
2611             //                    for( int i = 0; i < a.length; i++ ) {
2612             //                        System.out.print( a[ i ] + " " );
2613             //                    }
2614             //                    System.out.println();
2615             //                }
2616             //            }
2617             //
2618             final BufferedWriter out_counts = new BufferedWriter( new FileWriter( outfilename_for_counts ) );
2619             final BufferedWriter out_dc = new BufferedWriter( new FileWriter( outfilename_for_dc ) );
2620             final BufferedWriter out_dc_for_go_mapping = new BufferedWriter( new FileWriter( outfilename_for_dc_for_go_mapping ) );
2621             final BufferedWriter out_dc_for_go_mapping_unique = new BufferedWriter( new FileWriter( outfilename_for_dc_for_go_mapping_unique ) );
2622             final SortedMap<String, Integer> dc_gain_counts = new TreeMap<String, Integer>();
2623             for( final PhylogenyNodeIterator it = local_phylogeny_l.iteratorPostorder(); it.hasNext(); ) {
2624                 final PhylogenyNode n = it.next();
2625                 final Set<String> gained_dc = n.getNodeData().getBinaryCharacters().getGainedCharacters();
2626                 for( final String dc : gained_dc ) {
2627                     if ( dc_gain_counts.containsKey( dc ) ) {
2628                         dc_gain_counts.put( dc, dc_gain_counts.get( dc ) + 1 );
2629                     }
2630                     else {
2631                         dc_gain_counts.put( dc, 1 );
2632                     }
2633                 }
2634             }
2635             final SortedMap<Integer, Integer> histogram = new TreeMap<Integer, Integer>();
2636             final SortedMap<Integer, StringBuilder> domain_lists = new TreeMap<Integer, StringBuilder>();
2637             final SortedMap<Integer, DescriptiveStatistics> dc_reapp_counts_to_protein_length_stats = new TreeMap<Integer, DescriptiveStatistics>();
2638             final SortedMap<Integer, DescriptiveStatistics> dc_reapp_counts_to_domain_number_stats = new TreeMap<Integer, DescriptiveStatistics>();
2639             final SortedMap<Integer, DescriptiveStatistics> dc_reapp_counts_to_domain_lengths_stats = new TreeMap<Integer, DescriptiveStatistics>();
2640             final SortedMap<Integer, PriorityQueue<String>> domain_lists_go = new TreeMap<Integer, PriorityQueue<String>>();
2641             final SortedMap<Integer, SortedSet<String>> domain_lists_go_unique = new TreeMap<Integer, SortedSet<String>>();
2642             final Set<String> dcs = dc_gain_counts.keySet();
2643             final SortedSet<String> more_than_once = new TreeSet<String>();
2644             DescriptiveStatistics gained_once_lengths_stats = new BasicDescriptiveStatistics();
2645             DescriptiveStatistics gained_once_domain_count_stats = new BasicDescriptiveStatistics();
2646             DescriptiveStatistics gained_multiple_times_lengths_stats = new BasicDescriptiveStatistics();
2647             final DescriptiveStatistics gained_multiple_times_domain_count_stats = new BasicDescriptiveStatistics();
2648             long gained_multiple_times_domain_length_sum = 0;
2649             long gained_once_domain_length_sum = 0;
2650             long gained_multiple_times_domain_length_count = 0;
2651             long gained_once_domain_length_count = 0;
2652             for( final String dc : dcs ) {
2653                 final int count = dc_gain_counts.get( dc );
2654                 if ( histogram.containsKey( count ) ) {
2655                     histogram.put( count, histogram.get( count ) + 1 );
2656                     domain_lists.get( count ).append( ", " + dc );
2657                     domain_lists_go.get( count ).addAll( splitDomainCombination( dc ) );
2658                     domain_lists_go_unique.get( count ).addAll( splitDomainCombination( dc ) );
2659                 }
2660                 else {
2661                     histogram.put( count, 1 );
2662                     domain_lists.put( count, new StringBuilder( dc ) );
2663                     final PriorityQueue<String> q = new PriorityQueue<String>();
2664                     q.addAll( splitDomainCombination( dc ) );
2665                     domain_lists_go.put( count, q );
2666                     final SortedSet<String> set = new TreeSet<String>();
2667                     set.addAll( splitDomainCombination( dc ) );
2668                     domain_lists_go_unique.put( count, set );
2669                 }
2670                 if ( protein_length_stats_by_dc != null ) {
2671                     if ( !dc_reapp_counts_to_protein_length_stats.containsKey( count ) ) {
2672                         dc_reapp_counts_to_protein_length_stats.put( count, new BasicDescriptiveStatistics() );
2673                     }
2674                     dc_reapp_counts_to_protein_length_stats.get( count ).addValue( protein_length_stats_by_dc.get( dc )
2675                             .arithmeticMean() );
2676                 }
2677                 if ( domain_number_stats_by_dc != null ) {
2678                     if ( !dc_reapp_counts_to_domain_number_stats.containsKey( count ) ) {
2679                         dc_reapp_counts_to_domain_number_stats.put( count, new BasicDescriptiveStatistics() );
2680                     }
2681                     dc_reapp_counts_to_domain_number_stats.get( count ).addValue( domain_number_stats_by_dc.get( dc )
2682                             .arithmeticMean() );
2683                 }
2684                 if ( domain_length_stats_by_domain != null ) {
2685                     if ( !dc_reapp_counts_to_domain_lengths_stats.containsKey( count ) ) {
2686                         dc_reapp_counts_to_domain_lengths_stats.put( count, new BasicDescriptiveStatistics() );
2687                     }
2688                     final String[] ds = dc.split( "=" );
2689                     dc_reapp_counts_to_domain_lengths_stats.get( count ).addValue( domain_length_stats_by_domain
2690                             .get( ds[ 0 ] ).arithmeticMean() );
2691                     dc_reapp_counts_to_domain_lengths_stats.get( count ).addValue( domain_length_stats_by_domain
2692                             .get( ds[ 1 ] ).arithmeticMean() );
2693                 }
2694                 if ( count > 1 ) {
2695                     more_than_once.add( dc );
2696                     if ( protein_length_stats_by_dc != null ) {
2697                         final DescriptiveStatistics s = protein_length_stats_by_dc.get( dc );
2698                         for( final double element : s.getData() ) {
2699                             gained_multiple_times_lengths_stats.addValue( element );
2700                         }
2701                     }
2702                     if ( domain_number_stats_by_dc != null ) {
2703                         final DescriptiveStatistics s = domain_number_stats_by_dc.get( dc );
2704                         for( final double element : s.getData() ) {
2705                             gained_multiple_times_domain_count_stats.addValue( element );
2706                         }
2707                     }
2708                     if ( domain_length_stats_by_domain != null ) {
2709                         final String[] ds = dc.split( "=" );
2710                         final DescriptiveStatistics s0 = domain_length_stats_by_domain.get( ds[ 0 ] );
2711                         final DescriptiveStatistics s1 = domain_length_stats_by_domain.get( ds[ 1 ] );
2712                         for( final double element : s0.getData() ) {
2713                             gained_multiple_times_domain_length_sum += element;
2714                             ++gained_multiple_times_domain_length_count;
2715                         }
2716                         for( final double element : s1.getData() ) {
2717                             gained_multiple_times_domain_length_sum += element;
2718                             ++gained_multiple_times_domain_length_count;
2719                         }
2720                     }
2721                 }
2722                 else {
2723                     if ( protein_length_stats_by_dc != null ) {
2724                         final DescriptiveStatistics s = protein_length_stats_by_dc.get( dc );
2725                         for( final double element : s.getData() ) {
2726                             gained_once_lengths_stats.addValue( element );
2727                         }
2728                     }
2729                     if ( domain_number_stats_by_dc != null ) {
2730                         final DescriptiveStatistics s = domain_number_stats_by_dc.get( dc );
2731                         for( final double element : s.getData() ) {
2732                             gained_once_domain_count_stats.addValue( element );
2733                         }
2734                     }
2735                     if ( domain_length_stats_by_domain != null ) {
2736                         final String[] ds = dc.split( "=" );
2737                         final DescriptiveStatistics s0 = domain_length_stats_by_domain.get( ds[ 0 ] );
2738                         final DescriptiveStatistics s1 = domain_length_stats_by_domain.get( ds[ 1 ] );
2739                         for( final double element : s0.getData() ) {
2740                             gained_once_domain_length_sum += element;
2741                             ++gained_once_domain_length_count;
2742                         }
2743                         for( final double element : s1.getData() ) {
2744                             gained_once_domain_length_sum += element;
2745                             ++gained_once_domain_length_count;
2746                         }
2747                     }
2748                 }
2749             }
2750             final Set<Integer> histogram_keys = histogram.keySet();
2751             for( final Integer histogram_key : histogram_keys ) {
2752                 final int count = histogram.get( histogram_key );
2753                 final StringBuilder dc = domain_lists.get( histogram_key );
2754                 out_counts.write( histogram_key + "\t" + count + ForesterUtil.LINE_SEPARATOR );
2755                 out_dc.write( histogram_key + "\t" + dc + ForesterUtil.LINE_SEPARATOR );
2756                 out_dc_for_go_mapping.write( "#" + histogram_key + ForesterUtil.LINE_SEPARATOR );
2757                 final Object[] sorted = domain_lists_go.get( histogram_key ).toArray();
2758                 Arrays.sort( sorted );
2759                 for( final Object domain : sorted ) {
2760                     out_dc_for_go_mapping.write( domain + ForesterUtil.LINE_SEPARATOR );
2761                 }
2762                 out_dc_for_go_mapping_unique.write( "#" + histogram_key + ForesterUtil.LINE_SEPARATOR );
2763                 for( final String domain : domain_lists_go_unique.get( histogram_key ) ) {
2764                     out_dc_for_go_mapping_unique.write( domain + ForesterUtil.LINE_SEPARATOR );
2765                 }
2766             }
2767             out_counts.close();
2768             out_dc.close();
2769             out_dc_for_go_mapping.close();
2770             out_dc_for_go_mapping_unique.close();
2771             final SortedMap<String, Integer> lca_rank_counts = new TreeMap<String, Integer>();
2772             final SortedMap<String, Integer> lca_ancestor_species_counts = new TreeMap<String, Integer>();
2773             for( final String dc : more_than_once ) {
2774                 final List<PhylogenyNode> nodes = new ArrayList<PhylogenyNode>();
2775                 for( final PhylogenyNodeIterator it = local_phylogeny_l.iteratorExternalForward(); it.hasNext(); ) {
2776                     final PhylogenyNode n = it.next();
2777                     if ( n.getNodeData().getBinaryCharacters().getGainedCharacters().contains( dc ) ) {
2778                         nodes.add( n );
2779                     }
2780                 }
2781                 for( int i = 0; i < ( nodes.size() - 1 ); ++i ) {
2782                     for( int j = i + 1; j < nodes.size(); ++j ) {
2783                         final PhylogenyNode lca = PhylogenyMethods.calculateLCA( nodes.get( i ), nodes.get( j ) );
2784                         String rank = "unknown";
2785                         if ( lca.getNodeData().isHasTaxonomy()
2786                                 && !ForesterUtil.isEmpty( lca.getNodeData().getTaxonomy().getRank() ) ) {
2787                             rank = lca.getNodeData().getTaxonomy().getRank();
2788                         }
2789                         addToCountMap( lca_rank_counts, rank );
2790                         String lca_species;
2791                         if ( lca.getNodeData().isHasTaxonomy()
2792                                 && !ForesterUtil.isEmpty( lca.getNodeData().getTaxonomy().getScientificName() ) ) {
2793                             lca_species = lca.getNodeData().getTaxonomy().getScientificName();
2794                         }
2795                         else if ( lca.getNodeData().isHasTaxonomy()
2796                                 && !ForesterUtil.isEmpty( lca.getNodeData().getTaxonomy().getCommonName() ) ) {
2797                             lca_species = lca.getNodeData().getTaxonomy().getCommonName();
2798                         }
2799                         else {
2800                             lca_species = lca.getName();
2801                         }
2802                         addToCountMap( lca_ancestor_species_counts, lca_species );
2803                     }
2804                 }
2805             }
2806             final BufferedWriter out_for_rank_counts = new BufferedWriter( new FileWriter( outfilename_for_rank_counts ) );
2807             final BufferedWriter out_for_ancestor_species_counts = new BufferedWriter( new FileWriter( outfilename_for_ancestor_species_counts ) );
2808             ForesterUtil.map2writer( out_for_rank_counts, lca_rank_counts, "\t", ForesterUtil.LINE_SEPARATOR );
2809             ForesterUtil.map2writer( out_for_ancestor_species_counts,
2810                                      lca_ancestor_species_counts,
2811                                      "\t",
2812                                      ForesterUtil.LINE_SEPARATOR );
2813             out_for_rank_counts.close();
2814             out_for_ancestor_species_counts.close();
2815             if ( !ForesterUtil.isEmpty( outfilename_for_protein_stats )
2816                     && ( ( domain_length_stats_by_domain != null ) || ( protein_length_stats_by_dc != null ) || ( domain_number_stats_by_dc != null ) ) ) {
2817                 final BufferedWriter w = new BufferedWriter( new FileWriter( outfilename_for_protein_stats ) );
2818                 w.write( "Domain Lengths: " );
2819                 w.write( "\n" );
2820                 if ( domain_length_stats_by_domain != null ) {
2821                     for( final Entry<Integer, DescriptiveStatistics> entry : dc_reapp_counts_to_domain_lengths_stats
2822                             .entrySet() ) {
2823                         w.write( entry.getKey().toString() );
2824                         w.write( "\t" + entry.getValue().arithmeticMean() );
2825                         w.write( "\t" + entry.getValue().median() );
2826                         w.write( "\n" );
2827                     }
2828                 }
2829                 w.flush();
2830                 w.write( "\n" );
2831                 w.write( "\n" );
2832                 w.write( "Protein Lengths: " );
2833                 w.write( "\n" );
2834                 if ( protein_length_stats_by_dc != null ) {
2835                     for( final Entry<Integer, DescriptiveStatistics> entry : dc_reapp_counts_to_protein_length_stats
2836                             .entrySet() ) {
2837                         w.write( entry.getKey().toString() );
2838                         w.write( "\t" + entry.getValue().arithmeticMean() );
2839                         w.write( "\t" + entry.getValue().median() );
2840                         w.write( "\n" );
2841                     }
2842                 }
2843                 w.flush();
2844                 w.write( "\n" );
2845                 w.write( "\n" );
2846                 w.write( "Number of domains: " );
2847                 w.write( "\n" );
2848                 if ( domain_number_stats_by_dc != null ) {
2849                     for( final Entry<Integer, DescriptiveStatistics> entry : dc_reapp_counts_to_domain_number_stats
2850                             .entrySet() ) {
2851                         w.write( entry.getKey().toString() );
2852                         w.write( "\t" + entry.getValue().arithmeticMean() );
2853                         w.write( "\t" + entry.getValue().median() );
2854                         w.write( "\n" );
2855                     }
2856                 }
2857                 w.flush();
2858                 w.write( "\n" );
2859                 w.write( "\n" );
2860                 w.write( "Gained once, domain lengths:" );
2861                 w.write( "\n" );
2862                 w.write( "N: " + gained_once_domain_length_count );
2863                 w.write( "\n" );
2864                 w.write( "Avg: " + ( ( double ) gained_once_domain_length_sum / gained_once_domain_length_count ) );
2865                 w.write( "\n" );
2866                 w.write( "\n" );
2867                 w.write( "Gained multiple times, domain lengths:" );
2868                 w.write( "\n" );
2869                 w.write( "N: " + gained_multiple_times_domain_length_count );
2870                 w.write( "\n" );
2871                 w.write( "Avg: "
2872                         + ( ( double ) gained_multiple_times_domain_length_sum / gained_multiple_times_domain_length_count ) );
2873                 w.write( "\n" );
2874                 w.write( "\n" );
2875                 w.write( "\n" );
2876                 w.write( "\n" );
2877                 w.write( "Gained once, protein lengths:" );
2878                 w.write( "\n" );
2879                 w.write( gained_once_lengths_stats.toString() );
2880                 gained_once_lengths_stats = null;
2881                 w.write( "\n" );
2882                 w.write( "\n" );
2883                 w.write( "Gained once, domain counts:" );
2884                 w.write( "\n" );
2885                 w.write( gained_once_domain_count_stats.toString() );
2886                 gained_once_domain_count_stats = null;
2887                 w.write( "\n" );
2888                 w.write( "\n" );
2889                 w.write( "Gained multiple times, protein lengths:" );
2890                 w.write( "\n" );
2891                 w.write( gained_multiple_times_lengths_stats.toString() );
2892                 gained_multiple_times_lengths_stats = null;
2893                 w.write( "\n" );
2894                 w.write( "\n" );
2895                 w.write( "Gained multiple times, domain counts:" );
2896                 w.write( "\n" );
2897                 w.write( gained_multiple_times_domain_count_stats.toString() );
2898                 w.flush();
2899                 w.close();
2900             }
2901         }
2902         catch ( final IOException e ) {
2903             ForesterUtil.printWarningMessage( surfacing.PRG_NAME, "Failure to write: " + e );
2904         }
2905         ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote independent domain combination gains fitch counts to ["
2906                 + outfilename_for_counts + "]" );
2907         ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote independent domain combination gains fitch lists to ["
2908                 + outfilename_for_dc + "]" );
2909         ForesterUtil.programMessage( surfacing.PRG_NAME,
2910                                      "Wrote independent domain combination gains fitch lists to (for GO mapping) ["
2911                                              + outfilename_for_dc_for_go_mapping + "]" );
2912         ForesterUtil.programMessage( surfacing.PRG_NAME,
2913                                      "Wrote independent domain combination gains fitch lists to (for GO mapping, unique) ["
2914                                              + outfilename_for_dc_for_go_mapping_unique + "]" );
2915     }
2916
2917     private static SortedSet<String> collectAllDomainsChangedOnSubtree( final PhylogenyNode subtree_root,
2918                                                                         final boolean get_gains ) {
2919         final SortedSet<String> domains = new TreeSet<String>();
2920         for( final PhylogenyNode descendant : PhylogenyMethods.getAllDescendants( subtree_root ) ) {
2921             final BinaryCharacters chars = descendant.getNodeData().getBinaryCharacters();
2922             if ( get_gains ) {
2923                 domains.addAll( chars.getGainedCharacters() );
2924             }
2925             else {
2926                 domains.addAll( chars.getLostCharacters() );
2927             }
2928         }
2929         return domains;
2930     }
2931
2932     private static File createBaseDirForPerNodeDomainFiles( final String base_dir,
2933                                                             final boolean domain_combinations,
2934                                                             final CharacterStateMatrix.GainLossStates state,
2935                                                             final String outfile ) {
2936         File per_node_go_mapped_domain_gain_loss_files_base_dir = new File( new File( outfile ).getParent()
2937                 + ForesterUtil.FILE_SEPARATOR + base_dir );
2938         if ( !per_node_go_mapped_domain_gain_loss_files_base_dir.exists() ) {
2939             per_node_go_mapped_domain_gain_loss_files_base_dir.mkdir();
2940         }
2941         if ( domain_combinations ) {
2942             per_node_go_mapped_domain_gain_loss_files_base_dir = new File( per_node_go_mapped_domain_gain_loss_files_base_dir
2943                     + ForesterUtil.FILE_SEPARATOR + "DC" );
2944         }
2945         else {
2946             per_node_go_mapped_domain_gain_loss_files_base_dir = new File( per_node_go_mapped_domain_gain_loss_files_base_dir
2947                     + ForesterUtil.FILE_SEPARATOR + "DOMAINS" );
2948         }
2949         if ( !per_node_go_mapped_domain_gain_loss_files_base_dir.exists() ) {
2950             per_node_go_mapped_domain_gain_loss_files_base_dir.mkdir();
2951         }
2952         if ( state == GainLossStates.GAIN ) {
2953             per_node_go_mapped_domain_gain_loss_files_base_dir = new File( per_node_go_mapped_domain_gain_loss_files_base_dir
2954                     + ForesterUtil.FILE_SEPARATOR + "GAINS" );
2955         }
2956         else if ( state == GainLossStates.LOSS ) {
2957             per_node_go_mapped_domain_gain_loss_files_base_dir = new File( per_node_go_mapped_domain_gain_loss_files_base_dir
2958                     + ForesterUtil.FILE_SEPARATOR + "LOSSES" );
2959         }
2960         else {
2961             per_node_go_mapped_domain_gain_loss_files_base_dir = new File( per_node_go_mapped_domain_gain_loss_files_base_dir
2962                     + ForesterUtil.FILE_SEPARATOR + "PRESENT" );
2963         }
2964         if ( !per_node_go_mapped_domain_gain_loss_files_base_dir.exists() ) {
2965             per_node_go_mapped_domain_gain_loss_files_base_dir.mkdir();
2966         }
2967         return per_node_go_mapped_domain_gain_loss_files_base_dir;
2968     }
2969
2970     private static SortedSet<BinaryDomainCombination> createSetOfAllBinaryDomainCombinationsPerGenome( final GenomeWideCombinableDomains gwcd ) {
2971         final SortedMap<String, CombinableDomains> cds = gwcd.getAllCombinableDomainsIds();
2972         final SortedSet<BinaryDomainCombination> binary_combinations = new TreeSet<BinaryDomainCombination>();
2973         for( final String domain_id : cds.keySet() ) {
2974             final CombinableDomains cd = cds.get( domain_id );
2975             binary_combinations.addAll( cd.toBinaryDomainCombinations() );
2976         }
2977         return binary_combinations;
2978     }
2979
2980     private static void printSomeStats( final DescriptiveStatistics stats, final AsciiHistogram histo, final Writer w )
2981             throws IOException {
2982         w.write( "<hr>" );
2983         w.write( "<br>" );
2984         w.write( SurfacingConstants.NL );
2985         w.write( "<tt><pre>" );
2986         w.write( SurfacingConstants.NL );
2987         if ( histo != null ) {
2988             w.write( histo.toStringBuffer( 20, '|', 40, 5 ).toString() );
2989             w.write( SurfacingConstants.NL );
2990         }
2991         w.write( "</pre></tt>" );
2992         w.write( SurfacingConstants.NL );
2993         w.write( "<table>" );
2994         w.write( SurfacingConstants.NL );
2995         w.write( "<tr><td>N: </td><td>" + stats.getN() + "</td></tr>" );
2996         w.write( SurfacingConstants.NL );
2997         w.write( "<tr><td>Min: </td><td>" + stats.getMin() + "</td></tr>" );
2998         w.write( SurfacingConstants.NL );
2999         w.write( "<tr><td>Max: </td><td>" + stats.getMax() + "</td></tr>" );
3000         w.write( SurfacingConstants.NL );
3001         w.write( "<tr><td>Mean: </td><td>" + stats.arithmeticMean() + "</td></tr>" );
3002         w.write( SurfacingConstants.NL );
3003         if ( stats.getN() > 1 ) {
3004             w.write( "<tr><td>SD: </td><td>" + stats.sampleStandardDeviation() + "</td></tr>" );
3005         }
3006         else {
3007             w.write( "<tr><td>SD: </td><td>n/a</td></tr>" );
3008         }
3009         w.write( SurfacingConstants.NL );
3010         w.write( "</table>" );
3011         w.write( SurfacingConstants.NL );
3012         w.write( "<br>" );
3013         w.write( SurfacingConstants.NL );
3014     }
3015
3016     private static List<String> splitDomainCombination( final String dc ) {
3017         final String[] s = dc.split( "=" );
3018         if ( s.length != 2 ) {
3019             ForesterUtil.printErrorMessage( surfacing.PRG_NAME, "Stringyfied domain combination has illegal format: "
3020                     + dc );
3021             System.exit( -1 );
3022         }
3023         final List<String> l = new ArrayList<String>( 2 );
3024         l.add( s[ 0 ] );
3025         l.add( s[ 1 ] );
3026         return l;
3027     }
3028
3029     private static void writeAllEncounteredPfamsToFile( final Map<String, List<GoId>> domain_id_to_go_ids_map,
3030                                                         final Map<GoId, GoTerm> go_id_to_term_map,
3031                                                         final String outfile_name,
3032                                                         final SortedSet<String> all_pfams_encountered ) {
3033         final File all_pfams_encountered_file = new File( outfile_name + surfacing.ALL_PFAMS_ENCOUNTERED_SUFFIX );
3034         final File all_pfams_encountered_with_go_annotation_file = new File( outfile_name
3035                 + surfacing.ALL_PFAMS_ENCOUNTERED_WITH_GO_ANNOTATION_SUFFIX );
3036         final File encountered_pfams_summary_file = new File( outfile_name + surfacing.ENCOUNTERED_PFAMS_SUMMARY_SUFFIX );
3037         int biological_process_counter = 0;
3038         int cellular_component_counter = 0;
3039         int molecular_function_counter = 0;
3040         int pfams_with_mappings_counter = 0;
3041         int pfams_without_mappings_counter = 0;
3042         int pfams_without_mappings_to_bp_or_mf_counter = 0;
3043         int pfams_with_mappings_to_bp_or_mf_counter = 0;
3044         try {
3045             final Writer all_pfams_encountered_writer = new BufferedWriter( new FileWriter( all_pfams_encountered_file ) );
3046             final Writer all_pfams_encountered_with_go_annotation_writer = new BufferedWriter( new FileWriter( all_pfams_encountered_with_go_annotation_file ) );
3047             final Writer summary_writer = new BufferedWriter( new FileWriter( encountered_pfams_summary_file ) );
3048             summary_writer.write( "# Pfam to GO mapping summary" );
3049             summary_writer.write( ForesterUtil.LINE_SEPARATOR );
3050             summary_writer.write( "# Actual summary is at the end of this file." );
3051             summary_writer.write( ForesterUtil.LINE_SEPARATOR );
3052             summary_writer.write( "# Encountered Pfams without a GO mapping:" );
3053             summary_writer.write( ForesterUtil.LINE_SEPARATOR );
3054             for( final String pfam : all_pfams_encountered ) {
3055                 all_pfams_encountered_writer.write( pfam );
3056                 all_pfams_encountered_writer.write( ForesterUtil.LINE_SEPARATOR );
3057                 final String domain_id = new String( pfam );
3058                 if ( domain_id_to_go_ids_map.containsKey( domain_id ) ) {
3059                     ++pfams_with_mappings_counter;
3060                     all_pfams_encountered_with_go_annotation_writer.write( pfam );
3061                     all_pfams_encountered_with_go_annotation_writer.write( ForesterUtil.LINE_SEPARATOR );
3062                     final List<GoId> go_ids = domain_id_to_go_ids_map.get( domain_id );
3063                     boolean maps_to_bp = false;
3064                     boolean maps_to_cc = false;
3065                     boolean maps_to_mf = false;
3066                     for( final GoId go_id : go_ids ) {
3067                         final GoTerm go_term = go_id_to_term_map.get( go_id );
3068                         if ( go_term.getGoNameSpace().isBiologicalProcess() ) {
3069                             maps_to_bp = true;
3070                         }
3071                         else if ( go_term.getGoNameSpace().isCellularComponent() ) {
3072                             maps_to_cc = true;
3073                         }
3074                         else if ( go_term.getGoNameSpace().isMolecularFunction() ) {
3075                             maps_to_mf = true;
3076                         }
3077                     }
3078                     if ( maps_to_bp ) {
3079                         ++biological_process_counter;
3080                     }
3081                     if ( maps_to_cc ) {
3082                         ++cellular_component_counter;
3083                     }
3084                     if ( maps_to_mf ) {
3085                         ++molecular_function_counter;
3086                     }
3087                     if ( maps_to_bp || maps_to_mf ) {
3088                         ++pfams_with_mappings_to_bp_or_mf_counter;
3089                     }
3090                     else {
3091                         ++pfams_without_mappings_to_bp_or_mf_counter;
3092                     }
3093                 }
3094                 else {
3095                     ++pfams_without_mappings_to_bp_or_mf_counter;
3096                     ++pfams_without_mappings_counter;
3097                     summary_writer.write( pfam );
3098                     summary_writer.write( ForesterUtil.LINE_SEPARATOR );
3099                 }
3100             }
3101             all_pfams_encountered_writer.close();
3102             all_pfams_encountered_with_go_annotation_writer.close();
3103             ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote all [" + all_pfams_encountered.size()
3104                     + "] encountered Pfams to: \"" + all_pfams_encountered_file + "\"" );
3105             ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote all [" + pfams_with_mappings_counter
3106                     + "] encountered Pfams with GO mappings to: \"" + all_pfams_encountered_with_go_annotation_file
3107                     + "\"" );
3108             ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote summary (including all ["
3109                     + pfams_without_mappings_counter + "] encountered Pfams without GO mappings) to: \""
3110                     + encountered_pfams_summary_file + "\"" );
3111             ForesterUtil.programMessage( surfacing.PRG_NAME, "Sum of Pfams encountered                : "
3112                     + all_pfams_encountered.size() );
3113             ForesterUtil.programMessage( surfacing.PRG_NAME, "Pfams without a mapping                 : "
3114                     + pfams_without_mappings_counter + " ["
3115                     + ( ( 100 * pfams_without_mappings_counter ) / all_pfams_encountered.size() ) + "%]" );
3116             ForesterUtil.programMessage( surfacing.PRG_NAME, "Pfams without mapping to proc. or func. : "
3117                     + pfams_without_mappings_to_bp_or_mf_counter + " ["
3118                     + ( ( 100 * pfams_without_mappings_to_bp_or_mf_counter ) / all_pfams_encountered.size() ) + "%]" );
3119             ForesterUtil.programMessage( surfacing.PRG_NAME, "Pfams with a mapping                    : "
3120                     + pfams_with_mappings_counter + " ["
3121                     + ( ( 100 * pfams_with_mappings_counter ) / all_pfams_encountered.size() ) + "%]" );
3122             ForesterUtil.programMessage( surfacing.PRG_NAME, "Pfams with a mapping to proc. or func.  : "
3123                     + pfams_with_mappings_to_bp_or_mf_counter + " ["
3124                     + ( ( 100 * pfams_with_mappings_to_bp_or_mf_counter ) / all_pfams_encountered.size() ) + "%]" );
3125             ForesterUtil.programMessage( surfacing.PRG_NAME, "Pfams with mapping to biological process: "
3126                     + biological_process_counter + " ["
3127                     + ( ( 100 * biological_process_counter ) / all_pfams_encountered.size() ) + "%]" );
3128             ForesterUtil.programMessage( surfacing.PRG_NAME, "Pfams with mapping to molecular function: "
3129                     + molecular_function_counter + " ["
3130                     + ( ( 100 * molecular_function_counter ) / all_pfams_encountered.size() ) + "%]" );
3131             ForesterUtil.programMessage( surfacing.PRG_NAME, "Pfams with mapping to cellular component: "
3132                     + cellular_component_counter + " ["
3133                     + ( ( 100 * cellular_component_counter ) / all_pfams_encountered.size() ) + "%]" );
3134             summary_writer.write( ForesterUtil.LINE_SEPARATOR );
3135             summary_writer.write( "# Sum of Pfams encountered                : " + all_pfams_encountered.size() );
3136             summary_writer.write( ForesterUtil.LINE_SEPARATOR );
3137             summary_writer.write( "# Pfams without a mapping                 : " + pfams_without_mappings_counter
3138                     + " [" + ( ( 100 * pfams_without_mappings_counter ) / all_pfams_encountered.size() ) + "%]" );
3139             summary_writer.write( ForesterUtil.LINE_SEPARATOR );
3140             summary_writer.write( "# Pfams without mapping to proc. or func. : "
3141                     + pfams_without_mappings_to_bp_or_mf_counter + " ["
3142                     + ( ( 100 * pfams_without_mappings_to_bp_or_mf_counter ) / all_pfams_encountered.size() ) + "%]" );
3143             summary_writer.write( ForesterUtil.LINE_SEPARATOR );
3144             summary_writer.write( "# Pfams with a mapping                    : " + pfams_with_mappings_counter + " ["
3145                     + ( ( 100 * pfams_with_mappings_counter ) / all_pfams_encountered.size() ) + "%]" );
3146             summary_writer.write( ForesterUtil.LINE_SEPARATOR );
3147             summary_writer.write( "# Pfams with a mapping to proc. or func.  : "
3148                     + pfams_with_mappings_to_bp_or_mf_counter + " ["
3149                     + ( ( 100 * pfams_with_mappings_to_bp_or_mf_counter ) / all_pfams_encountered.size() ) + "%]" );
3150             summary_writer.write( ForesterUtil.LINE_SEPARATOR );
3151             summary_writer.write( "# Pfams with mapping to biological process: " + biological_process_counter + " ["
3152                     + ( ( 100 * biological_process_counter ) / all_pfams_encountered.size() ) + "%]" );
3153             summary_writer.write( ForesterUtil.LINE_SEPARATOR );
3154             summary_writer.write( "# Pfams with mapping to molecular function: " + molecular_function_counter + " ["
3155                     + ( ( 100 * molecular_function_counter ) / all_pfams_encountered.size() ) + "%]" );
3156             summary_writer.write( ForesterUtil.LINE_SEPARATOR );
3157             summary_writer.write( "# Pfams with mapping to cellular component: " + cellular_component_counter + " ["
3158                     + ( ( 100 * cellular_component_counter ) / all_pfams_encountered.size() ) + "%]" );
3159             summary_writer.write( ForesterUtil.LINE_SEPARATOR );
3160             summary_writer.close();
3161         }
3162         catch ( final IOException e ) {
3163             ForesterUtil.printWarningMessage( surfacing.PRG_NAME, "Failure to write: " + e );
3164         }
3165     }
3166
3167     private final static void writeColorLabels( final String l, final Color c, final Writer w ) throws IOException {
3168         w.write( "<tr><td><b><span style=\"color:" );
3169         w.write( String.format( "#%02x%02x%02x", c.getRed(), c.getGreen(), c.getBlue() ) );
3170         w.write( "\">" );
3171         w.write( l );
3172         w.write( "</span></b></td></tr>" );
3173         w.write( SurfacingConstants.NL );
3174     }
3175
3176     private static void writeDomainData( final Map<String, List<GoId>> domain_id_to_go_ids_map,
3177                                          final Map<GoId, GoTerm> go_id_to_term_map,
3178                                          final GoNameSpace go_namespace_limit,
3179                                          final Writer out,
3180                                          final String domain_0,
3181                                          final String domain_1,
3182                                          final String prefix_for_html,
3183                                          final String character_separator_for_non_html_output,
3184                                          final Map<String, Set<String>>[] domain_id_to_secondary_features_maps,
3185                                          final Set<GoId> all_go_ids ) throws IOException {
3186         boolean any_go_annotation_present = false;
3187         boolean first_has_no_go = false;
3188         int domain_count = 2; // To distinguish between domains and binary domain combinations.
3189         if ( ForesterUtil.isEmpty( domain_1 ) ) {
3190             domain_count = 1;
3191         }
3192         // The following has a difficult to understand logic.  
3193         for( int d = 0; d < domain_count; ++d ) {
3194             List<GoId> go_ids = null;
3195             boolean go_annotation_present = false;
3196             if ( d == 0 ) {
3197                 if ( domain_id_to_go_ids_map.containsKey( domain_0 ) ) {
3198                     go_annotation_present = true;
3199                     any_go_annotation_present = true;
3200                     go_ids = domain_id_to_go_ids_map.get( domain_0 );
3201                 }
3202                 else {
3203                     first_has_no_go = true;
3204                 }
3205             }
3206             else {
3207                 if ( domain_id_to_go_ids_map.containsKey( domain_1 ) ) {
3208                     go_annotation_present = true;
3209                     any_go_annotation_present = true;
3210                     go_ids = domain_id_to_go_ids_map.get( domain_1 );
3211                 }
3212             }
3213             if ( go_annotation_present ) {
3214                 boolean first = ( ( d == 0 ) || ( ( d == 1 ) && first_has_no_go ) );
3215                 for( final GoId go_id : go_ids ) {
3216                     out.write( "<tr>" );
3217                     if ( first ) {
3218                         first = false;
3219                         writeDomainIdsToHtml( out,
3220                                               domain_0,
3221                                               domain_1,
3222                                               prefix_for_html,
3223                                               domain_id_to_secondary_features_maps );
3224                     }
3225                     else {
3226                         out.write( "<td></td>" );
3227                     }
3228                     if ( !go_id_to_term_map.containsKey( go_id ) ) {
3229                         throw new IllegalArgumentException( "GO-id [" + go_id + "] not found in GO-id to GO-term map" );
3230                     }
3231                     final GoTerm go_term = go_id_to_term_map.get( go_id );
3232                     if ( ( go_namespace_limit == null ) || go_namespace_limit.equals( go_term.getGoNameSpace() ) ) {
3233                         // final String top = GoUtils.getPenultimateGoTerm( go_term, go_id_to_term_map ).getName();
3234                         final String go_id_str = go_id.getId();
3235                         out.write( "<td>" );
3236                         out.write( "<a href=\"" + SurfacingConstants.AMIGO_LINK + go_id_str
3237                                 + "\" target=\"amigo_window\">" + go_id_str + "</a>" );
3238                         out.write( "</td><td>" );
3239                         out.write( go_term.getName() );
3240                         if ( domain_count == 2 ) {
3241                             out.write( " (" + d + ")" );
3242                         }
3243                         out.write( "</td><td>" );
3244                         // out.write( top );
3245                         // out.write( "</td><td>" );
3246                         out.write( "[" );
3247                         out.write( go_term.getGoNameSpace().toShortString() );
3248                         out.write( "]" );
3249                         out.write( "</td>" );
3250                         if ( all_go_ids != null ) {
3251                             all_go_ids.add( go_id );
3252                         }
3253                     }
3254                     else {
3255                         out.write( "<td>" );
3256                         out.write( "</td><td>" );
3257                         out.write( "</td><td>" );
3258                         out.write( "</td><td>" );
3259                         out.write( "</td>" );
3260                     }
3261                     out.write( "</tr>" );
3262                     out.write( SurfacingConstants.NL );
3263                 }
3264             }
3265         } //  for( int d = 0; d < domain_count; ++d ) 
3266         if ( !any_go_annotation_present ) {
3267             out.write( "<tr>" );
3268             writeDomainIdsToHtml( out, domain_0, domain_1, prefix_for_html, domain_id_to_secondary_features_maps );
3269             out.write( "<td>" );
3270             out.write( "</td><td>" );
3271             out.write( "</td><td>" );
3272             out.write( "</td><td>" );
3273             out.write( "</td>" );
3274             out.write( "</tr>" );
3275             out.write( SurfacingConstants.NL );
3276         }
3277     }
3278
3279     private static void writeDomainIdsToHtml( final Writer out,
3280                                               final String domain_0,
3281                                               final String domain_1,
3282                                               final String prefix_for_detailed_html,
3283                                               final Map<String, Set<String>>[] domain_id_to_secondary_features_maps )
3284             throws IOException {
3285         out.write( "<td>" );
3286         if ( !ForesterUtil.isEmpty( prefix_for_detailed_html ) ) {
3287             out.write( prefix_for_detailed_html );
3288             out.write( " " );
3289         }
3290         out.write( "<a href=\"" + SurfacingConstants.PFAM_FAMILY_ID_LINK + domain_0 + "\">" + domain_0 + "</a>" );
3291         out.write( "</td>" );
3292     }
3293
3294     private static void writeDomainsToIndividualFilePerTreeNode( final Writer individual_files_writer,
3295                                                                  final String domain_0,
3296                                                                  final String domain_1 ) throws IOException {
3297         individual_files_writer.write( domain_0 );
3298         individual_files_writer.write( ForesterUtil.LINE_SEPARATOR );
3299         if ( !ForesterUtil.isEmpty( domain_1 ) ) {
3300             individual_files_writer.write( domain_1 );
3301             individual_files_writer.write( ForesterUtil.LINE_SEPARATOR );
3302         }
3303     }
3304
3305     private static void writePfamsToFile( final String outfile_name, final SortedSet<String> pfams ) {
3306         try {
3307             final Writer writer = new BufferedWriter( new FileWriter( new File( outfile_name ) ) );
3308             for( final String pfam : pfams ) {
3309                 writer.write( pfam );
3310                 writer.write( ForesterUtil.LINE_SEPARATOR );
3311             }
3312             writer.close();
3313             ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote " + pfams.size() + " pfams to [" + outfile_name
3314                     + "]" );
3315         }
3316         catch ( final IOException e ) {
3317             ForesterUtil.printWarningMessage( surfacing.PRG_NAME, "Failure to write: " + e );
3318         }
3319     }
3320
3321     private static void writeToNexus( final String outfile_name,
3322                                       final CharacterStateMatrix<BinaryStates> matrix,
3323                                       final Phylogeny phylogeny ) {
3324         if ( !( matrix instanceof BasicCharacterStateMatrix ) ) {
3325             throw new IllegalArgumentException( "can only write matrices of type [" + BasicCharacterStateMatrix.class
3326                     + "] to nexus" );
3327         }
3328         final BasicCharacterStateMatrix<BinaryStates> my_matrix = ( org.forester.evoinference.matrix.character.BasicCharacterStateMatrix<BinaryStates> ) matrix;
3329         final List<Phylogeny> phylogenies = new ArrayList<Phylogeny>( 1 );
3330         phylogenies.add( phylogeny );
3331         try {
3332             final BufferedWriter w = new BufferedWriter( new FileWriter( outfile_name ) );
3333             w.write( NexusConstants.NEXUS );
3334             w.write( ForesterUtil.LINE_SEPARATOR );
3335             my_matrix.writeNexusTaxaBlock( w );
3336             my_matrix.writeNexusBinaryChractersBlock( w );
3337             PhylogenyWriter.writeNexusTreesBlock( w, phylogenies, NH_CONVERSION_SUPPORT_VALUE_STYLE.NONE );
3338             w.flush();
3339             w.close();
3340             ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote Nexus file: \"" + outfile_name + "\"" );
3341         }
3342         catch ( final IOException e ) {
3343             ForesterUtil.fatalError( surfacing.PRG_NAME, e.getMessage() );
3344         }
3345     }
3346
3347     private static void writeToNexus( final String outfile_name,
3348                                       final DomainParsimonyCalculator domain_parsimony,
3349                                       final Phylogeny phylogeny ) {
3350         writeToNexus( outfile_name + surfacing.NEXUS_EXTERNAL_DOMAINS,
3351                       domain_parsimony.createMatrixOfDomainPresenceOrAbsence(),
3352                       phylogeny );
3353         writeToNexus( outfile_name + surfacing.NEXUS_EXTERNAL_DOMAIN_COMBINATIONS,
3354                       domain_parsimony.createMatrixOfBinaryDomainCombinationPresenceOrAbsence(),
3355                       phylogeny );
3356     }
3357
3358     final static class DomainComparator implements Comparator<Domain> {
3359
3360         final private boolean _ascending;
3361
3362         public DomainComparator( final boolean ascending ) {
3363             _ascending = ascending;
3364         }
3365
3366         @Override
3367         public final int compare( final Domain d0, final Domain d1 ) {
3368             if ( d0.getFrom() < d1.getFrom() ) {
3369                 return _ascending ? -1 : 1;
3370             }
3371             else if ( d0.getFrom() > d1.getFrom() ) {
3372                 return _ascending ? 1 : -1;
3373             }
3374             return 0;
3375         }
3376     }
3377 }