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