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.msa.BasicMsa;
45 import org.forester.msa.DeleteableMsa;
46 import org.forester.msa.Mafft;
47 import org.forester.msa.Msa;
48 import org.forester.msa.Msa.MSA_FORMAT;
49 import org.forester.msa.MsaInferrer;
50 import org.forester.msa.MsaMethods;
51 import org.forester.msa.ResampleableMsa;
52 import org.forester.phylogeny.Phylogeny;
53 import org.forester.phylogeny.PhylogenyMethods;
54 import org.forester.sequence.Sequence;
55 import org.forester.tools.ConfidenceAssessor;
56 import org.forester.util.ForesterUtil;
58 public class MsaCompactor {
60 final private static NumberFormat NF_3 = new DecimalFormat( "#.###" );
61 final private static NumberFormat NF_4 = new DecimalFormat( "#.####" );
62 private double _gap_ratio = -1;
64 private final String _maffts_opts = "--auto";
65 private int _min_length = -1;
67 private DeleteableMsa _msa = null;
68 private boolean _norm = true;
69 private File _out_file_base = null;
70 private MSA_FORMAT _output_format = MSA_FORMAT.FASTA;
71 private String _path_to_mafft = null;
73 private boolean _realign = false;
74 private final SortedSet<String> _removed_seq_ids;
75 private final File _removed_seqs_out_base = null;
76 private boolean _report_aln_mean_identity = false;
77 private int _step = -1;
78 private int _step_for_diagnostics = -1;
79 private final short _longest_id_length;
80 private final ArrayList<Sequence> _removed_seqs;
82 NF_4.setRoundingMode( RoundingMode.HALF_UP );
83 NF_3.setRoundingMode( RoundingMode.HALF_UP );
86 public MsaCompactor( final DeleteableMsa msa ) {
88 _removed_seq_ids = new TreeSet<String>();
89 _longest_id_length = _msa.determineMaxIdLength();
90 _removed_seqs = new ArrayList<Sequence>();
93 final public Msa getMsa() {
97 final public SortedSet<String> getRemovedSeqIds() {
98 return _removed_seq_ids;
101 public final void removeViaGapAverage( final double mean_gapiness ) throws IOException, InterruptedException {
102 final GapContribution stats[] = calcGapContribtionsStats( _norm );
103 final List<String> to_remove_ids = new ArrayList<String>();
104 for( final GapContribution gap_gontribution : stats ) {
105 to_remove_ids.add( gap_gontribution.getId() );
109 while ( MsaMethods.calcGapRatio( _msa ) > mean_gapiness ) {
110 final String id = to_remove_ids.get( i );
111 _removed_seq_ids.add( id );
112 final Sequence deleted = _msa.deleteRow( id );
113 _removed_seqs.add( deleted );
115 if ( ( ( _step > 0 ) && ( ( ( i + 1 ) % _step ) == 0 ) )
116 || ( MsaMethods.calcGapRatio( _msa ) <= mean_gapiness ) ) {
117 printMsaStatsWriteOutfileAndRealign( _realign, id );
120 final MsaProperties msa_prop = new MsaProperties( _msa, _report_aln_mean_identity );
121 printMsaProperties( id, msa_prop );
123 System.out.println();
126 final String msg = writeAndAlignRemovedSeqs();
127 System.out.println( msg );
130 public void removeViaLength( final int length ) throws IOException, InterruptedException {
131 final GapContribution stats[] = calcGapContribtionsStats( _norm );
132 final List<String> to_remove_ids = new ArrayList<String>();
133 for( final GapContribution gap_gontribution : stats ) {
134 to_remove_ids.add( gap_gontribution.getId() );
138 while ( _msa.getLength() > length ) {
139 final String id = to_remove_ids.get( i );
140 _removed_seq_ids.add( id );
141 final Sequence deleted = _msa.deleteRow( id );
142 _removed_seqs.add( deleted );
144 if ( ( ( _step > 0 ) && ( ( ( i + 1 ) % _step ) == 0 ) ) || ( _msa.getLength() <= length ) ) {
145 printMsaStatsWriteOutfileAndRealign( _realign, id );
147 final MsaProperties msa_prop = new MsaProperties( _msa, _report_aln_mean_identity );
148 printMsaProperties( id, msa_prop );
149 System.out.println();
152 final String msg = writeAndAlignRemovedSeqs();
153 System.out.println( msg );
156 public final void removeWorstOffenders( final int to_remove ) throws IOException, InterruptedException {
157 final GapContribution stats[] = calcGapContribtionsStats( _norm );
158 final List<String> to_remove_ids = new ArrayList<String>();
159 for( int j = 0; j < to_remove; ++j ) {
160 to_remove_ids.add( stats[ j ].getId() );
161 _removed_seq_ids.add( stats[ j ].getId() );
164 for( int i = 0; i < to_remove_ids.size(); ++i ) {
165 final String id = to_remove_ids.get( i );
166 _removed_seq_ids.add( id );
167 final Sequence deleted = _msa.deleteRow( id );
168 _removed_seqs.add( deleted );
170 if ( isPrintMsaStatsWriteOutfileAndRealign( i ) || ( i == ( to_remove_ids.size() - 1 ) ) ) {
171 printMsaStatsWriteOutfileAndRealign( _realign, id );
172 System.out.println();
174 else if ( isPrintMsaStats( i ) ) {
175 final MsaProperties msa_prop = new MsaProperties( _msa, _report_aln_mean_identity );
176 printMsaProperties( id, msa_prop );
177 System.out.println();
180 final String msg = writeAndAlignRemovedSeqs();
181 System.out.println( msg );
184 public final List<MsaProperties> chart( final int step, final boolean realign, final boolean norm )
185 throws IOException, InterruptedException {
186 final GapContribution stats[] = calcGapContribtionsStats( norm );
187 final List<String> to_remove_ids = new ArrayList<String>();
188 final List<MsaProperties> msa_props = new ArrayList<MsaProperties>();
189 for( final GapContribution gap_gontribution : stats ) {
190 to_remove_ids.add( gap_gontribution.getId() );
194 final int x = ForesterUtil.roundToInt( _msa.getNumberOfSequences() / 20.0 );
195 MsaProperties msa_prop = new MsaProperties( _msa, _report_aln_mean_identity );
196 msa_props.add( msa_prop );
197 printMsaProperties( "", msa_prop );
198 System.out.println();
199 while ( _msa.getNumberOfSequences() > x ) {
200 final String id = to_remove_ids.get( i );
201 _msa.deleteRow( id );
202 if ( realign && isPrintMsaStatsWriteOutfileAndRealign( i ) ) {
205 msa_prop = new MsaProperties( _msa, _report_aln_mean_identity );
206 msa_props.add( msa_prop );
207 printMsaProperties( id, msa_prop );
208 System.out.print( "(realigned)" );
209 System.out.println();
211 else if ( isPrintMsaStats( i ) ) {
213 msa_prop = new MsaProperties( _msa, _report_aln_mean_identity );
214 msa_props.add( msa_prop );
215 printMsaProperties( id, msa_prop );
216 System.out.println();
223 private final boolean isPrintMsaStats( final int i ) {
224 return ( ( _step_for_diagnostics < 2 ) || ( ( ( i + 1 ) % _step_for_diagnostics ) == 0 ) );
227 private final boolean isPrintMsaStatsWriteOutfileAndRealign( final int i ) {
228 return ( ( _step < 2 ) || ( ( ( i + 1 ) % _step ) == 0 ) );
231 public final void setGapRatio( final double gap_ratio ) {
232 _gap_ratio = gap_ratio;
235 public final void setMinLength( final int min_length ) {
236 _min_length = min_length;
239 public final void setNorm( final boolean norm ) {
243 final public void setOutFileBase( final File out_file_base ) {
244 _out_file_base = out_file_base;
247 public final void setOutputFormat( final MSA_FORMAT output_format ) {
248 _output_format = output_format;
251 public void setPathToMafft( final String path_to_mafft ) {
252 _path_to_mafft = path_to_mafft;
255 public final void setRealign( final boolean realign ) {
259 public final void setStep( final int step ) {
263 public final void setStepForDiagnostics( final int step_for_diagnostics ) {
264 _step_for_diagnostics = step_for_diagnostics;
267 public final void setReportAlnMeanIdentity( final boolean report_aln_mean_identity ) {
268 _report_aln_mean_identity = report_aln_mean_identity;
271 final public String writeMsa( final File outfile, final MSA_FORMAT format, final String suffix ) throws IOException {
272 final Double gr = MsaMethods.calcGapRatio( _msa );
273 final String s = outfile + "_" + _msa.getNumberOfSequences() + "_" + _msa.getLength() + "_"
274 + ForesterUtil.roundToInt( gr * 100 );
275 writeMsa( _msa, s + suffix, format );
279 final public String writeAndAlignRemovedSeqs() throws IOException, InterruptedException {
280 final StringBuilder msg = new StringBuilder();
281 final Msa removed = BasicMsa.createInstance( _removed_seqs );
282 final String n = _removed_seqs_out_base + "_" + removed.getNumberOfSequences() + ".fasta";
283 writeMsa( removed, n, MSA_FORMAT.FASTA );
284 msg.append( "wrote " + removed.getNumberOfSequences() + " removed sequences to " + n );
286 final MsaInferrer mafft = Mafft.createInstance( _path_to_mafft );
287 final List<String> opts = new ArrayList<String>();
288 for( final String o : _maffts_opts.split( "\\s" ) ) {
291 final Msa removed_msa = mafft.infer( _removed_seqs, opts );
292 final Double gr = MsaMethods.calcGapRatio( removed_msa );
293 String s = _removed_seqs_out_base + "_" + removed_msa.getNumberOfSequences() + "_"
294 + removed_msa.getLength() + "_" + ForesterUtil.roundToInt( gr * 100 );
296 if ( _output_format == MSA_FORMAT.FASTA ) {
299 else if ( _output_format == MSA_FORMAT.PHYLIP ) {
303 writeMsa( removed_msa, s, _output_format );
304 msg.append( ", and as MSA of length " + removed_msa.getLength() + " to " + s );
306 return msg.toString();
309 final int calcNonGapResidues( final Sequence seq ) {
311 for( int i = 0; i < seq.getLength(); ++i ) {
312 if ( !seq.isGapAt( i ) ) {
319 private final GapContribution[] calcGapContribtions( final boolean normalize_for_effective_seq_length ) {
320 final double gappiness[] = calcGappiness();
321 final GapContribution stats[] = new GapContribution[ _msa.getNumberOfSequences() ];
322 for( int row = 0; row < _msa.getNumberOfSequences(); ++row ) {
323 stats[ row ] = new GapContribution( _msa.getIdentifier( row ) );
324 for( int col = 0; col < _msa.getLength(); ++col ) {
325 if ( !_msa.isGapAt( row, col ) ) {
326 stats[ row ].addToValue( gappiness[ col ] );
329 if ( normalize_for_effective_seq_length ) {
330 stats[ row ].divideValue( calcNonGapResidues( _msa.getSequence( row ) ) );
333 stats[ row ].divideValue( _msa.getLength() );
339 final private GapContribution[] calcGapContribtionsStats( final boolean norm ) {
340 final GapContribution stats[] = calcGapContribtions( norm );
341 Arrays.sort( stats );
345 private final double[] calcGappiness() {
346 final int l = _msa.getLength();
347 final double gappiness[] = new double[ l ];
348 final int seqs = _msa.getNumberOfSequences();
349 for( int i = 0; i < l; ++i ) {
350 gappiness[ i ] = ( double ) MsaMethods.calcGapSumPerColumn( _msa, i ) / seqs;
355 private final Phylogeny inferNJphylogeny( final PWD_DISTANCE_METHOD pwd_distance_method,
357 final boolean write_matrix,
358 final String matrix_name ) {
359 BasicSymmetricalDistanceMatrix m = null;
360 switch ( pwd_distance_method ) {
361 case KIMURA_DISTANCE:
362 m = PairwiseDistanceCalculator.calcKimuraDistances( msa );
364 case POISSON_DISTANCE:
365 m = PairwiseDistanceCalculator.calcPoissonDistances( msa );
367 case FRACTIONAL_DISSIMILARITY:
368 m = PairwiseDistanceCalculator.calcFractionalDissimilarities( msa );
371 throw new IllegalArgumentException( "invalid pwd method" );
373 if ( write_matrix ) {
375 m.write( ForesterUtil.createBufferedWriter( matrix_name ) );
377 catch ( final IOException e ) {
381 final NeighborJoiningF nj = NeighborJoiningF.createInstance( false, 5 );
382 final Phylogeny phy = nj.execute( m );
386 private final Phylogeny pi( final String matrix ) {
387 final Phylogeny master_phy = inferNJphylogeny( PWD_DISTANCE_METHOD.KIMURA_DISTANCE, _msa, true, matrix );
390 final ResampleableMsa resampleable_msa = new ResampleableMsa( _msa );
391 final int[][] resampled_column_positions = BootstrapResampler.createResampledColumnPositions( _msa.getLength(),
394 final Phylogeny[] eval_phys = new Phylogeny[ n ];
395 for( int i = 0; i < n; ++i ) {
396 resampleable_msa.resample( resampled_column_positions[ i ] );
397 eval_phys[ i ] = inferNJphylogeny( PWD_DISTANCE_METHOD.KIMURA_DISTANCE, resampleable_msa, false, null );
399 ConfidenceAssessor.evaluate( "bootstrap", eval_phys, master_phy, true, 1 );
400 PhylogenyMethods.extractFastaInformation( master_phy );
404 private final void printMsaProperties( final String id, final MsaProperties msa_properties ) {
405 System.out.print( ForesterUtil.pad( _longest_id_length + 1, 20, ' ', false ) );
406 System.out.print( "\t" );
407 final StringBuilder sb = msaPropertiesAsSB( msa_properties );
408 System.out.print( sb );
409 System.out.print( "\t" );
412 private final StringBuilder msaPropertiesAsSB( final MsaProperties msa_properties ) {
413 final StringBuilder sb = new StringBuilder();
414 sb.append( msa_properties.getNumberOfSequences() );
416 sb.append( msa_properties.getLength() );
418 sb.append( NF_4.format( msa_properties.getGapRatio() ) );
419 if ( _report_aln_mean_identity /*msa_properties.getAverageIdentityRatio() >= 0*/) {
421 sb.append( NF_4.format( msa_properties.getAverageIdentityRatio() ) );
426 final private void printMsaStatsWriteOutfileAndRealign( final boolean realign, final String id )
427 throws IOException, InterruptedException {
431 final MsaProperties msa_prop = new MsaProperties( _msa, _report_aln_mean_identity );
432 printMsaProperties( id, msa_prop );
433 final String s = writeOutfile();
434 System.out.print( "-> " + s + ( realign ? "\t(realigned)" : "" ) );
437 final private void realignWithMafft() throws IOException, InterruptedException {
438 final MsaInferrer mafft = Mafft.createInstance( _path_to_mafft );
439 final List<String> opts = new ArrayList<String>();
440 for( final String o : _maffts_opts.split( "\\s" ) ) {
443 _msa = DeleteableMsa.createInstance( mafft.infer( _msa.asSequenceList(), opts ) );
446 final private void removeGapColumns() {
447 _msa.deleteGapOnlyColumns();
450 final private static void writeMsa( final Msa msa, final String outfile, final MSA_FORMAT format )
452 final Writer w = ForesterUtil.createBufferedWriter( outfile );
453 msa.write( w, format );
457 private final String writeOutfile() throws IOException {
458 final String s = writeMsa( _out_file_base, MSA_FORMAT.PHYLIP, ".aln" );
459 //writeMsa( _out_file_base, MSA_FORMAT.FASTA, ".fasta" );
463 // Returns null if not path found.
464 final public static String guessPathToMafft() {
466 if ( ForesterUtil.OS_NAME.toLowerCase().indexOf( "win" ) >= 0 ) {
467 path = "C:\\Program Files\\mafft-win\\mafft.bat";
468 if ( MsaInferrer.isInstalled( path ) ) {
472 path = "/home/czmasek/SOFTWARE/MSA/MAFFT/mafft-7.130-without-extensions/scripts/mafft";
473 if ( MsaInferrer.isInstalled( path ) ) {
476 path = "/usr/local/bin/mafft";
477 if ( MsaInferrer.isInstalled( path ) ) {
480 path = "/usr/bin/mafft";
481 if ( MsaInferrer.isInstalled( path ) ) {
485 if ( MsaInferrer.isInstalled( path ) ) {
489 if ( MsaInferrer.isInstalled( path ) ) {
495 private final void printTableHeader() {
496 System.out.print( ForesterUtil.pad( "Id", _longest_id_length + 1, ' ', false ) );
497 System.out.print( "\t" );
498 System.out.print( "Seqs" );
499 System.out.print( "\t" );
500 System.out.print( "Length" );
501 System.out.print( "\t" );
502 System.out.print( "Gaps" );
503 System.out.print( "\t" );
504 if ( _report_aln_mean_identity ) {
505 System.out.print( "MSA qual" );
506 System.out.print( "\t" );
508 System.out.println();