3 // FORESTER -- software libraries and applications
4 // for evolutionary biology research and applications.
6 // Copyright (C) 2008-2009 Christian M. Zmasek
7 // Copyright (C) 2008-2009 Burnham Institute for Medical Research
10 // This library is free software; you can redistribute it and/or
11 // modify it under the terms of the GNU Lesser General Public
12 // License as published by the Free Software Foundation; either
13 // version 2.1 of the License, or (at your option) any later version.
15 // This library is distributed in the hope that it will be useful,
16 // but WITHOUT ANY WARRANTY; without even the implied warranty of
17 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
18 // Lesser General Public License for more details.
20 // You should have received a copy of the GNU Lesser General Public
21 // License along with this library; if not, write to the Free Software
22 // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
24 // Contact: phylosoft @ gmail . com
25 // WWW: www.phylosoft.org/forester
27 package org.forester.surfacing;
29 import java.io.BufferedWriter;
31 import java.io.FileWriter;
32 import java.io.IOException;
33 import java.io.Writer;
34 import java.text.DecimalFormat;
35 import java.text.NumberFormat;
36 import java.util.ArrayList;
37 import java.util.Arrays;
38 import java.util.Collections;
39 import java.util.Comparator;
40 import java.util.HashMap;
41 import java.util.HashSet;
42 import java.util.List;
44 import java.util.PriorityQueue;
46 import java.util.SortedMap;
47 import java.util.SortedSet;
48 import java.util.TreeMap;
49 import java.util.TreeSet;
50 import java.util.regex.Matcher;
51 import java.util.regex.Pattern;
53 import org.forester.application.surfacing;
54 import org.forester.evoinference.distance.NeighborJoining;
55 import org.forester.evoinference.matrix.character.BasicCharacterStateMatrix;
56 import org.forester.evoinference.matrix.character.CharacterStateMatrix;
57 import org.forester.evoinference.matrix.character.CharacterStateMatrix.BinaryStates;
58 import org.forester.evoinference.matrix.character.CharacterStateMatrix.Format;
59 import org.forester.evoinference.matrix.character.CharacterStateMatrix.GainLossStates;
60 import org.forester.evoinference.matrix.distance.DistanceMatrix;
61 import org.forester.go.GoId;
62 import org.forester.go.GoNameSpace;
63 import org.forester.go.GoTerm;
64 import org.forester.go.PfamToGoMapping;
65 import org.forester.io.parsers.nexus.NexusConstants;
66 import org.forester.io.writers.PhylogenyWriter;
67 import org.forester.phylogeny.Phylogeny;
68 import org.forester.phylogeny.PhylogenyMethods;
69 import org.forester.phylogeny.PhylogenyNode;
70 import org.forester.phylogeny.data.BinaryCharacters;
71 import org.forester.phylogeny.data.Confidence;
72 import org.forester.phylogeny.iterators.PhylogenyNodeIterator;
73 import org.forester.surfacing.DomainSimilarityCalculator.Detailedness;
74 import org.forester.surfacing.DomainSimilarityCalculator.GoAnnotationOutput;
75 import org.forester.surfacing.GenomeWideCombinableDomains.GenomeWideCombinableDomainsSortOrder;
76 import org.forester.util.AsciiHistogram;
77 import org.forester.util.BasicDescriptiveStatistics;
78 import org.forester.util.BasicTable;
79 import org.forester.util.BasicTableParser;
80 import org.forester.util.DescriptiveStatistics;
81 import org.forester.util.ForesterUtil;
83 public final class SurfacingUtil {
85 private final static NumberFormat FORMATTER = new DecimalFormat( "0.0E0" );
86 private final static NumberFormat FORMATTER_3 = new DecimalFormat( "0.000" );
87 private static final Comparator<Domain> ASCENDING_CONFIDENCE_VALUE_ORDER = new Comparator<Domain>() {
90 public int compare( final Domain d1,
92 if ( d1.getPerSequenceEvalue() < d2
93 .getPerSequenceEvalue() ) {
97 .getPerSequenceEvalue() > d2
98 .getPerSequenceEvalue() ) {
102 return d1.compareTo( d2 );
106 public final static Pattern PATTERN_SP_STYLE_TAXONOMY = Pattern.compile( "^[A-Z0-9]{3,5}$" );
108 private SurfacingUtil() {
109 // Hidden constructor.
112 public static void addAllBinaryDomainCombinationToSet( final GenomeWideCombinableDomains genome,
113 final SortedSet<BinaryDomainCombination> binary_domain_combinations ) {
114 final SortedMap<DomainId, CombinableDomains> all_cd = genome.getAllCombinableDomainsIds();
115 for( final DomainId domain_id : all_cd.keySet() ) {
116 binary_domain_combinations.addAll( all_cd.get( domain_id ).toBinaryDomainCombinations() );
120 public static void addAllDomainIdsToSet( final GenomeWideCombinableDomains genome,
121 final SortedSet<DomainId> domain_ids ) {
122 final SortedSet<DomainId> domains = genome.getAllDomainIds();
123 for( final DomainId domain : domains ) {
124 domain_ids.add( domain );
128 public static void addHtmlHead( final Writer w, final String title ) throws IOException {
129 w.write( SurfacingConstants.NL );
131 w.write( "<title>" );
133 w.write( "</title>" );
134 w.write( SurfacingConstants.NL );
135 w.write( "<style>" );
136 w.write( SurfacingConstants.NL );
137 w.write( "a:visited { color : #6633FF; text-decoration : none; }" );
138 w.write( SurfacingConstants.NL );
139 w.write( "a:link { color : #6633FF; text-decoration : none; }" );
140 w.write( SurfacingConstants.NL );
141 w.write( "a:active { color : #99FF00; text-decoration : none; }" );
142 w.write( SurfacingConstants.NL );
143 w.write( "a:hover { color : #FFFFFF; background-color : #99FF00; text-decoration : none; }" );
144 w.write( SurfacingConstants.NL );
145 w.write( "td { text-align: left; vertical-align: top; font-family: Verdana, Arial, Helvetica; font-size: 8pt}" );
146 w.write( SurfacingConstants.NL );
147 w.write( "h1 { color : #0000FF; font-family: Verdana, Arial, Helvetica; font-size: 18pt; font-weight: bold }" );
148 w.write( SurfacingConstants.NL );
149 w.write( "h2 { color : #0000FF; font-family: Verdana, Arial, Helvetica; font-size: 16pt; font-weight: bold }" );
150 w.write( SurfacingConstants.NL );
151 w.write( "</style>" );
152 w.write( SurfacingConstants.NL );
153 w.write( "</head>" );
154 w.write( SurfacingConstants.NL );
157 public static DescriptiveStatistics calculateDescriptiveStatisticsForMeanValues( final Set<DomainSimilarity> similarities ) {
158 final DescriptiveStatistics stats = new BasicDescriptiveStatistics();
159 for( final DomainSimilarity similarity : similarities ) {
160 stats.addValue( similarity.getMeanSimilarityScore() );
165 private static void calculateIndependentDomainCombinationGains( final Phylogeny local_phylogeny_l,
166 final String outfilename_for_counts,
167 final String outfilename_for_dc,
168 final String outfilename_for_dc_for_go_mapping,
169 final String outfilename_for_dc_for_go_mapping_unique ) {
171 final BufferedWriter out_counts = new BufferedWriter( new FileWriter( outfilename_for_counts ) );
172 final BufferedWriter out_dc = new BufferedWriter( new FileWriter( outfilename_for_dc ) );
173 final BufferedWriter out_dc_for_go_mapping = new BufferedWriter( new FileWriter( outfilename_for_dc_for_go_mapping ) );
174 final BufferedWriter out_dc_for_go_mapping_unique = new BufferedWriter( new FileWriter( outfilename_for_dc_for_go_mapping_unique ) );
175 final SortedMap<String, Integer> dc_gain_counts = new TreeMap<String, Integer>();
176 for( final PhylogenyNodeIterator it = local_phylogeny_l.iteratorPostorder(); it.hasNext(); ) {
177 final PhylogenyNode n = it.next();
178 final Set<String> gained_dc = n.getNodeData().getBinaryCharacters().getGainedCharacters();
179 for( final String dc : gained_dc ) {
180 if ( dc_gain_counts.containsKey( dc ) ) {
181 dc_gain_counts.put( dc, dc_gain_counts.get( dc ) + 1 );
184 dc_gain_counts.put( dc, 1 );
188 final SortedMap<Integer, Integer> histogram = new TreeMap<Integer, Integer>();
189 final SortedMap<Integer, StringBuilder> domain_lists = new TreeMap<Integer, StringBuilder>();
190 final SortedMap<Integer, PriorityQueue<String>> domain_lists_go = new TreeMap<Integer, PriorityQueue<String>>();
191 final SortedMap<Integer, SortedSet<String>> domain_lists_go_unique = new TreeMap<Integer, SortedSet<String>>();
192 final Set<String> dcs = dc_gain_counts.keySet();
193 for( final String dc : dcs ) {
194 final int count = dc_gain_counts.get( dc );
195 if ( histogram.containsKey( count ) ) {
196 histogram.put( count, histogram.get( count ) + 1 );
197 domain_lists.get( count ).append( ", " + dc );
198 domain_lists_go.get( count ).addAll( splitDomainCombination( dc ) );
199 domain_lists_go_unique.get( count ).addAll( splitDomainCombination( dc ) );
202 histogram.put( count, 1 );
203 domain_lists.put( count, new StringBuilder( dc ) );
204 final PriorityQueue<String> q = new PriorityQueue<String>();
205 q.addAll( splitDomainCombination( dc ) );
206 domain_lists_go.put( count, q );
207 final SortedSet<String> set = new TreeSet<String>();
208 set.addAll( splitDomainCombination( dc ) );
209 domain_lists_go_unique.put( count, set );
212 final Set<Integer> histogram_keys = histogram.keySet();
213 for( final Integer histogram_key : histogram_keys ) {
214 final int count = histogram.get( histogram_key );
215 final StringBuilder dc = domain_lists.get( histogram_key );
216 out_counts.write( histogram_key + "\t" + count + ForesterUtil.LINE_SEPARATOR );
217 out_dc.write( histogram_key + "\t" + dc + ForesterUtil.LINE_SEPARATOR );
218 out_dc_for_go_mapping.write( "#" + histogram_key + ForesterUtil.LINE_SEPARATOR );
219 final Object[] sorted = domain_lists_go.get( histogram_key ).toArray();
220 Arrays.sort( sorted );
221 for( final Object domain : sorted ) {
222 out_dc_for_go_mapping.write( domain + ForesterUtil.LINE_SEPARATOR );
224 out_dc_for_go_mapping_unique.write( "#" + histogram_key + ForesterUtil.LINE_SEPARATOR );
225 for( final String domain : domain_lists_go_unique.get( histogram_key ) ) {
226 out_dc_for_go_mapping_unique.write( domain + ForesterUtil.LINE_SEPARATOR );
231 out_dc_for_go_mapping.close();
232 out_dc_for_go_mapping_unique.close();
234 catch ( final IOException e ) {
235 ForesterUtil.printWarningMessage( surfacing.PRG_NAME, "Failure to write: " + e );
237 ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote independent domain combination gains fitch counts to ["
238 + outfilename_for_counts + "]" );
239 ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote independent domain combination gains fitch lists to ["
240 + outfilename_for_dc + "]" );
241 ForesterUtil.programMessage( surfacing.PRG_NAME,
242 "Wrote independent domain combination gains fitch lists to (for GO mapping) ["
243 + outfilename_for_dc_for_go_mapping + "]" );
244 ForesterUtil.programMessage( surfacing.PRG_NAME,
245 "Wrote independent domain combination gains fitch lists to (for GO mapping, unique) ["
246 + outfilename_for_dc_for_go_mapping_unique + "]" );
249 public static int calculateOverlap( final Domain domain, final List<Boolean> covered_positions ) {
250 int overlap_count = 0;
251 for( int i = domain.getFrom(); i <= domain.getTo(); ++i ) {
252 if ( ( i < covered_positions.size() ) && ( covered_positions.get( i ) == true ) ) {
256 return overlap_count;
259 public static void checkForOutputFileWriteability( final File outfile ) {
260 final String error = ForesterUtil.isWritableFile( outfile );
261 if ( !ForesterUtil.isEmpty( error ) ) {
262 ForesterUtil.fatalError( surfacing.PRG_NAME, error );
266 private static SortedSet<String> collectAllDomainsChangedOnSubtree( final PhylogenyNode subtree_root,
267 final boolean get_gains ) {
268 final SortedSet<String> domains = new TreeSet<String>();
269 for( final PhylogenyNode descendant : PhylogenyMethods.getAllDescendants( subtree_root ) ) {
270 final BinaryCharacters chars = descendant.getNodeData().getBinaryCharacters();
272 domains.addAll( chars.getGainedCharacters() );
275 domains.addAll( chars.getLostCharacters() );
281 public static void collectChangedDomainCombinationsFromBinaryStatesMatrixAsListToFile( final CharacterStateMatrix<CharacterStateMatrix.GainLossStates> matrix,
282 final BinaryDomainCombination.DomainCombinationType dc_type,
283 final List<BinaryDomainCombination> all_binary_domains_combination_gained,
284 final boolean get_gains ) {
285 final SortedSet<String> sorted_ids = new TreeSet<String>();
286 for( int i = 0; i < matrix.getNumberOfIdentifiers(); ++i ) {
287 sorted_ids.add( matrix.getIdentifier( i ) );
289 for( final String id : sorted_ids ) {
290 for( int c = 0; c < matrix.getNumberOfCharacters(); ++c ) {
291 if ( ( get_gains && ( matrix.getState( id, c ) == CharacterStateMatrix.GainLossStates.GAIN ) )
292 || ( !get_gains && ( matrix.getState( id, c ) == CharacterStateMatrix.GainLossStates.LOSS ) ) ) {
293 if ( dc_type == BinaryDomainCombination.DomainCombinationType.DIRECTED_ADJACTANT ) {
294 all_binary_domains_combination_gained.add( AdjactantDirectedBinaryDomainCombination
295 .createInstance( matrix.getCharacter( c ) ) );
297 else if ( dc_type == BinaryDomainCombination.DomainCombinationType.DIRECTED ) {
298 all_binary_domains_combination_gained.add( DirectedBinaryDomainCombination
299 .createInstance( matrix.getCharacter( c ) ) );
302 all_binary_domains_combination_gained.add( BasicBinaryDomainCombination.createInstance( matrix
303 .getCharacter( c ) ) );
310 private static File createBaseDirForPerNodeDomainFiles( final String base_dir,
311 final boolean domain_combinations,
312 final CharacterStateMatrix.GainLossStates state,
313 final String outfile ) {
314 File per_node_go_mapped_domain_gain_loss_files_base_dir = new File( new File( outfile ).getParent()
315 + ForesterUtil.FILE_SEPARATOR + base_dir );
316 if ( !per_node_go_mapped_domain_gain_loss_files_base_dir.exists() ) {
317 per_node_go_mapped_domain_gain_loss_files_base_dir.mkdir();
319 if ( domain_combinations ) {
320 per_node_go_mapped_domain_gain_loss_files_base_dir = new File( per_node_go_mapped_domain_gain_loss_files_base_dir
321 + ForesterUtil.FILE_SEPARATOR + "DC" );
324 per_node_go_mapped_domain_gain_loss_files_base_dir = new File( per_node_go_mapped_domain_gain_loss_files_base_dir
325 + ForesterUtil.FILE_SEPARATOR + "DOMAINS" );
327 if ( !per_node_go_mapped_domain_gain_loss_files_base_dir.exists() ) {
328 per_node_go_mapped_domain_gain_loss_files_base_dir.mkdir();
330 if ( state == GainLossStates.GAIN ) {
331 per_node_go_mapped_domain_gain_loss_files_base_dir = new File( per_node_go_mapped_domain_gain_loss_files_base_dir
332 + ForesterUtil.FILE_SEPARATOR + "GAINS" );
334 else if ( state == GainLossStates.LOSS ) {
335 per_node_go_mapped_domain_gain_loss_files_base_dir = new File( per_node_go_mapped_domain_gain_loss_files_base_dir
336 + ForesterUtil.FILE_SEPARATOR + "LOSSES" );
339 per_node_go_mapped_domain_gain_loss_files_base_dir = new File( per_node_go_mapped_domain_gain_loss_files_base_dir
340 + ForesterUtil.FILE_SEPARATOR + "PRESENT" );
342 if ( !per_node_go_mapped_domain_gain_loss_files_base_dir.exists() ) {
343 per_node_go_mapped_domain_gain_loss_files_base_dir.mkdir();
345 return per_node_go_mapped_domain_gain_loss_files_base_dir;
348 public static Map<DomainId, List<GoId>> createDomainIdToGoIdMap( final List<PfamToGoMapping> pfam_to_go_mappings ) {
349 final Map<DomainId, List<GoId>> domain_id_to_go_ids_map = new HashMap<DomainId, List<GoId>>( pfam_to_go_mappings
351 for( final PfamToGoMapping pfam_to_go : pfam_to_go_mappings ) {
352 if ( !domain_id_to_go_ids_map.containsKey( pfam_to_go.getKey() ) ) {
353 domain_id_to_go_ids_map.put( pfam_to_go.getKey(), new ArrayList<GoId>() );
355 domain_id_to_go_ids_map.get( pfam_to_go.getKey() ).add( pfam_to_go.getValue() );
357 return domain_id_to_go_ids_map;
360 public static Map<DomainId, Set<String>> createDomainIdToSecondaryFeaturesMap( final File secondary_features_map_file )
362 final BasicTable<String> primary_table = BasicTableParser.parse( secondary_features_map_file, "\t" );
363 final Map<DomainId, Set<String>> map = new TreeMap<DomainId, Set<String>>();
364 for( int r = 0; r < primary_table.getNumberOfRows(); ++r ) {
365 final DomainId domain_id = new DomainId( primary_table.getValue( 0, r ) );
366 if ( !map.containsKey( domain_id ) ) {
367 map.put( domain_id, new HashSet<String>() );
369 map.get( domain_id ).add( primary_table.getValue( 1, r ) );
374 public static Phylogeny createNjTreeBasedOnMatrixToFile( final File nj_tree_outfile, final DistanceMatrix distance ) {
375 checkForOutputFileWriteability( nj_tree_outfile );
376 final NeighborJoining nj = NeighborJoining.createInstance();
377 final Phylogeny phylogeny = nj.execute( distance );
378 phylogeny.setName( nj_tree_outfile.getName() );
379 writePhylogenyToFile( phylogeny, nj_tree_outfile.toString() );
383 private static SortedSet<BinaryDomainCombination> createSetOfAllBinaryDomainCombinationsPerGenome( final GenomeWideCombinableDomains gwcd ) {
384 final SortedMap<DomainId, CombinableDomains> cds = gwcd.getAllCombinableDomainsIds();
385 final SortedSet<BinaryDomainCombination> binary_combinations = new TreeSet<BinaryDomainCombination>();
386 for( final DomainId domain_id : cds.keySet() ) {
387 final CombinableDomains cd = cds.get( domain_id );
388 binary_combinations.addAll( cd.toBinaryDomainCombinations() );
390 return binary_combinations;
393 public static void decoratePrintableDomainSimilarities( final SortedSet<DomainSimilarity> domain_similarities,
394 final Detailedness detailedness,
395 final GoAnnotationOutput go_annotation_output,
396 final Map<GoId, GoTerm> go_id_to_term_map,
397 final GoNameSpace go_namespace_limit ) {
398 if ( ( go_namespace_limit != null ) && ( ( go_id_to_term_map == null ) || go_id_to_term_map.isEmpty() ) ) {
399 throw new IllegalArgumentException( "attempt to use a GO namespace limit without a GO id to term map" );
401 for( final DomainSimilarity domain_similarity : domain_similarities ) {
402 if ( domain_similarity instanceof PrintableDomainSimilarity ) {
403 final PrintableDomainSimilarity printable_domain_similarity = ( PrintableDomainSimilarity ) domain_similarity;
404 printable_domain_similarity.setDetailedness( detailedness );
405 printable_domain_similarity.setGoAnnotationOutput( go_annotation_output );
406 printable_domain_similarity.setGoIdToTermMap( go_id_to_term_map );
407 printable_domain_similarity.setGoNamespaceLimit( go_namespace_limit );
412 public static void executeDomainLengthAnalysis( final String[][] input_file_properties,
413 final int number_of_genomes,
414 final DomainLengthsTable domain_lengths_table,
415 final File outfile ) throws IOException {
416 final DecimalFormat df = new DecimalFormat( "#.00" );
417 checkForOutputFileWriteability( outfile );
418 final BufferedWriter out = new BufferedWriter( new FileWriter( outfile ) );
419 out.write( "MEAN BASED STATISTICS PER SPECIES" );
420 out.write( ForesterUtil.LINE_SEPARATOR );
421 out.write( domain_lengths_table.createMeanBasedStatisticsPerSpeciesTable().toString() );
422 out.write( ForesterUtil.LINE_SEPARATOR );
423 out.write( ForesterUtil.LINE_SEPARATOR );
424 final List<DomainLengths> domain_lengths_list = domain_lengths_table.getDomainLengthsList();
425 out.write( "OUTLIER SPECIES PER DOMAIN (Z>=1.5)" );
426 out.write( ForesterUtil.LINE_SEPARATOR );
427 for( final DomainLengths domain_lengths : domain_lengths_list ) {
428 final List<Species> species_list = domain_lengths.getMeanBasedOutlierSpecies( 1.5 );
429 if ( species_list.size() > 0 ) {
430 out.write( domain_lengths.getDomainId() + "\t" );
431 for( final Species species : species_list ) {
432 out.write( species + "\t" );
434 out.write( ForesterUtil.LINE_SEPARATOR );
435 // DescriptiveStatistics stats_for_domain = domain_lengths
436 // .calculateMeanBasedStatistics();
437 //AsciiHistogram histo = new AsciiHistogram( stats_for_domain );
438 //System.out.println( histo.toStringBuffer( 40, '=', 60, 4 ).toString() );
441 out.write( ForesterUtil.LINE_SEPARATOR );
442 out.write( ForesterUtil.LINE_SEPARATOR );
443 out.write( "OUTLIER SPECIES (Z 1.0)" );
444 out.write( ForesterUtil.LINE_SEPARATOR );
445 final DescriptiveStatistics stats_for_all_species = domain_lengths_table
446 .calculateMeanBasedStatisticsForAllSpecies();
447 out.write( stats_for_all_species.asSummary() );
448 out.write( ForesterUtil.LINE_SEPARATOR );
449 final AsciiHistogram histo = new AsciiHistogram( stats_for_all_species );
450 out.write( histo.toStringBuffer( 40, '=', 60, 4 ).toString() );
451 out.write( ForesterUtil.LINE_SEPARATOR );
452 final double population_sd = stats_for_all_species.sampleStandardDeviation();
453 final double population_mean = stats_for_all_species.arithmeticMean();
454 for( final Species species : domain_lengths_table.getSpecies() ) {
455 final double x = domain_lengths_table.calculateMeanBasedStatisticsForSpecies( species ).arithmeticMean();
456 final double z = ( x - population_mean ) / population_sd;
457 out.write( species + "\t" + z );
458 out.write( ForesterUtil.LINE_SEPARATOR );
460 out.write( ForesterUtil.LINE_SEPARATOR );
461 for( final Species species : domain_lengths_table.getSpecies() ) {
462 final DescriptiveStatistics stats_for_species = domain_lengths_table
463 .calculateMeanBasedStatisticsForSpecies( species );
464 final double x = stats_for_species.arithmeticMean();
465 final double z = ( x - population_mean ) / population_sd;
466 if ( ( z <= -1.0 ) || ( z >= 1.0 ) ) {
467 out.write( species + "\t" + df.format( z ) + "\t" + stats_for_species.asSummary() );
468 out.write( ForesterUtil.LINE_SEPARATOR );
472 // final List<HistogramData> histogram_datas = new ArrayList<HistogramData>();
473 // for( int i = 0; i < number_of_genomes; ++i ) {
474 // final Species species = new BasicSpecies( input_file_properties[ i ][ 0 ] );
476 // .add( new HistogramData( species.toString(), domain_lengths_table
477 // .calculateMeanBasedStatisticsForSpecies( species )
478 // .getDataAsDoubleArray(), 5, 600, null, 60 ) );
480 // final HistogramsFrame hf = new HistogramsFrame( histogram_datas );
481 // hf.setVisible( true );
487 * @param all_binary_domains_combination_lost_fitch
488 * @param consider_directedness_and_adjacency_for_bin_combinations
489 * @param all_binary_domains_combination_gained if null ignored, otherwise this is to list all binary domain combinations
490 * which were gained under unweighted (Fitch) parsimony.
492 public static void executeParsimonyAnalysis( final long random_number_seed_for_fitch_parsimony,
493 final boolean radomize_fitch_parsimony,
494 final String outfile_name,
495 final DomainParsimonyCalculator domain_parsimony,
496 final Phylogeny phylogeny,
497 final Map<DomainId, List<GoId>> domain_id_to_go_ids_map,
498 final Map<GoId, GoTerm> go_id_to_term_map,
499 final GoNameSpace go_namespace_limit,
500 final String parameters_str,
501 final Map<DomainId, Set<String>>[] domain_id_to_secondary_features_maps,
502 final SortedSet<DomainId> positive_filter,
503 final boolean output_binary_domain_combinations_for_graphs,
504 final List<BinaryDomainCombination> all_binary_domains_combination_gained_fitch,
505 final List<BinaryDomainCombination> all_binary_domains_combination_lost_fitch,
506 final BinaryDomainCombination.DomainCombinationType dc_type ) {
507 final String sep = ForesterUtil.LINE_SEPARATOR + "###################" + ForesterUtil.LINE_SEPARATOR;
508 final String date_time = ForesterUtil.getCurrentDateTime();
509 final SortedSet<String> all_pfams_encountered = new TreeSet<String>();
510 final SortedSet<String> all_pfams_gained_as_domains = new TreeSet<String>();
511 final SortedSet<String> all_pfams_lost_as_domains = new TreeSet<String>();
512 final SortedSet<String> all_pfams_gained_as_dom_combinations = new TreeSet<String>();
513 final SortedSet<String> all_pfams_lost_as_dom_combinations = new TreeSet<String>();
514 writeToNexus( outfile_name, domain_parsimony, phylogeny );
517 Phylogeny local_phylogeny_l = phylogeny.copy();
518 if ( ( positive_filter != null ) && ( positive_filter.size() > 0 ) ) {
519 domain_parsimony.executeDolloParsimonyOnDomainPresence( positive_filter );
522 domain_parsimony.executeDolloParsimonyOnDomainPresence();
524 SurfacingUtil.writeMatrixToFile( domain_parsimony.getGainLossMatrix(), outfile_name
525 + surfacing.PARSIMONY_OUTPUT_GL_SUFFIX_DOLLO_DOMAINS, Format.FORESTER );
526 SurfacingUtil.writeMatrixToFile( domain_parsimony.getGainLossCountsMatrix(), outfile_name
527 + surfacing.PARSIMONY_OUTPUT_GL_COUNTS_SUFFIX_DOLLO_DOMAINS, Format.FORESTER );
528 SurfacingUtil.writeBinaryStatesMatrixAsListToFile( domain_parsimony.getGainLossMatrix(),
529 CharacterStateMatrix.GainLossStates.GAIN,
530 outfile_name + surfacing.PARSIMONY_OUTPUT_DOLLO_GAINS_D,
532 ForesterUtil.LINE_SEPARATOR,
534 SurfacingUtil.writeBinaryStatesMatrixAsListToFile( domain_parsimony.getGainLossMatrix(),
535 CharacterStateMatrix.GainLossStates.LOSS,
536 outfile_name + surfacing.PARSIMONY_OUTPUT_DOLLO_LOSSES_D,
538 ForesterUtil.LINE_SEPARATOR,
540 SurfacingUtil.writeBinaryStatesMatrixAsListToFile( domain_parsimony.getGainLossMatrix(), null, outfile_name
541 + surfacing.PARSIMONY_OUTPUT_DOLLO_PRESENT_D, sep, ForesterUtil.LINE_SEPARATOR, null );
543 writeBinaryStatesMatrixToList( domain_id_to_go_ids_map,
547 domain_parsimony.getGainLossMatrix(),
548 CharacterStateMatrix.GainLossStates.GAIN,
549 outfile_name + surfacing.PARSIMONY_OUTPUT_DOLLO_GAINS_HTML_D,
551 ForesterUtil.LINE_SEPARATOR,
552 "Dollo Parsimony | Gains | Domains",
554 domain_id_to_secondary_features_maps,
555 all_pfams_encountered,
556 all_pfams_gained_as_domains,
558 writeBinaryStatesMatrixToList( domain_id_to_go_ids_map,
562 domain_parsimony.getGainLossMatrix(),
563 CharacterStateMatrix.GainLossStates.LOSS,
564 outfile_name + surfacing.PARSIMONY_OUTPUT_DOLLO_LOSSES_HTML_D,
566 ForesterUtil.LINE_SEPARATOR,
567 "Dollo Parsimony | Losses | Domains",
569 domain_id_to_secondary_features_maps,
570 all_pfams_encountered,
571 all_pfams_lost_as_domains,
573 writeBinaryStatesMatrixToList( domain_id_to_go_ids_map,
577 domain_parsimony.getGainLossMatrix(),
579 outfile_name + surfacing.PARSIMONY_OUTPUT_DOLLO_PRESENT_HTML_D,
581 ForesterUtil.LINE_SEPARATOR,
582 "Dollo Parsimony | Present | Domains",
584 domain_id_to_secondary_features_maps,
585 all_pfams_encountered,
587 "_dollo_present_d" );
588 preparePhylogeny( local_phylogeny_l,
591 "Dollo parsimony on domain presence/absence",
592 "dollo_on_domains_" + outfile_name,
594 SurfacingUtil.writePhylogenyToFile( local_phylogeny_l, outfile_name
595 + surfacing.DOMAINS_PARSIMONY_TREE_OUTPUT_SUFFIX_DOLLO );
597 writeAllDomainsChangedOnAllSubtrees( local_phylogeny_l, true, outfile_name, "_dollo_all_gains_d" );
598 writeAllDomainsChangedOnAllSubtrees( local_phylogeny_l, false, outfile_name, "_dollo_all_losses_d" );
600 catch ( final IOException e ) {
602 ForesterUtil.fatalError( surfacing.PRG_NAME, e.getLocalizedMessage() );
604 if ( domain_parsimony.calculateNumberOfBinaryDomainCombination() > 0 ) {
605 // FITCH DOMAIN COMBINATIONS
606 // -------------------------
607 local_phylogeny_l = phylogeny.copy();
608 String randomization = "no";
609 if ( radomize_fitch_parsimony ) {
610 domain_parsimony.executeFitchParsimonyOnBinaryDomainCombintion( random_number_seed_for_fitch_parsimony );
611 randomization = "yes, seed = " + random_number_seed_for_fitch_parsimony;
614 domain_parsimony.executeFitchParsimonyOnBinaryDomainCombintion( false );
616 SurfacingUtil.writeMatrixToFile( domain_parsimony.getGainLossMatrix(), outfile_name
617 + surfacing.PARSIMONY_OUTPUT_GL_SUFFIX_FITCH_BINARY_COMBINATIONS, Format.FORESTER );
618 SurfacingUtil.writeMatrixToFile( domain_parsimony.getGainLossCountsMatrix(), outfile_name
619 + surfacing.PARSIMONY_OUTPUT_GL_COUNTS_SUFFIX_FITCH_BINARY_COMBINATIONS, Format.FORESTER );
621 .writeBinaryStatesMatrixAsListToFile( domain_parsimony.getGainLossMatrix(),
622 CharacterStateMatrix.GainLossStates.GAIN,
623 outfile_name + surfacing.PARSIMONY_OUTPUT_FITCH_GAINS_BC,
625 ForesterUtil.LINE_SEPARATOR,
627 SurfacingUtil.writeBinaryStatesMatrixAsListToFile( domain_parsimony.getGainLossMatrix(),
628 CharacterStateMatrix.GainLossStates.LOSS,
630 + surfacing.PARSIMONY_OUTPUT_FITCH_LOSSES_BC,
632 ForesterUtil.LINE_SEPARATOR,
634 SurfacingUtil.writeBinaryStatesMatrixAsListToFile( domain_parsimony.getGainLossMatrix(), null, outfile_name
635 + surfacing.PARSIMONY_OUTPUT_FITCH_PRESENT_BC, sep, ForesterUtil.LINE_SEPARATOR, null );
636 if ( all_binary_domains_combination_gained_fitch != null ) {
637 collectChangedDomainCombinationsFromBinaryStatesMatrixAsListToFile( domain_parsimony.getGainLossMatrix(),
639 all_binary_domains_combination_gained_fitch,
642 if ( all_binary_domains_combination_lost_fitch != null ) {
643 collectChangedDomainCombinationsFromBinaryStatesMatrixAsListToFile( domain_parsimony.getGainLossMatrix(),
645 all_binary_domains_combination_lost_fitch,
648 if ( output_binary_domain_combinations_for_graphs ) {
650 .writeBinaryStatesMatrixAsListToFileForBinaryCombinationsForGraphAnalysis( domain_parsimony
651 .getGainLossMatrix(),
654 + surfacing.PARSIMONY_OUTPUT_FITCH_PRESENT_BC_OUTPUTFILE_SUFFIX_FOR_GRAPH_ANALYSIS,
656 ForesterUtil.LINE_SEPARATOR,
657 BinaryDomainCombination.OutputFormat.DOT );
660 writeBinaryStatesMatrixToList( domain_id_to_go_ids_map,
664 domain_parsimony.getGainLossMatrix(),
665 CharacterStateMatrix.GainLossStates.GAIN,
666 outfile_name + surfacing.PARSIMONY_OUTPUT_FITCH_GAINS_HTML_BC,
668 ForesterUtil.LINE_SEPARATOR,
669 "Fitch Parsimony | Gains | Domain Combinations",
672 all_pfams_encountered,
673 all_pfams_gained_as_dom_combinations,
675 writeBinaryStatesMatrixToList( domain_id_to_go_ids_map,
679 domain_parsimony.getGainLossMatrix(),
680 CharacterStateMatrix.GainLossStates.LOSS,
681 outfile_name + surfacing.PARSIMONY_OUTPUT_FITCH_LOSSES_HTML_BC,
683 ForesterUtil.LINE_SEPARATOR,
684 "Fitch Parsimony | Losses | Domain Combinations",
687 all_pfams_encountered,
688 all_pfams_lost_as_dom_combinations,
689 "_fitch_losses_dc" );
690 writeBinaryStatesMatrixToList( domain_id_to_go_ids_map,
694 domain_parsimony.getGainLossMatrix(),
696 outfile_name + surfacing.PARSIMONY_OUTPUT_FITCH_PRESENT_HTML_BC,
698 ForesterUtil.LINE_SEPARATOR,
699 "Fitch Parsimony | Present | Domain Combinations",
702 all_pfams_encountered,
704 "_fitch_present_dc" );
705 writeAllEncounteredPfamsToFile( domain_id_to_go_ids_map,
708 all_pfams_encountered );
709 writePfamsToFile( outfile_name + surfacing.ALL_PFAMS_GAINED_AS_DOMAINS_SUFFIX, all_pfams_gained_as_domains );
710 writePfamsToFile( outfile_name + surfacing.ALL_PFAMS_LOST_AS_DOMAINS_SUFFIX, all_pfams_lost_as_domains );
711 writePfamsToFile( outfile_name + surfacing.ALL_PFAMS_GAINED_AS_DC_SUFFIX,
712 all_pfams_gained_as_dom_combinations );
713 writePfamsToFile( outfile_name + surfacing.ALL_PFAMS_LOST_AS_DC_SUFFIX, all_pfams_lost_as_dom_combinations );
714 preparePhylogeny( local_phylogeny_l,
717 "Fitch parsimony on binary domain combination presence/absence randomization: "
719 "fitch_on_binary_domain_combinations_" + outfile_name,
721 SurfacingUtil.writePhylogenyToFile( local_phylogeny_l, outfile_name
722 + surfacing.BINARY_DOMAIN_COMBINATIONS_PARSIMONY_TREE_OUTPUT_SUFFIX_FITCH );
723 calculateIndependentDomainCombinationGains( local_phylogeny_l, outfile_name
724 + surfacing.INDEPENDENT_DC_GAINS_FITCH_PARS_COUNTS_OUTPUT_SUFFIX, outfile_name
725 + surfacing.INDEPENDENT_DC_GAINS_FITCH_PARS_DC_OUTPUT_SUFFIX, outfile_name
726 + surfacing.INDEPENDENT_DC_GAINS_FITCH_PARS_DC_FOR_GO_MAPPING_OUTPUT_SUFFIX, outfile_name
727 + surfacing.INDEPENDENT_DC_GAINS_FITCH_PARS_DC_FOR_GO_MAPPING_OUTPUT_UNIQUE_SUFFIX );
731 public static void executeParsimonyAnalysisForSecondaryFeatures( final String outfile_name,
732 final DomainParsimonyCalculator secondary_features_parsimony,
733 final Phylogeny phylogeny,
734 final String parameters_str,
735 final Map<Species, MappingResults> mapping_results_map ) {
736 final String sep = ForesterUtil.LINE_SEPARATOR + "###################" + ForesterUtil.LINE_SEPARATOR;
737 final String date_time = ForesterUtil.getCurrentDateTime();
738 System.out.println();
739 writeToNexus( outfile_name + surfacing.NEXUS_SECONDARY_FEATURES,
740 secondary_features_parsimony.createMatrixOfSecondaryFeaturePresenceOrAbsence( null ),
742 final Phylogeny local_phylogeny_copy = phylogeny.copy();
743 secondary_features_parsimony.executeDolloParsimonyOnSecondaryFeatures( mapping_results_map );
744 SurfacingUtil.writeMatrixToFile( secondary_features_parsimony.getGainLossMatrix(), outfile_name
745 + surfacing.PARSIMONY_OUTPUT_GL_SUFFIX_DOLLO_SECONDARY_FEATURES, Format.FORESTER );
746 SurfacingUtil.writeMatrixToFile( secondary_features_parsimony.getGainLossCountsMatrix(), outfile_name
747 + surfacing.PARSIMONY_OUTPUT_GL_COUNTS_SUFFIX_DOLLO_SECONDARY_FEATURES, Format.FORESTER );
749 .writeBinaryStatesMatrixAsListToFile( secondary_features_parsimony.getGainLossMatrix(),
750 CharacterStateMatrix.GainLossStates.GAIN,
752 + surfacing.PARSIMONY_OUTPUT_DOLLO_GAINS_SECONDARY_FEATURES,
754 ForesterUtil.LINE_SEPARATOR,
757 .writeBinaryStatesMatrixAsListToFile( secondary_features_parsimony.getGainLossMatrix(),
758 CharacterStateMatrix.GainLossStates.LOSS,
760 + surfacing.PARSIMONY_OUTPUT_DOLLO_LOSSES_SECONDARY_FEATURES,
762 ForesterUtil.LINE_SEPARATOR,
765 .writeBinaryStatesMatrixAsListToFile( secondary_features_parsimony.getGainLossMatrix(),
768 + surfacing.PARSIMONY_OUTPUT_DOLLO_PRESENT_SECONDARY_FEATURES,
770 ForesterUtil.LINE_SEPARATOR,
772 preparePhylogeny( local_phylogeny_copy,
773 secondary_features_parsimony,
775 "Dollo parsimony on secondary feature presence/absence",
776 "dollo_on_secondary_features_" + outfile_name,
778 SurfacingUtil.writePhylogenyToFile( local_phylogeny_copy, outfile_name
779 + surfacing.SECONDARY_FEATURES_PARSIMONY_TREE_OUTPUT_SUFFIX_DOLLO );
782 public static void extractProteinNames( final List<Protein> proteins,
783 final List<DomainId> query_domain_ids_nc_order,
785 final String separator ) throws IOException {
786 for( final Protein protein : proteins ) {
787 if ( protein.contains( query_domain_ids_nc_order, true ) ) {
788 out.write( protein.getSpecies().getSpeciesId() );
789 out.write( separator );
790 out.write( protein.getProteinId().getId() );
791 out.write( separator );
793 final Set<DomainId> visited_domain_ids = new HashSet<DomainId>();
794 boolean first = true;
795 for( final Domain domain : protein.getProteinDomains() ) {
796 if ( !visited_domain_ids.contains( domain.getDomainId() ) ) {
797 visited_domain_ids.add( domain.getDomainId() );
804 out.write( domain.getDomainId().getId() );
806 out.write( "" + domain.getTotalCount() );
811 out.write( separator );
812 if ( !( ForesterUtil.isEmpty( protein.getDescription() ) || protein.getDescription()
813 .equals( SurfacingConstants.NONE ) ) ) {
814 out.write( protein.getDescription() );
816 out.write( separator );
817 if ( !( ForesterUtil.isEmpty( protein.getAccession() ) || protein.getAccession()
818 .equals( SurfacingConstants.NONE ) ) ) {
819 out.write( protein.getAccession() );
821 out.write( SurfacingConstants.NL );
827 public static void extractProteinNames( final SortedMap<Species, List<Protein>> protein_lists_per_species,
828 final DomainId domain_id,
830 final String separator ) throws IOException {
831 for( final Species species : protein_lists_per_species.keySet() ) {
832 for( final Protein protein : protein_lists_per_species.get( species ) ) {
833 final List<Domain> domains = protein.getProteinDomains( domain_id );
834 if ( domains.size() > 0 ) {
835 final DescriptiveStatistics stats = new BasicDescriptiveStatistics();
836 for( final Domain domain : domains ) {
837 stats.addValue( domain.getPerSequenceEvalue() );
839 out.write( protein.getSpecies().getSpeciesId() );
840 out.write( separator );
841 out.write( protein.getProteinId().getId() );
842 out.write( separator );
843 out.write( "[" + FORMATTER.format( stats.median() ) + "]" );
844 out.write( separator );
845 if ( !( ForesterUtil.isEmpty( protein.getDescription() ) || protein.getDescription()
846 .equals( SurfacingConstants.NONE ) ) ) {
847 out.write( protein.getDescription() );
849 out.write( separator );
850 if ( !( ForesterUtil.isEmpty( protein.getAccession() ) || protein.getAccession()
851 .equals( SurfacingConstants.NONE ) ) ) {
852 out.write( protein.getAccession() );
854 out.write( SurfacingConstants.NL );
861 public static SortedSet<DomainId> getAllDomainIds( final List<GenomeWideCombinableDomains> gwcd_list ) {
862 final SortedSet<DomainId> all_domains_ids = new TreeSet<DomainId>();
863 for( final GenomeWideCombinableDomains gwcd : gwcd_list ) {
864 final Set<DomainId> all_domains = gwcd.getAllDomainIds();
865 // for( final Domain domain : all_domains ) {
866 all_domains_ids.addAll( all_domains );
869 return all_domains_ids;
872 public static SortedMap<String, Integer> getDomainCounts( final List<Protein> protein_domain_collections ) {
873 final SortedMap<String, Integer> map = new TreeMap<String, Integer>();
874 for( final Protein protein_domain_collection : protein_domain_collections ) {
875 for( final Object name : protein_domain_collection.getProteinDomains() ) {
876 final BasicDomain protein_domain = ( BasicDomain ) name;
877 final String id = protein_domain.getDomainId().getId();
878 if ( map.containsKey( id ) ) {
879 map.put( id, map.get( id ) + 1 );
889 public static int getNumberOfNodesLackingName( final Phylogeny p, final StringBuilder names ) {
890 final PhylogenyNodeIterator it = p.iteratorPostorder();
892 while ( it.hasNext() ) {
893 final PhylogenyNode n = it.next();
894 if ( ForesterUtil.isEmpty( n.getName() )
895 && ( !n.getNodeData().isHasTaxonomy() || ForesterUtil.isEmpty( n.getNodeData().getTaxonomy()
896 .getScientificName() ) ) ) {
897 if ( n.getParent() != null ) {
899 names.append( n.getParent().getName() );
908 * Returns true is Domain domain falls in an uninterrupted stretch of
912 * @param covered_positions
915 public static boolean isEngulfed( final Domain domain, final List<Boolean> covered_positions ) {
916 for( int i = domain.getFrom(); i <= domain.getTo(); ++i ) {
917 if ( ( i >= covered_positions.size() ) || ( covered_positions.get( i ) != true ) ) {
924 public static void preparePhylogeny( final Phylogeny p,
925 final DomainParsimonyCalculator domain_parsimony,
926 final String date_time,
929 final String parameters_str ) {
930 domain_parsimony.decoratePhylogenyWithDomains( p );
931 final StringBuilder desc = new StringBuilder();
932 desc.append( "[Method: " + method + "] [Date: " + date_time + "] " );
933 desc.append( "[Cost: " + domain_parsimony.getCost() + "] " );
934 desc.append( "[Gains: " + domain_parsimony.getTotalGains() + "] " );
935 desc.append( "[Losses: " + domain_parsimony.getTotalLosses() + "] " );
936 desc.append( "[Unchanged: " + domain_parsimony.getTotalUnchanged() + "] " );
937 desc.append( "[Parameters: " + parameters_str + "]" );
939 p.setDescription( desc.toString() );
940 p.setConfidence( new Confidence( domain_parsimony.getCost(), "parsimony" ) );
941 p.setRerootable( false );
946 * species | protein id | n-terminal domain | c-terminal domain | n-terminal domain per domain E-value | c-terminal domain per domain E-value
950 static public StringBuffer proteinToDomainCombinations( final Protein protein,
951 final String protein_id,
952 final String separator ) {
953 final StringBuffer sb = new StringBuffer();
954 if ( protein.getSpecies() == null ) {
955 throw new IllegalArgumentException( "species must not be null" );
957 if ( ForesterUtil.isEmpty( protein.getSpecies().getSpeciesId() ) ) {
958 throw new IllegalArgumentException( "species id must not be empty" );
960 final List<Domain> domains = protein.getProteinDomains();
961 if ( domains.size() > 1 ) {
962 final Map<String, Integer> counts = new HashMap<String, Integer>();
963 for( final Domain domain : domains ) {
964 final String id = domain.getDomainId().getId();
965 if ( counts.containsKey( id ) ) {
966 counts.put( id, counts.get( id ) + 1 );
972 final Set<String> dcs = new HashSet<String>();
973 for( int i = 1; i < domains.size(); ++i ) {
974 for( int j = 0; j < i; ++j ) {
975 Domain domain_n = domains.get( i );
976 Domain domain_c = domains.get( j );
977 if ( domain_n.getFrom() > domain_c.getFrom() ) {
978 domain_n = domains.get( j );
979 domain_c = domains.get( i );
981 final String dc = domain_n.getDomainId().getId() + domain_c.getDomainId().getId();
982 if ( !dcs.contains( dc ) ) {
984 sb.append( protein.getSpecies() );
985 sb.append( separator );
986 sb.append( protein_id );
987 sb.append( separator );
988 sb.append( domain_n.getDomainId().getId() );
989 sb.append( separator );
990 sb.append( domain_c.getDomainId().getId() );
991 sb.append( separator );
992 sb.append( domain_n.getPerDomainEvalue() );
993 sb.append( separator );
994 sb.append( domain_c.getPerDomainEvalue() );
995 sb.append( separator );
996 sb.append( counts.get( domain_n.getDomainId().getId() ) );
997 sb.append( separator );
998 sb.append( counts.get( domain_c.getDomainId().getId() ) );
999 sb.append( ForesterUtil.LINE_SEPARATOR );
1004 else if ( domains.size() == 1 ) {
1005 sb.append( protein.getSpecies() );
1006 sb.append( separator );
1007 sb.append( protein_id );
1008 sb.append( separator );
1009 sb.append( domains.get( 0 ).getDomainId().getId() );
1010 sb.append( separator );
1011 sb.append( separator );
1012 sb.append( domains.get( 0 ).getPerDomainEvalue() );
1013 sb.append( separator );
1014 sb.append( separator );
1016 sb.append( separator );
1017 sb.append( ForesterUtil.LINE_SEPARATOR );
1020 sb.append( protein.getSpecies() );
1021 sb.append( separator );
1022 sb.append( protein_id );
1023 sb.append( separator );
1024 sb.append( separator );
1025 sb.append( separator );
1026 sb.append( separator );
1027 sb.append( separator );
1028 sb.append( separator );
1029 sb.append( ForesterUtil.LINE_SEPARATOR );
1036 * Example regarding engulfment: ------------0.1 ----------0.2 --0.3 =>
1037 * domain with 0.3 is ignored
1039 * -----------0.1 ----------0.2 --0.3 => domain with 0.3 is ignored
1042 * ------------0.1 ----------0.3 --0.2 => domains with 0.3 and 0.2 are _not_
1045 * @param max_allowed_overlap
1046 * maximal allowed overlap (inclusive) to be still considered not
1047 * overlapping (zero or negative value to allow any overlap)
1048 * @param remove_engulfed_domains
1049 * to remove domains which are completely engulfed by coverage of
1050 * domains with better support
1054 public static Protein removeOverlappingDomains( final int max_allowed_overlap,
1055 final boolean remove_engulfed_domains,
1056 final Protein protein ) {
1057 final Protein pruned_protein = new BasicProtein( protein.getProteinId().getId(), protein.getSpecies()
1059 final List<Domain> sorted = SurfacingUtil.sortDomainsWithAscendingConfidenceValues( protein );
1060 final List<Boolean> covered_positions = new ArrayList<Boolean>();
1061 for( final Domain domain : sorted ) {
1062 if ( ( ( max_allowed_overlap < 0 ) || ( SurfacingUtil.calculateOverlap( domain, covered_positions ) <= max_allowed_overlap ) )
1063 && ( !remove_engulfed_domains || !isEngulfed( domain, covered_positions ) ) ) {
1064 final int covered_positions_size = covered_positions.size();
1065 for( int i = covered_positions_size; i < domain.getFrom(); ++i ) {
1066 covered_positions.add( false );
1068 final int new_covered_positions_size = covered_positions.size();
1069 for( int i = domain.getFrom(); i <= domain.getTo(); ++i ) {
1070 if ( i < new_covered_positions_size ) {
1071 covered_positions.set( i, true );
1074 covered_positions.add( true );
1077 pruned_protein.addProteinDomain( domain );
1080 return pruned_protein;
1083 public static List<Domain> sortDomainsWithAscendingConfidenceValues( final Protein protein ) {
1084 final List<Domain> domains = new ArrayList<Domain>();
1085 for( final Domain d : protein.getProteinDomains() ) {
1088 Collections.sort( domains, SurfacingUtil.ASCENDING_CONFIDENCE_VALUE_ORDER );
1092 private static List<String> splitDomainCombination( final String dc ) {
1093 final String[] s = dc.split( "=" );
1094 if ( s.length != 2 ) {
1095 ForesterUtil.printErrorMessage( surfacing.PRG_NAME, "Stringyfied domain combination has illegal format: "
1099 final List<String> l = new ArrayList<String>( 2 );
1105 public static void writeAllDomainsChangedOnAllSubtrees( final Phylogeny p,
1106 final boolean get_gains,
1107 final String outdir,
1108 final String suffix_for_filename ) throws IOException {
1109 CharacterStateMatrix.GainLossStates state = CharacterStateMatrix.GainLossStates.GAIN;
1111 state = CharacterStateMatrix.GainLossStates.LOSS;
1113 final File base_dir = createBaseDirForPerNodeDomainFiles( surfacing.BASE_DIRECTORY_PER_SUBTREE_DOMAIN_GAIN_LOSS_FILES,
1117 for( final PhylogenyNodeIterator it = p.iteratorPostorder(); it.hasNext(); ) {
1118 final PhylogenyNode node = it.next();
1119 if ( !node.isExternal() ) {
1120 final SortedSet<String> domains = collectAllDomainsChangedOnSubtree( node, get_gains );
1121 if ( domains.size() > 0 ) {
1122 final Writer writer = ForesterUtil.createBufferedWriter( base_dir + ForesterUtil.FILE_SEPARATOR
1123 + node.getName() + suffix_for_filename );
1124 for( final String domain : domains ) {
1125 writer.write( domain );
1126 writer.write( ForesterUtil.LINE_SEPARATOR );
1134 private static void writeAllEncounteredPfamsToFile( final Map<DomainId, List<GoId>> domain_id_to_go_ids_map,
1135 final Map<GoId, GoTerm> go_id_to_term_map,
1136 final String outfile_name,
1137 final SortedSet<String> all_pfams_encountered ) {
1138 final File all_pfams_encountered_file = new File( outfile_name + surfacing.ALL_PFAMS_ENCOUNTERED_SUFFIX );
1139 final File all_pfams_encountered_with_go_annotation_file = new File( outfile_name
1140 + surfacing.ALL_PFAMS_ENCOUNTERED_WITH_GO_ANNOTATION_SUFFIX );
1141 final File encountered_pfams_summary_file = new File( outfile_name + surfacing.ENCOUNTERED_PFAMS_SUMMARY_SUFFIX );
1142 int biological_process_counter = 0;
1143 int cellular_component_counter = 0;
1144 int molecular_function_counter = 0;
1145 int pfams_with_mappings_counter = 0;
1146 int pfams_without_mappings_counter = 0;
1147 int pfams_without_mappings_to_bp_or_mf_counter = 0;
1148 int pfams_with_mappings_to_bp_or_mf_counter = 0;
1150 final Writer all_pfams_encountered_writer = new BufferedWriter( new FileWriter( all_pfams_encountered_file ) );
1151 final Writer all_pfams_encountered_with_go_annotation_writer = new BufferedWriter( new FileWriter( all_pfams_encountered_with_go_annotation_file ) );
1152 final Writer summary_writer = new BufferedWriter( new FileWriter( encountered_pfams_summary_file ) );
1153 summary_writer.write( "# Pfam to GO mapping summary" );
1154 summary_writer.write( ForesterUtil.LINE_SEPARATOR );
1155 summary_writer.write( "# Actual summary is at the end of this file." );
1156 summary_writer.write( ForesterUtil.LINE_SEPARATOR );
1157 summary_writer.write( "# Encountered Pfams without a GO mapping:" );
1158 summary_writer.write( ForesterUtil.LINE_SEPARATOR );
1159 for( final String pfam : all_pfams_encountered ) {
1160 all_pfams_encountered_writer.write( pfam );
1161 all_pfams_encountered_writer.write( ForesterUtil.LINE_SEPARATOR );
1162 final DomainId domain_id = new DomainId( pfam );
1163 if ( domain_id_to_go_ids_map.containsKey( domain_id ) ) {
1164 ++pfams_with_mappings_counter;
1165 all_pfams_encountered_with_go_annotation_writer.write( pfam );
1166 all_pfams_encountered_with_go_annotation_writer.write( ForesterUtil.LINE_SEPARATOR );
1167 final List<GoId> go_ids = domain_id_to_go_ids_map.get( domain_id );
1168 boolean maps_to_bp = false;
1169 boolean maps_to_cc = false;
1170 boolean maps_to_mf = false;
1171 for( final GoId go_id : go_ids ) {
1172 final GoTerm go_term = go_id_to_term_map.get( go_id );
1173 if ( go_term.getGoNameSpace().isBiologicalProcess() ) {
1176 else if ( go_term.getGoNameSpace().isCellularComponent() ) {
1179 else if ( go_term.getGoNameSpace().isMolecularFunction() ) {
1184 ++biological_process_counter;
1187 ++cellular_component_counter;
1190 ++molecular_function_counter;
1192 if ( maps_to_bp || maps_to_mf ) {
1193 ++pfams_with_mappings_to_bp_or_mf_counter;
1196 ++pfams_without_mappings_to_bp_or_mf_counter;
1200 ++pfams_without_mappings_to_bp_or_mf_counter;
1201 ++pfams_without_mappings_counter;
1202 summary_writer.write( pfam );
1203 summary_writer.write( ForesterUtil.LINE_SEPARATOR );
1206 all_pfams_encountered_writer.close();
1207 all_pfams_encountered_with_go_annotation_writer.close();
1208 ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote all [" + all_pfams_encountered.size()
1209 + "] encountered Pfams to: \"" + all_pfams_encountered_file + "\"" );
1210 ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote all [" + pfams_with_mappings_counter
1211 + "] encountered Pfams with GO mappings to: \"" + all_pfams_encountered_with_go_annotation_file
1213 ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote summary (including all ["
1214 + pfams_without_mappings_counter + "] encountered Pfams without GO mappings) to: \""
1215 + encountered_pfams_summary_file + "\"" );
1216 ForesterUtil.programMessage( surfacing.PRG_NAME, "Sum of Pfams encountered : "
1217 + all_pfams_encountered.size() );
1218 ForesterUtil.programMessage( surfacing.PRG_NAME, "Pfams without a mapping : "
1219 + pfams_without_mappings_counter + " ["
1220 + ( 100 * pfams_without_mappings_counter / all_pfams_encountered.size() ) + "%]" );
1221 ForesterUtil.programMessage( surfacing.PRG_NAME, "Pfams without mapping to proc. or func. : "
1222 + pfams_without_mappings_to_bp_or_mf_counter + " ["
1223 + ( 100 * pfams_without_mappings_to_bp_or_mf_counter / all_pfams_encountered.size() ) + "%]" );
1224 ForesterUtil.programMessage( surfacing.PRG_NAME,
1225 "Pfams with a mapping : " + pfams_with_mappings_counter
1227 + ( 100 * pfams_with_mappings_counter / all_pfams_encountered.size() )
1229 ForesterUtil.programMessage( surfacing.PRG_NAME, "Pfams with a mapping to proc. or func. : "
1230 + pfams_with_mappings_to_bp_or_mf_counter + " ["
1231 + ( 100 * pfams_with_mappings_to_bp_or_mf_counter / all_pfams_encountered.size() ) + "%]" );
1232 ForesterUtil.programMessage( surfacing.PRG_NAME,
1233 "Pfams with mapping to biological process: " + biological_process_counter
1235 + ( 100 * biological_process_counter / all_pfams_encountered.size() )
1237 ForesterUtil.programMessage( surfacing.PRG_NAME,
1238 "Pfams with mapping to molecular function: " + molecular_function_counter
1240 + ( 100 * molecular_function_counter / all_pfams_encountered.size() )
1242 ForesterUtil.programMessage( surfacing.PRG_NAME,
1243 "Pfams with mapping to cellular component: " + cellular_component_counter
1245 + ( 100 * cellular_component_counter / all_pfams_encountered.size() )
1247 summary_writer.write( ForesterUtil.LINE_SEPARATOR );
1248 summary_writer.write( "# Sum of Pfams encountered : " + all_pfams_encountered.size() );
1249 summary_writer.write( ForesterUtil.LINE_SEPARATOR );
1250 summary_writer.write( "# Pfams without a mapping : " + pfams_without_mappings_counter
1251 + " [" + ( 100 * pfams_without_mappings_counter / all_pfams_encountered.size() ) + "%]" );
1252 summary_writer.write( ForesterUtil.LINE_SEPARATOR );
1253 summary_writer.write( "# Pfams without mapping to proc. or func. : "
1254 + pfams_without_mappings_to_bp_or_mf_counter + " ["
1255 + ( 100 * pfams_without_mappings_to_bp_or_mf_counter / all_pfams_encountered.size() ) + "%]" );
1256 summary_writer.write( ForesterUtil.LINE_SEPARATOR );
1257 summary_writer.write( "# Pfams with a mapping : " + pfams_with_mappings_counter + " ["
1258 + ( 100 * pfams_with_mappings_counter / all_pfams_encountered.size() ) + "%]" );
1259 summary_writer.write( ForesterUtil.LINE_SEPARATOR );
1260 summary_writer.write( "# Pfams with a mapping to proc. or func. : "
1261 + pfams_with_mappings_to_bp_or_mf_counter + " ["
1262 + ( 100 * pfams_with_mappings_to_bp_or_mf_counter / all_pfams_encountered.size() ) + "%]" );
1263 summary_writer.write( ForesterUtil.LINE_SEPARATOR );
1264 summary_writer.write( "# Pfams with mapping to biological process: " + biological_process_counter + " ["
1265 + ( 100 * biological_process_counter / all_pfams_encountered.size() ) + "%]" );
1266 summary_writer.write( ForesterUtil.LINE_SEPARATOR );
1267 summary_writer.write( "# Pfams with mapping to molecular function: " + molecular_function_counter + " ["
1268 + ( 100 * molecular_function_counter / all_pfams_encountered.size() ) + "%]" );
1269 summary_writer.write( ForesterUtil.LINE_SEPARATOR );
1270 summary_writer.write( "# Pfams with mapping to cellular component: " + cellular_component_counter + " ["
1271 + ( 100 * cellular_component_counter / all_pfams_encountered.size() ) + "%]" );
1272 summary_writer.write( ForesterUtil.LINE_SEPARATOR );
1273 summary_writer.close();
1275 catch ( final IOException e ) {
1276 ForesterUtil.printWarningMessage( surfacing.PRG_NAME, "Failure to write: " + e );
1280 public static void writeBinaryDomainCombinationsFileForGraphAnalysis( final String[][] input_file_properties,
1281 final File output_dir,
1282 final GenomeWideCombinableDomains gwcd,
1284 final GenomeWideCombinableDomainsSortOrder dc_sort_order ) {
1285 File dc_outfile_dot = new File( input_file_properties[ i ][ 0 ]
1286 + surfacing.DOMAIN_COMBINITONS_OUTPUTFILE_SUFFIX_FOR_GRAPH_ANALYSIS );
1287 if ( output_dir != null ) {
1288 dc_outfile_dot = new File( output_dir + ForesterUtil.FILE_SEPARATOR + dc_outfile_dot );
1290 checkForOutputFileWriteability( dc_outfile_dot );
1291 final SortedSet<BinaryDomainCombination> binary_combinations = createSetOfAllBinaryDomainCombinationsPerGenome( gwcd );
1293 final BufferedWriter out_dot = new BufferedWriter( new FileWriter( dc_outfile_dot ) );
1294 for( final BinaryDomainCombination bdc : binary_combinations ) {
1295 out_dot.write( bdc.toGraphDescribingLanguage( BinaryDomainCombination.OutputFormat.DOT, null, null )
1297 out_dot.write( SurfacingConstants.NL );
1301 catch ( final IOException e ) {
1302 ForesterUtil.fatalError( surfacing.PRG_NAME, e.getMessage() );
1304 ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote binary domain combination for \""
1305 + input_file_properties[ i ][ 0 ] + "\" (" + input_file_properties[ i ][ 1 ] + ", "
1306 + input_file_properties[ i ][ 2 ] + ") to: \"" + dc_outfile_dot + "\"" );
1309 public static void writeBinaryStatesMatrixAsListToFile( final CharacterStateMatrix<CharacterStateMatrix.GainLossStates> matrix,
1310 final CharacterStateMatrix.GainLossStates state,
1311 final String filename,
1312 final String indentifier_characters_separator,
1313 final String character_separator,
1314 final Map<String, String> descriptions ) {
1315 final File outfile = new File( filename );
1316 checkForOutputFileWriteability( outfile );
1317 final SortedSet<String> sorted_ids = new TreeSet<String>();
1318 for( int i = 0; i < matrix.getNumberOfIdentifiers(); ++i ) {
1319 sorted_ids.add( matrix.getIdentifier( i ) );
1322 final BufferedWriter out = new BufferedWriter( new FileWriter( outfile ) );
1323 for( final String id : sorted_ids ) {
1324 out.write( indentifier_characters_separator );
1325 out.write( "#" + id );
1326 out.write( indentifier_characters_separator );
1327 for( int c = 0; c < matrix.getNumberOfCharacters(); ++c ) {
1329 // using null to indicate either UNCHANGED_PRESENT or GAIN.
1330 if ( ( matrix.getState( id, c ) == state )
1331 || ( ( state == null ) && ( ( matrix.getState( id, c ) == CharacterStateMatrix.GainLossStates.GAIN ) || ( matrix
1332 .getState( id, c ) == CharacterStateMatrix.GainLossStates.UNCHANGED_PRESENT ) ) ) ) {
1333 out.write( matrix.getCharacter( c ) );
1334 if ( ( descriptions != null ) && !descriptions.isEmpty()
1335 && descriptions.containsKey( matrix.getCharacter( c ) ) ) {
1337 out.write( descriptions.get( matrix.getCharacter( c ) ) );
1339 out.write( character_separator );
1346 catch ( final IOException e ) {
1347 ForesterUtil.fatalError( surfacing.PRG_NAME, e.getMessage() );
1349 ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote characters list: \"" + filename + "\"" );
1352 public static void writeBinaryStatesMatrixAsListToFileForBinaryCombinationsForGraphAnalysis( final CharacterStateMatrix<CharacterStateMatrix.GainLossStates> matrix,
1353 final CharacterStateMatrix.GainLossStates state,
1354 final String filename,
1355 final String indentifier_characters_separator,
1356 final String character_separator,
1357 final BinaryDomainCombination.OutputFormat bc_output_format ) {
1358 final File outfile = new File( filename );
1359 checkForOutputFileWriteability( outfile );
1360 final SortedSet<String> sorted_ids = new TreeSet<String>();
1361 for( int i = 0; i < matrix.getNumberOfIdentifiers(); ++i ) {
1362 sorted_ids.add( matrix.getIdentifier( i ) );
1365 final BufferedWriter out = new BufferedWriter( new FileWriter( outfile ) );
1366 for( final String id : sorted_ids ) {
1367 out.write( indentifier_characters_separator );
1368 out.write( "#" + id );
1369 out.write( indentifier_characters_separator );
1370 for( int c = 0; c < matrix.getNumberOfCharacters(); ++c ) {
1372 // using null to indicate either UNCHANGED_PRESENT or GAIN.
1373 if ( ( matrix.getState( id, c ) == state )
1374 || ( ( state == null ) && ( ( matrix.getState( id, c ) == CharacterStateMatrix.GainLossStates.GAIN ) || ( matrix
1375 .getState( id, c ) == CharacterStateMatrix.GainLossStates.UNCHANGED_PRESENT ) ) ) ) {
1376 BinaryDomainCombination bdc = null;
1378 bdc = BasicBinaryDomainCombination.createInstance( matrix.getCharacter( c ) );
1380 catch ( final Exception e ) {
1381 ForesterUtil.fatalError( surfacing.PRG_NAME, e.getLocalizedMessage() );
1383 out.write( bdc.toGraphDescribingLanguage( bc_output_format, null, null ).toString() );
1384 out.write( character_separator );
1391 catch ( final IOException e ) {
1392 ForesterUtil.fatalError( surfacing.PRG_NAME, e.getMessage() );
1394 ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote characters list: \"" + filename + "\"" );
1397 public static void writeBinaryStatesMatrixToList( final Map<DomainId, List<GoId>> domain_id_to_go_ids_map,
1398 final Map<GoId, GoTerm> go_id_to_term_map,
1399 final GoNameSpace go_namespace_limit,
1400 final boolean domain_combinations,
1401 final CharacterStateMatrix<CharacterStateMatrix.GainLossStates> matrix,
1402 final CharacterStateMatrix.GainLossStates state,
1403 final String filename,
1404 final String indentifier_characters_separator,
1405 final String character_separator,
1406 final String title_for_html,
1407 final String prefix_for_html,
1408 final Map<DomainId, Set<String>>[] domain_id_to_secondary_features_maps,
1409 final SortedSet<String> all_pfams_encountered,
1410 final SortedSet<String> pfams_gained_or_lost,
1411 final String suffix_for_per_node_events_file ) {
1412 if ( ( go_namespace_limit != null ) && ( ( go_id_to_term_map == null ) || ( go_id_to_term_map.size() < 1 ) ) ) {
1413 throw new IllegalArgumentException( "attempt to use GO namespace limit without a GO-id to term map" );
1415 else if ( ( ( domain_id_to_go_ids_map == null ) || ( domain_id_to_go_ids_map.size() < 1 ) ) ) {
1416 throw new IllegalArgumentException( "attempt to output detailed HTML without a Pfam to GO map" );
1418 else if ( ( ( go_id_to_term_map == null ) || ( go_id_to_term_map.size() < 1 ) ) ) {
1419 throw new IllegalArgumentException( "attempt to output detailed HTML without a GO-id to term map" );
1421 final File outfile = new File( filename );
1422 checkForOutputFileWriteability( outfile );
1423 final SortedSet<String> sorted_ids = new TreeSet<String>();
1424 for( int i = 0; i < matrix.getNumberOfIdentifiers(); ++i ) {
1425 sorted_ids.add( matrix.getIdentifier( i ) );
1428 final Writer out = new BufferedWriter( new FileWriter( outfile ) );
1429 final File per_node_go_mapped_domain_gain_loss_files_base_dir = createBaseDirForPerNodeDomainFiles( surfacing.BASE_DIRECTORY_PER_NODE_DOMAIN_GAIN_LOSS_FILES,
1430 domain_combinations,
1433 Writer per_node_go_mapped_domain_gain_loss_outfile_writer = null;
1434 File per_node_go_mapped_domain_gain_loss_outfile = null;
1435 int per_node_counter = 0;
1436 out.write( "<html>" );
1437 out.write( SurfacingConstants.NL );
1438 addHtmlHead( out, title_for_html );
1439 out.write( SurfacingConstants.NL );
1440 out.write( "<body>" );
1441 out.write( SurfacingConstants.NL );
1442 out.write( "<h1>" );
1443 out.write( SurfacingConstants.NL );
1444 out.write( title_for_html );
1445 out.write( SurfacingConstants.NL );
1446 out.write( "</h1>" );
1447 out.write( SurfacingConstants.NL );
1448 out.write( "<table>" );
1449 out.write( SurfacingConstants.NL );
1450 for( final String id : sorted_ids ) {
1451 final Matcher matcher = PATTERN_SP_STYLE_TAXONOMY.matcher( id );
1452 if ( matcher.matches() ) {
1455 out.write( "<tr>" );
1456 out.write( "<td>" );
1457 out.write( "<a href=\"#" + id + "\">" + id + "</a>" );
1458 out.write( "</td>" );
1459 out.write( "</tr>" );
1460 out.write( SurfacingConstants.NL );
1462 out.write( "</table>" );
1463 out.write( SurfacingConstants.NL );
1464 for( final String id : sorted_ids ) {
1465 final Matcher matcher = PATTERN_SP_STYLE_TAXONOMY.matcher( id );
1466 if ( matcher.matches() ) {
1469 out.write( SurfacingConstants.NL );
1470 out.write( "<h2>" );
1471 out.write( "<a name=\"" + id + "\">" + id + "</a>" );
1472 writeTaxonomyLinks( out, id );
1473 out.write( "</h2>" );
1474 out.write( SurfacingConstants.NL );
1475 out.write( "<table>" );
1476 out.write( SurfacingConstants.NL );
1477 out.write( "<tr>" );
1478 out.write( "<td><b>" );
1479 out.write( "Pfam domain(s)" );
1480 out.write( "</b></td><td><b>" );
1481 out.write( "GO term acc" );
1482 out.write( "</b></td><td><b>" );
1483 out.write( "GO term" );
1484 out.write( "</b></td><td><b>" );
1485 out.write( "GO namespace" );
1486 out.write( "</b></td>" );
1487 out.write( "</tr>" );
1488 out.write( SurfacingConstants.NL );
1489 out.write( "</tr>" );
1490 out.write( SurfacingConstants.NL );
1491 per_node_counter = 0;
1492 if ( matrix.getNumberOfCharacters() > 0 ) {
1493 per_node_go_mapped_domain_gain_loss_outfile = new File( per_node_go_mapped_domain_gain_loss_files_base_dir
1494 + ForesterUtil.FILE_SEPARATOR + id + suffix_for_per_node_events_file );
1495 SurfacingUtil.checkForOutputFileWriteability( per_node_go_mapped_domain_gain_loss_outfile );
1496 per_node_go_mapped_domain_gain_loss_outfile_writer = ForesterUtil
1497 .createBufferedWriter( per_node_go_mapped_domain_gain_loss_outfile );
1500 per_node_go_mapped_domain_gain_loss_outfile = null;
1501 per_node_go_mapped_domain_gain_loss_outfile_writer = null;
1503 for( int c = 0; c < matrix.getNumberOfCharacters(); ++c ) {
1505 // using null to indicate either UNCHANGED_PRESENT or GAIN.
1506 if ( ( matrix.getState( id, c ) == state )
1507 || ( ( state == null ) && ( ( matrix.getState( id, c ) == CharacterStateMatrix.GainLossStates.UNCHANGED_PRESENT ) || ( matrix
1508 .getState( id, c ) == CharacterStateMatrix.GainLossStates.GAIN ) ) ) ) {
1509 final String character = matrix.getCharacter( c );
1510 String domain_0 = "";
1511 String domain_1 = "";
1512 if ( character.indexOf( BinaryDomainCombination.SEPARATOR ) > 0 ) {
1513 final String[] s = character.split( BinaryDomainCombination.SEPARATOR );
1514 if ( s.length != 2 ) {
1515 throw new AssertionError( "this should not have happened: unexpected format for domain combination: ["
1516 + character + "]" );
1522 domain_0 = character;
1524 writeDomainData( domain_id_to_go_ids_map,
1531 character_separator,
1532 domain_id_to_secondary_features_maps,
1534 all_pfams_encountered.add( domain_0 );
1535 if ( pfams_gained_or_lost != null ) {
1536 pfams_gained_or_lost.add( domain_0 );
1538 if ( !ForesterUtil.isEmpty( domain_1 ) ) {
1539 all_pfams_encountered.add( domain_1 );
1540 if ( pfams_gained_or_lost != null ) {
1541 pfams_gained_or_lost.add( domain_1 );
1544 if ( per_node_go_mapped_domain_gain_loss_outfile_writer != null ) {
1545 writeDomainsToIndividualFilePerTreeNode( per_node_go_mapped_domain_gain_loss_outfile_writer,
1552 if ( per_node_go_mapped_domain_gain_loss_outfile_writer != null ) {
1553 per_node_go_mapped_domain_gain_loss_outfile_writer.close();
1554 if ( per_node_counter < 1 ) {
1555 per_node_go_mapped_domain_gain_loss_outfile.delete();
1557 per_node_counter = 0;
1559 out.write( "</table>" );
1560 out.write( SurfacingConstants.NL );
1561 out.write( "<hr>" );
1562 out.write( SurfacingConstants.NL );
1563 } // for( final String id : sorted_ids ) {
1564 out.write( "</body>" );
1565 out.write( SurfacingConstants.NL );
1566 out.write( "</html>" );
1567 out.write( SurfacingConstants.NL );
1571 catch ( final IOException e ) {
1572 ForesterUtil.fatalError( surfacing.PRG_NAME, e.getMessage() );
1574 ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote characters detailed HTML list: \"" + filename + "\"" );
1577 public static void writeBinaryStatesMatrixToListORIGIG( final Map<DomainId, List<GoId>> domain_id_to_go_ids_map,
1578 final Map<GoId, GoTerm> go_id_to_term_map,
1579 final GoNameSpace go_namespace_limit,
1580 final boolean domain_combinations,
1581 final CharacterStateMatrix<CharacterStateMatrix.GainLossStates> matrix,
1582 final CharacterStateMatrix.GainLossStates state,
1583 final String filename,
1584 final String indentifier_characters_separator,
1585 final String character_separator,
1586 final String title_for_html,
1587 final String prefix_for_html,
1588 final Map<DomainId, Set<String>>[] domain_id_to_secondary_features_maps,
1589 final SortedSet<String> all_pfams_encountered,
1590 final SortedSet<String> pfams_gained_or_lost,
1591 final String suffix_for_per_node_events_file ) {
1592 if ( ( go_namespace_limit != null ) && ( ( go_id_to_term_map == null ) || ( go_id_to_term_map.size() < 1 ) ) ) {
1593 throw new IllegalArgumentException( "attempt to use GO namespace limit without a GO-id to term map" );
1595 else if ( ( ( domain_id_to_go_ids_map == null ) || ( domain_id_to_go_ids_map.size() < 1 ) ) ) {
1596 throw new IllegalArgumentException( "attempt to output detailed HTML without a Pfam to GO map" );
1598 else if ( ( ( go_id_to_term_map == null ) || ( go_id_to_term_map.size() < 1 ) ) ) {
1599 throw new IllegalArgumentException( "attempt to output detailed HTML without a GO-id to term map" );
1601 final File outfile = new File( filename );
1602 checkForOutputFileWriteability( outfile );
1603 final SortedSet<String> sorted_ids = new TreeSet<String>();
1604 for( int i = 0; i < matrix.getNumberOfIdentifiers(); ++i ) {
1605 sorted_ids.add( matrix.getIdentifier( i ) );
1608 final Writer out = new BufferedWriter( new FileWriter( outfile ) );
1609 final File per_node_go_mapped_domain_gain_loss_files_base_dir = createBaseDirForPerNodeDomainFiles( surfacing.BASE_DIRECTORY_PER_NODE_DOMAIN_GAIN_LOSS_FILES,
1610 domain_combinations,
1613 Writer per_node_go_mapped_domain_gain_loss_outfile_writer = null;
1614 File per_node_go_mapped_domain_gain_loss_outfile = null;
1615 int per_node_counter = 0;
1616 out.write( "<html>" );
1617 out.write( SurfacingConstants.NL );
1618 addHtmlHead( out, title_for_html );
1619 out.write( SurfacingConstants.NL );
1620 out.write( "<body>" );
1621 out.write( SurfacingConstants.NL );
1622 out.write( "<h1>" );
1623 out.write( SurfacingConstants.NL );
1624 out.write( title_for_html );
1625 out.write( SurfacingConstants.NL );
1626 out.write( "</h1>" );
1627 out.write( SurfacingConstants.NL );
1628 out.write( "<table>" );
1629 out.write( SurfacingConstants.NL );
1630 for( final String id : sorted_ids ) {
1631 out.write( "<tr>" );
1632 out.write( "<td>" );
1633 out.write( "<a href=\"#" + id + "\">" + id + "</a>" );
1634 writeTaxonomyLinks( out, id );
1635 out.write( "</td>" );
1636 out.write( "</tr>" );
1637 out.write( SurfacingConstants.NL );
1639 out.write( "</table>" );
1640 out.write( SurfacingConstants.NL );
1641 for( final String id : sorted_ids ) {
1642 out.write( SurfacingConstants.NL );
1643 out.write( "<h2>" );
1644 out.write( "<a name=\"" + id + "\">" + id + "</a>" );
1645 writeTaxonomyLinks( out, id );
1646 out.write( "</h2>" );
1647 out.write( SurfacingConstants.NL );
1648 out.write( "<table>" );
1649 out.write( SurfacingConstants.NL );
1650 out.write( "<tr>" );
1651 out.write( "<td><b>" );
1652 out.write( "Pfam domain(s)" );
1653 out.write( "</b></td><td><b>" );
1654 out.write( "GO term acc" );
1655 out.write( "</b></td><td><b>" );
1656 out.write( "GO term" );
1657 out.write( "</b></td><td><b>" );
1658 out.write( "Penultimate GO term" );
1659 out.write( "</b></td><td><b>" );
1660 out.write( "GO namespace" );
1661 out.write( "</b></td>" );
1662 out.write( "</tr>" );
1663 out.write( SurfacingConstants.NL );
1664 out.write( "</tr>" );
1665 out.write( SurfacingConstants.NL );
1666 per_node_counter = 0;
1667 if ( matrix.getNumberOfCharacters() > 0 ) {
1668 per_node_go_mapped_domain_gain_loss_outfile = new File( per_node_go_mapped_domain_gain_loss_files_base_dir
1669 + ForesterUtil.FILE_SEPARATOR + id + suffix_for_per_node_events_file );
1670 SurfacingUtil.checkForOutputFileWriteability( per_node_go_mapped_domain_gain_loss_outfile );
1671 per_node_go_mapped_domain_gain_loss_outfile_writer = ForesterUtil
1672 .createBufferedWriter( per_node_go_mapped_domain_gain_loss_outfile );
1675 per_node_go_mapped_domain_gain_loss_outfile = null;
1676 per_node_go_mapped_domain_gain_loss_outfile_writer = null;
1678 for( int c = 0; c < matrix.getNumberOfCharacters(); ++c ) {
1680 // using null to indicate either UNCHANGED_PRESENT or GAIN.
1681 if ( ( matrix.getState( id, c ) == state )
1682 || ( ( state == null ) && ( ( matrix.getState( id, c ) == CharacterStateMatrix.GainLossStates.UNCHANGED_PRESENT ) || ( matrix
1683 .getState( id, c ) == CharacterStateMatrix.GainLossStates.GAIN ) ) ) ) {
1684 final String character = matrix.getCharacter( c );
1685 String domain_0 = "";
1686 String domain_1 = "";
1687 if ( character.indexOf( BinaryDomainCombination.SEPARATOR ) > 0 ) {
1688 final String[] s = character.split( BinaryDomainCombination.SEPARATOR );
1689 if ( s.length != 2 ) {
1690 throw new AssertionError( "this should not have happened: unexpected format for domain combination: ["
1691 + character + "]" );
1697 domain_0 = character;
1699 writeDomainData( domain_id_to_go_ids_map,
1706 character_separator,
1707 domain_id_to_secondary_features_maps,
1709 all_pfams_encountered.add( domain_0 );
1710 if ( pfams_gained_or_lost != null ) {
1711 pfams_gained_or_lost.add( domain_0 );
1713 if ( !ForesterUtil.isEmpty( domain_1 ) ) {
1714 all_pfams_encountered.add( domain_1 );
1715 if ( pfams_gained_or_lost != null ) {
1716 pfams_gained_or_lost.add( domain_1 );
1719 if ( per_node_go_mapped_domain_gain_loss_outfile_writer != null ) {
1720 writeDomainsToIndividualFilePerTreeNode( per_node_go_mapped_domain_gain_loss_outfile_writer,
1727 if ( per_node_go_mapped_domain_gain_loss_outfile_writer != null ) {
1728 per_node_go_mapped_domain_gain_loss_outfile_writer.close();
1729 if ( per_node_counter < 1 ) {
1730 per_node_go_mapped_domain_gain_loss_outfile.delete();
1732 per_node_counter = 0;
1734 out.write( "</table>" );
1735 out.write( SurfacingConstants.NL );
1736 out.write( "<hr>" );
1737 out.write( SurfacingConstants.NL );
1738 } // for( final String id : sorted_ids ) {
1739 out.write( "</body>" );
1740 out.write( SurfacingConstants.NL );
1741 out.write( "</html>" );
1742 out.write( SurfacingConstants.NL );
1746 catch ( final IOException e ) {
1747 ForesterUtil.fatalError( surfacing.PRG_NAME, e.getMessage() );
1749 ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote characters detailed HTML list: \"" + filename + "\"" );
1752 public static void writeDomainCombinationsCountsFile( final String[][] input_file_properties,
1753 final File output_dir,
1754 final Writer per_genome_domain_promiscuity_statistics_writer,
1755 final GenomeWideCombinableDomains gwcd,
1757 final GenomeWideCombinableDomains.GenomeWideCombinableDomainsSortOrder dc_sort_order ) {
1758 File dc_outfile = new File( input_file_properties[ i ][ 0 ]
1759 + surfacing.DOMAIN_COMBINITON_COUNTS_OUTPUTFILE_SUFFIX );
1760 if ( output_dir != null ) {
1761 dc_outfile = new File( output_dir + ForesterUtil.FILE_SEPARATOR + dc_outfile );
1763 checkForOutputFileWriteability( dc_outfile );
1765 final BufferedWriter out = new BufferedWriter( new FileWriter( dc_outfile ) );
1766 out.write( gwcd.toStringBuilder( dc_sort_order ).toString() );
1769 catch ( final IOException e ) {
1770 ForesterUtil.fatalError( surfacing.PRG_NAME, e.getMessage() );
1772 final DescriptiveStatistics stats = gwcd.getPerGenomeDomainPromiscuityStatistics();
1774 per_genome_domain_promiscuity_statistics_writer.write( input_file_properties[ i ][ 0 ] + "\t" );
1775 per_genome_domain_promiscuity_statistics_writer.write( FORMATTER_3.format( stats.arithmeticMean() ) + "\t" );
1776 if ( stats.getN() < 2 ) {
1777 per_genome_domain_promiscuity_statistics_writer.write( "n/a" + "\t" );
1780 per_genome_domain_promiscuity_statistics_writer.write( FORMATTER_3.format( stats
1781 .sampleStandardDeviation() ) + "\t" );
1783 per_genome_domain_promiscuity_statistics_writer.write( FORMATTER_3.format( stats.median() ) + "\t" );
1784 per_genome_domain_promiscuity_statistics_writer.write( ( int ) stats.getMin() + "\t" );
1785 per_genome_domain_promiscuity_statistics_writer.write( ( int ) stats.getMax() + "\t" );
1786 per_genome_domain_promiscuity_statistics_writer.write( stats.getN() + "\t" );
1787 final SortedSet<DomainId> mpds = gwcd.getMostPromiscuosDomain();
1788 for( final DomainId mpd : mpds ) {
1789 per_genome_domain_promiscuity_statistics_writer.write( mpd.getId() + " " );
1791 per_genome_domain_promiscuity_statistics_writer.write( ForesterUtil.LINE_SEPARATOR );
1793 catch ( final IOException e ) {
1794 ForesterUtil.fatalError( surfacing.PRG_NAME, e.getMessage() );
1796 if ( input_file_properties[ i ].length == 3 ) {
1797 ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote domain combination counts for \""
1798 + input_file_properties[ i ][ 0 ] + "\" (" + input_file_properties[ i ][ 1 ] + ", "
1799 + input_file_properties[ i ][ 2 ] + ") to: \"" + dc_outfile + "\"" );
1802 ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote domain combination counts for \""
1803 + input_file_properties[ i ][ 0 ] + "\" (" + input_file_properties[ i ][ 1 ] + ") to: \""
1804 + dc_outfile + "\"" );
1808 private static void writeDomainData( final Map<DomainId, List<GoId>> domain_id_to_go_ids_map,
1809 final Map<GoId, GoTerm> go_id_to_term_map,
1810 final GoNameSpace go_namespace_limit,
1812 final String domain_0,
1813 final String domain_1,
1814 final String prefix_for_html,
1815 final String character_separator_for_non_html_output,
1816 final Map<DomainId, Set<String>>[] domain_id_to_secondary_features_maps,
1817 final Set<GoId> all_go_ids ) throws IOException {
1818 boolean any_go_annotation_present = false;
1819 boolean first_has_no_go = false;
1820 int domain_count = 2; // To distinguish between domains and binary domain combinations.
1821 if ( ForesterUtil.isEmpty( domain_1 ) ) {
1824 // The following has a difficult to understand logic.
1825 for( int d = 0; d < domain_count; ++d ) {
1826 List<GoId> go_ids = null;
1827 boolean go_annotation_present = false;
1829 final DomainId domain_id = new DomainId( domain_0 );
1830 if ( domain_id_to_go_ids_map.containsKey( domain_id ) ) {
1831 go_annotation_present = true;
1832 any_go_annotation_present = true;
1833 go_ids = domain_id_to_go_ids_map.get( domain_id );
1836 first_has_no_go = true;
1840 final DomainId domain_id = new DomainId( domain_1 );
1841 if ( domain_id_to_go_ids_map.containsKey( domain_id ) ) {
1842 go_annotation_present = true;
1843 any_go_annotation_present = true;
1844 go_ids = domain_id_to_go_ids_map.get( domain_id );
1847 if ( go_annotation_present ) {
1848 boolean first = ( ( d == 0 ) || ( ( d == 1 ) && first_has_no_go ) );
1849 for( final GoId go_id : go_ids ) {
1850 out.write( "<tr>" );
1853 writeDomainIdsToHtml( out,
1857 domain_id_to_secondary_features_maps );
1860 out.write( "<td></td>" );
1862 if ( !go_id_to_term_map.containsKey( go_id ) ) {
1863 throw new IllegalArgumentException( "GO-id [" + go_id + "] not found in GO-id to GO-term map" );
1865 final GoTerm go_term = go_id_to_term_map.get( go_id );
1866 if ( ( go_namespace_limit == null ) || go_namespace_limit.equals( go_term.getGoNameSpace() ) ) {
1867 // final String top = GoUtils.getPenultimateGoTerm( go_term, go_id_to_term_map ).getName();
1868 final String go_id_str = go_id.getId();
1869 out.write( "<td>" );
1870 out.write( "<a href=\"" + SurfacingConstants.AMIGO_LINK + go_id_str
1871 + "\" target=\"amigo_window\">" + go_id_str + "</a>" );
1872 out.write( "</td><td>" );
1873 out.write( go_term.getName() );
1874 if ( domain_count == 2 ) {
1875 out.write( " (" + d + ")" );
1877 out.write( "</td><td>" );
1878 // out.write( top );
1879 // out.write( "</td><td>" );
1881 out.write( go_term.getGoNameSpace().toShortString() );
1883 out.write( "</td>" );
1884 if ( all_go_ids != null ) {
1885 all_go_ids.add( go_id );
1889 out.write( "<td>" );
1890 out.write( "</td><td>" );
1891 out.write( "</td><td>" );
1892 out.write( "</td><td>" );
1893 out.write( "</td>" );
1895 out.write( "</tr>" );
1896 out.write( SurfacingConstants.NL );
1899 } // for( int d = 0; d < domain_count; ++d )
1900 if ( !any_go_annotation_present ) {
1901 out.write( "<tr>" );
1902 writeDomainIdsToHtml( out, domain_0, domain_1, prefix_for_html, domain_id_to_secondary_features_maps );
1903 out.write( "<td>" );
1904 out.write( "</td><td>" );
1905 out.write( "</td><td>" );
1906 out.write( "</td><td>" );
1907 out.write( "</td>" );
1908 out.write( "</tr>" );
1909 out.write( SurfacingConstants.NL );
1913 private static void writeDomainIdsToHtml( final Writer out,
1914 final String domain_0,
1915 final String domain_1,
1916 final String prefix_for_detailed_html,
1917 final Map<DomainId, Set<String>>[] domain_id_to_secondary_features_maps )
1918 throws IOException {
1919 out.write( "<td>" );
1920 if ( !ForesterUtil.isEmpty( prefix_for_detailed_html ) ) {
1921 out.write( prefix_for_detailed_html );
1924 out.write( "<a href=\"" + SurfacingConstants.PFAM_FAMILY_ID_LINK + domain_0 + "\">" + domain_0 + "</a>" );
1925 out.write( "</td>" );
1928 public static DescriptiveStatistics writeDomainSimilaritiesToFile( final StringBuilder html_desc,
1929 final StringBuilder html_title,
1931 final SortedSet<DomainSimilarity> similarities,
1932 final boolean treat_as_binary,
1933 final List<Species> species_order,
1934 final PrintableDomainSimilarity.PRINT_OPTION print_option,
1935 final DomainSimilarity.DomainSimilaritySortField sort_field,
1936 final DomainSimilarity.DomainSimilarityScoring scoring,
1937 final boolean verbose ) throws IOException {
1938 final DescriptiveStatistics stats = new BasicDescriptiveStatistics();
1939 String histogram_title = null;
1940 switch ( sort_field ) {
1941 case ABS_MAX_COUNTS_DIFFERENCE:
1942 if ( treat_as_binary ) {
1943 histogram_title = "absolute counts difference:";
1946 histogram_title = "absolute (maximal) counts difference:";
1949 case MAX_COUNTS_DIFFERENCE:
1950 if ( treat_as_binary ) {
1951 histogram_title = "counts difference:";
1954 histogram_title = "(maximal) counts difference:";
1958 histogram_title = "score mean:";
1961 histogram_title = "score minimum:";
1964 histogram_title = "score maximum:";
1966 case MAX_DIFFERENCE:
1967 if ( treat_as_binary ) {
1968 histogram_title = "difference:";
1971 histogram_title = "(maximal) difference:";
1975 histogram_title = "score mean:";
1978 histogram_title = "score standard deviation:";
1981 histogram_title = "species number:";
1984 throw new AssertionError( "Unknown sort field: " + sort_field );
1986 for( final DomainSimilarity similarity : similarities ) {
1987 switch ( sort_field ) {
1988 case ABS_MAX_COUNTS_DIFFERENCE:
1989 stats.addValue( Math.abs( similarity.getMaximalDifferenceInCounts() ) );
1991 case MAX_COUNTS_DIFFERENCE:
1992 stats.addValue( similarity.getMaximalDifferenceInCounts() );
1995 stats.addValue( similarity.getMeanSimilarityScore() );
1998 stats.addValue( similarity.getMinimalSimilarityScore() );
2001 stats.addValue( similarity.getMaximalSimilarityScore() );
2003 case MAX_DIFFERENCE:
2004 stats.addValue( similarity.getMaximalDifference() );
2007 stats.addValue( similarity.getMeanSimilarityScore() );
2010 stats.addValue( similarity.getStandardDeviationOfSimilarityScore() );
2013 stats.addValue( similarity.getSpecies().size() );
2016 throw new AssertionError( "Unknown sort field: " + sort_field );
2020 // final HistogramData[] hists = new HistogramData[ 1 ];
2023 // List<HistogramDataItem> data_items = new
2024 // ArrayList<HistogramDataItem>();
2025 // double[] values = stats.getDataAsDoubleArray();
2026 // for( int i = 0; i < values.length; i++ ) {
2027 // HistogramDataItem data_item = new BasicHistogramDataItem( "", values[
2029 // data_items.add( data_item );
2033 // HistogramData hd0 = new HistogramData( "name",
2041 // hists[ 0 ] = hd0;
2043 // final HistogramsFrame hf = new HistogramsFrame( hists );
2044 // hf.setVisible( true );
2046 AsciiHistogram histo = null;
2047 if ( stats.getMin() < stats.getMin() ) {
2048 histo = new AsciiHistogram( stats, histogram_title );
2051 if ( histo != null ) {
2052 System.out.println( histo.toStringBuffer( 20, '|', 40, 5 ) );
2054 System.out.println();
2055 System.out.println( "N : " + stats.getN() );
2056 System.out.println( "Min : " + stats.getMin() );
2057 System.out.println( "Max : " + stats.getMax() );
2058 System.out.println( "Mean : " + stats.arithmeticMean() );
2059 if ( stats.getN() > 1 ) {
2060 System.out.println( "SD : " + stats.sampleStandardDeviation() );
2063 System.out.println( "SD : n/a" );
2065 System.out.println( "Median : " + stats.median() );
2066 if ( stats.getN() > 1 ) {
2067 System.out.println( "Pearsonian skewness : " + stats.pearsonianSkewness() );
2070 System.out.println( "Pearsonian skewness : n/a" );
2073 switch ( print_option ) {
2074 case SIMPLE_TAB_DELIMITED:
2077 w.write( "<html>" );
2078 w.write( SurfacingConstants.NL );
2079 addHtmlHead( w, "SURFACING :: " + html_title );
2080 w.write( SurfacingConstants.NL );
2081 w.write( "<body>" );
2082 w.write( SurfacingConstants.NL );
2083 w.write( html_desc.toString() );
2084 w.write( SurfacingConstants.NL );
2087 w.write( SurfacingConstants.NL );
2088 w.write( "<tt><pre>" );
2089 w.write( SurfacingConstants.NL );
2090 if ( histo != null ) {
2091 w.write( histo.toStringBuffer( 20, '|', 40, 5 ).toString() );
2092 w.write( SurfacingConstants.NL );
2094 w.write( "</pre></tt>" );
2095 w.write( SurfacingConstants.NL );
2096 w.write( "<table>" );
2097 w.write( SurfacingConstants.NL );
2098 w.write( "<tr><td>N: </td><td>" + stats.getN() + "</td></tr>" );
2099 w.write( SurfacingConstants.NL );
2100 w.write( "<tr><td>Min: </td><td>" + stats.getMin() + "</td></tr>" );
2101 w.write( SurfacingConstants.NL );
2102 w.write( "<tr><td>Max: </td><td>" + stats.getMax() + "</td></tr>" );
2103 w.write( SurfacingConstants.NL );
2104 w.write( "<tr><td>Mean: </td><td>" + stats.arithmeticMean() + "</td></tr>" );
2105 w.write( SurfacingConstants.NL );
2106 if ( stats.getN() > 1 ) {
2107 w.write( "<tr><td>SD: </td><td>" + stats.sampleStandardDeviation() + "</td></tr>" );
2110 w.write( "<tr><td>SD: </td><td>n/a</td></tr>" );
2112 w.write( SurfacingConstants.NL );
2113 w.write( "<tr><td>Median: </td><td>" + stats.median() + "</td></tr>" );
2114 w.write( SurfacingConstants.NL );
2115 if ( stats.getN() > 1 ) {
2116 w.write( "<tr><td>Pearsonian skewness: </td><td>" + stats.pearsonianSkewness() + "</td></tr>" );
2119 w.write( "<tr><td>Pearsonian skewness: </td><td>n/a</td></tr>" );
2121 w.write( SurfacingConstants.NL );
2122 w.write( "</table>" );
2123 w.write( SurfacingConstants.NL );
2125 w.write( SurfacingConstants.NL );
2127 w.write( SurfacingConstants.NL );
2129 w.write( SurfacingConstants.NL );
2130 w.write( "<table>" );
2131 w.write( SurfacingConstants.NL );
2134 w.write( SurfacingConstants.NL );
2135 for( final DomainSimilarity similarity : similarities ) {
2136 if ( ( species_order != null ) && !species_order.isEmpty() ) {
2137 ( ( PrintableDomainSimilarity ) similarity ).setSpeciesOrder( species_order );
2139 w.write( similarity.toStringBuffer( print_option ).toString() );
2140 w.write( SurfacingConstants.NL );
2142 switch ( print_option ) {
2144 w.write( SurfacingConstants.NL );
2145 w.write( "</table>" );
2146 w.write( SurfacingConstants.NL );
2147 w.write( "</font>" );
2148 w.write( SurfacingConstants.NL );
2149 w.write( "</body>" );
2150 w.write( SurfacingConstants.NL );
2151 w.write( "</html>" );
2152 w.write( SurfacingConstants.NL );
2160 private static void writeDomainsToIndividualFilePerTreeNode( final Writer individual_files_writer,
2161 final String domain_0,
2162 final String domain_1 ) throws IOException {
2163 individual_files_writer.write( domain_0 );
2164 individual_files_writer.write( ForesterUtil.LINE_SEPARATOR );
2165 if ( !ForesterUtil.isEmpty( domain_1 ) ) {
2166 individual_files_writer.write( domain_1 );
2167 individual_files_writer.write( ForesterUtil.LINE_SEPARATOR );
2171 public static void writeMatrixToFile( final CharacterStateMatrix<?> matrix,
2172 final String filename,
2173 final Format format ) {
2174 final File outfile = new File( filename );
2175 checkForOutputFileWriteability( outfile );
2177 final BufferedWriter out = new BufferedWriter( new FileWriter( outfile ) );
2178 matrix.toWriter( out, format );
2182 catch ( final IOException e ) {
2183 ForesterUtil.fatalError( surfacing.PRG_NAME, e.getMessage() );
2185 ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote matrix: \"" + filename + "\"" );
2188 public static void writeMatrixToFile( final File matrix_outfile, final List<DistanceMatrix> matrices ) {
2189 checkForOutputFileWriteability( matrix_outfile );
2191 final BufferedWriter out = new BufferedWriter( new FileWriter( matrix_outfile ) );
2192 for( final DistanceMatrix distance_matrix : matrices ) {
2193 out.write( distance_matrix.toStringBuffer( DistanceMatrix.Format.PHYLIP ).toString() );
2194 out.write( ForesterUtil.LINE_SEPARATOR );
2199 catch ( final IOException e ) {
2200 ForesterUtil.fatalError( surfacing.PRG_NAME, e.getMessage() );
2202 ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote distance matrices to \"" + matrix_outfile + "\"" );
2205 private static void writePfamsToFile( final String outfile_name, final SortedSet<String> pfams ) {
2207 final Writer writer = new BufferedWriter( new FileWriter( new File( outfile_name ) ) );
2208 for( final String pfam : pfams ) {
2209 writer.write( pfam );
2210 writer.write( ForesterUtil.LINE_SEPARATOR );
2213 ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote " + pfams.size() + " pfams to [" + outfile_name
2216 catch ( final IOException e ) {
2217 ForesterUtil.printWarningMessage( surfacing.PRG_NAME, "Failure to write: " + e );
2221 public static void writePhylogenyToFile( final Phylogeny phylogeny, final String filename ) {
2222 final PhylogenyWriter writer = new PhylogenyWriter();
2224 writer.toPhyloXML( new File( filename ), phylogeny, 1 );
2226 catch ( final IOException e ) {
2227 ForesterUtil.printWarningMessage( surfacing.PRG_NAME, "failed to write phylogeny to \"" + filename + "\": "
2230 ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote phylogeny to \"" + filename + "\"" );
2233 public static void writeTaxonomyLinks( final Writer writer, final String species ) throws IOException {
2234 if ( ( species.length() > 1 ) && ( species.indexOf( '_' ) < 1 ) ) {
2235 final Matcher matcher = PATTERN_SP_STYLE_TAXONOMY.matcher( species );
2236 writer.write( " [" );
2237 if ( matcher.matches() ) {
2238 writer.write( "<a href=\"" + SurfacingConstants.UNIPROT_LINK + species
2239 + "\" target=\"taxonomy_window\">uniprot</a>" );
2242 writer.write( "<a href=\"" + SurfacingConstants.EOL_LINK + species
2243 + "\" target=\"taxonomy_window\">eol</a>" );
2244 writer.write( "|" );
2245 writer.write( "<a href=\"" + SurfacingConstants.TOL_LINK + species
2246 + "\" target=\"taxonomy_window\">tol</a>" );
2248 writer.write( "]" );
2252 private static void writeToNexus( final String outfile_name,
2253 final CharacterStateMatrix<BinaryStates> matrix,
2254 final Phylogeny phylogeny ) {
2255 if ( !( matrix instanceof BasicCharacterStateMatrix ) ) {
2256 throw new IllegalArgumentException( "can only write matrices of type [" + BasicCharacterStateMatrix.class
2259 final BasicCharacterStateMatrix<BinaryStates> my_matrix = ( org.forester.evoinference.matrix.character.BasicCharacterStateMatrix<BinaryStates> ) matrix;
2260 final List<Phylogeny> phylogenies = new ArrayList<Phylogeny>( 1 );
2261 phylogenies.add( phylogeny );
2263 final BufferedWriter w = new BufferedWriter( new FileWriter( outfile_name ) );
2264 w.write( NexusConstants.NEXUS );
2265 w.write( ForesterUtil.LINE_SEPARATOR );
2266 my_matrix.writeNexusTaxaBlock( w );
2267 my_matrix.writeNexusBinaryChractersBlock( w );
2268 PhylogenyWriter.writeNexusTreesBlock( w, phylogenies );
2271 ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote Nexus file: \"" + outfile_name + "\"" );
2273 catch ( final IOException e ) {
2274 ForesterUtil.fatalError( surfacing.PRG_NAME, e.getMessage() );
2278 private static void writeToNexus( final String outfile_name,
2279 final DomainParsimonyCalculator domain_parsimony,
2280 final Phylogeny phylogeny ) {
2281 writeToNexus( outfile_name + surfacing.NEXUS_EXTERNAL_DOMAINS,
2282 domain_parsimony.createMatrixOfDomainPresenceOrAbsence(),
2284 writeToNexus( outfile_name + surfacing.NEXUS_EXTERNAL_DOMAIN_COMBINATIONS,
2285 domain_parsimony.createMatrixOfBinaryDomainCombinationPresenceOrAbsence(),