eef4ff9102c5565695dd0cebf52914bf4683ef91
[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                 if ( n.getParent() != null ) {
898                     names.append( " " );
899                     names.append( n.getParent().getName() );
900                 }
901                 ++c;
902             }
903         }
904         return c;
905     }
906
907     /**
908      * Returns true is Domain domain falls in an uninterrupted stretch of
909      * covered positions.
910      * 
911      * @param domain
912      * @param covered_positions
913      * @return
914      */
915     public static boolean isEngulfed( final Domain domain, final List<Boolean> covered_positions ) {
916         for( int i = domain.getFrom(); i <= domain.getTo(); ++i ) {
917             if ( ( i >= covered_positions.size() ) || ( covered_positions.get( i ) != true ) ) {
918                 return false;
919             }
920         }
921         return true;
922     }
923
924     public static void preparePhylogeny( final Phylogeny p,
925                                          final DomainParsimonyCalculator domain_parsimony,
926                                          final String date_time,
927                                          final String method,
928                                          final String name,
929                                          final String parameters_str ) {
930         domain_parsimony.decoratePhylogenyWithDomains( p );
931         final StringBuilder desc = new StringBuilder();
932         desc.append( "[Method: " + method + "] [Date: " + date_time + "] " );
933         desc.append( "[Cost: " + domain_parsimony.getCost() + "] " );
934         desc.append( "[Gains: " + domain_parsimony.getTotalGains() + "] " );
935         desc.append( "[Losses: " + domain_parsimony.getTotalLosses() + "] " );
936         desc.append( "[Unchanged: " + domain_parsimony.getTotalUnchanged() + "] " );
937         desc.append( "[Parameters: " + parameters_str + "]" );
938         p.setName( name );
939         p.setDescription( desc.toString() );
940         p.setConfidence( new Confidence( domain_parsimony.getCost(), "parsimony" ) );
941         p.setRerootable( false );
942         p.setRooted( true );
943     }
944
945     /*
946      * species | protein id | n-terminal domain | c-terminal domain | n-terminal domain per domain E-value | c-terminal domain per domain E-value
947      * 
948      * 
949      */
950     static public StringBuffer proteinToDomainCombinations( final Protein protein,
951                                                             final String protein_id,
952                                                             final String separator ) {
953         final StringBuffer sb = new StringBuffer();
954         if ( protein.getSpecies() == null ) {
955             throw new IllegalArgumentException( "species must not be null" );
956         }
957         if ( ForesterUtil.isEmpty( protein.getSpecies().getSpeciesId() ) ) {
958             throw new IllegalArgumentException( "species id must not be empty" );
959         }
960         final List<Domain> domains = protein.getProteinDomains();
961         if ( domains.size() > 1 ) {
962             final Map<String, Integer> counts = new HashMap<String, Integer>();
963             for( final Domain domain : domains ) {
964                 final String id = domain.getDomainId().getId();
965                 if ( counts.containsKey( id ) ) {
966                     counts.put( id, counts.get( id ) + 1 );
967                 }
968                 else {
969                     counts.put( id, 1 );
970                 }
971             }
972             final Set<String> dcs = new HashSet<String>();
973             for( int i = 1; i < domains.size(); ++i ) {
974                 for( int j = 0; j < i; ++j ) {
975                     Domain domain_n = domains.get( i );
976                     Domain domain_c = domains.get( j );
977                     if ( domain_n.getFrom() > domain_c.getFrom() ) {
978                         domain_n = domains.get( j );
979                         domain_c = domains.get( i );
980                     }
981                     final String dc = domain_n.getDomainId().getId() + domain_c.getDomainId().getId();
982                     if ( !dcs.contains( dc ) ) {
983                         dcs.add( dc );
984                         sb.append( protein.getSpecies() );
985                         sb.append( separator );
986                         sb.append( protein_id );
987                         sb.append( separator );
988                         sb.append( domain_n.getDomainId().getId() );
989                         sb.append( separator );
990                         sb.append( domain_c.getDomainId().getId() );
991                         sb.append( separator );
992                         sb.append( domain_n.getPerDomainEvalue() );
993                         sb.append( separator );
994                         sb.append( domain_c.getPerDomainEvalue() );
995                         sb.append( separator );
996                         sb.append( counts.get( domain_n.getDomainId().getId() ) );
997                         sb.append( separator );
998                         sb.append( counts.get( domain_c.getDomainId().getId() ) );
999                         sb.append( ForesterUtil.LINE_SEPARATOR );
1000                     }
1001                 }
1002             }
1003         }
1004         else if ( domains.size() == 1 ) {
1005             sb.append( protein.getSpecies() );
1006             sb.append( separator );
1007             sb.append( protein_id );
1008             sb.append( separator );
1009             sb.append( domains.get( 0 ).getDomainId().getId() );
1010             sb.append( separator );
1011             sb.append( separator );
1012             sb.append( domains.get( 0 ).getPerDomainEvalue() );
1013             sb.append( separator );
1014             sb.append( separator );
1015             sb.append( 1 );
1016             sb.append( separator );
1017             sb.append( ForesterUtil.LINE_SEPARATOR );
1018         }
1019         else {
1020             sb.append( protein.getSpecies() );
1021             sb.append( separator );
1022             sb.append( protein_id );
1023             sb.append( separator );
1024             sb.append( separator );
1025             sb.append( separator );
1026             sb.append( separator );
1027             sb.append( separator );
1028             sb.append( separator );
1029             sb.append( ForesterUtil.LINE_SEPARATOR );
1030         }
1031         return sb;
1032     }
1033
1034     /**
1035      * 
1036      * Example regarding engulfment: ------------0.1 ----------0.2 --0.3 =>
1037      * domain with 0.3 is ignored
1038      * 
1039      * -----------0.1 ----------0.2 --0.3 => domain with 0.3 is ignored
1040      * 
1041      * 
1042      * ------------0.1 ----------0.3 --0.2 => domains with 0.3 and 0.2 are _not_
1043      * ignored
1044      * 
1045      * @param max_allowed_overlap
1046      *            maximal allowed overlap (inclusive) to be still considered not
1047      *            overlapping (zero or negative value to allow any overlap)
1048      * @param remove_engulfed_domains
1049      *            to remove domains which are completely engulfed by coverage of
1050      *            domains with better support
1051      * @param protein
1052      * @return
1053      */
1054     public static Protein removeOverlappingDomains( final int max_allowed_overlap,
1055                                                     final boolean remove_engulfed_domains,
1056                                                     final Protein protein ) {
1057         final Protein pruned_protein = new BasicProtein( protein.getProteinId().getId(), protein.getSpecies()
1058                 .getSpeciesId() );
1059         final List<Domain> sorted = SurfacingUtil.sortDomainsWithAscendingConfidenceValues( protein );
1060         final List<Boolean> covered_positions = new ArrayList<Boolean>();
1061         for( final Domain domain : sorted ) {
1062             if ( ( ( max_allowed_overlap < 0 ) || ( SurfacingUtil.calculateOverlap( domain, covered_positions ) <= max_allowed_overlap ) )
1063                     && ( !remove_engulfed_domains || !isEngulfed( domain, covered_positions ) ) ) {
1064                 final int covered_positions_size = covered_positions.size();
1065                 for( int i = covered_positions_size; i < domain.getFrom(); ++i ) {
1066                     covered_positions.add( false );
1067                 }
1068                 final int new_covered_positions_size = covered_positions.size();
1069                 for( int i = domain.getFrom(); i <= domain.getTo(); ++i ) {
1070                     if ( i < new_covered_positions_size ) {
1071                         covered_positions.set( i, true );
1072                     }
1073                     else {
1074                         covered_positions.add( true );
1075                     }
1076                 }
1077                 pruned_protein.addProteinDomain( domain );
1078             }
1079         }
1080         return pruned_protein;
1081     }
1082
1083     public static List<Domain> sortDomainsWithAscendingConfidenceValues( final Protein protein ) {
1084         final List<Domain> domains = new ArrayList<Domain>();
1085         for( final Domain d : protein.getProteinDomains() ) {
1086             domains.add( d );
1087         }
1088         Collections.sort( domains, SurfacingUtil.ASCENDING_CONFIDENCE_VALUE_ORDER );
1089         return domains;
1090     }
1091
1092     private static List<String> splitDomainCombination( final String dc ) {
1093         final String[] s = dc.split( "=" );
1094         if ( s.length != 2 ) {
1095             ForesterUtil.printErrorMessage( surfacing.PRG_NAME, "Stringyfied domain combination has illegal format: "
1096                     + dc );
1097             System.exit( -1 );
1098         }
1099         final List<String> l = new ArrayList<String>( 2 );
1100         l.add( s[ 0 ] );
1101         l.add( s[ 1 ] );
1102         return l;
1103     }
1104
1105     public static void writeAllDomainsChangedOnAllSubtrees( final Phylogeny p,
1106                                                             final boolean get_gains,
1107                                                             final String outdir,
1108                                                             final String suffix_for_filename ) throws IOException {
1109         CharacterStateMatrix.GainLossStates state = CharacterStateMatrix.GainLossStates.GAIN;
1110         if ( !get_gains ) {
1111             state = CharacterStateMatrix.GainLossStates.LOSS;
1112         }
1113         final File base_dir = createBaseDirForPerNodeDomainFiles( surfacing.BASE_DIRECTORY_PER_SUBTREE_DOMAIN_GAIN_LOSS_FILES,
1114                                                                   false,
1115                                                                   state,
1116                                                                   outdir );
1117         for( final PhylogenyNodeIterator it = p.iteratorPostorder(); it.hasNext(); ) {
1118             final PhylogenyNode node = it.next();
1119             if ( !node.isExternal() ) {
1120                 final SortedSet<String> domains = collectAllDomainsChangedOnSubtree( node, get_gains );
1121                 if ( domains.size() > 0 ) {
1122                     final Writer writer = ForesterUtil.createBufferedWriter( base_dir + ForesterUtil.FILE_SEPARATOR
1123                             + node.getName() + suffix_for_filename );
1124                     for( final String domain : domains ) {
1125                         writer.write( domain );
1126                         writer.write( ForesterUtil.LINE_SEPARATOR );
1127                     }
1128                     writer.close();
1129                 }
1130             }
1131         }
1132     }
1133
1134     private static void writeAllEncounteredPfamsToFile( final Map<DomainId, List<GoId>> domain_id_to_go_ids_map,
1135                                                         final Map<GoId, GoTerm> go_id_to_term_map,
1136                                                         final String outfile_name,
1137                                                         final SortedSet<String> all_pfams_encountered ) {
1138         final File all_pfams_encountered_file = new File( outfile_name + surfacing.ALL_PFAMS_ENCOUNTERED_SUFFIX );
1139         final File all_pfams_encountered_with_go_annotation_file = new File( outfile_name
1140                 + surfacing.ALL_PFAMS_ENCOUNTERED_WITH_GO_ANNOTATION_SUFFIX );
1141         final File encountered_pfams_summary_file = new File( outfile_name + surfacing.ENCOUNTERED_PFAMS_SUMMARY_SUFFIX );
1142         int biological_process_counter = 0;
1143         int cellular_component_counter = 0;
1144         int molecular_function_counter = 0;
1145         int pfams_with_mappings_counter = 0;
1146         int pfams_without_mappings_counter = 0;
1147         int pfams_without_mappings_to_bp_or_mf_counter = 0;
1148         int pfams_with_mappings_to_bp_or_mf_counter = 0;
1149         try {
1150             final Writer all_pfams_encountered_writer = new BufferedWriter( new FileWriter( all_pfams_encountered_file ) );
1151             final Writer all_pfams_encountered_with_go_annotation_writer = new BufferedWriter( new FileWriter( all_pfams_encountered_with_go_annotation_file ) );
1152             final Writer summary_writer = new BufferedWriter( new FileWriter( encountered_pfams_summary_file ) );
1153             summary_writer.write( "# Pfam to GO mapping summary" );
1154             summary_writer.write( ForesterUtil.LINE_SEPARATOR );
1155             summary_writer.write( "# Actual summary is at the end of this file." );
1156             summary_writer.write( ForesterUtil.LINE_SEPARATOR );
1157             summary_writer.write( "# Encountered Pfams without a GO mapping:" );
1158             summary_writer.write( ForesterUtil.LINE_SEPARATOR );
1159             for( final String pfam : all_pfams_encountered ) {
1160                 all_pfams_encountered_writer.write( pfam );
1161                 all_pfams_encountered_writer.write( ForesterUtil.LINE_SEPARATOR );
1162                 final DomainId domain_id = new DomainId( pfam );
1163                 if ( domain_id_to_go_ids_map.containsKey( domain_id ) ) {
1164                     ++pfams_with_mappings_counter;
1165                     all_pfams_encountered_with_go_annotation_writer.write( pfam );
1166                     all_pfams_encountered_with_go_annotation_writer.write( ForesterUtil.LINE_SEPARATOR );
1167                     final List<GoId> go_ids = domain_id_to_go_ids_map.get( domain_id );
1168                     boolean maps_to_bp = false;
1169                     boolean maps_to_cc = false;
1170                     boolean maps_to_mf = false;
1171                     for( final GoId go_id : go_ids ) {
1172                         final GoTerm go_term = go_id_to_term_map.get( go_id );
1173                         if ( go_term.getGoNameSpace().isBiologicalProcess() ) {
1174                             maps_to_bp = true;
1175                         }
1176                         else if ( go_term.getGoNameSpace().isCellularComponent() ) {
1177                             maps_to_cc = true;
1178                         }
1179                         else if ( go_term.getGoNameSpace().isMolecularFunction() ) {
1180                             maps_to_mf = true;
1181                         }
1182                     }
1183                     if ( maps_to_bp ) {
1184                         ++biological_process_counter;
1185                     }
1186                     if ( maps_to_cc ) {
1187                         ++cellular_component_counter;
1188                     }
1189                     if ( maps_to_mf ) {
1190                         ++molecular_function_counter;
1191                     }
1192                     if ( maps_to_bp || maps_to_mf ) {
1193                         ++pfams_with_mappings_to_bp_or_mf_counter;
1194                     }
1195                     else {
1196                         ++pfams_without_mappings_to_bp_or_mf_counter;
1197                     }
1198                 }
1199                 else {
1200                     ++pfams_without_mappings_to_bp_or_mf_counter;
1201                     ++pfams_without_mappings_counter;
1202                     summary_writer.write( pfam );
1203                     summary_writer.write( ForesterUtil.LINE_SEPARATOR );
1204                 }
1205             }
1206             all_pfams_encountered_writer.close();
1207             all_pfams_encountered_with_go_annotation_writer.close();
1208             ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote all [" + all_pfams_encountered.size()
1209                     + "] encountered Pfams to: \"" + all_pfams_encountered_file + "\"" );
1210             ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote all [" + pfams_with_mappings_counter
1211                     + "] encountered Pfams with GO mappings to: \"" + all_pfams_encountered_with_go_annotation_file
1212                     + "\"" );
1213             ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote summary (including all ["
1214                     + pfams_without_mappings_counter + "] encountered Pfams without GO mappings) to: \""
1215                     + encountered_pfams_summary_file + "\"" );
1216             ForesterUtil.programMessage( surfacing.PRG_NAME, "Sum of Pfams encountered                : "
1217                     + all_pfams_encountered.size() );
1218             ForesterUtil.programMessage( surfacing.PRG_NAME, "Pfams without a mapping                 : "
1219                     + pfams_without_mappings_counter + " ["
1220                     + ( 100 * pfams_without_mappings_counter / all_pfams_encountered.size() ) + "%]" );
1221             ForesterUtil.programMessage( surfacing.PRG_NAME, "Pfams without mapping to proc. or func. : "
1222                     + pfams_without_mappings_to_bp_or_mf_counter + " ["
1223                     + ( 100 * pfams_without_mappings_to_bp_or_mf_counter / all_pfams_encountered.size() ) + "%]" );
1224             ForesterUtil.programMessage( surfacing.PRG_NAME,
1225                                          "Pfams with a mapping                    : " + pfams_with_mappings_counter
1226                                                  + " ["
1227                                                  + ( 100 * pfams_with_mappings_counter / all_pfams_encountered.size() )
1228                                                  + "%]" );
1229             ForesterUtil.programMessage( surfacing.PRG_NAME, "Pfams with a mapping to proc. or func.  : "
1230                     + pfams_with_mappings_to_bp_or_mf_counter + " ["
1231                     + ( 100 * pfams_with_mappings_to_bp_or_mf_counter / all_pfams_encountered.size() ) + "%]" );
1232             ForesterUtil.programMessage( surfacing.PRG_NAME,
1233                                          "Pfams with mapping to biological process: " + biological_process_counter
1234                                                  + " ["
1235                                                  + ( 100 * biological_process_counter / all_pfams_encountered.size() )
1236                                                  + "%]" );
1237             ForesterUtil.programMessage( surfacing.PRG_NAME,
1238                                          "Pfams with mapping to molecular function: " + molecular_function_counter
1239                                                  + " ["
1240                                                  + ( 100 * molecular_function_counter / all_pfams_encountered.size() )
1241                                                  + "%]" );
1242             ForesterUtil.programMessage( surfacing.PRG_NAME,
1243                                          "Pfams with mapping to cellular component: " + cellular_component_counter
1244                                                  + " ["
1245                                                  + ( 100 * cellular_component_counter / all_pfams_encountered.size() )
1246                                                  + "%]" );
1247             summary_writer.write( ForesterUtil.LINE_SEPARATOR );
1248             summary_writer.write( "# Sum of Pfams encountered                : " + all_pfams_encountered.size() );
1249             summary_writer.write( ForesterUtil.LINE_SEPARATOR );
1250             summary_writer.write( "# Pfams without a mapping                 : " + pfams_without_mappings_counter
1251                     + " [" + ( 100 * pfams_without_mappings_counter / all_pfams_encountered.size() ) + "%]" );
1252             summary_writer.write( ForesterUtil.LINE_SEPARATOR );
1253             summary_writer.write( "# Pfams without mapping to proc. or func. : "
1254                     + pfams_without_mappings_to_bp_or_mf_counter + " ["
1255                     + ( 100 * pfams_without_mappings_to_bp_or_mf_counter / all_pfams_encountered.size() ) + "%]" );
1256             summary_writer.write( ForesterUtil.LINE_SEPARATOR );
1257             summary_writer.write( "# Pfams with a mapping                    : " + pfams_with_mappings_counter + " ["
1258                     + ( 100 * pfams_with_mappings_counter / all_pfams_encountered.size() ) + "%]" );
1259             summary_writer.write( ForesterUtil.LINE_SEPARATOR );
1260             summary_writer.write( "# Pfams with a mapping to proc. or func.  : "
1261                     + pfams_with_mappings_to_bp_or_mf_counter + " ["
1262                     + ( 100 * pfams_with_mappings_to_bp_or_mf_counter / all_pfams_encountered.size() ) + "%]" );
1263             summary_writer.write( ForesterUtil.LINE_SEPARATOR );
1264             summary_writer.write( "# Pfams with mapping to biological process: " + biological_process_counter + " ["
1265                     + ( 100 * biological_process_counter / all_pfams_encountered.size() ) + "%]" );
1266             summary_writer.write( ForesterUtil.LINE_SEPARATOR );
1267             summary_writer.write( "# Pfams with mapping to molecular function: " + molecular_function_counter + " ["
1268                     + ( 100 * molecular_function_counter / all_pfams_encountered.size() ) + "%]" );
1269             summary_writer.write( ForesterUtil.LINE_SEPARATOR );
1270             summary_writer.write( "# Pfams with mapping to cellular component: " + cellular_component_counter + " ["
1271                     + ( 100 * cellular_component_counter / all_pfams_encountered.size() ) + "%]" );
1272             summary_writer.write( ForesterUtil.LINE_SEPARATOR );
1273             summary_writer.close();
1274         }
1275         catch ( final IOException e ) {
1276             ForesterUtil.printWarningMessage( surfacing.PRG_NAME, "Failure to write: " + e );
1277         }
1278     }
1279
1280     public static void writeBinaryDomainCombinationsFileForGraphAnalysis( final String[][] input_file_properties,
1281                                                                           final File output_dir,
1282                                                                           final GenomeWideCombinableDomains gwcd,
1283                                                                           final int i,
1284                                                                           final GenomeWideCombinableDomainsSortOrder dc_sort_order ) {
1285         File dc_outfile_dot = new File( input_file_properties[ i ][ 0 ]
1286                 + surfacing.DOMAIN_COMBINITONS_OUTPUTFILE_SUFFIX_FOR_GRAPH_ANALYSIS );
1287         if ( output_dir != null ) {
1288             dc_outfile_dot = new File( output_dir + ForesterUtil.FILE_SEPARATOR + dc_outfile_dot );
1289         }
1290         checkForOutputFileWriteability( dc_outfile_dot );
1291         final SortedSet<BinaryDomainCombination> binary_combinations = createSetOfAllBinaryDomainCombinationsPerGenome( gwcd );
1292         try {
1293             final BufferedWriter out_dot = new BufferedWriter( new FileWriter( dc_outfile_dot ) );
1294             for( final BinaryDomainCombination bdc : binary_combinations ) {
1295                 out_dot.write( bdc.toGraphDescribingLanguage( BinaryDomainCombination.OutputFormat.DOT, null, null )
1296                         .toString() );
1297                 out_dot.write( SurfacingConstants.NL );
1298             }
1299             out_dot.close();
1300         }
1301         catch ( final IOException e ) {
1302             ForesterUtil.fatalError( surfacing.PRG_NAME, e.getMessage() );
1303         }
1304         ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote binary domain combination for \""
1305                 + input_file_properties[ i ][ 0 ] + "\" (" + input_file_properties[ i ][ 1 ] + ", "
1306                 + input_file_properties[ i ][ 2 ] + ") to: \"" + dc_outfile_dot + "\"" );
1307     }
1308
1309     public static void writeBinaryStatesMatrixAsListToFile( final CharacterStateMatrix<CharacterStateMatrix.GainLossStates> matrix,
1310                                                             final CharacterStateMatrix.GainLossStates state,
1311                                                             final String filename,
1312                                                             final String indentifier_characters_separator,
1313                                                             final String character_separator,
1314                                                             final Map<String, String> descriptions ) {
1315         final File outfile = new File( filename );
1316         checkForOutputFileWriteability( outfile );
1317         final SortedSet<String> sorted_ids = new TreeSet<String>();
1318         for( int i = 0; i < matrix.getNumberOfIdentifiers(); ++i ) {
1319             sorted_ids.add( matrix.getIdentifier( i ) );
1320         }
1321         try {
1322             final BufferedWriter out = new BufferedWriter( new FileWriter( outfile ) );
1323             for( final String id : sorted_ids ) {
1324                 out.write( indentifier_characters_separator );
1325                 out.write( "#" + id );
1326                 out.write( indentifier_characters_separator );
1327                 for( int c = 0; c < matrix.getNumberOfCharacters(); ++c ) {
1328                     // Not nice:
1329                     // using null to indicate either UNCHANGED_PRESENT or GAIN.
1330                     if ( ( matrix.getState( id, c ) == state )
1331                             || ( ( state == null ) && ( ( matrix.getState( id, c ) == CharacterStateMatrix.GainLossStates.GAIN ) || ( matrix
1332                                     .getState( id, c ) == CharacterStateMatrix.GainLossStates.UNCHANGED_PRESENT ) ) ) ) {
1333                         out.write( matrix.getCharacter( c ) );
1334                         if ( ( descriptions != null ) && !descriptions.isEmpty()
1335                                 && descriptions.containsKey( matrix.getCharacter( c ) ) ) {
1336                             out.write( "\t" );
1337                             out.write( descriptions.get( matrix.getCharacter( c ) ) );
1338                         }
1339                         out.write( character_separator );
1340                     }
1341                 }
1342             }
1343             out.flush();
1344             out.close();
1345         }
1346         catch ( final IOException e ) {
1347             ForesterUtil.fatalError( surfacing.PRG_NAME, e.getMessage() );
1348         }
1349         ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote characters list: \"" + filename + "\"" );
1350     }
1351
1352     public static void writeBinaryStatesMatrixAsListToFileForBinaryCombinationsForGraphAnalysis( final CharacterStateMatrix<CharacterStateMatrix.GainLossStates> matrix,
1353                                                                                                  final CharacterStateMatrix.GainLossStates state,
1354                                                                                                  final String filename,
1355                                                                                                  final String indentifier_characters_separator,
1356                                                                                                  final String character_separator,
1357                                                                                                  final BinaryDomainCombination.OutputFormat bc_output_format ) {
1358         final File outfile = new File( filename );
1359         checkForOutputFileWriteability( outfile );
1360         final SortedSet<String> sorted_ids = new TreeSet<String>();
1361         for( int i = 0; i < matrix.getNumberOfIdentifiers(); ++i ) {
1362             sorted_ids.add( matrix.getIdentifier( i ) );
1363         }
1364         try {
1365             final BufferedWriter out = new BufferedWriter( new FileWriter( outfile ) );
1366             for( final String id : sorted_ids ) {
1367                 out.write( indentifier_characters_separator );
1368                 out.write( "#" + id );
1369                 out.write( indentifier_characters_separator );
1370                 for( int c = 0; c < matrix.getNumberOfCharacters(); ++c ) {
1371                     // Not nice:
1372                     // using null to indicate either UNCHANGED_PRESENT or GAIN.
1373                     if ( ( matrix.getState( id, c ) == state )
1374                             || ( ( state == null ) && ( ( matrix.getState( id, c ) == CharacterStateMatrix.GainLossStates.GAIN ) || ( matrix
1375                                     .getState( id, c ) == CharacterStateMatrix.GainLossStates.UNCHANGED_PRESENT ) ) ) ) {
1376                         BinaryDomainCombination bdc = null;
1377                         try {
1378                             bdc = BasicBinaryDomainCombination.createInstance( matrix.getCharacter( c ) );
1379                         }
1380                         catch ( final Exception e ) {
1381                             ForesterUtil.fatalError( surfacing.PRG_NAME, e.getLocalizedMessage() );
1382                         }
1383                         out.write( bdc.toGraphDescribingLanguage( bc_output_format, null, null ).toString() );
1384                         out.write( character_separator );
1385                     }
1386                 }
1387             }
1388             out.flush();
1389             out.close();
1390         }
1391         catch ( final IOException e ) {
1392             ForesterUtil.fatalError( surfacing.PRG_NAME, e.getMessage() );
1393         }
1394         ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote characters list: \"" + filename + "\"" );
1395     }
1396
1397     public static void writeBinaryStatesMatrixToList( final Map<DomainId, List<GoId>> domain_id_to_go_ids_map,
1398                                                       final Map<GoId, GoTerm> go_id_to_term_map,
1399                                                       final GoNameSpace go_namespace_limit,
1400                                                       final boolean domain_combinations,
1401                                                       final CharacterStateMatrix<CharacterStateMatrix.GainLossStates> matrix,
1402                                                       final CharacterStateMatrix.GainLossStates state,
1403                                                       final String filename,
1404                                                       final String indentifier_characters_separator,
1405                                                       final String character_separator,
1406                                                       final String title_for_html,
1407                                                       final String prefix_for_html,
1408                                                       final Map<DomainId, Set<String>>[] domain_id_to_secondary_features_maps,
1409                                                       final SortedSet<String> all_pfams_encountered,
1410                                                       final SortedSet<String> pfams_gained_or_lost,
1411                                                       final String suffix_for_per_node_events_file ) {
1412         if ( ( go_namespace_limit != null ) && ( ( go_id_to_term_map == null ) || ( go_id_to_term_map.size() < 1 ) ) ) {
1413             throw new IllegalArgumentException( "attempt to use GO namespace limit without a GO-id to term map" );
1414         }
1415         else if ( ( ( domain_id_to_go_ids_map == null ) || ( domain_id_to_go_ids_map.size() < 1 ) ) ) {
1416             throw new IllegalArgumentException( "attempt to output detailed HTML without a Pfam to GO map" );
1417         }
1418         else if ( ( ( go_id_to_term_map == null ) || ( go_id_to_term_map.size() < 1 ) ) ) {
1419             throw new IllegalArgumentException( "attempt to output detailed HTML without a GO-id to term map" );
1420         }
1421         final File outfile = new File( filename );
1422         checkForOutputFileWriteability( outfile );
1423         final SortedSet<String> sorted_ids = new TreeSet<String>();
1424         for( int i = 0; i < matrix.getNumberOfIdentifiers(); ++i ) {
1425             sorted_ids.add( matrix.getIdentifier( i ) );
1426         }
1427         try {
1428             final Writer out = new BufferedWriter( new FileWriter( outfile ) );
1429             final File per_node_go_mapped_domain_gain_loss_files_base_dir = createBaseDirForPerNodeDomainFiles( surfacing.BASE_DIRECTORY_PER_NODE_DOMAIN_GAIN_LOSS_FILES,
1430                                                                                                                 domain_combinations,
1431                                                                                                                 state,
1432                                                                                                                 filename );
1433             Writer per_node_go_mapped_domain_gain_loss_outfile_writer = null;
1434             File per_node_go_mapped_domain_gain_loss_outfile = null;
1435             int per_node_counter = 0;
1436             out.write( "<html>" );
1437             out.write( SurfacingConstants.NL );
1438             addHtmlHead( out, title_for_html );
1439             out.write( SurfacingConstants.NL );
1440             out.write( "<body>" );
1441             out.write( SurfacingConstants.NL );
1442             out.write( "<h1>" );
1443             out.write( SurfacingConstants.NL );
1444             out.write( title_for_html );
1445             out.write( SurfacingConstants.NL );
1446             out.write( "</h1>" );
1447             out.write( SurfacingConstants.NL );
1448             out.write( "<table>" );
1449             out.write( SurfacingConstants.NL );
1450             for( final String id : sorted_ids ) {
1451                 final Matcher matcher = PATTERN_SP_STYLE_TAXONOMY.matcher( id );
1452                 if ( matcher.matches() ) {
1453                     continue;
1454                 }
1455                 out.write( "<tr>" );
1456                 out.write( "<td>" );
1457                 out.write( "<a href=\"#" + id + "\">" + id + "</a>" );
1458                 out.write( "</td>" );
1459                 out.write( "</tr>" );
1460                 out.write( SurfacingConstants.NL );
1461             }
1462             out.write( "</table>" );
1463             out.write( SurfacingConstants.NL );
1464             for( final String id : sorted_ids ) {
1465                 final Matcher matcher = PATTERN_SP_STYLE_TAXONOMY.matcher( id );
1466                 if ( matcher.matches() ) {
1467                     continue;
1468                 }
1469                 out.write( SurfacingConstants.NL );
1470                 out.write( "<h2>" );
1471                 out.write( "<a name=\"" + id + "\">" + id + "</a>" );
1472                 writeTaxonomyLinks( out, id );
1473                 out.write( "</h2>" );
1474                 out.write( SurfacingConstants.NL );
1475                 out.write( "<table>" );
1476                 out.write( SurfacingConstants.NL );
1477                 out.write( "<tr>" );
1478                 out.write( "<td><b>" );
1479                 out.write( "Pfam domain(s)" );
1480                 out.write( "</b></td><td><b>" );
1481                 out.write( "GO term acc" );
1482                 out.write( "</b></td><td><b>" );
1483                 out.write( "GO term" );
1484                 out.write( "</b></td><td><b>" );
1485                 out.write( "GO namespace" );
1486                 out.write( "</b></td>" );
1487                 out.write( "</tr>" );
1488                 out.write( SurfacingConstants.NL );
1489                 out.write( "</tr>" );
1490                 out.write( SurfacingConstants.NL );
1491                 per_node_counter = 0;
1492                 if ( matrix.getNumberOfCharacters() > 0 ) {
1493                     per_node_go_mapped_domain_gain_loss_outfile = new File( per_node_go_mapped_domain_gain_loss_files_base_dir
1494                             + ForesterUtil.FILE_SEPARATOR + id + suffix_for_per_node_events_file );
1495                     SurfacingUtil.checkForOutputFileWriteability( per_node_go_mapped_domain_gain_loss_outfile );
1496                     per_node_go_mapped_domain_gain_loss_outfile_writer = ForesterUtil
1497                             .createBufferedWriter( per_node_go_mapped_domain_gain_loss_outfile );
1498                 }
1499                 else {
1500                     per_node_go_mapped_domain_gain_loss_outfile = null;
1501                     per_node_go_mapped_domain_gain_loss_outfile_writer = null;
1502                 }
1503                 for( int c = 0; c < matrix.getNumberOfCharacters(); ++c ) {
1504                     // Not nice:
1505                     // using null to indicate either UNCHANGED_PRESENT or GAIN.
1506                     if ( ( matrix.getState( id, c ) == state )
1507                             || ( ( state == null ) && ( ( matrix.getState( id, c ) == CharacterStateMatrix.GainLossStates.UNCHANGED_PRESENT ) || ( matrix
1508                                     .getState( id, c ) == CharacterStateMatrix.GainLossStates.GAIN ) ) ) ) {
1509                         final String character = matrix.getCharacter( c );
1510                         String domain_0 = "";
1511                         String domain_1 = "";
1512                         if ( character.indexOf( BinaryDomainCombination.SEPARATOR ) > 0 ) {
1513                             final String[] s = character.split( BinaryDomainCombination.SEPARATOR );
1514                             if ( s.length != 2 ) {
1515                                 throw new AssertionError( "this should not have happened: unexpected format for domain combination: ["
1516                                         + character + "]" );
1517                             }
1518                             domain_0 = s[ 0 ];
1519                             domain_1 = s[ 1 ];
1520                         }
1521                         else {
1522                             domain_0 = character;
1523                         }
1524                         writeDomainData( domain_id_to_go_ids_map,
1525                                          go_id_to_term_map,
1526                                          go_namespace_limit,
1527                                          out,
1528                                          domain_0,
1529                                          domain_1,
1530                                          prefix_for_html,
1531                                          character_separator,
1532                                          domain_id_to_secondary_features_maps,
1533                                          null );
1534                         all_pfams_encountered.add( domain_0 );
1535                         if ( pfams_gained_or_lost != null ) {
1536                             pfams_gained_or_lost.add( domain_0 );
1537                         }
1538                         if ( !ForesterUtil.isEmpty( domain_1 ) ) {
1539                             all_pfams_encountered.add( domain_1 );
1540                             if ( pfams_gained_or_lost != null ) {
1541                                 pfams_gained_or_lost.add( domain_1 );
1542                             }
1543                         }
1544                         if ( per_node_go_mapped_domain_gain_loss_outfile_writer != null ) {
1545                             writeDomainsToIndividualFilePerTreeNode( per_node_go_mapped_domain_gain_loss_outfile_writer,
1546                                                                      domain_0,
1547                                                                      domain_1 );
1548                             per_node_counter++;
1549                         }
1550                     }
1551                 }
1552                 if ( per_node_go_mapped_domain_gain_loss_outfile_writer != null ) {
1553                     per_node_go_mapped_domain_gain_loss_outfile_writer.close();
1554                     if ( per_node_counter < 1 ) {
1555                         per_node_go_mapped_domain_gain_loss_outfile.delete();
1556                     }
1557                     per_node_counter = 0;
1558                 }
1559                 out.write( "</table>" );
1560                 out.write( SurfacingConstants.NL );
1561                 out.write( "<hr>" );
1562                 out.write( SurfacingConstants.NL );
1563             } // for( final String id : sorted_ids ) {  
1564             out.write( "</body>" );
1565             out.write( SurfacingConstants.NL );
1566             out.write( "</html>" );
1567             out.write( SurfacingConstants.NL );
1568             out.flush();
1569             out.close();
1570         }
1571         catch ( final IOException e ) {
1572             ForesterUtil.fatalError( surfacing.PRG_NAME, e.getMessage() );
1573         }
1574         ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote characters detailed HTML list: \"" + filename + "\"" );
1575     }
1576
1577     public static void writeBinaryStatesMatrixToListORIGIG( final Map<DomainId, List<GoId>> domain_id_to_go_ids_map,
1578                                                             final Map<GoId, GoTerm> go_id_to_term_map,
1579                                                             final GoNameSpace go_namespace_limit,
1580                                                             final boolean domain_combinations,
1581                                                             final CharacterStateMatrix<CharacterStateMatrix.GainLossStates> matrix,
1582                                                             final CharacterStateMatrix.GainLossStates state,
1583                                                             final String filename,
1584                                                             final String indentifier_characters_separator,
1585                                                             final String character_separator,
1586                                                             final String title_for_html,
1587                                                             final String prefix_for_html,
1588                                                             final Map<DomainId, Set<String>>[] domain_id_to_secondary_features_maps,
1589                                                             final SortedSet<String> all_pfams_encountered,
1590                                                             final SortedSet<String> pfams_gained_or_lost,
1591                                                             final String suffix_for_per_node_events_file ) {
1592         if ( ( go_namespace_limit != null ) && ( ( go_id_to_term_map == null ) || ( go_id_to_term_map.size() < 1 ) ) ) {
1593             throw new IllegalArgumentException( "attempt to use GO namespace limit without a GO-id to term map" );
1594         }
1595         else if ( ( ( domain_id_to_go_ids_map == null ) || ( domain_id_to_go_ids_map.size() < 1 ) ) ) {
1596             throw new IllegalArgumentException( "attempt to output detailed HTML without a Pfam to GO map" );
1597         }
1598         else if ( ( ( go_id_to_term_map == null ) || ( go_id_to_term_map.size() < 1 ) ) ) {
1599             throw new IllegalArgumentException( "attempt to output detailed HTML without a GO-id to term map" );
1600         }
1601         final File outfile = new File( filename );
1602         checkForOutputFileWriteability( outfile );
1603         final SortedSet<String> sorted_ids = new TreeSet<String>();
1604         for( int i = 0; i < matrix.getNumberOfIdentifiers(); ++i ) {
1605             sorted_ids.add( matrix.getIdentifier( i ) );
1606         }
1607         try {
1608             final Writer out = new BufferedWriter( new FileWriter( outfile ) );
1609             final File per_node_go_mapped_domain_gain_loss_files_base_dir = createBaseDirForPerNodeDomainFiles( surfacing.BASE_DIRECTORY_PER_NODE_DOMAIN_GAIN_LOSS_FILES,
1610                                                                                                                 domain_combinations,
1611                                                                                                                 state,
1612                                                                                                                 filename );
1613             Writer per_node_go_mapped_domain_gain_loss_outfile_writer = null;
1614             File per_node_go_mapped_domain_gain_loss_outfile = null;
1615             int per_node_counter = 0;
1616             out.write( "<html>" );
1617             out.write( SurfacingConstants.NL );
1618             addHtmlHead( out, title_for_html );
1619             out.write( SurfacingConstants.NL );
1620             out.write( "<body>" );
1621             out.write( SurfacingConstants.NL );
1622             out.write( "<h1>" );
1623             out.write( SurfacingConstants.NL );
1624             out.write( title_for_html );
1625             out.write( SurfacingConstants.NL );
1626             out.write( "</h1>" );
1627             out.write( SurfacingConstants.NL );
1628             out.write( "<table>" );
1629             out.write( SurfacingConstants.NL );
1630             for( final String id : sorted_ids ) {
1631                 out.write( "<tr>" );
1632                 out.write( "<td>" );
1633                 out.write( "<a href=\"#" + id + "\">" + id + "</a>" );
1634                 writeTaxonomyLinks( out, id );
1635                 out.write( "</td>" );
1636                 out.write( "</tr>" );
1637                 out.write( SurfacingConstants.NL );
1638             }
1639             out.write( "</table>" );
1640             out.write( SurfacingConstants.NL );
1641             for( final String id : sorted_ids ) {
1642                 out.write( SurfacingConstants.NL );
1643                 out.write( "<h2>" );
1644                 out.write( "<a name=\"" + id + "\">" + id + "</a>" );
1645                 writeTaxonomyLinks( out, id );
1646                 out.write( "</h2>" );
1647                 out.write( SurfacingConstants.NL );
1648                 out.write( "<table>" );
1649                 out.write( SurfacingConstants.NL );
1650                 out.write( "<tr>" );
1651                 out.write( "<td><b>" );
1652                 out.write( "Pfam domain(s)" );
1653                 out.write( "</b></td><td><b>" );
1654                 out.write( "GO term acc" );
1655                 out.write( "</b></td><td><b>" );
1656                 out.write( "GO term" );
1657                 out.write( "</b></td><td><b>" );
1658                 out.write( "Penultimate GO term" );
1659                 out.write( "</b></td><td><b>" );
1660                 out.write( "GO namespace" );
1661                 out.write( "</b></td>" );
1662                 out.write( "</tr>" );
1663                 out.write( SurfacingConstants.NL );
1664                 out.write( "</tr>" );
1665                 out.write( SurfacingConstants.NL );
1666                 per_node_counter = 0;
1667                 if ( matrix.getNumberOfCharacters() > 0 ) {
1668                     per_node_go_mapped_domain_gain_loss_outfile = new File( per_node_go_mapped_domain_gain_loss_files_base_dir
1669                             + ForesterUtil.FILE_SEPARATOR + id + suffix_for_per_node_events_file );
1670                     SurfacingUtil.checkForOutputFileWriteability( per_node_go_mapped_domain_gain_loss_outfile );
1671                     per_node_go_mapped_domain_gain_loss_outfile_writer = ForesterUtil
1672                             .createBufferedWriter( per_node_go_mapped_domain_gain_loss_outfile );
1673                 }
1674                 else {
1675                     per_node_go_mapped_domain_gain_loss_outfile = null;
1676                     per_node_go_mapped_domain_gain_loss_outfile_writer = null;
1677                 }
1678                 for( int c = 0; c < matrix.getNumberOfCharacters(); ++c ) {
1679                     // Not nice:
1680                     // using null to indicate either UNCHANGED_PRESENT or GAIN.
1681                     if ( ( matrix.getState( id, c ) == state )
1682                             || ( ( state == null ) && ( ( matrix.getState( id, c ) == CharacterStateMatrix.GainLossStates.UNCHANGED_PRESENT ) || ( matrix
1683                                     .getState( id, c ) == CharacterStateMatrix.GainLossStates.GAIN ) ) ) ) {
1684                         final String character = matrix.getCharacter( c );
1685                         String domain_0 = "";
1686                         String domain_1 = "";
1687                         if ( character.indexOf( BinaryDomainCombination.SEPARATOR ) > 0 ) {
1688                             final String[] s = character.split( BinaryDomainCombination.SEPARATOR );
1689                             if ( s.length != 2 ) {
1690                                 throw new AssertionError( "this should not have happened: unexpected format for domain combination: ["
1691                                         + character + "]" );
1692                             }
1693                             domain_0 = s[ 0 ];
1694                             domain_1 = s[ 1 ];
1695                         }
1696                         else {
1697                             domain_0 = character;
1698                         }
1699                         writeDomainData( domain_id_to_go_ids_map,
1700                                          go_id_to_term_map,
1701                                          go_namespace_limit,
1702                                          out,
1703                                          domain_0,
1704                                          domain_1,
1705                                          prefix_for_html,
1706                                          character_separator,
1707                                          domain_id_to_secondary_features_maps,
1708                                          null );
1709                         all_pfams_encountered.add( domain_0 );
1710                         if ( pfams_gained_or_lost != null ) {
1711                             pfams_gained_or_lost.add( domain_0 );
1712                         }
1713                         if ( !ForesterUtil.isEmpty( domain_1 ) ) {
1714                             all_pfams_encountered.add( domain_1 );
1715                             if ( pfams_gained_or_lost != null ) {
1716                                 pfams_gained_or_lost.add( domain_1 );
1717                             }
1718                         }
1719                         if ( per_node_go_mapped_domain_gain_loss_outfile_writer != null ) {
1720                             writeDomainsToIndividualFilePerTreeNode( per_node_go_mapped_domain_gain_loss_outfile_writer,
1721                                                                      domain_0,
1722                                                                      domain_1 );
1723                             per_node_counter++;
1724                         }
1725                     }
1726                 }
1727                 if ( per_node_go_mapped_domain_gain_loss_outfile_writer != null ) {
1728                     per_node_go_mapped_domain_gain_loss_outfile_writer.close();
1729                     if ( per_node_counter < 1 ) {
1730                         per_node_go_mapped_domain_gain_loss_outfile.delete();
1731                     }
1732                     per_node_counter = 0;
1733                 }
1734                 out.write( "</table>" );
1735                 out.write( SurfacingConstants.NL );
1736                 out.write( "<hr>" );
1737                 out.write( SurfacingConstants.NL );
1738             } // for( final String id : sorted_ids ) {  
1739             out.write( "</body>" );
1740             out.write( SurfacingConstants.NL );
1741             out.write( "</html>" );
1742             out.write( SurfacingConstants.NL );
1743             out.flush();
1744             out.close();
1745         }
1746         catch ( final IOException e ) {
1747             ForesterUtil.fatalError( surfacing.PRG_NAME, e.getMessage() );
1748         }
1749         ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote characters detailed HTML list: \"" + filename + "\"" );
1750     }
1751
1752     public static void writeDomainCombinationsCountsFile( final String[][] input_file_properties,
1753                                                           final File output_dir,
1754                                                           final Writer per_genome_domain_promiscuity_statistics_writer,
1755                                                           final GenomeWideCombinableDomains gwcd,
1756                                                           final int i,
1757                                                           final GenomeWideCombinableDomains.GenomeWideCombinableDomainsSortOrder dc_sort_order ) {
1758         File dc_outfile = new File( input_file_properties[ i ][ 0 ]
1759                 + surfacing.DOMAIN_COMBINITON_COUNTS_OUTPUTFILE_SUFFIX );
1760         if ( output_dir != null ) {
1761             dc_outfile = new File( output_dir + ForesterUtil.FILE_SEPARATOR + dc_outfile );
1762         }
1763         checkForOutputFileWriteability( dc_outfile );
1764         try {
1765             final BufferedWriter out = new BufferedWriter( new FileWriter( dc_outfile ) );
1766             out.write( gwcd.toStringBuilder( dc_sort_order ).toString() );
1767             out.close();
1768         }
1769         catch ( final IOException e ) {
1770             ForesterUtil.fatalError( surfacing.PRG_NAME, e.getMessage() );
1771         }
1772         final DescriptiveStatistics stats = gwcd.getPerGenomeDomainPromiscuityStatistics();
1773         try {
1774             per_genome_domain_promiscuity_statistics_writer.write( input_file_properties[ i ][ 0 ] + "\t" );
1775             per_genome_domain_promiscuity_statistics_writer.write( FORMATTER_3.format( stats.arithmeticMean() ) + "\t" );
1776             if ( stats.getN() < 2 ) {
1777                 per_genome_domain_promiscuity_statistics_writer.write( "n/a" + "\t" );
1778             }
1779             else {
1780                 per_genome_domain_promiscuity_statistics_writer.write( FORMATTER_3.format( stats
1781                         .sampleStandardDeviation() ) + "\t" );
1782             }
1783             per_genome_domain_promiscuity_statistics_writer.write( FORMATTER_3.format( stats.median() ) + "\t" );
1784             per_genome_domain_promiscuity_statistics_writer.write( ( int ) stats.getMin() + "\t" );
1785             per_genome_domain_promiscuity_statistics_writer.write( ( int ) stats.getMax() + "\t" );
1786             per_genome_domain_promiscuity_statistics_writer.write( stats.getN() + "\t" );
1787             final SortedSet<DomainId> mpds = gwcd.getMostPromiscuosDomain();
1788             for( final DomainId mpd : mpds ) {
1789                 per_genome_domain_promiscuity_statistics_writer.write( mpd.getId() + " " );
1790             }
1791             per_genome_domain_promiscuity_statistics_writer.write( ForesterUtil.LINE_SEPARATOR );
1792         }
1793         catch ( final IOException e ) {
1794             ForesterUtil.fatalError( surfacing.PRG_NAME, e.getMessage() );
1795         }
1796         if ( input_file_properties[ i ].length == 3 ) {
1797             ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote domain combination counts for \""
1798                     + input_file_properties[ i ][ 0 ] + "\" (" + input_file_properties[ i ][ 1 ] + ", "
1799                     + input_file_properties[ i ][ 2 ] + ") to: \"" + dc_outfile + "\"" );
1800         }
1801         else {
1802             ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote domain combination counts for \""
1803                     + input_file_properties[ i ][ 0 ] + "\" (" + input_file_properties[ i ][ 1 ] + ") to: \""
1804                     + dc_outfile + "\"" );
1805         }
1806     }
1807
1808     private static void writeDomainData( final Map<DomainId, List<GoId>> domain_id_to_go_ids_map,
1809                                          final Map<GoId, GoTerm> go_id_to_term_map,
1810                                          final GoNameSpace go_namespace_limit,
1811                                          final Writer out,
1812                                          final String domain_0,
1813                                          final String domain_1,
1814                                          final String prefix_for_html,
1815                                          final String character_separator_for_non_html_output,
1816                                          final Map<DomainId, Set<String>>[] domain_id_to_secondary_features_maps,
1817                                          final Set<GoId> all_go_ids ) throws IOException {
1818         boolean any_go_annotation_present = false;
1819         boolean first_has_no_go = false;
1820         int domain_count = 2; // To distinguish between domains and binary domain combinations.
1821         if ( ForesterUtil.isEmpty( domain_1 ) ) {
1822             domain_count = 1;
1823         }
1824         // The following has a difficult to understand logic.  
1825         for( int d = 0; d < domain_count; ++d ) {
1826             List<GoId> go_ids = null;
1827             boolean go_annotation_present = false;
1828             if ( d == 0 ) {
1829                 final DomainId domain_id = new DomainId( domain_0 );
1830                 if ( domain_id_to_go_ids_map.containsKey( domain_id ) ) {
1831                     go_annotation_present = true;
1832                     any_go_annotation_present = true;
1833                     go_ids = domain_id_to_go_ids_map.get( domain_id );
1834                 }
1835                 else {
1836                     first_has_no_go = true;
1837                 }
1838             }
1839             else {
1840                 final DomainId domain_id = new DomainId( domain_1 );
1841                 if ( domain_id_to_go_ids_map.containsKey( domain_id ) ) {
1842                     go_annotation_present = true;
1843                     any_go_annotation_present = true;
1844                     go_ids = domain_id_to_go_ids_map.get( domain_id );
1845                 }
1846             }
1847             if ( go_annotation_present ) {
1848                 boolean first = ( ( d == 0 ) || ( ( d == 1 ) && first_has_no_go ) );
1849                 for( final GoId go_id : go_ids ) {
1850                     out.write( "<tr>" );
1851                     if ( first ) {
1852                         first = false;
1853                         writeDomainIdsToHtml( out,
1854                                               domain_0,
1855                                               domain_1,
1856                                               prefix_for_html,
1857                                               domain_id_to_secondary_features_maps );
1858                     }
1859                     else {
1860                         out.write( "<td></td>" );
1861                     }
1862                     if ( !go_id_to_term_map.containsKey( go_id ) ) {
1863                         throw new IllegalArgumentException( "GO-id [" + go_id + "] not found in GO-id to GO-term map" );
1864                     }
1865                     final GoTerm go_term = go_id_to_term_map.get( go_id );
1866                     if ( ( go_namespace_limit == null ) || go_namespace_limit.equals( go_term.getGoNameSpace() ) ) {
1867                         // final String top = GoUtils.getPenultimateGoTerm( go_term, go_id_to_term_map ).getName();
1868                         final String go_id_str = go_id.getId();
1869                         out.write( "<td>" );
1870                         out.write( "<a href=\"" + SurfacingConstants.AMIGO_LINK + go_id_str
1871                                 + "\" target=\"amigo_window\">" + go_id_str + "</a>" );
1872                         out.write( "</td><td>" );
1873                         out.write( go_term.getName() );
1874                         if ( domain_count == 2 ) {
1875                             out.write( " (" + d + ")" );
1876                         }
1877                         out.write( "</td><td>" );
1878                         // out.write( top );
1879                         // out.write( "</td><td>" );
1880                         out.write( "[" );
1881                         out.write( go_term.getGoNameSpace().toShortString() );
1882                         out.write( "]" );
1883                         out.write( "</td>" );
1884                         if ( all_go_ids != null ) {
1885                             all_go_ids.add( go_id );
1886                         }
1887                     }
1888                     else {
1889                         out.write( "<td>" );
1890                         out.write( "</td><td>" );
1891                         out.write( "</td><td>" );
1892                         out.write( "</td><td>" );
1893                         out.write( "</td>" );
1894                     }
1895                     out.write( "</tr>" );
1896                     out.write( SurfacingConstants.NL );
1897                 }
1898             }
1899         } //  for( int d = 0; d < domain_count; ++d ) 
1900         if ( !any_go_annotation_present ) {
1901             out.write( "<tr>" );
1902             writeDomainIdsToHtml( out, domain_0, domain_1, prefix_for_html, domain_id_to_secondary_features_maps );
1903             out.write( "<td>" );
1904             out.write( "</td><td>" );
1905             out.write( "</td><td>" );
1906             out.write( "</td><td>" );
1907             out.write( "</td>" );
1908             out.write( "</tr>" );
1909             out.write( SurfacingConstants.NL );
1910         }
1911     }
1912
1913     private static void writeDomainIdsToHtml( final Writer out,
1914                                               final String domain_0,
1915                                               final String domain_1,
1916                                               final String prefix_for_detailed_html,
1917                                               final Map<DomainId, Set<String>>[] domain_id_to_secondary_features_maps )
1918             throws IOException {
1919         out.write( "<td>" );
1920         if ( !ForesterUtil.isEmpty( prefix_for_detailed_html ) ) {
1921             out.write( prefix_for_detailed_html );
1922             out.write( " " );
1923         }
1924         out.write( "<a href=\"" + SurfacingConstants.PFAM_FAMILY_ID_LINK + domain_0 + "\">" + domain_0 + "</a>" );
1925         out.write( "</td>" );
1926     }
1927
1928     public static DescriptiveStatistics writeDomainSimilaritiesToFile( final StringBuilder html_desc,
1929                                                                        final StringBuilder html_title,
1930                                                                        final Writer w,
1931                                                                        final SortedSet<DomainSimilarity> similarities,
1932                                                                        final boolean treat_as_binary,
1933                                                                        final List<Species> species_order,
1934                                                                        final PrintableDomainSimilarity.PRINT_OPTION print_option,
1935                                                                        final DomainSimilarity.DomainSimilaritySortField sort_field,
1936                                                                        final DomainSimilarity.DomainSimilarityScoring scoring,
1937                                                                        final boolean verbose ) throws IOException {
1938         final DescriptiveStatistics stats = new BasicDescriptiveStatistics();
1939         String histogram_title = null;
1940         switch ( sort_field ) {
1941             case ABS_MAX_COUNTS_DIFFERENCE:
1942                 if ( treat_as_binary ) {
1943                     histogram_title = "absolute counts difference:";
1944                 }
1945                 else {
1946                     histogram_title = "absolute (maximal) counts difference:";
1947                 }
1948                 break;
1949             case MAX_COUNTS_DIFFERENCE:
1950                 if ( treat_as_binary ) {
1951                     histogram_title = "counts difference:";
1952                 }
1953                 else {
1954                     histogram_title = "(maximal) counts difference:";
1955                 }
1956                 break;
1957             case DOMAIN_ID:
1958                 histogram_title = "score mean:";
1959                 break;
1960             case MIN:
1961                 histogram_title = "score minimum:";
1962                 break;
1963             case MAX:
1964                 histogram_title = "score maximum:";
1965                 break;
1966             case MAX_DIFFERENCE:
1967                 if ( treat_as_binary ) {
1968                     histogram_title = "difference:";
1969                 }
1970                 else {
1971                     histogram_title = "(maximal) difference:";
1972                 }
1973                 break;
1974             case MEAN:
1975                 histogram_title = "score mean:";
1976                 break;
1977             case SD:
1978                 histogram_title = "score standard deviation:";
1979                 break;
1980             case SPECIES_COUNT:
1981                 histogram_title = "species number:";
1982                 break;
1983             default:
1984                 throw new AssertionError( "Unknown sort field: " + sort_field );
1985         }
1986         for( final DomainSimilarity similarity : similarities ) {
1987             switch ( sort_field ) {
1988                 case ABS_MAX_COUNTS_DIFFERENCE:
1989                     stats.addValue( Math.abs( similarity.getMaximalDifferenceInCounts() ) );
1990                     break;
1991                 case MAX_COUNTS_DIFFERENCE:
1992                     stats.addValue( similarity.getMaximalDifferenceInCounts() );
1993                     break;
1994                 case DOMAIN_ID:
1995                     stats.addValue( similarity.getMeanSimilarityScore() );
1996                     break;
1997                 case MIN:
1998                     stats.addValue( similarity.getMinimalSimilarityScore() );
1999                     break;
2000                 case MAX:
2001                     stats.addValue( similarity.getMaximalSimilarityScore() );
2002                     break;
2003                 case MAX_DIFFERENCE:
2004                     stats.addValue( similarity.getMaximalDifference() );
2005                     break;
2006                 case MEAN:
2007                     stats.addValue( similarity.getMeanSimilarityScore() );
2008                     break;
2009                 case SD:
2010                     stats.addValue( similarity.getStandardDeviationOfSimilarityScore() );
2011                     break;
2012                 case SPECIES_COUNT:
2013                     stats.addValue( similarity.getSpecies().size() );
2014                     break;
2015                 default:
2016                     throw new AssertionError( "Unknown sort field: " + sort_field );
2017             }
2018         }
2019         //
2020         // final HistogramData[] hists = new HistogramData[ 1 ];
2021         //      
2022         //        
2023         // List<HistogramDataItem> data_items = new
2024         // ArrayList<HistogramDataItem>();
2025         // double[] values = stats.getDataAsDoubleArray();
2026         // for( int i = 0; i < values.length; i++ ) {
2027         // HistogramDataItem data_item = new BasicHistogramDataItem( "", values[
2028         // i ] );
2029         // data_items.add( data_item );
2030         // }
2031         //        
2032         //        
2033         // HistogramData hd0 = new HistogramData( "name",
2034         // data_items,
2035         // null, 20,
2036         // 40 );
2037         //        
2038         //        
2039         //        
2040         //        
2041         // hists[ 0 ] = hd0;
2042         //       
2043         // final HistogramsFrame hf = new HistogramsFrame( hists );
2044         // hf.setVisible( true );
2045         //
2046         AsciiHistogram histo = null;
2047         if ( stats.getMin() < stats.getMin() ) {
2048             histo = new AsciiHistogram( stats, histogram_title );
2049         }
2050         if ( verbose ) {
2051             if ( histo != null ) {
2052                 System.out.println( histo.toStringBuffer( 20, '|', 40, 5 ) );
2053             }
2054             System.out.println();
2055             System.out.println( "N                   : " + stats.getN() );
2056             System.out.println( "Min                 : " + stats.getMin() );
2057             System.out.println( "Max                 : " + stats.getMax() );
2058             System.out.println( "Mean                : " + stats.arithmeticMean() );
2059             if ( stats.getN() > 1 ) {
2060                 System.out.println( "SD                  : " + stats.sampleStandardDeviation() );
2061             }
2062             else {
2063                 System.out.println( "SD                  : n/a" );
2064             }
2065             System.out.println( "Median              : " + stats.median() );
2066             if ( stats.getN() > 1 ) {
2067                 System.out.println( "Pearsonian skewness : " + stats.pearsonianSkewness() );
2068             }
2069             else {
2070                 System.out.println( "Pearsonian skewness : n/a" );
2071             }
2072         }
2073         switch ( print_option ) {
2074             case SIMPLE_TAB_DELIMITED:
2075                 break;
2076             case HTML:
2077                 w.write( "<html>" );
2078                 w.write( SurfacingConstants.NL );
2079                 addHtmlHead( w, "SURFACING :: " + html_title );
2080                 w.write( SurfacingConstants.NL );
2081                 w.write( "<body>" );
2082                 w.write( SurfacingConstants.NL );
2083                 w.write( html_desc.toString() );
2084                 w.write( SurfacingConstants.NL );
2085                 w.write( "<hr>" );
2086                 w.write( "<br>" );
2087                 w.write( SurfacingConstants.NL );
2088                 w.write( "<tt><pre>" );
2089                 w.write( SurfacingConstants.NL );
2090                 if ( histo != null ) {
2091                     w.write( histo.toStringBuffer( 20, '|', 40, 5 ).toString() );
2092                     w.write( SurfacingConstants.NL );
2093                 }
2094                 w.write( "</pre></tt>" );
2095                 w.write( SurfacingConstants.NL );
2096                 w.write( "<table>" );
2097                 w.write( SurfacingConstants.NL );
2098                 w.write( "<tr><td>N: </td><td>" + stats.getN() + "</td></tr>" );
2099                 w.write( SurfacingConstants.NL );
2100                 w.write( "<tr><td>Min: </td><td>" + stats.getMin() + "</td></tr>" );
2101                 w.write( SurfacingConstants.NL );
2102                 w.write( "<tr><td>Max: </td><td>" + stats.getMax() + "</td></tr>" );
2103                 w.write( SurfacingConstants.NL );
2104                 w.write( "<tr><td>Mean: </td><td>" + stats.arithmeticMean() + "</td></tr>" );
2105                 w.write( SurfacingConstants.NL );
2106                 if ( stats.getN() > 1 ) {
2107                     w.write( "<tr><td>SD: </td><td>" + stats.sampleStandardDeviation() + "</td></tr>" );
2108                 }
2109                 else {
2110                     w.write( "<tr><td>SD: </td><td>n/a</td></tr>" );
2111                 }
2112                 w.write( SurfacingConstants.NL );
2113                 w.write( "<tr><td>Median: </td><td>" + stats.median() + "</td></tr>" );
2114                 w.write( SurfacingConstants.NL );
2115                 if ( stats.getN() > 1 ) {
2116                     w.write( "<tr><td>Pearsonian skewness: </td><td>" + stats.pearsonianSkewness() + "</td></tr>" );
2117                 }
2118                 else {
2119                     w.write( "<tr><td>Pearsonian skewness: </td><td>n/a</td></tr>" );
2120                 }
2121                 w.write( SurfacingConstants.NL );
2122                 w.write( "</table>" );
2123                 w.write( SurfacingConstants.NL );
2124                 w.write( "<br>" );
2125                 w.write( SurfacingConstants.NL );
2126                 w.write( "<hr>" );
2127                 w.write( SurfacingConstants.NL );
2128                 w.write( "<br>" );
2129                 w.write( SurfacingConstants.NL );
2130                 w.write( "<table>" );
2131                 w.write( SurfacingConstants.NL );
2132                 break;
2133         }
2134         w.write( SurfacingConstants.NL );
2135         for( final DomainSimilarity similarity : similarities ) {
2136             if ( ( species_order != null ) && !species_order.isEmpty() ) {
2137                 ( ( PrintableDomainSimilarity ) similarity ).setSpeciesOrder( species_order );
2138             }
2139             w.write( similarity.toStringBuffer( print_option ).toString() );
2140             w.write( SurfacingConstants.NL );
2141         }
2142         switch ( print_option ) {
2143             case HTML:
2144                 w.write( SurfacingConstants.NL );
2145                 w.write( "</table>" );
2146                 w.write( SurfacingConstants.NL );
2147                 w.write( "</font>" );
2148                 w.write( SurfacingConstants.NL );
2149                 w.write( "</body>" );
2150                 w.write( SurfacingConstants.NL );
2151                 w.write( "</html>" );
2152                 w.write( SurfacingConstants.NL );
2153                 break;
2154         }
2155         w.flush();
2156         w.close();
2157         return stats;
2158     }
2159
2160     private static void writeDomainsToIndividualFilePerTreeNode( final Writer individual_files_writer,
2161                                                                  final String domain_0,
2162                                                                  final String domain_1 ) throws IOException {
2163         individual_files_writer.write( domain_0 );
2164         individual_files_writer.write( ForesterUtil.LINE_SEPARATOR );
2165         if ( !ForesterUtil.isEmpty( domain_1 ) ) {
2166             individual_files_writer.write( domain_1 );
2167             individual_files_writer.write( ForesterUtil.LINE_SEPARATOR );
2168         }
2169     }
2170
2171     public static void writeMatrixToFile( final CharacterStateMatrix<?> matrix,
2172                                           final String filename,
2173                                           final Format format ) {
2174         final File outfile = new File( filename );
2175         checkForOutputFileWriteability( outfile );
2176         try {
2177             final BufferedWriter out = new BufferedWriter( new FileWriter( outfile ) );
2178             matrix.toWriter( out, format );
2179             out.flush();
2180             out.close();
2181         }
2182         catch ( final IOException e ) {
2183             ForesterUtil.fatalError( surfacing.PRG_NAME, e.getMessage() );
2184         }
2185         ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote matrix: \"" + filename + "\"" );
2186     }
2187
2188     public static void writeMatrixToFile( final File matrix_outfile, final List<DistanceMatrix> matrices ) {
2189         checkForOutputFileWriteability( matrix_outfile );
2190         try {
2191             final BufferedWriter out = new BufferedWriter( new FileWriter( matrix_outfile ) );
2192             for( final DistanceMatrix distance_matrix : matrices ) {
2193                 out.write( distance_matrix.toStringBuffer( DistanceMatrix.Format.PHYLIP ).toString() );
2194                 out.write( ForesterUtil.LINE_SEPARATOR );
2195                 out.flush();
2196             }
2197             out.close();
2198         }
2199         catch ( final IOException e ) {
2200             ForesterUtil.fatalError( surfacing.PRG_NAME, e.getMessage() );
2201         }
2202         ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote distance matrices to \"" + matrix_outfile + "\"" );
2203     }
2204
2205     private static void writePfamsToFile( final String outfile_name, final SortedSet<String> pfams ) {
2206         try {
2207             final Writer writer = new BufferedWriter( new FileWriter( new File( outfile_name ) ) );
2208             for( final String pfam : pfams ) {
2209                 writer.write( pfam );
2210                 writer.write( ForesterUtil.LINE_SEPARATOR );
2211             }
2212             writer.close();
2213             ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote " + pfams.size() + " pfams to [" + outfile_name
2214                     + "]" );
2215         }
2216         catch ( final IOException e ) {
2217             ForesterUtil.printWarningMessage( surfacing.PRG_NAME, "Failure to write: " + e );
2218         }
2219     }
2220
2221     public static void writePhylogenyToFile( final Phylogeny phylogeny, final String filename ) {
2222         final PhylogenyWriter writer = new PhylogenyWriter();
2223         try {
2224             writer.toPhyloXML( new File( filename ), phylogeny, 1 );
2225         }
2226         catch ( final IOException e ) {
2227             ForesterUtil.printWarningMessage( surfacing.PRG_NAME, "failed to write phylogeny to \"" + filename + "\": "
2228                     + e );
2229         }
2230         ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote phylogeny to \"" + filename + "\"" );
2231     }
2232
2233     public static void writeTaxonomyLinks( final Writer writer, final String species ) throws IOException {
2234         if ( ( species.length() > 1 ) && ( species.indexOf( '_' ) < 1 ) ) {
2235             final Matcher matcher = PATTERN_SP_STYLE_TAXONOMY.matcher( species );
2236             writer.write( " [" );
2237             if ( matcher.matches() ) {
2238                 writer.write( "<a href=\"" + SurfacingConstants.UNIPROT_LINK + species
2239                         + "\" target=\"taxonomy_window\">uniprot</a>" );
2240             }
2241             else {
2242                 writer.write( "<a href=\"" + SurfacingConstants.EOL_LINK + species
2243                         + "\" target=\"taxonomy_window\">eol</a>" );
2244                 writer.write( "|" );
2245                 writer.write( "<a href=\"" + SurfacingConstants.TOL_LINK + species
2246                         + "\" target=\"taxonomy_window\">tol</a>" );
2247             }
2248             writer.write( "]" );
2249         }
2250     }
2251
2252     private static void writeToNexus( final String outfile_name,
2253                                       final CharacterStateMatrix<BinaryStates> matrix,
2254                                       final Phylogeny phylogeny ) {
2255         if ( !( matrix instanceof BasicCharacterStateMatrix ) ) {
2256             throw new IllegalArgumentException( "can only write matrices of type [" + BasicCharacterStateMatrix.class
2257                     + "] to nexus" );
2258         }
2259         final BasicCharacterStateMatrix<BinaryStates> my_matrix = ( org.forester.evoinference.matrix.character.BasicCharacterStateMatrix<BinaryStates> ) matrix;
2260         final List<Phylogeny> phylogenies = new ArrayList<Phylogeny>( 1 );
2261         phylogenies.add( phylogeny );
2262         try {
2263             final BufferedWriter w = new BufferedWriter( new FileWriter( outfile_name ) );
2264             w.write( NexusConstants.NEXUS );
2265             w.write( ForesterUtil.LINE_SEPARATOR );
2266             my_matrix.writeNexusTaxaBlock( w );
2267             my_matrix.writeNexusBinaryChractersBlock( w );
2268             PhylogenyWriter.writeNexusTreesBlock( w, phylogenies );
2269             w.flush();
2270             w.close();
2271             ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote Nexus file: \"" + outfile_name + "\"" );
2272         }
2273         catch ( final IOException e ) {
2274             ForesterUtil.fatalError( surfacing.PRG_NAME, e.getMessage() );
2275         }
2276     }
2277
2278     private static void writeToNexus( final String outfile_name,
2279                                       final DomainParsimonyCalculator domain_parsimony,
2280                                       final Phylogeny phylogeny ) {
2281         writeToNexus( outfile_name + surfacing.NEXUS_EXTERNAL_DOMAINS,
2282                       domain_parsimony.createMatrixOfDomainPresenceOrAbsence(),
2283                       phylogeny );
2284         writeToNexus( outfile_name + surfacing.NEXUS_EXTERNAL_DOMAIN_COMBINATIONS,
2285                       domain_parsimony.createMatrixOfBinaryDomainCombinationPresenceOrAbsence(),
2286                       phylogeny );
2287     }
2288
2289     public static void domainsPerProteinsStatistics( final String genome,
2290                                                      final List<Protein> protein_list,
2291                                                      final DescriptiveStatistics all_genomes_domains_per_potein_stats,
2292                                                      final SortedMap<Integer, Integer> all_genomes_domains_per_potein_histo,
2293                                                      final SortedSet<String> domains_which_are_always_single,
2294                                                      final SortedSet<String> domains_which_are_sometimes_single_sometimes_not,
2295                                                      final SortedSet<String> domains_which_never_single,
2296                                                      final Writer writer ) {
2297         final DescriptiveStatistics stats = new BasicDescriptiveStatistics();
2298         for( final Protein protein : protein_list ) {
2299             final int domains = protein.getNumberOfProteinDomains();
2300             //System.out.println( domains );
2301             stats.addValue( domains );
2302             all_genomes_domains_per_potein_stats.addValue( domains );
2303             if ( !all_genomes_domains_per_potein_histo.containsKey( domains ) ) {
2304                 all_genomes_domains_per_potein_histo.put( domains, 1 );
2305             }
2306             else {
2307                 all_genomes_domains_per_potein_histo.put( domains,
2308                                                           1 + all_genomes_domains_per_potein_histo.get( domains ) );
2309             }
2310             if ( domains == 1 ) {
2311                 final String domain = protein.getProteinDomain( 0 ).getDomainId().getId();
2312                 if ( !domains_which_are_sometimes_single_sometimes_not.contains( domain ) ) {
2313                     if ( domains_which_never_single.contains( domain ) ) {
2314                         domains_which_never_single.remove( domain );
2315                         domains_which_are_sometimes_single_sometimes_not.add( domain );
2316                     }
2317                     else {
2318                         domains_which_are_always_single.add( domain );
2319                     }
2320                 }
2321             }
2322             else if ( domains > 1 ) {
2323                 for( final Domain d : protein.getProteinDomains() ) {
2324                     final String domain = d.getDomainId().getId();
2325                     // System.out.println( domain );
2326                     if ( !domains_which_are_sometimes_single_sometimes_not.contains( domain ) ) {
2327                         if ( domains_which_are_always_single.contains( domain ) ) {
2328                             domains_which_are_always_single.remove( domain );
2329                             domains_which_are_sometimes_single_sometimes_not.add( domain );
2330                         }
2331                         else {
2332                             domains_which_never_single.add( domain );
2333                         }
2334                     }
2335                 }
2336             }
2337         }
2338         try {
2339             writer.write( genome );
2340             writer.write( "\t" );
2341             writer.write( stats.arithmeticMean() + "" );
2342             writer.write( "\t" );
2343             writer.write( stats.sampleStandardDeviation() + "" );
2344             writer.write( "\t" );
2345             writer.write( stats.median() + "" );
2346             writer.write( "\t" );
2347             writer.write( stats.getN() + "" );
2348             writer.write( "\t" );
2349             writer.write( stats.getMin() + "" );
2350             writer.write( "\t" );
2351             writer.write( stats.getMax() + "" );
2352             writer.write( "\n" );
2353         }
2354         catch ( final IOException e ) {
2355             e.printStackTrace();
2356         }
2357     }
2358 }