in progress
[jalview.git] / forester / java / src / org / forester / archaeopteryx / tools / PhylogeneticInferrer.java
1 // $Id:
2 // forester -- software libraries and applications
3 // for genomics and evolutionary biology research.
4 //
5 // Copyright (C) 2010 Christian M Zmasek
6 // Copyright (C) 2010 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 // Contact: phylosoft @ gmail . com
24 // WWW: www.phylosoft.org/forester
25
26 package org.forester.archaeopteryx.tools;
27
28 import java.io.BufferedWriter;
29 import java.io.File;
30 import java.io.FileWriter;
31 import java.io.IOException;
32 import java.util.ArrayList;
33 import java.util.List;
34 import java.util.regex.Matcher;
35
36 import javax.swing.JOptionPane;
37
38 import org.forester.archaeopteryx.AptxUtil;
39 import org.forester.archaeopteryx.MainFrameApplication;
40 import org.forester.evoinference.distance.NeighborJoining;
41 import org.forester.evoinference.distance.PairwiseDistanceCalculator;
42 import org.forester.evoinference.matrix.distance.BasicSymmetricalDistanceMatrix;
43 import org.forester.evoinference.tools.BootstrapResampler;
44 import org.forester.io.parsers.FastaParser;
45 import org.forester.io.writers.SequenceWriter;
46 import org.forester.io.writers.SequenceWriter.SEQ_FORMAT;
47 import org.forester.msa.BasicMsa;
48 import org.forester.msa.Mafft;
49 import org.forester.msa.Msa;
50 import org.forester.msa.MsaInferrer;
51 import org.forester.msa.MsaMethods;
52 import org.forester.msa.ResampleableMsa;
53 import org.forester.phylogeny.Phylogeny;
54 import org.forester.phylogeny.PhylogenyNode;
55 import org.forester.phylogeny.data.Accession;
56 import org.forester.phylogeny.iterators.PhylogenyNodeIterator;
57 import org.forester.sequence.Sequence;
58 import org.forester.tools.ConfidenceAssessor;
59 import org.forester.util.ForesterUtil;
60
61 public class PhylogeneticInferrer extends RunnableProcess {
62
63     private Msa                                _msa;
64     private final MainFrameApplication         _mf;
65     private final PhylogeneticInferenceOptions _options;
66     private final List<Sequence>               _seqs;
67     private final boolean                      DEBUG           = true;
68     public final static String                 MSA_FILE_SUFFIX = ".aln";
69     public final static String                 PWD_FILE_SUFFIX = ".pwd";
70
71     public PhylogeneticInferrer( final List<Sequence> seqs,
72                                  final PhylogeneticInferenceOptions options,
73                                  final MainFrameApplication mf ) {
74         _msa = null;
75         _seqs = seqs;
76         _mf = mf;
77         _options = options;
78     }
79
80     public PhylogeneticInferrer( final Msa msa,
81                                  final PhylogeneticInferenceOptions options,
82                                  final MainFrameApplication mf ) {
83         _msa = msa;
84         _seqs = null;
85         _mf = mf;
86         _options = options;
87     }
88
89     private Msa inferMsa() throws IOException, InterruptedException {
90         final File temp_seqs_file = File.createTempFile( "__msa__temp__", ".fasta" );
91         if ( DEBUG ) {
92             System.out.println();
93             System.out.println( "temp file: " + temp_seqs_file );
94             System.out.println();
95         }
96         //final File temp_seqs_file = new File( _options.getTempDir() + ForesterUtil.FILE_SEPARATOR + "s.fasta" );
97         final BufferedWriter writer = new BufferedWriter( new FileWriter( temp_seqs_file ) );
98         SequenceWriter.writeSeqs( _seqs, writer, SEQ_FORMAT.FASTA, 100 );
99         writer.close();
100         final List<String> opts = processMafftOptions();
101         return runMAFFT( temp_seqs_file, opts );
102     }
103
104     private List<String> processMafftOptions() {
105         final String opts_str = _options.getMsaPrgParameters().trim().toLowerCase();
106         final String[] opts_ary = opts_str.split( " " );
107         final List<String> opts = new ArrayList<String>();
108         boolean saw_quiet = false;
109         for( final String opt : opts_ary ) {
110             opts.add( opt );
111             if ( opt.equals( "--quiet" ) ) {
112                 saw_quiet = true;
113             }
114         }
115         if ( !saw_quiet ) {
116             opts.add( "--quiet" );
117         }
118         return opts;
119     }
120
121     private Phylogeny inferPhylogeny( final Msa msa ) {
122         BasicSymmetricalDistanceMatrix m = null;
123         switch ( _options.getPwdDistanceMethod() ) {
124             case KIMURA_DISTANCE:
125                 m = PairwiseDistanceCalculator.calcKimuraDistances( msa );
126                 break;
127             case POISSON_DISTANCE:
128                 m = PairwiseDistanceCalculator.calcPoissonDistances( msa );
129                 break;
130             case FRACTIONAL_DISSIMILARITY:
131                 m = PairwiseDistanceCalculator.calcFractionalDissimilarities( msa );
132                 break;
133             default:
134                 throw new RuntimeException( "invalid pwd method" );
135         }
136         if ( !ForesterUtil.isEmpty( _options.getIntermediateFilesBase() ) ) {
137             BufferedWriter pwd_writer;
138             try {
139                 pwd_writer = new BufferedWriter( new FileWriter( _options.getIntermediateFilesBase() + PWD_FILE_SUFFIX ) );
140                 m.write( pwd_writer );
141                 pwd_writer.close();
142             }
143             catch ( final IOException e ) {
144                 // TODO Auto-generated catch block
145                 e.printStackTrace();
146             }
147         }
148         final NeighborJoining nj = NeighborJoining.createInstance();
149         final Phylogeny phy = nj.execute( m );
150         PhylogeneticInferrer.extractFastaInformation( phy );
151         return phy;
152     }
153
154     private void infer() throws InterruptedException {
155         //_mf.getMainPanel().getCurrentTreePanel().setWaitCursor();
156         if ( ( _msa == null ) && ( _seqs == null ) ) {
157             throw new IllegalArgumentException( "cannot run phylogenetic analysis with null msa and seq array" );
158         }
159         start( _mf, "phylogenetic inference" );
160         if ( _msa == null ) {
161             Msa msa = null;
162             try {
163                 msa = inferMsa();
164             }
165             catch ( final IOException e ) {
166                 end( _mf );
167                 JOptionPane.showMessageDialog( _mf,
168                                                "Could not create multiple sequence alignment with \""
169                                                        + _options.getMsaPrg() + "\" and the following parameters:\n\""
170                                                        + _options.getMsaPrgParameters() + "\"\nError: "
171                                                        + e.getLocalizedMessage(),
172                                                "Failed to Calculate MSA",
173                                                JOptionPane.ERROR_MESSAGE );
174                 if ( DEBUG ) {
175                     e.printStackTrace();
176                 }
177                 return;
178             }
179             catch ( final Exception e ) {
180                 end( _mf );
181                 JOptionPane.showMessageDialog( _mf,
182                                                "Could not create multiple sequence alignment with \""
183                                                        + _options.getMsaPrg() + "\" and the following parameters:\n\""
184                                                        + _options.getMsaPrgParameters() + "\"\nError: "
185                                                        + e.getLocalizedMessage(),
186                                                "Unexpected Exception During MSA Calculation",
187                                                JOptionPane.ERROR_MESSAGE );
188                 if ( DEBUG ) {
189                     e.printStackTrace();
190                 }
191                 return;
192             }
193             if ( msa == null ) {
194                 end( _mf );
195                 JOptionPane.showMessageDialog( _mf,
196                                                "Could not create multiple sequence alignment with "
197                                                        + _options.getMsaPrg() + "\nand the following parameters:\n\""
198                                                        + _options.getMsaPrgParameters() + "\"",
199                                                "Failed to Calculate MSA",
200                                                JOptionPane.ERROR_MESSAGE );
201                 return;
202             }
203             if ( DEBUG ) {
204                 System.out.println( msa.toString() );
205                 System.out.println( MsaMethods.calcBasicGapinessStatistics( msa ).toString() );
206             }
207             final MsaMethods msa_tools = MsaMethods.createInstance();
208             if ( _options.isExecuteMsaProcessing() ) {
209                 msa = msa_tools.removeGapColumns( _options.getMsaProcessingMaxAllowedGapRatio(),
210                                                   _options.getMsaProcessingMinAllowedLength(),
211                                                   msa );
212                 if ( msa == null ) {
213                     end( _mf );
214                     JOptionPane.showMessageDialog( _mf,
215                                                    "Less than two sequences longer than "
216                                                            + _options.getMsaProcessingMinAllowedLength()
217                                                            + " residues left after MSA processing",
218                                                    "MSA Processing Settings Too Stringent",
219                                                    JOptionPane.ERROR_MESSAGE );
220                     return;
221                 }
222             }
223             if ( DEBUG ) {
224                 System.out.println( msa_tools.getIgnoredSequenceIds() );
225                 System.out.println( msa.toString() );
226                 System.out.println( MsaMethods.calcBasicGapinessStatistics( msa ).toString() );
227             }
228             _msa = msa;
229         }
230         final int n = _options.getBootstrapSamples();
231         final long seed = _options.getRandomNumberGeneratorSeed();
232         final Phylogeny master_phy = inferPhylogeny( _msa );
233         if ( _options.isPerformBootstrapResampling() && ( n > 0 ) ) {
234             final ResampleableMsa resampleable_msa = new ResampleableMsa( ( BasicMsa ) _msa );
235             final int[][] resampled_column_positions = BootstrapResampler.createResampledColumnPositions( _msa
236                     .getLength(), n, seed );
237             final Phylogeny[] eval_phys = new Phylogeny[ n ];
238             for( int i = 0; i < n; ++i ) {
239                 resampleable_msa.resample( resampled_column_positions[ i ] );
240                 eval_phys[ i ] = inferPhylogeny( resampleable_msa );
241             }
242             ConfidenceAssessor.evaluate( "bootstrap", eval_phys, master_phy, true, 1 );
243         }
244         _mf.getMainPanel().addPhylogenyInNewTab( master_phy, _mf.getConfiguration(), "nj", "njpath" );
245         //  _mf.getMainPanel().getCurrentTreePanel().setArrowCursor();
246         end( _mf );
247         JOptionPane.showMessageDialog( _mf,
248                                        "Inference successfully completed",
249                                        "Inference Completed",
250                                        JOptionPane.INFORMATION_MESSAGE );
251     }
252
253     @Override
254     public void run() {
255         try {
256             infer();
257         }
258         catch ( final InterruptedException e ) {
259             // TODO need to handle this exception SOMEHOW!
260             // TODO Auto-generated catch block
261             e.printStackTrace();
262         }
263     }
264
265     private Msa runMAFFT( final File input_seqs, final List<String> opts ) throws IOException, InterruptedException {
266         Msa msa = null;
267         final MsaInferrer mafft = Mafft.createInstance();
268         try {
269             msa = mafft.infer( input_seqs, opts );
270         }
271         catch ( final IOException e ) {
272             System.out.println( mafft.getErrorDescription() );
273         }
274         return msa;
275     }
276
277     private void writeToFiles( final BasicSymmetricalDistanceMatrix m ) {
278         if ( !ForesterUtil.isEmpty( _options.getIntermediateFilesBase() ) ) {
279             try {
280                 final BufferedWriter msa_writer = new BufferedWriter( new FileWriter( _options.getIntermediateFilesBase()
281                         + MSA_FILE_SUFFIX ) );
282                 _msa.write( msa_writer );
283                 msa_writer.close();
284                 final BufferedWriter pwd_writer = new BufferedWriter( new FileWriter( _options.getIntermediateFilesBase()
285                         + PWD_FILE_SUFFIX ) );
286                 m.write( pwd_writer );
287                 pwd_writer.close();
288             }
289             catch ( final Exception e ) {
290                 System.out.println( "Error: " + e.getMessage() );
291             }
292         }
293     }
294
295     public static void extractFastaInformation( final Phylogeny phy ) {
296         for( final PhylogenyNodeIterator iter = phy.iteratorExternalForward(); iter.hasNext(); ) {
297             final PhylogenyNode node = iter.next();
298             if ( !ForesterUtil.isEmpty( node.getName() ) ) {
299                 final Matcher name_m = FastaParser.FASTA_DESC_LINE.matcher( node.getName() );
300                 if ( name_m.lookingAt() ) {
301                     System.out.println();
302                     // System.out.println( name_m.group( 1 ) );
303                     // System.out.println( name_m.group( 2 ) );
304                     // System.out.println( name_m.group( 3 ) );
305                     // System.out.println( name_m.group( 4 ) );
306                     final String acc_source = name_m.group( 1 );
307                     final String acc = name_m.group( 2 );
308                     final String seq_name = name_m.group( 3 );
309                     final String tax_sn = name_m.group( 4 );
310                     if ( !ForesterUtil.isEmpty( acc_source ) && !ForesterUtil.isEmpty( acc ) ) {
311                         AptxUtil.ensurePresenceOfSequence( node );
312                         node.getNodeData().getSequence( 0 ).setAccession( new Accession( acc, acc_source ) );
313                     }
314                     if ( !ForesterUtil.isEmpty( seq_name ) ) {
315                         AptxUtil.ensurePresenceOfSequence( node );
316                         node.getNodeData().getSequence( 0 ).setName( seq_name );
317                     }
318                     if ( !ForesterUtil.isEmpty( tax_sn ) ) {
319                         AptxUtil.ensurePresenceOfTaxonomy( node );
320                         node.getNodeData().getTaxonomy( 0 ).setScientificName( tax_sn );
321                     }
322                 }
323             }
324         }
325     }
326 }