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