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_old;
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_old.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_old.PARSIMONY_OUTPUT_GL_SUFFIX_DOLLO_DOMAINS, Format.FORESTER );
441 SurfacingUtil.writeMatrixToFile( domain_parsimony.getGainLossCountsMatrix(), outfile_name
442 + surfacing_old.PARSIMONY_OUTPUT_GL_COUNTS_SUFFIX_DOLLO_DOMAINS, Format.FORESTER );
443 SurfacingUtil.writeBinaryStatesMatrixAsListToFile( domain_parsimony.getGainLossMatrix(),
444 CharacterStateMatrix.GainLossStates.GAIN,
445 outfile_name + surfacing_old.PARSIMONY_OUTPUT_DOLLO_GAINS_D,
447 ForesterUtil.LINE_SEPARATOR,
450 .writeBinaryStatesMatrixAsListToFile( domain_parsimony.getGainLossMatrix(),
451 CharacterStateMatrix.GainLossStates.LOSS,
452 outfile_name + surfacing_old.PARSIMONY_OUTPUT_DOLLO_LOSSES_D,
454 ForesterUtil.LINE_SEPARATOR,
456 SurfacingUtil.writeBinaryStatesMatrixAsListToFile( domain_parsimony.getGainLossMatrix(), null, outfile_name
457 + surfacing_old.PARSIMONY_OUTPUT_DOLLO_PRESENT_D, sep, ForesterUtil.LINE_SEPARATOR, null );
459 writeBinaryStatesMatrixToList( domain_id_to_go_ids_map,
463 domain_parsimony.getGainLossMatrix(),
464 CharacterStateMatrix.GainLossStates.GAIN,
465 outfile_name + surfacing_old.PARSIMONY_OUTPUT_DOLLO_GAINS_HTML_D,
467 ForesterUtil.LINE_SEPARATOR,
468 "Dollo Parsimony | Gains | Domains",
470 domain_id_to_secondary_features_maps,
471 all_pfams_encountered,
472 all_pfams_gained_as_domains,
474 writeBinaryStatesMatrixToList( domain_id_to_go_ids_map,
478 domain_parsimony.getGainLossMatrix(),
479 CharacterStateMatrix.GainLossStates.LOSS,
480 outfile_name + surfacing_old.PARSIMONY_OUTPUT_DOLLO_LOSSES_HTML_D,
482 ForesterUtil.LINE_SEPARATOR,
483 "Dollo Parsimony | Losses | Domains",
485 domain_id_to_secondary_features_maps,
486 all_pfams_encountered,
487 all_pfams_lost_as_domains,
489 writeBinaryStatesMatrixToList( domain_id_to_go_ids_map,
493 domain_parsimony.getGainLossMatrix(),
495 outfile_name + surfacing_old.PARSIMONY_OUTPUT_DOLLO_PRESENT_HTML_D,
497 ForesterUtil.LINE_SEPARATOR,
498 "Dollo Parsimony | Present | Domains",
500 domain_id_to_secondary_features_maps,
501 all_pfams_encountered,
503 "_dollo_present_d" );
504 preparePhylogeny( local_phylogeny_l,
507 "Dollo parsimony on domain presence/absence",
508 "dollo_on_domains_" + outfile_name,
510 SurfacingUtil.writePhylogenyToFile( local_phylogeny_l, outfile_name
511 + surfacing_old.DOMAINS_PARSIMONY_TREE_OUTPUT_SUFFIX_DOLLO );
513 writeAllDomainsChangedOnAllSubtrees( local_phylogeny_l, true, outfile_name, "_dollo_all_gains_d" );
514 writeAllDomainsChangedOnAllSubtrees( local_phylogeny_l, false, outfile_name, "_dollo_all_losses_d" );
516 catch ( final IOException e ) {
518 ForesterUtil.fatalError( surfacing_old.PRG_NAME, e.getLocalizedMessage() );
520 if ( domain_parsimony.calculateNumberOfBinaryDomainCombination() > 0 ) {
521 // FITCH DOMAIN COMBINATIONS
522 // -------------------------
523 local_phylogeny_l = phylogeny.copy();
524 String randomization = "no";
525 if ( radomize_fitch_parsimony ) {
526 domain_parsimony.executeFitchParsimonyOnBinaryDomainCombintion( random_number_seed_for_fitch_parsimony );
527 randomization = "yes, seed = " + random_number_seed_for_fitch_parsimony;
530 domain_parsimony.executeFitchParsimonyOnBinaryDomainCombintion( false );
532 SurfacingUtil.writeMatrixToFile( domain_parsimony.getGainLossMatrix(), outfile_name
533 + surfacing_old.PARSIMONY_OUTPUT_GL_SUFFIX_FITCH_BINARY_COMBINATIONS, Format.FORESTER );
534 SurfacingUtil.writeMatrixToFile( domain_parsimony.getGainLossCountsMatrix(), outfile_name
535 + surfacing_old.PARSIMONY_OUTPUT_GL_COUNTS_SUFFIX_FITCH_BINARY_COMBINATIONS, Format.FORESTER );
536 SurfacingUtil.writeBinaryStatesMatrixAsListToFile( domain_parsimony.getGainLossMatrix(),
537 CharacterStateMatrix.GainLossStates.GAIN,
539 + surfacing_old.PARSIMONY_OUTPUT_FITCH_GAINS_BC,
541 ForesterUtil.LINE_SEPARATOR,
544 .writeBinaryStatesMatrixAsListToFile( domain_parsimony.getGainLossMatrix(),
545 CharacterStateMatrix.GainLossStates.LOSS,
546 outfile_name + surfacing_old.PARSIMONY_OUTPUT_FITCH_LOSSES_BC,
548 ForesterUtil.LINE_SEPARATOR,
550 SurfacingUtil.writeBinaryStatesMatrixAsListToFile( domain_parsimony.getGainLossMatrix(), null, outfile_name
551 + surfacing_old.PARSIMONY_OUTPUT_FITCH_PRESENT_BC, sep, ForesterUtil.LINE_SEPARATOR, null );
552 if ( all_binary_domains_combination_gained_fitch != null ) {
553 collectChangedDomainCombinationsFromBinaryStatesMatrixAsListToFile( domain_parsimony.getGainLossMatrix(),
555 all_binary_domains_combination_gained_fitch,
558 if ( all_binary_domains_combination_lost_fitch != null ) {
559 collectChangedDomainCombinationsFromBinaryStatesMatrixAsListToFile( domain_parsimony.getGainLossMatrix(),
561 all_binary_domains_combination_lost_fitch,
564 if ( output_binary_domain_combinations_for_graphs ) {
566 .writeBinaryStatesMatrixAsListToFileForBinaryCombinationsForGraphAnalysis( domain_parsimony
567 .getGainLossMatrix(),
570 + surfacing_old.PARSIMONY_OUTPUT_FITCH_PRESENT_BC_OUTPUTFILE_SUFFIX_FOR_GRAPH_ANALYSIS,
572 ForesterUtil.LINE_SEPARATOR,
573 BinaryDomainCombination.OutputFormat.DOT );
576 writeBinaryStatesMatrixToList( domain_id_to_go_ids_map,
580 domain_parsimony.getGainLossMatrix(),
581 CharacterStateMatrix.GainLossStates.GAIN,
582 outfile_name + surfacing_old.PARSIMONY_OUTPUT_FITCH_GAINS_HTML_BC,
584 ForesterUtil.LINE_SEPARATOR,
585 "Fitch Parsimony | Gains | Domain Combinations",
588 all_pfams_encountered,
589 all_pfams_gained_as_dom_combinations,
591 writeBinaryStatesMatrixToList( domain_id_to_go_ids_map,
595 domain_parsimony.getGainLossMatrix(),
596 CharacterStateMatrix.GainLossStates.LOSS,
597 outfile_name + surfacing_old.PARSIMONY_OUTPUT_FITCH_LOSSES_HTML_BC,
599 ForesterUtil.LINE_SEPARATOR,
600 "Fitch Parsimony | Losses | Domain Combinations",
603 all_pfams_encountered,
604 all_pfams_lost_as_dom_combinations,
605 "_fitch_losses_dc" );
606 writeBinaryStatesMatrixToList( domain_id_to_go_ids_map,
610 domain_parsimony.getGainLossMatrix(),
612 outfile_name + surfacing_old.PARSIMONY_OUTPUT_FITCH_PRESENT_HTML_BC,
614 ForesterUtil.LINE_SEPARATOR,
615 "Fitch Parsimony | Present | Domain Combinations",
618 all_pfams_encountered,
620 "_fitch_present_dc" );
621 writeAllEncounteredPfamsToFile( domain_id_to_go_ids_map,
624 all_pfams_encountered );
625 writePfamsToFile( outfile_name + surfacing_old.ALL_PFAMS_GAINED_AS_DOMAINS_SUFFIX,
626 all_pfams_gained_as_domains );
627 writePfamsToFile( outfile_name + surfacing_old.ALL_PFAMS_LOST_AS_DOMAINS_SUFFIX, all_pfams_lost_as_domains );
628 writePfamsToFile( outfile_name + surfacing_old.ALL_PFAMS_GAINED_AS_DC_SUFFIX,
629 all_pfams_gained_as_dom_combinations );
630 writePfamsToFile( outfile_name + surfacing_old.ALL_PFAMS_LOST_AS_DC_SUFFIX,
631 all_pfams_lost_as_dom_combinations );
632 preparePhylogeny( local_phylogeny_l,
635 "Fitch parsimony on binary domain combination presence/absence randomization: "
637 "fitch_on_binary_domain_combinations_" + outfile_name,
639 SurfacingUtil.writePhylogenyToFile( local_phylogeny_l, outfile_name
640 + surfacing_old.BINARY_DOMAIN_COMBINATIONS_PARSIMONY_TREE_OUTPUT_SUFFIX_FITCH );
644 public static void executeParsimonyAnalysisForSecondaryFeatures( final String outfile_name,
645 final DomainParsimonyCalculator secondary_features_parsimony,
646 final Phylogeny phylogeny,
647 final String parameters_str,
648 final Map<Species, MappingResults> mapping_results_map ) {
649 final String sep = ForesterUtil.LINE_SEPARATOR + "###################" + ForesterUtil.LINE_SEPARATOR;
650 final String date_time = ForesterUtil.getCurrentDateTime();
651 System.out.println();
652 writeToNexus( outfile_name + surfacing_old.NEXUS_SECONDARY_FEATURES,
653 secondary_features_parsimony.createMatrixOfSecondaryFeaturePresenceOrAbsence( null ),
655 final Phylogeny local_phylogeny_copy = phylogeny.copy();
656 secondary_features_parsimony.executeDolloParsimonyOnSecondaryFeatures( mapping_results_map );
657 SurfacingUtil.writeMatrixToFile( secondary_features_parsimony.getGainLossMatrix(), outfile_name
658 + surfacing_old.PARSIMONY_OUTPUT_GL_SUFFIX_DOLLO_SECONDARY_FEATURES, Format.FORESTER );
659 SurfacingUtil.writeMatrixToFile( secondary_features_parsimony.getGainLossCountsMatrix(), outfile_name
660 + surfacing_old.PARSIMONY_OUTPUT_GL_COUNTS_SUFFIX_DOLLO_SECONDARY_FEATURES, Format.FORESTER );
662 .writeBinaryStatesMatrixAsListToFile( secondary_features_parsimony.getGainLossMatrix(),
663 CharacterStateMatrix.GainLossStates.GAIN,
665 + surfacing_old.PARSIMONY_OUTPUT_DOLLO_GAINS_SECONDARY_FEATURES,
667 ForesterUtil.LINE_SEPARATOR,
670 .writeBinaryStatesMatrixAsListToFile( secondary_features_parsimony.getGainLossMatrix(),
671 CharacterStateMatrix.GainLossStates.LOSS,
673 + surfacing_old.PARSIMONY_OUTPUT_DOLLO_LOSSES_SECONDARY_FEATURES,
675 ForesterUtil.LINE_SEPARATOR,
678 .writeBinaryStatesMatrixAsListToFile( secondary_features_parsimony.getGainLossMatrix(),
681 + surfacing_old.PARSIMONY_OUTPUT_DOLLO_PRESENT_SECONDARY_FEATURES,
683 ForesterUtil.LINE_SEPARATOR,
685 preparePhylogeny( local_phylogeny_copy,
686 secondary_features_parsimony,
688 "Dollo parsimony on secondary feature presence/absence",
689 "dollo_on_secondary_features_" + outfile_name,
691 SurfacingUtil.writePhylogenyToFile( local_phylogeny_copy, outfile_name
692 + surfacing_old.SECONDARY_FEATURES_PARSIMONY_TREE_OUTPUT_SUFFIX_DOLLO );
695 public static void extractProteinNames( final List<Protein> proteins,
696 final List<DomainId> query_domain_ids_nc_order,
698 final String separator ) throws IOException {
699 for( final Protein protein : proteins ) {
700 if ( protein.contains( query_domain_ids_nc_order, true ) ) {
701 out.write( protein.getSpecies().getSpeciesId() );
702 out.write( separator );
703 out.write( protein.getProteinId().getId() );
704 out.write( separator );
706 final Set<DomainId> visited_domain_ids = new HashSet<DomainId>();
707 boolean first = true;
708 for( final Domain domain : protein.getProteinDomains() ) {
709 if ( !visited_domain_ids.contains( domain.getDomainId() ) ) {
710 visited_domain_ids.add( domain.getDomainId() );
717 out.write( domain.getDomainId().getId() );
719 out.write( "" + domain.getTotalCount() );
724 out.write( separator );
725 if ( !( ForesterUtil.isEmpty( protein.getDescription() ) || protein.getDescription()
726 .equals( SurfacingConstants.NONE ) ) ) {
727 out.write( protein.getDescription() );
729 out.write( separator );
730 if ( !( ForesterUtil.isEmpty( protein.getAccession() ) || protein.getAccession()
731 .equals( SurfacingConstants.NONE ) ) ) {
732 out.write( protein.getAccession() );
734 out.write( SurfacingConstants.NL );
740 public static void extractProteinNames( final SortedMap<Species, List<Protein>> protein_lists_per_species,
741 final DomainId domain_id,
743 final String separator ) throws IOException {
744 for( final Species species : protein_lists_per_species.keySet() ) {
745 for( final Protein protein : protein_lists_per_species.get( species ) ) {
746 final List<Domain> domains = protein.getProteinDomains( domain_id );
747 if ( domains.size() > 0 ) {
748 final DescriptiveStatistics stats = new BasicDescriptiveStatistics();
749 for( final Domain domain : domains ) {
750 stats.addValue( domain.getPerSequenceEvalue() );
752 out.write( protein.getSpecies().getSpeciesId() );
753 out.write( separator );
754 out.write( protein.getProteinId().getId() );
755 out.write( separator );
756 out.write( "[" + FORMATTER.format( stats.median() ) + "]" );
757 out.write( separator );
758 if ( !( ForesterUtil.isEmpty( protein.getDescription() ) || protein.getDescription()
759 .equals( SurfacingConstants.NONE ) ) ) {
760 out.write( protein.getDescription() );
762 out.write( separator );
763 if ( !( ForesterUtil.isEmpty( protein.getAccession() ) || protein.getAccession()
764 .equals( SurfacingConstants.NONE ) ) ) {
765 out.write( protein.getAccession() );
767 out.write( SurfacingConstants.NL );
774 public static SortedSet<DomainId> getAllDomainIds( final List<GenomeWideCombinableDomains> gwcd_list ) {
775 final SortedSet<DomainId> all_domains_ids = new TreeSet<DomainId>();
776 for( final GenomeWideCombinableDomains gwcd : gwcd_list ) {
777 final Set<DomainId> all_domains = gwcd.getAllDomainIds();
778 // for( final Domain domain : all_domains ) {
779 all_domains_ids.addAll( all_domains );
782 return all_domains_ids;
785 public static SortedMap<String, Integer> getDomainCounts( final List<Protein> protein_domain_collections ) {
786 final SortedMap<String, Integer> map = new TreeMap<String, Integer>();
787 for( final Protein protein_domain_collection : protein_domain_collections ) {
788 for( final Object name : protein_domain_collection.getProteinDomains() ) {
789 final BasicDomain protein_domain = ( BasicDomain ) name;
790 final String id = protein_domain.getDomainId().getId();
791 if ( map.containsKey( id ) ) {
792 map.put( id, map.get( id ) + 1 );
802 public static int getNumberOfNodesLackingName( final Phylogeny p, final StringBuilder names ) {
803 final PhylogenyNodeIterator it = p.iteratorPostorder();
805 while ( it.hasNext() ) {
806 final PhylogenyNode n = it.next();
807 if ( ForesterUtil.isEmpty( n.getName() )
808 && ( !n.getNodeData().isHasTaxonomy() || ForesterUtil.isEmpty( n.getNodeData().getTaxonomy()
809 .getScientificName() ) ) ) {
810 if ( n.getParent() != null ) {
812 names.append( n.getParent().getName() );
821 * Returns true is Domain domain falls in an uninterrupted stretch of
825 * @param covered_positions
828 public static boolean isEngulfed( final Domain domain, final List<Boolean> covered_positions ) {
829 for( int i = domain.getFrom(); i <= domain.getTo(); ++i ) {
830 if ( ( i >= covered_positions.size() ) || ( covered_positions.get( i ) != true ) ) {
837 public static void preparePhylogeny( final Phylogeny p,
838 final DomainParsimonyCalculator domain_parsimony,
839 final String date_time,
842 final String parameters_str ) {
843 domain_parsimony.decoratePhylogenyWithDomains( p );
844 final StringBuilder desc = new StringBuilder();
845 desc.append( "[Method: " + method + "] [Date: " + date_time + "] " );
846 desc.append( "[Cost: " + domain_parsimony.getCost() + "] " );
847 desc.append( "[Gains: " + domain_parsimony.getTotalGains() + "] " );
848 desc.append( "[Losses: " + domain_parsimony.getTotalLosses() + "] " );
849 desc.append( "[Unchanged: " + domain_parsimony.getTotalUnchanged() + "] " );
850 desc.append( "[Parameters: " + parameters_str + "]" );
852 p.setDescription( desc.toString() );
853 p.setConfidence( new Confidence( domain_parsimony.getCost(), "parsimony" ) );
854 p.setRerootable( false );
860 * Example regarding engulfment: ------------0.1 ----------0.2 --0.3 =>
861 * domain with 0.3 is ignored
863 * -----------0.1 ----------0.2 --0.3 => domain with 0.3 is ignored
866 * ------------0.1 ----------0.3 --0.2 => domains with 0.3 and 0.2 are _not_
869 * @param max_allowed_overlap
870 * maximal allowed overlap (inclusive) to be still considered not
871 * overlapping (zero or negative value to allow any overlap)
872 * @param remove_engulfed_domains
873 * to remove domains which are completely engulfed by coverage of
874 * domains with better support
878 public static Protein removeOverlappingDomains( final int max_allowed_overlap,
879 final boolean remove_engulfed_domains,
880 final Protein protein ) {
881 final Protein pruned_protein = new BasicProtein( protein.getProteinId().getId(), protein.getSpecies()
883 final List<Domain> sorted = SurfacingUtil.sortDomainsWithAscendingConfidenceValues( protein );
884 final List<Boolean> covered_positions = new ArrayList<Boolean>();
885 for( final Domain domain : sorted ) {
886 if ( ( ( max_allowed_overlap < 0 ) || ( SurfacingUtil.calculateOverlap( domain, covered_positions ) <= max_allowed_overlap ) )
887 && ( !remove_engulfed_domains || !isEngulfed( domain, covered_positions ) ) ) {
888 final int covered_positions_size = covered_positions.size();
889 for( int i = covered_positions_size; i < domain.getFrom(); ++i ) {
890 covered_positions.add( false );
892 final int new_covered_positions_size = covered_positions.size();
893 for( int i = domain.getFrom(); i <= domain.getTo(); ++i ) {
894 if ( i < new_covered_positions_size ) {
895 covered_positions.set( i, true );
898 covered_positions.add( true );
901 pruned_protein.addProteinDomain( domain );
904 return pruned_protein;
907 static List<Domain> sortDomainsWithAscendingConfidenceValues( final Protein protein ) {
908 final List<Domain> domains = new ArrayList<Domain>();
909 for( final Domain d : protein.getProteinDomains() ) {
912 Collections.sort( domains, SurfacingUtil.ASCENDING_CONFIDENCE_VALUE_ORDER );
916 public static void writeAllDomainsChangedOnAllSubtrees( final Phylogeny p,
917 final boolean get_gains,
919 final String suffix_for_filename ) throws IOException {
920 CharacterStateMatrix.GainLossStates state = CharacterStateMatrix.GainLossStates.GAIN;
922 state = CharacterStateMatrix.GainLossStates.LOSS;
924 final File base_dir = createBaseDirForPerNodeDomainFiles( surfacing_old.BASE_DIRECTORY_PER_SUBTREE_DOMAIN_GAIN_LOSS_FILES,
928 for( final PhylogenyNodeIterator it = p.iteratorPostorder(); it.hasNext(); ) {
929 final PhylogenyNode node = it.next();
930 if ( !node.isExternal() ) {
931 final SortedSet<String> domains = collectAllDomainsChangedOnSubtree( node, get_gains );
932 if ( domains.size() > 0 ) {
933 final Writer writer = ForesterUtil.createBufferedWriter( base_dir + ForesterUtil.FILE_SEPARATOR
934 + node.getName() + suffix_for_filename );
935 for( final String domain : domains ) {
936 writer.write( domain );
937 writer.write( ForesterUtil.LINE_SEPARATOR );
945 private static void writeAllEncounteredPfamsToFile( final Map<DomainId, List<GoId>> domain_id_to_go_ids_map,
946 final Map<GoId, GoTerm> go_id_to_term_map,
947 final String outfile_name,
948 final SortedSet<String> all_pfams_encountered ) {
949 final File all_pfams_encountered_file = new File( outfile_name + surfacing_old.ALL_PFAMS_ENCOUNTERED_SUFFIX );
950 final File all_pfams_encountered_with_go_annotation_file = new File( outfile_name
951 + surfacing_old.ALL_PFAMS_ENCOUNTERED_WITH_GO_ANNOTATION_SUFFIX );
952 final File encountered_pfams_summary_file = new File( outfile_name
953 + surfacing_old.ENCOUNTERED_PFAMS_SUMMARY_SUFFIX );
954 int biological_process_counter = 0;
955 int cellular_component_counter = 0;
956 int molecular_function_counter = 0;
957 int pfams_with_mappings_counter = 0;
958 int pfams_without_mappings_counter = 0;
959 int pfams_without_mappings_to_bp_or_mf_counter = 0;
960 int pfams_with_mappings_to_bp_or_mf_counter = 0;
962 final Writer all_pfams_encountered_writer = new BufferedWriter( new FileWriter( all_pfams_encountered_file ) );
963 final Writer all_pfams_encountered_with_go_annotation_writer = new BufferedWriter( new FileWriter( all_pfams_encountered_with_go_annotation_file ) );
964 final Writer summary_writer = new BufferedWriter( new FileWriter( encountered_pfams_summary_file ) );
965 summary_writer.write( "# Pfam to GO mapping summary" );
966 summary_writer.write( ForesterUtil.LINE_SEPARATOR );
967 summary_writer.write( "# Actual summary is at the end of this file." );
968 summary_writer.write( ForesterUtil.LINE_SEPARATOR );
969 summary_writer.write( "# Encountered Pfams without a GO mapping:" );
970 summary_writer.write( ForesterUtil.LINE_SEPARATOR );
971 for( final String pfam : all_pfams_encountered ) {
972 all_pfams_encountered_writer.write( pfam );
973 all_pfams_encountered_writer.write( ForesterUtil.LINE_SEPARATOR );
974 final DomainId domain_id = new DomainId( pfam );
975 if ( domain_id_to_go_ids_map.containsKey( domain_id ) ) {
976 ++pfams_with_mappings_counter;
977 all_pfams_encountered_with_go_annotation_writer.write( pfam );
978 all_pfams_encountered_with_go_annotation_writer.write( ForesterUtil.LINE_SEPARATOR );
979 final List<GoId> go_ids = domain_id_to_go_ids_map.get( domain_id );
980 boolean maps_to_bp = false;
981 boolean maps_to_cc = false;
982 boolean maps_to_mf = false;
983 for( final GoId go_id : go_ids ) {
984 final GoTerm go_term = go_id_to_term_map.get( go_id );
985 if ( go_term.getGoNameSpace().isBiologicalProcess() ) {
988 else if ( go_term.getGoNameSpace().isCellularComponent() ) {
991 else if ( go_term.getGoNameSpace().isMolecularFunction() ) {
996 ++biological_process_counter;
999 ++cellular_component_counter;
1002 ++molecular_function_counter;
1004 if ( maps_to_bp || maps_to_mf ) {
1005 ++pfams_with_mappings_to_bp_or_mf_counter;
1008 ++pfams_without_mappings_to_bp_or_mf_counter;
1012 ++pfams_without_mappings_to_bp_or_mf_counter;
1013 ++pfams_without_mappings_counter;
1014 summary_writer.write( pfam );
1015 summary_writer.write( ForesterUtil.LINE_SEPARATOR );
1018 all_pfams_encountered_writer.close();
1019 all_pfams_encountered_with_go_annotation_writer.close();
1020 ForesterUtil.programMessage( surfacing_old.PRG_NAME, "Wrote all [" + all_pfams_encountered.size()
1021 + "] encountered Pfams to: \"" + all_pfams_encountered_file + "\"" );
1022 ForesterUtil.programMessage( surfacing_old.PRG_NAME, "Wrote all [" + pfams_with_mappings_counter
1023 + "] encountered Pfams with GO mappings to: \"" + all_pfams_encountered_with_go_annotation_file
1025 ForesterUtil.programMessage( surfacing_old.PRG_NAME, "Wrote summary (including all ["
1026 + pfams_without_mappings_counter + "] encountered Pfams without GO mappings) to: \""
1027 + encountered_pfams_summary_file + "\"" );
1028 ForesterUtil.programMessage( surfacing_old.PRG_NAME, "Sum of Pfams encountered : "
1029 + all_pfams_encountered.size() );
1030 ForesterUtil.programMessage( surfacing_old.PRG_NAME, "Pfams without a mapping : "
1031 + pfams_without_mappings_counter + " ["
1032 + ( 100 * pfams_without_mappings_counter / all_pfams_encountered.size() ) + "%]" );
1033 ForesterUtil.programMessage( surfacing_old.PRG_NAME, "Pfams without mapping to proc. or func. : "
1034 + pfams_without_mappings_to_bp_or_mf_counter + " ["
1035 + ( 100 * pfams_without_mappings_to_bp_or_mf_counter / all_pfams_encountered.size() ) + "%]" );
1036 ForesterUtil.programMessage( surfacing_old.PRG_NAME,
1037 "Pfams with a mapping : " + pfams_with_mappings_counter
1039 + ( 100 * pfams_with_mappings_counter / all_pfams_encountered.size() )
1041 ForesterUtil.programMessage( surfacing_old.PRG_NAME, "Pfams with a mapping to proc. or func. : "
1042 + pfams_with_mappings_to_bp_or_mf_counter + " ["
1043 + ( 100 * pfams_with_mappings_to_bp_or_mf_counter / all_pfams_encountered.size() ) + "%]" );
1044 ForesterUtil.programMessage( surfacing_old.PRG_NAME,
1045 "Pfams with mapping to biological process: " + biological_process_counter
1047 + ( 100 * biological_process_counter / all_pfams_encountered.size() )
1049 ForesterUtil.programMessage( surfacing_old.PRG_NAME,
1050 "Pfams with mapping to molecular function: " + molecular_function_counter
1052 + ( 100 * molecular_function_counter / all_pfams_encountered.size() )
1054 ForesterUtil.programMessage( surfacing_old.PRG_NAME,
1055 "Pfams with mapping to cellular component: " + cellular_component_counter
1057 + ( 100 * cellular_component_counter / all_pfams_encountered.size() )
1059 summary_writer.write( ForesterUtil.LINE_SEPARATOR );
1060 summary_writer.write( "# Sum of Pfams encountered : " + all_pfams_encountered.size() );
1061 summary_writer.write( ForesterUtil.LINE_SEPARATOR );
1062 summary_writer.write( "# Pfams without a mapping : " + pfams_without_mappings_counter
1063 + " [" + ( 100 * pfams_without_mappings_counter / all_pfams_encountered.size() ) + "%]" );
1064 summary_writer.write( ForesterUtil.LINE_SEPARATOR );
1065 summary_writer.write( "# Pfams without mapping to proc. or func. : "
1066 + pfams_without_mappings_to_bp_or_mf_counter + " ["
1067 + ( 100 * pfams_without_mappings_to_bp_or_mf_counter / all_pfams_encountered.size() ) + "%]" );
1068 summary_writer.write( ForesterUtil.LINE_SEPARATOR );
1069 summary_writer.write( "# Pfams with a mapping : " + pfams_with_mappings_counter + " ["
1070 + ( 100 * pfams_with_mappings_counter / all_pfams_encountered.size() ) + "%]" );
1071 summary_writer.write( ForesterUtil.LINE_SEPARATOR );
1072 summary_writer.write( "# Pfams with a mapping to proc. or func. : "
1073 + pfams_with_mappings_to_bp_or_mf_counter + " ["
1074 + ( 100 * pfams_with_mappings_to_bp_or_mf_counter / all_pfams_encountered.size() ) + "%]" );
1075 summary_writer.write( ForesterUtil.LINE_SEPARATOR );
1076 summary_writer.write( "# Pfams with mapping to biological process: " + biological_process_counter + " ["
1077 + ( 100 * biological_process_counter / all_pfams_encountered.size() ) + "%]" );
1078 summary_writer.write( ForesterUtil.LINE_SEPARATOR );
1079 summary_writer.write( "# Pfams with mapping to molecular function: " + molecular_function_counter + " ["
1080 + ( 100 * molecular_function_counter / all_pfams_encountered.size() ) + "%]" );
1081 summary_writer.write( ForesterUtil.LINE_SEPARATOR );
1082 summary_writer.write( "# Pfams with mapping to cellular component: " + cellular_component_counter + " ["
1083 + ( 100 * cellular_component_counter / all_pfams_encountered.size() ) + "%]" );
1084 summary_writer.write( ForesterUtil.LINE_SEPARATOR );
1085 summary_writer.close();
1087 catch ( final IOException e ) {
1088 ForesterUtil.printWarningMessage( surfacing_old.PRG_NAME, "Failure to write: " + e );
1092 public static void writeBinaryDomainCombinationsFileForGraphAnalysis( final String[][] input_file_properties,
1093 final File output_dir,
1094 final GenomeWideCombinableDomains gwcd,
1096 final GenomeWideCombinableDomainsSortOrder dc_sort_order ) {
1097 File dc_outfile_dot = new File( input_file_properties[ i ][ 0 ]
1098 + surfacing_old.DOMAIN_COMBINITONS_OUTPUTFILE_SUFFIX_FOR_GRAPH_ANALYSIS );
1099 if ( output_dir != null ) {
1100 dc_outfile_dot = new File( output_dir + ForesterUtil.FILE_SEPARATOR + dc_outfile_dot );
1102 checkForOutputFileWriteability( dc_outfile_dot );
1103 final SortedSet<BinaryDomainCombination> binary_combinations = createSetOfAllBinaryDomainCombinationsPerGenome( gwcd );
1105 final BufferedWriter out_dot = new BufferedWriter( new FileWriter( dc_outfile_dot ) );
1106 for( final BinaryDomainCombination bdc : binary_combinations ) {
1107 out_dot.write( bdc.toGraphDescribingLanguage( BinaryDomainCombination.OutputFormat.DOT, null, null )
1109 out_dot.write( SurfacingConstants.NL );
1113 catch ( final IOException e ) {
1114 ForesterUtil.fatalError( surfacing_old.PRG_NAME, e.getMessage() );
1116 ForesterUtil.programMessage( surfacing_old.PRG_NAME, "Wrote binary domain combination for \""
1117 + input_file_properties[ i ][ 0 ] + "\" (" + input_file_properties[ i ][ 1 ] + ", "
1118 + input_file_properties[ i ][ 2 ] + ") to: \"" + dc_outfile_dot + "\"" );
1122 * species | protein id | n-terminal domain | c-terminal domain | n-terminal domain per domain E-value | c-terminal domain per domain E-value
1126 static public StringBuffer proteinToDomainCombinations( final Protein protein,
1127 final String protein_id,
1128 final String separator ) {
1129 final StringBuffer sb = new StringBuffer();
1130 if ( protein.getSpecies() == null ) {
1131 throw new IllegalArgumentException( "species must not be null" );
1133 if ( ForesterUtil.isEmpty( protein.getSpecies().getSpeciesId() ) ) {
1134 throw new IllegalArgumentException( "species id must not be empty" );
1136 final List<Domain> domains = protein.getProteinDomains();
1137 if ( domains.size() > 1 ) {
1138 final Map<String, Integer> counts = new HashMap<String, Integer>();
1139 for( final Domain domain : domains ) {
1140 final String id = domain.getDomainId().getId();
1141 if ( counts.containsKey( id ) ) {
1142 counts.put( id, counts.get( id ) + 1 );
1145 counts.put( id, 1 );
1148 for( int i = 1; i < domains.size(); ++i ) {
1149 for( int j = 0; j < i; ++j ) {
1150 Domain domain_n = domains.get( i );
1151 Domain domain_c = domains.get( j );
1152 if ( domain_n.getFrom() > domain_c.getFrom() ) {
1153 domain_n = domains.get( j );
1154 domain_c = domains.get( i );
1156 sb.append( protein.getSpecies() );
1157 sb.append( separator );
1158 sb.append( protein_id );
1159 sb.append( separator );
1160 sb.append( domain_n.getDomainId().getId() );
1161 sb.append( separator );
1162 sb.append( domain_c.getDomainId().getId() );
1163 sb.append( separator );
1164 sb.append( domain_n.getPerDomainEvalue() );
1165 sb.append( separator );
1166 sb.append( domain_c.getPerDomainEvalue() );
1167 sb.append( separator );
1168 sb.append( counts.get( domain_n.getDomainId().getId() ) );
1169 sb.append( separator );
1170 sb.append( counts.get( domain_c.getDomainId().getId() ) );
1171 sb.append( ForesterUtil.LINE_SEPARATOR );
1175 else if ( domains.size() == 1 ) {
1176 sb.append( protein.getSpecies() );
1177 sb.append( separator );
1178 sb.append( protein_id );
1179 sb.append( separator );
1180 sb.append( domains.get( 0 ).getDomainId().getId() );
1181 sb.append( separator );
1182 sb.append( separator );
1183 sb.append( domains.get( 0 ).getPerDomainEvalue() );
1184 sb.append( separator );
1185 sb.append( separator );
1187 sb.append( separator );
1188 sb.append( ForesterUtil.LINE_SEPARATOR );
1191 sb.append( protein.getSpecies() );
1192 sb.append( separator );
1193 sb.append( protein_id );
1194 sb.append( separator );
1195 sb.append( separator );
1196 sb.append( separator );
1197 sb.append( separator );
1198 sb.append( separator );
1199 sb.append( separator );
1200 sb.append( ForesterUtil.LINE_SEPARATOR );
1205 public static void writeBinaryStatesMatrixAsListToFile( final CharacterStateMatrix<CharacterStateMatrix.GainLossStates> matrix,
1206 final CharacterStateMatrix.GainLossStates state,
1207 final String filename,
1208 final String indentifier_characters_separator,
1209 final String character_separator,
1210 final Map<String, String> descriptions ) {
1211 final File outfile = new File( filename );
1212 checkForOutputFileWriteability( outfile );
1213 final SortedSet<String> sorted_ids = new TreeSet<String>();
1214 for( int i = 0; i < matrix.getNumberOfIdentifiers(); ++i ) {
1215 sorted_ids.add( matrix.getIdentifier( i ) );
1218 final BufferedWriter out = new BufferedWriter( new FileWriter( outfile ) );
1219 for( final String id : sorted_ids ) {
1220 out.write( indentifier_characters_separator );
1221 out.write( "#" + id );
1222 out.write( indentifier_characters_separator );
1223 for( int c = 0; c < matrix.getNumberOfCharacters(); ++c ) {
1225 // using null to indicate either UNCHANGED_PRESENT or GAIN.
1226 if ( ( matrix.getState( id, c ) == state )
1227 || ( ( state == null ) && ( ( matrix.getState( id, c ) == CharacterStateMatrix.GainLossStates.GAIN ) || ( matrix
1228 .getState( id, c ) == CharacterStateMatrix.GainLossStates.UNCHANGED_PRESENT ) ) ) ) {
1229 out.write( matrix.getCharacter( c ) );
1230 if ( ( descriptions != null ) && !descriptions.isEmpty()
1231 && descriptions.containsKey( matrix.getCharacter( c ) ) ) {
1233 out.write( descriptions.get( matrix.getCharacter( c ) ) );
1235 out.write( character_separator );
1242 catch ( final IOException e ) {
1243 ForesterUtil.fatalError( surfacing_old.PRG_NAME, e.getMessage() );
1245 ForesterUtil.programMessage( surfacing_old.PRG_NAME, "Wrote characters list: \"" + filename + "\"" );
1248 public static void writeBinaryStatesMatrixAsListToFileForBinaryCombinationsForGraphAnalysis( final CharacterStateMatrix<CharacterStateMatrix.GainLossStates> matrix,
1249 final CharacterStateMatrix.GainLossStates state,
1250 final String filename,
1251 final String indentifier_characters_separator,
1252 final String character_separator,
1253 final BinaryDomainCombination.OutputFormat bc_output_format ) {
1254 final File outfile = new File( filename );
1255 checkForOutputFileWriteability( outfile );
1256 final SortedSet<String> sorted_ids = new TreeSet<String>();
1257 for( int i = 0; i < matrix.getNumberOfIdentifiers(); ++i ) {
1258 sorted_ids.add( matrix.getIdentifier( i ) );
1261 final BufferedWriter out = new BufferedWriter( new FileWriter( outfile ) );
1262 for( final String id : sorted_ids ) {
1263 out.write( indentifier_characters_separator );
1264 out.write( "#" + id );
1265 out.write( indentifier_characters_separator );
1266 for( int c = 0; c < matrix.getNumberOfCharacters(); ++c ) {
1268 // using null to indicate either UNCHANGED_PRESENT or GAIN.
1269 if ( ( matrix.getState( id, c ) == state )
1270 || ( ( state == null ) && ( ( matrix.getState( id, c ) == CharacterStateMatrix.GainLossStates.GAIN ) || ( matrix
1271 .getState( id, c ) == CharacterStateMatrix.GainLossStates.UNCHANGED_PRESENT ) ) ) ) {
1272 BinaryDomainCombination bdc = null;
1274 bdc = BasicBinaryDomainCombination.createInstance( matrix.getCharacter( c ) );
1276 catch ( final Exception e ) {
1277 ForesterUtil.fatalError( surfacing_old.PRG_NAME, e.getLocalizedMessage() );
1279 out.write( bdc.toGraphDescribingLanguage( bc_output_format, null, null ).toString() );
1280 out.write( character_separator );
1287 catch ( final IOException e ) {
1288 ForesterUtil.fatalError( surfacing_old.PRG_NAME, e.getMessage() );
1290 ForesterUtil.programMessage( surfacing_old.PRG_NAME, "Wrote characters list: \"" + filename + "\"" );
1293 public static void writeBinaryStatesMatrixToList( final Map<DomainId, List<GoId>> domain_id_to_go_ids_map,
1294 final Map<GoId, GoTerm> go_id_to_term_map,
1295 final GoNameSpace go_namespace_limit,
1296 final boolean domain_combinations,
1297 final CharacterStateMatrix<CharacterStateMatrix.GainLossStates> matrix,
1298 final CharacterStateMatrix.GainLossStates state,
1299 final String filename,
1300 final String indentifier_characters_separator,
1301 final String character_separator,
1302 final String title_for_html,
1303 final String prefix_for_html,
1304 final Map<DomainId, Set<String>>[] domain_id_to_secondary_features_maps,
1305 final SortedSet<String> all_pfams_encountered,
1306 final SortedSet<String> pfams_gained_or_lost,
1307 final String suffix_for_per_node_events_file ) {
1308 if ( ( go_namespace_limit != null ) && ( ( go_id_to_term_map == null ) || ( go_id_to_term_map.size() < 1 ) ) ) {
1309 throw new IllegalArgumentException( "attempt to use GO namespace limit without a GO-id to term map" );
1311 else if ( ( ( domain_id_to_go_ids_map == null ) || ( domain_id_to_go_ids_map.size() < 1 ) ) ) {
1312 throw new IllegalArgumentException( "attempt to output detailed HTML without a Pfam to GO map" );
1314 else if ( ( ( go_id_to_term_map == null ) || ( go_id_to_term_map.size() < 1 ) ) ) {
1315 throw new IllegalArgumentException( "attempt to output detailed HTML without a GO-id to term map" );
1317 final File outfile = new File( filename );
1318 checkForOutputFileWriteability( outfile );
1319 final SortedSet<String> sorted_ids = new TreeSet<String>();
1320 for( int i = 0; i < matrix.getNumberOfIdentifiers(); ++i ) {
1321 sorted_ids.add( matrix.getIdentifier( i ) );
1324 final Writer out = new BufferedWriter( new FileWriter( outfile ) );
1325 final File per_node_go_mapped_domain_gain_loss_files_base_dir = createBaseDirForPerNodeDomainFiles( surfacing_old.BASE_DIRECTORY_PER_NODE_DOMAIN_GAIN_LOSS_FILES,
1326 domain_combinations,
1329 Writer per_node_go_mapped_domain_gain_loss_outfile_writer = null;
1330 File per_node_go_mapped_domain_gain_loss_outfile = null;
1331 int per_node_counter = 0;
1332 out.write( "<html>" );
1333 out.write( SurfacingConstants.NL );
1334 addHtmlHead( out, title_for_html );
1335 out.write( SurfacingConstants.NL );
1336 out.write( "<body>" );
1337 out.write( SurfacingConstants.NL );
1338 out.write( "<h1>" );
1339 out.write( SurfacingConstants.NL );
1340 out.write( title_for_html );
1341 out.write( SurfacingConstants.NL );
1342 out.write( "</h1>" );
1343 out.write( SurfacingConstants.NL );
1344 out.write( "<table>" );
1345 out.write( SurfacingConstants.NL );
1346 for( final String id : sorted_ids ) {
1347 final Matcher matcher = PATTERN_SP_STYLE_TAXONOMY.matcher( id );
1348 if ( matcher.matches() ) {
1351 out.write( "<tr>" );
1352 out.write( "<td>" );
1353 out.write( "<a href=\"#" + id + "\">" + id + "</a>" );
1354 out.write( "</td>" );
1355 out.write( "</tr>" );
1356 out.write( SurfacingConstants.NL );
1358 out.write( "</table>" );
1359 out.write( SurfacingConstants.NL );
1360 for( final String id : sorted_ids ) {
1361 final Matcher matcher = PATTERN_SP_STYLE_TAXONOMY.matcher( id );
1362 if ( matcher.matches() ) {
1365 out.write( SurfacingConstants.NL );
1366 out.write( "<h2>" );
1367 out.write( "<a name=\"" + id + "\">" + id + "</a>" );
1368 writeTaxonomyLinks( out, id );
1369 out.write( "</h2>" );
1370 out.write( SurfacingConstants.NL );
1371 out.write( "<table>" );
1372 out.write( SurfacingConstants.NL );
1373 out.write( "<tr>" );
1374 out.write( "<td><b>" );
1375 out.write( "Pfam domain(s)" );
1376 out.write( "</b></td><td><b>" );
1377 out.write( "GO term acc" );
1378 out.write( "</b></td><td><b>" );
1379 out.write( "GO term" );
1380 out.write( "</b></td><td><b>" );
1381 out.write( "GO namespace" );
1382 out.write( "</b></td>" );
1383 out.write( "</tr>" );
1384 out.write( SurfacingConstants.NL );
1385 out.write( "</tr>" );
1386 out.write( SurfacingConstants.NL );
1387 per_node_counter = 0;
1388 if ( matrix.getNumberOfCharacters() > 0 ) {
1389 per_node_go_mapped_domain_gain_loss_outfile = new File( per_node_go_mapped_domain_gain_loss_files_base_dir
1390 + ForesterUtil.FILE_SEPARATOR + id + suffix_for_per_node_events_file );
1391 SurfacingUtil.checkForOutputFileWriteability( per_node_go_mapped_domain_gain_loss_outfile );
1392 per_node_go_mapped_domain_gain_loss_outfile_writer = ForesterUtil
1393 .createBufferedWriter( per_node_go_mapped_domain_gain_loss_outfile );
1396 per_node_go_mapped_domain_gain_loss_outfile = null;
1397 per_node_go_mapped_domain_gain_loss_outfile_writer = null;
1399 for( int c = 0; c < matrix.getNumberOfCharacters(); ++c ) {
1401 // using null to indicate either UNCHANGED_PRESENT or GAIN.
1402 if ( ( matrix.getState( id, c ) == state )
1403 || ( ( state == null ) && ( ( matrix.getState( id, c ) == CharacterStateMatrix.GainLossStates.UNCHANGED_PRESENT ) || ( matrix
1404 .getState( id, c ) == CharacterStateMatrix.GainLossStates.GAIN ) ) ) ) {
1405 final String character = matrix.getCharacter( c );
1406 String domain_0 = "";
1407 String domain_1 = "";
1408 if ( character.indexOf( BinaryDomainCombination.SEPARATOR ) > 0 ) {
1409 final String[] s = character.split( BinaryDomainCombination.SEPARATOR );
1410 if ( s.length != 2 ) {
1411 throw new AssertionError( "this should not have happened: unexpected format for domain combination: ["
1412 + character + "]" );
1418 domain_0 = character;
1420 writeDomainData( domain_id_to_go_ids_map,
1427 character_separator,
1428 domain_id_to_secondary_features_maps,
1430 all_pfams_encountered.add( domain_0 );
1431 if ( pfams_gained_or_lost != null ) {
1432 pfams_gained_or_lost.add( domain_0 );
1434 if ( !ForesterUtil.isEmpty( domain_1 ) ) {
1435 all_pfams_encountered.add( domain_1 );
1436 if ( pfams_gained_or_lost != null ) {
1437 pfams_gained_or_lost.add( domain_1 );
1440 if ( per_node_go_mapped_domain_gain_loss_outfile_writer != null ) {
1441 writeDomainsToIndividualFilePerTreeNode( per_node_go_mapped_domain_gain_loss_outfile_writer,
1448 if ( per_node_go_mapped_domain_gain_loss_outfile_writer != null ) {
1449 per_node_go_mapped_domain_gain_loss_outfile_writer.close();
1450 if ( per_node_counter < 1 ) {
1451 per_node_go_mapped_domain_gain_loss_outfile.delete();
1453 per_node_counter = 0;
1455 out.write( "</table>" );
1456 out.write( SurfacingConstants.NL );
1457 out.write( "<hr>" );
1458 out.write( SurfacingConstants.NL );
1459 } // for( final String id : sorted_ids ) {
1460 out.write( "</body>" );
1461 out.write( SurfacingConstants.NL );
1462 out.write( "</html>" );
1463 out.write( SurfacingConstants.NL );
1467 catch ( final IOException e ) {
1468 ForesterUtil.fatalError( surfacing_old.PRG_NAME, e.getMessage() );
1470 ForesterUtil.programMessage( surfacing_old.PRG_NAME, "Wrote characters detailed HTML list: \"" + filename
1474 public static void writeBinaryStatesMatrixToListORIGIG( final Map<DomainId, List<GoId>> domain_id_to_go_ids_map,
1475 final Map<GoId, GoTerm> go_id_to_term_map,
1476 final GoNameSpace go_namespace_limit,
1477 final boolean domain_combinations,
1478 final CharacterStateMatrix<CharacterStateMatrix.GainLossStates> matrix,
1479 final CharacterStateMatrix.GainLossStates state,
1480 final String filename,
1481 final String indentifier_characters_separator,
1482 final String character_separator,
1483 final String title_for_html,
1484 final String prefix_for_html,
1485 final Map<DomainId, Set<String>>[] domain_id_to_secondary_features_maps,
1486 final SortedSet<String> all_pfams_encountered,
1487 final SortedSet<String> pfams_gained_or_lost,
1488 final String suffix_for_per_node_events_file ) {
1489 if ( ( go_namespace_limit != null ) && ( ( go_id_to_term_map == null ) || ( go_id_to_term_map.size() < 1 ) ) ) {
1490 throw new IllegalArgumentException( "attempt to use GO namespace limit without a GO-id to term map" );
1492 else if ( ( ( domain_id_to_go_ids_map == null ) || ( domain_id_to_go_ids_map.size() < 1 ) ) ) {
1493 throw new IllegalArgumentException( "attempt to output detailed HTML without a Pfam to GO map" );
1495 else if ( ( ( go_id_to_term_map == null ) || ( go_id_to_term_map.size() < 1 ) ) ) {
1496 throw new IllegalArgumentException( "attempt to output detailed HTML without a GO-id to term map" );
1498 final File outfile = new File( filename );
1499 checkForOutputFileWriteability( outfile );
1500 final SortedSet<String> sorted_ids = new TreeSet<String>();
1501 for( int i = 0; i < matrix.getNumberOfIdentifiers(); ++i ) {
1502 sorted_ids.add( matrix.getIdentifier( i ) );
1505 final Writer out = new BufferedWriter( new FileWriter( outfile ) );
1506 final File per_node_go_mapped_domain_gain_loss_files_base_dir = createBaseDirForPerNodeDomainFiles( surfacing_old.BASE_DIRECTORY_PER_NODE_DOMAIN_GAIN_LOSS_FILES,
1507 domain_combinations,
1510 Writer per_node_go_mapped_domain_gain_loss_outfile_writer = null;
1511 File per_node_go_mapped_domain_gain_loss_outfile = null;
1512 int per_node_counter = 0;
1513 out.write( "<html>" );
1514 out.write( SurfacingConstants.NL );
1515 addHtmlHead( out, title_for_html );
1516 out.write( SurfacingConstants.NL );
1517 out.write( "<body>" );
1518 out.write( SurfacingConstants.NL );
1519 out.write( "<h1>" );
1520 out.write( SurfacingConstants.NL );
1521 out.write( title_for_html );
1522 out.write( SurfacingConstants.NL );
1523 out.write( "</h1>" );
1524 out.write( SurfacingConstants.NL );
1525 out.write( "<table>" );
1526 out.write( SurfacingConstants.NL );
1527 for( final String id : sorted_ids ) {
1528 out.write( "<tr>" );
1529 out.write( "<td>" );
1530 out.write( "<a href=\"#" + id + "\">" + id + "</a>" );
1531 writeTaxonomyLinks( out, id );
1532 out.write( "</td>" );
1533 out.write( "</tr>" );
1534 out.write( SurfacingConstants.NL );
1536 out.write( "</table>" );
1537 out.write( SurfacingConstants.NL );
1538 for( final String id : sorted_ids ) {
1539 out.write( SurfacingConstants.NL );
1540 out.write( "<h2>" );
1541 out.write( "<a name=\"" + id + "\">" + id + "</a>" );
1542 writeTaxonomyLinks( out, id );
1543 out.write( "</h2>" );
1544 out.write( SurfacingConstants.NL );
1545 out.write( "<table>" );
1546 out.write( SurfacingConstants.NL );
1547 out.write( "<tr>" );
1548 out.write( "<td><b>" );
1549 out.write( "Pfam domain(s)" );
1550 out.write( "</b></td><td><b>" );
1551 out.write( "GO term acc" );
1552 out.write( "</b></td><td><b>" );
1553 out.write( "GO term" );
1554 out.write( "</b></td><td><b>" );
1555 out.write( "Penultimate GO term" );
1556 out.write( "</b></td><td><b>" );
1557 out.write( "GO namespace" );
1558 out.write( "</b></td>" );
1559 out.write( "</tr>" );
1560 out.write( SurfacingConstants.NL );
1561 out.write( "</tr>" );
1562 out.write( SurfacingConstants.NL );
1563 per_node_counter = 0;
1564 if ( matrix.getNumberOfCharacters() > 0 ) {
1565 per_node_go_mapped_domain_gain_loss_outfile = new File( per_node_go_mapped_domain_gain_loss_files_base_dir
1566 + ForesterUtil.FILE_SEPARATOR + id + suffix_for_per_node_events_file );
1567 SurfacingUtil.checkForOutputFileWriteability( per_node_go_mapped_domain_gain_loss_outfile );
1568 per_node_go_mapped_domain_gain_loss_outfile_writer = ForesterUtil
1569 .createBufferedWriter( per_node_go_mapped_domain_gain_loss_outfile );
1572 per_node_go_mapped_domain_gain_loss_outfile = null;
1573 per_node_go_mapped_domain_gain_loss_outfile_writer = null;
1575 for( int c = 0; c < matrix.getNumberOfCharacters(); ++c ) {
1577 // using null to indicate either UNCHANGED_PRESENT or GAIN.
1578 if ( ( matrix.getState( id, c ) == state )
1579 || ( ( state == null ) && ( ( matrix.getState( id, c ) == CharacterStateMatrix.GainLossStates.UNCHANGED_PRESENT ) || ( matrix
1580 .getState( id, c ) == CharacterStateMatrix.GainLossStates.GAIN ) ) ) ) {
1581 final String character = matrix.getCharacter( c );
1582 String domain_0 = "";
1583 String domain_1 = "";
1584 if ( character.indexOf( BinaryDomainCombination.SEPARATOR ) > 0 ) {
1585 final String[] s = character.split( BinaryDomainCombination.SEPARATOR );
1586 if ( s.length != 2 ) {
1587 throw new AssertionError( "this should not have happened: unexpected format for domain combination: ["
1588 + character + "]" );
1594 domain_0 = character;
1596 writeDomainData( domain_id_to_go_ids_map,
1603 character_separator,
1604 domain_id_to_secondary_features_maps,
1606 all_pfams_encountered.add( domain_0 );
1607 if ( pfams_gained_or_lost != null ) {
1608 pfams_gained_or_lost.add( domain_0 );
1610 if ( !ForesterUtil.isEmpty( domain_1 ) ) {
1611 all_pfams_encountered.add( domain_1 );
1612 if ( pfams_gained_or_lost != null ) {
1613 pfams_gained_or_lost.add( domain_1 );
1616 if ( per_node_go_mapped_domain_gain_loss_outfile_writer != null ) {
1617 writeDomainsToIndividualFilePerTreeNode( per_node_go_mapped_domain_gain_loss_outfile_writer,
1624 if ( per_node_go_mapped_domain_gain_loss_outfile_writer != null ) {
1625 per_node_go_mapped_domain_gain_loss_outfile_writer.close();
1626 if ( per_node_counter < 1 ) {
1627 per_node_go_mapped_domain_gain_loss_outfile.delete();
1629 per_node_counter = 0;
1631 out.write( "</table>" );
1632 out.write( SurfacingConstants.NL );
1633 out.write( "<hr>" );
1634 out.write( SurfacingConstants.NL );
1635 } // for( final String id : sorted_ids ) {
1636 out.write( "</body>" );
1637 out.write( SurfacingConstants.NL );
1638 out.write( "</html>" );
1639 out.write( SurfacingConstants.NL );
1643 catch ( final IOException e ) {
1644 ForesterUtil.fatalError( surfacing_old.PRG_NAME, e.getMessage() );
1646 ForesterUtil.programMessage( surfacing_old.PRG_NAME, "Wrote characters detailed HTML list: \"" + filename
1650 public static void writeDomainCombinationsCountsFile( final String[][] input_file_properties,
1651 final File output_dir,
1652 final Writer per_genome_domain_promiscuity_statistics_writer,
1653 final GenomeWideCombinableDomains gwcd,
1655 final GenomeWideCombinableDomains.GenomeWideCombinableDomainsSortOrder dc_sort_order ) {
1656 File dc_outfile = new File( input_file_properties[ i ][ 0 ]
1657 + surfacing_old.DOMAIN_COMBINITON_COUNTS_OUTPUTFILE_SUFFIX );
1658 if ( output_dir != null ) {
1659 dc_outfile = new File( output_dir + ForesterUtil.FILE_SEPARATOR + dc_outfile );
1661 checkForOutputFileWriteability( dc_outfile );
1663 final BufferedWriter out = new BufferedWriter( new FileWriter( dc_outfile ) );
1664 out.write( gwcd.toStringBuilder( dc_sort_order ).toString() );
1667 catch ( final IOException e ) {
1668 ForesterUtil.fatalError( surfacing_old.PRG_NAME, e.getMessage() );
1670 final DescriptiveStatistics stats = gwcd.getPerGenomeDomainPromiscuityStatistics();
1672 per_genome_domain_promiscuity_statistics_writer.write( input_file_properties[ i ][ 0 ] + "\t" );
1673 per_genome_domain_promiscuity_statistics_writer.write( FORMATTER_3.format( stats.arithmeticMean() ) + "\t" );
1674 if ( stats.getN() < 2 ) {
1675 per_genome_domain_promiscuity_statistics_writer.write( "n/a" + "\t" );
1678 per_genome_domain_promiscuity_statistics_writer.write( FORMATTER_3.format( stats
1679 .sampleStandardDeviation() ) + "\t" );
1681 per_genome_domain_promiscuity_statistics_writer.write( FORMATTER_3.format( stats.median() ) + "\t" );
1682 per_genome_domain_promiscuity_statistics_writer.write( ( int ) stats.getMin() + "\t" );
1683 per_genome_domain_promiscuity_statistics_writer.write( ( int ) stats.getMax() + "\t" );
1684 per_genome_domain_promiscuity_statistics_writer.write( stats.getN() + "\t" );
1685 final SortedSet<DomainId> mpds = gwcd.getMostPromiscuosDomain();
1686 for( final DomainId mpd : mpds ) {
1687 per_genome_domain_promiscuity_statistics_writer.write( mpd.getId() + " " );
1689 per_genome_domain_promiscuity_statistics_writer.write( ForesterUtil.LINE_SEPARATOR );
1691 catch ( final IOException e ) {
1692 ForesterUtil.fatalError( surfacing_old.PRG_NAME, e.getMessage() );
1694 if ( input_file_properties[ i ].length == 3 ) {
1695 ForesterUtil.programMessage( surfacing_old.PRG_NAME, "Wrote domain combination counts for \""
1696 + input_file_properties[ i ][ 0 ] + "\" (" + input_file_properties[ i ][ 1 ] + ", "
1697 + input_file_properties[ i ][ 2 ] + ") to: \"" + dc_outfile + "\"" );
1700 ForesterUtil.programMessage( surfacing_old.PRG_NAME, "Wrote domain combination counts for \""
1701 + input_file_properties[ i ][ 0 ] + "\" (" + input_file_properties[ i ][ 1 ] + ") to: \""
1702 + dc_outfile + "\"" );
1706 private static void writeDomainData( final Map<DomainId, List<GoId>> domain_id_to_go_ids_map,
1707 final Map<GoId, GoTerm> go_id_to_term_map,
1708 final GoNameSpace go_namespace_limit,
1710 final String domain_0,
1711 final String domain_1,
1712 final String prefix_for_html,
1713 final String character_separator_for_non_html_output,
1714 final Map<DomainId, Set<String>>[] domain_id_to_secondary_features_maps,
1715 final Set<GoId> all_go_ids ) throws IOException {
1716 boolean any_go_annotation_present = false;
1717 boolean first_has_no_go = false;
1718 int domain_count = 2; // To distinguish between domains and binary domain combinations.
1719 if ( ForesterUtil.isEmpty( domain_1 ) ) {
1722 // The following has a difficult to understand logic.
1723 for( int d = 0; d < domain_count; ++d ) {
1724 List<GoId> go_ids = null;
1725 boolean go_annotation_present = false;
1727 final DomainId domain_id = new DomainId( domain_0 );
1728 if ( domain_id_to_go_ids_map.containsKey( domain_id ) ) {
1729 go_annotation_present = true;
1730 any_go_annotation_present = true;
1731 go_ids = domain_id_to_go_ids_map.get( domain_id );
1734 first_has_no_go = true;
1738 final DomainId domain_id = new DomainId( domain_1 );
1739 if ( domain_id_to_go_ids_map.containsKey( domain_id ) ) {
1740 go_annotation_present = true;
1741 any_go_annotation_present = true;
1742 go_ids = domain_id_to_go_ids_map.get( domain_id );
1745 if ( go_annotation_present ) {
1746 boolean first = ( ( d == 0 ) || ( ( d == 1 ) && first_has_no_go ) );
1747 for( final GoId go_id : go_ids ) {
1748 out.write( "<tr>" );
1751 writeDomainIdsToHtml( out,
1755 domain_id_to_secondary_features_maps );
1758 out.write( "<td></td>" );
1760 if ( !go_id_to_term_map.containsKey( go_id ) ) {
1761 throw new IllegalArgumentException( "GO-id [" + go_id + "] not found in GO-id to GO-term map" );
1763 final GoTerm go_term = go_id_to_term_map.get( go_id );
1764 if ( ( go_namespace_limit == null ) || go_namespace_limit.equals( go_term.getGoNameSpace() ) ) {
1765 // final String top = GoUtils.getPenultimateGoTerm( go_term, go_id_to_term_map ).getName();
1766 final String go_id_str = go_id.getId();
1767 out.write( "<td>" );
1768 out.write( "<a href=\"" + SurfacingConstants.AMIGO_LINK + go_id_str
1769 + "\" target=\"amigo_window\">" + go_id_str + "</a>" );
1770 out.write( "</td><td>" );
1771 out.write( go_term.getName() );
1772 if ( domain_count == 2 ) {
1773 out.write( " (" + d + ")" );
1775 out.write( "</td><td>" );
1776 // out.write( top );
1777 // out.write( "</td><td>" );
1779 out.write( go_term.getGoNameSpace().toShortString() );
1781 out.write( "</td>" );
1782 if ( all_go_ids != null ) {
1783 all_go_ids.add( go_id );
1787 out.write( "<td>" );
1788 out.write( "</td><td>" );
1789 out.write( "</td><td>" );
1790 out.write( "</td><td>" );
1791 out.write( "</td>" );
1793 out.write( "</tr>" );
1794 out.write( SurfacingConstants.NL );
1797 } // for( int d = 0; d < domain_count; ++d )
1798 if ( !any_go_annotation_present ) {
1799 out.write( "<tr>" );
1800 writeDomainIdsToHtml( out, domain_0, domain_1, prefix_for_html, domain_id_to_secondary_features_maps );
1801 out.write( "<td>" );
1802 out.write( "</td><td>" );
1803 out.write( "</td><td>" );
1804 out.write( "</td><td>" );
1805 out.write( "</td>" );
1806 out.write( "</tr>" );
1807 out.write( SurfacingConstants.NL );
1811 private static void writeDomainDataORIG( final Map<DomainId, List<GoId>> domain_id_to_go_ids_map,
1812 final Map<GoId, GoTerm> go_id_to_term_map,
1813 final GoNameSpace go_namespace_limit,
1815 final String domain_0,
1816 final String domain_1,
1817 final String prefix_for_html,
1818 final String character_separator_for_non_html_output,
1819 final Map<DomainId, Set<String>>[] domain_id_to_secondary_features_maps,
1820 final Set<GoId> all_go_ids ) throws IOException {
1821 boolean any_go_annotation_present = false;
1822 boolean first_has_no_go = false;
1823 int domain_count = 2; // To distinguish between domains and binary domain combinations.
1824 if ( ForesterUtil.isEmpty( domain_1 ) ) {
1827 // The following has a difficult to understand logic.
1828 for( int d = 0; d < domain_count; ++d ) {
1829 List<GoId> go_ids = null;
1830 boolean go_annotation_present = false;
1832 final DomainId domain_id = new DomainId( domain_0 );
1833 if ( domain_id_to_go_ids_map.containsKey( domain_id ) ) {
1834 go_annotation_present = true;
1835 any_go_annotation_present = true;
1836 go_ids = domain_id_to_go_ids_map.get( domain_id );
1839 first_has_no_go = true;
1843 final DomainId domain_id = new DomainId( domain_1 );
1844 if ( domain_id_to_go_ids_map.containsKey( domain_id ) ) {
1845 go_annotation_present = true;
1846 any_go_annotation_present = true;
1847 go_ids = domain_id_to_go_ids_map.get( domain_id );
1850 if ( go_annotation_present ) {
1851 boolean first = ( ( d == 0 ) || ( ( d == 1 ) && first_has_no_go ) );
1852 for( final GoId go_id : go_ids ) {
1853 out.write( "<tr>" );
1856 writeDomainIdsToHtml( out,
1860 domain_id_to_secondary_features_maps );
1863 out.write( "<td></td>" );
1865 if ( !go_id_to_term_map.containsKey( go_id ) ) {
1866 throw new IllegalArgumentException( "GO-id [" + go_id + "] not found in GO-id to GO-term map" );
1868 final GoTerm go_term = go_id_to_term_map.get( go_id );
1869 if ( ( go_namespace_limit == null ) || go_namespace_limit.equals( go_term.getGoNameSpace() ) ) {
1870 final String top = GoUtils.getPenultimateGoTerm( go_term, go_id_to_term_map ).getName();
1871 final String go_id_str = go_id.getId();
1872 out.write( "<td>" );
1873 out.write( "<a href=\"" + SurfacingConstants.AMIGO_LINK + go_id_str
1874 + "\" target=\"amigo_window\">" + go_id_str + "</a>" );
1875 out.write( "</td><td>" );
1876 out.write( go_term.getName() );
1877 if ( domain_count == 2 ) {
1878 out.write( " (" + d + ")" );
1880 out.write( "</td><td>" );
1882 out.write( "</td><td>" );
1884 out.write( go_term.getGoNameSpace().toShortString() );
1886 out.write( "</td>" );
1887 if ( all_go_ids != null ) {
1888 all_go_ids.add( go_id );
1892 out.write( "<td>" );
1893 out.write( "</td><td>" );
1894 out.write( "</td><td>" );
1895 out.write( "</td><td>" );
1896 out.write( "</td>" );
1898 out.write( "</tr>" );
1899 out.write( SurfacingConstants.NL );
1902 } // for( int d = 0; d < domain_count; ++d )
1903 if ( !any_go_annotation_present ) {
1904 out.write( "<tr>" );
1905 writeDomainIdsToHtml( out, domain_0, domain_1, prefix_for_html, domain_id_to_secondary_features_maps );
1906 out.write( "<td>" );
1907 out.write( "</td><td>" );
1908 out.write( "</td><td>" );
1909 out.write( "</td><td>" );
1910 out.write( "</td>" );
1911 out.write( "</tr>" );
1912 out.write( SurfacingConstants.NL );
1916 private static void writeDomainIdsToHtml( final Writer out,
1917 final String domain_0,
1918 final String domain_1,
1919 final String prefix_for_detailed_html,
1920 final Map<DomainId, Set<String>>[] domain_id_to_secondary_features_maps )
1921 throws IOException {
1922 out.write( "<td>" );
1923 if ( !ForesterUtil.isEmpty( prefix_for_detailed_html ) ) {
1924 out.write( prefix_for_detailed_html );
1927 out.write( "<a href=\"" + SurfacingConstants.PFAM_FAMILY_ID_LINK + domain_0 + "\">" + domain_0 + "</a>" );
1928 //if ( ForesterUtil.isEmpty( domain_1 ) ) {
1929 // out.write( " <a href=\"" + SurfacingConstants.GOOGLE_SCHOLAR_LINK + domain_0
1930 // + SurfacingConstants.GOOGLE_SCHOLAR_LIMITS + "\">[gs]</a>" );
1932 // if ( !ForesterUtil.isEmpty( domain_1 ) ) {
1933 // out.write( "=" );
1934 // out.write( "<a href=\"" + SurfacingConstants.PFAM_FAMILY_ID_LINK + domain_1 + "\">" + domain_1 + "</a>" );
1936 // else if ( ( domain_id_to_secondary_features_maps != null )
1937 // && ( domain_id_to_secondary_features_maps.length > 0 ) ) {
1938 // out.write( " [" );
1939 // boolean first = true;
1940 // for( final Map<DomainId, Set<String>> domain_id_to_secondary_features_map : domain_id_to_secondary_features_maps ) {
1941 // final Set<String> sec_features = domain_id_to_secondary_features_map.get( new DomainId( domain_0 ) );
1942 // if ( ( sec_features != null ) && ( sec_features.size() > 0 ) ) {
1943 // for( final String sec_feature : sec_features ) {
1948 // out.write( ", " );
1950 // if ( SurfacingConstants.SECONDARY_FEATURES_ARE_SCOP
1951 // && ( SurfacingConstants.SECONDARY_FEATURES_SCOP_LINK != null ) ) {
1952 // out.write( "<a href=\"" + SurfacingConstants.SECONDARY_FEATURES_SCOP_LINK + sec_feature
1953 // + "\" target=\"scop_window\">" + sec_feature + "</a>" );
1956 // out.write( sec_feature );
1961 // out.write( "]" );
1963 out.write( "</td>" );
1966 private static void writeDomainIdsToHtmlORIG( final Writer out,
1967 final String domain_0,
1968 final String domain_1,
1969 final String prefix_for_detailed_html,
1970 final Map<DomainId, Set<String>>[] domain_id_to_secondary_features_maps )
1971 throws IOException {
1972 out.write( "<td>" );
1973 if ( !ForesterUtil.isEmpty( prefix_for_detailed_html ) ) {
1974 out.write( prefix_for_detailed_html );
1977 out.write( "<a href=\"" + SurfacingConstants.PFAM_FAMILY_ID_LINK + domain_0 + "\">" + domain_0 + "</a>" );
1978 if ( ForesterUtil.isEmpty( domain_1 ) ) {
1979 out.write( " <a href=\"" + SurfacingConstants.GOOGLE_SCHOLAR_LINK + domain_0
1980 + SurfacingConstants.GOOGLE_SCHOLAR_LIMITS + "\">[gs]</a>" );
1982 if ( !ForesterUtil.isEmpty( domain_1 ) ) {
1984 out.write( "<a href=\"" + SurfacingConstants.PFAM_FAMILY_ID_LINK + domain_1 + "\">" + domain_1 + "</a>" );
1986 else if ( ( domain_id_to_secondary_features_maps != null )
1987 && ( domain_id_to_secondary_features_maps.length > 0 ) ) {
1989 boolean first = true;
1990 for( final Map<DomainId, Set<String>> domain_id_to_secondary_features_map : domain_id_to_secondary_features_maps ) {
1991 final Set<String> sec_features = domain_id_to_secondary_features_map.get( new DomainId( domain_0 ) );
1992 if ( ( sec_features != null ) && ( sec_features.size() > 0 ) ) {
1993 for( final String sec_feature : sec_features ) {
2000 if ( SurfacingConstants.SECONDARY_FEATURES_ARE_SCOP
2001 && ( SurfacingConstants.SECONDARY_FEATURES_SCOP_LINK != null ) ) {
2002 out.write( "<a href=\"" + SurfacingConstants.SECONDARY_FEATURES_SCOP_LINK + sec_feature
2003 + "\" target=\"scop_window\">" + sec_feature + "</a>" );
2006 out.write( sec_feature );
2013 out.write( "</td>" );
2016 public static DescriptiveStatistics writeDomainSimilaritiesToFile( final StringBuilder html_desc,
2017 final StringBuilder html_title,
2019 final SortedSet<DomainSimilarity> similarities,
2020 final boolean treat_as_binary,
2021 final List<Species> species_order,
2022 final PrintableDomainSimilarity.PRINT_OPTION print_option,
2023 final DomainSimilarity.DomainSimilaritySortField sort_field,
2024 final DomainSimilarity.DomainSimilarityScoring scoring,
2025 final boolean verbose ) throws IOException {
2026 final DescriptiveStatistics stats = new BasicDescriptiveStatistics();
2027 String histogram_title = null;
2028 switch ( sort_field ) {
2029 case ABS_MAX_COUNTS_DIFFERENCE:
2030 if ( treat_as_binary ) {
2031 histogram_title = "absolute counts difference:";
2034 histogram_title = "absolute (maximal) counts difference:";
2037 case MAX_COUNTS_DIFFERENCE:
2038 if ( treat_as_binary ) {
2039 histogram_title = "counts difference:";
2042 histogram_title = "(maximal) counts difference:";
2046 histogram_title = "score mean:";
2049 histogram_title = "score minimum:";
2052 histogram_title = "score maximum:";
2054 case MAX_DIFFERENCE:
2055 if ( treat_as_binary ) {
2056 histogram_title = "difference:";
2059 histogram_title = "(maximal) difference:";
2063 histogram_title = "score mean:";
2066 histogram_title = "score standard deviation:";
2069 histogram_title = "species number:";
2072 throw new AssertionError( "Unknown sort field: " + sort_field );
2074 for( final DomainSimilarity similarity : similarities ) {
2075 switch ( sort_field ) {
2076 case ABS_MAX_COUNTS_DIFFERENCE:
2077 stats.addValue( Math.abs( similarity.getMaximalDifferenceInCounts() ) );
2079 case MAX_COUNTS_DIFFERENCE:
2080 stats.addValue( similarity.getMaximalDifferenceInCounts() );
2083 stats.addValue( similarity.getMeanSimilarityScore() );
2086 stats.addValue( similarity.getMinimalSimilarityScore() );
2089 stats.addValue( similarity.getMaximalSimilarityScore() );
2091 case MAX_DIFFERENCE:
2092 stats.addValue( similarity.getMaximalDifference() );
2095 stats.addValue( similarity.getMeanSimilarityScore() );
2098 stats.addValue( similarity.getStandardDeviationOfSimilarityScore() );
2101 stats.addValue( similarity.getSpecies().size() );
2104 throw new AssertionError( "Unknown sort field: " + sort_field );
2108 // final HistogramData[] hists = new HistogramData[ 1 ];
2111 // List<HistogramDataItem> data_items = new
2112 // ArrayList<HistogramDataItem>();
2113 // double[] values = stats.getDataAsDoubleArray();
2114 // for( int i = 0; i < values.length; i++ ) {
2115 // HistogramDataItem data_item = new BasicHistogramDataItem( "", values[
2117 // data_items.add( data_item );
2121 // HistogramData hd0 = new HistogramData( "name",
2129 // hists[ 0 ] = hd0;
2131 // final HistogramsFrame hf = new HistogramsFrame( hists );
2132 // hf.setVisible( true );
2134 AsciiHistogram histo = null;
2135 if ( stats.getMin() < stats.getMin() ) {
2136 histo = new AsciiHistogram( stats, histogram_title );
2139 if ( histo != null ) {
2140 System.out.println( histo.toStringBuffer( 20, '|', 40, 5 ) );
2142 System.out.println();
2143 System.out.println( "N : " + stats.getN() );
2144 System.out.println( "Min : " + stats.getMin() );
2145 System.out.println( "Max : " + stats.getMax() );
2146 System.out.println( "Mean : " + stats.arithmeticMean() );
2147 if ( stats.getN() > 1 ) {
2148 System.out.println( "SD : " + stats.sampleStandardDeviation() );
2151 System.out.println( "SD : n/a" );
2153 System.out.println( "Median : " + stats.median() );
2154 if ( stats.getN() > 1 ) {
2155 System.out.println( "Pearsonian skewness : " + stats.pearsonianSkewness() );
2158 System.out.println( "Pearsonian skewness : n/a" );
2161 switch ( print_option ) {
2162 case SIMPLE_TAB_DELIMITED:
2165 w.write( "<html>" );
2166 w.write( SurfacingConstants.NL );
2167 addHtmlHead( w, "SURFACING :: " + html_title );
2168 w.write( SurfacingConstants.NL );
2169 w.write( "<body>" );
2170 w.write( SurfacingConstants.NL );
2171 w.write( html_desc.toString() );
2172 w.write( SurfacingConstants.NL );
2175 w.write( SurfacingConstants.NL );
2176 w.write( "<tt><pre>" );
2177 w.write( SurfacingConstants.NL );
2178 if ( histo != null ) {
2179 w.write( histo.toStringBuffer( 20, '|', 40, 5 ).toString() );
2180 w.write( SurfacingConstants.NL );
2182 w.write( "</pre></tt>" );
2183 w.write( SurfacingConstants.NL );
2184 w.write( "<table>" );
2185 w.write( SurfacingConstants.NL );
2186 w.write( "<tr><td>N: </td><td>" + stats.getN() + "</td></tr>" );
2187 w.write( SurfacingConstants.NL );
2188 w.write( "<tr><td>Min: </td><td>" + stats.getMin() + "</td></tr>" );
2189 w.write( SurfacingConstants.NL );
2190 w.write( "<tr><td>Max: </td><td>" + stats.getMax() + "</td></tr>" );
2191 w.write( SurfacingConstants.NL );
2192 w.write( "<tr><td>Mean: </td><td>" + stats.arithmeticMean() + "</td></tr>" );
2193 w.write( SurfacingConstants.NL );
2194 if ( stats.getN() > 1 ) {
2195 w.write( "<tr><td>SD: </td><td>" + stats.sampleStandardDeviation() + "</td></tr>" );
2198 w.write( "<tr><td>SD: </td><td>n/a</td></tr>" );
2200 w.write( SurfacingConstants.NL );
2201 w.write( "<tr><td>Median: </td><td>" + stats.median() + "</td></tr>" );
2202 w.write( SurfacingConstants.NL );
2203 if ( stats.getN() > 1 ) {
2204 w.write( "<tr><td>Pearsonian skewness: </td><td>" + stats.pearsonianSkewness() + "</td></tr>" );
2207 w.write( "<tr><td>Pearsonian skewness: </td><td>n/a</td></tr>" );
2209 w.write( SurfacingConstants.NL );
2210 w.write( "</table>" );
2211 w.write( SurfacingConstants.NL );
2213 w.write( SurfacingConstants.NL );
2215 w.write( SurfacingConstants.NL );
2217 w.write( SurfacingConstants.NL );
2218 w.write( "<table>" );
2219 w.write( SurfacingConstants.NL );
2222 w.write( SurfacingConstants.NL );
2223 for( final DomainSimilarity similarity : similarities ) {
2224 if ( ( species_order != null ) && !species_order.isEmpty() ) {
2225 ( ( PrintableDomainSimilarity ) similarity ).setSpeciesOrder( species_order );
2227 w.write( similarity.toStringBuffer( print_option ).toString() );
2228 w.write( SurfacingConstants.NL );
2230 switch ( print_option ) {
2232 w.write( SurfacingConstants.NL );
2233 w.write( "</table>" );
2234 w.write( SurfacingConstants.NL );
2235 w.write( "</font>" );
2236 w.write( SurfacingConstants.NL );
2237 w.write( "</body>" );
2238 w.write( SurfacingConstants.NL );
2239 w.write( "</html>" );
2240 w.write( SurfacingConstants.NL );
2248 private static void writeDomainsToIndividualFilePerTreeNode( final Writer individual_files_writer,
2249 final String domain_0,
2250 final String domain_1 ) throws IOException {
2251 individual_files_writer.write( domain_0 );
2252 individual_files_writer.write( ForesterUtil.LINE_SEPARATOR );
2253 if ( !ForesterUtil.isEmpty( domain_1 ) ) {
2254 individual_files_writer.write( domain_1 );
2255 individual_files_writer.write( ForesterUtil.LINE_SEPARATOR );
2259 public static void writeMatrixToFile( final CharacterStateMatrix<?> matrix,
2260 final String filename,
2261 final Format format ) {
2262 final File outfile = new File( filename );
2263 checkForOutputFileWriteability( outfile );
2265 final BufferedWriter out = new BufferedWriter( new FileWriter( outfile ) );
2266 matrix.toWriter( out, format );
2270 catch ( final IOException e ) {
2271 ForesterUtil.fatalError( surfacing_old.PRG_NAME, e.getMessage() );
2273 ForesterUtil.programMessage( surfacing_old.PRG_NAME, "Wrote matrix: \"" + filename + "\"" );
2276 public static void writeMatrixToFile( final File matrix_outfile, final List<DistanceMatrix> matrices ) {
2277 checkForOutputFileWriteability( matrix_outfile );
2279 final BufferedWriter out = new BufferedWriter( new FileWriter( matrix_outfile ) );
2280 for( final DistanceMatrix distance_matrix : matrices ) {
2281 out.write( distance_matrix.toStringBuffer( DistanceMatrix.Format.PHYLIP ).toString() );
2282 out.write( ForesterUtil.LINE_SEPARATOR );
2287 catch ( final IOException e ) {
2288 ForesterUtil.fatalError( surfacing_old.PRG_NAME, e.getMessage() );
2290 ForesterUtil.programMessage( surfacing_old.PRG_NAME, "Wrote distance matrices to \"" + matrix_outfile + "\"" );
2293 private static void writePfamsToFile( final String outfile_name, final SortedSet<String> pfams ) {
2295 final Writer writer = new BufferedWriter( new FileWriter( new File( outfile_name ) ) );
2296 for( final String pfam : pfams ) {
2297 writer.write( pfam );
2298 writer.write( ForesterUtil.LINE_SEPARATOR );
2301 ForesterUtil.programMessage( surfacing_old.PRG_NAME, "Wrote " + pfams.size() + " pfams to [" + outfile_name
2304 catch ( final IOException e ) {
2305 ForesterUtil.printWarningMessage( surfacing_old.PRG_NAME, "Failure to write: " + e );
2309 public static void writePhylogenyToFile( final Phylogeny phylogeny, final String filename ) {
2310 final PhylogenyWriter writer = new PhylogenyWriter();
2312 writer.toPhyloXML( new File( filename ), phylogeny, 1 );
2314 catch ( final IOException e ) {
2315 ForesterUtil.printWarningMessage( surfacing_old.PRG_NAME, "failed to write phylogeny to \"" + filename
2318 ForesterUtil.programMessage( surfacing_old.PRG_NAME, "Wrote phylogeny to \"" + filename + "\"" );
2321 public static void writeTaxonomyLinks( final Writer writer, final String species ) throws IOException {
2322 if ( ( species.length() > 1 ) && ( species.indexOf( '_' ) < 1 ) ) {
2323 final Matcher matcher = PATTERN_SP_STYLE_TAXONOMY.matcher( species );
2324 writer.write( " [" );
2325 if ( matcher.matches() ) {
2326 writer.write( "<a href=\"" + SurfacingConstants.UNIPROT_LINK + species
2327 + "\" target=\"taxonomy_window\">uniprot</a>" );
2330 writer.write( "<a href=\"" + SurfacingConstants.EOL_LINK + species
2331 + "\" target=\"taxonomy_window\">eol</a>" );
2332 writer.write( "|" );
2333 writer.write( "<a href=\"" + SurfacingConstants.TOL_LINK + species
2334 + "\" target=\"taxonomy_window\">tol</a>" );
2336 writer.write( "]" );
2340 public static void writeTaxonomyLinksORIG( final Writer writer, final String species ) throws IOException {
2341 if ( ( species.length() > 1 ) && ( species.indexOf( '_' ) < 1 ) ) {
2342 final Matcher matcher = PATTERN_SP_STYLE_TAXONOMY.matcher( species );
2343 writer.write( " [" );
2344 if ( matcher.matches() ) {
2345 writer.write( "<a href=\"" + SurfacingConstants.UNIPROT_LINK + species
2346 + "\" target=\"taxonomy_window\">uniprot</a>" );
2349 writer.write( "<a href=\"" + SurfacingConstants.EOL_LINK + species
2350 + "\" target=\"taxonomy_window\">eol</a>" );
2351 writer.write( "|" );
2352 writer.write( "<a href=\"" + SurfacingConstants.TOL_LINK + species
2353 + "\" target=\"taxonomy_window\">tol</a>" );
2354 writer.write( "|" );
2355 writer.write( "<a href=\"" + SurfacingConstants.WIKIPEDIA_LINK + species
2356 + "\" target=\"taxonomy_window\">wikipedia</a>" );
2357 writer.write( "|" );
2358 writer.write( "<a href=\"" + SurfacingConstants.GOOGLE_SCHOLAR_LINK + species
2359 + "\" target=\"taxonomy_window\">gs</a>" );
2361 writer.write( "]" );
2365 private static void writeToNexus( final String outfile_name, final CharacterStateMatrix<BinaryStates> matrix ) {
2366 if ( !( matrix instanceof BasicCharacterStateMatrix ) ) {
2367 throw new IllegalArgumentException( "can only write matrices of type [" + BasicCharacterStateMatrix.class
2370 final BasicCharacterStateMatrix<BinaryStates> my_matrix = ( org.forester.evoinference.matrix.character.BasicCharacterStateMatrix<BinaryStates> ) matrix;
2372 final BufferedWriter w = new BufferedWriter( new FileWriter( outfile_name ) );
2373 w.write( NexusConstants.NEXUS );
2374 w.write( ForesterUtil.LINE_SEPARATOR );
2375 my_matrix.writeNexusTaxaBlock( w );
2376 my_matrix.writeNexusBinaryChractersBlock( w );
2379 ForesterUtil.programMessage( surfacing_old.PRG_NAME, "Wrote Nexus file: \"" + outfile_name + "\"" );
2381 catch ( final IOException e ) {
2382 ForesterUtil.fatalError( surfacing_old.PRG_NAME, e.getMessage() );
2386 private static void writeToNexus( final String outfile_name,
2387 final CharacterStateMatrix<BinaryStates> matrix,
2388 final Phylogeny phylogeny ) {
2389 if ( !( matrix instanceof BasicCharacterStateMatrix ) ) {
2390 throw new IllegalArgumentException( "can only write matrices of type [" + BasicCharacterStateMatrix.class
2393 final BasicCharacterStateMatrix<BinaryStates> my_matrix = ( org.forester.evoinference.matrix.character.BasicCharacterStateMatrix<BinaryStates> ) matrix;
2394 final List<Phylogeny> phylogenies = new ArrayList<Phylogeny>( 1 );
2395 phylogenies.add( phylogeny );
2397 final BufferedWriter w = new BufferedWriter( new FileWriter( outfile_name ) );
2398 w.write( NexusConstants.NEXUS );
2399 w.write( ForesterUtil.LINE_SEPARATOR );
2400 my_matrix.writeNexusTaxaBlock( w );
2401 my_matrix.writeNexusBinaryChractersBlock( w );
2402 PhylogenyWriter.writeNexusTreesBlock( w, phylogenies );
2405 ForesterUtil.programMessage( surfacing_old.PRG_NAME, "Wrote Nexus file: \"" + outfile_name + "\"" );
2407 catch ( final IOException e ) {
2408 ForesterUtil.fatalError( surfacing_old.PRG_NAME, e.getMessage() );
2412 private static void writeToNexus( final String outfile_name, final DomainParsimonyCalculator domain_parsimony ) {
2413 writeToNexus( outfile_name + surfacing_old.NEXUS_EXTERNAL_DOMAINS,
2414 domain_parsimony.createMatrixOfDomainPresenceOrAbsence() );
2415 writeToNexus( outfile_name + surfacing_old.NEXUS_EXTERNAL_DOMAIN_COMBINATIONS,
2416 domain_parsimony.createMatrixOfBinaryDomainCombinationPresenceOrAbsence() );
2419 private static void writeToNexus( final String outfile_name,
2420 final DomainParsimonyCalculator domain_parsimony,
2421 final Phylogeny phylogeny ) {
2422 writeToNexus( outfile_name + surfacing_old.NEXUS_EXTERNAL_DOMAINS,
2423 domain_parsimony.createMatrixOfDomainPresenceOrAbsence(),
2425 writeToNexus( outfile_name + surfacing_old.NEXUS_EXTERNAL_DOMAIN_COMBINATIONS,
2426 domain_parsimony.createMatrixOfBinaryDomainCombinationPresenceOrAbsence(),