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