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