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