inprogress
[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.io.BufferedWriter;
30 import java.io.File;
31 import java.io.FileWriter;
32 import java.io.IOException;
33 import java.io.Writer;
34 import java.text.DecimalFormat;
35 import java.text.NumberFormat;
36 import java.util.ArrayList;
37 import java.util.Arrays;
38 import java.util.Collections;
39 import java.util.Comparator;
40 import java.util.HashMap;
41 import java.util.HashSet;
42 import java.util.Iterator;
43 import java.util.List;
44 import java.util.Map;
45 import java.util.Map.Entry;
46 import java.util.PriorityQueue;
47 import java.util.Set;
48 import java.util.SortedMap;
49 import java.util.SortedSet;
50 import java.util.TreeMap;
51 import java.util.TreeSet;
52 import java.util.regex.Matcher;
53 import java.util.regex.Pattern;
54
55 import org.forester.application.surfacing;
56 import org.forester.evoinference.distance.NeighborJoining;
57 import org.forester.evoinference.matrix.character.BasicCharacterStateMatrix;
58 import org.forester.evoinference.matrix.character.CharacterStateMatrix;
59 import org.forester.evoinference.matrix.character.CharacterStateMatrix.BinaryStates;
60 import org.forester.evoinference.matrix.character.CharacterStateMatrix.Format;
61 import org.forester.evoinference.matrix.character.CharacterStateMatrix.GainLossStates;
62 import org.forester.evoinference.matrix.distance.BasicSymmetricalDistanceMatrix;
63 import org.forester.evoinference.matrix.distance.DistanceMatrix;
64 import org.forester.go.GoId;
65 import org.forester.go.GoNameSpace;
66 import org.forester.go.GoTerm;
67 import org.forester.go.PfamToGoMapping;
68 import org.forester.io.parsers.nexus.NexusConstants;
69 import org.forester.io.writers.PhylogenyWriter;
70 import org.forester.phylogeny.Phylogeny;
71 import org.forester.phylogeny.PhylogenyMethods;
72 import org.forester.phylogeny.PhylogenyNode;
73 import org.forester.phylogeny.PhylogenyNode.NH_CONVERSION_SUPPORT_VALUE_STYLE;
74 import org.forester.phylogeny.data.BinaryCharacters;
75 import org.forester.phylogeny.data.Confidence;
76 import org.forester.phylogeny.data.Taxonomy;
77 import org.forester.phylogeny.iterators.PhylogenyNodeIterator;
78 import org.forester.protein.BasicDomain;
79 import org.forester.protein.BasicProtein;
80 import org.forester.protein.BinaryDomainCombination;
81 import org.forester.protein.Domain;
82 import org.forester.protein.Protein;
83 import org.forester.species.Species;
84 import org.forester.surfacing.DomainSimilarityCalculator.Detailedness;
85 import org.forester.surfacing.GenomeWideCombinableDomains.GenomeWideCombinableDomainsSortOrder;
86 import org.forester.util.AsciiHistogram;
87 import org.forester.util.BasicDescriptiveStatistics;
88 import org.forester.util.BasicTable;
89 import org.forester.util.BasicTableParser;
90 import org.forester.util.DescriptiveStatistics;
91 import org.forester.util.ForesterUtil;
92
93 public final class SurfacingUtil {
94
95     private final static NumberFormat       FORMATTER_3                      = new DecimalFormat( "0.000" );
96     private static final Comparator<Domain> ASCENDING_CONFIDENCE_VALUE_ORDER = new Comparator<Domain>() {
97
98                                                                                  @Override
99                                                                                  public int compare( final Domain d1,
100                                                                                                      final Domain d2 ) {
101                                                                                      if ( d1.getPerSequenceEvalue() < d2
102                                                                                              .getPerSequenceEvalue() ) {
103                                                                                          return -1;
104                                                                                      }
105                                                                                      else if ( d1
106                                                                                              .getPerSequenceEvalue() > d2
107                                                                                              .getPerSequenceEvalue() ) {
108                                                                                          return 1;
109                                                                                      }
110                                                                                      else {
111                                                                                          return d1.compareTo( d2 );
112                                                                                      }
113                                                                                  }
114                                                                              };
115     public final static Pattern             PATTERN_SP_STYLE_TAXONOMY        = Pattern.compile( "^[A-Z0-9]{3,5}$" );
116
117     private SurfacingUtil() {
118         // Hidden constructor.
119     }
120
121     public static void addAllBinaryDomainCombinationToSet( final GenomeWideCombinableDomains genome,
122                                                            final SortedSet<BinaryDomainCombination> binary_domain_combinations ) {
123         final SortedMap<String, CombinableDomains> all_cd = genome.getAllCombinableDomainsIds();
124         for( final String domain_id : all_cd.keySet() ) {
125             binary_domain_combinations.addAll( all_cd.get( domain_id ).toBinaryDomainCombinations() );
126         }
127     }
128
129     public static void addAllDomainIdsToSet( final GenomeWideCombinableDomains genome,
130                                              final SortedSet<String> domain_ids ) {
131         final SortedSet<String> domains = genome.getAllDomainIds();
132         for( final String domain : domains ) {
133             domain_ids.add( domain );
134         }
135     }
136
137     public static void addHtmlHead( final Writer w, final String title ) throws IOException {
138         w.write( SurfacingConstants.NL );
139         w.write( "<head>" );
140         w.write( "<title>" );
141         w.write( title );
142         w.write( "</title>" );
143         w.write( SurfacingConstants.NL );
144         w.write( "<style>" );
145         w.write( SurfacingConstants.NL );
146         w.write( "a:visited { color : #6633FF; text-decoration : none; }" );
147         w.write( SurfacingConstants.NL );
148         w.write( "a:link { color : #6633FF; text-decoration : none; }" );
149         w.write( SurfacingConstants.NL );
150         w.write( "a:active { color : #99FF00; text-decoration : none; }" );
151         w.write( SurfacingConstants.NL );
152         w.write( "a:hover { color : #FFFFFF; background-color : #99FF00; text-decoration : none; }" );
153         w.write( SurfacingConstants.NL );
154         //
155         w.write( "a.pl:visited { color : #505050; text-decoration : none; font-size: 7pt;}" );
156         w.write( SurfacingConstants.NL );
157         w.write( "a.pl:link { color : #505050; text-decoration : none; font-size: 7pt;}" );
158         w.write( SurfacingConstants.NL );
159         w.write( "a.pl:active { color : #505050; text-decoration : none; font-size: 7pt;}" );
160         w.write( SurfacingConstants.NL );
161         w.write( "a.pl:hover { color : #FFFFFF; background-color : #99FF00; text-decoration : none; font-size: 7pt;}" );
162         w.write( SurfacingConstants.NL );
163         //
164         w.write( "a.ps:visited { color : #707070; text-decoration : none; font-size: 7pt;}" );
165         w.write( SurfacingConstants.NL );
166         w.write( "a.ps:link { color : #707070; text-decoration : none; font-size: 7pt;}" );
167         w.write( SurfacingConstants.NL );
168         w.write( "a.ps:active { color : #707070; text-decoration : none; font-size: 7pt;}" );
169         w.write( SurfacingConstants.NL );
170         w.write( "a.ps:hover { color : #FFFFFF; background-color : #99FF00; text-decoration : none; font-size: 7pt;}" );
171         w.write( SurfacingConstants.NL );
172         //
173         w.write( "td { text-align: left; vertical-align: top; font-family: Verdana, Arial, Helvetica; font-size: 8pt}" );
174         w.write( SurfacingConstants.NL );
175         w.write( "h1 { color : #0000FF; font-family: Verdana, Arial, Helvetica; font-size: 18pt; font-weight: bold }" );
176         w.write( SurfacingConstants.NL );
177         w.write( "h2 { color : #0000FF; font-family: Verdana, Arial, Helvetica; font-size: 16pt; font-weight: bold }" );
178         w.write( SurfacingConstants.NL );
179         w.write( "</style>" );
180         w.write( SurfacingConstants.NL );
181         w.write( "</head>" );
182         w.write( SurfacingConstants.NL );
183     }
184
185     public static DescriptiveStatistics calculateDescriptiveStatisticsForMeanValues( final Set<DomainSimilarity> similarities ) {
186         final DescriptiveStatistics stats = new BasicDescriptiveStatistics();
187         for( final DomainSimilarity similarity : similarities ) {
188             stats.addValue( similarity.getMeanSimilarityScore() );
189         }
190         return stats;
191     }
192
193     public static int calculateOverlap( final Domain domain, final List<Boolean> covered_positions ) {
194         int overlap_count = 0;
195         for( int i = domain.getFrom(); i <= domain.getTo(); ++i ) {
196             if ( ( i < covered_positions.size() ) && ( covered_positions.get( i ) == true ) ) {
197                 ++overlap_count;
198             }
199         }
200         return overlap_count;
201     }
202
203     public static void checkForOutputFileWriteability( final File outfile ) {
204         final String error = ForesterUtil.isWritableFile( outfile );
205         if ( !ForesterUtil.isEmpty( error ) ) {
206             ForesterUtil.fatalError( surfacing.PRG_NAME, error );
207         }
208     }
209
210     public static void collectChangedDomainCombinationsFromBinaryStatesMatrixAsListToFile( final CharacterStateMatrix<CharacterStateMatrix.GainLossStates> matrix,
211                                                                                            final BinaryDomainCombination.DomainCombinationType dc_type,
212                                                                                            final List<BinaryDomainCombination> all_binary_domains_combination_gained,
213                                                                                            final boolean get_gains ) {
214         final SortedSet<String> sorted_ids = new TreeSet<String>();
215         for( int i = 0; i < matrix.getNumberOfIdentifiers(); ++i ) {
216             sorted_ids.add( matrix.getIdentifier( i ) );
217         }
218         for( final String id : sorted_ids ) {
219             for( int c = 0; c < matrix.getNumberOfCharacters(); ++c ) {
220                 if ( ( get_gains && ( matrix.getState( id, c ) == CharacterStateMatrix.GainLossStates.GAIN ) )
221                         || ( !get_gains && ( matrix.getState( id, c ) == CharacterStateMatrix.GainLossStates.LOSS ) ) ) {
222                     if ( dc_type == BinaryDomainCombination.DomainCombinationType.DIRECTED_ADJACTANT ) {
223                         all_binary_domains_combination_gained.add( AdjactantDirectedBinaryDomainCombination
224                                 .createInstance( matrix.getCharacter( c ) ) );
225                     }
226                     else if ( dc_type == BinaryDomainCombination.DomainCombinationType.DIRECTED ) {
227                         all_binary_domains_combination_gained.add( DirectedBinaryDomainCombination
228                                 .createInstance( matrix.getCharacter( c ) ) );
229                     }
230                     else {
231                         all_binary_domains_combination_gained.add( BasicBinaryDomainCombination.createInstance( matrix
232                                 .getCharacter( c ) ) );
233                     }
234                 }
235             }
236         }
237     }
238
239     public static Map<String, List<GoId>> createDomainIdToGoIdMap( final List<PfamToGoMapping> pfam_to_go_mappings ) {
240         final Map<String, List<GoId>> domain_id_to_go_ids_map = new HashMap<String, List<GoId>>( pfam_to_go_mappings.size() );
241         for( final PfamToGoMapping pfam_to_go : pfam_to_go_mappings ) {
242             if ( !domain_id_to_go_ids_map.containsKey( pfam_to_go.getKey() ) ) {
243                 domain_id_to_go_ids_map.put( pfam_to_go.getKey(), new ArrayList<GoId>() );
244             }
245             domain_id_to_go_ids_map.get( pfam_to_go.getKey() ).add( pfam_to_go.getValue() );
246         }
247         return domain_id_to_go_ids_map;
248     }
249
250     public static Map<String, Set<String>> createDomainIdToSecondaryFeaturesMap( final File secondary_features_map_file )
251             throws IOException {
252         final BasicTable<String> primary_table = BasicTableParser.parse( secondary_features_map_file, '\t' );
253         final Map<String, Set<String>> map = new TreeMap<String, Set<String>>();
254         for( int r = 0; r < primary_table.getNumberOfRows(); ++r ) {
255             final String domain_id = primary_table.getValue( 0, r );
256             if ( !map.containsKey( domain_id ) ) {
257                 map.put( domain_id, new HashSet<String>() );
258             }
259             map.get( domain_id ).add( primary_table.getValue( 1, r ) );
260         }
261         return map;
262     }
263
264     public static Phylogeny createNjTreeBasedOnMatrixToFile( final File nj_tree_outfile, final DistanceMatrix distance ) {
265         checkForOutputFileWriteability( nj_tree_outfile );
266         final NeighborJoining nj = NeighborJoining.createInstance();
267         final Phylogeny phylogeny = nj.execute( ( BasicSymmetricalDistanceMatrix ) distance );
268         phylogeny.setName( nj_tree_outfile.getName() );
269         writePhylogenyToFile( phylogeny, nj_tree_outfile.toString() );
270         return phylogeny;
271     }
272
273     public static Map<String, Integer> createTaxCodeToIdMap( final Phylogeny phy ) {
274         final Map<String, Integer> m = new HashMap<String, Integer>();
275         for( final PhylogenyNodeIterator iter = phy.iteratorExternalForward(); iter.hasNext(); ) {
276             final PhylogenyNode n = iter.next();
277             if ( n.getNodeData().isHasTaxonomy() ) {
278                 final Taxonomy t = n.getNodeData().getTaxonomy();
279                 final String c = t.getTaxonomyCode();
280                 if ( !ForesterUtil.isEmpty( c ) ) {
281                     if ( n.getNodeData().getTaxonomy() == null ) {
282                         ForesterUtil.fatalError( surfacing.PRG_NAME, "no taxonomy id for node " + n );
283                     }
284                     final String id = n.getNodeData().getTaxonomy().getIdentifier().getValue();
285                     if ( ForesterUtil.isEmpty( id ) ) {
286                         ForesterUtil.fatalError( surfacing.PRG_NAME, "no taxonomy id for node " + n );
287                     }
288                     if ( m.containsKey( c ) ) {
289                         ForesterUtil.fatalError( surfacing.PRG_NAME, "taxonomy code " + c + " is not unique" );
290                     }
291                     final int iid = Integer.valueOf( id );
292                     if ( m.containsValue( iid ) ) {
293                         ForesterUtil.fatalError( surfacing.PRG_NAME, "taxonomy id " + iid + " is not unique" );
294                     }
295                     m.put( c, iid );
296                 }
297             }
298             else {
299                 ForesterUtil.fatalError( surfacing.PRG_NAME, "no taxonomy for node " + n );
300             }
301         }
302         return m;
303     }
304
305     public static void decoratePrintableDomainSimilarities( final SortedSet<DomainSimilarity> domain_similarities,
306                                                             final Detailedness detailedness ) {
307         for( final DomainSimilarity domain_similarity : domain_similarities ) {
308             if ( domain_similarity instanceof PrintableDomainSimilarity ) {
309                 final PrintableDomainSimilarity printable_domain_similarity = ( PrintableDomainSimilarity ) domain_similarity;
310                 printable_domain_similarity.setDetailedness( detailedness );
311             }
312         }
313     }
314
315     public static void doit( final List<Protein> proteins,
316                              final List<String> query_domain_ids_nc_order,
317                              final Writer out,
318                              final String separator,
319                              final String limit_to_species,
320                              final Map<String, List<Integer>> average_protein_lengths_by_dc ) throws IOException {
321         for( final Protein protein : proteins ) {
322             if ( ForesterUtil.isEmpty( limit_to_species )
323                     || protein.getSpecies().getSpeciesId().equalsIgnoreCase( limit_to_species ) ) {
324                 if ( protein.contains( query_domain_ids_nc_order, true ) ) {
325                     out.write( protein.getSpecies().getSpeciesId() );
326                     out.write( separator );
327                     out.write( protein.getProteinId().getId() );
328                     out.write( separator );
329                     out.write( "[" );
330                     final Set<String> visited_domain_ids = new HashSet<String>();
331                     boolean first = true;
332                     for( final Domain domain : protein.getProteinDomains() ) {
333                         if ( !visited_domain_ids.contains( domain.getDomainId() ) ) {
334                             visited_domain_ids.add( domain.getDomainId() );
335                             if ( first ) {
336                                 first = false;
337                             }
338                             else {
339                                 out.write( " " );
340                             }
341                             out.write( domain.getDomainId() );
342                             out.write( " {" );
343                             out.write( "" + domain.getTotalCount() );
344                             out.write( "}" );
345                         }
346                     }
347                     out.write( "]" );
348                     out.write( separator );
349                     if ( !( ForesterUtil.isEmpty( protein.getDescription() ) || protein.getDescription()
350                             .equals( SurfacingConstants.NONE ) ) ) {
351                         out.write( protein.getDescription() );
352                     }
353                     out.write( separator );
354                     if ( !( ForesterUtil.isEmpty( protein.getAccession() ) || protein.getAccession()
355                             .equals( SurfacingConstants.NONE ) ) ) {
356                         out.write( protein.getAccession() );
357                     }
358                     out.write( SurfacingConstants.NL );
359                 }
360             }
361         }
362         out.flush();
363     }
364
365     public static void domainsPerProteinsStatistics( final String genome,
366                                                      final List<Protein> protein_list,
367                                                      final DescriptiveStatistics all_genomes_domains_per_potein_stats,
368                                                      final SortedMap<Integer, Integer> all_genomes_domains_per_potein_histo,
369                                                      final SortedSet<String> domains_which_are_always_single,
370                                                      final SortedSet<String> domains_which_are_sometimes_single_sometimes_not,
371                                                      final SortedSet<String> domains_which_never_single,
372                                                      final Writer writer ) {
373         final DescriptiveStatistics stats = new BasicDescriptiveStatistics();
374         for( final Protein protein : protein_list ) {
375             final int domains = protein.getNumberOfProteinDomains();
376             //System.out.println( domains );
377             stats.addValue( domains );
378             all_genomes_domains_per_potein_stats.addValue( domains );
379             if ( !all_genomes_domains_per_potein_histo.containsKey( domains ) ) {
380                 all_genomes_domains_per_potein_histo.put( domains, 1 );
381             }
382             else {
383                 all_genomes_domains_per_potein_histo.put( domains,
384                                                           1 + all_genomes_domains_per_potein_histo.get( domains ) );
385             }
386             if ( domains == 1 ) {
387                 final String domain = protein.getProteinDomain( 0 ).getDomainId();
388                 if ( !domains_which_are_sometimes_single_sometimes_not.contains( domain ) ) {
389                     if ( domains_which_never_single.contains( domain ) ) {
390                         domains_which_never_single.remove( domain );
391                         domains_which_are_sometimes_single_sometimes_not.add( domain );
392                     }
393                     else {
394                         domains_which_are_always_single.add( domain );
395                     }
396                 }
397             }
398             else if ( domains > 1 ) {
399                 for( final Domain d : protein.getProteinDomains() ) {
400                     final String domain = d.getDomainId();
401                     // System.out.println( domain );
402                     if ( !domains_which_are_sometimes_single_sometimes_not.contains( domain ) ) {
403                         if ( domains_which_are_always_single.contains( domain ) ) {
404                             domains_which_are_always_single.remove( domain );
405                             domains_which_are_sometimes_single_sometimes_not.add( domain );
406                         }
407                         else {
408                             domains_which_never_single.add( domain );
409                         }
410                     }
411                 }
412             }
413         }
414         try {
415             writer.write( genome );
416             writer.write( "\t" );
417             if ( stats.getN() >= 1 ) {
418                 writer.write( stats.arithmeticMean() + "" );
419                 writer.write( "\t" );
420                 if ( stats.getN() >= 2 ) {
421                     writer.write( stats.sampleStandardDeviation() + "" );
422                 }
423                 else {
424                     writer.write( "" );
425                 }
426                 writer.write( "\t" );
427                 writer.write( stats.median() + "" );
428                 writer.write( "\t" );
429                 writer.write( stats.getN() + "" );
430                 writer.write( "\t" );
431                 writer.write( stats.getMin() + "" );
432                 writer.write( "\t" );
433                 writer.write( stats.getMax() + "" );
434             }
435             else {
436                 writer.write( "\t" );
437                 writer.write( "\t" );
438                 writer.write( "\t" );
439                 writer.write( "0" );
440                 writer.write( "\t" );
441                 writer.write( "\t" );
442             }
443             writer.write( "\n" );
444         }
445         catch ( final IOException e ) {
446             e.printStackTrace();
447         }
448     }
449
450     public static void executeDomainLengthAnalysis( final String[][] input_file_properties,
451                                                     final int number_of_genomes,
452                                                     final DomainLengthsTable domain_lengths_table,
453                                                     final File outfile ) throws IOException {
454         final DecimalFormat df = new DecimalFormat( "#.00" );
455         checkForOutputFileWriteability( outfile );
456         final BufferedWriter out = new BufferedWriter( new FileWriter( outfile ) );
457         out.write( "MEAN BASED STATISTICS PER SPECIES" );
458         out.write( ForesterUtil.LINE_SEPARATOR );
459         out.write( domain_lengths_table.createMeanBasedStatisticsPerSpeciesTable().toString() );
460         out.write( ForesterUtil.LINE_SEPARATOR );
461         out.write( ForesterUtil.LINE_SEPARATOR );
462         final List<DomainLengths> domain_lengths_list = domain_lengths_table.getDomainLengthsList();
463         out.write( "OUTLIER SPECIES PER DOMAIN (Z>=1.5)" );
464         out.write( ForesterUtil.LINE_SEPARATOR );
465         for( final DomainLengths domain_lengths : domain_lengths_list ) {
466             final List<Species> species_list = domain_lengths.getMeanBasedOutlierSpecies( 1.5 );
467             if ( species_list.size() > 0 ) {
468                 out.write( domain_lengths.getDomainId() + "\t" );
469                 for( final Species species : species_list ) {
470                     out.write( species + "\t" );
471                 }
472                 out.write( ForesterUtil.LINE_SEPARATOR );
473             }
474         }
475         out.write( ForesterUtil.LINE_SEPARATOR );
476         out.write( ForesterUtil.LINE_SEPARATOR );
477         out.write( "OUTLIER SPECIES (Z 1.0)" );
478         out.write( ForesterUtil.LINE_SEPARATOR );
479         final DescriptiveStatistics stats_for_all_species = domain_lengths_table
480                 .calculateMeanBasedStatisticsForAllSpecies();
481         out.write( stats_for_all_species.asSummary() );
482         out.write( ForesterUtil.LINE_SEPARATOR );
483         final AsciiHistogram histo = new AsciiHistogram( stats_for_all_species );
484         out.write( histo.toStringBuffer( 40, '=', 60, 4 ).toString() );
485         out.write( ForesterUtil.LINE_SEPARATOR );
486         final double population_sd = stats_for_all_species.sampleStandardDeviation();
487         final double population_mean = stats_for_all_species.arithmeticMean();
488         for( final Species species : domain_lengths_table.getSpecies() ) {
489             final double x = domain_lengths_table.calculateMeanBasedStatisticsForSpecies( species ).arithmeticMean();
490             final double z = ( x - population_mean ) / population_sd;
491             out.write( species + "\t" + z );
492             out.write( ForesterUtil.LINE_SEPARATOR );
493         }
494         out.write( ForesterUtil.LINE_SEPARATOR );
495         for( final Species species : domain_lengths_table.getSpecies() ) {
496             final DescriptiveStatistics stats_for_species = domain_lengths_table
497                     .calculateMeanBasedStatisticsForSpecies( species );
498             final double x = stats_for_species.arithmeticMean();
499             final double z = ( x - population_mean ) / population_sd;
500             if ( ( z <= -1.0 ) || ( z >= 1.0 ) ) {
501                 out.write( species + "\t" + df.format( z ) + "\t" + stats_for_species.asSummary() );
502                 out.write( ForesterUtil.LINE_SEPARATOR );
503             }
504         }
505         out.close();
506         System.gc();
507     }
508
509     /**
510      * 
511      * @param all_binary_domains_combination_lost_fitch 
512      * @param use_last_in_fitch_parsimony 
513      * @param consider_directedness_and_adjacency_for_bin_combinations 
514      * @param all_binary_domains_combination_gained if null ignored, otherwise this is to list all binary domain combinations
515      * which were gained under unweighted (Fitch) parsimony.
516      */
517     public static void executeParsimonyAnalysis( final long random_number_seed_for_fitch_parsimony,
518                                                  final boolean radomize_fitch_parsimony,
519                                                  final String outfile_name,
520                                                  final DomainParsimonyCalculator domain_parsimony,
521                                                  final Phylogeny phylogeny,
522                                                  final Map<String, List<GoId>> domain_id_to_go_ids_map,
523                                                  final Map<GoId, GoTerm> go_id_to_term_map,
524                                                  final GoNameSpace go_namespace_limit,
525                                                  final String parameters_str,
526                                                  final Map<String, Set<String>>[] domain_id_to_secondary_features_maps,
527                                                  final SortedSet<String> positive_filter,
528                                                  final boolean output_binary_domain_combinations_for_graphs,
529                                                  final List<BinaryDomainCombination> all_binary_domains_combination_gained_fitch,
530                                                  final List<BinaryDomainCombination> all_binary_domains_combination_lost_fitch,
531                                                  final BinaryDomainCombination.DomainCombinationType dc_type,
532                                                  final Map<String, DescriptiveStatistics> protein_length_stats_by_dc,
533                                                  final Map<String, DescriptiveStatistics> domain_number_stats_by_dc,
534                                                  final Map<String, DescriptiveStatistics> domain_length_stats_by_domain,
535                                                  final Map<String, Integer> tax_code_to_id_map,
536                                                  final boolean write_to_nexus,
537                                                  final boolean use_last_in_fitch_parsimony ) {
538         final String sep = ForesterUtil.LINE_SEPARATOR + "###################" + ForesterUtil.LINE_SEPARATOR;
539         final String date_time = ForesterUtil.getCurrentDateTime();
540         final SortedSet<String> all_pfams_encountered = new TreeSet<String>();
541         final SortedSet<String> all_pfams_gained_as_domains = new TreeSet<String>();
542         final SortedSet<String> all_pfams_lost_as_domains = new TreeSet<String>();
543         final SortedSet<String> all_pfams_gained_as_dom_combinations = new TreeSet<String>();
544         final SortedSet<String> all_pfams_lost_as_dom_combinations = new TreeSet<String>();
545         if ( write_to_nexus ) {
546             writeToNexus( outfile_name, domain_parsimony, phylogeny );
547         }
548         // DOLLO DOMAINS
549         // -------------
550         Phylogeny local_phylogeny_l = phylogeny.copy();
551         if ( ( positive_filter != null ) && ( positive_filter.size() > 0 ) ) {
552             domain_parsimony.executeDolloParsimonyOnDomainPresence( positive_filter );
553         }
554         else {
555             domain_parsimony.executeDolloParsimonyOnDomainPresence();
556         }
557         SurfacingUtil.writeMatrixToFile( domain_parsimony.getGainLossMatrix(), outfile_name
558                 + surfacing.PARSIMONY_OUTPUT_GL_SUFFIX_DOLLO_DOMAINS, Format.FORESTER );
559         SurfacingUtil.writeMatrixToFile( domain_parsimony.getGainLossCountsMatrix(), outfile_name
560                 + surfacing.PARSIMONY_OUTPUT_GL_COUNTS_SUFFIX_DOLLO_DOMAINS, Format.FORESTER );
561         SurfacingUtil.writeBinaryStatesMatrixAsListToFile( domain_parsimony.getGainLossMatrix(),
562                                                            CharacterStateMatrix.GainLossStates.GAIN,
563                                                            outfile_name + surfacing.PARSIMONY_OUTPUT_DOLLO_GAINS_D,
564                                                            sep,
565                                                            ForesterUtil.LINE_SEPARATOR,
566                                                            null );
567         SurfacingUtil.writeBinaryStatesMatrixAsListToFile( domain_parsimony.getGainLossMatrix(),
568                                                            CharacterStateMatrix.GainLossStates.LOSS,
569                                                            outfile_name + surfacing.PARSIMONY_OUTPUT_DOLLO_LOSSES_D,
570                                                            sep,
571                                                            ForesterUtil.LINE_SEPARATOR,
572                                                            null );
573         SurfacingUtil.writeBinaryStatesMatrixAsListToFile( domain_parsimony.getGainLossMatrix(), null, outfile_name
574                 + surfacing.PARSIMONY_OUTPUT_DOLLO_PRESENT_D, sep, ForesterUtil.LINE_SEPARATOR, null );
575         //HTML:
576         writeBinaryStatesMatrixToList( domain_id_to_go_ids_map,
577                                        go_id_to_term_map,
578                                        go_namespace_limit,
579                                        false,
580                                        domain_parsimony.getGainLossMatrix(),
581                                        CharacterStateMatrix.GainLossStates.GAIN,
582                                        outfile_name + surfacing.PARSIMONY_OUTPUT_DOLLO_GAINS_HTML_D,
583                                        sep,
584                                        ForesterUtil.LINE_SEPARATOR,
585                                        "Dollo Parsimony | Gains | Domains",
586                                        "+",
587                                        domain_id_to_secondary_features_maps,
588                                        all_pfams_encountered,
589                                        all_pfams_gained_as_domains,
590                                        "_dollo_gains_d",
591                                        tax_code_to_id_map );
592         writeBinaryStatesMatrixToList( domain_id_to_go_ids_map,
593                                        go_id_to_term_map,
594                                        go_namespace_limit,
595                                        false,
596                                        domain_parsimony.getGainLossMatrix(),
597                                        CharacterStateMatrix.GainLossStates.LOSS,
598                                        outfile_name + surfacing.PARSIMONY_OUTPUT_DOLLO_LOSSES_HTML_D,
599                                        sep,
600                                        ForesterUtil.LINE_SEPARATOR,
601                                        "Dollo Parsimony | Losses | Domains",
602                                        "-",
603                                        domain_id_to_secondary_features_maps,
604                                        all_pfams_encountered,
605                                        all_pfams_lost_as_domains,
606                                        "_dollo_losses_d",
607                                        tax_code_to_id_map );
608         //        writeBinaryStatesMatrixToList( domain_id_to_go_ids_map,
609         //                                       go_id_to_term_map,
610         //                                       go_namespace_limit,
611         //                                       false,
612         //                                       domain_parsimony.getGainLossMatrix(),
613         //                                       null,
614         //                                       outfile_name + surfacing.PARSIMONY_OUTPUT_DOLLO_PRESENT_HTML_D,
615         //                                       sep,
616         //                                       ForesterUtil.LINE_SEPARATOR,
617         //                                       "Dollo Parsimony | Present | Domains",
618         //                                       "",
619         //                                       domain_id_to_secondary_features_maps,
620         //                                       all_pfams_encountered,
621         //                                       null,
622         //                                       "_dollo_present_d",
623         //                                       tax_code_to_id_map );
624         preparePhylogeny( local_phylogeny_l,
625                           domain_parsimony,
626                           date_time,
627                           "Dollo parsimony on domain presence/absence",
628                           "dollo_on_domains_" + outfile_name,
629                           parameters_str );
630         SurfacingUtil.writePhylogenyToFile( local_phylogeny_l, outfile_name
631                 + surfacing.DOMAINS_PARSIMONY_TREE_OUTPUT_SUFFIX_DOLLO );
632         try {
633             writeAllDomainsChangedOnAllSubtrees( local_phylogeny_l, true, outfile_name, "_dollo_all_gains_d" );
634             writeAllDomainsChangedOnAllSubtrees( local_phylogeny_l, false, outfile_name, "_dollo_all_losses_d" );
635         }
636         catch ( final IOException e ) {
637             e.printStackTrace();
638             ForesterUtil.fatalError( surfacing.PRG_NAME, e.getLocalizedMessage() );
639         }
640         if ( domain_parsimony.calculateNumberOfBinaryDomainCombination() > 0 ) {
641             // FITCH DOMAIN COMBINATIONS
642             // -------------------------
643             local_phylogeny_l = phylogeny.copy();
644             String randomization = "no";
645             if ( radomize_fitch_parsimony ) {
646                 domain_parsimony.executeFitchParsimonyOnBinaryDomainCombintion( random_number_seed_for_fitch_parsimony );
647                 randomization = "yes, seed = " + random_number_seed_for_fitch_parsimony;
648             }
649             else {
650                 domain_parsimony.executeFitchParsimonyOnBinaryDomainCombintion( use_last_in_fitch_parsimony );
651             }
652             SurfacingUtil.writeMatrixToFile( domain_parsimony.getGainLossMatrix(), outfile_name
653                     + surfacing.PARSIMONY_OUTPUT_GL_SUFFIX_FITCH_BINARY_COMBINATIONS, Format.FORESTER );
654             SurfacingUtil.writeMatrixToFile( domain_parsimony.getGainLossCountsMatrix(), outfile_name
655                     + surfacing.PARSIMONY_OUTPUT_GL_COUNTS_SUFFIX_FITCH_BINARY_COMBINATIONS, Format.FORESTER );
656             SurfacingUtil
657                     .writeBinaryStatesMatrixAsListToFile( domain_parsimony.getGainLossMatrix(),
658                                                           CharacterStateMatrix.GainLossStates.GAIN,
659                                                           outfile_name + surfacing.PARSIMONY_OUTPUT_FITCH_GAINS_BC,
660                                                           sep,
661                                                           ForesterUtil.LINE_SEPARATOR,
662                                                           null );
663             SurfacingUtil.writeBinaryStatesMatrixAsListToFile( domain_parsimony.getGainLossMatrix(),
664                                                                CharacterStateMatrix.GainLossStates.LOSS,
665                                                                outfile_name
666                                                                        + surfacing.PARSIMONY_OUTPUT_FITCH_LOSSES_BC,
667                                                                sep,
668                                                                ForesterUtil.LINE_SEPARATOR,
669                                                                null );
670             SurfacingUtil.writeBinaryStatesMatrixAsListToFile( domain_parsimony.getGainLossMatrix(), null, outfile_name
671                     + surfacing.PARSIMONY_OUTPUT_FITCH_PRESENT_BC, sep, ForesterUtil.LINE_SEPARATOR, null );
672             if ( all_binary_domains_combination_gained_fitch != null ) {
673                 collectChangedDomainCombinationsFromBinaryStatesMatrixAsListToFile( domain_parsimony.getGainLossMatrix(),
674                                                                                     dc_type,
675                                                                                     all_binary_domains_combination_gained_fitch,
676                                                                                     true );
677             }
678             if ( all_binary_domains_combination_lost_fitch != null ) {
679                 collectChangedDomainCombinationsFromBinaryStatesMatrixAsListToFile( domain_parsimony.getGainLossMatrix(),
680                                                                                     dc_type,
681                                                                                     all_binary_domains_combination_lost_fitch,
682                                                                                     false );
683             }
684             if ( output_binary_domain_combinations_for_graphs ) {
685                 SurfacingUtil
686                         .writeBinaryStatesMatrixAsListToFileForBinaryCombinationsForGraphAnalysis( domain_parsimony
687                                                                                                            .getGainLossMatrix(),
688                                                                                                    null,
689                                                                                                    outfile_name
690                                                                                                            + surfacing.PARSIMONY_OUTPUT_FITCH_PRESENT_BC_OUTPUTFILE_SUFFIX_FOR_GRAPH_ANALYSIS,
691                                                                                                    sep,
692                                                                                                    ForesterUtil.LINE_SEPARATOR,
693                                                                                                    BinaryDomainCombination.OutputFormat.DOT );
694             }
695             // HTML:
696             writeBinaryStatesMatrixToList( domain_id_to_go_ids_map,
697                                            go_id_to_term_map,
698                                            go_namespace_limit,
699                                            true,
700                                            domain_parsimony.getGainLossMatrix(),
701                                            CharacterStateMatrix.GainLossStates.GAIN,
702                                            outfile_name + surfacing.PARSIMONY_OUTPUT_FITCH_GAINS_HTML_BC,
703                                            sep,
704                                            ForesterUtil.LINE_SEPARATOR,
705                                            "Fitch Parsimony | Gains | Domain Combinations",
706                                            "+",
707                                            null,
708                                            all_pfams_encountered,
709                                            all_pfams_gained_as_dom_combinations,
710                                            "_fitch_gains_dc",
711                                            tax_code_to_id_map );
712             writeBinaryStatesMatrixToList( domain_id_to_go_ids_map,
713                                            go_id_to_term_map,
714                                            go_namespace_limit,
715                                            true,
716                                            domain_parsimony.getGainLossMatrix(),
717                                            CharacterStateMatrix.GainLossStates.LOSS,
718                                            outfile_name + surfacing.PARSIMONY_OUTPUT_FITCH_LOSSES_HTML_BC,
719                                            sep,
720                                            ForesterUtil.LINE_SEPARATOR,
721                                            "Fitch Parsimony | Losses | Domain Combinations",
722                                            "-",
723                                            null,
724                                            all_pfams_encountered,
725                                            all_pfams_lost_as_dom_combinations,
726                                            "_fitch_losses_dc",
727                                            tax_code_to_id_map );
728             //            writeBinaryStatesMatrixToList( domain_id_to_go_ids_map,
729             //                                           go_id_to_term_map,
730             //                                           go_namespace_limit,
731             //                                           true,
732             //                                           domain_parsimony.getGainLossMatrix(),
733             //                                           null,
734             //                                           outfile_name + surfacing.PARSIMONY_OUTPUT_FITCH_PRESENT_HTML_BC,
735             //                                           sep,
736             //                                           ForesterUtil.LINE_SEPARATOR,
737             //                                           "Fitch Parsimony | Present | Domain Combinations",
738             //                                           "",
739             //                                           null,
740             //                                           all_pfams_encountered,
741             //                                           null,
742             //                                           "_fitch_present_dc",
743             //                                           tax_code_to_id_map );
744             writeAllEncounteredPfamsToFile( domain_id_to_go_ids_map,
745                                             go_id_to_term_map,
746                                             outfile_name,
747                                             all_pfams_encountered );
748             writePfamsToFile( outfile_name + surfacing.ALL_PFAMS_GAINED_AS_DOMAINS_SUFFIX, all_pfams_gained_as_domains );
749             writePfamsToFile( outfile_name + surfacing.ALL_PFAMS_LOST_AS_DOMAINS_SUFFIX, all_pfams_lost_as_domains );
750             writePfamsToFile( outfile_name + surfacing.ALL_PFAMS_GAINED_AS_DC_SUFFIX,
751                               all_pfams_gained_as_dom_combinations );
752             writePfamsToFile( outfile_name + surfacing.ALL_PFAMS_LOST_AS_DC_SUFFIX, all_pfams_lost_as_dom_combinations );
753             preparePhylogeny( local_phylogeny_l,
754                               domain_parsimony,
755                               date_time,
756                               "Fitch parsimony on binary domain combination presence/absence randomization: "
757                                       + randomization,
758                               "fitch_on_binary_domain_combinations_" + outfile_name,
759                               parameters_str );
760             SurfacingUtil.writePhylogenyToFile( local_phylogeny_l, outfile_name
761                     + surfacing.BINARY_DOMAIN_COMBINATIONS_PARSIMONY_TREE_OUTPUT_SUFFIX_FITCH );
762             calculateIndependentDomainCombinationGains( local_phylogeny_l,
763                                                         outfile_name
764                                                                 + surfacing.INDEPENDENT_DC_GAINS_FITCH_PARS_COUNTS_OUTPUT_SUFFIX,
765                                                         outfile_name
766                                                                 + surfacing.INDEPENDENT_DC_GAINS_FITCH_PARS_DC_OUTPUT_SUFFIX,
767                                                         outfile_name
768                                                                 + surfacing.INDEPENDENT_DC_GAINS_FITCH_PARS_DC_FOR_GO_MAPPING_OUTPUT_SUFFIX,
769                                                         outfile_name
770                                                                 + surfacing.INDEPENDENT_DC_GAINS_FITCH_PARS_DC_FOR_GO_MAPPING_OUTPUT_UNIQUE_SUFFIX,
771                                                         outfile_name + "_indep_dc_gains_fitch_lca_ranks.txt",
772                                                         outfile_name + "_indep_dc_gains_fitch_lca_taxonomies.txt",
773                                                         outfile_name + "_indep_dc_gains_fitch_protein_statistics.txt",
774                                                         protein_length_stats_by_dc,
775                                                         domain_number_stats_by_dc,
776                                                         domain_length_stats_by_domain );
777         }
778     }
779
780     public static void executeParsimonyAnalysisForSecondaryFeatures( final String outfile_name,
781                                                                      final DomainParsimonyCalculator secondary_features_parsimony,
782                                                                      final Phylogeny phylogeny,
783                                                                      final String parameters_str,
784                                                                      final Map<Species, MappingResults> mapping_results_map,
785                                                                      final boolean use_last_in_fitch_parsimony ) {
786         final String sep = ForesterUtil.LINE_SEPARATOR + "###################" + ForesterUtil.LINE_SEPARATOR;
787         final String date_time = ForesterUtil.getCurrentDateTime();
788         System.out.println();
789         writeToNexus( outfile_name + surfacing.NEXUS_SECONDARY_FEATURES,
790                       secondary_features_parsimony.createMatrixOfSecondaryFeaturePresenceOrAbsence( null ),
791                       phylogeny );
792         Phylogeny local_phylogeny_copy = phylogeny.copy();
793         secondary_features_parsimony.executeDolloParsimonyOnSecondaryFeatures( mapping_results_map );
794         SurfacingUtil.writeMatrixToFile( secondary_features_parsimony.getGainLossMatrix(), outfile_name
795                 + surfacing.PARSIMONY_OUTPUT_GL_SUFFIX_DOLLO_SECONDARY_FEATURES, Format.FORESTER );
796         SurfacingUtil.writeMatrixToFile( secondary_features_parsimony.getGainLossCountsMatrix(), outfile_name
797                 + surfacing.PARSIMONY_OUTPUT_GL_COUNTS_SUFFIX_DOLLO_SECONDARY_FEATURES, Format.FORESTER );
798         SurfacingUtil
799                 .writeBinaryStatesMatrixAsListToFile( secondary_features_parsimony.getGainLossMatrix(),
800                                                       CharacterStateMatrix.GainLossStates.GAIN,
801                                                       outfile_name
802                                                               + surfacing.PARSIMONY_OUTPUT_DOLLO_GAINS_SECONDARY_FEATURES,
803                                                       sep,
804                                                       ForesterUtil.LINE_SEPARATOR,
805                                                       null );
806         SurfacingUtil
807                 .writeBinaryStatesMatrixAsListToFile( secondary_features_parsimony.getGainLossMatrix(),
808                                                       CharacterStateMatrix.GainLossStates.LOSS,
809                                                       outfile_name
810                                                               + surfacing.PARSIMONY_OUTPUT_DOLLO_LOSSES_SECONDARY_FEATURES,
811                                                       sep,
812                                                       ForesterUtil.LINE_SEPARATOR,
813                                                       null );
814         SurfacingUtil
815                 .writeBinaryStatesMatrixAsListToFile( secondary_features_parsimony.getGainLossMatrix(),
816                                                       null,
817                                                       outfile_name
818                                                               + surfacing.PARSIMONY_OUTPUT_DOLLO_PRESENT_SECONDARY_FEATURES,
819                                                       sep,
820                                                       ForesterUtil.LINE_SEPARATOR,
821                                                       null );
822         preparePhylogeny( local_phylogeny_copy,
823                           secondary_features_parsimony,
824                           date_time,
825                           "Dollo parsimony on secondary feature presence/absence",
826                           "dollo_on_secondary_features_" + outfile_name,
827                           parameters_str );
828         SurfacingUtil.writePhylogenyToFile( local_phylogeny_copy, outfile_name
829                 + surfacing.SECONDARY_FEATURES_PARSIMONY_TREE_OUTPUT_SUFFIX_DOLLO );
830         // FITCH DOMAIN COMBINATIONS
831         // -------------------------
832         local_phylogeny_copy = phylogeny.copy();
833         final String randomization = "no";
834         secondary_features_parsimony
835                 .executeFitchParsimonyOnBinaryDomainCombintionOnSecondaryFeatures( use_last_in_fitch_parsimony );
836         preparePhylogeny( local_phylogeny_copy,
837                           secondary_features_parsimony,
838                           date_time,
839                           "Fitch parsimony on secondary binary domain combination presence/absence randomization: "
840                                   + randomization,
841                           "fitch_on_binary_domain_combinations_" + outfile_name,
842                           parameters_str );
843         SurfacingUtil.writePhylogenyToFile( local_phylogeny_copy, outfile_name
844                 + surfacing.BINARY_DOMAIN_COMBINATIONS_PARSIMONY_TREE_OUTPUT_SUFFIX_FITCH_MAPPED );
845         calculateIndependentDomainCombinationGains( local_phylogeny_copy, outfile_name
846                 + surfacing.INDEPENDENT_DC_GAINS_FITCH_PARS_COUNTS_MAPPED_OUTPUT_SUFFIX, outfile_name
847                 + surfacing.INDEPENDENT_DC_GAINS_FITCH_PARS_DC_MAPPED_OUTPUT_SUFFIX, outfile_name
848                 + surfacing.INDEPENDENT_DC_GAINS_FITCH_PARS_DC_FOR_GO_MAPPING_MAPPED_OUTPUT_SUFFIX, outfile_name
849                 + surfacing.INDEPENDENT_DC_GAINS_FITCH_PARS_DC_FOR_GO_MAPPING_MAPPED_OUTPUT_UNIQUE_SUFFIX, outfile_name
850                 + "_MAPPED_indep_dc_gains_fitch_lca_ranks.txt", outfile_name
851                 + "_MAPPED_indep_dc_gains_fitch_lca_taxonomies.txt", null, null, null, null );
852     }
853
854     public static void extractProteinNames( final List<Protein> proteins,
855                                             final List<String> query_domain_ids_nc_order,
856                                             final Writer out,
857                                             final String separator,
858                                             final String limit_to_species ) throws IOException {
859         for( final Protein protein : proteins ) {
860             if ( ForesterUtil.isEmpty( limit_to_species )
861                     || protein.getSpecies().getSpeciesId().equalsIgnoreCase( limit_to_species ) ) {
862                 if ( protein.contains( query_domain_ids_nc_order, true ) ) {
863                     out.write( protein.getSpecies().getSpeciesId() );
864                     out.write( separator );
865                     out.write( protein.getProteinId().getId() );
866                     out.write( separator );
867                     out.write( "[" );
868                     final Set<String> visited_domain_ids = new HashSet<String>();
869                     boolean first = true;
870                     for( final Domain domain : protein.getProteinDomains() ) {
871                         if ( !visited_domain_ids.contains( domain.getDomainId() ) ) {
872                             visited_domain_ids.add( domain.getDomainId() );
873                             if ( first ) {
874                                 first = false;
875                             }
876                             else {
877                                 out.write( " " );
878                             }
879                             out.write( domain.getDomainId() );
880                             out.write( " {" );
881                             out.write( "" + domain.getTotalCount() );
882                             out.write( "}" );
883                         }
884                     }
885                     out.write( "]" );
886                     out.write( separator );
887                     if ( !( ForesterUtil.isEmpty( protein.getDescription() ) || protein.getDescription()
888                             .equals( SurfacingConstants.NONE ) ) ) {
889                         out.write( protein.getDescription() );
890                     }
891                     out.write( separator );
892                     if ( !( ForesterUtil.isEmpty( protein.getAccession() ) || protein.getAccession()
893                             .equals( SurfacingConstants.NONE ) ) ) {
894                         out.write( protein.getAccession() );
895                     }
896                     out.write( SurfacingConstants.NL );
897                 }
898             }
899         }
900         out.flush();
901     }
902
903     public static void extractProteinNames( final SortedMap<Species, List<Protein>> protein_lists_per_species,
904                                             final String domain_id,
905                                             final Writer out,
906                                             final String separator,
907                                             final String limit_to_species,
908                                             final double domain_e_cutoff ) throws IOException {
909         System.out.println( "Per domain E-value: " + domain_e_cutoff );
910         for( final Species species : protein_lists_per_species.keySet() ) {
911             System.out.println( species + ":" );
912             for( final Protein protein : protein_lists_per_species.get( species ) ) {
913                 if ( ForesterUtil.isEmpty( limit_to_species )
914                         || protein.getSpecies().getSpeciesId().equalsIgnoreCase( limit_to_species ) ) {
915                     final List<Domain> domains = protein.getProteinDomains( domain_id );
916                     if ( domains.size() > 0 ) {
917                         out.write( protein.getSpecies().getSpeciesId() );
918                         out.write( separator );
919                         out.write( protein.getProteinId().getId() );
920                         out.write( separator );
921                         out.write( domain_id.toString() );
922                         out.write( separator );
923                         int prev_to = -1;
924                         for( final Domain domain : domains ) {
925                             if ( ( domain_e_cutoff < 0 ) || ( domain.getPerDomainEvalue() <= domain_e_cutoff ) ) {
926                                 out.write( "/" );
927                                 out.write( domain.getFrom() + "-" + domain.getTo() );
928                                 if ( prev_to >= 0 ) {
929                                     final int l = domain.getFrom() - prev_to;
930                                     System.out.println( l );
931                                 }
932                                 prev_to = domain.getTo();
933                             }
934                         }
935                         out.write( "/" );
936                         out.write( separator );
937                         final List<Domain> domain_list = new ArrayList<Domain>();
938                         for( final Domain domain : protein.getProteinDomains() ) {
939                             if ( ( domain_e_cutoff < 0 ) || ( domain.getPerDomainEvalue() <= domain_e_cutoff ) ) {
940                                 domain_list.add( domain );
941                             }
942                         }
943                         final Domain domain_ary[] = new Domain[ domain_list.size() ];
944                         for( int i = 0; i < domain_list.size(); ++i ) {
945                             domain_ary[ i ] = domain_list.get( i );
946                         }
947                         Arrays.sort( domain_ary, new DomainComparator( true ) );
948                         out.write( "{" );
949                         boolean first = true;
950                         for( final Domain domain : domain_ary ) {
951                             if ( first ) {
952                                 first = false;
953                             }
954                             else {
955                                 out.write( "," );
956                             }
957                             out.write( domain.getDomainId().toString() );
958                             out.write( ":" + domain.getFrom() + "-" + domain.getTo() );
959                             out.write( ":" + domain.getPerDomainEvalue() );
960                         }
961                         out.write( "}" );
962                         if ( !( ForesterUtil.isEmpty( protein.getDescription() ) || protein.getDescription()
963                                 .equals( SurfacingConstants.NONE ) ) ) {
964                             out.write( protein.getDescription() );
965                         }
966                         out.write( separator );
967                         if ( !( ForesterUtil.isEmpty( protein.getAccession() ) || protein.getAccession()
968                                 .equals( SurfacingConstants.NONE ) ) ) {
969                             out.write( protein.getAccession() );
970                         }
971                         out.write( SurfacingConstants.NL );
972                     }
973                 }
974             }
975         }
976         out.flush();
977     }
978
979     public static SortedSet<String> getAllDomainIds( final List<GenomeWideCombinableDomains> gwcd_list ) {
980         final SortedSet<String> all_domains_ids = new TreeSet<String>();
981         for( final GenomeWideCombinableDomains gwcd : gwcd_list ) {
982             final Set<String> all_domains = gwcd.getAllDomainIds();
983             //    for( final Domain domain : all_domains ) {
984             all_domains_ids.addAll( all_domains );
985             //    }
986         }
987         return all_domains_ids;
988     }
989
990     public static SortedMap<String, Integer> getDomainCounts( final List<Protein> protein_domain_collections ) {
991         final SortedMap<String, Integer> map = new TreeMap<String, Integer>();
992         for( final Protein protein_domain_collection : protein_domain_collections ) {
993             for( final Object name : protein_domain_collection.getProteinDomains() ) {
994                 final BasicDomain protein_domain = ( BasicDomain ) name;
995                 final String id = protein_domain.getDomainId();
996                 if ( map.containsKey( id ) ) {
997                     map.put( id, map.get( id ) + 1 );
998                 }
999                 else {
1000                     map.put( id, 1 );
1001                 }
1002             }
1003         }
1004         return map;
1005     }
1006
1007     public static int getNumberOfNodesLackingName( final Phylogeny p, final StringBuilder names ) {
1008         final PhylogenyNodeIterator it = p.iteratorPostorder();
1009         int c = 0;
1010         while ( it.hasNext() ) {
1011             final PhylogenyNode n = it.next();
1012             if ( ForesterUtil.isEmpty( n.getName() )
1013                     && ( !n.getNodeData().isHasTaxonomy() || ForesterUtil.isEmpty( n.getNodeData().getTaxonomy()
1014                             .getScientificName() ) )
1015                     && ( !n.getNodeData().isHasTaxonomy() || ForesterUtil.isEmpty( n.getNodeData().getTaxonomy()
1016                             .getCommonName() ) ) ) {
1017                 if ( n.getParent() != null ) {
1018                     names.append( " " );
1019                     names.append( n.getParent().getName() );
1020                 }
1021                 final List l = n.getAllExternalDescendants();
1022                 for( final Object object : l ) {
1023                     System.out.println( l.toString() );
1024                 }
1025                 ++c;
1026             }
1027         }
1028         return c;
1029     }
1030
1031     /**
1032      * Returns true is Domain domain falls in an uninterrupted stretch of
1033      * covered positions.
1034      * 
1035      * @param domain
1036      * @param covered_positions
1037      * @return
1038      */
1039     public static boolean isEngulfed( final Domain domain, final List<Boolean> covered_positions ) {
1040         for( int i = domain.getFrom(); i <= domain.getTo(); ++i ) {
1041             if ( ( i >= covered_positions.size() ) || ( covered_positions.get( i ) != true ) ) {
1042                 return false;
1043             }
1044         }
1045         return true;
1046     }
1047
1048     public static void performDomainArchitectureAnalysis( final SortedMap<String, Set<String>> domain_architecutures,
1049                                                           final SortedMap<String, Integer> domain_architecuture_counts,
1050                                                           final int min_count,
1051                                                           final File da_counts_outfile,
1052                                                           final File unique_da_outfile ) {
1053         checkForOutputFileWriteability( da_counts_outfile );
1054         checkForOutputFileWriteability( unique_da_outfile );
1055         try {
1056             final BufferedWriter da_counts_out = new BufferedWriter( new FileWriter( da_counts_outfile ) );
1057             final BufferedWriter unique_da_out = new BufferedWriter( new FileWriter( unique_da_outfile ) );
1058             final Iterator<Entry<String, Integer>> it = domain_architecuture_counts.entrySet().iterator();
1059             while ( it.hasNext() ) {
1060                 final Map.Entry<String, Integer> e = it.next();
1061                 final String da = e.getKey();
1062                 final int count = e.getValue();
1063                 if ( count >= min_count ) {
1064                     da_counts_out.write( da );
1065                     da_counts_out.write( "\t" );
1066                     da_counts_out.write( String.valueOf( count ) );
1067                     da_counts_out.write( ForesterUtil.LINE_SEPARATOR );
1068                 }
1069                 if ( count == 1 ) {
1070                     final Iterator<Entry<String, Set<String>>> it2 = domain_architecutures.entrySet().iterator();
1071                     while ( it2.hasNext() ) {
1072                         final Map.Entry<String, Set<String>> e2 = it2.next();
1073                         final String genome = e2.getKey();
1074                         final Set<String> das = e2.getValue();
1075                         if ( das.contains( da ) ) {
1076                             unique_da_out.write( genome );
1077                             unique_da_out.write( "\t" );
1078                             unique_da_out.write( da );
1079                             unique_da_out.write( ForesterUtil.LINE_SEPARATOR );
1080                         }
1081                     }
1082                 }
1083             }
1084             unique_da_out.close();
1085             da_counts_out.close();
1086         }
1087         catch ( final IOException e ) {
1088             ForesterUtil.fatalError( surfacing.PRG_NAME, e.getMessage() );
1089         }
1090         ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote distance matrices to \"" + da_counts_outfile + "\"" );
1091         ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote distance matrices to \"" + unique_da_outfile + "\"" );
1092         //
1093     }
1094
1095     public static void preparePhylogeny( final Phylogeny p,
1096                                          final DomainParsimonyCalculator domain_parsimony,
1097                                          final String date_time,
1098                                          final String method,
1099                                          final String name,
1100                                          final String parameters_str ) {
1101         domain_parsimony.decoratePhylogenyWithDomains( p );
1102         final StringBuilder desc = new StringBuilder();
1103         desc.append( "[Method: " + method + "] [Date: " + date_time + "] " );
1104         desc.append( "[Cost: " + domain_parsimony.getCost() + "] " );
1105         desc.append( "[Gains: " + domain_parsimony.getTotalGains() + "] " );
1106         desc.append( "[Losses: " + domain_parsimony.getTotalLosses() + "] " );
1107         desc.append( "[Unchanged: " + domain_parsimony.getTotalUnchanged() + "] " );
1108         desc.append( "[Parameters: " + parameters_str + "]" );
1109         p.setName( name );
1110         p.setDescription( desc.toString() );
1111         p.setConfidence( new Confidence( domain_parsimony.getCost(), "parsimony" ) );
1112         p.setRerootable( false );
1113         p.setRooted( true );
1114     }
1115
1116     /*
1117      * species | protein id | n-terminal domain | c-terminal domain | n-terminal domain per domain E-value | c-terminal domain per domain E-value
1118      * 
1119      * 
1120      */
1121     static public StringBuffer proteinToDomainCombinations( final Protein protein,
1122                                                             final String protein_id,
1123                                                             final String separator ) {
1124         final StringBuffer sb = new StringBuffer();
1125         if ( protein.getSpecies() == null ) {
1126             throw new IllegalArgumentException( "species must not be null" );
1127         }
1128         if ( ForesterUtil.isEmpty( protein.getSpecies().getSpeciesId() ) ) {
1129             throw new IllegalArgumentException( "species id must not be empty" );
1130         }
1131         final List<Domain> domains = protein.getProteinDomains();
1132         if ( domains.size() > 1 ) {
1133             final Map<String, Integer> counts = new HashMap<String, Integer>();
1134             for( final Domain domain : domains ) {
1135                 final String id = domain.getDomainId();
1136                 if ( counts.containsKey( id ) ) {
1137                     counts.put( id, counts.get( id ) + 1 );
1138                 }
1139                 else {
1140                     counts.put( id, 1 );
1141                 }
1142             }
1143             final Set<String> dcs = new HashSet<String>();
1144             for( int i = 1; i < domains.size(); ++i ) {
1145                 for( int j = 0; j < i; ++j ) {
1146                     Domain domain_n = domains.get( i );
1147                     Domain domain_c = domains.get( j );
1148                     if ( domain_n.getFrom() > domain_c.getFrom() ) {
1149                         domain_n = domains.get( j );
1150                         domain_c = domains.get( i );
1151                     }
1152                     final String dc = domain_n.getDomainId() + domain_c.getDomainId();
1153                     if ( !dcs.contains( dc ) ) {
1154                         dcs.add( dc );
1155                         sb.append( protein.getSpecies() );
1156                         sb.append( separator );
1157                         sb.append( protein_id );
1158                         sb.append( separator );
1159                         sb.append( domain_n.getDomainId() );
1160                         sb.append( separator );
1161                         sb.append( domain_c.getDomainId() );
1162                         sb.append( separator );
1163                         sb.append( domain_n.getPerDomainEvalue() );
1164                         sb.append( separator );
1165                         sb.append( domain_c.getPerDomainEvalue() );
1166                         sb.append( separator );
1167                         sb.append( counts.get( domain_n.getDomainId() ) );
1168                         sb.append( separator );
1169                         sb.append( counts.get( domain_c.getDomainId() ) );
1170                         sb.append( ForesterUtil.LINE_SEPARATOR );
1171                     }
1172                 }
1173             }
1174         }
1175         else if ( domains.size() == 1 ) {
1176             sb.append( protein.getSpecies() );
1177             sb.append( separator );
1178             sb.append( protein_id );
1179             sb.append( separator );
1180             sb.append( domains.get( 0 ).getDomainId() );
1181             sb.append( separator );
1182             sb.append( separator );
1183             sb.append( domains.get( 0 ).getPerDomainEvalue() );
1184             sb.append( separator );
1185             sb.append( separator );
1186             sb.append( 1 );
1187             sb.append( separator );
1188             sb.append( ForesterUtil.LINE_SEPARATOR );
1189         }
1190         else {
1191             sb.append( protein.getSpecies() );
1192             sb.append( separator );
1193             sb.append( protein_id );
1194             sb.append( separator );
1195             sb.append( separator );
1196             sb.append( separator );
1197             sb.append( separator );
1198             sb.append( separator );
1199             sb.append( separator );
1200             sb.append( ForesterUtil.LINE_SEPARATOR );
1201         }
1202         return sb;
1203     }
1204
1205     /**
1206      * 
1207      * Example regarding engulfment: ------------0.1 ----------0.2 --0.3 =>
1208      * domain with 0.3 is ignored
1209      * 
1210      * -----------0.1 ----------0.2 --0.3 => domain with 0.3 is ignored
1211      * 
1212      * 
1213      * ------------0.1 ----------0.3 --0.2 => domains with 0.3 and 0.2 are _not_
1214      * ignored
1215      * 
1216      * @param max_allowed_overlap
1217      *            maximal allowed overlap (inclusive) to be still considered not
1218      *            overlapping (zero or negative value to allow any overlap)
1219      * @param remove_engulfed_domains
1220      *            to remove domains which are completely engulfed by coverage of
1221      *            domains with better support
1222      * @param protein
1223      * @return
1224      */
1225     public static Protein removeOverlappingDomains( final int max_allowed_overlap,
1226                                                     final boolean remove_engulfed_domains,
1227                                                     final Protein protein ) {
1228         final Protein pruned_protein = new BasicProtein( protein.getProteinId().getId(), protein.getSpecies()
1229                 .getSpeciesId(), protein.getLength() );
1230         final List<Domain> sorted = SurfacingUtil.sortDomainsWithAscendingConfidenceValues( protein );
1231         final List<Boolean> covered_positions = new ArrayList<Boolean>();
1232         for( final Domain domain : sorted ) {
1233             if ( ( ( max_allowed_overlap < 0 ) || ( SurfacingUtil.calculateOverlap( domain, covered_positions ) <= max_allowed_overlap ) )
1234                     && ( !remove_engulfed_domains || !isEngulfed( domain, covered_positions ) ) ) {
1235                 final int covered_positions_size = covered_positions.size();
1236                 for( int i = covered_positions_size; i < domain.getFrom(); ++i ) {
1237                     covered_positions.add( false );
1238                 }
1239                 final int new_covered_positions_size = covered_positions.size();
1240                 for( int i = domain.getFrom(); i <= domain.getTo(); ++i ) {
1241                     if ( i < new_covered_positions_size ) {
1242                         covered_positions.set( i, true );
1243                     }
1244                     else {
1245                         covered_positions.add( true );
1246                     }
1247                 }
1248                 pruned_protein.addProteinDomain( domain );
1249             }
1250         }
1251         return pruned_protein;
1252     }
1253
1254     public static List<Domain> sortDomainsWithAscendingConfidenceValues( final Protein protein ) {
1255         final List<Domain> domains = new ArrayList<Domain>();
1256         for( final Domain d : protein.getProteinDomains() ) {
1257             domains.add( d );
1258         }
1259         Collections.sort( domains, SurfacingUtil.ASCENDING_CONFIDENCE_VALUE_ORDER );
1260         return domains;
1261     }
1262
1263     public static int storeDomainArchitectures( final String genome,
1264                                                 final SortedMap<String, Set<String>> domain_architecutures,
1265                                                 final List<Protein> protein_list,
1266                                                 final Map<String, Integer> distinct_domain_architecuture_counts ) {
1267         final Set<String> da = new HashSet<String>();
1268         domain_architecutures.put( genome, da );
1269         for( final Protein protein : protein_list ) {
1270             final String da_str = ( ( BasicProtein ) protein ).toDomainArchitectureString( "~", 3, "=" );
1271             if ( !da.contains( da_str ) ) {
1272                 if ( !distinct_domain_architecuture_counts.containsKey( da_str ) ) {
1273                     distinct_domain_architecuture_counts.put( da_str, 1 );
1274                 }
1275                 else {
1276                     distinct_domain_architecuture_counts.put( da_str,
1277                                                               distinct_domain_architecuture_counts.get( da_str ) + 1 );
1278                 }
1279                 da.add( da_str );
1280             }
1281         }
1282         return da.size();
1283     }
1284
1285     public static void writeAllDomainsChangedOnAllSubtrees( final Phylogeny p,
1286                                                             final boolean get_gains,
1287                                                             final String outdir,
1288                                                             final String suffix_for_filename ) throws IOException {
1289         CharacterStateMatrix.GainLossStates state = CharacterStateMatrix.GainLossStates.GAIN;
1290         if ( !get_gains ) {
1291             state = CharacterStateMatrix.GainLossStates.LOSS;
1292         }
1293         final File base_dir = createBaseDirForPerNodeDomainFiles( surfacing.BASE_DIRECTORY_PER_SUBTREE_DOMAIN_GAIN_LOSS_FILES,
1294                                                                   false,
1295                                                                   state,
1296                                                                   outdir );
1297         for( final PhylogenyNodeIterator it = p.iteratorPostorder(); it.hasNext(); ) {
1298             final PhylogenyNode node = it.next();
1299             if ( !node.isExternal() ) {
1300                 final SortedSet<String> domains = collectAllDomainsChangedOnSubtree( node, get_gains );
1301                 if ( domains.size() > 0 ) {
1302                     final Writer writer = ForesterUtil.createBufferedWriter( base_dir + ForesterUtil.FILE_SEPARATOR
1303                             + node.getName() + suffix_for_filename );
1304                     for( final String domain : domains ) {
1305                         writer.write( domain );
1306                         writer.write( ForesterUtil.LINE_SEPARATOR );
1307                     }
1308                     writer.close();
1309                 }
1310             }
1311         }
1312     }
1313
1314     public static void writeBinaryDomainCombinationsFileForGraphAnalysis( final String[][] input_file_properties,
1315                                                                           final File output_dir,
1316                                                                           final GenomeWideCombinableDomains gwcd,
1317                                                                           final int i,
1318                                                                           final GenomeWideCombinableDomainsSortOrder dc_sort_order ) {
1319         File dc_outfile_dot = new File( input_file_properties[ i ][ 1 ]
1320                 + surfacing.DOMAIN_COMBINITONS_OUTPUTFILE_SUFFIX_FOR_GRAPH_ANALYSIS );
1321         if ( output_dir != null ) {
1322             dc_outfile_dot = new File( output_dir + ForesterUtil.FILE_SEPARATOR + dc_outfile_dot );
1323         }
1324         checkForOutputFileWriteability( dc_outfile_dot );
1325         final SortedSet<BinaryDomainCombination> binary_combinations = createSetOfAllBinaryDomainCombinationsPerGenome( gwcd );
1326         try {
1327             final BufferedWriter out_dot = new BufferedWriter( new FileWriter( dc_outfile_dot ) );
1328             for( final BinaryDomainCombination bdc : binary_combinations ) {
1329                 out_dot.write( bdc.toGraphDescribingLanguage( BinaryDomainCombination.OutputFormat.DOT, null, null )
1330                         .toString() );
1331                 out_dot.write( SurfacingConstants.NL );
1332             }
1333             out_dot.close();
1334         }
1335         catch ( final IOException e ) {
1336             ForesterUtil.fatalError( surfacing.PRG_NAME, e.getMessage() );
1337         }
1338         ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote binary domain combination for \""
1339                 + input_file_properties[ i ][ 0 ] + "\" (" + input_file_properties[ i ][ 1 ] + ", "
1340                 + input_file_properties[ i ][ 2 ] + ") to: \"" + dc_outfile_dot + "\"" );
1341     }
1342
1343     public static void writeBinaryStatesMatrixAsListToFile( final CharacterStateMatrix<CharacterStateMatrix.GainLossStates> matrix,
1344                                                             final CharacterStateMatrix.GainLossStates state,
1345                                                             final String filename,
1346                                                             final String indentifier_characters_separator,
1347                                                             final String character_separator,
1348                                                             final Map<String, String> descriptions ) {
1349         final File outfile = new File( filename );
1350         checkForOutputFileWriteability( outfile );
1351         final SortedSet<String> sorted_ids = new TreeSet<String>();
1352         for( int i = 0; i < matrix.getNumberOfIdentifiers(); ++i ) {
1353             sorted_ids.add( matrix.getIdentifier( i ) );
1354         }
1355         try {
1356             final BufferedWriter out = new BufferedWriter( new FileWriter( outfile ) );
1357             for( final String id : sorted_ids ) {
1358                 out.write( indentifier_characters_separator );
1359                 out.write( "#" + id );
1360                 out.write( indentifier_characters_separator );
1361                 for( int c = 0; c < matrix.getNumberOfCharacters(); ++c ) {
1362                     // Not nice:
1363                     // using null to indicate either UNCHANGED_PRESENT or GAIN.
1364                     if ( ( matrix.getState( id, c ) == state )
1365                             || ( ( state == null ) && ( ( matrix.getState( id, c ) == CharacterStateMatrix.GainLossStates.GAIN ) || ( matrix
1366                                     .getState( id, c ) == CharacterStateMatrix.GainLossStates.UNCHANGED_PRESENT ) ) ) ) {
1367                         out.write( matrix.getCharacter( c ) );
1368                         if ( ( descriptions != null ) && !descriptions.isEmpty()
1369                                 && descriptions.containsKey( matrix.getCharacter( c ) ) ) {
1370                             out.write( "\t" );
1371                             out.write( descriptions.get( matrix.getCharacter( c ) ) );
1372                         }
1373                         out.write( character_separator );
1374                     }
1375                 }
1376             }
1377             out.flush();
1378             out.close();
1379         }
1380         catch ( final IOException e ) {
1381             ForesterUtil.fatalError( surfacing.PRG_NAME, e.getMessage() );
1382         }
1383         ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote characters list: \"" + filename + "\"" );
1384     }
1385
1386     public static void writeBinaryStatesMatrixAsListToFileForBinaryCombinationsForGraphAnalysis( final CharacterStateMatrix<CharacterStateMatrix.GainLossStates> matrix,
1387                                                                                                  final CharacterStateMatrix.GainLossStates state,
1388                                                                                                  final String filename,
1389                                                                                                  final String indentifier_characters_separator,
1390                                                                                                  final String character_separator,
1391                                                                                                  final BinaryDomainCombination.OutputFormat bc_output_format ) {
1392         final File outfile = new File( filename );
1393         checkForOutputFileWriteability( outfile );
1394         final SortedSet<String> sorted_ids = new TreeSet<String>();
1395         for( int i = 0; i < matrix.getNumberOfIdentifiers(); ++i ) {
1396             sorted_ids.add( matrix.getIdentifier( i ) );
1397         }
1398         try {
1399             final BufferedWriter out = new BufferedWriter( new FileWriter( outfile ) );
1400             for( final String id : sorted_ids ) {
1401                 out.write( indentifier_characters_separator );
1402                 out.write( "#" + id );
1403                 out.write( indentifier_characters_separator );
1404                 for( int c = 0; c < matrix.getNumberOfCharacters(); ++c ) {
1405                     // Not nice:
1406                     // using null to indicate either UNCHANGED_PRESENT or GAIN.
1407                     if ( ( matrix.getState( id, c ) == state )
1408                             || ( ( state == null ) && ( ( matrix.getState( id, c ) == CharacterStateMatrix.GainLossStates.GAIN ) || ( matrix
1409                                     .getState( id, c ) == CharacterStateMatrix.GainLossStates.UNCHANGED_PRESENT ) ) ) ) {
1410                         BinaryDomainCombination bdc = null;
1411                         try {
1412                             bdc = BasicBinaryDomainCombination.createInstance( matrix.getCharacter( c ) );
1413                         }
1414                         catch ( final Exception e ) {
1415                             ForesterUtil.fatalError( surfacing.PRG_NAME, e.getLocalizedMessage() );
1416                         }
1417                         out.write( bdc.toGraphDescribingLanguage( bc_output_format, null, null ).toString() );
1418                         out.write( character_separator );
1419                     }
1420                 }
1421             }
1422             out.flush();
1423             out.close();
1424         }
1425         catch ( final IOException e ) {
1426             ForesterUtil.fatalError( surfacing.PRG_NAME, e.getMessage() );
1427         }
1428         ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote characters list: \"" + filename + "\"" );
1429     }
1430
1431     public static void writeBinaryStatesMatrixToList( final Map<String, List<GoId>> domain_id_to_go_ids_map,
1432                                                       final Map<GoId, GoTerm> go_id_to_term_map,
1433                                                       final GoNameSpace go_namespace_limit,
1434                                                       final boolean domain_combinations,
1435                                                       final CharacterStateMatrix<CharacterStateMatrix.GainLossStates> matrix,
1436                                                       final CharacterStateMatrix.GainLossStates state,
1437                                                       final String filename,
1438                                                       final String indentifier_characters_separator,
1439                                                       final String character_separator,
1440                                                       final String title_for_html,
1441                                                       final String prefix_for_html,
1442                                                       final Map<String, Set<String>>[] domain_id_to_secondary_features_maps,
1443                                                       final SortedSet<String> all_pfams_encountered,
1444                                                       final SortedSet<String> pfams_gained_or_lost,
1445                                                       final String suffix_for_per_node_events_file,
1446                                                       final Map<String, Integer> tax_code_to_id_map ) {
1447         if ( ( go_namespace_limit != null ) && ( ( go_id_to_term_map == null ) || ( go_id_to_term_map.size() < 1 ) ) ) {
1448             throw new IllegalArgumentException( "attempt to use GO namespace limit without a GO-id to term map" );
1449         }
1450         else if ( ( ( domain_id_to_go_ids_map == null ) || ( domain_id_to_go_ids_map.size() < 1 ) ) ) {
1451             throw new IllegalArgumentException( "attempt to output detailed HTML without a Pfam to GO map" );
1452         }
1453         else if ( ( ( go_id_to_term_map == null ) || ( go_id_to_term_map.size() < 1 ) ) ) {
1454             throw new IllegalArgumentException( "attempt to output detailed HTML without a GO-id to term map" );
1455         }
1456         final File outfile = new File( filename );
1457         checkForOutputFileWriteability( outfile );
1458         final SortedSet<String> sorted_ids = new TreeSet<String>();
1459         for( int i = 0; i < matrix.getNumberOfIdentifiers(); ++i ) {
1460             sorted_ids.add( matrix.getIdentifier( i ) );
1461         }
1462         try {
1463             final Writer out = new BufferedWriter( new FileWriter( outfile ) );
1464             final File per_node_go_mapped_domain_gain_loss_files_base_dir = createBaseDirForPerNodeDomainFiles( surfacing.BASE_DIRECTORY_PER_NODE_DOMAIN_GAIN_LOSS_FILES,
1465                                                                                                                 domain_combinations,
1466                                                                                                                 state,
1467                                                                                                                 filename );
1468             Writer per_node_go_mapped_domain_gain_loss_outfile_writer = null;
1469             File per_node_go_mapped_domain_gain_loss_outfile = null;
1470             int per_node_counter = 0;
1471             out.write( "<html>" );
1472             out.write( SurfacingConstants.NL );
1473             addHtmlHead( out, title_for_html );
1474             out.write( SurfacingConstants.NL );
1475             out.write( "<body>" );
1476             out.write( SurfacingConstants.NL );
1477             out.write( "<h1>" );
1478             out.write( SurfacingConstants.NL );
1479             out.write( title_for_html );
1480             out.write( SurfacingConstants.NL );
1481             out.write( "</h1>" );
1482             out.write( SurfacingConstants.NL );
1483             out.write( "<table>" );
1484             out.write( SurfacingConstants.NL );
1485             for( final String id : sorted_ids ) {
1486                 final Matcher matcher = PATTERN_SP_STYLE_TAXONOMY.matcher( id );
1487                 if ( matcher.matches() ) {
1488                     continue;
1489                 }
1490                 out.write( "<tr>" );
1491                 out.write( "<td>" );
1492                 out.write( "<a href=\"#" + id + "\">" + id + "</a>" );
1493                 out.write( "</td>" );
1494                 out.write( "</tr>" );
1495                 out.write( SurfacingConstants.NL );
1496             }
1497             out.write( "</table>" );
1498             out.write( SurfacingConstants.NL );
1499             for( final String id : sorted_ids ) {
1500                 final Matcher matcher = PATTERN_SP_STYLE_TAXONOMY.matcher( id );
1501                 if ( matcher.matches() ) {
1502                     continue;
1503                 }
1504                 out.write( SurfacingConstants.NL );
1505                 out.write( "<h2>" );
1506                 out.write( "<a name=\"" + id + "\">" + id + "</a>" );
1507                 writeTaxonomyLinks( out, id, tax_code_to_id_map );
1508                 out.write( "</h2>" );
1509                 out.write( SurfacingConstants.NL );
1510                 out.write( "<table>" );
1511                 out.write( SurfacingConstants.NL );
1512                 out.write( "<tr>" );
1513                 out.write( "<td><b>" );
1514                 out.write( "Pfam domain(s)" );
1515                 out.write( "</b></td><td><b>" );
1516                 out.write( "GO term acc" );
1517                 out.write( "</b></td><td><b>" );
1518                 out.write( "GO term" );
1519                 out.write( "</b></td><td><b>" );
1520                 out.write( "GO namespace" );
1521                 out.write( "</b></td>" );
1522                 out.write( "</tr>" );
1523                 out.write( SurfacingConstants.NL );
1524                 out.write( "</tr>" );
1525                 out.write( SurfacingConstants.NL );
1526                 per_node_counter = 0;
1527                 if ( matrix.getNumberOfCharacters() > 0 ) {
1528                     per_node_go_mapped_domain_gain_loss_outfile = new File( per_node_go_mapped_domain_gain_loss_files_base_dir
1529                             + ForesterUtil.FILE_SEPARATOR + id + suffix_for_per_node_events_file );
1530                     SurfacingUtil.checkForOutputFileWriteability( per_node_go_mapped_domain_gain_loss_outfile );
1531                     per_node_go_mapped_domain_gain_loss_outfile_writer = ForesterUtil
1532                             .createBufferedWriter( per_node_go_mapped_domain_gain_loss_outfile );
1533                 }
1534                 else {
1535                     per_node_go_mapped_domain_gain_loss_outfile = null;
1536                     per_node_go_mapped_domain_gain_loss_outfile_writer = null;
1537                 }
1538                 for( int c = 0; c < matrix.getNumberOfCharacters(); ++c ) {
1539                     // Not nice:
1540                     // using null to indicate either UNCHANGED_PRESENT or GAIN.
1541                     if ( ( matrix.getState( id, c ) == state )
1542                             || ( ( state == null ) && ( ( matrix.getState( id, c ) == CharacterStateMatrix.GainLossStates.UNCHANGED_PRESENT ) || ( matrix
1543                                     .getState( id, c ) == CharacterStateMatrix.GainLossStates.GAIN ) ) ) ) {
1544                         final String character = matrix.getCharacter( c );
1545                         String domain_0 = "";
1546                         String domain_1 = "";
1547                         if ( character.indexOf( BinaryDomainCombination.SEPARATOR ) > 0 ) {
1548                             final String[] s = character.split( BinaryDomainCombination.SEPARATOR );
1549                             if ( s.length != 2 ) {
1550                                 throw new AssertionError( "this should not have happened: unexpected format for domain combination: ["
1551                                         + character + "]" );
1552                             }
1553                             domain_0 = s[ 0 ];
1554                             domain_1 = s[ 1 ];
1555                         }
1556                         else {
1557                             domain_0 = character;
1558                         }
1559                         writeDomainData( domain_id_to_go_ids_map,
1560                                          go_id_to_term_map,
1561                                          go_namespace_limit,
1562                                          out,
1563                                          domain_0,
1564                                          domain_1,
1565                                          prefix_for_html,
1566                                          character_separator,
1567                                          domain_id_to_secondary_features_maps,
1568                                          null );
1569                         all_pfams_encountered.add( domain_0 );
1570                         if ( pfams_gained_or_lost != null ) {
1571                             pfams_gained_or_lost.add( domain_0 );
1572                         }
1573                         if ( !ForesterUtil.isEmpty( domain_1 ) ) {
1574                             all_pfams_encountered.add( domain_1 );
1575                             if ( pfams_gained_or_lost != null ) {
1576                                 pfams_gained_or_lost.add( domain_1 );
1577                             }
1578                         }
1579                         if ( per_node_go_mapped_domain_gain_loss_outfile_writer != null ) {
1580                             writeDomainsToIndividualFilePerTreeNode( per_node_go_mapped_domain_gain_loss_outfile_writer,
1581                                                                      domain_0,
1582                                                                      domain_1 );
1583                             per_node_counter++;
1584                         }
1585                     }
1586                 }
1587                 if ( per_node_go_mapped_domain_gain_loss_outfile_writer != null ) {
1588                     per_node_go_mapped_domain_gain_loss_outfile_writer.close();
1589                     if ( per_node_counter < 1 ) {
1590                         per_node_go_mapped_domain_gain_loss_outfile.delete();
1591                     }
1592                     per_node_counter = 0;
1593                 }
1594                 out.write( "</table>" );
1595                 out.write( SurfacingConstants.NL );
1596                 out.write( "<hr>" );
1597                 out.write( SurfacingConstants.NL );
1598             } // for( final String id : sorted_ids ) {  
1599             out.write( "</body>" );
1600             out.write( SurfacingConstants.NL );
1601             out.write( "</html>" );
1602             out.write( SurfacingConstants.NL );
1603             out.flush();
1604             out.close();
1605         }
1606         catch ( final IOException e ) {
1607             ForesterUtil.fatalError( surfacing.PRG_NAME, e.getMessage() );
1608         }
1609         ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote characters detailed HTML list: \"" + filename + "\"" );
1610     }
1611
1612     public static void writeDomainCombinationsCountsFile( final String[][] input_file_properties,
1613                                                           final File output_dir,
1614                                                           final Writer per_genome_domain_promiscuity_statistics_writer,
1615                                                           final GenomeWideCombinableDomains gwcd,
1616                                                           final int i,
1617                                                           final GenomeWideCombinableDomains.GenomeWideCombinableDomainsSortOrder dc_sort_order ) {
1618         File dc_outfile = new File( input_file_properties[ i ][ 1 ]
1619                 + surfacing.DOMAIN_COMBINITON_COUNTS_OUTPUTFILE_SUFFIX );
1620         if ( output_dir != null ) {
1621             dc_outfile = new File( output_dir + ForesterUtil.FILE_SEPARATOR + dc_outfile );
1622         }
1623         checkForOutputFileWriteability( dc_outfile );
1624         try {
1625             final BufferedWriter out = new BufferedWriter( new FileWriter( dc_outfile ) );
1626             out.write( gwcd.toStringBuilder( dc_sort_order ).toString() );
1627             out.close();
1628         }
1629         catch ( final IOException e ) {
1630             ForesterUtil.fatalError( surfacing.PRG_NAME, e.getMessage() );
1631         }
1632         final DescriptiveStatistics stats = gwcd.getPerGenomeDomainPromiscuityStatistics();
1633         try {
1634             per_genome_domain_promiscuity_statistics_writer.write( input_file_properties[ i ][ 1 ] + "\t" );
1635             per_genome_domain_promiscuity_statistics_writer.write( FORMATTER_3.format( stats.arithmeticMean() ) + "\t" );
1636             if ( stats.getN() < 2 ) {
1637                 per_genome_domain_promiscuity_statistics_writer.write( "n/a" + "\t" );
1638             }
1639             else {
1640                 per_genome_domain_promiscuity_statistics_writer.write( FORMATTER_3.format( stats
1641                         .sampleStandardDeviation() ) + "\t" );
1642             }
1643             per_genome_domain_promiscuity_statistics_writer.write( FORMATTER_3.format( stats.median() ) + "\t" );
1644             per_genome_domain_promiscuity_statistics_writer.write( ( int ) stats.getMin() + "\t" );
1645             per_genome_domain_promiscuity_statistics_writer.write( ( int ) stats.getMax() + "\t" );
1646             per_genome_domain_promiscuity_statistics_writer.write( stats.getN() + "\t" );
1647             final SortedSet<String> mpds = gwcd.getMostPromiscuosDomain();
1648             for( final String mpd : mpds ) {
1649                 per_genome_domain_promiscuity_statistics_writer.write( mpd + " " );
1650             }
1651             per_genome_domain_promiscuity_statistics_writer.write( ForesterUtil.LINE_SEPARATOR );
1652         }
1653         catch ( final IOException e ) {
1654             ForesterUtil.fatalError( surfacing.PRG_NAME, e.getMessage() );
1655         }
1656         if ( input_file_properties[ i ].length == 3 ) {
1657             ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote domain combination counts for \""
1658                     + input_file_properties[ i ][ 0 ] + "\" (" + input_file_properties[ i ][ 1 ] + ", "
1659                     + input_file_properties[ i ][ 2 ] + ") to: \"" + dc_outfile + "\"" );
1660         }
1661         else {
1662             ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote domain combination counts for \""
1663                     + input_file_properties[ i ][ 0 ] + "\" (" + input_file_properties[ i ][ 1 ] + ") to: \""
1664                     + dc_outfile + "\"" );
1665         }
1666     }
1667
1668     public static void writeDomainSimilaritiesToFile( final StringBuilder html_desc,
1669                                                       final StringBuilder html_title,
1670                                                       final Writer single_writer,
1671                                                       Map<Character, Writer> split_writers,
1672                                                       final SortedSet<DomainSimilarity> similarities,
1673                                                       final boolean treat_as_binary,
1674                                                       final List<Species> species_order,
1675                                                       final PrintableDomainSimilarity.PRINT_OPTION print_option,
1676                                                       final DomainSimilarity.DomainSimilarityScoring scoring,
1677                                                       final boolean verbose,
1678                                                       final Map<String, Integer> tax_code_to_id_map )
1679             throws IOException {
1680         if ( ( single_writer != null ) && ( ( split_writers == null ) || split_writers.isEmpty() ) ) {
1681             split_writers = new HashMap<Character, Writer>();
1682             split_writers.put( '_', single_writer );
1683         }
1684         switch ( print_option ) {
1685             case SIMPLE_TAB_DELIMITED:
1686                 break;
1687             case HTML:
1688                 for( final Character key : split_writers.keySet() ) {
1689                     final Writer w = split_writers.get( key );
1690                     w.write( "<html>" );
1691                     w.write( SurfacingConstants.NL );
1692                     if ( key != '_' ) {
1693                         addHtmlHead( w, "DC analysis (" + html_title + ") " + key.toString().toUpperCase() );
1694                     }
1695                     else {
1696                         addHtmlHead( w, "DC analysis (" + html_title + ")" );
1697                     }
1698                     w.write( SurfacingConstants.NL );
1699                     w.write( "<body>" );
1700                     w.write( SurfacingConstants.NL );
1701                     w.write( html_desc.toString() );
1702                     w.write( SurfacingConstants.NL );
1703                     w.write( "<hr>" );
1704                     w.write( SurfacingConstants.NL );
1705                     w.write( "<br>" );
1706                     w.write( SurfacingConstants.NL );
1707                     w.write( "<table>" );
1708                     w.write( SurfacingConstants.NL );
1709                     w.write( "<tr><td><b>Domains:</b></td></tr>" );
1710                     w.write( SurfacingConstants.NL );
1711                 }
1712                 break;
1713         }
1714         //
1715         for( final DomainSimilarity similarity : similarities ) {
1716             if ( ( species_order != null ) && !species_order.isEmpty() ) {
1717                 ( ( PrintableDomainSimilarity ) similarity ).setSpeciesOrder( species_order );
1718             }
1719             if ( single_writer != null ) {
1720                 single_writer.write( "<tr><td><b><a href=\"#" + similarity.getDomainId() + "\">"
1721                         + similarity.getDomainId() + "</a></b></td></tr>" );
1722                 single_writer.write( SurfacingConstants.NL );
1723             }
1724             else {
1725                 Writer local_writer = split_writers.get( ( similarity.getDomainId().charAt( 0 ) + "" ).toLowerCase()
1726                         .charAt( 0 ) );
1727                 if ( local_writer == null ) {
1728                     local_writer = split_writers.get( '0' );
1729                 }
1730                 local_writer.write( "<tr><td><b><a href=\"#" + similarity.getDomainId() + "\">"
1731                         + similarity.getDomainId() + "</a></b></td></tr>" );
1732                 local_writer.write( SurfacingConstants.NL );
1733             }
1734         }
1735         for( final Writer w : split_writers.values() ) {
1736             w.write( "</table>" );
1737             w.write( SurfacingConstants.NL );
1738             w.write( "<hr>" );
1739             w.write( SurfacingConstants.NL );
1740             w.write( "<table>" );
1741             w.write( SurfacingConstants.NL );
1742         }
1743         //
1744         for( final DomainSimilarity similarity : similarities ) {
1745             if ( ( species_order != null ) && !species_order.isEmpty() ) {
1746                 ( ( PrintableDomainSimilarity ) similarity ).setSpeciesOrder( species_order );
1747             }
1748             if ( single_writer != null ) {
1749                 single_writer.write( similarity.toStringBuffer( print_option, tax_code_to_id_map ).toString() );
1750                 single_writer.write( SurfacingConstants.NL );
1751             }
1752             else {
1753                 Writer local_writer = split_writers.get( ( similarity.getDomainId().charAt( 0 ) + "" ).toLowerCase()
1754                         .charAt( 0 ) );
1755                 if ( local_writer == null ) {
1756                     local_writer = split_writers.get( '0' );
1757                 }
1758                 local_writer.write( similarity.toStringBuffer( print_option, tax_code_to_id_map ).toString() );
1759                 local_writer.write( SurfacingConstants.NL );
1760             }
1761         }
1762         switch ( print_option ) {
1763             case HTML:
1764                 for( final Writer w : split_writers.values() ) {
1765                     w.write( SurfacingConstants.NL );
1766                     w.write( "</table>" );
1767                     w.write( SurfacingConstants.NL );
1768                     w.write( "</font>" );
1769                     w.write( SurfacingConstants.NL );
1770                     w.write( "</body>" );
1771                     w.write( SurfacingConstants.NL );
1772                     w.write( "</html>" );
1773                     w.write( SurfacingConstants.NL );
1774                 }
1775                 break;
1776         }
1777         for( final Writer w : split_writers.values() ) {
1778             w.close();
1779         }
1780     }
1781
1782     private static void printSomeStats( final DescriptiveStatistics stats, final AsciiHistogram histo, final Writer w )
1783             throws IOException {
1784         w.write( "<hr>" );
1785         w.write( "<br>" );
1786         w.write( SurfacingConstants.NL );
1787         w.write( "<tt><pre>" );
1788         w.write( SurfacingConstants.NL );
1789         if ( histo != null ) {
1790             w.write( histo.toStringBuffer( 20, '|', 40, 5 ).toString() );
1791             w.write( SurfacingConstants.NL );
1792         }
1793         w.write( "</pre></tt>" );
1794         w.write( SurfacingConstants.NL );
1795         w.write( "<table>" );
1796         w.write( SurfacingConstants.NL );
1797         w.write( "<tr><td>N: </td><td>" + stats.getN() + "</td></tr>" );
1798         w.write( SurfacingConstants.NL );
1799         w.write( "<tr><td>Min: </td><td>" + stats.getMin() + "</td></tr>" );
1800         w.write( SurfacingConstants.NL );
1801         w.write( "<tr><td>Max: </td><td>" + stats.getMax() + "</td></tr>" );
1802         w.write( SurfacingConstants.NL );
1803         w.write( "<tr><td>Mean: </td><td>" + stats.arithmeticMean() + "</td></tr>" );
1804         w.write( SurfacingConstants.NL );
1805         if ( stats.getN() > 1 ) {
1806             w.write( "<tr><td>SD: </td><td>" + stats.sampleStandardDeviation() + "</td></tr>" );
1807         }
1808         else {
1809             w.write( "<tr><td>SD: </td><td>n/a</td></tr>" );
1810         }
1811         w.write( SurfacingConstants.NL );
1812         w.write( "</table>" );
1813         w.write( SurfacingConstants.NL );
1814         w.write( "<br>" );
1815         w.write( SurfacingConstants.NL );
1816     }
1817
1818     public static void writeMatrixToFile( final CharacterStateMatrix<?> matrix,
1819                                           final String filename,
1820                                           final Format format ) {
1821         final File outfile = new File( filename );
1822         checkForOutputFileWriteability( outfile );
1823         try {
1824             final BufferedWriter out = new BufferedWriter( new FileWriter( outfile ) );
1825             matrix.toWriter( out, format );
1826             out.flush();
1827             out.close();
1828         }
1829         catch ( final IOException e ) {
1830             ForesterUtil.fatalError( surfacing.PRG_NAME, e.getMessage() );
1831         }
1832         ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote matrix: \"" + filename + "\"" );
1833     }
1834
1835     public static void writeMatrixToFile( final File matrix_outfile, final List<DistanceMatrix> matrices ) {
1836         checkForOutputFileWriteability( matrix_outfile );
1837         try {
1838             final BufferedWriter out = new BufferedWriter( new FileWriter( matrix_outfile ) );
1839             for( final DistanceMatrix distance_matrix : matrices ) {
1840                 out.write( distance_matrix.toStringBuffer( DistanceMatrix.Format.PHYLIP ).toString() );
1841                 out.write( ForesterUtil.LINE_SEPARATOR );
1842                 out.flush();
1843             }
1844             out.close();
1845         }
1846         catch ( final IOException e ) {
1847             ForesterUtil.fatalError( surfacing.PRG_NAME, e.getMessage() );
1848         }
1849         ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote distance matrices to \"" + matrix_outfile + "\"" );
1850     }
1851
1852     public static void writePhylogenyToFile( final Phylogeny phylogeny, final String filename ) {
1853         final PhylogenyWriter writer = new PhylogenyWriter();
1854         try {
1855             writer.toPhyloXML( new File( filename ), phylogeny, 1 );
1856         }
1857         catch ( final IOException e ) {
1858             ForesterUtil.printWarningMessage( surfacing.PRG_NAME, "failed to write phylogeny to \"" + filename + "\": "
1859                     + e );
1860         }
1861         ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote phylogeny to \"" + filename + "\"" );
1862     }
1863
1864     public static void writeTaxonomyLinks( final Writer writer,
1865                                            final String species,
1866                                            final Map<String, Integer> tax_code_to_id_map ) throws IOException {
1867         if ( ( species.length() > 1 ) && ( species.indexOf( '_' ) < 1 ) ) {
1868             writer.write( " [" );
1869             if ( ( tax_code_to_id_map != null ) && tax_code_to_id_map.containsKey( species ) ) {
1870                 writer.write( "<a href=\"" + SurfacingConstants.UNIPROT_TAXONOMY_ID_LINK
1871                         + tax_code_to_id_map.get( species ) + "\" target=\"taxonomy_window\">uniprot</a>" );
1872             }
1873             else {
1874                 writer.write( "<a href=\"" + SurfacingConstants.EOL_LINK + species
1875                         + "\" target=\"taxonomy_window\">eol</a>" );
1876                 writer.write( "|" );
1877                 writer.write( "<a href=\"" + SurfacingConstants.GOOGLE_SCHOLAR_SEARCH + species
1878                         + "\" target=\"taxonomy_window\">scholar</a>" );
1879                 writer.write( "|" );
1880                 writer.write( "<a href=\"" + SurfacingConstants.GOOGLE_WEB_SEARCH_LINK + species
1881                         + "\" target=\"taxonomy_window\">google</a>" );
1882             }
1883             writer.write( "]" );
1884         }
1885     }
1886
1887     private final static void addToCountMap( final Map<String, Integer> map, final String s ) {
1888         if ( map.containsKey( s ) ) {
1889             map.put( s, map.get( s ) + 1 );
1890         }
1891         else {
1892             map.put( s, 1 );
1893         }
1894     }
1895
1896     private static void calculateIndependentDomainCombinationGains( final Phylogeny local_phylogeny_l,
1897                                                                     final String outfilename_for_counts,
1898                                                                     final String outfilename_for_dc,
1899                                                                     final String outfilename_for_dc_for_go_mapping,
1900                                                                     final String outfilename_for_dc_for_go_mapping_unique,
1901                                                                     final String outfilename_for_rank_counts,
1902                                                                     final String outfilename_for_ancestor_species_counts,
1903                                                                     final String outfilename_for_protein_stats,
1904                                                                     final Map<String, DescriptiveStatistics> protein_length_stats_by_dc,
1905                                                                     final Map<String, DescriptiveStatistics> domain_number_stats_by_dc,
1906                                                                     final Map<String, DescriptiveStatistics> domain_length_stats_by_domain ) {
1907         try {
1908             //
1909             //            if ( protein_length_stats_by_dc != null ) {
1910             //                for( final Entry<?, DescriptiveStatistics> entry : protein_length_stats_by_dc.entrySet() ) {
1911             //                    System.out.print( entry.getKey().toString() );
1912             //                    System.out.print( ": " );
1913             //                    double[] a = entry.getValue().getDataAsDoubleArray();
1914             //                    for( int i = 0; i < a.length; i++ ) {
1915             //                        System.out.print( a[ i ] + " " );
1916             //                    }
1917             //                    System.out.println();
1918             //                }
1919             //            }
1920             //            if ( domain_number_stats_by_dc != null ) {
1921             //                for( final Entry<?, DescriptiveStatistics> entry : domain_number_stats_by_dc.entrySet() ) {
1922             //                    System.out.print( entry.getKey().toString() );
1923             //                    System.out.print( ": " );
1924             //                    double[] a = entry.getValue().getDataAsDoubleArray();
1925             //                    for( int i = 0; i < a.length; i++ ) {
1926             //                        System.out.print( a[ i ] + " " );
1927             //                    }
1928             //                    System.out.println();
1929             //                }
1930             //            }
1931             //
1932             final BufferedWriter out_counts = new BufferedWriter( new FileWriter( outfilename_for_counts ) );
1933             final BufferedWriter out_dc = new BufferedWriter( new FileWriter( outfilename_for_dc ) );
1934             final BufferedWriter out_dc_for_go_mapping = new BufferedWriter( new FileWriter( outfilename_for_dc_for_go_mapping ) );
1935             final BufferedWriter out_dc_for_go_mapping_unique = new BufferedWriter( new FileWriter( outfilename_for_dc_for_go_mapping_unique ) );
1936             final SortedMap<String, Integer> dc_gain_counts = new TreeMap<String, Integer>();
1937             for( final PhylogenyNodeIterator it = local_phylogeny_l.iteratorPostorder(); it.hasNext(); ) {
1938                 final PhylogenyNode n = it.next();
1939                 final Set<String> gained_dc = n.getNodeData().getBinaryCharacters().getGainedCharacters();
1940                 for( final String dc : gained_dc ) {
1941                     if ( dc_gain_counts.containsKey( dc ) ) {
1942                         dc_gain_counts.put( dc, dc_gain_counts.get( dc ) + 1 );
1943                     }
1944                     else {
1945                         dc_gain_counts.put( dc, 1 );
1946                     }
1947                 }
1948             }
1949             final SortedMap<Integer, Integer> histogram = new TreeMap<Integer, Integer>();
1950             final SortedMap<Integer, StringBuilder> domain_lists = new TreeMap<Integer, StringBuilder>();
1951             final SortedMap<Integer, DescriptiveStatistics> dc_reapp_counts_to_protein_length_stats = new TreeMap<Integer, DescriptiveStatistics>();
1952             final SortedMap<Integer, DescriptiveStatistics> dc_reapp_counts_to_domain_number_stats = new TreeMap<Integer, DescriptiveStatistics>();
1953             final SortedMap<Integer, DescriptiveStatistics> dc_reapp_counts_to_domain_lengths_stats = new TreeMap<Integer, DescriptiveStatistics>();
1954             final SortedMap<Integer, PriorityQueue<String>> domain_lists_go = new TreeMap<Integer, PriorityQueue<String>>();
1955             final SortedMap<Integer, SortedSet<String>> domain_lists_go_unique = new TreeMap<Integer, SortedSet<String>>();
1956             final Set<String> dcs = dc_gain_counts.keySet();
1957             final SortedSet<String> more_than_once = new TreeSet<String>();
1958             DescriptiveStatistics gained_once_lengths_stats = new BasicDescriptiveStatistics();
1959             DescriptiveStatistics gained_once_domain_count_stats = new BasicDescriptiveStatistics();
1960             DescriptiveStatistics gained_multiple_times_lengths_stats = new BasicDescriptiveStatistics();
1961             final DescriptiveStatistics gained_multiple_times_domain_count_stats = new BasicDescriptiveStatistics();
1962             long gained_multiple_times_domain_length_sum = 0;
1963             long gained_once_domain_length_sum = 0;
1964             long gained_multiple_times_domain_length_count = 0;
1965             long gained_once_domain_length_count = 0;
1966             for( final String dc : dcs ) {
1967                 final int count = dc_gain_counts.get( dc );
1968                 if ( histogram.containsKey( count ) ) {
1969                     histogram.put( count, histogram.get( count ) + 1 );
1970                     domain_lists.get( count ).append( ", " + dc );
1971                     domain_lists_go.get( count ).addAll( splitDomainCombination( dc ) );
1972                     domain_lists_go_unique.get( count ).addAll( splitDomainCombination( dc ) );
1973                 }
1974                 else {
1975                     histogram.put( count, 1 );
1976                     domain_lists.put( count, new StringBuilder( dc ) );
1977                     final PriorityQueue<String> q = new PriorityQueue<String>();
1978                     q.addAll( splitDomainCombination( dc ) );
1979                     domain_lists_go.put( count, q );
1980                     final SortedSet<String> set = new TreeSet<String>();
1981                     set.addAll( splitDomainCombination( dc ) );
1982                     domain_lists_go_unique.put( count, set );
1983                 }
1984                 if ( protein_length_stats_by_dc != null ) {
1985                     if ( !dc_reapp_counts_to_protein_length_stats.containsKey( count ) ) {
1986                         dc_reapp_counts_to_protein_length_stats.put( count, new BasicDescriptiveStatistics() );
1987                     }
1988                     dc_reapp_counts_to_protein_length_stats.get( count ).addValue( protein_length_stats_by_dc.get( dc )
1989                             .arithmeticMean() );
1990                 }
1991                 if ( domain_number_stats_by_dc != null ) {
1992                     if ( !dc_reapp_counts_to_domain_number_stats.containsKey( count ) ) {
1993                         dc_reapp_counts_to_domain_number_stats.put( count, new BasicDescriptiveStatistics() );
1994                     }
1995                     dc_reapp_counts_to_domain_number_stats.get( count ).addValue( domain_number_stats_by_dc.get( dc )
1996                             .arithmeticMean() );
1997                 }
1998                 if ( domain_length_stats_by_domain != null ) {
1999                     if ( !dc_reapp_counts_to_domain_lengths_stats.containsKey( count ) ) {
2000                         dc_reapp_counts_to_domain_lengths_stats.put( count, new BasicDescriptiveStatistics() );
2001                     }
2002                     final String[] ds = dc.split( "=" );
2003                     dc_reapp_counts_to_domain_lengths_stats.get( count ).addValue( domain_length_stats_by_domain
2004                             .get( ds[ 0 ] ).arithmeticMean() );
2005                     dc_reapp_counts_to_domain_lengths_stats.get( count ).addValue( domain_length_stats_by_domain
2006                             .get( ds[ 1 ] ).arithmeticMean() );
2007                 }
2008                 if ( count > 1 ) {
2009                     more_than_once.add( dc );
2010                     if ( protein_length_stats_by_dc != null ) {
2011                         final DescriptiveStatistics s = protein_length_stats_by_dc.get( dc );
2012                         for( final double element : s.getData() ) {
2013                             gained_multiple_times_lengths_stats.addValue( element );
2014                         }
2015                     }
2016                     if ( domain_number_stats_by_dc != null ) {
2017                         final DescriptiveStatistics s = domain_number_stats_by_dc.get( dc );
2018                         for( final double element : s.getData() ) {
2019                             gained_multiple_times_domain_count_stats.addValue( element );
2020                         }
2021                     }
2022                     if ( domain_length_stats_by_domain != null ) {
2023                         final String[] ds = dc.split( "=" );
2024                         final DescriptiveStatistics s0 = domain_length_stats_by_domain.get( ds[ 0 ] );
2025                         final DescriptiveStatistics s1 = domain_length_stats_by_domain.get( ds[ 1 ] );
2026                         for( final double element : s0.getData() ) {
2027                             gained_multiple_times_domain_length_sum += element;
2028                             ++gained_multiple_times_domain_length_count;
2029                         }
2030                         for( final double element : s1.getData() ) {
2031                             gained_multiple_times_domain_length_sum += element;
2032                             ++gained_multiple_times_domain_length_count;
2033                         }
2034                     }
2035                 }
2036                 else {
2037                     if ( protein_length_stats_by_dc != null ) {
2038                         final DescriptiveStatistics s = protein_length_stats_by_dc.get( dc );
2039                         for( final double element : s.getData() ) {
2040                             gained_once_lengths_stats.addValue( element );
2041                         }
2042                     }
2043                     if ( domain_number_stats_by_dc != null ) {
2044                         final DescriptiveStatistics s = domain_number_stats_by_dc.get( dc );
2045                         for( final double element : s.getData() ) {
2046                             gained_once_domain_count_stats.addValue( element );
2047                         }
2048                     }
2049                     if ( domain_length_stats_by_domain != null ) {
2050                         final String[] ds = dc.split( "=" );
2051                         final DescriptiveStatistics s0 = domain_length_stats_by_domain.get( ds[ 0 ] );
2052                         final DescriptiveStatistics s1 = domain_length_stats_by_domain.get( ds[ 1 ] );
2053                         for( final double element : s0.getData() ) {
2054                             gained_once_domain_length_sum += element;
2055                             ++gained_once_domain_length_count;
2056                         }
2057                         for( final double element : s1.getData() ) {
2058                             gained_once_domain_length_sum += element;
2059                             ++gained_once_domain_length_count;
2060                         }
2061                     }
2062                 }
2063             }
2064             final Set<Integer> histogram_keys = histogram.keySet();
2065             for( final Integer histogram_key : histogram_keys ) {
2066                 final int count = histogram.get( histogram_key );
2067                 final StringBuilder dc = domain_lists.get( histogram_key );
2068                 out_counts.write( histogram_key + "\t" + count + ForesterUtil.LINE_SEPARATOR );
2069                 out_dc.write( histogram_key + "\t" + dc + ForesterUtil.LINE_SEPARATOR );
2070                 out_dc_for_go_mapping.write( "#" + histogram_key + ForesterUtil.LINE_SEPARATOR );
2071                 final Object[] sorted = domain_lists_go.get( histogram_key ).toArray();
2072                 Arrays.sort( sorted );
2073                 for( final Object domain : sorted ) {
2074                     out_dc_for_go_mapping.write( domain + ForesterUtil.LINE_SEPARATOR );
2075                 }
2076                 out_dc_for_go_mapping_unique.write( "#" + histogram_key + ForesterUtil.LINE_SEPARATOR );
2077                 for( final String domain : domain_lists_go_unique.get( histogram_key ) ) {
2078                     out_dc_for_go_mapping_unique.write( domain + ForesterUtil.LINE_SEPARATOR );
2079                 }
2080             }
2081             out_counts.close();
2082             out_dc.close();
2083             out_dc_for_go_mapping.close();
2084             out_dc_for_go_mapping_unique.close();
2085             final SortedMap<String, Integer> lca_rank_counts = new TreeMap<String, Integer>();
2086             final SortedMap<String, Integer> lca_ancestor_species_counts = new TreeMap<String, Integer>();
2087             for( final String dc : more_than_once ) {
2088                 final List<PhylogenyNode> nodes = new ArrayList<PhylogenyNode>();
2089                 for( final PhylogenyNodeIterator it = local_phylogeny_l.iteratorExternalForward(); it.hasNext(); ) {
2090                     final PhylogenyNode n = it.next();
2091                     if ( n.getNodeData().getBinaryCharacters().getGainedCharacters().contains( dc ) ) {
2092                         nodes.add( n );
2093                     }
2094                 }
2095                 for( int i = 0; i < ( nodes.size() - 1 ); ++i ) {
2096                     for( int j = i + 1; j < nodes.size(); ++j ) {
2097                         final PhylogenyNode lca = PhylogenyMethods.calculateLCA( nodes.get( i ), nodes.get( j ) );
2098                         String rank = "unknown";
2099                         if ( lca.getNodeData().isHasTaxonomy()
2100                                 && !ForesterUtil.isEmpty( lca.getNodeData().getTaxonomy().getRank() ) ) {
2101                             rank = lca.getNodeData().getTaxonomy().getRank();
2102                         }
2103                         addToCountMap( lca_rank_counts, rank );
2104                         String lca_species;
2105                         if ( lca.getNodeData().isHasTaxonomy()
2106                                 && !ForesterUtil.isEmpty( lca.getNodeData().getTaxonomy().getScientificName() ) ) {
2107                             lca_species = lca.getNodeData().getTaxonomy().getScientificName();
2108                         }
2109                         else if ( lca.getNodeData().isHasTaxonomy()
2110                                 && !ForesterUtil.isEmpty( lca.getNodeData().getTaxonomy().getCommonName() ) ) {
2111                             lca_species = lca.getNodeData().getTaxonomy().getCommonName();
2112                         }
2113                         else {
2114                             lca_species = lca.getName();
2115                         }
2116                         addToCountMap( lca_ancestor_species_counts, lca_species );
2117                     }
2118                 }
2119             }
2120             final BufferedWriter out_for_rank_counts = new BufferedWriter( new FileWriter( outfilename_for_rank_counts ) );
2121             final BufferedWriter out_for_ancestor_species_counts = new BufferedWriter( new FileWriter( outfilename_for_ancestor_species_counts ) );
2122             ForesterUtil.map2writer( out_for_rank_counts, lca_rank_counts, "\t", ForesterUtil.LINE_SEPARATOR );
2123             ForesterUtil.map2writer( out_for_ancestor_species_counts,
2124                                      lca_ancestor_species_counts,
2125                                      "\t",
2126                                      ForesterUtil.LINE_SEPARATOR );
2127             out_for_rank_counts.close();
2128             out_for_ancestor_species_counts.close();
2129             if ( !ForesterUtil.isEmpty( outfilename_for_protein_stats )
2130                     && ( ( domain_length_stats_by_domain != null ) || ( protein_length_stats_by_dc != null ) || ( domain_number_stats_by_dc != null ) ) ) {
2131                 final BufferedWriter w = new BufferedWriter( new FileWriter( outfilename_for_protein_stats ) );
2132                 w.write( "Domain Lengths: " );
2133                 w.write( "\n" );
2134                 if ( domain_length_stats_by_domain != null ) {
2135                     for( final Entry<Integer, DescriptiveStatistics> entry : dc_reapp_counts_to_domain_lengths_stats
2136                             .entrySet() ) {
2137                         w.write( entry.getKey().toString() );
2138                         w.write( "\t" + entry.getValue().arithmeticMean() );
2139                         w.write( "\t" + entry.getValue().median() );
2140                         w.write( "\n" );
2141                     }
2142                 }
2143                 w.flush();
2144                 w.write( "\n" );
2145                 w.write( "\n" );
2146                 w.write( "Protein Lengths: " );
2147                 w.write( "\n" );
2148                 if ( protein_length_stats_by_dc != null ) {
2149                     for( final Entry<Integer, DescriptiveStatistics> entry : dc_reapp_counts_to_protein_length_stats
2150                             .entrySet() ) {
2151                         w.write( entry.getKey().toString() );
2152                         w.write( "\t" + entry.getValue().arithmeticMean() );
2153                         w.write( "\t" + entry.getValue().median() );
2154                         w.write( "\n" );
2155                     }
2156                 }
2157                 w.flush();
2158                 w.write( "\n" );
2159                 w.write( "\n" );
2160                 w.write( "Number of domains: " );
2161                 w.write( "\n" );
2162                 if ( domain_number_stats_by_dc != null ) {
2163                     for( final Entry<Integer, DescriptiveStatistics> entry : dc_reapp_counts_to_domain_number_stats
2164                             .entrySet() ) {
2165                         w.write( entry.getKey().toString() );
2166                         w.write( "\t" + entry.getValue().arithmeticMean() );
2167                         w.write( "\t" + entry.getValue().median() );
2168                         w.write( "\n" );
2169                     }
2170                 }
2171                 w.flush();
2172                 w.write( "\n" );
2173                 w.write( "\n" );
2174                 w.write( "Gained once, domain lengths:" );
2175                 w.write( "\n" );
2176                 w.write( "N: " + gained_once_domain_length_count );
2177                 w.write( "\n" );
2178                 w.write( "Avg: " + ( ( double ) gained_once_domain_length_sum / gained_once_domain_length_count ) );
2179                 w.write( "\n" );
2180                 w.write( "\n" );
2181                 w.write( "Gained multiple times, domain lengths:" );
2182                 w.write( "\n" );
2183                 w.write( "N: " + gained_multiple_times_domain_length_count );
2184                 w.write( "\n" );
2185                 w.write( "Avg: "
2186                         + ( ( double ) gained_multiple_times_domain_length_sum / gained_multiple_times_domain_length_count ) );
2187                 w.write( "\n" );
2188                 w.write( "\n" );
2189                 w.write( "\n" );
2190                 w.write( "\n" );
2191                 w.write( "Gained once, protein lengths:" );
2192                 w.write( "\n" );
2193                 w.write( gained_once_lengths_stats.toString() );
2194                 gained_once_lengths_stats = null;
2195                 w.write( "\n" );
2196                 w.write( "\n" );
2197                 w.write( "Gained once, domain counts:" );
2198                 w.write( "\n" );
2199                 w.write( gained_once_domain_count_stats.toString() );
2200                 gained_once_domain_count_stats = null;
2201                 w.write( "\n" );
2202                 w.write( "\n" );
2203                 w.write( "Gained multiple times, protein lengths:" );
2204                 w.write( "\n" );
2205                 w.write( gained_multiple_times_lengths_stats.toString() );
2206                 gained_multiple_times_lengths_stats = null;
2207                 w.write( "\n" );
2208                 w.write( "\n" );
2209                 w.write( "Gained multiple times, domain counts:" );
2210                 w.write( "\n" );
2211                 w.write( gained_multiple_times_domain_count_stats.toString() );
2212                 w.flush();
2213                 w.close();
2214             }
2215         }
2216         catch ( final IOException e ) {
2217             ForesterUtil.printWarningMessage( surfacing.PRG_NAME, "Failure to write: " + e );
2218         }
2219         ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote independent domain combination gains fitch counts to ["
2220                 + outfilename_for_counts + "]" );
2221         ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote independent domain combination gains fitch lists to ["
2222                 + outfilename_for_dc + "]" );
2223         ForesterUtil.programMessage( surfacing.PRG_NAME,
2224                                      "Wrote independent domain combination gains fitch lists to (for GO mapping) ["
2225                                              + outfilename_for_dc_for_go_mapping + "]" );
2226         ForesterUtil.programMessage( surfacing.PRG_NAME,
2227                                      "Wrote independent domain combination gains fitch lists to (for GO mapping, unique) ["
2228                                              + outfilename_for_dc_for_go_mapping_unique + "]" );
2229     }
2230
2231     private static SortedSet<String> collectAllDomainsChangedOnSubtree( final PhylogenyNode subtree_root,
2232                                                                         final boolean get_gains ) {
2233         final SortedSet<String> domains = new TreeSet<String>();
2234         for( final PhylogenyNode descendant : PhylogenyMethods.getAllDescendants( subtree_root ) ) {
2235             final BinaryCharacters chars = descendant.getNodeData().getBinaryCharacters();
2236             if ( get_gains ) {
2237                 domains.addAll( chars.getGainedCharacters() );
2238             }
2239             else {
2240                 domains.addAll( chars.getLostCharacters() );
2241             }
2242         }
2243         return domains;
2244     }
2245
2246     private static File createBaseDirForPerNodeDomainFiles( final String base_dir,
2247                                                             final boolean domain_combinations,
2248                                                             final CharacterStateMatrix.GainLossStates state,
2249                                                             final String outfile ) {
2250         File per_node_go_mapped_domain_gain_loss_files_base_dir = new File( new File( outfile ).getParent()
2251                 + ForesterUtil.FILE_SEPARATOR + base_dir );
2252         if ( !per_node_go_mapped_domain_gain_loss_files_base_dir.exists() ) {
2253             per_node_go_mapped_domain_gain_loss_files_base_dir.mkdir();
2254         }
2255         if ( domain_combinations ) {
2256             per_node_go_mapped_domain_gain_loss_files_base_dir = new File( per_node_go_mapped_domain_gain_loss_files_base_dir
2257                     + ForesterUtil.FILE_SEPARATOR + "DC" );
2258         }
2259         else {
2260             per_node_go_mapped_domain_gain_loss_files_base_dir = new File( per_node_go_mapped_domain_gain_loss_files_base_dir
2261                     + ForesterUtil.FILE_SEPARATOR + "DOMAINS" );
2262         }
2263         if ( !per_node_go_mapped_domain_gain_loss_files_base_dir.exists() ) {
2264             per_node_go_mapped_domain_gain_loss_files_base_dir.mkdir();
2265         }
2266         if ( state == GainLossStates.GAIN ) {
2267             per_node_go_mapped_domain_gain_loss_files_base_dir = new File( per_node_go_mapped_domain_gain_loss_files_base_dir
2268                     + ForesterUtil.FILE_SEPARATOR + "GAINS" );
2269         }
2270         else if ( state == GainLossStates.LOSS ) {
2271             per_node_go_mapped_domain_gain_loss_files_base_dir = new File( per_node_go_mapped_domain_gain_loss_files_base_dir
2272                     + ForesterUtil.FILE_SEPARATOR + "LOSSES" );
2273         }
2274         else {
2275             per_node_go_mapped_domain_gain_loss_files_base_dir = new File( per_node_go_mapped_domain_gain_loss_files_base_dir
2276                     + ForesterUtil.FILE_SEPARATOR + "PRESENT" );
2277         }
2278         if ( !per_node_go_mapped_domain_gain_loss_files_base_dir.exists() ) {
2279             per_node_go_mapped_domain_gain_loss_files_base_dir.mkdir();
2280         }
2281         return per_node_go_mapped_domain_gain_loss_files_base_dir;
2282     }
2283
2284     private static SortedSet<BinaryDomainCombination> createSetOfAllBinaryDomainCombinationsPerGenome( final GenomeWideCombinableDomains gwcd ) {
2285         final SortedMap<String, CombinableDomains> cds = gwcd.getAllCombinableDomainsIds();
2286         final SortedSet<BinaryDomainCombination> binary_combinations = new TreeSet<BinaryDomainCombination>();
2287         for( final String domain_id : cds.keySet() ) {
2288             final CombinableDomains cd = cds.get( domain_id );
2289             binary_combinations.addAll( cd.toBinaryDomainCombinations() );
2290         }
2291         return binary_combinations;
2292     }
2293
2294     private static List<String> splitDomainCombination( final String dc ) {
2295         final String[] s = dc.split( "=" );
2296         if ( s.length != 2 ) {
2297             ForesterUtil.printErrorMessage( surfacing.PRG_NAME, "Stringyfied domain combination has illegal format: "
2298                     + dc );
2299             System.exit( -1 );
2300         }
2301         final List<String> l = new ArrayList<String>( 2 );
2302         l.add( s[ 0 ] );
2303         l.add( s[ 1 ] );
2304         return l;
2305     }
2306
2307     private static void writeAllEncounteredPfamsToFile( final Map<String, List<GoId>> domain_id_to_go_ids_map,
2308                                                         final Map<GoId, GoTerm> go_id_to_term_map,
2309                                                         final String outfile_name,
2310                                                         final SortedSet<String> all_pfams_encountered ) {
2311         final File all_pfams_encountered_file = new File( outfile_name + surfacing.ALL_PFAMS_ENCOUNTERED_SUFFIX );
2312         final File all_pfams_encountered_with_go_annotation_file = new File( outfile_name
2313                 + surfacing.ALL_PFAMS_ENCOUNTERED_WITH_GO_ANNOTATION_SUFFIX );
2314         final File encountered_pfams_summary_file = new File( outfile_name + surfacing.ENCOUNTERED_PFAMS_SUMMARY_SUFFIX );
2315         int biological_process_counter = 0;
2316         int cellular_component_counter = 0;
2317         int molecular_function_counter = 0;
2318         int pfams_with_mappings_counter = 0;
2319         int pfams_without_mappings_counter = 0;
2320         int pfams_without_mappings_to_bp_or_mf_counter = 0;
2321         int pfams_with_mappings_to_bp_or_mf_counter = 0;
2322         try {
2323             final Writer all_pfams_encountered_writer = new BufferedWriter( new FileWriter( all_pfams_encountered_file ) );
2324             final Writer all_pfams_encountered_with_go_annotation_writer = new BufferedWriter( new FileWriter( all_pfams_encountered_with_go_annotation_file ) );
2325             final Writer summary_writer = new BufferedWriter( new FileWriter( encountered_pfams_summary_file ) );
2326             summary_writer.write( "# Pfam to GO mapping summary" );
2327             summary_writer.write( ForesterUtil.LINE_SEPARATOR );
2328             summary_writer.write( "# Actual summary is at the end of this file." );
2329             summary_writer.write( ForesterUtil.LINE_SEPARATOR );
2330             summary_writer.write( "# Encountered Pfams without a GO mapping:" );
2331             summary_writer.write( ForesterUtil.LINE_SEPARATOR );
2332             for( final String pfam : all_pfams_encountered ) {
2333                 all_pfams_encountered_writer.write( pfam );
2334                 all_pfams_encountered_writer.write( ForesterUtil.LINE_SEPARATOR );
2335                 final String domain_id = new String( pfam );
2336                 if ( domain_id_to_go_ids_map.containsKey( domain_id ) ) {
2337                     ++pfams_with_mappings_counter;
2338                     all_pfams_encountered_with_go_annotation_writer.write( pfam );
2339                     all_pfams_encountered_with_go_annotation_writer.write( ForesterUtil.LINE_SEPARATOR );
2340                     final List<GoId> go_ids = domain_id_to_go_ids_map.get( domain_id );
2341                     boolean maps_to_bp = false;
2342                     boolean maps_to_cc = false;
2343                     boolean maps_to_mf = false;
2344                     for( final GoId go_id : go_ids ) {
2345                         final GoTerm go_term = go_id_to_term_map.get( go_id );
2346                         if ( go_term.getGoNameSpace().isBiologicalProcess() ) {
2347                             maps_to_bp = true;
2348                         }
2349                         else if ( go_term.getGoNameSpace().isCellularComponent() ) {
2350                             maps_to_cc = true;
2351                         }
2352                         else if ( go_term.getGoNameSpace().isMolecularFunction() ) {
2353                             maps_to_mf = true;
2354                         }
2355                     }
2356                     if ( maps_to_bp ) {
2357                         ++biological_process_counter;
2358                     }
2359                     if ( maps_to_cc ) {
2360                         ++cellular_component_counter;
2361                     }
2362                     if ( maps_to_mf ) {
2363                         ++molecular_function_counter;
2364                     }
2365                     if ( maps_to_bp || maps_to_mf ) {
2366                         ++pfams_with_mappings_to_bp_or_mf_counter;
2367                     }
2368                     else {
2369                         ++pfams_without_mappings_to_bp_or_mf_counter;
2370                     }
2371                 }
2372                 else {
2373                     ++pfams_without_mappings_to_bp_or_mf_counter;
2374                     ++pfams_without_mappings_counter;
2375                     summary_writer.write( pfam );
2376                     summary_writer.write( ForesterUtil.LINE_SEPARATOR );
2377                 }
2378             }
2379             all_pfams_encountered_writer.close();
2380             all_pfams_encountered_with_go_annotation_writer.close();
2381             ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote all [" + all_pfams_encountered.size()
2382                     + "] encountered Pfams to: \"" + all_pfams_encountered_file + "\"" );
2383             ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote all [" + pfams_with_mappings_counter
2384                     + "] encountered Pfams with GO mappings to: \"" + all_pfams_encountered_with_go_annotation_file
2385                     + "\"" );
2386             ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote summary (including all ["
2387                     + pfams_without_mappings_counter + "] encountered Pfams without GO mappings) to: \""
2388                     + encountered_pfams_summary_file + "\"" );
2389             ForesterUtil.programMessage( surfacing.PRG_NAME, "Sum of Pfams encountered                : "
2390                     + all_pfams_encountered.size() );
2391             ForesterUtil.programMessage( surfacing.PRG_NAME, "Pfams without a mapping                 : "
2392                     + pfams_without_mappings_counter + " ["
2393                     + ( ( 100 * pfams_without_mappings_counter ) / all_pfams_encountered.size() ) + "%]" );
2394             ForesterUtil.programMessage( surfacing.PRG_NAME, "Pfams without mapping to proc. or func. : "
2395                     + pfams_without_mappings_to_bp_or_mf_counter + " ["
2396                     + ( ( 100 * pfams_without_mappings_to_bp_or_mf_counter ) / all_pfams_encountered.size() ) + "%]" );
2397             ForesterUtil.programMessage( surfacing.PRG_NAME, "Pfams with a mapping                    : "
2398                     + pfams_with_mappings_counter + " ["
2399                     + ( ( 100 * pfams_with_mappings_counter ) / all_pfams_encountered.size() ) + "%]" );
2400             ForesterUtil.programMessage( surfacing.PRG_NAME, "Pfams with a mapping to proc. or func.  : "
2401                     + pfams_with_mappings_to_bp_or_mf_counter + " ["
2402                     + ( ( 100 * pfams_with_mappings_to_bp_or_mf_counter ) / all_pfams_encountered.size() ) + "%]" );
2403             ForesterUtil.programMessage( surfacing.PRG_NAME, "Pfams with mapping to biological process: "
2404                     + biological_process_counter + " ["
2405                     + ( ( 100 * biological_process_counter ) / all_pfams_encountered.size() ) + "%]" );
2406             ForesterUtil.programMessage( surfacing.PRG_NAME, "Pfams with mapping to molecular function: "
2407                     + molecular_function_counter + " ["
2408                     + ( ( 100 * molecular_function_counter ) / all_pfams_encountered.size() ) + "%]" );
2409             ForesterUtil.programMessage( surfacing.PRG_NAME, "Pfams with mapping to cellular component: "
2410                     + cellular_component_counter + " ["
2411                     + ( ( 100 * cellular_component_counter ) / all_pfams_encountered.size() ) + "%]" );
2412             summary_writer.write( ForesterUtil.LINE_SEPARATOR );
2413             summary_writer.write( "# Sum of Pfams encountered                : " + all_pfams_encountered.size() );
2414             summary_writer.write( ForesterUtil.LINE_SEPARATOR );
2415             summary_writer.write( "# Pfams without a mapping                 : " + pfams_without_mappings_counter
2416                     + " [" + ( ( 100 * pfams_without_mappings_counter ) / all_pfams_encountered.size() ) + "%]" );
2417             summary_writer.write( ForesterUtil.LINE_SEPARATOR );
2418             summary_writer.write( "# Pfams without mapping to proc. or func. : "
2419                     + pfams_without_mappings_to_bp_or_mf_counter + " ["
2420                     + ( ( 100 * pfams_without_mappings_to_bp_or_mf_counter ) / all_pfams_encountered.size() ) + "%]" );
2421             summary_writer.write( ForesterUtil.LINE_SEPARATOR );
2422             summary_writer.write( "# Pfams with a mapping                    : " + pfams_with_mappings_counter + " ["
2423                     + ( ( 100 * pfams_with_mappings_counter ) / all_pfams_encountered.size() ) + "%]" );
2424             summary_writer.write( ForesterUtil.LINE_SEPARATOR );
2425             summary_writer.write( "# Pfams with a mapping to proc. or func.  : "
2426                     + pfams_with_mappings_to_bp_or_mf_counter + " ["
2427                     + ( ( 100 * pfams_with_mappings_to_bp_or_mf_counter ) / all_pfams_encountered.size() ) + "%]" );
2428             summary_writer.write( ForesterUtil.LINE_SEPARATOR );
2429             summary_writer.write( "# Pfams with mapping to biological process: " + biological_process_counter + " ["
2430                     + ( ( 100 * biological_process_counter ) / all_pfams_encountered.size() ) + "%]" );
2431             summary_writer.write( ForesterUtil.LINE_SEPARATOR );
2432             summary_writer.write( "# Pfams with mapping to molecular function: " + molecular_function_counter + " ["
2433                     + ( ( 100 * molecular_function_counter ) / all_pfams_encountered.size() ) + "%]" );
2434             summary_writer.write( ForesterUtil.LINE_SEPARATOR );
2435             summary_writer.write( "# Pfams with mapping to cellular component: " + cellular_component_counter + " ["
2436                     + ( ( 100 * cellular_component_counter ) / all_pfams_encountered.size() ) + "%]" );
2437             summary_writer.write( ForesterUtil.LINE_SEPARATOR );
2438             summary_writer.close();
2439         }
2440         catch ( final IOException e ) {
2441             ForesterUtil.printWarningMessage( surfacing.PRG_NAME, "Failure to write: " + e );
2442         }
2443     }
2444
2445     private static void writeDomainData( final Map<String, List<GoId>> domain_id_to_go_ids_map,
2446                                          final Map<GoId, GoTerm> go_id_to_term_map,
2447                                          final GoNameSpace go_namespace_limit,
2448                                          final Writer out,
2449                                          final String domain_0,
2450                                          final String domain_1,
2451                                          final String prefix_for_html,
2452                                          final String character_separator_for_non_html_output,
2453                                          final Map<String, Set<String>>[] domain_id_to_secondary_features_maps,
2454                                          final Set<GoId> all_go_ids ) throws IOException {
2455         boolean any_go_annotation_present = false;
2456         boolean first_has_no_go = false;
2457         int domain_count = 2; // To distinguish between domains and binary domain combinations.
2458         if ( ForesterUtil.isEmpty( domain_1 ) ) {
2459             domain_count = 1;
2460         }
2461         // The following has a difficult to understand logic.  
2462         for( int d = 0; d < domain_count; ++d ) {
2463             List<GoId> go_ids = null;
2464             boolean go_annotation_present = false;
2465             if ( d == 0 ) {
2466                 if ( domain_id_to_go_ids_map.containsKey( domain_0 ) ) {
2467                     go_annotation_present = true;
2468                     any_go_annotation_present = true;
2469                     go_ids = domain_id_to_go_ids_map.get( domain_0 );
2470                 }
2471                 else {
2472                     first_has_no_go = true;
2473                 }
2474             }
2475             else {
2476                 if ( domain_id_to_go_ids_map.containsKey( domain_1 ) ) {
2477                     go_annotation_present = true;
2478                     any_go_annotation_present = true;
2479                     go_ids = domain_id_to_go_ids_map.get( domain_1 );
2480                 }
2481             }
2482             if ( go_annotation_present ) {
2483                 boolean first = ( ( d == 0 ) || ( ( d == 1 ) && first_has_no_go ) );
2484                 for( final GoId go_id : go_ids ) {
2485                     out.write( "<tr>" );
2486                     if ( first ) {
2487                         first = false;
2488                         writeDomainIdsToHtml( out,
2489                                               domain_0,
2490                                               domain_1,
2491                                               prefix_for_html,
2492                                               domain_id_to_secondary_features_maps );
2493                     }
2494                     else {
2495                         out.write( "<td></td>" );
2496                     }
2497                     if ( !go_id_to_term_map.containsKey( go_id ) ) {
2498                         throw new IllegalArgumentException( "GO-id [" + go_id + "] not found in GO-id to GO-term map" );
2499                     }
2500                     final GoTerm go_term = go_id_to_term_map.get( go_id );
2501                     if ( ( go_namespace_limit == null ) || go_namespace_limit.equals( go_term.getGoNameSpace() ) ) {
2502                         // final String top = GoUtils.getPenultimateGoTerm( go_term, go_id_to_term_map ).getName();
2503                         final String go_id_str = go_id.getId();
2504                         out.write( "<td>" );
2505                         out.write( "<a href=\"" + SurfacingConstants.AMIGO_LINK + go_id_str
2506                                 + "\" target=\"amigo_window\">" + go_id_str + "</a>" );
2507                         out.write( "</td><td>" );
2508                         out.write( go_term.getName() );
2509                         if ( domain_count == 2 ) {
2510                             out.write( " (" + d + ")" );
2511                         }
2512                         out.write( "</td><td>" );
2513                         // out.write( top );
2514                         // out.write( "</td><td>" );
2515                         out.write( "[" );
2516                         out.write( go_term.getGoNameSpace().toShortString() );
2517                         out.write( "]" );
2518                         out.write( "</td>" );
2519                         if ( all_go_ids != null ) {
2520                             all_go_ids.add( go_id );
2521                         }
2522                     }
2523                     else {
2524                         out.write( "<td>" );
2525                         out.write( "</td><td>" );
2526                         out.write( "</td><td>" );
2527                         out.write( "</td><td>" );
2528                         out.write( "</td>" );
2529                     }
2530                     out.write( "</tr>" );
2531                     out.write( SurfacingConstants.NL );
2532                 }
2533             }
2534         } //  for( int d = 0; d < domain_count; ++d ) 
2535         if ( !any_go_annotation_present ) {
2536             out.write( "<tr>" );
2537             writeDomainIdsToHtml( out, domain_0, domain_1, prefix_for_html, domain_id_to_secondary_features_maps );
2538             out.write( "<td>" );
2539             out.write( "</td><td>" );
2540             out.write( "</td><td>" );
2541             out.write( "</td><td>" );
2542             out.write( "</td>" );
2543             out.write( "</tr>" );
2544             out.write( SurfacingConstants.NL );
2545         }
2546     }
2547
2548     private static void writeDomainIdsToHtml( final Writer out,
2549                                               final String domain_0,
2550                                               final String domain_1,
2551                                               final String prefix_for_detailed_html,
2552                                               final Map<String, Set<String>>[] domain_id_to_secondary_features_maps )
2553             throws IOException {
2554         out.write( "<td>" );
2555         if ( !ForesterUtil.isEmpty( prefix_for_detailed_html ) ) {
2556             out.write( prefix_for_detailed_html );
2557             out.write( " " );
2558         }
2559         out.write( "<a href=\"" + SurfacingConstants.PFAM_FAMILY_ID_LINK + domain_0 + "\">" + domain_0 + "</a>" );
2560         out.write( "</td>" );
2561     }
2562
2563     private static void writeDomainsToIndividualFilePerTreeNode( final Writer individual_files_writer,
2564                                                                  final String domain_0,
2565                                                                  final String domain_1 ) throws IOException {
2566         individual_files_writer.write( domain_0 );
2567         individual_files_writer.write( ForesterUtil.LINE_SEPARATOR );
2568         if ( !ForesterUtil.isEmpty( domain_1 ) ) {
2569             individual_files_writer.write( domain_1 );
2570             individual_files_writer.write( ForesterUtil.LINE_SEPARATOR );
2571         }
2572     }
2573
2574     private static void writePfamsToFile( final String outfile_name, final SortedSet<String> pfams ) {
2575         try {
2576             final Writer writer = new BufferedWriter( new FileWriter( new File( outfile_name ) ) );
2577             for( final String pfam : pfams ) {
2578                 writer.write( pfam );
2579                 writer.write( ForesterUtil.LINE_SEPARATOR );
2580             }
2581             writer.close();
2582             ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote " + pfams.size() + " pfams to [" + outfile_name
2583                     + "]" );
2584         }
2585         catch ( final IOException e ) {
2586             ForesterUtil.printWarningMessage( surfacing.PRG_NAME, "Failure to write: " + e );
2587         }
2588     }
2589
2590     private static void writeToNexus( final String outfile_name,
2591                                       final CharacterStateMatrix<BinaryStates> matrix,
2592                                       final Phylogeny phylogeny ) {
2593         if ( !( matrix instanceof BasicCharacterStateMatrix ) ) {
2594             throw new IllegalArgumentException( "can only write matrices of type [" + BasicCharacterStateMatrix.class
2595                     + "] to nexus" );
2596         }
2597         final BasicCharacterStateMatrix<BinaryStates> my_matrix = ( org.forester.evoinference.matrix.character.BasicCharacterStateMatrix<BinaryStates> ) matrix;
2598         final List<Phylogeny> phylogenies = new ArrayList<Phylogeny>( 1 );
2599         phylogenies.add( phylogeny );
2600         try {
2601             final BufferedWriter w = new BufferedWriter( new FileWriter( outfile_name ) );
2602             w.write( NexusConstants.NEXUS );
2603             w.write( ForesterUtil.LINE_SEPARATOR );
2604             my_matrix.writeNexusTaxaBlock( w );
2605             my_matrix.writeNexusBinaryChractersBlock( w );
2606             PhylogenyWriter.writeNexusTreesBlock( w, phylogenies, NH_CONVERSION_SUPPORT_VALUE_STYLE.NONE );
2607             w.flush();
2608             w.close();
2609             ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote Nexus file: \"" + outfile_name + "\"" );
2610         }
2611         catch ( final IOException e ) {
2612             ForesterUtil.fatalError( surfacing.PRG_NAME, e.getMessage() );
2613         }
2614     }
2615
2616     private static void writeToNexus( final String outfile_name,
2617                                       final DomainParsimonyCalculator domain_parsimony,
2618                                       final Phylogeny phylogeny ) {
2619         writeToNexus( outfile_name + surfacing.NEXUS_EXTERNAL_DOMAINS,
2620                       domain_parsimony.createMatrixOfDomainPresenceOrAbsence(),
2621                       phylogeny );
2622         writeToNexus( outfile_name + surfacing.NEXUS_EXTERNAL_DOMAIN_COMBINATIONS,
2623                       domain_parsimony.createMatrixOfBinaryDomainCombinationPresenceOrAbsence(),
2624                       phylogeny );
2625     }
2626
2627     final static class DomainComparator implements Comparator<Domain> {
2628
2629         final private boolean _ascending;
2630
2631         public DomainComparator( final boolean ascending ) {
2632             _ascending = ascending;
2633         }
2634
2635         @Override
2636         public final int compare( final Domain d0, final Domain d1 ) {
2637             if ( d0.getFrom() < d1.getFrom() ) {
2638                 return _ascending ? -1 : 1;
2639             }
2640             else if ( d0.getFrom() > d1.getFrom() ) {
2641                 return _ascending ? 1 : -1;
2642             }
2643             return 0;
2644         }
2645     }
2646 }