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.awt.Color;
28 import java.io.File;
29 import java.io.IOException;
30 import java.io.Writer;
31 import java.math.RoundingMode;
32 import java.text.DecimalFormat;
33 import java.text.NumberFormat;
34 import java.util.ArrayList;
35 import java.util.Arrays;
36 import java.util.List;
37 import java.util.SortedSet;
38 import java.util.TreeSet;
39
40 import org.forester.archaeopteryx.Archaeopteryx;
41 import org.forester.archaeopteryx.Configuration;
42 import org.forester.evoinference.distance.NeighborJoiningF;
43 import org.forester.evoinference.distance.PairwiseDistanceCalculator;
44 import org.forester.evoinference.distance.PairwiseDistanceCalculator.PWD_DISTANCE_METHOD;
45 import org.forester.evoinference.matrix.distance.BasicSymmetricalDistanceMatrix;
46 import org.forester.evoinference.tools.BootstrapResampler;
47 import org.forester.io.parsers.nhx.NHXParser.TAXONOMY_EXTRACTION;
48 import org.forester.io.parsers.phyloxml.PhyloXmlDataFormatException;
49 import org.forester.io.parsers.util.ParserUtils;
50 import org.forester.io.writers.SequenceWriter;
51 import org.forester.io.writers.SequenceWriter.SEQ_FORMAT;
52 import org.forester.msa.DeleteableMsa;
53 import org.forester.msa.Mafft;
54 import org.forester.msa.Msa;
55 import org.forester.msa.Msa.MSA_FORMAT;
56 import org.forester.msa.MsaInferrer;
57 import org.forester.msa.MsaMethods;
58 import org.forester.msa.ResampleableMsa;
59 import org.forester.phylogeny.Phylogeny;
60 import org.forester.phylogeny.PhylogenyMethods;
61 import org.forester.phylogeny.PhylogenyMethods.DESCENDANT_SORT_PRIORITY;
62 import org.forester.phylogeny.PhylogenyNode;
63 import org.forester.phylogeny.data.NodeVisualData;
64 import org.forester.phylogeny.data.NodeVisualData.NodeFill;
65 import org.forester.phylogeny.data.NodeVisualData.NodeShape;
66 import org.forester.phylogeny.iterators.PhylogenyNodeIterator;
67 import org.forester.sequence.Sequence;
68 import org.forester.tools.ConfidenceAssessor;
69 import org.forester.util.BasicDescriptiveStatistics;
70 import org.forester.util.ForesterUtil;
71
72 public class MsaCompactor {
73
74     final private static NumberFormat NF_3                      = new DecimalFormat( "#.###" );
75     final private static NumberFormat NF_4                      = new DecimalFormat( "#.####" );
76     private double                    _gap_ratio                = -1;
77     private final short               _longest_id_length;
78     //
79     private String                    _maffts_opts              = "--auto";
80     private int                       _min_length               = -1;
81     //
82     private String                    _infile_name              = null;
83     private DeleteableMsa             _msa                      = null;
84     private boolean                   _norm                     = true;
85     private File                      _out_file_base            = null;
86     private MSA_FORMAT                _output_format            = MSA_FORMAT.FASTA;
87     private String                    _path_to_mafft            = null;
88     //
89     private boolean                   _realign                  = false;
90     private final SortedSet<String>   _removed_seq_ids;
91     private final ArrayList<Sequence> _removed_seqs;
92     private File                      _removed_seqs_out_base    = null;
93     private boolean                   _report_aln_mean_identity = false;
94     private int                       _step                     = -1;
95     private int                       _step_for_diagnostics     = -1;
96     private boolean                   _phylogentic_inference    = false;
97     static {
98         NF_4.setRoundingMode( RoundingMode.HALF_UP );
99         NF_3.setRoundingMode( RoundingMode.HALF_UP );
100     }
101
102     public MsaCompactor( final DeleteableMsa msa ) {
103         _msa = msa;
104         _removed_seq_ids = new TreeSet<String>();
105         _longest_id_length = _msa.determineMaxIdLength();
106         _removed_seqs = new ArrayList<Sequence>();
107     }
108
109     public final List<MsaProperties> chart( final int step, final boolean realign, final boolean norm )
110             throws IOException, InterruptedException {
111         final GapContribution stats[] = calcGapContribtionsStats( norm );
112         final List<String> to_remove_ids = new ArrayList<String>();
113         final List<MsaProperties> msa_props = new ArrayList<MsaProperties>();
114         for( final GapContribution gap_gontribution : stats ) {
115             to_remove_ids.add( gap_gontribution.getId() );
116         }
117         if ( !_realign ) {
118             _step = -1;
119         }
120         int x = ForesterUtil.roundToInt( _msa.getNumberOfSequences() / 20.0 );
121         if ( x < 1 ) {
122             x = 1;
123         }
124         MsaProperties msa_prop = new MsaProperties( _msa, "", _report_aln_mean_identity );
125         msa_props.add( msa_prop );
126         Phylogeny phy = null;
127         if ( _phylogentic_inference ) {
128             System.out.println( "calculating phylogentic tree..." );
129             System.out.println();
130             phy = calcTree();
131         }
132         printTableHeader();
133         printMsaProperties( "", msa_prop );
134         System.out.println();
135         int i = 0;
136         while ( _msa.getNumberOfSequences() > x ) {
137             final String id = to_remove_ids.get( i );
138             _msa.deleteRow( id, false );
139             if ( realign && isPrintMsaStatsWriteOutfileAndRealign( i ) ) {
140                 removeGapColumns();
141                 realignWithMafft();
142                 msa_prop = new MsaProperties( _msa, id, _report_aln_mean_identity );
143                 msa_props.add( msa_prop );
144                 printMsaProperties( id, msa_prop );
145                 System.out.print( "(realigned)" );
146                 System.out.println();
147             }
148             else if ( isPrintMsaStats( i ) ) {
149                 removeGapColumns();
150                 msa_prop = new MsaProperties( _msa, id, _report_aln_mean_identity );
151                 msa_props.add( msa_prop );
152                 printMsaProperties( id, msa_prop );
153                 System.out.println();
154             }
155             ++i;
156         }
157         if ( _phylogentic_inference ) {
158             final Phylogeny p2 = phy.copy();
159             decorateTree( p2, to_remove_ids );
160             decorateTree2( phy, msa_props );
161             displayTree( p2 );
162             displayTree( phy );
163         }
164         return msa_props;
165     }
166
167     final public void deleteGapColumns( final double max_allowed_gap_ratio ) {
168         _msa.deleteGapColumns( max_allowed_gap_ratio );
169     }
170
171     final public Msa getMsa() {
172         return _msa;
173     }
174
175     final public SortedSet<String> getRemovedSeqIds() {
176         return _removed_seq_ids;
177     }
178
179     public final void removeSequencesByMinimalLength( final int min_effective_length ) {
180         printMsaProperties( "", new MsaProperties( _msa, "", _report_aln_mean_identity ) );
181         System.out.println();
182         _msa = DeleteableMsa.createInstance( MsaMethods.removeSequencesByMinimalLength( _msa, min_effective_length ) );
183         removeGapColumns();
184         printMsaProperties( "", new MsaProperties( _msa, "", _report_aln_mean_identity ) );
185         System.out.println();
186     }
187
188     public final List<MsaProperties> removeViaGapAverage( final double mean_gapiness ) throws IOException,
189             InterruptedException {
190         final GapContribution stats[] = calcGapContribtionsStats( _norm );
191         final List<String> to_remove_ids = new ArrayList<String>();
192         final List<MsaProperties> msa_props = new ArrayList<MsaProperties>();
193         for( final GapContribution gap_gontribution : stats ) {
194             to_remove_ids.add( gap_gontribution.getId() );
195         }
196         printTableHeader();
197         MsaProperties msa_prop = new MsaProperties( _msa, "", _report_aln_mean_identity );
198         msa_props.add( msa_prop );
199         printMsaProperties( "", msa_prop );
200         System.out.println();
201         int i = 0;
202         while ( MsaMethods.calcGapRatio( _msa ) > mean_gapiness ) {
203             final String id = to_remove_ids.get( i );
204             _removed_seq_ids.add( id );
205             final Sequence deleted = _msa.deleteRow( id, true );
206             _removed_seqs.add( deleted );
207             removeGapColumns();
208             if ( isPrintMsaStatsWriteOutfileAndRealign( i ) || ( MsaMethods.calcGapRatio( _msa ) <= mean_gapiness ) ) {
209                 msa_prop = printMsaStatsWriteOutfileAndRealign( _realign, id );
210                 msa_props.add( msa_prop );
211                 System.out.println();
212             }
213             else if ( isPrintMsaStats( i ) ) {
214                 msa_prop = new MsaProperties( _msa, id, _report_aln_mean_identity );
215                 msa_props.add( msa_prop );
216                 printMsaProperties( id, msa_prop );
217                 System.out.println();
218             }
219             ++i;
220         }
221         if ( _removed_seqs_out_base != null ) {
222             final String msg = writeAndAlignRemovedSeqs();
223             System.out.println();
224             System.out.println( msg );
225         }
226         return msa_props;
227     }
228
229     public List<MsaProperties> removeViaLength( final int length ) throws IOException, InterruptedException {
230         final GapContribution stats[] = calcGapContribtionsStats( _norm );
231         final List<String> to_remove_ids = new ArrayList<String>();
232         final List<MsaProperties> msa_props = new ArrayList<MsaProperties>();
233         for( final GapContribution gap_gontribution : stats ) {
234             to_remove_ids.add( gap_gontribution.getId() );
235         }
236         printTableHeader();
237         MsaProperties msa_prop = new MsaProperties( _msa, "", _report_aln_mean_identity );
238         msa_props.add( msa_prop );
239         printMsaProperties( "", msa_prop );
240         System.out.println();
241         int i = 0;
242         while ( _msa.getLength() > length ) {
243             final String id = to_remove_ids.get( i );
244             _removed_seq_ids.add( id );
245             final Sequence deleted = _msa.deleteRow( id, true );
246             _removed_seqs.add( deleted );
247             removeGapColumns();
248             if ( isPrintMsaStatsWriteOutfileAndRealign( i ) || ( _msa.getLength() <= length ) ) {
249                 msa_prop = printMsaStatsWriteOutfileAndRealign( _realign, id );
250                 msa_props.add( msa_prop );
251                 System.out.println();
252             }
253             else if ( isPrintMsaStats( i ) ) {
254                 msa_prop = new MsaProperties( _msa, id, _report_aln_mean_identity );
255                 printMsaProperties( id, msa_prop );
256                 msa_props.add( msa_prop );
257                 System.out.println();
258             }
259             ++i;
260         }
261         if ( _removed_seqs_out_base != null ) {
262             final String msg = writeAndAlignRemovedSeqs();
263             System.out.println();
264             System.out.println( msg );
265         }
266         return msa_props;
267     }
268
269     public final List<MsaProperties> removeWorstOffenders( final int to_remove ) throws IOException,
270             InterruptedException {
271         final GapContribution stats[] = calcGapContribtionsStats( _norm );
272         final List<String> to_remove_ids = new ArrayList<String>();
273         final List<MsaProperties> msa_props = new ArrayList<MsaProperties>();
274         for( int j = 0; j < to_remove; ++j ) {
275             to_remove_ids.add( stats[ j ].getId() );
276             _removed_seq_ids.add( stats[ j ].getId() );
277         }
278         printTableHeader();
279         MsaProperties msa_prop = new MsaProperties( _msa, "", _report_aln_mean_identity );
280         msa_props.add( msa_prop );
281         printMsaProperties( "", msa_prop );
282         System.out.println();
283         for( int i = 0; i < to_remove_ids.size(); ++i ) {
284             final String id = to_remove_ids.get( i );
285             _removed_seq_ids.add( id );
286             final Sequence deleted = _msa.deleteRow( id, true );
287             _removed_seqs.add( deleted );
288             removeGapColumns();
289             if ( isPrintMsaStatsWriteOutfileAndRealign( i ) || ( i == ( to_remove_ids.size() - 1 ) ) ) {
290                 msa_prop = printMsaStatsWriteOutfileAndRealign( _realign, id );
291                 msa_props.add( msa_prop );
292                 System.out.println();
293             }
294             else if ( isPrintMsaStats( i ) ) {
295                 msa_prop = new MsaProperties( _msa, id, _report_aln_mean_identity );
296                 msa_props.add( msa_prop );
297                 printMsaProperties( id, msa_prop );
298                 System.out.println();
299             }
300         }
301         if ( _removed_seqs_out_base != null ) {
302             final String msg = writeAndAlignRemovedSeqs();
303             System.out.println();
304             System.out.println( msg );
305         }
306         return msa_props;
307     }
308
309     public final void setGapRatio( final double gap_ratio ) {
310         _gap_ratio = gap_ratio;
311     }
312
313     public final void setMafftOptions( final String maffts_opts ) {
314         _maffts_opts = maffts_opts;
315     }
316
317     public final void setMinLength( final int min_length ) {
318         _min_length = min_length;
319     }
320
321     public final void setNorm( final boolean norm ) {
322         _norm = norm;
323     }
324
325     final public void setOutFileBase( final File out_file_base ) {
326         _out_file_base = out_file_base;
327     }
328
329     public final void setOutputFormat( final MSA_FORMAT output_format ) {
330         _output_format = output_format;
331     }
332
333     public void setPathToMafft( final String path_to_mafft ) {
334         _path_to_mafft = path_to_mafft;
335     }
336
337     public final void setRealign( final boolean realign ) {
338         _realign = realign;
339     }
340
341     public final void setRemovedSeqsOutBase( final File removed_seqs_out_base ) {
342         _removed_seqs_out_base = removed_seqs_out_base;
343     }
344
345     public final void setReportAlnMeanIdentity( final boolean report_aln_mean_identity ) {
346         _report_aln_mean_identity = report_aln_mean_identity;
347     }
348
349     public final void setStep( final int step ) {
350         _step = step;
351     }
352
353     public final void setStepForDiagnostics( final int step_for_diagnostics ) {
354         _step_for_diagnostics = step_for_diagnostics;
355     }
356
357     final public String writeAndAlignRemovedSeqs() throws IOException, InterruptedException {
358         final StringBuilder msg = new StringBuilder();
359         final String n = _removed_seqs_out_base + "_" + _removed_seqs.size() + ".fasta";
360         SequenceWriter.writeSeqs( _removed_seqs, new File( n ), SEQ_FORMAT.FASTA, 100 );
361         msg.append( "wrote " + _removed_seqs.size() + " removed sequences to " + "\"" + n + "\"" );
362         if ( _realign ) {
363             final MsaInferrer mafft = Mafft.createInstance( _path_to_mafft );
364             final List<String> opts = new ArrayList<String>();
365             for( final String o : _maffts_opts.split( "\\s" ) ) {
366                 opts.add( o );
367             }
368             final Msa removed_msa = mafft.infer( _removed_seqs, opts );
369             final Double gr = MsaMethods.calcGapRatio( removed_msa );
370             String s = _removed_seqs_out_base + "_" + removed_msa.getNumberOfSequences() + "_"
371                     + removed_msa.getLength() + "_" + ForesterUtil.roundToInt( gr * 100 );
372             final String suffix = obtainSuffix();
373             s += suffix;
374             writeMsa( removed_msa, s, _output_format );
375             msg.append( ", and as MSA of length " + removed_msa.getLength() + " to \"" + s + "\"" );
376         }
377         return msg.toString();
378     }
379
380     final public String writeMsa( final File outfile ) throws IOException {
381         final Double gr = MsaMethods.calcGapRatio( _msa );
382         final String s = outfile + "_" + _msa.getNumberOfSequences() + "_" + _msa.getLength() + "_"
383                 + ForesterUtil.roundToInt( gr * 100 );
384         writeMsa( _msa, s + obtainSuffix(), _output_format );
385         return s;
386     }
387
388     final int calcNonGapResidues( final Sequence seq ) {
389         int ng = 0;
390         for( int i = 0; i < seq.getLength(); ++i ) {
391             if ( !seq.isGapAt( i ) ) {
392                 ++ng;
393             }
394         }
395         return ng;
396     }
397
398     private final GapContribution[] calcGapContribtions( final boolean normalize_for_effective_seq_length ) {
399         final double gappiness[] = calcGappiness();
400         final GapContribution stats[] = new GapContribution[ _msa.getNumberOfSequences() ];
401         for( int row = 0; row < _msa.getNumberOfSequences(); ++row ) {
402             stats[ row ] = new GapContribution( _msa.getIdentifier( row ) );
403             for( int col = 0; col < _msa.getLength(); ++col ) {
404                 if ( !_msa.isGapAt( row, col ) ) {
405                     stats[ row ].addToValue( gappiness[ col ] );
406                 }
407             }
408             if ( normalize_for_effective_seq_length ) {
409                 stats[ row ].divideValue( calcNonGapResidues( _msa.getSequence( row ) ) );
410             }
411             else {
412                 stats[ row ].divideValue( _msa.getLength() );
413             }
414         }
415         return stats;
416     }
417
418     final private GapContribution[] calcGapContribtionsStats( final boolean norm ) {
419         final GapContribution stats[] = calcGapContribtions( norm );
420         Arrays.sort( stats );
421         return stats;
422     }
423
424     private final double[] calcGappiness() {
425         final int l = _msa.getLength();
426         final double gappiness[] = new double[ l ];
427         final int seqs = _msa.getNumberOfSequences();
428         for( int i = 0; i < l; ++i ) {
429             gappiness[ i ] = ( double ) MsaMethods.calcGapSumPerColumn( _msa, i ) / seqs;
430         }
431         return gappiness;
432     }
433
434     private final Phylogeny inferNJphylogeny( final PWD_DISTANCE_METHOD pwd_distance_method,
435                                               final Msa msa,
436                                               final boolean write_matrix,
437                                               final String matrix_name ) {
438         BasicSymmetricalDistanceMatrix m = null;
439         switch ( pwd_distance_method ) {
440             case KIMURA_DISTANCE:
441                 m = PairwiseDistanceCalculator.calcKimuraDistances( msa );
442                 break;
443             case POISSON_DISTANCE:
444                 m = PairwiseDistanceCalculator.calcPoissonDistances( msa );
445                 break;
446             case FRACTIONAL_DISSIMILARITY:
447                 m = PairwiseDistanceCalculator.calcFractionalDissimilarities( msa );
448                 break;
449             default:
450                 throw new IllegalArgumentException( "invalid pwd method" );
451         }
452         if ( write_matrix ) {
453             try {
454                 m.write( ForesterUtil.createBufferedWriter( matrix_name ) );
455             }
456             catch ( final IOException e ) {
457                 e.printStackTrace();
458             }
459         }
460         final NeighborJoiningF nj = NeighborJoiningF.createInstance( false, 5 );
461         final Phylogeny phy = nj.execute( m );
462         return phy;
463     }
464
465     private final boolean isPrintMsaStats( final int i ) {
466         return ( ( ( _step == 1 ) && ( _step_for_diagnostics == 1 ) ) || ( ( _step_for_diagnostics > 0 ) && ( ( ( i + 1 ) % _step_for_diagnostics ) == 0 ) ) );
467     }
468
469     private final boolean isPrintMsaStatsWriteOutfileAndRealign( final int i ) {
470         return ( ( ( _step == 1 ) && ( _step_for_diagnostics == 1 ) ) || ( ( _step > 0 ) && ( ( ( i + 1 ) % _step ) == 0 ) ) );
471     }
472
473     private final StringBuilder msaPropertiesAsSB( final MsaProperties msa_properties ) {
474         final StringBuilder sb = new StringBuilder();
475         sb.append( msa_properties.getNumberOfSequences() );
476         sb.append( "\t" );
477         sb.append( msa_properties.getLength() );
478         sb.append( "\t" );
479         sb.append( NF_4.format( msa_properties.getGapRatio() ) );
480         if ( _report_aln_mean_identity ) {
481             sb.append( "\t" );
482             sb.append( NF_4.format( msa_properties.getAverageIdentityRatio() ) );
483         }
484         return sb;
485     }
486
487     private String obtainSuffix() {
488         if ( _output_format == MSA_FORMAT.FASTA ) {
489             return ".fasta";
490         }
491         else if ( _output_format == MSA_FORMAT.PHYLIP ) {
492             return ".aln";
493         }
494         return "";
495     }
496
497     private final Phylogeny pi( final String matrix, final int boostrap ) {
498         final Phylogeny master_phy = inferNJphylogeny( PWD_DISTANCE_METHOD.KIMURA_DISTANCE, _msa, true, matrix );
499         final int seed = 15;
500         final int n = 100;
501         final ResampleableMsa resampleable_msa = new ResampleableMsa( _msa );
502         final int[][] resampled_column_positions = BootstrapResampler.createResampledColumnPositions( _msa.getLength(),
503                                                                                                       n,
504                                                                                                       seed );
505         final Phylogeny[] eval_phys = new Phylogeny[ n ];
506         for( int i = 0; i < n; ++i ) {
507             resampleable_msa.resample( resampled_column_positions[ i ] );
508             eval_phys[ i ] = inferNJphylogeny( PWD_DISTANCE_METHOD.KIMURA_DISTANCE, resampleable_msa, false, null );
509         }
510         ConfidenceAssessor.evaluate( "bootstrap", eval_phys, master_phy, true, 1 );
511         PhylogenyMethods.extractFastaInformation( master_phy );
512         return master_phy;
513     }
514
515     public final Phylogeny calcTree() {
516         final Phylogeny phy = inferNJphylogeny( PWD_DISTANCE_METHOD.KIMURA_DISTANCE, _msa, false, "" );
517         PhylogenyMethods.midpointRoot( phy );
518         PhylogenyMethods.orderAppearance( phy.getRoot(), true, true, DESCENDANT_SORT_PRIORITY.NODE_NAME );
519         final boolean x = PhylogenyMethods.extractFastaInformation( phy );
520         if ( !x ) {
521             final PhylogenyNodeIterator it = phy.iteratorExternalForward();
522             while ( it.hasNext() ) {
523                 final PhylogenyNode n = it.next();
524                 final String name = n.getName().trim();
525                 if ( !ForesterUtil.isEmpty( name ) ) {
526                     try {
527                         ParserUtils.extractTaxonomyDataFromNodeName( n, TAXONOMY_EXTRACTION.AGGRESSIVE );
528                     }
529                     catch ( final PhyloXmlDataFormatException e ) {
530                         // Ignore.
531                     }
532                 }
533             }
534         }
535         return phy;
536     }
537
538     public final void decorateTree( final Phylogeny phy, final List<String> to_remove_ids ) {
539         for( int i = 0; i < to_remove_ids.size(); ++i ) {
540             final String id = to_remove_ids.get( i );
541             final PhylogenyNode n = phy.getNode( id );
542             n.setName( n.getName() + " [" + ( i + 1 ) + "]" );
543             final NodeVisualData vis = new NodeVisualData();
544             vis.setFillType( NodeFill.SOLID );
545             vis.setShape( NodeShape.RECTANGLE );
546             vis.setSize( 6 );
547             vis.setNodeColor( new Color( i > 255 ? 0 : 255 - i, 0, 0 ) );
548             n.getNodeData().setNodeVisualData( vis );
549         }
550     }
551
552     public final void decorateTree2( final Phylogeny phy, final List<MsaProperties> msa_props ) {
553         final BasicDescriptiveStatistics length_stats = new BasicDescriptiveStatistics();
554         for( int i = 0; i < msa_props.size(); ++i ) {
555             final MsaProperties msa_prop = msa_props.get( i );
556             final String id = msa_prop.getRemovedSeq();
557             if ( !ForesterUtil.isEmpty( id ) ) {
558                 length_stats.addValue( msa_prop.getLength() );
559             }
560         }
561         final double mean = length_stats.arithmeticMean();
562         final double min = length_stats.getMin();
563         final double max = length_stats.getMax();
564         final Color min_color = new Color( 0, 255, 0 );
565         final Color max_color = new Color( 255, 0, 0 );
566         final Color mean_color = new Color( 255, 255, 0 );
567         final PhylogenyNodeIterator it = phy.iteratorExternalForward();
568         while ( it.hasNext() ) {
569             final NodeVisualData vis = new NodeVisualData();
570             vis.setFillType( NodeFill.SOLID );
571             vis.setShape( NodeShape.RECTANGLE );
572             vis.setSize( 6 );
573             vis.setNodeColor( min_color );
574             it.next().getNodeData().setNodeVisualData( vis );
575         }
576         for( int i = 0; i < msa_props.size(); ++i ) {
577             final MsaProperties msa_prop = msa_props.get( i );
578             final String id = msa_prop.getRemovedSeq();
579             if ( !ForesterUtil.isEmpty( id ) ) {
580                 final PhylogenyNode n = phy.getNode( id );
581                 n.setName( n.getName() + " [" + i + "]" );
582                 n.getNodeData()
583                         .getNodeVisualData()
584                         .setNodeColor( ForesterUtil.calcColor( msa_prop.getLength(),
585                                                                min,
586                                                                max,
587                                                                mean,
588                                                                min_color,
589                                                                max_color,
590                                                                mean_color ) );
591             }
592         }
593     }
594
595     public final void displayTree( final Phylogeny phy ) {
596         final Configuration config = new Configuration();
597         config.setDisplayAsPhylogram( true );
598         config.setUseStyle( true );
599         config.setDisplayTaxonomyCode( false );
600         config.setDisplayTaxonomyCommonNames( false );
601         config.setDisplayTaxonomyScientificNames( false );
602         config.setDisplaySequenceNames( false );
603         config.setDisplaySequenceSymbols( false );
604         config.setDisplayGeneNames( false );
605         config.setShowScale( true );
606         config.setAddTaxonomyImagesCB( false );
607         config.setBaseFontSize( 9 );
608         config.setBaseFontFamilyName( "Arial" );
609         Archaeopteryx.createApplication( phy, config, _infile_name );
610     }
611
612     private final void printMsaProperties( final String id, final MsaProperties msa_properties ) {
613         if ( ( _step == 1 ) || ( _step_for_diagnostics == 1 ) ) {
614             System.out.print( ForesterUtil.pad( id, _longest_id_length, ' ', false ) );
615             System.out.print( "\t" );
616         }
617         System.out.print( msaPropertiesAsSB( msa_properties ) );
618         System.out.print( "\t" );
619     }
620
621     final private MsaProperties printMsaStatsWriteOutfileAndRealign( final boolean realign, final String id )
622             throws IOException, InterruptedException {
623         if ( realign ) {
624             realignWithMafft();
625         }
626         final MsaProperties msa_prop = new MsaProperties( _msa, id, _report_aln_mean_identity );
627         printMsaProperties( id, msa_prop );
628         final String s = writeOutfile();
629         System.out.print( "-> " + s + ( realign ? "\t(realigned)" : "" ) );
630         return msa_prop;
631     }
632
633     private final void printTableHeader() {
634         if ( ( _step == 1 ) || ( _step_for_diagnostics == 1 ) ) {
635             System.out.print( ForesterUtil.pad( "Id", _longest_id_length, ' ', false ) );
636             System.out.print( "\t" );
637         }
638         System.out.print( "Seqs" );
639         System.out.print( "\t" );
640         System.out.print( "Length" );
641         System.out.print( "\t" );
642         System.out.print( "Gaps" );
643         System.out.print( "\t" );
644         if ( _report_aln_mean_identity ) {
645             System.out.print( "MSA qual" );
646             System.out.print( "\t" );
647         }
648         System.out.println();
649     }
650
651     final private void realignWithMafft() throws IOException, InterruptedException {
652         final MsaInferrer mafft = Mafft.createInstance( _path_to_mafft );
653         final List<String> opts = new ArrayList<String>();
654         for( final String o : _maffts_opts.split( "\\s" ) ) {
655             opts.add( o );
656         }
657         _msa = DeleteableMsa.createInstance( mafft.infer( _msa.asSequenceList(), opts ) );
658     }
659
660     final private void removeGapColumns() {
661         _msa.deleteGapOnlyColumns();
662     }
663
664     private final String writeOutfile() throws IOException {
665         final String s = writeMsa( _out_file_base );
666         return s;
667     }
668
669     // Returns null if not path found.
670     final public static String guessPathToMafft() {
671         String path;
672         if ( ForesterUtil.OS_NAME.toLowerCase().indexOf( "win" ) >= 0 ) {
673             path = "C:\\Program Files\\mafft-win\\mafft.bat";
674             if ( MsaInferrer.isInstalled( path ) ) {
675                 return path;
676             }
677         }
678         path = "/home/czmasek/SOFTWARE/MSA/MAFFT/mafft-7.130-without-extensions/scripts/mafft";
679         if ( MsaInferrer.isInstalled( path ) ) {
680             return path;
681         }
682         path = "/usr/local/bin/mafft";
683         if ( MsaInferrer.isInstalled( path ) ) {
684             return path;
685         }
686         path = "/usr/bin/mafft";
687         if ( MsaInferrer.isInstalled( path ) ) {
688             return path;
689         }
690         path = "/bin/mafft";
691         if ( MsaInferrer.isInstalled( path ) ) {
692             return path;
693         }
694         path = "mafft";
695         if ( MsaInferrer.isInstalled( path ) ) {
696             return path;
697         }
698         return null;
699     }
700
701     final private static void writeMsa( final Msa msa, final String outfile, final MSA_FORMAT format )
702             throws IOException {
703         final Writer w = ForesterUtil.createBufferedWriter( outfile );
704         msa.write( w, format );
705         w.close();
706     }
707
708     public void setPeformPhylogenticInference( final boolean phylogentic_inference ) {
709         _phylogentic_inference = phylogentic_inference;
710     }
711
712     public void setInfileName( final String infile_name ) {
713         _infile_name = infile_name;
714     }
715 }