2 // FORESTER -- software libraries and applications
3 // for evolutionary biology research and applications.
5 // Copyright (C) 2014 Christian M. Zmasek
6 // Copyright (C) 2014 Sanford-Burnham Medical Research Institute
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.
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.
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
23 // WWW: https://sites.google.com/site/cmzmasek/home/software/forester
25 package org.forester.msa_compactor;
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;
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.io.writers.SequenceWriter;
45 import org.forester.io.writers.SequenceWriter.SEQ_FORMAT;
46 import org.forester.msa.DeleteableMsa;
47 import org.forester.msa.Mafft;
48 import org.forester.msa.Msa;
49 import org.forester.msa.Msa.MSA_FORMAT;
50 import org.forester.msa.MsaInferrer;
51 import org.forester.msa.MsaMethods;
52 import org.forester.msa.ResampleableMsa;
53 import org.forester.phylogeny.Phylogeny;
54 import org.forester.phylogeny.PhylogenyMethods;
55 import org.forester.sequence.Sequence;
56 import org.forester.tools.ConfidenceAssessor;
57 import org.forester.util.ForesterUtil;
59 public class MsaCompactor {
61 final private static NumberFormat NF_3 = new DecimalFormat( "#.###" );
62 final private static NumberFormat NF_4 = new DecimalFormat( "#.####" );
63 private double _gap_ratio = -1;
64 private final short _longest_id_length;
66 private String _maffts_opts = "--auto";
67 private int _min_length = -1;
69 private DeleteableMsa _msa = null;
70 private boolean _norm = true;
71 private File _out_file_base = null;
72 private MSA_FORMAT _output_format = MSA_FORMAT.FASTA;
73 private String _path_to_mafft = null;
75 private boolean _realign = false;
76 private final SortedSet<String> _removed_seq_ids;
77 private final ArrayList<Sequence> _removed_seqs;
78 private File _removed_seqs_out_base = null;
79 private boolean _report_aln_mean_identity = false;
80 private int _step = -1;
81 private int _step_for_diagnostics = -1;
83 NF_4.setRoundingMode( RoundingMode.HALF_UP );
84 NF_3.setRoundingMode( RoundingMode.HALF_UP );
87 public MsaCompactor( final DeleteableMsa msa ) {
89 _removed_seq_ids = new TreeSet<String>();
90 _longest_id_length = _msa.determineMaxIdLength();
91 _removed_seqs = new ArrayList<Sequence>();
94 public final List<MsaProperties> chart( final int step, final boolean realign, final boolean norm )
95 throws IOException, InterruptedException {
96 final GapContribution stats[] = calcGapContribtionsStats( norm );
97 final List<String> to_remove_ids = new ArrayList<String>();
98 final List<MsaProperties> msa_props = new ArrayList<MsaProperties>();
99 for( final GapContribution gap_gontribution : stats ) {
100 to_remove_ids.add( gap_gontribution.getId() );
102 final boolean print_id = ( _step < 2 ) && ( _step_for_diagnostics < 2 );
103 printTableHeader( print_id );
104 int x = ForesterUtil.roundToInt( _msa.getNumberOfSequences() / 20.0 );
108 MsaProperties msa_prop = new MsaProperties( _msa, _report_aln_mean_identity );
109 msa_props.add( msa_prop );
110 printMsaProperties( "", msa_prop );
111 System.out.println();
113 while ( _msa.getNumberOfSequences() > x ) {
114 final String id = to_remove_ids.get( i );
115 _msa.deleteRow( id, false );
116 if ( realign && isPrintMsaStatsWriteOutfileAndRealign( i ) ) {
119 msa_prop = new MsaProperties( _msa, _report_aln_mean_identity );
120 msa_props.add( msa_prop );
121 printMsaProperties( id, msa_prop );
122 System.out.print( "(realigned)" );
123 System.out.println();
125 else if ( isPrintMsaStats( i ) ) {
127 msa_prop = new MsaProperties( _msa, _report_aln_mean_identity );
128 msa_props.add( msa_prop );
129 printMsaProperties( id, msa_prop );
130 System.out.println();
137 final public Msa getMsa() {
141 final public SortedSet<String> getRemovedSeqIds() {
142 return _removed_seq_ids;
145 public final List<MsaProperties> removeViaGapAverage( final double mean_gapiness ) throws IOException,
146 InterruptedException {
147 final GapContribution stats[] = calcGapContribtionsStats( _norm );
148 final List<String> to_remove_ids = new ArrayList<String>();
149 final List<MsaProperties> msa_props = new ArrayList<MsaProperties>();
150 for( final GapContribution gap_gontribution : stats ) {
151 to_remove_ids.add( gap_gontribution.getId() );
153 final boolean print_id = ( _step < 2 ) || ( _step_for_diagnostics < 2 );
154 printTableHeader( print_id );
155 MsaProperties msa_prop = new MsaProperties( _msa, _report_aln_mean_identity );
156 msa_props.add( msa_prop );
157 printMsaProperties( "", msa_prop );
158 System.out.println();
160 while ( MsaMethods.calcGapRatio( _msa ) > mean_gapiness ) {
161 final String id = to_remove_ids.get( i );
162 _removed_seq_ids.add( id );
163 final Sequence deleted = _msa.deleteRow( id, true );
164 _removed_seqs.add( deleted );
166 if ( isPrintMsaStatsWriteOutfileAndRealign( i ) || ( MsaMethods.calcGapRatio( _msa ) <= mean_gapiness ) ) {
167 msa_prop = printMsaStatsWriteOutfileAndRealign( _realign, id );
168 msa_props.add( msa_prop );
169 System.out.println();
171 else if ( isPrintMsaStats( i ) ) {
172 msa_prop = new MsaProperties( _msa, _report_aln_mean_identity );
173 msa_props.add( msa_prop );
174 printMsaProperties( id, msa_prop );
175 System.out.println();
179 if ( _removed_seqs_out_base != null ) {
180 final String msg = writeAndAlignRemovedSeqs();
181 System.out.println();
182 System.out.println( msg );
187 public List<MsaProperties> removeViaLength( final int length ) throws IOException, InterruptedException {
188 final GapContribution stats[] = calcGapContribtionsStats( _norm );
189 final List<String> to_remove_ids = new ArrayList<String>();
190 final List<MsaProperties> msa_props = new ArrayList<MsaProperties>();
191 for( final GapContribution gap_gontribution : stats ) {
192 to_remove_ids.add( gap_gontribution.getId() );
194 final boolean print_id = ( _step < 2 ) || ( _step_for_diagnostics < 2 );
195 printTableHeader( print_id );
196 MsaProperties msa_prop = new MsaProperties( _msa, _report_aln_mean_identity );
197 msa_props.add( msa_prop );
198 printMsaProperties( "", msa_prop );
199 System.out.println();
201 while ( _msa.getLength() > length ) {
202 final String id = to_remove_ids.get( i );
203 _removed_seq_ids.add( id );
204 final Sequence deleted = _msa.deleteRow( id, true );
205 _removed_seqs.add( deleted );
207 if ( isPrintMsaStatsWriteOutfileAndRealign( i ) || ( _msa.getLength() <= length ) ) {
208 msa_prop = printMsaStatsWriteOutfileAndRealign( _realign, id );
209 msa_props.add( msa_prop );
210 System.out.println();
212 else if ( isPrintMsaStats( i ) ) {
213 msa_prop = new MsaProperties( _msa, _report_aln_mean_identity );
214 printMsaProperties( id, msa_prop );
215 msa_props.add( msa_prop );
216 System.out.println();
220 if ( _removed_seqs_out_base != null ) {
221 final String msg = writeAndAlignRemovedSeqs();
222 System.out.println();
223 System.out.println( msg );
228 public final void removeSequencesByMinimalLength( final int min_effective_length ) {
229 printMsaProperties( "", new MsaProperties( _msa, _report_aln_mean_identity ) );
230 System.out.println();
231 _msa = DeleteableMsa.createInstance( MsaMethods.removeSequencesByMinimalLength( _msa, min_effective_length ) );
233 printMsaProperties( "", new MsaProperties( _msa, _report_aln_mean_identity ) );
234 System.out.println();
237 public final List<MsaProperties> removeWorstOffenders( final int to_remove ) throws IOException,
238 InterruptedException {
239 final GapContribution stats[] = calcGapContribtionsStats( _norm );
240 final List<String> to_remove_ids = new ArrayList<String>();
241 final List<MsaProperties> msa_props = new ArrayList<MsaProperties>();
242 for( int j = 0; j < to_remove; ++j ) {
243 to_remove_ids.add( stats[ j ].getId() );
244 _removed_seq_ids.add( stats[ j ].getId() );
246 final boolean print_id = ( _step < 2 ) || ( _step_for_diagnostics < 2 );
247 printTableHeader( print_id );
248 MsaProperties msa_prop = new MsaProperties( _msa, _report_aln_mean_identity );
249 msa_props.add( msa_prop );
250 printMsaProperties( "", msa_prop );
251 System.out.println();
252 for( int i = 0; i < to_remove_ids.size(); ++i ) {
253 final String id = to_remove_ids.get( i );
254 _removed_seq_ids.add( id );
255 final Sequence deleted = _msa.deleteRow( id, true );
256 _removed_seqs.add( deleted );
258 if ( isPrintMsaStatsWriteOutfileAndRealign( i ) || ( i == ( to_remove_ids.size() - 1 ) ) ) {
259 msa_prop = printMsaStatsWriteOutfileAndRealign( _realign, id );
260 msa_props.add( msa_prop );
261 System.out.println();
263 else if ( isPrintMsaStats( i ) ) {
264 msa_prop = new MsaProperties( _msa, _report_aln_mean_identity );
265 msa_props.add( msa_prop );
266 printMsaProperties( id, msa_prop );
267 System.out.println();
270 if ( _removed_seqs_out_base != null ) {
271 final String msg = writeAndAlignRemovedSeqs();
272 System.out.println();
273 System.out.println( msg );
278 final public void deleteGapColumns( final double max_allowed_gap_ratio ) {
279 _msa.deleteGapColumns( max_allowed_gap_ratio );
282 public final void setGapRatio( final double gap_ratio ) {
283 _gap_ratio = gap_ratio;
286 public final void setMafftOptions( final String maffts_opts ) {
287 _maffts_opts = maffts_opts;
290 public final void setMinLength( final int min_length ) {
291 _min_length = min_length;
294 public final void setNorm( final boolean norm ) {
298 final public void setOutFileBase( final File out_file_base ) {
299 _out_file_base = out_file_base;
302 public final void setOutputFormat( final MSA_FORMAT output_format ) {
303 _output_format = output_format;
306 public void setPathToMafft( final String path_to_mafft ) {
307 _path_to_mafft = path_to_mafft;
310 public final void setRealign( final boolean realign ) {
314 public final void setRemovedSeqsOutBase( final File removed_seqs_out_base ) {
315 _removed_seqs_out_base = removed_seqs_out_base;
318 public final void setReportAlnMeanIdentity( final boolean report_aln_mean_identity ) {
319 _report_aln_mean_identity = report_aln_mean_identity;
322 public final void setStep( final int step ) {
326 public final void setStepForDiagnostics( final int step_for_diagnostics ) {
327 _step_for_diagnostics = step_for_diagnostics;
330 final public String writeAndAlignRemovedSeqs() throws IOException, InterruptedException {
331 final StringBuilder msg = new StringBuilder();
332 final String n = _removed_seqs_out_base + "_" + _removed_seqs.size() + ".fasta";
333 SequenceWriter.writeSeqs( _removed_seqs, new File( n ), SEQ_FORMAT.FASTA, 100 );
334 msg.append( "wrote " + _removed_seqs.size() + " removed sequences to " + "\"" + n + "\"" );
336 final MsaInferrer mafft = Mafft.createInstance( _path_to_mafft );
337 final List<String> opts = new ArrayList<String>();
338 for( final String o : _maffts_opts.split( "\\s" ) ) {
341 final Msa removed_msa = mafft.infer( _removed_seqs, opts );
342 final Double gr = MsaMethods.calcGapRatio( removed_msa );
343 String s = _removed_seqs_out_base + "_" + removed_msa.getNumberOfSequences() + "_"
344 + removed_msa.getLength() + "_" + ForesterUtil.roundToInt( gr * 100 );
345 final String suffix = obtainSuffix();
347 writeMsa( removed_msa, s, _output_format );
348 msg.append( ", and as MSA of length " + removed_msa.getLength() + " to \"" + s + "\"" );
350 return msg.toString();
353 final public String writeMsa( final File outfile ) throws IOException {
354 final Double gr = MsaMethods.calcGapRatio( _msa );
355 final String s = outfile + "_" + _msa.getNumberOfSequences() + "_" + _msa.getLength() + "_"
356 + ForesterUtil.roundToInt( gr * 100 );
357 writeMsa( _msa, s + obtainSuffix(), _output_format );
361 final int calcNonGapResidues( final Sequence seq ) {
363 for( int i = 0; i < seq.getLength(); ++i ) {
364 if ( !seq.isGapAt( i ) ) {
371 private final GapContribution[] calcGapContribtions( final boolean normalize_for_effective_seq_length ) {
372 final double gappiness[] = calcGappiness();
373 final GapContribution stats[] = new GapContribution[ _msa.getNumberOfSequences() ];
374 for( int row = 0; row < _msa.getNumberOfSequences(); ++row ) {
375 stats[ row ] = new GapContribution( _msa.getIdentifier( row ) );
376 for( int col = 0; col < _msa.getLength(); ++col ) {
377 if ( !_msa.isGapAt( row, col ) ) {
378 stats[ row ].addToValue( gappiness[ col ] );
381 if ( normalize_for_effective_seq_length ) {
382 stats[ row ].divideValue( calcNonGapResidues( _msa.getSequence( row ) ) );
385 stats[ row ].divideValue( _msa.getLength() );
391 final private GapContribution[] calcGapContribtionsStats( final boolean norm ) {
392 final GapContribution stats[] = calcGapContribtions( norm );
393 Arrays.sort( stats );
397 private final double[] calcGappiness() {
398 final int l = _msa.getLength();
399 final double gappiness[] = new double[ l ];
400 final int seqs = _msa.getNumberOfSequences();
401 for( int i = 0; i < l; ++i ) {
402 gappiness[ i ] = ( double ) MsaMethods.calcGapSumPerColumn( _msa, i ) / seqs;
407 private final Phylogeny inferNJphylogeny( final PWD_DISTANCE_METHOD pwd_distance_method,
409 final boolean write_matrix,
410 final String matrix_name ) {
411 BasicSymmetricalDistanceMatrix m = null;
412 switch ( pwd_distance_method ) {
413 case KIMURA_DISTANCE:
414 m = PairwiseDistanceCalculator.calcKimuraDistances( msa );
416 case POISSON_DISTANCE:
417 m = PairwiseDistanceCalculator.calcPoissonDistances( msa );
419 case FRACTIONAL_DISSIMILARITY:
420 m = PairwiseDistanceCalculator.calcFractionalDissimilarities( msa );
423 throw new IllegalArgumentException( "invalid pwd method" );
425 if ( write_matrix ) {
427 m.write( ForesterUtil.createBufferedWriter( matrix_name ) );
429 catch ( final IOException e ) {
433 final NeighborJoiningF nj = NeighborJoiningF.createInstance( false, 5 );
434 final Phylogeny phy = nj.execute( m );
438 private final boolean isPrintMsaStats( final int i ) {
439 return ( ( ( _step < 2 ) && ( _step_for_diagnostics < 2 ) ) || ( ( _step_for_diagnostics > 0 ) && ( ( ( i + 1 ) % _step_for_diagnostics ) == 0 ) ) );
442 private final boolean isPrintMsaStatsWriteOutfileAndRealign( final int i ) {
443 return ( ( ( _step < 2 ) && ( _step_for_diagnostics < 2 ) ) || ( ( _step > 0 ) && ( ( ( i + 1 ) % _step ) == 0 ) ) );
446 private final StringBuilder msaPropertiesAsSB( final MsaProperties msa_properties ) {
447 final StringBuilder sb = new StringBuilder();
448 sb.append( msa_properties.getNumberOfSequences() );
450 sb.append( msa_properties.getLength() );
452 sb.append( NF_4.format( msa_properties.getGapRatio() ) );
453 if ( _report_aln_mean_identity ) {
455 sb.append( NF_4.format( msa_properties.getAverageIdentityRatio() ) );
460 private String obtainSuffix() {
461 if ( _output_format == MSA_FORMAT.FASTA ) {
464 else if ( _output_format == MSA_FORMAT.PHYLIP ) {
470 private final Phylogeny pi( final String matrix ) {
471 final Phylogeny master_phy = inferNJphylogeny( PWD_DISTANCE_METHOD.KIMURA_DISTANCE, _msa, true, matrix );
474 final ResampleableMsa resampleable_msa = new ResampleableMsa( _msa );
475 final int[][] resampled_column_positions = BootstrapResampler.createResampledColumnPositions( _msa.getLength(),
478 final Phylogeny[] eval_phys = new Phylogeny[ n ];
479 for( int i = 0; i < n; ++i ) {
480 resampleable_msa.resample( resampled_column_positions[ i ] );
481 eval_phys[ i ] = inferNJphylogeny( PWD_DISTANCE_METHOD.KIMURA_DISTANCE, resampleable_msa, false, null );
483 ConfidenceAssessor.evaluate( "bootstrap", eval_phys, master_phy, true, 1 );
484 PhylogenyMethods.extractFastaInformation( master_phy );
488 private final void printMsaProperties( final String id, final MsaProperties msa_properties ) {
489 if ( ( _step < 2 ) || ( _step_for_diagnostics < 2 ) ) {
490 System.out.print( ForesterUtil.pad( id, _longest_id_length, ' ', false ) );
491 System.out.print( "\t" );
493 System.out.print( msaPropertiesAsSB( msa_properties ) );
494 System.out.print( "\t" );
497 final private MsaProperties printMsaStatsWriteOutfileAndRealign( final boolean realign, final String id )
498 throws IOException, InterruptedException {
502 final MsaProperties msa_prop = new MsaProperties( _msa, _report_aln_mean_identity );
503 printMsaProperties( id, msa_prop );
504 final String s = writeOutfile();
505 System.out.print( "-> " + s + ( realign ? "\t(realigned)" : "" ) );
509 private final void printTableHeader( final boolean print_id ) {
511 System.out.print( ForesterUtil.pad( "Id", _longest_id_length, ' ', false ) );
512 System.out.print( "\t" );
514 System.out.print( "Seqs" );
515 System.out.print( "\t" );
516 System.out.print( "Length" );
517 System.out.print( "\t" );
518 System.out.print( "Gaps" );
519 System.out.print( "\t" );
520 if ( _report_aln_mean_identity ) {
521 System.out.print( "MSA qual" );
522 System.out.print( "\t" );
524 System.out.println();
527 final private void realignWithMafft() throws IOException, InterruptedException {
528 final MsaInferrer mafft = Mafft.createInstance( _path_to_mafft );
529 final List<String> opts = new ArrayList<String>();
530 for( final String o : _maffts_opts.split( "\\s" ) ) {
533 _msa = DeleteableMsa.createInstance( mafft.infer( _msa.asSequenceList(), opts ) );
536 final private void removeGapColumns() {
537 _msa.deleteGapOnlyColumns();
540 private final String writeOutfile() throws IOException {
541 final String s = writeMsa( _out_file_base );
545 // Returns null if not path found.
546 final public static String guessPathToMafft() {
548 if ( ForesterUtil.OS_NAME.toLowerCase().indexOf( "win" ) >= 0 ) {
549 path = "C:\\Program Files\\mafft-win\\mafft.bat";
550 if ( MsaInferrer.isInstalled( path ) ) {
554 path = "/home/czmasek/SOFTWARE/MSA/MAFFT/mafft-7.130-without-extensions/scripts/mafft";
555 if ( MsaInferrer.isInstalled( path ) ) {
558 path = "/usr/local/bin/mafft";
559 if ( MsaInferrer.isInstalled( path ) ) {
562 path = "/usr/bin/mafft";
563 if ( MsaInferrer.isInstalled( path ) ) {
567 if ( MsaInferrer.isInstalled( path ) ) {
571 if ( MsaInferrer.isInstalled( path ) ) {
577 final private static void writeMsa( final Msa msa, final String outfile, final MSA_FORMAT format )
579 final Writer w = ForesterUtil.createBufferedWriter( outfile );
580 msa.write( w, format );