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