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: https://sites.google.com/site/cmzmasek/home/software/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.Arrays;
38 import java.util.Collections;
39 import java.util.Comparator;
40 import java.util.HashMap;
41 import java.util.HashSet;
42 import java.util.Iterator;
43 import java.util.List;
45 import java.util.Map.Entry;
46 import java.util.PriorityQueue;
48 import java.util.SortedMap;
49 import java.util.SortedSet;
50 import java.util.TreeMap;
51 import java.util.TreeSet;
52 import java.util.regex.Matcher;
53 import java.util.regex.Pattern;
55 import org.forester.application.surfacing;
56 import org.forester.evoinference.distance.NeighborJoining;
57 import org.forester.evoinference.matrix.character.BasicCharacterStateMatrix;
58 import org.forester.evoinference.matrix.character.CharacterStateMatrix;
59 import org.forester.evoinference.matrix.character.CharacterStateMatrix.BinaryStates;
60 import org.forester.evoinference.matrix.character.CharacterStateMatrix.Format;
61 import org.forester.evoinference.matrix.character.CharacterStateMatrix.GainLossStates;
62 import org.forester.evoinference.matrix.distance.BasicSymmetricalDistanceMatrix;
63 import org.forester.evoinference.matrix.distance.DistanceMatrix;
64 import org.forester.go.GoId;
65 import org.forester.go.GoNameSpace;
66 import org.forester.go.GoTerm;
67 import org.forester.go.PfamToGoMapping;
68 import org.forester.io.parsers.nexus.NexusConstants;
69 import org.forester.io.writers.PhylogenyWriter;
70 import org.forester.phylogeny.Phylogeny;
71 import org.forester.phylogeny.PhylogenyMethods;
72 import org.forester.phylogeny.PhylogenyNode;
73 import org.forester.phylogeny.PhylogenyNode.NH_CONVERSION_SUPPORT_VALUE_STYLE;
74 import org.forester.phylogeny.data.BinaryCharacters;
75 import org.forester.phylogeny.data.Confidence;
76 import org.forester.phylogeny.data.Taxonomy;
77 import org.forester.phylogeny.iterators.PhylogenyNodeIterator;
78 import org.forester.protein.BasicDomain;
79 import org.forester.protein.BasicProtein;
80 import org.forester.protein.BinaryDomainCombination;
81 import org.forester.protein.Domain;
82 import org.forester.protein.Protein;
83 import org.forester.species.Species;
84 import org.forester.surfacing.DomainSimilarityCalculator.Detailedness;
85 import org.forester.surfacing.GenomeWideCombinableDomains.GenomeWideCombinableDomainsSortOrder;
86 import org.forester.util.AsciiHistogram;
87 import org.forester.util.BasicDescriptiveStatistics;
88 import org.forester.util.BasicTable;
89 import org.forester.util.BasicTableParser;
90 import org.forester.util.DescriptiveStatistics;
91 import org.forester.util.ForesterUtil;
93 public final class SurfacingUtil {
95 private final static NumberFormat FORMATTER_3 = new DecimalFormat( "0.000" );
96 private static final Comparator<Domain> ASCENDING_CONFIDENCE_VALUE_ORDER = new Comparator<Domain>() {
99 public int compare( final Domain d1,
101 if ( d1.getPerSequenceEvalue() < d2
102 .getPerSequenceEvalue() ) {
106 .getPerSequenceEvalue() > d2
107 .getPerSequenceEvalue() ) {
111 return d1.compareTo( d2 );
115 public final static Pattern PATTERN_SP_STYLE_TAXONOMY = Pattern.compile( "^[A-Z0-9]{3,5}$" );
117 private SurfacingUtil() {
118 // Hidden constructor.
121 public static void addAllBinaryDomainCombinationToSet( final GenomeWideCombinableDomains genome,
122 final SortedSet<BinaryDomainCombination> binary_domain_combinations ) {
123 final SortedMap<String, CombinableDomains> all_cd = genome.getAllCombinableDomainsIds();
124 for( final String domain_id : all_cd.keySet() ) {
125 binary_domain_combinations.addAll( all_cd.get( domain_id ).toBinaryDomainCombinations() );
129 public static void addAllDomainIdsToSet( final GenomeWideCombinableDomains genome,
130 final SortedSet<String> domain_ids ) {
131 final SortedSet<String> domains = genome.getAllDomainIds();
132 for( final String domain : domains ) {
133 domain_ids.add( domain );
137 public static void addHtmlHead( final Writer w, final String title ) throws IOException {
138 w.write( SurfacingConstants.NL );
140 w.write( "<title>" );
142 w.write( "</title>" );
143 w.write( SurfacingConstants.NL );
144 w.write( "<style>" );
145 w.write( SurfacingConstants.NL );
146 w.write( "a:visited { color : #6633FF; text-decoration : none; }" );
147 w.write( SurfacingConstants.NL );
148 w.write( "a:link { color : #6633FF; text-decoration : none; }" );
149 w.write( SurfacingConstants.NL );
150 w.write( "a:active { color : #99FF00; text-decoration : none; }" );
151 w.write( SurfacingConstants.NL );
152 w.write( "a:hover { color : #FFFFFF; background-color : #99FF00; text-decoration : none; }" );
153 w.write( SurfacingConstants.NL );
155 w.write( "a.pl:visited { color : #505050; text-decoration : none; font-size: 7pt;}" );
156 w.write( SurfacingConstants.NL );
157 w.write( "a.pl:link { color : #505050; text-decoration : none; font-size: 7pt;}" );
158 w.write( SurfacingConstants.NL );
159 w.write( "a.pl:active { color : #505050; text-decoration : none; font-size: 7pt;}" );
160 w.write( SurfacingConstants.NL );
161 w.write( "a.pl:hover { color : #FFFFFF; background-color : #99FF00; text-decoration : none; font-size: 7pt;}" );
162 w.write( SurfacingConstants.NL );
164 w.write( "a.ps:visited { color : #707070; text-decoration : none; font-size: 7pt;}" );
165 w.write( SurfacingConstants.NL );
166 w.write( "a.ps:link { color : #707070; text-decoration : none; font-size: 7pt;}" );
167 w.write( SurfacingConstants.NL );
168 w.write( "a.ps:active { color : #707070; text-decoration : none; font-size: 7pt;}" );
169 w.write( SurfacingConstants.NL );
170 w.write( "a.ps:hover { color : #FFFFFF; background-color : #99FF00; text-decoration : none; font-size: 7pt;}" );
171 w.write( SurfacingConstants.NL );
173 w.write( "td { text-align: left; vertical-align: top; font-family: Verdana, Arial, Helvetica; font-size: 8pt}" );
174 w.write( SurfacingConstants.NL );
175 w.write( "h1 { color : #0000FF; font-family: Verdana, Arial, Helvetica; font-size: 18pt; font-weight: bold }" );
176 w.write( SurfacingConstants.NL );
177 w.write( "h2 { color : #0000FF; font-family: Verdana, Arial, Helvetica; font-size: 16pt; font-weight: bold }" );
178 w.write( SurfacingConstants.NL );
179 w.write( "</style>" );
180 w.write( SurfacingConstants.NL );
181 w.write( "</head>" );
182 w.write( SurfacingConstants.NL );
185 public static DescriptiveStatistics calculateDescriptiveStatisticsForMeanValues( final Set<DomainSimilarity> similarities ) {
186 final DescriptiveStatistics stats = new BasicDescriptiveStatistics();
187 for( final DomainSimilarity similarity : similarities ) {
188 stats.addValue( similarity.getMeanSimilarityScore() );
193 public static int calculateOverlap( final Domain domain, final List<Boolean> covered_positions ) {
194 int overlap_count = 0;
195 for( int i = domain.getFrom(); i <= domain.getTo(); ++i ) {
196 if ( ( i < covered_positions.size() ) && ( covered_positions.get( i ) == true ) ) {
200 return overlap_count;
203 public static void checkForOutputFileWriteability( final File outfile ) {
204 final String error = ForesterUtil.isWritableFile( outfile );
205 if ( !ForesterUtil.isEmpty( error ) ) {
206 ForesterUtil.fatalError( surfacing.PRG_NAME, error );
210 public static void collectChangedDomainCombinationsFromBinaryStatesMatrixAsListToFile( final CharacterStateMatrix<CharacterStateMatrix.GainLossStates> matrix,
211 final BinaryDomainCombination.DomainCombinationType dc_type,
212 final List<BinaryDomainCombination> all_binary_domains_combination_gained,
213 final boolean get_gains ) {
214 final SortedSet<String> sorted_ids = new TreeSet<String>();
215 for( int i = 0; i < matrix.getNumberOfIdentifiers(); ++i ) {
216 sorted_ids.add( matrix.getIdentifier( i ) );
218 for( final String id : sorted_ids ) {
219 for( int c = 0; c < matrix.getNumberOfCharacters(); ++c ) {
220 if ( ( get_gains && ( matrix.getState( id, c ) == CharacterStateMatrix.GainLossStates.GAIN ) )
221 || ( !get_gains && ( matrix.getState( id, c ) == CharacterStateMatrix.GainLossStates.LOSS ) ) ) {
222 if ( dc_type == BinaryDomainCombination.DomainCombinationType.DIRECTED_ADJACTANT ) {
223 all_binary_domains_combination_gained.add( AdjactantDirectedBinaryDomainCombination
224 .createInstance( matrix.getCharacter( c ) ) );
226 else if ( dc_type == BinaryDomainCombination.DomainCombinationType.DIRECTED ) {
227 all_binary_domains_combination_gained.add( DirectedBinaryDomainCombination
228 .createInstance( matrix.getCharacter( c ) ) );
231 all_binary_domains_combination_gained.add( BasicBinaryDomainCombination.createInstance( matrix
232 .getCharacter( c ) ) );
239 public static Map<String, List<GoId>> createDomainIdToGoIdMap( final List<PfamToGoMapping> pfam_to_go_mappings ) {
240 final Map<String, List<GoId>> domain_id_to_go_ids_map = new HashMap<String, List<GoId>>( pfam_to_go_mappings.size() );
241 for( final PfamToGoMapping pfam_to_go : pfam_to_go_mappings ) {
242 if ( !domain_id_to_go_ids_map.containsKey( pfam_to_go.getKey() ) ) {
243 domain_id_to_go_ids_map.put( pfam_to_go.getKey(), new ArrayList<GoId>() );
245 domain_id_to_go_ids_map.get( pfam_to_go.getKey() ).add( pfam_to_go.getValue() );
247 return domain_id_to_go_ids_map;
250 public static Map<String, Set<String>> createDomainIdToSecondaryFeaturesMap( final File secondary_features_map_file )
252 final BasicTable<String> primary_table = BasicTableParser.parse( secondary_features_map_file, '\t' );
253 final Map<String, Set<String>> map = new TreeMap<String, Set<String>>();
254 for( int r = 0; r < primary_table.getNumberOfRows(); ++r ) {
255 final String domain_id = primary_table.getValue( 0, r );
256 if ( !map.containsKey( domain_id ) ) {
257 map.put( domain_id, new HashSet<String>() );
259 map.get( domain_id ).add( primary_table.getValue( 1, r ) );
264 public static Phylogeny createNjTreeBasedOnMatrixToFile( final File nj_tree_outfile, final DistanceMatrix distance ) {
265 checkForOutputFileWriteability( nj_tree_outfile );
266 final NeighborJoining nj = NeighborJoining.createInstance();
267 final Phylogeny phylogeny = nj.execute( ( BasicSymmetricalDistanceMatrix ) distance );
268 phylogeny.setName( nj_tree_outfile.getName() );
269 writePhylogenyToFile( phylogeny, nj_tree_outfile.toString() );
273 public static Map<String, Integer> createTaxCodeToIdMap( final Phylogeny phy ) {
274 final Map<String, Integer> m = new HashMap<String, Integer>();
275 for( final PhylogenyNodeIterator iter = phy.iteratorExternalForward(); iter.hasNext(); ) {
276 final PhylogenyNode n = iter.next();
277 if ( n.getNodeData().isHasTaxonomy() ) {
278 final Taxonomy t = n.getNodeData().getTaxonomy();
279 final String c = t.getTaxonomyCode();
280 if ( !ForesterUtil.isEmpty( c ) ) {
281 if ( n.getNodeData().getTaxonomy() == null ) {
282 ForesterUtil.fatalError( surfacing.PRG_NAME, "no taxonomy id for node " + n );
284 final String id = n.getNodeData().getTaxonomy().getIdentifier().getValue();
285 if ( ForesterUtil.isEmpty( id ) ) {
286 ForesterUtil.fatalError( surfacing.PRG_NAME, "no taxonomy id for node " + n );
288 if ( m.containsKey( c ) ) {
289 ForesterUtil.fatalError( surfacing.PRG_NAME, "taxonomy code " + c + " is not unique" );
291 final int iid = Integer.valueOf( id );
292 if ( m.containsValue( iid ) ) {
293 ForesterUtil.fatalError( surfacing.PRG_NAME, "taxonomy id " + iid + " is not unique" );
299 ForesterUtil.fatalError( surfacing.PRG_NAME, "no taxonomy for node " + n );
305 public static void decoratePrintableDomainSimilarities( final SortedSet<DomainSimilarity> domain_similarities,
306 final Detailedness detailedness ) {
307 for( final DomainSimilarity domain_similarity : domain_similarities ) {
308 if ( domain_similarity instanceof PrintableDomainSimilarity ) {
309 final PrintableDomainSimilarity printable_domain_similarity = ( PrintableDomainSimilarity ) domain_similarity;
310 printable_domain_similarity.setDetailedness( detailedness );
315 public static void doit( final List<Protein> proteins,
316 final List<String> query_domain_ids_nc_order,
318 final String separator,
319 final String limit_to_species,
320 final Map<String, List<Integer>> average_protein_lengths_by_dc ) throws IOException {
321 for( final Protein protein : proteins ) {
322 if ( ForesterUtil.isEmpty( limit_to_species )
323 || protein.getSpecies().getSpeciesId().equalsIgnoreCase( limit_to_species ) ) {
324 if ( protein.contains( query_domain_ids_nc_order, true ) ) {
325 out.write( protein.getSpecies().getSpeciesId() );
326 out.write( separator );
327 out.write( protein.getProteinId().getId() );
328 out.write( separator );
330 final Set<String> visited_domain_ids = new HashSet<String>();
331 boolean first = true;
332 for( final Domain domain : protein.getProteinDomains() ) {
333 if ( !visited_domain_ids.contains( domain.getDomainId() ) ) {
334 visited_domain_ids.add( domain.getDomainId() );
341 out.write( domain.getDomainId() );
343 out.write( "" + domain.getTotalCount() );
348 out.write( separator );
349 if ( !( ForesterUtil.isEmpty( protein.getDescription() ) || protein.getDescription()
350 .equals( SurfacingConstants.NONE ) ) ) {
351 out.write( protein.getDescription() );
353 out.write( separator );
354 if ( !( ForesterUtil.isEmpty( protein.getAccession() ) || protein.getAccession()
355 .equals( SurfacingConstants.NONE ) ) ) {
356 out.write( protein.getAccession() );
358 out.write( SurfacingConstants.NL );
365 public static void domainsPerProteinsStatistics( final String genome,
366 final List<Protein> protein_list,
367 final DescriptiveStatistics all_genomes_domains_per_potein_stats,
368 final SortedMap<Integer, Integer> all_genomes_domains_per_potein_histo,
369 final SortedSet<String> domains_which_are_always_single,
370 final SortedSet<String> domains_which_are_sometimes_single_sometimes_not,
371 final SortedSet<String> domains_which_never_single,
372 final Writer writer ) {
373 final DescriptiveStatistics stats = new BasicDescriptiveStatistics();
374 for( final Protein protein : protein_list ) {
375 final int domains = protein.getNumberOfProteinDomains();
376 //System.out.println( domains );
377 stats.addValue( domains );
378 all_genomes_domains_per_potein_stats.addValue( domains );
379 if ( !all_genomes_domains_per_potein_histo.containsKey( domains ) ) {
380 all_genomes_domains_per_potein_histo.put( domains, 1 );
383 all_genomes_domains_per_potein_histo.put( domains,
384 1 + all_genomes_domains_per_potein_histo.get( domains ) );
386 if ( domains == 1 ) {
387 final String domain = protein.getProteinDomain( 0 ).getDomainId();
388 if ( !domains_which_are_sometimes_single_sometimes_not.contains( domain ) ) {
389 if ( domains_which_never_single.contains( domain ) ) {
390 domains_which_never_single.remove( domain );
391 domains_which_are_sometimes_single_sometimes_not.add( domain );
394 domains_which_are_always_single.add( domain );
398 else if ( domains > 1 ) {
399 for( final Domain d : protein.getProteinDomains() ) {
400 final String domain = d.getDomainId();
401 // System.out.println( domain );
402 if ( !domains_which_are_sometimes_single_sometimes_not.contains( domain ) ) {
403 if ( domains_which_are_always_single.contains( domain ) ) {
404 domains_which_are_always_single.remove( domain );
405 domains_which_are_sometimes_single_sometimes_not.add( domain );
408 domains_which_never_single.add( domain );
415 writer.write( genome );
416 writer.write( "\t" );
417 if ( stats.getN() >= 1 ) {
418 writer.write( stats.arithmeticMean() + "" );
419 writer.write( "\t" );
420 if ( stats.getN() >= 2 ) {
421 writer.write( stats.sampleStandardDeviation() + "" );
426 writer.write( "\t" );
427 writer.write( stats.median() + "" );
428 writer.write( "\t" );
429 writer.write( stats.getN() + "" );
430 writer.write( "\t" );
431 writer.write( stats.getMin() + "" );
432 writer.write( "\t" );
433 writer.write( stats.getMax() + "" );
436 writer.write( "\t" );
437 writer.write( "\t" );
438 writer.write( "\t" );
440 writer.write( "\t" );
441 writer.write( "\t" );
443 writer.write( "\n" );
445 catch ( final IOException e ) {
450 public static void executeDomainLengthAnalysis( final String[][] input_file_properties,
451 final int number_of_genomes,
452 final DomainLengthsTable domain_lengths_table,
453 final File outfile ) throws IOException {
454 final DecimalFormat df = new DecimalFormat( "#.00" );
455 checkForOutputFileWriteability( outfile );
456 final BufferedWriter out = new BufferedWriter( new FileWriter( outfile ) );
457 out.write( "MEAN BASED STATISTICS PER SPECIES" );
458 out.write( ForesterUtil.LINE_SEPARATOR );
459 out.write( domain_lengths_table.createMeanBasedStatisticsPerSpeciesTable().toString() );
460 out.write( ForesterUtil.LINE_SEPARATOR );
461 out.write( ForesterUtil.LINE_SEPARATOR );
462 final List<DomainLengths> domain_lengths_list = domain_lengths_table.getDomainLengthsList();
463 out.write( "OUTLIER SPECIES PER DOMAIN (Z>=1.5)" );
464 out.write( ForesterUtil.LINE_SEPARATOR );
465 for( final DomainLengths domain_lengths : domain_lengths_list ) {
466 final List<Species> species_list = domain_lengths.getMeanBasedOutlierSpecies( 1.5 );
467 if ( species_list.size() > 0 ) {
468 out.write( domain_lengths.getDomainId() + "\t" );
469 for( final Species species : species_list ) {
470 out.write( species + "\t" );
472 out.write( ForesterUtil.LINE_SEPARATOR );
475 out.write( ForesterUtil.LINE_SEPARATOR );
476 out.write( ForesterUtil.LINE_SEPARATOR );
477 out.write( "OUTLIER SPECIES (Z 1.0)" );
478 out.write( ForesterUtil.LINE_SEPARATOR );
479 final DescriptiveStatistics stats_for_all_species = domain_lengths_table
480 .calculateMeanBasedStatisticsForAllSpecies();
481 out.write( stats_for_all_species.asSummary() );
482 out.write( ForesterUtil.LINE_SEPARATOR );
483 final AsciiHistogram histo = new AsciiHistogram( stats_for_all_species );
484 out.write( histo.toStringBuffer( 40, '=', 60, 4 ).toString() );
485 out.write( ForesterUtil.LINE_SEPARATOR );
486 final double population_sd = stats_for_all_species.sampleStandardDeviation();
487 final double population_mean = stats_for_all_species.arithmeticMean();
488 for( final Species species : domain_lengths_table.getSpecies() ) {
489 final double x = domain_lengths_table.calculateMeanBasedStatisticsForSpecies( species ).arithmeticMean();
490 final double z = ( x - population_mean ) / population_sd;
491 out.write( species + "\t" + z );
492 out.write( ForesterUtil.LINE_SEPARATOR );
494 out.write( ForesterUtil.LINE_SEPARATOR );
495 for( final Species species : domain_lengths_table.getSpecies() ) {
496 final DescriptiveStatistics stats_for_species = domain_lengths_table
497 .calculateMeanBasedStatisticsForSpecies( species );
498 final double x = stats_for_species.arithmeticMean();
499 final double z = ( x - population_mean ) / population_sd;
500 if ( ( z <= -1.0 ) || ( z >= 1.0 ) ) {
501 out.write( species + "\t" + df.format( z ) + "\t" + stats_for_species.asSummary() );
502 out.write( ForesterUtil.LINE_SEPARATOR );
511 * @param all_binary_domains_combination_lost_fitch
512 * @param use_last_in_fitch_parsimony
513 * @param consider_directedness_and_adjacency_for_bin_combinations
514 * @param all_binary_domains_combination_gained if null ignored, otherwise this is to list all binary domain combinations
515 * which were gained under unweighted (Fitch) parsimony.
517 public static void executeParsimonyAnalysis( final long random_number_seed_for_fitch_parsimony,
518 final boolean radomize_fitch_parsimony,
519 final String outfile_name,
520 final DomainParsimonyCalculator domain_parsimony,
521 final Phylogeny phylogeny,
522 final Map<String, List<GoId>> domain_id_to_go_ids_map,
523 final Map<GoId, GoTerm> go_id_to_term_map,
524 final GoNameSpace go_namespace_limit,
525 final String parameters_str,
526 final Map<String, Set<String>>[] domain_id_to_secondary_features_maps,
527 final SortedSet<String> positive_filter,
528 final boolean output_binary_domain_combinations_for_graphs,
529 final List<BinaryDomainCombination> all_binary_domains_combination_gained_fitch,
530 final List<BinaryDomainCombination> all_binary_domains_combination_lost_fitch,
531 final BinaryDomainCombination.DomainCombinationType dc_type,
532 final Map<String, DescriptiveStatistics> protein_length_stats_by_dc,
533 final Map<String, DescriptiveStatistics> domain_number_stats_by_dc,
534 final Map<String, DescriptiveStatistics> domain_length_stats_by_domain,
535 final Map<String, Integer> tax_code_to_id_map,
536 final boolean write_to_nexus,
537 final boolean use_last_in_fitch_parsimony ) {
538 final String sep = ForesterUtil.LINE_SEPARATOR + "###################" + ForesterUtil.LINE_SEPARATOR;
539 final String date_time = ForesterUtil.getCurrentDateTime();
540 final SortedSet<String> all_pfams_encountered = new TreeSet<String>();
541 final SortedSet<String> all_pfams_gained_as_domains = new TreeSet<String>();
542 final SortedSet<String> all_pfams_lost_as_domains = new TreeSet<String>();
543 final SortedSet<String> all_pfams_gained_as_dom_combinations = new TreeSet<String>();
544 final SortedSet<String> all_pfams_lost_as_dom_combinations = new TreeSet<String>();
545 if ( write_to_nexus ) {
546 writeToNexus( outfile_name, domain_parsimony, phylogeny );
550 Phylogeny local_phylogeny_l = phylogeny.copy();
551 if ( ( positive_filter != null ) && ( positive_filter.size() > 0 ) ) {
552 domain_parsimony.executeDolloParsimonyOnDomainPresence( positive_filter );
555 domain_parsimony.executeDolloParsimonyOnDomainPresence();
557 SurfacingUtil.writeMatrixToFile( domain_parsimony.getGainLossMatrix(), outfile_name
558 + surfacing.PARSIMONY_OUTPUT_GL_SUFFIX_DOLLO_DOMAINS, Format.FORESTER );
559 SurfacingUtil.writeMatrixToFile( domain_parsimony.getGainLossCountsMatrix(), outfile_name
560 + surfacing.PARSIMONY_OUTPUT_GL_COUNTS_SUFFIX_DOLLO_DOMAINS, Format.FORESTER );
561 SurfacingUtil.writeBinaryStatesMatrixAsListToFile( domain_parsimony.getGainLossMatrix(),
562 CharacterStateMatrix.GainLossStates.GAIN,
563 outfile_name + surfacing.PARSIMONY_OUTPUT_DOLLO_GAINS_D,
565 ForesterUtil.LINE_SEPARATOR,
567 SurfacingUtil.writeBinaryStatesMatrixAsListToFile( domain_parsimony.getGainLossMatrix(),
568 CharacterStateMatrix.GainLossStates.LOSS,
569 outfile_name + surfacing.PARSIMONY_OUTPUT_DOLLO_LOSSES_D,
571 ForesterUtil.LINE_SEPARATOR,
573 SurfacingUtil.writeBinaryStatesMatrixAsListToFile( domain_parsimony.getGainLossMatrix(), null, outfile_name
574 + surfacing.PARSIMONY_OUTPUT_DOLLO_PRESENT_D, sep, ForesterUtil.LINE_SEPARATOR, null );
576 writeBinaryStatesMatrixToList( domain_id_to_go_ids_map,
580 domain_parsimony.getGainLossMatrix(),
581 CharacterStateMatrix.GainLossStates.GAIN,
582 outfile_name + surfacing.PARSIMONY_OUTPUT_DOLLO_GAINS_HTML_D,
584 ForesterUtil.LINE_SEPARATOR,
585 "Dollo Parsimony | Gains | Domains",
587 domain_id_to_secondary_features_maps,
588 all_pfams_encountered,
589 all_pfams_gained_as_domains,
591 tax_code_to_id_map );
592 writeBinaryStatesMatrixToList( domain_id_to_go_ids_map,
596 domain_parsimony.getGainLossMatrix(),
597 CharacterStateMatrix.GainLossStates.LOSS,
598 outfile_name + surfacing.PARSIMONY_OUTPUT_DOLLO_LOSSES_HTML_D,
600 ForesterUtil.LINE_SEPARATOR,
601 "Dollo Parsimony | Losses | Domains",
603 domain_id_to_secondary_features_maps,
604 all_pfams_encountered,
605 all_pfams_lost_as_domains,
607 tax_code_to_id_map );
608 // writeBinaryStatesMatrixToList( domain_id_to_go_ids_map,
609 // go_id_to_term_map,
610 // go_namespace_limit,
612 // domain_parsimony.getGainLossMatrix(),
614 // outfile_name + surfacing.PARSIMONY_OUTPUT_DOLLO_PRESENT_HTML_D,
616 // ForesterUtil.LINE_SEPARATOR,
617 // "Dollo Parsimony | Present | Domains",
619 // domain_id_to_secondary_features_maps,
620 // all_pfams_encountered,
622 // "_dollo_present_d",
623 // tax_code_to_id_map );
624 preparePhylogeny( local_phylogeny_l,
627 "Dollo parsimony on domain presence/absence",
628 "dollo_on_domains_" + outfile_name,
630 SurfacingUtil.writePhylogenyToFile( local_phylogeny_l, outfile_name
631 + surfacing.DOMAINS_PARSIMONY_TREE_OUTPUT_SUFFIX_DOLLO );
633 writeAllDomainsChangedOnAllSubtrees( local_phylogeny_l, true, outfile_name, "_dollo_all_gains_d" );
634 writeAllDomainsChangedOnAllSubtrees( local_phylogeny_l, false, outfile_name, "_dollo_all_losses_d" );
636 catch ( final IOException e ) {
638 ForesterUtil.fatalError( surfacing.PRG_NAME, e.getLocalizedMessage() );
640 if ( domain_parsimony.calculateNumberOfBinaryDomainCombination() > 0 ) {
641 // FITCH DOMAIN COMBINATIONS
642 // -------------------------
643 local_phylogeny_l = phylogeny.copy();
644 String randomization = "no";
645 if ( radomize_fitch_parsimony ) {
646 domain_parsimony.executeFitchParsimonyOnBinaryDomainCombintion( random_number_seed_for_fitch_parsimony );
647 randomization = "yes, seed = " + random_number_seed_for_fitch_parsimony;
650 domain_parsimony.executeFitchParsimonyOnBinaryDomainCombintion( use_last_in_fitch_parsimony );
652 SurfacingUtil.writeMatrixToFile( domain_parsimony.getGainLossMatrix(), outfile_name
653 + surfacing.PARSIMONY_OUTPUT_GL_SUFFIX_FITCH_BINARY_COMBINATIONS, Format.FORESTER );
654 SurfacingUtil.writeMatrixToFile( domain_parsimony.getGainLossCountsMatrix(), outfile_name
655 + surfacing.PARSIMONY_OUTPUT_GL_COUNTS_SUFFIX_FITCH_BINARY_COMBINATIONS, Format.FORESTER );
657 .writeBinaryStatesMatrixAsListToFile( domain_parsimony.getGainLossMatrix(),
658 CharacterStateMatrix.GainLossStates.GAIN,
659 outfile_name + surfacing.PARSIMONY_OUTPUT_FITCH_GAINS_BC,
661 ForesterUtil.LINE_SEPARATOR,
663 SurfacingUtil.writeBinaryStatesMatrixAsListToFile( domain_parsimony.getGainLossMatrix(),
664 CharacterStateMatrix.GainLossStates.LOSS,
666 + surfacing.PARSIMONY_OUTPUT_FITCH_LOSSES_BC,
668 ForesterUtil.LINE_SEPARATOR,
670 SurfacingUtil.writeBinaryStatesMatrixAsListToFile( domain_parsimony.getGainLossMatrix(), null, outfile_name
671 + surfacing.PARSIMONY_OUTPUT_FITCH_PRESENT_BC, sep, ForesterUtil.LINE_SEPARATOR, null );
672 if ( all_binary_domains_combination_gained_fitch != null ) {
673 collectChangedDomainCombinationsFromBinaryStatesMatrixAsListToFile( domain_parsimony.getGainLossMatrix(),
675 all_binary_domains_combination_gained_fitch,
678 if ( all_binary_domains_combination_lost_fitch != null ) {
679 collectChangedDomainCombinationsFromBinaryStatesMatrixAsListToFile( domain_parsimony.getGainLossMatrix(),
681 all_binary_domains_combination_lost_fitch,
684 if ( output_binary_domain_combinations_for_graphs ) {
686 .writeBinaryStatesMatrixAsListToFileForBinaryCombinationsForGraphAnalysis( domain_parsimony
687 .getGainLossMatrix(),
690 + surfacing.PARSIMONY_OUTPUT_FITCH_PRESENT_BC_OUTPUTFILE_SUFFIX_FOR_GRAPH_ANALYSIS,
692 ForesterUtil.LINE_SEPARATOR,
693 BinaryDomainCombination.OutputFormat.DOT );
696 writeBinaryStatesMatrixToList( domain_id_to_go_ids_map,
700 domain_parsimony.getGainLossMatrix(),
701 CharacterStateMatrix.GainLossStates.GAIN,
702 outfile_name + surfacing.PARSIMONY_OUTPUT_FITCH_GAINS_HTML_BC,
704 ForesterUtil.LINE_SEPARATOR,
705 "Fitch Parsimony | Gains | Domain Combinations",
708 all_pfams_encountered,
709 all_pfams_gained_as_dom_combinations,
711 tax_code_to_id_map );
712 writeBinaryStatesMatrixToList( domain_id_to_go_ids_map,
716 domain_parsimony.getGainLossMatrix(),
717 CharacterStateMatrix.GainLossStates.LOSS,
718 outfile_name + surfacing.PARSIMONY_OUTPUT_FITCH_LOSSES_HTML_BC,
720 ForesterUtil.LINE_SEPARATOR,
721 "Fitch Parsimony | Losses | Domain Combinations",
724 all_pfams_encountered,
725 all_pfams_lost_as_dom_combinations,
727 tax_code_to_id_map );
728 // writeBinaryStatesMatrixToList( domain_id_to_go_ids_map,
729 // go_id_to_term_map,
730 // go_namespace_limit,
732 // domain_parsimony.getGainLossMatrix(),
734 // outfile_name + surfacing.PARSIMONY_OUTPUT_FITCH_PRESENT_HTML_BC,
736 // ForesterUtil.LINE_SEPARATOR,
737 // "Fitch Parsimony | Present | Domain Combinations",
740 // all_pfams_encountered,
742 // "_fitch_present_dc",
743 // tax_code_to_id_map );
744 writeAllEncounteredPfamsToFile( domain_id_to_go_ids_map,
747 all_pfams_encountered );
748 writePfamsToFile( outfile_name + surfacing.ALL_PFAMS_GAINED_AS_DOMAINS_SUFFIX, all_pfams_gained_as_domains );
749 writePfamsToFile( outfile_name + surfacing.ALL_PFAMS_LOST_AS_DOMAINS_SUFFIX, all_pfams_lost_as_domains );
750 writePfamsToFile( outfile_name + surfacing.ALL_PFAMS_GAINED_AS_DC_SUFFIX,
751 all_pfams_gained_as_dom_combinations );
752 writePfamsToFile( outfile_name + surfacing.ALL_PFAMS_LOST_AS_DC_SUFFIX, all_pfams_lost_as_dom_combinations );
753 preparePhylogeny( local_phylogeny_l,
756 "Fitch parsimony on binary domain combination presence/absence randomization: "
758 "fitch_on_binary_domain_combinations_" + outfile_name,
760 SurfacingUtil.writePhylogenyToFile( local_phylogeny_l, outfile_name
761 + surfacing.BINARY_DOMAIN_COMBINATIONS_PARSIMONY_TREE_OUTPUT_SUFFIX_FITCH );
762 calculateIndependentDomainCombinationGains( local_phylogeny_l,
764 + surfacing.INDEPENDENT_DC_GAINS_FITCH_PARS_COUNTS_OUTPUT_SUFFIX,
766 + surfacing.INDEPENDENT_DC_GAINS_FITCH_PARS_DC_OUTPUT_SUFFIX,
768 + surfacing.INDEPENDENT_DC_GAINS_FITCH_PARS_DC_FOR_GO_MAPPING_OUTPUT_SUFFIX,
770 + surfacing.INDEPENDENT_DC_GAINS_FITCH_PARS_DC_FOR_GO_MAPPING_OUTPUT_UNIQUE_SUFFIX,
771 outfile_name + "_indep_dc_gains_fitch_lca_ranks.txt",
772 outfile_name + "_indep_dc_gains_fitch_lca_taxonomies.txt",
773 outfile_name + "_indep_dc_gains_fitch_protein_statistics.txt",
774 protein_length_stats_by_dc,
775 domain_number_stats_by_dc,
776 domain_length_stats_by_domain );
780 public static void executeParsimonyAnalysisForSecondaryFeatures( final String outfile_name,
781 final DomainParsimonyCalculator secondary_features_parsimony,
782 final Phylogeny phylogeny,
783 final String parameters_str,
784 final Map<Species, MappingResults> mapping_results_map,
785 final boolean use_last_in_fitch_parsimony ) {
786 final String sep = ForesterUtil.LINE_SEPARATOR + "###################" + ForesterUtil.LINE_SEPARATOR;
787 final String date_time = ForesterUtil.getCurrentDateTime();
788 System.out.println();
789 writeToNexus( outfile_name + surfacing.NEXUS_SECONDARY_FEATURES,
790 secondary_features_parsimony.createMatrixOfSecondaryFeaturePresenceOrAbsence( null ),
792 Phylogeny local_phylogeny_copy = phylogeny.copy();
793 secondary_features_parsimony.executeDolloParsimonyOnSecondaryFeatures( mapping_results_map );
794 SurfacingUtil.writeMatrixToFile( secondary_features_parsimony.getGainLossMatrix(), outfile_name
795 + surfacing.PARSIMONY_OUTPUT_GL_SUFFIX_DOLLO_SECONDARY_FEATURES, Format.FORESTER );
796 SurfacingUtil.writeMatrixToFile( secondary_features_parsimony.getGainLossCountsMatrix(), outfile_name
797 + surfacing.PARSIMONY_OUTPUT_GL_COUNTS_SUFFIX_DOLLO_SECONDARY_FEATURES, Format.FORESTER );
799 .writeBinaryStatesMatrixAsListToFile( secondary_features_parsimony.getGainLossMatrix(),
800 CharacterStateMatrix.GainLossStates.GAIN,
802 + surfacing.PARSIMONY_OUTPUT_DOLLO_GAINS_SECONDARY_FEATURES,
804 ForesterUtil.LINE_SEPARATOR,
807 .writeBinaryStatesMatrixAsListToFile( secondary_features_parsimony.getGainLossMatrix(),
808 CharacterStateMatrix.GainLossStates.LOSS,
810 + surfacing.PARSIMONY_OUTPUT_DOLLO_LOSSES_SECONDARY_FEATURES,
812 ForesterUtil.LINE_SEPARATOR,
815 .writeBinaryStatesMatrixAsListToFile( secondary_features_parsimony.getGainLossMatrix(),
818 + surfacing.PARSIMONY_OUTPUT_DOLLO_PRESENT_SECONDARY_FEATURES,
820 ForesterUtil.LINE_SEPARATOR,
822 preparePhylogeny( local_phylogeny_copy,
823 secondary_features_parsimony,
825 "Dollo parsimony on secondary feature presence/absence",
826 "dollo_on_secondary_features_" + outfile_name,
828 SurfacingUtil.writePhylogenyToFile( local_phylogeny_copy, outfile_name
829 + surfacing.SECONDARY_FEATURES_PARSIMONY_TREE_OUTPUT_SUFFIX_DOLLO );
830 // FITCH DOMAIN COMBINATIONS
831 // -------------------------
832 local_phylogeny_copy = phylogeny.copy();
833 final String randomization = "no";
834 secondary_features_parsimony
835 .executeFitchParsimonyOnBinaryDomainCombintionOnSecondaryFeatures( use_last_in_fitch_parsimony );
836 preparePhylogeny( local_phylogeny_copy,
837 secondary_features_parsimony,
839 "Fitch parsimony on secondary binary domain combination presence/absence randomization: "
841 "fitch_on_binary_domain_combinations_" + outfile_name,
843 SurfacingUtil.writePhylogenyToFile( local_phylogeny_copy, outfile_name
844 + surfacing.BINARY_DOMAIN_COMBINATIONS_PARSIMONY_TREE_OUTPUT_SUFFIX_FITCH_MAPPED );
845 calculateIndependentDomainCombinationGains( local_phylogeny_copy, outfile_name
846 + surfacing.INDEPENDENT_DC_GAINS_FITCH_PARS_COUNTS_MAPPED_OUTPUT_SUFFIX, outfile_name
847 + surfacing.INDEPENDENT_DC_GAINS_FITCH_PARS_DC_MAPPED_OUTPUT_SUFFIX, outfile_name
848 + surfacing.INDEPENDENT_DC_GAINS_FITCH_PARS_DC_FOR_GO_MAPPING_MAPPED_OUTPUT_SUFFIX, outfile_name
849 + surfacing.INDEPENDENT_DC_GAINS_FITCH_PARS_DC_FOR_GO_MAPPING_MAPPED_OUTPUT_UNIQUE_SUFFIX, outfile_name
850 + "_MAPPED_indep_dc_gains_fitch_lca_ranks.txt", outfile_name
851 + "_MAPPED_indep_dc_gains_fitch_lca_taxonomies.txt", null, null, null, null );
854 public static void extractProteinNames( final List<Protein> proteins,
855 final List<String> query_domain_ids_nc_order,
857 final String separator,
858 final String limit_to_species ) throws IOException {
859 for( final Protein protein : proteins ) {
860 if ( ForesterUtil.isEmpty( limit_to_species )
861 || protein.getSpecies().getSpeciesId().equalsIgnoreCase( limit_to_species ) ) {
862 if ( protein.contains( query_domain_ids_nc_order, true ) ) {
863 out.write( protein.getSpecies().getSpeciesId() );
864 out.write( separator );
865 out.write( protein.getProteinId().getId() );
866 out.write( separator );
868 final Set<String> visited_domain_ids = new HashSet<String>();
869 boolean first = true;
870 for( final Domain domain : protein.getProteinDomains() ) {
871 if ( !visited_domain_ids.contains( domain.getDomainId() ) ) {
872 visited_domain_ids.add( domain.getDomainId() );
879 out.write( domain.getDomainId() );
881 out.write( "" + domain.getTotalCount() );
886 out.write( separator );
887 if ( !( ForesterUtil.isEmpty( protein.getDescription() ) || protein.getDescription()
888 .equals( SurfacingConstants.NONE ) ) ) {
889 out.write( protein.getDescription() );
891 out.write( separator );
892 if ( !( ForesterUtil.isEmpty( protein.getAccession() ) || protein.getAccession()
893 .equals( SurfacingConstants.NONE ) ) ) {
894 out.write( protein.getAccession() );
896 out.write( SurfacingConstants.NL );
903 public static void extractProteinNames( final SortedMap<Species, List<Protein>> protein_lists_per_species,
904 final String domain_id,
906 final String separator,
907 final String limit_to_species,
908 final double domain_e_cutoff ) throws IOException {
909 System.out.println( "Per domain E-value: " + domain_e_cutoff );
910 for( final Species species : protein_lists_per_species.keySet() ) {
911 System.out.println( species + ":" );
912 for( final Protein protein : protein_lists_per_species.get( species ) ) {
913 if ( ForesterUtil.isEmpty( limit_to_species )
914 || protein.getSpecies().getSpeciesId().equalsIgnoreCase( limit_to_species ) ) {
915 final List<Domain> domains = protein.getProteinDomains( domain_id );
916 if ( domains.size() > 0 ) {
917 out.write( protein.getSpecies().getSpeciesId() );
918 out.write( separator );
919 out.write( protein.getProteinId().getId() );
920 out.write( separator );
921 out.write( domain_id.toString() );
922 out.write( separator );
924 for( final Domain domain : domains ) {
925 if ( ( domain_e_cutoff < 0 ) || ( domain.getPerDomainEvalue() <= domain_e_cutoff ) ) {
927 out.write( domain.getFrom() + "-" + domain.getTo() );
928 if ( prev_to >= 0 ) {
929 final int l = domain.getFrom() - prev_to;
930 System.out.println( l );
932 prev_to = domain.getTo();
936 out.write( separator );
937 final List<Domain> domain_list = new ArrayList<Domain>();
938 for( final Domain domain : protein.getProteinDomains() ) {
939 if ( ( domain_e_cutoff < 0 ) || ( domain.getPerDomainEvalue() <= domain_e_cutoff ) ) {
940 domain_list.add( domain );
943 final Domain domain_ary[] = new Domain[ domain_list.size() ];
944 for( int i = 0; i < domain_list.size(); ++i ) {
945 domain_ary[ i ] = domain_list.get( i );
947 Arrays.sort( domain_ary, new DomainComparator( true ) );
949 boolean first = true;
950 for( final Domain domain : domain_ary ) {
957 out.write( domain.getDomainId().toString() );
958 out.write( ":" + domain.getFrom() + "-" + domain.getTo() );
959 out.write( ":" + domain.getPerDomainEvalue() );
962 if ( !( ForesterUtil.isEmpty( protein.getDescription() ) || protein.getDescription()
963 .equals( SurfacingConstants.NONE ) ) ) {
964 out.write( protein.getDescription() );
966 out.write( separator );
967 if ( !( ForesterUtil.isEmpty( protein.getAccession() ) || protein.getAccession()
968 .equals( SurfacingConstants.NONE ) ) ) {
969 out.write( protein.getAccession() );
971 out.write( SurfacingConstants.NL );
979 public static SortedSet<String> getAllDomainIds( final List<GenomeWideCombinableDomains> gwcd_list ) {
980 final SortedSet<String> all_domains_ids = new TreeSet<String>();
981 for( final GenomeWideCombinableDomains gwcd : gwcd_list ) {
982 final Set<String> all_domains = gwcd.getAllDomainIds();
983 // for( final Domain domain : all_domains ) {
984 all_domains_ids.addAll( all_domains );
987 return all_domains_ids;
990 public static SortedMap<String, Integer> getDomainCounts( final List<Protein> protein_domain_collections ) {
991 final SortedMap<String, Integer> map = new TreeMap<String, Integer>();
992 for( final Protein protein_domain_collection : protein_domain_collections ) {
993 for( final Object name : protein_domain_collection.getProteinDomains() ) {
994 final BasicDomain protein_domain = ( BasicDomain ) name;
995 final String id = protein_domain.getDomainId();
996 if ( map.containsKey( id ) ) {
997 map.put( id, map.get( id ) + 1 );
1007 public static int getNumberOfNodesLackingName( final Phylogeny p, final StringBuilder names ) {
1008 final PhylogenyNodeIterator it = p.iteratorPostorder();
1010 while ( it.hasNext() ) {
1011 final PhylogenyNode n = it.next();
1012 if ( ForesterUtil.isEmpty( n.getName() )
1013 && ( !n.getNodeData().isHasTaxonomy() || ForesterUtil.isEmpty( n.getNodeData().getTaxonomy()
1014 .getScientificName() ) )
1015 && ( !n.getNodeData().isHasTaxonomy() || ForesterUtil.isEmpty( n.getNodeData().getTaxonomy()
1016 .getCommonName() ) ) ) {
1017 if ( n.getParent() != null ) {
1018 names.append( " " );
1019 names.append( n.getParent().getName() );
1021 final List l = n.getAllExternalDescendants();
1022 for( final Object object : l ) {
1023 System.out.println( l.toString() );
1032 * Returns true is Domain domain falls in an uninterrupted stretch of
1033 * covered positions.
1036 * @param covered_positions
1039 public static boolean isEngulfed( final Domain domain, final List<Boolean> covered_positions ) {
1040 for( int i = domain.getFrom(); i <= domain.getTo(); ++i ) {
1041 if ( ( i >= covered_positions.size() ) || ( covered_positions.get( i ) != true ) ) {
1048 public static void performDomainArchitectureAnalysis( final SortedMap<String, Set<String>> domain_architecutures,
1049 final SortedMap<String, Integer> domain_architecuture_counts,
1050 final int min_count,
1051 final File da_counts_outfile,
1052 final File unique_da_outfile ) {
1053 checkForOutputFileWriteability( da_counts_outfile );
1054 checkForOutputFileWriteability( unique_da_outfile );
1056 final BufferedWriter da_counts_out = new BufferedWriter( new FileWriter( da_counts_outfile ) );
1057 final BufferedWriter unique_da_out = new BufferedWriter( new FileWriter( unique_da_outfile ) );
1058 final Iterator<Entry<String, Integer>> it = domain_architecuture_counts.entrySet().iterator();
1059 while ( it.hasNext() ) {
1060 final Map.Entry<String, Integer> e = it.next();
1061 final String da = e.getKey();
1062 final int count = e.getValue();
1063 if ( count >= min_count ) {
1064 da_counts_out.write( da );
1065 da_counts_out.write( "\t" );
1066 da_counts_out.write( String.valueOf( count ) );
1067 da_counts_out.write( ForesterUtil.LINE_SEPARATOR );
1070 final Iterator<Entry<String, Set<String>>> it2 = domain_architecutures.entrySet().iterator();
1071 while ( it2.hasNext() ) {
1072 final Map.Entry<String, Set<String>> e2 = it2.next();
1073 final String genome = e2.getKey();
1074 final Set<String> das = e2.getValue();
1075 if ( das.contains( da ) ) {
1076 unique_da_out.write( genome );
1077 unique_da_out.write( "\t" );
1078 unique_da_out.write( da );
1079 unique_da_out.write( ForesterUtil.LINE_SEPARATOR );
1084 unique_da_out.close();
1085 da_counts_out.close();
1087 catch ( final IOException e ) {
1088 ForesterUtil.fatalError( surfacing.PRG_NAME, e.getMessage() );
1090 ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote distance matrices to \"" + da_counts_outfile + "\"" );
1091 ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote distance matrices to \"" + unique_da_outfile + "\"" );
1095 public static void preparePhylogeny( final Phylogeny p,
1096 final DomainParsimonyCalculator domain_parsimony,
1097 final String date_time,
1098 final String method,
1100 final String parameters_str ) {
1101 domain_parsimony.decoratePhylogenyWithDomains( p );
1102 final StringBuilder desc = new StringBuilder();
1103 desc.append( "[Method: " + method + "] [Date: " + date_time + "] " );
1104 desc.append( "[Cost: " + domain_parsimony.getCost() + "] " );
1105 desc.append( "[Gains: " + domain_parsimony.getTotalGains() + "] " );
1106 desc.append( "[Losses: " + domain_parsimony.getTotalLosses() + "] " );
1107 desc.append( "[Unchanged: " + domain_parsimony.getTotalUnchanged() + "] " );
1108 desc.append( "[Parameters: " + parameters_str + "]" );
1110 p.setDescription( desc.toString() );
1111 p.setConfidence( new Confidence( domain_parsimony.getCost(), "parsimony" ) );
1112 p.setRerootable( false );
1113 p.setRooted( true );
1117 * species | protein id | n-terminal domain | c-terminal domain | n-terminal domain per domain E-value | c-terminal domain per domain E-value
1121 static public StringBuffer proteinToDomainCombinations( final Protein protein,
1122 final String protein_id,
1123 final String separator ) {
1124 final StringBuffer sb = new StringBuffer();
1125 if ( protein.getSpecies() == null ) {
1126 throw new IllegalArgumentException( "species must not be null" );
1128 if ( ForesterUtil.isEmpty( protein.getSpecies().getSpeciesId() ) ) {
1129 throw new IllegalArgumentException( "species id must not be empty" );
1131 final List<Domain> domains = protein.getProteinDomains();
1132 if ( domains.size() > 1 ) {
1133 final Map<String, Integer> counts = new HashMap<String, Integer>();
1134 for( final Domain domain : domains ) {
1135 final String id = domain.getDomainId();
1136 if ( counts.containsKey( id ) ) {
1137 counts.put( id, counts.get( id ) + 1 );
1140 counts.put( id, 1 );
1143 final Set<String> dcs = new HashSet<String>();
1144 for( int i = 1; i < domains.size(); ++i ) {
1145 for( int j = 0; j < i; ++j ) {
1146 Domain domain_n = domains.get( i );
1147 Domain domain_c = domains.get( j );
1148 if ( domain_n.getFrom() > domain_c.getFrom() ) {
1149 domain_n = domains.get( j );
1150 domain_c = domains.get( i );
1152 final String dc = domain_n.getDomainId() + domain_c.getDomainId();
1153 if ( !dcs.contains( dc ) ) {
1155 sb.append( protein.getSpecies() );
1156 sb.append( separator );
1157 sb.append( protein_id );
1158 sb.append( separator );
1159 sb.append( domain_n.getDomainId() );
1160 sb.append( separator );
1161 sb.append( domain_c.getDomainId() );
1162 sb.append( separator );
1163 sb.append( domain_n.getPerDomainEvalue() );
1164 sb.append( separator );
1165 sb.append( domain_c.getPerDomainEvalue() );
1166 sb.append( separator );
1167 sb.append( counts.get( domain_n.getDomainId() ) );
1168 sb.append( separator );
1169 sb.append( counts.get( domain_c.getDomainId() ) );
1170 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() );
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 );
1207 * Example regarding engulfment: ------------0.1 ----------0.2 --0.3 =>
1208 * domain with 0.3 is ignored
1210 * -----------0.1 ----------0.2 --0.3 => domain with 0.3 is ignored
1213 * ------------0.1 ----------0.3 --0.2 => domains with 0.3 and 0.2 are _not_
1216 * @param max_allowed_overlap
1217 * maximal allowed overlap (inclusive) to be still considered not
1218 * overlapping (zero or negative value to allow any overlap)
1219 * @param remove_engulfed_domains
1220 * to remove domains which are completely engulfed by coverage of
1221 * domains with better support
1225 public static Protein removeOverlappingDomains( final int max_allowed_overlap,
1226 final boolean remove_engulfed_domains,
1227 final Protein protein ) {
1228 final Protein pruned_protein = new BasicProtein( protein.getProteinId().getId(), protein.getSpecies()
1229 .getSpeciesId(), protein.getLength() );
1230 final List<Domain> sorted = SurfacingUtil.sortDomainsWithAscendingConfidenceValues( protein );
1231 final List<Boolean> covered_positions = new ArrayList<Boolean>();
1232 for( final Domain domain : sorted ) {
1233 if ( ( ( max_allowed_overlap < 0 ) || ( SurfacingUtil.calculateOverlap( domain, covered_positions ) <= max_allowed_overlap ) )
1234 && ( !remove_engulfed_domains || !isEngulfed( domain, covered_positions ) ) ) {
1235 final int covered_positions_size = covered_positions.size();
1236 for( int i = covered_positions_size; i < domain.getFrom(); ++i ) {
1237 covered_positions.add( false );
1239 final int new_covered_positions_size = covered_positions.size();
1240 for( int i = domain.getFrom(); i <= domain.getTo(); ++i ) {
1241 if ( i < new_covered_positions_size ) {
1242 covered_positions.set( i, true );
1245 covered_positions.add( true );
1248 pruned_protein.addProteinDomain( domain );
1251 return pruned_protein;
1254 public static List<Domain> sortDomainsWithAscendingConfidenceValues( final Protein protein ) {
1255 final List<Domain> domains = new ArrayList<Domain>();
1256 for( final Domain d : protein.getProteinDomains() ) {
1259 Collections.sort( domains, SurfacingUtil.ASCENDING_CONFIDENCE_VALUE_ORDER );
1263 public static int storeDomainArchitectures( final String genome,
1264 final SortedMap<String, Set<String>> domain_architecutures,
1265 final List<Protein> protein_list,
1266 final Map<String, Integer> distinct_domain_architecuture_counts ) {
1267 final Set<String> da = new HashSet<String>();
1268 domain_architecutures.put( genome, da );
1269 for( final Protein protein : protein_list ) {
1270 final String da_str = ( ( BasicProtein ) protein ).toDomainArchitectureString( "~", 3, "=" );
1271 if ( !da.contains( da_str ) ) {
1272 if ( !distinct_domain_architecuture_counts.containsKey( da_str ) ) {
1273 distinct_domain_architecuture_counts.put( da_str, 1 );
1276 distinct_domain_architecuture_counts.put( da_str,
1277 distinct_domain_architecuture_counts.get( da_str ) + 1 );
1285 public static void writeAllDomainsChangedOnAllSubtrees( final Phylogeny p,
1286 final boolean get_gains,
1287 final String outdir,
1288 final String suffix_for_filename ) throws IOException {
1289 CharacterStateMatrix.GainLossStates state = CharacterStateMatrix.GainLossStates.GAIN;
1291 state = CharacterStateMatrix.GainLossStates.LOSS;
1293 final File base_dir = createBaseDirForPerNodeDomainFiles( surfacing.BASE_DIRECTORY_PER_SUBTREE_DOMAIN_GAIN_LOSS_FILES,
1297 for( final PhylogenyNodeIterator it = p.iteratorPostorder(); it.hasNext(); ) {
1298 final PhylogenyNode node = it.next();
1299 if ( !node.isExternal() ) {
1300 final SortedSet<String> domains = collectAllDomainsChangedOnSubtree( node, get_gains );
1301 if ( domains.size() > 0 ) {
1302 final Writer writer = ForesterUtil.createBufferedWriter( base_dir + ForesterUtil.FILE_SEPARATOR
1303 + node.getName() + suffix_for_filename );
1304 for( final String domain : domains ) {
1305 writer.write( domain );
1306 writer.write( ForesterUtil.LINE_SEPARATOR );
1314 public static void writeBinaryDomainCombinationsFileForGraphAnalysis( final String[][] input_file_properties,
1315 final File output_dir,
1316 final GenomeWideCombinableDomains gwcd,
1318 final GenomeWideCombinableDomainsSortOrder dc_sort_order ) {
1319 File dc_outfile_dot = new File( input_file_properties[ i ][ 1 ]
1320 + surfacing.DOMAIN_COMBINITONS_OUTPUTFILE_SUFFIX_FOR_GRAPH_ANALYSIS );
1321 if ( output_dir != null ) {
1322 dc_outfile_dot = new File( output_dir + ForesterUtil.FILE_SEPARATOR + dc_outfile_dot );
1324 checkForOutputFileWriteability( dc_outfile_dot );
1325 final SortedSet<BinaryDomainCombination> binary_combinations = createSetOfAllBinaryDomainCombinationsPerGenome( gwcd );
1327 final BufferedWriter out_dot = new BufferedWriter( new FileWriter( dc_outfile_dot ) );
1328 for( final BinaryDomainCombination bdc : binary_combinations ) {
1329 out_dot.write( bdc.toGraphDescribingLanguage( BinaryDomainCombination.OutputFormat.DOT, null, null )
1331 out_dot.write( SurfacingConstants.NL );
1335 catch ( final IOException e ) {
1336 ForesterUtil.fatalError( surfacing.PRG_NAME, e.getMessage() );
1338 ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote binary domain combination for \""
1339 + input_file_properties[ i ][ 0 ] + "\" (" + input_file_properties[ i ][ 1 ] + ", "
1340 + input_file_properties[ i ][ 2 ] + ") to: \"" + dc_outfile_dot + "\"" );
1343 public static void writeBinaryStatesMatrixAsListToFile( final CharacterStateMatrix<CharacterStateMatrix.GainLossStates> matrix,
1344 final CharacterStateMatrix.GainLossStates state,
1345 final String filename,
1346 final String indentifier_characters_separator,
1347 final String character_separator,
1348 final Map<String, String> descriptions ) {
1349 final File outfile = new File( filename );
1350 checkForOutputFileWriteability( outfile );
1351 final SortedSet<String> sorted_ids = new TreeSet<String>();
1352 for( int i = 0; i < matrix.getNumberOfIdentifiers(); ++i ) {
1353 sorted_ids.add( matrix.getIdentifier( i ) );
1356 final BufferedWriter out = new BufferedWriter( new FileWriter( outfile ) );
1357 for( final String id : sorted_ids ) {
1358 out.write( indentifier_characters_separator );
1359 out.write( "#" + id );
1360 out.write( indentifier_characters_separator );
1361 for( int c = 0; c < matrix.getNumberOfCharacters(); ++c ) {
1363 // using null to indicate either UNCHANGED_PRESENT or GAIN.
1364 if ( ( matrix.getState( id, c ) == state )
1365 || ( ( state == null ) && ( ( matrix.getState( id, c ) == CharacterStateMatrix.GainLossStates.GAIN ) || ( matrix
1366 .getState( id, c ) == CharacterStateMatrix.GainLossStates.UNCHANGED_PRESENT ) ) ) ) {
1367 out.write( matrix.getCharacter( c ) );
1368 if ( ( descriptions != null ) && !descriptions.isEmpty()
1369 && descriptions.containsKey( matrix.getCharacter( c ) ) ) {
1371 out.write( descriptions.get( matrix.getCharacter( c ) ) );
1373 out.write( character_separator );
1380 catch ( final IOException e ) {
1381 ForesterUtil.fatalError( surfacing.PRG_NAME, e.getMessage() );
1383 ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote characters list: \"" + filename + "\"" );
1386 public static void writeBinaryStatesMatrixAsListToFileForBinaryCombinationsForGraphAnalysis( final CharacterStateMatrix<CharacterStateMatrix.GainLossStates> matrix,
1387 final CharacterStateMatrix.GainLossStates state,
1388 final String filename,
1389 final String indentifier_characters_separator,
1390 final String character_separator,
1391 final BinaryDomainCombination.OutputFormat bc_output_format ) {
1392 final File outfile = new File( filename );
1393 checkForOutputFileWriteability( outfile );
1394 final SortedSet<String> sorted_ids = new TreeSet<String>();
1395 for( int i = 0; i < matrix.getNumberOfIdentifiers(); ++i ) {
1396 sorted_ids.add( matrix.getIdentifier( i ) );
1399 final BufferedWriter out = new BufferedWriter( new FileWriter( outfile ) );
1400 for( final String id : sorted_ids ) {
1401 out.write( indentifier_characters_separator );
1402 out.write( "#" + id );
1403 out.write( indentifier_characters_separator );
1404 for( int c = 0; c < matrix.getNumberOfCharacters(); ++c ) {
1406 // using null to indicate either UNCHANGED_PRESENT or GAIN.
1407 if ( ( matrix.getState( id, c ) == state )
1408 || ( ( state == null ) && ( ( matrix.getState( id, c ) == CharacterStateMatrix.GainLossStates.GAIN ) || ( matrix
1409 .getState( id, c ) == CharacterStateMatrix.GainLossStates.UNCHANGED_PRESENT ) ) ) ) {
1410 BinaryDomainCombination bdc = null;
1412 bdc = BasicBinaryDomainCombination.createInstance( matrix.getCharacter( c ) );
1414 catch ( final Exception e ) {
1415 ForesterUtil.fatalError( surfacing.PRG_NAME, e.getLocalizedMessage() );
1417 out.write( bdc.toGraphDescribingLanguage( bc_output_format, null, null ).toString() );
1418 out.write( character_separator );
1425 catch ( final IOException e ) {
1426 ForesterUtil.fatalError( surfacing.PRG_NAME, e.getMessage() );
1428 ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote characters list: \"" + filename + "\"" );
1431 public static void writeBinaryStatesMatrixToList( final Map<String, List<GoId>> domain_id_to_go_ids_map,
1432 final Map<GoId, GoTerm> go_id_to_term_map,
1433 final GoNameSpace go_namespace_limit,
1434 final boolean domain_combinations,
1435 final CharacterStateMatrix<CharacterStateMatrix.GainLossStates> matrix,
1436 final CharacterStateMatrix.GainLossStates state,
1437 final String filename,
1438 final String indentifier_characters_separator,
1439 final String character_separator,
1440 final String title_for_html,
1441 final String prefix_for_html,
1442 final Map<String, Set<String>>[] domain_id_to_secondary_features_maps,
1443 final SortedSet<String> all_pfams_encountered,
1444 final SortedSet<String> pfams_gained_or_lost,
1445 final String suffix_for_per_node_events_file,
1446 final Map<String, Integer> tax_code_to_id_map ) {
1447 if ( ( go_namespace_limit != null ) && ( ( go_id_to_term_map == null ) || ( go_id_to_term_map.size() < 1 ) ) ) {
1448 throw new IllegalArgumentException( "attempt to use GO namespace limit without a GO-id to term map" );
1450 else if ( ( ( domain_id_to_go_ids_map == null ) || ( domain_id_to_go_ids_map.size() < 1 ) ) ) {
1451 throw new IllegalArgumentException( "attempt to output detailed HTML without a Pfam to GO map" );
1453 else if ( ( ( go_id_to_term_map == null ) || ( go_id_to_term_map.size() < 1 ) ) ) {
1454 throw new IllegalArgumentException( "attempt to output detailed HTML without a GO-id to term map" );
1456 final File outfile = new File( filename );
1457 checkForOutputFileWriteability( outfile );
1458 final SortedSet<String> sorted_ids = new TreeSet<String>();
1459 for( int i = 0; i < matrix.getNumberOfIdentifiers(); ++i ) {
1460 sorted_ids.add( matrix.getIdentifier( i ) );
1463 final Writer out = new BufferedWriter( new FileWriter( outfile ) );
1464 final File per_node_go_mapped_domain_gain_loss_files_base_dir = createBaseDirForPerNodeDomainFiles( surfacing.BASE_DIRECTORY_PER_NODE_DOMAIN_GAIN_LOSS_FILES,
1465 domain_combinations,
1468 Writer per_node_go_mapped_domain_gain_loss_outfile_writer = null;
1469 File per_node_go_mapped_domain_gain_loss_outfile = null;
1470 int per_node_counter = 0;
1471 out.write( "<html>" );
1472 out.write( SurfacingConstants.NL );
1473 addHtmlHead( out, title_for_html );
1474 out.write( SurfacingConstants.NL );
1475 out.write( "<body>" );
1476 out.write( SurfacingConstants.NL );
1477 out.write( "<h1>" );
1478 out.write( SurfacingConstants.NL );
1479 out.write( title_for_html );
1480 out.write( SurfacingConstants.NL );
1481 out.write( "</h1>" );
1482 out.write( SurfacingConstants.NL );
1483 out.write( "<table>" );
1484 out.write( SurfacingConstants.NL );
1485 for( final String id : sorted_ids ) {
1486 final Matcher matcher = PATTERN_SP_STYLE_TAXONOMY.matcher( id );
1487 if ( matcher.matches() ) {
1490 out.write( "<tr>" );
1491 out.write( "<td>" );
1492 out.write( "<a href=\"#" + id + "\">" + id + "</a>" );
1493 out.write( "</td>" );
1494 out.write( "</tr>" );
1495 out.write( SurfacingConstants.NL );
1497 out.write( "</table>" );
1498 out.write( SurfacingConstants.NL );
1499 for( final String id : sorted_ids ) {
1500 final Matcher matcher = PATTERN_SP_STYLE_TAXONOMY.matcher( id );
1501 if ( matcher.matches() ) {
1504 out.write( SurfacingConstants.NL );
1505 out.write( "<h2>" );
1506 out.write( "<a name=\"" + id + "\">" + id + "</a>" );
1507 writeTaxonomyLinks( out, id, tax_code_to_id_map );
1508 out.write( "</h2>" );
1509 out.write( SurfacingConstants.NL );
1510 out.write( "<table>" );
1511 out.write( SurfacingConstants.NL );
1512 out.write( "<tr>" );
1513 out.write( "<td><b>" );
1514 out.write( "Pfam domain(s)" );
1515 out.write( "</b></td><td><b>" );
1516 out.write( "GO term acc" );
1517 out.write( "</b></td><td><b>" );
1518 out.write( "GO term" );
1519 out.write( "</b></td><td><b>" );
1520 out.write( "GO namespace" );
1521 out.write( "</b></td>" );
1522 out.write( "</tr>" );
1523 out.write( SurfacingConstants.NL );
1524 out.write( "</tr>" );
1525 out.write( SurfacingConstants.NL );
1526 per_node_counter = 0;
1527 if ( matrix.getNumberOfCharacters() > 0 ) {
1528 per_node_go_mapped_domain_gain_loss_outfile = new File( per_node_go_mapped_domain_gain_loss_files_base_dir
1529 + ForesterUtil.FILE_SEPARATOR + id + suffix_for_per_node_events_file );
1530 SurfacingUtil.checkForOutputFileWriteability( per_node_go_mapped_domain_gain_loss_outfile );
1531 per_node_go_mapped_domain_gain_loss_outfile_writer = ForesterUtil
1532 .createBufferedWriter( per_node_go_mapped_domain_gain_loss_outfile );
1535 per_node_go_mapped_domain_gain_loss_outfile = null;
1536 per_node_go_mapped_domain_gain_loss_outfile_writer = null;
1538 for( int c = 0; c < matrix.getNumberOfCharacters(); ++c ) {
1540 // using null to indicate either UNCHANGED_PRESENT or GAIN.
1541 if ( ( matrix.getState( id, c ) == state )
1542 || ( ( state == null ) && ( ( matrix.getState( id, c ) == CharacterStateMatrix.GainLossStates.UNCHANGED_PRESENT ) || ( matrix
1543 .getState( id, c ) == CharacterStateMatrix.GainLossStates.GAIN ) ) ) ) {
1544 final String character = matrix.getCharacter( c );
1545 String domain_0 = "";
1546 String domain_1 = "";
1547 if ( character.indexOf( BinaryDomainCombination.SEPARATOR ) > 0 ) {
1548 final String[] s = character.split( BinaryDomainCombination.SEPARATOR );
1549 if ( s.length != 2 ) {
1550 throw new AssertionError( "this should not have happened: unexpected format for domain combination: ["
1551 + character + "]" );
1557 domain_0 = character;
1559 writeDomainData( domain_id_to_go_ids_map,
1566 character_separator,
1567 domain_id_to_secondary_features_maps,
1569 all_pfams_encountered.add( domain_0 );
1570 if ( pfams_gained_or_lost != null ) {
1571 pfams_gained_or_lost.add( domain_0 );
1573 if ( !ForesterUtil.isEmpty( domain_1 ) ) {
1574 all_pfams_encountered.add( domain_1 );
1575 if ( pfams_gained_or_lost != null ) {
1576 pfams_gained_or_lost.add( domain_1 );
1579 if ( per_node_go_mapped_domain_gain_loss_outfile_writer != null ) {
1580 writeDomainsToIndividualFilePerTreeNode( per_node_go_mapped_domain_gain_loss_outfile_writer,
1587 if ( per_node_go_mapped_domain_gain_loss_outfile_writer != null ) {
1588 per_node_go_mapped_domain_gain_loss_outfile_writer.close();
1589 if ( per_node_counter < 1 ) {
1590 per_node_go_mapped_domain_gain_loss_outfile.delete();
1592 per_node_counter = 0;
1594 out.write( "</table>" );
1595 out.write( SurfacingConstants.NL );
1596 out.write( "<hr>" );
1597 out.write( SurfacingConstants.NL );
1598 } // for( final String id : sorted_ids ) {
1599 out.write( "</body>" );
1600 out.write( SurfacingConstants.NL );
1601 out.write( "</html>" );
1602 out.write( SurfacingConstants.NL );
1606 catch ( final IOException e ) {
1607 ForesterUtil.fatalError( surfacing.PRG_NAME, e.getMessage() );
1609 ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote characters detailed HTML list: \"" + filename + "\"" );
1612 public static void writeDomainCombinationsCountsFile( final String[][] input_file_properties,
1613 final File output_dir,
1614 final Writer per_genome_domain_promiscuity_statistics_writer,
1615 final GenomeWideCombinableDomains gwcd,
1617 final GenomeWideCombinableDomains.GenomeWideCombinableDomainsSortOrder dc_sort_order ) {
1618 File dc_outfile = new File( input_file_properties[ i ][ 1 ]
1619 + surfacing.DOMAIN_COMBINITON_COUNTS_OUTPUTFILE_SUFFIX );
1620 if ( output_dir != null ) {
1621 dc_outfile = new File( output_dir + ForesterUtil.FILE_SEPARATOR + dc_outfile );
1623 checkForOutputFileWriteability( dc_outfile );
1625 final BufferedWriter out = new BufferedWriter( new FileWriter( dc_outfile ) );
1626 out.write( gwcd.toStringBuilder( dc_sort_order ).toString() );
1629 catch ( final IOException e ) {
1630 ForesterUtil.fatalError( surfacing.PRG_NAME, e.getMessage() );
1632 final DescriptiveStatistics stats = gwcd.getPerGenomeDomainPromiscuityStatistics();
1634 per_genome_domain_promiscuity_statistics_writer.write( input_file_properties[ i ][ 1 ] + "\t" );
1635 per_genome_domain_promiscuity_statistics_writer.write( FORMATTER_3.format( stats.arithmeticMean() ) + "\t" );
1636 if ( stats.getN() < 2 ) {
1637 per_genome_domain_promiscuity_statistics_writer.write( "n/a" + "\t" );
1640 per_genome_domain_promiscuity_statistics_writer.write( FORMATTER_3.format( stats
1641 .sampleStandardDeviation() ) + "\t" );
1643 per_genome_domain_promiscuity_statistics_writer.write( FORMATTER_3.format( stats.median() ) + "\t" );
1644 per_genome_domain_promiscuity_statistics_writer.write( ( int ) stats.getMin() + "\t" );
1645 per_genome_domain_promiscuity_statistics_writer.write( ( int ) stats.getMax() + "\t" );
1646 per_genome_domain_promiscuity_statistics_writer.write( stats.getN() + "\t" );
1647 final SortedSet<String> mpds = gwcd.getMostPromiscuosDomain();
1648 for( final String mpd : mpds ) {
1649 per_genome_domain_promiscuity_statistics_writer.write( mpd + " " );
1651 per_genome_domain_promiscuity_statistics_writer.write( ForesterUtil.LINE_SEPARATOR );
1653 catch ( final IOException e ) {
1654 ForesterUtil.fatalError( surfacing.PRG_NAME, e.getMessage() );
1656 if ( input_file_properties[ i ].length == 3 ) {
1657 ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote domain combination counts for \""
1658 + input_file_properties[ i ][ 0 ] + "\" (" + input_file_properties[ i ][ 1 ] + ", "
1659 + input_file_properties[ i ][ 2 ] + ") to: \"" + dc_outfile + "\"" );
1662 ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote domain combination counts for \""
1663 + input_file_properties[ i ][ 0 ] + "\" (" + input_file_properties[ i ][ 1 ] + ") to: \""
1664 + dc_outfile + "\"" );
1668 public static DescriptiveStatistics writeDomainSimilaritiesToFile( final StringBuilder html_desc,
1669 final StringBuilder html_title,
1670 final Writer single_writer,
1671 Map<Character, Writer> split_writers,
1672 final SortedSet<DomainSimilarity> similarities,
1673 final boolean treat_as_binary,
1674 final List<Species> species_order,
1675 final PrintableDomainSimilarity.PRINT_OPTION print_option,
1676 final DomainSimilarity.DomainSimilarityScoring scoring,
1677 final boolean verbose,
1678 final Map<String, Integer> tax_code_to_id_map,
1679 final boolean print_some_stats )
1680 throws IOException {
1681 DescriptiveStatistics stats = null;
1682 AsciiHistogram histo = null;
1683 if ( print_some_stats ) {
1684 stats = new BasicDescriptiveStatistics();
1685 final String histogram_title = "score mean distribution:";
1686 for( final DomainSimilarity similarity : similarities ) {
1687 stats.addValue( similarity.getMeanSimilarityScore() );
1690 if ( stats.getMin() < stats.getMax() ) {
1691 histo = new AsciiHistogram( stats, histogram_title );
1694 catch ( final Exception e ) {
1698 if ( ( single_writer != null ) && ( ( split_writers == null ) || split_writers.isEmpty() ) ) {
1699 split_writers = new HashMap<Character, Writer>();
1700 split_writers.put( '_', single_writer );
1702 switch ( print_option ) {
1703 case SIMPLE_TAB_DELIMITED:
1706 for( final Character key : split_writers.keySet() ) {
1707 final Writer w = split_writers.get( key );
1708 w.write( "<html>" );
1709 w.write( SurfacingConstants.NL );
1711 addHtmlHead( w, "DC analysis (" + html_title + ") " + key.toString().toUpperCase() );
1714 addHtmlHead( w, "DC analysis (" + html_title + ")" );
1716 w.write( SurfacingConstants.NL );
1717 w.write( "<body>" );
1718 w.write( SurfacingConstants.NL );
1719 w.write( html_desc.toString() );
1720 w.write( SurfacingConstants.NL );
1721 if ( print_some_stats ) {
1722 printSomeStats( stats, histo, w );
1725 w.write( SurfacingConstants.NL );
1727 w.write( SurfacingConstants.NL );
1728 w.write( "<table>" );
1729 w.write( SurfacingConstants.NL );
1730 w.write( "<tr><td><b>Domains:</b></td></tr>" );
1731 w.write( SurfacingConstants.NL );
1736 for( final DomainSimilarity similarity : similarities ) {
1737 if ( ( species_order != null ) && !species_order.isEmpty() ) {
1738 ( ( PrintableDomainSimilarity ) similarity ).setSpeciesOrder( species_order );
1740 if ( single_writer != null ) {
1741 single_writer.write( "<tr><td><b><a href=\"#" + similarity.getDomainId() + "\">"
1742 + similarity.getDomainId() + "</a></b></td></tr>" );
1743 single_writer.write( SurfacingConstants.NL );
1746 Writer local_writer = split_writers.get( ( similarity.getDomainId().charAt( 0 ) + "" ).toLowerCase()
1748 if ( local_writer == null ) {
1749 local_writer = split_writers.get( '0' );
1751 local_writer.write( "<tr><td><b><a href=\"#" + similarity.getDomainId() + "\">"
1752 + similarity.getDomainId() + "</a></b></td></tr>" );
1753 local_writer.write( SurfacingConstants.NL );
1756 for( final Writer w : split_writers.values() ) {
1757 w.write( "</table>" );
1758 w.write( SurfacingConstants.NL );
1760 w.write( SurfacingConstants.NL );
1761 w.write( "<table>" );
1762 w.write( SurfacingConstants.NL );
1765 for( final DomainSimilarity similarity : similarities ) {
1766 if ( ( species_order != null ) && !species_order.isEmpty() ) {
1767 ( ( PrintableDomainSimilarity ) similarity ).setSpeciesOrder( species_order );
1769 if ( single_writer != null ) {
1770 single_writer.write( similarity.toStringBuffer( print_option, tax_code_to_id_map ).toString() );
1771 single_writer.write( SurfacingConstants.NL );
1774 Writer local_writer = split_writers.get( ( similarity.getDomainId().charAt( 0 ) + "" ).toLowerCase()
1776 if ( local_writer == null ) {
1777 local_writer = split_writers.get( '0' );
1779 local_writer.write( similarity.toStringBuffer( print_option, tax_code_to_id_map ).toString() );
1780 local_writer.write( SurfacingConstants.NL );
1783 switch ( print_option ) {
1785 for( final Writer w : split_writers.values() ) {
1786 w.write( SurfacingConstants.NL );
1787 w.write( "</table>" );
1788 w.write( SurfacingConstants.NL );
1789 w.write( "</font>" );
1790 w.write( SurfacingConstants.NL );
1791 w.write( "</body>" );
1792 w.write( SurfacingConstants.NL );
1793 w.write( "</html>" );
1794 w.write( SurfacingConstants.NL );
1798 for( final Writer w : split_writers.values() ) {
1804 private static void printSomeStats( final DescriptiveStatistics stats, final AsciiHistogram histo, final Writer w )
1805 throws IOException {
1808 w.write( SurfacingConstants.NL );
1809 w.write( "<tt><pre>" );
1810 w.write( SurfacingConstants.NL );
1811 if ( histo != null ) {
1812 w.write( histo.toStringBuffer( 20, '|', 40, 5 ).toString() );
1813 w.write( SurfacingConstants.NL );
1815 w.write( "</pre></tt>" );
1816 w.write( SurfacingConstants.NL );
1817 w.write( "<table>" );
1818 w.write( SurfacingConstants.NL );
1819 w.write( "<tr><td>N: </td><td>" + stats.getN() + "</td></tr>" );
1820 w.write( SurfacingConstants.NL );
1821 w.write( "<tr><td>Min: </td><td>" + stats.getMin() + "</td></tr>" );
1822 w.write( SurfacingConstants.NL );
1823 w.write( "<tr><td>Max: </td><td>" + stats.getMax() + "</td></tr>" );
1824 w.write( SurfacingConstants.NL );
1825 w.write( "<tr><td>Mean: </td><td>" + stats.arithmeticMean() + "</td></tr>" );
1826 w.write( SurfacingConstants.NL );
1827 if ( stats.getN() > 1 ) {
1828 w.write( "<tr><td>SD: </td><td>" + stats.sampleStandardDeviation() + "</td></tr>" );
1831 w.write( "<tr><td>SD: </td><td>n/a</td></tr>" );
1833 w.write( SurfacingConstants.NL );
1834 w.write( "</table>" );
1835 w.write( SurfacingConstants.NL );
1837 w.write( SurfacingConstants.NL );
1840 public static void writeMatrixToFile( final CharacterStateMatrix<?> matrix,
1841 final String filename,
1842 final Format format ) {
1843 final File outfile = new File( filename );
1844 checkForOutputFileWriteability( outfile );
1846 final BufferedWriter out = new BufferedWriter( new FileWriter( outfile ) );
1847 matrix.toWriter( out, format );
1851 catch ( final IOException e ) {
1852 ForesterUtil.fatalError( surfacing.PRG_NAME, e.getMessage() );
1854 ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote matrix: \"" + filename + "\"" );
1857 public static void writeMatrixToFile( final File matrix_outfile, final List<DistanceMatrix> matrices ) {
1858 checkForOutputFileWriteability( matrix_outfile );
1860 final BufferedWriter out = new BufferedWriter( new FileWriter( matrix_outfile ) );
1861 for( final DistanceMatrix distance_matrix : matrices ) {
1862 out.write( distance_matrix.toStringBuffer( DistanceMatrix.Format.PHYLIP ).toString() );
1863 out.write( ForesterUtil.LINE_SEPARATOR );
1868 catch ( final IOException e ) {
1869 ForesterUtil.fatalError( surfacing.PRG_NAME, e.getMessage() );
1871 ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote distance matrices to \"" + matrix_outfile + "\"" );
1874 public static void writePhylogenyToFile( final Phylogeny phylogeny, final String filename ) {
1875 final PhylogenyWriter writer = new PhylogenyWriter();
1877 writer.toPhyloXML( new File( filename ), phylogeny, 1 );
1879 catch ( final IOException e ) {
1880 ForesterUtil.printWarningMessage( surfacing.PRG_NAME, "failed to write phylogeny to \"" + filename + "\": "
1883 ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote phylogeny to \"" + filename + "\"" );
1886 public static void writeTaxonomyLinks( final Writer writer,
1887 final String species,
1888 final Map<String, Integer> tax_code_to_id_map ) throws IOException {
1889 if ( ( species.length() > 1 ) && ( species.indexOf( '_' ) < 1 ) ) {
1890 writer.write( " [" );
1891 if ( ( tax_code_to_id_map != null ) && tax_code_to_id_map.containsKey( species ) ) {
1892 writer.write( "<a href=\"" + SurfacingConstants.UNIPROT_TAXONOMY_ID_LINK
1893 + tax_code_to_id_map.get( species ) + "\" target=\"taxonomy_window\">uniprot</a>" );
1896 writer.write( "<a href=\"" + SurfacingConstants.EOL_LINK + species
1897 + "\" target=\"taxonomy_window\">eol</a>" );
1898 writer.write( "|" );
1899 writer.write( "<a href=\"" + SurfacingConstants.GOOGLE_SCHOLAR_SEARCH + species
1900 + "\" target=\"taxonomy_window\">scholar</a>" );
1901 writer.write( "|" );
1902 writer.write( "<a href=\"" + SurfacingConstants.GOOGLE_WEB_SEARCH_LINK + species
1903 + "\" target=\"taxonomy_window\">google</a>" );
1905 writer.write( "]" );
1909 private final static void addToCountMap( final Map<String, Integer> map, final String s ) {
1910 if ( map.containsKey( s ) ) {
1911 map.put( s, map.get( s ) + 1 );
1918 private static void calculateIndependentDomainCombinationGains( final Phylogeny local_phylogeny_l,
1919 final String outfilename_for_counts,
1920 final String outfilename_for_dc,
1921 final String outfilename_for_dc_for_go_mapping,
1922 final String outfilename_for_dc_for_go_mapping_unique,
1923 final String outfilename_for_rank_counts,
1924 final String outfilename_for_ancestor_species_counts,
1925 final String outfilename_for_protein_stats,
1926 final Map<String, DescriptiveStatistics> protein_length_stats_by_dc,
1927 final Map<String, DescriptiveStatistics> domain_number_stats_by_dc,
1928 final Map<String, DescriptiveStatistics> domain_length_stats_by_domain ) {
1931 // if ( protein_length_stats_by_dc != null ) {
1932 // for( final Entry<?, DescriptiveStatistics> entry : protein_length_stats_by_dc.entrySet() ) {
1933 // System.out.print( entry.getKey().toString() );
1934 // System.out.print( ": " );
1935 // double[] a = entry.getValue().getDataAsDoubleArray();
1936 // for( int i = 0; i < a.length; i++ ) {
1937 // System.out.print( a[ i ] + " " );
1939 // System.out.println();
1942 // if ( domain_number_stats_by_dc != null ) {
1943 // for( final Entry<?, DescriptiveStatistics> entry : domain_number_stats_by_dc.entrySet() ) {
1944 // System.out.print( entry.getKey().toString() );
1945 // System.out.print( ": " );
1946 // double[] a = entry.getValue().getDataAsDoubleArray();
1947 // for( int i = 0; i < a.length; i++ ) {
1948 // System.out.print( a[ i ] + " " );
1950 // System.out.println();
1954 final BufferedWriter out_counts = new BufferedWriter( new FileWriter( outfilename_for_counts ) );
1955 final BufferedWriter out_dc = new BufferedWriter( new FileWriter( outfilename_for_dc ) );
1956 final BufferedWriter out_dc_for_go_mapping = new BufferedWriter( new FileWriter( outfilename_for_dc_for_go_mapping ) );
1957 final BufferedWriter out_dc_for_go_mapping_unique = new BufferedWriter( new FileWriter( outfilename_for_dc_for_go_mapping_unique ) );
1958 final SortedMap<String, Integer> dc_gain_counts = new TreeMap<String, Integer>();
1959 for( final PhylogenyNodeIterator it = local_phylogeny_l.iteratorPostorder(); it.hasNext(); ) {
1960 final PhylogenyNode n = it.next();
1961 final Set<String> gained_dc = n.getNodeData().getBinaryCharacters().getGainedCharacters();
1962 for( final String dc : gained_dc ) {
1963 if ( dc_gain_counts.containsKey( dc ) ) {
1964 dc_gain_counts.put( dc, dc_gain_counts.get( dc ) + 1 );
1967 dc_gain_counts.put( dc, 1 );
1971 final SortedMap<Integer, Integer> histogram = new TreeMap<Integer, Integer>();
1972 final SortedMap<Integer, StringBuilder> domain_lists = new TreeMap<Integer, StringBuilder>();
1973 final SortedMap<Integer, DescriptiveStatistics> dc_reapp_counts_to_protein_length_stats = new TreeMap<Integer, DescriptiveStatistics>();
1974 final SortedMap<Integer, DescriptiveStatistics> dc_reapp_counts_to_domain_number_stats = new TreeMap<Integer, DescriptiveStatistics>();
1975 final SortedMap<Integer, DescriptiveStatistics> dc_reapp_counts_to_domain_lengths_stats = new TreeMap<Integer, DescriptiveStatistics>();
1976 final SortedMap<Integer, PriorityQueue<String>> domain_lists_go = new TreeMap<Integer, PriorityQueue<String>>();
1977 final SortedMap<Integer, SortedSet<String>> domain_lists_go_unique = new TreeMap<Integer, SortedSet<String>>();
1978 final Set<String> dcs = dc_gain_counts.keySet();
1979 final SortedSet<String> more_than_once = new TreeSet<String>();
1980 DescriptiveStatistics gained_once_lengths_stats = new BasicDescriptiveStatistics();
1981 DescriptiveStatistics gained_once_domain_count_stats = new BasicDescriptiveStatistics();
1982 DescriptiveStatistics gained_multiple_times_lengths_stats = new BasicDescriptiveStatistics();
1983 final DescriptiveStatistics gained_multiple_times_domain_count_stats = new BasicDescriptiveStatistics();
1984 long gained_multiple_times_domain_length_sum = 0;
1985 long gained_once_domain_length_sum = 0;
1986 long gained_multiple_times_domain_length_count = 0;
1987 long gained_once_domain_length_count = 0;
1988 for( final String dc : dcs ) {
1989 final int count = dc_gain_counts.get( dc );
1990 if ( histogram.containsKey( count ) ) {
1991 histogram.put( count, histogram.get( count ) + 1 );
1992 domain_lists.get( count ).append( ", " + dc );
1993 domain_lists_go.get( count ).addAll( splitDomainCombination( dc ) );
1994 domain_lists_go_unique.get( count ).addAll( splitDomainCombination( dc ) );
1997 histogram.put( count, 1 );
1998 domain_lists.put( count, new StringBuilder( dc ) );
1999 final PriorityQueue<String> q = new PriorityQueue<String>();
2000 q.addAll( splitDomainCombination( dc ) );
2001 domain_lists_go.put( count, q );
2002 final SortedSet<String> set = new TreeSet<String>();
2003 set.addAll( splitDomainCombination( dc ) );
2004 domain_lists_go_unique.put( count, set );
2006 if ( protein_length_stats_by_dc != null ) {
2007 if ( !dc_reapp_counts_to_protein_length_stats.containsKey( count ) ) {
2008 dc_reapp_counts_to_protein_length_stats.put( count, new BasicDescriptiveStatistics() );
2010 dc_reapp_counts_to_protein_length_stats.get( count ).addValue( protein_length_stats_by_dc.get( dc )
2011 .arithmeticMean() );
2013 if ( domain_number_stats_by_dc != null ) {
2014 if ( !dc_reapp_counts_to_domain_number_stats.containsKey( count ) ) {
2015 dc_reapp_counts_to_domain_number_stats.put( count, new BasicDescriptiveStatistics() );
2017 dc_reapp_counts_to_domain_number_stats.get( count ).addValue( domain_number_stats_by_dc.get( dc )
2018 .arithmeticMean() );
2020 if ( domain_length_stats_by_domain != null ) {
2021 if ( !dc_reapp_counts_to_domain_lengths_stats.containsKey( count ) ) {
2022 dc_reapp_counts_to_domain_lengths_stats.put( count, new BasicDescriptiveStatistics() );
2024 final String[] ds = dc.split( "=" );
2025 dc_reapp_counts_to_domain_lengths_stats.get( count ).addValue( domain_length_stats_by_domain
2026 .get( ds[ 0 ] ).arithmeticMean() );
2027 dc_reapp_counts_to_domain_lengths_stats.get( count ).addValue( domain_length_stats_by_domain
2028 .get( ds[ 1 ] ).arithmeticMean() );
2031 more_than_once.add( dc );
2032 if ( protein_length_stats_by_dc != null ) {
2033 final DescriptiveStatistics s = protein_length_stats_by_dc.get( dc );
2034 for( final double element : s.getData() ) {
2035 gained_multiple_times_lengths_stats.addValue( element );
2038 if ( domain_number_stats_by_dc != null ) {
2039 final DescriptiveStatistics s = domain_number_stats_by_dc.get( dc );
2040 for( final double element : s.getData() ) {
2041 gained_multiple_times_domain_count_stats.addValue( element );
2044 if ( domain_length_stats_by_domain != null ) {
2045 final String[] ds = dc.split( "=" );
2046 final DescriptiveStatistics s0 = domain_length_stats_by_domain.get( ds[ 0 ] );
2047 final DescriptiveStatistics s1 = domain_length_stats_by_domain.get( ds[ 1 ] );
2048 for( final double element : s0.getData() ) {
2049 gained_multiple_times_domain_length_sum += element;
2050 ++gained_multiple_times_domain_length_count;
2052 for( final double element : s1.getData() ) {
2053 gained_multiple_times_domain_length_sum += element;
2054 ++gained_multiple_times_domain_length_count;
2059 if ( protein_length_stats_by_dc != null ) {
2060 final DescriptiveStatistics s = protein_length_stats_by_dc.get( dc );
2061 for( final double element : s.getData() ) {
2062 gained_once_lengths_stats.addValue( element );
2065 if ( domain_number_stats_by_dc != null ) {
2066 final DescriptiveStatistics s = domain_number_stats_by_dc.get( dc );
2067 for( final double element : s.getData() ) {
2068 gained_once_domain_count_stats.addValue( element );
2071 if ( domain_length_stats_by_domain != null ) {
2072 final String[] ds = dc.split( "=" );
2073 final DescriptiveStatistics s0 = domain_length_stats_by_domain.get( ds[ 0 ] );
2074 final DescriptiveStatistics s1 = domain_length_stats_by_domain.get( ds[ 1 ] );
2075 for( final double element : s0.getData() ) {
2076 gained_once_domain_length_sum += element;
2077 ++gained_once_domain_length_count;
2079 for( final double element : s1.getData() ) {
2080 gained_once_domain_length_sum += element;
2081 ++gained_once_domain_length_count;
2086 final Set<Integer> histogram_keys = histogram.keySet();
2087 for( final Integer histogram_key : histogram_keys ) {
2088 final int count = histogram.get( histogram_key );
2089 final StringBuilder dc = domain_lists.get( histogram_key );
2090 out_counts.write( histogram_key + "\t" + count + ForesterUtil.LINE_SEPARATOR );
2091 out_dc.write( histogram_key + "\t" + dc + ForesterUtil.LINE_SEPARATOR );
2092 out_dc_for_go_mapping.write( "#" + histogram_key + ForesterUtil.LINE_SEPARATOR );
2093 final Object[] sorted = domain_lists_go.get( histogram_key ).toArray();
2094 Arrays.sort( sorted );
2095 for( final Object domain : sorted ) {
2096 out_dc_for_go_mapping.write( domain + ForesterUtil.LINE_SEPARATOR );
2098 out_dc_for_go_mapping_unique.write( "#" + histogram_key + ForesterUtil.LINE_SEPARATOR );
2099 for( final String domain : domain_lists_go_unique.get( histogram_key ) ) {
2100 out_dc_for_go_mapping_unique.write( domain + ForesterUtil.LINE_SEPARATOR );
2105 out_dc_for_go_mapping.close();
2106 out_dc_for_go_mapping_unique.close();
2107 final SortedMap<String, Integer> lca_rank_counts = new TreeMap<String, Integer>();
2108 final SortedMap<String, Integer> lca_ancestor_species_counts = new TreeMap<String, Integer>();
2109 for( final String dc : more_than_once ) {
2110 final List<PhylogenyNode> nodes = new ArrayList<PhylogenyNode>();
2111 for( final PhylogenyNodeIterator it = local_phylogeny_l.iteratorExternalForward(); it.hasNext(); ) {
2112 final PhylogenyNode n = it.next();
2113 if ( n.getNodeData().getBinaryCharacters().getGainedCharacters().contains( dc ) ) {
2117 for( int i = 0; i < ( nodes.size() - 1 ); ++i ) {
2118 for( int j = i + 1; j < nodes.size(); ++j ) {
2119 final PhylogenyNode lca = PhylogenyMethods.calculateLCA( nodes.get( i ), nodes.get( j ) );
2120 String rank = "unknown";
2121 if ( lca.getNodeData().isHasTaxonomy()
2122 && !ForesterUtil.isEmpty( lca.getNodeData().getTaxonomy().getRank() ) ) {
2123 rank = lca.getNodeData().getTaxonomy().getRank();
2125 addToCountMap( lca_rank_counts, rank );
2127 if ( lca.getNodeData().isHasTaxonomy()
2128 && !ForesterUtil.isEmpty( lca.getNodeData().getTaxonomy().getScientificName() ) ) {
2129 lca_species = lca.getNodeData().getTaxonomy().getScientificName();
2131 else if ( lca.getNodeData().isHasTaxonomy()
2132 && !ForesterUtil.isEmpty( lca.getNodeData().getTaxonomy().getCommonName() ) ) {
2133 lca_species = lca.getNodeData().getTaxonomy().getCommonName();
2136 lca_species = lca.getName();
2138 addToCountMap( lca_ancestor_species_counts, lca_species );
2142 final BufferedWriter out_for_rank_counts = new BufferedWriter( new FileWriter( outfilename_for_rank_counts ) );
2143 final BufferedWriter out_for_ancestor_species_counts = new BufferedWriter( new FileWriter( outfilename_for_ancestor_species_counts ) );
2144 ForesterUtil.map2writer( out_for_rank_counts, lca_rank_counts, "\t", ForesterUtil.LINE_SEPARATOR );
2145 ForesterUtil.map2writer( out_for_ancestor_species_counts,
2146 lca_ancestor_species_counts,
2148 ForesterUtil.LINE_SEPARATOR );
2149 out_for_rank_counts.close();
2150 out_for_ancestor_species_counts.close();
2151 if ( !ForesterUtil.isEmpty( outfilename_for_protein_stats )
2152 && ( ( domain_length_stats_by_domain != null ) || ( protein_length_stats_by_dc != null ) || ( domain_number_stats_by_dc != null ) ) ) {
2153 final BufferedWriter w = new BufferedWriter( new FileWriter( outfilename_for_protein_stats ) );
2154 w.write( "Domain Lengths: " );
2156 if ( domain_length_stats_by_domain != null ) {
2157 for( final Entry<Integer, DescriptiveStatistics> entry : dc_reapp_counts_to_domain_lengths_stats
2159 w.write( entry.getKey().toString() );
2160 w.write( "\t" + entry.getValue().arithmeticMean() );
2161 w.write( "\t" + entry.getValue().median() );
2168 w.write( "Protein Lengths: " );
2170 if ( protein_length_stats_by_dc != null ) {
2171 for( final Entry<Integer, DescriptiveStatistics> entry : dc_reapp_counts_to_protein_length_stats
2173 w.write( entry.getKey().toString() );
2174 w.write( "\t" + entry.getValue().arithmeticMean() );
2175 w.write( "\t" + entry.getValue().median() );
2182 w.write( "Number of domains: " );
2184 if ( domain_number_stats_by_dc != null ) {
2185 for( final Entry<Integer, DescriptiveStatistics> entry : dc_reapp_counts_to_domain_number_stats
2187 w.write( entry.getKey().toString() );
2188 w.write( "\t" + entry.getValue().arithmeticMean() );
2189 w.write( "\t" + entry.getValue().median() );
2196 w.write( "Gained once, domain lengths:" );
2198 w.write( "N: " + gained_once_domain_length_count );
2200 w.write( "Avg: " + ( ( double ) gained_once_domain_length_sum / gained_once_domain_length_count ) );
2203 w.write( "Gained multiple times, domain lengths:" );
2205 w.write( "N: " + gained_multiple_times_domain_length_count );
2208 + ( ( double ) gained_multiple_times_domain_length_sum / gained_multiple_times_domain_length_count ) );
2213 w.write( "Gained once, protein lengths:" );
2215 w.write( gained_once_lengths_stats.toString() );
2216 gained_once_lengths_stats = null;
2219 w.write( "Gained once, domain counts:" );
2221 w.write( gained_once_domain_count_stats.toString() );
2222 gained_once_domain_count_stats = null;
2225 w.write( "Gained multiple times, protein lengths:" );
2227 w.write( gained_multiple_times_lengths_stats.toString() );
2228 gained_multiple_times_lengths_stats = null;
2231 w.write( "Gained multiple times, domain counts:" );
2233 w.write( gained_multiple_times_domain_count_stats.toString() );
2238 catch ( final IOException e ) {
2239 ForesterUtil.printWarningMessage( surfacing.PRG_NAME, "Failure to write: " + e );
2241 ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote independent domain combination gains fitch counts to ["
2242 + outfilename_for_counts + "]" );
2243 ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote independent domain combination gains fitch lists to ["
2244 + outfilename_for_dc + "]" );
2245 ForesterUtil.programMessage( surfacing.PRG_NAME,
2246 "Wrote independent domain combination gains fitch lists to (for GO mapping) ["
2247 + outfilename_for_dc_for_go_mapping + "]" );
2248 ForesterUtil.programMessage( surfacing.PRG_NAME,
2249 "Wrote independent domain combination gains fitch lists to (for GO mapping, unique) ["
2250 + outfilename_for_dc_for_go_mapping_unique + "]" );
2253 private static SortedSet<String> collectAllDomainsChangedOnSubtree( final PhylogenyNode subtree_root,
2254 final boolean get_gains ) {
2255 final SortedSet<String> domains = new TreeSet<String>();
2256 for( final PhylogenyNode descendant : PhylogenyMethods.getAllDescendants( subtree_root ) ) {
2257 final BinaryCharacters chars = descendant.getNodeData().getBinaryCharacters();
2259 domains.addAll( chars.getGainedCharacters() );
2262 domains.addAll( chars.getLostCharacters() );
2268 private static File createBaseDirForPerNodeDomainFiles( final String base_dir,
2269 final boolean domain_combinations,
2270 final CharacterStateMatrix.GainLossStates state,
2271 final String outfile ) {
2272 File per_node_go_mapped_domain_gain_loss_files_base_dir = new File( new File( outfile ).getParent()
2273 + ForesterUtil.FILE_SEPARATOR + base_dir );
2274 if ( !per_node_go_mapped_domain_gain_loss_files_base_dir.exists() ) {
2275 per_node_go_mapped_domain_gain_loss_files_base_dir.mkdir();
2277 if ( domain_combinations ) {
2278 per_node_go_mapped_domain_gain_loss_files_base_dir = new File( per_node_go_mapped_domain_gain_loss_files_base_dir
2279 + ForesterUtil.FILE_SEPARATOR + "DC" );
2282 per_node_go_mapped_domain_gain_loss_files_base_dir = new File( per_node_go_mapped_domain_gain_loss_files_base_dir
2283 + ForesterUtil.FILE_SEPARATOR + "DOMAINS" );
2285 if ( !per_node_go_mapped_domain_gain_loss_files_base_dir.exists() ) {
2286 per_node_go_mapped_domain_gain_loss_files_base_dir.mkdir();
2288 if ( state == GainLossStates.GAIN ) {
2289 per_node_go_mapped_domain_gain_loss_files_base_dir = new File( per_node_go_mapped_domain_gain_loss_files_base_dir
2290 + ForesterUtil.FILE_SEPARATOR + "GAINS" );
2292 else if ( state == GainLossStates.LOSS ) {
2293 per_node_go_mapped_domain_gain_loss_files_base_dir = new File( per_node_go_mapped_domain_gain_loss_files_base_dir
2294 + ForesterUtil.FILE_SEPARATOR + "LOSSES" );
2297 per_node_go_mapped_domain_gain_loss_files_base_dir = new File( per_node_go_mapped_domain_gain_loss_files_base_dir
2298 + ForesterUtil.FILE_SEPARATOR + "PRESENT" );
2300 if ( !per_node_go_mapped_domain_gain_loss_files_base_dir.exists() ) {
2301 per_node_go_mapped_domain_gain_loss_files_base_dir.mkdir();
2303 return per_node_go_mapped_domain_gain_loss_files_base_dir;
2306 private static SortedSet<BinaryDomainCombination> createSetOfAllBinaryDomainCombinationsPerGenome( final GenomeWideCombinableDomains gwcd ) {
2307 final SortedMap<String, CombinableDomains> cds = gwcd.getAllCombinableDomainsIds();
2308 final SortedSet<BinaryDomainCombination> binary_combinations = new TreeSet<BinaryDomainCombination>();
2309 for( final String domain_id : cds.keySet() ) {
2310 final CombinableDomains cd = cds.get( domain_id );
2311 binary_combinations.addAll( cd.toBinaryDomainCombinations() );
2313 return binary_combinations;
2316 private static List<String> splitDomainCombination( final String dc ) {
2317 final String[] s = dc.split( "=" );
2318 if ( s.length != 2 ) {
2319 ForesterUtil.printErrorMessage( surfacing.PRG_NAME, "Stringyfied domain combination has illegal format: "
2323 final List<String> l = new ArrayList<String>( 2 );
2329 private static void writeAllEncounteredPfamsToFile( final Map<String, List<GoId>> domain_id_to_go_ids_map,
2330 final Map<GoId, GoTerm> go_id_to_term_map,
2331 final String outfile_name,
2332 final SortedSet<String> all_pfams_encountered ) {
2333 final File all_pfams_encountered_file = new File( outfile_name + surfacing.ALL_PFAMS_ENCOUNTERED_SUFFIX );
2334 final File all_pfams_encountered_with_go_annotation_file = new File( outfile_name
2335 + surfacing.ALL_PFAMS_ENCOUNTERED_WITH_GO_ANNOTATION_SUFFIX );
2336 final File encountered_pfams_summary_file = new File( outfile_name + surfacing.ENCOUNTERED_PFAMS_SUMMARY_SUFFIX );
2337 int biological_process_counter = 0;
2338 int cellular_component_counter = 0;
2339 int molecular_function_counter = 0;
2340 int pfams_with_mappings_counter = 0;
2341 int pfams_without_mappings_counter = 0;
2342 int pfams_without_mappings_to_bp_or_mf_counter = 0;
2343 int pfams_with_mappings_to_bp_or_mf_counter = 0;
2345 final Writer all_pfams_encountered_writer = new BufferedWriter( new FileWriter( all_pfams_encountered_file ) );
2346 final Writer all_pfams_encountered_with_go_annotation_writer = new BufferedWriter( new FileWriter( all_pfams_encountered_with_go_annotation_file ) );
2347 final Writer summary_writer = new BufferedWriter( new FileWriter( encountered_pfams_summary_file ) );
2348 summary_writer.write( "# Pfam to GO mapping summary" );
2349 summary_writer.write( ForesterUtil.LINE_SEPARATOR );
2350 summary_writer.write( "# Actual summary is at the end of this file." );
2351 summary_writer.write( ForesterUtil.LINE_SEPARATOR );
2352 summary_writer.write( "# Encountered Pfams without a GO mapping:" );
2353 summary_writer.write( ForesterUtil.LINE_SEPARATOR );
2354 for( final String pfam : all_pfams_encountered ) {
2355 all_pfams_encountered_writer.write( pfam );
2356 all_pfams_encountered_writer.write( ForesterUtil.LINE_SEPARATOR );
2357 final String domain_id = new String( pfam );
2358 if ( domain_id_to_go_ids_map.containsKey( domain_id ) ) {
2359 ++pfams_with_mappings_counter;
2360 all_pfams_encountered_with_go_annotation_writer.write( pfam );
2361 all_pfams_encountered_with_go_annotation_writer.write( ForesterUtil.LINE_SEPARATOR );
2362 final List<GoId> go_ids = domain_id_to_go_ids_map.get( domain_id );
2363 boolean maps_to_bp = false;
2364 boolean maps_to_cc = false;
2365 boolean maps_to_mf = false;
2366 for( final GoId go_id : go_ids ) {
2367 final GoTerm go_term = go_id_to_term_map.get( go_id );
2368 if ( go_term.getGoNameSpace().isBiologicalProcess() ) {
2371 else if ( go_term.getGoNameSpace().isCellularComponent() ) {
2374 else if ( go_term.getGoNameSpace().isMolecularFunction() ) {
2379 ++biological_process_counter;
2382 ++cellular_component_counter;
2385 ++molecular_function_counter;
2387 if ( maps_to_bp || maps_to_mf ) {
2388 ++pfams_with_mappings_to_bp_or_mf_counter;
2391 ++pfams_without_mappings_to_bp_or_mf_counter;
2395 ++pfams_without_mappings_to_bp_or_mf_counter;
2396 ++pfams_without_mappings_counter;
2397 summary_writer.write( pfam );
2398 summary_writer.write( ForesterUtil.LINE_SEPARATOR );
2401 all_pfams_encountered_writer.close();
2402 all_pfams_encountered_with_go_annotation_writer.close();
2403 ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote all [" + all_pfams_encountered.size()
2404 + "] encountered Pfams to: \"" + all_pfams_encountered_file + "\"" );
2405 ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote all [" + pfams_with_mappings_counter
2406 + "] encountered Pfams with GO mappings to: \"" + all_pfams_encountered_with_go_annotation_file
2408 ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote summary (including all ["
2409 + pfams_without_mappings_counter + "] encountered Pfams without GO mappings) to: \""
2410 + encountered_pfams_summary_file + "\"" );
2411 ForesterUtil.programMessage( surfacing.PRG_NAME, "Sum of Pfams encountered : "
2412 + all_pfams_encountered.size() );
2413 ForesterUtil.programMessage( surfacing.PRG_NAME, "Pfams without a mapping : "
2414 + pfams_without_mappings_counter + " ["
2415 + ( ( 100 * pfams_without_mappings_counter ) / all_pfams_encountered.size() ) + "%]" );
2416 ForesterUtil.programMessage( surfacing.PRG_NAME, "Pfams without mapping to proc. or func. : "
2417 + pfams_without_mappings_to_bp_or_mf_counter + " ["
2418 + ( ( 100 * pfams_without_mappings_to_bp_or_mf_counter ) / all_pfams_encountered.size() ) + "%]" );
2419 ForesterUtil.programMessage( surfacing.PRG_NAME, "Pfams with a mapping : "
2420 + pfams_with_mappings_counter + " ["
2421 + ( ( 100 * pfams_with_mappings_counter ) / all_pfams_encountered.size() ) + "%]" );
2422 ForesterUtil.programMessage( surfacing.PRG_NAME, "Pfams with a mapping to proc. or func. : "
2423 + pfams_with_mappings_to_bp_or_mf_counter + " ["
2424 + ( ( 100 * pfams_with_mappings_to_bp_or_mf_counter ) / all_pfams_encountered.size() ) + "%]" );
2425 ForesterUtil.programMessage( surfacing.PRG_NAME, "Pfams with mapping to biological process: "
2426 + biological_process_counter + " ["
2427 + ( ( 100 * biological_process_counter ) / all_pfams_encountered.size() ) + "%]" );
2428 ForesterUtil.programMessage( surfacing.PRG_NAME, "Pfams with mapping to molecular function: "
2429 + molecular_function_counter + " ["
2430 + ( ( 100 * molecular_function_counter ) / all_pfams_encountered.size() ) + "%]" );
2431 ForesterUtil.programMessage( surfacing.PRG_NAME, "Pfams with mapping to cellular component: "
2432 + cellular_component_counter + " ["
2433 + ( ( 100 * cellular_component_counter ) / all_pfams_encountered.size() ) + "%]" );
2434 summary_writer.write( ForesterUtil.LINE_SEPARATOR );
2435 summary_writer.write( "# Sum of Pfams encountered : " + all_pfams_encountered.size() );
2436 summary_writer.write( ForesterUtil.LINE_SEPARATOR );
2437 summary_writer.write( "# Pfams without a mapping : " + pfams_without_mappings_counter
2438 + " [" + ( ( 100 * pfams_without_mappings_counter ) / all_pfams_encountered.size() ) + "%]" );
2439 summary_writer.write( ForesterUtil.LINE_SEPARATOR );
2440 summary_writer.write( "# Pfams without mapping to proc. or func. : "
2441 + pfams_without_mappings_to_bp_or_mf_counter + " ["
2442 + ( ( 100 * pfams_without_mappings_to_bp_or_mf_counter ) / all_pfams_encountered.size() ) + "%]" );
2443 summary_writer.write( ForesterUtil.LINE_SEPARATOR );
2444 summary_writer.write( "# Pfams with a mapping : " + pfams_with_mappings_counter + " ["
2445 + ( ( 100 * pfams_with_mappings_counter ) / all_pfams_encountered.size() ) + "%]" );
2446 summary_writer.write( ForesterUtil.LINE_SEPARATOR );
2447 summary_writer.write( "# Pfams with a mapping to proc. or func. : "
2448 + pfams_with_mappings_to_bp_or_mf_counter + " ["
2449 + ( ( 100 * pfams_with_mappings_to_bp_or_mf_counter ) / all_pfams_encountered.size() ) + "%]" );
2450 summary_writer.write( ForesterUtil.LINE_SEPARATOR );
2451 summary_writer.write( "# Pfams with mapping to biological process: " + biological_process_counter + " ["
2452 + ( ( 100 * biological_process_counter ) / all_pfams_encountered.size() ) + "%]" );
2453 summary_writer.write( ForesterUtil.LINE_SEPARATOR );
2454 summary_writer.write( "# Pfams with mapping to molecular function: " + molecular_function_counter + " ["
2455 + ( ( 100 * molecular_function_counter ) / all_pfams_encountered.size() ) + "%]" );
2456 summary_writer.write( ForesterUtil.LINE_SEPARATOR );
2457 summary_writer.write( "# Pfams with mapping to cellular component: " + cellular_component_counter + " ["
2458 + ( ( 100 * cellular_component_counter ) / all_pfams_encountered.size() ) + "%]" );
2459 summary_writer.write( ForesterUtil.LINE_SEPARATOR );
2460 summary_writer.close();
2462 catch ( final IOException e ) {
2463 ForesterUtil.printWarningMessage( surfacing.PRG_NAME, "Failure to write: " + e );
2467 private static void writeDomainData( final Map<String, List<GoId>> domain_id_to_go_ids_map,
2468 final Map<GoId, GoTerm> go_id_to_term_map,
2469 final GoNameSpace go_namespace_limit,
2471 final String domain_0,
2472 final String domain_1,
2473 final String prefix_for_html,
2474 final String character_separator_for_non_html_output,
2475 final Map<String, Set<String>>[] domain_id_to_secondary_features_maps,
2476 final Set<GoId> all_go_ids ) throws IOException {
2477 boolean any_go_annotation_present = false;
2478 boolean first_has_no_go = false;
2479 int domain_count = 2; // To distinguish between domains and binary domain combinations.
2480 if ( ForesterUtil.isEmpty( domain_1 ) ) {
2483 // The following has a difficult to understand logic.
2484 for( int d = 0; d < domain_count; ++d ) {
2485 List<GoId> go_ids = null;
2486 boolean go_annotation_present = false;
2488 if ( domain_id_to_go_ids_map.containsKey( domain_0 ) ) {
2489 go_annotation_present = true;
2490 any_go_annotation_present = true;
2491 go_ids = domain_id_to_go_ids_map.get( domain_0 );
2494 first_has_no_go = true;
2498 if ( domain_id_to_go_ids_map.containsKey( domain_1 ) ) {
2499 go_annotation_present = true;
2500 any_go_annotation_present = true;
2501 go_ids = domain_id_to_go_ids_map.get( domain_1 );
2504 if ( go_annotation_present ) {
2505 boolean first = ( ( d == 0 ) || ( ( d == 1 ) && first_has_no_go ) );
2506 for( final GoId go_id : go_ids ) {
2507 out.write( "<tr>" );
2510 writeDomainIdsToHtml( out,
2514 domain_id_to_secondary_features_maps );
2517 out.write( "<td></td>" );
2519 if ( !go_id_to_term_map.containsKey( go_id ) ) {
2520 throw new IllegalArgumentException( "GO-id [" + go_id + "] not found in GO-id to GO-term map" );
2522 final GoTerm go_term = go_id_to_term_map.get( go_id );
2523 if ( ( go_namespace_limit == null ) || go_namespace_limit.equals( go_term.getGoNameSpace() ) ) {
2524 // final String top = GoUtils.getPenultimateGoTerm( go_term, go_id_to_term_map ).getName();
2525 final String go_id_str = go_id.getId();
2526 out.write( "<td>" );
2527 out.write( "<a href=\"" + SurfacingConstants.AMIGO_LINK + go_id_str
2528 + "\" target=\"amigo_window\">" + go_id_str + "</a>" );
2529 out.write( "</td><td>" );
2530 out.write( go_term.getName() );
2531 if ( domain_count == 2 ) {
2532 out.write( " (" + d + ")" );
2534 out.write( "</td><td>" );
2535 // out.write( top );
2536 // out.write( "</td><td>" );
2538 out.write( go_term.getGoNameSpace().toShortString() );
2540 out.write( "</td>" );
2541 if ( all_go_ids != null ) {
2542 all_go_ids.add( go_id );
2546 out.write( "<td>" );
2547 out.write( "</td><td>" );
2548 out.write( "</td><td>" );
2549 out.write( "</td><td>" );
2550 out.write( "</td>" );
2552 out.write( "</tr>" );
2553 out.write( SurfacingConstants.NL );
2556 } // for( int d = 0; d < domain_count; ++d )
2557 if ( !any_go_annotation_present ) {
2558 out.write( "<tr>" );
2559 writeDomainIdsToHtml( out, domain_0, domain_1, prefix_for_html, domain_id_to_secondary_features_maps );
2560 out.write( "<td>" );
2561 out.write( "</td><td>" );
2562 out.write( "</td><td>" );
2563 out.write( "</td><td>" );
2564 out.write( "</td>" );
2565 out.write( "</tr>" );
2566 out.write( SurfacingConstants.NL );
2570 private static void writeDomainIdsToHtml( final Writer out,
2571 final String domain_0,
2572 final String domain_1,
2573 final String prefix_for_detailed_html,
2574 final Map<String, Set<String>>[] domain_id_to_secondary_features_maps )
2575 throws IOException {
2576 out.write( "<td>" );
2577 if ( !ForesterUtil.isEmpty( prefix_for_detailed_html ) ) {
2578 out.write( prefix_for_detailed_html );
2581 out.write( "<a href=\"" + SurfacingConstants.PFAM_FAMILY_ID_LINK + domain_0 + "\">" + domain_0 + "</a>" );
2582 out.write( "</td>" );
2585 private static void writeDomainsToIndividualFilePerTreeNode( final Writer individual_files_writer,
2586 final String domain_0,
2587 final String domain_1 ) throws IOException {
2588 individual_files_writer.write( domain_0 );
2589 individual_files_writer.write( ForesterUtil.LINE_SEPARATOR );
2590 if ( !ForesterUtil.isEmpty( domain_1 ) ) {
2591 individual_files_writer.write( domain_1 );
2592 individual_files_writer.write( ForesterUtil.LINE_SEPARATOR );
2596 private static void writePfamsToFile( final String outfile_name, final SortedSet<String> pfams ) {
2598 final Writer writer = new BufferedWriter( new FileWriter( new File( outfile_name ) ) );
2599 for( final String pfam : pfams ) {
2600 writer.write( pfam );
2601 writer.write( ForesterUtil.LINE_SEPARATOR );
2604 ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote " + pfams.size() + " pfams to [" + outfile_name
2607 catch ( final IOException e ) {
2608 ForesterUtil.printWarningMessage( surfacing.PRG_NAME, "Failure to write: " + e );
2612 private static void writeToNexus( final String outfile_name,
2613 final CharacterStateMatrix<BinaryStates> matrix,
2614 final Phylogeny phylogeny ) {
2615 if ( !( matrix instanceof BasicCharacterStateMatrix ) ) {
2616 throw new IllegalArgumentException( "can only write matrices of type [" + BasicCharacterStateMatrix.class
2619 final BasicCharacterStateMatrix<BinaryStates> my_matrix = ( org.forester.evoinference.matrix.character.BasicCharacterStateMatrix<BinaryStates> ) matrix;
2620 final List<Phylogeny> phylogenies = new ArrayList<Phylogeny>( 1 );
2621 phylogenies.add( phylogeny );
2623 final BufferedWriter w = new BufferedWriter( new FileWriter( outfile_name ) );
2624 w.write( NexusConstants.NEXUS );
2625 w.write( ForesterUtil.LINE_SEPARATOR );
2626 my_matrix.writeNexusTaxaBlock( w );
2627 my_matrix.writeNexusBinaryChractersBlock( w );
2628 PhylogenyWriter.writeNexusTreesBlock( w, phylogenies, NH_CONVERSION_SUPPORT_VALUE_STYLE.NONE );
2631 ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote Nexus file: \"" + outfile_name + "\"" );
2633 catch ( final IOException e ) {
2634 ForesterUtil.fatalError( surfacing.PRG_NAME, e.getMessage() );
2638 private static void writeToNexus( final String outfile_name,
2639 final DomainParsimonyCalculator domain_parsimony,
2640 final Phylogeny phylogeny ) {
2641 writeToNexus( outfile_name + surfacing.NEXUS_EXTERNAL_DOMAINS,
2642 domain_parsimony.createMatrixOfDomainPresenceOrAbsence(),
2644 writeToNexus( outfile_name + surfacing.NEXUS_EXTERNAL_DOMAIN_COMBINATIONS,
2645 domain_parsimony.createMatrixOfBinaryDomainCombinationPresenceOrAbsence(),
2649 final static class DomainComparator implements Comparator<Domain> {
2651 final private boolean _ascending;
2653 public DomainComparator( final boolean ascending ) {
2654 _ascending = ascending;
2658 public final int compare( final Domain d0, final Domain d1 ) {
2659 if ( d0.getFrom() < d1.getFrom() ) {
2660 return _ascending ? -1 : 1;
2662 else if ( d0.getFrom() > d1.getFrom() ) {
2663 return _ascending ? 1 : -1;