Debian Codegraph @

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

raw symbols SCIP
1 /*
2 * MulSpeciesBindings.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.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.evomodel.alloppnet.parsers.MulSpeciesBindingsParser;
34 import dr.inference.loggers.LogColumn;
35 import dr.inference.loggers.Loggable;
36 import dr.inference.model.*;
37 import dr.math.MathUtils;
38 import dr.util.HeapSort;
39 import jebl.util.FixedBitSet;
40
41 import java.util.Arrays;
42 import java.util.HashMap;
43 import java.util.HashSet;
44 import java.util.Map;
45 import java.util.Set;
46
47 /**
48 * Binds taxa in gene trees to multiply labelled species.
49 *
50 * Extension of Joseph Heled's SpeciesBindings to deal with multiply labelled trees.
51 * It combines the SpeciesBindings code with functions from AlloppSpeciesBindings.
52 *
53 * @author Joseph Heled, Graham Jones
54 * Date: 21/12/2011
55 */
56
57
58
59 public class MulSpeciesBindings extends AbstractModel implements Loggable {
60 // grj all gene trees
61 private final GeneTreeInfo[] geneTreeInfos;
62
63 // grj Species definition
64 private final AlloppSpeciesBindings.ApSpInfo[] apspecies;
65 private final Taxon[] taxa;
66 private final Map<Taxon, Integer> taxon2index = new HashMap<Taxon, Integer>();
67 private final int spsq[][];
68 private final int numberOfSpSeqs;
69
70
71 // jh
72 private final double[][] popTimesPair;
73 private boolean dirty_pp;
74
75 private final double[][] popTimesSingle;
76 private boolean dirty_sg;
77 private final boolean verbose = false;
78
79 // grj
80 private class SpeciesIndivPair {
81 public int spIndex;
82 public int ivIndex;
83
84 public SpeciesIndivPair(int spIndex, int ivIndex) {
85 this.spIndex = spIndex;
86 this.ivIndex = ivIndex;
87 }
88 }
89
90
91 // mostly grj
92 public MulSpeciesBindings(AlloppSpeciesBindings.ApSpInfo[] apspecies, TreeModel[] geneTrees, double[] popFactors) {
93 super(MulSpeciesBindingsParser.MUL_SPECIES);
94
95 this.apspecies = apspecies;
96
97 // make the flattened arrays
98 int n = 0;
99 for (AlloppSpeciesBindings.ApSpInfo apspi : apspecies) {
100 n += apspi.individuals.length;
101 }
102 AlloppSpeciesBindings.Individual [] indivs = new AlloppSpeciesBindings.Individual[n];
103 n = 0;
104 for (AlloppSpeciesBindings.ApSpInfo apspi : apspecies) {
105 for (int i = 0; i < apspi.individuals.length; i++, n++) {
106 indivs[n] = apspi.individuals[i];
107 }
108 }
109 int t = 0;
110 for (AlloppSpeciesBindings.Individual indiv : indivs) {
111 t += indiv.taxa.length;
112 }
113 taxa = new Taxon[t];
114 t = 0;
115 for (AlloppSpeciesBindings.Individual indiv : indivs) {
116 for (int j = 0; j < indiv.taxa.length; j++, t++) {
117 taxa[t] = indiv.taxa[j];
118 }
119 }
120 // set up maps to indices
121 for (int i = 0; i < taxa.length; i++) {
122 taxon2index.put(taxa[i], i);
123 }
124 spsq = new int[apspecies.length][];
125 int spsqindex = 0;
126 for (int sp = 0; sp < apspecies.length; sp++) {
127 spsq[sp] = new int[apspecies[sp].ploidylevel/2];
128 for (int seq = 0; seq < spsq[sp].length; seq++, spsqindex++) {
129 spsq[sp][seq] = spsqindex;
130 }
131 }
132 numberOfSpSeqs = spsqindex;
133
134 geneTreeInfos = new GeneTreeInfo[geneTrees.length];
135 for (int i = 0; i < geneTrees.length; i++) {
136 final TreeModel gtm = geneTrees[i];
137 addModel(gtm);
138 geneTreeInfos[i] = new GeneTreeInfo(gtm, popFactors[i]);
139 }
140
141 // like SpeciesBindings but using number of species-sequence pairs, not number of species
142 popTimesSingle = new double[numberOfSpSeqs][];
143 for (int ns = 0; ns < popTimesSingle.length; ++ns) {
144 popTimesSingle[ns] = new double[allCoalPointsCount(ns)];
145 }
146 dirty_sg = true;
147
148 popTimesPair = new double[(numberOfSpSeqs * (numberOfSpSeqs - 1)) / 2][];
149 {
150 final int nps = allPairCoalPointsCount();
151 for (int ns = 0; ns < popTimesPair.length; ++ns) {
152 popTimesPair[ns] = new double[nps];
153 }
154 }
155
156 dirty_pp = true;
157
158 addStatistic(new SpeciesLimits());
159 }
160
161
162
163
164
165
166 // grj
167 public int numberOfGeneTrees() {
168 return geneTreeInfos.length;
169 }
170
171
172 // grj
173 public int nSpSeqs() {
174 return numberOfSpSeqs;
175 }
176
177 // grj
178 public String apspeciesName(int i) {
179 return apspecies[i].name;
180 }
181
182
183 //grj
184 public int spseqindex2sp(int spsqindex) {
185 return spseqindex2spandseq(spsqindex)[0];
186 }
187
188 //grj
189 public int spseqindex2seq(int spsqindex) {
190 return spseqindex2spandseq(spsqindex)[1];
191 }
192
193
194
195 // grj
196 public SpeciesIndivPair apspeciesId2speciesindiv(String apspId) {
197 int sp = -1;
198 int iv = -1;
199 for (int s = 0; s < apspecies.length; s++) {
200 for (int i = 0; i < apspecies[s].individuals.length; i++) {
201 for (int t = 0; t < apspecies[s].individuals[i].taxa.length; t++) {
202 Taxon taxon = apspecies[s].individuals[i].taxa[t];
203 if (taxon.getId().compareTo(apspId) == 0) {
204 sp = s;
205 iv = i;
206 }
207 }
208 }
209 }
210 assert sp != -1;
211 SpeciesIndivPair x = new SpeciesIndivPair(sp, iv);
212
213 return x;
214 }
215
216 // grj
217 public void permuteOneSpeciesOneIndivForOneGene() {
218 int i = MathUtils.nextInt(geneTreeInfos.length);
219 geneTreeInfos[i].permuteOneSpeciesOneIndiv();
220 geneTreeInfos[i].wasChanged();
221 }
222
223
224 // grj
225 public void permuteSetOfIndivsForOneGene() {
226 int i = MathUtils.nextInt(geneTreeInfos.length);
227 geneTreeInfos[i].permuteSetOfIndivs();
228 geneTreeInfos[i].wasChanged();
229 }
230
231
232 // grj
233 public String seqassignsAsText(int g) {
234 return geneTreeInfos[g].seqassignsAsText();
235 }
236
237 // grj
238 public String genetreeAsText(int g) {
239 return geneTreeInfos[g].genetreeAsText();
240 }
241
242
243 /**
244 * Per species coalecent times.
245 * <p/>
246 * Indexed by sp index, a list of coalescent times of taxa of this sp from all gene trees.
247 *
248 * @return Per species coalecent times
249 */
250 // jh
251 public double[][] getPopTimesSingle() {
252 if (dirty_sg) {
253 for (int ns = 0; ns < popTimesSingle.length; ++ns) {
254 getAllCoalPoints(ns, popTimesSingle[ns]);
255 }
256 dirty_sg = false;
257 }
258 return popTimesSingle;
259 }
260
261 // jh
262 public double[][] getPopTimesPair() {
263 if (dirty_pp) {
264 final int nsp = nSpSeqs();
265 for (int ns1 = 0; ns1 < nsp - 1; ++ns1) {
266 final int z = (ns1 * (2 * nsp - ns1 - 3)) / 2 - 1;
267
268 for (int ns2 = ns1 + 1; ns2 < nsp; ++ns2) {
269 getAllPairCoalPoints(ns1, ns2, popTimesPair[z + ns2]);
270 }
271 }
272 }
273 return popTimesPair;
274 }
275
276
277 // jh
278 private void getAllPairCoalPoints(int ns1, int ns2, double[] popTimes) {
279
280 for (int i = 0; i < geneTreeInfos.length; i++) {
281 for (CoalInfo ci : geneTreeInfos[i].getCoalInfo()) {
282 if ((ci.sinfo[0].contains(ns1) && ci.sinfo[1].contains(ns2)) ||
283 (ci.sinfo[1].contains(ns1) && ci.sinfo[0].contains(ns2))) {
284 popTimes[i] = ci.ctime;
285 break;
286 }
287 }
288 }
289 HeapSort.sort(popTimes);
290 }
291
292
293 // jh
294 private int allCoalPointsCount(int spseqIndex) {
295 int tot = 0;
296 for (GeneTreeInfo t : geneTreeInfos) {
297 if (t.nLineages(spseqIndex) > 0) {
298 tot += t.nLineages(spseqIndex) - 1;
299 }
300 }
301 return tot;
302 }
303
304
305 // length of points must be right
306 // jh
307 void getAllCoalPoints(int spseqIndex, double[] points) {
308
309 int k = 0;
310 for (GeneTreeInfo t : geneTreeInfos) {
311 final int totCoalEvents = t.nLineages(spseqIndex) - 1;
312 int savek = k;
313 for (CoalInfo ci : t.getCoalInfo()) {
314 // if( ci == null ) {
315 // assert ci != null;
316 // }
317 if (ci.allHas(spseqIndex)) {
318 points[k] = ci.ctime;
319 ++k;
320 }
321 }
322 if (!(totCoalEvents >= 0 && savek + totCoalEvents == k) || (totCoalEvents < 0 && savek == k)) {
323 System.err.println(totCoalEvents);
324 }
325 assert (totCoalEvents >= 0 && savek + totCoalEvents == k) || (totCoalEvents < 0 && savek == k);
326 }
327 assert k == points.length;
328 HeapSort.sort(points);
329 }
330
331
332 // jh
333 private int allPairCoalPointsCount() {
334 return geneTreeInfos.length;
335 }
336
337
338 // jh
339 public double speciationUpperBound(FixedBitSet sub1, FixedBitSet sub2) {
340 //Determined by the last time any pair of sp's in sub1 x sub2 have been seen
341 // together in any of the gene trees."""
342
343 double bound = Double.MAX_VALUE;
344 for (GeneTreeInfo g : getGeneTrees()) {
345 for (CoalInfo ci : g.getCoalInfo()) {
346 // if past time of current bound, can't change it anymore
347 if (ci.ctime >= bound) {
348 break;
349 }
350 if ((ci.sinfo[0].intersectCardinality(sub1) > 0 && ci.sinfo[1].intersectCardinality(sub2) > 0)
351 ||
352 (ci.sinfo[0].intersectCardinality(sub2) > 0 && ci.sinfo[1].intersectCardinality(sub1) > 0)) {
353 bound = ci.ctime;
354 break;
355 }
356 }
357 }
358 return bound;
359 }
360
361
362 // jh
363 public void makeCompatible(double rootHeight) {
364 for( GeneTreeInfo t : getGeneTrees() ) {
365
366 MutableTree tree = t.tree;
367
368 for (int i = 0; i < tree.getExternalNodeCount(); i++) {
369 final NodeRef node = tree.getExternalNode(i);
370 final NodeRef p = tree.getParent(node);
371 tree.setNodeHeight(p, rootHeight + tree.getNodeHeight(p));
372 }
373 MutableTree.Utils.correctHeightsForTips(tree);
374 // (todo) ugly re-init - can I do something better?
375 t.wasChanged();
376 t.getCoalInfo();
377 t.wasBacked = false;
378 //t.wasChanged();
379 }
380 }
381
382
383 // jh
384 class CoalInfo implements Comparable<CoalInfo> {
385 // zero based, 0 is taxa time, i.e. in tree branch units
386 final double ctime;
387 // sp info for each subtree
388 final FixedBitSet[] sinfo;
389
390 CoalInfo(double t, int nc) {
391 ctime = t;
392 sinfo = new FixedBitSet[nc];
393 }
394
395 public int compareTo(CoalInfo o) {
396 return o.ctime < ctime ? +1 : (o.ctime > ctime ? -1 : 0);
397 }
398
399 /**
400 * @param s
401 * @return true if all children have at least one taxa from sp 's'
402 */
403 public boolean allHas(int s) {
404 for (FixedBitSet b : sinfo) {
405 if (!b.contains(s)) {
406 return false;
407 }
408 }
409 return true;
410 }
411 }
412
413
414 // jh + grj
415 /**
416 * Collect coalescence information for sub-tree rooted at 'node'.
417 *
418 * @param tree
419 * @param node
420 * @param loc Place node data in loc, sub-tree info before that.
421 * @param info array to fill
422 * @return location of next available location
423 */
424 private int collectCoalInfo(Tree tree, NodeRef node,
425 GeneTreeInfo.SequenceAssignment[] seqassigns, int loc, CoalInfo[] info) {
426
427 info[loc] = new CoalInfo(tree.getNodeHeight(node), tree.getChildCount(node));
428
429 int newLoc = loc - 1;
430 for (int i = 0; i < 2; i++) {
431 NodeRef child = tree.getChild(node, i);
432 info[loc].sinfo[i] = new FixedBitSet(nSpSeqs());
433
434 if (tree.isExternal(child)) {
435 Taxon taxon = tree.getNodeTaxon(child);
436 int ti = taxon2index.get(taxon);
437 int spseq = spsq[seqassigns[ti].spIndex][seqassigns[ti].seqIndex];
438 info[loc].sinfo[i].set(spseq);
439
440 assert tree.getNodeHeight(child) == 0;
441 } else {
442 final int used = collectCoalInfo(tree, child, seqassigns, newLoc, info);
443 for (int j = 0; j < info[newLoc].sinfo.length; ++j) {
444 info[loc].sinfo[i].union(info[newLoc].sinfo[j]);
445 }
446 newLoc = used;
447 }
448 }
449 return newLoc;
450 }
451
452
453 // mostly grj
454 public class GeneTreeInfo {
455 public final TreeModel tree;
456 private SequenceAssignment seqassigns[];
457 private SequenceAssignment oldseqassigns[];
458 private final int[] lineagesCount;
459 private CoalInfo[] cList;
460 private CoalInfo[] savedcList;
461 private boolean dirty;
462 private boolean wasBacked;
463 private final double popFactor;
464
465
466 /* class GeneTreeInfo.SequenceAssignments
467 *
468 * spIndex is an index for an allopolyploid species. For example, it identifies
469 * a bit in a FixedBitSet (union) in a MulLabTree
470 *
471 * seqIndex identifies a sequence copy for this gene and for each individual.
472 * seqIndex is 0 or 1 for tetraploids and it is these that get flipped to change
473 * assignments of sequence copies to legs in AlloppSpeciesNetworkModel (or
474 * equivalently to tips in a MulLabTree).
475 *
476 * 2011-06-23 spIndex is the same for all gene trees. Maybe
477 * allow non-rectangular data later.
478 */
479 private class SequenceAssignment {
480 public int spIndex;
481 public int seqIndex;
482
483 public SequenceAssignment(int spIndex, int seqIndex) {
484 this.spIndex = spIndex;
485 this.seqIndex = seqIndex;
486 }
487
488 public String toString() {
489 String s = "" + seqIndex;
490 return s;
491 }
492 }
493
494
495
496 // grj
497 GeneTreeInfo(TreeModel tree, double popFactor) {
498 this.tree = tree;
499 this.popFactor = popFactor;
500 seqassigns = new SequenceAssignment[taxa.length];
501 oldseqassigns = new SequenceAssignment[taxa.length];
502
503 // This uses taxa list for *all* gene trees, not this gene tree.
504 for (int s = 0; s < apspecies.length; s++) {
505 for (int i = 0; i < apspecies[s].individuals.length; i++) {
506 int nseqs = apspecies[s].individuals[i].taxa.length;
507 int asgns[] = new int [nseqs];
508 for (int x = 0; x < nseqs; x++) {
509 asgns[x] = x;
510 }
511 MathUtils.permute(asgns);
512 for (int x = 0; x < nseqs; x++) {
513 int t = taxon2index.get(apspecies[s].individuals[i].taxa[x]);
514 seqassigns[t] = new SequenceAssignment(s, asgns[x]);
515 oldseqassigns[t] = new SequenceAssignment(s, asgns[x]);
516 }
517 }
518 }
519 lineagesCount = new int[nSpSeqs()];
520 Arrays.fill(lineagesCount, 0);
521
522 for (int nl = 0; nl < lineagesCount.length; ++nl) {
523 int sp = spseqindex2sp(nl);
524 for (AlloppSpeciesBindings.Individual indiv : apspecies[sp].individuals) {
525 boolean got = false;
526 for (Taxon t : indiv.taxa) {
527 if (tree.getTaxonIndex(t) >= 0) {
528 got = true;
529 }
530 }
531 for (Taxon t : indiv.taxa) {
532 assert (tree.getTaxonIndex(t) >= 0) == got;
533 }
534 assert got;
535 if (got) {
536 ++lineagesCount[nl];
537 }
538 }
539 }
540
541 // this bit jh
542 cList = new CoalInfo[tree.getExternalNodeCount() - 1];
543 savedcList = new CoalInfo[cList.length];
544 wasChanged();
545 getCoalInfo();
546 wasBacked = false;
547 }
548
549
550 // grj
551 public String seqassignsAsText() {
552 String s = "Sequence assignments" + System.getProperty("line.separator");
553 for (int tx = 0; tx < seqassigns.length; tx++) {
554 s += taxa[tx];
555 s += ":";
556 s += seqassigns[tx].seqIndex;
557 if (tx+1 < seqassigns.length && seqassigns[tx].spIndex != seqassigns[tx+1].spIndex) {
558 s += System.getProperty("line.separator");
559 } else {
560 s += " ";
561 }
562 }
563 return s;
564 }
565
566 // grj
567 public String genetreeAsText() {
568 return tree.getNewick();
569 }
570
571 // grj
572 public SequenceAssignment getSeqassigns(int tx) {
573 return seqassigns[tx];
574 }
575
576
577 // grj
578 public void storeSequenceAssignments() {
579 for (int i = 0; i < seqassigns.length; i++) {
580 oldseqassigns[i].seqIndex = seqassigns[i].seqIndex;
581 }
582 }
583
584 // grj
585 public void restoreSequenceAssignments() {
586 for (int i = 0; i < seqassigns.length; i++) {
587 seqassigns[i].seqIndex = oldseqassigns[i].seqIndex;
588 }
589 }
590
591
592 // grj
593 public void permuteOneSpeciesOneIndiv() {
594 int sp = MathUtils.nextInt(apspecies.length);
595 int iv = MathUtils.nextInt(apspecies[sp].individuals.length);
596 permuteOneAssignment(sp, iv);
597 }
598
599
600 /* grjtodo-oneday
601 * This is a bit odd. It collects individuals as (sp, iv) indices
602 * that `belong' to a node in the sense that any taxon (sequence)
603 * of an individual belongs to the clade of the node.
604 * I've used a set but not made SpeciesIndivPair's comparable
605 * so that if both sequences of an individual occurs in clade it appears
606 * twice. Then permuteOneAssignment() flips everything so that those
607 * occurring twice get flipped twice and so not changed.
608 *
609 * Result is that individuals with one but not two sequences in
610 * the clade of the node get flipped. Sometimes all individuals
611 * are flipped, sometimes none, sometimes just one, the last is the
612 * same as permuteOneSpeciesOneIndiv().
613 *
614 * 2011-07-29 it appears to work OK on minimal testing and I
615 * don't have a good idea for a more rational or efficient version.
616 *
617 */
618 public void permuteSetOfIndivs() {
619 int num = tree.getInternalNodeCount();
620 int i = MathUtils.nextInt(num);
621 NodeRef node = tree.getInternalNode(i);
622 Set<SpeciesIndivPair> spivs = new HashSet<SpeciesIndivPair>();
623 collectIndivsOfNode(node, spivs);
624 for (SpeciesIndivPair spiv : spivs) {
625 permuteOneAssignment(spiv.spIndex, spiv.ivIndex);
626 }
627 }
628
629
630 // jh
631 int nLineages(int spseqIndex) {
632 return lineagesCount[spseqIndex];
633 }
634
635 // jh
636 public CoalInfo[] getCoalInfo() {
637 if (dirty) {
638 swap();
639
640 collectCoalInfo(tree, tree.getRoot(), seqassigns, cList.length - 1, cList);
641 HeapSort.sort(cList);
642 dirty = false;
643 wasBacked = true;
644 }
645
646 /*
647 CoalInfo check[] = new CoalInfo[cList.length];
648 collectCoalInfo(tree, tree.getRoot(), seqassigns, check.length - 1, check);
649 HeapSort.sort(check);
650 for (int i=0; i<check.length; ++i) {
651 if (check[i].ctime != cList[i].ctime) {
652 System.err.println("Inconsistent ctimes " + i + " check " + check[i].ctime+ " cList " + cList[i].ctime);
653 }
654 if (!check[i].sinfo[0].equals(cList[i].sinfo[0])) {
655 System.err.println("Inconsistent sinfo[0] " + i );
656 }
657 if (!check[i].sinfo[1].equals(cList[i].sinfo[1])) {
658 System.err.println("Inconsistent sinfo[1] " + i );
659 }
660 }*/
661 return cList;
662 }
663
664 // jh
665 private void swap() {
666 CoalInfo[] tmp = cList;
667 cList = savedcList;
668 savedcList = tmp;
669 }
670
671 // jh
672 void wasChanged() {
673 dirty = true;
674 wasBacked = false;
675 }
676
677 // jh
678 boolean restore() {
679 if (verbose) System.out.println(" SP binding: restore " + tree.getId() + " (" + wasBacked + ")");
680 if (wasBacked) {
681 // if( false ) {
682 // swap();
683 // dirty = true;
684 // getCoalInfo();
685 // for(int k = 0; k < cList.length; ++k) {
686 // assert cList[k].ctime == savedcList[k].ctime &&
687 // cList[k].sinfo[0].equals(savedcList[k].sinfo[0]) &&
688 // cList[k].sinfo[1].equals(savedcList[k].sinfo[1]);
689 // }
690 // }
691 swap();
692 wasBacked = false;
693 dirty = false;
694 return true;
695 }
696 return false;
697 }
698
699
700 // jh
701 void accept() {
702 if (verbose) System.out.println(" SP binding: accept " + tree.getId());
703
704 wasBacked = false;
705 }
706
707
708 // jh
709 public double popFactor() {
710 return popFactor;
711 }
712
713
714 // grj
715 private void collectIndivsOfNode(NodeRef node, Set<SpeciesIndivPair> spivs) {
716 if (tree.isExternal(node)) {
717 SpeciesIndivPair x = apspeciesId2speciesindiv(tree.getNodeTaxon(node).getId());
718 spivs.add(x);
719 } else {
720 collectIndivsOfNode(tree.getChild(node, 0), spivs);
721 collectIndivsOfNode(tree.getChild(node, 1), spivs);
722 }
723 }
724
725
726 // grj
727 private void permuteOneAssignment(int sp, int iv) {
728 // grjtodo-tetraonly
729 int tx;
730 if (apspecies[sp].individuals[iv].taxa.length == 2) {
731 tx = taxon2index.get(apspecies[sp].individuals[iv].taxa[0]);
732 seqassigns[tx].seqIndex = 1 - seqassigns[tx].seqIndex;
733 tx = taxon2index.get(apspecies[sp].individuals[iv].taxa[1]);
734 seqassigns[tx].seqIndex = 1 - seqassigns[tx].seqIndex;
735 }
736 }
737
738 } // end of GeneTreeInfo
739
740
741 // jh
742 public GeneTreeInfo[] getGeneTrees() {
743 return geneTreeInfos;
744 }
745
746
747 // jh + grj
748 protected void handleModelChangedEvent(Model model, Object object, int index) {
749 if (verbose) System.out.println(" SP binding: model changed " + model.getId());
750
751 dirty_sg = true;
752 dirty_pp = true;
753
754 for (GeneTreeInfo g : geneTreeInfos) {
755 if (g.tree == model) {
756 g.wasChanged();
757 break;
758 }
759 }
760 fireModelChanged(object, index);
761 }
762
763 // jh
764 protected final void handleVariableChangedEvent(Variable variable, int index, Parameter.ChangeType type) {
765 assert false;
766 }
767
768 // grj
769 // jh comment was 'do on a per need basis'. I hope its ok to mix with doing always.
770 protected void storeState() {
771 for (GeneTreeInfo gti : geneTreeInfos) {
772 gti.storeSequenceAssignments();
773 }
774 if (MulSpeciesTreeModel.DBUGTUNE)
775 System.err.println("MulSpeciesBindings.storeState()");
776 }
777
778
779
780
781 // jh + grj
782 protected void restoreState() {
783 for (GeneTreeInfo gti : geneTreeInfos) {
784 gti.restoreSequenceAssignments();
785 }
786 for (GeneTreeInfo g : geneTreeInfos) {
787 if (g.restore()) {
788 dirty_sg = true;
789 dirty_pp = true;
790 }
791 }
792 if (MulSpeciesTreeModel.DBUGTUNE)
793 System.err.println("MulSpeciesBindings.restoreState()");
794 }
795
796
797 // jh + grj
798 protected void acceptState() {
799 for (GeneTreeInfo g : geneTreeInfos) {
800 g.accept();
801 }
802 }
803
804
805 // grj
806 public LogColumn[] getColumns() {
807 int ncols = geneTreeInfos.length * taxa.length;
808 LogColumn[] columns = new LogColumn[ncols];
809 for (int g = 0, i = 0; g < geneTreeInfos.length; g++) {
810 for (int tx = 0; tx < taxa.length; tx++, i++) {
811 GeneTreeInfo.SequenceAssignment sqa = geneTreeInfos[g].getSeqassigns(tx);
812 String header = "Gene" + g + "taxon" + tx;
813 columns[i] = new LogColumn.Default(header, sqa);
814 }
815
816 }
817
818 return columns;
819 }
820
821 // jh
822 public class SpeciesLimits extends Statistic.Abstract {
823 int nDim;
824 int c[][];
825
826 SpeciesLimits() {
827 super("SpeciationBounds");
828
829 nDim = 0;
830
831 final int nsp = nSpSeqs();
832
833 c = new int[nsp + 1][nsp + 1];
834 for(int k = 0; k < nsp + 1; ++k) {
835 c[k][0] = 1;
836 c[k][k] = 1;
837 }
838 for(int k = 0; k < nsp + 1; ++k) {
839 for(int j = 1; j < k; ++j) {
840 c[k][j] = c[k - 1][j - 1] + c[k - 1][j];
841 }
842 }
843
844 for(int k = 0; k <= (int) (nsp / 2); ++k) {
845 nDim += c[nsp][k];
846 }
847
848 }
849
850 // jh
851 public int getDimension() {
852 return nDim;
853 }
854
855 // jh
856 private double boundOnRoot() {
857 double bound = Double.MAX_VALUE;
858 final int nsp = nSpSeqs();
859 for(GeneTreeInfo g : getGeneTrees()) {
860 for(CoalInfo ci : g.getCoalInfo()) {
861 if( ci.sinfo[0].cardinality() == nsp || ci.sinfo[1].cardinality() == nsp ) {
862 bound = Math.min(bound, ci.ctime);
863 break;
864 }
865 }
866 }
867 return bound;
868 }
869
870 // jh
871 public double getStatisticValue(int dim) {
872 if( dim == 0 ) {
873 return boundOnRoot();
874 }
875
876 final int nsp = nSpSeqs();
877 int r = 0;
878 int k;
879 for(k = 0; k <= (int) (nsp / 2); ++k) {
880 final int i = c[nsp][k];
881 if( dim < r + i ) {
882 break;
883 }
884 r += i;
885 }
886
887 // Classic index -> select k of nsp subset
888
889 // number of species in set is k
890 int n = dim - r;
891 FixedBitSet in = new FixedBitSet(nsp),
892 out = new FixedBitSet(nsp);
893 int fr = nsp;
894 for(int i = 0; i < nsp; ++i) {
895 if( k == 0 ) {
896 out.set(i);
897 } else {
898 if( n < c[fr - 1][k - 1] ) {
899 in.set(i);
900 k -= 1;
901 } else {
902 out.set(i);
903 n -= c[fr - 1][k];
904 }
905 fr -= 1;
906 }
907 }
908 return speciationUpperBound(in, out);
909 }
910 }
911
912
913
914 // grj
915 private int[] spseqindex2spandseq(int spsqindex) {
916 int indexp = -1;
917 int indexq = -1;
918 for (int p = 0; p < spsq.length; p++) {
919 for (int q = 0; q < spsq[p].length; q++) {
920 if (spsq[p][q] == spsqindex) {
921 assert indexp == -1;
922 assert indexq == -1;
923 indexp = p;
924 indexq = q;
925 }
926 }
927 }
928 assert indexp != -1;
929 assert indexq != -1;
930 int[] pq = new int[2];
931 pq[0] = indexp;
932 pq[1] = indexq;
933 return pq;
934 }
935
936 }