Debian Codegraph @

src/dr/evomodel/MSSD/AbstractObservationProcess.java

raw symbols SCIP
1 /*
2 * AbstractObservationProcess.java
3 *
4 * Copyright (c) 2002-2016 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.MSSD;
27
28 import dr.evomodel.siteratemodel.SiteRateModel;
29 import dr.evolution.alignment.AscertainedSitePatterns;
30 import dr.evolution.alignment.PatternList;
31 import dr.evolution.datatype.MutationDeathType;
32 import dr.evolution.tree.NodeRef;
33 import dr.evomodel.branchratemodel.BranchRateModel;
34 import dr.evomodel.branchratemodel.DefaultBranchRateModel;
35 import dr.evomodel.tree.TreeChangedEvent;
36 import dr.evomodel.tree.TreeModel;
37 import dr.inference.model.AbstractModel;
38 import dr.inference.model.Model;
39 import dr.inference.model.Parameter;
40 import dr.inference.model.Variable;
41 import dr.math.GammaFunction;
42
43 /**
44 * Package: AbstractObservationProcess
45 * Description:
46 * <p/>
47 * <p/>
48 * Created by
49 * Alexander V. Alekseyenko ([email protected])
50 * Date: Feb 19, 2008
51 * Time: 12:41:01 PM
52 */
53 abstract public class AbstractObservationProcess extends AbstractModel {
54 protected boolean[] nodePatternInclusion;
55 protected boolean[] storedNodePatternInclusion;
56 protected double[] cumLike;
57 protected double[] nodePartials;
58 protected double[] nodeLikelihoods;
59 protected int nodeCount;
60 protected int patternCount;
61 protected int stateCount;
62 protected TreeModel treeModel;
63 protected PatternList patterns;
64 protected double[] patternWeights;
65 protected Parameter mu;
66 protected Parameter lam;
67
68 // update control variables
69 protected boolean weightKnown;
70 protected double logTreeWeight;
71 protected double storedLogTreeWeight;
72 private double gammaNorm;
73 private double totalPatterns;
74 protected MutationDeathType dataType;
75 protected int deathState;
76 protected SiteRateModel siteModel;
77 private double logN;
78 protected boolean nodePatternInclusionKnown = false;
79 BranchRateModel branchRateModel;
80
81 public AbstractObservationProcess(String Name, TreeModel treeModel, PatternList patterns, SiteRateModel siteModel,
82 BranchRateModel branchRateModel, Parameter mu, Parameter lam) {
83 super(Name);
84 this.treeModel = treeModel;
85 this.patterns = patterns;
86 this.mu = mu;
87 this.lam = lam;
88 this.siteModel = siteModel;
89 if (branchRateModel != null) {
90 this.branchRateModel = branchRateModel;
91 } else {
92 this.branchRateModel = new DefaultBranchRateModel();
93 }
94 addModel(treeModel);
95 addModel(siteModel);
96 addModel(this.branchRateModel);
97 addVariable(mu);
98 addVariable(lam);
99
100 nodeCount = treeModel.getNodeCount();
101 stateCount = patterns.getDataType().getStateCount();
102 this.patterns = patterns;
103 patternCount = patterns.getPatternCount();
104 patternWeights = patterns.getPatternWeights();
105 totalPatterns = 0;
106 for (int i = 0; i < patternCount; ++i) {
107 totalPatterns += patternWeights[i];
108 }
109 logN = Math.log(totalPatterns);
110
111 gammaNorm = -GammaFunction.lnGamma(totalPatterns + 1);
112
113 dataType = (MutationDeathType) patterns.getDataType();
114 this.deathState = dataType.DEATHSTATE;
115 setNodePatternInclusion();
116 cumLike = new double[patternCount];
117 nodeLikelihoods = new double[patternCount];
118 weightKnown = false;
119 }
120
121 // public Parameter getMuParameter() {
122 // return mu;
123 // }
124 //
125 // public Parameter getLamParameter() {
126 // return lam;
127 // }
128
129 private double calculateSiteLogLikelihood(int site, double[] partials, double[] frequencies) {
130 int v = site * stateCount;
131 double sum = 0.0;
132 for (int i = 0; i < stateCount; i++) {
133 sum += frequencies[i] * partials[v + i];
134 }
135 return Math.log(sum);
136 }
137
138
139 // @todo needs updating to use BEAGLE
140 // private void calculateNodePatternLikelihood(int nodeIndex,
141 // double[] freqs,
142 // LikelihoodCore likelihoodCore,
143 // double averageRate,
144 // double[] cumLike) {
145 // // get partials for node nodeIndex
146 // likelihoodCore.getPartials(nodeIndex, nodePartials); // MAS
147 // /*
148 // multiply the partials by equilibrium probs
149 // this part could be optimized by first summing
150 // and then multiplying by equilibrium probs
151 // */
152 // double prob = Math.log(getNodeSurvivalProbability(nodeIndex, averageRate));
153 //
154 // for (int j = 0; j < patternCount; ++j) {
155 // if (nodePatternInclusion[nodeIndex * patternCount + j]) {
156 // cumLike[j] += Math.exp(calculateSiteLogLikelihood(j, nodePartials, freqs) + prob);
157 // }
158 // }
159 // }
160 //
161 // private double accumulateCorrectedLikelihoods(double[] cumLike, double ascertainmentCorrection,
162 // double[] patterWeights) {
163 // double logL = 0;
164 // for (int j = 0; j < patternCount; ++j) {
165 // logL += Math.log(cumLike[j] / ascertainmentCorrection) * patternWeights[j];
166 // }
167 // return logL;
168 // }
169 //
170 // public final double nodePatternLikelihood(double[] freqs, LikelihoodPartialsProvider likelihoodCore,
171 // ScaleFactorsHelper scaleFactorsHelper) {
172 // int i, j;
173 // double logL = gammaNorm;
174 //
175 // double birthRate = lam.getParameterValue(0);
176 // double logProb;
177 // if (!nodePatternInclusionKnown)
178 // setNodePatternInclusion();
179 // if (nodePartials == null) {
180 // nodePartials = new double[patternCount * stateCount];
181 // }
182 //
183 // double averageRate = getAverageRate();
184 //
185 // for (j = 0; j < patternCount; ++j) cumLike[j] = 0;
186 //
187 // for (i = 0; i < nodeCount; ++i) {
188 // // get partials for node i
189 // likelihoodCore.getPartials(i, nodePartials);
190 // scaleFactorsHelper.rescalePartials(i, nodePartials);
191 // /*
192 // multiply the partials by equilibrium probs
193 // this part could be optimized by first summing
194 // and then multiplying by equilibrium probs
195 // */
196 //// likelihoodCore.calculateLogLikelihoods(nodePartials, freqs, nodeLikelihoods); // MAS Removed
197 // logProb = Math.log(getNodeSurvivalProbability(i, averageRate));
198 //
199 // for (j = 0; j < patternCount; ++j) {
200 // if (nodePatternInclusion[i * patternCount + j]) {
201 //// cumLike[j] += Math.exp(nodeLikelihoods[j] + logProb); // MAS Replaced with line below
202 // cumLike[j] += Math.exp(calculateSiteLogLikelihood(j, nodePartials, freqs)
203 // + logProb);
204 // }
205 // }
206 // }
207 //
208 // double ascertainmentCorrection = getAscertainmentCorrection(cumLike);
209 //// System.err.println("AscertainmentCorrection: "+ascertainmentCorrection);
210 //
211 // for (j = 0; j < patternCount; ++j) {
212 // logL += Math.log(cumLike[j] / ascertainmentCorrection) * patternWeights[j];
213 // }
214 //
215 // double deathRate = mu.getParameterValue(0);
216 //
217 // double logTreeWeight = getLogTreeWeight();
218 //
219 // if (integrateGainRate) {
220 // logL -= gammaNorm + logN + Math.log(-logTreeWeight * deathRate / birthRate) * totalPatterns;
221 // } else {
222 // logL += logTreeWeight + Math.log(birthRate / deathRate) * totalPatterns;
223 // }
224 // return logL;
225 // }
226
227 protected double getAscertainmentCorrection(double[] patternProbs) {
228 // This function probably belongs better to the AscertainedSitePatterns
229 double excludeProb = 0, includeProb = 0, returnProb = 1.0;
230 if (this.patterns instanceof AscertainedSitePatterns) {
231 int[] includeIndices = ((AscertainedSitePatterns) patterns).getIncludePatternIndices();
232 int[] excludeIndices = ((AscertainedSitePatterns) patterns).getExcludePatternIndices();
233 for (int i = 0; i < ((AscertainedSitePatterns) patterns).getIncludePatternCount(); i++) {
234 int index = includeIndices[i];
235 includeProb += patternProbs[index];
236 }
237 for (int j = 0; j < ((AscertainedSitePatterns) patterns).getExcludePatternCount(); j++) {
238 int index = excludeIndices[j];
239 excludeProb += patternProbs[index];
240 }
241 if (includeProb == 0.0) {
242 returnProb -= excludeProb;
243 } else if (excludeProb == 0.0) {
244 returnProb = includeProb;
245 } else {
246 returnProb = includeProb - excludeProb;
247 }
248 }
249
250 return returnProb;
251 }
252
253 final public double getLogTreeWeight() {
254 if (!weightKnown) {
255 logTreeWeight = calculateLogTreeWeight();
256 weightKnown = true;
257 }
258
259 return logTreeWeight;
260 }
261
262 abstract public double calculateLogTreeWeight();
263
264 abstract void setNodePatternInclusion();
265
266 final public double getAverageRate() {
267 if (!averageRateKnown) {
268 double avgRate = 0.0;
269 double proportions[] = siteModel.getCategoryProportions();
270 for (int i = 0; i < siteModel.getCategoryCount(); ++i) {
271 avgRate += proportions[i] * siteModel.getRateForCategory(i);
272 }
273 averageRate = avgRate;
274 averageRateKnown = true;
275 }
276 return averageRate;
277 }
278
279 public double getNodeSurvivalProbability(int index, double averageRate) {
280 NodeRef node = treeModel.getNode(index);
281 NodeRef parent = treeModel.getParent(node);
282
283 if (parent == null) return 1.0;
284
285 final double deathRate = mu.getParameterValue(0) * averageRate; //getAverageRate();
286 final double branchRate = branchRateModel.getBranchRate(treeModel, node);
287 // Get the operational time of the branch
288 final double branchTime = branchRate * treeModel.getBranchLength(node);
289 return 1.0 - Math.exp(-deathRate * branchTime);
290 }
291
292 protected void handleModelChangedEvent(Model model, Object object, int index) {
293 if (model == siteModel) {
294 averageRateKnown = false;
295 }
296 if (model == treeModel || model == siteModel || model == branchRateModel) {
297 weightKnown = false;
298 }
299 if (model == treeModel) {
300 if (object instanceof TreeChangedEvent) {
301 if (((TreeChangedEvent) object).isTreeChanged()) {
302 nodePatternInclusionKnown = false;
303 }
304 }
305 }
306 }
307
308 protected final void handleVariableChangedEvent(Variable variable, int index, Parameter.ChangeType type) {
309 if (variable == mu || variable == lam) {
310 weightKnown = false;
311 } else {
312 System.err.println("AbstractObservationProcess: Got unexpected parameter changed event. (Parameter = " + variable + ")");
313 }
314 }
315
316 protected void storeState() {
317 // storedAverageRate = averageRate;
318 storedLogTreeWeight = logTreeWeight;
319 System.arraycopy(nodePatternInclusion, 0, storedNodePatternInclusion, 0, storedNodePatternInclusion.length);
320 }
321
322 protected void restoreState() {
323 // averageRate = storedAverageRate;
324 averageRateKnown = false;
325 logTreeWeight = storedLogTreeWeight;
326 boolean[] tmp = storedNodePatternInclusion;
327 storedNodePatternInclusion = nodePatternInclusion;
328 nodePatternInclusion = tmp;
329 }
330
331 protected void acceptState() {
332 }
333
334 public void setIntegrateGainRate(boolean integrateGainRate) {
335 this.integrateGainRate = integrateGainRate;
336 }
337
338 private boolean integrateGainRate = false;
339
340 private double storedAverageRate;
341 private double averageRate;
342 private boolean averageRateKnown = false;
343 }