Debian Codegraph @

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

raw symbols SCIP
1
2
3 /*
4 * AlloppMulLabTree.java
5 *
6 * Copyright (c) 2002-2017 Alexei Drummond, Andrew Rambaut and Marc Suchard
7 *
8 * This file is part of BEAST.
9 * See the NOTICE file distributed with this work for additional
10 * information regarding copyright ownership and licensing.
11 *
12 * BEAST is free software; you can redistribute it and/or modify
13 * it under the terms of the GNU Lesser General Public License as
14 * published by the Free Software Foundation; either version 2
15 * of the License, or (at your option) any later version.
16 *
17 * BEAST is distributed in the hope that it will be useful,
18 * but WITHOUT ANY WARRANTY; without even the implied warranty of
19 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 * GNU Lesser General Public License for more details.
21 *
22 * You should have received a copy of the GNU Lesser General Public
23 * License along with BEAST; if not, write to the
24 * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
25 * Boston, MA 02110-1301 USA
26 */
27
28 package dr.evomodel.alloppnet.speciation;
29
30 import java.util.ArrayList;
31 import java.util.Collections;
32 import java.util.Comparator;
33 import java.util.Formatter;
34 import java.util.Locale;
35 import java.util.Stack;
36
37 import dr.evolution.tree.*;
38 import jebl.util.FixedBitSet;
39 import dr.evolution.util.Taxon;
40 import dr.inference.model.Parameter;
41 import dr.evomodel.alloppnet.util.AlloppMisc;
42
43
44
45
46
47 /**
48 * An AlloppMulLabTree represents the species network as single
49 * binary tree with tips that can be multiply labelled with species.
50 *
51 * @author Graham Jones
52 * Date: 13/09/2011
53 */
54
55
56 /*
57 * An AlloppMulLabTree represents the species network as single
58 * binary tree with tips that can be multiply labelled with species.
59 *
60 * classes LegLink and FootLinks are for gathering and organising
61 * the links between trees of different ploidy, so that the
62 * rootward-pointing legs can become tipward-pointing branches.
63 *
64 * SpSqUnion is used for sorting the nodes in an AlloppMulLabTree. It is
65 * used by Comparator SPUNION_ORDER, and hence indirectly by
66 * fillinpopvals().
67 *
68 * class BranchPopulationAndLineages records the information needed
69 * to calculate the probability of coalescences in a single branch of the
70 * AlloppMulLabTree.
71 *
72 */
73
74
75 /* mlnodes[], rootn implement the tree; nextn is for building it
76 *
77 * apsp references the (species, indivs, sequences) structure.
78 *
79 * popvals references the population parameters. fillinpopvals() assigns
80 * them to branches.
81 *
82 * simptree is so that AlloppSpeciesNetworkModel, which contains a AlloppMulLabTree,
83 * can implement the Tree interface.
84 */
85 public class AlloppMulLabTree {
86 private MulLabNode[] mlnodes;
87 private int rootn;
88 private int nextn;
89 private AlloppSpeciesBindings apsp;
90 private Parameter tippopvals;
91 private Parameter rootpopvals;
92 private double [] hybpopvals;
93 private int nofhybpopvals;
94 public SimpleTree simptree;
95
96
97
98
99 /*
100 * parent, child[] join the nodes into a binary tree.
101 *
102 * height is time into past
103 *
104 * popsize is population at start of branch, and for tips, also at end.
105 *
106 * union is a set of species for a single choice of sequence copy from
107 * each individual of the species. There is one bit for each Taxon like
108 * "c0" or "c1"
109 */
110 private class MulLabNode extends AlloppNode.Abstract implements AlloppNode, NodeRef {
111 private int nodeNumber;
112 private int anc;
113 private int lft;
114 private int rgt;
115 private double height;
116 private boolean tetraroot; // true iff this node is root of a teraploid subtree
117 private boolean intetratree; // true iff this is in a tetratree
118 private boolean tetraancestor; // true iff this is a node with no diploid tip descendants
119 private int ttreeindex;
120 private double hybridheight;
121 private FixedBitSet union;
122 private ArrayList<Double> coalheights;
123 private int nlineages;
124 private Taxon taxon;
125 private int tippopindex;
126 private int hybpopindex;
127 private int rootpopindex;
128
129 // dud constuctor
130 MulLabNode(int nn) {
131 nodeNumber = nn;
132 anc = -1;
133 lft = -1;
134 rgt = -1;
135 height = -1.0;
136 tetraroot = false;
137 intetratree = false;
138 tetraancestor = false;
139 ttreeindex = -1;
140 hybridheight = -1.0;
141 coalheights = new ArrayList<Double>();
142 taxon = new Taxon("");
143 tippopindex = -1;
144 hybpopindex = -1;
145 rootpopindex = -1;
146 }
147
148
149 public double tippop() {
150 return tippopvals.getParameterValue(tippopindex);
151 }
152
153 public double hybpop() {
154 return hybpopvals[hybpopindex];
155 }
156
157 public double rootpop() {
158 return rootpopvals.getParameterValue(rootpopindex);
159 }
160
161 @Override
162 public String asText(int indentlen) {
163 StringBuilder s = new StringBuilder();
164 Formatter formatter = new Formatter(s, Locale.US);
165 if (lft < 0) {
166 formatter.format("%s ", taxon.getId());
167 } else {
168 formatter.format("%s ", "+");
169 }
170 while (s.length() < 20-indentlen) {
171 formatter.format("%s", " ");
172 }
173 formatter.format("%s ", AlloppMisc.nonnegIn8Chars(height));
174 formatter.format("%60s ", AlloppMisc.FixedBitSetasText(union));
175 double tippop = (tippopindex >= 0) ? tippop() : -1.0;
176 formatter.format("%s %s ", AlloppMisc.nonnegIntIn2Chars(tippopindex), AlloppMisc.nonnegIn8Chars(tippop));
177 double hybpop = (hybpopindex >= 0) ? hybpop() : -1.0;
178 formatter.format("%s %s ", AlloppMisc.nonnegIntIn2Chars(hybpopindex), AlloppMisc.nonnegIn8Chars(hybpop));
179 double rootpop = (rootpopindex >= 0) ? rootpop() : -1.0;
180 formatter.format("%s %s ", AlloppMisc.nonnegIntIn2Chars(rootpopindex), AlloppMisc.nonnegIn8Chars(rootpop));
181 formatter.format("%s ", tetraroot ? "tetroot" : " ");
182 formatter.format("%s ", AlloppMisc.nonnegIn8Chars(hybridheight));
183 formatter.format("%3d ", nlineages);
184 for (int c = 0; c < coalheights.size(); c++) {
185 formatter.format(AlloppMisc.nonnegIn8Chars(coalheights.get(c)) + ",");
186 }
187 return s.toString();
188 }
189
190
191 @Override
192 public int nofChildren() {
193 return ((lft < 0) ? 0 : 2);
194 }
195
196
197 @Override
198 public AlloppNode getChild(int ch) {
199 return ch==0 ? mlnodes[lft] : mlnodes[rgt];
200 }
201
202
203 @Override
204 public AlloppNode getAnc() {
205 return mlnodes[anc];
206 }
207
208
209
210 @Override
211 public double getHeight() {
212 return height;
213 }
214
215
216 @Override
217 public FixedBitSet getUnion() {
218 return union;
219 }
220
221
222 @Override
223 public void setChild(int ch, AlloppNode newchild) {
224 int newch = ((MulLabNode)newchild).nodeNumber;
225 if (ch == 0) {
226 lft = newch;
227 } else {
228 rgt = newch;
229 }
230 }
231
232
233 @Override
234 public void setAnc(AlloppNode anc) {
235 this.anc = ((MulLabNode)anc).nodeNumber;
236 }
237
238 @Override
239 public Taxon getTaxon() {
240 return taxon;
241 }
242
243
244 @Override
245 public void setTaxon(String name) {
246 taxon = new Taxon(name);
247 }
248
249
250 @Override
251 public void setHeight(double height) {
252 this.height = height;
253 }
254
255
256 @Override
257 public void setUnion(FixedBitSet union) {
258 this.union = union;
259
260 }
261
262
263 @Override
264 public void addChildren(AlloppNode c0, AlloppNode c1) {
265 lft = ((MulLabNode)c0).nodeNumber;
266 mlnodes[lft].anc = nodeNumber;
267 rgt = ((MulLabNode)c1).nodeNumber;
268 mlnodes[rgt].anc = nodeNumber;
269 }
270
271
272 @Override
273 public int getNumber() {
274 return nodeNumber;
275 }
276
277 @Override
278 public void setNumber(int nn) {
279 nodeNumber = nn;
280 }
281 }
282
283
284 private class SpSqUnion {
285 public FixedBitSet spsqunion;
286 public FixedBitSet spunion;
287 public SpSqUnion(FixedBitSet spsqunion) {
288 this.spsqunion = spsqunion;
289 spunion = apsp.spsqunion2spunion(spsqunion);
290 }
291 }
292
293
294 private class PopulationAndLineages {
295 public double t[];
296 public double tippop;
297 public double rootpop;
298 public int tipnlin;
299
300 public PopulationAndLineages(double[] t2, double tippop, double rootpop,
301 int tipnlin) {
302 this.t = t2;
303 this.tippop = tippop;
304 this.rootpop = rootpop;
305 this.tipnlin = tipnlin;
306 }
307
308 public double populationAt(double x) {
309 final double begt = t[0];
310 final double endt = t[t.length - 1];
311 return ((endt-x)*tippop + (x-begt)*rootpop) / (endt-begt);
312 }
313 }
314
315
316
317
318 /*
319 * This constructor makes a single multiply labelled tree from the diploid
320 * history and set of tetraploid AlloppLeggedTrees which is passed to it. It is called directly
321 * by testing code.
322 */
323 AlloppMulLabTree(AlloppDiploidHistory adhist, ArrayList<AlloppLeggedTree> tettrees,
324 AlloppSpeciesBindings apsp, Parameter tippopvals, Parameter rootpopvals, double [] hybpopvals) {
325 this.apsp = apsp;
326 this.tippopvals = tippopvals;
327 this.rootpopvals = rootpopvals;
328 this.hybpopvals = hybpopvals;
329 nofhybpopvals = tettrees.size();
330 // Count tips for the tree to be made
331 int ntips = 0;
332 ntips += adhist.getDiploidTipCount();
333 for (AlloppLeggedTree ttree : tettrees) {
334 ntips += 2 * ttree.getExternalNodeCount();
335 }
336 // Make array of dud nodes
337 mlnodes = new MulLabNode[2 * ntips - 1];
338 for (int i = 0; i < mlnodes.length; i++) {
339 mlnodes[i] = new MulLabNode(i);
340 mlnodes[i].tetraancestor = true;
341 }
342 // get dip hist and tetratrees into array; unions are filled at tips
343 nextn = 0;
344 nextn = subtree2MulLabNodes(adhist, adhist.getRootIndex(), tettrees, apsp);
345 rootn = nextn - 1;
346 // fill unions from tips
347 mlnodes[rootn].fillinUnionsInSubtree(apsp.numberOfSpSeqs());
348 // The tetraroot flags were initialised false, set to final values by subtree2MulLabNodes()
349 // The tetraancestor flags were initialised true, diploid tips later set false by subtree2MulLabNodes()
350 // The intetratree flags were initialised false, tetraploid tips later set true by allopptree2MulLabNodes()
351 // Now fill in tetraancestor and intetratree flags from tips.
352 fillinTetraFlagsInSubtree(mlnodes[rootn]);
353 makesimpletree();
354 }
355
356
357
358
359
360 // constructor for testing conversion of diploid history plus tetraploid trees to MUL-tree
361 public AlloppMulLabTree(AlloppDiploidHistory adhist, ArrayList<AlloppLeggedTree> tettrees, AlloppSpeciesBindings apsp,
362 Parameter testtippopvalues, Parameter testrootpopvalues, double [] testhybpopvalues, int testcase) {
363 this(adhist, tettrees, apsp, testtippopvalues, testrootpopvalues, testhybpopvalues);
364 assert testcase >= 1;
365 assert testcase <= 5;
366 fillinpopvals();
367 }
368
369
370 // constructor for testing likelihood calculations.
371 // Makes a particular multree with nlineages, coalheights so test can call
372 // geneTreeInMULTreeLogLikelihood()
373 public AlloppMulLabTree(AlloppSpeciesBindings apsp) {
374 this.apsp = apsp;
375 nofhybpopvals = 1;
376 tippopvals = new Parameter.Default(3, .003);
377 rootpopvals = new Parameter.Default(4, .001);
378 hybpopvals = new double[1];
379 hybpopvals[0] = .001;
380 fillmlnodesforlhoodtest1();
381 fillinTetraFlagsInSubtree(mlnodes[rootn]);
382 mlnodes[rootn].fillinUnionsInSubtree(4);
383 }
384
385
386 public double testGeneTreeInMULTreeLogLikelihood() {
387 return geneTreeInMULTreeLogLikelihood();
388 }
389
390 private void fillmlnodesforlhoodtest1() {
391 mlnodes = new MulLabNode[7];
392 for (int i = 0; i < mlnodes.length; i++) {
393 mlnodes[i] = new MulLabNode(i);
394 }
395 // 4 tips, 2 dips, 1 tet
396 mlnodes[0].taxon = new Taxon("a");
397 mlnodes[1].taxon = new Taxon("b");
398 mlnodes[2].taxon = new Taxon("z0");
399 mlnodes[3].taxon = new Taxon("z1");
400 mlnodes[2].tetraancestor = true;
401 mlnodes[3].tetraancestor = true;
402 mlnodes[2].intetratree = true;
403 mlnodes[3].intetratree = true;
404 mlnodes[2].tetraroot = true;
405 mlnodes[3].tetraroot = true;
406 mlnodes[0].union = new FixedBitSet(4); mlnodes[0].union.set(0);
407 mlnodes[1].union = new FixedBitSet(4); mlnodes[1].union.set(1);
408 mlnodes[2].union = new FixedBitSet(4); mlnodes[2].union.set(2);
409 mlnodes[3].union = new FixedBitSet(4); mlnodes[3].union.set(3);
410 // toplogy and times
411 mlnodes[4].addChildren(mlnodes[0], mlnodes[2]);
412 mlnodes[5].addChildren(mlnodes[1], mlnodes[3]);
413 mlnodes[6].addChildren(mlnodes[4], mlnodes[5]);
414 rootn = 6;
415 mlnodes[0].height = 0.0;
416 mlnodes[1].height = 0.0;
417 mlnodes[2].height = 0.0;
418 mlnodes[3].height = 0.0;
419 mlnodes[4].height = 0.01;
420 mlnodes[5].height = 0.02;
421 mlnodes[6].height = 0.03;
422 mlnodes[2].hybridheight = 0.005;
423 mlnodes[3].hybridheight = 0.005;
424 // nlineages and coalheights
425 mlnodes[0].nlineages = 1;
426 mlnodes[1].nlineages = 2;
427 mlnodes[2].nlineages = 1;
428 mlnodes[3].nlineages = 1;
429 mlnodes[4].nlineages = 2;
430 mlnodes[4].coalheights.add(0.015);
431 mlnodes[5].nlineages = 3;
432 mlnodes[5].coalheights.add(0.025);
433 mlnodes[6].nlineages = 3;
434 mlnodes[6].coalheights.add(0.035);
435 mlnodes[6].coalheights.add(0.045);
436 }
437
438
439
440 // For testing.
441 boolean mullabtreeOK() {
442 int nroots = 0;
443 for (int i = 0; i < mlnodes.length; i++) {
444 if (mlnodes[i].anc < 0) {
445 nroots++;
446 }
447 }
448 if (nroots != 1) {
449 return false;
450 }
451 for (int i = 0; i < mlnodes.length; i++) {
452 int nparents = 0;
453 for (int j = 0; j < mlnodes.length; j++) {
454 if (mlnodes[j].lft == i) { nparents++; }
455 if (mlnodes[j].rgt == i) { nparents++; }
456 }
457 if (mlnodes[i].anc < 0 && nparents != 0) {
458 return false;
459 }
460 if (mlnodes[i].anc >= 0 && nparents != 1) {
461 return false;
462 }
463 }
464 for (int i = 0; i < mlnodes.length; i++) {
465 if (mlnodes[i].getNumber() != i) {
466 return false;
467 }
468 }
469 for (int i = 0; i < mlnodes.length; i++) {
470 if (mlnodes[i].lft >= 0) {
471 if (mlnodes[i].rgt < 0) {
472 return false;
473 }
474 int lft = mlnodes[i].lft;
475 int rgt = mlnodes[i].rgt;
476 if (mlnodes[lft].anc != i) {
477 return false;
478 }
479 if (mlnodes[rgt].anc != i) {
480 return false;
481 }
482 if (mlnodes[i].height <= mlnodes[lft].height) {
483 return false;
484 }
485 if (mlnodes[i].height <= mlnodes[rgt].height) {
486 return false;
487 }
488 } else {
489 if (mlnodes[i].height != 0) {
490 return false;
491 }
492 }
493 }
494 if (mlnodes[rootn].anc >= 0) {
495 return false;
496 }
497 return true;
498 }
499
500
501
502 String mullabTreeAsNewick() {
503 String s = TreeUtils.uniqueNewick(simptree, simptree.getRoot());
504 return s;
505 }
506
507 String asText() {
508 String header = "MUL-tree height union [] tippop [] hybpop [] rootpop tetroot hybhgt nlin coalheights" + System.getProperty("line.separator");
509
510 String s = "";
511 Stack<Integer> x = new Stack<Integer>();
512 return header + AlloppNode.Abstract.subtreeAsText(mlnodes[rootn], s, x, 0, "");
513 }
514
515
516 void clearCoalescences() {
517 clearSubtreeCoalescences(mlnodes[rootn]);
518 }
519
520 void recordLineageCounts() {
521 recordSubtreeLineageCounts(mlnodes[rootn]);
522 }
523
524 boolean coalescenceIsCompatible(double height, FixedBitSet union) {
525 MulLabNode node = (MulLabNode) mlnodes[rootn].nodeOfUnionInSubtree(union);
526 return (node.height <= height);
527 }
528
529
530 void recordCoalescence(double height, FixedBitSet union) {
531 MulLabNode node = (MulLabNode) mlnodes[rootn].nodeOfUnionInSubtree(union);
532 assert (node.height <= height);
533 while (node.anc >= 0 && mlnodes[node.anc].height <= height) {
534 node = mlnodes[node.anc];
535 }
536 node.coalheights.add(height);
537 }
538
539 void sortCoalescences() {
540 for (MulLabNode node : mlnodes) {
541 Collections.sort(node.coalheights);
542 }
543 }
544
545
546 double geneTreeInMULTreeLogLikelihood() {
547 fillinpopvals();
548 //System.out.println(asText());
549 return geneTreeInMULSubtreeLogLikelihood(mlnodes[rootn]);
550 }
551
552
553
554
555
556 /*
557 *
558 * ***************************************************
559 * Private
560 */
561
562
563
564 private void fillinTetraFlagsInSubtree(AlloppNode node) {
565 if (node.nofChildren() == 2) {
566 MulLabNode mnode = (MulLabNode)node;
567 MulLabNode ch0 = (MulLabNode)node.getChild(0);
568 MulLabNode ch1 = (MulLabNode)node.getChild(1);
569 fillinTetraFlagsInSubtree(node.getChild(0));
570 fillinTetraFlagsInSubtree(node.getChild(1));
571 mnode.tetraancestor = (ch0.tetraancestor && ch1.tetraancestor);
572 mnode.intetratree = (ch0.intetratree && !ch0.tetraroot && ch1.intetratree && !ch1.tetraroot);
573 }
574 }
575
576
577 private int subtree2MulLabNodes(AlloppDiploidHistory adhist, int dhni, ArrayList<AlloppLeggedTree> tettrees, AlloppSpeciesBindings apsp) {
578 if (adhist.getLftFromIndex(dhni) < 0) {
579 int tt = adhist.getNodeTettree(dhni);
580 if (tt < 0) {
581 mlnodes[nextn].setTaxon(adhist.getTaxonFromIndex(dhni).getId());
582 mlnodes[nextn].setUnion(apsp.taxonseqToTipUnion(mlnodes[nextn].taxon, 0));
583 mlnodes[nextn].setHeight(adhist.getHeightFromIndex(dhni));
584 mlnodes[nextn].tetraancestor = false;
585 nextn++;
586 } else {
587 AlloppNode troot = (AlloppNode)tettrees.get(tt).getSlidableRoot();
588 int seq = (adhist.getNodeLeg(dhni) == AlloppDiploidHistory.LegLorR.left) ? 0 : 1;
589 nextn = allopptree2MulLabNodes(apsp, troot, seq);
590 mlnodes[nextn-1].hybridheight = adhist.getHeightFromIndex(dhni);
591 mlnodes[nextn-1].tetraroot = true;
592 mlnodes[nextn-1].ttreeindex = tt;
593 }
594 } else {
595 nextn = subtree2MulLabNodes(adhist, adhist.getLftFromIndex(dhni), tettrees, apsp);
596 int c0 = nextn - 1;
597 nextn = subtree2MulLabNodes(adhist, adhist.getRgtFromIndex(dhni), tettrees, apsp);
598 int c1 = nextn - 1;
599 mlnodes[nextn].addChildren(mlnodes[c0], mlnodes[c1]);
600 mlnodes[nextn].setHeight(adhist.getHeightFromIndex(dhni));
601 nextn++;
602 }
603 return nextn;
604 }
605
606
607
608 private int allopptree2MulLabNodes(AlloppSpeciesBindings apsp,
609 AlloppNode snode, int seq) {
610 if (snode.nofChildren() == 0) {
611 mlnodes[nextn].setTaxon(snode.getTaxon().getId() + seq);
612 mlnodes[nextn].setUnion(apsp.taxonseqToTipUnion(snode.getTaxon(), seq));
613 mlnodes[nextn].intetratree = true;
614 } else {
615 nextn = allopptree2MulLabNodes(apsp, snode.getChild(0), seq);
616 int c0 = nextn - 1;
617 nextn = allopptree2MulLabNodes(apsp, snode.getChild(1), seq);
618 int c1 = nextn - 1;
619 mlnodes[nextn].addChildren(mlnodes[c0], mlnodes[c1]);
620 }
621 mlnodes[nextn].setHeight(snode.getHeight());
622 nextn++;
623 return nextn;
624 }
625
626
627
628
629
630 private void makesimpletree() {
631 SimpleNode[] snodes = new SimpleNode[mlnodes.length];
632 for (int n = 0; n < mlnodes.length; n++) {
633 snodes[n] = new SimpleNode();
634 }
635 makesimplesubtree(snodes, 0, mlnodes[rootn]);
636 simptree = new SimpleTree(snodes[mlnodes.length-1]);
637 }
638
639
640 private int makesimplesubtree(SimpleNode[] snodes, int nextsn, MulLabNode mnode) {
641 if (mnode.lft < 0) {
642 snodes[nextsn].setTaxon(new Taxon(mnode.taxon.getId()));
643 } else {
644 nextsn = makesimplesubtree(snodes, nextsn, mlnodes[mnode.lft]);
645 int subtree0 = nextsn-1;
646 nextsn = makesimplesubtree(snodes, nextsn, mlnodes[mnode.rgt]);
647 int subtree1 = nextsn-1;
648 snodes[nextsn].addChild(snodes[subtree0]);
649 snodes[nextsn].addChild(snodes[subtree1]);
650 }
651 snodes[nextsn].setHeight(mnode.height);
652 String tti;
653 if (mnode.ttreeindex < 0) {
654 tti = "X";
655 } else {
656 tti = "T" + mnode.ttreeindex;
657 }
658 snodes[nextsn].setAttribute("tti", tti);
659 if (mnode.hybridheight >= 0.0) {
660 snodes[nextsn].setAttribute("hybhgt", mnode.hybridheight);
661 }
662 return nextsn+1;
663 }
664
665
666 private void clearSubtreeCoalescences(MulLabNode node) {
667 if (node.lft >= 0) {
668 clearSubtreeCoalescences(mlnodes[node.lft]);
669 clearSubtreeCoalescences(mlnodes[node.rgt]);
670 }
671 node.coalheights.clear();
672 }
673
674
675 private void recordSubtreeLineageCounts(MulLabNode node) {
676 if (node.lft < 0) {
677 node.nlineages = apsp.nLineages(apsp.spseqindex2sp(union2spseqindex(node.union)));
678 } else {
679 node.nlineages = 0;
680 recordSubtreeLineageCounts(mlnodes[node.lft]);
681 recordSubtreeLineageCounts(mlnodes[node.rgt]);
682 node.nlineages += mlnodes[node.lft].nlineages - mlnodes[node.lft].coalheights.size();
683 node.nlineages += mlnodes[node.rgt].nlineages - mlnodes[node.rgt].coalheights.size();
684 }
685 }
686
687
688
689 /*
690 * This copies population values in the Parameter popvalues
691 * to nodes in the AlloppMulLabTree. The population values are
692 * per-species-clade (per-branch in network), but of course more than
693 * one node in AlloppMulLabTree may correspond to the same species.
694 *
695 * The other complications are that tips are different from internal
696 * nodes, and that nodes which roots of tetratrees or just below,
697 * as well as the root are special cases.
698 *
699 * It collects unions (which represent sets whose elements
700 * identify a species and a sequence) from the nodes and then
701 * sorts them primarily using identities of the species, so
702 * that sets of node with same species clade are grouped together. The sort
703 * also puts the node sets corresponding to tips first in the array and sorts
704 * nodes within node sets in a well-defined way.
705 * This mainly does what is required, since nodes with the same
706 * species clade are treated the same.
707 *
708 * fillinpopvalsforspunion() deals with a set of nodes
709 * with same species clade.
710 */
711 private void fillinpopvals() {
712 ArrayList<SpSqUnion> unionarraylist = new ArrayList<SpSqUnion>();
713 for (int n = 0; n < mlnodes.length; n++) {
714 unionarraylist.add(new SpSqUnion(mlnodes[n].union));
715 }
716 Collections.sort(unionarraylist, SPUNION_ORDER);
717 SpSqUnion[] unionarray = new SpSqUnion[unionarraylist.size()];
718 unionarray = unionarraylist.toArray(unionarray);
719 PopValIndices pvis = new PopValIndices(0,0,0);
720 // set all pop indices to dud values
721 for (int n = 0; n < mlnodes.length; n++) {
722 mlnodes[n].tippopindex = -1;
723 mlnodes[n].rootpopindex = -1;
724 mlnodes[n].hybpopindex = -1;
725 }
726 int noftippopvals = tippopvals.getDimension();
727 int nofrootpopvals = rootpopvals.getDimension();
728 for (int n0 = 0; n0 < unionarray.length; ) {
729 int n1 = n0+1;
730 while (n1 < unionarray.length && unionarray[n1].spunion.equals(unionarray[n0].spunion)) {
731 n1++;
732 }
733 assert pvis.tipp <= noftippopvals;
734 if (!(pvis.rootp <= nofrootpopvals)) {
735 System.out.println("BUG in fillinpopvals()");
736 }
737 assert pvis.rootp <= nofrootpopvals;
738 assert pvis.hybp <= nofhybpopvals;
739 pvis = fillinpopvalsforspunion(unionarray, n0, n1, pvis);
740 n0 = n1;
741 }
742 if (pvis.tipp != noftippopvals || pvis.rootp != nofrootpopvals || pvis.hybp != nofhybpopvals) {
743 System.out.println("BUG in fillinpopvals()");
744 }
745 assert pvis.tipp == noftippopvals;
746 assert pvis.rootp == nofrootpopvals;
747 assert pvis.hybp == nofhybpopvals;
748 }
749
750
751 private class PopValIndices {
752 public int tipp;
753 public int rootp;
754 public int hybp;
755 PopValIndices(int tipp, int rootp, int hybp) {
756 this.tipp = tipp;
757 this.rootp = rootp;
758 this.hybp = hybp;
759 }
760 }
761
762
763 private PopValIndices fillinpopvalsforspunion(SpSqUnion[] unionarray, int n0, int n1, PopValIndices pvis) {
764 int n = n1-n0;
765 MulLabNode nodeset[] = new MulLabNode[n];
766 // get set of nodes with same species clade
767 for (int i = n0; i < n1; i++) {
768 nodeset[i-n0] = (MulLabNode) mlnodes[rootn].nodeOfUnionInSubtree(unionarray[i].spsqunion);
769 }
770 // Hybridization pops. Nodes in pairs, shared pop.
771 if (nodeset[0].tetraroot) {
772 assert n >= 2;
773 assert nodeset[1].tetraroot;
774 for (int i = 0; i < 2; i++) {
775 nodeset[i].hybpopindex = pvis.hybp;
776 }
777 pvis.hybp++;
778 }
779 // Tip pops. Either dip or tet; in latter case shared pop.
780 int ntips = 0;
781 for (int i = 0; i < n; i++) {
782 if (nodeset[i].lft < 0) {
783 nodeset[i].tippopindex = pvis.tipp;
784 ntips++;
785 }
786 }
787 assert ntips <= 2;
788 if (ntips > 0) {
789 pvis.tipp++;
790 }
791
792 // Root pops within tetra trees. Nodes in pairs.
793 if (nodeset[0].intetratree && !nodeset[0].tetraroot) {
794 if (n != 2) {
795 System.out.println("BUG in fillinpopvalsforspunion() 2");
796 }
797 assert n == 2;
798 assert (nodeset[1].intetratree && !nodeset[1].tetraroot);
799 for (int i = 0; i < 2; i++) {
800 nodeset[i].rootpopindex = pvis.rootp;
801 }
802 pvis.rootp++;
803 } else {
804 // Root pops NOT within tetra trees. Here the nodeset[] structure is not useful.
805 // Here, pop is shared with sibling if either is ancestor to tetraploids only
806 for (int i = 0; i < n; i++) {
807 MulLabNode node = nodeset[i];
808 if (node.anc >= 0) {
809 MulLabNode sibling = siblingOfNode(node);
810 if (node.tetraancestor || sibling.tetraancestor) {
811 if (sibling.rootpopindex >= 0) {
812 node.rootpopindex = sibling.rootpopindex;
813 } else {
814 node.rootpopindex = pvis.rootp;
815 pvis.rootp++;
816 }
817 } else {
818 node.rootpopindex = pvis.rootp;
819 pvis.rootp++;
820 }
821 }
822 }
823 }
824
825 return pvis;
826 }
827
828
829
830 private MulLabNode siblingOfNode(MulLabNode node) {
831 assert node.anc >= 0;
832 MulLabNode sibling;
833 if (mlnodes[ mlnodes[node.anc].lft ] == node) {
834 sibling = mlnodes[ mlnodes[node.anc].rgt ];
835 } else {
836 assert mlnodes[ mlnodes[node.anc].rgt ] == node;
837 sibling = mlnodes[ mlnodes[node.anc].lft ];
838 }
839 return sibling;
840 }
841
842
843
844 /*
845 * Visits each node in MULtree and accumulates LogLikelihood
846 */
847 private double geneTreeInMULSubtreeLogLikelihood(MulLabNode node) {
848 double loglike = 0.0;
849 if (node.lft >= 0) {
850 loglike += geneTreeInMULSubtreeLogLikelihood(mlnodes[node.lft]);
851 loglike += geneTreeInMULSubtreeLogLikelihood(mlnodes[node.rgt]);
852 }
853 loglike += branchLLInMULtree(node);
854
855 return loglike;
856 }
857
858
859 /*
860 * Does likelihood calculation for a single node in the case
861 * of two diploids.
862 */
863 private double branchLLInMULtree(MulLabNode node) {
864 double loglike = 0.0;
865
866 double tippop = 0.0;
867 if (node.lft < 0) {
868 tippop = node.tippop();
869 } else {
870 tippop = mlnodes[node.lft].rootpop() + mlnodes[node.rgt].rootpop();
871 }
872
873 PopulationAndLineages pal;
874 double t[];
875 if (node.tetraroot) {
876 // since hybridization
877 int nsince = 0;
878 for ( ; nsince < node.coalheights.size() &&
879 node.coalheights.get(nsince) < node.hybridheight; nsince++) {}
880 t = new double[nsince + 2];
881 t[0] = node.height;
882 for (int i = 0; i < nsince; i++) {
883 t[i+1] = node.coalheights.get(i);
884 }
885 t[t.length-1] = node.hybridheight;
886 pal = new PopulationAndLineages(t, tippop, node.hybpop(), node.nlineages);
887 loglike += limbLogLike(pal);
888 if (Double.isNaN(loglike)) {
889 System.out.println("BUG in branchLLInMULtree");
890 }
891 // before hybridization
892 int nbefore = node.coalheights.size() - nsince;
893 t = new double[nbefore + 2];
894 t[0] = node.hybridheight;
895 for (int i = 0; i < nbefore; i++) {
896 t[i+1] = node.coalheights.get(nsince+i);
897 }
898 t[t.length-1] = mlnodes[node.anc].height;
899
900 pal = new PopulationAndLineages(t, node.rootpop(), node.rootpop(), node.nlineages - nsince);
901 loglike += limbLogLike(pal);
902 } else if (node.anc < 0) {
903 t = new double[node.coalheights.size() + 2];
904 t[0] = node.height;
905 t[t.length-1] = apsp.maxGeneTreeHeight();
906 for (int i = 0; i < node.coalheights.size(); i++) {
907 t[i+1] = node.coalheights.get(i);
908 }
909 pal = new PopulationAndLineages(t, tippop, tippop, node.nlineages);
910 loglike += limbLogLike(pal);
911 } else {
912 t = new double[node.coalheights.size() + 2];
913 t[0] = node.height;
914 t[t.length-1] = mlnodes[node.anc].height;
915 for (int i = 0; i < node.coalheights.size(); i++) {
916 t[i+1] = node.coalheights.get(i);
917 }
918 pal = new PopulationAndLineages(t, tippop, node.rootpop(), node.nlineages);
919 loglike += limbLogLike(pal);
920 }
921 if (Double.isNaN(loglike)) {
922 System.out.println("BUG in branchLLInMULtree");
923 }
924 return loglike;
925 }
926
927
928
929
930 /*
931 * limbLogLike calculates the log-likelihood for
932 * the coalescences at t[1],t[2],...t[k] within a limb
933 * from t[0] to t[k+1]. ('limb' means a branch or part of one.)
934 */
935 private double limbLogLike(PopulationAndLineages pal) {
936 double loglike = 0.0;
937 int k = pal.t.length - 2;
938 for (int i = 1; i <= k; i++) {
939 loglike -= Math.log(pal.populationAt(pal.t[i]));
940 }
941 for (int i = 0; i <= k; i++) {
942 final double y = (pal.tipnlin-i) * (pal.tipnlin-i-1) / 2 ;
943 final double z = limbLinPopIntegral(pal, pal.t[i], pal.t[i+1]);
944 loglike -= y * z;
945 }
946 if (Double.isNaN(loglike)) {
947 System.out.println("BUG in limbLogLike");
948 }
949 return loglike;
950 }
951
952
953
954 // integral from t0 to t1 of (endt-begt)/((endt-x)begPop + (x-begt)endPop)
955 // with respect to x
956 private double limbLinPopIntegral(PopulationAndLineages b, double t0, double t1) {
957 final double begt = b.t[0];
958 final double endt = b.t[b.t.length-1];
959 if (b.rootpop < 1E-20) {
960 System.out.println("Underflow in limbLinPopIntegral()");
961 }
962 final double d = b.rootpop - b.tippop;
963 final double c = endt * b.tippop - begt * b.rootpop;
964 final double x = Math.abs(d / b.tippop);
965 if (x > 0.001) {
966 return ((endt - begt) / d) * Math.log((c + d * t1) / (c + d * t0));
967 } else {
968 double y = d * (t1 - t0) / (c + d * t0);
969 double ys = (1.0 - y/2.0 + y*y * (1.0/3.0 - y/4.0 + y*y * (1.0/5.0 - y/6.0)));
970 return ((endt - begt) * (t1 - t0) / (c + d * t0)) * ys;
971 }
972 }
973
974
975
976
977 private static int union2spseqindex(FixedBitSet union) {
978 assert union.cardinality() == 1;
979 return union.nextOnBit(0);
980 }
981
982
983
984
985 /*
986 * This is for ordering the unions in the nodes of the AlloppMulLabTree.
987 * Those unions are of (species, sequence) pairs.
988 *
989 * The comparator sorts the unions of (species, sequence) pairs (SpSqUnions)
990 * so that all unions containing the same set of species (ignoring sequence)
991 * are grouped together. Call the sets of SpSqUnions for the same species a
992 * `group'. There can be 1,2 or 3 SpSqUnions in a group.
993 *
994 * The groups are sorted in order of increasing number of species (clade size).
995 * All groups for a single species (a tip in the network) come first, then
996 * those groups for two species, and so on to the root for all species.
997 * For groups that have equal numbers of species, a lexicographical
998 * ordering using species indices is used.
999 *
1000 * Within each group, species and sequence information is used to sort the 1 to 3
1001 * SpSqUnions. The size of the `clade' of (species, sequence) pairs is used
1002 * first in the comparison, which ensures that the three nodes with the same species
1003 * - corresponding to two roots of tetratrees in the AlloppMulLabTree plus a leg-join -
1004 * are ordered so that the two roots come first.
1005 *
1006 */
1007
1008 static final Comparator<SpSqUnion> SPUNION_ORDER = new Comparator<SpSqUnion>() {
1009 public int compare(SpSqUnion a, SpSqUnion b) {
1010 int ac = a.spunion.cardinality();
1011 int bc = b.spunion.cardinality();
1012 if (ac != bc) {
1013 return ac-bc;
1014 } else {
1015 int an = a.spunion.nextOnBit(0);
1016 int bn = b.spunion.nextOnBit(0);
1017 while (an >= 0 || bn >= 0) {
1018 if (an != bn) {
1019 return an-bn;
1020 }
1021 an = a.spunion.nextOnBit(an+1);
1022 bn = b.spunion.nextOnBit(bn+1);
1023 }
1024 // spunions compare equal; do spsqunions
1025 ac = a.spsqunion.cardinality();
1026 bc = b.spsqunion.cardinality();
1027 if (ac != bc) {
1028 return ac-bc;
1029 } else {
1030 an = a.spsqunion.nextOnBit(0);
1031 bn = b.spsqunion.nextOnBit(0);
1032 while (an >= 0 || bn >= 0) {
1033 if (an != bn) {
1034 return an-bn;
1035 }
1036 an = a.spsqunion.nextOnBit(an+1);
1037 bn = b.spsqunion.nextOnBit(bn+1);
1038 }
1039 return 0;
1040 }
1041 }
1042 }
1043 };
1044
1045
1046
1047
1048 }