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;
100 public final class SurfacingUtil {
102 public final static Pattern PATTERN_SP_STYLE_TAXONOMY = Pattern.compile( "^[A-Z0-9]{3,5}$" );
103 private final static Map<String, String> _TAXCODE_HEXCOLORSTRING_MAP = new HashMap<String, String>();
104 private final static Map<String, String> _TAXCODE_TAXGROUP_MAP = new HashMap<String, String>();
105 private static final Comparator<Domain> ASCENDING_CONFIDENCE_VALUE_ORDER = new Comparator<Domain>() {
108 public int compare( final Domain d1,
110 if ( d1.getPerDomainEvalue() < d2
111 .getPerDomainEvalue() ) {
114 else if ( d1.getPerDomainEvalue() > d2
115 .getPerDomainEvalue() ) {
119 return d1.compareTo( d2 );
123 private final static NumberFormat FORMATTER_3 = new DecimalFormat( "0.000" );
125 private SurfacingUtil() {
126 // Hidden constructor.
129 public static void addAllBinaryDomainCombinationToSet( final GenomeWideCombinableDomains genome,
130 final SortedSet<BinaryDomainCombination> binary_domain_combinations ) {
131 final SortedMap<String, CombinableDomains> all_cd = genome.getAllCombinableDomainsIds();
132 for( final String domain_id : all_cd.keySet() ) {
133 binary_domain_combinations.addAll( all_cd.get( domain_id ).toBinaryDomainCombinations() );
137 public static void addAllDomainIdsToSet( final GenomeWideCombinableDomains genome,
138 final SortedSet<String> domain_ids ) {
139 final SortedSet<String> domains = genome.getAllDomainIds();
140 for( final String domain : domains ) {
141 domain_ids.add( domain );
145 public static DescriptiveStatistics calculateDescriptiveStatisticsForMeanValues( final Set<DomainSimilarity> similarities ) {
146 final DescriptiveStatistics stats = new BasicDescriptiveStatistics();
147 for( final DomainSimilarity similarity : similarities ) {
148 stats.addValue( similarity.getMeanSimilarityScore() );
153 public static void checkForOutputFileWriteability( final File outfile ) {
154 final String error = ForesterUtil.isWritableFile( outfile );
155 if ( !ForesterUtil.isEmpty( error ) ) {
156 ForesterUtil.fatalError( surfacing.PRG_NAME, error );
160 public static void checkWriteabilityForPairwiseComparisons( final DomainSimilarity.PRINT_OPTION domain_similarity_print_option,
161 final String[][] input_file_properties,
162 final String automated_pairwise_comparison_suffix,
163 final File outdir ) {
164 for( int i = 0; i < input_file_properties.length; ++i ) {
165 for( int j = 0; j < i; ++j ) {
166 final String species_i = input_file_properties[ i ][ 1 ];
167 final String species_j = input_file_properties[ j ][ 1 ];
168 String pairwise_similarities_output_file_str = surfacing.PAIRWISE_DOMAIN_COMPARISONS_PREFIX + species_i
169 + "_" + species_j + automated_pairwise_comparison_suffix;
170 switch ( domain_similarity_print_option ) {
172 if ( !pairwise_similarities_output_file_str.endsWith( ".html" ) ) {
173 pairwise_similarities_output_file_str += ".html";
177 final String error = ForesterUtil
178 .isWritableFile( new File( outdir == null ? pairwise_similarities_output_file_str : outdir
179 + ForesterUtil.FILE_SEPARATOR + pairwise_similarities_output_file_str ) );
180 if ( !ForesterUtil.isEmpty( error ) ) {
181 ForesterUtil.fatalError( surfacing.PRG_NAME, error );
187 public static void collectChangedDomainCombinationsFromBinaryStatesMatrixAsListToFile( final CharacterStateMatrix<CharacterStateMatrix.GainLossStates> matrix,
188 final BinaryDomainCombination.DomainCombinationType dc_type,
189 final List<BinaryDomainCombination> all_binary_domains_combination_gained,
190 final boolean get_gains ) {
191 final SortedSet<String> sorted_ids = new TreeSet<String>();
192 for( int i = 0; i < matrix.getNumberOfIdentifiers(); ++i ) {
193 sorted_ids.add( matrix.getIdentifier( i ) );
195 for( final String id : sorted_ids ) {
196 for( int c = 0; c < matrix.getNumberOfCharacters(); ++c ) {
197 if ( ( get_gains && ( matrix.getState( id, c ) == CharacterStateMatrix.GainLossStates.GAIN ) )
198 || ( !get_gains && ( matrix.getState( id, c ) == CharacterStateMatrix.GainLossStates.LOSS ) ) ) {
199 if ( dc_type == BinaryDomainCombination.DomainCombinationType.DIRECTED_ADJACTANT ) {
200 all_binary_domains_combination_gained.add( AdjactantDirectedBinaryDomainCombination
201 .obtainInstance( matrix.getCharacter( c ) ) );
203 else if ( dc_type == BinaryDomainCombination.DomainCombinationType.DIRECTED ) {
204 all_binary_domains_combination_gained.add( DirectedBinaryDomainCombination
205 .obtainInstance( matrix.getCharacter( c ) ) );
208 all_binary_domains_combination_gained.add( BasicBinaryDomainCombination.obtainInstance( matrix
209 .getCharacter( c ) ) );
216 public static Map<String, List<GoId>> createDomainIdToGoIdMap( final List<PfamToGoMapping> pfam_to_go_mappings ) {
217 final Map<String, List<GoId>> domain_id_to_go_ids_map = new HashMap<String, List<GoId>>( pfam_to_go_mappings.size() );
218 for( final PfamToGoMapping pfam_to_go : pfam_to_go_mappings ) {
219 if ( !domain_id_to_go_ids_map.containsKey( pfam_to_go.getKey() ) ) {
220 domain_id_to_go_ids_map.put( pfam_to_go.getKey(), new ArrayList<GoId>() );
222 domain_id_to_go_ids_map.get( pfam_to_go.getKey() ).add( pfam_to_go.getValue() );
224 return domain_id_to_go_ids_map;
227 public static Map<String, Set<String>> createDomainIdToSecondaryFeaturesMap( final File secondary_features_map_file )
229 final BasicTable<String> primary_table = BasicTableParser.parse( secondary_features_map_file, '\t' );
230 final Map<String, Set<String>> map = new TreeMap<String, Set<String>>();
231 for( int r = 0; r < primary_table.getNumberOfRows(); ++r ) {
232 final String domain_id = primary_table.getValue( 0, r );
233 if ( !map.containsKey( domain_id ) ) {
234 map.put( domain_id, new HashSet<String>() );
236 map.get( domain_id ).add( primary_table.getValue( 1, r ) );
241 public static Phylogeny createNjTreeBasedOnMatrixToFile( final File nj_tree_outfile, final DistanceMatrix distance ) {
242 checkForOutputFileWriteability( nj_tree_outfile );
243 final NeighborJoining nj = NeighborJoining.createInstance();
244 final Phylogeny phylogeny = nj.execute( ( BasicSymmetricalDistanceMatrix ) distance );
245 phylogeny.setName( nj_tree_outfile.getName() );
246 writePhylogenyToFile( phylogeny, nj_tree_outfile.toString() );
250 public static StringBuilder createParametersAsString( final boolean ignore_dufs,
251 final double ie_value_max,
252 final double fs_e_value_max,
253 final int max_allowed_overlap,
254 final boolean no_engulfing_overlaps,
255 final File cutoff_scores_file,
256 final BinaryDomainCombination.DomainCombinationType dc_type ) {
257 final StringBuilder parameters_sb = new StringBuilder();
258 parameters_sb.append( "iE-value: " + ie_value_max );
259 parameters_sb.append( ", FS E-value: " + fs_e_value_max );
260 if ( cutoff_scores_file != null ) {
261 parameters_sb.append( ", Cutoff-scores-file: " + cutoff_scores_file );
264 parameters_sb.append( ", Cutoff-scores-file: not-set" );
266 if ( max_allowed_overlap != surfacing.MAX_ALLOWED_OVERLAP_DEFAULT ) {
267 parameters_sb.append( ", Max-overlap: " + max_allowed_overlap );
270 parameters_sb.append( ", Max-overlap: not-set" );
272 if ( no_engulfing_overlaps ) {
273 parameters_sb.append( ", Engulfing-overlaps: not-allowed" );
276 parameters_sb.append( ", Engulfing-overlaps: allowed" );
279 parameters_sb.append( ", Ignore-dufs: true" );
282 parameters_sb.append( ", Ignore-dufs: false" );
284 parameters_sb.append( ", DC type (if applicable): " + dc_type );
285 return parameters_sb;
288 public static void createSplitWriters( final File out_dir,
289 final String my_outfile,
290 final Map<Character, Writer> split_writers ) throws IOException {
291 split_writers.put( 'a', new BufferedWriter( new FileWriter( out_dir + ForesterUtil.FILE_SEPARATOR + my_outfile
292 + "_domains_A.html" ) ) );
293 split_writers.put( 'b', new BufferedWriter( new FileWriter( out_dir + ForesterUtil.FILE_SEPARATOR + my_outfile
294 + "_domains_B.html" ) ) );
295 split_writers.put( 'c', new BufferedWriter( new FileWriter( out_dir + ForesterUtil.FILE_SEPARATOR + my_outfile
296 + "_domains_C.html" ) ) );
297 split_writers.put( 'd', new BufferedWriter( new FileWriter( out_dir + ForesterUtil.FILE_SEPARATOR + my_outfile
298 + "_domains_D.html" ) ) );
299 split_writers.put( 'e', new BufferedWriter( new FileWriter( out_dir + ForesterUtil.FILE_SEPARATOR + my_outfile
300 + "_domains_E.html" ) ) );
301 split_writers.put( 'f', new BufferedWriter( new FileWriter( out_dir + ForesterUtil.FILE_SEPARATOR + my_outfile
302 + "_domains_F.html" ) ) );
303 split_writers.put( 'g', new BufferedWriter( new FileWriter( out_dir + ForesterUtil.FILE_SEPARATOR + my_outfile
304 + "_domains_G.html" ) ) );
305 split_writers.put( 'h', new BufferedWriter( new FileWriter( out_dir + ForesterUtil.FILE_SEPARATOR + my_outfile
306 + "_domains_H.html" ) ) );
307 split_writers.put( 'i', new BufferedWriter( new FileWriter( out_dir + ForesterUtil.FILE_SEPARATOR + my_outfile
308 + "_domains_I.html" ) ) );
309 split_writers.put( 'j', new BufferedWriter( new FileWriter( out_dir + ForesterUtil.FILE_SEPARATOR + my_outfile
310 + "_domains_J.html" ) ) );
311 split_writers.put( 'k', new BufferedWriter( new FileWriter( out_dir + ForesterUtil.FILE_SEPARATOR + my_outfile
312 + "_domains_K.html" ) ) );
313 split_writers.put( 'l', new BufferedWriter( new FileWriter( out_dir + ForesterUtil.FILE_SEPARATOR + my_outfile
314 + "_domains_L.html" ) ) );
315 split_writers.put( 'm', new BufferedWriter( new FileWriter( out_dir + ForesterUtil.FILE_SEPARATOR + my_outfile
316 + "_domains_M.html" ) ) );
317 split_writers.put( 'n', new BufferedWriter( new FileWriter( out_dir + ForesterUtil.FILE_SEPARATOR + my_outfile
318 + "_domains_N.html" ) ) );
319 split_writers.put( 'o', new BufferedWriter( new FileWriter( out_dir + ForesterUtil.FILE_SEPARATOR + my_outfile
320 + "_domains_O.html" ) ) );
321 split_writers.put( 'p', new BufferedWriter( new FileWriter( out_dir + ForesterUtil.FILE_SEPARATOR + my_outfile
322 + "_domains_P.html" ) ) );
323 split_writers.put( 'q', new BufferedWriter( new FileWriter( out_dir + ForesterUtil.FILE_SEPARATOR + my_outfile
324 + "_domains_Q.html" ) ) );
325 split_writers.put( 'r', new BufferedWriter( new FileWriter( out_dir + ForesterUtil.FILE_SEPARATOR + my_outfile
326 + "_domains_R.html" ) ) );
327 split_writers.put( 's', new BufferedWriter( new FileWriter( out_dir + ForesterUtil.FILE_SEPARATOR + my_outfile
328 + "_domains_S.html" ) ) );
329 split_writers.put( 't', new BufferedWriter( new FileWriter( out_dir + ForesterUtil.FILE_SEPARATOR + my_outfile
330 + "_domains_T.html" ) ) );
331 split_writers.put( 'u', new BufferedWriter( new FileWriter( out_dir + ForesterUtil.FILE_SEPARATOR + my_outfile
332 + "_domains_U.html" ) ) );
333 split_writers.put( 'v', new BufferedWriter( new FileWriter( out_dir + ForesterUtil.FILE_SEPARATOR + my_outfile
334 + "_domains_V.html" ) ) );
335 split_writers.put( 'w', new BufferedWriter( new FileWriter( out_dir + ForesterUtil.FILE_SEPARATOR + my_outfile
336 + "_domains_W.html" ) ) );
337 split_writers.put( 'x', new BufferedWriter( new FileWriter( out_dir + ForesterUtil.FILE_SEPARATOR + my_outfile
338 + "_domains_X.html" ) ) );
339 split_writers.put( 'y', new BufferedWriter( new FileWriter( out_dir + ForesterUtil.FILE_SEPARATOR + my_outfile
340 + "_domains_Y.html" ) ) );
341 split_writers.put( 'z', new BufferedWriter( new FileWriter( out_dir + ForesterUtil.FILE_SEPARATOR + my_outfile
342 + "_domains_Z.html" ) ) );
343 split_writers.put( '0', new BufferedWriter( new FileWriter( out_dir + ForesterUtil.FILE_SEPARATOR + my_outfile
344 + "_domains_0.html" ) ) );
347 public static Map<String, Integer> createTaxCodeToIdMap( final Phylogeny phy ) {
348 final Map<String, Integer> m = new HashMap<String, Integer>();
349 for( final PhylogenyNodeIterator iter = phy.iteratorExternalForward(); iter.hasNext(); ) {
350 final PhylogenyNode n = iter.next();
351 if ( n.getNodeData().isHasTaxonomy() ) {
352 final Taxonomy t = n.getNodeData().getTaxonomy();
353 final String c = t.getTaxonomyCode();
354 if ( !ForesterUtil.isEmpty( c ) ) {
355 if ( n.getNodeData().getTaxonomy() == null ) {
356 ForesterUtil.fatalError( surfacing.PRG_NAME, "no taxonomy id for node " + n );
358 final String id = n.getNodeData().getTaxonomy().getIdentifier().getValue();
359 if ( ForesterUtil.isEmpty( id ) ) {
360 ForesterUtil.fatalError( surfacing.PRG_NAME, "no taxonomy id for node " + n );
362 if ( m.containsKey( c ) ) {
363 ForesterUtil.fatalError( surfacing.PRG_NAME, "taxonomy code " + c + " is not unique" );
365 final int iid = Integer.valueOf( id );
366 if ( m.containsValue( iid ) ) {
367 ForesterUtil.fatalError( surfacing.PRG_NAME, "taxonomy id " + iid + " is not unique" );
373 ForesterUtil.fatalError( surfacing.PRG_NAME, "no taxonomy for node " + n );
379 public static void decoratePrintableDomainSimilarities( final SortedSet<DomainSimilarity> domain_similarities,
380 final Detailedness detailedness ) {
381 for( final DomainSimilarity domain_similarity : domain_similarities ) {
382 if ( domain_similarity instanceof DomainSimilarity ) {
383 final DomainSimilarity printable_domain_similarity = domain_similarity;
384 printable_domain_similarity.setDetailedness( detailedness );
389 public static void doit( final List<Protein> proteins,
390 final List<String> query_domain_ids_nc_order,
392 final String separator,
393 final String limit_to_species,
394 final Map<String, List<Integer>> average_protein_lengths_by_dc ) throws IOException {
395 for( final Protein protein : proteins ) {
396 if ( ForesterUtil.isEmpty( limit_to_species )
397 || protein.getSpecies().getSpeciesId().equalsIgnoreCase( limit_to_species ) ) {
398 if ( protein.contains( query_domain_ids_nc_order, true ) ) {
399 out.write( protein.getSpecies().getSpeciesId() );
400 out.write( separator );
401 out.write( protein.getProteinId().getId() );
402 out.write( separator );
404 final Set<String> visited_domain_ids = new HashSet<String>();
405 boolean first = true;
406 for( final Domain domain : protein.getProteinDomains() ) {
407 if ( !visited_domain_ids.contains( domain.getDomainId() ) ) {
408 visited_domain_ids.add( domain.getDomainId() );
415 out.write( domain.getDomainId() );
417 out.write( "" + domain.getTotalCount() );
422 out.write( separator );
423 if ( !( ForesterUtil.isEmpty( protein.getDescription() ) || protein.getDescription()
424 .equals( SurfacingConstants.NONE ) ) ) {
425 out.write( protein.getDescription() );
427 out.write( separator );
428 if ( !( ForesterUtil.isEmpty( protein.getAccession() ) || protein.getAccession()
429 .equals( SurfacingConstants.NONE ) ) ) {
430 out.write( protein.getAccession() );
432 out.write( SurfacingConstants.NL );
439 public static void domainsPerProteinsStatistics( final String genome,
440 final List<Protein> protein_list,
441 final DescriptiveStatistics all_genomes_domains_per_potein_stats,
442 final SortedMap<Integer, Integer> all_genomes_domains_per_potein_histo,
443 final SortedSet<String> domains_which_are_always_single,
444 final SortedSet<String> domains_which_are_sometimes_single_sometimes_not,
445 final SortedSet<String> domains_which_never_single,
446 final Writer writer ) {
447 final DescriptiveStatistics stats = new BasicDescriptiveStatistics();
448 for( final Protein protein : protein_list ) {
449 final int domains = protein.getNumberOfProteinDomains();
450 //System.out.println( domains );
451 stats.addValue( domains );
452 all_genomes_domains_per_potein_stats.addValue( domains );
453 if ( !all_genomes_domains_per_potein_histo.containsKey( domains ) ) {
454 all_genomes_domains_per_potein_histo.put( domains, 1 );
457 all_genomes_domains_per_potein_histo.put( domains,
458 1 + all_genomes_domains_per_potein_histo.get( domains ) );
460 if ( domains == 1 ) {
461 final String domain = protein.getProteinDomain( 0 ).getDomainId();
462 if ( !domains_which_are_sometimes_single_sometimes_not.contains( domain ) ) {
463 if ( domains_which_never_single.contains( domain ) ) {
464 domains_which_never_single.remove( domain );
465 domains_which_are_sometimes_single_sometimes_not.add( domain );
468 domains_which_are_always_single.add( domain );
472 else if ( domains > 1 ) {
473 for( final Domain d : protein.getProteinDomains() ) {
474 final String domain = d.getDomainId();
475 // System.out.println( domain );
476 if ( !domains_which_are_sometimes_single_sometimes_not.contains( domain ) ) {
477 if ( domains_which_are_always_single.contains( domain ) ) {
478 domains_which_are_always_single.remove( domain );
479 domains_which_are_sometimes_single_sometimes_not.add( domain );
482 domains_which_never_single.add( domain );
489 writer.write( genome );
490 writer.write( "\t" );
491 if ( stats.getN() >= 1 ) {
492 writer.write( stats.arithmeticMean() + "" );
493 writer.write( "\t" );
494 if ( stats.getN() >= 2 ) {
495 writer.write( stats.sampleStandardDeviation() + "" );
500 writer.write( "\t" );
501 writer.write( stats.median() + "" );
502 writer.write( "\t" );
503 writer.write( stats.getN() + "" );
504 writer.write( "\t" );
505 writer.write( stats.getMin() + "" );
506 writer.write( "\t" );
507 writer.write( stats.getMax() + "" );
510 writer.write( "\t" );
511 writer.write( "\t" );
512 writer.write( "\t" );
514 writer.write( "\t" );
515 writer.write( "\t" );
517 writer.write( "\n" );
519 catch ( final IOException e ) {
524 public static void executeDomainLengthAnalysis( final String[][] input_file_properties,
525 final int number_of_genomes,
526 final DomainLengthsTable domain_lengths_table,
527 final File outfile ) throws IOException {
528 final DecimalFormat df = new DecimalFormat( "#.00" );
529 checkForOutputFileWriteability( outfile );
530 final BufferedWriter out = new BufferedWriter( new FileWriter( outfile ) );
531 out.write( "MEAN BASED STATISTICS PER SPECIES" );
532 out.write( ForesterUtil.LINE_SEPARATOR );
533 out.write( domain_lengths_table.createMeanBasedStatisticsPerSpeciesTable().toString() );
534 out.write( ForesterUtil.LINE_SEPARATOR );
535 out.write( ForesterUtil.LINE_SEPARATOR );
536 final List<DomainLengths> domain_lengths_list = domain_lengths_table.getDomainLengthsList();
537 out.write( "OUTLIER SPECIES PER DOMAIN (Z>=1.5)" );
538 out.write( ForesterUtil.LINE_SEPARATOR );
539 for( final DomainLengths domain_lengths : domain_lengths_list ) {
540 final List<Species> species_list = domain_lengths.getMeanBasedOutlierSpecies( 1.5 );
541 if ( species_list.size() > 0 ) {
542 out.write( domain_lengths.getDomainId() + "\t" );
543 for( final Species species : species_list ) {
544 out.write( species + "\t" );
546 out.write( ForesterUtil.LINE_SEPARATOR );
549 out.write( ForesterUtil.LINE_SEPARATOR );
550 out.write( ForesterUtil.LINE_SEPARATOR );
551 out.write( "OUTLIER SPECIES (Z 1.0)" );
552 out.write( ForesterUtil.LINE_SEPARATOR );
553 final DescriptiveStatistics stats_for_all_species = domain_lengths_table
554 .calculateMeanBasedStatisticsForAllSpecies();
555 out.write( stats_for_all_species.asSummary() );
556 out.write( ForesterUtil.LINE_SEPARATOR );
557 final AsciiHistogram histo = new AsciiHistogram( stats_for_all_species );
558 out.write( histo.toStringBuffer( 40, '=', 60, 4 ).toString() );
559 out.write( ForesterUtil.LINE_SEPARATOR );
560 final double population_sd = stats_for_all_species.sampleStandardDeviation();
561 final double population_mean = stats_for_all_species.arithmeticMean();
562 for( final Species species : domain_lengths_table.getSpecies() ) {
563 final double x = domain_lengths_table.calculateMeanBasedStatisticsForSpecies( species ).arithmeticMean();
564 final double z = ( x - population_mean ) / population_sd;
565 out.write( species + "\t" + z );
566 out.write( ForesterUtil.LINE_SEPARATOR );
568 out.write( ForesterUtil.LINE_SEPARATOR );
569 for( final Species species : domain_lengths_table.getSpecies() ) {
570 final DescriptiveStatistics stats_for_species = domain_lengths_table
571 .calculateMeanBasedStatisticsForSpecies( species );
572 final double x = stats_for_species.arithmeticMean();
573 final double z = ( x - population_mean ) / population_sd;
574 if ( ( z <= -1.0 ) || ( z >= 1.0 ) ) {
575 out.write( species + "\t" + df.format( z ) + "\t" + stats_for_species.asSummary() );
576 out.write( ForesterUtil.LINE_SEPARATOR );
584 * Warning: This side-effects 'all_bin_domain_combinations_encountered'!
588 * @param all_bin_domain_combinations_changed
589 * @param sum_of_all_domains_encountered
590 * @param all_bin_domain_combinations_encountered
591 * @param is_gains_analysis
592 * @param protein_length_stats_by_dc
593 * @throws IOException
595 public static void executeFitchGainsAnalysis( final File output_file,
596 final List<BinaryDomainCombination> all_bin_domain_combinations_changed,
597 final int sum_of_all_domains_encountered,
598 final SortedSet<BinaryDomainCombination> all_bin_domain_combinations_encountered,
599 final boolean is_gains_analysis ) throws IOException {
600 checkForOutputFileWriteability( output_file );
601 final Writer out = ForesterUtil.createBufferedWriter( output_file );
602 final SortedMap<Object, Integer> bdc_to_counts = ForesterUtil
603 .listToSortedCountsMap( all_bin_domain_combinations_changed );
604 final SortedSet<String> all_domains_in_combination_changed_more_than_once = new TreeSet<String>();
605 final SortedSet<String> all_domains_in_combination_changed_only_once = new TreeSet<String>();
608 for( final Object bdc_object : bdc_to_counts.keySet() ) {
609 final BinaryDomainCombination bdc = ( BinaryDomainCombination ) bdc_object;
610 final int count = bdc_to_counts.get( bdc_object );
612 ForesterUtil.unexpectedFatalError( surfacing.PRG_NAME, "count < 1 " );
614 out.write( bdc + "\t" + count + ForesterUtil.LINE_SEPARATOR );
616 all_domains_in_combination_changed_more_than_once.add( bdc.getId0() );
617 all_domains_in_combination_changed_more_than_once.add( bdc.getId1() );
620 else if ( count == 1 ) {
621 all_domains_in_combination_changed_only_once.add( bdc.getId0() );
622 all_domains_in_combination_changed_only_once.add( bdc.getId1() );
626 final int all = all_bin_domain_combinations_encountered.size();
628 if ( !is_gains_analysis ) {
629 all_bin_domain_combinations_encountered.removeAll( all_bin_domain_combinations_changed );
630 never_lost = all_bin_domain_combinations_encountered.size();
631 for( final BinaryDomainCombination bdc : all_bin_domain_combinations_encountered ) {
632 out.write( bdc + "\t" + "0" + ForesterUtil.LINE_SEPARATOR );
635 if ( is_gains_analysis ) {
636 out.write( "Sum of all distinct domain combinations appearing once : " + one
637 + ForesterUtil.LINE_SEPARATOR );
638 out.write( "Sum of all distinct domain combinations appearing more than once : " + above_one
639 + ForesterUtil.LINE_SEPARATOR );
640 out.write( "Sum of all distinct domains in combinations apppearing only once : "
641 + all_domains_in_combination_changed_only_once.size() + ForesterUtil.LINE_SEPARATOR );
642 out.write( "Sum of all distinct domains in combinations apppearing more than once: "
643 + all_domains_in_combination_changed_more_than_once.size() + ForesterUtil.LINE_SEPARATOR );
646 out.write( "Sum of all distinct domain combinations never lost : " + never_lost
647 + ForesterUtil.LINE_SEPARATOR );
648 out.write( "Sum of all distinct domain combinations lost once : " + one
649 + ForesterUtil.LINE_SEPARATOR );
650 out.write( "Sum of all distinct domain combinations lost more than once : " + above_one
651 + ForesterUtil.LINE_SEPARATOR );
652 out.write( "Sum of all distinct domains in combinations lost only once : "
653 + all_domains_in_combination_changed_only_once.size() + ForesterUtil.LINE_SEPARATOR );
654 out.write( "Sum of all distinct domains in combinations lost more than once: "
655 + all_domains_in_combination_changed_more_than_once.size() + ForesterUtil.LINE_SEPARATOR );
657 out.write( "All binary combinations : " + all
658 + ForesterUtil.LINE_SEPARATOR );
659 out.write( "All domains : "
660 + sum_of_all_domains_encountered );
662 ForesterUtil.programMessage( surfacing.PRG_NAME,
663 "Wrote fitch domain combination dynamics counts analysis to \"" + output_file
669 * @param all_binary_domains_combination_lost_fitch
670 * @param use_last_in_fitch_parsimony
671 * @param perform_dc_fich
672 * @param consider_directedness_and_adjacency_for_bin_combinations
673 * @param all_binary_domains_combination_gained if null ignored, otherwise this is to list all binary domain combinations
674 * which were gained under unweighted (Fitch) parsimony.
676 public static void executeParsimonyAnalysis( final long random_number_seed_for_fitch_parsimony,
677 final boolean radomize_fitch_parsimony,
678 final String outfile_name,
679 final DomainParsimonyCalculator domain_parsimony,
680 final Phylogeny phylogeny,
681 final Map<String, List<GoId>> domain_id_to_go_ids_map,
682 final Map<GoId, GoTerm> go_id_to_term_map,
683 final GoNameSpace go_namespace_limit,
684 final String parameters_str,
685 final Map<String, Set<String>>[] domain_id_to_secondary_features_maps,
686 final SortedSet<String> positive_filter,
687 final boolean output_binary_domain_combinations_for_graphs,
688 final List<BinaryDomainCombination> all_binary_domains_combination_gained_fitch,
689 final List<BinaryDomainCombination> all_binary_domains_combination_lost_fitch,
690 final BinaryDomainCombination.DomainCombinationType dc_type,
691 final Map<String, DescriptiveStatistics> protein_length_stats_by_dc,
692 final Map<String, DescriptiveStatistics> domain_number_stats_by_dc,
693 final Map<String, DescriptiveStatistics> domain_length_stats_by_domain,
694 final Map<String, Integer> tax_code_to_id_map,
695 final boolean write_to_nexus,
696 final boolean use_last_in_fitch_parsimony,
697 final boolean perform_dc_fich ) {
698 final String sep = ForesterUtil.LINE_SEPARATOR + "###################" + ForesterUtil.LINE_SEPARATOR;
699 final String date_time = ForesterUtil.getCurrentDateTime();
700 final SortedSet<String> all_pfams_encountered = new TreeSet<String>();
701 final SortedSet<String> all_pfams_gained_as_domains = new TreeSet<String>();
702 final SortedSet<String> all_pfams_lost_as_domains = new TreeSet<String>();
703 final SortedSet<String> all_pfams_gained_as_dom_combinations = new TreeSet<String>();
704 final SortedSet<String> all_pfams_lost_as_dom_combinations = new TreeSet<String>();
705 if ( write_to_nexus ) {
706 writeToNexus( outfile_name, domain_parsimony, phylogeny );
710 Phylogeny local_phylogeny_l = phylogeny.copy();
711 if ( ( positive_filter != null ) && ( positive_filter.size() > 0 ) ) {
712 domain_parsimony.executeDolloParsimonyOnDomainPresence( positive_filter );
715 domain_parsimony.executeDolloParsimonyOnDomainPresence();
717 SurfacingUtil.writeMatrixToFile( domain_parsimony.getGainLossMatrix(), outfile_name
718 + surfacing.PARSIMONY_OUTPUT_GL_SUFFIX_DOLLO_DOMAINS, Format.FORESTER );
719 SurfacingUtil.writeMatrixToFile( domain_parsimony.getGainLossCountsMatrix(), outfile_name
720 + surfacing.PARSIMONY_OUTPUT_GL_COUNTS_SUFFIX_DOLLO_DOMAINS, Format.FORESTER );
721 SurfacingUtil.writeBinaryStatesMatrixAsListToFile( domain_parsimony.getGainLossMatrix(),
722 CharacterStateMatrix.GainLossStates.GAIN,
723 outfile_name + surfacing.PARSIMONY_OUTPUT_DOLLO_GAINS_D,
725 ForesterUtil.LINE_SEPARATOR,
727 SurfacingUtil.writeBinaryStatesMatrixAsListToFile( domain_parsimony.getGainLossMatrix(),
728 CharacterStateMatrix.GainLossStates.LOSS,
729 outfile_name + surfacing.PARSIMONY_OUTPUT_DOLLO_LOSSES_D,
731 ForesterUtil.LINE_SEPARATOR,
733 SurfacingUtil.writeBinaryStatesMatrixAsListToFile( domain_parsimony.getGainLossMatrix(), null, outfile_name
734 + surfacing.PARSIMONY_OUTPUT_DOLLO_PRESENT_D, sep, ForesterUtil.LINE_SEPARATOR, null );
736 writeBinaryStatesMatrixToList( domain_id_to_go_ids_map,
740 domain_parsimony.getGainLossMatrix(),
741 CharacterStateMatrix.GainLossStates.GAIN,
742 outfile_name + surfacing.PARSIMONY_OUTPUT_DOLLO_GAINS_HTML_D,
744 ForesterUtil.LINE_SEPARATOR,
745 "Dollo Parsimony | Gains | Domains",
747 domain_id_to_secondary_features_maps,
748 all_pfams_encountered,
749 all_pfams_gained_as_domains,
751 tax_code_to_id_map );
752 writeBinaryStatesMatrixToList( domain_id_to_go_ids_map,
756 domain_parsimony.getGainLossMatrix(),
757 CharacterStateMatrix.GainLossStates.LOSS,
758 outfile_name + surfacing.PARSIMONY_OUTPUT_DOLLO_LOSSES_HTML_D,
760 ForesterUtil.LINE_SEPARATOR,
761 "Dollo Parsimony | Losses | Domains",
763 domain_id_to_secondary_features_maps,
764 all_pfams_encountered,
765 all_pfams_lost_as_domains,
767 tax_code_to_id_map );
768 // writeBinaryStatesMatrixToList( domain_id_to_go_ids_map,
769 // go_id_to_term_map,
770 // go_namespace_limit,
772 // domain_parsimony.getGainLossMatrix(),
774 // outfile_name + surfacing.PARSIMONY_OUTPUT_DOLLO_PRESENT_HTML_D,
776 // ForesterUtil.LINE_SEPARATOR,
777 // "Dollo Parsimony | Present | Domains",
779 // domain_id_to_secondary_features_maps,
780 // all_pfams_encountered,
782 // "_dollo_present_d",
783 // tax_code_to_id_map );
784 preparePhylogeny( local_phylogeny_l,
787 "Dollo parsimony on domain presence/absence",
788 "dollo_on_domains_" + outfile_name,
790 SurfacingUtil.writePhylogenyToFile( local_phylogeny_l, outfile_name
791 + surfacing.DOMAINS_PARSIMONY_TREE_OUTPUT_SUFFIX_DOLLO );
793 writeAllDomainsChangedOnAllSubtrees( local_phylogeny_l, true, outfile_name, "_dollo_all_gains_d" );
794 writeAllDomainsChangedOnAllSubtrees( local_phylogeny_l, false, outfile_name, "_dollo_all_losses_d" );
796 catch ( final IOException e ) {
798 ForesterUtil.fatalError( surfacing.PRG_NAME, e.getLocalizedMessage() );
800 if ( perform_dc_fich && ( domain_parsimony.calculateNumberOfBinaryDomainCombination() > 0 ) ) {
801 // FITCH DOMAIN COMBINATIONS
802 // -------------------------
803 local_phylogeny_l = phylogeny.copy();
804 String randomization = "no";
805 if ( radomize_fitch_parsimony ) {
806 domain_parsimony.executeFitchParsimonyOnBinaryDomainCombintion( random_number_seed_for_fitch_parsimony );
807 randomization = "yes, seed = " + random_number_seed_for_fitch_parsimony;
810 domain_parsimony.executeFitchParsimonyOnBinaryDomainCombintion( use_last_in_fitch_parsimony );
812 SurfacingUtil.writeMatrixToFile( domain_parsimony.getGainLossMatrix(), outfile_name
813 + surfacing.PARSIMONY_OUTPUT_GL_SUFFIX_FITCH_BINARY_COMBINATIONS, Format.FORESTER );
814 SurfacingUtil.writeMatrixToFile( domain_parsimony.getGainLossCountsMatrix(), outfile_name
815 + surfacing.PARSIMONY_OUTPUT_GL_COUNTS_SUFFIX_FITCH_BINARY_COMBINATIONS, Format.FORESTER );
817 .writeBinaryStatesMatrixAsListToFile( domain_parsimony.getGainLossMatrix(),
818 CharacterStateMatrix.GainLossStates.GAIN,
819 outfile_name + surfacing.PARSIMONY_OUTPUT_FITCH_GAINS_BC,
821 ForesterUtil.LINE_SEPARATOR,
823 SurfacingUtil.writeBinaryStatesMatrixAsListToFile( domain_parsimony.getGainLossMatrix(),
824 CharacterStateMatrix.GainLossStates.LOSS,
826 + surfacing.PARSIMONY_OUTPUT_FITCH_LOSSES_BC,
828 ForesterUtil.LINE_SEPARATOR,
830 SurfacingUtil.writeBinaryStatesMatrixAsListToFile( domain_parsimony.getGainLossMatrix(), null, outfile_name
831 + surfacing.PARSIMONY_OUTPUT_FITCH_PRESENT_BC, sep, ForesterUtil.LINE_SEPARATOR, null );
832 if ( all_binary_domains_combination_gained_fitch != null ) {
833 collectChangedDomainCombinationsFromBinaryStatesMatrixAsListToFile( domain_parsimony.getGainLossMatrix(),
835 all_binary_domains_combination_gained_fitch,
838 if ( all_binary_domains_combination_lost_fitch != null ) {
839 collectChangedDomainCombinationsFromBinaryStatesMatrixAsListToFile( domain_parsimony.getGainLossMatrix(),
841 all_binary_domains_combination_lost_fitch,
844 if ( output_binary_domain_combinations_for_graphs ) {
846 .writeBinaryStatesMatrixAsListToFileForBinaryCombinationsForGraphAnalysis( domain_parsimony
847 .getGainLossMatrix(),
850 + surfacing.PARSIMONY_OUTPUT_FITCH_PRESENT_BC_OUTPUTFILE_SUFFIX_FOR_GRAPH_ANALYSIS,
852 ForesterUtil.LINE_SEPARATOR,
853 BinaryDomainCombination.OutputFormat.DOT );
856 writeBinaryStatesMatrixToList( domain_id_to_go_ids_map,
860 domain_parsimony.getGainLossMatrix(),
861 CharacterStateMatrix.GainLossStates.GAIN,
862 outfile_name + surfacing.PARSIMONY_OUTPUT_FITCH_GAINS_HTML_BC,
864 ForesterUtil.LINE_SEPARATOR,
865 "Fitch Parsimony | Gains | Domain Combinations",
868 all_pfams_encountered,
869 all_pfams_gained_as_dom_combinations,
871 tax_code_to_id_map );
872 writeBinaryStatesMatrixToList( domain_id_to_go_ids_map,
876 domain_parsimony.getGainLossMatrix(),
877 CharacterStateMatrix.GainLossStates.LOSS,
878 outfile_name + surfacing.PARSIMONY_OUTPUT_FITCH_LOSSES_HTML_BC,
880 ForesterUtil.LINE_SEPARATOR,
881 "Fitch Parsimony | Losses | Domain Combinations",
884 all_pfams_encountered,
885 all_pfams_lost_as_dom_combinations,
887 tax_code_to_id_map );
888 // writeBinaryStatesMatrixToList( domain_id_to_go_ids_map,
889 // go_id_to_term_map,
890 // go_namespace_limit,
892 // domain_parsimony.getGainLossMatrix(),
894 // outfile_name + surfacing.PARSIMONY_OUTPUT_FITCH_PRESENT_HTML_BC,
896 // ForesterUtil.LINE_SEPARATOR,
897 // "Fitch Parsimony | Present | Domain Combinations",
900 // all_pfams_encountered,
902 // "_fitch_present_dc",
903 // tax_code_to_id_map );
904 writeAllEncounteredPfamsToFile( domain_id_to_go_ids_map,
907 all_pfams_encountered );
908 writePfamsToFile( outfile_name + surfacing.ALL_PFAMS_GAINED_AS_DOMAINS_SUFFIX, all_pfams_gained_as_domains );
909 writePfamsToFile( outfile_name + surfacing.ALL_PFAMS_LOST_AS_DOMAINS_SUFFIX, all_pfams_lost_as_domains );
910 writePfamsToFile( outfile_name + surfacing.ALL_PFAMS_GAINED_AS_DC_SUFFIX,
911 all_pfams_gained_as_dom_combinations );
912 writePfamsToFile( outfile_name + surfacing.ALL_PFAMS_LOST_AS_DC_SUFFIX, all_pfams_lost_as_dom_combinations );
913 preparePhylogeny( local_phylogeny_l,
916 "Fitch parsimony on binary domain combination presence/absence randomization: "
918 "fitch_on_binary_domain_combinations_" + outfile_name,
920 SurfacingUtil.writePhylogenyToFile( local_phylogeny_l, outfile_name
921 + surfacing.BINARY_DOMAIN_COMBINATIONS_PARSIMONY_TREE_OUTPUT_SUFFIX_FITCH );
922 calculateIndependentDomainCombinationGains( local_phylogeny_l,
924 + surfacing.INDEPENDENT_DC_GAINS_FITCH_PARS_COUNTS_OUTPUT_SUFFIX,
926 + surfacing.INDEPENDENT_DC_GAINS_FITCH_PARS_DC_OUTPUT_SUFFIX,
928 + surfacing.INDEPENDENT_DC_GAINS_FITCH_PARS_DC_FOR_GO_MAPPING_OUTPUT_SUFFIX,
930 + surfacing.INDEPENDENT_DC_GAINS_FITCH_PARS_DC_FOR_GO_MAPPING_OUTPUT_UNIQUE_SUFFIX,
931 outfile_name + "_indep_dc_gains_fitch_lca_ranks.txt",
932 outfile_name + "_indep_dc_gains_fitch_lca_taxonomies.txt",
933 outfile_name + "_indep_dc_gains_fitch_protein_statistics.txt",
934 protein_length_stats_by_dc,
935 domain_number_stats_by_dc,
936 domain_length_stats_by_domain );
940 public static void executeParsimonyAnalysisForSecondaryFeatures( final String outfile_name,
941 final DomainParsimonyCalculator secondary_features_parsimony,
942 final Phylogeny phylogeny,
943 final String parameters_str,
944 final Map<Species, MappingResults> mapping_results_map,
945 final boolean use_last_in_fitch_parsimony ) {
946 final String sep = ForesterUtil.LINE_SEPARATOR + "###################" + ForesterUtil.LINE_SEPARATOR;
947 final String date_time = ForesterUtil.getCurrentDateTime();
948 System.out.println();
949 writeToNexus( outfile_name + surfacing.NEXUS_SECONDARY_FEATURES,
950 secondary_features_parsimony.createMatrixOfSecondaryFeaturePresenceOrAbsence( null ),
952 Phylogeny local_phylogeny_copy = phylogeny.copy();
953 secondary_features_parsimony.executeDolloParsimonyOnSecondaryFeatures( mapping_results_map );
954 SurfacingUtil.writeMatrixToFile( secondary_features_parsimony.getGainLossMatrix(), outfile_name
955 + surfacing.PARSIMONY_OUTPUT_GL_SUFFIX_DOLLO_SECONDARY_FEATURES, Format.FORESTER );
956 SurfacingUtil.writeMatrixToFile( secondary_features_parsimony.getGainLossCountsMatrix(), outfile_name
957 + surfacing.PARSIMONY_OUTPUT_GL_COUNTS_SUFFIX_DOLLO_SECONDARY_FEATURES, Format.FORESTER );
959 .writeBinaryStatesMatrixAsListToFile( secondary_features_parsimony.getGainLossMatrix(),
960 CharacterStateMatrix.GainLossStates.GAIN,
962 + surfacing.PARSIMONY_OUTPUT_DOLLO_GAINS_SECONDARY_FEATURES,
964 ForesterUtil.LINE_SEPARATOR,
967 .writeBinaryStatesMatrixAsListToFile( secondary_features_parsimony.getGainLossMatrix(),
968 CharacterStateMatrix.GainLossStates.LOSS,
970 + surfacing.PARSIMONY_OUTPUT_DOLLO_LOSSES_SECONDARY_FEATURES,
972 ForesterUtil.LINE_SEPARATOR,
975 .writeBinaryStatesMatrixAsListToFile( secondary_features_parsimony.getGainLossMatrix(),
978 + surfacing.PARSIMONY_OUTPUT_DOLLO_PRESENT_SECONDARY_FEATURES,
980 ForesterUtil.LINE_SEPARATOR,
982 preparePhylogeny( local_phylogeny_copy,
983 secondary_features_parsimony,
985 "Dollo parsimony on secondary feature presence/absence",
986 "dollo_on_secondary_features_" + outfile_name,
988 SurfacingUtil.writePhylogenyToFile( local_phylogeny_copy, outfile_name
989 + surfacing.SECONDARY_FEATURES_PARSIMONY_TREE_OUTPUT_SUFFIX_DOLLO );
990 // FITCH DOMAIN COMBINATIONS
991 // -------------------------
992 local_phylogeny_copy = phylogeny.copy();
993 final String randomization = "no";
994 secondary_features_parsimony
995 .executeFitchParsimonyOnBinaryDomainCombintionOnSecondaryFeatures( use_last_in_fitch_parsimony );
996 preparePhylogeny( local_phylogeny_copy,
997 secondary_features_parsimony,
999 "Fitch parsimony on secondary binary domain combination presence/absence randomization: "
1001 "fitch_on_binary_domain_combinations_" + outfile_name,
1003 SurfacingUtil.writePhylogenyToFile( local_phylogeny_copy, outfile_name
1004 + surfacing.BINARY_DOMAIN_COMBINATIONS_PARSIMONY_TREE_OUTPUT_SUFFIX_FITCH_MAPPED );
1005 calculateIndependentDomainCombinationGains( local_phylogeny_copy, outfile_name
1006 + surfacing.INDEPENDENT_DC_GAINS_FITCH_PARS_COUNTS_MAPPED_OUTPUT_SUFFIX, outfile_name
1007 + surfacing.INDEPENDENT_DC_GAINS_FITCH_PARS_DC_MAPPED_OUTPUT_SUFFIX, outfile_name
1008 + surfacing.INDEPENDENT_DC_GAINS_FITCH_PARS_DC_FOR_GO_MAPPING_MAPPED_OUTPUT_SUFFIX, outfile_name
1009 + surfacing.INDEPENDENT_DC_GAINS_FITCH_PARS_DC_FOR_GO_MAPPING_MAPPED_OUTPUT_UNIQUE_SUFFIX, outfile_name
1010 + "_MAPPED_indep_dc_gains_fitch_lca_ranks.txt", outfile_name
1011 + "_MAPPED_indep_dc_gains_fitch_lca_taxonomies.txt", null, null, null, null );
1014 public static void executePlusMinusAnalysis( final File output_file,
1015 final List<String> plus_minus_analysis_high_copy_base,
1016 final List<String> plus_minus_analysis_high_copy_target,
1017 final List<String> plus_minus_analysis_low_copy,
1018 final List<GenomeWideCombinableDomains> gwcd_list,
1019 final SortedMap<Species, List<Protein>> protein_lists_per_species,
1020 final Map<String, List<GoId>> domain_id_to_go_ids_map,
1021 final Map<GoId, GoTerm> go_id_to_term_map,
1022 final List<Object> plus_minus_analysis_numbers ) {
1023 final Set<String> all_spec = new HashSet<String>();
1024 for( final GenomeWideCombinableDomains gwcd : gwcd_list ) {
1025 all_spec.add( gwcd.getSpecies().getSpeciesId() );
1027 final File html_out_dom = new File( output_file + surfacing.PLUS_MINUS_DOM_SUFFIX_HTML );
1028 final File plain_out_dom = new File( output_file + surfacing.PLUS_MINUS_DOM_SUFFIX );
1029 final File html_out_dc = new File( output_file + surfacing.PLUS_MINUS_DC_SUFFIX_HTML );
1030 final File all_domains_go_ids_out_dom = new File( output_file + surfacing.PLUS_MINUS_ALL_GO_IDS_DOM_SUFFIX );
1031 final File passing_domains_go_ids_out_dom = new File( output_file
1032 + surfacing.PLUS_MINUS_PASSING_GO_IDS_DOM_SUFFIX );
1033 final File proteins_file_base = new File( output_file + "" );
1034 final int min_diff = ( ( Integer ) plus_minus_analysis_numbers.get( 0 ) ).intValue();
1035 final double factor = ( ( Double ) plus_minus_analysis_numbers.get( 1 ) ).doubleValue();
1037 DomainCountsDifferenceUtil.calculateCopyNumberDifferences( gwcd_list,
1038 protein_lists_per_species,
1039 plus_minus_analysis_high_copy_base,
1040 plus_minus_analysis_high_copy_target,
1041 plus_minus_analysis_low_copy,
1047 domain_id_to_go_ids_map,
1049 all_domains_go_ids_out_dom,
1050 passing_domains_go_ids_out_dom,
1051 proteins_file_base );
1053 catch ( final IOException e ) {
1054 ForesterUtil.fatalError( surfacing.PRG_NAME, e.getLocalizedMessage() );
1056 ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote plus minus domain analysis results to \""
1057 + html_out_dom + "\"" );
1058 ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote plus minus domain analysis results to \""
1059 + plain_out_dom + "\"" );
1060 ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote plus minus domain analysis results to \"" + html_out_dc
1062 ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote plus minus domain analysis based passing GO ids to \""
1063 + passing_domains_go_ids_out_dom + "\"" );
1064 ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote plus minus domain analysis based all GO ids to \""
1065 + all_domains_go_ids_out_dom + "\"" );
1068 public static void extractProteinNames( final List<Protein> proteins,
1069 final List<String> query_domain_ids_nc_order,
1071 final String separator,
1072 final String limit_to_species ) throws IOException {
1073 for( final Protein protein : proteins ) {
1074 if ( ForesterUtil.isEmpty( limit_to_species )
1075 || protein.getSpecies().getSpeciesId().equalsIgnoreCase( limit_to_species ) ) {
1076 if ( protein.contains( query_domain_ids_nc_order, true ) ) {
1077 out.write( protein.getSpecies().getSpeciesId() );
1078 out.write( separator );
1079 out.write( protein.getProteinId().getId() );
1080 out.write( separator );
1082 final Set<String> visited_domain_ids = new HashSet<String>();
1083 boolean first = true;
1084 for( final Domain domain : protein.getProteinDomains() ) {
1085 if ( !visited_domain_ids.contains( domain.getDomainId() ) ) {
1086 visited_domain_ids.add( domain.getDomainId() );
1093 out.write( domain.getDomainId() );
1095 out.write( "" + domain.getTotalCount() );
1100 out.write( separator );
1101 if ( !( ForesterUtil.isEmpty( protein.getDescription() ) || protein.getDescription()
1102 .equals( SurfacingConstants.NONE ) ) ) {
1103 out.write( protein.getDescription() );
1105 out.write( separator );
1106 if ( !( ForesterUtil.isEmpty( protein.getAccession() ) || protein.getAccession()
1107 .equals( SurfacingConstants.NONE ) ) ) {
1108 out.write( protein.getAccession() );
1110 out.write( SurfacingConstants.NL );
1117 public static void extractProteinNames( final SortedMap<Species, List<Protein>> protein_lists_per_species,
1118 final String domain_id,
1120 final String separator,
1121 final String limit_to_species,
1122 final double domain_e_cutoff ) throws IOException {
1123 //System.out.println( "Per domain E-value: " + domain_e_cutoff );
1124 for( final Species species : protein_lists_per_species.keySet() ) {
1125 //System.out.println( species + ":" );
1126 for( final Protein protein : protein_lists_per_species.get( species ) ) {
1127 if ( ForesterUtil.isEmpty( limit_to_species )
1128 || protein.getSpecies().getSpeciesId().equalsIgnoreCase( limit_to_species ) ) {
1129 final List<Domain> domains = protein.getProteinDomains( domain_id );
1130 if ( domains.size() > 0 ) {
1131 out.write( protein.getSpecies().getSpeciesId() );
1132 out.write( separator );
1133 out.write( protein.getProteinId().getId() );
1134 out.write( separator );
1135 out.write( domain_id.toString() );
1136 out.write( separator );
1138 for( final Domain domain : domains ) {
1139 if ( ( domain_e_cutoff < 0 ) || ( domain.getPerDomainEvalue() <= domain_e_cutoff ) ) {
1141 out.write( domain.getFrom() + "-" + domain.getTo() );
1142 if ( prev_to >= 0 ) {
1143 final int l = domain.getFrom() - prev_to;
1144 // System.out.println( l );
1146 prev_to = domain.getTo();
1150 out.write( separator );
1151 final List<Domain> domain_list = new ArrayList<Domain>();
1152 for( final Domain domain : protein.getProteinDomains() ) {
1153 if ( ( domain_e_cutoff < 0 ) || ( domain.getPerDomainEvalue() <= domain_e_cutoff ) ) {
1154 domain_list.add( domain );
1157 final Domain domain_ary[] = new Domain[ domain_list.size() ];
1158 for( int i = 0; i < domain_list.size(); ++i ) {
1159 domain_ary[ i ] = domain_list.get( i );
1161 Arrays.sort( domain_ary, new DomainComparator( true ) );
1163 boolean first = true;
1164 for( final Domain domain : domain_ary ) {
1171 out.write( domain.getDomainId().toString() );
1172 out.write( ":" + domain.getFrom() + "-" + domain.getTo() );
1173 out.write( ":" + domain.getPerDomainEvalue() );
1176 if ( !( ForesterUtil.isEmpty( protein.getDescription() ) || protein.getDescription()
1177 .equals( SurfacingConstants.NONE ) ) ) {
1178 out.write( protein.getDescription() );
1180 out.write( separator );
1181 if ( !( ForesterUtil.isEmpty( protein.getAccession() ) || protein.getAccession()
1182 .equals( SurfacingConstants.NONE ) ) ) {
1183 out.write( protein.getAccession() );
1185 out.write( SurfacingConstants.NL );
1193 public static SortedSet<String> getAllDomainIds( final List<GenomeWideCombinableDomains> gwcd_list ) {
1194 final SortedSet<String> all_domains_ids = new TreeSet<String>();
1195 for( final GenomeWideCombinableDomains gwcd : gwcd_list ) {
1196 final Set<String> all_domains = gwcd.getAllDomainIds();
1197 // for( final Domain domain : all_domains ) {
1198 all_domains_ids.addAll( all_domains );
1201 return all_domains_ids;
1204 public static SortedMap<String, Integer> getDomainCounts( final List<Protein> protein_domain_collections ) {
1205 final SortedMap<String, Integer> map = new TreeMap<String, Integer>();
1206 for( final Protein protein_domain_collection : protein_domain_collections ) {
1207 for( final Object name : protein_domain_collection.getProteinDomains() ) {
1208 final BasicDomain protein_domain = ( BasicDomain ) name;
1209 final String id = protein_domain.getDomainId();
1210 if ( map.containsKey( id ) ) {
1211 map.put( id, map.get( id ) + 1 );
1221 public static int getNumberOfNodesLackingName( final Phylogeny p, final StringBuilder names ) {
1222 final PhylogenyNodeIterator it = p.iteratorPostorder();
1224 while ( it.hasNext() ) {
1225 final PhylogenyNode n = it.next();
1226 if ( ForesterUtil.isEmpty( n.getName() )
1227 && ( !n.getNodeData().isHasTaxonomy() || ForesterUtil.isEmpty( n.getNodeData().getTaxonomy()
1228 .getScientificName() ) )
1229 && ( !n.getNodeData().isHasTaxonomy() || ForesterUtil.isEmpty( n.getNodeData().getTaxonomy()
1230 .getCommonName() ) ) ) {
1231 if ( n.getParent() != null ) {
1232 names.append( " " );
1233 names.append( n.getParent().getName() );
1235 final List l = n.getAllExternalDescendants();
1236 for( final Object object : l ) {
1237 System.out.println( l.toString() );
1245 public static void log( final String msg, final Writer w ) {
1248 w.write( ForesterUtil.LINE_SEPARATOR );
1250 catch ( final IOException e ) {
1251 ForesterUtil.fatalError( surfacing.PRG_NAME, e.getLocalizedMessage() );
1255 public static Phylogeny[] obtainAndPreProcessIntrees( final File[] intree_files,
1256 final int number_of_genomes,
1257 final String[][] input_file_properties ) {
1258 final Phylogeny[] intrees = new Phylogeny[ intree_files.length ];
1260 for( final File intree_file : intree_files ) {
1261 Phylogeny intree = null;
1262 final String error = ForesterUtil.isReadableFile( intree_file );
1263 if ( !ForesterUtil.isEmpty( error ) ) {
1264 ForesterUtil.fatalError( surfacing.PRG_NAME, "cannot read input tree file [" + intree_file + "]: "
1268 final Phylogeny[] p_array = ParserBasedPhylogenyFactory.getInstance()
1269 .create( intree_file, ParserUtils.createParserDependingOnFileType( intree_file, true ) );
1270 if ( p_array.length < 1 ) {
1271 ForesterUtil.fatalError( surfacing.PRG_NAME, "file [" + intree_file
1272 + "] does not contain any phylogeny in phyloXML format" );
1274 else if ( p_array.length > 1 ) {
1275 ForesterUtil.fatalError( surfacing.PRG_NAME, "file [" + intree_file
1276 + "] contains more than one phylogeny in phyloXML format" );
1278 intree = p_array[ 0 ];
1280 catch ( final Exception e ) {
1281 ForesterUtil.fatalError( surfacing.PRG_NAME, "failed to read input tree from file [" + intree_file
1284 if ( ( intree == null ) || intree.isEmpty() ) {
1285 ForesterUtil.fatalError( surfacing.PRG_NAME, "input tree [" + intree_file + "] is empty" );
1287 if ( !intree.isRooted() ) {
1288 ForesterUtil.fatalError( surfacing.PRG_NAME, "input tree [" + intree_file + "] is not rooted" );
1290 if ( intree.getNumberOfExternalNodes() < number_of_genomes ) {
1291 ForesterUtil.fatalError( surfacing.PRG_NAME,
1292 "number of external nodes [" + intree.getNumberOfExternalNodes()
1293 + "] of input tree [" + intree_file
1294 + "] is smaller than the number of genomes the be analyzed ["
1295 + number_of_genomes + "]" );
1297 final StringBuilder parent_names = new StringBuilder();
1298 final int nodes_lacking_name = getNumberOfNodesLackingName( intree, parent_names );
1299 if ( nodes_lacking_name > 0 ) {
1300 ForesterUtil.fatalError( surfacing.PRG_NAME, "input tree [" + intree_file + "] has "
1301 + nodes_lacking_name + " node(s) lacking a name [parent names:" + parent_names + "]" );
1303 preparePhylogenyForParsimonyAnalyses( intree, input_file_properties );
1304 if ( !intree.isCompletelyBinary() ) {
1305 ForesterUtil.printWarningMessage( surfacing.PRG_NAME, "input tree [" + intree_file
1306 + "] is not completely binary" );
1308 intrees[ i++ ] = intree;
1313 public static Phylogeny obtainFirstIntree( final File intree_file ) {
1314 Phylogeny intree = null;
1315 final String error = ForesterUtil.isReadableFile( intree_file );
1316 if ( !ForesterUtil.isEmpty( error ) ) {
1317 ForesterUtil.fatalError( surfacing.PRG_NAME, "cannot read input tree file [" + intree_file + "]: " + error );
1320 final Phylogeny[] phys = ParserBasedPhylogenyFactory.getInstance()
1321 .create( intree_file, ParserUtils.createParserDependingOnFileType( intree_file, true ) );
1322 if ( phys.length < 1 ) {
1323 ForesterUtil.fatalError( surfacing.PRG_NAME, "file [" + intree_file
1324 + "] does not contain any phylogeny in phyloXML format" );
1326 else if ( phys.length > 1 ) {
1327 ForesterUtil.fatalError( surfacing.PRG_NAME, "file [" + intree_file
1328 + "] contains more than one phylogeny in phyloXML format" );
1332 catch ( final Exception e ) {
1333 ForesterUtil.fatalError( surfacing.PRG_NAME, "failed to read input tree from file [" + intree_file + "]: "
1336 if ( ( intree == null ) || intree.isEmpty() ) {
1337 ForesterUtil.fatalError( surfacing.PRG_NAME, "input tree [" + intree_file + "] is empty" );
1339 if ( !intree.isRooted() ) {
1340 ForesterUtil.fatalError( surfacing.PRG_NAME, "input tree [" + intree_file + "] is not rooted" );
1345 public static String obtainHexColorStringDependingOnTaxonomyGroup( final String tax_code, final Phylogeny phy )
1346 throws IllegalArgumentException {
1347 if ( !_TAXCODE_HEXCOLORSTRING_MAP.containsKey( tax_code ) ) {
1348 if ( ( phy != null ) && !phy.isEmpty() ) {
1349 // final List<PhylogenyNode> nodes = phy.getNodesViaTaxonomyCode( tax_code );
1351 // if ( ( nodes == null ) || nodes.isEmpty() ) {
1352 // throw new IllegalArgumentException( "code " + tax_code + " is not found" );
1354 // if ( nodes.size() != 1 ) {
1355 // throw new IllegalArgumentException( "code " + tax_code + " is not unique" );
1357 // PhylogenyNode n = nodes.get( 0 );
1358 // while ( n != null ) {
1359 // if ( n.getNodeData().isHasTaxonomy()
1360 // && !ForesterUtil.isEmpty( n.getNodeData().getTaxonomy().getScientificName() ) ) {
1361 // c = ForesterUtil.obtainColorDependingOnTaxonomyGroup( n.getNodeData().getTaxonomy()
1362 // .getScientificName(), tax_code );
1364 // if ( ( c == null ) && !ForesterUtil.isEmpty( n.getName() ) ) {
1365 // c = ForesterUtil.obtainColorDependingOnTaxonomyGroup( n.getName(), tax_code );
1367 // if ( c != null ) {
1370 // n = n.getParent();
1372 final String group = obtainTaxonomyGroup( tax_code, phy );
1373 final Color c = ForesterUtil.obtainColorDependingOnTaxonomyGroup( group );
1375 throw new IllegalArgumentException( "no color found for taxonomy group \"" + group
1376 + "\" for code \"" + tax_code + "\"" );
1378 final String hex = String.format( "#%02x%02x%02x", c.getRed(), c.getGreen(), c.getBlue() );
1379 _TAXCODE_HEXCOLORSTRING_MAP.put( tax_code, hex );
1382 throw new IllegalArgumentException( "unable to obtain color for code " + tax_code
1383 + " (tree is null or empty and code is not in map)" );
1386 return _TAXCODE_HEXCOLORSTRING_MAP.get( tax_code );
1389 public static String obtainTaxonomyGroup( final String tax_code, final Phylogeny species_tree )
1390 throws IllegalArgumentException {
1391 if ( !_TAXCODE_TAXGROUP_MAP.containsKey( tax_code ) ) {
1392 if ( ( species_tree != null ) && !species_tree.isEmpty() ) {
1393 final List<PhylogenyNode> nodes = species_tree.getNodesViaTaxonomyCode( tax_code );
1394 if ( ( nodes == null ) || nodes.isEmpty() ) {
1395 throw new IllegalArgumentException( "code " + tax_code + " is not found" );
1397 if ( nodes.size() != 1 ) {
1398 throw new IllegalArgumentException( "code " + tax_code + " is not unique" );
1400 PhylogenyNode n = nodes.get( 0 );
1401 String group = null;
1402 while ( n != null ) {
1403 if ( n.getNodeData().isHasTaxonomy()
1404 && !ForesterUtil.isEmpty( n.getNodeData().getTaxonomy().getScientificName() ) ) {
1405 group = ForesterUtil.obtainNormalizedTaxonomyGroup( n.getNodeData().getTaxonomy()
1406 .getScientificName() );
1408 if ( ForesterUtil.isEmpty( group ) && !ForesterUtil.isEmpty( n.getName() ) ) {
1409 group = ForesterUtil.obtainNormalizedTaxonomyGroup( n.getName() );
1411 if ( !ForesterUtil.isEmpty( group ) ) {
1416 if ( ForesterUtil.isEmpty( group ) ) {
1417 throw new IllegalArgumentException( "no group found for taxonomy code \"" + tax_code + "\"" );
1419 _TAXCODE_TAXGROUP_MAP.put( tax_code, group );
1422 throw new IllegalArgumentException( "unable to obtain group for code " + tax_code
1423 + " (tree is null or empty and code is not in map)" );
1426 return _TAXCODE_TAXGROUP_MAP.get( tax_code );
1429 public static void performDomainArchitectureAnalysis( final SortedMap<String, Set<String>> domain_architecutures,
1430 final SortedMap<String, Integer> domain_architecuture_counts,
1431 final int min_count,
1432 final File da_counts_outfile,
1433 final File unique_da_outfile ) {
1434 checkForOutputFileWriteability( da_counts_outfile );
1435 checkForOutputFileWriteability( unique_da_outfile );
1437 final BufferedWriter da_counts_out = new BufferedWriter( new FileWriter( da_counts_outfile ) );
1438 final BufferedWriter unique_da_out = new BufferedWriter( new FileWriter( unique_da_outfile ) );
1439 final Iterator<Entry<String, Integer>> it = domain_architecuture_counts.entrySet().iterator();
1440 while ( it.hasNext() ) {
1441 final Map.Entry<String, Integer> e = it.next();
1442 final String da = e.getKey();
1443 final int count = e.getValue();
1444 if ( count >= min_count ) {
1445 da_counts_out.write( da );
1446 da_counts_out.write( "\t" );
1447 da_counts_out.write( String.valueOf( count ) );
1448 da_counts_out.write( ForesterUtil.LINE_SEPARATOR );
1451 final Iterator<Entry<String, Set<String>>> it2 = domain_architecutures.entrySet().iterator();
1452 while ( it2.hasNext() ) {
1453 final Map.Entry<String, Set<String>> e2 = it2.next();
1454 final String genome = e2.getKey();
1455 final Set<String> das = e2.getValue();
1456 if ( das.contains( da ) ) {
1457 unique_da_out.write( genome );
1458 unique_da_out.write( "\t" );
1459 unique_da_out.write( da );
1460 unique_da_out.write( ForesterUtil.LINE_SEPARATOR );
1465 unique_da_out.close();
1466 da_counts_out.close();
1468 catch ( final IOException e ) {
1469 ForesterUtil.fatalError( surfacing.PRG_NAME, e.getMessage() );
1471 ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote distance matrices to \"" + da_counts_outfile + "\"" );
1472 ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote distance matrices to \"" + unique_da_outfile + "\"" );
1476 public static void preparePhylogeny( final Phylogeny p,
1477 final DomainParsimonyCalculator domain_parsimony,
1478 final String date_time,
1479 final String method,
1481 final String parameters_str ) {
1482 domain_parsimony.decoratePhylogenyWithDomains( p );
1483 final StringBuilder desc = new StringBuilder();
1484 desc.append( "[Method: " + method + "] [Date: " + date_time + "] " );
1485 desc.append( "[Cost: " + domain_parsimony.getCost() + "] " );
1486 desc.append( "[Gains: " + domain_parsimony.getTotalGains() + "] " );
1487 desc.append( "[Losses: " + domain_parsimony.getTotalLosses() + "] " );
1488 desc.append( "[Unchanged: " + domain_parsimony.getTotalUnchanged() + "] " );
1489 desc.append( "[Parameters: " + parameters_str + "]" );
1491 p.setDescription( desc.toString() );
1492 p.setConfidence( new Confidence( domain_parsimony.getCost(), "parsimony" ) );
1493 p.setRerootable( false );
1494 p.setRooted( true );
1497 public static void preparePhylogenyForParsimonyAnalyses( final Phylogeny intree,
1498 final String[][] input_file_properties ) {
1499 final String[] genomes = new String[ input_file_properties.length ];
1500 for( int i = 0; i < input_file_properties.length; ++i ) {
1501 if ( intree.getNodes( input_file_properties[ i ][ 1 ] ).size() > 1 ) {
1502 ForesterUtil.fatalError( surfacing.PRG_NAME, "node named [" + input_file_properties[ i ][ 1 ]
1503 + "] is not unique in input tree " + intree.getName() );
1505 genomes[ i ] = input_file_properties[ i ][ 1 ];
1508 final PhylogenyNodeIterator it = intree.iteratorPostorder();
1509 while ( it.hasNext() ) {
1510 final PhylogenyNode n = it.next();
1511 if ( ForesterUtil.isEmpty( n.getName() ) ) {
1512 if ( n.getNodeData().isHasTaxonomy()
1513 && !ForesterUtil.isEmpty( n.getNodeData().getTaxonomy().getTaxonomyCode() ) ) {
1514 n.setName( n.getNodeData().getTaxonomy().getTaxonomyCode() );
1516 else if ( n.getNodeData().isHasTaxonomy()
1517 && !ForesterUtil.isEmpty( n.getNodeData().getTaxonomy().getScientificName() ) ) {
1518 n.setName( n.getNodeData().getTaxonomy().getScientificName() );
1520 else if ( n.getNodeData().isHasTaxonomy()
1521 && !ForesterUtil.isEmpty( n.getNodeData().getTaxonomy().getCommonName() ) ) {
1522 n.setName( n.getNodeData().getTaxonomy().getCommonName() );
1526 .fatalError( surfacing.PRG_NAME,
1527 "node with no name, scientific name, common name, or taxonomy code present" );
1532 final List<String> igns = PhylogenyMethods.deleteExternalNodesPositiveSelection( genomes, intree );
1533 if ( igns.size() > 0 ) {
1534 System.out.println( "Not using the following " + igns.size() + " nodes:" );
1535 for( int i = 0; i < igns.size(); ++i ) {
1536 System.out.println( " " + i + ": " + igns.get( i ) );
1538 System.out.println( "--" );
1540 for( final String[] input_file_propertie : input_file_properties ) {
1542 intree.getNode( input_file_propertie[ 1 ] );
1544 catch ( final IllegalArgumentException e ) {
1545 ForesterUtil.fatalError( surfacing.PRG_NAME, "node named [" + input_file_propertie[ 1 ]
1546 + "] not present/not unique in input tree" );
1551 public static void printOutPercentageOfMultidomainProteins( final SortedMap<Integer, Integer> all_genomes_domains_per_potein_histo,
1552 final Writer log_writer ) {
1554 for( final Entry<Integer, Integer> entry : all_genomes_domains_per_potein_histo.entrySet() ) {
1555 sum += entry.getValue();
1557 final double percentage = ( 100.0 * ( sum - all_genomes_domains_per_potein_histo.get( 1 ) ) ) / sum;
1558 ForesterUtil.programMessage( surfacing.PRG_NAME, "Percentage of multidomain proteins: " + percentage + "%" );
1559 log( "Percentage of multidomain proteins: : " + percentage + "%", log_writer );
1562 public static void processFilter( final File filter_file, final SortedSet<String> filter ) {
1563 SortedSet<String> filter_str = null;
1565 filter_str = ForesterUtil.file2set( filter_file );
1567 catch ( final IOException e ) {
1568 ForesterUtil.fatalError( surfacing.PRG_NAME, e.getMessage() );
1570 if ( filter_str != null ) {
1571 for( final String string : filter_str ) {
1572 filter.add( string );
1575 if ( surfacing.VERBOSE ) {
1576 System.out.println( "Filter:" );
1577 for( final String domainId : filter ) {
1578 System.out.println( domainId );
1583 public static String[][] processInputGenomesFile( final File input_genomes ) {
1584 String[][] input_file_properties = null;
1586 input_file_properties = ForesterUtil.file22dArray( input_genomes );
1588 catch ( final IOException e ) {
1589 ForesterUtil.fatalError( surfacing.PRG_NAME,
1590 "genomes files is to be in the following format \"<hmmpfam output file> <species>\": "
1591 + e.getLocalizedMessage() );
1593 final Set<String> specs = new HashSet<String>();
1594 final Set<String> paths = new HashSet<String>();
1595 for( int i = 0; i < input_file_properties.length; ++i ) {
1596 if ( !PhyloXmlUtil.TAXOMONY_CODE_PATTERN.matcher( input_file_properties[ i ][ 1 ] ).matches() ) {
1597 ForesterUtil.fatalError( surfacing.PRG_NAME, "illegal format for species code: "
1598 + input_file_properties[ i ][ 1 ] );
1600 if ( specs.contains( input_file_properties[ i ][ 1 ] ) ) {
1601 ForesterUtil.fatalError( surfacing.PRG_NAME, "species code " + input_file_properties[ i ][ 1 ]
1602 + " is not unique" );
1604 specs.add( input_file_properties[ i ][ 1 ] );
1605 if ( paths.contains( input_file_properties[ i ][ 0 ] ) ) {
1606 ForesterUtil.fatalError( surfacing.PRG_NAME, "path " + input_file_properties[ i ][ 0 ]
1607 + " is not unique" );
1609 paths.add( input_file_properties[ i ][ 0 ] );
1610 final String error = ForesterUtil.isReadableFile( new File( input_file_properties[ i ][ 0 ] ) );
1611 if ( !ForesterUtil.isEmpty( error ) ) {
1612 ForesterUtil.fatalError( surfacing.PRG_NAME, error );
1615 return input_file_properties;
1618 public static void processPlusMinusAnalysisOption( final CommandLineArguments cla,
1619 final List<String> high_copy_base,
1620 final List<String> high_copy_target,
1621 final List<String> low_copy,
1622 final List<Object> numbers ) {
1623 if ( cla.isOptionSet( surfacing.PLUS_MINUS_ANALYSIS_OPTION ) ) {
1624 if ( !cla.isOptionValueSet( surfacing.PLUS_MINUS_ANALYSIS_OPTION ) ) {
1625 ForesterUtil.fatalError( surfacing.PRG_NAME, "no value for 'plus-minus' file: -"
1626 + surfacing.PLUS_MINUS_ANALYSIS_OPTION + "=<file>" );
1628 final File plus_minus_file = new File( cla.getOptionValue( surfacing.PLUS_MINUS_ANALYSIS_OPTION ) );
1629 final String msg = ForesterUtil.isReadableFile( plus_minus_file );
1630 if ( !ForesterUtil.isEmpty( msg ) ) {
1631 ForesterUtil.fatalError( surfacing.PRG_NAME, "can not read from \"" + plus_minus_file + "\": " + msg );
1633 processPlusMinusFile( plus_minus_file, high_copy_base, high_copy_target, low_copy, numbers );
1637 // First numbers is minimal difference, second is factor.
1638 public static void processPlusMinusFile( final File plus_minus_file,
1639 final List<String> high_copy_base,
1640 final List<String> high_copy_target,
1641 final List<String> low_copy,
1642 final List<Object> numbers ) {
1643 Set<String> species_set = null;
1644 int min_diff = surfacing.PLUS_MINUS_ANALYSIS_MIN_DIFF_DEFAULT;
1645 double factor = surfacing.PLUS_MINUS_ANALYSIS_FACTOR_DEFAULT;
1647 species_set = ForesterUtil.file2set( plus_minus_file );
1649 catch ( final IOException e ) {
1650 ForesterUtil.fatalError( surfacing.PRG_NAME, e.getMessage() );
1652 if ( species_set != null ) {
1653 for( final String species : species_set ) {
1654 final String species_trimmed = species.substring( 1 );
1655 if ( species.startsWith( "+" ) ) {
1656 if ( low_copy.contains( species_trimmed ) ) {
1657 ForesterUtil.fatalError( surfacing.PRG_NAME,
1658 "species/genome names can not appear with both '+' and '-' suffix, as appears the case for: \""
1659 + species_trimmed + "\"" );
1661 high_copy_base.add( species_trimmed );
1663 else if ( species.startsWith( "*" ) ) {
1664 if ( low_copy.contains( species_trimmed ) ) {
1665 ForesterUtil.fatalError( surfacing.PRG_NAME,
1666 "species/genome names can not appear with both '*' and '-' suffix, as appears the case for: \""
1667 + species_trimmed + "\"" );
1669 high_copy_target.add( species_trimmed );
1671 else if ( species.startsWith( "-" ) ) {
1672 if ( high_copy_base.contains( species_trimmed ) || high_copy_target.contains( species_trimmed ) ) {
1673 ForesterUtil.fatalError( surfacing.PRG_NAME,
1674 "species/genome names can not appear with both '+' or '*' and '-' suffix, as appears the case for: \""
1675 + species_trimmed + "\"" );
1677 low_copy.add( species_trimmed );
1679 else if ( species.startsWith( "$D" ) ) {
1681 min_diff = Integer.parseInt( species.substring( 3 ) );
1683 catch ( final NumberFormatException e ) {
1684 ForesterUtil.fatalError( surfacing.PRG_NAME,
1685 "could not parse integer value for minimal difference from: \""
1686 + species.substring( 3 ) + "\"" );
1689 else if ( species.startsWith( "$F" ) ) {
1691 factor = Double.parseDouble( species.substring( 3 ) );
1693 catch ( final NumberFormatException e ) {
1694 ForesterUtil.fatalError( surfacing.PRG_NAME, "could not parse double value for factor from: \""
1695 + species.substring( 3 ) + "\"" );
1698 else if ( species.startsWith( "#" ) ) {
1703 .fatalError( surfacing.PRG_NAME,
1704 "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: \""
1707 numbers.add( new Integer( min_diff + "" ) );
1708 numbers.add( new Double( factor + "" ) );
1712 ForesterUtil.fatalError( surfacing.PRG_NAME, "'plus minus' file [" + plus_minus_file + "] appears empty" );
1717 * species | protein id | n-terminal domain | c-terminal domain | n-terminal domain per domain E-value | c-terminal domain per domain E-value
1721 static public StringBuffer proteinToDomainCombinations( final Protein protein,
1722 final String protein_id,
1723 final String separator ) {
1724 final StringBuffer sb = new StringBuffer();
1725 if ( protein.getSpecies() == null ) {
1726 throw new IllegalArgumentException( "species must not be null" );
1728 if ( ForesterUtil.isEmpty( protein.getSpecies().getSpeciesId() ) ) {
1729 throw new IllegalArgumentException( "species id must not be empty" );
1731 final List<Domain> domains = protein.getProteinDomains();
1732 if ( domains.size() > 1 ) {
1733 final Map<String, Integer> counts = new HashMap<String, Integer>();
1734 for( final Domain domain : domains ) {
1735 final String id = domain.getDomainId();
1736 if ( counts.containsKey( id ) ) {
1737 counts.put( id, counts.get( id ) + 1 );
1740 counts.put( id, 1 );
1743 final Set<String> dcs = new HashSet<String>();
1744 for( int i = 1; i < domains.size(); ++i ) {
1745 for( int j = 0; j < i; ++j ) {
1746 Domain domain_n = domains.get( i );
1747 Domain domain_c = domains.get( j );
1748 if ( domain_n.getFrom() > domain_c.getFrom() ) {
1749 domain_n = domains.get( j );
1750 domain_c = domains.get( i );
1752 final String dc = domain_n.getDomainId() + domain_c.getDomainId();
1753 if ( !dcs.contains( dc ) ) {
1755 sb.append( protein.getSpecies() );
1756 sb.append( separator );
1757 sb.append( protein_id );
1758 sb.append( separator );
1759 sb.append( domain_n.getDomainId() );
1760 sb.append( separator );
1761 sb.append( domain_c.getDomainId() );
1762 sb.append( separator );
1763 sb.append( domain_n.getPerDomainEvalue() );
1764 sb.append( separator );
1765 sb.append( domain_c.getPerDomainEvalue() );
1766 sb.append( separator );
1767 sb.append( counts.get( domain_n.getDomainId() ) );
1768 sb.append( separator );
1769 sb.append( counts.get( domain_c.getDomainId() ) );
1770 sb.append( ForesterUtil.LINE_SEPARATOR );
1775 else if ( domains.size() == 1 ) {
1776 sb.append( protein.getSpecies() );
1777 sb.append( separator );
1778 sb.append( protein_id );
1779 sb.append( separator );
1780 sb.append( domains.get( 0 ).getDomainId() );
1781 sb.append( separator );
1782 sb.append( separator );
1783 sb.append( domains.get( 0 ).getPerDomainEvalue() );
1784 sb.append( separator );
1785 sb.append( separator );
1787 sb.append( separator );
1788 sb.append( ForesterUtil.LINE_SEPARATOR );
1791 sb.append( protein.getSpecies() );
1792 sb.append( separator );
1793 sb.append( protein_id );
1794 sb.append( separator );
1795 sb.append( separator );
1796 sb.append( separator );
1797 sb.append( separator );
1798 sb.append( separator );
1799 sb.append( separator );
1800 sb.append( ForesterUtil.LINE_SEPARATOR );
1805 public static List<Domain> sortDomainsWithAscendingConfidenceValues( final Protein protein ) {
1806 final List<Domain> domains = new ArrayList<Domain>();
1807 for( final Domain d : protein.getProteinDomains() ) {
1810 Collections.sort( domains, SurfacingUtil.ASCENDING_CONFIDENCE_VALUE_ORDER );
1814 public static int storeDomainArchitectures( final String genome,
1815 final SortedMap<String, Set<String>> domain_architecutures,
1816 final List<Protein> protein_list,
1817 final Map<String, Integer> distinct_domain_architecuture_counts ) {
1818 final Set<String> da = new HashSet<String>();
1819 domain_architecutures.put( genome, da );
1820 for( final Protein protein : protein_list ) {
1821 final String da_str = ( ( BasicProtein ) protein ).toDomainArchitectureString( "~", 3, "=" );
1822 if ( !da.contains( da_str ) ) {
1823 if ( !distinct_domain_architecuture_counts.containsKey( da_str ) ) {
1824 distinct_domain_architecuture_counts.put( da_str, 1 );
1827 distinct_domain_architecuture_counts.put( da_str,
1828 distinct_domain_architecuture_counts.get( da_str ) + 1 );
1836 public static void writeAllDomainsChangedOnAllSubtrees( final Phylogeny p,
1837 final boolean get_gains,
1838 final String outdir,
1839 final String suffix_for_filename ) throws IOException {
1840 CharacterStateMatrix.GainLossStates state = CharacterStateMatrix.GainLossStates.GAIN;
1842 state = CharacterStateMatrix.GainLossStates.LOSS;
1844 final File base_dir = createBaseDirForPerNodeDomainFiles( surfacing.BASE_DIRECTORY_PER_SUBTREE_DOMAIN_GAIN_LOSS_FILES,
1848 for( final PhylogenyNodeIterator it = p.iteratorPostorder(); it.hasNext(); ) {
1849 final PhylogenyNode node = it.next();
1850 if ( !node.isExternal() ) {
1851 final SortedSet<String> domains = collectAllDomainsChangedOnSubtree( node, get_gains );
1852 if ( domains.size() > 0 ) {
1853 final Writer writer = ForesterUtil.createBufferedWriter( base_dir + ForesterUtil.FILE_SEPARATOR
1854 + node.getName() + suffix_for_filename );
1855 for( final String domain : domains ) {
1856 writer.write( domain );
1857 writer.write( ForesterUtil.LINE_SEPARATOR );
1865 public static void writeBinaryDomainCombinationsFileForGraphAnalysis( final String[][] input_file_properties,
1866 final File output_dir,
1867 final GenomeWideCombinableDomains gwcd,
1869 final GenomeWideCombinableDomainsSortOrder dc_sort_order ) {
1870 File dc_outfile_dot = new File( input_file_properties[ i ][ 1 ]
1871 + surfacing.DOMAIN_COMBINITONS_OUTPUTFILE_SUFFIX_FOR_GRAPH_ANALYSIS );
1872 if ( output_dir != null ) {
1873 dc_outfile_dot = new File( output_dir + ForesterUtil.FILE_SEPARATOR + dc_outfile_dot );
1875 checkForOutputFileWriteability( dc_outfile_dot );
1876 final SortedSet<BinaryDomainCombination> binary_combinations = createSetOfAllBinaryDomainCombinationsPerGenome( gwcd );
1878 final BufferedWriter out_dot = new BufferedWriter( new FileWriter( dc_outfile_dot ) );
1879 for( final BinaryDomainCombination bdc : binary_combinations ) {
1880 out_dot.write( bdc.toGraphDescribingLanguage( BinaryDomainCombination.OutputFormat.DOT, null, null )
1882 out_dot.write( SurfacingConstants.NL );
1886 catch ( final IOException e ) {
1887 ForesterUtil.fatalError( surfacing.PRG_NAME, e.getMessage() );
1889 ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote binary domain combination for \""
1890 + input_file_properties[ i ][ 0 ] + "\" (" + input_file_properties[ i ][ 1 ] + ", "
1891 + input_file_properties[ i ][ 2 ] + ") to: \"" + dc_outfile_dot + "\"" );
1894 public static void writeBinaryStatesMatrixAsListToFile( final CharacterStateMatrix<CharacterStateMatrix.GainLossStates> matrix,
1895 final CharacterStateMatrix.GainLossStates state,
1896 final String filename,
1897 final String indentifier_characters_separator,
1898 final String character_separator,
1899 final Map<String, String> descriptions ) {
1900 final File outfile = new File( filename );
1901 checkForOutputFileWriteability( outfile );
1902 final SortedSet<String> sorted_ids = new TreeSet<String>();
1903 for( int i = 0; i < matrix.getNumberOfIdentifiers(); ++i ) {
1904 sorted_ids.add( matrix.getIdentifier( i ) );
1907 final BufferedWriter out = new BufferedWriter( new FileWriter( outfile ) );
1908 for( final String id : sorted_ids ) {
1909 out.write( indentifier_characters_separator );
1910 out.write( "#" + id );
1911 out.write( indentifier_characters_separator );
1912 for( int c = 0; c < matrix.getNumberOfCharacters(); ++c ) {
1914 // using null to indicate either UNCHANGED_PRESENT or GAIN.
1915 if ( ( matrix.getState( id, c ) == state )
1916 || ( ( state == null ) && ( ( matrix.getState( id, c ) == CharacterStateMatrix.GainLossStates.GAIN ) || ( matrix
1917 .getState( id, c ) == CharacterStateMatrix.GainLossStates.UNCHANGED_PRESENT ) ) ) ) {
1918 out.write( matrix.getCharacter( c ) );
1919 if ( ( descriptions != null ) && !descriptions.isEmpty()
1920 && descriptions.containsKey( matrix.getCharacter( c ) ) ) {
1922 out.write( descriptions.get( matrix.getCharacter( c ) ) );
1924 out.write( character_separator );
1931 catch ( final IOException e ) {
1932 ForesterUtil.fatalError( surfacing.PRG_NAME, e.getMessage() );
1934 ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote characters list: \"" + filename + "\"" );
1937 public static void writeBinaryStatesMatrixAsListToFileForBinaryCombinationsForGraphAnalysis( final CharacterStateMatrix<CharacterStateMatrix.GainLossStates> matrix,
1938 final CharacterStateMatrix.GainLossStates state,
1939 final String filename,
1940 final String indentifier_characters_separator,
1941 final String character_separator,
1942 final BinaryDomainCombination.OutputFormat bc_output_format ) {
1943 final File outfile = new File( filename );
1944 checkForOutputFileWriteability( outfile );
1945 final SortedSet<String> sorted_ids = new TreeSet<String>();
1946 for( int i = 0; i < matrix.getNumberOfIdentifiers(); ++i ) {
1947 sorted_ids.add( matrix.getIdentifier( i ) );
1950 final BufferedWriter out = new BufferedWriter( new FileWriter( outfile ) );
1951 for( final String id : sorted_ids ) {
1952 out.write( indentifier_characters_separator );
1953 out.write( "#" + id );
1954 out.write( indentifier_characters_separator );
1955 for( int c = 0; c < matrix.getNumberOfCharacters(); ++c ) {
1957 // using null to indicate either UNCHANGED_PRESENT or GAIN.
1958 if ( ( matrix.getState( id, c ) == state )
1959 || ( ( state == null ) && ( ( matrix.getState( id, c ) == CharacterStateMatrix.GainLossStates.GAIN ) || ( matrix
1960 .getState( id, c ) == CharacterStateMatrix.GainLossStates.UNCHANGED_PRESENT ) ) ) ) {
1961 BinaryDomainCombination bdc = null;
1963 bdc = BasicBinaryDomainCombination.obtainInstance( matrix.getCharacter( c ) );
1965 catch ( final Exception e ) {
1966 ForesterUtil.fatalError( surfacing.PRG_NAME, e.getLocalizedMessage() );
1968 out.write( bdc.toGraphDescribingLanguage( bc_output_format, null, null ).toString() );
1969 out.write( character_separator );
1976 catch ( final IOException e ) {
1977 ForesterUtil.fatalError( surfacing.PRG_NAME, e.getMessage() );
1979 ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote characters list: \"" + filename + "\"" );
1982 public static void writeBinaryStatesMatrixToList( final Map<String, List<GoId>> domain_id_to_go_ids_map,
1983 final Map<GoId, GoTerm> go_id_to_term_map,
1984 final GoNameSpace go_namespace_limit,
1985 final boolean domain_combinations,
1986 final CharacterStateMatrix<CharacterStateMatrix.GainLossStates> matrix,
1987 final CharacterStateMatrix.GainLossStates state,
1988 final String filename,
1989 final String indentifier_characters_separator,
1990 final String character_separator,
1991 final String title_for_html,
1992 final String prefix_for_html,
1993 final Map<String, Set<String>>[] domain_id_to_secondary_features_maps,
1994 final SortedSet<String> all_pfams_encountered,
1995 final SortedSet<String> pfams_gained_or_lost,
1996 final String suffix_for_per_node_events_file,
1997 final Map<String, Integer> tax_code_to_id_map ) {
1998 if ( ( go_namespace_limit != null ) && ( ( go_id_to_term_map == null ) || ( go_id_to_term_map.size() < 1 ) ) ) {
1999 throw new IllegalArgumentException( "attempt to use GO namespace limit without a GO-id to term map" );
2001 else if ( ( ( domain_id_to_go_ids_map == null ) || ( domain_id_to_go_ids_map.size() < 1 ) ) ) {
2002 throw new IllegalArgumentException( "attempt to output detailed HTML without a Pfam to GO map" );
2004 else if ( ( ( go_id_to_term_map == null ) || ( go_id_to_term_map.size() < 1 ) ) ) {
2005 throw new IllegalArgumentException( "attempt to output detailed HTML without a GO-id to term map" );
2007 final File outfile = new File( filename );
2008 checkForOutputFileWriteability( outfile );
2009 final SortedSet<String> sorted_ids = new TreeSet<String>();
2010 for( int i = 0; i < matrix.getNumberOfIdentifiers(); ++i ) {
2011 sorted_ids.add( matrix.getIdentifier( i ) );
2014 final Writer out = new BufferedWriter( new FileWriter( outfile ) );
2015 final File per_node_go_mapped_domain_gain_loss_files_base_dir = createBaseDirForPerNodeDomainFiles( surfacing.BASE_DIRECTORY_PER_NODE_DOMAIN_GAIN_LOSS_FILES,
2016 domain_combinations,
2019 Writer per_node_go_mapped_domain_gain_loss_outfile_writer = null;
2020 File per_node_go_mapped_domain_gain_loss_outfile = null;
2021 int per_node_counter = 0;
2022 out.write( "<html>" );
2023 out.write( SurfacingConstants.NL );
2024 writeHtmlHead( out, title_for_html );
2025 out.write( SurfacingConstants.NL );
2026 out.write( "<body>" );
2027 out.write( SurfacingConstants.NL );
2028 out.write( "<h1>" );
2029 out.write( SurfacingConstants.NL );
2030 out.write( title_for_html );
2031 out.write( SurfacingConstants.NL );
2032 out.write( "</h1>" );
2033 out.write( SurfacingConstants.NL );
2034 out.write( "<table>" );
2035 out.write( SurfacingConstants.NL );
2036 for( final String id : sorted_ids ) {
2037 final Matcher matcher = PATTERN_SP_STYLE_TAXONOMY.matcher( id );
2038 if ( matcher.matches() ) {
2041 out.write( "<tr>" );
2042 out.write( "<td>" );
2043 out.write( "<a href=\"#" + id + "\">" + id + "</a>" );
2044 out.write( "</td>" );
2045 out.write( "</tr>" );
2046 out.write( SurfacingConstants.NL );
2048 out.write( "</table>" );
2049 out.write( SurfacingConstants.NL );
2050 for( final String id : sorted_ids ) {
2051 final Matcher matcher = PATTERN_SP_STYLE_TAXONOMY.matcher( id );
2052 if ( matcher.matches() ) {
2055 out.write( SurfacingConstants.NL );
2056 out.write( "<h2>" );
2057 out.write( "<a name=\"" + id + "\">" + id + "</a>" );
2058 writeTaxonomyLinks( out, id, tax_code_to_id_map );
2059 out.write( "</h2>" );
2060 out.write( SurfacingConstants.NL );
2061 out.write( "<table>" );
2062 out.write( SurfacingConstants.NL );
2063 out.write( "<tr>" );
2064 out.write( "<td><b>" );
2065 out.write( "Pfam domain(s)" );
2066 out.write( "</b></td><td><b>" );
2067 out.write( "GO term acc" );
2068 out.write( "</b></td><td><b>" );
2069 out.write( "GO term" );
2070 out.write( "</b></td><td><b>" );
2071 out.write( "GO namespace" );
2072 out.write( "</b></td>" );
2073 out.write( "</tr>" );
2074 out.write( SurfacingConstants.NL );
2075 out.write( "</tr>" );
2076 out.write( SurfacingConstants.NL );
2077 per_node_counter = 0;
2078 if ( matrix.getNumberOfCharacters() > 0 ) {
2079 per_node_go_mapped_domain_gain_loss_outfile = new File( per_node_go_mapped_domain_gain_loss_files_base_dir
2080 + ForesterUtil.FILE_SEPARATOR + id + suffix_for_per_node_events_file );
2081 SurfacingUtil.checkForOutputFileWriteability( per_node_go_mapped_domain_gain_loss_outfile );
2082 per_node_go_mapped_domain_gain_loss_outfile_writer = ForesterUtil
2083 .createBufferedWriter( per_node_go_mapped_domain_gain_loss_outfile );
2086 per_node_go_mapped_domain_gain_loss_outfile = null;
2087 per_node_go_mapped_domain_gain_loss_outfile_writer = null;
2089 for( int c = 0; c < matrix.getNumberOfCharacters(); ++c ) {
2091 // using null to indicate either UNCHANGED_PRESENT or GAIN.
2092 if ( ( matrix.getState( id, c ) == state )
2093 || ( ( state == null ) && ( ( matrix.getState( id, c ) == CharacterStateMatrix.GainLossStates.UNCHANGED_PRESENT ) || ( matrix
2094 .getState( id, c ) == CharacterStateMatrix.GainLossStates.GAIN ) ) ) ) {
2095 final String character = matrix.getCharacter( c );
2096 String domain_0 = "";
2097 String domain_1 = "";
2098 if ( character.indexOf( BinaryDomainCombination.SEPARATOR ) > 0 ) {
2099 final String[] s = character.split( BinaryDomainCombination.SEPARATOR );
2100 if ( s.length != 2 ) {
2101 throw new AssertionError( "this should not have happened: unexpected format for domain combination: ["
2102 + character + "]" );
2108 domain_0 = character;
2110 writeDomainData( domain_id_to_go_ids_map,
2117 character_separator,
2118 domain_id_to_secondary_features_maps,
2120 all_pfams_encountered.add( domain_0 );
2121 if ( pfams_gained_or_lost != null ) {
2122 pfams_gained_or_lost.add( domain_0 );
2124 if ( !ForesterUtil.isEmpty( domain_1 ) ) {
2125 all_pfams_encountered.add( domain_1 );
2126 if ( pfams_gained_or_lost != null ) {
2127 pfams_gained_or_lost.add( domain_1 );
2130 if ( per_node_go_mapped_domain_gain_loss_outfile_writer != null ) {
2131 writeDomainsToIndividualFilePerTreeNode( per_node_go_mapped_domain_gain_loss_outfile_writer,
2138 if ( per_node_go_mapped_domain_gain_loss_outfile_writer != null ) {
2139 per_node_go_mapped_domain_gain_loss_outfile_writer.close();
2140 if ( per_node_counter < 1 ) {
2141 per_node_go_mapped_domain_gain_loss_outfile.delete();
2143 per_node_counter = 0;
2145 out.write( "</table>" );
2146 out.write( SurfacingConstants.NL );
2147 out.write( "<hr>" );
2148 out.write( SurfacingConstants.NL );
2149 } // for( final String id : sorted_ids ) {
2150 out.write( "</body>" );
2151 out.write( SurfacingConstants.NL );
2152 out.write( "</html>" );
2153 out.write( SurfacingConstants.NL );
2157 catch ( final IOException e ) {
2158 ForesterUtil.fatalError( surfacing.PRG_NAME, e.getMessage() );
2160 ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote characters detailed HTML list: \"" + filename + "\"" );
2163 public static void writeDomainCombinationsCountsFile( final String[][] input_file_properties,
2164 final File output_dir,
2165 final Writer per_genome_domain_promiscuity_statistics_writer,
2166 final GenomeWideCombinableDomains gwcd,
2168 final GenomeWideCombinableDomains.GenomeWideCombinableDomainsSortOrder dc_sort_order ) {
2169 File dc_outfile = new File( input_file_properties[ i ][ 1 ]
2170 + surfacing.DOMAIN_COMBINITON_COUNTS_OUTPUTFILE_SUFFIX );
2171 if ( output_dir != null ) {
2172 dc_outfile = new File( output_dir + ForesterUtil.FILE_SEPARATOR + dc_outfile );
2174 checkForOutputFileWriteability( dc_outfile );
2176 final BufferedWriter out = new BufferedWriter( new FileWriter( dc_outfile ) );
2177 out.write( gwcd.toStringBuilder( dc_sort_order ).toString() );
2180 catch ( final IOException e ) {
2181 ForesterUtil.fatalError( surfacing.PRG_NAME, e.getMessage() );
2183 final DescriptiveStatistics stats = gwcd.getPerGenomeDomainPromiscuityStatistics();
2185 per_genome_domain_promiscuity_statistics_writer.write( input_file_properties[ i ][ 1 ] + "\t" );
2186 per_genome_domain_promiscuity_statistics_writer.write( FORMATTER_3.format( stats.arithmeticMean() ) + "\t" );
2187 if ( stats.getN() < 2 ) {
2188 per_genome_domain_promiscuity_statistics_writer.write( "n/a" + "\t" );
2191 per_genome_domain_promiscuity_statistics_writer.write( FORMATTER_3.format( stats
2192 .sampleStandardDeviation() ) + "\t" );
2194 per_genome_domain_promiscuity_statistics_writer.write( FORMATTER_3.format( stats.median() ) + "\t" );
2195 per_genome_domain_promiscuity_statistics_writer.write( ( int ) stats.getMin() + "\t" );
2196 per_genome_domain_promiscuity_statistics_writer.write( ( int ) stats.getMax() + "\t" );
2197 per_genome_domain_promiscuity_statistics_writer.write( stats.getN() + "\t" );
2198 final SortedSet<String> mpds = gwcd.getMostPromiscuosDomain();
2199 for( final String mpd : mpds ) {
2200 per_genome_domain_promiscuity_statistics_writer.write( mpd + " " );
2202 per_genome_domain_promiscuity_statistics_writer.write( ForesterUtil.LINE_SEPARATOR );
2204 catch ( final IOException e ) {
2205 ForesterUtil.fatalError( surfacing.PRG_NAME, e.getMessage() );
2207 if ( input_file_properties[ i ].length == 3 ) {
2208 ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote domain combination counts for \""
2209 + input_file_properties[ i ][ 0 ] + "\" (" + input_file_properties[ i ][ 1 ] + ", "
2210 + input_file_properties[ i ][ 2 ] + ") to: \"" + dc_outfile + "\"" );
2213 ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote domain combination counts for \""
2214 + input_file_properties[ i ][ 0 ] + "\" (" + input_file_properties[ i ][ 1 ] + ") to: \""
2215 + dc_outfile + "\"" );
2219 public static void writeDomainSimilaritiesToFile( final StringBuilder html_desc,
2220 final StringBuilder html_title,
2221 final Writer simple_tab_writer,
2222 final Writer single_writer,
2223 Map<Character, Writer> split_writers,
2224 final SortedSet<DomainSimilarity> similarities,
2225 final boolean treat_as_binary,
2226 final List<Species> species_order,
2227 final DomainSimilarity.PRINT_OPTION print_option,
2228 final DomainSimilarity.DomainSimilarityScoring scoring,
2229 final boolean verbose,
2230 final Map<String, Integer> tax_code_to_id_map,
2231 final Phylogeny phy,
2232 final Set<String> pos_filter_doms ) throws IOException {
2233 if ( ( single_writer != null ) && ( ( split_writers == null ) || split_writers.isEmpty() ) ) {
2234 split_writers = new HashMap<Character, Writer>();
2235 split_writers.put( '_', single_writer );
2237 switch ( print_option ) {
2238 case SIMPLE_TAB_DELIMITED:
2241 for( final Character key : split_writers.keySet() ) {
2242 final Writer w = split_writers.get( key );
2243 w.write( "<html>" );
2244 w.write( SurfacingConstants.NL );
2246 writeHtmlHead( w, "DC analysis (" + html_title + ") " + key.toString().toUpperCase() );
2249 writeHtmlHead( w, "DC analysis (" + html_title + ")" );
2251 w.write( SurfacingConstants.NL );
2252 w.write( "<body>" );
2253 w.write( SurfacingConstants.NL );
2254 w.write( html_desc.toString() );
2255 w.write( SurfacingConstants.NL );
2257 w.write( SurfacingConstants.NL );
2259 w.write( SurfacingConstants.NL );
2260 w.write( "<table>" );
2261 w.write( SurfacingConstants.NL );
2262 w.write( "<tr><td><b>Domains:</b></td></tr>" );
2263 w.write( SurfacingConstants.NL );
2268 for( final DomainSimilarity similarity : similarities ) {
2269 if ( ( species_order != null ) && !species_order.isEmpty() ) {
2270 ( similarity ).setSpeciesOrder( species_order );
2272 if ( single_writer != null ) {
2273 if ( !ForesterUtil.isEmpty( pos_filter_doms ) && pos_filter_doms.contains( similarity.getDomainId() ) ) {
2274 single_writer.write( "<tr><td><b><a href=\"#" + similarity.getDomainId()
2275 + "\"><span style=\"color:#00ff00\">" + similarity.getDomainId()
2276 + "</span></a></b></td></tr>" );
2279 single_writer.write( "<tr><td><b><a href=\"#" + similarity.getDomainId() + "\">"
2280 + similarity.getDomainId() + "</a></b></td></tr>" );
2282 single_writer.write( SurfacingConstants.NL );
2285 Writer local_writer = split_writers.get( ( similarity.getDomainId().charAt( 0 ) + "" ).toLowerCase()
2287 if ( local_writer == null ) {
2288 local_writer = split_writers.get( '0' );
2290 if ( !ForesterUtil.isEmpty( pos_filter_doms ) && pos_filter_doms.contains( similarity.getDomainId() ) ) {
2291 local_writer.write( "<tr><td><b><a href=\"#" + similarity.getDomainId()
2292 + "\"><span style=\"color:#00ff00\">" + similarity.getDomainId()
2293 + "</span></a></b></td></tr>" );
2296 local_writer.write( "<tr><td><b><a href=\"#" + similarity.getDomainId() + "\">"
2297 + similarity.getDomainId() + "</a></b></td></tr>" );
2299 local_writer.write( SurfacingConstants.NL );
2302 for( final Writer w : split_writers.values() ) {
2303 w.write( "</table>" );
2304 w.write( SurfacingConstants.NL );
2306 w.write( SurfacingConstants.NL );
2308 w.write( "<table>" );
2309 w.write( SurfacingConstants.NL );
2310 w.write( "<tr><td><b>" );
2311 w.write( "Species group colors:" );
2312 w.write( "</b></td></tr>" );
2313 w.write( SurfacingConstants.NL );
2314 writeColorLabels( "Deuterostomia", TaxonomyColors.DEUTEROSTOMIA_COLOR, w );
2315 writeColorLabels( "Protostomia", TaxonomyColors.PROTOSTOMIA_COLOR, w );
2316 writeColorLabels( "Cnidaria", TaxonomyColors.CNIDARIA_COLOR, w );
2317 writeColorLabels( "Placozoa", TaxonomyColors.PLACOZOA_COLOR, w );
2318 writeColorLabels( "Ctenophora (comb jellies)", TaxonomyColors.CTENOPHORA_COLOR, w );
2319 writeColorLabels( "Porifera (sponges)", TaxonomyColors.PORIFERA_COLOR, w );
2320 writeColorLabels( "Choanoflagellida", TaxonomyColors.CHOANOFLAGELLIDA, w );
2321 writeColorLabels( "Ichthyosporea & Filasterea", TaxonomyColors.ICHTHYOSPOREA_AND_FILASTEREA, w );
2322 writeColorLabels( "Dikarya (Ascomycota & Basidiomycota, so-called \"higher fungi\")",
2323 TaxonomyColors.DIKARYA_COLOR,
2325 writeColorLabels( "other Fungi", TaxonomyColors.OTHER_FUNGI_COLOR, w );
2326 writeColorLabels( "Nucleariidae and Fonticula group",
2327 TaxonomyColors.NUCLEARIIDAE_AND_FONTICULA_GROUP_COLOR,
2329 writeColorLabels( "Amoebozoa", TaxonomyColors.AMOEBOZOA_COLOR, w );
2330 writeColorLabels( "Embryophyta (plants)", TaxonomyColors.EMBRYOPHYTA_COLOR, w );
2331 writeColorLabels( "Chlorophyta (green algae)", TaxonomyColors.CHLOROPHYTA_COLOR, w );
2332 writeColorLabels( "Rhodophyta (red algae)", TaxonomyColors.RHODOPHYTA_COLOR, w );
2333 writeColorLabels( "Glaucocystophyce (Glaucophyta)", TaxonomyColors.GLAUCOPHYTA_COLOR, w );
2334 writeColorLabels( "Hacrobia (Cryptophyta & Haptophyceae & Centroheliozoa)",
2335 TaxonomyColors.HACROBIA_COLOR,
2337 writeColorLabels( "Stramenopiles (Chromophyta, heterokonts)", TaxonomyColors.STRAMENOPILES_COLOR, w );
2338 writeColorLabels( "Alveolata", TaxonomyColors.ALVEOLATA_COLOR, w );
2339 writeColorLabels( "Rhizaria", TaxonomyColors.RHIZARIA_COLOR, w );
2340 writeColorLabels( "Excavata", TaxonomyColors.EXCAVATA_COLOR, w );
2341 writeColorLabels( "Apusozoa", TaxonomyColors.APUSOZOA_COLOR, w );
2342 writeColorLabels( "Archaea", TaxonomyColors.ARCHAEA_COLOR, w );
2343 writeColorLabels( "Bacteria", TaxonomyColors.BACTERIA_COLOR, w );
2344 w.write( "</table>" );
2345 w.write( SurfacingConstants.NL );
2348 w.write( SurfacingConstants.NL );
2349 w.write( "<table>" );
2350 w.write( SurfacingConstants.NL );
2353 for( final DomainSimilarity similarity : similarities ) {
2354 if ( ( species_order != null ) && !species_order.isEmpty() ) {
2355 ( similarity ).setSpeciesOrder( species_order );
2357 if ( simple_tab_writer != null ) {
2358 simple_tab_writer.write( similarity.toStringBuffer( PRINT_OPTION.SIMPLE_TAB_DELIMITED,
2360 null ).toString() );
2362 if ( single_writer != null ) {
2363 single_writer.write( similarity.toStringBuffer( print_option, tax_code_to_id_map, phy ).toString() );
2364 single_writer.write( SurfacingConstants.NL );
2367 Writer local_writer = split_writers.get( ( similarity.getDomainId().charAt( 0 ) + "" ).toLowerCase()
2369 if ( local_writer == null ) {
2370 local_writer = split_writers.get( '0' );
2372 local_writer.write( similarity.toStringBuffer( print_option, tax_code_to_id_map, phy ).toString() );
2373 local_writer.write( SurfacingConstants.NL );
2376 switch ( print_option ) {
2378 for( final Writer w : split_writers.values() ) {
2379 w.write( SurfacingConstants.NL );
2380 w.write( "</table>" );
2381 w.write( SurfacingConstants.NL );
2382 w.write( "</font>" );
2383 w.write( SurfacingConstants.NL );
2384 w.write( "</body>" );
2385 w.write( SurfacingConstants.NL );
2386 w.write( "</html>" );
2387 w.write( SurfacingConstants.NL );
2393 for( final Writer w : split_writers.values() ) {
2398 public static void writeHtmlHead( final Writer w, final String title ) throws IOException {
2399 w.write( SurfacingConstants.NL );
2400 w.write( "<head>" );
2401 w.write( "<title>" );
2403 w.write( "</title>" );
2404 w.write( SurfacingConstants.NL );
2405 w.write( "<style>" );
2406 w.write( SurfacingConstants.NL );
2407 w.write( "a:visited { color : #000066; text-decoration : none; }" );
2408 w.write( SurfacingConstants.NL );
2409 w.write( "a:link { color : #000066; text-decoration : none; }" );
2410 w.write( SurfacingConstants.NL );
2411 w.write( "a:active { color : ##000066; text-decoration : none; }" );
2412 w.write( SurfacingConstants.NL );
2413 w.write( "a:hover { color : #FFFFFF; background-color : #000000; text-decoration : none; }" );
2414 w.write( SurfacingConstants.NL );
2416 w.write( "a.pl:visited { color : #505050; text-decoration : none; font-size: 7px;}" );
2417 w.write( SurfacingConstants.NL );
2418 w.write( "a.pl:link { color : #505050; text-decoration : none; font-size: 7px;}" );
2419 w.write( SurfacingConstants.NL );
2420 w.write( "a.pl:active { color : #505050; text-decoration : none; font-size: 7px;}" );
2421 w.write( SurfacingConstants.NL );
2422 w.write( "a.pl:hover { color : #FFFFFF; background-color : #000000; text-decoration : none; font-size: 7px;}" );
2423 w.write( SurfacingConstants.NL );
2425 w.write( "a.ps:visited { color : #707070; text-decoration : none; font-size: 7px;}" );
2426 w.write( SurfacingConstants.NL );
2427 w.write( "a.ps:link { color : #707070; text-decoration : none; font-size: 7px;}" );
2428 w.write( SurfacingConstants.NL );
2429 w.write( "a.ps:active { color : #707070; text-decoration : none; font-size: 7px;}" );
2430 w.write( SurfacingConstants.NL );
2431 w.write( "a.ps:hover { color : #FFFFFF; background-color : #000000; text-decoration : none; font-size: 7px;}" );
2432 w.write( SurfacingConstants.NL );
2434 w.write( "td { text-align: left; vertical-align: top; font-family: Verdana, Arial, Helvetica; font-size: 8pt}" );
2435 w.write( SurfacingConstants.NL );
2436 w.write( "h1 { color : #0000FF; font-family: Verdana, Arial, Helvetica; font-size: 18pt; font-weight: bold }" );
2437 w.write( SurfacingConstants.NL );
2438 w.write( "h2 { color : #0000FF; font-family: Verdana, Arial, Helvetica; font-size: 16pt; font-weight: bold }" );
2439 w.write( SurfacingConstants.NL );
2440 w.write( "</style>" );
2441 w.write( SurfacingConstants.NL );
2442 w.write( "</head>" );
2443 w.write( SurfacingConstants.NL );
2446 public static void writeMatrixToFile( final CharacterStateMatrix<?> matrix,
2447 final String filename,
2448 final Format format ) {
2449 final File outfile = new File( filename );
2450 checkForOutputFileWriteability( outfile );
2452 final BufferedWriter out = new BufferedWriter( new FileWriter( outfile ) );
2453 matrix.toWriter( out, format );
2457 catch ( final IOException e ) {
2458 ForesterUtil.fatalError( surfacing.PRG_NAME, e.getMessage() );
2460 ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote matrix: \"" + filename + "\"" );
2463 public static void writeMatrixToFile( final File matrix_outfile, final List<DistanceMatrix> matrices ) {
2464 checkForOutputFileWriteability( matrix_outfile );
2466 final BufferedWriter out = new BufferedWriter( new FileWriter( matrix_outfile ) );
2467 for( final DistanceMatrix distance_matrix : matrices ) {
2468 out.write( distance_matrix.toStringBuffer( DistanceMatrix.Format.PHYLIP ).toString() );
2469 out.write( ForesterUtil.LINE_SEPARATOR );
2474 catch ( final IOException e ) {
2475 ForesterUtil.fatalError( surfacing.PRG_NAME, e.getMessage() );
2477 ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote distance matrices to \"" + matrix_outfile + "\"" );
2480 public static void writePhylogenyToFile( final Phylogeny phylogeny, final String filename ) {
2481 final PhylogenyWriter writer = new PhylogenyWriter();
2483 writer.toPhyloXML( new File( filename ), phylogeny, 1 );
2485 catch ( final IOException e ) {
2486 ForesterUtil.printWarningMessage( surfacing.PRG_NAME, "failed to write phylogeny to \"" + filename + "\": "
2489 ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote phylogeny to \"" + filename + "\"" );
2492 public static void writePresentToNexus( final File output_file,
2493 final File positive_filter_file,
2494 final SortedSet<String> filter,
2495 final List<GenomeWideCombinableDomains> gwcd_list ) {
2497 writeMatrixToFile( DomainParsimonyCalculator.createMatrixOfDomainPresenceOrAbsence( gwcd_list,
2498 positive_filter_file == null ? null
2500 output_file + surfacing.DOMAINS_PRESENT_NEXUS,
2501 Format.NEXUS_BINARY );
2502 writeMatrixToFile( DomainParsimonyCalculator.createMatrixOfBinaryDomainCombinationPresenceOrAbsence( gwcd_list ),
2503 output_file + surfacing.BDC_PRESENT_NEXUS,
2504 Format.NEXUS_BINARY );
2506 catch ( final Exception e ) {
2507 ForesterUtil.fatalError( surfacing.PRG_NAME, e.getLocalizedMessage() );
2511 public static void writeProteinListsForAllSpecies( final File output_dir,
2512 final SortedMap<Species, List<Protein>> protein_lists_per_species,
2513 final List<GenomeWideCombinableDomains> gwcd_list,
2514 final double domain_e_cutoff ) {
2515 final SortedSet<String> all_domains = new TreeSet<String>();
2516 for( final GenomeWideCombinableDomains gwcd : gwcd_list ) {
2517 all_domains.addAll( gwcd.getAllDomainIds() );
2519 for( final String domain : all_domains ) {
2520 final File out = new File( output_dir + ForesterUtil.FILE_SEPARATOR + domain + surfacing.SEQ_EXTRACT_SUFFIX );
2521 checkForOutputFileWriteability( out );
2523 final Writer proteins_file_writer = new BufferedWriter( new FileWriter( out ) );
2524 extractProteinNames( protein_lists_per_species,
2526 proteins_file_writer,
2528 surfacing.LIMIT_SPEC_FOR_PROT_EX,
2530 proteins_file_writer.close();
2532 catch ( final IOException e ) {
2533 ForesterUtil.fatalError( surfacing.PRG_NAME, e.getLocalizedMessage() );
2535 ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote proteins list to \"" + out + "\"" );
2539 public static void writeTaxonomyLinks( final Writer writer,
2540 final String species,
2541 final Map<String, Integer> tax_code_to_id_map ) throws IOException {
2542 if ( ( species.length() > 1 ) && ( species.indexOf( '_' ) < 1 ) ) {
2543 writer.write( " [" );
2544 if ( ( tax_code_to_id_map != null ) && tax_code_to_id_map.containsKey( species ) ) {
2545 writer.write( "<a href=\"" + SurfacingConstants.UNIPROT_TAXONOMY_ID_LINK
2546 + tax_code_to_id_map.get( species ) + "\" target=\"taxonomy_window\">uniprot</a>" );
2549 writer.write( "<a href=\"" + SurfacingConstants.EOL_LINK + species
2550 + "\" target=\"taxonomy_window\">eol</a>" );
2551 writer.write( "|" );
2552 writer.write( "<a href=\"" + SurfacingConstants.GOOGLE_SCHOLAR_SEARCH + species
2553 + "\" target=\"taxonomy_window\">scholar</a>" );
2554 writer.write( "|" );
2555 writer.write( "<a href=\"" + SurfacingConstants.GOOGLE_WEB_SEARCH_LINK + species
2556 + "\" target=\"taxonomy_window\">google</a>" );
2558 writer.write( "]" );
2562 private final static void addToCountMap( final Map<String, Integer> map, final String s ) {
2563 if ( map.containsKey( s ) ) {
2564 map.put( s, map.get( s ) + 1 );
2571 private static void calculateIndependentDomainCombinationGains( final Phylogeny local_phylogeny_l,
2572 final String outfilename_for_counts,
2573 final String outfilename_for_dc,
2574 final String outfilename_for_dc_for_go_mapping,
2575 final String outfilename_for_dc_for_go_mapping_unique,
2576 final String outfilename_for_rank_counts,
2577 final String outfilename_for_ancestor_species_counts,
2578 final String outfilename_for_protein_stats,
2579 final Map<String, DescriptiveStatistics> protein_length_stats_by_dc,
2580 final Map<String, DescriptiveStatistics> domain_number_stats_by_dc,
2581 final Map<String, DescriptiveStatistics> domain_length_stats_by_domain ) {
2584 // if ( protein_length_stats_by_dc != null ) {
2585 // for( final Entry<?, DescriptiveStatistics> entry : protein_length_stats_by_dc.entrySet() ) {
2586 // System.out.print( entry.getKey().toString() );
2587 // System.out.print( ": " );
2588 // double[] a = entry.getValue().getDataAsDoubleArray();
2589 // for( int i = 0; i < a.length; i++ ) {
2590 // System.out.print( a[ i ] + " " );
2592 // System.out.println();
2595 // if ( domain_number_stats_by_dc != null ) {
2596 // for( final Entry<?, DescriptiveStatistics> entry : domain_number_stats_by_dc.entrySet() ) {
2597 // System.out.print( entry.getKey().toString() );
2598 // System.out.print( ": " );
2599 // double[] a = entry.getValue().getDataAsDoubleArray();
2600 // for( int i = 0; i < a.length; i++ ) {
2601 // System.out.print( a[ i ] + " " );
2603 // System.out.println();
2607 final BufferedWriter out_counts = new BufferedWriter( new FileWriter( outfilename_for_counts ) );
2608 final BufferedWriter out_dc = new BufferedWriter( new FileWriter( outfilename_for_dc ) );
2609 final BufferedWriter out_dc_for_go_mapping = new BufferedWriter( new FileWriter( outfilename_for_dc_for_go_mapping ) );
2610 final BufferedWriter out_dc_for_go_mapping_unique = new BufferedWriter( new FileWriter( outfilename_for_dc_for_go_mapping_unique ) );
2611 final SortedMap<String, Integer> dc_gain_counts = new TreeMap<String, Integer>();
2612 for( final PhylogenyNodeIterator it = local_phylogeny_l.iteratorPostorder(); it.hasNext(); ) {
2613 final PhylogenyNode n = it.next();
2614 final Set<String> gained_dc = n.getNodeData().getBinaryCharacters().getGainedCharacters();
2615 for( final String dc : gained_dc ) {
2616 if ( dc_gain_counts.containsKey( dc ) ) {
2617 dc_gain_counts.put( dc, dc_gain_counts.get( dc ) + 1 );
2620 dc_gain_counts.put( dc, 1 );
2624 final SortedMap<Integer, Integer> histogram = new TreeMap<Integer, Integer>();
2625 final SortedMap<Integer, StringBuilder> domain_lists = new TreeMap<Integer, StringBuilder>();
2626 final SortedMap<Integer, DescriptiveStatistics> dc_reapp_counts_to_protein_length_stats = new TreeMap<Integer, DescriptiveStatistics>();
2627 final SortedMap<Integer, DescriptiveStatistics> dc_reapp_counts_to_domain_number_stats = new TreeMap<Integer, DescriptiveStatistics>();
2628 final SortedMap<Integer, DescriptiveStatistics> dc_reapp_counts_to_domain_lengths_stats = new TreeMap<Integer, DescriptiveStatistics>();
2629 final SortedMap<Integer, PriorityQueue<String>> domain_lists_go = new TreeMap<Integer, PriorityQueue<String>>();
2630 final SortedMap<Integer, SortedSet<String>> domain_lists_go_unique = new TreeMap<Integer, SortedSet<String>>();
2631 final Set<String> dcs = dc_gain_counts.keySet();
2632 final SortedSet<String> more_than_once = new TreeSet<String>();
2633 DescriptiveStatistics gained_once_lengths_stats = new BasicDescriptiveStatistics();
2634 DescriptiveStatistics gained_once_domain_count_stats = new BasicDescriptiveStatistics();
2635 DescriptiveStatistics gained_multiple_times_lengths_stats = new BasicDescriptiveStatistics();
2636 final DescriptiveStatistics gained_multiple_times_domain_count_stats = new BasicDescriptiveStatistics();
2637 long gained_multiple_times_domain_length_sum = 0;
2638 long gained_once_domain_length_sum = 0;
2639 long gained_multiple_times_domain_length_count = 0;
2640 long gained_once_domain_length_count = 0;
2641 for( final String dc : dcs ) {
2642 final int count = dc_gain_counts.get( dc );
2643 if ( histogram.containsKey( count ) ) {
2644 histogram.put( count, histogram.get( count ) + 1 );
2645 domain_lists.get( count ).append( ", " + dc );
2646 domain_lists_go.get( count ).addAll( splitDomainCombination( dc ) );
2647 domain_lists_go_unique.get( count ).addAll( splitDomainCombination( dc ) );
2650 histogram.put( count, 1 );
2651 domain_lists.put( count, new StringBuilder( dc ) );
2652 final PriorityQueue<String> q = new PriorityQueue<String>();
2653 q.addAll( splitDomainCombination( dc ) );
2654 domain_lists_go.put( count, q );
2655 final SortedSet<String> set = new TreeSet<String>();
2656 set.addAll( splitDomainCombination( dc ) );
2657 domain_lists_go_unique.put( count, set );
2659 if ( protein_length_stats_by_dc != null ) {
2660 if ( !dc_reapp_counts_to_protein_length_stats.containsKey( count ) ) {
2661 dc_reapp_counts_to_protein_length_stats.put( count, new BasicDescriptiveStatistics() );
2663 dc_reapp_counts_to_protein_length_stats.get( count ).addValue( protein_length_stats_by_dc.get( dc )
2664 .arithmeticMean() );
2666 if ( domain_number_stats_by_dc != null ) {
2667 if ( !dc_reapp_counts_to_domain_number_stats.containsKey( count ) ) {
2668 dc_reapp_counts_to_domain_number_stats.put( count, new BasicDescriptiveStatistics() );
2670 dc_reapp_counts_to_domain_number_stats.get( count ).addValue( domain_number_stats_by_dc.get( dc )
2671 .arithmeticMean() );
2673 if ( domain_length_stats_by_domain != null ) {
2674 if ( !dc_reapp_counts_to_domain_lengths_stats.containsKey( count ) ) {
2675 dc_reapp_counts_to_domain_lengths_stats.put( count, new BasicDescriptiveStatistics() );
2677 final String[] ds = dc.split( "=" );
2678 dc_reapp_counts_to_domain_lengths_stats.get( count ).addValue( domain_length_stats_by_domain
2679 .get( ds[ 0 ] ).arithmeticMean() );
2680 dc_reapp_counts_to_domain_lengths_stats.get( count ).addValue( domain_length_stats_by_domain
2681 .get( ds[ 1 ] ).arithmeticMean() );
2684 more_than_once.add( dc );
2685 if ( protein_length_stats_by_dc != null ) {
2686 final DescriptiveStatistics s = protein_length_stats_by_dc.get( dc );
2687 for( final double element : s.getData() ) {
2688 gained_multiple_times_lengths_stats.addValue( element );
2691 if ( domain_number_stats_by_dc != null ) {
2692 final DescriptiveStatistics s = domain_number_stats_by_dc.get( dc );
2693 for( final double element : s.getData() ) {
2694 gained_multiple_times_domain_count_stats.addValue( element );
2697 if ( domain_length_stats_by_domain != null ) {
2698 final String[] ds = dc.split( "=" );
2699 final DescriptiveStatistics s0 = domain_length_stats_by_domain.get( ds[ 0 ] );
2700 final DescriptiveStatistics s1 = domain_length_stats_by_domain.get( ds[ 1 ] );
2701 for( final double element : s0.getData() ) {
2702 gained_multiple_times_domain_length_sum += element;
2703 ++gained_multiple_times_domain_length_count;
2705 for( final double element : s1.getData() ) {
2706 gained_multiple_times_domain_length_sum += element;
2707 ++gained_multiple_times_domain_length_count;
2712 if ( protein_length_stats_by_dc != null ) {
2713 final DescriptiveStatistics s = protein_length_stats_by_dc.get( dc );
2714 for( final double element : s.getData() ) {
2715 gained_once_lengths_stats.addValue( element );
2718 if ( domain_number_stats_by_dc != null ) {
2719 final DescriptiveStatistics s = domain_number_stats_by_dc.get( dc );
2720 for( final double element : s.getData() ) {
2721 gained_once_domain_count_stats.addValue( element );
2724 if ( domain_length_stats_by_domain != null ) {
2725 final String[] ds = dc.split( "=" );
2726 final DescriptiveStatistics s0 = domain_length_stats_by_domain.get( ds[ 0 ] );
2727 final DescriptiveStatistics s1 = domain_length_stats_by_domain.get( ds[ 1 ] );
2728 for( final double element : s0.getData() ) {
2729 gained_once_domain_length_sum += element;
2730 ++gained_once_domain_length_count;
2732 for( final double element : s1.getData() ) {
2733 gained_once_domain_length_sum += element;
2734 ++gained_once_domain_length_count;
2739 final Set<Integer> histogram_keys = histogram.keySet();
2740 for( final Integer histogram_key : histogram_keys ) {
2741 final int count = histogram.get( histogram_key );
2742 final StringBuilder dc = domain_lists.get( histogram_key );
2743 out_counts.write( histogram_key + "\t" + count + ForesterUtil.LINE_SEPARATOR );
2744 out_dc.write( histogram_key + "\t" + dc + ForesterUtil.LINE_SEPARATOR );
2745 out_dc_for_go_mapping.write( "#" + histogram_key + ForesterUtil.LINE_SEPARATOR );
2746 final Object[] sorted = domain_lists_go.get( histogram_key ).toArray();
2747 Arrays.sort( sorted );
2748 for( final Object domain : sorted ) {
2749 out_dc_for_go_mapping.write( domain + ForesterUtil.LINE_SEPARATOR );
2751 out_dc_for_go_mapping_unique.write( "#" + histogram_key + ForesterUtil.LINE_SEPARATOR );
2752 for( final String domain : domain_lists_go_unique.get( histogram_key ) ) {
2753 out_dc_for_go_mapping_unique.write( domain + ForesterUtil.LINE_SEPARATOR );
2758 out_dc_for_go_mapping.close();
2759 out_dc_for_go_mapping_unique.close();
2760 final SortedMap<String, Integer> lca_rank_counts = new TreeMap<String, Integer>();
2761 final SortedMap<String, Integer> lca_ancestor_species_counts = new TreeMap<String, Integer>();
2762 for( final String dc : more_than_once ) {
2763 final List<PhylogenyNode> nodes = new ArrayList<PhylogenyNode>();
2764 for( final PhylogenyNodeIterator it = local_phylogeny_l.iteratorExternalForward(); it.hasNext(); ) {
2765 final PhylogenyNode n = it.next();
2766 if ( n.getNodeData().getBinaryCharacters().getGainedCharacters().contains( dc ) ) {
2770 for( int i = 0; i < ( nodes.size() - 1 ); ++i ) {
2771 for( int j = i + 1; j < nodes.size(); ++j ) {
2772 final PhylogenyNode lca = PhylogenyMethods.calculateLCA( nodes.get( i ), nodes.get( j ) );
2773 String rank = "unknown";
2774 if ( lca.getNodeData().isHasTaxonomy()
2775 && !ForesterUtil.isEmpty( lca.getNodeData().getTaxonomy().getRank() ) ) {
2776 rank = lca.getNodeData().getTaxonomy().getRank();
2778 addToCountMap( lca_rank_counts, rank );
2780 if ( lca.getNodeData().isHasTaxonomy()
2781 && !ForesterUtil.isEmpty( lca.getNodeData().getTaxonomy().getScientificName() ) ) {
2782 lca_species = lca.getNodeData().getTaxonomy().getScientificName();
2784 else if ( lca.getNodeData().isHasTaxonomy()
2785 && !ForesterUtil.isEmpty( lca.getNodeData().getTaxonomy().getCommonName() ) ) {
2786 lca_species = lca.getNodeData().getTaxonomy().getCommonName();
2789 lca_species = lca.getName();
2791 addToCountMap( lca_ancestor_species_counts, lca_species );
2795 final BufferedWriter out_for_rank_counts = new BufferedWriter( new FileWriter( outfilename_for_rank_counts ) );
2796 final BufferedWriter out_for_ancestor_species_counts = new BufferedWriter( new FileWriter( outfilename_for_ancestor_species_counts ) );
2797 ForesterUtil.map2writer( out_for_rank_counts, lca_rank_counts, "\t", ForesterUtil.LINE_SEPARATOR );
2798 ForesterUtil.map2writer( out_for_ancestor_species_counts,
2799 lca_ancestor_species_counts,
2801 ForesterUtil.LINE_SEPARATOR );
2802 out_for_rank_counts.close();
2803 out_for_ancestor_species_counts.close();
2804 if ( !ForesterUtil.isEmpty( outfilename_for_protein_stats )
2805 && ( ( domain_length_stats_by_domain != null ) || ( protein_length_stats_by_dc != null ) || ( domain_number_stats_by_dc != null ) ) ) {
2806 final BufferedWriter w = new BufferedWriter( new FileWriter( outfilename_for_protein_stats ) );
2807 w.write( "Domain Lengths: " );
2809 if ( domain_length_stats_by_domain != null ) {
2810 for( final Entry<Integer, DescriptiveStatistics> entry : dc_reapp_counts_to_domain_lengths_stats
2812 w.write( entry.getKey().toString() );
2813 w.write( "\t" + entry.getValue().arithmeticMean() );
2814 w.write( "\t" + entry.getValue().median() );
2821 w.write( "Protein Lengths: " );
2823 if ( protein_length_stats_by_dc != null ) {
2824 for( final Entry<Integer, DescriptiveStatistics> entry : dc_reapp_counts_to_protein_length_stats
2826 w.write( entry.getKey().toString() );
2827 w.write( "\t" + entry.getValue().arithmeticMean() );
2828 w.write( "\t" + entry.getValue().median() );
2835 w.write( "Number of domains: " );
2837 if ( domain_number_stats_by_dc != null ) {
2838 for( final Entry<Integer, DescriptiveStatistics> entry : dc_reapp_counts_to_domain_number_stats
2840 w.write( entry.getKey().toString() );
2841 w.write( "\t" + entry.getValue().arithmeticMean() );
2842 w.write( "\t" + entry.getValue().median() );
2849 w.write( "Gained once, domain lengths:" );
2851 w.write( "N: " + gained_once_domain_length_count );
2853 w.write( "Avg: " + ( ( double ) gained_once_domain_length_sum / gained_once_domain_length_count ) );
2856 w.write( "Gained multiple times, domain lengths:" );
2858 w.write( "N: " + gained_multiple_times_domain_length_count );
2861 + ( ( double ) gained_multiple_times_domain_length_sum / gained_multiple_times_domain_length_count ) );
2866 w.write( "Gained once, protein lengths:" );
2868 w.write( gained_once_lengths_stats.toString() );
2869 gained_once_lengths_stats = null;
2872 w.write( "Gained once, domain counts:" );
2874 w.write( gained_once_domain_count_stats.toString() );
2875 gained_once_domain_count_stats = null;
2878 w.write( "Gained multiple times, protein lengths:" );
2880 w.write( gained_multiple_times_lengths_stats.toString() );
2881 gained_multiple_times_lengths_stats = null;
2884 w.write( "Gained multiple times, domain counts:" );
2886 w.write( gained_multiple_times_domain_count_stats.toString() );
2891 catch ( final IOException e ) {
2892 ForesterUtil.printWarningMessage( surfacing.PRG_NAME, "Failure to write: " + e );
2894 ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote independent domain combination gains fitch counts to ["
2895 + outfilename_for_counts + "]" );
2896 ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote independent domain combination gains fitch lists to ["
2897 + outfilename_for_dc + "]" );
2898 ForesterUtil.programMessage( surfacing.PRG_NAME,
2899 "Wrote independent domain combination gains fitch lists to (for GO mapping) ["
2900 + outfilename_for_dc_for_go_mapping + "]" );
2901 ForesterUtil.programMessage( surfacing.PRG_NAME,
2902 "Wrote independent domain combination gains fitch lists to (for GO mapping, unique) ["
2903 + outfilename_for_dc_for_go_mapping_unique + "]" );
2906 private static SortedSet<String> collectAllDomainsChangedOnSubtree( final PhylogenyNode subtree_root,
2907 final boolean get_gains ) {
2908 final SortedSet<String> domains = new TreeSet<String>();
2909 for( final PhylogenyNode descendant : PhylogenyMethods.getAllDescendants( subtree_root ) ) {
2910 final BinaryCharacters chars = descendant.getNodeData().getBinaryCharacters();
2912 domains.addAll( chars.getGainedCharacters() );
2915 domains.addAll( chars.getLostCharacters() );
2921 private static File createBaseDirForPerNodeDomainFiles( final String base_dir,
2922 final boolean domain_combinations,
2923 final CharacterStateMatrix.GainLossStates state,
2924 final String outfile ) {
2925 File per_node_go_mapped_domain_gain_loss_files_base_dir = new File( new File( outfile ).getParent()
2926 + ForesterUtil.FILE_SEPARATOR + base_dir );
2927 if ( !per_node_go_mapped_domain_gain_loss_files_base_dir.exists() ) {
2928 per_node_go_mapped_domain_gain_loss_files_base_dir.mkdir();
2930 if ( domain_combinations ) {
2931 per_node_go_mapped_domain_gain_loss_files_base_dir = new File( per_node_go_mapped_domain_gain_loss_files_base_dir
2932 + ForesterUtil.FILE_SEPARATOR + "DC" );
2935 per_node_go_mapped_domain_gain_loss_files_base_dir = new File( per_node_go_mapped_domain_gain_loss_files_base_dir
2936 + ForesterUtil.FILE_SEPARATOR + "DOMAINS" );
2938 if ( !per_node_go_mapped_domain_gain_loss_files_base_dir.exists() ) {
2939 per_node_go_mapped_domain_gain_loss_files_base_dir.mkdir();
2941 if ( state == GainLossStates.GAIN ) {
2942 per_node_go_mapped_domain_gain_loss_files_base_dir = new File( per_node_go_mapped_domain_gain_loss_files_base_dir
2943 + ForesterUtil.FILE_SEPARATOR + "GAINS" );
2945 else if ( state == GainLossStates.LOSS ) {
2946 per_node_go_mapped_domain_gain_loss_files_base_dir = new File( per_node_go_mapped_domain_gain_loss_files_base_dir
2947 + ForesterUtil.FILE_SEPARATOR + "LOSSES" );
2950 per_node_go_mapped_domain_gain_loss_files_base_dir = new File( per_node_go_mapped_domain_gain_loss_files_base_dir
2951 + ForesterUtil.FILE_SEPARATOR + "PRESENT" );
2953 if ( !per_node_go_mapped_domain_gain_loss_files_base_dir.exists() ) {
2954 per_node_go_mapped_domain_gain_loss_files_base_dir.mkdir();
2956 return per_node_go_mapped_domain_gain_loss_files_base_dir;
2959 private static SortedSet<BinaryDomainCombination> createSetOfAllBinaryDomainCombinationsPerGenome( final GenomeWideCombinableDomains gwcd ) {
2960 final SortedMap<String, CombinableDomains> cds = gwcd.getAllCombinableDomainsIds();
2961 final SortedSet<BinaryDomainCombination> binary_combinations = new TreeSet<BinaryDomainCombination>();
2962 for( final String domain_id : cds.keySet() ) {
2963 final CombinableDomains cd = cds.get( domain_id );
2964 binary_combinations.addAll( cd.toBinaryDomainCombinations() );
2966 return binary_combinations;
2969 private static void printSomeStats( final DescriptiveStatistics stats, final AsciiHistogram histo, final Writer w )
2970 throws IOException {
2973 w.write( SurfacingConstants.NL );
2974 w.write( "<tt><pre>" );
2975 w.write( SurfacingConstants.NL );
2976 if ( histo != null ) {
2977 w.write( histo.toStringBuffer( 20, '|', 40, 5 ).toString() );
2978 w.write( SurfacingConstants.NL );
2980 w.write( "</pre></tt>" );
2981 w.write( SurfacingConstants.NL );
2982 w.write( "<table>" );
2983 w.write( SurfacingConstants.NL );
2984 w.write( "<tr><td>N: </td><td>" + stats.getN() + "</td></tr>" );
2985 w.write( SurfacingConstants.NL );
2986 w.write( "<tr><td>Min: </td><td>" + stats.getMin() + "</td></tr>" );
2987 w.write( SurfacingConstants.NL );
2988 w.write( "<tr><td>Max: </td><td>" + stats.getMax() + "</td></tr>" );
2989 w.write( SurfacingConstants.NL );
2990 w.write( "<tr><td>Mean: </td><td>" + stats.arithmeticMean() + "</td></tr>" );
2991 w.write( SurfacingConstants.NL );
2992 if ( stats.getN() > 1 ) {
2993 w.write( "<tr><td>SD: </td><td>" + stats.sampleStandardDeviation() + "</td></tr>" );
2996 w.write( "<tr><td>SD: </td><td>n/a</td></tr>" );
2998 w.write( SurfacingConstants.NL );
2999 w.write( "</table>" );
3000 w.write( SurfacingConstants.NL );
3002 w.write( SurfacingConstants.NL );
3005 private static List<String> splitDomainCombination( final String dc ) {
3006 final String[] s = dc.split( "=" );
3007 if ( s.length != 2 ) {
3008 ForesterUtil.printErrorMessage( surfacing.PRG_NAME, "Stringyfied domain combination has illegal format: "
3012 final List<String> l = new ArrayList<String>( 2 );
3018 private static void writeAllEncounteredPfamsToFile( final Map<String, List<GoId>> domain_id_to_go_ids_map,
3019 final Map<GoId, GoTerm> go_id_to_term_map,
3020 final String outfile_name,
3021 final SortedSet<String> all_pfams_encountered ) {
3022 final File all_pfams_encountered_file = new File( outfile_name + surfacing.ALL_PFAMS_ENCOUNTERED_SUFFIX );
3023 final File all_pfams_encountered_with_go_annotation_file = new File( outfile_name
3024 + surfacing.ALL_PFAMS_ENCOUNTERED_WITH_GO_ANNOTATION_SUFFIX );
3025 final File encountered_pfams_summary_file = new File( outfile_name + surfacing.ENCOUNTERED_PFAMS_SUMMARY_SUFFIX );
3026 int biological_process_counter = 0;
3027 int cellular_component_counter = 0;
3028 int molecular_function_counter = 0;
3029 int pfams_with_mappings_counter = 0;
3030 int pfams_without_mappings_counter = 0;
3031 int pfams_without_mappings_to_bp_or_mf_counter = 0;
3032 int pfams_with_mappings_to_bp_or_mf_counter = 0;
3034 final Writer all_pfams_encountered_writer = new BufferedWriter( new FileWriter( all_pfams_encountered_file ) );
3035 final Writer all_pfams_encountered_with_go_annotation_writer = new BufferedWriter( new FileWriter( all_pfams_encountered_with_go_annotation_file ) );
3036 final Writer summary_writer = new BufferedWriter( new FileWriter( encountered_pfams_summary_file ) );
3037 summary_writer.write( "# Pfam to GO mapping summary" );
3038 summary_writer.write( ForesterUtil.LINE_SEPARATOR );
3039 summary_writer.write( "# Actual summary is at the end of this file." );
3040 summary_writer.write( ForesterUtil.LINE_SEPARATOR );
3041 summary_writer.write( "# Encountered Pfams without a GO mapping:" );
3042 summary_writer.write( ForesterUtil.LINE_SEPARATOR );
3043 for( final String pfam : all_pfams_encountered ) {
3044 all_pfams_encountered_writer.write( pfam );
3045 all_pfams_encountered_writer.write( ForesterUtil.LINE_SEPARATOR );
3046 final String domain_id = new String( pfam );
3047 if ( domain_id_to_go_ids_map.containsKey( domain_id ) ) {
3048 ++pfams_with_mappings_counter;
3049 all_pfams_encountered_with_go_annotation_writer.write( pfam );
3050 all_pfams_encountered_with_go_annotation_writer.write( ForesterUtil.LINE_SEPARATOR );
3051 final List<GoId> go_ids = domain_id_to_go_ids_map.get( domain_id );
3052 boolean maps_to_bp = false;
3053 boolean maps_to_cc = false;
3054 boolean maps_to_mf = false;
3055 for( final GoId go_id : go_ids ) {
3056 final GoTerm go_term = go_id_to_term_map.get( go_id );
3057 if ( go_term.getGoNameSpace().isBiologicalProcess() ) {
3060 else if ( go_term.getGoNameSpace().isCellularComponent() ) {
3063 else if ( go_term.getGoNameSpace().isMolecularFunction() ) {
3068 ++biological_process_counter;
3071 ++cellular_component_counter;
3074 ++molecular_function_counter;
3076 if ( maps_to_bp || maps_to_mf ) {
3077 ++pfams_with_mappings_to_bp_or_mf_counter;
3080 ++pfams_without_mappings_to_bp_or_mf_counter;
3084 ++pfams_without_mappings_to_bp_or_mf_counter;
3085 ++pfams_without_mappings_counter;
3086 summary_writer.write( pfam );
3087 summary_writer.write( ForesterUtil.LINE_SEPARATOR );
3090 all_pfams_encountered_writer.close();
3091 all_pfams_encountered_with_go_annotation_writer.close();
3092 ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote all [" + all_pfams_encountered.size()
3093 + "] encountered Pfams to: \"" + all_pfams_encountered_file + "\"" );
3094 ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote all [" + pfams_with_mappings_counter
3095 + "] encountered Pfams with GO mappings to: \"" + all_pfams_encountered_with_go_annotation_file
3097 ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote summary (including all ["
3098 + pfams_without_mappings_counter + "] encountered Pfams without GO mappings) to: \""
3099 + encountered_pfams_summary_file + "\"" );
3100 ForesterUtil.programMessage( surfacing.PRG_NAME, "Sum of Pfams encountered : "
3101 + all_pfams_encountered.size() );
3102 ForesterUtil.programMessage( surfacing.PRG_NAME, "Pfams without a mapping : "
3103 + pfams_without_mappings_counter + " ["
3104 + ( ( 100 * pfams_without_mappings_counter ) / all_pfams_encountered.size() ) + "%]" );
3105 ForesterUtil.programMessage( surfacing.PRG_NAME, "Pfams without mapping to proc. or func. : "
3106 + pfams_without_mappings_to_bp_or_mf_counter + " ["
3107 + ( ( 100 * pfams_without_mappings_to_bp_or_mf_counter ) / all_pfams_encountered.size() ) + "%]" );
3108 ForesterUtil.programMessage( surfacing.PRG_NAME, "Pfams with a mapping : "
3109 + pfams_with_mappings_counter + " ["
3110 + ( ( 100 * pfams_with_mappings_counter ) / all_pfams_encountered.size() ) + "%]" );
3111 ForesterUtil.programMessage( surfacing.PRG_NAME, "Pfams with a mapping to proc. or func. : "
3112 + pfams_with_mappings_to_bp_or_mf_counter + " ["
3113 + ( ( 100 * pfams_with_mappings_to_bp_or_mf_counter ) / all_pfams_encountered.size() ) + "%]" );
3114 ForesterUtil.programMessage( surfacing.PRG_NAME, "Pfams with mapping to biological process: "
3115 + biological_process_counter + " ["
3116 + ( ( 100 * biological_process_counter ) / all_pfams_encountered.size() ) + "%]" );
3117 ForesterUtil.programMessage( surfacing.PRG_NAME, "Pfams with mapping to molecular function: "
3118 + molecular_function_counter + " ["
3119 + ( ( 100 * molecular_function_counter ) / all_pfams_encountered.size() ) + "%]" );
3120 ForesterUtil.programMessage( surfacing.PRG_NAME, "Pfams with mapping to cellular component: "
3121 + cellular_component_counter + " ["
3122 + ( ( 100 * cellular_component_counter ) / all_pfams_encountered.size() ) + "%]" );
3123 summary_writer.write( ForesterUtil.LINE_SEPARATOR );
3124 summary_writer.write( "# Sum of Pfams encountered : " + all_pfams_encountered.size() );
3125 summary_writer.write( ForesterUtil.LINE_SEPARATOR );
3126 summary_writer.write( "# Pfams without a mapping : " + pfams_without_mappings_counter
3127 + " [" + ( ( 100 * pfams_without_mappings_counter ) / all_pfams_encountered.size() ) + "%]" );
3128 summary_writer.write( ForesterUtil.LINE_SEPARATOR );
3129 summary_writer.write( "# Pfams without mapping to proc. or func. : "
3130 + pfams_without_mappings_to_bp_or_mf_counter + " ["
3131 + ( ( 100 * pfams_without_mappings_to_bp_or_mf_counter ) / all_pfams_encountered.size() ) + "%]" );
3132 summary_writer.write( ForesterUtil.LINE_SEPARATOR );
3133 summary_writer.write( "# Pfams with a mapping : " + pfams_with_mappings_counter + " ["
3134 + ( ( 100 * pfams_with_mappings_counter ) / all_pfams_encountered.size() ) + "%]" );
3135 summary_writer.write( ForesterUtil.LINE_SEPARATOR );
3136 summary_writer.write( "# Pfams with a mapping to proc. or func. : "
3137 + pfams_with_mappings_to_bp_or_mf_counter + " ["
3138 + ( ( 100 * pfams_with_mappings_to_bp_or_mf_counter ) / all_pfams_encountered.size() ) + "%]" );
3139 summary_writer.write( ForesterUtil.LINE_SEPARATOR );
3140 summary_writer.write( "# Pfams with mapping to biological process: " + biological_process_counter + " ["
3141 + ( ( 100 * biological_process_counter ) / all_pfams_encountered.size() ) + "%]" );
3142 summary_writer.write( ForesterUtil.LINE_SEPARATOR );
3143 summary_writer.write( "# Pfams with mapping to molecular function: " + molecular_function_counter + " ["
3144 + ( ( 100 * molecular_function_counter ) / all_pfams_encountered.size() ) + "%]" );
3145 summary_writer.write( ForesterUtil.LINE_SEPARATOR );
3146 summary_writer.write( "# Pfams with mapping to cellular component: " + cellular_component_counter + " ["
3147 + ( ( 100 * cellular_component_counter ) / all_pfams_encountered.size() ) + "%]" );
3148 summary_writer.write( ForesterUtil.LINE_SEPARATOR );
3149 summary_writer.close();
3151 catch ( final IOException e ) {
3152 ForesterUtil.printWarningMessage( surfacing.PRG_NAME, "Failure to write: " + e );
3156 private final static void writeColorLabels( final String l, final Color c, final Writer w ) throws IOException {
3157 w.write( "<tr><td><b><span style=\"color:" );
3158 w.write( String.format( "#%02x%02x%02x", c.getRed(), c.getGreen(), c.getBlue() ) );
3161 w.write( "</span></b></td></tr>" );
3162 w.write( SurfacingConstants.NL );
3165 private static void writeDomainData( final Map<String, List<GoId>> domain_id_to_go_ids_map,
3166 final Map<GoId, GoTerm> go_id_to_term_map,
3167 final GoNameSpace go_namespace_limit,
3169 final String domain_0,
3170 final String domain_1,
3171 final String prefix_for_html,
3172 final String character_separator_for_non_html_output,
3173 final Map<String, Set<String>>[] domain_id_to_secondary_features_maps,
3174 final Set<GoId> all_go_ids ) throws IOException {
3175 boolean any_go_annotation_present = false;
3176 boolean first_has_no_go = false;
3177 int domain_count = 2; // To distinguish between domains and binary domain combinations.
3178 if ( ForesterUtil.isEmpty( domain_1 ) ) {
3181 // The following has a difficult to understand logic.
3182 for( int d = 0; d < domain_count; ++d ) {
3183 List<GoId> go_ids = null;
3184 boolean go_annotation_present = false;
3186 if ( domain_id_to_go_ids_map.containsKey( domain_0 ) ) {
3187 go_annotation_present = true;
3188 any_go_annotation_present = true;
3189 go_ids = domain_id_to_go_ids_map.get( domain_0 );
3192 first_has_no_go = true;
3196 if ( domain_id_to_go_ids_map.containsKey( domain_1 ) ) {
3197 go_annotation_present = true;
3198 any_go_annotation_present = true;
3199 go_ids = domain_id_to_go_ids_map.get( domain_1 );
3202 if ( go_annotation_present ) {
3203 boolean first = ( ( d == 0 ) || ( ( d == 1 ) && first_has_no_go ) );
3204 for( final GoId go_id : go_ids ) {
3205 out.write( "<tr>" );
3208 writeDomainIdsToHtml( out,
3212 domain_id_to_secondary_features_maps );
3215 out.write( "<td></td>" );
3217 if ( !go_id_to_term_map.containsKey( go_id ) ) {
3218 throw new IllegalArgumentException( "GO-id [" + go_id + "] not found in GO-id to GO-term map" );
3220 final GoTerm go_term = go_id_to_term_map.get( go_id );
3221 if ( ( go_namespace_limit == null ) || go_namespace_limit.equals( go_term.getGoNameSpace() ) ) {
3222 // final String top = GoUtils.getPenultimateGoTerm( go_term, go_id_to_term_map ).getName();
3223 final String go_id_str = go_id.getId();
3224 out.write( "<td>" );
3225 out.write( "<a href=\"" + SurfacingConstants.AMIGO_LINK + go_id_str
3226 + "\" target=\"amigo_window\">" + go_id_str + "</a>" );
3227 out.write( "</td><td>" );
3228 out.write( go_term.getName() );
3229 if ( domain_count == 2 ) {
3230 out.write( " (" + d + ")" );
3232 out.write( "</td><td>" );
3233 // out.write( top );
3234 // out.write( "</td><td>" );
3236 out.write( go_term.getGoNameSpace().toShortString() );
3238 out.write( "</td>" );
3239 if ( all_go_ids != null ) {
3240 all_go_ids.add( go_id );
3244 out.write( "<td>" );
3245 out.write( "</td><td>" );
3246 out.write( "</td><td>" );
3247 out.write( "</td><td>" );
3248 out.write( "</td>" );
3250 out.write( "</tr>" );
3251 out.write( SurfacingConstants.NL );
3254 } // for( int d = 0; d < domain_count; ++d )
3255 if ( !any_go_annotation_present ) {
3256 out.write( "<tr>" );
3257 writeDomainIdsToHtml( out, domain_0, domain_1, prefix_for_html, domain_id_to_secondary_features_maps );
3258 out.write( "<td>" );
3259 out.write( "</td><td>" );
3260 out.write( "</td><td>" );
3261 out.write( "</td><td>" );
3262 out.write( "</td>" );
3263 out.write( "</tr>" );
3264 out.write( SurfacingConstants.NL );
3268 private static void writeDomainIdsToHtml( final Writer out,
3269 final String domain_0,
3270 final String domain_1,
3271 final String prefix_for_detailed_html,
3272 final Map<String, Set<String>>[] domain_id_to_secondary_features_maps )
3273 throws IOException {
3274 out.write( "<td>" );
3275 if ( !ForesterUtil.isEmpty( prefix_for_detailed_html ) ) {
3276 out.write( prefix_for_detailed_html );
3279 out.write( "<a href=\"" + SurfacingConstants.PFAM_FAMILY_ID_LINK + domain_0 + "\">" + domain_0 + "</a>" );
3280 out.write( "</td>" );
3283 private static void writeDomainsToIndividualFilePerTreeNode( final Writer individual_files_writer,
3284 final String domain_0,
3285 final String domain_1 ) throws IOException {
3286 individual_files_writer.write( domain_0 );
3287 individual_files_writer.write( ForesterUtil.LINE_SEPARATOR );
3288 if ( !ForesterUtil.isEmpty( domain_1 ) ) {
3289 individual_files_writer.write( domain_1 );
3290 individual_files_writer.write( ForesterUtil.LINE_SEPARATOR );
3294 private static void writePfamsToFile( final String outfile_name, final SortedSet<String> pfams ) {
3296 final Writer writer = new BufferedWriter( new FileWriter( new File( outfile_name ) ) );
3297 for( final String pfam : pfams ) {
3298 writer.write( pfam );
3299 writer.write( ForesterUtil.LINE_SEPARATOR );
3302 ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote " + pfams.size() + " pfams to [" + outfile_name
3305 catch ( final IOException e ) {
3306 ForesterUtil.printWarningMessage( surfacing.PRG_NAME, "Failure to write: " + e );
3310 private static void writeToNexus( final String outfile_name,
3311 final CharacterStateMatrix<BinaryStates> matrix,
3312 final Phylogeny phylogeny ) {
3313 if ( !( matrix instanceof BasicCharacterStateMatrix ) ) {
3314 throw new IllegalArgumentException( "can only write matrices of type [" + BasicCharacterStateMatrix.class
3317 final BasicCharacterStateMatrix<BinaryStates> my_matrix = ( org.forester.evoinference.matrix.character.BasicCharacterStateMatrix<BinaryStates> ) matrix;
3318 final List<Phylogeny> phylogenies = new ArrayList<Phylogeny>( 1 );
3319 phylogenies.add( phylogeny );
3321 final BufferedWriter w = new BufferedWriter( new FileWriter( outfile_name ) );
3322 w.write( NexusConstants.NEXUS );
3323 w.write( ForesterUtil.LINE_SEPARATOR );
3324 my_matrix.writeNexusTaxaBlock( w );
3325 my_matrix.writeNexusBinaryChractersBlock( w );
3326 PhylogenyWriter.writeNexusTreesBlock( w, phylogenies, NH_CONVERSION_SUPPORT_VALUE_STYLE.NONE );
3329 ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote Nexus file: \"" + outfile_name + "\"" );
3331 catch ( final IOException e ) {
3332 ForesterUtil.fatalError( surfacing.PRG_NAME, e.getMessage() );
3336 private static void writeToNexus( final String outfile_name,
3337 final DomainParsimonyCalculator domain_parsimony,
3338 final Phylogeny phylogeny ) {
3339 writeToNexus( outfile_name + surfacing.NEXUS_EXTERNAL_DOMAINS,
3340 domain_parsimony.createMatrixOfDomainPresenceOrAbsence(),
3342 writeToNexus( outfile_name + surfacing.NEXUS_EXTERNAL_DOMAIN_COMBINATIONS,
3343 domain_parsimony.createMatrixOfBinaryDomainCombinationPresenceOrAbsence(),
3347 final static class DomainComparator implements Comparator<Domain> {
3349 final private boolean _ascending;
3351 public DomainComparator( final boolean ascending ) {
3352 _ascending = ascending;
3356 public final int compare( final Domain d0, final Domain d1 ) {
3357 if ( d0.getFrom() < d1.getFrom() ) {
3358 return _ascending ? -1 : 1;
3360 else if ( d0.getFrom() > d1.getFrom() ) {
3361 return _ascending ? 1 : -1;