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