2 package org.forester.msa_compactor;
5 import java.io.IOException;
7 import java.math.RoundingMode;
8 import java.text.DecimalFormat;
9 import java.text.NumberFormat;
10 import java.util.ArrayList;
11 import java.util.Arrays;
12 import java.util.List;
13 import java.util.SortedSet;
14 import java.util.TreeSet;
16 import org.forester.evoinference.distance.NeighborJoiningF;
17 import org.forester.evoinference.distance.PairwiseDistanceCalculator;
18 import org.forester.evoinference.distance.PairwiseDistanceCalculator.PWD_DISTANCE_METHOD;
19 import org.forester.evoinference.matrix.distance.BasicSymmetricalDistanceMatrix;
20 import org.forester.evoinference.tools.BootstrapResampler;
21 import org.forester.msa.BasicMsa;
22 import org.forester.msa.Mafft;
23 import org.forester.msa.Msa;
24 import org.forester.msa.Msa.MSA_FORMAT;
25 import org.forester.msa.MsaInferrer;
26 import org.forester.msa.MsaMethods;
27 import org.forester.msa.ResampleableMsa;
28 import org.forester.phylogeny.Phylogeny;
29 import org.forester.phylogeny.PhylogenyMethods;
30 import org.forester.sequence.Sequence;
31 import org.forester.tools.ConfidenceAssessor;
32 import org.forester.util.BasicDescriptiveStatistics;
33 import org.forester.util.DescriptiveStatistics;
34 import org.forester.util.ForesterUtil;
36 public class MsaCompactor {
38 final private static NumberFormat NF_3 = new DecimalFormat( "#.###" );
39 final private static NumberFormat NF_4 = new DecimalFormat( "#.####" );
40 private static final boolean VERBOSE = true;
42 private final SortedSet<String> _removed_seq_ids;
43 private String _path_to_mafft;
45 NF_4.setRoundingMode( RoundingMode.HALF_UP );
46 NF_3.setRoundingMode( RoundingMode.HALF_UP );
49 private MsaCompactor( final Msa msa ) {
51 _removed_seq_ids = new TreeSet<String>();
54 final public Msa getMsa() {
58 final public SortedSet<String> getRemovedSeqIds() {
59 return _removed_seq_ids;
62 final public void writeMsa( final File outfile, final MSA_FORMAT format, final String suffix ) throws IOException {
63 final Double gr = MsaMethods.calcGapRatio( _msa );
64 writeMsa( outfile + "_" + _msa.getNumberOfSequences() + "_" + _msa.getLength() + "_"
65 + ForesterUtil.roundToInt( gr * 100 ) + suffix,
69 final int calcNonGapResidues( final Sequence seq ) {
71 for( int i = 0; i < seq.getLength(); ++i ) {
72 if ( !seq.isGapAt( i ) ) {
79 private final GapContribution[] calcGapContribtions( final boolean normalize_for_effective_seq_length ) {
80 final double gappiness[] = calcGappiness();
81 final GapContribution stats[] = new GapContribution[ _msa.getNumberOfSequences() ];
82 for( int row = 0; row < _msa.getNumberOfSequences(); ++row ) {
83 stats[ row ] = new GapContribution( _msa.getIdentifier( row ) );
84 for( int col = 0; col < _msa.getLength(); ++col ) {
85 if ( !_msa.isGapAt( row, col ) ) {
86 stats[ row ].addToValue( gappiness[ col ] );
89 if ( normalize_for_effective_seq_length ) {
90 stats[ row ].divideValue( calcNonGapResidues( _msa.getSequence( row ) ) );
93 stats[ row ].divideValue( _msa.getLength() );
99 final private GapContribution[] calcGapContribtionsStats( final boolean norm ) {
100 final GapContribution stats[] = calcGapContribtions( norm );
101 Arrays.sort( stats );
102 // for( final GapContribution stat : stats ) {
103 // final StringBuilder sb = new StringBuilder();
104 // sb.append( stat.getId() );
105 // sb.append( "\t" );
106 // sb.append( NF_4.format( stat.getValue() ) );
107 // sb.append( "\t" );
108 // sb.append( NF_4.format( stat.median() ) );
109 // sb.append( "\t" );
110 // sb.append( NF_4.format( stat.getMin() ) );
111 // sb.append( "\t" );
112 // sb.append( NF_4.format( stat.getMax() ) );
114 //System.out.println( sb );
119 private static DescriptiveStatistics calculateIdentityRatio( final int from, final int to, final Msa msa ) {
120 final DescriptiveStatistics stats = new BasicDescriptiveStatistics();
121 for( int c = from; c <= to; ++c ) {
122 stats.addValue( MsaMethods.calculateIdentityRatio( msa, c ) );
127 private final double[] calcGappiness() {
128 final int l = _msa.getLength();
129 final double gappiness[] = new double[ l ];
130 final int seqs = _msa.getNumberOfSequences();
131 for( int i = 0; i < l; ++i ) {
132 gappiness[ i ] = ( double ) MsaMethods.calcGapSumPerColumn( _msa, i ) / seqs;
137 // Returns null if not path found.
138 final public static String guessPathToMafft() {
140 if ( ForesterUtil.OS_NAME.toLowerCase().indexOf( "win" ) >= 0 ) {
141 path = "C:\\Program Files\\mafft-win\\mafft.bat";
142 if ( MsaInferrer.isInstalled( path ) ) {
146 path = "/usr/local/bin/mafft";
147 if ( MsaInferrer.isInstalled( path ) ) {
150 path = "/usr/bin/mafft";
151 if ( MsaInferrer.isInstalled( path ) ) {
155 if ( MsaInferrer.isInstalled( path ) ) {
159 if ( MsaInferrer.isInstalled( path ) ) {
165 final private void mafft() throws IOException, InterruptedException {
166 // final MsaInferrer mafft = Mafft
167 // .createInstance( "/home/czmasek/SOFTWARE/MSA/MAFFT/mafft-7.130-without-extensions/scripts/mafft" );
168 final MsaInferrer mafft = Mafft.createInstance( _path_to_mafft );
169 final List<String> opts = new ArrayList<String>();
170 opts.add( "--maxiterate" );
172 opts.add( "--localpair" );
173 opts.add( "--quiet" );
174 _msa = mafft.infer( _msa.asSequenceList(), opts );
177 private StringBuilder msaStatsAsSB() {
178 final StringBuilder sb = new StringBuilder();
179 sb.append( _msa.getNumberOfSequences() );
181 sb.append( _msa.getLength() );
183 sb.append( NF_3.format( MsaMethods.calcGapRatio( _msa ) ) );
185 sb.append( NF_3.format( calculateIdentityRatio( 0, _msa.getLength() - 1, _msa ).arithmeticMean() ) );
189 final private void removeGapColumns() {
190 _msa = MsaMethods.createInstance().removeGapColumns( 1, 0, _msa );
193 final private void removeViaGapAverage( final double mean_gapiness,
195 final boolean realign,
197 final int minimal_effective_length ) throws IOException,
198 InterruptedException {
200 throw new IllegalArgumentException( "step cannot be less than 1" );
202 if ( mean_gapiness < 0 ) {
203 throw new IllegalArgumentException( "target average gap ratio cannot be less than 0" );
206 System.out.println( "orig: " + msaStatsAsSB() );
208 if ( minimal_effective_length > 1 ) {
209 _msa = MsaMethods.removeSequencesByMinimalLength( _msa, minimal_effective_length );
211 System.out.println( "short seq removal: " + msaStatsAsSB() );
217 removeWorstOffenders( step, 1, false, false );
221 gr = MsaMethods.calcGapRatio( _msa );
223 System.out.println( counter + ": " + msaStatsAsSB() );
225 // write( outfile, gr );
227 } while ( gr > mean_gapiness );
229 System.out.println( "final: " + msaStatsAsSB() );
233 final private void removeViaLength( final int length, final int step, final boolean realign ) throws IOException,
234 InterruptedException {
236 throw new IllegalArgumentException( "step cannot be less than 1" );
239 throw new IllegalArgumentException( "target length cannot be less than 1" );
242 System.out.println( "orig: " + msaStatsAsSB() );
245 while ( _msa.getLength() > length ) {
246 removeWorstOffenders( step, 1, false, false );
251 System.out.println( counter + ": " + msaStatsAsSB() );
257 Phylogeny pi( final String matrix ) {
258 final Phylogeny master_phy = inferNJphylogeny( PWD_DISTANCE_METHOD.KIMURA_DISTANCE, _msa, true, matrix );
261 final ResampleableMsa resampleable_msa = new ResampleableMsa( ( BasicMsa ) _msa );
262 final int[][] resampled_column_positions = BootstrapResampler.createResampledColumnPositions( _msa.getLength(),
265 final Phylogeny[] eval_phys = new Phylogeny[ n ];
266 for( int i = 0; i < n; ++i ) {
267 resampleable_msa.resample( resampled_column_positions[ i ] );
268 eval_phys[ i ] = inferNJphylogeny( PWD_DISTANCE_METHOD.KIMURA_DISTANCE, resampleable_msa, false, null );
270 ConfidenceAssessor.evaluate( "bootstrap", eval_phys, master_phy, true, 1 );
271 PhylogenyMethods.extractFastaInformation( master_phy );
275 private Phylogeny inferNJphylogeny( final PWD_DISTANCE_METHOD pwd_distance_method,
277 final boolean write_matrix,
278 final String matrix_name ) {
279 BasicSymmetricalDistanceMatrix m = null;
280 switch ( pwd_distance_method ) {
281 case KIMURA_DISTANCE:
282 m = PairwiseDistanceCalculator.calcKimuraDistances( msa );
284 case POISSON_DISTANCE:
285 m = PairwiseDistanceCalculator.calcPoissonDistances( msa );
287 case FRACTIONAL_DISSIMILARITY:
288 m = PairwiseDistanceCalculator.calcFractionalDissimilarities( msa );
291 throw new IllegalArgumentException( "invalid pwd method" );
293 if ( write_matrix ) {
295 m.write( ForesterUtil.createBufferedWriter( matrix_name ) );
297 catch ( final IOException e ) {
298 // TODO Auto-generated catch block
302 final NeighborJoiningF nj = NeighborJoiningF.createInstance( false, 5 );
303 final Phylogeny phy = nj.execute( m );
307 final private void removeWorstOffenders( final int to_remove,
309 final boolean realign,
310 final boolean norm ) throws IOException, InterruptedException {
311 //final Phylogeny a = pi( "a.pwd" );
312 //Archaeopteryx.createApplication( a );
313 final GapContribution stats[] = calcGapContribtionsStats( norm );
314 final List<String> to_remove_ids = new ArrayList<String>();
315 for( int j = 0; j < to_remove; ++j ) {
316 to_remove_ids.add( stats[ j ].getId() );
317 _removed_seq_ids.add( stats[ j ].getId() );
319 //TODO if verbose/interactive
320 for( final String id : to_remove_ids ) {
321 _msa = MsaMethods.removeSequence( _msa, id );
323 //System.out.print( id );
324 System.out.print( ForesterUtil.pad( id, 20, ' ', false ) );
325 System.out.print( "\t" );
326 final StringBuilder sb = msaStatsAsSB();
327 System.out.println( sb );
330 //_msa = MsaMethods.removeSequences( _msa, to_remove_ids );
331 //removeGapColumns();
335 //final Phylogeny b = pi( "b.pwd" );
336 //Archaeopteryx.createApplication( b );
339 final private void writeMsa( final String outfile, final MSA_FORMAT format ) throws IOException {
340 final Writer w = ForesterUtil.createBufferedWriter( outfile );
341 _msa.write( w, format );
345 public final static MsaCompactor reduceGapAverage( final Msa msa,
346 final double max_gap_average,
348 final boolean realign,
350 final int minimal_effective_length,
351 final String path_to_mafft ) throws IOException,
352 InterruptedException {
353 final MsaCompactor mc = new MsaCompactor( msa );
355 mc.setPathToMafft( path_to_mafft );
357 mc.removeViaGapAverage( max_gap_average, step, realign, out, minimal_effective_length );
361 public final static MsaCompactor reduceLength( final Msa msa,
364 final boolean realign,
365 final String path_to_mafft ) throws IOException,
366 InterruptedException {
367 final MsaCompactor mc = new MsaCompactor( msa );
369 mc.setPathToMafft( path_to_mafft );
371 mc.removeViaLength( length, step, realign );
375 public final static MsaCompactor removeWorstOffenders( final Msa msa,
376 final int worst_offenders_to_remove,
377 final boolean realign,
379 final String path_to_mafft ) throws IOException,
380 InterruptedException {
381 final MsaCompactor mc = new MsaCompactor( msa );
383 mc.setPathToMafft( path_to_mafft );
385 mc.removeWorstOffenders( worst_offenders_to_remove, 1, realign, norm );
389 private void setPathToMafft( final String path_to_mafft ) {
390 _path_to_mafft = path_to_mafft;