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