Debian Codegraph @

src/dr/app/misc/Coevolve.java

raw symbols SCIP
1 /*
2 * Coevolve.java
3 *
4 * Copyright (c) 2002-2015 Alexei Drummond, Andrew Rambaut and Marc Suchard
5 *
6 * This file is part of BEAST.
7 * See the NOTICE file distributed with this work for additional
8 * information regarding copyright ownership and licensing.
9 *
10 * BEAST is free software; you can redistribute it and/or modify
11 * it under the terms of the GNU Lesser General Public License as
12 * published by the Free Software Foundation; either version 2
13 * of the License, or (at your option) any later version.
14 *
15 * BEAST is distributed in the hope that it will be useful,
16 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 * GNU Lesser General Public License for more details.
19 *
20 * You should have received a copy of the GNU Lesser General Public
21 * License along with BEAST; if not, write to the
22 * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
23 * Boston, MA 02110-1301 USA
24 */
25
26 package dr.app.misc;
27
28 import dr.app.util.Utils;
29 import dr.evolution.alignment.*;
30 import dr.evolution.datatype.DataType;
31 import dr.evolution.datatype.GeneralDataType;
32 import dr.evolution.io.Importer;
33 import dr.evolution.io.NexusImporter;
34 import dr.evolution.sequence.Sequence;
35 import dr.evolution.tree.Tree;
36 import dr.evolution.util.TaxonList;
37 import dr.oldevomodel.sitemodel.GammaSiteModel;
38 import dr.oldevomodel.sitemodel.SiteModel;
39 import dr.evomodel.substmodel.*;
40 import dr.evomodel.tree.TreeModel;
41 import dr.oldevomodel.substmodel.FrequencyModel;
42 import dr.oldevomodel.treelikelihood.TreeLikelihood;
43 import dr.inference.model.Parameter;
44 import dr.math.*;
45 import dr.oldevomodel.substmodel.GeneralSubstitutionModel;
46 import dr.oldevomodel.substmodel.SubstitutionModel;
47
48 import java.io.*;
49
50 /**
51 * @author Alexei Drummond
52 * @author Andrew Rambaut
53 *
54 * @version $Id: Coevolve.java,v 1.3 2006/01/09 15:12:17 rambaut Exp $
55 */
56 public class Coevolve {
57
58 public Coevolve(String fileName, String treeFileName) throws java.io.IOException {
59
60 Alignment alignment = null;
61 Tree tree = null;
62
63 try {
64 alignment = readNexusFile(fileName);
65 tree = readTreeFile(treeFileName);
66
67 } catch (IOException ioex) {
68 System.err.println("File I/O Error: " + ioex);
69 return;
70 } catch (Exception ex) {
71 System.err.println("Fatal exception: " + ex);
72 return;
73 }
74
75 if (alignment == null) {
76 System.err.println("No alignment in file: " + fileName);
77 return;
78 }
79
80 if (tree == null) {
81 System.err.println("No tree in file: " + fileName);
82 return;
83 }
84
85 System.out.println("Alignment read: " + alignment.getSequenceCount() + " taxa, " + alignment.getSiteCount() + " sites.");
86 System.out.println("Tree read: " + tree.getTaxonCount() + " taxa.");
87
88 PrintWriter pw = new PrintWriter(new FileWriter(fileName + ".out"));
89 for (int dist = 3; dist < Math.min(alignment.getSiteCount()-200,2000); dist += 3) {
90
91 System.out.print(dist+"\t");
92 pw.write(dist+"\t");
93 // create a pair alignment of only third positions
94 Alignment pairAlignment = makePairAlignment(alignment, dist,2,3);
95 SitePatterns sitePatterns = new SitePatterns(pairAlignment);
96
97 Parameter beta = new Parameter.Default(2, 1.0);
98 beta.setId("betakappa");
99 SubstitutionModel pairModel = makePairSubstModel(alignment, pairAlignment, beta);
100 runModel2(sitePatterns, pw, tree, pairModel, beta);
101 }
102 }
103
104 private SubstitutionModel makePairSubstModel(Alignment alignment, Alignment pairAlignment, Parameter beta) {
105
106 DataType newDataType = makePairDataType(alignment);
107
108 double[] frequencies = pairAlignment.getStateFrequencies();
109 Parameter frequencyParameter = new Parameter.Default(frequencies);
110 FrequencyModel freqModel = new FrequencyModel(newDataType, frequencyParameter);
111
112 return new SitePairSubstitutionModel(newDataType, freqModel, beta);
113 }
114
115 class SitePairSubstitutionModel extends GeneralSubstitutionModel {
116
117 public SitePairSubstitutionModel(DataType dataType, FrequencyModel freqModel, Parameter beta) {
118 super(dataType, freqModel, beta, 0);
119 }
120
121 protected void setupRelativeRates() {
122
123 // WARNING!! Assumes nucleotides!
124
125 int stateCount = dataType.getStateCount();
126
127 int k = 0;
128 for (int i = 0; i < stateCount; i++) {
129 for (int j = i+1; j < stateCount; j++) {
130 relativeRates[k] = 1.0;
131 int x1 = i % 4;
132 int y1 = i / 4;
133 int x2 = j % 4;
134 int y2 = j / 4;
135 // if both nucleotides different in the two pairs then use beta
136 if (x1 != x2 && y1 != y2) {
137 relativeRates[k] = ratesParameter.getParameterValue(0);
138 }
139
140 // if transition at first position then multiply rate by kappa
141 if (x1 != x2 && (x1 % 2 == x2 % 2)) {
142 relativeRates[k] *= ratesParameter.getParameterValue(1);
143 }
144 // if transition at second position then multiply rate by kappa
145 if (y1 != y2 && (y1 % 2 == y2 % 2)) {
146 relativeRates[k] *= ratesParameter.getParameterValue(1);
147 }
148
149 k += 1;
150 }
151 }
152 }
153 }
154
155 private DataType makePairDataType(Alignment alignment) {
156
157 DataType dataType = alignment.getDataType();
158 int stateCount = dataType.getStateCount();
159
160 String[] stateChars = new String[stateCount*stateCount];
161 for (int i = 0; i < Math.min(10, stateChars.length); i++) { stateChars[i] = String.valueOf((char)('0' + i)); }
162 if (stateCount > 10) {
163 for (int i = 10; i < stateChars.length; i++) { stateChars[i] = String.valueOf((char)('A' + i-10)); }
164 }
165
166 GeneralDataType newDataType = new GeneralDataType(stateChars);
167 // int[] ambiguities = new int[stateChars.length];
168 // for (int i = 0; i < ambiguities.length; i++) {
169 // ambiguities[i] = i;
170 // }
171 //
172 // // question mark for unknown states
173 // newDataType.addAmbiguity("?", ambiguities);
174
175 return newDataType;
176 }
177
178 /**
179 * @param alignment
180 * @param dist the distance |i-j| between the site pairs (j = i + dist).
181 * @param start the first i value considered
182 * @param step the distance between successive i values (i += step)
183 * @return an alignment of sites, where each site corresponds to a pair (i, j) in the old alignment.
184 */
185 private Alignment makePairAlignment(Alignment alignment, int dist, int start, int step) {
186
187 DataType dataType = alignment.getDataType();
188 int stateCount = dataType.getStateCount();
189
190 DataType newDataType = makePairDataType(alignment);
191
192 SimpleAlignment pairAlignment = new SimpleAlignment();
193 pairAlignment.setDataType(newDataType);
194 for (int k = 0; k < alignment.getSequenceCount(); k++) {
195 StringBuffer sequence = new StringBuffer();
196 for (int i = start; (i+dist) < alignment.getSiteCount(); i+= step) {
197 int j = i + dist;
198
199 int state = alignment.getState(k,i) * stateCount + alignment.getState(k, j);
200 if (state < newDataType.getStateCount()) {
201 sequence.append(newDataType.getChar(state));
202 } else {
203 sequence.append('?');
204 }
205 }
206 pairAlignment.addSequence(new Sequence(alignment.getTaxon(k),sequence.toString()));
207 }
208 return pairAlignment;
209 }
210
211 private void runModel2(PatternList patternList, PrintWriter pw, Tree tree, SubstitutionModel substModel, final Parameter betaParameter) {
212
213 final Parameter muParameter = new Parameter.Default(1.0);
214 muParameter.setId("mu");
215
216 SiteModel siteModel = new GammaSiteModel(substModel, muParameter, null, 1, null);
217 TreeModel treeModel = new TreeModel(tree);
218 final TreeLikelihood treeLikelihood = new TreeLikelihood(patternList, treeModel, siteModel, null, null, false, false, true, false, false);
219 treeLikelihood.setId("likelihood");
220
221 MultivariateFunction function = new MultivariateFunction() {
222
223 public double evaluate(double[] argument) {
224 betaParameter.setParameterValue(0, argument[0]);
225 betaParameter.setParameterValue(1, argument[1]);
226 muParameter.setParameterValue(0, argument[2]);
227 double lnL = -treeLikelihood.getLogLikelihood();
228
229 // System.err.println("" + argument[0] + "\t" + argument[1] + "\t" + argument[2] + "\t" + lnL);
230 return lnL;
231 }
232
233 public int getNumArguments() {
234 return 3;
235 }
236
237 public double getLowerBound(int n) {
238 return 0.0;
239 }
240
241 public double getUpperBound(int n) {
242 return 100.0;
243 }
244 };
245
246 MultivariateMinimum optimizer = new ConjugateGradientSearch();
247 double lnL = optimizer.findMinimum(function, new double[] { 1.0, 1.0, 1.0}, 6, 6);
248 pw.write(betaParameter.getParameterValue(0)+"\t");
249 pw.write(betaParameter.getParameterValue(1)+"\t");
250 pw.write(muParameter.getParameterValue(0)+"\t");
251 pw.write(lnL+"\n");
252 pw.flush();
253 System.out.println("" + betaParameter.getParameterValue(0) + "\t" + betaParameter.getParameterValue(1)+"\t" + muParameter.getParameterValue(0)+"\t" + lnL);
254 }
255
256 /**
257 * @param fileName
258 * @throws java.io.IOException
259 */
260 private Alignment readNexusFile(String fileName) throws java.io.IOException {
261
262 Alignment alignment = null;
263 TaxonList taxonList = null;
264
265 try {
266 FileReader reader = new FileReader(fileName);
267
268 NexusImporter importer = new NexusImporter(reader);
269
270 boolean done = false;
271
272 while (!done) {
273 try {
274
275 NexusImporter.NexusBlock block = importer.findNextBlock();
276
277 if (block == NexusImporter.TAXA_BLOCK) {
278
279 if (taxonList != null) {
280 throw new NexusImporter.MissingBlockException("TAXA block already defined");
281 }
282
283 taxonList = importer.parseTaxaBlock();
284
285 } else if (block == NexusImporter.DATA_BLOCK) {
286
287 // A data block doesn't need a taxon block before it
288 // but if one exists then it will use it.
289 alignment = importer.parseDataBlock(taxonList);
290 if (taxonList == null) {
291 taxonList = alignment;
292 }
293
294 } else if (block == NexusImporter.TREES_BLOCK) {
295
296 // ignore tree block
297 } else {
298 // Ignore the block..
299 }
300
301 } catch (EOFException ex) {
302 done = true;
303 }
304 }
305
306 } catch (Importer.ImportException ime) {
307 System.err.println("Error reading alignment: " + ime);
308 }
309
310 return alignment;
311 }
312
313 /**
314 * @param fileName
315 * @throws java.io.IOException
316 */
317 private Tree readTreeFile(String fileName) throws java.io.IOException {
318
319 Alignment alignment = null;
320 Tree[] trees = null;
321 TaxonList taxonList = null;
322
323 try {
324 FileReader reader = new FileReader(fileName);
325
326 NexusImporter importer = new NexusImporter(reader);
327
328 boolean done = false;
329
330 while (!done) {
331 try {
332
333 NexusImporter.NexusBlock block = importer.findNextBlock();
334
335 if (block == NexusImporter.TAXA_BLOCK) {
336
337 if (taxonList != null) {
338 throw new NexusImporter.MissingBlockException("TAXA block already defined");
339 }
340
341 taxonList = importer.parseTaxaBlock();
342
343 } else if (block == NexusImporter.DATA_BLOCK) {
344
345 // A data block doesn't need a taxon block before it
346 // but if one exists then it will use it.
347 alignment = importer.parseDataBlock(taxonList);
348 if (taxonList == null) {
349 taxonList = alignment;
350 }
351
352 } else if (block == NexusImporter.TREES_BLOCK) {
353
354 trees = importer.parseTreesBlock(taxonList);
355 if (taxonList == null) {
356 taxonList = alignment;
357 }
358
359 } else {
360 // Ignore the block..
361 }
362
363 } catch (EOFException ex) {
364 done = true;
365 }
366 }
367
368 } catch (Importer.ImportException ime) {
369 System.err.println("Error reading alignment: " + ime);
370 }
371
372 return trees[0];
373 }
374
375 // Main entry point
376 static public void main(String[] args) throws java.io.IOException {
377 if (args.length > 2) {
378 System.err.println("Unknown option: " + args[3]);
379 System.err.println();
380 System.out.println("Usage: misc <alignmentfilename> <treefilename> <outputFileName>");
381 System.exit(1);
382 }
383
384 String inputFileName = null;
385 String treeFileName = null;
386
387 if (args.length > 0) {
388 inputFileName = args[0];
389 }
390
391 if (args.length > 1) {
392 treeFileName = args[1];
393 }
394
395
396 if (inputFileName == null) {
397 // No input file name was given so throw up a dialog box...
398 inputFileName = Utils.getLoadFileName("Select NEXUS file to analyse");
399 }
400
401 if (treeFileName == null) {
402 // No input file name was given so throw up a dialog box...
403 treeFileName = Utils.getLoadFileName("Select tree file to analyse");
404 }
405
406 new Coevolve(inputFileName, treeFileName);
407 }
408
409 }