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