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