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