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 final String _maffts_opts = "--retree 1";
42 private File _out_file_base;
43 private String _path_to_mafft;
44 private final SortedSet<String> _removed_seq_ids;
46 NF_4.setRoundingMode( RoundingMode.HALF_UP );
47 NF_3.setRoundingMode( RoundingMode.HALF_UP );
50 private MsaCompactor( final Msa msa ) {
52 _removed_seq_ids = new TreeSet<String>();
55 final public Msa getMsa() {
59 final public SortedSet<String> getRemovedSeqIds() {
60 return _removed_seq_ids;
63 final public void setOutFileBase( final File out_file_base ) {
64 _out_file_base = out_file_base;
67 final public String writeMsa( final File outfile, final MSA_FORMAT format, final String suffix ) throws IOException {
68 final Double gr = MsaMethods.calcGapRatio( _msa );
69 final String s = outfile + "_" + _msa.getNumberOfSequences() + "_" + _msa.getLength() + "_"
70 + ForesterUtil.roundToInt( gr * 100 );
71 writeMsa( s + suffix, format );
75 final int calcNonGapResidues( final Sequence seq ) {
77 for( int i = 0; i < seq.getLength(); ++i ) {
78 if ( !seq.isGapAt( i ) ) {
85 Phylogeny pi( final String matrix ) {
86 final Phylogeny master_phy = inferNJphylogeny( PWD_DISTANCE_METHOD.KIMURA_DISTANCE, _msa, true, matrix );
89 final ResampleableMsa resampleable_msa = new ResampleableMsa( ( BasicMsa ) _msa );
90 final int[][] resampled_column_positions = BootstrapResampler.createResampledColumnPositions( _msa.getLength(),
93 final Phylogeny[] eval_phys = new Phylogeny[ n ];
94 for( int i = 0; i < n; ++i ) {
95 resampleable_msa.resample( resampled_column_positions[ i ] );
96 eval_phys[ i ] = inferNJphylogeny( PWD_DISTANCE_METHOD.KIMURA_DISTANCE, resampleable_msa, false, null );
98 ConfidenceAssessor.evaluate( "bootstrap", eval_phys, master_phy, true, 1 );
99 PhylogenyMethods.extractFastaInformation( master_phy );
103 private final GapContribution[] calcGapContribtions( final boolean normalize_for_effective_seq_length ) {
104 final double gappiness[] = calcGappiness();
105 final GapContribution stats[] = new GapContribution[ _msa.getNumberOfSequences() ];
106 for( int row = 0; row < _msa.getNumberOfSequences(); ++row ) {
107 stats[ row ] = new GapContribution( _msa.getIdentifier( row ) );
108 for( int col = 0; col < _msa.getLength(); ++col ) {
109 if ( !_msa.isGapAt( row, col ) ) {
110 stats[ row ].addToValue( gappiness[ col ] );
113 if ( normalize_for_effective_seq_length ) {
114 stats[ row ].divideValue( calcNonGapResidues( _msa.getSequence( row ) ) );
117 stats[ row ].divideValue( _msa.getLength() );
123 final private GapContribution[] calcGapContribtionsStats( final boolean norm ) {
124 final GapContribution stats[] = calcGapContribtions( norm );
125 Arrays.sort( stats );
129 private final double[] calcGappiness() {
130 final int l = _msa.getLength();
131 final double gappiness[] = new double[ l ];
132 final int seqs = _msa.getNumberOfSequences();
133 for( int i = 0; i < l; ++i ) {
134 gappiness[ i ] = ( double ) MsaMethods.calcGapSumPerColumn( _msa, i ) / seqs;
139 private Phylogeny inferNJphylogeny( final PWD_DISTANCE_METHOD pwd_distance_method,
141 final boolean write_matrix,
142 final String matrix_name ) {
143 BasicSymmetricalDistanceMatrix m = null;
144 switch ( pwd_distance_method ) {
145 case KIMURA_DISTANCE:
146 m = PairwiseDistanceCalculator.calcKimuraDistances( msa );
148 case POISSON_DISTANCE:
149 m = PairwiseDistanceCalculator.calcPoissonDistances( msa );
151 case FRACTIONAL_DISSIMILARITY:
152 m = PairwiseDistanceCalculator.calcFractionalDissimilarities( msa );
155 throw new IllegalArgumentException( "invalid pwd method" );
157 if ( write_matrix ) {
159 m.write( ForesterUtil.createBufferedWriter( matrix_name ) );
161 catch ( final IOException e ) {
165 final NeighborJoiningF nj = NeighborJoiningF.createInstance( false, 5 );
166 final Phylogeny phy = nj.execute( m );
170 private StringBuilder msaStatsAsSB() {
171 final StringBuilder sb = new StringBuilder();
172 sb.append( _msa.getNumberOfSequences() );
174 sb.append( _msa.getLength() );
176 sb.append( NF_4.format( MsaMethods.calcGapRatio( _msa ) ) );
178 sb.append( NF_4.format( calculateIdentityRatio( 0, _msa.getLength() - 1, _msa ).arithmeticMean() ) );
182 private final void printMsaStats( final String id ) {
183 System.out.print( ForesterUtil.pad( id, 20, ' ', false ) );
184 System.out.print( "\t" );
185 final StringBuilder sb = msaStatsAsSB();
186 System.out.print( sb );
187 System.out.print( "\t" );
190 final private void realignWithMafft() throws IOException, InterruptedException {
191 // final MsaInferrer mafft = Mafft
192 // .createInstance( "/home/czmasek/SOFTWARE/MSA/MAFFT/mafft-7.130-without-extensions/scripts/mafft" );
193 final MsaInferrer mafft = Mafft.createInstance( _path_to_mafft );
194 final List<String> opts = new ArrayList<String>();
195 for( final String o : _maffts_opts.split( "\\s" ) ) {
198 //opts.add( "--maxiterate" );
199 //opts.add( "1000" );
200 //opts.add( "--localpair" );
201 //opts.add( "--quiet" );
202 _msa = mafft.infer( _msa.asSequenceList(), opts );
205 final private void removeGapColumns() {
206 _msa = MsaMethods.createInstance().removeGapColumns( 1, 0, _msa );
209 final private void removeViaGapAverage( final double mean_gapiness,
211 final boolean realign,
213 final boolean verbose ) throws IOException, InterruptedException {
214 final GapContribution stats[] = calcGapContribtionsStats( norm );
215 final List<String> to_remove_ids = new ArrayList<String>();
216 for( final GapContribution gap_gontribution : stats ) {
217 to_remove_ids.add( gap_gontribution.getId() );
223 while ( MsaMethods.calcGapRatio( _msa ) > mean_gapiness ) {
224 final String id = to_remove_ids.get( i );
225 _msa = MsaMethods.removeSequence( _msa, id );
230 if ( ( ( step > 0 ) && ( ( ( i + 1 ) % step ) == 0 ) )
231 || ( MsaMethods.calcGapRatio( _msa ) <= mean_gapiness ) ) {
235 final String s = writeOutfile();
237 System.out.print( "-> " + s );
241 System.out.println();
247 final private void removeViaLength( final int length,
249 final boolean realign,
251 final boolean verbose ) throws IOException, InterruptedException {
252 final GapContribution stats[] = calcGapContribtionsStats( norm );
253 final List<String> to_remove_ids = new ArrayList<String>();
254 for( final GapContribution gap_gontribution : stats ) {
255 to_remove_ids.add( gap_gontribution.getId() );
261 while ( _msa.getLength() > length ) {
262 final String id = to_remove_ids.get( i );
263 _msa = MsaMethods.removeSequence( _msa, id );
268 if ( ( ( step > 0 ) && ( ( ( i + 1 ) % step ) == 0 ) ) || ( _msa.getLength() <= length ) ) {
272 final String s = writeOutfile();
274 System.out.print( "-> " + s );
278 System.out.println();
284 final private void removeWorstOffenders( final int to_remove,
286 final boolean realign,
288 final boolean verbose ) throws IOException, InterruptedException {
289 final GapContribution stats[] = calcGapContribtionsStats( norm );
290 final List<String> to_remove_ids = new ArrayList<String>();
291 for( int j = 0; j < to_remove; ++j ) {
292 to_remove_ids.add( stats[ j ].getId() );
293 _removed_seq_ids.add( stats[ j ].getId() );
298 for( int i = 0; i < to_remove_ids.size(); ++i ) {
299 final String id = to_remove_ids.get( i );
300 _msa = MsaMethods.removeSequence( _msa, id );
305 if ( ( ( step > 0 ) && ( ( ( i + 1 ) % step ) == 0 ) ) || ( i == ( to_remove_ids.size() - 1 ) ) ) {
309 final String s = writeOutfile();
311 System.out.print( "-> " + s );
315 System.out.println();
320 private void setPathToMafft( final String path_to_mafft ) {
321 _path_to_mafft = path_to_mafft;
324 final private void writeMsa( final String outfile, final MSA_FORMAT format ) throws IOException {
325 final Writer w = ForesterUtil.createBufferedWriter( outfile );
326 _msa.write( w, format );
330 private String writeOutfile() throws IOException {
331 final String s = writeMsa( _out_file_base, MSA_FORMAT.PHYLIP, ".aln" );
332 //writeMsa( _out_file_base, MSA_FORMAT.FASTA, ".fasta" );
336 // Returns null if not path found.
337 final public static String guessPathToMafft() {
339 if ( ForesterUtil.OS_NAME.toLowerCase().indexOf( "win" ) >= 0 ) {
340 path = "C:\\Program Files\\mafft-win\\mafft.bat";
341 if ( MsaInferrer.isInstalled( path ) ) {
345 path = "/home/czmasek/SOFTWARE/MSA/MAFFT/mafft-7.130-without-extensions/scripts/mafft";
346 if ( MsaInferrer.isInstalled( path ) ) {
349 path = "/usr/local/bin/mafft";
350 if ( MsaInferrer.isInstalled( path ) ) {
353 path = "/usr/bin/mafft";
354 if ( MsaInferrer.isInstalled( path ) ) {
358 if ( MsaInferrer.isInstalled( path ) ) {
362 if ( MsaInferrer.isInstalled( path ) ) {
368 public final static MsaCompactor reduceGapAverage( final Msa msa,
369 final double max_gap_average,
371 final boolean realign,
373 final String path_to_mafft,
374 final File out ) throws IOException, InterruptedException {
375 final MsaCompactor mc = new MsaCompactor( msa );
377 mc.setPathToMafft( path_to_mafft );
379 mc.setOutFileBase( out );
380 mc.removeViaGapAverage( max_gap_average, step, realign, norm, true );
384 public final static MsaCompactor reduceLength( final Msa msa,
387 final boolean realign,
389 final String path_to_mafft,
390 final File out ) throws IOException, InterruptedException {
391 final MsaCompactor mc = new MsaCompactor( msa );
393 mc.setPathToMafft( path_to_mafft );
395 mc.setOutFileBase( out );
396 mc.removeViaLength( length, step, realign, norm, true );
400 public final static MsaCompactor removeWorstOffenders( final Msa msa,
401 final int worst_offenders_to_remove,
403 final boolean realign,
405 final String path_to_mafft,
406 final File out ) throws IOException, InterruptedException {
407 final MsaCompactor mc = new MsaCompactor( msa );
409 mc.setPathToMafft( path_to_mafft );
411 mc.setOutFileBase( out );
412 mc.removeWorstOffenders( worst_offenders_to_remove, step, realign, norm, true );
416 private static DescriptiveStatistics calculateIdentityRatio( final int from, final int to, final Msa msa ) {
417 final DescriptiveStatistics stats = new BasicDescriptiveStatistics();
418 for( int c = from; c <= to; ++c ) {
419 stats.addValue( MsaMethods.calculateIdentityRatio( msa, c ) );
424 private final static void printTableHeader() {
425 System.out.print( ForesterUtil.pad( "Id", 20, ' ', false ) );
426 System.out.print( "\t" );
427 System.out.print( "Seqs" );
428 System.out.print( "\t" );
429 System.out.print( "Length" );
430 System.out.print( "\t" );
431 System.out.print( "Gaps" );
432 System.out.print( "\t" );
433 System.out.print( "MSA qual" );
434 System.out.print( "\t" );
435 System.out.println();