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