3 // FORESTER -- software libraries and applications
4 // for evolutionary biology research and applications.
6 // Copyright (C) 2008-2009 Christian M. Zmasek
7 // Copyright (C) 2008-2009 Burnham Institute for Medical Research
10 // This library is free software; you can redistribute it and/or
11 // modify it under the terms of the GNU Lesser General Public
12 // License as published by the Free Software Foundation; either
13 // version 2.1 of the License, or (at your option) any later version.
15 // This library is distributed in the hope that it will be useful,
16 // but WITHOUT ANY WARRANTY; without even the implied warranty of
17 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
18 // Lesser General Public License for more details.
20 // You should have received a copy of the GNU Lesser General Public
21 // License along with this library; if not, write to the Free Software
22 // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
24 // Contact: phylosoft @ gmail . com
25 // WWW: www.phylosoft.org/forester
27 package org.forester.surfacing;
29 import java.io.BufferedWriter;
31 import java.io.FileWriter;
32 import java.io.IOException;
33 import java.io.Writer;
34 import java.text.DecimalFormat;
35 import java.text.NumberFormat;
36 import java.util.ArrayList;
37 import java.util.Arrays;
38 import java.util.Collections;
39 import java.util.Comparator;
40 import java.util.HashMap;
41 import java.util.HashSet;
42 import java.util.List;
44 import java.util.PriorityQueue;
46 import java.util.SortedMap;
47 import java.util.SortedSet;
48 import java.util.TreeMap;
49 import java.util.TreeSet;
50 import java.util.regex.Matcher;
51 import java.util.regex.Pattern;
53 import org.forester.application.surfacing;
54 import org.forester.evoinference.distance.NeighborJoining;
55 import org.forester.evoinference.matrix.character.BasicCharacterStateMatrix;
56 import org.forester.evoinference.matrix.character.CharacterStateMatrix;
57 import org.forester.evoinference.matrix.character.CharacterStateMatrix.BinaryStates;
58 import org.forester.evoinference.matrix.character.CharacterStateMatrix.Format;
59 import org.forester.evoinference.matrix.character.CharacterStateMatrix.GainLossStates;
60 import org.forester.evoinference.matrix.distance.DistanceMatrix;
61 import org.forester.go.GoId;
62 import org.forester.go.GoNameSpace;
63 import org.forester.go.GoTerm;
64 import org.forester.go.PfamToGoMapping;
65 import org.forester.io.parsers.nexus.NexusConstants;
66 import org.forester.io.writers.PhylogenyWriter;
67 import org.forester.phylogeny.Phylogeny;
68 import org.forester.phylogeny.PhylogenyMethods;
69 import org.forester.phylogeny.PhylogenyNode;
70 import org.forester.phylogeny.PhylogenyNodeI.NH_CONVERSION_SUPPORT_VALUE_STYLE;
71 import org.forester.phylogeny.data.BinaryCharacters;
72 import org.forester.phylogeny.data.Confidence;
73 import org.forester.phylogeny.iterators.PhylogenyNodeIterator;
74 import org.forester.surfacing.DomainSimilarityCalculator.Detailedness;
75 import org.forester.surfacing.DomainSimilarityCalculator.GoAnnotationOutput;
76 import org.forester.surfacing.GenomeWideCombinableDomains.GenomeWideCombinableDomainsSortOrder;
77 import org.forester.util.AsciiHistogram;
78 import org.forester.util.BasicDescriptiveStatistics;
79 import org.forester.util.BasicTable;
80 import org.forester.util.BasicTableParser;
81 import org.forester.util.DescriptiveStatistics;
82 import org.forester.util.ForesterUtil;
84 public final class SurfacingUtil {
86 private final static NumberFormat FORMATTER = new DecimalFormat( "0.0E0" );
87 private final static NumberFormat FORMATTER_3 = new DecimalFormat( "0.000" );
88 private static final Comparator<Domain> ASCENDING_CONFIDENCE_VALUE_ORDER = new Comparator<Domain>() {
91 public int compare( final Domain d1,
93 if ( d1.getPerSequenceEvalue() < d2
94 .getPerSequenceEvalue() ) {
98 .getPerSequenceEvalue() > d2
99 .getPerSequenceEvalue() ) {
103 return d1.compareTo( d2 );
107 public final static Pattern PATTERN_SP_STYLE_TAXONOMY = Pattern.compile( "^[A-Z0-9]{3,5}$" );
109 private SurfacingUtil() {
110 // Hidden constructor.
113 public static void addAllBinaryDomainCombinationToSet( final GenomeWideCombinableDomains genome,
114 final SortedSet<BinaryDomainCombination> binary_domain_combinations ) {
115 final SortedMap<DomainId, CombinableDomains> all_cd = genome.getAllCombinableDomainsIds();
116 for( final DomainId domain_id : all_cd.keySet() ) {
117 binary_domain_combinations.addAll( all_cd.get( domain_id ).toBinaryDomainCombinations() );
121 public static void addAllDomainIdsToSet( final GenomeWideCombinableDomains genome,
122 final SortedSet<DomainId> domain_ids ) {
123 final SortedSet<DomainId> domains = genome.getAllDomainIds();
124 for( final DomainId domain : domains ) {
125 domain_ids.add( domain );
129 public static void addHtmlHead( final Writer w, final String title ) throws IOException {
130 w.write( SurfacingConstants.NL );
132 w.write( "<title>" );
134 w.write( "</title>" );
135 w.write( SurfacingConstants.NL );
136 w.write( "<style>" );
137 w.write( SurfacingConstants.NL );
138 w.write( "a:visited { color : #6633FF; text-decoration : none; }" );
139 w.write( SurfacingConstants.NL );
140 w.write( "a:link { color : #6633FF; text-decoration : none; }" );
141 w.write( SurfacingConstants.NL );
142 w.write( "a:active { color : #99FF00; text-decoration : none; }" );
143 w.write( SurfacingConstants.NL );
144 w.write( "a:hover { color : #FFFFFF; background-color : #99FF00; text-decoration : none; }" );
145 w.write( SurfacingConstants.NL );
146 w.write( "td { text-align: left; vertical-align: top; font-family: Verdana, Arial, Helvetica; font-size: 8pt}" );
147 w.write( SurfacingConstants.NL );
148 w.write( "h1 { color : #0000FF; font-family: Verdana, Arial, Helvetica; font-size: 18pt; font-weight: bold }" );
149 w.write( SurfacingConstants.NL );
150 w.write( "h2 { color : #0000FF; font-family: Verdana, Arial, Helvetica; font-size: 16pt; font-weight: bold }" );
151 w.write( SurfacingConstants.NL );
152 w.write( "</style>" );
153 w.write( SurfacingConstants.NL );
154 w.write( "</head>" );
155 w.write( SurfacingConstants.NL );
158 public static DescriptiveStatistics calculateDescriptiveStatisticsForMeanValues( final Set<DomainSimilarity> similarities ) {
159 final DescriptiveStatistics stats = new BasicDescriptiveStatistics();
160 for( final DomainSimilarity similarity : similarities ) {
161 stats.addValue( similarity.getMeanSimilarityScore() );
166 private static void calculateIndependentDomainCombinationGains( final Phylogeny local_phylogeny_l,
167 final String outfilename_for_counts,
168 final String outfilename_for_dc,
169 final String outfilename_for_dc_for_go_mapping,
170 final String outfilename_for_dc_for_go_mapping_unique,
171 final String outfilename_for_rank_counts,
172 final String outfilename_for_ancestor_species_counts ) {
174 final BufferedWriter out_counts = new BufferedWriter( new FileWriter( outfilename_for_counts ) );
175 final BufferedWriter out_dc = new BufferedWriter( new FileWriter( outfilename_for_dc ) );
176 final BufferedWriter out_dc_for_go_mapping = new BufferedWriter( new FileWriter( outfilename_for_dc_for_go_mapping ) );
177 final BufferedWriter out_dc_for_go_mapping_unique = new BufferedWriter( new FileWriter( outfilename_for_dc_for_go_mapping_unique ) );
178 final SortedMap<String, Integer> dc_gain_counts = new TreeMap<String, Integer>();
179 for( final PhylogenyNodeIterator it = local_phylogeny_l.iteratorPostorder(); it.hasNext(); ) {
180 final PhylogenyNode n = it.next();
181 final Set<String> gained_dc = n.getNodeData().getBinaryCharacters().getGainedCharacters();
182 for( final String dc : gained_dc ) {
183 if ( dc_gain_counts.containsKey( dc ) ) {
184 dc_gain_counts.put( dc, dc_gain_counts.get( dc ) + 1 );
187 dc_gain_counts.put( dc, 1 );
191 final SortedMap<Integer, Integer> histogram = new TreeMap<Integer, Integer>();
192 final SortedMap<Integer, StringBuilder> domain_lists = new TreeMap<Integer, StringBuilder>();
193 final SortedMap<Integer, PriorityQueue<String>> domain_lists_go = new TreeMap<Integer, PriorityQueue<String>>();
194 final SortedMap<Integer, SortedSet<String>> domain_lists_go_unique = new TreeMap<Integer, SortedSet<String>>();
195 final Set<String> dcs = dc_gain_counts.keySet();
196 final SortedSet<String> more_than_once = new TreeSet<String>();
197 for( final String dc : dcs ) {
198 final int count = dc_gain_counts.get( dc );
199 if ( histogram.containsKey( count ) ) {
200 histogram.put( count, histogram.get( count ) + 1 );
201 domain_lists.get( count ).append( ", " + dc );
202 domain_lists_go.get( count ).addAll( splitDomainCombination( dc ) );
203 domain_lists_go_unique.get( count ).addAll( splitDomainCombination( dc ) );
206 histogram.put( count, 1 );
207 domain_lists.put( count, new StringBuilder( dc ) );
208 final PriorityQueue<String> q = new PriorityQueue<String>();
209 q.addAll( splitDomainCombination( dc ) );
210 domain_lists_go.put( count, q );
211 final SortedSet<String> set = new TreeSet<String>();
212 set.addAll( splitDomainCombination( dc ) );
213 domain_lists_go_unique.put( count, set );
216 more_than_once.add( dc );
219 final Set<Integer> histogram_keys = histogram.keySet();
220 for( final Integer histogram_key : histogram_keys ) {
221 final int count = histogram.get( histogram_key );
222 final StringBuilder dc = domain_lists.get( histogram_key );
223 out_counts.write( histogram_key + "\t" + count + ForesterUtil.LINE_SEPARATOR );
224 out_dc.write( histogram_key + "\t" + dc + ForesterUtil.LINE_SEPARATOR );
225 out_dc_for_go_mapping.write( "#" + histogram_key + ForesterUtil.LINE_SEPARATOR );
226 final Object[] sorted = domain_lists_go.get( histogram_key ).toArray();
227 Arrays.sort( sorted );
228 for( final Object domain : sorted ) {
229 out_dc_for_go_mapping.write( domain + ForesterUtil.LINE_SEPARATOR );
231 out_dc_for_go_mapping_unique.write( "#" + histogram_key + ForesterUtil.LINE_SEPARATOR );
232 for( final String domain : domain_lists_go_unique.get( histogram_key ) ) {
233 out_dc_for_go_mapping_unique.write( domain + ForesterUtil.LINE_SEPARATOR );
238 out_dc_for_go_mapping.close();
239 out_dc_for_go_mapping_unique.close();
241 final SortedMap<String, Integer> lca_rank_counts = new TreeMap<String, Integer>();
242 final SortedMap<String, Integer> lca_ancestor_species_counts = new TreeMap<String, Integer>();
243 for( final String dc : more_than_once ) {
244 final List<PhylogenyNode> nodes = new ArrayList<PhylogenyNode>();
245 for( final PhylogenyNodeIterator it = local_phylogeny_l.iteratorExternalForward(); it.hasNext(); ) {
246 final PhylogenyNode n = it.next();
247 if ( n.getNodeData().getBinaryCharacters().getGainedCharacters().contains( dc ) ) {
251 for( int i = 0; i < nodes.size() - 1; ++i ) {
252 for( int j = i + 1; j < nodes.size(); ++j ) {
253 final PhylogenyNode lca = PhylogenyMethods.getInstance().obtainLCA( nodes.get( i ),
255 String rank = "unknown";
256 if ( lca.getNodeData().isHasTaxonomy()
257 && !ForesterUtil.isEmpty( lca.getNodeData().getTaxonomy().getRank() ) ) {
258 rank = lca.getNodeData().getTaxonomy().getRank();
260 addToCountMap( lca_rank_counts, rank );
262 if ( lca.getNodeData().isHasTaxonomy()
263 && !ForesterUtil.isEmpty( lca.getNodeData().getTaxonomy().getScientificName() ) ) {
264 lca_species = lca.getNodeData().getTaxonomy().getScientificName();
266 else if ( lca.getNodeData().isHasTaxonomy()
267 && !ForesterUtil.isEmpty( lca.getNodeData().getTaxonomy().getCommonName() ) ) {
268 lca_species = lca.getNodeData().getTaxonomy().getCommonName();
271 lca_species = lca.getName();
273 addToCountMap( lca_ancestor_species_counts, lca_species );
277 final BufferedWriter out_for_rank_counts = new BufferedWriter( new FileWriter( outfilename_for_rank_counts ) );
278 final BufferedWriter out_for_ancestor_species_counts = new BufferedWriter( new FileWriter( outfilename_for_ancestor_species_counts ) );
279 ForesterUtil.map2writer( out_for_rank_counts, lca_rank_counts, "\t", ForesterUtil.LINE_SEPARATOR );
280 ForesterUtil.map2writer( out_for_ancestor_species_counts,
281 lca_ancestor_species_counts,
283 ForesterUtil.LINE_SEPARATOR );
284 out_for_rank_counts.close();
285 out_for_ancestor_species_counts.close();
287 catch ( final IOException e ) {
288 ForesterUtil.printWarningMessage( surfacing.PRG_NAME, "Failure to write: " + e );
290 ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote independent domain combination gains fitch counts to ["
291 + outfilename_for_counts + "]" );
292 ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote independent domain combination gains fitch lists to ["
293 + outfilename_for_dc + "]" );
294 ForesterUtil.programMessage( surfacing.PRG_NAME,
295 "Wrote independent domain combination gains fitch lists to (for GO mapping) ["
296 + outfilename_for_dc_for_go_mapping + "]" );
297 ForesterUtil.programMessage( surfacing.PRG_NAME,
298 "Wrote independent domain combination gains fitch lists to (for GO mapping, unique) ["
299 + outfilename_for_dc_for_go_mapping_unique + "]" );
302 private final static void addToCountMap( final Map<String, Integer> map, final String s ) {
303 if ( map.containsKey( s ) ) {
304 map.put( s, map.get( s ) + 1 );
311 public static int calculateOverlap( final Domain domain, final List<Boolean> covered_positions ) {
312 int overlap_count = 0;
313 for( int i = domain.getFrom(); i <= domain.getTo(); ++i ) {
314 if ( ( i < covered_positions.size() ) && ( covered_positions.get( i ) == true ) ) {
318 return overlap_count;
321 public static void checkForOutputFileWriteability( final File outfile ) {
322 final String error = ForesterUtil.isWritableFile( outfile );
323 if ( !ForesterUtil.isEmpty( error ) ) {
324 ForesterUtil.fatalError( surfacing.PRG_NAME, error );
328 private static SortedSet<String> collectAllDomainsChangedOnSubtree( final PhylogenyNode subtree_root,
329 final boolean get_gains ) {
330 final SortedSet<String> domains = new TreeSet<String>();
331 for( final PhylogenyNode descendant : PhylogenyMethods.getAllDescendants( subtree_root ) ) {
332 final BinaryCharacters chars = descendant.getNodeData().getBinaryCharacters();
334 domains.addAll( chars.getGainedCharacters() );
337 domains.addAll( chars.getLostCharacters() );
343 public static void collectChangedDomainCombinationsFromBinaryStatesMatrixAsListToFile( final CharacterStateMatrix<CharacterStateMatrix.GainLossStates> matrix,
344 final BinaryDomainCombination.DomainCombinationType dc_type,
345 final List<BinaryDomainCombination> all_binary_domains_combination_gained,
346 final boolean get_gains ) {
347 final SortedSet<String> sorted_ids = new TreeSet<String>();
348 for( int i = 0; i < matrix.getNumberOfIdentifiers(); ++i ) {
349 sorted_ids.add( matrix.getIdentifier( i ) );
351 for( final String id : sorted_ids ) {
352 for( int c = 0; c < matrix.getNumberOfCharacters(); ++c ) {
353 if ( ( get_gains && ( matrix.getState( id, c ) == CharacterStateMatrix.GainLossStates.GAIN ) )
354 || ( !get_gains && ( matrix.getState( id, c ) == CharacterStateMatrix.GainLossStates.LOSS ) ) ) {
355 if ( dc_type == BinaryDomainCombination.DomainCombinationType.DIRECTED_ADJACTANT ) {
356 all_binary_domains_combination_gained.add( AdjactantDirectedBinaryDomainCombination
357 .createInstance( matrix.getCharacter( c ) ) );
359 else if ( dc_type == BinaryDomainCombination.DomainCombinationType.DIRECTED ) {
360 all_binary_domains_combination_gained.add( DirectedBinaryDomainCombination
361 .createInstance( matrix.getCharacter( c ) ) );
364 all_binary_domains_combination_gained.add( BasicBinaryDomainCombination.createInstance( matrix
365 .getCharacter( c ) ) );
372 private static File createBaseDirForPerNodeDomainFiles( final String base_dir,
373 final boolean domain_combinations,
374 final CharacterStateMatrix.GainLossStates state,
375 final String outfile ) {
376 File per_node_go_mapped_domain_gain_loss_files_base_dir = new File( new File( outfile ).getParent()
377 + ForesterUtil.FILE_SEPARATOR + base_dir );
378 if ( !per_node_go_mapped_domain_gain_loss_files_base_dir.exists() ) {
379 per_node_go_mapped_domain_gain_loss_files_base_dir.mkdir();
381 if ( domain_combinations ) {
382 per_node_go_mapped_domain_gain_loss_files_base_dir = new File( per_node_go_mapped_domain_gain_loss_files_base_dir
383 + ForesterUtil.FILE_SEPARATOR + "DC" );
386 per_node_go_mapped_domain_gain_loss_files_base_dir = new File( per_node_go_mapped_domain_gain_loss_files_base_dir
387 + ForesterUtil.FILE_SEPARATOR + "DOMAINS" );
389 if ( !per_node_go_mapped_domain_gain_loss_files_base_dir.exists() ) {
390 per_node_go_mapped_domain_gain_loss_files_base_dir.mkdir();
392 if ( state == GainLossStates.GAIN ) {
393 per_node_go_mapped_domain_gain_loss_files_base_dir = new File( per_node_go_mapped_domain_gain_loss_files_base_dir
394 + ForesterUtil.FILE_SEPARATOR + "GAINS" );
396 else if ( state == GainLossStates.LOSS ) {
397 per_node_go_mapped_domain_gain_loss_files_base_dir = new File( per_node_go_mapped_domain_gain_loss_files_base_dir
398 + ForesterUtil.FILE_SEPARATOR + "LOSSES" );
401 per_node_go_mapped_domain_gain_loss_files_base_dir = new File( per_node_go_mapped_domain_gain_loss_files_base_dir
402 + ForesterUtil.FILE_SEPARATOR + "PRESENT" );
404 if ( !per_node_go_mapped_domain_gain_loss_files_base_dir.exists() ) {
405 per_node_go_mapped_domain_gain_loss_files_base_dir.mkdir();
407 return per_node_go_mapped_domain_gain_loss_files_base_dir;
410 public static Map<DomainId, List<GoId>> createDomainIdToGoIdMap( final List<PfamToGoMapping> pfam_to_go_mappings ) {
411 final Map<DomainId, List<GoId>> domain_id_to_go_ids_map = new HashMap<DomainId, List<GoId>>( pfam_to_go_mappings
413 for( final PfamToGoMapping pfam_to_go : pfam_to_go_mappings ) {
414 if ( !domain_id_to_go_ids_map.containsKey( pfam_to_go.getKey() ) ) {
415 domain_id_to_go_ids_map.put( pfam_to_go.getKey(), new ArrayList<GoId>() );
417 domain_id_to_go_ids_map.get( pfam_to_go.getKey() ).add( pfam_to_go.getValue() );
419 return domain_id_to_go_ids_map;
422 public static Map<DomainId, Set<String>> createDomainIdToSecondaryFeaturesMap( final File secondary_features_map_file )
424 final BasicTable<String> primary_table = BasicTableParser.parse( secondary_features_map_file, "\t" );
425 final Map<DomainId, Set<String>> map = new TreeMap<DomainId, Set<String>>();
426 for( int r = 0; r < primary_table.getNumberOfRows(); ++r ) {
427 final DomainId domain_id = new DomainId( primary_table.getValue( 0, r ) );
428 if ( !map.containsKey( domain_id ) ) {
429 map.put( domain_id, new HashSet<String>() );
431 map.get( domain_id ).add( primary_table.getValue( 1, r ) );
436 public static Phylogeny createNjTreeBasedOnMatrixToFile( final File nj_tree_outfile, final DistanceMatrix distance ) {
437 checkForOutputFileWriteability( nj_tree_outfile );
438 final NeighborJoining nj = NeighborJoining.createInstance();
439 final Phylogeny phylogeny = nj.execute( distance );
440 phylogeny.setName( nj_tree_outfile.getName() );
441 writePhylogenyToFile( phylogeny, nj_tree_outfile.toString() );
445 private static SortedSet<BinaryDomainCombination> createSetOfAllBinaryDomainCombinationsPerGenome( final GenomeWideCombinableDomains gwcd ) {
446 final SortedMap<DomainId, CombinableDomains> cds = gwcd.getAllCombinableDomainsIds();
447 final SortedSet<BinaryDomainCombination> binary_combinations = new TreeSet<BinaryDomainCombination>();
448 for( final DomainId domain_id : cds.keySet() ) {
449 final CombinableDomains cd = cds.get( domain_id );
450 binary_combinations.addAll( cd.toBinaryDomainCombinations() );
452 return binary_combinations;
455 public static void decoratePrintableDomainSimilarities( final SortedSet<DomainSimilarity> domain_similarities,
456 final Detailedness detailedness,
457 final GoAnnotationOutput go_annotation_output,
458 final Map<GoId, GoTerm> go_id_to_term_map,
459 final GoNameSpace go_namespace_limit ) {
460 if ( ( go_namespace_limit != null ) && ( ( go_id_to_term_map == null ) || go_id_to_term_map.isEmpty() ) ) {
461 throw new IllegalArgumentException( "attempt to use a GO namespace limit without a GO id to term map" );
463 for( final DomainSimilarity domain_similarity : domain_similarities ) {
464 if ( domain_similarity instanceof PrintableDomainSimilarity ) {
465 final PrintableDomainSimilarity printable_domain_similarity = ( PrintableDomainSimilarity ) domain_similarity;
466 printable_domain_similarity.setDetailedness( detailedness );
467 printable_domain_similarity.setGoAnnotationOutput( go_annotation_output );
468 printable_domain_similarity.setGoIdToTermMap( go_id_to_term_map );
469 printable_domain_similarity.setGoNamespaceLimit( go_namespace_limit );
474 public static void executeDomainLengthAnalysis( final String[][] input_file_properties,
475 final int number_of_genomes,
476 final DomainLengthsTable domain_lengths_table,
477 final File outfile ) throws IOException {
478 final DecimalFormat df = new DecimalFormat( "#.00" );
479 checkForOutputFileWriteability( outfile );
480 final BufferedWriter out = new BufferedWriter( new FileWriter( outfile ) );
481 out.write( "MEAN BASED STATISTICS PER SPECIES" );
482 out.write( ForesterUtil.LINE_SEPARATOR );
483 out.write( domain_lengths_table.createMeanBasedStatisticsPerSpeciesTable().toString() );
484 out.write( ForesterUtil.LINE_SEPARATOR );
485 out.write( ForesterUtil.LINE_SEPARATOR );
486 final List<DomainLengths> domain_lengths_list = domain_lengths_table.getDomainLengthsList();
487 out.write( "OUTLIER SPECIES PER DOMAIN (Z>=1.5)" );
488 out.write( ForesterUtil.LINE_SEPARATOR );
489 for( final DomainLengths domain_lengths : domain_lengths_list ) {
490 final List<Species> species_list = domain_lengths.getMeanBasedOutlierSpecies( 1.5 );
491 if ( species_list.size() > 0 ) {
492 out.write( domain_lengths.getDomainId() + "\t" );
493 for( final Species species : species_list ) {
494 out.write( species + "\t" );
496 out.write( ForesterUtil.LINE_SEPARATOR );
497 // DescriptiveStatistics stats_for_domain = domain_lengths
498 // .calculateMeanBasedStatistics();
499 //AsciiHistogram histo = new AsciiHistogram( stats_for_domain );
500 //System.out.println( histo.toStringBuffer( 40, '=', 60, 4 ).toString() );
503 out.write( ForesterUtil.LINE_SEPARATOR );
504 out.write( ForesterUtil.LINE_SEPARATOR );
505 out.write( "OUTLIER SPECIES (Z 1.0)" );
506 out.write( ForesterUtil.LINE_SEPARATOR );
507 final DescriptiveStatistics stats_for_all_species = domain_lengths_table
508 .calculateMeanBasedStatisticsForAllSpecies();
509 out.write( stats_for_all_species.asSummary() );
510 out.write( ForesterUtil.LINE_SEPARATOR );
511 final AsciiHistogram histo = new AsciiHistogram( stats_for_all_species );
512 out.write( histo.toStringBuffer( 40, '=', 60, 4 ).toString() );
513 out.write( ForesterUtil.LINE_SEPARATOR );
514 final double population_sd = stats_for_all_species.sampleStandardDeviation();
515 final double population_mean = stats_for_all_species.arithmeticMean();
516 for( final Species species : domain_lengths_table.getSpecies() ) {
517 final double x = domain_lengths_table.calculateMeanBasedStatisticsForSpecies( species ).arithmeticMean();
518 final double z = ( x - population_mean ) / population_sd;
519 out.write( species + "\t" + z );
520 out.write( ForesterUtil.LINE_SEPARATOR );
522 out.write( ForesterUtil.LINE_SEPARATOR );
523 for( final Species species : domain_lengths_table.getSpecies() ) {
524 final DescriptiveStatistics stats_for_species = domain_lengths_table
525 .calculateMeanBasedStatisticsForSpecies( species );
526 final double x = stats_for_species.arithmeticMean();
527 final double z = ( x - population_mean ) / population_sd;
528 if ( ( z <= -1.0 ) || ( z >= 1.0 ) ) {
529 out.write( species + "\t" + df.format( z ) + "\t" + stats_for_species.asSummary() );
530 out.write( ForesterUtil.LINE_SEPARATOR );
534 // final List<HistogramData> histogram_datas = new ArrayList<HistogramData>();
535 // for( int i = 0; i < number_of_genomes; ++i ) {
536 // final Species species = new BasicSpecies( input_file_properties[ i ][ 0 ] );
538 // .add( new HistogramData( species.toString(), domain_lengths_table
539 // .calculateMeanBasedStatisticsForSpecies( species )
540 // .getDataAsDoubleArray(), 5, 600, null, 60 ) );
542 // final HistogramsFrame hf = new HistogramsFrame( histogram_datas );
543 // hf.setVisible( true );
549 * @param all_binary_domains_combination_lost_fitch
550 * @param consider_directedness_and_adjacency_for_bin_combinations
551 * @param all_binary_domains_combination_gained if null ignored, otherwise this is to list all binary domain combinations
552 * which were gained under unweighted (Fitch) parsimony.
554 public static void executeParsimonyAnalysis( final long random_number_seed_for_fitch_parsimony,
555 final boolean radomize_fitch_parsimony,
556 final String outfile_name,
557 final DomainParsimonyCalculator domain_parsimony,
558 final Phylogeny phylogeny,
559 final Map<DomainId, List<GoId>> domain_id_to_go_ids_map,
560 final Map<GoId, GoTerm> go_id_to_term_map,
561 final GoNameSpace go_namespace_limit,
562 final String parameters_str,
563 final Map<DomainId, Set<String>>[] domain_id_to_secondary_features_maps,
564 final SortedSet<DomainId> positive_filter,
565 final boolean output_binary_domain_combinations_for_graphs,
566 final List<BinaryDomainCombination> all_binary_domains_combination_gained_fitch,
567 final List<BinaryDomainCombination> all_binary_domains_combination_lost_fitch,
568 final BinaryDomainCombination.DomainCombinationType dc_type ) {
569 final String sep = ForesterUtil.LINE_SEPARATOR + "###################" + ForesterUtil.LINE_SEPARATOR;
570 final String date_time = ForesterUtil.getCurrentDateTime();
571 final SortedSet<String> all_pfams_encountered = new TreeSet<String>();
572 final SortedSet<String> all_pfams_gained_as_domains = new TreeSet<String>();
573 final SortedSet<String> all_pfams_lost_as_domains = new TreeSet<String>();
574 final SortedSet<String> all_pfams_gained_as_dom_combinations = new TreeSet<String>();
575 final SortedSet<String> all_pfams_lost_as_dom_combinations = new TreeSet<String>();
576 writeToNexus( outfile_name, domain_parsimony, phylogeny );
579 Phylogeny local_phylogeny_l = phylogeny.copy();
580 if ( ( positive_filter != null ) && ( positive_filter.size() > 0 ) ) {
581 domain_parsimony.executeDolloParsimonyOnDomainPresence( positive_filter );
584 domain_parsimony.executeDolloParsimonyOnDomainPresence();
586 SurfacingUtil.writeMatrixToFile( domain_parsimony.getGainLossMatrix(), outfile_name
587 + surfacing.PARSIMONY_OUTPUT_GL_SUFFIX_DOLLO_DOMAINS, Format.FORESTER );
588 SurfacingUtil.writeMatrixToFile( domain_parsimony.getGainLossCountsMatrix(), outfile_name
589 + surfacing.PARSIMONY_OUTPUT_GL_COUNTS_SUFFIX_DOLLO_DOMAINS, Format.FORESTER );
590 SurfacingUtil.writeBinaryStatesMatrixAsListToFile( domain_parsimony.getGainLossMatrix(),
591 CharacterStateMatrix.GainLossStates.GAIN,
592 outfile_name + surfacing.PARSIMONY_OUTPUT_DOLLO_GAINS_D,
594 ForesterUtil.LINE_SEPARATOR,
596 SurfacingUtil.writeBinaryStatesMatrixAsListToFile( domain_parsimony.getGainLossMatrix(),
597 CharacterStateMatrix.GainLossStates.LOSS,
598 outfile_name + surfacing.PARSIMONY_OUTPUT_DOLLO_LOSSES_D,
600 ForesterUtil.LINE_SEPARATOR,
602 SurfacingUtil.writeBinaryStatesMatrixAsListToFile( domain_parsimony.getGainLossMatrix(), null, outfile_name
603 + surfacing.PARSIMONY_OUTPUT_DOLLO_PRESENT_D, sep, ForesterUtil.LINE_SEPARATOR, null );
605 writeBinaryStatesMatrixToList( domain_id_to_go_ids_map,
609 domain_parsimony.getGainLossMatrix(),
610 CharacterStateMatrix.GainLossStates.GAIN,
611 outfile_name + surfacing.PARSIMONY_OUTPUT_DOLLO_GAINS_HTML_D,
613 ForesterUtil.LINE_SEPARATOR,
614 "Dollo Parsimony | Gains | Domains",
616 domain_id_to_secondary_features_maps,
617 all_pfams_encountered,
618 all_pfams_gained_as_domains,
620 writeBinaryStatesMatrixToList( domain_id_to_go_ids_map,
624 domain_parsimony.getGainLossMatrix(),
625 CharacterStateMatrix.GainLossStates.LOSS,
626 outfile_name + surfacing.PARSIMONY_OUTPUT_DOLLO_LOSSES_HTML_D,
628 ForesterUtil.LINE_SEPARATOR,
629 "Dollo Parsimony | Losses | Domains",
631 domain_id_to_secondary_features_maps,
632 all_pfams_encountered,
633 all_pfams_lost_as_domains,
635 writeBinaryStatesMatrixToList( domain_id_to_go_ids_map,
639 domain_parsimony.getGainLossMatrix(),
641 outfile_name + surfacing.PARSIMONY_OUTPUT_DOLLO_PRESENT_HTML_D,
643 ForesterUtil.LINE_SEPARATOR,
644 "Dollo Parsimony | Present | Domains",
646 domain_id_to_secondary_features_maps,
647 all_pfams_encountered,
649 "_dollo_present_d" );
650 preparePhylogeny( local_phylogeny_l,
653 "Dollo parsimony on domain presence/absence",
654 "dollo_on_domains_" + outfile_name,
656 SurfacingUtil.writePhylogenyToFile( local_phylogeny_l, outfile_name
657 + surfacing.DOMAINS_PARSIMONY_TREE_OUTPUT_SUFFIX_DOLLO );
659 writeAllDomainsChangedOnAllSubtrees( local_phylogeny_l, true, outfile_name, "_dollo_all_gains_d" );
660 writeAllDomainsChangedOnAllSubtrees( local_phylogeny_l, false, outfile_name, "_dollo_all_losses_d" );
662 catch ( final IOException e ) {
664 ForesterUtil.fatalError( surfacing.PRG_NAME, e.getLocalizedMessage() );
666 if ( domain_parsimony.calculateNumberOfBinaryDomainCombination() > 0 ) {
667 // FITCH DOMAIN COMBINATIONS
668 // -------------------------
669 local_phylogeny_l = phylogeny.copy();
670 String randomization = "no";
671 if ( radomize_fitch_parsimony ) {
672 domain_parsimony.executeFitchParsimonyOnBinaryDomainCombintion( random_number_seed_for_fitch_parsimony );
673 randomization = "yes, seed = " + random_number_seed_for_fitch_parsimony;
676 domain_parsimony.executeFitchParsimonyOnBinaryDomainCombintion( true );
678 SurfacingUtil.writeMatrixToFile( domain_parsimony.getGainLossMatrix(), outfile_name
679 + surfacing.PARSIMONY_OUTPUT_GL_SUFFIX_FITCH_BINARY_COMBINATIONS, Format.FORESTER );
680 SurfacingUtil.writeMatrixToFile( domain_parsimony.getGainLossCountsMatrix(), outfile_name
681 + surfacing.PARSIMONY_OUTPUT_GL_COUNTS_SUFFIX_FITCH_BINARY_COMBINATIONS, Format.FORESTER );
683 .writeBinaryStatesMatrixAsListToFile( domain_parsimony.getGainLossMatrix(),
684 CharacterStateMatrix.GainLossStates.GAIN,
685 outfile_name + surfacing.PARSIMONY_OUTPUT_FITCH_GAINS_BC,
687 ForesterUtil.LINE_SEPARATOR,
689 SurfacingUtil.writeBinaryStatesMatrixAsListToFile( domain_parsimony.getGainLossMatrix(),
690 CharacterStateMatrix.GainLossStates.LOSS,
692 + surfacing.PARSIMONY_OUTPUT_FITCH_LOSSES_BC,
694 ForesterUtil.LINE_SEPARATOR,
696 SurfacingUtil.writeBinaryStatesMatrixAsListToFile( domain_parsimony.getGainLossMatrix(), null, outfile_name
697 + surfacing.PARSIMONY_OUTPUT_FITCH_PRESENT_BC, sep, ForesterUtil.LINE_SEPARATOR, null );
698 if ( all_binary_domains_combination_gained_fitch != null ) {
699 collectChangedDomainCombinationsFromBinaryStatesMatrixAsListToFile( domain_parsimony.getGainLossMatrix(),
701 all_binary_domains_combination_gained_fitch,
704 if ( all_binary_domains_combination_lost_fitch != null ) {
705 collectChangedDomainCombinationsFromBinaryStatesMatrixAsListToFile( domain_parsimony.getGainLossMatrix(),
707 all_binary_domains_combination_lost_fitch,
710 if ( output_binary_domain_combinations_for_graphs ) {
712 .writeBinaryStatesMatrixAsListToFileForBinaryCombinationsForGraphAnalysis( domain_parsimony
713 .getGainLossMatrix(),
716 + surfacing.PARSIMONY_OUTPUT_FITCH_PRESENT_BC_OUTPUTFILE_SUFFIX_FOR_GRAPH_ANALYSIS,
718 ForesterUtil.LINE_SEPARATOR,
719 BinaryDomainCombination.OutputFormat.DOT );
722 writeBinaryStatesMatrixToList( domain_id_to_go_ids_map,
726 domain_parsimony.getGainLossMatrix(),
727 CharacterStateMatrix.GainLossStates.GAIN,
728 outfile_name + surfacing.PARSIMONY_OUTPUT_FITCH_GAINS_HTML_BC,
730 ForesterUtil.LINE_SEPARATOR,
731 "Fitch Parsimony | Gains | Domain Combinations",
734 all_pfams_encountered,
735 all_pfams_gained_as_dom_combinations,
737 writeBinaryStatesMatrixToList( domain_id_to_go_ids_map,
741 domain_parsimony.getGainLossMatrix(),
742 CharacterStateMatrix.GainLossStates.LOSS,
743 outfile_name + surfacing.PARSIMONY_OUTPUT_FITCH_LOSSES_HTML_BC,
745 ForesterUtil.LINE_SEPARATOR,
746 "Fitch Parsimony | Losses | Domain Combinations",
749 all_pfams_encountered,
750 all_pfams_lost_as_dom_combinations,
751 "_fitch_losses_dc" );
752 writeBinaryStatesMatrixToList( domain_id_to_go_ids_map,
756 domain_parsimony.getGainLossMatrix(),
758 outfile_name + surfacing.PARSIMONY_OUTPUT_FITCH_PRESENT_HTML_BC,
760 ForesterUtil.LINE_SEPARATOR,
761 "Fitch Parsimony | Present | Domain Combinations",
764 all_pfams_encountered,
766 "_fitch_present_dc" );
767 writeAllEncounteredPfamsToFile( domain_id_to_go_ids_map,
770 all_pfams_encountered );
771 writePfamsToFile( outfile_name + surfacing.ALL_PFAMS_GAINED_AS_DOMAINS_SUFFIX, all_pfams_gained_as_domains );
772 writePfamsToFile( outfile_name + surfacing.ALL_PFAMS_LOST_AS_DOMAINS_SUFFIX, all_pfams_lost_as_domains );
773 writePfamsToFile( outfile_name + surfacing.ALL_PFAMS_GAINED_AS_DC_SUFFIX,
774 all_pfams_gained_as_dom_combinations );
775 writePfamsToFile( outfile_name + surfacing.ALL_PFAMS_LOST_AS_DC_SUFFIX, all_pfams_lost_as_dom_combinations );
776 preparePhylogeny( local_phylogeny_l,
779 "Fitch parsimony on binary domain combination presence/absence randomization: "
781 "fitch_on_binary_domain_combinations_" + outfile_name,
783 SurfacingUtil.writePhylogenyToFile( local_phylogeny_l, outfile_name
784 + surfacing.BINARY_DOMAIN_COMBINATIONS_PARSIMONY_TREE_OUTPUT_SUFFIX_FITCH );
785 calculateIndependentDomainCombinationGains( local_phylogeny_l, outfile_name
786 + surfacing.INDEPENDENT_DC_GAINS_FITCH_PARS_COUNTS_OUTPUT_SUFFIX, outfile_name
787 + surfacing.INDEPENDENT_DC_GAINS_FITCH_PARS_DC_OUTPUT_SUFFIX, outfile_name
788 + surfacing.INDEPENDENT_DC_GAINS_FITCH_PARS_DC_FOR_GO_MAPPING_OUTPUT_SUFFIX, outfile_name
789 + surfacing.INDEPENDENT_DC_GAINS_FITCH_PARS_DC_FOR_GO_MAPPING_OUTPUT_UNIQUE_SUFFIX, outfile_name
790 + "_indep_dc_gains_fitch_lca_ranks.txt", outfile_name + "_indep_dc_gains_fitch_lca_taxonomies.txt" );
794 public static void executeParsimonyAnalysisForSecondaryFeatures( final String outfile_name,
795 final DomainParsimonyCalculator secondary_features_parsimony,
796 final Phylogeny phylogeny,
797 final String parameters_str,
798 final Map<Species, MappingResults> mapping_results_map ) {
799 final String sep = ForesterUtil.LINE_SEPARATOR + "###################" + ForesterUtil.LINE_SEPARATOR;
800 final String date_time = ForesterUtil.getCurrentDateTime();
801 System.out.println();
802 writeToNexus( outfile_name + surfacing.NEXUS_SECONDARY_FEATURES,
803 secondary_features_parsimony.createMatrixOfSecondaryFeaturePresenceOrAbsence( null ),
805 final Phylogeny local_phylogeny_copy = phylogeny.copy();
806 secondary_features_parsimony.executeDolloParsimonyOnSecondaryFeatures( mapping_results_map );
807 SurfacingUtil.writeMatrixToFile( secondary_features_parsimony.getGainLossMatrix(), outfile_name
808 + surfacing.PARSIMONY_OUTPUT_GL_SUFFIX_DOLLO_SECONDARY_FEATURES, Format.FORESTER );
809 SurfacingUtil.writeMatrixToFile( secondary_features_parsimony.getGainLossCountsMatrix(), outfile_name
810 + surfacing.PARSIMONY_OUTPUT_GL_COUNTS_SUFFIX_DOLLO_SECONDARY_FEATURES, Format.FORESTER );
812 .writeBinaryStatesMatrixAsListToFile( secondary_features_parsimony.getGainLossMatrix(),
813 CharacterStateMatrix.GainLossStates.GAIN,
815 + surfacing.PARSIMONY_OUTPUT_DOLLO_GAINS_SECONDARY_FEATURES,
817 ForesterUtil.LINE_SEPARATOR,
820 .writeBinaryStatesMatrixAsListToFile( secondary_features_parsimony.getGainLossMatrix(),
821 CharacterStateMatrix.GainLossStates.LOSS,
823 + surfacing.PARSIMONY_OUTPUT_DOLLO_LOSSES_SECONDARY_FEATURES,
825 ForesterUtil.LINE_SEPARATOR,
828 .writeBinaryStatesMatrixAsListToFile( secondary_features_parsimony.getGainLossMatrix(),
831 + surfacing.PARSIMONY_OUTPUT_DOLLO_PRESENT_SECONDARY_FEATURES,
833 ForesterUtil.LINE_SEPARATOR,
835 preparePhylogeny( local_phylogeny_copy,
836 secondary_features_parsimony,
838 "Dollo parsimony on secondary feature presence/absence",
839 "dollo_on_secondary_features_" + outfile_name,
841 SurfacingUtil.writePhylogenyToFile( local_phylogeny_copy, outfile_name
842 + surfacing.SECONDARY_FEATURES_PARSIMONY_TREE_OUTPUT_SUFFIX_DOLLO );
845 public static void extractProteinNames( final List<Protein> proteins,
846 final List<DomainId> query_domain_ids_nc_order,
848 final String separator,
849 final String limit_to_species ) throws IOException {
850 for( final Protein protein : proteins ) {
851 if ( ForesterUtil.isEmpty( limit_to_species )
852 || protein.getSpecies().getSpeciesId().equalsIgnoreCase( limit_to_species ) ) {
853 if ( protein.contains( query_domain_ids_nc_order, true ) ) {
854 out.write( protein.getSpecies().getSpeciesId() );
855 out.write( separator );
856 out.write( protein.getProteinId().getId() );
857 out.write( separator );
859 final Set<DomainId> visited_domain_ids = new HashSet<DomainId>();
860 boolean first = true;
861 for( final Domain domain : protein.getProteinDomains() ) {
862 if ( !visited_domain_ids.contains( domain.getDomainId() ) ) {
863 visited_domain_ids.add( domain.getDomainId() );
870 out.write( domain.getDomainId().getId() );
872 out.write( "" + domain.getTotalCount() );
877 out.write( separator );
878 if ( !( ForesterUtil.isEmpty( protein.getDescription() ) || protein.getDescription()
879 .equals( SurfacingConstants.NONE ) ) ) {
880 out.write( protein.getDescription() );
882 out.write( separator );
883 if ( !( ForesterUtil.isEmpty( protein.getAccession() ) || protein.getAccession()
884 .equals( SurfacingConstants.NONE ) ) ) {
885 out.write( protein.getAccession() );
887 out.write( SurfacingConstants.NL );
894 public static void extractProteinNames( final SortedMap<Species, List<Protein>> protein_lists_per_species,
895 final DomainId domain_id,
897 final String separator,
898 final String limit_to_species ) throws IOException {
899 for( final Species species : protein_lists_per_species.keySet() ) {
900 for( final Protein protein : protein_lists_per_species.get( species ) ) {
901 if ( ForesterUtil.isEmpty( limit_to_species )
902 || protein.getSpecies().getSpeciesId().equalsIgnoreCase( limit_to_species ) ) {
903 final List<Domain> domains = protein.getProteinDomains( domain_id );
904 if ( domains.size() > 0 ) {
905 final DescriptiveStatistics stats = new BasicDescriptiveStatistics();
906 for( final Domain domain : domains ) {
907 stats.addValue( domain.getPerSequenceEvalue() );
909 out.write( protein.getSpecies().getSpeciesId() );
910 out.write( separator );
911 out.write( protein.getProteinId().getId() );
912 out.write( separator );
913 out.write( "[" + FORMATTER.format( stats.median() ) + "]" );
914 out.write( separator );
915 if ( !( ForesterUtil.isEmpty( protein.getDescription() ) || protein.getDescription()
916 .equals( SurfacingConstants.NONE ) ) ) {
917 out.write( protein.getDescription() );
919 out.write( separator );
920 if ( !( ForesterUtil.isEmpty( protein.getAccession() ) || protein.getAccession()
921 .equals( SurfacingConstants.NONE ) ) ) {
922 out.write( protein.getAccession() );
924 out.write( SurfacingConstants.NL );
932 public static SortedSet<DomainId> getAllDomainIds( final List<GenomeWideCombinableDomains> gwcd_list ) {
933 final SortedSet<DomainId> all_domains_ids = new TreeSet<DomainId>();
934 for( final GenomeWideCombinableDomains gwcd : gwcd_list ) {
935 final Set<DomainId> all_domains = gwcd.getAllDomainIds();
936 // for( final Domain domain : all_domains ) {
937 all_domains_ids.addAll( all_domains );
940 return all_domains_ids;
943 public static SortedMap<String, Integer> getDomainCounts( final List<Protein> protein_domain_collections ) {
944 final SortedMap<String, Integer> map = new TreeMap<String, Integer>();
945 for( final Protein protein_domain_collection : protein_domain_collections ) {
946 for( final Object name : protein_domain_collection.getProteinDomains() ) {
947 final BasicDomain protein_domain = ( BasicDomain ) name;
948 final String id = protein_domain.getDomainId().getId();
949 if ( map.containsKey( id ) ) {
950 map.put( id, map.get( id ) + 1 );
960 public static int getNumberOfNodesLackingName( final Phylogeny p, final StringBuilder names ) {
961 final PhylogenyNodeIterator it = p.iteratorPostorder();
963 while ( it.hasNext() ) {
964 final PhylogenyNode n = it.next();
965 if ( ForesterUtil.isEmpty( n.getName() )
966 && ( !n.getNodeData().isHasTaxonomy() || ForesterUtil.isEmpty( n.getNodeData().getTaxonomy()
967 .getScientificName() ) )
968 && ( !n.getNodeData().isHasTaxonomy() || ForesterUtil.isEmpty( n.getNodeData().getTaxonomy()
969 .getCommonName() ) ) ) {
970 if ( n.getParent() != null ) {
972 names.append( n.getParent().getName() );
974 final List l = n.getAllExternalDescendants();
975 for( final Object object : l ) {
976 System.out.println( l.toString() );
985 * Returns true is Domain domain falls in an uninterrupted stretch of
989 * @param covered_positions
992 public static boolean isEngulfed( final Domain domain, final List<Boolean> covered_positions ) {
993 for( int i = domain.getFrom(); i <= domain.getTo(); ++i ) {
994 if ( ( i >= covered_positions.size() ) || ( covered_positions.get( i ) != true ) ) {
1001 public static void preparePhylogeny( final Phylogeny p,
1002 final DomainParsimonyCalculator domain_parsimony,
1003 final String date_time,
1004 final String method,
1006 final String parameters_str ) {
1007 domain_parsimony.decoratePhylogenyWithDomains( p );
1008 final StringBuilder desc = new StringBuilder();
1009 desc.append( "[Method: " + method + "] [Date: " + date_time + "] " );
1010 desc.append( "[Cost: " + domain_parsimony.getCost() + "] " );
1011 desc.append( "[Gains: " + domain_parsimony.getTotalGains() + "] " );
1012 desc.append( "[Losses: " + domain_parsimony.getTotalLosses() + "] " );
1013 desc.append( "[Unchanged: " + domain_parsimony.getTotalUnchanged() + "] " );
1014 desc.append( "[Parameters: " + parameters_str + "]" );
1016 p.setDescription( desc.toString() );
1017 p.setConfidence( new Confidence( domain_parsimony.getCost(), "parsimony" ) );
1018 p.setRerootable( false );
1019 p.setRooted( true );
1023 * species | protein id | n-terminal domain | c-terminal domain | n-terminal domain per domain E-value | c-terminal domain per domain E-value
1027 static public StringBuffer proteinToDomainCombinations( final Protein protein,
1028 final String protein_id,
1029 final String separator ) {
1030 final StringBuffer sb = new StringBuffer();
1031 if ( protein.getSpecies() == null ) {
1032 throw new IllegalArgumentException( "species must not be null" );
1034 if ( ForesterUtil.isEmpty( protein.getSpecies().getSpeciesId() ) ) {
1035 throw new IllegalArgumentException( "species id must not be empty" );
1037 final List<Domain> domains = protein.getProteinDomains();
1038 if ( domains.size() > 1 ) {
1039 final Map<String, Integer> counts = new HashMap<String, Integer>();
1040 for( final Domain domain : domains ) {
1041 final String id = domain.getDomainId().getId();
1042 if ( counts.containsKey( id ) ) {
1043 counts.put( id, counts.get( id ) + 1 );
1046 counts.put( id, 1 );
1049 final Set<String> dcs = new HashSet<String>();
1050 for( int i = 1; i < domains.size(); ++i ) {
1051 for( int j = 0; j < i; ++j ) {
1052 Domain domain_n = domains.get( i );
1053 Domain domain_c = domains.get( j );
1054 if ( domain_n.getFrom() > domain_c.getFrom() ) {
1055 domain_n = domains.get( j );
1056 domain_c = domains.get( i );
1058 final String dc = domain_n.getDomainId().getId() + domain_c.getDomainId().getId();
1059 if ( !dcs.contains( dc ) ) {
1061 sb.append( protein.getSpecies() );
1062 sb.append( separator );
1063 sb.append( protein_id );
1064 sb.append( separator );
1065 sb.append( domain_n.getDomainId().getId() );
1066 sb.append( separator );
1067 sb.append( domain_c.getDomainId().getId() );
1068 sb.append( separator );
1069 sb.append( domain_n.getPerDomainEvalue() );
1070 sb.append( separator );
1071 sb.append( domain_c.getPerDomainEvalue() );
1072 sb.append( separator );
1073 sb.append( counts.get( domain_n.getDomainId().getId() ) );
1074 sb.append( separator );
1075 sb.append( counts.get( domain_c.getDomainId().getId() ) );
1076 sb.append( ForesterUtil.LINE_SEPARATOR );
1081 else if ( domains.size() == 1 ) {
1082 sb.append( protein.getSpecies() );
1083 sb.append( separator );
1084 sb.append( protein_id );
1085 sb.append( separator );
1086 sb.append( domains.get( 0 ).getDomainId().getId() );
1087 sb.append( separator );
1088 sb.append( separator );
1089 sb.append( domains.get( 0 ).getPerDomainEvalue() );
1090 sb.append( separator );
1091 sb.append( separator );
1093 sb.append( separator );
1094 sb.append( ForesterUtil.LINE_SEPARATOR );
1097 sb.append( protein.getSpecies() );
1098 sb.append( separator );
1099 sb.append( protein_id );
1100 sb.append( separator );
1101 sb.append( separator );
1102 sb.append( separator );
1103 sb.append( separator );
1104 sb.append( separator );
1105 sb.append( separator );
1106 sb.append( ForesterUtil.LINE_SEPARATOR );
1113 * Example regarding engulfment: ------------0.1 ----------0.2 --0.3 =>
1114 * domain with 0.3 is ignored
1116 * -----------0.1 ----------0.2 --0.3 => domain with 0.3 is ignored
1119 * ------------0.1 ----------0.3 --0.2 => domains with 0.3 and 0.2 are _not_
1122 * @param max_allowed_overlap
1123 * maximal allowed overlap (inclusive) to be still considered not
1124 * overlapping (zero or negative value to allow any overlap)
1125 * @param remove_engulfed_domains
1126 * to remove domains which are completely engulfed by coverage of
1127 * domains with better support
1131 public static Protein removeOverlappingDomains( final int max_allowed_overlap,
1132 final boolean remove_engulfed_domains,
1133 final Protein protein ) {
1134 final Protein pruned_protein = new BasicProtein( protein.getProteinId().getId(), protein.getSpecies()
1136 final List<Domain> sorted = SurfacingUtil.sortDomainsWithAscendingConfidenceValues( protein );
1137 final List<Boolean> covered_positions = new ArrayList<Boolean>();
1138 for( final Domain domain : sorted ) {
1139 if ( ( ( max_allowed_overlap < 0 ) || ( SurfacingUtil.calculateOverlap( domain, covered_positions ) <= max_allowed_overlap ) )
1140 && ( !remove_engulfed_domains || !isEngulfed( domain, covered_positions ) ) ) {
1141 final int covered_positions_size = covered_positions.size();
1142 for( int i = covered_positions_size; i < domain.getFrom(); ++i ) {
1143 covered_positions.add( false );
1145 final int new_covered_positions_size = covered_positions.size();
1146 for( int i = domain.getFrom(); i <= domain.getTo(); ++i ) {
1147 if ( i < new_covered_positions_size ) {
1148 covered_positions.set( i, true );
1151 covered_positions.add( true );
1154 pruned_protein.addProteinDomain( domain );
1157 return pruned_protein;
1160 public static List<Domain> sortDomainsWithAscendingConfidenceValues( final Protein protein ) {
1161 final List<Domain> domains = new ArrayList<Domain>();
1162 for( final Domain d : protein.getProteinDomains() ) {
1165 Collections.sort( domains, SurfacingUtil.ASCENDING_CONFIDENCE_VALUE_ORDER );
1169 private static List<String> splitDomainCombination( final String dc ) {
1170 final String[] s = dc.split( "=" );
1171 if ( s.length != 2 ) {
1172 ForesterUtil.printErrorMessage( surfacing.PRG_NAME, "Stringyfied domain combination has illegal format: "
1176 final List<String> l = new ArrayList<String>( 2 );
1182 public static void writeAllDomainsChangedOnAllSubtrees( final Phylogeny p,
1183 final boolean get_gains,
1184 final String outdir,
1185 final String suffix_for_filename ) throws IOException {
1186 CharacterStateMatrix.GainLossStates state = CharacterStateMatrix.GainLossStates.GAIN;
1188 state = CharacterStateMatrix.GainLossStates.LOSS;
1190 final File base_dir = createBaseDirForPerNodeDomainFiles( surfacing.BASE_DIRECTORY_PER_SUBTREE_DOMAIN_GAIN_LOSS_FILES,
1194 for( final PhylogenyNodeIterator it = p.iteratorPostorder(); it.hasNext(); ) {
1195 final PhylogenyNode node = it.next();
1196 if ( !node.isExternal() ) {
1197 final SortedSet<String> domains = collectAllDomainsChangedOnSubtree( node, get_gains );
1198 if ( domains.size() > 0 ) {
1199 final Writer writer = ForesterUtil.createBufferedWriter( base_dir + ForesterUtil.FILE_SEPARATOR
1200 + node.getName() + suffix_for_filename );
1201 for( final String domain : domains ) {
1202 writer.write( domain );
1203 writer.write( ForesterUtil.LINE_SEPARATOR );
1211 private static void writeAllEncounteredPfamsToFile( final Map<DomainId, List<GoId>> domain_id_to_go_ids_map,
1212 final Map<GoId, GoTerm> go_id_to_term_map,
1213 final String outfile_name,
1214 final SortedSet<String> all_pfams_encountered ) {
1215 final File all_pfams_encountered_file = new File( outfile_name + surfacing.ALL_PFAMS_ENCOUNTERED_SUFFIX );
1216 final File all_pfams_encountered_with_go_annotation_file = new File( outfile_name
1217 + surfacing.ALL_PFAMS_ENCOUNTERED_WITH_GO_ANNOTATION_SUFFIX );
1218 final File encountered_pfams_summary_file = new File( outfile_name + surfacing.ENCOUNTERED_PFAMS_SUMMARY_SUFFIX );
1219 int biological_process_counter = 0;
1220 int cellular_component_counter = 0;
1221 int molecular_function_counter = 0;
1222 int pfams_with_mappings_counter = 0;
1223 int pfams_without_mappings_counter = 0;
1224 int pfams_without_mappings_to_bp_or_mf_counter = 0;
1225 int pfams_with_mappings_to_bp_or_mf_counter = 0;
1227 final Writer all_pfams_encountered_writer = new BufferedWriter( new FileWriter( all_pfams_encountered_file ) );
1228 final Writer all_pfams_encountered_with_go_annotation_writer = new BufferedWriter( new FileWriter( all_pfams_encountered_with_go_annotation_file ) );
1229 final Writer summary_writer = new BufferedWriter( new FileWriter( encountered_pfams_summary_file ) );
1230 summary_writer.write( "# Pfam to GO mapping summary" );
1231 summary_writer.write( ForesterUtil.LINE_SEPARATOR );
1232 summary_writer.write( "# Actual summary is at the end of this file." );
1233 summary_writer.write( ForesterUtil.LINE_SEPARATOR );
1234 summary_writer.write( "# Encountered Pfams without a GO mapping:" );
1235 summary_writer.write( ForesterUtil.LINE_SEPARATOR );
1236 for( final String pfam : all_pfams_encountered ) {
1237 all_pfams_encountered_writer.write( pfam );
1238 all_pfams_encountered_writer.write( ForesterUtil.LINE_SEPARATOR );
1239 final DomainId domain_id = new DomainId( pfam );
1240 if ( domain_id_to_go_ids_map.containsKey( domain_id ) ) {
1241 ++pfams_with_mappings_counter;
1242 all_pfams_encountered_with_go_annotation_writer.write( pfam );
1243 all_pfams_encountered_with_go_annotation_writer.write( ForesterUtil.LINE_SEPARATOR );
1244 final List<GoId> go_ids = domain_id_to_go_ids_map.get( domain_id );
1245 boolean maps_to_bp = false;
1246 boolean maps_to_cc = false;
1247 boolean maps_to_mf = false;
1248 for( final GoId go_id : go_ids ) {
1249 final GoTerm go_term = go_id_to_term_map.get( go_id );
1250 if ( go_term.getGoNameSpace().isBiologicalProcess() ) {
1253 else if ( go_term.getGoNameSpace().isCellularComponent() ) {
1256 else if ( go_term.getGoNameSpace().isMolecularFunction() ) {
1261 ++biological_process_counter;
1264 ++cellular_component_counter;
1267 ++molecular_function_counter;
1269 if ( maps_to_bp || maps_to_mf ) {
1270 ++pfams_with_mappings_to_bp_or_mf_counter;
1273 ++pfams_without_mappings_to_bp_or_mf_counter;
1277 ++pfams_without_mappings_to_bp_or_mf_counter;
1278 ++pfams_without_mappings_counter;
1279 summary_writer.write( pfam );
1280 summary_writer.write( ForesterUtil.LINE_SEPARATOR );
1283 all_pfams_encountered_writer.close();
1284 all_pfams_encountered_with_go_annotation_writer.close();
1285 ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote all [" + all_pfams_encountered.size()
1286 + "] encountered Pfams to: \"" + all_pfams_encountered_file + "\"" );
1287 ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote all [" + pfams_with_mappings_counter
1288 + "] encountered Pfams with GO mappings to: \"" + all_pfams_encountered_with_go_annotation_file
1290 ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote summary (including all ["
1291 + pfams_without_mappings_counter + "] encountered Pfams without GO mappings) to: \""
1292 + encountered_pfams_summary_file + "\"" );
1293 ForesterUtil.programMessage( surfacing.PRG_NAME, "Sum of Pfams encountered : "
1294 + all_pfams_encountered.size() );
1295 ForesterUtil.programMessage( surfacing.PRG_NAME, "Pfams without a mapping : "
1296 + pfams_without_mappings_counter + " ["
1297 + ( 100 * pfams_without_mappings_counter / all_pfams_encountered.size() ) + "%]" );
1298 ForesterUtil.programMessage( surfacing.PRG_NAME, "Pfams without mapping to proc. or func. : "
1299 + pfams_without_mappings_to_bp_or_mf_counter + " ["
1300 + ( 100 * pfams_without_mappings_to_bp_or_mf_counter / all_pfams_encountered.size() ) + "%]" );
1301 ForesterUtil.programMessage( surfacing.PRG_NAME,
1302 "Pfams with a mapping : " + pfams_with_mappings_counter
1304 + ( 100 * pfams_with_mappings_counter / all_pfams_encountered.size() )
1306 ForesterUtil.programMessage( surfacing.PRG_NAME, "Pfams with a mapping to proc. or func. : "
1307 + pfams_with_mappings_to_bp_or_mf_counter + " ["
1308 + ( 100 * pfams_with_mappings_to_bp_or_mf_counter / all_pfams_encountered.size() ) + "%]" );
1309 ForesterUtil.programMessage( surfacing.PRG_NAME,
1310 "Pfams with mapping to biological process: " + biological_process_counter
1312 + ( 100 * biological_process_counter / all_pfams_encountered.size() )
1314 ForesterUtil.programMessage( surfacing.PRG_NAME,
1315 "Pfams with mapping to molecular function: " + molecular_function_counter
1317 + ( 100 * molecular_function_counter / all_pfams_encountered.size() )
1319 ForesterUtil.programMessage( surfacing.PRG_NAME,
1320 "Pfams with mapping to cellular component: " + cellular_component_counter
1322 + ( 100 * cellular_component_counter / all_pfams_encountered.size() )
1324 summary_writer.write( ForesterUtil.LINE_SEPARATOR );
1325 summary_writer.write( "# Sum of Pfams encountered : " + all_pfams_encountered.size() );
1326 summary_writer.write( ForesterUtil.LINE_SEPARATOR );
1327 summary_writer.write( "# Pfams without a mapping : " + pfams_without_mappings_counter
1328 + " [" + ( 100 * pfams_without_mappings_counter / all_pfams_encountered.size() ) + "%]" );
1329 summary_writer.write( ForesterUtil.LINE_SEPARATOR );
1330 summary_writer.write( "# Pfams without mapping to proc. or func. : "
1331 + pfams_without_mappings_to_bp_or_mf_counter + " ["
1332 + ( 100 * pfams_without_mappings_to_bp_or_mf_counter / all_pfams_encountered.size() ) + "%]" );
1333 summary_writer.write( ForesterUtil.LINE_SEPARATOR );
1334 summary_writer.write( "# Pfams with a mapping : " + pfams_with_mappings_counter + " ["
1335 + ( 100 * pfams_with_mappings_counter / all_pfams_encountered.size() ) + "%]" );
1336 summary_writer.write( ForesterUtil.LINE_SEPARATOR );
1337 summary_writer.write( "# Pfams with a mapping to proc. or func. : "
1338 + pfams_with_mappings_to_bp_or_mf_counter + " ["
1339 + ( 100 * pfams_with_mappings_to_bp_or_mf_counter / all_pfams_encountered.size() ) + "%]" );
1340 summary_writer.write( ForesterUtil.LINE_SEPARATOR );
1341 summary_writer.write( "# Pfams with mapping to biological process: " + biological_process_counter + " ["
1342 + ( 100 * biological_process_counter / all_pfams_encountered.size() ) + "%]" );
1343 summary_writer.write( ForesterUtil.LINE_SEPARATOR );
1344 summary_writer.write( "# Pfams with mapping to molecular function: " + molecular_function_counter + " ["
1345 + ( 100 * molecular_function_counter / all_pfams_encountered.size() ) + "%]" );
1346 summary_writer.write( ForesterUtil.LINE_SEPARATOR );
1347 summary_writer.write( "# Pfams with mapping to cellular component: " + cellular_component_counter + " ["
1348 + ( 100 * cellular_component_counter / all_pfams_encountered.size() ) + "%]" );
1349 summary_writer.write( ForesterUtil.LINE_SEPARATOR );
1350 summary_writer.close();
1352 catch ( final IOException e ) {
1353 ForesterUtil.printWarningMessage( surfacing.PRG_NAME, "Failure to write: " + e );
1357 public static void writeBinaryDomainCombinationsFileForGraphAnalysis( final String[][] input_file_properties,
1358 final File output_dir,
1359 final GenomeWideCombinableDomains gwcd,
1361 final GenomeWideCombinableDomainsSortOrder dc_sort_order ) {
1362 File dc_outfile_dot = new File( input_file_properties[ i ][ 0 ]
1363 + surfacing.DOMAIN_COMBINITONS_OUTPUTFILE_SUFFIX_FOR_GRAPH_ANALYSIS );
1364 if ( output_dir != null ) {
1365 dc_outfile_dot = new File( output_dir + ForesterUtil.FILE_SEPARATOR + dc_outfile_dot );
1367 checkForOutputFileWriteability( dc_outfile_dot );
1368 final SortedSet<BinaryDomainCombination> binary_combinations = createSetOfAllBinaryDomainCombinationsPerGenome( gwcd );
1370 final BufferedWriter out_dot = new BufferedWriter( new FileWriter( dc_outfile_dot ) );
1371 for( final BinaryDomainCombination bdc : binary_combinations ) {
1372 out_dot.write( bdc.toGraphDescribingLanguage( BinaryDomainCombination.OutputFormat.DOT, null, null )
1374 out_dot.write( SurfacingConstants.NL );
1378 catch ( final IOException e ) {
1379 ForesterUtil.fatalError( surfacing.PRG_NAME, e.getMessage() );
1381 ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote binary domain combination for \""
1382 + input_file_properties[ i ][ 0 ] + "\" (" + input_file_properties[ i ][ 1 ] + ", "
1383 + input_file_properties[ i ][ 2 ] + ") to: \"" + dc_outfile_dot + "\"" );
1386 public static void writeBinaryStatesMatrixAsListToFile( final CharacterStateMatrix<CharacterStateMatrix.GainLossStates> matrix,
1387 final CharacterStateMatrix.GainLossStates state,
1388 final String filename,
1389 final String indentifier_characters_separator,
1390 final String character_separator,
1391 final Map<String, String> descriptions ) {
1392 final File outfile = new File( filename );
1393 checkForOutputFileWriteability( outfile );
1394 final SortedSet<String> sorted_ids = new TreeSet<String>();
1395 for( int i = 0; i < matrix.getNumberOfIdentifiers(); ++i ) {
1396 sorted_ids.add( matrix.getIdentifier( i ) );
1399 final BufferedWriter out = new BufferedWriter( new FileWriter( outfile ) );
1400 for( final String id : sorted_ids ) {
1401 out.write( indentifier_characters_separator );
1402 out.write( "#" + id );
1403 out.write( indentifier_characters_separator );
1404 for( int c = 0; c < matrix.getNumberOfCharacters(); ++c ) {
1406 // using null to indicate either UNCHANGED_PRESENT or GAIN.
1407 if ( ( matrix.getState( id, c ) == state )
1408 || ( ( state == null ) && ( ( matrix.getState( id, c ) == CharacterStateMatrix.GainLossStates.GAIN ) || ( matrix
1409 .getState( id, c ) == CharacterStateMatrix.GainLossStates.UNCHANGED_PRESENT ) ) ) ) {
1410 out.write( matrix.getCharacter( c ) );
1411 if ( ( descriptions != null ) && !descriptions.isEmpty()
1412 && descriptions.containsKey( matrix.getCharacter( c ) ) ) {
1414 out.write( descriptions.get( matrix.getCharacter( c ) ) );
1416 out.write( character_separator );
1423 catch ( final IOException e ) {
1424 ForesterUtil.fatalError( surfacing.PRG_NAME, e.getMessage() );
1426 ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote characters list: \"" + filename + "\"" );
1429 public static void writeBinaryStatesMatrixAsListToFileForBinaryCombinationsForGraphAnalysis( final CharacterStateMatrix<CharacterStateMatrix.GainLossStates> matrix,
1430 final CharacterStateMatrix.GainLossStates state,
1431 final String filename,
1432 final String indentifier_characters_separator,
1433 final String character_separator,
1434 final BinaryDomainCombination.OutputFormat bc_output_format ) {
1435 final File outfile = new File( filename );
1436 checkForOutputFileWriteability( outfile );
1437 final SortedSet<String> sorted_ids = new TreeSet<String>();
1438 for( int i = 0; i < matrix.getNumberOfIdentifiers(); ++i ) {
1439 sorted_ids.add( matrix.getIdentifier( i ) );
1442 final BufferedWriter out = new BufferedWriter( new FileWriter( outfile ) );
1443 for( final String id : sorted_ids ) {
1444 out.write( indentifier_characters_separator );
1445 out.write( "#" + id );
1446 out.write( indentifier_characters_separator );
1447 for( int c = 0; c < matrix.getNumberOfCharacters(); ++c ) {
1449 // using null to indicate either UNCHANGED_PRESENT or GAIN.
1450 if ( ( matrix.getState( id, c ) == state )
1451 || ( ( state == null ) && ( ( matrix.getState( id, c ) == CharacterStateMatrix.GainLossStates.GAIN ) || ( matrix
1452 .getState( id, c ) == CharacterStateMatrix.GainLossStates.UNCHANGED_PRESENT ) ) ) ) {
1453 BinaryDomainCombination bdc = null;
1455 bdc = BasicBinaryDomainCombination.createInstance( matrix.getCharacter( c ) );
1457 catch ( final Exception e ) {
1458 ForesterUtil.fatalError( surfacing.PRG_NAME, e.getLocalizedMessage() );
1460 out.write( bdc.toGraphDescribingLanguage( bc_output_format, null, null ).toString() );
1461 out.write( character_separator );
1468 catch ( final IOException e ) {
1469 ForesterUtil.fatalError( surfacing.PRG_NAME, e.getMessage() );
1471 ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote characters list: \"" + filename + "\"" );
1474 public static void writeBinaryStatesMatrixToList( final Map<DomainId, List<GoId>> domain_id_to_go_ids_map,
1475 final Map<GoId, GoTerm> go_id_to_term_map,
1476 final GoNameSpace go_namespace_limit,
1477 final boolean domain_combinations,
1478 final CharacterStateMatrix<CharacterStateMatrix.GainLossStates> matrix,
1479 final CharacterStateMatrix.GainLossStates state,
1480 final String filename,
1481 final String indentifier_characters_separator,
1482 final String character_separator,
1483 final String title_for_html,
1484 final String prefix_for_html,
1485 final Map<DomainId, Set<String>>[] domain_id_to_secondary_features_maps,
1486 final SortedSet<String> all_pfams_encountered,
1487 final SortedSet<String> pfams_gained_or_lost,
1488 final String suffix_for_per_node_events_file ) {
1489 if ( ( go_namespace_limit != null ) && ( ( go_id_to_term_map == null ) || ( go_id_to_term_map.size() < 1 ) ) ) {
1490 throw new IllegalArgumentException( "attempt to use GO namespace limit without a GO-id to term map" );
1492 else if ( ( ( domain_id_to_go_ids_map == null ) || ( domain_id_to_go_ids_map.size() < 1 ) ) ) {
1493 throw new IllegalArgumentException( "attempt to output detailed HTML without a Pfam to GO map" );
1495 else if ( ( ( go_id_to_term_map == null ) || ( go_id_to_term_map.size() < 1 ) ) ) {
1496 throw new IllegalArgumentException( "attempt to output detailed HTML without a GO-id to term map" );
1498 final File outfile = new File( filename );
1499 checkForOutputFileWriteability( outfile );
1500 final SortedSet<String> sorted_ids = new TreeSet<String>();
1501 for( int i = 0; i < matrix.getNumberOfIdentifiers(); ++i ) {
1502 sorted_ids.add( matrix.getIdentifier( i ) );
1505 final Writer out = new BufferedWriter( new FileWriter( outfile ) );
1506 final File per_node_go_mapped_domain_gain_loss_files_base_dir = createBaseDirForPerNodeDomainFiles( surfacing.BASE_DIRECTORY_PER_NODE_DOMAIN_GAIN_LOSS_FILES,
1507 domain_combinations,
1510 Writer per_node_go_mapped_domain_gain_loss_outfile_writer = null;
1511 File per_node_go_mapped_domain_gain_loss_outfile = null;
1512 int per_node_counter = 0;
1513 out.write( "<html>" );
1514 out.write( SurfacingConstants.NL );
1515 addHtmlHead( out, title_for_html );
1516 out.write( SurfacingConstants.NL );
1517 out.write( "<body>" );
1518 out.write( SurfacingConstants.NL );
1519 out.write( "<h1>" );
1520 out.write( SurfacingConstants.NL );
1521 out.write( title_for_html );
1522 out.write( SurfacingConstants.NL );
1523 out.write( "</h1>" );
1524 out.write( SurfacingConstants.NL );
1525 out.write( "<table>" );
1526 out.write( SurfacingConstants.NL );
1527 for( final String id : sorted_ids ) {
1528 final Matcher matcher = PATTERN_SP_STYLE_TAXONOMY.matcher( id );
1529 if ( matcher.matches() ) {
1532 out.write( "<tr>" );
1533 out.write( "<td>" );
1534 out.write( "<a href=\"#" + id + "\">" + id + "</a>" );
1535 out.write( "</td>" );
1536 out.write( "</tr>" );
1537 out.write( SurfacingConstants.NL );
1539 out.write( "</table>" );
1540 out.write( SurfacingConstants.NL );
1541 for( final String id : sorted_ids ) {
1542 final Matcher matcher = PATTERN_SP_STYLE_TAXONOMY.matcher( id );
1543 if ( matcher.matches() ) {
1546 out.write( SurfacingConstants.NL );
1547 out.write( "<h2>" );
1548 out.write( "<a name=\"" + id + "\">" + id + "</a>" );
1549 writeTaxonomyLinks( out, id );
1550 out.write( "</h2>" );
1551 out.write( SurfacingConstants.NL );
1552 out.write( "<table>" );
1553 out.write( SurfacingConstants.NL );
1554 out.write( "<tr>" );
1555 out.write( "<td><b>" );
1556 out.write( "Pfam domain(s)" );
1557 out.write( "</b></td><td><b>" );
1558 out.write( "GO term acc" );
1559 out.write( "</b></td><td><b>" );
1560 out.write( "GO term" );
1561 out.write( "</b></td><td><b>" );
1562 out.write( "GO namespace" );
1563 out.write( "</b></td>" );
1564 out.write( "</tr>" );
1565 out.write( SurfacingConstants.NL );
1566 out.write( "</tr>" );
1567 out.write( SurfacingConstants.NL );
1568 per_node_counter = 0;
1569 if ( matrix.getNumberOfCharacters() > 0 ) {
1570 per_node_go_mapped_domain_gain_loss_outfile = new File( per_node_go_mapped_domain_gain_loss_files_base_dir
1571 + ForesterUtil.FILE_SEPARATOR + id + suffix_for_per_node_events_file );
1572 SurfacingUtil.checkForOutputFileWriteability( per_node_go_mapped_domain_gain_loss_outfile );
1573 per_node_go_mapped_domain_gain_loss_outfile_writer = ForesterUtil
1574 .createBufferedWriter( per_node_go_mapped_domain_gain_loss_outfile );
1577 per_node_go_mapped_domain_gain_loss_outfile = null;
1578 per_node_go_mapped_domain_gain_loss_outfile_writer = null;
1580 for( int c = 0; c < matrix.getNumberOfCharacters(); ++c ) {
1582 // using null to indicate either UNCHANGED_PRESENT or GAIN.
1583 if ( ( matrix.getState( id, c ) == state )
1584 || ( ( state == null ) && ( ( matrix.getState( id, c ) == CharacterStateMatrix.GainLossStates.UNCHANGED_PRESENT ) || ( matrix
1585 .getState( id, c ) == CharacterStateMatrix.GainLossStates.GAIN ) ) ) ) {
1586 final String character = matrix.getCharacter( c );
1587 String domain_0 = "";
1588 String domain_1 = "";
1589 if ( character.indexOf( BinaryDomainCombination.SEPARATOR ) > 0 ) {
1590 final String[] s = character.split( BinaryDomainCombination.SEPARATOR );
1591 if ( s.length != 2 ) {
1592 throw new AssertionError( "this should not have happened: unexpected format for domain combination: ["
1593 + character + "]" );
1599 domain_0 = character;
1601 writeDomainData( domain_id_to_go_ids_map,
1608 character_separator,
1609 domain_id_to_secondary_features_maps,
1611 all_pfams_encountered.add( domain_0 );
1612 if ( pfams_gained_or_lost != null ) {
1613 pfams_gained_or_lost.add( domain_0 );
1615 if ( !ForesterUtil.isEmpty( domain_1 ) ) {
1616 all_pfams_encountered.add( domain_1 );
1617 if ( pfams_gained_or_lost != null ) {
1618 pfams_gained_or_lost.add( domain_1 );
1621 if ( per_node_go_mapped_domain_gain_loss_outfile_writer != null ) {
1622 writeDomainsToIndividualFilePerTreeNode( per_node_go_mapped_domain_gain_loss_outfile_writer,
1629 if ( per_node_go_mapped_domain_gain_loss_outfile_writer != null ) {
1630 per_node_go_mapped_domain_gain_loss_outfile_writer.close();
1631 if ( per_node_counter < 1 ) {
1632 per_node_go_mapped_domain_gain_loss_outfile.delete();
1634 per_node_counter = 0;
1636 out.write( "</table>" );
1637 out.write( SurfacingConstants.NL );
1638 out.write( "<hr>" );
1639 out.write( SurfacingConstants.NL );
1640 } // for( final String id : sorted_ids ) {
1641 out.write( "</body>" );
1642 out.write( SurfacingConstants.NL );
1643 out.write( "</html>" );
1644 out.write( SurfacingConstants.NL );
1648 catch ( final IOException e ) {
1649 ForesterUtil.fatalError( surfacing.PRG_NAME, e.getMessage() );
1651 ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote characters detailed HTML list: \"" + filename + "\"" );
1654 public static void writeBinaryStatesMatrixToListORIGIG( final Map<DomainId, List<GoId>> domain_id_to_go_ids_map,
1655 final Map<GoId, GoTerm> go_id_to_term_map,
1656 final GoNameSpace go_namespace_limit,
1657 final boolean domain_combinations,
1658 final CharacterStateMatrix<CharacterStateMatrix.GainLossStates> matrix,
1659 final CharacterStateMatrix.GainLossStates state,
1660 final String filename,
1661 final String indentifier_characters_separator,
1662 final String character_separator,
1663 final String title_for_html,
1664 final String prefix_for_html,
1665 final Map<DomainId, Set<String>>[] domain_id_to_secondary_features_maps,
1666 final SortedSet<String> all_pfams_encountered,
1667 final SortedSet<String> pfams_gained_or_lost,
1668 final String suffix_for_per_node_events_file ) {
1669 if ( ( go_namespace_limit != null ) && ( ( go_id_to_term_map == null ) || ( go_id_to_term_map.size() < 1 ) ) ) {
1670 throw new IllegalArgumentException( "attempt to use GO namespace limit without a GO-id to term map" );
1672 else if ( ( ( domain_id_to_go_ids_map == null ) || ( domain_id_to_go_ids_map.size() < 1 ) ) ) {
1673 throw new IllegalArgumentException( "attempt to output detailed HTML without a Pfam to GO map" );
1675 else if ( ( ( go_id_to_term_map == null ) || ( go_id_to_term_map.size() < 1 ) ) ) {
1676 throw new IllegalArgumentException( "attempt to output detailed HTML without a GO-id to term map" );
1678 final File outfile = new File( filename );
1679 checkForOutputFileWriteability( outfile );
1680 final SortedSet<String> sorted_ids = new TreeSet<String>();
1681 for( int i = 0; i < matrix.getNumberOfIdentifiers(); ++i ) {
1682 sorted_ids.add( matrix.getIdentifier( i ) );
1685 final Writer out = new BufferedWriter( new FileWriter( outfile ) );
1686 final File per_node_go_mapped_domain_gain_loss_files_base_dir = createBaseDirForPerNodeDomainFiles( surfacing.BASE_DIRECTORY_PER_NODE_DOMAIN_GAIN_LOSS_FILES,
1687 domain_combinations,
1690 Writer per_node_go_mapped_domain_gain_loss_outfile_writer = null;
1691 File per_node_go_mapped_domain_gain_loss_outfile = null;
1692 int per_node_counter = 0;
1693 out.write( "<html>" );
1694 out.write( SurfacingConstants.NL );
1695 addHtmlHead( out, title_for_html );
1696 out.write( SurfacingConstants.NL );
1697 out.write( "<body>" );
1698 out.write( SurfacingConstants.NL );
1699 out.write( "<h1>" );
1700 out.write( SurfacingConstants.NL );
1701 out.write( title_for_html );
1702 out.write( SurfacingConstants.NL );
1703 out.write( "</h1>" );
1704 out.write( SurfacingConstants.NL );
1705 out.write( "<table>" );
1706 out.write( SurfacingConstants.NL );
1707 for( final String id : sorted_ids ) {
1708 out.write( "<tr>" );
1709 out.write( "<td>" );
1710 out.write( "<a href=\"#" + id + "\">" + id + "</a>" );
1711 writeTaxonomyLinks( out, id );
1712 out.write( "</td>" );
1713 out.write( "</tr>" );
1714 out.write( SurfacingConstants.NL );
1716 out.write( "</table>" );
1717 out.write( SurfacingConstants.NL );
1718 for( final String id : sorted_ids ) {
1719 out.write( SurfacingConstants.NL );
1720 out.write( "<h2>" );
1721 out.write( "<a name=\"" + id + "\">" + id + "</a>" );
1722 writeTaxonomyLinks( out, id );
1723 out.write( "</h2>" );
1724 out.write( SurfacingConstants.NL );
1725 out.write( "<table>" );
1726 out.write( SurfacingConstants.NL );
1727 out.write( "<tr>" );
1728 out.write( "<td><b>" );
1729 out.write( "Pfam domain(s)" );
1730 out.write( "</b></td><td><b>" );
1731 out.write( "GO term acc" );
1732 out.write( "</b></td><td><b>" );
1733 out.write( "GO term" );
1734 out.write( "</b></td><td><b>" );
1735 out.write( "Penultimate GO term" );
1736 out.write( "</b></td><td><b>" );
1737 out.write( "GO namespace" );
1738 out.write( "</b></td>" );
1739 out.write( "</tr>" );
1740 out.write( SurfacingConstants.NL );
1741 out.write( "</tr>" );
1742 out.write( SurfacingConstants.NL );
1743 per_node_counter = 0;
1744 if ( matrix.getNumberOfCharacters() > 0 ) {
1745 per_node_go_mapped_domain_gain_loss_outfile = new File( per_node_go_mapped_domain_gain_loss_files_base_dir
1746 + ForesterUtil.FILE_SEPARATOR + id + suffix_for_per_node_events_file );
1747 SurfacingUtil.checkForOutputFileWriteability( per_node_go_mapped_domain_gain_loss_outfile );
1748 per_node_go_mapped_domain_gain_loss_outfile_writer = ForesterUtil
1749 .createBufferedWriter( per_node_go_mapped_domain_gain_loss_outfile );
1752 per_node_go_mapped_domain_gain_loss_outfile = null;
1753 per_node_go_mapped_domain_gain_loss_outfile_writer = null;
1755 for( int c = 0; c < matrix.getNumberOfCharacters(); ++c ) {
1757 // using null to indicate either UNCHANGED_PRESENT or GAIN.
1758 if ( ( matrix.getState( id, c ) == state )
1759 || ( ( state == null ) && ( ( matrix.getState( id, c ) == CharacterStateMatrix.GainLossStates.UNCHANGED_PRESENT ) || ( matrix
1760 .getState( id, c ) == CharacterStateMatrix.GainLossStates.GAIN ) ) ) ) {
1761 final String character = matrix.getCharacter( c );
1762 String domain_0 = "";
1763 String domain_1 = "";
1764 if ( character.indexOf( BinaryDomainCombination.SEPARATOR ) > 0 ) {
1765 final String[] s = character.split( BinaryDomainCombination.SEPARATOR );
1766 if ( s.length != 2 ) {
1767 throw new AssertionError( "this should not have happened: unexpected format for domain combination: ["
1768 + character + "]" );
1774 domain_0 = character;
1776 writeDomainData( domain_id_to_go_ids_map,
1783 character_separator,
1784 domain_id_to_secondary_features_maps,
1786 all_pfams_encountered.add( domain_0 );
1787 if ( pfams_gained_or_lost != null ) {
1788 pfams_gained_or_lost.add( domain_0 );
1790 if ( !ForesterUtil.isEmpty( domain_1 ) ) {
1791 all_pfams_encountered.add( domain_1 );
1792 if ( pfams_gained_or_lost != null ) {
1793 pfams_gained_or_lost.add( domain_1 );
1796 if ( per_node_go_mapped_domain_gain_loss_outfile_writer != null ) {
1797 writeDomainsToIndividualFilePerTreeNode( per_node_go_mapped_domain_gain_loss_outfile_writer,
1804 if ( per_node_go_mapped_domain_gain_loss_outfile_writer != null ) {
1805 per_node_go_mapped_domain_gain_loss_outfile_writer.close();
1806 if ( per_node_counter < 1 ) {
1807 per_node_go_mapped_domain_gain_loss_outfile.delete();
1809 per_node_counter = 0;
1811 out.write( "</table>" );
1812 out.write( SurfacingConstants.NL );
1813 out.write( "<hr>" );
1814 out.write( SurfacingConstants.NL );
1815 } // for( final String id : sorted_ids ) {
1816 out.write( "</body>" );
1817 out.write( SurfacingConstants.NL );
1818 out.write( "</html>" );
1819 out.write( SurfacingConstants.NL );
1823 catch ( final IOException e ) {
1824 ForesterUtil.fatalError( surfacing.PRG_NAME, e.getMessage() );
1826 ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote characters detailed HTML list: \"" + filename + "\"" );
1829 public static void writeDomainCombinationsCountsFile( final String[][] input_file_properties,
1830 final File output_dir,
1831 final Writer per_genome_domain_promiscuity_statistics_writer,
1832 final GenomeWideCombinableDomains gwcd,
1834 final GenomeWideCombinableDomains.GenomeWideCombinableDomainsSortOrder dc_sort_order ) {
1835 File dc_outfile = new File( input_file_properties[ i ][ 0 ]
1836 + surfacing.DOMAIN_COMBINITON_COUNTS_OUTPUTFILE_SUFFIX );
1837 if ( output_dir != null ) {
1838 dc_outfile = new File( output_dir + ForesterUtil.FILE_SEPARATOR + dc_outfile );
1840 checkForOutputFileWriteability( dc_outfile );
1842 final BufferedWriter out = new BufferedWriter( new FileWriter( dc_outfile ) );
1843 out.write( gwcd.toStringBuilder( dc_sort_order ).toString() );
1846 catch ( final IOException e ) {
1847 ForesterUtil.fatalError( surfacing.PRG_NAME, e.getMessage() );
1849 final DescriptiveStatistics stats = gwcd.getPerGenomeDomainPromiscuityStatistics();
1851 per_genome_domain_promiscuity_statistics_writer.write( input_file_properties[ i ][ 0 ] + "\t" );
1852 per_genome_domain_promiscuity_statistics_writer.write( FORMATTER_3.format( stats.arithmeticMean() ) + "\t" );
1853 if ( stats.getN() < 2 ) {
1854 per_genome_domain_promiscuity_statistics_writer.write( "n/a" + "\t" );
1857 per_genome_domain_promiscuity_statistics_writer.write( FORMATTER_3.format( stats
1858 .sampleStandardDeviation() ) + "\t" );
1860 per_genome_domain_promiscuity_statistics_writer.write( FORMATTER_3.format( stats.median() ) + "\t" );
1861 per_genome_domain_promiscuity_statistics_writer.write( ( int ) stats.getMin() + "\t" );
1862 per_genome_domain_promiscuity_statistics_writer.write( ( int ) stats.getMax() + "\t" );
1863 per_genome_domain_promiscuity_statistics_writer.write( stats.getN() + "\t" );
1864 final SortedSet<DomainId> mpds = gwcd.getMostPromiscuosDomain();
1865 for( final DomainId mpd : mpds ) {
1866 per_genome_domain_promiscuity_statistics_writer.write( mpd.getId() + " " );
1868 per_genome_domain_promiscuity_statistics_writer.write( ForesterUtil.LINE_SEPARATOR );
1870 catch ( final IOException e ) {
1871 ForesterUtil.fatalError( surfacing.PRG_NAME, e.getMessage() );
1873 if ( input_file_properties[ i ].length == 3 ) {
1874 ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote domain combination counts for \""
1875 + input_file_properties[ i ][ 0 ] + "\" (" + input_file_properties[ i ][ 1 ] + ", "
1876 + input_file_properties[ i ][ 2 ] + ") to: \"" + dc_outfile + "\"" );
1879 ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote domain combination counts for \""
1880 + input_file_properties[ i ][ 0 ] + "\" (" + input_file_properties[ i ][ 1 ] + ") to: \""
1881 + dc_outfile + "\"" );
1885 private static void writeDomainData( final Map<DomainId, List<GoId>> domain_id_to_go_ids_map,
1886 final Map<GoId, GoTerm> go_id_to_term_map,
1887 final GoNameSpace go_namespace_limit,
1889 final String domain_0,
1890 final String domain_1,
1891 final String prefix_for_html,
1892 final String character_separator_for_non_html_output,
1893 final Map<DomainId, Set<String>>[] domain_id_to_secondary_features_maps,
1894 final Set<GoId> all_go_ids ) throws IOException {
1895 boolean any_go_annotation_present = false;
1896 boolean first_has_no_go = false;
1897 int domain_count = 2; // To distinguish between domains and binary domain combinations.
1898 if ( ForesterUtil.isEmpty( domain_1 ) ) {
1901 // The following has a difficult to understand logic.
1902 for( int d = 0; d < domain_count; ++d ) {
1903 List<GoId> go_ids = null;
1904 boolean go_annotation_present = false;
1906 final DomainId domain_id = new DomainId( domain_0 );
1907 if ( domain_id_to_go_ids_map.containsKey( domain_id ) ) {
1908 go_annotation_present = true;
1909 any_go_annotation_present = true;
1910 go_ids = domain_id_to_go_ids_map.get( domain_id );
1913 first_has_no_go = true;
1917 final DomainId domain_id = new DomainId( domain_1 );
1918 if ( domain_id_to_go_ids_map.containsKey( domain_id ) ) {
1919 go_annotation_present = true;
1920 any_go_annotation_present = true;
1921 go_ids = domain_id_to_go_ids_map.get( domain_id );
1924 if ( go_annotation_present ) {
1925 boolean first = ( ( d == 0 ) || ( ( d == 1 ) && first_has_no_go ) );
1926 for( final GoId go_id : go_ids ) {
1927 out.write( "<tr>" );
1930 writeDomainIdsToHtml( out,
1934 domain_id_to_secondary_features_maps );
1937 out.write( "<td></td>" );
1939 if ( !go_id_to_term_map.containsKey( go_id ) ) {
1940 throw new IllegalArgumentException( "GO-id [" + go_id + "] not found in GO-id to GO-term map" );
1942 final GoTerm go_term = go_id_to_term_map.get( go_id );
1943 if ( ( go_namespace_limit == null ) || go_namespace_limit.equals( go_term.getGoNameSpace() ) ) {
1944 // final String top = GoUtils.getPenultimateGoTerm( go_term, go_id_to_term_map ).getName();
1945 final String go_id_str = go_id.getId();
1946 out.write( "<td>" );
1947 out.write( "<a href=\"" + SurfacingConstants.AMIGO_LINK + go_id_str
1948 + "\" target=\"amigo_window\">" + go_id_str + "</a>" );
1949 out.write( "</td><td>" );
1950 out.write( go_term.getName() );
1951 if ( domain_count == 2 ) {
1952 out.write( " (" + d + ")" );
1954 out.write( "</td><td>" );
1955 // out.write( top );
1956 // out.write( "</td><td>" );
1958 out.write( go_term.getGoNameSpace().toShortString() );
1960 out.write( "</td>" );
1961 if ( all_go_ids != null ) {
1962 all_go_ids.add( go_id );
1966 out.write( "<td>" );
1967 out.write( "</td><td>" );
1968 out.write( "</td><td>" );
1969 out.write( "</td><td>" );
1970 out.write( "</td>" );
1972 out.write( "</tr>" );
1973 out.write( SurfacingConstants.NL );
1976 } // for( int d = 0; d < domain_count; ++d )
1977 if ( !any_go_annotation_present ) {
1978 out.write( "<tr>" );
1979 writeDomainIdsToHtml( out, domain_0, domain_1, prefix_for_html, domain_id_to_secondary_features_maps );
1980 out.write( "<td>" );
1981 out.write( "</td><td>" );
1982 out.write( "</td><td>" );
1983 out.write( "</td><td>" );
1984 out.write( "</td>" );
1985 out.write( "</tr>" );
1986 out.write( SurfacingConstants.NL );
1990 private static void writeDomainIdsToHtml( final Writer out,
1991 final String domain_0,
1992 final String domain_1,
1993 final String prefix_for_detailed_html,
1994 final Map<DomainId, Set<String>>[] domain_id_to_secondary_features_maps )
1995 throws IOException {
1996 out.write( "<td>" );
1997 if ( !ForesterUtil.isEmpty( prefix_for_detailed_html ) ) {
1998 out.write( prefix_for_detailed_html );
2001 out.write( "<a href=\"" + SurfacingConstants.PFAM_FAMILY_ID_LINK + domain_0 + "\">" + domain_0 + "</a>" );
2002 out.write( "</td>" );
2005 public static DescriptiveStatistics writeDomainSimilaritiesToFile( final StringBuilder html_desc,
2006 final StringBuilder html_title,
2007 final Writer single_writer,
2008 Map<Character, Writer> split_writers,
2009 final SortedSet<DomainSimilarity> similarities,
2010 final boolean treat_as_binary,
2011 final List<Species> species_order,
2012 final PrintableDomainSimilarity.PRINT_OPTION print_option,
2013 final DomainSimilarity.DomainSimilaritySortField sort_field,
2014 final DomainSimilarity.DomainSimilarityScoring scoring,
2015 final boolean verbose ) throws IOException {
2016 final DescriptiveStatistics stats = new BasicDescriptiveStatistics();
2017 String histogram_title = null;
2018 switch ( sort_field ) {
2019 case ABS_MAX_COUNTS_DIFFERENCE:
2020 if ( treat_as_binary ) {
2021 histogram_title = "absolute counts difference:";
2024 histogram_title = "absolute (maximal) counts difference:";
2027 case MAX_COUNTS_DIFFERENCE:
2028 if ( treat_as_binary ) {
2029 histogram_title = "counts difference:";
2032 histogram_title = "(maximal) counts difference:";
2036 histogram_title = "score mean:";
2039 histogram_title = "score minimum:";
2042 histogram_title = "score maximum:";
2044 case MAX_DIFFERENCE:
2045 if ( treat_as_binary ) {
2046 histogram_title = "difference:";
2049 histogram_title = "(maximal) difference:";
2053 histogram_title = "score mean:";
2056 histogram_title = "score standard deviation:";
2059 histogram_title = "species number:";
2062 throw new AssertionError( "Unknown sort field: " + sort_field );
2064 for( final DomainSimilarity similarity : similarities ) {
2065 switch ( sort_field ) {
2066 case ABS_MAX_COUNTS_DIFFERENCE:
2067 stats.addValue( Math.abs( similarity.getMaximalDifferenceInCounts() ) );
2069 case MAX_COUNTS_DIFFERENCE:
2070 stats.addValue( similarity.getMaximalDifferenceInCounts() );
2073 stats.addValue( similarity.getMeanSimilarityScore() );
2076 stats.addValue( similarity.getMinimalSimilarityScore() );
2079 stats.addValue( similarity.getMaximalSimilarityScore() );
2081 case MAX_DIFFERENCE:
2082 stats.addValue( similarity.getMaximalDifference() );
2085 stats.addValue( similarity.getMeanSimilarityScore() );
2088 stats.addValue( similarity.getStandardDeviationOfSimilarityScore() );
2091 stats.addValue( similarity.getSpecies().size() );
2094 throw new AssertionError( "Unknown sort field: " + sort_field );
2098 // final HistogramData[] hists = new HistogramData[ 1 ];
2101 // List<HistogramDataItem> data_items = new
2102 // ArrayList<HistogramDataItem>();
2103 // double[] values = stats.getDataAsDoubleArray();
2104 // for( int i = 0; i < values.length; i++ ) {
2105 // HistogramDataItem data_item = new BasicHistogramDataItem( "", values[
2107 // data_items.add( data_item );
2111 // HistogramData hd0 = new HistogramData( "name",
2119 // hists[ 0 ] = hd0;
2121 // final HistogramsFrame hf = new HistogramsFrame( hists );
2122 // hf.setVisible( true );
2124 AsciiHistogram histo = null;
2125 if ( stats.getMin() < stats.getMin() ) {
2126 histo = new AsciiHistogram( stats, histogram_title );
2129 if ( histo != null ) {
2130 System.out.println( histo.toStringBuffer( 20, '|', 40, 5 ) );
2132 System.out.println();
2133 System.out.println( "N : " + stats.getN() );
2134 System.out.println( "Min : " + stats.getMin() );
2135 System.out.println( "Max : " + stats.getMax() );
2136 System.out.println( "Mean : " + stats.arithmeticMean() );
2137 if ( stats.getN() > 1 ) {
2138 System.out.println( "SD : " + stats.sampleStandardDeviation() );
2141 System.out.println( "SD : n/a" );
2143 System.out.println( "Median : " + stats.median() );
2144 if ( stats.getN() > 1 ) {
2145 System.out.println( "Pearsonian skewness : " + stats.pearsonianSkewness() );
2148 System.out.println( "Pearsonian skewness : n/a" );
2151 if ( ( single_writer != null ) && ( ( split_writers == null ) || split_writers.isEmpty() ) ) {
2152 split_writers = new HashMap<Character, Writer>();
2153 split_writers.put( '_', single_writer );
2155 switch ( print_option ) {
2156 case SIMPLE_TAB_DELIMITED:
2159 for( final Character key : split_writers.keySet() ) {
2160 final Writer w = split_writers.get( key );
2161 w.write( "<html>" );
2162 w.write( SurfacingConstants.NL );
2164 addHtmlHead( w, "DCs (" + html_title + ") " + key.toString().toUpperCase() );
2167 addHtmlHead( w, "DCs (" + html_title + ")" );
2169 w.write( SurfacingConstants.NL );
2170 w.write( "<body>" );
2171 w.write( SurfacingConstants.NL );
2172 w.write( html_desc.toString() );
2173 w.write( SurfacingConstants.NL );
2176 w.write( SurfacingConstants.NL );
2177 w.write( "<tt><pre>" );
2178 w.write( SurfacingConstants.NL );
2179 if ( histo != null ) {
2180 w.write( histo.toStringBuffer( 20, '|', 40, 5 ).toString() );
2181 w.write( SurfacingConstants.NL );
2183 w.write( "</pre></tt>" );
2184 w.write( SurfacingConstants.NL );
2185 w.write( "<table>" );
2186 w.write( SurfacingConstants.NL );
2187 w.write( "<tr><td>N: </td><td>" + stats.getN() + "</td></tr>" );
2188 w.write( SurfacingConstants.NL );
2189 w.write( "<tr><td>Min: </td><td>" + stats.getMin() + "</td></tr>" );
2190 w.write( SurfacingConstants.NL );
2191 w.write( "<tr><td>Max: </td><td>" + stats.getMax() + "</td></tr>" );
2192 w.write( SurfacingConstants.NL );
2193 w.write( "<tr><td>Mean: </td><td>" + stats.arithmeticMean() + "</td></tr>" );
2194 w.write( SurfacingConstants.NL );
2195 if ( stats.getN() > 1 ) {
2196 w.write( "<tr><td>SD: </td><td>" + stats.sampleStandardDeviation() + "</td></tr>" );
2199 w.write( "<tr><td>SD: </td><td>n/a</td></tr>" );
2201 w.write( SurfacingConstants.NL );
2202 w.write( "<tr><td>Median: </td><td>" + stats.median() + "</td></tr>" );
2203 w.write( SurfacingConstants.NL );
2204 if ( stats.getN() > 1 ) {
2205 w.write( "<tr><td>Pearsonian skewness: </td><td>" + stats.pearsonianSkewness() + "</td></tr>" );
2208 w.write( "<tr><td>Pearsonian skewness: </td><td>n/a</td></tr>" );
2210 w.write( SurfacingConstants.NL );
2211 w.write( "</table>" );
2212 w.write( SurfacingConstants.NL );
2214 w.write( SurfacingConstants.NL );
2216 w.write( SurfacingConstants.NL );
2218 w.write( SurfacingConstants.NL );
2219 w.write( "<table>" );
2220 w.write( SurfacingConstants.NL );
2224 for( final Writer w : split_writers.values() ) {
2225 w.write( SurfacingConstants.NL );
2227 for( final DomainSimilarity similarity : similarities ) {
2228 if ( ( species_order != null ) && !species_order.isEmpty() ) {
2229 ( ( PrintableDomainSimilarity ) similarity ).setSpeciesOrder( species_order );
2231 if ( single_writer != null ) {
2232 single_writer.write( similarity.toStringBuffer( print_option ).toString() );
2235 Writer local_writer = split_writers.get( ( similarity.getDomainId().getId().charAt( 0 ) + "" )
2236 .toLowerCase().charAt( 0 ) );
2237 if ( local_writer == null ) {
2238 local_writer = split_writers.get( '0' );
2240 local_writer.write( similarity.toStringBuffer( print_option ).toString() );
2242 for( final Writer w : split_writers.values() ) {
2243 w.write( SurfacingConstants.NL );
2246 switch ( print_option ) {
2248 for( final Writer w : split_writers.values() ) {
2249 w.write( SurfacingConstants.NL );
2250 w.write( "</table>" );
2251 w.write( SurfacingConstants.NL );
2252 w.write( "</font>" );
2253 w.write( SurfacingConstants.NL );
2254 w.write( "</body>" );
2255 w.write( SurfacingConstants.NL );
2256 w.write( "</html>" );
2257 w.write( SurfacingConstants.NL );
2261 for( final Writer w : split_writers.values() ) {
2267 private static void writeDomainsToIndividualFilePerTreeNode( final Writer individual_files_writer,
2268 final String domain_0,
2269 final String domain_1 ) throws IOException {
2270 individual_files_writer.write( domain_0 );
2271 individual_files_writer.write( ForesterUtil.LINE_SEPARATOR );
2272 if ( !ForesterUtil.isEmpty( domain_1 ) ) {
2273 individual_files_writer.write( domain_1 );
2274 individual_files_writer.write( ForesterUtil.LINE_SEPARATOR );
2278 public static void writeMatrixToFile( final CharacterStateMatrix<?> matrix,
2279 final String filename,
2280 final Format format ) {
2281 final File outfile = new File( filename );
2282 checkForOutputFileWriteability( outfile );
2284 final BufferedWriter out = new BufferedWriter( new FileWriter( outfile ) );
2285 matrix.toWriter( out, format );
2289 catch ( final IOException e ) {
2290 ForesterUtil.fatalError( surfacing.PRG_NAME, e.getMessage() );
2292 ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote matrix: \"" + filename + "\"" );
2295 public static void writeMatrixToFile( final File matrix_outfile, final List<DistanceMatrix> matrices ) {
2296 checkForOutputFileWriteability( matrix_outfile );
2298 final BufferedWriter out = new BufferedWriter( new FileWriter( matrix_outfile ) );
2299 for( final DistanceMatrix distance_matrix : matrices ) {
2300 out.write( distance_matrix.toStringBuffer( DistanceMatrix.Format.PHYLIP ).toString() );
2301 out.write( ForesterUtil.LINE_SEPARATOR );
2306 catch ( final IOException e ) {
2307 ForesterUtil.fatalError( surfacing.PRG_NAME, e.getMessage() );
2309 ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote distance matrices to \"" + matrix_outfile + "\"" );
2312 private static void writePfamsToFile( final String outfile_name, final SortedSet<String> pfams ) {
2314 final Writer writer = new BufferedWriter( new FileWriter( new File( outfile_name ) ) );
2315 for( final String pfam : pfams ) {
2316 writer.write( pfam );
2317 writer.write( ForesterUtil.LINE_SEPARATOR );
2320 ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote " + pfams.size() + " pfams to [" + outfile_name
2323 catch ( final IOException e ) {
2324 ForesterUtil.printWarningMessage( surfacing.PRG_NAME, "Failure to write: " + e );
2328 public static void writePhylogenyToFile( final Phylogeny phylogeny, final String filename ) {
2329 final PhylogenyWriter writer = new PhylogenyWriter();
2331 writer.toPhyloXML( new File( filename ), phylogeny, 1 );
2333 catch ( final IOException e ) {
2334 ForesterUtil.printWarningMessage( surfacing.PRG_NAME, "failed to write phylogeny to \"" + filename + "\": "
2337 ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote phylogeny to \"" + filename + "\"" );
2340 public static void writeTaxonomyLinks( final Writer writer, final String species ) throws IOException {
2341 if ( ( species.length() > 1 ) && ( species.indexOf( '_' ) < 1 ) ) {
2342 final Matcher matcher = PATTERN_SP_STYLE_TAXONOMY.matcher( species );
2343 writer.write( " [" );
2344 if ( matcher.matches() ) {
2345 writer.write( "<a href=\"" + SurfacingConstants.UNIPROT_LINK + species
2346 + "\" target=\"taxonomy_window\">uniprot</a>" );
2349 writer.write( "<a href=\"" + SurfacingConstants.EOL_LINK + species
2350 + "\" target=\"taxonomy_window\">eol</a>" );
2351 writer.write( "|" );
2352 writer.write( "<a href=\"" + SurfacingConstants.TOL_LINK + species
2353 + "\" target=\"taxonomy_window\">tol</a>" );
2355 writer.write( "]" );
2359 private static void writeToNexus( final String outfile_name,
2360 final CharacterStateMatrix<BinaryStates> matrix,
2361 final Phylogeny phylogeny ) {
2362 if ( !( matrix instanceof BasicCharacterStateMatrix ) ) {
2363 throw new IllegalArgumentException( "can only write matrices of type [" + BasicCharacterStateMatrix.class
2366 final BasicCharacterStateMatrix<BinaryStates> my_matrix = ( org.forester.evoinference.matrix.character.BasicCharacterStateMatrix<BinaryStates> ) matrix;
2367 final List<Phylogeny> phylogenies = new ArrayList<Phylogeny>( 1 );
2368 phylogenies.add( phylogeny );
2370 final BufferedWriter w = new BufferedWriter( new FileWriter( outfile_name ) );
2371 w.write( NexusConstants.NEXUS );
2372 w.write( ForesterUtil.LINE_SEPARATOR );
2373 my_matrix.writeNexusTaxaBlock( w );
2374 my_matrix.writeNexusBinaryChractersBlock( w );
2375 PhylogenyWriter.writeNexusTreesBlock( w, phylogenies, NH_CONVERSION_SUPPORT_VALUE_STYLE.NONE );
2378 ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote Nexus file: \"" + outfile_name + "\"" );
2380 catch ( final IOException e ) {
2381 ForesterUtil.fatalError( surfacing.PRG_NAME, e.getMessage() );
2385 private static void writeToNexus( final String outfile_name,
2386 final DomainParsimonyCalculator domain_parsimony,
2387 final Phylogeny phylogeny ) {
2388 writeToNexus( outfile_name + surfacing.NEXUS_EXTERNAL_DOMAINS,
2389 domain_parsimony.createMatrixOfDomainPresenceOrAbsence(),
2391 writeToNexus( outfile_name + surfacing.NEXUS_EXTERNAL_DOMAIN_COMBINATIONS,
2392 domain_parsimony.createMatrixOfBinaryDomainCombinationPresenceOrAbsence(),
2396 public static void domainsPerProteinsStatistics( final String genome,
2397 final List<Protein> protein_list,
2398 final DescriptiveStatistics all_genomes_domains_per_potein_stats,
2399 final SortedMap<Integer, Integer> all_genomes_domains_per_potein_histo,
2400 final SortedSet<String> domains_which_are_always_single,
2401 final SortedSet<String> domains_which_are_sometimes_single_sometimes_not,
2402 final SortedSet<String> domains_which_never_single,
2403 final Writer writer ) {
2404 final DescriptiveStatistics stats = new BasicDescriptiveStatistics();
2405 for( final Protein protein : protein_list ) {
2406 final int domains = protein.getNumberOfProteinDomains();
2407 //System.out.println( domains );
2408 stats.addValue( domains );
2409 all_genomes_domains_per_potein_stats.addValue( domains );
2410 if ( !all_genomes_domains_per_potein_histo.containsKey( domains ) ) {
2411 all_genomes_domains_per_potein_histo.put( domains, 1 );
2414 all_genomes_domains_per_potein_histo.put( domains,
2415 1 + all_genomes_domains_per_potein_histo.get( domains ) );
2417 if ( domains == 1 ) {
2418 final String domain = protein.getProteinDomain( 0 ).getDomainId().getId();
2419 if ( !domains_which_are_sometimes_single_sometimes_not.contains( domain ) ) {
2420 if ( domains_which_never_single.contains( domain ) ) {
2421 domains_which_never_single.remove( domain );
2422 domains_which_are_sometimes_single_sometimes_not.add( domain );
2425 domains_which_are_always_single.add( domain );
2429 else if ( domains > 1 ) {
2430 for( final Domain d : protein.getProteinDomains() ) {
2431 final String domain = d.getDomainId().getId();
2432 // System.out.println( domain );
2433 if ( !domains_which_are_sometimes_single_sometimes_not.contains( domain ) ) {
2434 if ( domains_which_are_always_single.contains( domain ) ) {
2435 domains_which_are_always_single.remove( domain );
2436 domains_which_are_sometimes_single_sometimes_not.add( domain );
2439 domains_which_never_single.add( domain );
2446 writer.write( genome );
2447 writer.write( "\t" );
2448 if ( stats.getN() >= 1 ) {
2449 writer.write( stats.arithmeticMean() + "" );
2450 writer.write( "\t" );
2451 if ( stats.getN() >= 2 ) {
2452 writer.write( stats.sampleStandardDeviation() + "" );
2457 writer.write( "\t" );
2458 writer.write( stats.median() + "" );
2459 writer.write( "\t" );
2460 writer.write( stats.getN() + "" );
2461 writer.write( "\t" );
2462 writer.write( stats.getMin() + "" );
2463 writer.write( "\t" );
2464 writer.write( stats.getMax() + "" );
2467 writer.write( "\t" );
2468 writer.write( "\t" );
2469 writer.write( "\t" );
2470 writer.write( "0" );
2471 writer.write( "\t" );
2472 writer.write( "\t" );
2474 writer.write( "\n" );
2476 catch ( final IOException e ) {
2477 e.printStackTrace();