Debian Codegraph @

src/dr/evomodel/treelikelihood/MarkovJumpsBeagleTreeLikelihood.java

raw symbols SCIP
1 /*
2 * MarkovJumpsBeagleTreeLikelihood.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 dr.evomodel.branchmodel.BranchModel;
29 import dr.evomodel.siteratemodel.SiteRateModel;
30 import dr.evomodel.substmodel.MarkovJumpsSubstitutionModel;
31 import dr.evomodel.substmodel.SubstitutionModel;
32 import dr.evomodel.substmodel.UniformizedSubstitutionModel;
33 import dr.evolution.alignment.PatternList;
34 import dr.evolution.datatype.DataType;
35 import dr.evolution.tree.NodeRef;
36 import dr.evolution.tree.Tree;
37 import dr.evolution.tree.TreeTrait;
38 import dr.evomodel.branchratemodel.BranchRateModel;
39 import dr.evomodel.tree.TreeModel;
40 import dr.evomodel.tipstatesmodel.TipStatesModel;
41 import dr.inference.loggers.LogColumn;
42 import dr.inference.loggers.NumberColumn;
43 import dr.inference.markovjumps.MarkovJumpsRegisterAcceptor;
44 import dr.inference.markovjumps.MarkovJumpsType;
45 import dr.inference.model.Parameter;
46 import dr.inference.model.Variable;
47 import dr.util.Citation;
48 import dr.util.CommonCitations;
49
50 import java.util.*;
51
52 /**
53 * @author Marc Suchard
54 * @author Vladimir Minin
55 * <p/>
56 * A base class for implementing Markov chain-induced counting processes (markovjumps) in BEAST using BEAGLE
57 * This work is supported by NSF grant 0856099
58 * <p/>
59 * Minin VN and Suchard MA (2008) Counting labeled transitions in continous-time Markov models of evolution.
60 * Journal of Mathematical Biology, 56, 391-412.
61 */
62 public class MarkovJumpsBeagleTreeLikelihood extends AncestralStateBeagleTreeLikelihood
63 implements MarkovJumpsRegisterAcceptor, MarkovJumpsTraitProvider {
64
65 public MarkovJumpsBeagleTreeLikelihood(PatternList patternList, TreeModel treeModel,
66 BranchModel branchModel,
67 SiteRateModel siteRateModel,
68 BranchRateModel branchRateModel,
69 TipStatesModel tipStatesModel,
70 boolean useAmbiguities,
71 PartialsRescalingScheme scalingScheme,
72 boolean delayScaling,
73 Map<Set<String>, Parameter> partialsRestrictions,
74 DataType dataType, String stateTag,
75 boolean useMAP,
76 boolean returnMarginalLikelihood,
77 boolean useUniformization,
78 boolean reportUnconditionedColumns,
79 int nSimulants) {
80
81 super(patternList, treeModel, branchModel, siteRateModel, branchRateModel, tipStatesModel, useAmbiguities,
82 scalingScheme, delayScaling, partialsRestrictions, dataType, stateTag, useMAP, returnMarginalLikelihood);
83
84 this.useUniformization = useUniformization;
85 this.reportUnconditionedColumns = reportUnconditionedColumns;
86 this.nSimulants = nSimulants;
87
88 markovjumps = new ArrayList<MarkovJumpsSubstitutionModel>();
89 branchModelNumber = new ArrayList<Integer>();
90 registerParameter = new ArrayList<Parameter>();
91 jumpTag = new ArrayList<String>();
92 expectedJumps = new ArrayList<double[][]>();
93 // storedExpectedJumps = new ArrayList<double[][]>();
94
95 tmpProbabilities = new double[stateCount * stateCount * categoryCount];
96 condJumps = new double[categoryCount][stateCount * stateCount];
97 }
98
99 public void addRegister(Parameter addRegisterParameter,
100 MarkovJumpsType type,
101 boolean scaleByTime) {
102
103 if ((type == MarkovJumpsType.COUNTS &&
104 addRegisterParameter.getDimension() != stateCount * stateCount) ||
105 (type == MarkovJumpsType.REWARDS &&
106 addRegisterParameter.getDimension() != stateCount)
107 ) {
108 throw new RuntimeException("Register parameter of wrong dimension");
109 }
110 addVariable(addRegisterParameter);
111 final String tag = addRegisterParameter.getId();
112
113 for (int i = 0; i < substitutionModelDelegate.getSubstitutionModelCount(); ++i) {
114
115 registerParameter.add(addRegisterParameter);
116 MarkovJumpsSubstitutionModel mjModel;
117 SubstitutionModel substitutionModel = substitutionModelDelegate.getSubstitutionModel(i);
118
119 if (useUniformization) {
120 mjModel = new UniformizedSubstitutionModel(substitutionModel, type, nSimulants);
121 } else {
122 if (type == MarkovJumpsType.HISTORY) {
123 throw new RuntimeException("Can only report complete history using uniformization");
124 }
125 mjModel = new MarkovJumpsSubstitutionModel(substitutionModel, type);
126 }
127 markovjumps.add(mjModel);
128 branchModelNumber.add(i);
129 addModel(mjModel);
130 setupRegistration(numRegisters);
131
132 String traitName;
133
134 if (substitutionModelDelegate.getSubstitutionModelCount() == 1) {
135 traitName = tag;
136 } else {
137 traitName = tag + i;
138 }
139
140 jumpTag.add(traitName);
141
142 expectedJumps.add(new double[treeModel.getNodeCount()][patternCount]);
143 // storedExpectedJumps.add(new double[treeModel.getNodeCount()][patternCount]);
144
145 boolean[] oldScaleByTime = this.scaleByTime;
146 int oldScaleByTimeLength = (oldScaleByTime == null ? 0 : oldScaleByTime.length);
147 this.scaleByTime = new boolean[oldScaleByTimeLength + 1];
148 if (oldScaleByTimeLength > 0) {
149 System.arraycopy(oldScaleByTime, 0, this.scaleByTime, 0, oldScaleByTimeLength);
150 }
151 this.scaleByTime[oldScaleByTimeLength] = scaleByTime;
152
153 if (type != MarkovJumpsType.HISTORY) {
154
155
156 TreeTrait.DA da = new TreeTrait.DA() {
157
158 final int registerNumber = numRegisters;
159
160 public String getTraitName() {
161 return tag;
162 }
163
164 public Intent getIntent() {
165 return Intent.BRANCH;
166 }
167
168 public double[] getTrait(Tree tree, NodeRef node) {
169 return getMarkovJumpsForNodeAndRegister(tree, node, registerNumber);
170 }
171 };
172
173 treeTraits.addTrait(traitName + "_base", da);
174
175 treeTraits.addTrait(addRegisterParameter.getId(),
176 new TreeTrait.SumAcrossArrayD(
177 new TreeTrait.SumOverTreeDA(da)));
178
179 } else {
180 if (histories == null) {
181 histories = new String[treeModel.getNodeCount()][patternCount];
182 } else {
183 throw new RuntimeException("Only one complete history per markovJumpTreeLikelihood is allowed");
184 }
185 if (nSimulants > 1) {
186 throw new RuntimeException("Only one simulant allowed when saving complete history");
187 }
188
189 // Add total number of changes over tree trait
190 TreeTrait da = new TreeTrait.DA() {
191
192 final int registerNumber = numRegisters;
193
194 public String getTraitName() {
195 return tag;
196 }
197
198 public Intent getIntent() {
199 return Intent.BRANCH;
200 }
201
202 public double[] getTrait(Tree tree, NodeRef node) {
203 return getMarkovJumpsForNodeAndRegister(tree, node, registerNumber);
204 }
205 };
206
207 treeTraits.addTrait(addRegisterParameter.getId(), new TreeTrait.SumOverTreeDA(da));
208
209 historyRegisterNumber = numRegisters; // Record the complete history for this register
210 ((UniformizedSubstitutionModel) mjModel).setSaveCompleteHistory(true);
211
212 if (useCompactHistory && logHistory) {
213
214 treeTraits.addTrait(ALL_HISTORY, new TreeTrait.SA() {
215 public String getTraitName() {
216 return ALL_HISTORY;
217 }
218
219 public Intent getIntent() {
220 return Intent.BRANCH;
221 }
222
223 public boolean getFormatAsArray() {
224 return true;
225 }
226
227 public String[] getTrait(Tree tree, NodeRef node) {
228
229 List<String> events = new ArrayList<String>();
230 for (int i = 0; i < patternCount; i++) {
231 String eventString = getHistoryForNode(tree, node, i);
232 if (eventString != null && eventString.compareTo("{}") != 0) {
233 eventString = eventString.substring(1, eventString.length() - 1);
234 if (eventString.contains("},{")) { // There are multiple events
235 String[] elements = eventString.split("(?<=\\}),(?=\\{)");
236 for (String e : elements) {
237 events.add(e);
238 }
239 } else {
240 events.add(eventString);
241 }
242 }
243 }
244 String[] array = new String[events.size()];
245 events.toArray(array);
246 return array;
247 }
248
249 public boolean getLoggable() {
250 return true;
251 }
252 });
253 }
254
255 for (int site = 0; site < patternCount; ++site) {
256
257 final String anonName = (patternCount == 1) ? HISTORY : HISTORY + "_" + (site + 1);
258 final int anonSite = site;
259
260 treeTraits.addTrait(anonName, new TreeTrait.S() {
261
262 public String getTraitName() {
263 return anonName;
264 }
265
266 public Intent getIntent() {
267 return Intent.BRANCH;
268 }
269
270 public String getTrait(Tree tree, NodeRef node) {
271 String history = getHistoryForNode(tree, node, anonSite);
272 return (history.compareTo("{}") != 0) ? history : null; // Return null if empty
273 }
274
275 public boolean getLoggable() {
276 return logHistory && !useCompactHistory;
277 }
278 });
279 }
280 }
281
282 numRegisters++;
283
284 } // End of loop over branch models
285 }
286
287 public void setLogHistories(boolean in) {
288 logHistory = in;
289 }
290
291 public void setUseCompactHistory(boolean in) {
292 useCompactHistory = in;
293 }
294
295 // public double[] getRewardsForNodeAndPattern(Tree tree, NodeRef node, int pattern) {
296 // double[] rtn = new double[numRegisters];
297 // for (int r = 0; r < numRegisters; r++) {
298 // double[] mjs = getMarkovJumpsForNodeAndRegister(tree, node, r);
299 // rtn[r] = mjs[pattern];
300 // }
301 // return rtn;
302 // }
303
304
305 public double[] getMarkovJumpsForNodeAndRegister(Tree tree, NodeRef node, int whichRegister) {
306 return getMarkovJumpsForRegister(tree, whichRegister)[node.getNumber()];
307 }
308
309 // public double[][] getMarkovJumpsForNode(Tree tree, NodeRef node) {
310 // double[][] rtn = new double[numRegisters][];
311 // for (int r = 0; r < numRegisters; r++) {
312 // rtn[r] = getMarkovJumpsForNodeAndRegister(tree, node, r);
313 // }
314 // return rtn;
315 // }
316
317 private void refresh(Tree tree) {
318 if (tree != treeModel) {
319 throw new RuntimeException("Must call with internal tree");
320 }
321
322 if (!likelihoodKnown) {
323 calculateLogLikelihood();
324 likelihoodKnown = true;
325 }
326
327 if (!areStatesRedrawn) {
328 redrawAncestralStates();
329 }
330 }
331
332 public double[][] getMarkovJumpsForRegister(Tree tree, int whichRegister) {
333 refresh(tree);
334 return expectedJumps.get(whichRegister);
335 }
336
337 public String getHistoryForNode(Tree tree, NodeRef node, int site) {
338 return getHistory(tree)[node.getNumber()][site];
339 }
340
341 public String[][] getHistory(Tree tree) {
342 refresh(tree);
343 return histories;
344 }
345
346 // private static String formattedValue(double[] values) {
347 // double total = 0;
348 // for (double summant : values) {
349 // total += summant;
350 // }
351 // return Double.toString(total); // Currently return the sum across sites
352 // }
353
354 private void setupRegistration(int whichRegistration) {
355
356 double[] registration = registerParameter.get(whichRegistration).getParameterValues();
357 markovjumps.get(whichRegistration).setRegistration(registration);
358 areStatesRedrawn = false;
359 }
360
361 protected void handleVariableChangedEvent(Variable variable, int index, Parameter.ChangeType type) {
362 for (int r = 0; r < numRegisters; r++) {
363 if (variable == registerParameter.get(r)) {
364 setupRegistration(r);
365 return;
366 }
367 }
368 super.handleVariableChangedEvent(variable, index, type);
369 }
370
371 protected void hookCalculation(Tree tree, NodeRef parentNode, NodeRef childNode,
372 int[] parentStates, int[] childStates,
373 double[] inProbabilities, int[] rateCategory) {
374
375 final int childNum = childNode.getNumber();
376
377 double[] probabilities = inProbabilities;
378 if (probabilities == null) { // Leaf will call this hook with a null
379 getMatrix(childNum, tmpProbabilities);
380 probabilities = tmpProbabilities;
381 }
382
383 final double branchRate = branchRateModel.getBranchRate(tree, childNode);
384 final double parentTime = tree.getNodeHeight(parentNode);
385 final double childTime = tree.getNodeHeight(childNode);
386 final double substTime = parentTime - childTime;
387
388 for (int r = 0; r < markovjumps.size(); r++) {
389 MarkovJumpsSubstitutionModel thisMarkovJumps = markovjumps.get(r);
390
391 final int modelNumberFromrRegistry = branchModelNumber.get(r);
392 // int dummy = 0;
393 // final int modelNumberFromTree = branchSubstitutionModel.getBranchIndex(tree, childNode, dummy);
394 // @todo AR - not sure about this - if this is an epoch this is just going to get the most
395 // @todo tipward model for the branch. I think this was what was happening before (in comment,
396 // @todo above).
397 BranchModel.Mapping mapping = branchModel.getBranchModelMapping(childNode);
398
399 if (modelNumberFromrRegistry == mapping.getOrder()[0]) {
400 if (useUniformization) {
401 computeSampledMarkovJumpsForBranch(((UniformizedSubstitutionModel) thisMarkovJumps), substTime,
402 branchRate, childNum, parentStates, childStates, parentTime, childTime, probabilities, scaleByTime[r],
403 expectedJumps.get(r), rateCategory, r == historyRegisterNumber);
404 } else {
405 computeIntegratedMarkovJumpsForBranch(thisMarkovJumps, substTime, branchRate, childNum, parentStates,
406 childStates, probabilities, condJumps, scaleByTime[r], expectedJumps.get(r), rateCategory);
407 }
408 } else {
409 // Fill with zeros
410 double[] result = expectedJumps.get(r)[childNum];
411 Arrays.fill(result, 0.0);
412 }
413 }
414 }
415
416 private void computeSampledMarkovJumpsForBranch(UniformizedSubstitutionModel thisMarkovJumps,
417 double substTime,
418 double branchRate,
419 int childNum,
420 int[] parentStates,
421 int[] childStates,
422 double parentTime,
423 double childTime,
424 double[] probabilities,
425 boolean scaleByTime,
426 double[][] thisExpectedJumps,
427 int[] rateCategory,
428 boolean saveHistory) {
429
430
431 // Fill condJumps with sampled values for this branch for each site
432 for (int j = 0; j < patternCount; j++) {
433 final int category = rateCategory == null ? 0 : rateCategory[j];
434 final double categoryRate = siteRateModel.getRateForCategory(category);
435 final int matrixIndex = category * stateCount * stateCount;
436 double value = thisMarkovJumps.computeCondStatMarkovJumps(
437 parentStates[j],
438 childStates[j],
439 substTime * branchRate * categoryRate,
440 probabilities[matrixIndex + parentStates[j] * stateCount + childStates[j]]
441 );
442 if (scaleByTime) {
443 value /= branchRate * categoryRate;
444 }
445 thisExpectedJumps[childNum][j] = value;
446 if (saveHistory) {
447 int site = (useCompactHistory) ? j + 1 : -1;
448 histories[childNum][j] = thisMarkovJumps.getCompleteHistory(site, parentTime, childTime);
449 }
450 }
451 }
452
453 private void computeIntegratedMarkovJumpsForBranch(MarkovJumpsSubstitutionModel thisMarkovJumps,
454 double substTime,
455 double branchRate,
456 int childNum,
457 int[] parentStates,
458 int[] childStates,
459 double[] probabilities,
460 double[][] condJumps,
461 boolean scaleByTime,
462 double[][] thisExpectedJumps,
463 int[] rateCategory) {
464
465 // Fill condJumps with conditional mean values for this branch
466 for (int i = 0; i < categoryCount; i++) {
467
468 double rate = siteRateModel.getRateForCategory(i);
469 if (rate > 0) {
470
471 if (categoryCount == 1) {
472 thisMarkovJumps.computeCondStatMarkovJumps(
473 substTime * branchRate * rate,
474 probabilities,
475 condJumps[i]);
476 } else {
477
478 System.arraycopy(probabilities, i * stateCount * stateCount, tmpProbabilities, 0,
479 stateCount * stateCount);
480
481 thisMarkovJumps.computeCondStatMarkovJumps(
482 substTime * branchRate * rate,
483 tmpProbabilities,
484 condJumps[i]);
485 }
486
487 if (scaleByTime) {
488 double scalar = branchRate * rate;
489 for (int j = 0; j < condJumps[i].length; j++) {
490 condJumps[i][j] /= scalar;
491 }
492 }
493 } else {
494 Arrays.fill(condJumps[i], 0.0);
495 if (thisMarkovJumps.getType() == MarkovJumpsType.REWARDS && scaleByTime) {
496 for (int j = 0; j < stateCount; j++) {
497 condJumps[i][j * stateCount + j] = substTime;
498 }
499 }
500 }
501 }
502
503 for (int j = 0; j < patternCount; j++) { // Pick out values given parent and child states
504 int category = rateCategory == null ? 0 : rateCategory[j];
505 thisExpectedJumps[childNum][j] = condJumps[category][parentStates[j] * stateCount + childStates[j]];
506 }
507 }
508
509 // public void storeState() {
510 //
511 // super.storeState();
512 //
513 //// if (areStatesRedrawn) {
514 // for (int i = 0; i < expectedJumps.size(); i++) {
515 // double[][] thisExpectedJumps = expectedJumps.get(i);
516 // double[][] storedThisExpectedJumps = storedExpectedJumps.get(i);
517 // for (int j = 0; j < thisExpectedJumps.length; j++) {
518 // System.arraycopy(thisExpectedJumps[j], 0, storedThisExpectedJumps[j], 0,
519 // thisExpectedJumps[j].length);
520 // }
521 // }
522 //// }
523 // }
524 //
525 // public void restoreState() {
526 //
527 // super.restoreState();
528 //
529 // List<double[][]> tmp = expectedJumps;
530 // expectedJumps = storedExpectedJumps;
531 // storedExpectedJumps = tmp;
532 // areStatesRedrawn = false;
533 //
534 // }
535
536 public LogColumn[] getColumns() {
537
538 int nColumns = patternCount * numRegisters;
539 if (reportUnconditionedColumns) {
540 if (categoryCount == 1) {
541 nColumns += numRegisters;
542 } else {
543 nColumns *= 2;
544 }
545 }
546
547 int index = 0;
548 LogColumn[] allColumns = new LogColumn[nColumns];
549 for (int r = 0; r < numRegisters; r++) {
550 for (int j = 0; j < patternCount; j++) {
551 allColumns[index++] = new ConditionedCountColumn(jumpTag.get(r), r, j);
552 if (reportUnconditionedColumns) {
553 if (categoryCount > 1) {
554 allColumns[index++] = new UnconditionedCountColumn(jumpTag.get(r), r, j, rateCategory);
555 }
556 }
557 }
558 if (reportUnconditionedColumns) {
559 if (categoryCount == 1) {
560 allColumns[index++] = new UnconditionedCountColumn(jumpTag.get(r), r);
561 }
562 }
563 }
564 return allColumns;
565 }
566
567 protected abstract class CountColumn extends NumberColumn {
568 protected int indexRegistration;
569 protected int indexSite;
570
571 public CountColumn(String label, int r, int j) {
572 super(label + (j >= 0 ? "[" + (j + 1) + "]" : ""));
573 indexRegistration = r;
574 indexSite = j;
575 }
576
577 public abstract double getDoubleValue();
578 }
579
580 protected class ConditionedCountColumn extends CountColumn {
581
582 public ConditionedCountColumn(String label, int r, int j) {
583 super("c_" + label, r, j);
584 }
585
586 public double getDoubleValue() {
587 double total = 0;
588 double[][] values = getMarkovJumpsForRegister(treeModel, indexRegistration);
589 for (int i = 0; i < treeModel.getNodeCount(); i++) {
590 total += values[i][indexSite];
591 }
592 return total;
593 }
594 }
595
596 protected class UnconditionedCountColumn extends CountColumn {
597 int[] rateCategory;
598
599 public UnconditionedCountColumn(String label, int r, int j, int[] rateCategory) {
600 super("u_" + label, r, j);
601 this.rateCategory = rateCategory;
602 }
603
604 public UnconditionedCountColumn(String label, int r) {
605 this(label, r, -1, null);
606 }
607
608 public double getDoubleValue() {
609 double value = markovjumps.get(indexRegistration).getMarginalRate() * getExpectedTreeLength();
610 if (rateCategory != null) {
611 value *= siteRateModel.getRateForCategory(rateCategory[indexSite]);
612 }
613 return value;
614 }
615
616 private double getExpectedTreeLength() {
617 double expectedTreeLength = 0;
618 for (int i = 0; i < treeModel.getNodeCount(); i++) {
619 NodeRef node = treeModel.getNode(i);
620 if (!treeModel.isRoot(node)) {
621 expectedTreeLength += branchRateModel.getBranchRate(treeModel, node)
622 * treeModel.getBranchLength(node);
623 }
624 }
625 return expectedTreeLength;
626 }
627 }
628
629 @Override
630 public String getDescription() {
631 return super.getDescription() + " (first citation) with MarkovJumps inference techniques (second citation)";
632 }
633
634 public List<Citation> getCitations() {
635 List<Citation> citationList = new ArrayList<Citation>(super.getCitations());
636 citationList.add(CommonCitations.MININ_2008_COUNTING);
637 return citationList;
638 }
639
640 public static final String ALL_HISTORY = "history_all";
641 public static final String HISTORY = "history";
642 public static final String TOTAL_COUNTS = "allTransitions";
643
644 private List<MarkovJumpsSubstitutionModel> markovjumps;
645 private List<Integer> branchModelNumber;
646 private List<Parameter> registerParameter;
647 private List<String> jumpTag;
648 private List<double[][]> expectedJumps;
649 // private List<double[][]> storedExpectedJumps;
650 private boolean logHistory = false;
651 private boolean useCompactHistory = false;
652 private String[][] histories = null;
653 private boolean[] scaleByTime;
654 private double[] tmpProbabilities;
655 private double[][] condJumps;
656 private int numRegisters;
657 private int historyRegisterNumber = -1;
658 private final boolean useUniformization;
659 private final int nSimulants;
660 private final boolean reportUnconditionedColumns;
661 }