inprogress
[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.BasicMsa;
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 Msa                       _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 Msa 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( ( BasicMsa ) _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 x = ForesterUtil.roundToInt( _msa.getNumberOfSequences() / 20.0 );
176         while ( _msa.getNumberOfSequences() > x ) {
177             final String id = to_remove_ids.get( i );
178             _msa = MsaMethods.removeSequence( _msa, id );
179             removeGapColumns();
180             msa_props.add( new MsaProperties( _msa ) );
181             if ( verbose ) {
182                 printMsaStats( id );
183             }
184             if ( ( step > 0 ) && ( ( ( i + 1 ) % step ) == 0 ) ) {
185                 if ( realign ) {
186                     realignWithMafft();
187                 }
188             }
189             if ( verbose ) {
190                 System.out.println();
191             }
192             ++i;
193         }
194         return msa_props;
195     }
196
197     private Phylogeny inferNJphylogeny( final PWD_DISTANCE_METHOD pwd_distance_method,
198                                         final Msa msa,
199                                         final boolean write_matrix,
200                                         final String matrix_name ) {
201         BasicSymmetricalDistanceMatrix m = null;
202         switch ( pwd_distance_method ) {
203             case KIMURA_DISTANCE:
204                 m = PairwiseDistanceCalculator.calcKimuraDistances( msa );
205                 break;
206             case POISSON_DISTANCE:
207                 m = PairwiseDistanceCalculator.calcPoissonDistances( msa );
208                 break;
209             case FRACTIONAL_DISSIMILARITY:
210                 m = PairwiseDistanceCalculator.calcFractionalDissimilarities( msa );
211                 break;
212             default:
213                 throw new IllegalArgumentException( "invalid pwd method" );
214         }
215         if ( write_matrix ) {
216             try {
217                 m.write( ForesterUtil.createBufferedWriter( matrix_name ) );
218             }
219             catch ( final IOException e ) {
220                 e.printStackTrace();
221             }
222         }
223         final NeighborJoiningF nj = NeighborJoiningF.createInstance( false, 5 );
224         final Phylogeny phy = nj.execute( m );
225         return phy;
226     }
227
228     private StringBuilder msaStatsAsSB() {
229         final StringBuilder sb = new StringBuilder();
230         sb.append( _msa.getNumberOfSequences() );
231         sb.append( "\t" );
232         sb.append( _msa.getLength() );
233         sb.append( "\t" );
234         sb.append( NF_4.format( MsaMethods.calcGapRatio( _msa ) ) );
235         sb.append( "\t" );
236         sb.append( NF_4.format( MsaMethods.calculateIdentityRatio( 0, _msa.getLength() - 1, _msa ).arithmeticMean() ) );
237         return sb;
238     }
239
240     private final void printMsaStats( final String id ) {
241         System.out.print( ForesterUtil.pad( id, 20, ' ', false ) );
242         System.out.print( "\t" );
243         final StringBuilder sb = msaStatsAsSB();
244         System.out.print( sb );
245         System.out.print( "\t" );
246     }
247
248     final private void printMsaStatsWriteOutfileAndRealign( final boolean realign,
249                                                             final boolean verbose,
250                                                             final String id ) throws IOException, InterruptedException {
251         if ( realign ) {
252             realignWithMafft();
253         }
254         if ( verbose ) {
255             printMsaStats( id );
256         }
257         final String s = writeOutfile();
258         if ( verbose ) {
259             System.out.print( "-> " + s + ( realign ? " (realigned)" : "" ) );
260         }
261     }
262
263     final private void realignWithMafft() throws IOException, InterruptedException {
264         //  final MsaInferrer mafft = Mafft
265         //       .createInstance( "/home/czmasek/SOFTWARE/MSA/MAFFT/mafft-7.130-without-extensions/scripts/mafft" );
266         final MsaInferrer mafft = Mafft.createInstance( _path_to_mafft );
267         final List<String> opts = new ArrayList<String>();
268         for( final String o : _maffts_opts.split( "\\s" ) ) {
269             opts.add( o );
270         }
271         //opts.add( "--maxiterate" );
272         //opts.add( "1000" );
273         //opts.add( "--localpair" );
274         //opts.add( "--quiet" );
275         _msa = mafft.infer( _msa.asSequenceList(), opts );
276     }
277
278     final private void removeGapColumns() {
279         _msa = MsaMethods.createInstance().removeGapColumns( 1, 0, _msa );
280     }
281
282     final private void removeViaGapAverage( final double mean_gapiness,
283                                             final int step,
284                                             final boolean realign,
285                                             final boolean norm,
286                                             final boolean verbose ) throws IOException, InterruptedException {
287         final GapContribution stats[] = calcGapContribtionsStats( norm );
288         final List<String> to_remove_ids = new ArrayList<String>();
289         for( final GapContribution gap_gontribution : stats ) {
290             to_remove_ids.add( gap_gontribution.getId() );
291         }
292         if ( verbose ) {
293             printTableHeader();
294         }
295         int i = 0;
296         while ( MsaMethods.calcGapRatio( _msa ) > mean_gapiness ) {
297             final String id = to_remove_ids.get( i );
298             _msa = MsaMethods.removeSequence( _msa, id );
299             removeGapColumns();
300             if ( ( ( step > 0 ) && ( ( ( i + 1 ) % step ) == 0 ) )
301                     || ( MsaMethods.calcGapRatio( _msa ) <= mean_gapiness ) ) {
302                 printMsaStatsWriteOutfileAndRealign( realign, verbose, id );
303             }
304             else if ( verbose ) {
305                 printMsaStats( id );
306             }
307             if ( verbose ) {
308                 System.out.println();
309             }
310             ++i;
311         }
312     }
313
314     final private void removeViaLength( final int length,
315                                         final int step,
316                                         final boolean realign,
317                                         final boolean norm,
318                                         final boolean verbose ) throws IOException, InterruptedException {
319         final GapContribution stats[] = calcGapContribtionsStats( norm );
320         final List<String> to_remove_ids = new ArrayList<String>();
321         for( final GapContribution gap_gontribution : stats ) {
322             to_remove_ids.add( gap_gontribution.getId() );
323         }
324         if ( verbose ) {
325             printTableHeader();
326         }
327         int i = 0;
328         while ( _msa.getLength() > length ) {
329             final String id = to_remove_ids.get( i );
330             _msa = MsaMethods.removeSequence( _msa, id );
331             removeGapColumns();
332             if ( ( ( step > 0 ) && ( ( ( i + 1 ) % step ) == 0 ) ) || ( _msa.getLength() <= length ) ) {
333                 printMsaStatsWriteOutfileAndRealign( realign, verbose, id );
334             }
335             else if ( verbose ) {
336                 printMsaStats( id );
337             }
338             if ( verbose ) {
339                 System.out.println();
340             }
341             ++i;
342         }
343     }
344
345     final private void removeWorstOffenders( final int to_remove,
346                                              final int step,
347                                              final boolean realign,
348                                              final boolean norm,
349                                              final boolean verbose ) throws IOException, InterruptedException {
350         final GapContribution stats[] = calcGapContribtionsStats( norm );
351         final List<String> to_remove_ids = new ArrayList<String>();
352         for( int j = 0; j < to_remove; ++j ) {
353             to_remove_ids.add( stats[ j ].getId() );
354             _removed_seq_ids.add( stats[ j ].getId() );
355         }
356         if ( verbose ) {
357             printTableHeader();
358         }
359         for( int i = 0; i < to_remove_ids.size(); ++i ) {
360             final String id = to_remove_ids.get( i );
361             _msa = MsaMethods.removeSequence( _msa, id );
362             removeGapColumns();
363             if ( ( ( step > 0 ) && ( ( ( i + 1 ) % step ) == 0 ) ) || ( i == ( to_remove_ids.size() - 1 ) ) ) {
364                 printMsaStatsWriteOutfileAndRealign( realign, verbose, id );
365             }
366             else if ( verbose ) {
367                 printMsaStats( id );
368             }
369             if ( verbose ) {
370                 System.out.println();
371             }
372         }
373     }
374
375     private void setPathToMafft( final String path_to_mafft ) {
376         _path_to_mafft = path_to_mafft;
377     }
378
379     final private void writeMsa( final String outfile, final MSA_FORMAT format ) throws IOException {
380         final Writer w = ForesterUtil.createBufferedWriter( outfile );
381         _msa.write( w, format );
382         w.close();
383     }
384
385     private String writeOutfile() throws IOException {
386         final String s = writeMsa( _out_file_base, MSA_FORMAT.PHYLIP, ".aln" );
387         //writeMsa( _out_file_base, MSA_FORMAT.FASTA, ".fasta" );
388         return s;
389     }
390
391     public final static MsaCompactor chart( final Msa msa,
392                                             final int step,
393                                             final boolean realign,
394                                             final boolean norm,
395                                             final String path_to_mafft ) throws IOException, InterruptedException {
396         final MsaCompactor mc = new MsaCompactor( msa );
397         if ( realign ) {
398             mc.setPathToMafft( path_to_mafft );
399         }
400         final List<MsaProperties> msa_props = mc.chart( step, realign, norm, true );
401         Chart.display( msa_props );
402         return mc;
403     }
404
405     // Returns null if not path found.
406     final public static String guessPathToMafft() {
407         String path;
408         if ( ForesterUtil.OS_NAME.toLowerCase().indexOf( "win" ) >= 0 ) {
409             path = "C:\\Program Files\\mafft-win\\mafft.bat";
410             if ( MsaInferrer.isInstalled( path ) ) {
411                 return path;
412             }
413         }
414         path = "/home/czmasek/SOFTWARE/MSA/MAFFT/mafft-7.130-without-extensions/scripts/mafft";
415         if ( MsaInferrer.isInstalled( path ) ) {
416             return path;
417         }
418         path = "/usr/local/bin/mafft";
419         if ( MsaInferrer.isInstalled( path ) ) {
420             return path;
421         }
422         path = "/usr/bin/mafft";
423         if ( MsaInferrer.isInstalled( path ) ) {
424             return path;
425         }
426         path = "/bin/mafft";
427         if ( MsaInferrer.isInstalled( path ) ) {
428             return path;
429         }
430         path = "mafft";
431         if ( MsaInferrer.isInstalled( path ) ) {
432             return path;
433         }
434         return null;
435     }
436
437     public final static MsaCompactor reduceGapAverage( final Msa msa,
438                                                        final double max_gap_average,
439                                                        final int step,
440                                                        final boolean realign,
441                                                        final boolean norm,
442                                                        final String path_to_mafft,
443                                                        final File out ) throws IOException, InterruptedException {
444         final MsaCompactor mc = new MsaCompactor( msa );
445         if ( realign ) {
446             mc.setPathToMafft( path_to_mafft );
447         }
448         mc.setOutFileBase( out );
449         mc.removeViaGapAverage( max_gap_average, step, realign, norm, true );
450         return mc;
451     }
452
453     public final static MsaCompactor reduceLength( final Msa msa,
454                                                    final int length,
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.removeViaLength( length, step, realign, norm, true );
466         return mc;
467     }
468
469     public final static MsaCompactor removeWorstOffenders( final Msa msa,
470                                                            final int worst_offenders_to_remove,
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.removeWorstOffenders( worst_offenders_to_remove, step, realign, norm, true );
482         return mc;
483     }
484
485     private final static void printTableHeader() {
486         System.out.print( ForesterUtil.pad( "Id", 20, ' ', false ) );
487         System.out.print( "\t" );
488         System.out.print( "Seqs" );
489         System.out.print( "\t" );
490         System.out.print( "Length" );
491         System.out.print( "\t" );
492         System.out.print( "Gaps" );
493         System.out.print( "\t" );
494         System.out.print( "MSA qual" );
495         System.out.print( "\t" );
496         System.out.println();
497     }
498 }