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