3 // FORESTER -- software libraries and applications
4 // for evolutionary biology research and applications.
6 // Copyright (C) 2008-2009 Christian M. Zmasek
7 // Copyright (C) 2008-2009 Burnham Institute for Medical Research
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.
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.
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
24 // Contact: phylosoft @ gmail . com
25 // WWW: www.phylosoft.org/forester
27 package org.forester.surfacing;
29 import java.io.BufferedWriter;
31 import java.io.FileWriter;
32 import java.io.IOException;
33 import java.io.Writer;
34 import java.text.DecimalFormat;
35 import java.text.NumberFormat;
36 import java.util.ArrayList;
37 import java.util.Collections;
38 import java.util.Comparator;
39 import java.util.HashMap;
40 import java.util.HashSet;
41 import java.util.List;
44 import java.util.SortedMap;
45 import java.util.SortedSet;
46 import java.util.TreeMap;
47 import java.util.TreeSet;
48 import java.util.regex.Matcher;
49 import java.util.regex.Pattern;
51 import org.forester.application.surfacing;
52 import org.forester.evoinference.distance.NeighborJoining;
53 import org.forester.evoinference.matrix.character.BasicCharacterStateMatrix;
54 import org.forester.evoinference.matrix.character.CharacterStateMatrix;
55 import org.forester.evoinference.matrix.character.CharacterStateMatrix.BinaryStates;
56 import org.forester.evoinference.matrix.character.CharacterStateMatrix.Format;
57 import org.forester.evoinference.matrix.character.CharacterStateMatrix.GainLossStates;
58 import org.forester.evoinference.matrix.distance.DistanceMatrix;
59 import org.forester.go.GoId;
60 import org.forester.go.GoNameSpace;
61 import org.forester.go.GoTerm;
62 import org.forester.go.GoUtils;
63 import org.forester.go.PfamToGoMapping;
64 import org.forester.io.parsers.nexus.NexusConstants;
65 import org.forester.io.writers.PhylogenyWriter;
66 import org.forester.phylogeny.Phylogeny;
67 import org.forester.phylogeny.PhylogenyMethods;
68 import org.forester.phylogeny.PhylogenyNode;
69 import org.forester.phylogeny.data.BinaryCharacters;
70 import org.forester.phylogeny.data.Confidence;
71 import org.forester.phylogeny.iterators.PhylogenyNodeIterator;
72 import org.forester.surfacing.DomainSimilarityCalculator.Detailedness;
73 import org.forester.surfacing.DomainSimilarityCalculator.GoAnnotationOutput;
74 import org.forester.surfacing.GenomeWideCombinableDomains.GenomeWideCombinableDomainsSortOrder;
75 import org.forester.util.AsciiHistogram;
76 import org.forester.util.BasicDescriptiveStatistics;
77 import org.forester.util.BasicTable;
78 import org.forester.util.BasicTableParser;
79 import org.forester.util.DescriptiveStatistics;
80 import org.forester.util.ForesterUtil;
82 public final class SurfacingUtil {
84 private final static NumberFormat FORMATTER = new DecimalFormat( "0.0E0" );
85 private final static NumberFormat FORMATTER_3 = new DecimalFormat( "0.000" );
86 private static final Comparator<Domain> ASCENDING_CONFIDENCE_VALUE_ORDER = new Comparator<Domain>() {
89 public int compare( final Domain d1,
91 if ( d1.getPerSequenceEvalue() < d2
92 .getPerSequenceEvalue() ) {
96 .getPerSequenceEvalue() > d2
97 .getPerSequenceEvalue() ) {
101 return d1.compareTo( d2 );
105 public final static Pattern PATTERN_SP_STYLE_TAXONOMY = Pattern.compile( "^[A-Z0-9]{3,5}$" );
107 private SurfacingUtil() {
108 // Hidden constructor.
111 public static void addAllBinaryDomainCombinationToSet( final GenomeWideCombinableDomains genome,
112 final SortedSet<BinaryDomainCombination> binary_domain_combinations ) {
113 final SortedMap<DomainId, CombinableDomains> all_cd = genome.getAllCombinableDomainsIds();
114 for( final DomainId domain_id : all_cd.keySet() ) {
115 binary_domain_combinations.addAll( all_cd.get( domain_id ).toBinaryDomainCombinations() );
119 public static void addAllDomainIdsToSet( final GenomeWideCombinableDomains genome,
120 final SortedSet<DomainId> domain_ids ) {
121 final SortedSet<DomainId> domains = genome.getAllDomainIds();
122 for( final DomainId domain : domains ) {
123 domain_ids.add( domain );
127 public static void addHtmlHead( final Writer w, final String title ) throws IOException {
128 w.write( SurfacingConstants.NL );
130 w.write( "<title>" );
132 w.write( "</title>" );
133 w.write( SurfacingConstants.NL );
134 w.write( "<style>" );
135 w.write( SurfacingConstants.NL );
136 w.write( "a:visited { color : #6633FF; text-decoration : none; }" );
137 w.write( SurfacingConstants.NL );
138 w.write( "a:link { color : #6633FF; text-decoration : none; }" );
139 w.write( SurfacingConstants.NL );
140 w.write( "a:active { color : #99FF00; text-decoration : none; }" );
141 w.write( SurfacingConstants.NL );
142 w.write( "a:hover { color : #FFFFFF; background-color : #99FF00; text-decoration : none; }" );
143 w.write( SurfacingConstants.NL );
144 w.write( "td { text-align: left; vertical-align: top; font-family: Verdana, Arial, Helvetica; font-size: 8pt}" );
145 w.write( SurfacingConstants.NL );
146 w.write( "h1 { color : #0000FF; font-family: Verdana, Arial, Helvetica; font-size: 18pt; font-weight: bold }" );
147 w.write( SurfacingConstants.NL );
148 w.write( "h2 { color : #0000FF; font-family: Verdana, Arial, Helvetica; font-size: 16pt; font-weight: bold }" );
149 w.write( SurfacingConstants.NL );
150 w.write( "</style>" );
151 w.write( SurfacingConstants.NL );
152 w.write( "</head>" );
153 w.write( SurfacingConstants.NL );
156 public static DescriptiveStatistics calculateDescriptiveStatisticsForMeanValues( final Set<DomainSimilarity> similarities ) {
157 final DescriptiveStatistics stats = new BasicDescriptiveStatistics();
158 for( final DomainSimilarity similarity : similarities ) {
159 stats.addValue( similarity.getMeanSimilarityScore() );
164 public static int calculateOverlap( final Domain domain, final List<Boolean> covered_positions ) {
165 int overlap_count = 0;
166 for( int i = domain.getFrom(); i <= domain.getTo(); ++i ) {
167 if ( ( i < covered_positions.size() ) && ( covered_positions.get( i ) == true ) ) {
171 return overlap_count;
174 public static void checkForOutputFileWriteability( final File outfile ) {
175 final String error = ForesterUtil.isWritableFile( outfile );
176 if ( !ForesterUtil.isEmpty( error ) ) {
177 ForesterUtil.fatalError( surfacing.PRG_NAME, error );
181 private static SortedSet<String> collectAllDomainsChangedOnSubtree( final PhylogenyNode subtree_root,
182 final boolean get_gains ) {
183 final SortedSet<String> domains = new TreeSet<String>();
184 for( final PhylogenyNode descendant : PhylogenyMethods.getAllDescendants( subtree_root ) ) {
185 final BinaryCharacters chars = descendant.getNodeData().getBinaryCharacters();
187 domains.addAll( chars.getGainedCharacters() );
190 domains.addAll( chars.getLostCharacters() );
196 public static void collectChangedDomainCombinationsFromBinaryStatesMatrixAsListToFile( final CharacterStateMatrix<CharacterStateMatrix.GainLossStates> matrix,
197 final BinaryDomainCombination.DomainCombinationType dc_type,
198 final List<BinaryDomainCombination> all_binary_domains_combination_gained,
199 final boolean get_gains ) {
200 final SortedSet<String> sorted_ids = new TreeSet<String>();
201 for( int i = 0; i < matrix.getNumberOfIdentifiers(); ++i ) {
202 sorted_ids.add( matrix.getIdentifier( i ) );
204 for( final String id : sorted_ids ) {
205 for( int c = 0; c < matrix.getNumberOfCharacters(); ++c ) {
206 if ( ( get_gains && ( matrix.getState( id, c ) == CharacterStateMatrix.GainLossStates.GAIN ) )
207 || ( !get_gains && ( matrix.getState( id, c ) == CharacterStateMatrix.GainLossStates.LOSS ) ) ) {
208 if ( dc_type == BinaryDomainCombination.DomainCombinationType.DIRECTED_ADJACTANT ) {
209 all_binary_domains_combination_gained.add( AdjactantDirectedBinaryDomainCombination
210 .createInstance( matrix.getCharacter( c ) ) );
212 else if ( dc_type == BinaryDomainCombination.DomainCombinationType.DIRECTED ) {
213 all_binary_domains_combination_gained.add( DirectedBinaryDomainCombination
214 .createInstance( matrix.getCharacter( c ) ) );
217 all_binary_domains_combination_gained.add( BasicBinaryDomainCombination.createInstance( matrix
218 .getCharacter( c ) ) );
225 private static File createBaseDirForPerNodeDomainFiles( final String base_dir,
226 final boolean domain_combinations,
227 final CharacterStateMatrix.GainLossStates state,
228 final String outfile ) {
229 File per_node_go_mapped_domain_gain_loss_files_base_dir = new File( new File( outfile ).getParent()
230 + ForesterUtil.FILE_SEPARATOR + base_dir );
231 if ( !per_node_go_mapped_domain_gain_loss_files_base_dir.exists() ) {
232 per_node_go_mapped_domain_gain_loss_files_base_dir.mkdir();
234 if ( domain_combinations ) {
235 per_node_go_mapped_domain_gain_loss_files_base_dir = new File( per_node_go_mapped_domain_gain_loss_files_base_dir
236 + ForesterUtil.FILE_SEPARATOR + "DC" );
239 per_node_go_mapped_domain_gain_loss_files_base_dir = new File( per_node_go_mapped_domain_gain_loss_files_base_dir
240 + ForesterUtil.FILE_SEPARATOR + "DOMAINS" );
242 if ( !per_node_go_mapped_domain_gain_loss_files_base_dir.exists() ) {
243 per_node_go_mapped_domain_gain_loss_files_base_dir.mkdir();
245 if ( state == GainLossStates.GAIN ) {
246 per_node_go_mapped_domain_gain_loss_files_base_dir = new File( per_node_go_mapped_domain_gain_loss_files_base_dir
247 + ForesterUtil.FILE_SEPARATOR + "GAINS" );
249 else if ( state == GainLossStates.LOSS ) {
250 per_node_go_mapped_domain_gain_loss_files_base_dir = new File( per_node_go_mapped_domain_gain_loss_files_base_dir
251 + ForesterUtil.FILE_SEPARATOR + "LOSSES" );
254 per_node_go_mapped_domain_gain_loss_files_base_dir = new File( per_node_go_mapped_domain_gain_loss_files_base_dir
255 + ForesterUtil.FILE_SEPARATOR + "PRESENT" );
257 if ( !per_node_go_mapped_domain_gain_loss_files_base_dir.exists() ) {
258 per_node_go_mapped_domain_gain_loss_files_base_dir.mkdir();
260 return per_node_go_mapped_domain_gain_loss_files_base_dir;
263 public static Map<DomainId, List<GoId>> createDomainIdToGoIdMap( final List<PfamToGoMapping> pfam_to_go_mappings ) {
264 final Map<DomainId, List<GoId>> domain_id_to_go_ids_map = new HashMap<DomainId, List<GoId>>( pfam_to_go_mappings
266 for( final PfamToGoMapping pfam_to_go : pfam_to_go_mappings ) {
267 if ( !domain_id_to_go_ids_map.containsKey( pfam_to_go.getKey() ) ) {
268 domain_id_to_go_ids_map.put( pfam_to_go.getKey(), new ArrayList<GoId>() );
270 domain_id_to_go_ids_map.get( pfam_to_go.getKey() ).add( pfam_to_go.getValue() );
272 return domain_id_to_go_ids_map;
275 public static Map<DomainId, Set<String>> createDomainIdToSecondaryFeaturesMap( final File secondary_features_map_file )
277 final BasicTable<String> primary_table = BasicTableParser.parse( secondary_features_map_file, "\t" );
278 final Map<DomainId, Set<String>> map = new TreeMap<DomainId, Set<String>>();
279 for( int r = 0; r < primary_table.getNumberOfRows(); ++r ) {
280 final DomainId domain_id = new DomainId( primary_table.getValue( 0, r ) );
281 if ( !map.containsKey( domain_id ) ) {
282 map.put( domain_id, new HashSet<String>() );
284 map.get( domain_id ).add( primary_table.getValue( 1, r ) );
289 public static Phylogeny createNjTreeBasedOnMatrixToFile( final File nj_tree_outfile, final DistanceMatrix distance ) {
290 checkForOutputFileWriteability( nj_tree_outfile );
291 final NeighborJoining nj = NeighborJoining.createInstance();
292 final Phylogeny phylogeny = nj.execute( distance );
293 phylogeny.setName( nj_tree_outfile.getName() );
294 writePhylogenyToFile( phylogeny, nj_tree_outfile.toString() );
298 private static SortedSet<BinaryDomainCombination> createSetOfAllBinaryDomainCombinationsPerGenome( final GenomeWideCombinableDomains gwcd ) {
299 final SortedMap<DomainId, CombinableDomains> cds = gwcd.getAllCombinableDomainsIds();
300 final SortedSet<BinaryDomainCombination> binary_combinations = new TreeSet<BinaryDomainCombination>();
301 for( final DomainId domain_id : cds.keySet() ) {
302 final CombinableDomains cd = cds.get( domain_id );
303 binary_combinations.addAll( cd.toBinaryDomainCombinations() );
305 return binary_combinations;
308 public static void decoratePrintableDomainSimilarities( final SortedSet<DomainSimilarity> domain_similarities,
309 final Detailedness detailedness,
310 final GoAnnotationOutput go_annotation_output,
311 final Map<GoId, GoTerm> go_id_to_term_map,
312 final GoNameSpace go_namespace_limit ) {
313 if ( ( go_namespace_limit != null ) && ( ( go_id_to_term_map == null ) || go_id_to_term_map.isEmpty() ) ) {
314 throw new IllegalArgumentException( "attempt to use a GO namespace limit without a GO id to term map" );
316 for( final DomainSimilarity domain_similarity : domain_similarities ) {
317 if ( domain_similarity instanceof PrintableDomainSimilarity ) {
318 final PrintableDomainSimilarity printable_domain_similarity = ( PrintableDomainSimilarity ) domain_similarity;
319 printable_domain_similarity.setDetailedness( detailedness );
320 printable_domain_similarity.setGoAnnotationOutput( go_annotation_output );
321 printable_domain_similarity.setGoIdToTermMap( go_id_to_term_map );
322 printable_domain_similarity.setGoNamespaceLimit( go_namespace_limit );
327 public static void executeDomainLengthAnalysis( final String[][] input_file_properties,
328 final int number_of_genomes,
329 final DomainLengthsTable domain_lengths_table,
330 final File outfile ) throws IOException {
331 final DecimalFormat df = new DecimalFormat( "#.00" );
332 checkForOutputFileWriteability( outfile );
333 final BufferedWriter out = new BufferedWriter( new FileWriter( outfile ) );
334 out.write( "MEAN BASED STATISTICS PER SPECIES" );
335 out.write( ForesterUtil.LINE_SEPARATOR );
336 out.write( domain_lengths_table.createMeanBasedStatisticsPerSpeciesTable().toString() );
337 out.write( ForesterUtil.LINE_SEPARATOR );
338 out.write( ForesterUtil.LINE_SEPARATOR );
339 final List<DomainLengths> domain_lengths_list = domain_lengths_table.getDomainLengthsList();
340 out.write( "OUTLIER SPECIES PER DOMAIN (Z>=1.5)" );
341 out.write( ForesterUtil.LINE_SEPARATOR );
342 for( final DomainLengths domain_lengths : domain_lengths_list ) {
343 final List<Species> species_list = domain_lengths.getMeanBasedOutlierSpecies( 1.5 );
344 if ( species_list.size() > 0 ) {
345 out.write( domain_lengths.getDomainId() + "\t" );
346 for( final Species species : species_list ) {
347 out.write( species + "\t" );
349 out.write( ForesterUtil.LINE_SEPARATOR );
350 // DescriptiveStatistics stats_for_domain = domain_lengths
351 // .calculateMeanBasedStatistics();
352 //AsciiHistogram histo = new AsciiHistogram( stats_for_domain );
353 //System.out.println( histo.toStringBuffer( 40, '=', 60, 4 ).toString() );
356 out.write( ForesterUtil.LINE_SEPARATOR );
357 out.write( ForesterUtil.LINE_SEPARATOR );
358 out.write( "OUTLIER SPECIES (Z 1.0)" );
359 out.write( ForesterUtil.LINE_SEPARATOR );
360 final DescriptiveStatistics stats_for_all_species = domain_lengths_table
361 .calculateMeanBasedStatisticsForAllSpecies();
362 out.write( stats_for_all_species.asSummary() );
363 out.write( ForesterUtil.LINE_SEPARATOR );
364 final AsciiHistogram histo = new AsciiHistogram( stats_for_all_species );
365 out.write( histo.toStringBuffer( 40, '=', 60, 4 ).toString() );
366 out.write( ForesterUtil.LINE_SEPARATOR );
367 final double population_sd = stats_for_all_species.sampleStandardDeviation();
368 final double population_mean = stats_for_all_species.arithmeticMean();
369 for( final Species species : domain_lengths_table.getSpecies() ) {
370 final double x = domain_lengths_table.calculateMeanBasedStatisticsForSpecies( species ).arithmeticMean();
371 final double z = ( x - population_mean ) / population_sd;
372 out.write( species + "\t" + z );
373 out.write( ForesterUtil.LINE_SEPARATOR );
375 out.write( ForesterUtil.LINE_SEPARATOR );
376 for( final Species species : domain_lengths_table.getSpecies() ) {
377 final DescriptiveStatistics stats_for_species = domain_lengths_table
378 .calculateMeanBasedStatisticsForSpecies( species );
379 final double x = stats_for_species.arithmeticMean();
380 final double z = ( x - population_mean ) / population_sd;
381 if ( ( z <= -1.0 ) || ( z >= 1.0 ) ) {
382 out.write( species + "\t" + df.format( z ) + "\t" + stats_for_species.asSummary() );
383 out.write( ForesterUtil.LINE_SEPARATOR );
387 // final List<HistogramData> histogram_datas = new ArrayList<HistogramData>();
388 // for( int i = 0; i < number_of_genomes; ++i ) {
389 // final Species species = new BasicSpecies( input_file_properties[ i ][ 0 ] );
391 // .add( new HistogramData( species.toString(), domain_lengths_table
392 // .calculateMeanBasedStatisticsForSpecies( species )
393 // .getDataAsDoubleArray(), 5, 600, null, 60 ) );
395 // final HistogramsFrame hf = new HistogramsFrame( histogram_datas );
396 // hf.setVisible( true );
402 * @param all_binary_domains_combination_lost_fitch
403 * @param consider_directedness_and_adjacency_for_bin_combinations
404 * @param all_binary_domains_combination_gained if null ignored, otherwise this is to list all binary domain combinations
405 * which were gained under unweighted (Fitch) parsimony.
407 public static void executeParsimonyAnalysis( final long random_number_seed_for_fitch_parsimony,
408 final boolean radomize_fitch_parsimony,
409 final String outfile_name,
410 final DomainParsimonyCalculator domain_parsimony,
411 final Phylogeny phylogeny,
412 final Map<DomainId, List<GoId>> domain_id_to_go_ids_map,
413 final Map<GoId, GoTerm> go_id_to_term_map,
414 final GoNameSpace go_namespace_limit,
415 final String parameters_str,
416 final Map<DomainId, Set<String>>[] domain_id_to_secondary_features_maps,
417 final SortedSet<DomainId> positive_filter,
418 final boolean output_binary_domain_combinations_for_graphs,
419 final List<BinaryDomainCombination> all_binary_domains_combination_gained_fitch,
420 final List<BinaryDomainCombination> all_binary_domains_combination_lost_fitch,
421 final BinaryDomainCombination.DomainCombinationType dc_type ) {
422 final String sep = ForesterUtil.LINE_SEPARATOR + "###################" + ForesterUtil.LINE_SEPARATOR;
423 final String date_time = ForesterUtil.getCurrentDateTime();
424 final SortedSet<String> all_pfams_encountered = new TreeSet<String>();
425 final SortedSet<String> all_pfams_gained_as_domains = new TreeSet<String>();
426 final SortedSet<String> all_pfams_lost_as_domains = new TreeSet<String>();
427 final SortedSet<String> all_pfams_gained_as_dom_combinations = new TreeSet<String>();
428 final SortedSet<String> all_pfams_lost_as_dom_combinations = new TreeSet<String>();
429 writeToNexus( outfile_name, domain_parsimony, phylogeny );
432 Phylogeny local_phylogeny_l = phylogeny.copy();
433 if ( ( positive_filter != null ) && ( positive_filter.size() > 0 ) ) {
434 domain_parsimony.executeDolloParsimonyOnDomainPresence( positive_filter );
437 domain_parsimony.executeDolloParsimonyOnDomainPresence();
439 SurfacingUtil.writeMatrixToFile( domain_parsimony.getGainLossMatrix(), outfile_name
440 + surfacing.PARSIMONY_OUTPUT_GL_SUFFIX_DOLLO_DOMAINS, Format.FORESTER );
441 SurfacingUtil.writeMatrixToFile( domain_parsimony.getGainLossCountsMatrix(), outfile_name
442 + surfacing.PARSIMONY_OUTPUT_GL_COUNTS_SUFFIX_DOLLO_DOMAINS, Format.FORESTER );
443 SurfacingUtil.writeBinaryStatesMatrixAsListToFile( domain_parsimony.getGainLossMatrix(),
444 CharacterStateMatrix.GainLossStates.GAIN,
445 outfile_name + surfacing.PARSIMONY_OUTPUT_DOLLO_GAINS_D,
447 ForesterUtil.LINE_SEPARATOR,
449 SurfacingUtil.writeBinaryStatesMatrixAsListToFile( domain_parsimony.getGainLossMatrix(),
450 CharacterStateMatrix.GainLossStates.LOSS,
451 outfile_name + surfacing.PARSIMONY_OUTPUT_DOLLO_LOSSES_D,
453 ForesterUtil.LINE_SEPARATOR,
455 SurfacingUtil.writeBinaryStatesMatrixAsListToFile( domain_parsimony.getGainLossMatrix(), null, outfile_name
456 + surfacing.PARSIMONY_OUTPUT_DOLLO_PRESENT_D, sep, ForesterUtil.LINE_SEPARATOR, null );
458 writeBinaryStatesMatrixToList( domain_id_to_go_ids_map,
462 domain_parsimony.getGainLossMatrix(),
463 CharacterStateMatrix.GainLossStates.GAIN,
464 outfile_name + surfacing.PARSIMONY_OUTPUT_DOLLO_GAINS_HTML_D,
466 ForesterUtil.LINE_SEPARATOR,
467 "Dollo Parsimony | Gains | Domains",
469 domain_id_to_secondary_features_maps,
470 all_pfams_encountered,
471 all_pfams_gained_as_domains,
473 writeBinaryStatesMatrixToList( domain_id_to_go_ids_map,
477 domain_parsimony.getGainLossMatrix(),
478 CharacterStateMatrix.GainLossStates.LOSS,
479 outfile_name + surfacing.PARSIMONY_OUTPUT_DOLLO_LOSSES_HTML_D,
481 ForesterUtil.LINE_SEPARATOR,
482 "Dollo Parsimony | Losses | Domains",
484 domain_id_to_secondary_features_maps,
485 all_pfams_encountered,
486 all_pfams_lost_as_domains,
488 writeBinaryStatesMatrixToList( domain_id_to_go_ids_map,
492 domain_parsimony.getGainLossMatrix(),
494 outfile_name + surfacing.PARSIMONY_OUTPUT_DOLLO_PRESENT_HTML_D,
496 ForesterUtil.LINE_SEPARATOR,
497 "Dollo Parsimony | Present | Domains",
499 domain_id_to_secondary_features_maps,
500 all_pfams_encountered,
502 "_dollo_present_d" );
503 preparePhylogeny( local_phylogeny_l,
506 "Dollo parsimony on domain presence/absence",
507 "dollo_on_domains_" + outfile_name,
509 SurfacingUtil.writePhylogenyToFile( local_phylogeny_l, outfile_name
510 + surfacing.DOMAINS_PARSIMONY_TREE_OUTPUT_SUFFIX_DOLLO );
512 writeAllDomainsChangedOnAllSubtrees( local_phylogeny_l, true, outfile_name, "_dollo_all_gains_d" );
513 writeAllDomainsChangedOnAllSubtrees( local_phylogeny_l, false, outfile_name, "_dollo_all_losses_d" );
515 catch ( final IOException e ) {
517 ForesterUtil.fatalError( surfacing.PRG_NAME, e.getLocalizedMessage() );
519 if ( domain_parsimony.calculateNumberOfBinaryDomainCombination() > 0 ) {
520 // FITCH DOMAIN COMBINATIONS
521 // -------------------------
522 local_phylogeny_l = phylogeny.copy();
523 String randomization = "no";
524 if ( radomize_fitch_parsimony ) {
525 domain_parsimony.executeFitchParsimonyOnBinaryDomainCombintion( random_number_seed_for_fitch_parsimony );
526 randomization = "yes, seed = " + random_number_seed_for_fitch_parsimony;
529 domain_parsimony.executeFitchParsimonyOnBinaryDomainCombintion( false );
531 SurfacingUtil.writeMatrixToFile( domain_parsimony.getGainLossMatrix(), outfile_name
532 + surfacing.PARSIMONY_OUTPUT_GL_SUFFIX_FITCH_BINARY_COMBINATIONS, Format.FORESTER );
533 SurfacingUtil.writeMatrixToFile( domain_parsimony.getGainLossCountsMatrix(), outfile_name
534 + surfacing.PARSIMONY_OUTPUT_GL_COUNTS_SUFFIX_FITCH_BINARY_COMBINATIONS, Format.FORESTER );
536 .writeBinaryStatesMatrixAsListToFile( domain_parsimony.getGainLossMatrix(),
537 CharacterStateMatrix.GainLossStates.GAIN,
538 outfile_name + surfacing.PARSIMONY_OUTPUT_FITCH_GAINS_BC,
540 ForesterUtil.LINE_SEPARATOR,
542 SurfacingUtil.writeBinaryStatesMatrixAsListToFile( domain_parsimony.getGainLossMatrix(),
543 CharacterStateMatrix.GainLossStates.LOSS,
545 + surfacing.PARSIMONY_OUTPUT_FITCH_LOSSES_BC,
547 ForesterUtil.LINE_SEPARATOR,
549 SurfacingUtil.writeBinaryStatesMatrixAsListToFile( domain_parsimony.getGainLossMatrix(), null, outfile_name
550 + surfacing.PARSIMONY_OUTPUT_FITCH_PRESENT_BC, sep, ForesterUtil.LINE_SEPARATOR, null );
551 if ( all_binary_domains_combination_gained_fitch != null ) {
552 collectChangedDomainCombinationsFromBinaryStatesMatrixAsListToFile( domain_parsimony.getGainLossMatrix(),
554 all_binary_domains_combination_gained_fitch,
557 if ( all_binary_domains_combination_lost_fitch != null ) {
558 collectChangedDomainCombinationsFromBinaryStatesMatrixAsListToFile( domain_parsimony.getGainLossMatrix(),
560 all_binary_domains_combination_lost_fitch,
563 if ( output_binary_domain_combinations_for_graphs ) {
565 .writeBinaryStatesMatrixAsListToFileForBinaryCombinationsForGraphAnalysis( domain_parsimony
566 .getGainLossMatrix(),
569 + surfacing.PARSIMONY_OUTPUT_FITCH_PRESENT_BC_OUTPUTFILE_SUFFIX_FOR_GRAPH_ANALYSIS,
571 ForesterUtil.LINE_SEPARATOR,
572 BinaryDomainCombination.OutputFormat.DOT );
575 writeBinaryStatesMatrixToList( domain_id_to_go_ids_map,
579 domain_parsimony.getGainLossMatrix(),
580 CharacterStateMatrix.GainLossStates.GAIN,
581 outfile_name + surfacing.PARSIMONY_OUTPUT_FITCH_GAINS_HTML_BC,
583 ForesterUtil.LINE_SEPARATOR,
584 "Fitch Parsimony | Gains | Domain Combinations",
587 all_pfams_encountered,
588 all_pfams_gained_as_dom_combinations,
590 writeBinaryStatesMatrixToList( domain_id_to_go_ids_map,
594 domain_parsimony.getGainLossMatrix(),
595 CharacterStateMatrix.GainLossStates.LOSS,
596 outfile_name + surfacing.PARSIMONY_OUTPUT_FITCH_LOSSES_HTML_BC,
598 ForesterUtil.LINE_SEPARATOR,
599 "Fitch Parsimony | Losses | Domain Combinations",
602 all_pfams_encountered,
603 all_pfams_lost_as_dom_combinations,
604 "_fitch_losses_dc" );
605 writeBinaryStatesMatrixToList( domain_id_to_go_ids_map,
609 domain_parsimony.getGainLossMatrix(),
611 outfile_name + surfacing.PARSIMONY_OUTPUT_FITCH_PRESENT_HTML_BC,
613 ForesterUtil.LINE_SEPARATOR,
614 "Fitch Parsimony | Present | Domain Combinations",
617 all_pfams_encountered,
619 "_fitch_present_dc" );
620 writeAllEncounteredPfamsToFile( domain_id_to_go_ids_map,
623 all_pfams_encountered );
624 writePfamsToFile( outfile_name + surfacing.ALL_PFAMS_GAINED_AS_DOMAINS_SUFFIX, all_pfams_gained_as_domains );
625 writePfamsToFile( outfile_name + surfacing.ALL_PFAMS_LOST_AS_DOMAINS_SUFFIX, all_pfams_lost_as_domains );
626 writePfamsToFile( outfile_name + surfacing.ALL_PFAMS_GAINED_AS_DC_SUFFIX,
627 all_pfams_gained_as_dom_combinations );
628 writePfamsToFile( outfile_name + surfacing.ALL_PFAMS_LOST_AS_DC_SUFFIX, all_pfams_lost_as_dom_combinations );
629 preparePhylogeny( local_phylogeny_l,
632 "Fitch parsimony on binary domain combination presence/absence randomization: "
634 "fitch_on_binary_domain_combinations_" + outfile_name,
636 SurfacingUtil.writePhylogenyToFile( local_phylogeny_l, outfile_name
637 + surfacing.BINARY_DOMAIN_COMBINATIONS_PARSIMONY_TREE_OUTPUT_SUFFIX_FITCH );
638 calculateIndependentDomainCombinationGains( local_phylogeny_l, outfile_name
639 + surfacing.INDEPENDENT_DC_GAINS_FITCH_PARS_COUNTS_OUTPUT_SUFFIX, outfile_name
640 + surfacing.INDEPENDENT_DC_GAINS_FITCH_PARS_DC_OUTPUT_SUFFIX );
644 private static void calculateIndependentDomainCombinationGains( final Phylogeny local_phylogeny_l,
645 final String outfilename_for_counts,
646 final String outfilename_for_dc ) {
648 final BufferedWriter out_counts = new BufferedWriter( new FileWriter( outfilename_for_counts ) );
649 final BufferedWriter out_dc = new BufferedWriter( new FileWriter( outfilename_for_dc ) );
650 final SortedMap<String, Integer> dc_gain_counts = new TreeMap<String, Integer>();
651 for( final PhylogenyNodeIterator it = local_phylogeny_l.iteratorPostorder(); it.hasNext(); ) {
652 final PhylogenyNode n = it.next();
653 final Set<String> gained_dc = n.getNodeData().getBinaryCharacters().getGainedCharacters();
654 for( final String dc : gained_dc ) {
655 if ( dc_gain_counts.containsKey( dc ) ) {
656 dc_gain_counts.put( dc, dc_gain_counts.get( dc ) + 1 );
659 dc_gain_counts.put( dc, 1 );
663 final SortedMap<Integer, Integer> histogram = new TreeMap<Integer, Integer>();
664 final SortedMap<Integer, StringBuilder> domain_lists = new TreeMap<Integer, StringBuilder>();
665 final Set<String> dcs = dc_gain_counts.keySet();
666 for( final String dc : dcs ) {
667 final int count = dc_gain_counts.get( dc );
668 if ( histogram.containsKey( count ) ) {
669 histogram.put( count, histogram.get( count ) + 1 );
670 domain_lists.put( count, domain_lists.get( count ).append( ", " + dc ) );
673 histogram.put( count, 1 );
674 domain_lists.put( count, new StringBuilder( dc ) );
677 final Set<Integer> histogram_keys = histogram.keySet();
678 for( final Integer histogram_key : histogram_keys ) {
679 final int count = histogram.get( histogram_key );
680 final StringBuilder dc = domain_lists.get( histogram_key );
681 out_counts.write( histogram_key + "\t" + count + ForesterUtil.LINE_SEPARATOR );
682 out_dc.write( histogram_key + "\t" + dc + ForesterUtil.LINE_SEPARATOR );
687 catch ( final IOException e ) {
688 ForesterUtil.printWarningMessage( surfacing.PRG_NAME, "Failure to write: " + e );
690 ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote independent domain combination gains fitch counts to ["
691 + outfilename_for_counts + "]" );
692 ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote independent domain combination gains fitch lists to ["
693 + outfilename_for_dc + "]" );
696 public static void executeParsimonyAnalysisForSecondaryFeatures( final String outfile_name,
697 final DomainParsimonyCalculator secondary_features_parsimony,
698 final Phylogeny phylogeny,
699 final String parameters_str,
700 final Map<Species, MappingResults> mapping_results_map ) {
701 final String sep = ForesterUtil.LINE_SEPARATOR + "###################" + ForesterUtil.LINE_SEPARATOR;
702 final String date_time = ForesterUtil.getCurrentDateTime();
703 System.out.println();
704 writeToNexus( outfile_name + surfacing.NEXUS_SECONDARY_FEATURES,
705 secondary_features_parsimony.createMatrixOfSecondaryFeaturePresenceOrAbsence( null ),
707 final Phylogeny local_phylogeny_copy = phylogeny.copy();
708 secondary_features_parsimony.executeDolloParsimonyOnSecondaryFeatures( mapping_results_map );
709 SurfacingUtil.writeMatrixToFile( secondary_features_parsimony.getGainLossMatrix(), outfile_name
710 + surfacing.PARSIMONY_OUTPUT_GL_SUFFIX_DOLLO_SECONDARY_FEATURES, Format.FORESTER );
711 SurfacingUtil.writeMatrixToFile( secondary_features_parsimony.getGainLossCountsMatrix(), outfile_name
712 + surfacing.PARSIMONY_OUTPUT_GL_COUNTS_SUFFIX_DOLLO_SECONDARY_FEATURES, Format.FORESTER );
714 .writeBinaryStatesMatrixAsListToFile( secondary_features_parsimony.getGainLossMatrix(),
715 CharacterStateMatrix.GainLossStates.GAIN,
717 + surfacing.PARSIMONY_OUTPUT_DOLLO_GAINS_SECONDARY_FEATURES,
719 ForesterUtil.LINE_SEPARATOR,
722 .writeBinaryStatesMatrixAsListToFile( secondary_features_parsimony.getGainLossMatrix(),
723 CharacterStateMatrix.GainLossStates.LOSS,
725 + surfacing.PARSIMONY_OUTPUT_DOLLO_LOSSES_SECONDARY_FEATURES,
727 ForesterUtil.LINE_SEPARATOR,
730 .writeBinaryStatesMatrixAsListToFile( secondary_features_parsimony.getGainLossMatrix(),
733 + surfacing.PARSIMONY_OUTPUT_DOLLO_PRESENT_SECONDARY_FEATURES,
735 ForesterUtil.LINE_SEPARATOR,
737 preparePhylogeny( local_phylogeny_copy,
738 secondary_features_parsimony,
740 "Dollo parsimony on secondary feature presence/absence",
741 "dollo_on_secondary_features_" + outfile_name,
743 SurfacingUtil.writePhylogenyToFile( local_phylogeny_copy, outfile_name
744 + surfacing.SECONDARY_FEATURES_PARSIMONY_TREE_OUTPUT_SUFFIX_DOLLO );
747 public static void extractProteinNames( final List<Protein> proteins,
748 final List<DomainId> query_domain_ids_nc_order,
750 final String separator ) throws IOException {
751 for( final Protein protein : proteins ) {
752 if ( protein.contains( query_domain_ids_nc_order, true ) ) {
753 out.write( protein.getSpecies().getSpeciesId() );
754 out.write( separator );
755 out.write( protein.getProteinId().getId() );
756 out.write( separator );
758 final Set<DomainId> visited_domain_ids = new HashSet<DomainId>();
759 boolean first = true;
760 for( final Domain domain : protein.getProteinDomains() ) {
761 if ( !visited_domain_ids.contains( domain.getDomainId() ) ) {
762 visited_domain_ids.add( domain.getDomainId() );
769 out.write( domain.getDomainId().getId() );
771 out.write( "" + domain.getTotalCount() );
776 out.write( separator );
777 if ( !( ForesterUtil.isEmpty( protein.getDescription() ) || protein.getDescription()
778 .equals( SurfacingConstants.NONE ) ) ) {
779 out.write( protein.getDescription() );
781 out.write( separator );
782 if ( !( ForesterUtil.isEmpty( protein.getAccession() ) || protein.getAccession()
783 .equals( SurfacingConstants.NONE ) ) ) {
784 out.write( protein.getAccession() );
786 out.write( SurfacingConstants.NL );
792 public static void extractProteinNames( final SortedMap<Species, List<Protein>> protein_lists_per_species,
793 final DomainId domain_id,
795 final String separator ) throws IOException {
796 for( final Species species : protein_lists_per_species.keySet() ) {
797 for( final Protein protein : protein_lists_per_species.get( species ) ) {
798 final List<Domain> domains = protein.getProteinDomains( domain_id );
799 if ( domains.size() > 0 ) {
800 final DescriptiveStatistics stats = new BasicDescriptiveStatistics();
801 for( final Domain domain : domains ) {
802 stats.addValue( domain.getPerSequenceEvalue() );
804 out.write( protein.getSpecies().getSpeciesId() );
805 out.write( separator );
806 out.write( protein.getProteinId().getId() );
807 out.write( separator );
808 out.write( "[" + FORMATTER.format( stats.median() ) + "]" );
809 out.write( separator );
810 if ( !( ForesterUtil.isEmpty( protein.getDescription() ) || protein.getDescription()
811 .equals( SurfacingConstants.NONE ) ) ) {
812 out.write( protein.getDescription() );
814 out.write( separator );
815 if ( !( ForesterUtil.isEmpty( protein.getAccession() ) || protein.getAccession()
816 .equals( SurfacingConstants.NONE ) ) ) {
817 out.write( protein.getAccession() );
819 out.write( SurfacingConstants.NL );
826 public static SortedSet<DomainId> getAllDomainIds( final List<GenomeWideCombinableDomains> gwcd_list ) {
827 final SortedSet<DomainId> all_domains_ids = new TreeSet<DomainId>();
828 for( final GenomeWideCombinableDomains gwcd : gwcd_list ) {
829 final Set<DomainId> all_domains = gwcd.getAllDomainIds();
830 // for( final Domain domain : all_domains ) {
831 all_domains_ids.addAll( all_domains );
834 return all_domains_ids;
837 public static SortedMap<String, Integer> getDomainCounts( final List<Protein> protein_domain_collections ) {
838 final SortedMap<String, Integer> map = new TreeMap<String, Integer>();
839 for( final Protein protein_domain_collection : protein_domain_collections ) {
840 for( final Object name : protein_domain_collection.getProteinDomains() ) {
841 final BasicDomain protein_domain = ( BasicDomain ) name;
842 final String id = protein_domain.getDomainId().getId();
843 if ( map.containsKey( id ) ) {
844 map.put( id, map.get( id ) + 1 );
854 public static int getNumberOfNodesLackingName( final Phylogeny p, final StringBuilder names ) {
855 final PhylogenyNodeIterator it = p.iteratorPostorder();
857 while ( it.hasNext() ) {
858 final PhylogenyNode n = it.next();
859 if ( ForesterUtil.isEmpty( n.getName() )
860 && ( !n.getNodeData().isHasTaxonomy() || ForesterUtil.isEmpty( n.getNodeData().getTaxonomy()
861 .getScientificName() ) ) ) {
862 if ( n.getParent() != null ) {
864 names.append( n.getParent().getName() );
873 * Returns true is Domain domain falls in an uninterrupted stretch of
877 * @param covered_positions
880 public static boolean isEngulfed( final Domain domain, final List<Boolean> covered_positions ) {
881 for( int i = domain.getFrom(); i <= domain.getTo(); ++i ) {
882 if ( ( i >= covered_positions.size() ) || ( covered_positions.get( i ) != true ) ) {
889 public static void preparePhylogeny( final Phylogeny p,
890 final DomainParsimonyCalculator domain_parsimony,
891 final String date_time,
894 final String parameters_str ) {
895 domain_parsimony.decoratePhylogenyWithDomains( p );
896 final StringBuilder desc = new StringBuilder();
897 desc.append( "[Method: " + method + "] [Date: " + date_time + "] " );
898 desc.append( "[Cost: " + domain_parsimony.getCost() + "] " );
899 desc.append( "[Gains: " + domain_parsimony.getTotalGains() + "] " );
900 desc.append( "[Losses: " + domain_parsimony.getTotalLosses() + "] " );
901 desc.append( "[Unchanged: " + domain_parsimony.getTotalUnchanged() + "] " );
902 desc.append( "[Parameters: " + parameters_str + "]" );
904 p.setDescription( desc.toString() );
905 p.setConfidence( new Confidence( domain_parsimony.getCost(), "parsimony" ) );
906 p.setRerootable( false );
912 * Example regarding engulfment: ------------0.1 ----------0.2 --0.3 =>
913 * domain with 0.3 is ignored
915 * -----------0.1 ----------0.2 --0.3 => domain with 0.3 is ignored
918 * ------------0.1 ----------0.3 --0.2 => domains with 0.3 and 0.2 are _not_
921 * @param max_allowed_overlap
922 * maximal allowed overlap (inclusive) to be still considered not
923 * overlapping (zero or negative value to allow any overlap)
924 * @param remove_engulfed_domains
925 * to remove domains which are completely engulfed by coverage of
926 * domains with better support
930 public static Protein removeOverlappingDomains( final int max_allowed_overlap,
931 final boolean remove_engulfed_domains,
932 final Protein protein ) {
933 final Protein pruned_protein = new BasicProtein( protein.getProteinId().getId(), protein.getSpecies()
935 final List<Domain> sorted = SurfacingUtil.sortDomainsWithAscendingConfidenceValues( protein );
936 final List<Boolean> covered_positions = new ArrayList<Boolean>();
937 for( final Domain domain : sorted ) {
938 if ( ( ( max_allowed_overlap < 0 ) || ( SurfacingUtil.calculateOverlap( domain, covered_positions ) <= max_allowed_overlap ) )
939 && ( !remove_engulfed_domains || !isEngulfed( domain, covered_positions ) ) ) {
940 final int covered_positions_size = covered_positions.size();
941 for( int i = covered_positions_size; i < domain.getFrom(); ++i ) {
942 covered_positions.add( false );
944 final int new_covered_positions_size = covered_positions.size();
945 for( int i = domain.getFrom(); i <= domain.getTo(); ++i ) {
946 if ( i < new_covered_positions_size ) {
947 covered_positions.set( i, true );
950 covered_positions.add( true );
953 pruned_protein.addProteinDomain( domain );
956 return pruned_protein;
959 static List<Domain> sortDomainsWithAscendingConfidenceValues( final Protein protein ) {
960 final List<Domain> domains = new ArrayList<Domain>();
961 for( final Domain d : protein.getProteinDomains() ) {
964 Collections.sort( domains, SurfacingUtil.ASCENDING_CONFIDENCE_VALUE_ORDER );
968 public static void writeAllDomainsChangedOnAllSubtrees( final Phylogeny p,
969 final boolean get_gains,
971 final String suffix_for_filename ) throws IOException {
972 CharacterStateMatrix.GainLossStates state = CharacterStateMatrix.GainLossStates.GAIN;
974 state = CharacterStateMatrix.GainLossStates.LOSS;
976 final File base_dir = createBaseDirForPerNodeDomainFiles( surfacing.BASE_DIRECTORY_PER_SUBTREE_DOMAIN_GAIN_LOSS_FILES,
980 for( final PhylogenyNodeIterator it = p.iteratorPostorder(); it.hasNext(); ) {
981 final PhylogenyNode node = it.next();
982 if ( !node.isExternal() ) {
983 final SortedSet<String> domains = collectAllDomainsChangedOnSubtree( node, get_gains );
984 if ( domains.size() > 0 ) {
985 final Writer writer = ForesterUtil.createBufferedWriter( base_dir + ForesterUtil.FILE_SEPARATOR
986 + node.getName() + suffix_for_filename );
987 for( final String domain : domains ) {
988 writer.write( domain );
989 writer.write( ForesterUtil.LINE_SEPARATOR );
997 private static void writeAllEncounteredPfamsToFile( final Map<DomainId, List<GoId>> domain_id_to_go_ids_map,
998 final Map<GoId, GoTerm> go_id_to_term_map,
999 final String outfile_name,
1000 final SortedSet<String> all_pfams_encountered ) {
1001 final File all_pfams_encountered_file = new File( outfile_name + surfacing.ALL_PFAMS_ENCOUNTERED_SUFFIX );
1002 final File all_pfams_encountered_with_go_annotation_file = new File( outfile_name
1003 + surfacing.ALL_PFAMS_ENCOUNTERED_WITH_GO_ANNOTATION_SUFFIX );
1004 final File encountered_pfams_summary_file = new File( outfile_name + surfacing.ENCOUNTERED_PFAMS_SUMMARY_SUFFIX );
1005 int biological_process_counter = 0;
1006 int cellular_component_counter = 0;
1007 int molecular_function_counter = 0;
1008 int pfams_with_mappings_counter = 0;
1009 int pfams_without_mappings_counter = 0;
1010 int pfams_without_mappings_to_bp_or_mf_counter = 0;
1011 int pfams_with_mappings_to_bp_or_mf_counter = 0;
1013 final Writer all_pfams_encountered_writer = new BufferedWriter( new FileWriter( all_pfams_encountered_file ) );
1014 final Writer all_pfams_encountered_with_go_annotation_writer = new BufferedWriter( new FileWriter( all_pfams_encountered_with_go_annotation_file ) );
1015 final Writer summary_writer = new BufferedWriter( new FileWriter( encountered_pfams_summary_file ) );
1016 summary_writer.write( "# Pfam to GO mapping summary" );
1017 summary_writer.write( ForesterUtil.LINE_SEPARATOR );
1018 summary_writer.write( "# Actual summary is at the end of this file." );
1019 summary_writer.write( ForesterUtil.LINE_SEPARATOR );
1020 summary_writer.write( "# Encountered Pfams without a GO mapping:" );
1021 summary_writer.write( ForesterUtil.LINE_SEPARATOR );
1022 for( final String pfam : all_pfams_encountered ) {
1023 all_pfams_encountered_writer.write( pfam );
1024 all_pfams_encountered_writer.write( ForesterUtil.LINE_SEPARATOR );
1025 final DomainId domain_id = new DomainId( pfam );
1026 if ( domain_id_to_go_ids_map.containsKey( domain_id ) ) {
1027 ++pfams_with_mappings_counter;
1028 all_pfams_encountered_with_go_annotation_writer.write( pfam );
1029 all_pfams_encountered_with_go_annotation_writer.write( ForesterUtil.LINE_SEPARATOR );
1030 final List<GoId> go_ids = domain_id_to_go_ids_map.get( domain_id );
1031 boolean maps_to_bp = false;
1032 boolean maps_to_cc = false;
1033 boolean maps_to_mf = false;
1034 for( final GoId go_id : go_ids ) {
1035 final GoTerm go_term = go_id_to_term_map.get( go_id );
1036 if ( go_term.getGoNameSpace().isBiologicalProcess() ) {
1039 else if ( go_term.getGoNameSpace().isCellularComponent() ) {
1042 else if ( go_term.getGoNameSpace().isMolecularFunction() ) {
1047 ++biological_process_counter;
1050 ++cellular_component_counter;
1053 ++molecular_function_counter;
1055 if ( maps_to_bp || maps_to_mf ) {
1056 ++pfams_with_mappings_to_bp_or_mf_counter;
1059 ++pfams_without_mappings_to_bp_or_mf_counter;
1063 ++pfams_without_mappings_to_bp_or_mf_counter;
1064 ++pfams_without_mappings_counter;
1065 summary_writer.write( pfam );
1066 summary_writer.write( ForesterUtil.LINE_SEPARATOR );
1069 all_pfams_encountered_writer.close();
1070 all_pfams_encountered_with_go_annotation_writer.close();
1071 ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote all [" + all_pfams_encountered.size()
1072 + "] encountered Pfams to: \"" + all_pfams_encountered_file + "\"" );
1073 ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote all [" + pfams_with_mappings_counter
1074 + "] encountered Pfams with GO mappings to: \"" + all_pfams_encountered_with_go_annotation_file
1076 ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote summary (including all ["
1077 + pfams_without_mappings_counter + "] encountered Pfams without GO mappings) to: \""
1078 + encountered_pfams_summary_file + "\"" );
1079 ForesterUtil.programMessage( surfacing.PRG_NAME, "Sum of Pfams encountered : "
1080 + all_pfams_encountered.size() );
1081 ForesterUtil.programMessage( surfacing.PRG_NAME, "Pfams without a mapping : "
1082 + pfams_without_mappings_counter + " ["
1083 + ( 100 * pfams_without_mappings_counter / all_pfams_encountered.size() ) + "%]" );
1084 ForesterUtil.programMessage( surfacing.PRG_NAME, "Pfams without mapping to proc. or func. : "
1085 + pfams_without_mappings_to_bp_or_mf_counter + " ["
1086 + ( 100 * pfams_without_mappings_to_bp_or_mf_counter / all_pfams_encountered.size() ) + "%]" );
1087 ForesterUtil.programMessage( surfacing.PRG_NAME,
1088 "Pfams with a mapping : " + pfams_with_mappings_counter
1090 + ( 100 * pfams_with_mappings_counter / all_pfams_encountered.size() )
1092 ForesterUtil.programMessage( surfacing.PRG_NAME, "Pfams with a mapping to proc. or func. : "
1093 + pfams_with_mappings_to_bp_or_mf_counter + " ["
1094 + ( 100 * pfams_with_mappings_to_bp_or_mf_counter / all_pfams_encountered.size() ) + "%]" );
1095 ForesterUtil.programMessage( surfacing.PRG_NAME,
1096 "Pfams with mapping to biological process: " + biological_process_counter
1098 + ( 100 * biological_process_counter / all_pfams_encountered.size() )
1100 ForesterUtil.programMessage( surfacing.PRG_NAME,
1101 "Pfams with mapping to molecular function: " + molecular_function_counter
1103 + ( 100 * molecular_function_counter / all_pfams_encountered.size() )
1105 ForesterUtil.programMessage( surfacing.PRG_NAME,
1106 "Pfams with mapping to cellular component: " + cellular_component_counter
1108 + ( 100 * cellular_component_counter / all_pfams_encountered.size() )
1110 summary_writer.write( ForesterUtil.LINE_SEPARATOR );
1111 summary_writer.write( "# Sum of Pfams encountered : " + all_pfams_encountered.size() );
1112 summary_writer.write( ForesterUtil.LINE_SEPARATOR );
1113 summary_writer.write( "# Pfams without a mapping : " + pfams_without_mappings_counter
1114 + " [" + ( 100 * pfams_without_mappings_counter / all_pfams_encountered.size() ) + "%]" );
1115 summary_writer.write( ForesterUtil.LINE_SEPARATOR );
1116 summary_writer.write( "# Pfams without mapping to proc. or func. : "
1117 + pfams_without_mappings_to_bp_or_mf_counter + " ["
1118 + ( 100 * pfams_without_mappings_to_bp_or_mf_counter / all_pfams_encountered.size() ) + "%]" );
1119 summary_writer.write( ForesterUtil.LINE_SEPARATOR );
1120 summary_writer.write( "# Pfams with a mapping : " + pfams_with_mappings_counter + " ["
1121 + ( 100 * pfams_with_mappings_counter / all_pfams_encountered.size() ) + "%]" );
1122 summary_writer.write( ForesterUtil.LINE_SEPARATOR );
1123 summary_writer.write( "# Pfams with a mapping to proc. or func. : "
1124 + pfams_with_mappings_to_bp_or_mf_counter + " ["
1125 + ( 100 * pfams_with_mappings_to_bp_or_mf_counter / all_pfams_encountered.size() ) + "%]" );
1126 summary_writer.write( ForesterUtil.LINE_SEPARATOR );
1127 summary_writer.write( "# Pfams with mapping to biological process: " + biological_process_counter + " ["
1128 + ( 100 * biological_process_counter / all_pfams_encountered.size() ) + "%]" );
1129 summary_writer.write( ForesterUtil.LINE_SEPARATOR );
1130 summary_writer.write( "# Pfams with mapping to molecular function: " + molecular_function_counter + " ["
1131 + ( 100 * molecular_function_counter / all_pfams_encountered.size() ) + "%]" );
1132 summary_writer.write( ForesterUtil.LINE_SEPARATOR );
1133 summary_writer.write( "# Pfams with mapping to cellular component: " + cellular_component_counter + " ["
1134 + ( 100 * cellular_component_counter / all_pfams_encountered.size() ) + "%]" );
1135 summary_writer.write( ForesterUtil.LINE_SEPARATOR );
1136 summary_writer.close();
1138 catch ( final IOException e ) {
1139 ForesterUtil.printWarningMessage( surfacing.PRG_NAME, "Failure to write: " + e );
1143 public static void writeBinaryDomainCombinationsFileForGraphAnalysis( final String[][] input_file_properties,
1144 final File output_dir,
1145 final GenomeWideCombinableDomains gwcd,
1147 final GenomeWideCombinableDomainsSortOrder dc_sort_order ) {
1148 File dc_outfile_dot = new File( input_file_properties[ i ][ 0 ]
1149 + surfacing.DOMAIN_COMBINITONS_OUTPUTFILE_SUFFIX_FOR_GRAPH_ANALYSIS );
1150 if ( output_dir != null ) {
1151 dc_outfile_dot = new File( output_dir + ForesterUtil.FILE_SEPARATOR + dc_outfile_dot );
1153 checkForOutputFileWriteability( dc_outfile_dot );
1154 final SortedSet<BinaryDomainCombination> binary_combinations = createSetOfAllBinaryDomainCombinationsPerGenome( gwcd );
1156 final BufferedWriter out_dot = new BufferedWriter( new FileWriter( dc_outfile_dot ) );
1157 for( final BinaryDomainCombination bdc : binary_combinations ) {
1158 out_dot.write( bdc.toGraphDescribingLanguage( BinaryDomainCombination.OutputFormat.DOT, null, null )
1160 out_dot.write( SurfacingConstants.NL );
1164 catch ( final IOException e ) {
1165 ForesterUtil.fatalError( surfacing.PRG_NAME, e.getMessage() );
1167 ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote binary domain combination for \""
1168 + input_file_properties[ i ][ 0 ] + "\" (" + input_file_properties[ i ][ 1 ] + ", "
1169 + input_file_properties[ i ][ 2 ] + ") to: \"" + dc_outfile_dot + "\"" );
1173 * species | protein id | n-terminal domain | c-terminal domain | n-terminal domain per domain E-value | c-terminal domain per domain E-value
1177 static public StringBuffer proteinToDomainCombinations( final Protein protein,
1178 final String protein_id,
1179 final String separator ) {
1180 final StringBuffer sb = new StringBuffer();
1181 if ( protein.getSpecies() == null ) {
1182 throw new IllegalArgumentException( "species must not be null" );
1184 if ( ForesterUtil.isEmpty( protein.getSpecies().getSpeciesId() ) ) {
1185 throw new IllegalArgumentException( "species id must not be empty" );
1187 final List<Domain> domains = protein.getProteinDomains();
1188 if ( domains.size() > 1 ) {
1189 final Map<String, Integer> counts = new HashMap<String, Integer>();
1190 for( final Domain domain : domains ) {
1191 final String id = domain.getDomainId().getId();
1192 if ( counts.containsKey( id ) ) {
1193 counts.put( id, counts.get( id ) + 1 );
1196 counts.put( id, 1 );
1199 final Set<String> dcs = new HashSet<String>();
1200 for( int i = 1; i < domains.size(); ++i ) {
1201 for( int j = 0; j < i; ++j ) {
1202 Domain domain_n = domains.get( i );
1203 Domain domain_c = domains.get( j );
1204 if ( domain_n.getFrom() > domain_c.getFrom() ) {
1205 domain_n = domains.get( j );
1206 domain_c = domains.get( i );
1208 final String dc = domain_n.getDomainId().getId() + domain_c.getDomainId().getId();
1209 if ( !dcs.contains( dc ) ) {
1211 sb.append( protein.getSpecies() );
1212 sb.append( separator );
1213 sb.append( protein_id );
1214 sb.append( separator );
1215 sb.append( domain_n.getDomainId().getId() );
1216 sb.append( separator );
1217 sb.append( domain_c.getDomainId().getId() );
1218 sb.append( separator );
1219 sb.append( domain_n.getPerDomainEvalue() );
1220 sb.append( separator );
1221 sb.append( domain_c.getPerDomainEvalue() );
1222 sb.append( separator );
1223 sb.append( counts.get( domain_n.getDomainId().getId() ) );
1224 sb.append( separator );
1225 sb.append( counts.get( domain_c.getDomainId().getId() ) );
1226 sb.append( ForesterUtil.LINE_SEPARATOR );
1231 else if ( domains.size() == 1 ) {
1232 sb.append( protein.getSpecies() );
1233 sb.append( separator );
1234 sb.append( protein_id );
1235 sb.append( separator );
1236 sb.append( domains.get( 0 ).getDomainId().getId() );
1237 sb.append( separator );
1238 sb.append( separator );
1239 sb.append( domains.get( 0 ).getPerDomainEvalue() );
1240 sb.append( separator );
1241 sb.append( separator );
1243 sb.append( separator );
1244 sb.append( ForesterUtil.LINE_SEPARATOR );
1247 sb.append( protein.getSpecies() );
1248 sb.append( separator );
1249 sb.append( protein_id );
1250 sb.append( separator );
1251 sb.append( separator );
1252 sb.append( separator );
1253 sb.append( separator );
1254 sb.append( separator );
1255 sb.append( separator );
1256 sb.append( ForesterUtil.LINE_SEPARATOR );
1261 public static void writeBinaryStatesMatrixAsListToFile( final CharacterStateMatrix<CharacterStateMatrix.GainLossStates> matrix,
1262 final CharacterStateMatrix.GainLossStates state,
1263 final String filename,
1264 final String indentifier_characters_separator,
1265 final String character_separator,
1266 final Map<String, String> descriptions ) {
1267 final File outfile = new File( filename );
1268 checkForOutputFileWriteability( outfile );
1269 final SortedSet<String> sorted_ids = new TreeSet<String>();
1270 for( int i = 0; i < matrix.getNumberOfIdentifiers(); ++i ) {
1271 sorted_ids.add( matrix.getIdentifier( i ) );
1274 final BufferedWriter out = new BufferedWriter( new FileWriter( outfile ) );
1275 for( final String id : sorted_ids ) {
1276 out.write( indentifier_characters_separator );
1277 out.write( "#" + id );
1278 out.write( indentifier_characters_separator );
1279 for( int c = 0; c < matrix.getNumberOfCharacters(); ++c ) {
1281 // using null to indicate either UNCHANGED_PRESENT or GAIN.
1282 if ( ( matrix.getState( id, c ) == state )
1283 || ( ( state == null ) && ( ( matrix.getState( id, c ) == CharacterStateMatrix.GainLossStates.GAIN ) || ( matrix
1284 .getState( id, c ) == CharacterStateMatrix.GainLossStates.UNCHANGED_PRESENT ) ) ) ) {
1285 out.write( matrix.getCharacter( c ) );
1286 if ( ( descriptions != null ) && !descriptions.isEmpty()
1287 && descriptions.containsKey( matrix.getCharacter( c ) ) ) {
1289 out.write( descriptions.get( matrix.getCharacter( c ) ) );
1291 out.write( character_separator );
1298 catch ( final IOException e ) {
1299 ForesterUtil.fatalError( surfacing.PRG_NAME, e.getMessage() );
1301 ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote characters list: \"" + filename + "\"" );
1304 public static void writeBinaryStatesMatrixAsListToFileForBinaryCombinationsForGraphAnalysis( final CharacterStateMatrix<CharacterStateMatrix.GainLossStates> matrix,
1305 final CharacterStateMatrix.GainLossStates state,
1306 final String filename,
1307 final String indentifier_characters_separator,
1308 final String character_separator,
1309 final BinaryDomainCombination.OutputFormat bc_output_format ) {
1310 final File outfile = new File( filename );
1311 checkForOutputFileWriteability( outfile );
1312 final SortedSet<String> sorted_ids = new TreeSet<String>();
1313 for( int i = 0; i < matrix.getNumberOfIdentifiers(); ++i ) {
1314 sorted_ids.add( matrix.getIdentifier( i ) );
1317 final BufferedWriter out = new BufferedWriter( new FileWriter( outfile ) );
1318 for( final String id : sorted_ids ) {
1319 out.write( indentifier_characters_separator );
1320 out.write( "#" + id );
1321 out.write( indentifier_characters_separator );
1322 for( int c = 0; c < matrix.getNumberOfCharacters(); ++c ) {
1324 // using null to indicate either UNCHANGED_PRESENT or GAIN.
1325 if ( ( matrix.getState( id, c ) == state )
1326 || ( ( state == null ) && ( ( matrix.getState( id, c ) == CharacterStateMatrix.GainLossStates.GAIN ) || ( matrix
1327 .getState( id, c ) == CharacterStateMatrix.GainLossStates.UNCHANGED_PRESENT ) ) ) ) {
1328 BinaryDomainCombination bdc = null;
1330 bdc = BasicBinaryDomainCombination.createInstance( matrix.getCharacter( c ) );
1332 catch ( final Exception e ) {
1333 ForesterUtil.fatalError( surfacing.PRG_NAME, e.getLocalizedMessage() );
1335 out.write( bdc.toGraphDescribingLanguage( bc_output_format, null, null ).toString() );
1336 out.write( character_separator );
1343 catch ( final IOException e ) {
1344 ForesterUtil.fatalError( surfacing.PRG_NAME, e.getMessage() );
1346 ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote characters list: \"" + filename + "\"" );
1349 public static void writeBinaryStatesMatrixToList( final Map<DomainId, List<GoId>> domain_id_to_go_ids_map,
1350 final Map<GoId, GoTerm> go_id_to_term_map,
1351 final GoNameSpace go_namespace_limit,
1352 final boolean domain_combinations,
1353 final CharacterStateMatrix<CharacterStateMatrix.GainLossStates> matrix,
1354 final CharacterStateMatrix.GainLossStates state,
1355 final String filename,
1356 final String indentifier_characters_separator,
1357 final String character_separator,
1358 final String title_for_html,
1359 final String prefix_for_html,
1360 final Map<DomainId, Set<String>>[] domain_id_to_secondary_features_maps,
1361 final SortedSet<String> all_pfams_encountered,
1362 final SortedSet<String> pfams_gained_or_lost,
1363 final String suffix_for_per_node_events_file ) {
1364 if ( ( go_namespace_limit != null ) && ( ( go_id_to_term_map == null ) || ( go_id_to_term_map.size() < 1 ) ) ) {
1365 throw new IllegalArgumentException( "attempt to use GO namespace limit without a GO-id to term map" );
1367 else if ( ( ( domain_id_to_go_ids_map == null ) || ( domain_id_to_go_ids_map.size() < 1 ) ) ) {
1368 throw new IllegalArgumentException( "attempt to output detailed HTML without a Pfam to GO map" );
1370 else if ( ( ( go_id_to_term_map == null ) || ( go_id_to_term_map.size() < 1 ) ) ) {
1371 throw new IllegalArgumentException( "attempt to output detailed HTML without a GO-id to term map" );
1373 final File outfile = new File( filename );
1374 checkForOutputFileWriteability( outfile );
1375 final SortedSet<String> sorted_ids = new TreeSet<String>();
1376 for( int i = 0; i < matrix.getNumberOfIdentifiers(); ++i ) {
1377 sorted_ids.add( matrix.getIdentifier( i ) );
1380 final Writer out = new BufferedWriter( new FileWriter( outfile ) );
1381 final File per_node_go_mapped_domain_gain_loss_files_base_dir = createBaseDirForPerNodeDomainFiles( surfacing.BASE_DIRECTORY_PER_NODE_DOMAIN_GAIN_LOSS_FILES,
1382 domain_combinations,
1385 Writer per_node_go_mapped_domain_gain_loss_outfile_writer = null;
1386 File per_node_go_mapped_domain_gain_loss_outfile = null;
1387 int per_node_counter = 0;
1388 out.write( "<html>" );
1389 out.write( SurfacingConstants.NL );
1390 addHtmlHead( out, title_for_html );
1391 out.write( SurfacingConstants.NL );
1392 out.write( "<body>" );
1393 out.write( SurfacingConstants.NL );
1394 out.write( "<h1>" );
1395 out.write( SurfacingConstants.NL );
1396 out.write( title_for_html );
1397 out.write( SurfacingConstants.NL );
1398 out.write( "</h1>" );
1399 out.write( SurfacingConstants.NL );
1400 out.write( "<table>" );
1401 out.write( SurfacingConstants.NL );
1402 for( final String id : sorted_ids ) {
1403 final Matcher matcher = PATTERN_SP_STYLE_TAXONOMY.matcher( id );
1404 if ( matcher.matches() ) {
1407 out.write( "<tr>" );
1408 out.write( "<td>" );
1409 out.write( "<a href=\"#" + id + "\">" + id + "</a>" );
1410 out.write( "</td>" );
1411 out.write( "</tr>" );
1412 out.write( SurfacingConstants.NL );
1414 out.write( "</table>" );
1415 out.write( SurfacingConstants.NL );
1416 for( final String id : sorted_ids ) {
1417 final Matcher matcher = PATTERN_SP_STYLE_TAXONOMY.matcher( id );
1418 if ( matcher.matches() ) {
1421 out.write( SurfacingConstants.NL );
1422 out.write( "<h2>" );
1423 out.write( "<a name=\"" + id + "\">" + id + "</a>" );
1424 writeTaxonomyLinks( out, id );
1425 out.write( "</h2>" );
1426 out.write( SurfacingConstants.NL );
1427 out.write( "<table>" );
1428 out.write( SurfacingConstants.NL );
1429 out.write( "<tr>" );
1430 out.write( "<td><b>" );
1431 out.write( "Pfam domain(s)" );
1432 out.write( "</b></td><td><b>" );
1433 out.write( "GO term acc" );
1434 out.write( "</b></td><td><b>" );
1435 out.write( "GO term" );
1436 out.write( "</b></td><td><b>" );
1437 out.write( "GO namespace" );
1438 out.write( "</b></td>" );
1439 out.write( "</tr>" );
1440 out.write( SurfacingConstants.NL );
1441 out.write( "</tr>" );
1442 out.write( SurfacingConstants.NL );
1443 per_node_counter = 0;
1444 if ( matrix.getNumberOfCharacters() > 0 ) {
1445 per_node_go_mapped_domain_gain_loss_outfile = new File( per_node_go_mapped_domain_gain_loss_files_base_dir
1446 + ForesterUtil.FILE_SEPARATOR + id + suffix_for_per_node_events_file );
1447 SurfacingUtil.checkForOutputFileWriteability( per_node_go_mapped_domain_gain_loss_outfile );
1448 per_node_go_mapped_domain_gain_loss_outfile_writer = ForesterUtil
1449 .createBufferedWriter( per_node_go_mapped_domain_gain_loss_outfile );
1452 per_node_go_mapped_domain_gain_loss_outfile = null;
1453 per_node_go_mapped_domain_gain_loss_outfile_writer = null;
1455 for( int c = 0; c < matrix.getNumberOfCharacters(); ++c ) {
1457 // using null to indicate either UNCHANGED_PRESENT or GAIN.
1458 if ( ( matrix.getState( id, c ) == state )
1459 || ( ( state == null ) && ( ( matrix.getState( id, c ) == CharacterStateMatrix.GainLossStates.UNCHANGED_PRESENT ) || ( matrix
1460 .getState( id, c ) == CharacterStateMatrix.GainLossStates.GAIN ) ) ) ) {
1461 final String character = matrix.getCharacter( c );
1462 String domain_0 = "";
1463 String domain_1 = "";
1464 if ( character.indexOf( BinaryDomainCombination.SEPARATOR ) > 0 ) {
1465 final String[] s = character.split( BinaryDomainCombination.SEPARATOR );
1466 if ( s.length != 2 ) {
1467 throw new AssertionError( "this should not have happened: unexpected format for domain combination: ["
1468 + character + "]" );
1474 domain_0 = character;
1476 writeDomainData( domain_id_to_go_ids_map,
1483 character_separator,
1484 domain_id_to_secondary_features_maps,
1486 all_pfams_encountered.add( domain_0 );
1487 if ( pfams_gained_or_lost != null ) {
1488 pfams_gained_or_lost.add( domain_0 );
1490 if ( !ForesterUtil.isEmpty( domain_1 ) ) {
1491 all_pfams_encountered.add( domain_1 );
1492 if ( pfams_gained_or_lost != null ) {
1493 pfams_gained_or_lost.add( domain_1 );
1496 if ( per_node_go_mapped_domain_gain_loss_outfile_writer != null ) {
1497 writeDomainsToIndividualFilePerTreeNode( per_node_go_mapped_domain_gain_loss_outfile_writer,
1504 if ( per_node_go_mapped_domain_gain_loss_outfile_writer != null ) {
1505 per_node_go_mapped_domain_gain_loss_outfile_writer.close();
1506 if ( per_node_counter < 1 ) {
1507 per_node_go_mapped_domain_gain_loss_outfile.delete();
1509 per_node_counter = 0;
1511 out.write( "</table>" );
1512 out.write( SurfacingConstants.NL );
1513 out.write( "<hr>" );
1514 out.write( SurfacingConstants.NL );
1515 } // for( final String id : sorted_ids ) {
1516 out.write( "</body>" );
1517 out.write( SurfacingConstants.NL );
1518 out.write( "</html>" );
1519 out.write( SurfacingConstants.NL );
1523 catch ( final IOException e ) {
1524 ForesterUtil.fatalError( surfacing.PRG_NAME, e.getMessage() );
1526 ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote characters detailed HTML list: \"" + filename + "\"" );
1529 public static void writeBinaryStatesMatrixToListORIGIG( final Map<DomainId, List<GoId>> domain_id_to_go_ids_map,
1530 final Map<GoId, GoTerm> go_id_to_term_map,
1531 final GoNameSpace go_namespace_limit,
1532 final boolean domain_combinations,
1533 final CharacterStateMatrix<CharacterStateMatrix.GainLossStates> matrix,
1534 final CharacterStateMatrix.GainLossStates state,
1535 final String filename,
1536 final String indentifier_characters_separator,
1537 final String character_separator,
1538 final String title_for_html,
1539 final String prefix_for_html,
1540 final Map<DomainId, Set<String>>[] domain_id_to_secondary_features_maps,
1541 final SortedSet<String> all_pfams_encountered,
1542 final SortedSet<String> pfams_gained_or_lost,
1543 final String suffix_for_per_node_events_file ) {
1544 if ( ( go_namespace_limit != null ) && ( ( go_id_to_term_map == null ) || ( go_id_to_term_map.size() < 1 ) ) ) {
1545 throw new IllegalArgumentException( "attempt to use GO namespace limit without a GO-id to term map" );
1547 else if ( ( ( domain_id_to_go_ids_map == null ) || ( domain_id_to_go_ids_map.size() < 1 ) ) ) {
1548 throw new IllegalArgumentException( "attempt to output detailed HTML without a Pfam to GO map" );
1550 else if ( ( ( go_id_to_term_map == null ) || ( go_id_to_term_map.size() < 1 ) ) ) {
1551 throw new IllegalArgumentException( "attempt to output detailed HTML without a GO-id to term map" );
1553 final File outfile = new File( filename );
1554 checkForOutputFileWriteability( outfile );
1555 final SortedSet<String> sorted_ids = new TreeSet<String>();
1556 for( int i = 0; i < matrix.getNumberOfIdentifiers(); ++i ) {
1557 sorted_ids.add( matrix.getIdentifier( i ) );
1560 final Writer out = new BufferedWriter( new FileWriter( outfile ) );
1561 final File per_node_go_mapped_domain_gain_loss_files_base_dir = createBaseDirForPerNodeDomainFiles( surfacing.BASE_DIRECTORY_PER_NODE_DOMAIN_GAIN_LOSS_FILES,
1562 domain_combinations,
1565 Writer per_node_go_mapped_domain_gain_loss_outfile_writer = null;
1566 File per_node_go_mapped_domain_gain_loss_outfile = null;
1567 int per_node_counter = 0;
1568 out.write( "<html>" );
1569 out.write( SurfacingConstants.NL );
1570 addHtmlHead( out, title_for_html );
1571 out.write( SurfacingConstants.NL );
1572 out.write( "<body>" );
1573 out.write( SurfacingConstants.NL );
1574 out.write( "<h1>" );
1575 out.write( SurfacingConstants.NL );
1576 out.write( title_for_html );
1577 out.write( SurfacingConstants.NL );
1578 out.write( "</h1>" );
1579 out.write( SurfacingConstants.NL );
1580 out.write( "<table>" );
1581 out.write( SurfacingConstants.NL );
1582 for( final String id : sorted_ids ) {
1583 out.write( "<tr>" );
1584 out.write( "<td>" );
1585 out.write( "<a href=\"#" + id + "\">" + id + "</a>" );
1586 writeTaxonomyLinks( out, id );
1587 out.write( "</td>" );
1588 out.write( "</tr>" );
1589 out.write( SurfacingConstants.NL );
1591 out.write( "</table>" );
1592 out.write( SurfacingConstants.NL );
1593 for( final String id : sorted_ids ) {
1594 out.write( SurfacingConstants.NL );
1595 out.write( "<h2>" );
1596 out.write( "<a name=\"" + id + "\">" + id + "</a>" );
1597 writeTaxonomyLinks( out, id );
1598 out.write( "</h2>" );
1599 out.write( SurfacingConstants.NL );
1600 out.write( "<table>" );
1601 out.write( SurfacingConstants.NL );
1602 out.write( "<tr>" );
1603 out.write( "<td><b>" );
1604 out.write( "Pfam domain(s)" );
1605 out.write( "</b></td><td><b>" );
1606 out.write( "GO term acc" );
1607 out.write( "</b></td><td><b>" );
1608 out.write( "GO term" );
1609 out.write( "</b></td><td><b>" );
1610 out.write( "Penultimate GO term" );
1611 out.write( "</b></td><td><b>" );
1612 out.write( "GO namespace" );
1613 out.write( "</b></td>" );
1614 out.write( "</tr>" );
1615 out.write( SurfacingConstants.NL );
1616 out.write( "</tr>" );
1617 out.write( SurfacingConstants.NL );
1618 per_node_counter = 0;
1619 if ( matrix.getNumberOfCharacters() > 0 ) {
1620 per_node_go_mapped_domain_gain_loss_outfile = new File( per_node_go_mapped_domain_gain_loss_files_base_dir
1621 + ForesterUtil.FILE_SEPARATOR + id + suffix_for_per_node_events_file );
1622 SurfacingUtil.checkForOutputFileWriteability( per_node_go_mapped_domain_gain_loss_outfile );
1623 per_node_go_mapped_domain_gain_loss_outfile_writer = ForesterUtil
1624 .createBufferedWriter( per_node_go_mapped_domain_gain_loss_outfile );
1627 per_node_go_mapped_domain_gain_loss_outfile = null;
1628 per_node_go_mapped_domain_gain_loss_outfile_writer = null;
1630 for( int c = 0; c < matrix.getNumberOfCharacters(); ++c ) {
1632 // using null to indicate either UNCHANGED_PRESENT or GAIN.
1633 if ( ( matrix.getState( id, c ) == state )
1634 || ( ( state == null ) && ( ( matrix.getState( id, c ) == CharacterStateMatrix.GainLossStates.UNCHANGED_PRESENT ) || ( matrix
1635 .getState( id, c ) == CharacterStateMatrix.GainLossStates.GAIN ) ) ) ) {
1636 final String character = matrix.getCharacter( c );
1637 String domain_0 = "";
1638 String domain_1 = "";
1639 if ( character.indexOf( BinaryDomainCombination.SEPARATOR ) > 0 ) {
1640 final String[] s = character.split( BinaryDomainCombination.SEPARATOR );
1641 if ( s.length != 2 ) {
1642 throw new AssertionError( "this should not have happened: unexpected format for domain combination: ["
1643 + character + "]" );
1649 domain_0 = character;
1651 writeDomainData( domain_id_to_go_ids_map,
1658 character_separator,
1659 domain_id_to_secondary_features_maps,
1661 all_pfams_encountered.add( domain_0 );
1662 if ( pfams_gained_or_lost != null ) {
1663 pfams_gained_or_lost.add( domain_0 );
1665 if ( !ForesterUtil.isEmpty( domain_1 ) ) {
1666 all_pfams_encountered.add( domain_1 );
1667 if ( pfams_gained_or_lost != null ) {
1668 pfams_gained_or_lost.add( domain_1 );
1671 if ( per_node_go_mapped_domain_gain_loss_outfile_writer != null ) {
1672 writeDomainsToIndividualFilePerTreeNode( per_node_go_mapped_domain_gain_loss_outfile_writer,
1679 if ( per_node_go_mapped_domain_gain_loss_outfile_writer != null ) {
1680 per_node_go_mapped_domain_gain_loss_outfile_writer.close();
1681 if ( per_node_counter < 1 ) {
1682 per_node_go_mapped_domain_gain_loss_outfile.delete();
1684 per_node_counter = 0;
1686 out.write( "</table>" );
1687 out.write( SurfacingConstants.NL );
1688 out.write( "<hr>" );
1689 out.write( SurfacingConstants.NL );
1690 } // for( final String id : sorted_ids ) {
1691 out.write( "</body>" );
1692 out.write( SurfacingConstants.NL );
1693 out.write( "</html>" );
1694 out.write( SurfacingConstants.NL );
1698 catch ( final IOException e ) {
1699 ForesterUtil.fatalError( surfacing.PRG_NAME, e.getMessage() );
1701 ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote characters detailed HTML list: \"" + filename + "\"" );
1704 public static void writeDomainCombinationsCountsFile( final String[][] input_file_properties,
1705 final File output_dir,
1706 final Writer per_genome_domain_promiscuity_statistics_writer,
1707 final GenomeWideCombinableDomains gwcd,
1709 final GenomeWideCombinableDomains.GenomeWideCombinableDomainsSortOrder dc_sort_order ) {
1710 File dc_outfile = new File( input_file_properties[ i ][ 0 ]
1711 + surfacing.DOMAIN_COMBINITON_COUNTS_OUTPUTFILE_SUFFIX );
1712 if ( output_dir != null ) {
1713 dc_outfile = new File( output_dir + ForesterUtil.FILE_SEPARATOR + dc_outfile );
1715 checkForOutputFileWriteability( dc_outfile );
1717 final BufferedWriter out = new BufferedWriter( new FileWriter( dc_outfile ) );
1718 out.write( gwcd.toStringBuilder( dc_sort_order ).toString() );
1721 catch ( final IOException e ) {
1722 ForesterUtil.fatalError( surfacing.PRG_NAME, e.getMessage() );
1724 final DescriptiveStatistics stats = gwcd.getPerGenomeDomainPromiscuityStatistics();
1726 per_genome_domain_promiscuity_statistics_writer.write( input_file_properties[ i ][ 0 ] + "\t" );
1727 per_genome_domain_promiscuity_statistics_writer.write( FORMATTER_3.format( stats.arithmeticMean() ) + "\t" );
1728 if ( stats.getN() < 2 ) {
1729 per_genome_domain_promiscuity_statistics_writer.write( "n/a" + "\t" );
1732 per_genome_domain_promiscuity_statistics_writer.write( FORMATTER_3.format( stats
1733 .sampleStandardDeviation() ) + "\t" );
1735 per_genome_domain_promiscuity_statistics_writer.write( FORMATTER_3.format( stats.median() ) + "\t" );
1736 per_genome_domain_promiscuity_statistics_writer.write( ( int ) stats.getMin() + "\t" );
1737 per_genome_domain_promiscuity_statistics_writer.write( ( int ) stats.getMax() + "\t" );
1738 per_genome_domain_promiscuity_statistics_writer.write( stats.getN() + "\t" );
1739 final SortedSet<DomainId> mpds = gwcd.getMostPromiscuosDomain();
1740 for( final DomainId mpd : mpds ) {
1741 per_genome_domain_promiscuity_statistics_writer.write( mpd.getId() + " " );
1743 per_genome_domain_promiscuity_statistics_writer.write( ForesterUtil.LINE_SEPARATOR );
1745 catch ( final IOException e ) {
1746 ForesterUtil.fatalError( surfacing.PRG_NAME, e.getMessage() );
1748 if ( input_file_properties[ i ].length == 3 ) {
1749 ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote domain combination counts for \""
1750 + input_file_properties[ i ][ 0 ] + "\" (" + input_file_properties[ i ][ 1 ] + ", "
1751 + input_file_properties[ i ][ 2 ] + ") to: \"" + dc_outfile + "\"" );
1754 ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote domain combination counts for \""
1755 + input_file_properties[ i ][ 0 ] + "\" (" + input_file_properties[ i ][ 1 ] + ") to: \""
1756 + dc_outfile + "\"" );
1760 private static void writeDomainData( final Map<DomainId, List<GoId>> domain_id_to_go_ids_map,
1761 final Map<GoId, GoTerm> go_id_to_term_map,
1762 final GoNameSpace go_namespace_limit,
1764 final String domain_0,
1765 final String domain_1,
1766 final String prefix_for_html,
1767 final String character_separator_for_non_html_output,
1768 final Map<DomainId, Set<String>>[] domain_id_to_secondary_features_maps,
1769 final Set<GoId> all_go_ids ) throws IOException {
1770 boolean any_go_annotation_present = false;
1771 boolean first_has_no_go = false;
1772 int domain_count = 2; // To distinguish between domains and binary domain combinations.
1773 if ( ForesterUtil.isEmpty( domain_1 ) ) {
1776 // The following has a difficult to understand logic.
1777 for( int d = 0; d < domain_count; ++d ) {
1778 List<GoId> go_ids = null;
1779 boolean go_annotation_present = false;
1781 final DomainId domain_id = new DomainId( domain_0 );
1782 if ( domain_id_to_go_ids_map.containsKey( domain_id ) ) {
1783 go_annotation_present = true;
1784 any_go_annotation_present = true;
1785 go_ids = domain_id_to_go_ids_map.get( domain_id );
1788 first_has_no_go = true;
1792 final DomainId domain_id = new DomainId( domain_1 );
1793 if ( domain_id_to_go_ids_map.containsKey( domain_id ) ) {
1794 go_annotation_present = true;
1795 any_go_annotation_present = true;
1796 go_ids = domain_id_to_go_ids_map.get( domain_id );
1799 if ( go_annotation_present ) {
1800 boolean first = ( ( d == 0 ) || ( ( d == 1 ) && first_has_no_go ) );
1801 for( final GoId go_id : go_ids ) {
1802 out.write( "<tr>" );
1805 writeDomainIdsToHtml( out,
1809 domain_id_to_secondary_features_maps );
1812 out.write( "<td></td>" );
1814 if ( !go_id_to_term_map.containsKey( go_id ) ) {
1815 throw new IllegalArgumentException( "GO-id [" + go_id + "] not found in GO-id to GO-term map" );
1817 final GoTerm go_term = go_id_to_term_map.get( go_id );
1818 if ( ( go_namespace_limit == null ) || go_namespace_limit.equals( go_term.getGoNameSpace() ) ) {
1819 // final String top = GoUtils.getPenultimateGoTerm( go_term, go_id_to_term_map ).getName();
1820 final String go_id_str = go_id.getId();
1821 out.write( "<td>" );
1822 out.write( "<a href=\"" + SurfacingConstants.AMIGO_LINK + go_id_str
1823 + "\" target=\"amigo_window\">" + go_id_str + "</a>" );
1824 out.write( "</td><td>" );
1825 out.write( go_term.getName() );
1826 if ( domain_count == 2 ) {
1827 out.write( " (" + d + ")" );
1829 out.write( "</td><td>" );
1830 // out.write( top );
1831 // out.write( "</td><td>" );
1833 out.write( go_term.getGoNameSpace().toShortString() );
1835 out.write( "</td>" );
1836 if ( all_go_ids != null ) {
1837 all_go_ids.add( go_id );
1841 out.write( "<td>" );
1842 out.write( "</td><td>" );
1843 out.write( "</td><td>" );
1844 out.write( "</td><td>" );
1845 out.write( "</td>" );
1847 out.write( "</tr>" );
1848 out.write( SurfacingConstants.NL );
1851 } // for( int d = 0; d < domain_count; ++d )
1852 if ( !any_go_annotation_present ) {
1853 out.write( "<tr>" );
1854 writeDomainIdsToHtml( out, domain_0, domain_1, prefix_for_html, domain_id_to_secondary_features_maps );
1855 out.write( "<td>" );
1856 out.write( "</td><td>" );
1857 out.write( "</td><td>" );
1858 out.write( "</td><td>" );
1859 out.write( "</td>" );
1860 out.write( "</tr>" );
1861 out.write( SurfacingConstants.NL );
1865 private static void writeDomainDataORIG( final Map<DomainId, List<GoId>> domain_id_to_go_ids_map,
1866 final Map<GoId, GoTerm> go_id_to_term_map,
1867 final GoNameSpace go_namespace_limit,
1869 final String domain_0,
1870 final String domain_1,
1871 final String prefix_for_html,
1872 final String character_separator_for_non_html_output,
1873 final Map<DomainId, Set<String>>[] domain_id_to_secondary_features_maps,
1874 final Set<GoId> all_go_ids ) throws IOException {
1875 boolean any_go_annotation_present = false;
1876 boolean first_has_no_go = false;
1877 int domain_count = 2; // To distinguish between domains and binary domain combinations.
1878 if ( ForesterUtil.isEmpty( domain_1 ) ) {
1881 // The following has a difficult to understand logic.
1882 for( int d = 0; d < domain_count; ++d ) {
1883 List<GoId> go_ids = null;
1884 boolean go_annotation_present = false;
1886 final DomainId domain_id = new DomainId( domain_0 );
1887 if ( domain_id_to_go_ids_map.containsKey( domain_id ) ) {
1888 go_annotation_present = true;
1889 any_go_annotation_present = true;
1890 go_ids = domain_id_to_go_ids_map.get( domain_id );
1893 first_has_no_go = true;
1897 final DomainId domain_id = new DomainId( domain_1 );
1898 if ( domain_id_to_go_ids_map.containsKey( domain_id ) ) {
1899 go_annotation_present = true;
1900 any_go_annotation_present = true;
1901 go_ids = domain_id_to_go_ids_map.get( domain_id );
1904 if ( go_annotation_present ) {
1905 boolean first = ( ( d == 0 ) || ( ( d == 1 ) && first_has_no_go ) );
1906 for( final GoId go_id : go_ids ) {
1907 out.write( "<tr>" );
1910 writeDomainIdsToHtml( out,
1914 domain_id_to_secondary_features_maps );
1917 out.write( "<td></td>" );
1919 if ( !go_id_to_term_map.containsKey( go_id ) ) {
1920 throw new IllegalArgumentException( "GO-id [" + go_id + "] not found in GO-id to GO-term map" );
1922 final GoTerm go_term = go_id_to_term_map.get( go_id );
1923 if ( ( go_namespace_limit == null ) || go_namespace_limit.equals( go_term.getGoNameSpace() ) ) {
1924 final String top = GoUtils.getPenultimateGoTerm( go_term, go_id_to_term_map ).getName();
1925 final String go_id_str = go_id.getId();
1926 out.write( "<td>" );
1927 out.write( "<a href=\"" + SurfacingConstants.AMIGO_LINK + go_id_str
1928 + "\" target=\"amigo_window\">" + go_id_str + "</a>" );
1929 out.write( "</td><td>" );
1930 out.write( go_term.getName() );
1931 if ( domain_count == 2 ) {
1932 out.write( " (" + d + ")" );
1934 out.write( "</td><td>" );
1936 out.write( "</td><td>" );
1938 out.write( go_term.getGoNameSpace().toShortString() );
1940 out.write( "</td>" );
1941 if ( all_go_ids != null ) {
1942 all_go_ids.add( go_id );
1946 out.write( "<td>" );
1947 out.write( "</td><td>" );
1948 out.write( "</td><td>" );
1949 out.write( "</td><td>" );
1950 out.write( "</td>" );
1952 out.write( "</tr>" );
1953 out.write( SurfacingConstants.NL );
1956 } // for( int d = 0; d < domain_count; ++d )
1957 if ( !any_go_annotation_present ) {
1958 out.write( "<tr>" );
1959 writeDomainIdsToHtml( out, domain_0, domain_1, prefix_for_html, domain_id_to_secondary_features_maps );
1960 out.write( "<td>" );
1961 out.write( "</td><td>" );
1962 out.write( "</td><td>" );
1963 out.write( "</td><td>" );
1964 out.write( "</td>" );
1965 out.write( "</tr>" );
1966 out.write( SurfacingConstants.NL );
1970 private static void writeDomainIdsToHtml( final Writer out,
1971 final String domain_0,
1972 final String domain_1,
1973 final String prefix_for_detailed_html,
1974 final Map<DomainId, Set<String>>[] domain_id_to_secondary_features_maps )
1975 throws IOException {
1976 out.write( "<td>" );
1977 if ( !ForesterUtil.isEmpty( prefix_for_detailed_html ) ) {
1978 out.write( prefix_for_detailed_html );
1981 out.write( "<a href=\"" + SurfacingConstants.PFAM_FAMILY_ID_LINK + domain_0 + "\">" + domain_0 + "</a>" );
1982 //if ( ForesterUtil.isEmpty( domain_1 ) ) {
1983 // out.write( " <a href=\"" + SurfacingConstants.GOOGLE_SCHOLAR_LINK + domain_0
1984 // + SurfacingConstants.GOOGLE_SCHOLAR_LIMITS + "\">[gs]</a>" );
1986 // if ( !ForesterUtil.isEmpty( domain_1 ) ) {
1987 // out.write( "=" );
1988 // out.write( "<a href=\"" + SurfacingConstants.PFAM_FAMILY_ID_LINK + domain_1 + "\">" + domain_1 + "</a>" );
1990 // else if ( ( domain_id_to_secondary_features_maps != null )
1991 // && ( domain_id_to_secondary_features_maps.length > 0 ) ) {
1992 // out.write( " [" );
1993 // boolean first = true;
1994 // for( final Map<DomainId, Set<String>> domain_id_to_secondary_features_map : domain_id_to_secondary_features_maps ) {
1995 // final Set<String> sec_features = domain_id_to_secondary_features_map.get( new DomainId( domain_0 ) );
1996 // if ( ( sec_features != null ) && ( sec_features.size() > 0 ) ) {
1997 // for( final String sec_feature : sec_features ) {
2002 // out.write( ", " );
2004 // if ( SurfacingConstants.SECONDARY_FEATURES_ARE_SCOP
2005 // && ( SurfacingConstants.SECONDARY_FEATURES_SCOP_LINK != null ) ) {
2006 // out.write( "<a href=\"" + SurfacingConstants.SECONDARY_FEATURES_SCOP_LINK + sec_feature
2007 // + "\" target=\"scop_window\">" + sec_feature + "</a>" );
2010 // out.write( sec_feature );
2015 // out.write( "]" );
2017 out.write( "</td>" );
2020 private static void writeDomainIdsToHtmlORIG( final Writer out,
2021 final String domain_0,
2022 final String domain_1,
2023 final String prefix_for_detailed_html,
2024 final Map<DomainId, Set<String>>[] domain_id_to_secondary_features_maps )
2025 throws IOException {
2026 out.write( "<td>" );
2027 if ( !ForesterUtil.isEmpty( prefix_for_detailed_html ) ) {
2028 out.write( prefix_for_detailed_html );
2031 out.write( "<a href=\"" + SurfacingConstants.PFAM_FAMILY_ID_LINK + domain_0 + "\">" + domain_0 + "</a>" );
2032 if ( ForesterUtil.isEmpty( domain_1 ) ) {
2033 out.write( " <a href=\"" + SurfacingConstants.GOOGLE_SCHOLAR_LINK + domain_0
2034 + SurfacingConstants.GOOGLE_SCHOLAR_LIMITS + "\">[gs]</a>" );
2036 if ( !ForesterUtil.isEmpty( domain_1 ) ) {
2038 out.write( "<a href=\"" + SurfacingConstants.PFAM_FAMILY_ID_LINK + domain_1 + "\">" + domain_1 + "</a>" );
2040 else if ( ( domain_id_to_secondary_features_maps != null )
2041 && ( domain_id_to_secondary_features_maps.length > 0 ) ) {
2043 boolean first = true;
2044 for( final Map<DomainId, Set<String>> domain_id_to_secondary_features_map : domain_id_to_secondary_features_maps ) {
2045 final Set<String> sec_features = domain_id_to_secondary_features_map.get( new DomainId( domain_0 ) );
2046 if ( ( sec_features != null ) && ( sec_features.size() > 0 ) ) {
2047 for( final String sec_feature : sec_features ) {
2054 if ( SurfacingConstants.SECONDARY_FEATURES_ARE_SCOP
2055 && ( SurfacingConstants.SECONDARY_FEATURES_SCOP_LINK != null ) ) {
2056 out.write( "<a href=\"" + SurfacingConstants.SECONDARY_FEATURES_SCOP_LINK + sec_feature
2057 + "\" target=\"scop_window\">" + sec_feature + "</a>" );
2060 out.write( sec_feature );
2067 out.write( "</td>" );
2070 public static DescriptiveStatistics writeDomainSimilaritiesToFile( final StringBuilder html_desc,
2071 final StringBuilder html_title,
2073 final SortedSet<DomainSimilarity> similarities,
2074 final boolean treat_as_binary,
2075 final List<Species> species_order,
2076 final PrintableDomainSimilarity.PRINT_OPTION print_option,
2077 final DomainSimilarity.DomainSimilaritySortField sort_field,
2078 final DomainSimilarity.DomainSimilarityScoring scoring,
2079 final boolean verbose ) throws IOException {
2080 final DescriptiveStatistics stats = new BasicDescriptiveStatistics();
2081 String histogram_title = null;
2082 switch ( sort_field ) {
2083 case ABS_MAX_COUNTS_DIFFERENCE:
2084 if ( treat_as_binary ) {
2085 histogram_title = "absolute counts difference:";
2088 histogram_title = "absolute (maximal) counts difference:";
2091 case MAX_COUNTS_DIFFERENCE:
2092 if ( treat_as_binary ) {
2093 histogram_title = "counts difference:";
2096 histogram_title = "(maximal) counts difference:";
2100 histogram_title = "score mean:";
2103 histogram_title = "score minimum:";
2106 histogram_title = "score maximum:";
2108 case MAX_DIFFERENCE:
2109 if ( treat_as_binary ) {
2110 histogram_title = "difference:";
2113 histogram_title = "(maximal) difference:";
2117 histogram_title = "score mean:";
2120 histogram_title = "score standard deviation:";
2123 histogram_title = "species number:";
2126 throw new AssertionError( "Unknown sort field: " + sort_field );
2128 for( final DomainSimilarity similarity : similarities ) {
2129 switch ( sort_field ) {
2130 case ABS_MAX_COUNTS_DIFFERENCE:
2131 stats.addValue( Math.abs( similarity.getMaximalDifferenceInCounts() ) );
2133 case MAX_COUNTS_DIFFERENCE:
2134 stats.addValue( similarity.getMaximalDifferenceInCounts() );
2137 stats.addValue( similarity.getMeanSimilarityScore() );
2140 stats.addValue( similarity.getMinimalSimilarityScore() );
2143 stats.addValue( similarity.getMaximalSimilarityScore() );
2145 case MAX_DIFFERENCE:
2146 stats.addValue( similarity.getMaximalDifference() );
2149 stats.addValue( similarity.getMeanSimilarityScore() );
2152 stats.addValue( similarity.getStandardDeviationOfSimilarityScore() );
2155 stats.addValue( similarity.getSpecies().size() );
2158 throw new AssertionError( "Unknown sort field: " + sort_field );
2162 // final HistogramData[] hists = new HistogramData[ 1 ];
2165 // List<HistogramDataItem> data_items = new
2166 // ArrayList<HistogramDataItem>();
2167 // double[] values = stats.getDataAsDoubleArray();
2168 // for( int i = 0; i < values.length; i++ ) {
2169 // HistogramDataItem data_item = new BasicHistogramDataItem( "", values[
2171 // data_items.add( data_item );
2175 // HistogramData hd0 = new HistogramData( "name",
2183 // hists[ 0 ] = hd0;
2185 // final HistogramsFrame hf = new HistogramsFrame( hists );
2186 // hf.setVisible( true );
2188 AsciiHistogram histo = null;
2189 if ( stats.getMin() < stats.getMin() ) {
2190 histo = new AsciiHistogram( stats, histogram_title );
2193 if ( histo != null ) {
2194 System.out.println( histo.toStringBuffer( 20, '|', 40, 5 ) );
2196 System.out.println();
2197 System.out.println( "N : " + stats.getN() );
2198 System.out.println( "Min : " + stats.getMin() );
2199 System.out.println( "Max : " + stats.getMax() );
2200 System.out.println( "Mean : " + stats.arithmeticMean() );
2201 if ( stats.getN() > 1 ) {
2202 System.out.println( "SD : " + stats.sampleStandardDeviation() );
2205 System.out.println( "SD : n/a" );
2207 System.out.println( "Median : " + stats.median() );
2208 if ( stats.getN() > 1 ) {
2209 System.out.println( "Pearsonian skewness : " + stats.pearsonianSkewness() );
2212 System.out.println( "Pearsonian skewness : n/a" );
2215 switch ( print_option ) {
2216 case SIMPLE_TAB_DELIMITED:
2219 w.write( "<html>" );
2220 w.write( SurfacingConstants.NL );
2221 addHtmlHead( w, "SURFACING :: " + html_title );
2222 w.write( SurfacingConstants.NL );
2223 w.write( "<body>" );
2224 w.write( SurfacingConstants.NL );
2225 w.write( html_desc.toString() );
2226 w.write( SurfacingConstants.NL );
2229 w.write( SurfacingConstants.NL );
2230 w.write( "<tt><pre>" );
2231 w.write( SurfacingConstants.NL );
2232 if ( histo != null ) {
2233 w.write( histo.toStringBuffer( 20, '|', 40, 5 ).toString() );
2234 w.write( SurfacingConstants.NL );
2236 w.write( "</pre></tt>" );
2237 w.write( SurfacingConstants.NL );
2238 w.write( "<table>" );
2239 w.write( SurfacingConstants.NL );
2240 w.write( "<tr><td>N: </td><td>" + stats.getN() + "</td></tr>" );
2241 w.write( SurfacingConstants.NL );
2242 w.write( "<tr><td>Min: </td><td>" + stats.getMin() + "</td></tr>" );
2243 w.write( SurfacingConstants.NL );
2244 w.write( "<tr><td>Max: </td><td>" + stats.getMax() + "</td></tr>" );
2245 w.write( SurfacingConstants.NL );
2246 w.write( "<tr><td>Mean: </td><td>" + stats.arithmeticMean() + "</td></tr>" );
2247 w.write( SurfacingConstants.NL );
2248 if ( stats.getN() > 1 ) {
2249 w.write( "<tr><td>SD: </td><td>" + stats.sampleStandardDeviation() + "</td></tr>" );
2252 w.write( "<tr><td>SD: </td><td>n/a</td></tr>" );
2254 w.write( SurfacingConstants.NL );
2255 w.write( "<tr><td>Median: </td><td>" + stats.median() + "</td></tr>" );
2256 w.write( SurfacingConstants.NL );
2257 if ( stats.getN() > 1 ) {
2258 w.write( "<tr><td>Pearsonian skewness: </td><td>" + stats.pearsonianSkewness() + "</td></tr>" );
2261 w.write( "<tr><td>Pearsonian skewness: </td><td>n/a</td></tr>" );
2263 w.write( SurfacingConstants.NL );
2264 w.write( "</table>" );
2265 w.write( SurfacingConstants.NL );
2267 w.write( SurfacingConstants.NL );
2269 w.write( SurfacingConstants.NL );
2271 w.write( SurfacingConstants.NL );
2272 w.write( "<table>" );
2273 w.write( SurfacingConstants.NL );
2276 w.write( SurfacingConstants.NL );
2277 for( final DomainSimilarity similarity : similarities ) {
2278 if ( ( species_order != null ) && !species_order.isEmpty() ) {
2279 ( ( PrintableDomainSimilarity ) similarity ).setSpeciesOrder( species_order );
2281 w.write( similarity.toStringBuffer( print_option ).toString() );
2282 w.write( SurfacingConstants.NL );
2284 switch ( print_option ) {
2286 w.write( SurfacingConstants.NL );
2287 w.write( "</table>" );
2288 w.write( SurfacingConstants.NL );
2289 w.write( "</font>" );
2290 w.write( SurfacingConstants.NL );
2291 w.write( "</body>" );
2292 w.write( SurfacingConstants.NL );
2293 w.write( "</html>" );
2294 w.write( SurfacingConstants.NL );
2302 private static void writeDomainsToIndividualFilePerTreeNode( final Writer individual_files_writer,
2303 final String domain_0,
2304 final String domain_1 ) throws IOException {
2305 individual_files_writer.write( domain_0 );
2306 individual_files_writer.write( ForesterUtil.LINE_SEPARATOR );
2307 if ( !ForesterUtil.isEmpty( domain_1 ) ) {
2308 individual_files_writer.write( domain_1 );
2309 individual_files_writer.write( ForesterUtil.LINE_SEPARATOR );
2313 public static void writeMatrixToFile( final CharacterStateMatrix<?> matrix,
2314 final String filename,
2315 final Format format ) {
2316 final File outfile = new File( filename );
2317 checkForOutputFileWriteability( outfile );
2319 final BufferedWriter out = new BufferedWriter( new FileWriter( outfile ) );
2320 matrix.toWriter( out, format );
2324 catch ( final IOException e ) {
2325 ForesterUtil.fatalError( surfacing.PRG_NAME, e.getMessage() );
2327 ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote matrix: \"" + filename + "\"" );
2330 public static void writeMatrixToFile( final File matrix_outfile, final List<DistanceMatrix> matrices ) {
2331 checkForOutputFileWriteability( matrix_outfile );
2333 final BufferedWriter out = new BufferedWriter( new FileWriter( matrix_outfile ) );
2334 for( final DistanceMatrix distance_matrix : matrices ) {
2335 out.write( distance_matrix.toStringBuffer( DistanceMatrix.Format.PHYLIP ).toString() );
2336 out.write( ForesterUtil.LINE_SEPARATOR );
2341 catch ( final IOException e ) {
2342 ForesterUtil.fatalError( surfacing.PRG_NAME, e.getMessage() );
2344 ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote distance matrices to \"" + matrix_outfile + "\"" );
2347 private static void writePfamsToFile( final String outfile_name, final SortedSet<String> pfams ) {
2349 final Writer writer = new BufferedWriter( new FileWriter( new File( outfile_name ) ) );
2350 for( final String pfam : pfams ) {
2351 writer.write( pfam );
2352 writer.write( ForesterUtil.LINE_SEPARATOR );
2355 ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote " + pfams.size() + " pfams to [" + outfile_name
2358 catch ( final IOException e ) {
2359 ForesterUtil.printWarningMessage( surfacing.PRG_NAME, "Failure to write: " + e );
2363 public static void writePhylogenyToFile( final Phylogeny phylogeny, final String filename ) {
2364 final PhylogenyWriter writer = new PhylogenyWriter();
2366 writer.toPhyloXML( new File( filename ), phylogeny, 1 );
2368 catch ( final IOException e ) {
2369 ForesterUtil.printWarningMessage( surfacing.PRG_NAME, "failed to write phylogeny to \"" + filename + "\": "
2372 ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote phylogeny to \"" + filename + "\"" );
2375 public static void writeTaxonomyLinks( final Writer writer, final String species ) throws IOException {
2376 if ( ( species.length() > 1 ) && ( species.indexOf( '_' ) < 1 ) ) {
2377 final Matcher matcher = PATTERN_SP_STYLE_TAXONOMY.matcher( species );
2378 writer.write( " [" );
2379 if ( matcher.matches() ) {
2380 writer.write( "<a href=\"" + SurfacingConstants.UNIPROT_LINK + species
2381 + "\" target=\"taxonomy_window\">uniprot</a>" );
2384 writer.write( "<a href=\"" + SurfacingConstants.EOL_LINK + species
2385 + "\" target=\"taxonomy_window\">eol</a>" );
2386 writer.write( "|" );
2387 writer.write( "<a href=\"" + SurfacingConstants.TOL_LINK + species
2388 + "\" target=\"taxonomy_window\">tol</a>" );
2390 writer.write( "]" );
2394 public static void writeTaxonomyLinksORIG( final Writer writer, final String species ) throws IOException {
2395 if ( ( species.length() > 1 ) && ( species.indexOf( '_' ) < 1 ) ) {
2396 final Matcher matcher = PATTERN_SP_STYLE_TAXONOMY.matcher( species );
2397 writer.write( " [" );
2398 if ( matcher.matches() ) {
2399 writer.write( "<a href=\"" + SurfacingConstants.UNIPROT_LINK + species
2400 + "\" target=\"taxonomy_window\">uniprot</a>" );
2403 writer.write( "<a href=\"" + SurfacingConstants.EOL_LINK + species
2404 + "\" target=\"taxonomy_window\">eol</a>" );
2405 writer.write( "|" );
2406 writer.write( "<a href=\"" + SurfacingConstants.TOL_LINK + species
2407 + "\" target=\"taxonomy_window\">tol</a>" );
2408 writer.write( "|" );
2409 writer.write( "<a href=\"" + SurfacingConstants.WIKIPEDIA_LINK + species
2410 + "\" target=\"taxonomy_window\">wikipedia</a>" );
2411 writer.write( "|" );
2412 writer.write( "<a href=\"" + SurfacingConstants.GOOGLE_SCHOLAR_LINK + species
2413 + "\" target=\"taxonomy_window\">gs</a>" );
2415 writer.write( "]" );
2419 private static void writeToNexus( final String outfile_name, final CharacterStateMatrix<BinaryStates> matrix ) {
2420 if ( !( matrix instanceof BasicCharacterStateMatrix ) ) {
2421 throw new IllegalArgumentException( "can only write matrices of type [" + BasicCharacterStateMatrix.class
2424 final BasicCharacterStateMatrix<BinaryStates> my_matrix = ( org.forester.evoinference.matrix.character.BasicCharacterStateMatrix<BinaryStates> ) matrix;
2426 final BufferedWriter w = new BufferedWriter( new FileWriter( outfile_name ) );
2427 w.write( NexusConstants.NEXUS );
2428 w.write( ForesterUtil.LINE_SEPARATOR );
2429 my_matrix.writeNexusTaxaBlock( w );
2430 my_matrix.writeNexusBinaryChractersBlock( w );
2433 ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote Nexus file: \"" + outfile_name + "\"" );
2435 catch ( final IOException e ) {
2436 ForesterUtil.fatalError( surfacing.PRG_NAME, e.getMessage() );
2440 private static void writeToNexus( final String outfile_name,
2441 final CharacterStateMatrix<BinaryStates> matrix,
2442 final Phylogeny phylogeny ) {
2443 if ( !( matrix instanceof BasicCharacterStateMatrix ) ) {
2444 throw new IllegalArgumentException( "can only write matrices of type [" + BasicCharacterStateMatrix.class
2447 final BasicCharacterStateMatrix<BinaryStates> my_matrix = ( org.forester.evoinference.matrix.character.BasicCharacterStateMatrix<BinaryStates> ) matrix;
2448 final List<Phylogeny> phylogenies = new ArrayList<Phylogeny>( 1 );
2449 phylogenies.add( phylogeny );
2451 final BufferedWriter w = new BufferedWriter( new FileWriter( outfile_name ) );
2452 w.write( NexusConstants.NEXUS );
2453 w.write( ForesterUtil.LINE_SEPARATOR );
2454 my_matrix.writeNexusTaxaBlock( w );
2455 my_matrix.writeNexusBinaryChractersBlock( w );
2456 PhylogenyWriter.writeNexusTreesBlock( w, phylogenies );
2459 ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote Nexus file: \"" + outfile_name + "\"" );
2461 catch ( final IOException e ) {
2462 ForesterUtil.fatalError( surfacing.PRG_NAME, e.getMessage() );
2466 private static void writeToNexus( final String outfile_name, final DomainParsimonyCalculator domain_parsimony ) {
2467 writeToNexus( outfile_name + surfacing.NEXUS_EXTERNAL_DOMAINS,
2468 domain_parsimony.createMatrixOfDomainPresenceOrAbsence() );
2469 writeToNexus( outfile_name + surfacing.NEXUS_EXTERNAL_DOMAIN_COMBINATIONS,
2470 domain_parsimony.createMatrixOfBinaryDomainCombinationPresenceOrAbsence() );
2473 private static void writeToNexus( final String outfile_name,
2474 final DomainParsimonyCalculator domain_parsimony,
2475 final Phylogeny phylogeny ) {
2476 writeToNexus( outfile_name + surfacing.NEXUS_EXTERNAL_DOMAINS,
2477 domain_parsimony.createMatrixOfDomainPresenceOrAbsence(),
2479 writeToNexus( outfile_name + surfacing.NEXUS_EXTERNAL_DOMAIN_COMBINATIONS,
2480 domain_parsimony.createMatrixOfBinaryDomainCombinationPresenceOrAbsence(),