inprogress
[jalview.git] / forester / java / src / org / forester / msa_compactor / MsaCompactor.java
1
2 package org.forester.msa_compactor;
3
4 import java.io.File;
5 import java.io.IOException;
6 import java.io.Writer;
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;
15
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;
35
36 public class MsaCompactor {
37
38     final private static NumberFormat NF_3         = new DecimalFormat( "#.###" );
39     final private static NumberFormat NF_4         = new DecimalFormat( "#.####" );
40     private Msa                       _msa;
41     private File                      _out_file_base;
42     private String                    _path_to_mafft;
43     private final SortedSet<String>   _removed_seq_ids;
44     private final String              _maffts_opts = "--retree 1";
45     static {
46         NF_4.setRoundingMode( RoundingMode.HALF_UP );
47         NF_3.setRoundingMode( RoundingMode.HALF_UP );
48     }
49
50     private MsaCompactor( final Msa msa ) {
51         _msa = msa;
52         _removed_seq_ids = new TreeSet<String>();
53     }
54
55     final public Msa getMsa() {
56         return _msa;
57     }
58
59     final public SortedSet<String> getRemovedSeqIds() {
60         return _removed_seq_ids;
61     }
62
63     final public void setOutFileBase( final File out_file_base ) {
64         _out_file_base = out_file_base;
65     }
66
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 );
72         return s;
73     }
74
75     final int calcNonGapResidues( final Sequence seq ) {
76         int ng = 0;
77         for( int i = 0; i < seq.getLength(); ++i ) {
78             if ( !seq.isGapAt( i ) ) {
79                 ++ng;
80             }
81         }
82         return ng;
83     }
84
85     Phylogeny pi( final String matrix ) {
86         final Phylogeny master_phy = inferNJphylogeny( PWD_DISTANCE_METHOD.KIMURA_DISTANCE, _msa, true, matrix );
87         final int seed = 15;
88         final int n = 100;
89         final ResampleableMsa resampleable_msa = new ResampleableMsa( ( BasicMsa ) _msa );
90         final int[][] resampled_column_positions = BootstrapResampler.createResampledColumnPositions( _msa.getLength(),
91                                                                                                       n,
92                                                                                                       seed );
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 );
97         }
98         ConfidenceAssessor.evaluate( "bootstrap", eval_phys, master_phy, true, 1 );
99         PhylogenyMethods.extractFastaInformation( master_phy );
100         return master_phy;
101     }
102
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 ] );
111                 }
112             }
113             if ( normalize_for_effective_seq_length ) {
114                 stats[ row ].divideValue( calcNonGapResidues( _msa.getSequence( row ) ) );
115             }
116             else {
117                 stats[ row ].divideValue( _msa.getLength() );
118             }
119         }
120         return stats;
121     }
122
123     final private GapContribution[] calcGapContribtionsStats( final boolean norm ) {
124         final GapContribution stats[] = calcGapContribtions( norm );
125         Arrays.sort( stats );
126         return stats;
127     }
128
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;
135         }
136         return gappiness;
137     }
138
139     private Phylogeny inferNJphylogeny( final PWD_DISTANCE_METHOD pwd_distance_method,
140                                         final Msa msa,
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 );
147                 break;
148             case POISSON_DISTANCE:
149                 m = PairwiseDistanceCalculator.calcPoissonDistances( msa );
150                 break;
151             case FRACTIONAL_DISSIMILARITY:
152                 m = PairwiseDistanceCalculator.calcFractionalDissimilarities( msa );
153                 break;
154             default:
155                 throw new IllegalArgumentException( "invalid pwd method" );
156         }
157         if ( write_matrix ) {
158             try {
159                 m.write( ForesterUtil.createBufferedWriter( matrix_name ) );
160             }
161             catch ( final IOException e ) {
162                 e.printStackTrace();
163             }
164         }
165         final NeighborJoiningF nj = NeighborJoiningF.createInstance( false, 5 );
166         final Phylogeny phy = nj.execute( m );
167         return phy;
168     }
169
170     private StringBuilder msaStatsAsSB() {
171         final StringBuilder sb = new StringBuilder();
172         sb.append( _msa.getNumberOfSequences() );
173         sb.append( "\t" );
174         sb.append( _msa.getLength() );
175         sb.append( "\t" );
176         sb.append( NF_4.format( MsaMethods.calcGapRatio( _msa ) ) );
177         sb.append( "\t" );
178         sb.append( NF_4.format( calculateIdentityRatio( 0, _msa.getLength() - 1, _msa ).arithmeticMean() ) );
179         return sb;
180     }
181
182     final private void realignWithMafft() throws IOException, InterruptedException {
183         //  final MsaInferrer mafft = Mafft
184         //       .createInstance( "/home/czmasek/SOFTWARE/MSA/MAFFT/mafft-7.130-without-extensions/scripts/mafft" );
185         final MsaInferrer mafft = Mafft.createInstance( _path_to_mafft );
186         final List<String> opts = new ArrayList<String>();
187         for( final String o : _maffts_opts.split( "\\s" ) ) {
188             opts.add( o );
189         }
190         //opts.add( "--maxiterate" );
191         //opts.add( "1000" );
192         //opts.add( "--localpair" );
193         //opts.add( "--quiet" );
194         _msa = mafft.infer( _msa.asSequenceList(), opts );
195     }
196
197     final private void removeGapColumns() {
198         _msa = MsaMethods.createInstance().removeGapColumns( 1, 0, _msa );
199     }
200
201     final private void removeViaGapAverage( final double mean_gapiness,
202                                             final int step,
203                                             final boolean realign,
204                                             final boolean norm,
205                                             final boolean verbose ) throws IOException, InterruptedException {
206         final GapContribution stats[] = calcGapContribtionsStats( norm );
207         final List<String> to_remove_ids = new ArrayList<String>();
208         for( final GapContribution gap_gontribution : stats ) {
209             to_remove_ids.add( gap_gontribution.getId() );
210         }
211         if ( verbose ) {
212             printTableHeader();
213         }
214         int i = 0;
215         while ( MsaMethods.calcGapRatio( _msa ) > mean_gapiness ) {
216             final String id = to_remove_ids.get( i );
217             _msa = MsaMethods.removeSequence( _msa, id );
218             removeGapColumns();
219             if ( verbose ) {
220                 System.out.print( ForesterUtil.pad( id, 20, ' ', false ) );
221                 System.out.print( "\t" );
222                 final StringBuilder sb = msaStatsAsSB();
223                 System.out.print( sb );
224                 System.out.print( "\t" );
225             }
226             if ( ( ( ( i + 1 ) % step ) == 0 ) || ( MsaMethods.calcGapRatio( _msa ) <= mean_gapiness ) ) {
227                 if ( realign ) {
228                     realignWithMafft();
229                 }
230                 final String s = writeOutfile();
231                 if ( verbose ) {
232                     System.out.print( "-> " + s );
233                 }
234             }
235             if ( verbose ) {
236                 System.out.println();
237             }
238             ++i;
239         }
240     }
241
242     private final static void printTableHeader() {
243         System.out.print( ForesterUtil.pad( "Id", 20, ' ', false ) );
244         System.out.print( "\t" );
245         System.out.print( "Seqs" );
246         System.out.print( "\t" );
247         System.out.print( "Length" );
248         System.out.print( "\t" );
249         System.out.print( "Gaps" );
250         System.out.print( "\t" );
251         System.out.print( "MSA qual" );
252         System.out.print( "\t" );
253         System.out.println();
254     }
255
256     final private void removeViaLength( final int length,
257                                         final int step,
258                                         final boolean realign,
259                                         final boolean norm,
260                                         final boolean verbose ) throws IOException, InterruptedException {
261         final GapContribution stats[] = calcGapContribtionsStats( norm );
262         final List<String> to_remove_ids = new ArrayList<String>();
263         for( final GapContribution gap_gontribution : stats ) {
264             to_remove_ids.add( gap_gontribution.getId() );
265         }
266         if ( verbose ) {
267             printTableHeader();
268         }
269         int i = 0;
270         while ( _msa.getLength() > length ) {
271             final String id = to_remove_ids.get( i );
272             _msa = MsaMethods.removeSequence( _msa, id );
273             removeGapColumns();
274             if ( verbose ) {
275                 System.out.print( ForesterUtil.pad( id, 20, ' ', false ) );
276                 System.out.print( "\t" );
277                 final StringBuilder sb = msaStatsAsSB();
278                 System.out.print( sb );
279                 System.out.print( "\t" );
280             }
281             if ( ( ( ( i + 1 ) % step ) == 0 ) || ( _msa.getLength() <= length ) ) {
282                 if ( realign ) {
283                     realignWithMafft();
284                 }
285                 final String s = writeOutfile();
286                 if ( verbose ) {
287                     System.out.print( "-> " + s );
288                 }
289             }
290             if ( verbose ) {
291                 System.out.println();
292             }
293             ++i;
294         }
295     }
296
297     final private void removeWorstOffenders( final int to_remove,
298                                              final int step,
299                                              final boolean realign,
300                                              final boolean norm,
301                                              final boolean verbose ) throws IOException, InterruptedException {
302         final GapContribution stats[] = calcGapContribtionsStats( norm );
303         final List<String> to_remove_ids = new ArrayList<String>();
304         for( int j = 0; j < to_remove; ++j ) {
305             to_remove_ids.add( stats[ j ].getId() );
306             _removed_seq_ids.add( stats[ j ].getId() );
307         }
308         if ( verbose ) {
309             printTableHeader();
310         }
311         for( int i = 0; i < to_remove_ids.size(); ++i ) {
312             final String id = to_remove_ids.get( i );
313             _msa = MsaMethods.removeSequence( _msa, id );
314             removeGapColumns();
315             if ( verbose ) {
316                 System.out.print( ForesterUtil.pad( id, 20, ' ', false ) );
317                 System.out.print( "\t" );
318                 final StringBuilder sb = msaStatsAsSB();
319                 System.out.print( sb );
320                 System.out.print( "\t" );
321             }
322             if ( ( ( ( i + 1 ) % step ) == 0 ) || ( i == ( to_remove_ids.size() - 1 ) ) ) {
323                 if ( realign ) {
324                     realignWithMafft();
325                 }
326                 final String s = writeOutfile();
327                 if ( verbose ) {
328                     System.out.print( "-> " + s );
329                 }
330             }
331             if ( verbose ) {
332                 System.out.println();
333             }
334         }
335     }
336
337     private void setPathToMafft( final String path_to_mafft ) {
338         _path_to_mafft = path_to_mafft;
339     }
340
341     final private void writeMsa( final String outfile, final MSA_FORMAT format ) throws IOException {
342         final Writer w = ForesterUtil.createBufferedWriter( outfile );
343         _msa.write( w, format );
344         w.close();
345     }
346
347     private String writeOutfile() throws IOException {
348         final String s = writeMsa( _out_file_base, MSA_FORMAT.PHYLIP, ".aln" );
349         //writeMsa( _out_file_base, MSA_FORMAT.FASTA, ".fasta" );
350         return s;
351     }
352
353     // Returns null if not path found.
354     final public static String guessPathToMafft() {
355         String path;
356         if ( ForesterUtil.OS_NAME.toLowerCase().indexOf( "win" ) >= 0 ) {
357             path = "C:\\Program Files\\mafft-win\\mafft.bat";
358             if ( MsaInferrer.isInstalled( path ) ) {
359                 return path;
360             }
361         }
362         path = "/home/czmasek/SOFTWARE/MSA/MAFFT/mafft-7.130-without-extensions/scripts/mafft";
363         if ( MsaInferrer.isInstalled( path ) ) {
364             return path;
365         }
366         path = "/usr/local/bin/mafft";
367         if ( MsaInferrer.isInstalled( path ) ) {
368             return path;
369         }
370         path = "/usr/bin/mafft";
371         if ( MsaInferrer.isInstalled( path ) ) {
372             return path;
373         }
374         path = "/bin/mafft";
375         if ( MsaInferrer.isInstalled( path ) ) {
376             return path;
377         }
378         path = "mafft";
379         if ( MsaInferrer.isInstalled( path ) ) {
380             return path;
381         }
382         return null;
383     }
384
385     public final static MsaCompactor reduceGapAverage( final Msa msa,
386                                                        final double max_gap_average,
387                                                        final int step,
388                                                        final boolean realign,
389                                                        final boolean norm,
390                                                        final String path_to_mafft,
391                                                        final File out ) throws IOException, InterruptedException {
392         final MsaCompactor mc = new MsaCompactor( msa );
393         if ( realign ) {
394             mc.setPathToMafft( path_to_mafft );
395         }
396         mc.setOutFileBase( out );
397         mc.removeViaGapAverage( max_gap_average, step, realign, norm, true );
398         return mc;
399     }
400
401     public final static MsaCompactor reduceLength( final Msa msa,
402                                                    final int length,
403                                                    final int step,
404                                                    final boolean realign,
405                                                    final boolean norm,
406                                                    final String path_to_mafft,
407                                                    final File out ) throws IOException, InterruptedException {
408         final MsaCompactor mc = new MsaCompactor( msa );
409         if ( realign ) {
410             mc.setPathToMafft( path_to_mafft );
411         }
412         mc.setOutFileBase( out );
413         mc.removeViaLength( length, step, realign, norm, true );
414         return mc;
415     }
416
417     public final static MsaCompactor removeWorstOffenders( final Msa msa,
418                                                            final int worst_offenders_to_remove,
419                                                            final int step,
420                                                            final boolean realign,
421                                                            final boolean norm,
422                                                            final String path_to_mafft,
423                                                            final File out ) throws IOException, InterruptedException {
424         final MsaCompactor mc = new MsaCompactor( msa );
425         if ( realign ) {
426             mc.setPathToMafft( path_to_mafft );
427         }
428         mc.setOutFileBase( out );
429         mc.removeWorstOffenders( worst_offenders_to_remove, step, realign, norm, true );
430         return mc;
431     }
432
433     private static DescriptiveStatistics calculateIdentityRatio( final int from, final int to, final Msa msa ) {
434         final DescriptiveStatistics stats = new BasicDescriptiveStatistics();
435         for( int c = from; c <= to; ++c ) {
436             stats.addValue( MsaMethods.calculateIdentityRatio( msa, c ) );
437         }
438         return stats;
439     }
440 }