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