Debian Codegraph @

src/dr/evomodel/treedatalikelihood/MultiPartitionDataLikelihoodDelegate.java

raw symbols SCIP
1 /*
2 * MultiPartitionDataLikelihoodDelegate.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 * MultiPartitionDataLikelihoodDelegate
30 *
31 * A DataLikelihoodDelegate that uses BEAGLE 3 to allow for parallelization across multiple data partitions
32 *
33 * @author Andrew Rambaut
34 * @author Marc Suchard
35 * @author Guy Baele
36 * @version $Id$
37 */
38
39 import beagle.*;
40 import dr.evolution.alignment.PatternList;
41 import dr.evolution.datatype.DataType;
42 import dr.evolution.tree.Tree;
43 import dr.evolution.util.TaxonList;
44 import dr.evomodel.branchmodel.BranchModel;
45 import dr.evomodel.siteratemodel.SiteRateModel;
46 import dr.evomodel.treelikelihood.PartialsRescalingScheme;
47 import dr.inference.model.AbstractModel;
48 import dr.inference.model.Model;
49 import dr.inference.model.Parameter;
50 import dr.inference.model.Variable;
51 import dr.util.Citable;
52 import dr.util.Citation;
53 import dr.util.CommonCitations;
54
55 import java.util.ArrayList;
56 import java.util.Collections;
57 import java.util.List;
58 import java.util.logging.Logger;
59
60 public class MultiPartitionDataLikelihoodDelegate extends AbstractModel implements DataLikelihoodDelegate, Citable {
61
62 private static final boolean RESCALING_OFF = false; // a debugging switch
63 private static final boolean DEBUG = false;
64
65 public static boolean IS_MULTI_PARTITION_COMPATIBLE() {
66 int[] versionNumbers = BeagleInfo.getVersionNumbers();
67 return versionNumbers.length != 0 && versionNumbers[0] >= 3;
68 }
69
70 public static boolean IS_THREAD_COUNT_COMPATIBLE() {
71 int[] versionNumbers = BeagleInfo.getVersionNumbers();
72 return versionNumbers.length != 0 && versionNumbers[0] >= 3 && versionNumbers[1] >= 1;
73 }
74
75 public static boolean IS_MULTI_PARTITION_RECOMMENDED() {
76 if (!IS_MULTI_PARTITION_COMPATIBLE()) {
77 return false;
78 }
79
80 String resourceAuto = System.getProperty(RESOURCE_AUTO_PROPERTY);
81 if (resourceAuto != null && Boolean.parseBoolean(resourceAuto)) {
82 return true;
83 }
84
85 fetchBeagleSettings();
86
87 int index = resourceOrder.size() > 0 ? instanceCount % resourceOrder.size() : 0;
88
89 if (resourceOrder.size() > 0 && resourceOrder.get(index) > 0) {
90 return true;
91 }
92 if (requiredOrder.size() > 0 &&
93 ((requiredOrder.get(index) & BeagleFlag.PROCESSOR_GPU.getMask()) != 0 ||
94 (requiredOrder.get(index) & BeagleFlag.FRAMEWORK_CUDA.getMask()) != 0 ||
95 (requiredOrder.get(index) & BeagleFlag.FRAMEWORK_OPENCL.getMask()) != 0)) {
96 return true;
97 }
98 if (preferredOrder.size() > 0 &&
99 ((preferredOrder.get(index) & BeagleFlag.PROCESSOR_GPU.getMask()) != 0 ||
100 (preferredOrder.get(index) & BeagleFlag.FRAMEWORK_CUDA.getMask()) != 0 ||
101 (preferredOrder.get(index) & BeagleFlag.FRAMEWORK_OPENCL.getMask()) != 0)) {
102 return true;
103 }
104
105 return false;
106 }
107
108 // This property is a comma-delimited list of resource numbers (0 == CPU) to
109 // allocate each BEAGLE instance to. If less than the number of instances then
110 // will wrap around.
111 private static final String RESOURCE_AUTO_PROPERTY = "beagle.resource.auto";
112 private static final String RESOURCE_ORDER_PROPERTY = "beagle.resource.order";
113 private static final String PREFERRED_FLAGS_PROPERTY = "beagle.preferred.flags";
114 private static final String REQUIRED_FLAGS_PROPERTY = "beagle.required.flags";
115 private static final String SCALING_PROPERTY = "beagle.scaling";
116 private static final String RESCALE_FREQUENCY_PROPERTY = "beagle.rescale";
117 private static final String DELAY_SCALING_PROPERTY = "beagle.delay.scaling";
118 private static final String EXTRA_BUFFER_COUNT_PROPERTY = "beagle.extra.buffer.count";
119 private static final String FORCE_VECTORIZATION = "beagle.force.vectorization";
120 private static final String THREAD_COUNT = "beagle.thread.count";
121
122
123 // Which scheme to use if choice not specified (or 'default' is selected):
124 private static final PartialsRescalingScheme DEFAULT_RESCALING_SCHEME = PartialsRescalingScheme.DYNAMIC;
125
126 private static int instanceCount = 0;
127 private static List<Integer> resourceOrder = null;
128 private static List<Integer> preferredOrder = null;
129 private static List<Integer> requiredOrder = null;
130 private static List<String> scalingOrder = null;
131 private static List<Integer> extraBufferOrder = null;
132
133 private static void fetchBeagleSettings() {
134 // Attempt to get the resource order from the System Property
135 if (resourceOrder == null) {
136 resourceOrder = parseSystemPropertyIntegerArray(RESOURCE_ORDER_PROPERTY);
137 }
138 if (preferredOrder == null) {
139 preferredOrder = parseSystemPropertyIntegerArray(PREFERRED_FLAGS_PROPERTY);
140 }
141 if (requiredOrder == null) {
142 requiredOrder = parseSystemPropertyIntegerArray(REQUIRED_FLAGS_PROPERTY);
143 }
144 if (scalingOrder == null) {
145 scalingOrder = parseSystemPropertyStringArray(SCALING_PROPERTY);
146 }
147 if (extraBufferOrder == null) {
148 extraBufferOrder = parseSystemPropertyIntegerArray(EXTRA_BUFFER_COUNT_PROPERTY);
149 }
150 }
151
152
153 // Default frequency for complete recomputation of scaling factors under the 'dynamic' scheme
154 private static final int RESCALE_FREQUENCY = 100;
155 private static final int RESCALE_TIMES = 1;
156
157 /**
158 * Construct an instance using a list of PatternLists, one for each partition. The
159 * partitions will share a tree but can have different branchModels and siteRateModels
160 * The latter should either have a size of 1 (in which case they are shared across partitions)
161 * or equal to patternLists.size() where each partition has a different model.
162 *
163 * @param tree Used for configuration - shouldn't be watched for changes
164 * @param branchModels Specifies a list of branch models for each partition
165 * @param patternLists List of patternLists comprising each partition
166 * @param siteRateModels A list of siteRateModels for each partition
167 * @param useAmbiguities Whether to respect state ambiguities in data
168 */
169 public MultiPartitionDataLikelihoodDelegate(Tree tree,
170 List<PatternList> patternLists,
171 List<BranchModel> branchModels,
172 List<SiteRateModel> siteRateModels,
173 boolean useAmbiguities,
174 PartialsRescalingScheme rescalingScheme,
175 boolean delayRescalingUntilUnderflow)
176 throws DelegateTypeException {
177
178 super("MultiPartitionDataLikelihoodDelegate");
179 final Logger logger = Logger.getLogger("dr.evomodel");
180
181 setId(patternLists.get(0).getId());
182
183 this.patternLists = patternLists;
184 this.dataType = patternLists.get(0).getDataType();
185 stateCount = dataType.getStateCount();
186
187 partitionCount = patternLists.size();
188 patternCounts = new int[partitionCount];
189 int total = 0;
190 int k = 0;
191 for (PatternList patternList : patternLists) {
192 assert(patternList.getDataType().equals(this.dataType));
193 patternCounts[k] = patternList.getPatternCount();
194 total += patternCounts[k];
195 k++;
196 }
197 totalPatternCount = total;
198
199 useScaleFactors = new boolean[partitionCount];
200 recomputeScaleFactors = new boolean[partitionCount];
201 everUnderflowed = new boolean[partitionCount];
202 flip = new boolean[partitionCount];
203 for (int i = 0; i < partitionCount; i++) {
204 flip[i] = true;
205 }
206
207 updatePartition = new boolean[partitionCount];
208 partitionWasUpdated = new boolean[partitionCount];
209 updateAllPartitions = true;
210
211 cachedLogLikelihoodsByPartition = new double[partitionCount];
212 storedCachedLogLikelihoodsByPartition = new double[partitionCount];
213
214 // Branch models determine the substitution models per branch. There can be either
215 // one per partition or one shared across all partitions
216 assert(branchModels.size() == 1 || (branchModels.size() == patternLists.size()));
217
218 this.branchModels.addAll(branchModels);
219
220 // SiteRateModels determine the rates per category (for site-heterogeneity models).
221 // There can be either one per partition or one shared across all partitions
222 assert(siteRateModels.size() == 1 || (siteRateModels.size() == patternLists.size()));
223
224 this.siteRateModels.addAll(siteRateModels);
225 this.categoryCount = this.siteRateModels.get(0).getCategoryCount();
226
227 nodeCount = tree.getNodeCount();
228 tipCount = tree.getExternalNodeCount();
229 internalNodeCount = nodeCount - tipCount;
230
231 branchUpdateIndices = new int[nodeCount];
232 branchLengths = new double[nodeCount];
233 //changed initialization to account for multiple partitions
234 scaleBufferIndices = new int[partitionCount][internalNodeCount];
235 storedScaleBufferIndices = new int[partitionCount][internalNodeCount];
236
237 operations = new int[internalNodeCount * Beagle.PARTITION_OPERATION_TUPLE_SIZE * partitionCount];
238
239 rescalingCount = new int[partitionCount];
240 rescalingCountInner = new int[partitionCount];
241 firstRescaleAttempt = true;
242
243 try {
244
245 int compactPartialsCount = tipCount;
246 if (useAmbiguities) {
247 // if we are using ambiguities then we don't use tip partials
248 compactPartialsCount = 0;
249 }
250
251 partialBufferHelper = new BufferIndexHelper[partitionCount];
252 scaleBufferHelper = new BufferIndexHelper[partitionCount];
253 categoryRateBufferHelper = new BufferIndexHelper[partitionCount];
254 for (int i = 0; i < partitionCount; i++) {
255 // one partials buffer for each tip and two for each internal node (for store restore)
256 partialBufferHelper[i] = new BufferIndexHelper(nodeCount, tipCount);
257
258 // one scaling buffer for each internal node plus an extra for the accumulation, then doubled for store/restore
259 scaleBufferHelper[i] = new BufferIndexHelper(getScaleBufferCount(), 0);
260
261 categoryRateBufferHelper[i] = new BufferIndexHelper(1, 0, i);
262 }
263
264 int eigenBufferCount = 0;
265 int matrixBufferCount = 0;
266
267 // create a substitutionModelDelegate for each branchModel
268 int partitionNumber = 0;
269 for (BranchModel branchModel : this.branchModels) {
270 HomogenousSubstitutionModelDelegate substitutionModelDelegate = new HomogenousSubstitutionModelDelegate(tree, branchModel, partitionNumber);
271 evolutionaryProcessDelegates.add(substitutionModelDelegate);
272
273 eigenBufferCount += substitutionModelDelegate.getEigenBufferCount();
274 matrixBufferCount += substitutionModelDelegate.getMatrixBufferCount();
275
276 partitionNumber ++;
277 }
278
279 fetchBeagleSettings(); // in case they haven't been set already
280
281 // first set the rescaling scheme to use from the parser
282 this.rescalingScheme = rescalingScheme;
283 this.delayRescalingUntilUnderflow = delayRescalingUntilUnderflow;
284
285 int[] resourceList = null;
286 long preferenceFlags = 0;
287 long requirementFlags = 0;
288
289 if (scalingOrder.size() > 0) {
290 this.rescalingScheme = PartialsRescalingScheme.parseFromString(
291 scalingOrder.get(instanceCount % scalingOrder.size()));
292 }
293
294 if (resourceOrder.size() > 0) {
295 // added the zero on the end so that a CPU is selected if requested resource fails
296 resourceList = new int[]{resourceOrder.get(instanceCount % resourceOrder.size()), 0};
297 if (resourceList[0] > 0) {
298 preferenceFlags |= BeagleFlag.PROCESSOR_GPU.getMask(); // Add preference weight against CPU
299 }
300 }
301
302 if (preferredOrder.size() > 0) {
303 preferenceFlags = preferredOrder.get(instanceCount % preferredOrder.size());
304 }
305
306 if (requiredOrder.size() > 0) {
307 requirementFlags = requiredOrder.get(instanceCount % requiredOrder.size());
308 }
309
310 // Define default behaviour here
311 if (this.rescalingScheme == PartialsRescalingScheme.DEFAULT) {
312 //if GPU: the default is dynamic scaling in BEAST
313 if (resourceList != null && resourceList[0] > 1) {
314 this.rescalingScheme = DEFAULT_RESCALING_SCHEME;
315 } else {
316 // if CPU: just run as fast as possible
317 // this.rescalingScheme = PartialsRescalingScheme.NONE;
318 // Dynamic should run as fast as none until first underflow
319 this.rescalingScheme = DEFAULT_RESCALING_SCHEME;
320 }
321 }
322
323 // to keep behaviour of the delayed scheme (always + delay)...
324 if (this.rescalingScheme == PartialsRescalingScheme.DELAYED) {
325 this.delayRescalingUntilUnderflow = true;
326 this.rescalingScheme = PartialsRescalingScheme.ALWAYS;
327 }
328
329 if (this.rescalingScheme == PartialsRescalingScheme.AUTO) {
330 // auto scaling not supported for multi-partition BEAGLE3 instances
331 preferenceFlags |= BeagleFlag.SCALING_DYNAMIC.getMask();
332 } else {
333 // preferenceFlags |= BeagleFlag.SCALING_MANUAL.getMask();
334 }
335
336 String r = System.getProperty(RESCALE_FREQUENCY_PROPERTY);
337 if (r != null) {
338 rescalingFrequency = Integer.parseInt(r);
339 if (rescalingFrequency < 1) {
340 rescalingFrequency = RESCALE_FREQUENCY;
341 }
342 }
343
344 String d = System.getProperty(DELAY_SCALING_PROPERTY);
345 if (d != null) {
346 this.delayRescalingUntilUnderflow = Boolean.parseBoolean(d);
347 }
348
349 // I don't think this performance stuff should be here. Perhaps have an intelligent automatic
350 // load balancer further up the chain.
351 // if (preferenceFlags == 0 && resourceList == null) { // else determine dataset characteristics
352 // if (stateCount == 4 && patternList.getPatternCount() < 10000) // TODO determine good cut-off
353 // preferenceFlags |= BeagleFlag.PROCESSOR_CPU.getMask();
354 // }
355
356 boolean forceVectorization = false;
357 String vectorizationString = System.getProperty(FORCE_VECTORIZATION);
358 if (vectorizationString != null) {
359 forceVectorization = true;
360 }
361
362 String tc = System.getProperty(THREAD_COUNT);
363 if (tc != null) {
364 threadCount = Integer.parseInt(tc);
365 if (threadCount < 2) {
366 threadCount = 1;
367 }
368 }
369
370
371 if (BeagleFlag.VECTOR_SSE.isSet(preferenceFlags) && (stateCount != 4)
372 && !forceVectorization
373 ) {
374 // @todo SSE doesn't seem to work for larger state spaces so for now we override the
375 // SSE option.
376 preferenceFlags &= ~BeagleFlag.VECTOR_SSE.getMask();
377 preferenceFlags |= BeagleFlag.VECTOR_NONE.getMask();
378
379 if (stateCount > 4 && this.rescalingScheme == PartialsRescalingScheme.DYNAMIC) {
380 this.rescalingScheme = PartialsRescalingScheme.DELAYED;
381 }
382 }
383
384 if (!BeagleFlag.PRECISION_SINGLE.isSet(preferenceFlags)) {
385 // if single precision not explicitly set then prefer double
386 preferenceFlags |= BeagleFlag.PRECISION_DOUBLE.getMask();
387 }
388
389 if (evolutionaryProcessDelegates.get(0).canReturnComplexDiagonalization()) {
390 requirementFlags |= BeagleFlag.EIGEN_COMPLEX.getMask();
391 }
392
393 if ((resourceList == null &&
394 (BeagleFlag.PROCESSOR_GPU.isSet(preferenceFlags) ||
395 BeagleFlag.FRAMEWORK_CUDA.isSet(preferenceFlags) ||
396 BeagleFlag.FRAMEWORK_OPENCL.isSet(preferenceFlags)))
397 ||
398 (resourceList != null && resourceList[0] > 0)) {
399 // non-CPU implementations don't have SSE so remove default preference for SSE
400 // when using non-CPU preferences or prioritising non-CPU resource
401 preferenceFlags &= ~BeagleFlag.VECTOR_SSE.getMask();
402 preferenceFlags &= ~BeagleFlag.THREADING_CPP.getMask();
403 }
404
405 // start auto resource selection
406 String resourceAuto = System.getProperty(RESOURCE_AUTO_PROPERTY);
407 if (resourceAuto != null && Boolean.parseBoolean(resourceAuto)) {
408
409 long benchmarkFlags = 0;
410
411 if (this.rescalingScheme == PartialsRescalingScheme.NONE) {
412 benchmarkFlags = BeagleBenchmarkFlag.SCALING_NONE.getMask();
413 } else if (this.rescalingScheme == PartialsRescalingScheme.ALWAYS) {
414 benchmarkFlags = BeagleBenchmarkFlag.SCALING_ALWAYS.getMask();
415 } else {
416 benchmarkFlags = BeagleBenchmarkFlag.SCALING_DYNAMIC.getMask();
417 }
418
419 logger.info("\nRunning benchmarks to automatically select fastest BEAGLE resource for analysis... ");
420
421 List<BenchmarkedResourceDetails> benchmarkedResourceDetails =
422 BeagleFactory.getBenchmarkedResourceDetails(
423 tipCount,
424 compactPartialsCount,
425 stateCount,
426 totalPatternCount,
427 categoryCount,
428 resourceList,
429 preferenceFlags,
430 requirementFlags,
431 1, // eigenModelCount,
432 partitionCount,
433 0, // calculateDerivatives,
434 benchmarkFlags);
435
436
437 logger.info(" Benchmark results, from fastest to slowest:");
438
439 for (BenchmarkedResourceDetails benchmarkedResource : benchmarkedResourceDetails) {
440 logger.info(benchmarkedResource.toString());
441 }
442
443 long benchedFlags = benchmarkedResourceDetails.get(0).getBenchedFlags();
444 if ((benchedFlags & BeagleFlag.FRAMEWORK_CPU.getMask()) != 0) {
445 throw new DelegateTypeException();
446 }
447
448 resourceList = new int[]{benchmarkedResourceDetails.get(0).getResourceNumber()};
449 }
450 // end auto resource selection
451
452 //TODO: check getBufferCount() calls with Daniel
453 //TODO: should we multiple getBufferCount() by the number of partitions?
454 beagle = BeagleFactory.loadBeagleInstance(
455 tipCount,
456 partialBufferHelper[0].getBufferCount(),
457 compactPartialsCount,
458 stateCount,
459 totalPatternCount,
460 eigenBufferCount,
461 matrixBufferCount,
462 categoryCount,
463 scaleBufferHelper[0].getBufferCount(), // Always allocate; they may become necessary
464 resourceList,
465 preferenceFlags,
466 requirementFlags
467 );
468
469 InstanceDetails instanceDetails = beagle.getDetails();
470 ResourceDetails resourceDetails = null;
471
472 long instanceFlags = instanceDetails.getFlags();
473 if ((instanceFlags & BeagleFlag.FRAMEWORK_CPU.getMask()) != 0) {
474 throw new DelegateTypeException();
475 }
476
477 logger.info("\nUsing Multi-Partition Data Likelihood Delegate with BEAGLE 3 multi-partition extensions");
478
479 for (BranchModel branchModel : this.branchModels) {
480 addModel(branchModel);
481 }
482
483 for (SiteRateModel siteRateModel : this.siteRateModels) {
484 assert(siteRateModel.getCategoryCount() == categoryCount);
485 addModel(siteRateModel);
486 }
487
488 if (instanceDetails != null) {
489 resourceDetails = BeagleFactory.getResourceDetails(instanceDetails.getResourceNumber());
490 if (resourceDetails != null) {
491 StringBuilder sb = new StringBuilder(" Using BEAGLE resource ");
492 sb.append(resourceDetails.getNumber()).append(": ");
493 sb.append(resourceDetails.getName()).append("\n");
494 if (resourceDetails.getDescription() != null) {
495 String[] description = resourceDetails.getDescription().split("\\|");
496 for (String desc : description) {
497 if (desc.trim().length() > 0) {
498 sb.append(" ").append(desc.trim()).append("\n");
499 }
500 }
501 }
502 sb.append(" with instance flags: ").append(instanceDetails.toString());
503 logger.info(sb.toString());
504 } else {
505 logger.info(" Error retrieving BEAGLE resource for instance: " + instanceDetails.toString());
506 }
507 } else {
508 logger.info(" No external BEAGLE resources available, or resource list/requirements not met, using Java implementation");
509 }
510
511 if (IS_THREAD_COUNT_COMPATIBLE() && threadCount > 1) {
512 beagle.setCPUThreadCount(threadCount);
513 }
514
515 patternPartitions = new int[totalPatternCount];
516 patternWeights = new double[totalPatternCount];
517
518 int j = 0;
519 k = 0;
520 for (PatternList patternList : patternLists) {
521 double[] pw = patternList.getPatternWeights();
522 for (int i = 0; i < patternList.getPatternCount(); i++) {
523 patternPartitions[k] = j;
524 patternWeights[k] = pw[i];
525 k++;
526 }
527 j++;
528 }
529
530 logger.info(" " + (useAmbiguities ? "Using" : "Ignoring") + " ambiguities in tree likelihood.");
531 String patternCountString = "" + patternLists.get(0).getPatternCount();
532 for (int i = 1; i < patternLists.size(); i++) {
533 patternCountString += ", " + patternLists.get(i).getPatternCount();
534 }
535 logger.info(" With " + patternLists.size() + " partitions comprising " + patternCountString + " unique site patterns");
536
537 // @todo - should check that each patternList spans the same set of taxa
538 for (int i = 0; i < tipCount; i++) {
539 String id = tree.getTaxonId(i);
540 if (useAmbiguities) {
541 setPartials(beagle, patternLists, id, i);
542 } else {
543 setStates(beagle, patternLists, id, i);
544 }
545 }
546
547 beagle.setPatternWeights(patternWeights);
548 beagle.setPatternPartitions(partitionCount, patternPartitions);
549
550 String rescaleMessage = " Using rescaling scheme : " + this.rescalingScheme.getText();
551 if (this.rescalingScheme == PartialsRescalingScheme.AUTO) {
552 // auto scaling in BEAGLE3 is not supported
553 this.rescalingScheme = PartialsRescalingScheme.DYNAMIC;
554 rescaleMessage = " Auto rescaling not supported in BEAGLE v3, using : " + this.rescalingScheme.getText();
555 }
556 boolean parenthesis = false;
557 if (this.rescalingScheme == PartialsRescalingScheme.DYNAMIC) {
558 rescaleMessage += " (rescaling every " + rescalingFrequency + " evaluations";
559 parenthesis = true;
560 }
561 if (this.delayRescalingUntilUnderflow) {
562 rescaleMessage += (parenthesis ? ", " : "(") + "delay rescaling until first overflow";
563 parenthesis = true;
564 }
565 rescaleMessage += (parenthesis ? ")" : "");
566 logger.info(rescaleMessage);
567
568 if (this.rescalingScheme == PartialsRescalingScheme.DYNAMIC) {
569 for (int i = 0; i < partitionCount; i++) {
570 everUnderflowed[i] = false; // If false, BEAST does not rescale until first under-/over-flow.
571 }
572 }
573
574 updateSubstitutionModels = new boolean[branchModels.size()];
575 updateSubstitutionModels();
576
577 updateSiteRateModels = new boolean[siteRateModels.size()];
578 updateSiteRateModels();
579
580 } catch (TaxonList.MissingTaxonException mte) {
581 throw new RuntimeException(mte.toString());
582 }
583
584 instanceCount ++;
585 }
586
587 @Override
588 public String getReport() {
589 return null;
590 }
591
592 @Override
593 public TreeTraversal.TraversalType getOptimalTraversalType() {
594 return TreeTraversal.TraversalType.REVERSE_LEVEL_ORDER;
595 }
596
597 public List<PatternList> getPatternLists() {
598 return this.patternLists;
599 }
600
601 @Override
602 public int getTraitCount() {
603 return 1;
604 }
605
606 @Override
607 public int getTraitDim() {
608 return totalPatternCount;
609 }
610
611 @Override
612 public RateRescalingScheme getRateRescalingScheme() {
613 return RateRescalingScheme.NONE;
614 }
615
616 private void updateSubstitutionModels(boolean... state) {
617 for (int i = 0; i < updateSubstitutionModels.length; i++) {
618 updateSubstitutionModels[i] = (state.length < 1 || state[0]);
619 }
620 }
621
622 private void updateSubstitutionModel(BranchModel branchModel) {
623 for (int i = 0; i < branchModels.size(); i++) {
624 if (branchModels.get(i) == branchModel) {
625 updateSubstitutionModels[i] = true;
626 }
627 }
628 }
629
630 private void updateSiteRateModels(boolean... state) {
631 for (int i = 0; i < updateSiteRateModels.length; i++) {
632 updateSiteRateModels[i] = (state.length < 1 || state[0]);
633 }
634 }
635
636 private void updateSiteRateModel(SiteRateModel siteRateModel) {
637 for (int i = 0; i < siteRateModels.size(); i++) {
638 if (siteRateModels.get(i) == siteRateModel) {
639 updateSiteRateModels[i] = true;
640 }
641 }
642 }
643
644
645 private static List<Integer> parseSystemPropertyIntegerArray(String propertyName) {
646 List<Integer> order = new ArrayList<Integer>();
647 String r = System.getProperty(propertyName);
648 if (r != null) {
649 String[] parts = r.split(",");
650 for (String part : parts) {
651 try {
652 int n = Integer.parseInt(part.trim());
653 order.add(n);
654 } catch (NumberFormatException nfe) {
655 System.err.println("Invalid entry '" + part + "' in " + propertyName);
656 }
657 }
658 }
659 return order;
660 }
661
662 private static List<String> parseSystemPropertyStringArray(String propertyName) {
663
664 List<String> order = new ArrayList<String>();
665
666 String r = System.getProperty(propertyName);
667 if (r != null) {
668 String[] parts = r.split(",");
669 for (String part : parts) {
670 try {
671 String s = part.trim();
672 order.add(s);
673 } catch (NumberFormatException nfe) {
674 System.err.println("Invalid entry '" + part + "' in " + propertyName);
675 }
676 }
677 }
678 return order;
679 }
680
681 private int getScaleBufferCount() {
682 return internalNodeCount + 1;
683 }
684
685 /**
686 * Sets the partials from a sequence in an alignment.
687 *
688 * @param beagle beagle
689 * @param patternLists patternLists
690 * @param taxonId taxonId
691 * @param nodeIndex nodeIndex
692 */
693 private final void setPartials(Beagle beagle,
694 List<PatternList> patternLists,
695 String taxonId,
696 int nodeIndex) throws TaxonList.MissingTaxonException {
697
698 double[] partials = new double[totalPatternCount * stateCount * categoryCount];
699 int v = 0;
700 for (PatternList patternList : patternLists) {
701 int sequenceIndex = patternList.getTaxonIndex(taxonId);
702
703 if (sequenceIndex == -1) {
704 throw new TaxonList.MissingTaxonException("Taxon, " + taxonId +
705 ", not found in patternList, " + patternList.getId());
706 }
707
708 boolean[] stateSet;
709
710 for (int i = 0; i < patternList.getPatternCount(); i++) {
711
712 int state = patternList.getPatternState(sequenceIndex, i);
713 stateSet = dataType.getStateSet(state);
714
715 for (int j = 0; j < stateCount; j++) {
716 if (stateSet[j]) {
717 partials[v] = 1.0;
718 } else {
719 partials[v] = 0.0;
720 }
721 v++;
722 }
723 }
724 }
725
726 // if there is more than one category then replicate the partials for each
727 int n = totalPatternCount * stateCount;
728 int k = n;
729 for (int i = 1; i < categoryCount; i++) {
730 System.arraycopy(partials, 0, partials, k, n);
731 k += n;
732 }
733
734 beagle.setPartials(nodeIndex, partials);
735 }
736
737 /**
738 * Sets the partials from a sequence in an alignment.
739 *
740 * @param beagle beagle
741 * @param patternLists patternLists
742 * @param taxonId taxonId
743 * @param nodeIndex nodeIndex
744 */
745 private final void setStates(Beagle beagle,
746 List<PatternList> patternLists,
747 String taxonId,
748 int nodeIndex) throws TaxonList.MissingTaxonException {
749
750 int[] states = new int[totalPatternCount];
751
752 int v = 0;
753 for (PatternList patternList : patternLists) {
754 int sequenceIndex = patternList.getTaxonIndex(taxonId);
755
756 if (sequenceIndex == -1) {
757 throw new TaxonList.MissingTaxonException("Taxon, " + taxonId +
758 ", not found in patternList, " + patternList.getId());
759 }
760
761 for (int i = 0; i < patternList.getPatternCount(); i++) {
762 states[v] = patternList.getPatternState(sequenceIndex, i);
763 v++;
764 }
765 }
766
767 beagle.setTipStates(nodeIndex, states);
768 }
769
770 /**
771 * Calculate the log likelihood of the current state.
772 *
773 * @return the log likelihood.
774 */
775 @Override
776 public double calculateLikelihood(List<BranchOperation> branchOperations, List<NodeOperation> nodeOperations, int rootNodeNumber) throws LikelihoodException {
777
778 boolean throwLikelihoodRescalingException = false;
779 if (!initialEvaluation) {
780 for (int i = 0; i < partitionCount; i++) {
781 if (!this.delayRescalingUntilUnderflow || everUnderflowed[i]) {
782 if (this.rescalingScheme == PartialsRescalingScheme.ALWAYS || this.rescalingScheme == PartialsRescalingScheme.DELAYED) {
783 useScaleFactors[i] = true;
784 recomputeScaleFactors[i] = true;
785 } else if (this.rescalingScheme == PartialsRescalingScheme.DYNAMIC) {
786 useScaleFactors[i] = true;
787
788 if (DEBUG) {
789 System.out.println("rescalingCount["+i+"] = " + rescalingCount[i]);
790 }
791
792 if (rescalingCount[i] > rescalingFrequency) {
793 if (DEBUG) {
794 System.out.println("rescalingCount > rescalingFrequency");
795 }
796 rescalingCount[i] = 0;
797 rescalingCountInner[i] = 0;
798 }
799
800 if (DEBUG) {
801 System.out.println("rescalingCountInner = " + rescalingCountInner[i]);
802 }
803
804 if (rescalingCountInner[i] < RESCALE_TIMES) {
805 if (DEBUG) {
806 System.out.println("rescalingCountInner < RESCALE_TIMES");
807 }
808
809 recomputeScaleFactors[i] = true;
810 updatePartition[i] = true;
811
812 rescalingCountInner[i]++;
813
814 throwLikelihoodRescalingException = true;
815 }
816 }
817 }
818 }
819
820 if (throwLikelihoodRescalingException) {
821 throw new LikelihoodRescalingException();
822 }
823 }
824
825 if (RESCALING_OFF) { // a debugging switch
826 for (int i = 0; i < partitionCount; i++) {
827 useScaleFactors[i] = false;
828 recomputeScaleFactors[i] = false;
829 }
830 }
831
832 int k = 0;
833 for (EvolutionaryProcessDelegate evolutionaryProcessDelegate : evolutionaryProcessDelegates) {
834 if (updateSubstitutionModels[k]) {
835 // TODO: More efficient to update only the substitution model that changed, instead of all
836 // TODO: flip currently assumes 1 substitution model per partition
837 evolutionaryProcessDelegate.updateSubstitutionModels(beagle, flip[k]);
838 updatePartition[k] = true;
839 if (DEBUG) {
840 System.out.println("updateSubstitutionModels, updatePartition["+k+"] = " + updatePartition[k]);
841 }
842 updateAllPartitions = false;
843 // we are currently assuming a no-category model...
844 }
845 k++;
846 }
847
848 k = 0;
849 for (SiteRateModel siteRateModel : siteRateModels) {
850 if (updateSiteRateModels[k]) {
851 double[] categoryRates = siteRateModel.getCategoryRates();
852 if (categoryRates == null) {
853 // If this returns null then there was a numerical error calculating the category rates
854 // (probably a very small alpha) so reject the move.
855
856 // mark model updates as completed before returning
857 updateSubstitutionModels(false);
858 updateSiteRateModels(false);
859
860 return Double.NEGATIVE_INFINITY;
861 }
862
863 if (flip[k]) {
864 categoryRateBufferHelper[k].flipOffset(0);
865 }
866
867 beagle.setCategoryRatesWithIndex(categoryRateBufferHelper[k].getOffsetIndex(0), categoryRates);
868 updatePartition[k] = true;
869 if (DEBUG) {
870 System.out.println("updateSiteRateModels, updatePartition["+k+"] = " + updatePartition[k]);
871 }
872 updateAllPartitions = false;
873 }
874 k++;
875 }
876
877 int branchUpdateCount = 0;
878 for (BranchOperation op : branchOperations) {
879 branchUpdateIndices[branchUpdateCount] = op.getBranchNumber();
880 branchLengths[branchUpdateCount] = op.getBranchLength();
881 branchUpdateCount++;
882 }
883
884 if (branchUpdateCount > 0) {
885 // TODO below only applies to homogenous substitution models
886
887 int [] eigenDecompositionIndices = new int [branchUpdateCount * partitionCount];
888 int [] categoryRateIndices = new int [branchUpdateCount * partitionCount];
889 int [] probabilityIndices = new int [branchUpdateCount * partitionCount];
890 double[] edgeLengths = new double[branchUpdateCount * partitionCount];
891
892 int op = 0;
893 int partition = 0;
894 for (EvolutionaryProcessDelegate evolutionaryProcessDelegate : evolutionaryProcessDelegates) {
895 if (updatePartition[partition] || updateAllPartitions) {
896 if (flip[partition]) {
897 evolutionaryProcessDelegate.flipTransitionMatrices(branchUpdateIndices,
898 branchUpdateCount);
899 }
900
901 for (int i = 0; i < branchUpdateCount; i++) {
902 eigenDecompositionIndices[op] = evolutionaryProcessDelegate.getEigenIndex(0);
903 categoryRateIndices[op] = categoryRateBufferHelper[partition].getOffsetIndex(0);
904 probabilityIndices[op] = evolutionaryProcessDelegate.getMatrixIndex(branchUpdateIndices[i]);
905 edgeLengths[op] = branchLengths[i];
906 op++;
907 }
908 }
909 partition++;
910 }
911
912 beagle.updateTransitionMatricesWithMultipleModels(
913 eigenDecompositionIndices,
914 categoryRateIndices,
915 probabilityIndices,
916 null, // firstDerivativeIndices
917 null, // secondDerivativeIndices
918 edgeLengths,
919 op);
920 }
921
922 for (int i = 0; i < partitionCount; i++) {
923 if (updatePartition[i] || updateAllPartitions) {
924
925 if (DEBUG) {
926 System.out.println("updatePartition["+i+"] = " + updatePartition[i] + ", updateAllPartitions = " + updateAllPartitions);
927 }
928
929 if (flip[i]) {
930 // Flip all the buffers to be written to first...
931
932 for (NodeOperation op : nodeOperations) {
933 partialBufferHelper[i].flipOffset(op.getNodeNumber());
934 }
935 }
936 }
937 }
938
939
940 int operationCount = 0;
941 k = 0;
942 for (NodeOperation op : nodeOperations) {
943 int nodeNum = op.getNodeNumber();
944
945 int[] writeScale = new int[partitionCount];
946 int[] readScale = new int[partitionCount];
947
948 for (int i = 0; i < partitionCount; i++) {
949 if (updatePartition[i] || updateAllPartitions) {
950 if (useScaleFactors[i]) {
951 // get the index of this scaling buffer
952 int n = nodeNum - tipCount;
953
954 if (recomputeScaleFactors[i]) {
955 // flip the indicator: can take either n or (internalNodeCount + 1) - n
956 scaleBufferHelper[i].flipOffset(n);
957
958 // store the index
959 scaleBufferIndices[i][n] = scaleBufferHelper[i].getOffsetIndex(n);
960
961 writeScale[i] = scaleBufferIndices[i][n]; // Write new scaleFactor
962 readScale[i] = Beagle.NONE;
963
964 } else {
965 writeScale[i] = Beagle.NONE;
966 readScale[i] = scaleBufferIndices[i][n]; // Read existing scaleFactor
967 }
968
969 } else {
970
971 writeScale[i] = Beagle.NONE; // Not using scaleFactors
972 readScale[i] = Beagle.NONE;
973 }
974 }
975 }
976
977 //Example 1: 1 partition with 1 evolutionary model & -beagle_instances 3
978 //partition 0 -> model 0
979 //partition 1 -> model 0
980 //partition 2 -> model 0
981
982 //Example 2: 3 partitions with 3 evolutionary models & -beagle_instances 2
983 //partitions 0 & 1 -> model 0
984 //partitions 2 & 3 -> model 1
985 //partitions 4 & 5 -> model 2
986
987 int mapPartition = partitionCount / evolutionaryProcessDelegates.size();
988
989 for (int i = 0; i < partitionCount; i++) {
990 if (updatePartition[i] || updateAllPartitions) {
991
992 EvolutionaryProcessDelegate evolutionaryProcessDelegate = evolutionaryProcessDelegates.get(i / (mapPartition));
993 /*if (evolutionaryProcessDelegates.size() == partitionCount) {
994 evolutionaryProcessDelegate = evolutionaryProcessDelegates.get(i);
995 } else {
996 evolutionaryProcessDelegate = evolutionaryProcessDelegates.get(0);
997 }*/
998
999 operations[k] = partialBufferHelper[i].getOffsetIndex(nodeNum);
1000 operations[k + 1] = writeScale[i];
1001 operations[k + 2] = readScale[i];
1002 operations[k + 3] = partialBufferHelper[i].getOffsetIndex(op.getLeftChild()); // source node 1
1003 operations[k + 4] = evolutionaryProcessDelegate.getMatrixIndex(op.getLeftChild()); // source matrix 1
1004 operations[k + 5] = partialBufferHelper[i].getOffsetIndex(op.getRightChild()); // source node 2
1005 operations[k + 6] = evolutionaryProcessDelegate.getMatrixIndex(op.getRightChild()); // source matrix 2
1006 operations[k + 7] = i;
1007 //TODO: we don't know the cumulateScaleBufferIndex here yet (see below)
1008 operations[k + 8] = Beagle.NONE;
1009
1010 if (DEBUG) {
1011 if (k == 0 || (k == Beagle.PARTITION_OPERATION_TUPLE_SIZE)) {
1012 System.out.println("write = " + writeScale[i] + "; read = " + readScale[i] + "; parent = " + operations[k] + ", k = " + k + ", i = " + i);
1013 }
1014
1015 }
1016
1017 k += Beagle.PARTITION_OPERATION_TUPLE_SIZE;
1018 operationCount++;
1019 }
1020
1021 }
1022 }
1023
1024
1025 beagle.updatePartialsByPartition(operations, operationCount);
1026
1027 //double[] rootPartials = new double[totalPatternCount * stateCount];
1028 //beagle.getPartials(rootIndex, 0, rootPartials);
1029
1030 int[] cumulativeScaleIndices = new int[partitionCount];
1031 for (int i = 0; i < partitionCount; i++) {
1032 cumulativeScaleIndices[i] = Beagle.NONE;
1033 if (useScaleFactors[i]) {
1034 if (recomputeScaleFactors[i] && (updatePartition[i] || updateAllPartitions)) {
1035 scaleBufferHelper[i].flipOffset(internalNodeCount);
1036 cumulativeScaleIndices[i] = scaleBufferHelper[i].getOffsetIndex(internalNodeCount);
1037 //TODO: check with Daniel if calling these methods using an iteration can be done more efficiently
1038 beagle.resetScaleFactorsByPartition(cumulativeScaleIndices[i], i);
1039 beagle.accumulateScaleFactorsByPartition(scaleBufferIndices[i], internalNodeCount, cumulativeScaleIndices[i], i);
1040 } else {
1041 cumulativeScaleIndices[i] = scaleBufferHelper[i].getOffsetIndex(internalNodeCount);
1042 }
1043 }
1044 }
1045
1046 // double[] scaleFactors = new double[totalPatternCount];
1047 // beagle.getLogScaleFactors(cumulateScaleBufferIndex, scaleFactors);
1048
1049 // these could be set only when they change but store/restore would need to be considered
1050 for (int i = 0; i < siteRateModels.size(); i++) {
1051 double[] categoryWeights = this.siteRateModels.get(i).getCategoryProportions();
1052 beagle.setCategoryWeights(i, categoryWeights);
1053
1054 // This should probably explicitly be the state frequencies for the root node...
1055 double[] frequencies = evolutionaryProcessDelegates.get(i).getRootStateFrequencies();
1056 beagle.setStateFrequencies(i, frequencies);
1057 }
1058
1059
1060 if (DEBUG) {
1061 for (int i = 0; i < partitionCount; i++) {
1062 System.out.println("useScaleFactors=" + useScaleFactors[i] + " recomputeScaleFactors=" + recomputeScaleFactors[i] + " (partition: " + i + ")");
1063 }
1064 }
1065
1066 /*System.out.println("partitionCount = " + partitionCount);
1067 for (int i = 0; i < partitionCount; i++) {
1068 System.out.println("partitionIndices[" + i + "] = " + partitionIndices[i]);
1069 }*/
1070
1071 int[] partitionIndices = new int[partitionCount];
1072 int[] rootIndices = new int[partitionCount];
1073 int[] categoryWeightsIndices = new int[partitionCount];
1074 int[] stateFrequenciesIndices = new int[partitionCount];
1075 double[] sumLogLikelihoods = new double[1];
1076 double[] sumLogLikelihoodsByPartition = new double[partitionCount];
1077
1078 // create a list of partitions that have been updated
1079 int updatedPartitionCount = 0;
1080 for (int i = 0; i < partitionCount; i++) {
1081 if (updatePartition[i] || updateAllPartitions) {
1082 partitionIndices[updatedPartitionCount] = i;
1083
1084 rootIndices [updatedPartitionCount] = partialBufferHelper[i].getOffsetIndex(rootNodeNumber);
1085 categoryWeightsIndices [updatedPartitionCount] = i % siteRateModels.size();
1086 stateFrequenciesIndices[updatedPartitionCount] = i % siteRateModels.size();
1087 cumulativeScaleIndices [updatedPartitionCount] = cumulativeScaleIndices[i];
1088
1089 updatedPartitionCount++;
1090 }
1091 }
1092
1093
1094 //TODO: check these arguments with Daniel
1095 //TODO: partitionIndices needs to be set according to which partitions need updating?
1096 beagle.calculateRootLogLikelihoodsByPartition(
1097 rootIndices,
1098 categoryWeightsIndices,
1099 stateFrequenciesIndices,
1100 cumulativeScaleIndices,
1101 partitionIndices,
1102 updatedPartitionCount,
1103 1,
1104 sumLogLikelihoodsByPartition,
1105 sumLogLikelihoods);
1106
1107 /*System.out.println();
1108 for (int i = 0; i < partitionCount; i++) {
1109 System.out.println("partition " + i + " lnL = " + sumLogLikelihoodsByPartition[i]);
1110 }*/
1111
1112 // write updated partition likelihoods to the cached array
1113 for (int i = 0; i < updatedPartitionCount; i++) {
1114 cachedLogLikelihoodsByPartition[partitionIndices[i]] = sumLogLikelihoodsByPartition[i];
1115
1116 // clear the global flags
1117 updatePartition[partitionIndices[i]] = false;
1118 recomputeScaleFactors[partitionIndices[i]] = false;
1119
1120 partitionWasUpdated[partitionIndices[i]] = true;
1121 }
1122
1123 double tmpLogL = sumLogLikelihoods[0];
1124
1125 if (DEBUG) {
1126 for (int i = 0; i < partitionCount; i++) {
1127 System.out.println("partition " + i + ": " + cachedLogLikelihoodsByPartition[i] +
1128 (partitionWasUpdated[i] ? " [updated]" : ""));
1129 }
1130 }
1131
1132 // If these are needed...
1133 // if (patternLogLikelihoods == null) {
1134 // patternLogLikelihoods = new double[totalPatternCount];
1135 // }
1136 // beagle.getSiteLogLikelihoods(patternLogLikelihoods);
1137
1138 updateSubstitutionModels(false);
1139 updateSiteRateModels(false);
1140 updateAllPartitions = true;
1141
1142 if (Double.isNaN(tmpLogL) || Double.isInfinite(tmpLogL)) {
1143 // one or more of the updated partitions has underflowed
1144
1145 if (DEBUG) {
1146 System.out.println("Double.isNaN(logL) || Double.isInfinite(logL)");
1147 }
1148
1149 for (int i = 0; i < updatedPartitionCount; i++) {
1150 if (Double.isNaN(sumLogLikelihoodsByPartition[i]) || Double.isInfinite(sumLogLikelihoodsByPartition[i])) {
1151 everUnderflowed[partitionIndices[i]] = true;
1152 }
1153 }
1154
1155 if (firstRescaleAttempt) {
1156 if (delayRescalingUntilUnderflow || rescalingScheme == PartialsRescalingScheme.DELAYED) {
1157 // show a message but only every 1000 rescales
1158 if (rescalingMessageCount % 1000 == 0) {
1159 if (rescalingMessageCount > 0) {
1160 Logger.getLogger("dr.evomodel").info("Underflow calculating likelihood (" + rescalingMessageCount + " messages not shown).");
1161 } else {
1162 Logger.getLogger("dr.evomodel").info("Underflow calculating likelihood. Attempting a rescaling... (" + getId() + ")");
1163 }
1164 }
1165 rescalingMessageCount += 1;
1166
1167 }
1168
1169 for (int i = 0; i < updatedPartitionCount; i++) {
1170 if (delayRescalingUntilUnderflow || rescalingScheme == PartialsRescalingScheme.DELAYED) {
1171 if (Double.isNaN(sumLogLikelihoodsByPartition[i]) || Double.isInfinite(sumLogLikelihoodsByPartition[i])) {
1172 useScaleFactors[partitionIndices[i]] = true;
1173 recomputeScaleFactors[partitionIndices[i]] = true;
1174 updatePartition[partitionIndices[i]] = true;
1175
1176 // turn off double buffer flipping so the next call overwrites the
1177 // underflowed buffers. Flip will be turned on again in storeState for
1178 // next step
1179 flip[partitionIndices[i]] = false;
1180
1181 updateAllPartitions = false;
1182 if (DEBUG) {
1183 System.out.println("Double.isNaN(logL) || Double.isInfinite(logL) (partition index: " + partitionIndices[i] + ")");
1184 }
1185 }
1186
1187 }
1188 }
1189
1190 firstRescaleAttempt = false;
1191
1192 throw new LikelihoodUnderflowException();
1193 }
1194
1195 return Double.NEGATIVE_INFINITY;
1196 } else {
1197
1198 for (int i = 0; i < updatedPartitionCount; i++) {
1199 if (partitionWasUpdated[partitionIndices[i]]) {
1200 if (!this.delayRescalingUntilUnderflow || everUnderflowed[partitionIndices[i]]) {
1201 if (this.rescalingScheme == PartialsRescalingScheme.DYNAMIC) {
1202 if (!initialEvaluation) {
1203 rescalingCount[partitionIndices[i]]++;
1204 }
1205 }
1206 }
1207 partitionWasUpdated[partitionIndices[i]] = false;
1208 }
1209
1210 //TODO: probably better to only switch back those booleans that were actually altered
1211 recomputeScaleFactors[partitionIndices[i]] = false;
1212 flip[partitionIndices[i]] = true;
1213 }
1214
1215 firstRescaleAttempt = true;
1216 initialEvaluation = false;
1217 }
1218
1219 //********************************************************************
1220 double logL = 0.0;
1221 for (double l : cachedLogLikelihoodsByPartition) {
1222 logL += l;
1223 }
1224
1225 return logL;
1226 }
1227
1228 /*public void getPartials(int number, double[] partials) {
1229 int cumulativeBufferIndex = Beagle.NONE;
1230 // No need to rescale partials
1231 beagle.getPartials(partialBufferHelper.getOffsetIndex(number), cumulativeBufferIndex, partials);
1232 }*/
1233
1234 /*private void setPartials(int number, double[] partials) {
1235 beagle.setPartials(partialBufferHelper.getOffsetIndex(number), partials);
1236 }*/
1237
1238 @Override
1239 public void makeDirty() {
1240 updateSiteRateModels();
1241 updateSubstitutionModels();
1242 }
1243
1244 @Override
1245 protected void handleModelChangedEvent(Model model, Object object, int index) {
1246 if (model instanceof SiteRateModel) {
1247 updateSiteRateModel((SiteRateModel)model);
1248 } else if (model instanceof BranchModel) {
1249 updateSubstitutionModel((BranchModel)model);
1250 }
1251 // Tell TreeDataLikelihood to update all nodes
1252 fireModelChanged();
1253 }
1254
1255 @Override
1256 protected void handleVariableChangedEvent(Variable variable, int index, Parameter.ChangeType type) {
1257
1258 }
1259
1260 /**
1261 * Stores the additional state other than model components
1262 */
1263 @Override
1264 public void storeState() {
1265 for (int i = 0; i < partitionCount; i++) {
1266 partialBufferHelper[i].storeState();
1267 categoryRateBufferHelper[i].storeState();
1268 }
1269 for (EvolutionaryProcessDelegate evolutionaryProcessDelegate : evolutionaryProcessDelegates) {
1270 evolutionaryProcessDelegate.storeState();
1271 }
1272
1273 for (int i = 0; i < partitionCount; i++) {
1274 if (useScaleFactors[i] ) { // Only store when actually used
1275 scaleBufferHelper[i].storeState();
1276 System.arraycopy(scaleBufferIndices[i], 0, storedScaleBufferIndices[i], 0, scaleBufferIndices[i].length);
1277 //storedRescalingCount = rescalingCount;
1278 }
1279
1280 // turn on double buffering flipping (may have been turned off to enable a rescale)
1281 flip[i] = true;
1282 }
1283 System.arraycopy(cachedLogLikelihoodsByPartition, 0, storedCachedLogLikelihoodsByPartition, 0, cachedLogLikelihoodsByPartition.length);
1284 }
1285
1286 /**
1287 * Restore the additional stored state
1288 */
1289 @Override
1290 public void restoreState() {
1291
1292 for (int i = 0; i < partitionCount; i++) {
1293 partialBufferHelper[i].restoreState();
1294 categoryRateBufferHelper[i].restoreState();
1295 }
1296 for (EvolutionaryProcessDelegate evolutionaryProcessDelegate : evolutionaryProcessDelegates) {
1297 evolutionaryProcessDelegate.restoreState();
1298 }
1299
1300 for (int i = 0; i < partitionCount; i++) {
1301 if (useScaleFactors[i]) {
1302 scaleBufferHelper[i].restoreState();
1303 int[] tmp = storedScaleBufferIndices[i];
1304 storedScaleBufferIndices[i] = scaleBufferIndices[i];
1305 scaleBufferIndices[i] = tmp;
1306 //rescalingCount = storedRescalingCount;
1307 }
1308 }
1309
1310 double[] tmp = cachedLogLikelihoodsByPartition;
1311 cachedLogLikelihoodsByPartition = storedCachedLogLikelihoodsByPartition;
1312 storedCachedLogLikelihoodsByPartition = tmp;
1313
1314 }
1315
1316 @Override
1317 public void setCallback(TreeDataLikelihood treeDataLikelihood) {
1318 // Callback not necessary
1319 }
1320
1321 @Override
1322 public int vectorizeNodeOperations(List<NodeOperation> nodeOperations, int[] operations) {
1323 throw new RuntimeException("Not yet implemented");
1324 }
1325
1326 @Override
1327 protected void acceptState() {
1328 }
1329
1330 // **************************************************************
1331 // INSTANCE CITABLE
1332 // **************************************************************
1333
1334 @Override
1335 public Citation.Category getCategory() {
1336 return Citation.Category.FRAMEWORK;
1337 }
1338
1339 @Override
1340 public String getDescription() {
1341 return "Using BEAGLE likelihood calculation library";
1342 }
1343
1344 @Override
1345 public List<Citation> getCitations() {
1346 return Collections.singletonList(CommonCitations.AYRES_2012_BEAGLE);
1347 }
1348
1349 // **************************************************************
1350 // INSTANCE VARIABLES
1351 // **************************************************************
1352
1353 private int nodeCount;
1354 private int tipCount;
1355 private int internalNodeCount;
1356
1357 private int[] branchUpdateIndices;
1358 private double[] branchLengths;
1359
1360 //provide per partition buffer indices
1361 private int[][] scaleBufferIndices;
1362 private int[][] storedScaleBufferIndices;
1363
1364 private int[] operations;
1365
1366 //allow flipping per partition
1367 private boolean[] flip;
1368 private BufferIndexHelper[] partialBufferHelper;
1369 private BufferIndexHelper[] scaleBufferHelper;
1370 private BufferIndexHelper[] categoryRateBufferHelper;
1371
1372 private PartialsRescalingScheme rescalingScheme;
1373 private int rescalingFrequency = RESCALE_FREQUENCY;
1374 private boolean delayRescalingUntilUnderflow = true;
1375
1376 private int threadCount = 1;
1377
1378 //allow per partition rescaling
1379 private boolean[] useScaleFactors;
1380 private boolean[] recomputeScaleFactors;
1381
1382 //keep track of underflow on a per partition basis
1383 private boolean[] everUnderflowed;
1384
1385 private int[] rescalingCount;
1386 private int[] rescalingCountInner;
1387
1388 private boolean firstRescaleAttempt;
1389 private int rescalingMessageCount = 0;
1390
1391 // keep track of which partitions need to be updated
1392 private boolean updatePartition[];
1393 private boolean updateAllPartitions;
1394 private boolean partitionWasUpdated[];
1395
1396 /**
1397 * the patternLists
1398 */
1399 private List<PatternList> patternLists;
1400
1401 private final DataType dataType;
1402
1403 private final int partitionCount;
1404
1405 /**
1406 * the pattern weights across all patterns
1407 */
1408 private final double[] patternWeights;
1409
1410 /**
1411 * The partition for each pattern
1412 */
1413 private final int[] patternPartitions;
1414
1415 /**
1416 * the number of patterns for each partition
1417 */
1418 private final int[] patternCounts;
1419
1420 /**
1421 * total number of patterns across all partitions
1422 */
1423 private final int totalPatternCount;
1424
1425 /**
1426 * the number of states in the data
1427 */
1428 private final int stateCount;
1429
1430 /**
1431 * the branch-site model for these sites
1432 */
1433 private final List<BranchModel> branchModels = new ArrayList<BranchModel>();
1434
1435 /**
1436 * A delegate to handle substitution models on branches
1437 */
1438 private final List<EvolutionaryProcessDelegate> evolutionaryProcessDelegates = new ArrayList<EvolutionaryProcessDelegate>();
1439
1440 /**
1441 * the site model for these sites
1442 */
1443 private final List<SiteRateModel> siteRateModels = new ArrayList<SiteRateModel>();
1444
1445 /**
1446 * the number of rate categories
1447 */
1448 private final int categoryCount;
1449
1450 /**
1451 * the BEAGLE library instance
1452 */
1453 private final Beagle beagle;
1454
1455 /**
1456 * Cached log likelihood for each partition
1457 */
1458 private double[] cachedLogLikelihoodsByPartition;
1459 private double[] storedCachedLogLikelihoodsByPartition;
1460
1461 /**
1462 * Flag to specify that the substitution model has changed
1463 */
1464 private final boolean[] updateSubstitutionModels;
1465
1466 /**
1467 * Flag to specify that the site model has changed
1468 */
1469 private final boolean[] updateSiteRateModels;
1470
1471 /**
1472 * Flag to take into account the first likelihood evaluation when initiating the MCMC chain
1473 */
1474 private boolean initialEvaluation = true;
1475
1476 }