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: www.phylosoft.org/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.List;
44 import java.util.PriorityQueue;
46 import java.util.SortedMap;
47 import java.util.SortedSet;
48 import java.util.TreeMap;
49 import java.util.TreeSet;
50 import java.util.regex.Matcher;
51 import java.util.regex.Pattern;
53 import org.forester.application.surfacing;
54 import org.forester.evoinference.distance.NeighborJoining;
55 import org.forester.evoinference.matrix.character.BasicCharacterStateMatrix;
56 import org.forester.evoinference.matrix.character.CharacterStateMatrix;
57 import org.forester.evoinference.matrix.character.CharacterStateMatrix.BinaryStates;
58 import org.forester.evoinference.matrix.character.CharacterStateMatrix.Format;
59 import org.forester.evoinference.matrix.character.CharacterStateMatrix.GainLossStates;
60 import org.forester.evoinference.matrix.distance.DistanceMatrix;
61 import org.forester.go.GoId;
62 import org.forester.go.GoNameSpace;
63 import org.forester.go.GoTerm;
64 import org.forester.go.PfamToGoMapping;
65 import org.forester.io.parsers.nexus.NexusConstants;
66 import org.forester.io.writers.PhylogenyWriter;
67 import org.forester.phylogeny.Phylogeny;
68 import org.forester.phylogeny.PhylogenyMethods;
69 import org.forester.phylogeny.PhylogenyNode;
70 import org.forester.phylogeny.PhylogenyNodeI.NH_CONVERSION_SUPPORT_VALUE_STYLE;
71 import org.forester.phylogeny.data.BinaryCharacters;
72 import org.forester.phylogeny.data.Confidence;
73 import org.forester.phylogeny.iterators.PhylogenyNodeIterator;
74 import org.forester.surfacing.DomainSimilarityCalculator.Detailedness;
75 import org.forester.surfacing.DomainSimilarityCalculator.GoAnnotationOutput;
76 import org.forester.surfacing.GenomeWideCombinableDomains.GenomeWideCombinableDomainsSortOrder;
77 import org.forester.util.AsciiHistogram;
78 import org.forester.util.BasicDescriptiveStatistics;
79 import org.forester.util.BasicTable;
80 import org.forester.util.BasicTableParser;
81 import org.forester.util.DescriptiveStatistics;
82 import org.forester.util.ForesterUtil;
84 public final class SurfacingUtil {
86 private final static NumberFormat FORMATTER = new DecimalFormat( "0.0E0" );
87 private final static NumberFormat FORMATTER_3 = new DecimalFormat( "0.000" );
88 private static final Comparator<Domain> ASCENDING_CONFIDENCE_VALUE_ORDER = new Comparator<Domain>() {
91 public int compare( final Domain d1,
93 if ( d1.getPerSequenceEvalue() < d2
94 .getPerSequenceEvalue() ) {
98 .getPerSequenceEvalue() > d2
99 .getPerSequenceEvalue() ) {
103 return d1.compareTo( d2 );
107 public final static Pattern PATTERN_SP_STYLE_TAXONOMY = Pattern.compile( "^[A-Z0-9]{3,5}$" );
109 private SurfacingUtil() {
110 // Hidden constructor.
113 public static void addAllBinaryDomainCombinationToSet( final GenomeWideCombinableDomains genome,
114 final SortedSet<BinaryDomainCombination> binary_domain_combinations ) {
115 final SortedMap<DomainId, CombinableDomains> all_cd = genome.getAllCombinableDomainsIds();
116 for( final DomainId domain_id : all_cd.keySet() ) {
117 binary_domain_combinations.addAll( all_cd.get( domain_id ).toBinaryDomainCombinations() );
121 public static void addAllDomainIdsToSet( final GenomeWideCombinableDomains genome,
122 final SortedSet<DomainId> domain_ids ) {
123 final SortedSet<DomainId> domains = genome.getAllDomainIds();
124 for( final DomainId domain : domains ) {
125 domain_ids.add( domain );
129 public static void addHtmlHead( final Writer w, final String title ) throws IOException {
130 w.write( SurfacingConstants.NL );
132 w.write( "<title>" );
134 w.write( "</title>" );
135 w.write( SurfacingConstants.NL );
136 w.write( "<style>" );
137 w.write( SurfacingConstants.NL );
138 w.write( "a:visited { color : #6633FF; text-decoration : none; }" );
139 w.write( SurfacingConstants.NL );
140 w.write( "a:link { color : #6633FF; text-decoration : none; }" );
141 w.write( SurfacingConstants.NL );
142 w.write( "a:active { color : #99FF00; text-decoration : none; }" );
143 w.write( SurfacingConstants.NL );
144 w.write( "a:hover { color : #FFFFFF; background-color : #99FF00; text-decoration : none; }" );
145 w.write( SurfacingConstants.NL );
146 w.write( "td { text-align: left; vertical-align: top; font-family: Verdana, Arial, Helvetica; font-size: 8pt}" );
147 w.write( SurfacingConstants.NL );
148 w.write( "h1 { color : #0000FF; font-family: Verdana, Arial, Helvetica; font-size: 18pt; font-weight: bold }" );
149 w.write( SurfacingConstants.NL );
150 w.write( "h2 { color : #0000FF; font-family: Verdana, Arial, Helvetica; font-size: 16pt; font-weight: bold }" );
151 w.write( SurfacingConstants.NL );
152 w.write( "</style>" );
153 w.write( SurfacingConstants.NL );
154 w.write( "</head>" );
155 w.write( SurfacingConstants.NL );
158 public static DescriptiveStatistics calculateDescriptiveStatisticsForMeanValues( final Set<DomainSimilarity> similarities ) {
159 final DescriptiveStatistics stats = new BasicDescriptiveStatistics();
160 for( final DomainSimilarity similarity : similarities ) {
161 stats.addValue( similarity.getMeanSimilarityScore() );
166 private static void calculateIndependentDomainCombinationGains( final Phylogeny local_phylogeny_l,
167 final String outfilename_for_counts,
168 final String outfilename_for_dc,
169 final String outfilename_for_dc_for_go_mapping,
170 final String outfilename_for_dc_for_go_mapping_unique,
171 final String outfilename_for_rank_counts,
172 final String outfilename_for_ancestor_species_counts ) {
174 final BufferedWriter out_counts = new BufferedWriter( new FileWriter( outfilename_for_counts ) );
175 final BufferedWriter out_dc = new BufferedWriter( new FileWriter( outfilename_for_dc ) );
176 final BufferedWriter out_dc_for_go_mapping = new BufferedWriter( new FileWriter( outfilename_for_dc_for_go_mapping ) );
177 final BufferedWriter out_dc_for_go_mapping_unique = new BufferedWriter( new FileWriter( outfilename_for_dc_for_go_mapping_unique ) );
178 final SortedMap<String, Integer> dc_gain_counts = new TreeMap<String, Integer>();
179 for( final PhylogenyNodeIterator it = local_phylogeny_l.iteratorPostorder(); it.hasNext(); ) {
180 final PhylogenyNode n = it.next();
181 final Set<String> gained_dc = n.getNodeData().getBinaryCharacters().getGainedCharacters();
182 for( final String dc : gained_dc ) {
183 if ( dc_gain_counts.containsKey( dc ) ) {
184 dc_gain_counts.put( dc, dc_gain_counts.get( dc ) + 1 );
187 dc_gain_counts.put( dc, 1 );
191 final SortedMap<Integer, Integer> histogram = new TreeMap<Integer, Integer>();
192 final SortedMap<Integer, StringBuilder> domain_lists = new TreeMap<Integer, StringBuilder>();
193 final SortedMap<Integer, PriorityQueue<String>> domain_lists_go = new TreeMap<Integer, PriorityQueue<String>>();
194 final SortedMap<Integer, SortedSet<String>> domain_lists_go_unique = new TreeMap<Integer, SortedSet<String>>();
195 final Set<String> dcs = dc_gain_counts.keySet();
196 final SortedSet<String> more_than_once = new TreeSet<String>();
197 for( final String dc : dcs ) {
198 final int count = dc_gain_counts.get( dc );
199 if ( histogram.containsKey( count ) ) {
200 histogram.put( count, histogram.get( count ) + 1 );
201 domain_lists.get( count ).append( ", " + dc );
202 domain_lists_go.get( count ).addAll( splitDomainCombination( dc ) );
203 domain_lists_go_unique.get( count ).addAll( splitDomainCombination( dc ) );
206 histogram.put( count, 1 );
207 domain_lists.put( count, new StringBuilder( dc ) );
208 final PriorityQueue<String> q = new PriorityQueue<String>();
209 q.addAll( splitDomainCombination( dc ) );
210 domain_lists_go.put( count, q );
211 final SortedSet<String> set = new TreeSet<String>();
212 set.addAll( splitDomainCombination( dc ) );
213 domain_lists_go_unique.put( count, set );
216 more_than_once.add( dc );
219 final Set<Integer> histogram_keys = histogram.keySet();
220 for( final Integer histogram_key : histogram_keys ) {
221 final int count = histogram.get( histogram_key );
222 final StringBuilder dc = domain_lists.get( histogram_key );
223 out_counts.write( histogram_key + "\t" + count + ForesterUtil.LINE_SEPARATOR );
224 out_dc.write( histogram_key + "\t" + dc + ForesterUtil.LINE_SEPARATOR );
225 out_dc_for_go_mapping.write( "#" + histogram_key + ForesterUtil.LINE_SEPARATOR );
226 final Object[] sorted = domain_lists_go.get( histogram_key ).toArray();
227 Arrays.sort( sorted );
228 for( final Object domain : sorted ) {
229 out_dc_for_go_mapping.write( domain + ForesterUtil.LINE_SEPARATOR );
231 out_dc_for_go_mapping_unique.write( "#" + histogram_key + ForesterUtil.LINE_SEPARATOR );
232 for( final String domain : domain_lists_go_unique.get( histogram_key ) ) {
233 out_dc_for_go_mapping_unique.write( domain + ForesterUtil.LINE_SEPARATOR );
238 out_dc_for_go_mapping.close();
239 out_dc_for_go_mapping_unique.close();
241 final SortedMap<String, Integer> lca_rank_counts = new TreeMap<String, Integer>();
242 final SortedMap<String, Integer> lca_ancestor_species_counts = new TreeMap<String, Integer>();
243 for( final String dc : more_than_once ) {
244 final List<PhylogenyNode> nodes = new ArrayList<PhylogenyNode>();
245 for( final PhylogenyNodeIterator it = local_phylogeny_l.iteratorExternalForward(); it.hasNext(); ) {
246 final PhylogenyNode n = it.next();
247 if ( n.getNodeData().getBinaryCharacters().getGainedCharacters().contains( dc ) ) {
251 for( int i = 0; i < nodes.size() - 1; ++i ) {
252 for( int j = i + 1; j < nodes.size(); ++j ) {
253 final PhylogenyNode lca = PhylogenyMethods.getInstance().obtainLCA( nodes.get( i ),
255 String rank = "unknown";
256 if ( lca.getNodeData().isHasTaxonomy()
257 && !ForesterUtil.isEmpty( lca.getNodeData().getTaxonomy().getRank() ) ) {
258 rank = lca.getNodeData().getTaxonomy().getRank();
260 addToCountMap( lca_rank_counts, rank );
262 if ( lca.getNodeData().isHasTaxonomy()
263 && !ForesterUtil.isEmpty( lca.getNodeData().getTaxonomy().getScientificName() ) ) {
264 lca_species = lca.getNodeData().getTaxonomy().getScientificName();
266 else if ( lca.getNodeData().isHasTaxonomy()
267 && !ForesterUtil.isEmpty( lca.getNodeData().getTaxonomy().getCommonName() ) ) {
268 lca_species = lca.getNodeData().getTaxonomy().getCommonName();
271 lca_species = lca.getName();
273 addToCountMap( lca_ancestor_species_counts, lca_species );
277 final BufferedWriter out_for_rank_counts = new BufferedWriter( new FileWriter( outfilename_for_rank_counts ) );
278 final BufferedWriter out_for_ancestor_species_counts = new BufferedWriter( new FileWriter( outfilename_for_ancestor_species_counts ) );
279 ForesterUtil.map2writer( out_for_rank_counts, lca_rank_counts, "\t", ForesterUtil.LINE_SEPARATOR );
280 ForesterUtil.map2writer( out_for_ancestor_species_counts,
281 lca_ancestor_species_counts,
283 ForesterUtil.LINE_SEPARATOR );
284 out_for_rank_counts.close();
285 out_for_ancestor_species_counts.close();
287 catch ( final IOException e ) {
288 ForesterUtil.printWarningMessage( surfacing.PRG_NAME, "Failure to write: " + e );
290 ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote independent domain combination gains fitch counts to ["
291 + outfilename_for_counts + "]" );
292 ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote independent domain combination gains fitch lists to ["
293 + outfilename_for_dc + "]" );
294 ForesterUtil.programMessage( surfacing.PRG_NAME,
295 "Wrote independent domain combination gains fitch lists to (for GO mapping) ["
296 + outfilename_for_dc_for_go_mapping + "]" );
297 ForesterUtil.programMessage( surfacing.PRG_NAME,
298 "Wrote independent domain combination gains fitch lists to (for GO mapping, unique) ["
299 + outfilename_for_dc_for_go_mapping_unique + "]" );
302 private final static void addToCountMap( final Map<String, Integer> map, final String s ) {
303 if ( map.containsKey( s ) ) {
304 map.put( s, map.get( s ) + 1 );
311 public static int calculateOverlap( final Domain domain, final List<Boolean> covered_positions ) {
312 int overlap_count = 0;
313 for( int i = domain.getFrom(); i <= domain.getTo(); ++i ) {
314 if ( ( i < covered_positions.size() ) && ( covered_positions.get( i ) == true ) ) {
318 return overlap_count;
321 public static void checkForOutputFileWriteability( final File outfile ) {
322 final String error = ForesterUtil.isWritableFile( outfile );
323 if ( !ForesterUtil.isEmpty( error ) ) {
324 ForesterUtil.fatalError( surfacing.PRG_NAME, error );
328 private static SortedSet<String> collectAllDomainsChangedOnSubtree( final PhylogenyNode subtree_root,
329 final boolean get_gains ) {
330 final SortedSet<String> domains = new TreeSet<String>();
331 for( final PhylogenyNode descendant : PhylogenyMethods.getAllDescendants( subtree_root ) ) {
332 final BinaryCharacters chars = descendant.getNodeData().getBinaryCharacters();
334 domains.addAll( chars.getGainedCharacters() );
337 domains.addAll( chars.getLostCharacters() );
343 public static void collectChangedDomainCombinationsFromBinaryStatesMatrixAsListToFile( final CharacterStateMatrix<CharacterStateMatrix.GainLossStates> matrix,
344 final BinaryDomainCombination.DomainCombinationType dc_type,
345 final List<BinaryDomainCombination> all_binary_domains_combination_gained,
346 final boolean get_gains ) {
347 final SortedSet<String> sorted_ids = new TreeSet<String>();
348 for( int i = 0; i < matrix.getNumberOfIdentifiers(); ++i ) {
349 sorted_ids.add( matrix.getIdentifier( i ) );
351 for( final String id : sorted_ids ) {
352 for( int c = 0; c < matrix.getNumberOfCharacters(); ++c ) {
353 if ( ( get_gains && ( matrix.getState( id, c ) == CharacterStateMatrix.GainLossStates.GAIN ) )
354 || ( !get_gains && ( matrix.getState( id, c ) == CharacterStateMatrix.GainLossStates.LOSS ) ) ) {
355 if ( dc_type == BinaryDomainCombination.DomainCombinationType.DIRECTED_ADJACTANT ) {
356 all_binary_domains_combination_gained.add( AdjactantDirectedBinaryDomainCombination
357 .createInstance( matrix.getCharacter( c ) ) );
359 else if ( dc_type == BinaryDomainCombination.DomainCombinationType.DIRECTED ) {
360 all_binary_domains_combination_gained.add( DirectedBinaryDomainCombination
361 .createInstance( matrix.getCharacter( c ) ) );
364 all_binary_domains_combination_gained.add( BasicBinaryDomainCombination.createInstance( matrix
365 .getCharacter( c ) ) );
372 private static File createBaseDirForPerNodeDomainFiles( final String base_dir,
373 final boolean domain_combinations,
374 final CharacterStateMatrix.GainLossStates state,
375 final String outfile ) {
376 File per_node_go_mapped_domain_gain_loss_files_base_dir = new File( new File( outfile ).getParent()
377 + ForesterUtil.FILE_SEPARATOR + base_dir );
378 if ( !per_node_go_mapped_domain_gain_loss_files_base_dir.exists() ) {
379 per_node_go_mapped_domain_gain_loss_files_base_dir.mkdir();
381 if ( domain_combinations ) {
382 per_node_go_mapped_domain_gain_loss_files_base_dir = new File( per_node_go_mapped_domain_gain_loss_files_base_dir
383 + ForesterUtil.FILE_SEPARATOR + "DC" );
386 per_node_go_mapped_domain_gain_loss_files_base_dir = new File( per_node_go_mapped_domain_gain_loss_files_base_dir
387 + ForesterUtil.FILE_SEPARATOR + "DOMAINS" );
389 if ( !per_node_go_mapped_domain_gain_loss_files_base_dir.exists() ) {
390 per_node_go_mapped_domain_gain_loss_files_base_dir.mkdir();
392 if ( state == GainLossStates.GAIN ) {
393 per_node_go_mapped_domain_gain_loss_files_base_dir = new File( per_node_go_mapped_domain_gain_loss_files_base_dir
394 + ForesterUtil.FILE_SEPARATOR + "GAINS" );
396 else if ( state == GainLossStates.LOSS ) {
397 per_node_go_mapped_domain_gain_loss_files_base_dir = new File( per_node_go_mapped_domain_gain_loss_files_base_dir
398 + ForesterUtil.FILE_SEPARATOR + "LOSSES" );
401 per_node_go_mapped_domain_gain_loss_files_base_dir = new File( per_node_go_mapped_domain_gain_loss_files_base_dir
402 + ForesterUtil.FILE_SEPARATOR + "PRESENT" );
404 if ( !per_node_go_mapped_domain_gain_loss_files_base_dir.exists() ) {
405 per_node_go_mapped_domain_gain_loss_files_base_dir.mkdir();
407 return per_node_go_mapped_domain_gain_loss_files_base_dir;
410 public static Map<DomainId, List<GoId>> createDomainIdToGoIdMap( final List<PfamToGoMapping> pfam_to_go_mappings ) {
411 final Map<DomainId, List<GoId>> domain_id_to_go_ids_map = new HashMap<DomainId, List<GoId>>( pfam_to_go_mappings
413 for( final PfamToGoMapping pfam_to_go : pfam_to_go_mappings ) {
414 if ( !domain_id_to_go_ids_map.containsKey( pfam_to_go.getKey() ) ) {
415 domain_id_to_go_ids_map.put( pfam_to_go.getKey(), new ArrayList<GoId>() );
417 domain_id_to_go_ids_map.get( pfam_to_go.getKey() ).add( pfam_to_go.getValue() );
419 return domain_id_to_go_ids_map;
422 public static Map<DomainId, Set<String>> createDomainIdToSecondaryFeaturesMap( final File secondary_features_map_file )
424 final BasicTable<String> primary_table = BasicTableParser.parse( secondary_features_map_file, "\t" );
425 final Map<DomainId, Set<String>> map = new TreeMap<DomainId, Set<String>>();
426 for( int r = 0; r < primary_table.getNumberOfRows(); ++r ) {
427 final DomainId domain_id = new DomainId( primary_table.getValue( 0, r ) );
428 if ( !map.containsKey( domain_id ) ) {
429 map.put( domain_id, new HashSet<String>() );
431 map.get( domain_id ).add( primary_table.getValue( 1, r ) );
436 public static Phylogeny createNjTreeBasedOnMatrixToFile( final File nj_tree_outfile, final DistanceMatrix distance ) {
437 checkForOutputFileWriteability( nj_tree_outfile );
438 final NeighborJoining nj = NeighborJoining.createInstance();
439 final Phylogeny phylogeny = nj.execute( distance );
440 phylogeny.setName( nj_tree_outfile.getName() );
441 writePhylogenyToFile( phylogeny, nj_tree_outfile.toString() );
445 private static SortedSet<BinaryDomainCombination> createSetOfAllBinaryDomainCombinationsPerGenome( final GenomeWideCombinableDomains gwcd ) {
446 final SortedMap<DomainId, CombinableDomains> cds = gwcd.getAllCombinableDomainsIds();
447 final SortedSet<BinaryDomainCombination> binary_combinations = new TreeSet<BinaryDomainCombination>();
448 for( final DomainId domain_id : cds.keySet() ) {
449 final CombinableDomains cd = cds.get( domain_id );
450 binary_combinations.addAll( cd.toBinaryDomainCombinations() );
452 return binary_combinations;
455 public static void decoratePrintableDomainSimilarities( final SortedSet<DomainSimilarity> domain_similarities,
456 final Detailedness detailedness,
457 final GoAnnotationOutput go_annotation_output,
458 final Map<GoId, GoTerm> go_id_to_term_map,
459 final GoNameSpace go_namespace_limit ) {
460 if ( ( go_namespace_limit != null ) && ( ( go_id_to_term_map == null ) || go_id_to_term_map.isEmpty() ) ) {
461 throw new IllegalArgumentException( "attempt to use a GO namespace limit without a GO id to term map" );
463 for( final DomainSimilarity domain_similarity : domain_similarities ) {
464 if ( domain_similarity instanceof PrintableDomainSimilarity ) {
465 final PrintableDomainSimilarity printable_domain_similarity = ( PrintableDomainSimilarity ) domain_similarity;
466 printable_domain_similarity.setDetailedness( detailedness );
467 printable_domain_similarity.setGoAnnotationOutput( go_annotation_output );
468 printable_domain_similarity.setGoIdToTermMap( go_id_to_term_map );
469 printable_domain_similarity.setGoNamespaceLimit( go_namespace_limit );
474 public static void executeDomainLengthAnalysis( final String[][] input_file_properties,
475 final int number_of_genomes,
476 final DomainLengthsTable domain_lengths_table,
477 final File outfile ) throws IOException {
478 final DecimalFormat df = new DecimalFormat( "#.00" );
479 checkForOutputFileWriteability( outfile );
480 final BufferedWriter out = new BufferedWriter( new FileWriter( outfile ) );
481 out.write( "MEAN BASED STATISTICS PER SPECIES" );
482 out.write( ForesterUtil.LINE_SEPARATOR );
483 out.write( domain_lengths_table.createMeanBasedStatisticsPerSpeciesTable().toString() );
484 out.write( ForesterUtil.LINE_SEPARATOR );
485 out.write( ForesterUtil.LINE_SEPARATOR );
486 final List<DomainLengths> domain_lengths_list = domain_lengths_table.getDomainLengthsList();
487 out.write( "OUTLIER SPECIES PER DOMAIN (Z>=1.5)" );
488 out.write( ForesterUtil.LINE_SEPARATOR );
489 for( final DomainLengths domain_lengths : domain_lengths_list ) {
490 final List<Species> species_list = domain_lengths.getMeanBasedOutlierSpecies( 1.5 );
491 if ( species_list.size() > 0 ) {
492 out.write( domain_lengths.getDomainId() + "\t" );
493 for( final Species species : species_list ) {
494 out.write( species + "\t" );
496 out.write( ForesterUtil.LINE_SEPARATOR );
497 // DescriptiveStatistics stats_for_domain = domain_lengths
498 // .calculateMeanBasedStatistics();
499 //AsciiHistogram histo = new AsciiHistogram( stats_for_domain );
500 //System.out.println( histo.toStringBuffer( 40, '=', 60, 4 ).toString() );
503 out.write( ForesterUtil.LINE_SEPARATOR );
504 out.write( ForesterUtil.LINE_SEPARATOR );
505 out.write( "OUTLIER SPECIES (Z 1.0)" );
506 out.write( ForesterUtil.LINE_SEPARATOR );
507 final DescriptiveStatistics stats_for_all_species = domain_lengths_table
508 .calculateMeanBasedStatisticsForAllSpecies();
509 out.write( stats_for_all_species.asSummary() );
510 out.write( ForesterUtil.LINE_SEPARATOR );
511 final AsciiHistogram histo = new AsciiHistogram( stats_for_all_species );
512 out.write( histo.toStringBuffer( 40, '=', 60, 4 ).toString() );
513 out.write( ForesterUtil.LINE_SEPARATOR );
514 final double population_sd = stats_for_all_species.sampleStandardDeviation();
515 final double population_mean = stats_for_all_species.arithmeticMean();
516 for( final Species species : domain_lengths_table.getSpecies() ) {
517 final double x = domain_lengths_table.calculateMeanBasedStatisticsForSpecies( species ).arithmeticMean();
518 final double z = ( x - population_mean ) / population_sd;
519 out.write( species + "\t" + z );
520 out.write( ForesterUtil.LINE_SEPARATOR );
522 out.write( ForesterUtil.LINE_SEPARATOR );
523 for( final Species species : domain_lengths_table.getSpecies() ) {
524 final DescriptiveStatistics stats_for_species = domain_lengths_table
525 .calculateMeanBasedStatisticsForSpecies( species );
526 final double x = stats_for_species.arithmeticMean();
527 final double z = ( x - population_mean ) / population_sd;
528 if ( ( z <= -1.0 ) || ( z >= 1.0 ) ) {
529 out.write( species + "\t" + df.format( z ) + "\t" + stats_for_species.asSummary() );
530 out.write( ForesterUtil.LINE_SEPARATOR );
534 // final List<HistogramData> histogram_datas = new ArrayList<HistogramData>();
535 // for( int i = 0; i < number_of_genomes; ++i ) {
536 // final Species species = new BasicSpecies( input_file_properties[ i ][ 0 ] );
538 // .add( new HistogramData( species.toString(), domain_lengths_table
539 // .calculateMeanBasedStatisticsForSpecies( species )
540 // .getDataAsDoubleArray(), 5, 600, null, 60 ) );
542 // final HistogramsFrame hf = new HistogramsFrame( histogram_datas );
543 // hf.setVisible( true );
549 * @param all_binary_domains_combination_lost_fitch
550 * @param consider_directedness_and_adjacency_for_bin_combinations
551 * @param all_binary_domains_combination_gained if null ignored, otherwise this is to list all binary domain combinations
552 * which were gained under unweighted (Fitch) parsimony.
554 public static void executeParsimonyAnalysis( final long random_number_seed_for_fitch_parsimony,
555 final boolean radomize_fitch_parsimony,
556 final String outfile_name,
557 final DomainParsimonyCalculator domain_parsimony,
558 final Phylogeny phylogeny,
559 final Map<DomainId, List<GoId>> domain_id_to_go_ids_map,
560 final Map<GoId, GoTerm> go_id_to_term_map,
561 final GoNameSpace go_namespace_limit,
562 final String parameters_str,
563 final Map<DomainId, Set<String>>[] domain_id_to_secondary_features_maps,
564 final SortedSet<DomainId> positive_filter,
565 final boolean output_binary_domain_combinations_for_graphs,
566 final List<BinaryDomainCombination> all_binary_domains_combination_gained_fitch,
567 final List<BinaryDomainCombination> all_binary_domains_combination_lost_fitch,
568 final BinaryDomainCombination.DomainCombinationType dc_type ) {
569 final String sep = ForesterUtil.LINE_SEPARATOR + "###################" + ForesterUtil.LINE_SEPARATOR;
570 final String date_time = ForesterUtil.getCurrentDateTime();
571 final SortedSet<String> all_pfams_encountered = new TreeSet<String>();
572 final SortedSet<String> all_pfams_gained_as_domains = new TreeSet<String>();
573 final SortedSet<String> all_pfams_lost_as_domains = new TreeSet<String>();
574 final SortedSet<String> all_pfams_gained_as_dom_combinations = new TreeSet<String>();
575 final SortedSet<String> all_pfams_lost_as_dom_combinations = new TreeSet<String>();
576 writeToNexus( outfile_name, domain_parsimony, phylogeny );
579 Phylogeny local_phylogeny_l = phylogeny.copy();
580 if ( ( positive_filter != null ) && ( positive_filter.size() > 0 ) ) {
581 domain_parsimony.executeDolloParsimonyOnDomainPresence( positive_filter );
584 domain_parsimony.executeDolloParsimonyOnDomainPresence();
586 SurfacingUtil.writeMatrixToFile( domain_parsimony.getGainLossMatrix(), outfile_name
587 + surfacing.PARSIMONY_OUTPUT_GL_SUFFIX_DOLLO_DOMAINS, Format.FORESTER );
588 SurfacingUtil.writeMatrixToFile( domain_parsimony.getGainLossCountsMatrix(), outfile_name
589 + surfacing.PARSIMONY_OUTPUT_GL_COUNTS_SUFFIX_DOLLO_DOMAINS, Format.FORESTER );
590 SurfacingUtil.writeBinaryStatesMatrixAsListToFile( domain_parsimony.getGainLossMatrix(),
591 CharacterStateMatrix.GainLossStates.GAIN,
592 outfile_name + surfacing.PARSIMONY_OUTPUT_DOLLO_GAINS_D,
594 ForesterUtil.LINE_SEPARATOR,
596 SurfacingUtil.writeBinaryStatesMatrixAsListToFile( domain_parsimony.getGainLossMatrix(),
597 CharacterStateMatrix.GainLossStates.LOSS,
598 outfile_name + surfacing.PARSIMONY_OUTPUT_DOLLO_LOSSES_D,
600 ForesterUtil.LINE_SEPARATOR,
602 SurfacingUtil.writeBinaryStatesMatrixAsListToFile( domain_parsimony.getGainLossMatrix(), null, outfile_name
603 + surfacing.PARSIMONY_OUTPUT_DOLLO_PRESENT_D, sep, ForesterUtil.LINE_SEPARATOR, null );
605 writeBinaryStatesMatrixToList( domain_id_to_go_ids_map,
609 domain_parsimony.getGainLossMatrix(),
610 CharacterStateMatrix.GainLossStates.GAIN,
611 outfile_name + surfacing.PARSIMONY_OUTPUT_DOLLO_GAINS_HTML_D,
613 ForesterUtil.LINE_SEPARATOR,
614 "Dollo Parsimony | Gains | Domains",
616 domain_id_to_secondary_features_maps,
617 all_pfams_encountered,
618 all_pfams_gained_as_domains,
620 writeBinaryStatesMatrixToList( domain_id_to_go_ids_map,
624 domain_parsimony.getGainLossMatrix(),
625 CharacterStateMatrix.GainLossStates.LOSS,
626 outfile_name + surfacing.PARSIMONY_OUTPUT_DOLLO_LOSSES_HTML_D,
628 ForesterUtil.LINE_SEPARATOR,
629 "Dollo Parsimony | Losses | Domains",
631 domain_id_to_secondary_features_maps,
632 all_pfams_encountered,
633 all_pfams_lost_as_domains,
635 writeBinaryStatesMatrixToList( domain_id_to_go_ids_map,
639 domain_parsimony.getGainLossMatrix(),
641 outfile_name + surfacing.PARSIMONY_OUTPUT_DOLLO_PRESENT_HTML_D,
643 ForesterUtil.LINE_SEPARATOR,
644 "Dollo Parsimony | Present | Domains",
646 domain_id_to_secondary_features_maps,
647 all_pfams_encountered,
649 "_dollo_present_d" );
650 preparePhylogeny( local_phylogeny_l,
653 "Dollo parsimony on domain presence/absence",
654 "dollo_on_domains_" + outfile_name,
656 SurfacingUtil.writePhylogenyToFile( local_phylogeny_l, outfile_name
657 + surfacing.DOMAINS_PARSIMONY_TREE_OUTPUT_SUFFIX_DOLLO );
659 writeAllDomainsChangedOnAllSubtrees( local_phylogeny_l, true, outfile_name, "_dollo_all_gains_d" );
660 writeAllDomainsChangedOnAllSubtrees( local_phylogeny_l, false, outfile_name, "_dollo_all_losses_d" );
662 catch ( final IOException e ) {
664 ForesterUtil.fatalError( surfacing.PRG_NAME, e.getLocalizedMessage() );
666 if ( domain_parsimony.calculateNumberOfBinaryDomainCombination() > 0 ) {
667 // FITCH DOMAIN COMBINATIONS
668 // -------------------------
669 local_phylogeny_l = phylogeny.copy();
670 String randomization = "no";
671 if ( radomize_fitch_parsimony ) {
672 domain_parsimony.executeFitchParsimonyOnBinaryDomainCombintion( random_number_seed_for_fitch_parsimony );
673 randomization = "yes, seed = " + random_number_seed_for_fitch_parsimony;
676 domain_parsimony.executeFitchParsimonyOnBinaryDomainCombintion( true );
678 SurfacingUtil.writeMatrixToFile( domain_parsimony.getGainLossMatrix(), outfile_name
679 + surfacing.PARSIMONY_OUTPUT_GL_SUFFIX_FITCH_BINARY_COMBINATIONS, Format.FORESTER );
680 SurfacingUtil.writeMatrixToFile( domain_parsimony.getGainLossCountsMatrix(), outfile_name
681 + surfacing.PARSIMONY_OUTPUT_GL_COUNTS_SUFFIX_FITCH_BINARY_COMBINATIONS, Format.FORESTER );
683 .writeBinaryStatesMatrixAsListToFile( domain_parsimony.getGainLossMatrix(),
684 CharacterStateMatrix.GainLossStates.GAIN,
685 outfile_name + surfacing.PARSIMONY_OUTPUT_FITCH_GAINS_BC,
687 ForesterUtil.LINE_SEPARATOR,
689 SurfacingUtil.writeBinaryStatesMatrixAsListToFile( domain_parsimony.getGainLossMatrix(),
690 CharacterStateMatrix.GainLossStates.LOSS,
692 + surfacing.PARSIMONY_OUTPUT_FITCH_LOSSES_BC,
694 ForesterUtil.LINE_SEPARATOR,
696 SurfacingUtil.writeBinaryStatesMatrixAsListToFile( domain_parsimony.getGainLossMatrix(), null, outfile_name
697 + surfacing.PARSIMONY_OUTPUT_FITCH_PRESENT_BC, sep, ForesterUtil.LINE_SEPARATOR, null );
698 if ( all_binary_domains_combination_gained_fitch != null ) {
699 collectChangedDomainCombinationsFromBinaryStatesMatrixAsListToFile( domain_parsimony.getGainLossMatrix(),
701 all_binary_domains_combination_gained_fitch,
704 if ( all_binary_domains_combination_lost_fitch != null ) {
705 collectChangedDomainCombinationsFromBinaryStatesMatrixAsListToFile( domain_parsimony.getGainLossMatrix(),
707 all_binary_domains_combination_lost_fitch,
710 if ( output_binary_domain_combinations_for_graphs ) {
712 .writeBinaryStatesMatrixAsListToFileForBinaryCombinationsForGraphAnalysis( domain_parsimony
713 .getGainLossMatrix(),
716 + surfacing.PARSIMONY_OUTPUT_FITCH_PRESENT_BC_OUTPUTFILE_SUFFIX_FOR_GRAPH_ANALYSIS,
718 ForesterUtil.LINE_SEPARATOR,
719 BinaryDomainCombination.OutputFormat.DOT );
722 writeBinaryStatesMatrixToList( domain_id_to_go_ids_map,
726 domain_parsimony.getGainLossMatrix(),
727 CharacterStateMatrix.GainLossStates.GAIN,
728 outfile_name + surfacing.PARSIMONY_OUTPUT_FITCH_GAINS_HTML_BC,
730 ForesterUtil.LINE_SEPARATOR,
731 "Fitch Parsimony | Gains | Domain Combinations",
734 all_pfams_encountered,
735 all_pfams_gained_as_dom_combinations,
737 writeBinaryStatesMatrixToList( domain_id_to_go_ids_map,
741 domain_parsimony.getGainLossMatrix(),
742 CharacterStateMatrix.GainLossStates.LOSS,
743 outfile_name + surfacing.PARSIMONY_OUTPUT_FITCH_LOSSES_HTML_BC,
745 ForesterUtil.LINE_SEPARATOR,
746 "Fitch Parsimony | Losses | Domain Combinations",
749 all_pfams_encountered,
750 all_pfams_lost_as_dom_combinations,
751 "_fitch_losses_dc" );
752 writeBinaryStatesMatrixToList( domain_id_to_go_ids_map,
756 domain_parsimony.getGainLossMatrix(),
758 outfile_name + surfacing.PARSIMONY_OUTPUT_FITCH_PRESENT_HTML_BC,
760 ForesterUtil.LINE_SEPARATOR,
761 "Fitch Parsimony | Present | Domain Combinations",
764 all_pfams_encountered,
766 "_fitch_present_dc" );
767 writeAllEncounteredPfamsToFile( domain_id_to_go_ids_map,
770 all_pfams_encountered );
771 writePfamsToFile( outfile_name + surfacing.ALL_PFAMS_GAINED_AS_DOMAINS_SUFFIX, all_pfams_gained_as_domains );
772 writePfamsToFile( outfile_name + surfacing.ALL_PFAMS_LOST_AS_DOMAINS_SUFFIX, all_pfams_lost_as_domains );
773 writePfamsToFile( outfile_name + surfacing.ALL_PFAMS_GAINED_AS_DC_SUFFIX,
774 all_pfams_gained_as_dom_combinations );
775 writePfamsToFile( outfile_name + surfacing.ALL_PFAMS_LOST_AS_DC_SUFFIX, all_pfams_lost_as_dom_combinations );
776 preparePhylogeny( local_phylogeny_l,
779 "Fitch parsimony on binary domain combination presence/absence randomization: "
781 "fitch_on_binary_domain_combinations_" + outfile_name,
783 SurfacingUtil.writePhylogenyToFile( local_phylogeny_l, outfile_name
784 + surfacing.BINARY_DOMAIN_COMBINATIONS_PARSIMONY_TREE_OUTPUT_SUFFIX_FITCH );
785 calculateIndependentDomainCombinationGains( local_phylogeny_l, outfile_name
786 + surfacing.INDEPENDENT_DC_GAINS_FITCH_PARS_COUNTS_OUTPUT_SUFFIX, outfile_name
787 + surfacing.INDEPENDENT_DC_GAINS_FITCH_PARS_DC_OUTPUT_SUFFIX, outfile_name
788 + surfacing.INDEPENDENT_DC_GAINS_FITCH_PARS_DC_FOR_GO_MAPPING_OUTPUT_SUFFIX, outfile_name
789 + surfacing.INDEPENDENT_DC_GAINS_FITCH_PARS_DC_FOR_GO_MAPPING_OUTPUT_UNIQUE_SUFFIX, outfile_name
790 + "_indep_dc_gains_fitch_lca_ranks.txt", outfile_name + "_indep_dc_gains_fitch_lca_taxonomies.txt" );
794 public static void executeParsimonyAnalysisForSecondaryFeatures( final String outfile_name,
795 final DomainParsimonyCalculator secondary_features_parsimony,
796 final Phylogeny phylogeny,
797 final String parameters_str,
798 final Map<Species, MappingResults> mapping_results_map ) {
799 final String sep = ForesterUtil.LINE_SEPARATOR + "###################" + ForesterUtil.LINE_SEPARATOR;
800 final String date_time = ForesterUtil.getCurrentDateTime();
801 System.out.println();
802 writeToNexus( outfile_name + surfacing.NEXUS_SECONDARY_FEATURES,
803 secondary_features_parsimony.createMatrixOfSecondaryFeaturePresenceOrAbsence( null ),
805 Phylogeny local_phylogeny_copy = phylogeny.copy();
806 secondary_features_parsimony.executeDolloParsimonyOnSecondaryFeatures( mapping_results_map );
807 SurfacingUtil.writeMatrixToFile( secondary_features_parsimony.getGainLossMatrix(), outfile_name
808 + surfacing.PARSIMONY_OUTPUT_GL_SUFFIX_DOLLO_SECONDARY_FEATURES, Format.FORESTER );
809 SurfacingUtil.writeMatrixToFile( secondary_features_parsimony.getGainLossCountsMatrix(), outfile_name
810 + surfacing.PARSIMONY_OUTPUT_GL_COUNTS_SUFFIX_DOLLO_SECONDARY_FEATURES, Format.FORESTER );
812 .writeBinaryStatesMatrixAsListToFile( secondary_features_parsimony.getGainLossMatrix(),
813 CharacterStateMatrix.GainLossStates.GAIN,
815 + surfacing.PARSIMONY_OUTPUT_DOLLO_GAINS_SECONDARY_FEATURES,
817 ForesterUtil.LINE_SEPARATOR,
820 .writeBinaryStatesMatrixAsListToFile( secondary_features_parsimony.getGainLossMatrix(),
821 CharacterStateMatrix.GainLossStates.LOSS,
823 + surfacing.PARSIMONY_OUTPUT_DOLLO_LOSSES_SECONDARY_FEATURES,
825 ForesterUtil.LINE_SEPARATOR,
828 .writeBinaryStatesMatrixAsListToFile( secondary_features_parsimony.getGainLossMatrix(),
831 + surfacing.PARSIMONY_OUTPUT_DOLLO_PRESENT_SECONDARY_FEATURES,
833 ForesterUtil.LINE_SEPARATOR,
835 preparePhylogeny( local_phylogeny_copy,
836 secondary_features_parsimony,
838 "Dollo parsimony on secondary feature presence/absence",
839 "dollo_on_secondary_features_" + outfile_name,
841 SurfacingUtil.writePhylogenyToFile( local_phylogeny_copy, outfile_name
842 + surfacing.SECONDARY_FEATURES_PARSIMONY_TREE_OUTPUT_SUFFIX_DOLLO );
845 // FITCH DOMAIN COMBINATIONS
846 // -------------------------
847 local_phylogeny_copy = phylogeny.copy();
848 String randomization = "no";
850 secondary_features_parsimony.executeFitchParsimonyOnBinaryDomainCombintion( true );
855 preparePhylogeny( local_phylogeny_copy,
856 secondary_features_parsimony,
858 "Fitch parsimony on secondary binary domain combination presence/absence randomization: "
860 "fitch_on_binary_domain_combinations_" + outfile_name,
862 SurfacingUtil.writePhylogenyToFile( local_phylogeny_copy, outfile_name
863 + surfacing.BINARY_DOMAIN_COMBINATIONS_PARSIMONY_TREE_OUTPUT_SUFFIX_FITCH_MAPPED );
864 calculateIndependentDomainCombinationGains( local_phylogeny_copy, outfile_name
865 + surfacing.INDEPENDENT_DC_GAINS_FITCH_PARS_COUNTS_MAPPED_OUTPUT_SUFFIX, outfile_name
866 + surfacing.INDEPENDENT_DC_GAINS_FITCH_PARS_DC_MAPPED_OUTPUT_SUFFIX, outfile_name
867 + surfacing.INDEPENDENT_DC_GAINS_FITCH_PARS_DC_FOR_GO_MAPPING_MAPPED_OUTPUT_SUFFIX, outfile_name
868 + surfacing.INDEPENDENT_DC_GAINS_FITCH_PARS_DC_FOR_GO_MAPPING_MAPPED_OUTPUT_UNIQUE_SUFFIX, outfile_name
869 + "_MAPPED_indep_dc_gains_fitch_lca_ranks.txt", outfile_name + "_MAPPED_indep_dc_gains_fitch_lca_taxonomies.txt" );
874 public static void extractProteinNames( final List<Protein> proteins,
875 final List<DomainId> query_domain_ids_nc_order,
877 final String separator,
878 final String limit_to_species ) throws IOException {
879 for( final Protein protein : proteins ) {
880 if ( ForesterUtil.isEmpty( limit_to_species )
881 || protein.getSpecies().getSpeciesId().equalsIgnoreCase( limit_to_species ) ) {
882 if ( protein.contains( query_domain_ids_nc_order, true ) ) {
883 out.write( protein.getSpecies().getSpeciesId() );
884 out.write( separator );
885 out.write( protein.getProteinId().getId() );
886 out.write( separator );
888 final Set<DomainId> visited_domain_ids = new HashSet<DomainId>();
889 boolean first = true;
890 for( final Domain domain : protein.getProteinDomains() ) {
891 if ( !visited_domain_ids.contains( domain.getDomainId() ) ) {
892 visited_domain_ids.add( domain.getDomainId() );
899 out.write( domain.getDomainId().getId() );
901 out.write( "" + domain.getTotalCount() );
906 out.write( separator );
907 if ( !( ForesterUtil.isEmpty( protein.getDescription() ) || protein.getDescription()
908 .equals( SurfacingConstants.NONE ) ) ) {
909 out.write( protein.getDescription() );
911 out.write( separator );
912 if ( !( ForesterUtil.isEmpty( protein.getAccession() ) || protein.getAccession()
913 .equals( SurfacingConstants.NONE ) ) ) {
914 out.write( protein.getAccession() );
916 out.write( SurfacingConstants.NL );
923 public static void extractProteinNames( final SortedMap<Species, List<Protein>> protein_lists_per_species,
924 final DomainId domain_id,
926 final String separator,
927 final String limit_to_species ) throws IOException {
928 for( final Species species : protein_lists_per_species.keySet() ) {
929 for( final Protein protein : protein_lists_per_species.get( species ) ) {
930 if ( ForesterUtil.isEmpty( limit_to_species )
931 || protein.getSpecies().getSpeciesId().equalsIgnoreCase( limit_to_species ) ) {
932 final List<Domain> domains = protein.getProteinDomains( domain_id );
933 if ( domains.size() > 0 ) {
934 final DescriptiveStatistics stats = new BasicDescriptiveStatistics();
935 for( final Domain domain : domains ) {
936 stats.addValue( domain.getPerSequenceEvalue() );
938 out.write( protein.getSpecies().getSpeciesId() );
939 out.write( separator );
940 out.write( protein.getProteinId().getId() );
941 out.write( separator );
942 out.write( "[" + FORMATTER.format( stats.median() ) + "]" );
943 out.write( separator );
944 if ( !( ForesterUtil.isEmpty( protein.getDescription() ) || protein.getDescription()
945 .equals( SurfacingConstants.NONE ) ) ) {
946 out.write( protein.getDescription() );
948 out.write( separator );
949 if ( !( ForesterUtil.isEmpty( protein.getAccession() ) || protein.getAccession()
950 .equals( SurfacingConstants.NONE ) ) ) {
951 out.write( protein.getAccession() );
953 out.write( SurfacingConstants.NL );
961 public static SortedSet<DomainId> getAllDomainIds( final List<GenomeWideCombinableDomains> gwcd_list ) {
962 final SortedSet<DomainId> all_domains_ids = new TreeSet<DomainId>();
963 for( final GenomeWideCombinableDomains gwcd : gwcd_list ) {
964 final Set<DomainId> all_domains = gwcd.getAllDomainIds();
965 // for( final Domain domain : all_domains ) {
966 all_domains_ids.addAll( all_domains );
969 return all_domains_ids;
972 public static SortedMap<String, Integer> getDomainCounts( final List<Protein> protein_domain_collections ) {
973 final SortedMap<String, Integer> map = new TreeMap<String, Integer>();
974 for( final Protein protein_domain_collection : protein_domain_collections ) {
975 for( final Object name : protein_domain_collection.getProteinDomains() ) {
976 final BasicDomain protein_domain = ( BasicDomain ) name;
977 final String id = protein_domain.getDomainId().getId();
978 if ( map.containsKey( id ) ) {
979 map.put( id, map.get( id ) + 1 );
989 public static int getNumberOfNodesLackingName( final Phylogeny p, final StringBuilder names ) {
990 final PhylogenyNodeIterator it = p.iteratorPostorder();
992 while ( it.hasNext() ) {
993 final PhylogenyNode n = it.next();
994 if ( ForesterUtil.isEmpty( n.getName() )
995 && ( !n.getNodeData().isHasTaxonomy() || ForesterUtil.isEmpty( n.getNodeData().getTaxonomy()
996 .getScientificName() ) )
997 && ( !n.getNodeData().isHasTaxonomy() || ForesterUtil.isEmpty( n.getNodeData().getTaxonomy()
998 .getCommonName() ) ) ) {
999 if ( n.getParent() != null ) {
1000 names.append( " " );
1001 names.append( n.getParent().getName() );
1003 final List l = n.getAllExternalDescendants();
1004 for( final Object object : l ) {
1005 System.out.println( l.toString() );
1014 * Returns true is Domain domain falls in an uninterrupted stretch of
1015 * covered positions.
1018 * @param covered_positions
1021 public static boolean isEngulfed( final Domain domain, final List<Boolean> covered_positions ) {
1022 for( int i = domain.getFrom(); i <= domain.getTo(); ++i ) {
1023 if ( ( i >= covered_positions.size() ) || ( covered_positions.get( i ) != true ) ) {
1030 public static void preparePhylogeny( final Phylogeny p,
1031 final DomainParsimonyCalculator domain_parsimony,
1032 final String date_time,
1033 final String method,
1035 final String parameters_str ) {
1036 domain_parsimony.decoratePhylogenyWithDomains( p );
1037 final StringBuilder desc = new StringBuilder();
1038 desc.append( "[Method: " + method + "] [Date: " + date_time + "] " );
1039 desc.append( "[Cost: " + domain_parsimony.getCost() + "] " );
1040 desc.append( "[Gains: " + domain_parsimony.getTotalGains() + "] " );
1041 desc.append( "[Losses: " + domain_parsimony.getTotalLosses() + "] " );
1042 desc.append( "[Unchanged: " + domain_parsimony.getTotalUnchanged() + "] " );
1043 desc.append( "[Parameters: " + parameters_str + "]" );
1045 p.setDescription( desc.toString() );
1046 p.setConfidence( new Confidence( domain_parsimony.getCost(), "parsimony" ) );
1047 p.setRerootable( false );
1048 p.setRooted( true );
1052 * species | protein id | n-terminal domain | c-terminal domain | n-terminal domain per domain E-value | c-terminal domain per domain E-value
1056 static public StringBuffer proteinToDomainCombinations( final Protein protein,
1057 final String protein_id,
1058 final String separator ) {
1059 final StringBuffer sb = new StringBuffer();
1060 if ( protein.getSpecies() == null ) {
1061 throw new IllegalArgumentException( "species must not be null" );
1063 if ( ForesterUtil.isEmpty( protein.getSpecies().getSpeciesId() ) ) {
1064 throw new IllegalArgumentException( "species id must not be empty" );
1066 final List<Domain> domains = protein.getProteinDomains();
1067 if ( domains.size() > 1 ) {
1068 final Map<String, Integer> counts = new HashMap<String, Integer>();
1069 for( final Domain domain : domains ) {
1070 final String id = domain.getDomainId().getId();
1071 if ( counts.containsKey( id ) ) {
1072 counts.put( id, counts.get( id ) + 1 );
1075 counts.put( id, 1 );
1078 final Set<String> dcs = new HashSet<String>();
1079 for( int i = 1; i < domains.size(); ++i ) {
1080 for( int j = 0; j < i; ++j ) {
1081 Domain domain_n = domains.get( i );
1082 Domain domain_c = domains.get( j );
1083 if ( domain_n.getFrom() > domain_c.getFrom() ) {
1084 domain_n = domains.get( j );
1085 domain_c = domains.get( i );
1087 final String dc = domain_n.getDomainId().getId() + domain_c.getDomainId().getId();
1088 if ( !dcs.contains( dc ) ) {
1090 sb.append( protein.getSpecies() );
1091 sb.append( separator );
1092 sb.append( protein_id );
1093 sb.append( separator );
1094 sb.append( domain_n.getDomainId().getId() );
1095 sb.append( separator );
1096 sb.append( domain_c.getDomainId().getId() );
1097 sb.append( separator );
1098 sb.append( domain_n.getPerDomainEvalue() );
1099 sb.append( separator );
1100 sb.append( domain_c.getPerDomainEvalue() );
1101 sb.append( separator );
1102 sb.append( counts.get( domain_n.getDomainId().getId() ) );
1103 sb.append( separator );
1104 sb.append( counts.get( domain_c.getDomainId().getId() ) );
1105 sb.append( ForesterUtil.LINE_SEPARATOR );
1110 else if ( domains.size() == 1 ) {
1111 sb.append( protein.getSpecies() );
1112 sb.append( separator );
1113 sb.append( protein_id );
1114 sb.append( separator );
1115 sb.append( domains.get( 0 ).getDomainId().getId() );
1116 sb.append( separator );
1117 sb.append( separator );
1118 sb.append( domains.get( 0 ).getPerDomainEvalue() );
1119 sb.append( separator );
1120 sb.append( separator );
1122 sb.append( separator );
1123 sb.append( ForesterUtil.LINE_SEPARATOR );
1126 sb.append( protein.getSpecies() );
1127 sb.append( separator );
1128 sb.append( protein_id );
1129 sb.append( separator );
1130 sb.append( separator );
1131 sb.append( separator );
1132 sb.append( separator );
1133 sb.append( separator );
1134 sb.append( separator );
1135 sb.append( ForesterUtil.LINE_SEPARATOR );
1142 * Example regarding engulfment: ------------0.1 ----------0.2 --0.3 =>
1143 * domain with 0.3 is ignored
1145 * -----------0.1 ----------0.2 --0.3 => domain with 0.3 is ignored
1148 * ------------0.1 ----------0.3 --0.2 => domains with 0.3 and 0.2 are _not_
1151 * @param max_allowed_overlap
1152 * maximal allowed overlap (inclusive) to be still considered not
1153 * overlapping (zero or negative value to allow any overlap)
1154 * @param remove_engulfed_domains
1155 * to remove domains which are completely engulfed by coverage of
1156 * domains with better support
1160 public static Protein removeOverlappingDomains( final int max_allowed_overlap,
1161 final boolean remove_engulfed_domains,
1162 final Protein protein ) {
1163 final Protein pruned_protein = new BasicProtein( protein.getProteinId().getId(), protein.getSpecies()
1165 final List<Domain> sorted = SurfacingUtil.sortDomainsWithAscendingConfidenceValues( protein );
1166 final List<Boolean> covered_positions = new ArrayList<Boolean>();
1167 for( final Domain domain : sorted ) {
1168 if ( ( ( max_allowed_overlap < 0 ) || ( SurfacingUtil.calculateOverlap( domain, covered_positions ) <= max_allowed_overlap ) )
1169 && ( !remove_engulfed_domains || !isEngulfed( domain, covered_positions ) ) ) {
1170 final int covered_positions_size = covered_positions.size();
1171 for( int i = covered_positions_size; i < domain.getFrom(); ++i ) {
1172 covered_positions.add( false );
1174 final int new_covered_positions_size = covered_positions.size();
1175 for( int i = domain.getFrom(); i <= domain.getTo(); ++i ) {
1176 if ( i < new_covered_positions_size ) {
1177 covered_positions.set( i, true );
1180 covered_positions.add( true );
1183 pruned_protein.addProteinDomain( domain );
1186 return pruned_protein;
1189 public static List<Domain> sortDomainsWithAscendingConfidenceValues( final Protein protein ) {
1190 final List<Domain> domains = new ArrayList<Domain>();
1191 for( final Domain d : protein.getProteinDomains() ) {
1194 Collections.sort( domains, SurfacingUtil.ASCENDING_CONFIDENCE_VALUE_ORDER );
1198 private static List<String> splitDomainCombination( final String dc ) {
1199 final String[] s = dc.split( "=" );
1200 if ( s.length != 2 ) {
1201 ForesterUtil.printErrorMessage( surfacing.PRG_NAME, "Stringyfied domain combination has illegal format: "
1205 final List<String> l = new ArrayList<String>( 2 );
1211 public static void writeAllDomainsChangedOnAllSubtrees( final Phylogeny p,
1212 final boolean get_gains,
1213 final String outdir,
1214 final String suffix_for_filename ) throws IOException {
1215 CharacterStateMatrix.GainLossStates state = CharacterStateMatrix.GainLossStates.GAIN;
1217 state = CharacterStateMatrix.GainLossStates.LOSS;
1219 final File base_dir = createBaseDirForPerNodeDomainFiles( surfacing.BASE_DIRECTORY_PER_SUBTREE_DOMAIN_GAIN_LOSS_FILES,
1223 for( final PhylogenyNodeIterator it = p.iteratorPostorder(); it.hasNext(); ) {
1224 final PhylogenyNode node = it.next();
1225 if ( !node.isExternal() ) {
1226 final SortedSet<String> domains = collectAllDomainsChangedOnSubtree( node, get_gains );
1227 if ( domains.size() > 0 ) {
1228 final Writer writer = ForesterUtil.createBufferedWriter( base_dir + ForesterUtil.FILE_SEPARATOR
1229 + node.getName() + suffix_for_filename );
1230 for( final String domain : domains ) {
1231 writer.write( domain );
1232 writer.write( ForesterUtil.LINE_SEPARATOR );
1240 private static void writeAllEncounteredPfamsToFile( final Map<DomainId, List<GoId>> domain_id_to_go_ids_map,
1241 final Map<GoId, GoTerm> go_id_to_term_map,
1242 final String outfile_name,
1243 final SortedSet<String> all_pfams_encountered ) {
1244 final File all_pfams_encountered_file = new File( outfile_name + surfacing.ALL_PFAMS_ENCOUNTERED_SUFFIX );
1245 final File all_pfams_encountered_with_go_annotation_file = new File( outfile_name
1246 + surfacing.ALL_PFAMS_ENCOUNTERED_WITH_GO_ANNOTATION_SUFFIX );
1247 final File encountered_pfams_summary_file = new File( outfile_name + surfacing.ENCOUNTERED_PFAMS_SUMMARY_SUFFIX );
1248 int biological_process_counter = 0;
1249 int cellular_component_counter = 0;
1250 int molecular_function_counter = 0;
1251 int pfams_with_mappings_counter = 0;
1252 int pfams_without_mappings_counter = 0;
1253 int pfams_without_mappings_to_bp_or_mf_counter = 0;
1254 int pfams_with_mappings_to_bp_or_mf_counter = 0;
1256 final Writer all_pfams_encountered_writer = new BufferedWriter( new FileWriter( all_pfams_encountered_file ) );
1257 final Writer all_pfams_encountered_with_go_annotation_writer = new BufferedWriter( new FileWriter( all_pfams_encountered_with_go_annotation_file ) );
1258 final Writer summary_writer = new BufferedWriter( new FileWriter( encountered_pfams_summary_file ) );
1259 summary_writer.write( "# Pfam to GO mapping summary" );
1260 summary_writer.write( ForesterUtil.LINE_SEPARATOR );
1261 summary_writer.write( "# Actual summary is at the end of this file." );
1262 summary_writer.write( ForesterUtil.LINE_SEPARATOR );
1263 summary_writer.write( "# Encountered Pfams without a GO mapping:" );
1264 summary_writer.write( ForesterUtil.LINE_SEPARATOR );
1265 for( final String pfam : all_pfams_encountered ) {
1266 all_pfams_encountered_writer.write( pfam );
1267 all_pfams_encountered_writer.write( ForesterUtil.LINE_SEPARATOR );
1268 final DomainId domain_id = new DomainId( pfam );
1269 if ( domain_id_to_go_ids_map.containsKey( domain_id ) ) {
1270 ++pfams_with_mappings_counter;
1271 all_pfams_encountered_with_go_annotation_writer.write( pfam );
1272 all_pfams_encountered_with_go_annotation_writer.write( ForesterUtil.LINE_SEPARATOR );
1273 final List<GoId> go_ids = domain_id_to_go_ids_map.get( domain_id );
1274 boolean maps_to_bp = false;
1275 boolean maps_to_cc = false;
1276 boolean maps_to_mf = false;
1277 for( final GoId go_id : go_ids ) {
1278 final GoTerm go_term = go_id_to_term_map.get( go_id );
1279 if ( go_term.getGoNameSpace().isBiologicalProcess() ) {
1282 else if ( go_term.getGoNameSpace().isCellularComponent() ) {
1285 else if ( go_term.getGoNameSpace().isMolecularFunction() ) {
1290 ++biological_process_counter;
1293 ++cellular_component_counter;
1296 ++molecular_function_counter;
1298 if ( maps_to_bp || maps_to_mf ) {
1299 ++pfams_with_mappings_to_bp_or_mf_counter;
1302 ++pfams_without_mappings_to_bp_or_mf_counter;
1306 ++pfams_without_mappings_to_bp_or_mf_counter;
1307 ++pfams_without_mappings_counter;
1308 summary_writer.write( pfam );
1309 summary_writer.write( ForesterUtil.LINE_SEPARATOR );
1312 all_pfams_encountered_writer.close();
1313 all_pfams_encountered_with_go_annotation_writer.close();
1314 ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote all [" + all_pfams_encountered.size()
1315 + "] encountered Pfams to: \"" + all_pfams_encountered_file + "\"" );
1316 ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote all [" + pfams_with_mappings_counter
1317 + "] encountered Pfams with GO mappings to: \"" + all_pfams_encountered_with_go_annotation_file
1319 ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote summary (including all ["
1320 + pfams_without_mappings_counter + "] encountered Pfams without GO mappings) to: \""
1321 + encountered_pfams_summary_file + "\"" );
1322 ForesterUtil.programMessage( surfacing.PRG_NAME, "Sum of Pfams encountered : "
1323 + all_pfams_encountered.size() );
1324 ForesterUtil.programMessage( surfacing.PRG_NAME, "Pfams without a mapping : "
1325 + pfams_without_mappings_counter + " ["
1326 + ( 100 * pfams_without_mappings_counter / all_pfams_encountered.size() ) + "%]" );
1327 ForesterUtil.programMessage( surfacing.PRG_NAME, "Pfams without mapping to proc. or func. : "
1328 + pfams_without_mappings_to_bp_or_mf_counter + " ["
1329 + ( 100 * pfams_without_mappings_to_bp_or_mf_counter / all_pfams_encountered.size() ) + "%]" );
1330 ForesterUtil.programMessage( surfacing.PRG_NAME,
1331 "Pfams with a mapping : " + pfams_with_mappings_counter
1333 + ( 100 * pfams_with_mappings_counter / all_pfams_encountered.size() )
1335 ForesterUtil.programMessage( surfacing.PRG_NAME, "Pfams with a mapping to proc. or func. : "
1336 + pfams_with_mappings_to_bp_or_mf_counter + " ["
1337 + ( 100 * pfams_with_mappings_to_bp_or_mf_counter / all_pfams_encountered.size() ) + "%]" );
1338 ForesterUtil.programMessage( surfacing.PRG_NAME,
1339 "Pfams with mapping to biological process: " + biological_process_counter
1341 + ( 100 * biological_process_counter / all_pfams_encountered.size() )
1343 ForesterUtil.programMessage( surfacing.PRG_NAME,
1344 "Pfams with mapping to molecular function: " + molecular_function_counter
1346 + ( 100 * molecular_function_counter / all_pfams_encountered.size() )
1348 ForesterUtil.programMessage( surfacing.PRG_NAME,
1349 "Pfams with mapping to cellular component: " + cellular_component_counter
1351 + ( 100 * cellular_component_counter / all_pfams_encountered.size() )
1353 summary_writer.write( ForesterUtil.LINE_SEPARATOR );
1354 summary_writer.write( "# Sum of Pfams encountered : " + all_pfams_encountered.size() );
1355 summary_writer.write( ForesterUtil.LINE_SEPARATOR );
1356 summary_writer.write( "# Pfams without a mapping : " + pfams_without_mappings_counter
1357 + " [" + ( 100 * pfams_without_mappings_counter / all_pfams_encountered.size() ) + "%]" );
1358 summary_writer.write( ForesterUtil.LINE_SEPARATOR );
1359 summary_writer.write( "# Pfams without mapping to proc. or func. : "
1360 + pfams_without_mappings_to_bp_or_mf_counter + " ["
1361 + ( 100 * pfams_without_mappings_to_bp_or_mf_counter / all_pfams_encountered.size() ) + "%]" );
1362 summary_writer.write( ForesterUtil.LINE_SEPARATOR );
1363 summary_writer.write( "# Pfams with a mapping : " + pfams_with_mappings_counter + " ["
1364 + ( 100 * pfams_with_mappings_counter / all_pfams_encountered.size() ) + "%]" );
1365 summary_writer.write( ForesterUtil.LINE_SEPARATOR );
1366 summary_writer.write( "# Pfams with a mapping to proc. or func. : "
1367 + pfams_with_mappings_to_bp_or_mf_counter + " ["
1368 + ( 100 * pfams_with_mappings_to_bp_or_mf_counter / all_pfams_encountered.size() ) + "%]" );
1369 summary_writer.write( ForesterUtil.LINE_SEPARATOR );
1370 summary_writer.write( "# Pfams with mapping to biological process: " + biological_process_counter + " ["
1371 + ( 100 * biological_process_counter / all_pfams_encountered.size() ) + "%]" );
1372 summary_writer.write( ForesterUtil.LINE_SEPARATOR );
1373 summary_writer.write( "# Pfams with mapping to molecular function: " + molecular_function_counter + " ["
1374 + ( 100 * molecular_function_counter / all_pfams_encountered.size() ) + "%]" );
1375 summary_writer.write( ForesterUtil.LINE_SEPARATOR );
1376 summary_writer.write( "# Pfams with mapping to cellular component: " + cellular_component_counter + " ["
1377 + ( 100 * cellular_component_counter / all_pfams_encountered.size() ) + "%]" );
1378 summary_writer.write( ForesterUtil.LINE_SEPARATOR );
1379 summary_writer.close();
1381 catch ( final IOException e ) {
1382 ForesterUtil.printWarningMessage( surfacing.PRG_NAME, "Failure to write: " + e );
1386 public static void writeBinaryDomainCombinationsFileForGraphAnalysis( final String[][] input_file_properties,
1387 final File output_dir,
1388 final GenomeWideCombinableDomains gwcd,
1390 final GenomeWideCombinableDomainsSortOrder dc_sort_order ) {
1391 File dc_outfile_dot = new File( input_file_properties[ i ][ 0 ]
1392 + surfacing.DOMAIN_COMBINITONS_OUTPUTFILE_SUFFIX_FOR_GRAPH_ANALYSIS );
1393 if ( output_dir != null ) {
1394 dc_outfile_dot = new File( output_dir + ForesterUtil.FILE_SEPARATOR + dc_outfile_dot );
1396 checkForOutputFileWriteability( dc_outfile_dot );
1397 final SortedSet<BinaryDomainCombination> binary_combinations = createSetOfAllBinaryDomainCombinationsPerGenome( gwcd );
1399 final BufferedWriter out_dot = new BufferedWriter( new FileWriter( dc_outfile_dot ) );
1400 for( final BinaryDomainCombination bdc : binary_combinations ) {
1401 out_dot.write( bdc.toGraphDescribingLanguage( BinaryDomainCombination.OutputFormat.DOT, null, null )
1403 out_dot.write( SurfacingConstants.NL );
1407 catch ( final IOException e ) {
1408 ForesterUtil.fatalError( surfacing.PRG_NAME, e.getMessage() );
1410 ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote binary domain combination for \""
1411 + input_file_properties[ i ][ 0 ] + "\" (" + input_file_properties[ i ][ 1 ] + ", "
1412 + input_file_properties[ i ][ 2 ] + ") to: \"" + dc_outfile_dot + "\"" );
1415 public static void writeBinaryStatesMatrixAsListToFile( final CharacterStateMatrix<CharacterStateMatrix.GainLossStates> matrix,
1416 final CharacterStateMatrix.GainLossStates state,
1417 final String filename,
1418 final String indentifier_characters_separator,
1419 final String character_separator,
1420 final Map<String, String> descriptions ) {
1421 final File outfile = new File( filename );
1422 checkForOutputFileWriteability( outfile );
1423 final SortedSet<String> sorted_ids = new TreeSet<String>();
1424 for( int i = 0; i < matrix.getNumberOfIdentifiers(); ++i ) {
1425 sorted_ids.add( matrix.getIdentifier( i ) );
1428 final BufferedWriter out = new BufferedWriter( new FileWriter( outfile ) );
1429 for( final String id : sorted_ids ) {
1430 out.write( indentifier_characters_separator );
1431 out.write( "#" + id );
1432 out.write( indentifier_characters_separator );
1433 for( int c = 0; c < matrix.getNumberOfCharacters(); ++c ) {
1435 // using null to indicate either UNCHANGED_PRESENT or GAIN.
1436 if ( ( matrix.getState( id, c ) == state )
1437 || ( ( state == null ) && ( ( matrix.getState( id, c ) == CharacterStateMatrix.GainLossStates.GAIN ) || ( matrix
1438 .getState( id, c ) == CharacterStateMatrix.GainLossStates.UNCHANGED_PRESENT ) ) ) ) {
1439 out.write( matrix.getCharacter( c ) );
1440 if ( ( descriptions != null ) && !descriptions.isEmpty()
1441 && descriptions.containsKey( matrix.getCharacter( c ) ) ) {
1443 out.write( descriptions.get( matrix.getCharacter( c ) ) );
1445 out.write( character_separator );
1452 catch ( final IOException e ) {
1453 ForesterUtil.fatalError( surfacing.PRG_NAME, e.getMessage() );
1455 ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote characters list: \"" + filename + "\"" );
1458 public static void writeBinaryStatesMatrixAsListToFileForBinaryCombinationsForGraphAnalysis( final CharacterStateMatrix<CharacterStateMatrix.GainLossStates> matrix,
1459 final CharacterStateMatrix.GainLossStates state,
1460 final String filename,
1461 final String indentifier_characters_separator,
1462 final String character_separator,
1463 final BinaryDomainCombination.OutputFormat bc_output_format ) {
1464 final File outfile = new File( filename );
1465 checkForOutputFileWriteability( outfile );
1466 final SortedSet<String> sorted_ids = new TreeSet<String>();
1467 for( int i = 0; i < matrix.getNumberOfIdentifiers(); ++i ) {
1468 sorted_ids.add( matrix.getIdentifier( i ) );
1471 final BufferedWriter out = new BufferedWriter( new FileWriter( outfile ) );
1472 for( final String id : sorted_ids ) {
1473 out.write( indentifier_characters_separator );
1474 out.write( "#" + id );
1475 out.write( indentifier_characters_separator );
1476 for( int c = 0; c < matrix.getNumberOfCharacters(); ++c ) {
1478 // using null to indicate either UNCHANGED_PRESENT or GAIN.
1479 if ( ( matrix.getState( id, c ) == state )
1480 || ( ( state == null ) && ( ( matrix.getState( id, c ) == CharacterStateMatrix.GainLossStates.GAIN ) || ( matrix
1481 .getState( id, c ) == CharacterStateMatrix.GainLossStates.UNCHANGED_PRESENT ) ) ) ) {
1482 BinaryDomainCombination bdc = null;
1484 bdc = BasicBinaryDomainCombination.createInstance( matrix.getCharacter( c ) );
1486 catch ( final Exception e ) {
1487 ForesterUtil.fatalError( surfacing.PRG_NAME, e.getLocalizedMessage() );
1489 out.write( bdc.toGraphDescribingLanguage( bc_output_format, null, null ).toString() );
1490 out.write( character_separator );
1497 catch ( final IOException e ) {
1498 ForesterUtil.fatalError( surfacing.PRG_NAME, e.getMessage() );
1500 ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote characters list: \"" + filename + "\"" );
1503 public static void writeBinaryStatesMatrixToList( final Map<DomainId, List<GoId>> domain_id_to_go_ids_map,
1504 final Map<GoId, GoTerm> go_id_to_term_map,
1505 final GoNameSpace go_namespace_limit,
1506 final boolean domain_combinations,
1507 final CharacterStateMatrix<CharacterStateMatrix.GainLossStates> matrix,
1508 final CharacterStateMatrix.GainLossStates state,
1509 final String filename,
1510 final String indentifier_characters_separator,
1511 final String character_separator,
1512 final String title_for_html,
1513 final String prefix_for_html,
1514 final Map<DomainId, Set<String>>[] domain_id_to_secondary_features_maps,
1515 final SortedSet<String> all_pfams_encountered,
1516 final SortedSet<String> pfams_gained_or_lost,
1517 final String suffix_for_per_node_events_file ) {
1518 if ( ( go_namespace_limit != null ) && ( ( go_id_to_term_map == null ) || ( go_id_to_term_map.size() < 1 ) ) ) {
1519 throw new IllegalArgumentException( "attempt to use GO namespace limit without a GO-id to term map" );
1521 else if ( ( ( domain_id_to_go_ids_map == null ) || ( domain_id_to_go_ids_map.size() < 1 ) ) ) {
1522 throw new IllegalArgumentException( "attempt to output detailed HTML without a Pfam to GO map" );
1524 else if ( ( ( go_id_to_term_map == null ) || ( go_id_to_term_map.size() < 1 ) ) ) {
1525 throw new IllegalArgumentException( "attempt to output detailed HTML without a GO-id to term map" );
1527 final File outfile = new File( filename );
1528 checkForOutputFileWriteability( outfile );
1529 final SortedSet<String> sorted_ids = new TreeSet<String>();
1530 for( int i = 0; i < matrix.getNumberOfIdentifiers(); ++i ) {
1531 sorted_ids.add( matrix.getIdentifier( i ) );
1534 final Writer out = new BufferedWriter( new FileWriter( outfile ) );
1535 final File per_node_go_mapped_domain_gain_loss_files_base_dir = createBaseDirForPerNodeDomainFiles( surfacing.BASE_DIRECTORY_PER_NODE_DOMAIN_GAIN_LOSS_FILES,
1536 domain_combinations,
1539 Writer per_node_go_mapped_domain_gain_loss_outfile_writer = null;
1540 File per_node_go_mapped_domain_gain_loss_outfile = null;
1541 int per_node_counter = 0;
1542 out.write( "<html>" );
1543 out.write( SurfacingConstants.NL );
1544 addHtmlHead( out, title_for_html );
1545 out.write( SurfacingConstants.NL );
1546 out.write( "<body>" );
1547 out.write( SurfacingConstants.NL );
1548 out.write( "<h1>" );
1549 out.write( SurfacingConstants.NL );
1550 out.write( title_for_html );
1551 out.write( SurfacingConstants.NL );
1552 out.write( "</h1>" );
1553 out.write( SurfacingConstants.NL );
1554 out.write( "<table>" );
1555 out.write( SurfacingConstants.NL );
1556 for( final String id : sorted_ids ) {
1557 final Matcher matcher = PATTERN_SP_STYLE_TAXONOMY.matcher( id );
1558 if ( matcher.matches() ) {
1561 out.write( "<tr>" );
1562 out.write( "<td>" );
1563 out.write( "<a href=\"#" + id + "\">" + id + "</a>" );
1564 out.write( "</td>" );
1565 out.write( "</tr>" );
1566 out.write( SurfacingConstants.NL );
1568 out.write( "</table>" );
1569 out.write( SurfacingConstants.NL );
1570 for( final String id : sorted_ids ) {
1571 final Matcher matcher = PATTERN_SP_STYLE_TAXONOMY.matcher( id );
1572 if ( matcher.matches() ) {
1575 out.write( SurfacingConstants.NL );
1576 out.write( "<h2>" );
1577 out.write( "<a name=\"" + id + "\">" + id + "</a>" );
1578 writeTaxonomyLinks( out, id );
1579 out.write( "</h2>" );
1580 out.write( SurfacingConstants.NL );
1581 out.write( "<table>" );
1582 out.write( SurfacingConstants.NL );
1583 out.write( "<tr>" );
1584 out.write( "<td><b>" );
1585 out.write( "Pfam domain(s)" );
1586 out.write( "</b></td><td><b>" );
1587 out.write( "GO term acc" );
1588 out.write( "</b></td><td><b>" );
1589 out.write( "GO term" );
1590 out.write( "</b></td><td><b>" );
1591 out.write( "GO namespace" );
1592 out.write( "</b></td>" );
1593 out.write( "</tr>" );
1594 out.write( SurfacingConstants.NL );
1595 out.write( "</tr>" );
1596 out.write( SurfacingConstants.NL );
1597 per_node_counter = 0;
1598 if ( matrix.getNumberOfCharacters() > 0 ) {
1599 per_node_go_mapped_domain_gain_loss_outfile = new File( per_node_go_mapped_domain_gain_loss_files_base_dir
1600 + ForesterUtil.FILE_SEPARATOR + id + suffix_for_per_node_events_file );
1601 SurfacingUtil.checkForOutputFileWriteability( per_node_go_mapped_domain_gain_loss_outfile );
1602 per_node_go_mapped_domain_gain_loss_outfile_writer = ForesterUtil
1603 .createBufferedWriter( per_node_go_mapped_domain_gain_loss_outfile );
1606 per_node_go_mapped_domain_gain_loss_outfile = null;
1607 per_node_go_mapped_domain_gain_loss_outfile_writer = null;
1609 for( int c = 0; c < matrix.getNumberOfCharacters(); ++c ) {
1611 // using null to indicate either UNCHANGED_PRESENT or GAIN.
1612 if ( ( matrix.getState( id, c ) == state )
1613 || ( ( state == null ) && ( ( matrix.getState( id, c ) == CharacterStateMatrix.GainLossStates.UNCHANGED_PRESENT ) || ( matrix
1614 .getState( id, c ) == CharacterStateMatrix.GainLossStates.GAIN ) ) ) ) {
1615 final String character = matrix.getCharacter( c );
1616 String domain_0 = "";
1617 String domain_1 = "";
1618 if ( character.indexOf( BinaryDomainCombination.SEPARATOR ) > 0 ) {
1619 final String[] s = character.split( BinaryDomainCombination.SEPARATOR );
1620 if ( s.length != 2 ) {
1621 throw new AssertionError( "this should not have happened: unexpected format for domain combination: ["
1622 + character + "]" );
1628 domain_0 = character;
1630 writeDomainData( domain_id_to_go_ids_map,
1637 character_separator,
1638 domain_id_to_secondary_features_maps,
1640 all_pfams_encountered.add( domain_0 );
1641 if ( pfams_gained_or_lost != null ) {
1642 pfams_gained_or_lost.add( domain_0 );
1644 if ( !ForesterUtil.isEmpty( domain_1 ) ) {
1645 all_pfams_encountered.add( domain_1 );
1646 if ( pfams_gained_or_lost != null ) {
1647 pfams_gained_or_lost.add( domain_1 );
1650 if ( per_node_go_mapped_domain_gain_loss_outfile_writer != null ) {
1651 writeDomainsToIndividualFilePerTreeNode( per_node_go_mapped_domain_gain_loss_outfile_writer,
1658 if ( per_node_go_mapped_domain_gain_loss_outfile_writer != null ) {
1659 per_node_go_mapped_domain_gain_loss_outfile_writer.close();
1660 if ( per_node_counter < 1 ) {
1661 per_node_go_mapped_domain_gain_loss_outfile.delete();
1663 per_node_counter = 0;
1665 out.write( "</table>" );
1666 out.write( SurfacingConstants.NL );
1667 out.write( "<hr>" );
1668 out.write( SurfacingConstants.NL );
1669 } // for( final String id : sorted_ids ) {
1670 out.write( "</body>" );
1671 out.write( SurfacingConstants.NL );
1672 out.write( "</html>" );
1673 out.write( SurfacingConstants.NL );
1677 catch ( final IOException e ) {
1678 ForesterUtil.fatalError( surfacing.PRG_NAME, e.getMessage() );
1680 ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote characters detailed HTML list: \"" + filename + "\"" );
1683 public static void writeBinaryStatesMatrixToListORIGIG( final Map<DomainId, List<GoId>> domain_id_to_go_ids_map,
1684 final Map<GoId, GoTerm> go_id_to_term_map,
1685 final GoNameSpace go_namespace_limit,
1686 final boolean domain_combinations,
1687 final CharacterStateMatrix<CharacterStateMatrix.GainLossStates> matrix,
1688 final CharacterStateMatrix.GainLossStates state,
1689 final String filename,
1690 final String indentifier_characters_separator,
1691 final String character_separator,
1692 final String title_for_html,
1693 final String prefix_for_html,
1694 final Map<DomainId, Set<String>>[] domain_id_to_secondary_features_maps,
1695 final SortedSet<String> all_pfams_encountered,
1696 final SortedSet<String> pfams_gained_or_lost,
1697 final String suffix_for_per_node_events_file ) {
1698 if ( ( go_namespace_limit != null ) && ( ( go_id_to_term_map == null ) || ( go_id_to_term_map.size() < 1 ) ) ) {
1699 throw new IllegalArgumentException( "attempt to use GO namespace limit without a GO-id to term map" );
1701 else if ( ( ( domain_id_to_go_ids_map == null ) || ( domain_id_to_go_ids_map.size() < 1 ) ) ) {
1702 throw new IllegalArgumentException( "attempt to output detailed HTML without a Pfam to GO map" );
1704 else if ( ( ( go_id_to_term_map == null ) || ( go_id_to_term_map.size() < 1 ) ) ) {
1705 throw new IllegalArgumentException( "attempt to output detailed HTML without a GO-id to term map" );
1707 final File outfile = new File( filename );
1708 checkForOutputFileWriteability( outfile );
1709 final SortedSet<String> sorted_ids = new TreeSet<String>();
1710 for( int i = 0; i < matrix.getNumberOfIdentifiers(); ++i ) {
1711 sorted_ids.add( matrix.getIdentifier( i ) );
1714 final Writer out = new BufferedWriter( new FileWriter( outfile ) );
1715 final File per_node_go_mapped_domain_gain_loss_files_base_dir = createBaseDirForPerNodeDomainFiles( surfacing.BASE_DIRECTORY_PER_NODE_DOMAIN_GAIN_LOSS_FILES,
1716 domain_combinations,
1719 Writer per_node_go_mapped_domain_gain_loss_outfile_writer = null;
1720 File per_node_go_mapped_domain_gain_loss_outfile = null;
1721 int per_node_counter = 0;
1722 out.write( "<html>" );
1723 out.write( SurfacingConstants.NL );
1724 addHtmlHead( out, title_for_html );
1725 out.write( SurfacingConstants.NL );
1726 out.write( "<body>" );
1727 out.write( SurfacingConstants.NL );
1728 out.write( "<h1>" );
1729 out.write( SurfacingConstants.NL );
1730 out.write( title_for_html );
1731 out.write( SurfacingConstants.NL );
1732 out.write( "</h1>" );
1733 out.write( SurfacingConstants.NL );
1734 out.write( "<table>" );
1735 out.write( SurfacingConstants.NL );
1736 for( final String id : sorted_ids ) {
1737 out.write( "<tr>" );
1738 out.write( "<td>" );
1739 out.write( "<a href=\"#" + id + "\">" + id + "</a>" );
1740 writeTaxonomyLinks( out, id );
1741 out.write( "</td>" );
1742 out.write( "</tr>" );
1743 out.write( SurfacingConstants.NL );
1745 out.write( "</table>" );
1746 out.write( SurfacingConstants.NL );
1747 for( final String id : sorted_ids ) {
1748 out.write( SurfacingConstants.NL );
1749 out.write( "<h2>" );
1750 out.write( "<a name=\"" + id + "\">" + id + "</a>" );
1751 writeTaxonomyLinks( out, id );
1752 out.write( "</h2>" );
1753 out.write( SurfacingConstants.NL );
1754 out.write( "<table>" );
1755 out.write( SurfacingConstants.NL );
1756 out.write( "<tr>" );
1757 out.write( "<td><b>" );
1758 out.write( "Pfam domain(s)" );
1759 out.write( "</b></td><td><b>" );
1760 out.write( "GO term acc" );
1761 out.write( "</b></td><td><b>" );
1762 out.write( "GO term" );
1763 out.write( "</b></td><td><b>" );
1764 out.write( "Penultimate GO term" );
1765 out.write( "</b></td><td><b>" );
1766 out.write( "GO namespace" );
1767 out.write( "</b></td>" );
1768 out.write( "</tr>" );
1769 out.write( SurfacingConstants.NL );
1770 out.write( "</tr>" );
1771 out.write( SurfacingConstants.NL );
1772 per_node_counter = 0;
1773 if ( matrix.getNumberOfCharacters() > 0 ) {
1774 per_node_go_mapped_domain_gain_loss_outfile = new File( per_node_go_mapped_domain_gain_loss_files_base_dir
1775 + ForesterUtil.FILE_SEPARATOR + id + suffix_for_per_node_events_file );
1776 SurfacingUtil.checkForOutputFileWriteability( per_node_go_mapped_domain_gain_loss_outfile );
1777 per_node_go_mapped_domain_gain_loss_outfile_writer = ForesterUtil
1778 .createBufferedWriter( per_node_go_mapped_domain_gain_loss_outfile );
1781 per_node_go_mapped_domain_gain_loss_outfile = null;
1782 per_node_go_mapped_domain_gain_loss_outfile_writer = null;
1784 for( int c = 0; c < matrix.getNumberOfCharacters(); ++c ) {
1786 // using null to indicate either UNCHANGED_PRESENT or GAIN.
1787 if ( ( matrix.getState( id, c ) == state )
1788 || ( ( state == null ) && ( ( matrix.getState( id, c ) == CharacterStateMatrix.GainLossStates.UNCHANGED_PRESENT ) || ( matrix
1789 .getState( id, c ) == CharacterStateMatrix.GainLossStates.GAIN ) ) ) ) {
1790 final String character = matrix.getCharacter( c );
1791 String domain_0 = "";
1792 String domain_1 = "";
1793 if ( character.indexOf( BinaryDomainCombination.SEPARATOR ) > 0 ) {
1794 final String[] s = character.split( BinaryDomainCombination.SEPARATOR );
1795 if ( s.length != 2 ) {
1796 throw new AssertionError( "this should not have happened: unexpected format for domain combination: ["
1797 + character + "]" );
1803 domain_0 = character;
1805 writeDomainData( domain_id_to_go_ids_map,
1812 character_separator,
1813 domain_id_to_secondary_features_maps,
1815 all_pfams_encountered.add( domain_0 );
1816 if ( pfams_gained_or_lost != null ) {
1817 pfams_gained_or_lost.add( domain_0 );
1819 if ( !ForesterUtil.isEmpty( domain_1 ) ) {
1820 all_pfams_encountered.add( domain_1 );
1821 if ( pfams_gained_or_lost != null ) {
1822 pfams_gained_or_lost.add( domain_1 );
1825 if ( per_node_go_mapped_domain_gain_loss_outfile_writer != null ) {
1826 writeDomainsToIndividualFilePerTreeNode( per_node_go_mapped_domain_gain_loss_outfile_writer,
1833 if ( per_node_go_mapped_domain_gain_loss_outfile_writer != null ) {
1834 per_node_go_mapped_domain_gain_loss_outfile_writer.close();
1835 if ( per_node_counter < 1 ) {
1836 per_node_go_mapped_domain_gain_loss_outfile.delete();
1838 per_node_counter = 0;
1840 out.write( "</table>" );
1841 out.write( SurfacingConstants.NL );
1842 out.write( "<hr>" );
1843 out.write( SurfacingConstants.NL );
1844 } // for( final String id : sorted_ids ) {
1845 out.write( "</body>" );
1846 out.write( SurfacingConstants.NL );
1847 out.write( "</html>" );
1848 out.write( SurfacingConstants.NL );
1852 catch ( final IOException e ) {
1853 ForesterUtil.fatalError( surfacing.PRG_NAME, e.getMessage() );
1855 ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote characters detailed HTML list: \"" + filename + "\"" );
1858 public static void writeDomainCombinationsCountsFile( final String[][] input_file_properties,
1859 final File output_dir,
1860 final Writer per_genome_domain_promiscuity_statistics_writer,
1861 final GenomeWideCombinableDomains gwcd,
1863 final GenomeWideCombinableDomains.GenomeWideCombinableDomainsSortOrder dc_sort_order ) {
1864 File dc_outfile = new File( input_file_properties[ i ][ 0 ]
1865 + surfacing.DOMAIN_COMBINITON_COUNTS_OUTPUTFILE_SUFFIX );
1866 if ( output_dir != null ) {
1867 dc_outfile = new File( output_dir + ForesterUtil.FILE_SEPARATOR + dc_outfile );
1869 checkForOutputFileWriteability( dc_outfile );
1871 final BufferedWriter out = new BufferedWriter( new FileWriter( dc_outfile ) );
1872 out.write( gwcd.toStringBuilder( dc_sort_order ).toString() );
1875 catch ( final IOException e ) {
1876 ForesterUtil.fatalError( surfacing.PRG_NAME, e.getMessage() );
1878 final DescriptiveStatistics stats = gwcd.getPerGenomeDomainPromiscuityStatistics();
1880 per_genome_domain_promiscuity_statistics_writer.write( input_file_properties[ i ][ 0 ] + "\t" );
1881 per_genome_domain_promiscuity_statistics_writer.write( FORMATTER_3.format( stats.arithmeticMean() ) + "\t" );
1882 if ( stats.getN() < 2 ) {
1883 per_genome_domain_promiscuity_statistics_writer.write( "n/a" + "\t" );
1886 per_genome_domain_promiscuity_statistics_writer.write( FORMATTER_3.format( stats
1887 .sampleStandardDeviation() ) + "\t" );
1889 per_genome_domain_promiscuity_statistics_writer.write( FORMATTER_3.format( stats.median() ) + "\t" );
1890 per_genome_domain_promiscuity_statistics_writer.write( ( int ) stats.getMin() + "\t" );
1891 per_genome_domain_promiscuity_statistics_writer.write( ( int ) stats.getMax() + "\t" );
1892 per_genome_domain_promiscuity_statistics_writer.write( stats.getN() + "\t" );
1893 final SortedSet<DomainId> mpds = gwcd.getMostPromiscuosDomain();
1894 for( final DomainId mpd : mpds ) {
1895 per_genome_domain_promiscuity_statistics_writer.write( mpd.getId() + " " );
1897 per_genome_domain_promiscuity_statistics_writer.write( ForesterUtil.LINE_SEPARATOR );
1899 catch ( final IOException e ) {
1900 ForesterUtil.fatalError( surfacing.PRG_NAME, e.getMessage() );
1902 if ( input_file_properties[ i ].length == 3 ) {
1903 ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote domain combination counts for \""
1904 + input_file_properties[ i ][ 0 ] + "\" (" + input_file_properties[ i ][ 1 ] + ", "
1905 + input_file_properties[ i ][ 2 ] + ") to: \"" + dc_outfile + "\"" );
1908 ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote domain combination counts for \""
1909 + input_file_properties[ i ][ 0 ] + "\" (" + input_file_properties[ i ][ 1 ] + ") to: \""
1910 + dc_outfile + "\"" );
1914 private static void writeDomainData( final Map<DomainId, List<GoId>> domain_id_to_go_ids_map,
1915 final Map<GoId, GoTerm> go_id_to_term_map,
1916 final GoNameSpace go_namespace_limit,
1918 final String domain_0,
1919 final String domain_1,
1920 final String prefix_for_html,
1921 final String character_separator_for_non_html_output,
1922 final Map<DomainId, Set<String>>[] domain_id_to_secondary_features_maps,
1923 final Set<GoId> all_go_ids ) throws IOException {
1924 boolean any_go_annotation_present = false;
1925 boolean first_has_no_go = false;
1926 int domain_count = 2; // To distinguish between domains and binary domain combinations.
1927 if ( ForesterUtil.isEmpty( domain_1 ) ) {
1930 // The following has a difficult to understand logic.
1931 for( int d = 0; d < domain_count; ++d ) {
1932 List<GoId> go_ids = null;
1933 boolean go_annotation_present = false;
1935 final DomainId domain_id = new DomainId( domain_0 );
1936 if ( domain_id_to_go_ids_map.containsKey( domain_id ) ) {
1937 go_annotation_present = true;
1938 any_go_annotation_present = true;
1939 go_ids = domain_id_to_go_ids_map.get( domain_id );
1942 first_has_no_go = true;
1946 final DomainId domain_id = new DomainId( domain_1 );
1947 if ( domain_id_to_go_ids_map.containsKey( domain_id ) ) {
1948 go_annotation_present = true;
1949 any_go_annotation_present = true;
1950 go_ids = domain_id_to_go_ids_map.get( domain_id );
1953 if ( go_annotation_present ) {
1954 boolean first = ( ( d == 0 ) || ( ( d == 1 ) && first_has_no_go ) );
1955 for( final GoId go_id : go_ids ) {
1956 out.write( "<tr>" );
1959 writeDomainIdsToHtml( out,
1963 domain_id_to_secondary_features_maps );
1966 out.write( "<td></td>" );
1968 if ( !go_id_to_term_map.containsKey( go_id ) ) {
1969 throw new IllegalArgumentException( "GO-id [" + go_id + "] not found in GO-id to GO-term map" );
1971 final GoTerm go_term = go_id_to_term_map.get( go_id );
1972 if ( ( go_namespace_limit == null ) || go_namespace_limit.equals( go_term.getGoNameSpace() ) ) {
1973 // final String top = GoUtils.getPenultimateGoTerm( go_term, go_id_to_term_map ).getName();
1974 final String go_id_str = go_id.getId();
1975 out.write( "<td>" );
1976 out.write( "<a href=\"" + SurfacingConstants.AMIGO_LINK + go_id_str
1977 + "\" target=\"amigo_window\">" + go_id_str + "</a>" );
1978 out.write( "</td><td>" );
1979 out.write( go_term.getName() );
1980 if ( domain_count == 2 ) {
1981 out.write( " (" + d + ")" );
1983 out.write( "</td><td>" );
1984 // out.write( top );
1985 // out.write( "</td><td>" );
1987 out.write( go_term.getGoNameSpace().toShortString() );
1989 out.write( "</td>" );
1990 if ( all_go_ids != null ) {
1991 all_go_ids.add( go_id );
1995 out.write( "<td>" );
1996 out.write( "</td><td>" );
1997 out.write( "</td><td>" );
1998 out.write( "</td><td>" );
1999 out.write( "</td>" );
2001 out.write( "</tr>" );
2002 out.write( SurfacingConstants.NL );
2005 } // for( int d = 0; d < domain_count; ++d )
2006 if ( !any_go_annotation_present ) {
2007 out.write( "<tr>" );
2008 writeDomainIdsToHtml( out, domain_0, domain_1, prefix_for_html, domain_id_to_secondary_features_maps );
2009 out.write( "<td>" );
2010 out.write( "</td><td>" );
2011 out.write( "</td><td>" );
2012 out.write( "</td><td>" );
2013 out.write( "</td>" );
2014 out.write( "</tr>" );
2015 out.write( SurfacingConstants.NL );
2019 private static void writeDomainIdsToHtml( final Writer out,
2020 final String domain_0,
2021 final String domain_1,
2022 final String prefix_for_detailed_html,
2023 final Map<DomainId, Set<String>>[] domain_id_to_secondary_features_maps )
2024 throws IOException {
2025 out.write( "<td>" );
2026 if ( !ForesterUtil.isEmpty( prefix_for_detailed_html ) ) {
2027 out.write( prefix_for_detailed_html );
2030 out.write( "<a href=\"" + SurfacingConstants.PFAM_FAMILY_ID_LINK + domain_0 + "\">" + domain_0 + "</a>" );
2031 out.write( "</td>" );
2034 public static DescriptiveStatistics writeDomainSimilaritiesToFile( final StringBuilder html_desc,
2035 final StringBuilder html_title,
2036 final Writer single_writer,
2037 Map<Character, Writer> split_writers,
2038 final SortedSet<DomainSimilarity> similarities,
2039 final boolean treat_as_binary,
2040 final List<Species> species_order,
2041 final PrintableDomainSimilarity.PRINT_OPTION print_option,
2042 final DomainSimilarity.DomainSimilaritySortField sort_field,
2043 final DomainSimilarity.DomainSimilarityScoring scoring,
2044 final boolean verbose ) throws IOException {
2045 final DescriptiveStatistics stats = new BasicDescriptiveStatistics();
2046 String histogram_title = null;
2047 switch ( sort_field ) {
2048 case ABS_MAX_COUNTS_DIFFERENCE:
2049 if ( treat_as_binary ) {
2050 histogram_title = "absolute counts difference:";
2053 histogram_title = "absolute (maximal) counts difference:";
2056 case MAX_COUNTS_DIFFERENCE:
2057 if ( treat_as_binary ) {
2058 histogram_title = "counts difference:";
2061 histogram_title = "(maximal) counts difference:";
2065 histogram_title = "score mean:";
2068 histogram_title = "score minimum:";
2071 histogram_title = "score maximum:";
2073 case MAX_DIFFERENCE:
2074 if ( treat_as_binary ) {
2075 histogram_title = "difference:";
2078 histogram_title = "(maximal) difference:";
2082 histogram_title = "score mean:";
2085 histogram_title = "score standard deviation:";
2088 histogram_title = "species number:";
2091 throw new AssertionError( "Unknown sort field: " + sort_field );
2093 for( final DomainSimilarity similarity : similarities ) {
2094 switch ( sort_field ) {
2095 case ABS_MAX_COUNTS_DIFFERENCE:
2096 stats.addValue( Math.abs( similarity.getMaximalDifferenceInCounts() ) );
2098 case MAX_COUNTS_DIFFERENCE:
2099 stats.addValue( similarity.getMaximalDifferenceInCounts() );
2102 stats.addValue( similarity.getMeanSimilarityScore() );
2105 stats.addValue( similarity.getMinimalSimilarityScore() );
2108 stats.addValue( similarity.getMaximalSimilarityScore() );
2110 case MAX_DIFFERENCE:
2111 stats.addValue( similarity.getMaximalDifference() );
2114 stats.addValue( similarity.getMeanSimilarityScore() );
2117 stats.addValue( similarity.getStandardDeviationOfSimilarityScore() );
2120 stats.addValue( similarity.getSpecies().size() );
2123 throw new AssertionError( "Unknown sort field: " + sort_field );
2127 // final HistogramData[] hists = new HistogramData[ 1 ];
2130 // List<HistogramDataItem> data_items = new
2131 // ArrayList<HistogramDataItem>();
2132 // double[] values = stats.getDataAsDoubleArray();
2133 // for( int i = 0; i < values.length; i++ ) {
2134 // HistogramDataItem data_item = new BasicHistogramDataItem( "", values[
2136 // data_items.add( data_item );
2140 // HistogramData hd0 = new HistogramData( "name",
2148 // hists[ 0 ] = hd0;
2150 // final HistogramsFrame hf = new HistogramsFrame( hists );
2151 // hf.setVisible( true );
2153 AsciiHistogram histo = null;
2154 if ( stats.getMin() < stats.getMin() ) {
2155 histo = new AsciiHistogram( stats, histogram_title );
2158 if ( histo != null ) {
2159 System.out.println( histo.toStringBuffer( 20, '|', 40, 5 ) );
2161 System.out.println();
2162 System.out.println( "N : " + stats.getN() );
2163 System.out.println( "Min : " + stats.getMin() );
2164 System.out.println( "Max : " + stats.getMax() );
2165 System.out.println( "Mean : " + stats.arithmeticMean() );
2166 if ( stats.getN() > 1 ) {
2167 System.out.println( "SD : " + stats.sampleStandardDeviation() );
2170 System.out.println( "SD : n/a" );
2172 System.out.println( "Median : " + stats.median() );
2173 if ( stats.getN() > 1 ) {
2174 System.out.println( "Pearsonian skewness : " + stats.pearsonianSkewness() );
2177 System.out.println( "Pearsonian skewness : n/a" );
2180 if ( ( single_writer != null ) && ( ( split_writers == null ) || split_writers.isEmpty() ) ) {
2181 split_writers = new HashMap<Character, Writer>();
2182 split_writers.put( '_', single_writer );
2184 switch ( print_option ) {
2185 case SIMPLE_TAB_DELIMITED:
2188 for( final Character key : split_writers.keySet() ) {
2189 final Writer w = split_writers.get( key );
2190 w.write( "<html>" );
2191 w.write( SurfacingConstants.NL );
2193 addHtmlHead( w, "DCs (" + html_title + ") " + key.toString().toUpperCase() );
2196 addHtmlHead( w, "DCs (" + html_title + ")" );
2198 w.write( SurfacingConstants.NL );
2199 w.write( "<body>" );
2200 w.write( SurfacingConstants.NL );
2201 w.write( html_desc.toString() );
2202 w.write( SurfacingConstants.NL );
2205 w.write( SurfacingConstants.NL );
2206 w.write( "<tt><pre>" );
2207 w.write( SurfacingConstants.NL );
2208 if ( histo != null ) {
2209 w.write( histo.toStringBuffer( 20, '|', 40, 5 ).toString() );
2210 w.write( SurfacingConstants.NL );
2212 w.write( "</pre></tt>" );
2213 w.write( SurfacingConstants.NL );
2214 w.write( "<table>" );
2215 w.write( SurfacingConstants.NL );
2216 w.write( "<tr><td>N: </td><td>" + stats.getN() + "</td></tr>" );
2217 w.write( SurfacingConstants.NL );
2218 w.write( "<tr><td>Min: </td><td>" + stats.getMin() + "</td></tr>" );
2219 w.write( SurfacingConstants.NL );
2220 w.write( "<tr><td>Max: </td><td>" + stats.getMax() + "</td></tr>" );
2221 w.write( SurfacingConstants.NL );
2222 w.write( "<tr><td>Mean: </td><td>" + stats.arithmeticMean() + "</td></tr>" );
2223 w.write( SurfacingConstants.NL );
2224 if ( stats.getN() > 1 ) {
2225 w.write( "<tr><td>SD: </td><td>" + stats.sampleStandardDeviation() + "</td></tr>" );
2228 w.write( "<tr><td>SD: </td><td>n/a</td></tr>" );
2230 w.write( SurfacingConstants.NL );
2231 w.write( "<tr><td>Median: </td><td>" + stats.median() + "</td></tr>" );
2232 w.write( SurfacingConstants.NL );
2233 if ( stats.getN() > 1 ) {
2234 w.write( "<tr><td>Pearsonian skewness: </td><td>" + stats.pearsonianSkewness() + "</td></tr>" );
2237 w.write( "<tr><td>Pearsonian skewness: </td><td>n/a</td></tr>" );
2239 w.write( SurfacingConstants.NL );
2240 w.write( "</table>" );
2241 w.write( SurfacingConstants.NL );
2243 w.write( SurfacingConstants.NL );
2245 w.write( SurfacingConstants.NL );
2247 w.write( SurfacingConstants.NL );
2248 w.write( "<table>" );
2249 w.write( SurfacingConstants.NL );
2253 for( final Writer w : split_writers.values() ) {
2254 w.write( SurfacingConstants.NL );
2256 for( final DomainSimilarity similarity : similarities ) {
2257 if ( ( species_order != null ) && !species_order.isEmpty() ) {
2258 ( ( PrintableDomainSimilarity ) similarity ).setSpeciesOrder( species_order );
2260 if ( single_writer != null ) {
2261 single_writer.write( similarity.toStringBuffer( print_option ).toString() );
2264 Writer local_writer = split_writers.get( ( similarity.getDomainId().getId().charAt( 0 ) + "" )
2265 .toLowerCase().charAt( 0 ) );
2266 if ( local_writer == null ) {
2267 local_writer = split_writers.get( '0' );
2269 local_writer.write( similarity.toStringBuffer( print_option ).toString() );
2271 for( final Writer w : split_writers.values() ) {
2272 w.write( SurfacingConstants.NL );
2275 switch ( print_option ) {
2277 for( final Writer w : split_writers.values() ) {
2278 w.write( SurfacingConstants.NL );
2279 w.write( "</table>" );
2280 w.write( SurfacingConstants.NL );
2281 w.write( "</font>" );
2282 w.write( SurfacingConstants.NL );
2283 w.write( "</body>" );
2284 w.write( SurfacingConstants.NL );
2285 w.write( "</html>" );
2286 w.write( SurfacingConstants.NL );
2290 for( final Writer w : split_writers.values() ) {
2296 private static void writeDomainsToIndividualFilePerTreeNode( final Writer individual_files_writer,
2297 final String domain_0,
2298 final String domain_1 ) throws IOException {
2299 individual_files_writer.write( domain_0 );
2300 individual_files_writer.write( ForesterUtil.LINE_SEPARATOR );
2301 if ( !ForesterUtil.isEmpty( domain_1 ) ) {
2302 individual_files_writer.write( domain_1 );
2303 individual_files_writer.write( ForesterUtil.LINE_SEPARATOR );
2307 public static void writeMatrixToFile( final CharacterStateMatrix<?> matrix,
2308 final String filename,
2309 final Format format ) {
2310 final File outfile = new File( filename );
2311 checkForOutputFileWriteability( outfile );
2313 final BufferedWriter out = new BufferedWriter( new FileWriter( outfile ) );
2314 matrix.toWriter( out, format );
2318 catch ( final IOException e ) {
2319 ForesterUtil.fatalError( surfacing.PRG_NAME, e.getMessage() );
2321 ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote matrix: \"" + filename + "\"" );
2324 public static void writeMatrixToFile( final File matrix_outfile, final List<DistanceMatrix> matrices ) {
2325 checkForOutputFileWriteability( matrix_outfile );
2327 final BufferedWriter out = new BufferedWriter( new FileWriter( matrix_outfile ) );
2328 for( final DistanceMatrix distance_matrix : matrices ) {
2329 out.write( distance_matrix.toStringBuffer( DistanceMatrix.Format.PHYLIP ).toString() );
2330 out.write( ForesterUtil.LINE_SEPARATOR );
2335 catch ( final IOException e ) {
2336 ForesterUtil.fatalError( surfacing.PRG_NAME, e.getMessage() );
2338 ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote distance matrices to \"" + matrix_outfile + "\"" );
2341 private static void writePfamsToFile( final String outfile_name, final SortedSet<String> pfams ) {
2343 final Writer writer = new BufferedWriter( new FileWriter( new File( outfile_name ) ) );
2344 for( final String pfam : pfams ) {
2345 writer.write( pfam );
2346 writer.write( ForesterUtil.LINE_SEPARATOR );
2349 ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote " + pfams.size() + " pfams to [" + outfile_name
2352 catch ( final IOException e ) {
2353 ForesterUtil.printWarningMessage( surfacing.PRG_NAME, "Failure to write: " + e );
2357 public static void writePhylogenyToFile( final Phylogeny phylogeny, final String filename ) {
2358 final PhylogenyWriter writer = new PhylogenyWriter();
2360 writer.toPhyloXML( new File( filename ), phylogeny, 1 );
2362 catch ( final IOException e ) {
2363 ForesterUtil.printWarningMessage( surfacing.PRG_NAME, "failed to write phylogeny to \"" + filename + "\": "
2366 ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote phylogeny to \"" + filename + "\"" );
2369 public static void writeTaxonomyLinks( final Writer writer, final String species ) throws IOException {
2370 if ( ( species.length() > 1 ) && ( species.indexOf( '_' ) < 1 ) ) {
2371 final Matcher matcher = PATTERN_SP_STYLE_TAXONOMY.matcher( species );
2372 writer.write( " [" );
2373 if ( matcher.matches() ) {
2374 writer.write( "<a href=\"" + SurfacingConstants.UNIPROT_LINK + species
2375 + "\" target=\"taxonomy_window\">uniprot</a>" );
2378 writer.write( "<a href=\"" + SurfacingConstants.EOL_LINK + species
2379 + "\" target=\"taxonomy_window\">eol</a>" );
2380 writer.write( "|" );
2381 writer.write( "<a href=\"" + SurfacingConstants.TOL_LINK + species
2382 + "\" target=\"taxonomy_window\">tol</a>" );
2384 writer.write( "]" );
2388 private static void writeToNexus( final String outfile_name,
2389 final CharacterStateMatrix<BinaryStates> matrix,
2390 final Phylogeny phylogeny ) {
2391 if ( !( matrix instanceof BasicCharacterStateMatrix ) ) {
2392 throw new IllegalArgumentException( "can only write matrices of type [" + BasicCharacterStateMatrix.class
2395 final BasicCharacterStateMatrix<BinaryStates> my_matrix = ( org.forester.evoinference.matrix.character.BasicCharacterStateMatrix<BinaryStates> ) matrix;
2396 final List<Phylogeny> phylogenies = new ArrayList<Phylogeny>( 1 );
2397 phylogenies.add( phylogeny );
2399 final BufferedWriter w = new BufferedWriter( new FileWriter( outfile_name ) );
2400 w.write( NexusConstants.NEXUS );
2401 w.write( ForesterUtil.LINE_SEPARATOR );
2402 my_matrix.writeNexusTaxaBlock( w );
2403 my_matrix.writeNexusBinaryChractersBlock( w );
2404 PhylogenyWriter.writeNexusTreesBlock( w, phylogenies, NH_CONVERSION_SUPPORT_VALUE_STYLE.NONE );
2407 ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote Nexus file: \"" + outfile_name + "\"" );
2409 catch ( final IOException e ) {
2410 ForesterUtil.fatalError( surfacing.PRG_NAME, e.getMessage() );
2414 private static void writeToNexus( final String outfile_name,
2415 final DomainParsimonyCalculator domain_parsimony,
2416 final Phylogeny phylogeny ) {
2417 writeToNexus( outfile_name + surfacing.NEXUS_EXTERNAL_DOMAINS,
2418 domain_parsimony.createMatrixOfDomainPresenceOrAbsence(),
2420 writeToNexus( outfile_name + surfacing.NEXUS_EXTERNAL_DOMAIN_COMBINATIONS,
2421 domain_parsimony.createMatrixOfBinaryDomainCombinationPresenceOrAbsence(),
2425 public static void domainsPerProteinsStatistics( final String genome,
2426 final List<Protein> protein_list,
2427 final DescriptiveStatistics all_genomes_domains_per_potein_stats,
2428 final SortedMap<Integer, Integer> all_genomes_domains_per_potein_histo,
2429 final SortedSet<String> domains_which_are_always_single,
2430 final SortedSet<String> domains_which_are_sometimes_single_sometimes_not,
2431 final SortedSet<String> domains_which_never_single,
2432 final Writer writer ) {
2433 final DescriptiveStatistics stats = new BasicDescriptiveStatistics();
2434 for( final Protein protein : protein_list ) {
2435 final int domains = protein.getNumberOfProteinDomains();
2436 //System.out.println( domains );
2437 stats.addValue( domains );
2438 all_genomes_domains_per_potein_stats.addValue( domains );
2439 if ( !all_genomes_domains_per_potein_histo.containsKey( domains ) ) {
2440 all_genomes_domains_per_potein_histo.put( domains, 1 );
2443 all_genomes_domains_per_potein_histo.put( domains,
2444 1 + all_genomes_domains_per_potein_histo.get( domains ) );
2446 if ( domains == 1 ) {
2447 final String domain = protein.getProteinDomain( 0 ).getDomainId().getId();
2448 if ( !domains_which_are_sometimes_single_sometimes_not.contains( domain ) ) {
2449 if ( domains_which_never_single.contains( domain ) ) {
2450 domains_which_never_single.remove( domain );
2451 domains_which_are_sometimes_single_sometimes_not.add( domain );
2454 domains_which_are_always_single.add( domain );
2458 else if ( domains > 1 ) {
2459 for( final Domain d : protein.getProteinDomains() ) {
2460 final String domain = d.getDomainId().getId();
2461 // System.out.println( domain );
2462 if ( !domains_which_are_sometimes_single_sometimes_not.contains( domain ) ) {
2463 if ( domains_which_are_always_single.contains( domain ) ) {
2464 domains_which_are_always_single.remove( domain );
2465 domains_which_are_sometimes_single_sometimes_not.add( domain );
2468 domains_which_never_single.add( domain );
2475 writer.write( genome );
2476 writer.write( "\t" );
2477 if ( stats.getN() >= 1 ) {
2478 writer.write( stats.arithmeticMean() + "" );
2479 writer.write( "\t" );
2480 if ( stats.getN() >= 2 ) {
2481 writer.write( stats.sampleStandardDeviation() + "" );
2486 writer.write( "\t" );
2487 writer.write( stats.median() + "" );
2488 writer.write( "\t" );
2489 writer.write( stats.getN() + "" );
2490 writer.write( "\t" );
2491 writer.write( stats.getMin() + "" );
2492 writer.write( "\t" );
2493 writer.write( stats.getMax() + "" );
2496 writer.write( "\t" );
2497 writer.write( "\t" );
2498 writer.write( "\t" );
2499 writer.write( "0" );
2500 writer.write( "\t" );
2501 writer.write( "\t" );
2503 writer.write( "\n" );
2505 catch ( final IOException e ) {
2506 e.printStackTrace();