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