Debian Codegraph @

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

raw symbols SCIP
1 /*
2 * AlloppSpeciesBindings.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
29
30
31 import java.util.ArrayList;
32 import java.util.Arrays;
33 import java.util.Formatter;
34 import java.util.HashMap;
35 import java.util.HashSet;
36 import java.util.Locale;
37 import java.util.Map;
38 import java.util.Set;
39 import java.util.Stack;
40
41 import jebl.util.FixedBitSet;
42
43 import dr.evolution.tree.NodeRef;
44 import dr.evolution.util.Taxon;
45 import dr.evomodel.tree.TreeModel;
46 import dr.evomodel.alloppnet.parsers.AlloppSpeciesBindingsParser;
47 import dr.inference.loggers.LogColumn;
48 import dr.inference.loggers.Loggable;
49 import dr.inference.model.AbstractModel;
50 import dr.inference.model.Model;
51 import dr.inference.model.ModelListener;
52 import dr.inference.model.Variable;
53 import dr.inference.model.Variable.ChangeType;
54 import dr.math.MathUtils;
55 import dr.evomodel.alloppnet.util.AlloppMisc;
56
57 /**
58 *
59 * Knows how species (diploid and allopolyploid species) are made of individuals
60 * and individuals are made of taxa (=sequences).
61 *
62 * @author Graham Jones
63 * Date: 30/04/2011
64 */
65
66
67
68 /*
69 *
70 * AlloppSpeciesBindings knows how species are made of individuals
71 * and how individuals are made of taxa (= diploid genomes within individuals).
72 *
73 * It also contains the list of gene trees - tree topologies and node
74 * times, plus popfactors. Given a AlloppSpeciesNetworkModel
75 * it can say if a gene tree is compatible.
76 *
77 * It is here that assignments of sequence copies within individuals
78 * get permuted.
79 *
80 * The class GeneUnionTree, defined here, is used during calculations.
81 *
82 * ******************************
83 *
84 * geneTreeInfos. The array of gene trees. Each one has an array of
85 * sequence assignments.
86 *
87 * apspecies. List of species containing Individuals
88 *
89 * indivs. A 'flattened' array of all Individuals from all species
90 *
91 * taxa. A 'flattened' array of all Taxons from all Individuals
92 *
93 * taxon2index, apspecies2index: maps to indices
94 *
95 * spsq used to map (species index, sequence index) to a single index.
96 *
97 * Eg of two individuals from a diploid "a" and two individuals from a tetraploid "b"
98 * apspecies: a(01,02), b(03,04)
99 * indivs: 01_a(0), 02_a(0), 03_b(0,1), 04_b(0,1)
100 * taxa: 01_a0, 02_a0, 03_b0, 03_b1, 04_b0, 04_b1
101 *
102 */
103 public class AlloppSpeciesBindings extends AbstractModel implements Loggable {
104
105 private final GeneTreeInfo[] geneTreeInfos;
106
107 private final ApSpInfo[] apspecies;
108 private final Taxon[] taxa;
109 private final Map<Taxon, Integer> taxon2index = new HashMap<Taxon, Integer>();
110 private final int spsq[][];
111 private final int numberOfSpSeqs;
112 private final double initialmingenenodeheight; // for starting network
113
114
115
116 /* ************ subclasses ********************/
117
118 /* class AlloppSpeciesBindings.Individual
119 *
120 * Individual is a list of Taxons. One for diploid individual, two for
121 * tetraploid, etc.
122 */
123 public static class Individual extends Taxon {
124 final public String id; // individual ID, such as "02_Alpha" in AlloppSpeciesInfoParser XML example
125 public final Taxon[] taxa;
126
127 public Individual(String id, Taxon[] taxa) {
128 super(id);
129 this.id = id;
130 this.taxa = taxa;
131 }
132 }
133
134
135 private class SpeciesIndivPair {
136 public int spIndex;
137 public int ivIndex;
138
139 public SpeciesIndivPair(int spIndex, int ivIndex) {
140 this.spIndex = spIndex;
141 this.ivIndex = ivIndex;
142 }
143 }
144
145
146 /* class AlloppSpeciesBindings.ApSpInfo
147 *
148 * Information on one allopolyploid species
149 *
150 * name is species name, such as "Alpha" in AlloppSpeciesInfoParser XML example
151 *
152 * ploidylevel; 2 means diploid, 4 means allotetraploid, etc
153 *
154 * individuals[]
155 */
156 public static class ApSpInfo extends Taxon {
157
158 final public String name;
159 final public int ploidylevel; // 2 means diploid, 4 means allotetraploid, etc
160 final Individual[] individuals;
161
162 public ApSpInfo(String name, int ploidylevel, Individual[] individuals) {
163 super(name);
164 this.name = name;
165 this.individuals = individuals;
166 this.ploidylevel = ploidylevel;
167
168 // check
169 if (individuals != null) {
170 int ntaxaperindiv = ploidylevel / 2;
171 for (int ii = 0; ii < individuals.length; ++ii) {
172 assert(individuals[ii].taxa.length == ntaxaperindiv);
173 // may want to allow 3 as well as 2 for tetraploid for organelle DNA
174 }
175 }
176 }
177
178
179 public Taxon taxonFromIndSeq(int i, int sq) {
180 return individuals[i].taxa[sq];
181 }
182 }
183
184
185 /* class AlloppSpeciesBindings.GeneTreeInfo
186 *
187 * Adapted from SpeciesBindings
188 *
189 * tree is the gene tree
190 *
191 * seqassigns[] is species index and sequence index. The latter
192 * is what MCMC acts on when permute sequence assignments
193 *
194 * lineagesCount[] is count for each species, and applies to one or
195 * more tips in MulLabTree. I assume this is the same for all genes
196 * though the info is stored per gene tree
197 *
198 * popFactor (normal diploid=2, X chromosome=1.5, chloroplast=.5, etc)
199 *
200 * I don't like the CoalInfo method of determining compatibility.
201 * Instead I copy the gene tree topology and heights into a new
202 * tree with unions in nodes. Maybe I'll find out why JH used CoalInfos...
203 */
204 private class GeneTreeInfo {
205 private final TreeModel tree;
206 private SequenceAssignment seqassigns[];
207 private SequenceAssignment oldseqassigns[];
208 private final int[] lineagesCount;
209 private final double popFactor; // grjtodo-oneday will mul pops by this, eg for chloroplast data.
210
211
212 /* class GeneTreeInfo.SequenceAssignments
213 *
214 * spIndex is an index for an allopolyploid species. For example, it identifies
215 * a bit in a FixedBitSet (union) in a MulLabTree
216 *
217 * seqIndex identifies a sequence copy for this gene and for each individual.
218 * seqIndex is 0 or 1 for tetraploids and it is these that get flipped to change
219 * assignments of sequence copies to legs in AlloppSpeciesNetworkModel (or
220 * equivalently to tips in a MulLabTree).
221 *
222 * 2011-06-23 spIndex is the same for all gene trees. Maybe
223 * allow non-rectangular data later.
224 */
225 private class SequenceAssignment {
226 public int spIndex;
227 public int seqIndex;
228
229 public SequenceAssignment(int spIndex, int seqIndex) {
230 this.spIndex = spIndex;
231 this.seqIndex = seqIndex;
232 }
233
234 public String toString() {
235 String s = "" + seqIndex;
236 return s;
237 }
238 }
239
240
241
242
243 /* class GeneTreeInfo.GeneUnionNode
244 *
245 * Node for GeneTreeInfo.GeneUnionTree.
246 */
247 private class GeneUnionNode {
248 private GeneUnionNode child[];
249 private double height;
250 private FixedBitSet union;
251 private String name; // for debugging
252
253 // Constructor makes a half-formed tip node. Tips need unions
254 // and internal nodes need all fields filling in.
255 public GeneUnionNode() {
256 child = new GeneUnionNode[0];
257 height = 0.0;
258 union = new FixedBitSet(numberOfSpSeqs());
259 name = "";
260 }
261
262
263
264 public String asText(int indentlen) {
265 StringBuilder s = new StringBuilder();
266 Formatter formatter = new Formatter(s, Locale.US);
267 if (child.length == 0) {
268 formatter.format("%s ", name);
269 } else {
270 formatter.format("%s ", "+");
271 }
272 while (s.length() < 30-indentlen) {
273 formatter.format("%s", " ");
274 }
275 formatter.format("%s ", AlloppMisc.nonnegIn8Chars(height));
276 formatter.format("%20s ", AlloppMisc.FixedBitSetasText(union));
277
278 return s.toString();
279 }
280
281 }
282
283 /* class GeneTreeInfo.GeneUnionTree
284 *
285 * Copy of gene tree topology and heights with unions,
286 * implemented as an array of GeneUnionNodes. This is
287 * used during calculations fitsInNetwork(), treeLogLikelihood()
288 * for one gene tree at a time, then discarded.
289 */
290 private class GeneUnionTree {
291 private GeneUnionNode[] nodes;
292 private int nextn;
293
294
295 public GeneUnionTree() {
296 nodes = new GeneUnionNode[tree.getNodeCount()];
297 for (int i = 0; i < nodes.length; i++) {
298 nodes[i] = new GeneUnionNode();
299 }
300 genetree2geneuniontree(tree.getRoot());
301 }
302
303
304 public GeneUnionNode getRoot() {
305 return nodes[nodes.length-1];
306 }
307
308
309
310 private boolean subtreeFitsInNetwork(GeneUnionNode node,
311 final AlloppSpeciesNetworkModel asnm) {
312 for (int i = 0; i < node.child.length; i++) {
313 if (!subtreeFitsInNetwork(node.child[i], asnm)) {
314 return false;
315 }
316 }
317 return asnm.coalescenceIsCompatible(node.height, node.union);
318 }
319
320
321 private void subtreeRecordCoalescences(GeneUnionNode node,
322 final AlloppSpeciesNetworkModel asnm) {
323 for (int i = 0; i < node.child.length; i++) {
324 subtreeRecordCoalescences(node.child[i], asnm);
325 }
326 if (node.child.length > 0) {
327 asnm.recordCoalescence(node.height, node.union);
328 }
329 }
330
331
332 /*
333 * Recursively copies the topology from subtree rooted at node into
334 * GeneUnionTree implemented as array nodes[].
335 * Fills in union fields.
336 *
337 */
338 private void genetree2geneuniontree(NodeRef gnode) {
339 if (tree.isExternal(gnode)) {
340 nodes[nextn].child = new GeneUnionNode[0];
341 int ti = taxon2index.get(tree.getNodeTaxon(gnode));
342 int spseq = spsq[seqassigns[ti].spIndex][seqassigns[ti].seqIndex];
343 nodes[nextn].union.set(spseq);
344 nodes[nextn].name = tree.getNodeTaxon(gnode).getId();
345 } else {
346 genetree2geneuniontree(tree.getChild(gnode,0));
347 int c0 = nextn - 1;
348 genetree2geneuniontree(tree.getChild(gnode,1));
349 int c1 = nextn - 1;
350 nodes[nextn].child = new GeneUnionNode[2];
351 nodes[nextn].child[0] = nodes[c0];
352 nodes[nextn].child[1] = nodes[c1];
353 nodes[nextn].union.union(nodes[c0].union);
354 nodes[nextn].union.union(nodes[c1].union);
355 }
356 nodes[nextn].height = tree.getNodeHeight(gnode);
357 nextn++;
358 }
359
360
361
362
363
364 public String asText() {
365 String s = "";
366 Stack<Integer> x = new Stack<Integer>();
367 return subtreeAsText(getRoot(), s, x, 0, "");
368 }
369
370
371 private String subtreeAsText(GeneUnionNode node, String s, Stack<Integer> x, int depth, String b) {
372 Integer[] y = x.toArray(new Integer[x.size()]);
373 StringBuffer indent = new StringBuffer();
374 for (int i = 0; i < depth; i++) {
375 indent.append(" ");
376 }
377 for (int i = 0; i < y.length; i++) {
378 indent.replace(2*y[i], 2*y[i]+1, "|");
379 }
380 if (b.length() > 0) {
381 indent.replace(indent.length()-b.length(), indent.length(), b);
382 }
383 s += indent;
384 s += node.asText(indent.length());
385 s += System.getProperty("line.separator");
386 String subs = "";
387 if (node.child.length > 0) {
388 x.push(depth);
389 subs += subtreeAsText(node.child[0], "", x, depth+1, "-");
390 x.pop();
391 subs += subtreeAsText(node.child[1], "", x, depth+1, "`-");
392 }
393 return s + subs;
394 }
395
396 } // end GeneTreeInfo.GeneUnionTree
397
398
399 /*
400 * GeneTreeInfo constructor
401 *
402 * JH's SpeciesBindings code has test
403 * if (tree.getTaxonIndex(t) >= 0) { add taxon to count }
404 *
405 * I am not clear about what happens if some gene trees don't have all taxa.
406 * I insist all gene trees have all taxa, and use missing data
407 * grjtodo-oneday make more efficient
408 */
409 GeneTreeInfo(TreeModel tree, double popFactor, boolean permuteSequenceAssignments) {
410 this.tree = tree;
411 this.popFactor = popFactor;
412 seqassigns = new SequenceAssignment[taxa.length];
413 oldseqassigns = new SequenceAssignment[taxa.length];
414
415 // This uses taxa list for *all* gene trees, not this gene tree.
416 for (int s = 0; s < apspecies.length; s++) {
417 for (int i = 0; i < apspecies[s].individuals.length; i++) {
418 int nseqs = apspecies[s].individuals[i].taxa.length;
419 int asgns[] = new int [nseqs];
420 for (int x = 0; x < nseqs; x++) {
421 asgns[x] = x;
422 }
423 if (permuteSequenceAssignments) { MathUtils.permute(asgns); }
424 for (int x = 0; x < nseqs; x++) {
425 int t = taxon2index.get(apspecies[s].individuals[i].taxa[x]);
426 seqassigns[t] = new SequenceAssignment(s, asgns[x]);
427 oldseqassigns[t] = new SequenceAssignment(s, asgns[x]);
428 }
429 }
430 }
431
432 lineagesCount = new int[apspecies.length];
433 Arrays.fill(lineagesCount, 0);
434
435 for (int nl = 0; nl < lineagesCount.length; ++nl) {
436 for (Individual indiv : apspecies[nl].individuals) {
437 boolean got = false;
438 for (Taxon t : indiv.taxa) {
439 if (tree.getTaxonIndex(t) >= 0) {
440 got = true;
441 }
442 }
443 for (Taxon t : indiv.taxa) {
444 assert (tree.getTaxonIndex(t) >= 0) == got;
445 }
446 assert got;
447 if (got) {
448 ++lineagesCount[nl];
449 }
450 }
451 }
452 }
453
454
455 public String seqassignsAsText() {
456 String s = "Sequence assignments" + System.getProperty("line.separator");
457 for (int tx = 0; tx < seqassigns.length; tx++) {
458 s += taxa[tx];
459 s += ":";
460 s += seqassigns[tx].seqIndex;
461 if (tx+1 < seqassigns.length && seqassigns[tx].spIndex != seqassigns[tx+1].spIndex) {
462 s += System.getProperty("line.separator");
463 } else {
464 s += " ";
465 }
466 }
467 return s;
468 }
469
470
471
472 public String genetreeAsText() {
473 GeneUnionTree gutree = new GeneUnionTree();
474 return gutree.asText();
475 }
476
477
478 public boolean fitsInNetwork(final AlloppSpeciesNetworkModel asnm) {
479 GeneUnionTree gutree = new GeneUnionTree();
480 boolean fits = gutree.subtreeFitsInNetwork(gutree.getRoot(), asnm);
481 if (AlloppSpeciesNetworkModel.DBUGTUNE) {
482 if (!fits) {
483 System.err.println("INCOMPATIBLE");
484 System.err.println(seqassignsAsText());
485 System.err.println(gutree.asText());
486 System.err.println(asnm.mullabTreeAsText());
487 }
488 }
489 return fits;
490 }
491
492
493 // returns log(P(g_i|S)) = probability that gene tree fits into species network
494 public double treeLogLikelihood(final AlloppSpeciesNetworkModel asnm) {
495 GeneUnionTree gutree = new GeneUnionTree();
496 asnm.clearCoalescences();
497 gutree.subtreeRecordCoalescences(gutree.getRoot(), asnm);
498 asnm.sortCoalescences();
499 asnm.recordLineageCounts();
500 double llhood = asnm.geneTreeInNetworkLogLikelihood();
501 if (AlloppSpeciesNetworkModel.DBUGTUNE) {
502 System.err.println("COMPATIBLE: log-likelihood = " + llhood);
503 System.err.println(seqassignsAsText());
504 System.err.println(gutree.asText());
505 System.err.println(asnm.mullabTreeAsText());
506 }
507 return llhood;
508 }
509
510
511 public void storeSequenceAssignments() {
512 for (int i = 0; i < seqassigns.length; i++) {
513 oldseqassigns[i].seqIndex = seqassigns[i].seqIndex;
514 }
515 }
516
517 public void restoreSequenceAssignments() {
518 for (int i = 0; i < seqassigns.length; i++) {
519 seqassigns[i].seqIndex = oldseqassigns[i].seqIndex;
520 }
521 }
522
523
524
525
526 public double spseqUpperBound(FixedBitSet spsq0, FixedBitSet spsq1) {
527 GeneUnionTree gutree = new GeneUnionTree();
528 return subtreeSpseqUpperBound(gutree.getRoot(), spsq0, spsq1, Double.MAX_VALUE);
529 }
530
531
532
533 public void permuteOneSpeciesOneIndiv() {
534 int sp = MathUtils.nextInt(apspecies.length);
535 int iv = MathUtils.nextInt(apspecies[sp].individuals.length);
536 flipOneAssignment(sp, iv);
537 }
538
539
540 /* grjtodo-oneday
541 * This is a bit odd. It collects individuals as (sp, iv) indices
542 * that `belong' to a node in the sense that any taxon (sequence)
543 * of an individual belongs to the clade of the node.
544 * I've used a set but not made SpeciesIndivPair's comparable
545 * so that if both sequences of an individual occurs in clade it appears
546 * twice. Then flipOneAssignment() flips everything so that those
547 * occurring twice get flipped twice and so not changed.
548 *
549 * Result is that individuals with one but not two sequences in
550 * the clade of the node get flipped. Sometimes all individuals
551 * are flipped, sometimes none, sometimes just one, the last is the
552 * same as permuteOneSpeciesOneIndiv().
553 *
554 * 2011-07-29 it appears to work OK on minimal testing and I
555 * don't have a good idea for a more rational or efficient version.
556 *
557 */
558 public void permuteSetOfIndivs() {
559 int num = tree.getInternalNodeCount();
560 int i = MathUtils.nextInt(num);
561 NodeRef node = tree.getInternalNode(i);
562 Set<SpeciesIndivPair> spivs = new HashSet<SpeciesIndivPair>();
563 collectIndivsOfNode(node, spivs);
564 for (SpeciesIndivPair spiv : spivs) {
565 flipOneAssignment(spiv.spIndex, spiv.ivIndex);
566 }
567 }
568
569
570
571
572 public SequenceAssignment getSeqassigns(int tx) {
573 return seqassigns[tx];
574 }
575
576
577 // called when a gene tree has changed, which affects likelihood.
578 // 2011-08-12 I am not using dirty flags (yet). I return
579 // false from getLikelihoodKnown() in AlloppMSCoalescent
580 // and that seems to be sufficient.
581 public void wasChanged() {
582 }
583
584
585
586
587
588
589 private void collectIndivsOfNode(NodeRef node, Set<SpeciesIndivPair> spivs) {
590 if (tree.isExternal(node)) {
591 SpeciesIndivPair x = apspeciesId2speciesindiv(tree.getNodeTaxon(node).getId());
592 spivs.add(x);
593 } else {
594 collectIndivsOfNode(tree.getChild(node, 0), spivs);
595 collectIndivsOfNode(tree.getChild(node, 1), spivs);
596 }
597 }
598
599
600
601
602
603 // start at root of gutree and recurse.
604 // A node which has one child which contains some of species spp0
605 // and where the other contains some of species spp1, imposes a limit
606 // on how early a speciation can occur.
607 private double subtreeSpseqUpperBound(GeneUnionNode node,
608 FixedBitSet spsq0, FixedBitSet spsq1, double bound) {
609 if (node.child.length == 0) {
610 return bound;
611 }
612 for (GeneUnionNode ch : node.child) {
613 bound = Math.min(bound, subtreeSpseqUpperBound(ch, spsq0, spsq1, bound));
614 }
615 FixedBitSet genespp0 = node.child[0].union;
616 int int00 = genespp0.intersectCardinality(spsq0);
617 int int01 = genespp0.intersectCardinality(spsq1);
618 FixedBitSet genespp1 = node.child[1].union;
619 int int10 = genespp1.intersectCardinality(spsq0);
620 int int11 = genespp1.intersectCardinality(spsq1);
621 if ((int00 > 0 && int11 > 0) || (int10 > 0 && int01 > 0)) {
622 bound = Math.min(bound, node.height);
623 }
624 return bound;
625 }
626
627
628
629 private void flipOneAssignment(int sp, int iv) {
630 // grjtodo-tetraonly
631 int tx;
632 if (apspecies[sp].individuals[iv].taxa.length == 2) {
633 tx = taxon2index.get(apspecies[sp].individuals[iv].taxa[0]);
634 seqassigns[tx].seqIndex = 1 - seqassigns[tx].seqIndex;
635 tx = taxon2index.get(apspecies[sp].individuals[iv].taxa[1]);
636 seqassigns[tx].seqIndex = 1 - seqassigns[tx].seqIndex;
637 }
638 }
639
640
641
642 private void flipAssignmentsForSpecies(int sp) {
643 for (int iv = 0; iv < apspecies[sp].individuals.length; iv++) {
644 flipOneAssignment(sp, iv);
645 }
646 }
647
648
649
650 }
651 // end of GeneTreeInfo
652
653
654
655
656 /* ******************** Constructor *****************************/
657
658 /*
659 * The standard constructor calls this with permuteSequenceAssignments==true.
660 * permuteSequenceAssignments==false is for testing.
661 */
662 public AlloppSpeciesBindings(ApSpInfo[] apspecies, TreeModel[] geneTrees,
663 double minheight, double[] popFactors, boolean permuteSequenceAssignments) {
664 super(AlloppSpeciesBindingsParser.ALLOPPSPECIES);
665
666 this.apspecies = apspecies;
667 initialmingenenodeheight = minheight;
668 // make the flattened arrays
669 int n = 0;
670 for (int s = 0; s < apspecies.length; s++) {
671 n += apspecies[s].individuals.length;
672 }
673 Individual [] indivs = new Individual[n];
674 n = 0;
675 for (int s = 0; s < apspecies.length; s++) {
676 for (int i = 0; i < apspecies[s].individuals.length; i++, n++) {
677 indivs[n] = apspecies[s].individuals[i];
678 }
679 }
680 int t = 0;
681 for (int i = 0; i < indivs.length; i++) {
682 t += indivs[i].taxa.length;
683 }
684 taxa = new Taxon[t];
685 t = 0;
686 for (int i = 0; i < indivs.length; i++) {
687 for (int j = 0; j < indivs[i].taxa.length; j++, t++) {
688 taxa[t] = indivs[i].taxa[j];
689 }
690 }
691 // set up maps to indices
692 for (int i = 0; i < taxa.length; i++) {
693 taxon2index.put(taxa[i], i);
694 }
695 spsq = new int[apspecies.length][];
696 int spsqindex = 0;
697 for (int sp = 0; sp < apspecies.length; sp++) {
698 spsq[sp] = new int[apspecies[sp].ploidylevel/2];
699 for (int seq = 0; seq < spsq[sp].length; seq++, spsqindex++) {
700 spsq[sp][seq] = spsqindex;
701 }
702 }
703 numberOfSpSeqs = spsqindex;
704
705 geneTreeInfos = new GeneTreeInfo[geneTrees.length];
706 for (int i = 0; i < geneTrees.length; i++) {
707 geneTreeInfos[i] = new GeneTreeInfo(geneTrees[i], popFactors[i], permuteSequenceAssignments);
708 }
709
710 for (GeneTreeInfo gti : geneTreeInfos) {
711 NodeRef[] nodes = gti.tree.getNodes();
712 for (NodeRef node : nodes) {
713 if (!gti.tree.isExternal(node)) {
714 double height = gti.tree.getNodeHeight(node);
715 gti.tree.setNodeHeight(node, minheight+height);
716 }
717 }
718 }
719 }
720
721
722 /*
723 * The normal constructor
724 */
725 public AlloppSpeciesBindings(ApSpInfo[] apspecies, TreeModel[] geneTrees,
726 double minheight, double[] popFactors) {
727 this(apspecies, geneTrees, minheight, popFactors, true);
728 }
729
730 /*
731 * Minimal constructor for testing conversions network -> multree, diphist
732 * and for testing likelihood in MUL tree.
733 */
734 public AlloppSpeciesBindings(ApSpInfo[] apspecies) {
735 this(apspecies, new TreeModel[0], 0.0, new double[0]);
736 }
737
738
739 public double initialMinGeneNodeHeight() {
740 return initialmingenenodeheight;
741 }
742
743
744
745 public FixedBitSet speciesseqEmptyUnion() {
746 FixedBitSet union = new FixedBitSet(numberOfSpSeqs());
747 return union;
748 }
749
750
751 // Taxons vs species.
752 // Taxons may have a final "0", "1",... to distinguish sequences, while
753 // species do not. AlloppLeggedTree uses a SimpleTree, which only has
754 // Taxons, so same thing there. Multree needs distinguishable Taxons
755 // so has suffices.
756 public FixedBitSet taxonseqToTipUnion(Taxon tx, int seq) {
757 FixedBitSet union = speciesseqEmptyUnion();
758 int sp = apspeciesId2index(tx.getId());
759 int spseq = spandseq2spseqindex(sp, seq);
760 union.set(spseq);
761 return union;
762 }
763
764
765 public FixedBitSet spsqunion2spunion(FixedBitSet spsqunion) {
766 FixedBitSet spunion = new FixedBitSet(apspecies.length);
767 for (int sp = 0; sp < apspecies.length; sp++) {
768 boolean got = false;
769 for (int seq = 0; seq < spsq[sp].length; seq++) {
770 if (spsqunion.contains(spsq[sp][seq])) {
771 got = true;
772 }
773 }
774 if (got) {
775 spunion.set(sp);
776 }
777 }
778 return spunion;
779 }
780
781
782 public int numberOfGeneTrees() {
783 return geneTreeInfos.length;
784 }
785
786
787 public double maxGeneTreeHeight() {
788 if (geneTreeInfos.length == 0) {
789 return 999; // for test code only
790 }
791 double maxheight = 0.0;
792 for (GeneTreeInfo gti : geneTreeInfos) {
793 double height = gti.tree.getNodeHeight(gti.tree.getRoot());
794 if (height > maxheight) {
795 maxheight = height;
796 }
797 }
798 return maxheight;
799 }
800
801
802
803
804 public boolean geneTreeFitsInNetwork(int i, final AlloppSpeciesNetworkModel asnm) {
805 return geneTreeInfos[i].fitsInNetwork(asnm);
806 }
807
808 public double geneTreeLogLikelihood(int i, final AlloppSpeciesNetworkModel asnm) {
809 return geneTreeInfos[i].treeLogLikelihood(asnm);
810 }
811
812
813 public int numberOfSpecies() {
814 return apspecies.length;
815 }
816
817
818
819 public String apspeciesName(int i) {
820 return apspecies[i].name;
821 }
822
823
824
825 public Taxon[] SpeciesWithinPloidyLevel(int pl) {
826 ArrayList<Taxon> names = new ArrayList<Taxon>();
827 for (int i = 0; i < apspecies.length; i++) {
828 if (apspecies[i].ploidylevel == pl) {
829 names.add(new Taxon(apspecies[i].name));
830 }
831 }
832 Taxon[] spp = new Taxon[names.size()];
833 names.toArray(spp);
834 return spp;
835 }
836
837
838 public int spandseq2spseqindex(int sp, int seq) {
839 return spsq[sp][seq];
840 }
841
842
843
844 public int spseqindex2sp(int spsqindex) {
845 return spseqindex2spandseq(spsqindex)[0];
846 }
847
848 public int spseqindex2seq(int spsqindex) {
849 return spseqindex2spandseq(spsqindex)[1];
850 }
851
852
853
854 public int apspeciesId2index(String apspId) {
855 int index = -1;
856 for (int i = 0; i < apspecies.length; i++) {
857 if (apspecies[i].name.compareTo(apspId) == 0) {
858 assert index == -1;
859 index = i;
860 }
861 }
862 if (index == -1) {
863 System.out.println("BUG in apspeciesId2index");
864 }
865 assert index != -1;
866 return index;
867 }
868
869
870 public SpeciesIndivPair apspeciesId2speciesindiv(String apspId) {
871 int sp = -1;
872 int iv = -1;
873 for (int s = 0; s < apspecies.length; s++) {
874 for (int i = 0; i < apspecies[s].individuals.length; i++) {
875 for (int t = 0; t < apspecies[s].individuals[i].taxa.length; t++) {
876 Taxon taxon = apspecies[s].individuals[i].taxa[t];
877 if (taxon.getId().compareTo(apspId) == 0) {
878 sp = s;
879 iv = i;
880 }
881 }
882 }
883 }
884 assert sp != -1;
885 SpeciesIndivPair x = new SpeciesIndivPair(sp, iv);
886
887 return x;
888 }
889
890
891 public int numberOfSpSeqs() {
892 return numberOfSpSeqs;
893 }
894
895
896 int nLineages(int speciesIndex) {
897 int n = geneTreeInfos[0].lineagesCount[speciesIndex];
898 for (GeneTreeInfo gti : geneTreeInfos) {
899 assert gti.lineagesCount[speciesIndex] == n;
900 }
901 return n;
902 }
903
904
905
906 public double spseqUpperBound(FixedBitSet left, FixedBitSet right) {
907 double bound = Double.MAX_VALUE;
908 for (GeneTreeInfo gti : geneTreeInfos) {
909 bound = Math.min(bound, gti.spseqUpperBound(left, right));
910 }
911 return bound;
912 }
913
914
915
916 public void permuteOneSpeciesOneIndivForOneGene() {
917 int i = MathUtils.nextInt(geneTreeInfos.length);
918 geneTreeInfos[i].permuteOneSpeciesOneIndiv();
919 }
920
921
922 public void permuteSetOfIndivsForOneGene() {
923 int i = MathUtils.nextInt(geneTreeInfos.length);
924 geneTreeInfos[i].permuteSetOfIndivs();
925 }
926
927
928 public void flipAssignmentsForAllGenesOneSpecies(int sp) {
929 for (GeneTreeInfo gti : geneTreeInfos) {
930 gti.flipAssignmentsForSpecies(sp);
931 }
932
933 }
934
935
936
937 public String seqassignsAsText(int g) {
938 return geneTreeInfos[g].seqassignsAsText();
939 }
940
941
942 public String genetreeAsText(int g) {
943 String s = "Gene tree " + g + " height union" + System.getProperty("line.separator");
944 s += geneTreeInfos[g].genetreeAsText();
945 return s;
946 }
947
948
949 @Override
950 protected void handleModelChangedEvent(Model model, Object object, int index) {
951 for (GeneTreeInfo g : geneTreeInfos) {
952 if (g.tree == model) {
953 g.wasChanged();
954 break;
955 }
956 }
957 fireModelChanged(object, index);
958 if (AlloppSpeciesNetworkModel.DBUGTUNE)
959 System.err.println("AlloppSpeciesBindings.handleModelChangedEvent() " + model.getId());
960 }
961
962 @Override
963 protected void handleVariableChangedEvent(Variable variable, int index,
964 ChangeType type) {
965 assert false; // copies SpeciesBindings; not understood
966 if (AlloppSpeciesNetworkModel.DBUGTUNE)
967 System.err.println("AlloppSpeciesBindings.handleVariableChangedEvent() " + variable.getId());
968 }
969
970 @Override
971 protected void storeState() {
972 for (GeneTreeInfo gti : geneTreeInfos) {
973 gti.storeSequenceAssignments();
974 }
975 if (AlloppSpeciesNetworkModel.DBUGTUNE)
976 System.err.println("AlloppSpeciesBindings.storeState()");
977 }
978
979 @Override
980 protected void restoreState() {
981 for (GeneTreeInfo gti : geneTreeInfos) {
982 gti.restoreSequenceAssignments();
983 if (AlloppSpeciesNetworkModel.DBUGTUNE)
984 System.err.println("AlloppSpeciesBindings.restoreState()");
985 }
986
987 }
988
989 @Override
990 protected void acceptState() {
991 }
992
993
994 public void addModelListeners(ModelListener listener) {
995 for (GeneTreeInfo gti : geneTreeInfos) {
996 gti.tree.addModelListener(listener);
997 }
998 addModelListener(listener); // for sequence assignments
999 }
1000
1001
1002
1003 public LogColumn[] getColumns() {
1004 int ncols = geneTreeInfos.length * taxa.length;
1005 LogColumn[] columns = new LogColumn[ncols];
1006 for (int g = 0, i = 0; g < geneTreeInfos.length; g++) {
1007 for (int tx = 0; tx < taxa.length; tx++, i++) {
1008 GeneTreeInfo.SequenceAssignment sqa = geneTreeInfos[g].getSeqassigns(tx);
1009 String header = "Gene" + g + "taxon" + tx;
1010 columns[i] = new LogColumn.Default(header, sqa);
1011 }
1012
1013 }
1014
1015 return columns;
1016 }
1017
1018
1019
1020 private int[] spseqindex2spandseq(int spsqindex) {
1021 int indexp = -1;
1022 int indexq = -1;
1023 for (int p = 0; p < spsq.length; p++) {
1024 for (int q = 0; q < spsq[p].length; q++) {
1025 if (spsq[p][q] == spsqindex) {
1026 assert indexp == -1;
1027 assert indexq == -1;
1028 indexp = p;
1029 indexq = q;
1030 }
1031 }
1032 }
1033 assert indexp != -1;
1034 assert indexq != -1;
1035 int[] pq = new int[2];
1036 pq[0] = indexp;
1037 pq[1] = indexq;
1038 return pq;
1039 }
1040
1041 }
1042
1043
1044