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.awt.Color;
30 import java.io.BufferedWriter;
32 import java.io.FileWriter;
33 import java.io.IOException;
34 import java.io.Writer;
35 import java.text.DecimalFormat;
36 import java.text.NumberFormat;
37 import java.util.ArrayList;
38 import java.util.Arrays;
39 import java.util.Collections;
40 import java.util.Comparator;
41 import java.util.HashMap;
42 import java.util.HashSet;
43 import java.util.Iterator;
44 import java.util.List;
46 import java.util.Map.Entry;
47 import java.util.PriorityQueue;
49 import java.util.SortedMap;
50 import java.util.SortedSet;
51 import java.util.TreeMap;
52 import java.util.TreeSet;
53 import java.util.regex.Matcher;
54 import java.util.regex.Pattern;
56 import org.forester.application.surfacing;
57 import org.forester.evoinference.distance.NeighborJoining;
58 import org.forester.evoinference.matrix.character.BasicCharacterStateMatrix;
59 import org.forester.evoinference.matrix.character.CharacterStateMatrix;
60 import org.forester.evoinference.matrix.character.CharacterStateMatrix.BinaryStates;
61 import org.forester.evoinference.matrix.character.CharacterStateMatrix.Format;
62 import org.forester.evoinference.matrix.character.CharacterStateMatrix.GainLossStates;
63 import org.forester.evoinference.matrix.distance.BasicSymmetricalDistanceMatrix;
64 import org.forester.evoinference.matrix.distance.DistanceMatrix;
65 import org.forester.go.GoId;
66 import org.forester.go.GoNameSpace;
67 import org.forester.go.GoTerm;
68 import org.forester.go.PfamToGoMapping;
69 import org.forester.io.parsers.nexus.NexusConstants;
70 import org.forester.io.parsers.phyloxml.PhyloXmlUtil;
71 import org.forester.io.parsers.util.ParserUtils;
72 import org.forester.io.writers.PhylogenyWriter;
73 import org.forester.phylogeny.Phylogeny;
74 import org.forester.phylogeny.PhylogenyMethods;
75 import org.forester.phylogeny.PhylogenyNode;
76 import org.forester.phylogeny.PhylogenyNode.NH_CONVERSION_SUPPORT_VALUE_STYLE;
77 import org.forester.phylogeny.data.BinaryCharacters;
78 import org.forester.phylogeny.data.Confidence;
79 import org.forester.phylogeny.data.Taxonomy;
80 import org.forester.phylogeny.factories.ParserBasedPhylogenyFactory;
81 import org.forester.phylogeny.iterators.PhylogenyNodeIterator;
82 import org.forester.protein.BasicDomain;
83 import org.forester.protein.BasicProtein;
84 import org.forester.protein.BinaryDomainCombination;
85 import org.forester.protein.Domain;
86 import org.forester.protein.Protein;
87 import org.forester.species.Species;
88 import org.forester.surfacing.DomainSimilarity.PRINT_OPTION;
89 import org.forester.surfacing.DomainSimilarityCalculator.Detailedness;
90 import org.forester.surfacing.GenomeWideCombinableDomains.GenomeWideCombinableDomainsSortOrder;
91 import org.forester.util.AsciiHistogram;
92 import org.forester.util.BasicDescriptiveStatistics;
93 import org.forester.util.BasicTable;
94 import org.forester.util.BasicTableParser;
95 import org.forester.util.CommandLineArguments;
96 import org.forester.util.DescriptiveStatistics;
97 import org.forester.util.ForesterUtil;
98 import org.forester.util.TaxonomyColors;
99 import org.forester.util.TaxonomyGroups;
101 public final class SurfacingUtil {
103 public final static Pattern PATTERN_SP_STYLE_TAXONOMY = Pattern.compile( "^[A-Z0-9]{3,5}$" );
104 private final static Map<String, String> _TAXCODE_HEXCOLORSTRING_MAP = new HashMap<String, String>();
105 private final static Map<String, String> _TAXCODE_TAXGROUP_MAP = new HashMap<String, String>();
106 private static final Comparator<Domain> ASCENDING_CONFIDENCE_VALUE_ORDER = new Comparator<Domain>() {
109 public int compare( final Domain d1,
111 if ( d1.getPerDomainEvalue() < d2
112 .getPerDomainEvalue() ) {
116 .getPerDomainEvalue() > d2
117 .getPerDomainEvalue() ) {
121 return d1.compareTo( d2 );
125 private final static NumberFormat FORMATTER_3 = new DecimalFormat( "0.000" );
127 private SurfacingUtil() {
128 // Hidden constructor.
131 public static void addAllBinaryDomainCombinationToSet( final GenomeWideCombinableDomains genome,
132 final SortedSet<BinaryDomainCombination> binary_domain_combinations ) {
133 final SortedMap<String, CombinableDomains> all_cd = genome.getAllCombinableDomainsIds();
134 for( final String domain_id : all_cd.keySet() ) {
135 binary_domain_combinations.addAll( all_cd.get( domain_id ).toBinaryDomainCombinations() );
139 public static void addAllDomainIdsToSet( final GenomeWideCombinableDomains genome,
140 final SortedSet<String> domain_ids ) {
141 final SortedSet<String> domains = genome.getAllDomainIds();
142 for( final String domain : domains ) {
143 domain_ids.add( domain );
147 public static DescriptiveStatistics calculateDescriptiveStatisticsForMeanValues( final Set<DomainSimilarity> similarities ) {
148 final DescriptiveStatistics stats = new BasicDescriptiveStatistics();
149 for( final DomainSimilarity similarity : similarities ) {
150 stats.addValue( similarity.getMeanSimilarityScore() );
155 public static void checkForOutputFileWriteability( final File outfile ) {
156 final String error = ForesterUtil.isWritableFile( outfile );
157 if ( !ForesterUtil.isEmpty( error ) ) {
158 ForesterUtil.fatalError( surfacing.PRG_NAME, error );
162 public static void checkWriteabilityForPairwiseComparisons( final DomainSimilarity.PRINT_OPTION domain_similarity_print_option,
163 final String[][] input_file_properties,
164 final String automated_pairwise_comparison_suffix,
165 final File outdir ) {
166 for( int i = 0; i < input_file_properties.length; ++i ) {
167 for( int j = 0; j < i; ++j ) {
168 final String species_i = input_file_properties[ i ][ 1 ];
169 final String species_j = input_file_properties[ j ][ 1 ];
170 String pairwise_similarities_output_file_str = surfacing.PAIRWISE_DOMAIN_COMPARISONS_PREFIX + species_i
171 + "_" + species_j + automated_pairwise_comparison_suffix;
172 switch ( domain_similarity_print_option ) {
174 if ( !pairwise_similarities_output_file_str.endsWith( ".html" ) ) {
175 pairwise_similarities_output_file_str += ".html";
179 final String error = ForesterUtil
180 .isWritableFile( new File( outdir == null ? pairwise_similarities_output_file_str
181 : outdir + ForesterUtil.FILE_SEPARATOR + pairwise_similarities_output_file_str ) );
182 if ( !ForesterUtil.isEmpty( error ) ) {
183 ForesterUtil.fatalError( surfacing.PRG_NAME, error );
189 public static void collectChangedDomainCombinationsFromBinaryStatesMatrixAsListToFile( final CharacterStateMatrix<CharacterStateMatrix.GainLossStates> matrix,
190 final BinaryDomainCombination.DomainCombinationType dc_type,
191 final List<BinaryDomainCombination> all_binary_domains_combination_gained,
192 final boolean get_gains ) {
193 final SortedSet<String> sorted_ids = new TreeSet<String>();
194 for( int i = 0; i < matrix.getNumberOfIdentifiers(); ++i ) {
195 sorted_ids.add( matrix.getIdentifier( i ) );
197 for( final String id : sorted_ids ) {
198 for( int c = 0; c < matrix.getNumberOfCharacters(); ++c ) {
199 if ( ( get_gains && ( matrix.getState( id, c ) == CharacterStateMatrix.GainLossStates.GAIN ) )
201 && ( matrix.getState( id, c ) == CharacterStateMatrix.GainLossStates.LOSS ) ) ) {
202 if ( dc_type == BinaryDomainCombination.DomainCombinationType.DIRECTED_ADJACTANT ) {
203 all_binary_domains_combination_gained.add( AdjactantDirectedBinaryDomainCombination
204 .obtainInstance( matrix.getCharacter( c ) ) );
206 else if ( dc_type == BinaryDomainCombination.DomainCombinationType.DIRECTED ) {
207 all_binary_domains_combination_gained
208 .add( DirectedBinaryDomainCombination.obtainInstance( matrix.getCharacter( c ) ) );
211 all_binary_domains_combination_gained
212 .add( BasicBinaryDomainCombination.obtainInstance( matrix.getCharacter( c ) ) );
219 public static Map<String, List<GoId>> createDomainIdToGoIdMap( final List<PfamToGoMapping> pfam_to_go_mappings ) {
220 final Map<String, List<GoId>> domain_id_to_go_ids_map = new HashMap<String, List<GoId>>( pfam_to_go_mappings
222 for( final PfamToGoMapping pfam_to_go : pfam_to_go_mappings ) {
223 if ( !domain_id_to_go_ids_map.containsKey( pfam_to_go.getKey() ) ) {
224 domain_id_to_go_ids_map.put( pfam_to_go.getKey(), new ArrayList<GoId>() );
226 domain_id_to_go_ids_map.get( pfam_to_go.getKey() ).add( pfam_to_go.getValue() );
228 return domain_id_to_go_ids_map;
231 public static Map<String, Set<String>> createDomainIdToSecondaryFeaturesMap( final File secondary_features_map_file )
233 final BasicTable<String> primary_table = BasicTableParser.parse( secondary_features_map_file, '\t' );
234 final Map<String, Set<String>> map = new TreeMap<String, Set<String>>();
235 for( int r = 0; r < primary_table.getNumberOfRows(); ++r ) {
236 final String domain_id = primary_table.getValue( 0, r );
237 if ( !map.containsKey( domain_id ) ) {
238 map.put( domain_id, new HashSet<String>() );
240 map.get( domain_id ).add( primary_table.getValue( 1, r ) );
245 public static Phylogeny createNjTreeBasedOnMatrixToFile( final File nj_tree_outfile,
246 final DistanceMatrix distance ) {
247 checkForOutputFileWriteability( nj_tree_outfile );
248 final NeighborJoining nj = NeighborJoining.createInstance();
249 final Phylogeny phylogeny = nj.execute( ( BasicSymmetricalDistanceMatrix ) distance );
250 phylogeny.setName( nj_tree_outfile.getName() );
251 writePhylogenyToFile( phylogeny, nj_tree_outfile.toString() );
255 public static StringBuilder createParametersAsString( final boolean ignore_dufs,
256 final double ie_value_max,
257 final double fs_e_value_max,
258 final int max_allowed_overlap,
259 final boolean no_engulfing_overlaps,
260 final File cutoff_scores_file,
261 final BinaryDomainCombination.DomainCombinationType dc_type ) {
262 final StringBuilder parameters_sb = new StringBuilder();
263 parameters_sb.append( "iE-value: " + ie_value_max );
264 parameters_sb.append( ", FS E-value: " + fs_e_value_max );
265 if ( cutoff_scores_file != null ) {
266 parameters_sb.append( ", Cutoff-scores-file: " + cutoff_scores_file );
269 parameters_sb.append( ", Cutoff-scores-file: not-set" );
271 if ( max_allowed_overlap != surfacing.MAX_ALLOWED_OVERLAP_DEFAULT ) {
272 parameters_sb.append( ", Max-overlap: " + max_allowed_overlap );
275 parameters_sb.append( ", Max-overlap: not-set" );
277 if ( no_engulfing_overlaps ) {
278 parameters_sb.append( ", Engulfing-overlaps: not-allowed" );
281 parameters_sb.append( ", Engulfing-overlaps: allowed" );
284 parameters_sb.append( ", Ignore-dufs: true" );
287 parameters_sb.append( ", Ignore-dufs: false" );
289 parameters_sb.append( ", DC type (if applicable): " + dc_type );
290 return parameters_sb;
293 public static void createSplitWriters( final File out_dir,
294 final String my_outfile,
295 final Map<Character, Writer> split_writers )
297 split_writers.put( 'a',
298 new BufferedWriter( new FileWriter( out_dir + ForesterUtil.FILE_SEPARATOR + my_outfile
299 + "_domains_A.html" ) ) );
300 split_writers.put( 'b',
301 new BufferedWriter( new FileWriter( out_dir + ForesterUtil.FILE_SEPARATOR + my_outfile
302 + "_domains_B.html" ) ) );
303 split_writers.put( 'c',
304 new BufferedWriter( new FileWriter( out_dir + ForesterUtil.FILE_SEPARATOR + my_outfile
305 + "_domains_C.html" ) ) );
306 split_writers.put( 'd',
307 new BufferedWriter( new FileWriter( out_dir + ForesterUtil.FILE_SEPARATOR + my_outfile
308 + "_domains_D.html" ) ) );
309 split_writers.put( 'e',
310 new BufferedWriter( new FileWriter( out_dir + ForesterUtil.FILE_SEPARATOR + my_outfile
311 + "_domains_E.html" ) ) );
312 split_writers.put( 'f',
313 new BufferedWriter( new FileWriter( out_dir + ForesterUtil.FILE_SEPARATOR + my_outfile
314 + "_domains_F.html" ) ) );
315 split_writers.put( 'g',
316 new BufferedWriter( new FileWriter( out_dir + ForesterUtil.FILE_SEPARATOR + my_outfile
317 + "_domains_G.html" ) ) );
318 split_writers.put( 'h',
319 new BufferedWriter( new FileWriter( out_dir + ForesterUtil.FILE_SEPARATOR + my_outfile
320 + "_domains_H.html" ) ) );
321 split_writers.put( 'i',
322 new BufferedWriter( new FileWriter( out_dir + ForesterUtil.FILE_SEPARATOR + my_outfile
323 + "_domains_I.html" ) ) );
324 split_writers.put( 'j',
325 new BufferedWriter( new FileWriter( out_dir + ForesterUtil.FILE_SEPARATOR + my_outfile
326 + "_domains_J.html" ) ) );
327 split_writers.put( 'k',
328 new BufferedWriter( new FileWriter( out_dir + ForesterUtil.FILE_SEPARATOR + my_outfile
329 + "_domains_K.html" ) ) );
330 split_writers.put( 'l',
331 new BufferedWriter( new FileWriter( out_dir + ForesterUtil.FILE_SEPARATOR + my_outfile
332 + "_domains_L.html" ) ) );
333 split_writers.put( 'm',
334 new BufferedWriter( new FileWriter( out_dir + ForesterUtil.FILE_SEPARATOR + my_outfile
335 + "_domains_M.html" ) ) );
336 split_writers.put( 'n',
337 new BufferedWriter( new FileWriter( out_dir + ForesterUtil.FILE_SEPARATOR + my_outfile
338 + "_domains_N.html" ) ) );
339 split_writers.put( 'o',
340 new BufferedWriter( new FileWriter( out_dir + ForesterUtil.FILE_SEPARATOR + my_outfile
341 + "_domains_O.html" ) ) );
342 split_writers.put( 'p',
343 new BufferedWriter( new FileWriter( out_dir + ForesterUtil.FILE_SEPARATOR + my_outfile
344 + "_domains_P.html" ) ) );
345 split_writers.put( 'q',
346 new BufferedWriter( new FileWriter( out_dir + ForesterUtil.FILE_SEPARATOR + my_outfile
347 + "_domains_Q.html" ) ) );
348 split_writers.put( 'r',
349 new BufferedWriter( new FileWriter( out_dir + ForesterUtil.FILE_SEPARATOR + my_outfile
350 + "_domains_R.html" ) ) );
351 split_writers.put( 's',
352 new BufferedWriter( new FileWriter( out_dir + ForesterUtil.FILE_SEPARATOR + my_outfile
353 + "_domains_S.html" ) ) );
354 split_writers.put( 't',
355 new BufferedWriter( new FileWriter( out_dir + ForesterUtil.FILE_SEPARATOR + my_outfile
356 + "_domains_T.html" ) ) );
357 split_writers.put( 'u',
358 new BufferedWriter( new FileWriter( out_dir + ForesterUtil.FILE_SEPARATOR + my_outfile
359 + "_domains_U.html" ) ) );
360 split_writers.put( 'v',
361 new BufferedWriter( new FileWriter( out_dir + ForesterUtil.FILE_SEPARATOR + my_outfile
362 + "_domains_V.html" ) ) );
363 split_writers.put( 'w',
364 new BufferedWriter( new FileWriter( out_dir + ForesterUtil.FILE_SEPARATOR + my_outfile
365 + "_domains_W.html" ) ) );
366 split_writers.put( 'x',
367 new BufferedWriter( new FileWriter( out_dir + ForesterUtil.FILE_SEPARATOR + my_outfile
368 + "_domains_X.html" ) ) );
369 split_writers.put( 'y',
370 new BufferedWriter( new FileWriter( out_dir + ForesterUtil.FILE_SEPARATOR + my_outfile
371 + "_domains_Y.html" ) ) );
372 split_writers.put( 'z',
373 new BufferedWriter( new FileWriter( out_dir + ForesterUtil.FILE_SEPARATOR + my_outfile
374 + "_domains_Z.html" ) ) );
375 split_writers.put( '0',
376 new BufferedWriter( new FileWriter( out_dir + ForesterUtil.FILE_SEPARATOR + my_outfile
377 + "_domains_0.html" ) ) );
380 public static Map<String, Integer> createTaxCodeToIdMap( final Phylogeny phy ) {
381 final Map<String, Integer> m = new HashMap<String, Integer>();
382 for( final PhylogenyNodeIterator iter = phy.iteratorExternalForward(); iter.hasNext(); ) {
383 final PhylogenyNode n = iter.next();
384 if ( n.getNodeData().isHasTaxonomy() ) {
385 final Taxonomy t = n.getNodeData().getTaxonomy();
386 final String c = t.getTaxonomyCode();
387 if ( !ForesterUtil.isEmpty( c ) ) {
388 if ( n.getNodeData().getTaxonomy() == null ) {
389 ForesterUtil.fatalError( surfacing.PRG_NAME, "no taxonomy id for node " + n );
391 final String id = n.getNodeData().getTaxonomy().getIdentifier().getValue();
392 if ( ForesterUtil.isEmpty( id ) ) {
393 ForesterUtil.fatalError( surfacing.PRG_NAME, "no taxonomy id for node " + n );
395 if ( m.containsKey( c ) ) {
396 ForesterUtil.fatalError( surfacing.PRG_NAME, "taxonomy code " + c + " is not unique" );
398 final int iid = Integer.valueOf( id );
399 if ( m.containsValue( iid ) ) {
400 ForesterUtil.fatalError( surfacing.PRG_NAME, "taxonomy id " + iid + " is not unique" );
406 ForesterUtil.fatalError( surfacing.PRG_NAME, "no taxonomy for node " + n );
412 public static void decoratePrintableDomainSimilarities( final SortedSet<DomainSimilarity> domain_similarities,
413 final Detailedness detailedness ) {
414 for( final DomainSimilarity domain_similarity : domain_similarities ) {
415 if ( domain_similarity instanceof DomainSimilarity ) {
416 final DomainSimilarity printable_domain_similarity = domain_similarity;
417 printable_domain_similarity.setDetailedness( detailedness );
422 public static void doit( final List<Protein> proteins,
423 final List<String> query_domain_ids_nc_order,
425 final String separator,
426 final String limit_to_species,
427 final Map<String, List<Integer>> average_protein_lengths_by_dc )
429 for( final Protein protein : proteins ) {
430 if ( ForesterUtil.isEmpty( limit_to_species )
431 || protein.getSpecies().getSpeciesId().equalsIgnoreCase( limit_to_species ) ) {
432 if ( protein.contains( query_domain_ids_nc_order, true ) ) {
433 out.write( protein.getSpecies().getSpeciesId() );
434 out.write( separator );
435 out.write( protein.getProteinId().getId() );
436 out.write( separator );
438 final Set<String> visited_domain_ids = new HashSet<String>();
439 boolean first = true;
440 for( final Domain domain : protein.getProteinDomains() ) {
441 if ( !visited_domain_ids.contains( domain.getDomainId() ) ) {
442 visited_domain_ids.add( domain.getDomainId() );
449 out.write( domain.getDomainId() );
451 out.write( "" + domain.getTotalCount() );
456 out.write( separator );
457 if ( !( ForesterUtil.isEmpty( protein.getDescription() )
458 || protein.getDescription().equals( SurfacingConstants.NONE ) ) ) {
459 out.write( protein.getDescription() );
461 out.write( separator );
462 if ( !( ForesterUtil.isEmpty( protein.getAccession() )
463 || protein.getAccession().equals( SurfacingConstants.NONE ) ) ) {
464 out.write( protein.getAccession() );
466 out.write( SurfacingConstants.NL );
473 public static void domainsPerProteinsStatistics( final String genome,
474 final List<Protein> protein_list,
475 final DescriptiveStatistics all_genomes_domains_per_potein_stats,
476 final SortedMap<Integer, Integer> all_genomes_domains_per_potein_histo,
477 final SortedSet<String> domains_which_are_always_single,
478 final SortedSet<String> domains_which_are_sometimes_single_sometimes_not,
479 final SortedSet<String> domains_which_never_single,
480 final Writer writer ) {
481 final DescriptiveStatistics stats = new BasicDescriptiveStatistics();
482 for( final Protein protein : protein_list ) {
483 final int domains = protein.getNumberOfProteinDomains();
484 //System.out.println( domains );
485 stats.addValue( domains );
486 all_genomes_domains_per_potein_stats.addValue( domains );
487 if ( !all_genomes_domains_per_potein_histo.containsKey( domains ) ) {
488 all_genomes_domains_per_potein_histo.put( domains, 1 );
491 all_genomes_domains_per_potein_histo.put( domains,
492 1 + all_genomes_domains_per_potein_histo.get( domains ) );
494 if ( domains == 1 ) {
495 final String domain = protein.getProteinDomain( 0 ).getDomainId();
496 if ( !domains_which_are_sometimes_single_sometimes_not.contains( domain ) ) {
497 if ( domains_which_never_single.contains( domain ) ) {
498 domains_which_never_single.remove( domain );
499 domains_which_are_sometimes_single_sometimes_not.add( domain );
502 domains_which_are_always_single.add( domain );
506 else if ( domains > 1 ) {
507 for( final Domain d : protein.getProteinDomains() ) {
508 final String domain = d.getDomainId();
509 // System.out.println( domain );
510 if ( !domains_which_are_sometimes_single_sometimes_not.contains( domain ) ) {
511 if ( domains_which_are_always_single.contains( domain ) ) {
512 domains_which_are_always_single.remove( domain );
513 domains_which_are_sometimes_single_sometimes_not.add( domain );
516 domains_which_never_single.add( domain );
523 writer.write( genome );
524 writer.write( "\t" );
525 if ( stats.getN() >= 1 ) {
526 writer.write( stats.arithmeticMean() + "" );
527 writer.write( "\t" );
528 if ( stats.getN() >= 2 ) {
529 writer.write( stats.sampleStandardDeviation() + "" );
534 writer.write( "\t" );
535 writer.write( stats.median() + "" );
536 writer.write( "\t" );
537 writer.write( stats.getN() + "" );
538 writer.write( "\t" );
539 writer.write( stats.getMin() + "" );
540 writer.write( "\t" );
541 writer.write( stats.getMax() + "" );
544 writer.write( "\t" );
545 writer.write( "\t" );
546 writer.write( "\t" );
548 writer.write( "\t" );
549 writer.write( "\t" );
551 writer.write( "\n" );
553 catch ( final IOException e ) {
558 public static void executeDomainLengthAnalysis( final String[][] input_file_properties,
559 final int number_of_genomes,
560 final DomainLengthsTable domain_lengths_table,
563 final DecimalFormat df = new DecimalFormat( "#.00" );
564 checkForOutputFileWriteability( outfile );
565 final BufferedWriter out = new BufferedWriter( new FileWriter( outfile ) );
566 out.write( "MEAN BASED STATISTICS PER SPECIES" );
567 out.write( ForesterUtil.LINE_SEPARATOR );
568 out.write( domain_lengths_table.createMeanBasedStatisticsPerSpeciesTable().toString() );
569 out.write( ForesterUtil.LINE_SEPARATOR );
570 out.write( ForesterUtil.LINE_SEPARATOR );
571 final List<DomainLengths> domain_lengths_list = domain_lengths_table.getDomainLengthsList();
572 out.write( "OUTLIER SPECIES PER DOMAIN (Z>=1.5)" );
573 out.write( ForesterUtil.LINE_SEPARATOR );
574 for( final DomainLengths domain_lengths : domain_lengths_list ) {
575 final List<Species> species_list = domain_lengths.getMeanBasedOutlierSpecies( 1.5 );
576 if ( species_list.size() > 0 ) {
577 out.write( domain_lengths.getDomainId() + "\t" );
578 for( final Species species : species_list ) {
579 out.write( species + "\t" );
581 out.write( ForesterUtil.LINE_SEPARATOR );
584 out.write( ForesterUtil.LINE_SEPARATOR );
585 out.write( ForesterUtil.LINE_SEPARATOR );
586 out.write( "OUTLIER SPECIES (Z 1.0)" );
587 out.write( ForesterUtil.LINE_SEPARATOR );
588 final DescriptiveStatistics stats_for_all_species = domain_lengths_table
589 .calculateMeanBasedStatisticsForAllSpecies();
590 out.write( stats_for_all_species.asSummary() );
591 out.write( ForesterUtil.LINE_SEPARATOR );
592 final AsciiHistogram histo = new AsciiHistogram( stats_for_all_species );
593 out.write( histo.toStringBuffer( 40, '=', 60, 4 ).toString() );
594 out.write( ForesterUtil.LINE_SEPARATOR );
595 final double population_sd = stats_for_all_species.sampleStandardDeviation();
596 final double population_mean = stats_for_all_species.arithmeticMean();
597 for( final Species species : domain_lengths_table.getSpecies() ) {
598 final double x = domain_lengths_table.calculateMeanBasedStatisticsForSpecies( species ).arithmeticMean();
599 final double z = ( x - population_mean ) / population_sd;
600 out.write( species + "\t" + z );
601 out.write( ForesterUtil.LINE_SEPARATOR );
603 out.write( ForesterUtil.LINE_SEPARATOR );
604 for( final Species species : domain_lengths_table.getSpecies() ) {
605 final DescriptiveStatistics stats_for_species = domain_lengths_table
606 .calculateMeanBasedStatisticsForSpecies( species );
607 final double x = stats_for_species.arithmeticMean();
608 final double z = ( x - population_mean ) / population_sd;
609 if ( ( z <= -1.0 ) || ( z >= 1.0 ) ) {
610 out.write( species + "\t" + df.format( z ) + "\t" + stats_for_species.asSummary() );
611 out.write( ForesterUtil.LINE_SEPARATOR );
619 * Warning: This side-effects 'all_bin_domain_combinations_encountered'!
623 * @param all_bin_domain_combinations_changed
624 * @param sum_of_all_domains_encountered
625 * @param all_bin_domain_combinations_encountered
626 * @param is_gains_analysis
627 * @param protein_length_stats_by_dc
628 * @throws IOException
630 public static void executeFitchGainsAnalysis( final File output_file,
631 final List<BinaryDomainCombination> all_bin_domain_combinations_changed,
632 final int sum_of_all_domains_encountered,
633 final SortedSet<BinaryDomainCombination> all_bin_domain_combinations_encountered,
634 final boolean is_gains_analysis )
636 checkForOutputFileWriteability( output_file );
637 final Writer out = ForesterUtil.createBufferedWriter( output_file );
638 final SortedMap<Object, Integer> bdc_to_counts = ForesterUtil
639 .listToSortedCountsMap( all_bin_domain_combinations_changed );
640 final SortedSet<String> all_domains_in_combination_changed_more_than_once = new TreeSet<String>();
641 final SortedSet<String> all_domains_in_combination_changed_only_once = new TreeSet<String>();
644 for( final Object bdc_object : bdc_to_counts.keySet() ) {
645 final BinaryDomainCombination bdc = ( BinaryDomainCombination ) bdc_object;
646 final int count = bdc_to_counts.get( bdc_object );
648 ForesterUtil.unexpectedFatalError( surfacing.PRG_NAME, "count < 1 " );
650 out.write( bdc + "\t" + count + ForesterUtil.LINE_SEPARATOR );
652 all_domains_in_combination_changed_more_than_once.add( bdc.getId0() );
653 all_domains_in_combination_changed_more_than_once.add( bdc.getId1() );
656 else if ( count == 1 ) {
657 all_domains_in_combination_changed_only_once.add( bdc.getId0() );
658 all_domains_in_combination_changed_only_once.add( bdc.getId1() );
662 final int all = all_bin_domain_combinations_encountered.size();
664 if ( !is_gains_analysis ) {
665 all_bin_domain_combinations_encountered.removeAll( all_bin_domain_combinations_changed );
666 never_lost = all_bin_domain_combinations_encountered.size();
667 for( final BinaryDomainCombination bdc : all_bin_domain_combinations_encountered ) {
668 out.write( bdc + "\t" + "0" + ForesterUtil.LINE_SEPARATOR );
671 if ( is_gains_analysis ) {
672 out.write( "Sum of all distinct domain combinations appearing once : " + one
673 + ForesterUtil.LINE_SEPARATOR );
674 out.write( "Sum of all distinct domain combinations appearing more than once : " + above_one
675 + ForesterUtil.LINE_SEPARATOR );
676 out.write( "Sum of all distinct domains in combinations apppearing only once : "
677 + all_domains_in_combination_changed_only_once.size() + ForesterUtil.LINE_SEPARATOR );
678 out.write( "Sum of all distinct domains in combinations apppearing more than once: "
679 + all_domains_in_combination_changed_more_than_once.size() + ForesterUtil.LINE_SEPARATOR );
682 out.write( "Sum of all distinct domain combinations never lost : " + never_lost
683 + ForesterUtil.LINE_SEPARATOR );
684 out.write( "Sum of all distinct domain combinations lost once : " + one
685 + ForesterUtil.LINE_SEPARATOR );
686 out.write( "Sum of all distinct domain combinations lost more than once : " + above_one
687 + ForesterUtil.LINE_SEPARATOR );
688 out.write( "Sum of all distinct domains in combinations lost only once : "
689 + all_domains_in_combination_changed_only_once.size() + ForesterUtil.LINE_SEPARATOR );
690 out.write( "Sum of all distinct domains in combinations lost more than once: "
691 + all_domains_in_combination_changed_more_than_once.size() + ForesterUtil.LINE_SEPARATOR );
693 out.write( "All binary combinations : " + all
694 + ForesterUtil.LINE_SEPARATOR );
695 out.write( "All domains : "
696 + sum_of_all_domains_encountered );
699 .programMessage( surfacing.PRG_NAME,
700 "Wrote fitch domain combination dynamics counts analysis to \"" + output_file + "\"" );
705 * @param all_binary_domains_combination_lost_fitch
706 * @param use_last_in_fitch_parsimony
707 * @param perform_dc_fich
708 * @param consider_directedness_and_adjacency_for_bin_combinations
709 * @param all_binary_domains_combination_gained if null ignored, otherwise this is to list all binary domain combinations
710 * which were gained under unweighted (Fitch) parsimony.
712 public static void executeParsimonyAnalysis( final long random_number_seed_for_fitch_parsimony,
713 final boolean radomize_fitch_parsimony,
714 final String outfile_name,
715 final DomainParsimonyCalculator domain_parsimony,
716 final Phylogeny phylogeny,
717 final Map<String, List<GoId>> domain_id_to_go_ids_map,
718 final Map<GoId, GoTerm> go_id_to_term_map,
719 final GoNameSpace go_namespace_limit,
720 final String parameters_str,
721 final Map<String, Set<String>>[] domain_id_to_secondary_features_maps,
722 final SortedSet<String> positive_filter,
723 final boolean output_binary_domain_combinations_for_graphs,
724 final List<BinaryDomainCombination> all_binary_domains_combination_gained_fitch,
725 final List<BinaryDomainCombination> all_binary_domains_combination_lost_fitch,
726 final BinaryDomainCombination.DomainCombinationType dc_type,
727 final Map<String, DescriptiveStatistics> protein_length_stats_by_dc,
728 final Map<String, DescriptiveStatistics> domain_number_stats_by_dc,
729 final Map<String, DescriptiveStatistics> domain_length_stats_by_domain,
730 final Map<String, Integer> tax_code_to_id_map,
731 final boolean write_to_nexus,
732 final boolean use_last_in_fitch_parsimony,
733 final boolean perform_dc_fich ) {
734 final String sep = ForesterUtil.LINE_SEPARATOR + "###################" + ForesterUtil.LINE_SEPARATOR;
735 final String date_time = ForesterUtil.getCurrentDateTime();
736 final SortedSet<String> all_pfams_encountered = new TreeSet<String>();
737 final SortedSet<String> all_pfams_gained_as_domains = new TreeSet<String>();
738 final SortedSet<String> all_pfams_lost_as_domains = new TreeSet<String>();
739 final SortedSet<String> all_pfams_gained_as_dom_combinations = new TreeSet<String>();
740 final SortedSet<String> all_pfams_lost_as_dom_combinations = new TreeSet<String>();
741 if ( write_to_nexus ) {
742 writeToNexus( outfile_name, domain_parsimony, phylogeny );
746 Phylogeny local_phylogeny_l = phylogeny.copy();
747 if ( ( positive_filter != null ) && ( positive_filter.size() > 0 ) ) {
748 domain_parsimony.executeDolloParsimonyOnDomainPresence( positive_filter );
751 domain_parsimony.executeDolloParsimonyOnDomainPresence();
753 SurfacingUtil.writeMatrixToFile( domain_parsimony.getGainLossMatrix(),
754 outfile_name + surfacing.PARSIMONY_OUTPUT_GL_SUFFIX_DOLLO_DOMAINS,
756 SurfacingUtil.writeMatrixToFile( domain_parsimony.getGainLossCountsMatrix(),
757 outfile_name + surfacing.PARSIMONY_OUTPUT_GL_COUNTS_SUFFIX_DOLLO_DOMAINS,
759 SurfacingUtil.writeBinaryStatesMatrixAsListToFile( domain_parsimony.getGainLossMatrix(),
760 CharacterStateMatrix.GainLossStates.GAIN,
761 outfile_name + surfacing.PARSIMONY_OUTPUT_DOLLO_GAINS_D,
763 ForesterUtil.LINE_SEPARATOR,
765 SurfacingUtil.writeBinaryStatesMatrixAsListToFile( domain_parsimony.getGainLossMatrix(),
766 CharacterStateMatrix.GainLossStates.LOSS,
767 outfile_name + surfacing.PARSIMONY_OUTPUT_DOLLO_LOSSES_D,
769 ForesterUtil.LINE_SEPARATOR,
771 SurfacingUtil.writeBinaryStatesMatrixAsListToFile( domain_parsimony.getGainLossMatrix(),
773 outfile_name + surfacing.PARSIMONY_OUTPUT_DOLLO_PRESENT_D,
775 ForesterUtil.LINE_SEPARATOR,
778 writeBinaryStatesMatrixToList( domain_id_to_go_ids_map,
782 domain_parsimony.getGainLossMatrix(),
783 CharacterStateMatrix.GainLossStates.GAIN,
784 outfile_name + surfacing.PARSIMONY_OUTPUT_DOLLO_GAINS_HTML_D,
786 ForesterUtil.LINE_SEPARATOR,
787 "Dollo Parsimony | Gains | Domains",
789 domain_id_to_secondary_features_maps,
790 all_pfams_encountered,
791 all_pfams_gained_as_domains,
793 tax_code_to_id_map );
794 writeBinaryStatesMatrixToList( domain_id_to_go_ids_map,
798 domain_parsimony.getGainLossMatrix(),
799 CharacterStateMatrix.GainLossStates.LOSS,
800 outfile_name + surfacing.PARSIMONY_OUTPUT_DOLLO_LOSSES_HTML_D,
802 ForesterUtil.LINE_SEPARATOR,
803 "Dollo Parsimony | Losses | Domains",
805 domain_id_to_secondary_features_maps,
806 all_pfams_encountered,
807 all_pfams_lost_as_domains,
809 tax_code_to_id_map );
810 writeBinaryStatesMatrixToList( domain_id_to_go_ids_map,
814 domain_parsimony.getGainLossMatrix(),
816 outfile_name + surfacing.PARSIMONY_OUTPUT_DOLLO_PRESENT_HTML_D,
818 ForesterUtil.LINE_SEPARATOR,
819 "Dollo Parsimony | Present | Domains",
821 domain_id_to_secondary_features_maps,
822 all_pfams_encountered,
825 tax_code_to_id_map );
826 preparePhylogeny( local_phylogeny_l,
829 "Dollo parsimony on domain presence/absence",
830 "dollo_on_domains_" + outfile_name,
832 SurfacingUtil.writePhylogenyToFile( local_phylogeny_l,
833 outfile_name + surfacing.DOMAINS_PARSIMONY_TREE_OUTPUT_SUFFIX_DOLLO );
835 writeAllDomainsChangedOnAllSubtrees( local_phylogeny_l, true, outfile_name, "_dollo_all_gains_d" );
836 writeAllDomainsChangedOnAllSubtrees( local_phylogeny_l, false, outfile_name, "_dollo_all_losses_d" );
838 catch ( final IOException e ) {
840 ForesterUtil.fatalError( surfacing.PRG_NAME, e.getLocalizedMessage() );
842 if ( perform_dc_fich && ( domain_parsimony.calculateNumberOfBinaryDomainCombination() > 0 ) ) {
843 // FITCH DOMAIN COMBINATIONS
844 // -------------------------
845 local_phylogeny_l = phylogeny.copy();
846 String randomization = "no";
847 if ( radomize_fitch_parsimony ) {
849 .executeFitchParsimonyOnBinaryDomainCombintion( random_number_seed_for_fitch_parsimony );
850 randomization = "yes, seed = " + random_number_seed_for_fitch_parsimony;
853 domain_parsimony.executeFitchParsimonyOnBinaryDomainCombintion( use_last_in_fitch_parsimony );
855 SurfacingUtil.writeMatrixToFile( domain_parsimony.getGainLossMatrix(),
857 + surfacing.PARSIMONY_OUTPUT_GL_SUFFIX_FITCH_BINARY_COMBINATIONS,
859 SurfacingUtil.writeMatrixToFile( domain_parsimony.getGainLossCountsMatrix(),
861 + surfacing.PARSIMONY_OUTPUT_GL_COUNTS_SUFFIX_FITCH_BINARY_COMBINATIONS,
863 SurfacingUtil.writeBinaryStatesMatrixAsListToFile( domain_parsimony.getGainLossMatrix(),
864 CharacterStateMatrix.GainLossStates.GAIN,
865 outfile_name + surfacing.PARSIMONY_OUTPUT_FITCH_GAINS_BC,
867 ForesterUtil.LINE_SEPARATOR,
869 SurfacingUtil.writeBinaryStatesMatrixAsListToFile( domain_parsimony.getGainLossMatrix(),
870 CharacterStateMatrix.GainLossStates.LOSS,
872 + surfacing.PARSIMONY_OUTPUT_FITCH_LOSSES_BC,
874 ForesterUtil.LINE_SEPARATOR,
876 SurfacingUtil.writeBinaryStatesMatrixAsListToFile( domain_parsimony.getGainLossMatrix(),
879 + surfacing.PARSIMONY_OUTPUT_FITCH_PRESENT_BC,
881 ForesterUtil.LINE_SEPARATOR,
883 if ( all_binary_domains_combination_gained_fitch != null ) {
884 collectChangedDomainCombinationsFromBinaryStatesMatrixAsListToFile( domain_parsimony
885 .getGainLossMatrix(), dc_type, all_binary_domains_combination_gained_fitch, true );
887 if ( all_binary_domains_combination_lost_fitch != null ) {
888 collectChangedDomainCombinationsFromBinaryStatesMatrixAsListToFile( domain_parsimony
889 .getGainLossMatrix(), dc_type, all_binary_domains_combination_lost_fitch, false );
891 if ( output_binary_domain_combinations_for_graphs ) {
892 SurfacingUtil.writeBinaryStatesMatrixAsListToFileForBinaryCombinationsForGraphAnalysis( domain_parsimony
893 .getGainLossMatrix(),
896 + surfacing.PARSIMONY_OUTPUT_FITCH_PRESENT_BC_OUTPUTFILE_SUFFIX_FOR_GRAPH_ANALYSIS,
898 ForesterUtil.LINE_SEPARATOR,
899 BinaryDomainCombination.OutputFormat.DOT );
902 writeBinaryStatesMatrixToList( domain_id_to_go_ids_map,
906 domain_parsimony.getGainLossMatrix(),
907 CharacterStateMatrix.GainLossStates.GAIN,
908 outfile_name + surfacing.PARSIMONY_OUTPUT_FITCH_GAINS_HTML_BC,
910 ForesterUtil.LINE_SEPARATOR,
911 "Fitch Parsimony | Gains | Domain Combinations",
914 all_pfams_encountered,
915 all_pfams_gained_as_dom_combinations,
917 tax_code_to_id_map );
918 writeBinaryStatesMatrixToList( domain_id_to_go_ids_map,
922 domain_parsimony.getGainLossMatrix(),
923 CharacterStateMatrix.GainLossStates.LOSS,
924 outfile_name + surfacing.PARSIMONY_OUTPUT_FITCH_LOSSES_HTML_BC,
926 ForesterUtil.LINE_SEPARATOR,
927 "Fitch Parsimony | Losses | Domain Combinations",
930 all_pfams_encountered,
931 all_pfams_lost_as_dom_combinations,
933 tax_code_to_id_map );
934 // writeBinaryStatesMatrixToList( domain_id_to_go_ids_map,
935 // go_id_to_term_map,
936 // go_namespace_limit,
938 // domain_parsimony.getGainLossMatrix(),
940 // outfile_name + surfacing.PARSIMONY_OUTPUT_FITCH_PRESENT_HTML_BC,
942 // ForesterUtil.LINE_SEPARATOR,
943 // "Fitch Parsimony | Present | Domain Combinations",
946 // all_pfams_encountered,
948 // "_fitch_present_dc",
949 // tax_code_to_id_map );
950 writeAllEncounteredPfamsToFile( domain_id_to_go_ids_map,
953 all_pfams_encountered );
954 writePfamsToFile( outfile_name + surfacing.ALL_PFAMS_GAINED_AS_DOMAINS_SUFFIX,
955 all_pfams_gained_as_domains );
956 writePfamsToFile( outfile_name + surfacing.ALL_PFAMS_LOST_AS_DOMAINS_SUFFIX, all_pfams_lost_as_domains );
957 writePfamsToFile( outfile_name + surfacing.ALL_PFAMS_GAINED_AS_DC_SUFFIX,
958 all_pfams_gained_as_dom_combinations );
959 writePfamsToFile( outfile_name + surfacing.ALL_PFAMS_LOST_AS_DC_SUFFIX,
960 all_pfams_lost_as_dom_combinations );
961 preparePhylogeny( local_phylogeny_l,
964 "Fitch parsimony on binary domain combination presence/absence randomization: "
966 "fitch_on_binary_domain_combinations_" + outfile_name,
969 .writePhylogenyToFile( local_phylogeny_l,
971 + surfacing.BINARY_DOMAIN_COMBINATIONS_PARSIMONY_TREE_OUTPUT_SUFFIX_FITCH );
972 calculateIndependentDomainCombinationGains( local_phylogeny_l,
974 + surfacing.INDEPENDENT_DC_GAINS_FITCH_PARS_COUNTS_OUTPUT_SUFFIX,
976 + surfacing.INDEPENDENT_DC_GAINS_FITCH_PARS_DC_OUTPUT_SUFFIX,
978 + surfacing.INDEPENDENT_DC_GAINS_FITCH_PARS_DC_FOR_GO_MAPPING_OUTPUT_SUFFIX,
980 + surfacing.INDEPENDENT_DC_GAINS_FITCH_PARS_DC_FOR_GO_MAPPING_OUTPUT_UNIQUE_SUFFIX,
981 outfile_name + "_indep_dc_gains_fitch_lca_ranks.txt",
982 outfile_name + "_indep_dc_gains_fitch_lca_taxonomies.txt",
983 outfile_name + "_indep_dc_gains_fitch_protein_statistics.txt",
984 protein_length_stats_by_dc,
985 domain_number_stats_by_dc,
986 domain_length_stats_by_domain );
990 public static void executeParsimonyAnalysisForSecondaryFeatures( final String outfile_name,
991 final DomainParsimonyCalculator secondary_features_parsimony,
992 final Phylogeny phylogeny,
993 final String parameters_str,
994 final Map<Species, MappingResults> mapping_results_map,
995 final boolean use_last_in_fitch_parsimony ) {
996 final String sep = ForesterUtil.LINE_SEPARATOR + "###################" + ForesterUtil.LINE_SEPARATOR;
997 final String date_time = ForesterUtil.getCurrentDateTime();
998 System.out.println();
999 writeToNexus( outfile_name + surfacing.NEXUS_SECONDARY_FEATURES,
1000 secondary_features_parsimony.createMatrixOfSecondaryFeaturePresenceOrAbsence( null ),
1002 Phylogeny local_phylogeny_copy = phylogeny.copy();
1003 secondary_features_parsimony.executeDolloParsimonyOnSecondaryFeatures( mapping_results_map );
1004 SurfacingUtil.writeMatrixToFile( secondary_features_parsimony.getGainLossMatrix(),
1005 outfile_name + surfacing.PARSIMONY_OUTPUT_GL_SUFFIX_DOLLO_SECONDARY_FEATURES,
1007 SurfacingUtil.writeMatrixToFile( secondary_features_parsimony.getGainLossCountsMatrix(),
1009 + surfacing.PARSIMONY_OUTPUT_GL_COUNTS_SUFFIX_DOLLO_SECONDARY_FEATURES,
1011 SurfacingUtil.writeBinaryStatesMatrixAsListToFile( secondary_features_parsimony.getGainLossMatrix(),
1012 CharacterStateMatrix.GainLossStates.GAIN,
1014 + surfacing.PARSIMONY_OUTPUT_DOLLO_GAINS_SECONDARY_FEATURES,
1016 ForesterUtil.LINE_SEPARATOR,
1018 SurfacingUtil.writeBinaryStatesMatrixAsListToFile( secondary_features_parsimony.getGainLossMatrix(),
1019 CharacterStateMatrix.GainLossStates.LOSS,
1021 + surfacing.PARSIMONY_OUTPUT_DOLLO_LOSSES_SECONDARY_FEATURES,
1023 ForesterUtil.LINE_SEPARATOR,
1025 SurfacingUtil.writeBinaryStatesMatrixAsListToFile( secondary_features_parsimony.getGainLossMatrix(),
1028 + surfacing.PARSIMONY_OUTPUT_DOLLO_PRESENT_SECONDARY_FEATURES,
1030 ForesterUtil.LINE_SEPARATOR,
1032 preparePhylogeny( local_phylogeny_copy,
1033 secondary_features_parsimony,
1035 "Dollo parsimony on secondary feature presence/absence",
1036 "dollo_on_secondary_features_" + outfile_name,
1039 .writePhylogenyToFile( local_phylogeny_copy,
1040 outfile_name + surfacing.SECONDARY_FEATURES_PARSIMONY_TREE_OUTPUT_SUFFIX_DOLLO );
1041 // FITCH DOMAIN COMBINATIONS
1042 // -------------------------
1043 local_phylogeny_copy = phylogeny.copy();
1044 final String randomization = "no";
1045 secondary_features_parsimony
1046 .executeFitchParsimonyOnBinaryDomainCombintionOnSecondaryFeatures( use_last_in_fitch_parsimony );
1047 preparePhylogeny( local_phylogeny_copy,
1048 secondary_features_parsimony,
1050 "Fitch parsimony on secondary binary domain combination presence/absence randomization: "
1052 "fitch_on_binary_domain_combinations_" + outfile_name,
1055 .writePhylogenyToFile( local_phylogeny_copy,
1057 + surfacing.BINARY_DOMAIN_COMBINATIONS_PARSIMONY_TREE_OUTPUT_SUFFIX_FITCH_MAPPED );
1058 calculateIndependentDomainCombinationGains( local_phylogeny_copy,
1060 + surfacing.INDEPENDENT_DC_GAINS_FITCH_PARS_COUNTS_MAPPED_OUTPUT_SUFFIX,
1062 + surfacing.INDEPENDENT_DC_GAINS_FITCH_PARS_DC_MAPPED_OUTPUT_SUFFIX,
1064 + surfacing.INDEPENDENT_DC_GAINS_FITCH_PARS_DC_FOR_GO_MAPPING_MAPPED_OUTPUT_SUFFIX,
1066 + surfacing.INDEPENDENT_DC_GAINS_FITCH_PARS_DC_FOR_GO_MAPPING_MAPPED_OUTPUT_UNIQUE_SUFFIX,
1067 outfile_name + "_MAPPED_indep_dc_gains_fitch_lca_ranks.txt",
1068 outfile_name + "_MAPPED_indep_dc_gains_fitch_lca_taxonomies.txt",
1075 public static void executePlusMinusAnalysis( final File output_file,
1076 final List<String> plus_minus_analysis_high_copy_base,
1077 final List<String> plus_minus_analysis_high_copy_target,
1078 final List<String> plus_minus_analysis_low_copy,
1079 final List<GenomeWideCombinableDomains> gwcd_list,
1080 final SortedMap<Species, List<Protein>> protein_lists_per_species,
1081 final Map<String, List<GoId>> domain_id_to_go_ids_map,
1082 final Map<GoId, GoTerm> go_id_to_term_map,
1083 final List<Object> plus_minus_analysis_numbers ) {
1084 final Set<String> all_spec = new HashSet<String>();
1085 for( final GenomeWideCombinableDomains gwcd : gwcd_list ) {
1086 all_spec.add( gwcd.getSpecies().getSpeciesId() );
1088 final File html_out_dom = new File( output_file + surfacing.PLUS_MINUS_DOM_SUFFIX_HTML );
1089 final File plain_out_dom = new File( output_file + surfacing.PLUS_MINUS_DOM_SUFFIX );
1090 final File html_out_dc = new File( output_file + surfacing.PLUS_MINUS_DC_SUFFIX_HTML );
1091 final File all_domains_go_ids_out_dom = new File( output_file + surfacing.PLUS_MINUS_ALL_GO_IDS_DOM_SUFFIX );
1092 final File passing_domains_go_ids_out_dom = new File( output_file
1093 + surfacing.PLUS_MINUS_PASSING_GO_IDS_DOM_SUFFIX );
1094 final File proteins_file_base = new File( output_file + "" );
1095 final int min_diff = ( ( Integer ) plus_minus_analysis_numbers.get( 0 ) ).intValue();
1096 final double factor = ( ( Double ) plus_minus_analysis_numbers.get( 1 ) ).doubleValue();
1098 DomainCountsDifferenceUtil.calculateCopyNumberDifferences( gwcd_list,
1099 protein_lists_per_species,
1100 plus_minus_analysis_high_copy_base,
1101 plus_minus_analysis_high_copy_target,
1102 plus_minus_analysis_low_copy,
1108 domain_id_to_go_ids_map,
1110 all_domains_go_ids_out_dom,
1111 passing_domains_go_ids_out_dom,
1112 proteins_file_base );
1114 catch ( final IOException e ) {
1115 ForesterUtil.fatalError( surfacing.PRG_NAME, e.getLocalizedMessage() );
1117 ForesterUtil.programMessage( surfacing.PRG_NAME,
1118 "Wrote plus minus domain analysis results to \"" + html_out_dom + "\"" );
1119 ForesterUtil.programMessage( surfacing.PRG_NAME,
1120 "Wrote plus minus domain analysis results to \"" + plain_out_dom + "\"" );
1121 ForesterUtil.programMessage( surfacing.PRG_NAME,
1122 "Wrote plus minus domain analysis results to \"" + html_out_dc + "\"" );
1123 ForesterUtil.programMessage( surfacing.PRG_NAME,
1124 "Wrote plus minus domain analysis based passing GO ids to \""
1125 + passing_domains_go_ids_out_dom + "\"" );
1126 ForesterUtil.programMessage( surfacing.PRG_NAME,
1127 "Wrote plus minus domain analysis based all GO ids to \""
1128 + all_domains_go_ids_out_dom + "\"" );
1131 public static void extractProteinNames( final List<Protein> proteins,
1132 final List<String> query_domain_ids_nc_order,
1134 final String separator,
1135 final String limit_to_species )
1136 throws IOException {
1137 for( final Protein protein : proteins ) {
1138 if ( ForesterUtil.isEmpty( limit_to_species )
1139 || protein.getSpecies().getSpeciesId().equalsIgnoreCase( limit_to_species ) ) {
1140 if ( protein.contains( query_domain_ids_nc_order, true ) ) {
1141 out.write( protein.getSpecies().getSpeciesId() );
1142 out.write( separator );
1143 out.write( protein.getProteinId().getId() );
1144 out.write( separator );
1146 final Set<String> visited_domain_ids = new HashSet<String>();
1147 boolean first = true;
1148 for( final Domain domain : protein.getProteinDomains() ) {
1149 if ( !visited_domain_ids.contains( domain.getDomainId() ) ) {
1150 visited_domain_ids.add( domain.getDomainId() );
1157 out.write( domain.getDomainId() );
1159 out.write( "" + domain.getTotalCount() );
1164 out.write( separator );
1165 if ( !( ForesterUtil.isEmpty( protein.getDescription() )
1166 || protein.getDescription().equals( SurfacingConstants.NONE ) ) ) {
1167 out.write( protein.getDescription() );
1169 out.write( separator );
1170 if ( !( ForesterUtil.isEmpty( protein.getAccession() )
1171 || protein.getAccession().equals( SurfacingConstants.NONE ) ) ) {
1172 out.write( protein.getAccession() );
1174 out.write( SurfacingConstants.NL );
1181 public static void extractProteinNames( final SortedMap<Species, List<Protein>> protein_lists_per_species,
1182 final String domain_id,
1184 final String separator,
1185 final String limit_to_species,
1186 final double domain_e_cutoff )
1187 throws IOException {
1188 //System.out.println( "Per domain E-value: " + domain_e_cutoff );
1189 for( final Species species : protein_lists_per_species.keySet() ) {
1190 //System.out.println( species + ":" );
1191 for( final Protein protein : protein_lists_per_species.get( species ) ) {
1192 if ( ForesterUtil.isEmpty( limit_to_species )
1193 || protein.getSpecies().getSpeciesId().equalsIgnoreCase( limit_to_species ) ) {
1194 final List<Domain> domains = protein.getProteinDomains( domain_id );
1195 if ( domains.size() > 0 ) {
1196 out.write( protein.getSpecies().getSpeciesId() );
1197 out.write( separator );
1198 out.write( protein.getProteinId().getId() );
1199 out.write( separator );
1200 out.write( domain_id.toString() );
1201 out.write( separator );
1203 for( final Domain domain : domains ) {
1204 if ( ( domain_e_cutoff < 0 ) || ( domain.getPerDomainEvalue() <= domain_e_cutoff ) ) {
1206 out.write( domain.getFrom() + "-" + domain.getTo() );
1207 if ( prev_to >= 0 ) {
1208 final int l = domain.getFrom() - prev_to;
1209 // System.out.println( l );
1211 prev_to = domain.getTo();
1215 out.write( separator );
1216 final List<Domain> domain_list = new ArrayList<Domain>();
1217 for( final Domain domain : protein.getProteinDomains() ) {
1218 if ( ( domain_e_cutoff < 0 ) || ( domain.getPerDomainEvalue() <= domain_e_cutoff ) ) {
1219 domain_list.add( domain );
1222 final Domain domain_ary[] = new Domain[ domain_list.size() ];
1223 for( int i = 0; i < domain_list.size(); ++i ) {
1224 domain_ary[ i ] = domain_list.get( i );
1226 Arrays.sort( domain_ary, new DomainComparator( true ) );
1228 boolean first = true;
1229 for( final Domain domain : domain_ary ) {
1236 out.write( domain.getDomainId().toString() );
1237 out.write( ":" + domain.getFrom() + "-" + domain.getTo() );
1238 out.write( ":" + domain.getPerDomainEvalue() );
1241 if ( !( ForesterUtil.isEmpty( protein.getDescription() )
1242 || protein.getDescription().equals( SurfacingConstants.NONE ) ) ) {
1243 out.write( protein.getDescription() );
1245 out.write( separator );
1246 if ( !( ForesterUtil.isEmpty( protein.getAccession() )
1247 || protein.getAccession().equals( SurfacingConstants.NONE ) ) ) {
1248 out.write( protein.getAccession() );
1250 out.write( SurfacingConstants.NL );
1258 public static SortedSet<String> getAllDomainIds( final List<GenomeWideCombinableDomains> gwcd_list ) {
1259 final SortedSet<String> all_domains_ids = new TreeSet<String>();
1260 for( final GenomeWideCombinableDomains gwcd : gwcd_list ) {
1261 final Set<String> all_domains = gwcd.getAllDomainIds();
1262 // for( final Domain domain : all_domains ) {
1263 all_domains_ids.addAll( all_domains );
1266 return all_domains_ids;
1269 public static SortedMap<String, Integer> getDomainCounts( final List<Protein> protein_domain_collections ) {
1270 final SortedMap<String, Integer> map = new TreeMap<String, Integer>();
1271 for( final Protein protein_domain_collection : protein_domain_collections ) {
1272 for( final Object name : protein_domain_collection.getProteinDomains() ) {
1273 final BasicDomain protein_domain = ( BasicDomain ) name;
1274 final String id = protein_domain.getDomainId();
1275 if ( map.containsKey( id ) ) {
1276 map.put( id, map.get( id ) + 1 );
1286 public static int getNumberOfNodesLackingName( final Phylogeny p, final StringBuilder names ) {
1287 final PhylogenyNodeIterator it = p.iteratorPostorder();
1289 while ( it.hasNext() ) {
1290 final PhylogenyNode n = it.next();
1291 if ( ForesterUtil.isEmpty( n.getName() )
1292 && ( !n.getNodeData().isHasTaxonomy()
1293 || ForesterUtil.isEmpty( n.getNodeData().getTaxonomy().getScientificName() ) )
1294 && ( !n.getNodeData().isHasTaxonomy()
1295 || ForesterUtil.isEmpty( n.getNodeData().getTaxonomy().getCommonName() ) ) ) {
1296 if ( n.getParent() != null ) {
1297 names.append( " " );
1298 names.append( n.getParent().getName() );
1300 final List l = n.getAllExternalDescendants();
1301 for( final Object object : l ) {
1302 System.out.println( l.toString() );
1310 public static void log( final String msg, final Writer w ) {
1313 w.write( ForesterUtil.LINE_SEPARATOR );
1315 catch ( final IOException e ) {
1316 ForesterUtil.fatalError( surfacing.PRG_NAME, e.getLocalizedMessage() );
1320 public static Phylogeny[] obtainAndPreProcessIntrees( final File[] intree_files,
1321 final int number_of_genomes,
1322 final String[][] input_file_properties ) {
1323 final Phylogeny[] intrees = new Phylogeny[ intree_files.length ];
1325 for( final File intree_file : intree_files ) {
1326 Phylogeny intree = null;
1327 final String error = ForesterUtil.isReadableFile( intree_file );
1328 if ( !ForesterUtil.isEmpty( error ) ) {
1329 ForesterUtil.fatalError( surfacing.PRG_NAME,
1330 "cannot read input tree file [" + intree_file + "]: " + error );
1333 final Phylogeny[] p_array = ParserBasedPhylogenyFactory.getInstance()
1334 .create( intree_file, ParserUtils.createParserDependingOnFileType( intree_file, true ) );
1335 if ( p_array.length < 1 ) {
1336 ForesterUtil.fatalError( surfacing.PRG_NAME,
1337 "file [" + intree_file
1338 + "] does not contain any phylogeny in phyloXML format" );
1340 else if ( p_array.length > 1 ) {
1341 ForesterUtil.fatalError( surfacing.PRG_NAME,
1342 "file [" + intree_file
1343 + "] contains more than one phylogeny in phyloXML format" );
1345 intree = p_array[ 0 ];
1347 catch ( final Exception e ) {
1348 ForesterUtil.fatalError( surfacing.PRG_NAME,
1349 "failed to read input tree from file [" + intree_file + "]: " + error );
1351 if ( ( intree == null ) || intree.isEmpty() ) {
1352 ForesterUtil.fatalError( surfacing.PRG_NAME, "input tree [" + intree_file + "] is empty" );
1354 if ( !intree.isRooted() ) {
1355 ForesterUtil.fatalError( surfacing.PRG_NAME, "input tree [" + intree_file + "] is not rooted" );
1357 if ( intree.getNumberOfExternalNodes() < number_of_genomes ) {
1358 ForesterUtil.fatalError( surfacing.PRG_NAME,
1359 "number of external nodes [" + intree.getNumberOfExternalNodes()
1360 + "] of input tree [" + intree_file
1361 + "] is smaller than the number of genomes the be analyzed ["
1362 + number_of_genomes + "]" );
1364 final StringBuilder parent_names = new StringBuilder();
1365 final int nodes_lacking_name = getNumberOfNodesLackingName( intree, parent_names );
1366 if ( nodes_lacking_name > 0 ) {
1367 ForesterUtil.fatalError( surfacing.PRG_NAME,
1368 "input tree [" + intree_file + "] has " + nodes_lacking_name
1369 + " node(s) lacking a name [parent names:" + parent_names + "]" );
1371 preparePhylogenyForParsimonyAnalyses( intree, input_file_properties );
1372 if ( !intree.isCompletelyBinary() ) {
1373 ForesterUtil.printWarningMessage( surfacing.PRG_NAME,
1374 "input tree [" + intree_file + "] is not completely binary" );
1376 intrees[ i++ ] = intree;
1381 public static Phylogeny obtainFirstIntree( final File intree_file ) {
1382 Phylogeny intree = null;
1383 final String error = ForesterUtil.isReadableFile( intree_file );
1384 if ( !ForesterUtil.isEmpty( error ) ) {
1385 ForesterUtil.fatalError( surfacing.PRG_NAME,
1386 "cannot read input tree file [" + intree_file + "]: " + error );
1389 final Phylogeny[] phys = ParserBasedPhylogenyFactory.getInstance()
1390 .create( intree_file, ParserUtils.createParserDependingOnFileType( intree_file, true ) );
1391 if ( phys.length < 1 ) {
1393 .fatalError( surfacing.PRG_NAME,
1394 "file [" + intree_file + "] does not contain any phylogeny in phyloXML format" );
1396 else if ( phys.length > 1 ) {
1398 .fatalError( surfacing.PRG_NAME,
1399 "file [" + intree_file + "] contains more than one phylogeny in phyloXML format" );
1403 catch ( final Exception e ) {
1404 ForesterUtil.fatalError( surfacing.PRG_NAME,
1405 "failed to read input tree from file [" + intree_file + "]: " + error );
1407 if ( ( intree == null ) || intree.isEmpty() ) {
1408 ForesterUtil.fatalError( surfacing.PRG_NAME, "input tree [" + intree_file + "] is empty" );
1410 if ( !intree.isRooted() ) {
1411 ForesterUtil.fatalError( surfacing.PRG_NAME, "input tree [" + intree_file + "] is not rooted" );
1416 public static String obtainHexColorStringDependingOnTaxonomyGroup( final String tax_code, final Phylogeny phy )
1417 throws IllegalArgumentException {
1418 if ( !_TAXCODE_HEXCOLORSTRING_MAP.containsKey( tax_code ) ) {
1419 if ( ( phy != null ) && !phy.isEmpty() ) {
1420 // final List<PhylogenyNode> nodes = phy.getNodesViaTaxonomyCode( tax_code );
1422 // if ( ( nodes == null ) || nodes.isEmpty() ) {
1423 // throw new IllegalArgumentException( "code " + tax_code + " is not found" );
1425 // if ( nodes.size() != 1 ) {
1426 // throw new IllegalArgumentException( "code " + tax_code + " is not unique" );
1428 // PhylogenyNode n = nodes.get( 0 );
1429 // while ( n != null ) {
1430 // if ( n.getNodeData().isHasTaxonomy()
1431 // && !ForesterUtil.isEmpty( n.getNodeData().getTaxonomy().getScientificName() ) ) {
1432 // c = ForesterUtil.obtainColorDependingOnTaxonomyGroup( n.getNodeData().getTaxonomy()
1433 // .getScientificName(), tax_code );
1435 // if ( ( c == null ) && !ForesterUtil.isEmpty( n.getName() ) ) {
1436 // c = ForesterUtil.obtainColorDependingOnTaxonomyGroup( n.getName(), tax_code );
1438 // if ( c != null ) {
1441 // n = n.getParent();
1443 final String group = obtainTaxonomyGroup( tax_code, phy );
1444 final Color c = ForesterUtil.obtainColorDependingOnTaxonomyGroup( group );
1446 throw new IllegalArgumentException( "no color found for taxonomy group \"" + group
1447 + "\" for code \"" + tax_code + "\"" );
1449 final String hex = String.format( "#%02x%02x%02x", c.getRed(), c.getGreen(), c.getBlue() );
1450 _TAXCODE_HEXCOLORSTRING_MAP.put( tax_code, hex );
1453 throw new IllegalArgumentException( "unable to obtain color for code " + tax_code
1454 + " (tree is null or empty and code is not in map)" );
1457 return _TAXCODE_HEXCOLORSTRING_MAP.get( tax_code );
1460 public static String obtainTaxonomyGroup( final String tax_code, final Phylogeny species_tree )
1461 throws IllegalArgumentException {
1462 if ( !_TAXCODE_TAXGROUP_MAP.containsKey( tax_code ) ) {
1463 if ( ( species_tree != null ) && !species_tree.isEmpty() ) {
1464 final List<PhylogenyNode> nodes = species_tree.getNodesViaTaxonomyCode( tax_code );
1465 if ( ( nodes == null ) || nodes.isEmpty() ) {
1466 throw new IllegalArgumentException( "code " + tax_code + " is not found" );
1468 if ( nodes.size() != 1 ) {
1469 throw new IllegalArgumentException( "code " + tax_code + " is not unique" );
1471 PhylogenyNode n = nodes.get( 0 );
1472 String group = null;
1473 while ( n != null ) {
1474 if ( n.getNodeData().isHasTaxonomy()
1475 && !ForesterUtil.isEmpty( n.getNodeData().getTaxonomy().getScientificName() ) ) {
1476 group = ForesterUtil
1477 .obtainNormalizedTaxonomyGroup( n.getNodeData().getTaxonomy().getScientificName() );
1479 if ( ForesterUtil.isEmpty( group ) && !ForesterUtil.isEmpty( n.getName() ) ) {
1480 group = ForesterUtil.obtainNormalizedTaxonomyGroup( n.getName() );
1482 if ( !ForesterUtil.isEmpty( group ) ) {
1487 if ( ForesterUtil.isEmpty( group ) ) {
1488 group = TaxonomyGroups.OTHER;
1490 _TAXCODE_TAXGROUP_MAP.put( tax_code, group );
1493 throw new IllegalArgumentException( "unable to obtain group for code " + tax_code
1494 + " (tree is null or empty and code is not in map)" );
1497 return _TAXCODE_TAXGROUP_MAP.get( tax_code );
1500 public static void performDomainArchitectureAnalysis( final SortedMap<String, Set<String>> domain_architecutures,
1501 final SortedMap<String, Integer> domain_architecuture_counts,
1502 final int min_count,
1503 final File da_counts_outfile,
1504 final File unique_da_outfile ) {
1505 checkForOutputFileWriteability( da_counts_outfile );
1506 checkForOutputFileWriteability( unique_da_outfile );
1508 final BufferedWriter da_counts_out = new BufferedWriter( new FileWriter( da_counts_outfile ) );
1509 final BufferedWriter unique_da_out = new BufferedWriter( new FileWriter( unique_da_outfile ) );
1510 final Iterator<Entry<String, Integer>> it = domain_architecuture_counts.entrySet().iterator();
1511 while ( it.hasNext() ) {
1512 final Map.Entry<String, Integer> e = it.next();
1513 final String da = e.getKey();
1514 final int count = e.getValue();
1515 if ( count >= min_count ) {
1516 da_counts_out.write( da );
1517 da_counts_out.write( "\t" );
1518 da_counts_out.write( String.valueOf( count ) );
1519 da_counts_out.write( ForesterUtil.LINE_SEPARATOR );
1522 final Iterator<Entry<String, Set<String>>> it2 = domain_architecutures.entrySet().iterator();
1523 while ( it2.hasNext() ) {
1524 final Map.Entry<String, Set<String>> e2 = it2.next();
1525 final String genome = e2.getKey();
1526 final Set<String> das = e2.getValue();
1527 if ( das.contains( da ) ) {
1528 unique_da_out.write( genome );
1529 unique_da_out.write( "\t" );
1530 unique_da_out.write( da );
1531 unique_da_out.write( ForesterUtil.LINE_SEPARATOR );
1536 unique_da_out.close();
1537 da_counts_out.close();
1539 catch ( final IOException e ) {
1540 ForesterUtil.fatalError( surfacing.PRG_NAME, e.getMessage() );
1542 ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote distance matrices to \"" + da_counts_outfile + "\"" );
1543 ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote distance matrices to \"" + unique_da_outfile + "\"" );
1547 public static void preparePhylogeny( final Phylogeny p,
1548 final DomainParsimonyCalculator domain_parsimony,
1549 final String date_time,
1550 final String method,
1552 final String parameters_str ) {
1553 domain_parsimony.decoratePhylogenyWithDomains( p );
1554 final StringBuilder desc = new StringBuilder();
1555 desc.append( "[Method: " + method + "] [Date: " + date_time + "] " );
1556 desc.append( "[Cost: " + domain_parsimony.getCost() + "] " );
1557 desc.append( "[Gains: " + domain_parsimony.getTotalGains() + "] " );
1558 desc.append( "[Losses: " + domain_parsimony.getTotalLosses() + "] " );
1559 desc.append( "[Unchanged: " + domain_parsimony.getTotalUnchanged() + "] " );
1560 desc.append( "[Parameters: " + parameters_str + "]" );
1562 p.setDescription( desc.toString() );
1563 p.setConfidence( new Confidence( domain_parsimony.getCost(), "parsimony" ) );
1564 p.setRerootable( false );
1565 p.setRooted( true );
1568 public static void preparePhylogenyForParsimonyAnalyses( final Phylogeny intree,
1569 final String[][] input_file_properties ) {
1570 final String[] genomes = new String[ input_file_properties.length ];
1571 for( int i = 0; i < input_file_properties.length; ++i ) {
1572 if ( intree.getNodes( input_file_properties[ i ][ 1 ] ).size() > 1 ) {
1573 ForesterUtil.fatalError( surfacing.PRG_NAME,
1574 "node named [" + input_file_properties[ i ][ 1 ]
1575 + "] is not unique in input tree " + intree.getName() );
1577 genomes[ i ] = input_file_properties[ i ][ 1 ];
1580 final PhylogenyNodeIterator it = intree.iteratorPostorder();
1581 while ( it.hasNext() ) {
1582 final PhylogenyNode n = it.next();
1583 if ( ForesterUtil.isEmpty( n.getName() ) ) {
1584 if ( n.getNodeData().isHasTaxonomy()
1585 && !ForesterUtil.isEmpty( n.getNodeData().getTaxonomy().getTaxonomyCode() ) ) {
1586 n.setName( n.getNodeData().getTaxonomy().getTaxonomyCode() );
1588 else if ( n.getNodeData().isHasTaxonomy()
1589 && !ForesterUtil.isEmpty( n.getNodeData().getTaxonomy().getScientificName() ) ) {
1590 n.setName( n.getNodeData().getTaxonomy().getScientificName() );
1592 else if ( n.getNodeData().isHasTaxonomy()
1593 && !ForesterUtil.isEmpty( n.getNodeData().getTaxonomy().getCommonName() ) ) {
1594 n.setName( n.getNodeData().getTaxonomy().getCommonName() );
1598 .fatalError( surfacing.PRG_NAME,
1599 "node with no name, scientific name, common name, or taxonomy code present" );
1604 final List<String> igns = PhylogenyMethods.deleteExternalNodesPositiveSelection( genomes, intree );
1605 if ( igns.size() > 0 ) {
1606 System.out.println( "Not using the following " + igns.size() + " nodes:" );
1607 for( int i = 0; i < igns.size(); ++i ) {
1608 System.out.println( " " + i + ": " + igns.get( i ) );
1610 System.out.println( "--" );
1612 for( final String[] input_file_propertie : input_file_properties ) {
1614 intree.getNode( input_file_propertie[ 1 ] );
1616 catch ( final IllegalArgumentException e ) {
1617 ForesterUtil.fatalError( surfacing.PRG_NAME,
1618 "node named [" + input_file_propertie[ 1 ]
1619 + "] not present/not unique in input tree" );
1624 public static void printOutPercentageOfMultidomainProteins( final SortedMap<Integer, Integer> all_genomes_domains_per_potein_histo,
1625 final Writer log_writer ) {
1627 for( final Entry<Integer, Integer> entry : all_genomes_domains_per_potein_histo.entrySet() ) {
1628 sum += entry.getValue();
1630 final double percentage = ( 100.0 * ( sum - all_genomes_domains_per_potein_histo.get( 1 ) ) ) / sum;
1631 ForesterUtil.programMessage( surfacing.PRG_NAME, "Percentage of multidomain proteins: " + percentage + "%" );
1632 log( "Percentage of multidomain proteins: : " + percentage + "%", log_writer );
1635 public static void processFilter( final File filter_file, final SortedSet<String> filter ) {
1636 SortedSet<String> filter_str = null;
1638 filter_str = ForesterUtil.file2set( filter_file );
1640 catch ( final IOException e ) {
1641 ForesterUtil.fatalError( surfacing.PRG_NAME, e.getMessage() );
1643 if ( filter_str != null ) {
1644 for( final String string : filter_str ) {
1645 filter.add( string );
1648 if ( surfacing.VERBOSE ) {
1649 System.out.println( "Filter:" );
1650 for( final String domainId : filter ) {
1651 System.out.println( domainId );
1656 public static String[][] processInputGenomesFile( final File input_genomes ) {
1657 String[][] input_file_properties = null;
1659 input_file_properties = ForesterUtil.file22dArray( input_genomes );
1661 catch ( final IOException e ) {
1662 ForesterUtil.fatalError( surfacing.PRG_NAME,
1663 "genomes files is to be in the following format \"<hmmpfam output file> <species>\": "
1664 + e.getLocalizedMessage() );
1666 final Set<String> specs = new HashSet<String>();
1667 final Set<String> paths = new HashSet<String>();
1668 for( int i = 0; i < input_file_properties.length; ++i ) {
1669 if ( !PhyloXmlUtil.TAXOMONY_CODE_PATTERN.matcher( input_file_properties[ i ][ 1 ] ).matches() ) {
1670 ForesterUtil.fatalError( surfacing.PRG_NAME,
1671 "illegal format for species code: " + input_file_properties[ i ][ 1 ] );
1673 if ( specs.contains( input_file_properties[ i ][ 1 ] ) ) {
1674 ForesterUtil.fatalError( surfacing.PRG_NAME,
1675 "species code " + input_file_properties[ i ][ 1 ] + " is not unique" );
1677 specs.add( input_file_properties[ i ][ 1 ] );
1678 if ( paths.contains( input_file_properties[ i ][ 0 ] ) ) {
1679 ForesterUtil.fatalError( surfacing.PRG_NAME,
1680 "path " + input_file_properties[ i ][ 0 ] + " is not unique" );
1682 paths.add( input_file_properties[ i ][ 0 ] );
1683 final String error = ForesterUtil.isReadableFile( new File( input_file_properties[ i ][ 0 ] ) );
1684 if ( !ForesterUtil.isEmpty( error ) ) {
1685 ForesterUtil.fatalError( surfacing.PRG_NAME, error );
1688 return input_file_properties;
1691 public static void processPlusMinusAnalysisOption( final CommandLineArguments cla,
1692 final List<String> high_copy_base,
1693 final List<String> high_copy_target,
1694 final List<String> low_copy,
1695 final List<Object> numbers ) {
1696 if ( cla.isOptionSet( surfacing.PLUS_MINUS_ANALYSIS_OPTION ) ) {
1697 if ( !cla.isOptionValueSet( surfacing.PLUS_MINUS_ANALYSIS_OPTION ) ) {
1698 ForesterUtil.fatalError( surfacing.PRG_NAME,
1699 "no value for 'plus-minus' file: -" + surfacing.PLUS_MINUS_ANALYSIS_OPTION
1702 final File plus_minus_file = new File( cla.getOptionValue( surfacing.PLUS_MINUS_ANALYSIS_OPTION ) );
1703 final String msg = ForesterUtil.isReadableFile( plus_minus_file );
1704 if ( !ForesterUtil.isEmpty( msg ) ) {
1705 ForesterUtil.fatalError( surfacing.PRG_NAME, "can not read from \"" + plus_minus_file + "\": " + msg );
1707 processPlusMinusFile( plus_minus_file, high_copy_base, high_copy_target, low_copy, numbers );
1711 // First numbers is minimal difference, second is factor.
1712 public static void processPlusMinusFile( final File plus_minus_file,
1713 final List<String> high_copy_base,
1714 final List<String> high_copy_target,
1715 final List<String> low_copy,
1716 final List<Object> numbers ) {
1717 Set<String> species_set = null;
1718 int min_diff = surfacing.PLUS_MINUS_ANALYSIS_MIN_DIFF_DEFAULT;
1719 double factor = surfacing.PLUS_MINUS_ANALYSIS_FACTOR_DEFAULT;
1721 species_set = ForesterUtil.file2set( plus_minus_file );
1723 catch ( final IOException e ) {
1724 ForesterUtil.fatalError( surfacing.PRG_NAME, e.getMessage() );
1726 if ( species_set != null ) {
1727 for( final String species : species_set ) {
1728 final String species_trimmed = species.substring( 1 );
1729 if ( species.startsWith( "+" ) ) {
1730 if ( low_copy.contains( species_trimmed ) ) {
1731 ForesterUtil.fatalError( surfacing.PRG_NAME,
1732 "species/genome names can not appear with both '+' and '-' suffix, as appears the case for: \""
1733 + species_trimmed + "\"" );
1735 high_copy_base.add( species_trimmed );
1737 else if ( species.startsWith( "*" ) ) {
1738 if ( low_copy.contains( species_trimmed ) ) {
1739 ForesterUtil.fatalError( surfacing.PRG_NAME,
1740 "species/genome names can not appear with both '*' and '-' suffix, as appears the case for: \""
1741 + species_trimmed + "\"" );
1743 high_copy_target.add( species_trimmed );
1745 else if ( species.startsWith( "-" ) ) {
1746 if ( high_copy_base.contains( species_trimmed ) || high_copy_target.contains( species_trimmed ) ) {
1747 ForesterUtil.fatalError( surfacing.PRG_NAME,
1748 "species/genome names can not appear with both '+' or '*' and '-' suffix, as appears the case for: \""
1749 + species_trimmed + "\"" );
1751 low_copy.add( species_trimmed );
1753 else if ( species.startsWith( "$D" ) ) {
1755 min_diff = Integer.parseInt( species.substring( 3 ) );
1757 catch ( final NumberFormatException e ) {
1758 ForesterUtil.fatalError( surfacing.PRG_NAME,
1759 "could not parse integer value for minimal difference from: \""
1760 + species.substring( 3 ) + "\"" );
1763 else if ( species.startsWith( "$F" ) ) {
1765 factor = Double.parseDouble( species.substring( 3 ) );
1767 catch ( final NumberFormatException e ) {
1768 ForesterUtil.fatalError( surfacing.PRG_NAME,
1769 "could not parse double value for factor from: \""
1770 + species.substring( 3 ) + "\"" );
1773 else if ( species.startsWith( "#" ) ) {
1777 ForesterUtil.fatalError( surfacing.PRG_NAME,
1778 "species/genome names in 'plus minus' file must begin with '*' (high copy target genome), '+' (high copy base genomes), '-' (low copy genomes), '$D=<integer>' minimal Difference (default is 1), '$F=<double>' factor (default is 1.0), double), or '#' (ignore) suffix, encountered: \""
1781 numbers.add( new Integer( min_diff + "" ) );
1782 numbers.add( new Double( factor + "" ) );
1786 ForesterUtil.fatalError( surfacing.PRG_NAME, "'plus minus' file [" + plus_minus_file + "] appears empty" );
1791 * species | protein id | n-terminal domain | c-terminal domain | n-terminal domain per domain E-value | c-terminal domain per domain E-value
1795 static public StringBuffer proteinToDomainCombinations( final Protein protein,
1796 final String protein_id,
1797 final String separator ) {
1798 final StringBuffer sb = new StringBuffer();
1799 if ( protein.getSpecies() == null ) {
1800 throw new IllegalArgumentException( "species must not be null" );
1802 if ( ForesterUtil.isEmpty( protein.getSpecies().getSpeciesId() ) ) {
1803 throw new IllegalArgumentException( "species id must not be empty" );
1805 final List<Domain> domains = protein.getProteinDomains();
1806 if ( domains.size() > 1 ) {
1807 final Map<String, Integer> counts = new HashMap<String, Integer>();
1808 for( final Domain domain : domains ) {
1809 final String id = domain.getDomainId();
1810 if ( counts.containsKey( id ) ) {
1811 counts.put( id, counts.get( id ) + 1 );
1814 counts.put( id, 1 );
1817 final Set<String> dcs = new HashSet<String>();
1818 for( int i = 1; i < domains.size(); ++i ) {
1819 for( int j = 0; j < i; ++j ) {
1820 Domain domain_n = domains.get( i );
1821 Domain domain_c = domains.get( j );
1822 if ( domain_n.getFrom() > domain_c.getFrom() ) {
1823 domain_n = domains.get( j );
1824 domain_c = domains.get( i );
1826 final String dc = domain_n.getDomainId() + domain_c.getDomainId();
1827 if ( !dcs.contains( dc ) ) {
1829 sb.append( protein.getSpecies() );
1830 sb.append( separator );
1831 sb.append( protein_id );
1832 sb.append( separator );
1833 sb.append( domain_n.getDomainId() );
1834 sb.append( separator );
1835 sb.append( domain_c.getDomainId() );
1836 sb.append( separator );
1837 sb.append( domain_n.getPerDomainEvalue() );
1838 sb.append( separator );
1839 sb.append( domain_c.getPerDomainEvalue() );
1840 sb.append( separator );
1841 sb.append( counts.get( domain_n.getDomainId() ) );
1842 sb.append( separator );
1843 sb.append( counts.get( domain_c.getDomainId() ) );
1844 sb.append( ForesterUtil.LINE_SEPARATOR );
1849 else if ( domains.size() == 1 ) {
1850 sb.append( protein.getSpecies() );
1851 sb.append( separator );
1852 sb.append( protein_id );
1853 sb.append( separator );
1854 sb.append( domains.get( 0 ).getDomainId() );
1855 sb.append( separator );
1856 sb.append( separator );
1857 sb.append( domains.get( 0 ).getPerDomainEvalue() );
1858 sb.append( separator );
1859 sb.append( separator );
1861 sb.append( separator );
1862 sb.append( ForesterUtil.LINE_SEPARATOR );
1865 sb.append( protein.getSpecies() );
1866 sb.append( separator );
1867 sb.append( protein_id );
1868 sb.append( separator );
1869 sb.append( separator );
1870 sb.append( separator );
1871 sb.append( separator );
1872 sb.append( separator );
1873 sb.append( separator );
1874 sb.append( ForesterUtil.LINE_SEPARATOR );
1879 public static List<Domain> sortDomainsWithAscendingConfidenceValues( final Protein protein ) {
1880 final List<Domain> domains = new ArrayList<Domain>();
1881 for( final Domain d : protein.getProteinDomains() ) {
1884 Collections.sort( domains, SurfacingUtil.ASCENDING_CONFIDENCE_VALUE_ORDER );
1888 public static int storeDomainArchitectures( final String genome,
1889 final SortedMap<String, Set<String>> domain_architecutures,
1890 final List<Protein> protein_list,
1891 final Map<String, Integer> distinct_domain_architecuture_counts ) {
1892 final Set<String> da = new HashSet<String>();
1893 domain_architecutures.put( genome, da );
1894 for( final Protein protein : protein_list ) {
1895 final String da_str = ( ( BasicProtein ) protein ).toDomainArchitectureString( "~", 3, "=" );
1896 if ( !da.contains( da_str ) ) {
1897 if ( !distinct_domain_architecuture_counts.containsKey( da_str ) ) {
1898 distinct_domain_architecuture_counts.put( da_str, 1 );
1901 distinct_domain_architecuture_counts.put( da_str,
1902 distinct_domain_architecuture_counts.get( da_str ) + 1 );
1910 public static void writeAllDomainsChangedOnAllSubtrees( final Phylogeny p,
1911 final boolean get_gains,
1912 final String outdir,
1913 final String suffix_for_filename )
1914 throws IOException {
1915 CharacterStateMatrix.GainLossStates state = CharacterStateMatrix.GainLossStates.GAIN;
1917 state = CharacterStateMatrix.GainLossStates.LOSS;
1919 final File base_dir = createBaseDirForPerNodeDomainFiles( surfacing.BASE_DIRECTORY_PER_SUBTREE_DOMAIN_GAIN_LOSS_FILES,
1923 for( final PhylogenyNodeIterator it = p.iteratorPostorder(); it.hasNext(); ) {
1924 final PhylogenyNode node = it.next();
1925 if ( !node.isExternal() ) {
1926 final SortedSet<String> domains = collectAllDomainsChangedOnSubtree( node, get_gains );
1927 if ( domains.size() > 0 ) {
1928 final Writer writer = ForesterUtil.createBufferedWriter( base_dir + ForesterUtil.FILE_SEPARATOR
1929 + node.getName() + suffix_for_filename );
1930 for( final String domain : domains ) {
1931 writer.write( domain );
1932 writer.write( ForesterUtil.LINE_SEPARATOR );
1940 public static void writeBinaryDomainCombinationsFileForGraphAnalysis( final String[][] input_file_properties,
1941 final File output_dir,
1942 final GenomeWideCombinableDomains gwcd,
1944 final GenomeWideCombinableDomainsSortOrder dc_sort_order ) {
1945 File dc_outfile_dot = new File( input_file_properties[ i ][ 1 ]
1946 + surfacing.DOMAIN_COMBINITONS_OUTPUTFILE_SUFFIX_FOR_GRAPH_ANALYSIS );
1947 if ( output_dir != null ) {
1948 dc_outfile_dot = new File( output_dir + ForesterUtil.FILE_SEPARATOR + dc_outfile_dot );
1950 checkForOutputFileWriteability( dc_outfile_dot );
1951 final SortedSet<BinaryDomainCombination> binary_combinations = createSetOfAllBinaryDomainCombinationsPerGenome( gwcd );
1953 final BufferedWriter out_dot = new BufferedWriter( new FileWriter( dc_outfile_dot ) );
1954 for( final BinaryDomainCombination bdc : binary_combinations ) {
1955 out_dot.write( bdc.toGraphDescribingLanguage( BinaryDomainCombination.OutputFormat.DOT, null, null )
1957 out_dot.write( SurfacingConstants.NL );
1961 catch ( final IOException e ) {
1962 ForesterUtil.fatalError( surfacing.PRG_NAME, e.getMessage() );
1964 if ( input_file_properties[ i ].length == 3 ) {
1966 .programMessage( surfacing.PRG_NAME,
1967 "Wrote binary domain combination for \"" + input_file_properties[ i ][ 0 ] + "\" ("
1968 + input_file_properties[ i ][ 1 ] + ", " + input_file_properties[ i ][ 2 ]
1969 + ") to: \"" + dc_outfile_dot + "\"" );
1972 ForesterUtil.programMessage( surfacing.PRG_NAME,
1973 "Wrote binary domain combination for \"" + input_file_properties[ i ][ 0 ]
1974 + "\" (" + input_file_properties[ i ][ 1 ] + ") to: \""
1975 + dc_outfile_dot + "\"" );
1979 public static void writeBinaryStatesMatrixAsListToFile( final CharacterStateMatrix<CharacterStateMatrix.GainLossStates> matrix,
1980 final CharacterStateMatrix.GainLossStates state,
1981 final String filename,
1982 final String indentifier_characters_separator,
1983 final String character_separator,
1984 final Map<String, String> descriptions ) {
1985 final File outfile = new File( filename );
1986 checkForOutputFileWriteability( outfile );
1987 final SortedSet<String> sorted_ids = new TreeSet<String>();
1988 for( int i = 0; i < matrix.getNumberOfIdentifiers(); ++i ) {
1989 sorted_ids.add( matrix.getIdentifier( i ) );
1992 final BufferedWriter out = new BufferedWriter( new FileWriter( outfile ) );
1993 for( final String id : sorted_ids ) {
1994 out.write( indentifier_characters_separator );
1995 out.write( "#" + id );
1996 out.write( indentifier_characters_separator );
1997 for( int c = 0; c < matrix.getNumberOfCharacters(); ++c ) {
1999 // using null to indicate either UNCHANGED_PRESENT or GAIN.
2000 if ( ( matrix.getState( id, c ) == state ) || ( ( state == null )
2001 && ( ( matrix.getState( id, c ) == CharacterStateMatrix.GainLossStates.GAIN ) || ( matrix
2003 c ) == CharacterStateMatrix.GainLossStates.UNCHANGED_PRESENT ) ) ) ) {
2004 out.write( matrix.getCharacter( c ) );
2005 if ( ( descriptions != null ) && !descriptions.isEmpty()
2006 && descriptions.containsKey( matrix.getCharacter( c ) ) ) {
2008 out.write( descriptions.get( matrix.getCharacter( c ) ) );
2010 out.write( character_separator );
2017 catch ( final IOException e ) {
2018 ForesterUtil.fatalError( surfacing.PRG_NAME, e.getMessage() );
2020 ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote characters list: \"" + filename + "\"" );
2023 public static void writeBinaryStatesMatrixAsListToFileForBinaryCombinationsForGraphAnalysis( final CharacterStateMatrix<CharacterStateMatrix.GainLossStates> matrix,
2024 final CharacterStateMatrix.GainLossStates state,
2025 final String filename,
2026 final String indentifier_characters_separator,
2027 final String character_separator,
2028 final BinaryDomainCombination.OutputFormat bc_output_format ) {
2029 final File outfile = new File( filename );
2030 checkForOutputFileWriteability( outfile );
2031 final SortedSet<String> sorted_ids = new TreeSet<String>();
2032 for( int i = 0; i < matrix.getNumberOfIdentifiers(); ++i ) {
2033 sorted_ids.add( matrix.getIdentifier( i ) );
2036 final BufferedWriter out = new BufferedWriter( new FileWriter( outfile ) );
2037 for( final String id : sorted_ids ) {
2038 out.write( indentifier_characters_separator );
2039 out.write( "#" + id );
2040 out.write( indentifier_characters_separator );
2041 for( int c = 0; c < matrix.getNumberOfCharacters(); ++c ) {
2043 // using null to indicate either UNCHANGED_PRESENT or GAIN.
2044 if ( ( matrix.getState( id, c ) == state ) || ( ( state == null )
2045 && ( ( matrix.getState( id, c ) == CharacterStateMatrix.GainLossStates.GAIN ) || ( matrix
2047 c ) == CharacterStateMatrix.GainLossStates.UNCHANGED_PRESENT ) ) ) ) {
2048 BinaryDomainCombination bdc = null;
2050 bdc = BasicBinaryDomainCombination.obtainInstance( matrix.getCharacter( c ) );
2052 catch ( final Exception e ) {
2053 ForesterUtil.fatalError( surfacing.PRG_NAME, e.getLocalizedMessage() );
2055 out.write( bdc.toGraphDescribingLanguage( bc_output_format, null, null ).toString() );
2056 out.write( character_separator );
2063 catch ( final IOException e ) {
2064 ForesterUtil.fatalError( surfacing.PRG_NAME, e.getMessage() );
2066 ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote characters list: \"" + filename + "\"" );
2069 public static void writeBinaryStatesMatrixToList( final Map<String, List<GoId>> domain_id_to_go_ids_map,
2070 final Map<GoId, GoTerm> go_id_to_term_map,
2071 final GoNameSpace go_namespace_limit,
2072 final boolean domain_combinations,
2073 final CharacterStateMatrix<CharacterStateMatrix.GainLossStates> matrix,
2074 final CharacterStateMatrix.GainLossStates state,
2075 final String filename,
2076 final String indentifier_characters_separator,
2077 final String character_separator,
2078 final String title_for_html,
2079 final String prefix_for_html,
2080 final Map<String, Set<String>>[] domain_id_to_secondary_features_maps,
2081 final SortedSet<String> all_pfams_encountered,
2082 final SortedSet<String> pfams_gained_or_lost,
2083 final String suffix_for_per_node_events_file,
2084 final Map<String, Integer> tax_code_to_id_map ) {
2085 if ( ( go_namespace_limit != null ) && ( ( go_id_to_term_map == null ) || ( go_id_to_term_map.size() < 1 ) ) ) {
2086 throw new IllegalArgumentException( "attempt to use GO namespace limit without a GO-id to term map" );
2088 else if ( ( ( domain_id_to_go_ids_map == null ) || ( domain_id_to_go_ids_map.size() < 1 ) ) ) {
2089 throw new IllegalArgumentException( "attempt to output detailed HTML without a Pfam to GO map" );
2091 else if ( ( ( go_id_to_term_map == null ) || ( go_id_to_term_map.size() < 1 ) ) ) {
2092 throw new IllegalArgumentException( "attempt to output detailed HTML without a GO-id to term map" );
2094 final File outfile = new File( filename );
2095 checkForOutputFileWriteability( outfile );
2096 final SortedSet<String> sorted_ids = new TreeSet<String>();
2097 for( int i = 0; i < matrix.getNumberOfIdentifiers(); ++i ) {
2098 sorted_ids.add( matrix.getIdentifier( i ) );
2101 final Writer out = new BufferedWriter( new FileWriter( outfile ) );
2102 final File per_node_go_mapped_domain_gain_loss_files_base_dir = createBaseDirForPerNodeDomainFiles( surfacing.BASE_DIRECTORY_PER_NODE_DOMAIN_GAIN_LOSS_FILES,
2103 domain_combinations,
2106 Writer per_node_go_mapped_domain_gain_loss_outfile_writer = null;
2107 File per_node_go_mapped_domain_gain_loss_outfile = null;
2108 int per_node_counter = 0;
2109 out.write( "<html>" );
2110 out.write( SurfacingConstants.NL );
2111 writeHtmlHead( out, title_for_html );
2112 out.write( SurfacingConstants.NL );
2113 out.write( "<body>" );
2114 out.write( SurfacingConstants.NL );
2115 out.write( "<h1>" );
2116 out.write( SurfacingConstants.NL );
2117 out.write( title_for_html );
2118 out.write( SurfacingConstants.NL );
2119 out.write( "</h1>" );
2120 out.write( SurfacingConstants.NL );
2121 out.write( "<table>" );
2122 out.write( SurfacingConstants.NL );
2123 for( final String id : sorted_ids ) {
2124 final Matcher matcher = PATTERN_SP_STYLE_TAXONOMY.matcher( id );
2125 if ( matcher.matches() ) {
2128 out.write( "<tr>" );
2129 out.write( "<td>" );
2130 out.write( "<a href=\"#" + id + "\">" + id + "</a>" );
2131 out.write( "</td>" );
2132 out.write( "</tr>" );
2133 out.write( SurfacingConstants.NL );
2135 out.write( "</table>" );
2136 out.write( SurfacingConstants.NL );
2137 for( final String id : sorted_ids ) {
2138 final Matcher matcher = PATTERN_SP_STYLE_TAXONOMY.matcher( id );
2139 if ( matcher.matches() ) {
2142 out.write( SurfacingConstants.NL );
2143 out.write( "<h2>" );
2144 out.write( "<a name=\"" + id + "\">" + id + "</a>" );
2145 writeTaxonomyLinks( out, id, tax_code_to_id_map );
2146 out.write( "</h2>" );
2147 out.write( SurfacingConstants.NL );
2148 out.write( "<table>" );
2149 out.write( SurfacingConstants.NL );
2150 out.write( "<tr>" );
2151 out.write( "<td><b>" );
2152 out.write( "Pfam domain(s)" );
2153 out.write( "</b></td><td><b>" );
2154 out.write( "GO term acc" );
2155 out.write( "</b></td><td><b>" );
2156 out.write( "GO term" );
2157 out.write( "</b></td><td><b>" );
2158 out.write( "GO namespace" );
2159 out.write( "</b></td>" );
2160 out.write( "</tr>" );
2161 out.write( SurfacingConstants.NL );
2162 out.write( "</tr>" );
2163 out.write( SurfacingConstants.NL );
2164 per_node_counter = 0;
2165 if ( matrix.getNumberOfCharacters() > 0 ) {
2166 per_node_go_mapped_domain_gain_loss_outfile = new File( per_node_go_mapped_domain_gain_loss_files_base_dir
2167 + ForesterUtil.FILE_SEPARATOR + id + suffix_for_per_node_events_file );
2168 SurfacingUtil.checkForOutputFileWriteability( per_node_go_mapped_domain_gain_loss_outfile );
2169 per_node_go_mapped_domain_gain_loss_outfile_writer = ForesterUtil
2170 .createBufferedWriter( per_node_go_mapped_domain_gain_loss_outfile );
2173 per_node_go_mapped_domain_gain_loss_outfile = null;
2174 per_node_go_mapped_domain_gain_loss_outfile_writer = null;
2176 for( int c = 0; c < matrix.getNumberOfCharacters(); ++c ) {
2178 // using null to indicate either UNCHANGED_PRESENT or GAIN.
2179 if ( ( matrix.getState( id, c ) == state ) || ( ( state == null )
2180 && ( ( matrix.getState( id, c ) == CharacterStateMatrix.GainLossStates.UNCHANGED_PRESENT )
2181 || ( matrix.getState( id, c ) == CharacterStateMatrix.GainLossStates.GAIN ) ) ) ) {
2182 final String character = matrix.getCharacter( c );
2183 String domain_0 = "";
2184 String domain_1 = "";
2185 if ( character.indexOf( BinaryDomainCombination.SEPARATOR ) > 0 ) {
2186 final String[] s = character.split( BinaryDomainCombination.SEPARATOR );
2187 if ( s.length != 2 ) {
2188 throw new AssertionError( "this should not have happened: unexpected format for domain combination: ["
2189 + character + "]" );
2195 domain_0 = character;
2197 writeDomainData( domain_id_to_go_ids_map,
2204 character_separator,
2205 domain_id_to_secondary_features_maps,
2207 all_pfams_encountered.add( domain_0 );
2208 if ( pfams_gained_or_lost != null ) {
2209 pfams_gained_or_lost.add( domain_0 );
2211 if ( !ForesterUtil.isEmpty( domain_1 ) ) {
2212 all_pfams_encountered.add( domain_1 );
2213 if ( pfams_gained_or_lost != null ) {
2214 pfams_gained_or_lost.add( domain_1 );
2217 if ( per_node_go_mapped_domain_gain_loss_outfile_writer != null ) {
2218 writeDomainsToIndividualFilePerTreeNode( per_node_go_mapped_domain_gain_loss_outfile_writer,
2225 if ( per_node_go_mapped_domain_gain_loss_outfile_writer != null ) {
2226 per_node_go_mapped_domain_gain_loss_outfile_writer.close();
2227 if ( per_node_counter < 1 ) {
2228 per_node_go_mapped_domain_gain_loss_outfile.delete();
2230 per_node_counter = 0;
2232 out.write( "</table>" );
2233 out.write( SurfacingConstants.NL );
2234 out.write( "<hr>" );
2235 out.write( SurfacingConstants.NL );
2236 } // for( final String id : sorted_ids ) {
2237 out.write( "</body>" );
2238 out.write( SurfacingConstants.NL );
2239 out.write( "</html>" );
2240 out.write( SurfacingConstants.NL );
2244 catch ( final IOException e ) {
2245 ForesterUtil.fatalError( surfacing.PRG_NAME, e.getMessage() );
2247 ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote characters detailed HTML list: \"" + filename + "\"" );
2250 public static void writeDomainCombinationsCountsFile( final String[][] input_file_properties,
2251 final File output_dir,
2252 final Writer per_genome_domain_promiscuity_statistics_writer,
2253 final GenomeWideCombinableDomains gwcd,
2255 final GenomeWideCombinableDomains.GenomeWideCombinableDomainsSortOrder dc_sort_order ) {
2256 File dc_outfile = new File( input_file_properties[ i ][ 1 ]
2257 + surfacing.DOMAIN_COMBINITON_COUNTS_OUTPUTFILE_SUFFIX );
2258 if ( output_dir != null ) {
2259 dc_outfile = new File( output_dir + ForesterUtil.FILE_SEPARATOR + dc_outfile );
2261 checkForOutputFileWriteability( dc_outfile );
2263 final BufferedWriter out = new BufferedWriter( new FileWriter( dc_outfile ) );
2264 out.write( gwcd.toStringBuilder( dc_sort_order ).toString() );
2267 catch ( final IOException e ) {
2268 ForesterUtil.fatalError( surfacing.PRG_NAME, e.getMessage() );
2270 final DescriptiveStatistics stats = gwcd.getPerGenomeDomainPromiscuityStatistics();
2272 per_genome_domain_promiscuity_statistics_writer.write( input_file_properties[ i ][ 1 ] + "\t" );
2273 per_genome_domain_promiscuity_statistics_writer
2274 .write( FORMATTER_3.format( stats.arithmeticMean() ) + "\t" );
2275 if ( stats.getN() < 2 ) {
2276 per_genome_domain_promiscuity_statistics_writer.write( "n/a" + "\t" );
2279 per_genome_domain_promiscuity_statistics_writer
2280 .write( FORMATTER_3.format( stats.sampleStandardDeviation() ) + "\t" );
2282 per_genome_domain_promiscuity_statistics_writer.write( FORMATTER_3.format( stats.median() ) + "\t" );
2283 per_genome_domain_promiscuity_statistics_writer.write( ( int ) stats.getMin() + "\t" );
2284 per_genome_domain_promiscuity_statistics_writer.write( ( int ) stats.getMax() + "\t" );
2285 per_genome_domain_promiscuity_statistics_writer.write( stats.getN() + "\t" );
2286 final SortedSet<String> mpds = gwcd.getMostPromiscuosDomain();
2287 for( final String mpd : mpds ) {
2288 per_genome_domain_promiscuity_statistics_writer.write( mpd + " " );
2290 per_genome_domain_promiscuity_statistics_writer.write( ForesterUtil.LINE_SEPARATOR );
2292 catch ( final IOException e ) {
2293 ForesterUtil.fatalError( surfacing.PRG_NAME, e.getMessage() );
2295 if ( input_file_properties[ i ].length == 3 ) {
2296 ForesterUtil.programMessage( surfacing.PRG_NAME,
2297 "Wrote domain combination counts for \"" + input_file_properties[ i ][ 0 ]
2298 + "\" (" + input_file_properties[ i ][ 1 ] + ", "
2299 + input_file_properties[ i ][ 2 ] + ") to: \"" + dc_outfile + "\"" );
2302 ForesterUtil.programMessage( surfacing.PRG_NAME,
2303 "Wrote domain combination counts for \"" + input_file_properties[ i ][ 0 ]
2304 + "\" (" + input_file_properties[ i ][ 1 ] + ") to: \"" + dc_outfile
2309 public static void writeDomainSimilaritiesToFile( final StringBuilder html_desc,
2310 final StringBuilder html_title,
2311 final Writer simple_tab_writer,
2312 final Writer single_writer,
2313 Map<Character, Writer> split_writers,
2314 final SortedSet<DomainSimilarity> similarities,
2315 final boolean treat_as_binary,
2316 final List<Species> species_order,
2317 final DomainSimilarity.PRINT_OPTION print_option,
2318 final DomainSimilarity.DomainSimilarityScoring scoring,
2319 final boolean verbose,
2320 final Map<String, Integer> tax_code_to_id_map,
2321 final Phylogeny phy,
2322 final Set<String> pos_filter_doms )
2323 throws IOException {
2324 if ( ( single_writer != null ) && ( ( split_writers == null ) || split_writers.isEmpty() ) ) {
2325 split_writers = new HashMap<Character, Writer>();
2326 split_writers.put( '_', single_writer );
2328 switch ( print_option ) {
2329 case SIMPLE_TAB_DELIMITED:
2332 for( final Character key : split_writers.keySet() ) {
2333 final Writer w = split_writers.get( key );
2334 w.write( "<html>" );
2335 w.write( SurfacingConstants.NL );
2337 writeHtmlHead( w, "DC analysis (" + html_title + ") " + key.toString().toUpperCase() );
2340 writeHtmlHead( w, "DC analysis (" + html_title + ")" );
2342 w.write( SurfacingConstants.NL );
2343 w.write( "<body>" );
2344 w.write( SurfacingConstants.NL );
2345 w.write( html_desc.toString() );
2346 w.write( SurfacingConstants.NL );
2348 w.write( SurfacingConstants.NL );
2350 w.write( SurfacingConstants.NL );
2351 w.write( "<table>" );
2352 w.write( SurfacingConstants.NL );
2353 w.write( "<tr><td><b>Domains:</b></td></tr>" );
2354 w.write( SurfacingConstants.NL );
2359 for( final DomainSimilarity similarity : similarities ) {
2360 if ( ( species_order != null ) && !species_order.isEmpty() ) {
2361 ( similarity ).setSpeciesOrder( species_order );
2363 if ( single_writer != null ) {
2364 if ( !ForesterUtil.isEmpty( pos_filter_doms )
2365 && pos_filter_doms.contains( similarity.getDomainId() ) ) {
2366 single_writer.write( "<tr><td><b><a href=\"#" + similarity.getDomainId()
2367 + "\"><span style=\"color:#00ff00\">" + similarity.getDomainId()
2368 + "</span></a></b></td></tr>" );
2371 single_writer.write( "<tr><td><b><a href=\"#" + similarity.getDomainId() + "\">"
2372 + similarity.getDomainId() + "</a></b></td></tr>" );
2374 single_writer.write( SurfacingConstants.NL );
2377 Writer local_writer = split_writers
2378 .get( ( similarity.getDomainId().charAt( 0 ) + "" ).toLowerCase().charAt( 0 ) );
2379 if ( local_writer == null ) {
2380 local_writer = split_writers.get( '0' );
2382 if ( !ForesterUtil.isEmpty( pos_filter_doms )
2383 && pos_filter_doms.contains( similarity.getDomainId() ) ) {
2384 local_writer.write( "<tr><td><b><a href=\"#" + similarity.getDomainId()
2385 + "\"><span style=\"color:#00ff00\">" + similarity.getDomainId()
2386 + "</span></a></b></td></tr>" );
2389 local_writer.write( "<tr><td><b><a href=\"#" + similarity.getDomainId() + "\">"
2390 + similarity.getDomainId() + "</a></b></td></tr>" );
2392 local_writer.write( SurfacingConstants.NL );
2395 for( final Writer w : split_writers.values() ) {
2396 w.write( "</table>" );
2397 w.write( SurfacingConstants.NL );
2399 w.write( SurfacingConstants.NL );
2401 w.write( "<table>" );
2402 w.write( SurfacingConstants.NL );
2403 w.write( "<tr><td><b>" );
2404 w.write( "Species group colors:" );
2405 w.write( "</b></td></tr>" );
2406 w.write( SurfacingConstants.NL );
2407 writeColorLabels( "Deuterostomia", TaxonomyColors.DEUTEROSTOMIA_COLOR, w );
2408 writeColorLabels( "Protostomia", TaxonomyColors.PROTOSTOMIA_COLOR, w );
2409 writeColorLabels( "Cnidaria", TaxonomyColors.CNIDARIA_COLOR, w );
2410 writeColorLabels( "Placozoa", TaxonomyColors.PLACOZOA_COLOR, w );
2411 writeColorLabels( "Ctenophora (comb jellies)", TaxonomyColors.CTENOPHORA_COLOR, w );
2412 writeColorLabels( "Porifera (sponges)", TaxonomyColors.PORIFERA_COLOR, w );
2413 writeColorLabels( "Choanoflagellida", TaxonomyColors.CHOANOFLAGELLIDA, w );
2414 writeColorLabels( "Ichthyosporea & Filasterea", TaxonomyColors.ICHTHYOSPOREA_AND_FILASTEREA, w );
2415 writeColorLabels( "Dikarya (Ascomycota & Basidiomycota, so-called \"higher fungi\")",
2416 TaxonomyColors.DIKARYA_COLOR,
2418 writeColorLabels( "other Fungi", TaxonomyColors.OTHER_FUNGI_COLOR, w );
2419 writeColorLabels( "Nucleariidae and Fonticula group",
2420 TaxonomyColors.NUCLEARIIDAE_AND_FONTICULA_GROUP_COLOR,
2422 writeColorLabels( "Amoebozoa", TaxonomyColors.AMOEBOZOA_COLOR, w );
2423 writeColorLabels( "Embryophyta (plants)", TaxonomyColors.EMBRYOPHYTA_COLOR, w );
2424 writeColorLabels( "Chlorophyta (green algae)", TaxonomyColors.CHLOROPHYTA_COLOR, w );
2425 writeColorLabels( "Rhodophyta (red algae)", TaxonomyColors.RHODOPHYTA_COLOR, w );
2426 writeColorLabels( "Glaucocystophyce (Glaucophyta)", TaxonomyColors.GLAUCOPHYTA_COLOR, w );
2427 writeColorLabels( "Hacrobia (Cryptophyta & Haptophyceae & Centroheliozoa)",
2428 TaxonomyColors.HACROBIA_COLOR,
2430 writeColorLabels( "Stramenopiles (Chromophyta, heterokonts)", TaxonomyColors.STRAMENOPILES_COLOR, w );
2431 writeColorLabels( "Alveolata", TaxonomyColors.ALVEOLATA_COLOR, w );
2432 writeColorLabels( "Rhizaria", TaxonomyColors.RHIZARIA_COLOR, w );
2433 writeColorLabels( "Excavata", TaxonomyColors.EXCAVATA_COLOR, w );
2434 writeColorLabels( "Apusozoa", TaxonomyColors.APUSOZOA_COLOR, w );
2435 writeColorLabels( "Archaea", TaxonomyColors.ARCHAEA_COLOR, w );
2436 writeColorLabels( "Bacteria", TaxonomyColors.BACTERIA_COLOR, w );
2437 w.write( "</table>" );
2438 w.write( SurfacingConstants.NL );
2441 w.write( SurfacingConstants.NL );
2442 w.write( "<table>" );
2443 w.write( SurfacingConstants.NL );
2446 for( final DomainSimilarity similarity : similarities ) {
2447 if ( ( species_order != null ) && !species_order.isEmpty() ) {
2448 ( similarity ).setSpeciesOrder( species_order );
2450 if ( simple_tab_writer != null ) {
2451 simple_tab_writer.write( similarity
2452 .toStringBuffer( PRINT_OPTION.SIMPLE_TAB_DELIMITED, tax_code_to_id_map, null ).toString() );
2454 if ( single_writer != null ) {
2455 single_writer.write( similarity.toStringBuffer( print_option, tax_code_to_id_map, phy ).toString() );
2456 single_writer.write( SurfacingConstants.NL );
2459 Writer local_writer = split_writers
2460 .get( ( similarity.getDomainId().charAt( 0 ) + "" ).toLowerCase().charAt( 0 ) );
2461 if ( local_writer == null ) {
2462 local_writer = split_writers.get( '0' );
2464 local_writer.write( similarity.toStringBuffer( print_option, tax_code_to_id_map, phy ).toString() );
2465 local_writer.write( SurfacingConstants.NL );
2468 switch ( print_option ) {
2470 for( final Writer w : split_writers.values() ) {
2471 w.write( SurfacingConstants.NL );
2472 w.write( "</table>" );
2473 w.write( SurfacingConstants.NL );
2474 w.write( "</font>" );
2475 w.write( SurfacingConstants.NL );
2476 w.write( "</body>" );
2477 w.write( SurfacingConstants.NL );
2478 w.write( "</html>" );
2479 w.write( SurfacingConstants.NL );
2485 for( final Writer w : split_writers.values() ) {
2490 public static void writeHtmlHead( final Writer w, final String title ) throws IOException {
2491 w.write( SurfacingConstants.NL );
2492 w.write( "<head>" );
2493 w.write( "<title>" );
2495 w.write( "</title>" );
2496 w.write( SurfacingConstants.NL );
2497 w.write( "<style>" );
2498 w.write( SurfacingConstants.NL );
2499 w.write( "a:visited { color : #000066; text-decoration : none; }" );
2500 w.write( SurfacingConstants.NL );
2501 w.write( "a:link { color : #000066; text-decoration : none; }" );
2502 w.write( SurfacingConstants.NL );
2503 w.write( "a:active { color : ##000066; text-decoration : none; }" );
2504 w.write( SurfacingConstants.NL );
2505 w.write( "a:hover { color : #FFFFFF; background-color : #000000; text-decoration : none; }" );
2506 w.write( SurfacingConstants.NL );
2508 w.write( "a.pl:visited { color : #505050; text-decoration : none; font-size: 7px;}" );
2509 w.write( SurfacingConstants.NL );
2510 w.write( "a.pl:link { color : #505050; text-decoration : none; font-size: 7px;}" );
2511 w.write( SurfacingConstants.NL );
2512 w.write( "a.pl:active { color : #505050; text-decoration : none; font-size: 7px;}" );
2513 w.write( SurfacingConstants.NL );
2514 w.write( "a.pl:hover { color : #FFFFFF; background-color : #000000; text-decoration : none; font-size: 7px;}" );
2515 w.write( SurfacingConstants.NL );
2517 w.write( "a.ps:visited { color : #707070; text-decoration : none; font-size: 7px;}" );
2518 w.write( SurfacingConstants.NL );
2519 w.write( "a.ps:link { color : #707070; text-decoration : none; font-size: 7px;}" );
2520 w.write( SurfacingConstants.NL );
2521 w.write( "a.ps:active { color : #707070; text-decoration : none; font-size: 7px;}" );
2522 w.write( SurfacingConstants.NL );
2523 w.write( "a.ps:hover { color : #FFFFFF; background-color : #000000; text-decoration : none; font-size: 7px;}" );
2524 w.write( SurfacingConstants.NL );
2526 w.write( "td { text-align: left; vertical-align: top; font-family: Verdana, Arial, Helvetica; font-size: 8pt}" );
2527 w.write( SurfacingConstants.NL );
2528 w.write( "h1 { color : #0000FF; font-family: Verdana, Arial, Helvetica; font-size: 18pt; font-weight: bold }" );
2529 w.write( SurfacingConstants.NL );
2530 w.write( "h2 { color : #0000FF; font-family: Verdana, Arial, Helvetica; font-size: 16pt; font-weight: bold }" );
2531 w.write( SurfacingConstants.NL );
2532 w.write( "</style>" );
2533 w.write( SurfacingConstants.NL );
2534 w.write( "</head>" );
2535 w.write( SurfacingConstants.NL );
2538 public static void writeMatrixToFile( final CharacterStateMatrix<?> matrix,
2539 final String filename,
2540 final Format format ) {
2541 final File outfile = new File( filename );
2542 checkForOutputFileWriteability( outfile );
2544 final BufferedWriter out = new BufferedWriter( new FileWriter( outfile ) );
2545 matrix.toWriter( out, format );
2549 catch ( final IOException e ) {
2550 ForesterUtil.fatalError( surfacing.PRG_NAME, e.getMessage() );
2552 ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote matrix: \"" + filename + "\"" );
2555 public static void writeMatrixToFile( final File matrix_outfile, final List<DistanceMatrix> matrices ) {
2556 checkForOutputFileWriteability( matrix_outfile );
2558 final BufferedWriter out = new BufferedWriter( new FileWriter( matrix_outfile ) );
2559 for( final DistanceMatrix distance_matrix : matrices ) {
2560 out.write( distance_matrix.toStringBuffer( DistanceMatrix.Format.PHYLIP ).toString() );
2561 out.write( ForesterUtil.LINE_SEPARATOR );
2566 catch ( final IOException e ) {
2567 ForesterUtil.fatalError( surfacing.PRG_NAME, e.getMessage() );
2569 ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote distance matrices to \"" + matrix_outfile + "\"" );
2572 public static void writePhylogenyToFile( final Phylogeny phylogeny, final String filename ) {
2573 final PhylogenyWriter writer = new PhylogenyWriter();
2575 writer.toPhyloXML( new File( filename ), phylogeny, 1 );
2577 catch ( final IOException e ) {
2578 ForesterUtil.printWarningMessage( surfacing.PRG_NAME,
2579 "failed to write phylogeny to \"" + filename + "\": " + e );
2581 ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote phylogeny to \"" + filename + "\"" );
2584 public static void writePresentToNexus( final File output_file,
2585 final File positive_filter_file,
2586 final SortedSet<String> filter,
2587 final List<GenomeWideCombinableDomains> gwcd_list ) {
2589 writeMatrixToFile( DomainParsimonyCalculator
2590 .createMatrixOfDomainPresenceOrAbsence( gwcd_list, positive_filter_file == null ? null : filter ),
2591 output_file + surfacing.DOMAINS_PRESENT_NEXUS,
2592 Format.NEXUS_BINARY );
2593 writeMatrixToFile( DomainParsimonyCalculator
2594 .createMatrixOfBinaryDomainCombinationPresenceOrAbsence( gwcd_list ),
2595 output_file + surfacing.BDC_PRESENT_NEXUS,
2596 Format.NEXUS_BINARY );
2598 catch ( final Exception e ) {
2599 ForesterUtil.fatalError( surfacing.PRG_NAME, e.getLocalizedMessage() );
2603 public static void writeProteinListsForAllSpecies( final File output_dir,
2604 final SortedMap<Species, List<Protein>> protein_lists_per_species,
2605 final List<GenomeWideCombinableDomains> gwcd_list,
2606 final double domain_e_cutoff,
2607 final Set<String> pos_filter_doms ) {
2608 final SortedSet<String> all_domains = new TreeSet<String>();
2609 for( final GenomeWideCombinableDomains gwcd : gwcd_list ) {
2610 all_domains.addAll( gwcd.getAllDomainIds() );
2612 for( final String domain : all_domains ) {
2613 if ( !ForesterUtil.isEmpty( pos_filter_doms ) && !pos_filter_doms.contains( domain ) ) {
2616 final File out = new File( output_dir + ForesterUtil.FILE_SEPARATOR + domain
2617 + surfacing.SEQ_EXTRACT_SUFFIX );
2618 checkForOutputFileWriteability( out );
2620 final Writer proteins_file_writer = new BufferedWriter( new FileWriter( out ) );
2621 extractProteinNames( protein_lists_per_species,
2623 proteins_file_writer,
2625 surfacing.LIMIT_SPEC_FOR_PROT_EX,
2627 proteins_file_writer.close();
2629 catch ( final IOException e ) {
2630 ForesterUtil.fatalError( surfacing.PRG_NAME, e.getLocalizedMessage() );
2632 ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote proteins list to \"" + out + "\"" );
2636 public static void writeTaxonomyLinks( final Writer writer,
2637 final String species,
2638 final Map<String, Integer> tax_code_to_id_map )
2639 throws IOException {
2640 if ( ( species.length() > 1 ) && ( species.indexOf( '_' ) < 1 ) ) {
2641 writer.write( " [" );
2642 if ( ( tax_code_to_id_map != null ) && tax_code_to_id_map.containsKey( species ) ) {
2643 writer.write( "<a href=\"" + SurfacingConstants.UNIPROT_TAXONOMY_ID_LINK
2644 + tax_code_to_id_map.get( species ) + "\" target=\"taxonomy_window\">uniprot</a>" );
2647 writer.write( "<a href=\"" + SurfacingConstants.EOL_LINK + species
2648 + "\" target=\"taxonomy_window\">eol</a>" );
2649 writer.write( "|" );
2650 writer.write( "<a href=\"" + SurfacingConstants.GOOGLE_SCHOLAR_SEARCH + species
2651 + "\" target=\"taxonomy_window\">scholar</a>" );
2652 writer.write( "|" );
2653 writer.write( "<a href=\"" + SurfacingConstants.GOOGLE_WEB_SEARCH_LINK + species
2654 + "\" target=\"taxonomy_window\">google</a>" );
2656 writer.write( "]" );
2660 private final static void addToCountMap( final Map<String, Integer> map, final String s ) {
2661 if ( map.containsKey( s ) ) {
2662 map.put( s, map.get( s ) + 1 );
2669 private static void calculateIndependentDomainCombinationGains( final Phylogeny local_phylogeny_l,
2670 final String outfilename_for_counts,
2671 final String outfilename_for_dc,
2672 final String outfilename_for_dc_for_go_mapping,
2673 final String outfilename_for_dc_for_go_mapping_unique,
2674 final String outfilename_for_rank_counts,
2675 final String outfilename_for_ancestor_species_counts,
2676 final String outfilename_for_protein_stats,
2677 final Map<String, DescriptiveStatistics> protein_length_stats_by_dc,
2678 final Map<String, DescriptiveStatistics> domain_number_stats_by_dc,
2679 final Map<String, DescriptiveStatistics> domain_length_stats_by_domain ) {
2682 // if ( protein_length_stats_by_dc != null ) {
2683 // for( final Entry<?, DescriptiveStatistics> entry : protein_length_stats_by_dc.entrySet() ) {
2684 // System.out.print( entry.getKey().toString() );
2685 // System.out.print( ": " );
2686 // double[] a = entry.getValue().getDataAsDoubleArray();
2687 // for( int i = 0; i < a.length; i++ ) {
2688 // System.out.print( a[ i ] + " " );
2690 // System.out.println();
2693 // if ( domain_number_stats_by_dc != null ) {
2694 // for( final Entry<?, DescriptiveStatistics> entry : domain_number_stats_by_dc.entrySet() ) {
2695 // System.out.print( entry.getKey().toString() );
2696 // System.out.print( ": " );
2697 // double[] a = entry.getValue().getDataAsDoubleArray();
2698 // for( int i = 0; i < a.length; i++ ) {
2699 // System.out.print( a[ i ] + " " );
2701 // System.out.println();
2705 final BufferedWriter out_counts = new BufferedWriter( new FileWriter( outfilename_for_counts ) );
2706 final BufferedWriter out_dc = new BufferedWriter( new FileWriter( outfilename_for_dc ) );
2707 final BufferedWriter out_dc_for_go_mapping = new BufferedWriter( new FileWriter( outfilename_for_dc_for_go_mapping ) );
2708 final BufferedWriter out_dc_for_go_mapping_unique = new BufferedWriter( new FileWriter( outfilename_for_dc_for_go_mapping_unique ) );
2709 final SortedMap<String, Integer> dc_gain_counts = new TreeMap<String, Integer>();
2710 for( final PhylogenyNodeIterator it = local_phylogeny_l.iteratorPostorder(); it.hasNext(); ) {
2711 final PhylogenyNode n = it.next();
2712 final Set<String> gained_dc = n.getNodeData().getBinaryCharacters().getGainedCharacters();
2713 for( final String dc : gained_dc ) {
2714 if ( dc_gain_counts.containsKey( dc ) ) {
2715 dc_gain_counts.put( dc, dc_gain_counts.get( dc ) + 1 );
2718 dc_gain_counts.put( dc, 1 );
2722 final SortedMap<Integer, Integer> histogram = new TreeMap<Integer, Integer>();
2723 final SortedMap<Integer, StringBuilder> domain_lists = new TreeMap<Integer, StringBuilder>();
2724 final SortedMap<Integer, DescriptiveStatistics> dc_reapp_counts_to_protein_length_stats = new TreeMap<Integer, DescriptiveStatistics>();
2725 final SortedMap<Integer, DescriptiveStatistics> dc_reapp_counts_to_domain_number_stats = new TreeMap<Integer, DescriptiveStatistics>();
2726 final SortedMap<Integer, DescriptiveStatistics> dc_reapp_counts_to_domain_lengths_stats = new TreeMap<Integer, DescriptiveStatistics>();
2727 final SortedMap<Integer, PriorityQueue<String>> domain_lists_go = new TreeMap<Integer, PriorityQueue<String>>();
2728 final SortedMap<Integer, SortedSet<String>> domain_lists_go_unique = new TreeMap<Integer, SortedSet<String>>();
2729 final Set<String> dcs = dc_gain_counts.keySet();
2730 final SortedSet<String> more_than_once = new TreeSet<String>();
2731 DescriptiveStatistics gained_once_lengths_stats = new BasicDescriptiveStatistics();
2732 DescriptiveStatistics gained_once_domain_count_stats = new BasicDescriptiveStatistics();
2733 DescriptiveStatistics gained_multiple_times_lengths_stats = new BasicDescriptiveStatistics();
2734 final DescriptiveStatistics gained_multiple_times_domain_count_stats = new BasicDescriptiveStatistics();
2735 long gained_multiple_times_domain_length_sum = 0;
2736 long gained_once_domain_length_sum = 0;
2737 long gained_multiple_times_domain_length_count = 0;
2738 long gained_once_domain_length_count = 0;
2739 for( final String dc : dcs ) {
2740 final int count = dc_gain_counts.get( dc );
2741 if ( histogram.containsKey( count ) ) {
2742 histogram.put( count, histogram.get( count ) + 1 );
2743 domain_lists.get( count ).append( ", " + dc );
2744 domain_lists_go.get( count ).addAll( splitDomainCombination( dc ) );
2745 domain_lists_go_unique.get( count ).addAll( splitDomainCombination( dc ) );
2748 histogram.put( count, 1 );
2749 domain_lists.put( count, new StringBuilder( dc ) );
2750 final PriorityQueue<String> q = new PriorityQueue<String>();
2751 q.addAll( splitDomainCombination( dc ) );
2752 domain_lists_go.put( count, q );
2753 final SortedSet<String> set = new TreeSet<String>();
2754 set.addAll( splitDomainCombination( dc ) );
2755 domain_lists_go_unique.put( count, set );
2757 if ( protein_length_stats_by_dc != null ) {
2758 if ( !dc_reapp_counts_to_protein_length_stats.containsKey( count ) ) {
2759 dc_reapp_counts_to_protein_length_stats.put( count, new BasicDescriptiveStatistics() );
2761 dc_reapp_counts_to_protein_length_stats.get( count )
2762 .addValue( protein_length_stats_by_dc.get( dc ).arithmeticMean() );
2764 if ( domain_number_stats_by_dc != null ) {
2765 if ( !dc_reapp_counts_to_domain_number_stats.containsKey( count ) ) {
2766 dc_reapp_counts_to_domain_number_stats.put( count, new BasicDescriptiveStatistics() );
2768 dc_reapp_counts_to_domain_number_stats.get( count )
2769 .addValue( domain_number_stats_by_dc.get( dc ).arithmeticMean() );
2771 if ( domain_length_stats_by_domain != null ) {
2772 if ( !dc_reapp_counts_to_domain_lengths_stats.containsKey( count ) ) {
2773 dc_reapp_counts_to_domain_lengths_stats.put( count, new BasicDescriptiveStatistics() );
2775 final String[] ds = dc.split( "=" );
2776 dc_reapp_counts_to_domain_lengths_stats.get( count )
2777 .addValue( domain_length_stats_by_domain.get( ds[ 0 ] ).arithmeticMean() );
2778 dc_reapp_counts_to_domain_lengths_stats.get( count )
2779 .addValue( domain_length_stats_by_domain.get( ds[ 1 ] ).arithmeticMean() );
2782 more_than_once.add( dc );
2783 if ( protein_length_stats_by_dc != null ) {
2784 final DescriptiveStatistics s = protein_length_stats_by_dc.get( dc );
2785 for( final double element : s.getData() ) {
2786 gained_multiple_times_lengths_stats.addValue( element );
2789 if ( domain_number_stats_by_dc != null ) {
2790 final DescriptiveStatistics s = domain_number_stats_by_dc.get( dc );
2791 for( final double element : s.getData() ) {
2792 gained_multiple_times_domain_count_stats.addValue( element );
2795 if ( domain_length_stats_by_domain != null ) {
2796 final String[] ds = dc.split( "=" );
2797 final DescriptiveStatistics s0 = domain_length_stats_by_domain.get( ds[ 0 ] );
2798 final DescriptiveStatistics s1 = domain_length_stats_by_domain.get( ds[ 1 ] );
2799 for( final double element : s0.getData() ) {
2800 gained_multiple_times_domain_length_sum += element;
2801 ++gained_multiple_times_domain_length_count;
2803 for( final double element : s1.getData() ) {
2804 gained_multiple_times_domain_length_sum += element;
2805 ++gained_multiple_times_domain_length_count;
2810 if ( protein_length_stats_by_dc != null ) {
2811 final DescriptiveStatistics s = protein_length_stats_by_dc.get( dc );
2812 for( final double element : s.getData() ) {
2813 gained_once_lengths_stats.addValue( element );
2816 if ( domain_number_stats_by_dc != null ) {
2817 final DescriptiveStatistics s = domain_number_stats_by_dc.get( dc );
2818 for( final double element : s.getData() ) {
2819 gained_once_domain_count_stats.addValue( element );
2822 if ( domain_length_stats_by_domain != null ) {
2823 final String[] ds = dc.split( "=" );
2824 final DescriptiveStatistics s0 = domain_length_stats_by_domain.get( ds[ 0 ] );
2825 final DescriptiveStatistics s1 = domain_length_stats_by_domain.get( ds[ 1 ] );
2826 for( final double element : s0.getData() ) {
2827 gained_once_domain_length_sum += element;
2828 ++gained_once_domain_length_count;
2830 for( final double element : s1.getData() ) {
2831 gained_once_domain_length_sum += element;
2832 ++gained_once_domain_length_count;
2837 final Set<Integer> histogram_keys = histogram.keySet();
2838 for( final Integer histogram_key : histogram_keys ) {
2839 final int count = histogram.get( histogram_key );
2840 final StringBuilder dc = domain_lists.get( histogram_key );
2841 out_counts.write( histogram_key + "\t" + count + ForesterUtil.LINE_SEPARATOR );
2842 out_dc.write( histogram_key + "\t" + dc + ForesterUtil.LINE_SEPARATOR );
2843 out_dc_for_go_mapping.write( "#" + histogram_key + ForesterUtil.LINE_SEPARATOR );
2844 final Object[] sorted = domain_lists_go.get( histogram_key ).toArray();
2845 Arrays.sort( sorted );
2846 for( final Object domain : sorted ) {
2847 out_dc_for_go_mapping.write( domain + ForesterUtil.LINE_SEPARATOR );
2849 out_dc_for_go_mapping_unique.write( "#" + histogram_key + ForesterUtil.LINE_SEPARATOR );
2850 for( final String domain : domain_lists_go_unique.get( histogram_key ) ) {
2851 out_dc_for_go_mapping_unique.write( domain + ForesterUtil.LINE_SEPARATOR );
2856 out_dc_for_go_mapping.close();
2857 out_dc_for_go_mapping_unique.close();
2858 final SortedMap<String, Integer> lca_rank_counts = new TreeMap<String, Integer>();
2859 final SortedMap<String, Integer> lca_ancestor_species_counts = new TreeMap<String, Integer>();
2860 for( final String dc : more_than_once ) {
2861 final List<PhylogenyNode> nodes = new ArrayList<PhylogenyNode>();
2862 for( final PhylogenyNodeIterator it = local_phylogeny_l.iteratorExternalForward(); it.hasNext(); ) {
2863 final PhylogenyNode n = it.next();
2864 if ( n.getNodeData().getBinaryCharacters().getGainedCharacters().contains( dc ) ) {
2868 for( int i = 0; i < ( nodes.size() - 1 ); ++i ) {
2869 for( int j = i + 1; j < nodes.size(); ++j ) {
2870 final PhylogenyNode lca = PhylogenyMethods.calculateLCA( nodes.get( i ), nodes.get( j ) );
2871 String rank = "unknown";
2872 if ( lca.getNodeData().isHasTaxonomy()
2873 && !ForesterUtil.isEmpty( lca.getNodeData().getTaxonomy().getRank() ) ) {
2874 rank = lca.getNodeData().getTaxonomy().getRank();
2876 addToCountMap( lca_rank_counts, rank );
2878 if ( lca.getNodeData().isHasTaxonomy()
2879 && !ForesterUtil.isEmpty( lca.getNodeData().getTaxonomy().getScientificName() ) ) {
2880 lca_species = lca.getNodeData().getTaxonomy().getScientificName();
2882 else if ( lca.getNodeData().isHasTaxonomy()
2883 && !ForesterUtil.isEmpty( lca.getNodeData().getTaxonomy().getCommonName() ) ) {
2884 lca_species = lca.getNodeData().getTaxonomy().getCommonName();
2887 lca_species = lca.getName();
2889 addToCountMap( lca_ancestor_species_counts, lca_species );
2893 final BufferedWriter out_for_rank_counts = new BufferedWriter( new FileWriter( outfilename_for_rank_counts ) );
2894 final BufferedWriter out_for_ancestor_species_counts = new BufferedWriter( new FileWriter( outfilename_for_ancestor_species_counts ) );
2895 ForesterUtil.map2writer( out_for_rank_counts, lca_rank_counts, "\t", ForesterUtil.LINE_SEPARATOR );
2896 ForesterUtil.map2writer( out_for_ancestor_species_counts,
2897 lca_ancestor_species_counts,
2899 ForesterUtil.LINE_SEPARATOR );
2900 out_for_rank_counts.close();
2901 out_for_ancestor_species_counts.close();
2902 if ( !ForesterUtil.isEmpty( outfilename_for_protein_stats ) && ( ( domain_length_stats_by_domain != null )
2903 || ( protein_length_stats_by_dc != null ) || ( domain_number_stats_by_dc != null ) ) ) {
2904 final BufferedWriter w = new BufferedWriter( new FileWriter( outfilename_for_protein_stats ) );
2905 w.write( "Domain Lengths: " );
2907 if ( domain_length_stats_by_domain != null ) {
2908 for( final Entry<Integer, DescriptiveStatistics> entry : dc_reapp_counts_to_domain_lengths_stats
2910 w.write( entry.getKey().toString() );
2911 w.write( "\t" + entry.getValue().arithmeticMean() );
2912 w.write( "\t" + entry.getValue().median() );
2919 w.write( "Protein Lengths: " );
2921 if ( protein_length_stats_by_dc != null ) {
2922 for( final Entry<Integer, DescriptiveStatistics> entry : dc_reapp_counts_to_protein_length_stats
2924 w.write( entry.getKey().toString() );
2925 w.write( "\t" + entry.getValue().arithmeticMean() );
2926 w.write( "\t" + entry.getValue().median() );
2933 w.write( "Number of domains: " );
2935 if ( domain_number_stats_by_dc != null ) {
2936 for( final Entry<Integer, DescriptiveStatistics> entry : dc_reapp_counts_to_domain_number_stats
2938 w.write( entry.getKey().toString() );
2939 w.write( "\t" + entry.getValue().arithmeticMean() );
2940 w.write( "\t" + entry.getValue().median() );
2947 w.write( "Gained once, domain lengths:" );
2949 w.write( "N: " + gained_once_domain_length_count );
2951 w.write( "Avg: " + ( ( double ) gained_once_domain_length_sum / gained_once_domain_length_count ) );
2954 w.write( "Gained multiple times, domain lengths:" );
2956 w.write( "N: " + gained_multiple_times_domain_length_count );
2958 w.write( "Avg: " + ( ( double ) gained_multiple_times_domain_length_sum
2959 / gained_multiple_times_domain_length_count ) );
2964 w.write( "Gained once, protein lengths:" );
2966 w.write( gained_once_lengths_stats.toString() );
2967 gained_once_lengths_stats = null;
2970 w.write( "Gained once, domain counts:" );
2972 w.write( gained_once_domain_count_stats.toString() );
2973 gained_once_domain_count_stats = null;
2976 w.write( "Gained multiple times, protein lengths:" );
2978 w.write( gained_multiple_times_lengths_stats.toString() );
2979 gained_multiple_times_lengths_stats = null;
2982 w.write( "Gained multiple times, domain counts:" );
2984 w.write( gained_multiple_times_domain_count_stats.toString() );
2989 catch ( final IOException e ) {
2990 ForesterUtil.printWarningMessage( surfacing.PRG_NAME, "Failure to write: " + e );
2992 ForesterUtil.programMessage( surfacing.PRG_NAME,
2993 "Wrote independent domain combination gains fitch counts to ["
2994 + outfilename_for_counts + "]" );
2995 ForesterUtil.programMessage( surfacing.PRG_NAME,
2996 "Wrote independent domain combination gains fitch lists to [" + outfilename_for_dc
2998 ForesterUtil.programMessage( surfacing.PRG_NAME,
2999 "Wrote independent domain combination gains fitch lists to (for GO mapping) ["
3000 + outfilename_for_dc_for_go_mapping + "]" );
3001 ForesterUtil.programMessage( surfacing.PRG_NAME,
3002 "Wrote independent domain combination gains fitch lists to (for GO mapping, unique) ["
3003 + outfilename_for_dc_for_go_mapping_unique + "]" );
3006 private static SortedSet<String> collectAllDomainsChangedOnSubtree( final PhylogenyNode subtree_root,
3007 final boolean get_gains ) {
3008 final SortedSet<String> domains = new TreeSet<String>();
3009 for( final PhylogenyNode descendant : PhylogenyMethods.getAllDescendants( subtree_root ) ) {
3010 final BinaryCharacters chars = descendant.getNodeData().getBinaryCharacters();
3012 domains.addAll( chars.getGainedCharacters() );
3015 domains.addAll( chars.getLostCharacters() );
3021 private static File createBaseDirForPerNodeDomainFiles( final String base_dir,
3022 final boolean domain_combinations,
3023 final CharacterStateMatrix.GainLossStates state,
3024 final String outfile ) {
3025 File per_node_go_mapped_domain_gain_loss_files_base_dir = new File( new File( outfile ).getParent()
3026 + ForesterUtil.FILE_SEPARATOR + base_dir );
3027 if ( !per_node_go_mapped_domain_gain_loss_files_base_dir.exists() ) {
3028 per_node_go_mapped_domain_gain_loss_files_base_dir.mkdir();
3030 if ( domain_combinations ) {
3031 per_node_go_mapped_domain_gain_loss_files_base_dir = new File( per_node_go_mapped_domain_gain_loss_files_base_dir
3032 + ForesterUtil.FILE_SEPARATOR + "DC" );
3035 per_node_go_mapped_domain_gain_loss_files_base_dir = new File( per_node_go_mapped_domain_gain_loss_files_base_dir
3036 + ForesterUtil.FILE_SEPARATOR + "DOMAINS" );
3038 if ( !per_node_go_mapped_domain_gain_loss_files_base_dir.exists() ) {
3039 per_node_go_mapped_domain_gain_loss_files_base_dir.mkdir();
3041 if ( state == GainLossStates.GAIN ) {
3042 per_node_go_mapped_domain_gain_loss_files_base_dir = new File( per_node_go_mapped_domain_gain_loss_files_base_dir
3043 + ForesterUtil.FILE_SEPARATOR + "GAINS" );
3045 else if ( state == GainLossStates.LOSS ) {
3046 per_node_go_mapped_domain_gain_loss_files_base_dir = new File( per_node_go_mapped_domain_gain_loss_files_base_dir
3047 + ForesterUtil.FILE_SEPARATOR + "LOSSES" );
3050 per_node_go_mapped_domain_gain_loss_files_base_dir = new File( per_node_go_mapped_domain_gain_loss_files_base_dir
3051 + ForesterUtil.FILE_SEPARATOR + "PRESENT" );
3053 if ( !per_node_go_mapped_domain_gain_loss_files_base_dir.exists() ) {
3054 per_node_go_mapped_domain_gain_loss_files_base_dir.mkdir();
3056 return per_node_go_mapped_domain_gain_loss_files_base_dir;
3059 private static SortedSet<BinaryDomainCombination> createSetOfAllBinaryDomainCombinationsPerGenome( final GenomeWideCombinableDomains gwcd ) {
3060 final SortedMap<String, CombinableDomains> cds = gwcd.getAllCombinableDomainsIds();
3061 final SortedSet<BinaryDomainCombination> binary_combinations = new TreeSet<BinaryDomainCombination>();
3062 for( final String domain_id : cds.keySet() ) {
3063 final CombinableDomains cd = cds.get( domain_id );
3064 binary_combinations.addAll( cd.toBinaryDomainCombinations() );
3066 return binary_combinations;
3069 private static void printSomeStats( final DescriptiveStatistics stats, final AsciiHistogram histo, final Writer w )
3070 throws IOException {
3073 w.write( SurfacingConstants.NL );
3074 w.write( "<tt><pre>" );
3075 w.write( SurfacingConstants.NL );
3076 if ( histo != null ) {
3077 w.write( histo.toStringBuffer( 20, '|', 40, 5 ).toString() );
3078 w.write( SurfacingConstants.NL );
3080 w.write( "</pre></tt>" );
3081 w.write( SurfacingConstants.NL );
3082 w.write( "<table>" );
3083 w.write( SurfacingConstants.NL );
3084 w.write( "<tr><td>N: </td><td>" + stats.getN() + "</td></tr>" );
3085 w.write( SurfacingConstants.NL );
3086 w.write( "<tr><td>Min: </td><td>" + stats.getMin() + "</td></tr>" );
3087 w.write( SurfacingConstants.NL );
3088 w.write( "<tr><td>Max: </td><td>" + stats.getMax() + "</td></tr>" );
3089 w.write( SurfacingConstants.NL );
3090 w.write( "<tr><td>Mean: </td><td>" + stats.arithmeticMean() + "</td></tr>" );
3091 w.write( SurfacingConstants.NL );
3092 if ( stats.getN() > 1 ) {
3093 w.write( "<tr><td>SD: </td><td>" + stats.sampleStandardDeviation() + "</td></tr>" );
3096 w.write( "<tr><td>SD: </td><td>n/a</td></tr>" );
3098 w.write( SurfacingConstants.NL );
3099 w.write( "</table>" );
3100 w.write( SurfacingConstants.NL );
3102 w.write( SurfacingConstants.NL );
3105 private static List<String> splitDomainCombination( final String dc ) {
3106 final String[] s = dc.split( "=" );
3107 if ( s.length != 2 ) {
3108 ForesterUtil.printErrorMessage( surfacing.PRG_NAME,
3109 "Stringyfied domain combination has illegal format: " + dc );
3112 final List<String> l = new ArrayList<String>( 2 );
3118 private static void writeAllEncounteredPfamsToFile( final Map<String, List<GoId>> domain_id_to_go_ids_map,
3119 final Map<GoId, GoTerm> go_id_to_term_map,
3120 final String outfile_name,
3121 final SortedSet<String> all_pfams_encountered ) {
3122 final File all_pfams_encountered_file = new File( outfile_name + surfacing.ALL_PFAMS_ENCOUNTERED_SUFFIX );
3123 final File all_pfams_encountered_with_go_annotation_file = new File( outfile_name
3124 + surfacing.ALL_PFAMS_ENCOUNTERED_WITH_GO_ANNOTATION_SUFFIX );
3125 final File encountered_pfams_summary_file = new File( outfile_name
3126 + surfacing.ENCOUNTERED_PFAMS_SUMMARY_SUFFIX );
3127 int biological_process_counter = 0;
3128 int cellular_component_counter = 0;
3129 int molecular_function_counter = 0;
3130 int pfams_with_mappings_counter = 0;
3131 int pfams_without_mappings_counter = 0;
3132 int pfams_without_mappings_to_bp_or_mf_counter = 0;
3133 int pfams_with_mappings_to_bp_or_mf_counter = 0;
3135 final Writer all_pfams_encountered_writer = new BufferedWriter( new FileWriter( all_pfams_encountered_file ) );
3136 final Writer all_pfams_encountered_with_go_annotation_writer = new BufferedWriter( new FileWriter( all_pfams_encountered_with_go_annotation_file ) );
3137 final Writer summary_writer = new BufferedWriter( new FileWriter( encountered_pfams_summary_file ) );
3138 summary_writer.write( "# Pfam to GO mapping summary" );
3139 summary_writer.write( ForesterUtil.LINE_SEPARATOR );
3140 summary_writer.write( "# Actual summary is at the end of this file." );
3141 summary_writer.write( ForesterUtil.LINE_SEPARATOR );
3142 summary_writer.write( "# Encountered Pfams without a GO mapping:" );
3143 summary_writer.write( ForesterUtil.LINE_SEPARATOR );
3144 for( final String pfam : all_pfams_encountered ) {
3145 all_pfams_encountered_writer.write( pfam );
3146 all_pfams_encountered_writer.write( ForesterUtil.LINE_SEPARATOR );
3147 final String domain_id = new String( pfam );
3148 if ( domain_id_to_go_ids_map.containsKey( domain_id ) ) {
3149 ++pfams_with_mappings_counter;
3150 all_pfams_encountered_with_go_annotation_writer.write( pfam );
3151 all_pfams_encountered_with_go_annotation_writer.write( ForesterUtil.LINE_SEPARATOR );
3152 final List<GoId> go_ids = domain_id_to_go_ids_map.get( domain_id );
3153 boolean maps_to_bp = false;
3154 boolean maps_to_cc = false;
3155 boolean maps_to_mf = false;
3156 for( final GoId go_id : go_ids ) {
3157 final GoTerm go_term = go_id_to_term_map.get( go_id );
3158 if ( go_term.getGoNameSpace().isBiologicalProcess() ) {
3161 else if ( go_term.getGoNameSpace().isCellularComponent() ) {
3164 else if ( go_term.getGoNameSpace().isMolecularFunction() ) {
3169 ++biological_process_counter;
3172 ++cellular_component_counter;
3175 ++molecular_function_counter;
3177 if ( maps_to_bp || maps_to_mf ) {
3178 ++pfams_with_mappings_to_bp_or_mf_counter;
3181 ++pfams_without_mappings_to_bp_or_mf_counter;
3185 ++pfams_without_mappings_to_bp_or_mf_counter;
3186 ++pfams_without_mappings_counter;
3187 summary_writer.write( pfam );
3188 summary_writer.write( ForesterUtil.LINE_SEPARATOR );
3191 all_pfams_encountered_writer.close();
3192 all_pfams_encountered_with_go_annotation_writer.close();
3193 ForesterUtil.programMessage( surfacing.PRG_NAME,
3194 "Wrote all [" + all_pfams_encountered.size() + "] encountered Pfams to: \""
3195 + all_pfams_encountered_file + "\"" );
3196 ForesterUtil.programMessage( surfacing.PRG_NAME,
3197 "Wrote all [" + pfams_with_mappings_counter
3198 + "] encountered Pfams with GO mappings to: \""
3199 + all_pfams_encountered_with_go_annotation_file + "\"" );
3200 ForesterUtil.programMessage( surfacing.PRG_NAME,
3201 "Wrote summary (including all [" + pfams_without_mappings_counter
3202 + "] encountered Pfams without GO mappings) to: \""
3203 + encountered_pfams_summary_file + "\"" );
3204 ForesterUtil.programMessage( surfacing.PRG_NAME,
3205 "Sum of Pfams encountered : " + all_pfams_encountered.size() );
3206 ForesterUtil.programMessage( surfacing.PRG_NAME,
3207 "Pfams without a mapping : " + pfams_without_mappings_counter
3208 + " [" + ( ( 100 * pfams_without_mappings_counter )
3209 / all_pfams_encountered.size() )
3211 ForesterUtil.programMessage( surfacing.PRG_NAME,
3212 "Pfams without mapping to proc. or func. : "
3213 + pfams_without_mappings_to_bp_or_mf_counter + " ["
3214 + ( ( 100 * pfams_without_mappings_to_bp_or_mf_counter )
3215 / all_pfams_encountered.size() )
3218 .programMessage( surfacing.PRG_NAME,
3219 "Pfams with a mapping : " + pfams_with_mappings_counter + " ["
3220 + ( ( 100 * pfams_with_mappings_counter ) / all_pfams_encountered.size() )
3222 ForesterUtil.programMessage( surfacing.PRG_NAME,
3223 "Pfams with a mapping to proc. or func. : "
3224 + pfams_with_mappings_to_bp_or_mf_counter + " ["
3225 + ( ( 100 * pfams_with_mappings_to_bp_or_mf_counter )
3226 / all_pfams_encountered.size() )
3229 .programMessage( surfacing.PRG_NAME,
3230 "Pfams with mapping to biological process: " + biological_process_counter + " ["
3231 + ( ( 100 * biological_process_counter ) / all_pfams_encountered.size() )
3234 .programMessage( surfacing.PRG_NAME,
3235 "Pfams with mapping to molecular function: " + molecular_function_counter + " ["
3236 + ( ( 100 * molecular_function_counter ) / all_pfams_encountered.size() )
3239 .programMessage( surfacing.PRG_NAME,
3240 "Pfams with mapping to cellular component: " + cellular_component_counter + " ["
3241 + ( ( 100 * cellular_component_counter ) / all_pfams_encountered.size() )
3243 summary_writer.write( ForesterUtil.LINE_SEPARATOR );
3244 summary_writer.write( "# Sum of Pfams encountered : " + all_pfams_encountered.size() );
3245 summary_writer.write( ForesterUtil.LINE_SEPARATOR );
3246 summary_writer.write( "# Pfams without a mapping : " + pfams_without_mappings_counter + " ["
3247 + ( ( 100 * pfams_without_mappings_counter ) / all_pfams_encountered.size() ) + "%]" );
3248 summary_writer.write( ForesterUtil.LINE_SEPARATOR );
3249 summary_writer.write( "# Pfams without mapping to proc. or func. : "
3250 + pfams_without_mappings_to_bp_or_mf_counter + " ["
3251 + ( ( 100 * pfams_without_mappings_to_bp_or_mf_counter ) / all_pfams_encountered.size() ) + "%]" );
3252 summary_writer.write( ForesterUtil.LINE_SEPARATOR );
3253 summary_writer.write( "# Pfams with a mapping : " + pfams_with_mappings_counter + " ["
3254 + ( ( 100 * pfams_with_mappings_counter ) / all_pfams_encountered.size() ) + "%]" );
3255 summary_writer.write( ForesterUtil.LINE_SEPARATOR );
3256 summary_writer.write( "# Pfams with a mapping to proc. or func. : "
3257 + pfams_with_mappings_to_bp_or_mf_counter + " ["
3258 + ( ( 100 * pfams_with_mappings_to_bp_or_mf_counter ) / all_pfams_encountered.size() ) + "%]" );
3259 summary_writer.write( ForesterUtil.LINE_SEPARATOR );
3260 summary_writer.write( "# Pfams with mapping to biological process: " + biological_process_counter + " ["
3261 + ( ( 100 * biological_process_counter ) / all_pfams_encountered.size() ) + "%]" );
3262 summary_writer.write( ForesterUtil.LINE_SEPARATOR );
3263 summary_writer.write( "# Pfams with mapping to molecular function: " + molecular_function_counter + " ["
3264 + ( ( 100 * molecular_function_counter ) / all_pfams_encountered.size() ) + "%]" );
3265 summary_writer.write( ForesterUtil.LINE_SEPARATOR );
3266 summary_writer.write( "# Pfams with mapping to cellular component: " + cellular_component_counter + " ["
3267 + ( ( 100 * cellular_component_counter ) / all_pfams_encountered.size() ) + "%]" );
3268 summary_writer.write( ForesterUtil.LINE_SEPARATOR );
3269 summary_writer.close();
3271 catch ( final IOException e ) {
3272 ForesterUtil.printWarningMessage( surfacing.PRG_NAME, "Failure to write: " + e );
3276 private final static void writeColorLabels( final String l, final Color c, final Writer w ) throws IOException {
3277 w.write( "<tr><td><b><span style=\"color:" );
3278 w.write( String.format( "#%02x%02x%02x", c.getRed(), c.getGreen(), c.getBlue() ) );
3281 w.write( "</span></b></td></tr>" );
3282 w.write( SurfacingConstants.NL );
3285 private static void writeDomainData( final Map<String, List<GoId>> domain_id_to_go_ids_map,
3286 final Map<GoId, GoTerm> go_id_to_term_map,
3287 final GoNameSpace go_namespace_limit,
3289 final String domain_0,
3290 final String domain_1,
3291 final String prefix_for_html,
3292 final String character_separator_for_non_html_output,
3293 final Map<String, Set<String>>[] domain_id_to_secondary_features_maps,
3294 final Set<GoId> all_go_ids )
3295 throws IOException {
3296 boolean any_go_annotation_present = false;
3297 boolean first_has_no_go = false;
3298 int domain_count = 2; // To distinguish between domains and binary domain combinations.
3299 if ( ForesterUtil.isEmpty( domain_1 ) ) {
3302 // The following has a difficult to understand logic.
3303 for( int d = 0; d < domain_count; ++d ) {
3304 List<GoId> go_ids = null;
3305 boolean go_annotation_present = false;
3307 if ( domain_id_to_go_ids_map.containsKey( domain_0 ) ) {
3308 go_annotation_present = true;
3309 any_go_annotation_present = true;
3310 go_ids = domain_id_to_go_ids_map.get( domain_0 );
3313 first_has_no_go = true;
3317 if ( domain_id_to_go_ids_map.containsKey( domain_1 ) ) {
3318 go_annotation_present = true;
3319 any_go_annotation_present = true;
3320 go_ids = domain_id_to_go_ids_map.get( domain_1 );
3323 if ( go_annotation_present ) {
3324 boolean first = ( ( d == 0 ) || ( ( d == 1 ) && first_has_no_go ) );
3325 for( final GoId go_id : go_ids ) {
3326 out.write( "<tr>" );
3329 writeDomainIdsToHtml( out,
3333 domain_id_to_secondary_features_maps );
3336 out.write( "<td></td>" );
3338 if ( !go_id_to_term_map.containsKey( go_id ) ) {
3339 throw new IllegalArgumentException( "GO-id [" + go_id + "] not found in GO-id to GO-term map" );
3341 final GoTerm go_term = go_id_to_term_map.get( go_id );
3342 if ( ( go_namespace_limit == null ) || go_namespace_limit.equals( go_term.getGoNameSpace() ) ) {
3343 // final String top = GoUtils.getPenultimateGoTerm( go_term, go_id_to_term_map ).getName();
3344 final String go_id_str = go_id.getId();
3345 out.write( "<td>" );
3346 out.write( "<a href=\"" + SurfacingConstants.AMIGO_LINK + go_id_str
3347 + "\" target=\"amigo_window\">" + go_id_str + "</a>" );
3348 out.write( "</td><td>" );
3349 out.write( go_term.getName() );
3350 if ( domain_count == 2 ) {
3351 out.write( " (" + d + ")" );
3353 out.write( "</td><td>" );
3354 // out.write( top );
3355 // out.write( "</td><td>" );
3357 out.write( go_term.getGoNameSpace().toShortString() );
3359 out.write( "</td>" );
3360 if ( all_go_ids != null ) {
3361 all_go_ids.add( go_id );
3365 out.write( "<td>" );
3366 out.write( "</td><td>" );
3367 out.write( "</td><td>" );
3368 out.write( "</td><td>" );
3369 out.write( "</td>" );
3371 out.write( "</tr>" );
3372 out.write( SurfacingConstants.NL );
3375 } // for( int d = 0; d < domain_count; ++d )
3376 if ( !any_go_annotation_present ) {
3377 out.write( "<tr>" );
3378 writeDomainIdsToHtml( out, domain_0, domain_1, prefix_for_html, domain_id_to_secondary_features_maps );
3379 out.write( "<td>" );
3380 out.write( "</td><td>" );
3381 out.write( "</td><td>" );
3382 out.write( "</td><td>" );
3383 out.write( "</td>" );
3384 out.write( "</tr>" );
3385 out.write( SurfacingConstants.NL );
3389 private static void writeDomainIdsToHtml( final Writer out,
3390 final String domain_0,
3391 final String domain_1,
3392 final String prefix_for_detailed_html,
3393 final Map<String, Set<String>>[] domain_id_to_secondary_features_maps )
3394 throws IOException {
3395 out.write( "<td>" );
3396 if ( !ForesterUtil.isEmpty( prefix_for_detailed_html ) ) {
3397 out.write( prefix_for_detailed_html );
3400 out.write( "<a href=\"" + SurfacingConstants.PFAM_FAMILY_ID_LINK + domain_0 + "\">" + domain_0 + "</a>" );
3401 out.write( "</td>" );
3404 private static void writeDomainsToIndividualFilePerTreeNode( final Writer individual_files_writer,
3405 final String domain_0,
3406 final String domain_1 )
3407 throws IOException {
3408 individual_files_writer.write( domain_0 );
3409 individual_files_writer.write( ForesterUtil.LINE_SEPARATOR );
3410 if ( !ForesterUtil.isEmpty( domain_1 ) ) {
3411 individual_files_writer.write( domain_1 );
3412 individual_files_writer.write( ForesterUtil.LINE_SEPARATOR );
3416 private static void writePfamsToFile( final String outfile_name, final SortedSet<String> pfams ) {
3418 final Writer writer = new BufferedWriter( new FileWriter( new File( outfile_name ) ) );
3419 for( final String pfam : pfams ) {
3420 writer.write( pfam );
3421 writer.write( ForesterUtil.LINE_SEPARATOR );
3424 ForesterUtil.programMessage( surfacing.PRG_NAME,
3425 "Wrote " + pfams.size() + " pfams to [" + outfile_name + "]" );
3427 catch ( final IOException e ) {
3428 ForesterUtil.printWarningMessage( surfacing.PRG_NAME, "Failure to write: " + e );
3432 private static void writeToNexus( final String outfile_name,
3433 final CharacterStateMatrix<BinaryStates> matrix,
3434 final Phylogeny phylogeny ) {
3435 if ( !( matrix instanceof BasicCharacterStateMatrix ) ) {
3436 throw new IllegalArgumentException( "can only write matrices of type [" + BasicCharacterStateMatrix.class
3439 final BasicCharacterStateMatrix<BinaryStates> my_matrix = ( org.forester.evoinference.matrix.character.BasicCharacterStateMatrix<BinaryStates> ) matrix;
3440 final List<Phylogeny> phylogenies = new ArrayList<Phylogeny>( 1 );
3441 phylogenies.add( phylogeny );
3443 final BufferedWriter w = new BufferedWriter( new FileWriter( outfile_name ) );
3444 w.write( NexusConstants.NEXUS );
3445 w.write( ForesterUtil.LINE_SEPARATOR );
3446 my_matrix.writeNexusTaxaBlock( w );
3447 my_matrix.writeNexusBinaryChractersBlock( w );
3448 PhylogenyWriter.writeNexusTreesBlock( w, phylogenies, NH_CONVERSION_SUPPORT_VALUE_STYLE.NONE );
3451 ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote Nexus file: \"" + outfile_name + "\"" );
3453 catch ( final IOException e ) {
3454 ForesterUtil.fatalError( surfacing.PRG_NAME, e.getMessage() );
3458 private static void writeToNexus( final String outfile_name,
3459 final DomainParsimonyCalculator domain_parsimony,
3460 final Phylogeny phylogeny ) {
3461 writeToNexus( outfile_name + surfacing.NEXUS_EXTERNAL_DOMAINS,
3462 domain_parsimony.createMatrixOfDomainPresenceOrAbsence(),
3464 writeToNexus( outfile_name + surfacing.NEXUS_EXTERNAL_DOMAIN_COMBINATIONS,
3465 domain_parsimony.createMatrixOfBinaryDomainCombinationPresenceOrAbsence(),
3469 final static class DomainComparator implements Comparator<Domain> {
3471 final private boolean _ascending;
3473 public DomainComparator( final boolean ascending ) {
3474 _ascending = ascending;
3478 public final int compare( final Domain d0, final Domain d1 ) {
3479 if ( d0.getFrom() < d1.getFrom() ) {
3480 return _ascending ? -1 : 1;
3482 else if ( d0.getFrom() > d1.getFrom() ) {
3483 return _ascending ? 1 : -1;