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