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