Debian Codegraph @

src/dr/evomodel/branchratemodel/DiscretizedBranchRates.java

raw symbols SCIP
1 /*
2 * DiscretizedBranchRates.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.tree.NodeRef;
29 import dr.evolution.tree.Tree;
30 import dr.evolution.tree.TreeTrait;
31 import dr.evomodel.tree.TreeModel;
32 import dr.evomodel.tree.TreeParameterModel;
33 import dr.evomodelxml.branchratemodel.DiscretizedBranchRatesParser;
34 import dr.inference.distribution.ParametricDistributionModel;
35 import dr.inference.model.Model;
36 import dr.inference.model.Parameter;
37 import dr.inference.model.Variable;
38 import dr.math.MathUtils;
39 import dr.util.Author;
40 import dr.util.Citable;
41 import dr.util.Citation;
42
43 import java.util.Collection;
44 import java.util.Collections;
45 import java.util.Iterator;
46 import java.util.List;
47
48 /**
49 * @author Alexei Drummond
50 * @author Andrew Rambaut
51 * @author Michael Defoin Platel
52 * @version $Id: DiscretizedBranchRates.java,v 1.11 2006/01/09 17:44:30 rambaut Exp $
53 */
54 public class DiscretizedBranchRates extends AbstractBranchRateModel implements Citable {
55 // Turn on an off the caching on rates for categories -
56 // if off then the rates will be flagged to update on
57 // a restore.
58 // Currently turned off as it is not working with multiple partitions for
59 // some reason.
60 private static final boolean DEFAULT_CACHE_RATES = false;
61
62 public static final String RATECATEGORY = "rateCat";
63
64 private final ParametricDistributionModel distributionModel;
65
66 // The rate categories of each branch
67 final TreeParameterModel rateCategories;
68
69 private final int categoryCount;
70 private final double step;
71 private final double[][] rates;
72 private final boolean normalize;
73 private final double normalizeBranchRateTo;
74
75 private final TreeModel treeModel;
76 private final double logDensityNormalizationConstant;
77
78 private double scaleFactor = 1.0;
79 private double storedScaleFactor;
80
81 private boolean updateRateCategories = true;
82 private int currentRateArrayIndex = 0;
83 private int storedRateArrayIndex;
84
85 private boolean cacheRates = DEFAULT_CACHE_RATES;
86
87 private TreeTrait[] traits;
88
89 //overSampling control the number of effective categories
90
91 public DiscretizedBranchRates(
92 TreeModel tree,
93 Parameter rateCategoryParameter,
94 ParametricDistributionModel model,
95 int overSampling) {
96 this(tree, rateCategoryParameter, model, overSampling, false, Double.NaN, false, false, DEFAULT_CACHE_RATES);
97
98 }
99
100 public DiscretizedBranchRates(
101 TreeModel tree,
102 Parameter rateCategoryParameter,
103 ParametricDistributionModel model,
104 int overSampling,
105 boolean normalize,
106 double normalizeBranchRateTo,
107 boolean randomizeRates,
108 boolean keepRates,
109 boolean cacheRates) {
110
111 super(DiscretizedBranchRatesParser.DISCRETIZED_BRANCH_RATES);
112
113 this.cacheRates = cacheRates;
114
115 this.rateCategories = new TreeParameterModel(tree, rateCategoryParameter, false);
116
117 categoryCount = (tree.getNodeCount() - 1) * overSampling;
118 step = 1.0 / (double) categoryCount;
119
120 rates = new double[2][categoryCount];
121
122 this.normalize = normalize;
123
124 this.treeModel = tree;
125
126 // adding the key word to the tree means the keyword will be logged in the
127 // header of the tree file.
128 treeModel.addKeyword("discretized_branch_rates");
129
130 // adding the key word to the model means the keyword will be logged in the
131 // header of the logfile.
132 this.addKeyword("discretized_branch_rates");
133
134 this.distributionModel = model;
135 this.normalizeBranchRateTo = normalizeBranchRateTo;
136
137 //Force the boundaries of rateCategoryParameter to match the category count
138 Parameter.DefaultBounds bound = new Parameter.DefaultBounds(categoryCount - 1, 0, rateCategoryParameter.getDimension());
139 rateCategoryParameter.addBounds(bound);
140
141 for (int i = 0; i < rateCategoryParameter.getDimension(); i++) {
142 if (!keepRates) {
143 int index = (randomizeRates) ?
144 MathUtils.nextInt(rateCategoryParameter.getDimension() * overSampling) : // random rate
145 (int) Math.floor((i + 0.5) * overSampling); // default behavior
146 rateCategoryParameter.setParameterValue(i, index);
147 }
148 }
149
150 addModel(model);
151 addModel(rateCategories);
152
153 updateRateCategories = true;
154
155 // Each parameter take any value in [1, \ldots, categoryCount]
156 // NB But this depends on the transition kernel employed. Using swap-only results in a different constant
157 logDensityNormalizationConstant = -rateCategoryParameter.getDimension() * Math.log(categoryCount);
158
159 //for each branch, log the rate and the rate catogory, i.e. dimension = 2
160 this.traits = new TreeTrait[2];
161
162 TreeTrait<Double> branchRate = new TreeTrait<Double>() {
163 @Override
164 public String getTraitName() {
165 return RATE;
166 }
167
168 @Override
169 public Intent getIntent() {
170 return Intent.BRANCH;
171 }
172
173 @Override
174 public Class getTraitClass() {
175 return Double.class;
176 }
177
178 @Override
179 public Double getTrait(Tree tree, NodeRef node) {
180 return getBranchRate(tree, node);
181 }
182
183 @Override
184 public String getTraitString(Tree tree, NodeRef node) {
185 return Double.toString(getBranchRate(tree, node));
186 }
187
188 @Override
189 public boolean getLoggable() {
190 return true;
191 }
192
193 @Override
194 public String toString() {
195 return RATE;
196 }
197 };
198
199 TreeTrait<Integer> rateCategory = new TreeTrait<Integer>() {
200 @Override
201 public String getTraitName() {
202 return RATECATEGORY;
203 }
204
205 @Override
206 public Intent getIntent() {
207 return Intent.BRANCH;
208 }
209
210 @Override
211 public Class getTraitClass() {
212 return Double.class;
213 }
214
215 @Override
216 public Integer getTrait(Tree tree, NodeRef node) {
217 return getBranchRateCategory(tree, node);
218 }
219
220 @Override
221 public String getTraitString(Tree tree, NodeRef node) {
222 return Integer.toString(getBranchRateCategory(tree, node));
223 }
224
225 @Override
226 public boolean getLoggable() {
227 return true;
228 }
229
230 @Override
231 public String toString() {
232 return RATECATEGORY;
233 }
234 };
235
236 traits[0] = branchRate;
237 traits[1] = rateCategory;
238
239 }
240
241 // compute scale factor
242
243 private void computeFactor() {
244
245 //scale mean rate to 1.0 or separate parameter
246
247 double treeRate = 0.0;
248 double treeTime = 0.0;
249
250 //normalizeBranchRateTo = 1.0;
251 for (int i = 0; i < treeModel.getNodeCount(); i++) {
252 NodeRef node = treeModel.getNode(i);
253 if (!treeModel.isRoot(node)) {
254 int rateCategory = (int) (rateCategories.getNodeValue(treeModel, node) + 0.5);
255 treeRate += rates[currentRateArrayIndex][rateCategory] * treeModel.getBranchLength(node);
256 treeTime += treeModel.getBranchLength(node);
257
258 //System.out.println("rates and time\t" + rates[rateCategory] + "\t" + treeModel.getBranchLength(node));
259 }
260 }
261 //treeRate /= treeTime;
262
263 scaleFactor = normalizeBranchRateTo / (treeRate / treeTime);
264 //System.out.println("scaleFactor\t\t\t\t\t" + scaleFactor);
265 }
266
267 public void handleModelChangedEvent(Model model, Object object, int index) {
268 if (model == distributionModel) {
269 updateRateCategories = true;
270 fireModelChanged();
271 } else if (model == rateCategories) {
272 fireModelChanged(null, index);
273 }
274 }
275
276 protected final void handleVariableChangedEvent(Variable variable, int index, Parameter.ChangeType type) {
277 // nothing to do here
278 }
279
280 protected void storeState() {
281 if (cacheRates) {
282 storedRateArrayIndex = currentRateArrayIndex;
283 storedScaleFactor = scaleFactor;
284 }
285 }
286
287 protected void restoreState() {
288 if (cacheRates) {
289 currentRateArrayIndex = storedRateArrayIndex;
290 scaleFactor = storedScaleFactor;
291 } else {
292 updateRateCategories = true;
293 }
294 }
295
296 protected void acceptState() {
297 }
298
299 public final double getBranchRate(final Tree tree, final NodeRef node) {
300
301 assert !tree.isRoot(node) : "root node doesn't have a rate!";
302
303 if (updateRateCategories) {
304 setupRates();
305 }
306
307 int rateCategory = (int) (rateCategories.getNodeValue(tree, node) + 0.5);
308
309 //System.out.println(rates[rateCategory] + "\t" + rateCategory);
310 return rates[currentRateArrayIndex][rateCategory] * scaleFactor;
311 }
312
313 public final int getBranchRateCategory(final Tree tree, final NodeRef node) {
314
315 assert !tree.isRoot(node) : "root node doesn't have a rate category!";
316
317 if (updateRateCategories) {
318 setupRates();
319 }
320
321 int rateCategory = (int) (rateCategories.getNodeValue(tree, node) + 0.5);
322
323 return rateCategory;
324
325 }
326
327 /**
328 * Calculates the actual rates corresponding to the category indices.
329 */
330 private void setupRates() {
331
332 if (cacheRates) {
333 // flip the current array index
334 currentRateArrayIndex = 1 - currentRateArrayIndex;
335 }
336
337 double z = step / 2.0;
338 for (int i = 0; i < categoryCount; i++) {
339 rates[currentRateArrayIndex][i] = distributionModel.quantile(z);
340 //System.out.print(rates[i]+"\t");
341 z += step;
342 }
343
344 if (normalize) computeFactor();
345
346 updateRateCategories = false;
347 }
348
349 @Override
350 public TreeTrait[] getTreeTraits() {
351 return traits;
352 }
353
354 public double getLogLikelihood() {
355 return logDensityNormalizationConstant;
356 }
357
358 @Override
359 public Citation.Category getCategory() {
360 return Citation.Category.MOLECULAR_CLOCK;
361 }
362
363 @Override
364 public String getDescription() {
365 return "Uncorrelated relaxed clock";
366 }
367
368 @Override
369 public List<Citation> getCitations() {
370 return Collections.singletonList(CITATION);
371 }
372
373 public static Citation CITATION = new Citation(
374 new Author[]{
375 new Author("AJ", "Drummond"),
376 new Author("SYW", "Ho"),
377 new Author("MJ", "Phillips"),
378 new Author("A", "Rambaut")
379 },
380 "Relaxed Phylogenetics and Dating with Confidence",
381 2006,
382 "PLoS Biology",
383 "4: e88",
384 "10.1371/journal.pbio.0040088"
385 );
386 }