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