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