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 if ( input_file_properties[ i ].length == 3 ) {
1890 ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote binary domain combination for \""
1891 + input_file_properties[ i ][ 0 ] + "\" (" + input_file_properties[ i ][ 1 ] + ", "
1892 + input_file_properties[ i ][ 2 ] + ") to: \"" + dc_outfile_dot + "\"" );
1895 ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote binary domain combination for \""
1896 + input_file_properties[ i ][ 0 ] + "\" (" + input_file_properties[ i ][ 1 ] + ") to: \""
1897 + dc_outfile_dot + "\"" );
1901 public static void writeBinaryStatesMatrixAsListToFile( final CharacterStateMatrix<CharacterStateMatrix.GainLossStates> matrix,
1902 final CharacterStateMatrix.GainLossStates state,
1903 final String filename,
1904 final String indentifier_characters_separator,
1905 final String character_separator,
1906 final Map<String, String> descriptions ) {
1907 final File outfile = new File( filename );
1908 checkForOutputFileWriteability( outfile );
1909 final SortedSet<String> sorted_ids = new TreeSet<String>();
1910 for( int i = 0; i < matrix.getNumberOfIdentifiers(); ++i ) {
1911 sorted_ids.add( matrix.getIdentifier( i ) );
1914 final BufferedWriter out = new BufferedWriter( new FileWriter( outfile ) );
1915 for( final String id : sorted_ids ) {
1916 out.write( indentifier_characters_separator );
1917 out.write( "#" + id );
1918 out.write( indentifier_characters_separator );
1919 for( int c = 0; c < matrix.getNumberOfCharacters(); ++c ) {
1921 // using null to indicate either UNCHANGED_PRESENT or GAIN.
1922 if ( ( matrix.getState( id, c ) == state )
1923 || ( ( state == null ) && ( ( matrix.getState( id, c ) == CharacterStateMatrix.GainLossStates.GAIN ) || ( matrix
1924 .getState( id, c ) == CharacterStateMatrix.GainLossStates.UNCHANGED_PRESENT ) ) ) ) {
1925 out.write( matrix.getCharacter( c ) );
1926 if ( ( descriptions != null ) && !descriptions.isEmpty()
1927 && descriptions.containsKey( matrix.getCharacter( c ) ) ) {
1929 out.write( descriptions.get( matrix.getCharacter( c ) ) );
1931 out.write( character_separator );
1938 catch ( final IOException e ) {
1939 ForesterUtil.fatalError( surfacing.PRG_NAME, e.getMessage() );
1941 ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote characters list: \"" + filename + "\"" );
1944 public static void writeBinaryStatesMatrixAsListToFileForBinaryCombinationsForGraphAnalysis( final CharacterStateMatrix<CharacterStateMatrix.GainLossStates> matrix,
1945 final CharacterStateMatrix.GainLossStates state,
1946 final String filename,
1947 final String indentifier_characters_separator,
1948 final String character_separator,
1949 final BinaryDomainCombination.OutputFormat bc_output_format ) {
1950 final File outfile = new File( filename );
1951 checkForOutputFileWriteability( outfile );
1952 final SortedSet<String> sorted_ids = new TreeSet<String>();
1953 for( int i = 0; i < matrix.getNumberOfIdentifiers(); ++i ) {
1954 sorted_ids.add( matrix.getIdentifier( i ) );
1957 final BufferedWriter out = new BufferedWriter( new FileWriter( outfile ) );
1958 for( final String id : sorted_ids ) {
1959 out.write( indentifier_characters_separator );
1960 out.write( "#" + id );
1961 out.write( indentifier_characters_separator );
1962 for( int c = 0; c < matrix.getNumberOfCharacters(); ++c ) {
1964 // using null to indicate either UNCHANGED_PRESENT or GAIN.
1965 if ( ( matrix.getState( id, c ) == state )
1966 || ( ( state == null ) && ( ( matrix.getState( id, c ) == CharacterStateMatrix.GainLossStates.GAIN ) || ( matrix
1967 .getState( id, c ) == CharacterStateMatrix.GainLossStates.UNCHANGED_PRESENT ) ) ) ) {
1968 BinaryDomainCombination bdc = null;
1970 bdc = BasicBinaryDomainCombination.obtainInstance( matrix.getCharacter( c ) );
1972 catch ( final Exception e ) {
1973 ForesterUtil.fatalError( surfacing.PRG_NAME, e.getLocalizedMessage() );
1975 out.write( bdc.toGraphDescribingLanguage( bc_output_format, null, null ).toString() );
1976 out.write( character_separator );
1983 catch ( final IOException e ) {
1984 ForesterUtil.fatalError( surfacing.PRG_NAME, e.getMessage() );
1986 ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote characters list: \"" + filename + "\"" );
1989 public static void writeBinaryStatesMatrixToList( final Map<String, List<GoId>> domain_id_to_go_ids_map,
1990 final Map<GoId, GoTerm> go_id_to_term_map,
1991 final GoNameSpace go_namespace_limit,
1992 final boolean domain_combinations,
1993 final CharacterStateMatrix<CharacterStateMatrix.GainLossStates> matrix,
1994 final CharacterStateMatrix.GainLossStates state,
1995 final String filename,
1996 final String indentifier_characters_separator,
1997 final String character_separator,
1998 final String title_for_html,
1999 final String prefix_for_html,
2000 final Map<String, Set<String>>[] domain_id_to_secondary_features_maps,
2001 final SortedSet<String> all_pfams_encountered,
2002 final SortedSet<String> pfams_gained_or_lost,
2003 final String suffix_for_per_node_events_file,
2004 final Map<String, Integer> tax_code_to_id_map ) {
2005 if ( ( go_namespace_limit != null ) && ( ( go_id_to_term_map == null ) || ( go_id_to_term_map.size() < 1 ) ) ) {
2006 throw new IllegalArgumentException( "attempt to use GO namespace limit without a GO-id to term map" );
2008 else if ( ( ( domain_id_to_go_ids_map == null ) || ( domain_id_to_go_ids_map.size() < 1 ) ) ) {
2009 throw new IllegalArgumentException( "attempt to output detailed HTML without a Pfam to GO map" );
2011 else if ( ( ( go_id_to_term_map == null ) || ( go_id_to_term_map.size() < 1 ) ) ) {
2012 throw new IllegalArgumentException( "attempt to output detailed HTML without a GO-id to term map" );
2014 final File outfile = new File( filename );
2015 checkForOutputFileWriteability( outfile );
2016 final SortedSet<String> sorted_ids = new TreeSet<String>();
2017 for( int i = 0; i < matrix.getNumberOfIdentifiers(); ++i ) {
2018 sorted_ids.add( matrix.getIdentifier( i ) );
2021 final Writer out = new BufferedWriter( new FileWriter( outfile ) );
2022 final File per_node_go_mapped_domain_gain_loss_files_base_dir = createBaseDirForPerNodeDomainFiles( surfacing.BASE_DIRECTORY_PER_NODE_DOMAIN_GAIN_LOSS_FILES,
2023 domain_combinations,
2026 Writer per_node_go_mapped_domain_gain_loss_outfile_writer = null;
2027 File per_node_go_mapped_domain_gain_loss_outfile = null;
2028 int per_node_counter = 0;
2029 out.write( "<html>" );
2030 out.write( SurfacingConstants.NL );
2031 writeHtmlHead( out, title_for_html );
2032 out.write( SurfacingConstants.NL );
2033 out.write( "<body>" );
2034 out.write( SurfacingConstants.NL );
2035 out.write( "<h1>" );
2036 out.write( SurfacingConstants.NL );
2037 out.write( title_for_html );
2038 out.write( SurfacingConstants.NL );
2039 out.write( "</h1>" );
2040 out.write( SurfacingConstants.NL );
2041 out.write( "<table>" );
2042 out.write( SurfacingConstants.NL );
2043 for( final String id : sorted_ids ) {
2044 final Matcher matcher = PATTERN_SP_STYLE_TAXONOMY.matcher( id );
2045 if ( matcher.matches() ) {
2048 out.write( "<tr>" );
2049 out.write( "<td>" );
2050 out.write( "<a href=\"#" + id + "\">" + id + "</a>" );
2051 out.write( "</td>" );
2052 out.write( "</tr>" );
2053 out.write( SurfacingConstants.NL );
2055 out.write( "</table>" );
2056 out.write( SurfacingConstants.NL );
2057 for( final String id : sorted_ids ) {
2058 final Matcher matcher = PATTERN_SP_STYLE_TAXONOMY.matcher( id );
2059 if ( matcher.matches() ) {
2062 out.write( SurfacingConstants.NL );
2063 out.write( "<h2>" );
2064 out.write( "<a name=\"" + id + "\">" + id + "</a>" );
2065 writeTaxonomyLinks( out, id, tax_code_to_id_map );
2066 out.write( "</h2>" );
2067 out.write( SurfacingConstants.NL );
2068 out.write( "<table>" );
2069 out.write( SurfacingConstants.NL );
2070 out.write( "<tr>" );
2071 out.write( "<td><b>" );
2072 out.write( "Pfam domain(s)" );
2073 out.write( "</b></td><td><b>" );
2074 out.write( "GO term acc" );
2075 out.write( "</b></td><td><b>" );
2076 out.write( "GO term" );
2077 out.write( "</b></td><td><b>" );
2078 out.write( "GO namespace" );
2079 out.write( "</b></td>" );
2080 out.write( "</tr>" );
2081 out.write( SurfacingConstants.NL );
2082 out.write( "</tr>" );
2083 out.write( SurfacingConstants.NL );
2084 per_node_counter = 0;
2085 if ( matrix.getNumberOfCharacters() > 0 ) {
2086 per_node_go_mapped_domain_gain_loss_outfile = new File( per_node_go_mapped_domain_gain_loss_files_base_dir
2087 + ForesterUtil.FILE_SEPARATOR + id + suffix_for_per_node_events_file );
2088 SurfacingUtil.checkForOutputFileWriteability( per_node_go_mapped_domain_gain_loss_outfile );
2089 per_node_go_mapped_domain_gain_loss_outfile_writer = ForesterUtil
2090 .createBufferedWriter( per_node_go_mapped_domain_gain_loss_outfile );
2093 per_node_go_mapped_domain_gain_loss_outfile = null;
2094 per_node_go_mapped_domain_gain_loss_outfile_writer = null;
2096 for( int c = 0; c < matrix.getNumberOfCharacters(); ++c ) {
2098 // using null to indicate either UNCHANGED_PRESENT or GAIN.
2099 if ( ( matrix.getState( id, c ) == state )
2100 || ( ( state == null ) && ( ( matrix.getState( id, c ) == CharacterStateMatrix.GainLossStates.UNCHANGED_PRESENT ) || ( matrix
2101 .getState( id, c ) == CharacterStateMatrix.GainLossStates.GAIN ) ) ) ) {
2102 final String character = matrix.getCharacter( c );
2103 String domain_0 = "";
2104 String domain_1 = "";
2105 if ( character.indexOf( BinaryDomainCombination.SEPARATOR ) > 0 ) {
2106 final String[] s = character.split( BinaryDomainCombination.SEPARATOR );
2107 if ( s.length != 2 ) {
2108 throw new AssertionError( "this should not have happened: unexpected format for domain combination: ["
2109 + character + "]" );
2115 domain_0 = character;
2117 writeDomainData( domain_id_to_go_ids_map,
2124 character_separator,
2125 domain_id_to_secondary_features_maps,
2127 all_pfams_encountered.add( domain_0 );
2128 if ( pfams_gained_or_lost != null ) {
2129 pfams_gained_or_lost.add( domain_0 );
2131 if ( !ForesterUtil.isEmpty( domain_1 ) ) {
2132 all_pfams_encountered.add( domain_1 );
2133 if ( pfams_gained_or_lost != null ) {
2134 pfams_gained_or_lost.add( domain_1 );
2137 if ( per_node_go_mapped_domain_gain_loss_outfile_writer != null ) {
2138 writeDomainsToIndividualFilePerTreeNode( per_node_go_mapped_domain_gain_loss_outfile_writer,
2145 if ( per_node_go_mapped_domain_gain_loss_outfile_writer != null ) {
2146 per_node_go_mapped_domain_gain_loss_outfile_writer.close();
2147 if ( per_node_counter < 1 ) {
2148 per_node_go_mapped_domain_gain_loss_outfile.delete();
2150 per_node_counter = 0;
2152 out.write( "</table>" );
2153 out.write( SurfacingConstants.NL );
2154 out.write( "<hr>" );
2155 out.write( SurfacingConstants.NL );
2156 } // for( final String id : sorted_ids ) {
2157 out.write( "</body>" );
2158 out.write( SurfacingConstants.NL );
2159 out.write( "</html>" );
2160 out.write( SurfacingConstants.NL );
2164 catch ( final IOException e ) {
2165 ForesterUtil.fatalError( surfacing.PRG_NAME, e.getMessage() );
2167 ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote characters detailed HTML list: \"" + filename + "\"" );
2170 public static void writeDomainCombinationsCountsFile( final String[][] input_file_properties,
2171 final File output_dir,
2172 final Writer per_genome_domain_promiscuity_statistics_writer,
2173 final GenomeWideCombinableDomains gwcd,
2175 final GenomeWideCombinableDomains.GenomeWideCombinableDomainsSortOrder dc_sort_order ) {
2176 File dc_outfile = new File( input_file_properties[ i ][ 1 ]
2177 + surfacing.DOMAIN_COMBINITON_COUNTS_OUTPUTFILE_SUFFIX );
2178 if ( output_dir != null ) {
2179 dc_outfile = new File( output_dir + ForesterUtil.FILE_SEPARATOR + dc_outfile );
2181 checkForOutputFileWriteability( dc_outfile );
2183 final BufferedWriter out = new BufferedWriter( new FileWriter( dc_outfile ) );
2184 out.write( gwcd.toStringBuilder( dc_sort_order ).toString() );
2187 catch ( final IOException e ) {
2188 ForesterUtil.fatalError( surfacing.PRG_NAME, e.getMessage() );
2190 final DescriptiveStatistics stats = gwcd.getPerGenomeDomainPromiscuityStatistics();
2192 per_genome_domain_promiscuity_statistics_writer.write( input_file_properties[ i ][ 1 ] + "\t" );
2193 per_genome_domain_promiscuity_statistics_writer.write( FORMATTER_3.format( stats.arithmeticMean() ) + "\t" );
2194 if ( stats.getN() < 2 ) {
2195 per_genome_domain_promiscuity_statistics_writer.write( "n/a" + "\t" );
2198 per_genome_domain_promiscuity_statistics_writer.write( FORMATTER_3.format( stats
2199 .sampleStandardDeviation() ) + "\t" );
2201 per_genome_domain_promiscuity_statistics_writer.write( FORMATTER_3.format( stats.median() ) + "\t" );
2202 per_genome_domain_promiscuity_statistics_writer.write( ( int ) stats.getMin() + "\t" );
2203 per_genome_domain_promiscuity_statistics_writer.write( ( int ) stats.getMax() + "\t" );
2204 per_genome_domain_promiscuity_statistics_writer.write( stats.getN() + "\t" );
2205 final SortedSet<String> mpds = gwcd.getMostPromiscuosDomain();
2206 for( final String mpd : mpds ) {
2207 per_genome_domain_promiscuity_statistics_writer.write( mpd + " " );
2209 per_genome_domain_promiscuity_statistics_writer.write( ForesterUtil.LINE_SEPARATOR );
2211 catch ( final IOException e ) {
2212 ForesterUtil.fatalError( surfacing.PRG_NAME, e.getMessage() );
2214 if ( input_file_properties[ i ].length == 3 ) {
2215 ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote domain combination counts for \""
2216 + input_file_properties[ i ][ 0 ] + "\" (" + input_file_properties[ i ][ 1 ] + ", "
2217 + input_file_properties[ i ][ 2 ] + ") to: \"" + dc_outfile + "\"" );
2220 ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote domain combination counts for \""
2221 + input_file_properties[ i ][ 0 ] + "\" (" + input_file_properties[ i ][ 1 ] + ") to: \""
2222 + dc_outfile + "\"" );
2226 public static void writeDomainSimilaritiesToFile( final StringBuilder html_desc,
2227 final StringBuilder html_title,
2228 final Writer simple_tab_writer,
2229 final Writer single_writer,
2230 Map<Character, Writer> split_writers,
2231 final SortedSet<DomainSimilarity> similarities,
2232 final boolean treat_as_binary,
2233 final List<Species> species_order,
2234 final DomainSimilarity.PRINT_OPTION print_option,
2235 final DomainSimilarity.DomainSimilarityScoring scoring,
2236 final boolean verbose,
2237 final Map<String, Integer> tax_code_to_id_map,
2238 final Phylogeny phy,
2239 final Set<String> pos_filter_doms ) throws IOException {
2240 if ( ( single_writer != null ) && ( ( split_writers == null ) || split_writers.isEmpty() ) ) {
2241 split_writers = new HashMap<Character, Writer>();
2242 split_writers.put( '_', single_writer );
2244 switch ( print_option ) {
2245 case SIMPLE_TAB_DELIMITED:
2248 for( final Character key : split_writers.keySet() ) {
2249 final Writer w = split_writers.get( key );
2250 w.write( "<html>" );
2251 w.write( SurfacingConstants.NL );
2253 writeHtmlHead( w, "DC analysis (" + html_title + ") " + key.toString().toUpperCase() );
2256 writeHtmlHead( w, "DC analysis (" + html_title + ")" );
2258 w.write( SurfacingConstants.NL );
2259 w.write( "<body>" );
2260 w.write( SurfacingConstants.NL );
2261 w.write( html_desc.toString() );
2262 w.write( SurfacingConstants.NL );
2264 w.write( SurfacingConstants.NL );
2266 w.write( SurfacingConstants.NL );
2267 w.write( "<table>" );
2268 w.write( SurfacingConstants.NL );
2269 w.write( "<tr><td><b>Domains:</b></td></tr>" );
2270 w.write( SurfacingConstants.NL );
2275 for( final DomainSimilarity similarity : similarities ) {
2276 if ( ( species_order != null ) && !species_order.isEmpty() ) {
2277 ( similarity ).setSpeciesOrder( species_order );
2279 if ( single_writer != null ) {
2280 if ( !ForesterUtil.isEmpty( pos_filter_doms ) && pos_filter_doms.contains( similarity.getDomainId() ) ) {
2281 single_writer.write( "<tr><td><b><a href=\"#" + similarity.getDomainId()
2282 + "\"><span style=\"color:#00ff00\">" + similarity.getDomainId()
2283 + "</span></a></b></td></tr>" );
2286 single_writer.write( "<tr><td><b><a href=\"#" + similarity.getDomainId() + "\">"
2287 + similarity.getDomainId() + "</a></b></td></tr>" );
2289 single_writer.write( SurfacingConstants.NL );
2292 Writer local_writer = split_writers.get( ( similarity.getDomainId().charAt( 0 ) + "" ).toLowerCase()
2294 if ( local_writer == null ) {
2295 local_writer = split_writers.get( '0' );
2297 if ( !ForesterUtil.isEmpty( pos_filter_doms ) && pos_filter_doms.contains( similarity.getDomainId() ) ) {
2298 local_writer.write( "<tr><td><b><a href=\"#" + similarity.getDomainId()
2299 + "\"><span style=\"color:#00ff00\">" + similarity.getDomainId()
2300 + "</span></a></b></td></tr>" );
2303 local_writer.write( "<tr><td><b><a href=\"#" + similarity.getDomainId() + "\">"
2304 + similarity.getDomainId() + "</a></b></td></tr>" );
2306 local_writer.write( SurfacingConstants.NL );
2309 for( final Writer w : split_writers.values() ) {
2310 w.write( "</table>" );
2311 w.write( SurfacingConstants.NL );
2313 w.write( SurfacingConstants.NL );
2315 w.write( "<table>" );
2316 w.write( SurfacingConstants.NL );
2317 w.write( "<tr><td><b>" );
2318 w.write( "Species group colors:" );
2319 w.write( "</b></td></tr>" );
2320 w.write( SurfacingConstants.NL );
2321 writeColorLabels( "Deuterostomia", TaxonomyColors.DEUTEROSTOMIA_COLOR, w );
2322 writeColorLabels( "Protostomia", TaxonomyColors.PROTOSTOMIA_COLOR, w );
2323 writeColorLabels( "Cnidaria", TaxonomyColors.CNIDARIA_COLOR, w );
2324 writeColorLabels( "Placozoa", TaxonomyColors.PLACOZOA_COLOR, w );
2325 writeColorLabels( "Ctenophora (comb jellies)", TaxonomyColors.CTENOPHORA_COLOR, w );
2326 writeColorLabels( "Porifera (sponges)", TaxonomyColors.PORIFERA_COLOR, w );
2327 writeColorLabels( "Choanoflagellida", TaxonomyColors.CHOANOFLAGELLIDA, w );
2328 writeColorLabels( "Ichthyosporea & Filasterea", TaxonomyColors.ICHTHYOSPOREA_AND_FILASTEREA, w );
2329 writeColorLabels( "Dikarya (Ascomycota & Basidiomycota, so-called \"higher fungi\")",
2330 TaxonomyColors.DIKARYA_COLOR,
2332 writeColorLabels( "other Fungi", TaxonomyColors.OTHER_FUNGI_COLOR, w );
2333 writeColorLabels( "Nucleariidae and Fonticula group",
2334 TaxonomyColors.NUCLEARIIDAE_AND_FONTICULA_GROUP_COLOR,
2336 writeColorLabels( "Amoebozoa", TaxonomyColors.AMOEBOZOA_COLOR, w );
2337 writeColorLabels( "Embryophyta (plants)", TaxonomyColors.EMBRYOPHYTA_COLOR, w );
2338 writeColorLabels( "Chlorophyta (green algae)", TaxonomyColors.CHLOROPHYTA_COLOR, w );
2339 writeColorLabels( "Rhodophyta (red algae)", TaxonomyColors.RHODOPHYTA_COLOR, w );
2340 writeColorLabels( "Glaucocystophyce (Glaucophyta)", TaxonomyColors.GLAUCOPHYTA_COLOR, w );
2341 writeColorLabels( "Hacrobia (Cryptophyta & Haptophyceae & Centroheliozoa)",
2342 TaxonomyColors.HACROBIA_COLOR,
2344 writeColorLabels( "Stramenopiles (Chromophyta, heterokonts)", TaxonomyColors.STRAMENOPILES_COLOR, w );
2345 writeColorLabels( "Alveolata", TaxonomyColors.ALVEOLATA_COLOR, w );
2346 writeColorLabels( "Rhizaria", TaxonomyColors.RHIZARIA_COLOR, w );
2347 writeColorLabels( "Excavata", TaxonomyColors.EXCAVATA_COLOR, w );
2348 writeColorLabels( "Apusozoa", TaxonomyColors.APUSOZOA_COLOR, w );
2349 writeColorLabels( "Archaea", TaxonomyColors.ARCHAEA_COLOR, w );
2350 writeColorLabels( "Bacteria", TaxonomyColors.BACTERIA_COLOR, w );
2351 w.write( "</table>" );
2352 w.write( SurfacingConstants.NL );
2355 w.write( SurfacingConstants.NL );
2356 w.write( "<table>" );
2357 w.write( SurfacingConstants.NL );
2360 for( final DomainSimilarity similarity : similarities ) {
2361 if ( ( species_order != null ) && !species_order.isEmpty() ) {
2362 ( similarity ).setSpeciesOrder( species_order );
2364 if ( simple_tab_writer != null ) {
2365 simple_tab_writer.write( similarity.toStringBuffer( PRINT_OPTION.SIMPLE_TAB_DELIMITED,
2367 null ).toString() );
2369 if ( single_writer != null ) {
2370 single_writer.write( similarity.toStringBuffer( print_option, tax_code_to_id_map, phy ).toString() );
2371 single_writer.write( SurfacingConstants.NL );
2374 Writer local_writer = split_writers.get( ( similarity.getDomainId().charAt( 0 ) + "" ).toLowerCase()
2376 if ( local_writer == null ) {
2377 local_writer = split_writers.get( '0' );
2379 local_writer.write( similarity.toStringBuffer( print_option, tax_code_to_id_map, phy ).toString() );
2380 local_writer.write( SurfacingConstants.NL );
2383 switch ( print_option ) {
2385 for( final Writer w : split_writers.values() ) {
2386 w.write( SurfacingConstants.NL );
2387 w.write( "</table>" );
2388 w.write( SurfacingConstants.NL );
2389 w.write( "</font>" );
2390 w.write( SurfacingConstants.NL );
2391 w.write( "</body>" );
2392 w.write( SurfacingConstants.NL );
2393 w.write( "</html>" );
2394 w.write( SurfacingConstants.NL );
2400 for( final Writer w : split_writers.values() ) {
2405 public static void writeHtmlHead( final Writer w, final String title ) throws IOException {
2406 w.write( SurfacingConstants.NL );
2407 w.write( "<head>" );
2408 w.write( "<title>" );
2410 w.write( "</title>" );
2411 w.write( SurfacingConstants.NL );
2412 w.write( "<style>" );
2413 w.write( SurfacingConstants.NL );
2414 w.write( "a:visited { color : #000066; text-decoration : none; }" );
2415 w.write( SurfacingConstants.NL );
2416 w.write( "a:link { color : #000066; text-decoration : none; }" );
2417 w.write( SurfacingConstants.NL );
2418 w.write( "a:active { color : ##000066; text-decoration : none; }" );
2419 w.write( SurfacingConstants.NL );
2420 w.write( "a:hover { color : #FFFFFF; background-color : #000000; text-decoration : none; }" );
2421 w.write( SurfacingConstants.NL );
2423 w.write( "a.pl:visited { color : #505050; text-decoration : none; font-size: 7px;}" );
2424 w.write( SurfacingConstants.NL );
2425 w.write( "a.pl:link { color : #505050; text-decoration : none; font-size: 7px;}" );
2426 w.write( SurfacingConstants.NL );
2427 w.write( "a.pl:active { color : #505050; text-decoration : none; font-size: 7px;}" );
2428 w.write( SurfacingConstants.NL );
2429 w.write( "a.pl:hover { color : #FFFFFF; background-color : #000000; text-decoration : none; font-size: 7px;}" );
2430 w.write( SurfacingConstants.NL );
2432 w.write( "a.ps:visited { color : #707070; text-decoration : none; font-size: 7px;}" );
2433 w.write( SurfacingConstants.NL );
2434 w.write( "a.ps:link { color : #707070; text-decoration : none; font-size: 7px;}" );
2435 w.write( SurfacingConstants.NL );
2436 w.write( "a.ps:active { color : #707070; text-decoration : none; font-size: 7px;}" );
2437 w.write( SurfacingConstants.NL );
2438 w.write( "a.ps:hover { color : #FFFFFF; background-color : #000000; text-decoration : none; font-size: 7px;}" );
2439 w.write( SurfacingConstants.NL );
2441 w.write( "td { text-align: left; vertical-align: top; font-family: Verdana, Arial, Helvetica; font-size: 8pt}" );
2442 w.write( SurfacingConstants.NL );
2443 w.write( "h1 { color : #0000FF; font-family: Verdana, Arial, Helvetica; font-size: 18pt; font-weight: bold }" );
2444 w.write( SurfacingConstants.NL );
2445 w.write( "h2 { color : #0000FF; font-family: Verdana, Arial, Helvetica; font-size: 16pt; font-weight: bold }" );
2446 w.write( SurfacingConstants.NL );
2447 w.write( "</style>" );
2448 w.write( SurfacingConstants.NL );
2449 w.write( "</head>" );
2450 w.write( SurfacingConstants.NL );
2453 public static void writeMatrixToFile( final CharacterStateMatrix<?> matrix,
2454 final String filename,
2455 final Format format ) {
2456 final File outfile = new File( filename );
2457 checkForOutputFileWriteability( outfile );
2459 final BufferedWriter out = new BufferedWriter( new FileWriter( outfile ) );
2460 matrix.toWriter( out, format );
2464 catch ( final IOException e ) {
2465 ForesterUtil.fatalError( surfacing.PRG_NAME, e.getMessage() );
2467 ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote matrix: \"" + filename + "\"" );
2470 public static void writeMatrixToFile( final File matrix_outfile, final List<DistanceMatrix> matrices ) {
2471 checkForOutputFileWriteability( matrix_outfile );
2473 final BufferedWriter out = new BufferedWriter( new FileWriter( matrix_outfile ) );
2474 for( final DistanceMatrix distance_matrix : matrices ) {
2475 out.write( distance_matrix.toStringBuffer( DistanceMatrix.Format.PHYLIP ).toString() );
2476 out.write( ForesterUtil.LINE_SEPARATOR );
2481 catch ( final IOException e ) {
2482 ForesterUtil.fatalError( surfacing.PRG_NAME, e.getMessage() );
2484 ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote distance matrices to \"" + matrix_outfile + "\"" );
2487 public static void writePhylogenyToFile( final Phylogeny phylogeny, final String filename ) {
2488 final PhylogenyWriter writer = new PhylogenyWriter();
2490 writer.toPhyloXML( new File( filename ), phylogeny, 1 );
2492 catch ( final IOException e ) {
2493 ForesterUtil.printWarningMessage( surfacing.PRG_NAME, "failed to write phylogeny to \"" + filename + "\": "
2496 ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote phylogeny to \"" + filename + "\"" );
2499 public static void writePresentToNexus( final File output_file,
2500 final File positive_filter_file,
2501 final SortedSet<String> filter,
2502 final List<GenomeWideCombinableDomains> gwcd_list ) {
2504 writeMatrixToFile( DomainParsimonyCalculator.createMatrixOfDomainPresenceOrAbsence( gwcd_list,
2505 positive_filter_file == null ? null
2507 output_file + surfacing.DOMAINS_PRESENT_NEXUS,
2508 Format.NEXUS_BINARY );
2509 writeMatrixToFile( DomainParsimonyCalculator.createMatrixOfBinaryDomainCombinationPresenceOrAbsence( gwcd_list ),
2510 output_file + surfacing.BDC_PRESENT_NEXUS,
2511 Format.NEXUS_BINARY );
2513 catch ( final Exception e ) {
2514 ForesterUtil.fatalError( surfacing.PRG_NAME, e.getLocalizedMessage() );
2518 public static void writeProteinListsForAllSpecies( final File output_dir,
2519 final SortedMap<Species, List<Protein>> protein_lists_per_species,
2520 final List<GenomeWideCombinableDomains> gwcd_list,
2521 final double domain_e_cutoff,
2522 final Set<String> pos_filter_doms ) {
2523 final SortedSet<String> all_domains = new TreeSet<String>();
2524 for( final GenomeWideCombinableDomains gwcd : gwcd_list ) {
2525 all_domains.addAll( gwcd.getAllDomainIds() );
2527 for( final String domain : all_domains ) {
2528 if ( !ForesterUtil.isEmpty( pos_filter_doms ) && !pos_filter_doms.contains( domain ) ) {
2531 final File out = new File( output_dir + ForesterUtil.FILE_SEPARATOR + domain + surfacing.SEQ_EXTRACT_SUFFIX );
2532 checkForOutputFileWriteability( out );
2534 final Writer proteins_file_writer = new BufferedWriter( new FileWriter( out ) );
2535 extractProteinNames( protein_lists_per_species,
2537 proteins_file_writer,
2539 surfacing.LIMIT_SPEC_FOR_PROT_EX,
2541 proteins_file_writer.close();
2543 catch ( final IOException e ) {
2544 ForesterUtil.fatalError( surfacing.PRG_NAME, e.getLocalizedMessage() );
2546 ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote proteins list to \"" + out + "\"" );
2550 public static void writeTaxonomyLinks( final Writer writer,
2551 final String species,
2552 final Map<String, Integer> tax_code_to_id_map ) throws IOException {
2553 if ( ( species.length() > 1 ) && ( species.indexOf( '_' ) < 1 ) ) {
2554 writer.write( " [" );
2555 if ( ( tax_code_to_id_map != null ) && tax_code_to_id_map.containsKey( species ) ) {
2556 writer.write( "<a href=\"" + SurfacingConstants.UNIPROT_TAXONOMY_ID_LINK
2557 + tax_code_to_id_map.get( species ) + "\" target=\"taxonomy_window\">uniprot</a>" );
2560 writer.write( "<a href=\"" + SurfacingConstants.EOL_LINK + species
2561 + "\" target=\"taxonomy_window\">eol</a>" );
2562 writer.write( "|" );
2563 writer.write( "<a href=\"" + SurfacingConstants.GOOGLE_SCHOLAR_SEARCH + species
2564 + "\" target=\"taxonomy_window\">scholar</a>" );
2565 writer.write( "|" );
2566 writer.write( "<a href=\"" + SurfacingConstants.GOOGLE_WEB_SEARCH_LINK + species
2567 + "\" target=\"taxonomy_window\">google</a>" );
2569 writer.write( "]" );
2573 private final static void addToCountMap( final Map<String, Integer> map, final String s ) {
2574 if ( map.containsKey( s ) ) {
2575 map.put( s, map.get( s ) + 1 );
2582 private static void calculateIndependentDomainCombinationGains( final Phylogeny local_phylogeny_l,
2583 final String outfilename_for_counts,
2584 final String outfilename_for_dc,
2585 final String outfilename_for_dc_for_go_mapping,
2586 final String outfilename_for_dc_for_go_mapping_unique,
2587 final String outfilename_for_rank_counts,
2588 final String outfilename_for_ancestor_species_counts,
2589 final String outfilename_for_protein_stats,
2590 final Map<String, DescriptiveStatistics> protein_length_stats_by_dc,
2591 final Map<String, DescriptiveStatistics> domain_number_stats_by_dc,
2592 final Map<String, DescriptiveStatistics> domain_length_stats_by_domain ) {
2595 // if ( protein_length_stats_by_dc != null ) {
2596 // for( final Entry<?, DescriptiveStatistics> entry : protein_length_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();
2606 // if ( domain_number_stats_by_dc != null ) {
2607 // for( final Entry<?, DescriptiveStatistics> entry : domain_number_stats_by_dc.entrySet() ) {
2608 // System.out.print( entry.getKey().toString() );
2609 // System.out.print( ": " );
2610 // double[] a = entry.getValue().getDataAsDoubleArray();
2611 // for( int i = 0; i < a.length; i++ ) {
2612 // System.out.print( a[ i ] + " " );
2614 // System.out.println();
2618 final BufferedWriter out_counts = new BufferedWriter( new FileWriter( outfilename_for_counts ) );
2619 final BufferedWriter out_dc = new BufferedWriter( new FileWriter( outfilename_for_dc ) );
2620 final BufferedWriter out_dc_for_go_mapping = new BufferedWriter( new FileWriter( outfilename_for_dc_for_go_mapping ) );
2621 final BufferedWriter out_dc_for_go_mapping_unique = new BufferedWriter( new FileWriter( outfilename_for_dc_for_go_mapping_unique ) );
2622 final SortedMap<String, Integer> dc_gain_counts = new TreeMap<String, Integer>();
2623 for( final PhylogenyNodeIterator it = local_phylogeny_l.iteratorPostorder(); it.hasNext(); ) {
2624 final PhylogenyNode n = it.next();
2625 final Set<String> gained_dc = n.getNodeData().getBinaryCharacters().getGainedCharacters();
2626 for( final String dc : gained_dc ) {
2627 if ( dc_gain_counts.containsKey( dc ) ) {
2628 dc_gain_counts.put( dc, dc_gain_counts.get( dc ) + 1 );
2631 dc_gain_counts.put( dc, 1 );
2635 final SortedMap<Integer, Integer> histogram = new TreeMap<Integer, Integer>();
2636 final SortedMap<Integer, StringBuilder> domain_lists = new TreeMap<Integer, StringBuilder>();
2637 final SortedMap<Integer, DescriptiveStatistics> dc_reapp_counts_to_protein_length_stats = new TreeMap<Integer, DescriptiveStatistics>();
2638 final SortedMap<Integer, DescriptiveStatistics> dc_reapp_counts_to_domain_number_stats = new TreeMap<Integer, DescriptiveStatistics>();
2639 final SortedMap<Integer, DescriptiveStatistics> dc_reapp_counts_to_domain_lengths_stats = new TreeMap<Integer, DescriptiveStatistics>();
2640 final SortedMap<Integer, PriorityQueue<String>> domain_lists_go = new TreeMap<Integer, PriorityQueue<String>>();
2641 final SortedMap<Integer, SortedSet<String>> domain_lists_go_unique = new TreeMap<Integer, SortedSet<String>>();
2642 final Set<String> dcs = dc_gain_counts.keySet();
2643 final SortedSet<String> more_than_once = new TreeSet<String>();
2644 DescriptiveStatistics gained_once_lengths_stats = new BasicDescriptiveStatistics();
2645 DescriptiveStatistics gained_once_domain_count_stats = new BasicDescriptiveStatistics();
2646 DescriptiveStatistics gained_multiple_times_lengths_stats = new BasicDescriptiveStatistics();
2647 final DescriptiveStatistics gained_multiple_times_domain_count_stats = new BasicDescriptiveStatistics();
2648 long gained_multiple_times_domain_length_sum = 0;
2649 long gained_once_domain_length_sum = 0;
2650 long gained_multiple_times_domain_length_count = 0;
2651 long gained_once_domain_length_count = 0;
2652 for( final String dc : dcs ) {
2653 final int count = dc_gain_counts.get( dc );
2654 if ( histogram.containsKey( count ) ) {
2655 histogram.put( count, histogram.get( count ) + 1 );
2656 domain_lists.get( count ).append( ", " + dc );
2657 domain_lists_go.get( count ).addAll( splitDomainCombination( dc ) );
2658 domain_lists_go_unique.get( count ).addAll( splitDomainCombination( dc ) );
2661 histogram.put( count, 1 );
2662 domain_lists.put( count, new StringBuilder( dc ) );
2663 final PriorityQueue<String> q = new PriorityQueue<String>();
2664 q.addAll( splitDomainCombination( dc ) );
2665 domain_lists_go.put( count, q );
2666 final SortedSet<String> set = new TreeSet<String>();
2667 set.addAll( splitDomainCombination( dc ) );
2668 domain_lists_go_unique.put( count, set );
2670 if ( protein_length_stats_by_dc != null ) {
2671 if ( !dc_reapp_counts_to_protein_length_stats.containsKey( count ) ) {
2672 dc_reapp_counts_to_protein_length_stats.put( count, new BasicDescriptiveStatistics() );
2674 dc_reapp_counts_to_protein_length_stats.get( count ).addValue( protein_length_stats_by_dc.get( dc )
2675 .arithmeticMean() );
2677 if ( domain_number_stats_by_dc != null ) {
2678 if ( !dc_reapp_counts_to_domain_number_stats.containsKey( count ) ) {
2679 dc_reapp_counts_to_domain_number_stats.put( count, new BasicDescriptiveStatistics() );
2681 dc_reapp_counts_to_domain_number_stats.get( count ).addValue( domain_number_stats_by_dc.get( dc )
2682 .arithmeticMean() );
2684 if ( domain_length_stats_by_domain != null ) {
2685 if ( !dc_reapp_counts_to_domain_lengths_stats.containsKey( count ) ) {
2686 dc_reapp_counts_to_domain_lengths_stats.put( count, new BasicDescriptiveStatistics() );
2688 final String[] ds = dc.split( "=" );
2689 dc_reapp_counts_to_domain_lengths_stats.get( count ).addValue( domain_length_stats_by_domain
2690 .get( ds[ 0 ] ).arithmeticMean() );
2691 dc_reapp_counts_to_domain_lengths_stats.get( count ).addValue( domain_length_stats_by_domain
2692 .get( ds[ 1 ] ).arithmeticMean() );
2695 more_than_once.add( dc );
2696 if ( protein_length_stats_by_dc != null ) {
2697 final DescriptiveStatistics s = protein_length_stats_by_dc.get( dc );
2698 for( final double element : s.getData() ) {
2699 gained_multiple_times_lengths_stats.addValue( element );
2702 if ( domain_number_stats_by_dc != null ) {
2703 final DescriptiveStatistics s = domain_number_stats_by_dc.get( dc );
2704 for( final double element : s.getData() ) {
2705 gained_multiple_times_domain_count_stats.addValue( element );
2708 if ( domain_length_stats_by_domain != null ) {
2709 final String[] ds = dc.split( "=" );
2710 final DescriptiveStatistics s0 = domain_length_stats_by_domain.get( ds[ 0 ] );
2711 final DescriptiveStatistics s1 = domain_length_stats_by_domain.get( ds[ 1 ] );
2712 for( final double element : s0.getData() ) {
2713 gained_multiple_times_domain_length_sum += element;
2714 ++gained_multiple_times_domain_length_count;
2716 for( final double element : s1.getData() ) {
2717 gained_multiple_times_domain_length_sum += element;
2718 ++gained_multiple_times_domain_length_count;
2723 if ( protein_length_stats_by_dc != null ) {
2724 final DescriptiveStatistics s = protein_length_stats_by_dc.get( dc );
2725 for( final double element : s.getData() ) {
2726 gained_once_lengths_stats.addValue( element );
2729 if ( domain_number_stats_by_dc != null ) {
2730 final DescriptiveStatistics s = domain_number_stats_by_dc.get( dc );
2731 for( final double element : s.getData() ) {
2732 gained_once_domain_count_stats.addValue( element );
2735 if ( domain_length_stats_by_domain != null ) {
2736 final String[] ds = dc.split( "=" );
2737 final DescriptiveStatistics s0 = domain_length_stats_by_domain.get( ds[ 0 ] );
2738 final DescriptiveStatistics s1 = domain_length_stats_by_domain.get( ds[ 1 ] );
2739 for( final double element : s0.getData() ) {
2740 gained_once_domain_length_sum += element;
2741 ++gained_once_domain_length_count;
2743 for( final double element : s1.getData() ) {
2744 gained_once_domain_length_sum += element;
2745 ++gained_once_domain_length_count;
2750 final Set<Integer> histogram_keys = histogram.keySet();
2751 for( final Integer histogram_key : histogram_keys ) {
2752 final int count = histogram.get( histogram_key );
2753 final StringBuilder dc = domain_lists.get( histogram_key );
2754 out_counts.write( histogram_key + "\t" + count + ForesterUtil.LINE_SEPARATOR );
2755 out_dc.write( histogram_key + "\t" + dc + ForesterUtil.LINE_SEPARATOR );
2756 out_dc_for_go_mapping.write( "#" + histogram_key + ForesterUtil.LINE_SEPARATOR );
2757 final Object[] sorted = domain_lists_go.get( histogram_key ).toArray();
2758 Arrays.sort( sorted );
2759 for( final Object domain : sorted ) {
2760 out_dc_for_go_mapping.write( domain + ForesterUtil.LINE_SEPARATOR );
2762 out_dc_for_go_mapping_unique.write( "#" + histogram_key + ForesterUtil.LINE_SEPARATOR );
2763 for( final String domain : domain_lists_go_unique.get( histogram_key ) ) {
2764 out_dc_for_go_mapping_unique.write( domain + ForesterUtil.LINE_SEPARATOR );
2769 out_dc_for_go_mapping.close();
2770 out_dc_for_go_mapping_unique.close();
2771 final SortedMap<String, Integer> lca_rank_counts = new TreeMap<String, Integer>();
2772 final SortedMap<String, Integer> lca_ancestor_species_counts = new TreeMap<String, Integer>();
2773 for( final String dc : more_than_once ) {
2774 final List<PhylogenyNode> nodes = new ArrayList<PhylogenyNode>();
2775 for( final PhylogenyNodeIterator it = local_phylogeny_l.iteratorExternalForward(); it.hasNext(); ) {
2776 final PhylogenyNode n = it.next();
2777 if ( n.getNodeData().getBinaryCharacters().getGainedCharacters().contains( dc ) ) {
2781 for( int i = 0; i < ( nodes.size() - 1 ); ++i ) {
2782 for( int j = i + 1; j < nodes.size(); ++j ) {
2783 final PhylogenyNode lca = PhylogenyMethods.calculateLCA( nodes.get( i ), nodes.get( j ) );
2784 String rank = "unknown";
2785 if ( lca.getNodeData().isHasTaxonomy()
2786 && !ForesterUtil.isEmpty( lca.getNodeData().getTaxonomy().getRank() ) ) {
2787 rank = lca.getNodeData().getTaxonomy().getRank();
2789 addToCountMap( lca_rank_counts, rank );
2791 if ( lca.getNodeData().isHasTaxonomy()
2792 && !ForesterUtil.isEmpty( lca.getNodeData().getTaxonomy().getScientificName() ) ) {
2793 lca_species = lca.getNodeData().getTaxonomy().getScientificName();
2795 else if ( lca.getNodeData().isHasTaxonomy()
2796 && !ForesterUtil.isEmpty( lca.getNodeData().getTaxonomy().getCommonName() ) ) {
2797 lca_species = lca.getNodeData().getTaxonomy().getCommonName();
2800 lca_species = lca.getName();
2802 addToCountMap( lca_ancestor_species_counts, lca_species );
2806 final BufferedWriter out_for_rank_counts = new BufferedWriter( new FileWriter( outfilename_for_rank_counts ) );
2807 final BufferedWriter out_for_ancestor_species_counts = new BufferedWriter( new FileWriter( outfilename_for_ancestor_species_counts ) );
2808 ForesterUtil.map2writer( out_for_rank_counts, lca_rank_counts, "\t", ForesterUtil.LINE_SEPARATOR );
2809 ForesterUtil.map2writer( out_for_ancestor_species_counts,
2810 lca_ancestor_species_counts,
2812 ForesterUtil.LINE_SEPARATOR );
2813 out_for_rank_counts.close();
2814 out_for_ancestor_species_counts.close();
2815 if ( !ForesterUtil.isEmpty( outfilename_for_protein_stats )
2816 && ( ( domain_length_stats_by_domain != null ) || ( protein_length_stats_by_dc != null ) || ( domain_number_stats_by_dc != null ) ) ) {
2817 final BufferedWriter w = new BufferedWriter( new FileWriter( outfilename_for_protein_stats ) );
2818 w.write( "Domain Lengths: " );
2820 if ( domain_length_stats_by_domain != null ) {
2821 for( final Entry<Integer, DescriptiveStatistics> entry : dc_reapp_counts_to_domain_lengths_stats
2823 w.write( entry.getKey().toString() );
2824 w.write( "\t" + entry.getValue().arithmeticMean() );
2825 w.write( "\t" + entry.getValue().median() );
2832 w.write( "Protein Lengths: " );
2834 if ( protein_length_stats_by_dc != null ) {
2835 for( final Entry<Integer, DescriptiveStatistics> entry : dc_reapp_counts_to_protein_length_stats
2837 w.write( entry.getKey().toString() );
2838 w.write( "\t" + entry.getValue().arithmeticMean() );
2839 w.write( "\t" + entry.getValue().median() );
2846 w.write( "Number of domains: " );
2848 if ( domain_number_stats_by_dc != null ) {
2849 for( final Entry<Integer, DescriptiveStatistics> entry : dc_reapp_counts_to_domain_number_stats
2851 w.write( entry.getKey().toString() );
2852 w.write( "\t" + entry.getValue().arithmeticMean() );
2853 w.write( "\t" + entry.getValue().median() );
2860 w.write( "Gained once, domain lengths:" );
2862 w.write( "N: " + gained_once_domain_length_count );
2864 w.write( "Avg: " + ( ( double ) gained_once_domain_length_sum / gained_once_domain_length_count ) );
2867 w.write( "Gained multiple times, domain lengths:" );
2869 w.write( "N: " + gained_multiple_times_domain_length_count );
2872 + ( ( double ) gained_multiple_times_domain_length_sum / gained_multiple_times_domain_length_count ) );
2877 w.write( "Gained once, protein lengths:" );
2879 w.write( gained_once_lengths_stats.toString() );
2880 gained_once_lengths_stats = null;
2883 w.write( "Gained once, domain counts:" );
2885 w.write( gained_once_domain_count_stats.toString() );
2886 gained_once_domain_count_stats = null;
2889 w.write( "Gained multiple times, protein lengths:" );
2891 w.write( gained_multiple_times_lengths_stats.toString() );
2892 gained_multiple_times_lengths_stats = null;
2895 w.write( "Gained multiple times, domain counts:" );
2897 w.write( gained_multiple_times_domain_count_stats.toString() );
2902 catch ( final IOException e ) {
2903 ForesterUtil.printWarningMessage( surfacing.PRG_NAME, "Failure to write: " + e );
2905 ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote independent domain combination gains fitch counts to ["
2906 + outfilename_for_counts + "]" );
2907 ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote independent domain combination gains fitch lists to ["
2908 + outfilename_for_dc + "]" );
2909 ForesterUtil.programMessage( surfacing.PRG_NAME,
2910 "Wrote independent domain combination gains fitch lists to (for GO mapping) ["
2911 + outfilename_for_dc_for_go_mapping + "]" );
2912 ForesterUtil.programMessage( surfacing.PRG_NAME,
2913 "Wrote independent domain combination gains fitch lists to (for GO mapping, unique) ["
2914 + outfilename_for_dc_for_go_mapping_unique + "]" );
2917 private static SortedSet<String> collectAllDomainsChangedOnSubtree( final PhylogenyNode subtree_root,
2918 final boolean get_gains ) {
2919 final SortedSet<String> domains = new TreeSet<String>();
2920 for( final PhylogenyNode descendant : PhylogenyMethods.getAllDescendants( subtree_root ) ) {
2921 final BinaryCharacters chars = descendant.getNodeData().getBinaryCharacters();
2923 domains.addAll( chars.getGainedCharacters() );
2926 domains.addAll( chars.getLostCharacters() );
2932 private static File createBaseDirForPerNodeDomainFiles( final String base_dir,
2933 final boolean domain_combinations,
2934 final CharacterStateMatrix.GainLossStates state,
2935 final String outfile ) {
2936 File per_node_go_mapped_domain_gain_loss_files_base_dir = new File( new File( outfile ).getParent()
2937 + ForesterUtil.FILE_SEPARATOR + base_dir );
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 ( domain_combinations ) {
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 + "DC" );
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 + "DOMAINS" );
2949 if ( !per_node_go_mapped_domain_gain_loss_files_base_dir.exists() ) {
2950 per_node_go_mapped_domain_gain_loss_files_base_dir.mkdir();
2952 if ( state == GainLossStates.GAIN ) {
2953 per_node_go_mapped_domain_gain_loss_files_base_dir = new File( per_node_go_mapped_domain_gain_loss_files_base_dir
2954 + ForesterUtil.FILE_SEPARATOR + "GAINS" );
2956 else if ( state == GainLossStates.LOSS ) {
2957 per_node_go_mapped_domain_gain_loss_files_base_dir = new File( per_node_go_mapped_domain_gain_loss_files_base_dir
2958 + ForesterUtil.FILE_SEPARATOR + "LOSSES" );
2961 per_node_go_mapped_domain_gain_loss_files_base_dir = new File( per_node_go_mapped_domain_gain_loss_files_base_dir
2962 + ForesterUtil.FILE_SEPARATOR + "PRESENT" );
2964 if ( !per_node_go_mapped_domain_gain_loss_files_base_dir.exists() ) {
2965 per_node_go_mapped_domain_gain_loss_files_base_dir.mkdir();
2967 return per_node_go_mapped_domain_gain_loss_files_base_dir;
2970 private static SortedSet<BinaryDomainCombination> createSetOfAllBinaryDomainCombinationsPerGenome( final GenomeWideCombinableDomains gwcd ) {
2971 final SortedMap<String, CombinableDomains> cds = gwcd.getAllCombinableDomainsIds();
2972 final SortedSet<BinaryDomainCombination> binary_combinations = new TreeSet<BinaryDomainCombination>();
2973 for( final String domain_id : cds.keySet() ) {
2974 final CombinableDomains cd = cds.get( domain_id );
2975 binary_combinations.addAll( cd.toBinaryDomainCombinations() );
2977 return binary_combinations;
2980 private static void printSomeStats( final DescriptiveStatistics stats, final AsciiHistogram histo, final Writer w )
2981 throws IOException {
2984 w.write( SurfacingConstants.NL );
2985 w.write( "<tt><pre>" );
2986 w.write( SurfacingConstants.NL );
2987 if ( histo != null ) {
2988 w.write( histo.toStringBuffer( 20, '|', 40, 5 ).toString() );
2989 w.write( SurfacingConstants.NL );
2991 w.write( "</pre></tt>" );
2992 w.write( SurfacingConstants.NL );
2993 w.write( "<table>" );
2994 w.write( SurfacingConstants.NL );
2995 w.write( "<tr><td>N: </td><td>" + stats.getN() + "</td></tr>" );
2996 w.write( SurfacingConstants.NL );
2997 w.write( "<tr><td>Min: </td><td>" + stats.getMin() + "</td></tr>" );
2998 w.write( SurfacingConstants.NL );
2999 w.write( "<tr><td>Max: </td><td>" + stats.getMax() + "</td></tr>" );
3000 w.write( SurfacingConstants.NL );
3001 w.write( "<tr><td>Mean: </td><td>" + stats.arithmeticMean() + "</td></tr>" );
3002 w.write( SurfacingConstants.NL );
3003 if ( stats.getN() > 1 ) {
3004 w.write( "<tr><td>SD: </td><td>" + stats.sampleStandardDeviation() + "</td></tr>" );
3007 w.write( "<tr><td>SD: </td><td>n/a</td></tr>" );
3009 w.write( SurfacingConstants.NL );
3010 w.write( "</table>" );
3011 w.write( SurfacingConstants.NL );
3013 w.write( SurfacingConstants.NL );
3016 private static List<String> splitDomainCombination( final String dc ) {
3017 final String[] s = dc.split( "=" );
3018 if ( s.length != 2 ) {
3019 ForesterUtil.printErrorMessage( surfacing.PRG_NAME, "Stringyfied domain combination has illegal format: "
3023 final List<String> l = new ArrayList<String>( 2 );
3029 private static void writeAllEncounteredPfamsToFile( final Map<String, List<GoId>> domain_id_to_go_ids_map,
3030 final Map<GoId, GoTerm> go_id_to_term_map,
3031 final String outfile_name,
3032 final SortedSet<String> all_pfams_encountered ) {
3033 final File all_pfams_encountered_file = new File( outfile_name + surfacing.ALL_PFAMS_ENCOUNTERED_SUFFIX );
3034 final File all_pfams_encountered_with_go_annotation_file = new File( outfile_name
3035 + surfacing.ALL_PFAMS_ENCOUNTERED_WITH_GO_ANNOTATION_SUFFIX );
3036 final File encountered_pfams_summary_file = new File( outfile_name + surfacing.ENCOUNTERED_PFAMS_SUMMARY_SUFFIX );
3037 int biological_process_counter = 0;
3038 int cellular_component_counter = 0;
3039 int molecular_function_counter = 0;
3040 int pfams_with_mappings_counter = 0;
3041 int pfams_without_mappings_counter = 0;
3042 int pfams_without_mappings_to_bp_or_mf_counter = 0;
3043 int pfams_with_mappings_to_bp_or_mf_counter = 0;
3045 final Writer all_pfams_encountered_writer = new BufferedWriter( new FileWriter( all_pfams_encountered_file ) );
3046 final Writer all_pfams_encountered_with_go_annotation_writer = new BufferedWriter( new FileWriter( all_pfams_encountered_with_go_annotation_file ) );
3047 final Writer summary_writer = new BufferedWriter( new FileWriter( encountered_pfams_summary_file ) );
3048 summary_writer.write( "# Pfam to GO mapping summary" );
3049 summary_writer.write( ForesterUtil.LINE_SEPARATOR );
3050 summary_writer.write( "# Actual summary is at the end of this file." );
3051 summary_writer.write( ForesterUtil.LINE_SEPARATOR );
3052 summary_writer.write( "# Encountered Pfams without a GO mapping:" );
3053 summary_writer.write( ForesterUtil.LINE_SEPARATOR );
3054 for( final String pfam : all_pfams_encountered ) {
3055 all_pfams_encountered_writer.write( pfam );
3056 all_pfams_encountered_writer.write( ForesterUtil.LINE_SEPARATOR );
3057 final String domain_id = new String( pfam );
3058 if ( domain_id_to_go_ids_map.containsKey( domain_id ) ) {
3059 ++pfams_with_mappings_counter;
3060 all_pfams_encountered_with_go_annotation_writer.write( pfam );
3061 all_pfams_encountered_with_go_annotation_writer.write( ForesterUtil.LINE_SEPARATOR );
3062 final List<GoId> go_ids = domain_id_to_go_ids_map.get( domain_id );
3063 boolean maps_to_bp = false;
3064 boolean maps_to_cc = false;
3065 boolean maps_to_mf = false;
3066 for( final GoId go_id : go_ids ) {
3067 final GoTerm go_term = go_id_to_term_map.get( go_id );
3068 if ( go_term.getGoNameSpace().isBiologicalProcess() ) {
3071 else if ( go_term.getGoNameSpace().isCellularComponent() ) {
3074 else if ( go_term.getGoNameSpace().isMolecularFunction() ) {
3079 ++biological_process_counter;
3082 ++cellular_component_counter;
3085 ++molecular_function_counter;
3087 if ( maps_to_bp || maps_to_mf ) {
3088 ++pfams_with_mappings_to_bp_or_mf_counter;
3091 ++pfams_without_mappings_to_bp_or_mf_counter;
3095 ++pfams_without_mappings_to_bp_or_mf_counter;
3096 ++pfams_without_mappings_counter;
3097 summary_writer.write( pfam );
3098 summary_writer.write( ForesterUtil.LINE_SEPARATOR );
3101 all_pfams_encountered_writer.close();
3102 all_pfams_encountered_with_go_annotation_writer.close();
3103 ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote all [" + all_pfams_encountered.size()
3104 + "] encountered Pfams to: \"" + all_pfams_encountered_file + "\"" );
3105 ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote all [" + pfams_with_mappings_counter
3106 + "] encountered Pfams with GO mappings to: \"" + all_pfams_encountered_with_go_annotation_file
3108 ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote summary (including all ["
3109 + pfams_without_mappings_counter + "] encountered Pfams without GO mappings) to: \""
3110 + encountered_pfams_summary_file + "\"" );
3111 ForesterUtil.programMessage( surfacing.PRG_NAME, "Sum of Pfams encountered : "
3112 + all_pfams_encountered.size() );
3113 ForesterUtil.programMessage( surfacing.PRG_NAME, "Pfams without a mapping : "
3114 + pfams_without_mappings_counter + " ["
3115 + ( ( 100 * pfams_without_mappings_counter ) / all_pfams_encountered.size() ) + "%]" );
3116 ForesterUtil.programMessage( surfacing.PRG_NAME, "Pfams without mapping to proc. or func. : "
3117 + pfams_without_mappings_to_bp_or_mf_counter + " ["
3118 + ( ( 100 * pfams_without_mappings_to_bp_or_mf_counter ) / all_pfams_encountered.size() ) + "%]" );
3119 ForesterUtil.programMessage( surfacing.PRG_NAME, "Pfams with a mapping : "
3120 + pfams_with_mappings_counter + " ["
3121 + ( ( 100 * pfams_with_mappings_counter ) / all_pfams_encountered.size() ) + "%]" );
3122 ForesterUtil.programMessage( surfacing.PRG_NAME, "Pfams with a mapping to proc. or func. : "
3123 + pfams_with_mappings_to_bp_or_mf_counter + " ["
3124 + ( ( 100 * pfams_with_mappings_to_bp_or_mf_counter ) / all_pfams_encountered.size() ) + "%]" );
3125 ForesterUtil.programMessage( surfacing.PRG_NAME, "Pfams with mapping to biological process: "
3126 + biological_process_counter + " ["
3127 + ( ( 100 * biological_process_counter ) / all_pfams_encountered.size() ) + "%]" );
3128 ForesterUtil.programMessage( surfacing.PRG_NAME, "Pfams with mapping to molecular function: "
3129 + molecular_function_counter + " ["
3130 + ( ( 100 * molecular_function_counter ) / all_pfams_encountered.size() ) + "%]" );
3131 ForesterUtil.programMessage( surfacing.PRG_NAME, "Pfams with mapping to cellular component: "
3132 + cellular_component_counter + " ["
3133 + ( ( 100 * cellular_component_counter ) / all_pfams_encountered.size() ) + "%]" );
3134 summary_writer.write( ForesterUtil.LINE_SEPARATOR );
3135 summary_writer.write( "# Sum of Pfams encountered : " + all_pfams_encountered.size() );
3136 summary_writer.write( ForesterUtil.LINE_SEPARATOR );
3137 summary_writer.write( "# Pfams without a mapping : " + pfams_without_mappings_counter
3138 + " [" + ( ( 100 * pfams_without_mappings_counter ) / all_pfams_encountered.size() ) + "%]" );
3139 summary_writer.write( ForesterUtil.LINE_SEPARATOR );
3140 summary_writer.write( "# Pfams without mapping to proc. or func. : "
3141 + pfams_without_mappings_to_bp_or_mf_counter + " ["
3142 + ( ( 100 * pfams_without_mappings_to_bp_or_mf_counter ) / all_pfams_encountered.size() ) + "%]" );
3143 summary_writer.write( ForesterUtil.LINE_SEPARATOR );
3144 summary_writer.write( "# Pfams with a mapping : " + pfams_with_mappings_counter + " ["
3145 + ( ( 100 * pfams_with_mappings_counter ) / all_pfams_encountered.size() ) + "%]" );
3146 summary_writer.write( ForesterUtil.LINE_SEPARATOR );
3147 summary_writer.write( "# Pfams with a mapping to proc. or func. : "
3148 + pfams_with_mappings_to_bp_or_mf_counter + " ["
3149 + ( ( 100 * pfams_with_mappings_to_bp_or_mf_counter ) / all_pfams_encountered.size() ) + "%]" );
3150 summary_writer.write( ForesterUtil.LINE_SEPARATOR );
3151 summary_writer.write( "# Pfams with mapping to biological process: " + biological_process_counter + " ["
3152 + ( ( 100 * biological_process_counter ) / all_pfams_encountered.size() ) + "%]" );
3153 summary_writer.write( ForesterUtil.LINE_SEPARATOR );
3154 summary_writer.write( "# Pfams with mapping to molecular function: " + molecular_function_counter + " ["
3155 + ( ( 100 * molecular_function_counter ) / all_pfams_encountered.size() ) + "%]" );
3156 summary_writer.write( ForesterUtil.LINE_SEPARATOR );
3157 summary_writer.write( "# Pfams with mapping to cellular component: " + cellular_component_counter + " ["
3158 + ( ( 100 * cellular_component_counter ) / all_pfams_encountered.size() ) + "%]" );
3159 summary_writer.write( ForesterUtil.LINE_SEPARATOR );
3160 summary_writer.close();
3162 catch ( final IOException e ) {
3163 ForesterUtil.printWarningMessage( surfacing.PRG_NAME, "Failure to write: " + e );
3167 private final static void writeColorLabels( final String l, final Color c, final Writer w ) throws IOException {
3168 w.write( "<tr><td><b><span style=\"color:" );
3169 w.write( String.format( "#%02x%02x%02x", c.getRed(), c.getGreen(), c.getBlue() ) );
3172 w.write( "</span></b></td></tr>" );
3173 w.write( SurfacingConstants.NL );
3176 private static void writeDomainData( final Map<String, List<GoId>> domain_id_to_go_ids_map,
3177 final Map<GoId, GoTerm> go_id_to_term_map,
3178 final GoNameSpace go_namespace_limit,
3180 final String domain_0,
3181 final String domain_1,
3182 final String prefix_for_html,
3183 final String character_separator_for_non_html_output,
3184 final Map<String, Set<String>>[] domain_id_to_secondary_features_maps,
3185 final Set<GoId> all_go_ids ) throws IOException {
3186 boolean any_go_annotation_present = false;
3187 boolean first_has_no_go = false;
3188 int domain_count = 2; // To distinguish between domains and binary domain combinations.
3189 if ( ForesterUtil.isEmpty( domain_1 ) ) {
3192 // The following has a difficult to understand logic.
3193 for( int d = 0; d < domain_count; ++d ) {
3194 List<GoId> go_ids = null;
3195 boolean go_annotation_present = false;
3197 if ( domain_id_to_go_ids_map.containsKey( domain_0 ) ) {
3198 go_annotation_present = true;
3199 any_go_annotation_present = true;
3200 go_ids = domain_id_to_go_ids_map.get( domain_0 );
3203 first_has_no_go = true;
3207 if ( domain_id_to_go_ids_map.containsKey( domain_1 ) ) {
3208 go_annotation_present = true;
3209 any_go_annotation_present = true;
3210 go_ids = domain_id_to_go_ids_map.get( domain_1 );
3213 if ( go_annotation_present ) {
3214 boolean first = ( ( d == 0 ) || ( ( d == 1 ) && first_has_no_go ) );
3215 for( final GoId go_id : go_ids ) {
3216 out.write( "<tr>" );
3219 writeDomainIdsToHtml( out,
3223 domain_id_to_secondary_features_maps );
3226 out.write( "<td></td>" );
3228 if ( !go_id_to_term_map.containsKey( go_id ) ) {
3229 throw new IllegalArgumentException( "GO-id [" + go_id + "] not found in GO-id to GO-term map" );
3231 final GoTerm go_term = go_id_to_term_map.get( go_id );
3232 if ( ( go_namespace_limit == null ) || go_namespace_limit.equals( go_term.getGoNameSpace() ) ) {
3233 // final String top = GoUtils.getPenultimateGoTerm( go_term, go_id_to_term_map ).getName();
3234 final String go_id_str = go_id.getId();
3235 out.write( "<td>" );
3236 out.write( "<a href=\"" + SurfacingConstants.AMIGO_LINK + go_id_str
3237 + "\" target=\"amigo_window\">" + go_id_str + "</a>" );
3238 out.write( "</td><td>" );
3239 out.write( go_term.getName() );
3240 if ( domain_count == 2 ) {
3241 out.write( " (" + d + ")" );
3243 out.write( "</td><td>" );
3244 // out.write( top );
3245 // out.write( "</td><td>" );
3247 out.write( go_term.getGoNameSpace().toShortString() );
3249 out.write( "</td>" );
3250 if ( all_go_ids != null ) {
3251 all_go_ids.add( go_id );
3255 out.write( "<td>" );
3256 out.write( "</td><td>" );
3257 out.write( "</td><td>" );
3258 out.write( "</td><td>" );
3259 out.write( "</td>" );
3261 out.write( "</tr>" );
3262 out.write( SurfacingConstants.NL );
3265 } // for( int d = 0; d < domain_count; ++d )
3266 if ( !any_go_annotation_present ) {
3267 out.write( "<tr>" );
3268 writeDomainIdsToHtml( out, domain_0, domain_1, prefix_for_html, domain_id_to_secondary_features_maps );
3269 out.write( "<td>" );
3270 out.write( "</td><td>" );
3271 out.write( "</td><td>" );
3272 out.write( "</td><td>" );
3273 out.write( "</td>" );
3274 out.write( "</tr>" );
3275 out.write( SurfacingConstants.NL );
3279 private static void writeDomainIdsToHtml( final Writer out,
3280 final String domain_0,
3281 final String domain_1,
3282 final String prefix_for_detailed_html,
3283 final Map<String, Set<String>>[] domain_id_to_secondary_features_maps )
3284 throws IOException {
3285 out.write( "<td>" );
3286 if ( !ForesterUtil.isEmpty( prefix_for_detailed_html ) ) {
3287 out.write( prefix_for_detailed_html );
3290 out.write( "<a href=\"" + SurfacingConstants.PFAM_FAMILY_ID_LINK + domain_0 + "\">" + domain_0 + "</a>" );
3291 out.write( "</td>" );
3294 private static void writeDomainsToIndividualFilePerTreeNode( final Writer individual_files_writer,
3295 final String domain_0,
3296 final String domain_1 ) throws IOException {
3297 individual_files_writer.write( domain_0 );
3298 individual_files_writer.write( ForesterUtil.LINE_SEPARATOR );
3299 if ( !ForesterUtil.isEmpty( domain_1 ) ) {
3300 individual_files_writer.write( domain_1 );
3301 individual_files_writer.write( ForesterUtil.LINE_SEPARATOR );
3305 private static void writePfamsToFile( final String outfile_name, final SortedSet<String> pfams ) {
3307 final Writer writer = new BufferedWriter( new FileWriter( new File( outfile_name ) ) );
3308 for( final String pfam : pfams ) {
3309 writer.write( pfam );
3310 writer.write( ForesterUtil.LINE_SEPARATOR );
3313 ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote " + pfams.size() + " pfams to [" + outfile_name
3316 catch ( final IOException e ) {
3317 ForesterUtil.printWarningMessage( surfacing.PRG_NAME, "Failure to write: " + e );
3321 private static void writeToNexus( final String outfile_name,
3322 final CharacterStateMatrix<BinaryStates> matrix,
3323 final Phylogeny phylogeny ) {
3324 if ( !( matrix instanceof BasicCharacterStateMatrix ) ) {
3325 throw new IllegalArgumentException( "can only write matrices of type [" + BasicCharacterStateMatrix.class
3328 final BasicCharacterStateMatrix<BinaryStates> my_matrix = ( org.forester.evoinference.matrix.character.BasicCharacterStateMatrix<BinaryStates> ) matrix;
3329 final List<Phylogeny> phylogenies = new ArrayList<Phylogeny>( 1 );
3330 phylogenies.add( phylogeny );
3332 final BufferedWriter w = new BufferedWriter( new FileWriter( outfile_name ) );
3333 w.write( NexusConstants.NEXUS );
3334 w.write( ForesterUtil.LINE_SEPARATOR );
3335 my_matrix.writeNexusTaxaBlock( w );
3336 my_matrix.writeNexusBinaryChractersBlock( w );
3337 PhylogenyWriter.writeNexusTreesBlock( w, phylogenies, NH_CONVERSION_SUPPORT_VALUE_STYLE.NONE );
3340 ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote Nexus file: \"" + outfile_name + "\"" );
3342 catch ( final IOException e ) {
3343 ForesterUtil.fatalError( surfacing.PRG_NAME, e.getMessage() );
3347 private static void writeToNexus( final String outfile_name,
3348 final DomainParsimonyCalculator domain_parsimony,
3349 final Phylogeny phylogeny ) {
3350 writeToNexus( outfile_name + surfacing.NEXUS_EXTERNAL_DOMAINS,
3351 domain_parsimony.createMatrixOfDomainPresenceOrAbsence(),
3353 writeToNexus( outfile_name + surfacing.NEXUS_EXTERNAL_DOMAIN_COMBINATIONS,
3354 domain_parsimony.createMatrixOfBinaryDomainCombinationPresenceOrAbsence(),
3358 final static class DomainComparator implements Comparator<Domain> {
3360 final private boolean _ascending;
3362 public DomainComparator( final boolean ascending ) {
3363 _ascending = ascending;
3367 public final int compare( final Domain d0, final Domain d1 ) {
3368 if ( d0.getFrom() < d1.getFrom() ) {
3369 return _ascending ? -1 : 1;
3371 else if ( d0.getFrom() > d1.getFrom() ) {
3372 return _ascending ? 1 : -1;