Debian Codegraph @

src/dr/evomodel/treedatalikelihood/SubstitutionModelDelegate.java

raw symbols SCIP
1 /*
2 * SubstitutionModelDelegate.java
3 *
4 * Copyright (c) 2002-2016 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.treedatalikelihood;
27
28 import beagle.Beagle;
29 import dr.evomodel.branchmodel.BranchModel;
30 import dr.evomodel.substmodel.EigenDecomposition;
31 import dr.evomodel.substmodel.SubstitutionModel;
32 import dr.evolution.tree.Tree;
33 import dr.util.Timer;
34
35 import java.io.Serializable;
36 import java.util.ArrayDeque;
37 import java.util.ArrayList;
38 import java.util.Deque;
39 import java.util.List;
40
41 /**
42 * @author Andrew Rambaut
43 * @author Filip Bielejec
44 * @author Marc A. Suchard
45 * @version $Id$
46 */
47 public final class SubstitutionModelDelegate implements EvolutionaryProcessDelegate, Serializable {
48 private static final boolean DEBUG = false;
49 private static final boolean RUN_IN_SERIES = false;
50 public static final boolean MEASURE_RUN_TIME = false;
51
52 public double updateTime;
53 public double convolveTime;
54
55 private static final int BUFFER_POOL_SIZE_DEFAULT = 100;
56
57 private final Tree tree;
58 private final List<SubstitutionModel> substitutionModelList;
59 private final BranchModel branchModel;
60
61 private final int eigenCount;
62 private final int nodeCount;
63
64 private final int extraBufferCount;
65 private final int reserveBufferIndex;
66
67 private final BufferIndexHelper eigenBufferHelper;
68 private final BufferIndexHelper matrixBufferHelper;
69
70 private Deque<Integer> availableBuffers = new ArrayDeque<Integer>();
71
72 /**
73 * A class which handles substitution models including epoch models where multiple
74 * substitution models on a branch are convolved.
75 * @param tree
76 * @param branchModel Describes which substitution models use on each branch
77 */
78 public SubstitutionModelDelegate(Tree tree, BranchModel branchModel) {
79 this(tree, branchModel, 0, BUFFER_POOL_SIZE_DEFAULT);
80 }
81
82 /**
83 * A class which handles substitution models including epoch models where multiple
84 * substitution models on a branch are convolved.
85 * @param tree
86 * @param branchModel Describes which substitution models use on each branch
87 * @param partitionNumber which data partition is this (used to offset eigen and matrix buffer numbers)
88 */
89 public SubstitutionModelDelegate(Tree tree, BranchModel branchModel, int partitionNumber) {
90 this(tree, branchModel, partitionNumber, BUFFER_POOL_SIZE_DEFAULT);
91 }
92
93 public SubstitutionModelDelegate(Tree tree, BranchModel branchModel, int partitionNumber, int bufferPoolSize) {
94
95 if (MEASURE_RUN_TIME) {
96 updateTime = 0;
97 convolveTime = 0;
98 }
99
100 this.tree = tree;
101
102 this.substitutionModelList = branchModel.getSubstitutionModels();
103
104 this.branchModel = branchModel;
105
106 eigenCount = substitutionModelList.size();
107 nodeCount = tree.getNodeCount();
108
109 // two eigen buffers for each decomposition for store and restore.
110 eigenBufferHelper = new BufferIndexHelper(eigenCount, 0, partitionNumber);
111
112 // two matrices for each node less the root
113 matrixBufferHelper = new BufferIndexHelper(nodeCount, 0, partitionNumber);
114
115 this.extraBufferCount = branchModel.requiresMatrixConvolution() ?
116 (bufferPoolSize > 0 ? bufferPoolSize : BUFFER_POOL_SIZE_DEFAULT) : 0;
117
118 if (branchModel.requiresMatrixConvolution() && this.extraBufferCount < eigenCount) {
119 throw new RuntimeException("SubstitutionModelDelegate requires at least " + eigenCount + " extra buffers to convolve matrices");
120 }
121
122 for (int i = 0; i < extraBufferCount; i++) {
123 pushAvailableBuffer(i + matrixBufferHelper.getBufferCount());
124 }
125
126 // one extra created as a reserve
127 // which is used to free up buffers when the avail stack is empty.
128 reserveBufferIndex = matrixBufferHelper.getBufferCount() + extraBufferCount;
129
130 if (DEBUG) {
131 System.out.println("Creating reserve buffer with index: "
132 + reserveBufferIndex);
133 }
134
135 }// END: Constructor
136
137 @Override
138 public boolean canReturnComplexDiagonalization() {
139 for (SubstitutionModel model : substitutionModelList) {
140 if (model.canReturnComplexDiagonalization()) {
141 return true;
142 }
143 }
144 return false;
145 }
146
147 @Override
148 public int getEigenBufferCount() {
149 return eigenBufferHelper.getBufferCount();
150 }
151
152 @Override
153 public int getMatrixBufferCount() {
154 // plus one for the reserve buffer
155 return matrixBufferHelper.getBufferCount() + extraBufferCount + 1;
156 }
157
158 @Override
159 public int getSubstitutionModelCount() {
160 return substitutionModelList.size();
161 }
162
163 @Override
164 public SubstitutionModel getSubstitutionModel(int index) {
165 return substitutionModelList.get(index);
166 }
167
168 @Override
169 public int getEigenIndex(int bufferIndex) {
170 return eigenBufferHelper.getOffsetIndex(bufferIndex);
171 }
172
173 @Override
174 public int getMatrixIndex(int branchIndex) {
175 return matrixBufferHelper.getOffsetIndex(branchIndex);
176 }
177
178 @Override
179 public double[] getRootStateFrequencies() {
180 return branchModel.getRootFrequencyModel().getFrequencies();
181 }// END: getStateFrequencies
182
183
184 @Override
185 public void updateSubstitutionModels(Beagle beagle, boolean flipBuffers) {
186 for (int i = 0; i < eigenCount; i++) {
187 if (flipBuffers) {
188 eigenBufferHelper.flipOffset(i);
189 }
190
191 EigenDecomposition ed = substitutionModelList.get(i).getEigenDecomposition();
192
193 beagle.setEigenDecomposition(
194 eigenBufferHelper.getOffsetIndex(i),
195 ed.getEigenVectors(),
196 ed.getInverseEigenVectors(),
197 ed.getEigenValues());
198 }
199 }
200
201 @Override
202 public void updateTransitionMatrices(Beagle beagle, int[] branchIndices, double[] edgeLength, int updateCount, boolean flipBuffers) {
203
204 int[][] probabilityIndices = new int[eigenCount][updateCount];
205 double[][] edgeLengths = new double[eigenCount][updateCount];
206
207 int[] counts = new int[eigenCount];
208
209 List<Deque<Integer>> convolutionList = new ArrayList<Deque<Integer>>();
210
211 for (int i = 0; i < updateCount; i++) {
212
213 BranchModel.Mapping mapping = branchModel.getBranchModelMapping(tree.getNode(branchIndices[i]));
214 int[] order = mapping.getOrder();
215 double[] weights = mapping.getWeights();
216
217 if (order.length == 1) {
218 int k = order[0];
219 if (flipBuffers) {
220 matrixBufferHelper.flipOffset(branchIndices[i]);
221 }
222 probabilityIndices[k][counts[k]] = matrixBufferHelper.getOffsetIndex(branchIndices[i]);
223 edgeLengths[k][counts[k]] = edgeLength[i];
224 counts[k]++;
225 } else {
226 double sum = 0.0;
227 for (double w : weights) {
228 sum += w;
229 }
230
231 if (getAvailableBufferCount() < order.length) {
232 // too few buffers available, process what we have and continue...
233 if (flipBuffers) { throw new UnsupportedOperationException("flipping not implemented for Epoch models"); }
234 computeTransitionMatrices(beagle, probabilityIndices, edgeLengths, counts);
235 convolveMatrices(beagle, convolutionList);
236
237 // reset the counts
238 for (int k = 0; k < eigenCount; k++) {
239 counts[k] = 0;
240 }
241 }
242
243 Deque<Integer> bufferIndices = new ArrayDeque<Integer>();
244 for (int j = 0; j < order.length; j++) {
245
246 int buffer = popAvailableBuffer();
247
248 if (buffer < 0) {
249 // no buffers available
250 throw new RuntimeException("Ran out of buffers for transition matrices - computing current list.");
251 }
252
253 int k = order[j];
254 probabilityIndices[k][counts[k]] = buffer;
255 edgeLengths[k][counts[k]] = weights[j] * edgeLength[i] / sum;
256 counts[k]++;
257
258 bufferIndices.add(buffer);
259 }
260 bufferIndices.add(matrixBufferHelper.getOffsetIndex(branchIndices[i]));
261
262 convolutionList.add(bufferIndices);
263 }// END: if convolution needed
264
265 }// END: i loop
266
267 computeTransitionMatrices(beagle, probabilityIndices, edgeLengths, counts);
268 convolveMatrices(beagle, convolutionList);
269
270 }// END: updateTransitionMatrices
271
272 @Override
273 public void flipTransitionMatrices(int[] branchIndices, int updateCount) {
274 for (int i = 0; i < updateCount; i++) {
275 matrixBufferHelper.flipOffset(branchIndices[i]);
276 }
277 }
278
279 private void computeTransitionMatrices(Beagle beagle, int[][] probabilityIndices, double[][] edgeLengths, int[] counts) {
280
281 Timer timer;
282 if (MEASURE_RUN_TIME) {
283 timer = new Timer();
284 timer.start();
285 }
286
287 if (DEBUG) {
288 System.out.print("Computing matrices:");
289 }
290
291 for (int i = 0; i < eigenCount; i++) {
292 if (DEBUG) {
293 for (int j = 0; j < counts[i]; j++) {
294 // System.out.print(" " + probabilityIndices[i][j]);
295 System.out.print(" " + probabilityIndices[i][j] + " (" + edgeLengths[i][j] + ")");
296 }
297 }
298 if (counts[i] > 0) {
299 beagle.updateTransitionMatrices(eigenBufferHelper.getOffsetIndex(i),
300 probabilityIndices[i],
301 null, // firstDerivativeIndices
302 null, // secondDerivativeIndices
303 edgeLengths[i],
304 counts[i]);
305 }
306 }
307
308 if (DEBUG) {
309 System.out.println();
310 }
311
312 if (MEASURE_RUN_TIME) {
313 timer.stop();
314 double timeInSeconds = timer.toSeconds();
315 updateTime += timeInSeconds;
316 }
317
318 }//END: computeTransitionMatrices
319
320 private void convolveMatrices(Beagle beagle, List<Deque<Integer>> convolutionList) {
321
322 Timer timer;
323 if (MEASURE_RUN_TIME) {
324 timer = new Timer();
325 timer.start();
326 }
327
328 while (convolutionList.size() > 0) {
329 int[] firstConvolutionBuffers = new int[nodeCount];
330 int[] secondConvolutionBuffers = new int[nodeCount];
331 int[] resultConvolutionBuffers = new int[nodeCount];
332 int operationsCount = 0;
333
334 List<Deque<Integer>> empty = new ArrayList<Deque<Integer>>();
335
336 for (Deque<Integer> convolve : convolutionList) {
337
338 if (convolve.size() > 3) {
339 firstConvolutionBuffers[operationsCount] = convolve.pop();
340 secondConvolutionBuffers[operationsCount] = convolve.pop();
341
342 int buffer;
343 boolean done;
344
345 do {
346 done = true;
347
348 buffer = popAvailableBuffer();
349
350 if (buffer < 0) {
351 // no buffers available
352 // throw new RuntimeException("All out of buffers");
353
354 // we have run out of buffers, process what we have and continue...
355 if (DEBUG) {
356 System.out.println("Ran out of buffers for convolving - computing current list.");
357 System.out.print("Convolving " + operationsCount + " matrices:");
358 for (int i = 0; i < operationsCount; i++) {
359 System.out.print(" " + firstConvolutionBuffers[i] + "*" + secondConvolutionBuffers[i] + "->" + resultConvolutionBuffers[i]);
360 }
361 System.out.println();
362 }
363
364 if (operationsCount > 0) {
365
366 convolveAndRelease(beagle, firstConvolutionBuffers, secondConvolutionBuffers, resultConvolutionBuffers, operationsCount);
367
368 // copy the uncompleted operation back down to the beginning of the operations list
369 firstConvolutionBuffers[0] = firstConvolutionBuffers[operationsCount];
370 secondConvolutionBuffers[0] = secondConvolutionBuffers[operationsCount];
371
372 // reset the operation count
373 operationsCount = 0;
374 done = false;
375
376 // there should be enough spare buffers to get a resultConvolutionBuffer for this operation now
377 } else {
378 // only one partially setup operation so there would be none to free up
379 // in this case we will use the reserve buffer
380 resultConvolutionBuffers[operationsCount] = getReserveBuffer();
381 convolveAndRelease(beagle, firstConvolutionBuffers, secondConvolutionBuffers, resultConvolutionBuffers, 1);
382 convolve.push(getReserveBuffer());
383 done = true; // break out of the do loop
384 }
385 }
386 } while (!done);
387
388 if (buffer >= 0) {
389 // if the buffer is still negative then the loop above will have used the reserve buffer
390 // to complete the convolution.
391 resultConvolutionBuffers[operationsCount] = buffer;
392 convolve.push(buffer);
393 operationsCount++;
394 }
395
396 } else if (convolve.size() == 3) {
397 firstConvolutionBuffers[operationsCount] = convolve.pop();
398 secondConvolutionBuffers[operationsCount] = convolve.pop();
399 resultConvolutionBuffers[operationsCount] = convolve.pop();
400 operationsCount++;
401 } else {
402 throw new RuntimeException("Unexpected convolve list size");
403 }
404
405 if (convolve.size() == 0) {
406 empty.add(convolve);
407 }
408 }
409
410 if (DEBUG) {
411 System.out.print("Convolving " + operationsCount+ " matrices:");
412 for (int i = 0; i < operationsCount; i++) {
413 System.out.print(" " + firstConvolutionBuffers[i] + "*" + secondConvolutionBuffers[i] + "->" + resultConvolutionBuffers[i]);
414 }
415 System.out.println();
416 }
417
418 convolveAndRelease(beagle, firstConvolutionBuffers, secondConvolutionBuffers, resultConvolutionBuffers, operationsCount);
419
420 convolutionList.removeAll(empty);
421 }
422
423 if (MEASURE_RUN_TIME) {
424 timer.stop();
425 double timeInSeconds = timer.toSeconds();
426 convolveTime += timeInSeconds;
427 }
428
429 }// END: convolveTransitionMatrices
430
431 private void convolveAndRelease(Beagle beagle, int[] firstConvolutionBuffers, int[] secondConvolutionBuffers, int[] resultConvolutionBuffers, int operationsCount) {
432
433 if (RUN_IN_SERIES) {
434 if (operationsCount > 1) {
435 throw new RuntimeException("Unable to convolve matrices in series");
436 }
437 }
438
439 beagle.convolveTransitionMatrices(firstConvolutionBuffers, // A
440 secondConvolutionBuffers, // B
441 resultConvolutionBuffers, // C
442 operationsCount // count
443 );
444
445 for (int i = 0; i < operationsCount; i++) {
446 if (firstConvolutionBuffers[i] >= matrixBufferHelper.getBufferCount() && firstConvolutionBuffers[i] != reserveBufferIndex) {
447 pushAvailableBuffer(firstConvolutionBuffers[i]);
448 }
449 if (secondConvolutionBuffers[i] >= matrixBufferHelper.getBufferCount() && secondConvolutionBuffers[i] != reserveBufferIndex) {
450 pushAvailableBuffer(secondConvolutionBuffers[i]);
451 }
452 }
453
454 }//END: convolveAndRelease
455
456 private int getAvailableBufferCount() {
457 if (RUN_IN_SERIES) {
458 return 0;
459 } else {
460 return availableBuffers.size();
461 }
462 }
463
464 private int popAvailableBuffer() {
465 if (availableBuffers.isEmpty()) {
466 return -1;
467 }
468 return availableBuffers.pop();
469 }
470
471 /**
472 * the reserve buffer is one extra buffer used to free up some spare buffers
473 * @return
474 */
475 private int getReserveBuffer() {
476 return reserveBufferIndex;
477 }
478
479 private void pushAvailableBuffer(int index) {
480 availableBuffers.push(index);
481 }
482
483 @Override
484 public void storeState() {
485 eigenBufferHelper.storeState();
486 matrixBufferHelper.storeState();
487 }
488
489 @Override
490 public void restoreState() {
491 eigenBufferHelper.restoreState();
492 matrixBufferHelper.restoreState();
493 }
494
495 }// END: class