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