Debian Codegraph @

src/dr/oldevomodel/substmodel/ComplexSubstitutionModel.java

raw symbols SCIP
1 /*
2 * ComplexSubstitutionModel.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.oldevomodel.substmodel;
27
28 import cern.colt.matrix.DoubleMatrix1D;
29 import cern.colt.matrix.DoubleMatrix2D;
30 import cern.colt.matrix.impl.DenseDoubleMatrix2D;
31 import cern.colt.matrix.linalg.Algebra;
32 import cern.colt.matrix.linalg.EigenvalueDecomposition;
33 import cern.colt.matrix.linalg.Property;
34 import dr.evolution.datatype.DataType;
35 import dr.inference.loggers.LogColumn;
36 import dr.inference.loggers.NumberColumn;
37 import dr.inference.model.*;
38 import dr.math.matrixAlgebra.Matrix;
39 import dr.math.matrixAlgebra.RobustEigenDecomposition;
40 import dr.math.matrixAlgebra.RobustSingularValueDecomposition;
41 import dr.util.Citable;
42 import dr.util.Citation;
43 import dr.util.CommonCitations;
44
45 import java.util.*;
46
47 /**
48 * <b>A general irreversible class for any
49 * data type; allows complex eigenstructures.</b>
50 *
51 * @author Marc Suchard
52 */
53
54 public class ComplexSubstitutionModel extends AbstractSubstitutionModel implements Likelihood, Citable {
55
56 public ComplexSubstitutionModel(String name, DataType dataType,
57 FrequencyModel rootFreqModel, Parameter parameter) {
58
59 super(name, dataType, rootFreqModel);
60 this.infinitesimalRates = parameter;
61
62 rateCount = stateCount * (stateCount - 1);
63
64 if (parameter != null) {
65 if (rateCount != infinitesimalRates.getDimension()) {
66 throw new RuntimeException("Dimension of '" + infinitesimalRates.getId() + "' ("
67 + infinitesimalRates.getDimension() + ") must equal " + rateCount);
68 }
69 addVariable(infinitesimalRates);
70 }
71
72
73 stationaryDistribution = new double[stateCount];
74 storedStationaryDistribution = new double[stateCount];
75
76 }
77
78 protected void handleModelChangedEvent(Model model, Object object, int index) {
79 if (model == freqModel)
80 return; // freqModel only affects the likelihood calculation at the tree root
81 super.handleModelChangedEvent(model, object, index);
82 }
83
84 protected void handleVariableChangedEvent(Variable variable, int index, Parameter.ChangeType type) {
85 // if (!updateMatrix) {
86 updateMatrix = true;
87 // fireModelChanged();
88 // }
89 }
90
91 protected void restoreState() {
92
93 // To restore all this stuff just swap the pointers...
94
95 double[] tmp3 = storedEvalImag;
96 storedEvalImag = EvalImag;
97 EvalImag = tmp3;
98
99 tmp3 = storedStationaryDistribution;
100 storedStationaryDistribution = stationaryDistribution;
101 stationaryDistribution = tmp3;
102
103 // normalization = storedNormalization;
104
105 // Inherited
106 updateMatrix = storedUpdateMatrix;
107 wellConditioned = storedWellConditioned;
108
109 double[] tmp1 = storedEval;
110 storedEval = Eval;
111 Eval = tmp1;
112
113 double[][] tmp2 = storedIevc;
114 storedIevc = Ievc;
115 Ievc = tmp2;
116
117 tmp2 = storedEvec;
118 storedEvec = Evec;
119 Evec = tmp2;
120
121 }
122
123 protected void storeState() {
124
125 storedUpdateMatrix = updateMatrix;
126
127 // if(updateMatrix)
128 // System.err.println("Storing updatable state!");
129
130 storedWellConditioned = wellConditioned;
131
132 System.arraycopy(stationaryDistribution, 0, storedStationaryDistribution, 0, stateCount);
133 System.arraycopy(EvalImag, 0, storedEvalImag, 0, stateCount);
134 // storedNormalization = normalization;
135
136 // Inherited
137 System.arraycopy(Eval, 0, storedEval, 0, stateCount);
138 for (int i = 0; i < stateCount; i++) {
139 System.arraycopy(Ievc[i], 0, storedIevc[i], 0, stateCount);
140 System.arraycopy(Evec[i], 0, storedEvec[i], 0, stateCount);
141 }
142 }
143
144 public void getTransitionProbabilities(double distance, double[] matrix) {
145
146 double temp;
147
148 int i, j, k;
149
150 synchronized (this) {
151 if (updateMatrix) {
152 setupMatrix();
153 }
154 }
155
156 if (!wellConditioned) {
157 Arrays.fill(matrix, 0.0);
158 return;
159 }
160
161
162 // Eigenvalues and eigenvectors of a real matrix A.
163 //
164 // If A is symmetric, then A = V*D*V' where the eigenvalue matrix D is diagonal
165 // and the eigenvector matrix V is orthogonal. I.e. A = V D V^t and V V^t equals
166 // the identity matrix.
167 //
168 // If A is not symmetric, then the eigenvalue matrix D is block diagonal with
169 // the real eigenvalues in 1-by-1 blocks and any complex eigenvalues,
170 // lambda + i*mu, in 2-by-2 blocks, [lambda, mu; -mu, lambda]. The columns
171 // of V represent the eigenvectors in the sense that A*V = V*D. The matrix
172 // V may be badly conditioned, or even singular, so the validity of the
173 // equation A = V D V^{-1} depends on the conditioning of V.
174
175 double[][] iexp = popiexp();
176
177 for (i = 0; i < stateCount; i++) {
178
179 if (EvalImag[i] == 0) {
180 // 1x1 block
181 temp = Math.exp(distance * Eval[i]);
182 for (j = 0; j < stateCount; j++) {
183 iexp[i][j] = Ievc[i][j] * temp;
184 }
185 } else {
186 // 2x2 conjugate block
187 // If A is 2x2 with complex conjugate pair eigenvalues a +/- bi, then
188 // exp(At) = exp(at)*( cos(bt)I + \frac{sin(bt)}{b}(A - aI)).
189 int i2 = i + 1;
190 double b = EvalImag[i];
191 double expat = Math.exp(distance * Eval[i]);
192 double expatcosbt = expat * Math.cos(distance * b);
193 double expatsinbt = expat * Math.sin(distance * b);
194
195 for (j = 0; j < stateCount; j++) {
196 iexp[i][j] = expatcosbt * Ievc[i][j] + expatsinbt * Ievc[i2][j];
197 iexp[i2][j] = expatcosbt * Ievc[i2][j] - expatsinbt * Ievc[i][j];
198 }
199 i++; // processed two conjugate rows
200 }
201 }
202
203 int u = 0;
204 for (i = 0; i < stateCount; i++) {
205 for (j = 0; j < stateCount; j++) {
206 temp = 0.0;
207 for (k = 0; k < stateCount; k++) {
208 temp += Evec[i][k] * iexp[k][j];
209 }
210 if (temp < 0.0)
211 matrix[u] = minProb;
212 else
213 matrix[u] = temp;
214 u++;
215 }
216 }
217 pushiexp(iexp);
218 }
219
220 public double[] getStationaryDistribution() {
221 return stationaryDistribution;
222 }
223
224 protected void computeStationaryDistribution() {
225 stationaryDistribution = freqModel.getFrequencies();
226 }
227
228
229 protected double[] getRates() {
230 return infinitesimalRates.getParameterValues();
231 }
232
233 protected double[] getPi() {
234 return freqModel.getFrequencies();
235 }
236
237 public void setupMatrix() {
238
239 if (!eigenInitialised) {
240 initialiseEigen();
241 storedEvalImag = new double[stateCount];
242 }
243
244 int i = 0;
245
246 storeIntoAmat();
247
248
249 makeValid(amat, stateCount);
250
251 // compute eigenvalues and eigenvectors
252 // EigenvalueDecomposition eigenDecomp = new EigenvalueDecomposition(new DenseDoubleMatrix2D(amat));
253
254 RobustEigenDecomposition eigenDecomp;
255 try {
256 eigenDecomp = new RobustEigenDecomposition(new DenseDoubleMatrix2D(amat), maxIterations);
257 } catch (ArithmeticException ae) {
258 System.err.println(ae.getMessage());
259 wellConditioned = false;
260 System.err.println("amat = \n" + new Matrix(amat));
261 return;
262 }
263
264 DoubleMatrix2D eigenV = eigenDecomp.getV();
265 DoubleMatrix1D eigenVReal = eigenDecomp.getRealEigenvalues();
266 DoubleMatrix1D eigenVImag = eigenDecomp.getImagEigenvalues();
267 DoubleMatrix2D eigenVInv;
268
269 // A better (?) approach to checking diagonalizability comes from:
270 //
271 // J. Gentle (2007) Matrix Algebra
272 //
273 // Diagonalizbility Theorem: A matrix A is (complex) diagonalizable iff all distinct eigenvalues \lambda_l
274 // with algebraic multiplicity m_l are semi-simple, i.e.
275 //
276 // rank(A - \lambda_l I) = n - m_l
277 //
278 // Equivalently (?), eigenV must be non-singular.
279 //
280 // SVD is needed to numerically approximate the rank of a matrix, so we can check Algrebra.rank()
281 // or Algebra.cond() with almost equal amounts of work. I don't know which is more reliable. -- MAS
282
283 if (checkConditioning) {
284 RobustSingularValueDecomposition svd;
285 try {
286 svd = new RobustSingularValueDecomposition(eigenV, maxIterations);
287 } catch (ArithmeticException ae) {
288 System.err.println(ae.getMessage());
289 wellConditioned = false;
290 return;
291 }
292 if (svd.cond() > maxConditionNumber) {
293 wellConditioned = false;
294 return;
295 }
296 }
297
298 try {
299 eigenVInv = alegbra.inverse(eigenV);
300 } catch (IllegalArgumentException e) {
301 wellConditioned = false;
302 return;
303 }
304
305 Ievc = eigenVInv.toArray();
306 Evec = eigenV.toArray();
307 Eval = eigenVReal.toArray();
308 EvalImag = eigenVImag.toArray();
309
310 // Check for valid decomposition
311 for (i = 0; i < stateCount; i++) {
312 if (Double.isNaN(Eval[i]) || Double.isNaN(EvalImag[i]) ||
313 Double.isInfinite(Eval[i]) || Double.isInfinite(EvalImag[i])) {
314 wellConditioned = false;
315 return;
316 } else if (Math.abs(Eval[i]) < 1e-10) {
317 Eval[i] = 0.0;
318 }
319 }
320
321 updateMatrix = false;
322 wellConditioned = true;
323 // compute normalization and rescale eigenvalues
324
325 computeStationaryDistribution();
326
327 if (doNormalization) {
328 double subst = 0.0;
329
330 for (i = 0; i < stateCount; i++)
331 subst += -amat[i][i] * stationaryDistribution[i];
332
333 // normalization = subst;
334
335 for (i = 0; i < stateCount; i++) {
336 Eval[i] /= subst;
337 EvalImag[i] /= subst;
338 }
339 }
340 }
341
342 //store the infinitesimal rates in the vector to a matrix called amat
343 //store the infinitesimal rates in the vector to a matrix called amat
344 public void storeIntoAmat(){
345 double[] rates = getRates();
346 double[] pi = getPi();
347 int i, j, k = 0;
348 for (i = 0; i < stateCount; i++) {
349 for (j = i+1; j < stateCount; j++) {
350 amat[i][j] = rates[k++] * pi[j];
351 }
352 }
353 // Copy lower triangle in column-order form (transposed)
354 for (j = 0; j< stateCount; j++) {
355 for (i = j+1; i < stateCount; i++) {
356 amat[i][j] = rates[k++] * pi[j];
357 }
358 }
359 }
360
361 private void printDebugSetupMatrix() {
362 System.out.println("Normalized infinitesimal rate matrix:");
363 System.out.println(new Matrix(amat));
364 System.out.println(new Matrix(amat).toStringOctave());
365 // System.out.println("Normalization = " + normalization);
366 System.out.println("Values in setupMatrix():");
367 // System.out.println(eigenV);
368 // System.out.println(eigenVInv);
369 // System.out.println(eigenVReal);
370 }
371
372 protected void checkComplexSolutions() {
373 boolean complex = false;
374 for (int i = 0; i < stateCount && !complex; i++) {
375 if (EvalImag[i] != 0)
376 complex = true;
377 }
378 isComplex = complex;
379 }
380
381 public boolean getIsComplex() {
382 return isComplex;
383 }
384
385 protected void frequenciesChanged() {
386 }
387
388 protected void ratesChanged() {
389 }
390
391 protected void setupRelativeRates() {
392 }
393
394 protected Parameter infinitesimalRates;
395
396 // public LogColumn[] getColumns() {
397 //
398 // LogColumn[] columnList = new LogColumn[stateCount * stateCount];
399 // int index = 0;
400 // for (int i = 0; i < stateCount; i++) {
401 // for (int j = 0; j < stateCount; j++)
402 // columnList[index++] = new MatrixEntryColumn(getId(), i, j, amat);
403 // }
404 // return columnList;
405 // }
406
407 public LogColumn[] getColumns() {
408 return new LogColumn[]{
409 new LikelihoodColumn(getId())
410 };
411 }
412
413 protected class LikelihoodColumn extends NumberColumn {
414 public LikelihoodColumn(String label) {
415 super(label);
416 }
417
418 public double getDoubleValue() {
419 return getLogLikelihood();
420 }
421 }
422
423
424 public static void main(String[] arg) {
425
426 // Parameter rates = new Parameter.Default(new double[]{5.0, 1.0, 1.0, 0.1, 5.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0});
427 // Parameter rates = new Parameter.Default(new double[] {5.0, 1.0, 1.0, 1.0, 5.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0});
428 // Parameter rates = new Parameter.Default(new double[] {1.0, 1.0});
429
430
431 Parameter rates = new Parameter.Default(159600, 1.0);
432
433
434 DataType dataType = new DataType() {
435
436 public String getDescription() {
437 return null;
438 }
439
440 public int getType() {
441 return 0;
442 }
443
444 @Override
445 public char[] getValidChars() {
446 return null;
447 }
448
449 public int getStateCount() {
450 return 400;
451 }
452 };
453
454 FrequencyModel freqModel = new FrequencyModel(dataType, new Parameter.Default(400, 1.0 / 400.0));
455
456 ComplexSubstitutionModel substModel = new ComplexSubstitutionModel("test",
457 // TwoStates.INSTANCE,
458 dataType,
459 freqModel,
460 rates);
461
462 long start = System.currentTimeMillis();
463 double[] finiteTimeProbs = new double[substModel.getDataType().getStateCount() * substModel.getDataType().getStateCount()];
464 double time = 1.0;
465 substModel.getTransitionProbabilities(time, finiteTimeProbs);
466 long end = System.currentTimeMillis();
467 System.out.println("Time: " + (end - start));
468 // System.out.println("Results:");
469 // System.out.println(new Vector(finiteTimeProbs));
470
471 // System.out.println("COLT value:");
472 // This should work, matches 'octave' results
473 // DoubleMatrix2D result = alegbra.mult(substModel.eigenV, alegbra.mult(blockDiagonalExponential(1.0, substModel.eigenD), substModel.eigenVInv));
474 //
475 // System.out.println(result);
476
477 }
478
479 public void setMaxIterations(int max) {
480 maxIterations = max;
481 }
482
483 public void setMaxConditionNumber(double max) {
484 maxConditionNumber = max;
485 }
486
487 public void setCheckConditioning(boolean check) {
488 checkConditioning = check;
489 }
490
491 private static DoubleMatrix2D blockDiagonalExponential(double distance, DoubleMatrix2D mat) {
492 for (int i = 0; i < mat.rows(); i++) {
493 if ((i + 1) < mat.rows() && mat.getQuick(i, i + 1) != 0) {
494 double a = mat.getQuick(i, i);
495 double b = mat.getQuick(i, i + 1);
496 double expat = Math.exp(distance * a);
497 double cosbt = Math.cos(distance * b);
498 double sinbt = Math.sin(distance * b);
499 mat.setQuick(i, i, expat * cosbt);
500 mat.setQuick(i + 1, i + 1, expat * cosbt);
501 mat.setQuick(i, i + 1, expat * sinbt);
502 mat.setQuick(i + 1, i, -expat * sinbt);
503 i++; // processed two entries in loop
504 } else
505 mat.setQuick(i, i, Math.exp(distance * mat.getQuick(i, i))); // 1x1 block
506 }
507 return mat;
508 }
509
510 private boolean isComplex = false;
511 private double[] stationaryDistribution = null;
512 private double[] storedStationaryDistribution;
513
514 protected boolean doNormalization = true;
515 // private Double normalization;
516 // private Double storedNormalization;
517
518 protected double[] EvalImag;
519 protected double[] storedEvalImag;
520
521 protected boolean wellConditioned = true;
522 private boolean storedWellConditioned;
523 // private double[] illConditionedProbabilities;
524
525 protected static final double minProb = Property.DEFAULT.tolerance();
526 // private static final double minProb = 1E-20;
527 // private static final double minProb = Property.ZERO.tolerance();
528 private static final Algebra alegbra = new Algebra(minProb);
529 EigenvalueDecomposition eigenDecomp;
530 EigenvalueDecomposition storedEigenDecomp;
531
532 private double maxConditionNumber = 1000;
533
534 private int maxIterations = 1000;
535
536 private boolean checkConditioning = true;
537
538 public Model getModel() {
539 return this;
540 }
541
542 public double getLogLikelihood() {
543 if (BayesianStochasticSearchVariableSelection.Utils.connectedAndWellConditioned(probability,this))
544 return 0;
545 return Double.NEGATIVE_INFINITY;
546 }
547
548 /**
549 * Needs to be evaluated before the corresponding data likelihood.
550 * @return
551 */
552 public boolean evaluateEarly() {
553 return true;
554 }
555
556 public String prettyName() {
557 return Abstract.getPrettyName(this);
558 }
559
560 public void setNormalization(boolean doNormalization) {
561 this.doNormalization = doNormalization;
562 }
563
564 public void makeDirty() {
565
566 }
567
568 @Override
569 public Set<Likelihood> getLikelihoodSet() {
570 return new HashSet<Likelihood>(Arrays.asList(this));
571 }
572
573 @Override
574 public boolean isUsed() {
575 return super.isUsed() && isUsed;
576 }
577
578 public void setUsed() {
579 isUsed = true;
580 }
581
582 private boolean isUsed = false;
583
584 private double[] probability = null;
585
586 @Override
587 public Citation.Category getCategory() {
588 return Citation.Category.SUBSTITUTION_MODELS;
589 }
590
591 @Override
592 public String getDescription() {
593 return "Complex-diagonalizable, irreversible substitution model";
594 }
595
596 @Override
597 public List<Citation> getCitations() {
598 return Collections.singletonList(CommonCitations.EDWARDS_2011_ANCIENT);
599 }
600
601 }