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