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