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.data.BinaryCharacters;
71 import org.forester.phylogeny.data.Confidence;
72 import org.forester.phylogeny.iterators.PhylogenyNodeIterator;
73 import org.forester.surfacing.DomainSimilarityCalculator.Detailedness;
74 import org.forester.surfacing.DomainSimilarityCalculator.GoAnnotationOutput;
75 import org.forester.surfacing.GenomeWideCombinableDomains.GenomeWideCombinableDomainsSortOrder;
76 import org.forester.util.AsciiHistogram;
77 import org.forester.util.BasicDescriptiveStatistics;
78 import org.forester.util.BasicTable;
79 import org.forester.util.BasicTableParser;
80 import org.forester.util.DescriptiveStatistics;
81 import org.forester.util.ForesterUtil;
83 public final class SurfacingUtil {
85 private final static NumberFormat FORMATTER = new DecimalFormat( "0.0E0" );
86 private final static NumberFormat FORMATTER_3 = new DecimalFormat( "0.000" );
87 private static final Comparator<Domain> ASCENDING_CONFIDENCE_VALUE_ORDER = new Comparator<Domain>() {
90 public int compare( final Domain d1,
92 if ( d1.getPerSequenceEvalue() < d2
93 .getPerSequenceEvalue() ) {
97 .getPerSequenceEvalue() > d2
98 .getPerSequenceEvalue() ) {
102 return d1.compareTo( d2 );
106 public final static Pattern PATTERN_SP_STYLE_TAXONOMY = Pattern.compile( "^[A-Z0-9]{3,5}$" );
108 private SurfacingUtil() {
109 // Hidden constructor.
112 public static void addAllBinaryDomainCombinationToSet( final GenomeWideCombinableDomains genome,
113 final SortedSet<BinaryDomainCombination> binary_domain_combinations ) {
114 final SortedMap<DomainId, CombinableDomains> all_cd = genome.getAllCombinableDomainsIds();
115 for( final DomainId domain_id : all_cd.keySet() ) {
116 binary_domain_combinations.addAll( all_cd.get( domain_id ).toBinaryDomainCombinations() );
120 public static void addAllDomainIdsToSet( final GenomeWideCombinableDomains genome,
121 final SortedSet<DomainId> domain_ids ) {
122 final SortedSet<DomainId> domains = genome.getAllDomainIds();
123 for( final DomainId domain : domains ) {
124 domain_ids.add( domain );
128 public static void addHtmlHead( final Writer w, final String title ) throws IOException {
129 w.write( SurfacingConstants.NL );
131 w.write( "<title>" );
133 w.write( "</title>" );
134 w.write( SurfacingConstants.NL );
135 w.write( "<style>" );
136 w.write( SurfacingConstants.NL );
137 w.write( "a:visited { color : #6633FF; text-decoration : none; }" );
138 w.write( SurfacingConstants.NL );
139 w.write( "a:link { color : #6633FF; text-decoration : none; }" );
140 w.write( SurfacingConstants.NL );
141 w.write( "a:active { color : #99FF00; text-decoration : none; }" );
142 w.write( SurfacingConstants.NL );
143 w.write( "a:hover { color : #FFFFFF; background-color : #99FF00; text-decoration : none; }" );
144 w.write( SurfacingConstants.NL );
145 w.write( "td { text-align: left; vertical-align: top; font-family: Verdana, Arial, Helvetica; font-size: 8pt}" );
146 w.write( SurfacingConstants.NL );
147 w.write( "h1 { color : #0000FF; font-family: Verdana, Arial, Helvetica; font-size: 18pt; font-weight: bold }" );
148 w.write( SurfacingConstants.NL );
149 w.write( "h2 { color : #0000FF; font-family: Verdana, Arial, Helvetica; font-size: 16pt; font-weight: bold }" );
150 w.write( SurfacingConstants.NL );
151 w.write( "</style>" );
152 w.write( SurfacingConstants.NL );
153 w.write( "</head>" );
154 w.write( SurfacingConstants.NL );
157 public static DescriptiveStatistics calculateDescriptiveStatisticsForMeanValues( final Set<DomainSimilarity> similarities ) {
158 final DescriptiveStatistics stats = new BasicDescriptiveStatistics();
159 for( final DomainSimilarity similarity : similarities ) {
160 stats.addValue( similarity.getMeanSimilarityScore() );
165 private static void calculateIndependentDomainCombinationGains( final Phylogeny local_phylogeny_l,
166 final String outfilename_for_counts,
167 final String outfilename_for_dc,
168 final String outfilename_for_dc_for_go_mapping,
169 final String outfilename_for_dc_for_go_mapping_unique,
170 final String outfilename_for_rank_counts,
171 final String outfilename_for_ancestor_species_counts ) {
173 final BufferedWriter out_counts = new BufferedWriter( new FileWriter( outfilename_for_counts ) );
174 final BufferedWriter out_dc = new BufferedWriter( new FileWriter( outfilename_for_dc ) );
175 final BufferedWriter out_dc_for_go_mapping = new BufferedWriter( new FileWriter( outfilename_for_dc_for_go_mapping ) );
176 final BufferedWriter out_dc_for_go_mapping_unique = new BufferedWriter( new FileWriter( outfilename_for_dc_for_go_mapping_unique ) );
177 final SortedMap<String, Integer> dc_gain_counts = new TreeMap<String, Integer>();
178 for( final PhylogenyNodeIterator it = local_phylogeny_l.iteratorPostorder(); it.hasNext(); ) {
179 final PhylogenyNode n = it.next();
180 final Set<String> gained_dc = n.getNodeData().getBinaryCharacters().getGainedCharacters();
181 for( final String dc : gained_dc ) {
182 if ( dc_gain_counts.containsKey( dc ) ) {
183 dc_gain_counts.put( dc, dc_gain_counts.get( dc ) + 1 );
186 dc_gain_counts.put( dc, 1 );
190 final SortedMap<Integer, Integer> histogram = new TreeMap<Integer, Integer>();
191 final SortedMap<Integer, StringBuilder> domain_lists = new TreeMap<Integer, StringBuilder>();
192 final SortedMap<Integer, PriorityQueue<String>> domain_lists_go = new TreeMap<Integer, PriorityQueue<String>>();
193 final SortedMap<Integer, SortedSet<String>> domain_lists_go_unique = new TreeMap<Integer, SortedSet<String>>();
194 final Set<String> dcs = dc_gain_counts.keySet();
195 final SortedSet<String> more_than_once = new TreeSet<String>();
196 for( final String dc : dcs ) {
197 final int count = dc_gain_counts.get( dc );
198 if ( histogram.containsKey( count ) ) {
199 histogram.put( count, histogram.get( count ) + 1 );
200 domain_lists.get( count ).append( ", " + dc );
201 domain_lists_go.get( count ).addAll( splitDomainCombination( dc ) );
202 domain_lists_go_unique.get( count ).addAll( splitDomainCombination( dc ) );
205 histogram.put( count, 1 );
206 domain_lists.put( count, new StringBuilder( dc ) );
207 final PriorityQueue<String> q = new PriorityQueue<String>();
208 q.addAll( splitDomainCombination( dc ) );
209 domain_lists_go.put( count, q );
210 final SortedSet<String> set = new TreeSet<String>();
211 set.addAll( splitDomainCombination( dc ) );
212 domain_lists_go_unique.put( count, set );
215 more_than_once.add( dc );
218 final Set<Integer> histogram_keys = histogram.keySet();
219 for( final Integer histogram_key : histogram_keys ) {
220 final int count = histogram.get( histogram_key );
221 final StringBuilder dc = domain_lists.get( histogram_key );
222 out_counts.write( histogram_key + "\t" + count + ForesterUtil.LINE_SEPARATOR );
223 out_dc.write( histogram_key + "\t" + dc + ForesterUtil.LINE_SEPARATOR );
224 out_dc_for_go_mapping.write( "#" + histogram_key + ForesterUtil.LINE_SEPARATOR );
225 final Object[] sorted = domain_lists_go.get( histogram_key ).toArray();
226 Arrays.sort( sorted );
227 for( final Object domain : sorted ) {
228 out_dc_for_go_mapping.write( domain + ForesterUtil.LINE_SEPARATOR );
230 out_dc_for_go_mapping_unique.write( "#" + histogram_key + ForesterUtil.LINE_SEPARATOR );
231 for( final String domain : domain_lists_go_unique.get( histogram_key ) ) {
232 out_dc_for_go_mapping_unique.write( domain + ForesterUtil.LINE_SEPARATOR );
237 out_dc_for_go_mapping.close();
238 out_dc_for_go_mapping_unique.close();
240 final SortedMap<String, Integer> lca_rank_counts = new TreeMap<String, Integer>();
241 final SortedMap<String, Integer> lca_ancestor_species_counts = new TreeMap<String, Integer>();
242 for( final String dc : more_than_once ) {
243 final List<PhylogenyNode> nodes = new ArrayList<PhylogenyNode>();
244 for( final PhylogenyNodeIterator it = local_phylogeny_l.iteratorExternalForward(); it.hasNext(); ) {
245 final PhylogenyNode n = it.next();
246 if ( n.getNodeData().getBinaryCharacters().getGainedCharacters().contains( dc ) ) {
250 for( int i = 0; i < nodes.size() - 1; ++i ) {
251 for( int j = i + 1; j < nodes.size(); ++j ) {
252 final PhylogenyNode lca = PhylogenyMethods.getInstance().obtainLCA( nodes.get( i ),
254 String rank = "unknown";
255 if ( lca.getNodeData().isHasTaxonomy()
256 && !ForesterUtil.isEmpty( lca.getNodeData().getTaxonomy().getRank() ) ) {
257 rank = lca.getNodeData().getTaxonomy().getRank();
259 addToCountMap( lca_rank_counts, rank );
261 if ( lca.getNodeData().isHasTaxonomy()
262 && !ForesterUtil.isEmpty( lca.getNodeData().getTaxonomy().getScientificName() ) ) {
263 lca_species = lca.getNodeData().getTaxonomy().getScientificName();
265 else if ( lca.getNodeData().isHasTaxonomy()
266 && !ForesterUtil.isEmpty( lca.getNodeData().getTaxonomy().getCommonName() ) ) {
267 lca_species = lca.getNodeData().getTaxonomy().getCommonName();
270 lca_species = lca.getName();
272 addToCountMap( lca_ancestor_species_counts, lca_species );
276 final BufferedWriter out_for_rank_counts = new BufferedWriter( new FileWriter( outfilename_for_rank_counts ) );
277 final BufferedWriter out_for_ancestor_species_counts = new BufferedWriter( new FileWriter( outfilename_for_ancestor_species_counts ) );
278 ForesterUtil.map2writer( out_for_rank_counts, lca_rank_counts, "\t", ForesterUtil.LINE_SEPARATOR );
279 ForesterUtil.map2writer( out_for_ancestor_species_counts,
280 lca_ancestor_species_counts,
282 ForesterUtil.LINE_SEPARATOR );
283 out_for_rank_counts.close();
284 out_for_ancestor_species_counts.close();
286 catch ( final IOException e ) {
287 ForesterUtil.printWarningMessage( surfacing.PRG_NAME, "Failure to write: " + e );
289 ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote independent domain combination gains fitch counts to ["
290 + outfilename_for_counts + "]" );
291 ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote independent domain combination gains fitch lists to ["
292 + outfilename_for_dc + "]" );
293 ForesterUtil.programMessage( surfacing.PRG_NAME,
294 "Wrote independent domain combination gains fitch lists to (for GO mapping) ["
295 + outfilename_for_dc_for_go_mapping + "]" );
296 ForesterUtil.programMessage( surfacing.PRG_NAME,
297 "Wrote independent domain combination gains fitch lists to (for GO mapping, unique) ["
298 + outfilename_for_dc_for_go_mapping_unique + "]" );
301 private final static void addToCountMap( final Map<String, Integer> map, final String s ) {
302 if ( map.containsKey( s ) ) {
303 map.put( s, map.get( s ) + 1 );
310 public static int calculateOverlap( final Domain domain, final List<Boolean> covered_positions ) {
311 int overlap_count = 0;
312 for( int i = domain.getFrom(); i <= domain.getTo(); ++i ) {
313 if ( ( i < covered_positions.size() ) && ( covered_positions.get( i ) == true ) ) {
317 return overlap_count;
320 public static void checkForOutputFileWriteability( final File outfile ) {
321 final String error = ForesterUtil.isWritableFile( outfile );
322 if ( !ForesterUtil.isEmpty( error ) ) {
323 ForesterUtil.fatalError( surfacing.PRG_NAME, error );
327 private static SortedSet<String> collectAllDomainsChangedOnSubtree( final PhylogenyNode subtree_root,
328 final boolean get_gains ) {
329 final SortedSet<String> domains = new TreeSet<String>();
330 for( final PhylogenyNode descendant : PhylogenyMethods.getAllDescendants( subtree_root ) ) {
331 final BinaryCharacters chars = descendant.getNodeData().getBinaryCharacters();
333 domains.addAll( chars.getGainedCharacters() );
336 domains.addAll( chars.getLostCharacters() );
342 public static void collectChangedDomainCombinationsFromBinaryStatesMatrixAsListToFile( final CharacterStateMatrix<CharacterStateMatrix.GainLossStates> matrix,
343 final BinaryDomainCombination.DomainCombinationType dc_type,
344 final List<BinaryDomainCombination> all_binary_domains_combination_gained,
345 final boolean get_gains ) {
346 final SortedSet<String> sorted_ids = new TreeSet<String>();
347 for( int i = 0; i < matrix.getNumberOfIdentifiers(); ++i ) {
348 sorted_ids.add( matrix.getIdentifier( i ) );
350 for( final String id : sorted_ids ) {
351 for( int c = 0; c < matrix.getNumberOfCharacters(); ++c ) {
352 if ( ( get_gains && ( matrix.getState( id, c ) == CharacterStateMatrix.GainLossStates.GAIN ) )
353 || ( !get_gains && ( matrix.getState( id, c ) == CharacterStateMatrix.GainLossStates.LOSS ) ) ) {
354 if ( dc_type == BinaryDomainCombination.DomainCombinationType.DIRECTED_ADJACTANT ) {
355 all_binary_domains_combination_gained.add( AdjactantDirectedBinaryDomainCombination
356 .createInstance( matrix.getCharacter( c ) ) );
358 else if ( dc_type == BinaryDomainCombination.DomainCombinationType.DIRECTED ) {
359 all_binary_domains_combination_gained.add( DirectedBinaryDomainCombination
360 .createInstance( matrix.getCharacter( c ) ) );
363 all_binary_domains_combination_gained.add( BasicBinaryDomainCombination.createInstance( matrix
364 .getCharacter( c ) ) );
371 private static File createBaseDirForPerNodeDomainFiles( final String base_dir,
372 final boolean domain_combinations,
373 final CharacterStateMatrix.GainLossStates state,
374 final String outfile ) {
375 File per_node_go_mapped_domain_gain_loss_files_base_dir = new File( new File( outfile ).getParent()
376 + ForesterUtil.FILE_SEPARATOR + base_dir );
377 if ( !per_node_go_mapped_domain_gain_loss_files_base_dir.exists() ) {
378 per_node_go_mapped_domain_gain_loss_files_base_dir.mkdir();
380 if ( domain_combinations ) {
381 per_node_go_mapped_domain_gain_loss_files_base_dir = new File( per_node_go_mapped_domain_gain_loss_files_base_dir
382 + ForesterUtil.FILE_SEPARATOR + "DC" );
385 per_node_go_mapped_domain_gain_loss_files_base_dir = new File( per_node_go_mapped_domain_gain_loss_files_base_dir
386 + ForesterUtil.FILE_SEPARATOR + "DOMAINS" );
388 if ( !per_node_go_mapped_domain_gain_loss_files_base_dir.exists() ) {
389 per_node_go_mapped_domain_gain_loss_files_base_dir.mkdir();
391 if ( state == GainLossStates.GAIN ) {
392 per_node_go_mapped_domain_gain_loss_files_base_dir = new File( per_node_go_mapped_domain_gain_loss_files_base_dir
393 + ForesterUtil.FILE_SEPARATOR + "GAINS" );
395 else if ( state == GainLossStates.LOSS ) {
396 per_node_go_mapped_domain_gain_loss_files_base_dir = new File( per_node_go_mapped_domain_gain_loss_files_base_dir
397 + ForesterUtil.FILE_SEPARATOR + "LOSSES" );
400 per_node_go_mapped_domain_gain_loss_files_base_dir = new File( per_node_go_mapped_domain_gain_loss_files_base_dir
401 + ForesterUtil.FILE_SEPARATOR + "PRESENT" );
403 if ( !per_node_go_mapped_domain_gain_loss_files_base_dir.exists() ) {
404 per_node_go_mapped_domain_gain_loss_files_base_dir.mkdir();
406 return per_node_go_mapped_domain_gain_loss_files_base_dir;
409 public static Map<DomainId, List<GoId>> createDomainIdToGoIdMap( final List<PfamToGoMapping> pfam_to_go_mappings ) {
410 final Map<DomainId, List<GoId>> domain_id_to_go_ids_map = new HashMap<DomainId, List<GoId>>( pfam_to_go_mappings
412 for( final PfamToGoMapping pfam_to_go : pfam_to_go_mappings ) {
413 if ( !domain_id_to_go_ids_map.containsKey( pfam_to_go.getKey() ) ) {
414 domain_id_to_go_ids_map.put( pfam_to_go.getKey(), new ArrayList<GoId>() );
416 domain_id_to_go_ids_map.get( pfam_to_go.getKey() ).add( pfam_to_go.getValue() );
418 return domain_id_to_go_ids_map;
421 public static Map<DomainId, Set<String>> createDomainIdToSecondaryFeaturesMap( final File secondary_features_map_file )
423 final BasicTable<String> primary_table = BasicTableParser.parse( secondary_features_map_file, "\t" );
424 final Map<DomainId, Set<String>> map = new TreeMap<DomainId, Set<String>>();
425 for( int r = 0; r < primary_table.getNumberOfRows(); ++r ) {
426 final DomainId domain_id = new DomainId( primary_table.getValue( 0, r ) );
427 if ( !map.containsKey( domain_id ) ) {
428 map.put( domain_id, new HashSet<String>() );
430 map.get( domain_id ).add( primary_table.getValue( 1, r ) );
435 public static Phylogeny createNjTreeBasedOnMatrixToFile( final File nj_tree_outfile, final DistanceMatrix distance ) {
436 checkForOutputFileWriteability( nj_tree_outfile );
437 final NeighborJoining nj = NeighborJoining.createInstance();
438 final Phylogeny phylogeny = nj.execute( distance );
439 phylogeny.setName( nj_tree_outfile.getName() );
440 writePhylogenyToFile( phylogeny, nj_tree_outfile.toString() );
444 private static SortedSet<BinaryDomainCombination> createSetOfAllBinaryDomainCombinationsPerGenome( final GenomeWideCombinableDomains gwcd ) {
445 final SortedMap<DomainId, CombinableDomains> cds = gwcd.getAllCombinableDomainsIds();
446 final SortedSet<BinaryDomainCombination> binary_combinations = new TreeSet<BinaryDomainCombination>();
447 for( final DomainId domain_id : cds.keySet() ) {
448 final CombinableDomains cd = cds.get( domain_id );
449 binary_combinations.addAll( cd.toBinaryDomainCombinations() );
451 return binary_combinations;
454 public static void decoratePrintableDomainSimilarities( final SortedSet<DomainSimilarity> domain_similarities,
455 final Detailedness detailedness,
456 final GoAnnotationOutput go_annotation_output,
457 final Map<GoId, GoTerm> go_id_to_term_map,
458 final GoNameSpace go_namespace_limit ) {
459 if ( ( go_namespace_limit != null ) && ( ( go_id_to_term_map == null ) || go_id_to_term_map.isEmpty() ) ) {
460 throw new IllegalArgumentException( "attempt to use a GO namespace limit without a GO id to term map" );
462 for( final DomainSimilarity domain_similarity : domain_similarities ) {
463 if ( domain_similarity instanceof PrintableDomainSimilarity ) {
464 final PrintableDomainSimilarity printable_domain_similarity = ( PrintableDomainSimilarity ) domain_similarity;
465 printable_domain_similarity.setDetailedness( detailedness );
466 printable_domain_similarity.setGoAnnotationOutput( go_annotation_output );
467 printable_domain_similarity.setGoIdToTermMap( go_id_to_term_map );
468 printable_domain_similarity.setGoNamespaceLimit( go_namespace_limit );
473 public static void executeDomainLengthAnalysis( final String[][] input_file_properties,
474 final int number_of_genomes,
475 final DomainLengthsTable domain_lengths_table,
476 final File outfile ) throws IOException {
477 final DecimalFormat df = new DecimalFormat( "#.00" );
478 checkForOutputFileWriteability( outfile );
479 final BufferedWriter out = new BufferedWriter( new FileWriter( outfile ) );
480 out.write( "MEAN BASED STATISTICS PER SPECIES" );
481 out.write( ForesterUtil.LINE_SEPARATOR );
482 out.write( domain_lengths_table.createMeanBasedStatisticsPerSpeciesTable().toString() );
483 out.write( ForesterUtil.LINE_SEPARATOR );
484 out.write( ForesterUtil.LINE_SEPARATOR );
485 final List<DomainLengths> domain_lengths_list = domain_lengths_table.getDomainLengthsList();
486 out.write( "OUTLIER SPECIES PER DOMAIN (Z>=1.5)" );
487 out.write( ForesterUtil.LINE_SEPARATOR );
488 for( final DomainLengths domain_lengths : domain_lengths_list ) {
489 final List<Species> species_list = domain_lengths.getMeanBasedOutlierSpecies( 1.5 );
490 if ( species_list.size() > 0 ) {
491 out.write( domain_lengths.getDomainId() + "\t" );
492 for( final Species species : species_list ) {
493 out.write( species + "\t" );
495 out.write( ForesterUtil.LINE_SEPARATOR );
496 // DescriptiveStatistics stats_for_domain = domain_lengths
497 // .calculateMeanBasedStatistics();
498 //AsciiHistogram histo = new AsciiHistogram( stats_for_domain );
499 //System.out.println( histo.toStringBuffer( 40, '=', 60, 4 ).toString() );
502 out.write( ForesterUtil.LINE_SEPARATOR );
503 out.write( ForesterUtil.LINE_SEPARATOR );
504 out.write( "OUTLIER SPECIES (Z 1.0)" );
505 out.write( ForesterUtil.LINE_SEPARATOR );
506 final DescriptiveStatistics stats_for_all_species = domain_lengths_table
507 .calculateMeanBasedStatisticsForAllSpecies();
508 out.write( stats_for_all_species.asSummary() );
509 out.write( ForesterUtil.LINE_SEPARATOR );
510 final AsciiHistogram histo = new AsciiHistogram( stats_for_all_species );
511 out.write( histo.toStringBuffer( 40, '=', 60, 4 ).toString() );
512 out.write( ForesterUtil.LINE_SEPARATOR );
513 final double population_sd = stats_for_all_species.sampleStandardDeviation();
514 final double population_mean = stats_for_all_species.arithmeticMean();
515 for( final Species species : domain_lengths_table.getSpecies() ) {
516 final double x = domain_lengths_table.calculateMeanBasedStatisticsForSpecies( species ).arithmeticMean();
517 final double z = ( x - population_mean ) / population_sd;
518 out.write( species + "\t" + z );
519 out.write( ForesterUtil.LINE_SEPARATOR );
521 out.write( ForesterUtil.LINE_SEPARATOR );
522 for( final Species species : domain_lengths_table.getSpecies() ) {
523 final DescriptiveStatistics stats_for_species = domain_lengths_table
524 .calculateMeanBasedStatisticsForSpecies( species );
525 final double x = stats_for_species.arithmeticMean();
526 final double z = ( x - population_mean ) / population_sd;
527 if ( ( z <= -1.0 ) || ( z >= 1.0 ) ) {
528 out.write( species + "\t" + df.format( z ) + "\t" + stats_for_species.asSummary() );
529 out.write( ForesterUtil.LINE_SEPARATOR );
533 // final List<HistogramData> histogram_datas = new ArrayList<HistogramData>();
534 // for( int i = 0; i < number_of_genomes; ++i ) {
535 // final Species species = new BasicSpecies( input_file_properties[ i ][ 0 ] );
537 // .add( new HistogramData( species.toString(), domain_lengths_table
538 // .calculateMeanBasedStatisticsForSpecies( species )
539 // .getDataAsDoubleArray(), 5, 600, null, 60 ) );
541 // final HistogramsFrame hf = new HistogramsFrame( histogram_datas );
542 // hf.setVisible( true );
548 * @param all_binary_domains_combination_lost_fitch
549 * @param consider_directedness_and_adjacency_for_bin_combinations
550 * @param all_binary_domains_combination_gained if null ignored, otherwise this is to list all binary domain combinations
551 * which were gained under unweighted (Fitch) parsimony.
553 public static void executeParsimonyAnalysis( final long random_number_seed_for_fitch_parsimony,
554 final boolean radomize_fitch_parsimony,
555 final String outfile_name,
556 final DomainParsimonyCalculator domain_parsimony,
557 final Phylogeny phylogeny,
558 final Map<DomainId, List<GoId>> domain_id_to_go_ids_map,
559 final Map<GoId, GoTerm> go_id_to_term_map,
560 final GoNameSpace go_namespace_limit,
561 final String parameters_str,
562 final Map<DomainId, Set<String>>[] domain_id_to_secondary_features_maps,
563 final SortedSet<DomainId> positive_filter,
564 final boolean output_binary_domain_combinations_for_graphs,
565 final List<BinaryDomainCombination> all_binary_domains_combination_gained_fitch,
566 final List<BinaryDomainCombination> all_binary_domains_combination_lost_fitch,
567 final BinaryDomainCombination.DomainCombinationType dc_type ) {
568 final String sep = ForesterUtil.LINE_SEPARATOR + "###################" + ForesterUtil.LINE_SEPARATOR;
569 final String date_time = ForesterUtil.getCurrentDateTime();
570 final SortedSet<String> all_pfams_encountered = new TreeSet<String>();
571 final SortedSet<String> all_pfams_gained_as_domains = new TreeSet<String>();
572 final SortedSet<String> all_pfams_lost_as_domains = new TreeSet<String>();
573 final SortedSet<String> all_pfams_gained_as_dom_combinations = new TreeSet<String>();
574 final SortedSet<String> all_pfams_lost_as_dom_combinations = new TreeSet<String>();
575 writeToNexus( outfile_name, domain_parsimony, phylogeny );
578 Phylogeny local_phylogeny_l = phylogeny.copy();
579 if ( ( positive_filter != null ) && ( positive_filter.size() > 0 ) ) {
580 domain_parsimony.executeDolloParsimonyOnDomainPresence( positive_filter );
583 domain_parsimony.executeDolloParsimonyOnDomainPresence();
585 SurfacingUtil.writeMatrixToFile( domain_parsimony.getGainLossMatrix(), outfile_name
586 + surfacing.PARSIMONY_OUTPUT_GL_SUFFIX_DOLLO_DOMAINS, Format.FORESTER );
587 SurfacingUtil.writeMatrixToFile( domain_parsimony.getGainLossCountsMatrix(), outfile_name
588 + surfacing.PARSIMONY_OUTPUT_GL_COUNTS_SUFFIX_DOLLO_DOMAINS, Format.FORESTER );
589 SurfacingUtil.writeBinaryStatesMatrixAsListToFile( domain_parsimony.getGainLossMatrix(),
590 CharacterStateMatrix.GainLossStates.GAIN,
591 outfile_name + surfacing.PARSIMONY_OUTPUT_DOLLO_GAINS_D,
593 ForesterUtil.LINE_SEPARATOR,
595 SurfacingUtil.writeBinaryStatesMatrixAsListToFile( domain_parsimony.getGainLossMatrix(),
596 CharacterStateMatrix.GainLossStates.LOSS,
597 outfile_name + surfacing.PARSIMONY_OUTPUT_DOLLO_LOSSES_D,
599 ForesterUtil.LINE_SEPARATOR,
601 SurfacingUtil.writeBinaryStatesMatrixAsListToFile( domain_parsimony.getGainLossMatrix(), null, outfile_name
602 + surfacing.PARSIMONY_OUTPUT_DOLLO_PRESENT_D, sep, ForesterUtil.LINE_SEPARATOR, null );
604 writeBinaryStatesMatrixToList( domain_id_to_go_ids_map,
608 domain_parsimony.getGainLossMatrix(),
609 CharacterStateMatrix.GainLossStates.GAIN,
610 outfile_name + surfacing.PARSIMONY_OUTPUT_DOLLO_GAINS_HTML_D,
612 ForesterUtil.LINE_SEPARATOR,
613 "Dollo Parsimony | Gains | Domains",
615 domain_id_to_secondary_features_maps,
616 all_pfams_encountered,
617 all_pfams_gained_as_domains,
619 writeBinaryStatesMatrixToList( domain_id_to_go_ids_map,
623 domain_parsimony.getGainLossMatrix(),
624 CharacterStateMatrix.GainLossStates.LOSS,
625 outfile_name + surfacing.PARSIMONY_OUTPUT_DOLLO_LOSSES_HTML_D,
627 ForesterUtil.LINE_SEPARATOR,
628 "Dollo Parsimony | Losses | Domains",
630 domain_id_to_secondary_features_maps,
631 all_pfams_encountered,
632 all_pfams_lost_as_domains,
634 writeBinaryStatesMatrixToList( domain_id_to_go_ids_map,
638 domain_parsimony.getGainLossMatrix(),
640 outfile_name + surfacing.PARSIMONY_OUTPUT_DOLLO_PRESENT_HTML_D,
642 ForesterUtil.LINE_SEPARATOR,
643 "Dollo Parsimony | Present | Domains",
645 domain_id_to_secondary_features_maps,
646 all_pfams_encountered,
648 "_dollo_present_d" );
649 preparePhylogeny( local_phylogeny_l,
652 "Dollo parsimony on domain presence/absence",
653 "dollo_on_domains_" + outfile_name,
655 SurfacingUtil.writePhylogenyToFile( local_phylogeny_l, outfile_name
656 + surfacing.DOMAINS_PARSIMONY_TREE_OUTPUT_SUFFIX_DOLLO );
658 writeAllDomainsChangedOnAllSubtrees( local_phylogeny_l, true, outfile_name, "_dollo_all_gains_d" );
659 writeAllDomainsChangedOnAllSubtrees( local_phylogeny_l, false, outfile_name, "_dollo_all_losses_d" );
661 catch ( final IOException e ) {
663 ForesterUtil.fatalError( surfacing.PRG_NAME, e.getLocalizedMessage() );
665 if ( domain_parsimony.calculateNumberOfBinaryDomainCombination() > 0 ) {
666 // FITCH DOMAIN COMBINATIONS
667 // -------------------------
668 local_phylogeny_l = phylogeny.copy();
669 String randomization = "no";
670 if ( radomize_fitch_parsimony ) {
671 domain_parsimony.executeFitchParsimonyOnBinaryDomainCombintion( random_number_seed_for_fitch_parsimony );
672 randomization = "yes, seed = " + random_number_seed_for_fitch_parsimony;
675 domain_parsimony.executeFitchParsimonyOnBinaryDomainCombintion( false );
677 SurfacingUtil.writeMatrixToFile( domain_parsimony.getGainLossMatrix(), outfile_name
678 + surfacing.PARSIMONY_OUTPUT_GL_SUFFIX_FITCH_BINARY_COMBINATIONS, Format.FORESTER );
679 SurfacingUtil.writeMatrixToFile( domain_parsimony.getGainLossCountsMatrix(), outfile_name
680 + surfacing.PARSIMONY_OUTPUT_GL_COUNTS_SUFFIX_FITCH_BINARY_COMBINATIONS, Format.FORESTER );
682 .writeBinaryStatesMatrixAsListToFile( domain_parsimony.getGainLossMatrix(),
683 CharacterStateMatrix.GainLossStates.GAIN,
684 outfile_name + surfacing.PARSIMONY_OUTPUT_FITCH_GAINS_BC,
686 ForesterUtil.LINE_SEPARATOR,
688 SurfacingUtil.writeBinaryStatesMatrixAsListToFile( domain_parsimony.getGainLossMatrix(),
689 CharacterStateMatrix.GainLossStates.LOSS,
691 + surfacing.PARSIMONY_OUTPUT_FITCH_LOSSES_BC,
693 ForesterUtil.LINE_SEPARATOR,
695 SurfacingUtil.writeBinaryStatesMatrixAsListToFile( domain_parsimony.getGainLossMatrix(), null, outfile_name
696 + surfacing.PARSIMONY_OUTPUT_FITCH_PRESENT_BC, sep, ForesterUtil.LINE_SEPARATOR, null );
697 if ( all_binary_domains_combination_gained_fitch != null ) {
698 collectChangedDomainCombinationsFromBinaryStatesMatrixAsListToFile( domain_parsimony.getGainLossMatrix(),
700 all_binary_domains_combination_gained_fitch,
703 if ( all_binary_domains_combination_lost_fitch != null ) {
704 collectChangedDomainCombinationsFromBinaryStatesMatrixAsListToFile( domain_parsimony.getGainLossMatrix(),
706 all_binary_domains_combination_lost_fitch,
709 if ( output_binary_domain_combinations_for_graphs ) {
711 .writeBinaryStatesMatrixAsListToFileForBinaryCombinationsForGraphAnalysis( domain_parsimony
712 .getGainLossMatrix(),
715 + surfacing.PARSIMONY_OUTPUT_FITCH_PRESENT_BC_OUTPUTFILE_SUFFIX_FOR_GRAPH_ANALYSIS,
717 ForesterUtil.LINE_SEPARATOR,
718 BinaryDomainCombination.OutputFormat.DOT );
721 writeBinaryStatesMatrixToList( domain_id_to_go_ids_map,
725 domain_parsimony.getGainLossMatrix(),
726 CharacterStateMatrix.GainLossStates.GAIN,
727 outfile_name + surfacing.PARSIMONY_OUTPUT_FITCH_GAINS_HTML_BC,
729 ForesterUtil.LINE_SEPARATOR,
730 "Fitch Parsimony | Gains | Domain Combinations",
733 all_pfams_encountered,
734 all_pfams_gained_as_dom_combinations,
736 writeBinaryStatesMatrixToList( domain_id_to_go_ids_map,
740 domain_parsimony.getGainLossMatrix(),
741 CharacterStateMatrix.GainLossStates.LOSS,
742 outfile_name + surfacing.PARSIMONY_OUTPUT_FITCH_LOSSES_HTML_BC,
744 ForesterUtil.LINE_SEPARATOR,
745 "Fitch Parsimony | Losses | Domain Combinations",
748 all_pfams_encountered,
749 all_pfams_lost_as_dom_combinations,
750 "_fitch_losses_dc" );
751 writeBinaryStatesMatrixToList( domain_id_to_go_ids_map,
755 domain_parsimony.getGainLossMatrix(),
757 outfile_name + surfacing.PARSIMONY_OUTPUT_FITCH_PRESENT_HTML_BC,
759 ForesterUtil.LINE_SEPARATOR,
760 "Fitch Parsimony | Present | Domain Combinations",
763 all_pfams_encountered,
765 "_fitch_present_dc" );
766 writeAllEncounteredPfamsToFile( domain_id_to_go_ids_map,
769 all_pfams_encountered );
770 writePfamsToFile( outfile_name + surfacing.ALL_PFAMS_GAINED_AS_DOMAINS_SUFFIX, all_pfams_gained_as_domains );
771 writePfamsToFile( outfile_name + surfacing.ALL_PFAMS_LOST_AS_DOMAINS_SUFFIX, all_pfams_lost_as_domains );
772 writePfamsToFile( outfile_name + surfacing.ALL_PFAMS_GAINED_AS_DC_SUFFIX,
773 all_pfams_gained_as_dom_combinations );
774 writePfamsToFile( outfile_name + surfacing.ALL_PFAMS_LOST_AS_DC_SUFFIX, all_pfams_lost_as_dom_combinations );
775 preparePhylogeny( local_phylogeny_l,
778 "Fitch parsimony on binary domain combination presence/absence randomization: "
780 "fitch_on_binary_domain_combinations_" + outfile_name,
782 SurfacingUtil.writePhylogenyToFile( local_phylogeny_l, outfile_name
783 + surfacing.BINARY_DOMAIN_COMBINATIONS_PARSIMONY_TREE_OUTPUT_SUFFIX_FITCH );
784 calculateIndependentDomainCombinationGains( local_phylogeny_l, outfile_name
785 + surfacing.INDEPENDENT_DC_GAINS_FITCH_PARS_COUNTS_OUTPUT_SUFFIX, outfile_name
786 + surfacing.INDEPENDENT_DC_GAINS_FITCH_PARS_DC_OUTPUT_SUFFIX, outfile_name
787 + surfacing.INDEPENDENT_DC_GAINS_FITCH_PARS_DC_FOR_GO_MAPPING_OUTPUT_SUFFIX, outfile_name
788 + surfacing.INDEPENDENT_DC_GAINS_FITCH_PARS_DC_FOR_GO_MAPPING_OUTPUT_UNIQUE_SUFFIX, outfile_name
789 + "_indep_dc_gains_fitch_lca_ranks.txt", outfile_name + "_indep_dc_gains_fitch_lca_taxonomies.txt" );
793 public static void executeParsimonyAnalysisForSecondaryFeatures( final String outfile_name,
794 final DomainParsimonyCalculator secondary_features_parsimony,
795 final Phylogeny phylogeny,
796 final String parameters_str,
797 final Map<Species, MappingResults> mapping_results_map ) {
798 final String sep = ForesterUtil.LINE_SEPARATOR + "###################" + ForesterUtil.LINE_SEPARATOR;
799 final String date_time = ForesterUtil.getCurrentDateTime();
800 System.out.println();
801 writeToNexus( outfile_name + surfacing.NEXUS_SECONDARY_FEATURES,
802 secondary_features_parsimony.createMatrixOfSecondaryFeaturePresenceOrAbsence( null ),
804 final Phylogeny local_phylogeny_copy = phylogeny.copy();
805 secondary_features_parsimony.executeDolloParsimonyOnSecondaryFeatures( mapping_results_map );
806 SurfacingUtil.writeMatrixToFile( secondary_features_parsimony.getGainLossMatrix(), outfile_name
807 + surfacing.PARSIMONY_OUTPUT_GL_SUFFIX_DOLLO_SECONDARY_FEATURES, Format.FORESTER );
808 SurfacingUtil.writeMatrixToFile( secondary_features_parsimony.getGainLossCountsMatrix(), outfile_name
809 + surfacing.PARSIMONY_OUTPUT_GL_COUNTS_SUFFIX_DOLLO_SECONDARY_FEATURES, Format.FORESTER );
811 .writeBinaryStatesMatrixAsListToFile( secondary_features_parsimony.getGainLossMatrix(),
812 CharacterStateMatrix.GainLossStates.GAIN,
814 + surfacing.PARSIMONY_OUTPUT_DOLLO_GAINS_SECONDARY_FEATURES,
816 ForesterUtil.LINE_SEPARATOR,
819 .writeBinaryStatesMatrixAsListToFile( secondary_features_parsimony.getGainLossMatrix(),
820 CharacterStateMatrix.GainLossStates.LOSS,
822 + surfacing.PARSIMONY_OUTPUT_DOLLO_LOSSES_SECONDARY_FEATURES,
824 ForesterUtil.LINE_SEPARATOR,
827 .writeBinaryStatesMatrixAsListToFile( secondary_features_parsimony.getGainLossMatrix(),
830 + surfacing.PARSIMONY_OUTPUT_DOLLO_PRESENT_SECONDARY_FEATURES,
832 ForesterUtil.LINE_SEPARATOR,
834 preparePhylogeny( local_phylogeny_copy,
835 secondary_features_parsimony,
837 "Dollo parsimony on secondary feature presence/absence",
838 "dollo_on_secondary_features_" + outfile_name,
840 SurfacingUtil.writePhylogenyToFile( local_phylogeny_copy, outfile_name
841 + surfacing.SECONDARY_FEATURES_PARSIMONY_TREE_OUTPUT_SUFFIX_DOLLO );
844 public static void extractProteinNames( final List<Protein> proteins,
845 final List<DomainId> query_domain_ids_nc_order,
847 final String separator ) throws IOException {
848 for( final Protein protein : proteins ) {
849 if ( protein.contains( query_domain_ids_nc_order, true ) ) {
850 out.write( protein.getSpecies().getSpeciesId() );
851 out.write( separator );
852 out.write( protein.getProteinId().getId() );
853 out.write( separator );
855 final Set<DomainId> visited_domain_ids = new HashSet<DomainId>();
856 boolean first = true;
857 for( final Domain domain : protein.getProteinDomains() ) {
858 if ( !visited_domain_ids.contains( domain.getDomainId() ) ) {
859 visited_domain_ids.add( domain.getDomainId() );
866 out.write( domain.getDomainId().getId() );
868 out.write( "" + domain.getTotalCount() );
873 out.write( separator );
874 if ( !( ForesterUtil.isEmpty( protein.getDescription() ) || protein.getDescription()
875 .equals( SurfacingConstants.NONE ) ) ) {
876 out.write( protein.getDescription() );
878 out.write( separator );
879 if ( !( ForesterUtil.isEmpty( protein.getAccession() ) || protein.getAccession()
880 .equals( SurfacingConstants.NONE ) ) ) {
881 out.write( protein.getAccession() );
883 out.write( SurfacingConstants.NL );
889 public static void extractProteinNames( final SortedMap<Species, List<Protein>> protein_lists_per_species,
890 final DomainId domain_id,
892 final String separator ) throws IOException {
893 for( final Species species : protein_lists_per_species.keySet() ) {
894 for( final Protein protein : protein_lists_per_species.get( species ) ) {
895 final List<Domain> domains = protein.getProteinDomains( domain_id );
896 if ( domains.size() > 0 ) {
897 final DescriptiveStatistics stats = new BasicDescriptiveStatistics();
898 for( final Domain domain : domains ) {
899 stats.addValue( domain.getPerSequenceEvalue() );
901 out.write( protein.getSpecies().getSpeciesId() );
902 out.write( separator );
903 out.write( protein.getProteinId().getId() );
904 out.write( separator );
905 out.write( "[" + FORMATTER.format( stats.median() ) + "]" );
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 SortedSet<DomainId> getAllDomainIds( final List<GenomeWideCombinableDomains> gwcd_list ) {
924 final SortedSet<DomainId> all_domains_ids = new TreeSet<DomainId>();
925 for( final GenomeWideCombinableDomains gwcd : gwcd_list ) {
926 final Set<DomainId> all_domains = gwcd.getAllDomainIds();
927 // for( final Domain domain : all_domains ) {
928 all_domains_ids.addAll( all_domains );
931 return all_domains_ids;
934 public static SortedMap<String, Integer> getDomainCounts( final List<Protein> protein_domain_collections ) {
935 final SortedMap<String, Integer> map = new TreeMap<String, Integer>();
936 for( final Protein protein_domain_collection : protein_domain_collections ) {
937 for( final Object name : protein_domain_collection.getProteinDomains() ) {
938 final BasicDomain protein_domain = ( BasicDomain ) name;
939 final String id = protein_domain.getDomainId().getId();
940 if ( map.containsKey( id ) ) {
941 map.put( id, map.get( id ) + 1 );
951 public static int getNumberOfNodesLackingName( final Phylogeny p, final StringBuilder names ) {
952 final PhylogenyNodeIterator it = p.iteratorPostorder();
954 while ( it.hasNext() ) {
955 final PhylogenyNode n = it.next();
956 if ( ForesterUtil.isEmpty( n.getName() )
957 && ( !n.getNodeData().isHasTaxonomy() || ForesterUtil.isEmpty( n.getNodeData().getTaxonomy()
958 .getScientificName() ) )
959 && ( !n.getNodeData().isHasTaxonomy() || ForesterUtil.isEmpty( n.getNodeData().getTaxonomy()
960 .getCommonName() ) ) ) {
961 if ( n.getParent() != null ) {
963 names.append( n.getParent().getName() );
965 final List l = n.getAllExternalDescendants();
966 for( final Object object : l ) {
967 System.out.println( l.toString() );
976 * Returns true is Domain domain falls in an uninterrupted stretch of
980 * @param covered_positions
983 public static boolean isEngulfed( final Domain domain, final List<Boolean> covered_positions ) {
984 for( int i = domain.getFrom(); i <= domain.getTo(); ++i ) {
985 if ( ( i >= covered_positions.size() ) || ( covered_positions.get( i ) != true ) ) {
992 public static void preparePhylogeny( final Phylogeny p,
993 final DomainParsimonyCalculator domain_parsimony,
994 final String date_time,
997 final String parameters_str ) {
998 domain_parsimony.decoratePhylogenyWithDomains( p );
999 final StringBuilder desc = new StringBuilder();
1000 desc.append( "[Method: " + method + "] [Date: " + date_time + "] " );
1001 desc.append( "[Cost: " + domain_parsimony.getCost() + "] " );
1002 desc.append( "[Gains: " + domain_parsimony.getTotalGains() + "] " );
1003 desc.append( "[Losses: " + domain_parsimony.getTotalLosses() + "] " );
1004 desc.append( "[Unchanged: " + domain_parsimony.getTotalUnchanged() + "] " );
1005 desc.append( "[Parameters: " + parameters_str + "]" );
1007 p.setDescription( desc.toString() );
1008 p.setConfidence( new Confidence( domain_parsimony.getCost(), "parsimony" ) );
1009 p.setRerootable( false );
1010 p.setRooted( true );
1014 * species | protein id | n-terminal domain | c-terminal domain | n-terminal domain per domain E-value | c-terminal domain per domain E-value
1018 static public StringBuffer proteinToDomainCombinations( final Protein protein,
1019 final String protein_id,
1020 final String separator ) {
1021 final StringBuffer sb = new StringBuffer();
1022 if ( protein.getSpecies() == null ) {
1023 throw new IllegalArgumentException( "species must not be null" );
1025 if ( ForesterUtil.isEmpty( protein.getSpecies().getSpeciesId() ) ) {
1026 throw new IllegalArgumentException( "species id must not be empty" );
1028 final List<Domain> domains = protein.getProteinDomains();
1029 if ( domains.size() > 1 ) {
1030 final Map<String, Integer> counts = new HashMap<String, Integer>();
1031 for( final Domain domain : domains ) {
1032 final String id = domain.getDomainId().getId();
1033 if ( counts.containsKey( id ) ) {
1034 counts.put( id, counts.get( id ) + 1 );
1037 counts.put( id, 1 );
1040 final Set<String> dcs = new HashSet<String>();
1041 for( int i = 1; i < domains.size(); ++i ) {
1042 for( int j = 0; j < i; ++j ) {
1043 Domain domain_n = domains.get( i );
1044 Domain domain_c = domains.get( j );
1045 if ( domain_n.getFrom() > domain_c.getFrom() ) {
1046 domain_n = domains.get( j );
1047 domain_c = domains.get( i );
1049 final String dc = domain_n.getDomainId().getId() + domain_c.getDomainId().getId();
1050 if ( !dcs.contains( dc ) ) {
1052 sb.append( protein.getSpecies() );
1053 sb.append( separator );
1054 sb.append( protein_id );
1055 sb.append( separator );
1056 sb.append( domain_n.getDomainId().getId() );
1057 sb.append( separator );
1058 sb.append( domain_c.getDomainId().getId() );
1059 sb.append( separator );
1060 sb.append( domain_n.getPerDomainEvalue() );
1061 sb.append( separator );
1062 sb.append( domain_c.getPerDomainEvalue() );
1063 sb.append( separator );
1064 sb.append( counts.get( domain_n.getDomainId().getId() ) );
1065 sb.append( separator );
1066 sb.append( counts.get( domain_c.getDomainId().getId() ) );
1067 sb.append( ForesterUtil.LINE_SEPARATOR );
1072 else if ( domains.size() == 1 ) {
1073 sb.append( protein.getSpecies() );
1074 sb.append( separator );
1075 sb.append( protein_id );
1076 sb.append( separator );
1077 sb.append( domains.get( 0 ).getDomainId().getId() );
1078 sb.append( separator );
1079 sb.append( separator );
1080 sb.append( domains.get( 0 ).getPerDomainEvalue() );
1081 sb.append( separator );
1082 sb.append( separator );
1084 sb.append( separator );
1085 sb.append( ForesterUtil.LINE_SEPARATOR );
1088 sb.append( protein.getSpecies() );
1089 sb.append( separator );
1090 sb.append( protein_id );
1091 sb.append( separator );
1092 sb.append( separator );
1093 sb.append( separator );
1094 sb.append( separator );
1095 sb.append( separator );
1096 sb.append( separator );
1097 sb.append( ForesterUtil.LINE_SEPARATOR );
1104 * Example regarding engulfment: ------------0.1 ----------0.2 --0.3 =>
1105 * domain with 0.3 is ignored
1107 * -----------0.1 ----------0.2 --0.3 => domain with 0.3 is ignored
1110 * ------------0.1 ----------0.3 --0.2 => domains with 0.3 and 0.2 are _not_
1113 * @param max_allowed_overlap
1114 * maximal allowed overlap (inclusive) to be still considered not
1115 * overlapping (zero or negative value to allow any overlap)
1116 * @param remove_engulfed_domains
1117 * to remove domains which are completely engulfed by coverage of
1118 * domains with better support
1122 public static Protein removeOverlappingDomains( final int max_allowed_overlap,
1123 final boolean remove_engulfed_domains,
1124 final Protein protein ) {
1125 final Protein pruned_protein = new BasicProtein( protein.getProteinId().getId(), protein.getSpecies()
1127 final List<Domain> sorted = SurfacingUtil.sortDomainsWithAscendingConfidenceValues( protein );
1128 final List<Boolean> covered_positions = new ArrayList<Boolean>();
1129 for( final Domain domain : sorted ) {
1130 if ( ( ( max_allowed_overlap < 0 ) || ( SurfacingUtil.calculateOverlap( domain, covered_positions ) <= max_allowed_overlap ) )
1131 && ( !remove_engulfed_domains || !isEngulfed( domain, covered_positions ) ) ) {
1132 final int covered_positions_size = covered_positions.size();
1133 for( int i = covered_positions_size; i < domain.getFrom(); ++i ) {
1134 covered_positions.add( false );
1136 final int new_covered_positions_size = covered_positions.size();
1137 for( int i = domain.getFrom(); i <= domain.getTo(); ++i ) {
1138 if ( i < new_covered_positions_size ) {
1139 covered_positions.set( i, true );
1142 covered_positions.add( true );
1145 pruned_protein.addProteinDomain( domain );
1148 return pruned_protein;
1151 public static List<Domain> sortDomainsWithAscendingConfidenceValues( final Protein protein ) {
1152 final List<Domain> domains = new ArrayList<Domain>();
1153 for( final Domain d : protein.getProteinDomains() ) {
1156 Collections.sort( domains, SurfacingUtil.ASCENDING_CONFIDENCE_VALUE_ORDER );
1160 private static List<String> splitDomainCombination( final String dc ) {
1161 final String[] s = dc.split( "=" );
1162 if ( s.length != 2 ) {
1163 ForesterUtil.printErrorMessage( surfacing.PRG_NAME, "Stringyfied domain combination has illegal format: "
1167 final List<String> l = new ArrayList<String>( 2 );
1173 public static void writeAllDomainsChangedOnAllSubtrees( final Phylogeny p,
1174 final boolean get_gains,
1175 final String outdir,
1176 final String suffix_for_filename ) throws IOException {
1177 CharacterStateMatrix.GainLossStates state = CharacterStateMatrix.GainLossStates.GAIN;
1179 state = CharacterStateMatrix.GainLossStates.LOSS;
1181 final File base_dir = createBaseDirForPerNodeDomainFiles( surfacing.BASE_DIRECTORY_PER_SUBTREE_DOMAIN_GAIN_LOSS_FILES,
1185 for( final PhylogenyNodeIterator it = p.iteratorPostorder(); it.hasNext(); ) {
1186 final PhylogenyNode node = it.next();
1187 if ( !node.isExternal() ) {
1188 final SortedSet<String> domains = collectAllDomainsChangedOnSubtree( node, get_gains );
1189 if ( domains.size() > 0 ) {
1190 final Writer writer = ForesterUtil.createBufferedWriter( base_dir + ForesterUtil.FILE_SEPARATOR
1191 + node.getName() + suffix_for_filename );
1192 for( final String domain : domains ) {
1193 writer.write( domain );
1194 writer.write( ForesterUtil.LINE_SEPARATOR );
1202 private static void writeAllEncounteredPfamsToFile( final Map<DomainId, List<GoId>> domain_id_to_go_ids_map,
1203 final Map<GoId, GoTerm> go_id_to_term_map,
1204 final String outfile_name,
1205 final SortedSet<String> all_pfams_encountered ) {
1206 final File all_pfams_encountered_file = new File( outfile_name + surfacing.ALL_PFAMS_ENCOUNTERED_SUFFIX );
1207 final File all_pfams_encountered_with_go_annotation_file = new File( outfile_name
1208 + surfacing.ALL_PFAMS_ENCOUNTERED_WITH_GO_ANNOTATION_SUFFIX );
1209 final File encountered_pfams_summary_file = new File( outfile_name + surfacing.ENCOUNTERED_PFAMS_SUMMARY_SUFFIX );
1210 int biological_process_counter = 0;
1211 int cellular_component_counter = 0;
1212 int molecular_function_counter = 0;
1213 int pfams_with_mappings_counter = 0;
1214 int pfams_without_mappings_counter = 0;
1215 int pfams_without_mappings_to_bp_or_mf_counter = 0;
1216 int pfams_with_mappings_to_bp_or_mf_counter = 0;
1218 final Writer all_pfams_encountered_writer = new BufferedWriter( new FileWriter( all_pfams_encountered_file ) );
1219 final Writer all_pfams_encountered_with_go_annotation_writer = new BufferedWriter( new FileWriter( all_pfams_encountered_with_go_annotation_file ) );
1220 final Writer summary_writer = new BufferedWriter( new FileWriter( encountered_pfams_summary_file ) );
1221 summary_writer.write( "# Pfam to GO mapping summary" );
1222 summary_writer.write( ForesterUtil.LINE_SEPARATOR );
1223 summary_writer.write( "# Actual summary is at the end of this file." );
1224 summary_writer.write( ForesterUtil.LINE_SEPARATOR );
1225 summary_writer.write( "# Encountered Pfams without a GO mapping:" );
1226 summary_writer.write( ForesterUtil.LINE_SEPARATOR );
1227 for( final String pfam : all_pfams_encountered ) {
1228 all_pfams_encountered_writer.write( pfam );
1229 all_pfams_encountered_writer.write( ForesterUtil.LINE_SEPARATOR );
1230 final DomainId domain_id = new DomainId( pfam );
1231 if ( domain_id_to_go_ids_map.containsKey( domain_id ) ) {
1232 ++pfams_with_mappings_counter;
1233 all_pfams_encountered_with_go_annotation_writer.write( pfam );
1234 all_pfams_encountered_with_go_annotation_writer.write( ForesterUtil.LINE_SEPARATOR );
1235 final List<GoId> go_ids = domain_id_to_go_ids_map.get( domain_id );
1236 boolean maps_to_bp = false;
1237 boolean maps_to_cc = false;
1238 boolean maps_to_mf = false;
1239 for( final GoId go_id : go_ids ) {
1240 final GoTerm go_term = go_id_to_term_map.get( go_id );
1241 if ( go_term.getGoNameSpace().isBiologicalProcess() ) {
1244 else if ( go_term.getGoNameSpace().isCellularComponent() ) {
1247 else if ( go_term.getGoNameSpace().isMolecularFunction() ) {
1252 ++biological_process_counter;
1255 ++cellular_component_counter;
1258 ++molecular_function_counter;
1260 if ( maps_to_bp || maps_to_mf ) {
1261 ++pfams_with_mappings_to_bp_or_mf_counter;
1264 ++pfams_without_mappings_to_bp_or_mf_counter;
1268 ++pfams_without_mappings_to_bp_or_mf_counter;
1269 ++pfams_without_mappings_counter;
1270 summary_writer.write( pfam );
1271 summary_writer.write( ForesterUtil.LINE_SEPARATOR );
1274 all_pfams_encountered_writer.close();
1275 all_pfams_encountered_with_go_annotation_writer.close();
1276 ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote all [" + all_pfams_encountered.size()
1277 + "] encountered Pfams to: \"" + all_pfams_encountered_file + "\"" );
1278 ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote all [" + pfams_with_mappings_counter
1279 + "] encountered Pfams with GO mappings to: \"" + all_pfams_encountered_with_go_annotation_file
1281 ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote summary (including all ["
1282 + pfams_without_mappings_counter + "] encountered Pfams without GO mappings) to: \""
1283 + encountered_pfams_summary_file + "\"" );
1284 ForesterUtil.programMessage( surfacing.PRG_NAME, "Sum of Pfams encountered : "
1285 + all_pfams_encountered.size() );
1286 ForesterUtil.programMessage( surfacing.PRG_NAME, "Pfams without a mapping : "
1287 + pfams_without_mappings_counter + " ["
1288 + ( 100 * pfams_without_mappings_counter / all_pfams_encountered.size() ) + "%]" );
1289 ForesterUtil.programMessage( surfacing.PRG_NAME, "Pfams without mapping to proc. or func. : "
1290 + pfams_without_mappings_to_bp_or_mf_counter + " ["
1291 + ( 100 * pfams_without_mappings_to_bp_or_mf_counter / all_pfams_encountered.size() ) + "%]" );
1292 ForesterUtil.programMessage( surfacing.PRG_NAME,
1293 "Pfams with a mapping : " + pfams_with_mappings_counter
1295 + ( 100 * pfams_with_mappings_counter / all_pfams_encountered.size() )
1297 ForesterUtil.programMessage( surfacing.PRG_NAME, "Pfams with a mapping to proc. or func. : "
1298 + pfams_with_mappings_to_bp_or_mf_counter + " ["
1299 + ( 100 * pfams_with_mappings_to_bp_or_mf_counter / all_pfams_encountered.size() ) + "%]" );
1300 ForesterUtil.programMessage( surfacing.PRG_NAME,
1301 "Pfams with mapping to biological process: " + biological_process_counter
1303 + ( 100 * biological_process_counter / all_pfams_encountered.size() )
1305 ForesterUtil.programMessage( surfacing.PRG_NAME,
1306 "Pfams with mapping to molecular function: " + molecular_function_counter
1308 + ( 100 * molecular_function_counter / all_pfams_encountered.size() )
1310 ForesterUtil.programMessage( surfacing.PRG_NAME,
1311 "Pfams with mapping to cellular component: " + cellular_component_counter
1313 + ( 100 * cellular_component_counter / all_pfams_encountered.size() )
1315 summary_writer.write( ForesterUtil.LINE_SEPARATOR );
1316 summary_writer.write( "# Sum of Pfams encountered : " + all_pfams_encountered.size() );
1317 summary_writer.write( ForesterUtil.LINE_SEPARATOR );
1318 summary_writer.write( "# Pfams without a mapping : " + pfams_without_mappings_counter
1319 + " [" + ( 100 * pfams_without_mappings_counter / all_pfams_encountered.size() ) + "%]" );
1320 summary_writer.write( ForesterUtil.LINE_SEPARATOR );
1321 summary_writer.write( "# Pfams without mapping to proc. or func. : "
1322 + pfams_without_mappings_to_bp_or_mf_counter + " ["
1323 + ( 100 * pfams_without_mappings_to_bp_or_mf_counter / all_pfams_encountered.size() ) + "%]" );
1324 summary_writer.write( ForesterUtil.LINE_SEPARATOR );
1325 summary_writer.write( "# Pfams with a mapping : " + pfams_with_mappings_counter + " ["
1326 + ( 100 * pfams_with_mappings_counter / all_pfams_encountered.size() ) + "%]" );
1327 summary_writer.write( ForesterUtil.LINE_SEPARATOR );
1328 summary_writer.write( "# Pfams with a mapping to proc. or func. : "
1329 + pfams_with_mappings_to_bp_or_mf_counter + " ["
1330 + ( 100 * pfams_with_mappings_to_bp_or_mf_counter / all_pfams_encountered.size() ) + "%]" );
1331 summary_writer.write( ForesterUtil.LINE_SEPARATOR );
1332 summary_writer.write( "# Pfams with mapping to biological process: " + biological_process_counter + " ["
1333 + ( 100 * biological_process_counter / all_pfams_encountered.size() ) + "%]" );
1334 summary_writer.write( ForesterUtil.LINE_SEPARATOR );
1335 summary_writer.write( "# Pfams with mapping to molecular function: " + molecular_function_counter + " ["
1336 + ( 100 * molecular_function_counter / all_pfams_encountered.size() ) + "%]" );
1337 summary_writer.write( ForesterUtil.LINE_SEPARATOR );
1338 summary_writer.write( "# Pfams with mapping to cellular component: " + cellular_component_counter + " ["
1339 + ( 100 * cellular_component_counter / all_pfams_encountered.size() ) + "%]" );
1340 summary_writer.write( ForesterUtil.LINE_SEPARATOR );
1341 summary_writer.close();
1343 catch ( final IOException e ) {
1344 ForesterUtil.printWarningMessage( surfacing.PRG_NAME, "Failure to write: " + e );
1348 public static void writeBinaryDomainCombinationsFileForGraphAnalysis( final String[][] input_file_properties,
1349 final File output_dir,
1350 final GenomeWideCombinableDomains gwcd,
1352 final GenomeWideCombinableDomainsSortOrder dc_sort_order ) {
1353 File dc_outfile_dot = new File( input_file_properties[ i ][ 0 ]
1354 + surfacing.DOMAIN_COMBINITONS_OUTPUTFILE_SUFFIX_FOR_GRAPH_ANALYSIS );
1355 if ( output_dir != null ) {
1356 dc_outfile_dot = new File( output_dir + ForesterUtil.FILE_SEPARATOR + dc_outfile_dot );
1358 checkForOutputFileWriteability( dc_outfile_dot );
1359 final SortedSet<BinaryDomainCombination> binary_combinations = createSetOfAllBinaryDomainCombinationsPerGenome( gwcd );
1361 final BufferedWriter out_dot = new BufferedWriter( new FileWriter( dc_outfile_dot ) );
1362 for( final BinaryDomainCombination bdc : binary_combinations ) {
1363 out_dot.write( bdc.toGraphDescribingLanguage( BinaryDomainCombination.OutputFormat.DOT, null, null )
1365 out_dot.write( SurfacingConstants.NL );
1369 catch ( final IOException e ) {
1370 ForesterUtil.fatalError( surfacing.PRG_NAME, e.getMessage() );
1372 ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote binary domain combination for \""
1373 + input_file_properties[ i ][ 0 ] + "\" (" + input_file_properties[ i ][ 1 ] + ", "
1374 + input_file_properties[ i ][ 2 ] + ") to: \"" + dc_outfile_dot + "\"" );
1377 public static void writeBinaryStatesMatrixAsListToFile( final CharacterStateMatrix<CharacterStateMatrix.GainLossStates> matrix,
1378 final CharacterStateMatrix.GainLossStates state,
1379 final String filename,
1380 final String indentifier_characters_separator,
1381 final String character_separator,
1382 final Map<String, String> descriptions ) {
1383 final File outfile = new File( filename );
1384 checkForOutputFileWriteability( outfile );
1385 final SortedSet<String> sorted_ids = new TreeSet<String>();
1386 for( int i = 0; i < matrix.getNumberOfIdentifiers(); ++i ) {
1387 sorted_ids.add( matrix.getIdentifier( i ) );
1390 final BufferedWriter out = new BufferedWriter( new FileWriter( outfile ) );
1391 for( final String id : sorted_ids ) {
1392 out.write( indentifier_characters_separator );
1393 out.write( "#" + id );
1394 out.write( indentifier_characters_separator );
1395 for( int c = 0; c < matrix.getNumberOfCharacters(); ++c ) {
1397 // using null to indicate either UNCHANGED_PRESENT or GAIN.
1398 if ( ( matrix.getState( id, c ) == state )
1399 || ( ( state == null ) && ( ( matrix.getState( id, c ) == CharacterStateMatrix.GainLossStates.GAIN ) || ( matrix
1400 .getState( id, c ) == CharacterStateMatrix.GainLossStates.UNCHANGED_PRESENT ) ) ) ) {
1401 out.write( matrix.getCharacter( c ) );
1402 if ( ( descriptions != null ) && !descriptions.isEmpty()
1403 && descriptions.containsKey( matrix.getCharacter( c ) ) ) {
1405 out.write( descriptions.get( matrix.getCharacter( c ) ) );
1407 out.write( character_separator );
1414 catch ( final IOException e ) {
1415 ForesterUtil.fatalError( surfacing.PRG_NAME, e.getMessage() );
1417 ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote characters list: \"" + filename + "\"" );
1420 public static void writeBinaryStatesMatrixAsListToFileForBinaryCombinationsForGraphAnalysis( final CharacterStateMatrix<CharacterStateMatrix.GainLossStates> matrix,
1421 final CharacterStateMatrix.GainLossStates state,
1422 final String filename,
1423 final String indentifier_characters_separator,
1424 final String character_separator,
1425 final BinaryDomainCombination.OutputFormat bc_output_format ) {
1426 final File outfile = new File( filename );
1427 checkForOutputFileWriteability( outfile );
1428 final SortedSet<String> sorted_ids = new TreeSet<String>();
1429 for( int i = 0; i < matrix.getNumberOfIdentifiers(); ++i ) {
1430 sorted_ids.add( matrix.getIdentifier( i ) );
1433 final BufferedWriter out = new BufferedWriter( new FileWriter( outfile ) );
1434 for( final String id : sorted_ids ) {
1435 out.write( indentifier_characters_separator );
1436 out.write( "#" + id );
1437 out.write( indentifier_characters_separator );
1438 for( int c = 0; c < matrix.getNumberOfCharacters(); ++c ) {
1440 // using null to indicate either UNCHANGED_PRESENT or GAIN.
1441 if ( ( matrix.getState( id, c ) == state )
1442 || ( ( state == null ) && ( ( matrix.getState( id, c ) == CharacterStateMatrix.GainLossStates.GAIN ) || ( matrix
1443 .getState( id, c ) == CharacterStateMatrix.GainLossStates.UNCHANGED_PRESENT ) ) ) ) {
1444 BinaryDomainCombination bdc = null;
1446 bdc = BasicBinaryDomainCombination.createInstance( matrix.getCharacter( c ) );
1448 catch ( final Exception e ) {
1449 ForesterUtil.fatalError( surfacing.PRG_NAME, e.getLocalizedMessage() );
1451 out.write( bdc.toGraphDescribingLanguage( bc_output_format, null, null ).toString() );
1452 out.write( character_separator );
1459 catch ( final IOException e ) {
1460 ForesterUtil.fatalError( surfacing.PRG_NAME, e.getMessage() );
1462 ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote characters list: \"" + filename + "\"" );
1465 public static void writeBinaryStatesMatrixToList( final Map<DomainId, List<GoId>> domain_id_to_go_ids_map,
1466 final Map<GoId, GoTerm> go_id_to_term_map,
1467 final GoNameSpace go_namespace_limit,
1468 final boolean domain_combinations,
1469 final CharacterStateMatrix<CharacterStateMatrix.GainLossStates> matrix,
1470 final CharacterStateMatrix.GainLossStates state,
1471 final String filename,
1472 final String indentifier_characters_separator,
1473 final String character_separator,
1474 final String title_for_html,
1475 final String prefix_for_html,
1476 final Map<DomainId, Set<String>>[] domain_id_to_secondary_features_maps,
1477 final SortedSet<String> all_pfams_encountered,
1478 final SortedSet<String> pfams_gained_or_lost,
1479 final String suffix_for_per_node_events_file ) {
1480 if ( ( go_namespace_limit != null ) && ( ( go_id_to_term_map == null ) || ( go_id_to_term_map.size() < 1 ) ) ) {
1481 throw new IllegalArgumentException( "attempt to use GO namespace limit without a GO-id to term map" );
1483 else if ( ( ( domain_id_to_go_ids_map == null ) || ( domain_id_to_go_ids_map.size() < 1 ) ) ) {
1484 throw new IllegalArgumentException( "attempt to output detailed HTML without a Pfam to GO map" );
1486 else if ( ( ( go_id_to_term_map == null ) || ( go_id_to_term_map.size() < 1 ) ) ) {
1487 throw new IllegalArgumentException( "attempt to output detailed HTML without a GO-id to term map" );
1489 final File outfile = new File( filename );
1490 checkForOutputFileWriteability( outfile );
1491 final SortedSet<String> sorted_ids = new TreeSet<String>();
1492 for( int i = 0; i < matrix.getNumberOfIdentifiers(); ++i ) {
1493 sorted_ids.add( matrix.getIdentifier( i ) );
1496 final Writer out = new BufferedWriter( new FileWriter( outfile ) );
1497 final File per_node_go_mapped_domain_gain_loss_files_base_dir = createBaseDirForPerNodeDomainFiles( surfacing.BASE_DIRECTORY_PER_NODE_DOMAIN_GAIN_LOSS_FILES,
1498 domain_combinations,
1501 Writer per_node_go_mapped_domain_gain_loss_outfile_writer = null;
1502 File per_node_go_mapped_domain_gain_loss_outfile = null;
1503 int per_node_counter = 0;
1504 out.write( "<html>" );
1505 out.write( SurfacingConstants.NL );
1506 addHtmlHead( out, title_for_html );
1507 out.write( SurfacingConstants.NL );
1508 out.write( "<body>" );
1509 out.write( SurfacingConstants.NL );
1510 out.write( "<h1>" );
1511 out.write( SurfacingConstants.NL );
1512 out.write( title_for_html );
1513 out.write( SurfacingConstants.NL );
1514 out.write( "</h1>" );
1515 out.write( SurfacingConstants.NL );
1516 out.write( "<table>" );
1517 out.write( SurfacingConstants.NL );
1518 for( final String id : sorted_ids ) {
1519 final Matcher matcher = PATTERN_SP_STYLE_TAXONOMY.matcher( id );
1520 if ( matcher.matches() ) {
1523 out.write( "<tr>" );
1524 out.write( "<td>" );
1525 out.write( "<a href=\"#" + id + "\">" + id + "</a>" );
1526 out.write( "</td>" );
1527 out.write( "</tr>" );
1528 out.write( SurfacingConstants.NL );
1530 out.write( "</table>" );
1531 out.write( SurfacingConstants.NL );
1532 for( final String id : sorted_ids ) {
1533 final Matcher matcher = PATTERN_SP_STYLE_TAXONOMY.matcher( id );
1534 if ( matcher.matches() ) {
1537 out.write( SurfacingConstants.NL );
1538 out.write( "<h2>" );
1539 out.write( "<a name=\"" + id + "\">" + id + "</a>" );
1540 writeTaxonomyLinks( out, id );
1541 out.write( "</h2>" );
1542 out.write( SurfacingConstants.NL );
1543 out.write( "<table>" );
1544 out.write( SurfacingConstants.NL );
1545 out.write( "<tr>" );
1546 out.write( "<td><b>" );
1547 out.write( "Pfam domain(s)" );
1548 out.write( "</b></td><td><b>" );
1549 out.write( "GO term acc" );
1550 out.write( "</b></td><td><b>" );
1551 out.write( "GO term" );
1552 out.write( "</b></td><td><b>" );
1553 out.write( "GO namespace" );
1554 out.write( "</b></td>" );
1555 out.write( "</tr>" );
1556 out.write( SurfacingConstants.NL );
1557 out.write( "</tr>" );
1558 out.write( SurfacingConstants.NL );
1559 per_node_counter = 0;
1560 if ( matrix.getNumberOfCharacters() > 0 ) {
1561 per_node_go_mapped_domain_gain_loss_outfile = new File( per_node_go_mapped_domain_gain_loss_files_base_dir
1562 + ForesterUtil.FILE_SEPARATOR + id + suffix_for_per_node_events_file );
1563 SurfacingUtil.checkForOutputFileWriteability( per_node_go_mapped_domain_gain_loss_outfile );
1564 per_node_go_mapped_domain_gain_loss_outfile_writer = ForesterUtil
1565 .createBufferedWriter( per_node_go_mapped_domain_gain_loss_outfile );
1568 per_node_go_mapped_domain_gain_loss_outfile = null;
1569 per_node_go_mapped_domain_gain_loss_outfile_writer = null;
1571 for( int c = 0; c < matrix.getNumberOfCharacters(); ++c ) {
1573 // using null to indicate either UNCHANGED_PRESENT or GAIN.
1574 if ( ( matrix.getState( id, c ) == state )
1575 || ( ( state == null ) && ( ( matrix.getState( id, c ) == CharacterStateMatrix.GainLossStates.UNCHANGED_PRESENT ) || ( matrix
1576 .getState( id, c ) == CharacterStateMatrix.GainLossStates.GAIN ) ) ) ) {
1577 final String character = matrix.getCharacter( c );
1578 String domain_0 = "";
1579 String domain_1 = "";
1580 if ( character.indexOf( BinaryDomainCombination.SEPARATOR ) > 0 ) {
1581 final String[] s = character.split( BinaryDomainCombination.SEPARATOR );
1582 if ( s.length != 2 ) {
1583 throw new AssertionError( "this should not have happened: unexpected format for domain combination: ["
1584 + character + "]" );
1590 domain_0 = character;
1592 writeDomainData( domain_id_to_go_ids_map,
1599 character_separator,
1600 domain_id_to_secondary_features_maps,
1602 all_pfams_encountered.add( domain_0 );
1603 if ( pfams_gained_or_lost != null ) {
1604 pfams_gained_or_lost.add( domain_0 );
1606 if ( !ForesterUtil.isEmpty( domain_1 ) ) {
1607 all_pfams_encountered.add( domain_1 );
1608 if ( pfams_gained_or_lost != null ) {
1609 pfams_gained_or_lost.add( domain_1 );
1612 if ( per_node_go_mapped_domain_gain_loss_outfile_writer != null ) {
1613 writeDomainsToIndividualFilePerTreeNode( per_node_go_mapped_domain_gain_loss_outfile_writer,
1620 if ( per_node_go_mapped_domain_gain_loss_outfile_writer != null ) {
1621 per_node_go_mapped_domain_gain_loss_outfile_writer.close();
1622 if ( per_node_counter < 1 ) {
1623 per_node_go_mapped_domain_gain_loss_outfile.delete();
1625 per_node_counter = 0;
1627 out.write( "</table>" );
1628 out.write( SurfacingConstants.NL );
1629 out.write( "<hr>" );
1630 out.write( SurfacingConstants.NL );
1631 } // for( final String id : sorted_ids ) {
1632 out.write( "</body>" );
1633 out.write( SurfacingConstants.NL );
1634 out.write( "</html>" );
1635 out.write( SurfacingConstants.NL );
1639 catch ( final IOException e ) {
1640 ForesterUtil.fatalError( surfacing.PRG_NAME, e.getMessage() );
1642 ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote characters detailed HTML list: \"" + filename + "\"" );
1645 public static void writeBinaryStatesMatrixToListORIGIG( final Map<DomainId, List<GoId>> domain_id_to_go_ids_map,
1646 final Map<GoId, GoTerm> go_id_to_term_map,
1647 final GoNameSpace go_namespace_limit,
1648 final boolean domain_combinations,
1649 final CharacterStateMatrix<CharacterStateMatrix.GainLossStates> matrix,
1650 final CharacterStateMatrix.GainLossStates state,
1651 final String filename,
1652 final String indentifier_characters_separator,
1653 final String character_separator,
1654 final String title_for_html,
1655 final String prefix_for_html,
1656 final Map<DomainId, Set<String>>[] domain_id_to_secondary_features_maps,
1657 final SortedSet<String> all_pfams_encountered,
1658 final SortedSet<String> pfams_gained_or_lost,
1659 final String suffix_for_per_node_events_file ) {
1660 if ( ( go_namespace_limit != null ) && ( ( go_id_to_term_map == null ) || ( go_id_to_term_map.size() < 1 ) ) ) {
1661 throw new IllegalArgumentException( "attempt to use GO namespace limit without a GO-id to term map" );
1663 else if ( ( ( domain_id_to_go_ids_map == null ) || ( domain_id_to_go_ids_map.size() < 1 ) ) ) {
1664 throw new IllegalArgumentException( "attempt to output detailed HTML without a Pfam to GO map" );
1666 else if ( ( ( go_id_to_term_map == null ) || ( go_id_to_term_map.size() < 1 ) ) ) {
1667 throw new IllegalArgumentException( "attempt to output detailed HTML without a GO-id to term map" );
1669 final File outfile = new File( filename );
1670 checkForOutputFileWriteability( outfile );
1671 final SortedSet<String> sorted_ids = new TreeSet<String>();
1672 for( int i = 0; i < matrix.getNumberOfIdentifiers(); ++i ) {
1673 sorted_ids.add( matrix.getIdentifier( i ) );
1676 final Writer out = new BufferedWriter( new FileWriter( outfile ) );
1677 final File per_node_go_mapped_domain_gain_loss_files_base_dir = createBaseDirForPerNodeDomainFiles( surfacing.BASE_DIRECTORY_PER_NODE_DOMAIN_GAIN_LOSS_FILES,
1678 domain_combinations,
1681 Writer per_node_go_mapped_domain_gain_loss_outfile_writer = null;
1682 File per_node_go_mapped_domain_gain_loss_outfile = null;
1683 int per_node_counter = 0;
1684 out.write( "<html>" );
1685 out.write( SurfacingConstants.NL );
1686 addHtmlHead( out, title_for_html );
1687 out.write( SurfacingConstants.NL );
1688 out.write( "<body>" );
1689 out.write( SurfacingConstants.NL );
1690 out.write( "<h1>" );
1691 out.write( SurfacingConstants.NL );
1692 out.write( title_for_html );
1693 out.write( SurfacingConstants.NL );
1694 out.write( "</h1>" );
1695 out.write( SurfacingConstants.NL );
1696 out.write( "<table>" );
1697 out.write( SurfacingConstants.NL );
1698 for( final String id : sorted_ids ) {
1699 out.write( "<tr>" );
1700 out.write( "<td>" );
1701 out.write( "<a href=\"#" + id + "\">" + id + "</a>" );
1702 writeTaxonomyLinks( out, id );
1703 out.write( "</td>" );
1704 out.write( "</tr>" );
1705 out.write( SurfacingConstants.NL );
1707 out.write( "</table>" );
1708 out.write( SurfacingConstants.NL );
1709 for( final String id : sorted_ids ) {
1710 out.write( SurfacingConstants.NL );
1711 out.write( "<h2>" );
1712 out.write( "<a name=\"" + id + "\">" + id + "</a>" );
1713 writeTaxonomyLinks( out, id );
1714 out.write( "</h2>" );
1715 out.write( SurfacingConstants.NL );
1716 out.write( "<table>" );
1717 out.write( SurfacingConstants.NL );
1718 out.write( "<tr>" );
1719 out.write( "<td><b>" );
1720 out.write( "Pfam domain(s)" );
1721 out.write( "</b></td><td><b>" );
1722 out.write( "GO term acc" );
1723 out.write( "</b></td><td><b>" );
1724 out.write( "GO term" );
1725 out.write( "</b></td><td><b>" );
1726 out.write( "Penultimate GO term" );
1727 out.write( "</b></td><td><b>" );
1728 out.write( "GO namespace" );
1729 out.write( "</b></td>" );
1730 out.write( "</tr>" );
1731 out.write( SurfacingConstants.NL );
1732 out.write( "</tr>" );
1733 out.write( SurfacingConstants.NL );
1734 per_node_counter = 0;
1735 if ( matrix.getNumberOfCharacters() > 0 ) {
1736 per_node_go_mapped_domain_gain_loss_outfile = new File( per_node_go_mapped_domain_gain_loss_files_base_dir
1737 + ForesterUtil.FILE_SEPARATOR + id + suffix_for_per_node_events_file );
1738 SurfacingUtil.checkForOutputFileWriteability( per_node_go_mapped_domain_gain_loss_outfile );
1739 per_node_go_mapped_domain_gain_loss_outfile_writer = ForesterUtil
1740 .createBufferedWriter( per_node_go_mapped_domain_gain_loss_outfile );
1743 per_node_go_mapped_domain_gain_loss_outfile = null;
1744 per_node_go_mapped_domain_gain_loss_outfile_writer = null;
1746 for( int c = 0; c < matrix.getNumberOfCharacters(); ++c ) {
1748 // using null to indicate either UNCHANGED_PRESENT or GAIN.
1749 if ( ( matrix.getState( id, c ) == state )
1750 || ( ( state == null ) && ( ( matrix.getState( id, c ) == CharacterStateMatrix.GainLossStates.UNCHANGED_PRESENT ) || ( matrix
1751 .getState( id, c ) == CharacterStateMatrix.GainLossStates.GAIN ) ) ) ) {
1752 final String character = matrix.getCharacter( c );
1753 String domain_0 = "";
1754 String domain_1 = "";
1755 if ( character.indexOf( BinaryDomainCombination.SEPARATOR ) > 0 ) {
1756 final String[] s = character.split( BinaryDomainCombination.SEPARATOR );
1757 if ( s.length != 2 ) {
1758 throw new AssertionError( "this should not have happened: unexpected format for domain combination: ["
1759 + character + "]" );
1765 domain_0 = character;
1767 writeDomainData( domain_id_to_go_ids_map,
1774 character_separator,
1775 domain_id_to_secondary_features_maps,
1777 all_pfams_encountered.add( domain_0 );
1778 if ( pfams_gained_or_lost != null ) {
1779 pfams_gained_or_lost.add( domain_0 );
1781 if ( !ForesterUtil.isEmpty( domain_1 ) ) {
1782 all_pfams_encountered.add( domain_1 );
1783 if ( pfams_gained_or_lost != null ) {
1784 pfams_gained_or_lost.add( domain_1 );
1787 if ( per_node_go_mapped_domain_gain_loss_outfile_writer != null ) {
1788 writeDomainsToIndividualFilePerTreeNode( per_node_go_mapped_domain_gain_loss_outfile_writer,
1795 if ( per_node_go_mapped_domain_gain_loss_outfile_writer != null ) {
1796 per_node_go_mapped_domain_gain_loss_outfile_writer.close();
1797 if ( per_node_counter < 1 ) {
1798 per_node_go_mapped_domain_gain_loss_outfile.delete();
1800 per_node_counter = 0;
1802 out.write( "</table>" );
1803 out.write( SurfacingConstants.NL );
1804 out.write( "<hr>" );
1805 out.write( SurfacingConstants.NL );
1806 } // for( final String id : sorted_ids ) {
1807 out.write( "</body>" );
1808 out.write( SurfacingConstants.NL );
1809 out.write( "</html>" );
1810 out.write( SurfacingConstants.NL );
1814 catch ( final IOException e ) {
1815 ForesterUtil.fatalError( surfacing.PRG_NAME, e.getMessage() );
1817 ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote characters detailed HTML list: \"" + filename + "\"" );
1820 public static void writeDomainCombinationsCountsFile( final String[][] input_file_properties,
1821 final File output_dir,
1822 final Writer per_genome_domain_promiscuity_statistics_writer,
1823 final GenomeWideCombinableDomains gwcd,
1825 final GenomeWideCombinableDomains.GenomeWideCombinableDomainsSortOrder dc_sort_order ) {
1826 File dc_outfile = new File( input_file_properties[ i ][ 0 ]
1827 + surfacing.DOMAIN_COMBINITON_COUNTS_OUTPUTFILE_SUFFIX );
1828 if ( output_dir != null ) {
1829 dc_outfile = new File( output_dir + ForesterUtil.FILE_SEPARATOR + dc_outfile );
1831 checkForOutputFileWriteability( dc_outfile );
1833 final BufferedWriter out = new BufferedWriter( new FileWriter( dc_outfile ) );
1834 out.write( gwcd.toStringBuilder( dc_sort_order ).toString() );
1837 catch ( final IOException e ) {
1838 ForesterUtil.fatalError( surfacing.PRG_NAME, e.getMessage() );
1840 final DescriptiveStatistics stats = gwcd.getPerGenomeDomainPromiscuityStatistics();
1842 per_genome_domain_promiscuity_statistics_writer.write( input_file_properties[ i ][ 0 ] + "\t" );
1843 per_genome_domain_promiscuity_statistics_writer.write( FORMATTER_3.format( stats.arithmeticMean() ) + "\t" );
1844 if ( stats.getN() < 2 ) {
1845 per_genome_domain_promiscuity_statistics_writer.write( "n/a" + "\t" );
1848 per_genome_domain_promiscuity_statistics_writer.write( FORMATTER_3.format( stats
1849 .sampleStandardDeviation() ) + "\t" );
1851 per_genome_domain_promiscuity_statistics_writer.write( FORMATTER_3.format( stats.median() ) + "\t" );
1852 per_genome_domain_promiscuity_statistics_writer.write( ( int ) stats.getMin() + "\t" );
1853 per_genome_domain_promiscuity_statistics_writer.write( ( int ) stats.getMax() + "\t" );
1854 per_genome_domain_promiscuity_statistics_writer.write( stats.getN() + "\t" );
1855 final SortedSet<DomainId> mpds = gwcd.getMostPromiscuosDomain();
1856 for( final DomainId mpd : mpds ) {
1857 per_genome_domain_promiscuity_statistics_writer.write( mpd.getId() + " " );
1859 per_genome_domain_promiscuity_statistics_writer.write( ForesterUtil.LINE_SEPARATOR );
1861 catch ( final IOException e ) {
1862 ForesterUtil.fatalError( surfacing.PRG_NAME, e.getMessage() );
1864 if ( input_file_properties[ i ].length == 3 ) {
1865 ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote domain combination counts for \""
1866 + input_file_properties[ i ][ 0 ] + "\" (" + input_file_properties[ i ][ 1 ] + ", "
1867 + input_file_properties[ i ][ 2 ] + ") to: \"" + dc_outfile + "\"" );
1870 ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote domain combination counts for \""
1871 + input_file_properties[ i ][ 0 ] + "\" (" + input_file_properties[ i ][ 1 ] + ") to: \""
1872 + dc_outfile + "\"" );
1876 private static void writeDomainData( final Map<DomainId, List<GoId>> domain_id_to_go_ids_map,
1877 final Map<GoId, GoTerm> go_id_to_term_map,
1878 final GoNameSpace go_namespace_limit,
1880 final String domain_0,
1881 final String domain_1,
1882 final String prefix_for_html,
1883 final String character_separator_for_non_html_output,
1884 final Map<DomainId, Set<String>>[] domain_id_to_secondary_features_maps,
1885 final Set<GoId> all_go_ids ) throws IOException {
1886 boolean any_go_annotation_present = false;
1887 boolean first_has_no_go = false;
1888 int domain_count = 2; // To distinguish between domains and binary domain combinations.
1889 if ( ForesterUtil.isEmpty( domain_1 ) ) {
1892 // The following has a difficult to understand logic.
1893 for( int d = 0; d < domain_count; ++d ) {
1894 List<GoId> go_ids = null;
1895 boolean go_annotation_present = false;
1897 final DomainId domain_id = new DomainId( domain_0 );
1898 if ( domain_id_to_go_ids_map.containsKey( domain_id ) ) {
1899 go_annotation_present = true;
1900 any_go_annotation_present = true;
1901 go_ids = domain_id_to_go_ids_map.get( domain_id );
1904 first_has_no_go = true;
1908 final DomainId domain_id = new DomainId( domain_1 );
1909 if ( domain_id_to_go_ids_map.containsKey( domain_id ) ) {
1910 go_annotation_present = true;
1911 any_go_annotation_present = true;
1912 go_ids = domain_id_to_go_ids_map.get( domain_id );
1915 if ( go_annotation_present ) {
1916 boolean first = ( ( d == 0 ) || ( ( d == 1 ) && first_has_no_go ) );
1917 for( final GoId go_id : go_ids ) {
1918 out.write( "<tr>" );
1921 writeDomainIdsToHtml( out,
1925 domain_id_to_secondary_features_maps );
1928 out.write( "<td></td>" );
1930 if ( !go_id_to_term_map.containsKey( go_id ) ) {
1931 throw new IllegalArgumentException( "GO-id [" + go_id + "] not found in GO-id to GO-term map" );
1933 final GoTerm go_term = go_id_to_term_map.get( go_id );
1934 if ( ( go_namespace_limit == null ) || go_namespace_limit.equals( go_term.getGoNameSpace() ) ) {
1935 // final String top = GoUtils.getPenultimateGoTerm( go_term, go_id_to_term_map ).getName();
1936 final String go_id_str = go_id.getId();
1937 out.write( "<td>" );
1938 out.write( "<a href=\"" + SurfacingConstants.AMIGO_LINK + go_id_str
1939 + "\" target=\"amigo_window\">" + go_id_str + "</a>" );
1940 out.write( "</td><td>" );
1941 out.write( go_term.getName() );
1942 if ( domain_count == 2 ) {
1943 out.write( " (" + d + ")" );
1945 out.write( "</td><td>" );
1946 // out.write( top );
1947 // out.write( "</td><td>" );
1949 out.write( go_term.getGoNameSpace().toShortString() );
1951 out.write( "</td>" );
1952 if ( all_go_ids != null ) {
1953 all_go_ids.add( go_id );
1957 out.write( "<td>" );
1958 out.write( "</td><td>" );
1959 out.write( "</td><td>" );
1960 out.write( "</td><td>" );
1961 out.write( "</td>" );
1963 out.write( "</tr>" );
1964 out.write( SurfacingConstants.NL );
1967 } // for( int d = 0; d < domain_count; ++d )
1968 if ( !any_go_annotation_present ) {
1969 out.write( "<tr>" );
1970 writeDomainIdsToHtml( out, domain_0, domain_1, prefix_for_html, domain_id_to_secondary_features_maps );
1971 out.write( "<td>" );
1972 out.write( "</td><td>" );
1973 out.write( "</td><td>" );
1974 out.write( "</td><td>" );
1975 out.write( "</td>" );
1976 out.write( "</tr>" );
1977 out.write( SurfacingConstants.NL );
1981 private static void writeDomainIdsToHtml( final Writer out,
1982 final String domain_0,
1983 final String domain_1,
1984 final String prefix_for_detailed_html,
1985 final Map<DomainId, Set<String>>[] domain_id_to_secondary_features_maps )
1986 throws IOException {
1987 out.write( "<td>" );
1988 if ( !ForesterUtil.isEmpty( prefix_for_detailed_html ) ) {
1989 out.write( prefix_for_detailed_html );
1992 out.write( "<a href=\"" + SurfacingConstants.PFAM_FAMILY_ID_LINK + domain_0 + "\">" + domain_0 + "</a>" );
1993 out.write( "</td>" );
1996 public static DescriptiveStatistics writeDomainSimilaritiesToFile( final StringBuilder html_desc,
1997 final StringBuilder html_title,
1999 final SortedSet<DomainSimilarity> similarities,
2000 final boolean treat_as_binary,
2001 final List<Species> species_order,
2002 final PrintableDomainSimilarity.PRINT_OPTION print_option,
2003 final DomainSimilarity.DomainSimilaritySortField sort_field,
2004 final DomainSimilarity.DomainSimilarityScoring scoring,
2005 final boolean verbose ) throws IOException {
2006 final DescriptiveStatistics stats = new BasicDescriptiveStatistics();
2007 String histogram_title = null;
2008 switch ( sort_field ) {
2009 case ABS_MAX_COUNTS_DIFFERENCE:
2010 if ( treat_as_binary ) {
2011 histogram_title = "absolute counts difference:";
2014 histogram_title = "absolute (maximal) counts difference:";
2017 case MAX_COUNTS_DIFFERENCE:
2018 if ( treat_as_binary ) {
2019 histogram_title = "counts difference:";
2022 histogram_title = "(maximal) counts difference:";
2026 histogram_title = "score mean:";
2029 histogram_title = "score minimum:";
2032 histogram_title = "score maximum:";
2034 case MAX_DIFFERENCE:
2035 if ( treat_as_binary ) {
2036 histogram_title = "difference:";
2039 histogram_title = "(maximal) difference:";
2043 histogram_title = "score mean:";
2046 histogram_title = "score standard deviation:";
2049 histogram_title = "species number:";
2052 throw new AssertionError( "Unknown sort field: " + sort_field );
2054 for( final DomainSimilarity similarity : similarities ) {
2055 switch ( sort_field ) {
2056 case ABS_MAX_COUNTS_DIFFERENCE:
2057 stats.addValue( Math.abs( similarity.getMaximalDifferenceInCounts() ) );
2059 case MAX_COUNTS_DIFFERENCE:
2060 stats.addValue( similarity.getMaximalDifferenceInCounts() );
2063 stats.addValue( similarity.getMeanSimilarityScore() );
2066 stats.addValue( similarity.getMinimalSimilarityScore() );
2069 stats.addValue( similarity.getMaximalSimilarityScore() );
2071 case MAX_DIFFERENCE:
2072 stats.addValue( similarity.getMaximalDifference() );
2075 stats.addValue( similarity.getMeanSimilarityScore() );
2078 stats.addValue( similarity.getStandardDeviationOfSimilarityScore() );
2081 stats.addValue( similarity.getSpecies().size() );
2084 throw new AssertionError( "Unknown sort field: " + sort_field );
2088 // final HistogramData[] hists = new HistogramData[ 1 ];
2091 // List<HistogramDataItem> data_items = new
2092 // ArrayList<HistogramDataItem>();
2093 // double[] values = stats.getDataAsDoubleArray();
2094 // for( int i = 0; i < values.length; i++ ) {
2095 // HistogramDataItem data_item = new BasicHistogramDataItem( "", values[
2097 // data_items.add( data_item );
2101 // HistogramData hd0 = new HistogramData( "name",
2109 // hists[ 0 ] = hd0;
2111 // final HistogramsFrame hf = new HistogramsFrame( hists );
2112 // hf.setVisible( true );
2114 AsciiHistogram histo = null;
2115 if ( stats.getMin() < stats.getMin() ) {
2116 histo = new AsciiHistogram( stats, histogram_title );
2119 if ( histo != null ) {
2120 System.out.println( histo.toStringBuffer( 20, '|', 40, 5 ) );
2122 System.out.println();
2123 System.out.println( "N : " + stats.getN() );
2124 System.out.println( "Min : " + stats.getMin() );
2125 System.out.println( "Max : " + stats.getMax() );
2126 System.out.println( "Mean : " + stats.arithmeticMean() );
2127 if ( stats.getN() > 1 ) {
2128 System.out.println( "SD : " + stats.sampleStandardDeviation() );
2131 System.out.println( "SD : n/a" );
2133 System.out.println( "Median : " + stats.median() );
2134 if ( stats.getN() > 1 ) {
2135 System.out.println( "Pearsonian skewness : " + stats.pearsonianSkewness() );
2138 System.out.println( "Pearsonian skewness : n/a" );
2141 switch ( print_option ) {
2142 case SIMPLE_TAB_DELIMITED:
2145 w.write( "<html>" );
2146 w.write( SurfacingConstants.NL );
2147 addHtmlHead( w, "SURFACING :: " + html_title );
2148 w.write( SurfacingConstants.NL );
2149 w.write( "<body>" );
2150 w.write( SurfacingConstants.NL );
2151 w.write( html_desc.toString() );
2152 w.write( SurfacingConstants.NL );
2155 w.write( SurfacingConstants.NL );
2156 w.write( "<tt><pre>" );
2157 w.write( SurfacingConstants.NL );
2158 if ( histo != null ) {
2159 w.write( histo.toStringBuffer( 20, '|', 40, 5 ).toString() );
2160 w.write( SurfacingConstants.NL );
2162 w.write( "</pre></tt>" );
2163 w.write( SurfacingConstants.NL );
2164 w.write( "<table>" );
2165 w.write( SurfacingConstants.NL );
2166 w.write( "<tr><td>N: </td><td>" + stats.getN() + "</td></tr>" );
2167 w.write( SurfacingConstants.NL );
2168 w.write( "<tr><td>Min: </td><td>" + stats.getMin() + "</td></tr>" );
2169 w.write( SurfacingConstants.NL );
2170 w.write( "<tr><td>Max: </td><td>" + stats.getMax() + "</td></tr>" );
2171 w.write( SurfacingConstants.NL );
2172 w.write( "<tr><td>Mean: </td><td>" + stats.arithmeticMean() + "</td></tr>" );
2173 w.write( SurfacingConstants.NL );
2174 if ( stats.getN() > 1 ) {
2175 w.write( "<tr><td>SD: </td><td>" + stats.sampleStandardDeviation() + "</td></tr>" );
2178 w.write( "<tr><td>SD: </td><td>n/a</td></tr>" );
2180 w.write( SurfacingConstants.NL );
2181 w.write( "<tr><td>Median: </td><td>" + stats.median() + "</td></tr>" );
2182 w.write( SurfacingConstants.NL );
2183 if ( stats.getN() > 1 ) {
2184 w.write( "<tr><td>Pearsonian skewness: </td><td>" + stats.pearsonianSkewness() + "</td></tr>" );
2187 w.write( "<tr><td>Pearsonian skewness: </td><td>n/a</td></tr>" );
2189 w.write( SurfacingConstants.NL );
2190 w.write( "</table>" );
2191 w.write( SurfacingConstants.NL );
2193 w.write( SurfacingConstants.NL );
2195 w.write( SurfacingConstants.NL );
2197 w.write( SurfacingConstants.NL );
2198 w.write( "<table>" );
2199 w.write( SurfacingConstants.NL );
2202 w.write( SurfacingConstants.NL );
2203 for( final DomainSimilarity similarity : similarities ) {
2204 if ( ( species_order != null ) && !species_order.isEmpty() ) {
2205 ( ( PrintableDomainSimilarity ) similarity ).setSpeciesOrder( species_order );
2207 w.write( similarity.toStringBuffer( print_option ).toString() );
2208 w.write( SurfacingConstants.NL );
2210 switch ( print_option ) {
2212 w.write( SurfacingConstants.NL );
2213 w.write( "</table>" );
2214 w.write( SurfacingConstants.NL );
2215 w.write( "</font>" );
2216 w.write( SurfacingConstants.NL );
2217 w.write( "</body>" );
2218 w.write( SurfacingConstants.NL );
2219 w.write( "</html>" );
2220 w.write( SurfacingConstants.NL );
2228 private static void writeDomainsToIndividualFilePerTreeNode( final Writer individual_files_writer,
2229 final String domain_0,
2230 final String domain_1 ) throws IOException {
2231 individual_files_writer.write( domain_0 );
2232 individual_files_writer.write( ForesterUtil.LINE_SEPARATOR );
2233 if ( !ForesterUtil.isEmpty( domain_1 ) ) {
2234 individual_files_writer.write( domain_1 );
2235 individual_files_writer.write( ForesterUtil.LINE_SEPARATOR );
2239 public static void writeMatrixToFile( final CharacterStateMatrix<?> matrix,
2240 final String filename,
2241 final Format format ) {
2242 final File outfile = new File( filename );
2243 checkForOutputFileWriteability( outfile );
2245 final BufferedWriter out = new BufferedWriter( new FileWriter( outfile ) );
2246 matrix.toWriter( out, format );
2250 catch ( final IOException e ) {
2251 ForesterUtil.fatalError( surfacing.PRG_NAME, e.getMessage() );
2253 ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote matrix: \"" + filename + "\"" );
2256 public static void writeMatrixToFile( final File matrix_outfile, final List<DistanceMatrix> matrices ) {
2257 checkForOutputFileWriteability( matrix_outfile );
2259 final BufferedWriter out = new BufferedWriter( new FileWriter( matrix_outfile ) );
2260 for( final DistanceMatrix distance_matrix : matrices ) {
2261 out.write( distance_matrix.toStringBuffer( DistanceMatrix.Format.PHYLIP ).toString() );
2262 out.write( ForesterUtil.LINE_SEPARATOR );
2267 catch ( final IOException e ) {
2268 ForesterUtil.fatalError( surfacing.PRG_NAME, e.getMessage() );
2270 ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote distance matrices to \"" + matrix_outfile + "\"" );
2273 private static void writePfamsToFile( final String outfile_name, final SortedSet<String> pfams ) {
2275 final Writer writer = new BufferedWriter( new FileWriter( new File( outfile_name ) ) );
2276 for( final String pfam : pfams ) {
2277 writer.write( pfam );
2278 writer.write( ForesterUtil.LINE_SEPARATOR );
2281 ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote " + pfams.size() + " pfams to [" + outfile_name
2284 catch ( final IOException e ) {
2285 ForesterUtil.printWarningMessage( surfacing.PRG_NAME, "Failure to write: " + e );
2289 public static void writePhylogenyToFile( final Phylogeny phylogeny, final String filename ) {
2290 final PhylogenyWriter writer = new PhylogenyWriter();
2292 writer.toPhyloXML( new File( filename ), phylogeny, 1 );
2294 catch ( final IOException e ) {
2295 ForesterUtil.printWarningMessage( surfacing.PRG_NAME, "failed to write phylogeny to \"" + filename + "\": "
2298 ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote phylogeny to \"" + filename + "\"" );
2301 public static void writeTaxonomyLinks( final Writer writer, final String species ) throws IOException {
2302 if ( ( species.length() > 1 ) && ( species.indexOf( '_' ) < 1 ) ) {
2303 final Matcher matcher = PATTERN_SP_STYLE_TAXONOMY.matcher( species );
2304 writer.write( " [" );
2305 if ( matcher.matches() ) {
2306 writer.write( "<a href=\"" + SurfacingConstants.UNIPROT_LINK + species
2307 + "\" target=\"taxonomy_window\">uniprot</a>" );
2310 writer.write( "<a href=\"" + SurfacingConstants.EOL_LINK + species
2311 + "\" target=\"taxonomy_window\">eol</a>" );
2312 writer.write( "|" );
2313 writer.write( "<a href=\"" + SurfacingConstants.TOL_LINK + species
2314 + "\" target=\"taxonomy_window\">tol</a>" );
2316 writer.write( "]" );
2320 private static void writeToNexus( final String outfile_name,
2321 final CharacterStateMatrix<BinaryStates> matrix,
2322 final Phylogeny phylogeny ) {
2323 if ( !( matrix instanceof BasicCharacterStateMatrix ) ) {
2324 throw new IllegalArgumentException( "can only write matrices of type [" + BasicCharacterStateMatrix.class
2327 final BasicCharacterStateMatrix<BinaryStates> my_matrix = ( org.forester.evoinference.matrix.character.BasicCharacterStateMatrix<BinaryStates> ) matrix;
2328 final List<Phylogeny> phylogenies = new ArrayList<Phylogeny>( 1 );
2329 phylogenies.add( phylogeny );
2331 final BufferedWriter w = new BufferedWriter( new FileWriter( outfile_name ) );
2332 w.write( NexusConstants.NEXUS );
2333 w.write( ForesterUtil.LINE_SEPARATOR );
2334 my_matrix.writeNexusTaxaBlock( w );
2335 my_matrix.writeNexusBinaryChractersBlock( w );
2336 PhylogenyWriter.writeNexusTreesBlock( w, phylogenies );
2339 ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote Nexus file: \"" + outfile_name + "\"" );
2341 catch ( final IOException e ) {
2342 ForesterUtil.fatalError( surfacing.PRG_NAME, e.getMessage() );
2346 private static void writeToNexus( final String outfile_name,
2347 final DomainParsimonyCalculator domain_parsimony,
2348 final Phylogeny phylogeny ) {
2349 writeToNexus( outfile_name + surfacing.NEXUS_EXTERNAL_DOMAINS,
2350 domain_parsimony.createMatrixOfDomainPresenceOrAbsence(),
2352 writeToNexus( outfile_name + surfacing.NEXUS_EXTERNAL_DOMAIN_COMBINATIONS,
2353 domain_parsimony.createMatrixOfBinaryDomainCombinationPresenceOrAbsence(),
2357 public static void domainsPerProteinsStatistics( final String genome,
2358 final List<Protein> protein_list,
2359 final DescriptiveStatistics all_genomes_domains_per_potein_stats,
2360 final SortedMap<Integer, Integer> all_genomes_domains_per_potein_histo,
2361 final SortedSet<String> domains_which_are_always_single,
2362 final SortedSet<String> domains_which_are_sometimes_single_sometimes_not,
2363 final SortedSet<String> domains_which_never_single,
2364 final Writer writer ) {
2365 final DescriptiveStatistics stats = new BasicDescriptiveStatistics();
2366 for( final Protein protein : protein_list ) {
2367 final int domains = protein.getNumberOfProteinDomains();
2368 //System.out.println( domains );
2369 stats.addValue( domains );
2370 all_genomes_domains_per_potein_stats.addValue( domains );
2371 if ( !all_genomes_domains_per_potein_histo.containsKey( domains ) ) {
2372 all_genomes_domains_per_potein_histo.put( domains, 1 );
2375 all_genomes_domains_per_potein_histo.put( domains,
2376 1 + all_genomes_domains_per_potein_histo.get( domains ) );
2378 if ( domains == 1 ) {
2379 final String domain = protein.getProteinDomain( 0 ).getDomainId().getId();
2380 if ( !domains_which_are_sometimes_single_sometimes_not.contains( domain ) ) {
2381 if ( domains_which_never_single.contains( domain ) ) {
2382 domains_which_never_single.remove( domain );
2383 domains_which_are_sometimes_single_sometimes_not.add( domain );
2386 domains_which_are_always_single.add( domain );
2390 else if ( domains > 1 ) {
2391 for( final Domain d : protein.getProteinDomains() ) {
2392 final String domain = d.getDomainId().getId();
2393 // System.out.println( domain );
2394 if ( !domains_which_are_sometimes_single_sometimes_not.contains( domain ) ) {
2395 if ( domains_which_are_always_single.contains( domain ) ) {
2396 domains_which_are_always_single.remove( domain );
2397 domains_which_are_sometimes_single_sometimes_not.add( domain );
2400 domains_which_never_single.add( domain );
2407 writer.write( genome );
2408 writer.write( "\t" );
2409 writer.write( stats.arithmeticMean() + "" );
2410 writer.write( "\t" );
2411 writer.write( stats.sampleStandardDeviation() + "" );
2412 writer.write( "\t" );
2413 writer.write( stats.median() + "" );
2414 writer.write( "\t" );
2415 writer.write( stats.getN() + "" );
2416 writer.write( "\t" );
2417 writer.write( stats.getMin() + "" );
2418 writer.write( "\t" );
2419 writer.write( stats.getMax() + "" );
2420 writer.write( "\n" );
2422 catch ( final IOException e ) {
2423 e.printStackTrace();