Debian Codegraph @

src/dr/evomodel/treelikelihood/MultiPartitionTreeLikelihood.java

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