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