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.Map.Entry;
45 import java.util.PriorityQueue;
47 import java.util.SortedMap;
48 import java.util.SortedSet;
49 import java.util.TreeMap;
50 import java.util.TreeSet;
51 import java.util.regex.Matcher;
52 import java.util.regex.Pattern;
54 import org.forester.application.surfacing;
55 import org.forester.evoinference.distance.NeighborJoining;
56 import org.forester.evoinference.matrix.character.BasicCharacterStateMatrix;
57 import org.forester.evoinference.matrix.character.CharacterStateMatrix;
58 import org.forester.evoinference.matrix.character.CharacterStateMatrix.BinaryStates;
59 import org.forester.evoinference.matrix.character.CharacterStateMatrix.Format;
60 import org.forester.evoinference.matrix.character.CharacterStateMatrix.GainLossStates;
61 import org.forester.evoinference.matrix.distance.DistanceMatrix;
62 import org.forester.go.GoId;
63 import org.forester.go.GoNameSpace;
64 import org.forester.go.GoTerm;
65 import org.forester.go.PfamToGoMapping;
66 import org.forester.io.parsers.nexus.NexusConstants;
67 import org.forester.io.writers.PhylogenyWriter;
68 import org.forester.phylogeny.Phylogeny;
69 import org.forester.phylogeny.PhylogenyMethods;
70 import org.forester.phylogeny.PhylogenyNode;
71 import org.forester.phylogeny.PhylogenyNodeI.NH_CONVERSION_SUPPORT_VALUE_STYLE;
72 import org.forester.phylogeny.data.BinaryCharacters;
73 import org.forester.phylogeny.data.Confidence;
74 import org.forester.phylogeny.iterators.PhylogenyNodeIterator;
75 import org.forester.protein.BasicProtein;
76 import org.forester.protein.BinaryDomainCombination;
77 import org.forester.protein.Domain;
78 import org.forester.protein.DomainId;
79 import org.forester.protein.Protein;
80 import org.forester.species.Species;
81 import org.forester.surfacing.DomainSimilarityCalculator.Detailedness;
82 import org.forester.surfacing.DomainSimilarityCalculator.GoAnnotationOutput;
83 import org.forester.surfacing.GenomeWideCombinableDomains.GenomeWideCombinableDomainsSortOrder;
84 import org.forester.util.AsciiHistogram;
85 import org.forester.util.BasicDescriptiveStatistics;
86 import org.forester.util.BasicTable;
87 import org.forester.util.BasicTableParser;
88 import org.forester.util.DescriptiveStatistics;
89 import org.forester.util.ForesterUtil;
91 public final class SurfacingUtil {
93 private final static NumberFormat FORMATTER = new DecimalFormat( "0.0E0" );
94 private final static NumberFormat FORMATTER_3 = new DecimalFormat( "0.000" );
95 private static final Comparator<Domain> ASCENDING_CONFIDENCE_VALUE_ORDER = new Comparator<Domain>() {
98 public int compare( final Domain d1,
100 if ( d1.getPerSequenceEvalue() < d2
101 .getPerSequenceEvalue() ) {
105 .getPerSequenceEvalue() > d2
106 .getPerSequenceEvalue() ) {
110 return d1.compareTo( d2 );
114 public final static Pattern PATTERN_SP_STYLE_TAXONOMY = Pattern.compile( "^[A-Z0-9]{3,5}$" );
115 private static final boolean USE_LAST = true;
117 private SurfacingUtil() {
118 // Hidden constructor.
121 public static void addAllBinaryDomainCombinationToSet( final GenomeWideCombinableDomains genome,
122 final SortedSet<BinaryDomainCombination> binary_domain_combinations ) {
123 final SortedMap<DomainId, CombinableDomains> all_cd = genome.getAllCombinableDomainsIds();
124 for( final DomainId domain_id : all_cd.keySet() ) {
125 binary_domain_combinations.addAll( all_cd.get( domain_id ).toBinaryDomainCombinations() );
129 public static void addAllDomainIdsToSet( final GenomeWideCombinableDomains genome,
130 final SortedSet<DomainId> domain_ids ) {
131 final SortedSet<DomainId> domains = genome.getAllDomainIds();
132 for( final DomainId domain : domains ) {
133 domain_ids.add( domain );
137 public static void addHtmlHead( final Writer w, final String title ) throws IOException {
138 w.write( SurfacingConstants.NL );
140 w.write( "<title>" );
142 w.write( "</title>" );
143 w.write( SurfacingConstants.NL );
144 w.write( "<style>" );
145 w.write( SurfacingConstants.NL );
146 w.write( "a:visited { color : #6633FF; text-decoration : none; }" );
147 w.write( SurfacingConstants.NL );
148 w.write( "a:link { color : #6633FF; text-decoration : none; }" );
149 w.write( SurfacingConstants.NL );
150 w.write( "a:active { color : #99FF00; text-decoration : none; }" );
151 w.write( SurfacingConstants.NL );
152 w.write( "a:hover { color : #FFFFFF; background-color : #99FF00; text-decoration : none; }" );
153 w.write( SurfacingConstants.NL );
154 w.write( "td { text-align: left; vertical-align: top; font-family: Verdana, Arial, Helvetica; font-size: 8pt}" );
155 w.write( SurfacingConstants.NL );
156 w.write( "h1 { color : #0000FF; font-family: Verdana, Arial, Helvetica; font-size: 18pt; font-weight: bold }" );
157 w.write( SurfacingConstants.NL );
158 w.write( "h2 { color : #0000FF; font-family: Verdana, Arial, Helvetica; font-size: 16pt; font-weight: bold }" );
159 w.write( SurfacingConstants.NL );
160 w.write( "</style>" );
161 w.write( SurfacingConstants.NL );
162 w.write( "</head>" );
163 w.write( SurfacingConstants.NL );
166 public static DescriptiveStatistics calculateDescriptiveStatisticsForMeanValues( final Set<DomainSimilarity> similarities ) {
167 final DescriptiveStatistics stats = new BasicDescriptiveStatistics();
168 for( final DomainSimilarity similarity : similarities ) {
169 stats.addValue( similarity.getMeanSimilarityScore() );
174 private static void calculateIndependentDomainCombinationGains( final Phylogeny local_phylogeny_l,
175 final String outfilename_for_counts,
176 final String outfilename_for_dc,
177 final String outfilename_for_dc_for_go_mapping,
178 final String outfilename_for_dc_for_go_mapping_unique,
179 final String outfilename_for_rank_counts,
180 final String outfilename_for_ancestor_species_counts,
181 final String outfilename_for_protein_stats,
182 final Map<String, DescriptiveStatistics> protein_length_stats_by_dc,
183 final Map<String, DescriptiveStatistics> domain_number_stats_by_dc ) {
186 // if ( protein_length_stats_by_dc != null ) {
187 // for( final Entry<?, DescriptiveStatistics> entry : protein_length_stats_by_dc.entrySet() ) {
188 // System.out.print( entry.getKey().toString() );
189 // System.out.print( ": " );
190 // double[] a = entry.getValue().getDataAsDoubleArray();
191 // for( int i = 0; i < a.length; i++ ) {
192 // System.out.print( a[ i ] + " " );
194 // System.out.println();
197 // if ( domain_number_stats_by_dc != null ) {
198 // for( final Entry<?, DescriptiveStatistics> entry : domain_number_stats_by_dc.entrySet() ) {
199 // System.out.print( entry.getKey().toString() );
200 // System.out.print( ": " );
201 // double[] a = entry.getValue().getDataAsDoubleArray();
202 // for( int i = 0; i < a.length; i++ ) {
203 // System.out.print( a[ i ] + " " );
205 // System.out.println();
209 final BufferedWriter out_counts = new BufferedWriter( new FileWriter( outfilename_for_counts ) );
210 final BufferedWriter out_dc = new BufferedWriter( new FileWriter( outfilename_for_dc ) );
211 final BufferedWriter out_dc_for_go_mapping = new BufferedWriter( new FileWriter( outfilename_for_dc_for_go_mapping ) );
212 final BufferedWriter out_dc_for_go_mapping_unique = new BufferedWriter( new FileWriter( outfilename_for_dc_for_go_mapping_unique ) );
213 final SortedMap<String, Integer> dc_gain_counts = new TreeMap<String, Integer>();
214 for( final PhylogenyNodeIterator it = local_phylogeny_l.iteratorPostorder(); it.hasNext(); ) {
215 final PhylogenyNode n = it.next();
216 final Set<String> gained_dc = n.getNodeData().getBinaryCharacters().getGainedCharacters();
217 for( final String dc : gained_dc ) {
218 if ( dc_gain_counts.containsKey( dc ) ) {
219 dc_gain_counts.put( dc, dc_gain_counts.get( dc ) + 1 );
222 dc_gain_counts.put( dc, 1 );
226 final SortedMap<Integer, Integer> histogram = new TreeMap<Integer, Integer>();
227 final SortedMap<Integer, StringBuilder> domain_lists = new TreeMap<Integer, StringBuilder>();
228 final SortedMap<Integer, DescriptiveStatistics> dc_reapp_counts_to_protein_length_stats = new TreeMap<Integer, DescriptiveStatistics>();
229 final SortedMap<Integer, DescriptiveStatistics> dc_reapp_counts_to_domain_number_stats = new TreeMap<Integer, DescriptiveStatistics>();
230 final SortedMap<Integer, PriorityQueue<String>> domain_lists_go = new TreeMap<Integer, PriorityQueue<String>>();
231 final SortedMap<Integer, SortedSet<String>> domain_lists_go_unique = new TreeMap<Integer, SortedSet<String>>();
232 final Set<String> dcs = dc_gain_counts.keySet();
233 final SortedSet<String> more_than_once = new TreeSet<String>();
234 final DescriptiveStatistics gained_once_lengths_stats = new BasicDescriptiveStatistics();
235 final DescriptiveStatistics gained_once_domain_count_stats = new BasicDescriptiveStatistics();
236 final DescriptiveStatistics gained_multiple_times_lengths_stats = new BasicDescriptiveStatistics();
237 final DescriptiveStatistics gained_multiple_times_domain_count_stats = new BasicDescriptiveStatistics();
238 for( final String dc : dcs ) {
239 final int count = dc_gain_counts.get( dc );
240 if ( histogram.containsKey( count ) ) {
241 histogram.put( count, histogram.get( count ) + 1 );
242 domain_lists.get( count ).append( ", " + dc );
243 domain_lists_go.get( count ).addAll( splitDomainCombination( dc ) );
244 domain_lists_go_unique.get( count ).addAll( splitDomainCombination( dc ) );
247 histogram.put( count, 1 );
248 domain_lists.put( count, new StringBuilder( dc ) );
249 final PriorityQueue<String> q = new PriorityQueue<String>();
250 q.addAll( splitDomainCombination( dc ) );
251 domain_lists_go.put( count, q );
252 final SortedSet<String> set = new TreeSet<String>();
253 set.addAll( splitDomainCombination( dc ) );
254 domain_lists_go_unique.put( count, set );
256 if ( protein_length_stats_by_dc != null ) {
257 if ( !dc_reapp_counts_to_protein_length_stats.containsKey( count ) ) {
258 dc_reapp_counts_to_protein_length_stats.put( count, new BasicDescriptiveStatistics() );
260 dc_reapp_counts_to_protein_length_stats.get( count ).addValue( protein_length_stats_by_dc.get( dc )
263 if ( domain_number_stats_by_dc != null ) {
264 if ( !dc_reapp_counts_to_domain_number_stats.containsKey( count ) ) {
265 dc_reapp_counts_to_domain_number_stats.put( count, new BasicDescriptiveStatistics() );
267 dc_reapp_counts_to_domain_number_stats.get( count ).addValue( domain_number_stats_by_dc.get( dc )
271 more_than_once.add( dc );
272 if ( protein_length_stats_by_dc != null ) {
273 final DescriptiveStatistics s = protein_length_stats_by_dc.get( dc );
274 final double[] a = s.getDataAsDoubleArray();
275 for( final double element : a ) {
276 gained_multiple_times_lengths_stats.addValue( element );
279 if ( domain_number_stats_by_dc != null ) {
280 final DescriptiveStatistics s = domain_number_stats_by_dc.get( dc );
281 final double[] a = s.getDataAsDoubleArray();
282 for( final double element : a ) {
283 gained_multiple_times_domain_count_stats.addValue( element );
288 if ( protein_length_stats_by_dc != null ) {
289 final DescriptiveStatistics s = protein_length_stats_by_dc.get( dc );
290 final double[] a = s.getDataAsDoubleArray();
291 for( final double element : a ) {
292 gained_once_lengths_stats.addValue( element );
295 if ( domain_number_stats_by_dc != null ) {
296 final DescriptiveStatistics s = domain_number_stats_by_dc.get( dc );
297 final double[] a = s.getDataAsDoubleArray();
298 for( final double element : a ) {
299 gained_once_domain_count_stats.addValue( element );
304 final Set<Integer> histogram_keys = histogram.keySet();
305 for( final Integer histogram_key : histogram_keys ) {
306 final int count = histogram.get( histogram_key );
307 final StringBuilder dc = domain_lists.get( histogram_key );
308 out_counts.write( histogram_key + "\t" + count + ForesterUtil.LINE_SEPARATOR );
309 out_dc.write( histogram_key + "\t" + dc + ForesterUtil.LINE_SEPARATOR );
310 out_dc_for_go_mapping.write( "#" + histogram_key + ForesterUtil.LINE_SEPARATOR );
311 final Object[] sorted = domain_lists_go.get( histogram_key ).toArray();
312 Arrays.sort( sorted );
313 for( final Object domain : sorted ) {
314 out_dc_for_go_mapping.write( domain + ForesterUtil.LINE_SEPARATOR );
316 out_dc_for_go_mapping_unique.write( "#" + histogram_key + ForesterUtil.LINE_SEPARATOR );
317 for( final String domain : domain_lists_go_unique.get( histogram_key ) ) {
318 out_dc_for_go_mapping_unique.write( domain + ForesterUtil.LINE_SEPARATOR );
323 out_dc_for_go_mapping.close();
324 out_dc_for_go_mapping_unique.close();
326 final SortedMap<String, Integer> lca_rank_counts = new TreeMap<String, Integer>();
327 final SortedMap<String, Integer> lca_ancestor_species_counts = new TreeMap<String, Integer>();
328 for( final String dc : more_than_once ) {
329 final List<PhylogenyNode> nodes = new ArrayList<PhylogenyNode>();
330 for( final PhylogenyNodeIterator it = local_phylogeny_l.iteratorExternalForward(); it.hasNext(); ) {
331 final PhylogenyNode n = it.next();
332 if ( n.getNodeData().getBinaryCharacters().getGainedCharacters().contains( dc ) ) {
336 for( int i = 0; i < nodes.size() - 1; ++i ) {
337 for( int j = i + 1; j < nodes.size(); ++j ) {
338 final PhylogenyNode lca = PhylogenyMethods.getInstance().obtainLCA( nodes.get( i ),
340 String rank = "unknown";
341 if ( lca.getNodeData().isHasTaxonomy()
342 && !ForesterUtil.isEmpty( lca.getNodeData().getTaxonomy().getRank() ) ) {
343 rank = lca.getNodeData().getTaxonomy().getRank();
345 addToCountMap( lca_rank_counts, rank );
347 if ( lca.getNodeData().isHasTaxonomy()
348 && !ForesterUtil.isEmpty( lca.getNodeData().getTaxonomy().getScientificName() ) ) {
349 lca_species = lca.getNodeData().getTaxonomy().getScientificName();
351 else if ( lca.getNodeData().isHasTaxonomy()
352 && !ForesterUtil.isEmpty( lca.getNodeData().getTaxonomy().getCommonName() ) ) {
353 lca_species = lca.getNodeData().getTaxonomy().getCommonName();
356 lca_species = lca.getName();
358 addToCountMap( lca_ancestor_species_counts, lca_species );
362 final BufferedWriter out_for_rank_counts = new BufferedWriter( new FileWriter( outfilename_for_rank_counts ) );
363 final BufferedWriter out_for_ancestor_species_counts = new BufferedWriter( new FileWriter( outfilename_for_ancestor_species_counts ) );
364 ForesterUtil.map2writer( out_for_rank_counts, lca_rank_counts, "\t", ForesterUtil.LINE_SEPARATOR );
365 ForesterUtil.map2writer( out_for_ancestor_species_counts,
366 lca_ancestor_species_counts,
368 ForesterUtil.LINE_SEPARATOR );
369 out_for_rank_counts.close();
370 out_for_ancestor_species_counts.close();
371 if ( !ForesterUtil.isEmpty( outfilename_for_protein_stats )
372 && ( ( protein_length_stats_by_dc != null ) || ( domain_number_stats_by_dc != null ) ) ) {
373 final BufferedWriter w = new BufferedWriter( new FileWriter( outfilename_for_protein_stats ) );
374 w.write( "Lengths: " );
376 if ( protein_length_stats_by_dc != null ) {
377 for( final Entry<Integer, DescriptiveStatistics> entry : dc_reapp_counts_to_protein_length_stats
379 w.write( entry.getKey().toString() );
380 w.write( ": " + entry.getValue().arithmeticMean() );
387 w.write( "Number of domains: " );
389 if ( domain_number_stats_by_dc != null ) {
390 for( final Entry<Integer, DescriptiveStatistics> entry : dc_reapp_counts_to_domain_number_stats
392 w.write( entry.getKey().toString() );
393 w.write( ": " + entry.getValue().arithmeticMean() );
400 w.write( "Gained once, protein lengths:" );
402 w.write( gained_once_lengths_stats.toString() );
405 w.write( "Gained once, domain counts:" );
407 w.write( gained_once_domain_count_stats.toString() );
410 w.write( "Gained multiple times, protein lengths:" );
412 w.write( gained_multiple_times_lengths_stats.toString() );
415 w.write( "Gained multiple times, domain counts:" );
417 w.write( gained_multiple_times_domain_count_stats.toString() );
422 catch ( final IOException e ) {
423 ForesterUtil.printWarningMessage( surfacing.PRG_NAME, "Failure to write: " + e );
425 ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote independent domain combination gains fitch counts to ["
426 + outfilename_for_counts + "]" );
427 ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote independent domain combination gains fitch lists to ["
428 + outfilename_for_dc + "]" );
429 ForesterUtil.programMessage( surfacing.PRG_NAME,
430 "Wrote independent domain combination gains fitch lists to (for GO mapping) ["
431 + outfilename_for_dc_for_go_mapping + "]" );
432 ForesterUtil.programMessage( surfacing.PRG_NAME,
433 "Wrote independent domain combination gains fitch lists to (for GO mapping, unique) ["
434 + outfilename_for_dc_for_go_mapping_unique + "]" );
437 private final static void addToCountMap( final Map<String, Integer> map, final String s ) {
438 if ( map.containsKey( s ) ) {
439 map.put( s, map.get( s ) + 1 );
446 public static int calculateOverlap( final Domain domain, final List<Boolean> covered_positions ) {
447 int overlap_count = 0;
448 for( int i = domain.getFrom(); i <= domain.getTo(); ++i ) {
449 if ( ( i < covered_positions.size() ) && ( covered_positions.get( i ) == true ) ) {
453 return overlap_count;
456 public static void checkForOutputFileWriteability( final File outfile ) {
457 final String error = ForesterUtil.isWritableFile( outfile );
458 if ( !ForesterUtil.isEmpty( error ) ) {
459 ForesterUtil.fatalError( surfacing.PRG_NAME, error );
463 private static SortedSet<String> collectAllDomainsChangedOnSubtree( final PhylogenyNode subtree_root,
464 final boolean get_gains ) {
465 final SortedSet<String> domains = new TreeSet<String>();
466 for( final PhylogenyNode descendant : PhylogenyMethods.getAllDescendants( subtree_root ) ) {
467 final BinaryCharacters chars = descendant.getNodeData().getBinaryCharacters();
469 domains.addAll( chars.getGainedCharacters() );
472 domains.addAll( chars.getLostCharacters() );
478 public static void collectChangedDomainCombinationsFromBinaryStatesMatrixAsListToFile( final CharacterStateMatrix<CharacterStateMatrix.GainLossStates> matrix,
479 final BinaryDomainCombination.DomainCombinationType dc_type,
480 final List<BinaryDomainCombination> all_binary_domains_combination_gained,
481 final boolean get_gains ) {
482 final SortedSet<String> sorted_ids = new TreeSet<String>();
483 for( int i = 0; i < matrix.getNumberOfIdentifiers(); ++i ) {
484 sorted_ids.add( matrix.getIdentifier( i ) );
486 for( final String id : sorted_ids ) {
487 for( int c = 0; c < matrix.getNumberOfCharacters(); ++c ) {
488 if ( ( get_gains && ( matrix.getState( id, c ) == CharacterStateMatrix.GainLossStates.GAIN ) )
489 || ( !get_gains && ( matrix.getState( id, c ) == CharacterStateMatrix.GainLossStates.LOSS ) ) ) {
490 if ( dc_type == BinaryDomainCombination.DomainCombinationType.DIRECTED_ADJACTANT ) {
491 all_binary_domains_combination_gained.add( AdjactantDirectedBinaryDomainCombination
492 .createInstance( matrix.getCharacter( c ) ) );
494 else if ( dc_type == BinaryDomainCombination.DomainCombinationType.DIRECTED ) {
495 all_binary_domains_combination_gained.add( DirectedBinaryDomainCombination
496 .createInstance( matrix.getCharacter( c ) ) );
499 all_binary_domains_combination_gained.add( BasicBinaryDomainCombination.createInstance( matrix
500 .getCharacter( c ) ) );
507 private static File createBaseDirForPerNodeDomainFiles( final String base_dir,
508 final boolean domain_combinations,
509 final CharacterStateMatrix.GainLossStates state,
510 final String outfile ) {
511 File per_node_go_mapped_domain_gain_loss_files_base_dir = new File( new File( outfile ).getParent()
512 + ForesterUtil.FILE_SEPARATOR + base_dir );
513 if ( !per_node_go_mapped_domain_gain_loss_files_base_dir.exists() ) {
514 per_node_go_mapped_domain_gain_loss_files_base_dir.mkdir();
516 if ( domain_combinations ) {
517 per_node_go_mapped_domain_gain_loss_files_base_dir = new File( per_node_go_mapped_domain_gain_loss_files_base_dir
518 + ForesterUtil.FILE_SEPARATOR + "DC" );
521 per_node_go_mapped_domain_gain_loss_files_base_dir = new File( per_node_go_mapped_domain_gain_loss_files_base_dir
522 + ForesterUtil.FILE_SEPARATOR + "DOMAINS" );
524 if ( !per_node_go_mapped_domain_gain_loss_files_base_dir.exists() ) {
525 per_node_go_mapped_domain_gain_loss_files_base_dir.mkdir();
527 if ( state == GainLossStates.GAIN ) {
528 per_node_go_mapped_domain_gain_loss_files_base_dir = new File( per_node_go_mapped_domain_gain_loss_files_base_dir
529 + ForesterUtil.FILE_SEPARATOR + "GAINS" );
531 else if ( state == GainLossStates.LOSS ) {
532 per_node_go_mapped_domain_gain_loss_files_base_dir = new File( per_node_go_mapped_domain_gain_loss_files_base_dir
533 + ForesterUtil.FILE_SEPARATOR + "LOSSES" );
536 per_node_go_mapped_domain_gain_loss_files_base_dir = new File( per_node_go_mapped_domain_gain_loss_files_base_dir
537 + ForesterUtil.FILE_SEPARATOR + "PRESENT" );
539 if ( !per_node_go_mapped_domain_gain_loss_files_base_dir.exists() ) {
540 per_node_go_mapped_domain_gain_loss_files_base_dir.mkdir();
542 return per_node_go_mapped_domain_gain_loss_files_base_dir;
545 public static Map<DomainId, List<GoId>> createDomainIdToGoIdMap( final List<PfamToGoMapping> pfam_to_go_mappings ) {
546 final Map<DomainId, List<GoId>> domain_id_to_go_ids_map = new HashMap<DomainId, List<GoId>>( pfam_to_go_mappings
548 for( final PfamToGoMapping pfam_to_go : pfam_to_go_mappings ) {
549 if ( !domain_id_to_go_ids_map.containsKey( pfam_to_go.getKey() ) ) {
550 domain_id_to_go_ids_map.put( pfam_to_go.getKey(), new ArrayList<GoId>() );
552 domain_id_to_go_ids_map.get( pfam_to_go.getKey() ).add( pfam_to_go.getValue() );
554 return domain_id_to_go_ids_map;
557 public static Map<DomainId, Set<String>> createDomainIdToSecondaryFeaturesMap( final File secondary_features_map_file )
559 final BasicTable<String> primary_table = BasicTableParser.parse( secondary_features_map_file, "\t" );
560 final Map<DomainId, Set<String>> map = new TreeMap<DomainId, Set<String>>();
561 for( int r = 0; r < primary_table.getNumberOfRows(); ++r ) {
562 final DomainId domain_id = new DomainId( primary_table.getValue( 0, r ) );
563 if ( !map.containsKey( domain_id ) ) {
564 map.put( domain_id, new HashSet<String>() );
566 map.get( domain_id ).add( primary_table.getValue( 1, r ) );
571 public static Phylogeny createNjTreeBasedOnMatrixToFile( final File nj_tree_outfile, final DistanceMatrix distance ) {
572 checkForOutputFileWriteability( nj_tree_outfile );
573 final NeighborJoining nj = NeighborJoining.createInstance();
574 final Phylogeny phylogeny = nj.execute( distance );
575 phylogeny.setName( nj_tree_outfile.getName() );
576 writePhylogenyToFile( phylogeny, nj_tree_outfile.toString() );
580 private static SortedSet<BinaryDomainCombination> createSetOfAllBinaryDomainCombinationsPerGenome( final GenomeWideCombinableDomains gwcd ) {
581 final SortedMap<DomainId, CombinableDomains> cds = gwcd.getAllCombinableDomainsIds();
582 final SortedSet<BinaryDomainCombination> binary_combinations = new TreeSet<BinaryDomainCombination>();
583 for( final DomainId domain_id : cds.keySet() ) {
584 final CombinableDomains cd = cds.get( domain_id );
585 binary_combinations.addAll( cd.toBinaryDomainCombinations() );
587 return binary_combinations;
590 public static void decoratePrintableDomainSimilarities( final SortedSet<DomainSimilarity> domain_similarities,
591 final Detailedness detailedness,
592 final GoAnnotationOutput go_annotation_output,
593 final Map<GoId, GoTerm> go_id_to_term_map,
594 final GoNameSpace go_namespace_limit ) {
595 if ( ( go_namespace_limit != null ) && ( ( go_id_to_term_map == null ) || go_id_to_term_map.isEmpty() ) ) {
596 throw new IllegalArgumentException( "attempt to use a GO namespace limit without a GO id to term map" );
598 for( final DomainSimilarity domain_similarity : domain_similarities ) {
599 if ( domain_similarity instanceof PrintableDomainSimilarity ) {
600 final PrintableDomainSimilarity printable_domain_similarity = ( PrintableDomainSimilarity ) domain_similarity;
601 printable_domain_similarity.setDetailedness( detailedness );
602 printable_domain_similarity.setGoAnnotationOutput( go_annotation_output );
603 printable_domain_similarity.setGoIdToTermMap( go_id_to_term_map );
604 printable_domain_similarity.setGoNamespaceLimit( go_namespace_limit );
609 public static void executeDomainLengthAnalysis( final String[][] input_file_properties,
610 final int number_of_genomes,
611 final DomainLengthsTable domain_lengths_table,
612 final File outfile ) throws IOException {
613 final DecimalFormat df = new DecimalFormat( "#.00" );
614 checkForOutputFileWriteability( outfile );
615 final BufferedWriter out = new BufferedWriter( new FileWriter( outfile ) );
616 out.write( "MEAN BASED STATISTICS PER SPECIES" );
617 out.write( ForesterUtil.LINE_SEPARATOR );
618 out.write( domain_lengths_table.createMeanBasedStatisticsPerSpeciesTable().toString() );
619 out.write( ForesterUtil.LINE_SEPARATOR );
620 out.write( ForesterUtil.LINE_SEPARATOR );
621 final List<DomainLengths> domain_lengths_list = domain_lengths_table.getDomainLengthsList();
622 out.write( "OUTLIER SPECIES PER DOMAIN (Z>=1.5)" );
623 out.write( ForesterUtil.LINE_SEPARATOR );
624 for( final DomainLengths domain_lengths : domain_lengths_list ) {
625 final List<Species> species_list = domain_lengths.getMeanBasedOutlierSpecies( 1.5 );
626 if ( species_list.size() > 0 ) {
627 out.write( domain_lengths.getDomainId() + "\t" );
628 for( final Species species : species_list ) {
629 out.write( species + "\t" );
631 out.write( ForesterUtil.LINE_SEPARATOR );
632 // DescriptiveStatistics stats_for_domain = domain_lengths
633 // .calculateMeanBasedStatistics();
634 //AsciiHistogram histo = new AsciiHistogram( stats_for_domain );
635 //System.out.println( histo.toStringBuffer( 40, '=', 60, 4 ).toString() );
638 out.write( ForesterUtil.LINE_SEPARATOR );
639 out.write( ForesterUtil.LINE_SEPARATOR );
640 out.write( "OUTLIER SPECIES (Z 1.0)" );
641 out.write( ForesterUtil.LINE_SEPARATOR );
642 final DescriptiveStatistics stats_for_all_species = domain_lengths_table
643 .calculateMeanBasedStatisticsForAllSpecies();
644 out.write( stats_for_all_species.asSummary() );
645 out.write( ForesterUtil.LINE_SEPARATOR );
646 final AsciiHistogram histo = new AsciiHistogram( stats_for_all_species );
647 out.write( histo.toStringBuffer( 40, '=', 60, 4 ).toString() );
648 out.write( ForesterUtil.LINE_SEPARATOR );
649 final double population_sd = stats_for_all_species.sampleStandardDeviation();
650 final double population_mean = stats_for_all_species.arithmeticMean();
651 for( final Species species : domain_lengths_table.getSpecies() ) {
652 final double x = domain_lengths_table.calculateMeanBasedStatisticsForSpecies( species ).arithmeticMean();
653 final double z = ( x - population_mean ) / population_sd;
654 out.write( species + "\t" + z );
655 out.write( ForesterUtil.LINE_SEPARATOR );
657 out.write( ForesterUtil.LINE_SEPARATOR );
658 for( final Species species : domain_lengths_table.getSpecies() ) {
659 final DescriptiveStatistics stats_for_species = domain_lengths_table
660 .calculateMeanBasedStatisticsForSpecies( species );
661 final double x = stats_for_species.arithmeticMean();
662 final double z = ( x - population_mean ) / population_sd;
663 if ( ( z <= -1.0 ) || ( z >= 1.0 ) ) {
664 out.write( species + "\t" + df.format( z ) + "\t" + stats_for_species.asSummary() );
665 out.write( ForesterUtil.LINE_SEPARATOR );
669 // final List<HistogramData> histogram_datas = new ArrayList<HistogramData>();
670 // for( int i = 0; i < number_of_genomes; ++i ) {
671 // final Species species = new BasicSpecies( input_file_properties[ i ][ 0 ] );
673 // .add( new HistogramData( species.toString(), domain_lengths_table
674 // .calculateMeanBasedStatisticsForSpecies( species )
675 // .getDataAsDoubleArray(), 5, 600, null, 60 ) );
677 // final HistogramsFrame hf = new HistogramsFrame( histogram_datas );
678 // hf.setVisible( true );
684 * @param all_binary_domains_combination_lost_fitch
685 * @param consider_directedness_and_adjacency_for_bin_combinations
686 * @param all_binary_domains_combination_gained if null ignored, otherwise this is to list all binary domain combinations
687 * which were gained under unweighted (Fitch) parsimony.
689 public static void executeParsimonyAnalysis( final long random_number_seed_for_fitch_parsimony,
690 final boolean radomize_fitch_parsimony,
691 final String outfile_name,
692 final DomainParsimonyCalculator domain_parsimony,
693 final Phylogeny phylogeny,
694 final Map<DomainId, List<GoId>> domain_id_to_go_ids_map,
695 final Map<GoId, GoTerm> go_id_to_term_map,
696 final GoNameSpace go_namespace_limit,
697 final String parameters_str,
698 final Map<DomainId, Set<String>>[] domain_id_to_secondary_features_maps,
699 final SortedSet<DomainId> positive_filter,
700 final boolean output_binary_domain_combinations_for_graphs,
701 final List<BinaryDomainCombination> all_binary_domains_combination_gained_fitch,
702 final List<BinaryDomainCombination> all_binary_domains_combination_lost_fitch,
703 final BinaryDomainCombination.DomainCombinationType dc_type,
704 final Map<String, DescriptiveStatistics> protein_length_stats_by_dc,
705 final Map<String, DescriptiveStatistics> domain_number_stats_by_dc ) {
706 final String sep = ForesterUtil.LINE_SEPARATOR + "###################" + ForesterUtil.LINE_SEPARATOR;
707 final String date_time = ForesterUtil.getCurrentDateTime();
708 final SortedSet<String> all_pfams_encountered = new TreeSet<String>();
709 final SortedSet<String> all_pfams_gained_as_domains = new TreeSet<String>();
710 final SortedSet<String> all_pfams_lost_as_domains = new TreeSet<String>();
711 final SortedSet<String> all_pfams_gained_as_dom_combinations = new TreeSet<String>();
712 final SortedSet<String> all_pfams_lost_as_dom_combinations = new TreeSet<String>();
713 writeToNexus( outfile_name, domain_parsimony, phylogeny );
716 Phylogeny local_phylogeny_l = phylogeny.copy();
717 if ( ( positive_filter != null ) && ( positive_filter.size() > 0 ) ) {
718 domain_parsimony.executeDolloParsimonyOnDomainPresence( positive_filter );
721 domain_parsimony.executeDolloParsimonyOnDomainPresence();
723 SurfacingUtil.writeMatrixToFile( domain_parsimony.getGainLossMatrix(), outfile_name
724 + surfacing.PARSIMONY_OUTPUT_GL_SUFFIX_DOLLO_DOMAINS, Format.FORESTER );
725 SurfacingUtil.writeMatrixToFile( domain_parsimony.getGainLossCountsMatrix(), outfile_name
726 + surfacing.PARSIMONY_OUTPUT_GL_COUNTS_SUFFIX_DOLLO_DOMAINS, Format.FORESTER );
727 SurfacingUtil.writeBinaryStatesMatrixAsListToFile( domain_parsimony.getGainLossMatrix(),
728 CharacterStateMatrix.GainLossStates.GAIN,
729 outfile_name + surfacing.PARSIMONY_OUTPUT_DOLLO_GAINS_D,
731 ForesterUtil.LINE_SEPARATOR,
733 SurfacingUtil.writeBinaryStatesMatrixAsListToFile( domain_parsimony.getGainLossMatrix(),
734 CharacterStateMatrix.GainLossStates.LOSS,
735 outfile_name + surfacing.PARSIMONY_OUTPUT_DOLLO_LOSSES_D,
737 ForesterUtil.LINE_SEPARATOR,
739 SurfacingUtil.writeBinaryStatesMatrixAsListToFile( domain_parsimony.getGainLossMatrix(), null, outfile_name
740 + surfacing.PARSIMONY_OUTPUT_DOLLO_PRESENT_D, sep, ForesterUtil.LINE_SEPARATOR, null );
742 writeBinaryStatesMatrixToList( domain_id_to_go_ids_map,
746 domain_parsimony.getGainLossMatrix(),
747 CharacterStateMatrix.GainLossStates.GAIN,
748 outfile_name + surfacing.PARSIMONY_OUTPUT_DOLLO_GAINS_HTML_D,
750 ForesterUtil.LINE_SEPARATOR,
751 "Dollo Parsimony | Gains | Domains",
753 domain_id_to_secondary_features_maps,
754 all_pfams_encountered,
755 all_pfams_gained_as_domains,
757 writeBinaryStatesMatrixToList( domain_id_to_go_ids_map,
761 domain_parsimony.getGainLossMatrix(),
762 CharacterStateMatrix.GainLossStates.LOSS,
763 outfile_name + surfacing.PARSIMONY_OUTPUT_DOLLO_LOSSES_HTML_D,
765 ForesterUtil.LINE_SEPARATOR,
766 "Dollo Parsimony | Losses | Domains",
768 domain_id_to_secondary_features_maps,
769 all_pfams_encountered,
770 all_pfams_lost_as_domains,
772 writeBinaryStatesMatrixToList( domain_id_to_go_ids_map,
776 domain_parsimony.getGainLossMatrix(),
778 outfile_name + surfacing.PARSIMONY_OUTPUT_DOLLO_PRESENT_HTML_D,
780 ForesterUtil.LINE_SEPARATOR,
781 "Dollo Parsimony | Present | Domains",
783 domain_id_to_secondary_features_maps,
784 all_pfams_encountered,
786 "_dollo_present_d" );
787 preparePhylogeny( local_phylogeny_l,
790 "Dollo parsimony on domain presence/absence",
791 "dollo_on_domains_" + outfile_name,
793 SurfacingUtil.writePhylogenyToFile( local_phylogeny_l, outfile_name
794 + surfacing.DOMAINS_PARSIMONY_TREE_OUTPUT_SUFFIX_DOLLO );
796 writeAllDomainsChangedOnAllSubtrees( local_phylogeny_l, true, outfile_name, "_dollo_all_gains_d" );
797 writeAllDomainsChangedOnAllSubtrees( local_phylogeny_l, false, outfile_name, "_dollo_all_losses_d" );
799 catch ( final IOException e ) {
801 ForesterUtil.fatalError( surfacing.PRG_NAME, e.getLocalizedMessage() );
803 if ( domain_parsimony.calculateNumberOfBinaryDomainCombination() > 0 ) {
804 // FITCH DOMAIN COMBINATIONS
805 // -------------------------
806 local_phylogeny_l = phylogeny.copy();
807 String randomization = "no";
808 if ( radomize_fitch_parsimony ) {
809 domain_parsimony.executeFitchParsimonyOnBinaryDomainCombintion( random_number_seed_for_fitch_parsimony );
810 randomization = "yes, seed = " + random_number_seed_for_fitch_parsimony;
813 domain_parsimony.executeFitchParsimonyOnBinaryDomainCombintion( USE_LAST );
815 SurfacingUtil.writeMatrixToFile( domain_parsimony.getGainLossMatrix(), outfile_name
816 + surfacing.PARSIMONY_OUTPUT_GL_SUFFIX_FITCH_BINARY_COMBINATIONS, Format.FORESTER );
817 SurfacingUtil.writeMatrixToFile( domain_parsimony.getGainLossCountsMatrix(), outfile_name
818 + surfacing.PARSIMONY_OUTPUT_GL_COUNTS_SUFFIX_FITCH_BINARY_COMBINATIONS, Format.FORESTER );
820 .writeBinaryStatesMatrixAsListToFile( domain_parsimony.getGainLossMatrix(),
821 CharacterStateMatrix.GainLossStates.GAIN,
822 outfile_name + surfacing.PARSIMONY_OUTPUT_FITCH_GAINS_BC,
824 ForesterUtil.LINE_SEPARATOR,
826 SurfacingUtil.writeBinaryStatesMatrixAsListToFile( domain_parsimony.getGainLossMatrix(),
827 CharacterStateMatrix.GainLossStates.LOSS,
829 + surfacing.PARSIMONY_OUTPUT_FITCH_LOSSES_BC,
831 ForesterUtil.LINE_SEPARATOR,
833 SurfacingUtil.writeBinaryStatesMatrixAsListToFile( domain_parsimony.getGainLossMatrix(), null, outfile_name
834 + surfacing.PARSIMONY_OUTPUT_FITCH_PRESENT_BC, sep, ForesterUtil.LINE_SEPARATOR, null );
835 if ( all_binary_domains_combination_gained_fitch != null ) {
836 collectChangedDomainCombinationsFromBinaryStatesMatrixAsListToFile( domain_parsimony.getGainLossMatrix(),
838 all_binary_domains_combination_gained_fitch,
841 if ( all_binary_domains_combination_lost_fitch != null ) {
842 collectChangedDomainCombinationsFromBinaryStatesMatrixAsListToFile( domain_parsimony.getGainLossMatrix(),
844 all_binary_domains_combination_lost_fitch,
847 if ( output_binary_domain_combinations_for_graphs ) {
849 .writeBinaryStatesMatrixAsListToFileForBinaryCombinationsForGraphAnalysis( domain_parsimony
850 .getGainLossMatrix(),
853 + surfacing.PARSIMONY_OUTPUT_FITCH_PRESENT_BC_OUTPUTFILE_SUFFIX_FOR_GRAPH_ANALYSIS,
855 ForesterUtil.LINE_SEPARATOR,
856 BinaryDomainCombination.OutputFormat.DOT );
859 writeBinaryStatesMatrixToList( domain_id_to_go_ids_map,
863 domain_parsimony.getGainLossMatrix(),
864 CharacterStateMatrix.GainLossStates.GAIN,
865 outfile_name + surfacing.PARSIMONY_OUTPUT_FITCH_GAINS_HTML_BC,
867 ForesterUtil.LINE_SEPARATOR,
868 "Fitch Parsimony | Gains | Domain Combinations",
871 all_pfams_encountered,
872 all_pfams_gained_as_dom_combinations,
874 writeBinaryStatesMatrixToList( domain_id_to_go_ids_map,
878 domain_parsimony.getGainLossMatrix(),
879 CharacterStateMatrix.GainLossStates.LOSS,
880 outfile_name + surfacing.PARSIMONY_OUTPUT_FITCH_LOSSES_HTML_BC,
882 ForesterUtil.LINE_SEPARATOR,
883 "Fitch Parsimony | Losses | Domain Combinations",
886 all_pfams_encountered,
887 all_pfams_lost_as_dom_combinations,
888 "_fitch_losses_dc" );
889 writeBinaryStatesMatrixToList( domain_id_to_go_ids_map,
893 domain_parsimony.getGainLossMatrix(),
895 outfile_name + surfacing.PARSIMONY_OUTPUT_FITCH_PRESENT_HTML_BC,
897 ForesterUtil.LINE_SEPARATOR,
898 "Fitch Parsimony | Present | Domain Combinations",
901 all_pfams_encountered,
903 "_fitch_present_dc" );
904 writeAllEncounteredPfamsToFile( domain_id_to_go_ids_map,
907 all_pfams_encountered );
908 writePfamsToFile( outfile_name + surfacing.ALL_PFAMS_GAINED_AS_DOMAINS_SUFFIX, all_pfams_gained_as_domains );
909 writePfamsToFile( outfile_name + surfacing.ALL_PFAMS_LOST_AS_DOMAINS_SUFFIX, all_pfams_lost_as_domains );
910 writePfamsToFile( outfile_name + surfacing.ALL_PFAMS_GAINED_AS_DC_SUFFIX,
911 all_pfams_gained_as_dom_combinations );
912 writePfamsToFile( outfile_name + surfacing.ALL_PFAMS_LOST_AS_DC_SUFFIX, all_pfams_lost_as_dom_combinations );
913 preparePhylogeny( local_phylogeny_l,
916 "Fitch parsimony on binary domain combination presence/absence randomization: "
918 "fitch_on_binary_domain_combinations_" + outfile_name,
920 SurfacingUtil.writePhylogenyToFile( local_phylogeny_l, outfile_name
921 + surfacing.BINARY_DOMAIN_COMBINATIONS_PARSIMONY_TREE_OUTPUT_SUFFIX_FITCH );
922 calculateIndependentDomainCombinationGains( local_phylogeny_l,
924 + surfacing.INDEPENDENT_DC_GAINS_FITCH_PARS_COUNTS_OUTPUT_SUFFIX,
926 + surfacing.INDEPENDENT_DC_GAINS_FITCH_PARS_DC_OUTPUT_SUFFIX,
928 + surfacing.INDEPENDENT_DC_GAINS_FITCH_PARS_DC_FOR_GO_MAPPING_OUTPUT_SUFFIX,
930 + surfacing.INDEPENDENT_DC_GAINS_FITCH_PARS_DC_FOR_GO_MAPPING_OUTPUT_UNIQUE_SUFFIX,
931 outfile_name + "_indep_dc_gains_fitch_lca_ranks.txt",
932 outfile_name + "_indep_dc_gains_fitch_lca_taxonomies.txt",
933 outfile_name + "_indep_dc_gains_fitch_protein_statistics.txt",
934 protein_length_stats_by_dc,
935 domain_number_stats_by_dc );
939 public static void executeParsimonyAnalysisForSecondaryFeatures( final String outfile_name,
940 final DomainParsimonyCalculator secondary_features_parsimony,
941 final Phylogeny phylogeny,
942 final String parameters_str,
943 final Map<Species, MappingResults> mapping_results_map ) {
944 final String sep = ForesterUtil.LINE_SEPARATOR + "###################" + ForesterUtil.LINE_SEPARATOR;
945 final String date_time = ForesterUtil.getCurrentDateTime();
946 System.out.println();
947 writeToNexus( outfile_name + surfacing.NEXUS_SECONDARY_FEATURES,
948 secondary_features_parsimony.createMatrixOfSecondaryFeaturePresenceOrAbsence( null ),
950 Phylogeny local_phylogeny_copy = phylogeny.copy();
951 secondary_features_parsimony.executeDolloParsimonyOnSecondaryFeatures( mapping_results_map );
952 SurfacingUtil.writeMatrixToFile( secondary_features_parsimony.getGainLossMatrix(), outfile_name
953 + surfacing.PARSIMONY_OUTPUT_GL_SUFFIX_DOLLO_SECONDARY_FEATURES, Format.FORESTER );
954 SurfacingUtil.writeMatrixToFile( secondary_features_parsimony.getGainLossCountsMatrix(), outfile_name
955 + surfacing.PARSIMONY_OUTPUT_GL_COUNTS_SUFFIX_DOLLO_SECONDARY_FEATURES, Format.FORESTER );
957 .writeBinaryStatesMatrixAsListToFile( secondary_features_parsimony.getGainLossMatrix(),
958 CharacterStateMatrix.GainLossStates.GAIN,
960 + surfacing.PARSIMONY_OUTPUT_DOLLO_GAINS_SECONDARY_FEATURES,
962 ForesterUtil.LINE_SEPARATOR,
965 .writeBinaryStatesMatrixAsListToFile( secondary_features_parsimony.getGainLossMatrix(),
966 CharacterStateMatrix.GainLossStates.LOSS,
968 + surfacing.PARSIMONY_OUTPUT_DOLLO_LOSSES_SECONDARY_FEATURES,
970 ForesterUtil.LINE_SEPARATOR,
973 .writeBinaryStatesMatrixAsListToFile( secondary_features_parsimony.getGainLossMatrix(),
976 + surfacing.PARSIMONY_OUTPUT_DOLLO_PRESENT_SECONDARY_FEATURES,
978 ForesterUtil.LINE_SEPARATOR,
980 preparePhylogeny( local_phylogeny_copy,
981 secondary_features_parsimony,
983 "Dollo parsimony on secondary feature presence/absence",
984 "dollo_on_secondary_features_" + outfile_name,
986 SurfacingUtil.writePhylogenyToFile( local_phylogeny_copy, outfile_name
987 + surfacing.SECONDARY_FEATURES_PARSIMONY_TREE_OUTPUT_SUFFIX_DOLLO );
988 // FITCH DOMAIN COMBINATIONS
989 // -------------------------
990 local_phylogeny_copy = phylogeny.copy();
991 final String randomization = "no";
992 secondary_features_parsimony.executeFitchParsimonyOnBinaryDomainCombintionOnSecondaryFeatures( USE_LAST );
993 preparePhylogeny( local_phylogeny_copy,
994 secondary_features_parsimony,
996 "Fitch parsimony on secondary binary domain combination presence/absence randomization: "
998 "fitch_on_binary_domain_combinations_" + outfile_name,
1000 SurfacingUtil.writePhylogenyToFile( local_phylogeny_copy, outfile_name
1001 + surfacing.BINARY_DOMAIN_COMBINATIONS_PARSIMONY_TREE_OUTPUT_SUFFIX_FITCH_MAPPED );
1002 calculateIndependentDomainCombinationGains( local_phylogeny_copy, outfile_name
1003 + surfacing.INDEPENDENT_DC_GAINS_FITCH_PARS_COUNTS_MAPPED_OUTPUT_SUFFIX, outfile_name
1004 + surfacing.INDEPENDENT_DC_GAINS_FITCH_PARS_DC_MAPPED_OUTPUT_SUFFIX, outfile_name
1005 + surfacing.INDEPENDENT_DC_GAINS_FITCH_PARS_DC_FOR_GO_MAPPING_MAPPED_OUTPUT_SUFFIX, outfile_name
1006 + surfacing.INDEPENDENT_DC_GAINS_FITCH_PARS_DC_FOR_GO_MAPPING_MAPPED_OUTPUT_UNIQUE_SUFFIX, outfile_name
1007 + "_MAPPED_indep_dc_gains_fitch_lca_ranks.txt", outfile_name
1008 + "_MAPPED_indep_dc_gains_fitch_lca_taxonomies.txt", null, null, null );
1011 public static void doit( final List<Protein> proteins,
1012 final List<DomainId> query_domain_ids_nc_order,
1014 final String separator,
1015 final String limit_to_species,
1016 final Map<String, List<Integer>> average_protein_lengths_by_dc ) throws IOException {
1017 for( final Protein protein : proteins ) {
1018 if ( ForesterUtil.isEmpty( limit_to_species )
1019 || protein.getSpecies().getSpeciesId().equalsIgnoreCase( limit_to_species ) ) {
1020 if ( protein.contains( query_domain_ids_nc_order, true ) ) {
1021 out.write( protein.getSpecies().getSpeciesId() );
1022 out.write( separator );
1023 out.write( protein.getProteinId().getId() );
1024 out.write( separator );
1026 final Set<DomainId> visited_domain_ids = new HashSet<DomainId>();
1027 boolean first = true;
1028 for( final Domain domain : protein.getProteinDomains() ) {
1029 if ( !visited_domain_ids.contains( domain.getDomainId() ) ) {
1030 visited_domain_ids.add( domain.getDomainId() );
1037 out.write( domain.getDomainId().getId() );
1039 out.write( "" + domain.getTotalCount() );
1044 out.write( separator );
1045 if ( !( ForesterUtil.isEmpty( protein.getDescription() ) || protein.getDescription()
1046 .equals( SurfacingConstants.NONE ) ) ) {
1047 out.write( protein.getDescription() );
1049 out.write( separator );
1050 if ( !( ForesterUtil.isEmpty( protein.getAccession() ) || protein.getAccession()
1051 .equals( SurfacingConstants.NONE ) ) ) {
1052 out.write( protein.getAccession() );
1054 out.write( SurfacingConstants.NL );
1061 public static void extractProteinNames( final List<Protein> proteins,
1062 final List<DomainId> query_domain_ids_nc_order,
1064 final String separator,
1065 final String limit_to_species ) throws IOException {
1066 for( final Protein protein : proteins ) {
1067 if ( ForesterUtil.isEmpty( limit_to_species )
1068 || protein.getSpecies().getSpeciesId().equalsIgnoreCase( limit_to_species ) ) {
1069 if ( protein.contains( query_domain_ids_nc_order, true ) ) {
1070 out.write( protein.getSpecies().getSpeciesId() );
1071 out.write( separator );
1072 out.write( protein.getProteinId().getId() );
1073 out.write( separator );
1075 final Set<DomainId> visited_domain_ids = new HashSet<DomainId>();
1076 boolean first = true;
1077 for( final Domain domain : protein.getProteinDomains() ) {
1078 if ( !visited_domain_ids.contains( domain.getDomainId() ) ) {
1079 visited_domain_ids.add( domain.getDomainId() );
1086 out.write( domain.getDomainId().getId() );
1088 out.write( "" + domain.getTotalCount() );
1093 out.write( separator );
1094 if ( !( ForesterUtil.isEmpty( protein.getDescription() ) || protein.getDescription()
1095 .equals( SurfacingConstants.NONE ) ) ) {
1096 out.write( protein.getDescription() );
1098 out.write( separator );
1099 if ( !( ForesterUtil.isEmpty( protein.getAccession() ) || protein.getAccession()
1100 .equals( SurfacingConstants.NONE ) ) ) {
1101 out.write( protein.getAccession() );
1103 out.write( SurfacingConstants.NL );
1110 public static void extractProteinNames( final SortedMap<Species, List<Protein>> protein_lists_per_species,
1111 final DomainId domain_id,
1113 final String separator,
1114 final String limit_to_species ) throws IOException {
1115 for( final Species species : protein_lists_per_species.keySet() ) {
1116 for( final Protein protein : protein_lists_per_species.get( species ) ) {
1117 if ( ForesterUtil.isEmpty( limit_to_species )
1118 || protein.getSpecies().getSpeciesId().equalsIgnoreCase( limit_to_species ) ) {
1119 final List<Domain> domains = protein.getProteinDomains( domain_id );
1120 if ( domains.size() > 0 ) {
1121 final DescriptiveStatistics stats = new BasicDescriptiveStatistics();
1122 for( final Domain domain : domains ) {
1123 stats.addValue( domain.getPerSequenceEvalue() );
1125 out.write( protein.getSpecies().getSpeciesId() );
1126 out.write( separator );
1127 out.write( protein.getProteinId().getId() );
1128 out.write( separator );
1129 out.write( "[" + FORMATTER.format( stats.median() ) + "]" );
1130 out.write( separator );
1131 if ( !( ForesterUtil.isEmpty( protein.getDescription() ) || protein.getDescription()
1132 .equals( SurfacingConstants.NONE ) ) ) {
1133 out.write( protein.getDescription() );
1135 out.write( separator );
1136 if ( !( ForesterUtil.isEmpty( protein.getAccession() ) || protein.getAccession()
1137 .equals( SurfacingConstants.NONE ) ) ) {
1138 out.write( protein.getAccession() );
1140 out.write( SurfacingConstants.NL );
1148 public static SortedSet<DomainId> getAllDomainIds( final List<GenomeWideCombinableDomains> gwcd_list ) {
1149 final SortedSet<DomainId> all_domains_ids = new TreeSet<DomainId>();
1150 for( final GenomeWideCombinableDomains gwcd : gwcd_list ) {
1151 final Set<DomainId> all_domains = gwcd.getAllDomainIds();
1152 // for( final Domain domain : all_domains ) {
1153 all_domains_ids.addAll( all_domains );
1156 return all_domains_ids;
1159 public static SortedMap<String, Integer> getDomainCounts( final List<Protein> protein_domain_collections ) {
1160 final SortedMap<String, Integer> map = new TreeMap<String, Integer>();
1161 for( final Protein protein_domain_collection : protein_domain_collections ) {
1162 for( final Object name : protein_domain_collection.getProteinDomains() ) {
1163 final BasicDomain protein_domain = ( BasicDomain ) name;
1164 final String id = protein_domain.getDomainId().getId();
1165 if ( map.containsKey( id ) ) {
1166 map.put( id, map.get( id ) + 1 );
1176 public static int getNumberOfNodesLackingName( final Phylogeny p, final StringBuilder names ) {
1177 final PhylogenyNodeIterator it = p.iteratorPostorder();
1179 while ( it.hasNext() ) {
1180 final PhylogenyNode n = it.next();
1181 if ( ForesterUtil.isEmpty( n.getName() )
1182 && ( !n.getNodeData().isHasTaxonomy() || ForesterUtil.isEmpty( n.getNodeData().getTaxonomy()
1183 .getScientificName() ) )
1184 && ( !n.getNodeData().isHasTaxonomy() || ForesterUtil.isEmpty( n.getNodeData().getTaxonomy()
1185 .getCommonName() ) ) ) {
1186 if ( n.getParent() != null ) {
1187 names.append( " " );
1188 names.append( n.getParent().getName() );
1190 final List l = n.getAllExternalDescendants();
1191 for( final Object object : l ) {
1192 System.out.println( l.toString() );
1201 * Returns true is Domain domain falls in an uninterrupted stretch of
1202 * covered positions.
1205 * @param covered_positions
1208 public static boolean isEngulfed( final Domain domain, final List<Boolean> covered_positions ) {
1209 for( int i = domain.getFrom(); i <= domain.getTo(); ++i ) {
1210 if ( ( i >= covered_positions.size() ) || ( covered_positions.get( i ) != true ) ) {
1217 public static void preparePhylogeny( final Phylogeny p,
1218 final DomainParsimonyCalculator domain_parsimony,
1219 final String date_time,
1220 final String method,
1222 final String parameters_str ) {
1223 domain_parsimony.decoratePhylogenyWithDomains( p );
1224 final StringBuilder desc = new StringBuilder();
1225 desc.append( "[Method: " + method + "] [Date: " + date_time + "] " );
1226 desc.append( "[Cost: " + domain_parsimony.getCost() + "] " );
1227 desc.append( "[Gains: " + domain_parsimony.getTotalGains() + "] " );
1228 desc.append( "[Losses: " + domain_parsimony.getTotalLosses() + "] " );
1229 desc.append( "[Unchanged: " + domain_parsimony.getTotalUnchanged() + "] " );
1230 desc.append( "[Parameters: " + parameters_str + "]" );
1232 p.setDescription( desc.toString() );
1233 p.setConfidence( new Confidence( domain_parsimony.getCost(), "parsimony" ) );
1234 p.setRerootable( false );
1235 p.setRooted( true );
1239 * species | protein id | n-terminal domain | c-terminal domain | n-terminal domain per domain E-value | c-terminal domain per domain E-value
1243 static public StringBuffer proteinToDomainCombinations( final Protein protein,
1244 final String protein_id,
1245 final String separator ) {
1246 final StringBuffer sb = new StringBuffer();
1247 if ( protein.getSpecies() == null ) {
1248 throw new IllegalArgumentException( "species must not be null" );
1250 if ( ForesterUtil.isEmpty( protein.getSpecies().getSpeciesId() ) ) {
1251 throw new IllegalArgumentException( "species id must not be empty" );
1253 final List<Domain> domains = protein.getProteinDomains();
1254 if ( domains.size() > 1 ) {
1255 final Map<String, Integer> counts = new HashMap<String, Integer>();
1256 for( final Domain domain : domains ) {
1257 final String id = domain.getDomainId().getId();
1258 if ( counts.containsKey( id ) ) {
1259 counts.put( id, counts.get( id ) + 1 );
1262 counts.put( id, 1 );
1265 final Set<String> dcs = new HashSet<String>();
1266 for( int i = 1; i < domains.size(); ++i ) {
1267 for( int j = 0; j < i; ++j ) {
1268 Domain domain_n = domains.get( i );
1269 Domain domain_c = domains.get( j );
1270 if ( domain_n.getFrom() > domain_c.getFrom() ) {
1271 domain_n = domains.get( j );
1272 domain_c = domains.get( i );
1274 final String dc = domain_n.getDomainId().getId() + domain_c.getDomainId().getId();
1275 if ( !dcs.contains( dc ) ) {
1277 sb.append( protein.getSpecies() );
1278 sb.append( separator );
1279 sb.append( protein_id );
1280 sb.append( separator );
1281 sb.append( domain_n.getDomainId().getId() );
1282 sb.append( separator );
1283 sb.append( domain_c.getDomainId().getId() );
1284 sb.append( separator );
1285 sb.append( domain_n.getPerDomainEvalue() );
1286 sb.append( separator );
1287 sb.append( domain_c.getPerDomainEvalue() );
1288 sb.append( separator );
1289 sb.append( counts.get( domain_n.getDomainId().getId() ) );
1290 sb.append( separator );
1291 sb.append( counts.get( domain_c.getDomainId().getId() ) );
1292 sb.append( ForesterUtil.LINE_SEPARATOR );
1297 else if ( domains.size() == 1 ) {
1298 sb.append( protein.getSpecies() );
1299 sb.append( separator );
1300 sb.append( protein_id );
1301 sb.append( separator );
1302 sb.append( domains.get( 0 ).getDomainId().getId() );
1303 sb.append( separator );
1304 sb.append( separator );
1305 sb.append( domains.get( 0 ).getPerDomainEvalue() );
1306 sb.append( separator );
1307 sb.append( separator );
1309 sb.append( separator );
1310 sb.append( ForesterUtil.LINE_SEPARATOR );
1313 sb.append( protein.getSpecies() );
1314 sb.append( separator );
1315 sb.append( protein_id );
1316 sb.append( separator );
1317 sb.append( separator );
1318 sb.append( separator );
1319 sb.append( separator );
1320 sb.append( separator );
1321 sb.append( separator );
1322 sb.append( ForesterUtil.LINE_SEPARATOR );
1329 * Example regarding engulfment: ------------0.1 ----------0.2 --0.3 =>
1330 * domain with 0.3 is ignored
1332 * -----------0.1 ----------0.2 --0.3 => domain with 0.3 is ignored
1335 * ------------0.1 ----------0.3 --0.2 => domains with 0.3 and 0.2 are _not_
1338 * @param max_allowed_overlap
1339 * maximal allowed overlap (inclusive) to be still considered not
1340 * overlapping (zero or negative value to allow any overlap)
1341 * @param remove_engulfed_domains
1342 * to remove domains which are completely engulfed by coverage of
1343 * domains with better support
1347 public static Protein removeOverlappingDomains( final int max_allowed_overlap,
1348 final boolean remove_engulfed_domains,
1349 final Protein protein ) {
1350 final Protein pruned_protein = new BasicProtein( protein.getProteinId().getId(), protein.getSpecies()
1351 .getSpeciesId(), protein.getLength() );
1352 final List<Domain> sorted = SurfacingUtil.sortDomainsWithAscendingConfidenceValues( protein );
1353 final List<Boolean> covered_positions = new ArrayList<Boolean>();
1354 for( final Domain domain : sorted ) {
1355 if ( ( ( max_allowed_overlap < 0 ) || ( SurfacingUtil.calculateOverlap( domain, covered_positions ) <= max_allowed_overlap ) )
1356 && ( !remove_engulfed_domains || !isEngulfed( domain, covered_positions ) ) ) {
1357 final int covered_positions_size = covered_positions.size();
1358 for( int i = covered_positions_size; i < domain.getFrom(); ++i ) {
1359 covered_positions.add( false );
1361 final int new_covered_positions_size = covered_positions.size();
1362 for( int i = domain.getFrom(); i <= domain.getTo(); ++i ) {
1363 if ( i < new_covered_positions_size ) {
1364 covered_positions.set( i, true );
1367 covered_positions.add( true );
1370 pruned_protein.addProteinDomain( domain );
1373 return pruned_protein;
1376 public static List<Domain> sortDomainsWithAscendingConfidenceValues( final Protein protein ) {
1377 final List<Domain> domains = new ArrayList<Domain>();
1378 for( final Domain d : protein.getProteinDomains() ) {
1381 Collections.sort( domains, SurfacingUtil.ASCENDING_CONFIDENCE_VALUE_ORDER );
1385 private static List<String> splitDomainCombination( final String dc ) {
1386 final String[] s = dc.split( "=" );
1387 if ( s.length != 2 ) {
1388 ForesterUtil.printErrorMessage( surfacing.PRG_NAME, "Stringyfied domain combination has illegal format: "
1392 final List<String> l = new ArrayList<String>( 2 );
1398 public static void writeAllDomainsChangedOnAllSubtrees( final Phylogeny p,
1399 final boolean get_gains,
1400 final String outdir,
1401 final String suffix_for_filename ) throws IOException {
1402 CharacterStateMatrix.GainLossStates state = CharacterStateMatrix.GainLossStates.GAIN;
1404 state = CharacterStateMatrix.GainLossStates.LOSS;
1406 final File base_dir = createBaseDirForPerNodeDomainFiles( surfacing.BASE_DIRECTORY_PER_SUBTREE_DOMAIN_GAIN_LOSS_FILES,
1410 for( final PhylogenyNodeIterator it = p.iteratorPostorder(); it.hasNext(); ) {
1411 final PhylogenyNode node = it.next();
1412 if ( !node.isExternal() ) {
1413 final SortedSet<String> domains = collectAllDomainsChangedOnSubtree( node, get_gains );
1414 if ( domains.size() > 0 ) {
1415 final Writer writer = ForesterUtil.createBufferedWriter( base_dir + ForesterUtil.FILE_SEPARATOR
1416 + node.getName() + suffix_for_filename );
1417 for( final String domain : domains ) {
1418 writer.write( domain );
1419 writer.write( ForesterUtil.LINE_SEPARATOR );
1427 private static void writeAllEncounteredPfamsToFile( final Map<DomainId, List<GoId>> domain_id_to_go_ids_map,
1428 final Map<GoId, GoTerm> go_id_to_term_map,
1429 final String outfile_name,
1430 final SortedSet<String> all_pfams_encountered ) {
1431 final File all_pfams_encountered_file = new File( outfile_name + surfacing.ALL_PFAMS_ENCOUNTERED_SUFFIX );
1432 final File all_pfams_encountered_with_go_annotation_file = new File( outfile_name
1433 + surfacing.ALL_PFAMS_ENCOUNTERED_WITH_GO_ANNOTATION_SUFFIX );
1434 final File encountered_pfams_summary_file = new File( outfile_name + surfacing.ENCOUNTERED_PFAMS_SUMMARY_SUFFIX );
1435 int biological_process_counter = 0;
1436 int cellular_component_counter = 0;
1437 int molecular_function_counter = 0;
1438 int pfams_with_mappings_counter = 0;
1439 int pfams_without_mappings_counter = 0;
1440 int pfams_without_mappings_to_bp_or_mf_counter = 0;
1441 int pfams_with_mappings_to_bp_or_mf_counter = 0;
1443 final Writer all_pfams_encountered_writer = new BufferedWriter( new FileWriter( all_pfams_encountered_file ) );
1444 final Writer all_pfams_encountered_with_go_annotation_writer = new BufferedWriter( new FileWriter( all_pfams_encountered_with_go_annotation_file ) );
1445 final Writer summary_writer = new BufferedWriter( new FileWriter( encountered_pfams_summary_file ) );
1446 summary_writer.write( "# Pfam to GO mapping summary" );
1447 summary_writer.write( ForesterUtil.LINE_SEPARATOR );
1448 summary_writer.write( "# Actual summary is at the end of this file." );
1449 summary_writer.write( ForesterUtil.LINE_SEPARATOR );
1450 summary_writer.write( "# Encountered Pfams without a GO mapping:" );
1451 summary_writer.write( ForesterUtil.LINE_SEPARATOR );
1452 for( final String pfam : all_pfams_encountered ) {
1453 all_pfams_encountered_writer.write( pfam );
1454 all_pfams_encountered_writer.write( ForesterUtil.LINE_SEPARATOR );
1455 final DomainId domain_id = new DomainId( pfam );
1456 if ( domain_id_to_go_ids_map.containsKey( domain_id ) ) {
1457 ++pfams_with_mappings_counter;
1458 all_pfams_encountered_with_go_annotation_writer.write( pfam );
1459 all_pfams_encountered_with_go_annotation_writer.write( ForesterUtil.LINE_SEPARATOR );
1460 final List<GoId> go_ids = domain_id_to_go_ids_map.get( domain_id );
1461 boolean maps_to_bp = false;
1462 boolean maps_to_cc = false;
1463 boolean maps_to_mf = false;
1464 for( final GoId go_id : go_ids ) {
1465 final GoTerm go_term = go_id_to_term_map.get( go_id );
1466 if ( go_term.getGoNameSpace().isBiologicalProcess() ) {
1469 else if ( go_term.getGoNameSpace().isCellularComponent() ) {
1472 else if ( go_term.getGoNameSpace().isMolecularFunction() ) {
1477 ++biological_process_counter;
1480 ++cellular_component_counter;
1483 ++molecular_function_counter;
1485 if ( maps_to_bp || maps_to_mf ) {
1486 ++pfams_with_mappings_to_bp_or_mf_counter;
1489 ++pfams_without_mappings_to_bp_or_mf_counter;
1493 ++pfams_without_mappings_to_bp_or_mf_counter;
1494 ++pfams_without_mappings_counter;
1495 summary_writer.write( pfam );
1496 summary_writer.write( ForesterUtil.LINE_SEPARATOR );
1499 all_pfams_encountered_writer.close();
1500 all_pfams_encountered_with_go_annotation_writer.close();
1501 ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote all [" + all_pfams_encountered.size()
1502 + "] encountered Pfams to: \"" + all_pfams_encountered_file + "\"" );
1503 ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote all [" + pfams_with_mappings_counter
1504 + "] encountered Pfams with GO mappings to: \"" + all_pfams_encountered_with_go_annotation_file
1506 ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote summary (including all ["
1507 + pfams_without_mappings_counter + "] encountered Pfams without GO mappings) to: \""
1508 + encountered_pfams_summary_file + "\"" );
1509 ForesterUtil.programMessage( surfacing.PRG_NAME, "Sum of Pfams encountered : "
1510 + all_pfams_encountered.size() );
1511 ForesterUtil.programMessage( surfacing.PRG_NAME, "Pfams without a mapping : "
1512 + pfams_without_mappings_counter + " ["
1513 + ( 100 * pfams_without_mappings_counter / all_pfams_encountered.size() ) + "%]" );
1514 ForesterUtil.programMessage( surfacing.PRG_NAME, "Pfams without mapping to proc. or func. : "
1515 + pfams_without_mappings_to_bp_or_mf_counter + " ["
1516 + ( 100 * pfams_without_mappings_to_bp_or_mf_counter / all_pfams_encountered.size() ) + "%]" );
1517 ForesterUtil.programMessage( surfacing.PRG_NAME,
1518 "Pfams with a mapping : " + pfams_with_mappings_counter
1520 + ( 100 * pfams_with_mappings_counter / all_pfams_encountered.size() )
1522 ForesterUtil.programMessage( surfacing.PRG_NAME, "Pfams with a mapping to proc. or func. : "
1523 + pfams_with_mappings_to_bp_or_mf_counter + " ["
1524 + ( 100 * pfams_with_mappings_to_bp_or_mf_counter / all_pfams_encountered.size() ) + "%]" );
1525 ForesterUtil.programMessage( surfacing.PRG_NAME,
1526 "Pfams with mapping to biological process: " + biological_process_counter
1528 + ( 100 * biological_process_counter / all_pfams_encountered.size() )
1530 ForesterUtil.programMessage( surfacing.PRG_NAME,
1531 "Pfams with mapping to molecular function: " + molecular_function_counter
1533 + ( 100 * molecular_function_counter / all_pfams_encountered.size() )
1535 ForesterUtil.programMessage( surfacing.PRG_NAME,
1536 "Pfams with mapping to cellular component: " + cellular_component_counter
1538 + ( 100 * cellular_component_counter / all_pfams_encountered.size() )
1540 summary_writer.write( ForesterUtil.LINE_SEPARATOR );
1541 summary_writer.write( "# Sum of Pfams encountered : " + all_pfams_encountered.size() );
1542 summary_writer.write( ForesterUtil.LINE_SEPARATOR );
1543 summary_writer.write( "# Pfams without a mapping : " + pfams_without_mappings_counter
1544 + " [" + ( 100 * pfams_without_mappings_counter / all_pfams_encountered.size() ) + "%]" );
1545 summary_writer.write( ForesterUtil.LINE_SEPARATOR );
1546 summary_writer.write( "# Pfams without mapping to proc. or func. : "
1547 + pfams_without_mappings_to_bp_or_mf_counter + " ["
1548 + ( 100 * pfams_without_mappings_to_bp_or_mf_counter / all_pfams_encountered.size() ) + "%]" );
1549 summary_writer.write( ForesterUtil.LINE_SEPARATOR );
1550 summary_writer.write( "# Pfams with a mapping : " + pfams_with_mappings_counter + " ["
1551 + ( 100 * pfams_with_mappings_counter / all_pfams_encountered.size() ) + "%]" );
1552 summary_writer.write( ForesterUtil.LINE_SEPARATOR );
1553 summary_writer.write( "# Pfams with a mapping to proc. or func. : "
1554 + pfams_with_mappings_to_bp_or_mf_counter + " ["
1555 + ( 100 * pfams_with_mappings_to_bp_or_mf_counter / all_pfams_encountered.size() ) + "%]" );
1556 summary_writer.write( ForesterUtil.LINE_SEPARATOR );
1557 summary_writer.write( "# Pfams with mapping to biological process: " + biological_process_counter + " ["
1558 + ( 100 * biological_process_counter / all_pfams_encountered.size() ) + "%]" );
1559 summary_writer.write( ForesterUtil.LINE_SEPARATOR );
1560 summary_writer.write( "# Pfams with mapping to molecular function: " + molecular_function_counter + " ["
1561 + ( 100 * molecular_function_counter / all_pfams_encountered.size() ) + "%]" );
1562 summary_writer.write( ForesterUtil.LINE_SEPARATOR );
1563 summary_writer.write( "# Pfams with mapping to cellular component: " + cellular_component_counter + " ["
1564 + ( 100 * cellular_component_counter / all_pfams_encountered.size() ) + "%]" );
1565 summary_writer.write( ForesterUtil.LINE_SEPARATOR );
1566 summary_writer.close();
1568 catch ( final IOException e ) {
1569 ForesterUtil.printWarningMessage( surfacing.PRG_NAME, "Failure to write: " + e );
1573 public static void writeBinaryDomainCombinationsFileForGraphAnalysis( final String[][] input_file_properties,
1574 final File output_dir,
1575 final GenomeWideCombinableDomains gwcd,
1577 final GenomeWideCombinableDomainsSortOrder dc_sort_order ) {
1578 File dc_outfile_dot = new File( input_file_properties[ i ][ 0 ]
1579 + surfacing.DOMAIN_COMBINITONS_OUTPUTFILE_SUFFIX_FOR_GRAPH_ANALYSIS );
1580 if ( output_dir != null ) {
1581 dc_outfile_dot = new File( output_dir + ForesterUtil.FILE_SEPARATOR + dc_outfile_dot );
1583 checkForOutputFileWriteability( dc_outfile_dot );
1584 final SortedSet<BinaryDomainCombination> binary_combinations = createSetOfAllBinaryDomainCombinationsPerGenome( gwcd );
1586 final BufferedWriter out_dot = new BufferedWriter( new FileWriter( dc_outfile_dot ) );
1587 for( final BinaryDomainCombination bdc : binary_combinations ) {
1588 out_dot.write( bdc.toGraphDescribingLanguage( BinaryDomainCombination.OutputFormat.DOT, null, null )
1590 out_dot.write( SurfacingConstants.NL );
1594 catch ( final IOException e ) {
1595 ForesterUtil.fatalError( surfacing.PRG_NAME, e.getMessage() );
1597 ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote binary domain combination for \""
1598 + input_file_properties[ i ][ 0 ] + "\" (" + input_file_properties[ i ][ 1 ] + ", "
1599 + input_file_properties[ i ][ 2 ] + ") to: \"" + dc_outfile_dot + "\"" );
1602 public static void writeBinaryStatesMatrixAsListToFile( final CharacterStateMatrix<CharacterStateMatrix.GainLossStates> matrix,
1603 final CharacterStateMatrix.GainLossStates state,
1604 final String filename,
1605 final String indentifier_characters_separator,
1606 final String character_separator,
1607 final Map<String, String> descriptions ) {
1608 final File outfile = new File( filename );
1609 checkForOutputFileWriteability( outfile );
1610 final SortedSet<String> sorted_ids = new TreeSet<String>();
1611 for( int i = 0; i < matrix.getNumberOfIdentifiers(); ++i ) {
1612 sorted_ids.add( matrix.getIdentifier( i ) );
1615 final BufferedWriter out = new BufferedWriter( new FileWriter( outfile ) );
1616 for( final String id : sorted_ids ) {
1617 out.write( indentifier_characters_separator );
1618 out.write( "#" + id );
1619 out.write( indentifier_characters_separator );
1620 for( int c = 0; c < matrix.getNumberOfCharacters(); ++c ) {
1622 // using null to indicate either UNCHANGED_PRESENT or GAIN.
1623 if ( ( matrix.getState( id, c ) == state )
1624 || ( ( state == null ) && ( ( matrix.getState( id, c ) == CharacterStateMatrix.GainLossStates.GAIN ) || ( matrix
1625 .getState( id, c ) == CharacterStateMatrix.GainLossStates.UNCHANGED_PRESENT ) ) ) ) {
1626 out.write( matrix.getCharacter( c ) );
1627 if ( ( descriptions != null ) && !descriptions.isEmpty()
1628 && descriptions.containsKey( matrix.getCharacter( c ) ) ) {
1630 out.write( descriptions.get( matrix.getCharacter( c ) ) );
1632 out.write( character_separator );
1639 catch ( final IOException e ) {
1640 ForesterUtil.fatalError( surfacing.PRG_NAME, e.getMessage() );
1642 ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote characters list: \"" + filename + "\"" );
1645 public static void writeBinaryStatesMatrixAsListToFileForBinaryCombinationsForGraphAnalysis( final CharacterStateMatrix<CharacterStateMatrix.GainLossStates> matrix,
1646 final CharacterStateMatrix.GainLossStates state,
1647 final String filename,
1648 final String indentifier_characters_separator,
1649 final String character_separator,
1650 final BinaryDomainCombination.OutputFormat bc_output_format ) {
1651 final File outfile = new File( filename );
1652 checkForOutputFileWriteability( outfile );
1653 final SortedSet<String> sorted_ids = new TreeSet<String>();
1654 for( int i = 0; i < matrix.getNumberOfIdentifiers(); ++i ) {
1655 sorted_ids.add( matrix.getIdentifier( i ) );
1658 final BufferedWriter out = new BufferedWriter( new FileWriter( outfile ) );
1659 for( final String id : sorted_ids ) {
1660 out.write( indentifier_characters_separator );
1661 out.write( "#" + id );
1662 out.write( indentifier_characters_separator );
1663 for( int c = 0; c < matrix.getNumberOfCharacters(); ++c ) {
1665 // using null to indicate either UNCHANGED_PRESENT or GAIN.
1666 if ( ( matrix.getState( id, c ) == state )
1667 || ( ( state == null ) && ( ( matrix.getState( id, c ) == CharacterStateMatrix.GainLossStates.GAIN ) || ( matrix
1668 .getState( id, c ) == CharacterStateMatrix.GainLossStates.UNCHANGED_PRESENT ) ) ) ) {
1669 BinaryDomainCombination bdc = null;
1671 bdc = BasicBinaryDomainCombination.createInstance( matrix.getCharacter( c ) );
1673 catch ( final Exception e ) {
1674 ForesterUtil.fatalError( surfacing.PRG_NAME, e.getLocalizedMessage() );
1676 out.write( bdc.toGraphDescribingLanguage( bc_output_format, null, null ).toString() );
1677 out.write( character_separator );
1684 catch ( final IOException e ) {
1685 ForesterUtil.fatalError( surfacing.PRG_NAME, e.getMessage() );
1687 ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote characters list: \"" + filename + "\"" );
1690 public static void writeBinaryStatesMatrixToList( final Map<DomainId, List<GoId>> domain_id_to_go_ids_map,
1691 final Map<GoId, GoTerm> go_id_to_term_map,
1692 final GoNameSpace go_namespace_limit,
1693 final boolean domain_combinations,
1694 final CharacterStateMatrix<CharacterStateMatrix.GainLossStates> matrix,
1695 final CharacterStateMatrix.GainLossStates state,
1696 final String filename,
1697 final String indentifier_characters_separator,
1698 final String character_separator,
1699 final String title_for_html,
1700 final String prefix_for_html,
1701 final Map<DomainId, Set<String>>[] domain_id_to_secondary_features_maps,
1702 final SortedSet<String> all_pfams_encountered,
1703 final SortedSet<String> pfams_gained_or_lost,
1704 final String suffix_for_per_node_events_file ) {
1705 if ( ( go_namespace_limit != null ) && ( ( go_id_to_term_map == null ) || ( go_id_to_term_map.size() < 1 ) ) ) {
1706 throw new IllegalArgumentException( "attempt to use GO namespace limit without a GO-id to term map" );
1708 else if ( ( ( domain_id_to_go_ids_map == null ) || ( domain_id_to_go_ids_map.size() < 1 ) ) ) {
1709 throw new IllegalArgumentException( "attempt to output detailed HTML without a Pfam to GO map" );
1711 else if ( ( ( go_id_to_term_map == null ) || ( go_id_to_term_map.size() < 1 ) ) ) {
1712 throw new IllegalArgumentException( "attempt to output detailed HTML without a GO-id to term map" );
1714 final File outfile = new File( filename );
1715 checkForOutputFileWriteability( outfile );
1716 final SortedSet<String> sorted_ids = new TreeSet<String>();
1717 for( int i = 0; i < matrix.getNumberOfIdentifiers(); ++i ) {
1718 sorted_ids.add( matrix.getIdentifier( i ) );
1721 final Writer out = new BufferedWriter( new FileWriter( outfile ) );
1722 final File per_node_go_mapped_domain_gain_loss_files_base_dir = createBaseDirForPerNodeDomainFiles( surfacing.BASE_DIRECTORY_PER_NODE_DOMAIN_GAIN_LOSS_FILES,
1723 domain_combinations,
1726 Writer per_node_go_mapped_domain_gain_loss_outfile_writer = null;
1727 File per_node_go_mapped_domain_gain_loss_outfile = null;
1728 int per_node_counter = 0;
1729 out.write( "<html>" );
1730 out.write( SurfacingConstants.NL );
1731 addHtmlHead( out, title_for_html );
1732 out.write( SurfacingConstants.NL );
1733 out.write( "<body>" );
1734 out.write( SurfacingConstants.NL );
1735 out.write( "<h1>" );
1736 out.write( SurfacingConstants.NL );
1737 out.write( title_for_html );
1738 out.write( SurfacingConstants.NL );
1739 out.write( "</h1>" );
1740 out.write( SurfacingConstants.NL );
1741 out.write( "<table>" );
1742 out.write( SurfacingConstants.NL );
1743 for( final String id : sorted_ids ) {
1744 final Matcher matcher = PATTERN_SP_STYLE_TAXONOMY.matcher( id );
1745 if ( matcher.matches() ) {
1748 out.write( "<tr>" );
1749 out.write( "<td>" );
1750 out.write( "<a href=\"#" + id + "\">" + id + "</a>" );
1751 out.write( "</td>" );
1752 out.write( "</tr>" );
1753 out.write( SurfacingConstants.NL );
1755 out.write( "</table>" );
1756 out.write( SurfacingConstants.NL );
1757 for( final String id : sorted_ids ) {
1758 final Matcher matcher = PATTERN_SP_STYLE_TAXONOMY.matcher( id );
1759 if ( matcher.matches() ) {
1762 out.write( SurfacingConstants.NL );
1763 out.write( "<h2>" );
1764 out.write( "<a name=\"" + id + "\">" + id + "</a>" );
1765 writeTaxonomyLinks( out, id );
1766 out.write( "</h2>" );
1767 out.write( SurfacingConstants.NL );
1768 out.write( "<table>" );
1769 out.write( SurfacingConstants.NL );
1770 out.write( "<tr>" );
1771 out.write( "<td><b>" );
1772 out.write( "Pfam domain(s)" );
1773 out.write( "</b></td><td><b>" );
1774 out.write( "GO term acc" );
1775 out.write( "</b></td><td><b>" );
1776 out.write( "GO term" );
1777 out.write( "</b></td><td><b>" );
1778 out.write( "GO namespace" );
1779 out.write( "</b></td>" );
1780 out.write( "</tr>" );
1781 out.write( SurfacingConstants.NL );
1782 out.write( "</tr>" );
1783 out.write( SurfacingConstants.NL );
1784 per_node_counter = 0;
1785 if ( matrix.getNumberOfCharacters() > 0 ) {
1786 per_node_go_mapped_domain_gain_loss_outfile = new File( per_node_go_mapped_domain_gain_loss_files_base_dir
1787 + ForesterUtil.FILE_SEPARATOR + id + suffix_for_per_node_events_file );
1788 SurfacingUtil.checkForOutputFileWriteability( per_node_go_mapped_domain_gain_loss_outfile );
1789 per_node_go_mapped_domain_gain_loss_outfile_writer = ForesterUtil
1790 .createBufferedWriter( per_node_go_mapped_domain_gain_loss_outfile );
1793 per_node_go_mapped_domain_gain_loss_outfile = null;
1794 per_node_go_mapped_domain_gain_loss_outfile_writer = null;
1796 for( int c = 0; c < matrix.getNumberOfCharacters(); ++c ) {
1798 // using null to indicate either UNCHANGED_PRESENT or GAIN.
1799 if ( ( matrix.getState( id, c ) == state )
1800 || ( ( state == null ) && ( ( matrix.getState( id, c ) == CharacterStateMatrix.GainLossStates.UNCHANGED_PRESENT ) || ( matrix
1801 .getState( id, c ) == CharacterStateMatrix.GainLossStates.GAIN ) ) ) ) {
1802 final String character = matrix.getCharacter( c );
1803 String domain_0 = "";
1804 String domain_1 = "";
1805 if ( character.indexOf( BinaryDomainCombination.SEPARATOR ) > 0 ) {
1806 final String[] s = character.split( BinaryDomainCombination.SEPARATOR );
1807 if ( s.length != 2 ) {
1808 throw new AssertionError( "this should not have happened: unexpected format for domain combination: ["
1809 + character + "]" );
1815 domain_0 = character;
1817 writeDomainData( domain_id_to_go_ids_map,
1824 character_separator,
1825 domain_id_to_secondary_features_maps,
1827 all_pfams_encountered.add( domain_0 );
1828 if ( pfams_gained_or_lost != null ) {
1829 pfams_gained_or_lost.add( domain_0 );
1831 if ( !ForesterUtil.isEmpty( domain_1 ) ) {
1832 all_pfams_encountered.add( domain_1 );
1833 if ( pfams_gained_or_lost != null ) {
1834 pfams_gained_or_lost.add( domain_1 );
1837 if ( per_node_go_mapped_domain_gain_loss_outfile_writer != null ) {
1838 writeDomainsToIndividualFilePerTreeNode( per_node_go_mapped_domain_gain_loss_outfile_writer,
1845 if ( per_node_go_mapped_domain_gain_loss_outfile_writer != null ) {
1846 per_node_go_mapped_domain_gain_loss_outfile_writer.close();
1847 if ( per_node_counter < 1 ) {
1848 per_node_go_mapped_domain_gain_loss_outfile.delete();
1850 per_node_counter = 0;
1852 out.write( "</table>" );
1853 out.write( SurfacingConstants.NL );
1854 out.write( "<hr>" );
1855 out.write( SurfacingConstants.NL );
1856 } // for( final String id : sorted_ids ) {
1857 out.write( "</body>" );
1858 out.write( SurfacingConstants.NL );
1859 out.write( "</html>" );
1860 out.write( SurfacingConstants.NL );
1864 catch ( final IOException e ) {
1865 ForesterUtil.fatalError( surfacing.PRG_NAME, e.getMessage() );
1867 ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote characters detailed HTML list: \"" + filename + "\"" );
1870 public static void writeBinaryStatesMatrixToListORIGIG( final Map<DomainId, List<GoId>> domain_id_to_go_ids_map,
1871 final Map<GoId, GoTerm> go_id_to_term_map,
1872 final GoNameSpace go_namespace_limit,
1873 final boolean domain_combinations,
1874 final CharacterStateMatrix<CharacterStateMatrix.GainLossStates> matrix,
1875 final CharacterStateMatrix.GainLossStates state,
1876 final String filename,
1877 final String indentifier_characters_separator,
1878 final String character_separator,
1879 final String title_for_html,
1880 final String prefix_for_html,
1881 final Map<DomainId, Set<String>>[] domain_id_to_secondary_features_maps,
1882 final SortedSet<String> all_pfams_encountered,
1883 final SortedSet<String> pfams_gained_or_lost,
1884 final String suffix_for_per_node_events_file ) {
1885 if ( ( go_namespace_limit != null ) && ( ( go_id_to_term_map == null ) || ( go_id_to_term_map.size() < 1 ) ) ) {
1886 throw new IllegalArgumentException( "attempt to use GO namespace limit without a GO-id to term map" );
1888 else if ( ( ( domain_id_to_go_ids_map == null ) || ( domain_id_to_go_ids_map.size() < 1 ) ) ) {
1889 throw new IllegalArgumentException( "attempt to output detailed HTML without a Pfam to GO map" );
1891 else if ( ( ( go_id_to_term_map == null ) || ( go_id_to_term_map.size() < 1 ) ) ) {
1892 throw new IllegalArgumentException( "attempt to output detailed HTML without a GO-id to term map" );
1894 final File outfile = new File( filename );
1895 checkForOutputFileWriteability( outfile );
1896 final SortedSet<String> sorted_ids = new TreeSet<String>();
1897 for( int i = 0; i < matrix.getNumberOfIdentifiers(); ++i ) {
1898 sorted_ids.add( matrix.getIdentifier( i ) );
1901 final Writer out = new BufferedWriter( new FileWriter( outfile ) );
1902 final File per_node_go_mapped_domain_gain_loss_files_base_dir = createBaseDirForPerNodeDomainFiles( surfacing.BASE_DIRECTORY_PER_NODE_DOMAIN_GAIN_LOSS_FILES,
1903 domain_combinations,
1906 Writer per_node_go_mapped_domain_gain_loss_outfile_writer = null;
1907 File per_node_go_mapped_domain_gain_loss_outfile = null;
1908 int per_node_counter = 0;
1909 out.write( "<html>" );
1910 out.write( SurfacingConstants.NL );
1911 addHtmlHead( out, title_for_html );
1912 out.write( SurfacingConstants.NL );
1913 out.write( "<body>" );
1914 out.write( SurfacingConstants.NL );
1915 out.write( "<h1>" );
1916 out.write( SurfacingConstants.NL );
1917 out.write( title_for_html );
1918 out.write( SurfacingConstants.NL );
1919 out.write( "</h1>" );
1920 out.write( SurfacingConstants.NL );
1921 out.write( "<table>" );
1922 out.write( SurfacingConstants.NL );
1923 for( final String id : sorted_ids ) {
1924 out.write( "<tr>" );
1925 out.write( "<td>" );
1926 out.write( "<a href=\"#" + id + "\">" + id + "</a>" );
1927 writeTaxonomyLinks( out, id );
1928 out.write( "</td>" );
1929 out.write( "</tr>" );
1930 out.write( SurfacingConstants.NL );
1932 out.write( "</table>" );
1933 out.write( SurfacingConstants.NL );
1934 for( final String id : sorted_ids ) {
1935 out.write( SurfacingConstants.NL );
1936 out.write( "<h2>" );
1937 out.write( "<a name=\"" + id + "\">" + id + "</a>" );
1938 writeTaxonomyLinks( out, id );
1939 out.write( "</h2>" );
1940 out.write( SurfacingConstants.NL );
1941 out.write( "<table>" );
1942 out.write( SurfacingConstants.NL );
1943 out.write( "<tr>" );
1944 out.write( "<td><b>" );
1945 out.write( "Pfam domain(s)" );
1946 out.write( "</b></td><td><b>" );
1947 out.write( "GO term acc" );
1948 out.write( "</b></td><td><b>" );
1949 out.write( "GO term" );
1950 out.write( "</b></td><td><b>" );
1951 out.write( "Penultimate GO term" );
1952 out.write( "</b></td><td><b>" );
1953 out.write( "GO namespace" );
1954 out.write( "</b></td>" );
1955 out.write( "</tr>" );
1956 out.write( SurfacingConstants.NL );
1957 out.write( "</tr>" );
1958 out.write( SurfacingConstants.NL );
1959 per_node_counter = 0;
1960 if ( matrix.getNumberOfCharacters() > 0 ) {
1961 per_node_go_mapped_domain_gain_loss_outfile = new File( per_node_go_mapped_domain_gain_loss_files_base_dir
1962 + ForesterUtil.FILE_SEPARATOR + id + suffix_for_per_node_events_file );
1963 SurfacingUtil.checkForOutputFileWriteability( per_node_go_mapped_domain_gain_loss_outfile );
1964 per_node_go_mapped_domain_gain_loss_outfile_writer = ForesterUtil
1965 .createBufferedWriter( per_node_go_mapped_domain_gain_loss_outfile );
1968 per_node_go_mapped_domain_gain_loss_outfile = null;
1969 per_node_go_mapped_domain_gain_loss_outfile_writer = null;
1971 for( int c = 0; c < matrix.getNumberOfCharacters(); ++c ) {
1973 // using null to indicate either UNCHANGED_PRESENT or GAIN.
1974 if ( ( matrix.getState( id, c ) == state )
1975 || ( ( state == null ) && ( ( matrix.getState( id, c ) == CharacterStateMatrix.GainLossStates.UNCHANGED_PRESENT ) || ( matrix
1976 .getState( id, c ) == CharacterStateMatrix.GainLossStates.GAIN ) ) ) ) {
1977 final String character = matrix.getCharacter( c );
1978 String domain_0 = "";
1979 String domain_1 = "";
1980 if ( character.indexOf( BinaryDomainCombination.SEPARATOR ) > 0 ) {
1981 final String[] s = character.split( BinaryDomainCombination.SEPARATOR );
1982 if ( s.length != 2 ) {
1983 throw new AssertionError( "this should not have happened: unexpected format for domain combination: ["
1984 + character + "]" );
1990 domain_0 = character;
1992 writeDomainData( domain_id_to_go_ids_map,
1999 character_separator,
2000 domain_id_to_secondary_features_maps,
2002 all_pfams_encountered.add( domain_0 );
2003 if ( pfams_gained_or_lost != null ) {
2004 pfams_gained_or_lost.add( domain_0 );
2006 if ( !ForesterUtil.isEmpty( domain_1 ) ) {
2007 all_pfams_encountered.add( domain_1 );
2008 if ( pfams_gained_or_lost != null ) {
2009 pfams_gained_or_lost.add( domain_1 );
2012 if ( per_node_go_mapped_domain_gain_loss_outfile_writer != null ) {
2013 writeDomainsToIndividualFilePerTreeNode( per_node_go_mapped_domain_gain_loss_outfile_writer,
2020 if ( per_node_go_mapped_domain_gain_loss_outfile_writer != null ) {
2021 per_node_go_mapped_domain_gain_loss_outfile_writer.close();
2022 if ( per_node_counter < 1 ) {
2023 per_node_go_mapped_domain_gain_loss_outfile.delete();
2025 per_node_counter = 0;
2027 out.write( "</table>" );
2028 out.write( SurfacingConstants.NL );
2029 out.write( "<hr>" );
2030 out.write( SurfacingConstants.NL );
2031 } // for( final String id : sorted_ids ) {
2032 out.write( "</body>" );
2033 out.write( SurfacingConstants.NL );
2034 out.write( "</html>" );
2035 out.write( SurfacingConstants.NL );
2039 catch ( final IOException e ) {
2040 ForesterUtil.fatalError( surfacing.PRG_NAME, e.getMessage() );
2042 ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote characters detailed HTML list: \"" + filename + "\"" );
2045 public static void writeDomainCombinationsCountsFile( final String[][] input_file_properties,
2046 final File output_dir,
2047 final Writer per_genome_domain_promiscuity_statistics_writer,
2048 final GenomeWideCombinableDomains gwcd,
2050 final GenomeWideCombinableDomains.GenomeWideCombinableDomainsSortOrder dc_sort_order ) {
2051 File dc_outfile = new File( input_file_properties[ i ][ 0 ]
2052 + surfacing.DOMAIN_COMBINITON_COUNTS_OUTPUTFILE_SUFFIX );
2053 if ( output_dir != null ) {
2054 dc_outfile = new File( output_dir + ForesterUtil.FILE_SEPARATOR + dc_outfile );
2056 checkForOutputFileWriteability( dc_outfile );
2058 final BufferedWriter out = new BufferedWriter( new FileWriter( dc_outfile ) );
2059 out.write( gwcd.toStringBuilder( dc_sort_order ).toString() );
2062 catch ( final IOException e ) {
2063 ForesterUtil.fatalError( surfacing.PRG_NAME, e.getMessage() );
2065 final DescriptiveStatistics stats = gwcd.getPerGenomeDomainPromiscuityStatistics();
2067 per_genome_domain_promiscuity_statistics_writer.write( input_file_properties[ i ][ 0 ] + "\t" );
2068 per_genome_domain_promiscuity_statistics_writer.write( FORMATTER_3.format( stats.arithmeticMean() ) + "\t" );
2069 if ( stats.getN() < 2 ) {
2070 per_genome_domain_promiscuity_statistics_writer.write( "n/a" + "\t" );
2073 per_genome_domain_promiscuity_statistics_writer.write( FORMATTER_3.format( stats
2074 .sampleStandardDeviation() ) + "\t" );
2076 per_genome_domain_promiscuity_statistics_writer.write( FORMATTER_3.format( stats.median() ) + "\t" );
2077 per_genome_domain_promiscuity_statistics_writer.write( ( int ) stats.getMin() + "\t" );
2078 per_genome_domain_promiscuity_statistics_writer.write( ( int ) stats.getMax() + "\t" );
2079 per_genome_domain_promiscuity_statistics_writer.write( stats.getN() + "\t" );
2080 final SortedSet<DomainId> mpds = gwcd.getMostPromiscuosDomain();
2081 for( final DomainId mpd : mpds ) {
2082 per_genome_domain_promiscuity_statistics_writer.write( mpd.getId() + " " );
2084 per_genome_domain_promiscuity_statistics_writer.write( ForesterUtil.LINE_SEPARATOR );
2086 catch ( final IOException e ) {
2087 ForesterUtil.fatalError( surfacing.PRG_NAME, e.getMessage() );
2089 if ( input_file_properties[ i ].length == 3 ) {
2090 ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote domain combination counts for \""
2091 + input_file_properties[ i ][ 0 ] + "\" (" + input_file_properties[ i ][ 1 ] + ", "
2092 + input_file_properties[ i ][ 2 ] + ") to: \"" + dc_outfile + "\"" );
2095 ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote domain combination counts for \""
2096 + input_file_properties[ i ][ 0 ] + "\" (" + input_file_properties[ i ][ 1 ] + ") to: \""
2097 + dc_outfile + "\"" );
2101 private static void writeDomainData( final Map<DomainId, List<GoId>> domain_id_to_go_ids_map,
2102 final Map<GoId, GoTerm> go_id_to_term_map,
2103 final GoNameSpace go_namespace_limit,
2105 final String domain_0,
2106 final String domain_1,
2107 final String prefix_for_html,
2108 final String character_separator_for_non_html_output,
2109 final Map<DomainId, Set<String>>[] domain_id_to_secondary_features_maps,
2110 final Set<GoId> all_go_ids ) throws IOException {
2111 boolean any_go_annotation_present = false;
2112 boolean first_has_no_go = false;
2113 int domain_count = 2; // To distinguish between domains and binary domain combinations.
2114 if ( ForesterUtil.isEmpty( domain_1 ) ) {
2117 // The following has a difficult to understand logic.
2118 for( int d = 0; d < domain_count; ++d ) {
2119 List<GoId> go_ids = null;
2120 boolean go_annotation_present = false;
2122 final DomainId domain_id = new DomainId( domain_0 );
2123 if ( domain_id_to_go_ids_map.containsKey( domain_id ) ) {
2124 go_annotation_present = true;
2125 any_go_annotation_present = true;
2126 go_ids = domain_id_to_go_ids_map.get( domain_id );
2129 first_has_no_go = true;
2133 final DomainId domain_id = new DomainId( domain_1 );
2134 if ( domain_id_to_go_ids_map.containsKey( domain_id ) ) {
2135 go_annotation_present = true;
2136 any_go_annotation_present = true;
2137 go_ids = domain_id_to_go_ids_map.get( domain_id );
2140 if ( go_annotation_present ) {
2141 boolean first = ( ( d == 0 ) || ( ( d == 1 ) && first_has_no_go ) );
2142 for( final GoId go_id : go_ids ) {
2143 out.write( "<tr>" );
2146 writeDomainIdsToHtml( out,
2150 domain_id_to_secondary_features_maps );
2153 out.write( "<td></td>" );
2155 if ( !go_id_to_term_map.containsKey( go_id ) ) {
2156 throw new IllegalArgumentException( "GO-id [" + go_id + "] not found in GO-id to GO-term map" );
2158 final GoTerm go_term = go_id_to_term_map.get( go_id );
2159 if ( ( go_namespace_limit == null ) || go_namespace_limit.equals( go_term.getGoNameSpace() ) ) {
2160 // final String top = GoUtils.getPenultimateGoTerm( go_term, go_id_to_term_map ).getName();
2161 final String go_id_str = go_id.getId();
2162 out.write( "<td>" );
2163 out.write( "<a href=\"" + SurfacingConstants.AMIGO_LINK + go_id_str
2164 + "\" target=\"amigo_window\">" + go_id_str + "</a>" );
2165 out.write( "</td><td>" );
2166 out.write( go_term.getName() );
2167 if ( domain_count == 2 ) {
2168 out.write( " (" + d + ")" );
2170 out.write( "</td><td>" );
2171 // out.write( top );
2172 // out.write( "</td><td>" );
2174 out.write( go_term.getGoNameSpace().toShortString() );
2176 out.write( "</td>" );
2177 if ( all_go_ids != null ) {
2178 all_go_ids.add( go_id );
2182 out.write( "<td>" );
2183 out.write( "</td><td>" );
2184 out.write( "</td><td>" );
2185 out.write( "</td><td>" );
2186 out.write( "</td>" );
2188 out.write( "</tr>" );
2189 out.write( SurfacingConstants.NL );
2192 } // for( int d = 0; d < domain_count; ++d )
2193 if ( !any_go_annotation_present ) {
2194 out.write( "<tr>" );
2195 writeDomainIdsToHtml( out, domain_0, domain_1, prefix_for_html, domain_id_to_secondary_features_maps );
2196 out.write( "<td>" );
2197 out.write( "</td><td>" );
2198 out.write( "</td><td>" );
2199 out.write( "</td><td>" );
2200 out.write( "</td>" );
2201 out.write( "</tr>" );
2202 out.write( SurfacingConstants.NL );
2206 private static void writeDomainIdsToHtml( final Writer out,
2207 final String domain_0,
2208 final String domain_1,
2209 final String prefix_for_detailed_html,
2210 final Map<DomainId, Set<String>>[] domain_id_to_secondary_features_maps )
2211 throws IOException {
2212 out.write( "<td>" );
2213 if ( !ForesterUtil.isEmpty( prefix_for_detailed_html ) ) {
2214 out.write( prefix_for_detailed_html );
2217 out.write( "<a href=\"" + SurfacingConstants.PFAM_FAMILY_ID_LINK + domain_0 + "\">" + domain_0 + "</a>" );
2218 out.write( "</td>" );
2221 public static DescriptiveStatistics writeDomainSimilaritiesToFile( final StringBuilder html_desc,
2222 final StringBuilder html_title,
2223 final Writer single_writer,
2224 Map<Character, Writer> split_writers,
2225 final SortedSet<DomainSimilarity> similarities,
2226 final boolean treat_as_binary,
2227 final List<Species> species_order,
2228 final PrintableDomainSimilarity.PRINT_OPTION print_option,
2229 final DomainSimilarity.DomainSimilaritySortField sort_field,
2230 final DomainSimilarity.DomainSimilarityScoring scoring,
2231 final boolean verbose ) throws IOException {
2232 final DescriptiveStatistics stats = new BasicDescriptiveStatistics();
2233 String histogram_title = null;
2234 switch ( sort_field ) {
2235 case ABS_MAX_COUNTS_DIFFERENCE:
2236 if ( treat_as_binary ) {
2237 histogram_title = "absolute counts difference:";
2240 histogram_title = "absolute (maximal) counts difference:";
2243 case MAX_COUNTS_DIFFERENCE:
2244 if ( treat_as_binary ) {
2245 histogram_title = "counts difference:";
2248 histogram_title = "(maximal) counts difference:";
2252 histogram_title = "score mean:";
2255 histogram_title = "score minimum:";
2258 histogram_title = "score maximum:";
2260 case MAX_DIFFERENCE:
2261 if ( treat_as_binary ) {
2262 histogram_title = "difference:";
2265 histogram_title = "(maximal) difference:";
2269 histogram_title = "score mean:";
2272 histogram_title = "score standard deviation:";
2275 histogram_title = "species number:";
2278 throw new AssertionError( "Unknown sort field: " + sort_field );
2280 for( final DomainSimilarity similarity : similarities ) {
2281 switch ( sort_field ) {
2282 case ABS_MAX_COUNTS_DIFFERENCE:
2283 stats.addValue( Math.abs( similarity.getMaximalDifferenceInCounts() ) );
2285 case MAX_COUNTS_DIFFERENCE:
2286 stats.addValue( similarity.getMaximalDifferenceInCounts() );
2289 stats.addValue( similarity.getMeanSimilarityScore() );
2292 stats.addValue( similarity.getMinimalSimilarityScore() );
2295 stats.addValue( similarity.getMaximalSimilarityScore() );
2297 case MAX_DIFFERENCE:
2298 stats.addValue( similarity.getMaximalDifference() );
2301 stats.addValue( similarity.getMeanSimilarityScore() );
2304 stats.addValue( similarity.getStandardDeviationOfSimilarityScore() );
2307 stats.addValue( similarity.getSpecies().size() );
2310 throw new AssertionError( "Unknown sort field: " + sort_field );
2314 // final HistogramData[] hists = new HistogramData[ 1 ];
2317 // List<HistogramDataItem> data_items = new
2318 // ArrayList<HistogramDataItem>();
2319 // double[] values = stats.getDataAsDoubleArray();
2320 // for( int i = 0; i < values.length; i++ ) {
2321 // HistogramDataItem data_item = new BasicHistogramDataItem( "", values[
2323 // data_items.add( data_item );
2327 // HistogramData hd0 = new HistogramData( "name",
2335 // hists[ 0 ] = hd0;
2337 // final HistogramsFrame hf = new HistogramsFrame( hists );
2338 // hf.setVisible( true );
2340 AsciiHistogram histo = null;
2341 if ( stats.getMin() < stats.getMin() ) {
2342 histo = new AsciiHistogram( stats, histogram_title );
2345 if ( histo != null ) {
2346 System.out.println( histo.toStringBuffer( 20, '|', 40, 5 ) );
2348 System.out.println();
2349 System.out.println( "N : " + stats.getN() );
2350 System.out.println( "Min : " + stats.getMin() );
2351 System.out.println( "Max : " + stats.getMax() );
2352 System.out.println( "Mean : " + stats.arithmeticMean() );
2353 if ( stats.getN() > 1 ) {
2354 System.out.println( "SD : " + stats.sampleStandardDeviation() );
2357 System.out.println( "SD : n/a" );
2359 System.out.println( "Median : " + stats.median() );
2360 if ( stats.getN() > 1 ) {
2361 System.out.println( "Pearsonian skewness : " + stats.pearsonianSkewness() );
2364 System.out.println( "Pearsonian skewness : n/a" );
2367 if ( ( single_writer != null ) && ( ( split_writers == null ) || split_writers.isEmpty() ) ) {
2368 split_writers = new HashMap<Character, Writer>();
2369 split_writers.put( '_', single_writer );
2371 switch ( print_option ) {
2372 case SIMPLE_TAB_DELIMITED:
2375 for( final Character key : split_writers.keySet() ) {
2376 final Writer w = split_writers.get( key );
2377 w.write( "<html>" );
2378 w.write( SurfacingConstants.NL );
2380 addHtmlHead( w, "DCs (" + html_title + ") " + key.toString().toUpperCase() );
2383 addHtmlHead( w, "DCs (" + html_title + ")" );
2385 w.write( SurfacingConstants.NL );
2386 w.write( "<body>" );
2387 w.write( SurfacingConstants.NL );
2388 w.write( html_desc.toString() );
2389 w.write( SurfacingConstants.NL );
2392 w.write( SurfacingConstants.NL );
2393 w.write( "<tt><pre>" );
2394 w.write( SurfacingConstants.NL );
2395 if ( histo != null ) {
2396 w.write( histo.toStringBuffer( 20, '|', 40, 5 ).toString() );
2397 w.write( SurfacingConstants.NL );
2399 w.write( "</pre></tt>" );
2400 w.write( SurfacingConstants.NL );
2401 w.write( "<table>" );
2402 w.write( SurfacingConstants.NL );
2403 w.write( "<tr><td>N: </td><td>" + stats.getN() + "</td></tr>" );
2404 w.write( SurfacingConstants.NL );
2405 w.write( "<tr><td>Min: </td><td>" + stats.getMin() + "</td></tr>" );
2406 w.write( SurfacingConstants.NL );
2407 w.write( "<tr><td>Max: </td><td>" + stats.getMax() + "</td></tr>" );
2408 w.write( SurfacingConstants.NL );
2409 w.write( "<tr><td>Mean: </td><td>" + stats.arithmeticMean() + "</td></tr>" );
2410 w.write( SurfacingConstants.NL );
2411 if ( stats.getN() > 1 ) {
2412 w.write( "<tr><td>SD: </td><td>" + stats.sampleStandardDeviation() + "</td></tr>" );
2415 w.write( "<tr><td>SD: </td><td>n/a</td></tr>" );
2417 w.write( SurfacingConstants.NL );
2418 w.write( "<tr><td>Median: </td><td>" + stats.median() + "</td></tr>" );
2419 w.write( SurfacingConstants.NL );
2420 if ( stats.getN() > 1 ) {
2421 w.write( "<tr><td>Pearsonian skewness: </td><td>" + stats.pearsonianSkewness() + "</td></tr>" );
2424 w.write( "<tr><td>Pearsonian skewness: </td><td>n/a</td></tr>" );
2426 w.write( SurfacingConstants.NL );
2427 w.write( "</table>" );
2428 w.write( SurfacingConstants.NL );
2430 w.write( SurfacingConstants.NL );
2432 w.write( SurfacingConstants.NL );
2434 w.write( SurfacingConstants.NL );
2435 w.write( "<table>" );
2436 w.write( SurfacingConstants.NL );
2440 for( final Writer w : split_writers.values() ) {
2441 w.write( SurfacingConstants.NL );
2443 for( final DomainSimilarity similarity : similarities ) {
2444 if ( ( species_order != null ) && !species_order.isEmpty() ) {
2445 ( ( PrintableDomainSimilarity ) similarity ).setSpeciesOrder( species_order );
2447 if ( single_writer != null ) {
2448 single_writer.write( similarity.toStringBuffer( print_option ).toString() );
2451 Writer local_writer = split_writers.get( ( similarity.getDomainId().getId().charAt( 0 ) + "" )
2452 .toLowerCase().charAt( 0 ) );
2453 if ( local_writer == null ) {
2454 local_writer = split_writers.get( '0' );
2456 local_writer.write( similarity.toStringBuffer( print_option ).toString() );
2458 for( final Writer w : split_writers.values() ) {
2459 w.write( SurfacingConstants.NL );
2462 switch ( print_option ) {
2464 for( final Writer w : split_writers.values() ) {
2465 w.write( SurfacingConstants.NL );
2466 w.write( "</table>" );
2467 w.write( SurfacingConstants.NL );
2468 w.write( "</font>" );
2469 w.write( SurfacingConstants.NL );
2470 w.write( "</body>" );
2471 w.write( SurfacingConstants.NL );
2472 w.write( "</html>" );
2473 w.write( SurfacingConstants.NL );
2477 for( final Writer w : split_writers.values() ) {
2483 private static void writeDomainsToIndividualFilePerTreeNode( final Writer individual_files_writer,
2484 final String domain_0,
2485 final String domain_1 ) throws IOException {
2486 individual_files_writer.write( domain_0 );
2487 individual_files_writer.write( ForesterUtil.LINE_SEPARATOR );
2488 if ( !ForesterUtil.isEmpty( domain_1 ) ) {
2489 individual_files_writer.write( domain_1 );
2490 individual_files_writer.write( ForesterUtil.LINE_SEPARATOR );
2494 public static void writeMatrixToFile( final CharacterStateMatrix<?> matrix,
2495 final String filename,
2496 final Format format ) {
2497 final File outfile = new File( filename );
2498 checkForOutputFileWriteability( outfile );
2500 final BufferedWriter out = new BufferedWriter( new FileWriter( outfile ) );
2501 matrix.toWriter( out, format );
2505 catch ( final IOException e ) {
2506 ForesterUtil.fatalError( surfacing.PRG_NAME, e.getMessage() );
2508 ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote matrix: \"" + filename + "\"" );
2511 public static void writeMatrixToFile( final File matrix_outfile, final List<DistanceMatrix> matrices ) {
2512 checkForOutputFileWriteability( matrix_outfile );
2514 final BufferedWriter out = new BufferedWriter( new FileWriter( matrix_outfile ) );
2515 for( final DistanceMatrix distance_matrix : matrices ) {
2516 out.write( distance_matrix.toStringBuffer( DistanceMatrix.Format.PHYLIP ).toString() );
2517 out.write( ForesterUtil.LINE_SEPARATOR );
2522 catch ( final IOException e ) {
2523 ForesterUtil.fatalError( surfacing.PRG_NAME, e.getMessage() );
2525 ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote distance matrices to \"" + matrix_outfile + "\"" );
2528 private static void writePfamsToFile( final String outfile_name, final SortedSet<String> pfams ) {
2530 final Writer writer = new BufferedWriter( new FileWriter( new File( outfile_name ) ) );
2531 for( final String pfam : pfams ) {
2532 writer.write( pfam );
2533 writer.write( ForesterUtil.LINE_SEPARATOR );
2536 ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote " + pfams.size() + " pfams to [" + outfile_name
2539 catch ( final IOException e ) {
2540 ForesterUtil.printWarningMessage( surfacing.PRG_NAME, "Failure to write: " + e );
2544 public static void writePhylogenyToFile( final Phylogeny phylogeny, final String filename ) {
2545 final PhylogenyWriter writer = new PhylogenyWriter();
2547 writer.toPhyloXML( new File( filename ), phylogeny, 1 );
2549 catch ( final IOException e ) {
2550 ForesterUtil.printWarningMessage( surfacing.PRG_NAME, "failed to write phylogeny to \"" + filename + "\": "
2553 ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote phylogeny to \"" + filename + "\"" );
2556 public static void writeTaxonomyLinks( final Writer writer, final String species ) throws IOException {
2557 if ( ( species.length() > 1 ) && ( species.indexOf( '_' ) < 1 ) ) {
2558 final Matcher matcher = PATTERN_SP_STYLE_TAXONOMY.matcher( species );
2559 writer.write( " [" );
2560 if ( matcher.matches() ) {
2561 writer.write( "<a href=\"" + SurfacingConstants.UNIPROT_LINK + species
2562 + "\" target=\"taxonomy_window\">uniprot</a>" );
2565 writer.write( "<a href=\"" + SurfacingConstants.EOL_LINK + species
2566 + "\" target=\"taxonomy_window\">eol</a>" );
2567 writer.write( "|" );
2568 writer.write( "<a href=\"" + SurfacingConstants.TOL_LINK + species
2569 + "\" target=\"taxonomy_window\">tol</a>" );
2571 writer.write( "]" );
2575 private static void writeToNexus( final String outfile_name,
2576 final CharacterStateMatrix<BinaryStates> matrix,
2577 final Phylogeny phylogeny ) {
2578 if ( !( matrix instanceof BasicCharacterStateMatrix ) ) {
2579 throw new IllegalArgumentException( "can only write matrices of type [" + BasicCharacterStateMatrix.class
2582 final BasicCharacterStateMatrix<BinaryStates> my_matrix = ( org.forester.evoinference.matrix.character.BasicCharacterStateMatrix<BinaryStates> ) matrix;
2583 final List<Phylogeny> phylogenies = new ArrayList<Phylogeny>( 1 );
2584 phylogenies.add( phylogeny );
2586 final BufferedWriter w = new BufferedWriter( new FileWriter( outfile_name ) );
2587 w.write( NexusConstants.NEXUS );
2588 w.write( ForesterUtil.LINE_SEPARATOR );
2589 my_matrix.writeNexusTaxaBlock( w );
2590 my_matrix.writeNexusBinaryChractersBlock( w );
2591 PhylogenyWriter.writeNexusTreesBlock( w, phylogenies, NH_CONVERSION_SUPPORT_VALUE_STYLE.NONE );
2594 ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote Nexus file: \"" + outfile_name + "\"" );
2596 catch ( final IOException e ) {
2597 ForesterUtil.fatalError( surfacing.PRG_NAME, e.getMessage() );
2601 private static void writeToNexus( final String outfile_name,
2602 final DomainParsimonyCalculator domain_parsimony,
2603 final Phylogeny phylogeny ) {
2604 writeToNexus( outfile_name + surfacing.NEXUS_EXTERNAL_DOMAINS,
2605 domain_parsimony.createMatrixOfDomainPresenceOrAbsence(),
2607 writeToNexus( outfile_name + surfacing.NEXUS_EXTERNAL_DOMAIN_COMBINATIONS,
2608 domain_parsimony.createMatrixOfBinaryDomainCombinationPresenceOrAbsence(),
2612 public static void domainsPerProteinsStatistics( final String genome,
2613 final List<Protein> protein_list,
2614 final DescriptiveStatistics all_genomes_domains_per_potein_stats,
2615 final SortedMap<Integer, Integer> all_genomes_domains_per_potein_histo,
2616 final SortedSet<String> domains_which_are_always_single,
2617 final SortedSet<String> domains_which_are_sometimes_single_sometimes_not,
2618 final SortedSet<String> domains_which_never_single,
2619 final Writer writer ) {
2620 final DescriptiveStatistics stats = new BasicDescriptiveStatistics();
2621 for( final Protein protein : protein_list ) {
2622 final int domains = protein.getNumberOfProteinDomains();
2623 //System.out.println( domains );
2624 stats.addValue( domains );
2625 all_genomes_domains_per_potein_stats.addValue( domains );
2626 if ( !all_genomes_domains_per_potein_histo.containsKey( domains ) ) {
2627 all_genomes_domains_per_potein_histo.put( domains, 1 );
2630 all_genomes_domains_per_potein_histo.put( domains,
2631 1 + all_genomes_domains_per_potein_histo.get( domains ) );
2633 if ( domains == 1 ) {
2634 final String domain = protein.getProteinDomain( 0 ).getDomainId().getId();
2635 if ( !domains_which_are_sometimes_single_sometimes_not.contains( domain ) ) {
2636 if ( domains_which_never_single.contains( domain ) ) {
2637 domains_which_never_single.remove( domain );
2638 domains_which_are_sometimes_single_sometimes_not.add( domain );
2641 domains_which_are_always_single.add( domain );
2645 else if ( domains > 1 ) {
2646 for( final Domain d : protein.getProteinDomains() ) {
2647 final String domain = d.getDomainId().getId();
2648 // System.out.println( domain );
2649 if ( !domains_which_are_sometimes_single_sometimes_not.contains( domain ) ) {
2650 if ( domains_which_are_always_single.contains( domain ) ) {
2651 domains_which_are_always_single.remove( domain );
2652 domains_which_are_sometimes_single_sometimes_not.add( domain );
2655 domains_which_never_single.add( domain );
2662 writer.write( genome );
2663 writer.write( "\t" );
2664 if ( stats.getN() >= 1 ) {
2665 writer.write( stats.arithmeticMean() + "" );
2666 writer.write( "\t" );
2667 if ( stats.getN() >= 2 ) {
2668 writer.write( stats.sampleStandardDeviation() + "" );
2673 writer.write( "\t" );
2674 writer.write( stats.median() + "" );
2675 writer.write( "\t" );
2676 writer.write( stats.getN() + "" );
2677 writer.write( "\t" );
2678 writer.write( stats.getMin() + "" );
2679 writer.write( "\t" );
2680 writer.write( stats.getMax() + "" );
2683 writer.write( "\t" );
2684 writer.write( "\t" );
2685 writer.write( "\t" );
2686 writer.write( "0" );
2687 writer.write( "\t" );
2688 writer.write( "\t" );
2690 writer.write( "\n" );
2692 catch ( final IOException e ) {
2693 e.printStackTrace();