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