Debian Codegraph @

src/dr/evomodel/alloppnet/speciation/MulMSCoalescent.java

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