Debian Codegraph @

src/dr/evomodel/continuous/AbstractMultivariateTraitLikelihood.java

raw symbols SCIP
1 /*
2 * AbstractMultivariateTraitLikelihood.java
3 *
4 * Copyright (c) 2002-2013 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.continuous;
27
28 import dr.evolution.tree.*;
29 import dr.evolution.util.Taxon;
30 import dr.evomodel.branchratemodel.BranchRateModel;
31 import dr.evomodel.branchratemodel.StrictClockBranchRates;
32 import dr.evomodel.tree.TreeChangedEvent;
33 import dr.evomodel.tree.TreeModel;
34 import dr.evomodelxml.treedatalikelihood.ContinuousDataLikelihoodParser;
35 import dr.evomodelxml.treelikelihood.TreeTraitParserUtilities;
36 import dr.inference.distribution.MultivariateDistributionLikelihood;
37 import dr.inference.loggers.LogColumn;
38 import dr.inference.loggers.NumberColumn;
39 import dr.inference.model.*;
40 import dr.math.distributions.MultivariateDistribution;
41 import dr.math.distributions.MultivariateNormalDistribution;
42 import dr.stats.DiscreteStatistics;
43 import dr.util.Author;
44 import dr.util.Citable;
45 import dr.util.Citation;
46 import dr.util.CommonCitations;
47 import dr.xml.*;
48 import org.w3c.dom.Document;
49 import org.w3c.dom.Element;
50
51 import java.util.*;
52 import java.util.logging.Logger;
53
54 /**
55 * @author Marc Suchard
56 */
57
58 public abstract class AbstractMultivariateTraitLikelihood extends AbstractModelLikelihood
59 implements TreeTraitProvider, Citable {
60
61 public static final String TRAIT_LIKELIHOOD = "multivariateTraitLikelihood";
62 public static final String CONJUGATE_ROOT_PRIOR = "conjugateRootPrior";
63 public static final String MODEL = "diffusionModel";
64 public static final String TREE = "tree";
65 public static final String CACHE_BRANCHES = "cacheBranches";
66 public static final String REPORT_MULTIVARIATE = "reportAsMultivariate";
67 public static final String CHECK = "check";
68 public static final String USE_TREE_LENGTH = "useTreeLength";
69 public static final String SCALE_BY_TIME = "scaleByTime";
70 public static final String SUBSTITUTIONS = "substitutions";
71 public static final String SAMPLING_DENSITY = "samplingDensity";
72 public static final String INTEGRATE = "integrateInternalTraits";
73 public static final String STANDARDIZE_TRAITS = "standardizeTraits";
74 public static final String RECIPROCAL_RATES = "reciprocalRates";
75 public static final String PRIOR_SAMPLE_SIZE = "priorSampleSize";
76 public static final String RANDOM_SAMPLE = "randomSample";
77 public static final String IGNORE_PHYLOGENY = "ignorePhylogeny";
78 public static final String ASCERTAINMENT = "ascertainedTaxon";
79 public static final String EXCHANGEABLE_TIPS = "exchangeableTips";
80 public static final String DRIFT_MODELS = "driftModels";
81 private BranchRateModel branchRateModel;
82 public static final String STRENGTH_OF_SELECTION = "strengthOfSelection";
83 public static final String OPTIMAL_TRAITS = "optimalTraits";
84
85 // public AbstractMultivariateTraitLikelihood(String traitName,
86 // MutableTreeModel treeModel,
87 // MultivariateDiffusionModel diffusionModel,
88 // CompoundParameter traitParameter,
89 // List<Integer> missingIndices,
90 // boolean cacheBranches,
91 // boolean scaleByTime,
92 // boolean useTreeLength,
93 // BranchRateModel rateModel,
94 // Model samplingDensity,
95 // boolean reportAsMultivariate,
96 // boolean reciprocalRates) {
97 // this(traitName, treeModel, diffusionModel, traitParameter, null, missingIndices, cacheBranches,
98 // scaleByTime, useTreeLength, rateModel, null, samplingDensity, reportAsMultivariate, reciprocalRates);
99 // }
100
101 public AbstractMultivariateTraitLikelihood(String traitName,
102 MutableTreeModel treeModel,
103 MultivariateDiffusionModel diffusionModel,
104 CompoundParameter traitParameter,
105 Parameter deltaParameter,
106 List<Integer> missingIndices,
107 boolean cacheBranches,
108 boolean scaleByTime,
109 boolean useTreeLength,
110 BranchRateModel rateModel,
111 List<BranchRateModel> driftModels,
112 List<BranchRateModel> optimalValues,
113 BranchRateModel strengthOfSelection,
114 Model samplingDensity,
115 boolean reportAsMultivariate,
116 boolean reciprocalRates) {
117
118 super(TRAIT_LIKELIHOOD);
119
120 this.traitName = traitName;
121 this.treeModel = treeModel;
122 this.branchRateModel = rateModel;
123 this.driftModels = driftModels;
124 this.optimalValues = optimalValues;
125 this.strengthOfSelection = strengthOfSelection;
126 this.diffusionModel = diffusionModel;
127 this.traitParameter = traitParameter;
128 this.missingIndices = missingIndices;
129 addModel(treeModel);
130 addModel(diffusionModel);
131
132 this.deltaParameter = deltaParameter;
133 if (deltaParameter != null) {
134 addVariable(deltaParameter);
135 }
136
137 if (rateModel != null) {
138 hasBranchRateModel = true;
139 addModel(rateModel);
140 }
141
142 if (driftModels != null) {
143 for (BranchRateModel drift : driftModels) {
144 addModel(drift);
145 }
146 }
147
148 if (optimalValues != null) {
149 for (BranchRateModel optVal : optimalValues) {
150 addModel(optVal);
151 }
152 }
153
154 if (strengthOfSelection != null) {
155 addModel(strengthOfSelection);
156 }
157
158 if (samplingDensity != null) {
159 addModel(samplingDensity);
160 }
161
162 if (traitParameter != null)
163 addVariable(traitParameter);
164
165 this.reportAsMultivariate = reportAsMultivariate;
166
167 this.cacheBranches = cacheBranches;
168 if (cacheBranches) {
169 cachedLogLikelihoods = new double[treeModel.getNodeCount()];
170 storedCachedLogLikelihood = new double[treeModel.getNodeCount()];
171 validLogLikelihoods = new boolean[treeModel.getNodeCount()];
172 storedValidLogLikelihoods = new boolean[treeModel.getNodeCount()];
173 }
174
175 this.scaleByTime = scaleByTime;
176 this.useTreeLength = useTreeLength;
177 this.reciprocalRates = reciprocalRates;
178
179 dimTrait = diffusionModel.getPrecisionmatrix().length;
180 dim = traitParameter != null ? traitParameter.getParameter(0).getDimension() : 0;
181 numData = dim / dimTrait;
182
183 if (dim % dimTrait != 0)
184 throw new RuntimeException("dim is not divisible by dimTrait");
185
186 recalculateTreeLength();
187 printInformtion();
188
189 }
190
191 // public AbstractMultivariateTraitLikelihood(String traitName,
192 // MutableTreeModel treeModel,
193 // MultivariateDiffusionModel diffusionModel,
194 // CompoundParameter traitParameter,
195 // Parameter deltaParameter,
196 // List<Integer> missingIndices,
197 // boolean cacheBranches,
198 // boolean scaleByTime,
199 // boolean useTreeLength,
200 // BranchRateModel rateModel,
201 // List<BranchRateModel> optimalValues,
202 // BranchRateModel strengthOfSelection,
203 // Model samplingDensity,
204 // boolean reportAsMultivariate,
205 // boolean reciprocalRates) {
206 //
207 // super(TRAIT_LIKELIHOOD);
208 //
209 // this.traitName = traitName;
210 // this.treeModel = treeModel;
211 // this.branchRateModel = rateModel;
212 // this.optimalValues = optimalValues;
213 // this.strengthOfSelection = strengthOfSelection;
214 // this.diffusionModel = diffusionModel;
215 // this.traitParameter = traitParameter;
216 // this.missingIndices = missingIndices;
217 // addModel(treeModel);
218 // addModel(diffusionModel);
219 //
220 // this.deltaParameter = deltaParameter;
221 // if (deltaParameter != null) {
222 // addVariable(deltaParameter);
223 // }
224 //
225 //
226 // if (rateModel != null) {
227 // hasBranchRateModel = true;
228 // addModel(rateModel);
229 // }
230 //
231 // if (optimalValues != null) {
232 // for (BranchRateModel optVal : optimalValues) {
233 // addModel(optVal);
234 // }
235 // }
236 //
237 // if (strengthOfSelection != null) {
238 // addModel(strengthOfSelection);
239 // }
240 //
241 // if (samplingDensity != null) {
242 // addModel(samplingDensity);
243 // }
244 //
245 // if (traitParameter != null)
246 // addVariable(traitParameter);
247 //
248 // this.reportAsMultivariate = reportAsMultivariate;
249 //
250 // this.cacheBranches = cacheBranches;
251 // if (cacheBranches) {
252 // cachedLogLikelihoods = new double[treeModel.getNodeCount()];
253 // storedCachedLogLikelihood = new double[treeModel.getNodeCount()];
254 // validLogLikelihoods = new boolean[treeModel.getNodeCount()];
255 // storedValidLogLikelihoods = new boolean[treeModel.getNodeCount()];
256 // }
257 //
258 // this.scaleByTime = scaleByTime;
259 // this.useTreeLength = useTreeLength;
260 // this.reciprocalRates = reciprocalRates;
261 //
262 // dimTrait = diffusionModel.getPrecisionmatrix().length;
263 // dim = traitParameter != null ? traitParameter.getParameter(0).getDimension() : 0;
264 // numData = dim / dimTrait;
265 //
266 // if (dim % dimTrait != 0)
267 // throw new RuntimeException("dim is not divisible by dimTrait");
268 //
269 // recalculateTreeLength();
270 // printInformtion();
271 //
272 // }
273
274
275 protected void printInformtion() {
276 StringBuffer sb = new StringBuffer("Creating multivariate diffusion model:\n");
277 sb.append("\tTrait: ").append(traitName).append("\n");
278 sb.append("\tDiffusion process: ").append(diffusionModel.getId()).append("\n");
279 sb.append("\tHeterogenity model: ").append(branchRateModel != null ? branchRateModel.getId() : "homogeneous").append("\n");
280 sb.append("\tTree normalization: ").append(scaleByTime ? (useTreeLength ? "length" : "height") : "off").append("\n");
281 sb.append("\tUsing reciprocal (precision) rates: ").append(reciprocalRates).append("\n");
282 if (scaleByTime) {
283 recalculateTreeLength();
284 if (useTreeLength) {
285 sb.append("\tInitial tree length: ").append(treeLength).append("\n");
286 } else {
287 sb.append("\tInitial tree height: ").append(treeLength).append("\n");
288 }
289 }
290 sb.append(extraInfo());
291 sb.append("\tPlease cite:\n");
292 sb.append(Citable.Utils.getCitationString(this));
293
294
295 sb.append("\n\tDiffusion dimension : ").append(dimTrait).append("\n");
296 sb.append("\tNumber of observations: ").append(numData).append("\n");
297 Logger.getLogger("dr.evomodel").info(sb.toString());
298 }
299
300 @Override
301 public Citation.Category getCategory() {
302 return Citation.Category.TRAIT_MODELS;
303 }
304
305 @Override
306 public String getDescription() {
307 return "Multivariate Diffusion model";
308 }
309
310 @Override
311 public List<Citation> getCitations() {
312 List<Citation> citations = new ArrayList<Citation>();
313 citations.add(CommonCitations.LEMEY_2010_PHYLOGEOGRAPHY);
314 if (doAscertainmentCorrect) {
315 citations.add(
316 new Citation(
317 new Author[]{
318 new Author("MA", "Suchard"),
319 new Author("J", "Novembre"),
320 new Author("B", "von Holdt"),
321 new Author("G", "Cybis"),
322 },
323 Citation.Status.IN_PREPARATION
324 )
325 );
326 }
327 return citations;
328 }
329
330 protected abstract String extraInfo();
331
332 public CompoundParameter getTraitParameter() {
333 return traitParameter;
334 }
335
336 public void setAscertainedTaxon(Taxon taxon) {
337 ascertainedTaxonIndex = treeModel.getTaxonIndex(taxon);
338 if (ascertainedTaxonIndex == -1) {
339 throw new RuntimeException("Taxon " + taxon.getId() + " is not in tree " + treeModel.getId());
340 }
341 doAscertainmentCorrect = true;
342 StringBuilder sb = new StringBuilder("Enabling ascertainment correction for multivariate trait model: ");
343 sb.append(getId()).append("\n");
344 sb.append("\tTaxon: ").append(taxon.getId()).append("\n");
345 Logger.getLogger("dr.evomodel").info(sb.toString());
346 }
347
348 public double[] getShiftForBranchLength(NodeRef node) {
349 if (driftModels != null) {
350 final int dim = driftModels.size();
351 double[] drift = new double[dim];
352 double realTimeBranchLength = treeModel.getBranchLength(node);
353 for (int i = 0; i < dim; ++i) {
354 drift[i] = driftModels.get(i).getBranchRate(treeModel, node) * realTimeBranchLength;
355 }
356 return drift;
357 } else {
358 throw new RuntimeException("getShiftForBranchLength should not be called.");
359 }
360 // But really should get values from driftModel.getBranchRate(treeModel, node);
361 }
362
363 public double[] getOptimalValue(NodeRef node) {
364 if (optimalValues != null) {
365 final int dim = optimalValues.size();
366 double[] optVals = new double[dim];
367 for (int i = 0; i < dim; ++i) {
368 optVals[i] = optimalValues.get(i).getBranchRate(treeModel, node);
369 }
370 return optVals;
371 } else {
372 throw new RuntimeException("getOptimalValue should not be called.");
373 }
374 }
375
376
377 public double getTimeScaledSelection(NodeRef node) {
378 if (strengthOfSelection != null) {
379 double selection;
380 double realTimeBranchLength = treeModel.getBranchLength(node);
381 selection = strengthOfSelection.getBranchRate(treeModel, node) * realTimeBranchLength;
382 return selection;
383 } else {
384 throw new RuntimeException("getTimeScaledSelection should not be called.");
385 }
386 }
387
388 protected double rescaleLength(double length) {
389 if (scaleByTime) {
390 length /= treeLength;
391 }
392 return length;
393 }
394
395 public double getRescaledBranchLengthForPrecision(NodeRef node) {
396
397 double length = treeModel.getBranchLength(node);
398
399 if (hasBranchRateModel) {
400 if (reciprocalRates) {
401 length /= branchRateModel.getBranchRate(treeModel, node); // branch rate scales as precision (inv-time)
402 } else {
403 length *= branchRateModel.getBranchRate(treeModel, node); // branch rate scales as variance (time)
404 }
405 }
406
407 // if (scaleByTime) {
408 // length /= treeLength;
409 // }
410 length = rescaleLength(length);
411
412 if (deltaParameter != null && treeModel.isExternal(node)) {
413 length += deltaParameter.getParameterValue(0);
414 }
415 //System.err.println("Node Number: " + node.getNumber());
416
417 //System.err.println("Trait value" + traitParameter.getParameterValue(0));
418 //System.err.println("Trait value" + traitParameter.getParameterValue(1));
419 // System.err.println("Trait value" + traitParameter.getParameterValue(2));
420 // System.err.println("Trait value" + traitParameter.getParameterValue(3));
421
422 // System.err.println("branch length: " + treeModel.getBranchLength(node));
423 // System.err.println("rate: " + branchRateModel.getBranchRate(treeModel,node));
424 return length;
425 }
426
427 // **************************************************************
428 // ModelListener IMPLEMENTATION
429 // **************************************************************
430
431 protected void handleModelChangedEvent(Model model, Object object, int index) {
432
433 if (!cacheBranches) {
434 likelihoodKnown = false;
435 updateRestrictedNodePartials = true;
436 if (model == treeModel)
437 recalculateTreeLength();
438 return;
439 }
440
441 if (model == diffusionModel) {
442 updateAllNodes();
443 }
444
445 // fireTreeEvents sends two events here when a node trait is changed,
446 // ignoring object instance Parameter case
447
448 else if (model == treeModel) {
449 if (object instanceof TreeChangedEvent) {
450 TreeChangedEvent event = (TreeChangedEvent) object;
451 if (event.isTreeChanged()) {
452 recalculateTreeLength();
453 updateAllNodes();
454 updateRestrictedNodePartials = true;
455 } else if (event.isHeightChanged()) {
456 recalculateTreeLength();
457 if (useTreeLength || (scaleByTime && treeModel.isRoot(event.getNode())))
458 updateAllNodes();
459 else {
460 updateNodeAndChildren(event.getNode());
461 }
462 } else if (event.isNodeParameterChanged()) {
463 updateNodeAndChildren(event.getNode());
464 } else if (event.isNodeChanged()) {
465 recalculateTreeLength();
466 if (useTreeLength || (scaleByTime && treeModel.isRoot(event.getNode())))
467 updateAllNodes();
468 else {
469 updateNodeAndChildren(event.getNode());
470 }
471 updateRestrictedNodePartials = true;
472 } else {
473 throw new RuntimeException("Unexpected TreeModel TreeChangedEvent occurring in AbstractMultivariateTraitLikelihood");
474 }
475 } else if (object instanceof Parameter) {
476 // Ignoring
477 } else {
478 throw new RuntimeException("Unexpected object throwing events in AbstractMultivariateTraitLikelihood");
479 }
480 } else if (model == branchRateModel) {
481 if (index == -1) {
482 updateAllNodes();
483 } else {
484 if (object == null || ((Parameter) object).getDimension() == 2 * (treeModel.getNodeCount() - 1))
485 updateNode(treeModel.getNode(index)); // This is a branch specific update
486 else
487 updateAllNodes(); // Probably an epoch model
488 }
489 } else if (model instanceof RestrictedPartials) {
490 updateAllNodes();
491 updateRestrictedNodePartials = true;
492 } else {
493 throw new RuntimeException("Unknown componentChangedEvent");
494 }
495 }
496
497 protected void updateAllNodes() {
498 for (int i = 0; i < treeModel.getNodeCount(); i++)
499 validLogLikelihoods[i] = false;
500 likelihoodKnown = false;
501 }
502
503 private void updateNode(NodeRef node) {
504 validLogLikelihoods[node.getNumber()] = false;
505 likelihoodKnown = false;
506 }
507
508 private void updateNodeAndChildren(NodeRef node) {
509 validLogLikelihoods[node.getNumber()] = false;
510 for (int i = 0; i < treeModel.getChildCount(node); i++)
511 validLogLikelihoods[treeModel.getChild(node, i).getNumber()] = false;
512 likelihoodKnown = false;
513 }
514
515 protected double getTreeLength() {
516 double treeLength = 0;
517 for (int i = 0; i < treeModel.getNodeCount(); i++) {
518 NodeRef node = treeModel.getNode(i);
519 if (!treeModel.isRoot(node))
520 treeLength += treeModel.getBranchLength(node); // Bug was here
521 }
522 return treeLength;
523 }
524
525 public void recalculateTreeLength() {
526
527 if (!scaleByTime)
528 return;
529
530 if (useTreeLength) {
531 treeLength = getTreeLength();
532 } else { // Normalizing by tree height.
533 treeLength = treeModel.getNodeHeight(treeModel.getRoot());
534 }
535 }
536
537 public BranchRateModel getBranchRateModel() {
538 return branchRateModel;
539 }
540
541 // **************************************************************
542 // VariableListener IMPLEMENTATION
543 // **************************************************************
544
545 protected void handleVariableChangedEvent(Variable variable, int index, Parameter.ChangeType type) {
546 if (variable == deltaParameter) {
547 likelihoodKnown = false;
548 }
549
550 if (variable == traitParameter) {
551 likelihoodKnown = false;
552 }
553
554 // All parameter changes are handled first by the treeModel
555 if (!cacheBranches)
556 likelihoodKnown = false;
557 }
558
559 // **************************************************************
560 // Model IMPLEMENTATION
561 // **************************************************************
562
563 /**
564 * Stores the precalculated state: in this case the intervals
565 */
566 protected void storeState() {
567 storedLikelihoodKnown = likelihoodKnown;
568 storedLogLikelihood = logLikelihood;
569 storedTreeLength = treeLength;
570
571 if (cacheBranches) {
572 System.arraycopy(cachedLogLikelihoods, 0, storedCachedLogLikelihood, 0, treeModel.getNodeCount());
573 System.arraycopy(validLogLikelihoods, 0, storedValidLogLikelihoods, 0, treeModel.getNodeCount());
574 }
575 }
576
577 /**
578 * Restores the precalculated state: that is the intervals of the tree.
579 */
580 protected void restoreState() {
581 likelihoodKnown = storedLikelihoodKnown;
582 logLikelihood = storedLogLikelihood;
583 treeLength = storedTreeLength;
584
585 if (cacheBranches) {
586 double[] tmp = storedCachedLogLikelihood;
587 storedCachedLogLikelihood = cachedLogLikelihoods;
588 cachedLogLikelihoods = tmp;
589 boolean[] tmp2 = storedValidLogLikelihoods;
590 storedValidLogLikelihoods = validLogLikelihoods;
591 validLogLikelihoods = tmp2;
592 }
593 updateRestrictedNodePartials = true; // TODO remove or cache? Caching is still not working, see IMTL.restoreState()
594 }
595
596 protected void acceptState() {
597 } // nothing to do
598
599 public MutableTreeModel getTreeModel() {
600 return treeModel;
601 }
602
603 public String getTraitName() {
604 return traitName;
605 }
606
607 public MultivariateDiffusionModel getDiffusionModel() {
608 return diffusionModel;
609 }
610
611 // public boolean getInSubstitutionTime() {
612 // return inSubstitutionTime;
613 // }
614
615 // **************************************************************
616 // Likelihood IMPLEMENTATION
617 // **************************************************************
618
619 public Model getModel() {
620 return this;
621 }
622
623 public String toString() {
624 return getClass().getName() + "(" + getLogLikelihood() + ")";
625
626 }
627
628 public final double getLogLikelihood() {
629 if (!likelihoodKnown) {
630 logLikelihood = calculateLogLikelihood();
631 if (doAscertainmentCorrect) {
632 double correction = calculateAscertainmentCorrection(ascertainedTaxonIndex);
633 // System.err.println("Correction = " + correction);
634 logLikelihood -= correction;
635 }
636 likelihoodKnown = true;
637 }
638 return logLikelihood;
639 }
640
641 protected abstract double calculateAscertainmentCorrection(int taxonIndex);
642
643 public abstract double getLogDataLikelihood();
644
645 public void makeDirty() {
646 likelihoodKnown = false;
647 if (cacheBranches)
648 updateAllNodes();
649 }
650
651 public LogColumn[] getColumns() {
652 return new LogColumn[]{
653 new LikelihoodColumn(getId() + ".joint"),
654 new NumberColumn(getId() + ".data") {
655 public double getDoubleValue() {
656 return getLogDataLikelihood();
657 }
658 }
659 };
660 }
661
662 public abstract double calculateLogLikelihood();
663
664 // public double getMaxLogLikelihood() {
665 // return maxLogLikelihood;
666 // }
667
668
669 // **************************************************************
670 // Loggable IMPLEMENTATION
671 // **************************************************************
672
673 private TreeTrait[] treeTraits = null;
674
675 public TreeTrait[] getTreeTraits() {
676 if (treeTraits == null) {
677 final double[] trait = getRootNodeTrait();
678 if (trait.length == 1 || reportAsMultivariate) {
679 treeTraits = new TreeTrait[]{
680 new TreeTrait.DA() {
681 public String getTraitName() {
682 return traitName;
683 }
684
685 public Intent getIntent() {
686 return Intent.NODE;
687 }
688
689 public Class getTraitClass() {
690 return Double.class;
691 }
692
693 public double[] getTrait(Tree tree, NodeRef node) {
694 return getTraitForNode(tree, node, traitName);
695 }
696 }
697 };
698 } else {
699 throw new RuntimeException("Reporting of traits is only supported as multivariate");
700 }
701 }
702 return treeTraits;
703 }
704
705 public TreeTrait getTreeTrait(String key) {
706 TreeTrait[] tts = getTreeTraits();
707 for (TreeTrait tt : tts) {
708 if (tt.getTraitName().equals(key)) {
709 return tt;
710 }
711 }
712 return null;
713 }
714
715 public final int getNumData() {
716 return numData;
717 }
718
719 public final int getDimTrait() {
720 return dimTrait;
721 }
722
723 protected double[] getRootNodeTrait() {
724 return treeModel.getMultivariateNodeTrait(treeModel.getRoot(), traitName);
725 }
726
727 public abstract double[] getTraitForNode(Tree tree, NodeRef node, String traitName);
728
729 public void check(Parameter trait) throws XMLParseException {
730 diffusionModel.check(trait);
731 }
732
733 // **************************************************************
734 // XMLElement IMPLEMENTATION
735 // **************************************************************
736
737 public Element createElement(Document d) {
738 throw new RuntimeException("Not implemented yet!");
739 }
740
741 // **************************************************************
742 // XMLObjectParser
743 // **************************************************************
744
745 public static XMLObjectParser PARSER = new AbstractXMLObjectParser() {
746
747 public String getParserName() {
748 return TRAIT_LIKELIHOOD;
749 }
750
751 public Object parseXMLObject(XMLObject xo) throws XMLParseException {
752
753 MultivariateDiffusionModel diffusionModel = (MultivariateDiffusionModel) xo.getChild(MultivariateDiffusionModel.class);
754 MutableTreeModel treeModel = (MutableTreeModel) xo.getChild(MutableTreeModel.class);
755
756 boolean cacheBranches = xo.getAttribute(CACHE_BRANCHES, true);
757 boolean integrate = xo.getAttribute(INTEGRATE, false);
758 boolean useTreeLength = xo.getAttribute(USE_TREE_LENGTH, false);
759 boolean scaleByTime = xo.getAttribute(SCALE_BY_TIME, false);
760 boolean reciprocalRates = xo.getAttribute(RECIPROCAL_RATES, false);
761 boolean reportAsMultivariate = xo.getAttribute(REPORT_MULTIVARIATE, true);
762 boolean standardizeTraits = xo.getAttribute(STANDARDIZE_TRAITS, false);
763
764 BranchRateModel rateModel = (BranchRateModel) xo.getChild(BranchRateModel.class);
765
766 List<BranchRateModel> driftModels = parseDriftModels(xo, diffusionModel);
767
768 List<BranchRateModel> optimalValues = null;
769 BranchRateModel strengthOfSelection = null;
770
771 if (xo.hasChildNamed(OPTIMAL_TRAITS)) {
772 optimalValues = new ArrayList<BranchRateModel>();
773 XMLObject cxo = xo.getChild(OPTIMAL_TRAITS);
774 final int numberModels = cxo.getChildCount();
775 if (numberModels != diffusionModel.getPrecisionmatrix().length) {
776 throw new XMLParseException("Wrong number of optimal trait models (" + numberModels + ") for a trait of" +
777 " dimension " + diffusionModel.getPrecisionmatrix().length + " in " + xo.getId()
778 );
779 }
780 for (int i = 0; i < numberModels; ++i) {
781 optimalValues.add((BranchRateModel) cxo.getChild(i));
782 }
783 }
784
785 if (xo.hasChildNamed(STRENGTH_OF_SELECTION)) {
786 XMLObject cxo = xo.getChild(STRENGTH_OF_SELECTION);
787 strengthOfSelection = (BranchRateModel) cxo.getChild(BranchRateModel.class);
788 }
789
790 TreeTraitParserUtilities utilities = new TreeTraitParserUtilities();
791 String traitName = TreeTraitParserUtilities.DEFAULT_TRAIT_NAME;
792
793 TreeTraitParserUtilities.TraitsAndMissingIndices returnValue =
794 utilities.parseTraitsFromTaxonAttributes(xo, traitName, treeModel, integrate);
795 CompoundParameter traitParameter = returnValue.traitParameter;
796 List<Integer> missingIndices = returnValue.missingIndices;
797 traitName = returnValue.traitName;
798
799 /* TODO Add partially integrated traits here */
800
801 Model samplingDensity = null;
802
803 if (xo.hasChildNamed(SAMPLING_DENSITY)) {
804 XMLObject cxo = xo.getChild(SAMPLING_DENSITY);
805 samplingDensity = (Model) cxo.getChild(Model.class);
806 }
807
808 Parameter deltaParameter = null;
809 if (xo.hasChildNamed("delta")) {
810 XMLObject cxo = xo.getChild("delta");
811 deltaParameter = (Parameter) cxo.getChild(Parameter.class);
812 }
813
814
815 if (standardizeTraits) {
816 // standardize(traitParameter);
817 // dimTrait = diffusionModel.getPrecisionmatrix().length;
818 // dim = traitParameter != null ? traitParameter.getParameter(0).getDimension() : 0;
819 // numData = dim / dimTrait;
820
821 // System.err.println(traitParameter.getDimension());
822 // System.err.println(traitParameter.getParameterCount());
823 // System.err.println(traitParameter.getParameter(0).getDimension());
824 // System.exit(-1);
825 int numTraits = traitParameter.getParameter(0).getDimension();
826 int numObservations = traitParameter.getParameterCount();
827
828 StringBuilder sb = new StringBuilder();
829 sb.append("Traits have been standardized. Use following to transform values back to original scale.\n");
830 for (int trait = 0; trait < numTraits; ++trait) {
831 double[] values = new double[numObservations];
832 for (int obs = 0; obs < numObservations; ++obs) {
833 values[obs] = traitParameter.getParameter(obs).getParameterValue(trait);
834 }
835
836 double traitMean = DiscreteStatistics.mean(values);
837 double traitSD = Math.sqrt(DiscreteStatistics.variance(values, traitMean));
838
839 sb.append("\tDimension " + (trait + 1) + ": multiply by " + traitSD + " then add " + traitMean + "\n");
840
841 for (int obs = 0; obs < numObservations; ++obs) {
842 traitParameter.getParameter(obs).setParameterValue(trait,
843 (values[obs] - traitMean) / traitSD);
844 }
845 }
846
847 Logger.getLogger("dr.evomodel").info(sb.toString());
848
849 }
850
851 List<RestrictedPartials> restrictedPartialsList = parseRestrictedPartials(xo, integrate);
852
853 AbstractMultivariateTraitLikelihood like;
854
855 if (integrate) {
856
857 MultivariateDistributionLikelihood rootPrior =
858 (MultivariateDistributionLikelihood) xo.getChild(MultivariateDistributionLikelihood.class);
859 if (rootPrior != null) {
860
861 if (!(rootPrior.getDistribution() instanceof MultivariateDistribution))
862 throw new XMLParseException("Only multivariate normal priors allowed for Gibbs sampling the root trait");
863
864 MultivariateNormalDistribution rootDistribution =
865 (MultivariateNormalDistribution) rootPrior.getDistribution();
866
867 like = new SemiConjugateMultivariateTraitLikelihood(traitName, treeModel, diffusionModel,
868 traitParameter, missingIndices, cacheBranches,
869 scaleByTime, useTreeLength, rateModel, samplingDensity, reportAsMultivariate,
870 rootDistribution, reciprocalRates, restrictedPartialsList);
871
872 // like = new DebugableIntegratedMultivariateTraitLikelihood(traitName, treeModel, diffusionModel,
873 // traitParameter, missingIndices, cacheBranches,
874 // scaleByTime, useTreeLength, rateModel, samplingDensity, reportAsMultivariate,
875 // rootDistribution, reciprocalRates);
876 } else {
877 XMLObject cxo = xo.getChild(CONJUGATE_ROOT_PRIOR);
878 if (cxo == null) {
879 throw new XMLParseException("Must specify a conjugate or multivariate normal root prior");
880 }
881
882 boolean ignorePhylogeny = xo.getAttribute(IGNORE_PHYLOGENY, false);
883
884 Parameter meanParameter = (Parameter) cxo.getChild(MultivariateDistributionLikelihood.MVN_MEAN)
885 .getChild(Parameter.class);
886
887 if (meanParameter.getDimension() != diffusionModel.getPrecisionmatrix().length) {
888 throw new XMLParseException("Root prior mean dimension does not match trait diffusion dimension");
889 }
890
891 Parameter sampleSizeParameter = (Parameter) cxo.getChild(PRIOR_SAMPLE_SIZE).getChild(Parameter.class);
892
893 double[] mean = meanParameter.getParameterValues();
894 double pseudoObservations = sampleSizeParameter.getParameterValue(0);
895
896 if (ignorePhylogeny) {
897 boolean exchangeableTips = xo.getAttribute(EXCHANGEABLE_TIPS, true);
898
899 like = new NonPhylogeneticMultivariateTraitLikelihood(traitName, treeModel, diffusionModel,
900 traitParameter, deltaParameter, missingIndices, cacheBranches,
901 scaleByTime, useTreeLength, rateModel, samplingDensity, reportAsMultivariate,
902 mean, pseudoObservations, restrictedPartialsList, reciprocalRates, exchangeableTips);
903 } else {
904 if (driftModels == null) {
905 if (strengthOfSelection == null) {
906 like = new FullyConjugateMultivariateTraitLikelihood(traitName, treeModel, diffusionModel,
907 traitParameter, deltaParameter, missingIndices, cacheBranches,
908 scaleByTime, useTreeLength,
909 rateModel, null, null, null,
910 samplingDensity, reportAsMultivariate,
911 mean, restrictedPartialsList, pseudoObservations, reciprocalRates);
912 } else {
913 like = new FullyConjugateMultivariateTraitLikelihood(traitName, treeModel, diffusionModel,
914 traitParameter, deltaParameter, missingIndices, cacheBranches,
915 scaleByTime, useTreeLength,
916 rateModel, null, optimalValues, strengthOfSelection,
917 samplingDensity, reportAsMultivariate,
918 mean, restrictedPartialsList,pseudoObservations, reciprocalRates);
919 }
920 } else {
921 like = new FullyConjugateMultivariateTraitLikelihood(traitName, treeModel, diffusionModel,
922 traitParameter, deltaParameter, missingIndices, cacheBranches,
923 scaleByTime, useTreeLength,
924 rateModel, driftModels, null, null,
925 samplingDensity, reportAsMultivariate,
926 mean, restrictedPartialsList, pseudoObservations, reciprocalRates);
927 }
928 }
929 }
930 } else {
931
932 like = new SampledMultivariateTraitLikelihood(traitName, treeModel, diffusionModel,
933 traitParameter, missingIndices, cacheBranches,
934 scaleByTime, useTreeLength, rateModel, samplingDensity, reportAsMultivariate,
935 reciprocalRates);
936 }
937
938 if (!integrate && xo.hasChildNamed(TreeTraitParserUtilities.RANDOMIZE)) {
939 utilities.randomize(xo);
940 }
941
942 if (xo.hasChildNamed(TreeTraitParserUtilities.JITTER)) {
943 utilities.jitter(xo, diffusionModel.getPrecisionmatrix().length, missingIndices);
944 }
945
946 if (xo.hasChildNamed(CHECK)) {
947 XMLObject cxo = xo.getChild(CHECK);
948 Parameter check = (Parameter) cxo.getChild(Parameter.class);
949 like.check(check);
950 }
951
952 boolean isRRW = (rateModel != null) && (!(rateModel instanceof StrictClockBranchRates));
953
954 if (!xo.hasAttribute(TreeTraitParserUtilities.ALLOW_IDENTICAL) &&
955 isRRW &&
956 utilities.hasIdenticalTraits(traitParameter, missingIndices, diffusionModel.getPrecisionmatrix().length)) {
957 throw new XMLParseException("For multivariate trait analyses, all trait values should be unique.\n" +
958 "Check data or add random noise using 'jitter' option.");
959 }
960
961 if (xo.hasChildNamed(ASCERTAINMENT)) {
962 XMLObject cxo = xo.getChild(ASCERTAINMENT);
963 Taxon taxon = (Taxon) cxo.getChild(Taxon.class);
964 if (!integrate) {
965 throw new XMLParseException("Ascertainment correction is currently only implemented" +
966 " for integrated multivariate trait likelihood models");
967 }
968 like.setAscertainedTaxon(taxon);
969 }
970
971 return like;
972 }
973
974 //************************************************************************
975 // AbstractXMLObjectParser implementation
976 //************************************************************************
977
978 public String getParserDescription() {
979 return "Provides the likelihood of a continuous trait evolving on a tree by a " +
980 "given diffusion model.";
981 }
982
983 public XMLSyntaxRule[] getSyntaxRules() {
984 return rules;
985 }
986
987 private final XMLSyntaxRule[] rules = {
988 new StringAttributeRule(TreeTraitParserUtilities.TRAIT_NAME, "The name of the trait for which a likelihood should be calculated"),
989 new ElementRule(TreeTraitParserUtilities.TRAIT_PARAMETER, new XMLSyntaxRule[]{
990 new ElementRule(Parameter.class)
991 }),
992 new ElementRule("delta", new XMLSyntaxRule[]{
993 new ElementRule(Parameter.class)
994 }, true),
995 AttributeRule.newBooleanRule(INTEGRATE, true),
996 // new XORRule(
997 new ElementRule(MultivariateDistributionLikelihood.class, true),
998 new ElementRule(CONJUGATE_ROOT_PRIOR, new XMLSyntaxRule[]{
999 new ElementRule(MultivariateDistributionLikelihood.MVN_MEAN,
1000 new XMLSyntaxRule[]{new ElementRule(Parameter.class)}),
1001 new ElementRule(PRIOR_SAMPLE_SIZE,
1002 new XMLSyntaxRule[]{new ElementRule(Parameter.class)}),
1003 }, true),
1004 // true),
1005 new ElementRule(ASCERTAINMENT, new XMLSyntaxRule[]{
1006 new ElementRule(Taxon.class)
1007 }, true),
1008 new ElementRule(MultivariateDiffusionModel.class),
1009 new ElementRule(MutableTreeModel.class),
1010 new ElementRule(BranchRateModel.class, true),
1011 AttributeRule.newDoubleArrayRule("cut", true),
1012 AttributeRule.newBooleanRule(REPORT_MULTIVARIATE, true),
1013 AttributeRule.newBooleanRule(USE_TREE_LENGTH, true),
1014 AttributeRule.newBooleanRule(SCALE_BY_TIME, true),
1015 AttributeRule.newBooleanRule(RECIPROCAL_RATES, true),
1016 AttributeRule.newBooleanRule(CACHE_BRANCHES, true),
1017 AttributeRule.newIntegerRule(RANDOM_SAMPLE, true),
1018 AttributeRule.newBooleanRule(IGNORE_PHYLOGENY, true),
1019 AttributeRule.newBooleanRule(EXCHANGEABLE_TIPS, true),
1020 AttributeRule.newBooleanRule(TreeTraitParserUtilities.SAMPLE_MISSING_TRAITS, true),
1021 new ElementRule(Parameter.class, true),
1022 TreeTraitParserUtilities.randomizeRules(true),
1023 TreeTraitParserUtilities.jitterRules(true),
1024 new ElementRule(CHECK, new XMLSyntaxRule[]{
1025 new ElementRule(Parameter.class)
1026 }, true),
1027 new ElementRule(DRIFT_MODELS, new XMLSyntaxRule[]{
1028 new ElementRule(BranchRateModel.class, 1, Integer.MAX_VALUE),
1029 }, true),
1030 new ElementRule(RestrictedPartials.class, 0, Integer.MAX_VALUE),
1031 };
1032
1033
1034 public Class getReturnType() {
1035 return AbstractMultivariateTraitLikelihood.class;
1036 }
1037 };
1038
1039
1040 public static List<BranchRateModel> parseDriftModels(XMLObject xo,
1041 MultivariateDiffusionModel diffusionModel)
1042 throws XMLParseException {
1043
1044 List<BranchRateModel> driftModels = null;
1045
1046 if (xo.hasChildNamed(DRIFT_MODELS)) {
1047 driftModels = new ArrayList<BranchRateModel>();
1048 XMLObject cxo = xo.getChild(DRIFT_MODELS);
1049
1050 final int number = cxo.getChildCount();
1051
1052 if (number != diffusionModel.getPrecisionmatrix().length) {
1053 throw new XMLParseException("Wrong number of drift models (" + number + ") for a trait of" +
1054 " dimension " + diffusionModel.getPrecisionmatrix().length + " in " + xo.getId()
1055 );
1056 }
1057
1058 for (int i = 0; i < number; ++i) {
1059 driftModels.add((BranchRateModel) cxo.getChild(i));
1060 }
1061
1062 }
1063 return driftModels;
1064 }
1065
1066 public static List<RestrictedPartials> parseRestrictedPartials(XMLObject xo, boolean integrate)
1067 throws XMLParseException {
1068
1069 List<RestrictedPartials> restrictedPartialsList = null;
1070 for (int i = 0; i < xo.getChildCount(); ++i) {
1071 Object cxo = xo.getChild(i);
1072
1073 if (cxo instanceof RestrictedPartials) {
1074 if (!integrate) {
1075 throw new XMLParseException("Restricted partials are currently only implements" +
1076 "for integrated multivariate trait likelihood models");
1077 }
1078 if (restrictedPartialsList == null) {
1079 restrictedPartialsList = new ArrayList<RestrictedPartials>();
1080 }
1081 restrictedPartialsList.add((RestrictedPartials) cxo);
1082 }
1083 }
1084 return restrictedPartialsList;
1085 }
1086
1087 protected void addRestrictedPartials(RestrictedPartials restrictedPartials) {
1088 throw new IllegalArgumentException("Not implemented for this model type");
1089 }
1090
1091 MutableTreeModel treeModel = null;
1092 MultivariateDiffusionModel diffusionModel = null;
1093 String traitName = null;
1094 CompoundParameter traitParameter;
1095 List<Integer> missingIndices;
1096
1097 protected double logLikelihood;
1098 protected double maxLogLikelihood = Double.NEGATIVE_INFINITY;
1099 private double storedLogLikelihood;
1100 protected boolean likelihoodKnown = false;
1101 private boolean storedLikelihoodKnown = false;
1102 protected List<BranchRateModel> driftModels = null;
1103 protected List<BranchRateModel> optimalValues = null;
1104 protected BranchRateModel strengthOfSelection = null;
1105 private boolean hasBranchRateModel = false;
1106
1107 private double treeLength;
1108 private double storedTreeLength;
1109
1110 private final boolean reportAsMultivariate;
1111
1112 private final boolean scaleByTime;
1113 private final boolean useTreeLength;
1114 private final boolean reciprocalRates;
1115
1116 protected boolean cacheBranches;
1117 protected double[] cachedLogLikelihoods;
1118 protected double[] storedCachedLogLikelihood;
1119 protected boolean[] validLogLikelihoods;
1120 protected boolean[] storedValidLogLikelihoods;
1121
1122 private final Parameter deltaParameter;
1123
1124 private boolean doAscertainmentCorrect = false;
1125 private int ascertainedTaxonIndex;
1126
1127 protected int numData;
1128 protected int dimTrait;
1129 protected int dim;
1130
1131 protected boolean updateRestrictedNodePartials = true;
1132 protected boolean savedUpdateRestrictedNodePartials;
1133 // protected Map<BitSet, RestrictedPartials> restrictedPartialsMap;
1134 }
1135