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