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