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