Debian Codegraph @

src/dr/evomodel/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.evomodel.substmodel;
27
28 import dr.evolution.datatype.DataType;
29 import dr.inference.loggers.LogColumn;
30 import dr.inference.loggers.NumberColumn;
31 import dr.inference.model.BayesianStochasticSearchVariableSelection;
32 import dr.inference.model.Likelihood;
33 import dr.inference.model.Model;
34 import dr.inference.model.Parameter;
35 import dr.math.matrixAlgebra.Vector;
36 import dr.util.Citable;
37 import dr.util.Citation;
38 import dr.util.CommonCitations;
39
40 import java.util.*;
41
42 /**
43 * @author Marc Suchard
44 */
45 public class ComplexSubstitutionModel extends GeneralSubstitutionModel implements Likelihood, Citable {
46
47 public ComplexSubstitutionModel(String name, DataType dataType, FrequencyModel freqModel, Parameter parameter) {
48 super(name, dataType, freqModel, parameter, -1);
49 probability = new double[stateCount * stateCount];
50 }
51
52 @Override
53 protected void setupDimensionNames(int relativeTo) {
54 List<String> rateNames = new ArrayList<String>();
55
56 String ratePrefix = ratesParameter.getParameterName();
57
58 for (int i = 0; i < dataType.getStateCount(); ++i) {
59 for (int j = i + 1; j < dataType.getStateCount(); ++j) {
60 rateNames.add(getDimensionString(i, j, ratePrefix));
61 }
62 }
63
64 for (int j = 0; j < dataType.getStateCount(); ++j) {
65 for (int i = j + 1; i < dataType.getStateCount(); ++i) {
66 rateNames.add(getDimensionString(i, j, ratePrefix));
67 }
68 }
69
70 String[] tmp = new String[0];
71 ratesParameter.setDimensionNames(rateNames.toArray(tmp));
72 }
73
74 protected EigenSystem getDefaultEigenSystem(int stateCount) {
75 return new ComplexColtEigenSystem(stateCount);
76 }
77
78 /**
79 * get the complete transition probability matrix for the given distance
80 *
81 * @param distance the expected number of substitutions
82 * @param matrix an array to store the matrix
83 */
84 public void getTransitionProbabilities(double distance, double[] matrix) {
85 getTransitionProbabilities(distance, matrix, getEigenDecomposition());
86 }
87
88 protected void getTransitionProbabilities(double distance, double[] matrix, EigenDecomposition eigen) {
89 double temp;
90 if (eigen == null) {
91 Arrays.fill(matrix, 0.0);
92 return;
93 }
94
95 double[] Evec = eigen.getEigenVectors();
96 double[] Eval = eigen.getEigenValues();
97 double[] EvalImag = new double[stateCount];
98 System.arraycopy(Eval, stateCount, EvalImag, 0, stateCount);
99 double[] Ievc = eigen.getInverseEigenVectors();
100
101 double[][] iexp = new double[stateCount][stateCount];
102
103 // Eigenvalues and eigenvectors of a real matrix A.
104 //
105 // If A is symmetric, then A = V*D*V' where the eigenvalue matrix D is diagonal
106 // and the eigenvector matrix V is orthogonal. I.e. A = V D V^t and V V^t equals
107 // the identity matrix.
108 //
109 // If A is not symmetric, then the eigenvalue matrix D is block diagonal with
110 // the real eigenvalues in 1-by-1 blocks and any complex eigenvalues,
111 // lambda + i*mu, in 2-by-2 blocks, [lambda, mu; -mu, lambda]. The columns
112 // of V represent the eigenvectors in the sense that A*V = V*D. The matrix
113 // V may be badly conditioned, or even singular, so the validity of the
114 // equation A = V D V^{-1} depends on the conditioning of V.
115
116 for (int i = 0; i < stateCount; i++) {
117
118 if (EvalImag[i] == 0) {
119 // 1x1 block
120 temp = Math.exp(distance * Eval[i]);
121 for (int j = 0; j < stateCount; j++) {
122 iexp[i][j] = Ievc[i * stateCount + j] * temp;
123 }
124 } else {
125 // 2x2 conjugate block
126 // If A is 2x2 with complex conjugate pair eigenvalues a +/- bi, then
127 // exp(At) = exp(at)*( cos(bt)I + \frac{sin(bt)}{b}(A - aI)).
128 int i2 = i + 1;
129 double b = EvalImag[i];
130 double expat = Math.exp(distance * Eval[i]);
131 double expatcosbt = expat * Math.cos(distance * b);
132 double expatsinbt = expat * Math.sin(distance * b);
133
134 for (int j = 0; j < stateCount; j++) {
135 iexp[i][j] = expatcosbt * Ievc[i * stateCount + j] +
136 expatsinbt * Ievc[i2 * stateCount + j];
137 iexp[i2][j] = expatcosbt * Ievc[i2 * stateCount + j] -
138 expatsinbt * Ievc[i * stateCount + j];
139 }
140 i++; // processed two conjugate rows
141 }
142 }
143
144 int u = 0;
145 for (int i = 0; i < stateCount; i++) {
146 for (int j = 0; j < stateCount; j++) {
147 temp = 0.0;
148 for (int k = 0; k < stateCount; k++) {
149 temp += Evec[i * stateCount + k] * iexp[k][j];
150 }
151 matrix[u] = Math.abs(temp);
152 u++;
153 }
154 }
155 }
156
157 protected int getRateCount(int stateCount) {
158 return (stateCount - 1) * stateCount;
159 }
160
161 protected void setupRelativeRates(double[] rates) {
162 for (int i = 0; i < rates.length; i++)
163 rates[i] = ratesParameter.getParameterValue(i);
164 }
165
166 protected void setupQMatrix(double[] rates, double[] pi, double[][] matrix) {
167 int i, j, k = 0;
168 for (i = 0; i < stateCount; i++) {
169 for (j = i + 1; j < stateCount; j++) {
170 double thisRate = rates[k++];
171 if (thisRate < 0.0) thisRate = 0.0;
172 matrix[i][j] = thisRate * pi[j];
173 }
174 }
175 // Copy lower triangle in column-order form (transposed)
176 for (j = 0; j < stateCount; j++) {
177 for (i = j + 1; i < stateCount; i++) {
178 double thisRate = rates[k++];
179 if (thisRate < 0.0) thisRate = 0.0;
180 matrix[i][j] = thisRate * pi[j];
181 }
182 }
183 }
184
185 public boolean canReturnComplexDiagonalization() {
186 return true;
187 }
188
189 protected double getNormalizationValue(double[][] matrix, double[] pi) {
190 double norm = 1.0;
191 if (doNormalization) {
192 norm = super.getNormalizationValue(matrix, pi);
193 }
194 // return super.getNormalizationValue(matrix, pi);
195 // } else {
196 // return 1.0;
197 // }
198 // System.err.println("norm = " + doNormalization + " " + norm);
199 // System.err.println(new Matrix(matrix));
200 return norm;
201 }
202
203 public double getLogLikelihood() {
204 if (BayesianStochasticSearchVariableSelection.Utils.connectedAndWellConditioned(probability, this))
205 return 0;
206 return Double.NEGATIVE_INFINITY;
207 }
208
209 /**
210 * Needs to be evaluated before the corresponding data likelihood.
211 *
212 * @return
213 */
214 public boolean evaluateEarly() {
215 return true;
216 }
217
218 public String prettyName() {
219 return Abstract.getPrettyName(this);
220 }
221
222 public void setNormalization(boolean doNormalization) {
223 this.doNormalization = doNormalization;
224 }
225
226 public void makeDirty() {
227
228 }
229
230 public void printLastProbabilityMatrix() {
231 getLogLikelihood();
232 System.err.println((probability == null) ? "Null probability vector" : "Not null probability vector");
233 if (probability == null) {
234 boolean test = BayesianStochasticSearchVariableSelection.Utils.connectedAndWellConditioned(probability, this);
235 System.err.println("BSSVS valid = " + test);
236 }
237 System.err.println(new Vector(probability));
238 }
239
240 @Override
241 public Set<Likelihood> getLikelihoodSet() {
242 return new HashSet<Likelihood>(Arrays.asList(this));
243 }
244
245 @Override
246 public boolean isUsed() {
247 return super.isUsed() && isUsed;
248 }
249
250 public void setUsed() {
251 isUsed = true;
252 }
253
254 private boolean isUsed = false;
255 private double[] probability;
256
257 public Model getModel() {
258 return this;
259 }
260
261 public LogColumn[] getColumns() {
262 return new LogColumn[]{
263 new LikelihoodColumn(getId()),
264 new NormalizationColumn(getId()),
265 };
266 }
267
268 protected class LikelihoodColumn extends NumberColumn {
269 public LikelihoodColumn(String label) {
270 super(label);
271 }
272
273 public double getDoubleValue() {
274 return getLogLikelihood();
275 }
276 }
277
278 protected class NormalizationColumn extends NumberColumn {
279 public NormalizationColumn(String label) { super(label); }
280
281 public double getDoubleValue() {
282 return getEigenDecomposition().getNormalization();
283 }
284 }
285
286 void setDoNormalization(boolean normalize) {
287 this.doNormalization = normalize;
288 }
289
290 @Override
291 public Citation.Category getCategory() {
292 return Citation.Category.SUBSTITUTION_MODELS;
293 }
294
295 @Override
296 public String getDescription() {
297 return "Complex-diagonalizable, irreversible substitution model";
298 }
299
300 @Override
301 public List<Citation> getCitations() {
302 return Collections.singletonList(CommonCitations.EDWARDS_2011_ANCIENT);
303 }
304
305 private boolean doNormalization = true;
306 }