in progress
[jalview.git] / forester / java / src / org / forester / application / surfacing.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.application;
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.util.ArrayList;
35 import java.util.Date;
36 import java.util.HashSet;
37 import java.util.List;
38 import java.util.Map;
39 import java.util.Set;
40 import java.util.SortedMap;
41 import java.util.SortedSet;
42 import java.util.TreeMap;
43 import java.util.TreeSet;
44
45 import org.forester.evoinference.distance.NeighborJoining;
46 import org.forester.evoinference.matrix.character.CharacterStateMatrix.Format;
47 import org.forester.evoinference.matrix.distance.DistanceMatrix;
48 import org.forester.go.GoId;
49 import org.forester.go.GoNameSpace;
50 import org.forester.go.GoTerm;
51 import org.forester.go.GoUtils;
52 import org.forester.go.OBOparser;
53 import org.forester.go.PfamToGoMapping;
54 import org.forester.go.PfamToGoParser;
55 import org.forester.io.parsers.HmmscanPerDomainTableParser;
56 import org.forester.io.parsers.HmmscanPerDomainTableParser.INDIVIDUAL_SCORE_CUTOFF;
57 import org.forester.io.writers.PhylogenyWriter;
58 import org.forester.phylogeny.Phylogeny;
59 import org.forester.phylogeny.PhylogenyMethods;
60 import org.forester.phylogeny.PhylogenyNode;
61 import org.forester.phylogeny.factories.ParserBasedPhylogenyFactory;
62 import org.forester.phylogeny.iterators.PhylogenyNodeIterator;
63 import org.forester.surfacing.BasicDomainSimilarityCalculator;
64 import org.forester.surfacing.BasicGenomeWideCombinableDomains;
65 import org.forester.surfacing.BasicSpecies;
66 import org.forester.surfacing.BinaryDomainCombination;
67 import org.forester.surfacing.CombinationsBasedPairwiseDomainSimilarityCalculator;
68 import org.forester.surfacing.DomainCountsBasedPairwiseSimilarityCalculator;
69 import org.forester.surfacing.DomainCountsDifferenceUtil;
70 import org.forester.surfacing.DomainId;
71 import org.forester.surfacing.DomainLengthsTable;
72 import org.forester.surfacing.DomainParsimonyCalculator;
73 import org.forester.surfacing.DomainSimilarity;
74 import org.forester.surfacing.DomainSimilarity.DomainSimilarityScoring;
75 import org.forester.surfacing.DomainSimilarity.DomainSimilaritySortField;
76 import org.forester.surfacing.DomainSimilarityCalculator;
77 import org.forester.surfacing.DomainSimilarityCalculator.Detailedness;
78 import org.forester.surfacing.GenomeWideCombinableDomains;
79 import org.forester.surfacing.GenomeWideCombinableDomains.GenomeWideCombinableDomainsSortOrder;
80 import org.forester.surfacing.MappingResults;
81 import org.forester.surfacing.PairwiseDomainSimilarityCalculator;
82 import org.forester.surfacing.PairwiseGenomeComparator;
83 import org.forester.surfacing.PrintableDomainSimilarity;
84 import org.forester.surfacing.PrintableDomainSimilarity.PRINT_OPTION;
85 import org.forester.surfacing.Protein;
86 import org.forester.surfacing.ProteinCountsBasedPairwiseDomainSimilarityCalculator;
87 import org.forester.surfacing.Species;
88 import org.forester.surfacing.SurfacingUtil;
89 import org.forester.util.BasicTable;
90 import org.forester.util.BasicTableParser;
91 import org.forester.util.CommandLineArguments;
92 import org.forester.util.DescriptiveStatistics;
93 import org.forester.util.ForesterConstants;
94 import org.forester.util.ForesterUtil;
95
96 public class surfacing {
97
98     public final static String                                DOMAIN_COMBINITONS_OUTPUT_OPTION_FOR_GRAPH_ANALYSIS                    = "graph_analysis_out";
99     public final static String                                DOMAIN_COMBINITONS_OUTPUTFILE_SUFFIX_FOR_GRAPH_ANALYSIS                = "_dc.dot";
100     public final static String                                PARSIMONY_OUTPUT_FITCH_PRESENT_BC_OUTPUTFILE_SUFFIX_FOR_GRAPH_ANALYSIS = "_fitch_present_dc.dot";
101     public final static String                                DOMAIN_COMBINITON_COUNTS_OUTPUTFILE_SUFFIX                             = ".dcc";
102     // gain/loss:
103     public final static String                                PARSIMONY_OUTPUT_GL_SUFFIX_DOLLO_DOMAINS                               = "_dollo_gl_d";
104     public final static String                                PARSIMONY_OUTPUT_GL_SUFFIX_DOLLO_BINARY_COMBINATIONS                   = "_dollo_gl_dc";
105     public final static String                                PARSIMONY_OUTPUT_GL_SUFFIX_FITCH_DOMAINS                               = "_fitch_gl_d";
106     public final static String                                PARSIMONY_OUTPUT_GL_SUFFIX_FITCH_BINARY_COMBINATIONS                   = "_fitch_gl_dc";
107     // gain/loss counts:
108     public final static String                                PARSIMONY_OUTPUT_GL_COUNTS_SUFFIX_DOLLO_DOMAINS                        = "_dollo_glc_d";
109     public final static String                                PARSIMONY_OUTPUT_GL_COUNTS_SUFFIX_DOLLO_BINARY_COMBINATIONS            = "_dollo_glc_dc";
110     public final static String                                PARSIMONY_OUTPUT_GL_COUNTS_SUFFIX_FITCH_DOMAINS                        = "_fitch_glc_d";
111     public final static String                                PARSIMONY_OUTPUT_GL_COUNTS_SUFFIX_FITCH_BINARY_COMBINATIONS            = "_fitch_glc_dc";
112     // tables:
113     public final static String                                PARSIMONY_OUTPUT_FITCH_GAINS_BC                                        = "_fitch_gains_dc";
114     public final static String                                PARSIMONY_OUTPUT_FITCH_GAINS_HTML_BC                                   = "_fitch_gains_dc.html";
115     public final static String                                PARSIMONY_OUTPUT_FITCH_LOSSES_BC                                       = "_fitch_losses_dc";
116     public final static String                                PARSIMONY_OUTPUT_FITCH_LOSSES_HTML_BC                                  = "_fitch_losses_dc.html";
117     public final static String                                PARSIMONY_OUTPUT_FITCH_PRESENT_BC                                      = "_fitch_present_dc";
118     public final static String                                PARSIMONY_OUTPUT_FITCH_PRESENT_HTML_BC                                 = "_fitch_present_dc.html";
119     public final static String                                PARSIMONY_OUTPUT_DOLLO_GAINS_D                                         = "_dollo_gains_d";
120     public final static String                                PARSIMONY_OUTPUT_DOLLO_GAINS_HTML_D                                    = "_dollo_gains_d.html";
121     public final static String                                PARSIMONY_OUTPUT_DOLLO_LOSSES_D                                        = "_dollo_losses_d";
122     public final static String                                PARSIMONY_OUTPUT_DOLLO_LOSSES_HTML_D                                   = "_dollo_losses_d.html";
123     public final static String                                PARSIMONY_OUTPUT_DOLLO_PRESENT_D                                       = "_dollo_present_d";
124     public final static String                                PARSIMONY_OUTPUT_DOLLO_PRESENT_HTML_D                                  = "_dollo_present_d.html";
125     public final static String                                DOMAINS_PRESENT_NEXUS                                                  = "_dom.nex";
126     public final static String                                BDC_PRESENT_NEXUS                                                      = "_dc.nex";
127     // ---
128     public final static String                                PRG_NAME                                                               = "surfacing";
129     public static final String                                DOMAINS_PARSIMONY_TREE_OUTPUT_SUFFIX_DOLLO                             = "_d_dollo"
130                                                                                                                                              + ForesterConstants.PHYLO_XML_SUFFIX;
131     public static final String                                DOMAINS_PARSIMONY_TREE_OUTPUT_SUFFIX_FITCH                             = "_d_fitch"
132                                                                                                                                              + ForesterConstants.PHYLO_XML_SUFFIX;
133     public static final String                                BINARY_DOMAIN_COMBINATIONS_PARSIMONY_TREE_OUTPUT_SUFFIX_DOLLO          = "_dc_dollo"
134                                                                                                                                              + ForesterConstants.PHYLO_XML_SUFFIX;
135     public static final String                                BINARY_DOMAIN_COMBINATIONS_PARSIMONY_TREE_OUTPUT_SUFFIX_FITCH          = "_dc_fitch"
136                                                                                                                                              + ForesterConstants.PHYLO_XML_SUFFIX;
137     public static final String                                NEXUS_EXTERNAL_DOMAINS                                                 = "_dom.nex";
138     public static final String                                NEXUS_EXTERNAL_DOMAIN_COMBINATIONS                                     = "_dc.nex";
139     public static final String                                NEXUS_SECONDARY_FEATURES                                               = "_secondary_features.nex";
140     public static final String                                PARSIMONY_OUTPUT_GL_SUFFIX_DOLLO_SECONDARY_FEATURES                    = "_dollo_gl_secondary_features";
141     public static final String                                PARSIMONY_OUTPUT_GL_COUNTS_SUFFIX_DOLLO_SECONDARY_FEATURES             = "_dollo_glc_secondary_features";
142     public static final String                                PARSIMONY_OUTPUT_DOLLO_GAINS_SECONDARY_FEATURES                        = "_dollo_gains_secondary_features";
143     public static final String                                PARSIMONY_OUTPUT_DOLLO_LOSSES_SECONDARY_FEATURES                       = "_dollo_losses_secondary_features";
144     public static final String                                PARSIMONY_OUTPUT_DOLLO_PRESENT_SECONDARY_FEATURES                      = "_dollo_present_secondary_features";
145     public static final String                                SECONDARY_FEATURES_PARSIMONY_TREE_OUTPUT_SUFFIX_DOLLO                  = "_secondary_features_dollo"
146                                                                                                                                              + ForesterConstants.PHYLO_XML_SUFFIX;
147     public static final String                                PARSIMONY_OUTPUT_DOLLO_ALL_GOID_D_ALL_NAMESPACES                       = "_dollo_goid_d";
148     public static final String                                PARSIMONY_OUTPUT_FITCH_ALL_GOID_BC_ALL_NAMESPACES                      = "_fitch_goid_dc";
149     final static private String                               HELP_OPTION_1                                                          = "help";
150     final static private String                               HELP_OPTION_2                                                          = "h";
151     final static private String                               OUTPUT_DIR_OPTION                                                      = "out_dir";
152     final static private String                               SCORING_OPTION                                                         = "scoring";
153     private static final DomainSimilarityScoring              SCORING_DEFAULT                                                        = DomainSimilarity.DomainSimilarityScoring.COMBINATIONS;
154     final static private String                               SCORING_DOMAIN_COUNT_BASED                                             = "domains";
155     final static private String                               SCORING_PROTEIN_COUNT_BASED                                            = "proteins";
156     final static private String                               SCORING_COMBINATION_BASED                                              = "combinations";
157     final static private String                               DETAILEDNESS_OPTION                                                    = "detail";
158     private final static Detailedness                         DETAILEDNESS_DEFAULT                                                   = DomainSimilarityCalculator.Detailedness.PUNCTILIOUS;
159     final static private String                               SPECIES_MATRIX_OPTION                                                  = "smatrix";
160     final static private String                               DETAILEDNESS_BASIC                                                     = "basic";
161     final static private String                               DETAILEDNESS_LIST_IDS                                                  = "list_ids";
162     final static private String                               DETAILEDNESS_PUNCTILIOUS                                               = "punctilious";
163     final static private String                               DOMAIN_SIMILARITY_SORT_OPTION                                          = "sort";
164     private static final DomainSimilaritySortField            DOMAIN_SORT_FILD_DEFAULT                                               = DomainSimilarity.DomainSimilaritySortField.DOMAIN_ID;
165     final static private String                               DOMAIN_SIMILARITY_SORT_MIN                                             = "min";
166     final static private String                               DOMAIN_SIMILARITY_SORT_MAX                                             = "max";
167     final static private String                               DOMAIN_SIMILARITY_SORT_SD                                              = "sd";
168     final static private String                               DOMAIN_SIMILARITY_SORT_MEAN                                            = "mean";
169     final static private String                               DOMAIN_SIMILARITY_SORT_DIFF                                            = "diff";
170     final static private String                               DOMAIN_SIMILARITY_SORT_COUNTS_DIFF                                     = "count_diff";
171     final static private String                               DOMAIN_SIMILARITY_SORT_ABS_COUNTS_DIFF                                 = "abs_count_diff";
172     final static private String                               DOMAIN_SIMILARITY_SORT_SPECIES_COUNT                                   = "species";
173     final static private String                               DOMAIN_SIMILARITY_SORT_ALPHA                                           = "alpha";
174     final static private String                               DOMAIN_SIMILARITY_SORT_BY_SPECIES_COUNT_FIRST_OPTION                   = "species_first";
175     final static private String                               DOMAIN_COUNT_SORT_OPTION                                               = "dc_sort";
176     private static final GenomeWideCombinableDomainsSortOrder DOMAINS_SORT_ORDER_DEFAULT                                             = GenomeWideCombinableDomains.GenomeWideCombinableDomainsSortOrder.ALPHABETICAL_KEY_ID;
177     final static private String                               DOMAIN_COUNT_SORT_ALPHA                                                = "alpha";
178     final static private String                               DOMAIN_COUNT_SORT_KEY_DOMAIN_COUNT                                     = "dom";
179     final static private String                               DOMAIN_COUNT_SORT_KEY_DOMAIN_PROTEINS_COUNT                            = "prot";
180     final static private String                               DOMAIN_COUNT_SORT_COMBINATIONS_COUNT                                   = "comb";
181     final static private String                               CUTOFF_SCORE_FILE_OPTION                                               = "cos";
182     final static private String                               NOT_IGNORE_DUFS_OPTION                                                 = "dufs";
183     final static private String                               MAX_E_VALUE_OPTION                                                     = "e";
184     final static private String                               MAX_ALLOWED_OVERLAP_OPTION                                             = "mo";
185     final static private String                               NO_ENGULFING_OVERLAP_OPTION                                            = "no_eo";
186     final static private String                               IGNORE_COMBINATION_WITH_SAME_OPTION                                    = "ignore_self_comb";
187     final static private String                               PAIRWISE_DOMAIN_COMPARISONS_PREFIX                                     = "pwc_";
188     final static private String                               PAIRWISE_DOMAIN_COMPARISONS_OPTION                                     = "pwc";
189     final static private String                               OUTPUT_FILE_OPTION                                                     = "o";
190     final static private String                               PFAM_TO_GO_FILE_USE_OPTION                                             = "p2g";
191     final static private String                               GO_OBO_FILE_USE_OPTION                                                 = "obo";
192     final static private String                               GO_NAMESPACE_LIMIT_OPTION                                              = "go_namespace";
193     final static private String                               GO_NAMESPACE_LIMIT_OPTION_MOLECULAR_FUNCTION                           = "molecular_function";
194     final static private String                               GO_NAMESPACE_LIMIT_OPTION_BIOLOGICAL_PROCESS                           = "biological_process";
195     final static private String                               GO_NAMESPACE_LIMIT_OPTION_CELLULAR_COMPONENT                           = "cellular_component";
196     final static private String                               SECONDARY_FEATURES_PARSIMONY_MAP_FILE                                  = "secondary";
197     final static private String                               DOMAIN_SIMILARITY_PRINT_OPTION_SIMPLE_TAB_DELIMITED                    = "simple_tab";
198     final static private String                               DOMAIN_SIMILARITY_PRINT_OPTION_SIMPLE_HTML                             = "simple_html";
199     final static private String                               DOMAIN_SIMILARITY_PRINT_OPTION_DETAILED_HTML                           = "detailed_html";
200     final static private String                               DOMAIN_SIMILARITY_PRINT_OPTION                                         = "ds_output";
201     private static final PRINT_OPTION                         DOMAIN_SIMILARITY_PRINT_OPTION_DEFAULT                                 = PrintableDomainSimilarity.PRINT_OPTION.HTML;
202     final static private String                               IGNORE_DOMAINS_WITHOUT_COMBINATIONS_IN_ALL_SPECIES_OPTION              = "ignore_singlet_domains";
203     final static private String                               IGNORE_VIRAL_IDS                                                       = "ignore_viral_ids";
204     final static private boolean                              IGNORE_DOMAINS_WITHOUT_COMBINATIONS_IN_ALL_SPECIES_DEFAULT             = false;
205     final static private String                               IGNORE_DOMAINS_SPECIFIC_TO_ONE_SPECIES_OPTION                          = "ignore_species_specific_domains";
206     final static private boolean                              IGNORE_DOMAINS_SPECIFIC_TO_ONE_SPECIES_OPTION_DEFAULT                  = false;
207     final static private String                               MATRIX_MEAN_SCORE_BASED_GENOME_DISTANCE_SUFFIX                         = "_mean_score.pwd";
208     final static private String                               MATRIX_SHARED_DOMAINS_BASED_GENOME_DISTANCE_SUFFIX                     = "_domains.pwd";
209     final static private String                               MATRIX_SHARED_BIN_COMBINATIONS_BASED_GENOME_DISTANCE_SUFFIX            = "_bin_combinations.pwd";
210     final static private String                               NJ_TREE_MEAN_SCORE_BASED_GENOME_DISTANCE_SUFFIX                        = "_mean_score_NJ"
211                                                                                                                                              + ForesterConstants.PHYLO_XML_SUFFIX;
212     final static private String                               NJ_TREE_SHARED_DOMAINS_BASED_GENOME_DISTANCE_SUFFIX                    = "_domains_NJ"
213                                                                                                                                              + ForesterConstants.PHYLO_XML_SUFFIX;
214     final static private String                               NJ_TREE_SHARED_BIN_COMBINATIONS_BASED_GENOME_DISTANCE_SUFFIX           = "_bin_combinations_NJ"
215                                                                                                                                              + ForesterConstants.PHYLO_XML_SUFFIX;
216     final static private String                               JACKNIFE_OPTION                                                        = "jack";
217     final static private String                               JACKNIFE_RANDOM_SEED_OPTION                                            = "seed";
218     final static private String                               JACKNIFE_RATIO_OPTION                                                  = "jack_ratio";
219     private static final int                                  JACKNIFE_NUMBER_OF_RESAMPLINGS_DEFAULT                                 = 100;
220     final static private long                                 JACKNIFE_RANDOM_SEED_DEFAULT                                           = 19;
221     final static private double                               JACKNIFE_RATIO_DEFAULT                                                 = 0.5;
222     //final static private String  INFER_SPECIES_TREES_OPTION                                             = "species_tree_inference";
223     final static private String                               INFERRED_SD_BASED_NJ_SPECIES_TREE_SUFFIX                               = "_sd_nj.nh";
224     final static private String                               INFERRED_SBC_BASED_NJ_SPECIES_TREE_SUFFIX                              = "_sbc_nj.nh";
225     final static private String                               FILTER_POSITIVE_OPTION                                                 = "pos_filter";
226     final static private String                               FILTER_NEGATIVE_OPTION                                                 = "neg_filter";
227     final static private String                               FILTER_NEGATIVE_DOMAINS_OPTION                                         = "neg_dom_filter";
228     final static private String                               INPUT_FILES_FROM_FILE_OPTION                                           = "input";
229     final static private String                               INPUT_SPECIES_TREE_OPTION                                              = "species_tree";
230     final static private String                               SEQ_EXTRACT_OPTION                                                     = "prot_extract";
231     final static private char                                 SEPARATOR_FOR_INPUT_VALUES                                             = '#';
232     final static private String                               PRG_VERSION                                                            = "2.100";
233     final static private String                               PRG_DATE                                                               = "2011.06.17";
234     final static private String                               E_MAIL                                                                 = "czmasek@burnham.org";
235     final static private String                               WWW                                                                    = "www.phylosoft.org/forester/applications/surfacing";
236     final static private boolean                              IGNORE_DUFS_DEFAULT                                                    = true;
237     final static private boolean                              IGNORE_COMBINATION_WITH_SAME_DEFAULLT                                  = false;
238     final static private double                               MAX_E_VALUE_DEFAULT                                                    = -1;
239     final static private int                                  MAX_ALLOWED_OVERLAP_DEFAULT                                            = -1;
240     private static final String                               RANDOM_SEED_FOR_FITCH_PARSIMONY_OPTION                                 = "random_seed";
241     private static final String                               CONSIDER_DOMAIN_COMBINATION_DIRECTEDNESS                               = "consider_bdc_direction";
242     private static final String                               CONSIDER_DOMAIN_COMBINATION_DIRECTEDNESS_AND_ADJACENCY                 = "consider_bdc_adj";
243     private static final String                               SEQ_EXTRACT_SUFFIX                                                     = ".prot";
244     private static final String                               PLUS_MINUS_ANALYSIS_OPTION                                             = "plus_minus";
245     private static final String                               PLUS_MINUS_DOM_SUFFIX                                                  = "_plus_minus_dom.txt";
246     private static final String                               PLUS_MINUS_DOM_SUFFIX_HTML                                             = "_plus_minus_dom.html";
247     private static final String                               PLUS_MINUS_DC_SUFFIX_HTML                                              = "_plus_minus_dc.html";
248     private static final int                                  PLUS_MINUS_ANALYSIS_MIN_DIFF_DEFAULT                                   = 0;
249     private static final double                               PLUS_MINUS_ANALYSIS_FACTOR_DEFAULT                                     = 1.0;
250     private static final String                               PLUS_MINUS_ALL_GO_IDS_DOM_SUFFIX                                       = "_plus_minus_go_ids_all.txt";
251     private static final String                               PLUS_MINUS_PASSING_GO_IDS_DOM_SUFFIX                                   = "_plus_minus_go_ids_passing.txt";
252     private static final String                               OUTPUT_LIST_OF_ALL_PROTEINS_OPTIONS                                    = "all_prot";
253     private static final boolean                              VERBOSE                                                                = false;
254     private static final String                               OUTPUT_DOMAIN_COMBINATIONS_GAINED_MORE_THAN_ONCE_ANALYSIS_SUFFIX       = "_fitch_dc_gains_counts";
255     private static final String                               OUTPUT_DOMAIN_COMBINATIONS_LOST_MORE_THAN_ONCE_ANALYSIS_SUFFIX         = "_fitch_dc_losses_counts";
256     private static final String                               DOMAIN_LENGTHS_ANALYSIS_SUFFIX                                         = "_domain_lengths_analysis";
257     private static final boolean                              PERFORM_DOMAIN_LENGTH_ANALYSIS                                         = true;
258     public static final String                                ALL_PFAMS_ENCOUNTERED_SUFFIX                                           = "_all_encountered_pfams";
259     public static final String                                ALL_PFAMS_ENCOUNTERED_WITH_GO_ANNOTATION_SUFFIX                        = "_all_encountered_pfams_with_go_annotation";
260     public static final String                                ENCOUNTERED_PFAMS_SUMMARY_SUFFIX                                       = "_encountered_pfams_summary";
261     public static final String                                ALL_PFAMS_GAINED_AS_DOMAINS_SUFFIX                                     = "_all_pfams_gained_as_domains";
262     public static final String                                ALL_PFAMS_LOST_AS_DOMAINS_SUFFIX                                       = "_all_pfams_lost_as_domains";
263     public static final String                                ALL_PFAMS_GAINED_AS_DC_SUFFIX                                          = "_all_pfams_gained_as_dc";
264     public static final String                                ALL_PFAMS_LOST_AS_DC_SUFFIX                                            = "_all_pfams_lost_as_dc";
265     public static final String                                BASE_DIRECTORY_PER_NODE_DOMAIN_GAIN_LOSS_FILES                         = "PER_NODE_EVENTS";
266     public static final String                                BASE_DIRECTORY_PER_SUBTREE_DOMAIN_GAIN_LOSS_FILES                      = "PER_SUBTREE_EVENTS";
267     public static final String                                D_PROMISCUITY_FILE_SUFFIX                                              = "_domain_promiscuities";
268     private static final String                               LOG_FILE_SUFFIX                                                        = "_log.txt";
269     private static final String                               DATA_FILE_SUFFIX                                                       = "_domain_combination_data.txt";
270     private static final String                               DATA_FILE_DESC                                                         = "#SPECIES\tPRTEIN_ID\tN_TERM_DOMAIN\tC_TERM_DOMAIN\tN_TERM_DOMAIN_PER_DOMAIN_E_VALUE\tC_TERM_DOMAIN_PER_DOMAIN_E_VALUE\tN_TERM_DOMAIN_COUNTS_PER_PROTEIN\tC_TERM_DOMAIN_COUNTS_PER_PROTEIN";
271     private static final INDIVIDUAL_SCORE_CUTOFF              INDIVIDUAL_SCORE_CUTOFF_DEFAULT                                        = INDIVIDUAL_SCORE_CUTOFF.FULL_SEQUENCE;
272     public static final String                                INDEPENDENT_DC_GAINS_FITCH_PARS_COUNTS_OUTPUT_SUFFIX                   = "_indep_dc_gains_fitch_counts.txt";
273     public static final String                                INDEPENDENT_DC_GAINS_FITCH_PARS_DC_OUTPUT_SUFFIX                       = "_indep_dc_gains_fitch_lists.txt";
274     public static final String                                INDEPENDENT_DC_GAINS_FITCH_PARS_DC_FOR_GO_MAPPING_OUTPUT_SUFFIX        = "_indep_dc_gains_fitch_lists_for_go_mapping.txt";
275
276     private static void checkWriteabilityForPairwiseComparisons( final PrintableDomainSimilarity.PRINT_OPTION domain_similarity_print_option,
277                                                                  final String[][] input_file_properties,
278                                                                  final String automated_pairwise_comparison_suffix,
279                                                                  final File outdir ) {
280         for( int i = 0; i < input_file_properties.length; ++i ) {
281             for( int j = 0; j < i; ++j ) {
282                 final String species_i = input_file_properties[ i ][ 1 ];
283                 final String species_j = input_file_properties[ j ][ 1 ];
284                 String pairwise_similarities_output_file_str = PAIRWISE_DOMAIN_COMPARISONS_PREFIX + species_i + "_"
285                         + species_j + automated_pairwise_comparison_suffix;
286                 switch ( domain_similarity_print_option ) {
287                     case HTML:
288                         if ( !pairwise_similarities_output_file_str.endsWith( ".html" ) ) {
289                             pairwise_similarities_output_file_str += ".html";
290                         }
291                         break;
292                 }
293                 final String error = ForesterUtil
294                         .isWritableFile( new File( outdir == null ? pairwise_similarities_output_file_str : outdir
295                                 + ForesterUtil.FILE_SEPARATOR + pairwise_similarities_output_file_str ) );
296                 if ( !ForesterUtil.isEmpty( error ) ) {
297                     ForesterUtil.fatalError( surfacing.PRG_NAME, error );
298                 }
299             }
300         }
301     }
302
303     private static StringBuilder createParametersAsString( final boolean ignore_dufs,
304                                                            final double e_value_max,
305                                                            final int max_allowed_overlap,
306                                                            final boolean no_engulfing_overlaps,
307                                                            final File cutoff_scores_file,
308                                                            final BinaryDomainCombination.DomainCombinationType dc_type ) {
309         final StringBuilder parameters_sb = new StringBuilder();
310         parameters_sb.append( "E-value: " + e_value_max );
311         if ( cutoff_scores_file != null ) {
312             parameters_sb.append( ", Cutoff-scores-file: " + cutoff_scores_file );
313         }
314         else {
315             parameters_sb.append( ", Cutoff-scores-file: not-set" );
316         }
317         if ( max_allowed_overlap != surfacing.MAX_ALLOWED_OVERLAP_DEFAULT ) {
318             parameters_sb.append( ", Max-overlap: " + max_allowed_overlap );
319         }
320         else {
321             parameters_sb.append( ", Max-overlap: not-set" );
322         }
323         if ( no_engulfing_overlaps ) {
324             parameters_sb.append( ", Engulfing-overlaps: not-allowed" );
325         }
326         else {
327             parameters_sb.append( ", Engulfing-overlaps: allowed" );
328         }
329         if ( ignore_dufs ) {
330             parameters_sb.append( ", Ignore-dufs: true" );
331         }
332         else {
333             parameters_sb.append( ", Ignore-dufs: false" );
334         }
335         parameters_sb.append( ", DC type (if applicable): " + dc_type );
336         return parameters_sb;
337     }
338
339     /**
340      * Warning: This side-effects 'all_bin_domain_combinations_encountered'!
341      * 
342      * 
343      * @param output_file
344      * @param all_bin_domain_combinations_changed
345      * @param sum_of_all_domains_encountered
346      * @param all_bin_domain_combinations_encountered
347      * @param is_gains_analysis
348      * @throws IOException
349      */
350     private static void executeFitchGainsAnalysis( final File output_file,
351                                                    final List<BinaryDomainCombination> all_bin_domain_combinations_changed,
352                                                    final int sum_of_all_domains_encountered,
353                                                    final SortedSet<BinaryDomainCombination> all_bin_domain_combinations_encountered,
354                                                    final boolean is_gains_analysis ) throws IOException {
355         SurfacingUtil.checkForOutputFileWriteability( output_file );
356         final Writer out = ForesterUtil.createBufferedWriter( output_file );
357         final SortedMap<Object, Integer> bdc_to_counts = ForesterUtil
358                 .listToSortedCountsMap( all_bin_domain_combinations_changed );
359         final SortedSet<DomainId> all_domains_in_combination_changed_more_than_once = new TreeSet<DomainId>();
360         final SortedSet<DomainId> all_domains_in_combination_changed_only_once = new TreeSet<DomainId>();
361         int above_one = 0;
362         int one = 0;
363         for( final Object bdc_object : bdc_to_counts.keySet() ) {
364             final BinaryDomainCombination bdc = ( BinaryDomainCombination ) bdc_object;
365             final int count = bdc_to_counts.get( bdc_object );
366             if ( count < 1 ) {
367                 ForesterUtil.unexpectedFatalError( PRG_NAME, "count < 1 " );
368             }
369             out.write( bdc + "\t" + count + ForesterUtil.LINE_SEPARATOR );
370             if ( count > 1 ) {
371                 all_domains_in_combination_changed_more_than_once.add( bdc.getId0() );
372                 all_domains_in_combination_changed_more_than_once.add( bdc.getId1() );
373                 above_one++;
374             }
375             else if ( count == 1 ) {
376                 all_domains_in_combination_changed_only_once.add( bdc.getId0() );
377                 all_domains_in_combination_changed_only_once.add( bdc.getId1() );
378                 one++;
379             }
380         }
381         final int all = all_bin_domain_combinations_encountered.size();
382         int never_lost = -1;
383         if ( !is_gains_analysis ) {
384             all_bin_domain_combinations_encountered.removeAll( all_bin_domain_combinations_changed );
385             never_lost = all_bin_domain_combinations_encountered.size();
386             for( final BinaryDomainCombination bdc : all_bin_domain_combinations_encountered ) {
387                 out.write( bdc + "\t" + "0" + ForesterUtil.LINE_SEPARATOR );
388             }
389         }
390         if ( is_gains_analysis ) {
391             out.write( "Sum of all distinct domain combinations appearing once               : " + one
392                     + ForesterUtil.LINE_SEPARATOR );
393             out.write( "Sum of all distinct domain combinations appearing more than once     : " + above_one
394                     + ForesterUtil.LINE_SEPARATOR );
395             out.write( "Sum of all distinct domains in combinations apppearing only once     : "
396                     + all_domains_in_combination_changed_only_once.size() + ForesterUtil.LINE_SEPARATOR );
397             out.write( "Sum of all distinct domains in combinations apppearing more than once: "
398                     + all_domains_in_combination_changed_more_than_once.size() + ForesterUtil.LINE_SEPARATOR );
399         }
400         else {
401             out.write( "Sum of all distinct domain combinations never lost                   : " + never_lost
402                     + ForesterUtil.LINE_SEPARATOR );
403             out.write( "Sum of all distinct domain combinations lost once                    : " + one
404                     + ForesterUtil.LINE_SEPARATOR );
405             out.write( "Sum of all distinct domain combinations lost more than once          : " + above_one
406                     + ForesterUtil.LINE_SEPARATOR );
407             out.write( "Sum of all distinct domains in combinations lost only once           : "
408                     + all_domains_in_combination_changed_only_once.size() + ForesterUtil.LINE_SEPARATOR );
409             out.write( "Sum of all distinct domains in combinations lost more than once: "
410                     + all_domains_in_combination_changed_more_than_once.size() + ForesterUtil.LINE_SEPARATOR );
411         }
412         out.write( "All binary combinations                                              : " + all
413                 + ForesterUtil.LINE_SEPARATOR );
414         out.write( "All domains                                                          : "
415                 + sum_of_all_domains_encountered );
416         out.close();
417         ForesterUtil.programMessage( surfacing.PRG_NAME,
418                                      "Wrote fitch domain combination dynamics counts analysis to \"" + output_file
419                                              + "\"" );
420     }
421
422     private static void executePlusMinusAnalysis( final File output_file,
423                                                   final List<String> plus_minus_analysis_high_copy_base,
424                                                   final List<String> plus_minus_analysis_high_copy_target,
425                                                   final List<String> plus_minus_analysis_low_copy,
426                                                   final List<GenomeWideCombinableDomains> gwcd_list,
427                                                   final SortedMap<Species, List<Protein>> protein_lists_per_species,
428                                                   final Map<DomainId, List<GoId>> domain_id_to_go_ids_map,
429                                                   final Map<GoId, GoTerm> go_id_to_term_map,
430                                                   final List<Object> plus_minus_analysis_numbers ) {
431         final Set<String> all_spec = new HashSet<String>();
432         for( final GenomeWideCombinableDomains gwcd : gwcd_list ) {
433             all_spec.add( gwcd.getSpecies().getSpeciesId() );
434         }
435         final File html_out_dom = new File( output_file + PLUS_MINUS_DOM_SUFFIX_HTML );
436         final File plain_out_dom = new File( output_file + PLUS_MINUS_DOM_SUFFIX );
437         final File html_out_dc = new File( output_file + PLUS_MINUS_DC_SUFFIX_HTML );
438         final File all_domains_go_ids_out_dom = new File( output_file + PLUS_MINUS_ALL_GO_IDS_DOM_SUFFIX );
439         final File passing_domains_go_ids_out_dom = new File( output_file + PLUS_MINUS_PASSING_GO_IDS_DOM_SUFFIX );
440         final File proteins_file_base = new File( output_file + "" );
441         final int min_diff = ( ( Integer ) plus_minus_analysis_numbers.get( 0 ) ).intValue();
442         final double factor = ( ( Double ) plus_minus_analysis_numbers.get( 1 ) ).doubleValue();
443         try {
444             DomainCountsDifferenceUtil.calculateCopyNumberDifferences( gwcd_list,
445                                                                        protein_lists_per_species,
446                                                                        plus_minus_analysis_high_copy_base,
447                                                                        plus_minus_analysis_high_copy_target,
448                                                                        plus_minus_analysis_low_copy,
449                                                                        min_diff,
450                                                                        factor,
451                                                                        plain_out_dom,
452                                                                        html_out_dom,
453                                                                        html_out_dc,
454                                                                        domain_id_to_go_ids_map,
455                                                                        go_id_to_term_map,
456                                                                        all_domains_go_ids_out_dom,
457                                                                        passing_domains_go_ids_out_dom,
458                                                                        proteins_file_base );
459         }
460         catch ( final IOException e ) {
461             ForesterUtil.fatalError( surfacing.PRG_NAME, e.getLocalizedMessage() );
462         }
463         ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote plus minus domain analysis results to \""
464                 + html_out_dom + "\"" );
465         ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote plus minus domain analysis results to \""
466                 + plain_out_dom + "\"" );
467         ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote plus minus domain analysis results to \"" + html_out_dc
468                 + "\"" );
469         ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote plus minus domain analysis based passing GO ids to \""
470                 + passing_domains_go_ids_out_dom + "\"" );
471         ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote plus minus domain analysis based all GO ids to \""
472                 + all_domains_go_ids_out_dom + "\"" );
473     }
474
475     private static Phylogeny[] getIntrees( final File[] intree_files,
476                                            final int number_of_genomes,
477                                            final String[][] input_file_properties ) {
478         final Phylogeny[] intrees = new Phylogeny[ intree_files.length ];
479         int i = 0;
480         for( final File intree_file : intree_files ) {
481             Phylogeny intree = null;
482             final String error = ForesterUtil.isReadableFile( intree_file );
483             if ( !ForesterUtil.isEmpty( error ) ) {
484                 ForesterUtil.fatalError( surfacing.PRG_NAME, "cannot read input tree file [" + intree_file + "]: "
485                         + error );
486             }
487             try {
488                 final Phylogeny[] p_array = ParserBasedPhylogenyFactory.getInstance()
489                         .create( intree_file, ForesterUtil.createParserDependingOnFileType( intree_file, true ) );
490                 if ( p_array.length < 1 ) {
491                     ForesterUtil.fatalError( surfacing.PRG_NAME, "file [" + intree_file
492                             + "] does not contain any phylogeny in phyloXML format" );
493                 }
494                 else if ( p_array.length > 1 ) {
495                     ForesterUtil.fatalError( surfacing.PRG_NAME, "file [" + intree_file
496                             + "] contains more than one phylogeny in phyloXML format" );
497                 }
498                 intree = p_array[ 0 ];
499             }
500             catch ( final Exception e ) {
501                 ForesterUtil.fatalError( surfacing.PRG_NAME, "failed to read input tree from file [" + intree_file
502                         + "]: " + error );
503             }
504             if ( ( intree == null ) || intree.isEmpty() ) {
505                 ForesterUtil.fatalError( surfacing.PRG_NAME, "input tree [" + intree_file + "] is empty" );
506             }
507             if ( !intree.isRooted() ) {
508                 ForesterUtil.fatalError( surfacing.PRG_NAME, "input tree [" + intree_file + "] is not rooted" );
509             }
510             if ( intree.getNumberOfExternalNodes() < number_of_genomes ) {
511                 ForesterUtil.fatalError( surfacing.PRG_NAME,
512                                          "number of external nodes [" + intree.getNumberOfExternalNodes()
513                                                  + "] of input tree [" + intree_file
514                                                  + "] is smaller than the number of genomes the be analyzed ["
515                                                  + number_of_genomes + "]" );
516             }
517             final StringBuilder parent_names = new StringBuilder();
518             final int nodes_lacking_name = SurfacingUtil.getNumberOfNodesLackingName( intree, parent_names );
519             if ( nodes_lacking_name > 0 ) {
520                 ForesterUtil.fatalError( surfacing.PRG_NAME, "input tree [" + intree_file + "] has "
521                         + nodes_lacking_name + " node(s) lacking a name [parent names:" + parent_names + "]" );
522             }
523             preparePhylogenyForParsimonyAnalyses( intree, input_file_properties );
524             if ( !intree.isCompletelyBinary() ) {
525                 ForesterUtil.printWarningMessage( surfacing.PRG_NAME, "input tree [" + intree_file
526                         + "] is not completely binary" );
527             }
528             intrees[ i++ ] = intree;
529         }
530         return intrees;
531     }
532
533     private static List<Phylogeny> inferSpeciesTrees( final File outfile, final List<DistanceMatrix> distances_list ) {
534         final NeighborJoining nj = NeighborJoining.createInstance();
535         final List<Phylogeny> phylogenies = nj.execute( distances_list );
536         final PhylogenyWriter w = new PhylogenyWriter();
537         try {
538             w.toNewHampshire( phylogenies, true, true, outfile, ";" );
539         }
540         catch ( final IOException e ) {
541             ForesterUtil.fatalError( PRG_NAME, "failed to write to outfile [" + outfile + "]: " + e.getMessage() );
542         }
543         return phylogenies;
544     }
545
546     private static void log( final String msg, final Writer w ) {
547         try {
548             w.write( msg );
549             w.write( ForesterUtil.LINE_SEPARATOR );
550         }
551         catch ( final IOException e ) {
552             ForesterUtil.fatalError( surfacing.PRG_NAME, e.getLocalizedMessage() );
553         }
554     }
555
556     public static void main( final String args[] ) {
557         final long start_time = new Date().getTime();
558         // final StringBuffer log = new StringBuffer();
559         final StringBuilder html_desc = new StringBuilder();
560         ForesterUtil.printProgramInformation( surfacing.PRG_NAME,
561                                               surfacing.PRG_VERSION,
562                                               surfacing.PRG_DATE,
563                                               surfacing.E_MAIL,
564                                               surfacing.WWW );
565         final String nl = ForesterUtil.LINE_SEPARATOR;
566         html_desc.append( "<table>" + nl );
567         html_desc.append( "<tr><td>Produced by:</td><td>" + surfacing.PRG_NAME + "</td></tr>" + nl );
568         html_desc.append( "<tr><td>Version:</td><td>" + surfacing.PRG_VERSION + "</td></tr>" + nl );
569         html_desc.append( "<tr><td>Release Date:</td><td>" + surfacing.PRG_DATE + "</td></tr>" + nl );
570         html_desc.append( "<tr><td>Contact:</td><td>" + surfacing.E_MAIL + "</td></tr>" + nl );
571         html_desc.append( "<tr><td>WWW:</td><td>" + surfacing.WWW + "</td></tr>" + nl );
572         CommandLineArguments cla = null;
573         try {
574             cla = new CommandLineArguments( args );
575         }
576         catch ( final Exception e ) {
577             ForesterUtil.fatalError( surfacing.PRG_NAME, e.getMessage() );
578         }
579         if ( cla.isOptionSet( surfacing.HELP_OPTION_1 ) || cla.isOptionSet( surfacing.HELP_OPTION_2 ) ) {
580             surfacing.printHelp();
581             System.exit( 0 );
582         }
583         if ( ( args.length < 1 ) ) {
584             surfacing.printHelp();
585             System.exit( -1 );
586         }
587         final List<String> allowed_options = new ArrayList<String>();
588         allowed_options.add( surfacing.NOT_IGNORE_DUFS_OPTION );
589         allowed_options.add( surfacing.MAX_E_VALUE_OPTION );
590         allowed_options.add( surfacing.DETAILEDNESS_OPTION );
591         allowed_options.add( surfacing.OUTPUT_FILE_OPTION );
592         allowed_options.add( surfacing.DOMAIN_SIMILARITY_SORT_OPTION );
593         allowed_options.add( surfacing.SPECIES_MATRIX_OPTION );
594         allowed_options.add( surfacing.SCORING_OPTION );
595         allowed_options.add( surfacing.MAX_ALLOWED_OVERLAP_OPTION );
596         allowed_options.add( surfacing.NO_ENGULFING_OVERLAP_OPTION );
597         allowed_options.add( surfacing.DOMAIN_COUNT_SORT_OPTION );
598         allowed_options.add( surfacing.CUTOFF_SCORE_FILE_OPTION );
599         allowed_options.add( surfacing.DOMAIN_SIMILARITY_SORT_BY_SPECIES_COUNT_FIRST_OPTION );
600         allowed_options.add( surfacing.OUTPUT_DIR_OPTION );
601         allowed_options.add( surfacing.IGNORE_COMBINATION_WITH_SAME_OPTION );
602         allowed_options.add( surfacing.PFAM_TO_GO_FILE_USE_OPTION );
603         allowed_options.add( surfacing.GO_OBO_FILE_USE_OPTION );
604         allowed_options.add( surfacing.DOMAIN_SIMILARITY_PRINT_OPTION );
605         allowed_options.add( surfacing.GO_NAMESPACE_LIMIT_OPTION );
606         allowed_options.add( surfacing.PAIRWISE_DOMAIN_COMPARISONS_OPTION );
607         allowed_options.add( surfacing.IGNORE_DOMAINS_WITHOUT_COMBINATIONS_IN_ALL_SPECIES_OPTION );
608         allowed_options.add( surfacing.CONSIDER_DOMAIN_COMBINATION_DIRECTEDNESS );
609         allowed_options.add( JACKNIFE_OPTION );
610         allowed_options.add( JACKNIFE_RANDOM_SEED_OPTION );
611         allowed_options.add( JACKNIFE_RATIO_OPTION );
612         allowed_options.add( INPUT_SPECIES_TREE_OPTION );
613         //allowed_options.add( INFER_SPECIES_TREES_OPTION );
614         allowed_options.add( FILTER_POSITIVE_OPTION );
615         allowed_options.add( FILTER_NEGATIVE_OPTION );
616         allowed_options.add( INPUT_FILES_FROM_FILE_OPTION );
617         allowed_options.add( RANDOM_SEED_FOR_FITCH_PARSIMONY_OPTION );
618         allowed_options.add( FILTER_NEGATIVE_DOMAINS_OPTION );
619         allowed_options.add( IGNORE_VIRAL_IDS );
620         allowed_options.add( SEQ_EXTRACT_OPTION );
621         allowed_options.add( SECONDARY_FEATURES_PARSIMONY_MAP_FILE );
622         allowed_options.add( PLUS_MINUS_ANALYSIS_OPTION );
623         allowed_options.add( DOMAIN_COMBINITONS_OUTPUT_OPTION_FOR_GRAPH_ANALYSIS );
624         allowed_options.add( OUTPUT_LIST_OF_ALL_PROTEINS_OPTIONS );
625         allowed_options.add( CONSIDER_DOMAIN_COMBINATION_DIRECTEDNESS_AND_ADJACENCY );
626         boolean ignore_dufs = surfacing.IGNORE_DUFS_DEFAULT;
627         boolean ignore_combination_with_same = surfacing.IGNORE_COMBINATION_WITH_SAME_DEFAULLT;
628         double e_value_max = surfacing.MAX_E_VALUE_DEFAULT;
629         int max_allowed_overlap = surfacing.MAX_ALLOWED_OVERLAP_DEFAULT;
630         final String dissallowed_options = cla.validateAllowedOptionsAsString( allowed_options );
631         if ( dissallowed_options.length() > 0 ) {
632             ForesterUtil.fatalError( surfacing.PRG_NAME, "unknown option(s): " + dissallowed_options );
633         }
634         boolean output_binary_domain_combinationsfor_graph_analysis = false;
635         if ( cla.isOptionSet( DOMAIN_COMBINITONS_OUTPUT_OPTION_FOR_GRAPH_ANALYSIS ) ) {
636             output_binary_domain_combinationsfor_graph_analysis = true;
637         }
638         if ( cla.isOptionSet( surfacing.MAX_E_VALUE_OPTION ) ) {
639             try {
640                 e_value_max = cla.getOptionValueAsDouble( surfacing.MAX_E_VALUE_OPTION );
641             }
642             catch ( final Exception e ) {
643                 ForesterUtil.fatalError( surfacing.PRG_NAME, "no acceptable value for E-value maximum" );
644             }
645         }
646         if ( cla.isOptionSet( surfacing.MAX_ALLOWED_OVERLAP_OPTION ) ) {
647             try {
648                 max_allowed_overlap = cla.getOptionValueAsInt( surfacing.MAX_ALLOWED_OVERLAP_OPTION );
649             }
650             catch ( final Exception e ) {
651                 ForesterUtil.fatalError( surfacing.PRG_NAME, "no acceptable value for maximal allowed domain overlap" );
652             }
653         }
654         boolean no_engulfing_overlaps = false;
655         if ( cla.isOptionSet( surfacing.NO_ENGULFING_OVERLAP_OPTION ) ) {
656             no_engulfing_overlaps = true;
657         }
658         boolean ignore_virus_like_ids = false;
659         if ( cla.isOptionSet( surfacing.IGNORE_VIRAL_IDS ) ) {
660             ignore_virus_like_ids = true;
661         }
662         if ( cla.isOptionSet( surfacing.NOT_IGNORE_DUFS_OPTION ) ) {
663             ignore_dufs = false;
664         }
665         if ( cla.isOptionSet( surfacing.IGNORE_COMBINATION_WITH_SAME_OPTION ) ) {
666             ignore_combination_with_same = true;
667         }
668         boolean ignore_domains_without_combs_in_all_spec = IGNORE_DOMAINS_WITHOUT_COMBINATIONS_IN_ALL_SPECIES_DEFAULT;
669         if ( cla.isOptionSet( surfacing.IGNORE_DOMAINS_WITHOUT_COMBINATIONS_IN_ALL_SPECIES_OPTION ) ) {
670             ignore_domains_without_combs_in_all_spec = true;
671         }
672         boolean ignore_species_specific_domains = IGNORE_DOMAINS_SPECIFIC_TO_ONE_SPECIES_OPTION_DEFAULT;
673         if ( cla.isOptionSet( surfacing.IGNORE_DOMAINS_SPECIFIC_TO_ONE_SPECIES_OPTION ) ) {
674             ignore_species_specific_domains = true;
675         }
676         File output_file = null;
677         if ( cla.isOptionSet( surfacing.OUTPUT_FILE_OPTION ) ) {
678             if ( !cla.isOptionValueSet( surfacing.OUTPUT_FILE_OPTION ) ) {
679                 ForesterUtil.fatalError( surfacing.PRG_NAME,
680                                          "no value for domain combinations similarities output file: -"
681                                                  + surfacing.OUTPUT_FILE_OPTION + "=<file>" );
682             }
683             output_file = new File( cla.getOptionValue( surfacing.OUTPUT_FILE_OPTION ) );
684             SurfacingUtil.checkForOutputFileWriteability( output_file );
685         }
686         File cutoff_scores_file = null;
687         Map<String, Double> individual_score_cutoffs = null;
688         if ( cla.isOptionSet( surfacing.CUTOFF_SCORE_FILE_OPTION ) ) {
689             if ( !cla.isOptionValueSet( surfacing.CUTOFF_SCORE_FILE_OPTION ) ) {
690                 ForesterUtil.fatalError( surfacing.PRG_NAME, "no value for individual domain score cutoffs file: -"
691                         + surfacing.CUTOFF_SCORE_FILE_OPTION + "=<file>" );
692             }
693             cutoff_scores_file = new File( cla.getOptionValue( surfacing.CUTOFF_SCORE_FILE_OPTION ) );
694             final String error = ForesterUtil.isReadableFile( cutoff_scores_file );
695             if ( !ForesterUtil.isEmpty( error ) ) {
696                 ForesterUtil.fatalError( surfacing.PRG_NAME, "cannot read individual domain score cutoffs file: "
697                         + error );
698             }
699             try {
700                 final BasicTable<String> scores_table = BasicTableParser.parse( cutoff_scores_file, " " );
701                 individual_score_cutoffs = scores_table.getColumnsAsMapDouble( 0, 1 );
702             }
703             catch ( final IOException e ) {
704                 ForesterUtil.fatalError( surfacing.PRG_NAME, "cannot read from individual score cutoffs file: " + e );
705             }
706         }
707         BinaryDomainCombination.DomainCombinationType dc_type = BinaryDomainCombination.DomainCombinationType.BASIC;
708         if ( cla.isOptionSet( surfacing.CONSIDER_DOMAIN_COMBINATION_DIRECTEDNESS ) ) {
709             dc_type = BinaryDomainCombination.DomainCombinationType.DIRECTED;
710         }
711         if ( cla.isOptionSet( surfacing.CONSIDER_DOMAIN_COMBINATION_DIRECTEDNESS_AND_ADJACENCY ) ) {
712             dc_type = BinaryDomainCombination.DomainCombinationType.DIRECTED_ADJACTANT;
713         }
714         File out_dir = null;
715         if ( cla.isOptionSet( surfacing.OUTPUT_DIR_OPTION ) ) {
716             if ( !cla.isOptionValueSet( surfacing.OUTPUT_DIR_OPTION ) ) {
717                 ForesterUtil.fatalError( surfacing.PRG_NAME, "no value for output directory: -"
718                         + surfacing.OUTPUT_DIR_OPTION + "=<dir>" );
719             }
720             out_dir = new File( cla.getOptionValue( surfacing.OUTPUT_DIR_OPTION ) );
721             if ( out_dir.exists() && ( out_dir.listFiles().length > 0 ) ) {
722                 ForesterUtil.fatalError( surfacing.PRG_NAME, "\"" + out_dir + "\" aready exists and is not empty" );
723             }
724             if ( !out_dir.exists() ) {
725                 final boolean success = out_dir.mkdir();
726                 if ( !success || !out_dir.exists() ) {
727                     ForesterUtil.fatalError( surfacing.PRG_NAME, "failed to create \"" + out_dir + "\"" );
728                 }
729             }
730             if ( !out_dir.canWrite() ) {
731                 ForesterUtil.fatalError( surfacing.PRG_NAME, "cannot write to \"" + out_dir + "\"" );
732             }
733         }
734         File positive_filter_file = null;
735         File negative_filter_file = null;
736         File negative_domains_filter_file = null;
737         if ( cla.isOptionSet( surfacing.FILTER_NEGATIVE_OPTION ) && cla.isOptionSet( surfacing.FILTER_POSITIVE_OPTION ) ) {
738             ForesterUtil.fatalError( surfacing.PRG_NAME, "attempt to use both negative and positive protein filter" );
739         }
740         if ( cla.isOptionSet( surfacing.FILTER_NEGATIVE_DOMAINS_OPTION )
741                 && ( cla.isOptionSet( surfacing.FILTER_NEGATIVE_OPTION ) || cla
742                         .isOptionSet( surfacing.FILTER_POSITIVE_OPTION ) ) ) {
743             ForesterUtil
744                     .fatalError( surfacing.PRG_NAME,
745                                  "attempt to use both negative or positive protein filter together wirh a negative domains filter" );
746         }
747         if ( cla.isOptionSet( surfacing.FILTER_NEGATIVE_OPTION ) ) {
748             if ( !cla.isOptionValueSet( surfacing.FILTER_NEGATIVE_OPTION ) ) {
749                 ForesterUtil.fatalError( surfacing.PRG_NAME, "no value for negative filter: -"
750                         + surfacing.FILTER_NEGATIVE_OPTION + "=<file>" );
751             }
752             negative_filter_file = new File( cla.getOptionValue( surfacing.FILTER_NEGATIVE_OPTION ) );
753             final String msg = ForesterUtil.isReadableFile( negative_filter_file );
754             if ( !ForesterUtil.isEmpty( msg ) ) {
755                 ForesterUtil.fatalError( surfacing.PRG_NAME, "can not read from \"" + negative_filter_file + "\": "
756                         + msg );
757             }
758         }
759         else if ( cla.isOptionSet( surfacing.FILTER_POSITIVE_OPTION ) ) {
760             if ( !cla.isOptionValueSet( surfacing.FILTER_POSITIVE_OPTION ) ) {
761                 ForesterUtil.fatalError( surfacing.PRG_NAME, "no value for positive filter: -"
762                         + surfacing.FILTER_POSITIVE_OPTION + "=<file>" );
763             }
764             positive_filter_file = new File( cla.getOptionValue( surfacing.FILTER_POSITIVE_OPTION ) );
765             final String msg = ForesterUtil.isReadableFile( positive_filter_file );
766             if ( !ForesterUtil.isEmpty( msg ) ) {
767                 ForesterUtil.fatalError( surfacing.PRG_NAME, "can not read from \"" + positive_filter_file + "\": "
768                         + msg );
769             }
770         }
771         else if ( cla.isOptionSet( surfacing.FILTER_NEGATIVE_DOMAINS_OPTION ) ) {
772             if ( !cla.isOptionValueSet( surfacing.FILTER_NEGATIVE_DOMAINS_OPTION ) ) {
773                 ForesterUtil.fatalError( surfacing.PRG_NAME, "no value for negative domains filter: -"
774                         + surfacing.FILTER_NEGATIVE_DOMAINS_OPTION + "=<file>" );
775             }
776             negative_domains_filter_file = new File( cla.getOptionValue( surfacing.FILTER_NEGATIVE_DOMAINS_OPTION ) );
777             final String msg = ForesterUtil.isReadableFile( negative_domains_filter_file );
778             if ( !ForesterUtil.isEmpty( msg ) ) {
779                 ForesterUtil.fatalError( surfacing.PRG_NAME, "can not read from \"" + negative_domains_filter_file
780                         + "\": " + msg );
781             }
782         }
783         final List<String> plus_minus_analysis_high_copy_base_species = new ArrayList<String>();
784         final List<String> plus_minus_analysis_high_copy_target_species = new ArrayList<String>();
785         final List<String> plus_minus_analysis_high_low_copy_species = new ArrayList<String>();
786         final List<Object> plus_minus_analysis_numbers = new ArrayList<Object>();
787         processPlusMinusAnalysisOption( cla,
788                                         plus_minus_analysis_high_copy_base_species,
789                                         plus_minus_analysis_high_copy_target_species,
790                                         plus_minus_analysis_high_low_copy_species,
791                                         plus_minus_analysis_numbers );
792         File input_files_file = null;
793         String[] input_file_names_from_file = null;
794         if ( cla.isOptionSet( surfacing.INPUT_FILES_FROM_FILE_OPTION ) ) {
795             if ( !cla.isOptionValueSet( surfacing.INPUT_FILES_FROM_FILE_OPTION ) ) {
796                 ForesterUtil.fatalError( surfacing.PRG_NAME, "no value for input files file: -"
797                         + surfacing.INPUT_FILES_FROM_FILE_OPTION + "=<file>" );
798             }
799             input_files_file = new File( cla.getOptionValue( surfacing.INPUT_FILES_FROM_FILE_OPTION ) );
800             final String msg = ForesterUtil.isReadableFile( input_files_file );
801             if ( !ForesterUtil.isEmpty( msg ) ) {
802                 ForesterUtil.fatalError( surfacing.PRG_NAME, "can not read from \"" + input_files_file + "\": " + msg );
803             }
804             try {
805                 input_file_names_from_file = ForesterUtil.file2array( input_files_file );
806             }
807             catch ( final IOException e ) {
808                 ForesterUtil.fatalError( surfacing.PRG_NAME, "failed to read from \"" + input_files_file + "\": " + e );
809             }
810         }
811         if ( ( cla.getNumberOfNames() < 1 )
812                 && ( ( input_file_names_from_file == null ) || ( input_file_names_from_file.length < 1 ) ) ) {
813             ForesterUtil.fatalError( surfacing.PRG_NAME,
814                                      "No hmmpfam output file indicated is input: use comand line directly or "
815                                              + surfacing.INPUT_FILES_FROM_FILE_OPTION + "=<file>" );
816         }
817         DomainSimilarity.DomainSimilarityScoring scoring = SCORING_DEFAULT;
818         if ( cla.isOptionSet( surfacing.SCORING_OPTION ) ) {
819             if ( !cla.isOptionValueSet( surfacing.SCORING_OPTION ) ) {
820                 ForesterUtil.fatalError( surfacing.PRG_NAME,
821                                          "no value for scoring method for domain combinations similarity calculation: -"
822                                                  + surfacing.SCORING_OPTION + "=<"
823                                                  + surfacing.SCORING_DOMAIN_COUNT_BASED + "|"
824                                                  + surfacing.SCORING_PROTEIN_COUNT_BASED + "|"
825                                                  + surfacing.SCORING_COMBINATION_BASED + ">\"" );
826             }
827             final String scoring_str = cla.getOptionValue( surfacing.SCORING_OPTION );
828             if ( scoring_str.equals( surfacing.SCORING_DOMAIN_COUNT_BASED ) ) {
829                 scoring = DomainSimilarity.DomainSimilarityScoring.DOMAINS;
830             }
831             else if ( scoring_str.equals( surfacing.SCORING_COMBINATION_BASED ) ) {
832                 scoring = DomainSimilarity.DomainSimilarityScoring.COMBINATIONS;
833             }
834             else if ( scoring_str.equals( surfacing.SCORING_PROTEIN_COUNT_BASED ) ) {
835                 scoring = DomainSimilarity.DomainSimilarityScoring.PROTEINS;
836             }
837             else {
838                 ForesterUtil.fatalError( surfacing.PRG_NAME, "unknown value \"" + scoring_str
839                         + "\" for scoring method for domain combinations similarity calculation: \"-"
840                         + surfacing.SCORING_OPTION + "=<" + surfacing.SCORING_DOMAIN_COUNT_BASED + "|"
841                         + surfacing.SCORING_PROTEIN_COUNT_BASED + "|" + surfacing.SCORING_COMBINATION_BASED + ">\"" );
842             }
843         }
844         boolean sort_by_species_count_first = false;
845         if ( cla.isOptionSet( surfacing.DOMAIN_SIMILARITY_SORT_BY_SPECIES_COUNT_FIRST_OPTION ) ) {
846             sort_by_species_count_first = true;
847         }
848         boolean species_matrix = false;
849         if ( cla.isOptionSet( surfacing.SPECIES_MATRIX_OPTION ) ) {
850             species_matrix = true;
851         }
852         boolean output_protein_lists_for_all_domains = false;
853         if ( cla.isOptionSet( surfacing.OUTPUT_LIST_OF_ALL_PROTEINS_OPTIONS ) ) {
854             output_protein_lists_for_all_domains = true;
855         }
856         Detailedness detailedness = DETAILEDNESS_DEFAULT;
857         if ( cla.isOptionSet( surfacing.DETAILEDNESS_OPTION ) ) {
858             if ( !cla.isOptionValueSet( surfacing.DETAILEDNESS_OPTION ) ) {
859                 ForesterUtil.fatalError( surfacing.PRG_NAME, "no value for -" + surfacing.DETAILEDNESS_OPTION + "=<"
860                         + surfacing.DETAILEDNESS_BASIC + "|" + surfacing.DETAILEDNESS_LIST_IDS + "|"
861                         + surfacing.DETAILEDNESS_PUNCTILIOUS + ">\"" );
862             }
863             final String detness = cla.getOptionValue( surfacing.DETAILEDNESS_OPTION ).toLowerCase();
864             if ( detness.equals( surfacing.DETAILEDNESS_BASIC ) ) {
865                 detailedness = DomainSimilarityCalculator.Detailedness.BASIC;
866             }
867             else if ( detness.equals( surfacing.DETAILEDNESS_LIST_IDS ) ) {
868                 detailedness = DomainSimilarityCalculator.Detailedness.LIST_COMBINING_DOMAIN_FOR_EACH_SPECIES;
869             }
870             else if ( detness.equals( surfacing.DETAILEDNESS_PUNCTILIOUS ) ) {
871                 detailedness = DomainSimilarityCalculator.Detailedness.PUNCTILIOUS;
872             }
873             else {
874                 ForesterUtil.fatalError( surfacing.PRG_NAME, "unknown value \"" + detness + "\" for detailedness: \"-"
875                         + surfacing.DETAILEDNESS_OPTION + "=<" + surfacing.DETAILEDNESS_BASIC + "|"
876                         + surfacing.DETAILEDNESS_LIST_IDS + "|" + surfacing.DETAILEDNESS_PUNCTILIOUS + ">\"" );
877             }
878         }
879         String automated_pairwise_comparison_suffix = null;
880         boolean perform_pwc = false;
881         boolean write_pwc_files = false;
882         if ( cla.isOptionSet( surfacing.PAIRWISE_DOMAIN_COMPARISONS_OPTION ) ) {
883             perform_pwc = true;
884             if ( !cla.isOptionValueSet( surfacing.PAIRWISE_DOMAIN_COMPARISONS_OPTION ) ) {
885                 write_pwc_files = false;
886             }
887             else {
888                 write_pwc_files = true;
889                 automated_pairwise_comparison_suffix = "_"
890                         + cla.getOptionValue( surfacing.PAIRWISE_DOMAIN_COMPARISONS_OPTION );
891             }
892         }
893         String query_domain_ids = null;
894         if ( cla.isOptionSet( surfacing.SEQ_EXTRACT_OPTION ) ) {
895             if ( !cla.isOptionValueSet( surfacing.SEQ_EXTRACT_OPTION ) ) {
896                 ForesterUtil
897                         .fatalError( surfacing.PRG_NAME,
898                                      "no domain ids given for sequences with given domains to be extracted : -"
899                                              + surfacing.SEQ_EXTRACT_OPTION
900                                              + "=<ordered domain sequences, domain ids separated by '~', sequences separated by '#'>" );
901             }
902             query_domain_ids = cla.getOptionValue( surfacing.SEQ_EXTRACT_OPTION );
903         }
904         DomainSimilarity.DomainSimilaritySortField domain_similarity_sort_field = DOMAIN_SORT_FILD_DEFAULT;
905         DomainSimilarity.DomainSimilaritySortField domain_similarity_sort_field_for_automated_pwc = DOMAIN_SORT_FILD_DEFAULT;
906         if ( cla.isOptionSet( surfacing.DOMAIN_SIMILARITY_SORT_OPTION ) ) {
907             if ( !cla.isOptionValueSet( surfacing.DOMAIN_SIMILARITY_SORT_OPTION ) ) {
908                 ForesterUtil.fatalError( surfacing.PRG_NAME, "no value for domain combinations similarities sorting: -"
909                         + surfacing.DOMAIN_SIMILARITY_SORT_OPTION + "=<" + surfacing.DOMAIN_SIMILARITY_SORT_ALPHA + "|"
910                         + surfacing.DOMAIN_SIMILARITY_SORT_MAX + "|" + surfacing.DOMAIN_SIMILARITY_SORT_MIN + "|"
911                         + surfacing.DOMAIN_SIMILARITY_SORT_MEAN + "|" + surfacing.DOMAIN_SIMILARITY_SORT_DIFF + "|"
912                         + surfacing.DOMAIN_SIMILARITY_SORT_ABS_COUNTS_DIFF + "|"
913                         + surfacing.DOMAIN_SIMILARITY_SORT_COUNTS_DIFF + "|"
914                         + surfacing.DOMAIN_SIMILARITY_SORT_SPECIES_COUNT + "|" + surfacing.DOMAIN_SIMILARITY_SORT_SD
915                         + ">\"" );
916             }
917             final String sort_str = cla.getOptionValue( surfacing.DOMAIN_SIMILARITY_SORT_OPTION ).toLowerCase();
918             if ( sort_str.equals( surfacing.DOMAIN_SIMILARITY_SORT_ALPHA ) ) {
919                 domain_similarity_sort_field = DomainSimilarity.DomainSimilaritySortField.DOMAIN_ID;
920                 domain_similarity_sort_field_for_automated_pwc = DomainSimilarity.DomainSimilaritySortField.DOMAIN_ID;
921             }
922             else if ( sort_str.equals( surfacing.DOMAIN_SIMILARITY_SORT_MAX ) ) {
923                 domain_similarity_sort_field = DomainSimilarity.DomainSimilaritySortField.MAX;
924                 domain_similarity_sort_field_for_automated_pwc = DomainSimilarity.DomainSimilaritySortField.DOMAIN_ID;
925             }
926             else if ( sort_str.equals( surfacing.DOMAIN_SIMILARITY_SORT_MIN ) ) {
927                 domain_similarity_sort_field = DomainSimilarity.DomainSimilaritySortField.MIN;
928                 domain_similarity_sort_field_for_automated_pwc = DomainSimilarity.DomainSimilaritySortField.DOMAIN_ID;
929             }
930             else if ( sort_str.equals( surfacing.DOMAIN_SIMILARITY_SORT_MEAN ) ) {
931                 domain_similarity_sort_field = DomainSimilarity.DomainSimilaritySortField.MEAN;
932                 domain_similarity_sort_field_for_automated_pwc = DomainSimilarity.DomainSimilaritySortField.MEAN;
933             }
934             else if ( sort_str.equals( surfacing.DOMAIN_SIMILARITY_SORT_SPECIES_COUNT ) ) {
935                 domain_similarity_sort_field = DomainSimilarity.DomainSimilaritySortField.SPECIES_COUNT;
936                 domain_similarity_sort_field_for_automated_pwc = DomainSimilarity.DomainSimilaritySortField.DOMAIN_ID;
937             }
938             else if ( sort_str.equals( surfacing.DOMAIN_SIMILARITY_SORT_SD ) ) {
939                 domain_similarity_sort_field = DomainSimilarity.DomainSimilaritySortField.SD;
940                 domain_similarity_sort_field_for_automated_pwc = DomainSimilarity.DomainSimilaritySortField.DOMAIN_ID;
941             }
942             else if ( sort_str.equals( surfacing.DOMAIN_SIMILARITY_SORT_DIFF ) ) {
943                 domain_similarity_sort_field = DomainSimilarity.DomainSimilaritySortField.MAX_DIFFERENCE;
944                 domain_similarity_sort_field_for_automated_pwc = DomainSimilarity.DomainSimilaritySortField.MAX_DIFFERENCE;
945             }
946             else if ( sort_str.equals( surfacing.DOMAIN_SIMILARITY_SORT_ABS_COUNTS_DIFF ) ) {
947                 domain_similarity_sort_field = DomainSimilarity.DomainSimilaritySortField.ABS_MAX_COUNTS_DIFFERENCE;
948                 domain_similarity_sort_field_for_automated_pwc = DomainSimilarity.DomainSimilaritySortField.ABS_MAX_COUNTS_DIFFERENCE;
949             }
950             else if ( sort_str.equals( surfacing.DOMAIN_SIMILARITY_SORT_COUNTS_DIFF ) ) {
951                 domain_similarity_sort_field = DomainSimilarity.DomainSimilaritySortField.MAX_COUNTS_DIFFERENCE;
952                 domain_similarity_sort_field_for_automated_pwc = DomainSimilarity.DomainSimilaritySortField.MAX_COUNTS_DIFFERENCE;
953             }
954             else {
955                 ForesterUtil.fatalError( surfacing.PRG_NAME, "unknown value \"" + sort_str
956                         + "\" for domain combinations similarities sorting: \"-"
957                         + surfacing.DOMAIN_SIMILARITY_SORT_OPTION + "=<" + surfacing.DOMAIN_SIMILARITY_SORT_ALPHA + "|"
958                         + surfacing.DOMAIN_SIMILARITY_SORT_MAX + "|" + surfacing.DOMAIN_SIMILARITY_SORT_MIN + "|"
959                         + surfacing.DOMAIN_SIMILARITY_SORT_MEAN + "|" + surfacing.DOMAIN_SIMILARITY_SORT_DIFF + "|"
960                         + surfacing.DOMAIN_SIMILARITY_SORT_ABS_COUNTS_DIFF + "|"
961                         + surfacing.DOMAIN_SIMILARITY_SORT_COUNTS_DIFF + "|" + "|"
962                         + surfacing.DOMAIN_SIMILARITY_SORT_SPECIES_COUNT + "|" + surfacing.DOMAIN_SIMILARITY_SORT_SD
963                         + ">\"" );
964             }
965         }
966         PrintableDomainSimilarity.PRINT_OPTION domain_similarity_print_option = DOMAIN_SIMILARITY_PRINT_OPTION_DEFAULT;
967         if ( cla.isOptionSet( surfacing.DOMAIN_SIMILARITY_PRINT_OPTION ) ) {
968             if ( !cla.isOptionValueSet( surfacing.DOMAIN_SIMILARITY_PRINT_OPTION ) ) {
969                 ForesterUtil.fatalError( surfacing.PRG_NAME, "no value for print option: -"
970                         + surfacing.DOMAIN_SIMILARITY_PRINT_OPTION_DETAILED_HTML + "|"
971                         + surfacing.DOMAIN_SIMILARITY_PRINT_OPTION_SIMPLE_HTML + "|"
972                         + surfacing.DOMAIN_SIMILARITY_PRINT_OPTION_SIMPLE_TAB_DELIMITED + ">\"" );
973             }
974             final String sort = cla.getOptionValue( surfacing.DOMAIN_SIMILARITY_PRINT_OPTION ).toLowerCase();
975             if ( sort.equals( surfacing.DOMAIN_SIMILARITY_PRINT_OPTION_DETAILED_HTML ) ) {
976                 domain_similarity_print_option = PrintableDomainSimilarity.PRINT_OPTION.HTML;
977             }
978             else if ( sort.equals( surfacing.DOMAIN_SIMILARITY_PRINT_OPTION_SIMPLE_HTML ) ) {
979                 // domain_similarity_print_option =
980                 // DomainSimilarity.PRINT_OPTION.SIMPLE_HTML;
981                 ForesterUtil.fatalError( surfacing.PRG_NAME, "simple HTML output not implemented yet :(" );
982             }
983             else if ( sort.equals( surfacing.DOMAIN_SIMILARITY_PRINT_OPTION_SIMPLE_TAB_DELIMITED ) ) {
984                 domain_similarity_print_option = PrintableDomainSimilarity.PRINT_OPTION.SIMPLE_TAB_DELIMITED;
985             }
986             else {
987                 ForesterUtil.fatalError( surfacing.PRG_NAME, "unknown value \"" + sort + "\" for print option: -"
988                         + surfacing.DOMAIN_SIMILARITY_PRINT_OPTION_DETAILED_HTML + "|"
989                         + surfacing.DOMAIN_SIMILARITY_PRINT_OPTION_SIMPLE_HTML + "|"
990                         + surfacing.DOMAIN_SIMILARITY_PRINT_OPTION_SIMPLE_TAB_DELIMITED + ">\"" );
991             }
992         }
993         GenomeWideCombinableDomains.GenomeWideCombinableDomainsSortOrder dc_sort_order = DOMAINS_SORT_ORDER_DEFAULT;
994         if ( cla.isOptionSet( surfacing.DOMAIN_COUNT_SORT_OPTION ) ) {
995             if ( !cla.isOptionValueSet( surfacing.DOMAIN_COUNT_SORT_OPTION ) ) {
996                 ForesterUtil.fatalError( surfacing.PRG_NAME, "no value for sorting of domain counts: -"
997                         + surfacing.DOMAIN_COUNT_SORT_OPTION + "=<" + surfacing.DOMAIN_COUNT_SORT_ALPHA + "|"
998                         + surfacing.DOMAIN_COUNT_SORT_KEY_DOMAIN_COUNT + "|"
999                         + surfacing.DOMAIN_COUNT_SORT_KEY_DOMAIN_PROTEINS_COUNT + "|"
1000                         + surfacing.DOMAIN_COUNT_SORT_COMBINATIONS_COUNT + ">\"" );
1001             }
1002             final String sort = cla.getOptionValue( surfacing.DOMAIN_COUNT_SORT_OPTION ).toLowerCase();
1003             if ( sort.equals( surfacing.DOMAIN_COUNT_SORT_ALPHA ) ) {
1004                 dc_sort_order = GenomeWideCombinableDomains.GenomeWideCombinableDomainsSortOrder.ALPHABETICAL_KEY_ID;
1005             }
1006             else if ( sort.equals( surfacing.DOMAIN_COUNT_SORT_KEY_DOMAIN_COUNT ) ) {
1007                 dc_sort_order = GenomeWideCombinableDomains.GenomeWideCombinableDomainsSortOrder.KEY_DOMAIN_COUNT;
1008             }
1009             else if ( sort.equals( surfacing.DOMAIN_COUNT_SORT_KEY_DOMAIN_PROTEINS_COUNT ) ) {
1010                 dc_sort_order = GenomeWideCombinableDomains.GenomeWideCombinableDomainsSortOrder.KEY_DOMAIN_PROTEINS_COUNT;
1011             }
1012             else if ( sort.equals( surfacing.DOMAIN_COUNT_SORT_COMBINATIONS_COUNT ) ) {
1013                 dc_sort_order = GenomeWideCombinableDomains.GenomeWideCombinableDomainsSortOrder.COMBINATIONS_COUNT;
1014             }
1015             else {
1016                 ForesterUtil.fatalError( surfacing.PRG_NAME, "unknown value \"" + sort
1017                         + "\" for sorting of domain counts: \"-" + surfacing.DOMAIN_COUNT_SORT_OPTION + "=<"
1018                         + surfacing.DOMAIN_COUNT_SORT_ALPHA + "|" + surfacing.DOMAIN_COUNT_SORT_KEY_DOMAIN_COUNT + "|"
1019                         + surfacing.DOMAIN_COUNT_SORT_KEY_DOMAIN_PROTEINS_COUNT + "|"
1020                         + surfacing.DOMAIN_COUNT_SORT_COMBINATIONS_COUNT + ">\"" );
1021             }
1022         }
1023         String[][] input_file_properties = null;
1024         if ( input_file_names_from_file != null ) {
1025             input_file_properties = surfacing.processInputFileNames( input_file_names_from_file );
1026         }
1027         else {
1028             input_file_properties = surfacing.processInputFileNames( cla.getNames() );
1029         }
1030         final int number_of_genomes = input_file_properties.length;
1031         if ( number_of_genomes < 2 ) {
1032             ForesterUtil.fatalError( surfacing.PRG_NAME, "cannot analyze less than two files" );
1033         }
1034         if ( ( number_of_genomes < 3 ) && perform_pwc ) {
1035             ForesterUtil.fatalError( surfacing.PRG_NAME, "cannot use : -"
1036                     + surfacing.PAIRWISE_DOMAIN_COMPARISONS_OPTION
1037                     + "=<suffix> to turn on pairwise analyses with less than three input files" );
1038         }
1039         checkWriteabilityForPairwiseComparisons( domain_similarity_print_option,
1040                                                  input_file_properties,
1041                                                  automated_pairwise_comparison_suffix,
1042                                                  out_dir );
1043         for( int i = 0; i < number_of_genomes; i++ ) {
1044             File dcc_outfile = new File( input_file_properties[ i ][ 0 ]
1045                     + surfacing.DOMAIN_COMBINITON_COUNTS_OUTPUTFILE_SUFFIX );
1046             if ( out_dir != null ) {
1047                 dcc_outfile = new File( out_dir + ForesterUtil.FILE_SEPARATOR + dcc_outfile );
1048             }
1049             SurfacingUtil.checkForOutputFileWriteability( dcc_outfile );
1050         }
1051         File pfam_to_go_file = null;
1052         Map<DomainId, List<GoId>> domain_id_to_go_ids_map = null;
1053         int domain_id_to_go_ids_count = 0;
1054         if ( cla.isOptionSet( surfacing.PFAM_TO_GO_FILE_USE_OPTION ) ) {
1055             if ( !cla.isOptionValueSet( surfacing.PFAM_TO_GO_FILE_USE_OPTION ) ) {
1056                 ForesterUtil.fatalError( surfacing.PRG_NAME, "no value for Pfam to GO mapping file: -"
1057                         + surfacing.PFAM_TO_GO_FILE_USE_OPTION + "=<file>" );
1058             }
1059             pfam_to_go_file = new File( cla.getOptionValue( surfacing.PFAM_TO_GO_FILE_USE_OPTION ) );
1060             final String error = ForesterUtil.isReadableFile( pfam_to_go_file );
1061             if ( !ForesterUtil.isEmpty( error ) ) {
1062                 ForesterUtil.fatalError( surfacing.PRG_NAME, "cannot read Pfam to GO mapping file: " + error );
1063             }
1064             try {
1065                 final PfamToGoParser parser = new PfamToGoParser( pfam_to_go_file );
1066                 final List<PfamToGoMapping> pfam_to_go_mappings = parser.parse();
1067                 domain_id_to_go_ids_map = SurfacingUtil.createDomainIdToGoIdMap( pfam_to_go_mappings );
1068                 if ( parser.getMappingCount() < domain_id_to_go_ids_map.size() ) {
1069                     ForesterUtil.unexpectedFatalError( surfacing.PRG_NAME,
1070                                                        "parser.getMappingCount() < domain_id_to_go_ids_map.size()" );
1071                 }
1072                 domain_id_to_go_ids_count = parser.getMappingCount();
1073             }
1074             catch ( final IOException e ) {
1075                 ForesterUtil.fatalError( surfacing.PRG_NAME, "cannot read from Pfam to GO mapping file: " + e );
1076             }
1077         }
1078         File go_obo_file = null;
1079         List<GoTerm> go_terms = null;
1080         if ( cla.isOptionSet( surfacing.GO_OBO_FILE_USE_OPTION ) ) {
1081             if ( !cla.isOptionValueSet( surfacing.GO_OBO_FILE_USE_OPTION ) ) {
1082                 ForesterUtil.fatalError( surfacing.PRG_NAME, "no value for GO OBO file: -"
1083                         + surfacing.GO_OBO_FILE_USE_OPTION + "=<file>" );
1084             }
1085             if ( ( domain_id_to_go_ids_map == null ) || ( domain_id_to_go_ids_map.size() < 1 ) ) {
1086                 ForesterUtil.fatalError( surfacing.PRG_NAME, "cannot use GO OBO file (-"
1087                         + surfacing.GO_OBO_FILE_USE_OPTION + "=<file>) without Pfam to GO mapping file ("
1088                         + surfacing.PFAM_TO_GO_FILE_USE_OPTION + "=<file>)" );
1089             }
1090             go_obo_file = new File( cla.getOptionValue( surfacing.GO_OBO_FILE_USE_OPTION ) );
1091             final String error = ForesterUtil.isReadableFile( go_obo_file );
1092             if ( !ForesterUtil.isEmpty( error ) ) {
1093                 ForesterUtil.fatalError( surfacing.PRG_NAME, "cannot read GO OBO file: " + error );
1094             }
1095             try {
1096                 final OBOparser parser = new OBOparser( go_obo_file, OBOparser.ReturnType.BASIC_GO_TERM );
1097                 go_terms = parser.parse();
1098                 if ( parser.getGoTermCount() != go_terms.size() ) {
1099                     ForesterUtil
1100                             .unexpectedFatalError( surfacing.PRG_NAME, "parser.getGoTermCount() != go_terms.size()" );
1101                 }
1102             }
1103             catch ( final IOException e ) {
1104                 ForesterUtil.fatalError( surfacing.PRG_NAME, "cannot read from GO OBO file: " + e );
1105             }
1106         }
1107         Map<GoId, GoTerm> go_id_to_term_map = null;
1108         if ( ( ( domain_id_to_go_ids_map != null ) && ( domain_id_to_go_ids_map.size() > 0 ) )
1109                 && ( ( go_terms != null ) && ( go_terms.size() > 0 ) ) ) {
1110             go_id_to_term_map = GoUtils.createGoIdToGoTermMap( go_terms );
1111         }
1112         GoNameSpace go_namespace_limit = null;
1113         if ( cla.isOptionSet( surfacing.GO_NAMESPACE_LIMIT_OPTION ) ) {
1114             if ( ( go_id_to_term_map == null ) || go_id_to_term_map.isEmpty() ) {
1115                 ForesterUtil.fatalError( surfacing.PRG_NAME, "cannot use GO namespace limit (-"
1116                         + surfacing.GO_NAMESPACE_LIMIT_OPTION + "=<namespace>) without Pfam to GO mapping file ("
1117                         + surfacing.PFAM_TO_GO_FILE_USE_OPTION + "=<file>) and GO OBO file (-"
1118                         + surfacing.GO_OBO_FILE_USE_OPTION + "=<file>)" );
1119             }
1120             if ( !cla.isOptionValueSet( surfacing.GO_NAMESPACE_LIMIT_OPTION ) ) {
1121                 ForesterUtil.fatalError( surfacing.PRG_NAME, "no value for GO namespace limit: \"-"
1122                         + surfacing.GO_NAMESPACE_LIMIT_OPTION + "=<"
1123                         + surfacing.GO_NAMESPACE_LIMIT_OPTION_MOLECULAR_FUNCTION + "|"
1124                         + surfacing.GO_NAMESPACE_LIMIT_OPTION_BIOLOGICAL_PROCESS + "|"
1125                         + surfacing.GO_NAMESPACE_LIMIT_OPTION_CELLULAR_COMPONENT + ">\"" );
1126             }
1127             final String go_namespace_limit_str = cla.getOptionValue( surfacing.GO_NAMESPACE_LIMIT_OPTION )
1128                     .toLowerCase();
1129             if ( go_namespace_limit_str.equals( surfacing.GO_NAMESPACE_LIMIT_OPTION_MOLECULAR_FUNCTION ) ) {
1130                 go_namespace_limit = GoNameSpace.createMolecularFunction();
1131             }
1132             else if ( go_namespace_limit_str.equals( surfacing.GO_NAMESPACE_LIMIT_OPTION_BIOLOGICAL_PROCESS ) ) {
1133                 go_namespace_limit = GoNameSpace.createBiologicalProcess();
1134             }
1135             else if ( go_namespace_limit_str.equals( surfacing.GO_NAMESPACE_LIMIT_OPTION_CELLULAR_COMPONENT ) ) {
1136                 go_namespace_limit = GoNameSpace.createCellularComponent();
1137             }
1138             else {
1139                 ForesterUtil.fatalError( surfacing.PRG_NAME, "unknown value \"" + go_namespace_limit_str
1140                         + "\" for GO namespace limit: \"-" + surfacing.GO_NAMESPACE_LIMIT_OPTION + "=<"
1141                         + surfacing.GO_NAMESPACE_LIMIT_OPTION_MOLECULAR_FUNCTION + "|"
1142                         + surfacing.GO_NAMESPACE_LIMIT_OPTION_BIOLOGICAL_PROCESS + "|"
1143                         + surfacing.GO_NAMESPACE_LIMIT_OPTION_CELLULAR_COMPONENT + ">\"" );
1144             }
1145         }
1146         if ( ( domain_similarity_sort_field == DomainSimilarity.DomainSimilaritySortField.MAX_COUNTS_DIFFERENCE )
1147                 && ( number_of_genomes > 2 ) ) {
1148             domain_similarity_sort_field = DomainSimilarity.DomainSimilaritySortField.ABS_MAX_COUNTS_DIFFERENCE;
1149         }
1150         boolean jacknifed_distances = false;
1151         int jacknife_resamplings = JACKNIFE_NUMBER_OF_RESAMPLINGS_DEFAULT;
1152         double jacknife_ratio = JACKNIFE_RATIO_DEFAULT;
1153         long random_seed = JACKNIFE_RANDOM_SEED_DEFAULT;
1154         if ( cla.isOptionSet( surfacing.JACKNIFE_OPTION ) ) {
1155             if ( ( number_of_genomes < 3 ) || !perform_pwc ) {
1156                 ForesterUtil.fatalError( surfacing.PRG_NAME, "cannot use jacknife resampling analysis (-"
1157                         + surfacing.JACKNIFE_OPTION + "[=<number of resamplings>]) without pairwise analyses ("
1158                         + surfacing.PAIRWISE_DOMAIN_COMPARISONS_OPTION
1159                         + "=<suffix for pairwise comparison output files>)" );
1160             }
1161             jacknifed_distances = true;
1162             if ( cla.isOptionHasAValue( surfacing.JACKNIFE_OPTION ) ) {
1163                 try {
1164                     jacknife_resamplings = cla.getOptionValueAsInt( surfacing.JACKNIFE_OPTION );
1165                 }
1166                 catch ( final IOException e ) {
1167                     ForesterUtil.fatalError( surfacing.PRG_NAME, "illegal format for number of resamplings" );
1168                 }
1169                 if ( jacknife_resamplings < 2 ) {
1170                     ForesterUtil.fatalError( surfacing.PRG_NAME, "attempt to use less than 2 resamplings" );
1171                 }
1172             }
1173             if ( cla.isOptionSet( surfacing.JACKNIFE_RATIO_OPTION )
1174                     && cla.isOptionHasAValue( surfacing.JACKNIFE_RATIO_OPTION ) ) {
1175                 try {
1176                     jacknife_ratio = cla.getOptionValueAsDouble( surfacing.JACKNIFE_RATIO_OPTION );
1177                 }
1178                 catch ( final IOException e ) {
1179                     ForesterUtil.fatalError( surfacing.PRG_NAME, "illegal format for jacknife ratio" );
1180                 }
1181                 if ( ( jacknife_ratio <= 0.0 ) || ( jacknife_ratio >= 1.0 ) ) {
1182                     ForesterUtil.fatalError( surfacing.PRG_NAME, "attempt to use illegal value for jacknife ratio: "
1183                             + jacknife_ratio );
1184                 }
1185             }
1186             if ( cla.isOptionSet( surfacing.JACKNIFE_RANDOM_SEED_OPTION )
1187                     && cla.isOptionHasAValue( surfacing.JACKNIFE_RANDOM_SEED_OPTION ) ) {
1188                 try {
1189                     random_seed = cla.getOptionValueAsLong( surfacing.JACKNIFE_RANDOM_SEED_OPTION );
1190                 }
1191                 catch ( final IOException e ) {
1192                     ForesterUtil.fatalError( surfacing.PRG_NAME, "illegal format for random generator seed" );
1193                 }
1194             }
1195         }
1196         //        boolean infer_species_trees = false;
1197         //        if ( cla.isOptionSet( surfacing.INFER_SPECIES_TREES_OPTION ) ) {
1198         //            if ( ( output_file == null ) || ( number_of_genomes < 3 )
1199         //                    || ForesterUtil.isEmpty( automated_pairwise_comparison_suffix ) ) {
1200         //                ForesterUtil.fatalError( surfacing.PRG_NAME, "cannot infer species trees (-"
1201         //                        + surfacing.INFER_SPECIES_TREES_OPTION + " without pairwise analyses ("
1202         //                        + surfacing.PAIRWISE_DOMAIN_COMPARISONS_OPTION
1203         //                        + "=<suffix for pairwise comparison output files>)" );
1204         //            }
1205         //            infer_species_trees = true;
1206         //        }
1207         File[] intree_files = null;
1208         Phylogeny[] intrees = null;
1209         if ( cla.isOptionSet( surfacing.INPUT_SPECIES_TREE_OPTION ) ) {
1210             // TODO FIXME if jacknife.... maybe not
1211             if ( number_of_genomes < 3 ) {
1212                 ForesterUtil.fatalError( surfacing.PRG_NAME, "cannot infer gains and losses on input species trees (-"
1213                         + surfacing.INPUT_SPECIES_TREE_OPTION + " without pairwise analyses ("
1214                         + surfacing.PAIRWISE_DOMAIN_COMPARISONS_OPTION
1215                         + "=<suffix for pairwise comparison output files>)" );
1216             }
1217             if ( !cla.isOptionValueSet( surfacing.INPUT_SPECIES_TREE_OPTION ) ) {
1218                 ForesterUtil.fatalError( surfacing.PRG_NAME, "no value for input tree: -"
1219                         + surfacing.INPUT_SPECIES_TREE_OPTION + "=<tree file in phyloXML format>" );
1220             }
1221             final String intrees_str = cla.getOptionValue( surfacing.INPUT_SPECIES_TREE_OPTION );
1222             if ( intrees_str.indexOf( "#" ) > 0 ) {
1223                 final String[] intrees_strs = intrees_str.split( "#" );
1224                 intree_files = new File[ intrees_strs.length ];
1225                 int i = 0;
1226                 for( final String s : intrees_strs ) {
1227                     intree_files[ i++ ] = new File( s.trim() );
1228                 }
1229             }
1230             else {
1231                 intree_files = new File[ 1 ];
1232                 intree_files[ 0 ] = new File( intrees_str );
1233             }
1234             intrees = getIntrees( intree_files, number_of_genomes, input_file_properties );
1235         }
1236         long random_number_seed_for_fitch_parsimony = 0l;
1237         boolean radomize_fitch_parsimony = false;
1238         if ( cla.isOptionSet( surfacing.RANDOM_SEED_FOR_FITCH_PARSIMONY_OPTION ) ) {
1239             if ( !cla.isOptionValueSet( surfacing.RANDOM_SEED_FOR_FITCH_PARSIMONY_OPTION ) ) {
1240                 ForesterUtil.fatalError( surfacing.PRG_NAME, "no value for random number seed: -"
1241                         + surfacing.RANDOM_SEED_FOR_FITCH_PARSIMONY_OPTION + "=<seed>" );
1242             }
1243             try {
1244                 random_number_seed_for_fitch_parsimony = cla
1245                         .getOptionValueAsLong( RANDOM_SEED_FOR_FITCH_PARSIMONY_OPTION );
1246             }
1247             catch ( final IOException e ) {
1248                 ForesterUtil.fatalError( surfacing.PRG_NAME, e.getMessage() );
1249             }
1250             radomize_fitch_parsimony = true;
1251         }
1252         SortedSet<DomainId> filter = null;
1253         if ( ( positive_filter_file != null ) || ( negative_filter_file != null )
1254                 || ( negative_domains_filter_file != null ) ) {
1255             filter = new TreeSet<DomainId>();
1256             if ( positive_filter_file != null ) {
1257                 processFilter( positive_filter_file, filter );
1258             }
1259             else if ( negative_filter_file != null ) {
1260                 processFilter( negative_filter_file, filter );
1261             }
1262             else if ( negative_domains_filter_file != null ) {
1263                 processFilter( negative_domains_filter_file, filter );
1264             }
1265         }
1266         Map<DomainId, Set<String>>[] domain_id_to_secondary_features_maps = null;
1267         File[] secondary_features_map_files = null;
1268         final File domain_lengths_analysis_outfile = new File( out_dir + ForesterUtil.FILE_SEPARATOR + output_file
1269                 + DOMAIN_LENGTHS_ANALYSIS_SUFFIX );
1270         if ( PERFORM_DOMAIN_LENGTH_ANALYSIS ) {
1271             SurfacingUtil.checkForOutputFileWriteability( domain_lengths_analysis_outfile );
1272         }
1273         if ( cla.isOptionSet( surfacing.SECONDARY_FEATURES_PARSIMONY_MAP_FILE ) ) {
1274             if ( !cla.isOptionValueSet( surfacing.SECONDARY_FEATURES_PARSIMONY_MAP_FILE ) ) {
1275                 ForesterUtil.fatalError( surfacing.PRG_NAME, "no value for secondary features map file: -"
1276                         + surfacing.SECONDARY_FEATURES_PARSIMONY_MAP_FILE + "=<file>" );
1277             }
1278             final String[] secondary_features_map_files_strs = cla
1279                     .getOptionValue( surfacing.SECONDARY_FEATURES_PARSIMONY_MAP_FILE ).split( "#" );
1280             secondary_features_map_files = new File[ secondary_features_map_files_strs.length ];
1281             domain_id_to_secondary_features_maps = new Map[ secondary_features_map_files_strs.length ];
1282             int i = 0;
1283             for( final String secondary_features_map_files_str : secondary_features_map_files_strs ) {
1284                 secondary_features_map_files[ i ] = new File( secondary_features_map_files_str );
1285                 final String error = ForesterUtil.isReadableFile( secondary_features_map_files[ i ] );
1286                 if ( !ForesterUtil.isEmpty( error ) ) {
1287                     ForesterUtil.fatalError( surfacing.PRG_NAME, "cannot read secondary features map file: " + error );
1288                 }
1289                 try {
1290                     domain_id_to_secondary_features_maps[ i ] = SurfacingUtil
1291                             .createDomainIdToSecondaryFeaturesMap( secondary_features_map_files[ i ] );
1292                 }
1293                 catch ( final IOException e ) {
1294                     ForesterUtil.fatalError( surfacing.PRG_NAME,
1295                                              "cannot read secondary features map file: " + e.getMessage() );
1296                 }
1297                 catch ( final Exception e ) {
1298                     ForesterUtil.fatalError( surfacing.PRG_NAME, "problem with contents of features map file ["
1299                             + secondary_features_map_files[ i ] + "]: " + e.getMessage() );
1300                 }
1301                 i++;
1302             }
1303         }
1304         if ( out_dir == null ) {
1305             ForesterUtil.fatalError( surfacing.PRG_NAME, "no output directory indicated (-"
1306                     + surfacing.OUTPUT_DIR_OPTION + "=<dir>)" );
1307         }
1308         if ( output_file == null ) {
1309             ForesterUtil.fatalError( surfacing.PRG_NAME, "no name for (main) output file indicated (-"
1310                     + surfacing.OUTPUT_FILE_OPTION + "=<file>)" );
1311         }
1312         if ( ( domain_id_to_go_ids_map == null ) || domain_id_to_go_ids_map.isEmpty() ) {
1313             ForesterUtil.fatalError( surfacing.PRG_NAME,
1314                                      "no (acceptable) Pfam to GO id mapping file provided ('pfam2go file') (-"
1315                                              + surfacing.PFAM_TO_GO_FILE_USE_OPTION + "=<file>)" );
1316         }
1317         if ( ( go_id_to_term_map == null ) || go_id_to_term_map.isEmpty() ) {
1318             ForesterUtil.fatalError( surfacing.PRG_NAME,
1319                                      "no (acceptable) go id to term mapping file provided ('GO OBO file') (-"
1320                                              + surfacing.GO_OBO_FILE_USE_OPTION + "=<file>)" );
1321         }
1322         System.out.println( "Output directory            : " + out_dir );
1323         if ( input_file_names_from_file != null ) {
1324             System.out.println( "Input files names from      : " + input_files_file + " ["
1325                     + input_file_names_from_file.length + " input files]" );
1326             html_desc.append( "<tr><td>Input files names from:</td><td>" + input_files_file + " ["
1327                     + input_file_names_from_file.length + " input files]</td></tr>" + nl );
1328         }
1329         if ( positive_filter_file != null ) {
1330             final int filter_size = filter.size();
1331             System.out.println( "Positive protein filter     : " + positive_filter_file + " [" + filter_size
1332                     + " domain ids]" );
1333             html_desc.append( "<tr><td>Positive protein filter:</td><td>" + positive_filter_file + " [" + filter_size
1334                     + " domain ids]</td></tr>" + nl );
1335         }
1336         if ( negative_filter_file != null ) {
1337             final int filter_size = filter.size();
1338             System.out.println( "Negative protein filter     : " + negative_filter_file + " [" + filter_size
1339                     + " domain ids]" );
1340             html_desc.append( "<tr><td>Negative protein filter:</td><td>" + negative_filter_file + " [" + filter_size
1341                     + " domain ids]</td></tr>" + nl );
1342         }
1343         if ( negative_domains_filter_file != null ) {
1344             final int filter_size = filter.size();
1345             System.out.println( "Negative domain filter      : " + negative_domains_filter_file + " [" + filter_size
1346                     + " domain ids]" );
1347             html_desc.append( "<tr><td>Negative domain filter:</td><td>" + negative_domains_filter_file + " ["
1348                     + filter_size + " domain ids]</td></tr>" + nl );
1349         }
1350         if ( plus_minus_analysis_high_copy_base_species.size() > 0 ) {
1351             String plus0 = "";
1352             for( final String s : plus_minus_analysis_high_copy_base_species ) {
1353                 plus0 += "+" + s + " ";
1354             }
1355             String plus1 = "";
1356             for( final String s : plus_minus_analysis_high_copy_target_species ) {
1357                 plus1 += "*" + s + " ";
1358             }
1359             String minus = "";
1360             for( final String s : plus_minus_analysis_high_low_copy_species ) {
1361                 minus += "-" + s + " ";
1362             }
1363             System.out.println( "Plus-minus analysis         : " + plus1 + "&& " + plus0 + "&& " + minus );
1364             html_desc.append( "<tr><td>Plus-minus analysis:</td><td>" + plus1 + "&& " + plus0 + "&& " + minus
1365                     + "</td></tr>" + nl );
1366         }
1367         if ( cutoff_scores_file != null ) {
1368             System.out.println( "Cutoff scores file          : " + cutoff_scores_file );
1369             html_desc.append( "<tr><td>Cutoff scores file:</td><td>" + cutoff_scores_file + "</td></tr>" + nl );
1370         }
1371         if ( e_value_max >= 0.0 ) {
1372             System.out.println( "E-value maximum (inclusive) : " + e_value_max );
1373             html_desc.append( "<tr><td>E-value maximum (inclusive):</td><td>" + e_value_max + "</td></tr>" + nl );
1374         }
1375         System.out.println( "Ignore DUFs                 : " + ignore_dufs );
1376         if ( ignore_virus_like_ids ) {
1377             System.out.println( "Ignore virus like ids       : " + ignore_virus_like_ids );
1378             html_desc.append( "<tr><td>Ignore virus, phage, transposition related ids:</td><td>"
1379                     + ignore_virus_like_ids + "</td></tr>" + nl );
1380         }
1381         html_desc.append( "<tr><td>Ignore DUFs:</td><td>" + ignore_dufs + "</td></tr>" + nl );
1382         if ( max_allowed_overlap != surfacing.MAX_ALLOWED_OVERLAP_DEFAULT ) {
1383             System.out.println( "Max allowed domain overlap  : " + max_allowed_overlap );
1384             html_desc.append( "<tr><td>Max allowed domain overlap:</td><td>" + max_allowed_overlap + "</td></tr>" + nl );
1385         }
1386         if ( no_engulfing_overlaps ) {
1387             System.out.println( "Ignore engulfed domains     : " + no_engulfing_overlaps );
1388             html_desc.append( "<tr><td>Ignore (lower confidence) engulfed domains:</td><td>" + no_engulfing_overlaps
1389                     + "</td></tr>" + nl );
1390         }
1391         System.out.println( "Ignore singlet domains      : " + ignore_domains_without_combs_in_all_spec );
1392         html_desc
1393                 .append( "<tr><td>Ignore singlet domains for domain combination similarity analyses (not for parsimony analyses):</td><td>"
1394                         + ignore_domains_without_combs_in_all_spec + "</td></tr>" + nl );
1395         System.out.println( "Ignore species specific doms: " + ignore_species_specific_domains );
1396         html_desc
1397                 .append( "<tr><td>Ignore species specific domains for domain combination similarity analyses (not for parsimony analyses):</td><td>"
1398                         + ignore_species_specific_domains + "</td></tr>" + nl );
1399         System.out.println( "Ignore combination with self: " + ignore_combination_with_same );
1400         html_desc.append( "<tr><td>Ignore combination with self for domain combination similarity analyses:</td><td>"
1401                 + ignore_combination_with_same + "</td></tr>" + nl );
1402         ;
1403         System.out.println( "Consider directedness       : "
1404                 + ( dc_type != BinaryDomainCombination.DomainCombinationType.BASIC ) );
1405         html_desc.append( "<tr><td>Consider directedness of binary domain combinations:</td><td>"
1406                 + ( dc_type != BinaryDomainCombination.DomainCombinationType.BASIC ) + "</td></tr>" + nl );
1407         if ( dc_type != BinaryDomainCombination.DomainCombinationType.BASIC ) {
1408             System.out.println( "Consider adjacency          : "
1409                     + ( dc_type == BinaryDomainCombination.DomainCombinationType.DIRECTED_ADJACTANT ) );
1410             html_desc.append( "<tr><td>Consider djacency of binary domain combinations:</td><td>"
1411                     + ( dc_type == BinaryDomainCombination.DomainCombinationType.DIRECTED_ADJACTANT ) + "</td></tr>"
1412                     + nl );
1413         }
1414         System.out.print( "Domain counts sort order    : " );
1415         switch ( dc_sort_order ) {
1416             case ALPHABETICAL_KEY_ID:
1417                 System.out.println( "alphabetical" );
1418                 break;
1419             case KEY_DOMAIN_COUNT:
1420                 System.out.println( "domain count" );
1421                 break;
1422             case KEY_DOMAIN_PROTEINS_COUNT:
1423                 System.out.println( "domain proteins count" );
1424                 break;
1425             case COMBINATIONS_COUNT:
1426                 System.out.println( "domain combinations count" );
1427                 break;
1428             default:
1429                 ForesterUtil.unexpectedFatalError( surfacing.PRG_NAME, "unknown value for dc sort order" );
1430         }
1431         if ( domain_id_to_go_ids_map != null ) {
1432             System.out.println( "Pfam to GO mappings from    : " + pfam_to_go_file + " [" + domain_id_to_go_ids_count
1433                     + " mappings]" );
1434             html_desc.append( "<tr><td>Pfam to GO mappings from:</td><td>" + pfam_to_go_file + " ["
1435                     + domain_id_to_go_ids_count + " mappings]" + "</td></tr>" + nl );
1436         }
1437         if ( go_terms != null ) {
1438             System.out.println( "GO terms from               : " + go_obo_file + " [" + go_terms.size() + " terms]" );
1439             html_desc.append( "<tr><td>GO terms from:</td><td>" + go_obo_file + " [" + go_terms.size() + " terms]"
1440                     + "</td></tr>" + nl );
1441         }
1442         if ( go_namespace_limit != null ) {
1443             System.out.println( "Limit GO terms to           : " + go_namespace_limit.toString() );
1444             html_desc.append( "<tr><td>Limit GO terms to</td><td>" + go_namespace_limit + "</td></tr>" + nl );
1445         }
1446         if ( perform_pwc ) {
1447             System.out.println( "Suffix for PWC files        : " + automated_pairwise_comparison_suffix );
1448             html_desc.append( "<tr><td>Suffix for PWC files</td><td>" + automated_pairwise_comparison_suffix
1449                     + "</td></tr>" + nl );
1450         }
1451         if ( out_dir != null ) {
1452             System.out.println( "Output directory            : " + out_dir );
1453         }
1454         if ( query_domain_ids != null ) {
1455             System.out.println( "Query domains (ordered)     : " + query_domain_ids );
1456             html_desc.append( "<tr><td></td><td>" + query_domain_ids + "</td></tr>" + nl );
1457         }
1458         System.out.println( "Write similarities to       : " + output_file );
1459         System.out.print( "  Scoring method            : " );
1460         html_desc.append( "<tr><td>Scoring method:</td><td>" );
1461         switch ( scoring ) {
1462             case COMBINATIONS:
1463                 System.out.println( "domain combinations based" );
1464                 html_desc.append( "domain combinations based" + "</td></tr>" + nl );
1465                 break;
1466             case DOMAINS:
1467                 System.out.println( "domain counts based" );
1468                 html_desc.append( "domain counts based" + "</td></tr>" + nl );
1469                 break;
1470             case PROTEINS:
1471                 System.out.println( "domain proteins counts based" );
1472                 html_desc.append( "domain proteins counts based" + "</td></tr>" + nl );
1473                 break;
1474             default:
1475                 ForesterUtil.unexpectedFatalError( surfacing.PRG_NAME, "unknown value for sorting for scoring" );
1476         }
1477         System.out.print( "  Sort by                   : " );
1478         html_desc.append( "<tr><td>Sort by:</td><td>" );
1479         switch ( domain_similarity_sort_field ) {
1480             case MIN:
1481                 System.out.print( "score minimum" );
1482                 html_desc.append( "score minimum" );
1483                 break;
1484             case MAX:
1485                 System.out.print( "score maximum" );
1486                 html_desc.append( "score maximum" );
1487                 break;
1488             case MEAN:
1489                 System.out.print( "score mean" );
1490                 html_desc.append( "score mean" );
1491                 break;
1492             case SD:
1493                 System.out.print( "score standard deviation" );
1494                 html_desc.append( "score standard deviation" );
1495                 break;
1496             case SPECIES_COUNT:
1497                 System.out.print( "species number" );
1498                 html_desc.append( "species number" );
1499                 break;
1500             case DOMAIN_ID:
1501                 System.out.print( "alphabetical domain identifier" );
1502                 html_desc.append( "alphabetical domain identifier" );
1503                 break;
1504             case MAX_DIFFERENCE:
1505                 System.out.print( "(maximal) difference" );
1506                 html_desc.append( "(maximal) difference" );
1507                 break;
1508             case ABS_MAX_COUNTS_DIFFERENCE:
1509                 System.out.print( "absolute (maximal) counts difference" );
1510                 html_desc.append( "absolute (maximal) counts difference" );
1511                 break;
1512             case MAX_COUNTS_DIFFERENCE:
1513                 System.out.print( "(maximal) counts difference" );
1514                 html_desc.append( "(maximal) counts  difference" );
1515                 break;
1516             default:
1517                 ForesterUtil.unexpectedFatalError( surfacing.PRG_NAME, "unknown value for sorting for similarities" );
1518         }
1519         if ( sort_by_species_count_first ) {
1520             System.out.println( " (sort by species count first)" );
1521             html_desc.append( " (sort by species count first)" );
1522         }
1523         else {
1524             System.out.println();
1525         }
1526         html_desc.append( "</td></tr>" + nl );
1527         System.out.print( "  Detailedness              : " );
1528         switch ( detailedness ) {
1529             case BASIC:
1530                 System.out.println( "basic" );
1531                 break;
1532             case LIST_COMBINING_DOMAIN_FOR_EACH_SPECIES:
1533                 System.out.println( "list combining domains for each species" );
1534                 break;
1535             case PUNCTILIOUS:
1536                 System.out.println( "punctilious" );
1537                 break;
1538             default:
1539                 ForesterUtil.unexpectedFatalError( surfacing.PRG_NAME, "unknown value for sorting for detailedness" );
1540         }
1541         System.out.print( "  Print option              : " );
1542         switch ( domain_similarity_print_option ) {
1543             case HTML:
1544                 System.out.println( "HTML" );
1545                 break;
1546             case SIMPLE_TAB_DELIMITED:
1547                 System.out.println( "simple tab delimited" );
1548                 break;
1549             default:
1550                 ForesterUtil.unexpectedFatalError( surfacing.PRG_NAME, "unknown value for print option" );
1551         }
1552         System.out.print( "  Species matrix            : " + species_matrix );
1553         System.out.println();
1554         final File dc_data_file = new File( out_dir + ForesterUtil.FILE_SEPARATOR + output_file + DATA_FILE_SUFFIX );
1555         System.out.println( "Domain comb data output     : " + dc_data_file );
1556         html_desc.append( "<tr><td>Domain combination data output:</td><td> " + dc_data_file + " </td></tr>" );
1557         System.out.println();
1558         if ( perform_pwc ) {
1559             System.out.println( "Pairwise comparisons: " );
1560             html_desc.append( "<tr><td>Pairwise comparisons:</td><td></td></tr>" );
1561             System.out.print( "  Sort by                   : " );
1562             html_desc.append( "<tr><td>Sort by:</td><td>" );
1563             switch ( domain_similarity_sort_field_for_automated_pwc ) {
1564                 case MEAN:
1565                     System.out.print( "score mean" );
1566                     html_desc.append( "score mean" );
1567                     break;
1568                 case DOMAIN_ID:
1569                     System.out.print( "alphabetical domain identifier" );
1570                     html_desc.append( "alphabetical domain identifier" );
1571                     break;
1572                 case MAX_DIFFERENCE:
1573                     System.out.print( "difference" );
1574                     html_desc.append( "difference" );
1575                     break;
1576                 case ABS_MAX_COUNTS_DIFFERENCE:
1577                     System.out.print( "absolute counts difference" );
1578                     html_desc.append( "absolute counts difference" );
1579                     break;
1580                 case MAX_COUNTS_DIFFERENCE:
1581                     System.out.print( "counts difference" );
1582                     html_desc.append( "counts difference" );
1583                     break;
1584                 default:
1585                     ForesterUtil
1586                             .unexpectedFatalError( surfacing.PRG_NAME, "unknown value for sorting for similarities" );
1587             }
1588             System.out.println();
1589             html_desc.append( "</td></tr>" + nl );
1590             if ( jacknifed_distances ) {
1591                 html_desc.append( "<tr><td>Jacknife:</td><td>" + jacknife_resamplings + " resamplings</td></tr>" + nl );
1592                 html_desc.append( "<tr><td>Jacknife ratio:</td><td>" + ForesterUtil.round( jacknife_ratio, 2 )
1593                         + "</td></tr>" + nl );
1594                 html_desc.append( "<tr><td>Jacknife random number seed:</td><td>" + random_seed + "</td></tr>" + nl );
1595                 System.out.println( "  Jacknife                  : " + jacknife_resamplings + " resamplings" );
1596                 System.out.println( "    Ratio                   : " + ForesterUtil.round( jacknife_ratio, 2 ) );
1597                 System.out.println( "    Random number seed      : " + random_seed );
1598             }
1599             //                if ( infer_species_trees ) {
1600             //                    html_desc.append( "<tr><td>Infer species trees:</td><td>true</td></tr>" + nl );
1601             //                    System.out.println( "  Infer species trees       : true" );
1602             //                }
1603             if ( ( intrees != null ) && ( intrees.length > 0 ) ) {
1604                 for( final File intree_file : intree_files ) {
1605                     html_desc.append( "<tr><td>Intree for gain/loss parsimony analysis:</td><td>" + intree_file
1606                             + "</td></tr>" + nl );
1607                     System.out.println( "  Intree for gain/loss pars.: " + intree_file );
1608                 }
1609             }
1610             if ( radomize_fitch_parsimony ) {
1611                 html_desc.append( "<tr><td>    Random number seed for Fitch parsimony analysis:</td><td>"
1612                         + random_number_seed_for_fitch_parsimony + "</td></tr>" + nl );
1613                 System.out.println( "    Random number seed      : " + random_number_seed_for_fitch_parsimony );
1614             }
1615             if ( ( domain_id_to_secondary_features_maps != null ) && ( domain_id_to_secondary_features_maps.length > 0 ) ) {
1616                 for( int i = 0; i < secondary_features_map_files.length; i++ ) {
1617                     html_desc.append( "<tr><td>Secondary features map file:</td><td>"
1618                             + secondary_features_map_files[ i ] + "</td></tr>" + nl );
1619                     System.out.println( "Secondary features map file : " + secondary_features_map_files[ i ]
1620                             + " [mappings for " + domain_id_to_secondary_features_maps[ i ].size() + " domain ids]" );
1621                     if ( VERBOSE ) {
1622                         System.out.println();
1623                         System.out.println( "Domain ids to secondary features map:" );
1624                         for( final DomainId domain_id : domain_id_to_secondary_features_maps[ i ].keySet() ) {
1625                             System.out.print( domain_id.getId() );
1626                             System.out.print( " => " );
1627                             for( final String sec : domain_id_to_secondary_features_maps[ i ].get( domain_id ) ) {
1628                                 System.out.print( sec );
1629                                 System.out.print( " " );
1630                             }
1631                             System.out.println();
1632                         }
1633                     }
1634                 }
1635             }
1636         } // if ( perform_pwc ) {
1637         System.out.println();
1638         html_desc.append( "<tr><td>Command line:</td><td>" + cla.getCommandLineArgsAsString() + "</td></tr>" + nl );
1639         System.out.println( "Command line                : " + cla.getCommandLineArgsAsString() );
1640         BufferedWriter[] query_domains_writer_ary = null;
1641         List<DomainId>[] query_domain_ids_array = null;
1642         if ( query_domain_ids != null ) {
1643             final String[] query_domain_ids_str_array = query_domain_ids.split( "#" );
1644             query_domain_ids_array = new ArrayList[ query_domain_ids_str_array.length ];
1645             query_domains_writer_ary = new BufferedWriter[ query_domain_ids_str_array.length ];
1646             for( int i = 0; i < query_domain_ids_str_array.length; i++ ) {
1647                 String query_domain_ids_str = query_domain_ids_str_array[ i ];
1648                 final String[] query_domain_ids_str_ary = query_domain_ids_str.split( "~" );
1649                 final List<DomainId> query = new ArrayList<DomainId>();
1650                 for( final String element : query_domain_ids_str_ary ) {
1651                     query.add( new DomainId( element ) );
1652                 }
1653                 query_domain_ids_array[ i ] = query;
1654                 query_domain_ids_str = query_domain_ids_str.replace( '~', '_' );
1655                 String protein_names_writer_str = query_domain_ids_str + surfacing.SEQ_EXTRACT_SUFFIX;
1656                 if ( out_dir != null ) {
1657                     protein_names_writer_str = out_dir + ForesterUtil.FILE_SEPARATOR + protein_names_writer_str;
1658                 }
1659                 try {
1660                     query_domains_writer_ary[ i ] = new BufferedWriter( new FileWriter( protein_names_writer_str ) );
1661                 }
1662                 catch ( final IOException e ) {
1663                     ForesterUtil.fatalError( surfacing.PRG_NAME, "Could not open [" + protein_names_writer_str + "]: "
1664                             + e.getLocalizedMessage() );
1665                 }
1666             }
1667         }
1668         SortedMap<Species, List<Protein>> protein_lists_per_species = null; //This will only be created if neede.
1669         boolean need_protein_lists_per_species = false;
1670         if ( ( plus_minus_analysis_high_copy_base_species.size() > 0 ) || output_protein_lists_for_all_domains ) {
1671             need_protein_lists_per_species = true;
1672         }
1673         if ( need_protein_lists_per_species ) {
1674             protein_lists_per_species = new TreeMap<Species, List<Protein>>();
1675         }
1676         final List<GenomeWideCombinableDomains> gwcd_list = new ArrayList<GenomeWideCombinableDomains>( number_of_genomes );
1677         final SortedSet<DomainId> all_domains_encountered = new TreeSet<DomainId>();
1678         final SortedSet<BinaryDomainCombination> all_bin_domain_combinations_encountered = new TreeSet<BinaryDomainCombination>();
1679         List<BinaryDomainCombination> all_bin_domain_combinations_gained_fitch = null;
1680         List<BinaryDomainCombination> all_bin_domain_combinations_lost_fitch = null;
1681         if ( ( intrees != null ) && ( intrees.length == 1 ) ) {
1682             all_bin_domain_combinations_gained_fitch = new ArrayList<BinaryDomainCombination>();
1683             all_bin_domain_combinations_lost_fitch = new ArrayList<BinaryDomainCombination>();
1684         }
1685         final DomainLengthsTable domain_lengths_table = new DomainLengthsTable();
1686         final File per_genome_domain_promiscuity_statistics_file = new File( out_dir + ForesterUtil.FILE_SEPARATOR
1687                 + output_file + D_PROMISCUITY_FILE_SUFFIX );
1688         BufferedWriter per_genome_domain_promiscuity_statistics_writer = null;
1689         try {
1690             per_genome_domain_promiscuity_statistics_writer = new BufferedWriter( new FileWriter( per_genome_domain_promiscuity_statistics_file ) );
1691             per_genome_domain_promiscuity_statistics_writer.write( "Species:\t" );
1692             per_genome_domain_promiscuity_statistics_writer.write( "Mean:\t" );
1693             per_genome_domain_promiscuity_statistics_writer.write( "SD:\t" );
1694             per_genome_domain_promiscuity_statistics_writer.write( "Median:\t" );
1695             per_genome_domain_promiscuity_statistics_writer.write( "Min:\t" );
1696             per_genome_domain_promiscuity_statistics_writer.write( "Max:\t" );
1697             per_genome_domain_promiscuity_statistics_writer.write( "N:\t" );
1698             per_genome_domain_promiscuity_statistics_writer.write( "Max Promiscuous Domains:"
1699                     + ForesterUtil.LINE_SEPARATOR );
1700         }
1701         catch ( final IOException e2 ) {
1702             ForesterUtil.fatalError( surfacing.PRG_NAME, e2.getMessage() );
1703         }
1704         final File log_file = new File( out_dir + ForesterUtil.FILE_SEPARATOR + output_file + LOG_FILE_SUFFIX );
1705         BufferedWriter log_writer = null;
1706         try {
1707             log_writer = new BufferedWriter( new FileWriter( log_file ) );
1708         }
1709         catch ( final IOException e2 ) {
1710             ForesterUtil.fatalError( surfacing.PRG_NAME, e2.getMessage() );
1711         }
1712         BufferedWriter dc_data_writer = null;
1713         try {
1714             dc_data_writer = new BufferedWriter( new FileWriter( dc_data_file ) );
1715             dc_data_writer.write( DATA_FILE_DESC );
1716             dc_data_writer.write( ForesterUtil.LINE_SEPARATOR );
1717         }
1718         catch ( final IOException e2 ) {
1719             ForesterUtil.fatalError( surfacing.PRG_NAME, e2.getMessage() );
1720         }
1721         for( int i = 0; i < number_of_genomes; ++i ) {
1722             System.out.println();
1723             System.out.println( ( i + 1 ) + "/" + number_of_genomes );
1724             log( ( i + 1 ) + "/" + number_of_genomes, log_writer );
1725             System.out.println( "Processing                                     : " + input_file_properties[ i ][ 0 ] );
1726             log( "Genome                                         : " + input_file_properties[ i ][ 0 ], log_writer );
1727             HmmscanPerDomainTableParser parser = null;
1728             INDIVIDUAL_SCORE_CUTOFF ind_score_cutoff = INDIVIDUAL_SCORE_CUTOFF.NONE;
1729             if ( individual_score_cutoffs != null ) {
1730                 ind_score_cutoff = INDIVIDUAL_SCORE_CUTOFF_DEFAULT;
1731             }
1732             if ( ( positive_filter_file != null ) || ( negative_filter_file != null )
1733                     || ( negative_domains_filter_file != null ) ) {
1734                 HmmscanPerDomainTableParser.FilterType filter_type = HmmscanPerDomainTableParser.FilterType.NONE;
1735                 if ( positive_filter_file != null ) {
1736                     filter_type = HmmscanPerDomainTableParser.FilterType.POSITIVE_PROTEIN;
1737                 }
1738                 else if ( negative_filter_file != null ) {
1739                     filter_type = HmmscanPerDomainTableParser.FilterType.NEGATIVE_PROTEIN;
1740                 }
1741                 else if ( negative_domains_filter_file != null ) {
1742                     filter_type = HmmscanPerDomainTableParser.FilterType.NEGATIVE_DOMAIN;
1743                 }
1744                 parser = new HmmscanPerDomainTableParser( new File( input_file_properties[ i ][ 0 ] ),
1745                                                           input_file_properties[ i ][ 1 ],
1746                                                           filter,
1747                                                           filter_type,
1748                                                           ind_score_cutoff );
1749             }
1750             else {
1751                 parser = new HmmscanPerDomainTableParser( new File( input_file_properties[ i ][ 0 ] ),
1752                                                           input_file_properties[ i ][ 1 ],
1753                                                           ind_score_cutoff );
1754             }
1755             if ( e_value_max >= 0.0 ) {
1756                 parser.setEValueMaximum( e_value_max );
1757             }
1758             parser.setIgnoreDufs( ignore_dufs );
1759             parser.setIgnoreVirusLikeIds( ignore_virus_like_ids );
1760             parser.setIgnoreEngulfedDomains( no_engulfing_overlaps );
1761             if ( max_allowed_overlap != surfacing.MAX_ALLOWED_OVERLAP_DEFAULT ) {
1762                 parser.setMaxAllowedOverlap( max_allowed_overlap );
1763             }
1764             parser.setReturnType( HmmscanPerDomainTableParser.ReturnType.UNORDERED_PROTEIN_DOMAIN_COLLECTION_PER_PROTEIN );
1765             if ( individual_score_cutoffs != null ) {
1766                 parser.setIndividualScoreCutoffs( individual_score_cutoffs );
1767             }
1768             List<Protein> protein_list = null;
1769             try {
1770                 protein_list = parser.parse();
1771             }
1772             catch ( final IOException e ) {
1773                 ForesterUtil.fatalError( surfacing.PRG_NAME, e.getMessage() );
1774             }
1775             catch ( final Exception e ) {
1776                 ForesterUtil.unexpectedFatalError( surfacing.PRG_NAME, e.getMessage(), e );
1777             }
1778             if ( VERBOSE ) {
1779                 System.out.println( "Domains ignored due to negative domain filter: " );
1780                 ForesterUtil.printCountingMap( parser.getDomainsIgnoredDueToNegativeDomainFilterCountsMap() );
1781                 System.out.println( "Domains ignored due to virus like id: " );
1782                 ForesterUtil.printCountingMap( parser.getDomainsIgnoredDueToVirusLikeIdCountsMap() );
1783             }
1784             System.out.println( "Number of proteins encountered                 : " + parser.getProteinsEncountered() );
1785             log( "Number of proteins encountered                 : " + parser.getProteinsEncountered(), log_writer );
1786             System.out.println( "Number of proteins stored                      : " + protein_list.size() );
1787             log( "Number of proteins stored                      : " + protein_list.size(), log_writer );
1788             System.out.println( "Domains encountered                            : " + parser.getDomainsEncountered() );
1789             log( "Domains encountered                            : " + parser.getDomainsEncountered(), log_writer );
1790             System.out.println( "Domains stored                                 : " + parser.getDomainsStored() );
1791             log( "Domains stored                                 : " + parser.getDomainsStored(), log_writer );
1792             System.out.println( "Distinct domains stored                        : "
1793                     + parser.getDomainsStoredSet().size() );
1794             log( "Distinct domains stored                        : " + parser.getDomainsStoredSet().size(), log_writer );
1795             System.out.println( "Domains ignored due to individual score cutoffs: "
1796                     + parser.getDomainsIgnoredDueToIndividualScoreCutoff() );
1797             log( "Domains ignored due to individual score cutoffs: "
1798                          + parser.getDomainsIgnoredDueToIndividualScoreCutoff(),
1799                  log_writer );
1800             System.out.println( "Domains ignored due to E-value                 : "
1801                     + parser.getDomainsIgnoredDueToEval() );
1802             log( "Domains ignored due to E-value                 : " + parser.getDomainsIgnoredDueToEval(), log_writer );
1803             System.out.println( "Domains ignored due to DUF designation         : "
1804                     + parser.getDomainsIgnoredDueToDuf() );
1805             log( "Domains ignored due to DUF designation         : " + parser.getDomainsIgnoredDueToDuf(), log_writer );
1806             if ( ignore_virus_like_ids ) {
1807                 System.out.println( "Domains ignored due virus like ids             : "
1808                         + parser.getDomainsIgnoredDueToVirusLikeIds() );
1809                 log( "Domains ignored due virus like ids             : " + parser.getDomainsIgnoredDueToVirusLikeIds(),
1810                      log_writer );
1811             }
1812             System.out.println( "Domains ignored due negative domain filter     : "
1813                     + parser.getDomainsIgnoredDueToNegativeDomainFilter() );
1814             log( "Domains ignored due negative domain filter     : "
1815                          + parser.getDomainsIgnoredDueToNegativeDomainFilter(),
1816                  log_writer );
1817             System.out.println( "Domains ignored due to overlap                 : "
1818                     + parser.getDomainsIgnoredDueToOverlap() );
1819             log( "Domains ignored due to overlap                 : " + parser.getDomainsIgnoredDueToOverlap(),
1820                  log_writer );
1821             if ( negative_filter_file != null ) {
1822                 System.out.println( "Proteins ignored due to negative filter        : "
1823                         + parser.getProteinsIgnoredDueToFilter() );
1824                 log( "Proteins ignored due to negative filter        : " + parser.getProteinsIgnoredDueToFilter(),
1825                      log_writer );
1826             }
1827             if ( positive_filter_file != null ) {
1828                 System.out.println( "Proteins ignored due to positive filter        : "
1829                         + parser.getProteinsIgnoredDueToFilter() );
1830                 log( "Proteins ignored due to positive filter        : " + parser.getProteinsIgnoredDueToFilter(),
1831                      log_writer );
1832             }
1833             System.out.println( "Time for processing                            : " + parser.getTime() + "ms" );
1834             log( "", log_writer );
1835             html_desc.append( "<tr><td>" + input_file_properties[ i ][ 0 ] + " [species: "
1836                     + input_file_properties[ i ][ 1 ] + "]" + ":</td><td>domains analyzed: "
1837                     + parser.getDomainsStored() + "; domains ignored: [ind score cutoffs: "
1838                     + parser.getDomainsIgnoredDueToIndividualScoreCutoff() + "] [E-value cutoff: "
1839                     + parser.getDomainsIgnoredDueToEval() + "] [DUF: " + parser.getDomainsIgnoredDueToDuf()
1840                     + "] [virus like ids: " + parser.getDomainsIgnoredDueToVirusLikeIds()
1841                     + "] [negative domain filter: " + parser.getDomainsIgnoredDueToNegativeDomainFilter()
1842                     + "] [overlap: " + parser.getDomainsIgnoredDueToOverlap() + "]" );
1843             if ( negative_filter_file != null ) {
1844                 html_desc.append( "; proteins ignored due to negative filter: "
1845                         + parser.getProteinsIgnoredDueToFilter() );
1846             }
1847             if ( positive_filter_file != null ) {
1848                 html_desc.append( "; proteins ignored due to positive filter: "
1849                         + parser.getProteinsIgnoredDueToFilter() );
1850             }
1851             html_desc.append( "</td></tr>" + nl );
1852             // domain_partner_counts_array[ i ] =
1853             // Methods.getDomainPartnerCounts( protein_domain_collections_array[
1854             // i ],
1855             // false, input_file_properties[ i ][ 1 ] );
1856             try {
1857                 int count = 0;
1858                 for( final Protein protein : protein_list ) {
1859                     dc_data_writer.write( SurfacingUtil.proteinToDomainCombinations( protein, count + "", "\t" )
1860                             .toString() );
1861                     ++count;
1862                 }
1863             }
1864             catch ( final IOException e ) {
1865                 ForesterUtil.fatalError( surfacing.PRG_NAME, e.toString() );
1866             }
1867             gwcd_list.add( BasicGenomeWideCombinableDomains
1868                     .createInstance( protein_list,
1869                                      ignore_combination_with_same,
1870                                      new BasicSpecies( input_file_properties[ i ][ 1 ] ),
1871                                      domain_id_to_go_ids_map,
1872                                      dc_type ) );
1873             domain_lengths_table.addLengths( protein_list );
1874             if ( gwcd_list.get( i ).getSize() > 0 ) {
1875                 SurfacingUtil.writeDomainCombinationsCountsFile( input_file_properties,
1876                                                                  out_dir,
1877                                                                  per_genome_domain_promiscuity_statistics_writer,
1878                                                                  gwcd_list.get( i ),
1879                                                                  i,
1880                                                                  dc_sort_order );
1881                 if ( output_binary_domain_combinationsfor_graph_analysis ) {
1882                     SurfacingUtil.writeBinaryDomainCombinationsFileForGraphAnalysis( input_file_properties,
1883                                                                                      out_dir,
1884                                                                                      gwcd_list.get( i ),
1885                                                                                      i,
1886                                                                                      dc_sort_order );
1887                 }
1888                 SurfacingUtil.addAllDomainIdsToSet( gwcd_list.get( i ), all_domains_encountered );
1889                 SurfacingUtil.addAllBinaryDomainCombinationToSet( gwcd_list.get( i ),
1890                                                                   all_bin_domain_combinations_encountered );
1891             }
1892             if ( query_domains_writer_ary != null ) {
1893                 for( int j = 0; j < query_domain_ids_array.length; j++ ) {
1894                     try {
1895                         SurfacingUtil.extractProteinNames( protein_list,
1896                                                            query_domain_ids_array[ j ],
1897                                                            query_domains_writer_ary[ j ],
1898                                                            "\t" );
1899                         query_domains_writer_ary[ j ].flush();
1900                     }
1901                     catch ( final IOException e ) {
1902                         e.printStackTrace();
1903                     }
1904                 }
1905             }
1906             if ( need_protein_lists_per_species ) {
1907                 protein_lists_per_species.put( new BasicSpecies( input_file_properties[ i ][ 1 ] ), protein_list );
1908             }
1909             try {
1910                 log_writer.flush();
1911             }
1912             catch ( final IOException e2 ) {
1913                 ForesterUtil.fatalError( surfacing.PRG_NAME, e2.getLocalizedMessage() );
1914             }
1915             System.gc();
1916         } // for( int i = 0; i < number_of_genomes; ++i ) {
1917         try {
1918             per_genome_domain_promiscuity_statistics_writer.flush();
1919             per_genome_domain_promiscuity_statistics_writer.close();
1920             dc_data_writer.flush();
1921             dc_data_writer.close();
1922             log_writer.flush();
1923             log_writer.close();
1924         }
1925         catch ( final IOException e2 ) {
1926             ForesterUtil.fatalError( surfacing.PRG_NAME, e2.getLocalizedMessage() );
1927         }
1928         ForesterUtil.programMessage( PRG_NAME, "Wrote domain promiscuities to: "
1929                 + per_genome_domain_promiscuity_statistics_file );
1930         if ( query_domains_writer_ary != null ) {
1931             for( int j = 0; j < query_domain_ids_array.length; j++ ) {
1932                 try {
1933                     query_domains_writer_ary[ j ].close();
1934                 }
1935                 catch ( final IOException e ) {
1936                     ForesterUtil.fatalError( surfacing.PRG_NAME, e.toString() );
1937                 }
1938             }
1939         }
1940         if ( PERFORM_DOMAIN_LENGTH_ANALYSIS ) {
1941             try {
1942                 SurfacingUtil.executeDomainLengthAnalysis( input_file_properties,
1943                                                            number_of_genomes,
1944                                                            domain_lengths_table,
1945                                                            domain_lengths_analysis_outfile );
1946             }
1947             catch ( final IOException e1 ) {
1948                 ForesterUtil.fatalError( surfacing.PRG_NAME, e1.toString() );
1949             }
1950             System.out.println();
1951             ForesterUtil.programMessage( PRG_NAME, "Wrote domain length data to: " + domain_lengths_analysis_outfile );
1952             System.out.println();
1953         }
1954         final long analysis_start_time = new Date().getTime();
1955         PairwiseDomainSimilarityCalculator pw_calc = null;
1956         // double[] values_for_all_scores_histogram = null;
1957         final DomainSimilarityCalculator calc = new BasicDomainSimilarityCalculator( domain_similarity_sort_field,
1958                                                                                      sort_by_species_count_first,
1959                                                                                      number_of_genomes == 2 );
1960         switch ( scoring ) {
1961             case COMBINATIONS:
1962                 pw_calc = new CombinationsBasedPairwiseDomainSimilarityCalculator();
1963                 break;
1964             case DOMAINS:
1965                 pw_calc = new DomainCountsBasedPairwiseSimilarityCalculator();
1966                 break;
1967             case PROTEINS:
1968                 pw_calc = new ProteinCountsBasedPairwiseDomainSimilarityCalculator();
1969                 break;
1970             default:
1971                 ForesterUtil.unexpectedFatalError( surfacing.PRG_NAME, "unknown value for sorting for scoring" );
1972         }
1973         DomainSimilarityCalculator.GoAnnotationOutput go_annotation_output = DomainSimilarityCalculator.GoAnnotationOutput.NONE;
1974         if ( domain_id_to_go_ids_map != null ) {
1975             go_annotation_output = DomainSimilarityCalculator.GoAnnotationOutput.ALL;
1976         }
1977         final SortedSet<DomainSimilarity> similarities = calc
1978                 .calculateSimilarities( pw_calc,
1979                                         gwcd_list,
1980                                         ignore_domains_without_combs_in_all_spec,
1981                                         ignore_species_specific_domains );
1982         SurfacingUtil.decoratePrintableDomainSimilarities( similarities,
1983                                                            detailedness,
1984                                                            go_annotation_output,
1985                                                            go_id_to_term_map,
1986                                                            go_namespace_limit );
1987         DescriptiveStatistics pw_stats = null;
1988         try {
1989             String my_outfile = output_file.toString();
1990             if ( !my_outfile.endsWith( ".html" ) ) {
1991                 my_outfile += ".html";
1992             }
1993             final Writer writer = new BufferedWriter( new FileWriter( out_dir == null ? my_outfile : out_dir
1994                     + ForesterUtil.FILE_SEPARATOR + my_outfile ) );
1995             List<Species> species_order = null;
1996             if ( species_matrix ) {
1997                 species_order = new ArrayList<Species>();
1998                 for( int i = 0; i < number_of_genomes; i++ ) {
1999                     species_order.add( new BasicSpecies( input_file_properties[ i ][ 1 ] ) );
2000                 }
2001             }
2002             html_desc.append( "<tr><td>Sum of all distinct binary combinations:</td><td>"
2003                     + all_bin_domain_combinations_encountered.size() + "</td></tr>" + nl );
2004             html_desc.append( "<tr><td>Sum of all distinct domains:</td><td>" + all_domains_encountered.size()
2005                     + "</td></tr>" + nl );
2006             html_desc.append( "<tr><td>Analysis date/time:</td><td>"
2007                     + new java.text.SimpleDateFormat( "yyyy.MM.dd HH:mm:ss" ).format( new java.util.Date() )
2008                     + "</td></tr>" + nl );
2009             html_desc.append( "</table>" + nl );
2010             pw_stats = SurfacingUtil
2011                     .writeDomainSimilaritiesToFile( html_desc,
2012                                                     new StringBuilder( number_of_genomes + " genomes" ),
2013                                                     writer,
2014                                                     similarities,
2015                                                     number_of_genomes == 2,
2016                                                     species_order,
2017                                                     domain_similarity_print_option,
2018                                                     domain_similarity_sort_field,
2019                                                     scoring,
2020                                                     true );
2021             ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote main output (includes domain similarities) to: \""
2022                     + ( out_dir == null ? my_outfile : out_dir + ForesterUtil.FILE_SEPARATOR + my_outfile ) + "\"" );
2023         }
2024         catch ( final IOException e ) {
2025             ForesterUtil.fatalError( surfacing.PRG_NAME, "Failed to write similarites to: \"" + output_file + "\" ["
2026                     + e.getMessage() + "]" );
2027         }
2028         System.out.println();
2029         // values_for_all_scores_histogram = pw_stats.getDataAsDoubleArray();
2030         final Species[] species = new Species[ number_of_genomes ];
2031         for( int i = 0; i < number_of_genomes; ++i ) {
2032             species[ i ] = new BasicSpecies( input_file_properties[ i ][ 1 ] );
2033         }
2034         List<Phylogeny> inferred_trees = null;
2035         if ( ( number_of_genomes > 2 ) && perform_pwc ) {
2036             final PairwiseGenomeComparator pwgc = new PairwiseGenomeComparator();
2037             pwgc.performPairwiseComparisons( html_desc,
2038                                              sort_by_species_count_first,
2039                                              detailedness,
2040                                              ignore_domains_without_combs_in_all_spec,
2041                                              ignore_species_specific_domains,
2042                                              domain_similarity_sort_field_for_automated_pwc,
2043                                              domain_similarity_print_option,
2044                                              scoring,
2045                                              domain_id_to_go_ids_map,
2046                                              go_id_to_term_map,
2047                                              go_namespace_limit,
2048                                              species,
2049                                              number_of_genomes,
2050                                              gwcd_list,
2051                                              pw_calc,
2052                                              automated_pairwise_comparison_suffix,
2053                                              true,
2054                                              surfacing.PAIRWISE_DOMAIN_COMPARISONS_PREFIX,
2055                                              surfacing.PRG_NAME,
2056                                              out_dir,
2057                                              write_pwc_files );
2058             String matrix_output_file = new String( output_file.toString() );
2059             if ( matrix_output_file.indexOf( '.' ) > 1 ) {
2060                 matrix_output_file = matrix_output_file.substring( 0, matrix_output_file.indexOf( '.' ) );
2061             }
2062             if ( out_dir != null ) {
2063                 matrix_output_file = out_dir + ForesterUtil.FILE_SEPARATOR + matrix_output_file;
2064                 output_file = new File( out_dir + ForesterUtil.FILE_SEPARATOR + output_file );
2065             }
2066             SurfacingUtil.writeMatrixToFile( new File( matrix_output_file
2067                     + surfacing.MATRIX_MEAN_SCORE_BASED_GENOME_DISTANCE_SUFFIX ), pwgc.getDomainDistanceScoresMeans() );
2068             SurfacingUtil
2069                     .writeMatrixToFile( new File( matrix_output_file
2070                                                 + surfacing.MATRIX_SHARED_BIN_COMBINATIONS_BASED_GENOME_DISTANCE_SUFFIX ),
2071                                         pwgc.getSharedBinaryCombinationsBasedDistances() );
2072             SurfacingUtil.writeMatrixToFile( new File( matrix_output_file
2073                                                      + surfacing.MATRIX_SHARED_DOMAINS_BASED_GENOME_DISTANCE_SUFFIX ),
2074                                              pwgc.getSharedDomainsBasedDistances() );
2075             final Phylogeny nj_gd = SurfacingUtil.createNjTreeBasedOnMatrixToFile( new File( matrix_output_file
2076                     + surfacing.NJ_TREE_MEAN_SCORE_BASED_GENOME_DISTANCE_SUFFIX ), pwgc.getDomainDistanceScoresMeans()
2077                     .get( 0 ) );
2078             final Phylogeny nj_bc = SurfacingUtil.createNjTreeBasedOnMatrixToFile( new File( matrix_output_file
2079                     + surfacing.NJ_TREE_SHARED_BIN_COMBINATIONS_BASED_GENOME_DISTANCE_SUFFIX ), pwgc
2080                     .getSharedBinaryCombinationsBasedDistances().get( 0 ) );
2081             final Phylogeny nj_d = SurfacingUtil.createNjTreeBasedOnMatrixToFile( new File( matrix_output_file
2082                     + surfacing.NJ_TREE_SHARED_DOMAINS_BASED_GENOME_DISTANCE_SUFFIX ), pwgc
2083                     .getSharedDomainsBasedDistances().get( 0 ) );
2084             inferred_trees = new ArrayList<Phylogeny>();
2085             inferred_trees.add( nj_gd );
2086             inferred_trees.add( nj_bc );
2087             inferred_trees.add( nj_d );
2088             if ( jacknifed_distances ) {
2089                 pwgc.performPairwiseComparisonsJacknifed( species,
2090                                                           number_of_genomes,
2091                                                           gwcd_list,
2092                                                           true,
2093                                                           jacknife_resamplings,
2094                                                           jacknife_ratio,
2095                                                           random_seed );
2096                 SurfacingUtil
2097                         .writeMatrixToFile( new File( matrix_output_file
2098                                                     + "_"
2099                                                     + ForesterUtil.round( jacknife_ratio, 2 )
2100                                                     + "_"
2101                                                     + jacknife_resamplings
2102                                                     + surfacing.MATRIX_SHARED_BIN_COMBINATIONS_BASED_GENOME_DISTANCE_SUFFIX ),
2103                                             pwgc.getSharedBinaryCombinationsBasedDistances() );
2104                 SurfacingUtil
2105                         .writeMatrixToFile( new File( matrix_output_file + "_" + ForesterUtil.round( jacknife_ratio, 2 )
2106                                                     + "_" + jacknife_resamplings
2107                                                     + surfacing.MATRIX_SHARED_DOMAINS_BASED_GENOME_DISTANCE_SUFFIX ),
2108                                             pwgc.getSharedDomainsBasedDistances() );
2109                 //                if ( infer_species_trees ) {
2110                 //                    inferSpeciesTrees( new File( output_file + "_" + jacknife_resamplings
2111                 //                            + INFERRED_SBC_BASED_NJ_SPECIES_TREE_SUFFIX ), pwgc
2112                 //                            .getSharedBinaryCombinationsBasedDistances() );
2113                 //                    inferSpeciesTrees( new File( output_file + "_" + jacknife_resamplings
2114                 //                            + INFERRED_SD_BASED_NJ_SPECIES_TREE_SUFFIX ), pwgc.getSharedDomainsBasedDistances() );
2115                 //                }
2116             }
2117         } // if ( ( output_file != null ) && ( number_of_genomes > 2 ) && !isEmpty( automated_pairwise_comparison_suffix ) )
2118         if ( ( out_dir != null ) && ( !perform_pwc ) ) {
2119             output_file = new File( out_dir + ForesterUtil.FILE_SEPARATOR + output_file );
2120         }
2121         writePresentToNexus( output_file, positive_filter_file, filter, gwcd_list );
2122         if ( ( ( intrees != null ) && ( intrees.length > 0 ) ) && ( number_of_genomes > 2 ) ) {
2123             final StringBuilder parameters_sb = createParametersAsString( ignore_dufs,
2124                                                                           e_value_max,
2125                                                                           max_allowed_overlap,
2126                                                                           no_engulfing_overlaps,
2127                                                                           cutoff_scores_file,
2128                                                                           dc_type );
2129             String s = "_";
2130             if ( radomize_fitch_parsimony ) {
2131                 s += random_number_seed_for_fitch_parsimony + "_";
2132             }
2133             int i = 0;
2134             for( final Phylogeny intree : intrees ) {
2135                 final String outfile_name = ForesterUtil.removeSuffix( output_file.toString() ) + s
2136                         + ForesterUtil.removeSuffix( intree_files[ i ].toString() );
2137                 final DomainParsimonyCalculator domain_parsimony = DomainParsimonyCalculator.createInstance( intree,
2138                                                                                                              gwcd_list );
2139                 SurfacingUtil.executeParsimonyAnalysis( random_number_seed_for_fitch_parsimony,
2140                                                         radomize_fitch_parsimony,
2141                                                         outfile_name,
2142                                                         domain_parsimony,
2143                                                         intree,
2144                                                         domain_id_to_go_ids_map,
2145                                                         go_id_to_term_map,
2146                                                         go_namespace_limit,
2147                                                         parameters_sb.toString(),
2148                                                         domain_id_to_secondary_features_maps,
2149                                                         positive_filter_file == null ? null : filter,
2150                                                         output_binary_domain_combinationsfor_graph_analysis,
2151                                                         all_bin_domain_combinations_gained_fitch,
2152                                                         all_bin_domain_combinations_lost_fitch,
2153                                                         dc_type );
2154                 // Listing of all domain combinations gained is only done if only one input tree is used. 
2155                 if ( ( domain_id_to_secondary_features_maps != null )
2156                         && ( domain_id_to_secondary_features_maps.length > 0 ) ) {
2157                     int j = 0;
2158                     for( final Map<DomainId, Set<String>> domain_id_to_secondary_features_map : domain_id_to_secondary_features_maps ) {
2159                         final Map<Species, MappingResults> mapping_results_map = new TreeMap<Species, MappingResults>();
2160                         final DomainParsimonyCalculator secondary_features_parsimony = DomainParsimonyCalculator
2161                                 .createInstance( intree, gwcd_list, domain_id_to_secondary_features_map );
2162                         SurfacingUtil
2163                                 .executeParsimonyAnalysisForSecondaryFeatures( outfile_name
2164                                                                                        + "_"
2165                                                                                        + secondary_features_map_files[ j++ ],
2166                                                                                secondary_features_parsimony,
2167                                                                                intree,
2168                                                                                parameters_sb.toString(),
2169                                                                                mapping_results_map );
2170                         if ( i == 0 ) {
2171                             System.out.println();
2172                             System.out.println( "Mapping to secondary features:" );
2173                             for( final Species spec : mapping_results_map.keySet() ) {
2174                                 final MappingResults mapping_results = mapping_results_map.get( spec );
2175                                 final int total_domains = mapping_results.getSumOfFailures()
2176                                         + mapping_results.getSumOfSuccesses();
2177                                 System.out.print( spec + ":" );
2178                                 System.out.print( " mapped domains = " + mapping_results.getSumOfSuccesses() );
2179                                 System.out.print( ", not mapped domains = " + mapping_results.getSumOfFailures() );
2180                                 if ( total_domains > 0 ) {
2181                                     System.out.println( ", mapped ratio = "
2182                                             + ( 100 * mapping_results.getSumOfSuccesses() / total_domains ) + "%" );
2183                                 }
2184                                 else {
2185                                     System.out.println( ", mapped ratio = n/a (total domains = 0 )" );
2186                                 }
2187                             }
2188                         }
2189                     }
2190                 }
2191                 i++;
2192             } // for( final Phylogeny intree : intrees ) {
2193         }
2194         if ( plus_minus_analysis_high_copy_base_species.size() > 0 ) {
2195             executePlusMinusAnalysis( output_file,
2196                                       plus_minus_analysis_high_copy_base_species,
2197                                       plus_minus_analysis_high_copy_target_species,
2198                                       plus_minus_analysis_high_low_copy_species,
2199                                       gwcd_list,
2200                                       protein_lists_per_species,
2201                                       domain_id_to_go_ids_map,
2202                                       go_id_to_term_map,
2203                                       plus_minus_analysis_numbers );
2204         }
2205         if ( output_protein_lists_for_all_domains ) {
2206             writeProteinListsForAllSpecies( out_dir, protein_lists_per_species, gwcd_list );
2207         }
2208         //        if ( ( intrees != null ) && ( intrees.length > 0 ) && ( inferred_trees != null ) && ( inferred_trees.size() > 0 ) ) {
2209         //            final StringBuilder parameters_sb = createParametersAsString( ignore_dufs,
2210         //                                                                          e_value_max,
2211         //                                                                          max_allowed_overlap,
2212         //                                                                          no_engulfing_overlaps,
2213         //                                                                          cutoff_scores_file );
2214         //            String s = "_";
2215         //            if ( radomize_fitch_parsimony ) {
2216         //                s += random_number_seed_for_fitch_parsimony + "_";
2217         //            }
2218         //            int i = 0;
2219         //            for( final Phylogeny inferred_tree : inferred_trees ) {
2220         //                if ( !inferred_tree.isRooted() ) { 
2221         //                    intrees[ 0 ].getRoot().getName();
2222         //                    inferred_tree.r
2223         //                }
2224         //                final String outfile_name = ForesterUtil.removeSuffix( inferred_tree.getName() ) + s;
2225         //                final DomainParsimonyCalculator domain_parsimony = DomainParsimonyCalculator
2226         //                        .createInstance( inferred_tree, gwcd_list );
2227         //                SurfacingUtil.executeParsimonyAnalysis( random_number_seed_for_fitch_parsimony,
2228         //                                                        radomize_fitch_parsimony,
2229         //                                                        outfile_name,
2230         //                                                        domain_parsimony,
2231         //                                                        inferred_tree,
2232         //                                                        domain_id_to_go_ids_map,
2233         //                                                        go_id_to_term_map,
2234         //                                                        go_namespace_limit,
2235         //                                                        parameters_sb.toString() );
2236         //                i++;
2237         //            }
2238         //        }
2239         if ( all_bin_domain_combinations_gained_fitch != null ) {
2240             try {
2241                 executeFitchGainsAnalysis( new File( output_file
2242                                                    + surfacing.OUTPUT_DOMAIN_COMBINATIONS_GAINED_MORE_THAN_ONCE_ANALYSIS_SUFFIX ),
2243                                            all_bin_domain_combinations_gained_fitch,
2244                                            all_domains_encountered.size(),
2245                                            all_bin_domain_combinations_encountered,
2246                                            true );
2247             }
2248             catch ( final IOException e ) {
2249                 ForesterUtil.fatalError( PRG_NAME, e.getLocalizedMessage() );
2250             }
2251         }
2252         if ( all_bin_domain_combinations_lost_fitch != null ) {
2253             try {
2254                 executeFitchGainsAnalysis( new File( output_file
2255                                                    + surfacing.OUTPUT_DOMAIN_COMBINATIONS_LOST_MORE_THAN_ONCE_ANALYSIS_SUFFIX ),
2256                                            all_bin_domain_combinations_lost_fitch,
2257                                            all_domains_encountered.size(),
2258                                            all_bin_domain_combinations_encountered,
2259                                            false );
2260             }
2261             catch ( final IOException e ) {
2262                 ForesterUtil.fatalError( PRG_NAME, e.getLocalizedMessage() );
2263             }
2264         }
2265         final Runtime rt = java.lang.Runtime.getRuntime();
2266         final long free_memory = rt.freeMemory() / 1000000;
2267         final long total_memory = rt.totalMemory() / 1000000;
2268         System.out.println();
2269         System.out.println( "Time for analysis : " + ( new Date().getTime() - analysis_start_time ) + "ms" );
2270         System.out.println( "Total running time: " + ( new Date().getTime() - start_time ) + "ms " );
2271         System.out.println( "Free memory       : " + free_memory + "MB, total memory: " + total_memory + "MB" );
2272         System.out.println();
2273         System.out.println( "If this application is useful to you, please cite:" );
2274         System.out.println( surfacing.WWW );
2275         System.out.println();
2276         ForesterUtil.programMessage( PRG_NAME, "OK" );
2277         System.out.println();
2278     }
2279
2280     private static void preparePhylogenyForParsimonyAnalyses( final Phylogeny intree,
2281                                                               final String[][] input_file_properties ) {
2282         final String[] genomes = new String[ input_file_properties.length ];
2283         for( int i = 0; i < input_file_properties.length; ++i ) {
2284             if ( intree.getNodes( input_file_properties[ i ][ 1 ] ).size() > 1 ) {
2285                 ForesterUtil.fatalError( surfacing.PRG_NAME, "node named [" + input_file_properties[ i ][ 1 ]
2286                         + "] is not unique in input tree " + intree.getName() );
2287             }
2288             genomes[ i ] = input_file_properties[ i ][ 1 ];
2289         }
2290         //
2291         final PhylogenyNodeIterator it = intree.iteratorPostorder();
2292         while ( it.hasNext() ) {
2293             final PhylogenyNode n = it.next();
2294             if ( ForesterUtil.isEmpty( n.getName() ) ) {
2295                 if ( n.getNodeData().isHasTaxonomy()
2296                         && !ForesterUtil.isEmpty( n.getNodeData().getTaxonomy().getScientificName() ) ) {
2297                     n.setName( n.getNodeData().getTaxonomy().getScientificName() );
2298                 }
2299                 else {
2300                     ForesterUtil.fatalError( surfacing.PRG_NAME,
2301                                              "node without both name and scientific taxonomy name found" );
2302                 }
2303             }
2304         }
2305         //
2306         final List<String> igns = PhylogenyMethods.deleteExternalNodesPositiveSelection( genomes, intree );
2307         if ( igns.size() > 0 ) {
2308             System.out.println( "Not using the following " + igns.size() + " nodes:" );
2309             for( int i = 0; i < igns.size(); ++i ) {
2310                 System.out.println( " " + i + ": " + igns.get( i ) );
2311             }
2312             System.out.println( "--" );
2313         }
2314         for( int i = 0; i < input_file_properties.length; ++i ) {
2315             try {
2316                 intree.getNode( input_file_properties[ i ][ 1 ] );
2317             }
2318             catch ( final IllegalArgumentException e ) {
2319                 ForesterUtil.fatalError( surfacing.PRG_NAME, "node named [" + input_file_properties[ i ][ 1 ]
2320                         + "] not present/not unique in input tree" );
2321             }
2322         }
2323     }
2324
2325     // public static StringBuffer stringCombinableDomainsMapToStringBuffer(
2326     // final SortedMap<String, CombinableDomains> map ) {
2327     // final StringBuffer sb = new StringBuffer();
2328     // for( final Iterator<String> iter = map.keySet().iterator();
2329     // iter.hasNext(); ) {
2330     // final Object key = iter.next();
2331     // sb.append( ForesterUtil.pad( new StringBuffer( key.toString() ), 18, ' ',
2332     // false ) );
2333     // final CombinableDomains domain_combination = map.get( key );
2334     // sb.append( ForesterUtil.pad( new StringBuffer( "" +
2335     // domain_combination.getNumberOfCombiningDomains() ), 8,
2336     // ' ', false ) );
2337     // sb.append( domain_combination.toStringBuffer() );
2338     // sb.append( ForesterUtil.getLineSeparator() );
2339     // }
2340     // return sb;
2341     // }
2342     private static void printHelp() {
2343         System.out.println();
2344         System.out.println( "Usage:" );
2345         System.out.println();
2346         System.out.println( "% java -Xms256m -Xmx512m -cp forester.jar org.forester.applications." + surfacing.PRG_NAME
2347                 + " [options] <phylogen(y|ies) infile> [external node name 1] [name 2] ... [name n]" );
2348         System.out.println();
2349         System.out.println( " Note: This software might need a significant amount of memory (heap space);" );
2350         System.out
2351                 .println( "       hence use \"-Xms128m -Xmx512m\" (or more) to prevent a \"java.lang.OutOfMemoryError\"." );
2352         System.out.println();
2353         System.out.println( " Options: " );
2354         System.out.println( surfacing.DETAILEDNESS_OPTION + ": level of detail for similarities output file (default:"
2355                 + DETAILEDNESS_DEFAULT + ")" );
2356         System.out.println( surfacing.IGNORE_COMBINATION_WITH_SAME_OPTION
2357                 + ": to ignore combinations with self (default: not to ignore)" );
2358         System.out
2359                 .println( surfacing.IGNORE_DOMAINS_WITHOUT_COMBINATIONS_IN_ALL_SPECIES_OPTION
2360                         + ": to ignore domains without combinations in any species (for similarity calc purposes, not for parsimony analyses) (default: not to ignore)" );
2361         System.out
2362                 .println( surfacing.IGNORE_DOMAINS_SPECIFIC_TO_ONE_SPECIES_OPTION
2363                         + ": to ignore domains specific to one species (for similarity calc purposes, not for parsimony analyses) (default: not to ignore)" );
2364         System.out.println( surfacing.NOT_IGNORE_DUFS_OPTION
2365                 + ": to _not_ ignore DUFs (domains with unknown function) (default: ignore DUFs)" );
2366         System.out
2367                 .println( surfacing.IGNORE_VIRAL_IDS
2368                         + ": to ignore domains with ids containing 'vir', 'retro', 'transpos', 'phage', or starting with 'rv' or 'gag_'" );
2369         System.out.println( surfacing.DOMAIN_SIMILARITY_SORT_OPTION + ": sorting for similarities (default: "
2370                 + DOMAIN_SORT_FILD_DEFAULT + ")" );
2371         System.out.println( surfacing.OUTPUT_FILE_OPTION + ": name for (main) output file (mandatory)" );
2372         System.out.println( surfacing.MAX_E_VALUE_OPTION + ": max (inclusive) E-value" );
2373         System.out.println( surfacing.MAX_ALLOWED_OVERLAP_OPTION + ": maximal allowed domain overlap" );
2374         System.out.println( surfacing.NO_ENGULFING_OVERLAP_OPTION + ": to ignore engulfed lower confidence domains" );
2375         System.out.println( surfacing.SPECIES_MATRIX_OPTION + ": species matrix" );
2376         System.out.println( surfacing.SCORING_OPTION + ": scoring (default:" + SCORING_DEFAULT + ")" );
2377         System.out.println( surfacing.DOMAIN_COUNT_SORT_OPTION + ": sorting for domain counts (default:"
2378                 + DOMAINS_SORT_ORDER_DEFAULT + ")" );
2379         System.out.println( surfacing.DOMAIN_SIMILARITY_PRINT_OPTION + ": domain similarity print option (default:"
2380                 + DOMAIN_SIMILARITY_PRINT_OPTION_DEFAULT + ")" );
2381         System.out.println( surfacing.CUTOFF_SCORE_FILE_OPTION + ": cutoff score file" );
2382         System.out.println( surfacing.DOMAIN_SIMILARITY_SORT_BY_SPECIES_COUNT_FIRST_OPTION
2383                 + ": sort by species count first" );
2384         System.out.println( surfacing.OUTPUT_DIR_OPTION + ": output directory" );
2385         System.out.println( surfacing.PFAM_TO_GO_FILE_USE_OPTION + ": Pfam to GO mapping file" );
2386         System.out.println( surfacing.GO_OBO_FILE_USE_OPTION + ": GO terms file (OBO format)" );
2387         System.out.println( surfacing.GO_NAMESPACE_LIMIT_OPTION + ": limit GO term to one GO namespace" );
2388         System.out.println( surfacing.PAIRWISE_DOMAIN_COMPARISONS_OPTION
2389                 + "[=<suffix for pairwise comparison output files>]: to perform pairwise comparison based analyses" );
2390         System.out.println( surfacing.INPUT_SPECIES_TREE_OPTION
2391                 + ": species tree, to perform (Dollo, Fitch) parismony analyses" );
2392         System.out
2393                 .println( JACKNIFE_OPTION
2394                         + ": perform jacknife resampling for domain and binary domain combination based distance matrices [default resamplings: "
2395                         + JACKNIFE_NUMBER_OF_RESAMPLINGS_DEFAULT + "]" );
2396         System.out.println( JACKNIFE_RATIO_OPTION + ": ratio for jacknife resampling [default: "
2397                 + JACKNIFE_RATIO_DEFAULT + "]" );
2398         System.out.println( JACKNIFE_RANDOM_SEED_OPTION
2399                 + ": seed for random number generator for jacknife resampling [default: "
2400                 + JACKNIFE_RANDOM_SEED_DEFAULT + "]" );
2401         //        System.out.println( surfacing.INFER_SPECIES_TREES_OPTION
2402         //                + ": to infer NJ species trees based on shared domains/binary domain combinations" );
2403         System.out
2404                 .println( surfacing.INPUT_SPECIES_TREE_OPTION
2405                         + "=<treefiles in phyloXML format, separated by #>: to infer domain/binary domain combination gains/losses on given species trees" );
2406         System.out.println( surfacing.FILTER_POSITIVE_OPTION
2407                 + "=<file>: to filter out proteins not containing at least one domain listed in <file>" );
2408         System.out.println( surfacing.FILTER_NEGATIVE_OPTION
2409                 + "=<file>: to filter out proteins containing at least one domain listed in <file>" );
2410         System.out.println( surfacing.FILTER_NEGATIVE_DOMAINS_OPTION
2411                 + "=<file>: to filter out (ignore) domains listed in <file>" );
2412         System.out.println( surfacing.INPUT_FILES_FROM_FILE_OPTION + "=<file>: to read input files from <file>" );
2413         System.out
2414                 .println( surfacing.RANDOM_SEED_FOR_FITCH_PARSIMONY_OPTION
2415                         + "=<seed>: seed for random number generator for Fitch Parsimony analysis (type: long, default: no randomization - given a choice, prefer absence" );
2416         System.out.println( surfacing.CONSIDER_DOMAIN_COMBINATION_DIRECTEDNESS
2417                 + ": to consider directedness in binary combinations: e.g. A-B != B-A" );
2418         System.out.println( surfacing.CONSIDER_DOMAIN_COMBINATION_DIRECTEDNESS_AND_ADJACENCY
2419                 + ": to consider directedness and adjacency in binary combinations" );
2420         System.out
2421                 .println( surfacing.SEQ_EXTRACT_OPTION
2422                         + "=<domain ids (Pfam names)>: to extract sequence names of sequences containing matching domains and/or domain-sequences (order N to C) (domain separator: '~', domain sequences speparator: '#', e.g. 'NACHT#BIR~CARD')" );
2423         System.out.println( surfacing.SECONDARY_FEATURES_PARSIMONY_MAP_FILE
2424                 + "=<file>: to perfom parsimony analysis on secondary features" );
2425         System.out.println( surfacing.PLUS_MINUS_ANALYSIS_OPTION + "=<file>: to presence/absence genome analysis" );
2426         System.out.println( surfacing.DOMAIN_COMBINITONS_OUTPUT_OPTION_FOR_GRAPH_ANALYSIS
2427                 + ": to output binary domain combinations for (downstream) graph analysis" );
2428         System.out.println( surfacing.OUTPUT_LIST_OF_ALL_PROTEINS_OPTIONS + ": to output all proteins per domain" );
2429         System.out.println();
2430         System.out.println();
2431         System.out.println( "Example: java -Xms128m -Xmx512m -cp path/to/forester.jar"
2432                 + " org.forester.application.surfacing -detail=punctilious -o=TEST.html -pwc=TEST"
2433                 + " -cos=Pfam_ls_22_TC2 -p2g=pfam2go -obo=gene_ontology_edit.obo "
2434                 + "-dc_sort=dom -ignore_with_self -no_singles -e=0.001 -mo=1 -no_eo "
2435                 + "-ds_output=detailed_html -scoring=domains -sort=alpha -" + JACKNIFE_OPTION
2436                 + "=50 human mouse brafl strpu" );
2437         System.out.println();
2438     }
2439
2440     private static void processFilter( final File filter_file, final SortedSet<DomainId> filter ) {
2441         SortedSet<String> filter_str = null;
2442         try {
2443             filter_str = ForesterUtil.file2set( filter_file );
2444         }
2445         catch ( final IOException e ) {
2446             ForesterUtil.fatalError( surfacing.PRG_NAME, e.getMessage() );
2447         }
2448         if ( filter_str != null ) {
2449             for( final String string : filter_str ) {
2450                 filter.add( new DomainId( string ) );
2451             }
2452         }
2453         if ( VERBOSE ) {
2454             System.out.println( "Filter:" );
2455             for( final DomainId domainId : filter ) {
2456                 System.out.println( domainId.getId() );
2457             }
2458         }
2459     }
2460
2461     private static String[][] processInputFileNames( final String[] names ) {
2462         final String[][] input_file_properties = new String[ names.length ][];
2463         for( int i = 0; i < names.length; ++i ) {
2464             if ( names[ i ].indexOf( SEPARATOR_FOR_INPUT_VALUES ) < 0 ) {
2465                 input_file_properties[ i ] = new String[ 2 ];
2466                 input_file_properties[ i ][ 0 ] = names[ i ];
2467                 input_file_properties[ i ][ 1 ] = names[ i ];
2468             }
2469             else {
2470                 input_file_properties[ i ] = names[ i ].split( surfacing.SEPARATOR_FOR_INPUT_VALUES + "" );
2471                 if ( input_file_properties[ i ].length != 3 ) {
2472                     ForesterUtil
2473                             .fatalError( surfacing.PRG_NAME,
2474                                          "properties for the input files (hmmpfam output) are expected "
2475                                                  + "to be in the following format \"<hmmpfam output file>#<species>\" (or just one word, which is both the filename and the species id), instead received \""
2476                                                  + names[ i ] + "\"" );
2477                 }
2478             }
2479             final String error = ForesterUtil.isReadableFile( new File( input_file_properties[ i ][ 0 ] ) );
2480             if ( !ForesterUtil.isEmpty( error ) ) {
2481                 ForesterUtil.fatalError( surfacing.PRG_NAME, error );
2482             }
2483         }
2484         return input_file_properties;
2485     }
2486
2487     private static void processPlusMinusAnalysisOption( final CommandLineArguments cla,
2488                                                         final List<String> high_copy_base,
2489                                                         final List<String> high_copy_target,
2490                                                         final List<String> low_copy,
2491                                                         final List<Object> numbers ) {
2492         if ( cla.isOptionSet( surfacing.PLUS_MINUS_ANALYSIS_OPTION ) ) {
2493             if ( !cla.isOptionValueSet( surfacing.PLUS_MINUS_ANALYSIS_OPTION ) ) {
2494                 ForesterUtil.fatalError( surfacing.PRG_NAME, "no value for 'plus-minus' file: -"
2495                         + surfacing.PLUS_MINUS_ANALYSIS_OPTION + "=<file>" );
2496             }
2497             final File plus_minus_file = new File( cla.getOptionValue( surfacing.PLUS_MINUS_ANALYSIS_OPTION ) );
2498             final String msg = ForesterUtil.isReadableFile( plus_minus_file );
2499             if ( !ForesterUtil.isEmpty( msg ) ) {
2500                 ForesterUtil.fatalError( surfacing.PRG_NAME, "can not read from \"" + plus_minus_file + "\": " + msg );
2501             }
2502             processPlusMinusFile( plus_minus_file, high_copy_base, high_copy_target, low_copy, numbers );
2503         }
2504     }
2505
2506     // First numbers is minimal difference, second is factor.
2507     private static void processPlusMinusFile( final File plus_minus_file,
2508                                               final List<String> high_copy_base,
2509                                               final List<String> high_copy_target,
2510                                               final List<String> low_copy,
2511                                               final List<Object> numbers ) {
2512         Set<String> species_set = null;
2513         int min_diff = PLUS_MINUS_ANALYSIS_MIN_DIFF_DEFAULT;
2514         double factor = PLUS_MINUS_ANALYSIS_FACTOR_DEFAULT;
2515         try {
2516             species_set = ForesterUtil.file2set( plus_minus_file );
2517         }
2518         catch ( final IOException e ) {
2519             ForesterUtil.fatalError( surfacing.PRG_NAME, e.getMessage() );
2520         }
2521         if ( species_set != null ) {
2522             for( final String species : species_set ) {
2523                 final String species_trimmed = species.substring( 1 );
2524                 if ( species.startsWith( "+" ) ) {
2525                     if ( low_copy.contains( species_trimmed ) ) {
2526                         ForesterUtil.fatalError( surfacing.PRG_NAME,
2527                                                  "species/genome names can not appear with both '+' and '-' suffix, as appears the case for: \""
2528                                                          + species_trimmed + "\"" );
2529                     }
2530                     high_copy_base.add( species_trimmed );
2531                 }
2532                 else if ( species.startsWith( "*" ) ) {
2533                     if ( low_copy.contains( species_trimmed ) ) {
2534                         ForesterUtil.fatalError( surfacing.PRG_NAME,
2535                                                  "species/genome names can not appear with both '*' and '-' suffix, as appears the case for: \""
2536                                                          + species_trimmed + "\"" );
2537                     }
2538                     high_copy_target.add( species_trimmed );
2539                 }
2540                 else if ( species.startsWith( "-" ) ) {
2541                     if ( high_copy_base.contains( species_trimmed ) || high_copy_target.contains( species_trimmed ) ) {
2542                         ForesterUtil.fatalError( surfacing.PRG_NAME,
2543                                                  "species/genome names can not appear with both '+' or '*' and '-' suffix, as appears the case for: \""
2544                                                          + species_trimmed + "\"" );
2545                     }
2546                     low_copy.add( species_trimmed );
2547                 }
2548                 else if ( species.startsWith( "$D" ) ) {
2549                     try {
2550                         min_diff = Integer.parseInt( species.substring( 3 ) );
2551                     }
2552                     catch ( final NumberFormatException e ) {
2553                         ForesterUtil.fatalError( surfacing.PRG_NAME,
2554                                                  "could not parse integer value for minimal difference from: \""
2555                                                          + species.substring( 3 ) + "\"" );
2556                     }
2557                 }
2558                 else if ( species.startsWith( "$F" ) ) {
2559                     try {
2560                         factor = Double.parseDouble( species.substring( 3 ) );
2561                     }
2562                     catch ( final NumberFormatException e ) {
2563                         ForesterUtil.fatalError( surfacing.PRG_NAME, "could not parse double value for factor from: \""
2564                                 + species.substring( 3 ) + "\"" );
2565                     }
2566                 }
2567                 else if ( species.startsWith( "#" ) ) {
2568                     // Comment, ignore.
2569                 }
2570                 else {
2571                     ForesterUtil
2572                             .fatalError( surfacing.PRG_NAME,
2573                                          "species/genome names in 'plus minus' file must begin with '*' (high copy target genome), '+' (high copy base genomes), '-' (low copy genomes), '$D=<integer>' minimal Difference (default is 1), '$F=<double>' factor (default is 1.0), double), or '#' (ignore) suffix, encountered: \""
2574                                                  + species + "\"" );
2575                 }
2576                 numbers.add( new Integer( min_diff + "" ) );
2577                 numbers.add( new Double( factor + "" ) );
2578             }
2579         }
2580         else {
2581             ForesterUtil.fatalError( surfacing.PRG_NAME, "'plus minus' file [" + plus_minus_file + "] appears empty" );
2582         }
2583     }
2584
2585     private static void writePresentToNexus( final File output_file,
2586                                              final File positive_filter_file,
2587                                              final SortedSet<DomainId> filter,
2588                                              final List<GenomeWideCombinableDomains> gwcd_list ) {
2589         try {
2590             SurfacingUtil
2591                     .writeMatrixToFile( DomainParsimonyCalculator
2592                             .createMatrixOfDomainPresenceOrAbsence( gwcd_list, positive_filter_file == null ? null
2593                                     : filter ), output_file + DOMAINS_PRESENT_NEXUS, Format.NEXUS_BINARY );
2594             SurfacingUtil.writeMatrixToFile( DomainParsimonyCalculator
2595                     .createMatrixOfBinaryDomainCombinationPresenceOrAbsence( gwcd_list ), output_file
2596                     + BDC_PRESENT_NEXUS, Format.NEXUS_BINARY );
2597         }
2598         catch ( final Exception e ) {
2599             ForesterUtil.fatalError( surfacing.PRG_NAME, e.getLocalizedMessage() );
2600         }
2601     }
2602
2603     private static void writeProteinListsForAllSpecies( final File output_dir,
2604                                                         final SortedMap<Species, List<Protein>> protein_lists_per_species,
2605                                                         final List<GenomeWideCombinableDomains> gwcd_list ) {
2606         final SortedSet<DomainId> all_domains = new TreeSet<DomainId>();
2607         for( final GenomeWideCombinableDomains gwcd : gwcd_list ) {
2608             all_domains.addAll( gwcd.getAllDomainIds() );
2609         }
2610         for( final DomainId domain : all_domains ) {
2611             final File out = new File( output_dir + ForesterUtil.FILE_SEPARATOR + domain + SEQ_EXTRACT_SUFFIX );
2612             SurfacingUtil.checkForOutputFileWriteability( out );
2613             try {
2614                 final Writer proteins_file_writer = new BufferedWriter( new FileWriter( out ) );
2615                 SurfacingUtil.extractProteinNames( protein_lists_per_species, domain, proteins_file_writer, "\t" );
2616                 proteins_file_writer.close();
2617             }
2618             catch ( final IOException e ) {
2619                 ForesterUtil.fatalError( surfacing.PRG_NAME, e.getLocalizedMessage() );
2620             }
2621             ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote proteins list to \"" + out + "\"" );
2622         }
2623     }
2624 }