Debian Codegraph @

src/dr/evomodel/coalescent/VariableSkylineLikelihood.java

raw symbols SCIP
1 /*
2 * VariableSkylineLikelihood.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.coalescent;
27
28 import dr.evolution.coalescent.ConstantPopulation;
29 import dr.evolution.tree.Tree;
30 import dr.evolution.util.Units;
31 import dr.evomodel.tree.TreeModel;
32 import dr.evomodelxml.coalescent.VariableSkylineLikelihoodParser;
33 import dr.inference.model.Parameter;
34 import dr.inference.model.Variable;
35 import dr.util.Author;
36 import dr.util.Citable;
37 import dr.util.Citation;
38
39 import java.util.ArrayList;
40 import java.util.Collections;
41 import java.util.List;
42
43 /**
44 * A likelihood function for the variable skyline plot coalescent.
45 * Takes a tree, population size and an indicator parameter.
46 *
47 * @author Alexei Drummond
48 */
49 public class VariableSkylineLikelihood extends OldAbstractCoalescentLikelihood implements Citable {
50
51 // PUBLIC STUFF
52
53 public enum Type {
54 STEPWISE,
55 LINEAR,
56 EXPONENTIAL
57 }
58
59 public VariableSkylineLikelihood(Tree tree, Parameter popSizeParameter, Parameter indicatorParameter,
60 Type type, boolean logSpace) {
61 super(VariableSkylineLikelihoodParser.SKYLINE_LIKELIHOOD);
62
63 this.popSizeParameter = popSizeParameter;
64 this.indicatorParameter = indicatorParameter;
65 final int redcueDim = type == Type.STEPWISE ? 1 : 0;
66 final int events = tree.getExternalNodeCount() - redcueDim;
67 final int paramDim1 = popSizeParameter.getDimension();
68 final int paramDim2 = indicatorParameter.getDimension();
69 this.type = type;
70 this.logSpace = logSpace;
71
72 if (paramDim1 != events) {
73 throw new IllegalArgumentException("Dimension of population parameter (" + paramDim1 + ") must be the same as the number of internal nodes in the tree ("
74 + events + ").");
75 }
76 if (paramDim2 != events - 1) {
77 throw new IllegalArgumentException("Dimension of indicator parameter must one less than the number of internal nodes in the tree. ("
78 + paramDim2 + " != " + (events - 1) + ")");
79 }
80
81 this.tree = tree;
82 if (tree instanceof TreeModel) {
83 addModel((TreeModel) tree);
84 }
85
86 addVariable(indicatorParameter);
87 addVariable(popSizeParameter);
88
89 setupIntervals();
90 }
91
92 // **************************************************************
93 // Likelihood IMPLEMENTATION
94 // **************************************************************
95
96 /**
97 * Calculates the log likelihood of this set of coalescent intervals,
98 * given a demographic model.
99 */
100 public synchronized double getLogLikelihood() {
101
102 insureValid();
103
104 double logL = 0.0;
105
106 double currentTime = 0.0;
107
108 // index of current interval in the population function
109 int groupIndex = 0;
110
111 // how many intervals precessed in the current group - tell when to switch to next group
112 int subIndex = 0;
113 ConstantPopulation cp = new ConstantPopulation(Units.Type.YEARS);
114
115 final double[] pop = new double[1];
116 if (type == Type.LINEAR) {
117 cp = new ConstantPopulation(Units.Type.YEARS) {
118 public double getDemographic(double t) {
119 return pop[0];
120 }
121 };
122 }
123
124 //if( false ) { System.err.println("Old:"); }
125
126 for (int j = 0; j < intervalCount; j++) {
127
128 // set the population size to the size of the middle of the current interval
129 if (type == Type.LINEAR) {
130 pop[0] = getPopSize(groupIndex, currentTime + intervals[j]);
131 }
132 cp.setN0(getPopSize(groupIndex, currentTime + (intervals[j] / 2.0)));
133 final CoalescentEventType iType = getIntervalType(j);
134 if (iType == CoalescentEventType.COALESCENT) {
135 subIndex += 1;
136 if (subIndex >= groupSizes.get(groupIndex)) {
137 groupIndex += 1;
138 subIndex = 0;
139 }
140 }
141
142 logL += calculateIntervalLikelihood(cp, intervals[j], currentTime, lineageCounts[j], iType);
143
144 //if( false ) { System.err.println(" lgl " + logL); }
145
146 if (logL > 0 && j > 1) {
147 System.out.println(logL);
148 }
149
150 // insert zero-length coalescent intervals
151 final int diff = getCoalescentEvents(j) - 1;
152 for (int k = 0; k < diff; k++) {
153 // not clear, seems wrong - how can population size change in 0 time?
154 pop[0] = getPopSize(groupIndex, currentTime);
155 cp.setN0(pop[0]);
156 logL += calculateIntervalLikelihood(cp, 0.0, currentTime, lineageCounts[j] - k - 1,
157 CoalescentEventType.COALESCENT);
158 subIndex += 1;
159 if (subIndex >= groupSizes.get(groupIndex)) {
160 groupIndex += 1;
161 subIndex = 0;
162 }
163 }
164
165 currentTime += intervals[j];
166 }
167
168 return logL;
169 }
170
171 private void insureValid() {
172 if (!intervalsKnown) {
173 // System.out.println("**" + intervalsKnown);
174 // assert !intervalsKnown;
175 setupIntervals();
176 groupsValid = false;
177 }
178
179 if (!groupsValid) {
180 calculateGroupSizesHeightsAndEnds();
181 popPoints = null;
182 }
183 }
184
185 private double[] popPoints = null;
186
187 public double[] getPopulation(int dim) {
188 insureValid();
189
190 if (popPoints != null && popPoints.length == dim) {
191 return popPoints;
192 }
193
194 if (popPoints == null || popPoints.length != dim) {
195 popPoints = new double[dim];
196 }
197
198 final double height = tree.getNodeHeight(tree.getRoot());
199 double hstep = height / popPoints.length;
200
201 int groupIndex = 0;
202 double currentTime = 0.0;
203 double switchAt = groupEnds.get(groupIndex);
204 for (int k = 0; k < popPoints.length - 1; ++k) {
205 popPoints[k] = getPopSize(groupIndex, currentTime);
206 currentTime += hstep;
207 while (currentTime >= switchAt) {
208 ++groupIndex;
209 switchAt = groupEnds.get(groupIndex);
210 }
211 }
212 popPoints[popPoints.length - 1] = getPopSize(groupIndex, currentTime);
213 return popPoints;
214 }
215
216 /**
217 * @param groupIndex time inside this group
218 * @param atTime given time
219 * @return the population size for the given time. If linear model is being used then this pop size is
220 * interpolated between the two pop sizes at either end of the grouped interval.
221 */
222 private double getPopSize(int groupIndex, double atTime) {
223
224 final double startGroupTime = groupIndex > 0 ? groupEnds.get(groupIndex - 1) : 0.0;
225 final double endGroupTime = groupEnds.get(groupIndex);
226 final double startGroupPopSize = groupHeights.get(groupIndex);
227
228 if (!(startGroupTime <= atTime &&
229 ((type != Type.STEPWISE && atTime <= endGroupTime) ||
230 (type == Type.STEPWISE && atTime < endGroupTime)))) {
231 System.out.println(atTime + " " + startGroupTime + "/" + endGroupTime);
232 }
233
234 switch (type) {
235 case EXPONENTIAL: {
236 throw new UnsupportedOperationException("Exponential Skyline Plot not implemented yet");
237 }
238 case LINEAR: {
239 if (groupIndex + 1 >= groupHeights.size()) {
240 return startGroupPopSize;
241 }
242
243 final double endGroupPopSize = groupHeights.get(groupIndex + 1);
244
245 // calculate the gradient
246 //final double m = (endGroupPopSize - startGroupPopSize) / (endGroupTime - startGroupTime);
247 final double a = (atTime - startGroupTime) / (endGroupTime - startGroupTime);
248 // calculate the population size at atTime using linear interpolation
249
250 double v = (1 - a) * startGroupPopSize + a * endGroupPopSize;
251 if (v <= 0) {
252 // numerical problems, very small endGroupPopSize
253 if (a == 1) {
254 assert endGroupPopSize > 0;
255 return endGroupPopSize;
256 }
257 System.out.println(v);
258 assert v > 0;
259 }
260 return v;
261 }
262 case STEPWISE: {
263 return startGroupPopSize;
264 }
265 }
266
267 return -1; // never reached
268 }
269
270 private void calculateGroupSizesHeightsAndEnds() {
271 // System.out.println(intervalsKnown);
272 // if( !intervalsKnown ) {
273 //// System.out.println("**" + intervalsKnown);
274 //// assert !intervalsKnown;
275 // setupIntervals();
276 // }
277 // need to do this only if demo model or indicator changed
278 groupSizes.clear();
279 groupHeights.clear();
280 groupEnds.clear();
281
282 int groupSize = 1;
283 int nextPopSizeIndex = 0;
284 double height = 0.0;
285 for (int i = 0; i < indicatorParameter.getDimension(); i++) {
286 height += intervals[i];
287 if (indicatorParameter.getParameterValue(i) != 0.0) {
288 groupSizes.add(groupSize);
289 groupHeights.add(popSizeParameter.getParameterValue(nextPopSizeIndex));
290 groupSize = 1;
291 nextPopSizeIndex = i + 1;
292
293 groupEnds.add(height);
294
295 } else {
296 groupSize += 1;
297 }
298 }
299 height += intervals[indicatorParameter.getDimension()];
300
301 groupSizes.add(groupSize);
302 groupHeights.add(popSizeParameter.getParameterValue(nextPopSizeIndex));
303 groupEnds.add(height);
304
305 if (logSpace) {
306 for (int i = 0; i < groupHeights.size(); i++) {
307 groupHeights.set(i, Math.exp(groupHeights.get(i)));
308 }
309 }
310
311 groupsValid = true;
312 }
313
314 protected final void handleVariableChangedEvent(Variable variable, int index, Parameter.ChangeType type) {
315 super.handleVariableChangedEvent(variable, index, type);
316 // if( parameter == indicatorParameter || parameter == popSizeParameter ) {
317 groupsValid = false;
318 // }
319 }
320
321 protected void storeState() {
322 super.storeState();
323 storeSizes.clear();
324 storeSizes.addAll(groupSizes);
325 storeHeights.clear();
326 storeHeights.addAll(groupHeights);
327 storeEnds.clear();
328 storeEnds.addAll(groupEnds);
329 storeValid = groupsValid;
330 }
331
332 protected void restoreState() {
333 super.restoreState();
334 groupsValid = storeValid;
335 groupSizes.clear();
336 groupSizes.addAll(storeSizes);
337 groupHeights.clear();
338 groupHeights.addAll(storeHeights);
339 groupEnds.clear();
340 groupEnds.addAll(storeEnds);
341 }
342
343 // ****************************************************************
344 // Private and protected stuff
345 // ****************************************************************
346
347 /**
348 * The demographic model.
349 */
350 private final Parameter popSizeParameter;
351
352 private final Parameter indicatorParameter;
353
354 private boolean groupsValid = false;
355
356 List<Integer> groupSizes = new ArrayList<Integer>();
357 List<Double> groupHeights = new ArrayList<Double>();
358 List<Double> groupEnds = new ArrayList<Double>();
359
360 private final ArrayList<Integer> storeSizes = new ArrayList<Integer>();
361 private final ArrayList<Double> storeHeights = new ArrayList<Double>();
362 private final ArrayList<Double> storeEnds = new ArrayList<Double>();
363 private boolean storeValid;
364
365 private final Type type;
366
367 private boolean logSpace = false;
368
369 @Override
370 public Citation.Category getCategory() {
371 return Citation.Category.TREE_PRIORS;
372 }
373
374 @Override
375 public String getDescription() {
376 return "Extended Skyline Coalescent";
377 }
378
379 @Override
380 public List<Citation> getCitations() {
381 return Collections.singletonList(CITATION);
382 }
383
384 public static Citation CITATION = new Citation(
385 new Author[]{
386 new Author("J", "Heled"),
387 new Author("AJ", "Drummond")
388 },
389 "",
390 0,
391 "",
392 0, 0, 0,
393 ""
394 );
395 }