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