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.surfacing.PrintableDomainSimilarity.PRINT_OPTION;
87 import org.forester.util.AsciiHistogram;
88 import org.forester.util.BasicDescriptiveStatistics;
89 import org.forester.util.BasicTable;
90 import org.forester.util.BasicTableParser;
91 import org.forester.util.DescriptiveStatistics;
92 import org.forester.util.ForesterUtil;
94 public final class SurfacingUtil {
96 private final static NumberFormat FORMATTER_3 = new DecimalFormat( "0.000" );
97 private static final Comparator<Domain> ASCENDING_CONFIDENCE_VALUE_ORDER = new Comparator<Domain>() {
100 public int compare( final Domain d1,
102 if ( d1.getPerSequenceEvalue() < d2
103 .getPerSequenceEvalue() ) {
107 .getPerSequenceEvalue() > d2
108 .getPerSequenceEvalue() ) {
112 return d1.compareTo( d2 );
116 public final static Pattern PATTERN_SP_STYLE_TAXONOMY = Pattern.compile( "^[A-Z0-9]{3,5}$" );
118 private SurfacingUtil() {
119 // Hidden constructor.
122 public static void addAllBinaryDomainCombinationToSet( final GenomeWideCombinableDomains genome,
123 final SortedSet<BinaryDomainCombination> binary_domain_combinations ) {
124 final SortedMap<String, CombinableDomains> all_cd = genome.getAllCombinableDomainsIds();
125 for( final String domain_id : all_cd.keySet() ) {
126 binary_domain_combinations.addAll( all_cd.get( domain_id ).toBinaryDomainCombinations() );
130 public static void addAllDomainIdsToSet( final GenomeWideCombinableDomains genome,
131 final SortedSet<String> domain_ids ) {
132 final SortedSet<String> domains = genome.getAllDomainIds();
133 for( final String domain : domains ) {
134 domain_ids.add( domain );
138 public static void addHtmlHead( final Writer w, final String title ) throws IOException {
139 w.write( SurfacingConstants.NL );
141 w.write( "<title>" );
143 w.write( "</title>" );
144 w.write( SurfacingConstants.NL );
145 w.write( "<style>" );
146 w.write( SurfacingConstants.NL );
147 w.write( "a:visited { color : #6633FF; text-decoration : none; }" );
148 w.write( SurfacingConstants.NL );
149 w.write( "a:link { color : #6633FF; text-decoration : none; }" );
150 w.write( SurfacingConstants.NL );
151 w.write( "a:active { color : #99FF00; text-decoration : none; }" );
152 w.write( SurfacingConstants.NL );
153 w.write( "a:hover { color : #FFFFFF; background-color : #99FF00; text-decoration : none; }" );
154 w.write( SurfacingConstants.NL );
156 w.write( "a.pl:visited { color : #505050; text-decoration : none; font-size: 7pt;}" );
157 w.write( SurfacingConstants.NL );
158 w.write( "a.pl:link { color : #505050; text-decoration : none; font-size: 7pt;}" );
159 w.write( SurfacingConstants.NL );
160 w.write( "a.pl:active { color : #505050; text-decoration : none; font-size: 7pt;}" );
161 w.write( SurfacingConstants.NL );
162 w.write( "a.pl:hover { color : #FFFFFF; background-color : #99FF00; text-decoration : none; font-size: 7pt;}" );
163 w.write( SurfacingConstants.NL );
165 w.write( "a.ps:visited { color : #707070; text-decoration : none; font-size: 7pt;}" );
166 w.write( SurfacingConstants.NL );
167 w.write( "a.ps:link { color : #707070; text-decoration : none; font-size: 7pt;}" );
168 w.write( SurfacingConstants.NL );
169 w.write( "a.ps:active { color : #707070; text-decoration : none; font-size: 7pt;}" );
170 w.write( SurfacingConstants.NL );
171 w.write( "a.ps:hover { color : #FFFFFF; background-color : #99FF00; text-decoration : none; font-size: 7pt;}" );
172 w.write( SurfacingConstants.NL );
174 w.write( "td { text-align: left; vertical-align: top; font-family: Verdana, Arial, Helvetica; font-size: 8pt}" );
175 w.write( SurfacingConstants.NL );
176 w.write( "h1 { color : #0000FF; font-family: Verdana, Arial, Helvetica; font-size: 18pt; font-weight: bold }" );
177 w.write( SurfacingConstants.NL );
178 w.write( "h2 { color : #0000FF; font-family: Verdana, Arial, Helvetica; font-size: 16pt; font-weight: bold }" );
179 w.write( SurfacingConstants.NL );
180 w.write( "</style>" );
181 w.write( SurfacingConstants.NL );
182 w.write( "</head>" );
183 w.write( SurfacingConstants.NL );
186 public static DescriptiveStatistics calculateDescriptiveStatisticsForMeanValues( final Set<DomainSimilarity> similarities ) {
187 final DescriptiveStatistics stats = new BasicDescriptiveStatistics();
188 for( final DomainSimilarity similarity : similarities ) {
189 stats.addValue( similarity.getMeanSimilarityScore() );
194 public static int calculateOverlap( final Domain domain, final List<Boolean> covered_positions ) {
195 int overlap_count = 0;
196 for( int i = domain.getFrom(); i <= domain.getTo(); ++i ) {
197 if ( ( i < covered_positions.size() ) && ( covered_positions.get( i ) == true ) ) {
201 return overlap_count;
204 public static void checkForOutputFileWriteability( final File outfile ) {
205 final String error = ForesterUtil.isWritableFile( outfile );
206 if ( !ForesterUtil.isEmpty( error ) ) {
207 ForesterUtil.fatalError( surfacing.PRG_NAME, error );
211 public static void collectChangedDomainCombinationsFromBinaryStatesMatrixAsListToFile( final CharacterStateMatrix<CharacterStateMatrix.GainLossStates> matrix,
212 final BinaryDomainCombination.DomainCombinationType dc_type,
213 final List<BinaryDomainCombination> all_binary_domains_combination_gained,
214 final boolean get_gains ) {
215 final SortedSet<String> sorted_ids = new TreeSet<String>();
216 for( int i = 0; i < matrix.getNumberOfIdentifiers(); ++i ) {
217 sorted_ids.add( matrix.getIdentifier( i ) );
219 for( final String id : sorted_ids ) {
220 for( int c = 0; c < matrix.getNumberOfCharacters(); ++c ) {
221 if ( ( get_gains && ( matrix.getState( id, c ) == CharacterStateMatrix.GainLossStates.GAIN ) )
222 || ( !get_gains && ( matrix.getState( id, c ) == CharacterStateMatrix.GainLossStates.LOSS ) ) ) {
223 if ( dc_type == BinaryDomainCombination.DomainCombinationType.DIRECTED_ADJACTANT ) {
224 all_binary_domains_combination_gained.add( AdjactantDirectedBinaryDomainCombination
225 .createInstance( matrix.getCharacter( c ) ) );
227 else if ( dc_type == BinaryDomainCombination.DomainCombinationType.DIRECTED ) {
228 all_binary_domains_combination_gained.add( DirectedBinaryDomainCombination
229 .createInstance( matrix.getCharacter( c ) ) );
232 all_binary_domains_combination_gained.add( BasicBinaryDomainCombination.createInstance( matrix
233 .getCharacter( c ) ) );
240 public static Map<String, List<GoId>> createDomainIdToGoIdMap( final List<PfamToGoMapping> pfam_to_go_mappings ) {
241 final Map<String, List<GoId>> domain_id_to_go_ids_map = new HashMap<String, List<GoId>>( pfam_to_go_mappings.size() );
242 for( final PfamToGoMapping pfam_to_go : pfam_to_go_mappings ) {
243 if ( !domain_id_to_go_ids_map.containsKey( pfam_to_go.getKey() ) ) {
244 domain_id_to_go_ids_map.put( pfam_to_go.getKey(), new ArrayList<GoId>() );
246 domain_id_to_go_ids_map.get( pfam_to_go.getKey() ).add( pfam_to_go.getValue() );
248 return domain_id_to_go_ids_map;
251 public static Map<String, Set<String>> createDomainIdToSecondaryFeaturesMap( final File secondary_features_map_file )
253 final BasicTable<String> primary_table = BasicTableParser.parse( secondary_features_map_file, '\t' );
254 final Map<String, Set<String>> map = new TreeMap<String, Set<String>>();
255 for( int r = 0; r < primary_table.getNumberOfRows(); ++r ) {
256 final String domain_id = primary_table.getValue( 0, r );
257 if ( !map.containsKey( domain_id ) ) {
258 map.put( domain_id, new HashSet<String>() );
260 map.get( domain_id ).add( primary_table.getValue( 1, r ) );
265 public static Phylogeny createNjTreeBasedOnMatrixToFile( final File nj_tree_outfile, final DistanceMatrix distance ) {
266 checkForOutputFileWriteability( nj_tree_outfile );
267 final NeighborJoining nj = NeighborJoining.createInstance();
268 final Phylogeny phylogeny = nj.execute( ( BasicSymmetricalDistanceMatrix ) distance );
269 phylogeny.setName( nj_tree_outfile.getName() );
270 writePhylogenyToFile( phylogeny, nj_tree_outfile.toString() );
274 public static Map<String, Integer> createTaxCodeToIdMap( final Phylogeny phy ) {
275 final Map<String, Integer> m = new HashMap<String, Integer>();
276 for( final PhylogenyNodeIterator iter = phy.iteratorExternalForward(); iter.hasNext(); ) {
277 final PhylogenyNode n = iter.next();
278 if ( n.getNodeData().isHasTaxonomy() ) {
279 final Taxonomy t = n.getNodeData().getTaxonomy();
280 final String c = t.getTaxonomyCode();
281 if ( !ForesterUtil.isEmpty( c ) ) {
282 if ( n.getNodeData().getTaxonomy() == null ) {
283 ForesterUtil.fatalError( surfacing.PRG_NAME, "no taxonomy id for node " + n );
285 final String id = n.getNodeData().getTaxonomy().getIdentifier().getValue();
286 if ( ForesterUtil.isEmpty( id ) ) {
287 ForesterUtil.fatalError( surfacing.PRG_NAME, "no taxonomy id for node " + n );
289 if ( m.containsKey( c ) ) {
290 ForesterUtil.fatalError( surfacing.PRG_NAME, "taxonomy code " + c + " is not unique" );
292 final int iid = Integer.valueOf( id );
293 if ( m.containsValue( iid ) ) {
294 ForesterUtil.fatalError( surfacing.PRG_NAME, "taxonomy id " + iid + " is not unique" );
300 ForesterUtil.fatalError( surfacing.PRG_NAME, "no taxonomy for node " + n );
306 public static void decoratePrintableDomainSimilarities( final SortedSet<DomainSimilarity> domain_similarities,
307 final Detailedness detailedness ) {
308 for( final DomainSimilarity domain_similarity : domain_similarities ) {
309 if ( domain_similarity instanceof PrintableDomainSimilarity ) {
310 final PrintableDomainSimilarity printable_domain_similarity = ( PrintableDomainSimilarity ) domain_similarity;
311 printable_domain_similarity.setDetailedness( detailedness );
316 public static void doit( final List<Protein> proteins,
317 final List<String> query_domain_ids_nc_order,
319 final String separator,
320 final String limit_to_species,
321 final Map<String, List<Integer>> average_protein_lengths_by_dc ) throws IOException {
322 for( final Protein protein : proteins ) {
323 if ( ForesterUtil.isEmpty( limit_to_species )
324 || protein.getSpecies().getSpeciesId().equalsIgnoreCase( limit_to_species ) ) {
325 if ( protein.contains( query_domain_ids_nc_order, true ) ) {
326 out.write( protein.getSpecies().getSpeciesId() );
327 out.write( separator );
328 out.write( protein.getProteinId().getId() );
329 out.write( separator );
331 final Set<String> visited_domain_ids = new HashSet<String>();
332 boolean first = true;
333 for( final Domain domain : protein.getProteinDomains() ) {
334 if ( !visited_domain_ids.contains( domain.getDomainId() ) ) {
335 visited_domain_ids.add( domain.getDomainId() );
342 out.write( domain.getDomainId() );
344 out.write( "" + domain.getTotalCount() );
349 out.write( separator );
350 if ( !( ForesterUtil.isEmpty( protein.getDescription() ) || protein.getDescription()
351 .equals( SurfacingConstants.NONE ) ) ) {
352 out.write( protein.getDescription() );
354 out.write( separator );
355 if ( !( ForesterUtil.isEmpty( protein.getAccession() ) || protein.getAccession()
356 .equals( SurfacingConstants.NONE ) ) ) {
357 out.write( protein.getAccession() );
359 out.write( SurfacingConstants.NL );
366 public static void domainsPerProteinsStatistics( final String genome,
367 final List<Protein> protein_list,
368 final DescriptiveStatistics all_genomes_domains_per_potein_stats,
369 final SortedMap<Integer, Integer> all_genomes_domains_per_potein_histo,
370 final SortedSet<String> domains_which_are_always_single,
371 final SortedSet<String> domains_which_are_sometimes_single_sometimes_not,
372 final SortedSet<String> domains_which_never_single,
373 final Writer writer ) {
374 final DescriptiveStatistics stats = new BasicDescriptiveStatistics();
375 for( final Protein protein : protein_list ) {
376 final int domains = protein.getNumberOfProteinDomains();
377 //System.out.println( domains );
378 stats.addValue( domains );
379 all_genomes_domains_per_potein_stats.addValue( domains );
380 if ( !all_genomes_domains_per_potein_histo.containsKey( domains ) ) {
381 all_genomes_domains_per_potein_histo.put( domains, 1 );
384 all_genomes_domains_per_potein_histo.put( domains,
385 1 + all_genomes_domains_per_potein_histo.get( domains ) );
387 if ( domains == 1 ) {
388 final String domain = protein.getProteinDomain( 0 ).getDomainId();
389 if ( !domains_which_are_sometimes_single_sometimes_not.contains( domain ) ) {
390 if ( domains_which_never_single.contains( domain ) ) {
391 domains_which_never_single.remove( domain );
392 domains_which_are_sometimes_single_sometimes_not.add( domain );
395 domains_which_are_always_single.add( domain );
399 else if ( domains > 1 ) {
400 for( final Domain d : protein.getProteinDomains() ) {
401 final String domain = d.getDomainId();
402 // System.out.println( domain );
403 if ( !domains_which_are_sometimes_single_sometimes_not.contains( domain ) ) {
404 if ( domains_which_are_always_single.contains( domain ) ) {
405 domains_which_are_always_single.remove( domain );
406 domains_which_are_sometimes_single_sometimes_not.add( domain );
409 domains_which_never_single.add( domain );
416 writer.write( genome );
417 writer.write( "\t" );
418 if ( stats.getN() >= 1 ) {
419 writer.write( stats.arithmeticMean() + "" );
420 writer.write( "\t" );
421 if ( stats.getN() >= 2 ) {
422 writer.write( stats.sampleStandardDeviation() + "" );
427 writer.write( "\t" );
428 writer.write( stats.median() + "" );
429 writer.write( "\t" );
430 writer.write( stats.getN() + "" );
431 writer.write( "\t" );
432 writer.write( stats.getMin() + "" );
433 writer.write( "\t" );
434 writer.write( stats.getMax() + "" );
437 writer.write( "\t" );
438 writer.write( "\t" );
439 writer.write( "\t" );
441 writer.write( "\t" );
442 writer.write( "\t" );
444 writer.write( "\n" );
446 catch ( final IOException e ) {
451 public static void executeDomainLengthAnalysis( final String[][] input_file_properties,
452 final int number_of_genomes,
453 final DomainLengthsTable domain_lengths_table,
454 final File outfile ) throws IOException {
455 final DecimalFormat df = new DecimalFormat( "#.00" );
456 checkForOutputFileWriteability( outfile );
457 final BufferedWriter out = new BufferedWriter( new FileWriter( outfile ) );
458 out.write( "MEAN BASED STATISTICS PER SPECIES" );
459 out.write( ForesterUtil.LINE_SEPARATOR );
460 out.write( domain_lengths_table.createMeanBasedStatisticsPerSpeciesTable().toString() );
461 out.write( ForesterUtil.LINE_SEPARATOR );
462 out.write( ForesterUtil.LINE_SEPARATOR );
463 final List<DomainLengths> domain_lengths_list = domain_lengths_table.getDomainLengthsList();
464 out.write( "OUTLIER SPECIES PER DOMAIN (Z>=1.5)" );
465 out.write( ForesterUtil.LINE_SEPARATOR );
466 for( final DomainLengths domain_lengths : domain_lengths_list ) {
467 final List<Species> species_list = domain_lengths.getMeanBasedOutlierSpecies( 1.5 );
468 if ( species_list.size() > 0 ) {
469 out.write( domain_lengths.getDomainId() + "\t" );
470 for( final Species species : species_list ) {
471 out.write( species + "\t" );
473 out.write( ForesterUtil.LINE_SEPARATOR );
476 out.write( ForesterUtil.LINE_SEPARATOR );
477 out.write( ForesterUtil.LINE_SEPARATOR );
478 out.write( "OUTLIER SPECIES (Z 1.0)" );
479 out.write( ForesterUtil.LINE_SEPARATOR );
480 final DescriptiveStatistics stats_for_all_species = domain_lengths_table
481 .calculateMeanBasedStatisticsForAllSpecies();
482 out.write( stats_for_all_species.asSummary() );
483 out.write( ForesterUtil.LINE_SEPARATOR );
484 final AsciiHistogram histo = new AsciiHistogram( stats_for_all_species );
485 out.write( histo.toStringBuffer( 40, '=', 60, 4 ).toString() );
486 out.write( ForesterUtil.LINE_SEPARATOR );
487 final double population_sd = stats_for_all_species.sampleStandardDeviation();
488 final double population_mean = stats_for_all_species.arithmeticMean();
489 for( final Species species : domain_lengths_table.getSpecies() ) {
490 final double x = domain_lengths_table.calculateMeanBasedStatisticsForSpecies( species ).arithmeticMean();
491 final double z = ( x - population_mean ) / population_sd;
492 out.write( species + "\t" + z );
493 out.write( ForesterUtil.LINE_SEPARATOR );
495 out.write( ForesterUtil.LINE_SEPARATOR );
496 for( final Species species : domain_lengths_table.getSpecies() ) {
497 final DescriptiveStatistics stats_for_species = domain_lengths_table
498 .calculateMeanBasedStatisticsForSpecies( species );
499 final double x = stats_for_species.arithmeticMean();
500 final double z = ( x - population_mean ) / population_sd;
501 if ( ( z <= -1.0 ) || ( z >= 1.0 ) ) {
502 out.write( species + "\t" + df.format( z ) + "\t" + stats_for_species.asSummary() );
503 out.write( ForesterUtil.LINE_SEPARATOR );
512 * @param all_binary_domains_combination_lost_fitch
513 * @param use_last_in_fitch_parsimony
514 * @param consider_directedness_and_adjacency_for_bin_combinations
515 * @param all_binary_domains_combination_gained if null ignored, otherwise this is to list all binary domain combinations
516 * which were gained under unweighted (Fitch) parsimony.
518 public static void executeParsimonyAnalysis( final long random_number_seed_for_fitch_parsimony,
519 final boolean radomize_fitch_parsimony,
520 final String outfile_name,
521 final DomainParsimonyCalculator domain_parsimony,
522 final Phylogeny phylogeny,
523 final Map<String, List<GoId>> domain_id_to_go_ids_map,
524 final Map<GoId, GoTerm> go_id_to_term_map,
525 final GoNameSpace go_namespace_limit,
526 final String parameters_str,
527 final Map<String, Set<String>>[] domain_id_to_secondary_features_maps,
528 final SortedSet<String> positive_filter,
529 final boolean output_binary_domain_combinations_for_graphs,
530 final List<BinaryDomainCombination> all_binary_domains_combination_gained_fitch,
531 final List<BinaryDomainCombination> all_binary_domains_combination_lost_fitch,
532 final BinaryDomainCombination.DomainCombinationType dc_type,
533 final Map<String, DescriptiveStatistics> protein_length_stats_by_dc,
534 final Map<String, DescriptiveStatistics> domain_number_stats_by_dc,
535 final Map<String, DescriptiveStatistics> domain_length_stats_by_domain,
536 final Map<String, Integer> tax_code_to_id_map,
537 final boolean write_to_nexus,
538 final boolean use_last_in_fitch_parsimony ) {
539 final String sep = ForesterUtil.LINE_SEPARATOR + "###################" + ForesterUtil.LINE_SEPARATOR;
540 final String date_time = ForesterUtil.getCurrentDateTime();
541 final SortedSet<String> all_pfams_encountered = new TreeSet<String>();
542 final SortedSet<String> all_pfams_gained_as_domains = new TreeSet<String>();
543 final SortedSet<String> all_pfams_lost_as_domains = new TreeSet<String>();
544 final SortedSet<String> all_pfams_gained_as_dom_combinations = new TreeSet<String>();
545 final SortedSet<String> all_pfams_lost_as_dom_combinations = new TreeSet<String>();
546 if ( write_to_nexus ) {
547 writeToNexus( outfile_name, domain_parsimony, phylogeny );
551 Phylogeny local_phylogeny_l = phylogeny.copy();
552 if ( ( positive_filter != null ) && ( positive_filter.size() > 0 ) ) {
553 domain_parsimony.executeDolloParsimonyOnDomainPresence( positive_filter );
556 domain_parsimony.executeDolloParsimonyOnDomainPresence();
558 SurfacingUtil.writeMatrixToFile( domain_parsimony.getGainLossMatrix(), outfile_name
559 + surfacing.PARSIMONY_OUTPUT_GL_SUFFIX_DOLLO_DOMAINS, Format.FORESTER );
560 SurfacingUtil.writeMatrixToFile( domain_parsimony.getGainLossCountsMatrix(), outfile_name
561 + surfacing.PARSIMONY_OUTPUT_GL_COUNTS_SUFFIX_DOLLO_DOMAINS, Format.FORESTER );
562 SurfacingUtil.writeBinaryStatesMatrixAsListToFile( domain_parsimony.getGainLossMatrix(),
563 CharacterStateMatrix.GainLossStates.GAIN,
564 outfile_name + surfacing.PARSIMONY_OUTPUT_DOLLO_GAINS_D,
566 ForesterUtil.LINE_SEPARATOR,
568 SurfacingUtil.writeBinaryStatesMatrixAsListToFile( domain_parsimony.getGainLossMatrix(),
569 CharacterStateMatrix.GainLossStates.LOSS,
570 outfile_name + surfacing.PARSIMONY_OUTPUT_DOLLO_LOSSES_D,
572 ForesterUtil.LINE_SEPARATOR,
574 SurfacingUtil.writeBinaryStatesMatrixAsListToFile( domain_parsimony.getGainLossMatrix(), null, outfile_name
575 + surfacing.PARSIMONY_OUTPUT_DOLLO_PRESENT_D, sep, ForesterUtil.LINE_SEPARATOR, null );
577 writeBinaryStatesMatrixToList( domain_id_to_go_ids_map,
581 domain_parsimony.getGainLossMatrix(),
582 CharacterStateMatrix.GainLossStates.GAIN,
583 outfile_name + surfacing.PARSIMONY_OUTPUT_DOLLO_GAINS_HTML_D,
585 ForesterUtil.LINE_SEPARATOR,
586 "Dollo Parsimony | Gains | Domains",
588 domain_id_to_secondary_features_maps,
589 all_pfams_encountered,
590 all_pfams_gained_as_domains,
592 tax_code_to_id_map );
593 writeBinaryStatesMatrixToList( domain_id_to_go_ids_map,
597 domain_parsimony.getGainLossMatrix(),
598 CharacterStateMatrix.GainLossStates.LOSS,
599 outfile_name + surfacing.PARSIMONY_OUTPUT_DOLLO_LOSSES_HTML_D,
601 ForesterUtil.LINE_SEPARATOR,
602 "Dollo Parsimony | Losses | Domains",
604 domain_id_to_secondary_features_maps,
605 all_pfams_encountered,
606 all_pfams_lost_as_domains,
608 tax_code_to_id_map );
609 // writeBinaryStatesMatrixToList( domain_id_to_go_ids_map,
610 // go_id_to_term_map,
611 // go_namespace_limit,
613 // domain_parsimony.getGainLossMatrix(),
615 // outfile_name + surfacing.PARSIMONY_OUTPUT_DOLLO_PRESENT_HTML_D,
617 // ForesterUtil.LINE_SEPARATOR,
618 // "Dollo Parsimony | Present | Domains",
620 // domain_id_to_secondary_features_maps,
621 // all_pfams_encountered,
623 // "_dollo_present_d",
624 // tax_code_to_id_map );
625 preparePhylogeny( local_phylogeny_l,
628 "Dollo parsimony on domain presence/absence",
629 "dollo_on_domains_" + outfile_name,
631 SurfacingUtil.writePhylogenyToFile( local_phylogeny_l, outfile_name
632 + surfacing.DOMAINS_PARSIMONY_TREE_OUTPUT_SUFFIX_DOLLO );
634 writeAllDomainsChangedOnAllSubtrees( local_phylogeny_l, true, outfile_name, "_dollo_all_gains_d" );
635 writeAllDomainsChangedOnAllSubtrees( local_phylogeny_l, false, outfile_name, "_dollo_all_losses_d" );
637 catch ( final IOException e ) {
639 ForesterUtil.fatalError( surfacing.PRG_NAME, e.getLocalizedMessage() );
641 if ( domain_parsimony.calculateNumberOfBinaryDomainCombination() > 0 ) {
642 // FITCH DOMAIN COMBINATIONS
643 // -------------------------
644 local_phylogeny_l = phylogeny.copy();
645 String randomization = "no";
646 if ( radomize_fitch_parsimony ) {
647 domain_parsimony.executeFitchParsimonyOnBinaryDomainCombintion( random_number_seed_for_fitch_parsimony );
648 randomization = "yes, seed = " + random_number_seed_for_fitch_parsimony;
651 domain_parsimony.executeFitchParsimonyOnBinaryDomainCombintion( use_last_in_fitch_parsimony );
653 SurfacingUtil.writeMatrixToFile( domain_parsimony.getGainLossMatrix(), outfile_name
654 + surfacing.PARSIMONY_OUTPUT_GL_SUFFIX_FITCH_BINARY_COMBINATIONS, Format.FORESTER );
655 SurfacingUtil.writeMatrixToFile( domain_parsimony.getGainLossCountsMatrix(), outfile_name
656 + surfacing.PARSIMONY_OUTPUT_GL_COUNTS_SUFFIX_FITCH_BINARY_COMBINATIONS, Format.FORESTER );
658 .writeBinaryStatesMatrixAsListToFile( domain_parsimony.getGainLossMatrix(),
659 CharacterStateMatrix.GainLossStates.GAIN,
660 outfile_name + surfacing.PARSIMONY_OUTPUT_FITCH_GAINS_BC,
662 ForesterUtil.LINE_SEPARATOR,
664 SurfacingUtil.writeBinaryStatesMatrixAsListToFile( domain_parsimony.getGainLossMatrix(),
665 CharacterStateMatrix.GainLossStates.LOSS,
667 + surfacing.PARSIMONY_OUTPUT_FITCH_LOSSES_BC,
669 ForesterUtil.LINE_SEPARATOR,
671 SurfacingUtil.writeBinaryStatesMatrixAsListToFile( domain_parsimony.getGainLossMatrix(), null, outfile_name
672 + surfacing.PARSIMONY_OUTPUT_FITCH_PRESENT_BC, sep, ForesterUtil.LINE_SEPARATOR, null );
673 if ( all_binary_domains_combination_gained_fitch != null ) {
674 collectChangedDomainCombinationsFromBinaryStatesMatrixAsListToFile( domain_parsimony.getGainLossMatrix(),
676 all_binary_domains_combination_gained_fitch,
679 if ( all_binary_domains_combination_lost_fitch != null ) {
680 collectChangedDomainCombinationsFromBinaryStatesMatrixAsListToFile( domain_parsimony.getGainLossMatrix(),
682 all_binary_domains_combination_lost_fitch,
685 if ( output_binary_domain_combinations_for_graphs ) {
687 .writeBinaryStatesMatrixAsListToFileForBinaryCombinationsForGraphAnalysis( domain_parsimony
688 .getGainLossMatrix(),
691 + surfacing.PARSIMONY_OUTPUT_FITCH_PRESENT_BC_OUTPUTFILE_SUFFIX_FOR_GRAPH_ANALYSIS,
693 ForesterUtil.LINE_SEPARATOR,
694 BinaryDomainCombination.OutputFormat.DOT );
697 writeBinaryStatesMatrixToList( domain_id_to_go_ids_map,
701 domain_parsimony.getGainLossMatrix(),
702 CharacterStateMatrix.GainLossStates.GAIN,
703 outfile_name + surfacing.PARSIMONY_OUTPUT_FITCH_GAINS_HTML_BC,
705 ForesterUtil.LINE_SEPARATOR,
706 "Fitch Parsimony | Gains | Domain Combinations",
709 all_pfams_encountered,
710 all_pfams_gained_as_dom_combinations,
712 tax_code_to_id_map );
713 writeBinaryStatesMatrixToList( domain_id_to_go_ids_map,
717 domain_parsimony.getGainLossMatrix(),
718 CharacterStateMatrix.GainLossStates.LOSS,
719 outfile_name + surfacing.PARSIMONY_OUTPUT_FITCH_LOSSES_HTML_BC,
721 ForesterUtil.LINE_SEPARATOR,
722 "Fitch Parsimony | Losses | Domain Combinations",
725 all_pfams_encountered,
726 all_pfams_lost_as_dom_combinations,
728 tax_code_to_id_map );
729 // writeBinaryStatesMatrixToList( domain_id_to_go_ids_map,
730 // go_id_to_term_map,
731 // go_namespace_limit,
733 // domain_parsimony.getGainLossMatrix(),
735 // outfile_name + surfacing.PARSIMONY_OUTPUT_FITCH_PRESENT_HTML_BC,
737 // ForesterUtil.LINE_SEPARATOR,
738 // "Fitch Parsimony | Present | Domain Combinations",
741 // all_pfams_encountered,
743 // "_fitch_present_dc",
744 // tax_code_to_id_map );
745 writeAllEncounteredPfamsToFile( domain_id_to_go_ids_map,
748 all_pfams_encountered );
749 writePfamsToFile( outfile_name + surfacing.ALL_PFAMS_GAINED_AS_DOMAINS_SUFFIX, all_pfams_gained_as_domains );
750 writePfamsToFile( outfile_name + surfacing.ALL_PFAMS_LOST_AS_DOMAINS_SUFFIX, all_pfams_lost_as_domains );
751 writePfamsToFile( outfile_name + surfacing.ALL_PFAMS_GAINED_AS_DC_SUFFIX,
752 all_pfams_gained_as_dom_combinations );
753 writePfamsToFile( outfile_name + surfacing.ALL_PFAMS_LOST_AS_DC_SUFFIX, all_pfams_lost_as_dom_combinations );
754 preparePhylogeny( local_phylogeny_l,
757 "Fitch parsimony on binary domain combination presence/absence randomization: "
759 "fitch_on_binary_domain_combinations_" + outfile_name,
761 SurfacingUtil.writePhylogenyToFile( local_phylogeny_l, outfile_name
762 + surfacing.BINARY_DOMAIN_COMBINATIONS_PARSIMONY_TREE_OUTPUT_SUFFIX_FITCH );
763 calculateIndependentDomainCombinationGains( local_phylogeny_l,
765 + surfacing.INDEPENDENT_DC_GAINS_FITCH_PARS_COUNTS_OUTPUT_SUFFIX,
767 + surfacing.INDEPENDENT_DC_GAINS_FITCH_PARS_DC_OUTPUT_SUFFIX,
769 + surfacing.INDEPENDENT_DC_GAINS_FITCH_PARS_DC_FOR_GO_MAPPING_OUTPUT_SUFFIX,
771 + surfacing.INDEPENDENT_DC_GAINS_FITCH_PARS_DC_FOR_GO_MAPPING_OUTPUT_UNIQUE_SUFFIX,
772 outfile_name + "_indep_dc_gains_fitch_lca_ranks.txt",
773 outfile_name + "_indep_dc_gains_fitch_lca_taxonomies.txt",
774 outfile_name + "_indep_dc_gains_fitch_protein_statistics.txt",
775 protein_length_stats_by_dc,
776 domain_number_stats_by_dc,
777 domain_length_stats_by_domain );
781 public static void executeParsimonyAnalysisForSecondaryFeatures( final String outfile_name,
782 final DomainParsimonyCalculator secondary_features_parsimony,
783 final Phylogeny phylogeny,
784 final String parameters_str,
785 final Map<Species, MappingResults> mapping_results_map,
786 final boolean use_last_in_fitch_parsimony ) {
787 final String sep = ForesterUtil.LINE_SEPARATOR + "###################" + ForesterUtil.LINE_SEPARATOR;
788 final String date_time = ForesterUtil.getCurrentDateTime();
789 System.out.println();
790 writeToNexus( outfile_name + surfacing.NEXUS_SECONDARY_FEATURES,
791 secondary_features_parsimony.createMatrixOfSecondaryFeaturePresenceOrAbsence( null ),
793 Phylogeny local_phylogeny_copy = phylogeny.copy();
794 secondary_features_parsimony.executeDolloParsimonyOnSecondaryFeatures( mapping_results_map );
795 SurfacingUtil.writeMatrixToFile( secondary_features_parsimony.getGainLossMatrix(), outfile_name
796 + surfacing.PARSIMONY_OUTPUT_GL_SUFFIX_DOLLO_SECONDARY_FEATURES, Format.FORESTER );
797 SurfacingUtil.writeMatrixToFile( secondary_features_parsimony.getGainLossCountsMatrix(), outfile_name
798 + surfacing.PARSIMONY_OUTPUT_GL_COUNTS_SUFFIX_DOLLO_SECONDARY_FEATURES, Format.FORESTER );
800 .writeBinaryStatesMatrixAsListToFile( secondary_features_parsimony.getGainLossMatrix(),
801 CharacterStateMatrix.GainLossStates.GAIN,
803 + surfacing.PARSIMONY_OUTPUT_DOLLO_GAINS_SECONDARY_FEATURES,
805 ForesterUtil.LINE_SEPARATOR,
808 .writeBinaryStatesMatrixAsListToFile( secondary_features_parsimony.getGainLossMatrix(),
809 CharacterStateMatrix.GainLossStates.LOSS,
811 + surfacing.PARSIMONY_OUTPUT_DOLLO_LOSSES_SECONDARY_FEATURES,
813 ForesterUtil.LINE_SEPARATOR,
816 .writeBinaryStatesMatrixAsListToFile( secondary_features_parsimony.getGainLossMatrix(),
819 + surfacing.PARSIMONY_OUTPUT_DOLLO_PRESENT_SECONDARY_FEATURES,
821 ForesterUtil.LINE_SEPARATOR,
823 preparePhylogeny( local_phylogeny_copy,
824 secondary_features_parsimony,
826 "Dollo parsimony on secondary feature presence/absence",
827 "dollo_on_secondary_features_" + outfile_name,
829 SurfacingUtil.writePhylogenyToFile( local_phylogeny_copy, outfile_name
830 + surfacing.SECONDARY_FEATURES_PARSIMONY_TREE_OUTPUT_SUFFIX_DOLLO );
831 // FITCH DOMAIN COMBINATIONS
832 // -------------------------
833 local_phylogeny_copy = phylogeny.copy();
834 final String randomization = "no";
835 secondary_features_parsimony
836 .executeFitchParsimonyOnBinaryDomainCombintionOnSecondaryFeatures( use_last_in_fitch_parsimony );
837 preparePhylogeny( local_phylogeny_copy,
838 secondary_features_parsimony,
840 "Fitch parsimony on secondary binary domain combination presence/absence randomization: "
842 "fitch_on_binary_domain_combinations_" + outfile_name,
844 SurfacingUtil.writePhylogenyToFile( local_phylogeny_copy, outfile_name
845 + surfacing.BINARY_DOMAIN_COMBINATIONS_PARSIMONY_TREE_OUTPUT_SUFFIX_FITCH_MAPPED );
846 calculateIndependentDomainCombinationGains( local_phylogeny_copy, outfile_name
847 + surfacing.INDEPENDENT_DC_GAINS_FITCH_PARS_COUNTS_MAPPED_OUTPUT_SUFFIX, outfile_name
848 + surfacing.INDEPENDENT_DC_GAINS_FITCH_PARS_DC_MAPPED_OUTPUT_SUFFIX, outfile_name
849 + surfacing.INDEPENDENT_DC_GAINS_FITCH_PARS_DC_FOR_GO_MAPPING_MAPPED_OUTPUT_SUFFIX, outfile_name
850 + surfacing.INDEPENDENT_DC_GAINS_FITCH_PARS_DC_FOR_GO_MAPPING_MAPPED_OUTPUT_UNIQUE_SUFFIX, outfile_name
851 + "_MAPPED_indep_dc_gains_fitch_lca_ranks.txt", outfile_name
852 + "_MAPPED_indep_dc_gains_fitch_lca_taxonomies.txt", null, null, null, null );
855 public static void extractProteinNames( final List<Protein> proteins,
856 final List<String> query_domain_ids_nc_order,
858 final String separator,
859 final String limit_to_species ) throws IOException {
860 for( final Protein protein : proteins ) {
861 if ( ForesterUtil.isEmpty( limit_to_species )
862 || protein.getSpecies().getSpeciesId().equalsIgnoreCase( limit_to_species ) ) {
863 if ( protein.contains( query_domain_ids_nc_order, true ) ) {
864 out.write( protein.getSpecies().getSpeciesId() );
865 out.write( separator );
866 out.write( protein.getProteinId().getId() );
867 out.write( separator );
869 final Set<String> visited_domain_ids = new HashSet<String>();
870 boolean first = true;
871 for( final Domain domain : protein.getProteinDomains() ) {
872 if ( !visited_domain_ids.contains( domain.getDomainId() ) ) {
873 visited_domain_ids.add( domain.getDomainId() );
880 out.write( domain.getDomainId() );
882 out.write( "" + domain.getTotalCount() );
887 out.write( separator );
888 if ( !( ForesterUtil.isEmpty( protein.getDescription() ) || protein.getDescription()
889 .equals( SurfacingConstants.NONE ) ) ) {
890 out.write( protein.getDescription() );
892 out.write( separator );
893 if ( !( ForesterUtil.isEmpty( protein.getAccession() ) || protein.getAccession()
894 .equals( SurfacingConstants.NONE ) ) ) {
895 out.write( protein.getAccession() );
897 out.write( SurfacingConstants.NL );
904 public static void extractProteinNames( final SortedMap<Species, List<Protein>> protein_lists_per_species,
905 final String domain_id,
907 final String separator,
908 final String limit_to_species,
909 final double domain_e_cutoff ) throws IOException {
910 System.out.println( "Per domain E-value: " + domain_e_cutoff );
911 for( final Species species : protein_lists_per_species.keySet() ) {
912 System.out.println( species + ":" );
913 for( final Protein protein : protein_lists_per_species.get( species ) ) {
914 if ( ForesterUtil.isEmpty( limit_to_species )
915 || protein.getSpecies().getSpeciesId().equalsIgnoreCase( limit_to_species ) ) {
916 final List<Domain> domains = protein.getProteinDomains( domain_id );
917 if ( domains.size() > 0 ) {
918 out.write( protein.getSpecies().getSpeciesId() );
919 out.write( separator );
920 out.write( protein.getProteinId().getId() );
921 out.write( separator );
922 out.write( domain_id.toString() );
923 out.write( separator );
925 for( final Domain domain : domains ) {
926 if ( ( domain_e_cutoff < 0 ) || ( domain.getPerDomainEvalue() <= domain_e_cutoff ) ) {
928 out.write( domain.getFrom() + "-" + domain.getTo() );
929 if ( prev_to >= 0 ) {
930 final int l = domain.getFrom() - prev_to;
931 System.out.println( l );
933 prev_to = domain.getTo();
937 out.write( separator );
938 final List<Domain> domain_list = new ArrayList<Domain>();
939 for( final Domain domain : protein.getProteinDomains() ) {
940 if ( ( domain_e_cutoff < 0 ) || ( domain.getPerDomainEvalue() <= domain_e_cutoff ) ) {
941 domain_list.add( domain );
944 final Domain domain_ary[] = new Domain[ domain_list.size() ];
945 for( int i = 0; i < domain_list.size(); ++i ) {
946 domain_ary[ i ] = domain_list.get( i );
948 Arrays.sort( domain_ary, new DomainComparator( true ) );
950 boolean first = true;
951 for( final Domain domain : domain_ary ) {
958 out.write( domain.getDomainId().toString() );
959 out.write( ":" + domain.getFrom() + "-" + domain.getTo() );
960 out.write( ":" + domain.getPerDomainEvalue() );
963 if ( !( ForesterUtil.isEmpty( protein.getDescription() ) || protein.getDescription()
964 .equals( SurfacingConstants.NONE ) ) ) {
965 out.write( protein.getDescription() );
967 out.write( separator );
968 if ( !( ForesterUtil.isEmpty( protein.getAccession() ) || protein.getAccession()
969 .equals( SurfacingConstants.NONE ) ) ) {
970 out.write( protein.getAccession() );
972 out.write( SurfacingConstants.NL );
980 public static SortedSet<String> getAllDomainIds( final List<GenomeWideCombinableDomains> gwcd_list ) {
981 final SortedSet<String> all_domains_ids = new TreeSet<String>();
982 for( final GenomeWideCombinableDomains gwcd : gwcd_list ) {
983 final Set<String> all_domains = gwcd.getAllDomainIds();
984 // for( final Domain domain : all_domains ) {
985 all_domains_ids.addAll( all_domains );
988 return all_domains_ids;
991 public static SortedMap<String, Integer> getDomainCounts( final List<Protein> protein_domain_collections ) {
992 final SortedMap<String, Integer> map = new TreeMap<String, Integer>();
993 for( final Protein protein_domain_collection : protein_domain_collections ) {
994 for( final Object name : protein_domain_collection.getProteinDomains() ) {
995 final BasicDomain protein_domain = ( BasicDomain ) name;
996 final String id = protein_domain.getDomainId();
997 if ( map.containsKey( id ) ) {
998 map.put( id, map.get( id ) + 1 );
1008 public static int getNumberOfNodesLackingName( final Phylogeny p, final StringBuilder names ) {
1009 final PhylogenyNodeIterator it = p.iteratorPostorder();
1011 while ( it.hasNext() ) {
1012 final PhylogenyNode n = it.next();
1013 if ( ForesterUtil.isEmpty( n.getName() )
1014 && ( !n.getNodeData().isHasTaxonomy() || ForesterUtil.isEmpty( n.getNodeData().getTaxonomy()
1015 .getScientificName() ) )
1016 && ( !n.getNodeData().isHasTaxonomy() || ForesterUtil.isEmpty( n.getNodeData().getTaxonomy()
1017 .getCommonName() ) ) ) {
1018 if ( n.getParent() != null ) {
1019 names.append( " " );
1020 names.append( n.getParent().getName() );
1022 final List l = n.getAllExternalDescendants();
1023 for( final Object object : l ) {
1024 System.out.println( l.toString() );
1033 * Returns true is Domain domain falls in an uninterrupted stretch of
1034 * covered positions.
1037 * @param covered_positions
1040 public static boolean isEngulfed( final Domain domain, final List<Boolean> covered_positions ) {
1041 for( int i = domain.getFrom(); i <= domain.getTo(); ++i ) {
1042 if ( ( i >= covered_positions.size() ) || ( covered_positions.get( i ) != true ) ) {
1049 public static void performDomainArchitectureAnalysis( final SortedMap<String, Set<String>> domain_architecutures,
1050 final SortedMap<String, Integer> domain_architecuture_counts,
1051 final int min_count,
1052 final File da_counts_outfile,
1053 final File unique_da_outfile ) {
1054 checkForOutputFileWriteability( da_counts_outfile );
1055 checkForOutputFileWriteability( unique_da_outfile );
1057 final BufferedWriter da_counts_out = new BufferedWriter( new FileWriter( da_counts_outfile ) );
1058 final BufferedWriter unique_da_out = new BufferedWriter( new FileWriter( unique_da_outfile ) );
1059 final Iterator<Entry<String, Integer>> it = domain_architecuture_counts.entrySet().iterator();
1060 while ( it.hasNext() ) {
1061 final Map.Entry<String, Integer> e = it.next();
1062 final String da = e.getKey();
1063 final int count = e.getValue();
1064 if ( count >= min_count ) {
1065 da_counts_out.write( da );
1066 da_counts_out.write( "\t" );
1067 da_counts_out.write( String.valueOf( count ) );
1068 da_counts_out.write( ForesterUtil.LINE_SEPARATOR );
1071 final Iterator<Entry<String, Set<String>>> it2 = domain_architecutures.entrySet().iterator();
1072 while ( it2.hasNext() ) {
1073 final Map.Entry<String, Set<String>> e2 = it2.next();
1074 final String genome = e2.getKey();
1075 final Set<String> das = e2.getValue();
1076 if ( das.contains( da ) ) {
1077 unique_da_out.write( genome );
1078 unique_da_out.write( "\t" );
1079 unique_da_out.write( da );
1080 unique_da_out.write( ForesterUtil.LINE_SEPARATOR );
1085 unique_da_out.close();
1086 da_counts_out.close();
1088 catch ( final IOException e ) {
1089 ForesterUtil.fatalError( surfacing.PRG_NAME, e.getMessage() );
1091 ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote distance matrices to \"" + da_counts_outfile + "\"" );
1092 ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote distance matrices to \"" + unique_da_outfile + "\"" );
1096 public static void preparePhylogeny( final Phylogeny p,
1097 final DomainParsimonyCalculator domain_parsimony,
1098 final String date_time,
1099 final String method,
1101 final String parameters_str ) {
1102 domain_parsimony.decoratePhylogenyWithDomains( p );
1103 final StringBuilder desc = new StringBuilder();
1104 desc.append( "[Method: " + method + "] [Date: " + date_time + "] " );
1105 desc.append( "[Cost: " + domain_parsimony.getCost() + "] " );
1106 desc.append( "[Gains: " + domain_parsimony.getTotalGains() + "] " );
1107 desc.append( "[Losses: " + domain_parsimony.getTotalLosses() + "] " );
1108 desc.append( "[Unchanged: " + domain_parsimony.getTotalUnchanged() + "] " );
1109 desc.append( "[Parameters: " + parameters_str + "]" );
1111 p.setDescription( desc.toString() );
1112 p.setConfidence( new Confidence( domain_parsimony.getCost(), "parsimony" ) );
1113 p.setRerootable( false );
1114 p.setRooted( true );
1118 * species | protein id | n-terminal domain | c-terminal domain | n-terminal domain per domain E-value | c-terminal domain per domain E-value
1122 static public StringBuffer proteinToDomainCombinations( final Protein protein,
1123 final String protein_id,
1124 final String separator ) {
1125 final StringBuffer sb = new StringBuffer();
1126 if ( protein.getSpecies() == null ) {
1127 throw new IllegalArgumentException( "species must not be null" );
1129 if ( ForesterUtil.isEmpty( protein.getSpecies().getSpeciesId() ) ) {
1130 throw new IllegalArgumentException( "species id must not be empty" );
1132 final List<Domain> domains = protein.getProteinDomains();
1133 if ( domains.size() > 1 ) {
1134 final Map<String, Integer> counts = new HashMap<String, Integer>();
1135 for( final Domain domain : domains ) {
1136 final String id = domain.getDomainId();
1137 if ( counts.containsKey( id ) ) {
1138 counts.put( id, counts.get( id ) + 1 );
1141 counts.put( id, 1 );
1144 final Set<String> dcs = new HashSet<String>();
1145 for( int i = 1; i < domains.size(); ++i ) {
1146 for( int j = 0; j < i; ++j ) {
1147 Domain domain_n = domains.get( i );
1148 Domain domain_c = domains.get( j );
1149 if ( domain_n.getFrom() > domain_c.getFrom() ) {
1150 domain_n = domains.get( j );
1151 domain_c = domains.get( i );
1153 final String dc = domain_n.getDomainId() + domain_c.getDomainId();
1154 if ( !dcs.contains( dc ) ) {
1156 sb.append( protein.getSpecies() );
1157 sb.append( separator );
1158 sb.append( protein_id );
1159 sb.append( separator );
1160 sb.append( domain_n.getDomainId() );
1161 sb.append( separator );
1162 sb.append( domain_c.getDomainId() );
1163 sb.append( separator );
1164 sb.append( domain_n.getPerDomainEvalue() );
1165 sb.append( separator );
1166 sb.append( domain_c.getPerDomainEvalue() );
1167 sb.append( separator );
1168 sb.append( counts.get( domain_n.getDomainId() ) );
1169 sb.append( separator );
1170 sb.append( counts.get( domain_c.getDomainId() ) );
1171 sb.append( ForesterUtil.LINE_SEPARATOR );
1176 else if ( domains.size() == 1 ) {
1177 sb.append( protein.getSpecies() );
1178 sb.append( separator );
1179 sb.append( protein_id );
1180 sb.append( separator );
1181 sb.append( domains.get( 0 ).getDomainId() );
1182 sb.append( separator );
1183 sb.append( separator );
1184 sb.append( domains.get( 0 ).getPerDomainEvalue() );
1185 sb.append( separator );
1186 sb.append( separator );
1188 sb.append( separator );
1189 sb.append( ForesterUtil.LINE_SEPARATOR );
1192 sb.append( protein.getSpecies() );
1193 sb.append( separator );
1194 sb.append( protein_id );
1195 sb.append( separator );
1196 sb.append( separator );
1197 sb.append( separator );
1198 sb.append( separator );
1199 sb.append( separator );
1200 sb.append( separator );
1201 sb.append( ForesterUtil.LINE_SEPARATOR );
1208 * Example regarding engulfment: ------------0.1 ----------0.2 --0.3 =>
1209 * domain with 0.3 is ignored
1211 * -----------0.1 ----------0.2 --0.3 => domain with 0.3 is ignored
1214 * ------------0.1 ----------0.3 --0.2 => domains with 0.3 and 0.2 are _not_
1217 * @param max_allowed_overlap
1218 * maximal allowed overlap (inclusive) to be still considered not
1219 * overlapping (zero or negative value to allow any overlap)
1220 * @param remove_engulfed_domains
1221 * to remove domains which are completely engulfed by coverage of
1222 * domains with better support
1226 public static Protein removeOverlappingDomains( final int max_allowed_overlap,
1227 final boolean remove_engulfed_domains,
1228 final Protein protein ) {
1229 final Protein pruned_protein = new BasicProtein( protein.getProteinId().getId(), protein.getSpecies()
1230 .getSpeciesId(), protein.getLength() );
1231 final List<Domain> sorted = SurfacingUtil.sortDomainsWithAscendingConfidenceValues( protein );
1232 final List<Boolean> covered_positions = new ArrayList<Boolean>();
1233 for( final Domain domain : sorted ) {
1234 if ( ( ( max_allowed_overlap < 0 ) || ( SurfacingUtil.calculateOverlap( domain, covered_positions ) <= max_allowed_overlap ) )
1235 && ( !remove_engulfed_domains || !isEngulfed( domain, covered_positions ) ) ) {
1236 final int covered_positions_size = covered_positions.size();
1237 for( int i = covered_positions_size; i < domain.getFrom(); ++i ) {
1238 covered_positions.add( false );
1240 final int new_covered_positions_size = covered_positions.size();
1241 for( int i = domain.getFrom(); i <= domain.getTo(); ++i ) {
1242 if ( i < new_covered_positions_size ) {
1243 covered_positions.set( i, true );
1246 covered_positions.add( true );
1249 pruned_protein.addProteinDomain( domain );
1252 return pruned_protein;
1255 public static List<Domain> sortDomainsWithAscendingConfidenceValues( final Protein protein ) {
1256 final List<Domain> domains = new ArrayList<Domain>();
1257 for( final Domain d : protein.getProteinDomains() ) {
1260 Collections.sort( domains, SurfacingUtil.ASCENDING_CONFIDENCE_VALUE_ORDER );
1264 public static int storeDomainArchitectures( final String genome,
1265 final SortedMap<String, Set<String>> domain_architecutures,
1266 final List<Protein> protein_list,
1267 final Map<String, Integer> distinct_domain_architecuture_counts ) {
1268 final Set<String> da = new HashSet<String>();
1269 domain_architecutures.put( genome, da );
1270 for( final Protein protein : protein_list ) {
1271 final String da_str = ( ( BasicProtein ) protein ).toDomainArchitectureString( "~", 3, "=" );
1272 if ( !da.contains( da_str ) ) {
1273 if ( !distinct_domain_architecuture_counts.containsKey( da_str ) ) {
1274 distinct_domain_architecuture_counts.put( da_str, 1 );
1277 distinct_domain_architecuture_counts.put( da_str,
1278 distinct_domain_architecuture_counts.get( da_str ) + 1 );
1286 public static void writeAllDomainsChangedOnAllSubtrees( final Phylogeny p,
1287 final boolean get_gains,
1288 final String outdir,
1289 final String suffix_for_filename ) throws IOException {
1290 CharacterStateMatrix.GainLossStates state = CharacterStateMatrix.GainLossStates.GAIN;
1292 state = CharacterStateMatrix.GainLossStates.LOSS;
1294 final File base_dir = createBaseDirForPerNodeDomainFiles( surfacing.BASE_DIRECTORY_PER_SUBTREE_DOMAIN_GAIN_LOSS_FILES,
1298 for( final PhylogenyNodeIterator it = p.iteratorPostorder(); it.hasNext(); ) {
1299 final PhylogenyNode node = it.next();
1300 if ( !node.isExternal() ) {
1301 final SortedSet<String> domains = collectAllDomainsChangedOnSubtree( node, get_gains );
1302 if ( domains.size() > 0 ) {
1303 final Writer writer = ForesterUtil.createBufferedWriter( base_dir + ForesterUtil.FILE_SEPARATOR
1304 + node.getName() + suffix_for_filename );
1305 for( final String domain : domains ) {
1306 writer.write( domain );
1307 writer.write( ForesterUtil.LINE_SEPARATOR );
1315 public static void writeBinaryDomainCombinationsFileForGraphAnalysis( final String[][] input_file_properties,
1316 final File output_dir,
1317 final GenomeWideCombinableDomains gwcd,
1319 final GenomeWideCombinableDomainsSortOrder dc_sort_order ) {
1320 File dc_outfile_dot = new File( input_file_properties[ i ][ 1 ]
1321 + surfacing.DOMAIN_COMBINITONS_OUTPUTFILE_SUFFIX_FOR_GRAPH_ANALYSIS );
1322 if ( output_dir != null ) {
1323 dc_outfile_dot = new File( output_dir + ForesterUtil.FILE_SEPARATOR + dc_outfile_dot );
1325 checkForOutputFileWriteability( dc_outfile_dot );
1326 final SortedSet<BinaryDomainCombination> binary_combinations = createSetOfAllBinaryDomainCombinationsPerGenome( gwcd );
1328 final BufferedWriter out_dot = new BufferedWriter( new FileWriter( dc_outfile_dot ) );
1329 for( final BinaryDomainCombination bdc : binary_combinations ) {
1330 out_dot.write( bdc.toGraphDescribingLanguage( BinaryDomainCombination.OutputFormat.DOT, null, null )
1332 out_dot.write( SurfacingConstants.NL );
1336 catch ( final IOException e ) {
1337 ForesterUtil.fatalError( surfacing.PRG_NAME, e.getMessage() );
1339 ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote binary domain combination for \""
1340 + input_file_properties[ i ][ 0 ] + "\" (" + input_file_properties[ i ][ 1 ] + ", "
1341 + input_file_properties[ i ][ 2 ] + ") to: \"" + dc_outfile_dot + "\"" );
1344 public static void writeBinaryStatesMatrixAsListToFile( final CharacterStateMatrix<CharacterStateMatrix.GainLossStates> matrix,
1345 final CharacterStateMatrix.GainLossStates state,
1346 final String filename,
1347 final String indentifier_characters_separator,
1348 final String character_separator,
1349 final Map<String, String> descriptions ) {
1350 final File outfile = new File( filename );
1351 checkForOutputFileWriteability( outfile );
1352 final SortedSet<String> sorted_ids = new TreeSet<String>();
1353 for( int i = 0; i < matrix.getNumberOfIdentifiers(); ++i ) {
1354 sorted_ids.add( matrix.getIdentifier( i ) );
1357 final BufferedWriter out = new BufferedWriter( new FileWriter( outfile ) );
1358 for( final String id : sorted_ids ) {
1359 out.write( indentifier_characters_separator );
1360 out.write( "#" + id );
1361 out.write( indentifier_characters_separator );
1362 for( int c = 0; c < matrix.getNumberOfCharacters(); ++c ) {
1364 // using null to indicate either UNCHANGED_PRESENT or GAIN.
1365 if ( ( matrix.getState( id, c ) == state )
1366 || ( ( state == null ) && ( ( matrix.getState( id, c ) == CharacterStateMatrix.GainLossStates.GAIN ) || ( matrix
1367 .getState( id, c ) == CharacterStateMatrix.GainLossStates.UNCHANGED_PRESENT ) ) ) ) {
1368 out.write( matrix.getCharacter( c ) );
1369 if ( ( descriptions != null ) && !descriptions.isEmpty()
1370 && descriptions.containsKey( matrix.getCharacter( c ) ) ) {
1372 out.write( descriptions.get( matrix.getCharacter( c ) ) );
1374 out.write( character_separator );
1381 catch ( final IOException e ) {
1382 ForesterUtil.fatalError( surfacing.PRG_NAME, e.getMessage() );
1384 ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote characters list: \"" + filename + "\"" );
1387 public static void writeBinaryStatesMatrixAsListToFileForBinaryCombinationsForGraphAnalysis( final CharacterStateMatrix<CharacterStateMatrix.GainLossStates> matrix,
1388 final CharacterStateMatrix.GainLossStates state,
1389 final String filename,
1390 final String indentifier_characters_separator,
1391 final String character_separator,
1392 final BinaryDomainCombination.OutputFormat bc_output_format ) {
1393 final File outfile = new File( filename );
1394 checkForOutputFileWriteability( outfile );
1395 final SortedSet<String> sorted_ids = new TreeSet<String>();
1396 for( int i = 0; i < matrix.getNumberOfIdentifiers(); ++i ) {
1397 sorted_ids.add( matrix.getIdentifier( i ) );
1400 final BufferedWriter out = new BufferedWriter( new FileWriter( outfile ) );
1401 for( final String id : sorted_ids ) {
1402 out.write( indentifier_characters_separator );
1403 out.write( "#" + id );
1404 out.write( indentifier_characters_separator );
1405 for( int c = 0; c < matrix.getNumberOfCharacters(); ++c ) {
1407 // using null to indicate either UNCHANGED_PRESENT or GAIN.
1408 if ( ( matrix.getState( id, c ) == state )
1409 || ( ( state == null ) && ( ( matrix.getState( id, c ) == CharacterStateMatrix.GainLossStates.GAIN ) || ( matrix
1410 .getState( id, c ) == CharacterStateMatrix.GainLossStates.UNCHANGED_PRESENT ) ) ) ) {
1411 BinaryDomainCombination bdc = null;
1413 bdc = BasicBinaryDomainCombination.createInstance( matrix.getCharacter( c ) );
1415 catch ( final Exception e ) {
1416 ForesterUtil.fatalError( surfacing.PRG_NAME, e.getLocalizedMessage() );
1418 out.write( bdc.toGraphDescribingLanguage( bc_output_format, null, null ).toString() );
1419 out.write( character_separator );
1426 catch ( final IOException e ) {
1427 ForesterUtil.fatalError( surfacing.PRG_NAME, e.getMessage() );
1429 ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote characters list: \"" + filename + "\"" );
1432 public static void writeBinaryStatesMatrixToList( final Map<String, List<GoId>> domain_id_to_go_ids_map,
1433 final Map<GoId, GoTerm> go_id_to_term_map,
1434 final GoNameSpace go_namespace_limit,
1435 final boolean domain_combinations,
1436 final CharacterStateMatrix<CharacterStateMatrix.GainLossStates> matrix,
1437 final CharacterStateMatrix.GainLossStates state,
1438 final String filename,
1439 final String indentifier_characters_separator,
1440 final String character_separator,
1441 final String title_for_html,
1442 final String prefix_for_html,
1443 final Map<String, Set<String>>[] domain_id_to_secondary_features_maps,
1444 final SortedSet<String> all_pfams_encountered,
1445 final SortedSet<String> pfams_gained_or_lost,
1446 final String suffix_for_per_node_events_file,
1447 final Map<String, Integer> tax_code_to_id_map ) {
1448 if ( ( go_namespace_limit != null ) && ( ( go_id_to_term_map == null ) || ( go_id_to_term_map.size() < 1 ) ) ) {
1449 throw new IllegalArgumentException( "attempt to use GO namespace limit without a GO-id to term map" );
1451 else if ( ( ( domain_id_to_go_ids_map == null ) || ( domain_id_to_go_ids_map.size() < 1 ) ) ) {
1452 throw new IllegalArgumentException( "attempt to output detailed HTML without a Pfam to GO map" );
1454 else if ( ( ( go_id_to_term_map == null ) || ( go_id_to_term_map.size() < 1 ) ) ) {
1455 throw new IllegalArgumentException( "attempt to output detailed HTML without a GO-id to term map" );
1457 final File outfile = new File( filename );
1458 checkForOutputFileWriteability( outfile );
1459 final SortedSet<String> sorted_ids = new TreeSet<String>();
1460 for( int i = 0; i < matrix.getNumberOfIdentifiers(); ++i ) {
1461 sorted_ids.add( matrix.getIdentifier( i ) );
1464 final Writer out = new BufferedWriter( new FileWriter( outfile ) );
1465 final File per_node_go_mapped_domain_gain_loss_files_base_dir = createBaseDirForPerNodeDomainFiles( surfacing.BASE_DIRECTORY_PER_NODE_DOMAIN_GAIN_LOSS_FILES,
1466 domain_combinations,
1469 Writer per_node_go_mapped_domain_gain_loss_outfile_writer = null;
1470 File per_node_go_mapped_domain_gain_loss_outfile = null;
1471 int per_node_counter = 0;
1472 out.write( "<html>" );
1473 out.write( SurfacingConstants.NL );
1474 addHtmlHead( out, title_for_html );
1475 out.write( SurfacingConstants.NL );
1476 out.write( "<body>" );
1477 out.write( SurfacingConstants.NL );
1478 out.write( "<h1>" );
1479 out.write( SurfacingConstants.NL );
1480 out.write( title_for_html );
1481 out.write( SurfacingConstants.NL );
1482 out.write( "</h1>" );
1483 out.write( SurfacingConstants.NL );
1484 out.write( "<table>" );
1485 out.write( SurfacingConstants.NL );
1486 for( final String id : sorted_ids ) {
1487 final Matcher matcher = PATTERN_SP_STYLE_TAXONOMY.matcher( id );
1488 if ( matcher.matches() ) {
1491 out.write( "<tr>" );
1492 out.write( "<td>" );
1493 out.write( "<a href=\"#" + id + "\">" + id + "</a>" );
1494 out.write( "</td>" );
1495 out.write( "</tr>" );
1496 out.write( SurfacingConstants.NL );
1498 out.write( "</table>" );
1499 out.write( SurfacingConstants.NL );
1500 for( final String id : sorted_ids ) {
1501 final Matcher matcher = PATTERN_SP_STYLE_TAXONOMY.matcher( id );
1502 if ( matcher.matches() ) {
1505 out.write( SurfacingConstants.NL );
1506 out.write( "<h2>" );
1507 out.write( "<a name=\"" + id + "\">" + id + "</a>" );
1508 writeTaxonomyLinks( out, id, tax_code_to_id_map );
1509 out.write( "</h2>" );
1510 out.write( SurfacingConstants.NL );
1511 out.write( "<table>" );
1512 out.write( SurfacingConstants.NL );
1513 out.write( "<tr>" );
1514 out.write( "<td><b>" );
1515 out.write( "Pfam domain(s)" );
1516 out.write( "</b></td><td><b>" );
1517 out.write( "GO term acc" );
1518 out.write( "</b></td><td><b>" );
1519 out.write( "GO term" );
1520 out.write( "</b></td><td><b>" );
1521 out.write( "GO namespace" );
1522 out.write( "</b></td>" );
1523 out.write( "</tr>" );
1524 out.write( SurfacingConstants.NL );
1525 out.write( "</tr>" );
1526 out.write( SurfacingConstants.NL );
1527 per_node_counter = 0;
1528 if ( matrix.getNumberOfCharacters() > 0 ) {
1529 per_node_go_mapped_domain_gain_loss_outfile = new File( per_node_go_mapped_domain_gain_loss_files_base_dir
1530 + ForesterUtil.FILE_SEPARATOR + id + suffix_for_per_node_events_file );
1531 SurfacingUtil.checkForOutputFileWriteability( per_node_go_mapped_domain_gain_loss_outfile );
1532 per_node_go_mapped_domain_gain_loss_outfile_writer = ForesterUtil
1533 .createBufferedWriter( per_node_go_mapped_domain_gain_loss_outfile );
1536 per_node_go_mapped_domain_gain_loss_outfile = null;
1537 per_node_go_mapped_domain_gain_loss_outfile_writer = null;
1539 for( int c = 0; c < matrix.getNumberOfCharacters(); ++c ) {
1541 // using null to indicate either UNCHANGED_PRESENT or GAIN.
1542 if ( ( matrix.getState( id, c ) == state )
1543 || ( ( state == null ) && ( ( matrix.getState( id, c ) == CharacterStateMatrix.GainLossStates.UNCHANGED_PRESENT ) || ( matrix
1544 .getState( id, c ) == CharacterStateMatrix.GainLossStates.GAIN ) ) ) ) {
1545 final String character = matrix.getCharacter( c );
1546 String domain_0 = "";
1547 String domain_1 = "";
1548 if ( character.indexOf( BinaryDomainCombination.SEPARATOR ) > 0 ) {
1549 final String[] s = character.split( BinaryDomainCombination.SEPARATOR );
1550 if ( s.length != 2 ) {
1551 throw new AssertionError( "this should not have happened: unexpected format for domain combination: ["
1552 + character + "]" );
1558 domain_0 = character;
1560 writeDomainData( domain_id_to_go_ids_map,
1567 character_separator,
1568 domain_id_to_secondary_features_maps,
1570 all_pfams_encountered.add( domain_0 );
1571 if ( pfams_gained_or_lost != null ) {
1572 pfams_gained_or_lost.add( domain_0 );
1574 if ( !ForesterUtil.isEmpty( domain_1 ) ) {
1575 all_pfams_encountered.add( domain_1 );
1576 if ( pfams_gained_or_lost != null ) {
1577 pfams_gained_or_lost.add( domain_1 );
1580 if ( per_node_go_mapped_domain_gain_loss_outfile_writer != null ) {
1581 writeDomainsToIndividualFilePerTreeNode( per_node_go_mapped_domain_gain_loss_outfile_writer,
1588 if ( per_node_go_mapped_domain_gain_loss_outfile_writer != null ) {
1589 per_node_go_mapped_domain_gain_loss_outfile_writer.close();
1590 if ( per_node_counter < 1 ) {
1591 per_node_go_mapped_domain_gain_loss_outfile.delete();
1593 per_node_counter = 0;
1595 out.write( "</table>" );
1596 out.write( SurfacingConstants.NL );
1597 out.write( "<hr>" );
1598 out.write( SurfacingConstants.NL );
1599 } // for( final String id : sorted_ids ) {
1600 out.write( "</body>" );
1601 out.write( SurfacingConstants.NL );
1602 out.write( "</html>" );
1603 out.write( SurfacingConstants.NL );
1607 catch ( final IOException e ) {
1608 ForesterUtil.fatalError( surfacing.PRG_NAME, e.getMessage() );
1610 ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote characters detailed HTML list: \"" + filename + "\"" );
1613 public static void writeDomainCombinationsCountsFile( final String[][] input_file_properties,
1614 final File output_dir,
1615 final Writer per_genome_domain_promiscuity_statistics_writer,
1616 final GenomeWideCombinableDomains gwcd,
1618 final GenomeWideCombinableDomains.GenomeWideCombinableDomainsSortOrder dc_sort_order ) {
1619 File dc_outfile = new File( input_file_properties[ i ][ 1 ]
1620 + surfacing.DOMAIN_COMBINITON_COUNTS_OUTPUTFILE_SUFFIX );
1621 if ( output_dir != null ) {
1622 dc_outfile = new File( output_dir + ForesterUtil.FILE_SEPARATOR + dc_outfile );
1624 checkForOutputFileWriteability( dc_outfile );
1626 final BufferedWriter out = new BufferedWriter( new FileWriter( dc_outfile ) );
1627 out.write( gwcd.toStringBuilder( dc_sort_order ).toString() );
1630 catch ( final IOException e ) {
1631 ForesterUtil.fatalError( surfacing.PRG_NAME, e.getMessage() );
1633 final DescriptiveStatistics stats = gwcd.getPerGenomeDomainPromiscuityStatistics();
1635 per_genome_domain_promiscuity_statistics_writer.write( input_file_properties[ i ][ 1 ] + "\t" );
1636 per_genome_domain_promiscuity_statistics_writer.write( FORMATTER_3.format( stats.arithmeticMean() ) + "\t" );
1637 if ( stats.getN() < 2 ) {
1638 per_genome_domain_promiscuity_statistics_writer.write( "n/a" + "\t" );
1641 per_genome_domain_promiscuity_statistics_writer.write( FORMATTER_3.format( stats
1642 .sampleStandardDeviation() ) + "\t" );
1644 per_genome_domain_promiscuity_statistics_writer.write( FORMATTER_3.format( stats.median() ) + "\t" );
1645 per_genome_domain_promiscuity_statistics_writer.write( ( int ) stats.getMin() + "\t" );
1646 per_genome_domain_promiscuity_statistics_writer.write( ( int ) stats.getMax() + "\t" );
1647 per_genome_domain_promiscuity_statistics_writer.write( stats.getN() + "\t" );
1648 final SortedSet<String> mpds = gwcd.getMostPromiscuosDomain();
1649 for( final String mpd : mpds ) {
1650 per_genome_domain_promiscuity_statistics_writer.write( mpd + " " );
1652 per_genome_domain_promiscuity_statistics_writer.write( ForesterUtil.LINE_SEPARATOR );
1654 catch ( final IOException e ) {
1655 ForesterUtil.fatalError( surfacing.PRG_NAME, e.getMessage() );
1657 if ( input_file_properties[ i ].length == 3 ) {
1658 ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote domain combination counts for \""
1659 + input_file_properties[ i ][ 0 ] + "\" (" + input_file_properties[ i ][ 1 ] + ", "
1660 + input_file_properties[ i ][ 2 ] + ") to: \"" + dc_outfile + "\"" );
1663 ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote domain combination counts for \""
1664 + input_file_properties[ i ][ 0 ] + "\" (" + input_file_properties[ i ][ 1 ] + ") to: \""
1665 + dc_outfile + "\"" );
1669 public static void writeDomainSimilaritiesToFile( final StringBuilder html_desc,
1670 final StringBuilder html_title,
1671 final Writer simple_tab_writer,
1672 final Writer single_writer,
1673 Map<Character, Writer> split_writers,
1674 final SortedSet<DomainSimilarity> similarities,
1675 final boolean treat_as_binary,
1676 final List<Species> species_order,
1677 final PrintableDomainSimilarity.PRINT_OPTION print_option,
1678 final DomainSimilarity.DomainSimilarityScoring scoring,
1679 final boolean verbose,
1680 final Map<String, Integer> tax_code_to_id_map )
1681 throws IOException {
1682 if ( ( single_writer != null ) && ( ( split_writers == null ) || split_writers.isEmpty() ) ) {
1683 split_writers = new HashMap<Character, Writer>();
1684 split_writers.put( '_', single_writer );
1686 switch ( print_option ) {
1687 case SIMPLE_TAB_DELIMITED:
1690 for( final Character key : split_writers.keySet() ) {
1691 final Writer w = split_writers.get( key );
1692 w.write( "<html>" );
1693 w.write( SurfacingConstants.NL );
1695 addHtmlHead( w, "DC analysis (" + html_title + ") " + key.toString().toUpperCase() );
1698 addHtmlHead( w, "DC analysis (" + html_title + ")" );
1700 w.write( SurfacingConstants.NL );
1701 w.write( "<body>" );
1702 w.write( SurfacingConstants.NL );
1703 w.write( html_desc.toString() );
1704 w.write( SurfacingConstants.NL );
1706 w.write( SurfacingConstants.NL );
1708 w.write( SurfacingConstants.NL );
1709 w.write( "<table>" );
1710 w.write( SurfacingConstants.NL );
1711 w.write( "<tr><td><b>Domains:</b></td></tr>" );
1712 w.write( SurfacingConstants.NL );
1717 for( final DomainSimilarity similarity : similarities ) {
1718 if ( ( species_order != null ) && !species_order.isEmpty() ) {
1719 ( ( PrintableDomainSimilarity ) similarity ).setSpeciesOrder( species_order );
1721 if ( single_writer != null ) {
1722 single_writer.write( "<tr><td><b><a href=\"#" + similarity.getDomainId() + "\">"
1723 + similarity.getDomainId() + "</a></b></td></tr>" );
1724 single_writer.write( SurfacingConstants.NL );
1727 Writer local_writer = split_writers.get( ( similarity.getDomainId().charAt( 0 ) + "" ).toLowerCase()
1729 if ( local_writer == null ) {
1730 local_writer = split_writers.get( '0' );
1732 local_writer.write( "<tr><td><b><a href=\"#" + similarity.getDomainId() + "\">"
1733 + similarity.getDomainId() + "</a></b></td></tr>" );
1734 local_writer.write( SurfacingConstants.NL );
1737 for( final Writer w : split_writers.values() ) {
1738 w.write( "</table>" );
1739 w.write( SurfacingConstants.NL );
1741 w.write( SurfacingConstants.NL );
1742 w.write( "<table>" );
1743 w.write( SurfacingConstants.NL );
1746 for( final DomainSimilarity similarity : similarities ) {
1747 if ( ( species_order != null ) && !species_order.isEmpty() ) {
1748 ( ( PrintableDomainSimilarity ) similarity ).setSpeciesOrder( species_order );
1750 if ( simple_tab_writer != null ) {
1751 simple_tab_writer.write( similarity.toStringBuffer( PRINT_OPTION.SIMPLE_TAB_DELIMITED,
1752 tax_code_to_id_map ).toString() );
1754 if ( single_writer != null ) {
1755 single_writer.write( similarity.toStringBuffer( print_option, tax_code_to_id_map ).toString() );
1756 single_writer.write( SurfacingConstants.NL );
1759 Writer local_writer = split_writers.get( ( similarity.getDomainId().charAt( 0 ) + "" ).toLowerCase()
1761 if ( local_writer == null ) {
1762 local_writer = split_writers.get( '0' );
1764 local_writer.write( similarity.toStringBuffer( print_option, tax_code_to_id_map ).toString() );
1765 local_writer.write( SurfacingConstants.NL );
1768 switch ( print_option ) {
1770 for( final Writer w : split_writers.values() ) {
1771 w.write( SurfacingConstants.NL );
1772 w.write( "</table>" );
1773 w.write( SurfacingConstants.NL );
1774 w.write( "</font>" );
1775 w.write( SurfacingConstants.NL );
1776 w.write( "</body>" );
1777 w.write( SurfacingConstants.NL );
1778 w.write( "</html>" );
1779 w.write( SurfacingConstants.NL );
1783 for( final Writer w : split_writers.values() ) {
1788 private static void printSomeStats( final DescriptiveStatistics stats, final AsciiHistogram histo, final Writer w )
1789 throws IOException {
1792 w.write( SurfacingConstants.NL );
1793 w.write( "<tt><pre>" );
1794 w.write( SurfacingConstants.NL );
1795 if ( histo != null ) {
1796 w.write( histo.toStringBuffer( 20, '|', 40, 5 ).toString() );
1797 w.write( SurfacingConstants.NL );
1799 w.write( "</pre></tt>" );
1800 w.write( SurfacingConstants.NL );
1801 w.write( "<table>" );
1802 w.write( SurfacingConstants.NL );
1803 w.write( "<tr><td>N: </td><td>" + stats.getN() + "</td></tr>" );
1804 w.write( SurfacingConstants.NL );
1805 w.write( "<tr><td>Min: </td><td>" + stats.getMin() + "</td></tr>" );
1806 w.write( SurfacingConstants.NL );
1807 w.write( "<tr><td>Max: </td><td>" + stats.getMax() + "</td></tr>" );
1808 w.write( SurfacingConstants.NL );
1809 w.write( "<tr><td>Mean: </td><td>" + stats.arithmeticMean() + "</td></tr>" );
1810 w.write( SurfacingConstants.NL );
1811 if ( stats.getN() > 1 ) {
1812 w.write( "<tr><td>SD: </td><td>" + stats.sampleStandardDeviation() + "</td></tr>" );
1815 w.write( "<tr><td>SD: </td><td>n/a</td></tr>" );
1817 w.write( SurfacingConstants.NL );
1818 w.write( "</table>" );
1819 w.write( SurfacingConstants.NL );
1821 w.write( SurfacingConstants.NL );
1824 public static void writeMatrixToFile( final CharacterStateMatrix<?> matrix,
1825 final String filename,
1826 final Format format ) {
1827 final File outfile = new File( filename );
1828 checkForOutputFileWriteability( outfile );
1830 final BufferedWriter out = new BufferedWriter( new FileWriter( outfile ) );
1831 matrix.toWriter( out, format );
1835 catch ( final IOException e ) {
1836 ForesterUtil.fatalError( surfacing.PRG_NAME, e.getMessage() );
1838 ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote matrix: \"" + filename + "\"" );
1841 public static void writeMatrixToFile( final File matrix_outfile, final List<DistanceMatrix> matrices ) {
1842 checkForOutputFileWriteability( matrix_outfile );
1844 final BufferedWriter out = new BufferedWriter( new FileWriter( matrix_outfile ) );
1845 for( final DistanceMatrix distance_matrix : matrices ) {
1846 out.write( distance_matrix.toStringBuffer( DistanceMatrix.Format.PHYLIP ).toString() );
1847 out.write( ForesterUtil.LINE_SEPARATOR );
1852 catch ( final IOException e ) {
1853 ForesterUtil.fatalError( surfacing.PRG_NAME, e.getMessage() );
1855 ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote distance matrices to \"" + matrix_outfile + "\"" );
1858 public static void writePhylogenyToFile( final Phylogeny phylogeny, final String filename ) {
1859 final PhylogenyWriter writer = new PhylogenyWriter();
1861 writer.toPhyloXML( new File( filename ), phylogeny, 1 );
1863 catch ( final IOException e ) {
1864 ForesterUtil.printWarningMessage( surfacing.PRG_NAME, "failed to write phylogeny to \"" + filename + "\": "
1867 ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote phylogeny to \"" + filename + "\"" );
1870 public static void writeTaxonomyLinks( final Writer writer,
1871 final String species,
1872 final Map<String, Integer> tax_code_to_id_map ) throws IOException {
1873 if ( ( species.length() > 1 ) && ( species.indexOf( '_' ) < 1 ) ) {
1874 writer.write( " [" );
1875 if ( ( tax_code_to_id_map != null ) && tax_code_to_id_map.containsKey( species ) ) {
1876 writer.write( "<a href=\"" + SurfacingConstants.UNIPROT_TAXONOMY_ID_LINK
1877 + tax_code_to_id_map.get( species ) + "\" target=\"taxonomy_window\">uniprot</a>" );
1880 writer.write( "<a href=\"" + SurfacingConstants.EOL_LINK + species
1881 + "\" target=\"taxonomy_window\">eol</a>" );
1882 writer.write( "|" );
1883 writer.write( "<a href=\"" + SurfacingConstants.GOOGLE_SCHOLAR_SEARCH + species
1884 + "\" target=\"taxonomy_window\">scholar</a>" );
1885 writer.write( "|" );
1886 writer.write( "<a href=\"" + SurfacingConstants.GOOGLE_WEB_SEARCH_LINK + species
1887 + "\" target=\"taxonomy_window\">google</a>" );
1889 writer.write( "]" );
1893 private final static void addToCountMap( final Map<String, Integer> map, final String s ) {
1894 if ( map.containsKey( s ) ) {
1895 map.put( s, map.get( s ) + 1 );
1902 private static void calculateIndependentDomainCombinationGains( final Phylogeny local_phylogeny_l,
1903 final String outfilename_for_counts,
1904 final String outfilename_for_dc,
1905 final String outfilename_for_dc_for_go_mapping,
1906 final String outfilename_for_dc_for_go_mapping_unique,
1907 final String outfilename_for_rank_counts,
1908 final String outfilename_for_ancestor_species_counts,
1909 final String outfilename_for_protein_stats,
1910 final Map<String, DescriptiveStatistics> protein_length_stats_by_dc,
1911 final Map<String, DescriptiveStatistics> domain_number_stats_by_dc,
1912 final Map<String, DescriptiveStatistics> domain_length_stats_by_domain ) {
1915 // if ( protein_length_stats_by_dc != null ) {
1916 // for( final Entry<?, DescriptiveStatistics> entry : protein_length_stats_by_dc.entrySet() ) {
1917 // System.out.print( entry.getKey().toString() );
1918 // System.out.print( ": " );
1919 // double[] a = entry.getValue().getDataAsDoubleArray();
1920 // for( int i = 0; i < a.length; i++ ) {
1921 // System.out.print( a[ i ] + " " );
1923 // System.out.println();
1926 // if ( domain_number_stats_by_dc != null ) {
1927 // for( final Entry<?, DescriptiveStatistics> entry : domain_number_stats_by_dc.entrySet() ) {
1928 // System.out.print( entry.getKey().toString() );
1929 // System.out.print( ": " );
1930 // double[] a = entry.getValue().getDataAsDoubleArray();
1931 // for( int i = 0; i < a.length; i++ ) {
1932 // System.out.print( a[ i ] + " " );
1934 // System.out.println();
1938 final BufferedWriter out_counts = new BufferedWriter( new FileWriter( outfilename_for_counts ) );
1939 final BufferedWriter out_dc = new BufferedWriter( new FileWriter( outfilename_for_dc ) );
1940 final BufferedWriter out_dc_for_go_mapping = new BufferedWriter( new FileWriter( outfilename_for_dc_for_go_mapping ) );
1941 final BufferedWriter out_dc_for_go_mapping_unique = new BufferedWriter( new FileWriter( outfilename_for_dc_for_go_mapping_unique ) );
1942 final SortedMap<String, Integer> dc_gain_counts = new TreeMap<String, Integer>();
1943 for( final PhylogenyNodeIterator it = local_phylogeny_l.iteratorPostorder(); it.hasNext(); ) {
1944 final PhylogenyNode n = it.next();
1945 final Set<String> gained_dc = n.getNodeData().getBinaryCharacters().getGainedCharacters();
1946 for( final String dc : gained_dc ) {
1947 if ( dc_gain_counts.containsKey( dc ) ) {
1948 dc_gain_counts.put( dc, dc_gain_counts.get( dc ) + 1 );
1951 dc_gain_counts.put( dc, 1 );
1955 final SortedMap<Integer, Integer> histogram = new TreeMap<Integer, Integer>();
1956 final SortedMap<Integer, StringBuilder> domain_lists = new TreeMap<Integer, StringBuilder>();
1957 final SortedMap<Integer, DescriptiveStatistics> dc_reapp_counts_to_protein_length_stats = new TreeMap<Integer, DescriptiveStatistics>();
1958 final SortedMap<Integer, DescriptiveStatistics> dc_reapp_counts_to_domain_number_stats = new TreeMap<Integer, DescriptiveStatistics>();
1959 final SortedMap<Integer, DescriptiveStatistics> dc_reapp_counts_to_domain_lengths_stats = new TreeMap<Integer, DescriptiveStatistics>();
1960 final SortedMap<Integer, PriorityQueue<String>> domain_lists_go = new TreeMap<Integer, PriorityQueue<String>>();
1961 final SortedMap<Integer, SortedSet<String>> domain_lists_go_unique = new TreeMap<Integer, SortedSet<String>>();
1962 final Set<String> dcs = dc_gain_counts.keySet();
1963 final SortedSet<String> more_than_once = new TreeSet<String>();
1964 DescriptiveStatistics gained_once_lengths_stats = new BasicDescriptiveStatistics();
1965 DescriptiveStatistics gained_once_domain_count_stats = new BasicDescriptiveStatistics();
1966 DescriptiveStatistics gained_multiple_times_lengths_stats = new BasicDescriptiveStatistics();
1967 final DescriptiveStatistics gained_multiple_times_domain_count_stats = new BasicDescriptiveStatistics();
1968 long gained_multiple_times_domain_length_sum = 0;
1969 long gained_once_domain_length_sum = 0;
1970 long gained_multiple_times_domain_length_count = 0;
1971 long gained_once_domain_length_count = 0;
1972 for( final String dc : dcs ) {
1973 final int count = dc_gain_counts.get( dc );
1974 if ( histogram.containsKey( count ) ) {
1975 histogram.put( count, histogram.get( count ) + 1 );
1976 domain_lists.get( count ).append( ", " + dc );
1977 domain_lists_go.get( count ).addAll( splitDomainCombination( dc ) );
1978 domain_lists_go_unique.get( count ).addAll( splitDomainCombination( dc ) );
1981 histogram.put( count, 1 );
1982 domain_lists.put( count, new StringBuilder( dc ) );
1983 final PriorityQueue<String> q = new PriorityQueue<String>();
1984 q.addAll( splitDomainCombination( dc ) );
1985 domain_lists_go.put( count, q );
1986 final SortedSet<String> set = new TreeSet<String>();
1987 set.addAll( splitDomainCombination( dc ) );
1988 domain_lists_go_unique.put( count, set );
1990 if ( protein_length_stats_by_dc != null ) {
1991 if ( !dc_reapp_counts_to_protein_length_stats.containsKey( count ) ) {
1992 dc_reapp_counts_to_protein_length_stats.put( count, new BasicDescriptiveStatistics() );
1994 dc_reapp_counts_to_protein_length_stats.get( count ).addValue( protein_length_stats_by_dc.get( dc )
1995 .arithmeticMean() );
1997 if ( domain_number_stats_by_dc != null ) {
1998 if ( !dc_reapp_counts_to_domain_number_stats.containsKey( count ) ) {
1999 dc_reapp_counts_to_domain_number_stats.put( count, new BasicDescriptiveStatistics() );
2001 dc_reapp_counts_to_domain_number_stats.get( count ).addValue( domain_number_stats_by_dc.get( dc )
2002 .arithmeticMean() );
2004 if ( domain_length_stats_by_domain != null ) {
2005 if ( !dc_reapp_counts_to_domain_lengths_stats.containsKey( count ) ) {
2006 dc_reapp_counts_to_domain_lengths_stats.put( count, new BasicDescriptiveStatistics() );
2008 final String[] ds = dc.split( "=" );
2009 dc_reapp_counts_to_domain_lengths_stats.get( count ).addValue( domain_length_stats_by_domain
2010 .get( ds[ 0 ] ).arithmeticMean() );
2011 dc_reapp_counts_to_domain_lengths_stats.get( count ).addValue( domain_length_stats_by_domain
2012 .get( ds[ 1 ] ).arithmeticMean() );
2015 more_than_once.add( dc );
2016 if ( protein_length_stats_by_dc != null ) {
2017 final DescriptiveStatistics s = protein_length_stats_by_dc.get( dc );
2018 for( final double element : s.getData() ) {
2019 gained_multiple_times_lengths_stats.addValue( element );
2022 if ( domain_number_stats_by_dc != null ) {
2023 final DescriptiveStatistics s = domain_number_stats_by_dc.get( dc );
2024 for( final double element : s.getData() ) {
2025 gained_multiple_times_domain_count_stats.addValue( element );
2028 if ( domain_length_stats_by_domain != null ) {
2029 final String[] ds = dc.split( "=" );
2030 final DescriptiveStatistics s0 = domain_length_stats_by_domain.get( ds[ 0 ] );
2031 final DescriptiveStatistics s1 = domain_length_stats_by_domain.get( ds[ 1 ] );
2032 for( final double element : s0.getData() ) {
2033 gained_multiple_times_domain_length_sum += element;
2034 ++gained_multiple_times_domain_length_count;
2036 for( final double element : s1.getData() ) {
2037 gained_multiple_times_domain_length_sum += element;
2038 ++gained_multiple_times_domain_length_count;
2043 if ( protein_length_stats_by_dc != null ) {
2044 final DescriptiveStatistics s = protein_length_stats_by_dc.get( dc );
2045 for( final double element : s.getData() ) {
2046 gained_once_lengths_stats.addValue( element );
2049 if ( domain_number_stats_by_dc != null ) {
2050 final DescriptiveStatistics s = domain_number_stats_by_dc.get( dc );
2051 for( final double element : s.getData() ) {
2052 gained_once_domain_count_stats.addValue( element );
2055 if ( domain_length_stats_by_domain != null ) {
2056 final String[] ds = dc.split( "=" );
2057 final DescriptiveStatistics s0 = domain_length_stats_by_domain.get( ds[ 0 ] );
2058 final DescriptiveStatistics s1 = domain_length_stats_by_domain.get( ds[ 1 ] );
2059 for( final double element : s0.getData() ) {
2060 gained_once_domain_length_sum += element;
2061 ++gained_once_domain_length_count;
2063 for( final double element : s1.getData() ) {
2064 gained_once_domain_length_sum += element;
2065 ++gained_once_domain_length_count;
2070 final Set<Integer> histogram_keys = histogram.keySet();
2071 for( final Integer histogram_key : histogram_keys ) {
2072 final int count = histogram.get( histogram_key );
2073 final StringBuilder dc = domain_lists.get( histogram_key );
2074 out_counts.write( histogram_key + "\t" + count + ForesterUtil.LINE_SEPARATOR );
2075 out_dc.write( histogram_key + "\t" + dc + ForesterUtil.LINE_SEPARATOR );
2076 out_dc_for_go_mapping.write( "#" + histogram_key + ForesterUtil.LINE_SEPARATOR );
2077 final Object[] sorted = domain_lists_go.get( histogram_key ).toArray();
2078 Arrays.sort( sorted );
2079 for( final Object domain : sorted ) {
2080 out_dc_for_go_mapping.write( domain + ForesterUtil.LINE_SEPARATOR );
2082 out_dc_for_go_mapping_unique.write( "#" + histogram_key + ForesterUtil.LINE_SEPARATOR );
2083 for( final String domain : domain_lists_go_unique.get( histogram_key ) ) {
2084 out_dc_for_go_mapping_unique.write( domain + ForesterUtil.LINE_SEPARATOR );
2089 out_dc_for_go_mapping.close();
2090 out_dc_for_go_mapping_unique.close();
2091 final SortedMap<String, Integer> lca_rank_counts = new TreeMap<String, Integer>();
2092 final SortedMap<String, Integer> lca_ancestor_species_counts = new TreeMap<String, Integer>();
2093 for( final String dc : more_than_once ) {
2094 final List<PhylogenyNode> nodes = new ArrayList<PhylogenyNode>();
2095 for( final PhylogenyNodeIterator it = local_phylogeny_l.iteratorExternalForward(); it.hasNext(); ) {
2096 final PhylogenyNode n = it.next();
2097 if ( n.getNodeData().getBinaryCharacters().getGainedCharacters().contains( dc ) ) {
2101 for( int i = 0; i < ( nodes.size() - 1 ); ++i ) {
2102 for( int j = i + 1; j < nodes.size(); ++j ) {
2103 final PhylogenyNode lca = PhylogenyMethods.calculateLCA( nodes.get( i ), nodes.get( j ) );
2104 String rank = "unknown";
2105 if ( lca.getNodeData().isHasTaxonomy()
2106 && !ForesterUtil.isEmpty( lca.getNodeData().getTaxonomy().getRank() ) ) {
2107 rank = lca.getNodeData().getTaxonomy().getRank();
2109 addToCountMap( lca_rank_counts, rank );
2111 if ( lca.getNodeData().isHasTaxonomy()
2112 && !ForesterUtil.isEmpty( lca.getNodeData().getTaxonomy().getScientificName() ) ) {
2113 lca_species = lca.getNodeData().getTaxonomy().getScientificName();
2115 else if ( lca.getNodeData().isHasTaxonomy()
2116 && !ForesterUtil.isEmpty( lca.getNodeData().getTaxonomy().getCommonName() ) ) {
2117 lca_species = lca.getNodeData().getTaxonomy().getCommonName();
2120 lca_species = lca.getName();
2122 addToCountMap( lca_ancestor_species_counts, lca_species );
2126 final BufferedWriter out_for_rank_counts = new BufferedWriter( new FileWriter( outfilename_for_rank_counts ) );
2127 final BufferedWriter out_for_ancestor_species_counts = new BufferedWriter( new FileWriter( outfilename_for_ancestor_species_counts ) );
2128 ForesterUtil.map2writer( out_for_rank_counts, lca_rank_counts, "\t", ForesterUtil.LINE_SEPARATOR );
2129 ForesterUtil.map2writer( out_for_ancestor_species_counts,
2130 lca_ancestor_species_counts,
2132 ForesterUtil.LINE_SEPARATOR );
2133 out_for_rank_counts.close();
2134 out_for_ancestor_species_counts.close();
2135 if ( !ForesterUtil.isEmpty( outfilename_for_protein_stats )
2136 && ( ( domain_length_stats_by_domain != null ) || ( protein_length_stats_by_dc != null ) || ( domain_number_stats_by_dc != null ) ) ) {
2137 final BufferedWriter w = new BufferedWriter( new FileWriter( outfilename_for_protein_stats ) );
2138 w.write( "Domain Lengths: " );
2140 if ( domain_length_stats_by_domain != null ) {
2141 for( final Entry<Integer, DescriptiveStatistics> entry : dc_reapp_counts_to_domain_lengths_stats
2143 w.write( entry.getKey().toString() );
2144 w.write( "\t" + entry.getValue().arithmeticMean() );
2145 w.write( "\t" + entry.getValue().median() );
2152 w.write( "Protein Lengths: " );
2154 if ( protein_length_stats_by_dc != null ) {
2155 for( final Entry<Integer, DescriptiveStatistics> entry : dc_reapp_counts_to_protein_length_stats
2157 w.write( entry.getKey().toString() );
2158 w.write( "\t" + entry.getValue().arithmeticMean() );
2159 w.write( "\t" + entry.getValue().median() );
2166 w.write( "Number of domains: " );
2168 if ( domain_number_stats_by_dc != null ) {
2169 for( final Entry<Integer, DescriptiveStatistics> entry : dc_reapp_counts_to_domain_number_stats
2171 w.write( entry.getKey().toString() );
2172 w.write( "\t" + entry.getValue().arithmeticMean() );
2173 w.write( "\t" + entry.getValue().median() );
2180 w.write( "Gained once, domain lengths:" );
2182 w.write( "N: " + gained_once_domain_length_count );
2184 w.write( "Avg: " + ( ( double ) gained_once_domain_length_sum / gained_once_domain_length_count ) );
2187 w.write( "Gained multiple times, domain lengths:" );
2189 w.write( "N: " + gained_multiple_times_domain_length_count );
2192 + ( ( double ) gained_multiple_times_domain_length_sum / gained_multiple_times_domain_length_count ) );
2197 w.write( "Gained once, protein lengths:" );
2199 w.write( gained_once_lengths_stats.toString() );
2200 gained_once_lengths_stats = null;
2203 w.write( "Gained once, domain counts:" );
2205 w.write( gained_once_domain_count_stats.toString() );
2206 gained_once_domain_count_stats = null;
2209 w.write( "Gained multiple times, protein lengths:" );
2211 w.write( gained_multiple_times_lengths_stats.toString() );
2212 gained_multiple_times_lengths_stats = null;
2215 w.write( "Gained multiple times, domain counts:" );
2217 w.write( gained_multiple_times_domain_count_stats.toString() );
2222 catch ( final IOException e ) {
2223 ForesterUtil.printWarningMessage( surfacing.PRG_NAME, "Failure to write: " + e );
2225 ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote independent domain combination gains fitch counts to ["
2226 + outfilename_for_counts + "]" );
2227 ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote independent domain combination gains fitch lists to ["
2228 + outfilename_for_dc + "]" );
2229 ForesterUtil.programMessage( surfacing.PRG_NAME,
2230 "Wrote independent domain combination gains fitch lists to (for GO mapping) ["
2231 + outfilename_for_dc_for_go_mapping + "]" );
2232 ForesterUtil.programMessage( surfacing.PRG_NAME,
2233 "Wrote independent domain combination gains fitch lists to (for GO mapping, unique) ["
2234 + outfilename_for_dc_for_go_mapping_unique + "]" );
2237 private static SortedSet<String> collectAllDomainsChangedOnSubtree( final PhylogenyNode subtree_root,
2238 final boolean get_gains ) {
2239 final SortedSet<String> domains = new TreeSet<String>();
2240 for( final PhylogenyNode descendant : PhylogenyMethods.getAllDescendants( subtree_root ) ) {
2241 final BinaryCharacters chars = descendant.getNodeData().getBinaryCharacters();
2243 domains.addAll( chars.getGainedCharacters() );
2246 domains.addAll( chars.getLostCharacters() );
2252 private static File createBaseDirForPerNodeDomainFiles( final String base_dir,
2253 final boolean domain_combinations,
2254 final CharacterStateMatrix.GainLossStates state,
2255 final String outfile ) {
2256 File per_node_go_mapped_domain_gain_loss_files_base_dir = new File( new File( outfile ).getParent()
2257 + ForesterUtil.FILE_SEPARATOR + base_dir );
2258 if ( !per_node_go_mapped_domain_gain_loss_files_base_dir.exists() ) {
2259 per_node_go_mapped_domain_gain_loss_files_base_dir.mkdir();
2261 if ( domain_combinations ) {
2262 per_node_go_mapped_domain_gain_loss_files_base_dir = new File( per_node_go_mapped_domain_gain_loss_files_base_dir
2263 + ForesterUtil.FILE_SEPARATOR + "DC" );
2266 per_node_go_mapped_domain_gain_loss_files_base_dir = new File( per_node_go_mapped_domain_gain_loss_files_base_dir
2267 + ForesterUtil.FILE_SEPARATOR + "DOMAINS" );
2269 if ( !per_node_go_mapped_domain_gain_loss_files_base_dir.exists() ) {
2270 per_node_go_mapped_domain_gain_loss_files_base_dir.mkdir();
2272 if ( state == GainLossStates.GAIN ) {
2273 per_node_go_mapped_domain_gain_loss_files_base_dir = new File( per_node_go_mapped_domain_gain_loss_files_base_dir
2274 + ForesterUtil.FILE_SEPARATOR + "GAINS" );
2276 else if ( state == GainLossStates.LOSS ) {
2277 per_node_go_mapped_domain_gain_loss_files_base_dir = new File( per_node_go_mapped_domain_gain_loss_files_base_dir
2278 + ForesterUtil.FILE_SEPARATOR + "LOSSES" );
2281 per_node_go_mapped_domain_gain_loss_files_base_dir = new File( per_node_go_mapped_domain_gain_loss_files_base_dir
2282 + ForesterUtil.FILE_SEPARATOR + "PRESENT" );
2284 if ( !per_node_go_mapped_domain_gain_loss_files_base_dir.exists() ) {
2285 per_node_go_mapped_domain_gain_loss_files_base_dir.mkdir();
2287 return per_node_go_mapped_domain_gain_loss_files_base_dir;
2290 private static SortedSet<BinaryDomainCombination> createSetOfAllBinaryDomainCombinationsPerGenome( final GenomeWideCombinableDomains gwcd ) {
2291 final SortedMap<String, CombinableDomains> cds = gwcd.getAllCombinableDomainsIds();
2292 final SortedSet<BinaryDomainCombination> binary_combinations = new TreeSet<BinaryDomainCombination>();
2293 for( final String domain_id : cds.keySet() ) {
2294 final CombinableDomains cd = cds.get( domain_id );
2295 binary_combinations.addAll( cd.toBinaryDomainCombinations() );
2297 return binary_combinations;
2300 private static List<String> splitDomainCombination( final String dc ) {
2301 final String[] s = dc.split( "=" );
2302 if ( s.length != 2 ) {
2303 ForesterUtil.printErrorMessage( surfacing.PRG_NAME, "Stringyfied domain combination has illegal format: "
2307 final List<String> l = new ArrayList<String>( 2 );
2313 private static void writeAllEncounteredPfamsToFile( final Map<String, List<GoId>> domain_id_to_go_ids_map,
2314 final Map<GoId, GoTerm> go_id_to_term_map,
2315 final String outfile_name,
2316 final SortedSet<String> all_pfams_encountered ) {
2317 final File all_pfams_encountered_file = new File( outfile_name + surfacing.ALL_PFAMS_ENCOUNTERED_SUFFIX );
2318 final File all_pfams_encountered_with_go_annotation_file = new File( outfile_name
2319 + surfacing.ALL_PFAMS_ENCOUNTERED_WITH_GO_ANNOTATION_SUFFIX );
2320 final File encountered_pfams_summary_file = new File( outfile_name + surfacing.ENCOUNTERED_PFAMS_SUMMARY_SUFFIX );
2321 int biological_process_counter = 0;
2322 int cellular_component_counter = 0;
2323 int molecular_function_counter = 0;
2324 int pfams_with_mappings_counter = 0;
2325 int pfams_without_mappings_counter = 0;
2326 int pfams_without_mappings_to_bp_or_mf_counter = 0;
2327 int pfams_with_mappings_to_bp_or_mf_counter = 0;
2329 final Writer all_pfams_encountered_writer = new BufferedWriter( new FileWriter( all_pfams_encountered_file ) );
2330 final Writer all_pfams_encountered_with_go_annotation_writer = new BufferedWriter( new FileWriter( all_pfams_encountered_with_go_annotation_file ) );
2331 final Writer summary_writer = new BufferedWriter( new FileWriter( encountered_pfams_summary_file ) );
2332 summary_writer.write( "# Pfam to GO mapping summary" );
2333 summary_writer.write( ForesterUtil.LINE_SEPARATOR );
2334 summary_writer.write( "# Actual summary is at the end of this file." );
2335 summary_writer.write( ForesterUtil.LINE_SEPARATOR );
2336 summary_writer.write( "# Encountered Pfams without a GO mapping:" );
2337 summary_writer.write( ForesterUtil.LINE_SEPARATOR );
2338 for( final String pfam : all_pfams_encountered ) {
2339 all_pfams_encountered_writer.write( pfam );
2340 all_pfams_encountered_writer.write( ForesterUtil.LINE_SEPARATOR );
2341 final String domain_id = new String( pfam );
2342 if ( domain_id_to_go_ids_map.containsKey( domain_id ) ) {
2343 ++pfams_with_mappings_counter;
2344 all_pfams_encountered_with_go_annotation_writer.write( pfam );
2345 all_pfams_encountered_with_go_annotation_writer.write( ForesterUtil.LINE_SEPARATOR );
2346 final List<GoId> go_ids = domain_id_to_go_ids_map.get( domain_id );
2347 boolean maps_to_bp = false;
2348 boolean maps_to_cc = false;
2349 boolean maps_to_mf = false;
2350 for( final GoId go_id : go_ids ) {
2351 final GoTerm go_term = go_id_to_term_map.get( go_id );
2352 if ( go_term.getGoNameSpace().isBiologicalProcess() ) {
2355 else if ( go_term.getGoNameSpace().isCellularComponent() ) {
2358 else if ( go_term.getGoNameSpace().isMolecularFunction() ) {
2363 ++biological_process_counter;
2366 ++cellular_component_counter;
2369 ++molecular_function_counter;
2371 if ( maps_to_bp || maps_to_mf ) {
2372 ++pfams_with_mappings_to_bp_or_mf_counter;
2375 ++pfams_without_mappings_to_bp_or_mf_counter;
2379 ++pfams_without_mappings_to_bp_or_mf_counter;
2380 ++pfams_without_mappings_counter;
2381 summary_writer.write( pfam );
2382 summary_writer.write( ForesterUtil.LINE_SEPARATOR );
2385 all_pfams_encountered_writer.close();
2386 all_pfams_encountered_with_go_annotation_writer.close();
2387 ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote all [" + all_pfams_encountered.size()
2388 + "] encountered Pfams to: \"" + all_pfams_encountered_file + "\"" );
2389 ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote all [" + pfams_with_mappings_counter
2390 + "] encountered Pfams with GO mappings to: \"" + all_pfams_encountered_with_go_annotation_file
2392 ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote summary (including all ["
2393 + pfams_without_mappings_counter + "] encountered Pfams without GO mappings) to: \""
2394 + encountered_pfams_summary_file + "\"" );
2395 ForesterUtil.programMessage( surfacing.PRG_NAME, "Sum of Pfams encountered : "
2396 + all_pfams_encountered.size() );
2397 ForesterUtil.programMessage( surfacing.PRG_NAME, "Pfams without a mapping : "
2398 + pfams_without_mappings_counter + " ["
2399 + ( ( 100 * pfams_without_mappings_counter ) / all_pfams_encountered.size() ) + "%]" );
2400 ForesterUtil.programMessage( surfacing.PRG_NAME, "Pfams without mapping to proc. or func. : "
2401 + pfams_without_mappings_to_bp_or_mf_counter + " ["
2402 + ( ( 100 * pfams_without_mappings_to_bp_or_mf_counter ) / all_pfams_encountered.size() ) + "%]" );
2403 ForesterUtil.programMessage( surfacing.PRG_NAME, "Pfams with a mapping : "
2404 + pfams_with_mappings_counter + " ["
2405 + ( ( 100 * pfams_with_mappings_counter ) / all_pfams_encountered.size() ) + "%]" );
2406 ForesterUtil.programMessage( surfacing.PRG_NAME, "Pfams with a mapping to proc. or func. : "
2407 + pfams_with_mappings_to_bp_or_mf_counter + " ["
2408 + ( ( 100 * pfams_with_mappings_to_bp_or_mf_counter ) / all_pfams_encountered.size() ) + "%]" );
2409 ForesterUtil.programMessage( surfacing.PRG_NAME, "Pfams with mapping to biological process: "
2410 + biological_process_counter + " ["
2411 + ( ( 100 * biological_process_counter ) / all_pfams_encountered.size() ) + "%]" );
2412 ForesterUtil.programMessage( surfacing.PRG_NAME, "Pfams with mapping to molecular function: "
2413 + molecular_function_counter + " ["
2414 + ( ( 100 * molecular_function_counter ) / all_pfams_encountered.size() ) + "%]" );
2415 ForesterUtil.programMessage( surfacing.PRG_NAME, "Pfams with mapping to cellular component: "
2416 + cellular_component_counter + " ["
2417 + ( ( 100 * cellular_component_counter ) / all_pfams_encountered.size() ) + "%]" );
2418 summary_writer.write( ForesterUtil.LINE_SEPARATOR );
2419 summary_writer.write( "# Sum of Pfams encountered : " + all_pfams_encountered.size() );
2420 summary_writer.write( ForesterUtil.LINE_SEPARATOR );
2421 summary_writer.write( "# Pfams without a mapping : " + pfams_without_mappings_counter
2422 + " [" + ( ( 100 * pfams_without_mappings_counter ) / all_pfams_encountered.size() ) + "%]" );
2423 summary_writer.write( ForesterUtil.LINE_SEPARATOR );
2424 summary_writer.write( "# Pfams without mapping to proc. or func. : "
2425 + pfams_without_mappings_to_bp_or_mf_counter + " ["
2426 + ( ( 100 * pfams_without_mappings_to_bp_or_mf_counter ) / all_pfams_encountered.size() ) + "%]" );
2427 summary_writer.write( ForesterUtil.LINE_SEPARATOR );
2428 summary_writer.write( "# Pfams with a mapping : " + pfams_with_mappings_counter + " ["
2429 + ( ( 100 * pfams_with_mappings_counter ) / all_pfams_encountered.size() ) + "%]" );
2430 summary_writer.write( ForesterUtil.LINE_SEPARATOR );
2431 summary_writer.write( "# Pfams with a mapping to proc. or func. : "
2432 + pfams_with_mappings_to_bp_or_mf_counter + " ["
2433 + ( ( 100 * pfams_with_mappings_to_bp_or_mf_counter ) / all_pfams_encountered.size() ) + "%]" );
2434 summary_writer.write( ForesterUtil.LINE_SEPARATOR );
2435 summary_writer.write( "# Pfams with mapping to biological process: " + biological_process_counter + " ["
2436 + ( ( 100 * biological_process_counter ) / all_pfams_encountered.size() ) + "%]" );
2437 summary_writer.write( ForesterUtil.LINE_SEPARATOR );
2438 summary_writer.write( "# Pfams with mapping to molecular function: " + molecular_function_counter + " ["
2439 + ( ( 100 * molecular_function_counter ) / all_pfams_encountered.size() ) + "%]" );
2440 summary_writer.write( ForesterUtil.LINE_SEPARATOR );
2441 summary_writer.write( "# Pfams with mapping to cellular component: " + cellular_component_counter + " ["
2442 + ( ( 100 * cellular_component_counter ) / all_pfams_encountered.size() ) + "%]" );
2443 summary_writer.write( ForesterUtil.LINE_SEPARATOR );
2444 summary_writer.close();
2446 catch ( final IOException e ) {
2447 ForesterUtil.printWarningMessage( surfacing.PRG_NAME, "Failure to write: " + e );
2451 private static void writeDomainData( final Map<String, List<GoId>> domain_id_to_go_ids_map,
2452 final Map<GoId, GoTerm> go_id_to_term_map,
2453 final GoNameSpace go_namespace_limit,
2455 final String domain_0,
2456 final String domain_1,
2457 final String prefix_for_html,
2458 final String character_separator_for_non_html_output,
2459 final Map<String, Set<String>>[] domain_id_to_secondary_features_maps,
2460 final Set<GoId> all_go_ids ) throws IOException {
2461 boolean any_go_annotation_present = false;
2462 boolean first_has_no_go = false;
2463 int domain_count = 2; // To distinguish between domains and binary domain combinations.
2464 if ( ForesterUtil.isEmpty( domain_1 ) ) {
2467 // The following has a difficult to understand logic.
2468 for( int d = 0; d < domain_count; ++d ) {
2469 List<GoId> go_ids = null;
2470 boolean go_annotation_present = false;
2472 if ( domain_id_to_go_ids_map.containsKey( domain_0 ) ) {
2473 go_annotation_present = true;
2474 any_go_annotation_present = true;
2475 go_ids = domain_id_to_go_ids_map.get( domain_0 );
2478 first_has_no_go = true;
2482 if ( domain_id_to_go_ids_map.containsKey( domain_1 ) ) {
2483 go_annotation_present = true;
2484 any_go_annotation_present = true;
2485 go_ids = domain_id_to_go_ids_map.get( domain_1 );
2488 if ( go_annotation_present ) {
2489 boolean first = ( ( d == 0 ) || ( ( d == 1 ) && first_has_no_go ) );
2490 for( final GoId go_id : go_ids ) {
2491 out.write( "<tr>" );
2494 writeDomainIdsToHtml( out,
2498 domain_id_to_secondary_features_maps );
2501 out.write( "<td></td>" );
2503 if ( !go_id_to_term_map.containsKey( go_id ) ) {
2504 throw new IllegalArgumentException( "GO-id [" + go_id + "] not found in GO-id to GO-term map" );
2506 final GoTerm go_term = go_id_to_term_map.get( go_id );
2507 if ( ( go_namespace_limit == null ) || go_namespace_limit.equals( go_term.getGoNameSpace() ) ) {
2508 // final String top = GoUtils.getPenultimateGoTerm( go_term, go_id_to_term_map ).getName();
2509 final String go_id_str = go_id.getId();
2510 out.write( "<td>" );
2511 out.write( "<a href=\"" + SurfacingConstants.AMIGO_LINK + go_id_str
2512 + "\" target=\"amigo_window\">" + go_id_str + "</a>" );
2513 out.write( "</td><td>" );
2514 out.write( go_term.getName() );
2515 if ( domain_count == 2 ) {
2516 out.write( " (" + d + ")" );
2518 out.write( "</td><td>" );
2519 // out.write( top );
2520 // out.write( "</td><td>" );
2522 out.write( go_term.getGoNameSpace().toShortString() );
2524 out.write( "</td>" );
2525 if ( all_go_ids != null ) {
2526 all_go_ids.add( go_id );
2530 out.write( "<td>" );
2531 out.write( "</td><td>" );
2532 out.write( "</td><td>" );
2533 out.write( "</td><td>" );
2534 out.write( "</td>" );
2536 out.write( "</tr>" );
2537 out.write( SurfacingConstants.NL );
2540 } // for( int d = 0; d < domain_count; ++d )
2541 if ( !any_go_annotation_present ) {
2542 out.write( "<tr>" );
2543 writeDomainIdsToHtml( out, domain_0, domain_1, prefix_for_html, domain_id_to_secondary_features_maps );
2544 out.write( "<td>" );
2545 out.write( "</td><td>" );
2546 out.write( "</td><td>" );
2547 out.write( "</td><td>" );
2548 out.write( "</td>" );
2549 out.write( "</tr>" );
2550 out.write( SurfacingConstants.NL );
2554 private static void writeDomainIdsToHtml( final Writer out,
2555 final String domain_0,
2556 final String domain_1,
2557 final String prefix_for_detailed_html,
2558 final Map<String, Set<String>>[] domain_id_to_secondary_features_maps )
2559 throws IOException {
2560 out.write( "<td>" );
2561 if ( !ForesterUtil.isEmpty( prefix_for_detailed_html ) ) {
2562 out.write( prefix_for_detailed_html );
2565 out.write( "<a href=\"" + SurfacingConstants.PFAM_FAMILY_ID_LINK + domain_0 + "\">" + domain_0 + "</a>" );
2566 out.write( "</td>" );
2569 private static void writeDomainsToIndividualFilePerTreeNode( final Writer individual_files_writer,
2570 final String domain_0,
2571 final String domain_1 ) throws IOException {
2572 individual_files_writer.write( domain_0 );
2573 individual_files_writer.write( ForesterUtil.LINE_SEPARATOR );
2574 if ( !ForesterUtil.isEmpty( domain_1 ) ) {
2575 individual_files_writer.write( domain_1 );
2576 individual_files_writer.write( ForesterUtil.LINE_SEPARATOR );
2580 private static void writePfamsToFile( final String outfile_name, final SortedSet<String> pfams ) {
2582 final Writer writer = new BufferedWriter( new FileWriter( new File( outfile_name ) ) );
2583 for( final String pfam : pfams ) {
2584 writer.write( pfam );
2585 writer.write( ForesterUtil.LINE_SEPARATOR );
2588 ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote " + pfams.size() + " pfams to [" + outfile_name
2591 catch ( final IOException e ) {
2592 ForesterUtil.printWarningMessage( surfacing.PRG_NAME, "Failure to write: " + e );
2596 private static void writeToNexus( final String outfile_name,
2597 final CharacterStateMatrix<BinaryStates> matrix,
2598 final Phylogeny phylogeny ) {
2599 if ( !( matrix instanceof BasicCharacterStateMatrix ) ) {
2600 throw new IllegalArgumentException( "can only write matrices of type [" + BasicCharacterStateMatrix.class
2603 final BasicCharacterStateMatrix<BinaryStates> my_matrix = ( org.forester.evoinference.matrix.character.BasicCharacterStateMatrix<BinaryStates> ) matrix;
2604 final List<Phylogeny> phylogenies = new ArrayList<Phylogeny>( 1 );
2605 phylogenies.add( phylogeny );
2607 final BufferedWriter w = new BufferedWriter( new FileWriter( outfile_name ) );
2608 w.write( NexusConstants.NEXUS );
2609 w.write( ForesterUtil.LINE_SEPARATOR );
2610 my_matrix.writeNexusTaxaBlock( w );
2611 my_matrix.writeNexusBinaryChractersBlock( w );
2612 PhylogenyWriter.writeNexusTreesBlock( w, phylogenies, NH_CONVERSION_SUPPORT_VALUE_STYLE.NONE );
2615 ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote Nexus file: \"" + outfile_name + "\"" );
2617 catch ( final IOException e ) {
2618 ForesterUtil.fatalError( surfacing.PRG_NAME, e.getMessage() );
2622 private static void writeToNexus( final String outfile_name,
2623 final DomainParsimonyCalculator domain_parsimony,
2624 final Phylogeny phylogeny ) {
2625 writeToNexus( outfile_name + surfacing.NEXUS_EXTERNAL_DOMAINS,
2626 domain_parsimony.createMatrixOfDomainPresenceOrAbsence(),
2628 writeToNexus( outfile_name + surfacing.NEXUS_EXTERNAL_DOMAIN_COMBINATIONS,
2629 domain_parsimony.createMatrixOfBinaryDomainCombinationPresenceOrAbsence(),
2633 final static class DomainComparator implements Comparator<Domain> {
2635 final private boolean _ascending;
2637 public DomainComparator( final boolean ascending ) {
2638 _ascending = ascending;
2642 public final int compare( final Domain d0, final Domain d1 ) {
2643 if ( d0.getFrom() < d1.getFrom() ) {
2644 return _ascending ? -1 : 1;
2646 else if ( d0.getFrom() > d1.getFrom() ) {
2647 return _ascending ? 1 : -1;