Debian Codegraph @

src/dr/evomodel/branchratemodel/DiscreteTraitBranchRateModel.java

raw symbols SCIP
1 /*
2 * DiscreteTraitBranchRateModel.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.branchratemodel;
27
28 import dr.evolution.alignment.PatternList;
29 import dr.evolution.datatype.DataType;
30 import dr.evolution.parsimony.FitchParsimony;
31 import dr.evolution.tree.NodeRef;
32 import dr.evolution.tree.Tree;
33 import dr.evolution.tree.TreeTrait;
34 import dr.evolution.tree.TreeTraitProvider;
35 import dr.evolution.util.TaxonList;
36 import dr.evomodel.tree.TreeModel;
37 import dr.inference.model.Model;
38 import dr.inference.model.Parameter;
39 import dr.inference.model.Variable;
40
41 /**
42 * This Branch Rate Model takes a ancestral state likelihood and
43 * gives the rate for each branch of the tree based on the ancestor
44 * state and child state or based on the Markov Rewards (i.e., time
45 * spent in each state).
46 *
47 * @author Alexei Drummond
48 * @author Marc Suchard
49 * @author Andrew Rambaut
50 * @author Trevor Bedford
51 */
52 public class DiscreteTraitBranchRateModel extends AbstractBranchRateModel {
53 private static final boolean CACHING_RATES = true;
54
55 enum Mode {
56 NODE_STATES,
57 MARKOV_JUMP_PROCESS,
58 MARKOV_JUMP_COUNT,
59 PARSIMONY
60 }
61
62 public static final String DISCRETE_TRAIT_BRANCH_RATE_MODEL = "discreteTraitRateModel";
63
64 protected TreeTrait trait = null;
65 private Parameter rateParameter;
66 private Parameter relativeRatesParameter;
67 private Parameter indicatorParameter;
68 protected int traitIndex;
69
70 private double[] rates;
71 private double[] storedRates;
72 private boolean[] rateKnown;
73
74 // private boolean normKnown = false;
75 // private boolean storedNormKnown = false;
76 // private double norm = 1.0;
77 // private double storedNorm = 1.0;
78
79 private TreeTrait[] traits;
80
81 private FitchParsimony fitchParsimony;
82
83 private boolean treeChanged = true;
84
85 private Mode mode;
86 private DataType dataType;
87 // private int treeInitializeCounter = 0;
88
89 /**
90 * A constructor for the (crude) parsimony reconstruction form of this class.
91 * @param treeModel
92 * @param patternList
93 * @param traitIndex
94 * @param ratesParameter
95 */
96 public DiscreteTraitBranchRateModel(TreeModel treeModel, PatternList patternList, int traitIndex, Parameter ratesParameter) {
97
98 this(treeModel, traitIndex, ratesParameter, null, null);
99
100 if (!TaxonList.Utils.getTaxonListIdSet(treeModel).equals(TaxonList.Utils.getTaxonListIdSet(patternList))) {
101 throw new IllegalArgumentException("Tree model and pattern list must have the same list of taxa!");
102 }
103
104 ratesParameter.setDimension(patternList.getDataType().getStateCount());
105
106 fitchParsimony = new FitchParsimony(patternList, false);
107 mode = Mode.PARSIMONY;
108 }
109
110 /**
111 * A constructor for a node-sampled discrete trait
112 * @param treeModel
113 * @param trait
114 * @param traitIndex
115 * @param rateParameter
116 * @param relativeRatesParameter
117 * @param indicatorParameter
118 */
119 public DiscreteTraitBranchRateModel(TreeTraitProvider traitProvider, DataType dataType, TreeModel treeModel,
120 TreeTrait trait, int traitIndex, Parameter rateParameter, Parameter relativeRatesParameter, Parameter indicatorParameter) {
121
122 this(treeModel, traitIndex, rateParameter, relativeRatesParameter, indicatorParameter);
123
124 // if (trait.getTreeModel() != treeModel)
125 // throw new IllegalArgumentException("Tree Models for ancestral state tree likelihood and target model of these rates must match!");
126
127 this.trait = trait;
128 this.dataType = dataType;
129
130 if (trait.getTraitName().equals("states")) {
131 // Assume the trait is one or more discrete traits reconstructed at nodes
132 mode = Mode.NODE_STATES;
133 } else /*if (double[].class.isAssignableFrom(trait.getClass()))*/ {
134 // Assume the trait itself is the dwell times for the individual states on the branch above the node
135 mode = Mode.MARKOV_JUMP_PROCESS;
136 } /* else {
137 throw new IllegalArgumentException("The trait class type is not suitable for use in this class.");
138 } */
139
140 relativeRatesParameter.setDimension(dataType.getStateCount());
141
142 if (traitProvider instanceof Model) {
143 addModel((Model)traitProvider);
144 }
145
146 if (trait instanceof Model) {
147 addModel((Model)trait); // MAS: Does this ever occur?
148 }
149 }
150
151 public DiscreteTraitBranchRateModel(TreeTraitProvider traitProvider, DataType dataType, TreeModel treeModel,
152 TreeTrait trait, int traitIndex, Parameter ratesParameter) {
153
154 this(treeModel, traitIndex, ratesParameter, null, null);
155
156 // if (trait.getTreeModel() != treeModel)
157 // throw new IllegalArgumentException("Tree Models for ancestral state tree likelihood and target model of these rates must match!");
158
159 this.trait = trait;
160 this.dataType = dataType;
161
162 if (trait.getTraitName().equals("states")) {
163 // Assume the trait is one or more discrete traits reconstructed at nodes
164 mode = Mode.NODE_STATES;
165 } else /*if (double[].class.isAssignableFrom(trait.getClass()))*/ {
166 // Assume the trait itself is the dwell times for the individual states on the branch above the node
167 mode = Mode.MARKOV_JUMP_PROCESS;
168 } /* else {
169 throw new IllegalArgumentException("The trait class type is not suitable for use in this class.");
170 } */
171
172 ratesParameter.setDimension(dataType.getStateCount());
173
174 if (traitProvider instanceof Model) {
175 addModel((Model)traitProvider);
176 }
177
178 if (trait instanceof Model) {
179 addModel((Model)trait); // MAS: Does this ever occur?
180 }
181 }
182
183 public DiscreteTraitBranchRateModel(TreeTraitProvider traitProvider, TreeTrait[] traits, TreeModel treeModel, Parameter ratesParameter) {
184
185 this(treeModel, 0, ratesParameter, null, null);
186
187 this.traits = traits;
188 mode = Mode.MARKOV_JUMP_PROCESS;
189
190 ratesParameter.setDimension(traits.length);
191
192
193 if (traitProvider instanceof Model) {
194 addModel((Model)traitProvider);
195 }
196 }
197
198 private DiscreteTraitBranchRateModel(TreeModel treeModel, int traitIndex,
199 Parameter rateParameter, Parameter relativeRatesParameter, Parameter indicatorParameter) {
200 super(DISCRETE_TRAIT_BRANCH_RATE_MODEL);
201 addModel(treeModel);
202 this.traitIndex = traitIndex;
203
204 this.rateParameter = rateParameter;
205 addVariable(rateParameter);
206
207 this.relativeRatesParameter = relativeRatesParameter;
208 if (relativeRatesParameter != null) {
209 addVariable(relativeRatesParameter);
210 }
211
212 this.indicatorParameter = indicatorParameter;
213 if (indicatorParameter != null) {
214 addVariable(indicatorParameter);
215 }
216
217 rates = new double[treeModel.getNodeCount()];
218 storedRates = new double[treeModel.getNodeCount()];
219 rateKnown = new boolean[treeModel.getNodeCount()];
220
221 }
222
223 public void handleModelChangedEvent(Model model, Object object, int index) {
224 // TreeModel has changed...
225 for (int i = 0; i < rateKnown.length; i++) {
226 rateKnown[i] = false;
227 }
228 treeChanged = true;
229 fireModelChanged();
230 }
231
232 protected final void handleVariableChangedEvent(Variable variable, int index, Parameter.ChangeType type) {
233 // Rate Parameters have changed
234 for (int i = 0; i < rateKnown.length; i++) {
235 rateKnown[i] = false;
236 }
237 fireModelChanged();
238 }
239
240 protected void storeState() {
241 if (CACHING_RATES) {
242 System.arraycopy(rates, 0, storedRates, 0, rates.length);
243 }
244 }
245
246 protected void restoreState() {
247 if (CACHING_RATES) {
248 double[] tmp = rates;
249 rates = storedRates;
250 storedRates = tmp;
251
252 for (int i = 0; i < rateKnown.length; i++) {
253 rateKnown[i] = true;
254 }
255 } else {
256 for (int i = 0; i < rateKnown.length; i++) {
257 rateKnown[i] = false;
258 }
259 treeChanged = true;
260 }
261 }
262
263 protected void acceptState() {
264 // nothing to do
265 }
266
267 protected int getStateCount() {
268 int dimen = 0;
269 if (mode == Mode.NODE_STATES || mode == Mode.MARKOV_JUMP_PROCESS) {
270 dimen = dataType.getStateCount();
271 }
272 else if (mode == Mode.PARSIMONY) {
273 dimen = fitchParsimony.getPatterns().getStateCount();
274 }
275 return dimen;
276 }
277
278 public double getBranchRate(final Tree tree, final NodeRef node) {
279
280 if (CACHING_RATES) {
281 if (!rateKnown[node.getNumber()]) {
282 rates[node.getNumber()] = getRawBranchRate(tree, node);
283 rateKnown[node.getNumber()] = true;
284 }
285
286 return rates[node.getNumber()];
287 } else {
288 return getRawBranchRate(tree, node);
289 }
290 }
291
292 // produce weighted mean of rate for a branch
293 // rate = absRate * branchWeight[0] * relativeRates[0] + absRate * branchWeight[1] * relativeRates[1]
294 protected double getRawBranchRate(final Tree tree, final NodeRef node) {
295
296 double rate = 0.0;
297 int stateCount = getStateCount();
298
299 double[] processValues = getProcessValues(tree, node);
300 // double[] processValues = {1.0, 1.0};
301 double[] branchWeights = new double[stateCount];
302 double totalTime = 0;
303
304 for (int i = 0; i < stateCount; i++) {
305 branchWeights[i] += processValues[i];
306 totalTime += processValues[i];
307 }
308
309 for (int i = 0; i < stateCount; i++) {
310 branchWeights[i] /= totalTime;
311 }
312
313 if (relativeRatesParameter != null && indicatorParameter == null) {
314 double absRate = rateParameter.getParameterValue(0);
315 for (int i = 0; i < stateCount; i++) {
316 rate += absRate * relativeRatesParameter.getParameterValue(i) * branchWeights[i];
317 }
318 }
319 else if (relativeRatesParameter != null && indicatorParameter != null) {
320 double absRate = rateParameter.getParameterValue(0);
321 for (int i = 0; i < stateCount; i++) {
322 rate += absRate * relativeRatesParameter.getParameterValue(i) * branchWeights[i] * (double) indicatorParameter.getParameterValue(i);
323 }
324 } else {
325 for (int i = 0; i < stateCount; i++) {
326 rate += rateParameter.getParameterValue(i) * processValues[i];
327 totalTime += processValues[i];
328 }
329 }
330
331 return rate;
332 }
333
334 /**
335 *
336 * @param tree
337 * @param node
338 * @return and array of the total amount of time spent in each of the discrete states along the branch above the given node.
339 */
340 private double[] getProcessValues(final Tree tree, final NodeRef node) {
341
342 double[] processValues = null;
343 int stateCount = getStateCount();
344 double branchTime = tree.getBranchLength(node);
345
346 if (mode == Mode.MARKOV_JUMP_PROCESS) {
347 processValues = new double[stateCount];
348 for (int i = 0; i < stateCount; i++) {
349 processValues[i] = ((TreeTrait.DA)traits[i]).getTrait(tree, node)[0];
350 }
351 } else if (mode == Mode.PARSIMONY) {
352 // an approximation to dwell times using parsimony, assuming
353 // the state changes midpoint on the tree. Does a weighted
354 // average of the equally parsimonious state reconstructions
355 // at the top and bottom of each branch.
356
357 if (treeChanged) {
358 fitchParsimony.initialize(tree);
359 // Debugging test to count work
360 // treeInitializeCounter += 1;
361 // if (treeInitializeCounter % 10 == 0) {
362 // System.err.println("Cnt: "+treeInitializeCounter);
363 // }
364 treeChanged = false;
365 }
366 int[] states = fitchParsimony.getStates(tree, node);
367 int[] parentStates = fitchParsimony.getStates(tree, tree.getParent(node));
368
369 processValues = new double[fitchParsimony.getPatterns().getStateCount()];
370
371 for (int state : states) {
372 processValues[state] += branchTime / 2;
373 }
374 for (int state : parentStates) {
375 processValues[state] += branchTime / 2;
376 }
377
378 for (int i = 0; i < processValues.length; i++) {
379 // normalize by the number of equally parsimonious states at each end of the branch
380 // processValues should add up to the total branch length
381 processValues[i] /= (states.length + parentStates.length) / 2;
382 }
383 } else if (mode == Mode.NODE_STATES) {
384 processValues = new double[stateCount];
385
386 // if the states are being sampled - then there is only one possible state at each
387 // end of the branch.
388 int state = ((int[])trait.getTrait(tree, node))[traitIndex];
389 processValues[state] += branchTime / 2;
390 NodeRef parent = tree.getParent(node);
391 int parentState = ((int[])trait.getTrait(tree, parent))[traitIndex];
392 processValues[parentState] += branchTime / 2;
393 }
394
395 return processValues;
396 }
397
398 }