Debian Codegraph @

src/dr/evomodel/substmodel/BaseSubstitutionModel.java

raw symbols SCIP
1 /*
2 * BaseSubstitutionModel.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.model.AbstractModel;
30 import dr.inference.model.Model;
31 import dr.inference.model.Parameter;
32 import dr.inference.model.Variable;
33
34 import java.util.Arrays;
35
36 /**
37 * An abstract base class for substitution models.
38 *
39 * @author Andrew Rambaut
40 * @author Marc Suchard
41 * @author Alexei Drummond
42 * @version $Id: AbstractSubstitutionModel.java,v 1.41 2005/05/24 20:25:58 rambaut Exp $
43 */
44 @SuppressWarnings({"SuspiciousNameCombination", "UnusedAssignment"})
45 public abstract class BaseSubstitutionModel extends AbstractModel
46 implements SubstitutionModel {
47
48
49 public static final String MODEL = "model";
50
51 protected DataType dataType = null;
52
53 protected FrequencyModel freqModel;
54 protected double[] relativeRates;
55 protected double[] storedRelativeRates;
56
57 protected int stateCount;
58 protected int rateCount;
59
60 protected boolean updateMatrix = true;
61 protected boolean storedUpdateMatrix = true;
62
63 private final EigenSystem eigenSystem;
64
65 public BaseSubstitutionModel(String name) {
66 super(name);
67
68 // For a wrapper model (KroneckerSumSM), most computation is handled in the wrapped classes
69 eigenSystem = null;
70 q = null;
71 }
72
73 public BaseSubstitutionModel(String name, DataType dataType, FrequencyModel freqModel) {
74 this(name, dataType, freqModel, null);
75 }
76
77 public BaseSubstitutionModel(String name, DataType dataType, FrequencyModel freqModel, EigenSystem eigenSystem) {
78 super(name);
79
80 if (eigenSystem == null)
81 this.eigenSystem = getDefaultEigenSystem(dataType.getStateCount());
82 else
83 this.eigenSystem = eigenSystem;
84
85 this.dataType = dataType;
86
87 setStateCount(dataType.getStateCount());
88
89 if (freqModel != null) {
90 // freqModel can be null at this point but must be
91 // in place by the time setupMatrix is called.
92
93 if (freqModel.getDataType() != dataType) {
94 throw new IllegalArgumentException("Datatypes do not match.");
95 }
96
97 this.freqModel = freqModel;
98 addModel(freqModel);
99
100 if (!(freqModel instanceof CovarionFrequencyModel)) {
101 checkFrequencies();
102 }
103 }
104
105 q = new double[stateCount][stateCount];
106
107 updateMatrix = true;
108 }
109
110 protected EigenSystem getDefaultEigenSystem(int stateCount) {
111 return new DefaultEigenSystem(stateCount);
112 }
113
114 private void setStateCount(int stateCount) {
115 this.stateCount = stateCount;
116 rateCount = getRateCount(stateCount);
117
118 relativeRates = new double[rateCount];
119 storedRelativeRates = new double[rateCount];
120 for (int i = 0; i < rateCount; i++) {
121 relativeRates[i] = 1.0;
122 }
123 }
124
125 protected int getRateCount(int stateCount) {
126 return ((stateCount - 1) * stateCount) / 2;
127 }
128
129 // *****************************************************************
130 // Interface Model
131 // *****************************************************************
132
133 protected void handleModelChangedEvent(Model model, Object object, int index) {
134 // frequencyModel changed!
135 updateMatrix = true;
136 frequenciesChanged();
137 fireModelChanged();
138 }
139
140 protected void handleVariableChangedEvent(Variable variable, int index, Parameter.ChangeType type) {
141 // relativeRates changed
142 updateMatrix = true;
143 ratesChanged();
144 }
145
146 protected void storeState() {
147
148 storedUpdateMatrix = updateMatrix;
149
150 System.arraycopy(relativeRates, 0, storedRelativeRates, 0, rateCount);
151
152 if (eigenDecomposition != null) {
153 storedEigenDecomposition = eigenDecomposition.copy();
154 }
155 }
156
157 /**
158 * Restore the additional stored state
159 */
160 protected void restoreState() {
161
162 updateMatrix = storedUpdateMatrix;
163
164 // To restore all this stuff just swap the pointers...
165 double[] tmp1 = storedRelativeRates;
166 storedRelativeRates = relativeRates;
167 relativeRates = tmp1;
168
169 EigenDecomposition tmp = storedEigenDecomposition;
170 storedEigenDecomposition = eigenDecomposition;
171 eigenDecomposition = tmp;
172
173 }
174
175 protected void acceptState() {
176 } // nothing to do
177
178 abstract protected void frequenciesChanged();
179
180 abstract protected void ratesChanged();
181
182 abstract protected void setupRelativeRates(double[] rates);
183
184 public FrequencyModel getFrequencyModel() {
185 return freqModel;
186 }
187
188 /**
189 * @return the data type
190 */
191 public DataType getDataType() {
192 return dataType;
193 }
194
195 /**
196 * get the complete transition probability matrix for the given distance
197 *
198 * @param distance the expected number of substitutions
199 * @param matrix an array to store the matrix
200 */
201 public void getTransitionProbabilities(double distance, double[] matrix) {
202 double temp;
203
204 EigenDecomposition eigen = getEigenDecomposition();
205
206 if (eigen == null) {
207 Arrays.fill(matrix, 0.0);
208 return;
209 }
210
211 double[] Evec = eigen.getEigenVectors();
212 double[] Ievc = eigen.getInverseEigenVectors();
213 double[] Eval = eigen.getEigenValues();
214
215 // implemented a pool of iexp matrices to support multiple threads
216 // without creating a new matrix each call. - AJD
217 double[][] iexp = new double[stateCount][stateCount];
218 for (int i = 0; i < stateCount; i++) {
219 temp = Math.exp(distance * Eval[i]);
220 for (int j = 0; j < stateCount; j++) {
221 iexp[i][j] = Ievc[i * stateCount + j] * temp;
222 }
223 }
224
225 int u = 0;
226 for (int i = 0; i < stateCount; i++) {
227 for (int j = 0; j < stateCount; j++) {
228 temp = 0.0;
229 for (int k = 0; k < stateCount; k++) {
230 temp += Evec[i * stateCount + k] * iexp[k][j];
231 }
232
233 matrix[u] = Math.abs(temp);
234 u++;
235 }
236 }
237 }
238
239 /**
240 * This function returns the Eigen vectors.
241 *
242 * @return the array
243 */
244 public EigenDecomposition getEigenDecomposition() {
245 synchronized (this) {
246 if (updateMatrix) {
247 decompose();
248 }
249 }
250 return eigenDecomposition;
251 }
252
253 protected void setupQMatrix(double[] rates, double[] pi, double[][] matrix) {
254 int k = 0;
255 // Set the instantaneous rate matrix
256 for (int i = 0; i < stateCount; i++) {
257 for (int j = i + 1; j < stateCount; j++) {
258 matrix[i][j] = rates[k] * pi[j];
259 matrix[j][i] = rates[k] * pi[i];
260 k++;
261 }
262 }
263 }
264
265 /**
266 * setup substitution matrix
267 */
268 private void decompose() {
269
270 double normalization = setupMatrix();
271
272 eigenDecomposition = eigenSystem.decomposeMatrix(q);
273
274 if (eigenDecomposition != null)
275 eigenDecomposition.normalizeEigenValues(normalization);
276
277 updateMatrix = false;
278 }
279
280 private double setupMatrix() {
281 setupRelativeRates(relativeRates);
282 double[] pi = freqModel.getFrequencies();
283 setupQMatrix(relativeRates, pi, q);
284 makeValid(q, stateCount);
285 return getNormalizationValue(q, pi);
286 }
287
288 public void getInfinitesimalMatrix(double[] out) {
289
290 double normalization = setupMatrix();
291 int index = 0;
292 for (int i = 0; i < stateCount; i++) {
293 for (int j = 0; j < stateCount; j++) {
294 out[index] = q[i][j] / normalization;
295 index++;
296 }
297 }
298 }
299
300 /**
301 * Normalize rate matrix to one expected substitution per unit time
302 *
303 * @param matrix the matrix to normalize to one expected substitution
304 * @param pi the equilibrium distribution of states
305 * @return expected substitution per unit time
306 */
307 protected double getNormalizationValue(double[][] matrix, double[] pi) {
308 double subst = 0.0;
309
310 for (int i = 0; i < stateCount; i++)
311 subst += -matrix[i][i] * pi[i];
312
313 return subst;
314 }
315
316 static String format = "%2.1e";
317
318 public String printQ() {
319 double[] out = new double[stateCount * stateCount];
320 getInfinitesimalMatrix(out);
321
322 StringBuffer sb = new StringBuffer();
323 int index = 0;
324 for (int i = 0; i < stateCount; i++) {
325 if (i > 0)
326 sb.append(String.format(format, out[index]));
327 for (int j = 1; j < stateCount; j++) {
328 sb.append("\t");
329 if (j != i)
330 sb.append(String.format(format, out[index]));
331 index++;
332 }
333 sb.append("\n");
334 }
335 return sb.toString();
336 }
337
338 // Make it a valid rate matrix (make sum of rows = 0)
339 private void makeValid(double[][] matrix, int dimension) {
340 for (int i = 0; i < dimension; i++) {
341 double sum = 0.0;
342 for (int j = 0; j < dimension; j++) {
343 if (i != j)
344 sum += matrix[i][j];
345 }
346 matrix[i][i] = -sum;
347 }
348 }
349
350 /**
351 * Ensures that frequencies are not smaller than MINFREQ and
352 * that two frequencies differ by at least 2*MINFDIFF.
353 * This avoids potential problems later when eigenvalues
354 * are computed.
355 */
356 private void checkFrequencies() {
357 // required frequency difference
358 double MINFDIFF = getMINFDIFF();
359
360 // lower limit on frequency
361 double MINFREQ = getMINFREQ();
362
363
364 // System.err.println("diff = "+MINFDIFF+" freq = "+MINFREQ);
365 int maxi = 0;
366 double sum = 0.0;
367 double maxfreq = 0.0;
368 for (int i = 0; i < stateCount; i++) {
369 double freq = freqModel.getFrequency(i);
370 if (freq < MINFREQ) freqModel.setFrequency(i, MINFREQ);
371 if (freq > maxfreq) {
372 maxfreq = freq;
373 maxi = i;
374 }
375 sum += freqModel.getFrequency(i);
376 }
377 double diff = 1.0 - sum;
378 freqModel.setFrequency(maxi, freqModel.getFrequency(maxi) + diff);
379
380 for (int i = 0; i < stateCount - 1; i++) {
381 for (int j = i + 1; j < stateCount; j++) {
382 if (freqModel.getFrequency(i) == freqModel.getFrequency(j)) {
383 freqModel.setFrequency(i, freqModel.getFrequency(i) + MINFDIFF);
384 freqModel.setFrequency(j, freqModel.getFrequency(j) - MINFDIFF);
385 }
386 }
387 }
388 }
389
390 public boolean canReturnComplexDiagonalization() {
391 return false;
392 }
393
394 protected double getMINFDIFF() {
395 return 1.0E-10;
396 }
397
398 protected double getMINFREQ() {
399 return 1.0E-10;
400 }
401
402 protected double[][] getQCopy() {
403 double[][] copy = new double[q.length][q.length];
404 for (int i = 0; i < q.length; ++i) {
405 System.arraycopy(q[i], 0, copy[i], 0, q.length);
406 }
407 return copy;
408 }
409
410 private final double q[][];
411 protected EigenDecomposition eigenDecomposition;
412 private EigenDecomposition storedEigenDecomposition;
413
414 }