Debian Codegraph @

src/dr/evomodel/arg/coalescent/VeryOldCoalescentLikelihood.java

raw symbols SCIP
1 /*
2 * VeryOldCoalescentLikelihood.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.arg.coalescent;
27
28 import dr.evolution.coalescent.DemographicFunction;
29 import dr.evolution.tree.NodeRef;
30 import dr.evolution.tree.Tree;
31 import dr.evolution.util.Units;
32 import dr.evomodel.coalescent.DemographicModel;
33 import dr.evomodel.tree.TreeModel;
34 import dr.inference.model.*;
35 import dr.math.Binomial;
36 import dr.util.ComparableDouble;
37 import dr.util.HeapSort;
38 import dr.xml.*;
39
40 import java.util.ArrayList;
41
42
43 /**
44 * A likelihood function for the coalescent. Takes a tree and a demographic model.
45 * <p/>
46 * Parts of this class were derived from C++ code provided by Oliver Pybus.
47 *
48 * @author Andrew Rambaut
49 * @author Alexei Drummond
50 * @version $Id: VeryOldCoalescentLikelihood.java,v 1.43 2006/07/28 11:27:32 rambaut Exp $
51 */
52 public class VeryOldCoalescentLikelihood extends AbstractModelLikelihood implements Units {
53
54 // PUBLIC STUFF
55
56 public static final String COALESCENT_LIKELIHOOD = "veryOldCoalescentLikelihood";
57 public static final String ANALYTICAL = "analytical";
58 public static final String MODEL = "model";
59 public static final String POPULATION_TREE = "populationTree";
60
61 /**
62 * Denotes an interval after which a coalescent event is observed
63 * (i.e. the number of lineages is smaller in the next interval)
64 */
65 public static final int COALESCENT = 0;
66
67 /**
68 * Denotes an interval at the end of which a new sample addition is
69 * observed (i.e. the number of lineages is larger in the next interval).
70 */
71 public static final int NEW_SAMPLE = 1;
72
73 /**
74 * Denotes an interval at the end of which nothing is
75 * observed (i.e. the number of lineages is the same in the next interval).
76 */
77 public static final int NOTHING = 2;
78
79
80 public VeryOldCoalescentLikelihood(Tree tree, DemographicModel demoModel) {
81 this(COALESCENT_LIKELIHOOD, tree, demoModel, true);
82 }
83
84 public VeryOldCoalescentLikelihood(String name, Tree tree, DemographicModel demoModel, boolean setupIntervals) {
85
86 super(name);
87
88 this.tree = tree;
89 this.demoModel = demoModel;
90 if (tree instanceof TreeModel) {
91 addModel((TreeModel) tree);
92 }
93 if (demoModel != null) {
94 addModel(demoModel);
95 }
96 if (setupIntervals) setupIntervals();
97
98 addStatistic(new DeltaStatistic());
99 }
100
101 VeryOldCoalescentLikelihood(String name) {
102 super(name);
103 }
104
105 // **************************************************************
106 // Extendable methods
107 // **************************************************************
108
109 /**
110 * @return the node ref of the MRCA of this coalescent prior in the given tree.
111 */
112 public NodeRef getMRCAOfCoalescent(Tree tree) {
113 return tree.getRoot();
114 }
115
116 /**
117 * @return an array of noderefs that represent the MRCAs of subtrees to exclude from coalescent prior.
118 * May return null if no subtrees should be excluded.
119 */
120 public NodeRef[] getExcludedMRCAs(Tree tree) {
121 return null;
122 }
123
124 // **************************************************************
125 // ModelListener IMPLEMENTATION
126 // **************************************************************
127
128 protected void handleModelChangedEvent(Model model, Object object, int index) {
129 if (model == tree) {
130 // treeModel has changed so recalculate the intervals
131 intervalsKnown = false;
132 } else {
133 // demoModel has changed so we don't need to recalculate the intervals
134 }
135
136 likelihoodKnown = false;
137 }
138
139 // **************************************************************
140 // VariableListener IMPLEMENTATION
141 // **************************************************************
142
143 protected final void handleVariableChangedEvent(Variable variable, int index, Parameter.ChangeType type) {
144 } // No parameters to respond to
145
146 // **************************************************************
147 // Model IMPLEMENTATION
148 // **************************************************************
149
150 /**
151 * Stores the precalculated state: in this case the intervals
152 */
153 protected void storeState() {
154 System.arraycopy(intervals, 0, storedIntervals, 0, intervals.length);
155 System.arraycopy(lineageCounts, 0, storedLineageCounts, 0, lineageCounts.length);
156 storedIntervalsKnown = intervalsKnown;
157 storedIntervalCount = intervalCount;
158 storedLikelihoodKnown = likelihoodKnown;
159 storedLogLikelihood = logLikelihood;
160 }
161
162 /**
163 * Restores the precalculated state: that is the intervals of the tree.
164 */
165 protected void restoreState() {
166 System.arraycopy(storedIntervals, 0, intervals, 0, storedIntervals.length);
167 System.arraycopy(storedLineageCounts, 0, lineageCounts, 0, storedLineageCounts.length);
168 intervalsKnown = storedIntervalsKnown;
169 intervalCount = storedIntervalCount;
170 likelihoodKnown = storedLikelihoodKnown;
171 logLikelihood = storedLogLikelihood;
172
173 if (!intervalsKnown) {
174 likelihoodKnown = false;
175 }
176 }
177
178 protected final void acceptState() {
179 } // nothing to do
180
181 /**
182 * Adopt the state of the model from source.
183 */
184 protected final void adoptState(Model source) {
185 // all we need to do is force a recalculation of intervals
186 makeDirty();
187 }
188
189 // **************************************************************
190 // Likelihood IMPLEMENTATION
191 // **************************************************************
192
193 public final Model getModel() {
194 return this;
195 }
196
197 public double getLogLikelihood() {
198 if (!likelihoodKnown) {
199 logLikelihood = calculateLogLikelihood();
200 likelihoodKnown = true;
201 }
202 return logLikelihood;
203 }
204
205 public final void makeDirty() {
206 likelihoodKnown = false;
207 intervalsKnown = false;
208 }
209
210 /**
211 * Calculates the log likelihood of this set of coalescent intervals,
212 * given a demographic model.
213 */
214 public double calculateLogLikelihood() {
215
216 if ( !intervalsKnown ) setupIntervals();
217
218 if (demoModel == null) return calculateAnalyticalLogLikelihood();
219
220 double logL = 0.0;
221
222 double currentTime = 0.0;
223
224 DemographicFunction demoFunction = demoModel.getDemographicFunction();
225
226 for (int j = 0; j < intervalCount; j++) {
227
228
229 logL += calculateIntervalLikelihood(demoFunction, intervals[j], currentTime, lineageCounts[j],
230 getIntervalType(j));
231
232 // insert zero-length coalescent intervals
233 int diff = getCoalescentEvents(j) - 1;
234 for (int k = 0; k < diff; k++) {
235 logL += calculateIntervalLikelihood(demoFunction, 0.0, currentTime, lineageCounts[j] - k - 1, COALESCENT);
236 }
237
238 currentTime += intervals[j];
239 }
240
241 return logL;
242 }
243
244 private double calculateAnalyticalLogLikelihood() {
245
246 final double lambda = getLambda();
247 final int n = tree.getExternalNodeCount();
248
249 // assumes a 1/theta prior
250 //logLikelihood = Math.log(1.0/Math.pow(lambda,n));
251
252 // assumes a flat prior
253 double logL = Math.log(1.0 / Math.pow(lambda, n - 1));
254 return logL;
255 }
256
257 /**
258 * Returns the likelihood of a given *coalescent* interval
259 */
260 public final double calculateIntervalLikelihood(DemographicFunction demoFunction, double width, double timeOfPrevCoal, int lineageCount) {
261
262 return calculateIntervalLikelihood(demoFunction, width, timeOfPrevCoal, lineageCount, COALESCENT);
263 }
264
265 /**
266 * Returns the likelihood of a given interval,coalescent or otherwise.
267 */
268 public final double calculateIntervalLikelihood(DemographicFunction demoFunction, double width, double timeOfPrevCoal,
269 int lineageCount, int type) {
270 //binom.setMax(lineageCount);
271
272 double timeOfThisCoal = width + timeOfPrevCoal;
273
274 // System.err.printf("s: %7.6f f: %7.6f, %d, %d\n", timeOfPrevCoal, timeOfThisCoal, lineageCount, type);
275 double intervalArea = demoFunction.getIntegral(timeOfPrevCoal, timeOfThisCoal);
276 double like = 0;
277 switch (type) {
278 case COALESCENT:
279 like =
280 -Math.log(demoFunction.getDemographic(timeOfThisCoal)) -
281 (Binomial.choose2(lineageCount) * intervalArea);
282 break;
283 case NEW_SAMPLE:
284 like = -(Binomial.choose2(lineageCount) * intervalArea);
285 break;
286 }
287
288 return like;
289 }
290
291 /**
292 * Returns a factor lambda such that the likelihood can be expressed as
293 * 1/theta^(n-1) * exp(-lambda/theta). This allows theta to be integrated
294 * out analytically. :-)
295 */
296 private double getLambda() {
297 double lambda = 0.0;
298 for (int i = 0; i < getIntervalCount(); i++) {
299 lambda += (intervals[i] * lineageCounts[i]);
300 }
301 lambda /= 2;
302
303 return lambda;
304 }
305
306 /**
307 * Recalculates all the intervals from the tree model.
308 */
309 protected final void setupIntervals() {
310
311 double MULTIFURCATION_LIMIT = 1e-9;
312
313 ArrayList times = new ArrayList();
314 ArrayList<Integer> childs = new ArrayList<Integer>();
315 collectAllTimes(tree, getMRCAOfCoalescent(tree), getExcludedMRCAs(tree), times, childs);
316 int[] indices = new int[times.size()];
317
318 HeapSort.sort(times, indices);
319
320 int maxIntervalCount = tree.getNodeCount();
321
322 if (intervals == null) {
323 intervals = new double[maxIntervalCount];
324 lineageCounts = new int[maxIntervalCount];
325 storedIntervals = new double[maxIntervalCount];
326 storedLineageCounts = new int[maxIntervalCount];
327 }
328
329 // start is the time of the first tip
330 double start = ((ComparableDouble) times.get(indices[0])).doubleValue();
331 int numLines = 0;
332 int i = 0;
333 intervalCount = 0;
334 while (i < times.size()) {
335
336 int lineagesRemoved = 0;
337 int lineagesAdded = 0;
338
339 double finish = ((ComparableDouble) times.get(indices[i])).doubleValue();
340 double next = finish;
341
342 while (Math.abs(next - finish) < MULTIFURCATION_LIMIT) {
343 int children = childs.get(indices[i]);
344 if (children == 0) {
345 lineagesAdded += 1;
346 } else {
347 lineagesRemoved += (children - 1);
348 }
349 i += 1;
350 if (i < times.size()) {
351 next = ((ComparableDouble) times.get(indices[i])).doubleValue();
352 } else break;
353 }
354 //System.out.println("time = " + finish + " removed = " + lineagesRemoved + " added = " + lineagesAdded);
355 if (lineagesAdded > 0) {
356
357 if (intervalCount > 0 || ((finish - start) > MULTIFURCATION_LIMIT)) {
358 intervals[intervalCount] = finish - start;
359 lineageCounts[intervalCount] = numLines;
360 intervalCount += 1;
361 }
362
363 start = finish;
364 }
365 // add sample event
366 numLines += lineagesAdded;
367
368 if (lineagesRemoved > 0) {
369
370 intervals[intervalCount] = finish - start;
371 lineageCounts[intervalCount] = numLines;
372 intervalCount += 1;
373 start = finish;
374 }
375 // coalescent event
376 numLines -= lineagesRemoved;
377 }
378 intervalsKnown = true;
379 }
380
381
382 /**
383 * extract coalescent times and tip information into ArrayList times from tree.
384 *
385 * @param node the node to start from
386 * @param excludeBelow an optional array of nodes to exclude (corresponding subtrees) from density.
387 */
388 private static void collectAllTimes(Tree tree, NodeRef node, NodeRef[] excludeBelow, ArrayList times, ArrayList<Integer> childs) {
389
390 times.add(new ComparableDouble(tree.getNodeHeight(node)));
391 childs.add(tree.getChildCount(node));
392
393 for (int i = 0; i < tree.getChildCount(node); i++) {
394 NodeRef child = tree.getChild(node, i);
395 if (excludeBelow == null) {
396 collectAllTimes(tree, child, excludeBelow, times, childs);
397 } else {
398 // check if this subtree is included in the coalescent density
399 boolean include = true;
400 for(NodeRef anExcludeBelow : excludeBelow) {
401 if( anExcludeBelow.getNumber() == child.getNumber() ) {
402 include = false;
403 break;
404 }
405 }
406 if (include) collectAllTimes(tree, child, excludeBelow, times, childs);
407 }
408 }
409 }
410
411
412 /**
413 * get number of intervals
414 */
415 public final int getIntervalCount() {
416 return intervalCount;
417 }
418
419 /**
420 * Gets an interval.
421 */
422 public final double getInterval(int i) {
423 if (i >= intervalCount) throw new IllegalArgumentException();
424 return intervals[i];
425 }
426
427 /**
428 * Returns the number of uncoalesced lineages within this interval.
429 * Required for s-coalescents, where new lineages are added as
430 * earlier samples are come across.
431 */
432 public final int getLineageCount(int i) {
433 if (i >= intervalCount) throw new IllegalArgumentException();
434 return lineageCounts[i];
435 }
436
437 /**
438 * Returns the number coalescent events in an interval
439 */
440 public final int getCoalescentEvents(int i) {
441
442 if (i >= intervalCount) throw new IllegalArgumentException();
443 if (i < intervalCount - 1) {
444 return lineageCounts[i] - lineageCounts[i + 1];
445 } else {
446 return lineageCounts[i] - 1;
447 }
448 }
449
450 /**
451 * Returns the type of interval observed.
452 */
453 public final int getIntervalType(int i) {
454
455 if (i >= intervalCount) throw new IllegalArgumentException();
456 int numEvents = getCoalescentEvents(i);
457
458 if (numEvents > 0) return COALESCENT;
459 else if (numEvents < 0) return NEW_SAMPLE;
460 else return NOTHING;
461 }
462
463 /**
464 * get the total height of the genealogy represented by these
465 * intervals.
466 */
467 public final double getTotalHeight() {
468
469 double height = 0.0;
470 for (int j = 0; j < intervalCount; j++) {
471 height += intervals[j];
472 }
473 return height;
474 }
475
476 /**
477 * Checks whether this set of coalescent intervals is fully resolved
478 * (i.e. whether is has exactly one coalescent event in each
479 * subsequent interval)
480 */
481 public final boolean isBinaryCoalescent() {
482 for (int i = 0; i < intervalCount; i++) {
483 if (getCoalescentEvents(i) != 1) return false;
484 }
485
486 return true;
487 }
488
489 /**
490 * Checks whether this set of coalescent intervals coalescent only
491 * (i.e. whether is has exactly one or more coalescent event in each
492 * subsequent interval)
493 */
494 public final boolean isCoalescentOnly() {
495 for (int i = 0; i < intervalCount; i++) {
496 if (getCoalescentEvents(i) < 1) return false;
497 }
498 return true;
499 }
500
501 public String toString() {
502 return Double.toString(getLogLikelihood());
503
504 }
505
506 // **************************************************************
507 // Units IMPLEMENTATION
508 // **************************************************************
509
510
511 public final Type getUnits() {
512 return demoModel.getUnits();
513 }
514
515 public void setUnits(Type units) {
516 demoModel.setUnits(units);
517
518 }
519
520 // ****************************************************************
521 // Inner classes
522 // ****************************************************************
523
524 public class DeltaStatistic extends Statistic.Abstract {
525
526 public DeltaStatistic() {
527 super("delta");
528 }
529
530 public int getDimension() {
531 return 1;
532 }
533
534 public double getStatisticValue(int i) {
535 throw new RuntimeException("Not implemented");
536 // return IntervalList.Utils.getDelta(intervals);
537 }
538
539 }
540
541 // ****************************************************************
542 // Private and protected stuff
543 // ****************************************************************
544
545 public static XMLObjectParser PARSER = new AbstractXMLObjectParser() {
546
547 public String getParserName() {
548 return COALESCENT_LIKELIHOOD;
549 }
550
551 public Object parseXMLObject(XMLObject xo) {
552
553 XMLObject cxo = xo.getChild(MODEL);
554 DemographicModel demoModel = (DemographicModel) cxo.getChild(DemographicModel.class);
555
556 cxo = xo.getChild(POPULATION_TREE);
557 TreeModel treeModel = (TreeModel) cxo.getChild(TreeModel.class);
558
559 return new VeryOldCoalescentLikelihood(treeModel, demoModel);
560 }
561
562 //************************************************************************
563 // AbstractXMLObjectParser implementation
564 //************************************************************************
565
566 public String getParserDescription() {
567 return "This element represents the likelihood of the tree given the demographic function.";
568 }
569
570 public Class getReturnType() {
571 return Likelihood.class;
572 }
573
574 public XMLSyntaxRule[] getSyntaxRules() {
575 return rules;
576 }
577
578 private final XMLSyntaxRule[] rules = {
579 new ElementRule(MODEL, new XMLSyntaxRule[]{
580 new ElementRule(DemographicModel.class)
581 }),
582 new ElementRule(POPULATION_TREE, new XMLSyntaxRule[]{
583 new ElementRule(TreeModel.class)
584 }),
585 };
586 };
587
588 // ****************************************************************
589 // Private and protected stuff
590 // ****************************************************************
591
592 /* public static XMLObjectParser PARSER = new AbstractXMLObjectParser() {
593
594 public String getParserName() { return COALESCENT_LIKELIHOOD; }
595
596 public Object parseXMLObject(XMLObject xo) throws XMLParseException {
597
598 DemographicModel demoModel = null;
599 if (xo.hasAttribute(MODEL)) {
600 demoModel = (DemographicModel)xo.getAttribute(MODEL);
601 }
602 TreeModel treeModel = (TreeModel)xo.getAttribute(TREE);
603 return new VeryOldCoalescentLikelihood(treeModel, demoModel);
604 }
605
606 //************************************************************************
607 // AbstractXMLObjectParser implementation
608 //************************************************************************
609
610 public String getParserDescription() {
611 return "This element represents the likelihood of the tree given the demographic function.";
612 }
613
614 public Class getReturnType() { return Likelihood.class; }
615
616 public XMLSyntaxRule[] getSyntaxRules() { return rules; }
617
618 private XMLSyntaxRule[] rules = new XMLSyntaxRule[] {
619 new XORRule(
620 new EnumAttributeRule(ANALYTICAL, new String[] { "constant" }),
621 new AttributeRule(MODEL, DemographicModel.class)
622 ),
623 new AttributeRule(TREE, TreeModel.class)
624 };
625 };*/
626
627 /**
628 * The demographic model.
629 */
630 DemographicModel demoModel = null;
631
632 /**
633 * The tree.
634 */
635 Tree tree = null;
636
637 /**
638 * The widths of the intervals.
639 */
640 double[] intervals;
641 private double[] storedIntervals;
642
643 /**
644 * The number of uncoalesced lineages within a particular interval.
645 */
646 int[] lineageCounts;
647 private int[] storedLineageCounts;
648
649 boolean intervalsKnown = false;
650 protected boolean storedIntervalsKnown = false;
651
652 double logLikelihood;
653 protected double storedLogLikelihood;
654 boolean likelihoodKnown = false;
655 protected boolean storedLikelihoodKnown = false;
656
657 int intervalCount = 0;
658 private int storedIntervalCount = 0;
659 }