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