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.BasicSymmetricalDistanceMatrix;
62 import org.forester.evoinference.matrix.distance.DistanceMatrix;
63 import org.forester.go.GoId;
64 import org.forester.go.GoNameSpace;
65 import org.forester.go.GoTerm;
66 import org.forester.go.PfamToGoMapping;
67 import org.forester.io.parsers.nexus.NexusConstants;
68 import org.forester.io.writers.PhylogenyWriter;
69 import org.forester.phylogeny.Phylogeny;
70 import org.forester.phylogeny.PhylogenyMethods;
71 import org.forester.phylogeny.PhylogenyNode;
72 import org.forester.phylogeny.PhylogenyNodeI.NH_CONVERSION_SUPPORT_VALUE_STYLE;
73 import org.forester.phylogeny.data.BinaryCharacters;
74 import org.forester.phylogeny.data.Confidence;
75 import org.forester.phylogeny.iterators.PhylogenyNodeIterator;
76 import org.forester.protein.BasicDomain;
77 import org.forester.protein.BasicProtein;
78 import org.forester.protein.BinaryDomainCombination;
79 import org.forester.protein.Domain;
80 import org.forester.protein.DomainId;
81 import org.forester.protein.Protein;
82 import org.forester.species.Species;
83 import org.forester.surfacing.DomainSimilarityCalculator.Detailedness;
84 import org.forester.surfacing.DomainSimilarityCalculator.GoAnnotationOutput;
85 import org.forester.surfacing.GenomeWideCombinableDomains.GenomeWideCombinableDomainsSortOrder;
86 import org.forester.util.AsciiHistogram;
87 import org.forester.util.BasicDescriptiveStatistics;
88 import org.forester.util.BasicTable;
89 import org.forester.util.BasicTableParser;
90 import org.forester.util.DescriptiveStatistics;
91 import org.forester.util.ForesterUtil;
93 public final class SurfacingUtil {
95 private final static NumberFormat FORMATTER = new DecimalFormat( "0.0E0" );
96 private final static NumberFormat FORMATTER_3 = new DecimalFormat( "0.000" );
97 private static final Comparator<Domain> ASCENDING_CONFIDENCE_VALUE_ORDER = new Comparator<Domain>() {
100 public int compare( final Domain d1,
102 if ( d1.getPerSequenceEvalue() < d2
103 .getPerSequenceEvalue() ) {
107 .getPerSequenceEvalue() > d2
108 .getPerSequenceEvalue() ) {
112 return d1.compareTo( d2 );
116 public final static Pattern PATTERN_SP_STYLE_TAXONOMY = Pattern.compile( "^[A-Z0-9]{3,5}$" );
117 private static final boolean USE_LAST = true;
119 private SurfacingUtil() {
120 // Hidden constructor.
123 public static void addAllBinaryDomainCombinationToSet( final GenomeWideCombinableDomains genome,
124 final SortedSet<BinaryDomainCombination> binary_domain_combinations ) {
125 final SortedMap<DomainId, CombinableDomains> all_cd = genome.getAllCombinableDomainsIds();
126 for( final DomainId domain_id : all_cd.keySet() ) {
127 binary_domain_combinations.addAll( all_cd.get( domain_id ).toBinaryDomainCombinations() );
131 public static void addAllDomainIdsToSet( final GenomeWideCombinableDomains genome,
132 final SortedSet<DomainId> domain_ids ) {
133 final SortedSet<DomainId> domains = genome.getAllDomainIds();
134 for( final DomainId domain : domains ) {
135 domain_ids.add( domain );
139 public static void addHtmlHead( final Writer w, final String title ) throws IOException {
140 w.write( SurfacingConstants.NL );
142 w.write( "<title>" );
144 w.write( "</title>" );
145 w.write( SurfacingConstants.NL );
146 w.write( "<style>" );
147 w.write( SurfacingConstants.NL );
148 w.write( "a:visited { color : #6633FF; text-decoration : none; }" );
149 w.write( SurfacingConstants.NL );
150 w.write( "a:link { color : #6633FF; text-decoration : none; }" );
151 w.write( SurfacingConstants.NL );
152 w.write( "a:active { color : #99FF00; text-decoration : none; }" );
153 w.write( SurfacingConstants.NL );
154 w.write( "a:hover { color : #FFFFFF; background-color : #99FF00; text-decoration : none; }" );
155 w.write( SurfacingConstants.NL );
156 w.write( "td { text-align: left; vertical-align: top; font-family: Verdana, Arial, Helvetica; font-size: 8pt}" );
157 w.write( SurfacingConstants.NL );
158 w.write( "h1 { color : #0000FF; font-family: Verdana, Arial, Helvetica; font-size: 18pt; font-weight: bold }" );
159 w.write( SurfacingConstants.NL );
160 w.write( "h2 { color : #0000FF; font-family: Verdana, Arial, Helvetica; font-size: 16pt; font-weight: bold }" );
161 w.write( SurfacingConstants.NL );
162 w.write( "</style>" );
163 w.write( SurfacingConstants.NL );
164 w.write( "</head>" );
165 w.write( SurfacingConstants.NL );
168 public static DescriptiveStatistics calculateDescriptiveStatisticsForMeanValues( final Set<DomainSimilarity> similarities ) {
169 final DescriptiveStatistics stats = new BasicDescriptiveStatistics();
170 for( final DomainSimilarity similarity : similarities ) {
171 stats.addValue( similarity.getMeanSimilarityScore() );
176 private static void calculateIndependentDomainCombinationGains( final Phylogeny local_phylogeny_l,
177 final String outfilename_for_counts,
178 final String outfilename_for_dc,
179 final String outfilename_for_dc_for_go_mapping,
180 final String outfilename_for_dc_for_go_mapping_unique,
181 final String outfilename_for_rank_counts,
182 final String outfilename_for_ancestor_species_counts,
183 final String outfilename_for_protein_stats,
184 final Map<String, DescriptiveStatistics> protein_length_stats_by_dc,
185 final Map<String, DescriptiveStatistics> domain_number_stats_by_dc,
186 final Map<String, DescriptiveStatistics> domain_length_stats_by_domain ) {
189 // if ( protein_length_stats_by_dc != null ) {
190 // for( final Entry<?, DescriptiveStatistics> entry : protein_length_stats_by_dc.entrySet() ) {
191 // System.out.print( entry.getKey().toString() );
192 // System.out.print( ": " );
193 // double[] a = entry.getValue().getDataAsDoubleArray();
194 // for( int i = 0; i < a.length; i++ ) {
195 // System.out.print( a[ i ] + " " );
197 // System.out.println();
200 // if ( domain_number_stats_by_dc != null ) {
201 // for( final Entry<?, DescriptiveStatistics> entry : domain_number_stats_by_dc.entrySet() ) {
202 // System.out.print( entry.getKey().toString() );
203 // System.out.print( ": " );
204 // double[] a = entry.getValue().getDataAsDoubleArray();
205 // for( int i = 0; i < a.length; i++ ) {
206 // System.out.print( a[ i ] + " " );
208 // System.out.println();
212 final BufferedWriter out_counts = new BufferedWriter( new FileWriter( outfilename_for_counts ) );
213 final BufferedWriter out_dc = new BufferedWriter( new FileWriter( outfilename_for_dc ) );
214 final BufferedWriter out_dc_for_go_mapping = new BufferedWriter( new FileWriter( outfilename_for_dc_for_go_mapping ) );
215 final BufferedWriter out_dc_for_go_mapping_unique = new BufferedWriter( new FileWriter( outfilename_for_dc_for_go_mapping_unique ) );
216 final SortedMap<String, Integer> dc_gain_counts = new TreeMap<String, Integer>();
217 for( final PhylogenyNodeIterator it = local_phylogeny_l.iteratorPostorder(); it.hasNext(); ) {
218 final PhylogenyNode n = it.next();
219 final Set<String> gained_dc = n.getNodeData().getBinaryCharacters().getGainedCharacters();
220 for( final String dc : gained_dc ) {
221 if ( dc_gain_counts.containsKey( dc ) ) {
222 dc_gain_counts.put( dc, dc_gain_counts.get( dc ) + 1 );
225 dc_gain_counts.put( dc, 1 );
229 final SortedMap<Integer, Integer> histogram = new TreeMap<Integer, Integer>();
230 final SortedMap<Integer, StringBuilder> domain_lists = new TreeMap<Integer, StringBuilder>();
231 final SortedMap<Integer, DescriptiveStatistics> dc_reapp_counts_to_protein_length_stats = new TreeMap<Integer, DescriptiveStatistics>();
232 final SortedMap<Integer, DescriptiveStatistics> dc_reapp_counts_to_domain_number_stats = new TreeMap<Integer, DescriptiveStatistics>();
233 final SortedMap<Integer, DescriptiveStatistics> dc_reapp_counts_to_domain_lengths_stats = new TreeMap<Integer, DescriptiveStatistics>();
234 final SortedMap<Integer, PriorityQueue<String>> domain_lists_go = new TreeMap<Integer, PriorityQueue<String>>();
235 final SortedMap<Integer, SortedSet<String>> domain_lists_go_unique = new TreeMap<Integer, SortedSet<String>>();
236 final Set<String> dcs = dc_gain_counts.keySet();
237 final SortedSet<String> more_than_once = new TreeSet<String>();
238 final DescriptiveStatistics gained_once_lengths_stats = new BasicDescriptiveStatistics();
239 final DescriptiveStatistics gained_once_domain_count_stats = new BasicDescriptiveStatistics();
240 final DescriptiveStatistics gained_multiple_times_lengths_stats = new BasicDescriptiveStatistics();
241 final DescriptiveStatistics gained_multiple_times_domain_count_stats = new BasicDescriptiveStatistics();
242 long gained_multiple_times_domain_length_sum = 0;
243 long gained_once_domain_length_sum = 0;
244 long gained_multiple_times_domain_length_count = 0;
245 long gained_once_domain_length_count = 0;
246 for( final String dc : dcs ) {
247 final int count = dc_gain_counts.get( dc );
248 if ( histogram.containsKey( count ) ) {
249 histogram.put( count, histogram.get( count ) + 1 );
250 domain_lists.get( count ).append( ", " + dc );
251 domain_lists_go.get( count ).addAll( splitDomainCombination( dc ) );
252 domain_lists_go_unique.get( count ).addAll( splitDomainCombination( dc ) );
255 histogram.put( count, 1 );
256 domain_lists.put( count, new StringBuilder( dc ) );
257 final PriorityQueue<String> q = new PriorityQueue<String>();
258 q.addAll( splitDomainCombination( dc ) );
259 domain_lists_go.put( count, q );
260 final SortedSet<String> set = new TreeSet<String>();
261 set.addAll( splitDomainCombination( dc ) );
262 domain_lists_go_unique.put( count, set );
264 if ( protein_length_stats_by_dc != null ) {
265 if ( !dc_reapp_counts_to_protein_length_stats.containsKey( count ) ) {
266 dc_reapp_counts_to_protein_length_stats.put( count, new BasicDescriptiveStatistics() );
268 dc_reapp_counts_to_protein_length_stats.get( count ).addValue( protein_length_stats_by_dc.get( dc )
271 if ( domain_number_stats_by_dc != null ) {
272 if ( !dc_reapp_counts_to_domain_number_stats.containsKey( count ) ) {
273 dc_reapp_counts_to_domain_number_stats.put( count, new BasicDescriptiveStatistics() );
275 dc_reapp_counts_to_domain_number_stats.get( count ).addValue( domain_number_stats_by_dc.get( dc )
278 if ( domain_length_stats_by_domain != null ) {
279 if ( !dc_reapp_counts_to_domain_lengths_stats.containsKey( count ) ) {
280 dc_reapp_counts_to_domain_lengths_stats.put( count, new BasicDescriptiveStatistics() );
282 final String[] ds = dc.split( "=" );
283 dc_reapp_counts_to_domain_lengths_stats.get( count ).addValue( domain_length_stats_by_domain
284 .get( ds[ 0 ] ).arithmeticMean() );
285 dc_reapp_counts_to_domain_lengths_stats.get( count ).addValue( domain_length_stats_by_domain
286 .get( ds[ 1 ] ).arithmeticMean() );
289 more_than_once.add( dc );
290 if ( protein_length_stats_by_dc != null ) {
291 final DescriptiveStatistics s = protein_length_stats_by_dc.get( dc );
292 for( final double element : s.getData() ) {
293 gained_multiple_times_lengths_stats.addValue( element );
296 if ( domain_number_stats_by_dc != null ) {
297 final DescriptiveStatistics s = domain_number_stats_by_dc.get( dc );
298 for( final double element : s.getData() ) {
299 gained_multiple_times_domain_count_stats.addValue( element );
302 if ( domain_length_stats_by_domain != null ) {
303 final String[] ds = dc.split( "=" );
304 final DescriptiveStatistics s0 = domain_length_stats_by_domain.get( ds[ 0 ] );
305 final DescriptiveStatistics s1 = domain_length_stats_by_domain.get( ds[ 1 ] );
306 for( final double element : s0.getData() ) {
307 gained_multiple_times_domain_length_sum += element;
308 ++gained_multiple_times_domain_length_count;
310 for( final double element : s1.getData() ) {
311 gained_multiple_times_domain_length_sum += element;
312 ++gained_multiple_times_domain_length_count;
317 if ( protein_length_stats_by_dc != null ) {
318 final DescriptiveStatistics s = protein_length_stats_by_dc.get( dc );
319 for( final double element : s.getData() ) {
320 gained_once_lengths_stats.addValue( element );
323 if ( domain_number_stats_by_dc != null ) {
324 final DescriptiveStatistics s = domain_number_stats_by_dc.get( dc );
325 for( final double element : s.getData() ) {
326 gained_once_domain_count_stats.addValue( element );
329 if ( domain_length_stats_by_domain != null ) {
330 final String[] ds = dc.split( "=" );
331 final DescriptiveStatistics s0 = domain_length_stats_by_domain.get( ds[ 0 ] );
332 final DescriptiveStatistics s1 = domain_length_stats_by_domain.get( ds[ 1 ] );
333 for( final double element : s0.getData() ) {
334 gained_once_domain_length_sum += element;
335 ++gained_once_domain_length_count;
337 for( final double element : s1.getData() ) {
338 gained_once_domain_length_sum += element;
339 ++gained_once_domain_length_count;
344 final Set<Integer> histogram_keys = histogram.keySet();
345 for( final Integer histogram_key : histogram_keys ) {
346 final int count = histogram.get( histogram_key );
347 final StringBuilder dc = domain_lists.get( histogram_key );
348 out_counts.write( histogram_key + "\t" + count + ForesterUtil.LINE_SEPARATOR );
349 out_dc.write( histogram_key + "\t" + dc + ForesterUtil.LINE_SEPARATOR );
350 out_dc_for_go_mapping.write( "#" + histogram_key + ForesterUtil.LINE_SEPARATOR );
351 final Object[] sorted = domain_lists_go.get( histogram_key ).toArray();
352 Arrays.sort( sorted );
353 for( final Object domain : sorted ) {
354 out_dc_for_go_mapping.write( domain + ForesterUtil.LINE_SEPARATOR );
356 out_dc_for_go_mapping_unique.write( "#" + histogram_key + ForesterUtil.LINE_SEPARATOR );
357 for( final String domain : domain_lists_go_unique.get( histogram_key ) ) {
358 out_dc_for_go_mapping_unique.write( domain + ForesterUtil.LINE_SEPARATOR );
363 out_dc_for_go_mapping.close();
364 out_dc_for_go_mapping_unique.close();
365 final SortedMap<String, Integer> lca_rank_counts = new TreeMap<String, Integer>();
366 final SortedMap<String, Integer> lca_ancestor_species_counts = new TreeMap<String, Integer>();
367 for( final String dc : more_than_once ) {
368 final List<PhylogenyNode> nodes = new ArrayList<PhylogenyNode>();
369 for( final PhylogenyNodeIterator it = local_phylogeny_l.iteratorExternalForward(); it.hasNext(); ) {
370 final PhylogenyNode n = it.next();
371 if ( n.getNodeData().getBinaryCharacters().getGainedCharacters().contains( dc ) ) {
375 for( int i = 0; i < nodes.size() - 1; ++i ) {
376 for( int j = i + 1; j < nodes.size(); ++j ) {
377 final PhylogenyNode lca = PhylogenyMethods.getInstance().obtainLCA( nodes.get( i ),
379 String rank = "unknown";
380 if ( lca.getNodeData().isHasTaxonomy()
381 && !ForesterUtil.isEmpty( lca.getNodeData().getTaxonomy().getRank() ) ) {
382 rank = lca.getNodeData().getTaxonomy().getRank();
384 addToCountMap( lca_rank_counts, rank );
386 if ( lca.getNodeData().isHasTaxonomy()
387 && !ForesterUtil.isEmpty( lca.getNodeData().getTaxonomy().getScientificName() ) ) {
388 lca_species = lca.getNodeData().getTaxonomy().getScientificName();
390 else if ( lca.getNodeData().isHasTaxonomy()
391 && !ForesterUtil.isEmpty( lca.getNodeData().getTaxonomy().getCommonName() ) ) {
392 lca_species = lca.getNodeData().getTaxonomy().getCommonName();
395 lca_species = lca.getName();
397 addToCountMap( lca_ancestor_species_counts, lca_species );
401 final BufferedWriter out_for_rank_counts = new BufferedWriter( new FileWriter( outfilename_for_rank_counts ) );
402 final BufferedWriter out_for_ancestor_species_counts = new BufferedWriter( new FileWriter( outfilename_for_ancestor_species_counts ) );
403 ForesterUtil.map2writer( out_for_rank_counts, lca_rank_counts, "\t", ForesterUtil.LINE_SEPARATOR );
404 ForesterUtil.map2writer( out_for_ancestor_species_counts,
405 lca_ancestor_species_counts,
407 ForesterUtil.LINE_SEPARATOR );
408 out_for_rank_counts.close();
409 out_for_ancestor_species_counts.close();
410 if ( !ForesterUtil.isEmpty( outfilename_for_protein_stats )
411 && ( ( domain_length_stats_by_domain != null ) || ( protein_length_stats_by_dc != null ) || ( domain_number_stats_by_dc != null ) ) ) {
412 final BufferedWriter w = new BufferedWriter( new FileWriter( outfilename_for_protein_stats ) );
413 w.write( "Domain Lengths: " );
415 if ( domain_length_stats_by_domain != null ) {
416 for( final Entry<Integer, DescriptiveStatistics> entry : dc_reapp_counts_to_domain_lengths_stats
418 w.write( entry.getKey().toString() );
419 w.write( "\t" + entry.getValue().arithmeticMean() );
420 w.write( "\t" + entry.getValue().median() );
427 w.write( "Protein Lengths: " );
429 if ( protein_length_stats_by_dc != null ) {
430 for( final Entry<Integer, DescriptiveStatistics> entry : dc_reapp_counts_to_protein_length_stats
432 w.write( entry.getKey().toString() );
433 w.write( "\t" + entry.getValue().arithmeticMean() );
434 w.write( "\t" + entry.getValue().median() );
441 w.write( "Number of domains: " );
443 if ( domain_number_stats_by_dc != null ) {
444 for( final Entry<Integer, DescriptiveStatistics> entry : dc_reapp_counts_to_domain_number_stats
446 w.write( entry.getKey().toString() );
447 w.write( "\t" + entry.getValue().arithmeticMean() );
448 w.write( "\t" + entry.getValue().median() );
455 w.write( "Gained once, domain lengths:" );
457 w.write( "N: " + gained_once_domain_length_count );
459 w.write( "Avg: " + ( ( double ) gained_once_domain_length_sum / gained_once_domain_length_count ) );
462 w.write( "Gained multiple times, domain lengths:" );
464 w.write( "N: " + gained_multiple_times_domain_length_count );
467 + ( ( double ) gained_multiple_times_domain_length_sum / gained_multiple_times_domain_length_count ) );
472 w.write( "Gained once, protein lengths:" );
474 w.write( gained_once_lengths_stats.toString() );
477 w.write( "Gained once, domain counts:" );
479 w.write( gained_once_domain_count_stats.toString() );
482 w.write( "Gained multiple times, protein lengths:" );
484 w.write( gained_multiple_times_lengths_stats.toString() );
487 w.write( "Gained multiple times, domain counts:" );
489 w.write( gained_multiple_times_domain_count_stats.toString() );
494 catch ( final IOException e ) {
495 ForesterUtil.printWarningMessage( surfacing.PRG_NAME, "Failure to write: " + e );
497 ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote independent domain combination gains fitch counts to ["
498 + outfilename_for_counts + "]" );
499 ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote independent domain combination gains fitch lists to ["
500 + outfilename_for_dc + "]" );
501 ForesterUtil.programMessage( surfacing.PRG_NAME,
502 "Wrote independent domain combination gains fitch lists to (for GO mapping) ["
503 + outfilename_for_dc_for_go_mapping + "]" );
504 ForesterUtil.programMessage( surfacing.PRG_NAME,
505 "Wrote independent domain combination gains fitch lists to (for GO mapping, unique) ["
506 + outfilename_for_dc_for_go_mapping_unique + "]" );
509 private final static void addToCountMap( final Map<String, Integer> map, final String s ) {
510 if ( map.containsKey( s ) ) {
511 map.put( s, map.get( s ) + 1 );
518 public static int calculateOverlap( final Domain domain, final List<Boolean> covered_positions ) {
519 int overlap_count = 0;
520 for( int i = domain.getFrom(); i <= domain.getTo(); ++i ) {
521 if ( ( i < covered_positions.size() ) && ( covered_positions.get( i ) == true ) ) {
525 return overlap_count;
528 public static void checkForOutputFileWriteability( final File outfile ) {
529 final String error = ForesterUtil.isWritableFile( outfile );
530 if ( !ForesterUtil.isEmpty( error ) ) {
531 ForesterUtil.fatalError( surfacing.PRG_NAME, error );
535 private static SortedSet<String> collectAllDomainsChangedOnSubtree( final PhylogenyNode subtree_root,
536 final boolean get_gains ) {
537 final SortedSet<String> domains = new TreeSet<String>();
538 for( final PhylogenyNode descendant : PhylogenyMethods.getAllDescendants( subtree_root ) ) {
539 final BinaryCharacters chars = descendant.getNodeData().getBinaryCharacters();
541 domains.addAll( chars.getGainedCharacters() );
544 domains.addAll( chars.getLostCharacters() );
550 public static void collectChangedDomainCombinationsFromBinaryStatesMatrixAsListToFile( final CharacterStateMatrix<CharacterStateMatrix.GainLossStates> matrix,
551 final BinaryDomainCombination.DomainCombinationType dc_type,
552 final List<BinaryDomainCombination> all_binary_domains_combination_gained,
553 final boolean get_gains ) {
554 final SortedSet<String> sorted_ids = new TreeSet<String>();
555 for( int i = 0; i < matrix.getNumberOfIdentifiers(); ++i ) {
556 sorted_ids.add( matrix.getIdentifier( i ) );
558 for( final String id : sorted_ids ) {
559 for( int c = 0; c < matrix.getNumberOfCharacters(); ++c ) {
560 if ( ( get_gains && ( matrix.getState( id, c ) == CharacterStateMatrix.GainLossStates.GAIN ) )
561 || ( !get_gains && ( matrix.getState( id, c ) == CharacterStateMatrix.GainLossStates.LOSS ) ) ) {
562 if ( dc_type == BinaryDomainCombination.DomainCombinationType.DIRECTED_ADJACTANT ) {
563 all_binary_domains_combination_gained.add( AdjactantDirectedBinaryDomainCombination
564 .createInstance( matrix.getCharacter( c ) ) );
566 else if ( dc_type == BinaryDomainCombination.DomainCombinationType.DIRECTED ) {
567 all_binary_domains_combination_gained.add( DirectedBinaryDomainCombination
568 .createInstance( matrix.getCharacter( c ) ) );
571 all_binary_domains_combination_gained.add( BasicBinaryDomainCombination.createInstance( matrix
572 .getCharacter( c ) ) );
579 private static File createBaseDirForPerNodeDomainFiles( final String base_dir,
580 final boolean domain_combinations,
581 final CharacterStateMatrix.GainLossStates state,
582 final String outfile ) {
583 File per_node_go_mapped_domain_gain_loss_files_base_dir = new File( new File( outfile ).getParent()
584 + ForesterUtil.FILE_SEPARATOR + base_dir );
585 if ( !per_node_go_mapped_domain_gain_loss_files_base_dir.exists() ) {
586 per_node_go_mapped_domain_gain_loss_files_base_dir.mkdir();
588 if ( domain_combinations ) {
589 per_node_go_mapped_domain_gain_loss_files_base_dir = new File( per_node_go_mapped_domain_gain_loss_files_base_dir
590 + ForesterUtil.FILE_SEPARATOR + "DC" );
593 per_node_go_mapped_domain_gain_loss_files_base_dir = new File( per_node_go_mapped_domain_gain_loss_files_base_dir
594 + ForesterUtil.FILE_SEPARATOR + "DOMAINS" );
596 if ( !per_node_go_mapped_domain_gain_loss_files_base_dir.exists() ) {
597 per_node_go_mapped_domain_gain_loss_files_base_dir.mkdir();
599 if ( state == GainLossStates.GAIN ) {
600 per_node_go_mapped_domain_gain_loss_files_base_dir = new File( per_node_go_mapped_domain_gain_loss_files_base_dir
601 + ForesterUtil.FILE_SEPARATOR + "GAINS" );
603 else if ( state == GainLossStates.LOSS ) {
604 per_node_go_mapped_domain_gain_loss_files_base_dir = new File( per_node_go_mapped_domain_gain_loss_files_base_dir
605 + ForesterUtil.FILE_SEPARATOR + "LOSSES" );
608 per_node_go_mapped_domain_gain_loss_files_base_dir = new File( per_node_go_mapped_domain_gain_loss_files_base_dir
609 + ForesterUtil.FILE_SEPARATOR + "PRESENT" );
611 if ( !per_node_go_mapped_domain_gain_loss_files_base_dir.exists() ) {
612 per_node_go_mapped_domain_gain_loss_files_base_dir.mkdir();
614 return per_node_go_mapped_domain_gain_loss_files_base_dir;
617 public static Map<DomainId, List<GoId>> createDomainIdToGoIdMap( final List<PfamToGoMapping> pfam_to_go_mappings ) {
618 final Map<DomainId, List<GoId>> domain_id_to_go_ids_map = new HashMap<DomainId, List<GoId>>( pfam_to_go_mappings
620 for( final PfamToGoMapping pfam_to_go : pfam_to_go_mappings ) {
621 if ( !domain_id_to_go_ids_map.containsKey( pfam_to_go.getKey() ) ) {
622 domain_id_to_go_ids_map.put( pfam_to_go.getKey(), new ArrayList<GoId>() );
624 domain_id_to_go_ids_map.get( pfam_to_go.getKey() ).add( pfam_to_go.getValue() );
626 return domain_id_to_go_ids_map;
629 public static Map<DomainId, Set<String>> createDomainIdToSecondaryFeaturesMap( final File secondary_features_map_file )
631 final BasicTable<String> primary_table = BasicTableParser.parse( secondary_features_map_file, "\t" );
632 final Map<DomainId, Set<String>> map = new TreeMap<DomainId, Set<String>>();
633 for( int r = 0; r < primary_table.getNumberOfRows(); ++r ) {
634 final DomainId domain_id = new DomainId( primary_table.getValue( 0, r ) );
635 if ( !map.containsKey( domain_id ) ) {
636 map.put( domain_id, new HashSet<String>() );
638 map.get( domain_id ).add( primary_table.getValue( 1, r ) );
643 public static Phylogeny createNjTreeBasedOnMatrixToFile( final File nj_tree_outfile, final DistanceMatrix distance ) {
644 checkForOutputFileWriteability( nj_tree_outfile );
645 final NeighborJoining nj = NeighborJoining.createInstance();
646 final Phylogeny phylogeny = nj.execute( ( BasicSymmetricalDistanceMatrix ) distance );
647 phylogeny.setName( nj_tree_outfile.getName() );
648 writePhylogenyToFile( phylogeny, nj_tree_outfile.toString() );
652 private static SortedSet<BinaryDomainCombination> createSetOfAllBinaryDomainCombinationsPerGenome( final GenomeWideCombinableDomains gwcd ) {
653 final SortedMap<DomainId, CombinableDomains> cds = gwcd.getAllCombinableDomainsIds();
654 final SortedSet<BinaryDomainCombination> binary_combinations = new TreeSet<BinaryDomainCombination>();
655 for( final DomainId domain_id : cds.keySet() ) {
656 final CombinableDomains cd = cds.get( domain_id );
657 binary_combinations.addAll( cd.toBinaryDomainCombinations() );
659 return binary_combinations;
662 public static void decoratePrintableDomainSimilarities( final SortedSet<DomainSimilarity> domain_similarities,
663 final Detailedness detailedness,
664 final GoAnnotationOutput go_annotation_output,
665 final Map<GoId, GoTerm> go_id_to_term_map,
666 final GoNameSpace go_namespace_limit ) {
667 if ( ( go_namespace_limit != null ) && ( ( go_id_to_term_map == null ) || go_id_to_term_map.isEmpty() ) ) {
668 throw new IllegalArgumentException( "attempt to use a GO namespace limit without a GO id to term map" );
670 for( final DomainSimilarity domain_similarity : domain_similarities ) {
671 if ( domain_similarity instanceof PrintableDomainSimilarity ) {
672 final PrintableDomainSimilarity printable_domain_similarity = ( PrintableDomainSimilarity ) domain_similarity;
673 printable_domain_similarity.setDetailedness( detailedness );
674 printable_domain_similarity.setGoAnnotationOutput( go_annotation_output );
675 printable_domain_similarity.setGoIdToTermMap( go_id_to_term_map );
676 printable_domain_similarity.setGoNamespaceLimit( go_namespace_limit );
681 public static void executeDomainLengthAnalysis( final String[][] input_file_properties,
682 final int number_of_genomes,
683 final DomainLengthsTable domain_lengths_table,
684 final File outfile ) throws IOException {
685 final DecimalFormat df = new DecimalFormat( "#.00" );
686 checkForOutputFileWriteability( outfile );
687 final BufferedWriter out = new BufferedWriter( new FileWriter( outfile ) );
688 out.write( "MEAN BASED STATISTICS PER SPECIES" );
689 out.write( ForesterUtil.LINE_SEPARATOR );
690 out.write( domain_lengths_table.createMeanBasedStatisticsPerSpeciesTable().toString() );
691 out.write( ForesterUtil.LINE_SEPARATOR );
692 out.write( ForesterUtil.LINE_SEPARATOR );
693 final List<DomainLengths> domain_lengths_list = domain_lengths_table.getDomainLengthsList();
694 out.write( "OUTLIER SPECIES PER DOMAIN (Z>=1.5)" );
695 out.write( ForesterUtil.LINE_SEPARATOR );
696 for( final DomainLengths domain_lengths : domain_lengths_list ) {
697 final List<Species> species_list = domain_lengths.getMeanBasedOutlierSpecies( 1.5 );
698 if ( species_list.size() > 0 ) {
699 out.write( domain_lengths.getDomainId() + "\t" );
700 for( final Species species : species_list ) {
701 out.write( species + "\t" );
703 out.write( ForesterUtil.LINE_SEPARATOR );
704 // DescriptiveStatistics stats_for_domain = domain_lengths
705 // .calculateMeanBasedStatistics();
706 //AsciiHistogram histo = new AsciiHistogram( stats_for_domain );
707 //System.out.println( histo.toStringBuffer( 40, '=', 60, 4 ).toString() );
710 out.write( ForesterUtil.LINE_SEPARATOR );
711 out.write( ForesterUtil.LINE_SEPARATOR );
712 out.write( "OUTLIER SPECIES (Z 1.0)" );
713 out.write( ForesterUtil.LINE_SEPARATOR );
714 final DescriptiveStatistics stats_for_all_species = domain_lengths_table
715 .calculateMeanBasedStatisticsForAllSpecies();
716 out.write( stats_for_all_species.asSummary() );
717 out.write( ForesterUtil.LINE_SEPARATOR );
718 final AsciiHistogram histo = new AsciiHistogram( stats_for_all_species );
719 out.write( histo.toStringBuffer( 40, '=', 60, 4 ).toString() );
720 out.write( ForesterUtil.LINE_SEPARATOR );
721 final double population_sd = stats_for_all_species.sampleStandardDeviation();
722 final double population_mean = stats_for_all_species.arithmeticMean();
723 for( final Species species : domain_lengths_table.getSpecies() ) {
724 final double x = domain_lengths_table.calculateMeanBasedStatisticsForSpecies( species ).arithmeticMean();
725 final double z = ( x - population_mean ) / population_sd;
726 out.write( species + "\t" + z );
727 out.write( ForesterUtil.LINE_SEPARATOR );
729 out.write( ForesterUtil.LINE_SEPARATOR );
730 for( final Species species : domain_lengths_table.getSpecies() ) {
731 final DescriptiveStatistics stats_for_species = domain_lengths_table
732 .calculateMeanBasedStatisticsForSpecies( species );
733 final double x = stats_for_species.arithmeticMean();
734 final double z = ( x - population_mean ) / population_sd;
735 if ( ( z <= -1.0 ) || ( z >= 1.0 ) ) {
736 out.write( species + "\t" + df.format( z ) + "\t" + stats_for_species.asSummary() );
737 out.write( ForesterUtil.LINE_SEPARATOR );
741 // final List<HistogramData> histogram_datas = new ArrayList<HistogramData>();
742 // for( int i = 0; i < number_of_genomes; ++i ) {
743 // final Species species = new BasicSpecies( input_file_properties[ i ][ 0 ] );
745 // .add( new HistogramData( species.toString(), domain_lengths_table
746 // .calculateMeanBasedStatisticsForSpecies( species )
747 // .getDataAsDoubleArray(), 5, 600, null, 60 ) );
749 // final HistogramsFrame hf = new HistogramsFrame( histogram_datas );
750 // hf.setVisible( true );
756 * @param all_binary_domains_combination_lost_fitch
757 * @param consider_directedness_and_adjacency_for_bin_combinations
758 * @param all_binary_domains_combination_gained if null ignored, otherwise this is to list all binary domain combinations
759 * which were gained under unweighted (Fitch) parsimony.
761 public static void executeParsimonyAnalysis( final long random_number_seed_for_fitch_parsimony,
762 final boolean radomize_fitch_parsimony,
763 final String outfile_name,
764 final DomainParsimonyCalculator domain_parsimony,
765 final Phylogeny phylogeny,
766 final Map<DomainId, List<GoId>> domain_id_to_go_ids_map,
767 final Map<GoId, GoTerm> go_id_to_term_map,
768 final GoNameSpace go_namespace_limit,
769 final String parameters_str,
770 final Map<DomainId, Set<String>>[] domain_id_to_secondary_features_maps,
771 final SortedSet<DomainId> positive_filter,
772 final boolean output_binary_domain_combinations_for_graphs,
773 final List<BinaryDomainCombination> all_binary_domains_combination_gained_fitch,
774 final List<BinaryDomainCombination> all_binary_domains_combination_lost_fitch,
775 final BinaryDomainCombination.DomainCombinationType dc_type,
776 final Map<String, DescriptiveStatistics> protein_length_stats_by_dc,
777 final Map<String, DescriptiveStatistics> domain_number_stats_by_dc,
778 final Map<String, DescriptiveStatistics> domain_length_stats_by_domain ) {
779 final String sep = ForesterUtil.LINE_SEPARATOR + "###################" + ForesterUtil.LINE_SEPARATOR;
780 final String date_time = ForesterUtil.getCurrentDateTime();
781 final SortedSet<String> all_pfams_encountered = new TreeSet<String>();
782 final SortedSet<String> all_pfams_gained_as_domains = new TreeSet<String>();
783 final SortedSet<String> all_pfams_lost_as_domains = new TreeSet<String>();
784 final SortedSet<String> all_pfams_gained_as_dom_combinations = new TreeSet<String>();
785 final SortedSet<String> all_pfams_lost_as_dom_combinations = new TreeSet<String>();
786 writeToNexus( outfile_name, domain_parsimony, phylogeny );
789 Phylogeny local_phylogeny_l = phylogeny.copy();
790 if ( ( positive_filter != null ) && ( positive_filter.size() > 0 ) ) {
791 domain_parsimony.executeDolloParsimonyOnDomainPresence( positive_filter );
794 domain_parsimony.executeDolloParsimonyOnDomainPresence();
796 SurfacingUtil.writeMatrixToFile( domain_parsimony.getGainLossMatrix(), outfile_name
797 + surfacing.PARSIMONY_OUTPUT_GL_SUFFIX_DOLLO_DOMAINS, Format.FORESTER );
798 SurfacingUtil.writeMatrixToFile( domain_parsimony.getGainLossCountsMatrix(), outfile_name
799 + surfacing.PARSIMONY_OUTPUT_GL_COUNTS_SUFFIX_DOLLO_DOMAINS, Format.FORESTER );
800 SurfacingUtil.writeBinaryStatesMatrixAsListToFile( domain_parsimony.getGainLossMatrix(),
801 CharacterStateMatrix.GainLossStates.GAIN,
802 outfile_name + surfacing.PARSIMONY_OUTPUT_DOLLO_GAINS_D,
804 ForesterUtil.LINE_SEPARATOR,
806 SurfacingUtil.writeBinaryStatesMatrixAsListToFile( domain_parsimony.getGainLossMatrix(),
807 CharacterStateMatrix.GainLossStates.LOSS,
808 outfile_name + surfacing.PARSIMONY_OUTPUT_DOLLO_LOSSES_D,
810 ForesterUtil.LINE_SEPARATOR,
812 SurfacingUtil.writeBinaryStatesMatrixAsListToFile( domain_parsimony.getGainLossMatrix(), null, outfile_name
813 + surfacing.PARSIMONY_OUTPUT_DOLLO_PRESENT_D, sep, ForesterUtil.LINE_SEPARATOR, null );
815 writeBinaryStatesMatrixToList( domain_id_to_go_ids_map,
819 domain_parsimony.getGainLossMatrix(),
820 CharacterStateMatrix.GainLossStates.GAIN,
821 outfile_name + surfacing.PARSIMONY_OUTPUT_DOLLO_GAINS_HTML_D,
823 ForesterUtil.LINE_SEPARATOR,
824 "Dollo Parsimony | Gains | Domains",
826 domain_id_to_secondary_features_maps,
827 all_pfams_encountered,
828 all_pfams_gained_as_domains,
830 writeBinaryStatesMatrixToList( domain_id_to_go_ids_map,
834 domain_parsimony.getGainLossMatrix(),
835 CharacterStateMatrix.GainLossStates.LOSS,
836 outfile_name + surfacing.PARSIMONY_OUTPUT_DOLLO_LOSSES_HTML_D,
838 ForesterUtil.LINE_SEPARATOR,
839 "Dollo Parsimony | Losses | Domains",
841 domain_id_to_secondary_features_maps,
842 all_pfams_encountered,
843 all_pfams_lost_as_domains,
845 writeBinaryStatesMatrixToList( domain_id_to_go_ids_map,
849 domain_parsimony.getGainLossMatrix(),
851 outfile_name + surfacing.PARSIMONY_OUTPUT_DOLLO_PRESENT_HTML_D,
853 ForesterUtil.LINE_SEPARATOR,
854 "Dollo Parsimony | Present | Domains",
856 domain_id_to_secondary_features_maps,
857 all_pfams_encountered,
859 "_dollo_present_d" );
860 preparePhylogeny( local_phylogeny_l,
863 "Dollo parsimony on domain presence/absence",
864 "dollo_on_domains_" + outfile_name,
866 SurfacingUtil.writePhylogenyToFile( local_phylogeny_l, outfile_name
867 + surfacing.DOMAINS_PARSIMONY_TREE_OUTPUT_SUFFIX_DOLLO );
869 writeAllDomainsChangedOnAllSubtrees( local_phylogeny_l, true, outfile_name, "_dollo_all_gains_d" );
870 writeAllDomainsChangedOnAllSubtrees( local_phylogeny_l, false, outfile_name, "_dollo_all_losses_d" );
872 catch ( final IOException e ) {
874 ForesterUtil.fatalError( surfacing.PRG_NAME, e.getLocalizedMessage() );
876 if ( domain_parsimony.calculateNumberOfBinaryDomainCombination() > 0 ) {
877 // FITCH DOMAIN COMBINATIONS
878 // -------------------------
879 local_phylogeny_l = phylogeny.copy();
880 String randomization = "no";
881 if ( radomize_fitch_parsimony ) {
882 domain_parsimony.executeFitchParsimonyOnBinaryDomainCombintion( random_number_seed_for_fitch_parsimony );
883 randomization = "yes, seed = " + random_number_seed_for_fitch_parsimony;
886 domain_parsimony.executeFitchParsimonyOnBinaryDomainCombintion( USE_LAST );
888 SurfacingUtil.writeMatrixToFile( domain_parsimony.getGainLossMatrix(), outfile_name
889 + surfacing.PARSIMONY_OUTPUT_GL_SUFFIX_FITCH_BINARY_COMBINATIONS, Format.FORESTER );
890 SurfacingUtil.writeMatrixToFile( domain_parsimony.getGainLossCountsMatrix(), outfile_name
891 + surfacing.PARSIMONY_OUTPUT_GL_COUNTS_SUFFIX_FITCH_BINARY_COMBINATIONS, Format.FORESTER );
893 .writeBinaryStatesMatrixAsListToFile( domain_parsimony.getGainLossMatrix(),
894 CharacterStateMatrix.GainLossStates.GAIN,
895 outfile_name + surfacing.PARSIMONY_OUTPUT_FITCH_GAINS_BC,
897 ForesterUtil.LINE_SEPARATOR,
899 SurfacingUtil.writeBinaryStatesMatrixAsListToFile( domain_parsimony.getGainLossMatrix(),
900 CharacterStateMatrix.GainLossStates.LOSS,
902 + surfacing.PARSIMONY_OUTPUT_FITCH_LOSSES_BC,
904 ForesterUtil.LINE_SEPARATOR,
906 SurfacingUtil.writeBinaryStatesMatrixAsListToFile( domain_parsimony.getGainLossMatrix(), null, outfile_name
907 + surfacing.PARSIMONY_OUTPUT_FITCH_PRESENT_BC, sep, ForesterUtil.LINE_SEPARATOR, null );
908 if ( all_binary_domains_combination_gained_fitch != null ) {
909 collectChangedDomainCombinationsFromBinaryStatesMatrixAsListToFile( domain_parsimony.getGainLossMatrix(),
911 all_binary_domains_combination_gained_fitch,
914 if ( all_binary_domains_combination_lost_fitch != null ) {
915 collectChangedDomainCombinationsFromBinaryStatesMatrixAsListToFile( domain_parsimony.getGainLossMatrix(),
917 all_binary_domains_combination_lost_fitch,
920 if ( output_binary_domain_combinations_for_graphs ) {
922 .writeBinaryStatesMatrixAsListToFileForBinaryCombinationsForGraphAnalysis( domain_parsimony
923 .getGainLossMatrix(),
926 + surfacing.PARSIMONY_OUTPUT_FITCH_PRESENT_BC_OUTPUTFILE_SUFFIX_FOR_GRAPH_ANALYSIS,
928 ForesterUtil.LINE_SEPARATOR,
929 BinaryDomainCombination.OutputFormat.DOT );
932 writeBinaryStatesMatrixToList( domain_id_to_go_ids_map,
936 domain_parsimony.getGainLossMatrix(),
937 CharacterStateMatrix.GainLossStates.GAIN,
938 outfile_name + surfacing.PARSIMONY_OUTPUT_FITCH_GAINS_HTML_BC,
940 ForesterUtil.LINE_SEPARATOR,
941 "Fitch Parsimony | Gains | Domain Combinations",
944 all_pfams_encountered,
945 all_pfams_gained_as_dom_combinations,
947 writeBinaryStatesMatrixToList( domain_id_to_go_ids_map,
951 domain_parsimony.getGainLossMatrix(),
952 CharacterStateMatrix.GainLossStates.LOSS,
953 outfile_name + surfacing.PARSIMONY_OUTPUT_FITCH_LOSSES_HTML_BC,
955 ForesterUtil.LINE_SEPARATOR,
956 "Fitch Parsimony | Losses | Domain Combinations",
959 all_pfams_encountered,
960 all_pfams_lost_as_dom_combinations,
961 "_fitch_losses_dc" );
962 writeBinaryStatesMatrixToList( domain_id_to_go_ids_map,
966 domain_parsimony.getGainLossMatrix(),
968 outfile_name + surfacing.PARSIMONY_OUTPUT_FITCH_PRESENT_HTML_BC,
970 ForesterUtil.LINE_SEPARATOR,
971 "Fitch Parsimony | Present | Domain Combinations",
974 all_pfams_encountered,
976 "_fitch_present_dc" );
977 writeAllEncounteredPfamsToFile( domain_id_to_go_ids_map,
980 all_pfams_encountered );
981 writePfamsToFile( outfile_name + surfacing.ALL_PFAMS_GAINED_AS_DOMAINS_SUFFIX, all_pfams_gained_as_domains );
982 writePfamsToFile( outfile_name + surfacing.ALL_PFAMS_LOST_AS_DOMAINS_SUFFIX, all_pfams_lost_as_domains );
983 writePfamsToFile( outfile_name + surfacing.ALL_PFAMS_GAINED_AS_DC_SUFFIX,
984 all_pfams_gained_as_dom_combinations );
985 writePfamsToFile( outfile_name + surfacing.ALL_PFAMS_LOST_AS_DC_SUFFIX, all_pfams_lost_as_dom_combinations );
986 preparePhylogeny( local_phylogeny_l,
989 "Fitch parsimony on binary domain combination presence/absence randomization: "
991 "fitch_on_binary_domain_combinations_" + outfile_name,
993 SurfacingUtil.writePhylogenyToFile( local_phylogeny_l, outfile_name
994 + surfacing.BINARY_DOMAIN_COMBINATIONS_PARSIMONY_TREE_OUTPUT_SUFFIX_FITCH );
995 calculateIndependentDomainCombinationGains( local_phylogeny_l,
997 + surfacing.INDEPENDENT_DC_GAINS_FITCH_PARS_COUNTS_OUTPUT_SUFFIX,
999 + surfacing.INDEPENDENT_DC_GAINS_FITCH_PARS_DC_OUTPUT_SUFFIX,
1001 + surfacing.INDEPENDENT_DC_GAINS_FITCH_PARS_DC_FOR_GO_MAPPING_OUTPUT_SUFFIX,
1003 + surfacing.INDEPENDENT_DC_GAINS_FITCH_PARS_DC_FOR_GO_MAPPING_OUTPUT_UNIQUE_SUFFIX,
1004 outfile_name + "_indep_dc_gains_fitch_lca_ranks.txt",
1005 outfile_name + "_indep_dc_gains_fitch_lca_taxonomies.txt",
1006 outfile_name + "_indep_dc_gains_fitch_protein_statistics.txt",
1007 protein_length_stats_by_dc,
1008 domain_number_stats_by_dc,
1009 domain_length_stats_by_domain );
1013 public static void executeParsimonyAnalysisForSecondaryFeatures( final String outfile_name,
1014 final DomainParsimonyCalculator secondary_features_parsimony,
1015 final Phylogeny phylogeny,
1016 final String parameters_str,
1017 final Map<Species, MappingResults> mapping_results_map ) {
1018 final String sep = ForesterUtil.LINE_SEPARATOR + "###################" + ForesterUtil.LINE_SEPARATOR;
1019 final String date_time = ForesterUtil.getCurrentDateTime();
1020 System.out.println();
1021 writeToNexus( outfile_name + surfacing.NEXUS_SECONDARY_FEATURES,
1022 secondary_features_parsimony.createMatrixOfSecondaryFeaturePresenceOrAbsence( null ),
1024 Phylogeny local_phylogeny_copy = phylogeny.copy();
1025 secondary_features_parsimony.executeDolloParsimonyOnSecondaryFeatures( mapping_results_map );
1026 SurfacingUtil.writeMatrixToFile( secondary_features_parsimony.getGainLossMatrix(), outfile_name
1027 + surfacing.PARSIMONY_OUTPUT_GL_SUFFIX_DOLLO_SECONDARY_FEATURES, Format.FORESTER );
1028 SurfacingUtil.writeMatrixToFile( secondary_features_parsimony.getGainLossCountsMatrix(), outfile_name
1029 + surfacing.PARSIMONY_OUTPUT_GL_COUNTS_SUFFIX_DOLLO_SECONDARY_FEATURES, Format.FORESTER );
1031 .writeBinaryStatesMatrixAsListToFile( secondary_features_parsimony.getGainLossMatrix(),
1032 CharacterStateMatrix.GainLossStates.GAIN,
1034 + surfacing.PARSIMONY_OUTPUT_DOLLO_GAINS_SECONDARY_FEATURES,
1036 ForesterUtil.LINE_SEPARATOR,
1039 .writeBinaryStatesMatrixAsListToFile( secondary_features_parsimony.getGainLossMatrix(),
1040 CharacterStateMatrix.GainLossStates.LOSS,
1042 + surfacing.PARSIMONY_OUTPUT_DOLLO_LOSSES_SECONDARY_FEATURES,
1044 ForesterUtil.LINE_SEPARATOR,
1047 .writeBinaryStatesMatrixAsListToFile( secondary_features_parsimony.getGainLossMatrix(),
1050 + surfacing.PARSIMONY_OUTPUT_DOLLO_PRESENT_SECONDARY_FEATURES,
1052 ForesterUtil.LINE_SEPARATOR,
1054 preparePhylogeny( local_phylogeny_copy,
1055 secondary_features_parsimony,
1057 "Dollo parsimony on secondary feature presence/absence",
1058 "dollo_on_secondary_features_" + outfile_name,
1060 SurfacingUtil.writePhylogenyToFile( local_phylogeny_copy, outfile_name
1061 + surfacing.SECONDARY_FEATURES_PARSIMONY_TREE_OUTPUT_SUFFIX_DOLLO );
1062 // FITCH DOMAIN COMBINATIONS
1063 // -------------------------
1064 local_phylogeny_copy = phylogeny.copy();
1065 final String randomization = "no";
1066 secondary_features_parsimony.executeFitchParsimonyOnBinaryDomainCombintionOnSecondaryFeatures( USE_LAST );
1067 preparePhylogeny( local_phylogeny_copy,
1068 secondary_features_parsimony,
1070 "Fitch parsimony on secondary binary domain combination presence/absence randomization: "
1072 "fitch_on_binary_domain_combinations_" + outfile_name,
1074 SurfacingUtil.writePhylogenyToFile( local_phylogeny_copy, outfile_name
1075 + surfacing.BINARY_DOMAIN_COMBINATIONS_PARSIMONY_TREE_OUTPUT_SUFFIX_FITCH_MAPPED );
1076 calculateIndependentDomainCombinationGains( local_phylogeny_copy, outfile_name
1077 + surfacing.INDEPENDENT_DC_GAINS_FITCH_PARS_COUNTS_MAPPED_OUTPUT_SUFFIX, outfile_name
1078 + surfacing.INDEPENDENT_DC_GAINS_FITCH_PARS_DC_MAPPED_OUTPUT_SUFFIX, outfile_name
1079 + surfacing.INDEPENDENT_DC_GAINS_FITCH_PARS_DC_FOR_GO_MAPPING_MAPPED_OUTPUT_SUFFIX, outfile_name
1080 + surfacing.INDEPENDENT_DC_GAINS_FITCH_PARS_DC_FOR_GO_MAPPING_MAPPED_OUTPUT_UNIQUE_SUFFIX, outfile_name
1081 + "_MAPPED_indep_dc_gains_fitch_lca_ranks.txt", outfile_name
1082 + "_MAPPED_indep_dc_gains_fitch_lca_taxonomies.txt", null, null, null, null );
1085 public static void doit( final List<Protein> proteins,
1086 final List<DomainId> query_domain_ids_nc_order,
1088 final String separator,
1089 final String limit_to_species,
1090 final Map<String, List<Integer>> average_protein_lengths_by_dc ) throws IOException {
1091 for( final Protein protein : proteins ) {
1092 if ( ForesterUtil.isEmpty( limit_to_species )
1093 || protein.getSpecies().getSpeciesId().equalsIgnoreCase( limit_to_species ) ) {
1094 if ( protein.contains( query_domain_ids_nc_order, true ) ) {
1095 out.write( protein.getSpecies().getSpeciesId() );
1096 out.write( separator );
1097 out.write( protein.getProteinId().getId() );
1098 out.write( separator );
1100 final Set<DomainId> visited_domain_ids = new HashSet<DomainId>();
1101 boolean first = true;
1102 for( final Domain domain : protein.getProteinDomains() ) {
1103 if ( !visited_domain_ids.contains( domain.getDomainId() ) ) {
1104 visited_domain_ids.add( domain.getDomainId() );
1111 out.write( domain.getDomainId().getId() );
1113 out.write( "" + domain.getTotalCount() );
1118 out.write( separator );
1119 if ( !( ForesterUtil.isEmpty( protein.getDescription() ) || protein.getDescription()
1120 .equals( SurfacingConstants.NONE ) ) ) {
1121 out.write( protein.getDescription() );
1123 out.write( separator );
1124 if ( !( ForesterUtil.isEmpty( protein.getAccession() ) || protein.getAccession()
1125 .equals( SurfacingConstants.NONE ) ) ) {
1126 out.write( protein.getAccession() );
1128 out.write( SurfacingConstants.NL );
1135 public static void extractProteinNames( final List<Protein> proteins,
1136 final List<DomainId> query_domain_ids_nc_order,
1138 final String separator,
1139 final String limit_to_species ) throws IOException {
1140 for( final Protein protein : proteins ) {
1141 if ( ForesterUtil.isEmpty( limit_to_species )
1142 || protein.getSpecies().getSpeciesId().equalsIgnoreCase( limit_to_species ) ) {
1143 if ( protein.contains( query_domain_ids_nc_order, true ) ) {
1144 out.write( protein.getSpecies().getSpeciesId() );
1145 out.write( separator );
1146 out.write( protein.getProteinId().getId() );
1147 out.write( separator );
1149 final Set<DomainId> visited_domain_ids = new HashSet<DomainId>();
1150 boolean first = true;
1151 for( final Domain domain : protein.getProteinDomains() ) {
1152 if ( !visited_domain_ids.contains( domain.getDomainId() ) ) {
1153 visited_domain_ids.add( domain.getDomainId() );
1160 out.write( domain.getDomainId().getId() );
1162 out.write( "" + domain.getTotalCount() );
1167 out.write( separator );
1168 if ( !( ForesterUtil.isEmpty( protein.getDescription() ) || protein.getDescription()
1169 .equals( SurfacingConstants.NONE ) ) ) {
1170 out.write( protein.getDescription() );
1172 out.write( separator );
1173 if ( !( ForesterUtil.isEmpty( protein.getAccession() ) || protein.getAccession()
1174 .equals( SurfacingConstants.NONE ) ) ) {
1175 out.write( protein.getAccession() );
1177 out.write( SurfacingConstants.NL );
1184 public static void extractProteinNames( final SortedMap<Species, List<Protein>> protein_lists_per_species,
1185 final DomainId domain_id,
1187 final String separator,
1188 final String limit_to_species ) throws IOException {
1189 for( final Species species : protein_lists_per_species.keySet() ) {
1190 for( final Protein protein : protein_lists_per_species.get( species ) ) {
1191 if ( ForesterUtil.isEmpty( limit_to_species )
1192 || protein.getSpecies().getSpeciesId().equalsIgnoreCase( limit_to_species ) ) {
1193 final List<Domain> domains = protein.getProteinDomains( domain_id );
1194 if ( domains.size() > 0 ) {
1195 out.write( protein.getSpecies().getSpeciesId() );
1196 out.write( separator );
1197 out.write( protein.getProteinId().getId() );
1198 out.write( separator );
1199 out.write( domain_id.toString() );
1200 out.write( separator );
1201 for( final Domain domain : domains ) {
1203 out.write( domain.getFrom() + "-" + domain.getTo() );
1206 out.write( separator );
1208 boolean first = true;
1209 for( final Domain domain : protein.getProteinDomains() ) {
1216 out.write( domain.getDomainId().toString() );
1219 if ( !( ForesterUtil.isEmpty( protein.getDescription() ) || protein.getDescription()
1220 .equals( SurfacingConstants.NONE ) ) ) {
1221 out.write( protein.getDescription() );
1223 out.write( separator );
1224 if ( !( ForesterUtil.isEmpty( protein.getAccession() ) || protein.getAccession()
1225 .equals( SurfacingConstants.NONE ) ) ) {
1226 out.write( protein.getAccession() );
1228 out.write( SurfacingConstants.NL );
1236 public static SortedSet<DomainId> getAllDomainIds( final List<GenomeWideCombinableDomains> gwcd_list ) {
1237 final SortedSet<DomainId> all_domains_ids = new TreeSet<DomainId>();
1238 for( final GenomeWideCombinableDomains gwcd : gwcd_list ) {
1239 final Set<DomainId> all_domains = gwcd.getAllDomainIds();
1240 // for( final Domain domain : all_domains ) {
1241 all_domains_ids.addAll( all_domains );
1244 return all_domains_ids;
1247 public static SortedMap<String, Integer> getDomainCounts( final List<Protein> protein_domain_collections ) {
1248 final SortedMap<String, Integer> map = new TreeMap<String, Integer>();
1249 for( final Protein protein_domain_collection : protein_domain_collections ) {
1250 for( final Object name : protein_domain_collection.getProteinDomains() ) {
1251 final BasicDomain protein_domain = ( BasicDomain ) name;
1252 final String id = protein_domain.getDomainId().getId();
1253 if ( map.containsKey( id ) ) {
1254 map.put( id, map.get( id ) + 1 );
1264 public static int getNumberOfNodesLackingName( final Phylogeny p, final StringBuilder names ) {
1265 final PhylogenyNodeIterator it = p.iteratorPostorder();
1267 while ( it.hasNext() ) {
1268 final PhylogenyNode n = it.next();
1269 if ( ForesterUtil.isEmpty( n.getName() )
1270 && ( !n.getNodeData().isHasTaxonomy() || ForesterUtil.isEmpty( n.getNodeData().getTaxonomy()
1271 .getScientificName() ) )
1272 && ( !n.getNodeData().isHasTaxonomy() || ForesterUtil.isEmpty( n.getNodeData().getTaxonomy()
1273 .getCommonName() ) ) ) {
1274 if ( n.getParent() != null ) {
1275 names.append( " " );
1276 names.append( n.getParent().getName() );
1278 final List l = n.getAllExternalDescendants();
1279 for( final Object object : l ) {
1280 System.out.println( l.toString() );
1289 * Returns true is Domain domain falls in an uninterrupted stretch of
1290 * covered positions.
1293 * @param covered_positions
1296 public static boolean isEngulfed( final Domain domain, final List<Boolean> covered_positions ) {
1297 for( int i = domain.getFrom(); i <= domain.getTo(); ++i ) {
1298 if ( ( i >= covered_positions.size() ) || ( covered_positions.get( i ) != true ) ) {
1305 public static void preparePhylogeny( final Phylogeny p,
1306 final DomainParsimonyCalculator domain_parsimony,
1307 final String date_time,
1308 final String method,
1310 final String parameters_str ) {
1311 domain_parsimony.decoratePhylogenyWithDomains( p );
1312 final StringBuilder desc = new StringBuilder();
1313 desc.append( "[Method: " + method + "] [Date: " + date_time + "] " );
1314 desc.append( "[Cost: " + domain_parsimony.getCost() + "] " );
1315 desc.append( "[Gains: " + domain_parsimony.getTotalGains() + "] " );
1316 desc.append( "[Losses: " + domain_parsimony.getTotalLosses() + "] " );
1317 desc.append( "[Unchanged: " + domain_parsimony.getTotalUnchanged() + "] " );
1318 desc.append( "[Parameters: " + parameters_str + "]" );
1320 p.setDescription( desc.toString() );
1321 p.setConfidence( new Confidence( domain_parsimony.getCost(), "parsimony" ) );
1322 p.setRerootable( false );
1323 p.setRooted( true );
1327 * species | protein id | n-terminal domain | c-terminal domain | n-terminal domain per domain E-value | c-terminal domain per domain E-value
1331 static public StringBuffer proteinToDomainCombinations( final Protein protein,
1332 final String protein_id,
1333 final String separator ) {
1334 final StringBuffer sb = new StringBuffer();
1335 if ( protein.getSpecies() == null ) {
1336 throw new IllegalArgumentException( "species must not be null" );
1338 if ( ForesterUtil.isEmpty( protein.getSpecies().getSpeciesId() ) ) {
1339 throw new IllegalArgumentException( "species id must not be empty" );
1341 final List<Domain> domains = protein.getProteinDomains();
1342 if ( domains.size() > 1 ) {
1343 final Map<String, Integer> counts = new HashMap<String, Integer>();
1344 for( final Domain domain : domains ) {
1345 final String id = domain.getDomainId().getId();
1346 if ( counts.containsKey( id ) ) {
1347 counts.put( id, counts.get( id ) + 1 );
1350 counts.put( id, 1 );
1353 final Set<String> dcs = new HashSet<String>();
1354 for( int i = 1; i < domains.size(); ++i ) {
1355 for( int j = 0; j < i; ++j ) {
1356 Domain domain_n = domains.get( i );
1357 Domain domain_c = domains.get( j );
1358 if ( domain_n.getFrom() > domain_c.getFrom() ) {
1359 domain_n = domains.get( j );
1360 domain_c = domains.get( i );
1362 final String dc = domain_n.getDomainId().getId() + domain_c.getDomainId().getId();
1363 if ( !dcs.contains( dc ) ) {
1365 sb.append( protein.getSpecies() );
1366 sb.append( separator );
1367 sb.append( protein_id );
1368 sb.append( separator );
1369 sb.append( domain_n.getDomainId().getId() );
1370 sb.append( separator );
1371 sb.append( domain_c.getDomainId().getId() );
1372 sb.append( separator );
1373 sb.append( domain_n.getPerDomainEvalue() );
1374 sb.append( separator );
1375 sb.append( domain_c.getPerDomainEvalue() );
1376 sb.append( separator );
1377 sb.append( counts.get( domain_n.getDomainId().getId() ) );
1378 sb.append( separator );
1379 sb.append( counts.get( domain_c.getDomainId().getId() ) );
1380 sb.append( ForesterUtil.LINE_SEPARATOR );
1385 else if ( domains.size() == 1 ) {
1386 sb.append( protein.getSpecies() );
1387 sb.append( separator );
1388 sb.append( protein_id );
1389 sb.append( separator );
1390 sb.append( domains.get( 0 ).getDomainId().getId() );
1391 sb.append( separator );
1392 sb.append( separator );
1393 sb.append( domains.get( 0 ).getPerDomainEvalue() );
1394 sb.append( separator );
1395 sb.append( separator );
1397 sb.append( separator );
1398 sb.append( ForesterUtil.LINE_SEPARATOR );
1401 sb.append( protein.getSpecies() );
1402 sb.append( separator );
1403 sb.append( protein_id );
1404 sb.append( separator );
1405 sb.append( separator );
1406 sb.append( separator );
1407 sb.append( separator );
1408 sb.append( separator );
1409 sb.append( separator );
1410 sb.append( ForesterUtil.LINE_SEPARATOR );
1417 * Example regarding engulfment: ------------0.1 ----------0.2 --0.3 =>
1418 * domain with 0.3 is ignored
1420 * -----------0.1 ----------0.2 --0.3 => domain with 0.3 is ignored
1423 * ------------0.1 ----------0.3 --0.2 => domains with 0.3 and 0.2 are _not_
1426 * @param max_allowed_overlap
1427 * maximal allowed overlap (inclusive) to be still considered not
1428 * overlapping (zero or negative value to allow any overlap)
1429 * @param remove_engulfed_domains
1430 * to remove domains which are completely engulfed by coverage of
1431 * domains with better support
1435 public static Protein removeOverlappingDomains( final int max_allowed_overlap,
1436 final boolean remove_engulfed_domains,
1437 final Protein protein ) {
1438 final Protein pruned_protein = new BasicProtein( protein.getProteinId().getId(), protein.getSpecies()
1439 .getSpeciesId(), protein.getLength() );
1440 final List<Domain> sorted = SurfacingUtil.sortDomainsWithAscendingConfidenceValues( protein );
1441 final List<Boolean> covered_positions = new ArrayList<Boolean>();
1442 for( final Domain domain : sorted ) {
1443 if ( ( ( max_allowed_overlap < 0 ) || ( SurfacingUtil.calculateOverlap( domain, covered_positions ) <= max_allowed_overlap ) )
1444 && ( !remove_engulfed_domains || !isEngulfed( domain, covered_positions ) ) ) {
1445 final int covered_positions_size = covered_positions.size();
1446 for( int i = covered_positions_size; i < domain.getFrom(); ++i ) {
1447 covered_positions.add( false );
1449 final int new_covered_positions_size = covered_positions.size();
1450 for( int i = domain.getFrom(); i <= domain.getTo(); ++i ) {
1451 if ( i < new_covered_positions_size ) {
1452 covered_positions.set( i, true );
1455 covered_positions.add( true );
1458 pruned_protein.addProteinDomain( domain );
1461 return pruned_protein;
1464 public static List<Domain> sortDomainsWithAscendingConfidenceValues( final Protein protein ) {
1465 final List<Domain> domains = new ArrayList<Domain>();
1466 for( final Domain d : protein.getProteinDomains() ) {
1469 Collections.sort( domains, SurfacingUtil.ASCENDING_CONFIDENCE_VALUE_ORDER );
1473 private static List<String> splitDomainCombination( final String dc ) {
1474 final String[] s = dc.split( "=" );
1475 if ( s.length != 2 ) {
1476 ForesterUtil.printErrorMessage( surfacing.PRG_NAME, "Stringyfied domain combination has illegal format: "
1480 final List<String> l = new ArrayList<String>( 2 );
1486 public static void writeAllDomainsChangedOnAllSubtrees( final Phylogeny p,
1487 final boolean get_gains,
1488 final String outdir,
1489 final String suffix_for_filename ) throws IOException {
1490 CharacterStateMatrix.GainLossStates state = CharacterStateMatrix.GainLossStates.GAIN;
1492 state = CharacterStateMatrix.GainLossStates.LOSS;
1494 final File base_dir = createBaseDirForPerNodeDomainFiles( surfacing.BASE_DIRECTORY_PER_SUBTREE_DOMAIN_GAIN_LOSS_FILES,
1498 for( final PhylogenyNodeIterator it = p.iteratorPostorder(); it.hasNext(); ) {
1499 final PhylogenyNode node = it.next();
1500 if ( !node.isExternal() ) {
1501 final SortedSet<String> domains = collectAllDomainsChangedOnSubtree( node, get_gains );
1502 if ( domains.size() > 0 ) {
1503 final Writer writer = ForesterUtil.createBufferedWriter( base_dir + ForesterUtil.FILE_SEPARATOR
1504 + node.getName() + suffix_for_filename );
1505 for( final String domain : domains ) {
1506 writer.write( domain );
1507 writer.write( ForesterUtil.LINE_SEPARATOR );
1515 private static void writeAllEncounteredPfamsToFile( final Map<DomainId, List<GoId>> domain_id_to_go_ids_map,
1516 final Map<GoId, GoTerm> go_id_to_term_map,
1517 final String outfile_name,
1518 final SortedSet<String> all_pfams_encountered ) {
1519 final File all_pfams_encountered_file = new File( outfile_name + surfacing.ALL_PFAMS_ENCOUNTERED_SUFFIX );
1520 final File all_pfams_encountered_with_go_annotation_file = new File( outfile_name
1521 + surfacing.ALL_PFAMS_ENCOUNTERED_WITH_GO_ANNOTATION_SUFFIX );
1522 final File encountered_pfams_summary_file = new File( outfile_name + surfacing.ENCOUNTERED_PFAMS_SUMMARY_SUFFIX );
1523 int biological_process_counter = 0;
1524 int cellular_component_counter = 0;
1525 int molecular_function_counter = 0;
1526 int pfams_with_mappings_counter = 0;
1527 int pfams_without_mappings_counter = 0;
1528 int pfams_without_mappings_to_bp_or_mf_counter = 0;
1529 int pfams_with_mappings_to_bp_or_mf_counter = 0;
1531 final Writer all_pfams_encountered_writer = new BufferedWriter( new FileWriter( all_pfams_encountered_file ) );
1532 final Writer all_pfams_encountered_with_go_annotation_writer = new BufferedWriter( new FileWriter( all_pfams_encountered_with_go_annotation_file ) );
1533 final Writer summary_writer = new BufferedWriter( new FileWriter( encountered_pfams_summary_file ) );
1534 summary_writer.write( "# Pfam to GO mapping summary" );
1535 summary_writer.write( ForesterUtil.LINE_SEPARATOR );
1536 summary_writer.write( "# Actual summary is at the end of this file." );
1537 summary_writer.write( ForesterUtil.LINE_SEPARATOR );
1538 summary_writer.write( "# Encountered Pfams without a GO mapping:" );
1539 summary_writer.write( ForesterUtil.LINE_SEPARATOR );
1540 for( final String pfam : all_pfams_encountered ) {
1541 all_pfams_encountered_writer.write( pfam );
1542 all_pfams_encountered_writer.write( ForesterUtil.LINE_SEPARATOR );
1543 final DomainId domain_id = new DomainId( pfam );
1544 if ( domain_id_to_go_ids_map.containsKey( domain_id ) ) {
1545 ++pfams_with_mappings_counter;
1546 all_pfams_encountered_with_go_annotation_writer.write( pfam );
1547 all_pfams_encountered_with_go_annotation_writer.write( ForesterUtil.LINE_SEPARATOR );
1548 final List<GoId> go_ids = domain_id_to_go_ids_map.get( domain_id );
1549 boolean maps_to_bp = false;
1550 boolean maps_to_cc = false;
1551 boolean maps_to_mf = false;
1552 for( final GoId go_id : go_ids ) {
1553 final GoTerm go_term = go_id_to_term_map.get( go_id );
1554 if ( go_term.getGoNameSpace().isBiologicalProcess() ) {
1557 else if ( go_term.getGoNameSpace().isCellularComponent() ) {
1560 else if ( go_term.getGoNameSpace().isMolecularFunction() ) {
1565 ++biological_process_counter;
1568 ++cellular_component_counter;
1571 ++molecular_function_counter;
1573 if ( maps_to_bp || maps_to_mf ) {
1574 ++pfams_with_mappings_to_bp_or_mf_counter;
1577 ++pfams_without_mappings_to_bp_or_mf_counter;
1581 ++pfams_without_mappings_to_bp_or_mf_counter;
1582 ++pfams_without_mappings_counter;
1583 summary_writer.write( pfam );
1584 summary_writer.write( ForesterUtil.LINE_SEPARATOR );
1587 all_pfams_encountered_writer.close();
1588 all_pfams_encountered_with_go_annotation_writer.close();
1589 ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote all [" + all_pfams_encountered.size()
1590 + "] encountered Pfams to: \"" + all_pfams_encountered_file + "\"" );
1591 ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote all [" + pfams_with_mappings_counter
1592 + "] encountered Pfams with GO mappings to: \"" + all_pfams_encountered_with_go_annotation_file
1594 ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote summary (including all ["
1595 + pfams_without_mappings_counter + "] encountered Pfams without GO mappings) to: \""
1596 + encountered_pfams_summary_file + "\"" );
1597 ForesterUtil.programMessage( surfacing.PRG_NAME, "Sum of Pfams encountered : "
1598 + all_pfams_encountered.size() );
1599 ForesterUtil.programMessage( surfacing.PRG_NAME, "Pfams without a mapping : "
1600 + pfams_without_mappings_counter + " ["
1601 + ( 100 * pfams_without_mappings_counter / all_pfams_encountered.size() ) + "%]" );
1602 ForesterUtil.programMessage( surfacing.PRG_NAME, "Pfams without mapping to proc. or func. : "
1603 + pfams_without_mappings_to_bp_or_mf_counter + " ["
1604 + ( 100 * pfams_without_mappings_to_bp_or_mf_counter / all_pfams_encountered.size() ) + "%]" );
1605 ForesterUtil.programMessage( surfacing.PRG_NAME,
1606 "Pfams with a mapping : " + pfams_with_mappings_counter
1608 + ( 100 * pfams_with_mappings_counter / all_pfams_encountered.size() )
1610 ForesterUtil.programMessage( surfacing.PRG_NAME, "Pfams with a mapping to proc. or func. : "
1611 + pfams_with_mappings_to_bp_or_mf_counter + " ["
1612 + ( 100 * pfams_with_mappings_to_bp_or_mf_counter / all_pfams_encountered.size() ) + "%]" );
1613 ForesterUtil.programMessage( surfacing.PRG_NAME,
1614 "Pfams with mapping to biological process: " + biological_process_counter
1616 + ( 100 * biological_process_counter / all_pfams_encountered.size() )
1618 ForesterUtil.programMessage( surfacing.PRG_NAME,
1619 "Pfams with mapping to molecular function: " + molecular_function_counter
1621 + ( 100 * molecular_function_counter / all_pfams_encountered.size() )
1623 ForesterUtil.programMessage( surfacing.PRG_NAME,
1624 "Pfams with mapping to cellular component: " + cellular_component_counter
1626 + ( 100 * cellular_component_counter / all_pfams_encountered.size() )
1628 summary_writer.write( ForesterUtil.LINE_SEPARATOR );
1629 summary_writer.write( "# Sum of Pfams encountered : " + all_pfams_encountered.size() );
1630 summary_writer.write( ForesterUtil.LINE_SEPARATOR );
1631 summary_writer.write( "# Pfams without a mapping : " + pfams_without_mappings_counter
1632 + " [" + ( 100 * pfams_without_mappings_counter / all_pfams_encountered.size() ) + "%]" );
1633 summary_writer.write( ForesterUtil.LINE_SEPARATOR );
1634 summary_writer.write( "# Pfams without mapping to proc. or func. : "
1635 + pfams_without_mappings_to_bp_or_mf_counter + " ["
1636 + ( 100 * pfams_without_mappings_to_bp_or_mf_counter / all_pfams_encountered.size() ) + "%]" );
1637 summary_writer.write( ForesterUtil.LINE_SEPARATOR );
1638 summary_writer.write( "# Pfams with a mapping : " + pfams_with_mappings_counter + " ["
1639 + ( 100 * pfams_with_mappings_counter / all_pfams_encountered.size() ) + "%]" );
1640 summary_writer.write( ForesterUtil.LINE_SEPARATOR );
1641 summary_writer.write( "# Pfams with a mapping to proc. or func. : "
1642 + pfams_with_mappings_to_bp_or_mf_counter + " ["
1643 + ( 100 * pfams_with_mappings_to_bp_or_mf_counter / all_pfams_encountered.size() ) + "%]" );
1644 summary_writer.write( ForesterUtil.LINE_SEPARATOR );
1645 summary_writer.write( "# Pfams with mapping to biological process: " + biological_process_counter + " ["
1646 + ( 100 * biological_process_counter / all_pfams_encountered.size() ) + "%]" );
1647 summary_writer.write( ForesterUtil.LINE_SEPARATOR );
1648 summary_writer.write( "# Pfams with mapping to molecular function: " + molecular_function_counter + " ["
1649 + ( 100 * molecular_function_counter / all_pfams_encountered.size() ) + "%]" );
1650 summary_writer.write( ForesterUtil.LINE_SEPARATOR );
1651 summary_writer.write( "# Pfams with mapping to cellular component: " + cellular_component_counter + " ["
1652 + ( 100 * cellular_component_counter / all_pfams_encountered.size() ) + "%]" );
1653 summary_writer.write( ForesterUtil.LINE_SEPARATOR );
1654 summary_writer.close();
1656 catch ( final IOException e ) {
1657 ForesterUtil.printWarningMessage( surfacing.PRG_NAME, "Failure to write: " + e );
1661 public static void writeBinaryDomainCombinationsFileForGraphAnalysis( final String[][] input_file_properties,
1662 final File output_dir,
1663 final GenomeWideCombinableDomains gwcd,
1665 final GenomeWideCombinableDomainsSortOrder dc_sort_order ) {
1666 File dc_outfile_dot = new File( input_file_properties[ i ][ 0 ]
1667 + surfacing.DOMAIN_COMBINITONS_OUTPUTFILE_SUFFIX_FOR_GRAPH_ANALYSIS );
1668 if ( output_dir != null ) {
1669 dc_outfile_dot = new File( output_dir + ForesterUtil.FILE_SEPARATOR + dc_outfile_dot );
1671 checkForOutputFileWriteability( dc_outfile_dot );
1672 final SortedSet<BinaryDomainCombination> binary_combinations = createSetOfAllBinaryDomainCombinationsPerGenome( gwcd );
1674 final BufferedWriter out_dot = new BufferedWriter( new FileWriter( dc_outfile_dot ) );
1675 for( final BinaryDomainCombination bdc : binary_combinations ) {
1676 out_dot.write( bdc.toGraphDescribingLanguage( BinaryDomainCombination.OutputFormat.DOT, null, null )
1678 out_dot.write( SurfacingConstants.NL );
1682 catch ( final IOException e ) {
1683 ForesterUtil.fatalError( surfacing.PRG_NAME, e.getMessage() );
1685 ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote binary domain combination for \""
1686 + input_file_properties[ i ][ 0 ] + "\" (" + input_file_properties[ i ][ 1 ] + ", "
1687 + input_file_properties[ i ][ 2 ] + ") to: \"" + dc_outfile_dot + "\"" );
1690 public static void writeBinaryStatesMatrixAsListToFile( final CharacterStateMatrix<CharacterStateMatrix.GainLossStates> matrix,
1691 final CharacterStateMatrix.GainLossStates state,
1692 final String filename,
1693 final String indentifier_characters_separator,
1694 final String character_separator,
1695 final Map<String, String> descriptions ) {
1696 final File outfile = new File( filename );
1697 checkForOutputFileWriteability( outfile );
1698 final SortedSet<String> sorted_ids = new TreeSet<String>();
1699 for( int i = 0; i < matrix.getNumberOfIdentifiers(); ++i ) {
1700 sorted_ids.add( matrix.getIdentifier( i ) );
1703 final BufferedWriter out = new BufferedWriter( new FileWriter( outfile ) );
1704 for( final String id : sorted_ids ) {
1705 out.write( indentifier_characters_separator );
1706 out.write( "#" + id );
1707 out.write( indentifier_characters_separator );
1708 for( int c = 0; c < matrix.getNumberOfCharacters(); ++c ) {
1710 // using null to indicate either UNCHANGED_PRESENT or GAIN.
1711 if ( ( matrix.getState( id, c ) == state )
1712 || ( ( state == null ) && ( ( matrix.getState( id, c ) == CharacterStateMatrix.GainLossStates.GAIN ) || ( matrix
1713 .getState( id, c ) == CharacterStateMatrix.GainLossStates.UNCHANGED_PRESENT ) ) ) ) {
1714 out.write( matrix.getCharacter( c ) );
1715 if ( ( descriptions != null ) && !descriptions.isEmpty()
1716 && descriptions.containsKey( matrix.getCharacter( c ) ) ) {
1718 out.write( descriptions.get( matrix.getCharacter( c ) ) );
1720 out.write( character_separator );
1727 catch ( final IOException e ) {
1728 ForesterUtil.fatalError( surfacing.PRG_NAME, e.getMessage() );
1730 ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote characters list: \"" + filename + "\"" );
1733 public static void writeBinaryStatesMatrixAsListToFileForBinaryCombinationsForGraphAnalysis( final CharacterStateMatrix<CharacterStateMatrix.GainLossStates> matrix,
1734 final CharacterStateMatrix.GainLossStates state,
1735 final String filename,
1736 final String indentifier_characters_separator,
1737 final String character_separator,
1738 final BinaryDomainCombination.OutputFormat bc_output_format ) {
1739 final File outfile = new File( filename );
1740 checkForOutputFileWriteability( outfile );
1741 final SortedSet<String> sorted_ids = new TreeSet<String>();
1742 for( int i = 0; i < matrix.getNumberOfIdentifiers(); ++i ) {
1743 sorted_ids.add( matrix.getIdentifier( i ) );
1746 final BufferedWriter out = new BufferedWriter( new FileWriter( outfile ) );
1747 for( final String id : sorted_ids ) {
1748 out.write( indentifier_characters_separator );
1749 out.write( "#" + id );
1750 out.write( indentifier_characters_separator );
1751 for( int c = 0; c < matrix.getNumberOfCharacters(); ++c ) {
1753 // using null to indicate either UNCHANGED_PRESENT or GAIN.
1754 if ( ( matrix.getState( id, c ) == state )
1755 || ( ( state == null ) && ( ( matrix.getState( id, c ) == CharacterStateMatrix.GainLossStates.GAIN ) || ( matrix
1756 .getState( id, c ) == CharacterStateMatrix.GainLossStates.UNCHANGED_PRESENT ) ) ) ) {
1757 BinaryDomainCombination bdc = null;
1759 bdc = BasicBinaryDomainCombination.createInstance( matrix.getCharacter( c ) );
1761 catch ( final Exception e ) {
1762 ForesterUtil.fatalError( surfacing.PRG_NAME, e.getLocalizedMessage() );
1764 out.write( bdc.toGraphDescribingLanguage( bc_output_format, null, null ).toString() );
1765 out.write( character_separator );
1772 catch ( final IOException e ) {
1773 ForesterUtil.fatalError( surfacing.PRG_NAME, e.getMessage() );
1775 ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote characters list: \"" + filename + "\"" );
1778 public static void writeBinaryStatesMatrixToList( final Map<DomainId, List<GoId>> domain_id_to_go_ids_map,
1779 final Map<GoId, GoTerm> go_id_to_term_map,
1780 final GoNameSpace go_namespace_limit,
1781 final boolean domain_combinations,
1782 final CharacterStateMatrix<CharacterStateMatrix.GainLossStates> matrix,
1783 final CharacterStateMatrix.GainLossStates state,
1784 final String filename,
1785 final String indentifier_characters_separator,
1786 final String character_separator,
1787 final String title_for_html,
1788 final String prefix_for_html,
1789 final Map<DomainId, Set<String>>[] domain_id_to_secondary_features_maps,
1790 final SortedSet<String> all_pfams_encountered,
1791 final SortedSet<String> pfams_gained_or_lost,
1792 final String suffix_for_per_node_events_file ) {
1793 if ( ( go_namespace_limit != null ) && ( ( go_id_to_term_map == null ) || ( go_id_to_term_map.size() < 1 ) ) ) {
1794 throw new IllegalArgumentException( "attempt to use GO namespace limit without a GO-id to term map" );
1796 else if ( ( ( domain_id_to_go_ids_map == null ) || ( domain_id_to_go_ids_map.size() < 1 ) ) ) {
1797 throw new IllegalArgumentException( "attempt to output detailed HTML without a Pfam to GO map" );
1799 else if ( ( ( go_id_to_term_map == null ) || ( go_id_to_term_map.size() < 1 ) ) ) {
1800 throw new IllegalArgumentException( "attempt to output detailed HTML without a GO-id to term map" );
1802 final File outfile = new File( filename );
1803 checkForOutputFileWriteability( outfile );
1804 final SortedSet<String> sorted_ids = new TreeSet<String>();
1805 for( int i = 0; i < matrix.getNumberOfIdentifiers(); ++i ) {
1806 sorted_ids.add( matrix.getIdentifier( i ) );
1809 final Writer out = new BufferedWriter( new FileWriter( outfile ) );
1810 final File per_node_go_mapped_domain_gain_loss_files_base_dir = createBaseDirForPerNodeDomainFiles( surfacing.BASE_DIRECTORY_PER_NODE_DOMAIN_GAIN_LOSS_FILES,
1811 domain_combinations,
1814 Writer per_node_go_mapped_domain_gain_loss_outfile_writer = null;
1815 File per_node_go_mapped_domain_gain_loss_outfile = null;
1816 int per_node_counter = 0;
1817 out.write( "<html>" );
1818 out.write( SurfacingConstants.NL );
1819 addHtmlHead( out, title_for_html );
1820 out.write( SurfacingConstants.NL );
1821 out.write( "<body>" );
1822 out.write( SurfacingConstants.NL );
1823 out.write( "<h1>" );
1824 out.write( SurfacingConstants.NL );
1825 out.write( title_for_html );
1826 out.write( SurfacingConstants.NL );
1827 out.write( "</h1>" );
1828 out.write( SurfacingConstants.NL );
1829 out.write( "<table>" );
1830 out.write( SurfacingConstants.NL );
1831 for( final String id : sorted_ids ) {
1832 final Matcher matcher = PATTERN_SP_STYLE_TAXONOMY.matcher( id );
1833 if ( matcher.matches() ) {
1836 out.write( "<tr>" );
1837 out.write( "<td>" );
1838 out.write( "<a href=\"#" + id + "\">" + id + "</a>" );
1839 out.write( "</td>" );
1840 out.write( "</tr>" );
1841 out.write( SurfacingConstants.NL );
1843 out.write( "</table>" );
1844 out.write( SurfacingConstants.NL );
1845 for( final String id : sorted_ids ) {
1846 final Matcher matcher = PATTERN_SP_STYLE_TAXONOMY.matcher( id );
1847 if ( matcher.matches() ) {
1850 out.write( SurfacingConstants.NL );
1851 out.write( "<h2>" );
1852 out.write( "<a name=\"" + id + "\">" + id + "</a>" );
1853 writeTaxonomyLinks( out, id );
1854 out.write( "</h2>" );
1855 out.write( SurfacingConstants.NL );
1856 out.write( "<table>" );
1857 out.write( SurfacingConstants.NL );
1858 out.write( "<tr>" );
1859 out.write( "<td><b>" );
1860 out.write( "Pfam domain(s)" );
1861 out.write( "</b></td><td><b>" );
1862 out.write( "GO term acc" );
1863 out.write( "</b></td><td><b>" );
1864 out.write( "GO term" );
1865 out.write( "</b></td><td><b>" );
1866 out.write( "GO namespace" );
1867 out.write( "</b></td>" );
1868 out.write( "</tr>" );
1869 out.write( SurfacingConstants.NL );
1870 out.write( "</tr>" );
1871 out.write( SurfacingConstants.NL );
1872 per_node_counter = 0;
1873 if ( matrix.getNumberOfCharacters() > 0 ) {
1874 per_node_go_mapped_domain_gain_loss_outfile = new File( per_node_go_mapped_domain_gain_loss_files_base_dir
1875 + ForesterUtil.FILE_SEPARATOR + id + suffix_for_per_node_events_file );
1876 SurfacingUtil.checkForOutputFileWriteability( per_node_go_mapped_domain_gain_loss_outfile );
1877 per_node_go_mapped_domain_gain_loss_outfile_writer = ForesterUtil
1878 .createBufferedWriter( per_node_go_mapped_domain_gain_loss_outfile );
1881 per_node_go_mapped_domain_gain_loss_outfile = null;
1882 per_node_go_mapped_domain_gain_loss_outfile_writer = null;
1884 for( int c = 0; c < matrix.getNumberOfCharacters(); ++c ) {
1886 // using null to indicate either UNCHANGED_PRESENT or GAIN.
1887 if ( ( matrix.getState( id, c ) == state )
1888 || ( ( state == null ) && ( ( matrix.getState( id, c ) == CharacterStateMatrix.GainLossStates.UNCHANGED_PRESENT ) || ( matrix
1889 .getState( id, c ) == CharacterStateMatrix.GainLossStates.GAIN ) ) ) ) {
1890 final String character = matrix.getCharacter( c );
1891 String domain_0 = "";
1892 String domain_1 = "";
1893 if ( character.indexOf( BinaryDomainCombination.SEPARATOR ) > 0 ) {
1894 final String[] s = character.split( BinaryDomainCombination.SEPARATOR );
1895 if ( s.length != 2 ) {
1896 throw new AssertionError( "this should not have happened: unexpected format for domain combination: ["
1897 + character + "]" );
1903 domain_0 = character;
1905 writeDomainData( domain_id_to_go_ids_map,
1912 character_separator,
1913 domain_id_to_secondary_features_maps,
1915 all_pfams_encountered.add( domain_0 );
1916 if ( pfams_gained_or_lost != null ) {
1917 pfams_gained_or_lost.add( domain_0 );
1919 if ( !ForesterUtil.isEmpty( domain_1 ) ) {
1920 all_pfams_encountered.add( domain_1 );
1921 if ( pfams_gained_or_lost != null ) {
1922 pfams_gained_or_lost.add( domain_1 );
1925 if ( per_node_go_mapped_domain_gain_loss_outfile_writer != null ) {
1926 writeDomainsToIndividualFilePerTreeNode( per_node_go_mapped_domain_gain_loss_outfile_writer,
1933 if ( per_node_go_mapped_domain_gain_loss_outfile_writer != null ) {
1934 per_node_go_mapped_domain_gain_loss_outfile_writer.close();
1935 if ( per_node_counter < 1 ) {
1936 per_node_go_mapped_domain_gain_loss_outfile.delete();
1938 per_node_counter = 0;
1940 out.write( "</table>" );
1941 out.write( SurfacingConstants.NL );
1942 out.write( "<hr>" );
1943 out.write( SurfacingConstants.NL );
1944 } // for( final String id : sorted_ids ) {
1945 out.write( "</body>" );
1946 out.write( SurfacingConstants.NL );
1947 out.write( "</html>" );
1948 out.write( SurfacingConstants.NL );
1952 catch ( final IOException e ) {
1953 ForesterUtil.fatalError( surfacing.PRG_NAME, e.getMessage() );
1955 ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote characters detailed HTML list: \"" + filename + "\"" );
1958 public static void writeDomainCombinationsCountsFile( final String[][] input_file_properties,
1959 final File output_dir,
1960 final Writer per_genome_domain_promiscuity_statistics_writer,
1961 final GenomeWideCombinableDomains gwcd,
1963 final GenomeWideCombinableDomains.GenomeWideCombinableDomainsSortOrder dc_sort_order ) {
1964 File dc_outfile = new File( input_file_properties[ i ][ 0 ]
1965 + surfacing.DOMAIN_COMBINITON_COUNTS_OUTPUTFILE_SUFFIX );
1966 if ( output_dir != null ) {
1967 dc_outfile = new File( output_dir + ForesterUtil.FILE_SEPARATOR + dc_outfile );
1969 checkForOutputFileWriteability( dc_outfile );
1971 final BufferedWriter out = new BufferedWriter( new FileWriter( dc_outfile ) );
1972 out.write( gwcd.toStringBuilder( dc_sort_order ).toString() );
1975 catch ( final IOException e ) {
1976 ForesterUtil.fatalError( surfacing.PRG_NAME, e.getMessage() );
1978 final DescriptiveStatistics stats = gwcd.getPerGenomeDomainPromiscuityStatistics();
1980 per_genome_domain_promiscuity_statistics_writer.write( input_file_properties[ i ][ 0 ] + "\t" );
1981 per_genome_domain_promiscuity_statistics_writer.write( FORMATTER_3.format( stats.arithmeticMean() ) + "\t" );
1982 if ( stats.getN() < 2 ) {
1983 per_genome_domain_promiscuity_statistics_writer.write( "n/a" + "\t" );
1986 per_genome_domain_promiscuity_statistics_writer.write( FORMATTER_3.format( stats
1987 .sampleStandardDeviation() ) + "\t" );
1989 per_genome_domain_promiscuity_statistics_writer.write( FORMATTER_3.format( stats.median() ) + "\t" );
1990 per_genome_domain_promiscuity_statistics_writer.write( ( int ) stats.getMin() + "\t" );
1991 per_genome_domain_promiscuity_statistics_writer.write( ( int ) stats.getMax() + "\t" );
1992 per_genome_domain_promiscuity_statistics_writer.write( stats.getN() + "\t" );
1993 final SortedSet<DomainId> mpds = gwcd.getMostPromiscuosDomain();
1994 for( final DomainId mpd : mpds ) {
1995 per_genome_domain_promiscuity_statistics_writer.write( mpd.getId() + " " );
1997 per_genome_domain_promiscuity_statistics_writer.write( ForesterUtil.LINE_SEPARATOR );
1999 catch ( final IOException e ) {
2000 ForesterUtil.fatalError( surfacing.PRG_NAME, e.getMessage() );
2002 if ( input_file_properties[ i ].length == 3 ) {
2003 ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote domain combination counts for \""
2004 + input_file_properties[ i ][ 0 ] + "\" (" + input_file_properties[ i ][ 1 ] + ", "
2005 + input_file_properties[ i ][ 2 ] + ") to: \"" + dc_outfile + "\"" );
2008 ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote domain combination counts for \""
2009 + input_file_properties[ i ][ 0 ] + "\" (" + input_file_properties[ i ][ 1 ] + ") to: \""
2010 + dc_outfile + "\"" );
2014 private static void writeDomainData( final Map<DomainId, List<GoId>> domain_id_to_go_ids_map,
2015 final Map<GoId, GoTerm> go_id_to_term_map,
2016 final GoNameSpace go_namespace_limit,
2018 final String domain_0,
2019 final String domain_1,
2020 final String prefix_for_html,
2021 final String character_separator_for_non_html_output,
2022 final Map<DomainId, Set<String>>[] domain_id_to_secondary_features_maps,
2023 final Set<GoId> all_go_ids ) throws IOException {
2024 boolean any_go_annotation_present = false;
2025 boolean first_has_no_go = false;
2026 int domain_count = 2; // To distinguish between domains and binary domain combinations.
2027 if ( ForesterUtil.isEmpty( domain_1 ) ) {
2030 // The following has a difficult to understand logic.
2031 for( int d = 0; d < domain_count; ++d ) {
2032 List<GoId> go_ids = null;
2033 boolean go_annotation_present = false;
2035 final DomainId domain_id = new DomainId( domain_0 );
2036 if ( domain_id_to_go_ids_map.containsKey( domain_id ) ) {
2037 go_annotation_present = true;
2038 any_go_annotation_present = true;
2039 go_ids = domain_id_to_go_ids_map.get( domain_id );
2042 first_has_no_go = true;
2046 final DomainId domain_id = new DomainId( domain_1 );
2047 if ( domain_id_to_go_ids_map.containsKey( domain_id ) ) {
2048 go_annotation_present = true;
2049 any_go_annotation_present = true;
2050 go_ids = domain_id_to_go_ids_map.get( domain_id );
2053 if ( go_annotation_present ) {
2054 boolean first = ( ( d == 0 ) || ( ( d == 1 ) && first_has_no_go ) );
2055 for( final GoId go_id : go_ids ) {
2056 out.write( "<tr>" );
2059 writeDomainIdsToHtml( out,
2063 domain_id_to_secondary_features_maps );
2066 out.write( "<td></td>" );
2068 if ( !go_id_to_term_map.containsKey( go_id ) ) {
2069 throw new IllegalArgumentException( "GO-id [" + go_id + "] not found in GO-id to GO-term map" );
2071 final GoTerm go_term = go_id_to_term_map.get( go_id );
2072 if ( ( go_namespace_limit == null ) || go_namespace_limit.equals( go_term.getGoNameSpace() ) ) {
2073 // final String top = GoUtils.getPenultimateGoTerm( go_term, go_id_to_term_map ).getName();
2074 final String go_id_str = go_id.getId();
2075 out.write( "<td>" );
2076 out.write( "<a href=\"" + SurfacingConstants.AMIGO_LINK + go_id_str
2077 + "\" target=\"amigo_window\">" + go_id_str + "</a>" );
2078 out.write( "</td><td>" );
2079 out.write( go_term.getName() );
2080 if ( domain_count == 2 ) {
2081 out.write( " (" + d + ")" );
2083 out.write( "</td><td>" );
2084 // out.write( top );
2085 // out.write( "</td><td>" );
2087 out.write( go_term.getGoNameSpace().toShortString() );
2089 out.write( "</td>" );
2090 if ( all_go_ids != null ) {
2091 all_go_ids.add( go_id );
2095 out.write( "<td>" );
2096 out.write( "</td><td>" );
2097 out.write( "</td><td>" );
2098 out.write( "</td><td>" );
2099 out.write( "</td>" );
2101 out.write( "</tr>" );
2102 out.write( SurfacingConstants.NL );
2105 } // for( int d = 0; d < domain_count; ++d )
2106 if ( !any_go_annotation_present ) {
2107 out.write( "<tr>" );
2108 writeDomainIdsToHtml( out, domain_0, domain_1, prefix_for_html, domain_id_to_secondary_features_maps );
2109 out.write( "<td>" );
2110 out.write( "</td><td>" );
2111 out.write( "</td><td>" );
2112 out.write( "</td><td>" );
2113 out.write( "</td>" );
2114 out.write( "</tr>" );
2115 out.write( SurfacingConstants.NL );
2119 private static void writeDomainIdsToHtml( final Writer out,
2120 final String domain_0,
2121 final String domain_1,
2122 final String prefix_for_detailed_html,
2123 final Map<DomainId, Set<String>>[] domain_id_to_secondary_features_maps )
2124 throws IOException {
2125 out.write( "<td>" );
2126 if ( !ForesterUtil.isEmpty( prefix_for_detailed_html ) ) {
2127 out.write( prefix_for_detailed_html );
2130 out.write( "<a href=\"" + SurfacingConstants.PFAM_FAMILY_ID_LINK + domain_0 + "\">" + domain_0 + "</a>" );
2131 out.write( "</td>" );
2134 public static DescriptiveStatistics writeDomainSimilaritiesToFile( final StringBuilder html_desc,
2135 final StringBuilder html_title,
2136 final Writer single_writer,
2137 Map<Character, Writer> split_writers,
2138 final SortedSet<DomainSimilarity> similarities,
2139 final boolean treat_as_binary,
2140 final List<Species> species_order,
2141 final PrintableDomainSimilarity.PRINT_OPTION print_option,
2142 final DomainSimilarity.DomainSimilaritySortField sort_field,
2143 final DomainSimilarity.DomainSimilarityScoring scoring,
2144 final boolean verbose ) throws IOException {
2145 final DescriptiveStatistics stats = new BasicDescriptiveStatistics();
2146 String histogram_title = null;
2147 switch ( sort_field ) {
2148 case ABS_MAX_COUNTS_DIFFERENCE:
2149 if ( treat_as_binary ) {
2150 histogram_title = "absolute counts difference:";
2153 histogram_title = "absolute (maximal) counts difference:";
2156 case MAX_COUNTS_DIFFERENCE:
2157 if ( treat_as_binary ) {
2158 histogram_title = "counts difference:";
2161 histogram_title = "(maximal) counts difference:";
2165 histogram_title = "score mean:";
2168 histogram_title = "score minimum:";
2171 histogram_title = "score maximum:";
2173 case MAX_DIFFERENCE:
2174 if ( treat_as_binary ) {
2175 histogram_title = "difference:";
2178 histogram_title = "(maximal) difference:";
2182 histogram_title = "score mean:";
2185 histogram_title = "score standard deviation:";
2188 histogram_title = "species number:";
2191 throw new AssertionError( "Unknown sort field: " + sort_field );
2193 for( final DomainSimilarity similarity : similarities ) {
2194 switch ( sort_field ) {
2195 case ABS_MAX_COUNTS_DIFFERENCE:
2196 stats.addValue( Math.abs( similarity.getMaximalDifferenceInCounts() ) );
2198 case MAX_COUNTS_DIFFERENCE:
2199 stats.addValue( similarity.getMaximalDifferenceInCounts() );
2202 stats.addValue( similarity.getMeanSimilarityScore() );
2205 stats.addValue( similarity.getMinimalSimilarityScore() );
2208 stats.addValue( similarity.getMaximalSimilarityScore() );
2210 case MAX_DIFFERENCE:
2211 stats.addValue( similarity.getMaximalDifference() );
2214 stats.addValue( similarity.getMeanSimilarityScore() );
2217 stats.addValue( similarity.getStandardDeviationOfSimilarityScore() );
2220 stats.addValue( similarity.getSpecies().size() );
2223 throw new AssertionError( "Unknown sort field: " + sort_field );
2227 // final HistogramData[] hists = new HistogramData[ 1 ];
2230 // List<HistogramDataItem> data_items = new
2231 // ArrayList<HistogramDataItem>();
2232 // double[] values = stats.getDataAsDoubleArray();
2233 // for( int i = 0; i < values.length; i++ ) {
2234 // HistogramDataItem data_item = new BasicHistogramDataItem( "", values[
2236 // data_items.add( data_item );
2240 // HistogramData hd0 = new HistogramData( "name",
2248 // hists[ 0 ] = hd0;
2250 // final HistogramsFrame hf = new HistogramsFrame( hists );
2251 // hf.setVisible( true );
2253 AsciiHistogram histo = null;
2254 if ( stats.getMin() < stats.getMin() ) {
2255 histo = new AsciiHistogram( stats, histogram_title );
2258 if ( histo != null ) {
2259 System.out.println( histo.toStringBuffer( 20, '|', 40, 5 ) );
2261 System.out.println();
2262 System.out.println( "N : " + stats.getN() );
2263 System.out.println( "Min : " + stats.getMin() );
2264 System.out.println( "Max : " + stats.getMax() );
2265 System.out.println( "Mean : " + stats.arithmeticMean() );
2266 if ( stats.getN() > 1 ) {
2267 System.out.println( "SD : " + stats.sampleStandardDeviation() );
2270 System.out.println( "SD : n/a" );
2272 System.out.println( "Median : " + stats.median() );
2273 if ( stats.getN() > 1 ) {
2274 System.out.println( "Pearsonian skewness : " + stats.pearsonianSkewness() );
2277 System.out.println( "Pearsonian skewness : n/a" );
2280 if ( ( single_writer != null ) && ( ( split_writers == null ) || split_writers.isEmpty() ) ) {
2281 split_writers = new HashMap<Character, Writer>();
2282 split_writers.put( '_', single_writer );
2284 switch ( print_option ) {
2285 case SIMPLE_TAB_DELIMITED:
2288 for( final Character key : split_writers.keySet() ) {
2289 final Writer w = split_writers.get( key );
2290 w.write( "<html>" );
2291 w.write( SurfacingConstants.NL );
2293 addHtmlHead( w, "DCs (" + html_title + ") " + key.toString().toUpperCase() );
2296 addHtmlHead( w, "DCs (" + html_title + ")" );
2298 w.write( SurfacingConstants.NL );
2299 w.write( "<body>" );
2300 w.write( SurfacingConstants.NL );
2301 w.write( html_desc.toString() );
2302 w.write( SurfacingConstants.NL );
2305 w.write( SurfacingConstants.NL );
2306 w.write( "<tt><pre>" );
2307 w.write( SurfacingConstants.NL );
2308 if ( histo != null ) {
2309 w.write( histo.toStringBuffer( 20, '|', 40, 5 ).toString() );
2310 w.write( SurfacingConstants.NL );
2312 w.write( "</pre></tt>" );
2313 w.write( SurfacingConstants.NL );
2314 w.write( "<table>" );
2315 w.write( SurfacingConstants.NL );
2316 w.write( "<tr><td>N: </td><td>" + stats.getN() + "</td></tr>" );
2317 w.write( SurfacingConstants.NL );
2318 w.write( "<tr><td>Min: </td><td>" + stats.getMin() + "</td></tr>" );
2319 w.write( SurfacingConstants.NL );
2320 w.write( "<tr><td>Max: </td><td>" + stats.getMax() + "</td></tr>" );
2321 w.write( SurfacingConstants.NL );
2322 w.write( "<tr><td>Mean: </td><td>" + stats.arithmeticMean() + "</td></tr>" );
2323 w.write( SurfacingConstants.NL );
2324 if ( stats.getN() > 1 ) {
2325 w.write( "<tr><td>SD: </td><td>" + stats.sampleStandardDeviation() + "</td></tr>" );
2328 w.write( "<tr><td>SD: </td><td>n/a</td></tr>" );
2330 w.write( SurfacingConstants.NL );
2331 w.write( "<tr><td>Median: </td><td>" + stats.median() + "</td></tr>" );
2332 w.write( SurfacingConstants.NL );
2333 if ( stats.getN() > 1 ) {
2334 w.write( "<tr><td>Pearsonian skewness: </td><td>" + stats.pearsonianSkewness() + "</td></tr>" );
2337 w.write( "<tr><td>Pearsonian skewness: </td><td>n/a</td></tr>" );
2339 w.write( SurfacingConstants.NL );
2340 w.write( "</table>" );
2341 w.write( SurfacingConstants.NL );
2343 w.write( SurfacingConstants.NL );
2345 w.write( SurfacingConstants.NL );
2347 w.write( SurfacingConstants.NL );
2348 w.write( "<table>" );
2349 w.write( SurfacingConstants.NL );
2353 for( final Writer w : split_writers.values() ) {
2354 w.write( SurfacingConstants.NL );
2356 for( final DomainSimilarity similarity : similarities ) {
2357 if ( ( species_order != null ) && !species_order.isEmpty() ) {
2358 ( ( PrintableDomainSimilarity ) similarity ).setSpeciesOrder( species_order );
2360 if ( single_writer != null ) {
2361 single_writer.write( similarity.toStringBuffer( print_option ).toString() );
2364 Writer local_writer = split_writers.get( ( similarity.getDomainId().getId().charAt( 0 ) + "" )
2365 .toLowerCase().charAt( 0 ) );
2366 if ( local_writer == null ) {
2367 local_writer = split_writers.get( '0' );
2369 local_writer.write( similarity.toStringBuffer( print_option ).toString() );
2371 for( final Writer w : split_writers.values() ) {
2372 w.write( SurfacingConstants.NL );
2375 switch ( print_option ) {
2377 for( final Writer w : split_writers.values() ) {
2378 w.write( SurfacingConstants.NL );
2379 w.write( "</table>" );
2380 w.write( SurfacingConstants.NL );
2381 w.write( "</font>" );
2382 w.write( SurfacingConstants.NL );
2383 w.write( "</body>" );
2384 w.write( SurfacingConstants.NL );
2385 w.write( "</html>" );
2386 w.write( SurfacingConstants.NL );
2390 for( final Writer w : split_writers.values() ) {
2396 private static void writeDomainsToIndividualFilePerTreeNode( final Writer individual_files_writer,
2397 final String domain_0,
2398 final String domain_1 ) throws IOException {
2399 individual_files_writer.write( domain_0 );
2400 individual_files_writer.write( ForesterUtil.LINE_SEPARATOR );
2401 if ( !ForesterUtil.isEmpty( domain_1 ) ) {
2402 individual_files_writer.write( domain_1 );
2403 individual_files_writer.write( ForesterUtil.LINE_SEPARATOR );
2407 public static void writeMatrixToFile( final CharacterStateMatrix<?> matrix,
2408 final String filename,
2409 final Format format ) {
2410 final File outfile = new File( filename );
2411 checkForOutputFileWriteability( outfile );
2413 final BufferedWriter out = new BufferedWriter( new FileWriter( outfile ) );
2414 matrix.toWriter( out, format );
2418 catch ( final IOException e ) {
2419 ForesterUtil.fatalError( surfacing.PRG_NAME, e.getMessage() );
2421 ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote matrix: \"" + filename + "\"" );
2424 public static void writeMatrixToFile( final File matrix_outfile, final List<DistanceMatrix> matrices ) {
2425 checkForOutputFileWriteability( matrix_outfile );
2427 final BufferedWriter out = new BufferedWriter( new FileWriter( matrix_outfile ) );
2428 for( final DistanceMatrix distance_matrix : matrices ) {
2429 out.write( distance_matrix.toStringBuffer( DistanceMatrix.Format.PHYLIP ).toString() );
2430 out.write( ForesterUtil.LINE_SEPARATOR );
2435 catch ( final IOException e ) {
2436 ForesterUtil.fatalError( surfacing.PRG_NAME, e.getMessage() );
2438 ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote distance matrices to \"" + matrix_outfile + "\"" );
2441 private static void writePfamsToFile( final String outfile_name, final SortedSet<String> pfams ) {
2443 final Writer writer = new BufferedWriter( new FileWriter( new File( outfile_name ) ) );
2444 for( final String pfam : pfams ) {
2445 writer.write( pfam );
2446 writer.write( ForesterUtil.LINE_SEPARATOR );
2449 ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote " + pfams.size() + " pfams to [" + outfile_name
2452 catch ( final IOException e ) {
2453 ForesterUtil.printWarningMessage( surfacing.PRG_NAME, "Failure to write: " + e );
2457 public static void writePhylogenyToFile( final Phylogeny phylogeny, final String filename ) {
2458 final PhylogenyWriter writer = new PhylogenyWriter();
2460 writer.toPhyloXML( new File( filename ), phylogeny, 1 );
2462 catch ( final IOException e ) {
2463 ForesterUtil.printWarningMessage( surfacing.PRG_NAME, "failed to write phylogeny to \"" + filename + "\": "
2466 ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote phylogeny to \"" + filename + "\"" );
2469 public static void writeTaxonomyLinks( final Writer writer, final String species ) throws IOException {
2470 if ( ( species.length() > 1 ) && ( species.indexOf( '_' ) < 1 ) ) {
2471 final Matcher matcher = PATTERN_SP_STYLE_TAXONOMY.matcher( species );
2472 writer.write( " [" );
2473 if ( matcher.matches() ) {
2474 writer.write( "<a href=\"" + SurfacingConstants.UNIPROT_LINK + species
2475 + "\" target=\"taxonomy_window\">uniprot</a>" );
2478 writer.write( "<a href=\"" + SurfacingConstants.EOL_LINK + species
2479 + "\" target=\"taxonomy_window\">eol</a>" );
2480 writer.write( "|" );
2481 writer.write( "<a href=\"" + SurfacingConstants.TOL_LINK + species
2482 + "\" target=\"taxonomy_window\">tol</a>" );
2484 writer.write( "]" );
2488 private static void writeToNexus( final String outfile_name,
2489 final CharacterStateMatrix<BinaryStates> matrix,
2490 final Phylogeny phylogeny ) {
2491 if ( !( matrix instanceof BasicCharacterStateMatrix ) ) {
2492 throw new IllegalArgumentException( "can only write matrices of type [" + BasicCharacterStateMatrix.class
2495 final BasicCharacterStateMatrix<BinaryStates> my_matrix = ( org.forester.evoinference.matrix.character.BasicCharacterStateMatrix<BinaryStates> ) matrix;
2496 final List<Phylogeny> phylogenies = new ArrayList<Phylogeny>( 1 );
2497 phylogenies.add( phylogeny );
2499 final BufferedWriter w = new BufferedWriter( new FileWriter( outfile_name ) );
2500 w.write( NexusConstants.NEXUS );
2501 w.write( ForesterUtil.LINE_SEPARATOR );
2502 my_matrix.writeNexusTaxaBlock( w );
2503 my_matrix.writeNexusBinaryChractersBlock( w );
2504 PhylogenyWriter.writeNexusTreesBlock( w, phylogenies, NH_CONVERSION_SUPPORT_VALUE_STYLE.NONE );
2507 ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote Nexus file: \"" + outfile_name + "\"" );
2509 catch ( final IOException e ) {
2510 ForesterUtil.fatalError( surfacing.PRG_NAME, e.getMessage() );
2514 private static void writeToNexus( final String outfile_name,
2515 final DomainParsimonyCalculator domain_parsimony,
2516 final Phylogeny phylogeny ) {
2517 writeToNexus( outfile_name + surfacing.NEXUS_EXTERNAL_DOMAINS,
2518 domain_parsimony.createMatrixOfDomainPresenceOrAbsence(),
2520 writeToNexus( outfile_name + surfacing.NEXUS_EXTERNAL_DOMAIN_COMBINATIONS,
2521 domain_parsimony.createMatrixOfBinaryDomainCombinationPresenceOrAbsence(),
2525 public static void domainsPerProteinsStatistics( final String genome,
2526 final List<Protein> protein_list,
2527 final DescriptiveStatistics all_genomes_domains_per_potein_stats,
2528 final SortedMap<Integer, Integer> all_genomes_domains_per_potein_histo,
2529 final SortedSet<String> domains_which_are_always_single,
2530 final SortedSet<String> domains_which_are_sometimes_single_sometimes_not,
2531 final SortedSet<String> domains_which_never_single,
2532 final Writer writer ) {
2533 final DescriptiveStatistics stats = new BasicDescriptiveStatistics();
2534 for( final Protein protein : protein_list ) {
2535 final int domains = protein.getNumberOfProteinDomains();
2536 //System.out.println( domains );
2537 stats.addValue( domains );
2538 all_genomes_domains_per_potein_stats.addValue( domains );
2539 if ( !all_genomes_domains_per_potein_histo.containsKey( domains ) ) {
2540 all_genomes_domains_per_potein_histo.put( domains, 1 );
2543 all_genomes_domains_per_potein_histo.put( domains,
2544 1 + all_genomes_domains_per_potein_histo.get( domains ) );
2546 if ( domains == 1 ) {
2547 final String domain = protein.getProteinDomain( 0 ).getDomainId().getId();
2548 if ( !domains_which_are_sometimes_single_sometimes_not.contains( domain ) ) {
2549 if ( domains_which_never_single.contains( domain ) ) {
2550 domains_which_never_single.remove( domain );
2551 domains_which_are_sometimes_single_sometimes_not.add( domain );
2554 domains_which_are_always_single.add( domain );
2558 else if ( domains > 1 ) {
2559 for( final Domain d : protein.getProteinDomains() ) {
2560 final String domain = d.getDomainId().getId();
2561 // System.out.println( domain );
2562 if ( !domains_which_are_sometimes_single_sometimes_not.contains( domain ) ) {
2563 if ( domains_which_are_always_single.contains( domain ) ) {
2564 domains_which_are_always_single.remove( domain );
2565 domains_which_are_sometimes_single_sometimes_not.add( domain );
2568 domains_which_never_single.add( domain );
2575 writer.write( genome );
2576 writer.write( "\t" );
2577 if ( stats.getN() >= 1 ) {
2578 writer.write( stats.arithmeticMean() + "" );
2579 writer.write( "\t" );
2580 if ( stats.getN() >= 2 ) {
2581 writer.write( stats.sampleStandardDeviation() + "" );
2586 writer.write( "\t" );
2587 writer.write( stats.median() + "" );
2588 writer.write( "\t" );
2589 writer.write( stats.getN() + "" );
2590 writer.write( "\t" );
2591 writer.write( stats.getMin() + "" );
2592 writer.write( "\t" );
2593 writer.write( stats.getMax() + "" );
2596 writer.write( "\t" );
2597 writer.write( "\t" );
2598 writer.write( "\t" );
2599 writer.write( "0" );
2600 writer.write( "\t" );
2601 writer.write( "\t" );
2603 writer.write( "\n" );
2605 catch ( final IOException e ) {
2606 e.printStackTrace();