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