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