Debian Codegraph @

src/dr/evomodel/treelikelihood/BeagleTreeLikelihood.java

raw symbols SCIP
1 /*
2 * BeagleTreeLikelihood.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.*;
29 import dr.evolution.datatype.HiddenDataType;
30 import dr.evolution.tree.TreeUtils;
31 import dr.evomodel.branchmodel.BranchModel;
32 import dr.evomodel.branchmodel.EpochBranchModel;
33 import dr.evomodel.branchmodel.HomogeneousBranchModel;
34 import dr.evomodel.substmodel.MarkovModulatedSubstitutionModel;
35 import dr.evomodel.tree.TreeChangedEvent;
36 import dr.evomodel.treedatalikelihood.BufferIndexHelper;
37 import dr.evomodelxml.treelikelihood.BeagleTreeLikelihoodParser;
38 import dr.evomodel.siteratemodel.GammaSiteRateModel;
39 import dr.evomodel.siteratemodel.SiteRateModel;
40 import dr.evomodel.substmodel.FrequencyModel;
41 import dr.evomodel.substmodel.nucleotide.HKY;
42 import dr.evomodel.substmodel.SubstitutionModel;
43 import dr.app.beagle.tools.BeagleSequenceSimulator;
44 import dr.app.beagle.tools.Partition;
45 import dr.evolution.alignment.Alignment;
46 import dr.evolution.alignment.AscertainedSitePatterns;
47 import dr.evolution.alignment.PatternList;
48 import dr.evolution.alignment.UncertainSiteList;
49 import dr.evolution.datatype.Nucleotides;
50 import dr.evolution.io.NewickImporter;
51 import dr.evolution.tree.NodeRef;
52 import dr.evolution.tree.Tree;
53 import dr.evolution.util.Taxon;
54 import dr.evolution.util.TaxonList;
55 import dr.evomodel.branchratemodel.BranchRateModel;
56 import dr.evomodel.branchratemodel.DefaultBranchRateModel;
57 import dr.evomodel.branchratemodel.StrictClockBranchRates;
58 import dr.evomodel.tipstatesmodel.TipStatesModel;
59 import dr.evomodel.tree.TreeModel;
60 import dr.inference.model.Model;
61 import dr.inference.model.Parameter;
62 import dr.inference.model.ThreadAwareLikelihood;
63 import dr.math.MathUtils;
64 import dr.util.Citable;
65 import dr.util.Citation;
66 import dr.util.CommonCitations;
67
68 import java.util.*;
69 import java.util.logging.Logger;
70
71 /**
72 * BeagleTreeLikelihoodModel - implements a Likelihood Function for sequences on a tree.
73 *
74 * @author Andrew Rambaut
75 * @author Alexei Drummond
76 * @author Marc Suchard
77 * @version $Id$
78 */
79
80 @SuppressWarnings("serial")
81 @Deprecated // Switching to TreeDataLikelihood
82 public class BeagleTreeLikelihood extends AbstractSinglePartitionTreeLikelihood implements ThreadAwareLikelihood, Citable {
83 public static boolean IS_THREAD_COUNT_COMPATIBLE() {
84 int[] versionNumbers = BeagleInfo.getVersionNumbers();
85 return versionNumbers.length != 0 && versionNumbers[0] >= 3 && versionNumbers[1] >= 1;
86 }
87
88 // This property is a comma-delimited list of resource numbers (0 == CPU) to
89 // allocate each BEAGLE instance to. If less than the number of instances then
90 // will wrap around.
91 private static final String RESOURCE_AUTO_PROPERTY = "beagle.resource.auto";
92 private static final String RESOURCE_ORDER_PROPERTY = "beagle.resource.order";
93 private static final String PREFERRED_FLAGS_PROPERTY = "beagle.preferred.flags";
94 private static final String REQUIRED_FLAGS_PROPERTY = "beagle.required.flags";
95 private static final String SCALING_PROPERTY = "beagle.scaling";
96 private static final String RESCALE_FREQUENCY_PROPERTY = "beagle.rescale";
97 private static final String DELAY_SCALING_PROPERTY = "beagle.delay.scaling";
98 private static final String EXTRA_BUFFER_COUNT_PROPERTY = "beagle.extra.buffer.count";
99 private static final String FORCE_VECTORIZATION = "beagle.force.vectorization";
100 private static final String THREAD_COUNT = "beagle.thread.count";
101
102 // Which scheme to use if choice not specified (or 'default' is selected):
103 private static final PartialsRescalingScheme DEFAULT_RESCALING_SCHEME = PartialsRescalingScheme.DYNAMIC;
104
105 private static int instanceCount = 0;
106 private static List<Integer> resourceOrder = null;
107 private static List<Integer> preferredOrder = null;
108 private static List<Integer> requiredOrder = null;
109 private static List<String> scalingOrder = null;
110 private static List<Integer> extraBufferOrder = null;
111
112 // Default frequency for complete recomputation of scaling factors under the 'dynamic' scheme
113 private static final int RESCALE_FREQUENCY = 100;
114 private static final int RESCALE_TIMES = 1;
115
116 private static final boolean RESCALING_OFF = false; // a debugging switch
117 private static final boolean DEBUG = false;
118
119 public BeagleTreeLikelihood(PatternList patternList,
120 TreeModel treeModel,
121 BranchModel branchModel,
122 SiteRateModel siteRateModel,
123 BranchRateModel branchRateModel,
124 TipStatesModel tipStatesModel,
125 boolean useAmbiguities,
126 PartialsRescalingScheme rescalingScheme,
127 boolean delayRescalingUntilUnderflow) {
128
129 this(patternList, treeModel, branchModel, siteRateModel, branchRateModel, tipStatesModel, useAmbiguities, rescalingScheme, delayRescalingUntilUnderflow, null);
130 }
131
132 public BeagleTreeLikelihood(PatternList patternList,
133 TreeModel treeModel,
134 BranchModel branchModel,
135 SiteRateModel siteRateModel,
136 BranchRateModel branchRateModel,
137 TipStatesModel tipStatesModel,
138 boolean useAmbiguities,
139 PartialsRescalingScheme rescalingScheme,
140 boolean delayRescalingUntilUnderflow,
141 Map<Set<String>, Parameter> partialsRestrictions) {
142
143 super(BeagleTreeLikelihoodParser.TREE_LIKELIHOOD, patternList, treeModel);
144
145 try {
146 final Logger logger = Logger.getLogger("dr.evomodel");
147
148 logger.info("\nUsing BEAGLE TreeLikelihood");
149
150 this.siteRateModel = siteRateModel;
151 addModel(this.siteRateModel);
152
153 this.branchModel = branchModel;
154 addModel(this.branchModel);
155
156 if (branchRateModel != null) {
157 this.branchRateModel = branchRateModel;
158 logger.info(" Branch rate model used: " + branchRateModel.getModelName());
159 } else {
160 this.branchRateModel = new DefaultBranchRateModel();
161 }
162 addModel(this.branchRateModel);
163
164 if (patternList instanceof UncertainSiteList ||
165 patternList.getDataType() instanceof HiddenDataType) {
166 useAmbiguities = true;
167 }
168
169 this.tipStatesModel = tipStatesModel;
170
171 this.categoryCount = this.siteRateModel.getCategoryCount();
172
173 this.tipCount = treeModel.getExternalNodeCount();
174
175 internalNodeCount = nodeCount - tipCount;
176
177 int compactPartialsCount = tipCount;
178 if (useAmbiguities) {
179 // if we are using ambiguities then we don't use tip partials
180 compactPartialsCount = 0;
181 }
182
183 // one partials buffer for each tip and two for each internal node (for store restore)
184 partialBufferHelper = new BufferIndexHelper(nodeCount, tipCount);
185
186 // one scaling buffer for each internal node plus an extra for the accumulation, then doubled for store/restore
187 scaleBufferHelper = new BufferIndexHelper(getScaleBufferCount(), 0);
188
189 // Attempt to get the resource order from the System Property
190 if (resourceOrder == null) {
191 resourceOrder = parseSystemPropertyIntegerArray(RESOURCE_ORDER_PROPERTY);
192 }
193 if (preferredOrder == null) {
194 preferredOrder = parseSystemPropertyIntegerArray(PREFERRED_FLAGS_PROPERTY);
195 }
196 if (requiredOrder == null) {
197 requiredOrder = parseSystemPropertyIntegerArray(REQUIRED_FLAGS_PROPERTY);
198 }
199 if (scalingOrder == null) {
200 scalingOrder = parseSystemPropertyStringArray(SCALING_PROPERTY);
201 }
202 if (extraBufferOrder == null) {
203 extraBufferOrder = parseSystemPropertyIntegerArray(EXTRA_BUFFER_COUNT_PROPERTY);
204 }
205
206 int extraBufferCount = -1; // default
207 if (extraBufferOrder.size() > 0) {
208 extraBufferCount = extraBufferOrder.get(instanceCount % extraBufferOrder.size());
209 }
210 substitutionModelDelegate = new SubstitutionModelDelegate(treeModel, branchModel, extraBufferCount);
211
212 // first set the rescaling scheme to use from the parser
213 this.rescalingScheme = rescalingScheme;
214 this.delayRescalingUntilUnderflow = delayRescalingUntilUnderflow;
215
216 int[] resourceList = null;
217 long preferenceFlags = 0;
218 long requirementFlags = 0;
219
220 if (scalingOrder.size() > 0) {
221 this.rescalingScheme = PartialsRescalingScheme.parseFromString(
222 scalingOrder.get(instanceCount % scalingOrder.size()));
223 }
224
225 if (resourceOrder.size() > 0) {
226 // added the zero on the end so that a CPU is selected if requested resource fails
227 resourceList = new int[]{resourceOrder.get(instanceCount % resourceOrder.size()), 0};
228 if (resourceList[0] > 0) {
229 preferenceFlags |= BeagleFlag.PROCESSOR_GPU.getMask(); // Add preference weight against CPU
230 }
231 }
232
233 if (preferredOrder.size() > 0) {
234 preferenceFlags = preferredOrder.get(instanceCount % preferredOrder.size());
235 }
236
237 if (requiredOrder.size() > 0) {
238 requirementFlags = requiredOrder.get(instanceCount % requiredOrder.size());
239 }
240
241 // Define default behaviour here
242 if (this.rescalingScheme == PartialsRescalingScheme.DEFAULT) {
243 //if GPU: the default is dynamic scaling in BEAST
244 if (resourceList != null && resourceList[0] > 1) {
245 this.rescalingScheme = DEFAULT_RESCALING_SCHEME;
246 } else { // if CPU: just run as fast as possible
247 // this.rescalingScheme = PartialsRescalingScheme.NONE;
248 // Dynamic should run as fast as none until first underflow
249 this.rescalingScheme = DEFAULT_RESCALING_SCHEME;
250 }
251 }
252
253 // to keep behaviour of the delayed scheme (always + delay)...
254 if (this.rescalingScheme == PartialsRescalingScheme.DELAYED) {
255 this.delayRescalingUntilUnderflow = true;
256 this.rescalingScheme = PartialsRescalingScheme.ALWAYS;
257 }
258
259 if (this.rescalingScheme == PartialsRescalingScheme.AUTO) {
260 preferenceFlags |= BeagleFlag.SCALING_AUTO.getMask();
261 useAutoScaling = true;
262 } else {
263 // preferenceFlags |= BeagleFlag.SCALING_MANUAL.getMask();
264 }
265
266 String r = System.getProperty(RESCALE_FREQUENCY_PROPERTY);
267 if (r != null) {
268 rescalingFrequency = Integer.parseInt(r);
269 if (rescalingFrequency < 1) {
270 rescalingFrequency = RESCALE_FREQUENCY;
271 }
272 }
273
274 String d = System.getProperty(DELAY_SCALING_PROPERTY);
275 if (d != null) {
276 this.delayRescalingUntilUnderflow = Boolean.parseBoolean(d);
277 }
278
279 // TODO Remove once issue #854 is fixed
280 for (int s = 0; s < substitutionModelDelegate.getSubstitutionModelCount(); ++s) {
281 if (substitutionModelDelegate.getSubstitutionModel(s) instanceof MarkovModulatedSubstitutionModel) {
282 this.rescalingScheme = PartialsRescalingScheme.ALWAYS;
283 this.delayRescalingUntilUnderflow = false;
284 }
285 }
286
287 if (preferenceFlags == 0 && resourceList == null) { // else determine dataset characteristics
288 if (stateCount == 4 && patternList.getPatternCount() < 10000) // TODO determine good cut-off
289 preferenceFlags |= BeagleFlag.PROCESSOR_CPU.getMask();
290 }
291
292 boolean forceVectorization = false;
293 String vectorizationString = System.getProperty(FORCE_VECTORIZATION);
294 if (vectorizationString != null) {
295 forceVectorization = true;
296 }
297
298 String tc = System.getProperty(THREAD_COUNT);
299 if (tc != null) {
300 threadCount = Integer.parseInt(tc);
301 if (threadCount < 2) {
302 threadCount = 1;
303 }
304 }
305
306 if (BeagleFlag.VECTOR_SSE.isSet(preferenceFlags) && (stateCount != 4)
307 && !forceVectorization
308 ) {
309 // @todo SSE doesn't seem to work for larger state spaces so for now we override the
310 // SSE option.
311 preferenceFlags &= ~BeagleFlag.VECTOR_SSE.getMask();
312 preferenceFlags |= BeagleFlag.VECTOR_NONE.getMask();
313
314 if (stateCount > 4 && this.rescalingScheme == PartialsRescalingScheme.DYNAMIC) {
315 this.rescalingScheme = PartialsRescalingScheme.DELAYED;
316 }
317 }
318
319 if (!BeagleFlag.PRECISION_SINGLE.isSet(preferenceFlags)) {
320 // if single precision not explicitly set then prefer double
321 preferenceFlags |= BeagleFlag.PRECISION_DOUBLE.getMask();
322 }
323
324 if (substitutionModelDelegate.canReturnComplexDiagonalization()) {
325 requirementFlags |= BeagleFlag.EIGEN_COMPLEX.getMask();
326 }
327
328 // Check for matching state counts
329 int stateCount2 = branchModel.getRootFrequencyModel().getFrequencyCount();
330 if (stateCount != stateCount2) {
331 throw new RuntimeException("Pattern state count (" + stateCount
332 + ") does not match substitution model state count (" + stateCount2 + ")");
333 }
334
335 if ((resourceList == null &&
336 (BeagleFlag.PROCESSOR_GPU.isSet(preferenceFlags) ||
337 BeagleFlag.FRAMEWORK_CUDA.isSet(preferenceFlags) ||
338 BeagleFlag.FRAMEWORK_OPENCL.isSet(preferenceFlags)))
339 ||
340 (resourceList != null && resourceList[0] > 0)) {
341 // non-CPU implementations don't have SSE so remove default preference for SSE
342 // when using non-CPU preferences or prioritising non-CPU resource
343 preferenceFlags &= ~BeagleFlag.VECTOR_SSE.getMask();
344 preferenceFlags &= ~BeagleFlag.THREADING_CPP.getMask();
345 }
346
347 // start auto resource selection
348 String resourceAuto = System.getProperty(RESOURCE_AUTO_PROPERTY);
349 if (resourceAuto != null && Boolean.parseBoolean(resourceAuto)) {
350
351 long benchmarkFlags = 0;
352
353 if (this.rescalingScheme == PartialsRescalingScheme.NONE) {
354 benchmarkFlags = BeagleBenchmarkFlag.SCALING_NONE.getMask();
355 } else if (this.rescalingScheme == PartialsRescalingScheme.ALWAYS) {
356 benchmarkFlags = BeagleBenchmarkFlag.SCALING_ALWAYS.getMask();
357 } else {
358 benchmarkFlags = BeagleBenchmarkFlag.SCALING_DYNAMIC.getMask();
359 }
360
361 logger.info("\nRunning benchmarks to automatically select fastest BEAGLE resource for analysis or partition... ");
362
363 List<BenchmarkedResourceDetails> benchmarkedResourceDetails =
364 BeagleFactory.getBenchmarkedResourceDetails(
365 tipCount,
366 compactPartialsCount,
367 stateCount,
368 patternCount,
369 categoryCount,
370 resourceList,
371 preferenceFlags,
372 requirementFlags,
373 1, // eigenModelCount,
374 1, // partitionCount,
375 0, // calculateDerivatives,
376 benchmarkFlags);
377
378
379 logger.info(" Benchmark results, from fastest to slowest:");
380
381 for (BenchmarkedResourceDetails benchmarkedResource : benchmarkedResourceDetails) {
382 logger.info(benchmarkedResource.toString());
383 }
384
385 resourceList = new int[]{benchmarkedResourceDetails.get(0).getResourceNumber()};
386 }
387 // end auto resource selection
388
389 instanceCount++;
390
391 beagle = BeagleFactory.loadBeagleInstance(
392 tipCount,
393 partialBufferHelper.getBufferCount(),
394 compactPartialsCount,
395 stateCount,
396 patternCount,
397 substitutionModelDelegate.getEigenBufferCount(),
398 substitutionModelDelegate.getMatrixBufferCount(),
399 categoryCount,
400 scaleBufferHelper.getBufferCount(), // Always allocate; they may become necessary
401 resourceList,
402 preferenceFlags,
403 requirementFlags
404 );
405
406 InstanceDetails instanceDetails = beagle.getDetails();
407 ResourceDetails resourceDetails = null;
408
409 if (instanceDetails != null) {
410 resourceDetails = BeagleFactory.getResourceDetails(instanceDetails.getResourceNumber());
411 if (resourceDetails != null) {
412 StringBuilder sb = new StringBuilder(" Using BEAGLE resource ");
413 sb.append(resourceDetails.getNumber()).append(": ");
414 sb.append(resourceDetails.getName()).append("\n");
415 if (resourceDetails.getDescription() != null) {
416 String[] description = resourceDetails.getDescription().split("\\|");
417 for (String desc : description) {
418 if (desc.trim().length() > 0) {
419 sb.append(" ").append(desc.trim()).append("\n");
420 }
421 }
422 }
423 sb.append(" with instance flags: ").append(instanceDetails.toString());
424 logger.info(sb.toString());
425 } else {
426 logger.info(" Error retrieving BEAGLE resource for instance: " + instanceDetails.toString());
427 }
428 } else {
429 logger.info(" No external BEAGLE resources available, or resource list/requirements not met, using Java implementation");
430 }
431
432 if (IS_THREAD_COUNT_COMPATIBLE() && threadCount > 1) {
433 beagle.setCPUThreadCount(threadCount);
434 }
435
436 logger.info(" " + (useAmbiguities ? "Using" : "Ignoring") + " ambiguities in tree likelihood.");
437 logger.info(" With " + patternList.getPatternCount() + " unique site patterns.");
438
439 if (tipStatesModel != null) {
440 tipStatesModel.setTree(treeModel);
441
442 if (tipStatesModel.getModelType() == TipStatesModel.Type.PARTIALS) {
443 tipPartials = new double[patternCount * stateCount];
444 } else {
445 tipStates = new int[patternCount];
446 }
447
448 addModel(tipStatesModel);
449 }
450
451 for (int i = 0; i < tipCount; i++) {
452 // Find the id of tip i in the patternList
453 String id = treeModel.getTaxonId(i);
454 int index = patternList.getTaxonIndex(id);
455
456 if (index == -1) {
457 throw new TaxonList.MissingTaxonException("Taxon, " + id + ", in tree, " + treeModel.getId() +
458 ", is not found in patternList, " + patternList.getId());
459 } else {
460 if (tipStatesModel != null) {
461 // using a tipPartials model.
462 // First set the observed states:
463 tipStatesModel.setStates(patternList, index, i, id);
464
465 if (tipStatesModel.getModelType() == TipStatesModel.Type.PARTIALS) {
466 // Then set the tip partials as determined by the model:
467 setPartials(beagle, tipStatesModel, i);
468 } else {
469 // or the tip states:
470 tipStatesModel.getTipStates(i, tipStates);
471 beagle.setTipStates(i, tipStates);
472 }
473
474 } else {
475 if (useAmbiguities) {
476 setPartials(beagle, patternList, index, i);
477 } else {
478 setStates(beagle, patternList, index, i);
479 }
480 }
481 }
482 }
483
484 if (patternList instanceof AscertainedSitePatterns) {
485 ascertainedSitePatterns = true;
486 }
487
488 this.partialsRestrictions = partialsRestrictions;
489 // hasRestrictedPartials = (partialsRestrictions != null);
490 if (hasRestrictedPartials) {
491 numRestrictedPartials = partialsRestrictions.size();
492 updateRestrictedNodePartials = true;
493 partialsMap = new Parameter[treeModel.getNodeCount()];
494 partials = new double[stateCount * patternCount * categoryCount];
495 } else {
496 numRestrictedPartials = 0;
497 updateRestrictedNodePartials = false;
498 }
499
500 beagle.setPatternWeights(patternWeights);
501
502 String rescaleMessage = " Using rescaling scheme : " + this.rescalingScheme.getText();
503 if (this.rescalingScheme == PartialsRescalingScheme.AUTO &&
504 resourceDetails != null &&
505 (resourceDetails.getFlags() & BeagleFlag.SCALING_AUTO.getMask()) == 0) {
506 // If auto scaling in BEAGLE is not supported then do it here
507 this.rescalingScheme = PartialsRescalingScheme.DYNAMIC;
508 rescaleMessage = " Auto rescaling not supported in BEAGLE, using : " + this.rescalingScheme.getText();
509 }
510 boolean parenthesis = false;
511 if (this.rescalingScheme == PartialsRescalingScheme.DYNAMIC) {
512 rescaleMessage += " (rescaling every " + rescalingFrequency + " evaluations";
513 parenthesis = true;
514 }
515 if (this.delayRescalingUntilUnderflow) {
516 rescaleMessage += (parenthesis ? ", " : " (") + "delay rescaling until first overflow";
517 parenthesis = true;
518 }
519 rescaleMessage += (parenthesis ? ")" : "");
520 logger.info(rescaleMessage);
521
522 if (this.rescalingScheme == PartialsRescalingScheme.DYNAMIC) {
523 everUnderflowed = false; // If false, BEAST does not rescale until first under-/over-flow.
524 }
525
526 updateSubstitutionModel = true;
527 updateSiteModel = true;
528
529 } catch (TaxonList.MissingTaxonException mte) {
530 throw new RuntimeException(mte.toString());
531 }
532 this.useAmbiguities = useAmbiguities;
533 hasInitialized = true;
534 }
535
536 private static List<Integer> parseSystemPropertyIntegerArray(String propertyName) {
537 List<Integer> order = new ArrayList<Integer>();
538 String r = System.getProperty(propertyName);
539 if (r != null) {
540 String[] parts = r.split(",");
541 for (String part : parts) {
542 try {
543 int n = Integer.parseInt(part.trim());
544 order.add(n);
545 } catch (NumberFormatException nfe) {
546 System.err.println("Invalid entry '" + part + "' in " + propertyName);
547 }
548 }
549 }
550 return order;
551 }
552
553 private static List<String> parseSystemPropertyStringArray(String propertyName) {
554
555 List<String> order = new ArrayList<String>();
556
557 String r = System.getProperty(propertyName);
558 if (r != null) {
559 String[] parts = r.split(",");
560 for (String part : parts) {
561 try {
562 String s = part.trim();
563 order.add(s);
564 } catch (NumberFormatException nfe) {
565 System.err.println("Invalid entry '" + part + "' in " + propertyName);
566 }
567 }
568 }
569 return order;
570 }
571
572 public TipStatesModel getTipStatesModel() {
573 return tipStatesModel;
574 }
575
576 public PatternList getPatternsList() {
577 return patternList;
578 }
579
580 public TreeModel getTreeModel() {
581 return treeModel;
582 }
583
584 public BranchModel getBranchModel() {
585 return branchModel;
586 }
587
588 public SiteRateModel getSiteRateModel() {
589 return siteRateModel;
590 }
591
592 public BranchRateModel getBranchRateModel() {
593 return branchRateModel;
594 }
595
596 public PartialsRescalingScheme getRescalingScheme() {
597 return rescalingScheme;
598 }
599
600 public boolean isDelayRescalingUntilUnderflow() {
601 return delayRescalingUntilUnderflow;
602 }
603
604 public Map<Set<String>, Parameter> getPartialsRestrictions() {
605 return partialsRestrictions;
606 }
607
608 public boolean useAmbiguities() {
609 return useAmbiguities;
610 }
611
612 protected int getScaleBufferCount() {
613 return internalNodeCount + 1;
614 }
615
616 /**
617 * Sets the partials from a sequence in an alignment.
618 *
619 * @param beagle beagle
620 * @param patternList patternList
621 * @param sequenceIndex sequenceIndex
622 * @param nodeIndex nodeIndex
623 */
624 protected final void setPartials(Beagle beagle,
625 PatternList patternList,
626 int sequenceIndex,
627 int nodeIndex) {
628 double[] partials = new double[patternCount * stateCount * categoryCount];
629
630 boolean[] stateSet;
631
632 int v = 0;
633 for (int i = 0; i < patternCount; i++) {
634
635 if (patternList instanceof UncertainSiteList) {
636 ((UncertainSiteList) patternList).fillPartials(sequenceIndex, i, partials, v);
637 v += stateCount;
638 // TODO Add this functionality to SimpleSiteList to avoid if statement here
639 } else {
640
641 int state = patternList.getPatternState(sequenceIndex, i);
642 stateSet = dataType.getStateSet(state);
643
644 for (int j = 0; j < stateCount; j++) {
645 if (stateSet[j]) {
646 partials[v] = 1.0;
647 } else {
648 partials[v] = 0.0;
649 }
650 v++;
651 }
652 }
653 }
654
655 // if there is more than one category then replicate the partials for each
656 int n = patternCount * stateCount;
657 int k = n;
658 for (int i = 1; i < categoryCount; i++) {
659 System.arraycopy(partials, 0, partials, k, n);
660 k += n;
661 }
662
663 beagle.setPartials(nodeIndex, partials);
664 }
665
666 /**
667 * Sets the partials from a sequence in an alignment.
668 */
669 protected final void setPartials(Beagle beagle,
670 TipStatesModel tipStatesModel,
671 int nodeIndex) {
672 double[] partials = new double[patternCount * stateCount * categoryCount];
673
674 tipStatesModel.getTipPartials(nodeIndex, partials);
675
676 // if there is more than one category then replicate the partials for each
677 int n = patternCount * stateCount;
678 int k = n;
679 for (int i = 1; i < categoryCount; i++) {
680 System.arraycopy(partials, 0, partials, k, n);
681 k += n;
682 }
683
684 beagle.setPartials(nodeIndex, partials);
685 }
686
687 public int getPatternCount() {
688 return patternCount;
689 }
690
691 /**
692 * Sets the partials from a sequence in an alignment.
693 *
694 * @param beagle beagle
695 * @param patternList patternList
696 * @param sequenceIndex sequenceIndex
697 * @param nodeIndex nodeIndex
698 */
699 protected final void setStates(Beagle beagle,
700 PatternList patternList,
701 int sequenceIndex,
702 int nodeIndex) {
703 int i;
704
705 int[] states = new int[patternCount];
706
707 for (i = 0; i < patternCount; i++) {
708
709 states[i] = patternList.getPatternState(sequenceIndex, i);
710 }
711
712 beagle.setTipStates(nodeIndex, states);
713 }
714
715
716 // public void setStates(int tipIndex, int[] states) {
717 // System.err.println("BTL:setStates");
718 // beagle.setTipStates(tipIndex, states);
719 // makeDirty();
720 // }
721 //
722 // public void getStates(int tipIndex, int[] states) {
723 // System.err.println("BTL:getStates");
724 // beagle.getTipStates(tipIndex, states);
725 // }
726
727 public final void setPatternWeights(double[] patternWeights) {
728 this.patternWeights = patternWeights;
729 beagle.setPatternWeights(patternWeights);
730 }
731
732
733 // **************************************************************
734 // ModelListener IMPLEMENTATION
735 // **************************************************************
736
737 /**
738 * Handles model changed events from the submodels.
739 */
740 protected void handleModelChangedEvent(Model model, Object object, int index) {
741
742 fireModelChanged();
743
744 if (model == treeModel) {
745 if (object instanceof TreeChangedEvent) {
746
747 if (((TreeChangedEvent) object).isNodeChanged()) {
748 // If a node event occurs the node and its two child nodes
749 // are flagged for updating (this will result in everything
750 // above being updated as well. Node events occur when a node
751 // is added to a branch, removed from a branch or its height or
752 // rate changes.
753 updateNodeAndChildren(((TreeChangedEvent) object).getNode());
754 updateRestrictedNodePartials = true;
755
756 } else if (((TreeChangedEvent) object).isTreeChanged()) {
757 // Full tree events result in a complete updating of the tree likelihood
758 // This event type is now used for EmpiricalTreeDistributions.
759 // System.err.println("Full tree update event - these events currently aren't used\n" +
760 // "so either this is in error or a new feature is using them so remove this message.");
761 updateAllNodes();
762 updateRestrictedNodePartials = true;
763 } else {
764 // Other event types are ignored (probably trait changes).
765 //System.err.println("Another tree event has occured (possibly a trait change).");
766 }
767 }
768
769 } else if (model == branchRateModel) {
770 if (index == -1) {
771 updateAllNodes();
772 } else {
773 updateNode(treeModel.getNode(index));
774 }
775
776 } else if (model == branchModel) {
777 if (index == -1) {
778 updateSubstitutionModel = true;
779 updateAllNodes();
780 } else {
781 updateNode(treeModel.getNode(index));
782 }
783 } else if (model == siteRateModel) {
784
785 updateSiteModel = true;
786 updateAllNodes();
787
788 } else if (model == tipStatesModel) {
789 if (object instanceof Taxon) {
790 for (int i = 0; i < treeModel.getNodeCount(); i++)
791 if (treeModel.getNodeTaxon(treeModel.getNode(i)) != null && treeModel.getNodeTaxon(treeModel.getNode(i)).getId().equalsIgnoreCase(((Taxon) object).getId()))
792 updateNode(treeModel.getNode(i));
793 } else if (object instanceof Parameter) {
794 // ignore...
795 } else {
796 updateAllNodes();
797 }
798 } else {
799
800 throw new RuntimeException("Unknown componentChangedEvent");
801 }
802
803 super.handleModelChangedEvent(model, object, index);
804 }
805
806 @Override
807 public void makeDirty() {
808 super.makeDirty();
809 updateSiteModel = true;
810 updateSubstitutionModel = true;
811 updateRestrictedNodePartials = true;
812 }
813 // **************************************************************
814 // Model IMPLEMENTATION
815 // **************************************************************
816
817 /**
818 * Stores the additional state other than model components
819 */
820 protected void storeState() {
821 partialBufferHelper.storeState();
822 substitutionModelDelegate.storeState();
823
824 if (useScaleFactors || useAutoScaling) { // Only store when actually used
825 scaleBufferHelper.storeState();
826 System.arraycopy(scaleBufferIndices, 0, storedScaleBufferIndices, 0, scaleBufferIndices.length);
827 // storedRescalingCount = rescalingCount;
828 }
829
830 super.storeState();
831
832 }
833
834 /**
835 * Restore the additional stored state
836 */
837 protected void restoreState() {
838 updateSiteModel = true; // this is required to upload the categoryRates to BEAGLE after the restore
839
840 partialBufferHelper.restoreState();
841 substitutionModelDelegate.restoreState();
842
843 if (useScaleFactors || useAutoScaling) {
844 scaleBufferHelper.restoreState();
845 int[] tmp = storedScaleBufferIndices;
846 storedScaleBufferIndices = scaleBufferIndices;
847 scaleBufferIndices = tmp;
848 // rescalingCount = storedRescalingCount;
849 }
850
851 updateRestrictedNodePartials = true;
852
853 super.restoreState();
854
855 }
856
857 // int marcCount = 0;
858 // **************************************************************
859 // Likelihood IMPLEMENTATION
860 // **************************************************************
861
862 /**
863 * Calculate the log likelihood of the current state.
864 *
865 * @return the log likelihood.
866 */
867 protected double calculateLogLikelihood() {
868
869 if (patternLogLikelihoods == null) {
870 patternLogLikelihoods = new double[patternCount];
871 }
872
873 if (branchUpdateIndices == null) {
874 branchUpdateIndices = new int[nodeCount];
875 branchLengths = new double[nodeCount];
876 scaleBufferIndices = new int[internalNodeCount];
877 storedScaleBufferIndices = new int[internalNodeCount];
878 }
879
880 if (operations == null) {
881 operations = new int[numRestrictedPartials + 1][internalNodeCount * Beagle.OPERATION_TUPLE_SIZE];
882 operationCount = new int[numRestrictedPartials + 1];
883 }
884
885 recomputeScaleFactors = false;
886
887 if (!this.delayRescalingUntilUnderflow || everUnderflowed) {
888 if (this.rescalingScheme == PartialsRescalingScheme.ALWAYS || this.rescalingScheme == PartialsRescalingScheme.DELAYED) {
889 useScaleFactors = true;
890 recomputeScaleFactors = true;
891 } else if (this.rescalingScheme == PartialsRescalingScheme.DYNAMIC) {
892 useScaleFactors = true;
893 if (DEBUG) {
894 System.out.println("rescalingCount = " + rescalingCount);
895 System.out.println("rescalingCountInner = " + rescalingCountInner);
896 }
897
898 if (rescalingCount > rescalingFrequency) {
899 if (DEBUG) {
900 System.out.println("rescalingCount > rescalingFrequency");
901 }
902 rescalingCount = 0;
903 rescalingCountInner = 0;
904 }
905
906 if (rescalingCountInner < RESCALE_TIMES) {
907 recomputeScaleFactors = true;
908 updateAllNodes();
909 rescalingCountInner++;
910 }
911
912 rescalingCount++;
913 }
914 }
915
916 if (RESCALING_OFF) { // a debugging switch
917 useScaleFactors = false;
918 recomputeScaleFactors = false;
919 }
920
921 if (tipStatesModel != null) {
922 int tipCount = treeModel.getExternalNodeCount();
923 for (int index = 0; index < tipCount; index++) {
924 if (updateNode[index]) {
925 if (tipStatesModel.getModelType() == TipStatesModel.Type.PARTIALS) {
926 tipStatesModel.getTipPartials(index, tipPartials);
927 beagle.setTipPartials(index, tipPartials);
928 } else {
929 tipStatesModel.getTipStates(index, tipStates);
930 beagle.setTipStates(index, tipStates);
931 }
932 }
933 }
934 }
935
936 branchUpdateCount = 0;
937 operationListCount = 0;
938
939 if (hasRestrictedPartials) {
940 for (int i = 0; i <= numRestrictedPartials; i++) {
941 operationCount[i] = 0;
942 }
943 } else {
944 operationCount[0] = 0;
945 }
946
947 final NodeRef root = treeModel.getRoot();
948 traverse(treeModel, root, null, true);
949
950 if (DEBUG) {
951 System.out.println("operationCount = " + operationCount[operationListCount]);
952 }
953
954 if (updateSubstitutionModel) { // TODO More efficient to update only the substitution model that changed, instead of all
955 substitutionModelDelegate.updateSubstitutionModels(beagle);
956
957 // we are currently assuming a no-category model...
958 }
959
960 if (updateSiteModel) {
961 double[] categoryRates = this.siteRateModel.getCategoryRates();
962 if (categoryRates == null) {
963 // If this returns null then there was a numerical error calculating the category rates
964 // (probably a very small alpha) so reject the move.
965 return Double.NEGATIVE_INFINITY;
966 }
967 beagle.setCategoryRates(categoryRates);
968 }
969
970 if (branchUpdateCount > 0) {
971 substitutionModelDelegate.updateTransitionMatrices(
972 beagle,
973 branchUpdateIndices,
974 branchLengths,
975 branchUpdateCount);
976 }
977
978 if (COUNT_TOTAL_OPERATIONS) {
979 totalMatrixUpdateCount += branchUpdateCount;
980
981 for (int i = 0; i <= numRestrictedPartials; i++) {
982 totalOperationCount += operationCount[i];
983 }
984 }
985
986 double logL;
987 boolean done;
988 boolean firstRescaleAttempt = true;
989
990 do {
991
992 if (hasRestrictedPartials) {
993 for (int i = 0; i <= numRestrictedPartials; i++) {
994 beagle.updatePartials(operations[i], operationCount[i], Beagle.NONE);
995 if (i < numRestrictedPartials) {
996 // restrictNodePartials(restrictedIndices[i]);
997 }
998 }
999 } else {
1000 beagle.updatePartials(operations[0], operationCount[0], Beagle.NONE);
1001 }
1002
1003 int rootIndex = partialBufferHelper.getOffsetIndex(root.getNumber());
1004
1005 double[] categoryWeights = this.siteRateModel.getCategoryProportions();
1006
1007 // This should probably explicitly be the state frequencies for the root node...
1008 double[] frequencies = substitutionModelDelegate.getRootStateFrequencies();
1009
1010 int cumulateScaleBufferIndex = Beagle.NONE;
1011 if (useScaleFactors) {
1012
1013 if (recomputeScaleFactors) {
1014 scaleBufferHelper.flipOffset(internalNodeCount);
1015 cumulateScaleBufferIndex = scaleBufferHelper.getOffsetIndex(internalNodeCount);
1016 beagle.resetScaleFactors(cumulateScaleBufferIndex);
1017 beagle.accumulateScaleFactors(scaleBufferIndices, internalNodeCount, cumulateScaleBufferIndex);
1018 } else {
1019 cumulateScaleBufferIndex = scaleBufferHelper.getOffsetIndex(internalNodeCount);
1020 }
1021 } else if (useAutoScaling) {
1022 beagle.accumulateScaleFactors(scaleBufferIndices, internalNodeCount, Beagle.NONE);
1023 }
1024
1025 // these could be set only when they change but store/restore would need to be considered
1026 beagle.setCategoryWeights(0, categoryWeights);
1027 beagle.setStateFrequencies(0, frequencies);
1028
1029 double[] sumLogLikelihoods = new double[1];
1030
1031 if (DEBUG) {
1032 System.out.println("useScaleFactors=" + useScaleFactors + " recomputeScaleFactors=" + recomputeScaleFactors);
1033 }
1034
1035 beagle.calculateRootLogLikelihoods(new int[]{rootIndex}, new int[]{0}, new int[]{0},
1036 new int[]{cumulateScaleBufferIndex}, 1, sumLogLikelihoods);
1037
1038 logL = sumLogLikelihoods[0];
1039
1040 if (DEBUG) {
1041 System.out.println(logL);
1042 // if (logL > -90000) {
1043 // System.exit(0);
1044 // }
1045 }
1046
1047 beagle.getSiteLogLikelihoods(patternLogLikelihoods);
1048
1049 if (ascertainedSitePatterns) {
1050 // Need to correct for ascertainedSitePatterns
1051 beagle.getSiteLogLikelihoods(patternLogLikelihoods);
1052 logL = getAscertainmentCorrectedLogLikelihood((AscertainedSitePatterns) patternList,
1053 patternLogLikelihoods, patternWeights);
1054 }
1055
1056 if (Double.isNaN(logL) || Double.isInfinite(logL)) {
1057
1058 if (DEBUG) {
1059 System.out.println("Double.isNaN(logL) || Double.isInfinite(logL)");
1060 }
1061
1062 everUnderflowed = true;
1063 logL = Double.NEGATIVE_INFINITY;
1064
1065 if (firstRescaleAttempt && (delayRescalingUntilUnderflow || rescalingScheme == PartialsRescalingScheme.DELAYED)) {
1066 // we have had a potential under/over flow so attempt a rescaling
1067 if (rescalingScheme == PartialsRescalingScheme.DYNAMIC || (rescalingCount == 0)) {
1068 // show a message but only every 1000 rescales
1069 if (rescalingMessageCount % 1000 == 0) {
1070 if (rescalingMessageCount > 0) {
1071 Logger.getLogger("dr.evomodel").info("Underflow calculating likelihood (" + rescalingMessageCount + " messages not shown).");
1072 } else {
1073 Logger.getLogger("dr.evomodel").info("Underflow calculating likelihood. Attempting a rescaling...");
1074 }
1075 }
1076 rescalingMessageCount += 1;
1077 }
1078 useScaleFactors = true;
1079 recomputeScaleFactors = true;
1080
1081 branchUpdateCount = 0;
1082
1083 updateAllNodes();
1084
1085 if (hasRestrictedPartials) {
1086 for (int i = 0; i <= numRestrictedPartials; i++) {
1087 operationCount[i] = 0;
1088 }
1089 } else {
1090 operationCount[0] = 0;
1091 }
1092
1093 // traverse again but without flipping partials indices as we
1094 // just want to overwrite the last attempt. We will flip the
1095 // scale buffer indices though as we are recomputing them.
1096 traverse(treeModel, root, null, false);
1097
1098 done = false; // Run through do-while loop again
1099 firstRescaleAttempt = false; // Only try to rescale once
1100
1101 } else {
1102 // we have already tried a rescale, not rescaling or always rescaling
1103 // so just return the likelihood...
1104 done = true;
1105 }
1106 } else {
1107 done = true; // No under-/over-flow, then done
1108 }
1109
1110 } while (!done);
1111
1112 // If these are needed...
1113 //beagle.getSiteLogLikelihoods(patternLogLikelihoods);
1114
1115 //********************************************************************
1116 // after traverse all nodes and patterns have been updated --
1117 //so change flags to reflect this.
1118 for (int i = 0; i < nodeCount; i++) {
1119 updateNode[i] = false;
1120 }
1121
1122 updateSubstitutionModel = false;
1123 updateSiteModel = false;
1124 //********************************************************************
1125
1126 return logL;
1127 }
1128
1129 public void getPartials(int number, double[] partials) {
1130 int cumulativeBufferIndex = Beagle.NONE;
1131 /* No need to rescale partials */
1132 beagle.getPartials(partialBufferHelper.getOffsetIndex(number), cumulativeBufferIndex, partials);
1133 }
1134
1135 public boolean arePartialsRescaled() {
1136 return useScaleFactors;
1137 }
1138
1139 protected void setPartials(int number, double[] partials) {
1140 beagle.setPartials(partialBufferHelper.getOffsetIndex(number), partials);
1141 }
1142
1143 private void restrictNodePartials(int nodeIndex) {
1144
1145 Parameter restrictionParameter = partialsMap[nodeIndex];
1146 if (restrictionParameter == null) {
1147 return;
1148 }
1149
1150 getPartials(nodeIndex, partials);
1151
1152 double[] restriction = restrictionParameter.getParameterValues();
1153 final int partialsLengthPerCategory = stateCount * patternCount;
1154 if (restriction.length == partialsLengthPerCategory) {
1155 for (int i = 0; i < categoryCount; i++) {
1156 componentwiseMultiply(partials, partialsLengthPerCategory * i, restriction, 0, partialsLengthPerCategory);
1157 }
1158 } else {
1159 componentwiseMultiply(partials, 0, restriction, 0, partialsLengthPerCategory * categoryCount);
1160 }
1161
1162 setPartials(nodeIndex, partials);
1163 }
1164
1165 private void componentwiseMultiply(double[] a, final int offsetA, double[] b, final int offsetB, final int length) {
1166 for (int i = 0; i < length; i++) {
1167 a[offsetA + i] *= b[offsetB + i];
1168 }
1169 }
1170
1171 private void computeNodeToRestrictionMap() {
1172 Arrays.fill(partialsMap, null);
1173 for (Set<String> taxonNames : partialsRestrictions.keySet()) {
1174 NodeRef node = TreeUtils.getCommonAncestorNode(treeModel, taxonNames);
1175 partialsMap[node.getNumber()] = partialsRestrictions.get(taxonNames);
1176 }
1177 }
1178
1179 private double getAscertainmentCorrectedLogLikelihood(AscertainedSitePatterns patternList,
1180 double[] patternLogLikelihoods,
1181 double[] patternWeights) {
1182 double logL = 0.0;
1183 double ascertainmentCorrection = patternList.getAscertainmentCorrection(patternLogLikelihoods);
1184 for (int i = 0; i < patternCount; i++) {
1185 logL += (patternLogLikelihoods[i] - ascertainmentCorrection) * patternWeights[i];
1186 }
1187 return logL;
1188 }
1189
1190 /**
1191 * Traverse the tree calculating partial likelihoods.
1192 *
1193 * @param tree tree
1194 * @param node node
1195 * @param operatorNumber operatorNumber
1196 * @param flip flip
1197 * @return boolean
1198 */
1199 private boolean traverse(Tree tree, NodeRef node, int[] operatorNumber, boolean flip) {
1200
1201 boolean update = false;
1202
1203 int nodeNum = node.getNumber();
1204
1205 NodeRef parent = tree.getParent(node);
1206
1207 if (operatorNumber != null) {
1208 operatorNumber[0] = -1;
1209 }
1210
1211 // First update the transition probability matrix(ices) for this branch
1212 if (parent != null && updateNode[nodeNum]) {
1213
1214 final double branchRate;
1215
1216 synchronized (branchRateModel) {
1217 branchRate = branchRateModel.getBranchRate(tree, node);
1218 }
1219 final double parentHeight = tree.getNodeHeight(parent);
1220 final double nodeHeight = tree.getNodeHeight(node);
1221
1222 // Get the operational time of the branch
1223 final double branchLength = branchRate * (parentHeight - nodeHeight);
1224 if (branchLength < 0.0) {
1225 throw new RuntimeException("Negative branch length: " + branchLength + " (parent: " + parent +
1226 "; height: " + parentHeight + " - child: " + node + "height: " + nodeHeight + ")");
1227 }
1228
1229 if (flip) {
1230 substitutionModelDelegate.flipMatrixBuffer(nodeNum);
1231 }
1232 branchUpdateIndices[branchUpdateCount] = nodeNum;
1233 branchLengths[branchUpdateCount] = branchLength;
1234 branchUpdateCount++;
1235
1236 update = true;
1237 }
1238
1239 // If the node is internal, update the partial likelihoods.
1240 if (!tree.isExternal(node)) {
1241
1242 // Traverse down the two child nodes
1243 NodeRef child1 = tree.getChild(node, 0);
1244 final int[] op1 = {-1};
1245 final boolean update1 = traverse(tree, child1, op1, flip);
1246
1247 NodeRef child2 = tree.getChild(node, 1);
1248 final int[] op2 = {-1};
1249 final boolean update2 = traverse(tree, child2, op2, flip);
1250
1251 // If either child node was updated then update this node too
1252 if (update1 || update2) {
1253
1254 int x = operationCount[operationListCount] * Beagle.OPERATION_TUPLE_SIZE;
1255
1256 if (flip) {
1257 // first flip the partialBufferHelper
1258 partialBufferHelper.flipOffset(nodeNum);
1259 }
1260
1261 final int[] operations = this.operations[operationListCount];
1262
1263 operations[x] = partialBufferHelper.getOffsetIndex(nodeNum);
1264
1265 if (useScaleFactors) {
1266 // get the index of this scaling buffer
1267 int n = nodeNum - tipCount;
1268
1269 if (recomputeScaleFactors) {
1270 // flip the indicator: can take either n or (internalNodeCount + 1) - n
1271 scaleBufferHelper.flipOffset(n);
1272
1273 // store the index
1274 scaleBufferIndices[n] = scaleBufferHelper.getOffsetIndex(n);
1275
1276 operations[x + 1] = scaleBufferIndices[n]; // Write new scaleFactor
1277 operations[x + 2] = Beagle.NONE;
1278
1279 } else {
1280 operations[x + 1] = Beagle.NONE;
1281 operations[x + 2] = scaleBufferIndices[n]; // Read existing scaleFactor
1282 }
1283
1284 } else {
1285
1286 if (useAutoScaling) {
1287 scaleBufferIndices[nodeNum - tipCount] = partialBufferHelper.getOffsetIndex(nodeNum);
1288 }
1289 operations[x + 1] = Beagle.NONE; // Not using scaleFactors
1290 operations[x + 2] = Beagle.NONE;
1291 }
1292
1293 operations[x + 3] = partialBufferHelper.getOffsetIndex(child1.getNumber()); // source node 1
1294 operations[x + 4] = substitutionModelDelegate.getMatrixIndex(child1.getNumber()); // source matrix 1
1295 operations[x + 5] = partialBufferHelper.getOffsetIndex(child2.getNumber()); // source node 2
1296 operations[x + 6] = substitutionModelDelegate.getMatrixIndex(child2.getNumber()); // source matrix 2
1297
1298 operationCount[operationListCount]++;
1299
1300 update = true;
1301
1302 if (hasRestrictedPartials) {
1303 // Test if this set of partials should be restricted
1304 if (updateRestrictedNodePartials) {
1305 // Recompute map
1306 computeNodeToRestrictionMap();
1307 updateRestrictedNodePartials = false;
1308 }
1309 if (partialsMap[nodeNum] != null) {
1310
1311 }
1312 }
1313
1314 }
1315 }
1316
1317 return update;
1318
1319 }
1320
1321 // **************************************************************
1322 // INSTANCE VARIABLES
1323 // **************************************************************
1324
1325 private int[] branchUpdateIndices;
1326 private double[] branchLengths;
1327 private int branchUpdateCount;
1328
1329 private int[] scaleBufferIndices;
1330 private int[] storedScaleBufferIndices;
1331
1332 private int[][] operations;
1333 private int operationListCount;
1334 private int[] operationCount;
1335 // private final boolean hasRestrictedPartials;
1336 private static final boolean hasRestrictedPartials = false;
1337
1338 private final int numRestrictedPartials;
1339 private final Map<Set<String>, Parameter> partialsRestrictions;
1340 private Parameter[] partialsMap;
1341 private double[] partials;
1342 private boolean updateRestrictedNodePartials;
1343 // private int[] restrictedIndices;
1344
1345 protected BufferIndexHelper partialBufferHelper;
1346 protected BufferIndexHelper scaleBufferHelper;
1347
1348 protected final int tipCount;
1349 protected final int internalNodeCount;
1350
1351 private PartialsRescalingScheme rescalingScheme;
1352 private int rescalingFrequency = RESCALE_FREQUENCY;
1353 private boolean delayRescalingUntilUnderflow = true;
1354
1355 protected boolean useScaleFactors = false;
1356 private boolean useAutoScaling = false;
1357 private boolean recomputeScaleFactors = false;
1358 private boolean everUnderflowed = false;
1359 private int rescalingCount = 0;
1360 private int rescalingCountInner = 0;
1361 // private int storedRescalingCount;
1362
1363 private int rescalingMessageCount = 0;
1364
1365 private int threadCount = 1;
1366
1367 /**
1368 * the branch-site model for these sites
1369 */
1370 protected final BranchModel branchModel;
1371
1372 /**
1373 * A delegate to handle substitution models on branches
1374 */
1375 protected final SubstitutionModelDelegate substitutionModelDelegate;
1376
1377 /**
1378 * the site model for these sites
1379 */
1380 protected final SiteRateModel siteRateModel;
1381
1382 /**
1383 * the branch rate model
1384 */
1385 protected final BranchRateModel branchRateModel;
1386
1387 /**
1388 * the tip partials model
1389 */
1390 private final TipStatesModel tipStatesModel;
1391
1392 /**
1393 * the pattern likelihoods
1394 */
1395 protected double[] patternLogLikelihoods = null;
1396
1397 /**
1398 * the number of rate categories
1399 */
1400 protected int categoryCount;
1401
1402 /**
1403 * an array used to transfer tip partials
1404 */
1405 protected double[] tipPartials;
1406
1407 /**
1408 * an array used to transfer tip states
1409 */
1410 protected int[] tipStates;
1411
1412 /**
1413 * the BEAGLE library instance
1414 */
1415 protected Beagle beagle;
1416
1417 /**
1418 * Flag to specify that the substitution model has changed
1419 */
1420 protected boolean updateSubstitutionModel;
1421
1422 /**
1423 * Flag to specify that the site model has changed
1424 */
1425 protected boolean updateSiteModel;
1426
1427 // /***
1428 // * Flag to specify if LikelihoodCore supports dynamic rescaling
1429 // */
1430 // private boolean dynamicRescaling = false;
1431
1432
1433 /**
1434 * Flag to specify if site patterns are acertained
1435 */
1436
1437 private boolean ascertainedSitePatterns = false;
1438
1439
1440 /**
1441 * Flag to specify if ambiguity codes are in use
1442 */
1443 protected final boolean useAmbiguities;
1444
1445 public static void main(String[] args) {
1446
1447 try {
1448
1449 MathUtils.setSeed(666);
1450
1451 System.out.println("Test case 1: simulateOnePartition");
1452
1453 int sequenceLength = 1000;
1454 ArrayList<Partition> partitionsList = new ArrayList<Partition>();
1455
1456 // create tree
1457 NewickImporter importer = new NewickImporter(
1458 "(SimSeq1:73.7468,(SimSeq2:25.256989999999995,SimSeq3:45.256989999999995):18.48981);");
1459 Tree tree = importer.importTree(null);
1460 TreeModel treeModel = new TreeModel(tree);
1461
1462 // create Frequency Model
1463 Parameter freqs = new Parameter.Default(new double[]{0.25, 0.25,
1464 0.25, 0.25});
1465 FrequencyModel freqModel = new FrequencyModel(Nucleotides.INSTANCE,
1466 freqs);
1467
1468 // create branch model
1469 Parameter kappa1 = new Parameter.Default(1, 1);
1470 Parameter kappa2 = new Parameter.Default(1, 1);
1471
1472 HKY hky1 = new HKY(kappa1, freqModel);
1473 HKY hky2 = new HKY(kappa2, freqModel);
1474
1475 HomogeneousBranchModel homogenousBranchSubstitutionModel = new HomogeneousBranchModel(
1476 hky1);
1477
1478 List<SubstitutionModel> substitutionModels = new ArrayList<SubstitutionModel>();
1479 substitutionModels.add(hky1);
1480 substitutionModels.add(hky2);
1481 List<FrequencyModel> freqModels = new ArrayList<FrequencyModel>();
1482 freqModels.add(freqModel);
1483
1484 Parameter epochTimes = new Parameter.Default(1, 20);
1485
1486 // create branch rate model
1487 Parameter rate = new Parameter.Default(1, 0.001);
1488 BranchRateModel branchRateModel = new StrictClockBranchRates(rate);
1489
1490 // create site model
1491 GammaSiteRateModel siteRateModel = new GammaSiteRateModel(
1492 "siteModel");
1493
1494 BranchModel homogeneousBranchModel = new HomogeneousBranchModel(hky1);
1495
1496 BranchModel epochBranchModel = new EpochBranchModel(treeModel, substitutionModels, epochTimes);
1497
1498 // create partition
1499 Partition partition1 = new Partition(treeModel, //
1500 homogenousBranchSubstitutionModel,//
1501 siteRateModel, //
1502 branchRateModel, //
1503 freqModel, //
1504 0, // from
1505 sequenceLength - 1, // to
1506 1 // every
1507 );
1508
1509 partitionsList.add(partition1);
1510
1511 // feed to sequence simulator and generate data
1512 BeagleSequenceSimulator simulator = new BeagleSequenceSimulator(partitionsList
1513 // , sequenceLength
1514 );
1515 Alignment alignment = simulator.simulate(false, false);
1516
1517 BeagleTreeLikelihood nbtl = new BeagleTreeLikelihood(alignment, treeModel, homogeneousBranchModel, siteRateModel, branchRateModel, null, false, PartialsRescalingScheme.DEFAULT, false);
1518
1519 System.out.println("nBTL(homogeneous) = " + nbtl.getLogLikelihood());
1520
1521 nbtl = new BeagleTreeLikelihood(alignment, treeModel, epochBranchModel, siteRateModel, branchRateModel, null, false, PartialsRescalingScheme.DEFAULT, false);
1522
1523 System.out.println("nBTL(epoch) = " + nbtl.getLogLikelihood());
1524
1525 } catch (Exception e) {
1526 e.printStackTrace();
1527 System.exit(-1);
1528 } // END: try-catch block
1529 }
1530
1531 public Double getUpdateTimer() {
1532 return Double.valueOf(substitutionModelDelegate.updateTime);
1533 }
1534
1535 public Double getConvolveTimer() {
1536 return Double.valueOf(substitutionModelDelegate.convolveTime);
1537 }
1538
1539 public void getLogScalingFactors(int nodeIndex, double[] buffer) {
1540 if (nodeIndex < tipCount) {
1541 Arrays.fill(buffer, 0.0);
1542 } else {
1543 // final int scaleIndex = scaleBufferHelper.getOffsetIndex(nodeIndex - tipCount);
1544 final int scaleIndex = scaleBufferIndices[nodeIndex - tipCount];
1545 beagle.getLogScaleFactors(scaleIndex, buffer);
1546 }
1547 }
1548
1549 public double[] getSiteLogLikelihoods() {
1550 getLogLikelihood();
1551 double[] siteLogLikelihoods = new double[patternCount];
1552 beagle.getSiteLogLikelihoods(siteLogLikelihoods);
1553 return siteLogLikelihoods;
1554 }
1555
1556 @Override
1557 public Citation.Category getCategory() {
1558 return Citation.Category.FRAMEWORK;
1559 }
1560
1561 @Override
1562 public String getDescription() {
1563 return "Using BEAGLE likelihood calculation library";
1564 }
1565
1566 public List<Citation> getCitations() {
1567 return Collections.singletonList(CommonCitations.AYRES_2012_BEAGLE);
1568 }
1569
1570 }//END: class