3 // FORESTER -- software libraries and applications
4 // for evolutionary biology research and applications.
6 // Copyright (C) 2008-2009 Christian M. Zmasek
7 // Copyright (C) 2008-2009 Burnham Institute for Medical Research
10 // This library is free software; you can redistribute it and/or
11 // modify it under the terms of the GNU Lesser General Public
12 // License as published by the Free Software Foundation; either
13 // version 2.1 of the License, or (at your option) any later version.
15 // This library is distributed in the hope that it will be useful,
16 // but WITHOUT ANY WARRANTY; without even the implied warranty of
17 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
18 // Lesser General Public License for more details.
20 // You should have received a copy of the GNU Lesser General Public
21 // License along with this library; if not, write to the Free Software
22 // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
24 // Contact: phylosoft @ gmail . com
25 // WWW: www.phylosoft.org/forester
27 package org.forester.surfacing;
29 import java.io.BufferedWriter;
31 import java.io.FileWriter;
32 import java.io.IOException;
33 import java.io.Writer;
34 import java.text.DecimalFormat;
35 import java.text.NumberFormat;
36 import java.util.ArrayList;
37 import java.util.Arrays;
38 import java.util.Collections;
39 import java.util.Comparator;
40 import java.util.HashMap;
41 import java.util.HashSet;
42 import java.util.List;
44 import java.util.PriorityQueue;
46 import java.util.SortedMap;
47 import java.util.SortedSet;
48 import java.util.TreeMap;
49 import java.util.TreeSet;
50 import java.util.regex.Matcher;
51 import java.util.regex.Pattern;
53 import org.forester.application.surfacing;
54 import org.forester.evoinference.distance.NeighborJoining;
55 import org.forester.evoinference.matrix.character.BasicCharacterStateMatrix;
56 import org.forester.evoinference.matrix.character.CharacterStateMatrix;
57 import org.forester.evoinference.matrix.character.CharacterStateMatrix.BinaryStates;
58 import org.forester.evoinference.matrix.character.CharacterStateMatrix.Format;
59 import org.forester.evoinference.matrix.character.CharacterStateMatrix.GainLossStates;
60 import org.forester.evoinference.matrix.distance.DistanceMatrix;
61 import org.forester.go.GoId;
62 import org.forester.go.GoNameSpace;
63 import org.forester.go.GoTerm;
64 import org.forester.go.PfamToGoMapping;
65 import org.forester.io.parsers.nexus.NexusConstants;
66 import org.forester.io.writers.PhylogenyWriter;
67 import org.forester.phylogeny.Phylogeny;
68 import org.forester.phylogeny.PhylogenyMethods;
69 import org.forester.phylogeny.PhylogenyNode;
70 import org.forester.phylogeny.PhylogenyNodeI.NH_CONVERSION_SUPPORT_VALUE_STYLE;
71 import org.forester.phylogeny.data.BinaryCharacters;
72 import org.forester.phylogeny.data.Confidence;
73 import org.forester.phylogeny.iterators.PhylogenyNodeIterator;
74 import org.forester.surfacing.DomainSimilarityCalculator.Detailedness;
75 import org.forester.surfacing.DomainSimilarityCalculator.GoAnnotationOutput;
76 import org.forester.surfacing.GenomeWideCombinableDomains.GenomeWideCombinableDomainsSortOrder;
77 import org.forester.util.AsciiHistogram;
78 import org.forester.util.BasicDescriptiveStatistics;
79 import org.forester.util.BasicTable;
80 import org.forester.util.BasicTableParser;
81 import org.forester.util.DescriptiveStatistics;
82 import org.forester.util.ForesterUtil;
84 public final class SurfacingUtil {
86 private final static NumberFormat FORMATTER = new DecimalFormat( "0.0E0" );
87 private final static NumberFormat FORMATTER_3 = new DecimalFormat( "0.000" );
88 private static final Comparator<Domain> ASCENDING_CONFIDENCE_VALUE_ORDER = new Comparator<Domain>() {
91 public int compare( final Domain d1,
93 if ( d1.getPerSequenceEvalue() < d2
94 .getPerSequenceEvalue() ) {
98 .getPerSequenceEvalue() > d2
99 .getPerSequenceEvalue() ) {
103 return d1.compareTo( d2 );
107 public final static Pattern PATTERN_SP_STYLE_TAXONOMY = Pattern.compile( "^[A-Z0-9]{3,5}$" );
108 private static final boolean USE_LAST = true;
110 private SurfacingUtil() {
111 // Hidden constructor.
114 public static void addAllBinaryDomainCombinationToSet( final GenomeWideCombinableDomains genome,
115 final SortedSet<BinaryDomainCombination> binary_domain_combinations ) {
116 final SortedMap<DomainId, CombinableDomains> all_cd = genome.getAllCombinableDomainsIds();
117 for( final DomainId domain_id : all_cd.keySet() ) {
118 binary_domain_combinations.addAll( all_cd.get( domain_id ).toBinaryDomainCombinations() );
122 public static void addAllDomainIdsToSet( final GenomeWideCombinableDomains genome,
123 final SortedSet<DomainId> domain_ids ) {
124 final SortedSet<DomainId> domains = genome.getAllDomainIds();
125 for( final DomainId domain : domains ) {
126 domain_ids.add( domain );
130 public static void addHtmlHead( final Writer w, final String title ) throws IOException {
131 w.write( SurfacingConstants.NL );
133 w.write( "<title>" );
135 w.write( "</title>" );
136 w.write( SurfacingConstants.NL );
137 w.write( "<style>" );
138 w.write( SurfacingConstants.NL );
139 w.write( "a:visited { color : #6633FF; text-decoration : none; }" );
140 w.write( SurfacingConstants.NL );
141 w.write( "a:link { color : #6633FF; text-decoration : none; }" );
142 w.write( SurfacingConstants.NL );
143 w.write( "a:active { color : #99FF00; text-decoration : none; }" );
144 w.write( SurfacingConstants.NL );
145 w.write( "a:hover { color : #FFFFFF; background-color : #99FF00; text-decoration : none; }" );
146 w.write( SurfacingConstants.NL );
147 w.write( "td { text-align: left; vertical-align: top; font-family: Verdana, Arial, Helvetica; font-size: 8pt}" );
148 w.write( SurfacingConstants.NL );
149 w.write( "h1 { color : #0000FF; font-family: Verdana, Arial, Helvetica; font-size: 18pt; font-weight: bold }" );
150 w.write( SurfacingConstants.NL );
151 w.write( "h2 { color : #0000FF; font-family: Verdana, Arial, Helvetica; font-size: 16pt; font-weight: bold }" );
152 w.write( SurfacingConstants.NL );
153 w.write( "</style>" );
154 w.write( SurfacingConstants.NL );
155 w.write( "</head>" );
156 w.write( SurfacingConstants.NL );
159 public static DescriptiveStatistics calculateDescriptiveStatisticsForMeanValues( final Set<DomainSimilarity> similarities ) {
160 final DescriptiveStatistics stats = new BasicDescriptiveStatistics();
161 for( final DomainSimilarity similarity : similarities ) {
162 stats.addValue( similarity.getMeanSimilarityScore() );
167 private static void calculateIndependentDomainCombinationGains( final Phylogeny local_phylogeny_l,
168 final String outfilename_for_counts,
169 final String outfilename_for_dc,
170 final String outfilename_for_dc_for_go_mapping,
171 final String outfilename_for_dc_for_go_mapping_unique,
172 final String outfilename_for_rank_counts,
173 final String outfilename_for_ancestor_species_counts ) {
175 final BufferedWriter out_counts = new BufferedWriter( new FileWriter( outfilename_for_counts ) );
176 final BufferedWriter out_dc = new BufferedWriter( new FileWriter( outfilename_for_dc ) );
177 final BufferedWriter out_dc_for_go_mapping = new BufferedWriter( new FileWriter( outfilename_for_dc_for_go_mapping ) );
178 final BufferedWriter out_dc_for_go_mapping_unique = new BufferedWriter( new FileWriter( outfilename_for_dc_for_go_mapping_unique ) );
179 final SortedMap<String, Integer> dc_gain_counts = new TreeMap<String, Integer>();
180 for( final PhylogenyNodeIterator it = local_phylogeny_l.iteratorPostorder(); it.hasNext(); ) {
181 final PhylogenyNode n = it.next();
182 final Set<String> gained_dc = n.getNodeData().getBinaryCharacters().getGainedCharacters();
183 for( final String dc : gained_dc ) {
184 if ( dc_gain_counts.containsKey( dc ) ) {
185 dc_gain_counts.put( dc, dc_gain_counts.get( dc ) + 1 );
188 dc_gain_counts.put( dc, 1 );
192 final SortedMap<Integer, Integer> histogram = new TreeMap<Integer, Integer>();
193 final SortedMap<Integer, StringBuilder> domain_lists = new TreeMap<Integer, StringBuilder>();
194 final SortedMap<Integer, PriorityQueue<String>> domain_lists_go = new TreeMap<Integer, PriorityQueue<String>>();
195 final SortedMap<Integer, SortedSet<String>> domain_lists_go_unique = new TreeMap<Integer, SortedSet<String>>();
196 final Set<String> dcs = dc_gain_counts.keySet();
197 final SortedSet<String> more_than_once = new TreeSet<String>();
198 for( final String dc : dcs ) {
199 final int count = dc_gain_counts.get( dc );
200 if ( histogram.containsKey( count ) ) {
201 histogram.put( count, histogram.get( count ) + 1 );
202 domain_lists.get( count ).append( ", " + dc );
203 domain_lists_go.get( count ).addAll( splitDomainCombination( dc ) );
204 domain_lists_go_unique.get( count ).addAll( splitDomainCombination( dc ) );
207 histogram.put( count, 1 );
208 domain_lists.put( count, new StringBuilder( dc ) );
209 final PriorityQueue<String> q = new PriorityQueue<String>();
210 q.addAll( splitDomainCombination( dc ) );
211 domain_lists_go.put( count, q );
212 final SortedSet<String> set = new TreeSet<String>();
213 set.addAll( splitDomainCombination( dc ) );
214 domain_lists_go_unique.put( count, set );
217 more_than_once.add( dc );
220 final Set<Integer> histogram_keys = histogram.keySet();
221 for( final Integer histogram_key : histogram_keys ) {
222 final int count = histogram.get( histogram_key );
223 final StringBuilder dc = domain_lists.get( histogram_key );
224 out_counts.write( histogram_key + "\t" + count + ForesterUtil.LINE_SEPARATOR );
225 out_dc.write( histogram_key + "\t" + dc + ForesterUtil.LINE_SEPARATOR );
226 out_dc_for_go_mapping.write( "#" + histogram_key + ForesterUtil.LINE_SEPARATOR );
227 final Object[] sorted = domain_lists_go.get( histogram_key ).toArray();
228 Arrays.sort( sorted );
229 for( final Object domain : sorted ) {
230 out_dc_for_go_mapping.write( domain + ForesterUtil.LINE_SEPARATOR );
232 out_dc_for_go_mapping_unique.write( "#" + histogram_key + ForesterUtil.LINE_SEPARATOR );
233 for( final String domain : domain_lists_go_unique.get( histogram_key ) ) {
234 out_dc_for_go_mapping_unique.write( domain + ForesterUtil.LINE_SEPARATOR );
239 out_dc_for_go_mapping.close();
240 out_dc_for_go_mapping_unique.close();
242 final SortedMap<String, Integer> lca_rank_counts = new TreeMap<String, Integer>();
243 final SortedMap<String, Integer> lca_ancestor_species_counts = new TreeMap<String, Integer>();
244 for( final String dc : more_than_once ) {
245 final List<PhylogenyNode> nodes = new ArrayList<PhylogenyNode>();
246 for( final PhylogenyNodeIterator it = local_phylogeny_l.iteratorExternalForward(); it.hasNext(); ) {
247 final PhylogenyNode n = it.next();
248 if ( n.getNodeData().getBinaryCharacters().getGainedCharacters().contains( dc ) ) {
252 for( int i = 0; i < nodes.size() - 1; ++i ) {
253 for( int j = i + 1; j < nodes.size(); ++j ) {
254 final PhylogenyNode lca = PhylogenyMethods.getInstance().obtainLCA( nodes.get( i ),
256 String rank = "unknown";
257 if ( lca.getNodeData().isHasTaxonomy()
258 && !ForesterUtil.isEmpty( lca.getNodeData().getTaxonomy().getRank() ) ) {
259 rank = lca.getNodeData().getTaxonomy().getRank();
261 addToCountMap( lca_rank_counts, rank );
263 if ( lca.getNodeData().isHasTaxonomy()
264 && !ForesterUtil.isEmpty( lca.getNodeData().getTaxonomy().getScientificName() ) ) {
265 lca_species = lca.getNodeData().getTaxonomy().getScientificName();
267 else if ( lca.getNodeData().isHasTaxonomy()
268 && !ForesterUtil.isEmpty( lca.getNodeData().getTaxonomy().getCommonName() ) ) {
269 lca_species = lca.getNodeData().getTaxonomy().getCommonName();
272 lca_species = lca.getName();
274 addToCountMap( lca_ancestor_species_counts, lca_species );
278 final BufferedWriter out_for_rank_counts = new BufferedWriter( new FileWriter( outfilename_for_rank_counts ) );
279 final BufferedWriter out_for_ancestor_species_counts = new BufferedWriter( new FileWriter( outfilename_for_ancestor_species_counts ) );
280 ForesterUtil.map2writer( out_for_rank_counts, lca_rank_counts, "\t", ForesterUtil.LINE_SEPARATOR );
281 ForesterUtil.map2writer( out_for_ancestor_species_counts,
282 lca_ancestor_species_counts,
284 ForesterUtil.LINE_SEPARATOR );
285 out_for_rank_counts.close();
286 out_for_ancestor_species_counts.close();
288 catch ( final IOException e ) {
289 ForesterUtil.printWarningMessage( surfacing.PRG_NAME, "Failure to write: " + e );
291 ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote independent domain combination gains fitch counts to ["
292 + outfilename_for_counts + "]" );
293 ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote independent domain combination gains fitch lists to ["
294 + outfilename_for_dc + "]" );
295 ForesterUtil.programMessage( surfacing.PRG_NAME,
296 "Wrote independent domain combination gains fitch lists to (for GO mapping) ["
297 + outfilename_for_dc_for_go_mapping + "]" );
298 ForesterUtil.programMessage( surfacing.PRG_NAME,
299 "Wrote independent domain combination gains fitch lists to (for GO mapping, unique) ["
300 + outfilename_for_dc_for_go_mapping_unique + "]" );
303 private final static void addToCountMap( final Map<String, Integer> map, final String s ) {
304 if ( map.containsKey( s ) ) {
305 map.put( s, map.get( s ) + 1 );
312 public static int calculateOverlap( final Domain domain, final List<Boolean> covered_positions ) {
313 int overlap_count = 0;
314 for( int i = domain.getFrom(); i <= domain.getTo(); ++i ) {
315 if ( ( i < covered_positions.size() ) && ( covered_positions.get( i ) == true ) ) {
319 return overlap_count;
322 public static void checkForOutputFileWriteability( final File outfile ) {
323 final String error = ForesterUtil.isWritableFile( outfile );
324 if ( !ForesterUtil.isEmpty( error ) ) {
325 ForesterUtil.fatalError( surfacing.PRG_NAME, error );
329 private static SortedSet<String> collectAllDomainsChangedOnSubtree( final PhylogenyNode subtree_root,
330 final boolean get_gains ) {
331 final SortedSet<String> domains = new TreeSet<String>();
332 for( final PhylogenyNode descendant : PhylogenyMethods.getAllDescendants( subtree_root ) ) {
333 final BinaryCharacters chars = descendant.getNodeData().getBinaryCharacters();
335 domains.addAll( chars.getGainedCharacters() );
338 domains.addAll( chars.getLostCharacters() );
344 public static void collectChangedDomainCombinationsFromBinaryStatesMatrixAsListToFile( final CharacterStateMatrix<CharacterStateMatrix.GainLossStates> matrix,
345 final BinaryDomainCombination.DomainCombinationType dc_type,
346 final List<BinaryDomainCombination> all_binary_domains_combination_gained,
347 final boolean get_gains ) {
348 final SortedSet<String> sorted_ids = new TreeSet<String>();
349 for( int i = 0; i < matrix.getNumberOfIdentifiers(); ++i ) {
350 sorted_ids.add( matrix.getIdentifier( i ) );
352 for( final String id : sorted_ids ) {
353 for( int c = 0; c < matrix.getNumberOfCharacters(); ++c ) {
354 if ( ( get_gains && ( matrix.getState( id, c ) == CharacterStateMatrix.GainLossStates.GAIN ) )
355 || ( !get_gains && ( matrix.getState( id, c ) == CharacterStateMatrix.GainLossStates.LOSS ) ) ) {
356 if ( dc_type == BinaryDomainCombination.DomainCombinationType.DIRECTED_ADJACTANT ) {
357 all_binary_domains_combination_gained.add( AdjactantDirectedBinaryDomainCombination
358 .createInstance( matrix.getCharacter( c ) ) );
360 else if ( dc_type == BinaryDomainCombination.DomainCombinationType.DIRECTED ) {
361 all_binary_domains_combination_gained.add( DirectedBinaryDomainCombination
362 .createInstance( matrix.getCharacter( c ) ) );
365 all_binary_domains_combination_gained.add( BasicBinaryDomainCombination.createInstance( matrix
366 .getCharacter( c ) ) );
373 private static File createBaseDirForPerNodeDomainFiles( final String base_dir,
374 final boolean domain_combinations,
375 final CharacterStateMatrix.GainLossStates state,
376 final String outfile ) {
377 File per_node_go_mapped_domain_gain_loss_files_base_dir = new File( new File( outfile ).getParent()
378 + ForesterUtil.FILE_SEPARATOR + base_dir );
379 if ( !per_node_go_mapped_domain_gain_loss_files_base_dir.exists() ) {
380 per_node_go_mapped_domain_gain_loss_files_base_dir.mkdir();
382 if ( domain_combinations ) {
383 per_node_go_mapped_domain_gain_loss_files_base_dir = new File( per_node_go_mapped_domain_gain_loss_files_base_dir
384 + ForesterUtil.FILE_SEPARATOR + "DC" );
387 per_node_go_mapped_domain_gain_loss_files_base_dir = new File( per_node_go_mapped_domain_gain_loss_files_base_dir
388 + ForesterUtil.FILE_SEPARATOR + "DOMAINS" );
390 if ( !per_node_go_mapped_domain_gain_loss_files_base_dir.exists() ) {
391 per_node_go_mapped_domain_gain_loss_files_base_dir.mkdir();
393 if ( state == GainLossStates.GAIN ) {
394 per_node_go_mapped_domain_gain_loss_files_base_dir = new File( per_node_go_mapped_domain_gain_loss_files_base_dir
395 + ForesterUtil.FILE_SEPARATOR + "GAINS" );
397 else if ( state == GainLossStates.LOSS ) {
398 per_node_go_mapped_domain_gain_loss_files_base_dir = new File( per_node_go_mapped_domain_gain_loss_files_base_dir
399 + ForesterUtil.FILE_SEPARATOR + "LOSSES" );
402 per_node_go_mapped_domain_gain_loss_files_base_dir = new File( per_node_go_mapped_domain_gain_loss_files_base_dir
403 + ForesterUtil.FILE_SEPARATOR + "PRESENT" );
405 if ( !per_node_go_mapped_domain_gain_loss_files_base_dir.exists() ) {
406 per_node_go_mapped_domain_gain_loss_files_base_dir.mkdir();
408 return per_node_go_mapped_domain_gain_loss_files_base_dir;
411 public static Map<DomainId, List<GoId>> createDomainIdToGoIdMap( final List<PfamToGoMapping> pfam_to_go_mappings ) {
412 final Map<DomainId, List<GoId>> domain_id_to_go_ids_map = new HashMap<DomainId, List<GoId>>( pfam_to_go_mappings
414 for( final PfamToGoMapping pfam_to_go : pfam_to_go_mappings ) {
415 if ( !domain_id_to_go_ids_map.containsKey( pfam_to_go.getKey() ) ) {
416 domain_id_to_go_ids_map.put( pfam_to_go.getKey(), new ArrayList<GoId>() );
418 domain_id_to_go_ids_map.get( pfam_to_go.getKey() ).add( pfam_to_go.getValue() );
420 return domain_id_to_go_ids_map;
423 public static Map<DomainId, Set<String>> createDomainIdToSecondaryFeaturesMap( final File secondary_features_map_file )
425 final BasicTable<String> primary_table = BasicTableParser.parse( secondary_features_map_file, "\t" );
426 final Map<DomainId, Set<String>> map = new TreeMap<DomainId, Set<String>>();
427 for( int r = 0; r < primary_table.getNumberOfRows(); ++r ) {
428 final DomainId domain_id = new DomainId( primary_table.getValue( 0, r ) );
429 if ( !map.containsKey( domain_id ) ) {
430 map.put( domain_id, new HashSet<String>() );
432 map.get( domain_id ).add( primary_table.getValue( 1, r ) );
437 public static Phylogeny createNjTreeBasedOnMatrixToFile( final File nj_tree_outfile, final DistanceMatrix distance ) {
438 checkForOutputFileWriteability( nj_tree_outfile );
439 final NeighborJoining nj = NeighborJoining.createInstance();
440 final Phylogeny phylogeny = nj.execute( distance );
441 phylogeny.setName( nj_tree_outfile.getName() );
442 writePhylogenyToFile( phylogeny, nj_tree_outfile.toString() );
446 private static SortedSet<BinaryDomainCombination> createSetOfAllBinaryDomainCombinationsPerGenome( final GenomeWideCombinableDomains gwcd ) {
447 final SortedMap<DomainId, CombinableDomains> cds = gwcd.getAllCombinableDomainsIds();
448 final SortedSet<BinaryDomainCombination> binary_combinations = new TreeSet<BinaryDomainCombination>();
449 for( final DomainId domain_id : cds.keySet() ) {
450 final CombinableDomains cd = cds.get( domain_id );
451 binary_combinations.addAll( cd.toBinaryDomainCombinations() );
453 return binary_combinations;
456 public static void decoratePrintableDomainSimilarities( final SortedSet<DomainSimilarity> domain_similarities,
457 final Detailedness detailedness,
458 final GoAnnotationOutput go_annotation_output,
459 final Map<GoId, GoTerm> go_id_to_term_map,
460 final GoNameSpace go_namespace_limit ) {
461 if ( ( go_namespace_limit != null ) && ( ( go_id_to_term_map == null ) || go_id_to_term_map.isEmpty() ) ) {
462 throw new IllegalArgumentException( "attempt to use a GO namespace limit without a GO id to term map" );
464 for( final DomainSimilarity domain_similarity : domain_similarities ) {
465 if ( domain_similarity instanceof PrintableDomainSimilarity ) {
466 final PrintableDomainSimilarity printable_domain_similarity = ( PrintableDomainSimilarity ) domain_similarity;
467 printable_domain_similarity.setDetailedness( detailedness );
468 printable_domain_similarity.setGoAnnotationOutput( go_annotation_output );
469 printable_domain_similarity.setGoIdToTermMap( go_id_to_term_map );
470 printable_domain_similarity.setGoNamespaceLimit( go_namespace_limit );
475 public static void executeDomainLengthAnalysis( final String[][] input_file_properties,
476 final int number_of_genomes,
477 final DomainLengthsTable domain_lengths_table,
478 final File outfile ) throws IOException {
479 final DecimalFormat df = new DecimalFormat( "#.00" );
480 checkForOutputFileWriteability( outfile );
481 final BufferedWriter out = new BufferedWriter( new FileWriter( outfile ) );
482 out.write( "MEAN BASED STATISTICS PER SPECIES" );
483 out.write( ForesterUtil.LINE_SEPARATOR );
484 out.write( domain_lengths_table.createMeanBasedStatisticsPerSpeciesTable().toString() );
485 out.write( ForesterUtil.LINE_SEPARATOR );
486 out.write( ForesterUtil.LINE_SEPARATOR );
487 final List<DomainLengths> domain_lengths_list = domain_lengths_table.getDomainLengthsList();
488 out.write( "OUTLIER SPECIES PER DOMAIN (Z>=1.5)" );
489 out.write( ForesterUtil.LINE_SEPARATOR );
490 for( final DomainLengths domain_lengths : domain_lengths_list ) {
491 final List<Species> species_list = domain_lengths.getMeanBasedOutlierSpecies( 1.5 );
492 if ( species_list.size() > 0 ) {
493 out.write( domain_lengths.getDomainId() + "\t" );
494 for( final Species species : species_list ) {
495 out.write( species + "\t" );
497 out.write( ForesterUtil.LINE_SEPARATOR );
498 // DescriptiveStatistics stats_for_domain = domain_lengths
499 // .calculateMeanBasedStatistics();
500 //AsciiHistogram histo = new AsciiHistogram( stats_for_domain );
501 //System.out.println( histo.toStringBuffer( 40, '=', 60, 4 ).toString() );
504 out.write( ForesterUtil.LINE_SEPARATOR );
505 out.write( ForesterUtil.LINE_SEPARATOR );
506 out.write( "OUTLIER SPECIES (Z 1.0)" );
507 out.write( ForesterUtil.LINE_SEPARATOR );
508 final DescriptiveStatistics stats_for_all_species = domain_lengths_table
509 .calculateMeanBasedStatisticsForAllSpecies();
510 out.write( stats_for_all_species.asSummary() );
511 out.write( ForesterUtil.LINE_SEPARATOR );
512 final AsciiHistogram histo = new AsciiHistogram( stats_for_all_species );
513 out.write( histo.toStringBuffer( 40, '=', 60, 4 ).toString() );
514 out.write( ForesterUtil.LINE_SEPARATOR );
515 final double population_sd = stats_for_all_species.sampleStandardDeviation();
516 final double population_mean = stats_for_all_species.arithmeticMean();
517 for( final Species species : domain_lengths_table.getSpecies() ) {
518 final double x = domain_lengths_table.calculateMeanBasedStatisticsForSpecies( species ).arithmeticMean();
519 final double z = ( x - population_mean ) / population_sd;
520 out.write( species + "\t" + z );
521 out.write( ForesterUtil.LINE_SEPARATOR );
523 out.write( ForesterUtil.LINE_SEPARATOR );
524 for( final Species species : domain_lengths_table.getSpecies() ) {
525 final DescriptiveStatistics stats_for_species = domain_lengths_table
526 .calculateMeanBasedStatisticsForSpecies( species );
527 final double x = stats_for_species.arithmeticMean();
528 final double z = ( x - population_mean ) / population_sd;
529 if ( ( z <= -1.0 ) || ( z >= 1.0 ) ) {
530 out.write( species + "\t" + df.format( z ) + "\t" + stats_for_species.asSummary() );
531 out.write( ForesterUtil.LINE_SEPARATOR );
535 // final List<HistogramData> histogram_datas = new ArrayList<HistogramData>();
536 // for( int i = 0; i < number_of_genomes; ++i ) {
537 // final Species species = new BasicSpecies( input_file_properties[ i ][ 0 ] );
539 // .add( new HistogramData( species.toString(), domain_lengths_table
540 // .calculateMeanBasedStatisticsForSpecies( species )
541 // .getDataAsDoubleArray(), 5, 600, null, 60 ) );
543 // final HistogramsFrame hf = new HistogramsFrame( histogram_datas );
544 // hf.setVisible( true );
550 * @param all_binary_domains_combination_lost_fitch
551 * @param consider_directedness_and_adjacency_for_bin_combinations
552 * @param all_binary_domains_combination_gained if null ignored, otherwise this is to list all binary domain combinations
553 * which were gained under unweighted (Fitch) parsimony.
555 public static void executeParsimonyAnalysis( final long random_number_seed_for_fitch_parsimony,
556 final boolean radomize_fitch_parsimony,
557 final String outfile_name,
558 final DomainParsimonyCalculator domain_parsimony,
559 final Phylogeny phylogeny,
560 final Map<DomainId, List<GoId>> domain_id_to_go_ids_map,
561 final Map<GoId, GoTerm> go_id_to_term_map,
562 final GoNameSpace go_namespace_limit,
563 final String parameters_str,
564 final Map<DomainId, Set<String>>[] domain_id_to_secondary_features_maps,
565 final SortedSet<DomainId> positive_filter,
566 final boolean output_binary_domain_combinations_for_graphs,
567 final List<BinaryDomainCombination> all_binary_domains_combination_gained_fitch,
568 final List<BinaryDomainCombination> all_binary_domains_combination_lost_fitch,
569 final BinaryDomainCombination.DomainCombinationType dc_type ) {
570 final String sep = ForesterUtil.LINE_SEPARATOR + "###################" + ForesterUtil.LINE_SEPARATOR;
571 final String date_time = ForesterUtil.getCurrentDateTime();
572 final SortedSet<String> all_pfams_encountered = new TreeSet<String>();
573 final SortedSet<String> all_pfams_gained_as_domains = new TreeSet<String>();
574 final SortedSet<String> all_pfams_lost_as_domains = new TreeSet<String>();
575 final SortedSet<String> all_pfams_gained_as_dom_combinations = new TreeSet<String>();
576 final SortedSet<String> all_pfams_lost_as_dom_combinations = new TreeSet<String>();
577 writeToNexus( outfile_name, domain_parsimony, phylogeny );
580 Phylogeny local_phylogeny_l = phylogeny.copy();
581 if ( ( positive_filter != null ) && ( positive_filter.size() > 0 ) ) {
582 domain_parsimony.executeDolloParsimonyOnDomainPresence( positive_filter );
585 domain_parsimony.executeDolloParsimonyOnDomainPresence();
587 SurfacingUtil.writeMatrixToFile( domain_parsimony.getGainLossMatrix(), outfile_name
588 + surfacing.PARSIMONY_OUTPUT_GL_SUFFIX_DOLLO_DOMAINS, Format.FORESTER );
589 SurfacingUtil.writeMatrixToFile( domain_parsimony.getGainLossCountsMatrix(), outfile_name
590 + surfacing.PARSIMONY_OUTPUT_GL_COUNTS_SUFFIX_DOLLO_DOMAINS, Format.FORESTER );
591 SurfacingUtil.writeBinaryStatesMatrixAsListToFile( domain_parsimony.getGainLossMatrix(),
592 CharacterStateMatrix.GainLossStates.GAIN,
593 outfile_name + surfacing.PARSIMONY_OUTPUT_DOLLO_GAINS_D,
595 ForesterUtil.LINE_SEPARATOR,
597 SurfacingUtil.writeBinaryStatesMatrixAsListToFile( domain_parsimony.getGainLossMatrix(),
598 CharacterStateMatrix.GainLossStates.LOSS,
599 outfile_name + surfacing.PARSIMONY_OUTPUT_DOLLO_LOSSES_D,
601 ForesterUtil.LINE_SEPARATOR,
603 SurfacingUtil.writeBinaryStatesMatrixAsListToFile( domain_parsimony.getGainLossMatrix(), null, outfile_name
604 + surfacing.PARSIMONY_OUTPUT_DOLLO_PRESENT_D, sep, ForesterUtil.LINE_SEPARATOR, null );
606 writeBinaryStatesMatrixToList( domain_id_to_go_ids_map,
610 domain_parsimony.getGainLossMatrix(),
611 CharacterStateMatrix.GainLossStates.GAIN,
612 outfile_name + surfacing.PARSIMONY_OUTPUT_DOLLO_GAINS_HTML_D,
614 ForesterUtil.LINE_SEPARATOR,
615 "Dollo Parsimony | Gains | Domains",
617 domain_id_to_secondary_features_maps,
618 all_pfams_encountered,
619 all_pfams_gained_as_domains,
621 writeBinaryStatesMatrixToList( domain_id_to_go_ids_map,
625 domain_parsimony.getGainLossMatrix(),
626 CharacterStateMatrix.GainLossStates.LOSS,
627 outfile_name + surfacing.PARSIMONY_OUTPUT_DOLLO_LOSSES_HTML_D,
629 ForesterUtil.LINE_SEPARATOR,
630 "Dollo Parsimony | Losses | Domains",
632 domain_id_to_secondary_features_maps,
633 all_pfams_encountered,
634 all_pfams_lost_as_domains,
636 writeBinaryStatesMatrixToList( domain_id_to_go_ids_map,
640 domain_parsimony.getGainLossMatrix(),
642 outfile_name + surfacing.PARSIMONY_OUTPUT_DOLLO_PRESENT_HTML_D,
644 ForesterUtil.LINE_SEPARATOR,
645 "Dollo Parsimony | Present | Domains",
647 domain_id_to_secondary_features_maps,
648 all_pfams_encountered,
650 "_dollo_present_d" );
651 preparePhylogeny( local_phylogeny_l,
654 "Dollo parsimony on domain presence/absence",
655 "dollo_on_domains_" + outfile_name,
657 SurfacingUtil.writePhylogenyToFile( local_phylogeny_l, outfile_name
658 + surfacing.DOMAINS_PARSIMONY_TREE_OUTPUT_SUFFIX_DOLLO );
660 writeAllDomainsChangedOnAllSubtrees( local_phylogeny_l, true, outfile_name, "_dollo_all_gains_d" );
661 writeAllDomainsChangedOnAllSubtrees( local_phylogeny_l, false, outfile_name, "_dollo_all_losses_d" );
663 catch ( final IOException e ) {
665 ForesterUtil.fatalError( surfacing.PRG_NAME, e.getLocalizedMessage() );
667 if ( domain_parsimony.calculateNumberOfBinaryDomainCombination() > 0 ) {
668 // FITCH DOMAIN COMBINATIONS
669 // -------------------------
670 local_phylogeny_l = phylogeny.copy();
671 String randomization = "no";
672 if ( radomize_fitch_parsimony ) {
673 domain_parsimony.executeFitchParsimonyOnBinaryDomainCombintion( random_number_seed_for_fitch_parsimony );
674 randomization = "yes, seed = " + random_number_seed_for_fitch_parsimony;
677 domain_parsimony.executeFitchParsimonyOnBinaryDomainCombintion( USE_LAST );
679 SurfacingUtil.writeMatrixToFile( domain_parsimony.getGainLossMatrix(), outfile_name
680 + surfacing.PARSIMONY_OUTPUT_GL_SUFFIX_FITCH_BINARY_COMBINATIONS, Format.FORESTER );
681 SurfacingUtil.writeMatrixToFile( domain_parsimony.getGainLossCountsMatrix(), outfile_name
682 + surfacing.PARSIMONY_OUTPUT_GL_COUNTS_SUFFIX_FITCH_BINARY_COMBINATIONS, Format.FORESTER );
684 .writeBinaryStatesMatrixAsListToFile( domain_parsimony.getGainLossMatrix(),
685 CharacterStateMatrix.GainLossStates.GAIN,
686 outfile_name + surfacing.PARSIMONY_OUTPUT_FITCH_GAINS_BC,
688 ForesterUtil.LINE_SEPARATOR,
690 SurfacingUtil.writeBinaryStatesMatrixAsListToFile( domain_parsimony.getGainLossMatrix(),
691 CharacterStateMatrix.GainLossStates.LOSS,
693 + surfacing.PARSIMONY_OUTPUT_FITCH_LOSSES_BC,
695 ForesterUtil.LINE_SEPARATOR,
697 SurfacingUtil.writeBinaryStatesMatrixAsListToFile( domain_parsimony.getGainLossMatrix(), null, outfile_name
698 + surfacing.PARSIMONY_OUTPUT_FITCH_PRESENT_BC, sep, ForesterUtil.LINE_SEPARATOR, null );
699 if ( all_binary_domains_combination_gained_fitch != null ) {
700 collectChangedDomainCombinationsFromBinaryStatesMatrixAsListToFile( domain_parsimony.getGainLossMatrix(),
702 all_binary_domains_combination_gained_fitch,
705 if ( all_binary_domains_combination_lost_fitch != null ) {
706 collectChangedDomainCombinationsFromBinaryStatesMatrixAsListToFile( domain_parsimony.getGainLossMatrix(),
708 all_binary_domains_combination_lost_fitch,
711 if ( output_binary_domain_combinations_for_graphs ) {
713 .writeBinaryStatesMatrixAsListToFileForBinaryCombinationsForGraphAnalysis( domain_parsimony
714 .getGainLossMatrix(),
717 + surfacing.PARSIMONY_OUTPUT_FITCH_PRESENT_BC_OUTPUTFILE_SUFFIX_FOR_GRAPH_ANALYSIS,
719 ForesterUtil.LINE_SEPARATOR,
720 BinaryDomainCombination.OutputFormat.DOT );
723 writeBinaryStatesMatrixToList( domain_id_to_go_ids_map,
727 domain_parsimony.getGainLossMatrix(),
728 CharacterStateMatrix.GainLossStates.GAIN,
729 outfile_name + surfacing.PARSIMONY_OUTPUT_FITCH_GAINS_HTML_BC,
731 ForesterUtil.LINE_SEPARATOR,
732 "Fitch Parsimony | Gains | Domain Combinations",
735 all_pfams_encountered,
736 all_pfams_gained_as_dom_combinations,
738 writeBinaryStatesMatrixToList( domain_id_to_go_ids_map,
742 domain_parsimony.getGainLossMatrix(),
743 CharacterStateMatrix.GainLossStates.LOSS,
744 outfile_name + surfacing.PARSIMONY_OUTPUT_FITCH_LOSSES_HTML_BC,
746 ForesterUtil.LINE_SEPARATOR,
747 "Fitch Parsimony | Losses | Domain Combinations",
750 all_pfams_encountered,
751 all_pfams_lost_as_dom_combinations,
752 "_fitch_losses_dc" );
753 writeBinaryStatesMatrixToList( domain_id_to_go_ids_map,
757 domain_parsimony.getGainLossMatrix(),
759 outfile_name + surfacing.PARSIMONY_OUTPUT_FITCH_PRESENT_HTML_BC,
761 ForesterUtil.LINE_SEPARATOR,
762 "Fitch Parsimony | Present | Domain Combinations",
765 all_pfams_encountered,
767 "_fitch_present_dc" );
768 writeAllEncounteredPfamsToFile( domain_id_to_go_ids_map,
771 all_pfams_encountered );
772 writePfamsToFile( outfile_name + surfacing.ALL_PFAMS_GAINED_AS_DOMAINS_SUFFIX, all_pfams_gained_as_domains );
773 writePfamsToFile( outfile_name + surfacing.ALL_PFAMS_LOST_AS_DOMAINS_SUFFIX, all_pfams_lost_as_domains );
774 writePfamsToFile( outfile_name + surfacing.ALL_PFAMS_GAINED_AS_DC_SUFFIX,
775 all_pfams_gained_as_dom_combinations );
776 writePfamsToFile( outfile_name + surfacing.ALL_PFAMS_LOST_AS_DC_SUFFIX, all_pfams_lost_as_dom_combinations );
777 preparePhylogeny( local_phylogeny_l,
780 "Fitch parsimony on binary domain combination presence/absence randomization: "
782 "fitch_on_binary_domain_combinations_" + outfile_name,
784 SurfacingUtil.writePhylogenyToFile( local_phylogeny_l, outfile_name
785 + surfacing.BINARY_DOMAIN_COMBINATIONS_PARSIMONY_TREE_OUTPUT_SUFFIX_FITCH );
786 calculateIndependentDomainCombinationGains( local_phylogeny_l, outfile_name
787 + surfacing.INDEPENDENT_DC_GAINS_FITCH_PARS_COUNTS_OUTPUT_SUFFIX, outfile_name
788 + surfacing.INDEPENDENT_DC_GAINS_FITCH_PARS_DC_OUTPUT_SUFFIX, outfile_name
789 + surfacing.INDEPENDENT_DC_GAINS_FITCH_PARS_DC_FOR_GO_MAPPING_OUTPUT_SUFFIX, outfile_name
790 + surfacing.INDEPENDENT_DC_GAINS_FITCH_PARS_DC_FOR_GO_MAPPING_OUTPUT_UNIQUE_SUFFIX, outfile_name
791 + "_indep_dc_gains_fitch_lca_ranks.txt", outfile_name + "_indep_dc_gains_fitch_lca_taxonomies.txt" );
795 public static void executeParsimonyAnalysisForSecondaryFeatures( final String outfile_name,
796 final DomainParsimonyCalculator secondary_features_parsimony,
797 final Phylogeny phylogeny,
798 final String parameters_str,
799 final Map<Species, MappingResults> mapping_results_map ) {
800 final String sep = ForesterUtil.LINE_SEPARATOR + "###################" + ForesterUtil.LINE_SEPARATOR;
801 final String date_time = ForesterUtil.getCurrentDateTime();
802 System.out.println();
803 writeToNexus( outfile_name + surfacing.NEXUS_SECONDARY_FEATURES,
804 secondary_features_parsimony.createMatrixOfSecondaryFeaturePresenceOrAbsence( null ),
806 Phylogeny local_phylogeny_copy = phylogeny.copy();
807 secondary_features_parsimony.executeDolloParsimonyOnSecondaryFeatures( mapping_results_map );
808 SurfacingUtil.writeMatrixToFile( secondary_features_parsimony.getGainLossMatrix(), outfile_name
809 + surfacing.PARSIMONY_OUTPUT_GL_SUFFIX_DOLLO_SECONDARY_FEATURES, Format.FORESTER );
810 SurfacingUtil.writeMatrixToFile( secondary_features_parsimony.getGainLossCountsMatrix(), outfile_name
811 + surfacing.PARSIMONY_OUTPUT_GL_COUNTS_SUFFIX_DOLLO_SECONDARY_FEATURES, Format.FORESTER );
813 .writeBinaryStatesMatrixAsListToFile( secondary_features_parsimony.getGainLossMatrix(),
814 CharacterStateMatrix.GainLossStates.GAIN,
816 + surfacing.PARSIMONY_OUTPUT_DOLLO_GAINS_SECONDARY_FEATURES,
818 ForesterUtil.LINE_SEPARATOR,
821 .writeBinaryStatesMatrixAsListToFile( secondary_features_parsimony.getGainLossMatrix(),
822 CharacterStateMatrix.GainLossStates.LOSS,
824 + surfacing.PARSIMONY_OUTPUT_DOLLO_LOSSES_SECONDARY_FEATURES,
826 ForesterUtil.LINE_SEPARATOR,
829 .writeBinaryStatesMatrixAsListToFile( secondary_features_parsimony.getGainLossMatrix(),
832 + surfacing.PARSIMONY_OUTPUT_DOLLO_PRESENT_SECONDARY_FEATURES,
834 ForesterUtil.LINE_SEPARATOR,
836 preparePhylogeny( local_phylogeny_copy,
837 secondary_features_parsimony,
839 "Dollo parsimony on secondary feature presence/absence",
840 "dollo_on_secondary_features_" + outfile_name,
842 SurfacingUtil.writePhylogenyToFile( local_phylogeny_copy, outfile_name
843 + surfacing.SECONDARY_FEATURES_PARSIMONY_TREE_OUTPUT_SUFFIX_DOLLO );
846 // FITCH DOMAIN COMBINATIONS
847 // -------------------------
848 local_phylogeny_copy = phylogeny.copy();
849 String randomization = "no";
851 secondary_features_parsimony.executeFitchParsimonyOnBinaryDomainCombintionOnSecondaryFeatures( USE_LAST );
856 preparePhylogeny( local_phylogeny_copy,
857 secondary_features_parsimony,
859 "Fitch parsimony on secondary binary domain combination presence/absence randomization: "
861 "fitch_on_binary_domain_combinations_" + outfile_name,
863 SurfacingUtil.writePhylogenyToFile( local_phylogeny_copy, outfile_name
864 + surfacing.BINARY_DOMAIN_COMBINATIONS_PARSIMONY_TREE_OUTPUT_SUFFIX_FITCH_MAPPED );
865 calculateIndependentDomainCombinationGains( local_phylogeny_copy, outfile_name
866 + surfacing.INDEPENDENT_DC_GAINS_FITCH_PARS_COUNTS_MAPPED_OUTPUT_SUFFIX, outfile_name
867 + surfacing.INDEPENDENT_DC_GAINS_FITCH_PARS_DC_MAPPED_OUTPUT_SUFFIX, outfile_name
868 + surfacing.INDEPENDENT_DC_GAINS_FITCH_PARS_DC_FOR_GO_MAPPING_MAPPED_OUTPUT_SUFFIX, outfile_name
869 + surfacing.INDEPENDENT_DC_GAINS_FITCH_PARS_DC_FOR_GO_MAPPING_MAPPED_OUTPUT_UNIQUE_SUFFIX, outfile_name
870 + "_MAPPED_indep_dc_gains_fitch_lca_ranks.txt", outfile_name + "_MAPPED_indep_dc_gains_fitch_lca_taxonomies.txt" );
875 public static void extractProteinNames( final List<Protein> proteins,
876 final List<DomainId> query_domain_ids_nc_order,
878 final String separator,
879 final String limit_to_species ) throws IOException {
880 for( final Protein protein : proteins ) {
881 if ( ForesterUtil.isEmpty( limit_to_species )
882 || protein.getSpecies().getSpeciesId().equalsIgnoreCase( limit_to_species ) ) {
883 if ( protein.contains( query_domain_ids_nc_order, true ) ) {
884 out.write( protein.getSpecies().getSpeciesId() );
885 out.write( separator );
886 out.write( protein.getProteinId().getId() );
887 out.write( separator );
889 final Set<DomainId> visited_domain_ids = new HashSet<DomainId>();
890 boolean first = true;
891 for( final Domain domain : protein.getProteinDomains() ) {
892 if ( !visited_domain_ids.contains( domain.getDomainId() ) ) {
893 visited_domain_ids.add( domain.getDomainId() );
900 out.write( domain.getDomainId().getId() );
902 out.write( "" + domain.getTotalCount() );
907 out.write( separator );
908 if ( !( ForesterUtil.isEmpty( protein.getDescription() ) || protein.getDescription()
909 .equals( SurfacingConstants.NONE ) ) ) {
910 out.write( protein.getDescription() );
912 out.write( separator );
913 if ( !( ForesterUtil.isEmpty( protein.getAccession() ) || protein.getAccession()
914 .equals( SurfacingConstants.NONE ) ) ) {
915 out.write( protein.getAccession() );
917 out.write( SurfacingConstants.NL );
924 public static void extractProteinNames( final SortedMap<Species, List<Protein>> protein_lists_per_species,
925 final DomainId domain_id,
927 final String separator,
928 final String limit_to_species ) throws IOException {
929 for( final Species species : protein_lists_per_species.keySet() ) {
930 for( final Protein protein : protein_lists_per_species.get( species ) ) {
931 if ( ForesterUtil.isEmpty( limit_to_species )
932 || protein.getSpecies().getSpeciesId().equalsIgnoreCase( limit_to_species ) ) {
933 final List<Domain> domains = protein.getProteinDomains( domain_id );
934 if ( domains.size() > 0 ) {
935 final DescriptiveStatistics stats = new BasicDescriptiveStatistics();
936 for( final Domain domain : domains ) {
937 stats.addValue( domain.getPerSequenceEvalue() );
939 out.write( protein.getSpecies().getSpeciesId() );
940 out.write( separator );
941 out.write( protein.getProteinId().getId() );
942 out.write( separator );
943 out.write( "[" + FORMATTER.format( stats.median() ) + "]" );
944 out.write( separator );
945 if ( !( ForesterUtil.isEmpty( protein.getDescription() ) || protein.getDescription()
946 .equals( SurfacingConstants.NONE ) ) ) {
947 out.write( protein.getDescription() );
949 out.write( separator );
950 if ( !( ForesterUtil.isEmpty( protein.getAccession() ) || protein.getAccession()
951 .equals( SurfacingConstants.NONE ) ) ) {
952 out.write( protein.getAccession() );
954 out.write( SurfacingConstants.NL );
962 public static SortedSet<DomainId> getAllDomainIds( final List<GenomeWideCombinableDomains> gwcd_list ) {
963 final SortedSet<DomainId> all_domains_ids = new TreeSet<DomainId>();
964 for( final GenomeWideCombinableDomains gwcd : gwcd_list ) {
965 final Set<DomainId> all_domains = gwcd.getAllDomainIds();
966 // for( final Domain domain : all_domains ) {
967 all_domains_ids.addAll( all_domains );
970 return all_domains_ids;
973 public static SortedMap<String, Integer> getDomainCounts( final List<Protein> protein_domain_collections ) {
974 final SortedMap<String, Integer> map = new TreeMap<String, Integer>();
975 for( final Protein protein_domain_collection : protein_domain_collections ) {
976 for( final Object name : protein_domain_collection.getProteinDomains() ) {
977 final BasicDomain protein_domain = ( BasicDomain ) name;
978 final String id = protein_domain.getDomainId().getId();
979 if ( map.containsKey( id ) ) {
980 map.put( id, map.get( id ) + 1 );
990 public static int getNumberOfNodesLackingName( final Phylogeny p, final StringBuilder names ) {
991 final PhylogenyNodeIterator it = p.iteratorPostorder();
993 while ( it.hasNext() ) {
994 final PhylogenyNode n = it.next();
995 if ( ForesterUtil.isEmpty( n.getName() )
996 && ( !n.getNodeData().isHasTaxonomy() || ForesterUtil.isEmpty( n.getNodeData().getTaxonomy()
997 .getScientificName() ) )
998 && ( !n.getNodeData().isHasTaxonomy() || ForesterUtil.isEmpty( n.getNodeData().getTaxonomy()
999 .getCommonName() ) ) ) {
1000 if ( n.getParent() != null ) {
1001 names.append( " " );
1002 names.append( n.getParent().getName() );
1004 final List l = n.getAllExternalDescendants();
1005 for( final Object object : l ) {
1006 System.out.println( l.toString() );
1015 * Returns true is Domain domain falls in an uninterrupted stretch of
1016 * covered positions.
1019 * @param covered_positions
1022 public static boolean isEngulfed( final Domain domain, final List<Boolean> covered_positions ) {
1023 for( int i = domain.getFrom(); i <= domain.getTo(); ++i ) {
1024 if ( ( i >= covered_positions.size() ) || ( covered_positions.get( i ) != true ) ) {
1031 public static void preparePhylogeny( final Phylogeny p,
1032 final DomainParsimonyCalculator domain_parsimony,
1033 final String date_time,
1034 final String method,
1036 final String parameters_str ) {
1037 domain_parsimony.decoratePhylogenyWithDomains( p );
1038 final StringBuilder desc = new StringBuilder();
1039 desc.append( "[Method: " + method + "] [Date: " + date_time + "] " );
1040 desc.append( "[Cost: " + domain_parsimony.getCost() + "] " );
1041 desc.append( "[Gains: " + domain_parsimony.getTotalGains() + "] " );
1042 desc.append( "[Losses: " + domain_parsimony.getTotalLosses() + "] " );
1043 desc.append( "[Unchanged: " + domain_parsimony.getTotalUnchanged() + "] " );
1044 desc.append( "[Parameters: " + parameters_str + "]" );
1046 p.setDescription( desc.toString() );
1047 p.setConfidence( new Confidence( domain_parsimony.getCost(), "parsimony" ) );
1048 p.setRerootable( false );
1049 p.setRooted( true );
1053 * species | protein id | n-terminal domain | c-terminal domain | n-terminal domain per domain E-value | c-terminal domain per domain E-value
1057 static public StringBuffer proteinToDomainCombinations( final Protein protein,
1058 final String protein_id,
1059 final String separator ) {
1060 final StringBuffer sb = new StringBuffer();
1061 if ( protein.getSpecies() == null ) {
1062 throw new IllegalArgumentException( "species must not be null" );
1064 if ( ForesterUtil.isEmpty( protein.getSpecies().getSpeciesId() ) ) {
1065 throw new IllegalArgumentException( "species id must not be empty" );
1067 final List<Domain> domains = protein.getProteinDomains();
1068 if ( domains.size() > 1 ) {
1069 final Map<String, Integer> counts = new HashMap<String, Integer>();
1070 for( final Domain domain : domains ) {
1071 final String id = domain.getDomainId().getId();
1072 if ( counts.containsKey( id ) ) {
1073 counts.put( id, counts.get( id ) + 1 );
1076 counts.put( id, 1 );
1079 final Set<String> dcs = new HashSet<String>();
1080 for( int i = 1; i < domains.size(); ++i ) {
1081 for( int j = 0; j < i; ++j ) {
1082 Domain domain_n = domains.get( i );
1083 Domain domain_c = domains.get( j );
1084 if ( domain_n.getFrom() > domain_c.getFrom() ) {
1085 domain_n = domains.get( j );
1086 domain_c = domains.get( i );
1088 final String dc = domain_n.getDomainId().getId() + domain_c.getDomainId().getId();
1089 if ( !dcs.contains( dc ) ) {
1091 sb.append( protein.getSpecies() );
1092 sb.append( separator );
1093 sb.append( protein_id );
1094 sb.append( separator );
1095 sb.append( domain_n.getDomainId().getId() );
1096 sb.append( separator );
1097 sb.append( domain_c.getDomainId().getId() );
1098 sb.append( separator );
1099 sb.append( domain_n.getPerDomainEvalue() );
1100 sb.append( separator );
1101 sb.append( domain_c.getPerDomainEvalue() );
1102 sb.append( separator );
1103 sb.append( counts.get( domain_n.getDomainId().getId() ) );
1104 sb.append( separator );
1105 sb.append( counts.get( domain_c.getDomainId().getId() ) );
1106 sb.append( ForesterUtil.LINE_SEPARATOR );
1111 else if ( domains.size() == 1 ) {
1112 sb.append( protein.getSpecies() );
1113 sb.append( separator );
1114 sb.append( protein_id );
1115 sb.append( separator );
1116 sb.append( domains.get( 0 ).getDomainId().getId() );
1117 sb.append( separator );
1118 sb.append( separator );
1119 sb.append( domains.get( 0 ).getPerDomainEvalue() );
1120 sb.append( separator );
1121 sb.append( separator );
1123 sb.append( separator );
1124 sb.append( ForesterUtil.LINE_SEPARATOR );
1127 sb.append( protein.getSpecies() );
1128 sb.append( separator );
1129 sb.append( protein_id );
1130 sb.append( separator );
1131 sb.append( separator );
1132 sb.append( separator );
1133 sb.append( separator );
1134 sb.append( separator );
1135 sb.append( separator );
1136 sb.append( ForesterUtil.LINE_SEPARATOR );
1143 * Example regarding engulfment: ------------0.1 ----------0.2 --0.3 =>
1144 * domain with 0.3 is ignored
1146 * -----------0.1 ----------0.2 --0.3 => domain with 0.3 is ignored
1149 * ------------0.1 ----------0.3 --0.2 => domains with 0.3 and 0.2 are _not_
1152 * @param max_allowed_overlap
1153 * maximal allowed overlap (inclusive) to be still considered not
1154 * overlapping (zero or negative value to allow any overlap)
1155 * @param remove_engulfed_domains
1156 * to remove domains which are completely engulfed by coverage of
1157 * domains with better support
1161 public static Protein removeOverlappingDomains( final int max_allowed_overlap,
1162 final boolean remove_engulfed_domains,
1163 final Protein protein ) {
1164 final Protein pruned_protein = new BasicProtein( protein.getProteinId().getId(), protein.getSpecies()
1166 final List<Domain> sorted = SurfacingUtil.sortDomainsWithAscendingConfidenceValues( protein );
1167 final List<Boolean> covered_positions = new ArrayList<Boolean>();
1168 for( final Domain domain : sorted ) {
1169 if ( ( ( max_allowed_overlap < 0 ) || ( SurfacingUtil.calculateOverlap( domain, covered_positions ) <= max_allowed_overlap ) )
1170 && ( !remove_engulfed_domains || !isEngulfed( domain, covered_positions ) ) ) {
1171 final int covered_positions_size = covered_positions.size();
1172 for( int i = covered_positions_size; i < domain.getFrom(); ++i ) {
1173 covered_positions.add( false );
1175 final int new_covered_positions_size = covered_positions.size();
1176 for( int i = domain.getFrom(); i <= domain.getTo(); ++i ) {
1177 if ( i < new_covered_positions_size ) {
1178 covered_positions.set( i, true );
1181 covered_positions.add( true );
1184 pruned_protein.addProteinDomain( domain );
1187 return pruned_protein;
1190 public static List<Domain> sortDomainsWithAscendingConfidenceValues( final Protein protein ) {
1191 final List<Domain> domains = new ArrayList<Domain>();
1192 for( final Domain d : protein.getProteinDomains() ) {
1195 Collections.sort( domains, SurfacingUtil.ASCENDING_CONFIDENCE_VALUE_ORDER );
1199 private static List<String> splitDomainCombination( final String dc ) {
1200 final String[] s = dc.split( "=" );
1201 if ( s.length != 2 ) {
1202 ForesterUtil.printErrorMessage( surfacing.PRG_NAME, "Stringyfied domain combination has illegal format: "
1206 final List<String> l = new ArrayList<String>( 2 );
1212 public static void writeAllDomainsChangedOnAllSubtrees( final Phylogeny p,
1213 final boolean get_gains,
1214 final String outdir,
1215 final String suffix_for_filename ) throws IOException {
1216 CharacterStateMatrix.GainLossStates state = CharacterStateMatrix.GainLossStates.GAIN;
1218 state = CharacterStateMatrix.GainLossStates.LOSS;
1220 final File base_dir = createBaseDirForPerNodeDomainFiles( surfacing.BASE_DIRECTORY_PER_SUBTREE_DOMAIN_GAIN_LOSS_FILES,
1224 for( final PhylogenyNodeIterator it = p.iteratorPostorder(); it.hasNext(); ) {
1225 final PhylogenyNode node = it.next();
1226 if ( !node.isExternal() ) {
1227 final SortedSet<String> domains = collectAllDomainsChangedOnSubtree( node, get_gains );
1228 if ( domains.size() > 0 ) {
1229 final Writer writer = ForesterUtil.createBufferedWriter( base_dir + ForesterUtil.FILE_SEPARATOR
1230 + node.getName() + suffix_for_filename );
1231 for( final String domain : domains ) {
1232 writer.write( domain );
1233 writer.write( ForesterUtil.LINE_SEPARATOR );
1241 private static void writeAllEncounteredPfamsToFile( final Map<DomainId, List<GoId>> domain_id_to_go_ids_map,
1242 final Map<GoId, GoTerm> go_id_to_term_map,
1243 final String outfile_name,
1244 final SortedSet<String> all_pfams_encountered ) {
1245 final File all_pfams_encountered_file = new File( outfile_name + surfacing.ALL_PFAMS_ENCOUNTERED_SUFFIX );
1246 final File all_pfams_encountered_with_go_annotation_file = new File( outfile_name
1247 + surfacing.ALL_PFAMS_ENCOUNTERED_WITH_GO_ANNOTATION_SUFFIX );
1248 final File encountered_pfams_summary_file = new File( outfile_name + surfacing.ENCOUNTERED_PFAMS_SUMMARY_SUFFIX );
1249 int biological_process_counter = 0;
1250 int cellular_component_counter = 0;
1251 int molecular_function_counter = 0;
1252 int pfams_with_mappings_counter = 0;
1253 int pfams_without_mappings_counter = 0;
1254 int pfams_without_mappings_to_bp_or_mf_counter = 0;
1255 int pfams_with_mappings_to_bp_or_mf_counter = 0;
1257 final Writer all_pfams_encountered_writer = new BufferedWriter( new FileWriter( all_pfams_encountered_file ) );
1258 final Writer all_pfams_encountered_with_go_annotation_writer = new BufferedWriter( new FileWriter( all_pfams_encountered_with_go_annotation_file ) );
1259 final Writer summary_writer = new BufferedWriter( new FileWriter( encountered_pfams_summary_file ) );
1260 summary_writer.write( "# Pfam to GO mapping summary" );
1261 summary_writer.write( ForesterUtil.LINE_SEPARATOR );
1262 summary_writer.write( "# Actual summary is at the end of this file." );
1263 summary_writer.write( ForesterUtil.LINE_SEPARATOR );
1264 summary_writer.write( "# Encountered Pfams without a GO mapping:" );
1265 summary_writer.write( ForesterUtil.LINE_SEPARATOR );
1266 for( final String pfam : all_pfams_encountered ) {
1267 all_pfams_encountered_writer.write( pfam );
1268 all_pfams_encountered_writer.write( ForesterUtil.LINE_SEPARATOR );
1269 final DomainId domain_id = new DomainId( pfam );
1270 if ( domain_id_to_go_ids_map.containsKey( domain_id ) ) {
1271 ++pfams_with_mappings_counter;
1272 all_pfams_encountered_with_go_annotation_writer.write( pfam );
1273 all_pfams_encountered_with_go_annotation_writer.write( ForesterUtil.LINE_SEPARATOR );
1274 final List<GoId> go_ids = domain_id_to_go_ids_map.get( domain_id );
1275 boolean maps_to_bp = false;
1276 boolean maps_to_cc = false;
1277 boolean maps_to_mf = false;
1278 for( final GoId go_id : go_ids ) {
1279 final GoTerm go_term = go_id_to_term_map.get( go_id );
1280 if ( go_term.getGoNameSpace().isBiologicalProcess() ) {
1283 else if ( go_term.getGoNameSpace().isCellularComponent() ) {
1286 else if ( go_term.getGoNameSpace().isMolecularFunction() ) {
1291 ++biological_process_counter;
1294 ++cellular_component_counter;
1297 ++molecular_function_counter;
1299 if ( maps_to_bp || maps_to_mf ) {
1300 ++pfams_with_mappings_to_bp_or_mf_counter;
1303 ++pfams_without_mappings_to_bp_or_mf_counter;
1307 ++pfams_without_mappings_to_bp_or_mf_counter;
1308 ++pfams_without_mappings_counter;
1309 summary_writer.write( pfam );
1310 summary_writer.write( ForesterUtil.LINE_SEPARATOR );
1313 all_pfams_encountered_writer.close();
1314 all_pfams_encountered_with_go_annotation_writer.close();
1315 ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote all [" + all_pfams_encountered.size()
1316 + "] encountered Pfams to: \"" + all_pfams_encountered_file + "\"" );
1317 ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote all [" + pfams_with_mappings_counter
1318 + "] encountered Pfams with GO mappings to: \"" + all_pfams_encountered_with_go_annotation_file
1320 ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote summary (including all ["
1321 + pfams_without_mappings_counter + "] encountered Pfams without GO mappings) to: \""
1322 + encountered_pfams_summary_file + "\"" );
1323 ForesterUtil.programMessage( surfacing.PRG_NAME, "Sum of Pfams encountered : "
1324 + all_pfams_encountered.size() );
1325 ForesterUtil.programMessage( surfacing.PRG_NAME, "Pfams without a mapping : "
1326 + pfams_without_mappings_counter + " ["
1327 + ( 100 * pfams_without_mappings_counter / all_pfams_encountered.size() ) + "%]" );
1328 ForesterUtil.programMessage( surfacing.PRG_NAME, "Pfams without mapping to proc. or func. : "
1329 + pfams_without_mappings_to_bp_or_mf_counter + " ["
1330 + ( 100 * pfams_without_mappings_to_bp_or_mf_counter / all_pfams_encountered.size() ) + "%]" );
1331 ForesterUtil.programMessage( surfacing.PRG_NAME,
1332 "Pfams with a mapping : " + pfams_with_mappings_counter
1334 + ( 100 * pfams_with_mappings_counter / all_pfams_encountered.size() )
1336 ForesterUtil.programMessage( surfacing.PRG_NAME, "Pfams with a mapping to proc. or func. : "
1337 + pfams_with_mappings_to_bp_or_mf_counter + " ["
1338 + ( 100 * pfams_with_mappings_to_bp_or_mf_counter / all_pfams_encountered.size() ) + "%]" );
1339 ForesterUtil.programMessage( surfacing.PRG_NAME,
1340 "Pfams with mapping to biological process: " + biological_process_counter
1342 + ( 100 * biological_process_counter / all_pfams_encountered.size() )
1344 ForesterUtil.programMessage( surfacing.PRG_NAME,
1345 "Pfams with mapping to molecular function: " + molecular_function_counter
1347 + ( 100 * molecular_function_counter / all_pfams_encountered.size() )
1349 ForesterUtil.programMessage( surfacing.PRG_NAME,
1350 "Pfams with mapping to cellular component: " + cellular_component_counter
1352 + ( 100 * cellular_component_counter / all_pfams_encountered.size() )
1354 summary_writer.write( ForesterUtil.LINE_SEPARATOR );
1355 summary_writer.write( "# Sum of Pfams encountered : " + all_pfams_encountered.size() );
1356 summary_writer.write( ForesterUtil.LINE_SEPARATOR );
1357 summary_writer.write( "# Pfams without a mapping : " + pfams_without_mappings_counter
1358 + " [" + ( 100 * pfams_without_mappings_counter / all_pfams_encountered.size() ) + "%]" );
1359 summary_writer.write( ForesterUtil.LINE_SEPARATOR );
1360 summary_writer.write( "# Pfams without mapping to proc. or func. : "
1361 + pfams_without_mappings_to_bp_or_mf_counter + " ["
1362 + ( 100 * pfams_without_mappings_to_bp_or_mf_counter / all_pfams_encountered.size() ) + "%]" );
1363 summary_writer.write( ForesterUtil.LINE_SEPARATOR );
1364 summary_writer.write( "# Pfams with a mapping : " + pfams_with_mappings_counter + " ["
1365 + ( 100 * pfams_with_mappings_counter / all_pfams_encountered.size() ) + "%]" );
1366 summary_writer.write( ForesterUtil.LINE_SEPARATOR );
1367 summary_writer.write( "# Pfams with a mapping to proc. or func. : "
1368 + pfams_with_mappings_to_bp_or_mf_counter + " ["
1369 + ( 100 * pfams_with_mappings_to_bp_or_mf_counter / all_pfams_encountered.size() ) + "%]" );
1370 summary_writer.write( ForesterUtil.LINE_SEPARATOR );
1371 summary_writer.write( "# Pfams with mapping to biological process: " + biological_process_counter + " ["
1372 + ( 100 * biological_process_counter / all_pfams_encountered.size() ) + "%]" );
1373 summary_writer.write( ForesterUtil.LINE_SEPARATOR );
1374 summary_writer.write( "# Pfams with mapping to molecular function: " + molecular_function_counter + " ["
1375 + ( 100 * molecular_function_counter / all_pfams_encountered.size() ) + "%]" );
1376 summary_writer.write( ForesterUtil.LINE_SEPARATOR );
1377 summary_writer.write( "# Pfams with mapping to cellular component: " + cellular_component_counter + " ["
1378 + ( 100 * cellular_component_counter / all_pfams_encountered.size() ) + "%]" );
1379 summary_writer.write( ForesterUtil.LINE_SEPARATOR );
1380 summary_writer.close();
1382 catch ( final IOException e ) {
1383 ForesterUtil.printWarningMessage( surfacing.PRG_NAME, "Failure to write: " + e );
1387 public static void writeBinaryDomainCombinationsFileForGraphAnalysis( final String[][] input_file_properties,
1388 final File output_dir,
1389 final GenomeWideCombinableDomains gwcd,
1391 final GenomeWideCombinableDomainsSortOrder dc_sort_order ) {
1392 File dc_outfile_dot = new File( input_file_properties[ i ][ 0 ]
1393 + surfacing.DOMAIN_COMBINITONS_OUTPUTFILE_SUFFIX_FOR_GRAPH_ANALYSIS );
1394 if ( output_dir != null ) {
1395 dc_outfile_dot = new File( output_dir + ForesterUtil.FILE_SEPARATOR + dc_outfile_dot );
1397 checkForOutputFileWriteability( dc_outfile_dot );
1398 final SortedSet<BinaryDomainCombination> binary_combinations = createSetOfAllBinaryDomainCombinationsPerGenome( gwcd );
1400 final BufferedWriter out_dot = new BufferedWriter( new FileWriter( dc_outfile_dot ) );
1401 for( final BinaryDomainCombination bdc : binary_combinations ) {
1402 out_dot.write( bdc.toGraphDescribingLanguage( BinaryDomainCombination.OutputFormat.DOT, null, null )
1404 out_dot.write( SurfacingConstants.NL );
1408 catch ( final IOException e ) {
1409 ForesterUtil.fatalError( surfacing.PRG_NAME, e.getMessage() );
1411 ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote binary domain combination for \""
1412 + input_file_properties[ i ][ 0 ] + "\" (" + input_file_properties[ i ][ 1 ] + ", "
1413 + input_file_properties[ i ][ 2 ] + ") to: \"" + dc_outfile_dot + "\"" );
1416 public static void writeBinaryStatesMatrixAsListToFile( final CharacterStateMatrix<CharacterStateMatrix.GainLossStates> matrix,
1417 final CharacterStateMatrix.GainLossStates state,
1418 final String filename,
1419 final String indentifier_characters_separator,
1420 final String character_separator,
1421 final Map<String, String> descriptions ) {
1422 final File outfile = new File( filename );
1423 checkForOutputFileWriteability( outfile );
1424 final SortedSet<String> sorted_ids = new TreeSet<String>();
1425 for( int i = 0; i < matrix.getNumberOfIdentifiers(); ++i ) {
1426 sorted_ids.add( matrix.getIdentifier( i ) );
1429 final BufferedWriter out = new BufferedWriter( new FileWriter( outfile ) );
1430 for( final String id : sorted_ids ) {
1431 out.write( indentifier_characters_separator );
1432 out.write( "#" + id );
1433 out.write( indentifier_characters_separator );
1434 for( int c = 0; c < matrix.getNumberOfCharacters(); ++c ) {
1436 // using null to indicate either UNCHANGED_PRESENT or GAIN.
1437 if ( ( matrix.getState( id, c ) == state )
1438 || ( ( state == null ) && ( ( matrix.getState( id, c ) == CharacterStateMatrix.GainLossStates.GAIN ) || ( matrix
1439 .getState( id, c ) == CharacterStateMatrix.GainLossStates.UNCHANGED_PRESENT ) ) ) ) {
1440 out.write( matrix.getCharacter( c ) );
1441 if ( ( descriptions != null ) && !descriptions.isEmpty()
1442 && descriptions.containsKey( matrix.getCharacter( c ) ) ) {
1444 out.write( descriptions.get( matrix.getCharacter( c ) ) );
1446 out.write( character_separator );
1453 catch ( final IOException e ) {
1454 ForesterUtil.fatalError( surfacing.PRG_NAME, e.getMessage() );
1456 ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote characters list: \"" + filename + "\"" );
1459 public static void writeBinaryStatesMatrixAsListToFileForBinaryCombinationsForGraphAnalysis( final CharacterStateMatrix<CharacterStateMatrix.GainLossStates> matrix,
1460 final CharacterStateMatrix.GainLossStates state,
1461 final String filename,
1462 final String indentifier_characters_separator,
1463 final String character_separator,
1464 final BinaryDomainCombination.OutputFormat bc_output_format ) {
1465 final File outfile = new File( filename );
1466 checkForOutputFileWriteability( outfile );
1467 final SortedSet<String> sorted_ids = new TreeSet<String>();
1468 for( int i = 0; i < matrix.getNumberOfIdentifiers(); ++i ) {
1469 sorted_ids.add( matrix.getIdentifier( i ) );
1472 final BufferedWriter out = new BufferedWriter( new FileWriter( outfile ) );
1473 for( final String id : sorted_ids ) {
1474 out.write( indentifier_characters_separator );
1475 out.write( "#" + id );
1476 out.write( indentifier_characters_separator );
1477 for( int c = 0; c < matrix.getNumberOfCharacters(); ++c ) {
1479 // using null to indicate either UNCHANGED_PRESENT or GAIN.
1480 if ( ( matrix.getState( id, c ) == state )
1481 || ( ( state == null ) && ( ( matrix.getState( id, c ) == CharacterStateMatrix.GainLossStates.GAIN ) || ( matrix
1482 .getState( id, c ) == CharacterStateMatrix.GainLossStates.UNCHANGED_PRESENT ) ) ) ) {
1483 BinaryDomainCombination bdc = null;
1485 bdc = BasicBinaryDomainCombination.createInstance( matrix.getCharacter( c ) );
1487 catch ( final Exception e ) {
1488 ForesterUtil.fatalError( surfacing.PRG_NAME, e.getLocalizedMessage() );
1490 out.write( bdc.toGraphDescribingLanguage( bc_output_format, null, null ).toString() );
1491 out.write( character_separator );
1498 catch ( final IOException e ) {
1499 ForesterUtil.fatalError( surfacing.PRG_NAME, e.getMessage() );
1501 ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote characters list: \"" + filename + "\"" );
1504 public static void writeBinaryStatesMatrixToList( final Map<DomainId, List<GoId>> domain_id_to_go_ids_map,
1505 final Map<GoId, GoTerm> go_id_to_term_map,
1506 final GoNameSpace go_namespace_limit,
1507 final boolean domain_combinations,
1508 final CharacterStateMatrix<CharacterStateMatrix.GainLossStates> matrix,
1509 final CharacterStateMatrix.GainLossStates state,
1510 final String filename,
1511 final String indentifier_characters_separator,
1512 final String character_separator,
1513 final String title_for_html,
1514 final String prefix_for_html,
1515 final Map<DomainId, Set<String>>[] domain_id_to_secondary_features_maps,
1516 final SortedSet<String> all_pfams_encountered,
1517 final SortedSet<String> pfams_gained_or_lost,
1518 final String suffix_for_per_node_events_file ) {
1519 if ( ( go_namespace_limit != null ) && ( ( go_id_to_term_map == null ) || ( go_id_to_term_map.size() < 1 ) ) ) {
1520 throw new IllegalArgumentException( "attempt to use GO namespace limit without a GO-id to term map" );
1522 else if ( ( ( domain_id_to_go_ids_map == null ) || ( domain_id_to_go_ids_map.size() < 1 ) ) ) {
1523 throw new IllegalArgumentException( "attempt to output detailed HTML without a Pfam to GO map" );
1525 else if ( ( ( go_id_to_term_map == null ) || ( go_id_to_term_map.size() < 1 ) ) ) {
1526 throw new IllegalArgumentException( "attempt to output detailed HTML without a GO-id to term map" );
1528 final File outfile = new File( filename );
1529 checkForOutputFileWriteability( outfile );
1530 final SortedSet<String> sorted_ids = new TreeSet<String>();
1531 for( int i = 0; i < matrix.getNumberOfIdentifiers(); ++i ) {
1532 sorted_ids.add( matrix.getIdentifier( i ) );
1535 final Writer out = new BufferedWriter( new FileWriter( outfile ) );
1536 final File per_node_go_mapped_domain_gain_loss_files_base_dir = createBaseDirForPerNodeDomainFiles( surfacing.BASE_DIRECTORY_PER_NODE_DOMAIN_GAIN_LOSS_FILES,
1537 domain_combinations,
1540 Writer per_node_go_mapped_domain_gain_loss_outfile_writer = null;
1541 File per_node_go_mapped_domain_gain_loss_outfile = null;
1542 int per_node_counter = 0;
1543 out.write( "<html>" );
1544 out.write( SurfacingConstants.NL );
1545 addHtmlHead( out, title_for_html );
1546 out.write( SurfacingConstants.NL );
1547 out.write( "<body>" );
1548 out.write( SurfacingConstants.NL );
1549 out.write( "<h1>" );
1550 out.write( SurfacingConstants.NL );
1551 out.write( title_for_html );
1552 out.write( SurfacingConstants.NL );
1553 out.write( "</h1>" );
1554 out.write( SurfacingConstants.NL );
1555 out.write( "<table>" );
1556 out.write( SurfacingConstants.NL );
1557 for( final String id : sorted_ids ) {
1558 final Matcher matcher = PATTERN_SP_STYLE_TAXONOMY.matcher( id );
1559 if ( matcher.matches() ) {
1562 out.write( "<tr>" );
1563 out.write( "<td>" );
1564 out.write( "<a href=\"#" + id + "\">" + id + "</a>" );
1565 out.write( "</td>" );
1566 out.write( "</tr>" );
1567 out.write( SurfacingConstants.NL );
1569 out.write( "</table>" );
1570 out.write( SurfacingConstants.NL );
1571 for( final String id : sorted_ids ) {
1572 final Matcher matcher = PATTERN_SP_STYLE_TAXONOMY.matcher( id );
1573 if ( matcher.matches() ) {
1576 out.write( SurfacingConstants.NL );
1577 out.write( "<h2>" );
1578 out.write( "<a name=\"" + id + "\">" + id + "</a>" );
1579 writeTaxonomyLinks( out, id );
1580 out.write( "</h2>" );
1581 out.write( SurfacingConstants.NL );
1582 out.write( "<table>" );
1583 out.write( SurfacingConstants.NL );
1584 out.write( "<tr>" );
1585 out.write( "<td><b>" );
1586 out.write( "Pfam domain(s)" );
1587 out.write( "</b></td><td><b>" );
1588 out.write( "GO term acc" );
1589 out.write( "</b></td><td><b>" );
1590 out.write( "GO term" );
1591 out.write( "</b></td><td><b>" );
1592 out.write( "GO namespace" );
1593 out.write( "</b></td>" );
1594 out.write( "</tr>" );
1595 out.write( SurfacingConstants.NL );
1596 out.write( "</tr>" );
1597 out.write( SurfacingConstants.NL );
1598 per_node_counter = 0;
1599 if ( matrix.getNumberOfCharacters() > 0 ) {
1600 per_node_go_mapped_domain_gain_loss_outfile = new File( per_node_go_mapped_domain_gain_loss_files_base_dir
1601 + ForesterUtil.FILE_SEPARATOR + id + suffix_for_per_node_events_file );
1602 SurfacingUtil.checkForOutputFileWriteability( per_node_go_mapped_domain_gain_loss_outfile );
1603 per_node_go_mapped_domain_gain_loss_outfile_writer = ForesterUtil
1604 .createBufferedWriter( per_node_go_mapped_domain_gain_loss_outfile );
1607 per_node_go_mapped_domain_gain_loss_outfile = null;
1608 per_node_go_mapped_domain_gain_loss_outfile_writer = null;
1610 for( int c = 0; c < matrix.getNumberOfCharacters(); ++c ) {
1612 // using null to indicate either UNCHANGED_PRESENT or GAIN.
1613 if ( ( matrix.getState( id, c ) == state )
1614 || ( ( state == null ) && ( ( matrix.getState( id, c ) == CharacterStateMatrix.GainLossStates.UNCHANGED_PRESENT ) || ( matrix
1615 .getState( id, c ) == CharacterStateMatrix.GainLossStates.GAIN ) ) ) ) {
1616 final String character = matrix.getCharacter( c );
1617 String domain_0 = "";
1618 String domain_1 = "";
1619 if ( character.indexOf( BinaryDomainCombination.SEPARATOR ) > 0 ) {
1620 final String[] s = character.split( BinaryDomainCombination.SEPARATOR );
1621 if ( s.length != 2 ) {
1622 throw new AssertionError( "this should not have happened: unexpected format for domain combination: ["
1623 + character + "]" );
1629 domain_0 = character;
1631 writeDomainData( domain_id_to_go_ids_map,
1638 character_separator,
1639 domain_id_to_secondary_features_maps,
1641 all_pfams_encountered.add( domain_0 );
1642 if ( pfams_gained_or_lost != null ) {
1643 pfams_gained_or_lost.add( domain_0 );
1645 if ( !ForesterUtil.isEmpty( domain_1 ) ) {
1646 all_pfams_encountered.add( domain_1 );
1647 if ( pfams_gained_or_lost != null ) {
1648 pfams_gained_or_lost.add( domain_1 );
1651 if ( per_node_go_mapped_domain_gain_loss_outfile_writer != null ) {
1652 writeDomainsToIndividualFilePerTreeNode( per_node_go_mapped_domain_gain_loss_outfile_writer,
1659 if ( per_node_go_mapped_domain_gain_loss_outfile_writer != null ) {
1660 per_node_go_mapped_domain_gain_loss_outfile_writer.close();
1661 if ( per_node_counter < 1 ) {
1662 per_node_go_mapped_domain_gain_loss_outfile.delete();
1664 per_node_counter = 0;
1666 out.write( "</table>" );
1667 out.write( SurfacingConstants.NL );
1668 out.write( "<hr>" );
1669 out.write( SurfacingConstants.NL );
1670 } // for( final String id : sorted_ids ) {
1671 out.write( "</body>" );
1672 out.write( SurfacingConstants.NL );
1673 out.write( "</html>" );
1674 out.write( SurfacingConstants.NL );
1678 catch ( final IOException e ) {
1679 ForesterUtil.fatalError( surfacing.PRG_NAME, e.getMessage() );
1681 ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote characters detailed HTML list: \"" + filename + "\"" );
1684 public static void writeBinaryStatesMatrixToListORIGIG( final Map<DomainId, List<GoId>> domain_id_to_go_ids_map,
1685 final Map<GoId, GoTerm> go_id_to_term_map,
1686 final GoNameSpace go_namespace_limit,
1687 final boolean domain_combinations,
1688 final CharacterStateMatrix<CharacterStateMatrix.GainLossStates> matrix,
1689 final CharacterStateMatrix.GainLossStates state,
1690 final String filename,
1691 final String indentifier_characters_separator,
1692 final String character_separator,
1693 final String title_for_html,
1694 final String prefix_for_html,
1695 final Map<DomainId, Set<String>>[] domain_id_to_secondary_features_maps,
1696 final SortedSet<String> all_pfams_encountered,
1697 final SortedSet<String> pfams_gained_or_lost,
1698 final String suffix_for_per_node_events_file ) {
1699 if ( ( go_namespace_limit != null ) && ( ( go_id_to_term_map == null ) || ( go_id_to_term_map.size() < 1 ) ) ) {
1700 throw new IllegalArgumentException( "attempt to use GO namespace limit without a GO-id to term map" );
1702 else if ( ( ( domain_id_to_go_ids_map == null ) || ( domain_id_to_go_ids_map.size() < 1 ) ) ) {
1703 throw new IllegalArgumentException( "attempt to output detailed HTML without a Pfam to GO map" );
1705 else if ( ( ( go_id_to_term_map == null ) || ( go_id_to_term_map.size() < 1 ) ) ) {
1706 throw new IllegalArgumentException( "attempt to output detailed HTML without a GO-id to term map" );
1708 final File outfile = new File( filename );
1709 checkForOutputFileWriteability( outfile );
1710 final SortedSet<String> sorted_ids = new TreeSet<String>();
1711 for( int i = 0; i < matrix.getNumberOfIdentifiers(); ++i ) {
1712 sorted_ids.add( matrix.getIdentifier( i ) );
1715 final Writer out = new BufferedWriter( new FileWriter( outfile ) );
1716 final File per_node_go_mapped_domain_gain_loss_files_base_dir = createBaseDirForPerNodeDomainFiles( surfacing.BASE_DIRECTORY_PER_NODE_DOMAIN_GAIN_LOSS_FILES,
1717 domain_combinations,
1720 Writer per_node_go_mapped_domain_gain_loss_outfile_writer = null;
1721 File per_node_go_mapped_domain_gain_loss_outfile = null;
1722 int per_node_counter = 0;
1723 out.write( "<html>" );
1724 out.write( SurfacingConstants.NL );
1725 addHtmlHead( out, title_for_html );
1726 out.write( SurfacingConstants.NL );
1727 out.write( "<body>" );
1728 out.write( SurfacingConstants.NL );
1729 out.write( "<h1>" );
1730 out.write( SurfacingConstants.NL );
1731 out.write( title_for_html );
1732 out.write( SurfacingConstants.NL );
1733 out.write( "</h1>" );
1734 out.write( SurfacingConstants.NL );
1735 out.write( "<table>" );
1736 out.write( SurfacingConstants.NL );
1737 for( final String id : sorted_ids ) {
1738 out.write( "<tr>" );
1739 out.write( "<td>" );
1740 out.write( "<a href=\"#" + id + "\">" + id + "</a>" );
1741 writeTaxonomyLinks( out, id );
1742 out.write( "</td>" );
1743 out.write( "</tr>" );
1744 out.write( SurfacingConstants.NL );
1746 out.write( "</table>" );
1747 out.write( SurfacingConstants.NL );
1748 for( final String id : sorted_ids ) {
1749 out.write( SurfacingConstants.NL );
1750 out.write( "<h2>" );
1751 out.write( "<a name=\"" + id + "\">" + id + "</a>" );
1752 writeTaxonomyLinks( out, id );
1753 out.write( "</h2>" );
1754 out.write( SurfacingConstants.NL );
1755 out.write( "<table>" );
1756 out.write( SurfacingConstants.NL );
1757 out.write( "<tr>" );
1758 out.write( "<td><b>" );
1759 out.write( "Pfam domain(s)" );
1760 out.write( "</b></td><td><b>" );
1761 out.write( "GO term acc" );
1762 out.write( "</b></td><td><b>" );
1763 out.write( "GO term" );
1764 out.write( "</b></td><td><b>" );
1765 out.write( "Penultimate GO term" );
1766 out.write( "</b></td><td><b>" );
1767 out.write( "GO namespace" );
1768 out.write( "</b></td>" );
1769 out.write( "</tr>" );
1770 out.write( SurfacingConstants.NL );
1771 out.write( "</tr>" );
1772 out.write( SurfacingConstants.NL );
1773 per_node_counter = 0;
1774 if ( matrix.getNumberOfCharacters() > 0 ) {
1775 per_node_go_mapped_domain_gain_loss_outfile = new File( per_node_go_mapped_domain_gain_loss_files_base_dir
1776 + ForesterUtil.FILE_SEPARATOR + id + suffix_for_per_node_events_file );
1777 SurfacingUtil.checkForOutputFileWriteability( per_node_go_mapped_domain_gain_loss_outfile );
1778 per_node_go_mapped_domain_gain_loss_outfile_writer = ForesterUtil
1779 .createBufferedWriter( per_node_go_mapped_domain_gain_loss_outfile );
1782 per_node_go_mapped_domain_gain_loss_outfile = null;
1783 per_node_go_mapped_domain_gain_loss_outfile_writer = null;
1785 for( int c = 0; c < matrix.getNumberOfCharacters(); ++c ) {
1787 // using null to indicate either UNCHANGED_PRESENT or GAIN.
1788 if ( ( matrix.getState( id, c ) == state )
1789 || ( ( state == null ) && ( ( matrix.getState( id, c ) == CharacterStateMatrix.GainLossStates.UNCHANGED_PRESENT ) || ( matrix
1790 .getState( id, c ) == CharacterStateMatrix.GainLossStates.GAIN ) ) ) ) {
1791 final String character = matrix.getCharacter( c );
1792 String domain_0 = "";
1793 String domain_1 = "";
1794 if ( character.indexOf( BinaryDomainCombination.SEPARATOR ) > 0 ) {
1795 final String[] s = character.split( BinaryDomainCombination.SEPARATOR );
1796 if ( s.length != 2 ) {
1797 throw new AssertionError( "this should not have happened: unexpected format for domain combination: ["
1798 + character + "]" );
1804 domain_0 = character;
1806 writeDomainData( domain_id_to_go_ids_map,
1813 character_separator,
1814 domain_id_to_secondary_features_maps,
1816 all_pfams_encountered.add( domain_0 );
1817 if ( pfams_gained_or_lost != null ) {
1818 pfams_gained_or_lost.add( domain_0 );
1820 if ( !ForesterUtil.isEmpty( domain_1 ) ) {
1821 all_pfams_encountered.add( domain_1 );
1822 if ( pfams_gained_or_lost != null ) {
1823 pfams_gained_or_lost.add( domain_1 );
1826 if ( per_node_go_mapped_domain_gain_loss_outfile_writer != null ) {
1827 writeDomainsToIndividualFilePerTreeNode( per_node_go_mapped_domain_gain_loss_outfile_writer,
1834 if ( per_node_go_mapped_domain_gain_loss_outfile_writer != null ) {
1835 per_node_go_mapped_domain_gain_loss_outfile_writer.close();
1836 if ( per_node_counter < 1 ) {
1837 per_node_go_mapped_domain_gain_loss_outfile.delete();
1839 per_node_counter = 0;
1841 out.write( "</table>" );
1842 out.write( SurfacingConstants.NL );
1843 out.write( "<hr>" );
1844 out.write( SurfacingConstants.NL );
1845 } // for( final String id : sorted_ids ) {
1846 out.write( "</body>" );
1847 out.write( SurfacingConstants.NL );
1848 out.write( "</html>" );
1849 out.write( SurfacingConstants.NL );
1853 catch ( final IOException e ) {
1854 ForesterUtil.fatalError( surfacing.PRG_NAME, e.getMessage() );
1856 ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote characters detailed HTML list: \"" + filename + "\"" );
1859 public static void writeDomainCombinationsCountsFile( final String[][] input_file_properties,
1860 final File output_dir,
1861 final Writer per_genome_domain_promiscuity_statistics_writer,
1862 final GenomeWideCombinableDomains gwcd,
1864 final GenomeWideCombinableDomains.GenomeWideCombinableDomainsSortOrder dc_sort_order ) {
1865 File dc_outfile = new File( input_file_properties[ i ][ 0 ]
1866 + surfacing.DOMAIN_COMBINITON_COUNTS_OUTPUTFILE_SUFFIX );
1867 if ( output_dir != null ) {
1868 dc_outfile = new File( output_dir + ForesterUtil.FILE_SEPARATOR + dc_outfile );
1870 checkForOutputFileWriteability( dc_outfile );
1872 final BufferedWriter out = new BufferedWriter( new FileWriter( dc_outfile ) );
1873 out.write( gwcd.toStringBuilder( dc_sort_order ).toString() );
1876 catch ( final IOException e ) {
1877 ForesterUtil.fatalError( surfacing.PRG_NAME, e.getMessage() );
1879 final DescriptiveStatistics stats = gwcd.getPerGenomeDomainPromiscuityStatistics();
1881 per_genome_domain_promiscuity_statistics_writer.write( input_file_properties[ i ][ 0 ] + "\t" );
1882 per_genome_domain_promiscuity_statistics_writer.write( FORMATTER_3.format( stats.arithmeticMean() ) + "\t" );
1883 if ( stats.getN() < 2 ) {
1884 per_genome_domain_promiscuity_statistics_writer.write( "n/a" + "\t" );
1887 per_genome_domain_promiscuity_statistics_writer.write( FORMATTER_3.format( stats
1888 .sampleStandardDeviation() ) + "\t" );
1890 per_genome_domain_promiscuity_statistics_writer.write( FORMATTER_3.format( stats.median() ) + "\t" );
1891 per_genome_domain_promiscuity_statistics_writer.write( ( int ) stats.getMin() + "\t" );
1892 per_genome_domain_promiscuity_statistics_writer.write( ( int ) stats.getMax() + "\t" );
1893 per_genome_domain_promiscuity_statistics_writer.write( stats.getN() + "\t" );
1894 final SortedSet<DomainId> mpds = gwcd.getMostPromiscuosDomain();
1895 for( final DomainId mpd : mpds ) {
1896 per_genome_domain_promiscuity_statistics_writer.write( mpd.getId() + " " );
1898 per_genome_domain_promiscuity_statistics_writer.write( ForesterUtil.LINE_SEPARATOR );
1900 catch ( final IOException e ) {
1901 ForesterUtil.fatalError( surfacing.PRG_NAME, e.getMessage() );
1903 if ( input_file_properties[ i ].length == 3 ) {
1904 ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote domain combination counts for \""
1905 + input_file_properties[ i ][ 0 ] + "\" (" + input_file_properties[ i ][ 1 ] + ", "
1906 + input_file_properties[ i ][ 2 ] + ") to: \"" + dc_outfile + "\"" );
1909 ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote domain combination counts for \""
1910 + input_file_properties[ i ][ 0 ] + "\" (" + input_file_properties[ i ][ 1 ] + ") to: \""
1911 + dc_outfile + "\"" );
1915 private static void writeDomainData( final Map<DomainId, List<GoId>> domain_id_to_go_ids_map,
1916 final Map<GoId, GoTerm> go_id_to_term_map,
1917 final GoNameSpace go_namespace_limit,
1919 final String domain_0,
1920 final String domain_1,
1921 final String prefix_for_html,
1922 final String character_separator_for_non_html_output,
1923 final Map<DomainId, Set<String>>[] domain_id_to_secondary_features_maps,
1924 final Set<GoId> all_go_ids ) throws IOException {
1925 boolean any_go_annotation_present = false;
1926 boolean first_has_no_go = false;
1927 int domain_count = 2; // To distinguish between domains and binary domain combinations.
1928 if ( ForesterUtil.isEmpty( domain_1 ) ) {
1931 // The following has a difficult to understand logic.
1932 for( int d = 0; d < domain_count; ++d ) {
1933 List<GoId> go_ids = null;
1934 boolean go_annotation_present = false;
1936 final DomainId domain_id = new DomainId( domain_0 );
1937 if ( domain_id_to_go_ids_map.containsKey( domain_id ) ) {
1938 go_annotation_present = true;
1939 any_go_annotation_present = true;
1940 go_ids = domain_id_to_go_ids_map.get( domain_id );
1943 first_has_no_go = true;
1947 final DomainId domain_id = new DomainId( domain_1 );
1948 if ( domain_id_to_go_ids_map.containsKey( domain_id ) ) {
1949 go_annotation_present = true;
1950 any_go_annotation_present = true;
1951 go_ids = domain_id_to_go_ids_map.get( domain_id );
1954 if ( go_annotation_present ) {
1955 boolean first = ( ( d == 0 ) || ( ( d == 1 ) && first_has_no_go ) );
1956 for( final GoId go_id : go_ids ) {
1957 out.write( "<tr>" );
1960 writeDomainIdsToHtml( out,
1964 domain_id_to_secondary_features_maps );
1967 out.write( "<td></td>" );
1969 if ( !go_id_to_term_map.containsKey( go_id ) ) {
1970 throw new IllegalArgumentException( "GO-id [" + go_id + "] not found in GO-id to GO-term map" );
1972 final GoTerm go_term = go_id_to_term_map.get( go_id );
1973 if ( ( go_namespace_limit == null ) || go_namespace_limit.equals( go_term.getGoNameSpace() ) ) {
1974 // final String top = GoUtils.getPenultimateGoTerm( go_term, go_id_to_term_map ).getName();
1975 final String go_id_str = go_id.getId();
1976 out.write( "<td>" );
1977 out.write( "<a href=\"" + SurfacingConstants.AMIGO_LINK + go_id_str
1978 + "\" target=\"amigo_window\">" + go_id_str + "</a>" );
1979 out.write( "</td><td>" );
1980 out.write( go_term.getName() );
1981 if ( domain_count == 2 ) {
1982 out.write( " (" + d + ")" );
1984 out.write( "</td><td>" );
1985 // out.write( top );
1986 // out.write( "</td><td>" );
1988 out.write( go_term.getGoNameSpace().toShortString() );
1990 out.write( "</td>" );
1991 if ( all_go_ids != null ) {
1992 all_go_ids.add( go_id );
1996 out.write( "<td>" );
1997 out.write( "</td><td>" );
1998 out.write( "</td><td>" );
1999 out.write( "</td><td>" );
2000 out.write( "</td>" );
2002 out.write( "</tr>" );
2003 out.write( SurfacingConstants.NL );
2006 } // for( int d = 0; d < domain_count; ++d )
2007 if ( !any_go_annotation_present ) {
2008 out.write( "<tr>" );
2009 writeDomainIdsToHtml( out, domain_0, domain_1, prefix_for_html, domain_id_to_secondary_features_maps );
2010 out.write( "<td>" );
2011 out.write( "</td><td>" );
2012 out.write( "</td><td>" );
2013 out.write( "</td><td>" );
2014 out.write( "</td>" );
2015 out.write( "</tr>" );
2016 out.write( SurfacingConstants.NL );
2020 private static void writeDomainIdsToHtml( final Writer out,
2021 final String domain_0,
2022 final String domain_1,
2023 final String prefix_for_detailed_html,
2024 final Map<DomainId, Set<String>>[] domain_id_to_secondary_features_maps )
2025 throws IOException {
2026 out.write( "<td>" );
2027 if ( !ForesterUtil.isEmpty( prefix_for_detailed_html ) ) {
2028 out.write( prefix_for_detailed_html );
2031 out.write( "<a href=\"" + SurfacingConstants.PFAM_FAMILY_ID_LINK + domain_0 + "\">" + domain_0 + "</a>" );
2032 out.write( "</td>" );
2035 public static DescriptiveStatistics writeDomainSimilaritiesToFile( final StringBuilder html_desc,
2036 final StringBuilder html_title,
2037 final Writer single_writer,
2038 Map<Character, Writer> split_writers,
2039 final SortedSet<DomainSimilarity> similarities,
2040 final boolean treat_as_binary,
2041 final List<Species> species_order,
2042 final PrintableDomainSimilarity.PRINT_OPTION print_option,
2043 final DomainSimilarity.DomainSimilaritySortField sort_field,
2044 final DomainSimilarity.DomainSimilarityScoring scoring,
2045 final boolean verbose ) throws IOException {
2046 final DescriptiveStatistics stats = new BasicDescriptiveStatistics();
2047 String histogram_title = null;
2048 switch ( sort_field ) {
2049 case ABS_MAX_COUNTS_DIFFERENCE:
2050 if ( treat_as_binary ) {
2051 histogram_title = "absolute counts difference:";
2054 histogram_title = "absolute (maximal) counts difference:";
2057 case MAX_COUNTS_DIFFERENCE:
2058 if ( treat_as_binary ) {
2059 histogram_title = "counts difference:";
2062 histogram_title = "(maximal) counts difference:";
2066 histogram_title = "score mean:";
2069 histogram_title = "score minimum:";
2072 histogram_title = "score maximum:";
2074 case MAX_DIFFERENCE:
2075 if ( treat_as_binary ) {
2076 histogram_title = "difference:";
2079 histogram_title = "(maximal) difference:";
2083 histogram_title = "score mean:";
2086 histogram_title = "score standard deviation:";
2089 histogram_title = "species number:";
2092 throw new AssertionError( "Unknown sort field: " + sort_field );
2094 for( final DomainSimilarity similarity : similarities ) {
2095 switch ( sort_field ) {
2096 case ABS_MAX_COUNTS_DIFFERENCE:
2097 stats.addValue( Math.abs( similarity.getMaximalDifferenceInCounts() ) );
2099 case MAX_COUNTS_DIFFERENCE:
2100 stats.addValue( similarity.getMaximalDifferenceInCounts() );
2103 stats.addValue( similarity.getMeanSimilarityScore() );
2106 stats.addValue( similarity.getMinimalSimilarityScore() );
2109 stats.addValue( similarity.getMaximalSimilarityScore() );
2111 case MAX_DIFFERENCE:
2112 stats.addValue( similarity.getMaximalDifference() );
2115 stats.addValue( similarity.getMeanSimilarityScore() );
2118 stats.addValue( similarity.getStandardDeviationOfSimilarityScore() );
2121 stats.addValue( similarity.getSpecies().size() );
2124 throw new AssertionError( "Unknown sort field: " + sort_field );
2128 // final HistogramData[] hists = new HistogramData[ 1 ];
2131 // List<HistogramDataItem> data_items = new
2132 // ArrayList<HistogramDataItem>();
2133 // double[] values = stats.getDataAsDoubleArray();
2134 // for( int i = 0; i < values.length; i++ ) {
2135 // HistogramDataItem data_item = new BasicHistogramDataItem( "", values[
2137 // data_items.add( data_item );
2141 // HistogramData hd0 = new HistogramData( "name",
2149 // hists[ 0 ] = hd0;
2151 // final HistogramsFrame hf = new HistogramsFrame( hists );
2152 // hf.setVisible( true );
2154 AsciiHistogram histo = null;
2155 if ( stats.getMin() < stats.getMin() ) {
2156 histo = new AsciiHistogram( stats, histogram_title );
2159 if ( histo != null ) {
2160 System.out.println( histo.toStringBuffer( 20, '|', 40, 5 ) );
2162 System.out.println();
2163 System.out.println( "N : " + stats.getN() );
2164 System.out.println( "Min : " + stats.getMin() );
2165 System.out.println( "Max : " + stats.getMax() );
2166 System.out.println( "Mean : " + stats.arithmeticMean() );
2167 if ( stats.getN() > 1 ) {
2168 System.out.println( "SD : " + stats.sampleStandardDeviation() );
2171 System.out.println( "SD : n/a" );
2173 System.out.println( "Median : " + stats.median() );
2174 if ( stats.getN() > 1 ) {
2175 System.out.println( "Pearsonian skewness : " + stats.pearsonianSkewness() );
2178 System.out.println( "Pearsonian skewness : n/a" );
2181 if ( ( single_writer != null ) && ( ( split_writers == null ) || split_writers.isEmpty() ) ) {
2182 split_writers = new HashMap<Character, Writer>();
2183 split_writers.put( '_', single_writer );
2185 switch ( print_option ) {
2186 case SIMPLE_TAB_DELIMITED:
2189 for( final Character key : split_writers.keySet() ) {
2190 final Writer w = split_writers.get( key );
2191 w.write( "<html>" );
2192 w.write( SurfacingConstants.NL );
2194 addHtmlHead( w, "DCs (" + html_title + ") " + key.toString().toUpperCase() );
2197 addHtmlHead( w, "DCs (" + html_title + ")" );
2199 w.write( SurfacingConstants.NL );
2200 w.write( "<body>" );
2201 w.write( SurfacingConstants.NL );
2202 w.write( html_desc.toString() );
2203 w.write( SurfacingConstants.NL );
2206 w.write( SurfacingConstants.NL );
2207 w.write( "<tt><pre>" );
2208 w.write( SurfacingConstants.NL );
2209 if ( histo != null ) {
2210 w.write( histo.toStringBuffer( 20, '|', 40, 5 ).toString() );
2211 w.write( SurfacingConstants.NL );
2213 w.write( "</pre></tt>" );
2214 w.write( SurfacingConstants.NL );
2215 w.write( "<table>" );
2216 w.write( SurfacingConstants.NL );
2217 w.write( "<tr><td>N: </td><td>" + stats.getN() + "</td></tr>" );
2218 w.write( SurfacingConstants.NL );
2219 w.write( "<tr><td>Min: </td><td>" + stats.getMin() + "</td></tr>" );
2220 w.write( SurfacingConstants.NL );
2221 w.write( "<tr><td>Max: </td><td>" + stats.getMax() + "</td></tr>" );
2222 w.write( SurfacingConstants.NL );
2223 w.write( "<tr><td>Mean: </td><td>" + stats.arithmeticMean() + "</td></tr>" );
2224 w.write( SurfacingConstants.NL );
2225 if ( stats.getN() > 1 ) {
2226 w.write( "<tr><td>SD: </td><td>" + stats.sampleStandardDeviation() + "</td></tr>" );
2229 w.write( "<tr><td>SD: </td><td>n/a</td></tr>" );
2231 w.write( SurfacingConstants.NL );
2232 w.write( "<tr><td>Median: </td><td>" + stats.median() + "</td></tr>" );
2233 w.write( SurfacingConstants.NL );
2234 if ( stats.getN() > 1 ) {
2235 w.write( "<tr><td>Pearsonian skewness: </td><td>" + stats.pearsonianSkewness() + "</td></tr>" );
2238 w.write( "<tr><td>Pearsonian skewness: </td><td>n/a</td></tr>" );
2240 w.write( SurfacingConstants.NL );
2241 w.write( "</table>" );
2242 w.write( SurfacingConstants.NL );
2244 w.write( SurfacingConstants.NL );
2246 w.write( SurfacingConstants.NL );
2248 w.write( SurfacingConstants.NL );
2249 w.write( "<table>" );
2250 w.write( SurfacingConstants.NL );
2254 for( final Writer w : split_writers.values() ) {
2255 w.write( SurfacingConstants.NL );
2257 for( final DomainSimilarity similarity : similarities ) {
2258 if ( ( species_order != null ) && !species_order.isEmpty() ) {
2259 ( ( PrintableDomainSimilarity ) similarity ).setSpeciesOrder( species_order );
2261 if ( single_writer != null ) {
2262 single_writer.write( similarity.toStringBuffer( print_option ).toString() );
2265 Writer local_writer = split_writers.get( ( similarity.getDomainId().getId().charAt( 0 ) + "" )
2266 .toLowerCase().charAt( 0 ) );
2267 if ( local_writer == null ) {
2268 local_writer = split_writers.get( '0' );
2270 local_writer.write( similarity.toStringBuffer( print_option ).toString() );
2272 for( final Writer w : split_writers.values() ) {
2273 w.write( SurfacingConstants.NL );
2276 switch ( print_option ) {
2278 for( final Writer w : split_writers.values() ) {
2279 w.write( SurfacingConstants.NL );
2280 w.write( "</table>" );
2281 w.write( SurfacingConstants.NL );
2282 w.write( "</font>" );
2283 w.write( SurfacingConstants.NL );
2284 w.write( "</body>" );
2285 w.write( SurfacingConstants.NL );
2286 w.write( "</html>" );
2287 w.write( SurfacingConstants.NL );
2291 for( final Writer w : split_writers.values() ) {
2297 private static void writeDomainsToIndividualFilePerTreeNode( final Writer individual_files_writer,
2298 final String domain_0,
2299 final String domain_1 ) throws IOException {
2300 individual_files_writer.write( domain_0 );
2301 individual_files_writer.write( ForesterUtil.LINE_SEPARATOR );
2302 if ( !ForesterUtil.isEmpty( domain_1 ) ) {
2303 individual_files_writer.write( domain_1 );
2304 individual_files_writer.write( ForesterUtil.LINE_SEPARATOR );
2308 public static void writeMatrixToFile( final CharacterStateMatrix<?> matrix,
2309 final String filename,
2310 final Format format ) {
2311 final File outfile = new File( filename );
2312 checkForOutputFileWriteability( outfile );
2314 final BufferedWriter out = new BufferedWriter( new FileWriter( outfile ) );
2315 matrix.toWriter( out, format );
2319 catch ( final IOException e ) {
2320 ForesterUtil.fatalError( surfacing.PRG_NAME, e.getMessage() );
2322 ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote matrix: \"" + filename + "\"" );
2325 public static void writeMatrixToFile( final File matrix_outfile, final List<DistanceMatrix> matrices ) {
2326 checkForOutputFileWriteability( matrix_outfile );
2328 final BufferedWriter out = new BufferedWriter( new FileWriter( matrix_outfile ) );
2329 for( final DistanceMatrix distance_matrix : matrices ) {
2330 out.write( distance_matrix.toStringBuffer( DistanceMatrix.Format.PHYLIP ).toString() );
2331 out.write( ForesterUtil.LINE_SEPARATOR );
2336 catch ( final IOException e ) {
2337 ForesterUtil.fatalError( surfacing.PRG_NAME, e.getMessage() );
2339 ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote distance matrices to \"" + matrix_outfile + "\"" );
2342 private static void writePfamsToFile( final String outfile_name, final SortedSet<String> pfams ) {
2344 final Writer writer = new BufferedWriter( new FileWriter( new File( outfile_name ) ) );
2345 for( final String pfam : pfams ) {
2346 writer.write( pfam );
2347 writer.write( ForesterUtil.LINE_SEPARATOR );
2350 ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote " + pfams.size() + " pfams to [" + outfile_name
2353 catch ( final IOException e ) {
2354 ForesterUtil.printWarningMessage( surfacing.PRG_NAME, "Failure to write: " + e );
2358 public static void writePhylogenyToFile( final Phylogeny phylogeny, final String filename ) {
2359 final PhylogenyWriter writer = new PhylogenyWriter();
2361 writer.toPhyloXML( new File( filename ), phylogeny, 1 );
2363 catch ( final IOException e ) {
2364 ForesterUtil.printWarningMessage( surfacing.PRG_NAME, "failed to write phylogeny to \"" + filename + "\": "
2367 ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote phylogeny to \"" + filename + "\"" );
2370 public static void writeTaxonomyLinks( final Writer writer, final String species ) throws IOException {
2371 if ( ( species.length() > 1 ) && ( species.indexOf( '_' ) < 1 ) ) {
2372 final Matcher matcher = PATTERN_SP_STYLE_TAXONOMY.matcher( species );
2373 writer.write( " [" );
2374 if ( matcher.matches() ) {
2375 writer.write( "<a href=\"" + SurfacingConstants.UNIPROT_LINK + species
2376 + "\" target=\"taxonomy_window\">uniprot</a>" );
2379 writer.write( "<a href=\"" + SurfacingConstants.EOL_LINK + species
2380 + "\" target=\"taxonomy_window\">eol</a>" );
2381 writer.write( "|" );
2382 writer.write( "<a href=\"" + SurfacingConstants.TOL_LINK + species
2383 + "\" target=\"taxonomy_window\">tol</a>" );
2385 writer.write( "]" );
2389 private static void writeToNexus( final String outfile_name,
2390 final CharacterStateMatrix<BinaryStates> matrix,
2391 final Phylogeny phylogeny ) {
2392 if ( !( matrix instanceof BasicCharacterStateMatrix ) ) {
2393 throw new IllegalArgumentException( "can only write matrices of type [" + BasicCharacterStateMatrix.class
2396 final BasicCharacterStateMatrix<BinaryStates> my_matrix = ( org.forester.evoinference.matrix.character.BasicCharacterStateMatrix<BinaryStates> ) matrix;
2397 final List<Phylogeny> phylogenies = new ArrayList<Phylogeny>( 1 );
2398 phylogenies.add( phylogeny );
2400 final BufferedWriter w = new BufferedWriter( new FileWriter( outfile_name ) );
2401 w.write( NexusConstants.NEXUS );
2402 w.write( ForesterUtil.LINE_SEPARATOR );
2403 my_matrix.writeNexusTaxaBlock( w );
2404 my_matrix.writeNexusBinaryChractersBlock( w );
2405 PhylogenyWriter.writeNexusTreesBlock( w, phylogenies, NH_CONVERSION_SUPPORT_VALUE_STYLE.NONE );
2408 ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote Nexus file: \"" + outfile_name + "\"" );
2410 catch ( final IOException e ) {
2411 ForesterUtil.fatalError( surfacing.PRG_NAME, e.getMessage() );
2415 private static void writeToNexus( final String outfile_name,
2416 final DomainParsimonyCalculator domain_parsimony,
2417 final Phylogeny phylogeny ) {
2418 writeToNexus( outfile_name + surfacing.NEXUS_EXTERNAL_DOMAINS,
2419 domain_parsimony.createMatrixOfDomainPresenceOrAbsence(),
2421 writeToNexus( outfile_name + surfacing.NEXUS_EXTERNAL_DOMAIN_COMBINATIONS,
2422 domain_parsimony.createMatrixOfBinaryDomainCombinationPresenceOrAbsence(),
2426 public static void domainsPerProteinsStatistics( final String genome,
2427 final List<Protein> protein_list,
2428 final DescriptiveStatistics all_genomes_domains_per_potein_stats,
2429 final SortedMap<Integer, Integer> all_genomes_domains_per_potein_histo,
2430 final SortedSet<String> domains_which_are_always_single,
2431 final SortedSet<String> domains_which_are_sometimes_single_sometimes_not,
2432 final SortedSet<String> domains_which_never_single,
2433 final Writer writer ) {
2434 final DescriptiveStatistics stats = new BasicDescriptiveStatistics();
2435 for( final Protein protein : protein_list ) {
2436 final int domains = protein.getNumberOfProteinDomains();
2437 //System.out.println( domains );
2438 stats.addValue( domains );
2439 all_genomes_domains_per_potein_stats.addValue( domains );
2440 if ( !all_genomes_domains_per_potein_histo.containsKey( domains ) ) {
2441 all_genomes_domains_per_potein_histo.put( domains, 1 );
2444 all_genomes_domains_per_potein_histo.put( domains,
2445 1 + all_genomes_domains_per_potein_histo.get( domains ) );
2447 if ( domains == 1 ) {
2448 final String domain = protein.getProteinDomain( 0 ).getDomainId().getId();
2449 if ( !domains_which_are_sometimes_single_sometimes_not.contains( domain ) ) {
2450 if ( domains_which_never_single.contains( domain ) ) {
2451 domains_which_never_single.remove( domain );
2452 domains_which_are_sometimes_single_sometimes_not.add( domain );
2455 domains_which_are_always_single.add( domain );
2459 else if ( domains > 1 ) {
2460 for( final Domain d : protein.getProteinDomains() ) {
2461 final String domain = d.getDomainId().getId();
2462 // System.out.println( domain );
2463 if ( !domains_which_are_sometimes_single_sometimes_not.contains( domain ) ) {
2464 if ( domains_which_are_always_single.contains( domain ) ) {
2465 domains_which_are_always_single.remove( domain );
2466 domains_which_are_sometimes_single_sometimes_not.add( domain );
2469 domains_which_never_single.add( domain );
2476 writer.write( genome );
2477 writer.write( "\t" );
2478 if ( stats.getN() >= 1 ) {
2479 writer.write( stats.arithmeticMean() + "" );
2480 writer.write( "\t" );
2481 if ( stats.getN() >= 2 ) {
2482 writer.write( stats.sampleStandardDeviation() + "" );
2487 writer.write( "\t" );
2488 writer.write( stats.median() + "" );
2489 writer.write( "\t" );
2490 writer.write( stats.getN() + "" );
2491 writer.write( "\t" );
2492 writer.write( stats.getMin() + "" );
2493 writer.write( "\t" );
2494 writer.write( stats.getMax() + "" );
2497 writer.write( "\t" );
2498 writer.write( "\t" );
2499 writer.write( "\t" );
2500 writer.write( "0" );
2501 writer.write( "\t" );
2502 writer.write( "\t" );
2504 writer.write( "\n" );
2506 catch ( final IOException e ) {
2507 e.printStackTrace();