Debian Codegraph @

src/dr/evomodel/speciation/MultiSpeciesCoalescent.java

raw symbols SCIP
1 /*
2 * MultiSpeciesCoalescent.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.speciation;
27
28 import dr.evolution.coalescent.DemographicFunction;
29 import dr.evolution.coalescent.ScaledDemographic;
30 import dr.evolution.tree.NodeRef;
31 import dr.evolution.tree.TreeUtils;
32 import dr.evolution.util.Units;
33 import dr.inference.model.Likelihood;
34 import dr.inference.model.Model;
35 import jebl.util.FixedBitSet;
36
37 import java.util.Arrays;
38
39 /**
40 * Compute coalecent log-liklihood of a set of gene trees embedded inside one species tree.
41 *
42 * @author Joseph Heled, Graham Jones
43 * Date: 26/05/2008
44 */
45 public class MultiSpeciesCoalescent extends Likelihood.Abstract implements Units {
46 private final SpeciesTreeModel spTree;
47 private final SpeciesBindings species;
48 private boolean checkCompatibility;
49 private final boolean[] compatibleCheckRequited;
50
51 public MultiSpeciesCoalescent(SpeciesBindings species, SpeciesTreeModel tree) {
52 super(tree);
53 spTree = tree;
54 this.species = species;
55
56 spTree.addModelRestoreListener(this);
57
58 // recompute on any change in geneTree -
59 // possible optimization: keep track which tree changed.
60 final SpeciesBindings.GeneTreeInfo[] trees = species.getGeneTrees();
61 for(SpeciesBindings.GeneTreeInfo geneTree : trees) {
62 geneTree.tree.addModelListener(this);
63 }
64
65 compatibleCheckRequited = new boolean[trees.length];
66 Arrays.fill(compatibleCheckRequited, false);
67 checkCompatibility = false;
68 }
69
70 // override this for efficiency, otherwise the overridden makeDirty, which results in additional overhead is called
71 public void modelRestored(Model model) {
72 super.makeDirty();
73 }
74
75 // Upon a direct "make dirty" enable all compatibility checks, since the last call to calculateLogLikelihood may have
76 // found a non compatible tree and returned -inf. This case is not explicitly saved.
77 public void makeDirty() {
78 super.makeDirty();
79 checkCompatibility = true;
80 for(int i = 0; i < species.getGeneTrees().length; i++) {
81 compatibleCheckRequited[i] = true;
82 }
83 }
84
85 protected double calculateLogLikelihood() {
86 if( checkCompatibility ) {
87 boolean compatibility = true;
88
89 for(int i = 0; i < compatibleCheckRequited.length; ++i) {
90 if( compatibleCheckRequited[i] ) {
91
92 if( !spTree.isCompatible(species.getGeneTrees()[i]) ) {
93 compatibility = false;
94 }
95 compatibleCheckRequited[i] = false;
96 //System.out.println("check compatibility:" + species.getGeneTrees()[i].tree.getId() + " - " + compatibility );
97 }
98 }
99 if( !compatibility ) {
100 return Double.NEGATIVE_INFINITY;
101 }
102 checkCompatibility = false;
103 }
104
105 double logl = 0;
106 int[] info = {0, 0};
107 for( SpeciesBindings.GeneTreeInfo geneTree : species.getGeneTrees() ) {
108 final double v = treeLogLikelihood(geneTree, spTree.getRoot(), info, geneTree.popFactor());
109 assert ! Double.isNaN(v);
110 // if( Double.isNaN(v) ) {
111 // double x = 0;
112 // }
113 logl += v;
114 }
115 ccc += 1;
116 return logl;
117 }
118 int ccc = 0;
119 private final boolean verbose = false;
120
121 private double treeLogLikelihood(SpeciesBindings.GeneTreeInfo geneTree, NodeRef node, int[] info, double popFactor) {
122 // number of lineages remaining at node
123 int nLineages;
124 // location in coalescent list (optimization)
125 int indexInClist = 0;
126 // accumulated log-likelihood inBranchh from node to it's parent
127 double like = 0;
128
129 final double t0 = spTree.getNodeHeight(node);
130
131 final SpeciesBindings.CoalInfo[] cList = geneTree.getCoalInfo();
132
133 if( verbose ) {
134 if( spTree.isRoot(node) ) {
135 System.err.println("gtree:" + geneTree.tree.getId());
136 System.err.println("t0 " + t0);
137 for(int k = 0; k < cList.length; ++k) {
138 System.err.println(k + " " + cList[k].ctime + " " + cList[k].sinfo[0] + " " + cList[k].sinfo[1]);
139 }
140 }
141 }
142
143 if( spTree.isExternal(node) ) {
144 nLineages = geneTree.nLineages(spTree.speciesIndex(node));
145 indexInClist = 0;
146 } else {
147 //assert spTree.getChildCount(node) == 2;
148
149 nLineages = 0;
150 for(int nc = 0; nc < 2; ++nc) {
151 final NodeRef child = spTree.getChild(node, nc);
152 like += treeLogLikelihood(geneTree, child, info, popFactor);
153 nLineages += info[0];
154 indexInClist = Math.max(indexInClist, info[1]);
155 }
156
157 // The root of every gene tree (last coalescent point) should be always above
158 // root of species tree
159 if( indexInClist >= cList.length) {
160 int k = 1;
161 }
162 assert indexInClist < cList.length;
163
164 // Skip over (presumably, not tested by assert) non interesting coalescent
165 // events to the first event before speciation point
166
167 while( cList[indexInClist].ctime < t0 ) {
168 ++indexInClist;
169 }
170 }
171
172 final boolean isRoot = spTree.isRoot(node);
173
174 // Upper limit
175 // use of (t0 + spTree.getBranchLength(node)) caused problem since there was a tiny difference
176 // between those (supposedly equal) values. we should track where the discrepancy comes from.
177 final double stopTime = isRoot ? Double.MAX_VALUE : spTree.getNodeHeight(spTree.getParent(node));
178
179 // demographic function is 0 based (relative to node height)
180 // time away from node
181 double lastTime = 0.0;
182
183 // demographic function across branch
184 DemographicFunction demog = spTree.getNodeDemographic(node);
185 if( popFactor > 0 ) {
186 demog = new ScaledDemographic(demog, popFactor);
187 }
188
189 // if(false) {
190 // final double duration = isRoot ? cList[cList.length - 1].ctime - t0 : stopTime;
191 // double demographicAtCoalPoint = demog.getDemographic(duration);
192 // double intervalArea = demog.getIntegral(0, duration);
193 // if( demographicAtCoalPoint < 1e-12 * (duration/intervalArea) ) {
194 // return Double.NEGATIVE_INFINITY;
195 // }
196 // }
197 // Species sharing this branch
198 FixedBitSet subspeciesSet = spTree.spSet(node);
199
200 if( verbose ) {
201 System.err.println(TreeUtils.uniqueNewick(spTree, node) + " nl " + nLineages
202 + " " + subspeciesSet + " t0 - st " + t0 + " - " + stopTime);
203 }
204
205 while( nLineages > 1 ) {
206 // if ( !( indexInClist < cList.length ) ) {
207 // System.err.println( indexInClist ) ;
208 // }
209 assert ( indexInClist < cList.length );
210
211 final double nextT = cList[indexInClist].ctime;
212
213 // while rare they can be equal
214 if( nextT >= stopTime ) {
215 break;
216 }
217
218 if( nonEmptyIntersection(cList[indexInClist].sinfo, subspeciesSet) ) {
219 final double time = nextT - t0;
220 if( time > 0 ) {
221 final double interval = demog.getIntegral(lastTime, time);
222 lastTime = time;
223
224 final int nLineageOver2 = (nLineages * (nLineages - 1)) / 2;
225 like -= nLineageOver2 * interval;
226
227 final double pop = demog.getDemographic(time); assert( pop > 0 );
228 like -= Math.log(pop);
229 }
230 --nLineages;
231 }
232 ++indexInClist;
233 }
234
235
236 if( nLineages > 1 ) {
237 // add term for No coalescent until root
238 final double interval = demog.getIntegral(lastTime, stopTime - t0);
239
240 final int nLineageOver2 = (nLineages * (nLineages - 1)) / 2;
241
242 like -= nLineageOver2 * interval;
243 }
244
245 info[0] = nLineages;
246 info[1] = indexInClist;
247 if( verbose ) {
248 System.err.println(TreeUtils.uniqueNewick(spTree, node) + " stopTime " + stopTime +
249 " nl " + nLineages + " icl " + indexInClist);
250 }
251 return like;
252 }
253
254 public void modelChangedEvent(Model model, Object object, int index) {
255 //super.modelChangedEvent(model, object, index);
256 // not the above for efficiency, otherwise the overridden makeDirty, which results in additional overhead is called.
257 super.makeDirty();
258
259 if( model == spTree ) {
260 if( object == spTree && index != -1 ) {
261 // Species tree scaling
262 checkCompatibility = true;
263 Arrays.fill(compatibleCheckRequited, true);
264 }
265 } else {
266
267 final SpeciesBindings.GeneTreeInfo[] trees = species.getGeneTrees();
268 for(int i = 0; i < species.getGeneTrees().length; i++) {
269 if( trees[i].tree == model ) {
270 checkCompatibility = true;
271 compatibleCheckRequited[i] = true;
272 break;
273 }
274 }
275 }
276 }
277
278 private boolean nonEmptyIntersection(FixedBitSet[] sinfo, FixedBitSet subspeciesSet) {
279 for( FixedBitSet nodeSpSet : sinfo ) {
280 if( nodeSpSet.intersectCardinality(subspeciesSet) == 0 ) {
281 return false;
282 }
283 }
284 return true;
285 }
286
287
288 public Type getUnits() {
289 return spTree.getUnits();
290 }
291
292 public void setUnits(Type units) {
293 assert false;
294 }
295
296 }