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.protein.BasicProtein;
75 import org.forester.protein.BinaryDomainCombination;
76 import org.forester.protein.Domain;
77 import org.forester.protein.DomainId;
78 import org.forester.protein.Protein;
79 import org.forester.species.Species;
80 import org.forester.surfacing.DomainSimilarityCalculator.Detailedness;
81 import org.forester.surfacing.DomainSimilarityCalculator.GoAnnotationOutput;
82 import org.forester.surfacing.GenomeWideCombinableDomains.GenomeWideCombinableDomainsSortOrder;
83 import org.forester.util.AsciiHistogram;
84 import org.forester.util.BasicDescriptiveStatistics;
85 import org.forester.util.BasicTable;
86 import org.forester.util.BasicTableParser;
87 import org.forester.util.DescriptiveStatistics;
88 import org.forester.util.ForesterUtil;
90 public final class SurfacingUtil {
92 private final static NumberFormat FORMATTER = new DecimalFormat( "0.0E0" );
93 private final static NumberFormat FORMATTER_3 = new DecimalFormat( "0.000" );
94 private static final Comparator<Domain> ASCENDING_CONFIDENCE_VALUE_ORDER = new Comparator<Domain>() {
97 public int compare( final Domain d1,
99 if ( d1.getPerSequenceEvalue() < d2
100 .getPerSequenceEvalue() ) {
104 .getPerSequenceEvalue() > d2
105 .getPerSequenceEvalue() ) {
109 return d1.compareTo( d2 );
113 public final static Pattern PATTERN_SP_STYLE_TAXONOMY = Pattern.compile( "^[A-Z0-9]{3,5}$" );
114 private static final boolean USE_LAST = true;
116 private SurfacingUtil() {
117 // Hidden constructor.
120 public static void addAllBinaryDomainCombinationToSet( final GenomeWideCombinableDomains genome,
121 final SortedSet<BinaryDomainCombination> binary_domain_combinations ) {
122 final SortedMap<DomainId, CombinableDomains> all_cd = genome.getAllCombinableDomainsIds();
123 for( final DomainId domain_id : all_cd.keySet() ) {
124 binary_domain_combinations.addAll( all_cd.get( domain_id ).toBinaryDomainCombinations() );
128 public static void addAllDomainIdsToSet( final GenomeWideCombinableDomains genome,
129 final SortedSet<DomainId> domain_ids ) {
130 final SortedSet<DomainId> domains = genome.getAllDomainIds();
131 for( final DomainId domain : domains ) {
132 domain_ids.add( domain );
136 public static void addHtmlHead( final Writer w, final String title ) throws IOException {
137 w.write( SurfacingConstants.NL );
139 w.write( "<title>" );
141 w.write( "</title>" );
142 w.write( SurfacingConstants.NL );
143 w.write( "<style>" );
144 w.write( SurfacingConstants.NL );
145 w.write( "a:visited { color : #6633FF; text-decoration : none; }" );
146 w.write( SurfacingConstants.NL );
147 w.write( "a:link { color : #6633FF; text-decoration : none; }" );
148 w.write( SurfacingConstants.NL );
149 w.write( "a:active { color : #99FF00; text-decoration : none; }" );
150 w.write( SurfacingConstants.NL );
151 w.write( "a:hover { color : #FFFFFF; background-color : #99FF00; text-decoration : none; }" );
152 w.write( SurfacingConstants.NL );
153 w.write( "td { text-align: left; vertical-align: top; font-family: Verdana, Arial, Helvetica; font-size: 8pt}" );
154 w.write( SurfacingConstants.NL );
155 w.write( "h1 { color : #0000FF; font-family: Verdana, Arial, Helvetica; font-size: 18pt; font-weight: bold }" );
156 w.write( SurfacingConstants.NL );
157 w.write( "h2 { color : #0000FF; font-family: Verdana, Arial, Helvetica; font-size: 16pt; font-weight: bold }" );
158 w.write( SurfacingConstants.NL );
159 w.write( "</style>" );
160 w.write( SurfacingConstants.NL );
161 w.write( "</head>" );
162 w.write( SurfacingConstants.NL );
165 public static DescriptiveStatistics calculateDescriptiveStatisticsForMeanValues( final Set<DomainSimilarity> similarities ) {
166 final DescriptiveStatistics stats = new BasicDescriptiveStatistics();
167 for( final DomainSimilarity similarity : similarities ) {
168 stats.addValue( similarity.getMeanSimilarityScore() );
173 private static void calculateIndependentDomainCombinationGains( final Phylogeny local_phylogeny_l,
174 final String outfilename_for_counts,
175 final String outfilename_for_dc,
176 final String outfilename_for_dc_for_go_mapping,
177 final String outfilename_for_dc_for_go_mapping_unique,
178 final String outfilename_for_rank_counts,
179 final String outfilename_for_ancestor_species_counts ) {
181 final BufferedWriter out_counts = new BufferedWriter( new FileWriter( outfilename_for_counts ) );
182 final BufferedWriter out_dc = new BufferedWriter( new FileWriter( outfilename_for_dc ) );
183 final BufferedWriter out_dc_for_go_mapping = new BufferedWriter( new FileWriter( outfilename_for_dc_for_go_mapping ) );
184 final BufferedWriter out_dc_for_go_mapping_unique = new BufferedWriter( new FileWriter( outfilename_for_dc_for_go_mapping_unique ) );
185 final SortedMap<String, Integer> dc_gain_counts = new TreeMap<String, Integer>();
186 for( final PhylogenyNodeIterator it = local_phylogeny_l.iteratorPostorder(); it.hasNext(); ) {
187 final PhylogenyNode n = it.next();
188 final Set<String> gained_dc = n.getNodeData().getBinaryCharacters().getGainedCharacters();
189 for( final String dc : gained_dc ) {
190 if ( dc_gain_counts.containsKey( dc ) ) {
191 dc_gain_counts.put( dc, dc_gain_counts.get( dc ) + 1 );
194 dc_gain_counts.put( dc, 1 );
198 final SortedMap<Integer, Integer> histogram = new TreeMap<Integer, Integer>();
199 final SortedMap<Integer, StringBuilder> domain_lists = new TreeMap<Integer, StringBuilder>();
200 final SortedMap<Integer, PriorityQueue<String>> domain_lists_go = new TreeMap<Integer, PriorityQueue<String>>();
201 final SortedMap<Integer, SortedSet<String>> domain_lists_go_unique = new TreeMap<Integer, SortedSet<String>>();
202 final Set<String> dcs = dc_gain_counts.keySet();
203 final SortedSet<String> more_than_once = new TreeSet<String>();
204 for( final String dc : dcs ) {
205 final int count = dc_gain_counts.get( dc );
206 if ( histogram.containsKey( count ) ) {
207 histogram.put( count, histogram.get( count ) + 1 );
208 domain_lists.get( count ).append( ", " + dc );
209 domain_lists_go.get( count ).addAll( splitDomainCombination( dc ) );
210 domain_lists_go_unique.get( count ).addAll( splitDomainCombination( dc ) );
213 histogram.put( count, 1 );
214 domain_lists.put( count, new StringBuilder( dc ) );
215 final PriorityQueue<String> q = new PriorityQueue<String>();
216 q.addAll( splitDomainCombination( dc ) );
217 domain_lists_go.put( count, q );
218 final SortedSet<String> set = new TreeSet<String>();
219 set.addAll( splitDomainCombination( dc ) );
220 domain_lists_go_unique.put( count, set );
223 more_than_once.add( dc );
226 final Set<Integer> histogram_keys = histogram.keySet();
227 for( final Integer histogram_key : histogram_keys ) {
228 final int count = histogram.get( histogram_key );
229 final StringBuilder dc = domain_lists.get( histogram_key );
230 out_counts.write( histogram_key + "\t" + count + ForesterUtil.LINE_SEPARATOR );
231 out_dc.write( histogram_key + "\t" + dc + ForesterUtil.LINE_SEPARATOR );
232 out_dc_for_go_mapping.write( "#" + histogram_key + ForesterUtil.LINE_SEPARATOR );
233 final Object[] sorted = domain_lists_go.get( histogram_key ).toArray();
234 Arrays.sort( sorted );
235 for( final Object domain : sorted ) {
236 out_dc_for_go_mapping.write( domain + ForesterUtil.LINE_SEPARATOR );
238 out_dc_for_go_mapping_unique.write( "#" + histogram_key + ForesterUtil.LINE_SEPARATOR );
239 for( final String domain : domain_lists_go_unique.get( histogram_key ) ) {
240 out_dc_for_go_mapping_unique.write( domain + ForesterUtil.LINE_SEPARATOR );
245 out_dc_for_go_mapping.close();
246 out_dc_for_go_mapping_unique.close();
248 final SortedMap<String, Integer> lca_rank_counts = new TreeMap<String, Integer>();
249 final SortedMap<String, Integer> lca_ancestor_species_counts = new TreeMap<String, Integer>();
250 for( final String dc : more_than_once ) {
251 final List<PhylogenyNode> nodes = new ArrayList<PhylogenyNode>();
252 for( final PhylogenyNodeIterator it = local_phylogeny_l.iteratorExternalForward(); it.hasNext(); ) {
253 final PhylogenyNode n = it.next();
254 if ( n.getNodeData().getBinaryCharacters().getGainedCharacters().contains( dc ) ) {
258 for( int i = 0; i < nodes.size() - 1; ++i ) {
259 for( int j = i + 1; j < nodes.size(); ++j ) {
260 final PhylogenyNode lca = PhylogenyMethods.getInstance().obtainLCA( nodes.get( i ),
262 String rank = "unknown";
263 if ( lca.getNodeData().isHasTaxonomy()
264 && !ForesterUtil.isEmpty( lca.getNodeData().getTaxonomy().getRank() ) ) {
265 rank = lca.getNodeData().getTaxonomy().getRank();
267 addToCountMap( lca_rank_counts, rank );
269 if ( lca.getNodeData().isHasTaxonomy()
270 && !ForesterUtil.isEmpty( lca.getNodeData().getTaxonomy().getScientificName() ) ) {
271 lca_species = lca.getNodeData().getTaxonomy().getScientificName();
273 else if ( lca.getNodeData().isHasTaxonomy()
274 && !ForesterUtil.isEmpty( lca.getNodeData().getTaxonomy().getCommonName() ) ) {
275 lca_species = lca.getNodeData().getTaxonomy().getCommonName();
278 lca_species = lca.getName();
280 addToCountMap( lca_ancestor_species_counts, lca_species );
284 final BufferedWriter out_for_rank_counts = new BufferedWriter( new FileWriter( outfilename_for_rank_counts ) );
285 final BufferedWriter out_for_ancestor_species_counts = new BufferedWriter( new FileWriter( outfilename_for_ancestor_species_counts ) );
286 ForesterUtil.map2writer( out_for_rank_counts, lca_rank_counts, "\t", ForesterUtil.LINE_SEPARATOR );
287 ForesterUtil.map2writer( out_for_ancestor_species_counts,
288 lca_ancestor_species_counts,
290 ForesterUtil.LINE_SEPARATOR );
291 out_for_rank_counts.close();
292 out_for_ancestor_species_counts.close();
294 catch ( final IOException e ) {
295 ForesterUtil.printWarningMessage( surfacing.PRG_NAME, "Failure to write: " + e );
297 ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote independent domain combination gains fitch counts to ["
298 + outfilename_for_counts + "]" );
299 ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote independent domain combination gains fitch lists to ["
300 + outfilename_for_dc + "]" );
301 ForesterUtil.programMessage( surfacing.PRG_NAME,
302 "Wrote independent domain combination gains fitch lists to (for GO mapping) ["
303 + outfilename_for_dc_for_go_mapping + "]" );
304 ForesterUtil.programMessage( surfacing.PRG_NAME,
305 "Wrote independent domain combination gains fitch lists to (for GO mapping, unique) ["
306 + outfilename_for_dc_for_go_mapping_unique + "]" );
309 private final static void addToCountMap( final Map<String, Integer> map, final String s ) {
310 if ( map.containsKey( s ) ) {
311 map.put( s, map.get( s ) + 1 );
318 public static int calculateOverlap( final Domain domain, final List<Boolean> covered_positions ) {
319 int overlap_count = 0;
320 for( int i = domain.getFrom(); i <= domain.getTo(); ++i ) {
321 if ( ( i < covered_positions.size() ) && ( covered_positions.get( i ) == true ) ) {
325 return overlap_count;
328 public static void checkForOutputFileWriteability( final File outfile ) {
329 final String error = ForesterUtil.isWritableFile( outfile );
330 if ( !ForesterUtil.isEmpty( error ) ) {
331 ForesterUtil.fatalError( surfacing.PRG_NAME, error );
335 private static SortedSet<String> collectAllDomainsChangedOnSubtree( final PhylogenyNode subtree_root,
336 final boolean get_gains ) {
337 final SortedSet<String> domains = new TreeSet<String>();
338 for( final PhylogenyNode descendant : PhylogenyMethods.getAllDescendants( subtree_root ) ) {
339 final BinaryCharacters chars = descendant.getNodeData().getBinaryCharacters();
341 domains.addAll( chars.getGainedCharacters() );
344 domains.addAll( chars.getLostCharacters() );
350 public static void collectChangedDomainCombinationsFromBinaryStatesMatrixAsListToFile( final CharacterStateMatrix<CharacterStateMatrix.GainLossStates> matrix,
351 final BinaryDomainCombination.DomainCombinationType dc_type,
352 final List<BinaryDomainCombination> all_binary_domains_combination_gained,
353 final boolean get_gains ) {
354 final SortedSet<String> sorted_ids = new TreeSet<String>();
355 for( int i = 0; i < matrix.getNumberOfIdentifiers(); ++i ) {
356 sorted_ids.add( matrix.getIdentifier( i ) );
358 for( final String id : sorted_ids ) {
359 for( int c = 0; c < matrix.getNumberOfCharacters(); ++c ) {
360 if ( ( get_gains && ( matrix.getState( id, c ) == CharacterStateMatrix.GainLossStates.GAIN ) )
361 || ( !get_gains && ( matrix.getState( id, c ) == CharacterStateMatrix.GainLossStates.LOSS ) ) ) {
362 if ( dc_type == BinaryDomainCombination.DomainCombinationType.DIRECTED_ADJACTANT ) {
363 all_binary_domains_combination_gained.add( AdjactantDirectedBinaryDomainCombination
364 .createInstance( matrix.getCharacter( c ) ) );
366 else if ( dc_type == BinaryDomainCombination.DomainCombinationType.DIRECTED ) {
367 all_binary_domains_combination_gained.add( DirectedBinaryDomainCombination
368 .createInstance( matrix.getCharacter( c ) ) );
371 all_binary_domains_combination_gained.add( BasicBinaryDomainCombination.createInstance( matrix
372 .getCharacter( c ) ) );
379 private static File createBaseDirForPerNodeDomainFiles( final String base_dir,
380 final boolean domain_combinations,
381 final CharacterStateMatrix.GainLossStates state,
382 final String outfile ) {
383 File per_node_go_mapped_domain_gain_loss_files_base_dir = new File( new File( outfile ).getParent()
384 + ForesterUtil.FILE_SEPARATOR + base_dir );
385 if ( !per_node_go_mapped_domain_gain_loss_files_base_dir.exists() ) {
386 per_node_go_mapped_domain_gain_loss_files_base_dir.mkdir();
388 if ( domain_combinations ) {
389 per_node_go_mapped_domain_gain_loss_files_base_dir = new File( per_node_go_mapped_domain_gain_loss_files_base_dir
390 + ForesterUtil.FILE_SEPARATOR + "DC" );
393 per_node_go_mapped_domain_gain_loss_files_base_dir = new File( per_node_go_mapped_domain_gain_loss_files_base_dir
394 + ForesterUtil.FILE_SEPARATOR + "DOMAINS" );
396 if ( !per_node_go_mapped_domain_gain_loss_files_base_dir.exists() ) {
397 per_node_go_mapped_domain_gain_loss_files_base_dir.mkdir();
399 if ( state == GainLossStates.GAIN ) {
400 per_node_go_mapped_domain_gain_loss_files_base_dir = new File( per_node_go_mapped_domain_gain_loss_files_base_dir
401 + ForesterUtil.FILE_SEPARATOR + "GAINS" );
403 else if ( state == GainLossStates.LOSS ) {
404 per_node_go_mapped_domain_gain_loss_files_base_dir = new File( per_node_go_mapped_domain_gain_loss_files_base_dir
405 + ForesterUtil.FILE_SEPARATOR + "LOSSES" );
408 per_node_go_mapped_domain_gain_loss_files_base_dir = new File( per_node_go_mapped_domain_gain_loss_files_base_dir
409 + ForesterUtil.FILE_SEPARATOR + "PRESENT" );
411 if ( !per_node_go_mapped_domain_gain_loss_files_base_dir.exists() ) {
412 per_node_go_mapped_domain_gain_loss_files_base_dir.mkdir();
414 return per_node_go_mapped_domain_gain_loss_files_base_dir;
417 public static Map<DomainId, List<GoId>> createDomainIdToGoIdMap( final List<PfamToGoMapping> pfam_to_go_mappings ) {
418 final Map<DomainId, List<GoId>> domain_id_to_go_ids_map = new HashMap<DomainId, List<GoId>>( pfam_to_go_mappings
420 for( final PfamToGoMapping pfam_to_go : pfam_to_go_mappings ) {
421 if ( !domain_id_to_go_ids_map.containsKey( pfam_to_go.getKey() ) ) {
422 domain_id_to_go_ids_map.put( pfam_to_go.getKey(), new ArrayList<GoId>() );
424 domain_id_to_go_ids_map.get( pfam_to_go.getKey() ).add( pfam_to_go.getValue() );
426 return domain_id_to_go_ids_map;
429 public static Map<DomainId, Set<String>> createDomainIdToSecondaryFeaturesMap( final File secondary_features_map_file )
431 final BasicTable<String> primary_table = BasicTableParser.parse( secondary_features_map_file, "\t" );
432 final Map<DomainId, Set<String>> map = new TreeMap<DomainId, Set<String>>();
433 for( int r = 0; r < primary_table.getNumberOfRows(); ++r ) {
434 final DomainId domain_id = new DomainId( primary_table.getValue( 0, r ) );
435 if ( !map.containsKey( domain_id ) ) {
436 map.put( domain_id, new HashSet<String>() );
438 map.get( domain_id ).add( primary_table.getValue( 1, r ) );
443 public static Phylogeny createNjTreeBasedOnMatrixToFile( final File nj_tree_outfile, final DistanceMatrix distance ) {
444 checkForOutputFileWriteability( nj_tree_outfile );
445 final NeighborJoining nj = NeighborJoining.createInstance();
446 final Phylogeny phylogeny = nj.execute( distance );
447 phylogeny.setName( nj_tree_outfile.getName() );
448 writePhylogenyToFile( phylogeny, nj_tree_outfile.toString() );
452 private static SortedSet<BinaryDomainCombination> createSetOfAllBinaryDomainCombinationsPerGenome( final GenomeWideCombinableDomains gwcd ) {
453 final SortedMap<DomainId, CombinableDomains> cds = gwcd.getAllCombinableDomainsIds();
454 final SortedSet<BinaryDomainCombination> binary_combinations = new TreeSet<BinaryDomainCombination>();
455 for( final DomainId domain_id : cds.keySet() ) {
456 final CombinableDomains cd = cds.get( domain_id );
457 binary_combinations.addAll( cd.toBinaryDomainCombinations() );
459 return binary_combinations;
462 public static void decoratePrintableDomainSimilarities( final SortedSet<DomainSimilarity> domain_similarities,
463 final Detailedness detailedness,
464 final GoAnnotationOutput go_annotation_output,
465 final Map<GoId, GoTerm> go_id_to_term_map,
466 final GoNameSpace go_namespace_limit ) {
467 if ( ( go_namespace_limit != null ) && ( ( go_id_to_term_map == null ) || go_id_to_term_map.isEmpty() ) ) {
468 throw new IllegalArgumentException( "attempt to use a GO namespace limit without a GO id to term map" );
470 for( final DomainSimilarity domain_similarity : domain_similarities ) {
471 if ( domain_similarity instanceof PrintableDomainSimilarity ) {
472 final PrintableDomainSimilarity printable_domain_similarity = ( PrintableDomainSimilarity ) domain_similarity;
473 printable_domain_similarity.setDetailedness( detailedness );
474 printable_domain_similarity.setGoAnnotationOutput( go_annotation_output );
475 printable_domain_similarity.setGoIdToTermMap( go_id_to_term_map );
476 printable_domain_similarity.setGoNamespaceLimit( go_namespace_limit );
481 public static void executeDomainLengthAnalysis( final String[][] input_file_properties,
482 final int number_of_genomes,
483 final DomainLengthsTable domain_lengths_table,
484 final File outfile ) throws IOException {
485 final DecimalFormat df = new DecimalFormat( "#.00" );
486 checkForOutputFileWriteability( outfile );
487 final BufferedWriter out = new BufferedWriter( new FileWriter( outfile ) );
488 out.write( "MEAN BASED STATISTICS PER SPECIES" );
489 out.write( ForesterUtil.LINE_SEPARATOR );
490 out.write( domain_lengths_table.createMeanBasedStatisticsPerSpeciesTable().toString() );
491 out.write( ForesterUtil.LINE_SEPARATOR );
492 out.write( ForesterUtil.LINE_SEPARATOR );
493 final List<DomainLengths> domain_lengths_list = domain_lengths_table.getDomainLengthsList();
494 out.write( "OUTLIER SPECIES PER DOMAIN (Z>=1.5)" );
495 out.write( ForesterUtil.LINE_SEPARATOR );
496 for( final DomainLengths domain_lengths : domain_lengths_list ) {
497 final List<Species> species_list = domain_lengths.getMeanBasedOutlierSpecies( 1.5 );
498 if ( species_list.size() > 0 ) {
499 out.write( domain_lengths.getDomainId() + "\t" );
500 for( final Species species : species_list ) {
501 out.write( species + "\t" );
503 out.write( ForesterUtil.LINE_SEPARATOR );
504 // DescriptiveStatistics stats_for_domain = domain_lengths
505 // .calculateMeanBasedStatistics();
506 //AsciiHistogram histo = new AsciiHistogram( stats_for_domain );
507 //System.out.println( histo.toStringBuffer( 40, '=', 60, 4 ).toString() );
510 out.write( ForesterUtil.LINE_SEPARATOR );
511 out.write( ForesterUtil.LINE_SEPARATOR );
512 out.write( "OUTLIER SPECIES (Z 1.0)" );
513 out.write( ForesterUtil.LINE_SEPARATOR );
514 final DescriptiveStatistics stats_for_all_species = domain_lengths_table
515 .calculateMeanBasedStatisticsForAllSpecies();
516 out.write( stats_for_all_species.asSummary() );
517 out.write( ForesterUtil.LINE_SEPARATOR );
518 final AsciiHistogram histo = new AsciiHistogram( stats_for_all_species );
519 out.write( histo.toStringBuffer( 40, '=', 60, 4 ).toString() );
520 out.write( ForesterUtil.LINE_SEPARATOR );
521 final double population_sd = stats_for_all_species.sampleStandardDeviation();
522 final double population_mean = stats_for_all_species.arithmeticMean();
523 for( final Species species : domain_lengths_table.getSpecies() ) {
524 final double x = domain_lengths_table.calculateMeanBasedStatisticsForSpecies( species ).arithmeticMean();
525 final double z = ( x - population_mean ) / population_sd;
526 out.write( species + "\t" + z );
527 out.write( ForesterUtil.LINE_SEPARATOR );
529 out.write( ForesterUtil.LINE_SEPARATOR );
530 for( final Species species : domain_lengths_table.getSpecies() ) {
531 final DescriptiveStatistics stats_for_species = domain_lengths_table
532 .calculateMeanBasedStatisticsForSpecies( species );
533 final double x = stats_for_species.arithmeticMean();
534 final double z = ( x - population_mean ) / population_sd;
535 if ( ( z <= -1.0 ) || ( z >= 1.0 ) ) {
536 out.write( species + "\t" + df.format( z ) + "\t" + stats_for_species.asSummary() );
537 out.write( ForesterUtil.LINE_SEPARATOR );
541 // final List<HistogramData> histogram_datas = new ArrayList<HistogramData>();
542 // for( int i = 0; i < number_of_genomes; ++i ) {
543 // final Species species = new BasicSpecies( input_file_properties[ i ][ 0 ] );
545 // .add( new HistogramData( species.toString(), domain_lengths_table
546 // .calculateMeanBasedStatisticsForSpecies( species )
547 // .getDataAsDoubleArray(), 5, 600, null, 60 ) );
549 // final HistogramsFrame hf = new HistogramsFrame( histogram_datas );
550 // hf.setVisible( true );
556 * @param all_binary_domains_combination_lost_fitch
557 * @param consider_directedness_and_adjacency_for_bin_combinations
558 * @param all_binary_domains_combination_gained if null ignored, otherwise this is to list all binary domain combinations
559 * which were gained under unweighted (Fitch) parsimony.
561 public static void executeParsimonyAnalysis( final long random_number_seed_for_fitch_parsimony,
562 final boolean radomize_fitch_parsimony,
563 final String outfile_name,
564 final DomainParsimonyCalculator domain_parsimony,
565 final Phylogeny phylogeny,
566 final Map<DomainId, List<GoId>> domain_id_to_go_ids_map,
567 final Map<GoId, GoTerm> go_id_to_term_map,
568 final GoNameSpace go_namespace_limit,
569 final String parameters_str,
570 final Map<DomainId, Set<String>>[] domain_id_to_secondary_features_maps,
571 final SortedSet<DomainId> positive_filter,
572 final boolean output_binary_domain_combinations_for_graphs,
573 final List<BinaryDomainCombination> all_binary_domains_combination_gained_fitch,
574 final List<BinaryDomainCombination> all_binary_domains_combination_lost_fitch,
575 final BinaryDomainCombination.DomainCombinationType dc_type ) {
576 final String sep = ForesterUtil.LINE_SEPARATOR + "###################" + ForesterUtil.LINE_SEPARATOR;
577 final String date_time = ForesterUtil.getCurrentDateTime();
578 final SortedSet<String> all_pfams_encountered = new TreeSet<String>();
579 final SortedSet<String> all_pfams_gained_as_domains = new TreeSet<String>();
580 final SortedSet<String> all_pfams_lost_as_domains = new TreeSet<String>();
581 final SortedSet<String> all_pfams_gained_as_dom_combinations = new TreeSet<String>();
582 final SortedSet<String> all_pfams_lost_as_dom_combinations = new TreeSet<String>();
583 writeToNexus( outfile_name, domain_parsimony, phylogeny );
586 Phylogeny local_phylogeny_l = phylogeny.copy();
587 if ( ( positive_filter != null ) && ( positive_filter.size() > 0 ) ) {
588 domain_parsimony.executeDolloParsimonyOnDomainPresence( positive_filter );
591 domain_parsimony.executeDolloParsimonyOnDomainPresence();
593 SurfacingUtil.writeMatrixToFile( domain_parsimony.getGainLossMatrix(), outfile_name
594 + surfacing.PARSIMONY_OUTPUT_GL_SUFFIX_DOLLO_DOMAINS, Format.FORESTER );
595 SurfacingUtil.writeMatrixToFile( domain_parsimony.getGainLossCountsMatrix(), outfile_name
596 + surfacing.PARSIMONY_OUTPUT_GL_COUNTS_SUFFIX_DOLLO_DOMAINS, Format.FORESTER );
597 SurfacingUtil.writeBinaryStatesMatrixAsListToFile( domain_parsimony.getGainLossMatrix(),
598 CharacterStateMatrix.GainLossStates.GAIN,
599 outfile_name + surfacing.PARSIMONY_OUTPUT_DOLLO_GAINS_D,
601 ForesterUtil.LINE_SEPARATOR,
603 SurfacingUtil.writeBinaryStatesMatrixAsListToFile( domain_parsimony.getGainLossMatrix(),
604 CharacterStateMatrix.GainLossStates.LOSS,
605 outfile_name + surfacing.PARSIMONY_OUTPUT_DOLLO_LOSSES_D,
607 ForesterUtil.LINE_SEPARATOR,
609 SurfacingUtil.writeBinaryStatesMatrixAsListToFile( domain_parsimony.getGainLossMatrix(), null, outfile_name
610 + surfacing.PARSIMONY_OUTPUT_DOLLO_PRESENT_D, sep, ForesterUtil.LINE_SEPARATOR, null );
612 writeBinaryStatesMatrixToList( domain_id_to_go_ids_map,
616 domain_parsimony.getGainLossMatrix(),
617 CharacterStateMatrix.GainLossStates.GAIN,
618 outfile_name + surfacing.PARSIMONY_OUTPUT_DOLLO_GAINS_HTML_D,
620 ForesterUtil.LINE_SEPARATOR,
621 "Dollo Parsimony | Gains | Domains",
623 domain_id_to_secondary_features_maps,
624 all_pfams_encountered,
625 all_pfams_gained_as_domains,
627 writeBinaryStatesMatrixToList( domain_id_to_go_ids_map,
631 domain_parsimony.getGainLossMatrix(),
632 CharacterStateMatrix.GainLossStates.LOSS,
633 outfile_name + surfacing.PARSIMONY_OUTPUT_DOLLO_LOSSES_HTML_D,
635 ForesterUtil.LINE_SEPARATOR,
636 "Dollo Parsimony | Losses | Domains",
638 domain_id_to_secondary_features_maps,
639 all_pfams_encountered,
640 all_pfams_lost_as_domains,
642 writeBinaryStatesMatrixToList( domain_id_to_go_ids_map,
646 domain_parsimony.getGainLossMatrix(),
648 outfile_name + surfacing.PARSIMONY_OUTPUT_DOLLO_PRESENT_HTML_D,
650 ForesterUtil.LINE_SEPARATOR,
651 "Dollo Parsimony | Present | Domains",
653 domain_id_to_secondary_features_maps,
654 all_pfams_encountered,
656 "_dollo_present_d" );
657 preparePhylogeny( local_phylogeny_l,
660 "Dollo parsimony on domain presence/absence",
661 "dollo_on_domains_" + outfile_name,
663 SurfacingUtil.writePhylogenyToFile( local_phylogeny_l, outfile_name
664 + surfacing.DOMAINS_PARSIMONY_TREE_OUTPUT_SUFFIX_DOLLO );
666 writeAllDomainsChangedOnAllSubtrees( local_phylogeny_l, true, outfile_name, "_dollo_all_gains_d" );
667 writeAllDomainsChangedOnAllSubtrees( local_phylogeny_l, false, outfile_name, "_dollo_all_losses_d" );
669 catch ( final IOException e ) {
671 ForesterUtil.fatalError( surfacing.PRG_NAME, e.getLocalizedMessage() );
673 if ( domain_parsimony.calculateNumberOfBinaryDomainCombination() > 0 ) {
674 // FITCH DOMAIN COMBINATIONS
675 // -------------------------
676 local_phylogeny_l = phylogeny.copy();
677 String randomization = "no";
678 if ( radomize_fitch_parsimony ) {
679 domain_parsimony.executeFitchParsimonyOnBinaryDomainCombintion( random_number_seed_for_fitch_parsimony );
680 randomization = "yes, seed = " + random_number_seed_for_fitch_parsimony;
683 domain_parsimony.executeFitchParsimonyOnBinaryDomainCombintion( USE_LAST );
685 SurfacingUtil.writeMatrixToFile( domain_parsimony.getGainLossMatrix(), outfile_name
686 + surfacing.PARSIMONY_OUTPUT_GL_SUFFIX_FITCH_BINARY_COMBINATIONS, Format.FORESTER );
687 SurfacingUtil.writeMatrixToFile( domain_parsimony.getGainLossCountsMatrix(), outfile_name
688 + surfacing.PARSIMONY_OUTPUT_GL_COUNTS_SUFFIX_FITCH_BINARY_COMBINATIONS, Format.FORESTER );
690 .writeBinaryStatesMatrixAsListToFile( domain_parsimony.getGainLossMatrix(),
691 CharacterStateMatrix.GainLossStates.GAIN,
692 outfile_name + surfacing.PARSIMONY_OUTPUT_FITCH_GAINS_BC,
694 ForesterUtil.LINE_SEPARATOR,
696 SurfacingUtil.writeBinaryStatesMatrixAsListToFile( domain_parsimony.getGainLossMatrix(),
697 CharacterStateMatrix.GainLossStates.LOSS,
699 + surfacing.PARSIMONY_OUTPUT_FITCH_LOSSES_BC,
701 ForesterUtil.LINE_SEPARATOR,
703 SurfacingUtil.writeBinaryStatesMatrixAsListToFile( domain_parsimony.getGainLossMatrix(), null, outfile_name
704 + surfacing.PARSIMONY_OUTPUT_FITCH_PRESENT_BC, sep, ForesterUtil.LINE_SEPARATOR, null );
705 if ( all_binary_domains_combination_gained_fitch != null ) {
706 collectChangedDomainCombinationsFromBinaryStatesMatrixAsListToFile( domain_parsimony.getGainLossMatrix(),
708 all_binary_domains_combination_gained_fitch,
711 if ( all_binary_domains_combination_lost_fitch != null ) {
712 collectChangedDomainCombinationsFromBinaryStatesMatrixAsListToFile( domain_parsimony.getGainLossMatrix(),
714 all_binary_domains_combination_lost_fitch,
717 if ( output_binary_domain_combinations_for_graphs ) {
719 .writeBinaryStatesMatrixAsListToFileForBinaryCombinationsForGraphAnalysis( domain_parsimony
720 .getGainLossMatrix(),
723 + surfacing.PARSIMONY_OUTPUT_FITCH_PRESENT_BC_OUTPUTFILE_SUFFIX_FOR_GRAPH_ANALYSIS,
725 ForesterUtil.LINE_SEPARATOR,
726 BinaryDomainCombination.OutputFormat.DOT );
729 writeBinaryStatesMatrixToList( domain_id_to_go_ids_map,
733 domain_parsimony.getGainLossMatrix(),
734 CharacterStateMatrix.GainLossStates.GAIN,
735 outfile_name + surfacing.PARSIMONY_OUTPUT_FITCH_GAINS_HTML_BC,
737 ForesterUtil.LINE_SEPARATOR,
738 "Fitch Parsimony | Gains | Domain Combinations",
741 all_pfams_encountered,
742 all_pfams_gained_as_dom_combinations,
744 writeBinaryStatesMatrixToList( domain_id_to_go_ids_map,
748 domain_parsimony.getGainLossMatrix(),
749 CharacterStateMatrix.GainLossStates.LOSS,
750 outfile_name + surfacing.PARSIMONY_OUTPUT_FITCH_LOSSES_HTML_BC,
752 ForesterUtil.LINE_SEPARATOR,
753 "Fitch Parsimony | Losses | Domain Combinations",
756 all_pfams_encountered,
757 all_pfams_lost_as_dom_combinations,
758 "_fitch_losses_dc" );
759 writeBinaryStatesMatrixToList( domain_id_to_go_ids_map,
763 domain_parsimony.getGainLossMatrix(),
765 outfile_name + surfacing.PARSIMONY_OUTPUT_FITCH_PRESENT_HTML_BC,
767 ForesterUtil.LINE_SEPARATOR,
768 "Fitch Parsimony | Present | Domain Combinations",
771 all_pfams_encountered,
773 "_fitch_present_dc" );
774 writeAllEncounteredPfamsToFile( domain_id_to_go_ids_map,
777 all_pfams_encountered );
778 writePfamsToFile( outfile_name + surfacing.ALL_PFAMS_GAINED_AS_DOMAINS_SUFFIX, all_pfams_gained_as_domains );
779 writePfamsToFile( outfile_name + surfacing.ALL_PFAMS_LOST_AS_DOMAINS_SUFFIX, all_pfams_lost_as_domains );
780 writePfamsToFile( outfile_name + surfacing.ALL_PFAMS_GAINED_AS_DC_SUFFIX,
781 all_pfams_gained_as_dom_combinations );
782 writePfamsToFile( outfile_name + surfacing.ALL_PFAMS_LOST_AS_DC_SUFFIX, all_pfams_lost_as_dom_combinations );
783 preparePhylogeny( local_phylogeny_l,
786 "Fitch parsimony on binary domain combination presence/absence randomization: "
788 "fitch_on_binary_domain_combinations_" + outfile_name,
790 SurfacingUtil.writePhylogenyToFile( local_phylogeny_l, outfile_name
791 + surfacing.BINARY_DOMAIN_COMBINATIONS_PARSIMONY_TREE_OUTPUT_SUFFIX_FITCH );
792 calculateIndependentDomainCombinationGains( local_phylogeny_l, outfile_name
793 + surfacing.INDEPENDENT_DC_GAINS_FITCH_PARS_COUNTS_OUTPUT_SUFFIX, outfile_name
794 + surfacing.INDEPENDENT_DC_GAINS_FITCH_PARS_DC_OUTPUT_SUFFIX, outfile_name
795 + surfacing.INDEPENDENT_DC_GAINS_FITCH_PARS_DC_FOR_GO_MAPPING_OUTPUT_SUFFIX, outfile_name
796 + surfacing.INDEPENDENT_DC_GAINS_FITCH_PARS_DC_FOR_GO_MAPPING_OUTPUT_UNIQUE_SUFFIX, outfile_name
797 + "_indep_dc_gains_fitch_lca_ranks.txt", outfile_name + "_indep_dc_gains_fitch_lca_taxonomies.txt" );
801 public static void executeParsimonyAnalysisForSecondaryFeatures( final String outfile_name,
802 final DomainParsimonyCalculator secondary_features_parsimony,
803 final Phylogeny phylogeny,
804 final String parameters_str,
805 final Map<Species, MappingResults> mapping_results_map ) {
806 final String sep = ForesterUtil.LINE_SEPARATOR + "###################" + ForesterUtil.LINE_SEPARATOR;
807 final String date_time = ForesterUtil.getCurrentDateTime();
808 System.out.println();
809 writeToNexus( outfile_name + surfacing.NEXUS_SECONDARY_FEATURES,
810 secondary_features_parsimony.createMatrixOfSecondaryFeaturePresenceOrAbsence( null ),
812 Phylogeny local_phylogeny_copy = phylogeny.copy();
813 secondary_features_parsimony.executeDolloParsimonyOnSecondaryFeatures( mapping_results_map );
814 SurfacingUtil.writeMatrixToFile( secondary_features_parsimony.getGainLossMatrix(), outfile_name
815 + surfacing.PARSIMONY_OUTPUT_GL_SUFFIX_DOLLO_SECONDARY_FEATURES, Format.FORESTER );
816 SurfacingUtil.writeMatrixToFile( secondary_features_parsimony.getGainLossCountsMatrix(), outfile_name
817 + surfacing.PARSIMONY_OUTPUT_GL_COUNTS_SUFFIX_DOLLO_SECONDARY_FEATURES, Format.FORESTER );
819 .writeBinaryStatesMatrixAsListToFile( secondary_features_parsimony.getGainLossMatrix(),
820 CharacterStateMatrix.GainLossStates.GAIN,
822 + surfacing.PARSIMONY_OUTPUT_DOLLO_GAINS_SECONDARY_FEATURES,
824 ForesterUtil.LINE_SEPARATOR,
827 .writeBinaryStatesMatrixAsListToFile( secondary_features_parsimony.getGainLossMatrix(),
828 CharacterStateMatrix.GainLossStates.LOSS,
830 + surfacing.PARSIMONY_OUTPUT_DOLLO_LOSSES_SECONDARY_FEATURES,
832 ForesterUtil.LINE_SEPARATOR,
835 .writeBinaryStatesMatrixAsListToFile( secondary_features_parsimony.getGainLossMatrix(),
838 + surfacing.PARSIMONY_OUTPUT_DOLLO_PRESENT_SECONDARY_FEATURES,
840 ForesterUtil.LINE_SEPARATOR,
842 preparePhylogeny( local_phylogeny_copy,
843 secondary_features_parsimony,
845 "Dollo parsimony on secondary feature presence/absence",
846 "dollo_on_secondary_features_" + outfile_name,
848 SurfacingUtil.writePhylogenyToFile( local_phylogeny_copy, outfile_name
849 + surfacing.SECONDARY_FEATURES_PARSIMONY_TREE_OUTPUT_SUFFIX_DOLLO );
850 // FITCH DOMAIN COMBINATIONS
851 // -------------------------
852 local_phylogeny_copy = phylogeny.copy();
853 final String randomization = "no";
854 secondary_features_parsimony.executeFitchParsimonyOnBinaryDomainCombintionOnSecondaryFeatures( USE_LAST );
855 preparePhylogeny( local_phylogeny_copy,
856 secondary_features_parsimony,
858 "Fitch parsimony on secondary binary domain combination presence/absence randomization: "
860 "fitch_on_binary_domain_combinations_" + outfile_name,
862 SurfacingUtil.writePhylogenyToFile( local_phylogeny_copy, outfile_name
863 + surfacing.BINARY_DOMAIN_COMBINATIONS_PARSIMONY_TREE_OUTPUT_SUFFIX_FITCH_MAPPED );
864 calculateIndependentDomainCombinationGains( local_phylogeny_copy, outfile_name
865 + surfacing.INDEPENDENT_DC_GAINS_FITCH_PARS_COUNTS_MAPPED_OUTPUT_SUFFIX, outfile_name
866 + surfacing.INDEPENDENT_DC_GAINS_FITCH_PARS_DC_MAPPED_OUTPUT_SUFFIX, outfile_name
867 + surfacing.INDEPENDENT_DC_GAINS_FITCH_PARS_DC_FOR_GO_MAPPING_MAPPED_OUTPUT_SUFFIX, outfile_name
868 + surfacing.INDEPENDENT_DC_GAINS_FITCH_PARS_DC_FOR_GO_MAPPING_MAPPED_OUTPUT_UNIQUE_SUFFIX, outfile_name
869 + "_MAPPED_indep_dc_gains_fitch_lca_ranks.txt", outfile_name
870 + "_MAPPED_indep_dc_gains_fitch_lca_taxonomies.txt" );
873 public static void extractProteinNames( final List<Protein> proteins,
874 final List<DomainId> query_domain_ids_nc_order,
876 final String separator,
877 final String limit_to_species ) throws IOException {
878 for( final Protein protein : proteins ) {
879 if ( ForesterUtil.isEmpty( limit_to_species )
880 || protein.getSpecies().getSpeciesId().equalsIgnoreCase( limit_to_species ) ) {
881 if ( protein.contains( query_domain_ids_nc_order, true ) ) {
882 out.write( protein.getSpecies().getSpeciesId() );
883 out.write( separator );
884 out.write( protein.getProteinId().getId() );
885 out.write( separator );
887 final Set<DomainId> visited_domain_ids = new HashSet<DomainId>();
888 boolean first = true;
889 for( final Domain domain : protein.getProteinDomains() ) {
890 if ( !visited_domain_ids.contains( domain.getDomainId() ) ) {
891 visited_domain_ids.add( domain.getDomainId() );
898 out.write( domain.getDomainId().getId() );
900 out.write( "" + domain.getTotalCount() );
905 out.write( separator );
906 if ( !( ForesterUtil.isEmpty( protein.getDescription() ) || protein.getDescription()
907 .equals( SurfacingConstants.NONE ) ) ) {
908 out.write( protein.getDescription() );
910 out.write( separator );
911 if ( !( ForesterUtil.isEmpty( protein.getAccession() ) || protein.getAccession()
912 .equals( SurfacingConstants.NONE ) ) ) {
913 out.write( protein.getAccession() );
915 out.write( SurfacingConstants.NL );
922 public static void extractProteinNames( final SortedMap<Species, List<Protein>> protein_lists_per_species,
923 final DomainId domain_id,
925 final String separator,
926 final String limit_to_species ) throws IOException {
927 for( final Species species : protein_lists_per_species.keySet() ) {
928 for( final Protein protein : protein_lists_per_species.get( species ) ) {
929 if ( ForesterUtil.isEmpty( limit_to_species )
930 || protein.getSpecies().getSpeciesId().equalsIgnoreCase( limit_to_species ) ) {
931 final List<Domain> domains = protein.getProteinDomains( domain_id );
932 if ( domains.size() > 0 ) {
933 final DescriptiveStatistics stats = new BasicDescriptiveStatistics();
934 for( final Domain domain : domains ) {
935 stats.addValue( domain.getPerSequenceEvalue() );
937 out.write( protein.getSpecies().getSpeciesId() );
938 out.write( separator );
939 out.write( protein.getProteinId().getId() );
940 out.write( separator );
941 out.write( "[" + FORMATTER.format( stats.median() ) + "]" );
942 out.write( separator );
943 if ( !( ForesterUtil.isEmpty( protein.getDescription() ) || protein.getDescription()
944 .equals( SurfacingConstants.NONE ) ) ) {
945 out.write( protein.getDescription() );
947 out.write( separator );
948 if ( !( ForesterUtil.isEmpty( protein.getAccession() ) || protein.getAccession()
949 .equals( SurfacingConstants.NONE ) ) ) {
950 out.write( protein.getAccession() );
952 out.write( SurfacingConstants.NL );
960 public static SortedSet<DomainId> getAllDomainIds( final List<GenomeWideCombinableDomains> gwcd_list ) {
961 final SortedSet<DomainId> all_domains_ids = new TreeSet<DomainId>();
962 for( final GenomeWideCombinableDomains gwcd : gwcd_list ) {
963 final Set<DomainId> all_domains = gwcd.getAllDomainIds();
964 // for( final Domain domain : all_domains ) {
965 all_domains_ids.addAll( all_domains );
968 return all_domains_ids;
971 public static SortedMap<String, Integer> getDomainCounts( final List<Protein> protein_domain_collections ) {
972 final SortedMap<String, Integer> map = new TreeMap<String, Integer>();
973 for( final Protein protein_domain_collection : protein_domain_collections ) {
974 for( final Object name : protein_domain_collection.getProteinDomains() ) {
975 final BasicDomain protein_domain = ( BasicDomain ) name;
976 final String id = protein_domain.getDomainId().getId();
977 if ( map.containsKey( id ) ) {
978 map.put( id, map.get( id ) + 1 );
988 public static int getNumberOfNodesLackingName( final Phylogeny p, final StringBuilder names ) {
989 final PhylogenyNodeIterator it = p.iteratorPostorder();
991 while ( it.hasNext() ) {
992 final PhylogenyNode n = it.next();
993 if ( ForesterUtil.isEmpty( n.getName() )
994 && ( !n.getNodeData().isHasTaxonomy() || ForesterUtil.isEmpty( n.getNodeData().getTaxonomy()
995 .getScientificName() ) )
996 && ( !n.getNodeData().isHasTaxonomy() || ForesterUtil.isEmpty( n.getNodeData().getTaxonomy()
997 .getCommonName() ) ) ) {
998 if ( n.getParent() != null ) {
1000 names.append( n.getParent().getName() );
1002 final List l = n.getAllExternalDescendants();
1003 for( final Object object : l ) {
1004 System.out.println( l.toString() );
1013 * Returns true is Domain domain falls in an uninterrupted stretch of
1014 * covered positions.
1017 * @param covered_positions
1020 public static boolean isEngulfed( final Domain domain, final List<Boolean> covered_positions ) {
1021 for( int i = domain.getFrom(); i <= domain.getTo(); ++i ) {
1022 if ( ( i >= covered_positions.size() ) || ( covered_positions.get( i ) != true ) ) {
1029 public static void preparePhylogeny( final Phylogeny p,
1030 final DomainParsimonyCalculator domain_parsimony,
1031 final String date_time,
1032 final String method,
1034 final String parameters_str ) {
1035 domain_parsimony.decoratePhylogenyWithDomains( p );
1036 final StringBuilder desc = new StringBuilder();
1037 desc.append( "[Method: " + method + "] [Date: " + date_time + "] " );
1038 desc.append( "[Cost: " + domain_parsimony.getCost() + "] " );
1039 desc.append( "[Gains: " + domain_parsimony.getTotalGains() + "] " );
1040 desc.append( "[Losses: " + domain_parsimony.getTotalLosses() + "] " );
1041 desc.append( "[Unchanged: " + domain_parsimony.getTotalUnchanged() + "] " );
1042 desc.append( "[Parameters: " + parameters_str + "]" );
1044 p.setDescription( desc.toString() );
1045 p.setConfidence( new Confidence( domain_parsimony.getCost(), "parsimony" ) );
1046 p.setRerootable( false );
1047 p.setRooted( true );
1051 * species | protein id | n-terminal domain | c-terminal domain | n-terminal domain per domain E-value | c-terminal domain per domain E-value
1055 static public StringBuffer proteinToDomainCombinations( final Protein protein,
1056 final String protein_id,
1057 final String separator ) {
1058 final StringBuffer sb = new StringBuffer();
1059 if ( protein.getSpecies() == null ) {
1060 throw new IllegalArgumentException( "species must not be null" );
1062 if ( ForesterUtil.isEmpty( protein.getSpecies().getSpeciesId() ) ) {
1063 throw new IllegalArgumentException( "species id must not be empty" );
1065 final List<Domain> domains = protein.getProteinDomains();
1066 if ( domains.size() > 1 ) {
1067 final Map<String, Integer> counts = new HashMap<String, Integer>();
1068 for( final Domain domain : domains ) {
1069 final String id = domain.getDomainId().getId();
1070 if ( counts.containsKey( id ) ) {
1071 counts.put( id, counts.get( id ) + 1 );
1074 counts.put( id, 1 );
1077 final Set<String> dcs = new HashSet<String>();
1078 for( int i = 1; i < domains.size(); ++i ) {
1079 for( int j = 0; j < i; ++j ) {
1080 Domain domain_n = domains.get( i );
1081 Domain domain_c = domains.get( j );
1082 if ( domain_n.getFrom() > domain_c.getFrom() ) {
1083 domain_n = domains.get( j );
1084 domain_c = domains.get( i );
1086 final String dc = domain_n.getDomainId().getId() + domain_c.getDomainId().getId();
1087 if ( !dcs.contains( dc ) ) {
1089 sb.append( protein.getSpecies() );
1090 sb.append( separator );
1091 sb.append( protein_id );
1092 sb.append( separator );
1093 sb.append( domain_n.getDomainId().getId() );
1094 sb.append( separator );
1095 sb.append( domain_c.getDomainId().getId() );
1096 sb.append( separator );
1097 sb.append( domain_n.getPerDomainEvalue() );
1098 sb.append( separator );
1099 sb.append( domain_c.getPerDomainEvalue() );
1100 sb.append( separator );
1101 sb.append( counts.get( domain_n.getDomainId().getId() ) );
1102 sb.append( separator );
1103 sb.append( counts.get( domain_c.getDomainId().getId() ) );
1104 sb.append( ForesterUtil.LINE_SEPARATOR );
1109 else if ( domains.size() == 1 ) {
1110 sb.append( protein.getSpecies() );
1111 sb.append( separator );
1112 sb.append( protein_id );
1113 sb.append( separator );
1114 sb.append( domains.get( 0 ).getDomainId().getId() );
1115 sb.append( separator );
1116 sb.append( separator );
1117 sb.append( domains.get( 0 ).getPerDomainEvalue() );
1118 sb.append( separator );
1119 sb.append( separator );
1121 sb.append( separator );
1122 sb.append( ForesterUtil.LINE_SEPARATOR );
1125 sb.append( protein.getSpecies() );
1126 sb.append( separator );
1127 sb.append( protein_id );
1128 sb.append( separator );
1129 sb.append( separator );
1130 sb.append( separator );
1131 sb.append( separator );
1132 sb.append( separator );
1133 sb.append( separator );
1134 sb.append( ForesterUtil.LINE_SEPARATOR );
1141 * Example regarding engulfment: ------------0.1 ----------0.2 --0.3 =>
1142 * domain with 0.3 is ignored
1144 * -----------0.1 ----------0.2 --0.3 => domain with 0.3 is ignored
1147 * ------------0.1 ----------0.3 --0.2 => domains with 0.3 and 0.2 are _not_
1150 * @param max_allowed_overlap
1151 * maximal allowed overlap (inclusive) to be still considered not
1152 * overlapping (zero or negative value to allow any overlap)
1153 * @param remove_engulfed_domains
1154 * to remove domains which are completely engulfed by coverage of
1155 * domains with better support
1159 public static Protein removeOverlappingDomains( final int max_allowed_overlap,
1160 final boolean remove_engulfed_domains,
1161 final Protein protein ) {
1162 final Protein pruned_protein = new BasicProtein( protein.getProteinId().getId(), protein.getSpecies()
1163 .getSpeciesId(), protein.getLength() );
1164 final List<Domain> sorted = SurfacingUtil.sortDomainsWithAscendingConfidenceValues( protein );
1165 final List<Boolean> covered_positions = new ArrayList<Boolean>();
1166 for( final Domain domain : sorted ) {
1167 if ( ( ( max_allowed_overlap < 0 ) || ( SurfacingUtil.calculateOverlap( domain, covered_positions ) <= max_allowed_overlap ) )
1168 && ( !remove_engulfed_domains || !isEngulfed( domain, covered_positions ) ) ) {
1169 final int covered_positions_size = covered_positions.size();
1170 for( int i = covered_positions_size; i < domain.getFrom(); ++i ) {
1171 covered_positions.add( false );
1173 final int new_covered_positions_size = covered_positions.size();
1174 for( int i = domain.getFrom(); i <= domain.getTo(); ++i ) {
1175 if ( i < new_covered_positions_size ) {
1176 covered_positions.set( i, true );
1179 covered_positions.add( true );
1182 pruned_protein.addProteinDomain( domain );
1185 return pruned_protein;
1188 public static List<Domain> sortDomainsWithAscendingConfidenceValues( final Protein protein ) {
1189 final List<Domain> domains = new ArrayList<Domain>();
1190 for( final Domain d : protein.getProteinDomains() ) {
1193 Collections.sort( domains, SurfacingUtil.ASCENDING_CONFIDENCE_VALUE_ORDER );
1197 private static List<String> splitDomainCombination( final String dc ) {
1198 final String[] s = dc.split( "=" );
1199 if ( s.length != 2 ) {
1200 ForesterUtil.printErrorMessage( surfacing.PRG_NAME, "Stringyfied domain combination has illegal format: "
1204 final List<String> l = new ArrayList<String>( 2 );
1210 public static void writeAllDomainsChangedOnAllSubtrees( final Phylogeny p,
1211 final boolean get_gains,
1212 final String outdir,
1213 final String suffix_for_filename ) throws IOException {
1214 CharacterStateMatrix.GainLossStates state = CharacterStateMatrix.GainLossStates.GAIN;
1216 state = CharacterStateMatrix.GainLossStates.LOSS;
1218 final File base_dir = createBaseDirForPerNodeDomainFiles( surfacing.BASE_DIRECTORY_PER_SUBTREE_DOMAIN_GAIN_LOSS_FILES,
1222 for( final PhylogenyNodeIterator it = p.iteratorPostorder(); it.hasNext(); ) {
1223 final PhylogenyNode node = it.next();
1224 if ( !node.isExternal() ) {
1225 final SortedSet<String> domains = collectAllDomainsChangedOnSubtree( node, get_gains );
1226 if ( domains.size() > 0 ) {
1227 final Writer writer = ForesterUtil.createBufferedWriter( base_dir + ForesterUtil.FILE_SEPARATOR
1228 + node.getName() + suffix_for_filename );
1229 for( final String domain : domains ) {
1230 writer.write( domain );
1231 writer.write( ForesterUtil.LINE_SEPARATOR );
1239 private static void writeAllEncounteredPfamsToFile( final Map<DomainId, List<GoId>> domain_id_to_go_ids_map,
1240 final Map<GoId, GoTerm> go_id_to_term_map,
1241 final String outfile_name,
1242 final SortedSet<String> all_pfams_encountered ) {
1243 final File all_pfams_encountered_file = new File( outfile_name + surfacing.ALL_PFAMS_ENCOUNTERED_SUFFIX );
1244 final File all_pfams_encountered_with_go_annotation_file = new File( outfile_name
1245 + surfacing.ALL_PFAMS_ENCOUNTERED_WITH_GO_ANNOTATION_SUFFIX );
1246 final File encountered_pfams_summary_file = new File( outfile_name + surfacing.ENCOUNTERED_PFAMS_SUMMARY_SUFFIX );
1247 int biological_process_counter = 0;
1248 int cellular_component_counter = 0;
1249 int molecular_function_counter = 0;
1250 int pfams_with_mappings_counter = 0;
1251 int pfams_without_mappings_counter = 0;
1252 int pfams_without_mappings_to_bp_or_mf_counter = 0;
1253 int pfams_with_mappings_to_bp_or_mf_counter = 0;
1255 final Writer all_pfams_encountered_writer = new BufferedWriter( new FileWriter( all_pfams_encountered_file ) );
1256 final Writer all_pfams_encountered_with_go_annotation_writer = new BufferedWriter( new FileWriter( all_pfams_encountered_with_go_annotation_file ) );
1257 final Writer summary_writer = new BufferedWriter( new FileWriter( encountered_pfams_summary_file ) );
1258 summary_writer.write( "# Pfam to GO mapping summary" );
1259 summary_writer.write( ForesterUtil.LINE_SEPARATOR );
1260 summary_writer.write( "# Actual summary is at the end of this file." );
1261 summary_writer.write( ForesterUtil.LINE_SEPARATOR );
1262 summary_writer.write( "# Encountered Pfams without a GO mapping:" );
1263 summary_writer.write( ForesterUtil.LINE_SEPARATOR );
1264 for( final String pfam : all_pfams_encountered ) {
1265 all_pfams_encountered_writer.write( pfam );
1266 all_pfams_encountered_writer.write( ForesterUtil.LINE_SEPARATOR );
1267 final DomainId domain_id = new DomainId( pfam );
1268 if ( domain_id_to_go_ids_map.containsKey( domain_id ) ) {
1269 ++pfams_with_mappings_counter;
1270 all_pfams_encountered_with_go_annotation_writer.write( pfam );
1271 all_pfams_encountered_with_go_annotation_writer.write( ForesterUtil.LINE_SEPARATOR );
1272 final List<GoId> go_ids = domain_id_to_go_ids_map.get( domain_id );
1273 boolean maps_to_bp = false;
1274 boolean maps_to_cc = false;
1275 boolean maps_to_mf = false;
1276 for( final GoId go_id : go_ids ) {
1277 final GoTerm go_term = go_id_to_term_map.get( go_id );
1278 if ( go_term.getGoNameSpace().isBiologicalProcess() ) {
1281 else if ( go_term.getGoNameSpace().isCellularComponent() ) {
1284 else if ( go_term.getGoNameSpace().isMolecularFunction() ) {
1289 ++biological_process_counter;
1292 ++cellular_component_counter;
1295 ++molecular_function_counter;
1297 if ( maps_to_bp || maps_to_mf ) {
1298 ++pfams_with_mappings_to_bp_or_mf_counter;
1301 ++pfams_without_mappings_to_bp_or_mf_counter;
1305 ++pfams_without_mappings_to_bp_or_mf_counter;
1306 ++pfams_without_mappings_counter;
1307 summary_writer.write( pfam );
1308 summary_writer.write( ForesterUtil.LINE_SEPARATOR );
1311 all_pfams_encountered_writer.close();
1312 all_pfams_encountered_with_go_annotation_writer.close();
1313 ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote all [" + all_pfams_encountered.size()
1314 + "] encountered Pfams to: \"" + all_pfams_encountered_file + "\"" );
1315 ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote all [" + pfams_with_mappings_counter
1316 + "] encountered Pfams with GO mappings to: \"" + all_pfams_encountered_with_go_annotation_file
1318 ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote summary (including all ["
1319 + pfams_without_mappings_counter + "] encountered Pfams without GO mappings) to: \""
1320 + encountered_pfams_summary_file + "\"" );
1321 ForesterUtil.programMessage( surfacing.PRG_NAME, "Sum of Pfams encountered : "
1322 + all_pfams_encountered.size() );
1323 ForesterUtil.programMessage( surfacing.PRG_NAME, "Pfams without a mapping : "
1324 + pfams_without_mappings_counter + " ["
1325 + ( 100 * pfams_without_mappings_counter / all_pfams_encountered.size() ) + "%]" );
1326 ForesterUtil.programMessage( surfacing.PRG_NAME, "Pfams without mapping to proc. or func. : "
1327 + pfams_without_mappings_to_bp_or_mf_counter + " ["
1328 + ( 100 * pfams_without_mappings_to_bp_or_mf_counter / all_pfams_encountered.size() ) + "%]" );
1329 ForesterUtil.programMessage( surfacing.PRG_NAME,
1330 "Pfams with a mapping : " + pfams_with_mappings_counter
1332 + ( 100 * pfams_with_mappings_counter / all_pfams_encountered.size() )
1334 ForesterUtil.programMessage( surfacing.PRG_NAME, "Pfams with a mapping to proc. or func. : "
1335 + pfams_with_mappings_to_bp_or_mf_counter + " ["
1336 + ( 100 * pfams_with_mappings_to_bp_or_mf_counter / all_pfams_encountered.size() ) + "%]" );
1337 ForesterUtil.programMessage( surfacing.PRG_NAME,
1338 "Pfams with mapping to biological process: " + biological_process_counter
1340 + ( 100 * biological_process_counter / all_pfams_encountered.size() )
1342 ForesterUtil.programMessage( surfacing.PRG_NAME,
1343 "Pfams with mapping to molecular function: " + molecular_function_counter
1345 + ( 100 * molecular_function_counter / all_pfams_encountered.size() )
1347 ForesterUtil.programMessage( surfacing.PRG_NAME,
1348 "Pfams with mapping to cellular component: " + cellular_component_counter
1350 + ( 100 * cellular_component_counter / all_pfams_encountered.size() )
1352 summary_writer.write( ForesterUtil.LINE_SEPARATOR );
1353 summary_writer.write( "# Sum of Pfams encountered : " + all_pfams_encountered.size() );
1354 summary_writer.write( ForesterUtil.LINE_SEPARATOR );
1355 summary_writer.write( "# Pfams without a mapping : " + pfams_without_mappings_counter
1356 + " [" + ( 100 * pfams_without_mappings_counter / all_pfams_encountered.size() ) + "%]" );
1357 summary_writer.write( ForesterUtil.LINE_SEPARATOR );
1358 summary_writer.write( "# Pfams without mapping to proc. or func. : "
1359 + pfams_without_mappings_to_bp_or_mf_counter + " ["
1360 + ( 100 * pfams_without_mappings_to_bp_or_mf_counter / all_pfams_encountered.size() ) + "%]" );
1361 summary_writer.write( ForesterUtil.LINE_SEPARATOR );
1362 summary_writer.write( "# Pfams with a mapping : " + pfams_with_mappings_counter + " ["
1363 + ( 100 * pfams_with_mappings_counter / all_pfams_encountered.size() ) + "%]" );
1364 summary_writer.write( ForesterUtil.LINE_SEPARATOR );
1365 summary_writer.write( "# Pfams with a mapping to proc. or func. : "
1366 + pfams_with_mappings_to_bp_or_mf_counter + " ["
1367 + ( 100 * pfams_with_mappings_to_bp_or_mf_counter / all_pfams_encountered.size() ) + "%]" );
1368 summary_writer.write( ForesterUtil.LINE_SEPARATOR );
1369 summary_writer.write( "# Pfams with mapping to biological process: " + biological_process_counter + " ["
1370 + ( 100 * biological_process_counter / all_pfams_encountered.size() ) + "%]" );
1371 summary_writer.write( ForesterUtil.LINE_SEPARATOR );
1372 summary_writer.write( "# Pfams with mapping to molecular function: " + molecular_function_counter + " ["
1373 + ( 100 * molecular_function_counter / all_pfams_encountered.size() ) + "%]" );
1374 summary_writer.write( ForesterUtil.LINE_SEPARATOR );
1375 summary_writer.write( "# Pfams with mapping to cellular component: " + cellular_component_counter + " ["
1376 + ( 100 * cellular_component_counter / all_pfams_encountered.size() ) + "%]" );
1377 summary_writer.write( ForesterUtil.LINE_SEPARATOR );
1378 summary_writer.close();
1380 catch ( final IOException e ) {
1381 ForesterUtil.printWarningMessage( surfacing.PRG_NAME, "Failure to write: " + e );
1385 public static void writeBinaryDomainCombinationsFileForGraphAnalysis( final String[][] input_file_properties,
1386 final File output_dir,
1387 final GenomeWideCombinableDomains gwcd,
1389 final GenomeWideCombinableDomainsSortOrder dc_sort_order ) {
1390 File dc_outfile_dot = new File( input_file_properties[ i ][ 0 ]
1391 + surfacing.DOMAIN_COMBINITONS_OUTPUTFILE_SUFFIX_FOR_GRAPH_ANALYSIS );
1392 if ( output_dir != null ) {
1393 dc_outfile_dot = new File( output_dir + ForesterUtil.FILE_SEPARATOR + dc_outfile_dot );
1395 checkForOutputFileWriteability( dc_outfile_dot );
1396 final SortedSet<BinaryDomainCombination> binary_combinations = createSetOfAllBinaryDomainCombinationsPerGenome( gwcd );
1398 final BufferedWriter out_dot = new BufferedWriter( new FileWriter( dc_outfile_dot ) );
1399 for( final BinaryDomainCombination bdc : binary_combinations ) {
1400 out_dot.write( bdc.toGraphDescribingLanguage( BinaryDomainCombination.OutputFormat.DOT, null, null )
1402 out_dot.write( SurfacingConstants.NL );
1406 catch ( final IOException e ) {
1407 ForesterUtil.fatalError( surfacing.PRG_NAME, e.getMessage() );
1409 ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote binary domain combination for \""
1410 + input_file_properties[ i ][ 0 ] + "\" (" + input_file_properties[ i ][ 1 ] + ", "
1411 + input_file_properties[ i ][ 2 ] + ") to: \"" + dc_outfile_dot + "\"" );
1414 public static void writeBinaryStatesMatrixAsListToFile( final CharacterStateMatrix<CharacterStateMatrix.GainLossStates> matrix,
1415 final CharacterStateMatrix.GainLossStates state,
1416 final String filename,
1417 final String indentifier_characters_separator,
1418 final String character_separator,
1419 final Map<String, String> descriptions ) {
1420 final File outfile = new File( filename );
1421 checkForOutputFileWriteability( outfile );
1422 final SortedSet<String> sorted_ids = new TreeSet<String>();
1423 for( int i = 0; i < matrix.getNumberOfIdentifiers(); ++i ) {
1424 sorted_ids.add( matrix.getIdentifier( i ) );
1427 final BufferedWriter out = new BufferedWriter( new FileWriter( outfile ) );
1428 for( final String id : sorted_ids ) {
1429 out.write( indentifier_characters_separator );
1430 out.write( "#" + id );
1431 out.write( indentifier_characters_separator );
1432 for( int c = 0; c < matrix.getNumberOfCharacters(); ++c ) {
1434 // using null to indicate either UNCHANGED_PRESENT or GAIN.
1435 if ( ( matrix.getState( id, c ) == state )
1436 || ( ( state == null ) && ( ( matrix.getState( id, c ) == CharacterStateMatrix.GainLossStates.GAIN ) || ( matrix
1437 .getState( id, c ) == CharacterStateMatrix.GainLossStates.UNCHANGED_PRESENT ) ) ) ) {
1438 out.write( matrix.getCharacter( c ) );
1439 if ( ( descriptions != null ) && !descriptions.isEmpty()
1440 && descriptions.containsKey( matrix.getCharacter( c ) ) ) {
1442 out.write( descriptions.get( matrix.getCharacter( c ) ) );
1444 out.write( character_separator );
1451 catch ( final IOException e ) {
1452 ForesterUtil.fatalError( surfacing.PRG_NAME, e.getMessage() );
1454 ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote characters list: \"" + filename + "\"" );
1457 public static void writeBinaryStatesMatrixAsListToFileForBinaryCombinationsForGraphAnalysis( final CharacterStateMatrix<CharacterStateMatrix.GainLossStates> matrix,
1458 final CharacterStateMatrix.GainLossStates state,
1459 final String filename,
1460 final String indentifier_characters_separator,
1461 final String character_separator,
1462 final BinaryDomainCombination.OutputFormat bc_output_format ) {
1463 final File outfile = new File( filename );
1464 checkForOutputFileWriteability( outfile );
1465 final SortedSet<String> sorted_ids = new TreeSet<String>();
1466 for( int i = 0; i < matrix.getNumberOfIdentifiers(); ++i ) {
1467 sorted_ids.add( matrix.getIdentifier( i ) );
1470 final BufferedWriter out = new BufferedWriter( new FileWriter( outfile ) );
1471 for( final String id : sorted_ids ) {
1472 out.write( indentifier_characters_separator );
1473 out.write( "#" + id );
1474 out.write( indentifier_characters_separator );
1475 for( int c = 0; c < matrix.getNumberOfCharacters(); ++c ) {
1477 // using null to indicate either UNCHANGED_PRESENT or GAIN.
1478 if ( ( matrix.getState( id, c ) == state )
1479 || ( ( state == null ) && ( ( matrix.getState( id, c ) == CharacterStateMatrix.GainLossStates.GAIN ) || ( matrix
1480 .getState( id, c ) == CharacterStateMatrix.GainLossStates.UNCHANGED_PRESENT ) ) ) ) {
1481 BinaryDomainCombination bdc = null;
1483 bdc = BasicBinaryDomainCombination.createInstance( matrix.getCharacter( c ) );
1485 catch ( final Exception e ) {
1486 ForesterUtil.fatalError( surfacing.PRG_NAME, e.getLocalizedMessage() );
1488 out.write( bdc.toGraphDescribingLanguage( bc_output_format, null, null ).toString() );
1489 out.write( character_separator );
1496 catch ( final IOException e ) {
1497 ForesterUtil.fatalError( surfacing.PRG_NAME, e.getMessage() );
1499 ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote characters list: \"" + filename + "\"" );
1502 public static void writeBinaryStatesMatrixToList( final Map<DomainId, List<GoId>> domain_id_to_go_ids_map,
1503 final Map<GoId, GoTerm> go_id_to_term_map,
1504 final GoNameSpace go_namespace_limit,
1505 final boolean domain_combinations,
1506 final CharacterStateMatrix<CharacterStateMatrix.GainLossStates> matrix,
1507 final CharacterStateMatrix.GainLossStates state,
1508 final String filename,
1509 final String indentifier_characters_separator,
1510 final String character_separator,
1511 final String title_for_html,
1512 final String prefix_for_html,
1513 final Map<DomainId, Set<String>>[] domain_id_to_secondary_features_maps,
1514 final SortedSet<String> all_pfams_encountered,
1515 final SortedSet<String> pfams_gained_or_lost,
1516 final String suffix_for_per_node_events_file ) {
1517 if ( ( go_namespace_limit != null ) && ( ( go_id_to_term_map == null ) || ( go_id_to_term_map.size() < 1 ) ) ) {
1518 throw new IllegalArgumentException( "attempt to use GO namespace limit without a GO-id to term map" );
1520 else if ( ( ( domain_id_to_go_ids_map == null ) || ( domain_id_to_go_ids_map.size() < 1 ) ) ) {
1521 throw new IllegalArgumentException( "attempt to output detailed HTML without a Pfam to GO map" );
1523 else if ( ( ( go_id_to_term_map == null ) || ( go_id_to_term_map.size() < 1 ) ) ) {
1524 throw new IllegalArgumentException( "attempt to output detailed HTML without a GO-id to term map" );
1526 final File outfile = new File( filename );
1527 checkForOutputFileWriteability( outfile );
1528 final SortedSet<String> sorted_ids = new TreeSet<String>();
1529 for( int i = 0; i < matrix.getNumberOfIdentifiers(); ++i ) {
1530 sorted_ids.add( matrix.getIdentifier( i ) );
1533 final Writer out = new BufferedWriter( new FileWriter( outfile ) );
1534 final File per_node_go_mapped_domain_gain_loss_files_base_dir = createBaseDirForPerNodeDomainFiles( surfacing.BASE_DIRECTORY_PER_NODE_DOMAIN_GAIN_LOSS_FILES,
1535 domain_combinations,
1538 Writer per_node_go_mapped_domain_gain_loss_outfile_writer = null;
1539 File per_node_go_mapped_domain_gain_loss_outfile = null;
1540 int per_node_counter = 0;
1541 out.write( "<html>" );
1542 out.write( SurfacingConstants.NL );
1543 addHtmlHead( out, title_for_html );
1544 out.write( SurfacingConstants.NL );
1545 out.write( "<body>" );
1546 out.write( SurfacingConstants.NL );
1547 out.write( "<h1>" );
1548 out.write( SurfacingConstants.NL );
1549 out.write( title_for_html );
1550 out.write( SurfacingConstants.NL );
1551 out.write( "</h1>" );
1552 out.write( SurfacingConstants.NL );
1553 out.write( "<table>" );
1554 out.write( SurfacingConstants.NL );
1555 for( final String id : sorted_ids ) {
1556 final Matcher matcher = PATTERN_SP_STYLE_TAXONOMY.matcher( id );
1557 if ( matcher.matches() ) {
1560 out.write( "<tr>" );
1561 out.write( "<td>" );
1562 out.write( "<a href=\"#" + id + "\">" + id + "</a>" );
1563 out.write( "</td>" );
1564 out.write( "</tr>" );
1565 out.write( SurfacingConstants.NL );
1567 out.write( "</table>" );
1568 out.write( SurfacingConstants.NL );
1569 for( final String id : sorted_ids ) {
1570 final Matcher matcher = PATTERN_SP_STYLE_TAXONOMY.matcher( id );
1571 if ( matcher.matches() ) {
1574 out.write( SurfacingConstants.NL );
1575 out.write( "<h2>" );
1576 out.write( "<a name=\"" + id + "\">" + id + "</a>" );
1577 writeTaxonomyLinks( out, id );
1578 out.write( "</h2>" );
1579 out.write( SurfacingConstants.NL );
1580 out.write( "<table>" );
1581 out.write( SurfacingConstants.NL );
1582 out.write( "<tr>" );
1583 out.write( "<td><b>" );
1584 out.write( "Pfam domain(s)" );
1585 out.write( "</b></td><td><b>" );
1586 out.write( "GO term acc" );
1587 out.write( "</b></td><td><b>" );
1588 out.write( "GO term" );
1589 out.write( "</b></td><td><b>" );
1590 out.write( "GO namespace" );
1591 out.write( "</b></td>" );
1592 out.write( "</tr>" );
1593 out.write( SurfacingConstants.NL );
1594 out.write( "</tr>" );
1595 out.write( SurfacingConstants.NL );
1596 per_node_counter = 0;
1597 if ( matrix.getNumberOfCharacters() > 0 ) {
1598 per_node_go_mapped_domain_gain_loss_outfile = new File( per_node_go_mapped_domain_gain_loss_files_base_dir
1599 + ForesterUtil.FILE_SEPARATOR + id + suffix_for_per_node_events_file );
1600 SurfacingUtil.checkForOutputFileWriteability( per_node_go_mapped_domain_gain_loss_outfile );
1601 per_node_go_mapped_domain_gain_loss_outfile_writer = ForesterUtil
1602 .createBufferedWriter( per_node_go_mapped_domain_gain_loss_outfile );
1605 per_node_go_mapped_domain_gain_loss_outfile = null;
1606 per_node_go_mapped_domain_gain_loss_outfile_writer = null;
1608 for( int c = 0; c < matrix.getNumberOfCharacters(); ++c ) {
1610 // using null to indicate either UNCHANGED_PRESENT or GAIN.
1611 if ( ( matrix.getState( id, c ) == state )
1612 || ( ( state == null ) && ( ( matrix.getState( id, c ) == CharacterStateMatrix.GainLossStates.UNCHANGED_PRESENT ) || ( matrix
1613 .getState( id, c ) == CharacterStateMatrix.GainLossStates.GAIN ) ) ) ) {
1614 final String character = matrix.getCharacter( c );
1615 String domain_0 = "";
1616 String domain_1 = "";
1617 if ( character.indexOf( BinaryDomainCombination.SEPARATOR ) > 0 ) {
1618 final String[] s = character.split( BinaryDomainCombination.SEPARATOR );
1619 if ( s.length != 2 ) {
1620 throw new AssertionError( "this should not have happened: unexpected format for domain combination: ["
1621 + character + "]" );
1627 domain_0 = character;
1629 writeDomainData( domain_id_to_go_ids_map,
1636 character_separator,
1637 domain_id_to_secondary_features_maps,
1639 all_pfams_encountered.add( domain_0 );
1640 if ( pfams_gained_or_lost != null ) {
1641 pfams_gained_or_lost.add( domain_0 );
1643 if ( !ForesterUtil.isEmpty( domain_1 ) ) {
1644 all_pfams_encountered.add( domain_1 );
1645 if ( pfams_gained_or_lost != null ) {
1646 pfams_gained_or_lost.add( domain_1 );
1649 if ( per_node_go_mapped_domain_gain_loss_outfile_writer != null ) {
1650 writeDomainsToIndividualFilePerTreeNode( per_node_go_mapped_domain_gain_loss_outfile_writer,
1657 if ( per_node_go_mapped_domain_gain_loss_outfile_writer != null ) {
1658 per_node_go_mapped_domain_gain_loss_outfile_writer.close();
1659 if ( per_node_counter < 1 ) {
1660 per_node_go_mapped_domain_gain_loss_outfile.delete();
1662 per_node_counter = 0;
1664 out.write( "</table>" );
1665 out.write( SurfacingConstants.NL );
1666 out.write( "<hr>" );
1667 out.write( SurfacingConstants.NL );
1668 } // for( final String id : sorted_ids ) {
1669 out.write( "</body>" );
1670 out.write( SurfacingConstants.NL );
1671 out.write( "</html>" );
1672 out.write( SurfacingConstants.NL );
1676 catch ( final IOException e ) {
1677 ForesterUtil.fatalError( surfacing.PRG_NAME, e.getMessage() );
1679 ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote characters detailed HTML list: \"" + filename + "\"" );
1682 public static void writeBinaryStatesMatrixToListORIGIG( final Map<DomainId, List<GoId>> domain_id_to_go_ids_map,
1683 final Map<GoId, GoTerm> go_id_to_term_map,
1684 final GoNameSpace go_namespace_limit,
1685 final boolean domain_combinations,
1686 final CharacterStateMatrix<CharacterStateMatrix.GainLossStates> matrix,
1687 final CharacterStateMatrix.GainLossStates state,
1688 final String filename,
1689 final String indentifier_characters_separator,
1690 final String character_separator,
1691 final String title_for_html,
1692 final String prefix_for_html,
1693 final Map<DomainId, Set<String>>[] domain_id_to_secondary_features_maps,
1694 final SortedSet<String> all_pfams_encountered,
1695 final SortedSet<String> pfams_gained_or_lost,
1696 final String suffix_for_per_node_events_file ) {
1697 if ( ( go_namespace_limit != null ) && ( ( go_id_to_term_map == null ) || ( go_id_to_term_map.size() < 1 ) ) ) {
1698 throw new IllegalArgumentException( "attempt to use GO namespace limit without a GO-id to term map" );
1700 else if ( ( ( domain_id_to_go_ids_map == null ) || ( domain_id_to_go_ids_map.size() < 1 ) ) ) {
1701 throw new IllegalArgumentException( "attempt to output detailed HTML without a Pfam to GO map" );
1703 else if ( ( ( go_id_to_term_map == null ) || ( go_id_to_term_map.size() < 1 ) ) ) {
1704 throw new IllegalArgumentException( "attempt to output detailed HTML without a GO-id to term map" );
1706 final File outfile = new File( filename );
1707 checkForOutputFileWriteability( outfile );
1708 final SortedSet<String> sorted_ids = new TreeSet<String>();
1709 for( int i = 0; i < matrix.getNumberOfIdentifiers(); ++i ) {
1710 sorted_ids.add( matrix.getIdentifier( i ) );
1713 final Writer out = new BufferedWriter( new FileWriter( outfile ) );
1714 final File per_node_go_mapped_domain_gain_loss_files_base_dir = createBaseDirForPerNodeDomainFiles( surfacing.BASE_DIRECTORY_PER_NODE_DOMAIN_GAIN_LOSS_FILES,
1715 domain_combinations,
1718 Writer per_node_go_mapped_domain_gain_loss_outfile_writer = null;
1719 File per_node_go_mapped_domain_gain_loss_outfile = null;
1720 int per_node_counter = 0;
1721 out.write( "<html>" );
1722 out.write( SurfacingConstants.NL );
1723 addHtmlHead( out, title_for_html );
1724 out.write( SurfacingConstants.NL );
1725 out.write( "<body>" );
1726 out.write( SurfacingConstants.NL );
1727 out.write( "<h1>" );
1728 out.write( SurfacingConstants.NL );
1729 out.write( title_for_html );
1730 out.write( SurfacingConstants.NL );
1731 out.write( "</h1>" );
1732 out.write( SurfacingConstants.NL );
1733 out.write( "<table>" );
1734 out.write( SurfacingConstants.NL );
1735 for( final String id : sorted_ids ) {
1736 out.write( "<tr>" );
1737 out.write( "<td>" );
1738 out.write( "<a href=\"#" + id + "\">" + id + "</a>" );
1739 writeTaxonomyLinks( out, id );
1740 out.write( "</td>" );
1741 out.write( "</tr>" );
1742 out.write( SurfacingConstants.NL );
1744 out.write( "</table>" );
1745 out.write( SurfacingConstants.NL );
1746 for( final String id : sorted_ids ) {
1747 out.write( SurfacingConstants.NL );
1748 out.write( "<h2>" );
1749 out.write( "<a name=\"" + id + "\">" + id + "</a>" );
1750 writeTaxonomyLinks( out, id );
1751 out.write( "</h2>" );
1752 out.write( SurfacingConstants.NL );
1753 out.write( "<table>" );
1754 out.write( SurfacingConstants.NL );
1755 out.write( "<tr>" );
1756 out.write( "<td><b>" );
1757 out.write( "Pfam domain(s)" );
1758 out.write( "</b></td><td><b>" );
1759 out.write( "GO term acc" );
1760 out.write( "</b></td><td><b>" );
1761 out.write( "GO term" );
1762 out.write( "</b></td><td><b>" );
1763 out.write( "Penultimate GO term" );
1764 out.write( "</b></td><td><b>" );
1765 out.write( "GO namespace" );
1766 out.write( "</b></td>" );
1767 out.write( "</tr>" );
1768 out.write( SurfacingConstants.NL );
1769 out.write( "</tr>" );
1770 out.write( SurfacingConstants.NL );
1771 per_node_counter = 0;
1772 if ( matrix.getNumberOfCharacters() > 0 ) {
1773 per_node_go_mapped_domain_gain_loss_outfile = new File( per_node_go_mapped_domain_gain_loss_files_base_dir
1774 + ForesterUtil.FILE_SEPARATOR + id + suffix_for_per_node_events_file );
1775 SurfacingUtil.checkForOutputFileWriteability( per_node_go_mapped_domain_gain_loss_outfile );
1776 per_node_go_mapped_domain_gain_loss_outfile_writer = ForesterUtil
1777 .createBufferedWriter( per_node_go_mapped_domain_gain_loss_outfile );
1780 per_node_go_mapped_domain_gain_loss_outfile = null;
1781 per_node_go_mapped_domain_gain_loss_outfile_writer = null;
1783 for( int c = 0; c < matrix.getNumberOfCharacters(); ++c ) {
1785 // using null to indicate either UNCHANGED_PRESENT or GAIN.
1786 if ( ( matrix.getState( id, c ) == state )
1787 || ( ( state == null ) && ( ( matrix.getState( id, c ) == CharacterStateMatrix.GainLossStates.UNCHANGED_PRESENT ) || ( matrix
1788 .getState( id, c ) == CharacterStateMatrix.GainLossStates.GAIN ) ) ) ) {
1789 final String character = matrix.getCharacter( c );
1790 String domain_0 = "";
1791 String domain_1 = "";
1792 if ( character.indexOf( BinaryDomainCombination.SEPARATOR ) > 0 ) {
1793 final String[] s = character.split( BinaryDomainCombination.SEPARATOR );
1794 if ( s.length != 2 ) {
1795 throw new AssertionError( "this should not have happened: unexpected format for domain combination: ["
1796 + character + "]" );
1802 domain_0 = character;
1804 writeDomainData( domain_id_to_go_ids_map,
1811 character_separator,
1812 domain_id_to_secondary_features_maps,
1814 all_pfams_encountered.add( domain_0 );
1815 if ( pfams_gained_or_lost != null ) {
1816 pfams_gained_or_lost.add( domain_0 );
1818 if ( !ForesterUtil.isEmpty( domain_1 ) ) {
1819 all_pfams_encountered.add( domain_1 );
1820 if ( pfams_gained_or_lost != null ) {
1821 pfams_gained_or_lost.add( domain_1 );
1824 if ( per_node_go_mapped_domain_gain_loss_outfile_writer != null ) {
1825 writeDomainsToIndividualFilePerTreeNode( per_node_go_mapped_domain_gain_loss_outfile_writer,
1832 if ( per_node_go_mapped_domain_gain_loss_outfile_writer != null ) {
1833 per_node_go_mapped_domain_gain_loss_outfile_writer.close();
1834 if ( per_node_counter < 1 ) {
1835 per_node_go_mapped_domain_gain_loss_outfile.delete();
1837 per_node_counter = 0;
1839 out.write( "</table>" );
1840 out.write( SurfacingConstants.NL );
1841 out.write( "<hr>" );
1842 out.write( SurfacingConstants.NL );
1843 } // for( final String id : sorted_ids ) {
1844 out.write( "</body>" );
1845 out.write( SurfacingConstants.NL );
1846 out.write( "</html>" );
1847 out.write( SurfacingConstants.NL );
1851 catch ( final IOException e ) {
1852 ForesterUtil.fatalError( surfacing.PRG_NAME, e.getMessage() );
1854 ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote characters detailed HTML list: \"" + filename + "\"" );
1857 public static void writeDomainCombinationsCountsFile( final String[][] input_file_properties,
1858 final File output_dir,
1859 final Writer per_genome_domain_promiscuity_statistics_writer,
1860 final GenomeWideCombinableDomains gwcd,
1862 final GenomeWideCombinableDomains.GenomeWideCombinableDomainsSortOrder dc_sort_order ) {
1863 File dc_outfile = new File( input_file_properties[ i ][ 0 ]
1864 + surfacing.DOMAIN_COMBINITON_COUNTS_OUTPUTFILE_SUFFIX );
1865 if ( output_dir != null ) {
1866 dc_outfile = new File( output_dir + ForesterUtil.FILE_SEPARATOR + dc_outfile );
1868 checkForOutputFileWriteability( dc_outfile );
1870 final BufferedWriter out = new BufferedWriter( new FileWriter( dc_outfile ) );
1871 out.write( gwcd.toStringBuilder( dc_sort_order ).toString() );
1874 catch ( final IOException e ) {
1875 ForesterUtil.fatalError( surfacing.PRG_NAME, e.getMessage() );
1877 final DescriptiveStatistics stats = gwcd.getPerGenomeDomainPromiscuityStatistics();
1879 per_genome_domain_promiscuity_statistics_writer.write( input_file_properties[ i ][ 0 ] + "\t" );
1880 per_genome_domain_promiscuity_statistics_writer.write( FORMATTER_3.format( stats.arithmeticMean() ) + "\t" );
1881 if ( stats.getN() < 2 ) {
1882 per_genome_domain_promiscuity_statistics_writer.write( "n/a" + "\t" );
1885 per_genome_domain_promiscuity_statistics_writer.write( FORMATTER_3.format( stats
1886 .sampleStandardDeviation() ) + "\t" );
1888 per_genome_domain_promiscuity_statistics_writer.write( FORMATTER_3.format( stats.median() ) + "\t" );
1889 per_genome_domain_promiscuity_statistics_writer.write( ( int ) stats.getMin() + "\t" );
1890 per_genome_domain_promiscuity_statistics_writer.write( ( int ) stats.getMax() + "\t" );
1891 per_genome_domain_promiscuity_statistics_writer.write( stats.getN() + "\t" );
1892 final SortedSet<DomainId> mpds = gwcd.getMostPromiscuosDomain();
1893 for( final DomainId mpd : mpds ) {
1894 per_genome_domain_promiscuity_statistics_writer.write( mpd.getId() + " " );
1896 per_genome_domain_promiscuity_statistics_writer.write( ForesterUtil.LINE_SEPARATOR );
1898 catch ( final IOException e ) {
1899 ForesterUtil.fatalError( surfacing.PRG_NAME, e.getMessage() );
1901 if ( input_file_properties[ i ].length == 3 ) {
1902 ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote domain combination counts for \""
1903 + input_file_properties[ i ][ 0 ] + "\" (" + input_file_properties[ i ][ 1 ] + ", "
1904 + input_file_properties[ i ][ 2 ] + ") to: \"" + dc_outfile + "\"" );
1907 ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote domain combination counts for \""
1908 + input_file_properties[ i ][ 0 ] + "\" (" + input_file_properties[ i ][ 1 ] + ") to: \""
1909 + dc_outfile + "\"" );
1913 private static void writeDomainData( final Map<DomainId, List<GoId>> domain_id_to_go_ids_map,
1914 final Map<GoId, GoTerm> go_id_to_term_map,
1915 final GoNameSpace go_namespace_limit,
1917 final String domain_0,
1918 final String domain_1,
1919 final String prefix_for_html,
1920 final String character_separator_for_non_html_output,
1921 final Map<DomainId, Set<String>>[] domain_id_to_secondary_features_maps,
1922 final Set<GoId> all_go_ids ) throws IOException {
1923 boolean any_go_annotation_present = false;
1924 boolean first_has_no_go = false;
1925 int domain_count = 2; // To distinguish between domains and binary domain combinations.
1926 if ( ForesterUtil.isEmpty( domain_1 ) ) {
1929 // The following has a difficult to understand logic.
1930 for( int d = 0; d < domain_count; ++d ) {
1931 List<GoId> go_ids = null;
1932 boolean go_annotation_present = false;
1934 final DomainId domain_id = new DomainId( domain_0 );
1935 if ( domain_id_to_go_ids_map.containsKey( domain_id ) ) {
1936 go_annotation_present = true;
1937 any_go_annotation_present = true;
1938 go_ids = domain_id_to_go_ids_map.get( domain_id );
1941 first_has_no_go = true;
1945 final DomainId domain_id = new DomainId( domain_1 );
1946 if ( domain_id_to_go_ids_map.containsKey( domain_id ) ) {
1947 go_annotation_present = true;
1948 any_go_annotation_present = true;
1949 go_ids = domain_id_to_go_ids_map.get( domain_id );
1952 if ( go_annotation_present ) {
1953 boolean first = ( ( d == 0 ) || ( ( d == 1 ) && first_has_no_go ) );
1954 for( final GoId go_id : go_ids ) {
1955 out.write( "<tr>" );
1958 writeDomainIdsToHtml( out,
1962 domain_id_to_secondary_features_maps );
1965 out.write( "<td></td>" );
1967 if ( !go_id_to_term_map.containsKey( go_id ) ) {
1968 throw new IllegalArgumentException( "GO-id [" + go_id + "] not found in GO-id to GO-term map" );
1970 final GoTerm go_term = go_id_to_term_map.get( go_id );
1971 if ( ( go_namespace_limit == null ) || go_namespace_limit.equals( go_term.getGoNameSpace() ) ) {
1972 // final String top = GoUtils.getPenultimateGoTerm( go_term, go_id_to_term_map ).getName();
1973 final String go_id_str = go_id.getId();
1974 out.write( "<td>" );
1975 out.write( "<a href=\"" + SurfacingConstants.AMIGO_LINK + go_id_str
1976 + "\" target=\"amigo_window\">" + go_id_str + "</a>" );
1977 out.write( "</td><td>" );
1978 out.write( go_term.getName() );
1979 if ( domain_count == 2 ) {
1980 out.write( " (" + d + ")" );
1982 out.write( "</td><td>" );
1983 // out.write( top );
1984 // out.write( "</td><td>" );
1986 out.write( go_term.getGoNameSpace().toShortString() );
1988 out.write( "</td>" );
1989 if ( all_go_ids != null ) {
1990 all_go_ids.add( go_id );
1994 out.write( "<td>" );
1995 out.write( "</td><td>" );
1996 out.write( "</td><td>" );
1997 out.write( "</td><td>" );
1998 out.write( "</td>" );
2000 out.write( "</tr>" );
2001 out.write( SurfacingConstants.NL );
2004 } // for( int d = 0; d < domain_count; ++d )
2005 if ( !any_go_annotation_present ) {
2006 out.write( "<tr>" );
2007 writeDomainIdsToHtml( out, domain_0, domain_1, prefix_for_html, domain_id_to_secondary_features_maps );
2008 out.write( "<td>" );
2009 out.write( "</td><td>" );
2010 out.write( "</td><td>" );
2011 out.write( "</td><td>" );
2012 out.write( "</td>" );
2013 out.write( "</tr>" );
2014 out.write( SurfacingConstants.NL );
2018 private static void writeDomainIdsToHtml( final Writer out,
2019 final String domain_0,
2020 final String domain_1,
2021 final String prefix_for_detailed_html,
2022 final Map<DomainId, Set<String>>[] domain_id_to_secondary_features_maps )
2023 throws IOException {
2024 out.write( "<td>" );
2025 if ( !ForesterUtil.isEmpty( prefix_for_detailed_html ) ) {
2026 out.write( prefix_for_detailed_html );
2029 out.write( "<a href=\"" + SurfacingConstants.PFAM_FAMILY_ID_LINK + domain_0 + "\">" + domain_0 + "</a>" );
2030 out.write( "</td>" );
2033 public static DescriptiveStatistics writeDomainSimilaritiesToFile( final StringBuilder html_desc,
2034 final StringBuilder html_title,
2035 final Writer single_writer,
2036 Map<Character, Writer> split_writers,
2037 final SortedSet<DomainSimilarity> similarities,
2038 final boolean treat_as_binary,
2039 final List<Species> species_order,
2040 final PrintableDomainSimilarity.PRINT_OPTION print_option,
2041 final DomainSimilarity.DomainSimilaritySortField sort_field,
2042 final DomainSimilarity.DomainSimilarityScoring scoring,
2043 final boolean verbose ) throws IOException {
2044 final DescriptiveStatistics stats = new BasicDescriptiveStatistics();
2045 String histogram_title = null;
2046 switch ( sort_field ) {
2047 case ABS_MAX_COUNTS_DIFFERENCE:
2048 if ( treat_as_binary ) {
2049 histogram_title = "absolute counts difference:";
2052 histogram_title = "absolute (maximal) counts difference:";
2055 case MAX_COUNTS_DIFFERENCE:
2056 if ( treat_as_binary ) {
2057 histogram_title = "counts difference:";
2060 histogram_title = "(maximal) counts difference:";
2064 histogram_title = "score mean:";
2067 histogram_title = "score minimum:";
2070 histogram_title = "score maximum:";
2072 case MAX_DIFFERENCE:
2073 if ( treat_as_binary ) {
2074 histogram_title = "difference:";
2077 histogram_title = "(maximal) difference:";
2081 histogram_title = "score mean:";
2084 histogram_title = "score standard deviation:";
2087 histogram_title = "species number:";
2090 throw new AssertionError( "Unknown sort field: " + sort_field );
2092 for( final DomainSimilarity similarity : similarities ) {
2093 switch ( sort_field ) {
2094 case ABS_MAX_COUNTS_DIFFERENCE:
2095 stats.addValue( Math.abs( similarity.getMaximalDifferenceInCounts() ) );
2097 case MAX_COUNTS_DIFFERENCE:
2098 stats.addValue( similarity.getMaximalDifferenceInCounts() );
2101 stats.addValue( similarity.getMeanSimilarityScore() );
2104 stats.addValue( similarity.getMinimalSimilarityScore() );
2107 stats.addValue( similarity.getMaximalSimilarityScore() );
2109 case MAX_DIFFERENCE:
2110 stats.addValue( similarity.getMaximalDifference() );
2113 stats.addValue( similarity.getMeanSimilarityScore() );
2116 stats.addValue( similarity.getStandardDeviationOfSimilarityScore() );
2119 stats.addValue( similarity.getSpecies().size() );
2122 throw new AssertionError( "Unknown sort field: " + sort_field );
2126 // final HistogramData[] hists = new HistogramData[ 1 ];
2129 // List<HistogramDataItem> data_items = new
2130 // ArrayList<HistogramDataItem>();
2131 // double[] values = stats.getDataAsDoubleArray();
2132 // for( int i = 0; i < values.length; i++ ) {
2133 // HistogramDataItem data_item = new BasicHistogramDataItem( "", values[
2135 // data_items.add( data_item );
2139 // HistogramData hd0 = new HistogramData( "name",
2147 // hists[ 0 ] = hd0;
2149 // final HistogramsFrame hf = new HistogramsFrame( hists );
2150 // hf.setVisible( true );
2152 AsciiHistogram histo = null;
2153 if ( stats.getMin() < stats.getMin() ) {
2154 histo = new AsciiHistogram( stats, histogram_title );
2157 if ( histo != null ) {
2158 System.out.println( histo.toStringBuffer( 20, '|', 40, 5 ) );
2160 System.out.println();
2161 System.out.println( "N : " + stats.getN() );
2162 System.out.println( "Min : " + stats.getMin() );
2163 System.out.println( "Max : " + stats.getMax() );
2164 System.out.println( "Mean : " + stats.arithmeticMean() );
2165 if ( stats.getN() > 1 ) {
2166 System.out.println( "SD : " + stats.sampleStandardDeviation() );
2169 System.out.println( "SD : n/a" );
2171 System.out.println( "Median : " + stats.median() );
2172 if ( stats.getN() > 1 ) {
2173 System.out.println( "Pearsonian skewness : " + stats.pearsonianSkewness() );
2176 System.out.println( "Pearsonian skewness : n/a" );
2179 if ( ( single_writer != null ) && ( ( split_writers == null ) || split_writers.isEmpty() ) ) {
2180 split_writers = new HashMap<Character, Writer>();
2181 split_writers.put( '_', single_writer );
2183 switch ( print_option ) {
2184 case SIMPLE_TAB_DELIMITED:
2187 for( final Character key : split_writers.keySet() ) {
2188 final Writer w = split_writers.get( key );
2189 w.write( "<html>" );
2190 w.write( SurfacingConstants.NL );
2192 addHtmlHead( w, "DCs (" + html_title + ") " + key.toString().toUpperCase() );
2195 addHtmlHead( w, "DCs (" + html_title + ")" );
2197 w.write( SurfacingConstants.NL );
2198 w.write( "<body>" );
2199 w.write( SurfacingConstants.NL );
2200 w.write( html_desc.toString() );
2201 w.write( SurfacingConstants.NL );
2204 w.write( SurfacingConstants.NL );
2205 w.write( "<tt><pre>" );
2206 w.write( SurfacingConstants.NL );
2207 if ( histo != null ) {
2208 w.write( histo.toStringBuffer( 20, '|', 40, 5 ).toString() );
2209 w.write( SurfacingConstants.NL );
2211 w.write( "</pre></tt>" );
2212 w.write( SurfacingConstants.NL );
2213 w.write( "<table>" );
2214 w.write( SurfacingConstants.NL );
2215 w.write( "<tr><td>N: </td><td>" + stats.getN() + "</td></tr>" );
2216 w.write( SurfacingConstants.NL );
2217 w.write( "<tr><td>Min: </td><td>" + stats.getMin() + "</td></tr>" );
2218 w.write( SurfacingConstants.NL );
2219 w.write( "<tr><td>Max: </td><td>" + stats.getMax() + "</td></tr>" );
2220 w.write( SurfacingConstants.NL );
2221 w.write( "<tr><td>Mean: </td><td>" + stats.arithmeticMean() + "</td></tr>" );
2222 w.write( SurfacingConstants.NL );
2223 if ( stats.getN() > 1 ) {
2224 w.write( "<tr><td>SD: </td><td>" + stats.sampleStandardDeviation() + "</td></tr>" );
2227 w.write( "<tr><td>SD: </td><td>n/a</td></tr>" );
2229 w.write( SurfacingConstants.NL );
2230 w.write( "<tr><td>Median: </td><td>" + stats.median() + "</td></tr>" );
2231 w.write( SurfacingConstants.NL );
2232 if ( stats.getN() > 1 ) {
2233 w.write( "<tr><td>Pearsonian skewness: </td><td>" + stats.pearsonianSkewness() + "</td></tr>" );
2236 w.write( "<tr><td>Pearsonian skewness: </td><td>n/a</td></tr>" );
2238 w.write( SurfacingConstants.NL );
2239 w.write( "</table>" );
2240 w.write( SurfacingConstants.NL );
2242 w.write( SurfacingConstants.NL );
2244 w.write( SurfacingConstants.NL );
2246 w.write( SurfacingConstants.NL );
2247 w.write( "<table>" );
2248 w.write( SurfacingConstants.NL );
2252 for( final Writer w : split_writers.values() ) {
2253 w.write( SurfacingConstants.NL );
2255 for( final DomainSimilarity similarity : similarities ) {
2256 if ( ( species_order != null ) && !species_order.isEmpty() ) {
2257 ( ( PrintableDomainSimilarity ) similarity ).setSpeciesOrder( species_order );
2259 if ( single_writer != null ) {
2260 single_writer.write( similarity.toStringBuffer( print_option ).toString() );
2263 Writer local_writer = split_writers.get( ( similarity.getDomainId().getId().charAt( 0 ) + "" )
2264 .toLowerCase().charAt( 0 ) );
2265 if ( local_writer == null ) {
2266 local_writer = split_writers.get( '0' );
2268 local_writer.write( similarity.toStringBuffer( print_option ).toString() );
2270 for( final Writer w : split_writers.values() ) {
2271 w.write( SurfacingConstants.NL );
2274 switch ( print_option ) {
2276 for( final Writer w : split_writers.values() ) {
2277 w.write( SurfacingConstants.NL );
2278 w.write( "</table>" );
2279 w.write( SurfacingConstants.NL );
2280 w.write( "</font>" );
2281 w.write( SurfacingConstants.NL );
2282 w.write( "</body>" );
2283 w.write( SurfacingConstants.NL );
2284 w.write( "</html>" );
2285 w.write( SurfacingConstants.NL );
2289 for( final Writer w : split_writers.values() ) {
2295 private static void writeDomainsToIndividualFilePerTreeNode( final Writer individual_files_writer,
2296 final String domain_0,
2297 final String domain_1 ) throws IOException {
2298 individual_files_writer.write( domain_0 );
2299 individual_files_writer.write( ForesterUtil.LINE_SEPARATOR );
2300 if ( !ForesterUtil.isEmpty( domain_1 ) ) {
2301 individual_files_writer.write( domain_1 );
2302 individual_files_writer.write( ForesterUtil.LINE_SEPARATOR );
2306 public static void writeMatrixToFile( final CharacterStateMatrix<?> matrix,
2307 final String filename,
2308 final Format format ) {
2309 final File outfile = new File( filename );
2310 checkForOutputFileWriteability( outfile );
2312 final BufferedWriter out = new BufferedWriter( new FileWriter( outfile ) );
2313 matrix.toWriter( out, format );
2317 catch ( final IOException e ) {
2318 ForesterUtil.fatalError( surfacing.PRG_NAME, e.getMessage() );
2320 ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote matrix: \"" + filename + "\"" );
2323 public static void writeMatrixToFile( final File matrix_outfile, final List<DistanceMatrix> matrices ) {
2324 checkForOutputFileWriteability( matrix_outfile );
2326 final BufferedWriter out = new BufferedWriter( new FileWriter( matrix_outfile ) );
2327 for( final DistanceMatrix distance_matrix : matrices ) {
2328 out.write( distance_matrix.toStringBuffer( DistanceMatrix.Format.PHYLIP ).toString() );
2329 out.write( ForesterUtil.LINE_SEPARATOR );
2334 catch ( final IOException e ) {
2335 ForesterUtil.fatalError( surfacing.PRG_NAME, e.getMessage() );
2337 ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote distance matrices to \"" + matrix_outfile + "\"" );
2340 private static void writePfamsToFile( final String outfile_name, final SortedSet<String> pfams ) {
2342 final Writer writer = new BufferedWriter( new FileWriter( new File( outfile_name ) ) );
2343 for( final String pfam : pfams ) {
2344 writer.write( pfam );
2345 writer.write( ForesterUtil.LINE_SEPARATOR );
2348 ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote " + pfams.size() + " pfams to [" + outfile_name
2351 catch ( final IOException e ) {
2352 ForesterUtil.printWarningMessage( surfacing.PRG_NAME, "Failure to write: " + e );
2356 public static void writePhylogenyToFile( final Phylogeny phylogeny, final String filename ) {
2357 final PhylogenyWriter writer = new PhylogenyWriter();
2359 writer.toPhyloXML( new File( filename ), phylogeny, 1 );
2361 catch ( final IOException e ) {
2362 ForesterUtil.printWarningMessage( surfacing.PRG_NAME, "failed to write phylogeny to \"" + filename + "\": "
2365 ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote phylogeny to \"" + filename + "\"" );
2368 public static void writeTaxonomyLinks( final Writer writer, final String species ) throws IOException {
2369 if ( ( species.length() > 1 ) && ( species.indexOf( '_' ) < 1 ) ) {
2370 final Matcher matcher = PATTERN_SP_STYLE_TAXONOMY.matcher( species );
2371 writer.write( " [" );
2372 if ( matcher.matches() ) {
2373 writer.write( "<a href=\"" + SurfacingConstants.UNIPROT_LINK + species
2374 + "\" target=\"taxonomy_window\">uniprot</a>" );
2377 writer.write( "<a href=\"" + SurfacingConstants.EOL_LINK + species
2378 + "\" target=\"taxonomy_window\">eol</a>" );
2379 writer.write( "|" );
2380 writer.write( "<a href=\"" + SurfacingConstants.TOL_LINK + species
2381 + "\" target=\"taxonomy_window\">tol</a>" );
2383 writer.write( "]" );
2387 private static void writeToNexus( final String outfile_name,
2388 final CharacterStateMatrix<BinaryStates> matrix,
2389 final Phylogeny phylogeny ) {
2390 if ( !( matrix instanceof BasicCharacterStateMatrix ) ) {
2391 throw new IllegalArgumentException( "can only write matrices of type [" + BasicCharacterStateMatrix.class
2394 final BasicCharacterStateMatrix<BinaryStates> my_matrix = ( org.forester.evoinference.matrix.character.BasicCharacterStateMatrix<BinaryStates> ) matrix;
2395 final List<Phylogeny> phylogenies = new ArrayList<Phylogeny>( 1 );
2396 phylogenies.add( phylogeny );
2398 final BufferedWriter w = new BufferedWriter( new FileWriter( outfile_name ) );
2399 w.write( NexusConstants.NEXUS );
2400 w.write( ForesterUtil.LINE_SEPARATOR );
2401 my_matrix.writeNexusTaxaBlock( w );
2402 my_matrix.writeNexusBinaryChractersBlock( w );
2403 PhylogenyWriter.writeNexusTreesBlock( w, phylogenies, NH_CONVERSION_SUPPORT_VALUE_STYLE.NONE );
2406 ForesterUtil.programMessage( surfacing.PRG_NAME, "Wrote Nexus file: \"" + outfile_name + "\"" );
2408 catch ( final IOException e ) {
2409 ForesterUtil.fatalError( surfacing.PRG_NAME, e.getMessage() );
2413 private static void writeToNexus( final String outfile_name,
2414 final DomainParsimonyCalculator domain_parsimony,
2415 final Phylogeny phylogeny ) {
2416 writeToNexus( outfile_name + surfacing.NEXUS_EXTERNAL_DOMAINS,
2417 domain_parsimony.createMatrixOfDomainPresenceOrAbsence(),
2419 writeToNexus( outfile_name + surfacing.NEXUS_EXTERNAL_DOMAIN_COMBINATIONS,
2420 domain_parsimony.createMatrixOfBinaryDomainCombinationPresenceOrAbsence(),
2424 public static void domainsPerProteinsStatistics( final String genome,
2425 final List<Protein> protein_list,
2426 final DescriptiveStatistics all_genomes_domains_per_potein_stats,
2427 final SortedMap<Integer, Integer> all_genomes_domains_per_potein_histo,
2428 final SortedSet<String> domains_which_are_always_single,
2429 final SortedSet<String> domains_which_are_sometimes_single_sometimes_not,
2430 final SortedSet<String> domains_which_never_single,
2431 final Writer writer ) {
2432 final DescriptiveStatistics stats = new BasicDescriptiveStatistics();
2433 for( final Protein protein : protein_list ) {
2434 final int domains = protein.getNumberOfProteinDomains();
2435 //System.out.println( domains );
2436 stats.addValue( domains );
2437 all_genomes_domains_per_potein_stats.addValue( domains );
2438 if ( !all_genomes_domains_per_potein_histo.containsKey( domains ) ) {
2439 all_genomes_domains_per_potein_histo.put( domains, 1 );
2442 all_genomes_domains_per_potein_histo.put( domains,
2443 1 + all_genomes_domains_per_potein_histo.get( domains ) );
2445 if ( domains == 1 ) {
2446 final String domain = protein.getProteinDomain( 0 ).getDomainId().getId();
2447 if ( !domains_which_are_sometimes_single_sometimes_not.contains( domain ) ) {
2448 if ( domains_which_never_single.contains( domain ) ) {
2449 domains_which_never_single.remove( domain );
2450 domains_which_are_sometimes_single_sometimes_not.add( domain );
2453 domains_which_are_always_single.add( domain );
2457 else if ( domains > 1 ) {
2458 for( final Domain d : protein.getProteinDomains() ) {
2459 final String domain = d.getDomainId().getId();
2460 // System.out.println( domain );
2461 if ( !domains_which_are_sometimes_single_sometimes_not.contains( domain ) ) {
2462 if ( domains_which_are_always_single.contains( domain ) ) {
2463 domains_which_are_always_single.remove( domain );
2464 domains_which_are_sometimes_single_sometimes_not.add( domain );
2467 domains_which_never_single.add( domain );
2474 writer.write( genome );
2475 writer.write( "\t" );
2476 if ( stats.getN() >= 1 ) {
2477 writer.write( stats.arithmeticMean() + "" );
2478 writer.write( "\t" );
2479 if ( stats.getN() >= 2 ) {
2480 writer.write( stats.sampleStandardDeviation() + "" );
2485 writer.write( "\t" );
2486 writer.write( stats.median() + "" );
2487 writer.write( "\t" );
2488 writer.write( stats.getN() + "" );
2489 writer.write( "\t" );
2490 writer.write( stats.getMin() + "" );
2491 writer.write( "\t" );
2492 writer.write( stats.getMax() + "" );
2495 writer.write( "\t" );
2496 writer.write( "\t" );
2497 writer.write( "\t" );
2498 writer.write( "0" );
2499 writer.write( "\t" );
2500 writer.write( "\t" );
2502 writer.write( "\n" );
2504 catch ( final IOException e ) {
2505 e.printStackTrace();