Debian Codegraph @

src/dr/evomodel/treelikelihood/BeagleOperationReport.java

raw symbols SCIP
1 /*
2 * BeagleOperationReport.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.treelikelihood;
27
28 import beagle.Beagle;
29 import dr.evomodelxml.treelikelihood.BeagleOperationParser;
30 import dr.evomodel.siteratemodel.GammaSiteRateModel;
31 import dr.evomodel.substmodel.SubstitutionModel;
32 import dr.evolution.alignment.Alignment;
33 import dr.evolution.alignment.PatternList;
34 import dr.evolution.datatype.DataType;
35 import dr.evolution.tree.NodeRef;
36 import dr.evolution.tree.Tree;
37 import dr.evolution.util.TaxonList;
38 import dr.evomodel.branchratemodel.BranchRateModel;
39 import dr.evomodel.tree.TreeModel;
40 import dr.evomodel.tipstatesmodel.TipStatesModel;
41 import dr.math.matrixAlgebra.Vector;
42
43 import java.io.PrintWriter;
44
45 /**
46 * BeagleTreeLikelihoodModel - implements a Likelihood Function for sequences on a tree.
47 *
48 * @author Andrew Rambaut
49 * @author Alexei Drummond
50 * @author Marc Suchard
51 * @version $Id$
52 */
53
54 public class BeagleOperationReport extends AbstractSinglePartitionTreeLikelihood {
55
56 /**
57 * the patternList
58 */
59 protected PatternList patternList = null;
60 protected DataType dataType = null;
61 /**
62 * the pattern weights
63 */
64 protected double[] patternWeights;
65 /**
66 * the number of patterns
67 */
68 protected int patternCount;
69 /**
70 * the number of states in the data
71 */
72 protected int stateCount;
73 /**
74 * Flags to specify which patterns are to be updated
75 */
76 protected boolean[] updatePattern = null;
77
78 public BeagleOperationReport(TreeModel treeModel, PatternList patternList, BranchRateModel branchRateModel, GammaSiteRateModel siteRateModel, Alignment alignment, PrintWriter branch, PrintWriter operation) {
79 super(BeagleOperationParser.OPERATION_REPORT, patternList, treeModel);
80
81 boolean useAmbiguities = false;
82 this.branchRateModel = branchRateModel;
83 this.branchWriter = branch;
84 this.operationWriter = operation;
85 this.alignment = alignment;
86 this.substitutionModel = siteRateModel.getSubstitutionModel();
87
88 try {
89
90 this.tipCount = treeModel.getExternalNodeCount();
91
92 internalNodeCount = nodeCount - tipCount;
93
94 int compactPartialsCount = tipCount;
95
96 // one partials buffer for each tip and two for each internal node (for store restore)
97 partialBufferHelper = new BufferIndexHelper(nodeCount, tipCount);
98
99 // two eigen buffers for each decomposition for store and restore.
100 eigenBufferHelper = new BufferIndexHelper(eigenCount, 0);
101
102 // two matrices for each node less the root
103 matrixBufferHelper = new BufferIndexHelper(nodeCount, 0);
104
105 for (int i = 0; i < tipCount; i++) {
106 // Find the id of tip i in the patternList
107 String id = treeModel.getTaxonId(i);
108 int index = patternList.getTaxonIndex(id);
109
110 if (index == -1) {
111 throw new TaxonList.MissingTaxonException("Taxon, " + id + ", in tree, " + treeModel.getId() +
112 ", is not found in patternList, " + patternList.getId());
113 } else {
114
115 if (useAmbiguities) {
116 setPartials(beagle, patternList, index, i);
117 } else {
118 setStates(beagle, patternList, id, index, i);
119 }
120
121 }
122 }
123
124
125 } catch (TaxonList.MissingTaxonException mte) {
126 throw new RuntimeException(mte.toString());
127 }
128 hasInitialized = true;
129 }
130
131
132 public String toString() {
133
134 calculateLogLikelihood();
135 return super.toString();
136 }
137
138
139 public TreeModel getTreeModel() {
140 return treeModel;
141 }
142
143 /**
144 * Sets the partials from a sequence in an alignment.
145 *
146 * @param beagle beagle
147 * @param patternList patternList
148 * @param sequenceIndex sequenceIndex
149 * @param nodeIndex nodeIndex
150 */
151 protected final void setPartials(Beagle beagle,
152 PatternList patternList,
153 int sequenceIndex,
154 int nodeIndex) {
155 double[] partials = new double[patternCount * stateCount * categoryCount];
156
157 boolean[] stateSet;
158
159 int v = 0;
160 for (int i = 0; i < patternCount; i++) {
161
162 int state = patternList.getPatternState(sequenceIndex, i);
163 stateSet = dataType.getStateSet(state);
164
165 for (int j = 0; j < stateCount; j++) {
166 if (stateSet[j]) {
167 partials[v] = 1.0;
168 } else {
169 partials[v] = 0.0;
170 }
171 v++;
172 }
173 }
174
175 // if there is more than one category then replicate the partials for each
176 int n = patternCount * stateCount;
177 int k = n;
178 for (int i = 1; i < categoryCount; i++) {
179 System.arraycopy(partials, 0, partials, k, n);
180 k += n;
181 }
182
183 System.err.println("TODO Print partials");
184 // beagle.setPartials(nodeIndex, partials);
185 }
186
187 /**
188 * Sets the partials from a sequence in an alignment.
189 */
190 protected final void setPartials(Beagle beagle,
191 TipStatesModel tipStatesModel,
192 int nodeIndex) {
193 double[] partials = new double[patternCount * stateCount * categoryCount];
194
195 tipStatesModel.getTipPartials(nodeIndex, partials);
196
197 // if there is more than one category then replicate the partials for each
198 int n = patternCount * stateCount;
199 int k = n;
200 for (int i = 1; i < categoryCount; i++) {
201 System.arraycopy(partials, 0, partials, k, n);
202 k += n;
203 }
204
205 System.err.println("TODO Print partials");
206 // beagle.setPartials(nodeIndex, partials);
207 }
208
209 public int getPatternCount() {
210 return patternCount;
211 }
212
213 /**
214 * Sets the partials from a sequence in an alignment.
215 *
216 * @param beagle beagle
217 * @param patternList patternList
218 * @param id
219 * @param sequenceIndex sequenceIndex
220 * @param nodeIndex nodeIndex
221 */
222 protected final void setStates(Beagle beagle,
223 PatternList patternList,
224 String id, int sequenceIndex,
225 int nodeIndex) {
226 int i;
227
228 StringBuilder sb = new StringBuilder();
229 sb.append("/* ").append(id).append(" */\n\t\tmSeqs[").append(nodeIndex).append("] = \"");
230 sb.append(alignment.getAlignedSequenceString(sequenceIndex)).append("\";\n");
231
232 int[] states = new int[patternCount];
233
234 for (i = 0; i < patternCount; i++) {
235 states[i] = patternList.getPatternState(sequenceIndex, i);
236 }
237
238 if (alignmentString == null) {
239 alignmentString = new StringBuilder();
240 }
241 alignmentString.append(sb);
242 }
243
244
245 protected double calculateLogLikelihood() {
246
247 if (matrixUpdateIndices == null) {
248 matrixUpdateIndices = new int[eigenCount][nodeCount];
249 branchLengths = new double[eigenCount][nodeCount];
250 branchUpdateCount = new int[eigenCount];
251 // scaleBufferIndices = new int[internalNodeCount];
252 // storedScaleBufferIndices = new int[internalNodeCount];
253 }
254
255 if (operations == null) {
256 operations = new int[numRestrictedPartials + 1][internalNodeCount * Beagle.OPERATION_TUPLE_SIZE];
257 operationCount = new int[numRestrictedPartials + 1];
258 }
259
260 recomputeScaleFactors = false;
261
262 for (int i = 0; i < eigenCount; i++) {
263 branchUpdateCount[i] = 0;
264 }
265 operationListCount = 0;
266
267 if (hasRestrictedPartials) {
268 for (int i = 0; i <= numRestrictedPartials; i++) {
269 operationCount[i] = 0;
270 }
271 } else {
272 operationCount[0] = 0;
273 }
274
275 System.out.println(alignmentString.toString());
276
277 final NodeRef root = treeModel.getRoot();
278 traverse(treeModel, root, null, false); // Do not flip buffers
279
280 // Print out eigendecompositions
281
282
283 for (int i = 0; i < eigenCount; i++) {
284 if (branchUpdateCount[i] > 0) {
285
286 if (DEBUG_BEAGLE_OPERATIONS) {
287 StringBuilder sb = new StringBuilder();
288
289 sb.append("eval = ").append(new Vector(substitutionModel.getEigenDecomposition().getEigenValues())).append("\n");
290 sb.append("evec = ").append(new Vector(substitutionModel.getEigenDecomposition().getEigenVectors())).append("\n");
291 sb.append("ivec = ").append(new Vector(substitutionModel.getEigenDecomposition().getInverseEigenVectors())).append("\n");
292
293 sb.append("Branch count: ").append(branchUpdateCount[i]);
294 sb.append("\nNode indices:\n");
295 if (SINGLE_LINE) {
296 sb.append("int n[] = {");
297 }
298 for (int k = 0; k < branchUpdateCount[i]; ++k) {
299 if (SINGLE_LINE) {
300 sb.append(" ").append(matrixUpdateIndices[i][k]);
301 if (k < (branchUpdateCount[i] - 1)) {
302 sb.append(",");
303 }
304 } else {
305 sb.append(matrixUpdateIndices[i][k]).append("\n");
306 }
307 }
308 if (SINGLE_LINE) {
309 sb.append(" };\n");
310 }
311 sb.append("\nBranch lengths:\n");
312 if (SINGLE_LINE) {
313 sb.append("double b[] = {");
314 }
315 for (int k = 0; k < branchUpdateCount[i]; ++k) {
316 if (SINGLE_LINE) {
317 sb.append(" ").append(branchLengths[i][k]);
318 if (k < (branchUpdateCount[i] - 1)) {
319 sb.append(",");
320 }
321 } else {
322 sb.append(branchLengths[i][k]).append("\n");
323 }
324 }
325 if (SINGLE_LINE) {
326 sb.append(" };\n");
327 }
328 System.out.println(sb.toString());
329 }
330 }
331 }
332
333
334 if (DEBUG_BEAGLE_OPERATIONS) {
335 StringBuilder sb = new StringBuilder();
336 sb.append("Operation count: ").append(operationCount[0]);
337 sb.append("\nOperations:\n");
338 if (SINGLE_LINE) {
339 sb.append("BeagleOperation o[] = {");
340 }
341 for (int k = 0; k < operationCount[0] * Beagle.OPERATION_TUPLE_SIZE; ++k) {
342 if (SINGLE_LINE) {
343 sb.append(" ").append(operations[0][k]);
344 if (k < (operationCount[0] * Beagle.OPERATION_TUPLE_SIZE - 1)) {
345 sb.append(",");
346 }
347 } else {
348 sb.append(operations[0][k]).append("\n");
349 }
350 }
351 if (SINGLE_LINE) {
352 sb.append(" };\n");
353 }
354 sb.append("Use scale factors: ").append(useScaleFactors).append("\n");
355 System.out.println(sb.toString());
356
357 }
358
359
360 int rootIndex = partialBufferHelper.getOffsetIndex(root.getNumber());
361
362 System.out.println("Root node: " + rootIndex);
363
364 return 0.0;
365 }
366
367
368 /**
369 * Traverse the tree calculating partial likelihoods.
370 *
371 * @param tree tree
372 * @param node node
373 * @param operatorNumber operatorNumber
374 * @param flip flip
375 * @return boolean
376 */
377 private boolean traverse(Tree tree, NodeRef node, int[] operatorNumber, boolean flip) {
378
379 boolean update = false;
380
381 int nodeNum = node.getNumber();
382
383 NodeRef parent = tree.getParent(node);
384
385 if (operatorNumber != null) {
386 operatorNumber[0] = -1;
387 }
388
389 // First update the transition probability matrix(ices) for this branch
390 if (parent != null && updateNode[nodeNum]) {
391
392 final double branchRate = branchRateModel.getBranchRate(tree, node);
393
394 // Get the operational time of the branch
395 final double branchTime = branchRate * (tree.getNodeHeight(parent) - tree.getNodeHeight(node));
396
397 if (branchTime < 0.0) {
398 throw new RuntimeException("Negative branch length: " + branchTime);
399 }
400
401 if (flip) {
402 // first flip the matrixBufferHelper
403 matrixBufferHelper.flipOffset(nodeNum);
404 }
405
406 // then set which matrix to update
407 final int eigenIndex = 0; //branchSubstitutionModel.getBranchIndex(tree, node);
408 final int updateCount = branchUpdateCount[eigenIndex];
409 matrixUpdateIndices[eigenIndex][updateCount] = matrixBufferHelper.getOffsetIndex(nodeNum);
410
411 branchLengths[eigenIndex][updateCount] = branchTime;
412 branchUpdateCount[eigenIndex]++;
413
414 update = true;
415 }
416
417 // If the node is internal, update the partial likelihoods.
418 if (!tree.isExternal(node)) {
419
420 // Traverse down the two child nodes
421 NodeRef child1 = tree.getChild(node, 0);
422 final int[] op1 = {-1};
423 final boolean update1 = traverse(tree, child1, op1, flip);
424
425 NodeRef child2 = tree.getChild(node, 1);
426 final int[] op2 = {-1};
427 final boolean update2 = traverse(tree, child2, op2, flip);
428
429 // If either child node was updated then update this node too
430 if (update1 || update2) {
431
432 int x = operationCount[operationListCount] * Beagle.OPERATION_TUPLE_SIZE;
433
434 if (flip) {
435 // first flip the partialBufferHelper
436 partialBufferHelper.flipOffset(nodeNum);
437 }
438
439 final int[] operations = this.operations[operationListCount];
440
441 operations[x] = partialBufferHelper.getOffsetIndex(nodeNum);
442
443 if (useScaleFactors) {
444 // get the index of this scaling buffer
445 int n = nodeNum - tipCount;
446
447 if (recomputeScaleFactors) {
448 // flip the indicator: can take either n or (internalNodeCount + 1) - n
449 scaleBufferHelper.flipOffset(n);
450
451 // store the index
452 scaleBufferIndices[n] = scaleBufferHelper.getOffsetIndex(n);
453
454 operations[x + 1] = scaleBufferIndices[n]; // Write new scaleFactor
455 operations[x + 2] = Beagle.NONE;
456
457 } else {
458 operations[x + 1] = Beagle.NONE;
459 operations[x + 2] = scaleBufferIndices[n]; // Read existing scaleFactor
460 }
461
462 } else {
463
464 if (useAutoScaling) {
465 scaleBufferIndices[nodeNum - tipCount] = partialBufferHelper.getOffsetIndex(nodeNum);
466 }
467 operations[x + 1] = Beagle.NONE; // Not using scaleFactors
468 operations[x + 2] = Beagle.NONE;
469 }
470
471 operations[x + 3] = partialBufferHelper.getOffsetIndex(child1.getNumber()); // source node 1
472 operations[x + 4] = matrixBufferHelper.getOffsetIndex(child1.getNumber()); // source matrix 1
473 operations[x + 5] = partialBufferHelper.getOffsetIndex(child2.getNumber()); // source node 2
474 operations[x + 6] = matrixBufferHelper.getOffsetIndex(child2.getNumber()); // source matrix 2
475
476 operationCount[operationListCount]++;
477
478 update = true;
479 }
480 }
481
482 return update;
483
484 }
485
486 // **************************************************************
487 // INSTANCE VARIABLES
488 // **************************************************************
489
490 private int eigenCount = 1;
491 private int[][] matrixUpdateIndices;
492 private double[][] branchLengths;
493 private int[] branchUpdateCount;
494 private int[] scaleBufferIndices;
495 private int[] storedScaleBufferIndices;
496
497 private int[][] operations;
498 private int operationListCount;
499 private int[] operationCount;
500 private static final boolean hasRestrictedPartials = false;
501
502 private final int numRestrictedPartials = 0;
503
504 protected BufferIndexHelper partialBufferHelper;
505 private final BufferIndexHelper eigenBufferHelper;
506 protected BufferIndexHelper matrixBufferHelper;
507 protected BufferIndexHelper scaleBufferHelper;
508
509 protected final int tipCount;
510 protected final int internalNodeCount;
511
512 private PartialsRescalingScheme rescalingScheme;
513 protected boolean useScaleFactors = false;
514 private boolean useAutoScaling = false;
515 private boolean recomputeScaleFactors = false;
516 private boolean everUnderflowed = false;
517 private int rescalingCount = 0;
518 private int rescalingCountInner = 0;
519
520 protected final BranchRateModel branchRateModel;
521 protected double[] patternLogLikelihoods = null;
522
523 /**
524 * the number of rate categories
525 */
526 protected int categoryCount;
527
528 /**
529 * an array used to transfer tip partials
530 */
531 protected double[] tipPartials;
532
533 /**
534 * an array used to transfer tip states
535 */
536 protected int[] tipStates;
537
538 /**
539 * the BEAGLE library instance
540 */
541 protected Beagle beagle;
542
543 /**
544 * Flag to specify that the substitution model has changed
545 */
546 protected boolean updateSubstitutionModel;
547
548 /**
549 * Flag to specify that the site model has changed
550 */
551 protected boolean updateSiteModel;
552
553 private static final boolean DEBUG_BEAGLE_OPERATIONS = true;
554 private static final boolean SINGLE_LINE = true;
555
556 private StringBuilder alignmentString;
557
558
559 private final PrintWriter branchWriter;
560 private final PrintWriter operationWriter;
561 private final SubstitutionModel substitutionModel;
562
563 private final Alignment alignment;
564
565 /**
566 * Set update flag for a pattern
567 */
568 protected void updatePattern(int i) {
569 if (updatePattern != null) {
570 updatePattern[i] = true;
571 }
572 likelihoodKnown = false;
573 }
574
575 /**
576 * Set update flag for all patterns
577 */
578 protected void updateAllPatterns() {
579 if (updatePattern != null) {
580 for (int i = 0; i < patternCount; i++) {
581 updatePattern[i] = true;
582 }
583 }
584 likelihoodKnown = false;
585 }
586
587 protected class BufferIndexHelper {
588 /**
589 * @param maxIndexValue the number of possible input values for the index
590 * @param minIndexValue the minimum index value to have the mirrored buffers
591 */
592 BufferIndexHelper(int maxIndexValue, int minIndexValue) {
593 this.maxIndexValue = maxIndexValue;
594 this.minIndexValue = minIndexValue;
595
596 offsetCount = maxIndexValue - minIndexValue;
597 indexOffsets = new int[offsetCount];
598 storedIndexOffsets = new int[offsetCount];
599 }
600
601 public int getBufferCount() {
602 return 2 * offsetCount + minIndexValue;
603 }
604
605 void flipOffset(int i) {
606 if (i >= minIndexValue) {
607 indexOffsets[i - minIndexValue] = offsetCount - indexOffsets[i - minIndexValue];
608 } // else do nothing
609 }
610
611 int getOffsetIndex(int i) {
612 if (i < minIndexValue) {
613 return i;
614 }
615 return indexOffsets[i - minIndexValue] + i;
616 }
617
618 void getIndices(int[] outIndices) {
619 for (int i = 0; i < maxIndexValue; i++) {
620 outIndices[i] = getOffsetIndex(i);
621 }
622 }
623
624 void storeState() {
625 System.arraycopy(indexOffsets, 0, storedIndexOffsets, 0, indexOffsets.length);
626
627 }
628
629 void restoreState() {
630 int[] tmp = storedIndexOffsets;
631 storedIndexOffsets = indexOffsets;
632 indexOffsets = tmp;
633 }
634
635 private final int maxIndexValue;
636 private final int minIndexValue;
637 private final int offsetCount;
638
639 private int[] indexOffsets;
640 private int[] storedIndexOffsets;
641
642 }
643 }