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