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