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