da74deca96393c08c7d8bacaeff66303316c07d7
[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       
234                 for( int i = 0; i < msa_props.size(); ++i ) {
235                     final MsaProperties msa_prop = msa_props.get( i );
236                     final String id = msa_prop.getRemovedSeq();
237                     if ( !ForesterUtil.isEmpty( id ) ) {
238                         final PhylogenyNode n = phy.getNode( id );
239                         n.setName( n.getName() + " [" + i + "]" );
240                         if ( !chart_only ) {
241                             final NodeVisualData vis = new NodeVisualData();
242                             vis.setFillType( NodeFill.SOLID );
243                             vis.setShape( NodeShape.RECTANGLE );
244                             vis.setNodeColor( ForesterUtil.calcColor( msa_prop.getLength(), min, max, mean_color, max_color ) );
245                             n.getNodeData().setNodeVisualData( vis );
246                         }
247                         else {
248                             n.getNodeData()
249                                     .getNodeVisualData()
250                                     .setNodeColor( ForesterUtil.calcColor( msa_prop.getLength(),
251                                                                            min,
252                                                                            max,
253                                                                            mean,
254                                                                            min_color,
255                                                                            max_color,
256                                                                            mean_color ) );
257                         }
258                     }
259         
260                 }
261     }
262
263     final public void deleteGapColumns( final double max_allowed_gap_ratio ) {
264         _msa.deleteGapColumns( max_allowed_gap_ratio );
265     }
266
267     public final void displayTree( final Phylogeny phy ) {
268         final Configuration config = new Configuration();
269         config.setDisplayAsPhylogram( true );
270         config.setUseStyle( true );
271         config.setDisplayTaxonomyCode( false );
272         config.setDisplayTaxonomyCommonNames( false );
273         config.setDisplayTaxonomyScientificNames( false );
274         config.setDisplaySequenceNames( false );
275         config.setDisplaySequenceSymbols( false );
276         config.setDisplayGeneNames( false );
277         config.setShowScale( true );
278         config.setAddTaxonomyImagesCB( false );
279         config.setBaseFontSize( 9 );
280         config.setBaseFontFamilyName( "Arial" );
281         Archaeopteryx.createApplication( phy, config, _infile_name );
282     }
283
284     final public Msa getMsa() {
285         return _msa;
286     }
287
288     public final void removeSequencesByMinimalLength( final int min_effective_length ) throws IOException {
289         _msa = DeleteableMsa.createInstance( MsaMethods.removeSequencesByMinimalLength( _msa, min_effective_length ) );
290         removeGapColumns();
291         final String s = writeOutfile();
292         final DescriptiveStatistics msa_stats = MsaMethods.calculateEffectiveLengthStatistics( _msa );
293         System.out.println( "Output MSA                           : " + s );
294         System.out.println( "  MSA length                         : " + _msa.getLength() );
295         System.out.println( "  Number of sequences                : " + _msa.getNumberOfSequences() );
296         System.out.println( "  Median sequence length             : " + NF_1.format( msa_stats.median() ) );
297         System.out.println( "  Mean sequence length               : " + NF_1.format( msa_stats.arithmeticMean() ) );
298         System.out.println( "  Max sequence length                : " + ( ( int ) msa_stats.getMax() ) );
299         System.out.println( "  Min sequence length                : " + ( ( int ) msa_stats.getMin() ) );
300         System.out.println( "  Gap ratio                          : " + NF_4.format( MsaMethods.calcGapRatio( _msa ) ) );
301         System.out.println( "  Normalized Shannon Entropy (entn21): "
302                 + NF_4.format( MsaMethods.calcNormalizedShannonsEntropy( 21, _msa ) ) );
303         System.out.println();
304     }
305
306     public final List<MsaProperties> removeViaGapAverage( final double mean_gapiness ) throws IOException,
307     InterruptedException {
308         final GapContribution stats[] = calcGapContribtionsStats( _norm );
309         final List<String> to_remove_ids = new ArrayList<String>();
310         final List<MsaProperties> msa_props = new ArrayList<MsaProperties>();
311         for( final GapContribution gap_gontribution : stats ) {
312             to_remove_ids.add( gap_gontribution.getId() );
313         }
314         Phylogeny phy = null;
315         if ( _phylogentic_inference ) {
316             System.out.println( "calculating phylogentic tree..." );
317             System.out.println();
318             phy = calcTree();
319             addSeqs2Tree( _msa, phy );
320         }
321         printTableHeader();
322         MsaProperties msa_prop = new MsaProperties( _msa, "", _calculate_shannon_entropy );
323         msa_props.add( msa_prop );
324         printMsaProperties( msa_prop );
325         System.out.println();
326         int i = 0;
327         while ( MsaMethods.calcGapRatio( _msa ) > mean_gapiness ) {
328             final String id = to_remove_ids.get( i );
329             _removed_seq_ids.add( id );
330             final MolecularSequence deleted = _msa.deleteRow( id, true );
331             _removed_seqs.add( deleted );
332             removeGapColumns();
333             if ( isPrintMsaStatsWriteOutfileAndRealign( i ) || ( MsaMethods.calcGapRatio( _msa ) <= mean_gapiness ) ) {
334                 msa_prop = printMsaStatsWriteOutfileAndRealign( _realign, id );
335                 msa_props.add( msa_prop );
336                 System.out.println();
337             }
338             else if ( isPrintMsaStats( i ) ) {
339                 msa_prop = new MsaProperties( _msa, id, _calculate_shannon_entropy );
340                 msa_props.add( msa_prop );
341                 printMsaProperties( msa_prop );
342                 System.out.println();
343             }
344             ++i;
345         }
346         if ( _removed_seqs_out_base != null ) {
347             final String msg = writeAndAlignRemovedSeqs();
348             System.out.println();
349             System.out.println( msg );
350         }
351         if ( _phylogentic_inference ) {
352             decorateTree( phy,  msa_props, false );
353             displayTree( phy );
354         }
355         return msa_props;
356     }
357
358     public List<MsaProperties> removeViaLength( final int length ) throws IOException, InterruptedException {
359         final GapContribution stats[] = calcGapContribtionsStats( _norm );
360         final List<String> to_remove_ids = new ArrayList<String>();
361         final List<MsaProperties> msa_props = new ArrayList<MsaProperties>();
362         for( final GapContribution gap_gontribution : stats ) {
363             to_remove_ids.add( gap_gontribution.getId() );
364         }
365         Phylogeny phy = null;
366         if ( _phylogentic_inference ) {
367             System.out.println( "calculating phylogentic tree..." );
368             System.out.println();
369             phy = calcTree();
370             addSeqs2Tree( _msa, phy );
371         }
372         printTableHeader();
373         MsaProperties msa_prop = new MsaProperties( _msa, "", _calculate_shannon_entropy );
374         msa_props.add( msa_prop );
375         printMsaProperties( msa_prop );
376         System.out.println();
377         int i = 0;
378         while ( _msa.getLength() > length ) {
379             final String id = to_remove_ids.get( i );
380             _removed_seq_ids.add( id );
381             final MolecularSequence deleted = _msa.deleteRow( id, true );
382             _removed_seqs.add( deleted );
383             removeGapColumns();
384             if ( isPrintMsaStatsWriteOutfileAndRealign( i ) || ( _msa.getLength() <= length ) ) {
385                 msa_prop = printMsaStatsWriteOutfileAndRealign( _realign, id );
386                 msa_props.add( msa_prop );
387                 System.out.println();
388             }
389             else if ( isPrintMsaStats( i ) ) {
390                 msa_prop = new MsaProperties( _msa, id, _calculate_shannon_entropy );
391                 printMsaProperties( msa_prop );
392                 msa_props.add( msa_prop );
393                 System.out.println();
394             }
395             ++i;
396         }
397         if ( _removed_seqs_out_base != null ) {
398             final String msg = writeAndAlignRemovedSeqs();
399             System.out.println();
400             System.out.println( msg );
401         }
402         if ( _phylogentic_inference ) {
403             decorateTree( phy,  msa_props, false );
404             displayTree( phy );
405         }
406         return msa_props;
407     }
408
409     public final List<MsaProperties> removeWorstOffenders( final int to_remove ) throws IOException,
410     InterruptedException {
411         final GapContribution stats[] = calcGapContribtionsStats( _norm );
412         final List<String> to_remove_ids = new ArrayList<String>();
413         final List<MsaProperties> msa_props = new ArrayList<MsaProperties>();
414         for( int j = 0; j < to_remove; ++j ) {
415             to_remove_ids.add( stats[ j ].getId() );
416         }
417         Phylogeny phy = null;
418         if ( _phylogentic_inference ) {
419             System.out.println( "calculating phylogentic tree..." );
420             System.out.println();
421             phy = calcTree();
422             addSeqs2Tree( _msa, phy );
423         }
424         printTableHeader();
425         MsaProperties msa_prop = new MsaProperties( _msa, "", _calculate_shannon_entropy );
426         msa_props.add( msa_prop );
427         printMsaProperties( msa_prop );
428         System.out.println();
429         for( int i = 0; i < to_remove_ids.size(); ++i ) {
430             final String id = to_remove_ids.get( i );
431             _removed_seq_ids.add( id );
432             final MolecularSequence deleted = _msa.deleteRow( id, true );
433             _removed_seqs.add( deleted );
434             removeGapColumns();
435             if ( isPrintMsaStatsWriteOutfileAndRealign( i ) || ( i == ( to_remove_ids.size() - 1 ) ) ) {
436                 msa_prop = printMsaStatsWriteOutfileAndRealign( _realign, id );
437                 msa_props.add( msa_prop );
438                 System.out.println();
439             }
440             else if ( isPrintMsaStats( i ) ) {
441                 msa_prop = new MsaProperties( _msa, id, _calculate_shannon_entropy );
442                 msa_props.add( msa_prop );
443                 printMsaProperties( msa_prop );
444                 System.out.println();
445             }
446         }
447         if ( _removed_seqs_out_base != null ) {
448             final String msg = writeAndAlignRemovedSeqs();
449             System.out.println();
450             System.out.println( msg );
451         }
452         if ( _phylogentic_inference ) {
453             decorateTree( phy,  msa_props, false );
454             displayTree( phy );
455             
456            
457                 System.out.println( "calculating phylogentic tree..." );
458                 System.out.println();
459                 Phylogeny phy2 = calcTree();
460                 addSeqs2Tree( _msa, phy2 );
461                 displayTree( phy2 );
462             
463         }
464         return msa_props;
465     }
466
467     public final void setCalculateNormalizedShannonEntropy( final boolean calculate_shannon_entropy ) {
468         _calculate_shannon_entropy = calculate_shannon_entropy;
469     }
470
471     public void setInfileName( final String infile_name ) {
472         _infile_name = infile_name;
473     }
474
475     public final void setMafftOptions( final String maffts_opts ) {
476         _maffts_opts = maffts_opts;
477     }
478
479     public final void setNorm( final boolean norm ) {
480         _norm = norm;
481     }
482
483     final public void setOutFileBase( final File out_file_base ) {
484         _out_file_base = out_file_base;
485     }
486
487     public final void setOutputFormat( final MSA_FORMAT output_format ) {
488         _output_format = output_format;
489     }
490
491     public void setPathToMafft( final String path_to_mafft ) {
492         _path_to_mafft = path_to_mafft;
493     }
494
495     public void setPeformPhylogenticInference( final boolean phylogentic_inference ) {
496         _phylogentic_inference = phylogentic_inference;
497     }
498
499     public final void setRealign( final boolean realign ) {
500         _realign = realign;
501     }
502
503     public final void setRemovedSeqsOutBase( final File removed_seqs_out_base ) {
504         _removed_seqs_out_base = removed_seqs_out_base;
505     }
506
507     public final void setStep( final int step ) {
508         _step = step;
509     }
510
511     public final void setStepForDiagnostics( final int step_for_diagnostics ) {
512         _step_for_diagnostics = step_for_diagnostics;
513     }
514
515     final public String writeAndAlignRemovedSeqs() throws IOException, InterruptedException {
516         final StringBuilder msg = new StringBuilder();
517         final String n = _removed_seqs_out_base + "_" + _removed_seqs.size() + ".fasta";
518         SequenceWriter.writeSeqs( _removed_seqs, new File( n ), SEQ_FORMAT.FASTA, 100 );
519         msg.append( "wrote " + _removed_seqs.size() + " removed sequences to " + "\"" + n + "\"" );
520         if ( _realign ) {
521             final MsaInferrer mafft = Mafft.createInstance( _path_to_mafft );
522             final List<String> opts = new ArrayList<String>();
523             for( final String o : _maffts_opts.split( "\\s" ) ) {
524                 opts.add( o );
525             }
526             final Msa removed_msa = mafft.infer( _removed_seqs, opts );
527             final Double gr = MsaMethods.calcGapRatio( removed_msa );
528             String s = _removed_seqs_out_base + "_" + removed_msa.getNumberOfSequences() + "_"
529                     + removed_msa.getLength() + "_" + ForesterUtil.roundToInt( gr * 100 );
530             final String suffix = obtainSuffix();
531             s += suffix;
532             writeMsa( removed_msa, s, _output_format );
533             msg.append( ", and as MSA of length " + removed_msa.getLength() + " to \"" + s + "\"" );
534         }
535         return msg.toString();
536     }
537
538     final public String writeMsa( final File outfile ) throws IOException {
539         final Double gr = MsaMethods.calcGapRatio( _msa );
540         final String s = outfile + "_" + _msa.getNumberOfSequences() + "_" + _msa.getLength() + "_"
541                 + ForesterUtil.roundToInt( gr * 100 );
542         writeMsa( _msa, s + obtainSuffix(), _output_format );
543         return s;
544     }
545
546     final int calcNonGapResidues( final MolecularSequence seq ) {
547         int ng = 0;
548         for( int i = 0; i < seq.getLength(); ++i ) {
549             if ( !seq.isGapAt( i ) ) {
550                 ++ng;
551             }
552         }
553         return ng;
554     }
555
556     private final GapContribution[] calcGapContribtions( final boolean normalize_for_effective_seq_length ) {
557         final double gappiness[] = calcGappiness();
558         final GapContribution stats[] = new GapContribution[ _msa.getNumberOfSequences() ];
559         for( int row = 0; row < _msa.getNumberOfSequences(); ++row ) {
560             stats[ row ] = new GapContribution( _msa.getIdentifier( row ) );
561             for( int col = 0; col < _msa.getLength(); ++col ) {
562                 if ( !_msa.isGapAt( row, col ) ) {
563                     stats[ row ].addToValue( gappiness[ col ] );
564                 }
565             }
566             if ( normalize_for_effective_seq_length ) {
567                 stats[ row ].divideValue( calcNonGapResidues( _msa.getSequence( row ) ) );
568             }
569             else {
570                 stats[ row ].divideValue( _msa.getLength() );
571             }
572         }
573         return stats;
574     }
575
576     final private GapContribution[] calcGapContribtionsStats( final boolean norm ) {
577         final GapContribution stats[] = calcGapContribtions( norm );
578         Arrays.sort( stats );
579         return stats;
580     }
581
582     private final double[] calcGappiness() {
583         final int l = _msa.getLength();
584         final double gappiness[] = new double[ l ];
585         final int seqs = _msa.getNumberOfSequences();
586         for( int i = 0; i < l; ++i ) {
587             gappiness[ i ] = ( double ) MsaMethods.calcGapSumPerColumn( _msa, i ) / seqs;
588         }
589         return gappiness;
590     }
591
592     private final Phylogeny collapse( final Msa msa, final int threshold ) {
593         final BasicSymmetricalDistanceMatrix m = PairwiseDistanceCalculator.calcFractionalDissimilarities( msa );
594         //TODO
595         return null;
596     }
597
598     private final Phylogeny inferNJphylogeny( final PWD_DISTANCE_METHOD pwd_distance_method,
599                                               final Msa msa,
600                                               final boolean write_matrix,
601                                               final String matrix_name ) {
602         BasicSymmetricalDistanceMatrix m = null;
603         switch ( pwd_distance_method ) {
604             case KIMURA_DISTANCE:
605                 m = PairwiseDistanceCalculator.calcKimuraDistances( msa );
606                 break;
607             case POISSON_DISTANCE:
608                 m = PairwiseDistanceCalculator.calcPoissonDistances( msa );
609                 break;
610             case FRACTIONAL_DISSIMILARITY:
611                 m = PairwiseDistanceCalculator.calcFractionalDissimilarities( msa );
612                 break;
613             default:
614                 throw new IllegalArgumentException( "invalid pwd method" );
615         }
616         if ( write_matrix ) {
617             try {
618                 m.write( ForesterUtil.createBufferedWriter( matrix_name ) );
619             }
620             catch ( final IOException e ) {
621                 e.printStackTrace();
622             }
623         }
624         final NeighborJoiningF nj = NeighborJoiningF.createInstance( false, 5 );
625         final Phylogeny phy = nj.execute( m );
626         return phy;
627     }
628
629     private final boolean isPrintMsaStats( final int i ) {
630         return ( ( ( _step == 1 ) && ( _step_for_diagnostics == 1 ) ) || ( ( _step_for_diagnostics > 0 ) && ( ( ( i + 1 ) % _step_for_diagnostics ) == 0 ) ) );
631     }
632
633     private final boolean isPrintMsaStatsWriteOutfileAndRealign( final int i ) {
634         return ( ( ( _step == 1 ) && ( _step_for_diagnostics == 1 ) ) || ( ( _step > 0 ) && ( ( ( i + 1 ) % _step ) == 0 ) ) );
635     }
636
637     private final StringBuilder msaPropertiesAsSB( final MsaProperties msa_properties ) {
638         final StringBuilder sb = new StringBuilder();
639         sb.append( msa_properties.getNumberOfSequences() );
640         sb.append( "\t" );
641         sb.append( msa_properties.getLength() );
642         sb.append( "\t" );
643         sb.append( NF_4.format( msa_properties.getGapRatio() ) );
644         if ( _calculate_shannon_entropy ) {
645             sb.append( "\t" );
646             sb.append( NF_4.format( msa_properties.getEntropy7() ) );
647             sb.append( "\t" );
648             sb.append( NF_4.format( msa_properties.getEntropy21() ) );
649         }
650         return sb;
651     }
652
653     private String obtainSuffix() {
654         if ( _output_format == MSA_FORMAT.FASTA ) {
655             return ".fasta";
656         }
657         else if ( _output_format == MSA_FORMAT.PHYLIP ) {
658             return ".aln";
659         }
660         return "";
661     }
662
663     private final Phylogeny pi( final String matrix, final int boostrap ) {
664         final Phylogeny master_phy = inferNJphylogeny( PWD_DISTANCE_METHOD.KIMURA_DISTANCE, _msa, true, matrix );
665         final int seed = 15;
666         final int n = 100;
667         final ResampleableMsa resampleable_msa = new ResampleableMsa( _msa );
668         final int[][] resampled_column_positions = BootstrapResampler.createResampledColumnPositions( _msa.getLength(),
669                                                                                                       n,
670                                                                                                       seed );
671         final Phylogeny[] eval_phys = new Phylogeny[ n ];
672         for( int i = 0; i < n; ++i ) {
673             resampleable_msa.resample( resampled_column_positions[ i ] );
674             eval_phys[ i ] = inferNJphylogeny( PWD_DISTANCE_METHOD.KIMURA_DISTANCE, resampleable_msa, false, null );
675         }
676         ConfidenceAssessor.evaluate( "bootstrap", eval_phys, master_phy, true, 1 );
677         PhylogenyMethods.extractFastaInformation( master_phy );
678         return master_phy;
679     }
680
681     private final void printMsaProperties( final MsaProperties msa_properties ) {
682         if ( ( _step == 1 ) || ( _step_for_diagnostics == 1 ) ) {
683             System.out.print( ForesterUtil.pad( msa_properties.getRemovedSeq(), _longest_id_length, ' ', false ) );
684             System.out.print( "\t" );
685         }
686         System.out.print( msaPropertiesAsSB( msa_properties ) );
687         System.out.print( "\t" );
688     }
689
690     final private MsaProperties printMsaStatsWriteOutfileAndRealign( final boolean realign, final String id )
691             throws IOException, InterruptedException {
692         if ( realign ) {
693             realignWithMafft();
694         }
695         final MsaProperties msa_prop = new MsaProperties( _msa, id, _calculate_shannon_entropy );
696         printMsaProperties( msa_prop );
697         final String s = writeOutfile();
698         System.out.print( "-> " + s + ( realign ? "\t(realigned)" : "" ) );
699         return msa_prop;
700     }
701
702     private final void printTableHeader() {
703         if ( ( _step == 1 ) || ( _step_for_diagnostics == 1 ) ) {
704             System.out.print( ForesterUtil.pad( "Id", _longest_id_length, ' ', false ) );
705             System.out.print( "\t" );
706         }
707         System.out.print( "Seqs" );
708         System.out.print( "\t" );
709         System.out.print( "Length" );
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 }