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