Debian Codegraph @

src/dr/evomodel/treedatalikelihood/BeagleDataLikelihoodDelegate.java

raw symbols SCIP
1 /*
2 * BeagleDataLikelihoodDelegate.java
3 *
4 * Copyright (c) 2002-2017 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 /**
29 * BeagleDataLikelihoodDelegate
30 *
31 * A DataLikelihoodDelegate that uses BEAGLE
32 *
33 * @author Andrew Rambaut
34 * @author Marc Suchard
35 * @version $Id$
36 */
37
38 import beagle.*;
39 import dr.evomodel.branchmodel.BranchModel;
40 import dr.evomodel.siteratemodel.SiteRateModel;
41 import dr.evomodel.treelikelihood.*;
42 import dr.evolution.alignment.PatternList;
43 import dr.evolution.alignment.UncertainSiteList;
44 import dr.evolution.datatype.DataType;
45 import dr.evolution.tree.Tree;
46 import dr.evolution.util.TaxonList;
47 import dr.evomodel.tipstatesmodel.TipStatesModel;
48 import dr.inference.model.AbstractModel;
49 import dr.inference.model.Model;
50 import dr.inference.model.Parameter;
51 import dr.inference.model.Variable;
52 import dr.math.matrixAlgebra.Vector;
53 import dr.util.Citable;
54 import dr.util.Citation;
55 import dr.util.CommonCitations;
56
57 import java.util.ArrayList;
58 import java.util.Collections;
59 import java.util.List;
60 import java.util.logging.Logger;
61
62 public class BeagleDataLikelihoodDelegate extends AbstractModel implements DataLikelihoodDelegate, Citable {
63
64 public static boolean IS_THREAD_COUNT_COMPATIBLE() {
65 int[] versionNumbers = BeagleInfo.getVersionNumbers();
66 return versionNumbers.length != 0 && versionNumbers[0] >= 3 && versionNumbers[1] >= 1;
67 }
68
69 // This property is a comma-delimited list of resource numbers (0 == CPU) to
70 // allocate each BEAGLE instance to. If less than the number of instances then
71 // will wrap around.
72 private static final String RESOURCE_AUTO_PROPERTY = "beagle.resource.auto";
73 private static final String RESOURCE_ORDER_PROPERTY = "beagle.resource.order";
74 private static final String PREFERRED_FLAGS_PROPERTY = "beagle.preferred.flags";
75 private static final String REQUIRED_FLAGS_PROPERTY = "beagle.required.flags";
76 private static final String SCALING_PROPERTY = "beagle.scaling";
77 private static final String RESCALE_FREQUENCY_PROPERTY = "beagle.rescale";
78 private static final String DELAY_SCALING_PROPERTY = "beagle.delay.scaling";
79 private static final String EXTRA_BUFFER_COUNT_PROPERTY = "beagle.extra.buffer.count";
80 private static final String FORCE_VECTORIZATION = "beagle.force.vectorization";
81 private static final String THREAD_COUNT = "beagle.thread.count";
82
83 // Which scheme to use if choice not specified (or 'default' is selected):
84 private static final PartialsRescalingScheme DEFAULT_RESCALING_SCHEME = PartialsRescalingScheme.DYNAMIC;
85
86 private static int instanceCount = 0;
87 private static List<Integer> resourceOrder = null;
88 private static List<Integer> preferredOrder = null;
89 private static List<Integer> requiredOrder = null;
90 private static List<String> scalingOrder = null;
91 private static List<Integer> extraBufferOrder = null;
92
93 // Default frequency for complete recomputation of scaling factors under the 'dynamic' scheme
94 private static final int RESCALE_FREQUENCY = 100;
95 private static final int RESCALE_TIMES = 1;
96
97 private static final boolean RESCALING_OFF = false; // a debugging switch
98
99 private static final boolean DEBUG = false;
100
101 /**
102 *
103 * @param tree Used for configuration - shouldn't be watched for changes
104 * @param branchModel Specifies substitution model for each branch
105 * @param patternList List of patterns
106 * @param siteRateModel Specifies rates per site
107 * @param useAmbiguities Whether to respect state ambiguities in data
108 */
109 public BeagleDataLikelihoodDelegate(Tree tree,
110 PatternList patternList,
111 BranchModel branchModel,
112 SiteRateModel siteRateModel,
113 boolean useAmbiguities,
114 PartialsRescalingScheme rescalingScheme,
115 boolean delayRescalingUntilUnderflow) {
116
117 super("BeagleDataLikelihoodDelegate");
118 final Logger logger = Logger.getLogger("dr.evomodel");
119
120 logger.info("\nUsing BEAGLE DataLikelihood Delegate");
121 setId(patternList.getId());
122
123 this.dataType = patternList.getDataType();
124 this.patternList = patternList;
125 patternCount = patternList.getPatternCount();
126 stateCount = dataType.getStateCount();
127
128 // Check for matching state counts
129 int stateCount2 = branchModel.getRootFrequencyModel().getFrequencyCount();
130 if (stateCount != stateCount2) {
131 throw new IllegalArgumentException("Pattern state count (" + stateCount
132 + ") does not match substitution model state count (" + stateCount2 + ")");
133 }
134
135 patternWeights = patternList.getPatternWeights();
136
137 this.branchModel = branchModel;
138 addModel(this.branchModel);
139
140 this.siteRateModel = siteRateModel;
141 addModel(this.siteRateModel);
142
143 this.categoryCount = this.siteRateModel.getCategoryCount();
144
145 nodeCount = tree.getNodeCount();
146 tipCount = tree.getExternalNodeCount();
147 internalNodeCount = nodeCount - tipCount;
148
149 branchUpdateIndices = new int[nodeCount];
150 branchLengths = new double[nodeCount];
151 scaleBufferIndices = new int[internalNodeCount];
152 storedScaleBufferIndices = new int[internalNodeCount];
153
154 operations = new int[internalNodeCount * Beagle.OPERATION_TUPLE_SIZE];
155
156 firstRescaleAttempt = true;
157
158 try {
159
160 int compactPartialsCount = tipCount;
161 if (useAmbiguities) {
162 // if we are using ambiguities then we don't use tip partials
163 compactPartialsCount = 0;
164 }
165
166 // one partials buffer for each tip and two for each internal node (for store restore)
167 partialBufferHelper = new BufferIndexHelper(nodeCount, tipCount);
168
169 // one scaling buffer for each internal node plus an extra for the accumulation, then doubled for store/restore
170 scaleBufferHelper = new BufferIndexHelper(getScaleBufferCount(), 0);
171
172 evolutionaryProcessDelegate = new HomogenousSubstitutionModelDelegate(tree, branchModel);
173
174 // Attempt to get the resource order from the System Property
175 if (resourceOrder == null) {
176 resourceOrder = parseSystemPropertyIntegerArray(RESOURCE_ORDER_PROPERTY);
177 }
178 if (preferredOrder == null) {
179 preferredOrder = parseSystemPropertyIntegerArray(PREFERRED_FLAGS_PROPERTY);
180 }
181 if (requiredOrder == null) {
182 requiredOrder = parseSystemPropertyIntegerArray(REQUIRED_FLAGS_PROPERTY);
183 }
184 if (scalingOrder == null) {
185 scalingOrder = parseSystemPropertyStringArray(SCALING_PROPERTY);
186 }
187 if (extraBufferOrder == null) {
188 extraBufferOrder = parseSystemPropertyIntegerArray(EXTRA_BUFFER_COUNT_PROPERTY);
189 }
190
191 // first set the rescaling scheme to use from the parser
192 this.rescalingScheme = rescalingScheme;
193 this.delayRescalingUntilUnderflow = delayRescalingUntilUnderflow;
194
195 int[] resourceList = null;
196 long preferenceFlags = 0;
197 long requirementFlags = 0;
198
199 if (scalingOrder.size() > 0) {
200 this.rescalingScheme = PartialsRescalingScheme.parseFromString(
201 scalingOrder.get(instanceCount % scalingOrder.size()));
202 }
203
204 if (resourceOrder.size() > 0) {
205 // added the zero on the end so that a CPU is selected if requested resource fails
206 resourceList = new int[]{resourceOrder.get(instanceCount % resourceOrder.size()), 0};
207 if (resourceList[0] > 0) {
208 preferenceFlags |= BeagleFlag.PROCESSOR_GPU.getMask(); // Add preference weight against CPU
209 }
210 }
211
212 if (preferredOrder.size() > 0) {
213 preferenceFlags = preferredOrder.get(instanceCount % preferredOrder.size());
214 }
215
216 if (requiredOrder.size() > 0) {
217 requirementFlags = requiredOrder.get(instanceCount % requiredOrder.size());
218 }
219
220
221 // Define default behaviour here
222 if (this.rescalingScheme == PartialsRescalingScheme.DEFAULT) {
223 //if GPU: the default is dynamic scaling in BEAST
224 if (resourceList != null && resourceList[0] > 1) {
225 this.rescalingScheme = DEFAULT_RESCALING_SCHEME;
226 } else { // if CPU: just run as fast as possible
227 // this.rescalingScheme = PartialsRescalingScheme.NONE;
228 // Dynamic should run as fast as none until first underflow
229 this.rescalingScheme = DEFAULT_RESCALING_SCHEME;
230 }
231 }
232
233 // to keep behaviour of the delayed scheme (always + delay)...
234 if (this.rescalingScheme == PartialsRescalingScheme.DELAYED) {
235 this.delayRescalingUntilUnderflow = true;
236 this.rescalingScheme = PartialsRescalingScheme.ALWAYS;
237 }
238
239 if (this.rescalingScheme == PartialsRescalingScheme.AUTO) {
240 preferenceFlags |= BeagleFlag.SCALING_AUTO.getMask();
241 useAutoScaling = true;
242 } else {
243 // preferenceFlags |= BeagleFlag.SCALING_MANUAL.getMask();
244 }
245
246 String r = System.getProperty(RESCALE_FREQUENCY_PROPERTY);
247 if (r != null) {
248 rescalingFrequency = Integer.parseInt(r);
249 if (rescalingFrequency < 1) {
250 rescalingFrequency = RESCALE_FREQUENCY;
251 }
252 }
253
254 String d = System.getProperty(DELAY_SCALING_PROPERTY);
255 if (d != null) {
256 this.delayRescalingUntilUnderflow = Boolean.parseBoolean(d);
257 }
258
259 if (preferenceFlags == 0 && resourceList == null) { // else determine dataset characteristics
260 if (stateCount == 4 && patternList.getPatternCount() < 10000) // TODO determine good cut-off
261 preferenceFlags |= BeagleFlag.PROCESSOR_CPU.getMask();
262 }
263
264 boolean forceVectorization = false;
265 String vectorizationString = System.getProperty(FORCE_VECTORIZATION);
266 if (vectorizationString != null) {
267 forceVectorization = true;
268 }
269
270 String tc = System.getProperty(THREAD_COUNT);
271 if (tc != null) {
272 threadCount = Integer.parseInt(tc);
273 if (threadCount < 2) {
274 threadCount = 1;
275 }
276 }
277
278 if (BeagleFlag.VECTOR_SSE.isSet(preferenceFlags) && (stateCount != 4)
279 && !forceVectorization
280 ) {
281 // @todo SSE doesn't seem to work for larger state spaces so for now we override the
282 // SSE option.
283 preferenceFlags &= ~BeagleFlag.VECTOR_SSE.getMask();
284 preferenceFlags |= BeagleFlag.VECTOR_NONE.getMask();
285
286 if (stateCount > 4 && this.rescalingScheme == PartialsRescalingScheme.DYNAMIC) {
287 this.rescalingScheme = PartialsRescalingScheme.DELAYED;
288 }
289 }
290
291 if (!BeagleFlag.PRECISION_SINGLE.isSet(preferenceFlags)) {
292 // if single precision not explicitly set then prefer double
293 preferenceFlags |= BeagleFlag.PRECISION_DOUBLE.getMask();
294 }
295
296 if (evolutionaryProcessDelegate.canReturnComplexDiagonalization()) {
297 requirementFlags |= BeagleFlag.EIGEN_COMPLEX.getMask();
298 }
299
300 if ((resourceList == null &&
301 (BeagleFlag.PROCESSOR_GPU.isSet(preferenceFlags) ||
302 BeagleFlag.FRAMEWORK_CUDA.isSet(preferenceFlags) ||
303 BeagleFlag.FRAMEWORK_OPENCL.isSet(preferenceFlags)))
304 ||
305 (resourceList != null && resourceList[0] > 0)) {
306 // non-CPU implementations don't have SSE so remove default preference for SSE
307 // when using non-CPU preferences or prioritising non-CPU resource
308 preferenceFlags &= ~BeagleFlag.VECTOR_SSE.getMask();
309 preferenceFlags &= ~BeagleFlag.THREADING_CPP.getMask();
310 }
311
312 // start auto resource selection
313 String resourceAuto = System.getProperty(RESOURCE_AUTO_PROPERTY);
314 if (resourceAuto != null && Boolean.parseBoolean(resourceAuto)) {
315
316 long benchmarkFlags = 0;
317
318 if (this.rescalingScheme == PartialsRescalingScheme.NONE) {
319 benchmarkFlags = BeagleBenchmarkFlag.SCALING_NONE.getMask();
320 } else if (this.rescalingScheme == PartialsRescalingScheme.ALWAYS) {
321 benchmarkFlags = BeagleBenchmarkFlag.SCALING_ALWAYS.getMask();
322 } else {
323 benchmarkFlags = BeagleBenchmarkFlag.SCALING_DYNAMIC.getMask();
324 }
325
326 logger.info("\nRunning benchmarks to automatically select fastest BEAGLE resource for analysis or partition... ");
327
328 List<BenchmarkedResourceDetails> benchmarkedResourceDetails =
329 BeagleFactory.getBenchmarkedResourceDetails(
330 tipCount,
331 compactPartialsCount,
332 stateCount,
333 patternCount,
334 categoryCount,
335 resourceList,
336 preferenceFlags,
337 requirementFlags,
338 1, // eigenModelCount,
339 1, // partitionCount,
340 0, // calculateDerivatives,
341 benchmarkFlags);
342
343
344 logger.info(" Benchmark results, from fastest to slowest:");
345
346 for (BenchmarkedResourceDetails benchmarkedResource : benchmarkedResourceDetails) {
347 logger.info(benchmarkedResource.toString());
348 }
349
350 resourceList = new int[]{benchmarkedResourceDetails.get(0).getResourceNumber()};
351 }
352 // end auto resource selection
353
354 beagle = BeagleFactory.loadBeagleInstance(
355 tipCount,
356 partialBufferHelper.getBufferCount(),
357 compactPartialsCount,
358 stateCount,
359 patternCount,
360 evolutionaryProcessDelegate.getEigenBufferCount(),
361 evolutionaryProcessDelegate.getMatrixBufferCount(),
362 categoryCount,
363 scaleBufferHelper.getBufferCount(), // Always allocate; they may become necessary
364 resourceList,
365 preferenceFlags,
366 requirementFlags
367 );
368
369 InstanceDetails instanceDetails = beagle.getDetails();
370 ResourceDetails resourceDetails = null;
371
372 if (instanceDetails != null) {
373 resourceDetails = BeagleFactory.getResourceDetails(instanceDetails.getResourceNumber());
374 if (resourceDetails != null) {
375 StringBuilder sb = new StringBuilder(" Using BEAGLE resource ");
376 sb.append(resourceDetails.getNumber()).append(": ");
377 sb.append(resourceDetails.getName()).append("\n");
378 if (resourceDetails.getDescription() != null) {
379 String[] description = resourceDetails.getDescription().split("\\|");
380 for (String desc : description) {
381 if (desc.trim().length() > 0) {
382 sb.append(" ").append(desc.trim()).append("\n");
383 }
384 }
385 }
386 sb.append(" with instance flags: ").append(instanceDetails.toString());
387 logger.info(sb.toString());
388 } else {
389 logger.info(" Error retrieving BEAGLE resource for instance: " + instanceDetails.toString());
390 }
391 } else {
392 logger.info(" No external BEAGLE resources available, or resource list/requirements not met, using Java implementation");
393 }
394
395 instanceFlags = instanceDetails.getFlags();
396
397 if (IS_THREAD_COUNT_COMPATIBLE() && threadCount > 1) {
398 beagle.setCPUThreadCount(threadCount);
399 }
400
401 if (patternList instanceof UncertainSiteList) { // TODO Remove
402 useAmbiguities = true;
403 }
404
405 logger.info(" " + (useAmbiguities ? "Using" : "Ignoring") + " ambiguities in tree likelihood.");
406 logger.info(" With " + patternList.getPatternCount() + " unique site patterns.");
407
408 if (patternList.areUncertain() && !useAmbiguities) {
409 logger.info(" WARNING: Uncertain site patterns will be ignored.");
410 }
411
412 for (int i = 0; i < tipCount; i++) {
413 // Find the id of tip i in the patternList
414 String id = tree.getTaxonId(i);
415 int index = patternList.getTaxonIndex(id);
416
417 if (index == -1) {
418 throw new TaxonList.MissingTaxonException("Taxon, " + id + ", in tree, " + tree.getId() +
419 ", is not found in patternList, " + patternList.getId());
420 } else {
421 if (useAmbiguities) {
422 setPartials(beagle, patternList, index, i);
423 } else {
424 setStates(beagle, patternList, index, i);
425 }
426 }
427 }
428
429 beagle.setPatternWeights(patternWeights);
430
431 String rescaleMessage = " Using rescaling scheme : " + this.rescalingScheme.getText();
432 if (this.rescalingScheme == PartialsRescalingScheme.AUTO &&
433 resourceDetails != null &&
434 (resourceDetails.getFlags() & BeagleFlag.SCALING_AUTO.getMask()) == 0) {
435 // If auto scaling in BEAGLE is not supported then do it here
436 this.rescalingScheme = PartialsRescalingScheme.DYNAMIC;
437 rescaleMessage = " Auto rescaling not supported in BEAGLE, using : " + this.rescalingScheme.getText();
438 }
439 boolean parenthesis = false;
440 if (this.rescalingScheme == PartialsRescalingScheme.DYNAMIC) {
441 rescaleMessage += " (rescaling every " + rescalingFrequency + " evaluations";
442 parenthesis = true;
443 }
444 if (this.delayRescalingUntilUnderflow) {
445 rescaleMessage += (parenthesis ? ", " : "(") + "delay rescaling until first overflow";
446 parenthesis = true;
447 }
448 rescaleMessage += (parenthesis ? ")" : "");
449 logger.info(rescaleMessage);
450
451 if (this.rescalingScheme == PartialsRescalingScheme.DYNAMIC) {
452 everUnderflowed = false; // If false, BEAST does not rescale until first under-/over-flow.
453 }
454
455 updateSubstitutionModel = true;
456 updateSiteModel = true;
457
458 } catch (TaxonList.MissingTaxonException mte) {
459 throw new RuntimeException(mte.toString());
460 }
461
462 instanceCount++;
463 }
464
465 @Override
466 public String getReport() {
467 return null;
468 }
469
470 @Override
471 public TreeTraversal.TraversalType getOptimalTraversalType() {
472 if ((instanceFlags & BeagleFlag.FRAMEWORK_CPU.getMask()) != 0) {
473 return TreeTraversal.TraversalType.POST_ORDER;
474 } else {
475 return TreeTraversal.TraversalType.REVERSE_LEVEL_ORDER;
476 }
477 }
478
479 @Override
480 public int getTraitCount() {
481 return 1;
482 }
483
484 @Override
485 public int getTraitDim() {
486 return patternCount;
487 }
488
489 @Override
490 public RateRescalingScheme getRateRescalingScheme() {
491 return RateRescalingScheme.NONE;
492 }
493
494 public PatternList getPatternList() {
495 return this.patternList;
496 }
497
498 private static List<Integer> parseSystemPropertyIntegerArray(String propertyName) {
499 List<Integer> order = new ArrayList<Integer>();
500 String r = System.getProperty(propertyName);
501 if (r != null) {
502 String[] parts = r.split(",");
503 for (String part : parts) {
504 try {
505 int n = Integer.parseInt(part.trim());
506 order.add(n);
507 } catch (NumberFormatException nfe) {
508 System.err.println("Invalid entry '" + part + "' in " + propertyName);
509 }
510 }
511 }
512 return order;
513 }
514
515 private static List<String> parseSystemPropertyStringArray(String propertyName) {
516
517 List<String> order = new ArrayList<String>();
518
519 String r = System.getProperty(propertyName);
520 if (r != null) {
521 String[] parts = r.split(",");
522 for (String part : parts) {
523 try {
524 String s = part.trim();
525 order.add(s);
526 } catch (NumberFormatException nfe) {
527 System.err.println("Invalid entry '" + part + "' in " + propertyName);
528 }
529 }
530 }
531 return order;
532 }
533
534 private int getScaleBufferCount() {
535 return internalNodeCount + 1;
536 }
537
538 /**
539 * Sets the partials from a sequence in an alignment.
540 *
541 * @param beagle beagle
542 * @param patternList patternList
543 * @param sequenceIndex sequenceIndex
544 * @param nodeIndex nodeIndex
545 */
546 private final void setPartials(Beagle beagle,
547 PatternList patternList,
548 int sequenceIndex,
549 int nodeIndex) {
550 double[] partials = new double[patternCount * stateCount * categoryCount];
551
552 int v = 0;
553 for (int i = 0; i < patternCount; i++) {
554
555 if (patternList instanceof UncertainSiteList) {
556 ((UncertainSiteList) patternList).fillPartials(sequenceIndex, i, partials, v);
557 v += stateCount;
558 // TODO Add this functionality to SimpleSiteList to avoid if statement here
559 } else if (patternList.areUncertain()) {
560
561 double[] prob = patternList.getUncertainPatternState(sequenceIndex, i);
562 System.arraycopy(prob, 0, partials, v, stateCount);
563 v += stateCount;
564
565 } else {
566 int state = patternList.getPatternState(sequenceIndex, i);
567 boolean[] stateSet = dataType.getStateSet(state);
568
569 for (int j = 0; j < stateCount; j++) {
570 if (stateSet[j]) {
571 partials[v] = 1.0;
572 } else {
573 partials[v] = 0.0;
574 }
575 v++;
576 }
577 }
578 }
579
580 // if there is more than one category then replicate the partials for each
581 int n = patternCount * stateCount;
582 int k = n;
583 for (int i = 1; i < categoryCount; i++) {
584 System.arraycopy(partials, 0, partials, k, n);
585 k += n;
586 }
587
588 beagle.setPartials(nodeIndex, partials);
589 }
590
591 /**
592 * Sets the partials from a sequence in an alignment.
593 */
594 private final void setPartials(Beagle beagle,
595 TipStatesModel tipStatesModel,
596 int nodeIndex) {
597 double[] partials = new double[patternCount * stateCount * categoryCount];
598
599 tipStatesModel.getTipPartials(nodeIndex, partials);
600
601 // if there is more than one category then replicate the partials for each
602 int n = patternCount * stateCount;
603 int k = n;
604 for (int i = 1; i < categoryCount; i++) {
605 System.arraycopy(partials, 0, partials, k, n);
606 k += n;
607 }
608
609 beagle.setPartials(nodeIndex, partials);
610 }
611
612 /**
613 * Sets the partials from a sequence in an alignment.
614 *
615 * @param beagle beagle
616 * @param patternList patternList
617 * @param sequenceIndex sequenceIndex
618 * @param nodeIndex nodeIndex
619 */
620 private final void setStates(Beagle beagle,
621 PatternList patternList,
622 int sequenceIndex,
623 int nodeIndex) {
624 int i;
625
626 int[] states = new int[patternCount];
627
628 for (i = 0; i < patternCount; i++) {
629
630 states[i] = patternList.getPatternState(sequenceIndex, i);
631 }
632
633 beagle.setTipStates(nodeIndex, states);
634 }
635
636 /**
637 * Calculate the log likelihood of the current state.
638 *
639 * @return the log likelihood.
640 */
641 @Override
642 public double calculateLikelihood(List<BranchOperation> branchOperations, List<NodeOperation> nodeOperations, int rootNodeNumber) throws LikelihoodException {
643
644 //recomputeScaleFactors = false;
645 if (DEBUG) {
646 System.out.println("Partition: " + this.getModelName());
647 }
648
649 if (!this.delayRescalingUntilUnderflow || everUnderflowed) {
650 if (this.rescalingScheme == PartialsRescalingScheme.ALWAYS || this.rescalingScheme == PartialsRescalingScheme.DELAYED) {
651 useScaleFactors = true;
652 recomputeScaleFactors = true;
653 } else if (this.rescalingScheme == PartialsRescalingScheme.DYNAMIC) {
654 useScaleFactors = true;
655
656 if (rescalingCount > rescalingFrequency) {
657 if (DEBUG) {
658 System.out.println("rescalingCount > rescalingFrequency");
659 }
660 rescalingCount = 0;
661 rescalingCountInner = 0;
662 }
663
664 if (DEBUG) {
665 System.out.println("rescalingCountInner = " + rescalingCountInner);
666 }
667
668 if (rescalingCountInner < RESCALE_TIMES) {
669 if (DEBUG) {
670 System.out.println("rescalingCountInner < RESCALE_TIMES");
671 }
672
673 recomputeScaleFactors = true;
674
675 rescalingCountInner++;
676
677 throw new LikelihoodRescalingException();
678
679 }
680
681 //underflowHandling takes into account the first evaluation when initiating the MCMC chain
682 //suggest replacing with boolean initialEvaluation
683 if (initialEvaluation) {
684 if (underflowHandling < 1) {
685 underflowHandling++;
686 if (DEBUG) {
687 System.out.println("underflowHandling < 1");
688 }
689 } else if (underflowHandling == 1) {
690 if (DEBUG) {
691 System.out.println("underflowHandling == 1");
692 }
693 recomputeScaleFactors = true;
694 underflowHandling++;
695 initialEvaluation = false;
696 }
697 }
698
699 rescalingCount++;
700 }
701 }
702
703 if (RESCALING_OFF) { // a debugging switch
704 useScaleFactors = false;
705 recomputeScaleFactors = false;
706 }
707
708 int branchUpdateCount = 0;
709 for (BranchOperation op : branchOperations) {
710 branchUpdateIndices[branchUpdateCount] = op.getBranchNumber();
711 branchLengths[branchUpdateCount] = op.getBranchLength();
712 branchUpdateCount ++;
713 }
714
715 if (updateSubstitutionModel) { // TODO More efficient to update only the substitution model that changed, instead of all
716 evolutionaryProcessDelegate.updateSubstitutionModels(beagle, flip);
717
718 // we are currently assuming a no-category model...
719 }
720
721 if (updateSiteModel) {
722 double[] categoryRates = this.siteRateModel.getCategoryRates();
723 if (categoryRates == null) {
724 // If this returns null then there was a numerical error calculating the category rates
725 // (probably a very small alpha) so reject the move.
726 return Double.NEGATIVE_INFINITY;
727 }
728 beagle.setCategoryRates(categoryRates);
729 }
730
731 if (branchUpdateCount > 0) {
732 evolutionaryProcessDelegate.updateTransitionMatrices(
733 beagle,
734 branchUpdateIndices,
735 branchLengths,
736 branchUpdateCount,
737 flip);
738 }
739
740 if (flip) {
741 // Flip all the buffers to be written to first...
742 for (NodeOperation op : nodeOperations) {
743 partialBufferHelper.flipOffset(op.getNodeNumber());
744 }
745 }
746
747 int operationCount = nodeOperations.size();
748 int k = 0;
749 for (NodeOperation op : nodeOperations) {
750 int nodeNum = op.getNodeNumber();
751
752 operations[k] = partialBufferHelper.getOffsetIndex(nodeNum);
753
754 if (useScaleFactors) {
755 // get the index of this scaling buffer
756 int n = nodeNum - tipCount;
757
758 if (recomputeScaleFactors) {
759 // flip the indicator: can take either n or (internalNodeCount + 1) - n
760 scaleBufferHelper.flipOffset(n);
761
762 // store the index
763 scaleBufferIndices[n] = scaleBufferHelper.getOffsetIndex(n);
764
765 operations[k + 1] = scaleBufferIndices[n]; // Write new scaleFactor
766 operations[k + 2] = Beagle.NONE;
767
768 } else {
769 operations[k + 1] = Beagle.NONE;
770 operations[k + 2] = scaleBufferIndices[n]; // Read existing scaleFactor
771 }
772
773 } else {
774
775 if (useAutoScaling) {
776 scaleBufferIndices[nodeNum - tipCount] = partialBufferHelper.getOffsetIndex(nodeNum);
777 }
778 operations[k + 1] = Beagle.NONE; // Not using scaleFactors
779 operations[k + 2] = Beagle.NONE;
780 }
781
782 operations[k + 3] = partialBufferHelper.getOffsetIndex(op.getLeftChild()); // source node 1
783 operations[k + 4] = evolutionaryProcessDelegate.getMatrixIndex(op.getLeftChild()); // source matrix 1
784 operations[k + 5] = partialBufferHelper.getOffsetIndex(op.getRightChild()); // source node 2
785 operations[k + 6] = evolutionaryProcessDelegate.getMatrixIndex(op.getRightChild()); // source matrix 2
786
787 k += Beagle.OPERATION_TUPLE_SIZE;
788 }
789
790 beagle.updatePartials(operations, operationCount, Beagle.NONE);
791
792 int rootIndex = partialBufferHelper.getOffsetIndex(rootNodeNumber);
793
794 double[] categoryWeights = this.siteRateModel.getCategoryProportions();
795
796 // This should probably explicitly be the state frequencies for the root node...
797 double[] frequencies = evolutionaryProcessDelegate.getRootStateFrequencies();
798
799 int cumulateScaleBufferIndex = Beagle.NONE;
800
801 if (useScaleFactors) {
802 if (recomputeScaleFactors) {
803 scaleBufferHelper.flipOffset(internalNodeCount);
804 cumulateScaleBufferIndex = scaleBufferHelper.getOffsetIndex(internalNodeCount);
805 beagle.resetScaleFactors(cumulateScaleBufferIndex);
806 beagle.accumulateScaleFactors(scaleBufferIndices, internalNodeCount, cumulateScaleBufferIndex);
807 } else {
808 cumulateScaleBufferIndex = scaleBufferHelper.getOffsetIndex(internalNodeCount);
809 }
810 } else if (useAutoScaling) {
811 beagle.accumulateScaleFactors(scaleBufferIndices, internalNodeCount, Beagle.NONE);
812 }
813
814 // these could be set only when they change but store/restore would need to be considered
815 beagle.setCategoryWeights(0, categoryWeights);
816 beagle.setStateFrequencies(0, frequencies);
817
818 double[] sumLogLikelihoods = new double[1];
819
820 if (DEBUG) {
821 System.out.println("useScaleFactors=" + useScaleFactors + " recomputeScaleFactors=" + recomputeScaleFactors + " (" + getId() + ")");
822 }
823
824 beagle.calculateRootLogLikelihoods(new int[]{rootIndex}, new int[]{0}, new int[]{0},
825 new int[]{cumulateScaleBufferIndex}, 1, sumLogLikelihoods);
826
827 double logL = sumLogLikelihoods[0];
828
829 /*if (DEBUG) {
830 System.out.println(logL);
831 if (logL > -90000) {
832 System.exit(0);
833 }
834 }*/
835
836 if (Double.isNaN(logL) || Double.isInfinite(logL)) {
837
838 if (DEBUG) {
839 System.out.println("Double.isNaN(logL) || Double.isInfinite(logL) (" + getId() + ")");
840 }
841
842 everUnderflowed = true;
843
844 logL = Double.NEGATIVE_INFINITY;
845
846 if (firstRescaleAttempt && (delayRescalingUntilUnderflow || rescalingScheme == PartialsRescalingScheme.DELAYED)) {
847
848 if (rescalingScheme == PartialsRescalingScheme.DYNAMIC || (rescalingCount == 0)) {
849 // show a message but only every 1000 rescales
850 if (rescalingMessageCount % 1000 == 0) {
851 if (rescalingMessageCount > 0) {
852 Logger.getLogger("dr.evomodel").info("Underflow calculating likelihood (" + rescalingMessageCount + " messages not shown; " + getId() + ").");
853 } else {
854 Logger.getLogger("dr.evomodel").info("Underflow calculating likelihood. Attempting a rescaling... (" + getId() + ")");
855 }
856 }
857 rescalingMessageCount += 1;
858 }
859
860 useScaleFactors = true;
861 recomputeScaleFactors = true;
862
863 firstRescaleAttempt = false; // Only try to rescale once
864
865 rescalingCount--;
866
867 }
868
869 // turn off double buffer flipping so the next call overwrites the
870 // underflowed buffers. Flip will be turned on again in storeState for
871 // next step
872 flip = false;
873 underflowHandling = 0;
874 throw new LikelihoodUnderflowException();
875
876 } else {
877
878 firstRescaleAttempt = true;
879 recomputeScaleFactors = false;
880 flip = true;
881
882 }
883
884 updateSubstitutionModel = false;
885 updateSiteModel = false;
886 //********************************************************************
887
888 // If these are needed...
889 //if (patternLogLikelihoods == null) {
890 // patternLogLikelihoods = new double[patternCount];
891 //}
892 //beagle.getSiteLogLikelihoods(patternLogLikelihoods);
893
894 return logL;
895 }
896
897 public void getPartials(int number, double[] partials) {
898 int cumulativeBufferIndex = Beagle.NONE;
899 /* No need to rescale partials */
900 beagle.getPartials(partialBufferHelper.getOffsetIndex(number), cumulativeBufferIndex, partials);
901 }
902
903 private void setPartials(int number, double[] partials) {
904 beagle.setPartials(partialBufferHelper.getOffsetIndex(number), partials);
905 }
906
907 @Override
908 public void makeDirty() {
909 updateSiteModel = true;
910 updateSubstitutionModel = true;
911 }
912
913 @Override
914 protected void handleModelChangedEvent(Model model, Object object, int index) {
915 if (model == siteRateModel) {
916 updateSiteModel = true;
917 } else if (model == branchModel) {
918 updateSubstitutionModel = true;
919 }
920
921 // Tell TreeDataLikelihood to update all nodes
922 fireModelChanged();
923 }
924
925 @Override
926 protected void handleVariableChangedEvent(Variable variable, int index, Parameter.ChangeType type) {
927
928 }
929
930 /**
931 * Stores the additional state other than model components
932 */
933 @Override
934 public void storeState() {
935 partialBufferHelper.storeState();
936 evolutionaryProcessDelegate.storeState();
937
938 if (useScaleFactors || useAutoScaling) { // Only store when actually used
939 scaleBufferHelper.storeState();
940 System.arraycopy(scaleBufferIndices, 0, storedScaleBufferIndices, 0, scaleBufferIndices.length);
941 // storedRescalingCount = rescalingCount;
942 }
943
944 // turn on double buffering flipping (may have been turned off to enable a rescale)
945 flip = true;
946 }
947
948 /**
949 * Restore the additional stored state
950 */
951 @Override
952 public void restoreState() {
953 updateSiteModel = true; // this is required to upload the categoryRates to BEAGLE after the restore
954
955 partialBufferHelper.restoreState();
956 evolutionaryProcessDelegate.restoreState();
957
958 if (useScaleFactors || useAutoScaling) {
959 scaleBufferHelper.restoreState();
960 int[] tmp = storedScaleBufferIndices;
961 storedScaleBufferIndices = scaleBufferIndices;
962 scaleBufferIndices = tmp;
963 // rescalingCount = storedRescalingCount;
964 }
965
966 }
967
968 @Override
969 public void setCallback(TreeDataLikelihood treeDataLikelihood) {
970 // Callback not necessary
971 }
972
973 @Override
974 public int vectorizeNodeOperations(List<ProcessOnTreeDelegate.NodeOperation> nodeOperations, int[] operations) {
975 throw new RuntimeException("Not yet implemented");
976 }
977
978 @Override
979 protected void acceptState() {
980 }
981
982 // **************************************************************
983 // INSTANCE CITABLE
984 // **************************************************************
985
986 @Override
987 public Citation.Category getCategory() {
988 return Citation.Category.FRAMEWORK;
989 }
990
991 @Override
992 public String getDescription() {
993 return "Using BEAGLE likelihood calculation library";
994 }
995
996 @Override
997 public List<Citation> getCitations() {
998 return Collections.singletonList(CommonCitations.AYRES_2012_BEAGLE);
999 }
1000
1001 // **************************************************************
1002 // INSTANCE VARIABLES
1003 // **************************************************************
1004
1005 private final int nodeCount;
1006 private final int tipCount;
1007 private final int internalNodeCount;
1008
1009 private final int[] branchUpdateIndices;
1010 private final double[] branchLengths;
1011
1012 private int[] scaleBufferIndices;
1013 private int[] storedScaleBufferIndices;
1014
1015 private final int[] operations;
1016
1017 private boolean flip = true;
1018 private final BufferIndexHelper partialBufferHelper;
1019 private final BufferIndexHelper scaleBufferHelper;
1020
1021 private PartialsRescalingScheme rescalingScheme;
1022 private int rescalingFrequency = RESCALE_FREQUENCY;
1023 private boolean delayRescalingUntilUnderflow = true;
1024
1025 private boolean useScaleFactors = false;
1026 private boolean useAutoScaling = false;
1027
1028 private boolean recomputeScaleFactors = false;
1029 private boolean everUnderflowed = false;
1030 private int rescalingCount = 0;
1031 private int rescalingCountInner = 0;
1032
1033 private int threadCount = 1;
1034 private long instanceFlags;
1035
1036 private boolean firstRescaleAttempt = false;
1037 private int rescalingMessageCount = 0;
1038
1039 //integer to keep track of setting recomputeScaleFactors correctly after an underflow
1040 private int underflowHandling = 0;
1041
1042 /**
1043 * the patternList
1044 */
1045 private final PatternList patternList;
1046
1047 /**
1048 * the data type
1049 */
1050 private final DataType dataType;
1051
1052 /**
1053 * the pattern weights
1054 */
1055 private final double[] patternWeights;
1056
1057 /**
1058 * the number of patterns
1059 */
1060 private final int patternCount;
1061
1062 /**
1063 * the number of states in the data
1064 */
1065 private final int stateCount;
1066
1067 /**
1068 * the branch-site model for these sites
1069 */
1070 private final BranchModel branchModel;
1071
1072 /**
1073 * A delegate to handle substitution models on branches
1074 */
1075 private final EvolutionaryProcessDelegate evolutionaryProcessDelegate;
1076
1077 /**
1078 * the site model for these sites
1079 */
1080 private final SiteRateModel siteRateModel;
1081
1082 /**
1083 * the pattern likelihoods
1084 */
1085 private double[] patternLogLikelihoods = null;
1086
1087 /**
1088 * the number of rate categories
1089 */
1090 private final int categoryCount;
1091
1092 /**
1093 * an array used to transfer tip partials
1094 */
1095 private double[] tipPartials;
1096
1097 /**
1098 * an array used to transfer tip states
1099 */
1100 private int[] tipStates;
1101
1102 /**
1103 * the BEAGLE library instance
1104 */
1105 private final Beagle beagle;
1106
1107 /**
1108 * Flag to specify that the substitution model has changed
1109 */
1110 private boolean updateSubstitutionModel;
1111
1112 /**
1113 * Flag to specify that the site model has changed
1114 */
1115 private boolean updateSiteModel;
1116
1117 /**
1118 * Flag to take into account the first likelihood evaluation when initiating the MCMC chain
1119 */
1120 private boolean initialEvaluation = true;
1121
1122 }