Debian Codegraph @

src/dr/evomodel/speciation/SpeciesBindings.java

raw symbols SCIP
1 /*
2 * SpeciesBindings.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.tree.MutableTree;
29 import dr.evolution.tree.NodeRef;
30 import dr.evolution.tree.Tree;
31 import dr.evolution.util.Taxon;
32 import dr.evomodel.tree.TreeModel;
33 import dr.inference.model.*;
34 import dr.util.HeapSort;
35 import jebl.util.FixedBitSet;
36
37 import java.util.Arrays;
38 import java.util.HashMap;
39 import java.util.Map;
40
41 /**
42 * Binds taxa in gene trees with species information.
43 *
44 * @author Joseph Heled
45 * Date: 25/05/2008
46 */
47 public class SpeciesBindings extends AbstractModel {
48 // all gene trees
49 private final GeneTreeInfo[] geneTrees;
50
51 // convenience
52 private final Map<Taxon, Integer> taxon2Species = new HashMap<Taxon, Integer>();
53
54 // Species definition
55 final SPinfo[] species;
56
57 private final double[][] popTimesPair;
58 private boolean dirty_pp;
59
60 private final double[][] popTimesSingle;
61 private boolean dirty_sg;
62 private final boolean verbose = false;
63
64 public SpeciesBindings(SPinfo[] species, TreeModel[] geneTrees, double[] popFactors) {
65 super(null);
66
67 this.species = species;
68
69 final int nsp = species.length;
70
71 for (int ns = 0; ns < nsp; ++ns) {
72 for (Taxon t : species[ns].taxa) {
73 if (taxon2Species.containsKey(t)) {
74 throw new Error("Multiple assignments for taxon" + t);
75 }
76 taxon2Species.put(t, ns);
77 }
78 }
79
80 this.geneTrees = new GeneTreeInfo[geneTrees.length];
81
82 for (int i = 0; i < geneTrees.length; i++) {
83 final TreeModel t = geneTrees[i];
84 addModel(t);
85 this.geneTrees[i] = new GeneTreeInfo(t, popFactors[i]);
86 }
87
88 for (GeneTreeInfo gt : this.geneTrees) {
89 for (int ns = 0; ns < nsp; ++ns) {
90 if (gt.nLineages(ns) == 0) {
91 throw new Error("Every gene tree must contain at least one tip from each species ("
92 + gt.tree.getId() + "," + species[ns].name + ")");
93 }
94 }
95 }
96
97 popTimesSingle = new double[nsp][];
98 for (int ns = 0; ns < popTimesSingle.length; ++ns) {
99 popTimesSingle[ns] = new double[allCoalPointsCount(ns)];
100 }
101 dirty_sg = true;
102
103 popTimesPair = new double[(nsp * (nsp - 1)) / 2][];
104 {
105 final int nps = allPairCoalPointsCount();
106 for (int ns = 0; ns < popTimesPair.length; ++ns) {
107 popTimesPair[ns] = new double[nps];
108 }
109 }
110
111 dirty_pp = true;
112
113 addStatistic(new SpeciesLimits());
114 }
115
116 public int nSpecies() {
117 return species.length;
118 }
119
120 /**
121 * Per species coalecent times.
122 * <p/>
123 * Indexed by sp index, a list of coalescent times of taxa of this sp from all gene trees.
124 *
125 * @return Per species coalecent times
126 */
127 public double[][] getPopTimesSingle() {
128 if (dirty_sg) {
129 for (int ns = 0; ns < popTimesSingle.length; ++ns) {
130 getAllCoalPoints(ns, popTimesSingle[ns]);
131 }
132 dirty_sg = false;
133 }
134 return popTimesSingle;
135 }
136
137 public double[][] getPopTimesPair() {
138 if (dirty_pp) {
139 final int nsp = nSpecies();
140 for (int ns1 = 0; ns1 < nsp - 1; ++ns1) {
141 final int z = (ns1 * (2 * nsp - ns1 - 3)) / 2 - 1;
142
143 for (int ns2 = ns1 + 1; ns2 < nsp; ++ns2) {
144 getAllPairCoalPoints(ns1, ns2, popTimesPair[z + ns2]);
145 }
146 }
147 }
148 return popTimesPair;
149 }
150
151 private void getAllPairCoalPoints(int ns1, int ns2, double[] popTimes) {
152
153 for (int i = 0; i < geneTrees.length; i++) {
154 for (CoalInfo ci : geneTrees[i].getCoalInfo()) {
155 if ((ci.sinfo[0].contains(ns1) && ci.sinfo[1].contains(ns2)) ||
156 (ci.sinfo[1].contains(ns1) && ci.sinfo[0].contains(ns2))) {
157 popTimes[i] = ci.ctime;
158 break;
159 }
160 }
161 }
162 HeapSort.sort(popTimes);
163 }
164
165 private int allCoalPointsCount(int spIndex) {
166 int tot = 0;
167 for (GeneTreeInfo t : geneTrees) {
168 if (t.nLineages(spIndex) > 0) {
169 tot += t.nLineages(spIndex) - 1;
170 }
171 }
172 return tot;
173 }
174
175 // length of points must be right
176 void getAllCoalPoints(int spIndex, double[] points) {
177
178 int k = 0;
179 for (GeneTreeInfo t : geneTrees) {
180 final int totCoalEvents = t.nLineages(spIndex) - 1;
181 int savek = k;
182 for (CoalInfo ci : t.getCoalInfo()) {
183 // if( ci == null ) {
184 // assert ci != null;
185 // }
186 if (ci.allHas(spIndex)) {
187 points[k] = ci.ctime;
188 ++k;
189 }
190 }
191 if (!(totCoalEvents >= 0 && savek + totCoalEvents == k) || (totCoalEvents < 0 && savek == k)) {
192 System.err.println(totCoalEvents);
193 }
194 assert (totCoalEvents >= 0 && savek + totCoalEvents == k) || (totCoalEvents < 0 && savek == k);
195 }
196 assert k == points.length;
197 HeapSort.sort(points);
198 }
199
200 private int allPairCoalPointsCount() {
201 return geneTrees.length;
202 }
203
204 public double speciationUpperBound(FixedBitSet sub1, FixedBitSet sub2) {
205 //Determined by the last time any pair of sp's in sub1 x sub2 have been seen
206 // together in any of the gene trees."""
207
208 double bound = Double.MAX_VALUE;
209 for (GeneTreeInfo g : getGeneTrees()) {
210 for (CoalInfo ci : g.getCoalInfo()) {
211 // if past time of current bound, can't change it anymore
212 if (ci.ctime >= bound) {
213 break;
214 }
215 if ((ci.sinfo[0].intersectCardinality(sub1) > 0 && ci.sinfo[1].intersectCardinality(sub2) > 0)
216 ||
217 (ci.sinfo[0].intersectCardinality(sub2) > 0 && ci.sinfo[1].intersectCardinality(sub1) > 0)) {
218 bound = ci.ctime;
219 break;
220 }
221 }
222 }
223 return bound;
224 }
225
226 public void makeCompatible(double rootHeight) {
227 for( GeneTreeInfo t : getGeneTrees() ) {
228
229 MutableTree tree = t.tree;
230
231 for (int i = 0; i < tree.getExternalNodeCount(); i++) {
232 final NodeRef node = tree.getExternalNode(i);
233 final NodeRef p = tree.getParent(node);
234 tree.setNodeHeight(p, rootHeight + tree.getNodeHeight(p));
235 }
236 MutableTree.Utils.correctHeightsForTips(tree);
237 // (todo) ugly re-init - can I do something better?
238 t.wasChanged();
239 t.getCoalInfo();
240 t.wasBacked = false;
241 //t.wasChanged();
242 }
243 }
244
245 /**
246 * Information on one species (sp)
247 */
248 public static class SPinfo extends Taxon {
249 // sp name
250 final public String name;
251
252 // all taxa belonging to sp
253 private final Taxon[] taxa;
254
255 public SPinfo(String name, Taxon[] taxa) {
256 super(name);
257
258 this.name = name;
259 this.taxa = taxa;
260 }
261 }
262
263 class CoalInfo implements Comparable<CoalInfo> {
264 // zero based, 0 is taxa time, i.e. in tree branch units
265 final double ctime;
266 // sp info for each subtree
267 final FixedBitSet[] sinfo;
268
269 CoalInfo(double t, int nc) {
270 ctime = t;
271 sinfo = new FixedBitSet[nc];
272 }
273
274 public int compareTo(CoalInfo o) {
275 return o.ctime < ctime ? +1 : (o.ctime > ctime ? -1 : 0);
276 }
277
278 /**
279 * @param s
280 * @return true if all children have at least one taxa from sp 's'
281 */
282 public boolean allHas(int s) {
283 for (FixedBitSet b : sinfo) {
284 if (!b.contains(s)) {
285 return false;
286 }
287 }
288 return true;
289 }
290 }
291
292 /**
293 * Collect coalescence information for sub-tree rooted at 'node'.
294 *
295 * @param tree
296 * @param node
297 * @param loc Place node data in loc, sub-tree info before that.
298 * @param info array to fill
299 * @return location of next available location
300 */
301 private int collectCoalInfo(Tree tree, NodeRef node, int loc, CoalInfo[] info) {
302
303 info[loc] = new CoalInfo(tree.getNodeHeight(node), tree.getChildCount(node));
304
305 int newLoc = loc - 1;
306 for (int i = 0; i < 2; i++) {
307 NodeRef child = tree.getChild(node, i);
308 info[loc].sinfo[i] = new FixedBitSet(nSpecies());
309
310 if (tree.isExternal(child)) {
311 info[loc].sinfo[i].set(taxon2Species.get(tree.getNodeTaxon(child)));
312 assert tree.getNodeHeight(child) == 0;
313 } else {
314 final int used = collectCoalInfo(tree, child, newLoc, info);
315 for (int j = 0; j < info[newLoc].sinfo.length; ++j) {
316 info[loc].sinfo[i].union(info[newLoc].sinfo[j]);
317 }
318 newLoc = used;
319 }
320 }
321 return newLoc;
322 }
323
324 public class GeneTreeInfo {
325 public final TreeModel tree;
326 private final int[] lineagesCount;
327 private CoalInfo[] cList;
328 private CoalInfo[] savedcList;
329 private boolean dirty;
330 private boolean wasBacked;
331 private final double popFactor;
332
333 GeneTreeInfo(TreeModel tree, double popFactor) {
334 this.tree = tree;
335 this.popFactor = popFactor;
336
337 lineagesCount = new int[species.length];
338 Arrays.fill(lineagesCount, 0);
339
340 for (int nl = 0; nl < lineagesCount.length; ++nl) {
341 for (Taxon t : species[nl].taxa) {
342 if (tree.getTaxonIndex(t) >= 0) {
343 ++lineagesCount[nl];
344 }
345 }
346 }
347
348 cList = new CoalInfo[tree.getExternalNodeCount() - 1];
349 savedcList = new CoalInfo[cList.length];
350 wasChanged();
351 getCoalInfo();
352 wasBacked = false;
353 }
354
355 int nLineages(int speciesIndex) {
356 return lineagesCount[speciesIndex];
357 }
358
359 public CoalInfo[] getCoalInfo() {
360 if (dirty) {
361 swap();
362
363 collectCoalInfo(tree, tree.getRoot(), cList.length - 1, cList);
364 HeapSort.sort(cList);
365 dirty = false;
366 wasBacked = true;
367 }
368 return cList;
369 }
370
371 private void swap() {
372 CoalInfo[] tmp = cList;
373 cList = savedcList;
374 savedcList = tmp;
375 }
376
377 void wasChanged() {
378 dirty = true;
379 wasBacked = false;
380 }
381
382 boolean restore() {
383 if (verbose) System.out.println(" SP binding: restore " + tree.getId() + " (" + wasBacked + ")");
384 if (wasBacked) {
385 // if( false ) {
386 // swap();
387 // dirty = true;
388 // getCoalInfo();
389 // for(int k = 0; k < cList.length; ++k) {
390 // assert cList[k].ctime == savedcList[k].ctime &&
391 // cList[k].sinfo[0].equals(savedcList[k].sinfo[0]) &&
392 // cList[k].sinfo[1].equals(savedcList[k].sinfo[1]);
393 // }
394 // }
395 swap();
396 wasBacked = false;
397 dirty = false;
398 return true;
399 }
400 return false;
401 }
402
403 void accept() {
404 if (verbose) System.out.println(" SP binding: accept " + tree.getId());
405
406 wasBacked = false;
407 }
408
409 public double popFactor() {
410 return popFactor;
411 }
412 }
413
414 public GeneTreeInfo[] getGeneTrees() {
415 return geneTrees;
416 }
417
418 protected void handleModelChangedEvent(Model model, Object object, int index) {
419 if (verbose) System.out.println(" SP binding: model changed " + model.getId());
420
421 dirty_sg = true;
422 dirty_pp = true;
423
424 for (GeneTreeInfo g : geneTrees) {
425 if (g.tree == model) {
426 g.wasChanged();
427 break;
428 }
429 }
430 fireModelChanged(object, index);
431 }
432
433 protected final void handleVariableChangedEvent(Variable variable, int index, Parameter.ChangeType type) {
434 assert false;
435 }
436
437 protected void storeState() {
438 // do on a per need basis
439 }
440
441 protected void restoreState() {
442 for (GeneTreeInfo g : geneTrees) {
443 if (g.restore()) {
444 dirty_sg = true;
445 dirty_pp = true;
446 }
447 }
448 }
449
450 protected void acceptState() {
451 for (GeneTreeInfo g : geneTrees) {
452 g.accept();
453 }
454 }
455
456 public class SpeciesLimits extends Statistic.Abstract {
457 int nDim;
458 int c[][];
459
460 SpeciesLimits() {
461 super("SpeciationBounds");
462
463 nDim = 0;
464
465 final int nsp = species.length;
466
467 c = new int[nsp + 1][nsp + 1];
468 for(int k = 0; k < nsp + 1; ++k) {
469 c[k][0] = 1;
470 c[k][k] = 1;
471 }
472 for(int k = 0; k < nsp + 1; ++k) {
473 for(int j = 1; j < k; ++j) {
474 c[k][j] = c[k - 1][j - 1] + c[k - 1][j];
475 }
476 }
477
478 for(int k = 0; k <= (int) (nsp / 2); ++k) {
479 nDim += c[nsp][k];
480 }
481
482 }
483
484 public int getDimension() {
485 return nDim;
486 }
487
488 private double boundOnRoot() {
489 double bound = Double.MAX_VALUE;
490 final int nsp = species.length;
491 for(GeneTreeInfo g : getGeneTrees()) {
492 for(CoalInfo ci : g.getCoalInfo()) {
493 if( ci.sinfo[0].cardinality() == nsp || ci.sinfo[1].cardinality() == nsp ) {
494 bound = Math.min(bound, ci.ctime);
495 break;
496 }
497 }
498 }
499 return bound;
500 }
501
502 public double getStatisticValue(int dim) {
503 if( dim == 0 ) {
504 return boundOnRoot();
505 }
506
507 final int nsp = species.length;
508 int r = 0;
509 int k;
510 for(k = 0; k <= (int) (nsp / 2); ++k) {
511 final int i = c[nsp][k];
512 if( dim < r + i ) {
513 break;
514 }
515 r += i;
516 }
517
518 // Classic index -> select k of nsp subset
519
520 // number of species in set is k
521 int n = dim - r;
522 FixedBitSet in = new FixedBitSet(nsp),
523 out = new FixedBitSet(nsp);
524 int fr = nsp;
525 for(int i = 0; i < nsp; ++i) {
526 if( k == 0 ) {
527 out.set(i);
528 } else {
529 if( n < c[fr - 1][k - 1] ) {
530 in.set(i);
531 k -= 1;
532 } else {
533 out.set(i);
534 n -= c[fr - 1][k];
535 }
536 fr -= 1;
537 }
538 }
539 return speciationUpperBound(in, out);
540 }
541 }
542 }