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.archaeopteryx.Archaeopteryx;
17 import org.forester.evoinference.distance.NeighborJoiningF;
18 import org.forester.evoinference.distance.PairwiseDistanceCalculator;
19 import org.forester.evoinference.distance.PairwiseDistanceCalculator.PWD_DISTANCE_METHOD;
20 import org.forester.evoinference.matrix.distance.BasicSymmetricalDistanceMatrix;
21 import org.forester.evoinference.tools.BootstrapResampler;
22 import org.forester.msa.BasicMsa;
23 import org.forester.msa.Mafft;
24 import org.forester.msa.Msa;
25 import org.forester.msa.Msa.MSA_FORMAT;
26 import org.forester.msa.MsaInferrer;
27 import org.forester.msa.MsaMethods;
28 import org.forester.msa.ResampleableMsa;
29 import org.forester.phylogeny.Phylogeny;
30 import org.forester.phylogeny.PhylogenyMethods;
31 import org.forester.sequence.Sequence;
32 import org.forester.tools.ConfidenceAssessor;
33 import org.forester.util.ForesterUtil;
35 public class MsaCompactor {
37 final private static NumberFormat NF_3 = new DecimalFormat( "#.###" );
38 final private static NumberFormat NF_4 = new DecimalFormat( "#.####" );
39 private static final boolean VERBOSE = true;
41 private final SortedSet<String> _removed_seq_ids;
43 NF_4.setRoundingMode( RoundingMode.HALF_UP );
44 NF_3.setRoundingMode( RoundingMode.HALF_UP );
47 private MsaCompactor( final Msa msa ) {
49 _removed_seq_ids = new TreeSet<String>();
52 final public Msa getMsa() {
56 final public SortedSet<String> getRemovedSeqIds() {
57 return _removed_seq_ids;
60 final public void writeMsa( final File outfile, final MSA_FORMAT format, final String suffix ) throws IOException {
61 final Double gr = MsaMethods.calcGapRatio( _msa );
62 writeMsa( outfile + "_" + _msa.getNumberOfSequences() + "_" + _msa.getLength() + "_"
63 + ForesterUtil.roundToInt( gr * 100 ) + suffix,
67 final int calcNonGapResidues( final Sequence seq ) {
69 for( int i = 0; i < seq.getLength(); ++i ) {
70 if ( !seq.isGapAt( i ) ) {
77 private final GapContribution[] calcGapContribtions( final boolean normalize_for_effective_seq_length ) {
78 final double gappiness[] = calcGappiness();
79 final GapContribution stats[] = new GapContribution[ _msa.getNumberOfSequences() ];
80 for( int row = 0; row < _msa.getNumberOfSequences(); ++row ) {
81 stats[ row ] = new GapContribution( _msa.getIdentifier( row ) );
82 for( int col = 0; col < _msa.getLength(); ++col ) {
83 if ( !_msa.isGapAt( row, col ) ) {
84 stats[ row ].addToValue( gappiness[ col ] );
87 if ( normalize_for_effective_seq_length ) {
88 stats[ row ].divideValue( calcNonGapResidues( _msa.getSequence( row ) ) );
91 stats[ row ].divideValue( _msa.getLength() );
97 final private GapContribution[] calcGapContribtionsStats( final boolean norm ) {
98 final GapContribution stats[] = calcGapContribtions( norm );
100 for( final GapContribution stat : stats ) {
101 final StringBuilder sb = new StringBuilder();
102 sb.append( stat.getId() );
104 sb.append( NF_4.format( stat.getValue() ) );
106 // sb.append( NF_4.format( stat.median() ) );
107 // sb.append( "\t" );
108 // sb.append( NF_4.format( stat.getMin() ) );
109 // sb.append( "\t" );
110 // sb.append( NF_4.format( stat.getMax() ) );
112 System.out.println( sb );
117 private final double[] calcGappiness() {
118 final int l = _msa.getLength();
119 final double gappiness[] = new double[ l ];
120 final int seqs = _msa.getNumberOfSequences();
121 for( int i = 0; i < l; ++i ) {
122 gappiness[ i ] = ( double ) MsaMethods.calcGapSumPerColumn( _msa, i ) / seqs;
127 final private void mafft() throws IOException, InterruptedException {
128 final MsaInferrer mafft = Mafft
129 .createInstance( "/home/czmasek/SOFTWARE/MSA/MAFFT/mafft-7.130-without-extensions/scripts/mafft" );
130 final List<String> opts = new ArrayList<String>();
131 opts.add( "--maxiterate" );
133 opts.add( "--localpair" );
134 opts.add( "--quiet" );
135 _msa = mafft.infer( _msa.asSequenceList(), opts );
138 private StringBuilder msaStatsAsSB() {
139 final StringBuilder sb = new StringBuilder();
140 sb.append( _msa.getNumberOfSequences() );
142 sb.append( _msa.getLength() );
144 sb.append( NF_3.format( MsaMethods.calcGapRatio( _msa ) ) );
148 final private void removeGapColumns() {
149 _msa = MsaMethods.createInstance().removeGapColumns( 1, 0, _msa );
152 final private void removeViaGapAverage( final double mean_gapiness,
154 final boolean realign,
156 final int minimal_effective_length ) throws IOException,
157 InterruptedException {
159 throw new IllegalArgumentException( "step cannot be less than 1" );
161 if ( mean_gapiness < 0 ) {
162 throw new IllegalArgumentException( "target average gap ratio cannot be less than 0" );
165 System.out.println( "orig: " + msaStatsAsSB() );
167 if ( minimal_effective_length > 1 ) {
168 _msa = MsaMethods.removeSequencesByMinimalLength( _msa, minimal_effective_length );
170 System.out.println( "short seq removal: " + msaStatsAsSB() );
176 removeWorstOffenders( step, 1, false, false );
180 gr = MsaMethods.calcGapRatio( _msa );
182 System.out.println( counter + ": " + msaStatsAsSB() );
184 // write( outfile, gr );
186 } while ( gr > mean_gapiness );
188 System.out.println( "final: " + msaStatsAsSB() );
192 final private void removeViaLength( final int length, final int step, final boolean realign ) throws IOException,
193 InterruptedException {
195 throw new IllegalArgumentException( "step cannot be less than 1" );
198 throw new IllegalArgumentException( "target length cannot be less than 1" );
201 System.out.println( "orig: " + msaStatsAsSB() );
204 while ( _msa.getLength() > length ) {
205 removeWorstOffenders( step, 1, false, false );
210 System.out.println( counter + ": " + msaStatsAsSB() );
216 Phylogeny pi( final String matrix ) {
217 final Phylogeny master_phy = inferNJphylogeny( PWD_DISTANCE_METHOD.KIMURA_DISTANCE, _msa, true, matrix );
220 final ResampleableMsa resampleable_msa = new ResampleableMsa( ( BasicMsa ) _msa );
221 final int[][] resampled_column_positions = BootstrapResampler.createResampledColumnPositions( _msa.getLength(),
224 final Phylogeny[] eval_phys = new Phylogeny[ n ];
225 for( int i = 0; i < n; ++i ) {
226 resampleable_msa.resample( resampled_column_positions[ i ] );
227 eval_phys[ i ] = inferNJphylogeny( PWD_DISTANCE_METHOD.KIMURA_DISTANCE, resampleable_msa, false, null );
229 ConfidenceAssessor.evaluate( "bootstrap", eval_phys, master_phy, true, 1 );
230 PhylogenyMethods.extractFastaInformation( master_phy );
234 private Phylogeny inferNJphylogeny( final PWD_DISTANCE_METHOD pwd_distance_method,
236 final boolean write_matrix,
237 final String matrix_name ) {
238 BasicSymmetricalDistanceMatrix m = null;
239 switch ( pwd_distance_method ) {
240 case KIMURA_DISTANCE:
241 m = PairwiseDistanceCalculator.calcKimuraDistances( msa );
243 case POISSON_DISTANCE:
244 m = PairwiseDistanceCalculator.calcPoissonDistances( msa );
246 case FRACTIONAL_DISSIMILARITY:
247 m = PairwiseDistanceCalculator.calcFractionalDissimilarities( msa );
250 throw new IllegalArgumentException( "invalid pwd method" );
252 if ( write_matrix ) {
254 m.write( ForesterUtil.createBufferedWriter( matrix_name ) );
256 catch ( final IOException e ) {
257 // TODO Auto-generated catch block
261 final NeighborJoiningF nj = NeighborJoiningF.createInstance( false, 5 );
262 final Phylogeny phy = nj.execute( m );
266 final private void removeWorstOffenders( final int to_remove,
268 final boolean realign,
269 final boolean norm ) throws IOException, InterruptedException {
270 final Phylogeny a = pi( "a.pwd" );
271 Archaeopteryx.createApplication( a );
272 final GapContribution stats[] = calcGapContribtionsStats( norm );
273 final List<String> to_remove_ids = new ArrayList<String>();
274 for( int j = 0; j < to_remove; ++j ) {
275 to_remove_ids.add( stats[ j ].getId() );
276 _removed_seq_ids.add( stats[ j ].getId() );
278 //TODO if verbose/interactve
279 for( final String id : to_remove_ids ) {
280 _msa = MsaMethods.removeSequence( _msa, id );
282 System.out.print( id );
283 System.out.print( "\t" );
284 final StringBuilder sb = msaStatsAsSB();
285 System.out.println( sb );
288 //_msa = MsaMethods.removeSequences( _msa, to_remove_ids );
289 //removeGapColumns();
293 final Phylogeny b = pi( "b.pwd" );
294 Archaeopteryx.createApplication( b );
297 final private void writeMsa( final String outfile, final MSA_FORMAT format ) throws IOException {
298 final Writer w = ForesterUtil.createBufferedWriter( outfile );
299 _msa.write( w, format );
303 public final static MsaCompactor reduceGapAverage( final Msa msa,
304 final double max_gap_average,
306 final boolean realign,
308 final int minimal_effective_length ) throws IOException,
309 InterruptedException {
310 final MsaCompactor mc = new MsaCompactor( msa );
311 mc.removeViaGapAverage( max_gap_average, step, realign, out, minimal_effective_length );
315 public final static MsaCompactor reduceLength( final Msa msa,
318 final boolean realign ) throws IOException, InterruptedException {
319 final MsaCompactor mc = new MsaCompactor( msa );
320 mc.removeViaLength( length, step, realign );
324 public final static MsaCompactor removeWorstOffenders( final Msa msa,
325 final int worst_offenders_to_remove,
326 final boolean realign,
327 final boolean norm ) throws IOException,
328 InterruptedException {
329 final MsaCompactor mc = new MsaCompactor( msa );
330 mc.removeWorstOffenders( worst_offenders_to_remove, 1, realign, norm );