3 // FORESTER -- software libraries and applications
4 // for evolutionary biology research and applications.
6 // Copyright (C) 2008-2009 Christian M. Zmasek
7 // Copyright (C) 2008-2009 Burnham Institute for Medical Research
10 // This library is free software; you can redistribute it and/or
11 // modify it under the terms of the GNU Lesser General Public
12 // License as published by the Free Software Foundation; either
13 // version 2.1 of the License, or (at your option) any later version.
15 // This library is distributed in the hope that it will be useful,
16 // but WITHOUT ANY WARRANTY; without even the implied warranty of
17 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
18 // Lesser General Public License for more details.
20 // You should have received a copy of the GNU Lesser General Public
21 // License along with this library; if not, write to the Free Software
22 // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
24 // Contact: phylosoft @ gmail . com
25 // WWW: https://sites.google.com/site/cmzmasek/home/software/forester
27 package org.forester.surfacing;
29 import java.io.BufferedWriter;
31 import java.io.FileWriter;
32 import java.io.IOException;
33 import java.io.Writer;
34 import java.text.DecimalFormat;
35 import java.text.NumberFormat;
36 import java.util.ArrayList;
37 import java.util.Arrays;
38 import java.util.Collections;
39 import java.util.Comparator;
40 import java.util.HashMap;
41 import java.util.HashSet;
42 import java.util.Iterator;
43 import java.util.List;
45 import java.util.Map.Entry;
46 import java.util.PriorityQueue;
48 import java.util.SortedMap;
49 import java.util.SortedSet;
50 import java.util.TreeMap;
51 import java.util.TreeSet;
52 import java.util.regex.Matcher;
53 import java.util.regex.Pattern;
55 import org.forester.application.surfacing;
56 import org.forester.evoinference.distance.NeighborJoining;
57 import org.forester.evoinference.matrix.character.BasicCharacterStateMatrix;
58 import org.forester.evoinference.matrix.character.CharacterStateMatrix;
59 import org.forester.evoinference.matrix.character.CharacterStateMatrix.BinaryStates;
60 import org.forester.evoinference.matrix.character.CharacterStateMatrix.Format;
61 import org.forester.evoinference.matrix.character.CharacterStateMatrix.GainLossStates;
62 import org.forester.evoinference.matrix.distance.BasicSymmetricalDistanceMatrix;
63 import org.forester.evoinference.matrix.distance.DistanceMatrix;
64 import org.forester.go.GoId;
65 import org.forester.go.GoNameSpace;
66 import org.forester.go.GoTerm;
67 import org.forester.go.PfamToGoMapping;
68 import org.forester.io.parsers.nexus.NexusConstants;
69 import org.forester.io.writers.PhylogenyWriter;
70 import org.forester.phylogeny.Phylogeny;
71 import org.forester.phylogeny.PhylogenyMethods;
72 import org.forester.phylogeny.PhylogenyNode;
73 import org.forester.phylogeny.PhylogenyNode.NH_CONVERSION_SUPPORT_VALUE_STYLE;
74 import org.forester.phylogeny.data.BinaryCharacters;
75 import org.forester.phylogeny.data.Confidence;
76 import org.forester.phylogeny.data.Taxonomy;
77 import org.forester.phylogeny.iterators.PhylogenyNodeIterator;
78 import org.forester.protein.BasicDomain;
79 import org.forester.protein.BasicProtein;
80 import org.forester.protein.BinaryDomainCombination;
81 import org.forester.protein.Domain;
82 import org.forester.protein.DomainId;
83 import org.forester.protein.Protein;
84 import org.forester.species.Species;
85 import org.forester.surfacing.DomainSimilarityCalculator.Detailedness;
86 import org.forester.surfacing.DomainSimilarityCalculator.GoAnnotationOutput;
87 import org.forester.surfacing.GenomeWideCombinableDomains.GenomeWideCombinableDomainsSortOrder;
88 import org.forester.util.AsciiHistogram;
89 import org.forester.util.BasicDescriptiveStatistics;
90 import org.forester.util.BasicTable;
91 import org.forester.util.BasicTableParser;
92 import org.forester.util.DescriptiveStatistics;
93 import org.forester.util.ForesterUtil;
95 public final class SurfacingUtil {
97 private final static NumberFormat FORMATTER_3 = new DecimalFormat( "0.000" );
98 private static final Comparator<Domain> ASCENDING_CONFIDENCE_VALUE_ORDER = new Comparator<Domain>() {
101 public int compare( final Domain d1,
103 if ( d1.getPerSequenceEvalue() < d2
104 .getPerSequenceEvalue() ) {
108 .getPerSequenceEvalue() > d2
109 .getPerSequenceEvalue() ) {
113 return d1.compareTo( d2 );
117 public final static Pattern PATTERN_SP_STYLE_TAXONOMY = Pattern.compile( "^[A-Z0-9]{3,5}$" );
118 private static final boolean USE_LAST = true;
120 private SurfacingUtil() {
121 // Hidden constructor.
124 public static void addAllBinaryDomainCombinationToSet( final GenomeWideCombinableDomains genome,
125 final SortedSet<BinaryDomainCombination> binary_domain_combinations ) {
126 final SortedMap<DomainId, CombinableDomains> all_cd = genome.getAllCombinableDomainsIds();
127 for( final DomainId domain_id : all_cd.keySet() ) {
128 binary_domain_combinations.addAll( all_cd.get( domain_id ).toBinaryDomainCombinations() );
132 public static void addAllDomainIdsToSet( final GenomeWideCombinableDomains genome,
133 final SortedSet<DomainId> domain_ids ) {
134 final SortedSet<DomainId> domains = genome.getAllDomainIds();
135 for( final DomainId domain : domains ) {
136 domain_ids.add( domain );
140 public static void addHtmlHead( final Writer w, final String title ) throws IOException {
141 w.write( SurfacingConstants.NL );
143 w.write( "<title>" );
145 w.write( "</title>" );
146 w.write( SurfacingConstants.NL );
147 w.write( "<style>" );
148 w.write( SurfacingConstants.NL );
149 w.write( "a:visited { color : #6633FF; text-decoration : none; }" );
150 w.write( SurfacingConstants.NL );
151 w.write( "a:link { color : #6633FF; text-decoration : none; }" );
152 w.write( SurfacingConstants.NL );
153 w.write( "a:active { color : #99FF00; text-decoration : none; }" );
154 w.write( SurfacingConstants.NL );
155 w.write( "a:hover { color : #FFFFFF; background-color : #99FF00; text-decoration : none; }" );
156 w.write( SurfacingConstants.NL );
157 w.write( "td { text-align: left; vertical-align: top; font-family: Verdana, Arial, Helvetica; font-size: 8pt}" );
158 w.write( SurfacingConstants.NL );
159 w.write( "h1 { color : #0000FF; font-family: Verdana, Arial, Helvetica; font-size: 18pt; font-weight: bold }" );
160 w.write( SurfacingConstants.NL );
161 w.write( "h2 { color : #0000FF; font-family: Verdana, Arial, Helvetica; font-size: 16pt; font-weight: bold }" );
162 w.write( SurfacingConstants.NL );
163 w.write( "</style>" );
164 w.write( SurfacingConstants.NL );
165 w.write( "</head>" );
166 w.write( SurfacingConstants.NL );
169 public static DescriptiveStatistics calculateDescriptiveStatisticsForMeanValues( final Set<DomainSimilarity> similarities ) {
170 final DescriptiveStatistics stats = new BasicDescriptiveStatistics();
171 for( final DomainSimilarity similarity : similarities ) {
172 stats.addValue( similarity.getMeanSimilarityScore() );
177 public static int calculateOverlap( final Domain domain, final List<Boolean> covered_positions ) {
178 int overlap_count = 0;
179 for( int i = domain.getFrom(); i <= domain.getTo(); ++i ) {
180 if ( ( i < covered_positions.size() ) && ( covered_positions.get( i ) == true ) ) {
184 return overlap_count;
187 public static void checkForOutputFileWriteability( final File outfile ) {
188 final String error = ForesterUtil.isWritableFile( outfile );
189 if ( !ForesterUtil.isEmpty( error ) ) {
190 ForesterUtil.fatalError( surfacing.PRG_NAME, error );
194 public static void collectChangedDomainCombinationsFromBinaryStatesMatrixAsListToFile( final CharacterStateMatrix<CharacterStateMatrix.GainLossStates> matrix,
195 final BinaryDomainCombination.DomainCombinationType dc_type,
196 final List<BinaryDomainCombination> all_binary_domains_combination_gained,
197 final boolean get_gains ) {
198 final SortedSet<String> sorted_ids = new TreeSet<String>();
199 for( int i = 0; i < matrix.getNumberOfIdentifiers(); ++i ) {
200 sorted_ids.add( matrix.getIdentifier( i ) );
202 for( final String id : sorted_ids ) {
203 for( int c = 0; c < matrix.getNumberOfCharacters(); ++c ) {
204 if ( ( get_gains && ( matrix.getState( id, c ) == CharacterStateMatrix.GainLossStates.GAIN ) )
205 || ( !get_gains && ( matrix.getState( id, c ) == CharacterStateMatrix.GainLossStates.LOSS ) ) ) {
206 if ( dc_type == BinaryDomainCombination.DomainCombinationType.DIRECTED_ADJACTANT ) {
207 all_binary_domains_combination_gained.add( AdjactantDirectedBinaryDomainCombination
208 .createInstance( matrix.getCharacter( c ) ) );
210 else if ( dc_type == BinaryDomainCombination.DomainCombinationType.DIRECTED ) {
211 all_binary_domains_combination_gained.add( DirectedBinaryDomainCombination
212 .createInstance( matrix.getCharacter( c ) ) );
215 all_binary_domains_combination_gained.add( BasicBinaryDomainCombination.createInstance( matrix
216 .getCharacter( c ) ) );
223 public static Map<DomainId, List<GoId>> createDomainIdToGoIdMap( final List<PfamToGoMapping> pfam_to_go_mappings ) {
224 final Map<DomainId, List<GoId>> domain_id_to_go_ids_map = new HashMap<DomainId, List<GoId>>( pfam_to_go_mappings
226 for( final PfamToGoMapping pfam_to_go : pfam_to_go_mappings ) {
227 if ( !domain_id_to_go_ids_map.containsKey( pfam_to_go.getKey() ) ) {
228 domain_id_to_go_ids_map.put( pfam_to_go.getKey(), new ArrayList<GoId>() );
230 domain_id_to_go_ids_map.get( pfam_to_go.getKey() ).add( pfam_to_go.getValue() );
232 return domain_id_to_go_ids_map;
235 public static Map<DomainId, Set<String>> createDomainIdToSecondaryFeaturesMap( final File secondary_features_map_file )
237 final BasicTable<String> primary_table = BasicTableParser.parse( secondary_features_map_file, '\t' );
238 final Map<DomainId, Set<String>> map = new TreeMap<DomainId, Set<String>>();
239 for( int r = 0; r < primary_table.getNumberOfRows(); ++r ) {
240 final DomainId domain_id = new DomainId( primary_table.getValue( 0, r ) );
241 if ( !map.containsKey( domain_id ) ) {
242 map.put( domain_id, new HashSet<String>() );
244 map.get( domain_id ).add( primary_table.getValue( 1, r ) );
249 public static Phylogeny createNjTreeBasedOnMatrixToFile( final File nj_tree_outfile, final DistanceMatrix distance ) {
250 checkForOutputFileWriteability( nj_tree_outfile );
251 final NeighborJoining nj = NeighborJoining.createInstance();
252 final Phylogeny phylogeny = nj.execute( ( BasicSymmetricalDistanceMatrix ) distance );
253 phylogeny.setName( nj_tree_outfile.getName() );
254 writePhylogenyToFile( phylogeny, nj_tree_outfile.toString() );
258 public static Map<String, Integer> createTaxCodeToIdMap( final Phylogeny phy ) {
259 final Map<String, Integer> m = new HashMap<String, Integer>();
260 for( final PhylogenyNodeIterator iter = phy.iteratorExternalForward(); iter.hasNext(); ) {
261 final PhylogenyNode n = iter.next();
262 if ( n.getNodeData().isHasTaxonomy() ) {
263 final Taxonomy t = n.getNodeData().getTaxonomy();
264 final String c = t.getTaxonomyCode();
265 if ( !ForesterUtil.isEmpty( c ) ) {
266 if ( n.getNodeData().getTaxonomy() == null ) {
267 ForesterUtil.fatalError( surfacing.PRG_NAME, "no taxonomy id for node " + n );
269 final String id = n.getNodeData().getTaxonomy().getIdentifier().getValue();
270 if ( ForesterUtil.isEmpty( id ) ) {
271 ForesterUtil.fatalError( surfacing.PRG_NAME, "no taxonomy id for node " + n );
273 if ( m.containsKey( c ) ) {
274 ForesterUtil.fatalError( surfacing.PRG_NAME, "taxonomy code " + c + " is not unique" );
276 final int iid = Integer.valueOf( id );
277 if ( m.containsValue( iid ) ) {
278 ForesterUtil.fatalError( surfacing.PRG_NAME, "taxonomy id " + iid + " is not unique" );
284 ForesterUtil.fatalError( surfacing.PRG_NAME, "no taxonomy for node " + n );
290 public static void decoratePrintableDomainSimilarities( final SortedSet<DomainSimilarity> domain_similarities,
291 final Detailedness detailedness,
292 final GoAnnotationOutput go_annotation_output,
293 final Map<GoId, GoTerm> go_id_to_term_map,
294 final GoNameSpace go_namespace_limit ) {
295 if ( ( go_namespace_limit != null ) && ( ( go_id_to_term_map == null ) || go_id_to_term_map.isEmpty() ) ) {
296 throw new IllegalArgumentException( "attempt to use a GO namespace limit without a GO id to term map" );
298 for( final DomainSimilarity domain_similarity : domain_similarities ) {
299 if ( domain_similarity instanceof PrintableDomainSimilarity ) {
300 final PrintableDomainSimilarity printable_domain_similarity = ( PrintableDomainSimilarity ) domain_similarity;
301 printable_domain_similarity.setDetailedness( detailedness );
302 printable_domain_similarity.setGoAnnotationOutput( go_annotation_output );
303 printable_domain_similarity.setGoIdToTermMap( go_id_to_term_map );
304 printable_domain_similarity.setGoNamespaceLimit( go_namespace_limit );
309 public static void doit( final List<Protein> proteins,
310 final List<DomainId> query_domain_ids_nc_order,
312 final String separator,
313 final String limit_to_species,
314 final Map<String, List<Integer>> average_protein_lengths_by_dc ) throws IOException {
315 for( final Protein protein : proteins ) {
316 if ( ForesterUtil.isEmpty( limit_to_species )
317 || protein.getSpecies().getSpeciesId().equalsIgnoreCase( limit_to_species ) ) {
318 if ( protein.contains( query_domain_ids_nc_order, true ) ) {
319 out.write( protein.getSpecies().getSpeciesId() );
320 out.write( separator );
321 out.write( protein.getProteinId().getId() );
322 out.write( separator );
324 final Set<DomainId> visited_domain_ids = new HashSet<DomainId>();
325 boolean first = true;
326 for( final Domain domain : protein.getProteinDomains() ) {
327 if ( !visited_domain_ids.contains( domain.getDomainId() ) ) {
328 visited_domain_ids.add( domain.getDomainId() );
335 out.write( domain.getDomainId().getId() );
337 out.write( "" + domain.getTotalCount() );
342 out.write( separator );
343 if ( !( ForesterUtil.isEmpty( protein.getDescription() ) || protein.getDescription()
344 .equals( SurfacingConstants.NONE ) ) ) {
345 out.write( protein.getDescription() );
347 out.write( separator );
348 if ( !( ForesterUtil.isEmpty( protein.getAccession() ) || protein.getAccession()
349 .equals( SurfacingConstants.NONE ) ) ) {
350 out.write( protein.getAccession() );
352 out.write( SurfacingConstants.NL );
359 public static void domainsPerProteinsStatistics( final String genome,
360 final List<Protein> protein_list,
361 final DescriptiveStatistics all_genomes_domains_per_potein_stats,
362 final SortedMap<Integer, Integer> all_genomes_domains_per_potein_histo,
363 final SortedSet<String> domains_which_are_always_single,
364 final SortedSet<String> domains_which_are_sometimes_single_sometimes_not,
365 final SortedSet<String> domains_which_never_single,
366 final Writer writer ) {
367 final DescriptiveStatistics stats = new BasicDescriptiveStatistics();
368 for( final Protein protein : protein_list ) {
369 final int domains = protein.getNumberOfProteinDomains();
370 //System.out.println( domains );
371 stats.addValue( domains );
372 all_genomes_domains_per_potein_stats.addValue( domains );
373 if ( !all_genomes_domains_per_potein_histo.containsKey( domains ) ) {
374 all_genomes_domains_per_potein_histo.put( domains, 1 );
377 all_genomes_domains_per_potein_histo.put( domains,
378 1 + all_genomes_domains_per_potein_histo.get( domains ) );
380 if ( domains == 1 ) {
381 final String domain = protein.getProteinDomain( 0 ).getDomainId().getId();
382 if ( !domains_which_are_sometimes_single_sometimes_not.contains( domain ) ) {
383 if ( domains_which_never_single.contains( domain ) ) {
384 domains_which_never_single.remove( domain );
385 domains_which_are_sometimes_single_sometimes_not.add( domain );
388 domains_which_are_always_single.add( domain );
392 else if ( domains > 1 ) {
393 for( final Domain d : protein.getProteinDomains() ) {
394 final String domain = d.getDomainId().getId();
395 // System.out.println( domain );
396 if ( !domains_which_are_sometimes_single_sometimes_not.contains( domain ) ) {
397 if ( domains_which_are_always_single.contains( domain ) ) {
398 domains_which_are_always_single.remove( domain );
399 domains_which_are_sometimes_single_sometimes_not.add( domain );
402 domains_which_never_single.add( domain );
409 writer.write( genome );
410 writer.write( "\t" );
411 if ( stats.getN() >= 1 ) {
412 writer.write( stats.arithmeticMean() + "" );
413 writer.write( "\t" );
414 if ( stats.getN() >= 2 ) {
415 writer.write( stats.sampleStandardDeviation() + "" );
420 writer.write( "\t" );
421 writer.write( stats.median() + "" );
422 writer.write( "\t" );
423 writer.write( stats.getN() + "" );
424 writer.write( "\t" );
425 writer.write( stats.getMin() + "" );
426 writer.write( "\t" );
427 writer.write( stats.getMax() + "" );
430 writer.write( "\t" );
431 writer.write( "\t" );
432 writer.write( "\t" );
434 writer.write( "\t" );
435 writer.write( "\t" );
437 writer.write( "\n" );
439 catch ( final IOException e ) {
444 public static void executeDomainLengthAnalysis( final String[][] input_file_properties,
445 final int number_of_genomes,
446 final DomainLengthsTable domain_lengths_table,
447 final File outfile ) throws IOException {
448 final DecimalFormat df = new DecimalFormat( "#.00" );
449 checkForOutputFileWriteability( outfile );
450 final BufferedWriter out = new BufferedWriter( new FileWriter( outfile ) );
451 out.write( "MEAN BASED STATISTICS PER SPECIES" );
452 out.write( ForesterUtil.LINE_SEPARATOR );
453 out.write( domain_lengths_table.createMeanBasedStatisticsPerSpeciesTable().toString() );
454 out.write( ForesterUtil.LINE_SEPARATOR );
455 out.write( ForesterUtil.LINE_SEPARATOR );
456 final List<DomainLengths> domain_lengths_list = domain_lengths_table.getDomainLengthsList();
457 out.write( "OUTLIER SPECIES PER DOMAIN (Z>=1.5)" );
458 out.write( ForesterUtil.LINE_SEPARATOR );
459 for( final DomainLengths domain_lengths : domain_lengths_list ) {
460 final List<Species> species_list = domain_lengths.getMeanBasedOutlierSpecies( 1.5 );
461 if ( species_list.size() > 0 ) {
462 out.write( domain_lengths.getDomainId() + "\t" );
463 for( final Species species : species_list ) {
464 out.write( species + "\t" );
466 out.write( ForesterUtil.LINE_SEPARATOR );
467 // DescriptiveStatistics stats_for_domain = domain_lengths
468 // .calculateMeanBasedStatistics();
469 //AsciiHistogram histo = new AsciiHistogram( stats_for_domain );
470 //System.out.println( histo.toStringBuffer( 40, '=', 60, 4 ).toString() );
473 out.write( ForesterUtil.LINE_SEPARATOR );
474 out.write( ForesterUtil.LINE_SEPARATOR );
475 out.write( "OUTLIER SPECIES (Z 1.0)" );
476 out.write( ForesterUtil.LINE_SEPARATOR );
477 final DescriptiveStatistics stats_for_all_species = domain_lengths_table
478 .calculateMeanBasedStatisticsForAllSpecies();
479 out.write( stats_for_all_species.asSummary() );
480 out.write( ForesterUtil.LINE_SEPARATOR );
481 final AsciiHistogram histo = new AsciiHistogram( stats_for_all_species );
482 out.write( histo.toStringBuffer( 40, '=', 60, 4 ).toString() );
483 out.write( ForesterUtil.LINE_SEPARATOR );
484 final double population_sd = stats_for_all_species.sampleStandardDeviation();
485 final double population_mean = stats_for_all_species.arithmeticMean();
486 for( final Species species : domain_lengths_table.getSpecies() ) {
487 final double x = domain_lengths_table.calculateMeanBasedStatisticsForSpecies( species ).arithmeticMean();
488 final double z = ( x - population_mean ) / population_sd;
489 out.write( species + "\t" + z );
490 out.write( ForesterUtil.LINE_SEPARATOR );
492 out.write( ForesterUtil.LINE_SEPARATOR );
493 for( final Species species : domain_lengths_table.getSpecies() ) {
494 final DescriptiveStatistics stats_for_species = domain_lengths_table
495 .calculateMeanBasedStatisticsForSpecies( species );
496 final double x = stats_for_species.arithmeticMean();
497 final double z = ( x - population_mean ) / population_sd;
498 if ( ( z <= -1.0 ) || ( z >= 1.0 ) ) {
499 out.write( species + "\t" + df.format( z ) + "\t" + stats_for_species.asSummary() );
500 out.write( ForesterUtil.LINE_SEPARATOR );
504 // final List<HistogramData> histogram_datas = new ArrayList<HistogramData>();
505 // for( int i = 0; i < number_of_genomes; ++i ) {
506 // final Species species = new BasicSpecies( input_file_properties[ i ][ 0 ] );
508 // .add( new HistogramData( species.toString(), domain_lengths_table
509 // .calculateMeanBasedStatisticsForSpecies( species )
510 // .getDataAsDoubleArray(), 5, 600, null, 60 ) );
512 // final HistogramsFrame hf = new HistogramsFrame( histogram_datas );
513 // hf.setVisible( true );
519 * @param all_binary_domains_combination_lost_fitch
520 * @param consider_directedness_and_adjacency_for_bin_combinations
521 * @param all_binary_domains_combination_gained if null ignored, otherwise this is to list all binary domain combinations
522 * which were gained under unweighted (Fitch) parsimony.
524 public static void executeParsimonyAnalysis( final long random_number_seed_for_fitch_parsimony,
525 final boolean radomize_fitch_parsimony,
526 final String outfile_name,
527 final DomainParsimonyCalculator domain_parsimony,
528 final Phylogeny phylogeny,
529 final Map<DomainId, List<GoId>> domain_id_to_go_ids_map,
530 final Map<GoId, GoTerm> go_id_to_term_map,
531 final GoNameSpace go_namespace_limit,
532 final String parameters_str,
533 final Map<DomainId, Set<String>>[] domain_id_to_secondary_features_maps,
534 final SortedSet<DomainId> positive_filter,
535 final boolean output_binary_domain_combinations_for_graphs,
536 final List<BinaryDomainCombination> all_binary_domains_combination_gained_fitch,
537 final List<BinaryDomainCombination> all_binary_domains_combination_lost_fitch,
538 final BinaryDomainCombination.DomainCombinationType dc_type,
539 final Map<String, DescriptiveStatistics> protein_length_stats_by_dc,
540 final Map<String, DescriptiveStatistics> domain_number_stats_by_dc,
541 final Map<String, DescriptiveStatistics> domain_length_stats_by_domain,
542 final Map<String, Integer> tax_code_to_id_map,
543 final boolean write_to_nexus ) {
544 final String sep = ForesterUtil.LINE_SEPARATOR + "###################" + ForesterUtil.LINE_SEPARATOR;
545 final String date_time = ForesterUtil.getCurrentDateTime();
546 final SortedSet<String> all_pfams_encountered = new TreeSet<String>();
547 final SortedSet<String> all_pfams_gained_as_domains = new TreeSet<String>();
548 final SortedSet<String> all_pfams_lost_as_domains = new TreeSet<String>();
549 final SortedSet<String> all_pfams_gained_as_dom_combinations = new TreeSet<String>();
550 final SortedSet<String> all_pfams_lost_as_dom_combinations = new TreeSet<String>();
551 if ( write_to_nexus ) {
552 writeToNexus( outfile_name, domain_parsimony, phylogeny );
556 Phylogeny local_phylogeny_l = phylogeny.copy();
557 if ( ( positive_filter != null ) && ( positive_filter.size() > 0 ) ) {
558 domain_parsimony.executeDolloParsimonyOnDomainPresence( positive_filter );
561 domain_parsimony.executeDolloParsimonyOnDomainPresence();
563 SurfacingUtil.writeMatrixToFile( domain_parsimony.getGainLossMatrix(), outfile_name
564 + surfacing.PARSIMONY_OUTPUT_GL_SUFFIX_DOLLO_DOMAINS, Format.FORESTER );
565 SurfacingUtil.writeMatrixToFile( domain_parsimony.getGainLossCountsMatrix(), outfile_name
566 + surfacing.PARSIMONY_OUTPUT_GL_COUNTS_SUFFIX_DOLLO_DOMAINS, Format.FORESTER );
567 SurfacingUtil.writeBinaryStatesMatrixAsListToFile( domain_parsimony.getGainLossMatrix(),
568 CharacterStateMatrix.GainLossStates.GAIN,
569 outfile_name + surfacing.PARSIMONY_OUTPUT_DOLLO_GAINS_D,
571 ForesterUtil.LINE_SEPARATOR,
573 SurfacingUtil.writeBinaryStatesMatrixAsListToFile( domain_parsimony.getGainLossMatrix(),
574 CharacterStateMatrix.GainLossStates.LOSS,
575 outfile_name + surfacing.PARSIMONY_OUTPUT_DOLLO_LOSSES_D,
577 ForesterUtil.LINE_SEPARATOR,
579 SurfacingUtil.writeBinaryStatesMatrixAsListToFile( domain_parsimony.getGainLossMatrix(), null, outfile_name
580 + surfacing.PARSIMONY_OUTPUT_DOLLO_PRESENT_D, sep, ForesterUtil.LINE_SEPARATOR, null );
582 writeBinaryStatesMatrixToList( domain_id_to_go_ids_map,
586 domain_parsimony.getGainLossMatrix(),
587 CharacterStateMatrix.GainLossStates.GAIN,
588 outfile_name + surfacing.PARSIMONY_OUTPUT_DOLLO_GAINS_HTML_D,
590 ForesterUtil.LINE_SEPARATOR,
591 "Dollo Parsimony | Gains | Domains",
593 domain_id_to_secondary_features_maps,
594 all_pfams_encountered,
595 all_pfams_gained_as_domains,
597 tax_code_to_id_map );
598 writeBinaryStatesMatrixToList( domain_id_to_go_ids_map,
602 domain_parsimony.getGainLossMatrix(),
603 CharacterStateMatrix.GainLossStates.LOSS,
604 outfile_name + surfacing.PARSIMONY_OUTPUT_DOLLO_LOSSES_HTML_D,
606 ForesterUtil.LINE_SEPARATOR,
607 "Dollo Parsimony | Losses | Domains",
609 domain_id_to_secondary_features_maps,
610 all_pfams_encountered,
611 all_pfams_lost_as_domains,
613 tax_code_to_id_map );
614 writeBinaryStatesMatrixToList( domain_id_to_go_ids_map,
618 domain_parsimony.getGainLossMatrix(),
620 outfile_name + surfacing.PARSIMONY_OUTPUT_DOLLO_PRESENT_HTML_D,
622 ForesterUtil.LINE_SEPARATOR,
623 "Dollo Parsimony | Present | Domains",
625 domain_id_to_secondary_features_maps,
626 all_pfams_encountered,
629 tax_code_to_id_map );
630 preparePhylogeny( local_phylogeny_l,
633 "Dollo parsimony on domain presence/absence",
634 "dollo_on_domains_" + outfile_name,
636 SurfacingUtil.writePhylogenyToFile( local_phylogeny_l, outfile_name
637 + surfacing.DOMAINS_PARSIMONY_TREE_OUTPUT_SUFFIX_DOLLO );
639 writeAllDomainsChangedOnAllSubtrees( local_phylogeny_l, true, outfile_name, "_dollo_all_gains_d" );
640 writeAllDomainsChangedOnAllSubtrees( local_phylogeny_l, false, outfile_name, "_dollo_all_losses_d" );
642 catch ( final IOException e ) {
644 ForesterUtil.fatalError( surfacing.PRG_NAME, e.getLocalizedMessage() );
646 if ( domain_parsimony.calculateNumberOfBinaryDomainCombination() > 0 ) {
647 // FITCH DOMAIN COMBINATIONS
648 // -------------------------
649 local_phylogeny_l = phylogeny.copy();
650 String randomization = "no";
651 if ( radomize_fitch_parsimony ) {
652 domain_parsimony.executeFitchParsimonyOnBinaryDomainCombintion( random_number_seed_for_fitch_parsimony );
653 randomization = "yes, seed = " + random_number_seed_for_fitch_parsimony;
656 domain_parsimony.executeFitchParsimonyOnBinaryDomainCombintion( USE_LAST );
658 SurfacingUtil.writeMatrixToFile( domain_parsimony.getGainLossMatrix(), outfile_name
659 + surfacing.PARSIMONY_OUTPUT_GL_SUFFIX_FITCH_BINARY_COMBINATIONS, Format.FORESTER );
660 SurfacingUtil.writeMatrixToFile( domain_parsimony.getGainLossCountsMatrix(), outfile_name
661 + surfacing.PARSIMONY_OUTPUT_GL_COUNTS_SUFFIX_FITCH_BINARY_COMBINATIONS, Format.FORESTER );
663 .writeBinaryStatesMatrixAsListToFile( domain_parsimony.getGainLossMatrix(),
664 CharacterStateMatrix.GainLossStates.GAIN,
665 outfile_name + surfacing.PARSIMONY_OUTPUT_FITCH_GAINS_BC,
667 ForesterUtil.LINE_SEPARATOR,
669 SurfacingUtil.writeBinaryStatesMatrixAsListToFile( domain_parsimony.getGainLossMatrix(),
670 CharacterStateMatrix.GainLossStates.LOSS,
672 + surfacing.PARSIMONY_OUTPUT_FITCH_LOSSES_BC,
674 ForesterUtil.LINE_SEPARATOR,
676 SurfacingUtil.writeBinaryStatesMatrixAsListToFile( domain_parsimony.getGainLossMatrix(), null, outfile_name
677 + surfacing.PARSIMONY_OUTPUT_FITCH_PRESENT_BC, sep, ForesterUtil.LINE_SEPARATOR, null );
678 if ( all_binary_domains_combination_gained_fitch != null ) {
679 collectChangedDomainCombinationsFromBinaryStatesMatrixAsListToFile( domain_parsimony.getGainLossMatrix(),
681 all_binary_domains_combination_gained_fitch,
684 if ( all_binary_domains_combination_lost_fitch != null ) {
685 collectChangedDomainCombinationsFromBinaryStatesMatrixAsListToFile( domain_parsimony.getGainLossMatrix(),
687 all_binary_domains_combination_lost_fitch,
690 if ( output_binary_domain_combinations_for_graphs ) {
692 .writeBinaryStatesMatrixAsListToFileForBinaryCombinationsForGraphAnalysis( domain_parsimony
693 .getGainLossMatrix(),
696 + surfacing.PARSIMONY_OUTPUT_FITCH_PRESENT_BC_OUTPUTFILE_SUFFIX_FOR_GRAPH_ANALYSIS,
698 ForesterUtil.LINE_SEPARATOR,
699 BinaryDomainCombination.OutputFormat.DOT );
702 writeBinaryStatesMatrixToList( domain_id_to_go_ids_map,
706 domain_parsimony.getGainLossMatrix(),
707 CharacterStateMatrix.GainLossStates.GAIN,
708 outfile_name + surfacing.PARSIMONY_OUTPUT_FITCH_GAINS_HTML_BC,
710 ForesterUtil.LINE_SEPARATOR,
711 "Fitch Parsimony | Gains | Domain Combinations",
714 all_pfams_encountered,
715 all_pfams_gained_as_dom_combinations,
717 tax_code_to_id_map );
718 writeBinaryStatesMatrixToList( domain_id_to_go_ids_map,
722 domain_parsimony.getGainLossMatrix(),
723 CharacterStateMatrix.GainLossStates.LOSS,
724 outfile_name + surfacing.PARSIMONY_OUTPUT_FITCH_LOSSES_HTML_BC,
726 ForesterUtil.LINE_SEPARATOR,
727 "Fitch Parsimony | Losses | Domain Combinations",
730 all_pfams_encountered,
731 all_pfams_lost_as_dom_combinations,
733 tax_code_to_id_map );
734 writeBinaryStatesMatrixToList( domain_id_to_go_ids_map,
738 domain_parsimony.getGainLossMatrix(),
740 outfile_name + surfacing.PARSIMONY_OUTPUT_FITCH_PRESENT_HTML_BC,
742 ForesterUtil.LINE_SEPARATOR,
743 "Fitch Parsimony | Present | Domain Combinations",
746 all_pfams_encountered,
749 tax_code_to_id_map );
750 writeAllEncounteredPfamsToFile( domain_id_to_go_ids_map,
753 all_pfams_encountered );
754 writePfamsToFile( outfile_name + surfacing.ALL_PFAMS_GAINED_AS_DOMAINS_SUFFIX, all_pfams_gained_as_domains );
755 writePfamsToFile( outfile_name + surfacing.ALL_PFAMS_LOST_AS_DOMAINS_SUFFIX, all_pfams_lost_as_domains );
756 writePfamsToFile( outfile_name + surfacing.ALL_PFAMS_GAINED_AS_DC_SUFFIX,
757 all_pfams_gained_as_dom_combinations );
758 writePfamsToFile( outfile_name + surfacing.ALL_PFAMS_LOST_AS_DC_SUFFIX, all_pfams_lost_as_dom_combinations );
759 preparePhylogeny( local_phylogeny_l,
762 "Fitch parsimony on binary domain combination presence/absence randomization: "
764 "fitch_on_binary_domain_combinations_" + outfile_name,
766 SurfacingUtil.writePhylogenyToFile( local_phylogeny_l, outfile_name
767 + surfacing.BINARY_DOMAIN_COMBINATIONS_PARSIMONY_TREE_OUTPUT_SUFFIX_FITCH );
768 calculateIndependentDomainCombinationGains( local_phylogeny_l,
770 + surfacing.INDEPENDENT_DC_GAINS_FITCH_PARS_COUNTS_OUTPUT_SUFFIX,
772 + surfacing.INDEPENDENT_DC_GAINS_FITCH_PARS_DC_OUTPUT_SUFFIX,
774 + surfacing.INDEPENDENT_DC_GAINS_FITCH_PARS_DC_FOR_GO_MAPPING_OUTPUT_SUFFIX,
776 + surfacing.INDEPENDENT_DC_GAINS_FITCH_PARS_DC_FOR_GO_MAPPING_OUTPUT_UNIQUE_SUFFIX,
777 outfile_name + "_indep_dc_gains_fitch_lca_ranks.txt",
778 outfile_name + "_indep_dc_gains_fitch_lca_taxonomies.txt",
779 outfile_name + "_indep_dc_gains_fitch_protein_statistics.txt",
780 protein_length_stats_by_dc,
781 domain_number_stats_by_dc,
782 domain_length_stats_by_domain );
786 public static void executeParsimonyAnalysisForSecondaryFeatures( final String outfile_name,
787 final DomainParsimonyCalculator secondary_features_parsimony,
788 final Phylogeny phylogeny,
789 final String parameters_str,
790 final Map<Species, MappingResults> mapping_results_map ) {
791 final String sep = ForesterUtil.LINE_SEPARATOR + "###################" + ForesterUtil.LINE_SEPARATOR;
792 final String date_time = ForesterUtil.getCurrentDateTime();
793 System.out.println();
794 writeToNexus( outfile_name + surfacing.NEXUS_SECONDARY_FEATURES,
795 secondary_features_parsimony.createMatrixOfSecondaryFeaturePresenceOrAbsence( null ),
797 Phylogeny local_phylogeny_copy = phylogeny.copy();
798 secondary_features_parsimony.executeDolloParsimonyOnSecondaryFeatures( mapping_results_map );
799 SurfacingUtil.writeMatrixToFile( secondary_features_parsimony.getGainLossMatrix(), outfile_name
800 + surfacing.PARSIMONY_OUTPUT_GL_SUFFIX_DOLLO_SECONDARY_FEATURES, Format.FORESTER );
801 SurfacingUtil.writeMatrixToFile( secondary_features_parsimony.getGainLossCountsMatrix(), outfile_name
802 + surfacing.PARSIMONY_OUTPUT_GL_COUNTS_SUFFIX_DOLLO_SECONDARY_FEATURES, Format.FORESTER );
804 .writeBinaryStatesMatrixAsListToFile( secondary_features_parsimony.getGainLossMatrix(),
805 CharacterStateMatrix.GainLossStates.GAIN,
807 + surfacing.PARSIMONY_OUTPUT_DOLLO_GAINS_SECONDARY_FEATURES,
809 ForesterUtil.LINE_SEPARATOR,
812 .writeBinaryStatesMatrixAsListToFile( secondary_features_parsimony.getGainLossMatrix(),
813 CharacterStateMatrix.GainLossStates.LOSS,
815 + surfacing.PARSIMONY_OUTPUT_DOLLO_LOSSES_SECONDARY_FEATURES,
817 ForesterUtil.LINE_SEPARATOR,
820 .writeBinaryStatesMatrixAsListToFile( secondary_features_parsimony.getGainLossMatrix(),
823 + surfacing.PARSIMONY_OUTPUT_DOLLO_PRESENT_SECONDARY_FEATURES,
825 ForesterUtil.LINE_SEPARATOR,
827 preparePhylogeny( local_phylogeny_copy,
828 secondary_features_parsimony,
830 "Dollo parsimony on secondary feature presence/absence",
831 "dollo_on_secondary_features_" + outfile_name,
833 SurfacingUtil.writePhylogenyToFile( local_phylogeny_copy, outfile_name
834 + surfacing.SECONDARY_FEATURES_PARSIMONY_TREE_OUTPUT_SUFFIX_DOLLO );
835 // FITCH DOMAIN COMBINATIONS
836 // -------------------------
837 local_phylogeny_copy = phylogeny.copy();
838 final String randomization = "no";
839 secondary_features_parsimony.executeFitchParsimonyOnBinaryDomainCombintionOnSecondaryFeatures( USE_LAST );
840 preparePhylogeny( local_phylogeny_copy,
841 secondary_features_parsimony,
843 "Fitch parsimony on secondary binary domain combination presence/absence randomization: "
845 "fitch_on_binary_domain_combinations_" + outfile_name,
847 SurfacingUtil.writePhylogenyToFile( local_phylogeny_copy, outfile_name
848 + surfacing.BINARY_DOMAIN_COMBINATIONS_PARSIMONY_TREE_OUTPUT_SUFFIX_FITCH_MAPPED );
849 calculateIndependentDomainCombinationGains( local_phylogeny_copy, outfile_name
850 + surfacing.INDEPENDENT_DC_GAINS_FITCH_PARS_COUNTS_MAPPED_OUTPUT_SUFFIX, outfile_name
851 + surfacing.INDEPENDENT_DC_GAINS_FITCH_PARS_DC_MAPPED_OUTPUT_SUFFIX, outfile_name
852 + surfacing.INDEPENDENT_DC_GAINS_FITCH_PARS_DC_FOR_GO_MAPPING_MAPPED_OUTPUT_SUFFIX, outfile_name
853 + surfacing.INDEPENDENT_DC_GAINS_FITCH_PARS_DC_FOR_GO_MAPPING_MAPPED_OUTPUT_UNIQUE_SUFFIX, outfile_name
854 + "_MAPPED_indep_dc_gains_fitch_lca_ranks.txt", outfile_name
855 + "_MAPPED_indep_dc_gains_fitch_lca_taxonomies.txt", null, null, null, null );
858 public static void extractProteinNames( final List<Protein> proteins,
859 final List<DomainId> query_domain_ids_nc_order,
861 final String separator,
862 final String limit_to_species ) throws IOException {
863 for( final Protein protein : proteins ) {
864 if ( ForesterUtil.isEmpty( limit_to_species )
865 || protein.getSpecies().getSpeciesId().equalsIgnoreCase( limit_to_species ) ) {
866 if ( protein.contains( query_domain_ids_nc_order, true ) ) {
867 out.write( protein.getSpecies().getSpeciesId() );
868 out.write( separator );
869 out.write( protein.getProteinId().getId() );
870 out.write( separator );
872 final Set<DomainId> visited_domain_ids = new HashSet<DomainId>();
873 boolean first = true;
874 for( final Domain domain : protein.getProteinDomains() ) {
875 if ( !visited_domain_ids.contains( domain.getDomainId() ) ) {
876 visited_domain_ids.add( domain.getDomainId() );
883 out.write( domain.getDomainId().getId() );
885 out.write( "" + domain.getTotalCount() );
890 out.write( separator );
891 if ( !( ForesterUtil.isEmpty( protein.getDescription() ) || protein.getDescription()
892 .equals( SurfacingConstants.NONE ) ) ) {
893 out.write( protein.getDescription() );
895 out.write( separator );
896 if ( !( ForesterUtil.isEmpty( protein.getAccession() ) || protein.getAccession()
897 .equals( SurfacingConstants.NONE ) ) ) {
898 out.write( protein.getAccession() );
900 out.write( SurfacingConstants.NL );
907 public static void extractProteinNames( final SortedMap<Species, List<Protein>> protein_lists_per_species,
908 final DomainId domain_id,
910 final String separator,
911 final String limit_to_species,
912 final double domain_e_cutoff ) throws IOException {
913 System.out.println( "Per domain E-value: " + domain_e_cutoff );
914 for( final Species species : protein_lists_per_species.keySet() ) {
915 System.out.println( species + ":" );
916 for( final Protein protein : protein_lists_per_species.get( species ) ) {
917 if ( ForesterUtil.isEmpty( limit_to_species )
918 || protein.getSpecies().getSpeciesId().equalsIgnoreCase( limit_to_species ) ) {
919 final List<Domain> domains = protein.getProteinDomains( domain_id );
920 if ( domains.size() > 0 ) {
921 out.write( protein.getSpecies().getSpeciesId() );
922 out.write( separator );
923 out.write( protein.getProteinId().getId() );
924 out.write( separator );
925 out.write( domain_id.toString() );
926 out.write( separator );
928 for( final Domain domain : domains ) {
929 if ( ( domain_e_cutoff < 0 ) || ( domain.getPerDomainEvalue() <= domain_e_cutoff ) ) {
931 out.write( domain.getFrom() + "-" + domain.getTo() );
932 if ( prev_to >= 0 ) {
933 final int l = domain.getFrom() - prev_to;
934 System.out.println( l );
936 prev_to = domain.getTo();
940 out.write( separator );
941 final List<Domain> domain_list = new ArrayList<Domain>();
942 for( final Domain domain : protein.getProteinDomains() ) {
943 if ( ( domain_e_cutoff < 0 ) || ( domain.getPerDomainEvalue() <= domain_e_cutoff ) ) {
944 domain_list.add( domain );
947 final Domain domain_ary[] = new Domain[ domain_list.size() ];
948 for( int i = 0; i < domain_list.size(); ++i ) {
949 domain_ary[ i ] = domain_list.get( i );
951 Arrays.sort( domain_ary, new DomainComparator( true ) );
953 boolean first = true;
954 for( final Domain domain : domain_ary ) {
961 out.write( domain.getDomainId().toString() );
962 out.write( ":" + domain.getFrom() + "-" + domain.getTo() );
963 out.write( ":" + domain.getPerDomainEvalue() );
966 if ( !( ForesterUtil.isEmpty( protein.getDescription() ) || protein.getDescription()
967 .equals( SurfacingConstants.NONE ) ) ) {
968 out.write( protein.getDescription() );
970 out.write( separator );
971 if ( !( ForesterUtil.isEmpty( protein.getAccession() ) || protein.getAccession()
972 .equals( SurfacingConstants.NONE ) ) ) {
973 out.write( protein.getAccession() );
975 out.write( SurfacingConstants.NL );
983 public static SortedSet<DomainId> getAllDomainIds( final List<GenomeWideCombinableDomains> gwcd_list ) {
984 final SortedSet<DomainId> all_domains_ids = new TreeSet<DomainId>();
985 for( final GenomeWideCombinableDomains gwcd : gwcd_list ) {
986 final Set<DomainId> all_domains = gwcd.getAllDomainIds();
987 // for( final Domain domain : all_domains ) {
988 all_domains_ids.addAll( all_domains );
991 return all_domains_ids;
994 public static SortedMap<String, Integer> getDomainCounts( final List<Protein> protein_domain_collections ) {
995 final SortedMap<String, Integer> map = new TreeMap<String, Integer>();
996 for( final Protein protein_domain_collection : protein_domain_collections ) {
997 for( final Object name : protein_domain_collection.getProteinDomains() ) {
998 final BasicDomain protein_domain = ( BasicDomain ) name;
999 final String id = protein_domain.getDomainId().getId();
1000 if ( map.containsKey( id ) ) {
1001 map.put( id, map.get( id ) + 1 );
1011 public static int getNumberOfNodesLackingName( final Phylogeny p, final StringBuilder names ) {
1012 final PhylogenyNodeIterator it = p.iteratorPostorder();
1014 while ( it.hasNext() ) {
1015 final PhylogenyNode n = it.next();
1016 if ( ForesterUtil.isEmpty( n.getName() )
1017 && ( !n.getNodeData().isHasTaxonomy() || ForesterUtil.isEmpty( n.getNodeData().getTaxonomy()
1018 .getScientificName() ) )
1019 && ( !n.getNodeData().isHasTaxonomy() || ForesterUtil.isEmpty( n.getNodeData().getTaxonomy()
1020 .getCommonName() ) ) ) {
1021 if ( n.getParent() != null ) {
1022 names.append( " " );
1023 names.append( n.getParent().getName() );
1025 final List l = n.getAllExternalDescendants();
1026 for( final Object object : l ) {
1027 System.out.println( l.toString() );
1036 * Returns true is Domain domain falls in an uninterrupted stretch of
1037 * covered positions.
1040 * @param covered_positions
1043 public static boolean isEngulfed( final Domain domain, final List<Boolean> covered_positions ) {
1044 for( int i = domain.getFrom(); i <= domain.getTo(); ++i ) {
1045 if ( ( i >= covered_positions.size() ) || ( covered_positions.get( i ) != true ) ) {
1052 public static void performDomainArchitectureAnalysis( final SortedMap<String, Set<String>> domain_architecutures,
1053 final SortedMap<String, Integer> domain_architecuture_counts,
1054 final int min_count,
1055 final File da_counts_outfile,
1056 final File unique_da_outfile ) {
1057 checkForOutputFileWriteability( da_counts_outfile );
1058 checkForOutputFileWriteability( unique_da_outfile );
1060 final BufferedWriter da_counts_out = new BufferedWriter( new FileWriter( da_counts_outfile ) );
1061 final BufferedWriter unique_da_out = new BufferedWriter( new FileWriter( unique_da_outfile ) );
1062 final Iterator<Entry<String, Integer>> it = domain_architecuture_counts.entrySet().iterator();
1063 while ( it.hasNext() ) {
1064 final Map.Entry<String, Integer> e = it.next();
1065 final String da = e.getKey();
1066 final int count = e.getValue();
1067 if ( count >= min_count ) {
1068 da_counts_out.write( da );
1069 da_counts_out.write( "\t" );
1070 da_counts_out.write( String.valueOf( count ) );
1071 da_counts_out.write( ForesterUtil.LINE_SEPARATOR );
1074 final Iterator<Entry<String, Set<String>>> it2 = domain_architecutures.entrySet().iterator();
1075 while ( it2.hasNext() ) {
1076 final Map.Entry<String, Set<String>> e2 = it2.next();
1077 final String genome = e2.getKey();
1078 final Set<String> das = e2.getValue();
1079 if ( das.contains( da ) ) {
1080 unique_da_out.write( genome );
1081 unique_da_out.write( "\t" );
1082 unique_da_out.write( da );
1083 unique_da_out.write( ForesterUtil.LINE_SEPARATOR );
1088 unique_da_out.close();
1089 da_counts_out.close();
1091 catch ( final IOException e ) {
1092 ForesterUtil.fatalError( surfacing.PRG_NAME, e.getMessage() );
1094 ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote distance matrices to \"" + da_counts_outfile + "\"" );
1095 ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote distance matrices to \"" + unique_da_outfile + "\"" );
1099 public static void preparePhylogeny( final Phylogeny p,
1100 final DomainParsimonyCalculator domain_parsimony,
1101 final String date_time,
1102 final String method,
1104 final String parameters_str ) {
1105 domain_parsimony.decoratePhylogenyWithDomains( p );
1106 final StringBuilder desc = new StringBuilder();
1107 desc.append( "[Method: " + method + "] [Date: " + date_time + "] " );
1108 desc.append( "[Cost: " + domain_parsimony.getCost() + "] " );
1109 desc.append( "[Gains: " + domain_parsimony.getTotalGains() + "] " );
1110 desc.append( "[Losses: " + domain_parsimony.getTotalLosses() + "] " );
1111 desc.append( "[Unchanged: " + domain_parsimony.getTotalUnchanged() + "] " );
1112 desc.append( "[Parameters: " + parameters_str + "]" );
1114 p.setDescription( desc.toString() );
1115 p.setConfidence( new Confidence( domain_parsimony.getCost(), "parsimony" ) );
1116 p.setRerootable( false );
1117 p.setRooted( true );
1121 * species | protein id | n-terminal domain | c-terminal domain | n-terminal domain per domain E-value | c-terminal domain per domain E-value
1125 static public StringBuffer proteinToDomainCombinations( final Protein protein,
1126 final String protein_id,
1127 final String separator ) {
1128 final StringBuffer sb = new StringBuffer();
1129 if ( protein.getSpecies() == null ) {
1130 throw new IllegalArgumentException( "species must not be null" );
1132 if ( ForesterUtil.isEmpty( protein.getSpecies().getSpeciesId() ) ) {
1133 throw new IllegalArgumentException( "species id must not be empty" );
1135 final List<Domain> domains = protein.getProteinDomains();
1136 if ( domains.size() > 1 ) {
1137 final Map<String, Integer> counts = new HashMap<String, Integer>();
1138 for( final Domain domain : domains ) {
1139 final String id = domain.getDomainId().getId();
1140 if ( counts.containsKey( id ) ) {
1141 counts.put( id, counts.get( id ) + 1 );
1144 counts.put( id, 1 );
1147 final Set<String> dcs = new HashSet<String>();
1148 for( int i = 1; i < domains.size(); ++i ) {
1149 for( int j = 0; j < i; ++j ) {
1150 Domain domain_n = domains.get( i );
1151 Domain domain_c = domains.get( j );
1152 if ( domain_n.getFrom() > domain_c.getFrom() ) {
1153 domain_n = domains.get( j );
1154 domain_c = domains.get( i );
1156 final String dc = domain_n.getDomainId().getId() + domain_c.getDomainId().getId();
1157 if ( !dcs.contains( dc ) ) {
1159 sb.append( protein.getSpecies() );
1160 sb.append( separator );
1161 sb.append( protein_id );
1162 sb.append( separator );
1163 sb.append( domain_n.getDomainId().getId() );
1164 sb.append( separator );
1165 sb.append( domain_c.getDomainId().getId() );
1166 sb.append( separator );
1167 sb.append( domain_n.getPerDomainEvalue() );
1168 sb.append( separator );
1169 sb.append( domain_c.getPerDomainEvalue() );
1170 sb.append( separator );
1171 sb.append( counts.get( domain_n.getDomainId().getId() ) );
1172 sb.append( separator );
1173 sb.append( counts.get( domain_c.getDomainId().getId() ) );
1174 sb.append( ForesterUtil.LINE_SEPARATOR );
1179 else if ( domains.size() == 1 ) {
1180 sb.append( protein.getSpecies() );
1181 sb.append( separator );
1182 sb.append( protein_id );
1183 sb.append( separator );
1184 sb.append( domains.get( 0 ).getDomainId().getId() );
1185 sb.append( separator );
1186 sb.append( separator );
1187 sb.append( domains.get( 0 ).getPerDomainEvalue() );
1188 sb.append( separator );
1189 sb.append( separator );
1191 sb.append( separator );
1192 sb.append( ForesterUtil.LINE_SEPARATOR );
1195 sb.append( protein.getSpecies() );
1196 sb.append( separator );
1197 sb.append( protein_id );
1198 sb.append( separator );
1199 sb.append( separator );
1200 sb.append( separator );
1201 sb.append( separator );
1202 sb.append( separator );
1203 sb.append( separator );
1204 sb.append( ForesterUtil.LINE_SEPARATOR );
1211 * Example regarding engulfment: ------------0.1 ----------0.2 --0.3 =>
1212 * domain with 0.3 is ignored
1214 * -----------0.1 ----------0.2 --0.3 => domain with 0.3 is ignored
1217 * ------------0.1 ----------0.3 --0.2 => domains with 0.3 and 0.2 are _not_
1220 * @param max_allowed_overlap
1221 * maximal allowed overlap (inclusive) to be still considered not
1222 * overlapping (zero or negative value to allow any overlap)
1223 * @param remove_engulfed_domains
1224 * to remove domains which are completely engulfed by coverage of
1225 * domains with better support
1229 public static Protein removeOverlappingDomains( final int max_allowed_overlap,
1230 final boolean remove_engulfed_domains,
1231 final Protein protein ) {
1232 final Protein pruned_protein = new BasicProtein( protein.getProteinId().getId(), protein.getSpecies()
1233 .getSpeciesId(), protein.getLength() );
1234 final List<Domain> sorted = SurfacingUtil.sortDomainsWithAscendingConfidenceValues( protein );
1235 final List<Boolean> covered_positions = new ArrayList<Boolean>();
1236 for( final Domain domain : sorted ) {
1237 if ( ( ( max_allowed_overlap < 0 ) || ( SurfacingUtil.calculateOverlap( domain, covered_positions ) <= max_allowed_overlap ) )
1238 && ( !remove_engulfed_domains || !isEngulfed( domain, covered_positions ) ) ) {
1239 final int covered_positions_size = covered_positions.size();
1240 for( int i = covered_positions_size; i < domain.getFrom(); ++i ) {
1241 covered_positions.add( false );
1243 final int new_covered_positions_size = covered_positions.size();
1244 for( int i = domain.getFrom(); i <= domain.getTo(); ++i ) {
1245 if ( i < new_covered_positions_size ) {
1246 covered_positions.set( i, true );
1249 covered_positions.add( true );
1252 pruned_protein.addProteinDomain( domain );
1255 return pruned_protein;
1258 public static List<Domain> sortDomainsWithAscendingConfidenceValues( final Protein protein ) {
1259 final List<Domain> domains = new ArrayList<Domain>();
1260 for( final Domain d : protein.getProteinDomains() ) {
1263 Collections.sort( domains, SurfacingUtil.ASCENDING_CONFIDENCE_VALUE_ORDER );
1267 public static int storeDomainArchitectures( final String genome,
1268 final SortedMap<String, Set<String>> domain_architecutures,
1269 final List<Protein> protein_list,
1270 final Map<String, Integer> distinct_domain_architecuture_counts ) {
1271 final Set<String> da = new HashSet<String>();
1272 domain_architecutures.put( genome, da );
1273 for( final Protein protein : protein_list ) {
1274 final String da_str = ( ( BasicProtein ) protein ).toDomainArchitectureString( "~", 3, "=" );
1275 if ( !da.contains( da_str ) ) {
1276 if ( !distinct_domain_architecuture_counts.containsKey( da_str ) ) {
1277 distinct_domain_architecuture_counts.put( da_str, 1 );
1280 distinct_domain_architecuture_counts.put( da_str,
1281 distinct_domain_architecuture_counts.get( da_str ) + 1 );
1289 public static void writeAllDomainsChangedOnAllSubtrees( final Phylogeny p,
1290 final boolean get_gains,
1291 final String outdir,
1292 final String suffix_for_filename ) throws IOException {
1293 CharacterStateMatrix.GainLossStates state = CharacterStateMatrix.GainLossStates.GAIN;
1295 state = CharacterStateMatrix.GainLossStates.LOSS;
1297 final File base_dir = createBaseDirForPerNodeDomainFiles( surfacing.BASE_DIRECTORY_PER_SUBTREE_DOMAIN_GAIN_LOSS_FILES,
1301 for( final PhylogenyNodeIterator it = p.iteratorPostorder(); it.hasNext(); ) {
1302 final PhylogenyNode node = it.next();
1303 if ( !node.isExternal() ) {
1304 final SortedSet<String> domains = collectAllDomainsChangedOnSubtree( node, get_gains );
1305 if ( domains.size() > 0 ) {
1306 final Writer writer = ForesterUtil.createBufferedWriter( base_dir + ForesterUtil.FILE_SEPARATOR
1307 + node.getName() + suffix_for_filename );
1308 for( final String domain : domains ) {
1309 writer.write( domain );
1310 writer.write( ForesterUtil.LINE_SEPARATOR );
1318 public static void writeBinaryDomainCombinationsFileForGraphAnalysis( final String[][] input_file_properties,
1319 final File output_dir,
1320 final GenomeWideCombinableDomains gwcd,
1322 final GenomeWideCombinableDomainsSortOrder dc_sort_order ) {
1323 File dc_outfile_dot = new File( input_file_properties[ i ][ 1 ]
1324 + surfacing.DOMAIN_COMBINITONS_OUTPUTFILE_SUFFIX_FOR_GRAPH_ANALYSIS );
1325 if ( output_dir != null ) {
1326 dc_outfile_dot = new File( output_dir + ForesterUtil.FILE_SEPARATOR + dc_outfile_dot );
1328 checkForOutputFileWriteability( dc_outfile_dot );
1329 final SortedSet<BinaryDomainCombination> binary_combinations = createSetOfAllBinaryDomainCombinationsPerGenome( gwcd );
1331 final BufferedWriter out_dot = new BufferedWriter( new FileWriter( dc_outfile_dot ) );
1332 for( final BinaryDomainCombination bdc : binary_combinations ) {
1333 out_dot.write( bdc.toGraphDescribingLanguage( BinaryDomainCombination.OutputFormat.DOT, null, null )
1335 out_dot.write( SurfacingConstants.NL );
1339 catch ( final IOException e ) {
1340 ForesterUtil.fatalError( surfacing.PRG_NAME, e.getMessage() );
1342 ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote binary domain combination for \""
1343 + input_file_properties[ i ][ 0 ] + "\" (" + input_file_properties[ i ][ 1 ] + ", "
1344 + input_file_properties[ i ][ 2 ] + ") to: \"" + dc_outfile_dot + "\"" );
1347 public static void writeBinaryStatesMatrixAsListToFile( final CharacterStateMatrix<CharacterStateMatrix.GainLossStates> matrix,
1348 final CharacterStateMatrix.GainLossStates state,
1349 final String filename,
1350 final String indentifier_characters_separator,
1351 final String character_separator,
1352 final Map<String, String> descriptions ) {
1353 final File outfile = new File( filename );
1354 checkForOutputFileWriteability( outfile );
1355 final SortedSet<String> sorted_ids = new TreeSet<String>();
1356 for( int i = 0; i < matrix.getNumberOfIdentifiers(); ++i ) {
1357 sorted_ids.add( matrix.getIdentifier( i ) );
1360 final BufferedWriter out = new BufferedWriter( new FileWriter( outfile ) );
1361 for( final String id : sorted_ids ) {
1362 out.write( indentifier_characters_separator );
1363 out.write( "#" + id );
1364 out.write( indentifier_characters_separator );
1365 for( int c = 0; c < matrix.getNumberOfCharacters(); ++c ) {
1367 // using null to indicate either UNCHANGED_PRESENT or GAIN.
1368 if ( ( matrix.getState( id, c ) == state )
1369 || ( ( state == null ) && ( ( matrix.getState( id, c ) == CharacterStateMatrix.GainLossStates.GAIN ) || ( matrix
1370 .getState( id, c ) == CharacterStateMatrix.GainLossStates.UNCHANGED_PRESENT ) ) ) ) {
1371 out.write( matrix.getCharacter( c ) );
1372 if ( ( descriptions != null ) && !descriptions.isEmpty()
1373 && descriptions.containsKey( matrix.getCharacter( c ) ) ) {
1375 out.write( descriptions.get( matrix.getCharacter( c ) ) );
1377 out.write( character_separator );
1384 catch ( final IOException e ) {
1385 ForesterUtil.fatalError( surfacing.PRG_NAME, e.getMessage() );
1387 ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote characters list: \"" + filename + "\"" );
1390 public static void writeBinaryStatesMatrixAsListToFileForBinaryCombinationsForGraphAnalysis( final CharacterStateMatrix<CharacterStateMatrix.GainLossStates> matrix,
1391 final CharacterStateMatrix.GainLossStates state,
1392 final String filename,
1393 final String indentifier_characters_separator,
1394 final String character_separator,
1395 final BinaryDomainCombination.OutputFormat bc_output_format ) {
1396 final File outfile = new File( filename );
1397 checkForOutputFileWriteability( outfile );
1398 final SortedSet<String> sorted_ids = new TreeSet<String>();
1399 for( int i = 0; i < matrix.getNumberOfIdentifiers(); ++i ) {
1400 sorted_ids.add( matrix.getIdentifier( i ) );
1403 final BufferedWriter out = new BufferedWriter( new FileWriter( outfile ) );
1404 for( final String id : sorted_ids ) {
1405 out.write( indentifier_characters_separator );
1406 out.write( "#" + id );
1407 out.write( indentifier_characters_separator );
1408 for( int c = 0; c < matrix.getNumberOfCharacters(); ++c ) {
1410 // using null to indicate either UNCHANGED_PRESENT or GAIN.
1411 if ( ( matrix.getState( id, c ) == state )
1412 || ( ( state == null ) && ( ( matrix.getState( id, c ) == CharacterStateMatrix.GainLossStates.GAIN ) || ( matrix
1413 .getState( id, c ) == CharacterStateMatrix.GainLossStates.UNCHANGED_PRESENT ) ) ) ) {
1414 BinaryDomainCombination bdc = null;
1416 bdc = BasicBinaryDomainCombination.createInstance( matrix.getCharacter( c ) );
1418 catch ( final Exception e ) {
1419 ForesterUtil.fatalError( surfacing.PRG_NAME, e.getLocalizedMessage() );
1421 out.write( bdc.toGraphDescribingLanguage( bc_output_format, null, null ).toString() );
1422 out.write( character_separator );
1429 catch ( final IOException e ) {
1430 ForesterUtil.fatalError( surfacing.PRG_NAME, e.getMessage() );
1432 ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote characters list: \"" + filename + "\"" );
1435 public static void writeBinaryStatesMatrixToList( final Map<DomainId, List<GoId>> domain_id_to_go_ids_map,
1436 final Map<GoId, GoTerm> go_id_to_term_map,
1437 final GoNameSpace go_namespace_limit,
1438 final boolean domain_combinations,
1439 final CharacterStateMatrix<CharacterStateMatrix.GainLossStates> matrix,
1440 final CharacterStateMatrix.GainLossStates state,
1441 final String filename,
1442 final String indentifier_characters_separator,
1443 final String character_separator,
1444 final String title_for_html,
1445 final String prefix_for_html,
1446 final Map<DomainId, Set<String>>[] domain_id_to_secondary_features_maps,
1447 final SortedSet<String> all_pfams_encountered,
1448 final SortedSet<String> pfams_gained_or_lost,
1449 final String suffix_for_per_node_events_file,
1450 final Map<String, Integer> tax_code_to_id_map ) {
1451 if ( ( go_namespace_limit != null ) && ( ( go_id_to_term_map == null ) || ( go_id_to_term_map.size() < 1 ) ) ) {
1452 throw new IllegalArgumentException( "attempt to use GO namespace limit without a GO-id to term map" );
1454 else if ( ( ( domain_id_to_go_ids_map == null ) || ( domain_id_to_go_ids_map.size() < 1 ) ) ) {
1455 throw new IllegalArgumentException( "attempt to output detailed HTML without a Pfam to GO map" );
1457 else if ( ( ( go_id_to_term_map == null ) || ( go_id_to_term_map.size() < 1 ) ) ) {
1458 throw new IllegalArgumentException( "attempt to output detailed HTML without a GO-id to term map" );
1460 final File outfile = new File( filename );
1461 checkForOutputFileWriteability( outfile );
1462 final SortedSet<String> sorted_ids = new TreeSet<String>();
1463 for( int i = 0; i < matrix.getNumberOfIdentifiers(); ++i ) {
1464 sorted_ids.add( matrix.getIdentifier( i ) );
1467 final Writer out = new BufferedWriter( new FileWriter( outfile ) );
1468 final File per_node_go_mapped_domain_gain_loss_files_base_dir = createBaseDirForPerNodeDomainFiles( surfacing.BASE_DIRECTORY_PER_NODE_DOMAIN_GAIN_LOSS_FILES,
1469 domain_combinations,
1472 Writer per_node_go_mapped_domain_gain_loss_outfile_writer = null;
1473 File per_node_go_mapped_domain_gain_loss_outfile = null;
1474 int per_node_counter = 0;
1475 out.write( "<html>" );
1476 out.write( SurfacingConstants.NL );
1477 addHtmlHead( out, title_for_html );
1478 out.write( SurfacingConstants.NL );
1479 out.write( "<body>" );
1480 out.write( SurfacingConstants.NL );
1481 out.write( "<h1>" );
1482 out.write( SurfacingConstants.NL );
1483 out.write( title_for_html );
1484 out.write( SurfacingConstants.NL );
1485 out.write( "</h1>" );
1486 out.write( SurfacingConstants.NL );
1487 out.write( "<table>" );
1488 out.write( SurfacingConstants.NL );
1489 for( final String id : sorted_ids ) {
1490 final Matcher matcher = PATTERN_SP_STYLE_TAXONOMY.matcher( id );
1491 if ( matcher.matches() ) {
1494 out.write( "<tr>" );
1495 out.write( "<td>" );
1496 out.write( "<a href=\"#" + id + "\">" + id + "</a>" );
1497 out.write( "</td>" );
1498 out.write( "</tr>" );
1499 out.write( SurfacingConstants.NL );
1501 out.write( "</table>" );
1502 out.write( SurfacingConstants.NL );
1503 for( final String id : sorted_ids ) {
1504 final Matcher matcher = PATTERN_SP_STYLE_TAXONOMY.matcher( id );
1505 if ( matcher.matches() ) {
1508 out.write( SurfacingConstants.NL );
1509 out.write( "<h2>" );
1510 out.write( "<a name=\"" + id + "\">" + id + "</a>" );
1511 writeTaxonomyLinks( out, id, tax_code_to_id_map );
1512 out.write( "</h2>" );
1513 out.write( SurfacingConstants.NL );
1514 out.write( "<table>" );
1515 out.write( SurfacingConstants.NL );
1516 out.write( "<tr>" );
1517 out.write( "<td><b>" );
1518 out.write( "Pfam domain(s)" );
1519 out.write( "</b></td><td><b>" );
1520 out.write( "GO term acc" );
1521 out.write( "</b></td><td><b>" );
1522 out.write( "GO term" );
1523 out.write( "</b></td><td><b>" );
1524 out.write( "GO namespace" );
1525 out.write( "</b></td>" );
1526 out.write( "</tr>" );
1527 out.write( SurfacingConstants.NL );
1528 out.write( "</tr>" );
1529 out.write( SurfacingConstants.NL );
1530 per_node_counter = 0;
1531 if ( matrix.getNumberOfCharacters() > 0 ) {
1532 per_node_go_mapped_domain_gain_loss_outfile = new File( per_node_go_mapped_domain_gain_loss_files_base_dir
1533 + ForesterUtil.FILE_SEPARATOR + id + suffix_for_per_node_events_file );
1534 SurfacingUtil.checkForOutputFileWriteability( per_node_go_mapped_domain_gain_loss_outfile );
1535 per_node_go_mapped_domain_gain_loss_outfile_writer = ForesterUtil
1536 .createBufferedWriter( per_node_go_mapped_domain_gain_loss_outfile );
1539 per_node_go_mapped_domain_gain_loss_outfile = null;
1540 per_node_go_mapped_domain_gain_loss_outfile_writer = null;
1542 for( int c = 0; c < matrix.getNumberOfCharacters(); ++c ) {
1544 // using null to indicate either UNCHANGED_PRESENT or GAIN.
1545 if ( ( matrix.getState( id, c ) == state )
1546 || ( ( state == null ) && ( ( matrix.getState( id, c ) == CharacterStateMatrix.GainLossStates.UNCHANGED_PRESENT ) || ( matrix
1547 .getState( id, c ) == CharacterStateMatrix.GainLossStates.GAIN ) ) ) ) {
1548 final String character = matrix.getCharacter( c );
1549 String domain_0 = "";
1550 String domain_1 = "";
1551 if ( character.indexOf( BinaryDomainCombination.SEPARATOR ) > 0 ) {
1552 final String[] s = character.split( BinaryDomainCombination.SEPARATOR );
1553 if ( s.length != 2 ) {
1554 throw new AssertionError( "this should not have happened: unexpected format for domain combination: ["
1555 + character + "]" );
1561 domain_0 = character;
1563 writeDomainData( domain_id_to_go_ids_map,
1570 character_separator,
1571 domain_id_to_secondary_features_maps,
1573 all_pfams_encountered.add( domain_0 );
1574 if ( pfams_gained_or_lost != null ) {
1575 pfams_gained_or_lost.add( domain_0 );
1577 if ( !ForesterUtil.isEmpty( domain_1 ) ) {
1578 all_pfams_encountered.add( domain_1 );
1579 if ( pfams_gained_or_lost != null ) {
1580 pfams_gained_or_lost.add( domain_1 );
1583 if ( per_node_go_mapped_domain_gain_loss_outfile_writer != null ) {
1584 writeDomainsToIndividualFilePerTreeNode( per_node_go_mapped_domain_gain_loss_outfile_writer,
1591 if ( per_node_go_mapped_domain_gain_loss_outfile_writer != null ) {
1592 per_node_go_mapped_domain_gain_loss_outfile_writer.close();
1593 if ( per_node_counter < 1 ) {
1594 per_node_go_mapped_domain_gain_loss_outfile.delete();
1596 per_node_counter = 0;
1598 out.write( "</table>" );
1599 out.write( SurfacingConstants.NL );
1600 out.write( "<hr>" );
1601 out.write( SurfacingConstants.NL );
1602 } // for( final String id : sorted_ids ) {
1603 out.write( "</body>" );
1604 out.write( SurfacingConstants.NL );
1605 out.write( "</html>" );
1606 out.write( SurfacingConstants.NL );
1610 catch ( final IOException e ) {
1611 ForesterUtil.fatalError( surfacing.PRG_NAME, e.getMessage() );
1613 ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote characters detailed HTML list: \"" + filename + "\"" );
1616 public static void writeDomainCombinationsCountsFile( final String[][] input_file_properties,
1617 final File output_dir,
1618 final Writer per_genome_domain_promiscuity_statistics_writer,
1619 final GenomeWideCombinableDomains gwcd,
1621 final GenomeWideCombinableDomains.GenomeWideCombinableDomainsSortOrder dc_sort_order ) {
1622 File dc_outfile = new File( input_file_properties[ i ][ 1 ]
1623 + surfacing.DOMAIN_COMBINITON_COUNTS_OUTPUTFILE_SUFFIX );
1624 if ( output_dir != null ) {
1625 dc_outfile = new File( output_dir + ForesterUtil.FILE_SEPARATOR + dc_outfile );
1627 checkForOutputFileWriteability( dc_outfile );
1629 final BufferedWriter out = new BufferedWriter( new FileWriter( dc_outfile ) );
1630 out.write( gwcd.toStringBuilder( dc_sort_order ).toString() );
1633 catch ( final IOException e ) {
1634 ForesterUtil.fatalError( surfacing.PRG_NAME, e.getMessage() );
1636 final DescriptiveStatistics stats = gwcd.getPerGenomeDomainPromiscuityStatistics();
1638 per_genome_domain_promiscuity_statistics_writer.write( input_file_properties[ i ][ 1 ] + "\t" );
1639 per_genome_domain_promiscuity_statistics_writer.write( FORMATTER_3.format( stats.arithmeticMean() ) + "\t" );
1640 if ( stats.getN() < 2 ) {
1641 per_genome_domain_promiscuity_statistics_writer.write( "n/a" + "\t" );
1644 per_genome_domain_promiscuity_statistics_writer.write( FORMATTER_3.format( stats
1645 .sampleStandardDeviation() ) + "\t" );
1647 per_genome_domain_promiscuity_statistics_writer.write( FORMATTER_3.format( stats.median() ) + "\t" );
1648 per_genome_domain_promiscuity_statistics_writer.write( ( int ) stats.getMin() + "\t" );
1649 per_genome_domain_promiscuity_statistics_writer.write( ( int ) stats.getMax() + "\t" );
1650 per_genome_domain_promiscuity_statistics_writer.write( stats.getN() + "\t" );
1651 final SortedSet<DomainId> mpds = gwcd.getMostPromiscuosDomain();
1652 for( final DomainId mpd : mpds ) {
1653 per_genome_domain_promiscuity_statistics_writer.write( mpd.getId() + " " );
1655 per_genome_domain_promiscuity_statistics_writer.write( ForesterUtil.LINE_SEPARATOR );
1657 catch ( final IOException e ) {
1658 ForesterUtil.fatalError( surfacing.PRG_NAME, e.getMessage() );
1660 if ( input_file_properties[ i ].length == 3 ) {
1661 ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote domain combination counts for \""
1662 + input_file_properties[ i ][ 0 ] + "\" (" + input_file_properties[ i ][ 1 ] + ", "
1663 + input_file_properties[ i ][ 2 ] + ") to: \"" + dc_outfile + "\"" );
1666 ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote domain combination counts for \""
1667 + input_file_properties[ i ][ 0 ] + "\" (" + input_file_properties[ i ][ 1 ] + ") to: \""
1668 + dc_outfile + "\"" );
1672 public static DescriptiveStatistics writeDomainSimilaritiesToFile( final StringBuilder html_desc,
1673 final StringBuilder html_title,
1674 final Writer single_writer,
1675 Map<Character, Writer> split_writers,
1676 final SortedSet<DomainSimilarity> similarities,
1677 final boolean treat_as_binary,
1678 final List<Species> species_order,
1679 final PrintableDomainSimilarity.PRINT_OPTION print_option,
1680 final DomainSimilarity.DomainSimilaritySortField sort_field,
1681 final DomainSimilarity.DomainSimilarityScoring scoring,
1682 final boolean verbose,
1683 final Map<String, Integer> tax_code_to_id_map )
1684 throws IOException {
1685 final DescriptiveStatistics stats = new BasicDescriptiveStatistics();
1686 String histogram_title = null;
1687 switch ( sort_field ) {
1688 case ABS_MAX_COUNTS_DIFFERENCE:
1689 if ( treat_as_binary ) {
1690 histogram_title = "absolute counts difference:";
1693 histogram_title = "absolute (maximal) counts difference:";
1696 case MAX_COUNTS_DIFFERENCE:
1697 if ( treat_as_binary ) {
1698 histogram_title = "counts difference:";
1701 histogram_title = "(maximal) counts difference:";
1705 histogram_title = "score mean:";
1708 histogram_title = "score minimum:";
1711 histogram_title = "score maximum:";
1713 case MAX_DIFFERENCE:
1714 if ( treat_as_binary ) {
1715 histogram_title = "difference:";
1718 histogram_title = "(maximal) difference:";
1722 histogram_title = "score mean:";
1725 histogram_title = "score standard deviation:";
1728 histogram_title = "species number:";
1731 throw new AssertionError( "Unknown sort field: " + sort_field );
1733 for( final DomainSimilarity similarity : similarities ) {
1734 switch ( sort_field ) {
1735 case ABS_MAX_COUNTS_DIFFERENCE:
1736 stats.addValue( Math.abs( similarity.getMaximalDifferenceInCounts() ) );
1738 case MAX_COUNTS_DIFFERENCE:
1739 stats.addValue( similarity.getMaximalDifferenceInCounts() );
1742 stats.addValue( similarity.getMeanSimilarityScore() );
1745 stats.addValue( similarity.getMinimalSimilarityScore() );
1748 stats.addValue( similarity.getMaximalSimilarityScore() );
1750 case MAX_DIFFERENCE:
1751 stats.addValue( similarity.getMaximalDifference() );
1754 stats.addValue( similarity.getMeanSimilarityScore() );
1757 stats.addValue( similarity.getStandardDeviationOfSimilarityScore() );
1760 stats.addValue( similarity.getSpecies().size() );
1763 throw new AssertionError( "Unknown sort field: " + sort_field );
1766 AsciiHistogram histo = null;
1767 if ( stats.getMin() < stats.getMin() ) {
1768 histo = new AsciiHistogram( stats, histogram_title );
1771 if ( histo != null ) {
1772 System.out.println( histo.toStringBuffer( 20, '|', 40, 5 ) );
1774 System.out.println();
1775 System.out.println( "N : " + stats.getN() );
1776 System.out.println( "Min : " + stats.getMin() );
1777 System.out.println( "Max : " + stats.getMax() );
1778 System.out.println( "Mean : " + stats.arithmeticMean() );
1779 if ( stats.getN() > 1 ) {
1780 System.out.println( "SD : " + stats.sampleStandardDeviation() );
1783 System.out.println( "SD : n/a" );
1785 System.out.println( "Median : " + stats.median() );
1786 if ( stats.getN() > 1 ) {
1787 System.out.println( "Pearsonian skewness : " + stats.pearsonianSkewness() );
1790 System.out.println( "Pearsonian skewness : n/a" );
1793 if ( ( single_writer != null ) && ( ( split_writers == null ) || split_writers.isEmpty() ) ) {
1794 split_writers = new HashMap<Character, Writer>();
1795 split_writers.put( '_', single_writer );
1797 switch ( print_option ) {
1798 case SIMPLE_TAB_DELIMITED:
1801 for( final Character key : split_writers.keySet() ) {
1802 final Writer w = split_writers.get( key );
1803 w.write( "<html>" );
1804 w.write( SurfacingConstants.NL );
1806 addHtmlHead( w, "DCs (" + html_title + ") " + key.toString().toUpperCase() );
1809 addHtmlHead( w, "DCs (" + html_title + ")" );
1811 w.write( SurfacingConstants.NL );
1812 w.write( "<body>" );
1813 w.write( SurfacingConstants.NL );
1814 w.write( html_desc.toString() );
1815 w.write( SurfacingConstants.NL );
1818 w.write( SurfacingConstants.NL );
1819 w.write( "<tt><pre>" );
1820 w.write( SurfacingConstants.NL );
1821 if ( histo != null ) {
1822 w.write( histo.toStringBuffer( 20, '|', 40, 5 ).toString() );
1823 w.write( SurfacingConstants.NL );
1825 w.write( "</pre></tt>" );
1826 w.write( SurfacingConstants.NL );
1827 w.write( "<table>" );
1828 w.write( SurfacingConstants.NL );
1829 w.write( "<tr><td>N: </td><td>" + stats.getN() + "</td></tr>" );
1830 w.write( SurfacingConstants.NL );
1831 w.write( "<tr><td>Min: </td><td>" + stats.getMin() + "</td></tr>" );
1832 w.write( SurfacingConstants.NL );
1833 w.write( "<tr><td>Max: </td><td>" + stats.getMax() + "</td></tr>" );
1834 w.write( SurfacingConstants.NL );
1835 w.write( "<tr><td>Mean: </td><td>" + stats.arithmeticMean() + "</td></tr>" );
1836 w.write( SurfacingConstants.NL );
1837 if ( stats.getN() > 1 ) {
1838 w.write( "<tr><td>SD: </td><td>" + stats.sampleStandardDeviation() + "</td></tr>" );
1841 w.write( "<tr><td>SD: </td><td>n/a</td></tr>" );
1843 w.write( SurfacingConstants.NL );
1844 w.write( "<tr><td>Median: </td><td>" + stats.median() + "</td></tr>" );
1845 w.write( SurfacingConstants.NL );
1846 if ( stats.getN() > 1 ) {
1847 w.write( "<tr><td>Pearsonian skewness: </td><td>" + stats.pearsonianSkewness() + "</td></tr>" );
1850 w.write( "<tr><td>Pearsonian skewness: </td><td>n/a</td></tr>" );
1852 w.write( SurfacingConstants.NL );
1853 w.write( "</table>" );
1854 w.write( SurfacingConstants.NL );
1856 w.write( SurfacingConstants.NL );
1858 w.write( SurfacingConstants.NL );
1860 w.write( SurfacingConstants.NL );
1861 w.write( "<table>" );
1862 w.write( SurfacingConstants.NL );
1866 for( final Writer w : split_writers.values() ) {
1867 w.write( SurfacingConstants.NL );
1869 for( final DomainSimilarity similarity : similarities ) {
1870 if ( ( species_order != null ) && !species_order.isEmpty() ) {
1871 ( ( PrintableDomainSimilarity ) similarity ).setSpeciesOrder( species_order );
1873 if ( single_writer != null ) {
1874 single_writer.write( similarity.toStringBuffer( print_option, tax_code_to_id_map ).toString() );
1877 Writer local_writer = split_writers.get( ( similarity.getDomainId().getId().charAt( 0 ) + "" )
1878 .toLowerCase().charAt( 0 ) );
1879 if ( local_writer == null ) {
1880 local_writer = split_writers.get( '0' );
1882 local_writer.write( similarity.toStringBuffer( print_option, tax_code_to_id_map ).toString() );
1884 for( final Writer w : split_writers.values() ) {
1885 w.write( SurfacingConstants.NL );
1888 switch ( print_option ) {
1890 for( final Writer w : split_writers.values() ) {
1891 w.write( SurfacingConstants.NL );
1892 w.write( "</table>" );
1893 w.write( SurfacingConstants.NL );
1894 w.write( "</font>" );
1895 w.write( SurfacingConstants.NL );
1896 w.write( "</body>" );
1897 w.write( SurfacingConstants.NL );
1898 w.write( "</html>" );
1899 w.write( SurfacingConstants.NL );
1903 for( final Writer w : split_writers.values() ) {
1909 public static void writeMatrixToFile( final CharacterStateMatrix<?> matrix,
1910 final String filename,
1911 final Format format ) {
1912 final File outfile = new File( filename );
1913 checkForOutputFileWriteability( outfile );
1915 final BufferedWriter out = new BufferedWriter( new FileWriter( outfile ) );
1916 matrix.toWriter( out, format );
1920 catch ( final IOException e ) {
1921 ForesterUtil.fatalError( surfacing.PRG_NAME, e.getMessage() );
1923 ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote matrix: \"" + filename + "\"" );
1926 public static void writeMatrixToFile( final File matrix_outfile, final List<DistanceMatrix> matrices ) {
1927 checkForOutputFileWriteability( matrix_outfile );
1929 final BufferedWriter out = new BufferedWriter( new FileWriter( matrix_outfile ) );
1930 for( final DistanceMatrix distance_matrix : matrices ) {
1931 out.write( distance_matrix.toStringBuffer( DistanceMatrix.Format.PHYLIP ).toString() );
1932 out.write( ForesterUtil.LINE_SEPARATOR );
1937 catch ( final IOException e ) {
1938 ForesterUtil.fatalError( surfacing.PRG_NAME, e.getMessage() );
1940 ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote distance matrices to \"" + matrix_outfile + "\"" );
1943 public static void writePhylogenyToFile( final Phylogeny phylogeny, final String filename ) {
1944 final PhylogenyWriter writer = new PhylogenyWriter();
1946 writer.toPhyloXML( new File( filename ), phylogeny, 1 );
1948 catch ( final IOException e ) {
1949 ForesterUtil.printWarningMessage( surfacing.PRG_NAME, "failed to write phylogeny to \"" + filename + "\": "
1952 ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote phylogeny to \"" + filename + "\"" );
1955 public static void writeTaxonomyLinks( final Writer writer,
1956 final String species,
1957 final Map<String, Integer> tax_code_to_id_map ) throws IOException {
1958 if ( ( species.length() > 1 ) && ( species.indexOf( '_' ) < 1 ) ) {
1959 writer.write( " [" );
1960 if ( ( tax_code_to_id_map != null ) && tax_code_to_id_map.containsKey( species ) ) {
1961 writer.write( "<a href=\"" + SurfacingConstants.UNIPROT_TAXONOMY_ID_LINK
1962 + tax_code_to_id_map.get( species ) + "\" target=\"taxonomy_window\">uniprot</a>" );
1965 writer.write( "<a href=\"" + SurfacingConstants.EOL_LINK + species
1966 + "\" target=\"taxonomy_window\">eol</a>" );
1967 writer.write( "|" );
1968 writer.write( "<a href=\"" + SurfacingConstants.GOOGLE_SCHOLAR_SEARCH + species
1969 + "\" target=\"taxonomy_window\">scholar</a>" );
1970 writer.write( "|" );
1971 writer.write( "<a href=\"" + SurfacingConstants.GOOGLE_WEB_SEARCH_LINK + species
1972 + "\" target=\"taxonomy_window\">google</a>" );
1974 writer.write( "]" );
1978 private final static void addToCountMap( final Map<String, Integer> map, final String s ) {
1979 if ( map.containsKey( s ) ) {
1980 map.put( s, map.get( s ) + 1 );
1987 private static void calculateIndependentDomainCombinationGains( final Phylogeny local_phylogeny_l,
1988 final String outfilename_for_counts,
1989 final String outfilename_for_dc,
1990 final String outfilename_for_dc_for_go_mapping,
1991 final String outfilename_for_dc_for_go_mapping_unique,
1992 final String outfilename_for_rank_counts,
1993 final String outfilename_for_ancestor_species_counts,
1994 final String outfilename_for_protein_stats,
1995 final Map<String, DescriptiveStatistics> protein_length_stats_by_dc,
1996 final Map<String, DescriptiveStatistics> domain_number_stats_by_dc,
1997 final Map<String, DescriptiveStatistics> domain_length_stats_by_domain ) {
2000 // if ( protein_length_stats_by_dc != null ) {
2001 // for( final Entry<?, DescriptiveStatistics> entry : protein_length_stats_by_dc.entrySet() ) {
2002 // System.out.print( entry.getKey().toString() );
2003 // System.out.print( ": " );
2004 // double[] a = entry.getValue().getDataAsDoubleArray();
2005 // for( int i = 0; i < a.length; i++ ) {
2006 // System.out.print( a[ i ] + " " );
2008 // System.out.println();
2011 // if ( domain_number_stats_by_dc != null ) {
2012 // for( final Entry<?, DescriptiveStatistics> entry : domain_number_stats_by_dc.entrySet() ) {
2013 // System.out.print( entry.getKey().toString() );
2014 // System.out.print( ": " );
2015 // double[] a = entry.getValue().getDataAsDoubleArray();
2016 // for( int i = 0; i < a.length; i++ ) {
2017 // System.out.print( a[ i ] + " " );
2019 // System.out.println();
2023 final BufferedWriter out_counts = new BufferedWriter( new FileWriter( outfilename_for_counts ) );
2024 final BufferedWriter out_dc = new BufferedWriter( new FileWriter( outfilename_for_dc ) );
2025 final BufferedWriter out_dc_for_go_mapping = new BufferedWriter( new FileWriter( outfilename_for_dc_for_go_mapping ) );
2026 final BufferedWriter out_dc_for_go_mapping_unique = new BufferedWriter( new FileWriter( outfilename_for_dc_for_go_mapping_unique ) );
2027 final SortedMap<String, Integer> dc_gain_counts = new TreeMap<String, Integer>();
2028 for( final PhylogenyNodeIterator it = local_phylogeny_l.iteratorPostorder(); it.hasNext(); ) {
2029 final PhylogenyNode n = it.next();
2030 final Set<String> gained_dc = n.getNodeData().getBinaryCharacters().getGainedCharacters();
2031 for( final String dc : gained_dc ) {
2032 if ( dc_gain_counts.containsKey( dc ) ) {
2033 dc_gain_counts.put( dc, dc_gain_counts.get( dc ) + 1 );
2036 dc_gain_counts.put( dc, 1 );
2040 final SortedMap<Integer, Integer> histogram = new TreeMap<Integer, Integer>();
2041 final SortedMap<Integer, StringBuilder> domain_lists = new TreeMap<Integer, StringBuilder>();
2042 final SortedMap<Integer, DescriptiveStatistics> dc_reapp_counts_to_protein_length_stats = new TreeMap<Integer, DescriptiveStatistics>();
2043 final SortedMap<Integer, DescriptiveStatistics> dc_reapp_counts_to_domain_number_stats = new TreeMap<Integer, DescriptiveStatistics>();
2044 final SortedMap<Integer, DescriptiveStatistics> dc_reapp_counts_to_domain_lengths_stats = new TreeMap<Integer, DescriptiveStatistics>();
2045 final SortedMap<Integer, PriorityQueue<String>> domain_lists_go = new TreeMap<Integer, PriorityQueue<String>>();
2046 final SortedMap<Integer, SortedSet<String>> domain_lists_go_unique = new TreeMap<Integer, SortedSet<String>>();
2047 final Set<String> dcs = dc_gain_counts.keySet();
2048 final SortedSet<String> more_than_once = new TreeSet<String>();
2049 final DescriptiveStatistics gained_once_lengths_stats = new BasicDescriptiveStatistics();
2050 final DescriptiveStatistics gained_once_domain_count_stats = new BasicDescriptiveStatistics();
2051 final DescriptiveStatistics gained_multiple_times_lengths_stats = new BasicDescriptiveStatistics();
2052 final DescriptiveStatistics gained_multiple_times_domain_count_stats = new BasicDescriptiveStatistics();
2053 long gained_multiple_times_domain_length_sum = 0;
2054 long gained_once_domain_length_sum = 0;
2055 long gained_multiple_times_domain_length_count = 0;
2056 long gained_once_domain_length_count = 0;
2057 for( final String dc : dcs ) {
2058 final int count = dc_gain_counts.get( dc );
2059 if ( histogram.containsKey( count ) ) {
2060 histogram.put( count, histogram.get( count ) + 1 );
2061 domain_lists.get( count ).append( ", " + dc );
2062 domain_lists_go.get( count ).addAll( splitDomainCombination( dc ) );
2063 domain_lists_go_unique.get( count ).addAll( splitDomainCombination( dc ) );
2066 histogram.put( count, 1 );
2067 domain_lists.put( count, new StringBuilder( dc ) );
2068 final PriorityQueue<String> q = new PriorityQueue<String>();
2069 q.addAll( splitDomainCombination( dc ) );
2070 domain_lists_go.put( count, q );
2071 final SortedSet<String> set = new TreeSet<String>();
2072 set.addAll( splitDomainCombination( dc ) );
2073 domain_lists_go_unique.put( count, set );
2075 if ( protein_length_stats_by_dc != null ) {
2076 if ( !dc_reapp_counts_to_protein_length_stats.containsKey( count ) ) {
2077 dc_reapp_counts_to_protein_length_stats.put( count, new BasicDescriptiveStatistics() );
2079 dc_reapp_counts_to_protein_length_stats.get( count ).addValue( protein_length_stats_by_dc.get( dc )
2080 .arithmeticMean() );
2082 if ( domain_number_stats_by_dc != null ) {
2083 if ( !dc_reapp_counts_to_domain_number_stats.containsKey( count ) ) {
2084 dc_reapp_counts_to_domain_number_stats.put( count, new BasicDescriptiveStatistics() );
2086 dc_reapp_counts_to_domain_number_stats.get( count ).addValue( domain_number_stats_by_dc.get( dc )
2087 .arithmeticMean() );
2089 if ( domain_length_stats_by_domain != null ) {
2090 if ( !dc_reapp_counts_to_domain_lengths_stats.containsKey( count ) ) {
2091 dc_reapp_counts_to_domain_lengths_stats.put( count, new BasicDescriptiveStatistics() );
2093 final String[] ds = dc.split( "=" );
2094 dc_reapp_counts_to_domain_lengths_stats.get( count ).addValue( domain_length_stats_by_domain
2095 .get( ds[ 0 ] ).arithmeticMean() );
2096 dc_reapp_counts_to_domain_lengths_stats.get( count ).addValue( domain_length_stats_by_domain
2097 .get( ds[ 1 ] ).arithmeticMean() );
2100 more_than_once.add( dc );
2101 if ( protein_length_stats_by_dc != null ) {
2102 final DescriptiveStatistics s = protein_length_stats_by_dc.get( dc );
2103 for( final double element : s.getData() ) {
2104 gained_multiple_times_lengths_stats.addValue( element );
2107 if ( domain_number_stats_by_dc != null ) {
2108 final DescriptiveStatistics s = domain_number_stats_by_dc.get( dc );
2109 for( final double element : s.getData() ) {
2110 gained_multiple_times_domain_count_stats.addValue( element );
2113 if ( domain_length_stats_by_domain != null ) {
2114 final String[] ds = dc.split( "=" );
2115 final DescriptiveStatistics s0 = domain_length_stats_by_domain.get( ds[ 0 ] );
2116 final DescriptiveStatistics s1 = domain_length_stats_by_domain.get( ds[ 1 ] );
2117 for( final double element : s0.getData() ) {
2118 gained_multiple_times_domain_length_sum += element;
2119 ++gained_multiple_times_domain_length_count;
2121 for( final double element : s1.getData() ) {
2122 gained_multiple_times_domain_length_sum += element;
2123 ++gained_multiple_times_domain_length_count;
2128 if ( protein_length_stats_by_dc != null ) {
2129 final DescriptiveStatistics s = protein_length_stats_by_dc.get( dc );
2130 for( final double element : s.getData() ) {
2131 gained_once_lengths_stats.addValue( element );
2134 if ( domain_number_stats_by_dc != null ) {
2135 final DescriptiveStatistics s = domain_number_stats_by_dc.get( dc );
2136 for( final double element : s.getData() ) {
2137 gained_once_domain_count_stats.addValue( element );
2140 if ( domain_length_stats_by_domain != null ) {
2141 final String[] ds = dc.split( "=" );
2142 final DescriptiveStatistics s0 = domain_length_stats_by_domain.get( ds[ 0 ] );
2143 final DescriptiveStatistics s1 = domain_length_stats_by_domain.get( ds[ 1 ] );
2144 for( final double element : s0.getData() ) {
2145 gained_once_domain_length_sum += element;
2146 ++gained_once_domain_length_count;
2148 for( final double element : s1.getData() ) {
2149 gained_once_domain_length_sum += element;
2150 ++gained_once_domain_length_count;
2155 final Set<Integer> histogram_keys = histogram.keySet();
2156 for( final Integer histogram_key : histogram_keys ) {
2157 final int count = histogram.get( histogram_key );
2158 final StringBuilder dc = domain_lists.get( histogram_key );
2159 out_counts.write( histogram_key + "\t" + count + ForesterUtil.LINE_SEPARATOR );
2160 out_dc.write( histogram_key + "\t" + dc + ForesterUtil.LINE_SEPARATOR );
2161 out_dc_for_go_mapping.write( "#" + histogram_key + ForesterUtil.LINE_SEPARATOR );
2162 final Object[] sorted = domain_lists_go.get( histogram_key ).toArray();
2163 Arrays.sort( sorted );
2164 for( final Object domain : sorted ) {
2165 out_dc_for_go_mapping.write( domain + ForesterUtil.LINE_SEPARATOR );
2167 out_dc_for_go_mapping_unique.write( "#" + histogram_key + ForesterUtil.LINE_SEPARATOR );
2168 for( final String domain : domain_lists_go_unique.get( histogram_key ) ) {
2169 out_dc_for_go_mapping_unique.write( domain + ForesterUtil.LINE_SEPARATOR );
2174 out_dc_for_go_mapping.close();
2175 out_dc_for_go_mapping_unique.close();
2176 final SortedMap<String, Integer> lca_rank_counts = new TreeMap<String, Integer>();
2177 final SortedMap<String, Integer> lca_ancestor_species_counts = new TreeMap<String, Integer>();
2178 for( final String dc : more_than_once ) {
2179 final List<PhylogenyNode> nodes = new ArrayList<PhylogenyNode>();
2180 for( final PhylogenyNodeIterator it = local_phylogeny_l.iteratorExternalForward(); it.hasNext(); ) {
2181 final PhylogenyNode n = it.next();
2182 if ( n.getNodeData().getBinaryCharacters().getGainedCharacters().contains( dc ) ) {
2186 for( int i = 0; i < ( nodes.size() - 1 ); ++i ) {
2187 for( int j = i + 1; j < nodes.size(); ++j ) {
2188 final PhylogenyNode lca = PhylogenyMethods.calculateLCA( nodes.get( i ), nodes.get( j ) );
2189 String rank = "unknown";
2190 if ( lca.getNodeData().isHasTaxonomy()
2191 && !ForesterUtil.isEmpty( lca.getNodeData().getTaxonomy().getRank() ) ) {
2192 rank = lca.getNodeData().getTaxonomy().getRank();
2194 addToCountMap( lca_rank_counts, rank );
2196 if ( lca.getNodeData().isHasTaxonomy()
2197 && !ForesterUtil.isEmpty( lca.getNodeData().getTaxonomy().getScientificName() ) ) {
2198 lca_species = lca.getNodeData().getTaxonomy().getScientificName();
2200 else if ( lca.getNodeData().isHasTaxonomy()
2201 && !ForesterUtil.isEmpty( lca.getNodeData().getTaxonomy().getCommonName() ) ) {
2202 lca_species = lca.getNodeData().getTaxonomy().getCommonName();
2205 lca_species = lca.getName();
2207 addToCountMap( lca_ancestor_species_counts, lca_species );
2211 final BufferedWriter out_for_rank_counts = new BufferedWriter( new FileWriter( outfilename_for_rank_counts ) );
2212 final BufferedWriter out_for_ancestor_species_counts = new BufferedWriter( new FileWriter( outfilename_for_ancestor_species_counts ) );
2213 ForesterUtil.map2writer( out_for_rank_counts, lca_rank_counts, "\t", ForesterUtil.LINE_SEPARATOR );
2214 ForesterUtil.map2writer( out_for_ancestor_species_counts,
2215 lca_ancestor_species_counts,
2217 ForesterUtil.LINE_SEPARATOR );
2218 out_for_rank_counts.close();
2219 out_for_ancestor_species_counts.close();
2220 if ( !ForesterUtil.isEmpty( outfilename_for_protein_stats )
2221 && ( ( domain_length_stats_by_domain != null ) || ( protein_length_stats_by_dc != null ) || ( domain_number_stats_by_dc != null ) ) ) {
2222 final BufferedWriter w = new BufferedWriter( new FileWriter( outfilename_for_protein_stats ) );
2223 w.write( "Domain Lengths: " );
2225 if ( domain_length_stats_by_domain != null ) {
2226 for( final Entry<Integer, DescriptiveStatistics> entry : dc_reapp_counts_to_domain_lengths_stats
2228 w.write( entry.getKey().toString() );
2229 w.write( "\t" + entry.getValue().arithmeticMean() );
2230 w.write( "\t" + entry.getValue().median() );
2237 w.write( "Protein Lengths: " );
2239 if ( protein_length_stats_by_dc != null ) {
2240 for( final Entry<Integer, DescriptiveStatistics> entry : dc_reapp_counts_to_protein_length_stats
2242 w.write( entry.getKey().toString() );
2243 w.write( "\t" + entry.getValue().arithmeticMean() );
2244 w.write( "\t" + entry.getValue().median() );
2251 w.write( "Number of domains: " );
2253 if ( domain_number_stats_by_dc != null ) {
2254 for( final Entry<Integer, DescriptiveStatistics> entry : dc_reapp_counts_to_domain_number_stats
2256 w.write( entry.getKey().toString() );
2257 w.write( "\t" + entry.getValue().arithmeticMean() );
2258 w.write( "\t" + entry.getValue().median() );
2265 w.write( "Gained once, domain lengths:" );
2267 w.write( "N: " + gained_once_domain_length_count );
2269 w.write( "Avg: " + ( ( double ) gained_once_domain_length_sum / gained_once_domain_length_count ) );
2272 w.write( "Gained multiple times, domain lengths:" );
2274 w.write( "N: " + gained_multiple_times_domain_length_count );
2277 + ( ( double ) gained_multiple_times_domain_length_sum / gained_multiple_times_domain_length_count ) );
2282 w.write( "Gained once, protein lengths:" );
2284 w.write( gained_once_lengths_stats.toString() );
2287 w.write( "Gained once, domain counts:" );
2289 w.write( gained_once_domain_count_stats.toString() );
2292 w.write( "Gained multiple times, protein lengths:" );
2294 w.write( gained_multiple_times_lengths_stats.toString() );
2297 w.write( "Gained multiple times, domain counts:" );
2299 w.write( gained_multiple_times_domain_count_stats.toString() );
2304 catch ( final IOException e ) {
2305 ForesterUtil.printWarningMessage( surfacing.PRG_NAME, "Failure to write: " + e );
2307 ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote independent domain combination gains fitch counts to ["
2308 + outfilename_for_counts + "]" );
2309 ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote independent domain combination gains fitch lists to ["
2310 + outfilename_for_dc + "]" );
2311 ForesterUtil.programMessage( surfacing.PRG_NAME,
2312 "Wrote independent domain combination gains fitch lists to (for GO mapping) ["
2313 + outfilename_for_dc_for_go_mapping + "]" );
2314 ForesterUtil.programMessage( surfacing.PRG_NAME,
2315 "Wrote independent domain combination gains fitch lists to (for GO mapping, unique) ["
2316 + outfilename_for_dc_for_go_mapping_unique + "]" );
2319 private static SortedSet<String> collectAllDomainsChangedOnSubtree( final PhylogenyNode subtree_root,
2320 final boolean get_gains ) {
2321 final SortedSet<String> domains = new TreeSet<String>();
2322 for( final PhylogenyNode descendant : PhylogenyMethods.getAllDescendants( subtree_root ) ) {
2323 final BinaryCharacters chars = descendant.getNodeData().getBinaryCharacters();
2325 domains.addAll( chars.getGainedCharacters() );
2328 domains.addAll( chars.getLostCharacters() );
2334 private static File createBaseDirForPerNodeDomainFiles( final String base_dir,
2335 final boolean domain_combinations,
2336 final CharacterStateMatrix.GainLossStates state,
2337 final String outfile ) {
2338 File per_node_go_mapped_domain_gain_loss_files_base_dir = new File( new File( outfile ).getParent()
2339 + ForesterUtil.FILE_SEPARATOR + base_dir );
2340 if ( !per_node_go_mapped_domain_gain_loss_files_base_dir.exists() ) {
2341 per_node_go_mapped_domain_gain_loss_files_base_dir.mkdir();
2343 if ( domain_combinations ) {
2344 per_node_go_mapped_domain_gain_loss_files_base_dir = new File( per_node_go_mapped_domain_gain_loss_files_base_dir
2345 + ForesterUtil.FILE_SEPARATOR + "DC" );
2348 per_node_go_mapped_domain_gain_loss_files_base_dir = new File( per_node_go_mapped_domain_gain_loss_files_base_dir
2349 + ForesterUtil.FILE_SEPARATOR + "DOMAINS" );
2351 if ( !per_node_go_mapped_domain_gain_loss_files_base_dir.exists() ) {
2352 per_node_go_mapped_domain_gain_loss_files_base_dir.mkdir();
2354 if ( state == GainLossStates.GAIN ) {
2355 per_node_go_mapped_domain_gain_loss_files_base_dir = new File( per_node_go_mapped_domain_gain_loss_files_base_dir
2356 + ForesterUtil.FILE_SEPARATOR + "GAINS" );
2358 else if ( state == GainLossStates.LOSS ) {
2359 per_node_go_mapped_domain_gain_loss_files_base_dir = new File( per_node_go_mapped_domain_gain_loss_files_base_dir
2360 + ForesterUtil.FILE_SEPARATOR + "LOSSES" );
2363 per_node_go_mapped_domain_gain_loss_files_base_dir = new File( per_node_go_mapped_domain_gain_loss_files_base_dir
2364 + ForesterUtil.FILE_SEPARATOR + "PRESENT" );
2366 if ( !per_node_go_mapped_domain_gain_loss_files_base_dir.exists() ) {
2367 per_node_go_mapped_domain_gain_loss_files_base_dir.mkdir();
2369 return per_node_go_mapped_domain_gain_loss_files_base_dir;
2372 private static SortedSet<BinaryDomainCombination> createSetOfAllBinaryDomainCombinationsPerGenome( final GenomeWideCombinableDomains gwcd ) {
2373 final SortedMap<DomainId, CombinableDomains> cds = gwcd.getAllCombinableDomainsIds();
2374 final SortedSet<BinaryDomainCombination> binary_combinations = new TreeSet<BinaryDomainCombination>();
2375 for( final DomainId domain_id : cds.keySet() ) {
2376 final CombinableDomains cd = cds.get( domain_id );
2377 binary_combinations.addAll( cd.toBinaryDomainCombinations() );
2379 return binary_combinations;
2382 private static List<String> splitDomainCombination( final String dc ) {
2383 final String[] s = dc.split( "=" );
2384 if ( s.length != 2 ) {
2385 ForesterUtil.printErrorMessage( surfacing.PRG_NAME, "Stringyfied domain combination has illegal format: "
2389 final List<String> l = new ArrayList<String>( 2 );
2395 private static void writeAllEncounteredPfamsToFile( final Map<DomainId, List<GoId>> domain_id_to_go_ids_map,
2396 final Map<GoId, GoTerm> go_id_to_term_map,
2397 final String outfile_name,
2398 final SortedSet<String> all_pfams_encountered ) {
2399 final File all_pfams_encountered_file = new File( outfile_name + surfacing.ALL_PFAMS_ENCOUNTERED_SUFFIX );
2400 final File all_pfams_encountered_with_go_annotation_file = new File( outfile_name
2401 + surfacing.ALL_PFAMS_ENCOUNTERED_WITH_GO_ANNOTATION_SUFFIX );
2402 final File encountered_pfams_summary_file = new File( outfile_name + surfacing.ENCOUNTERED_PFAMS_SUMMARY_SUFFIX );
2403 int biological_process_counter = 0;
2404 int cellular_component_counter = 0;
2405 int molecular_function_counter = 0;
2406 int pfams_with_mappings_counter = 0;
2407 int pfams_without_mappings_counter = 0;
2408 int pfams_without_mappings_to_bp_or_mf_counter = 0;
2409 int pfams_with_mappings_to_bp_or_mf_counter = 0;
2411 final Writer all_pfams_encountered_writer = new BufferedWriter( new FileWriter( all_pfams_encountered_file ) );
2412 final Writer all_pfams_encountered_with_go_annotation_writer = new BufferedWriter( new FileWriter( all_pfams_encountered_with_go_annotation_file ) );
2413 final Writer summary_writer = new BufferedWriter( new FileWriter( encountered_pfams_summary_file ) );
2414 summary_writer.write( "# Pfam to GO mapping summary" );
2415 summary_writer.write( ForesterUtil.LINE_SEPARATOR );
2416 summary_writer.write( "# Actual summary is at the end of this file." );
2417 summary_writer.write( ForesterUtil.LINE_SEPARATOR );
2418 summary_writer.write( "# Encountered Pfams without a GO mapping:" );
2419 summary_writer.write( ForesterUtil.LINE_SEPARATOR );
2420 for( final String pfam : all_pfams_encountered ) {
2421 all_pfams_encountered_writer.write( pfam );
2422 all_pfams_encountered_writer.write( ForesterUtil.LINE_SEPARATOR );
2423 final DomainId domain_id = new DomainId( pfam );
2424 if ( domain_id_to_go_ids_map.containsKey( domain_id ) ) {
2425 ++pfams_with_mappings_counter;
2426 all_pfams_encountered_with_go_annotation_writer.write( pfam );
2427 all_pfams_encountered_with_go_annotation_writer.write( ForesterUtil.LINE_SEPARATOR );
2428 final List<GoId> go_ids = domain_id_to_go_ids_map.get( domain_id );
2429 boolean maps_to_bp = false;
2430 boolean maps_to_cc = false;
2431 boolean maps_to_mf = false;
2432 for( final GoId go_id : go_ids ) {
2433 final GoTerm go_term = go_id_to_term_map.get( go_id );
2434 if ( go_term.getGoNameSpace().isBiologicalProcess() ) {
2437 else if ( go_term.getGoNameSpace().isCellularComponent() ) {
2440 else if ( go_term.getGoNameSpace().isMolecularFunction() ) {
2445 ++biological_process_counter;
2448 ++cellular_component_counter;
2451 ++molecular_function_counter;
2453 if ( maps_to_bp || maps_to_mf ) {
2454 ++pfams_with_mappings_to_bp_or_mf_counter;
2457 ++pfams_without_mappings_to_bp_or_mf_counter;
2461 ++pfams_without_mappings_to_bp_or_mf_counter;
2462 ++pfams_without_mappings_counter;
2463 summary_writer.write( pfam );
2464 summary_writer.write( ForesterUtil.LINE_SEPARATOR );
2467 all_pfams_encountered_writer.close();
2468 all_pfams_encountered_with_go_annotation_writer.close();
2469 ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote all [" + all_pfams_encountered.size()
2470 + "] encountered Pfams to: \"" + all_pfams_encountered_file + "\"" );
2471 ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote all [" + pfams_with_mappings_counter
2472 + "] encountered Pfams with GO mappings to: \"" + all_pfams_encountered_with_go_annotation_file
2474 ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote summary (including all ["
2475 + pfams_without_mappings_counter + "] encountered Pfams without GO mappings) to: \""
2476 + encountered_pfams_summary_file + "\"" );
2477 ForesterUtil.programMessage( surfacing.PRG_NAME, "Sum of Pfams encountered : "
2478 + all_pfams_encountered.size() );
2479 ForesterUtil.programMessage( surfacing.PRG_NAME, "Pfams without a mapping : "
2480 + pfams_without_mappings_counter + " ["
2481 + ( ( 100 * pfams_without_mappings_counter ) / all_pfams_encountered.size() ) + "%]" );
2482 ForesterUtil.programMessage( surfacing.PRG_NAME, "Pfams without mapping to proc. or func. : "
2483 + pfams_without_mappings_to_bp_or_mf_counter + " ["
2484 + ( ( 100 * pfams_without_mappings_to_bp_or_mf_counter ) / all_pfams_encountered.size() ) + "%]" );
2485 ForesterUtil.programMessage( surfacing.PRG_NAME, "Pfams with a mapping : "
2486 + pfams_with_mappings_counter + " ["
2487 + ( ( 100 * pfams_with_mappings_counter ) / all_pfams_encountered.size() ) + "%]" );
2488 ForesterUtil.programMessage( surfacing.PRG_NAME, "Pfams with a mapping to proc. or func. : "
2489 + pfams_with_mappings_to_bp_or_mf_counter + " ["
2490 + ( ( 100 * pfams_with_mappings_to_bp_or_mf_counter ) / all_pfams_encountered.size() ) + "%]" );
2491 ForesterUtil.programMessage( surfacing.PRG_NAME, "Pfams with mapping to biological process: "
2492 + biological_process_counter + " ["
2493 + ( ( 100 * biological_process_counter ) / all_pfams_encountered.size() ) + "%]" );
2494 ForesterUtil.programMessage( surfacing.PRG_NAME, "Pfams with mapping to molecular function: "
2495 + molecular_function_counter + " ["
2496 + ( ( 100 * molecular_function_counter ) / all_pfams_encountered.size() ) + "%]" );
2497 ForesterUtil.programMessage( surfacing.PRG_NAME, "Pfams with mapping to cellular component: "
2498 + cellular_component_counter + " ["
2499 + ( ( 100 * cellular_component_counter ) / all_pfams_encountered.size() ) + "%]" );
2500 summary_writer.write( ForesterUtil.LINE_SEPARATOR );
2501 summary_writer.write( "# Sum of Pfams encountered : " + all_pfams_encountered.size() );
2502 summary_writer.write( ForesterUtil.LINE_SEPARATOR );
2503 summary_writer.write( "# Pfams without a mapping : " + pfams_without_mappings_counter
2504 + " [" + ( ( 100 * pfams_without_mappings_counter ) / all_pfams_encountered.size() ) + "%]" );
2505 summary_writer.write( ForesterUtil.LINE_SEPARATOR );
2506 summary_writer.write( "# Pfams without mapping to proc. or func. : "
2507 + pfams_without_mappings_to_bp_or_mf_counter + " ["
2508 + ( ( 100 * pfams_without_mappings_to_bp_or_mf_counter ) / all_pfams_encountered.size() ) + "%]" );
2509 summary_writer.write( ForesterUtil.LINE_SEPARATOR );
2510 summary_writer.write( "# Pfams with a mapping : " + pfams_with_mappings_counter + " ["
2511 + ( ( 100 * pfams_with_mappings_counter ) / all_pfams_encountered.size() ) + "%]" );
2512 summary_writer.write( ForesterUtil.LINE_SEPARATOR );
2513 summary_writer.write( "# Pfams with a mapping to proc. or func. : "
2514 + pfams_with_mappings_to_bp_or_mf_counter + " ["
2515 + ( ( 100 * pfams_with_mappings_to_bp_or_mf_counter ) / all_pfams_encountered.size() ) + "%]" );
2516 summary_writer.write( ForesterUtil.LINE_SEPARATOR );
2517 summary_writer.write( "# Pfams with mapping to biological process: " + biological_process_counter + " ["
2518 + ( ( 100 * biological_process_counter ) / all_pfams_encountered.size() ) + "%]" );
2519 summary_writer.write( ForesterUtil.LINE_SEPARATOR );
2520 summary_writer.write( "# Pfams with mapping to molecular function: " + molecular_function_counter + " ["
2521 + ( ( 100 * molecular_function_counter ) / all_pfams_encountered.size() ) + "%]" );
2522 summary_writer.write( ForesterUtil.LINE_SEPARATOR );
2523 summary_writer.write( "# Pfams with mapping to cellular component: " + cellular_component_counter + " ["
2524 + ( ( 100 * cellular_component_counter ) / all_pfams_encountered.size() ) + "%]" );
2525 summary_writer.write( ForesterUtil.LINE_SEPARATOR );
2526 summary_writer.close();
2528 catch ( final IOException e ) {
2529 ForesterUtil.printWarningMessage( surfacing.PRG_NAME, "Failure to write: " + e );
2533 private static void writeDomainData( final Map<DomainId, List<GoId>> domain_id_to_go_ids_map,
2534 final Map<GoId, GoTerm> go_id_to_term_map,
2535 final GoNameSpace go_namespace_limit,
2537 final String domain_0,
2538 final String domain_1,
2539 final String prefix_for_html,
2540 final String character_separator_for_non_html_output,
2541 final Map<DomainId, Set<String>>[] domain_id_to_secondary_features_maps,
2542 final Set<GoId> all_go_ids ) throws IOException {
2543 boolean any_go_annotation_present = false;
2544 boolean first_has_no_go = false;
2545 int domain_count = 2; // To distinguish between domains and binary domain combinations.
2546 if ( ForesterUtil.isEmpty( domain_1 ) ) {
2549 // The following has a difficult to understand logic.
2550 for( int d = 0; d < domain_count; ++d ) {
2551 List<GoId> go_ids = null;
2552 boolean go_annotation_present = false;
2554 final DomainId domain_id = new DomainId( domain_0 );
2555 if ( domain_id_to_go_ids_map.containsKey( domain_id ) ) {
2556 go_annotation_present = true;
2557 any_go_annotation_present = true;
2558 go_ids = domain_id_to_go_ids_map.get( domain_id );
2561 first_has_no_go = true;
2565 final DomainId domain_id = new DomainId( domain_1 );
2566 if ( domain_id_to_go_ids_map.containsKey( domain_id ) ) {
2567 go_annotation_present = true;
2568 any_go_annotation_present = true;
2569 go_ids = domain_id_to_go_ids_map.get( domain_id );
2572 if ( go_annotation_present ) {
2573 boolean first = ( ( d == 0 ) || ( ( d == 1 ) && first_has_no_go ) );
2574 for( final GoId go_id : go_ids ) {
2575 out.write( "<tr>" );
2578 writeDomainIdsToHtml( out,
2582 domain_id_to_secondary_features_maps );
2585 out.write( "<td></td>" );
2587 if ( !go_id_to_term_map.containsKey( go_id ) ) {
2588 throw new IllegalArgumentException( "GO-id [" + go_id + "] not found in GO-id to GO-term map" );
2590 final GoTerm go_term = go_id_to_term_map.get( go_id );
2591 if ( ( go_namespace_limit == null ) || go_namespace_limit.equals( go_term.getGoNameSpace() ) ) {
2592 // final String top = GoUtils.getPenultimateGoTerm( go_term, go_id_to_term_map ).getName();
2593 final String go_id_str = go_id.getId();
2594 out.write( "<td>" );
2595 out.write( "<a href=\"" + SurfacingConstants.AMIGO_LINK + go_id_str
2596 + "\" target=\"amigo_window\">" + go_id_str + "</a>" );
2597 out.write( "</td><td>" );
2598 out.write( go_term.getName() );
2599 if ( domain_count == 2 ) {
2600 out.write( " (" + d + ")" );
2602 out.write( "</td><td>" );
2603 // out.write( top );
2604 // out.write( "</td><td>" );
2606 out.write( go_term.getGoNameSpace().toShortString() );
2608 out.write( "</td>" );
2609 if ( all_go_ids != null ) {
2610 all_go_ids.add( go_id );
2614 out.write( "<td>" );
2615 out.write( "</td><td>" );
2616 out.write( "</td><td>" );
2617 out.write( "</td><td>" );
2618 out.write( "</td>" );
2620 out.write( "</tr>" );
2621 out.write( SurfacingConstants.NL );
2624 } // for( int d = 0; d < domain_count; ++d )
2625 if ( !any_go_annotation_present ) {
2626 out.write( "<tr>" );
2627 writeDomainIdsToHtml( out, domain_0, domain_1, prefix_for_html, domain_id_to_secondary_features_maps );
2628 out.write( "<td>" );
2629 out.write( "</td><td>" );
2630 out.write( "</td><td>" );
2631 out.write( "</td><td>" );
2632 out.write( "</td>" );
2633 out.write( "</tr>" );
2634 out.write( SurfacingConstants.NL );
2638 private static void writeDomainIdsToHtml( final Writer out,
2639 final String domain_0,
2640 final String domain_1,
2641 final String prefix_for_detailed_html,
2642 final Map<DomainId, Set<String>>[] domain_id_to_secondary_features_maps )
2643 throws IOException {
2644 out.write( "<td>" );
2645 if ( !ForesterUtil.isEmpty( prefix_for_detailed_html ) ) {
2646 out.write( prefix_for_detailed_html );
2649 out.write( "<a href=\"" + SurfacingConstants.PFAM_FAMILY_ID_LINK + domain_0 + "\">" + domain_0 + "</a>" );
2650 out.write( "</td>" );
2653 private static void writeDomainsToIndividualFilePerTreeNode( final Writer individual_files_writer,
2654 final String domain_0,
2655 final String domain_1 ) throws IOException {
2656 individual_files_writer.write( domain_0 );
2657 individual_files_writer.write( ForesterUtil.LINE_SEPARATOR );
2658 if ( !ForesterUtil.isEmpty( domain_1 ) ) {
2659 individual_files_writer.write( domain_1 );
2660 individual_files_writer.write( ForesterUtil.LINE_SEPARATOR );
2664 private static void writePfamsToFile( final String outfile_name, final SortedSet<String> pfams ) {
2666 final Writer writer = new BufferedWriter( new FileWriter( new File( outfile_name ) ) );
2667 for( final String pfam : pfams ) {
2668 writer.write( pfam );
2669 writer.write( ForesterUtil.LINE_SEPARATOR );
2672 ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote " + pfams.size() + " pfams to [" + outfile_name
2675 catch ( final IOException e ) {
2676 ForesterUtil.printWarningMessage( surfacing.PRG_NAME, "Failure to write: " + e );
2680 private static void writeToNexus( final String outfile_name,
2681 final CharacterStateMatrix<BinaryStates> matrix,
2682 final Phylogeny phylogeny ) {
2683 if ( !( matrix instanceof BasicCharacterStateMatrix ) ) {
2684 throw new IllegalArgumentException( "can only write matrices of type [" + BasicCharacterStateMatrix.class
2687 final BasicCharacterStateMatrix<BinaryStates> my_matrix = ( org.forester.evoinference.matrix.character.BasicCharacterStateMatrix<BinaryStates> ) matrix;
2688 final List<Phylogeny> phylogenies = new ArrayList<Phylogeny>( 1 );
2689 phylogenies.add( phylogeny );
2691 final BufferedWriter w = new BufferedWriter( new FileWriter( outfile_name ) );
2692 w.write( NexusConstants.NEXUS );
2693 w.write( ForesterUtil.LINE_SEPARATOR );
2694 my_matrix.writeNexusTaxaBlock( w );
2695 my_matrix.writeNexusBinaryChractersBlock( w );
2696 PhylogenyWriter.writeNexusTreesBlock( w, phylogenies, NH_CONVERSION_SUPPORT_VALUE_STYLE.NONE );
2699 ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote Nexus file: \"" + outfile_name + "\"" );
2701 catch ( final IOException e ) {
2702 ForesterUtil.fatalError( surfacing.PRG_NAME, e.getMessage() );
2706 private static void writeToNexus( final String outfile_name,
2707 final DomainParsimonyCalculator domain_parsimony,
2708 final Phylogeny phylogeny ) {
2709 writeToNexus( outfile_name + surfacing.NEXUS_EXTERNAL_DOMAINS,
2710 domain_parsimony.createMatrixOfDomainPresenceOrAbsence(),
2712 writeToNexus( outfile_name + surfacing.NEXUS_EXTERNAL_DOMAIN_COMBINATIONS,
2713 domain_parsimony.createMatrixOfBinaryDomainCombinationPresenceOrAbsence(),
2717 final static class DomainComparator implements Comparator<Domain> {
2719 final private boolean _ascending;
2721 public DomainComparator( final boolean ascending ) {
2722 _ascending = ascending;
2726 public final int compare( final Domain d0, final Domain d1 ) {
2727 if ( d0.getFrom() < d1.getFrom() ) {
2728 return _ascending ? -1 : 1;
2730 else if ( d0.getFrom() > d1.getFrom() ) {
2731 return _ascending ? 1 : -1;