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