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