in progress
[jalview.git] / forester / java / src / org / forester / surfacing / SurfacingUtil.java
1 // $Id:
2 //
3 // FORESTER -- software libraries and applications
4 // for evolutionary biology research and applications.
5 //
6 // Copyright (C) 2008-2009 Christian M. Zmasek
7 // Copyright (C) 2008-2009 Burnham Institute for Medical Research
8 // All rights reserved
9 //
10 // This library is free software; you can redistribute it and/or
11 // modify it under the terms of the GNU Lesser General Public
12 // License as published by the Free Software Foundation; either
13 // version 2.1 of the License, or (at your option) any later version.
14 //
15 // This library is distributed in the hope that it will be useful,
16 // but WITHOUT ANY WARRANTY; without even the implied warranty of
17 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
18 // Lesser General Public License for more details.
19 //
20 // You should have received a copy of the GNU Lesser General Public
21 // License along with this library; if not, write to the Free Software
22 // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
23 //
24 // Contact: phylosoft @ gmail . com
25 // WWW: www.phylosoft.org/forester
26
27 package org.forester.surfacing;
28
29 import java.io.BufferedWriter;
30 import java.io.File;
31 import java.io.FileWriter;
32 import java.io.IOException;
33 import java.io.Writer;
34 import java.text.DecimalFormat;
35 import java.text.NumberFormat;
36 import java.util.ArrayList;
37 import java.util.Arrays;
38 import java.util.Collections;
39 import java.util.Comparator;
40 import java.util.HashMap;
41 import java.util.HashSet;
42 import java.util.List;
43 import java.util.Map;
44 import java.util.Map.Entry;
45 import java.util.PriorityQueue;
46 import java.util.Set;
47 import java.util.SortedMap;
48 import java.util.SortedSet;
49 import java.util.TreeMap;
50 import java.util.TreeSet;
51 import java.util.regex.Matcher;
52 import java.util.regex.Pattern;
53
54 import org.forester.application.surfacing;
55 import org.forester.evoinference.distance.NeighborJoining;
56 import org.forester.evoinference.matrix.character.BasicCharacterStateMatrix;
57 import org.forester.evoinference.matrix.character.CharacterStateMatrix;
58 import org.forester.evoinference.matrix.character.CharacterStateMatrix.BinaryStates;
59 import org.forester.evoinference.matrix.character.CharacterStateMatrix.Format;
60 import org.forester.evoinference.matrix.character.CharacterStateMatrix.GainLossStates;
61 import org.forester.evoinference.matrix.distance.BasicSymmetricalDistanceMatrix;
62 import org.forester.evoinference.matrix.distance.DistanceMatrix;
63 import org.forester.go.GoId;
64 import org.forester.go.GoNameSpace;
65 import org.forester.go.GoTerm;
66 import org.forester.go.PfamToGoMapping;
67 import org.forester.io.parsers.nexus.NexusConstants;
68 import org.forester.io.writers.PhylogenyWriter;
69 import org.forester.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                         out.write( protein.getSpecies().getSpeciesId() );
1196                         out.write( separator );
1197                         out.write( protein.getProteinId().getId() );
1198                         out.write( separator );
1199                         out.write( domain_id.toString() );
1200                         out.write( separator );
1201                         for( final Domain domain : domains ) {
1202                             out.write( "/" );
1203                             out.write( domain.getFrom() + "-" + domain.getTo() );
1204                         }
1205                         out.write( "/" );
1206                         out.write( separator );
1207                         out.write( "{" );
1208                         boolean first = true;
1209                         for( final Domain domain : protein.getProteinDomains() ) {
1210                             if ( first ) {
1211                                 first = false;
1212                             }
1213                             else {
1214                                 out.write( "," );
1215                             }
1216                             out.write( domain.getDomainId().toString() );
1217                         }
1218                         out.write( "}" );
1219                         if ( !( ForesterUtil.isEmpty( protein.getDescription() ) || protein.getDescription()
1220                                 .equals( SurfacingConstants.NONE ) ) ) {
1221                             out.write( protein.getDescription() );
1222                         }
1223                         out.write( separator );
1224                         if ( !( ForesterUtil.isEmpty( protein.getAccession() ) || protein.getAccession()
1225                                 .equals( SurfacingConstants.NONE ) ) ) {
1226                             out.write( protein.getAccession() );
1227                         }
1228                         out.write( SurfacingConstants.NL );
1229                     }
1230                 }
1231             }
1232         }
1233         out.flush();
1234     }
1235
1236     public static SortedSet<DomainId> getAllDomainIds( final List<GenomeWideCombinableDomains> gwcd_list ) {
1237         final SortedSet<DomainId> all_domains_ids = new TreeSet<DomainId>();
1238         for( final GenomeWideCombinableDomains gwcd : gwcd_list ) {
1239             final Set<DomainId> all_domains = gwcd.getAllDomainIds();
1240             //    for( final Domain domain : all_domains ) {
1241             all_domains_ids.addAll( all_domains );
1242             //    }
1243         }
1244         return all_domains_ids;
1245     }
1246
1247     public static SortedMap<String, Integer> getDomainCounts( final List<Protein> protein_domain_collections ) {
1248         final SortedMap<String, Integer> map = new TreeMap<String, Integer>();
1249         for( final Protein protein_domain_collection : protein_domain_collections ) {
1250             for( final Object name : protein_domain_collection.getProteinDomains() ) {
1251                 final BasicDomain protein_domain = ( BasicDomain ) name;
1252                 final String id = protein_domain.getDomainId().getId();
1253                 if ( map.containsKey( id ) ) {
1254                     map.put( id, map.get( id ) + 1 );
1255                 }
1256                 else {
1257                     map.put( id, 1 );
1258                 }
1259             }
1260         }
1261         return map;
1262     }
1263
1264     public static int getNumberOfNodesLackingName( final Phylogeny p, final StringBuilder names ) {
1265         final PhylogenyNodeIterator it = p.iteratorPostorder();
1266         int c = 0;
1267         while ( it.hasNext() ) {
1268             final PhylogenyNode n = it.next();
1269             if ( ForesterUtil.isEmpty( n.getName() )
1270                     && ( !n.getNodeData().isHasTaxonomy() || ForesterUtil.isEmpty( n.getNodeData().getTaxonomy()
1271                             .getScientificName() ) )
1272                     && ( !n.getNodeData().isHasTaxonomy() || ForesterUtil.isEmpty( n.getNodeData().getTaxonomy()
1273                             .getCommonName() ) ) ) {
1274                 if ( n.getParent() != null ) {
1275                     names.append( " " );
1276                     names.append( n.getParent().getName() );
1277                 }
1278                 final List l = n.getAllExternalDescendants();
1279                 for( final Object object : l ) {
1280                     System.out.println( l.toString() );
1281                 }
1282                 ++c;
1283             }
1284         }
1285         return c;
1286     }
1287
1288     /**
1289      * Returns true is Domain domain falls in an uninterrupted stretch of
1290      * covered positions.
1291      * 
1292      * @param domain
1293      * @param covered_positions
1294      * @return
1295      */
1296     public static boolean isEngulfed( final Domain domain, final List<Boolean> covered_positions ) {
1297         for( int i = domain.getFrom(); i <= domain.getTo(); ++i ) {
1298             if ( ( i >= covered_positions.size() ) || ( covered_positions.get( i ) != true ) ) {
1299                 return false;
1300             }
1301         }
1302         return true;
1303     }
1304
1305     public static void preparePhylogeny( final Phylogeny p,
1306                                          final DomainParsimonyCalculator domain_parsimony,
1307                                          final String date_time,
1308                                          final String method,
1309                                          final String name,
1310                                          final String parameters_str ) {
1311         domain_parsimony.decoratePhylogenyWithDomains( p );
1312         final StringBuilder desc = new StringBuilder();
1313         desc.append( "[Method: " + method + "] [Date: " + date_time + "] " );
1314         desc.append( "[Cost: " + domain_parsimony.getCost() + "] " );
1315         desc.append( "[Gains: " + domain_parsimony.getTotalGains() + "] " );
1316         desc.append( "[Losses: " + domain_parsimony.getTotalLosses() + "] " );
1317         desc.append( "[Unchanged: " + domain_parsimony.getTotalUnchanged() + "] " );
1318         desc.append( "[Parameters: " + parameters_str + "]" );
1319         p.setName( name );
1320         p.setDescription( desc.toString() );
1321         p.setConfidence( new Confidence( domain_parsimony.getCost(), "parsimony" ) );
1322         p.setRerootable( false );
1323         p.setRooted( true );
1324     }
1325
1326     /*
1327      * species | protein id | n-terminal domain | c-terminal domain | n-terminal domain per domain E-value | c-terminal domain per domain E-value
1328      * 
1329      * 
1330      */
1331     static public StringBuffer proteinToDomainCombinations( final Protein protein,
1332                                                             final String protein_id,
1333                                                             final String separator ) {
1334         final StringBuffer sb = new StringBuffer();
1335         if ( protein.getSpecies() == null ) {
1336             throw new IllegalArgumentException( "species must not be null" );
1337         }
1338         if ( ForesterUtil.isEmpty( protein.getSpecies().getSpeciesId() ) ) {
1339             throw new IllegalArgumentException( "species id must not be empty" );
1340         }
1341         final List<Domain> domains = protein.getProteinDomains();
1342         if ( domains.size() > 1 ) {
1343             final Map<String, Integer> counts = new HashMap<String, Integer>();
1344             for( final Domain domain : domains ) {
1345                 final String id = domain.getDomainId().getId();
1346                 if ( counts.containsKey( id ) ) {
1347                     counts.put( id, counts.get( id ) + 1 );
1348                 }
1349                 else {
1350                     counts.put( id, 1 );
1351                 }
1352             }
1353             final Set<String> dcs = new HashSet<String>();
1354             for( int i = 1; i < domains.size(); ++i ) {
1355                 for( int j = 0; j < i; ++j ) {
1356                     Domain domain_n = domains.get( i );
1357                     Domain domain_c = domains.get( j );
1358                     if ( domain_n.getFrom() > domain_c.getFrom() ) {
1359                         domain_n = domains.get( j );
1360                         domain_c = domains.get( i );
1361                     }
1362                     final String dc = domain_n.getDomainId().getId() + domain_c.getDomainId().getId();
1363                     if ( !dcs.contains( dc ) ) {
1364                         dcs.add( dc );
1365                         sb.append( protein.getSpecies() );
1366                         sb.append( separator );
1367                         sb.append( protein_id );
1368                         sb.append( separator );
1369                         sb.append( domain_n.getDomainId().getId() );
1370                         sb.append( separator );
1371                         sb.append( domain_c.getDomainId().getId() );
1372                         sb.append( separator );
1373                         sb.append( domain_n.getPerDomainEvalue() );
1374                         sb.append( separator );
1375                         sb.append( domain_c.getPerDomainEvalue() );
1376                         sb.append( separator );
1377                         sb.append( counts.get( domain_n.getDomainId().getId() ) );
1378                         sb.append( separator );
1379                         sb.append( counts.get( domain_c.getDomainId().getId() ) );
1380                         sb.append( ForesterUtil.LINE_SEPARATOR );
1381                     }
1382                 }
1383             }
1384         }
1385         else if ( domains.size() == 1 ) {
1386             sb.append( protein.getSpecies() );
1387             sb.append( separator );
1388             sb.append( protein_id );
1389             sb.append( separator );
1390             sb.append( domains.get( 0 ).getDomainId().getId() );
1391             sb.append( separator );
1392             sb.append( separator );
1393             sb.append( domains.get( 0 ).getPerDomainEvalue() );
1394             sb.append( separator );
1395             sb.append( separator );
1396             sb.append( 1 );
1397             sb.append( separator );
1398             sb.append( ForesterUtil.LINE_SEPARATOR );
1399         }
1400         else {
1401             sb.append( protein.getSpecies() );
1402             sb.append( separator );
1403             sb.append( protein_id );
1404             sb.append( separator );
1405             sb.append( separator );
1406             sb.append( separator );
1407             sb.append( separator );
1408             sb.append( separator );
1409             sb.append( separator );
1410             sb.append( ForesterUtil.LINE_SEPARATOR );
1411         }
1412         return sb;
1413     }
1414
1415     /**
1416      * 
1417      * Example regarding engulfment: ------------0.1 ----------0.2 --0.3 =>
1418      * domain with 0.3 is ignored
1419      * 
1420      * -----------0.1 ----------0.2 --0.3 => domain with 0.3 is ignored
1421      * 
1422      * 
1423      * ------------0.1 ----------0.3 --0.2 => domains with 0.3 and 0.2 are _not_
1424      * ignored
1425      * 
1426      * @param max_allowed_overlap
1427      *            maximal allowed overlap (inclusive) to be still considered not
1428      *            overlapping (zero or negative value to allow any overlap)
1429      * @param remove_engulfed_domains
1430      *            to remove domains which are completely engulfed by coverage of
1431      *            domains with better support
1432      * @param protein
1433      * @return
1434      */
1435     public static Protein removeOverlappingDomains( final int max_allowed_overlap,
1436                                                     final boolean remove_engulfed_domains,
1437                                                     final Protein protein ) {
1438         final Protein pruned_protein = new BasicProtein( protein.getProteinId().getId(), protein.getSpecies()
1439                 .getSpeciesId(), protein.getLength() );
1440         final List<Domain> sorted = SurfacingUtil.sortDomainsWithAscendingConfidenceValues( protein );
1441         final List<Boolean> covered_positions = new ArrayList<Boolean>();
1442         for( final Domain domain : sorted ) {
1443             if ( ( ( max_allowed_overlap < 0 ) || ( SurfacingUtil.calculateOverlap( domain, covered_positions ) <= max_allowed_overlap ) )
1444                     && ( !remove_engulfed_domains || !isEngulfed( domain, covered_positions ) ) ) {
1445                 final int covered_positions_size = covered_positions.size();
1446                 for( int i = covered_positions_size; i < domain.getFrom(); ++i ) {
1447                     covered_positions.add( false );
1448                 }
1449                 final int new_covered_positions_size = covered_positions.size();
1450                 for( int i = domain.getFrom(); i <= domain.getTo(); ++i ) {
1451                     if ( i < new_covered_positions_size ) {
1452                         covered_positions.set( i, true );
1453                     }
1454                     else {
1455                         covered_positions.add( true );
1456                     }
1457                 }
1458                 pruned_protein.addProteinDomain( domain );
1459             }
1460         }
1461         return pruned_protein;
1462     }
1463
1464     public static List<Domain> sortDomainsWithAscendingConfidenceValues( final Protein protein ) {
1465         final List<Domain> domains = new ArrayList<Domain>();
1466         for( final Domain d : protein.getProteinDomains() ) {
1467             domains.add( d );
1468         }
1469         Collections.sort( domains, SurfacingUtil.ASCENDING_CONFIDENCE_VALUE_ORDER );
1470         return domains;
1471     }
1472
1473     private static List<String> splitDomainCombination( final String dc ) {
1474         final String[] s = dc.split( "=" );
1475         if ( s.length != 2 ) {
1476             ForesterUtil.printErrorMessage( surfacing.PRG_NAME, "Stringyfied domain combination has illegal format: "
1477                     + dc );
1478             System.exit( -1 );
1479         }
1480         final List<String> l = new ArrayList<String>( 2 );
1481         l.add( s[ 0 ] );
1482         l.add( s[ 1 ] );
1483         return l;
1484     }
1485
1486     public static void writeAllDomainsChangedOnAllSubtrees( final Phylogeny p,
1487                                                             final boolean get_gains,
1488                                                             final String outdir,
1489                                                             final String suffix_for_filename ) throws IOException {
1490         CharacterStateMatrix.GainLossStates state = CharacterStateMatrix.GainLossStates.GAIN;
1491         if ( !get_gains ) {
1492             state = CharacterStateMatrix.GainLossStates.LOSS;
1493         }
1494         final File base_dir = createBaseDirForPerNodeDomainFiles( surfacing.BASE_DIRECTORY_PER_SUBTREE_DOMAIN_GAIN_LOSS_FILES,
1495                                                                   false,
1496                                                                   state,
1497                                                                   outdir );
1498         for( final PhylogenyNodeIterator it = p.iteratorPostorder(); it.hasNext(); ) {
1499             final PhylogenyNode node = it.next();
1500             if ( !node.isExternal() ) {
1501                 final SortedSet<String> domains = collectAllDomainsChangedOnSubtree( node, get_gains );
1502                 if ( domains.size() > 0 ) {
1503                     final Writer writer = ForesterUtil.createBufferedWriter( base_dir + ForesterUtil.FILE_SEPARATOR
1504                             + node.getName() + suffix_for_filename );
1505                     for( final String domain : domains ) {
1506                         writer.write( domain );
1507                         writer.write( ForesterUtil.LINE_SEPARATOR );
1508                     }
1509                     writer.close();
1510                 }
1511             }
1512         }
1513     }
1514
1515     private static void writeAllEncounteredPfamsToFile( final Map<DomainId, List<GoId>> domain_id_to_go_ids_map,
1516                                                         final Map<GoId, GoTerm> go_id_to_term_map,
1517                                                         final String outfile_name,
1518                                                         final SortedSet<String> all_pfams_encountered ) {
1519         final File all_pfams_encountered_file = new File( outfile_name + surfacing.ALL_PFAMS_ENCOUNTERED_SUFFIX );
1520         final File all_pfams_encountered_with_go_annotation_file = new File( outfile_name
1521                 + surfacing.ALL_PFAMS_ENCOUNTERED_WITH_GO_ANNOTATION_SUFFIX );
1522         final File encountered_pfams_summary_file = new File( outfile_name + surfacing.ENCOUNTERED_PFAMS_SUMMARY_SUFFIX );
1523         int biological_process_counter = 0;
1524         int cellular_component_counter = 0;
1525         int molecular_function_counter = 0;
1526         int pfams_with_mappings_counter = 0;
1527         int pfams_without_mappings_counter = 0;
1528         int pfams_without_mappings_to_bp_or_mf_counter = 0;
1529         int pfams_with_mappings_to_bp_or_mf_counter = 0;
1530         try {
1531             final Writer all_pfams_encountered_writer = new BufferedWriter( new FileWriter( all_pfams_encountered_file ) );
1532             final Writer all_pfams_encountered_with_go_annotation_writer = new BufferedWriter( new FileWriter( all_pfams_encountered_with_go_annotation_file ) );
1533             final Writer summary_writer = new BufferedWriter( new FileWriter( encountered_pfams_summary_file ) );
1534             summary_writer.write( "# Pfam to GO mapping summary" );
1535             summary_writer.write( ForesterUtil.LINE_SEPARATOR );
1536             summary_writer.write( "# Actual summary is at the end of this file." );
1537             summary_writer.write( ForesterUtil.LINE_SEPARATOR );
1538             summary_writer.write( "# Encountered Pfams without a GO mapping:" );
1539             summary_writer.write( ForesterUtil.LINE_SEPARATOR );
1540             for( final String pfam : all_pfams_encountered ) {
1541                 all_pfams_encountered_writer.write( pfam );
1542                 all_pfams_encountered_writer.write( ForesterUtil.LINE_SEPARATOR );
1543                 final DomainId domain_id = new DomainId( pfam );
1544                 if ( domain_id_to_go_ids_map.containsKey( domain_id ) ) {
1545                     ++pfams_with_mappings_counter;
1546                     all_pfams_encountered_with_go_annotation_writer.write( pfam );
1547                     all_pfams_encountered_with_go_annotation_writer.write( ForesterUtil.LINE_SEPARATOR );
1548                     final List<GoId> go_ids = domain_id_to_go_ids_map.get( domain_id );
1549                     boolean maps_to_bp = false;
1550                     boolean maps_to_cc = false;
1551                     boolean maps_to_mf = false;
1552                     for( final GoId go_id : go_ids ) {
1553                         final GoTerm go_term = go_id_to_term_map.get( go_id );
1554                         if ( go_term.getGoNameSpace().isBiologicalProcess() ) {
1555                             maps_to_bp = true;
1556                         }
1557                         else if ( go_term.getGoNameSpace().isCellularComponent() ) {
1558                             maps_to_cc = true;
1559                         }
1560                         else if ( go_term.getGoNameSpace().isMolecularFunction() ) {
1561                             maps_to_mf = true;
1562                         }
1563                     }
1564                     if ( maps_to_bp ) {
1565                         ++biological_process_counter;
1566                     }
1567                     if ( maps_to_cc ) {
1568                         ++cellular_component_counter;
1569                     }
1570                     if ( maps_to_mf ) {
1571                         ++molecular_function_counter;
1572                     }
1573                     if ( maps_to_bp || maps_to_mf ) {
1574                         ++pfams_with_mappings_to_bp_or_mf_counter;
1575                     }
1576                     else {
1577                         ++pfams_without_mappings_to_bp_or_mf_counter;
1578                     }
1579                 }
1580                 else {
1581                     ++pfams_without_mappings_to_bp_or_mf_counter;
1582                     ++pfams_without_mappings_counter;
1583                     summary_writer.write( pfam );
1584                     summary_writer.write( ForesterUtil.LINE_SEPARATOR );
1585                 }
1586             }
1587             all_pfams_encountered_writer.close();
1588             all_pfams_encountered_with_go_annotation_writer.close();
1589             ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote all [" + all_pfams_encountered.size()
1590                     + "] encountered Pfams to: \"" + all_pfams_encountered_file + "\"" );
1591             ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote all [" + pfams_with_mappings_counter
1592                     + "] encountered Pfams with GO mappings to: \"" + all_pfams_encountered_with_go_annotation_file
1593                     + "\"" );
1594             ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote summary (including all ["
1595                     + pfams_without_mappings_counter + "] encountered Pfams without GO mappings) to: \""
1596                     + encountered_pfams_summary_file + "\"" );
1597             ForesterUtil.programMessage( surfacing.PRG_NAME, "Sum of Pfams encountered                : "
1598                     + all_pfams_encountered.size() );
1599             ForesterUtil.programMessage( surfacing.PRG_NAME, "Pfams without a mapping                 : "
1600                     + pfams_without_mappings_counter + " ["
1601                     + ( 100 * pfams_without_mappings_counter / all_pfams_encountered.size() ) + "%]" );
1602             ForesterUtil.programMessage( surfacing.PRG_NAME, "Pfams without mapping to proc. or func. : "
1603                     + pfams_without_mappings_to_bp_or_mf_counter + " ["
1604                     + ( 100 * pfams_without_mappings_to_bp_or_mf_counter / all_pfams_encountered.size() ) + "%]" );
1605             ForesterUtil.programMessage( surfacing.PRG_NAME,
1606                                          "Pfams with a mapping                    : " + pfams_with_mappings_counter
1607                                                  + " ["
1608                                                  + ( 100 * pfams_with_mappings_counter / all_pfams_encountered.size() )
1609                                                  + "%]" );
1610             ForesterUtil.programMessage( surfacing.PRG_NAME, "Pfams with a mapping to proc. or func.  : "
1611                     + pfams_with_mappings_to_bp_or_mf_counter + " ["
1612                     + ( 100 * pfams_with_mappings_to_bp_or_mf_counter / all_pfams_encountered.size() ) + "%]" );
1613             ForesterUtil.programMessage( surfacing.PRG_NAME,
1614                                          "Pfams with mapping to biological process: " + biological_process_counter
1615                                                  + " ["
1616                                                  + ( 100 * biological_process_counter / all_pfams_encountered.size() )
1617                                                  + "%]" );
1618             ForesterUtil.programMessage( surfacing.PRG_NAME,
1619                                          "Pfams with mapping to molecular function: " + molecular_function_counter
1620                                                  + " ["
1621                                                  + ( 100 * molecular_function_counter / all_pfams_encountered.size() )
1622                                                  + "%]" );
1623             ForesterUtil.programMessage( surfacing.PRG_NAME,
1624                                          "Pfams with mapping to cellular component: " + cellular_component_counter
1625                                                  + " ["
1626                                                  + ( 100 * cellular_component_counter / all_pfams_encountered.size() )
1627                                                  + "%]" );
1628             summary_writer.write( ForesterUtil.LINE_SEPARATOR );
1629             summary_writer.write( "# Sum of Pfams encountered                : " + all_pfams_encountered.size() );
1630             summary_writer.write( ForesterUtil.LINE_SEPARATOR );
1631             summary_writer.write( "# Pfams without a mapping                 : " + pfams_without_mappings_counter
1632                     + " [" + ( 100 * pfams_without_mappings_counter / all_pfams_encountered.size() ) + "%]" );
1633             summary_writer.write( ForesterUtil.LINE_SEPARATOR );
1634             summary_writer.write( "# Pfams without mapping to proc. or func. : "
1635                     + pfams_without_mappings_to_bp_or_mf_counter + " ["
1636                     + ( 100 * pfams_without_mappings_to_bp_or_mf_counter / all_pfams_encountered.size() ) + "%]" );
1637             summary_writer.write( ForesterUtil.LINE_SEPARATOR );
1638             summary_writer.write( "# Pfams with a mapping                    : " + pfams_with_mappings_counter + " ["
1639                     + ( 100 * pfams_with_mappings_counter / all_pfams_encountered.size() ) + "%]" );
1640             summary_writer.write( ForesterUtil.LINE_SEPARATOR );
1641             summary_writer.write( "# Pfams with a mapping to proc. or func.  : "
1642                     + pfams_with_mappings_to_bp_or_mf_counter + " ["
1643                     + ( 100 * pfams_with_mappings_to_bp_or_mf_counter / all_pfams_encountered.size() ) + "%]" );
1644             summary_writer.write( ForesterUtil.LINE_SEPARATOR );
1645             summary_writer.write( "# Pfams with mapping to biological process: " + biological_process_counter + " ["
1646                     + ( 100 * biological_process_counter / all_pfams_encountered.size() ) + "%]" );
1647             summary_writer.write( ForesterUtil.LINE_SEPARATOR );
1648             summary_writer.write( "# Pfams with mapping to molecular function: " + molecular_function_counter + " ["
1649                     + ( 100 * molecular_function_counter / all_pfams_encountered.size() ) + "%]" );
1650             summary_writer.write( ForesterUtil.LINE_SEPARATOR );
1651             summary_writer.write( "# Pfams with mapping to cellular component: " + cellular_component_counter + " ["
1652                     + ( 100 * cellular_component_counter / all_pfams_encountered.size() ) + "%]" );
1653             summary_writer.write( ForesterUtil.LINE_SEPARATOR );
1654             summary_writer.close();
1655         }
1656         catch ( final IOException e ) {
1657             ForesterUtil.printWarningMessage( surfacing.PRG_NAME, "Failure to write: " + e );
1658         }
1659     }
1660
1661     public static void writeBinaryDomainCombinationsFileForGraphAnalysis( final String[][] input_file_properties,
1662                                                                           final File output_dir,
1663                                                                           final GenomeWideCombinableDomains gwcd,
1664                                                                           final int i,
1665                                                                           final GenomeWideCombinableDomainsSortOrder dc_sort_order ) {
1666         File dc_outfile_dot = new File( input_file_properties[ i ][ 0 ]
1667                 + surfacing.DOMAIN_COMBINITONS_OUTPUTFILE_SUFFIX_FOR_GRAPH_ANALYSIS );
1668         if ( output_dir != null ) {
1669             dc_outfile_dot = new File( output_dir + ForesterUtil.FILE_SEPARATOR + dc_outfile_dot );
1670         }
1671         checkForOutputFileWriteability( dc_outfile_dot );
1672         final SortedSet<BinaryDomainCombination> binary_combinations = createSetOfAllBinaryDomainCombinationsPerGenome( gwcd );
1673         try {
1674             final BufferedWriter out_dot = new BufferedWriter( new FileWriter( dc_outfile_dot ) );
1675             for( final BinaryDomainCombination bdc : binary_combinations ) {
1676                 out_dot.write( bdc.toGraphDescribingLanguage( BinaryDomainCombination.OutputFormat.DOT, null, null )
1677                         .toString() );
1678                 out_dot.write( SurfacingConstants.NL );
1679             }
1680             out_dot.close();
1681         }
1682         catch ( final IOException e ) {
1683             ForesterUtil.fatalError( surfacing.PRG_NAME, e.getMessage() );
1684         }
1685         ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote binary domain combination for \""
1686                 + input_file_properties[ i ][ 0 ] + "\" (" + input_file_properties[ i ][ 1 ] + ", "
1687                 + input_file_properties[ i ][ 2 ] + ") to: \"" + dc_outfile_dot + "\"" );
1688     }
1689
1690     public static void writeBinaryStatesMatrixAsListToFile( final CharacterStateMatrix<CharacterStateMatrix.GainLossStates> matrix,
1691                                                             final CharacterStateMatrix.GainLossStates state,
1692                                                             final String filename,
1693                                                             final String indentifier_characters_separator,
1694                                                             final String character_separator,
1695                                                             final Map<String, String> descriptions ) {
1696         final File outfile = new File( filename );
1697         checkForOutputFileWriteability( outfile );
1698         final SortedSet<String> sorted_ids = new TreeSet<String>();
1699         for( int i = 0; i < matrix.getNumberOfIdentifiers(); ++i ) {
1700             sorted_ids.add( matrix.getIdentifier( i ) );
1701         }
1702         try {
1703             final BufferedWriter out = new BufferedWriter( new FileWriter( outfile ) );
1704             for( final String id : sorted_ids ) {
1705                 out.write( indentifier_characters_separator );
1706                 out.write( "#" + id );
1707                 out.write( indentifier_characters_separator );
1708                 for( int c = 0; c < matrix.getNumberOfCharacters(); ++c ) {
1709                     // Not nice:
1710                     // using null to indicate either UNCHANGED_PRESENT or GAIN.
1711                     if ( ( matrix.getState( id, c ) == state )
1712                             || ( ( state == null ) && ( ( matrix.getState( id, c ) == CharacterStateMatrix.GainLossStates.GAIN ) || ( matrix
1713                                     .getState( id, c ) == CharacterStateMatrix.GainLossStates.UNCHANGED_PRESENT ) ) ) ) {
1714                         out.write( matrix.getCharacter( c ) );
1715                         if ( ( descriptions != null ) && !descriptions.isEmpty()
1716                                 && descriptions.containsKey( matrix.getCharacter( c ) ) ) {
1717                             out.write( "\t" );
1718                             out.write( descriptions.get( matrix.getCharacter( c ) ) );
1719                         }
1720                         out.write( character_separator );
1721                     }
1722                 }
1723             }
1724             out.flush();
1725             out.close();
1726         }
1727         catch ( final IOException e ) {
1728             ForesterUtil.fatalError( surfacing.PRG_NAME, e.getMessage() );
1729         }
1730         ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote characters list: \"" + filename + "\"" );
1731     }
1732
1733     public static void writeBinaryStatesMatrixAsListToFileForBinaryCombinationsForGraphAnalysis( final CharacterStateMatrix<CharacterStateMatrix.GainLossStates> matrix,
1734                                                                                                  final CharacterStateMatrix.GainLossStates state,
1735                                                                                                  final String filename,
1736                                                                                                  final String indentifier_characters_separator,
1737                                                                                                  final String character_separator,
1738                                                                                                  final BinaryDomainCombination.OutputFormat bc_output_format ) {
1739         final File outfile = new File( filename );
1740         checkForOutputFileWriteability( outfile );
1741         final SortedSet<String> sorted_ids = new TreeSet<String>();
1742         for( int i = 0; i < matrix.getNumberOfIdentifiers(); ++i ) {
1743             sorted_ids.add( matrix.getIdentifier( i ) );
1744         }
1745         try {
1746             final BufferedWriter out = new BufferedWriter( new FileWriter( outfile ) );
1747             for( final String id : sorted_ids ) {
1748                 out.write( indentifier_characters_separator );
1749                 out.write( "#" + id );
1750                 out.write( indentifier_characters_separator );
1751                 for( int c = 0; c < matrix.getNumberOfCharacters(); ++c ) {
1752                     // Not nice:
1753                     // using null to indicate either UNCHANGED_PRESENT or GAIN.
1754                     if ( ( matrix.getState( id, c ) == state )
1755                             || ( ( state == null ) && ( ( matrix.getState( id, c ) == CharacterStateMatrix.GainLossStates.GAIN ) || ( matrix
1756                                     .getState( id, c ) == CharacterStateMatrix.GainLossStates.UNCHANGED_PRESENT ) ) ) ) {
1757                         BinaryDomainCombination bdc = null;
1758                         try {
1759                             bdc = BasicBinaryDomainCombination.createInstance( matrix.getCharacter( c ) );
1760                         }
1761                         catch ( final Exception e ) {
1762                             ForesterUtil.fatalError( surfacing.PRG_NAME, e.getLocalizedMessage() );
1763                         }
1764                         out.write( bdc.toGraphDescribingLanguage( bc_output_format, null, null ).toString() );
1765                         out.write( character_separator );
1766                     }
1767                 }
1768             }
1769             out.flush();
1770             out.close();
1771         }
1772         catch ( final IOException e ) {
1773             ForesterUtil.fatalError( surfacing.PRG_NAME, e.getMessage() );
1774         }
1775         ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote characters list: \"" + filename + "\"" );
1776     }
1777
1778     public static void writeBinaryStatesMatrixToList( final Map<DomainId, List<GoId>> domain_id_to_go_ids_map,
1779                                                       final Map<GoId, GoTerm> go_id_to_term_map,
1780                                                       final GoNameSpace go_namespace_limit,
1781                                                       final boolean domain_combinations,
1782                                                       final CharacterStateMatrix<CharacterStateMatrix.GainLossStates> matrix,
1783                                                       final CharacterStateMatrix.GainLossStates state,
1784                                                       final String filename,
1785                                                       final String indentifier_characters_separator,
1786                                                       final String character_separator,
1787                                                       final String title_for_html,
1788                                                       final String prefix_for_html,
1789                                                       final Map<DomainId, Set<String>>[] domain_id_to_secondary_features_maps,
1790                                                       final SortedSet<String> all_pfams_encountered,
1791                                                       final SortedSet<String> pfams_gained_or_lost,
1792                                                       final String suffix_for_per_node_events_file ) {
1793         if ( ( go_namespace_limit != null ) && ( ( go_id_to_term_map == null ) || ( go_id_to_term_map.size() < 1 ) ) ) {
1794             throw new IllegalArgumentException( "attempt to use GO namespace limit without a GO-id to term map" );
1795         }
1796         else if ( ( ( domain_id_to_go_ids_map == null ) || ( domain_id_to_go_ids_map.size() < 1 ) ) ) {
1797             throw new IllegalArgumentException( "attempt to output detailed HTML without a Pfam to GO map" );
1798         }
1799         else if ( ( ( go_id_to_term_map == null ) || ( go_id_to_term_map.size() < 1 ) ) ) {
1800             throw new IllegalArgumentException( "attempt to output detailed HTML without a GO-id to term map" );
1801         }
1802         final File outfile = new File( filename );
1803         checkForOutputFileWriteability( outfile );
1804         final SortedSet<String> sorted_ids = new TreeSet<String>();
1805         for( int i = 0; i < matrix.getNumberOfIdentifiers(); ++i ) {
1806             sorted_ids.add( matrix.getIdentifier( i ) );
1807         }
1808         try {
1809             final Writer out = new BufferedWriter( new FileWriter( outfile ) );
1810             final File per_node_go_mapped_domain_gain_loss_files_base_dir = createBaseDirForPerNodeDomainFiles( surfacing.BASE_DIRECTORY_PER_NODE_DOMAIN_GAIN_LOSS_FILES,
1811                                                                                                                 domain_combinations,
1812                                                                                                                 state,
1813                                                                                                                 filename );
1814             Writer per_node_go_mapped_domain_gain_loss_outfile_writer = null;
1815             File per_node_go_mapped_domain_gain_loss_outfile = null;
1816             int per_node_counter = 0;
1817             out.write( "<html>" );
1818             out.write( SurfacingConstants.NL );
1819             addHtmlHead( out, title_for_html );
1820             out.write( SurfacingConstants.NL );
1821             out.write( "<body>" );
1822             out.write( SurfacingConstants.NL );
1823             out.write( "<h1>" );
1824             out.write( SurfacingConstants.NL );
1825             out.write( title_for_html );
1826             out.write( SurfacingConstants.NL );
1827             out.write( "</h1>" );
1828             out.write( SurfacingConstants.NL );
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( "<tr>" );
1837                 out.write( "<td>" );
1838                 out.write( "<a href=\"#" + id + "\">" + id + "</a>" );
1839                 out.write( "</td>" );
1840                 out.write( "</tr>" );
1841                 out.write( SurfacingConstants.NL );
1842             }
1843             out.write( "</table>" );
1844             out.write( SurfacingConstants.NL );
1845             for( final String id : sorted_ids ) {
1846                 final Matcher matcher = PATTERN_SP_STYLE_TAXONOMY.matcher( id );
1847                 if ( matcher.matches() ) {
1848                     continue;
1849                 }
1850                 out.write( SurfacingConstants.NL );
1851                 out.write( "<h2>" );
1852                 out.write( "<a name=\"" + id + "\">" + id + "</a>" );
1853                 writeTaxonomyLinks( out, id );
1854                 out.write( "</h2>" );
1855                 out.write( SurfacingConstants.NL );
1856                 out.write( "<table>" );
1857                 out.write( SurfacingConstants.NL );
1858                 out.write( "<tr>" );
1859                 out.write( "<td><b>" );
1860                 out.write( "Pfam domain(s)" );
1861                 out.write( "</b></td><td><b>" );
1862                 out.write( "GO term acc" );
1863                 out.write( "</b></td><td><b>" );
1864                 out.write( "GO term" );
1865                 out.write( "</b></td><td><b>" );
1866                 out.write( "GO namespace" );
1867                 out.write( "</b></td>" );
1868                 out.write( "</tr>" );
1869                 out.write( SurfacingConstants.NL );
1870                 out.write( "</tr>" );
1871                 out.write( SurfacingConstants.NL );
1872                 per_node_counter = 0;
1873                 if ( matrix.getNumberOfCharacters() > 0 ) {
1874                     per_node_go_mapped_domain_gain_loss_outfile = new File( per_node_go_mapped_domain_gain_loss_files_base_dir
1875                             + ForesterUtil.FILE_SEPARATOR + id + suffix_for_per_node_events_file );
1876                     SurfacingUtil.checkForOutputFileWriteability( per_node_go_mapped_domain_gain_loss_outfile );
1877                     per_node_go_mapped_domain_gain_loss_outfile_writer = ForesterUtil
1878                             .createBufferedWriter( per_node_go_mapped_domain_gain_loss_outfile );
1879                 }
1880                 else {
1881                     per_node_go_mapped_domain_gain_loss_outfile = null;
1882                     per_node_go_mapped_domain_gain_loss_outfile_writer = null;
1883                 }
1884                 for( int c = 0; c < matrix.getNumberOfCharacters(); ++c ) {
1885                     // Not nice:
1886                     // using null to indicate either UNCHANGED_PRESENT or GAIN.
1887                     if ( ( matrix.getState( id, c ) == state )
1888                             || ( ( state == null ) && ( ( matrix.getState( id, c ) == CharacterStateMatrix.GainLossStates.UNCHANGED_PRESENT ) || ( matrix
1889                                     .getState( id, c ) == CharacterStateMatrix.GainLossStates.GAIN ) ) ) ) {
1890                         final String character = matrix.getCharacter( c );
1891                         String domain_0 = "";
1892                         String domain_1 = "";
1893                         if ( character.indexOf( BinaryDomainCombination.SEPARATOR ) > 0 ) {
1894                             final String[] s = character.split( BinaryDomainCombination.SEPARATOR );
1895                             if ( s.length != 2 ) {
1896                                 throw new AssertionError( "this should not have happened: unexpected format for domain combination: ["
1897                                         + character + "]" );
1898                             }
1899                             domain_0 = s[ 0 ];
1900                             domain_1 = s[ 1 ];
1901                         }
1902                         else {
1903                             domain_0 = character;
1904                         }
1905                         writeDomainData( domain_id_to_go_ids_map,
1906                                          go_id_to_term_map,
1907                                          go_namespace_limit,
1908                                          out,
1909                                          domain_0,
1910                                          domain_1,
1911                                          prefix_for_html,
1912                                          character_separator,
1913                                          domain_id_to_secondary_features_maps,
1914                                          null );
1915                         all_pfams_encountered.add( domain_0 );
1916                         if ( pfams_gained_or_lost != null ) {
1917                             pfams_gained_or_lost.add( domain_0 );
1918                         }
1919                         if ( !ForesterUtil.isEmpty( domain_1 ) ) {
1920                             all_pfams_encountered.add( domain_1 );
1921                             if ( pfams_gained_or_lost != null ) {
1922                                 pfams_gained_or_lost.add( domain_1 );
1923                             }
1924                         }
1925                         if ( per_node_go_mapped_domain_gain_loss_outfile_writer != null ) {
1926                             writeDomainsToIndividualFilePerTreeNode( per_node_go_mapped_domain_gain_loss_outfile_writer,
1927                                                                      domain_0,
1928                                                                      domain_1 );
1929                             per_node_counter++;
1930                         }
1931                     }
1932                 }
1933                 if ( per_node_go_mapped_domain_gain_loss_outfile_writer != null ) {
1934                     per_node_go_mapped_domain_gain_loss_outfile_writer.close();
1935                     if ( per_node_counter < 1 ) {
1936                         per_node_go_mapped_domain_gain_loss_outfile.delete();
1937                     }
1938                     per_node_counter = 0;
1939                 }
1940                 out.write( "</table>" );
1941                 out.write( SurfacingConstants.NL );
1942                 out.write( "<hr>" );
1943                 out.write( SurfacingConstants.NL );
1944             } // for( final String id : sorted_ids ) {  
1945             out.write( "</body>" );
1946             out.write( SurfacingConstants.NL );
1947             out.write( "</html>" );
1948             out.write( SurfacingConstants.NL );
1949             out.flush();
1950             out.close();
1951         }
1952         catch ( final IOException e ) {
1953             ForesterUtil.fatalError( surfacing.PRG_NAME, e.getMessage() );
1954         }
1955         ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote characters detailed HTML list: \"" + filename + "\"" );
1956     }
1957
1958     public static void writeDomainCombinationsCountsFile( final String[][] input_file_properties,
1959                                                           final File output_dir,
1960                                                           final Writer per_genome_domain_promiscuity_statistics_writer,
1961                                                           final GenomeWideCombinableDomains gwcd,
1962                                                           final int i,
1963                                                           final GenomeWideCombinableDomains.GenomeWideCombinableDomainsSortOrder dc_sort_order ) {
1964         File dc_outfile = new File( input_file_properties[ i ][ 0 ]
1965                 + surfacing.DOMAIN_COMBINITON_COUNTS_OUTPUTFILE_SUFFIX );
1966         if ( output_dir != null ) {
1967             dc_outfile = new File( output_dir + ForesterUtil.FILE_SEPARATOR + dc_outfile );
1968         }
1969         checkForOutputFileWriteability( dc_outfile );
1970         try {
1971             final BufferedWriter out = new BufferedWriter( new FileWriter( dc_outfile ) );
1972             out.write( gwcd.toStringBuilder( dc_sort_order ).toString() );
1973             out.close();
1974         }
1975         catch ( final IOException e ) {
1976             ForesterUtil.fatalError( surfacing.PRG_NAME, e.getMessage() );
1977         }
1978         final DescriptiveStatistics stats = gwcd.getPerGenomeDomainPromiscuityStatistics();
1979         try {
1980             per_genome_domain_promiscuity_statistics_writer.write( input_file_properties[ i ][ 0 ] + "\t" );
1981             per_genome_domain_promiscuity_statistics_writer.write( FORMATTER_3.format( stats.arithmeticMean() ) + "\t" );
1982             if ( stats.getN() < 2 ) {
1983                 per_genome_domain_promiscuity_statistics_writer.write( "n/a" + "\t" );
1984             }
1985             else {
1986                 per_genome_domain_promiscuity_statistics_writer.write( FORMATTER_3.format( stats
1987                         .sampleStandardDeviation() ) + "\t" );
1988             }
1989             per_genome_domain_promiscuity_statistics_writer.write( FORMATTER_3.format( stats.median() ) + "\t" );
1990             per_genome_domain_promiscuity_statistics_writer.write( ( int ) stats.getMin() + "\t" );
1991             per_genome_domain_promiscuity_statistics_writer.write( ( int ) stats.getMax() + "\t" );
1992             per_genome_domain_promiscuity_statistics_writer.write( stats.getN() + "\t" );
1993             final SortedSet<DomainId> mpds = gwcd.getMostPromiscuosDomain();
1994             for( final DomainId mpd : mpds ) {
1995                 per_genome_domain_promiscuity_statistics_writer.write( mpd.getId() + " " );
1996             }
1997             per_genome_domain_promiscuity_statistics_writer.write( ForesterUtil.LINE_SEPARATOR );
1998         }
1999         catch ( final IOException e ) {
2000             ForesterUtil.fatalError( surfacing.PRG_NAME, e.getMessage() );
2001         }
2002         if ( input_file_properties[ i ].length == 3 ) {
2003             ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote domain combination counts for \""
2004                     + input_file_properties[ i ][ 0 ] + "\" (" + input_file_properties[ i ][ 1 ] + ", "
2005                     + input_file_properties[ i ][ 2 ] + ") to: \"" + dc_outfile + "\"" );
2006         }
2007         else {
2008             ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote domain combination counts for \""
2009                     + input_file_properties[ i ][ 0 ] + "\" (" + input_file_properties[ i ][ 1 ] + ") to: \""
2010                     + dc_outfile + "\"" );
2011         }
2012     }
2013
2014     private static void writeDomainData( final Map<DomainId, List<GoId>> domain_id_to_go_ids_map,
2015                                          final Map<GoId, GoTerm> go_id_to_term_map,
2016                                          final GoNameSpace go_namespace_limit,
2017                                          final Writer out,
2018                                          final String domain_0,
2019                                          final String domain_1,
2020                                          final String prefix_for_html,
2021                                          final String character_separator_for_non_html_output,
2022                                          final Map<DomainId, Set<String>>[] domain_id_to_secondary_features_maps,
2023                                          final Set<GoId> all_go_ids ) throws IOException {
2024         boolean any_go_annotation_present = false;
2025         boolean first_has_no_go = false;
2026         int domain_count = 2; // To distinguish between domains and binary domain combinations.
2027         if ( ForesterUtil.isEmpty( domain_1 ) ) {
2028             domain_count = 1;
2029         }
2030         // The following has a difficult to understand logic.  
2031         for( int d = 0; d < domain_count; ++d ) {
2032             List<GoId> go_ids = null;
2033             boolean go_annotation_present = false;
2034             if ( d == 0 ) {
2035                 final DomainId domain_id = new DomainId( domain_0 );
2036                 if ( domain_id_to_go_ids_map.containsKey( domain_id ) ) {
2037                     go_annotation_present = true;
2038                     any_go_annotation_present = true;
2039                     go_ids = domain_id_to_go_ids_map.get( domain_id );
2040                 }
2041                 else {
2042                     first_has_no_go = true;
2043                 }
2044             }
2045             else {
2046                 final DomainId domain_id = new DomainId( domain_1 );
2047                 if ( domain_id_to_go_ids_map.containsKey( domain_id ) ) {
2048                     go_annotation_present = true;
2049                     any_go_annotation_present = true;
2050                     go_ids = domain_id_to_go_ids_map.get( domain_id );
2051                 }
2052             }
2053             if ( go_annotation_present ) {
2054                 boolean first = ( ( d == 0 ) || ( ( d == 1 ) && first_has_no_go ) );
2055                 for( final GoId go_id : go_ids ) {
2056                     out.write( "<tr>" );
2057                     if ( first ) {
2058                         first = false;
2059                         writeDomainIdsToHtml( out,
2060                                               domain_0,
2061                                               domain_1,
2062                                               prefix_for_html,
2063                                               domain_id_to_secondary_features_maps );
2064                     }
2065                     else {
2066                         out.write( "<td></td>" );
2067                     }
2068                     if ( !go_id_to_term_map.containsKey( go_id ) ) {
2069                         throw new IllegalArgumentException( "GO-id [" + go_id + "] not found in GO-id to GO-term map" );
2070                     }
2071                     final GoTerm go_term = go_id_to_term_map.get( go_id );
2072                     if ( ( go_namespace_limit == null ) || go_namespace_limit.equals( go_term.getGoNameSpace() ) ) {
2073                         // final String top = GoUtils.getPenultimateGoTerm( go_term, go_id_to_term_map ).getName();
2074                         final String go_id_str = go_id.getId();
2075                         out.write( "<td>" );
2076                         out.write( "<a href=\"" + SurfacingConstants.AMIGO_LINK + go_id_str
2077                                 + "\" target=\"amigo_window\">" + go_id_str + "</a>" );
2078                         out.write( "</td><td>" );
2079                         out.write( go_term.getName() );
2080                         if ( domain_count == 2 ) {
2081                             out.write( " (" + d + ")" );
2082                         }
2083                         out.write( "</td><td>" );
2084                         // out.write( top );
2085                         // out.write( "</td><td>" );
2086                         out.write( "[" );
2087                         out.write( go_term.getGoNameSpace().toShortString() );
2088                         out.write( "]" );
2089                         out.write( "</td>" );
2090                         if ( all_go_ids != null ) {
2091                             all_go_ids.add( go_id );
2092                         }
2093                     }
2094                     else {
2095                         out.write( "<td>" );
2096                         out.write( "</td><td>" );
2097                         out.write( "</td><td>" );
2098                         out.write( "</td><td>" );
2099                         out.write( "</td>" );
2100                     }
2101                     out.write( "</tr>" );
2102                     out.write( SurfacingConstants.NL );
2103                 }
2104             }
2105         } //  for( int d = 0; d < domain_count; ++d ) 
2106         if ( !any_go_annotation_present ) {
2107             out.write( "<tr>" );
2108             writeDomainIdsToHtml( out, domain_0, domain_1, prefix_for_html, domain_id_to_secondary_features_maps );
2109             out.write( "<td>" );
2110             out.write( "</td><td>" );
2111             out.write( "</td><td>" );
2112             out.write( "</td><td>" );
2113             out.write( "</td>" );
2114             out.write( "</tr>" );
2115             out.write( SurfacingConstants.NL );
2116         }
2117     }
2118
2119     private static void writeDomainIdsToHtml( final Writer out,
2120                                               final String domain_0,
2121                                               final String domain_1,
2122                                               final String prefix_for_detailed_html,
2123                                               final Map<DomainId, Set<String>>[] domain_id_to_secondary_features_maps )
2124             throws IOException {
2125         out.write( "<td>" );
2126         if ( !ForesterUtil.isEmpty( prefix_for_detailed_html ) ) {
2127             out.write( prefix_for_detailed_html );
2128             out.write( " " );
2129         }
2130         out.write( "<a href=\"" + SurfacingConstants.PFAM_FAMILY_ID_LINK + domain_0 + "\">" + domain_0 + "</a>" );
2131         out.write( "</td>" );
2132     }
2133
2134     public static DescriptiveStatistics writeDomainSimilaritiesToFile( final StringBuilder html_desc,
2135                                                                        final StringBuilder html_title,
2136                                                                        final Writer single_writer,
2137                                                                        Map<Character, Writer> split_writers,
2138                                                                        final SortedSet<DomainSimilarity> similarities,
2139                                                                        final boolean treat_as_binary,
2140                                                                        final List<Species> species_order,
2141                                                                        final PrintableDomainSimilarity.PRINT_OPTION print_option,
2142                                                                        final DomainSimilarity.DomainSimilaritySortField sort_field,
2143                                                                        final DomainSimilarity.DomainSimilarityScoring scoring,
2144                                                                        final boolean verbose ) throws IOException {
2145         final DescriptiveStatistics stats = new BasicDescriptiveStatistics();
2146         String histogram_title = null;
2147         switch ( sort_field ) {
2148             case ABS_MAX_COUNTS_DIFFERENCE:
2149                 if ( treat_as_binary ) {
2150                     histogram_title = "absolute counts difference:";
2151                 }
2152                 else {
2153                     histogram_title = "absolute (maximal) counts difference:";
2154                 }
2155                 break;
2156             case MAX_COUNTS_DIFFERENCE:
2157                 if ( treat_as_binary ) {
2158                     histogram_title = "counts difference:";
2159                 }
2160                 else {
2161                     histogram_title = "(maximal) counts difference:";
2162                 }
2163                 break;
2164             case DOMAIN_ID:
2165                 histogram_title = "score mean:";
2166                 break;
2167             case MIN:
2168                 histogram_title = "score minimum:";
2169                 break;
2170             case MAX:
2171                 histogram_title = "score maximum:";
2172                 break;
2173             case MAX_DIFFERENCE:
2174                 if ( treat_as_binary ) {
2175                     histogram_title = "difference:";
2176                 }
2177                 else {
2178                     histogram_title = "(maximal) difference:";
2179                 }
2180                 break;
2181             case MEAN:
2182                 histogram_title = "score mean:";
2183                 break;
2184             case SD:
2185                 histogram_title = "score standard deviation:";
2186                 break;
2187             case SPECIES_COUNT:
2188                 histogram_title = "species number:";
2189                 break;
2190             default:
2191                 throw new AssertionError( "Unknown sort field: " + sort_field );
2192         }
2193         for( final DomainSimilarity similarity : similarities ) {
2194             switch ( sort_field ) {
2195                 case ABS_MAX_COUNTS_DIFFERENCE:
2196                     stats.addValue( Math.abs( similarity.getMaximalDifferenceInCounts() ) );
2197                     break;
2198                 case MAX_COUNTS_DIFFERENCE:
2199                     stats.addValue( similarity.getMaximalDifferenceInCounts() );
2200                     break;
2201                 case DOMAIN_ID:
2202                     stats.addValue( similarity.getMeanSimilarityScore() );
2203                     break;
2204                 case MIN:
2205                     stats.addValue( similarity.getMinimalSimilarityScore() );
2206                     break;
2207                 case MAX:
2208                     stats.addValue( similarity.getMaximalSimilarityScore() );
2209                     break;
2210                 case MAX_DIFFERENCE:
2211                     stats.addValue( similarity.getMaximalDifference() );
2212                     break;
2213                 case MEAN:
2214                     stats.addValue( similarity.getMeanSimilarityScore() );
2215                     break;
2216                 case SD:
2217                     stats.addValue( similarity.getStandardDeviationOfSimilarityScore() );
2218                     break;
2219                 case SPECIES_COUNT:
2220                     stats.addValue( similarity.getSpecies().size() );
2221                     break;
2222                 default:
2223                     throw new AssertionError( "Unknown sort field: " + sort_field );
2224             }
2225         }
2226         //
2227         // final HistogramData[] hists = new HistogramData[ 1 ];
2228         //      
2229         //        
2230         // List<HistogramDataItem> data_items = new
2231         // ArrayList<HistogramDataItem>();
2232         // double[] values = stats.getDataAsDoubleArray();
2233         // for( int i = 0; i < values.length; i++ ) {
2234         // HistogramDataItem data_item = new BasicHistogramDataItem( "", values[
2235         // i ] );
2236         // data_items.add( data_item );
2237         // }
2238         //        
2239         //        
2240         // HistogramData hd0 = new HistogramData( "name",
2241         // data_items,
2242         // null, 20,
2243         // 40 );
2244         //        
2245         //        
2246         //        
2247         //        
2248         // hists[ 0 ] = hd0;
2249         //       
2250         // final HistogramsFrame hf = new HistogramsFrame( hists );
2251         // hf.setVisible( true );
2252         //
2253         AsciiHistogram histo = null;
2254         if ( stats.getMin() < stats.getMin() ) {
2255             histo = new AsciiHistogram( stats, histogram_title );
2256         }
2257         if ( verbose ) {
2258             if ( histo != null ) {
2259                 System.out.println( histo.toStringBuffer( 20, '|', 40, 5 ) );
2260             }
2261             System.out.println();
2262             System.out.println( "N                   : " + stats.getN() );
2263             System.out.println( "Min                 : " + stats.getMin() );
2264             System.out.println( "Max                 : " + stats.getMax() );
2265             System.out.println( "Mean                : " + stats.arithmeticMean() );
2266             if ( stats.getN() > 1 ) {
2267                 System.out.println( "SD                  : " + stats.sampleStandardDeviation() );
2268             }
2269             else {
2270                 System.out.println( "SD                  : n/a" );
2271             }
2272             System.out.println( "Median              : " + stats.median() );
2273             if ( stats.getN() > 1 ) {
2274                 System.out.println( "Pearsonian skewness : " + stats.pearsonianSkewness() );
2275             }
2276             else {
2277                 System.out.println( "Pearsonian skewness : n/a" );
2278             }
2279         }
2280         if ( ( single_writer != null ) && ( ( split_writers == null ) || split_writers.isEmpty() ) ) {
2281             split_writers = new HashMap<Character, Writer>();
2282             split_writers.put( '_', single_writer );
2283         }
2284         switch ( print_option ) {
2285             case SIMPLE_TAB_DELIMITED:
2286                 break;
2287             case HTML:
2288                 for( final Character key : split_writers.keySet() ) {
2289                     final Writer w = split_writers.get( key );
2290                     w.write( "<html>" );
2291                     w.write( SurfacingConstants.NL );
2292                     if ( key != '_' ) {
2293                         addHtmlHead( w, "DCs (" + html_title + ") " + key.toString().toUpperCase() );
2294                     }
2295                     else {
2296                         addHtmlHead( w, "DCs (" + html_title + ")" );
2297                     }
2298                     w.write( SurfacingConstants.NL );
2299                     w.write( "<body>" );
2300                     w.write( SurfacingConstants.NL );
2301                     w.write( html_desc.toString() );
2302                     w.write( SurfacingConstants.NL );
2303                     w.write( "<hr>" );
2304                     w.write( "<br>" );
2305                     w.write( SurfacingConstants.NL );
2306                     w.write( "<tt><pre>" );
2307                     w.write( SurfacingConstants.NL );
2308                     if ( histo != null ) {
2309                         w.write( histo.toStringBuffer( 20, '|', 40, 5 ).toString() );
2310                         w.write( SurfacingConstants.NL );
2311                     }
2312                     w.write( "</pre></tt>" );
2313                     w.write( SurfacingConstants.NL );
2314                     w.write( "<table>" );
2315                     w.write( SurfacingConstants.NL );
2316                     w.write( "<tr><td>N: </td><td>" + stats.getN() + "</td></tr>" );
2317                     w.write( SurfacingConstants.NL );
2318                     w.write( "<tr><td>Min: </td><td>" + stats.getMin() + "</td></tr>" );
2319                     w.write( SurfacingConstants.NL );
2320                     w.write( "<tr><td>Max: </td><td>" + stats.getMax() + "</td></tr>" );
2321                     w.write( SurfacingConstants.NL );
2322                     w.write( "<tr><td>Mean: </td><td>" + stats.arithmeticMean() + "</td></tr>" );
2323                     w.write( SurfacingConstants.NL );
2324                     if ( stats.getN() > 1 ) {
2325                         w.write( "<tr><td>SD: </td><td>" + stats.sampleStandardDeviation() + "</td></tr>" );
2326                     }
2327                     else {
2328                         w.write( "<tr><td>SD: </td><td>n/a</td></tr>" );
2329                     }
2330                     w.write( SurfacingConstants.NL );
2331                     w.write( "<tr><td>Median: </td><td>" + stats.median() + "</td></tr>" );
2332                     w.write( SurfacingConstants.NL );
2333                     if ( stats.getN() > 1 ) {
2334                         w.write( "<tr><td>Pearsonian skewness: </td><td>" + stats.pearsonianSkewness() + "</td></tr>" );
2335                     }
2336                     else {
2337                         w.write( "<tr><td>Pearsonian skewness: </td><td>n/a</td></tr>" );
2338                     }
2339                     w.write( SurfacingConstants.NL );
2340                     w.write( "</table>" );
2341                     w.write( SurfacingConstants.NL );
2342                     w.write( "<br>" );
2343                     w.write( SurfacingConstants.NL );
2344                     w.write( "<hr>" );
2345                     w.write( SurfacingConstants.NL );
2346                     w.write( "<br>" );
2347                     w.write( SurfacingConstants.NL );
2348                     w.write( "<table>" );
2349                     w.write( SurfacingConstants.NL );
2350                 }
2351                 break;
2352         }
2353         for( final Writer w : split_writers.values() ) {
2354             w.write( SurfacingConstants.NL );
2355         }
2356         for( final DomainSimilarity similarity : similarities ) {
2357             if ( ( species_order != null ) && !species_order.isEmpty() ) {
2358                 ( ( PrintableDomainSimilarity ) similarity ).setSpeciesOrder( species_order );
2359             }
2360             if ( single_writer != null ) {
2361                 single_writer.write( similarity.toStringBuffer( print_option ).toString() );
2362             }
2363             else {
2364                 Writer local_writer = split_writers.get( ( similarity.getDomainId().getId().charAt( 0 ) + "" )
2365                         .toLowerCase().charAt( 0 ) );
2366                 if ( local_writer == null ) {
2367                     local_writer = split_writers.get( '0' );
2368                 }
2369                 local_writer.write( similarity.toStringBuffer( print_option ).toString() );
2370             }
2371             for( final Writer w : split_writers.values() ) {
2372                 w.write( SurfacingConstants.NL );
2373             }
2374         }
2375         switch ( print_option ) {
2376             case HTML:
2377                 for( final Writer w : split_writers.values() ) {
2378                     w.write( SurfacingConstants.NL );
2379                     w.write( "</table>" );
2380                     w.write( SurfacingConstants.NL );
2381                     w.write( "</font>" );
2382                     w.write( SurfacingConstants.NL );
2383                     w.write( "</body>" );
2384                     w.write( SurfacingConstants.NL );
2385                     w.write( "</html>" );
2386                     w.write( SurfacingConstants.NL );
2387                 }
2388                 break;
2389         }
2390         for( final Writer w : split_writers.values() ) {
2391             w.close();
2392         }
2393         return stats;
2394     }
2395
2396     private static void writeDomainsToIndividualFilePerTreeNode( final Writer individual_files_writer,
2397                                                                  final String domain_0,
2398                                                                  final String domain_1 ) throws IOException {
2399         individual_files_writer.write( domain_0 );
2400         individual_files_writer.write( ForesterUtil.LINE_SEPARATOR );
2401         if ( !ForesterUtil.isEmpty( domain_1 ) ) {
2402             individual_files_writer.write( domain_1 );
2403             individual_files_writer.write( ForesterUtil.LINE_SEPARATOR );
2404         }
2405     }
2406
2407     public static void writeMatrixToFile( final CharacterStateMatrix<?> matrix,
2408                                           final String filename,
2409                                           final Format format ) {
2410         final File outfile = new File( filename );
2411         checkForOutputFileWriteability( outfile );
2412         try {
2413             final BufferedWriter out = new BufferedWriter( new FileWriter( outfile ) );
2414             matrix.toWriter( out, format );
2415             out.flush();
2416             out.close();
2417         }
2418         catch ( final IOException e ) {
2419             ForesterUtil.fatalError( surfacing.PRG_NAME, e.getMessage() );
2420         }
2421         ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote matrix: \"" + filename + "\"" );
2422     }
2423
2424     public static void writeMatrixToFile( final File matrix_outfile, final List<DistanceMatrix> matrices ) {
2425         checkForOutputFileWriteability( matrix_outfile );
2426         try {
2427             final BufferedWriter out = new BufferedWriter( new FileWriter( matrix_outfile ) );
2428             for( final DistanceMatrix distance_matrix : matrices ) {
2429                 out.write( distance_matrix.toStringBuffer( DistanceMatrix.Format.PHYLIP ).toString() );
2430                 out.write( ForesterUtil.LINE_SEPARATOR );
2431                 out.flush();
2432             }
2433             out.close();
2434         }
2435         catch ( final IOException e ) {
2436             ForesterUtil.fatalError( surfacing.PRG_NAME, e.getMessage() );
2437         }
2438         ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote distance matrices to \"" + matrix_outfile + "\"" );
2439     }
2440
2441     private static void writePfamsToFile( final String outfile_name, final SortedSet<String> pfams ) {
2442         try {
2443             final Writer writer = new BufferedWriter( new FileWriter( new File( outfile_name ) ) );
2444             for( final String pfam : pfams ) {
2445                 writer.write( pfam );
2446                 writer.write( ForesterUtil.LINE_SEPARATOR );
2447             }
2448             writer.close();
2449             ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote " + pfams.size() + " pfams to [" + outfile_name
2450                     + "]" );
2451         }
2452         catch ( final IOException e ) {
2453             ForesterUtil.printWarningMessage( surfacing.PRG_NAME, "Failure to write: " + e );
2454         }
2455     }
2456
2457     public static void writePhylogenyToFile( final Phylogeny phylogeny, final String filename ) {
2458         final PhylogenyWriter writer = new PhylogenyWriter();
2459         try {
2460             writer.toPhyloXML( new File( filename ), phylogeny, 1 );
2461         }
2462         catch ( final IOException e ) {
2463             ForesterUtil.printWarningMessage( surfacing.PRG_NAME, "failed to write phylogeny to \"" + filename + "\": "
2464                     + e );
2465         }
2466         ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote phylogeny to \"" + filename + "\"" );
2467     }
2468
2469     public static void writeTaxonomyLinks( final Writer writer, final String species ) throws IOException {
2470         if ( ( species.length() > 1 ) && ( species.indexOf( '_' ) < 1 ) ) {
2471             final Matcher matcher = PATTERN_SP_STYLE_TAXONOMY.matcher( species );
2472             writer.write( " [" );
2473             if ( matcher.matches() ) {
2474                 writer.write( "<a href=\"" + SurfacingConstants.UNIPROT_LINK + species
2475                         + "\" target=\"taxonomy_window\">uniprot</a>" );
2476             }
2477             else {
2478                 writer.write( "<a href=\"" + SurfacingConstants.EOL_LINK + species
2479                         + "\" target=\"taxonomy_window\">eol</a>" );
2480                 writer.write( "|" );
2481                 writer.write( "<a href=\"" + SurfacingConstants.TOL_LINK + species
2482                         + "\" target=\"taxonomy_window\">tol</a>" );
2483             }
2484             writer.write( "]" );
2485         }
2486     }
2487
2488     private static void writeToNexus( final String outfile_name,
2489                                       final CharacterStateMatrix<BinaryStates> matrix,
2490                                       final Phylogeny phylogeny ) {
2491         if ( !( matrix instanceof BasicCharacterStateMatrix ) ) {
2492             throw new IllegalArgumentException( "can only write matrices of type [" + BasicCharacterStateMatrix.class
2493                     + "] to nexus" );
2494         }
2495         final BasicCharacterStateMatrix<BinaryStates> my_matrix = ( org.forester.evoinference.matrix.character.BasicCharacterStateMatrix<BinaryStates> ) matrix;
2496         final List<Phylogeny> phylogenies = new ArrayList<Phylogeny>( 1 );
2497         phylogenies.add( phylogeny );
2498         try {
2499             final BufferedWriter w = new BufferedWriter( new FileWriter( outfile_name ) );
2500             w.write( NexusConstants.NEXUS );
2501             w.write( ForesterUtil.LINE_SEPARATOR );
2502             my_matrix.writeNexusTaxaBlock( w );
2503             my_matrix.writeNexusBinaryChractersBlock( w );
2504             PhylogenyWriter.writeNexusTreesBlock( w, phylogenies, NH_CONVERSION_SUPPORT_VALUE_STYLE.NONE );
2505             w.flush();
2506             w.close();
2507             ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote Nexus file: \"" + outfile_name + "\"" );
2508         }
2509         catch ( final IOException e ) {
2510             ForesterUtil.fatalError( surfacing.PRG_NAME, e.getMessage() );
2511         }
2512     }
2513
2514     private static void writeToNexus( final String outfile_name,
2515                                       final DomainParsimonyCalculator domain_parsimony,
2516                                       final Phylogeny phylogeny ) {
2517         writeToNexus( outfile_name + surfacing.NEXUS_EXTERNAL_DOMAINS,
2518                       domain_parsimony.createMatrixOfDomainPresenceOrAbsence(),
2519                       phylogeny );
2520         writeToNexus( outfile_name + surfacing.NEXUS_EXTERNAL_DOMAIN_COMBINATIONS,
2521                       domain_parsimony.createMatrixOfBinaryDomainCombinationPresenceOrAbsence(),
2522                       phylogeny );
2523     }
2524
2525     public static void domainsPerProteinsStatistics( final String genome,
2526                                                      final List<Protein> protein_list,
2527                                                      final DescriptiveStatistics all_genomes_domains_per_potein_stats,
2528                                                      final SortedMap<Integer, Integer> all_genomes_domains_per_potein_histo,
2529                                                      final SortedSet<String> domains_which_are_always_single,
2530                                                      final SortedSet<String> domains_which_are_sometimes_single_sometimes_not,
2531                                                      final SortedSet<String> domains_which_never_single,
2532                                                      final Writer writer ) {
2533         final DescriptiveStatistics stats = new BasicDescriptiveStatistics();
2534         for( final Protein protein : protein_list ) {
2535             final int domains = protein.getNumberOfProteinDomains();
2536             //System.out.println( domains );
2537             stats.addValue( domains );
2538             all_genomes_domains_per_potein_stats.addValue( domains );
2539             if ( !all_genomes_domains_per_potein_histo.containsKey( domains ) ) {
2540                 all_genomes_domains_per_potein_histo.put( domains, 1 );
2541             }
2542             else {
2543                 all_genomes_domains_per_potein_histo.put( domains,
2544                                                           1 + all_genomes_domains_per_potein_histo.get( domains ) );
2545             }
2546             if ( domains == 1 ) {
2547                 final String domain = protein.getProteinDomain( 0 ).getDomainId().getId();
2548                 if ( !domains_which_are_sometimes_single_sometimes_not.contains( domain ) ) {
2549                     if ( domains_which_never_single.contains( domain ) ) {
2550                         domains_which_never_single.remove( domain );
2551                         domains_which_are_sometimes_single_sometimes_not.add( domain );
2552                     }
2553                     else {
2554                         domains_which_are_always_single.add( domain );
2555                     }
2556                 }
2557             }
2558             else if ( domains > 1 ) {
2559                 for( final Domain d : protein.getProteinDomains() ) {
2560                     final String domain = d.getDomainId().getId();
2561                     // System.out.println( domain );
2562                     if ( !domains_which_are_sometimes_single_sometimes_not.contains( domain ) ) {
2563                         if ( domains_which_are_always_single.contains( domain ) ) {
2564                             domains_which_are_always_single.remove( domain );
2565                             domains_which_are_sometimes_single_sometimes_not.add( domain );
2566                         }
2567                         else {
2568                             domains_which_never_single.add( domain );
2569                         }
2570                     }
2571                 }
2572             }
2573         }
2574         try {
2575             writer.write( genome );
2576             writer.write( "\t" );
2577             if ( stats.getN() >= 1 ) {
2578                 writer.write( stats.arithmeticMean() + "" );
2579                 writer.write( "\t" );
2580                 if ( stats.getN() >= 2 ) {
2581                     writer.write( stats.sampleStandardDeviation() + "" );
2582                 }
2583                 else {
2584                     writer.write( "" );
2585                 }
2586                 writer.write( "\t" );
2587                 writer.write( stats.median() + "" );
2588                 writer.write( "\t" );
2589                 writer.write( stats.getN() + "" );
2590                 writer.write( "\t" );
2591                 writer.write( stats.getMin() + "" );
2592                 writer.write( "\t" );
2593                 writer.write( stats.getMax() + "" );
2594             }
2595             else {
2596                 writer.write( "\t" );
2597                 writer.write( "\t" );
2598                 writer.write( "\t" );
2599                 writer.write( "0" );
2600                 writer.write( "\t" );
2601                 writer.write( "\t" );
2602             }
2603             writer.write( "\n" );
2604         }
2605         catch ( final IOException e ) {
2606             e.printStackTrace();
2607         }
2608     }
2609 }