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