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