Debian Codegraph @

src/dr/evomodel/substmodel/ProductChainSubstitutionModel.java

raw symbols SCIP
1 /*
2 * ProductChainSubstitutionModel.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.evomodel.substmodel;
27
28 import dr.evomodel.siteratemodel.SiteRateModel;
29 import dr.evolution.datatype.DataType;
30 import dr.evolution.datatype.GeneralDataType;
31 import dr.inference.model.Model;
32 import dr.math.KroneckerOperation;
33 import dr.util.Citable;
34 import dr.util.Citation;
35 import dr.util.CommonCitations;
36
37 import java.util.*;
38 import java.util.logging.Logger;
39
40 //import dr.math.matrixAlgebra.Vector;
41
42 /**
43 * @author Marc A. Suchard
44 * @author Vladimir Minin
45 * <p/>
46 * A class for implementing a kronecker sum of CTMC models in BEAST using BEAGLE
47 * This work is supported by NSF grant 0856099
48 * <p/>
49 * O'Brien JD, Minin VN and Suchard MA (2009) Learning to count: robust estimates for labeled distances between
50 * molecular sequences. Molecular Biology and Evolution, 26, 801-814
51 */
52 public class ProductChainSubstitutionModel extends BaseSubstitutionModel implements Citable {
53
54 public ProductChainSubstitutionModel(String name, List<SubstitutionModel> baseModels) {
55 this(name, baseModels, null);
56 }
57
58 public ProductChainSubstitutionModel(String name,
59 List<SubstitutionModel> baseModels,
60 List<SiteRateModel> rateModels) {
61 this(name, baseModels, rateModels, false);
62 }
63
64 public ProductChainSubstitutionModel(String name,
65 List<SubstitutionModel> baseModels,
66 List<SiteRateModel> rateModels,
67 boolean forceAverageModel) {
68 super(name);
69
70 this.baseModels = baseModels;
71 this.rateModels = rateModels;
72 this.forceAverageModel = forceAverageModel;
73 numBaseModel = baseModels.size();
74
75 if (numBaseModel == 0) {
76 throw new RuntimeException("May not construct ProductChainSubstitutionModel with 0 base models");
77 }
78
79 if (rateModels != null) {
80 for(SiteRateModel rateModel : rateModels) {
81 if (rateModel.getCategoryCount() > 1) {
82 throw new RuntimeException("ProductChainSubstitutionModels with multiple categories not yet implemented");
83 }
84 }
85 }
86
87 List<FrequencyModel> freqModels = new ArrayList<FrequencyModel>();
88 stateSizes = new int[numBaseModel];
89 stateCount = 1;
90 for (int i = 0; i < numBaseModel; i++) {
91 freqModels.add(baseModels.get(i).getFrequencyModel());
92 DataType dataType = baseModels.get(i).getDataType();
93 stateSizes[i] = dataType.getStateCount();
94 stateCount *= dataType.getStateCount();
95 addModel(baseModels.get(i));
96 addModel(rateModels.get(i));
97 }
98
99 pcFreqModel = new ProductChainFrequencyModel("pc",freqModels);
100 addModel(pcFreqModel);
101
102 String[] codeStrings = getCharacterStrings();
103
104 dataType = new GeneralDataType(codeStrings);
105
106 updateMatrix = true;
107
108 }
109
110 @Override
111 public Citation.Category getCategory() {
112 return Citation.Category.SUBSTITUTION_MODELS;
113 }
114
115 @Override
116 public String getDescription() {
117 return "Product chain substitution model";
118 }
119
120 public List<Citation> getCitations() {
121 return Collections.singletonList(CommonCitations.OBRIEN_2009_LEARNING);
122 }
123
124 public EigenDecomposition getEigenDecomposition() {
125 synchronized (this) {
126 if (updateMatrix) {
127 computeKroneckerSumsAndProducts();
128 }
129 }
130 return eigenDecomposition;
131 }
132
133 private String[] getCharacterStrings() {
134 String[] strings = null;
135 for (int i = numBaseModel - 1; i >= 0; i--) {
136 strings = recursivelyAppendCharacterStates(baseModels.get(i).getDataType(), strings);
137 }
138
139 return strings;
140 }
141
142 protected void handleModelChangedEvent(Model model, Object object, int index) {
143 super.handleModelChangedEvent(model, object, index);
144 // Propogate change to higher models
145 fireModelChanged(model);
146 averageModel = null;
147 }
148
149 private String[] recursivelyAppendCharacterStates(DataType dataType, String[] inSubStates) {
150
151 String[] subStates = inSubStates;
152 if (subStates == null) {
153 subStates = new String[]{""};
154 }
155
156 final int previousStateCount = subStates.length;
157 final int inStateCount = dataType.getStateCount();
158 String[] states = new String[previousStateCount * inStateCount];
159
160 for (int i = 0; i < inStateCount; i++) {
161 String code = dataType.getCode(i);
162 for (int j = 0; j < previousStateCount; j++) {
163 states[i * previousStateCount + j] = code + subStates[j];
164 }
165 }
166 return states;
167 }
168
169 public void getInfinitesimalMatrix(double[] out) {
170 getEigenDecomposition(); // Updates rate matrix if necessary
171 System.arraycopy(rateMatrix, 0, out, 0, stateCount * stateCount);
172 }
173
174 double getRateForModel(int index) {
175 if (!forceAverageModel) {
176 return rateModels.get(index).getRateForCategory(0);
177 } else {
178 double total = 0.0;
179 for (int i = 0; i < rateModels.size(); ++i) {
180 total += rateModels.get(i).getRateForCategory(0);
181 }
182 return total / rateModels.size();
183 }
184 }
185
186 protected double[] scaleForProductChain(double[] in, int model) {
187 if (rateModels == null) {
188 return in;
189 }
190 final double scalar = getRateForModel(model);
191 if (scalar == 1.0) {
192 return in;
193 }
194 final int len = in.length;
195 double[] out = new double[len];
196 for (int i = 0; i < len; i++) {
197 out[i] = scalar * in[i];
198 }
199 return out;
200 }
201
202 private SubstitutionProcess computeAverageModel() {
203
204 return new SubstitutionProcess() {
205 @Override
206 public void getTransitionProbabilities(double distance, double[] matrix) {
207 throw new RuntimeException("Should not be called");
208 }
209
210 @Override
211 public EigenDecomposition getEigenDecomposition() {
212 if (eigenDecomposition == null) {
213
214 // System.err.println("Statecount = " + stateSizes[0]);
215 // System.exit(-1);
216
217 double[][] mat = new double[stateSizes[0]][stateSizes[0]];
218 double[] vec = new double[stateSizes[0] * stateSizes[0]];
219 getInfinitesimalMatrix(vec);
220 for (int i = 0; i < stateSizes[0]; ++i) {
221 System.arraycopy(vec, i * stateSizes[0], mat[i], 0, stateSizes[0]);
222 }
223 eigenDecomposition = getDefaultEigenSystem(stateSizes[0]).decomposeMatrix(mat);
224 }
225 return eigenDecomposition;
226 }
227
228 @Override
229 public FrequencyModel getFrequencyModel() {
230 throw new RuntimeException("Should not be called");
231 }
232
233 @Override
234 public void getInfinitesimalMatrix(double[] matrix) {
235 if (averageMatrix == null) {
236 final int dim = matrix.length;
237 averageMatrix = new double[dim];
238
239 double[][] allMatrices = new double[baseModels.size()][dim];
240 for (int i = 0; i < baseModels.size(); ++i) {
241 baseModels.get(i).getInfinitesimalMatrix(allMatrices[i]);
242 }
243
244 for (int i = 0; i < dim; ++i) {
245 double total = 0.0;
246 for (int j = 0; j < baseModels.size(); ++j) {
247 total += allMatrices[j][i];
248 }
249 total /= baseModels.size();
250 averageMatrix[i] = total;
251 }
252 }
253 // System.err.println("averageMatrix.length " + averageMatrix.length);
254 // System.err.println("matrix.length " + matrix.length);
255 System.arraycopy(averageMatrix, 0, matrix, 0, averageMatrix.length);
256 }
257
258 @Override
259 public DataType getDataType() {
260 throw new RuntimeException("Should not be called");
261 }
262
263 @Override
264 public boolean canReturnComplexDiagonalization() {
265 throw new RuntimeException("Should not be called");
266 }
267
268 private double[] averageMatrix = null;
269 private EigenDecomposition eigenDecomposition = null;
270 };
271 }
272
273 // private SubstitutionProcess getAverageModel() {
274 // if (!forceAverageModel) {
275 // throw new RuntimeException("Error getting averaged model with non-averaged product chain");
276 // }
277 // if (averageModel == null) {
278 // averageModel = computeAverageModel();
279 // }
280 // return averageModel;
281 // }
282
283 private SubstitutionProcess getBaseModel(int index) {
284 if (!forceAverageModel) {
285 return baseModels.get(index);
286 } else {
287 if (averageModel == null) {
288 averageModel = computeAverageModel();
289 }
290 return averageModel;
291 }
292 }
293
294 private void computeKroneckerSumsAndProducts() {
295
296 // if (forceAverageModel) {
297 // if (averageModel == null) {
298 // averageModel = computeAverageModel();
299 // }
300 // eigenDecomposition = averageModel.getEigenDecomposition();
301 // if (rateMatrix == null) {
302 // rateMatrix = new double[stateCount * stateCount];
303 // }
304 // averageModel.getInfinitesimalMatrix(rateMatrix);
305 // updateMatrix = false;
306 //
307 // System.err.println("lambda = " + new Vector(rateMatrix));
308 //
309 // return;
310 // }
311
312 int currentStateSize = stateSizes[0];
313 double[] currentRate = new double[currentStateSize * currentStateSize];
314 getBaseModel(0).getInfinitesimalMatrix(currentRate);
315 currentRate = scaleForProductChain(currentRate, 0);
316
317 EigenDecomposition currentED = getBaseModel(0).getEigenDecomposition();
318 double[] currentEval = scaleForProductChain(currentED.getEigenValues(), 0);
319 double[] currentEvec = currentED.getEigenVectors();
320 double[] currentIevcT = transpose(currentED.getInverseEigenVectors(), currentStateSize);
321
322 for (int i = 1; i < numBaseModel; i++) {
323 SubstitutionProcess nextModel = getBaseModel(i);
324 int nextStateSize = stateSizes[i];
325 double[] nextRate = new double[nextStateSize * nextStateSize];
326 nextModel.getInfinitesimalMatrix(nextRate);
327 nextRate = scaleForProductChain(nextRate, i);
328 currentRate = KroneckerOperation.sum(currentRate, currentStateSize, nextRate, nextStateSize);
329
330 EigenDecomposition nextED = nextModel.getEigenDecomposition();
331 double[] nextEval = scaleForProductChain(nextED.getEigenValues(), i);
332 double[] nextEvec = nextED.getEigenVectors();
333 double[] nextIevcT = transpose(nextED.getInverseEigenVectors(), nextStateSize);
334
335 currentEval = KroneckerOperation.sum(currentEval, nextEval);
336
337 currentEvec = KroneckerOperation.product(
338 currentEvec, currentStateSize, currentStateSize,
339 nextEvec, nextStateSize, nextStateSize);
340
341 currentIevcT = KroneckerOperation.product(
342 currentIevcT, currentStateSize, currentStateSize,
343 nextIevcT, nextStateSize, nextStateSize);
344 currentStateSize *= nextStateSize;
345
346 }
347
348 rateMatrix = currentRate;
349
350 eigenDecomposition = new EigenDecomposition(
351 currentEvec,
352 transpose(currentIevcT, currentStateSize),
353 currentEval);
354 updateMatrix = false;
355 }
356
357 // private static void printSquareMatrix(double[] A, int dim) {
358 // double[] row = new double[dim];
359 // for (int i = 0; i < dim; i++) {
360 // System.arraycopy(A, i * dim, row, 0, dim);
361 // System.err.println(new Vector(row));
362 // }
363 // }
364
365 // transposes a square matrix
366 private static double[] transpose(double[] mat, int dim) {
367 double[] out = new double[dim * dim];
368 for (int i = 0; i < dim; i++) {
369 for (int j = 0; j < dim; j++) {
370 out[j * dim + i] = mat[i * dim + j];
371 }
372 }
373 return out;
374 }
375
376 public FrequencyModel getFrequencyModel() {
377 return pcFreqModel;
378 }
379
380 protected void frequenciesChanged() {
381 // Do nothing
382 }
383
384 protected void ratesChanged() {
385 // Do nothing
386 }
387
388 protected void setupRelativeRates(double[] rates) {
389 // Do nothing
390 }
391
392 protected final int numBaseModel;
393 protected final List<SubstitutionModel> baseModels;
394 protected final List<SiteRateModel> rateModels;
395 protected final int[] stateSizes;
396 protected final ProductChainFrequencyModel pcFreqModel;
397 protected double[] rateMatrix = null;
398 private final boolean forceAverageModel;
399 private SubstitutionProcess averageModel = null;
400
401 }