a4d71dac9a6f900c6578a4329d0892359c8de5bc
[jalview.git] / forester / java / src / org / forester / msa_compactor / MsaCompactor.java
1 // $Id:
2 // FORESTER -- software libraries and applications
3 // for evolutionary biology research and applications.
4 //
5 // Copyright (C) 2014 Christian M. Zmasek
6 // Copyright (C) 2014 Sanford-Burnham Medical Research Institute
7 // All rights reserved
8 //
9 // This library is free software; you can redistribute it and/or
10 // modify it under the terms of the GNU Lesser General Public
11 // License as published by the Free Software Foundation; either
12 // version 2.1 of the License, or (at your option) any later version.
13 //
14 // This library is distributed in the hope that it will be useful,
15 // but WITHOUT ANY WARRANTY; without even the implied warranty of
16 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
17 // Lesser General Public License for more details.
18 //
19 // You should have received a copy of the GNU Lesser General Public
20 // License along with this library; if not, write to the Free Software
21 // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
22 //
23 // WWW: https://sites.google.com/site/cmzmasek/home/software/forester
24
25 package org.forester.msa_compactor;
26
27 import java.io.File;
28 import java.io.IOException;
29 import java.io.Writer;
30 import java.math.RoundingMode;
31 import java.text.DecimalFormat;
32 import java.text.NumberFormat;
33 import java.util.ArrayList;
34 import java.util.Arrays;
35 import java.util.List;
36 import java.util.SortedSet;
37 import java.util.TreeSet;
38
39 import org.forester.evoinference.distance.NeighborJoiningF;
40 import org.forester.evoinference.distance.PairwiseDistanceCalculator;
41 import org.forester.evoinference.distance.PairwiseDistanceCalculator.PWD_DISTANCE_METHOD;
42 import org.forester.evoinference.matrix.distance.BasicSymmetricalDistanceMatrix;
43 import org.forester.evoinference.tools.BootstrapResampler;
44 import org.forester.msa.DeleteableMsa;
45 import org.forester.msa.Mafft;
46 import org.forester.msa.Msa;
47 import org.forester.msa.Msa.MSA_FORMAT;
48 import org.forester.msa.MsaInferrer;
49 import org.forester.msa.MsaMethods;
50 import org.forester.msa.ResampleableMsa;
51 import org.forester.phylogeny.Phylogeny;
52 import org.forester.phylogeny.PhylogenyMethods;
53 import org.forester.sequence.Sequence;
54 import org.forester.tools.ConfidenceAssessor;
55 import org.forester.util.ForesterUtil;
56
57 public class MsaCompactor {
58
59     final private static NumberFormat NF_3         = new DecimalFormat( "#.###" );
60     final private static NumberFormat NF_4         = new DecimalFormat( "#.####" );
61     //   private final String              _maffts_opts = "--retree 1";
62     private final String              _maffts_opts = "--auto";
63     private DeleteableMsa             _msa;
64     private File                      _out_file_base;
65     private String                    _path_to_mafft;
66     private final SortedSet<String>   _removed_seq_ids;
67     static {
68         NF_4.setRoundingMode( RoundingMode.HALF_UP );
69         NF_3.setRoundingMode( RoundingMode.HALF_UP );
70     }
71
72     private MsaCompactor( final DeleteableMsa msa ) {
73         _msa = msa;
74         _removed_seq_ids = new TreeSet<String>();
75     }
76
77     final public Msa getMsa() {
78         return _msa;
79     }
80
81     final public SortedSet<String> getRemovedSeqIds() {
82         return _removed_seq_ids;
83     }
84
85     final public void setOutFileBase( final File out_file_base ) {
86         _out_file_base = out_file_base;
87     }
88
89     final public String writeMsa( final File outfile, final MSA_FORMAT format, final String suffix ) throws IOException {
90         final Double gr = MsaMethods.calcGapRatio( _msa );
91         final String s = outfile + "_" + _msa.getNumberOfSequences() + "_" + _msa.getLength() + "_"
92                 + ForesterUtil.roundToInt( gr * 100 );
93         writeMsa( s + suffix, format );
94         return s;
95     }
96
97     final int calcNonGapResidues( final Sequence seq ) {
98         int ng = 0;
99         for( int i = 0; i < seq.getLength(); ++i ) {
100             if ( !seq.isGapAt( i ) ) {
101                 ++ng;
102             }
103         }
104         return ng;
105     }
106
107     Phylogeny pi( final String matrix ) {
108         final Phylogeny master_phy = inferNJphylogeny( PWD_DISTANCE_METHOD.KIMURA_DISTANCE, _msa, true, matrix );
109         final int seed = 15;
110         final int n = 100;
111         final ResampleableMsa resampleable_msa = new ResampleableMsa( _msa );
112         final int[][] resampled_column_positions = BootstrapResampler.createResampledColumnPositions( _msa.getLength(),
113                                                                                                       n,
114                                                                                                       seed );
115         final Phylogeny[] eval_phys = new Phylogeny[ n ];
116         for( int i = 0; i < n; ++i ) {
117             resampleable_msa.resample( resampled_column_positions[ i ] );
118             eval_phys[ i ] = inferNJphylogeny( PWD_DISTANCE_METHOD.KIMURA_DISTANCE, resampleable_msa, false, null );
119         }
120         ConfidenceAssessor.evaluate( "bootstrap", eval_phys, master_phy, true, 1 );
121         PhylogenyMethods.extractFastaInformation( master_phy );
122         return master_phy;
123     }
124
125     private final GapContribution[] calcGapContribtions( final boolean normalize_for_effective_seq_length ) {
126         final double gappiness[] = calcGappiness();
127         final GapContribution stats[] = new GapContribution[ _msa.getNumberOfSequences() ];
128         for( int row = 0; row < _msa.getNumberOfSequences(); ++row ) {
129             stats[ row ] = new GapContribution( _msa.getIdentifier( row ) );
130             for( int col = 0; col < _msa.getLength(); ++col ) {
131                 if ( !_msa.isGapAt( row, col ) ) {
132                     stats[ row ].addToValue( gappiness[ col ] );
133                 }
134             }
135             if ( normalize_for_effective_seq_length ) {
136                 stats[ row ].divideValue( calcNonGapResidues( _msa.getSequence( row ) ) );
137             }
138             else {
139                 stats[ row ].divideValue( _msa.getLength() );
140             }
141         }
142         return stats;
143     }
144
145     final private GapContribution[] calcGapContribtionsStats( final boolean norm ) {
146         final GapContribution stats[] = calcGapContribtions( norm );
147         Arrays.sort( stats );
148         return stats;
149     }
150
151     private final double[] calcGappiness() {
152         final int l = _msa.getLength();
153         final double gappiness[] = new double[ l ];
154         final int seqs = _msa.getNumberOfSequences();
155         for( int i = 0; i < l; ++i ) {
156             gappiness[ i ] = ( double ) MsaMethods.calcGapSumPerColumn( _msa, i ) / seqs;
157         }
158         return gappiness;
159     }
160
161     final private List<MsaProperties> chart( final int step,
162                                              final boolean realign,
163                                              final boolean norm,
164                                              final boolean verbose ) throws IOException, InterruptedException {
165         final GapContribution stats[] = calcGapContribtionsStats( norm );
166         final List<String> to_remove_ids = new ArrayList<String>();
167         final List<MsaProperties> msa_props = new ArrayList<MsaProperties>();
168         for( final GapContribution gap_gontribution : stats ) {
169             to_remove_ids.add( gap_gontribution.getId() );
170         }
171         if ( verbose ) {
172             printTableHeader();
173         }
174         int i = 0;
175         final int s = _msa.getNumberOfSequences();
176         final int x = ForesterUtil.roundToInt( s / 20.0 );
177         while ( _msa.getNumberOfSequences() > x ) {
178             final String id = to_remove_ids.get( i );
179             //~_msa = MsaMethods.removeSequence( _msa, id );
180             _msa.deleteRow( id );
181             if ( ( s < 500 ) || ( ( step > 0 ) && ( ( ( i + 1 ) % step ) == 0 ) ) ) {
182                 removeGapColumns();
183                 if ( realign && ( ( step > 0 ) && ( ( ( i + 1 ) % step ) == 0 ) ) ) {
184                     realignWithMafft();
185                     msa_props.add( new MsaProperties( _msa ) );
186                     if ( verbose ) {
187                         printMsaStats( id );
188                     }
189                     if ( verbose ) {
190                         System.out.print( "(realigned)" );
191                     }
192                 }
193                 else {
194                     msa_props.add( new MsaProperties( _msa ) );
195                     if ( verbose ) {
196                         printMsaStats( id );
197                     }
198                 }
199                 if ( verbose ) {
200                     System.out.println();
201                 }
202             }
203             ++i;
204         }
205         return msa_props;
206     }
207
208     private Phylogeny inferNJphylogeny( final PWD_DISTANCE_METHOD pwd_distance_method,
209                                         final Msa msa,
210                                         final boolean write_matrix,
211                                         final String matrix_name ) {
212         BasicSymmetricalDistanceMatrix m = null;
213         switch ( pwd_distance_method ) {
214             case KIMURA_DISTANCE:
215                 m = PairwiseDistanceCalculator.calcKimuraDistances( msa );
216                 break;
217             case POISSON_DISTANCE:
218                 m = PairwiseDistanceCalculator.calcPoissonDistances( msa );
219                 break;
220             case FRACTIONAL_DISSIMILARITY:
221                 m = PairwiseDistanceCalculator.calcFractionalDissimilarities( msa );
222                 break;
223             default:
224                 throw new IllegalArgumentException( "invalid pwd method" );
225         }
226         if ( write_matrix ) {
227             try {
228                 m.write( ForesterUtil.createBufferedWriter( matrix_name ) );
229             }
230             catch ( final IOException e ) {
231                 e.printStackTrace();
232             }
233         }
234         final NeighborJoiningF nj = NeighborJoiningF.createInstance( false, 5 );
235         final Phylogeny phy = nj.execute( m );
236         return phy;
237     }
238
239     private StringBuilder msaStatsAsSB() {
240         final StringBuilder sb = new StringBuilder();
241         sb.append( _msa.getNumberOfSequences() );
242         sb.append( "\t" );
243         sb.append( _msa.getLength() );
244         sb.append( "\t" );
245         sb.append( NF_4.format( MsaMethods.calcGapRatio( _msa ) ) );
246         sb.append( "\t" );
247         sb.append( NF_4.format( MsaMethods.calculateIdentityRatio( 0, _msa.getLength() - 1, _msa ).arithmeticMean() ) );
248         return sb;
249     }
250
251     private final void printMsaStats( final String id ) {
252         System.out.print( ForesterUtil.pad( id, 20, ' ', false ) );
253         System.out.print( "\t" );
254         final StringBuilder sb = msaStatsAsSB();
255         System.out.print( sb );
256         System.out.print( "\t" );
257     }
258
259     final private void printMsaStatsWriteOutfileAndRealign( final boolean realign,
260                                                             final boolean verbose,
261                                                             final String id ) throws IOException, InterruptedException {
262         if ( realign ) {
263             realignWithMafft();
264         }
265         if ( verbose ) {
266             printMsaStats( id );
267         }
268         final String s = writeOutfile();
269         if ( verbose ) {
270             System.out.print( "-> " + s + ( realign ? "\t(realigned)" : "" ) );
271         }
272     }
273
274     final private void realignWithMafft() throws IOException, InterruptedException {
275         //  final MsaInferrer mafft = Mafft
276         //       .createInstance( "/home/czmasek/SOFTWARE/MSA/MAFFT/mafft-7.130-without-extensions/scripts/mafft" );
277         final MsaInferrer mafft = Mafft.createInstance( _path_to_mafft );
278         final List<String> opts = new ArrayList<String>();
279         for( final String o : _maffts_opts.split( "\\s" ) ) {
280             opts.add( o );
281         }
282         //opts.add( "--maxiterate" );
283         //opts.add( "1000" );
284         //opts.add( "--localpair" );
285         //opts.add( "--quiet" );
286         _msa = DeleteableMsa.createInstance( mafft.infer( _msa.asSequenceList(), opts ) );
287     }
288
289     final private void removeGapColumns() {
290         //~ _msa = MsaMethods.createInstance().removeGapColumns( 1, 0, _msa );
291         _msa.deleteGapOnlyColumns();
292     }
293
294     final private void removeViaGapAverage( final double mean_gapiness,
295                                             final int step,
296                                             final boolean realign,
297                                             final boolean norm,
298                                             final boolean verbose ) throws IOException, InterruptedException {
299         final GapContribution stats[] = calcGapContribtionsStats( norm );
300         final List<String> to_remove_ids = new ArrayList<String>();
301         for( final GapContribution gap_gontribution : stats ) {
302             to_remove_ids.add( gap_gontribution.getId() );
303         }
304         if ( verbose ) {
305             printTableHeader();
306         }
307         int i = 0;
308         while ( MsaMethods.calcGapRatio( _msa ) > mean_gapiness ) {
309             final String id = to_remove_ids.get( i );
310             //`_msa = MsaMethods.removeSequence( _msa, id );
311             _msa.deleteRow( id );
312             removeGapColumns();
313             if ( ( ( step > 0 ) && ( ( ( i + 1 ) % step ) == 0 ) )
314                     || ( MsaMethods.calcGapRatio( _msa ) <= mean_gapiness ) ) {
315                 printMsaStatsWriteOutfileAndRealign( realign, verbose, id );
316             }
317             else if ( verbose ) {
318                 printMsaStats( id );
319             }
320             if ( verbose ) {
321                 System.out.println();
322             }
323             ++i;
324         }
325     }
326
327     final private void removeViaLength( final int length,
328                                         final int step,
329                                         final boolean realign,
330                                         final boolean norm,
331                                         final boolean verbose ) throws IOException, InterruptedException {
332         final GapContribution stats[] = calcGapContribtionsStats( norm );
333         final List<String> to_remove_ids = new ArrayList<String>();
334         for( final GapContribution gap_gontribution : stats ) {
335             to_remove_ids.add( gap_gontribution.getId() );
336         }
337         if ( verbose ) {
338             printTableHeader();
339         }
340         int i = 0;
341         while ( _msa.getLength() > length ) {
342             final String id = to_remove_ids.get( i );
343             //~_msa = MsaMethods.removeSequence( _msa, id );
344             _msa.deleteRow( id );
345             removeGapColumns();
346             if ( ( ( step > 0 ) && ( ( ( i + 1 ) % step ) == 0 ) ) || ( _msa.getLength() <= length ) ) {
347                 printMsaStatsWriteOutfileAndRealign( realign, verbose, id );
348             }
349             else if ( verbose ) {
350                 printMsaStats( id );
351             }
352             if ( verbose ) {
353                 System.out.println();
354             }
355             ++i;
356         }
357     }
358
359     final private void removeWorstOffenders( final int to_remove,
360                                              final int step,
361                                              final boolean realign,
362                                              final boolean norm,
363                                              final boolean verbose ) throws IOException, InterruptedException {
364         final GapContribution stats[] = calcGapContribtionsStats( norm );
365         final List<String> to_remove_ids = new ArrayList<String>();
366         for( int j = 0; j < to_remove; ++j ) {
367             to_remove_ids.add( stats[ j ].getId() );
368             _removed_seq_ids.add( stats[ j ].getId() );
369         }
370         if ( verbose ) {
371             printTableHeader();
372         }
373         for( int i = 0; i < to_remove_ids.size(); ++i ) {
374             final String id = to_remove_ids.get( i );
375             //~ _msa = MsaMethods.removeSequence( _msa, id );
376             _msa.deleteRow( id );
377             removeGapColumns();
378             if ( ( ( step > 0 ) && ( ( ( i + 1 ) % step ) == 0 ) ) || ( i == ( to_remove_ids.size() - 1 ) ) ) {
379                 printMsaStatsWriteOutfileAndRealign( realign, verbose, id );
380             }
381             else if ( verbose ) {
382                 printMsaStats( id );
383             }
384             if ( verbose ) {
385                 System.out.println();
386             }
387         }
388     }
389
390     private void setPathToMafft( final String path_to_mafft ) {
391         _path_to_mafft = path_to_mafft;
392     }
393
394     final private void writeMsa( final String outfile, final MSA_FORMAT format ) throws IOException {
395         final Writer w = ForesterUtil.createBufferedWriter( outfile );
396         _msa.write( w, format );
397         w.close();
398     }
399
400     private String writeOutfile() throws IOException {
401         final String s = writeMsa( _out_file_base, MSA_FORMAT.PHYLIP, ".aln" );
402         //writeMsa( _out_file_base, MSA_FORMAT.FASTA, ".fasta" );
403         return s;
404     }
405
406     public final static MsaCompactor chart( final DeleteableMsa msa,
407                                             final int step,
408                                             final boolean realign,
409                                             final boolean norm,
410                                             final String path_to_mafft ) throws IOException, InterruptedException {
411         final int initial_number_of_seqs = msa.getNumberOfSequences();
412         final MsaCompactor mc = new MsaCompactor( msa );
413         if ( realign ) {
414             mc.setPathToMafft( path_to_mafft );
415         }
416         final List<MsaProperties> msa_props = mc.chart( step, realign, norm, true );
417         Chart.display( msa_props, initial_number_of_seqs );
418         return mc;
419     }
420
421     // Returns null if not path found.
422     final public static String guessPathToMafft() {
423         String path;
424         if ( ForesterUtil.OS_NAME.toLowerCase().indexOf( "win" ) >= 0 ) {
425             path = "C:\\Program Files\\mafft-win\\mafft.bat";
426             if ( MsaInferrer.isInstalled( path ) ) {
427                 return path;
428             }
429         }
430         path = "/home/czmasek/SOFTWARE/MSA/MAFFT/mafft-7.130-without-extensions/scripts/mafft";
431         if ( MsaInferrer.isInstalled( path ) ) {
432             return path;
433         }
434         path = "/usr/local/bin/mafft";
435         if ( MsaInferrer.isInstalled( path ) ) {
436             return path;
437         }
438         path = "/usr/bin/mafft";
439         if ( MsaInferrer.isInstalled( path ) ) {
440             return path;
441         }
442         path = "/bin/mafft";
443         if ( MsaInferrer.isInstalled( path ) ) {
444             return path;
445         }
446         path = "mafft";
447         if ( MsaInferrer.isInstalled( path ) ) {
448             return path;
449         }
450         return null;
451     }
452
453     public final static MsaCompactor reduceGapAverage( final DeleteableMsa msa,
454                                                        final double max_gap_average,
455                                                        final int step,
456                                                        final boolean realign,
457                                                        final boolean norm,
458                                                        final String path_to_mafft,
459                                                        final File out ) throws IOException, InterruptedException {
460         final MsaCompactor mc = new MsaCompactor( msa );
461         if ( realign ) {
462             mc.setPathToMafft( path_to_mafft );
463         }
464         mc.setOutFileBase( out );
465         mc.removeViaGapAverage( max_gap_average, step, realign, norm, true );
466         return mc;
467     }
468
469     public final static MsaCompactor reduceLength( final DeleteableMsa msa,
470                                                    final int length,
471                                                    final int step,
472                                                    final boolean realign,
473                                                    final boolean norm,
474                                                    final String path_to_mafft,
475                                                    final File out ) throws IOException, InterruptedException {
476         final MsaCompactor mc = new MsaCompactor( msa );
477         if ( realign ) {
478             mc.setPathToMafft( path_to_mafft );
479         }
480         mc.setOutFileBase( out );
481         mc.removeViaLength( length, step, realign, norm, true );
482         return mc;
483     }
484
485     public final static MsaCompactor removeWorstOffenders( final DeleteableMsa msa,
486                                                            final int worst_offenders_to_remove,
487                                                            final int step,
488                                                            final boolean realign,
489                                                            final boolean norm,
490                                                            final String path_to_mafft,
491                                                            final File out ) throws IOException, InterruptedException {
492         final MsaCompactor mc = new MsaCompactor( msa );
493         if ( realign ) {
494             mc.setPathToMafft( path_to_mafft );
495         }
496         mc.setOutFileBase( out );
497         mc.removeWorstOffenders( worst_offenders_to_remove, step, realign, norm, true );
498         return mc;
499     }
500
501     private final static void printTableHeader() {
502         System.out.print( ForesterUtil.pad( "Id", 20, ' ', false ) );
503         System.out.print( "\t" );
504         System.out.print( "Seqs" );
505         System.out.print( "\t" );
506         System.out.print( "Length" );
507         System.out.print( "\t" );
508         System.out.print( "Gaps" );
509         System.out.print( "\t" );
510         System.out.print( "MSA qual" );
511         System.out.print( "\t" );
512         System.out.println();
513     }
514 }