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