7f652691f54e67a0b7a7c38656044a9123f84944
[jalview.git] / forester / java / src / org / forester / application / msa_compactor.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.application;
26
27 import java.io.File;
28 import java.io.FileInputStream;
29 import java.io.IOException;
30 import java.math.RoundingMode;
31 import java.text.DecimalFormat;
32 import java.text.NumberFormat;
33 import java.util.ArrayList;
34 import java.util.List;
35
36 import org.forester.io.parsers.FastaParser;
37 import org.forester.io.parsers.GeneralMsaParser;
38 import org.forester.msa.DeleteableMsa;
39 import org.forester.msa.Msa.MSA_FORMAT;
40 import org.forester.msa.MsaInferrer;
41 import org.forester.msa.MsaMethods;
42 import org.forester.msa_compactor.Chart;
43 import org.forester.msa_compactor.MsaCompactor;
44 import org.forester.msa_compactor.MsaProperties;
45 import org.forester.util.CommandLineArguments;
46 import org.forester.util.DescriptiveStatistics;
47 import org.forester.util.ForesterUtil;
48
49 public class msa_compactor {
50
51     final private static NumberFormat NF_1                                   = new DecimalFormat( "#.0" );
52     static {
53         NF_1.setRoundingMode( RoundingMode.HALF_UP );
54     }
55     final static private String       HELP_OPTION_1                          = "help";
56     final static private String       HELP_OPTION_2                          = "h";
57     final static private String       REMOVE_WORST_OFFENDERS_OPTION          = "r";
58     final static private String       AV_GAPINESS_OPTION                     = "g";
59     final static private String       STEP_OPTION                            = "s";
60     final static private String       LENGTH_OPTION                          = "l";
61     final static private String       REALIGN_OPTION                         = "a";
62     //
63     final static private String       STEP_FOR_DIAGNOSTICS_OPTION            = "sd";
64     final static private String       MIN_LENGTH_OPTION                      = "ml";
65     final static private String       GAP_RATIO_LENGTH_OPTION                = "gr";
66     final static private String       REPORT_ALN_MEAN_IDENTITY               = "q";
67     final static private String       OUTPUT_FORMAT_PHYLIP_OPTION            = "p";
68     final static private String       OUTPUT_REMOVED_SEQS_OPTION             = "ro";
69     final static private String       MAFFT_OPTIONS                          = "mo";
70     //        
71     final static private String       PATH_TO_MAFFT_OPTION                   = "mafft";
72     final static private String       DO_NOT_NORMALIZE_FOR_EFF_LENGTH_OPTION = "nn";
73     final static private String       PRG_NAME                               = "msa_compactor";
74     final static private String       PRG_DESC                               = "multiple sequence aligment compactor";
75     final static private String       PRG_VERSION                            = "0.2";
76     final static private String       PRG_DATE                               = "140428";
77     final static private String       E_MAIL                                 = "czmasek@sanfordburham.org";
78     final static private String       WWW                                    = "https://sites.google.com/site/cmzmasek/home/software/forester";
79
80     public static void main( final String args[] ) {
81         try {
82             final CommandLineArguments cla = new CommandLineArguments( args );
83             if ( cla.isOptionSet( HELP_OPTION_1 ) || cla.isOptionSet( HELP_OPTION_2 )
84                     || ( ( cla.getNumberOfNames() < 1 ) || ( cla.getNumberOfNames() > 2 ) ) ) {
85                 printHelp();
86                 System.exit( 0 );
87             }
88             final File in = cla.getFile( 0 );
89             File out = null;
90             if ( cla.getNumberOfNames() > 1 ) {
91                 out = cla.getFile( 1 );
92             }
93             int worst_remove = -1;
94             double av_gap = -1;
95             int length = -1;
96             int step = 1;
97             boolean realign = false;
98             boolean norm = true;
99             String path_to_mafft = null;
100             int step_for_diagnostics = 1;
101             int min_length = -1;
102             double gap_ratio = -1;
103             boolean report_aln_mean_identity = false;
104             MSA_FORMAT output_format = MSA_FORMAT.FASTA;
105             File removed_seqs_out_base = null;
106             String mafft_options = "--auto";
107             final List<String> allowed_options = new ArrayList<String>();
108             allowed_options.add( REMOVE_WORST_OFFENDERS_OPTION );
109             allowed_options.add( AV_GAPINESS_OPTION );
110             allowed_options.add( LENGTH_OPTION );
111             allowed_options.add( REALIGN_OPTION );
112             allowed_options.add( DO_NOT_NORMALIZE_FOR_EFF_LENGTH_OPTION );
113             allowed_options.add( STEP_OPTION );
114             allowed_options.add( PATH_TO_MAFFT_OPTION );
115             allowed_options.add( STEP_FOR_DIAGNOSTICS_OPTION );
116             allowed_options.add( MIN_LENGTH_OPTION );
117             allowed_options.add( GAP_RATIO_LENGTH_OPTION );
118             allowed_options.add( REPORT_ALN_MEAN_IDENTITY );
119             allowed_options.add( OUTPUT_FORMAT_PHYLIP_OPTION );
120             allowed_options.add( OUTPUT_REMOVED_SEQS_OPTION );
121             allowed_options.add( MAFFT_OPTIONS );
122             final String dissallowed_options = cla.validateAllowedOptionsAsString( allowed_options );
123             if ( dissallowed_options.length() > 0 ) {
124                 ForesterUtil.fatalError( PRG_NAME, "unknown option(s): " + dissallowed_options );
125             }
126             DeleteableMsa msa = null;
127             final FileInputStream is = new FileInputStream( in );
128             if ( FastaParser.isLikelyFasta( in ) ) {
129                 msa = DeleteableMsa.createInstance( FastaParser.parseMsa( is ) );
130             }
131             else {
132                 msa = DeleteableMsa.createInstance( GeneralMsaParser.parse( is ) );
133             }
134             final DescriptiveStatistics initial_msa_stats = MsaMethods.calculateEffectiveLengthStatistics( msa );
135             final boolean chart_only = ( !cla.isOptionSet( LENGTH_OPTION ) )
136                     && ( !cla.isOptionSet( REMOVE_WORST_OFFENDERS_OPTION ) )
137                     && ( !cla.isOptionSet( AV_GAPINESS_OPTION ) );
138             if ( !chart_only && ( out == null ) ) {
139                 ForesterUtil.fatalError( PRG_NAME, "outfile file missing" );
140             }
141             if ( cla.isOptionSet( REMOVE_WORST_OFFENDERS_OPTION ) ) {
142                 worst_remove = cla.getOptionValueAsInt( REMOVE_WORST_OFFENDERS_OPTION );
143                 if ( ( worst_remove < 1 ) || ( worst_remove >= msa.getNumberOfSequences() - 1 ) ) {
144                     ForesterUtil.fatalError( PRG_NAME, "number of worst offender sequences to remove is out of range: "
145                             + worst_remove );
146                 }
147             }
148             if ( cla.isOptionSet( AV_GAPINESS_OPTION ) ) {
149                 if ( cla.isOptionSet( REMOVE_WORST_OFFENDERS_OPTION ) ) {
150                     printHelp();
151                     System.exit( 0 );
152                 }
153                 av_gap = cla.getOptionValueAsDouble( AV_GAPINESS_OPTION );
154                 if ( ( av_gap < 0 ) || ( av_gap >= 1 ) ) {
155                     ForesterUtil.fatalError( PRG_NAME, "target gap-ratio is out of range: " + av_gap );
156                 }
157             }
158             if ( cla.isOptionSet( LENGTH_OPTION ) ) {
159                 if ( cla.isOptionSet( REMOVE_WORST_OFFENDERS_OPTION ) || cla.isOptionSet( AV_GAPINESS_OPTION ) ) {
160                     printHelp();
161                     System.exit( 0 );
162                 }
163                 length = cla.getOptionValueAsInt( LENGTH_OPTION );
164                 if ( length >= msa.getLength() ) {
165                     ForesterUtil.fatalError( PRG_NAME,
166                                              "target length is out of range [longer than MSA (" + msa.getLength()
167                                                      + ")]: " + length );
168                 }
169                 else if ( length < initial_msa_stats.getMin() ) {
170                     ForesterUtil.fatalError( PRG_NAME,
171                                              "target length is out of range [shorter than the shortest sequence ("
172                                                      + initial_msa_stats.getMin() + ") ]: " + length );
173                 }
174             }
175             if ( cla.isOptionSet( STEP_OPTION ) ) {
176                 step = cla.getOptionValueAsInt( STEP_OPTION );
177                 if ( ( step < 1 )
178                         || ( ( step > msa.getNumberOfSequences() ) || ( ( worst_remove > 0 ) && ( step > worst_remove ) ) ) ) {
179                     ForesterUtil.fatalError( PRG_NAME, "value for step is out of range: " + step );
180                 }
181             }
182             if ( cla.isOptionSet( REALIGN_OPTION ) ) {
183                 realign = true;
184             }
185             if ( cla.isOptionSet( PATH_TO_MAFFT_OPTION ) ) {
186                 if ( !realign ) {
187                     ForesterUtil.fatalError( PRG_NAME, "no need to indicate path to MAFFT without realigning" );
188                 }
189                 path_to_mafft = cla.getOptionValueAsCleanString( PATH_TO_MAFFT_OPTION );
190             }
191             if ( cla.isOptionSet( DO_NOT_NORMALIZE_FOR_EFF_LENGTH_OPTION ) ) {
192                 norm = false;
193             }
194             if ( cla.isOptionSet( STEP_FOR_DIAGNOSTICS_OPTION ) ) {
195                 step_for_diagnostics = cla.getOptionValueAsInt( STEP_FOR_DIAGNOSTICS_OPTION );
196                 if ( ( step_for_diagnostics < 1 )
197                         || ( ( step_for_diagnostics > msa.getNumberOfSequences() ) || ( ( worst_remove > 0 ) && ( step_for_diagnostics > worst_remove ) ) ) ) {
198                     ForesterUtil.fatalError( PRG_NAME, "value for diagnostic step is out of range: "
199                             + step_for_diagnostics );
200                 }
201             }
202             if ( cla.isOptionSet( MIN_LENGTH_OPTION ) ) {
203                 min_length = cla.getOptionValueAsInt( MIN_LENGTH_OPTION );
204                 if ( ( min_length < 2 ) || ( min_length > initial_msa_stats.getMax() ) ) {
205                     ForesterUtil.fatalError( PRG_NAME, "value for minimal sequence length is out of range: "
206                             + min_length );
207                 }
208             }
209             if ( cla.isOptionSet( GAP_RATIO_LENGTH_OPTION ) ) {
210                 gap_ratio = cla.getOptionValueAsDouble( GAP_RATIO_LENGTH_OPTION );
211                 if ( ( gap_ratio < 0 ) || ( gap_ratio > 1 ) ) {
212                     ForesterUtil.fatalError( PRG_NAME, "gap ratio is out of range: " + gap_ratio );
213                 }
214             }
215             if ( cla.isOptionSet( REPORT_ALN_MEAN_IDENTITY ) ) {
216                 report_aln_mean_identity = true;
217             }
218             if ( cla.isOptionSet( OUTPUT_FORMAT_PHYLIP_OPTION ) ) {
219                 output_format = MSA_FORMAT.PHYLIP;
220             }
221             if ( cla.isOptionSet( OUTPUT_REMOVED_SEQS_OPTION ) ) {
222                 final String s = cla.getOptionValueAsCleanString( OUTPUT_REMOVED_SEQS_OPTION );
223                 removed_seqs_out_base = new File( s );
224             }
225             if ( realign ) {
226                 if ( ForesterUtil.isEmpty( path_to_mafft ) ) {
227                     path_to_mafft = MsaCompactor.guessPathToMafft();
228                 }
229                 checkPathToMafft( path_to_mafft );
230                 if ( cla.isOptionSet( MAFFT_OPTIONS ) ) {
231                     mafft_options = cla.getOptionValueAsCleanString( MAFFT_OPTIONS );
232                     if ( ForesterUtil.isEmpty( mafft_options ) || ( mafft_options.length() < 3 ) ) {
233                         ForesterUtil.fatalError( PRG_NAME, "illegal or empty MAFFT options: " + mafft_options );
234                     }
235                 }
236             }
237             else if ( cla.isOptionSet( MAFFT_OPTIONS ) ) {
238                 ForesterUtil.fatalError( PRG_NAME, "no need to indicate MAFFT options without realigning" );
239             }
240             if ( chart_only ) {
241                 if ( ( out != null ) || ( removed_seqs_out_base != null ) ) {
242                     ForesterUtil
243                             .fatalError( PRG_NAME,
244                                          "chart only, no outfile(s) produced, thus no need to indicate output file(s)" );
245                 }
246                 if ( !realign && cla.isOptionSet( STEP_OPTION ) ) {
247                     ForesterUtil.fatalError( PRG_NAME,
248                                              "chart only, no re-aligning, thus no need to use step for output and re-aligning; use -"
249                                                      + STEP_FOR_DIAGNOSTICS_OPTION + " instead" );
250                 }
251             }
252             ForesterUtil.printProgramInformation( PRG_NAME,
253                                                   PRG_DESC,
254                                                   PRG_VERSION,
255                                                   PRG_DATE,
256                                                   E_MAIL,
257                                                   WWW,
258                                                   ForesterUtil.getForesterLibraryInformation() );
259             System.out.println( "Input MSA                            : " + in );
260             System.out.println( "  MSA length                         : " + msa.getLength() );
261             System.out.println( "  Number of sequences                : " + msa.getNumberOfSequences() );
262             System.out.println( "  Median sequence length             : " + NF_1.format( initial_msa_stats.median() ) );
263             System.out.println( "  Mean sequence length               : "
264                     + NF_1.format( initial_msa_stats.arithmeticMean() ) );
265             System.out.println( "  Max sequence length                : " + ( ( int ) initial_msa_stats.getMax() ) );
266             System.out.println( "  Min sequence length                : " + ( ( int ) initial_msa_stats.getMin() ) );
267             if ( !chart_only ) {
268                 System.out.println( "Output                               : " + out );
269             }
270             else {
271                 System.out.println( "Output                               : n/a" );
272             }
273             if ( removed_seqs_out_base != null ) {
274                 System.out.println( "Write removed sequences to           : " + removed_seqs_out_base );
275             }
276             if ( worst_remove > 0 ) {
277                 System.out.println( "Number of worst offenders to remove  : " + worst_remove );
278             }
279             if ( av_gap > 0 ) {
280                 System.out.println( "Target gap-ratio                     : " + av_gap );
281             }
282             if ( length > 0 ) {
283                 System.out.println( "Target MSA length                    : " + length );
284             }
285             if ( min_length > 1 ) {
286                 System.out.println( "Minimal effective sequence length    : " + min_length );
287             }
288             if ( gap_ratio > -1 ) {
289                 System.out.println( "Maximum allowed gap ratio per column : " + gap_ratio );
290             }
291             if ( ( out != null ) || ( removed_seqs_out_base != null ) ) {
292                 System.out.println( "Output format                        : "
293                         + ( output_format == MSA_FORMAT.FASTA ? "fasta" : "phylip" ) );
294             }
295             if ( chart_only && !realign ) {
296                 System.out.println( "Step for output and re-aligning      : n/a" );
297             }
298             else {
299                 if ( chart_only ) {
300                     System.out.println( "Step for re-aligning                 : " + step );
301                 }
302                 else {
303                     System.out.println( "Step for output and re-aligning      : " + step );
304                 }
305             }
306             System.out.println( "Step for diagnostics reports         : " + step_for_diagnostics );
307             System.out.println( "Calculate mean identity              : " + report_aln_mean_identity );
308             if ( !norm ) {
309                 System.out.println( "Normalize                            : " + norm );
310             }
311             System.out.println( "Realign with MAFFT                   : " + realign );
312             if ( realign ) {
313                 System.out.println( "MAFFT options                        : " + mafft_options );
314             }
315             System.out.println();
316             final int initial_number_of_seqs = msa.getNumberOfSequences();
317             List<MsaProperties> msa_props = null;
318             final MsaCompactor mc = new MsaCompactor( msa );
319             mc.setNorm( norm );
320             mc.setRealign( realign );
321             if ( realign ) {
322                 mc.setPathToMafft( path_to_mafft );
323                 mc.setMafftOptions( mafft_options );
324             }
325             mc.setStep( step );
326             mc.setStepForDiagnostics( step_for_diagnostics );
327             mc.setReportAlnMeanIdentity( report_aln_mean_identity );
328             if ( ( worst_remove > 0 ) || ( av_gap > 0 ) || ( length > 0 ) ) {
329                 mc.setOutputFormat( output_format );
330                 mc.setOutFileBase( out );
331                 if ( removed_seqs_out_base != null ) {
332                     mc.setRemovedSeqsOutBase( removed_seqs_out_base );
333                 }
334             }
335             if ( min_length > 1 ) {
336                 mc.removeSequencesByMinimalLength( min_length );
337                 mc.writeMsa( new File( "removed" ) );
338             }
339             if ( worst_remove > 0 ) {
340                 msa_props = mc.removeWorstOffenders( worst_remove );
341             }
342             else if ( av_gap > 0 ) {
343                 msa_props = mc.removeViaGapAverage( av_gap );
344             }
345             else if ( length > 0 ) {
346                 msa_props = mc.removeViaLength( length );
347             }
348             else {
349                 msa_props = mc.chart( step, realign, norm );
350             }
351             Chart.display( msa_props, initial_number_of_seqs, report_aln_mean_identity, in.toString() );
352         }
353         catch ( final IllegalArgumentException iae ) {
354             //  iae.printStackTrace(); //TODO remove me
355             ForesterUtil.fatalError( PRG_NAME, iae.getMessage() );
356         }
357         catch ( final IOException ioe ) {
358             // ioe.printStackTrace(); //TODO remove me
359             ForesterUtil.fatalError( PRG_NAME, ioe.getMessage() );
360         }
361         catch ( final Exception e ) {
362             ForesterUtil.unexpectedFatalError( PRG_NAME, e );
363         }
364     }
365
366     private static void checkPathToMafft( final String path_to_mafft ) {
367         if ( !ForesterUtil.isEmpty( path_to_mafft ) && MsaInferrer.isInstalled( path_to_mafft ) ) {
368         }
369         else {
370             if ( ForesterUtil.isEmpty( path_to_mafft ) ) {
371                 ForesterUtil.fatalError( PRG_NAME, "no MAFFT executable found, use -\"" + PATH_TO_MAFFT_OPTION
372                         + "=<path to MAFFT>\" option" );
373             }
374             else {
375                 ForesterUtil.fatalError( PRG_NAME, "no MAFFT executable at \"" + path_to_mafft + "\"" );
376             }
377         }
378     }
379
380     private static void printHelp() {
381         ForesterUtil.printProgramInformation( PRG_NAME,
382                                               PRG_DESC,
383                                               PRG_VERSION,
384                                               PRG_DATE,
385                                               E_MAIL,
386                                               WWW,
387                                               ForesterUtil.getForesterLibraryInformation() );
388         final String path_to_mafft = MsaCompactor.guessPathToMafft();
389         String mafft_comment;
390         if ( !ForesterUtil.isEmpty( path_to_mafft ) ) {
391             mafft_comment = " (using " + path_to_mafft + ")";
392         }
393         else {
394             mafft_comment = " (no path to MAFFT found, use -\"" + PATH_TO_MAFFT_OPTION + "=<path to MAFFT>\" option";
395         }
396         System.out.println( "Usage:" );
397         System.out.println();
398         System.out.println( PRG_NAME + " <options> <msa input file> <output file base>" );
399         System.out.println();
400         System.out.println( " options: " );
401         System.out.println();
402         System.out.println( "   -" + REMOVE_WORST_OFFENDERS_OPTION
403                 + "=<integer>   number of worst offender sequences to remove" );
404         System.out.println( "   -" + LENGTH_OPTION + "=<integer>   target MSA length" );
405         System.out.println( "   -" + AV_GAPINESS_OPTION + "=<decimal>   target gap-ratio (0.0-1.0)" );
406         System.out.println( "   -" + REALIGN_OPTION + "             to realign using MAFFT" + mafft_comment );
407         System.out.println( "   -" + MAFFT_OPTIONS + "=<string>   options for MAFFT (default: --auto)" );
408         System.out.println( "   -" + STEP_OPTION + "=<integer>   step for output and re-aligning (default: 1)" );
409         System.out.println( "   -" + STEP_FOR_DIAGNOSTICS_OPTION
410                 + "=<integer>  step for diagnostics reports (default: 1)" );
411         System.out
412                 .println( "   -"
413                         + REPORT_ALN_MEAN_IDENTITY
414                         + "             to calculate mean MSA column identity (\"MSA quality\") (not recommended for very large alignments)" );
415         System.out.println( "   -" + OUTPUT_FORMAT_PHYLIP_OPTION
416                 + "             to write output alignments in phylip format instead of fasta" );
417         System.out.println( "   -" + OUTPUT_REMOVED_SEQS_OPTION + "=<file>     to output the removed sequences" );
418         System.out.println( "   -" + MIN_LENGTH_OPTION
419                 + "=<integer>  minimal effecive sequence length (for deleting of shorter sequences)" );
420         System.out.println( "   -" + GAP_RATIO_LENGTH_OPTION
421                 + "=<decimal>  maximal allowed gap ratio per column (for deleting of columms) (0.0-1.0)" );
422         System.out.println();
423         System.out.println();
424         System.out.println();
425     }
426 }