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