7 * Dept. Integrative Biology
8 * University of California, Berkeley
9 * Berkeley, CA 94720-3140
13 * Swedish Museum of Natural History
15 * SE-10405 Stockholm, SWEDEN
16 * fredrik.ronquist@nrm.se
18 * With important contributions by
20 * Paul van der Mark (paulvdm@sc.fsu.edu)
21 * Maxim Teslenko (maxim.teslenko@nrm.se)
23 * and by many users (run 'acknowledgments' to see more info)
25 * This program is free software; you can redistribute it and/or
26 * modify it under the terms of the GNU General Public License
27 * as published by the Free Software Foundation; either version 2
28 * of the License, or (at your option) any later version.
30 * This program is distributed in the hope that it will be useful,
31 * but WITHOUT ANY WARRANTY; without even the implied warranty of
32 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
33 * GNU General Public License for more details (www.gnu.org).
45 const char* const svnRevisionProposalC = "$Rev: 1069 $"; /* Revision keyword which is expanded/updated by svn on each commit/update */
47 /* debugging compiler statements */
49 #undef DEBUG_UNROOTED_SLIDER
53 #undef DEBUG_ExtSPRClock
54 #undef DEBUG_ParsSPRClock
57 #undef DEBUG_SPLITMERGE
63 void TouchAllTreeNodes (ModelInfo *m, int chain);
66 int Move_Aamodel (Param *param, int chain, RandLong *seed, MrBFlt *lnPriorRatio, MrBFlt *lnProposalRatio, MrBFlt *mvp)
68 /* Change amino acid model for model mixing
82 MrBFlt *bs, *subValue;
85 /* get model params */
86 mp = &modelParams[param->relParts[0]];
88 subValue = GetParamSubVals(param, chain, state[chain]);
90 /* get old value of model */
91 newM = oldM = (int)*GetParamVals(param, chain, state[chain]);
93 /* get a new model ID */
96 newM = (int)(RandomNumber(seed) * 10);
97 } while (newM == oldM);
99 /* set proposal ratio */
100 *lnProposalRatio = 0.0;
102 /* set prior ratio */
103 *lnPriorRatio = subValue[newM] - subValue[oldM];
105 /* copy new amino acid model ID back */
106 *GetParamVals(param, chain, state[chain]) = (MrBFlt)newM;
108 /* set amino acid frequencies */
109 bs = GetParamSubVals (modelSettings[param->relParts[0]].stateFreq, chain, state[chain]);
110 if (newM == AAMODEL_POISSON)
112 for (i=0; i<mp->nStates; i++)
115 else if (newM == AAMODEL_JONES)
117 for (i=0; i<mp->nStates; i++)
120 else if (newM == AAMODEL_DAY)
122 for (i=0; i<mp->nStates; i++)
123 bs[i] = dayhoffPi[i];
125 else if (newM == AAMODEL_MTREV)
127 for (i=0; i<mp->nStates; i++)
128 bs[i] = mtrev24Pi[i];
130 else if (newM == AAMODEL_MTMAM)
132 for (i=0; i<mp->nStates; i++)
135 else if (newM == AAMODEL_WAG)
137 for (i=0; i<mp->nStates; i++)
140 else if (newM == AAMODEL_RTREV)
142 for (i=0; i<mp->nStates; i++)
145 else if (newM == AAMODEL_CPREV)
147 for (i=0; i<mp->nStates; i++)
150 else if (newM == AAMODEL_VT)
152 for (i=0; i<mp->nStates; i++)
155 else if (newM == AAMODEL_BLOSUM)
157 for (i=0; i<mp->nStates; i++)
161 /* Set update flags for all partitions that share this amino acid model. Note that the conditional
162 likelihood update flags have been set before we even call this function. */
163 for (i=0; i<param->nRelParts; i++)
164 TouchAllTreeNodes(&modelSettings[param->relParts[i]],chain);
166 /* Set update flags for cijks for all affected partitions. */
167 for (i=0; i<param->nRelParts; i++)
168 modelSettings[param->relParts[i]].upDateCijk = YES;
171 MrBayesPrint ("%lf", *mvp); /* just because I am tired of seeing the unused parameter error msg */
175 int Move_AddDeleteCPPEvent (Param *param, int chain, RandLong *seed, MrBFlt *lnPriorRatio, MrBFlt *lnProposalRatio, MrBFlt *mvp)
177 /* add or delete one Poisson process event */
179 int i, k, addEvent, *nEvents, numEvents;
180 MrBFlt sigma, m, lognormalLnProb, **position, **rateMultiplier, length, pos, rate;
185 /* get the model settings */
186 model = &modelSettings[param->relParts[0]];
189 rate = *GetParamVals (model->cppRate, chain, state[chain]);
191 /* get sigma of lognormal of rate multipliers */
192 sigma = *GetParamVals (model->cppMultDev, chain, state[chain]);
194 /* get the cpp event data */
195 nEvents = param->nEvents[2*chain+state[chain]];
196 position = param->position[2*chain+state[chain]];
197 rateMultiplier = param->rateMult[2*chain+state[chain]];
200 t = GetTree (param, chain, state[chain]);
205 p = t->allDownPass[(int)(RandomNumber(seed) * (t->nNodes -2))];
206 } while (p->anc == NULL || (p->anc->anc == NULL));
208 /* get number of events for convenience */
209 numEvents = nEvents[p->index];
211 /* add or delete ? */
215 else if (RandomNumber(seed) < 0.5)
222 /* choose random event */
223 k = (int) (RandomNumber(seed) * numEvents);
225 /* save multiplier to be deleted */
226 m = rateMultiplier[p->index][k];
228 /* rearrange and reduce */
229 for (i=k; i<numEvents-1; i++)
231 position[p->index][i] = position[p->index][i+1];
232 rateMultiplier[p->index][i] = rateMultiplier[p->index][i+1];
236 position[p->index] = (MrBFlt *) SafeRealloc ((void *) position[p->index], (numEvents-1)*sizeof(MrBFlt));
237 rateMultiplier[p->index] = (MrBFlt *) SafeRealloc ((void *) rateMultiplier[p->index], (numEvents-1)*sizeof(MrBFlt));
238 assert (position[p->index] != NULL && rateMultiplier[p->index] != NULL);
242 free (position[p->index]);
243 free (rateMultiplier[p->index]);
244 position[p->index] = rateMultiplier[p->index] = NULL;
246 /* update number of events */
249 else /* if (addEvent == YES) */
253 /* generate new multiplier */
254 m = LogNormalRandomVariable (0.0, sigma, seed);
256 /* generate new position */
257 pos = RandomNumber(seed);
259 /* find place in current array */
260 for (k=0; k<numEvents; k++)
262 if (position[p->index][k] > pos)
266 /* rearrange and insert */
267 position[p->index] = (MrBFlt *) SafeRealloc ((void *)position[p->index], (numEvents+1)*sizeof(MrBFlt));
268 rateMultiplier[p->index] = (MrBFlt *) SafeRealloc ((void *)rateMultiplier[p->index], (numEvents+1)*sizeof(MrBFlt));
269 assert (position[p->index] != NULL && rateMultiplier[p->index] != NULL);
270 for (i=numEvents; i>k; i--)
272 position[p->index][i] = position[p->index][i-1];
273 rateMultiplier[p->index][i] = rateMultiplier[p->index][i-1];
275 position[p->index][k] = pos;
276 rateMultiplier[p->index][k] = m;
278 /* update number of events */
282 /* the CPP process is relative to expected substitutions */
285 lognormalLnProb = LnProbLogNormal(0.0, sigma, m);
287 (*lnPriorRatio) = lognormalLnProb + log (rate);
289 (*lnPriorRatio) = -(lognormalLnProb + log(rate));
292 /* note that nEvents[p->index] now contains k+1 after addition */
293 (*lnProposalRatio) = log (length / ((double) nEvents[p->index])) - lognormalLnProb;
295 /* note that nEvents[p->index] contains k after deletion */
296 (*lnProposalRatio) = log ((double)(nEvents[p->index]+1) / length) + lognormalLnProb;
298 /* take care of asymmetric add and delete probabilities around 0 and 1 events */
299 if (addEvent == YES && nEvents[p->index] == 1)
300 (*lnProposalRatio) += log (0.5);
301 else if (addEvent == NO && nEvents[p->index] == 0)
302 (*lnProposalRatio) += log (2.0);
304 /* update evolLengths in subtree above new event */
305 if (UpdateCppEvolLengths (param, p, chain)==ERROR)
311 /* set update of cond likes down to root */
312 /* crown tree update flags set in UpdateCppEvolLengths */
314 while (q->anc != NULL)
321 MrBayesPrint ("%lf", *mvp); /* just because I am tired of seeing the unused parameter error msg */
325 int Move_Adgamma (Param *param, int chain, RandLong *seed, MrBFlt *lnPriorRatio, MrBFlt *lnProposalRatio, MrBFlt *mvp)
327 /* Change correlation parameter (-1, 1) of adgamma model */
330 MrBFlt oldP, newP, window, minP, maxP, ran, *markovTiValues;
333 /* get size of window, centered on current rho */
336 /* get model params */
337 mp = &modelParams[param->relParts[0]];
339 /* get minimum and maximum values for rho */
340 minP = mp->corrUni[0];
341 maxP = mp->corrUni[1];
343 /* get address of markovTi */
344 markovTiValues = GetParamSubVals (param, chain, state[chain]);
346 /* get old value of rho */
347 newP = oldP = *GetParamVals(param, chain, state[chain]);
349 /* change value for rho */
350 ran = RandomNumber(seed);
351 if (maxP-minP < window)
355 newP = oldP + window * (ran - 0.5);
357 /* check that new value is valid */
362 newP = 2* minP - newP;
363 else if (newP > maxP)
364 newP = 2 * maxP - newP;
367 } while (isValidP == NO);
369 /* get proposal ratio */
370 *lnProposalRatio = 0.0;
372 /* get prior ratio */
375 /* copy new rho value back */
376 *GetParamVals(param, chain, state[chain]) = newP;
378 /* fill in new Markov trans probs */
379 AutodGamma (markovTiValues, newP, mp->numGammaCats);
381 /* Set update flags for all partitions that share this rho. Note that the conditional
382 likelihood update flags have been set before we even call this function. */
383 for (i=0; i<param->nRelParts; i++)
384 TouchAllTreeNodes(&modelSettings[param->relParts[i]],chain);
386 /* Update flags for divisions already set */
392 int Move_Beta (Param *param, int chain, RandLong *seed, MrBFlt *lnPriorRatio, MrBFlt *lnProposalRatio, MrBFlt *mvp)
394 /* change symmetric Dirichlet variance using multiplier */
396 int i, j, k, isValidB, isPriorExp, nStates;
397 MrBFlt oldB, newB, minB, maxB, priorExp=0.0, *bs, ran, factor, tuning,
401 /* get tuning parameter */
402 tuning = mvp[0]; /* multiplier tuning parameter lambda */
404 /* get model paramaters */
405 mp = &modelParams[param->relParts[0]];
407 /* get prior, minimum and maximum values for rate */
408 if (!strcmp(mp->symPiPr,"Uniform"))
411 minB = mp->symBetaUni[0];
412 maxB = mp->symBetaUni[1];
417 priorExp = mp->symBetaExp;
422 /* get old value of symDir */
423 oldB = *GetParamVals(param, chain, state[chain]);
426 ran = RandomNumber(seed);
427 factor = exp(tuning * (ran - 0.5));
428 newB = oldB * factor;
435 newB = minB * minB / newB;
436 else if (newB > maxB)
437 newB = maxB * maxB / newB;
440 } while (isValidB == NO);
442 /* set new value of symDir */
443 *GetParamVals(param, chain, state[chain]) = newB;
445 /* get proposal ratio */
446 *lnProposalRatio = log (newB / oldB);
448 /* get prior ratio */
449 if (isPriorExp == YES)
451 *lnPriorRatio = priorExp * (oldB - newB);
456 /* fill in the new betacat frequencies */
457 bs = GetParamStdStateFreqs(param, chain, state[chain]);
459 BetaBreaks (newB, newB, bs, k);
461 for (i=k-2; i>0; i-=2)
467 bs[i] = 1.0 - bs[i-1];
470 /* if there are multistate characters, update prior probability of current pis */
471 bs += 2 * mp->numBetaCats;
472 for (i=0; i<param->nSympi; i++)
474 /* get number of states */
475 nStates = param->sympinStates[i];
477 /* get prior ratio update */
478 x = LnGamma(newB*nStates) - nStates*LnGamma(newB);
479 y = LnGamma(oldB*nStates) - nStates*LnGamma(oldB);
480 for (j=0; j<nStates; j++)
482 x += (newB-1.0)*log(bs[j]);
483 y += (oldB-1.0)*log(bs[j]);
485 (*lnPriorRatio) += x - y;
487 /* update pointer to state freqs */
491 /* Set update flags for all tree nodes. Note that the conditional
492 likelihood update flags have been set for the relevant partitions
493 before we even call the move function. */
494 for (i=0; i<param->nRelParts; i++)
495 TouchAllTreeNodes(&modelSettings[param->relParts[i]],chain);
497 /* may need to hit update flag for cijks if we have multistate characters */
498 for (i=0; i<param->nRelParts; i++)
500 if (modelSettings[param->relParts[i]].nCijkParts > 0)
501 modelSettings[param->relParts[i]].upDateCijk = YES;
508 int Move_BrLen (Param *param, int chain, RandLong *seed, MrBFlt *lnPriorRatio, MrBFlt *lnProposalRatio, MrBFlt *mvp)
510 /* change one branch length */
512 MrBFlt tuning, maxV, minV, m, newM, brlensPrExp=0.0;
518 tuning = mvp[0]; /* Larget & Simon's tuning parameter lambda */
520 mp = &modelParams[param->relParts[0]];
522 /* max and min brlen */
523 if (param->paramId == BRLENS_UNI)
525 minV = mp->brlensUni[0];
526 maxV = mp->brlensUni[1];
529 else if (param->paramId == BRLENS_GamDir)
535 else if (param->paramId == BRLENS_iGmDir)
541 else if (param->paramId == BRLENS_twoExp)
551 brlensPrExp = mp->brlensExp;
556 t = GetTree (param, chain, state[chain]);
558 /* Dirichlet or twoExp prior */
560 (*lnPriorRatio) = -LogDirPrior(t, mp, isVPriorExp);
564 p = t->allDownPass[(int)(RandomNumber(seed) * t->nNodes)];
566 while (p->anc == NULL || (t->isRooted == YES && p->anc->anc == NULL));
568 /* determine new length */
570 newM = m * exp(tuning * (RandomNumber(seed) - 0.5));
572 /* reflect new length if necessary */
573 while (newM < minV || newM > maxV)
576 newM = minV * minV / newM;
577 else if (newM > maxV)
578 newM = maxV * maxV / newM;
582 /* calculate proposal ratio */
583 /* must be based on new length after reflection */
584 (*lnProposalRatio) = log(newM / m);
586 /* set flags for update of transition probabilities at p */
589 /* set the update flag for cond likes if p is connected to root in unrooted */
590 /* tree, if this is not done, cond likes are not updated in this case */
591 if (t->isRooted == NO && p->anc->anc == NULL)
594 /* set flags for update of cond likes from p->anc and down to root */
595 while (p->anc->anc != NULL)
601 /* update prior if exponential prior on branch lengths */
602 if (param->paramId == BRLENS_EXP)
603 (*lnPriorRatio) = brlensPrExp * (m - newM);
604 /* Dirichlet or twoExp prior */
605 else if (isVPriorExp > 1)
606 (*lnPriorRatio) += LogDirPrior(t, mp, isVPriorExp);
612 int Move_ClockRate_M (Param *param, int chain, RandLong *seed, MrBFlt *lnPriorRatio, MrBFlt *lnProposalRatio, MrBFlt *mvp)
614 /* change clock rate using multiplier */
616 int i, j, k, *nEvents;
617 MrBFlt oldRate, newRate, factor, lambda, nu, igrvar, *brlens, *igrRate, *tk02Rate,
618 N, newTheta, oldTheta, growth, newLnPrior, oldLnPrior;
621 Param *treeParam, *subParm;
625 /* get old value of clock rate */
626 oldRate = *GetParamVals(param, chain, state[chain]);
628 /* Rely on general algorithm to change the value */
629 Move_PosRealMultiplier(param, chain, seed, lnPriorRatio, lnProposalRatio, mvp);
630 if (abortMove == YES)
633 /* get new value of clock rate */
634 newRate = *GetParamVals(param, chain, state[chain]);
636 /* calculate factor */
637 factor = newRate / oldRate;
639 /* clock rate applies to all clock trees */
640 for (i = 0; i < numTrees; i++)
642 t = GetTreeFromIndex(i, chain, state[chain]);
643 if (t->isClock == NO)
645 if (!strcmp(modelParams[t->relParts[0]].clockPr, "Fixed"))
648 oldT = GetTreeFromIndex(i, chain, 1^state[chain]);
649 treeParam = modelSettings[t->relParts[0]].brlens;
651 /* adjust the node depths and lengths */
652 for (j = 0; j < t->nNodes-1; j++)
654 p = t->allDownPass[j];
655 q = oldT->allDownPass[j];
656 p->nodeDepth *= factor; /* no harm done if nodeDepth==0.0 (undated tips) */
657 p->length *= factor; /* no harm done if length==0.0 (root or fossil ancestors)*/
658 if (p->length < 0.0 || p->length > BRLENS_MAX ||
659 (q->length > BRLENS_MIN && p->length < BRLENS_MIN) ||
660 (q->length < TIME_MIN && p->length > TIME_MIN))
661 { /* consider ancestral fossil (brl=0) in fossilized bd tree */
667 /* prior ratio for coalecent tree, as theta is changed */
668 mp = &modelParams[t->relParts[0]];
669 if (!strcmp(mp->clockPr,"Coalescence"))
671 m = &modelSettings[t->relParts[0]];
672 N = *GetParamVals(m->popSize, chain, state[chain]);
673 if (!strcmp(mp->ploidy, "Diploid"))
675 else if (!strcmp(mp->ploidy, "Zlinked"))
679 oldTheta = N * oldRate;
680 newTheta = N * newRate;
681 if (!strcmp(mp->growthPr, "Fixed"))
682 growth = mp->growthFix;
684 growth = *GetParamVals(m->growthRate, chain, state[chain]);
686 if (LnCoalescencePriorPr (oldT, &oldLnPrior, oldTheta, growth) == ERROR)
688 MrBayesPrint ("%s Problem calculating prior for coalescent process\n", spacer);
691 if (LnCoalescencePriorPr (t, &newLnPrior, newTheta, growth) == ERROR)
693 MrBayesPrint ("%s Problem calculating prior for coalescent process\n", spacer);
696 (*lnPriorRatio) += newLnPrior - oldLnPrior;
699 /* adjust proposal and prior ratio for relaxed clock models */
700 for (k = 0; k < treeParam->nSubParams; k++)
702 subParm = treeParam->subParams[k];
703 if (subParm->paramType == P_CPPEVENTS)
705 nEvents = subParm->nEvents[2*chain+state[chain]];
706 lambda = *GetParamVals (modelSettings[subParm->relParts[0]].cppRate, chain, state[chain]);
708 for (j=0; j<t->nNodes-2; j++)
710 p = t->allDownPass[j];
711 q = oldT->allDownPass[j];
712 (*lnProposalRatio) += nEvents[p->index ] * log (p->length / q->length);
715 (*lnPriorRatio) += lambda * (TreeLen(oldT) - TreeLen(t));
716 /* update effective evolutionary lengths */
717 if (UpdateCppEvolLengths (subParm, t->root->left, chain) == ERROR)
723 else if ( subParm->paramType == P_TK02BRANCHRATES ||
724 (subParm->paramType == P_MIXEDBRCHRATES && *GetParamIntVals(subParm, chain, state[chain]) == RCL_TK02))
726 if (subParm->paramType == P_TK02BRANCHRATES)
727 nu = *GetParamVals (modelSettings[subParm->relParts[0]].tk02var, chain, state[chain]);
729 nu = *GetParamVals (modelSettings[subParm->relParts[0]].mixedvar, chain, state[chain]);
730 tk02Rate = GetParamVals (subParm, chain, state[chain]);
731 brlens = GetParamSubVals (subParm, chain, state[chain]);
733 /* no proposal ratio effect */
735 /* prior ratio and update of brlens */
736 for (j = 0; j < t->nNodes-2; j++)
738 p = t->allDownPass[j];
739 q = oldT->allDownPass[j];
740 if (p->length > 0.0) // not ancestral fossil
742 (*lnPriorRatio) -= LnProbTK02LogNormal (tk02Rate[q->anc->index], nu*q->length, tk02Rate[q->index]);
743 (*lnPriorRatio) += LnProbTK02LogNormal (tk02Rate[p->anc->index], nu*p->length, tk02Rate[p->index]);
745 brlens[p->index] = p->length * (tk02Rate[p->anc->index]+tk02Rate[p->index])/2.0;
749 else if ( subParm->paramType == P_IGRBRANCHRATES ||
750 (subParm->paramType == P_MIXEDBRCHRATES && *GetParamIntVals(subParm, chain, state[chain]) == RCL_IGR))
752 if (subParm->paramType == P_IGRBRANCHRATES)
753 igrvar = *GetParamVals (modelSettings[subParm->relParts[0]].igrvar, chain, state[chain]);
755 igrvar = *GetParamVals (modelSettings[subParm->relParts[0]].mixedvar, chain, state[chain]);
756 igrRate = GetParamVals (subParm, chain, state[chain]);
757 brlens = GetParamSubVals (subParm, chain, state[chain]);
759 /* prior ratio and update of brlens */
760 for (j = 0; j < t->nNodes-2; j++)
762 p = t->allDownPass[j];
763 q = oldT->allDownPass[j];
764 if (p->length > 0.0) // not ancestral fossil
766 (*lnPriorRatio) -= LnProbGamma (q->length/igrvar, q->length/igrvar, igrRate[q->index]);
767 (*lnPriorRatio) += LnProbGamma (p->length/igrvar, p->length/igrvar, igrRate[p->index]);
769 brlens[p->index] = igrRate[p->index] * p->length;
780 int Move_CPPEventPosition (Param *param, int chain, RandLong *seed, MrBFlt *lnPriorRatio, MrBFlt *lnProposalRatio, MrBFlt *mvp)
782 /* move the position of one CPP event */
784 int i, j, k, *nEvents;
785 MrBFlt pos, temp, **position, **rateMultiplier;
786 TreeNode *p=NULL, *q;
789 /* get the cpp event data */
790 nEvents = param->nEvents[2*chain+state[chain]];
791 position = param->position[2*chain+state[chain]];
792 rateMultiplier = param->rateMult[2*chain+state[chain]];
795 t = GetTree (param, chain, state[chain]);
797 /* pick a branch and an event */
798 for (i=j=0; i<t->nNodes - 2; i++)
800 p = t->allDownPass[i];
801 j += nEvents[p->index];
808 k = (int) (RandomNumber(seed) * j);
809 for (i=j=0; i<t->nNodes - 2; i++)
811 p = t->allDownPass[i];
812 j += nEvents[p->index];
816 if (position[p->index] == NULL)
819 /* find local index */
820 k = k - (j - nEvents[p->index]);
822 /* find new position */
823 pos = RandomNumber(seed);
824 if (pos < POS_MIN || 1.0 - pos < POS_MIN)
829 position[p->index][k] = pos;
831 /* sort events; bubble sort for now */
832 for (i=0; i<nEvents[p->index]; i++)
834 for (j=i+1; j<nEvents[p->index]; j++)
836 if (position[p->index][j] < position[p->index][i])
838 temp = position[p->index][i];
839 position[p->index][i] = position[p->index][j];
840 position[p->index][j] = temp;
841 temp = rateMultiplier[p->index][i];
842 rateMultiplier[p->index][i] = rateMultiplier[p->index][j];
843 rateMultiplier[p->index][j] = temp;
848 /* calculate prior and proposal ratio */
849 (*lnPriorRatio) = (*lnProposalRatio) = 0.0;
851 /* update branch evolution lengths */
852 if (UpdateCppEvolLengths (param, p, chain) == ERROR)
858 /* set update of cond likes down to root */
859 /* update of crowntree set in UpdateCppEvolLengths */
861 while (q->anc != NULL)
868 MrBayesPrint ("%lf", *mvp); /* just because I am tired of seeing the unused parameter error msg */
872 int Move_CPPRate (Param *param, int chain, RandLong *seed, MrBFlt *lnPriorRatio, MrBFlt *lnProposalRatio, MrBFlt *mvp)
874 /* move the CPP rate (lambda) using multiplier */
876 int i, j, *nEvents, sumEvents;
877 MrBFlt oldLambda, newLambda, treeLength, tuning;
882 /* get tuning parameter */
885 /* get model params */
886 mp = &modelParams[param->relParts[0]];
888 /* get the CPP rate */
889 oldLambda = *GetParamVals (param, chain, state[chain]);
892 newLambda = oldLambda * exp ((0.5 - RandomNumber(seed))*tuning);
894 /* reflect if necessary */
895 while (newLambda < CPPLAMBDA_MIN || newLambda > CPPLAMBDA_MAX)
897 if (newLambda < CPPLAMBDA_MIN)
898 newLambda = CPPLAMBDA_MIN * CPPLAMBDA_MIN / newLambda;
899 if (newLambda > CPPLAMBDA_MAX)
900 newLambda = CPPLAMBDA_MAX * CPPLAMBDA_MAX / newLambda;
903 /* store new value */
904 (*GetParamVals (param, chain, state[chain])) = newLambda;
906 /* calculate prior ratio */
907 (*lnPriorRatio) = 0.0;
908 for (i=0; i<param->nSubParams; i++)
910 nEvents = param->subParams[i]->nEvents[2*chain+state[chain]];
912 t = GetTree (param->subParams[i], chain, state[chain]);
914 for (j=0; j<t->nNodes-2; j++)
916 p = t->allDownPass[j];
917 sumEvents += nEvents[p->index];
918 treeLength += p->length;
920 (*lnPriorRatio) += (oldLambda - newLambda) * treeLength;
921 (*lnPriorRatio) += sumEvents * log (newLambda / oldLambda);
924 /* adjust for prior on cppRate */
925 if (!strcmp(mp->cppRatePr,"Exponential"))
926 (*lnPriorRatio) += mp->cppRateExp * (oldLambda - newLambda);
928 /* calculate proposal ratio */
929 (*lnProposalRatio) = log (newLambda / oldLambda);
931 /* we do not need to update likelihoods */
932 for (i=0; i<param->nRelParts; i++)
934 modelSettings[param->relParts[i]].upDateCl = NO;
941 int Move_CPPRateMultiplier_M (Param *param, int chain, RandLong *seed, MrBFlt *lnPriorRatio, MrBFlt *lnProposalRatio, MrBFlt *mvp)
943 /* move one CPP rate multiplier using multiplier */
945 int i, j, k, *nEvents;
946 MrBFlt newRateMultiplier, oldRateMultiplier, tuning, minM, maxM, sigma, **rateMultiplier;
952 /* get the tuning parameter */
955 /* get the model settings */
956 m = &modelSettings[param->relParts[0]];
959 t = GetTree (param, chain, state[chain]);
961 /* get CPP event data */
962 nEvents = param->nEvents[2*chain+state[chain]];
963 rateMultiplier = param->rateMult[2*chain+state[chain]];
965 /* get minimum and maximum of CPP rate multiplier */
969 /* pick a branch and a rateMultiplier */
970 for (i=j=0; i<t->nNodes - 2; i++)
972 p = t->allDownPass[i];
973 j += nEvents[p->index];
980 k = (int) (RandomNumber(seed) * j);
981 for (i=j=0; i<t->nNodes - 2; i++)
983 p = t->allDownPass[i];
984 j += nEvents[p->index];
989 /* find local index */
990 k = nEvents[p->index] - (j - k);
992 /* find new rateMultiplier */
993 oldRateMultiplier = rateMultiplier[p->index][k];
994 newRateMultiplier = oldRateMultiplier * (exp (0.5 - RandomNumber(seed) * tuning));
996 /* reflect if necessary */
997 while (newRateMultiplier < minM || newRateMultiplier > maxM)
999 if (newRateMultiplier < minM)
1000 newRateMultiplier = minM * minM / newRateMultiplier;
1001 if (newRateMultiplier > maxM)
1002 newRateMultiplier = maxM * maxM / newRateMultiplier;
1005 rateMultiplier[p->index][k] = newRateMultiplier;
1007 /* calculate prior ratio */
1008 sigma = *GetParamVals (m->cppMultDev, chain, state[chain]);
1009 (*lnPriorRatio) = LnRatioLogNormal (0.0, sigma, newRateMultiplier, oldRateMultiplier);
1011 /* calculate proposal ratio */
1012 (*lnProposalRatio) = log (newRateMultiplier / oldRateMultiplier);
1014 /* update branch evolution lengths */
1015 if (UpdateCppEvolLengths (param, p, chain)==ERROR)
1021 /* set update of cond likes down to root */
1022 /* update of crowntree set in UpdateCppEvolLengths */
1024 while (q->anc != NULL)
1034 int Move_CPPRateMultiplierRnd (Param *param, int chain, RandLong *seed, MrBFlt *lnPriorRatio, MrBFlt *lnProposalRatio, MrBFlt *mvp)
1036 /* move one CPP rate multiplier by redrawing from prior */
1038 int i, j, k, *nEvents;
1039 MrBFlt sigma, newRateMultiplier, oldRateMultiplier, **rateMultiplier;
1040 TreeNode *p=NULL, *q;
1044 /* get the model settings */
1045 m = &modelSettings[param->relParts[0]];
1047 /* get the CPP event data */
1048 nEvents = param->nEvents[2*chain+state[chain]];
1049 rateMultiplier = param->rateMult[2*chain+state[chain]];
1052 t = GetTree (param, chain, state[chain]);
1054 /* pick a branch and a rateMultiplier */
1055 for (i=j=0; i<t->nNodes - 2; i++)
1057 p = t->allDownPass[i];
1058 j += nEvents[p->index];
1065 k = (int) (RandomNumber(seed) * j);
1066 for (i=j=0; i<t->nNodes - 2; i++)
1068 p = t->allDownPass[i];
1069 j += nEvents[p->index];
1074 /* find local index */
1075 k = nEvents[p->index] - (j - k);
1077 /* record old rate multiplier */
1078 oldRateMultiplier = rateMultiplier[p->index][k];
1080 /* find stdev of lognormal */
1081 sigma = *GetParamVals (m->cppMultDev, chain, state[chain]);
1085 newRateMultiplier = LogNormalRandomVariable (0.0, sigma, seed);
1086 } while (newRateMultiplier < param->min || newRateMultiplier > param->max);
1087 rateMultiplier[p->index][k] = newRateMultiplier;
1089 /* calculate prior ratio */
1090 (*lnPriorRatio) = LnRatioLogNormal(0.0, sigma, newRateMultiplier, oldRateMultiplier);
1092 /* calculate proposal ratio */
1093 (*lnProposalRatio) += LnRatioLogNormal (0.0, sigma, oldRateMultiplier, newRateMultiplier);
1095 /* update branch evolution lengths */
1096 if (UpdateCppEvolLengths (param, p, chain) == ERROR)
1102 /* set update of cond likes down to root */
1103 /* update of crowntree set in UpdateCppEvolLengths */
1105 while (q->anc != NULL)
1112 MrBayesPrint ("%lf", *mvp); /* just because I am tired of seeing the unused parameter error msg */
1116 int Move_AddBranch (Param *param, int chain, RandLong *seed, MrBFlt *lnPriorRatio, MrBFlt *lnProposalRatio, MrBFlt *mvp)
1118 /* Move an ancestral fossil (brl = 0) to fossil tip (brl > 0)
1127 1. Pich a fossil among those with brl = 0 (prob = 1/k)
1128 2. Propose brl from a uniform(0, ?) distribution
1131 int i, j, k, mFossil, kFossil;
1132 MrBFlt minDepth, maxDepth, newLength, clockRate, x, oldQLength, oldRLength,
1133 *brlens=NULL, nu=0.0, *tk02Rate=NULL, igrvar=0.0, *igrRate=NULL;
1134 TreeNode *p=NULL, *q=NULL, *r;
1139 Calibration *calibrationPtr = NULL;
1141 (*lnProposalRatio) = (*lnPriorRatio) = 0.0;
1144 t = GetTree (param, chain, state[chain]);
1146 /* get number of ancestral and tip fossils */
1147 kFossil = mFossil = 0;
1148 for (i = 0; i < t->nNodes -1; i++)
1150 p = t->allDownPass[i];
1151 p->marked = NO; // reset marked node
1152 if (p->left == NULL && p->right == NULL && p->nodeDepth > 0.0)
1154 if (p->length > 0.0)
1156 mFossil++; // count tip fossil
1160 p->marked = YES; // mark anc fossil
1161 kFossil++; // count anc fossil
1165 if (kFossil == 0) // no ancestral fossil, nothing to do
1171 /* get model params and model info */
1172 mp = &modelParams[param->relParts[0]];
1173 m = &modelSettings[param->relParts[0]];
1175 /* get clock rate */
1176 clockRate = *(GetParamVals(m->clockRate, chain, state[chain]));
1178 /* pick an ancestral fossil randomly */
1179 j = (int) (RandomNumber(seed) * kFossil);
1180 for (i = k = 0; i < t->nNodes -1; i++)
1182 p = t->allDownPass[i];
1183 if (p->marked == YES)
1188 /* now p is pointing to the ancestral fossil
1189 whose brl needs to be changed to >0. let's do it! */
1196 /* determine lower and upper bound of forward move, abort if impossible */
1197 minDepth = p->nodeDepth + BRLENS_MIN;
1198 if (q->anc->anc == NULL)
1199 maxDepth = TREEHEIGHT_MAX;
1201 maxDepth = q->anc->nodeDepth - BRLENS_MIN;
1203 if (q->isDated == YES)
1204 calibrationPtr = q->calibration;
1205 else if (q->anc->anc == NULL) // q is root but not dated
1206 calibrationPtr = &mp->treeAgePr;
1208 if (calibrationPtr != NULL)
1210 if (calibrationPtr->prior == fixed || calibrationPtr->min * clockRate > minDepth)
1215 if (calibrationPtr->max * clockRate < maxDepth)
1216 maxDepth = calibrationPtr->max * clockRate;
1218 if (minDepth >= maxDepth)
1224 /* record old lengths and depths */
1225 oldQLength = q->length;
1226 oldRLength = r->length;
1227 // oldDepth = q->nodeDepth;
1229 /* propose the branch length leading to the fossil */
1230 newLength = (RandomNumber(seed)) * (maxDepth - minDepth);
1232 /* adjust brls and depths, set flags for update of trans probs */
1233 p->length = newLength;
1235 q->nodeDepth += newLength;
1236 if (q->anc->anc != NULL)
1238 q->length -= newLength;
1241 r->length += newLength;
1243 // newDepth = q->nodeDepth;
1245 /* adjust age of q if dated */
1246 if (calibrationPtr != NULL)
1248 q->age = q->nodeDepth / clockRate;
1251 /* set flags for update of cond likes from p/r to root */
1254 while (q->anc != NULL)
1261 /* calculate prior ratio */
1262 if (LogClockTreePriorRatio(param, chain, &x) == ERROR)
1264 (*lnPriorRatio) += x;
1266 /* calculate proposal ratio, need to double check !! */
1267 (*lnProposalRatio) = log(kFossil) - log(mFossil +1);
1268 // if (mFossil == 0) // current tree has no fossil tips
1269 // (*lnProposalRatio) += log(0.5);
1270 // else if (kFossil == 1) // proposed tree has no ancestral fossils
1271 // (*lnProposalRatio) += log(2.0);
1273 /* add the Jacobian term */
1274 (*lnProposalRatio) += log((maxDepth - minDepth) / clockRate);
1276 /* adjust proposal and prior ratio for relaxed clock models */
1277 for (i=0; i<param->nSubParams; i++)
1279 subParm = param->subParams[i];
1280 if (subParm->paramType == P_CPPEVENTS)
1282 /* CPP is not compatible with FBD ancestral fossils until we have a good way to implement it !! */
1283 MrBayesPrint ("%s CPP clock is not compatible with Fossilization prior currently\n", spacer);
1286 else if ( subParm->paramType == P_TK02BRANCHRATES ||
1287 (subParm->paramType == P_MIXEDBRCHRATES && *GetParamIntVals(subParm, chain, state[chain]) == RCL_TK02))
1289 if (subParm->paramType == P_TK02BRANCHRATES)
1290 nu = *GetParamVals (modelSettings[subParm->relParts[0]].tk02var, chain, state[chain]);
1292 nu = *GetParamVals (modelSettings[subParm->relParts[0]].mixedvar, chain, state[chain]);
1293 tk02Rate = GetParamVals (subParm, chain, state[chain]);
1294 brlens = GetParamSubVals (subParm, chain, state[chain]);
1297 tk02Rate[p->index] = tk02Rate[q->index];
1298 (*lnPriorRatio) -= LnProbTK02LogNormal (tk02Rate[q->index], nu*oldRLength, tk02Rate[r->index]);
1299 (*lnPriorRatio) += LnProbTK02LogNormal (tk02Rate[q->index], nu* p->length, tk02Rate[p->index]);
1300 (*lnPriorRatio) += LnProbTK02LogNormal (tk02Rate[q->index], nu* r->length, tk02Rate[r->index]);
1301 if (q->anc->anc != NULL)
1303 (*lnPriorRatio) -= LnProbTK02LogNormal (tk02Rate[q->anc->index], nu*oldQLength, tk02Rate[q->index]);
1304 (*lnPriorRatio) += LnProbTK02LogNormal (tk02Rate[q->anc->index], nu* q->length, tk02Rate[q->index]);
1307 /* update effective evolutionary lengths */
1308 brlens[p->index] = p->length * (tk02Rate[p->index]+tk02Rate[q->index])/2.0;
1309 brlens[r->index] = r->length * (tk02Rate[r->index]+tk02Rate[q->index])/2.0;
1310 if (q->anc->anc != NULL)
1312 brlens[q->index] = q->length * (tk02Rate[q->index]+tk02Rate[q->anc->index])/2.0;
1315 else if ( subParm->paramType == P_IGRBRANCHRATES ||
1316 (subParm->paramType == P_MIXEDBRCHRATES && *GetParamIntVals(subParm, chain, state[chain]) == RCL_IGR))
1318 if (subParm->paramType == P_IGRBRANCHRATES)
1319 igrvar = *GetParamVals (modelSettings[subParm->relParts[0]].igrvar, chain, state[chain]);
1321 igrvar = *GetParamVals (modelSettings[subParm->relParts[0]].mixedvar, chain, state[chain]);
1322 igrRate = GetParamVals (subParm, chain, state[chain]);
1323 brlens = GetParamSubVals (subParm, chain, state[chain]);
1326 igrRate[p->index] = igrRate[q->index];
1327 (*lnPriorRatio) -= LnProbGamma (oldRLength/igrvar, oldRLength/igrvar, igrRate[r->index]);
1328 (*lnPriorRatio) += LnProbGamma (p->length /igrvar, p->length /igrvar, igrRate[p->index]);
1329 (*lnPriorRatio) += LnProbGamma (r->length /igrvar, r->length /igrvar, igrRate[r->index]);
1330 if (q->anc->anc != NULL)
1332 (*lnPriorRatio) -= LnProbGamma (oldQLength/igrvar, oldQLength/igrvar, igrRate[q->index]);
1333 (*lnPriorRatio) += LnProbGamma (q->length /igrvar, q->length /igrvar, igrRate[q->index]);
1336 /* update effective evolutionary lengths */
1337 brlens[p->index] = igrRate[p->index] * p->length;
1338 brlens[r->index] = igrRate[r->index] * r->length;
1339 if (q->anc->anc != NULL)
1341 brlens[q->index] = igrRate[q->index] * q->length;
1347 MrBayesPrint ("%lf", *mvp); /* just because I am tired of seeing the unused parameter error msg */
1351 int Move_DelBranch (Param *param, int chain, RandLong *seed, MrBFlt *lnPriorRatio, MrBFlt *lnProposalRatio, MrBFlt *mvp)
1353 /* Move a fossil tip (brl > 0) to be ancestral (brl =0)
1362 1. Pich a fossil among those with brl > 0 (prob = 1/m)
1366 int i, j, k, mFossil, kFossil;
1367 MrBFlt minDepth, maxDepth, clockRate, x, oldPLength, oldQLength, oldRLength,
1368 *brlens=NULL, nu=0.0, *tk02Rate=NULL, igrvar=0.0, *igrRate=NULL;
1369 TreeNode *p=NULL, *q=NULL, *r;
1374 Calibration *calibrationPtr = NULL;
1376 (*lnProposalRatio) = (*lnPriorRatio) = 0.0;
1379 t = GetTree (param, chain, state[chain]);
1381 /* get number of ancestral and tip fossils */
1382 kFossil = mFossil = 0;
1383 for (i = 0; i < t->nNodes -1; i++)
1385 p = t->allDownPass[i];
1386 p->marked = NO; // reset marked node
1387 if (p->left == NULL && p->right == NULL && p->nodeDepth > 0.0)
1389 if (p->length > 0.0)
1391 p->marked = YES; // mark tip fossil
1392 mFossil++; // count tip fossil
1396 kFossil++; // count anc fossil
1400 if (mFossil == 0) // no tip fossil, nothing to do
1406 /* get model params and model info */
1407 mp = &modelParams[param->relParts[0]];
1408 m = &modelSettings[param->relParts[0]];
1410 /* get clock rate */
1411 clockRate = *(GetParamVals(m->clockRate, chain, state[chain]));
1413 /* pick a tip fossil randomly */
1414 j = (int) (RandomNumber(seed) * mFossil);
1415 for (i = k = 0; i < t->nNodes -1; i++)
1417 p = t->allDownPass[i];
1418 if (p->marked == YES)
1423 /* now p is pointing to the fossil tip
1424 whose brl needs to be changed to 0. let's do it */
1431 /* determine lower and upper bound of backward move, abort if impossible */
1432 minDepth = p->nodeDepth + BRLENS_MIN;
1433 if (q->anc->anc == NULL)
1434 maxDepth = TREEHEIGHT_MAX;
1436 maxDepth = q->anc->nodeDepth - BRLENS_MIN;
1438 if (q->isDated == YES)
1439 calibrationPtr = q->calibration;
1440 else if (q->anc->anc == NULL) // q is root but not dated
1441 calibrationPtr = &mp->treeAgePr;
1443 if (calibrationPtr != NULL)
1445 if (calibrationPtr->prior == fixed || calibrationPtr->min * clockRate > minDepth)
1450 if (calibrationPtr->max * clockRate < maxDepth)
1451 maxDepth = calibrationPtr->max * clockRate;
1453 if (r->nodeDepth > p->nodeDepth -BRLENS_MIN || minDepth >= maxDepth)
1454 { /* the sister node (another fossil) is older than the current fossil */
1459 /* record old lengths and depths */
1460 oldPLength = p->length;
1461 oldQLength = q->length;
1462 oldRLength = r->length;
1463 // oldDepth = q->nodeDepth;
1465 /* set the brl to 0 for the fossil tip, it becomes an ancestral fossil */
1466 /* set flags for update of transition probabilities too */
1467 q->nodeDepth = p->nodeDepth;
1468 if (q->anc->anc != NULL)
1470 q->length += p->length;
1473 r->length -= p->length;
1477 // newDepth = q->nodeDepth;
1479 /* adjust age of q if dated */
1480 if (calibrationPtr != NULL)
1482 q->age = q->nodeDepth / clockRate;
1485 /* set flags for update of cond likes from p/r to root */
1488 while (q->anc != NULL)
1495 /* calculate prior ratio */
1496 if (LogClockTreePriorRatio(param, chain, &x) == ERROR)
1498 (*lnPriorRatio) += x;
1500 /* calculate proposal ratio, need to double check !! */
1501 (*lnProposalRatio) = log(mFossil) - log(kFossil +1);
1502 // if (kFossil == 0) // current tree has no ancestral fossils
1503 // (*lnProposalRatio) += log(2.0);
1504 // else if (mFossil == 1) // proposed tree has no fossil tips
1505 // (*lnProposalRatio) += log(0.5);
1507 /* add the Jacobian term */
1508 (*lnProposalRatio) -= log((maxDepth - minDepth) / clockRate);
1510 /* adjust proposal and prior ratio for relaxed clock models */
1511 for (i=0; i<param->nSubParams; i++)
1513 subParm = param->subParams[i];
1514 if (subParm->paramType == P_CPPEVENTS)
1516 /* CPP is not compatible with FBD ancestral fossils until we have a good way to implement it !! */
1517 MrBayesPrint ("%s CPP clock is not compatible with Fossilization prior currently\n", spacer);
1520 else if ( subParm->paramType == P_TK02BRANCHRATES ||
1521 (subParm->paramType == P_MIXEDBRCHRATES && *GetParamIntVals(subParm, chain, state[chain]) == RCL_TK02))
1523 if (subParm->paramType == P_TK02BRANCHRATES)
1524 nu = *GetParamVals (modelSettings[subParm->relParts[0]].tk02var, chain, state[chain]);
1526 nu = *GetParamVals (modelSettings[subParm->relParts[0]].mixedvar, chain, state[chain]);
1527 tk02Rate = GetParamVals (subParm, chain, state[chain]);
1528 brlens = GetParamSubVals (subParm, chain, state[chain]);
1531 (*lnPriorRatio) -= LnProbTK02LogNormal (tk02Rate[q->index], nu*oldPLength, tk02Rate[p->index]);
1532 (*lnPriorRatio) -= LnProbTK02LogNormal (tk02Rate[q->index], nu*oldRLength, tk02Rate[r->index]);
1533 (*lnPriorRatio) += LnProbTK02LogNormal (tk02Rate[q->index], nu* r->length, tk02Rate[r->index]);
1534 if (q->anc->anc != NULL)
1536 (*lnPriorRatio) -= LnProbTK02LogNormal (tk02Rate[q->anc->index], nu*oldQLength, tk02Rate[q->index]);
1537 (*lnPriorRatio) += LnProbTK02LogNormal (tk02Rate[q->anc->index], nu* q->length, tk02Rate[q->index]);
1540 /* update effective evolutionary lengths */
1541 brlens[p->index] = 0.0; // tk02Rate[p->index] = tk02Rate[q->index];
1542 brlens[r->index] = r->length * (tk02Rate[r->index]+tk02Rate[q->index])/2.0;
1543 if (q->anc->anc != NULL)
1545 brlens[q->index] = q->length * (tk02Rate[q->index]+tk02Rate[q->anc->index])/2.0;
1548 else if ( subParm->paramType == P_IGRBRANCHRATES ||
1549 (subParm->paramType == P_MIXEDBRCHRATES && *GetParamIntVals(subParm, chain, state[chain]) == RCL_IGR))
1551 if (subParm->paramType == P_IGRBRANCHRATES)
1552 igrvar = *GetParamVals (modelSettings[subParm->relParts[0]].igrvar, chain, state[chain]);
1554 igrvar = *GetParamVals (modelSettings[subParm->relParts[0]].mixedvar, chain, state[chain]);
1555 igrRate = GetParamVals (subParm, chain, state[chain]);
1556 brlens = GetParamSubVals (subParm, chain, state[chain]);
1558 (*lnPriorRatio) -= LnProbGamma (oldPLength/igrvar, oldPLength/igrvar, igrRate[p->index]);
1559 (*lnPriorRatio) -= LnProbGamma (oldRLength/igrvar, oldRLength/igrvar, igrRate[r->index]);
1560 (*lnPriorRatio) += LnProbGamma (r->length /igrvar, r->length /igrvar, igrRate[r->index]);
1561 if (q->anc->anc != NULL)
1563 (*lnPriorRatio) -= LnProbGamma (oldQLength/igrvar, oldQLength/igrvar, igrRate[q->index]);
1564 (*lnPriorRatio) += LnProbGamma (q->length /igrvar, q->length /igrvar, igrRate[q->index]);
1567 /* update effective evolutionary lengths */
1568 brlens[p->index] = 0.0; // igrRate[p->index] = igrRate[q->index];
1569 brlens[r->index] = igrRate[r->index] * r->length;
1570 if (q->anc->anc != NULL)
1572 brlens[q->index] = igrRate[q->index] * q->length;
1578 MrBayesPrint ("%lf", *mvp); /* just because I am tired of seeing the unused parameter error msg */
1582 int Move_Extinction (Param *param, int chain, RandLong *seed, MrBFlt *lnPriorRatio, MrBFlt *lnProposalRatio, MrBFlt *mvp)
1584 /* change relative extinction rate using sliding window */
1586 int i, isValidM, valIndex;
1587 MrBFlt *valPtr, oldM, newM, window, minM, maxM, *sR, *eR, sF, *fR, oldLnPrior, newLnPrior,
1588 oldProp[2], newProp[2], x, y, *alphaDir, clockRate;
1594 /* get size of window, centered on current value */
1597 /* get model params and settings */
1598 mp = &modelParams[param->relParts[0]];
1599 m = &modelSettings[param->relParts[0]];
1601 /* get minimum and maximum values */
1605 /* get pointer to value to be changed */
1606 valIndex = (int)(RandomNumber(seed) * param->nValues);
1607 valPtr = GetParamVals(param, chain, state[chain]) + valIndex;
1613 if (window > maxM-minM)
1615 newM = oldM + window * (RandomNumber(seed) - 0.5);
1617 /* check that new value is valid */
1621 newM = 2 * minM - newM;
1622 else if (newM > maxM)
1623 newM = 2 * maxM - newM;
1626 } while (isValidM == NO);
1628 /* get proposal ratio */
1629 *lnProposalRatio = 0.0;
1631 /* calculate prior ratio */
1632 t = GetTree(modelSettings[param->relParts[0]].brlens,chain,state[chain]);
1633 sR = GetParamVals (m->speciationRates, chain, state[chain]);
1634 eR = GetParamVals (param, chain, state[chain]);
1635 sF = mp->sampleProb;
1636 sS = mp->sampleStrat;
1637 clockRate = *GetParamVals (m->clockRate, chain, state[chain]);
1639 if (!strcmp(mp->clockPr,"Birthdeath"))
1641 if (LnBirthDeathPriorPr (t, clockRate, &oldLnPrior, *sR, *eR, sS, sF) == ERROR)
1643 MrBayesPrint ("%s Problem calculating prior for birth-death process\n", spacer);
1646 *valPtr = newM; // update with new value
1647 if (LnBirthDeathPriorPr (t, clockRate, &newLnPrior, *sR, *eR, sS, sF) == ERROR)
1649 MrBayesPrint ("%s Problem calculating prior for birth-death process\n", spacer);
1653 else if (!strcmp(mp->clockPr,"Fossilization"))
1655 fR = GetParamVals (m->fossilizationRates, chain, state[chain]);
1656 if (LnFossilizationPriorPr (t, clockRate, &oldLnPrior, sR, eR, sF, fR, sS) == ERROR)
1658 MrBayesPrint ("%s Problem calculating prior for fossilized birth-death process\n", spacer);
1661 *valPtr = newM; // update with new value
1662 // for (i=0; i<param->nValues; i++) *(GetParamVals(param, chain, state[chain]) + i) = newM;
1663 if (LnFossilizationPriorPr (t, clockRate, &newLnPrior, sR, eR, sF, fR, sS) == ERROR)
1665 MrBayesPrint ("%s Problem calculating prior for fossilized birth-death process\n", spacer);
1670 MrBayesPrint ("%s Move_Extinction not applicable\n", spacer);
1674 /* get proportions */
1676 oldProp[1] = 1.0 - oldM;
1678 newProp[1] = 1.0 - newM;
1680 /* adjust prior ratio according to beta distribution */
1681 alphaDir = mp->extinctionBeta;
1684 x += (alphaDir[i]-1.0)*log(newProp[i]);
1686 y += (alphaDir[i]-1.0)*log(oldProp[i]);
1687 (*lnPriorRatio) = x - y + newLnPrior - oldLnPrior;
1693 int Move_Fossilization (Param *param, int chain, RandLong *seed, MrBFlt *lnPriorRatio, MrBFlt *lnProposalRatio, MrBFlt *mvp)
1695 /* change fossilization rate using sliding window */
1697 int i, isValidM, valIndex;
1698 MrBFlt *valPtr, oldM, newM, window, minM, maxM, *sR, *eR, sF, *fR, oldLnPrior, newLnPrior,
1699 oldProp[2], newProp[2], x, y, *alphaDir, clockRate;
1705 /* get size of window, centered on current value */
1708 /* get model params and settings */
1709 mp = &modelParams[param->relParts[0]];
1710 m = &modelSettings[param->relParts[0]];
1712 /* get minimum and maximum values */
1716 /* get pointer to value to be changed */
1717 valIndex = (int)(RandomNumber(seed) * param->nValues);
1718 valPtr = GetParamVals(param, chain, state[chain]) + valIndex;
1724 if (window > maxM-minM)
1726 newM = oldM + window * (RandomNumber(seed) - 0.5);
1728 /* check that new value is valid */
1732 newM = 2 * minM - newM;
1733 else if (newM > maxM)
1734 newM = 2 * maxM - newM;
1737 } while (isValidM == NO);
1739 /* get proposal ratio */
1740 *lnProposalRatio = 0.0;
1742 /* calculate prior ratio */
1743 t = GetTree(modelSettings[param->relParts[0]].brlens,chain,state[chain]);
1744 sR = GetParamVals (m->speciationRates, chain, state[chain]);
1745 eR = GetParamVals (m->extinctionRates, chain, state[chain]);
1746 fR = GetParamVals (param, chain, state[chain]);
1747 sF = mp->sampleProb;
1748 sS = mp->sampleStrat;
1749 clockRate = *GetParamVals(m->clockRate, chain, state[chain]);
1751 if (LnFossilizationPriorPr (t, clockRate, &oldLnPrior, sR, eR, sF, fR, sS) == ERROR)
1753 MrBayesPrint ("%s Problem calculating prior for fossilized birth-death process\n", spacer);
1756 *valPtr = newM; // update with new value
1757 if (LnFossilizationPriorPr (t, clockRate, &newLnPrior, sR, eR, sF, fR, sS) == ERROR)
1759 MrBayesPrint ("%s Problem calculating prior for fossilized birth-death process\n", spacer);
1763 /* get proportions */
1765 oldProp[1] = 1.0 - oldM;
1767 newProp[1] = 1.0 - newM;
1769 /* adjust prior ratio according to beta distribution */
1770 alphaDir = mp->fossilizationBeta;
1773 x += (alphaDir[i]-1.0)*log(newProp[i]);
1775 y += (alphaDir[i]-1.0)*log(oldProp[i]);
1776 (*lnPriorRatio) = x - y + newLnPrior - oldLnPrior;
1782 int Move_ExtSPR (Param *param, int chain, RandLong *seed, MrBFlt *lnPriorRatio, MrBFlt *lnProposalRatio, MrBFlt *mvp)
1784 /* Change topology (and branch lengths) using SPR (unrooted) with extension probability.
1785 Pick either external or internal branches instead of just internal branches. */
1787 int i, j, topologyHasChanged, nCrownNodes, nRootNodes, directionLeft, directionUp,
1788 isVPriorExp, moveInRoot, isStartConstrained, isStopConstrained;
1789 MrBFlt m, x, y, tuning, maxV, minV, extensionProb, brlensExp=0.0;
1790 TreeNode *p, *q, *a, *b, *c, *d, *u, *v;
1794 /* these parameters should be possible to set by user */
1795 extensionProb = mvp[0]; /* extension probability */
1796 tuning = mvp[1]; /* Larget & Simon's tuning parameter lambda */
1798 (*lnProposalRatio) = (*lnPriorRatio) = 0.0;
1801 t = GetTree (param, chain, state[chain]);
1803 /* get model params */
1804 mp = &modelParams[param->relParts[0]];
1806 /* max and min brlen */
1807 if (param->subParams[0]->paramId == BRLENS_UNI)
1809 minV = mp->brlensUni[0] > BRLENS_MIN ? mp->brlensUni[0] : BRLENS_MIN;
1810 maxV = mp->brlensUni[1] < BRLENS_MAX ? mp->brlensUni[1] : BRLENS_MAX;
1813 else if (param->subParams[0]->paramId == BRLENS_GamDir)
1819 else if (param->subParams[0]->paramId == BRLENS_iGmDir)
1825 else if (param->subParams[0]->paramId == BRLENS_twoExp)
1831 else /* (param->subParams[0]->paramId == BRLENS_EXP) */
1835 brlensExp = mp->brlensExp;
1839 /* Dirichlet or twoExp prior */
1840 if (isVPriorExp > 1)
1841 (*lnPriorRatio) = -LogDirPrior(t, mp, isVPriorExp);
1843 topologyHasChanged = NO;
1845 # if defined (DEBUG_ExtSPR)
1846 printf ("Before:\n");
1847 ShowNodes (t->root, 2, NO);
1851 /* pick a random branch */
1853 p = t->allDownPass[(int)(RandomNumber(seed) * (t->nNodes -1))];
1854 q = p->anc->right; if (q == p) q = p->anc->left;
1856 if (p->left == NULL)
1858 if (p->anc->anc == NULL)
1860 if (p->anc->anc != NULL && (p->anc->isLocked == YES || p->anc->anc->anc == NULL))
1862 if (p->anc->anc != NULL && (q->isLocked == YES || q->left == NULL))
1864 if (p->left != NULL && (p->left->isLocked == YES || p->left->left == NULL))
1866 if (p->left != NULL && (p->right->isLocked == YES || p->right->left == NULL))
1868 } while (i == 2 && j == 2);
1870 /* change in root tree ? */
1875 else if (RandomNumber(seed) < 0.5)
1880 /* determine whether start is constrained on backward move */
1881 isStartConstrained = isStopConstrained = NO;
1882 if (moveInRoot == YES && i == 1)
1883 isStartConstrained = YES;
1884 else if (moveInRoot == NO && j == 1)
1885 isStartConstrained = YES;
1887 /* set up pointers for nodes around the picked branch */
1888 /* cut the tree into crown, root and attachment part */
1889 /* change the relevant lengths in the attachment part */
1893 /* modify length of middle branch */
1895 x = m * exp(tuning * (RandomNumber(seed) - 0.5));
1896 while (x < minV || x > maxV)
1898 if (x < minV) x = minV * minV / x;
1899 if (x > maxV) x = maxV * maxV / x;
1904 /* update proposal and prior ratio based on length modification */
1905 (*lnProposalRatio) += log (x / m);
1906 if (isVPriorExp == YES)
1907 (*lnPriorRatio) += brlensExp * (m - x);
1909 /* move around in root subtree */
1911 if (moveInRoot == YES)
1913 /* mark nodes in root part */
1914 /* also determine direction of move in root part */
1920 if (u->anc->anc == NULL || u->isLocked == YES)
1922 else if (a->left == NULL || a->isLocked == YES)
1924 else if (RandomNumber(seed) < 0.5)
1929 if (directionUp == NO)
1931 b = a; /* switch a and b */
1939 else // if (directionUp == YES)
1947 a->length = u->length;
1953 for (nRootNodes=0; RandomNumber(seed)<extensionProb || nRootNodes==0; nRootNodes++)
1955 if (directionUp == YES)
1956 { /* going up tree */
1957 if (a->left == NULL || a->isLocked == YES)
1958 break; /* can't go further */
1960 if (RandomNumber(seed) < 0.5)
1964 if (u->isLocked == YES)
1968 b->lockID = u->lockID;
1972 else // directionUp == NO
1973 { /* going down tree */
1974 if (a->anc == NULL || u->isLocked == YES)
1975 break; /* can't go further */
1976 if (RandomNumber(seed) < 0.5)
1978 directionUp = YES; /* switch direction */
1979 /* find sister of a */
1990 /* as long as we are moving upwards, the cond likes to update
1991 will be flagged by the last pass from u to the root */
1994 { /* continue down */
1998 if (b->isLocked == YES)
2002 u->lockID = b->lockID;
2009 topologyHasChanged = YES;
2010 /* check whether stop is constrained */
2011 if (directionUp == YES && (a->left == NULL || a->isLocked == YES))
2012 isStopConstrained = YES;
2013 if (directionUp == NO && (a->anc == NULL || u->isLocked == YES))
2014 isStopConstrained = YES;
2016 /* modify branch length */
2018 x = m * exp(tuning * (RandomNumber(seed) - 0.5));
2019 while (x < minV || x > maxV)
2021 if (x < minV) x = minV * minV / x;
2022 if (x > maxV) x = maxV * maxV / x;
2027 /* update proposal and prior ratio based on length modification */
2028 (*lnProposalRatio) += log (x / m);
2029 if (isVPriorExp == YES)
2030 (*lnPriorRatio) += brlensExp * (m - x);
2032 /* combine the subtrees */
2033 if (directionUp == YES)
2046 else // if (directionUp == NO)
2058 /* the modified branch contained in u->length will have to be moved to b->length to enable back move
2059 BUT if we haven't moved, it is better to keep it in place (necessary for rooted trees) */
2061 u->length = b->length;
2068 /* move around in crown subtree */
2070 if (moveInRoot == NO)
2072 /* set up pointers for crown part */
2073 /* also determine direction of move in crown part */
2074 if (v->right->left == NULL || v->right->isLocked == YES)
2075 directionLeft = YES;
2076 else if (v->left->left == NULL || v->left->isLocked == YES)
2078 else if (RandomNumber(seed) < 0.5)
2079 directionLeft = YES;
2082 if (directionLeft == YES)
2093 /* store brlen nodes and brlen to move */
2096 /* cut and reconnect crown part */
2100 for (nCrownNodes=0; RandomNumber(seed)<extensionProb || nCrownNodes==0; nCrownNodes++)
2102 if (c->left == NULL || c->isLocked == YES)
2103 break; /* can't go further */
2104 if (RandomNumber(seed) < 0.5)
2106 /* rotate c anticlockwise - prepare pointers for move left */
2107 c->anc = c->left; /* the root will be in the direction we are heading */
2113 /* rotate c clockwise - prepare pointers for move right */
2114 c->anc = c->right; /* the root will be in the direction we are heading */
2118 /* OK - let's move! c->anc points in the right direction
2119 don't forget to move the branch lengths as well */
2122 d->length = c->length; /* also rotate other info ?? */
2127 topologyHasChanged = YES;
2128 /* check if stop constrained */
2129 if (c->left == NULL || c->isLocked == YES)
2130 isStopConstrained = YES;
2132 /* combine the subtrees */
2135 if (directionLeft == YES)
2146 /* the dangling branch is inserted in reverted position such that the back move will be possible
2147 if we have moved around in crown subtree otherwise it is left in its original position */
2150 /* modify branch length */
2152 x = m * exp(tuning * (RandomNumber(seed) - 0.5));
2153 while (x < minV || x > maxV)
2155 if (x < minV) x = minV * minV / x;
2156 if (x > maxV) x = maxV * maxV / x;
2161 /* update proposal and prior ratio based on length modification */
2162 (*lnProposalRatio) += log (x / m);
2163 if (isVPriorExp == YES)
2164 (*lnPriorRatio) += brlensExp * (m - x);
2167 /* adjust proposal ratio for constraints */
2168 if (isStartConstrained == NO && isStopConstrained == YES)
2169 (*lnProposalRatio) += log (2.0 * (1.0 - extensionProb));
2170 else if (isStartConstrained == YES && isStopConstrained == NO)
2171 (*lnProposalRatio) -= log (2.0 * (1.0 - extensionProb));
2173 /* set flags for update of cond likes from v and down to root */
2175 while (p->anc != NULL)
2181 /* get down pass sequence if tree topology has changed */
2182 if (topologyHasChanged == YES)
2187 /* Dirichlet or twoExp prior */
2188 if (isVPriorExp > 1)
2189 (*lnPriorRatio) += LogDirPrior(t, mp, isVPriorExp);
2191 # if defined (DEBUG_ExtSPR)
2192 printf ("After:\n");
2193 ShowNodes (t->root, 2, NO);
2195 printf ("Proposal ratio: %f\n",(*lnProposalRatio));
2196 printf ("v: %d u: %d c: %d d: %d a: %d b: %d\n",v->index, u->index,
2197 c->index, d->index, a->index, b->index);
2198 printf ("No. nodes moved in root subtree: %d\n",nRootNodes);
2199 printf ("No. nodes moved in crown subtree: %d\n",nCrownNodes);
2200 printf ("Has topology changed? %d\n",topologyHasChanged);
2208 int Move_ExtSPR1 (Param *param, int chain, RandLong *seed, MrBFlt *lnPriorRatio, MrBFlt *lnProposalRatio, MrBFlt *mvp)
2210 /* Change topology (and branch lengths) using SPR (unrooted) with extension probability. */
2211 /* Pick only internal branches. For a description, see Lakner et al. (2008). */
2213 int i, j, topologyHasChanged, nCrownNodes, nRootNodes, directionLeft, directionUp,
2214 isVPriorExp, moveInRoot, isStartConstrained, isStopConstrained;
2215 MrBFlt m, x, y, tuning, maxV, minV, extensionProb, brlensExp=0.0;
2216 TreeNode *p, *a, *b, *c, *d, *u, *v, *brlenNode[7];
2220 /* these parameters should be possible to set by user */
2221 extensionProb = mvp[0]; /* extension probability */
2222 tuning = mvp[1]; /* Larget & Simon's tuning parameter lambda */
2224 (*lnProposalRatio) = (*lnPriorRatio) = 0.0;
2227 t = GetTree (param, chain, state[chain]);
2229 /* get model params */
2230 mp = &modelParams[param->relParts[0]];
2232 /* max and min brlen */
2233 if (param->subParams[0]->paramId == BRLENS_UNI)
2235 minV = mp->brlensUni[0] > BRLENS_MIN ? mp->brlensUni[0] : BRLENS_MIN;
2236 maxV = mp->brlensUni[1] < BRLENS_MAX ? mp->brlensUni[1] : BRLENS_MAX;
2239 else if (param->subParams[0]->paramId == BRLENS_GamDir)
2245 else if (param->subParams[0]->paramId == BRLENS_iGmDir)
2251 else if (param->subParams[0]->paramId == BRLENS_twoExp)
2261 brlensExp = mp->brlensExp;
2265 /* Dirichlet or twoExp prior */
2266 if (isVPriorExp > 1)
2267 (*lnPriorRatio) = -LogDirPrior(t, mp, isVPriorExp);
2269 topologyHasChanged = NO;
2271 # if defined (DEBUG_ExtSPR)
2272 printf ("Before:\n");
2273 ShowNodes (t->root, 2, NO);
2277 /* pick an internal branch that is free to move in either end
2278 (i and j keep track of number of locked directions) */
2280 p = t->intDownPass[(int)(RandomNumber(seed) * (t->nIntNodes-1))];
2281 if (p->anc->left == p)
2286 if (a->isLocked == YES || a->left == NULL)
2288 if (p->anc->isLocked == YES || p->anc->anc->anc == NULL)
2290 if (p->left->isLocked == YES || p->left->left == NULL)
2292 if (p->right->isLocked == YES || p->right->left == NULL)
2294 } while (i == 2 && j == 2);
2296 /* set up pointers for nodes around the picked branch */
2297 /* cut the tree into crown, root and attachment part */
2298 /* change the relevant lengths in the attachment part */
2299 /* the lengths of a and v are automatically contained in the */
2300 /* "attachment" part but the length of c has to be stored in x */
2304 /* store brlen node */
2307 /* change in root tree ? */
2312 else if (RandomNumber(seed) < 0.5)
2317 /* determine whether start is constrained on backward move */
2318 isStartConstrained = isStopConstrained = NO;
2319 if (moveInRoot == YES && i == 1)
2320 isStartConstrained = YES;
2321 else if (moveInRoot == NO && j == 1)
2322 isStartConstrained = YES;
2324 /* set up pointers for crown part */
2325 /* also determine direction of move in crown part */
2326 if (v->right->left == NULL || v->right->isLocked == YES)
2327 directionLeft = YES;
2328 else if (v->left->left == NULL || v->left->isLocked == YES)
2330 else if (RandomNumber(seed) < 0.5)
2331 directionLeft = YES;
2334 if (directionLeft == YES)
2345 /* store brlen nodes and brlen to move */
2350 /* cut and reconnect crown part */
2354 /* mark nodes in root part */
2355 /* also determine direction of move in root part */
2361 if (u->anc->anc == NULL || u->isLocked == YES)
2363 else if (a->left == NULL || a->isLocked == YES)
2365 else if (RandomNumber(seed) < 0.5)
2369 if (directionUp == NO)
2371 /* switch a and b */
2376 /* store brlen nodes */
2377 if (directionUp == YES)
2389 if (directionUp == NO)
2405 a->length = u->length;
2411 /* move around in root subtree */
2413 if (moveInRoot == YES)
2415 for (nRootNodes=0; RandomNumber(seed)<extensionProb || nRootNodes==0; nRootNodes++)
2417 if (directionUp == YES)
2418 { /* going up tree */
2419 if (a->left == NULL || a->isLocked == YES)
2420 break; /* can't go further */
2421 topologyHasChanged = YES;
2423 if (RandomNumber(seed) < 0.5)
2427 if (u->isLocked == YES)
2431 b->lockID = u->lockID;
2436 { /* going down tree */
2437 if (a->anc == NULL || u->isLocked == YES)
2438 break; /* can't go further */
2439 topologyHasChanged = YES;
2440 if (RandomNumber(seed)<0.5)
2442 directionUp = YES; /* switch direction */
2443 /* find sister of a */
2454 /* as long as we are moving upwards
2455 the cond likes to update will be
2456 flagged by the last pass from u to the root */
2459 { /* continue down */
2463 if (b->isLocked == YES)
2467 u->lockID = b->lockID;
2473 /* check whether stop is constrained */
2474 if (directionUp == YES)
2476 if (a->left == NULL || a->isLocked == YES)
2477 isStopConstrained = YES;
2481 if (a->anc == NULL || u->isLocked == YES)
2482 isStopConstrained = YES;
2486 /* store brlen nodes */
2489 if (directionUp == YES)
2501 /* move around in crown subtree */
2503 if (moveInRoot == NO)
2505 for (nCrownNodes=0; RandomNumber(seed)<extensionProb || nCrownNodes==0; nCrownNodes++)
2507 if (c->left == NULL || c->isLocked == YES)
2508 break; /* can't go further */
2509 topologyHasChanged = YES;
2510 if (RandomNumber(seed) < 0.5)
2512 /* rotate c anticlockwise - prepare pointers for move left */
2513 c->anc = c->left; /* the root will be in the direction we are heading */
2519 /* rotate c clockwise - prepare pointers for move right */
2520 c->anc = c->right; /* the root will be in the direction we are heading */
2524 /* OK - let's move!; c->anc points in the right direction
2525 don't forget to move the branch lengths as well */
2528 d->length = c->length;
2532 /* check if stop constrained */
2533 if (c->left == NULL || c->isLocked == YES)
2534 isStopConstrained = YES;
2537 /* store brlen nodes */
2538 if (nCrownNodes > 0)
2544 /* adjust proposal ratio for constraints */
2545 if (isStartConstrained == NO && isStopConstrained == YES)
2546 (*lnProposalRatio) += log (2.0 * (1.0 - extensionProb));
2547 else if (isStartConstrained == YES && isStopConstrained == NO)
2548 (*lnProposalRatio) -= log (2.0 * (1.0 - extensionProb));
2550 /* combine the subtrees */
2553 if (directionLeft == YES)
2564 /* the dangling branch is inserted in reverted position
2565 such that the back move will be possible
2566 if we have moved around in crown subtree
2567 otherwise it is left in its original position */
2568 if (nCrownNodes > 0)
2578 if (directionUp == YES)
2590 /* the dangling branch is contained in u->length
2591 and will automatically be inserted in the right position
2592 to enable the back move regardless of whether it was
2593 initially directed upwards or downwards
2594 BUT if we haven't moved in root subtree, it is advantageous (necessary
2595 for rooted trees) to avoid switching branches, which occurs otherwise
2596 if directionUp == YES */
2597 if (nRootNodes == 0)
2600 u->length = a->length;
2618 /* the modified branch contained in u->length will have
2619 to be moved to b->length to enable back move
2620 BUT if we haven't moved, it is better to keep it in place
2621 (necessary for rooted trees) */
2625 u->length = b->length;
2632 /* modify branch lengths */
2633 /* first modify length of middle branch */
2634 m = brlenNode[3]->length;
2635 x = m * exp(tuning * (RandomNumber(seed) - 0.5));
2636 while (x < minV || x > maxV)
2639 x = minV * minV / x;
2641 x = maxV * maxV / x;
2643 brlenNode[3]->length = x;
2644 brlenNode[3]->upDateTi = YES;
2646 /* update proposal and prior ratio based on length modification */
2647 (*lnProposalRatio) += log (x / m);
2648 if (isVPriorExp == YES)
2649 (*lnPriorRatio) += brlensExp * (m - x);
2651 if (moveInRoot == NO)
2653 /* if no move in crown, then select randomly, otherwise always the moved branch */
2654 if (nCrownNodes == 0 && RandomNumber(seed) < 0.5)
2659 /* modify branch length */
2661 x = m * exp(tuning * (RandomNumber(seed) - 0.5));
2662 while (x < minV || x > maxV)
2665 x = minV * minV / x;
2667 x = maxV * maxV / x;
2672 /* update proposal and prior ratio based on length modification */
2673 (*lnProposalRatio) += log (x / m);
2674 if (isVPriorExp == YES)
2675 (*lnPriorRatio) += brlensExp * (m - x);
2678 if (moveInRoot == YES)
2680 /* if no move in root, then select randomly, otherwise always the moved branch */
2681 if (nRootNodes == 0 && RandomNumber(seed) < 0.5)
2686 /* modify branch length but not if 'root' branch in rooted tree */
2687 if (t->isRooted == NO || p->anc->anc != NULL)
2690 x = m * exp(tuning * (RandomNumber(seed) - 0.5));
2691 while (x < minV || x > maxV)
2694 x = minV * minV / x;
2696 x = maxV * maxV / x;
2701 /* update proposal and prior ratio based on length modification */
2702 (*lnProposalRatio) += log (x / m);
2703 if (isVPriorExp == YES)
2704 (*lnPriorRatio) += brlensExp * (m - x);
2708 /* set flags for update of cond likes from v and down to root */
2710 while (p->anc != NULL)
2716 /* get down pass sequence if tree topology has changed */
2717 if (topologyHasChanged == YES)
2722 /* Dirichlet or twoExp prior */
2723 if (isVPriorExp > 1)
2724 (*lnPriorRatio) += LogDirPrior(t, mp, isVPriorExp);
2726 # if defined (DEBUG_ExtSPR)
2727 printf ("After:\n");
2728 ShowNodes (t->root, 2, NO);
2730 printf ("Proposal ratio: %f\n",(*lnProposalRatio));
2731 printf ("v: %d u: %d c: %d d: %d a: %d b: %d\n",v->index, u->index,
2732 c->index, d->index, a->index, b->index);
2733 printf ("No. nodes moved in root subtree: %d\n",nRootNodes);
2734 printf ("No. nodes moved in crown subtree: %d\n",nCrownNodes);
2735 printf ("Has topology changed? %d\n",topologyHasChanged);
2743 int Move_ExtSPRClock (Param *param, int chain, RandLong *seed, MrBFlt *lnPriorRatio, MrBFlt *lnProposalRatio, MrBFlt *mvp)
2745 /* Change branch lengths and topology (potentially) using SPR-type move
2746 with extension probability (rather than window, attachment rate or similar).
2747 The move is Metropolized, which should improve mixing. However, this means
2748 that it must be combined with a node slider move to be efficient.
2750 The move picks a branch and then moves its lower attachment point
2751 from its original position, one node at a time, with
2752 a probability determined by the extensionProb parameter. This is
2753 done in a way consistent with the clock constraints and any locked
2754 nodes there might be in the tree. The lower attachment point is
2755 minimally moved one node away.
2757 On the ending branch, the attachment point is reinserted randomly
2758 along the branch (below the minimum age of the node). */
2760 int i, j, topologyHasChanged=NO, isStartLocked=NO, isStopLocked=NO, nRootNodes, directionUp,
2761 n1=0, n2=0, n3=0, n4=0, n5=0, *nEvents;
2762 MrBFlt x, y, oldBrlen=0.0, newBrlen=0.0, extensionProb, igrvar, *igrRate=NULL,
2763 v1=0.0, v2=0.0, v3=0.0, v4=0.0, v5=0.0, v3new=0.0, lambda, *tk02Rate=NULL,
2764 **position=NULL, **rateMultiplier=NULL, *brlens, nu, minV, clockRate;
2765 TreeNode *p, *a, *b, *u, *v, *oldA;
2770 extensionProb = mvp[0]; /* extension probability */
2772 (*lnProposalRatio) = (*lnPriorRatio) = 0.0;
2775 t = GetTree (param, chain, state[chain]);
2777 /* get model params and model info */
2778 m = &modelSettings[param->relParts[0]];
2780 /* get clock rate */
2781 clockRate = *GetParamVals (m->clockRate, chain, state[chain]);
2783 /* get min and max branch lengths in relative time and substitution units */
2786 # if defined (DEBUG_ExtSPRClock)
2787 printf ("Before:\n");
2788 ShowNodes (t->root, 2, YES);
2794 p = t->allDownPass[(int)(RandomNumber(seed) * (t->nNodes - 2))];
2798 while (p->anc->isLocked == YES || p->anc->anc->anc == NULL
2799 || (p == b && a->length < TIME_MIN) || (p == a && b->length < TIME_MIN)
2800 || (p->length < TIME_MIN && p->calibration->prior == fixed));
2801 /* skip constraints, siblings of root (and root); and consider ancestral fossils in fbd tree */
2803 /* set up pointers for nodes around the picked branch */
2813 /* record branch length for insertion in back move */
2814 if (v->length > 0.0) /* side branch, not anc fossil */
2816 if (v->nodeDepth > a->nodeDepth)
2817 oldBrlen = b->nodeDepth - v->nodeDepth - 2.0*minV;
2819 oldBrlen = b->nodeDepth - a->nodeDepth - 2.0*minV;
2821 else /* ancestral fossil */
2823 y = (b->nodeDepth - minV > v->calibration->max * clockRate) ? (v->calibration->max * clockRate) : (b->nodeDepth - minV);
2824 x = (a->nodeDepth + minV < v->calibration->min * clockRate) ? (v->calibration->min * clockRate) : (a->nodeDepth + minV);
2831 /* reassign events for CPP and adjust prior and proposal ratios for relaxed clock models */
2832 for (i=0; i<param->subParams[0]->nSubParams; i++)
2834 subParm = param->subParams[0]->subParams[i];
2835 if (subParm->paramType == P_CPPEVENTS)
2837 /* get pointers to CPP events */
2838 nEvents = subParm->nEvents[2*chain+state[chain]];
2839 position = subParm->position[2*chain+state[chain]];
2840 rateMultiplier = subParm->rateMult[2*chain+state[chain]];
2841 n1 = nEvents[a->index];
2842 n2 = nEvents[u->index];
2843 n3 = nEvents[v->index];
2846 position[a->index] = (MrBFlt *) SafeRealloc ((void *) position[a->index], (n1+n2) * sizeof (MrBFlt));
2847 rateMultiplier[a->index] = (MrBFlt *) SafeRealloc ((void *) rateMultiplier[a->index], (n1+n2) * sizeof (MrBFlt));
2849 for (j=0; j<n1; j++)
2850 position[a->index][j] *= v1 / (v1+v2);
2851 for (j=n1; j<n1+n2; j++)
2853 position[a->index][j] = (position[u->index][j-n1] * v2 + v1) / (v1+v2);
2854 rateMultiplier[a->index][j] = rateMultiplier[u->index][j-n1];
2856 nEvents[a->index] = n1+n2;
2857 nEvents[u->index] = 0;
2860 free (position[u->index]);
2861 free (rateMultiplier[u->index]);
2862 position[u->index] = rateMultiplier[u->index] = NULL;
2864 } /* end CPP events parm */
2865 else if ( subParm->paramType == P_TK02BRANCHRATES ||
2866 (subParm->paramType == P_MIXEDBRCHRATES && *GetParamIntVals(subParm, chain, state[chain]) == RCL_TK02))
2868 /* adjust prior ratio */
2869 if (subParm->paramType == P_TK02BRANCHRATES)
2870 nu = *GetParamVals (modelSettings[subParm->relParts[0]].tk02var, chain, state[chain]);
2872 nu = *GetParamVals (modelSettings[subParm->relParts[0]].mixedvar, chain, state[chain]);
2873 tk02Rate = GetParamVals (subParm, chain, state[chain]);
2874 if (v->length > 0.0)
2875 (*lnPriorRatio) -= LnProbTK02LogNormal(tk02Rate[v->anc->index], nu*v->length, tk02Rate[v->index]);
2876 (*lnPriorRatio) -= LnProbTK02LogNormal(tk02Rate[a->anc->index], nu*a->length, tk02Rate[a->index]);
2877 (*lnPriorRatio) -= LnProbTK02LogNormal(tk02Rate[u->anc->index], nu*u->length, tk02Rate[u->index]);
2878 (*lnPriorRatio) += LnProbTK02LogNormal(tk02Rate[u->anc->index], nu*(a->length+u->length), tk02Rate[a->index]);
2880 /* adjust effective branch lengths */
2881 brlens = GetParamSubVals (subParm, chain, state[chain]);
2882 brlens[a->index] = (tk02Rate[a->index] + tk02Rate[b->index]) / 2.0 * (a->length + u->length);
2883 } /* end tk02 branch rate parameter */
2884 else if ( subParm->paramType == P_IGRBRANCHRATES ||
2885 (subParm->paramType == P_MIXEDBRCHRATES && *GetParamIntVals(subParm, chain, state[chain]) == RCL_IGR))
2887 if (subParm->paramType == P_IGRBRANCHRATES)
2888 igrvar = *GetParamVals (modelSettings[subParm->relParts[0]].igrvar, chain, state[chain]);
2890 igrvar = *GetParamVals (modelSettings[subParm->relParts[0]].mixedvar, chain, state[chain]);
2891 igrRate = GetParamVals (subParm, chain, state[chain]);
2893 /* adjust prior ratio for old branches */
2894 if (v->length > 0.0)
2895 (*lnPriorRatio) -= LnProbGamma(v->length/igrvar, v->length/igrvar, igrRate[v->index]);
2896 (*lnPriorRatio) -= LnProbGamma(a->length/igrvar, a->length/igrvar, igrRate[a->index]);
2897 (*lnPriorRatio) -= LnProbGamma(u->length/igrvar, u->length/igrvar, igrRate[u->index]);
2898 (*lnPriorRatio) += LnProbGamma((a->length+u->length)/igrvar, (a->length+u->length)/igrvar, igrRate[a->index]);
2900 /* adjust effective branch lengths and rates */
2901 brlens = GetParamSubVals (subParm, chain, state[chain]);
2902 brlens[a->index] = igrRate[a->index] * (a->length + u->length);
2904 } /* next subparameter */
2912 a->length += u->length;
2915 /* determine initial direction of move and whether the reverse move would be stopped by constraints */
2916 if (a->left == NULL || a->isLocked == YES || a->nodeDepth < v->nodeDepth + minV)
2918 isStartLocked = YES;
2924 if (RandomNumber(seed) < 0.5)
2930 /* move around in root subtree */
2931 for (nRootNodes=0; nRootNodes==0 || RandomNumber(seed)<extensionProb; nRootNodes++)
2933 if (directionUp == YES)
2934 { /* going up tree */
2935 if (a->left == NULL || a->isLocked == YES || a->nodeDepth < v->nodeDepth + minV)
2936 break; /* can't go farther */
2937 topologyHasChanged = YES;
2939 if (a->left->length < TIME_MIN)
2941 else if (a->right->length < TIME_MIN)
2943 else if (RandomNumber(seed) < 0.5)
2949 { /* going down tree */
2950 topologyHasChanged = YES;
2951 if (RandomNumber(seed) < 0.5 || b->anc->anc == NULL || b->isLocked == YES)
2953 directionUp = YES; /* switch direction */
2954 /* find sister of a */
2959 /* as long as we are moving upwards
2960 the cond likes to update will be
2961 flagged by the last pass from u to the root */
2964 { /* continue down */
2972 /* determine whether the forward move was or would have been stopped by constraints */
2974 if (directionUp == YES)
2976 if (a->left == NULL || a->isLocked == YES || a->nodeDepth < v->nodeDepth + minV)
2992 if (v->length > 0.0) /* side branch, not anc fossil */
2994 if (a->nodeDepth > v->nodeDepth)
2995 newBrlen = b->nodeDepth - a->nodeDepth - 2.0*minV;
2997 newBrlen = b->nodeDepth - v->nodeDepth - 2.0*minV;
2999 else /* ancestral fossil */
3001 y = (b->nodeDepth - minV > v->calibration->max * clockRate) ? (v->calibration->max * clockRate) : (b->nodeDepth - minV);
3002 x = (a->nodeDepth + minV < v->calibration->min * clockRate) ? (v->calibration->min * clockRate) : (a->nodeDepth + minV);
3005 if (newBrlen <= 0.0)
3011 /* adjust lengths */
3012 if (v->length > 0.0) /* side branch, not anc fossil */
3014 u->nodeDepth = b->nodeDepth - minV - RandomNumber(seed) * newBrlen;
3015 v->length = u->nodeDepth - v->nodeDepth;
3017 else /* ancestral fossil */
3019 u->nodeDepth = y - RandomNumber(seed) * newBrlen;
3020 v->nodeDepth = u->nodeDepth;
3021 v->age = u->age = u->nodeDepth / clockRate;
3023 u->length = b->nodeDepth - u->nodeDepth;
3024 a->length = u->nodeDepth - a->nodeDepth;
3030 /* adjust events, prior ratio and proposal ratio for relaxed clock models */
3031 for (i=0; i<param->subParams[0]->nSubParams; i++)
3033 subParm = param->subParams[0]->subParams[i];
3034 if (subParm->paramType == P_CPPEVENTS)
3036 /* reassign events for CPP */
3037 nEvents = subParm->nEvents[2*chain+state[chain]];
3038 position = subParm->position[2*chain+state[chain]];
3039 rateMultiplier = subParm->rateMult[2*chain+state[chain]];
3040 for (j=0; j<nEvents[a->index]; j++)
3042 if (position[a->index][j] > v4 / (v4+v5))
3046 n5 = nEvents[a->index] - j;
3047 nEvents[u->index] = n5;
3050 position[u->index] = (MrBFlt *) SafeRealloc ((void *) position[u->index], n5 * sizeof (MrBFlt));
3051 rateMultiplier[u->index] = (MrBFlt *) SafeRealloc ((void *) rateMultiplier[u->index], n5 * sizeof (MrBFlt));
3052 for (j=n4; j<nEvents[a->index]; j++)
3054 position[u->index][j-n4] = (position[a->index][j] * (v4+v5) - v4) / v5;
3055 rateMultiplier[u->index][j-n4] = rateMultiplier[a->index][j];
3059 position[a->index] = (MrBFlt *) SafeRealloc ((void *) position[a->index], n4 * sizeof (MrBFlt));
3060 rateMultiplier[a->index] = (MrBFlt *) SafeRealloc ((void *) rateMultiplier[a->index], n4 * sizeof (MrBFlt));
3061 for (j=0; j<n4; j++)
3062 position[a->index][j] *= ((v4+v5) / v4);
3066 free (position[a->index]);
3067 free (rateMultiplier[a->index]);
3068 position[a->index] = rateMultiplier[a->index] = NULL;
3070 nEvents[a->index] = n4;
3074 for (j=0; j<nEvents[a->index]; j++)
3075 position[a->index][j] *= ((v4+v5) / v4);
3078 /* adjust proposal ratio for length change in v branch*/
3079 (*lnProposalRatio) += n3 * log (v3new / v3);
3081 /* adjust prior ratio for length change */
3082 lambda = *GetParamVals (modelSettings[subParm->relParts[0]].cppRate, chain, state[chain]);
3083 (*lnPriorRatio) += lambda * (v3 - v3new);
3085 /* update effective branch lengths */
3086 if (UpdateCppEvolLengths (subParm, oldA, chain) == ERROR)
3091 if (UpdateCppEvolLengths (subParm, u, chain) == ERROR)
3096 } /* end cpp events parameter */
3097 else if ( subParm->paramType == P_TK02BRANCHRATES ||
3098 (subParm->paramType == P_MIXEDBRCHRATES && *GetParamIntVals(subParm, chain, state[chain]) == RCL_TK02))
3100 /* adjust prior ratio */
3101 if (subParm->paramType == P_TK02BRANCHRATES)
3102 nu = *GetParamVals (modelSettings[subParm->relParts[0]].tk02var, chain, state[chain]);
3104 nu = *GetParamVals (modelSettings[subParm->relParts[0]].mixedvar, chain, state[chain]);
3105 tk02Rate = GetParamVals (subParm, chain, state[chain]);
3106 (*lnPriorRatio) -= LnProbTK02LogNormal(tk02Rate[u->anc->index], nu*(a->length+u->length), tk02Rate[a->index]);
3107 (*lnPriorRatio) += LnProbTK02LogNormal(tk02Rate[a->anc->index], nu*a->length, tk02Rate[a->index]);
3108 (*lnPriorRatio) += LnProbTK02LogNormal(tk02Rate[u->anc->index], nu*u->length, tk02Rate[u->index]);
3109 if (v->length > 0.0)
3110 (*lnPriorRatio) += LnProbTK02LogNormal(tk02Rate[v->anc->index], nu*v->length, tk02Rate[v->index]);
3112 /* adjust effective branch lengths */
3113 brlens = GetParamSubVals (subParm, chain, state[chain]);
3114 brlens[a->index] = a->length * (tk02Rate[a->index] + tk02Rate[a->anc->index]) / 2.0;
3115 brlens[v->index] = v->length * (tk02Rate[v->index] + tk02Rate[v->anc->index]) / 2.0;
3116 brlens[u->index] = u->length * (tk02Rate[u->index] + tk02Rate[u->anc->index]) / 2.0;
3117 } /* end tk02 branch rate parameter */
3118 else if ( subParm->paramType == P_IGRBRANCHRATES ||
3119 (subParm->paramType == P_MIXEDBRCHRATES && *GetParamIntVals(subParm, chain, state[chain]) == RCL_IGR))
3121 /* adjust prior ratio */
3122 if (subParm->paramType == P_IGRBRANCHRATES)
3123 igrvar = *GetParamVals (modelSettings[subParm->relParts[0]].igrvar, chain, state[chain]);
3125 igrvar = *GetParamVals (modelSettings[subParm->relParts[0]].mixedvar, chain, state[chain]);
3126 igrRate = GetParamVals (subParm, chain, state[chain]);
3127 (*lnPriorRatio) -= LnProbGamma ((a->length+u->length)/igrvar, (a->length+u->length)/igrvar, igrRate[a->index]);
3128 (*lnPriorRatio) += LnProbGamma (a->length/igrvar, a->length/igrvar, igrRate[a->index]);
3129 (*lnPriorRatio) += LnProbGamma (u->length/igrvar, u->length/igrvar, igrRate[u->index]);
3130 if (v->length > 0.0)
3131 (*lnPriorRatio) += LnProbGamma (v->length/igrvar, v->length/igrvar, igrRate[v->index]);
3133 /* adjust effective branch lengths */
3134 brlens = GetParamSubVals (subParm, chain, state[chain]);
3135 brlens[v->index] = igrRate[v->index] * v->length;
3136 brlens[u->index] = igrRate[u->index] * u->length;
3137 brlens[a->index] = igrRate[a->index] * a->length;
3138 } /* end igr branch rate parameter */
3139 } /* next subparameter */
3141 /* set tiprobs update flags */
3146 /* set flags for update of cond likes from u and down to root */
3148 while (p->anc != NULL)
3154 /* adjust prior ratio for clock tree */
3155 if (LogClockTreePriorRatio(param, chain, &x) == ERROR)
3157 (*lnPriorRatio) += x;
3159 if (topologyHasChanged == YES)
3161 /* get down pass sequence if tree topology has changed */
3163 /* calculate proposal ratio for tree change */
3164 (*lnProposalRatio) += log (newBrlen / oldBrlen);
3165 if (isStartLocked == NO && isStopLocked == YES)
3166 (*lnProposalRatio) += log (2.0 * (1.0 - extensionProb));
3167 else if (isStartLocked == YES && isStopLocked == NO)
3168 (*lnProposalRatio) -= log (2.0 * (1.0 - extensionProb));
3171 # if defined (DEBUG_ExtSPRClock)
3172 ShowNodes (t->root, 2, YES);
3173 printf ("After\nProposal ratio: %f\n",(*lnProposalRatio));
3174 printf ("v: %d u: %d a: %d b: %d\n",v->index, u->index, a->index, b->index);
3175 printf ("No. nodes moved in root subtree: %d\n",nRootNodes);
3176 printf ("Has topology changed? %d\n",topologyHasChanged);
3183 int Move_ExtSS (Param *param, int chain, RandLong *seed, MrBFlt *lnPriorRatio, MrBFlt *lnProposalRatio, MrBFlt *mvp)
3185 /* Change branch lengths and topology (potentially) using Subtree Swapping (unrooted)
3186 with extension probability.
3188 This move type picks two subtrees and swaps their position. Like the SPR and TBR,
3189 it is a superset of the NNI but there are some interesting differences. With the
3190 SPR and TBR, it is not possible to go between all five-tip trees in a single
3191 step. For instance, going from ((1,2),3,(4,5)) to ((1,5),3,(4,2)) requires two
3192 steps. The SS move can go between all pairs of five-tip trees in a single step.
3193 Some six-tip tree pairs will require two steps though.
3195 Unlike the published version of the move (Lakner et al, Syst Bio), this version
3196 does _not_ multiply all branch lengths between the subtrees.
3200 int i, numFree, topologyHasChanged, nCrownNodes, nRootNodes, directionLeft, directionUp,
3201 isVPriorExp, moveInRoot;
3202 MrBFlt m, x, tuning, maxV, minV, extensionProb, brlensExp=0.0;
3203 TreeNode *p, *q, *a, *b, *c, *d, *u, *v;
3207 (*lnPriorRatio) = (*lnProposalRatio) = 0.0;
3209 /* these parameters should be possible to set by user */
3210 extensionProb = mvp[0]; /* extension probability */
3211 tuning = mvp[1]; /* Larget & Simon's tuning parameter lambda */
3214 t = GetTree (param, chain, state[chain]);
3216 /* get model params */
3217 mp = &modelParams[param->relParts[0]];
3219 /* max and min brlen */
3220 if (param->subParams[0]->paramId == BRLENS_UNI)
3222 minV = mp->brlensUni[0] > BRLENS_MIN ? mp->brlensUni[0] : BRLENS_MIN;
3223 maxV = mp->brlensUni[1];
3226 else if (param->subParams[0]->paramId == BRLENS_GamDir)
3232 else if (param->subParams[0]->paramId == BRLENS_iGmDir)
3238 else if (param->subParams[0]->paramId == BRLENS_twoExp)
3248 brlensExp = mp->brlensExp;
3252 /* Dirichlet or twoExp prior */
3253 if (isVPriorExp > 1)
3254 (*lnPriorRatio) = -LogDirPrior(t, mp, isVPriorExp);
3256 topologyHasChanged = NO;
3258 /* unmark all tree */
3259 for (i=0; i<t->nNodes; i++)
3261 p = t->allDownPass[i];
3268 p = t->allDownPass[(int)(RandomNumber(seed) * t->nNodes)];
3269 } while (p->anc == NULL);
3271 /* set up pointers for nodes around the picked branch */
3275 /* check the possible move directions */
3277 if (v->left != NULL && v->left->isLocked == NO)
3279 if (v->right != NULL && v->right->isLocked == NO)
3281 if (u->anc != NULL && u->isLocked == NO)
3285 if (u->right != NULL && u->right->isLocked == NO)
3290 if (u->left != NULL && u->left->isLocked == NO)
3294 /* select one of them randomly */
3295 i = (int) (RandomNumber(seed) * numFree) + 1;
3298 directionLeft = directionUp = moveInRoot = NO;
3299 if (v->left != NULL && v->left->isLocked == NO)
3305 directionLeft = YES;
3310 if (v->right != NULL && v->right->isLocked == NO)
3321 if (u->anc != NULL && u->isLocked == NO)
3334 if (u->right != NULL && u->right->isLocked == NO)
3348 if (u->left != NULL && u->left->isLocked == NO)
3361 # if defined (DEBUG_ExtSS)
3362 printf ("Before:\n");
3363 ShowNodes (t->root, 2, NO);
3364 printf ("v: %d u: %d c: %d d: %d a: %d b: %d\n",v->index, u->index,
3365 c->index, d->index, a->index, b->index);
3366 printf ("directionUp = %d -- directionLeft = %d -- moveInRoot = %d\n", directionUp, directionLeft, moveInRoot);
3370 /* move around and potentially swap in root subtree */
3372 if (moveInRoot == YES)
3374 for (nRootNodes=0; nRootNodes==0 || RandomNumber(seed)<extensionProb; nRootNodes++)
3376 if (directionUp == YES)
3377 { /* going up tree */
3378 if (a->left == NULL || a->isLocked == YES)
3379 break; /* can't go further */
3380 topologyHasChanged = YES;
3382 if (RandomNumber(seed) < 0.5)
3388 { /* going down tree */
3389 if (a->anc == NULL || a->isLocked == YES)
3390 break; /* can't go further */
3391 topologyHasChanged = YES;
3394 if (RandomNumber(seed) < 0.5)
3396 directionUp = YES; /* switch direction */
3397 /* find sister of a */
3410 { /* continue down */
3416 /* swap the root subtrees */
3419 if (directionUp == YES)
3425 else if (b->right == a)
3434 /* rotate the nodes from b to u*/
3438 while (p->left->marked == YES || p->right->marked == YES)
3440 if (p->left->marked == YES)
3442 /* rotate p anticlockwise - prepare pointers for move left */
3443 p->anc = p->left; /* the root will be in the direction we are heading */
3449 /* rotate p clockwise - prepare pointers for move right */
3450 p->anc = p->right; /* the root will be in the direction we are heading */
3454 /* OK - let's move!; p->anc points in the right direction
3455 don't forget to move the branch lengths as well */
3458 q->length = p->length;
3461 /* rotations finished, take care of u */
3467 /* now swap the subtrees of u and b */
3482 /* move around and potentially swap in crown subtree */
3484 if (moveInRoot == NO)
3486 x = v->length; /* save v length in case there is a move */
3487 for (nCrownNodes=0; nCrownNodes==0 || RandomNumber(seed)<extensionProb; nCrownNodes++)
3489 if (c->left == NULL || c->isLocked == YES)
3490 break; /* can't go further */
3492 topologyHasChanged = YES;
3494 /* prepare d for move */
3496 d->length = c->length;
3499 if (d->isLocked == YES)
3503 c->lockID = d->lockID;
3507 /* go left or right with equal probability */
3508 if (RandomNumber(seed) < 0.5)
3510 /* rotate c anticlockwise - prepare pointers for move left */
3511 c->anc = c->left; /* the root will be in the direction we are heading */
3517 /* rotate c clockwise - prepare pointers for move right */
3518 c->anc = c->right; /* the root will be in the direction we are heading */
3522 /* OK - let's move!; c->anc points in the right direction */
3527 /* swap the crown subtrees */
3528 if (nCrownNodes > 0)
3538 if (directionLeft == YES)
3545 /* modify branch lengths */
3546 if (nCrownNodes > 0)
3551 else if (nRootNodes > 0)
3553 if (directionUp == YES)
3567 if (RandomNumber(seed) < 0.5)
3569 if (RandomNumber(seed) < 0.5)
3581 if (RandomNumber(seed) < 0.5)
3591 x = m * exp(tuning * (RandomNumber(seed) - 0.5));
3592 while (x < minV || x > maxV)
3595 x = minV * minV / x;
3597 x = maxV * maxV / x;
3602 /* update proposal and prior ratio based on length modification */
3603 (*lnProposalRatio) += log (x / m);
3604 if (isVPriorExp == YES)
3605 (*lnPriorRatio) += brlensExp * (m - x);
3608 if (q != NULL && q->anc != NULL)
3611 x = m * exp(tuning * (RandomNumber(seed) - 0.5));
3612 while (x < minV || x > maxV)
3615 x = minV * minV / x;
3617 x = maxV * maxV / x;
3622 /* update proposal and prior ratio based on length modification */
3623 (*lnProposalRatio) += log (x / m);
3624 if (isVPriorExp == YES)
3625 (*lnPriorRatio) += brlensExp * (m - x);
3628 /* set flags for update of cond likes from v and down to root */
3630 while (p->anc != NULL)
3636 if (topologyHasChanged == YES)
3638 /* set flags for update of cond likes from u and down to root */
3640 while (p->anc != NULL)
3647 /* get down pass sequence if tree topology has changed */
3648 if (topologyHasChanged == YES)
3653 /* Dirichlet or twoExp prior */
3654 if (isVPriorExp > 1)
3655 (*lnPriorRatio) += LogDirPrior(t, mp, isVPriorExp);
3657 # if defined (DEBUG_ExtSS)
3658 printf ("After:\n");
3659 ShowNodes (t->root, 2, NO);
3661 printf ("Proposal ratio: %f\n",exp(*lnProposalRatio));
3662 printf ("v: %d u: %d c: %d d: %d a: %d b: %d\n",v->index, u->index,
3663 c->index, d->index, a->index, b->index);
3664 printf ("No. nodes moved in root subtree: %d\n",nRootNodes);
3665 printf ("No. nodes moved in crown subtree: %d\n",nCrownNodes);
3666 printf ("Has topology changed? %d\n",topologyHasChanged);
3667 printf ("directionUp = %d -- directionLeft = %d\n", directionUp, directionLeft);
3675 int Move_ExtSSClock (Param *param, int chain, RandLong *seed, MrBFlt *lnPriorRatio, MrBFlt *lnProposalRatio, MrBFlt *mvp)
3677 /* Change branch lengths and topology (potentially) using SS-type move
3678 with extension probability (rather than window, attachment rate or similar). */
3680 /* This move picks a branch at random. It then moves away from this branch, one
3681 one node at a time, with a probability determined by the extensionProb parameter.
3682 The process stops when a tip is reached or when a move further upwards would break
3683 the clock assumption. When the extension process stops, the subtrees supported by
3684 the two chosen branches are swapped. Since 2010-11-01, the move is Metropolized for
3685 increased efficiency. */
3686 /* Note: this move is not compatible with fossilized birth-death model with ancestral fossils */
3688 int i, *nEvents, numFreeOld, numFreeNew;
3689 MrBFlt x, oldALength, oldCLength, extensionProb, igrvar, *igrRate,
3690 *tk02Rate, *brlens, nu, ran, cumulativeProb, forwardProb,
3692 TreeNode *p, *q, *a, *c;
3696 extensionProb = mvp[0]; /* extension probability */
3698 (*lnProposalRatio) = (*lnPriorRatio) = 0.0;
3701 t = GetTree (param, chain, state[chain]);
3703 /* get min and max brlens in relative time and subst units */
3706 /* calculate the number of free nodes */
3707 numFreeOld = t->nNodes-2;
3708 if (t->nConstraints > 1)
3711 for (i=0; i<t->nNodes-2; i++)
3713 p = t->allDownPass[i];
3714 if (p->anc->left == p)
3718 if (p->anc->isLocked == NO || q->isLocked == NO)
3725 p = t->allDownPass[(int)(RandomNumber(seed) * (t->nNodes -2))];
3726 if (p->anc->left == p)
3731 while ((p->anc->isLocked == YES && q->isLocked == YES) || p->length < TIME_MIN || q->length < TIME_MIN);
3732 /* choose subtree that can be swapped */
3734 /* set up pointers for nodes around the picked branch */
3736 if (p->anc->left == p)
3740 if (p->anc->anc->left == p->anc)
3741 c = p->anc->anc->right;
3743 c = p->anc->anc->left;
3745 /* record branch length */
3746 oldALength = a->length;
3748 /* reset scratch variables */
3749 for (i=0; i<t->nNodes-1; i++)
3751 p = t->allDownPass[i];
3756 /* calculate distance from picked node */
3759 while (p->isLocked == NO && p->anc != NULL)
3761 p->anc->x = p->x + 1;
3764 for (i=t->nIntNodes-2; i>=0; i--)
3766 p = t->intDownPass[i];
3767 if (p->x < 0 && p->anc->x >= 0 && p != a && p->isLocked == NO)
3768 p->x = p->anc->x + 1;
3771 /* mark the free nodes and calculate the total score */
3772 cumulativeProb = 0.0;
3773 for (i=0; i<t->nNodes-2; i++)
3775 p = t->allDownPass[i];
3776 if (p != a && p->anc->x > 0 && a->anc->nodeDepth > p->nodeDepth + minV && p->anc->nodeDepth > a->nodeDepth + minV)
3779 p->d = pow(0.5 * extensionProb, p->anc->x);
3780 cumulativeProb += p->d;
3786 /* find the target node */
3787 ran = RandomNumber(seed) * cumulativeProb;
3789 for (i=0; i<t->nNodes-2; i++)
3791 p = t->allDownPass[i];
3799 if (i == t->nNodes - 2)
3805 /* record first forward prob */
3806 forwardProb = p->d / cumulativeProb;
3808 /* record partner swap branch */
3810 oldCLength = c->length;
3812 /* calculate second forward prob */
3814 /* reset scratch variables */
3815 for (i=0; i<t->nNodes-1; i++)
3817 p = t->allDownPass[i];
3822 /* calculate distance from picked node */
3825 while (p->isLocked == NO && p->anc != NULL)
3827 p->anc->x = p->x + 1;
3830 for (i=t->nIntNodes-1; i>=0; i--)
3832 p = t->intDownPass[i];
3833 if (p->x < 0 && p != c && p->anc->x >= 0 && p->isLocked == NO)
3834 p->x = p->anc->x + 1;
3837 /* mark the free nodes and calculate the total score */
3838 cumulativeProb = 0.0;
3839 for (i=0; i<t->nNodes-2; i++)
3841 p = t->allDownPass[i];
3842 if (p != c && p->anc->x > 0 && c->anc->nodeDepth > p->nodeDepth + minV && p->anc->nodeDepth > c->nodeDepth + minV)
3845 p->d = pow(0.5 * extensionProb, p->anc->x);
3846 cumulativeProb += p->d;
3852 /* now we can calculate second forward prob */
3853 forwardProb += a->d / cumulativeProb;
3856 if (a->anc->left == a)
3860 if (c->anc->left == c)
3867 a->length = a->anc->nodeDepth - a->nodeDepth;
3868 c->length = c->anc->nodeDepth - c->nodeDepth;
3870 /* get down pass sequence */
3873 /* set tiprobs update flags */
3877 /* set flags for update of cond likes from a->anc and down to root */
3879 while (p->anc != NULL)
3885 /* set flags for update of cond likes from c->anc and down to root */
3887 while (p->anc != NULL)
3893 /* adjust prior ratio for clock tree */
3894 if (LogClockTreePriorRatio(param, chain, &x) == ERROR)
3896 (*lnPriorRatio) += x;
3898 /* calculate first backward prob */
3900 /* reset scratch variables */
3901 for (i=0; i<t->nNodes-1; i++)
3903 p = t->allDownPass[i];
3908 /* calculate distance from picked node */
3911 while (p->isLocked == NO && p->anc != NULL)
3913 p->anc->x = p->x + 1;
3916 for (i=t->nIntNodes-1; i>=0; i--)
3918 p = t->intDownPass[i];
3919 if (p->x < 0 && p != a && p->anc->x >= 0 && p->isLocked == NO)
3920 p->x = p->anc->x + 1;
3923 /* mark the free nodes and calculate the total score */
3924 cumulativeProb = 0.0;
3925 for (i=0; i<t->nNodes-2; i++)
3927 p = t->allDownPass[i];
3928 if (p != a && p->anc->x > 0 && a->anc->nodeDepth > p->nodeDepth + minV && p->anc->nodeDepth > a->nodeDepth + minV)
3931 p->d = pow(0.5 * extensionProb, p->anc->x);
3932 cumulativeProb += p->d;
3938 /* calculate first backward prob */
3939 backwardProb = c->d / cumulativeProb;
3941 /* calculate second backward prob */
3943 /* reset scratch variables */
3944 for (i=0; i<t->nNodes-1; i++)
3946 p = t->allDownPass[i];
3951 /* calculate distance from picked node */
3954 while (p->isLocked == NO && p->anc != NULL)
3956 p->anc->x = p->x + 1;
3959 for (i=t->nIntNodes-1; i>=0; i--)
3961 p = t->intDownPass[i];
3962 if (p->x < 0 && p != c && p->anc->x >= 0 && p->isLocked == NO)
3963 p->x = p->anc->x + 1;
3966 /* mark the free nodes and calculate the total score */
3967 cumulativeProb = 0.0;
3968 for (i=0; i<t->nNodes-2; i++)
3970 p = t->allDownPass[i];
3971 if (p != c && p->anc->x > 0 && c->anc->nodeDepth > p->nodeDepth + minV && p->anc->nodeDepth > c->nodeDepth + minV)
3974 p->d = pow(0.5 * extensionProb, p->anc->x);
3975 cumulativeProb += p->d;
3981 /* calculate second backward prob */
3982 backwardProb += a->d / cumulativeProb;
3984 /* now we can calculate proposal ratio */
3985 (*lnProposalRatio) += log (backwardProb / forwardProb);
3987 /* adjust for number of free nodes */
3988 numFreeNew = t->nNodes-2;
3989 if (t->nConstraints > 1)
3992 for (i=0; i<t->nNodes-2; i++)
3994 p = t->allDownPass[i];
3995 if (p->anc->left == p)
3999 if (p->anc->isLocked == NO || q->isLocked == NO)
4002 (*lnProposalRatio) += log(numFreeOld / numFreeNew);
4005 /* adjust proposal and prior ratio for relaxed clock models */
4006 for (i=0; i<param->subParams[0]->nSubParams; i++)
4008 subParm = param->subParams[0]->subParams[i];
4009 if (subParm->paramType == P_CPPEVENTS)
4011 nEvents = subParm->nEvents[2*chain+state[chain]];
4013 /* proposal ratio */
4014 (*lnProposalRatio) += nEvents[a->index] * log (a->length / oldALength);
4015 (*lnProposalRatio) += nEvents[c->index] * log (c->length / oldCLength);
4017 /* prior ratio: no effect because tree length is the same */
4019 /* update effective evolutionary lengths */
4020 if (UpdateCppEvolLengths (subParm, a, chain) == ERROR || UpdateCppEvolLengths (subParm, c, chain) == ERROR)
4026 else if ( subParm->paramType == P_TK02BRANCHRATES ||
4027 (subParm->paramType == P_MIXEDBRCHRATES && *GetParamIntVals(subParm, chain, state[chain]) == RCL_TK02))
4029 if (subParm->paramType == P_TK02BRANCHRATES)
4030 nu = *GetParamVals (modelSettings[subParm->relParts[0]].tk02var, chain, state[chain]);
4032 nu = *GetParamVals (modelSettings[subParm->relParts[0]].mixedvar, chain, state[chain]);
4033 tk02Rate = GetParamVals (subParm, chain, state[chain]);
4034 brlens = GetParamSubVals (subParm, chain, state[chain]);
4036 /* no proposal ratio effect */
4038 /* prior ratio and update of effective evolutionary lengths */
4039 (*lnPriorRatio) -= LnProbTK02LogNormal (tk02Rate[c->anc->index], nu*oldALength, tk02Rate[a->index]);
4040 (*lnPriorRatio) += LnProbTK02LogNormal (tk02Rate[a->anc->index], nu* a->length, tk02Rate[a->index]);
4041 (*lnPriorRatio) -= LnProbTK02LogNormal (tk02Rate[a->anc->index], nu*oldCLength, tk02Rate[c->index]);
4042 (*lnPriorRatio) += LnProbTK02LogNormal (tk02Rate[c->anc->index], nu* c->length, tk02Rate[c->index]);
4043 brlens[a->index] = a->length * (tk02Rate[a->index] + tk02Rate[a->anc->index])/2.0;
4044 brlens[c->index] = c->length * (tk02Rate[c->index] + tk02Rate[c->anc->index])/2.0;
4046 else if ( subParm->paramType == P_IGRBRANCHRATES ||
4047 (subParm->paramType == P_MIXEDBRCHRATES && *GetParamIntVals(subParm, chain, state[chain]) == RCL_IGR))
4049 /* get relevant parameters */
4050 if (subParm->paramType == P_IGRBRANCHRATES)
4051 igrvar = *GetParamVals (modelSettings[subParm->relParts[0]].igrvar, chain, state[chain]);
4053 igrvar = *GetParamVals (modelSettings[subParm->relParts[0]].mixedvar, chain, state[chain]);
4054 igrRate = GetParamVals (subParm, chain, state[chain]);
4055 brlens = GetParamSubVals (subParm, chain, state[chain]);
4057 /* prior ratio and update of effective evolutionary lengths */
4058 (*lnPriorRatio) -= LnProbGamma (oldALength/igrvar, oldALength/igrvar, igrRate[a->index]);
4059 (*lnPriorRatio) -= LnProbGamma (oldCLength/igrvar, oldCLength/igrvar, igrRate[c->index]);
4060 (*lnPriorRatio) += LnProbGamma (a->length /igrvar, a->length /igrvar, igrRate[a->index]);
4061 (*lnPriorRatio) += LnProbGamma (c->length /igrvar, c->length /igrvar, igrRate[c->index]);
4062 brlens[a->index] = igrRate[a->index] * a->length;
4063 brlens[c->index] = igrRate[c->index] * c->length;
4067 assert (*lnPriorRatio == *lnPriorRatio);
4073 int Move_ExtTBR (Param *param, int chain, RandLong *seed, MrBFlt *lnPriorRatio, MrBFlt *lnProposalRatio, MrBFlt *mvp)
4075 /* Change topology (and branch lengths) using TBR with extension probability. */
4077 /* This move picks an internal branch and two "danglies", modifies their lengths
4078 independently according to the method of Larget & Simon (1999: MBE); it then
4079 moves the danglies away from their original position one node at a time with
4080 a probability determined by the extensionProb parameter. When the danglies are moved,
4081 their direction is changed -- "reflection" necessary to enable the back move.
4083 This move type has been tested on all combinations of rooted and unrooted,
4084 constrained and unconstrained trees */
4086 int i, j, topologyHasChanged, nCrownNodes, nRootNodes, directionLeft, directionUp,
4087 isVPriorExp, alwaysMoveRoot, isCrownStartConstrained, isRootStartConstrained, isStopConstrained;
4088 MrBFlt m, x, y, tuning, maxV, minV, extensionProb, brlensExp=0.0;
4089 TreeNode *p, *a, *b, *c, *d, *u, *v;
4093 /* these parameters should be possible to set by user */
4094 extensionProb = mvp[0]; /* extension probability */
4095 tuning = mvp[1]; /* Larget & Simon's tuning parameter lambda */
4097 (*lnProposalRatio) = (*lnPriorRatio) = 0.0;
4100 t = GetTree (param, chain, state[chain]);
4102 /* get model params */
4103 mp = &modelParams[param->relParts[0]];
4105 /* max and min brlen */
4106 if (param->subParams[0]->paramId == BRLENS_UNI)
4108 minV = mp->brlensUni[0] > BRLENS_MIN ? mp->brlensUni[0] : BRLENS_MIN;
4109 maxV = mp->brlensUni[1] < BRLENS_MAX ? mp->brlensUni[1] : BRLENS_MAX;
4112 else if (param->subParams[0]->paramId == BRLENS_GamDir)
4118 else if (param->subParams[0]->paramId == BRLENS_iGmDir)
4124 else if (param->subParams[0]->paramId == BRLENS_twoExp)
4134 brlensExp = mp->brlensExp;
4138 /* Dirichlet or twoExp prior */
4139 if (isVPriorExp > 1)
4140 (*lnPriorRatio) = -LogDirPrior(t, mp, isVPriorExp);
4142 topologyHasChanged = NO;
4144 # if defined (DEBUG_ExtTBR)
4145 printf ("Before:\n");
4146 ShowNodes (t->root, 2, NO);
4150 /* pick an internal branch */
4152 p = t->intDownPass[(int)(RandomNumber(seed) * (t->nIntNodes-1))];
4153 if (p->anc->left == p)
4158 if (a->isLocked == YES || a->left == NULL)
4160 if (p->anc->isLocked == YES || p->anc->anc->anc == NULL)
4162 if (p->left->isLocked == YES || p->left->left == NULL)
4164 if (p->right->isLocked == YES || p->right->left == NULL)
4166 } while (i == 2 && j == 2);
4168 /* determine whether to move first step unconditionally in root or in crown */
4170 alwaysMoveRoot = YES;
4172 alwaysMoveRoot = NO;
4173 else if (RandomNumber(seed) < 0.5)
4174 alwaysMoveRoot = YES;
4176 alwaysMoveRoot = NO;
4178 /* determine any starting constraints */
4179 isCrownStartConstrained = isRootStartConstrained = NO;
4181 isRootStartConstrained = YES;
4183 isCrownStartConstrained = YES;
4185 /* set up pointers for nodes around the picked branch */
4186 /* cut the tree into crown, root and attachment part */
4187 /* change the relevant lengths in the attachment part */
4188 /* the lengths of a and v are automatically contained in the */
4189 /* "attachment" part but the length of c has to be stored in x */
4193 /* set up pointers for crown part */
4194 /* also determine direction of move in crown part */
4195 if (v->right->left == NULL || v->right->isLocked == YES)
4196 directionLeft = YES;
4197 else if (v->left->left == NULL || v->left->isLocked == YES)
4199 else if (RandomNumber(seed) < 0.5)
4200 directionLeft = YES;
4203 if (directionLeft == YES)
4214 /* cut and reconnect crown part */
4218 /* record c length and adjust with multiplier using reflection */
4220 x = c->length * exp(tuning * (RandomNumber(seed) - 0.5)); /* save the modified dangling branch for later use */
4221 while (x < minV || x > maxV)
4223 if (x < minV) x = minV * minV / x;
4224 if (x > maxV) x = maxV * maxV / x;
4227 /* calculate proposal and prior ratio based on length modification */
4228 (*lnProposalRatio) = log (x / m);
4229 if (isVPriorExp == YES)
4230 (*lnPriorRatio) = brlensExp * (m - x);
4232 /* record v length and adjust with multiplier using reflection*/
4234 v->length *= exp(tuning * (RandomNumber(seed) - 0.5));
4235 while (v->length < minV || v->length > maxV)
4237 if (v->length < minV)
4238 v->length = minV * minV / v->length;
4239 else if (v->length > maxV)
4240 v->length = maxV * maxV / v->length;
4244 /* adjust proposal and prior ratio based on length modification */
4245 (*lnProposalRatio) += log (v->length / m);
4246 if (isVPriorExp == YES)
4247 (*lnPriorRatio) += brlensExp * (m - v->length);
4249 /* mark nodes in root part */
4250 /* also determine direction of move in root part */
4256 if (u->anc->anc == NULL || u->isLocked == YES)
4258 else if (a->left == NULL || a->isLocked == YES)
4260 else if (RandomNumber(seed) < 0.5)
4264 if (directionUp == NO)
4266 /* switch a and b */
4272 if (directionUp == NO)
4288 a->length = u->length;
4293 /* adjust length of branch to be modified */
4294 /* if it is not the root branch of a rooted tree */
4295 if (t->isRooted == NO || u->anc->anc != NULL)
4298 u->length *= exp(tuning * (RandomNumber(seed) - 0.5));
4299 while (u->length < minV || u->length > maxV)
4301 if (u->length < minV)
4302 u->length = minV * minV / u->length;
4303 else if (u->length > maxV)
4304 u->length = maxV * maxV / u->length;
4307 /* adjust proposal and prior ratio based on length modification */
4308 (*lnProposalRatio) += log (u->length / m);
4309 if (isVPriorExp == YES)
4310 (*lnPriorRatio) += brlensExp * (m - u->length);
4314 /* move around in root subtree */
4315 for (nRootNodes=0; (alwaysMoveRoot == YES && nRootNodes == 0) || RandomNumber(seed) < extensionProb; nRootNodes++)
4317 if (directionUp == YES)
4318 { /* going up tree */
4319 if (a->left == NULL || a->isLocked == YES)
4320 break; /* can't go further */
4321 topologyHasChanged = YES;
4323 if (RandomNumber(seed) < 0.5)
4327 if (u->isLocked == YES)
4331 b->lockID = u->lockID;
4336 { /* going down tree */
4337 if (a->anc == NULL || u->isLocked == YES)
4338 break; /* can't go further */
4339 topologyHasChanged = YES;
4340 if (RandomNumber(seed)<0.5)
4342 directionUp = YES; /* switch direction */
4343 /* find sister of a */
4354 /* as long as we are moving upwards
4355 the cond likes to update will be
4356 flagged by the last pass from u to the root */
4359 { /* continue down */
4363 if (b->isLocked == YES)
4367 u->lockID = b->lockID;
4374 /* adjust proposal ratio for root move if unbalanced */
4375 isStopConstrained = NO;
4376 if (directionUp == YES && (a->left == NULL || a->isLocked == YES))
4377 isStopConstrained = YES;
4378 if (directionUp == NO && (a->anc == NULL || u->isLocked == YES))
4379 isStopConstrained = YES;
4382 if (isRootStartConstrained == YES && isStopConstrained == NO)
4383 (*lnProposalRatio) -= log (2.0 * (1.0 - extensionProb));
4384 else if (isRootStartConstrained == NO && isStopConstrained == YES)
4385 (*lnProposalRatio) += log (2.0 * (1.0 - extensionProb));
4388 /* move around in crown subtree */
4389 for (nCrownNodes=0; (alwaysMoveRoot == NO && nCrownNodes == 0) || RandomNumber(seed) < extensionProb; nCrownNodes++)
4391 if (c->left == NULL || c->isLocked == YES)
4392 break; /* can't go further */
4393 topologyHasChanged = YES;
4394 if (RandomNumber(seed) < 0.5)
4396 /* rotate c anticlockwise - prepare pointers for move left */
4397 c->anc = c->left; /* the root will be in the direction we are heading */
4403 /* rotate c clockwise - prepare pointers for move right */
4404 c->anc = c->right; /* the root will be in the direction we are heading */
4408 /* OK - let's move!; c->anc points in the right direction
4409 don't forget to move the branch lengths as well */
4412 d->length = c->length;
4417 /* adjust proposal ratio for crown move if unbalanced */
4418 isStopConstrained = NO;
4419 if (c->left == NULL || c->isLocked == YES)
4420 isStopConstrained = YES;
4421 if (nCrownNodes > 0)
4423 if (isCrownStartConstrained == YES && isStopConstrained == NO)
4424 (*lnProposalRatio) -= log (2.0 * (1.0 - extensionProb));
4425 else if (isCrownStartConstrained == NO && isStopConstrained == YES)
4426 (*lnProposalRatio) += log (2.0 * (1.0 - extensionProb));
4429 /* combine the subtrees */
4432 if (directionLeft == YES)
4443 /* the dangling branch is inserted in reverted position
4444 such that the back move will be possible
4445 if we have moved around in crown subtree
4446 otherwise it is left in its original position */
4447 if (nCrownNodes > 0)
4458 if (directionUp == YES)
4470 /* the dangling branch is contained in u->length
4471 and will automatically be inserted in the right position
4472 to enable the back move regardless of whether it was
4473 initially directed upwards or downwards
4474 BUT if we haven't moved in root subtree, it is advantageous (necessary
4475 for rooted trees) to avoid switching branches, which occurs otherwise
4476 if directionUp == YES */
4477 if (nRootNodes == 0)
4480 u->length = a->length;
4483 u->upDateTi = NO; /* u retains its old length */
4498 /* the modified branch contained in u->length will have
4499 to be moved to b->length to enable back move
4500 BUT if we haven't moved, it is better to keep it in place
4501 (necessary for rooted trees) */
4505 u->length = b->length;
4511 /* set flags for update of cond likes from v and down to root */
4513 while (p->anc != NULL)
4519 /* get down pass sequence if tree topology has changed */
4520 if (topologyHasChanged == YES)
4525 /* Dirichlet or twoExp prior */
4526 if (isVPriorExp > 1)
4527 (*lnPriorRatio) += LogDirPrior(t, mp, isVPriorExp);
4529 # if defined (DEBUG_ExtTBR)
4530 printf ("After:\n");
4531 ShowNodes (t->root, 2, NO);
4533 printf ("Proposal ratio: %f\n",(*lnProposalRatio));
4534 printf ("v: %d u: %d c: %d d: %d a: %d b: %d\n",v->index, u->index,
4535 c->index, d->index, a->index, b->index);
4536 printf ("No. nodes moved in root subtree: %d\n",nRootNodes);
4537 printf ("No. nodes moved in crown subtree: %d\n",nCrownNodes);
4538 printf ("Has topology changed? %d\n",topologyHasChanged);
4546 /*----------------------------------------------------------------
4548 | Move_GeneRate_Dir: Change gene rate multiplier using Dirichlet
4551 ----------------------------------------------------------------*/
4552 int Move_GeneRate_Dir (Param *param, int chain, RandLong *seed, MrBFlt *lnPriorRatio, MrBFlt *lnProposalRatio, MrBFlt *mvp)
4554 int i, nRates, isValid;
4555 MrBFlt alphaPi, *value, *subValue, numSites, *alphaDir, x, y, sum,
4556 rate_pot, *dirParm, *oldRate, *newRate;
4558 /* allocate memory */
4559 dirParm = (MrBFlt *) SafeCalloc (3*(numTopologies-1), sizeof(MrBFlt));
4560 oldRate = dirParm + numCurrentDivisions;
4561 newRate = dirParm + 2*numCurrentDivisions;
4563 /* get number of rates */
4564 nRates = param->nValues;
4566 /* get pointer to rates and number of uncompressed chars */
4567 value = GetParamVals(param, chain, state[chain]);
4568 subValue = GetParamSubVals(param, chain, state[chain]);
4570 /* get Dirichlet parameters */
4571 alphaDir = subValue + nRates;
4573 /* calculate old ratesum proportions */
4575 for (i=0; i<nRates; i++)
4576 numSites += subValue[i]; /* numSites should be equal to the number of sites */
4577 for (i=0; i<nRates; i++)
4578 oldRate[i] = value[i] * subValue[i] / numSites;
4580 /* get so called alphaPi parameter */
4581 alphaPi = mvp[0] * nRates;
4583 /* multiply old ratesum proportions with some large number to get new values close to the old ones */
4584 for (i=0; i<nRates; i++)
4585 dirParm[i] = oldRate[i] * alphaPi;
4587 /* get new values */
4588 DirichletRandomVariable (dirParm, newRate, nRates, seed);
4590 /* check new values. we rely on newRate be already normalized */
4596 for (i=0; i<nRates; i++)
4598 if (newRate[i] <= DIR_MIN)
4600 if (newRate[i] < DIR_MIN)
4602 newRate[i] = DIR_MIN;
4605 rate_pot -= DIR_MIN;
4610 if (isValid==1) break;
4611 for (i=0; i<nRates; i++)
4613 if (newRate[i]!=DIR_MIN)
4614 newRate[i] = rate_pot * newRate[i] / sum;
4618 /* calculate and copy new rate ratio values back */
4619 for (i=0; i<nRates; i++)
4620 value[i] = newRate[i] * (numSites / subValue[i]);
4622 /* get proposal ratio */
4624 for (i=0; i<nRates; i++)
4625 sum += newRate[i]*alphaPi;
4627 for (i=0; i<nRates; i++)
4628 x -= LnGamma(newRate[i]*alphaPi);
4629 for (i=0; i<nRates; i++)
4630 x += (newRate[i]*alphaPi-1.0)*log(oldRate[i]);
4632 for (i=0; i<nRates; i++)
4633 sum += oldRate[i]*alphaPi;
4635 for (i=0; i<nRates; i++)
4636 y -= LnGamma(oldRate[i]*alphaPi);
4637 for (i=0; i<nRates; i++)
4638 y += (oldRate[i]*alphaPi-1.0)*log(newRate[i]);
4639 (*lnProposalRatio) = x - y;
4641 /* get prior ratio */
4643 for (i=0; i<nRates; i++)
4644 x += (alphaDir[i]-1.0)*log(newRate[i]);
4645 for (i=0; i<nRates; i++)
4646 y += (alphaDir[i]-1.0)*log(oldRate[i]);
4647 (*lnPriorRatio) = x - y;
4649 /* Set update flags for all partitions that share the rate multiplier. Note that the conditional
4650 likelihood update flags have been set before we even call this function. */
4651 for (i=0; i<param->nRelParts; i++)
4652 TouchAllTreeNodes(&modelSettings[param->relParts[i]],chain);
4654 /* may need to hit update flag for cijks when you have a covarion model */
4655 for (i=0; i<param->nRelParts; i++)
4656 if (modelSettings[param->relParts[i]].nCijkParts > 1)
4657 modelSettings[param->relParts[i]].upDateCijk = YES;
4665 int Move_RateShape_M (Param *param, int chain, RandLong *seed, MrBFlt *lnPriorRatio, MrBFlt *lnProposalRatio, MrBFlt *mvp)
4667 /* change gamma/lnorm shape parameter using multiplier */
4669 int i, isAPriorExp, isValidA;
4670 MrBFlt oldA, newA, minA, maxA, alphaExp=0.0, ran, factor, tuning, *rates;
4673 /* get tuning parameter */
4676 /* get model params */
4677 mp = &modelParams[param->relParts[0]];
4679 /* get minimum and maximum values for alpha */
4680 if (param->paramId == SHAPE_UNI)
4682 minA = mp->shapeUni[0];
4683 maxA = mp->shapeUni[1];
4684 if (minA < MIN_SHAPE_PARAM)
4685 minA = MIN_SHAPE_PARAM;
4686 if (maxA > MAX_SHAPE_PARAM)
4687 maxA = MAX_SHAPE_PARAM;
4692 minA = MIN_SHAPE_PARAM;
4693 maxA = MAX_SHAPE_PARAM;
4694 alphaExp = mp->shapeExp;
4698 /* get old value of alpha */
4699 oldA = *GetParamVals(param, chain, state[chain]);
4701 /* change value for alpha */
4702 ran = RandomNumber(seed);
4703 factor = exp(tuning * (ran - 0.5));
4704 newA = oldA * factor;
4706 /* check validity */
4710 newA = minA * minA / newA;
4711 else if (newA > maxA)
4712 newA = maxA * maxA / newA;
4715 } while (isValidA == NO);
4717 /* get proposal ratio */
4718 *lnProposalRatio = log(newA / oldA);
4720 /* get prior ratio */
4721 if (isAPriorExp == NO)
4722 *lnPriorRatio = 0.0;
4724 *lnPriorRatio = -alphaExp * (newA - oldA);
4726 /* copy new alpha value back */
4727 *GetParamVals(param, chain, state[chain]) = newA;
4729 /* now, update rate category information */
4730 rates = GetParamSubVals (param, chain, state[chain]);
4732 if(!strcmp(mp->ratesModel, "LNorm"))
4734 if (DiscreteLogNormal (rates, newA, mp->numGammaCats, 1) == ERROR)
4737 else /* gamma rate */
4739 if (DiscreteGamma (rates, newA, newA, mp->numGammaCats, 0) == ERROR)
4743 /* Set update flags for all partitions that share this alpha. Note that the conditional
4744 likelihood update flags have been set before we even call this function. */
4745 for (i=0; i<param->nRelParts; i++)
4746 TouchAllTreeNodes(&modelSettings[param->relParts[i]],chain);
4748 /* We need to update flags when we have a covarion model */
4749 for (i=0; i<param->nRelParts; i++)
4750 if (modelSettings[param->relParts[i]].nCijkParts > 1)
4751 modelSettings[param->relParts[i]].upDateCijk = YES;
4757 int Move_Growth_M (Param *param, int chain, RandLong *seed, MrBFlt *lnPriorRatio, MrBFlt *lnProposalRatio, MrBFlt *mvp)
4759 MrBFlt oldG, newG, lambda, minG, maxG, ran, oldLnPrior, newLnPrior, curTheta;
4764 /* get tuning parameter */
4767 /* get model params */
4768 m = &modelSettings[param->relParts[0]];
4769 mp = &modelParams[param->relParts[0]];
4770 curTheta = (*GetParamVals(m->popSize, chain, state[chain])) * (*GetParamVals(m->clockRate, chain, state[chain]));
4771 if (!strcmp(mp->ploidy, "Diploid"))
4773 else if (!strcmp(mp->ploidy, "Zlinked"))
4778 /* get minimum and maximum values for growth */
4782 /* get old value of theta */
4783 newG = oldG = *GetParamVals(param, chain, state[chain]);
4787 /* change value of growth */
4788 ran = RandomNumber(seed);
4789 newG = oldG * exp (lambda * (ran - 0.5));
4791 /* check that new value is valid */
4792 while (newG < minG || newG > maxG)
4795 newG = minG * minG / newG;
4796 else if (newG > maxG)
4797 newG = maxG * maxG / newG;
4800 /* get proposal ratio */
4801 (*lnProposalRatio) = log (newG / oldG);
4803 /* get prior ratio */
4804 t = GetTree(modelSettings[param->relParts[0]].brlens,chain,state[chain]);
4805 if (LnCoalescencePriorPr (t, &oldLnPrior, curTheta, oldG) == ERROR)
4807 MrBayesPrint ("%s Problem calculating prior for coalescent process\n", spacer);
4810 if (LnCoalescencePriorPr (t, &newLnPrior, curTheta, newG) == ERROR)
4812 MrBayesPrint ("%s Problem calculating prior for coalescent process\n", spacer);
4815 (*lnPriorRatio) = newLnPrior - oldLnPrior + param->LnPriorRatio(newG, oldG, param->priorParams);
4817 /* copy new growth value back */
4818 *GetParamVals(param, chain, state[chain]) = newG;
4824 int Move_IgrBranchRate (Param *param, int chain, RandLong *seed, MrBFlt *lnPriorRatio, MrBFlt *lnProposalRatio, MrBFlt *mvp)
4826 /* move one IGR relaxed clock branch rate using multiplier */
4829 MrBFlt newRate, oldRate, tuning, minR, maxR, igrvar, *igrRate, *brlens;
4835 /* get the tuning parameter */
4838 /* get the model settings */
4839 m = &modelSettings[param->relParts[0]];
4841 /* get the IGR branch rate and effective branch length data */
4842 igrRate = GetParamVals (param, chain, state[chain]);
4843 brlens = GetParamSubVals (param, chain, state[chain]);
4846 t = GetTree (param, chain, state[chain]);
4848 /* get minimum and maximum rate */
4852 /* randomly pick a branch */
4854 i = (int) (RandomNumber(seed) * (t->nNodes -2));
4855 p = t->allDownPass[i];
4857 while (p->length < TIME_MIN); // not ancestral fossil
4859 /* find new rate using multiplier */
4860 oldRate = igrRate[p->index];
4861 newRate = oldRate * exp ((0.5 - RandomNumber(seed)) * tuning);
4863 /* reflect if necessary */
4864 while (newRate < minR || newRate > maxR)
4867 newRate = minR * minR / newRate;
4869 newRate = maxR * maxR / newRate;
4872 igrRate[p->index] = newRate;
4874 /* calculate prior ratio */
4875 igrvar = *GetParamVals (m->igrvar, chain, state[chain]);
4876 (*lnPriorRatio) = LnProbGamma (p->length/igrvar, p->length/igrvar, newRate)
4877 - LnProbGamma (p->length/igrvar, p->length/igrvar, oldRate);
4879 /* calculate proposal ratio */
4880 (*lnProposalRatio) = log (newRate / oldRate);
4882 /* update branch evolution lengths */
4883 brlens[p->index] = newRate * p->length;
4885 /* set update of transition probability */
4888 /* set update of cond likes down to root */
4890 while (q->anc != NULL)
4900 int Move_IgrBranchRate2 (Param *param, int chain, RandLong *seed, MrBFlt *lnPriorRatio, MrBFlt *lnProposalRatio, MrBFlt *mvp)
4902 /* move one IGR relaxed clock branch rate using sliding window */
4905 MrBFlt newRate, oldRate, window, minR, maxR, igrvar, *igrRate, *brlens;
4911 /* get the tuning parameter */
4914 /* get the model settings */
4915 m = &modelSettings[param->relParts[0]];
4917 /* get the IGR branch rate and effective branch length data */
4918 igrRate = GetParamVals (param, chain, state[chain]);
4919 brlens = GetParamSubVals (param, chain, state[chain]);
4922 t = GetTree (param, chain, state[chain]);
4924 /* get minimum and maximum rate */
4928 /* randomly pick a branch */
4930 i = (int) (RandomNumber(seed) * (t->nNodes -2));
4931 p = t->allDownPass[i];
4933 while (p->length < TIME_MIN); // not ancestral fossil
4935 /* find new rate using multiplier */
4936 oldRate = igrRate[p->index];
4937 newRate = oldRate + window * (RandomNumber(seed) - 0.5);
4939 /* reflect if necessary */
4940 while (newRate < minR || newRate > maxR)
4943 newRate = 2 * minR - newRate;
4945 newRate = 2 * maxR - newRate;
4948 igrRate[p->index] = newRate;
4950 /* calculate prior ratio */
4951 igrvar = *GetParamVals (m->igrvar, chain, state[chain]);
4952 (*lnPriorRatio) = LnProbGamma (p->length/igrvar, p->length/igrvar, newRate)
4953 - LnProbGamma (p->length/igrvar, p->length/igrvar, oldRate);
4955 /* calculate proposal ratio */
4956 (*lnProposalRatio) = 0.0;
4958 /* update branch evolution lengths */
4959 brlens[p->index] = newRate * p->length;
4961 /* set update of transition probability */
4964 /* set update of cond likes down to root */
4966 while (q->anc != NULL)
4976 int Move_IgrVar (Param *param, int chain, RandLong *seed, MrBFlt *lnPriorRatio, MrBFlt *lnProposalRatio, MrBFlt *mvp)
4978 /* move the variance of the IGR relaxed clock model using multiplier */
4981 MrBFlt oldIgrvar, newIgrvar, minIgrvar, maxIgrvar, tuning, *igrRate;
4986 /* get tuning parameter */
4989 /* get model params */
4990 mp = &modelParams[param->relParts[0]];
4992 /* get the min and max values */
4993 minIgrvar = IGRVAR_MIN;
4994 maxIgrvar = IGRVAR_MAX;
4995 if (!strcmp(mp->igrvarPr,"Uniform"))
4997 minIgrvar = (mp->igrvarUni[0] < IGRVAR_MIN) ? IGRVAR_MIN : mp->igrvarUni[0];
4998 maxIgrvar = (mp->igrvarUni[1] > IGRVAR_MAX) ? IGRVAR_MAX : mp->igrvarUni[1];
5001 /* get the igr variance */
5002 oldIgrvar = *GetParamVals (param, chain, state[chain]);
5005 newIgrvar = oldIgrvar * exp ((0.5 - RandomNumber(seed))*tuning);
5007 /* reflect if necessary */
5008 while (newIgrvar < minIgrvar || newIgrvar > maxIgrvar)
5010 if (newIgrvar < minIgrvar)
5011 newIgrvar = minIgrvar * minIgrvar / newIgrvar;
5012 if (newIgrvar > maxIgrvar)
5013 newIgrvar = maxIgrvar * maxIgrvar / newIgrvar;
5016 /* store new value */
5017 (*GetParamVals (param, chain, state[chain])) = newIgrvar;
5019 /* calculate prior ratio */
5020 for (i=0; i<param->nSubParams; i++)
5022 igrRate = GetParamVals (param->subParams[i], chain, state[chain]);
5023 t = GetTree (param->subParams[i], chain, state[chain]);
5024 for (j=0; j<t->nNodes-2; j++)
5026 p = t->allDownPass[j];
5027 if (p->length > 0.0) // not ancestral fossil
5029 (*lnPriorRatio) -= LnProbGamma (p->length/oldIgrvar, p->length/oldIgrvar, igrRate[p->index]);
5030 (*lnPriorRatio) += LnProbGamma (p->length/newIgrvar, p->length/newIgrvar, igrRate[p->index]);
5035 /* take prior on Igrvar into account */
5036 if (!strcmp(mp->igrvarPr,"Exponential"))
5037 (*lnPriorRatio) += mp->igrvarExp * (oldIgrvar - newIgrvar);
5039 /* calculate proposal ratio */
5040 (*lnProposalRatio) = log (newIgrvar / oldIgrvar);
5042 /* we do not need to update likelihoods */
5043 for (i=0; i<param->nRelParts; i++)
5045 modelSettings[param->relParts[i]].upDateCl = NO;
5052 int Move_MixedBranchRate (Param *param, int chain, RandLong *seed, MrBFlt *lnPriorRatio, MrBFlt *lnProposalRatio, MrBFlt *mvp)
5054 /* move one relaxed clock branch rate using multiplier */
5056 int i, *rclModel=NULL;
5057 MrBFlt newRate, oldRate, tuning, minR, maxR, mxvar, *mxRate, *brlens;
5058 TreeNode *p = NULL, *q;
5062 /* get the tuning parameter */
5065 /* get the model settings */
5066 m = &modelSettings[param->relParts[0]];
5068 /* get the branch rate and effective branch length data */
5069 mxRate = GetParamVals (param, chain, state[chain]);
5070 brlens = GetParamSubVals (param, chain, state[chain]);
5071 rclModel = GetParamIntVals(param, chain, state[chain]);
5074 t = GetTree (param, chain, state[chain]);
5076 /* get minimum and maximum rate */
5080 /* randomly pick a length */
5082 i = (int) (RandomNumber(seed) * (t->nNodes -2));
5083 p = t->allDownPass[i];
5085 while (p->length < TIME_MIN); // not ancestral fossil
5087 /* find new rate using multiplier */
5088 oldRate = mxRate[p->index];
5089 newRate = oldRate * exp ((0.5 - RandomNumber(seed)) * tuning);
5091 /* reflect if necessary */
5092 while (newRate < minR || newRate > maxR)
5095 newRate = minR * minR / newRate;
5097 newRate = maxR * maxR / newRate;
5100 mxRate[p->index] = newRate;
5102 /* calculate prior ratio */
5103 mxvar = *GetParamVals (m->mixedvar, chain, state[chain]);
5105 if (*rclModel == RCL_TK02)
5107 (*lnPriorRatio) += LnRatioTK02LogNormal (mxRate[p->anc->index], mxvar*p->length, newRate, oldRate);
5108 if (p->left != NULL)
5110 if (p->left->length > 0.0)
5112 (*lnPriorRatio) -= LnProbTK02LogNormal (oldRate, mxvar*p->left->length, mxRate[p->left->index ]);
5113 (*lnPriorRatio) += LnProbTK02LogNormal (newRate, mxvar*p->left->length, mxRate[p->left->index ]);
5115 if (p->right->length > 0.0)
5117 (*lnPriorRatio) -= LnProbTK02LogNormal (oldRate, mxvar*p->right->length, mxRate[p->right->index]);
5118 (*lnPriorRatio) += LnProbTK02LogNormal (newRate, mxvar*p->right->length, mxRate[p->right->index]);
5122 /* update branch evolution lengths */
5123 brlens[p->index] = p->length * (newRate + mxRate[p->anc->index]) / 2.0;
5124 if (p->left != NULL)
5126 brlens[p->left->index ] = p->left->length * (mxRate[p->left->index ] + newRate) / 2.0;
5127 brlens[p->right->index] = p->right->length * (mxRate[p->right->index] + newRate) / 2.0;
5130 /* set update of ti probs */
5132 if (p->left != NULL)
5134 p->left ->upDateTi = YES;
5135 p->right->upDateTi = YES;
5138 else if (*rclModel == RCL_IGR)
5140 (*lnPriorRatio) -= LnProbGamma (p->length/mxvar, p->length/mxvar, oldRate);
5141 (*lnPriorRatio) += LnProbGamma (p->length/mxvar, p->length/mxvar, newRate);
5143 brlens[p->index] = newRate * p->length;
5145 /* set update of transition probability */
5149 /* calculate proposal ratio */
5150 (*lnProposalRatio) = log (newRate / oldRate);
5152 /* set update of cond likes down to root */
5155 while (q->anc != NULL)
5165 int Move_MixedVar (Param *param, int chain, RandLong *seed, MrBFlt *lnPriorRatio, MrBFlt *lnProposalRatio, MrBFlt *mvp)
5167 /* move the variance of the mixed relaxed clock models using multiplier */
5169 int i, j, *rclModel=NULL;
5170 MrBFlt oldVar, newVar, minVar, maxVar, tuning, *igrRate, *tk02Rate;
5175 /* get tuning parameter */
5178 /* get model params */
5179 mp = &modelParams[param->relParts[0]];
5181 /* get the min and max values */
5182 minVar = MIXEDVAR_MIN;
5183 maxVar = MIXEDVAR_MAX;
5184 if (!strcmp(mp->mixedvarPr,"Uniform"))
5186 minVar = (mp->mixedvarUni[0] < MIXEDVAR_MIN) ? MIXEDVAR_MIN : mp->mixedvarUni[0];
5187 maxVar = (mp->mixedvarUni[1] > MIXEDVAR_MAX) ? MIXEDVAR_MAX : mp->mixedvarUni[1];
5190 /* get the variance */
5191 oldVar = *GetParamVals (param, chain, state[chain]);
5194 newVar = oldVar * exp ((0.5 - RandomNumber(seed))*tuning);
5196 /* reflect if necessary */
5197 while (newVar < minVar || newVar > maxVar)
5199 if (newVar < minVar)
5200 newVar = minVar * minVar / newVar;
5201 if (newVar > maxVar)
5202 newVar = maxVar * maxVar / newVar;
5205 /* store new value */
5206 (*GetParamVals (param, chain, state[chain])) = newVar;
5208 /* calculate prior ratio */
5209 for (i=0; i<param->nSubParams; i++)
5211 rclModel = GetParamIntVals (param->subParams[i], chain, state[chain]);
5213 if (*rclModel == RCL_TK02)
5215 tk02Rate = GetParamVals (param->subParams[i], chain, state[chain]);
5216 t = GetTree (param->subParams[i], chain, state[chain]);
5217 for (j=0; j<t->nNodes-2; j++)
5219 p = t->allDownPass[j];
5220 if (p->length > 0.0) // not ancestral fossil
5222 (*lnPriorRatio) -= LnProbTK02LogNormal (tk02Rate[p->anc->index], oldVar*p->length, tk02Rate[p->index]);
5223 (*lnPriorRatio) += LnProbTK02LogNormal (tk02Rate[p->anc->index], newVar*p->length, tk02Rate[p->index]);
5227 else if (*rclModel == RCL_IGR)
5229 igrRate = GetParamVals (param->subParams[i], chain, state[chain]);
5230 t = GetTree (param->subParams[i], chain, state[chain]);
5231 for (j=0; j<t->nNodes-2; j++)
5233 p = t->allDownPass[j];
5234 if (p->length > 0.0) // not ancestral fossil
5236 (*lnPriorRatio) -= LnProbGamma (p->length/oldVar, p->length/oldVar, igrRate[p->index]);
5237 (*lnPriorRatio) += LnProbGamma (p->length/newVar, p->length/newVar, igrRate[p->index]);
5243 /* take prior on Mixedvar into account */
5244 if (!strcmp(mp->mixedvarPr,"Exponential"))
5245 (*lnPriorRatio) += mp->mixedvarExp * (oldVar - newVar);
5247 /* calculate proposal ratio */
5248 (*lnProposalRatio) = log (newVar / oldVar);
5250 /* we do not need to update likelihoods */
5251 for (i=0; i<param->nRelParts; i++)
5253 modelSettings[param->relParts[i]].upDateCl = NO;
5260 int Move_RelaxedClockModel (Param *param, int chain, RandLong *seed, MrBFlt *lnPriorRatio, MrBFlt *lnProposalRatio, MrBFlt *mvp)
5262 /* rjMCMC move between TK02 (correlated lognormal) and IGR (independent gamma rate)
5266 MrBFlt *mxvar, *mxRate, *brlens, ratio, tk02var, igrvar;
5272 /* get model settings and parameters */
5273 m = &modelSettings[param->relParts[0]];
5274 mp = &modelParams[param->relParts[0]];
5275 mxvar = GetParamVals (m->mixedvar, chain, state[chain]);
5276 mxRate = GetParamVals (param, chain, state[chain]);
5277 brlens = GetParamSubVals (param, chain, state[chain]);
5278 t = GetTree (param, chain, state[chain]);
5280 /* get current value of model indicator */
5281 rclModel = GetParamIntVals(param, chain, state[chain]);
5283 /* get tk02/igr var ratio */
5286 (*lnPriorRatio) = (*lnProposalRatio) = 0.0;
5288 /* rjMCMC between models: Pr(TK02) = Pr(IGR) = 1/2 */
5289 /* the current model is TK02, move to IGR */
5290 if ((*rclModel) == RCL_TK02)
5292 /* move the var parameter */
5294 // ratio *= RandomNumber(seed);
5295 igrvar = tk02var / ratio;
5296 if (igrvar < IGRVAR_MIN || igrvar > IGRVAR_MAX)
5302 /* take prior on Mixedvar into account */
5303 if (!strcmp(mp->mixedvarPr,"Exponential"))
5304 (*lnPriorRatio) += mp->mixedvarExp * (tk02var - igrvar);
5306 /* match the rates and change the effective branch lengths */
5307 for (i = 0; i < t->nNodes -2; i++)
5309 p = t->allDownPass[i];
5310 if (p->length > 0.0) // not ancestral fossil
5312 (*lnPriorRatio) -= LnProbTK02LogNormal (mxRate[p->anc->index], tk02var*p->length, mxRate[p->index]);
5313 (*lnPriorRatio) += LnProbGamma (p->length/igrvar, p->length/igrvar, mxRate[p->index]);
5315 brlens[p->index] = mxRate[p->index] * p->length;
5319 /* In this move, we simply match the parameters in each model,
5320 the dimension is same, the Jacobian is 1/ratio. */
5321 (*lnProposalRatio) -= log(ratio);
5324 (*rclModel) = RCL_IGR;
5327 /* the current model is IGR, move to TK02 */
5330 /* move the var parameter */
5332 // ratio *= RandomNumber(seed);
5333 tk02var = igrvar * ratio;
5334 if (tk02var < TK02VAR_MIN || tk02var > TK02VAR_MAX)
5340 /* take prior on Mixedvar into account */
5341 if (!strcmp(mp->mixedvarPr,"Exponential"))
5342 (*lnPriorRatio) += mp->mixedvarExp * (igrvar - tk02var);
5344 /* match the rates and change the effective branch lengths */
5345 for (i = 0; i < t->nNodes -2; i++)
5347 p = t->allDownPass[i];
5348 if (p->length > 0.0) // not ancestral fossil
5350 (*lnPriorRatio) -= LnProbGamma (p->length/igrvar, p->length/igrvar, mxRate[p->index]);
5351 (*lnPriorRatio) += LnProbTK02LogNormal (mxRate[p->anc->index], tk02var*p->length, mxRate[p->index]);
5353 brlens[p->index] = p->length * (mxRate[p->index] + mxRate[p->anc->index]) /2.0;
5357 /* In this move, we simply match the parameters in each model,
5358 the dimension is same, the Jacobian is ratio. */
5359 (*lnProposalRatio) += log(ratio);
5362 (*rclModel) = RCL_TK02;
5366 /* since effective branch lengths are updated, we need to update likelihood calculation */
5367 TouchAllTreeNodes(m, chain);
5370 MrBayesPrint ("%lf", *seed); /* just because I am tired of seeing the unused parameter error msg */
5374 /*----------------------------------------------------------------
5376 | Move_Local: This proposal mechanism changes the topology and
5377 | branch lengths of an unrooted tree using the LOCAL mech-
5378 | anism described by Larget & Simon (1999):
5380 | Larget, B. L., and D. L. Simon. 1999. Markov chain
5381 | Monte Carlo algorithms for the Bayesian analysis
5382 | of phylogenetic trees. Molecular Biology and
5383 | Evolution 16:750-759.
5385 | Programmed by FR 2001-10-14 and partly rewritten 2002-02-21
5386 | for more elegance and the ability to deal with rooted trees.
5387 | Support for locked nodes added 2004-01-12 based on mb v2.01.
5388 | Calculation of the Hastings ratio corrected 2004-07-01.
5389 | Boundary conditions correctly taken care of 2004-09-29.
5390 | NB! An alternative to reflection is to skip moves, which might
5391 | be better for the LOCAL given the complexity of taking
5392 | the boundary conditions into account
5394 ----------------------------------------------------------------*/
5395 int Move_Local (Param *param, int chain, RandLong *seed, MrBFlt *lnPriorRatio, MrBFlt *lnProposalRatio, MrBFlt *mvp)
5397 int topologyHasChanged, isVPriorExp, directionUp, moveX;
5398 MrBFlt oldM, newM, x, y, newX, newY,
5399 tuning, minV, maxV, brlensExp=0.0;
5400 TreeNode *v, *u, *a, *b, *c, *d;
5404 tuning = mvp[0]; /* Larget & Simon's tuning parameter lambda */
5407 t = GetTree (param, chain, state[chain]);
5409 /* get model params */
5410 mp = &modelParams[param->relParts[0]];
5412 /* max and min brlen */
5413 if (param->subParams[0]->paramId == BRLENS_UNI)
5415 minV = mp->brlensUni[0] > BRLENS_MIN ? mp->brlensUni[0] : BRLENS_MIN;
5416 maxV = mp->brlensUni[1];
5419 else if (param->subParams[0]->paramId == BRLENS_GamDir)
5425 else if (param->subParams[0]->paramId == BRLENS_iGmDir)
5431 else if (param->subParams[0]->paramId == BRLENS_twoExp)
5441 brlensExp = mp->brlensExp;
5445 /* Dirichlet or twoExp prior */
5446 if (isVPriorExp > 1)
5447 (*lnPriorRatio) = -LogDirPrior(t, mp, isVPriorExp);
5449 topologyHasChanged = NO;
5451 # if defined (DEBUG_LOCAL)
5452 printf ("Before:\n");
5453 ShowNodes (t->root, 2, NO);
5457 /* pick an internal branch */
5460 v = t->intDownPass[(int)(RandomNumber(seed)*t->nIntNodes)];
5461 } while (v->anc->anc == NULL);
5463 /* set up pointers for crown part */
5464 if (RandomNumber(seed) < 0.5)
5475 /* set up pointers for root part */
5477 if (RandomNumber(seed) < 0.5 || (t->isRooted == YES && u->anc->anc == NULL))
5496 /* store old and new path length as well as old x and y */
5497 oldM = c->length + v->length;
5498 if (directionUp == YES)
5511 /* pick dangly to move */
5512 if (RandomNumber(seed) < 0.5)
5517 /* find new m value */
5518 newM = exp(tuning * (RandomNumber(seed) - 0.5)) * oldM;
5520 /* pick dangly to move and
5521 pick new attachment point */
5526 /* first update y */
5527 newY = y * (newM / oldM);
5529 /* find reinsertion point */
5530 if (v->isLocked == YES)
5532 newX = RandomNumber(seed) * newY;
5536 newX = RandomNumber(seed) * newM;
5543 /* first update x */
5544 newX = x * (newM / oldM);
5546 /* find reinsertion point */
5547 if (v->isLocked == YES)
5549 newY = RandomNumber(seed) * (newM - newX) + newX;
5553 newY = RandomNumber(seed) * newM;
5557 /* adjust proposal and prior ratio based on length modification */
5558 /* and insertion mechanism */
5559 (*lnProposalRatio) += 3.0 * log (newM / oldM);
5560 if (isVPriorExp == YES)
5561 (*lnPriorRatio) = brlensExp * (oldM - newM);
5563 /* make topology move if necessary and then set branch lengths */
5566 /* check if we need to abort */
5567 if (newY < minV || newY > maxV || (newX-newY) < minV || (newX-newY) > maxV || (newM-newX) < minV || (newM-newX) > maxV)
5573 /* topology has changed */
5574 topologyHasChanged = YES;
5575 /* detach v and d */
5576 /* this scheme differs from that used by Larget and Simon but is more
5577 convenient because it avoids tree rotations */
5583 if (directionUp == YES)
5585 /* place v and d below a */
5595 /* v->anc is already u */
5596 /* adjust lengths */
5597 c->length = newM - newX;
5598 v->length = newX - newY;
5603 /* place v and d below u */
5604 if (u->isLocked == YES)
5608 v->lockID = u->lockID;
5621 /* adjust lengths */
5622 c->length = newM - newX;
5623 u->length = newX - newY;
5629 /* check if we need to abort */
5630 if (newX < minV || newX > maxV || (newY-newX) < minV || (newY-newX) > maxV || (newM-newY) < minV || (newM-newY) > maxV)
5636 /* topology has not changed */
5637 c->length = newM - newY;
5638 v->length = newY - newX;
5639 if (directionUp == YES)
5645 /* set update of transition probs */
5648 if (directionUp == YES)
5653 /* set flags for update of cond likes from v and u down to root */
5656 if (directionUp == YES)
5660 while (v->anc != NULL)
5666 /* get downpass sequence if tree topology has changed */
5667 if (topologyHasChanged == YES)
5672 /* Dirichlet or twoExp prior */
5673 if (isVPriorExp > 1)
5674 (*lnPriorRatio) += LogDirPrior(t, mp, isVPriorExp);
5676 # if defined (DEBUG_LOCAL)
5677 printf ("After:\n");
5678 ShowNodes (t->root, 2, NO);
5680 printf ("Proposal ratio: %f\n",(*lnProposalRatio));
5681 printf ("v: %d u: %d c: %d d: %d a: %d b: %d\n",v->index, u->index,
5682 c->index, d->index, a->index, b->index);
5683 printf ("Has topology changed? %d\n",topologyHasChanged);
5691 /*----------------------------------------------------------------
5693 | Move_LocalClock: This proposal mechanism changes the topology and
5694 | branch lengths of a rooted tree using the LOCAL (clock) mech-
5695 | anism described by Larget & Simon (1999):
5697 | Larget, B. L., and D. L. Simon. 1999. Markov chain
5698 | Monte Carlo algorithms for the Bayesian analysis
5699 | of phylogenetic trees. Molecular Biology and
5700 | Evolution 16:750-759.
5702 | Programmed by JH 2002-07-07
5703 | Modified by FR 2004-05-22 to handle locked and dated trees
5704 | Modified by FR 2005-11-09 to take care of erroneous
5705 | Hastings ratio. The fix implemented here results in
5706 | a move that does not change tree height.
5708 ----------------------------------------------------------------*/
5709 int Move_LocalClock (Param *param, int chain, RandLong *seed, MrBFlt *lnPriorRatio, MrBFlt *lnProposalRatio, MrBFlt *mvp)
5711 int i, topologyHasChanged, vIsRoot, aSister, bSister, cSister, *nEvents;
5712 MrBFlt x, y, h1, h2, h3, h[3], tempD, ran, distUv, distCv,
5713 oldALength, oldBLength, oldCLength, oldULength, oldVLength, lambda, nu,
5714 *tk02Rate=NULL, *brlens, oldTreeLength, newTreeLength;
5715 // MrBFlt newDepth, oldDepth, factor, diff;
5716 TreeNode *u, *v, *w=NULL, *a, *b, *c, *deepestChild, *p;
5721 t = GetTree (param, chain, state[chain]);
5723 #if defined (DEBUG_LOCAL)
5724 /* check branch lengths and node depths */
5725 for (i=0; i<t->nNodes-2; i++) {
5726 p = t->allDownPass[i];
5727 /* the two checkings don't consider ancestral fossil (brl=0) in fossilized bd tree */
5728 if (p->length < minV) {
5729 printf ("%s ERROR when entering LocalClock: node %d has length %lf", spacer, p->index, p->length);
5732 if (p->nodeDepth >= p->anc->nodeDepth) {
5733 printf ("%s ERROR when entering LocalClock: node %d has depth %lf larger than its ancestor %d depth %lf", spacer, p->index, p->nodeDepth, p->anc->index, p->anc->nodeDepth);
5739 topologyHasChanged = NO;
5741 # if defined (DEBUG_LOCAL)
5742 printf ("Before:\n");
5743 ShowNodes (t->root, 2, YES);
5746 /* set up pointers */
5749 u = t->intDownPass[(int)(RandomNumber(seed)*(t->nIntNodes-1))];
5750 } while (u->anc->anc == NULL);
5759 if (v->anc->anc != NULL)
5764 oldALength = a->length;
5765 oldBLength = b->length;
5766 oldCLength = c->length;
5767 oldVLength = v->length;
5768 oldULength = u->length;
5769 oldTreeLength = TreeLength (param, chain);
5771 /* get distances from root of move (w or v) to nodes a, b, and c */
5773 h1 = h2 = h3 = v->length;
5776 h1 += u->length + a->length;
5777 h2 += u->length + b->length;
5783 /* we also need the distances between u <-> v and c <-> v to calculate the hastings' term */
5787 /* sort distances (simply make three comparisons and swap values, if necessary) */
5807 /* Find the child node (a, b, or c) that is closest to the root (i.e., has smallest h_i; i=1,2,3). This
5808 part deals with the possibility that some of the nodes are at the same nodeDepth and randomly assigns
5809 a node to be deepest in case of ties. */
5810 if (AreDoublesEqual (h1, h2, 0.00000001) == YES && AreDoublesEqual (h1, h3, 0.00000001) == YES && AreDoublesEqual (h2, h3, 0.00000001) == YES)
5812 ran = RandomNumber(seed);
5813 if (ran < 0.33333333)
5815 else if (ran > 0.66666666)
5820 else if (AreDoublesEqual (h1, h2, 0.00000001) == YES && AreDoublesEqual (h1, h3, 0.00000001) == NO && AreDoublesEqual (h2, h3, 0.00000001) == NO)
5824 ran = RandomNumber(seed);
5833 else if (AreDoublesEqual (h1, h2, 0.00000001) == NO && AreDoublesEqual (h1, h3, 0.00000001) == YES && AreDoublesEqual (h2, h3, 0.00000001) == NO)
5837 ran = RandomNumber(seed);
5846 else if (AreDoublesEqual (h1, h2, 0.00000001) == NO && AreDoublesEqual (h1, h3, 0.00000001) == NO && AreDoublesEqual (h2, h3, 0.00000001) == YES)
5850 ran = RandomNumber(seed);
5861 if (h1 < h2 && h1 < h3)
5863 else if (h2 < h1 && h2 < h3)
5870 /* for most of the branches, the proposal ratio is 0.0 so it makes sense to set this first */
5871 (*lnProposalRatio) = 0.0;
5872 if (u->isDated == YES && v->isDated == YES)
5874 /* this proposal is wasted, change nothing */
5886 else if (u->isDated == YES && v->isDated == NO)
5888 /* we can only change the position of v */
5891 /* the upper limit of v's height is determined either by u-length + v->length or by c->length + v->length (h[0]) */
5892 x = v->length + u->length;
5895 y = RandomNumber(seed) * x;
5899 /* v is root: we leave tree height unchanged so we cannot change anything */
5904 else if (u->isDated == NO && v->isDated == YES)
5906 /* we can only change the position of u */
5911 if (u->isLocked == YES)
5915 x = y + RandomNumber(seed) * (h2 - y);
5919 x = y + RandomNumber(seed) * (h1 - y);
5924 x = y + RandomNumber(seed) * (h[1] - y);
5927 /* if we reach the statements down here, neither u nor v is dated */
5928 else if (u->isLocked == YES)
5932 y = RandomNumber(seed) * h[0];
5933 x = y + RandomNumber(seed) * (h2 - y);
5937 y = RandomNumber(seed) * h[0];
5938 x = y + RandomNumber(seed) * (h1 - y);
5941 else if (vIsRoot == NO)
5943 /* this is the standard variant for nonroot v */
5944 x = RandomNumber(seed) * h[1];
5945 y = RandomNumber(seed) * h[0];
5949 /* this is the standard variant when v is the root */
5950 /*oldDepth = t->root->left->nodeDepth;
5951 factor = exp((RandomNumber(seed) - 0.5) * 2.0 * log(1.2));
5952 t->root->left->nodeDepth = newDepth = factor * h[0] - h[0] + oldDepth;
5953 adjust h[0], h[1], and h[2]
5954 diff = newDepth - oldDepth;
5958 /* set y to 0.0 and select new x */
5960 x = RandomNumber(seed) * h[1];
5961 /* Adjust proposal ratio. We deal with topology bias below. Note that this
5962 proposal ratio is very different from what appeared in Larget and Simon */
5963 /*(*lnProposalRatio) += (t->nIntNodes-1) * log(oldDepth / newDepth);*/
5964 /*(*lnProposalRatio) += 2.0 * log (factor);*/
5967 /* decide which topology we will construct (cSister is what we started with) */
5968 aSister = bSister = cSister = NO;
5969 /* if u is locked then we cannot change topology */
5970 if (u->isLocked == YES)
5972 else if (MaximumValue (x, y) < h[0])
5974 ran = RandomNumber(seed);
5975 if (ran < 0.33333333)
5977 else if (ran > 0.66666666)
5984 if (deepestChild == a)
5986 else if (deepestChild == b)
5992 /* adjust lengths of nodes u and v */
5993 u->length = MaximumValue (x, y) - MinimumValue (x, y);
5994 v->length = MinimumValue (x, y);
5996 v->nodeDepth = w->nodeDepth - v->length;
5997 u->nodeDepth = v->nodeDepth - u->length;
5999 /* adjust pointers and lengths of nodes a, b, and c */
6000 topologyHasChanged = NO;
6009 a->anc = b->anc = u;
6011 a->length = u->nodeDepth - a->nodeDepth;
6012 b->length = u->nodeDepth - b->nodeDepth;
6013 c->length = v->nodeDepth - c->nodeDepth;
6015 else if (bSister == YES)
6023 a->anc = c->anc = u;
6025 a->length = u->nodeDepth - a->nodeDepth;
6026 b->length = v->nodeDepth - b->nodeDepth;
6027 c->length = u->nodeDepth - c->nodeDepth;
6028 topologyHasChanged = YES;
6030 else if (aSister == YES)
6038 b->anc = c->anc = u;
6040 a->length = v->nodeDepth - a->nodeDepth;
6041 b->length = u->nodeDepth - b->nodeDepth;
6042 c->length = u->nodeDepth - c->nodeDepth;
6043 topologyHasChanged = YES;
6046 /* check that all branch lengths are good */
6047 if (a->length < 0.0 && b->length < 0.0 && c->length < 0.0 && u->length < 0.0 && v->length < 0.0)
6053 /* calculate the proposal ratio due to asymmetric topology changes */
6054 if (u->isLocked == NO)
6056 if (v->isDated == YES || vIsRoot == YES)
6058 if (distUv > distCv && MaximumValue (x, y) < h[0])
6059 (*lnProposalRatio) += log(3.0);
6060 else if (distUv < distCv && MaximumValue (x, y) > h[0])
6061 (*lnProposalRatio) += log(1.0 / 3.0);
6065 /* note that Larget and Simon did not have the correct Hastings ratio
6067 if (distUv > distCv && MaximumValue (x, y) < h[0])
6068 (*lnProposalRatio) += log(3.0 / 2.0);
6069 else if (distUv < distCv && MaximumValue (x, y) > h[0])
6070 (*lnProposalRatio) += log(2.0 / 3.0);
6074 /* set update of transition probs */
6075 a->upDateTi = b->upDateTi = c->upDateTi = u->upDateTi = YES;
6079 /* set flags for update of cond likes from u down to root */
6081 while (p->anc != NULL)
6087 /* get downpass sequence if tree topology has changed */
6088 if (topologyHasChanged == YES)
6091 /* adjust proposal and prior ratio for relaxed clock models */
6092 newTreeLength = TreeLength(param, chain);
6093 for (i=0; i<param->subParams[0]->nSubParams; i++)
6095 subParm = param->subParams[0]->subParams[i];
6096 if (subParm->paramType == P_CPPEVENTS)
6098 nEvents = subParm->nEvents[2*chain+state[chain]];
6099 lambda = *GetParamVals (modelSettings[subParm->relParts[0]].cppRate, chain, state[chain]);
6100 /* proposal ratio */
6101 (*lnProposalRatio) += nEvents[a->index] * log (a->length / oldALength);
6102 (*lnProposalRatio) += nEvents[b->index] * log (b->length / oldBLength);
6103 (*lnProposalRatio) += nEvents[c->index] * log (c->length / oldCLength);
6104 (*lnProposalRatio) += nEvents[u->index] * log (u->length / oldULength);
6105 if (v->anc->anc != NULL && v->isDated == NO)
6106 (*lnProposalRatio) += nEvents[v->index] * log (v->length / oldVLength);
6108 (*lnPriorRatio) += lambda * ((oldTreeLength - newTreeLength)/t->root->left->nodeDepth);
6109 /* update effective evolutionary lengths */
6110 if (v->anc->anc == NULL || v->isDated == YES)
6112 if (UpdateCppEvolLengths (subParm, v->left, chain) == ERROR ||
6113 UpdateCppEvolLengths (subParm, v->right, chain) == ERROR)
6121 if (UpdateCppEvolLengths (subParm, v, chain) == ERROR)
6128 else if ( subParm->paramType == P_TK02BRANCHRATES ||
6129 (subParm->paramType == P_MIXEDBRCHRATES && *GetParamIntVals(subParm, chain, state[chain]) == RCL_TK02))
6131 if (subParm->paramType == P_TK02BRANCHRATES)
6132 nu = *GetParamVals (modelSettings[subParm->relParts[0]].tk02var, chain, state[chain]);
6134 nu = *GetParamVals (modelSettings[subParm->relParts[0]].mixedvar, chain, state[chain]);
6135 nu /= t->root->left->nodeDepth; /* variance increase measured relative to tree height */
6136 tk02Rate = GetParamVals (subParm, chain, state[chain]);
6137 brlens = GetParamSubVals (subParm, chain, state[chain]);
6138 /* no proposal ratio effect */
6139 /* prior ratio and update of effective evolutionary lengths */
6140 (*lnPriorRatio) -= LnProbTK02LogNormal (tk02Rate[u->index], nu*oldALength, tk02Rate[a->index]);
6141 (*lnPriorRatio) += LnProbTK02LogNormal (tk02Rate[u->index], nu*u->left->length, tk02Rate[u->left->index]);
6142 (*lnPriorRatio) -= LnProbTK02LogNormal (tk02Rate[u->index], nu*oldBLength, tk02Rate[b->index]);
6143 (*lnPriorRatio) += LnProbTK02LogNormal (tk02Rate[u->index], nu*u->right->length, tk02Rate[u->right->index]);
6144 (*lnPriorRatio) -= LnProbTK02LogNormal (tk02Rate[v->index], nu*oldCLength, tk02Rate[c->index]);
6145 (*lnPriorRatio) -= LnProbTK02LogNormal (tk02Rate[v->index], nu*oldULength, tk02Rate[u->index]);
6146 (*lnPriorRatio) += LnProbTK02LogNormal (tk02Rate[v->index], nu*v->left->length, tk02Rate[v->left->index]);
6147 (*lnPriorRatio) += LnProbTK02LogNormal (tk02Rate[v->index], nu*v->right->length, tk02Rate[v->right->index]);
6148 brlens[a->index] = a->length * (tk02Rate[a->index] + tk02Rate[a->anc->index])/2.0;
6149 brlens[b->index] = a->length * (tk02Rate[a->index] + tk02Rate[a->anc->index])/2.0;
6150 brlens[c->index] = c->length * (tk02Rate[c->index] + tk02Rate[c->anc->index])/2.0;
6151 brlens[u->index] = u->length * (tk02Rate[u->index] + tk02Rate[u->anc->index])/2.0;
6152 if (v->anc->anc != NULL && v->isDated == NO)
6154 (*lnPriorRatio) -= LnProbTK02LogNormal (tk02Rate[w->index], nu*oldVLength, tk02Rate[v->index]);
6155 (*lnPriorRatio) += LnProbTK02LogNormal (tk02Rate[w->index], nu*v->length, tk02Rate[v->index]);
6156 brlens[v->index] = v->length * (tk02Rate[v->index] + tk02Rate[v->anc->index])/2.0;
6159 else if ( subParm->paramType == P_IGRBRANCHRATES ||
6160 (subParm->paramType == P_MIXEDBRCHRATES && *GetParamIntVals(subParm, chain, state[chain]) == RCL_IGR))
6166 /* calculate and adjust prior ratio for clock tree */
6167 if (LogClockTreePriorRatio (param, chain, &x) == ERROR)
6169 (*lnPriorRatio) += x;
6171 # if defined (DEBUG_LOCAL)
6172 printf ("After:\n");
6173 ShowNodes (t->root, 2, YES);
6174 printf ("Has topology changed? %d\n",topologyHasChanged);
6176 /* check branch lengths and node depths */
6177 for (i=0; i<t->nNodes-2; i++) {
6178 p = t->allDownPass[i];
6179 if (p->length < minV) {
6180 printf ("%s ERROR when leaving LocalClock: node %d has length %lf", spacer, p->index, p->length);
6183 if (p->nodeDepth >= p->anc->nodeDepth) {
6184 printf ("%s ERROR when leaving LocalClock: node %d has depth %lf larger than its ancestor %d depth %lf", spacer, p->index, p->nodeDepth, p->anc->index, p->anc->nodeDepth);
6191 MrBayesPrint ("%lf", *mvp); /* just because I am tired of seeing the unused parameter error msg */
6196 /*--------------------------------------------------------------------
6198 | Move_LSPR: Change topology using move based on likelihood scores
6200 |--------------------------------------------------------------------*/
6201 int Move_LSPR (Param *param, int chain, RandLong *seed, MrBFlt *lnPriorRatio, MrBFlt *lnProposalRatio, MrBFlt *mvp)
6203 /* Change branch lengths and topology (potentially) using SPR-type move
6204 biased according to likelihood scores. NOT work for constrained trees. */
6206 int i, j, n, division, topologyHasChanged, isVPriorExp, nNodes;
6207 BitsLong *pA, *pV, *pP;
6208 MrBFlt x, minV, maxV, brlensExp=0.0, minLength=0.0, curLength=0.0, length=0.0,
6209 cumulativeProb, warpFactor, sum, ran, tuning, increaseProb, decreaseProb,
6210 divFactor, nStates, rateMult, temp;
6211 CLFlt *nSitesOfPat, *globalNSitesOfPat, *tempCondLikes, **tempCondLikePtr;
6212 TreeNode *p, *q, *a, *b, *u, *v, *c=NULL, *d, *candidateNodes[20], *vLeft, *vRight;
6215 ModelInfo *m = NULL;
6217 temp = mvp[0]; /* tuning parameter determining how heavily to weight according to likelihood scores */
6218 var = mvp[1]; /* variance of lognormal for proposing branch lengths */
6219 increaseProb = decreaseProb = mvp[2]; /* reweighting probabilities */
6221 (*lnProposalRatio) = (*lnPriorRatio) = 0.0;
6223 /* get model params and model info */
6224 mp = &modelParams[param->relParts[0]];
6225 m = &modelSettings[param->relParts[0]];
6228 t = GetTree (param, chain, state[chain]);
6230 /* max and min brlen */
6231 if (param->subParams[0]->paramId == BRLENS_UNI)
6233 minV = mp->brlensUni[0] > BRLENS_MIN ? mp->brlensUni[0] : BRLENS_MIN;
6234 maxV = mp->brlensUni[1];
6241 brlensExp = mp->brlensExp;
6245 # if defined (DEBUG_MLSPR)
6246 printf ("Before:\n");
6247 ShowNodes (t->root, 2, YES);
6251 /* set topologyHasChanged to NO */
6252 topologyHasChanged = NO;
6254 /* reset node variables that will be used */
6255 for (i=0; i<t->nNodes; i++)
6257 p = t->allDownPass[i];
6263 /* pick a random branch */
6266 p = t->allDownPass[(int)(RandomNumber(seed)*(t->nNodes - 1))];
6267 } while (p->anc->anc == NULL || p->anc->isLocked == YES);
6269 /* set up pointers for nodes around the picked branch */
6280 /* store the branch lengths */
6281 aLength = a->length;
6282 uLength = u->length;
6283 vLength = v->length;
6284 if (v->left != NULL)
6286 vLeftLength = v->left->length;
6287 vRightLength = v->right->length;
6290 vLeftLength = vRightLength = 0.0;
6292 /* get the ML branch lengths */
6293 /* set initial branch lengths */
6294 /* cycle through using Newton Raphson and reoptimization a fixed number of iterations */
6299 /* get variance of lognormal */
6308 /* count distance to root */
6311 while (q->anc != NULL)
6317 /* allocate space for temporary cond likes and condlike pointers */
6318 tempCondLikes = (CLFlt *) SafeCalloc (nNodes*m->numChars*m->numModelStates, sizeof (CLFlt));
6319 tempCondLikePtr = (CLFlt **) SafeCalloc (nNodes, sizeof (CLFlt *));
6320 if (!tempCondLikes || !tempCondLikePtr)
6322 free (tempCondLikes);
6323 free (tempCondLikePtr);
6327 /* shift pointers over */
6330 while (q->anc != NULL)
6332 tempCondLikePtr[j] = m->condLike[chain][q->index][q->clSpace];
6333 m->condLike[chain][q->index][q->clSpace] = tempCondLikes + j*m->numChars*m->numModelStates;
6338 /* set length to 0.1 for now; test ML brlen later */
6339 aLength = a->length;
6341 uLength = u->length;
6343 vLength = v->length;
6346 /* get downpass cond likes for the root part */
6348 while (q->anc != NULL)
6349 m->condLikeDown (q, division, chain);
6351 /* get final pass cond likes for the root part */
6352 GetLikeFPRootPath (a);
6354 /* get downpass parsimony states for the crown part */
6355 GetParsDP (t, v, chain);
6357 /* mark all nodes in the root part of the tree */
6358 t->root->left->marked = YES;
6359 for (i=t->nNodes-3; i>=0; i--)
6361 p = t->allDownPass[i];
6362 if (p->anc->marked == YES && p != u)
6366 /* find number of site patterns and modify randomly */
6367 globalNSitesOfPat = numSitesOfPat + (chainId[chain] % chainParams.numChains) * numCompressedChars + m->compCharStart;
6368 nSitesOfPat = (CLFlt *) SafeCalloc (numCompressedChars, sizeof(CLFlt));
6371 MrBayesPrint ("%s Problem allocating nSitesOfPat in Move_LSPR\n", spacer);
6372 free (tempCondLikes);
6373 free (tempCondLikePtr);
6376 for (i=0; i<numCompressedChars; i++)
6378 nSitesOfPat[i] = globalNSitesOfPat[i];
6379 for (j=0; j<globalNSitesOfPat[i]; j++)
6381 ran = RandomNumber(seed);
6382 if (ran < decreaseProb)
6384 else if (ran > 1.0 - increaseProb)
6389 /* cycle through the possibilities and record ln likelihood of each in p->d */
6391 for (i=0; i<t->nNodes; i++)
6393 p = t->allDownPass[i];
6394 if (p->marked == NO)
6396 /* find the parsimony length */
6398 for (n=0; n<t->nRelParts; n++)
6400 division = t->relParts[n];
6402 /* Find model settings */
6403 m = &modelSettings[division];
6405 nStates = m->numModelStates;
6406 if (m->dataType == STANDARD)
6408 rateMult = GetRate(division, chain);
6410 divFactor = warpFactor + log(nStates-1) - log (3) - log(rateMult);
6412 /* find downpass parsimony sets for the node and its environment */
6413 pP = parsPtr[chain][p->index] + m->parsMatrixStart + Bit(division, p->clSpace) * parsMatrixRowSize;
6414 pA = parsPtr[chain][p->anc->index] + m->parsMatrixStart + Bit(division, p->anc->clSpace) * parsMatrixRowSize;
6415 pV = parsPtr[chain][v->index] + m->parsMatrixStart + Bit(division, v->clSpace) * parsMatrixRowSize;
6418 for (j=0; j<m->numChars; j++)
6420 x = (pP[j] | pA[j]) & pV[j];
6422 length += nSitesOfPat[j];
6424 p->d += divFactor * length;
6428 else if (p->d < minLength)
6434 /* find the sum given the warp factor */
6436 for (i=0; i<t->nNodes; i++)
6438 p = t->allDownPass[i];
6439 if (p->marked == YES)
6441 p->d = exp (minLength - p->d);
6446 /* generate a random uniform */
6447 ran = RandomNumber(seed);
6449 /* select the appropriate reattachment point */
6450 cumulativeProb = 0.0;
6451 for (i=0; i<t->nNodes; i++)
6453 p = t->allDownPass[i];
6454 if (p->marked == YES)
6457 cumulativeProb += p->d / sum;
6458 if (cumulativeProb > ran)
6462 if (c->marked != YES)
6464 printf ("Could not select node\n");
6468 /* calculate the proposal ratio */
6470 (*lnProposalRatio) = 0.0;
6472 (*lnProposalRatio) = c->d - curLength;
6487 /* reassign branch lengths */
6490 topologyHasChanged = YES;
6491 if (RandomNumber(seed) < 0.5)
6494 u->length = a->length;
6497 if (RandomNumber(seed) < 0.5)
6500 c->length = u->length;
6503 /* hit c length with multiplier (a and u dealt with below) */
6504 x = c->length * exp(tuning * (RandomNumber(seed) - 0.5));
6505 while (x < minV || x > maxV)
6508 x = minV * minV / x;
6510 x = maxV * maxV / x;
6512 /* calculate proposal and prior ratio based on length modification */
6513 (*lnProposalRatio) += log (x / c->length);
6514 if (isVPriorExp == YES)
6515 (*lnPriorRatio) += brlensExp * (c->length - x);
6519 /* hit a length with multiplier (even if no topology change was made) */
6520 x = a->length * exp(tuning * (RandomNumber(seed) - 0.5));
6521 while (x < minV || x > maxV)
6524 x = minV * minV / x;
6526 x = maxV * maxV / x;
6529 /* calculate proposal and prior ratio based on length modification */
6530 (*lnProposalRatio) += log (x / a->length);
6531 if (isVPriorExp == YES)
6532 (*lnPriorRatio) += brlensExp * (a->length - x);
6535 /* hit u length with multiplier (even if no topology change was made) */
6536 x = u->length * exp(tuning * (RandomNumber(seed) - 0.5));
6537 while (x < minV || x > maxV)
6540 x = minV * minV / x;
6542 x = maxV * maxV / x;
6545 /* calculate proposal and prior ratio based on length modification */
6546 (*lnProposalRatio) += log (x / u->length);
6547 if (isVPriorExp == YES)
6548 (*lnPriorRatio) += brlensExp * (u->length - x);
6551 /* set tiprobs update flags */
6554 c->upDateTi = YES; /* could be same as a but that does not matter */
6556 /* set flags for update of cond likes from u and down to root */
6558 while (p->anc != NULL)
6564 /* set flags for update of cond likes from b and down to root */
6566 while (p->anc != NULL && p->upDateCl == NO)
6572 /* get down pass sequence if tree topology has changed */
6573 if (topologyHasChanged == YES)
6580 # if defined (DEBUG_MLSPR)
6581 printf ("After:\n");
6582 ShowNodes (t->root, 2, YES);
6584 printf ("Proposal ratio: %f\n",(*lnProposalRatio));
6585 printf ("v: %d u: %d a: %d b: %d\n",v->index, u->index, a->index, b->index);
6586 printf ("No. nodes moved in root subtree: %d\n",nRootNodes);
6587 printf ("Has topology changed? %d\n",topologyHasChanged);
6595 /*--------------------------------------------------------------------
6597 | Move_LSPR1: Change topology using move based on likelihood scores
6599 |--------------------------------------------------------------------*/
6600 int Move_LSPR1 (Param *param, int chain, RandLong *seed, MrBFlt *lnPriorRatio, MrBFlt *lnProposalRatio, MrBFlt *mvp)
6602 /* Change branch lengths and topology (potentially) using SPR-type move
6603 biased according to likelihood scores. NOT work for constrained trees. */
6605 int i, j, n, division, topologyHasChanged, isVPriorExp, nNodes;
6606 BitsLong *pA, *pV, *pP;
6607 MrBFlt x, minV, maxV, brlensExp=0.0, minLength=0.0, curLength=0.0, length=0.0,
6608 cumulativeProb, warpFactor, sum, ran, tuning, increaseProb, decreaseProb,
6609 divFactor, nStates, rateMult, temp;
6610 CLFlt *nSitesOfPat, *globalNSitesOfPat, *tempCondLikes, **tempCondLikePtr;
6611 TreeNode *p, *q, *a, *b, *u, *v, *c=NULL, *d, *candidateNodes[20], *vLeft, *vRight;
6614 ModelInfo *m = NULL;
6616 temp = mvp[0]; /* tuning parameter determining how heavily to weight according to likelihood scores */
6617 var = mvp[1]; /* variance of lognormal for proposing branch lengths */
6618 increaseProb = decreaseProb = mvp[2]; /* reweighting probabilities */
6620 (*lnProposalRatio) = (*lnPriorRatio) = 0.0;
6622 /* get model params and model info */
6623 mp = &modelParams[param->relParts[0]];
6624 m = &modelSettings[param->relParts[0]];
6627 t = GetTree (param, chain, state[chain]);
6629 /* max and min brlen */
6630 if (param->subParams[0]->paramId == BRLENS_UNI)
6632 minV = mp->brlensUni[0] > BRLENS_MIN ? mp->brlensUni[0] : BRLENS_MIN;
6633 maxV = mp->brlensUni[1];
6640 brlensExp = mp->brlensExp;
6644 # if defined (DEBUG_MLSPR)
6645 printf ("Before:\n");
6646 ShowNodes (t->root, 2, YES);
6650 /* set topologyHasChanged to NO */
6651 topologyHasChanged = NO;
6653 /* reset node variables that will be used */
6654 for (i=0; i<t->nNodes; i++)
6656 p = t->allDownPass[i];
6662 /* pick a random branch */
6665 p = t->allDownPass[(int)(RandomNumber(seed)*(t->nNodes - 1))];
6666 } while (p->anc->anc == NULL || p->anc->isLocked == YES);
6668 /* set up pointers for nodes around the picked branch */
6679 /* store the branch lengths */
6680 aLength = a->length;
6681 uLength = u->length;
6682 vLength = v->length;
6683 if (v->left != NULL)
6685 vLeftLength = v->left->length;
6686 vRightLength = v->right->length;
6689 vLeftLength = vRightLength = 0.0;
6691 /* save DP cond likes */
6692 /* count distance to root */
6695 while (q->anc != NULL)
6701 /* allocate space for temporary cond likes and condlike pointers */
6702 tempCondLikes = (CLFlt *) SafeCalloc (nNodes*m->numChars*m->numModelStates, sizeof (CLFlt));
6703 tempCondLikePtr = (CLFlt **) SafeCalloc (nNodes, sizeof (CLFlt *));
6704 if (!tempCondLikes || !tempCondLikePtr)
6706 free (tempCondLikes);
6707 free (tempCondLikePtr);
6711 /* shift pointers over */
6714 while (q->anc != NULL)
6716 tempCondLikePtr[j] = m->condLike[chain][q->index][q->clSpace];
6717 m->condLike[chain][q->index][q->clSpace] = tempCondLikes + j*m->numChars*m->numModelStates;
6722 /* get cond like uppass up to b */
6723 getLikeUPRootPath (t, b);
6725 /* get ML branch lengths */
6726 NRBrlenOptimizer (t, v, 5, 3);
6728 /* cycle through using Newton Raphson and reoptimization a fixed number of iterations */
6729 for (i=0; i<numIterations; i++)
6731 if (v->left != NULL)
6733 getBaseLikeUpLeft (t, v); /* store instead of DP */
6734 NewtonRaphsonBrlen (t, v->left, chain);
6735 getBaseLikeUpRight (t, v);
6736 GetNewtonRaphsonBrlen (t, v->right, chain);
6737 m->CondLikeDown (v);
6740 getBaseLikeUpLeft (t, u);
6742 getBaseLikeUpRight (t, u);
6743 NewtonRaphsonBrlen (t, v, chain);
6745 getBaseLikeUpRight (t, u);
6747 getBaseLikeUpLeft (t, u);
6748 NewtonRaphsonBrlen (t, a->length, chain);
6749 m->CondLikeDown (t, u);
6751 getBaseLikeUpLeft (t, b);
6753 getBaseLikeUpRight (t, b);
6754 NewtonRaphsonBrlen (t, u->length, chain);
6759 /* get variance of lognormal for forward move */
6760 f = log (a->length) - log (aLength);
6762 f = log (v->length) - log (vLength);
6764 f = log (u->length) - log (uLength);
6766 if (v->left != NULL)
6768 f = log (v->left->length) - log (vLeftLength);
6770 f = log (v->right->length) - log (vRightLength);
6784 /* get ML branch length for a */
6785 NewtonRaphsonBrlen (t, a, chain, 3);
6787 /* propose new length for a */
6788 f = PointNormal(RandomNumber(seed));
6790 f += log (a->length);
6793 /* get downpass cond likes for the root part */
6795 while (q->anc != NULL)
6796 m->condLikeDown (q, division, chain);
6798 /* get uppass cond likes for the root part */
6799 GetLikeUp (t, t->root->left);
6801 /* cycle through the possibilities and record ln likelihood of each in p->d */
6802 for (i=0; i<t->nNodes; i++)
6804 p = t->allDownPass[i];
6805 if (p->marked == NO)
6807 /* attach crown tree here */
6808 pLength = p->length;
6809 /* find ml branch lengths */
6810 NewtonRaphsonBrlens5 (t, v, chain, 5, 3);
6812 m->CondLikeDown (t, v);
6813 m->CondLikeRoot (t, u);
6814 m->Likelihood (t, u, &lnL);
6818 else if (p->d > maxLnL)
6822 /* detach crown tree */
6823 /* restore p->length */
6824 p->length = pLength;
6827 /* find the sum given the warp factor */
6829 for (i=0; i<t->nNodes; i++)
6831 p = t->allDownPass[i];
6832 if (p->marked == YES)
6834 p->d = exp (maxLnL - p->d);
6839 /* generate a random uniform */
6840 ran = RandomNumber(seed);
6842 /* select the appropriate reattachment point */
6843 cumulativeProb = 0.0;
6844 for (i=0; i<t->nNodes; i++)
6846 p = t->allDownPass[i];
6847 if (p->marked == YES)
6850 cumulativeProb += p->d / sum;
6851 if (cumulativeProb > ran)
6855 if (c->marked != YES)
6857 printf ("Could not select node\n");
6861 /* calculate the proposal ratio based on biased reattachment */
6863 (*lnProposalRatio) = 0.0;
6865 (*lnProposalRatio) = (maxLnL - log(c->d)) - curLnL;
6869 topologyHasChanged = YES;
6882 /* optimize branch lengths */
6883 NewtonRaphsonBrlens5 (t, v, chain, 5, 5);
6885 /* calculate variance of lognormal for back move */
6886 f = log (a->length) - log (aLength);
6888 f = log (v->length) - log (vLength);
6890 f = log (u->length) - log (uLength);
6892 if (v->left != NULL)
6894 f = log (v->left->length) - log (vLeftLength);
6896 f = log (v->right->length) - log (vRightLength);
6903 /* draw new branch lengths */
6904 c->length = fvar * PointNormal(RandomNumber(seed)) + log(c->length);
6905 u->length = fvar * PointNormal(RandomNumber(seed)) + log(u->length);
6906 v->length = fvar * PointNormal(RandomNumber(seed)) + log(v->length);
6907 if (v->left != NULL)
6909 v->left->length = fvar * PointNormal(RandomNumber(seed)) + log(v->left->length);
6910 v->right->length = fvar * PointNormal(RandomNumber(seed)) + log(v->right->length);
6913 /* calculate proposal ratio for branch lengths */
6915 /* set tiprobs update flags */
6918 c->upDateTi = YES; /* could be same as a but that does not matter */
6920 if (v->left != NULL)
6922 v->left->upDateTi = YES;
6923 v->right->upDateTi = YES;
6926 /* set flags for update of cond likes from v and down to root */
6928 while (q->anc != NULL)
6934 /* set flags for update of cond likes from b and down to root */
6936 while (q->anc != NULL && q->upDateCl == NO)
6942 /* get down pass sequence if tree topology has changed */
6943 if (topologyHasChanged == YES)
6948 /* restore old conditional likelihoods */
6950 # if defined (DEBUG_MLSPR)
6951 printf ("After:\n");
6952 ShowNodes (t->root, 2, YES);
6954 printf ("Proposal ratio: %f\n",(*lnProposalRatio));
6955 printf ("v: %d u: %d a: %d b: %d\n",v->index, u->index, a->index, b->index);
6956 printf ("No. nodes moved in root subtree: %d\n",nRootNodes);
6957 printf ("Has topology changed? %d\n",topologyHasChanged);
6966 /* Move_NNI, change topology using NNI move */
6967 int Move_NNI (Param *param, int chain, RandLong *seed, MrBFlt *lnPriorRatio, MrBFlt *lnProposalRatio, MrBFlt *mvp)
6969 TreeNode *p, *u, *v, *a, *b, *c;
6972 (*lnProposalRatio) = (*lnPriorRatio) = 0.0;
6975 t = GetTree (param, chain, state[chain]);
6977 /* pick an internal branch */
6979 p = t->intDownPass[(int)(RandomNumber(seed) * t->nIntNodes)];
6981 while (p->anc->anc == NULL || p->isLocked == YES);
6983 /* set up area of rearrangement */
6993 /* change topology */
6994 if (RandomNumber(seed) < 0.5)
7002 a->anc = c->anc = u;
7013 b->anc = c->anc = u;
7017 /* set update of cond likes */
7018 while (p->anc != NULL)
7027 MrBayesPrint ("%lf", *mvp); /* just because I am tired of seeing the unused parameter error msg */
7031 int Move_NNIClock (Param *param, int chain, RandLong *seed, MrBFlt *lnPriorRatio, MrBFlt *lnProposalRatio, MrBFlt *mvp)
7033 /* Change clock tree using NNI move */
7035 int i, *nEvents, numFreeOld, numFreeNew;
7036 MrBFlt x, *tk02Rate=NULL, *brlens, *igrRate=NULL, igrvar=0.0, nu=0.0, oldALength, oldCLength;
7037 TreeNode *p, *q, *a, *c, *u, *v;
7041 /* no tuning parameter */
7043 /* make absolutely sure the proposal ratio and prior ratio are reset */
7044 (*lnProposalRatio) = (*lnPriorRatio) = 0.0;
7047 t = GetTree (param, chain, state[chain]);
7049 # if defined (DEBUG_NNIClock)
7050 printf ("Before:\n");
7051 ShowNodes (t->root, 2, YES);
7055 /* count number of free interior branches */
7057 for (i=0; i<t->nIntNodes-1; i++)
7059 p = t->intDownPass[i];
7060 if (p->anc->left == p)
7064 if (p->isLocked == NO && p->nodeDepth >= q->nodeDepth + BRLENS_MIN)
7068 /* In extremely constrained trees, it might be impossible to change the tree before nodes have changed in position */
7069 if (numFreeOld == 0)
7075 /* pick an interior branch, around which it is possible to make an NNI */
7077 p = t->intDownPass[(int)(RandomNumber(seed) * (t->nIntNodes-1))];
7078 if (p->anc->left == p)
7083 while (p->isLocked == YES || p->nodeDepth < q->nodeDepth + BRLENS_MIN);
7085 /* set up pointers for nodes around the picked branch */
7086 /* consider ancestral fossil (brl=0) in fossilized bd tree */
7087 if (p->left->length < TIME_MIN)
7089 else if (p->right->length < TIME_MIN)
7091 else if (RandomNumber(seed) < 0.5)
7102 /* record branch lengths */
7103 oldALength = a->length;
7104 oldCLength = c->length;
7106 /* make topology change */
7118 /* adjust branch lengths */
7119 a->length = u->nodeDepth - a->nodeDepth;
7120 c->length = v->nodeDepth - c->nodeDepth;
7121 assert (a->length > BRLENS_MIN);
7122 assert (c->length > BRLENS_MIN);
7124 /* no reassignment of CPP events or branch rates necessary */
7126 /* set tiprobs update flags */
7130 /* set flags for update of cond likes from v and down to root */
7132 while (p->anc != NULL)
7138 /* get down pass sequence */
7141 /* count number of free interior branches after the move */
7143 for (i=0; i<t->nIntNodes-1; i++)
7145 p = t->intDownPass[i];
7146 if (p->anc->left == p)
7150 if (p->isLocked == NO && p->nodeDepth >= q->nodeDepth + BRLENS_MIN)
7154 /* get proposal ratio if number of free branches has changed */
7155 if (numFreeNew != numFreeOld)
7156 (*lnProposalRatio) = log((MrBFlt)numFreeOld / (MrBFlt)numFreeNew);
7158 /* calculate and adjust prior ratio for clock trees */
7159 if (LogClockTreePriorRatio(param, chain, &x) == ERROR)
7161 (*lnPriorRatio) += x;
7163 /* adjust proposal and prior ratio for relaxed clock models */
7164 for (i=0; i<param->subParams[0]->nSubParams; i++)
7166 subParm = param->subParams[0]->subParams[i];
7167 if (subParm->paramType == P_CPPEVENTS)
7169 nEvents = subParm->nEvents[2*chain+state[chain]];
7170 /* proposal ratio */
7171 (*lnProposalRatio) += nEvents[a->index] * log (a->length / oldALength);
7172 (*lnProposalRatio) += nEvents[c->index] * log (c->length / oldCLength);
7173 /* prior ratio: no effect because tree length is the same */
7174 /* update effective evolutionary lengths */
7175 if (UpdateCppEvolLengths (subParm, a, chain) == ERROR || UpdateCppEvolLengths (subParm, c, chain) == ERROR)
7181 else if ( subParm->paramType == P_TK02BRANCHRATES ||
7182 (subParm->paramType == P_MIXEDBRCHRATES && *GetParamIntVals(subParm, chain, state[chain]) == RCL_TK02))
7184 if (subParm->paramType == P_TK02BRANCHRATES)
7185 nu = *GetParamVals (modelSettings[subParm->relParts[0]].tk02var, chain, state[chain]);
7187 nu = *GetParamVals (modelSettings[subParm->relParts[0]].mixedvar, chain, state[chain]);
7188 tk02Rate = GetParamVals (subParm, chain, state[chain]);
7189 /* prior ratio and update of effective evolutionary lengths */
7190 (*lnPriorRatio) -= LnProbTK02LogNormal (tk02Rate[v->index], nu*oldALength, tk02Rate[a->index]);
7191 (*lnPriorRatio) += LnProbTK02LogNormal (tk02Rate[u->index], nu* a->length, tk02Rate[a->index]);
7192 (*lnPriorRatio) -= LnProbTK02LogNormal (tk02Rate[u->index], nu*oldCLength, tk02Rate[c->index]);
7193 (*lnPriorRatio) += LnProbTK02LogNormal (tk02Rate[v->index], nu* c->length, tk02Rate[c->index]);
7194 brlens = GetParamSubVals (subParm, chain, state[chain]);
7195 brlens[a->index] = a->length * (tk02Rate[a->index] + tk02Rate[a->anc->index])/2.0;
7196 brlens[c->index] = c->length * (tk02Rate[c->index] + tk02Rate[c->anc->index])/2.0;
7198 else if ( subParm->paramType == P_IGRBRANCHRATES ||
7199 (subParm->paramType == P_MIXEDBRCHRATES && *GetParamIntVals(subParm, chain, state[chain]) == RCL_IGR))
7201 if (subParm->paramType == P_IGRBRANCHRATES)
7202 igrvar = *GetParamVals (modelSettings[subParm->relParts[0]].igrvar, chain, state[chain]);
7204 igrvar = *GetParamVals (modelSettings[subParm->relParts[0]].mixedvar, chain, state[chain]);
7205 igrRate = GetParamVals (subParm, chain, state[chain]);
7206 /* prior ratio and update of effective evolutionary lengths */
7207 (*lnPriorRatio) -= LnProbGamma (oldALength/igrvar, oldALength/igrvar, igrRate[a->index]);
7208 (*lnPriorRatio) -= LnProbGamma (oldCLength/igrvar, oldCLength/igrvar, igrRate[c->index]);
7209 (*lnPriorRatio) += LnProbGamma (a->length /igrvar, a->length /igrvar, igrRate[a->index]);
7210 (*lnPriorRatio) += LnProbGamma (c->length /igrvar, c->length /igrvar, igrRate[c->index]);
7211 brlens = GetParamSubVals (subParm, chain, state[chain]);
7212 brlens[a->index] = igrRate[a->index] * a->length;
7213 brlens[c->index] = igrRate[c->index] * c->length;
7217 # if defined (DEBUG_NNIClock)
7218 printf ("After:\n");
7219 ShowNodes (t->root, 2, YES);
7221 printf ("Proposal ratio: %f\n",(*lnProposalRatio));
7222 printf ("v: %d u: %d a: %d b: %d\n",v->index, u->index, a->index, b->index);
7223 printf ("Has topology changed? %d\n",topologyHasChanged);
7228 MrBayesPrint ("%lf", *mvp); /* just because I am tired of seeing the unused parameter error msg */
7232 /* Move_NNI_Hetero, change topology with unlinked brlens using NNI */
7233 int Move_NNI_Hetero (Param *param, int chain, RandLong *seed, MrBFlt *lnPriorRatio, MrBFlt *lnProposalRatio, MrBFlt *mvp)
7235 int i, brIndex, moveType;
7236 TreeNode *p, *u, *v, *a, *b, *c;
7239 (*lnPriorRatio) = (*lnProposalRatio) = 0.0;
7241 /* get first tree */
7242 t = GetTree (param, chain, state[chain]);
7244 /* pick an internal branch */
7247 brIndex = (int) (RandomNumber(seed) * t->nIntNodes);
7248 p = t->intDownPass[brIndex];
7249 } while (p->anc->anc == NULL || p->isLocked == YES);
7251 /* decide on how to change the tree */
7252 if (RandomNumber(seed) < 0.5)
7257 /* cycle through trees */
7258 for (i=0; i<param->nSubParams; i++)
7261 t = GetTree (param->subParams[i], chain, state[chain]);
7264 p = t->intDownPass[brIndex];
7266 /* set up area of rearrangement */
7276 /* change topology */
7285 a->anc = c->anc = u;
7288 else if (moveType == 1)
7296 b->anc = c->anc = u;
7300 /* set update of ti probs */
7307 /* set update of conditional likelihoods */
7308 while (p->anc != NULL)
7314 /* reset tree downpass sequences */
7320 MrBayesPrint ("%lf", *mvp); /* just because I am tired of seeing the unused parameter error msg */
7324 /*-----------------------------------------------------------------------------------
7326 | Move_NodeSlider: move the position of one node without changing topology
7328 -------------------------------------------------------------------------------------*/
7329 int Move_NodeSlider (Param *param, int chain, RandLong *seed, MrBFlt *lnPriorRatio, MrBFlt *lnProposalRatio, MrBFlt *mvp)
7331 MrBFlt tuning, maxV, minV, oldM, newM, brlensPrExp=0.0, newMin, newMax, oldMin, oldMax;
7337 tuning = mvp[0]; /* Larget & Simon's tuning parameter lambda */
7339 mp = &modelParams[param->relParts[0]];
7341 /* max and min brlen (time) */
7342 if (param->paramId == BRLENS_UNI)
7344 minV = mp->brlensUni[0] > BRLENS_MIN ? mp->brlensUni[0] : BRLENS_MIN;
7345 maxV = mp->brlensUni[1];
7348 else if (param->paramId == BRLENS_GamDir)
7354 else if (param->paramId == BRLENS_iGmDir)
7360 else if (param->paramId == BRLENS_twoExp)
7370 brlensPrExp = mp->brlensExp;
7375 t = GetTree (param, chain, state[chain]);
7377 /* Dirichlet or twoExp prior */
7378 if (isVPriorExp > 1)
7379 (*lnPriorRatio) = -LogDirPrior(t, mp, isVPriorExp);
7381 /* pick an interior branch */
7383 p = t->intDownPass[(int)(RandomNumber(seed) * t->nIntNodes)];
7385 while (p->anc == NULL || (t->isRooted == YES && p->anc->anc == NULL));
7387 /* pick one descendant branch */
7388 if (RandomNumber(seed) < 0.5)
7393 /* determine new length */
7394 oldM = (q->length + p->length);
7395 newM = oldM * exp(tuning * (RandomNumber(seed) - 0.5));
7396 while (newM < 2.0 * minV || newM > 2.0 * maxV)
7398 if (newM < 2.0 * minV)
7399 newM = 4.0 * minV * minV / newM;
7400 else if (newM > 2.0 * maxV)
7401 newM = 4.0 * maxV * maxV / newM;
7404 /* determine new lengths of p and q */
7405 newMin = minV > newM - maxV ? minV : newM - maxV;
7406 newMax = maxV < newM - minV ? maxV : newM - minV;
7407 oldMin = minV > oldM - maxV ? minV : oldM - maxV;
7408 oldMax = maxV < oldM - minV ? maxV : oldM - minV;
7410 q->length = newMin + RandomNumber(seed) * (newMax - newMin);
7411 p->length = newM - q->length;
7413 /* the proposal ratio for two sliding windows */
7414 (*lnProposalRatio) = log ((newMax - newMin) / (oldMax - oldMin));
7416 /* The proposal ratio for shrinking/expanding two variables (x1 = p->length, x2 = q->length)
7417 by the same factor c = newM/oldM is c^2. This can be derived by variable transformation:
7418 y1 = x1, y2 = x2/x1. The proposal ratio in the transformed variables is c, the Jacobian is y1,
7419 so the proposal ratio in the original variables is c*c = c^2.
7420 (see Move_TreeLen for m variables and Yang 2006 CME P171 S5.4.4 for details) */
7421 (*lnProposalRatio) += 2.0 * log(newM / oldM);
7423 /* set flags for update of transition probabilities at p and q */
7428 /* set flags for update of cond likes from p->anc and down to root */
7429 while (p->anc->anc != NULL)
7435 /* update prior if exponential prior on branch lengths */
7436 if (param->paramId == BRLENS_EXP)
7437 (*lnPriorRatio) = brlensPrExp * (oldM - newM);
7438 /* Dirichlet or twoExp prior */
7439 else if (isVPriorExp > 1)
7440 (*lnPriorRatio) += LogDirPrior(t, mp, isVPriorExp);
7447 /*-----------------------------------------------------------------------------------
7449 | Move_NodeSliderClock: Move the position of one (root or nonroot) node in clock tree.
7450 | In calibrated trees, we need to move also calibrated terminal nodes.
7452 -------------------------------------------------------------------------------------*/
7453 int Move_NodeSliderClock (Param *param, int chain, RandLong *seed, MrBFlt *lnPriorRatio, MrBFlt *lnProposalRatio, MrBFlt *mvp)
7456 MrBFlt window, minDepth, maxDepth, oldDepth, newDepth, minL, minR,
7457 oldLeftLength=0.0, oldRightLength=0.0, oldPLength=0.0, x, clockRate,
7458 lambda=0.0, nu=0.0, igrvar=0.0, *brlens=NULL, *tk02Rate=NULL, *igrRate=NULL;
7464 Calibration *calibrationPtr;
7466 window = mvp[0]; /* window size */
7468 m = &modelSettings[param->relParts[0]];
7469 mp = &modelParams[param->relParts[0]];
7472 t = GetTree (param, chain, state[chain]);
7474 /* get clock rate */
7475 if (m->clockRate == NULL)
7478 clockRate = *GetParamVals (m->clockRate, chain, state[chain]);
7480 /* check whether or not we can change root */
7481 if ((t->root->left->isDated == YES && t->root->left->calibration->prior == fixed) ||
7482 ((!strcmp(mp->clockPr, "Uniform") || !strcmp(mp->clockPr, "Fossilization")) && mp->treeAgePr.prior == fixed))
7487 /* pick a node that can be changed in position */
7489 p = t->allDownPass[(int)(RandomNumber(seed) * i)];
7491 while ((p->left == NULL && p->isDated == NO) ||
7492 (p->left == NULL && p->length < TIME_MIN) ||
7493 (p->isDated == YES && p->calibration->prior == fixed));
7495 #if defined (DEBUG_CSLIDER)
7496 printf ("Before node slider (clock):\n");
7497 printf ("Picked branch with index %d and depth %f\n", p->index, p->nodeDepth);
7498 if (p->anc->anc == NULL)
7499 printf ("Old clock rate: %f\n", clockRate);
7500 ShowNodes (t->root, 0, t->isRooted);
7504 /* store values needed later for prior calculation (relaxed clocks) */
7505 oldPLength = p->length;
7506 if (p->left != NULL)
7508 oldLeftLength = p->left->length;
7509 oldRightLength = p->right->length;
7512 oldLeftLength = oldRightLength = 0.0;
7514 /* determine lower and upper bound */
7515 if (p->left == NULL)
7517 else // internal node
7519 if (p->left->length > 0.0)
7520 minL = p->left->nodeDepth + BRLENS_MIN;
7521 else // ancestral fossil
7523 assert (p->left->calibration != NULL);
7524 minL = p->left->calibration->min * clockRate;
7526 if (p->right->length > 0.0)
7527 minR = p->right->nodeDepth + BRLENS_MIN;
7528 else // ancestral fossil
7530 assert (p->right->calibration != NULL);
7531 minR = p->right->calibration->min * clockRate;
7539 if (p->anc->anc == NULL)
7540 maxDepth = TREEHEIGHT_MAX;
7542 maxDepth = p->anc->nodeDepth - BRLENS_MIN;
7543 if (p->left != NULL && p->left->length < TIME_MIN)
7545 assert (p->left->calibration != NULL);
7546 if (maxDepth > p->left->calibration->max * clockRate)
7547 maxDepth = p->left->calibration->max * clockRate;
7549 if (p->right != NULL && p->right->length < TIME_MIN)
7551 assert (p->right->calibration != NULL);
7552 if (maxDepth > p->right->calibration->max * clockRate)
7553 maxDepth = p->right->calibration->max * clockRate;
7556 if (p->isDated == YES)
7557 calibrationPtr = p->calibration;
7558 else if (p->anc->anc == NULL && (!strcmp(mp->clockPr,"Uniform") || !strcmp(mp->clockPr, "Fossilization")))
7559 calibrationPtr = &mp->treeAgePr;
7561 calibrationPtr = NULL;
7562 if (calibrationPtr != NULL)
7564 if (maxDepth > calibrationPtr->max * clockRate)
7565 maxDepth = calibrationPtr->max * clockRate;
7566 if (minDepth < calibrationPtr->min * clockRate)
7567 minDepth = calibrationPtr->min * clockRate;
7570 /* abort if impossible */
7571 if (minDepth > maxDepth -BRLENS_MIN)
7577 /* save some reflection time */
7578 if (maxDepth-minDepth < window)
7580 window = maxDepth-minDepth;
7583 /* pick the new node depth */
7584 oldDepth = p->nodeDepth;
7585 newDepth = oldDepth + (RandomNumber(seed) - 0.5) * window;
7587 /* reflect the new node depth */
7588 while (newDepth < minDepth || newDepth > maxDepth)
7590 if (newDepth < minDepth)
7591 newDepth = 2.0 * minDepth - newDepth;
7592 if (newDepth > maxDepth)
7593 newDepth = 2.0 * maxDepth - newDepth;
7596 p->nodeDepth = newDepth;
7598 /* determine new branch lengths around p and set update of transition probabilities */
7599 if (p->left != NULL)
7601 if (p->left->length > 0.0) {
7602 p->left->length = p->nodeDepth - p->left->nodeDepth;
7603 p->left->upDateTi = YES;
7606 p->left->nodeDepth = p->nodeDepth;
7607 if (p->right->length > 0.0) {
7608 p->right->length = p->nodeDepth - p->right->nodeDepth;
7609 p->right->upDateTi = YES;
7612 p->right->nodeDepth = p->nodeDepth;
7614 if (p->anc->anc != NULL)
7616 p->length = p->anc->nodeDepth - p->nodeDepth;
7620 /* adjust age of p if dated */
7621 if (calibrationPtr != NULL)
7622 p->age = p->nodeDepth / clockRate;
7623 if ((p->left != NULL) && (p->left->length < TIME_MIN))
7624 p->left->age = p->nodeDepth / clockRate;
7625 if ((p->right != NULL) && (p->right->length < TIME_MIN))
7626 p->right->age = p->nodeDepth / clockRate;
7628 /* set flags for update of cond likes from p and down to root */
7630 while (q->anc != NULL)
7636 /* calculate proposal ratio */
7637 (*lnProposalRatio) = (*lnPriorRatio) = 0.0;
7639 /* calculate and adjust prior ratio for clock tree */
7640 if (LogClockTreePriorRatio (param, chain, &x) == ERROR)
7642 (*lnPriorRatio) += x;
7644 /* adjust proposal and prior ratio for relaxed clock models */
7645 for (i=0; i<param->nSubParams; i++)
7647 subParm = param->subParams[i];
7648 if (subParm->paramType == P_CPPEVENTS)
7650 nEvents = subParm->nEvents[2*chain+state[chain]];
7651 lambda = *GetParamVals (modelSettings[subParm->relParts[0]].cppRate, chain, state[chain]);
7652 /* proposal ratio */
7653 if (p->left != NULL)
7655 (*lnProposalRatio) += nEvents[p->left->index ] * log (p->left->length / oldLeftLength);
7656 (*lnProposalRatio) += nEvents[p->right->index] * log (p->right->length / oldRightLength);
7658 if (p->anc->anc != NULL)
7659 (*lnProposalRatio) += nEvents[p->index] * log (p->length / oldPLength);
7662 if (p->anc->anc == NULL) // two branches changed in same direction
7663 (*lnPriorRatio) += lambda * (2.0 * (oldDepth - newDepth));
7664 else if (p->left != NULL) // two branches changed in one direction, one branch in the other direction
7665 (*lnPriorRatio) += lambda * (oldDepth - newDepth);
7666 else /* if (p->left == NULL) */ // one branch changed
7667 (*lnPriorRatio) += lambda * (newDepth - oldDepth);
7669 /* update effective evolutionary lengths */
7670 if (UpdateCppEvolLengths (subParm, p, chain) == ERROR)
7676 else if ( subParm->paramType == P_TK02BRANCHRATES ||
7677 (subParm->paramType == P_MIXEDBRCHRATES && *GetParamIntVals(subParm, chain, state[chain]) == RCL_TK02))
7679 if (subParm->paramType == P_TK02BRANCHRATES)
7680 nu = *GetParamVals (modelSettings[subParm->relParts[0]].tk02var, chain, state[chain]);
7682 nu = *GetParamVals (modelSettings[subParm->relParts[0]].mixedvar, chain, state[chain]);
7683 tk02Rate = GetParamVals (subParm, chain, state[chain]);
7684 brlens = GetParamSubVals (subParm, chain, state[chain]);
7686 /* prior ratio & update effective evolutionary lengths */
7687 if (p->left != NULL)
7689 if (p->left->length > 0.0)
7691 (*lnPriorRatio) -= LnProbTK02LogNormal (tk02Rate[p->index], nu*oldLeftLength, tk02Rate[p->left->index]);
7692 (*lnPriorRatio) += LnProbTK02LogNormal (tk02Rate[p->index], nu*p->left->length, tk02Rate[p->left->index]);
7693 brlens[p->left->index] = p->left->length * (tk02Rate[p->left->index]+tk02Rate[p->index])/2.0;
7695 if (p->right->length > 0.0)
7697 (*lnPriorRatio) -= LnProbTK02LogNormal (tk02Rate[p->index], nu*oldRightLength, tk02Rate[p->right->index]);
7698 (*lnPriorRatio) += LnProbTK02LogNormal (tk02Rate[p->index], nu*p->right->length, tk02Rate[p->right->index]);
7699 brlens[p->right->index] = p->right->length * (tk02Rate[p->right->index]+tk02Rate[p->index])/2.0;
7702 if (p->anc->anc != NULL)
7704 (*lnPriorRatio) -= LnProbTK02LogNormal (tk02Rate[p->anc->index], nu*oldPLength, tk02Rate[p->index]);
7705 (*lnPriorRatio) += LnProbTK02LogNormal (tk02Rate[p->anc->index], nu*p->length, tk02Rate[p->index]);
7706 brlens[p->index] = p->length * (tk02Rate[p->index]+tk02Rate[p->anc->index])/2.0;
7709 else if ( subParm->paramType == P_IGRBRANCHRATES ||
7710 (subParm->paramType == P_MIXEDBRCHRATES && *GetParamIntVals(subParm, chain, state[chain]) == RCL_IGR))
7712 if (subParm->paramType == P_IGRBRANCHRATES)
7713 igrvar = *GetParamVals (modelSettings[subParm->relParts[0]].igrvar, chain, state[chain]);
7715 igrvar = *GetParamVals (modelSettings[subParm->relParts[0]].mixedvar, chain, state[chain]);
7716 igrRate = GetParamVals (subParm, chain, state[chain]);
7717 brlens = GetParamSubVals (subParm, chain, state[chain]);
7719 /* prior ratio & update effective evolutionary lengths */
7720 if (p->left != NULL)
7722 if (p->left->length > 0.0)
7724 (*lnPriorRatio) -= LnProbGamma (oldLeftLength/igrvar, oldLeftLength/igrvar, igrRate[p->left->index ]);
7725 (*lnPriorRatio) += LnProbGamma (p->left->length/igrvar, p->left->length/igrvar, igrRate[p->left->index ]);
7726 brlens[p->left->index ] = igrRate[p->left->index ] * p->left->length;
7728 if (p->right->length > 0.0)
7730 (*lnPriorRatio) -= LnProbGamma (oldRightLength/igrvar, oldRightLength/igrvar, igrRate[p->right->index]);
7731 (*lnPriorRatio) += LnProbGamma (p->right->length/igrvar, p->right->length/igrvar, igrRate[p->right->index]);
7732 brlens[p->right->index] = igrRate[p->right->index] * p->right->length;
7735 if (p->anc->anc != NULL)
7737 (*lnPriorRatio) -= LnProbGamma (oldPLength/igrvar, oldPLength/igrvar, igrRate[p->index]);
7738 (*lnPriorRatio) += LnProbGamma (p->length /igrvar, p->length /igrvar, igrRate[p->index]);
7739 brlens[p->index] = igrRate[p->index] * p->length;
7744 #if defined (DEBUG_CSLIDER)
7745 printf ("After node slider (clock):\n");
7746 printf ("Old depth: %f -- New depth: %f -- LnPriorRatio %f -- LnProposalRatio %f\n",
7747 oldDepth, newDepth, (*lnPriorRatio), (*lnProposalRatio));
7748 ShowNodes (t->root, 0, t->isRooted);
7756 int Move_Nu (Param *param, int chain, RandLong *seed, MrBFlt *lnPriorRatio, MrBFlt *lnProposalRatio, MrBFlt *mvp)
7758 /* move the variance of the TK02 relaxed clock lognormal using multiplier */
7761 MrBFlt oldNu, newNu, minNu, maxNu, tuning, *tk02Rate;
7766 /* get tuning parameter */
7769 /* get model params */
7770 mp = &modelParams[param->relParts[0]];
7772 /* get the min and max values */
7773 minNu = TK02VAR_MIN;
7774 maxNu = TK02VAR_MAX;
7775 if (!strcmp(mp->tk02varPr,"Uniform"))
7777 minNu = (mp->tk02varUni[0] < TK02VAR_MIN) ? TK02VAR_MIN : mp->tk02varUni[0];
7778 maxNu = (mp->tk02varUni[1] > TK02VAR_MAX) ? TK02VAR_MAX : mp->tk02varUni[1];
7781 /* get the TK02 lognormal variance */
7782 oldNu = *GetParamVals (param, chain, state[chain]);
7785 newNu = oldNu * exp ((0.5 - RandomNumber(seed))*tuning);
7787 /* reflect if necessary */
7788 while (newNu < minNu || newNu > maxNu)
7791 newNu = minNu * minNu / newNu;
7793 newNu = maxNu * maxNu / newNu;
7796 /* store new value */
7797 (*GetParamVals (param, chain, state[chain])) = newNu;
7799 /* calculate prior ratio */
7800 for (i=0; i<param->nSubParams; i++)
7802 tk02Rate = GetParamVals (param->subParams[i], chain, state[chain]);
7803 t = GetTree (param->subParams[i], chain, state[chain]);
7804 for (j=0; j<t->nNodes-2; j++)
7806 p = t->allDownPass[j];
7807 if (p->length > 0.0) // not ancestral fossil
7809 (*lnPriorRatio) -= LnProbTK02LogNormal (tk02Rate[p->anc->index], oldNu*p->length, tk02Rate[p->index]);
7810 (*lnPriorRatio) += LnProbTK02LogNormal (tk02Rate[p->anc->index], newNu*p->length, tk02Rate[p->index]);
7815 /* take prior on nu into account */
7816 if (!strcmp(mp->tk02varPr,"Exponential"))
7817 (*lnPriorRatio) += mp->tk02varExp * (oldNu - newNu);
7819 /* calculate proposal ratio */
7820 (*lnProposalRatio) = log (newNu / oldNu);
7822 /* we do not need to update likelihoods */
7823 for (i=0; i<param->nRelParts; i++)
7825 modelSettings[param->relParts[i]].upDateCl = NO;
7832 /*----------------------------------------------------------------
7834 | Move_Omega: Change the nonysnonymous/synonymous rate ratio
7835 | Note that this is appropriate when omegavar=equal
7837 ----------------------------------------------------------------*/
7838 int Move_Omega (Param *param, int chain, RandLong *seed, MrBFlt *lnPriorRatio, MrBFlt *lnProposalRatio, MrBFlt *mvp)
7840 /* change omega using sliding window */
7843 MrBFlt oldO, newO, window, minO, maxO, ran, *alphaDir, oldPropRatio, newPropRatio, x, y;
7846 /* get size of window, centered on current omega value */
7849 /* get model params */
7850 mp = &modelParams[param->relParts[0]];
7852 /* get minimum and maximum values for omega */
7856 /* get old value of omega */
7857 oldO = *GetParamVals(param, chain, state[chain]);
7859 /* get Dirichlet parameters */
7860 alphaDir = mp->tRatioDir;
7862 /* change value for omega */
7863 ran = RandomNumber(seed);
7864 if (maxO-minO < window)
7868 newO = oldO + window * (ran - 0.5);
7870 /* check that new value is valid */
7874 newO = 2.0 * minO - newO;
7875 else if (newO > maxO)
7876 newO = 2.0 * maxO - newO;
7880 while (isValidO == NO);
7882 /* get proposal ratio */
7883 *lnProposalRatio = 0.0;
7885 /* get prior ratio from Dirichlet */
7886 oldPropRatio = oldO / (oldO + 1.0);
7887 newPropRatio = newO / (newO + 1.0);
7888 x = ((alphaDir[0] - 1.0) * log(newPropRatio)) + ((alphaDir[1] - 1.0) * log (1.0 - newPropRatio));
7889 y = ((alphaDir[0] - 1.0) * log(oldPropRatio)) + ((alphaDir[1] - 1.0) * log (1.0 - oldPropRatio));
7890 (*lnPriorRatio) = x - y;
7892 /* copy new omega value back */
7893 *GetParamVals(param, chain, state[chain]) = newO;
7895 /* Set update flags for all partitions that share this kappa. Note that the conditional
7896 likelihood update flags have been set before we even call this function. */
7897 for (i=0; i<param->nRelParts; i++)
7898 TouchAllTreeNodes(&modelSettings[param->relParts[i]],chain);
7900 /* Set update flags for cijks for all affected partitions. If this is a simple 4 X 4 model,
7901 we don't take any hit, because we will never go into a general transition probability
7902 calculator. However, for covarion, doublet, and codon models, we do want to update
7904 for (i=0; i<param->nRelParts; i++)
7905 modelSettings[param->relParts[i]].upDateCijk = YES;
7911 /*----------------------------------------------------------------
7913 | Move_Omega_M: Change the nonysnonymous/synonymous rate ratio
7914 | using multiplier. Note that this is appropriate when
7917 ----------------------------------------------------------------*/
7918 int Move_Omega_M (Param *param, int chain, RandLong *seed, MrBFlt *lnPriorRatio, MrBFlt *lnProposalRatio, MrBFlt *mvp)
7920 /* change omega using multiplier */
7923 MrBFlt oldO, newO, minO, maxO, tuning, ran, factor, *alphaDir, oldPropRatio, newPropRatio, x, y;
7926 /* get model params */
7927 mp = &modelParams[param->relParts[0]];
7929 /* get tuning parameter */
7932 /* get minimum and maximum values for omega */
7936 /* get old value of omega */
7937 oldO = *GetParamVals(param, chain, state[chain]);
7939 /* get Dirichlet parameters */
7940 alphaDir = mp->omegaDir;
7942 /* change value for omega */
7943 ran = RandomNumber(seed);
7944 factor = exp(tuning * (ran - 0.5));
7945 newO = oldO * factor;
7947 /* check that new value is valid */
7952 newO = minO * minO / newO;
7953 else if (newO > maxO)
7954 newO = maxO * maxO / newO;
7957 } while (isValidO == NO);
7959 /* get proposal ratio */
7960 *lnProposalRatio = log(newO / oldO);
7962 /* get prior ratio from Dirichlet */
7963 oldPropRatio = oldO / (oldO + 1.0);
7964 newPropRatio = newO / (newO + 1.0);
7965 x = ((alphaDir[0] - 1.0) * log(newPropRatio)) + ((alphaDir[1] - 1.0) * log (1.0 - newPropRatio));
7966 y = ((alphaDir[0] - 1.0) * log(oldPropRatio)) + ((alphaDir[1] - 1.0) * log (1.0 - oldPropRatio));
7967 (*lnPriorRatio) = x - y;
7969 /* copy new omega value back */
7970 *GetParamVals(param, chain, state[chain]) = newO;
7972 /* Set update flags for all partitions that share this omega. Note that the conditional
7973 likelihood update flags have been set before we even call this function. */
7974 for (i=0; i<param->nRelParts; i++)
7975 TouchAllTreeNodes(&modelSettings[param->relParts[i]],chain);
7977 /* Set update flags for cijks for all affected partitions. If this is a simple 4 X 4 model,
7978 we don't take any hit, because we will never go into a general transition probability
7979 calculator. However, for covarion, doublet, and codon models, we do want to update
7981 for (i=0; i<param->nRelParts; i++)
7982 modelSettings[param->relParts[i]].upDateCijk = YES;
7988 /*----------------------------------------------------------------
7990 | Move_OmegaBeta_M: Change parameters of the beta distribution
7991 | using multiplier for the M10 model. Note that this is
7992 | appropriate when omegavar=M10
7994 ----------------------------------------------------------------*/
7995 int Move_OmegaBeta_M (Param *param, int chain, RandLong *seed, MrBFlt *lnPriorRatio, MrBFlt *lnProposalRatio, MrBFlt *mvp)
7997 int i, isValidVal, whichParam;
7998 MrBFlt oldVal, newVal, minVal, maxVal, *vals, *subVals, tuning, ran, factor;
8001 /* do we pick alpha or beta of the Beta distribution to change */
8002 if (RandomNumber(seed) < 0.5)
8007 /* get model params */
8008 mp = &modelParams[param->relParts[0]];
8010 /* get tuning parameter */
8013 /* get minimum and maximum values for omega */
8017 /* get old value of omega */
8018 vals = GetParamVals(param, chain, state[chain]);
8019 subVals = GetParamSubVals(param, chain, state[chain]);
8020 oldVal = subVals[mp->numM10BetaCats + mp->numM10GammaCats + 4 + whichParam];
8022 /* change value for alpha/beta */
8023 ran = RandomNumber(seed);
8024 factor = exp(tuning * (ran - 0.5));
8025 newVal = oldVal * factor;
8027 /* check that new value is valid */
8031 if (newVal < minVal)
8032 newVal = minVal * minVal / newVal;
8033 else if (newVal > maxVal)
8034 newVal = maxVal * maxVal / newVal;
8037 } while (isValidVal == NO);
8039 /* get proposal ratio */
8040 *lnProposalRatio = log(newVal / oldVal);
8042 /* get prior ratio */
8043 if (!strcmp(mp->m10betapr, "Exponential"))
8044 (*lnPriorRatio) = (log(mp->m10betaExp) - newVal * mp->m10betaExp) - (log(mp->m10betaExp) - oldVal * mp->m10betaExp);
8046 (*lnPriorRatio) = 0.0;
8048 /* copy new omega value back */
8049 subVals[mp->numM10BetaCats + mp->numM10GammaCats + 4 + whichParam] = newVal;
8051 /* update the omega values */
8052 BetaBreaks (subVals[mp->numM10BetaCats + mp->numM10GammaCats + 4], subVals[mp->numM10BetaCats + mp->numM10GammaCats + 5], &vals[0], mp->numM10BetaCats);
8054 /* Set update flags for all partitions that share this kappa. Note that the conditional
8055 likelihood update flags have been set before we even call this function. */
8056 for (i=0; i<param->nRelParts; i++)
8057 TouchAllTreeNodes(&modelSettings[param->relParts[i]],chain);
8059 /* Set update flags for cijks for all affected partitions. If this is a simple 4 X 4 model,
8060 we don't take any hit, because we will never go into a general transition probability
8061 calculator. However, for covarion, doublet, and codon models, we do want to update
8063 for (i=0; i<param->nRelParts; i++)
8064 modelSettings[param->relParts[i]].upDateCijk = YES;
8070 /*----------------------------------------------------------------
8072 | Move_OmegaGamma_M: Change parameters of the gamma distribution
8073 | using multiplier for the M10 model. Note that this is
8074 | appropriate whenomegavar=M10
8076 ----------------------------------------------------------------*/
8077 int Move_OmegaGamma_M (Param *param, int chain, RandLong *seed, MrBFlt *lnPriorRatio, MrBFlt *lnProposalRatio, MrBFlt *mvp)
8079 int i, isValidVal, whichParam;
8080 MrBFlt oldVal, newVal, minVal, maxVal, *vals, *subVals, tuning, ran, factor, quantile95;
8083 /* do we pick alpha or beta of the Gamma distribution to change */
8084 if (RandomNumber(seed) < 0.5)
8089 /* get model params */
8090 mp = &modelParams[param->relParts[0]];
8092 /* get tuning parameter */
8095 /* get minimum and maximum values for omega */
8100 vals = GetParamVals(param, chain, state[chain]);
8101 subVals = GetParamSubVals(param, chain, state[chain]);
8102 oldVal = subVals[mp->numM10BetaCats + mp->numM10GammaCats + 6 + whichParam];
8104 /* change value for alpha/beta */
8107 ran = RandomNumber(seed);
8108 factor = exp(tuning * (ran - 0.5));
8109 newVal = oldVal * factor;
8111 /* check that new value is valid */
8115 if (newVal < minVal)
8116 newVal = minVal * minVal / newVal;
8117 else if (newVal > maxVal)
8118 newVal = maxVal * maxVal / newVal;
8121 } while (isValidVal == NO);
8123 /* check that the distribution does not go too far to the right */
8124 if (whichParam == 0)
8125 quantile95 = QuantileGamma (0.95, newVal, subVals[mp->numM10BetaCats + mp->numM10GammaCats + 7]);
8127 quantile95 = QuantileGamma (0.95, subVals[mp->numM10BetaCats + mp->numM10GammaCats + 6], newVal);
8129 } while (quantile95 > 100.0);
8131 /* get proposal ratio */
8132 *lnProposalRatio = log(newVal / oldVal);
8134 /* get prior ratio */
8135 if (!strcmp(mp->m10gammapr, "Exponential"))
8136 (*lnPriorRatio) = (log(mp->m10gammaExp) - newVal * mp->m10gammaExp) - (log(mp->m10gammaExp) - oldVal * mp->m10gammaExp);
8138 (*lnPriorRatio) = 0.0;
8140 /* copy new value back */
8141 subVals[mp->numM10BetaCats + mp->numM10GammaCats + 6 + whichParam] = newVal;
8143 /* update the omega values */
8144 if (DiscreteGamma (&vals[mp->numM10BetaCats], subVals[mp->numM10BetaCats + mp->numM10GammaCats + 6],
8145 subVals[mp->numM10BetaCats + mp->numM10GammaCats + 7], mp->numM10GammaCats, 0) == ERROR)
8147 for (i=0; i<mp->numM10GammaCats; i++)
8148 vals[mp->numM10BetaCats + i] += 1.0;
8150 /* Set update flags for all partitions that share this kappa. Note that the conditional
8151 likelihood update flags have been set before we even call this function. */
8152 for (i=0; i<param->nRelParts; i++)
8153 TouchAllTreeNodes(&modelSettings[param->relParts[i]],chain);
8155 /* Set update flags for cijks for all affected partitions. If this is a simple 4 X 4 model,
8156 we don't take any hit, because we will never go into a general transition probability
8157 calculator. However, for covarion, doublet, and codon models, we do want to update
8159 for (i=0; i<param->nRelParts; i++)
8160 modelSettings[param->relParts[i]].upDateCijk = YES;
8166 int Move_OmegaCat (Param *param, int chain, RandLong *seed, MrBFlt *lnPriorRatio, MrBFlt *lnProposalRatio, MrBFlt *mvp)
8168 int i, localNumCats, numBetaAndGammaCats;
8169 MrBFlt dirichletParameters[3], *newSubVals, *oldSubVals, *newFreqs, *oldFreqs, *priorParams, sum, alpha, x, y;
8172 /* get model params */
8173 mp = &modelParams[param->relParts[0]];
8175 /* how many categories are there */
8177 numBetaAndGammaCats = 0;
8178 if (!strcmp(mp->omegaVar, "M10"))
8181 numBetaAndGammaCats = mp->numM10BetaCats + mp->numM10GammaCats;
8184 /* get the values we need */
8185 newSubVals = GetParamSubVals (param, chain, state[chain]);
8186 oldSubVals = GetParamSubVals (param, chain, state[chain] ^ 1);
8187 if (!strcmp(mp->omegaVar, "M10"))
8189 newFreqs = newSubVals + numBetaAndGammaCats;
8190 oldFreqs = oldSubVals + numBetaAndGammaCats;
8191 priorParams = newSubVals + (numBetaAndGammaCats + 2);
8195 newFreqs = newSubVals + 0;
8196 oldFreqs = oldSubVals + 0;
8197 priorParams = newFreqs + 3;
8200 /* get parameter of proposal mechanism */
8203 /* multiply old values with some large number to get new values close to the old ones */
8204 for (i=0; i<localNumCats; i++)
8205 dirichletParameters[i] = oldFreqs[i] * alpha;
8207 /* get the new category frequencies */
8208 DirichletRandomVariable (dirichletParameters, newFreqs, localNumCats, seed);
8210 for (i=0; i<localNumCats; i++)
8212 if (newFreqs[i] < 0.0001)
8213 newFreqs[i] = 0.0001;
8216 for (i=0; i<localNumCats; i++)
8219 /* and get the new frequencies of the omega values, if we have another
8220 distribution for omega too */
8221 if (!strcmp(mp->omegaVar, "M10"))
8223 for (i=0; i<mp->numM10BetaCats; i++)
8224 newSubVals[i] = newFreqs[0] / mp->numM10BetaCats;
8225 for (i=mp->numM10BetaCats; i<mp->numM10BetaCats+mp->numM10GammaCats; i++)
8226 newSubVals[i] = newFreqs[1] / mp->numM10GammaCats;
8229 /* get proposal ratio */
8231 for (i=0; i<localNumCats; i++)
8232 sum += newFreqs[i]*alpha;
8234 for (i=0; i<localNumCats; i++)
8235 x -= LnGamma(newFreqs[i]*alpha);
8236 for (i=0; i<localNumCats; i++)
8237 x += (newFreqs[i]*alpha-1.0)*log(oldFreqs[i]);
8239 for (i=0; i<localNumCats; i++)
8240 sum += oldFreqs[i]*alpha;
8242 for (i=0; i<localNumCats; i++)
8243 y -= LnGamma(oldFreqs[i]*alpha);
8244 for (i=0; i<localNumCats; i++)
8245 y += (oldFreqs[i]*alpha-1.0)*log(newFreqs[i]);
8246 (*lnProposalRatio) = x - y;
8248 /* get prior ratio */
8249 x = y = 0.0; /* ignore the gamma part, it is identical */
8250 for (i=0; i<localNumCats; i++)
8251 x += (priorParams[i]-1.0)*log(newFreqs[i]);
8252 for (i=0; i<localNumCats; i++)
8253 y += (priorParams[i]-1.0)*log(oldFreqs[i]);
8254 (*lnPriorRatio) = x - y;
8256 /* Set update flags for all partitions that share this omega. Note that the conditional
8257 likelihood update flags have been set before we even call this function. */
8258 for (i=0; i<param->nRelParts; i++)
8259 TouchAllTreeNodes(&modelSettings[param->relParts[i]],chain);
8261 /* Set update flags for cijks for all affected partitions. */
8262 for (i=0; i<param->nRelParts; i++)
8263 modelSettings[param->relParts[i]].upDateCijk = YES;
8269 /*----------------------------------------------------------------
8271 | Move_OmegaM3: Change the nonysnonymous/synonymous rate ratio
8272 | of one class of the M3 model
8274 ----------------------------------------------------------------*/
8275 int Move_OmegaM3 (Param *param, int chain, RandLong *seed, MrBFlt *lnPriorRatio, MrBFlt *lnProposalRatio, MrBFlt *mvp)
8277 int i, isValidO, whichOmega;
8278 MrBFlt newO, window, minO, maxO, ran, *value, *oldValue, x, y;
8280 /* get size of window, centered on current omega value */
8283 /* get old value of omega */
8284 value = GetParamVals(param, chain, state[chain]);
8285 oldValue = GetParamVals(param, chain, state[chain] ^ 1);
8286 whichOmega = (int) (RandomNumber(seed)*3.0);
8288 /* get minimum and maximum values for omega */
8289 if (whichOmega == 0)
8292 minO = value[whichOmega-1];
8293 if (whichOmega == 2)
8296 maxO = value[whichOmega+1];
8298 /* change value for omega */
8299 ran = RandomNumber(seed);
8300 if (maxO-minO < window)
8304 newO = oldValue[whichOmega] + window * (ran - 0.5);
8306 /* check that new value is valid */
8311 newO = 2* minO - newO;
8312 else if (newO > maxO)
8313 newO = 2 * maxO - newO;
8316 } while (isValidO == NO);
8318 /* copy new omega value back */
8319 value[whichOmega] = newO;
8321 /* get proposal ratio */
8322 *lnProposalRatio = 0.0;
8324 /* get prior ratio */
8325 x = LogOmegaPrior (value[0], value[1], value[2]);
8326 y = LogOmegaPrior (oldValue[0], oldValue[1], oldValue[2]);
8327 *lnPriorRatio = x - y;
8329 /* Set update flags for all partitions that share this omega. Note that the conditional
8330 likelihood update flags have been set before we even call this function. */
8331 for (i=0; i<param->nRelParts; i++)
8332 TouchAllTreeNodes(&modelSettings[param->relParts[i]],chain);
8334 /* Set update flags for cijks for all affected partitions. */
8335 for (i=0; i<param->nRelParts; i++)
8336 modelSettings[param->relParts[i]].upDateCijk = YES;
8342 /*----------------------------------------------------------------
8344 | Move_OmegaNeu: Change the nonysnonymous/synonymous rate ratio
8347 ----------------------------------------------------------------*/
8348 int Move_OmegaNeu (Param *param, int chain, RandLong *seed, MrBFlt *lnPriorRatio, MrBFlt *lnProposalRatio, MrBFlt *mvp)
8350 int i, isOPriorExp, isValidO;
8351 MrBFlt oldO, newO, window, minO, maxO, ran, *value, x, y;
8353 /* get size of window, centered on current omega value */
8356 /* get old value of omega */
8357 value = GetParamVals(param, chain, state[chain]);
8358 newO = oldO = value[1];
8360 /* get minimum and maximum values for omega */
8364 /* the only way we would be updating the middle category (omega2) is
8365 if we have an exponential prior on all three omegas */
8368 /* change value for omega */
8369 ran = RandomNumber(seed);
8370 if (maxO-minO < window)
8374 newO = oldO + window * (ran - 0.5);
8376 /* check that new value is valid */
8381 newO = 2 * minO - newO;
8382 else if (newO > maxO)
8383 newO = 2 * maxO - newO;
8386 } while (isValidO == NO);
8388 /* get proposal ratio */
8389 *lnProposalRatio = 0.0;
8391 /* copy new omega value back */
8394 /* get prior ratio */
8395 if (isOPriorExp == NO)
8397 *lnPriorRatio = 0.0;
8401 x = LogOmegaPrior (value[0], newO, value[2]);
8402 y = LogOmegaPrior (value[0], oldO, value[2]);
8403 *lnPriorRatio = x - y;
8406 /* Set update flags for all partitions that share this omega. Note that the conditional
8407 likelihood update flags have been set before we even call this function. */
8408 for (i=0; i<param->nRelParts; i++)
8409 TouchAllTreeNodes(&modelSettings[param->relParts[i]],chain);
8411 /* Set update flags for cijks for all affected partitions. */
8412 for (i=0; i<param->nRelParts; i++)
8413 modelSettings[param->relParts[i]].upDateCijk = YES;
8419 /*----------------------------------------------------------------
8421 | Move_OmegaPos: Change the nonysnonymous/synonymous rate ratio
8422 | for positively selected sites
8424 ----------------------------------------------------------------*/
8425 int Move_OmegaPos (Param *param, int chain, RandLong *seed, MrBFlt *lnPriorRatio, MrBFlt *lnProposalRatio, MrBFlt *mvp)
8427 int i, isValidO, omegaUni, omegaExp1, omegaExp2;
8428 MrBFlt oldO, newO, window, minO=0.0, maxO=0.0, ran, *value, x, y;
8431 /* get size of window, centered on current omega value */
8434 /* get model params */
8435 mp = &modelParams[param->relParts[0]];
8437 /* get old value of omega */
8438 value = GetParamVals(param, chain, state[chain]);
8439 newO = oldO = value[2];
8441 /* determine prior for omega */
8442 omegaUni = omegaExp1 = omegaExp2 = NO;
8443 if (param->paramId == OMEGA_BUD || param->paramId == OMEGA_BUF || param->paramId == OMEGA_FUD || param->paramId == OMEGA_FUF)
8445 else if (param->paramId == OMEGA_BED || param->paramId == OMEGA_BEF || param->paramId == OMEGA_FED || param->paramId == OMEGA_FEF)
8447 else if (param->paramId == OMEGA_ED || param->paramId == OMEGA_EF)
8450 /* get minimum and maximum values for omega */
8451 if (omegaUni == YES)
8453 minO = mp->ny98omega3Uni[0];
8454 if (minO < value[1])
8456 maxO = mp->ny98omega3Uni[1];
8457 if (maxO > KAPPA_MAX)
8460 else if (omegaExp1 == YES || omegaExp2 == YES)
8466 /* change value for omega */
8467 ran = RandomNumber(seed);
8468 if (maxO-minO < window)
8472 newO = oldO + window * (ran - 0.5);
8474 /* check that new value is valid */
8479 newO = 2* minO - newO;
8480 else if (newO > maxO)
8481 newO = 2 * maxO - newO;
8484 } while (isValidO == NO);
8486 /* get proposal ratio */
8487 *lnProposalRatio = 0.0;
8489 /* copy new omega value back */
8492 /* get prior ratio (part 2) */
8493 if (omegaUni == YES)
8495 *lnPriorRatio = 0.0;
8497 else if (omegaExp1 == YES)
8499 *lnPriorRatio = mp->ny98omega3Exp * (oldO - newO);
8501 else if (omegaExp2 == YES)
8503 x = LogOmegaPrior (value[0], value[1], newO);
8504 y = LogOmegaPrior (value[0], value[1], oldO);
8505 *lnPriorRatio = x - y;
8508 /* Set update flags for all partitions that share this omega. Note that the conditional
8509 likelihood update flags have been set before we even call this function. */
8510 for (i=0; i<param->nRelParts; i++)
8511 TouchAllTreeNodes(&modelSettings[param->relParts[i]],chain);
8513 /* Set update flags for cijks for all affected partitions. */
8514 for (i=0; i<param->nRelParts; i++)
8515 modelSettings[param->relParts[i]].upDateCijk = YES;
8521 /*----------------------------------------------------------------
8523 | Move_OmegaPur: Change the nonysnonymous/synonymous rate ratio
8524 | for purifying selection sites
8526 ----------------------------------------------------------------*/
8527 int Move_OmegaPur (Param *param, int chain, RandLong *seed, MrBFlt *lnPriorRatio, MrBFlt *lnProposalRatio, MrBFlt *mvp)
8529 int i, isOPriorExp, isValidO;
8530 MrBFlt oldO, newO, window, minO, maxO, ran, *value, x, y;
8532 /* get size of window, centered on current omega value */
8535 /* get old value of omega */
8536 value = GetParamVals(param, chain, state[chain]);
8537 newO = oldO = value[0];
8539 /* get minimum and maximum values for omega */
8543 /* get prior for omega */
8544 if (param->paramId == OMEGA_BUD || param->paramId == OMEGA_BUF || param->paramId == OMEGA_BED ||
8545 param->paramId == OMEGA_BEF || param->paramId == OMEGA_BFD || param->paramId == OMEGA_BFF)
8550 /* change value for omega */
8551 ran = RandomNumber(seed);
8552 if (maxO-minO < window)
8556 newO = oldO + window * (ran - 0.5);
8558 /* check that new value is valid */
8563 newO = 2* minO - newO;
8564 else if (newO > maxO)
8565 newO = 2 * maxO - newO;
8568 } while (isValidO == NO);
8570 /* get proposal ratio */
8571 *lnProposalRatio = 0.0;
8573 /* copy new omega value back */
8576 /* get prior ratio (part 2) */
8577 if (isOPriorExp == NO)
8579 *lnPriorRatio = 0.0;
8583 x = LogOmegaPrior (newO, value[1], value[2]);
8584 y = LogOmegaPrior (oldO, value[1], value[2]);
8585 *lnPriorRatio = x - y;
8588 /* Set update flags for all partitions that share this omega. Note that the conditional
8589 likelihood update flags have been set before we even call this function. */
8590 for (i=0; i<param->nRelParts; i++)
8591 TouchAllTreeNodes(&modelSettings[param->relParts[i]],chain);
8593 /* Set update flags for cijks for all affected partitions. */
8594 for (i=0; i<param->nRelParts; i++)
8595 modelSettings[param->relParts[i]].upDateCijk = YES;
8601 /*----------------------------------------------------------------
8603 | Move_ParsEraser1: This proposal mechanism changes the topology and
8604 | branch lengths of an unrooted tree. A randomly chosen region of
8605 | the tree is erased. Parsimony is used to guide the selection of
8606 | a new topology for the erased part of the tree. The parsimony
8607 | branch lengths are used to guide the proposal of new branch
8608 | lengths. This variant (1) uses exhaustive enumeration.
8610 | Programmed by FR 2004-10-23--
8612 ----------------------------------------------------------------*/
8613 int Move_ParsEraser1 (Param *param, int chain, RandLong *seed, MrBFlt *lnPriorRatio, MrBFlt *lnProposalRatio, MrBFlt *mvp)
8615 int i, j, isVPriorExp, nSubTerminals, nEmbeddedTrees;
8616 MrBFlt alphaPi, warp, minV, maxV, minP, maxP, brlensExp=0.0, newM, oldM, maxLen,
8617 *brlensCur, *brlensNew, *parslensCur, *parslensNew,
8618 curLength, newLength, lnJacobian, lnRandomRatio, alpha[2], prob[2],
8619 minLenCur, minLenNew, f;
8621 Tree *t, *subtree, *subtree1, memTree[2];
8626 /* set pointers to NULL */
8627 subtree = subtree1 = NULL;
8631 memTree[i].allDownPass = NULL;
8632 memTree[i].intDownPass = NULL;
8633 memTree[i].nodes = NULL;
8637 /* Set alpha Pi for Dirichlet p generator */
8641 /* Set the parsimony warp factor */
8645 /* Set the number of terminals (nSubTerminals, column 3) in erased tree */
8646 /* Erased Nodes => Leaves => Terminals => Embedded trees => Embedded histories => New trees
8647 2 => 3 => 4 => 2 => 2 = 2! => 3 = 1*3
8648 3 => 4 => 5 => 5 => 6 = 3! => 15 = 1*3*5
8649 4 => 5 => 6 => 14 => 24 = 4! => 105 = 1*3*5*7
8650 5 => 6 => 7 => 42 => 120 = 5! => 945 = 1*3*5*7*9
8652 nSubTerminals = (int) (RandomNumber(seed) * 4) + 4;
8655 /* initialize log prior and log proposal probabilities */
8656 *lnPriorRatio = *lnProposalRatio = 0.0;
8659 t = GetTree (param, chain, state[chain]);
8661 /* get model params */
8662 mp = &modelParams[param->relParts[0]];
8664 /* max and min brlen */
8665 if (param->subParams[0]->paramId == BRLENS_UNI)
8667 minV = mp->brlensUni[0] > BRLENS_MIN ? mp->brlensUni[0] : BRLENS_MIN;
8668 maxV = mp->brlensUni[1];
8675 brlensExp = mp->brlensExp;
8678 minP = 3.0 * ((1.0 / 4.0) - ((1.0 / 4.0) * exp (-4.0 * minV / 3.0)));
8679 maxP = 3.0 * ((1.0 / 4.0) - ((1.0 / 4.0) * exp (-4.0 * maxV / 3.0)));
8681 /* allocate some memory for this move */
8682 brlensCur = (MrBFlt *) SafeMalloc (8 * nSubTerminals * sizeof (MrBFlt));
8685 MrBayesPrint ("%s ERROR: Could not allocate brlensCur\n", spacer);
8688 brlensNew = brlensCur + 2*nSubTerminals;
8689 parslensCur = brlensCur + 4 * nSubTerminals;
8690 parslensNew = brlensCur + 6 * nSubTerminals;
8692 subtree = &memTree[0];
8693 subtree->nNodes = 2 * nSubTerminals - 2;
8694 subtree->nIntNodes = nSubTerminals - 2;
8695 subtree->nodes = (TreeNode *) SafeCalloc (subtree->nNodes, sizeof (TreeNode));
8696 subtree->allDownPass = (TreeNode **) SafeCalloc (subtree->nNodes, sizeof (TreeNode *));
8697 subtree->intDownPass = (TreeNode **) SafeCalloc (subtree->nIntNodes, sizeof (TreeNode *));
8698 if (!subtree->nodes || !subtree->intDownPass || !subtree->allDownPass)
8700 MrBayesPrint ("%s ERROR: Could not allocate subtree\n", spacer);
8704 subtree1 = &memTree[1];
8705 subtree1->nNodes = 2 * nSubTerminals - 2;
8706 subtree1->nIntNodes = nSubTerminals - 2;
8707 subtree1->nodes = (TreeNode *) SafeCalloc (subtree1->nNodes, sizeof (TreeNode));
8708 subtree1->allDownPass = (TreeNode **) SafeCalloc (subtree1->nNodes, sizeof (TreeNode *));
8709 subtree1->intDownPass = (TreeNode **) SafeCalloc (subtree1->nIntNodes, sizeof (TreeNode *));
8710 if (!subtree1->nodes || !subtree1->intDownPass || !subtree1->allDownPass)
8712 MrBayesPrint ("%s ERROR: Could not allocate subtree1\n", spacer);
8716 tInfo.leaf = (TreeNode **) SafeCalloc (t->nNodes, sizeof(TreeNode *));
8719 MrBayesPrint ("%s ERROR: Could not allocate tInfo.leaf\n", spacer);
8722 tInfo.vertex = tInfo.leaf + t->nNodes - t->nIntNodes;
8724 /* Select a random embedded subtree with nSubTerminals terminals */
8725 if (GetRandomEmbeddedSubtree (t, nSubTerminals, seed, &nEmbeddedTrees) == ERROR)
8727 MrBayesPrint ("%s ERROR: Could not get subtree\n", spacer);
8731 /* Set update flags (We'd better do it before the marked nodes disappear) */
8732 for (i=0; i<t->nIntNodes; i++)
8734 p = t->intDownPass[i];
8735 if (p->marked == YES)
8740 else if (p->left->upDateCl == YES || p->right->upDateCl == YES)
8744 /* Fill in subtrees */
8745 CopyTreeToSubtree (t, subtree);
8746 CopyTreeToSubtree (t, subtree1);
8748 /* Calculate downstates and upstate of root node of subtree */
8749 GetParsDP (t, t->root->left, chain);
8750 for (i=0; i<t->nIntNodes; i++)
8752 p = t->intDownPass[i];
8753 if (p->marked == YES && p->anc->marked == NO)
8756 GetParsimonySubtreeRootstate (t, p->anc, chain);
8758 /* Get parsimony length of current tree */
8759 curLength = GetParsimonyLength (subtree, chain);
8761 /* Get the Markov and parsimony branch lengths of the current subtree */
8762 GetParsimonyBrlens (subtree, chain, parslensCur);
8763 for (i=0; i<subtree->nNodes-1; i++)
8764 brlensCur[i] = subtree->allDownPass[i]->length;
8766 /* Calculate parsimony score of all trees relative to shortest tree (1.0) */
8767 tInfo.totalScore = 0.0;
8768 tInfo.stopScore = -1.0;
8769 tInfo.minScore = curLength;
8771 ExhaustiveParsimonySearch (subtree, chain, &tInfo);
8773 /* Choose one of these trees randomly based on its score */
8774 tInfo.stopScore = RandomNumber(seed) * tInfo.totalScore;
8775 tInfo.totalScore = 0.0;
8776 ExhaustiveParsimonySearch (subtree1, chain, &tInfo);
8777 /* ShowNodes (subtree1->root, 0 , NO); */
8780 /* Get length of that tree */
8782 newLength = GetParsimonyLength (subtree1, chain);
8784 /* Get the parsimony branch lengths of the new subtree */
8785 GetParsimonyBrlens (subtree1, chain, parslensNew);
8787 /* Find the maximum length of a branch */
8789 for (i=0; i<t->nRelParts; i++)
8792 m = &modelSettings[j];
8793 maxLen += m->numUncompressedChars;
8796 /* Find the Markov branch lengths of the new subtree */
8797 /* Calculate Jacobian and prob ratio for the Dirichlet random number generator */
8798 lnJacobian = lnRandomRatio = 0.0;
8799 minLenCur = minLenNew = 0.0;
8800 for (i=0; i<subtree1->nNodes-1; i++)
8802 minLenCur += parslensCur[i];
8803 minLenNew += parslensNew[i];
8805 for (i=0; i<subtree1->nNodes-1; i++)
8807 p = subtree1->allDownPass[i];
8808 f = newLength / minLenNew;
8809 alpha[0] = parslensNew[i] * f * alphaPi + 1.0;
8810 alpha[1] = (maxLen - parslensNew[i] * f) * alphaPi + 1.0;
8811 DirichletRandomVariable (alpha, prob, 2, seed);
8812 if (prob[0] >= maxP || prob[0] <= minP)
8818 p->length = (-3.0 / 4.0) * log (1.0 - 4.0 * prob[0] / 3.0);
8819 lnJacobian += (-4.0 * brlensCur[i] / 3.0) - log (1.0 - 4.0 * prob[0] / 3.0);
8820 lnRandomRatio -= log (pow (prob[0], alpha[0] - 1.0) * pow (prob[1], alpha[1] - 1.0));
8821 f = curLength / minLenNew;
8822 alpha[0] = parslensCur[i] * f * alphaPi + 1.0;
8823 alpha[1] = (maxLen - parslensCur[i] * f) * alphaPi + 1.0;
8824 prob[0] = 3.0 * ((1.0 / 4.0) - ((1.0 / 4.0) * exp (-4.0 * brlensCur[i] / 3.0)));
8825 prob[1] = 1.0 - prob[0];
8826 lnRandomRatio += log (pow (prob[0], alpha[0] - 1.0) * pow (prob[1], alpha[1] - 1.0));
8829 /* Store the new Markov branch lengths */
8830 for (i=0; i<subtree1->nNodes-1; i++)
8831 brlensNew[i] = subtree1->allDownPass[i]->length;
8833 /* Calculate the proposal ratio */
8834 (*lnProposalRatio) = lnJacobian + lnRandomRatio + log (warp/3.0) * (curLength - newLength) + log (1.0-warp) * (newLength - curLength);
8836 /* Calculate the prior ratio */
8837 if (isVPriorExp == YES)
8840 for (i=0; i<subtree->nNodes-1; i++)
8842 oldM += brlensCur[i];
8843 newM += brlensNew[i];
8845 (*lnPriorRatio) += brlensExp * (oldM - newM);
8848 /* Copy subtree into tree */
8849 CopySubtreeToTree (subtree1, t);
8850 /* ShowNodes (subtree1->root, 0, NO); */
8851 /* ShowNodes (t->root, 0, NO); */
8853 /* Update node sequences */
8856 /* correct for difference in number of embedded subtrees */
8857 if (GetRandomEmbeddedSubtree (t, nSubTerminals, seed, &i) == ERROR)
8859 MrBayesPrint ("%s Could not count number of subtrees in Move_ParsEraser1\n", spacer);
8862 if (i != nEmbeddedTrees)
8863 (*lnProposalRatio) += log ((MrBFlt) nEmbeddedTrees / (MrBFlt) i);
8865 /* Free memory allocated for this move */
8866 free (subtree->allDownPass);
8867 free (subtree->intDownPass);
8868 free (subtree->nodes);
8869 free (subtree1->allDownPass);
8870 free (subtree1->intDownPass);
8871 free (subtree1->nodes);
8879 free (subtree->allDownPass);
8880 free (subtree->intDownPass);
8881 free (subtree->nodes);
8882 free (subtree1->allDownPass);
8883 free (subtree1->intDownPass);
8884 free (subtree1->nodes);
8892 int Move_ParsSPR (Param *param, int chain, RandLong *seed, MrBFlt *lnPriorRatio, MrBFlt *lnProposalRatio, MrBFlt *mvp)
8894 /* Change topology (and branch lengths) using SPR (asymmetric) biased according to parsimony scores. */
8896 int i, j, n, division, topologyHasChanged, isVPriorExp;
8897 BitsLong *pA, *pV, *pP, y[2];
8898 MrBFlt x, minV, maxV, brlensExp=0.0, minLength=0.0, length=0.0,
8899 cumulativeProb, warpFactor, ran, tuning, increaseProb, decreaseProb,
8900 divFactor, nStates, rateMult, v_typical, sum1, sum2, tempsum, tempc, tempy;
8901 CLFlt *nSitesOfPat, *nSites, *globalNSitesOfPat;
8902 TreeNode *p, *q, *a, *b, *u, *v, *c=NULL, *d;
8905 ModelInfo *m = NULL;
8907 warpFactor = mvp[0]; /* tuning parameter determining how heavily to weight according to parsimony scores */
8908 increaseProb = decreaseProb = mvp[1]; /* reweighting probabilities */
8909 v_typical = mvp[2]; /* typical branch length for conversion of parsimony score to log prob ratio */
8910 tuning = mvp[3]; /* multiplier tuning parameter */
8912 (*lnProposalRatio) = (*lnPriorRatio) = 0.0;
8914 /* get model params and model info */
8915 mp = &modelParams[param->relParts[0]];
8916 m = &modelSettings[param->relParts[0]];
8919 t = GetTree (param, chain, state[chain]);
8921 /* max and min brlen */
8922 if (param->subParams[0]->paramId == BRLENS_UNI)
8924 minV = mp->brlensUni[0] > BRLENS_MIN ? mp->brlensUni[0] : BRLENS_MIN;
8925 maxV = mp->brlensUni[1] < BRLENS_MAX ? mp->brlensUni[1] : BRLENS_MAX;
8928 else if (param->subParams[0]->paramId == BRLENS_GamDir)
8934 else if (param->subParams[0]->paramId == BRLENS_iGmDir)
8940 else if (param->subParams[0]->paramId == BRLENS_twoExp)
8950 brlensExp = mp->brlensExp;
8954 /* Dirichlet or twoExp prior */
8955 if (isVPriorExp > 1)
8956 (*lnPriorRatio) = -LogDirPrior(t, mp, isVPriorExp);
8958 # if defined (DEBUG_ParsSPR)
8959 // WriteTopologyToFile (stdout, t->root->left, t->isRooted); fprintf (stdout, ";\t");
8960 printf ("Before:\n");
8961 ShowNodes (t->root, 2, YES);
8965 /* set topologyHasChanged to NO */
8966 topologyHasChanged = NO;
8968 /* reset node variables that will be used */
8969 for (i=0; i<t->nNodes; i++)
8971 p = t->allDownPass[i];
8976 /* pick a random branch */
8977 p = t->allDownPass[(int)(RandomNumber(seed) * (t->nNodes -2))];
8981 if ((p->anc->anc->anc == NULL || p->anc->isLocked == YES) && (q->left == NULL || q->isLocked == YES))
8987 /* set up pointers for nodes around the picked branch */
9003 /* get final parsimony states for the root part */
9004 GetParsDP (t, t->root->left, chain);
9005 GetParsFP (t, t->root->left, chain);
9007 /* get downpass parsimony states for the crown part */
9008 GetParsDP (t, v, chain);
9010 /* mark all nodes in the root part of the tree, taking constraints into account */
9013 /* then move down towards root */
9014 if (u->isLocked == NO)
9017 while (p->anc != NULL)
9020 if (p->isLocked == YES)
9026 /* finally move up */
9027 for (i=t->nNodes-2; i>=0; i--)
9029 p = t->allDownPass[i];
9030 if (p->marked == NO && p->anc->marked == YES && p->anc->isLocked == NO && p != u)
9034 /* find number of site patterns and modify randomly */
9035 globalNSitesOfPat = numSitesOfPat + (chainId[chain] % chainParams.numChains) * numCompressedChars + m->compCharStart;
9036 nSitesOfPat = (CLFlt *) SafeCalloc (numCompressedChars, sizeof(CLFlt));
9039 MrBayesPrint ("%s Problem allocating nSitesOfPat in Move_ParsSPR\n", spacer);
9042 for (i=0; i<numCompressedChars; i++)
9044 nSitesOfPat[i] = globalNSitesOfPat[i];
9045 for (j=0; j<globalNSitesOfPat[i]; j++)
9047 ran = RandomNumber(seed);
9048 if (ran < decreaseProb)
9050 else if (ran > 1.0 - increaseProb)
9055 /* cycle through the possibilities and record the parsimony length */
9056 for (i=0; i<t->nNodes; i++)
9058 p = t->allDownPass[i];
9059 if (p->marked == NO)
9061 /* find the parsimony length */
9063 for (n=0; n<t->nRelParts; n++)
9065 division = t->relParts[n];
9067 /* Find model settings */
9068 m = &modelSettings[division];
9070 /* find nSitesOfPat */
9071 nSites = nSitesOfPat + m->compCharStart;
9073 /* find downpass parsimony sets for the node and its environment */
9074 pP = m->parsSets[p->index];
9075 pA = m->parsSets[p->anc->index];
9076 pV = m->parsSets[v->index];
9079 if (m->nParsIntsPerSite == 1)
9081 for (j=0; j<m->numChars; j++)
9083 y[0] = (pP[j] | pA[j]) & pV[j];
9085 length += nSites[j];
9088 else /* if (m->nParsIntsPerSite == 2) */
9090 for (j=0; j<2*m->numChars; j+=2)
9092 y[0] = (pP[j] | pA[j]) & pV[j];
9093 y[1] = (pP[j+1] | pA[j+1]) & pV[j+1];
9094 if ((y[0] | y[1]) == 0)
9095 length += nSites[j/2];
9099 /* find nStates and ratemult */
9100 nStates = m->numModelStates;
9101 if (m->dataType == STANDARD)
9103 rateMult = GetRate(division, chain);
9105 /* get division warp factor */
9106 divFactor = - warpFactor * log((1.0/nStates) - exp(-nStates/(nStates-1)*v_typical*rateMult)/nStates);
9108 p->d += divFactor * length;
9112 /* find the min length and the sum for the forward move */
9114 for (i=0; i<t->nNodes; i++)
9116 p = t->allDownPass[i];
9117 if (p->marked == NO || p == a)
9119 if (minLength < 0.0 || p->d < minLength)
9122 sum1 = 0.0; tempc = 0.0;
9123 for (i=0; i<t->nNodes; i++)
9125 p = t->allDownPass[i];
9126 if (p->marked == YES && p != a)
9128 /* Kahan summation to reduce numerical error */
9129 tempy = exp (minLength - p->d) - tempc;
9130 tempsum = sum1 + tempy;
9131 tempc = (tempsum - sum1) - tempy;
9136 /* generate a random uniform */
9137 ran = RandomNumber(seed) * sum1;
9139 /* select the appropriate reattachment point */
9140 cumulativeProb = 0.0; tempc = 0.0;
9141 for (i=0; i<t->nNodes; i++)
9143 p = t->allDownPass[i];
9144 if (p->marked == YES && p != a)
9147 /* Kahan summation to reduce numerical error */
9148 tempy = exp (minLength - p->d) - tempc;
9149 tempsum = cumulativeProb + tempy;
9150 tempc = (tempsum - cumulativeProb) - tempy;
9151 cumulativeProb = tempsum;
9152 if (cumulativeProb > ran)
9157 /* calculate the proposal ratio */
9158 (*lnProposalRatio) = c->d - minLength + log(sum1);
9160 /* find the min length and the sum for the backward move */
9162 for (i=0; i<t->nNodes; i++)
9164 p = t->allDownPass[i];
9165 if (p->marked == NO || p == c)
9167 if (minLength < 0.0 || p->d < minLength)
9170 sum2 = 0.0; tempc = 0.0;
9171 for (i=0; i<t->nNodes; i++)
9173 p = t->allDownPass[i];
9174 if (p->marked == YES && p != c)
9176 /* Kahan summation to reduce numerical error */
9177 tempy = exp (minLength - p->d) - tempc;
9178 tempsum = sum2 + tempy;
9179 tempc = (tempsum - sum2) - tempy;
9184 /* calculate the proposal ratio */
9185 (*lnProposalRatio) += minLength - a->d - log(sum2);
9200 /* c cannot be a, as a is skiped in the selection for reattachment point */
9202 /* transfer lock if necessary */
9203 /* if u is locked, then we have moved upwards and need to leave the u lock behind */
9204 if (u->isLocked == YES)
9208 a->lockID = u->lockID;
9211 /* if c is on root path and locked, we need to transfer lock to u */
9219 if (p == c && c->isLocked == YES)
9222 u->lockID = c->lockID;
9227 /* reassign branch lengths */
9229 while (p->anc->anc != NULL)
9237 /* c is descendant to a so move a->length and not u->length */
9239 u->length = a->length;
9243 while (p->anc->anc != NULL)
9251 /* c is ancestor to a so insert above instead of below */
9253 c->length = u->length;
9257 topologyHasChanged = YES;
9259 /* hit c length with multiplier (a and u dealt with below) */
9260 x = c->length * exp(tuning * (RandomNumber(seed) - 0.5));
9261 while (x < minV || x > maxV)
9264 x = minV * minV / x;
9266 x = maxV * maxV / x;
9268 /* calculate proposal and prior ratio based on length modification */
9269 (*lnProposalRatio) += log (x / c->length);
9270 if (isVPriorExp == YES)
9271 (*lnPriorRatio) += brlensExp * (c->length - x);
9274 /* hit a length with multiplier */
9275 x = a->length * exp(tuning * (RandomNumber(seed) - 0.5));
9276 while (x < minV || x > maxV)
9279 x = minV * minV / x;
9281 x = maxV * maxV / x;
9283 /* calculate proposal and prior ratio based on length modification */
9284 (*lnProposalRatio) += log (x / a->length);
9285 if (isVPriorExp == YES)
9286 (*lnPriorRatio) += brlensExp * (a->length - x);
9289 /* hit u length with multiplier */
9290 x = u->length * exp(tuning * (RandomNumber(seed) - 0.5));
9291 while (x < minV || x > maxV)
9294 x = minV * minV / x;
9296 x = maxV * maxV / x;
9298 /* calculate proposal and prior ratio based on length modification */
9299 (*lnProposalRatio) += log (x / u->length);
9300 if (isVPriorExp == YES)
9301 (*lnPriorRatio) += brlensExp * (u->length - x);
9304 /* set tiprobs update flags */
9307 c->upDateTi = YES; /* could be same as a but that does not matter */
9309 /* set flags for update of cond likes from u and down to root */
9311 while (p->anc != NULL)
9317 /* set flags for update of cond likes from b and down to root */
9319 while (p->anc != NULL && p->upDateCl == NO)
9325 /* get down pass sequence if tree topology has changed */
9326 if (topologyHasChanged == YES)
9331 /* Dirichlet or twoExp prior */
9332 if (isVPriorExp > 1)
9333 (*lnPriorRatio) += LogDirPrior(t, mp, isVPriorExp);
9335 # if defined (DEBUG_ParsSPR)
9336 // WriteTopologyToFile (stdout, t->root->left, t->isRooted);
9337 // fprintf (stdout, ";\t"); fprintf (stdout, "%lf\n", *lnProposalRatio);
9338 printf ("After:\n");
9339 ShowNodes (t->root, 2, YES);
9341 printf ("Proposal ratio: %f\n",(*lnProposalRatio));
9342 printf ("v: %d u: %d a: %d b: %d\n",v->index, u->index, a->index, b->index);
9343 printf ("Has topology changed? %d\n",topologyHasChanged);
9353 int Move_ParsSPR1 (Param *param, int chain, RandLong *seed, MrBFlt *lnPriorRatio, MrBFlt *lnProposalRatio, MrBFlt *mvp)
9355 /* Change topology (and branch lengths) using SPR (symmetric) biased according to parsimony scores,
9356 controlled by a window defined by a certain node distance radius. Note: w = e^{-S} */
9358 int i, j, k, n, division, topologyHasChanged, moveInRoot, nNeighbor, nRoot, nCrown, iA, jC, isVPriorExp;
9359 BitsLong *pA, *pB, *pP, *pC, *pD, y[2];
9360 MrBFlt x, minV, maxV, brlensExp=0.0, minLength=0.0, length=0.0, *parLength=NULL, prob, ran, tuning, warpFactor,
9361 sum1, sum2, tempsum, tempc, tempy;
9362 CLFlt *nSites, *nSitesOfPat=NULL, *globalNSitesOfPat;
9363 TreeNode *p, *q, *r, *a, *b, *u, *v, *c, *d, *newB, *newA, *newC, **pRoot=NULL, **pCrown=NULL;
9368 warpFactor = mvp[0]; /* tuning parameter determining how heavily to weight according to parsimony scores */
9369 // increaseProb = decreaseProb = mvp[1]; /* reweighting probabilities */
9370 // v_typical = mvp[2]; /* typical branch length for conversion of parsimony score to log prob ratio */
9371 tuning = mvp[3]; /* multiplier tuning parameter */
9372 nNeighbor = (int)mvp[4]; /* distance to move picked branch in root and crown part */
9374 (*lnProposalRatio) = (*lnPriorRatio) = 0.0;
9376 /* get model params and model info */
9377 mp = &modelParams[param->relParts[0]];
9378 m = &modelSettings[param->relParts[0]];
9381 t = GetTree (param, chain, state[chain]);
9383 /* max and min brlen */
9384 if (param->subParams[0]->paramId == BRLENS_UNI)
9386 minV = mp->brlensUni[0] > BRLENS_MIN ? mp->brlensUni[0] : BRLENS_MIN;
9387 maxV = mp->brlensUni[1] < BRLENS_MAX ? mp->brlensUni[1] : BRLENS_MAX;
9390 else if (param->subParams[0]->paramId == BRLENS_GamDir)
9396 else if (param->subParams[0]->paramId == BRLENS_iGmDir)
9402 else if (param->subParams[0]->paramId == BRLENS_twoExp)
9412 brlensExp = mp->brlensExp;
9416 /* Dirichlet or twoExp prior */
9417 if (isVPriorExp > 1)
9418 (*lnPriorRatio) = -LogDirPrior(t, mp, isVPriorExp);
9420 /* set topologyHasChanged to NO */
9421 topologyHasChanged = NO;
9423 /* pick a random branch */
9425 p = t->allDownPass[(int)(RandomNumber(seed) * (t->nNodes -1))];
9426 q = p->anc->right; if (q == p) q = p->anc->left;
9428 if (p->left == NULL)
9430 if (p->anc->anc == NULL)
9432 if (p->anc->anc != NULL && (p->anc->isLocked == YES || p->anc->anc->anc == NULL))
9434 if (p->anc->anc != NULL && (q->isLocked == YES || q->left == NULL))
9436 if (p->left != NULL && (p->left->isLocked == YES || p->left->left == NULL))
9438 if (p->left != NULL && (p->right->isLocked == YES || p->right->left == NULL))
9440 } while (i == 2 && j == 2);
9442 /* determine moving direction */
9447 else if (RandomNumber(seed) < 0.5)
9452 /* set up pointers for nodes around the picked branch */
9453 /* should never change u, v, a, b, c, d pointers */
9464 /* reset node variables that will be used */
9465 for (i=0; i<t->nNodes; i++)
9467 p = t->allDownPass[i];
9472 /* mark nodes nNeighbor away in root (negative) or crown (positive) respecting constraints */
9474 if (moveInRoot == YES)
9476 /* clip root part of tree */
9483 /* mark the root part */
9484 if (u->isLocked == NO )
9486 p = a; q = b; n = 0;
9487 while (q->anc != NULL)
9490 q->x = n; // temporary, for MarkDistance below
9492 MarkDistance(q->right, YES, nNeighbor, &nRoot);
9494 MarkDistance(q->left, YES, nNeighbor, &nRoot);
9495 q->x = --n; // final
9497 if (q->isLocked == YES || abs(q->x) >= nNeighbor)
9502 if (a->isLocked == NO)
9504 MarkDistance(a->left, YES, nNeighbor, &nRoot);
9505 MarkDistance(a->right, YES, nNeighbor, &nRoot);
9508 /* get final parsimony states for the root part */
9509 GetParsDP (t, t->root->left, chain);
9510 GetParsFP (t, t->root->left, chain);
9511 /* get final parsimony states for the crown part */
9512 GetParsDP (t, v, chain);
9513 GetParsFP (t, v, chain);
9515 else /* moveInRoot == NO */
9517 /* clip crown part of tree */
9521 /* mark the crown part */
9522 if (c->isLocked == NO)
9524 MarkDistance(c->left, NO, nNeighbor, &nCrown);
9525 MarkDistance(c->right, NO, nNeighbor, &nCrown);
9527 if (d->isLocked == NO)
9529 MarkDistance(d->left, NO, nNeighbor, &nCrown);
9530 MarkDistance(d->right, NO, nNeighbor, &nCrown);
9533 /* get final parsimony states for the root part */
9534 if (u->anc != NULL) {
9535 a->anc = b; /* clip */
9536 if (b->left == u) b->left = a;
9538 GetParsDP (t, t->root->left, chain);
9539 GetParsFP (t, t->root->left, chain);
9540 a->anc = u; /* change back */
9541 if (b->left == a) b->left = u;
9544 /* get final parsimony states for the crown part */
9545 GetParsDP (t, c, chain);
9546 GetParsDP (t, d, chain);
9547 GetParsFP (t, c, chain);
9548 GetParsFP (t, d, chain);
9551 /* find number of site patterns and modify randomly */
9552 globalNSitesOfPat = numSitesOfPat + (chainId[chain] % chainParams.numChains) * numCompressedChars + m->compCharStart;
9553 nSitesOfPat = (CLFlt *) SafeCalloc (numCompressedChars, sizeof(CLFlt));
9554 if (!nSitesOfPat) goto errorExit;
9555 for (i=0; i<numCompressedChars; i++)
9557 nSitesOfPat[i] = globalNSitesOfPat[i];
9558 /* for (j=0; j<globalNSitesOfPat[i]; j++)
9560 ran = RandomNumber(seed);
9561 if (ran < decreaseProb)
9563 else if (ran > 1.0 - increaseProb)
9565 } // this is slow at the moment */
9568 /* need to alloc a matrix for parsimony lengths, an array of pointers to crown part,
9569 and an array of pointers to root part. */
9570 parLength = (MrBFlt *) SafeCalloc ((size_t)nRoot * (size_t)nCrown, sizeof(MrBFlt));
9571 pRoot = (TreeNode **) SafeCalloc(nRoot, sizeof(TreeNode *));
9572 pCrown = (TreeNode **) SafeCalloc(nCrown, sizeof(TreeNode *));
9573 if (!parLength || !pRoot || !pCrown) goto errorExit;
9575 /* starting position */
9576 pRoot[0] = a; pCrown[0] = c;
9577 for (i=j=1, n=t->nNodes-2; n>=0; n--)
9578 { /* and the rest */
9579 p = t->allDownPass[n];
9580 if (p->marked == YES && p->x < 0)
9582 if (p->marked == YES && p->x > 0)
9585 assert (i==nRoot && j==nCrown);
9587 /* cycle through the possibilities and record the parsimony length */
9588 for (j=0; j<nCrown; j++)
9590 for (i=0; i<nRoot; i++)
9592 parLength[i+j*nRoot] = 0.0;
9593 for (n=0; n<t->nRelParts; n++)
9595 division = t->relParts[n];
9597 /* Find model settings */
9598 m = &modelSettings[division];
9600 /* find nSitesOfPat */
9601 nSites = nSitesOfPat + m->compCharStart;
9603 /* find parsimony length for each candidate position */
9605 if (moveInRoot == YES)
9607 pA = m->parsSets[pRoot[i]->index];
9608 pB = m->parsSets[pRoot[i]->anc->index];
9609 pP = m->parsSets[v->index];
9611 if (m->nParsIntsPerSite == 1)
9613 for (k=0; k<m->numChars; k++)
9615 y[0] = (pA[k] | pB[k]) & pP[k];
9617 length += nSites[k];
9620 else /* if (m->nParsIntsPerSite == 2) */
9622 for (k=0; k<2*m->numChars; k+=2)
9624 y[0] = (pA[k] | pB[k]) & pP[k];
9625 y[1] = (pA[k+1] | pB[k+1]) & pP[k+1];
9626 if ((y[0] | y[1]) == 0)
9627 length += nSites[k/2];
9631 else if (u->anc == NULL)
9633 pP = m->parsSets[u->index];
9634 pC = m->parsSets[pCrown[j]->index];
9635 pD = m->parsSets[pCrown[j]->anc->index];
9637 if (m->nParsIntsPerSite == 1)
9639 for (k=0; k<m->numChars; k++)
9641 y[0] = pP[k] & (pC[k] | pD[k]);
9643 length += nSites[k];
9646 else /* if (m->nParsIntsPerSite == 2) */
9648 for (k=0; k<2*m->numChars; k+=2)
9650 y[0] = pP[k] & (pC[k] | pD[k]);
9651 y[1] = pP[k+1] & (pC[k+1] | pD[k+1]);
9652 if ((y[0] | y[1]) == 0)
9653 length += nSites[k/2];
9659 pA = m->parsSets[a->index];
9660 pB = m->parsSets[b->index];
9661 pC = m->parsSets[pCrown[j]->index];
9662 pD = m->parsSets[pCrown[j]->anc->index];
9664 if (m->nParsIntsPerSite == 1)
9666 for (k=0; k<m->numChars; k++)
9668 y[0] = (pA[k] | pB[k]) & (pC[k] | pD[k]);
9670 length += nSites[k];
9673 else /* if (m->nParsIntsPerSite == 2) */
9675 for (k=0; k<2*m->numChars; k+=2)
9677 y[0] = (pA[k] | pB[k]) & (pC[k] | pD[k]);
9678 y[1] = (pA[k+1] | pB[k+1]) & (pC[k+1] | pD[k+1]);
9679 if ((y[0] | y[1]) == 0)
9680 length += nSites[k/2];
9685 /* get division warp factor */
9686 parLength[i+j*nRoot] += warpFactor * length;
9691 /* find the min length and the sum for the forward move */
9693 for (j=0; j<nCrown; j++)
9694 for (i=0; i<nRoot; i++)
9696 if (i == 0 && j == 0) // exclude original position
9698 if (minLength > parLength[i+j*nRoot] || minLength < 0.0)
9699 minLength = parLength[i+j*nRoot];
9701 sum1 = 0.0; tempc = 0.0;
9702 for (j=0; j<nCrown; j++)
9703 for (i=0; i<nRoot; i++)
9705 if (i == 0 && j == 0) // exclude original position
9707 /* Kahan summation to reduce numerical error */
9708 tempy = exp(minLength - parLength[i+j*nRoot]) - tempc;
9709 tempsum = sum1 + tempy; tempc = (tempsum - sum1) - tempy;
9711 // sum1 += exp(minLength - parLength[i+j*nRoot]);
9712 // printf("%d %d %lf\n", i, j, exp(minLength - parLength[i+j*nRoot]));
9715 /* generate a random uniform */
9716 ran = RandomNumber(seed) * sum1;
9718 /* select the appropriate reattachment point */
9720 prob = 0.0; tempc = 0.0;
9721 for (j=0; j<nCrown; j++)
9722 for (i=0; i<nRoot; i++)
9724 if (i == 0 && j == 0) // exclude original position
9726 // prob += exp (minLength - parLength[i+j*nRoot]);
9727 /* Kahan summation to reduce numerical error */
9728 tempy = exp(minLength - parLength[i+j*nRoot]) - tempc;
9729 tempsum = prob + tempy; tempc = (tempsum - prob) - tempy;
9732 /* proposed new attaching position */
9741 /* calculate the proposal ratio */
9742 (*lnProposalRatio) = parLength[i+j*nRoot] - minLength + log(sum1);
9744 /* find the min length and the sum for the backward move */
9746 for (j=0; j<nCrown; j++)
9747 for (i=0; i<nRoot; i++)
9749 if (i == iA && j == jC) // exclude new position
9751 if (minLength > parLength[i+j*nRoot] || minLength < 0.0)
9752 minLength = parLength[i+j*nRoot];
9754 sum2 = 0.0; tempc = 0.0;
9755 for (j=0; j<nCrown; j++)
9756 for (i=0; i<nRoot; i++)
9758 if (i == iA && j == jC) // exclude new position
9760 /* Kahan summation to reduce numerical error */
9761 tempy = exp(minLength - parLength[i+j*nRoot]) - tempc;
9762 tempsum = sum2 + tempy; tempc = (tempsum - sum2) - tempy;
9764 // sum2 += exp (minLength - parLength[i+j*nRoot]);
9765 // printf("%d %d %lf\n", i, j, exp(minLength - parLength[i+j*nRoot]));
9768 /* calculate the proposal ratio */
9769 (*lnProposalRatio) += minLength - parLength[0] - log(sum2);
9771 if (moveInRoot == YES) /* root part has changed */
9773 /* reattach the root part */
9781 if (newB->left == newA)
9786 /* if u is locked, then we have moved upwards and need to leave the u lock behind */
9787 if (u->isLocked == YES)
9791 a->lockID = u->lockID;
9796 while (p->anc != NULL)
9803 /* newA is descendant to a so move a->length not u->length */
9805 u->length = a->length;
9810 while (p->anc != NULL)
9812 if (p == newA) break;
9817 /* newA is ancestor to a so insert above instead of below */
9819 newA->length = u->length;
9821 /* newA is on root path and locked, we need to transfer lock to u */
9822 if (newA->isLocked == YES) {
9824 u->lockID = newA->lockID;
9825 newA->isLocked = NO;
9830 /* hit a length with multiplier */
9831 x = a->length * exp(tuning * (RandomNumber(seed) - 0.5));
9832 while (x < minV || x > maxV)
9834 if (x < minV) x = minV * minV / x;
9835 if (x > maxV) x = maxV * maxV / x;
9837 /* calculate proposal and prior ratio based on length modification */
9838 (*lnProposalRatio) += log (x / a->length);
9839 if (isVPriorExp == YES)
9840 (*lnPriorRatio) += brlensExp * (a->length - x);
9843 /* hit u length with multiplier */
9844 x = u->length * exp(tuning * (RandomNumber(seed) - 0.5));
9845 while (x < minV || x > maxV)
9847 if (x < minV) x = minV * minV / x;
9848 if (x > maxV) x = maxV * maxV / x;
9850 /* calculate proposal and prior ratio based on length modification */
9851 (*lnProposalRatio) += log (x / u->length);
9852 if (isVPriorExp == YES)
9853 (*lnPriorRatio) += brlensExp * (u->length - x);
9856 /* hit newA length with multiplier */
9857 x = newA->length * exp(tuning * (RandomNumber(seed) - 0.5));
9858 while (x < minV || x > maxV)
9860 if (x < minV) x = minV * minV / x;
9861 if (x > maxV) x = maxV * maxV / x;
9863 /* calculate proposal and prior ratio based on length modification */
9864 (*lnProposalRatio) += log (x / newA->length);
9865 if (isVPriorExp == YES)
9866 (*lnPriorRatio) += brlensExp * (newA->length - x);
9869 /* set tiprobs update flags */
9870 newA->upDateTi = YES;
9874 /* set flags for update of cond likes */
9876 while (p->anc != NULL)
9882 while (p->anc != NULL)
9889 if (moveInRoot == NO) /* crown part has changed */
9892 q = newB = newC->anc;
9893 /* rotate nodes from newC to c or d (whichever is closest) */
9895 while (r != c && r != d)
9898 /* rotate pointers of q */
9904 /* swap q and old */
9909 /* make sure we get q and r initialized for next round */
9913 newB->length = tempc;
9915 /* hit q length with multiplier while we are at it */
9916 x = q->length * exp(tuning * (RandomNumber(seed) - 0.5));
9917 while (x < minV || x > maxV)
9919 if (x < minV) x = minV * minV / x;
9920 if (x > maxV) x = maxV * maxV / x;
9922 /* calculate proposal and prior ratio based on length modification */
9923 (*lnProposalRatio) += log (x / q->length);
9924 if (isVPriorExp == YES)
9925 (*lnPriorRatio) += brlensExp * (q->length - x);
9929 /* hit newB length with multiplier */
9930 x = newB->length * exp(tuning * (RandomNumber(seed) - 0.5));
9931 while (x < minV || x > maxV)
9933 if (x < minV) x = minV * minV / x;
9934 if (x > maxV) x = maxV * maxV / x;
9936 /* calculate proposal and prior ratio based on length modification */
9937 (*lnProposalRatio) += log (x / newB->length);
9938 if (isVPriorExp == YES)
9939 (*lnPriorRatio) += brlensExp * (newB->length - x);
9941 newB->upDateTi = YES;
9943 /* hit newC length with multiplier */
9944 x = newC->length * exp(tuning * (RandomNumber(seed) - 0.5));
9945 while (x < minV || x > maxV)
9947 if (x < minV) x = minV * minV / x;
9948 if (x > maxV) x = maxV * maxV / x;
9950 /* calculate proposal and prior ratio based on length modification */
9951 (*lnProposalRatio) += log (x / newC->length);
9952 if (isVPriorExp == YES)
9953 (*lnPriorRatio) += brlensExp * (newC->length - x);
9955 newC->upDateTi = YES;
9957 /* reattach the crown part */
9960 newC->anc = newB->anc = v;
9962 /* set flags for update of cond likes */
9964 while (p->anc != NULL)
9970 while (p->anc != NULL)
9977 topologyHasChanged = YES;
9979 /* get down pass sequence if tree topology has changed */
9980 if (topologyHasChanged == YES)
9985 /* Dirichlet or twoExp prior */
9986 if (isVPriorExp > 1)
9987 (*lnPriorRatio) += LogDirPrior(t, mp, isVPriorExp);
9989 /* free up local memory */
9990 free (parLength); free (pRoot); free (pCrown); free (nSitesOfPat);
9995 MrBayesPrint ("%s Problem allocating memory in Move_ParsSPR\n", spacer);
9996 free (parLength); free (pRoot); free (pCrown); free (nSitesOfPat);
10002 int Move_ParsSPR2 (Param *param, int chain, RandLong *seed, MrBFlt *lnPriorRatio, MrBFlt *lnProposalRatio, MrBFlt *mvp)
10004 /* Change topology (and branch lengths) using SPR (symmetric) biased according to parsimony scores,
10005 controlled by a window defined by a certain node distance radius. Note: S/N */
10007 int i, j, k, n, division, topologyHasChanged, moveInRoot, nNeighbor, nRoot, nCrown, iA, jC, isVPriorExp;
10008 BitsLong *pA, *pB, *pP, *pC, *pD, y[2];
10009 MrBFlt x, minV, maxV, brlensExp=0.0, minLength=0.0, length=0.0, *parLength=NULL, prob, ran, tuning, warpFactor,
10010 v_typical, divFactor, nStates, sum1, sum2, tempsum, tempc, tempy;
10011 CLFlt *nSites, *nSitesOfPat=NULL, *globalNSitesOfPat;
10012 TreeNode *p, *q, *r, *a, *b, *u, *v, *c, *d, *newB, *newA, *newC, **pRoot=NULL, **pCrown=NULL;
10017 warpFactor = mvp[0]; /* tuning parameter determining how heavily to weight according to parsimony scores */
10018 // increaseProb = decreaseProb = mvp[1]; /* reweighting probabilities */
10019 v_typical = mvp[2]; /* typical branch length for conversion of parsimony score to log prob ratio */
10020 tuning = mvp[3]; /* multiplier tuning parameter */
10021 nNeighbor = (int)mvp[4]; /* distance to move picked branch in root and crown part */
10023 (*lnProposalRatio) = (*lnPriorRatio) = 0.0;
10025 /* get model params and model info */
10026 mp = &modelParams[param->relParts[0]];
10027 m = &modelSettings[param->relParts[0]];
10030 t = GetTree (param, chain, state[chain]);
10032 /* max and min brlen */
10033 if (param->subParams[0]->paramId == BRLENS_UNI)
10035 minV = mp->brlensUni[0] > BRLENS_MIN ? mp->brlensUni[0] : BRLENS_MIN;
10036 maxV = mp->brlensUni[1] < BRLENS_MAX ? mp->brlensUni[1] : BRLENS_MAX;
10039 else if (param->subParams[0]->paramId == BRLENS_GamDir)
10045 else if (param->subParams[0]->paramId == BRLENS_iGmDir)
10051 else if (param->subParams[0]->paramId == BRLENS_twoExp)
10061 brlensExp = mp->brlensExp;
10065 /* Dirichlet or twoExp prior */
10066 if (isVPriorExp > 1)
10067 (*lnPriorRatio) = -LogDirPrior(t, mp, isVPriorExp);
10069 /* set topologyHasChanged to NO */
10070 topologyHasChanged = NO;
10072 /* pick a random branch */
10074 p = t->allDownPass[(int)(RandomNumber(seed) * (t->nNodes -1))];
10075 q = p->anc->right; if (q == p) q = p->anc->left;
10077 if (p->left == NULL)
10079 if (p->anc->anc == NULL)
10081 if (p->anc->anc != NULL && (p->anc->isLocked == YES || p->anc->anc->anc == NULL))
10083 if (p->anc->anc != NULL && (q->isLocked == YES || q->left == NULL))
10085 if (p->left != NULL && (p->left->isLocked == YES || p->left->left == NULL))
10087 if (p->left != NULL && (p->right->isLocked == YES || p->right->left == NULL))
10089 } while (i == 2 && j == 2);
10091 /* pick an internal branch
10093 p = t->intDownPass[(int)(RandomNumber(seed)*(t->nIntNodes-1))];
10094 q = p->anc->left; if (q == p) q = p->anc->right;
10096 if (q->isLocked == YES || q->left == NULL)
10098 if (p->anc->isLocked == YES || p->anc->anc->anc == NULL)
10100 if (p->left->isLocked == YES || p->left->left == NULL)
10102 if (p->right->isLocked == YES || p->right->left == NULL)
10104 } while (i == 2 && j == 2);
10107 /* determine moving direction */
10112 else if (RandomNumber(seed) < 0.5)
10117 /* set up pointers for nodes around the picked branch */
10118 /* should never change u, v, a, b, c, d pointers */
10129 /* reset node variables that will be used */
10130 for (i=0; i<t->nNodes; i++)
10132 p = t->allDownPass[i];
10137 /* mark nodes nNeighbor away in root (negative) or crown (positive) respecting constraints */
10138 nRoot = nCrown = 1;
10139 if (moveInRoot == YES)
10141 /* clip root part of tree */
10148 /* mark the root part */
10149 if (u->isLocked == NO )
10151 p = a; q = b; n = 0;
10152 while (q->anc != NULL)
10155 q->x = n; // temporary, for MarkDistance below
10157 MarkDistance(q->right, YES, nNeighbor, &nRoot);
10159 MarkDistance(q->left, YES, nNeighbor, &nRoot);
10160 q->x = --n; // final
10162 if (q->isLocked == YES || abs(q->x) >= nNeighbor)
10167 if (a->isLocked == NO)
10169 MarkDistance(a->left, YES, nNeighbor, &nRoot);
10170 MarkDistance(a->right, YES, nNeighbor, &nRoot);
10173 /* get final parsimony states for the root part */
10174 GetParsDP (t, t->root->left, chain);
10175 GetParsFP (t, t->root->left, chain);
10176 /* get final parsimony states for the crown part */
10177 GetParsDP (t, v, chain);
10178 GetParsFP (t, v, chain);
10180 else /* moveInRoot == NO */
10182 /* clip crown part of tree */
10186 /* mark the crown part */
10187 if (c->isLocked == NO)
10189 MarkDistance(c->left, NO, nNeighbor, &nCrown);
10190 MarkDistance(c->right, NO, nNeighbor, &nCrown);
10192 if (d->isLocked == NO)
10194 MarkDistance(d->left, NO, nNeighbor, &nCrown);
10195 MarkDistance(d->right, NO, nNeighbor, &nCrown);
10198 /* get final parsimony states for the root part */
10199 if (u->anc != NULL) {
10200 a->anc = b; /* clip */
10201 if (b->left == u) b->left = a;
10203 GetParsDP (t, t->root->left, chain);
10204 GetParsFP (t, t->root->left, chain);
10205 a->anc = u; /* change back */
10206 if (b->left == a) b->left = u;
10209 /* get final parsimony states for the crown part */
10210 GetParsDP (t, c, chain);
10211 GetParsDP (t, d, chain);
10212 GetParsFP (t, c, chain);
10213 GetParsFP (t, d, chain);
10216 /* find number of site patterns and modify randomly */
10217 globalNSitesOfPat = numSitesOfPat + (chainId[chain] % chainParams.numChains) * numCompressedChars + m->compCharStart;
10218 nSitesOfPat = (CLFlt *) SafeCalloc (numCompressedChars, sizeof(CLFlt));
10219 if (!nSitesOfPat) goto errorExit;
10220 for (i=0; i<numCompressedChars; i++)
10222 nSitesOfPat[i] = globalNSitesOfPat[i];
10223 /* for (j=0; j<globalNSitesOfPat[i]; j++)
10225 ran = RandomNumber(seed);
10226 if (ran < decreaseProb)
10228 else if (ran > 1.0 - increaseProb)
10230 } // this is slow at the moment */
10233 /* need to alloc a matrix for parsimony lengths, an array of pointers to crown part,
10234 and an array of pointers to root part. */
10235 parLength = (MrBFlt *) SafeCalloc ((size_t)nRoot * (size_t)nCrown, sizeof(MrBFlt));
10236 pRoot = (TreeNode **) SafeCalloc(nRoot, sizeof(TreeNode *));
10237 pCrown = (TreeNode **) SafeCalloc(nCrown, sizeof(TreeNode *));
10238 if (!parLength || !pRoot || !pCrown) goto errorExit;
10240 /* starting position */
10241 pRoot[0] = a; pCrown[0] = c;
10242 for (i=j=1, n=t->nNodes-2; n>=0; n--)
10243 { /* and the rest */
10244 p = t->allDownPass[n];
10245 if (p->marked == YES && p->x < 0)
10247 if (p->marked == YES && p->x > 0)
10250 assert (i==nRoot && j==nCrown);
10252 /* cycle through the possibilities and record the parsimony length */
10253 for (j=0; j<nCrown; j++)
10255 for (i=0; i<nRoot; i++)
10257 parLength[i+j*nRoot] = 0.0;
10258 for (n=0; n<t->nRelParts; n++)
10260 division = t->relParts[n];
10262 /* Find model settings */
10263 m = &modelSettings[division];
10265 /* find nSitesOfPat */
10266 nSites = nSitesOfPat + m->compCharStart;
10268 /* find parsimony length for each candidate position */
10270 if (moveInRoot == YES)
10272 pA = m->parsSets[pRoot[i]->index];
10273 pB = m->parsSets[pRoot[i]->anc->index];
10274 pP = m->parsSets[v->index];
10276 if (m->nParsIntsPerSite == 1)
10278 for (k=0; k<m->numChars; k++)
10280 y[0] = (pA[k] | pB[k]) & pP[k];
10282 length += nSites[k];
10285 else /* if (m->nParsIntsPerSite == 2) */
10287 for (k=0; k<2*m->numChars; k+=2)
10289 y[0] = (pA[k] | pB[k]) & pP[k];
10290 y[1] = (pA[k+1] | pB[k+1]) & pP[k+1];
10291 if ((y[0] | y[1]) == 0)
10292 length += nSites[k/2];
10296 else if (u->anc == NULL)
10298 pP = m->parsSets[u->index];
10299 pC = m->parsSets[pCrown[j]->index];
10300 pD = m->parsSets[pCrown[j]->anc->index];
10302 if (m->nParsIntsPerSite == 1)
10304 for (k=0; k<m->numChars; k++)
10306 y[0] = pP[k] & (pC[k] | pD[k]);
10308 length += nSites[k];
10311 else /* if (m->nParsIntsPerSite == 2) */
10313 for (k=0; k<2*m->numChars; k+=2)
10315 y[0] = pP[k] & (pC[k] | pD[k]);
10316 y[1] = pP[k+1] & (pC[k+1] | pD[k+1]);
10317 if ((y[0] | y[1]) == 0)
10318 length += nSites[k/2];
10324 pA = m->parsSets[a->index];
10325 pB = m->parsSets[b->index];
10326 pC = m->parsSets[pCrown[j]->index];
10327 pD = m->parsSets[pCrown[j]->anc->index];
10329 if (m->nParsIntsPerSite == 1)
10331 for (k=0; k<m->numChars; k++)
10333 y[0] = (pA[k] | pB[k]) & (pC[k] | pD[k]);
10335 length += nSites[k];
10338 else /* if (m->nParsIntsPerSite == 2) */
10340 for (k=0; k<2*m->numChars; k+=2)
10342 y[0] = (pA[k] | pB[k]) & (pC[k] | pD[k]);
10343 y[1] = (pA[k+1] | pB[k+1]) & (pC[k+1] | pD[k+1]);
10344 if ((y[0] | y[1]) == 0)
10345 length += nSites[k/2];
10350 /* find nStates and ratemult */
10351 nStates = m->numModelStates;
10352 if (m->dataType == STANDARD)
10354 v_typical = length/m->numUncompressedChars + 0.0001;
10356 /* get division warp factor (prop. to prob. of change) */
10357 divFactor = - warpFactor * log(1.0/nStates - exp(-nStates/(nStates-1)*v_typical)/nStates);
10358 parLength[i+j*nRoot] += divFactor * length;
10363 /* find the min length and the sum for the forward move */
10365 for (j=0; j<nCrown; j++)
10366 for (i=0; i<nRoot; i++)
10368 if (i == 0 && j == 0) // exclude original position
10370 if (minLength > parLength[i+j*nRoot] || minLength < 0.0)
10371 minLength = parLength[i+j*nRoot];
10373 sum1 = 0.0; tempc = 0.0;
10374 for (j=0; j<nCrown; j++)
10375 for (i=0; i<nRoot; i++)
10377 if (i == 0 && j == 0) // exclude original position
10379 /* Kahan summation to reduce numerical error */
10380 tempy = exp(minLength - parLength[i+j*nRoot]) - tempc;
10381 tempsum = sum1 + tempy; tempc = (tempsum - sum1) - tempy;
10383 // sum1 += exp(minLength - parLength[i+j*nRoot]);
10384 // printf("%d %d %lf\n", i, j, exp(minLength - parLength[i+j*nRoot]));
10387 /* generate a random uniform */
10388 ran = RandomNumber(seed) * sum1;
10390 /* select the appropriate reattachment point */
10391 newA = a; newC = c;
10392 prob = 0.0; tempc = 0.0;
10393 for (j=0; j<nCrown; j++)
10394 for (i=0; i<nRoot; i++)
10396 if (i == 0 && j == 0) // exclude original position
10398 // prob += exp (minLength - parLength[i+j*nRoot]);
10399 /* Kahan summation to reduce numerical error */
10400 tempy = exp(minLength - parLength[i+j*nRoot]) - tempc;
10401 tempsum = prob + tempy; tempc = (tempsum - prob) - tempy;
10404 /* proposed new attaching position */
10413 /* calculate the proposal ratio */
10414 (*lnProposalRatio) = parLength[i+j*nRoot] - minLength + log(sum1);
10416 /* find the min length and the sum for the backward move */
10418 for (j=0; j<nCrown; j++)
10419 for (i=0; i<nRoot; i++)
10421 if (i == iA && j == jC) // exclude new position
10423 if (minLength > parLength[i+j*nRoot] || minLength < 0.0)
10424 minLength = parLength[i+j*nRoot];
10426 sum2 = 0.0; tempc = 0.0;
10427 for (j=0; j<nCrown; j++)
10428 for (i=0; i<nRoot; i++)
10430 if (i == iA && j == jC) // exclude new position
10432 /* Kahan summation to reduce numerical error */
10433 tempy = exp(minLength - parLength[i+j*nRoot]) - tempc;
10434 tempsum = sum2 + tempy; tempc = (tempsum - sum2) - tempy;
10436 // sum2 += exp (minLength - parLength[i+j*nRoot]);
10437 // printf("%d %d %lf\n", i, j, exp(minLength - parLength[i+j*nRoot]));
10440 /* calculate the proposal ratio */
10441 (*lnProposalRatio) += minLength - parLength[0] - log(sum2);
10443 if (moveInRoot == YES) /* root part has changed */
10445 /* reattach the root part */
10453 if (newB->left == newA)
10458 /* if u is locked, then we have moved upwards and need to leave the u lock behind */
10459 if (u->isLocked == YES)
10463 a->lockID = u->lockID;
10468 while (p->anc != NULL)
10475 /* newA is descendant to a so move a->length not u->length */
10477 u->length = a->length;
10482 while (p->anc != NULL)
10484 if (p == newA) break;
10489 /* newA is ancestor to a so insert above instead of below */
10491 newA->length = u->length;
10493 /* newA is on root path and locked, we need to transfer lock to u */
10494 if (newA->isLocked == YES) {
10496 u->lockID = newA->lockID;
10497 newA->isLocked = NO;
10502 /* hit a length with multiplier */
10503 x = a->length * exp(tuning * (RandomNumber(seed) - 0.5));
10504 while (x < minV || x > maxV)
10506 if (x < minV) x = minV * minV / x;
10507 if (x > maxV) x = maxV * maxV / x;
10509 /* calculate proposal and prior ratio based on length modification */
10510 (*lnProposalRatio) += log (x / a->length);
10511 if (isVPriorExp == YES)
10512 (*lnPriorRatio) += brlensExp * (a->length - x);
10515 /* hit u length with multiplier */
10516 x = u->length * exp(tuning * (RandomNumber(seed) - 0.5));
10517 while (x < minV || x > maxV)
10519 if (x < minV) x = minV * minV / x;
10520 if (x > maxV) x = maxV * maxV / x;
10522 /* calculate proposal and prior ratio based on length modification */
10523 (*lnProposalRatio) += log (x / u->length);
10524 if (isVPriorExp == YES)
10525 (*lnPriorRatio) += brlensExp * (u->length - x);
10528 /* hit newA length with multiplier */
10529 x = newA->length * exp(tuning * (RandomNumber(seed) - 0.5));
10530 while (x < minV || x > maxV)
10532 if (x < minV) x = minV * minV / x;
10533 if (x > maxV) x = maxV * maxV / x;
10535 /* calculate proposal and prior ratio based on length modification */
10536 (*lnProposalRatio) += log (x / newA->length);
10537 if (isVPriorExp == YES)
10538 (*lnPriorRatio) += brlensExp * (newA->length - x);
10541 /* set tiprobs update flags */
10542 newA->upDateTi = YES;
10546 /* set flags for update of cond likes */
10548 while (p->anc != NULL)
10554 while (p->anc != NULL)
10561 if (moveInRoot == NO) /* crown part has changed */
10564 q = newB = newC->anc;
10565 /* rotate nodes from newC to c or d (whichever is closest) */
10567 while (r != c && r != d)
10570 /* rotate pointers of q */
10576 /* swap q and old */
10581 /* make sure we get q and r initialized for next round */
10585 newB->length = tempc;
10587 /* hit q length with multiplier while we are at it */
10588 x = q->length * exp(tuning * (RandomNumber(seed) - 0.5));
10589 while (x < minV || x > maxV)
10591 if (x < minV) x = minV * minV / x;
10592 if (x > maxV) x = maxV * maxV / x;
10594 /* calculate proposal and prior ratio based on length modification */
10595 (*lnProposalRatio) += log (x / q->length);
10596 if (isVPriorExp == YES)
10597 (*lnPriorRatio) += brlensExp * (q->length - x);
10601 /* hit newB length with multiplier */
10602 x = newB->length * exp(tuning * (RandomNumber(seed) - 0.5));
10603 while (x < minV || x > maxV)
10605 if (x < minV) x = minV * minV / x;
10606 if (x > maxV) x = maxV * maxV / x;
10608 /* calculate proposal and prior ratio based on length modification */
10609 (*lnProposalRatio) += log (x / newB->length);
10610 if (isVPriorExp == YES)
10611 (*lnPriorRatio) += brlensExp * (newB->length - x);
10613 newB->upDateTi = YES;
10615 /* hit newC length with multiplier */
10616 x = newC->length * exp(tuning * (RandomNumber(seed) - 0.5));
10617 while (x < minV || x > maxV)
10619 if (x < minV) x = minV * minV / x;
10620 if (x > maxV) x = maxV * maxV / x;
10622 /* calculate proposal and prior ratio based on length modification */
10623 (*lnProposalRatio) += log (x / newC->length);
10624 if (isVPriorExp == YES)
10625 (*lnPriorRatio) += brlensExp * (newC->length - x);
10627 newC->upDateTi = YES;
10629 /* reattach the crown part */
10632 newC->anc = newB->anc = v;
10634 /* set flags for update of cond likes */
10636 while (p->anc != NULL)
10642 while (p->anc != NULL)
10649 topologyHasChanged = YES;
10651 /* get down pass sequence if tree topology has changed */
10652 if (topologyHasChanged == YES)
10657 /* Dirichlet or twoExp prior */
10658 if (isVPriorExp > 1)
10659 (*lnPriorRatio) += LogDirPrior(t, mp, isVPriorExp);
10661 /* free up local memory */
10662 free (parLength); free (pRoot); free (pCrown); free (nSitesOfPat);
10667 MrBayesPrint ("%s Problem allocating memory in Move_ParsSPR\n", spacer);
10668 free (parLength); free (pRoot); free (pCrown); free (nSitesOfPat);
10674 int Move_ParsSPRClock (Param *param, int chain, RandLong *seed, MrBFlt *lnPriorRatio, MrBFlt *lnProposalRatio, MrBFlt *mvp)
10676 /* Change branch lengths and topology (potentially) using SPR-type move, parsimony-biased */
10678 /* This move picks a branch and then chooses a reattachment point based on
10679 the parsimony score. On the ending branch, the attachment point is reinserted
10680 randomly along the branch (below the minimum age of the node). Since 2010-11-02
10681 the move is Metropolized to improve efficiency. */
10683 int i, j, n, division, n1=0, n2=0, n3=0, n4=0, n5=0, *nEvents;
10684 BitsLong *pA, *pV, *pP, y[2];
10685 MrBFlt x, oldBrlen=0.0, newBrlen=0.0, v1=0.0, v2=0.0, v3=0.0, v4=0.0, v5=0.0,
10686 v3new=0.0, lambda, **position=NULL, **rateMultiplier=NULL, *brlens,
10687 igrvar, *igrRate=NULL, nu, *tk02Rate=NULL, minLength=0.0, length=0.0,
10688 cumulativeProb, warpFactor, sum1, sum2, ran, increaseProb, decreaseProb,
10689 divFactor, nStates, rateMult, v_typical, minV;
10690 CLFlt *nSitesOfPat, *nSites, *globalNSitesOfPat;
10691 TreeNode *p, *a, *b, *u, *v, *c=NULL, *d;
10696 warpFactor = mvp[0]; /* tuning parameter determining how heavily to weight according to parsimony scores */
10697 increaseProb = decreaseProb = mvp[1]; /* reweighting probabilities */
10698 v_typical = mvp[2]; /* typical branch length for converting parsimony scores to log prob ratios */
10700 (*lnProposalRatio) = (*lnPriorRatio) = 0.0;
10703 t = GetTree (param, chain, state[chain]);
10705 /* get model params and model info */
10706 m = &modelSettings[param->relParts[0]];
10708 /* get min and max brlen in relative time and subst units */
10711 # if defined (DEBUG_ParsSPRClock)
10712 printf ("Before:\n");
10713 ShowNodes (t->root, 2, YES);
10717 /* pick a branch */
10719 p = t->allDownPass[(int)(RandomNumber(seed) * (t->nNodes - 2))];
10723 while (p->anc->isLocked == YES || p->anc->anc->anc == NULL
10724 || (p == b && a->length < TIME_MIN) || (p == a && b->length < TIME_MIN));
10725 /* skip constraints, siblings of root (and root); and consider ancestral fossils in fbd tree */
10727 /* set up pointers for nodes around the picked branch */
10736 /* record branch length for insertion in back move */
10737 if (v->length > 0.0) /* side branch, not anc fossil */
10739 if (v->nodeDepth > a->nodeDepth)
10740 oldBrlen = b->nodeDepth - v->nodeDepth - 2.0*minV;
10742 oldBrlen = b->nodeDepth - a->nodeDepth - 2.0*minV;
10748 /* reassign events for CPP and adjust prior and proposal ratios for relaxed clock models */
10749 for (i=0; i<param->subParams[0]->nSubParams; i++)
10751 subParm = param->subParams[0]->subParams[i];
10752 if (subParm->paramType == P_CPPEVENTS)
10754 nEvents = subParm->nEvents[2*chain+state[chain]];
10755 position = subParm->position[2*chain+state[chain]];
10756 rateMultiplier = subParm->rateMult[2*chain+state[chain]];
10757 n1 = nEvents[a->index];
10758 n2 = nEvents[u->index];
10759 n3 = nEvents[v->index];
10762 position[a->index] = (MrBFlt *) SafeRealloc ((void *) position[a->index], (n1+n2) * sizeof (MrBFlt));
10763 rateMultiplier[a->index] = (MrBFlt *) SafeRealloc ((void *) rateMultiplier[a->index], (n1+n2) * sizeof (MrBFlt));
10765 for (j=0; j<n1; j++)
10766 position[a->index][j] *= v1 / (v1+v2);
10767 for (j=n1; j<n1+n2; j++)
10769 position[a->index][j] = (position[u->index][j-n1] * v2 + v1) / (v1+v2);
10770 rateMultiplier[a->index][j] = rateMultiplier[u->index][j-n1];
10772 nEvents[a->index] = n1+n2;
10773 nEvents[u->index] = 0;
10776 free (position[u->index]);
10777 free (rateMultiplier[u->index]);
10778 position[u->index] = rateMultiplier[u->index] = NULL;
10780 /* adjust effective branch lengths */
10781 brlens = GetParamSubVals (subParm, chain, state[chain]);
10782 brlens[a->index] += brlens[u->index]; /* only change in effective branch lengths so far */
10783 } /* end CPP events parm */
10784 else if ( subParm->paramType == P_TK02BRANCHRATES ||
10785 (subParm->paramType == P_MIXEDBRCHRATES && *GetParamIntVals(subParm, chain, state[chain]) == RCL_TK02))
10787 /* adjust prior ratio */
10788 if (subParm->paramType == P_TK02BRANCHRATES)
10789 nu = *GetParamVals (modelSettings[subParm->relParts[0]].tk02var, chain, state[chain]);
10791 nu = *GetParamVals (modelSettings[subParm->relParts[0]].mixedvar, chain, state[chain]);
10792 tk02Rate = GetParamVals (subParm, chain, state[chain]);
10793 if (v->length > 0.0)
10794 (*lnPriorRatio) -= LnProbTK02LogNormal(tk02Rate[v->anc->index], nu*v->length, tk02Rate[v->index]);
10795 (*lnPriorRatio) -= LnProbTK02LogNormal(tk02Rate[a->anc->index], nu*a->length, tk02Rate[a->index]);
10796 (*lnPriorRatio) -= LnProbTK02LogNormal(tk02Rate[u->anc->index], nu*u->length, tk02Rate[u->index]);
10797 (*lnPriorRatio) += LnProbTK02LogNormal(tk02Rate[u->anc->index], nu*(a->length+u->length), tk02Rate[a->index]);
10799 /* adjust effective branch lengths */
10800 brlens = GetParamSubVals (subParm, chain, state[chain]);
10801 brlens[a->index] = (tk02Rate[a->index] + tk02Rate[b->index]) / 2.0 * (a->length + u->length);
10802 } /* end tk02 branch rate parameter */
10803 else if ( subParm->paramType == P_IGRBRANCHRATES ||
10804 (subParm->paramType == P_MIXEDBRCHRATES && *GetParamIntVals(subParm, chain, state[chain]) == RCL_IGR))
10806 if (subParm->paramType == P_IGRBRANCHRATES)
10807 igrvar = *GetParamVals (modelSettings[subParm->relParts[0]].igrvar, chain, state[chain]);
10809 igrvar = *GetParamVals (modelSettings[subParm->relParts[0]].mixedvar, chain, state[chain]);
10810 igrRate = GetParamVals (subParm, chain, state[chain]);
10812 /* adjust prior ratio for old branches */
10813 if (v->length > 0.0)
10814 (*lnPriorRatio) -= LnProbGamma(v->length/igrvar, v->length/igrvar, igrRate[v->index]);
10815 (*lnPriorRatio) -= LnProbGamma(a->length/igrvar, a->length/igrvar, igrRate[a->index]);
10816 (*lnPriorRatio) -= LnProbGamma(u->length/igrvar, u->length/igrvar, igrRate[u->index]);
10817 (*lnPriorRatio) += LnProbGamma((a->length+u->length)/igrvar, (a->length+u->length)/igrvar, igrRate[a->index]);
10819 /* adjust effective branch lengths */
10820 brlens = GetParamSubVals (subParm, chain, state[chain]);
10821 brlens[a->index] = igrRate[a->index] * (a->length + u->length);
10823 } /* next subparameter */
10831 a->length += u->length;
10834 /* get final parsimony states for the root part */
10835 GetParsDP (t, t->root->left, chain);
10836 GetParsFP (t, t->root->left->left, chain);
10837 GetParsFP (t, t->root->left->right, chain);
10839 /* get downpass parsimony states for the crown part */
10840 GetParsDP (t, v, chain);
10842 /* reset node variables that will be used */
10843 for (i=0; i<t->nNodes; i++)
10845 p = t->allDownPass[i];
10850 /* mark nodes in the root part of the tree, first mark a */
10852 /* then move down towards root taking constraints into account */
10854 while (p->isLocked == NO && p->anc->anc != NULL)
10859 /* make sure sisters of last node are marked otherwise it will not be marked in the uppass */
10860 p->left->marked = YES;
10861 p->right->marked = YES;
10862 /* finally move up, skip constraints and ancestral fossil */
10863 for (i=t->nNodes-2; i>=0; i--)
10865 p = t->allDownPass[i];
10866 if (p != u && p->marked == NO && p->anc->marked == YES && p->anc->isLocked == NO
10867 && p->anc->nodeDepth > v->nodeDepth + minV && p->length > 0.0)
10871 /* unmark nodes if the picked branch is 0 (ancestral fossil) */
10872 if (v->length < TIME_MIN)
10875 for (i=0; i<t->nNodes-1; i++)
10877 p = t->allDownPass[i];
10878 if (p->nodeDepth > v->nodeDepth - minV || p->anc->nodeDepth < v->nodeDepth + minV)
10880 if (p->marked == YES)
10883 if (n < 2) /* no new position to move */
10890 /* find number of site patterns and modify randomly */
10891 globalNSitesOfPat = numSitesOfPat + (chainId[chain] % chainParams.numChains) * numCompressedChars + m->compCharStart;
10892 nSitesOfPat = (CLFlt *) SafeCalloc (numCompressedChars, sizeof(CLFlt));
10895 MrBayesPrint ("%s Problem allocating nSitesOfPat in Move_ParsSPRClock\n", spacer);
10898 for (i=0; i<numCompressedChars; i++)
10900 nSitesOfPat[i] = globalNSitesOfPat[i];
10901 for (j=0; j<globalNSitesOfPat[i]; j++)
10903 ran = RandomNumber(seed);
10904 if (ran < decreaseProb)
10906 else if (ran > 1.0 - increaseProb)
10911 /* cycle through the possibilities and record the parsimony length */
10912 for (i=0; i<t->nNodes; i++)
10914 p = t->allDownPass[i];
10915 if (p->marked == NO)
10917 /* find the parsimony length */
10919 for (n=0; n<t->nRelParts; n++)
10921 division = t->relParts[n];
10923 /* Find model settings */
10924 m = &modelSettings[division];
10926 /* find nStates and ratemult */
10927 nStates = m->numModelStates;
10928 if (m->dataType == STANDARD)
10930 rateMult = GetRate(division, chain);
10932 /* find nSitesOfPat */
10933 nSites = nSitesOfPat + m->compCharStart;
10935 /* get division warp factor */
10936 divFactor = - warpFactor * log((1.0/nStates) - exp(-nStates/(nStates-1)*v_typical*rateMult)/nStates);
10938 /* find downpass parsimony sets for the node and its environment */
10939 pP = m->parsSets[p->index ];
10940 pA = m->parsSets[p->anc->index];
10941 pV = m->parsSets[v->index ];
10944 if (m->nParsIntsPerSite == 1)
10946 for (j=0; j<m->numChars; j++)
10948 y[0] = (pP[j] | pA[j]) & pV[j];
10950 length += nSites[j];
10953 else /* if (m->nParsIntsPerSite == 2) */
10955 for (j=0; j<2*m->numChars; j+=2)
10957 y[0] = (pP[j] | pA[j]) & pV[j];
10958 y[1] = (pP[j+1] | pA[j+1]) & pV[j+1];
10959 if ((y[0] | y[1]) == 0)
10960 length += nSites[j/2];
10963 p->d += divFactor * length;
10967 /* find the min length and the sum for the forward move */
10969 for (i=0; i<t->nNodes; i++)
10971 p = t->allDownPass[i];
10972 if (p->marked == NO || p == a)
10974 if (minLength < 0.0 || p->d < minLength)
10978 for (i=0; i<t->nNodes; i++)
10980 p = t->allDownPass[i];
10981 if (p->marked == YES && p != a)
10982 sum1 += exp (minLength - p->d);
10985 /* generate a random uniform */
10986 ran = RandomNumber(seed) * sum1;
10988 /* select the appropriate reattachment point (not a!) */
10989 cumulativeProb = 0.0;
10990 for (i=0; i<t->nNodes; i++)
10992 p = t->allDownPass[i];
10993 if (p->marked == YES && p != a)
10996 cumulativeProb += exp (minLength - p->d);
10997 if (cumulativeProb > ran)
11002 /* calculate the proposal ratio */
11003 (*lnProposalRatio) = c->d - minLength + log(sum1);
11005 /* find the min length and the sum for the backward move */
11007 for (i=0; i<t->nNodes; i++)
11009 p = t->allDownPass[i];
11010 if (p->marked == NO || p == c)
11012 if (minLength < 0.0 || p->d < minLength)
11016 for (i=0; i<t->nNodes; i++)
11018 p = t->allDownPass[i];
11019 if (p->marked == YES && p != c)
11020 sum2 += exp (minLength - p->d);
11023 /* calculate the proposal ratio */
11024 (*lnProposalRatio) += minLength - a->d - log(sum2);
11039 if (v->length > 0.0) /* side branch, not anc fossil */
11041 if (c->nodeDepth > v->nodeDepth)
11042 newBrlen = d->nodeDepth - c->nodeDepth - 2.0*minV;
11044 newBrlen = d->nodeDepth - v->nodeDepth - 2.0*minV;
11045 if (newBrlen <= 0.0)
11048 free (nSitesOfPat);
11052 /* adjust lengths */
11053 u->nodeDepth = d->nodeDepth - minV - RandomNumber(seed) * newBrlen;
11054 v->length = u->nodeDepth - v->nodeDepth;
11056 /* calculate proposal ratio for tree change */
11057 (*lnProposalRatio) += log (newBrlen / oldBrlen);
11059 u->length = d->nodeDepth - u->nodeDepth;
11060 c->length = u->nodeDepth - c->nodeDepth;
11066 /* reassign events for CPP and adjust prior and proposal ratios for relaxed clock models */
11067 for (i=0; i<param->subParams[0]->nSubParams; i++)
11069 subParm = param->subParams[0]->subParams[i];
11070 if (subParm->paramType == P_CPPEVENTS)
11072 nEvents = subParm->nEvents[2*chain+state[chain]];
11073 position = subParm->position[2*chain+state[chain]];
11074 rateMultiplier = subParm->rateMult[2*chain+state[chain]];
11075 for (j=0; j<nEvents[c->index]; j++)
11077 if (position[c->index][j] > v4 / (v4+v5))
11081 n5 = nEvents[c->index] - j;
11082 nEvents[u->index] = n5;
11085 position[u->index] = (MrBFlt *) SafeRealloc ((void *) position[u->index], n5 * sizeof (MrBFlt));
11086 rateMultiplier[u->index] = (MrBFlt *) SafeRealloc ((void *) rateMultiplier[u->index], n5 * sizeof (MrBFlt));
11087 for (j=n4; j<nEvents[c->index]; j++)
11089 position[u->index][j-n4] = (position[c->index][j] * (v4+v5) - v4) / v5;
11090 rateMultiplier[u->index][j-n4] = rateMultiplier[c->index][j];
11094 position[c->index] = (MrBFlt *) SafeRealloc ((void *) position[c->index], n4 * sizeof (MrBFlt));
11095 rateMultiplier[c->index] = (MrBFlt *) SafeRealloc ((void *) rateMultiplier[c->index], n4 * sizeof (MrBFlt));
11096 for (j=0; j<n4; j++)
11097 position[c->index][j] *= ((v4+v5) / v4);
11101 free (position[c->index]);
11102 free (rateMultiplier[c->index]);
11103 position[c->index] = rateMultiplier[c->index] = NULL;
11105 nEvents[c->index] = n4;
11109 for (j=0; j<nEvents[c->index]; j++)
11110 position[c->index][j] *= ((v4+v5) / v4);
11113 /* adjust proposal ratio */
11114 (*lnProposalRatio) += n3 * log (v3new / v3);
11116 /* adjust prior ratio */
11117 lambda = *GetParamVals (modelSettings[subParm->relParts[0]].cppRate, chain, state[chain]);
11118 (*lnPriorRatio) += lambda * (v3 - v3new);
11120 /* update effective branch lengths */
11121 if (UpdateCppEvolLengths (subParm, a, chain) == ERROR)
11124 free (nSitesOfPat);
11128 if (UpdateCppEvolLengths (subParm, u, chain) == ERROR)
11131 free (nSitesOfPat);
11134 } /* end cpp events parameter */
11135 else if ( subParm->paramType == P_TK02BRANCHRATES ||
11136 (subParm->paramType == P_MIXEDBRCHRATES && *GetParamIntVals(subParm, chain, state[chain]) == RCL_TK02))
11138 /* adjust prior ratio */
11139 if (subParm->paramType == P_TK02BRANCHRATES)
11140 nu = *GetParamVals (modelSettings[subParm->relParts[0]].tk02var, chain, state[chain]);
11142 nu = *GetParamVals (modelSettings[subParm->relParts[0]].mixedvar, chain, state[chain]);
11143 tk02Rate = GetParamVals (subParm, chain, state[chain]);
11144 (*lnPriorRatio) -= LnProbTK02LogNormal(tk02Rate[u->anc->index], nu*(c->length+u->length), tk02Rate[c->index]);
11145 (*lnPriorRatio) += LnProbTK02LogNormal(tk02Rate[c->anc->index], nu*c->length, tk02Rate[c->index]);
11146 (*lnPriorRatio) += LnProbTK02LogNormal(tk02Rate[u->anc->index], nu*u->length, tk02Rate[u->index]);
11147 if (v->length > 0.0)
11148 (*lnPriorRatio) += LnProbTK02LogNormal(tk02Rate[v->anc->index], nu*v->length, tk02Rate[v->index]);
11150 /* adjust effective branch lengths */
11151 brlens = GetParamSubVals (subParm, chain, state[chain]);
11152 brlens[c->index] = c->length * (tk02Rate[c->index] + tk02Rate[c->anc->index]) / 2.0;
11153 brlens[v->index] = v->length * (tk02Rate[v->index] + tk02Rate[v->anc->index]) / 2.0;
11154 brlens[u->index] = u->length * (tk02Rate[u->index] + tk02Rate[u->anc->index]) / 2.0;
11155 } /* end tk02 branch rate parameter */
11156 else if ( subParm->paramType == P_IGRBRANCHRATES ||
11157 (subParm->paramType == P_MIXEDBRCHRATES && *GetParamIntVals(subParm, chain, state[chain]) == RCL_IGR))
11159 /* adjust prior ratio */
11160 if (subParm->paramType == P_IGRBRANCHRATES)
11161 igrvar = *GetParamVals (modelSettings[subParm->relParts[0]].igrvar, chain, state[chain]);
11163 igrvar = *GetParamVals (modelSettings[subParm->relParts[0]].mixedvar, chain, state[chain]);
11164 igrRate = GetParamVals (subParm, chain, state[chain]);
11165 (*lnPriorRatio) -= LnProbGamma ((c->length+u->length)/igrvar, (c->length+u->length)/igrvar, igrRate[c->index]);
11166 (*lnPriorRatio) += LnProbGamma (c->length/igrvar, c->length/igrvar, igrRate[c->index]);
11167 (*lnPriorRatio) += LnProbGamma (u->length/igrvar, u->length/igrvar, igrRate[u->index]);
11168 if (v->length > 0.0)
11169 (*lnPriorRatio) += LnProbGamma (v->length/igrvar, v->length/igrvar, igrRate[v->index]);
11171 /* adjust effective branch lengths */
11172 brlens = GetParamSubVals (subParm, chain, state[chain]);
11173 brlens[v->index] = igrRate[v->index] * v->length;
11174 brlens[u->index] = igrRate[u->index] * u->length;
11175 brlens[c->index] = igrRate[c->index] * c->length;
11176 } /* end igr branch rate parameter */
11177 } /* next subparameter */
11179 /* set tiprobs update flags */
11184 /* set flags for update of cond likes down to root */
11186 while (p->anc != NULL)
11192 while (p->anc != NULL)
11198 /* get down pass sequence */
11201 /* adjust prior ratio for clock tree */
11202 if (LogClockTreePriorRatio (param, chain, &x) == ERROR)
11204 free (nSitesOfPat);
11207 (*lnPriorRatio) += x;
11209 # if defined (DEBUG_ParsSPRClock)
11210 ShowNodes (t->root, 2, YES);
11211 printf ("After\nProposal ratio: %f\n",(*lnProposalRatio));
11212 printf ("v: %d u: %d a: %d b: %d c: %d\n",v->index, u->index, a->index, b->index, c->index);
11216 free (nSitesOfPat);
11221 int Move_ParsTBR1 (Param *param, int chain, RandLong *seed, MrBFlt *lnPriorRatio, MrBFlt *lnProposalRatio, MrBFlt *mvp)
11223 /* Change topology and map branch lengths using TBR-type move biased according to parsimony scores,
11224 controlled by a window defined by a certain node distance radius. */
11226 int i, j, k, n, division, topologyHasChanged, nNeighbor, nRoot, nCrown, iA, jC, isVPriorExp;
11227 BitsLong *pA, *pB, *pC, *pD, y[2];
11228 MrBFlt x, minV, maxV, brlensExp=0.0, minLength=0.0, length=0.0, *parLength=NULL, prob, ran, tuning, warpFactor,
11229 sum1, sum2, tempsum, tempc, tempy;
11230 CLFlt *nSites, *nSitesOfPat=NULL, *globalNSitesOfPat;
11231 TreeNode *p, *q, *r, *a, *b, *u, *v, *c, *d, *newB, *newA, *newC, **pRoot=NULL, **pCrown=NULL;
11236 warpFactor = mvp[0]; /* tuning parameter determining how heavily to weight according to parsimony scores */
11237 // increaseProb = decreaseProb = mvp[1]; /* reweighting probabilities */
11238 // v_typical = mvp[2]; /* typical branch length for conversion of parsimony score to log prob ratio */
11239 tuning = mvp[3]; /* multiplier tuning parameter */
11240 nNeighbor = (int)mvp[4]; /* distance to move picked branch in root and crown part */
11242 (*lnProposalRatio) = (*lnPriorRatio) = 0.0;
11244 /* get model params and model info */
11245 mp = &modelParams[param->relParts[0]];
11246 m = &modelSettings[param->relParts[0]];
11249 t = GetTree (param, chain, state[chain]);
11251 /* max and min brlen */
11252 if (param->subParams[0]->paramId == BRLENS_UNI)
11254 minV = mp->brlensUni[0] > BRLENS_MIN ? mp->brlensUni[0] : BRLENS_MIN;
11255 maxV = mp->brlensUni[1] < BRLENS_MAX ? mp->brlensUni[1] : BRLENS_MAX;
11258 else if (param->subParams[0]->paramId == BRLENS_GamDir)
11264 else if (param->subParams[0]->paramId == BRLENS_iGmDir)
11270 else if (param->subParams[0]->paramId == BRLENS_twoExp)
11280 brlensExp = mp->brlensExp;
11284 /* Dirichlet or twoExp prior */
11285 if (isVPriorExp > 1)
11286 (*lnPriorRatio) = -LogDirPrior(t, mp, isVPriorExp);
11288 /* set topologyHasChanged to NO */
11289 topologyHasChanged = NO;
11291 /* reset node variables that will be used */
11292 for (i=0; i<t->nNodes; i++)
11294 p = t->allDownPass[i];
11299 /* pick an internal branch */
11301 p = t->intDownPass[(int)(RandomNumber(seed)*(t->nIntNodes-1))];
11303 if (q == p) q = p->anc->right;
11305 if (q->isLocked == YES || q->left == NULL)
11307 if (p->anc->isLocked == YES || p->anc->anc->anc == NULL)
11309 if (p->left->isLocked == YES || p->left->left == NULL)
11311 if (p->right->isLocked == YES || p->right->left == NULL)
11314 while (i == 2 && j == 2);
11316 /* set up pointers for nodes around the picked branch */
11318 c = p->left; d = p->right;
11319 if (u->left == v) a = u->right;
11322 /* clip root part of tree */
11324 if (b->left == u) b->left = a;
11326 /* clip crown part of tree */
11329 /* should never change u, v, a, b, c, d pointers */
11331 /* mark nodes nNeighbor away in root (negative) and crown (positive) respecting constraints */
11332 /* first move down towards root */
11333 nRoot = nCrown = 0;
11334 if (u->isLocked == NO)
11336 p = a; q = b; n = 0;
11337 while (q->anc != NULL)
11340 q->x = n; // temporary, for MarkDistance below
11342 MarkDistance(q->right, YES, nNeighbor, &nRoot);
11344 MarkDistance(q->left, YES, nNeighbor, &nRoot);
11345 q->x = --n; // final
11347 if (q->isLocked == YES || abs(q->x) >= nNeighbor)
11352 /* then move up in root part */
11353 a->marked = YES; nRoot++;
11354 if (a->isLocked == NO)
11356 MarkDistance(a->left, YES, nNeighbor, &nRoot);
11357 MarkDistance(a->right, YES, nNeighbor, &nRoot);
11359 /* finally in crown part */
11360 c->marked = YES; nCrown++;
11361 if (c->isLocked == NO)
11363 MarkDistance(c->left, NO, nNeighbor, &nCrown);
11364 MarkDistance(c->right, NO, nNeighbor, &nCrown);
11366 if (d->isLocked == NO)
11368 MarkDistance(d->left, NO, nNeighbor, &nCrown);
11369 MarkDistance(d->right, NO, nNeighbor, &nCrown);
11372 /* need to alloc a matrix for parsimony lengths, an array of pointers to crown part,
11373 and an array of pointers to root part. */
11374 parLength = (MrBFlt *) SafeCalloc ((size_t)nRoot * (size_t)nCrown, sizeof(MrBFlt));
11375 pRoot = (TreeNode **) SafeCalloc(nRoot, sizeof(TreeNode *));
11376 pCrown = (TreeNode **) SafeCalloc(nCrown, sizeof(TreeNode *));
11377 if (!parLength || !pRoot || !pCrown) goto errorExit;
11378 /* starting position */
11379 pRoot[0] = a; pCrown[0] = c;
11380 for (i=j=1, n=t->nNodes-2; n>=0; n--)
11381 { /* and the rest */
11382 p = t->allDownPass[n];
11383 if (p->marked == YES && p->x < 0)
11385 if (p->marked == YES && p->x > 0)
11388 assert (i==nRoot && j==nCrown);
11390 /* get final parsimony state sets for the root part */
11391 GetParsDP (t, t->root->left, chain);
11392 GetParsFP (t, t->root->left, chain);
11393 /* get final parsimony state sets for the crown part */
11394 GetParsDP (t, c, chain);
11395 GetParsDP (t, d, chain);
11396 GetParsFP (t, c, chain);
11397 GetParsFP (t, d, chain);
11399 /* find number of site patterns and modify randomly */
11400 globalNSitesOfPat = numSitesOfPat + (chainId[chain] % chainParams.numChains) * numCompressedChars + m->compCharStart;
11401 nSitesOfPat = (CLFlt *) SafeCalloc (numCompressedChars, sizeof(CLFlt));
11402 if (!nSitesOfPat) goto errorExit;
11403 for (i=0; i<numCompressedChars; i++)
11405 nSitesOfPat[i] = globalNSitesOfPat[i];
11406 /* for (j=0; j<globalNSitesOfPat[i]; j++)
11408 ran = RandomNumber(seed);
11409 if (ran < decreaseProb)
11411 else if (ran > 1.0 - increaseProb)
11413 } // this is not used at the moment */
11416 /* cycle through the possibilities and record the parsimony length */
11417 for (j=0; j<nCrown; j++)
11419 for (i=0; i<nRoot; i++)
11421 parLength[i+j*nRoot] = 0.0;
11422 for (n=0; n<t->nRelParts; n++)
11424 division = t->relParts[n];
11426 /* Find model settings */
11427 m = &modelSettings[division];
11429 /* find nSitesOfPat */
11430 nSites = nSitesOfPat + m->compCharStart;
11432 /* find downpass parsimony sets for the potential new connection nodes and their environment */
11433 pA = m->parsSets[pRoot[i]->index];
11434 pB = m->parsSets[pRoot[i]->anc->index];
11435 pC = m->parsSets[pCrown[j]->index];
11436 pD = m->parsSets[pCrown[j]->anc->index];
11439 if (m->nParsIntsPerSite == 1)
11441 for (k=0; k<m->numChars; k++)
11443 y[0] = (pC[k] | pD[k]) & (pA[k] | pB[k]);
11445 length += nSites[k];
11448 else /* if (m->nParsIntsPerSite == 2) */
11450 for (k=0; k<2*m->numChars; k+=2)
11452 y[0] = (pC[k] | pD[k]) & (pA[k] | pB[k]);
11453 y[1] = (pC[k+1] | pD[k+1]) & (pA[k+1] | pB[k+1]);;
11454 if ((y[0] | y[1]) == 0)
11455 length += nSites[k/2];
11458 parLength[i+j*nRoot] += warpFactor * length;
11463 /* find the min length and the sum for the forward move */
11465 for (j=0; j<nCrown; j++)
11466 for (i=0; i<nRoot; i++)
11468 if (i == 0 && j == 0) // exclude original position
11470 if (minLength > parLength[i+j*nRoot] || minLength < 0.0)
11471 minLength = parLength[i+j*nRoot];
11473 sum1 = 0.0; tempc = 0.0;
11474 for (j=0; j<nCrown; j++)
11475 for (i=0; i<nRoot; i++)
11477 if (i == 0 && j == 0) // exclude original position
11479 /* Kahan summation to reduce numerical error */
11480 tempy = exp(minLength - parLength[i+j*nRoot]) - tempc;
11481 tempsum = sum1 + tempy; tempc = (tempsum - sum1) - tempy;
11483 // sum1 += exp(minLength - parLength[i+j*nRoot]);
11484 // printf("%d %d %lf\n", i, j, exp(minLength - parLength[i+j*nRoot]));
11487 /* generate a random uniform */
11488 ran = RandomNumber(seed) * sum1;
11490 /* select the appropriate reattachment point */
11491 newA = a; newC = c;
11492 prob = 0.0; tempc = 0.0;
11493 for (j=0; j<nCrown; j++)
11494 for (i=0; i<nRoot; i++)
11496 if (i == 0 && j == 0) // exclude original position
11498 // prob += exp (minLength - parLength[i+j*nRoot]);
11499 /* Kahan summation to reduce numerical error */
11500 tempy = exp(minLength - parLength[i+j*nRoot]) - tempc;
11501 tempsum = prob + tempy; tempc = (tempsum - prob) - tempy;
11504 /* proposed new attaching position */
11513 /* calculate the proposal ratio */
11514 (*lnProposalRatio) = parLength[i+j*nRoot] - minLength + log(sum1);
11516 /* find the min length and the sum for the backward move */
11518 for (j=0; j<nCrown; j++)
11519 for (i=0; i<nRoot; i++)
11521 if (i == iA && j == jC) // exclude new position
11523 if (minLength > parLength[i+j*nRoot] || minLength < 0.0)
11524 minLength = parLength[i+j*nRoot];
11526 sum2 = 0.0; tempc = 0.0;
11527 for (j=0; j<nCrown; j++)
11528 for (i=0; i<nRoot; i++)
11530 if (i == iA && j == jC) // exclude new position
11532 /* Kahan summation to reduce numerical error */
11533 tempy = exp(minLength - parLength[i+j*nRoot]) - tempc;
11534 tempsum = sum2 + tempy; tempc = (tempsum - sum2) - tempy;
11536 // sum2 += exp (minLength - parLength[i+j*nRoot]);
11537 // printf("%d %d %lf\n", i, j, exp(minLength - parLength[i+j*nRoot]));
11540 /* calculate the proposal ratio */
11541 (*lnProposalRatio) += minLength - parLength[0] - log(sum2);
11543 /* reattach the root part */
11551 if (newB->left == newA)
11556 /* transfer lock and reassign branch lengths, if necessary */
11559 /* if u is locked, then we have moved upwards and need to leave the u lock behind */
11560 if (u->isLocked == YES)
11564 a->lockID = u->lockID;
11569 while (p->anc != NULL)
11576 /* newA is descendant to a so move a->length not u->length */
11578 u->length = a->length;
11583 while (p->anc != NULL)
11585 if (p == newA) break;
11590 /* newA is ancestor to a so insert above instead of below */
11592 newA->length = u->length;
11594 /* newA is on root path and locked, we need to transfer lock to u */
11595 if (newA->isLocked == YES) {
11597 u->lockID = newA->lockID;
11598 newA->isLocked = NO;
11603 /* hit u length with multiplier */
11604 x = u->length * exp(tuning * (RandomNumber(seed) - 0.5));
11605 while (x < minV || x > maxV)
11607 if (x < minV) x = minV * minV / x;
11608 if (x > maxV) x = maxV * maxV / x;
11610 /* calculate proposal and prior ratio based on length modification */
11611 (*lnProposalRatio) += log (x / u->length);
11612 if (isVPriorExp == YES)
11613 (*lnPriorRatio) += brlensExp * (u->length - x);
11616 /* set tiprobs update flags */
11618 newA->upDateTi = YES;
11623 q = newB = newC->anc;
11624 if (newC != c) // crown part has changed
11626 /* rotate nodes from newC to c or d (whichever is closest) */
11628 while (r != c && r != d)
11631 /* rotate pointers of q */
11637 /* swap q and old */
11642 /* make sure we get q and r initialized for next round */
11646 newB->length = tempc;
11648 /* hit newB length with multiplier */
11649 x = newB->length * exp(tuning * (RandomNumber(seed) - 0.5));
11650 while (x < minV || x > maxV)
11652 if (x < minV) x = minV * minV / x;
11653 if (x > maxV) x = maxV * maxV / x;
11655 /* calculate proposal and prior ratio based on length modification */
11656 (*lnProposalRatio) += log (x / newB->length);
11657 if (isVPriorExp == YES)
11658 (*lnPriorRatio) += brlensExp * (newB->length - x);
11660 newB->upDateTi = YES;
11663 /* reattach the crown part */
11666 newC->anc = newB->anc = v;
11668 topologyHasChanged = YES;
11670 /* hit v length with multiplier */
11671 x = v->length * exp(tuning * (RandomNumber(seed) - 0.5));
11672 while (x < minV || x > maxV)
11674 if (x < minV) x = minV * minV / x;
11675 if (x > maxV) x = maxV * maxV / x;
11677 /* calculate proposal and prior ratio based on length modification */
11678 (*lnProposalRatio) += log (x / v->length);
11679 if (isVPriorExp == YES)
11680 (*lnPriorRatio) += brlensExp * (v->length - x);
11684 /* set flags for update of cond likes */
11686 while (p->anc != NULL)
11692 while (p->anc != NULL)
11698 while (p->anc != NULL)
11704 while (p->anc != NULL)
11710 /* get down pass sequence if tree topology has changed */
11711 if (topologyHasChanged == YES)
11716 /* Dirichlet or twoExp prior */
11717 if (isVPriorExp > 1)
11718 (*lnPriorRatio) += LogDirPrior(t, mp, isVPriorExp);
11720 /* free up local memory */
11721 free (parLength); free (pRoot); free (pCrown); free (nSitesOfPat);
11726 MrBayesPrint ("%s Problem allocating memory in Move_ParsTBR\n", spacer);
11727 free (parLength); free (pRoot); free (pCrown); free (nSitesOfPat);
11733 int Move_ParsTBR2 (Param *param, int chain, RandLong *seed, MrBFlt *lnPriorRatio, MrBFlt *lnProposalRatio, MrBFlt *mvp)
11735 /* Change topology and map branch lengths using TBR-type move biased according to parsimony scores,
11736 controlled by a window defined by a certain node distance radius. */
11738 int i, j, k, n, division, topologyHasChanged, nNeighbor, nRoot, nCrown, iA, jC, isVPriorExp;
11739 BitsLong *pA, *pB, *pC, *pD, y[2];
11740 MrBFlt x, minV, maxV, brlensExp=0.0, minLength=0.0, length=0.0, *parLength=NULL, prob, ran, tuning, warpFactor,
11741 v_typical, divFactor, nStates, sum1, sum2, tempsum, tempc, tempy;
11742 CLFlt *nSites, *nSitesOfPat=NULL, *globalNSitesOfPat;
11743 TreeNode *p, *q, *r, *a, *b, *u, *v, *c, *d, *newB, *newA, *newC, **pRoot=NULL, **pCrown=NULL;
11748 warpFactor = mvp[0]; /* tuning parameter determining how heavily to weight according to parsimony scores */
11749 // increaseProb = decreaseProb = mvp[1]; /* reweighting probabilities */
11750 v_typical = mvp[2]; /* typical branch length for conversion of parsimony score to log prob ratio */
11751 tuning = mvp[3]; /* multiplier tuning parameter */
11752 nNeighbor = (int)mvp[4]; /* distance to move picked branch in root and crown part */
11754 (*lnProposalRatio) = (*lnPriorRatio) = 0.0;
11756 /* get model params and model info */
11757 mp = &modelParams[param->relParts[0]];
11758 m = &modelSettings[param->relParts[0]];
11761 t = GetTree (param, chain, state[chain]);
11763 /* max and min brlen */
11764 if (param->subParams[0]->paramId == BRLENS_UNI)
11766 minV = mp->brlensUni[0] > BRLENS_MIN ? mp->brlensUni[0] : BRLENS_MIN;
11767 maxV = mp->brlensUni[1] < BRLENS_MAX ? mp->brlensUni[1] : BRLENS_MAX;
11770 else if (param->subParams[0]->paramId == BRLENS_GamDir)
11776 else if (param->subParams[0]->paramId == BRLENS_iGmDir)
11782 else if (param->subParams[0]->paramId == BRLENS_twoExp)
11792 brlensExp = mp->brlensExp;
11796 /* Dirichlet or twoExp prior */
11797 if (isVPriorExp > 1)
11798 (*lnPriorRatio) = -LogDirPrior(t, mp, isVPriorExp);
11800 /* set topologyHasChanged to NO */
11801 topologyHasChanged = NO;
11803 /* reset node variables that will be used */
11804 for (i=0; i<t->nNodes; i++)
11806 p = t->allDownPass[i];
11811 /* pick an internal branch */
11813 p = t->intDownPass[(int)(RandomNumber(seed)*(t->nIntNodes-1))];
11815 if (q == p) q = p->anc->right;
11817 if (q->isLocked == YES || q->left == NULL)
11819 if (p->anc->isLocked == YES || p->anc->anc->anc == NULL)
11821 if (p->left->isLocked == YES || p->left->left == NULL)
11823 if (p->right->isLocked == YES || p->right->left == NULL)
11826 while (i == 2 && j == 2);
11828 /* set up pointers for nodes around the picked branch */
11830 c = p->left; d = p->right;
11831 if (u->left == v) a = u->right;
11834 /* clip root part of tree */
11836 if (b->left == u) b->left = a;
11838 /* clip crown part of tree */
11841 /* should never change u, v, a, b, c, d pointers */
11843 /* mark nodes nNeighbor away in root (negative) and crown (positive) respecting constraints */
11844 /* first move down towards root */
11845 nRoot = nCrown = 0;
11846 if (u->isLocked == NO)
11848 p = a; q = b; n = 0;
11849 while (q->anc != NULL)
11852 q->x = n; // temporary, for MarkDistance below
11854 MarkDistance(q->right, YES, nNeighbor, &nRoot);
11856 MarkDistance(q->left, YES, nNeighbor, &nRoot);
11857 q->x = --n; // final
11859 if (q->isLocked == YES || abs(q->x) >= nNeighbor)
11864 /* then move up in root part */
11865 a->marked = YES; nRoot++;
11866 if (a->isLocked == NO)
11868 MarkDistance(a->left, YES, nNeighbor, &nRoot);
11869 MarkDistance(a->right, YES, nNeighbor, &nRoot);
11871 /* finally in crown part */
11872 c->marked = YES; nCrown++;
11873 if (c->isLocked == NO)
11875 MarkDistance(c->left, NO, nNeighbor, &nCrown);
11876 MarkDistance(c->right, NO, nNeighbor, &nCrown);
11878 if (d->isLocked == NO)
11880 MarkDistance(d->left, NO, nNeighbor, &nCrown);
11881 MarkDistance(d->right, NO, nNeighbor, &nCrown);
11884 /* need to alloc a matrix for parsimony lengths, an array of pointers to crown part,
11885 and an array of pointers to root part. */
11886 parLength = (MrBFlt *) SafeCalloc ((size_t)nRoot * (size_t)nCrown, sizeof(MrBFlt));
11887 pRoot = (TreeNode **) SafeCalloc(nRoot, sizeof(TreeNode *));
11888 pCrown = (TreeNode **) SafeCalloc(nCrown, sizeof(TreeNode *));
11889 if (!parLength || !pRoot || !pCrown) goto errorExit;
11890 /* starting position */
11891 pRoot[0] = a; pCrown[0] = c;
11892 for (i=j=1, n=t->nNodes-2; n>=0; n--)
11893 { /* and the rest */
11894 p = t->allDownPass[n];
11895 if (p->marked == YES && p->x < 0)
11897 if (p->marked == YES && p->x > 0)
11900 assert (i==nRoot && j==nCrown);
11902 /* get final parsimony state sets for the root part */
11903 GetParsDP (t, t->root->left, chain);
11904 GetParsFP (t, t->root->left, chain);
11905 /* get final parsimony state sets for the crown part */
11906 GetParsDP (t, c, chain);
11907 GetParsDP (t, d, chain);
11908 GetParsFP (t, c, chain);
11909 GetParsFP (t, d, chain);
11911 /* find number of site patterns and modify randomly */
11912 globalNSitesOfPat = numSitesOfPat + (chainId[chain] % chainParams.numChains) * numCompressedChars + m->compCharStart;
11913 nSitesOfPat = (CLFlt *) SafeCalloc (numCompressedChars, sizeof(CLFlt));
11914 if (!nSitesOfPat) goto errorExit;
11915 for (i=0; i<numCompressedChars; i++)
11917 nSitesOfPat[i] = globalNSitesOfPat[i];
11918 /* for (j=0; j<globalNSitesOfPat[i]; j++)
11920 ran = RandomNumber(seed);
11921 if (ran < decreaseProb)
11923 else if (ran > 1.0 - increaseProb)
11925 } // this is not used at the moment */
11928 /* cycle through the possibilities and record the parsimony length */
11929 for (j=0; j<nCrown; j++)
11931 for (i=0; i<nRoot; i++)
11933 parLength[i+j*nRoot] = 0.0;
11934 for (n=0; n<t->nRelParts; n++)
11936 division = t->relParts[n];
11938 /* Find model settings */
11939 m = &modelSettings[division];
11941 /* find nSitesOfPat */
11942 nSites = nSitesOfPat + m->compCharStart;
11944 /* find downpass parsimony sets for the potential new connection nodes and their environment */
11945 pA = m->parsSets[pRoot[i]->index];
11946 pB = m->parsSets[pRoot[i]->anc->index];
11947 pC = m->parsSets[pCrown[j]->index];
11948 pD = m->parsSets[pCrown[j]->anc->index];
11951 if (m->nParsIntsPerSite == 1)
11953 for (k=0; k<m->numChars; k++)
11955 y[0] = (pC[k] | pD[k]) & (pA[k] | pB[k]);
11957 length += nSites[k];
11960 else /* if (m->nParsIntsPerSite == 2) */
11962 for (k=0; k<2*m->numChars; k+=2)
11964 y[0] = (pC[k] | pD[k]) & (pA[k] | pB[k]);
11965 y[1] = (pC[k+1] | pD[k+1]) & (pA[k+1] | pB[k+1]);;
11966 if ((y[0] | y[1]) == 0)
11967 length += nSites[k/2];
11971 /* find nStates and ratemult */
11972 nStates = m->numModelStates;
11973 if (m->dataType == STANDARD)
11975 v_typical = length/m->numUncompressedChars + 0.0001;
11977 /* get division warp factor (prop. to prob. of change) */
11978 divFactor = - warpFactor * log(1.0/nStates - exp(-nStates/(nStates-1)*v_typical)/nStates);
11979 parLength[i+j*nRoot] += divFactor * length;
11984 /* find the min length and the sum for the forward move */
11986 for (j=0; j<nCrown; j++)
11987 for (i=0; i<nRoot; i++)
11989 if (i == 0 && j == 0) // exclude original position
11991 if (minLength > parLength[i+j*nRoot] || minLength < 0.0)
11992 minLength = parLength[i+j*nRoot];
11994 sum1 = 0.0; tempc = 0.0;
11995 for (j=0; j<nCrown; j++)
11996 for (i=0; i<nRoot; i++)
11998 if (i == 0 && j == 0) // exclude original position
12000 /* Kahan summation to reduce numerical error */
12001 tempy = exp(minLength - parLength[i+j*nRoot]) - tempc;
12002 tempsum = sum1 + tempy; tempc = (tempsum - sum1) - tempy;
12004 // sum1 += exp(minLength - parLength[i+j*nRoot]);
12005 // printf("%d %d %lf\n", i, j, exp(minLength - parLength[i+j*nRoot]));
12008 /* generate a random uniform */
12009 ran = RandomNumber(seed) * sum1;
12011 /* select the appropriate reattachment point */
12012 newA = a; newC = c;
12013 prob = 0.0; tempc = 0.0;
12014 for (j=0; j<nCrown; j++)
12015 for (i=0; i<nRoot; i++)
12017 if (i == 0 && j == 0) // exclude original position
12019 // prob += exp (minLength - parLength[i+j*nRoot]);
12020 /* Kahan summation to reduce numerical error */
12021 tempy = exp(minLength - parLength[i+j*nRoot]) - tempc;
12022 tempsum = prob + tempy; tempc = (tempsum - prob) - tempy;
12025 /* proposed new attaching position */
12034 /* calculate the proposal ratio */
12035 (*lnProposalRatio) = parLength[i+j*nRoot] - minLength + log(sum1);
12037 /* find the min length and the sum for the backward move */
12039 for (j=0; j<nCrown; j++)
12040 for (i=0; i<nRoot; i++)
12042 if (i == iA && j == jC) // exclude new position
12044 if (minLength > parLength[i+j*nRoot] || minLength < 0.0)
12045 minLength = parLength[i+j*nRoot];
12047 sum2 = 0.0; tempc = 0.0;
12048 for (j=0; j<nCrown; j++)
12049 for (i=0; i<nRoot; i++)
12051 if (i == iA && j == jC) // exclude new position
12053 /* Kahan summation to reduce numerical error */
12054 tempy = exp(minLength - parLength[i+j*nRoot]) - tempc;
12055 tempsum = sum2 + tempy; tempc = (tempsum - sum2) - tempy;
12057 // sum2 += exp (minLength - parLength[i+j*nRoot]);
12058 // printf("%d %d %lf\n", i, j, exp(minLength - parLength[i+j*nRoot]));
12061 /* calculate the proposal ratio */
12062 (*lnProposalRatio) += minLength - parLength[0] - log(sum2);
12064 /* reattach the root part */
12072 if (newB->left == newA)
12077 /* transfer lock and reassign branch lengths, if necessary */
12080 /* if u is locked, then we have moved upwards and need to leave the u lock behind */
12081 if (u->isLocked == YES)
12085 a->lockID = u->lockID;
12090 while (p->anc != NULL)
12097 /* newA is descendant to a so move a->length not u->length */
12099 u->length = a->length;
12104 while (p->anc != NULL)
12106 if (p == newA) break;
12111 /* newA is ancestor to a so insert above instead of below */
12113 newA->length = u->length;
12115 /* newA is on root path and locked, we need to transfer lock to u */
12116 if (newA->isLocked == YES) {
12118 u->lockID = newA->lockID;
12119 newA->isLocked = NO;
12124 /* hit u length with multiplier */
12125 x = u->length * exp(tuning * (RandomNumber(seed) - 0.5));
12126 while (x < minV || x > maxV)
12128 if (x < minV) x = minV * minV / x;
12129 if (x > maxV) x = maxV * maxV / x;
12131 /* calculate proposal and prior ratio based on length modification */
12132 (*lnProposalRatio) += log (x / u->length);
12133 if (isVPriorExp == YES)
12134 (*lnPriorRatio) += brlensExp * (u->length - x);
12137 /* set tiprobs update flags */
12139 newA->upDateTi = YES;
12144 q = newB = newC->anc;
12145 if (newC != c) // crown part has changed
12147 /* rotate nodes from newC to c or d (whichever is closest) */
12149 while (r != c && r != d)
12152 /* rotate pointers of q */
12158 /* swap q and old */
12163 /* make sure we get q and r initialized for next round */
12167 newB->length = tempc;
12169 /* hit newB length with multiplier */
12170 x = newB->length * exp(tuning * (RandomNumber(seed) - 0.5));
12171 while (x < minV || x > maxV)
12173 if (x < minV) x = minV * minV / x;
12174 if (x > maxV) x = maxV * maxV / x;
12176 /* calculate proposal and prior ratio based on length modification */
12177 (*lnProposalRatio) += log (x / newB->length);
12178 if (isVPriorExp == YES)
12179 (*lnPriorRatio) += brlensExp * (newB->length - x);
12181 newB->upDateTi = YES;
12184 /* reattach the crown part */
12187 newC->anc = newB->anc = v;
12189 topologyHasChanged = YES;
12191 /* hit v length with multiplier */
12192 x = v->length * exp(tuning * (RandomNumber(seed) - 0.5));
12193 while (x < minV || x > maxV)
12195 if (x < minV) x = minV * minV / x;
12196 if (x > maxV) x = maxV * maxV / x;
12198 /* calculate proposal and prior ratio based on length modification */
12199 (*lnProposalRatio) += log (x / v->length);
12200 if (isVPriorExp == YES)
12201 (*lnPriorRatio) += brlensExp * (v->length - x);
12205 /* set flags for update of cond likes */
12207 while (p->anc != NULL)
12213 while (p->anc != NULL)
12219 while (p->anc != NULL)
12225 while (p->anc != NULL)
12231 /* get down pass sequence if tree topology has changed */
12232 if (topologyHasChanged == YES)
12237 /* Dirichlet or twoExp prior */
12238 if (isVPriorExp > 1)
12239 (*lnPriorRatio) += LogDirPrior(t, mp, isVPriorExp);
12241 /* free up local memory */
12242 free (parLength); free (pRoot); free (pCrown); free (nSitesOfPat);
12247 MrBayesPrint ("%s Problem allocating memory in Move_ParsTBR\n", spacer);
12248 free (parLength); free (pRoot); free (pCrown); free (nSitesOfPat);
12254 int Move_Pinvar (Param *param, int chain, RandLong *seed, MrBFlt *lnPriorRatio, MrBFlt *lnProposalRatio, MrBFlt *mvp)
12256 /* change proportion of invariable sites (pInvar) */
12258 int i, c, isValidP, *rateCat, nGammaCats;
12259 MrBFlt oldP, newP, window, minP, maxP, ran, lnInvarRatio, lnVarRatio;
12260 CLFlt *nSitesOfPat;
12264 /* get size of window, centered on current pInvar value */
12267 /* get model params */
12268 mp = &modelParams[param->relParts[0]];
12270 /* get minimum and maximum values for pInvar */
12271 minP = mp->pInvarUni[0];
12272 maxP = mp->pInvarUni[1];
12274 /* get old value of pInvar */
12275 newP = oldP = *GetParamVals(param, chain, state[chain]);
12277 /* change value for pInvar */
12278 ran = RandomNumber(seed);
12279 if (maxP-minP < window)
12281 window = maxP-minP;
12284 newP = oldP + window * (ran - 0.5);
12286 /* check validity */
12291 newP = 2* minP - newP;
12292 else if (newP > maxP)
12293 newP = 2 * maxP - newP;
12296 } while (isValidP == NO);
12298 /* get proposal ratio */
12299 *lnProposalRatio = 0.0;
12301 /* get prior ratio */
12302 *lnPriorRatio = 0.0;
12303 lnInvarRatio = log(newP) - log(oldP);
12304 lnVarRatio = log(1.0-newP) - log(1.0-oldP);
12305 for (i=0; i<param->nRelParts; i++)
12307 m = &modelSettings[param->relParts[i]];
12308 if (m->gibbsGamma == YES)
12310 /* find rate category index and number of gamma categories */
12311 rateCat = m->tiIndex + chain * m->numChars;
12312 nGammaCats = m->numGammaCats;
12314 /* find nSitesOfPat */
12315 nSitesOfPat = numSitesOfPat + (chainId[chain] % chainParams.numChains)*numCompressedChars + m->compCharStart;
12317 /* loop over characters */
12318 for (c=0; c<m->numChars; c++)
12320 if (rateCat[c] < nGammaCats)
12321 *lnPriorRatio += lnVarRatio * nSitesOfPat[c];
12323 *lnPriorRatio += lnInvarRatio * nSitesOfPat[c];
12328 /* copy new pInvar value back */
12329 *GetParamVals(param, chain, state[chain]) = newP;
12331 /* Set update flags for all partitions that share this pInvar. Note that the conditional
12332 likelihood update flags for divisions have been set before we even call this function. */
12333 for (i=0; i<param->nRelParts; i++)
12334 TouchAllTreeNodes(&modelSettings[param->relParts[i]],chain);
12336 /* However, you do need to update cijk flags if this is a covarion model */
12343 int Move_PopSize_M (Param *param, int chain, RandLong *seed, MrBFlt *lnPriorRatio, MrBFlt *lnProposalRatio, MrBFlt *mvp)
12345 int isValidN, valIndex;
12346 MrBFlt *valPtr, oldN, newN, tuning, minN, maxN, ran, oldLnPrior, newLnPrior, growth,
12347 oldT, newT, clockRate;
12352 /* get multiplier tuning parameter */
12355 /* get model params */
12356 mp = &modelParams[param->relParts[0]];
12358 /* get model settings */
12359 m = &modelSettings[param->relParts[0]];
12361 /* get minimum and maximum values for population size */
12362 if (param->paramId == POPSIZE_UNI)
12364 minN = mp->popSizeUni[0];
12365 maxN = mp->popSizeUni[1];
12373 /* get pointer to value to be changed */
12374 valIndex = (int)(RandomNumber(seed) * param->nValues);
12375 valPtr = GetParamVals(param, chain, state[chain]) + valIndex;
12377 /* get old value of population size */
12380 /* get old prior for species tree coalescence */
12381 if (m->brlens->paramId == BRLENS_CLOCK_SPCOAL)
12383 oldLnPrior = LnSpeciesTreeProb(chain);
12386 /* change value for theta */
12387 ran = RandomNumber(seed);
12388 newN = oldN * exp(tuning * (ran - 0.5));
12390 /* check that new value is valid */
12394 newN = 2* minN - newN;
12395 else if (newN > maxN)
12396 newN = 2 * maxN - newN;
12400 while (isValidN == NO);
12402 /* copy new population size value back */
12405 /* get proposal ratio */
12406 *lnProposalRatio = log (newN / oldN);
12408 /* get prior ratio */
12409 if (m->brlens->paramId == BRLENS_CLOCK_SPCOAL)
12411 newLnPrior = LnSpeciesTreeProb(chain);
12415 t = GetTree(modelSettings[param->relParts[0]].brlens,chain,state[chain]);
12416 m = &modelSettings[param->relParts[0]];
12417 clockRate = *GetParamVals(m->clockRate, chain, state[chain]);
12418 if (!strcmp(mp->ploidy, "Diploid"))
12420 else if (!strcmp(mp->ploidy, "Zlinked"))
12424 newT = oldN * clockRate;
12425 oldT = newN * clockRate;
12426 if (!strcmp(mp->growthPr, "Fixed"))
12427 growth = mp->growthFix;
12429 growth = *(GetParamVals (m->growthRate, chain, state[chain]));
12430 if (LnCoalescencePriorPr (t, &oldLnPrior, oldT, growth) == ERROR)
12432 MrBayesPrint ("%s Problem calculating prior for coalescent process\n", spacer);
12435 if (LnCoalescencePriorPr (t, &newLnPrior, newT, growth) == ERROR)
12437 MrBayesPrint ("%s Problem calculating prior for coalescent process\n", spacer);
12442 (*lnPriorRatio) = param->LnPriorRatio(newN, oldN, param->priorParams);
12443 (*lnPriorRatio) += newLnPrior - oldLnPrior;
12449 /* Generalized lognormal move for positive real random variables */
12450 int Move_PosRealLognormal (Param *param, int chain, RandLong *seed, MrBFlt *lnPriorRatio, MrBFlt *lnProposalRatio, MrBFlt *mvp)
12453 MrBFlt oldX, newX, minX, maxX, tuning, u, z;
12455 /* get tuning parameter */
12458 /* get minimum and maximum values for X */
12462 /* get old value of X */
12463 newX = oldX = *GetParamVals(param, chain, state[chain]);
12465 /* change value of X */
12466 u = RandomNumber(seed);
12467 z = PointNormal(u);
12469 newX = exp (log(oldX) + z * tuning);
12471 /* check that new value is valid */
12472 if (newX < minX || newX > maxX) {
12477 /* get proposal ratio */
12478 (*lnProposalRatio) = log (newX / oldX);
12480 /* get prior ratio */
12481 (*lnPriorRatio) = param->LnPriorRatio(newX, oldX, param->priorParams);
12483 /* copy new value back */
12484 (*GetParamVals(param, chain, state[chain])) = newX;
12486 /* Set update flags for tree nodes if relevant */
12487 if (param->affectsLikelihood == YES)
12489 for (i=0; i<param->nRelParts; i++)
12490 TouchAllTreeNodes(&modelSettings[param->relParts[i]],chain);
12497 /* Generalized multiplier move for positive real random variables */
12498 int Move_PosRealMultiplier (Param *param, int chain, RandLong *seed, MrBFlt *lnPriorRatio, MrBFlt *lnProposalRatio, MrBFlt *mvp)
12501 MrBFlt oldX, newX, minX, maxX, tuning, ran, factor;
12503 /* get tuning parameter */
12506 /* get minimum and maximum values for X */
12510 /* get old value of X */
12511 newX = oldX = *GetParamVals(param, chain, state[chain]);
12513 /* change value of X */
12514 ran = RandomNumber(seed);
12515 factor = exp(tuning * (ran - 0.5));
12516 newX = oldX * factor;
12518 /* check that new value is valid */
12523 newX = minX * minX / newX;
12524 else if (newX > maxX)
12525 newX = maxX * maxX / newX;
12528 } while (isValid == NO);
12530 /* get proposal ratio */
12531 (*lnProposalRatio) = log (newX / oldX);
12533 /* get prior ratio */
12534 (*lnPriorRatio) = param->LnPriorRatio(newX, oldX, param->priorParams);
12536 /* copy new value back */
12537 *(GetParamVals(param, chain, state[chain])) = newX;
12539 /* Set update flags for tree nodes if relevant */
12540 if (param->affectsLikelihood == YES)
12542 for (i=0; i<param->nRelParts; i++)
12543 TouchAllTreeNodes(&modelSettings[param->relParts[i]],chain);
12550 /*----------------------------------------------------------------
12552 | Move_RateMult_Dir: Change rate multiplier using Dirichlet
12555 ----------------------------------------------------------------*/
12556 int Move_RateMult_Dir (Param *param, int chain, RandLong *seed, MrBFlt *lnPriorRatio, MrBFlt *lnProposalRatio, MrBFlt *mvp)
12558 int i, nRates, isValid;
12559 MrBFlt alphaPi, *value, *subValue, numSites, *alphaDir, x, y, sum,
12560 rate_pot, *dirParm, *oldRate, *newRate;
12562 /* allocate memory */
12563 dirParm = (MrBFlt *) SafeCalloc (3*numCurrentDivisions, sizeof(MrBFlt));
12564 oldRate = dirParm + numCurrentDivisions;
12565 newRate = dirParm + 2*numCurrentDivisions;
12567 /* get number of rates */
12568 nRates = param->nValues;
12570 /* get pointer to rates and number of uncompressed chars */
12571 value = GetParamVals(param, chain, state[chain]);
12572 subValue = GetParamSubVals(param, chain, state[chain]);
12574 /* get Dirichlet parameters */
12575 alphaDir = subValue + nRates;
12577 /* calculate old ratesum proportions */
12579 for (i=0; i<nRates; i++)
12580 numSites += subValue[i]; /* numSites should be equal to the number of sites */
12581 for (i=0; i<nRates; i++)
12582 oldRate[i] = value[i] * subValue[i] / numSites;
12584 /* get alphaPi tuning parameter */
12585 alphaPi = mvp[0] * nRates;
12587 /* multiply old ratesum proportions with some large number to get new values close to the old ones */
12588 for (i=0; i<nRates; i++)
12589 dirParm[i] = oldRate[i] * alphaPi;
12591 /* get new values */
12592 DirichletRandomVariable (dirParm, newRate, nRates, seed);
12594 /* check new values. we rely on newRate be already normalized */
12600 for (i=0; i<nRates; i++)
12602 if (newRate[i] <= DIR_MIN)
12604 if (newRate[i] < DIR_MIN)
12606 newRate[i] = DIR_MIN;
12609 rate_pot -= DIR_MIN;
12614 if (isValid==1) break;
12615 for (i=0; i<nRates; i++)
12617 if (newRate[i]!=DIR_MIN)
12618 newRate[i] = rate_pot * newRate[i] / sum;
12622 /* calculate and copy new rate ratio values back */
12623 for (i=0; i<nRates; i++)
12624 value[i] = newRate[i] * (numSites / subValue[i]);
12626 /* get proposal ratio */
12628 for (i=0; i<nRates; i++)
12629 sum += newRate[i]*alphaPi;
12631 for (i=0; i<nRates; i++)
12632 x -= LnGamma(newRate[i]*alphaPi);
12633 for (i=0; i<nRates; i++)
12634 x += (newRate[i]*alphaPi-1.0)*log(oldRate[i]);
12636 for (i=0; i<nRates; i++)
12637 sum += oldRate[i]*alphaPi;
12639 for (i=0; i<nRates; i++)
12640 y -= LnGamma(oldRate[i]*alphaPi);
12641 for (i=0; i<nRates; i++)
12642 y += (oldRate[i]*alphaPi-1.0)*log(newRate[i]);
12643 (*lnProposalRatio) = x - y;
12645 /* get prior ratio */
12647 for (i=0; i<nRates; i++)
12648 x += (alphaDir[i]-1.0)*log(newRate[i]);
12649 for (i=0; i<nRates; i++)
12650 y += (alphaDir[i]-1.0)*log(oldRate[i]);
12651 (*lnPriorRatio) = x - y;
12653 /* Set update flags for all partitions that share the rate multiplier. Note that the conditional
12654 likelihood update flags have been set before we even call this function. */
12655 for (i=0; i<param->nRelParts; i++)
12656 TouchAllTreeNodes(&modelSettings[param->relParts[i]],chain);
12658 /* may need to hit update flag for cijks when you have a covarion model */
12659 for (i=0; i<param->nRelParts; i++)
12660 if (modelSettings[param->relParts[i]].nCijkParts > 1)
12661 modelSettings[param->relParts[i]].upDateCijk = YES;
12669 /*----------------------------------------------------------------
12671 | Move_RateMult_Slider: Change rate multiplier using slider
12674 ----------------------------------------------------------------*/
12675 int Move_RateMult_Slider (Param *param, int chain, RandLong *seed, MrBFlt *lnPriorRatio, MrBFlt *lnProposalRatio, MrBFlt *mvp)
12677 int i, indexI, indexJ, nRates;
12678 MrBFlt delta, *value, *subValue, sum, numSites, *alphaDir, x, y,
12679 oldRate[2], newRate[2], min, max;
12681 /* get number of rates */
12682 nRates = param->nValues;
12684 /* get pointer to rates and number of uncompressed chars */
12685 value = GetParamVals(param, chain, state[chain]);
12686 subValue = GetParamSubVals(param, chain, state[chain]);
12688 /* get Dirichlet prior parameters */
12689 alphaDir = subValue + nRates;
12691 /* randomly select two rates */
12692 indexI = (int) (RandomNumber(seed) * nRates);
12693 indexJ = (int) (RandomNumber(seed) * (nRates - 1));
12694 if (indexJ == indexI)
12695 indexJ = nRates - 1;
12697 /* calculate old ratesum proportions */
12699 for (i=0; i<nRates; i++)
12700 numSites += subValue[i]; /* numSites should be equal to the number of sites */
12701 oldRate[0] = value[indexI] * subValue[indexI] / numSites;
12702 oldRate[1] = value[indexJ] * subValue[indexJ] / numSites;
12703 sum = oldRate[0] + oldRate[1];
12705 /* get delta tuning parameter */
12709 min = DIR_MIN / sum;
12711 if (delta > max-min) /* we do it to avoid following long while loop in case if delta is high */
12714 x = oldRate[0] / sum;
12715 y = x + delta * (RandomNumber(seed) - 0.5);
12716 while (y < min || y > max)
12724 /* set the new values */
12725 newRate[0] = y * sum;
12726 newRate[1] = sum - newRate[0];
12727 value[indexI] = newRate[0] * numSites / subValue[indexI];
12728 value[indexJ] = newRate[1] * numSites / subValue[indexJ];
12730 /* get proposal ratio */
12731 (*lnProposalRatio) = 0.0;
12733 /* get prior ratio */
12734 (*lnPriorRatio) = (alphaDir[indexI]-1.0) * (log(newRate[0]) - log(oldRate[0]));
12735 (*lnPriorRatio) += (alphaDir[indexJ]-1.0) * (log(newRate[1]) - log(oldRate[1]));
12737 /* Set update flags for all partitions that share the rate multiplier. Note that the conditional
12738 likelihood update flags have been set before we even call this function. */
12739 for (i=0; i<param->nRelParts; i++)
12740 TouchAllTreeNodes(&modelSettings[param->relParts[i]],chain);
12742 /* may need to hit update flag for cijks when you have a covarion model */
12743 for (i=0; i<param->nRelParts; i++)
12744 if (modelSettings[param->relParts[i]].nCijkParts > 1)
12745 modelSettings[param->relParts[i]].upDateCijk = YES;
12751 /*----------------------------------------------------------------
12753 | Move_Revmat_Dir: Change rate matrix using Dirichlet proposal
12756 ----------------------------------------------------------------*/
12757 int Move_Revmat_Dir (Param *param, int chain, RandLong *seed, MrBFlt *lnPriorRatio, MrBFlt *lnProposalRatio, MrBFlt *mvp)
12759 /* change revMat using Dirichlet proposal */
12761 int i, nRates,isValid;
12762 MrBFlt oldRate[200], newRate[200], dirParm[200], *value, sum, x, y, rate_pot, *alphaDir, alphaPi;
12766 /* get model params and settings */
12767 mp = &modelParams[param->relParts[0]];
12768 m = &modelSettings[param->relParts[0]];
12770 /* get rates and nRates */
12771 value = GetParamVals(param, chain, state[chain]);
12772 nRates = param->nValues;
12774 /* get so called alpha_pi parameter and adjust for number of components */
12775 alphaPi = mvp[0] * nRates;
12777 /* get Dirichlet parameters */
12778 if (m->dataType == PROTEIN)
12779 alphaDir = mp->aaRevMatDir;
12781 alphaDir = mp->revMatDir;
12783 /* copy old rates */
12784 for (i=0; i<nRates; i++)
12785 oldRate[i] = value[i];
12787 /* multiply old ratesum props with some large number to get new values close to the old ones */
12788 for (i=0; i<nRates; i++)
12789 dirParm[i] = oldRate[i] * alphaPi;
12791 /* get new values */
12792 DirichletRandomVariable (dirParm, newRate, nRates, seed);
12794 /* check new values. we rely on newRate be already normalized */
12800 for (i=0; i<nRates; i++)
12802 if (newRate[i] <= RATE_MIN)
12804 if (newRate[i] < RATE_MIN)
12806 newRate[i] = RATE_MIN;
12809 rate_pot -= RATE_MIN;
12814 if (isValid==1) break;
12815 for (i=0; i<nRates; i++)
12817 if (newRate[i]!=RATE_MIN)
12818 newRate[i] = rate_pot * newRate[i] / sum;
12822 /* copy new rate ratio values back */
12823 for (i=0; i<nRates; i++)
12824 value[i] = newRate[i];
12826 /* get proposal ratio */
12828 for (i=0; i<nRates; i++)
12829 sum += newRate[i]*alphaPi;
12831 for (i=0; i<nRates; i++)
12832 x -= LnGamma(newRate[i]*alphaPi);
12833 for (i=0; i<nRates; i++)
12834 x += (newRate[i]*alphaPi-1.0)*log(oldRate[i]);
12836 for (i=0; i<nRates; i++)
12837 sum += oldRate[i]*alphaPi;
12839 for (i=0; i<nRates; i++)
12840 y -= LnGamma(oldRate[i]*alphaPi);
12841 for (i=0; i<nRates; i++)
12842 y += (oldRate[i]*alphaPi-1.0)*log(newRate[i]);
12843 (*lnProposalRatio) = x - y;
12845 /* get prior ratio */
12847 for (i=0; i<nRates; i++)
12848 x += (alphaDir[i]-1.0)*log(newRate[i]);
12849 for (i=0; i<nRates; i++)
12850 y += (alphaDir[i]-1.0)*log(oldRate[i]);
12851 (*lnPriorRatio) = x - y;
12853 /* Set update flags for all partitions that share this revmat. Note that the conditional
12854 likelihood update flags have been set before we even call this function. */
12855 for (i=0; i<param->nRelParts; i++)
12856 TouchAllTreeNodes(&modelSettings[param->relParts[i]],chain);
12858 /* Set update flags for cijks for all affected partitions */
12859 for (i=0; i<param->nRelParts; i++)
12860 modelSettings[param->relParts[i]].upDateCijk = YES;
12866 /*----------------------------------------------------------------
12868 | Move_Revmat_DirMix: Dirichlet proposal for REVMAT_MIX. From
12869 | Huelsenbeck et al. (2004), but note that the prior density
12870 | is different in that paper because they set the rate sum
12873 ----------------------------------------------------------------*/
12874 int Move_Revmat_DirMix (Param *param, int chain, RandLong *seed, MrBFlt *lnPriorRatio, MrBFlt *lnProposalRatio, MrBFlt *mvp)
12876 int i, j, k, isValid, *growthFxn, nRates, groupSize[6];
12877 MrBFlt *value, dirParm[6], newRate[6], oldRate[6], alphaPi, symDir, sum, rate_pot, x, y;
12880 /* get model params and settings */
12881 mp = &modelParams[param->relParts[0]];
12883 /* get growthFunction and nRates */
12884 value = GetParamVals (param, chain, state[chain]);
12885 growthFxn = GetParamIntVals (param, chain, state[chain]);
12886 nRates = GetKFromGrowthFxn(growthFxn);
12888 /* we can't do anything if there is only one rate */
12895 /* extract unique rates from value vector */
12896 for (i=0; i<nRates; i++)
12898 for (i=0; i<6; i++)
12899 oldRate[growthFxn[i]] += value[i];
12901 /* get so called alpha_pi parameter and adjust for number of components */
12902 alphaPi = mvp[0] * nRates;
12904 /* get symmetric dirichlet parameter */
12905 symDir = mp->revMatSymDir;
12907 /* multiply old ratesum props with some large number to get new values close to the old ones */
12908 for (i=0; i<nRates; i++)
12909 dirParm[i] = oldRate[i] * alphaPi;
12911 /* get new values */
12912 DirichletRandomVariable (dirParm, newRate, nRates, seed);
12914 /* check new values. we rely on newRate be already normalized */
12920 for (i=0; i<nRates; i++)
12922 if (newRate[i] <= RATE_MIN)
12924 if (newRate[i] < RATE_MIN)
12926 newRate[i] = RATE_MIN;
12929 rate_pot -= RATE_MIN;
12934 if (isValid==1) break;
12935 for (i=0; i<nRates; i++)
12937 if (newRate[i]!=RATE_MIN)
12938 newRate[i] = rate_pot * newRate[i] / sum;
12942 /* copy new unique rate ratio values back into the value array */
12943 for (i=0; i<nRates; i++)
12946 for (j=i; j<6; j++)
12948 if (growthFxn[j] == i)
12951 for (j=i; j<6; j++)
12953 if (growthFxn[j] == i)
12954 value[j] = newRate[i] / (MrBFlt) k;
12958 /* get proposal ratio */
12960 for (i=0; i<nRates; i++)
12961 sum += newRate[i]*alphaPi;
12963 for (i=0; i<nRates; i++)
12964 x -= LnGamma(newRate[i]*alphaPi);
12965 for (i=0; i<nRates; i++)
12966 x += (newRate[i]*alphaPi-1.0)*log(oldRate[i]);
12968 for (i=0; i<nRates; i++)
12969 sum += oldRate[i]*alphaPi;
12971 for (i=0; i<nRates; i++)
12972 y -= LnGamma(oldRate[i]*alphaPi);
12973 for (i=0; i<nRates; i++)
12974 y += (oldRate[i]*alphaPi-1.0)*log(newRate[i]);
12975 (*lnProposalRatio) = x - y;
12977 /* get group sizes, needed for prior ratio */
12978 for (i=0; i<nRates; i++)
12980 for (i=0; i<6; i++)
12981 groupSize[growthFxn[i]]++;
12983 /* get prior ratio */
12985 for (i=0; i<nRates; i++)
12986 x += (groupSize[i]*symDir-1.0)*log(newRate[i]);
12987 for (i=0; i<nRates; i++)
12988 y += (groupSize[i]*symDir-1.0)*log(oldRate[i]);
12989 (*lnPriorRatio) = x - y;
12991 /* Set update flags for all partitions that share this revmat. Note that the conditional
12992 likelihood update flags have been set before we even call this function. */
12993 for (i=0; i<param->nRelParts; i++)
12994 TouchAllTreeNodes(&modelSettings[param->relParts[i]],chain);
12996 /* Set update flags for cijks for all affected partitions */
12997 for (i=0; i<param->nRelParts; i++)
12998 modelSettings[param->relParts[i]].upDateCijk = YES;
13004 /*----------------------------------------------------------------
13006 | Move_Revmat_Slider: Change rate matrix using sliding window
13007 | move. Choose a pair of rates (e.g. r(A<>C), and r(A<>G)) at
13008 | random and denote them rA, and rB. Let oldProp = rA/(rA + rB)
13009 | and newProp = oldProp + delta(U - 0.5), where U is a uniform
13010 | random variable on the interval (0, 1] and delta is a tuning
13011 | parameter. Values that fall outside the boundaries are reflected
13012 | back in. Then set new_rA = newProp*(rA+rB) and new_rB =
13013 | (1-newProp)*(piA+piB). The Hastings ratio of this move is 1.0.
13015 ----------------------------------------------------------------*/
13016 int Move_Revmat_Slider (Param *param, int chain, RandLong *seed, MrBFlt *lnPriorRatio, MrBFlt *lnProposalRatio, MrBFlt *mvp)
13019 MrBFlt delta, *newRate, *oldRate, *priorAlpha, x, y, sum, min, max;
13023 /* get model params and settings */
13024 mp = &modelParams[param->relParts[0]];
13025 m = &modelSettings[param->relParts[0]];
13027 /* get Dirichlet parameters */
13028 if (m->dataType == PROTEIN)
13029 priorAlpha = mp->aaRevMatDir;
13031 priorAlpha = mp->revMatDir;
13033 /* get the values we need */
13034 nRates = param->nValues;
13035 newRate = GetParamVals (param, chain, state[chain]);
13036 oldRate = GetParamVals (param, chain, state[chain] ^ 1);
13038 /* choose a pair to change */
13039 i = (int) (RandomNumber(seed) * nRates);
13040 j = (int) (RandomNumber(seed) * (nRates-1));
13044 /* find new proportion */
13045 sum = oldRate[i] + oldRate[j];
13047 /* get window size */
13051 min = RATE_MIN / sum;
13053 if (delta > max-min) /* we do it to avoid following long while loop in case if delta is high */
13056 x = oldRate[i] / sum;
13057 y = x + delta * (RandomNumber(seed) - 0.5);
13058 while (y < min || y > max)
13066 /* set the new values */
13067 newRate[i] = y * sum;
13068 newRate[j] = sum - newRate[i];
13070 /* get proposal ratio */
13071 (*lnProposalRatio) = 0.0;
13073 /* get prior ratio */
13074 (*lnPriorRatio) = (priorAlpha[i]-1.0) * (log(newRate[i]) - log(oldRate[i]));
13075 (*lnPriorRatio) += (priorAlpha[j]-1.0) * (log(newRate[j]) - log(oldRate[j]));
13077 /* Set update for entire tree */
13078 for (i=0; i<param->nRelParts; i++)
13079 TouchAllTreeNodes(&modelSettings[param->relParts[i]],chain);
13081 /* Set update flags for cijks for all affected partitions. If this is a simple 4 X 4 model,
13082 we don't take any hit, because we will never go into a general transition probability
13083 calculator. However, for many models we do want to update the cijk flag, as the transition
13084 probability matrices require diagonalizing the rate matrix. */
13085 for (i=0; i<param->nRelParts; i++)
13086 modelSettings[param->relParts[i]].upDateCijk = YES;
13092 /*----------------------------------------------------------------
13094 | Move_Revmat_SplitMerge1: Split or merge rates of rate matrix.
13095 | See Huelsenbeck et al. (2004). Note that the prior used
13096 | here is different from theirs. Also, a Beta proposal is
13097 | used instead of a uniform to propose new rate proportions.
13099 ----------------------------------------------------------------*/
13100 int Move_Revmat_SplitMerge1 (Param *param, int chain, RandLong *seed, MrBFlt *lnPriorRatio, MrBFlt *lnProposalRatio, MrBFlt *mvp)
13102 int i, j, k, index_i, index_j, n_i, n_j, foundFirstI, foundFirstJ,
13103 *newGrowthFxn, *oldGrowthFxn, nOldRates, nNewRates, merge,
13104 groupSize[6], nCompositeRates;
13105 MrBFlt R, R_i, R_j, *newValue, *oldValue, newRate[6], oldRate[6], symDir,
13106 prob_split, prob_merge, dirParm[2], rateProps[2], x, alphaPi;
13109 /* get model params and settings */
13110 mp = &modelParams[param->relParts[0]];
13112 /* get the values we need */
13113 oldValue = GetParamVals(param, chain, state[chain] ^ 1);
13114 newValue = GetParamVals(param, chain, state[chain]);
13115 oldGrowthFxn = GetParamIntVals(param, chain, state[chain] ^ 1);
13116 newGrowthFxn = GetParamIntVals (param, chain, state[chain]);
13117 nOldRates = GetKFromGrowthFxn(oldGrowthFxn);
13118 symDir = mp->revMatSymDir;
13119 alphaPi = mvp[0]; /* tuning parameter alpha */
13121 /* get the old rates */
13122 for (i=0; i<nOldRates; i++)
13124 for (i=0; i<6; i++)
13125 oldRate[oldGrowthFxn[i]] += oldValue[i];
13127 /* decide whether to split or merge */
13128 if (nOldRates == 1)
13130 else if (nOldRates == 6)
13132 else if (RandomNumber(seed) < 0.5)
13137 /* now split or merge */
13138 R = R_i = R_j = 0.0;
13141 /* merge two rates */
13142 nNewRates = nOldRates - 1;
13144 /* determine split and merge probs */
13145 if (nNewRates == 1)
13149 if (nOldRates == 6)
13154 /* select two rates randomly */
13155 index_i = (int) (RandomNumber(seed) * nOldRates);
13156 index_j = (int) (RandomNumber(seed) * (nOldRates - 1));
13157 if (index_j == index_i)
13158 index_j = nOldRates - 1;
13160 /* make sure index_i is lower index */
13161 if (index_i > index_j)
13168 /* find group sizes */
13170 for (i=0; i<6; i++)
13172 if (oldGrowthFxn[i] == index_i)
13174 else if (oldGrowthFxn[i] == index_j)
13178 /* adjust growth function */
13179 for (i=0; i<6; i++)
13181 if (oldGrowthFxn[i] == index_j)
13182 newGrowthFxn[i] = index_i;
13183 else if (oldGrowthFxn[i] > index_j)
13184 newGrowthFxn[i] = oldGrowthFxn[i] - 1;
13186 newGrowthFxn[i] = oldGrowthFxn[i];
13189 /* find the new rates */
13190 for (i=0; i<nNewRates; i++)
13193 newRate[i] = (oldRate[index_i] + oldRate[index_j]);
13194 else if (i < index_j)
13195 newRate[i] = oldRate[i];
13196 else if (i >= index_j)
13197 newRate[i] = oldRate[i+1];
13200 /* copy new unique rate values back into the value array */
13201 for (i=0; i<nNewRates; i++)
13204 for (j=i; j<6; j++)
13206 if (newGrowthFxn[j] == i)
13209 for (j=i; j<6; j++)
13211 if (newGrowthFxn[j] == i)
13212 newValue[j] = newRate[i] / (MrBFlt) k;
13216 /* get the new and old rates (sum over parts) */
13217 R_i = oldRate[index_i];
13218 R_j = oldRate[index_j];
13221 /* check group sizes after merge (before split in back move) */
13222 for (i=0; i<nNewRates; i++)
13224 for (i=0; i<6; i++)
13225 groupSize[newGrowthFxn[i]]++;
13226 nCompositeRates = 0;
13227 for (i=0; i<nNewRates; i++)
13229 if (groupSize[i] > 1)
13233 /* calculate prior ratio (different in the paper) */
13234 (*lnPriorRatio) = LnGamma(n_i * symDir) + LnGamma(n_j * symDir) - LnGamma ((n_i + n_j) * symDir);
13235 (*lnPriorRatio) += ((n_i + n_j) * symDir - 1.0) * log(R) - (n_i * symDir - 1.0) * log(R_i) - (n_j * symDir - 1.0) * log(R_j);
13237 /* calculate proposal ratio */
13238 (*lnProposalRatio) = log ((prob_split / prob_merge) * ((nOldRates * (nOldRates - 1)) / (2.0 * nCompositeRates)) * (1.0 / ((pow(2, n_i + n_j - 1) - 1))));
13240 /* adjust for Beta proposal in back move */
13241 dirParm[0] = alphaPi * n_i;
13242 dirParm[1] = alphaPi * n_j;
13243 rateProps[0] = R_i / R;
13244 rateProps[1] = R_j / R;
13245 x = LnGamma(dirParm[0] + dirParm[1]);
13246 x -= LnGamma(dirParm[0]);
13247 x -= LnGamma(dirParm[1]);
13248 x += (dirParm[0] - 1.0) * log(rateProps[0]);
13249 x += (dirParm[1] - 1.0) * log(rateProps[1]);
13250 (*lnProposalRatio) += x;
13252 /* Jacobian for the rate proportion */
13253 (*lnProposalRatio) -= log(R);
13257 /* split two rates */
13258 nNewRates = nOldRates + 1;
13260 /* determine split and merge probs */
13261 if (nNewRates == 6)
13265 if (nOldRates == 1)
13270 /* check group sizes before split */
13271 for (i=0; i<nOldRates; i++)
13273 for (i=0; i<6; i++)
13274 groupSize[oldGrowthFxn[i]]++;
13275 nCompositeRates = 0;
13276 for (i=0; i<nOldRates; i++)
13278 if (groupSize[i] > 1)
13282 /* randomly select a rate with two or more components to split */
13283 k = (int) (RandomNumber(seed) * nCompositeRates);
13285 for (i=j=0; i<nOldRates; i++)
13287 if (groupSize[i] > 1)
13294 assert (i < nOldRates && groupSize[i] > 1);
13297 /* adjust growth function */
13299 foundFirstI = foundFirstJ = NO;
13302 for (i=0; i<6; i++)
13304 if (oldGrowthFxn[i] == index_i)
13306 if (foundFirstI == NO)
13308 newGrowthFxn[i] = index_i;
13313 if (RandomNumber(seed) < 0.5)
13315 if (foundFirstJ == NO)
13318 index_j = k + 1; /* one more than previous max */
13319 newGrowthFxn[i] = index_j;
13323 newGrowthFxn[i] = index_j;
13327 newGrowthFxn[i] = index_i;
13330 else if (foundFirstJ == YES && oldGrowthFxn[i] >= index_j)
13331 newGrowthFxn[i] = oldGrowthFxn[i] + 1;
13333 newGrowthFxn[i] = oldGrowthFxn[i];
13334 if (foundFirstJ == NO && oldGrowthFxn[i] > k)
13335 k = oldGrowthFxn[i];
13337 } while (foundFirstJ == NO);
13339 /* find group sizes */
13341 for (i=0; i<6; i++)
13343 if (newGrowthFxn[i] == index_i)
13345 else if (newGrowthFxn[i] == index_j)
13349 /* find old rate */
13350 R = oldRate[index_i];
13352 /* propose new rates */
13353 dirParm[0] = alphaPi * n_i;
13354 dirParm[1] = alphaPi * n_j;
13356 DirichletRandomVariable(dirParm, rateProps, 2, seed);
13357 R_i = rateProps[0] * R;
13358 R_j = rateProps[1] * R;
13360 if (R_i/n_i < RATE_MIN)
13362 R_i = RATE_MIN*n_i;
13363 rateProps[0] = R_i/R;
13364 rateProps[1] = 1-rateProps[0];
13365 R_j = rateProps[1] * R;
13366 assert (R_j/n_j < RATE_MIN);
13368 else if (R_j/n_j < RATE_MIN)
13370 R_j = RATE_MIN*n_j;
13371 rateProps[1] = R_j/R;
13372 rateProps[0] = 1-rateProps[1];
13373 R_i = rateProps[0] * R;
13374 assert (R_i/n_i < RATE_MIN);
13377 /* set the new rates */
13378 for (i=0; i<nNewRates; i++)
13382 else if (i == index_j)
13384 else if (i > index_j)
13385 newRate[i] = oldRate[i-1];
13387 newRate[i] = oldRate[i];
13390 /* copy new unique rate values back into the value array */
13391 for (i=0; i<nNewRates; i++)
13394 for (j=i; j<6; j++)
13396 if (newGrowthFxn[j] == i)
13399 for (j=i; j<6; j++)
13401 if (newGrowthFxn[j] == i)
13402 newValue[j] = newRate[i] / (MrBFlt) k;
13406 /* calculate prior ratio (different in the paper) */
13407 (*lnPriorRatio) = LnGamma((n_i + n_j) * symDir) - LnGamma(n_i * symDir) - LnGamma(n_j * symDir);
13408 (*lnPriorRatio) += (n_i * symDir - 1.0) * log(R_i) + (n_j * symDir - 1.0) * log(R_j) - ((n_i + n_j) * symDir - 1.0) * log(R);;
13410 /* calculate proposal ratio */
13411 (*lnProposalRatio) = log ((prob_merge / prob_split) * ((2.0 * nCompositeRates) / (nNewRates * (nNewRates - 1))) * ((pow(2, n_i + n_j - 1) - 1)));
13413 /* adjust for Beta proposal */
13414 x = LnGamma(dirParm[0] + dirParm[1]);
13415 x -= LnGamma(dirParm[0]);
13416 x -= LnGamma(dirParm[1]);
13417 x += (dirParm[0] - 1.0) * log(rateProps[0]);
13418 x += (dirParm[1] - 1.0) * log(rateProps[1]);
13419 (*lnProposalRatio) -= x;
13421 /* Jacobian for rate proportion */
13422 (*lnProposalRatio) += log (R);
13425 #if defined (DEBUG_SPLITMERGE)
13426 if (*lnPriorRatio != *lnPriorRatio)
13428 printf ("prob_merge=%f prob_split=%f nCompositeRates=%d nOldRates=%d nNewRates=%d\n", prob_merge, prob_split, nCompositeRates, nOldRates, nNewRates);
13429 printf ("merge=%s n_i=%d n_j=%d rateProps[0]=%f R=%f R_i=%f R_j=%f\n", merge == NO ? "NO" : "YES", n_i, n_j, rateProps[0], R, R_i, R_j);
13430 printf ("Old rates={%f,%f,%f,%f,%f,%f}\n", oldValue[0], oldValue[1], oldValue[2], oldValue[3], oldValue[4], oldValue[5]);
13431 printf ("Old growth fxn={%d,%d,%d,%d,%d,%d}\n", oldGrowthFxn[0], oldGrowthFxn[1], oldGrowthFxn[2], oldGrowthFxn[3], oldGrowthFxn[4], oldGrowthFxn[5]);
13432 printf ("New rates={%f,%f,%f,%f,%f,%f}\n", newValue[0], newValue[1], newValue[2], newValue[3], newValue[4], newValue[5]);
13433 printf ("New growth fxn={%d,%d,%d,%d,%d,%d}\n", newGrowthFxn[0], newGrowthFxn[1], newGrowthFxn[2], newGrowthFxn[3], newGrowthFxn[4], newGrowthFxn[5]);
13434 printf ("lnPriorRatio=%f lnProposalRatio=%f\n", *lnPriorRatio, *lnProposalRatio);
13439 /* Set update flags for all partitions that share this revmat. Note that the conditional
13440 likelihood update flags have been set before we even call this function. */
13441 for (i=0; i<param->nRelParts; i++)
13442 TouchAllTreeNodes(&modelSettings[param->relParts[i]],chain);
13444 /* Set update flags for cijks for all affected partitions */
13445 for (i=0; i<param->nRelParts; i++)
13446 modelSettings[param->relParts[i]].upDateCijk = YES;
13452 /*----------------------------------------------------------------
13454 | Move_Revmat_SplitMerge2: Componentwise split or merge move.
13456 ----------------------------------------------------------------*/
13457 int Move_Revmat_SplitMerge2 (Param *param, int chain, RandLong *seed, MrBFlt *lnPriorRatio, MrBFlt *lnProposalRatio, MrBFlt *mvp)
13459 int i, k, n_i, n_j, index_i, index_j, groupIndex_i, groupIndex_j,
13460 *newGrowthFxn, *oldGrowthFxn;
13461 MrBFlt R_i, R_j, r_j, alphaPi, *newValue, *oldValue, symDir,
13462 dirParm[2], rateProps[2], x;
13465 /* get model params and settings */
13466 mp = &modelParams[param->relParts[0]];
13468 /* get the values we need */
13469 oldValue = GetParamVals(param, chain, state[chain] ^ 1);
13470 newValue = GetParamVals(param, chain, state[chain]);
13471 oldGrowthFxn = GetParamIntVals(param, chain, state[chain] ^ 1);
13472 newGrowthFxn = GetParamIntVals (param, chain, state[chain]);
13473 symDir = mp->revMatSymDir;
13474 alphaPi = mvp[0]; /* tuning parameter */
13476 /* pick two component rates at random without replacement */
13477 index_i = (int) (RandomNumber(seed) * 6);
13478 index_j = (int) (RandomNumber(seed) * 5);
13479 if (index_j == index_i)
13481 groupIndex_i = oldGrowthFxn[index_i];
13482 groupIndex_j = oldGrowthFxn[index_j];
13484 if (oldGrowthFxn[index_i] != oldGrowthFxn[index_j])
13486 /* the rates are different, so merge them */
13488 /* calculate n_i, n_j, R_i and R_j before merge */
13491 for (i=0; i<6; i++)
13493 if (oldGrowthFxn[i] == groupIndex_i)
13496 R_i += oldValue[i];
13498 if (oldGrowthFxn[i] == groupIndex_j)
13501 R_j += oldValue[i];
13505 /* merge component rates by adding j to i */
13506 newGrowthFxn[index_j] = oldGrowthFxn[index_i];
13508 /* select a new rate for r_j */
13510 r_j = oldValue[index_j];
13513 dirParm[0] = alphaPi * 1;
13514 dirParm[1] = alphaPi * (n_j - 1);
13516 DirichletRandomVariable(dirParm, rateProps, 2, seed);
13517 r_j = rateProps[0] * R_j;
13519 if (R_j - r_j < RATE_MIN)
13521 r_j = R_j - RATE_MIN;
13522 rateProps[0] = r_j/R_j;
13523 rateProps[1] = 1 - rateProps[0];
13527 /* update new growth function */
13528 UpdateGrowthFxn(newGrowthFxn);
13530 /* we divide R_i + r_j equally among components of merged group,
13531 and R_j - r_j equally among split group */
13532 for (i=0; i<6; i++)
13534 if (oldGrowthFxn[i] == oldGrowthFxn[index_i] || i == index_j)
13535 newValue[i] = (R_i + r_j) / (MrBFlt)(n_i + 1);
13536 else if (oldGrowthFxn[i] == oldGrowthFxn[index_j])
13537 newValue[i] = (R_j - r_j) / (MrBFlt)(n_j - 1);
13539 newValue[i] = oldValue[i];
13542 /* calculate prior ratio */
13545 /* no category disappeared */
13546 (*lnPriorRatio) += LnGamma (n_i * symDir) + LnGamma(n_j * symDir);
13547 (*lnPriorRatio) -= LnGamma((n_i +1)* symDir) + LnGamma((n_j-1) * symDir);
13548 (*lnPriorRatio) += ((n_i + 1) * symDir - 1.0) * log(R_i + r_j) + ((n_j - 1) * symDir - 1.0) * log(R_j - r_j);
13549 (*lnPriorRatio) -= (n_i * symDir - 1.0) * log(R_i) + (n_j * symDir - 1.0) * log(R_j);
13553 /* j category disappeared */
13554 (*lnPriorRatio) += LnGamma (n_i * symDir) + LnGamma(n_j * symDir);
13555 (*lnPriorRatio) -= LnGamma((n_i +1)* symDir);
13556 (*lnPriorRatio) += ((n_i + 1) * symDir - 1.0) * log(R_i + r_j);
13557 (*lnPriorRatio) -= (n_i * symDir - 1.0) * log(R_i) + (n_j * symDir - 1.0) * log(R_j);
13560 /* calculate proposal ratio; this is the probability of choosing the right category for rate j when splitting */
13561 k = GetKFromGrowthFxn(newGrowthFxn);
13562 (*lnProposalRatio) = log (1.0 / k);
13564 /* adjust for Beta proposal in back move */
13565 dirParm[0] = alphaPi * 1;
13566 dirParm[1] = alphaPi * n_i;
13567 rateProps[0] = r_j / (R_i + r_j);
13568 rateProps[1] = 1.0 - rateProps[0];
13569 x = LnGamma(dirParm[0] + dirParm[1]);
13570 x -= LnGamma(dirParm[0]);
13571 x -= LnGamma(dirParm[1]);
13572 x += (dirParm[0] - 1.0) * log(rateProps[0]);
13573 x += (dirParm[1] - 1.0) * log(rateProps[1]);
13574 (*lnProposalRatio) += x;
13576 /* adjust for Beta proposal in forward move */
13579 dirParm[0] = alphaPi * 1;
13580 dirParm[1] = alphaPi * n_j;
13581 rateProps[0] = r_j / R_j;
13582 rateProps[1] = 1.0 - rateProps[0];
13583 x = LnGamma(dirParm[0] + dirParm[1]);
13584 x -= LnGamma(dirParm[0]);
13585 x -= LnGamma(dirParm[1]);
13586 x += (dirParm[0] - 1.0) * log(rateProps[0]);
13587 x += (dirParm[1] - 1.0) * log(rateProps[1]);
13588 (*lnProposalRatio) -= x;
13592 (*lnProposalRatio) -= log (R_i + r_j);
13594 (*lnProposalRatio) += log (R_j);
13598 /* split component rates because they are the same */
13600 /* split component rates by selecting new group for j from (0,K), with j starting a new group if index becomes the same */
13601 k = GetKFromGrowthFxn(oldGrowthFxn);
13602 newGrowthFxn[index_j] = (int) (RandomNumber(seed) * k);
13603 if (newGrowthFxn[index_j] == oldGrowthFxn[index_j])
13604 newGrowthFxn[index_j] = k + 1;
13606 /* update growth function and group indices */
13607 UpdateGrowthFxn(newGrowthFxn);
13608 groupIndex_i = newGrowthFxn[index_i];
13609 groupIndex_j = newGrowthFxn[index_j];
13611 /* calculate n_i, n_j, R_i and R_j after split */
13614 for (i=0; i<6; i++)
13618 R_i += oldValue[i];
13621 else if (newGrowthFxn[i] == groupIndex_i)
13624 R_i += oldValue[i];
13626 else if (newGrowthFxn[i] == groupIndex_j)
13629 R_j += oldValue[i];
13633 /* select a new rate for r_j */
13634 dirParm[0] = alphaPi * 1;
13635 dirParm[1] = alphaPi * (n_i - 1);
13637 DirichletRandomVariable(dirParm, rateProps, 2, seed);
13638 r_j = rateProps[0] * R_i;
13640 if (R_i-r_j < RATE_MIN)
13642 r_j = R_i - RATE_MIN;
13643 rateProps[0] = r_j/R_i;
13644 rateProps[1] = 1 - rateProps[0];
13647 /* update n_i, n_j, R_i and R_j after split */
13653 /* we divide R_i equally among remaining components of split group,
13654 and R_j equally among new or expanded group */
13655 for (i=0; i<6; i++)
13657 if (newGrowthFxn[i] == groupIndex_i)
13658 newValue[i] = R_i / (MrBFlt)(n_i);
13659 else if (newGrowthFxn[i] == groupIndex_j)
13660 newValue[i] = R_j / (MrBFlt)(n_j);
13662 newValue[i] = oldValue[i];
13665 /* calculate prior ratio */
13668 /* no new category created by split */
13669 (*lnPriorRatio) += LnGamma((n_i +1)* symDir) + LnGamma((n_j-1) * symDir);
13670 (*lnPriorRatio) -= LnGamma (n_i * symDir) + LnGamma(n_j * symDir);
13671 (*lnPriorRatio) += (n_i * symDir - 1.0) * log(R_i) + (n_j * symDir - 1.0) * log(R_j);
13672 (*lnPriorRatio) -= ((n_i + 1) * symDir - 1.0) * log(R_i + r_j) + ((n_j - 1) * symDir - 1.0) * log(R_j - r_j);
13676 /* new category created by split */
13677 (*lnPriorRatio) += LnGamma((n_i +1)* symDir);
13678 (*lnPriorRatio) -= LnGamma (n_i * symDir) + LnGamma(n_j * symDir);
13679 (*lnPriorRatio) += (n_i * symDir - 1.0) * log(R_i) + (n_j * symDir - 1.0) * log(R_j);
13680 (*lnPriorRatio) -= ((n_i + 1) * symDir - 1.0) * log(R_i + r_j);
13683 /* calculate proposal ratio; this is one over the probability of choosing the right category for rate j when splitting */
13684 k = GetKFromGrowthFxn(oldGrowthFxn);
13685 (*lnProposalRatio) = log (k);
13687 /* adjust for Beta proposal in back move */
13690 dirParm[0] = alphaPi * 1;
13691 dirParm[1] = alphaPi * (n_j - 1);
13692 rateProps[0] = r_j / R_j;
13693 rateProps[1] = 1.0 - rateProps[0];
13694 x = LnGamma(dirParm[0] + dirParm[1]);
13695 x -= LnGamma(dirParm[0]);
13696 x -= LnGamma(dirParm[1]);
13697 x += (dirParm[0] - 1.0) * log(rateProps[0]);
13698 x += (dirParm[1] - 1.0) * log(rateProps[1]);
13699 (*lnProposalRatio) += x;
13702 /* adjust for Beta proposal in forward move */
13703 dirParm[0] = alphaPi * 1;
13704 dirParm[1] = alphaPi * n_i;
13705 rateProps[0] = r_j / (R_i + r_j);
13706 rateProps[1] = 1.0 - rateProps[0];
13707 x = LnGamma(dirParm[0] + dirParm[1]);
13708 x -= LnGamma(dirParm[0]);
13709 x -= LnGamma(dirParm[1]);
13710 x += (dirParm[0] - 1.0) * log(rateProps[0]);
13711 x += (dirParm[1] - 1.0) * log(rateProps[1]);
13712 (*lnProposalRatio) -= x;
13715 (*lnProposalRatio) += log (R_i + r_j);
13717 (*lnProposalRatio) -= log (R_j);
13720 /* Set update flags for all partitions that share this revmat. Note that the conditional
13721 likelihood update flags have been set before we even call this function. */
13722 for (i=0; i<param->nRelParts; i++)
13723 TouchAllTreeNodes(&modelSettings[param->relParts[i]],chain);
13725 /* Set update flags for cijks for all affected partitions */
13726 for (i=0; i<param->nRelParts; i++)
13727 modelSettings[param->relParts[i]].upDateCijk = YES;
13733 int Move_Speciation (Param *param, int chain, RandLong *seed, MrBFlt *lnPriorRatio, MrBFlt *lnProposalRatio, MrBFlt *mvp)
13735 /* change speciation rate using sliding window */
13737 int isLPriorExp, isValidL, valIndex;
13738 MrBFlt *valPtr, oldL, newL, minL, maxL, lambdaExp=0.0, *sR, *eR, sF, *fR, oldLnPrior, newLnPrior,
13745 /* get size of window, centered on current value */
13748 /* get model params and settings */
13749 mp = &modelParams[param->relParts[0]];
13750 m = &modelSettings[param->relParts[0]];
13752 /* get minimum and maximum values */
13753 if (param->paramId == SPECRATE_UNI)
13755 minL = mp->speciationUni[0];
13756 maxL = mp->speciationUni[1];
13763 lambdaExp = mp->speciationExp;
13767 /* get pointer to value to be changed */
13768 valIndex = (int)(RandomNumber(seed) * param->nValues);
13769 valPtr = GetParamVals(param, chain, state[chain]) + valIndex;
13771 /* get old value */
13775 if (maxL-minL < window)
13776 window = maxL-minL;
13777 newL = oldL + window * (RandomNumber(seed) - 0.5);
13779 /* check that new value is valid */
13783 newL = 2 * minL - newL;
13784 else if (newL > maxL)
13785 newL = 2 * maxL - newL;
13788 } while (isValidL == NO);
13790 /* get proposal ratio */
13791 *lnProposalRatio = 0.0;
13793 /* calculate prior ratio */
13794 t = GetTree(modelSettings[param->relParts[0]].brlens,chain,state[chain]);
13795 sR = GetParamVals (param, chain, state[chain]);
13796 eR = GetParamVals (m->extinctionRates, chain, state[chain]);
13797 sF = mp->sampleProb;
13798 sS = mp->sampleStrat;
13799 clockRate = *GetParamVals (m->clockRate, chain, state[chain]);
13801 if (!strcmp(mp->clockPr,"Birthdeath"))
13803 if (LnBirthDeathPriorPr (t, clockRate, &oldLnPrior, *sR, *eR, sS, sF) == ERROR)
13805 MrBayesPrint ("%s Problem calculating prior for birth-death process\n", spacer);
13808 *valPtr = newL; // update with new value
13809 if (LnBirthDeathPriorPr (t, clockRate, &newLnPrior, *sR, *eR, sS, sF) == ERROR)
13811 MrBayesPrint ("%s Problem calculating prior for birth-death process\n", spacer);
13815 else if (!strcmp(mp->clockPr,"Fossilization"))
13817 fR = GetParamVals (m->fossilizationRates, chain, state[chain]);
13818 if (LnFossilizationPriorPr (t, clockRate, &oldLnPrior, sR, eR, sF, fR, sS) == ERROR)
13820 MrBayesPrint ("%s Problem calculating prior for fossilized birth-death process\n", spacer);
13823 *valPtr = newL; // update with new value
13824 // for (i=0; i<param->nValues; i++) *(GetParamVals(param, chain, state[chain]) + i) = newL;
13825 if (LnFossilizationPriorPr (t, clockRate, &newLnPrior, sR, eR, sF, fR, sS) == ERROR)
13827 MrBayesPrint ("%s Problem calculating prior for fossilized birth-death process\n", spacer);
13832 MrBayesPrint ("%s Move_Speciation not applicable\n", spacer);
13836 if (isLPriorExp == NO)
13837 *lnPriorRatio = newLnPrior - oldLnPrior;
13839 *lnPriorRatio = -lambdaExp * (newL - oldL) + (newLnPrior - oldLnPrior);
13845 int Move_Speciation_M (Param *param, int chain, RandLong *seed, MrBFlt *lnPriorRatio, MrBFlt *lnProposalRatio, MrBFlt *mvp)
13847 /* change speciation rate using multiplier */
13849 int isLPriorExp, isValidL, valIndex;
13850 MrBFlt *valPtr, oldL, newL, minL, maxL, lambdaExp=0.0, *sR, *eR, sF, *fR, oldLnPrior, newLnPrior,
13857 /* get tuning parameter */
13860 /* get model params and settings */
13861 mp = &modelParams[param->relParts[0]];
13862 m = &modelSettings[param->relParts[0]];
13864 /* get minimum and maximum values */
13865 if (param->paramId == SPECRATE_UNI)
13867 minL = mp->speciationUni[0];
13868 maxL = mp->speciationUni[1];
13875 lambdaExp = mp->speciationExp;
13879 /* get pointer to value to be changed */
13880 valIndex = (int)(RandomNumber(seed) * param->nValues);
13881 valPtr = GetParamVals(param, chain, state[chain]) + valIndex;
13883 /* get old value */
13887 newL = oldL * exp(tuning * (RandomNumber(seed) - 0.5));
13889 /* check that new value is valid */
13893 newL = minL * minL / newL;
13894 else if (newL > maxL)
13895 newL = maxL * maxL / newL;
13898 } while (isValidL == NO);
13900 /* get proposal ratio */
13901 *lnProposalRatio = log (newL / oldL);
13903 /* calculate prior ratio */
13904 t = GetTree(modelSettings[param->relParts[0]].brlens,chain,state[chain]);
13905 sR = GetParamVals (param, chain, state[chain]);
13906 eR = GetParamVals (m->extinctionRates, chain, state[chain]);
13907 sF = mp->sampleProb;
13908 sS = mp->sampleStrat;
13909 clockRate = *GetParamVals(m->clockRate, chain, state[chain]);
13911 if (!strcmp(mp->clockPr,"Birthdeath"))
13913 if (LnBirthDeathPriorPr (t, clockRate, &oldLnPrior, *sR, *eR, sS, sF) == ERROR)
13915 MrBayesPrint ("%s Problem calculating prior for birth-death process\n", spacer);
13918 *valPtr = newL; // update with new value
13919 if (LnBirthDeathPriorPr (t, clockRate, &newLnPrior, *sR, *eR, sS, sF) == ERROR)
13921 MrBayesPrint ("%s Problem calculating prior for birth-death process\n", spacer);
13925 else if (!strcmp(mp->clockPr,"Fossilization"))
13927 fR = GetParamVals (m->fossilizationRates, chain, state[chain]);
13928 if (LnFossilizationPriorPr (t, clockRate, &oldLnPrior, sR, eR, sF, fR, sS) == ERROR)
13930 MrBayesPrint ("%s Problem calculating prior for fossilized birth-death process\n", spacer);
13933 *valPtr = newL; // update with new value
13934 // for (i=0; i<param->nValues; i++) *(GetParamVals(param, chain, state[chain]) + i) = newL;
13935 if (LnFossilizationPriorPr (t, clockRate, &newLnPrior, sR, eR, sF, fR, sS) == ERROR)
13937 MrBayesPrint ("%s Problem calculating prior for fossilized birth-death process\n", spacer);
13942 MrBayesPrint ("%s Move_Speciation_M not applicable\n", spacer);
13946 if (isLPriorExp == NO)
13947 *lnPriorRatio = newLnPrior - oldLnPrior;
13949 *lnPriorRatio = -lambdaExp * (newL - oldL) + (newLnPrior - oldLnPrior);
13955 int Move_Statefreqs (Param *param, int chain, RandLong *seed, MrBFlt *lnPriorRatio, MrBFlt *lnProposalRatio, MrBFlt *mvp)
13958 int i, nStates, isValid;
13959 MrBFlt dirichletParameters[64], *newPi, *oldPi, *priorAlpha, sum, alphaPi, x, y;
13961 /* get the values we need */
13962 nStates = param->nSubValues;
13963 priorAlpha = GetParamVals(param, chain, state[chain]);
13964 newPi = GetParamSubVals (param, chain, state[chain]);
13965 oldPi = GetParamSubVals (param, chain, state[chain] ^ 1);
13967 /* tuning parameter */
13968 alphaPi = mvp[0]*nStates;
13970 /* multiply old values with some large number to get new values close to the old ones */
13971 for (i=0; i<nStates; i++)
13972 dirichletParameters[i] = oldPi[i] * alphaPi;
13975 DirichletRandomVariable (dirichletParameters, newPi, nStates, seed);
13977 for (i=0; i<nStates; i++)
13979 if (newPi[i] < PI_MIN)
13985 } while (isValid == NO);
13987 /* get proposal ratio */
13989 for (i=0; i<nStates; i++)
13990 sum += newPi[i]*alphaPi;
13992 for (i=0; i<nStates; i++)
13993 x -= LnGamma(newPi[i]*alphaPi);
13994 for (i=0; i<nStates; i++)
13995 x += (newPi[i]*alphaPi-1.0)*log(oldPi[i]);
13997 for (i=0; i<nStates; i++)
13998 sum += oldPi[i]*alphaPi;
14000 for (i=0; i<nStates; i++)
14001 y -= LnGamma(oldPi[i]*alphaPi);
14002 for (i=0; i<nStates; i++)
14003 y += (oldPi[i]*alphaPi-1.0)*log(newPi[i]);
14004 (*lnProposalRatio) = x - y;
14006 /* get prior ratio */
14007 y = x = 0.0; /* the Gamma part of the prior is the same */
14008 for (i=0; i<nStates; i++)
14009 x += (priorAlpha[i]-1.0)*log(newPi[i]);
14010 for (i=0; i<nStates; i++)
14011 y += (priorAlpha[i]-1.0)*log(oldPi[i]);
14012 (*lnPriorRatio) = x - y;
14014 /* Touch the entire tree */
14015 for (i=0; i<param->nRelParts; i++)
14016 TouchAllTreeNodes(&modelSettings[param->relParts[i]],chain);
14018 /* Set update flags for cijks for all affected partitions. If this is a simple 4 X 4 model,
14019 we don't take any hit, because we will never go into a general transition probability
14020 calculator. However, for many models we do want to update the cijk flag, as the transition
14021 probability matrices require diagonalizing the rate matrix. */
14022 for (i=0; i<param->nRelParts; i++)
14023 modelSettings[param->relParts[i]].upDateCijk = YES;
14029 /*----------------------------------------------------------------
14031 | Move_Statefreqs_Slider: Change state frequencies using Slider proposal
14033 | Choose pairs of the parameter values (e.g. pi(A), and pi(G)) at
14034 | random and denote them piA, and piB. Let oldProp = piA/(piA + piB)
14035 | and newProp = oldProp + delta(U - 0.5), where U is a uniform random variable
14036 | on the interval (0, 1] and delta is a tuning parameter. Values
14037 | that fall outside the boundaries are reflected back in. Then
14038 | set newPiA = newProp*(piA+piB) and newPiB = (1-newProp)*(piA+piB).
14039 | The Hastings ratio of this move is 1.0.
14041 ----------------------------------------------------------------*/
14042 int Move_Statefreqs_Slider (Param *param, int chain, RandLong *seed, MrBFlt *lnPriorRatio, MrBFlt *lnProposalRatio, MrBFlt *mvp)
14044 int i, j, nStates, isValid;
14045 MrBFlt delta, *newPi, *oldPi, *priorAlpha, x, y, sum, min, max;
14047 /* get the values we need */
14048 nStates = param->nSubValues;
14049 priorAlpha = GetParamVals(param, chain, state[chain]);
14050 newPi = GetParamSubVals (param, chain, state[chain]);
14051 oldPi = GetParamSubVals (param, chain, state[chain] ^ 1);
14053 /* get window size */
14056 /* choose a pair to change */
14057 i = (int) (RandomNumber(seed) * nStates);
14058 j = (int) (RandomNumber(seed) * (nStates-1));
14062 /* find new proportion */
14063 sum = oldPi[i] + oldPi[j];
14067 min = PI_MIN / sum;
14070 x = oldPi[i] / sum;
14071 if (delta > max-min) /* we do it to avoid following long while loop in case if delta is high */
14075 y = x + delta * (RandomNumber(seed) - 0.5);
14084 } while (isValid == NO);
14086 /* set the new values */
14087 newPi[i] = y * sum;
14088 newPi[j] = sum - newPi[i];
14090 /* get proposal ratio */
14091 *lnProposalRatio = 0.0;
14093 /* get prior ratio */
14094 /* (the Gamma part of the prior is the same) */
14095 x = (priorAlpha[i]-1.0)*log(newPi[i]);
14096 x += (priorAlpha[j]-1.0)*log(newPi[j]);
14097 y = (priorAlpha[i]-1.0)*log(oldPi[i]);
14098 y += (priorAlpha[j]-1.0)*log(oldPi[j]);
14099 (*lnPriorRatio) = x - y;
14101 /* Set update for entire tree */
14102 for (i=0; i<param->nRelParts; i++)
14103 TouchAllTreeNodes(&modelSettings[param->relParts[i]],chain);
14105 /* Set update flags for cijks for all affected partitions. If this is a simple 4 X 4 model,
14106 we don't take any hit, because we will never go into a general transition probability
14107 calculator. However, for many models we do want to update the cijk flag, as the transition
14108 probability matrices require diagonalizing the rate matrix. */
14109 for (i=0; i<param->nRelParts; i++)
14110 modelSettings[param->relParts[i]].upDateCijk = YES;
14116 int Move_StatefreqsSymDirMultistate (Param *param, int chain, RandLong *seed, MrBFlt *lnPriorRatio, MrBFlt *lnProposalRatio, MrBFlt *mvp)
14118 /* change state freqs of multistate characters */
14119 /* ideally, we would let the likelihood calculator deal with only the affected character
14120 but we do not have the mechanism for doing that in the current version of mrbayes, so
14121 take the hit of updating all chars of the morph partition(s). */
14122 int i, nStates, charIndex;
14123 MrBFlt dirichletParameters[10], symDirAlphai, *newPi, *oldPi, sum, alphaPi, x, y;
14126 /* tuning parameters */
14129 /* get model paramaters */
14130 mp = &modelParams[param->relParts[0]];
14132 /* select one character at random */
14133 charIndex = (int) (RandomNumber(seed) * param->nSympi);
14135 /* get the values we need */
14136 symDirAlphai = *GetParamVals(param, chain, state[chain]);
14137 newPi = GetParamStdStateFreqs (param, chain, state[chain]);
14138 oldPi = GetParamStdStateFreqs (param, chain, state[chain] ^ 1);
14139 newPi += 2 * mp->numBetaCats;
14140 oldPi += 2 * mp->numBetaCats;
14141 for (i=0; i<charIndex; i++)
14143 oldPi += param->sympinStates[i];
14144 newPi += param->sympinStates[i];
14146 nStates = param->sympinStates[charIndex];
14148 /* multiply old values with some large number to get new values close to the old ones */
14149 for (i=0; i<nStates; i++)
14150 dirichletParameters[i] = oldPi[i] * alphaPi;
14152 DirichletRandomVariable (dirichletParameters, newPi, nStates, seed);
14155 for (i=0; i<nStates; i++)
14157 if (newPi[i] < 0.0001)
14161 for (i=0; i<nStates; i++)
14164 /* get proposal ratio */
14166 for (i=0; i<nStates; i++)
14167 sum += newPi[i]*alphaPi;
14169 for (i=0; i<nStates; i++)
14170 x -= LnGamma(newPi[i]*alphaPi);
14171 for (i=0; i<nStates; i++)
14172 x += (newPi[i]*alphaPi-1.0)*log(oldPi[i]);
14174 for (i=0; i<nStates; i++)
14175 sum += oldPi[i]*alphaPi;
14177 for (i=0; i<nStates; i++)
14178 y -= LnGamma(oldPi[i]*alphaPi);
14179 for (i=0; i<nStates; i++)
14180 y += (oldPi[i]*alphaPi-1.0)*log(newPi[i]);
14181 (*lnProposalRatio) = x - y;
14183 /* get prior ratio */
14184 y = x = 0.0; /* the Gamma part of the prior is the same */
14185 for (i=0; i<nStates; i++)
14186 x += (symDirAlphai-1.0)*log(newPi[i]);
14187 for (i=0; i<nStates; i++)
14188 y += (symDirAlphai-1.0)*log(oldPi[i]);
14189 (*lnPriorRatio) = x - y;
14191 for (i=0; i<param->nRelParts; i++)
14192 TouchAllTreeNodes(&modelSettings[param->relParts[i]],chain);
14194 /* Set update flags for cijks for all affected partitions. Only cijks for the changed character
14195 actually need to be updated but we can't do that in the current version of the program. */
14196 for (i=0; i<param->nRelParts; i++)
14197 modelSettings[param->relParts[i]].upDateCijk = YES;
14203 int Move_SwitchRate (Param *param, int chain, RandLong *seed, MrBFlt *lnPriorRatio, MrBFlt *lnProposalRatio, MrBFlt *mvp)
14205 /* change switch rate of covarion model using sliding window */
14207 int i, isSPriorExp, isValidS, whichRate;
14208 MrBFlt oldS, newS, window, minS, maxS, sExp=0.0, ran, *value;
14211 /* decide which switching rate to change */
14212 if (RandomNumber(seed) < 0.5)
14217 /* get size of window, centered on current switching rates value */
14220 /* get model params */
14221 mp = &modelParams[param->relParts[0]];
14223 /* get minimum and maximum values for switching rate */
14224 if (param->paramId == SWITCH_UNI)
14226 minS = mp->covswitchUni[0];
14227 maxS = mp->covswitchUni[1];
14234 sExp = mp->covswitchExp;
14238 /* get old value of switching rate */
14239 value = GetParamVals(param, chain, state[chain]);
14240 newS = oldS = value[whichRate];
14242 /* change value for switching rate */
14243 ran = RandomNumber(seed);
14244 if (maxS-minS < window)
14246 window = maxS-minS;
14248 newS = oldS + window * (ran - 0.5);
14250 /* check that new value is valid */
14255 newS = 2* minS - newS;
14256 else if (newS > maxS)
14257 newS = 2 * maxS - newS;
14260 } while (isValidS == NO);
14262 /* get proposal ratio */
14263 *lnProposalRatio = 0.0;
14265 /* get prior ratio */
14266 if (isSPriorExp == NO)
14267 *lnPriorRatio = 0.0;
14269 *lnPriorRatio = -sExp * (newS - oldS);
14271 /* copy new switching rate value back */
14272 value[whichRate] = newS;
14274 /* Set update flags for all partitions that share this switching rate. Note that the conditional
14275 likelihood update flags have been set before we even call this function. */
14276 for (i=0; i<param->nRelParts; i++)
14277 TouchAllTreeNodes(&modelSettings[param->relParts[i]],chain);
14279 /* Set update flags for cijks for all affected partitions. If this is a simple 4 X 4 model,
14280 we don't take any hit, because we will never go into a general transition probability
14281 calculator. However, for covarion, doublet, and codon models, we do want to update
14283 for (i=0; i<param->nRelParts; i++)
14284 modelSettings[param->relParts[i]].upDateCijk = YES;
14290 int Move_SwitchRate_M (Param *param, int chain, RandLong *seed, MrBFlt *lnPriorRatio, MrBFlt *lnProposalRatio, MrBFlt *mvp)
14292 /* change switch rate of covarion model using multiplier */
14294 int i, isSPriorExp, isValidS, whichRate;
14295 MrBFlt oldS, newS, minS, maxS, sExp=0.0, tuning, ran, factor, *value;
14298 /* decide which switching rate to change */
14299 if (RandomNumber(seed) < 0.5)
14304 /* get tuning parameter */
14307 /* get model params */
14308 mp = &modelParams[param->relParts[0]];
14310 /* get minimum and maximum values for switching rate */
14311 if (param->paramId == SWITCH_UNI)
14313 minS = mp->covswitchUni[0];
14314 maxS = mp->covswitchUni[1];
14321 sExp = mp->covswitchExp;
14325 /* get old value of switching rate */
14326 value = GetParamVals(param, chain, state[chain]);
14327 newS = oldS = value[whichRate];
14329 /* change value for switching rate */
14330 ran = RandomNumber(seed);
14331 factor = exp(tuning * (ran - 0.5));
14332 newS = oldS * factor;
14334 /* check that new value is valid */
14339 newS = minS * minS / newS;
14340 else if (newS > maxS)
14341 newS = maxS * maxS / newS;
14344 } while (isValidS == NO);
14346 /* get proposal ratio */
14347 *lnProposalRatio = log (newS / oldS);
14349 /* get prior ratio */
14350 if (isSPriorExp == NO)
14351 *lnPriorRatio = 0.0;
14353 *lnPriorRatio = -sExp * (newS - oldS);
14355 /* copy new switching rate value back */
14356 value[whichRate] = newS;
14358 /* Set update flags for all partitions that share this switching rate. Note that the conditional
14359 likelihood update flags have been set before we even call this function. */
14360 for (i=0; i<param->nRelParts; i++)
14361 TouchAllTreeNodes(&modelSettings[param->relParts[i]],chain);
14363 /* Set update flags for cijks for all affected partitions. If this is a simple 4 X 4 model,
14364 we don't take any hit, because we will never go into a general transition probability
14365 calculator. However, for covarion, doublet, and codon models, we do want to update
14367 for (i=0; i<param->nRelParts; i++)
14368 modelSettings[param->relParts[i]].upDateCijk = YES;
14374 int Move_TK02BranchRate (Param *param, int chain, RandLong *seed, MrBFlt *lnPriorRatio, MrBFlt *lnProposalRatio, MrBFlt *mvp)
14376 /* move one TK02 relaxed clock branch rate using multiplier */
14379 MrBFlt newRate, oldRate, tuning, minR, maxR, nu, *tk02Rate, *brlens;
14380 TreeNode *p = NULL;
14385 /* get model settings */
14386 m = &modelSettings[param->relParts[0]];
14388 /* get the tuning parameter */
14391 /* get the TK02 branch rate and effective branch length data */
14392 tk02Rate = GetParamVals (param, chain, state[chain]);
14393 brlens = GetParamSubVals (param, chain, state[chain]);
14396 t = GetTree (param, chain, state[chain]);
14398 /* get minimum and maximum rate */
14402 /* randomly pick a rate */
14404 i = (int) (RandomNumber(seed) * (t->nNodes -2));
14405 p = t->allDownPass[i];
14407 while (p->length < TIME_MIN); // not ancestral fossil
14409 /* find new rate */
14410 oldRate = tk02Rate[p->index];
14411 newRate = oldRate * exp ((0.5 - RandomNumber(seed)) * tuning);
14413 /* reflect if necessary */
14414 while (newRate < minR || newRate > maxR)
14416 if (newRate < minR)
14417 newRate = minR * minR / newRate;
14418 if (newRate > maxR)
14419 newRate = maxR * maxR / newRate;
14422 tk02Rate[p->index] = newRate;
14424 /* calculate prior ratio */
14425 nu = *GetParamVals (m->tk02var, chain, state[chain]);
14426 (*lnPriorRatio) = LnRatioTK02LogNormal (tk02Rate[p->anc->index], nu*p->length, newRate, oldRate);
14427 if (p->left != NULL)
14429 if (p->left->length > 0.0)
14431 (*lnPriorRatio) -= LnProbTK02LogNormal (oldRate, nu*p->left->length, tk02Rate[p->left->index ]);
14432 (*lnPriorRatio) += LnProbTK02LogNormal (newRate, nu*p->left->length, tk02Rate[p->left->index ]);
14434 if (p->right->length > 0.0)
14436 (*lnPriorRatio) -= LnProbTK02LogNormal (oldRate, nu*p->right->length, tk02Rate[p->right->index]);
14437 (*lnPriorRatio) += LnProbTK02LogNormal (newRate, nu*p->right->length, tk02Rate[p->right->index]);
14441 /* calculate proposal ratio */
14442 (*lnProposalRatio) = log (newRate / oldRate);
14444 /* update branch evolution lengths */
14445 brlens[p->index] = p->length * (newRate + tk02Rate[p->anc->index]) / 2.0;
14446 if (p->left != NULL)
14448 if (p->left->length > 0.0)
14450 brlens[p->left->index] = p->left->length * (tk02Rate[p->left->index] + newRate) / 2.0;
14452 if (p->right->length > 0.0)
14454 brlens[p->right->index] = p->right->length * (tk02Rate[p->right->index] + newRate) / 2.0;
14458 /* set update of ti probs */
14460 if (p->left != NULL)
14462 p->left ->upDateTi = YES;
14463 p->right->upDateTi = YES;
14466 /* set update of cond likes down to root */
14467 /* update of crowntree set in UpdateCppEvolLengths */
14470 while (q->anc != NULL)
14480 int Move_Tratio_Dir (Param *param, int chain, RandLong *seed, MrBFlt *lnPriorRatio, MrBFlt *lnProposalRatio, MrBFlt *mvp)
14482 /* change tratio using Dirichlet proposal */
14485 MrBFlt oldK, alphaPi, *alphaDir, oldProp[2], newProp[2], dirParm[2], sum, x, y;
14488 /* get model params */
14489 mp = &modelParams[param->relParts[0]];
14491 /* get so called alphaPi parameter */
14494 /* get old value of kappa */
14495 oldK = *GetParamVals(param, chain, state[chain]);
14497 /* get Dirichlet parameters */
14498 alphaDir = mp->tRatioDir;
14500 /* calculate old ratesum proportions */
14501 oldProp[0] = oldK / (oldK + 1.0);
14502 oldProp[1] = 1.0 - oldProp[0];
14504 /* multiply old ratesum props with some large number to get new values close to the old ones */
14505 dirParm[0] = oldProp[0] * alphaPi;
14506 dirParm[1] = oldProp[1] * alphaPi;
14508 /* get new values */
14509 DirichletRandomVariable (dirParm, newProp, 2, seed);
14511 if (newProp[0] < DIR_MIN)
14513 newProp[0] = DIR_MIN;
14514 newProp[1] = 1.0-DIR_MIN;
14516 else if (newProp[1] < DIR_MIN)
14518 newProp[1] = DIR_MIN;
14519 newProp[0] = 1.0-DIR_MIN;
14522 /* calculate and copy new kappa value back */
14523 *GetParamVals(param, chain, state[chain]) = newProp[0] / newProp[1];
14525 /* get proposal ratio */
14527 for (i=0; i<2; i++)
14528 sum += newProp[i]*alphaPi;
14530 for (i=0; i<2; i++)
14531 x -= LnGamma(newProp[i]*alphaPi);
14532 for (i=0; i<2; i++)
14533 x += (newProp[i]*alphaPi-1.0)*log(oldProp[i]);
14535 for (i=0; i<2; i++)
14536 sum += oldProp[i]*alphaPi;
14538 for (i=0; i<2; i++)
14539 y -= LnGamma(oldProp[i]*alphaPi);
14540 for (i=0; i<2; i++)
14541 y += (oldProp[i]*alphaPi-1.0)*log(newProp[i]);
14542 (*lnProposalRatio) = x - y;
14544 /* get prior ratio */
14546 for (i=0; i<2; i++)
14547 x += (alphaDir[i]-1.0)*log(newProp[i]);
14548 for (i=0; i<2; i++)
14549 y += (alphaDir[i]-1.0)*log(oldProp[i]);
14550 (*lnPriorRatio) = x - y;
14552 /* Set update flags for all partitions that share this kappa. Note that the conditional
14553 likelihood update flags have been set before we even call this function. */
14554 for (i=0; i<param->nRelParts; i++)
14555 TouchAllTreeNodes(&modelSettings[param->relParts[i]],chain);
14557 /* Set update flags for cijks for all affected partitions. If this is a simple 4 X 4 model,
14558 we don't take any hit, because we will never go into a general transition probability
14559 calculator. However, for covarion, doublet, and codon models, we do want to update
14561 for (i=0; i<param->nRelParts; i++)
14562 modelSettings[param->relParts[i]].upDateCijk = YES;
14568 /* Code added by Jeremy Brown and modified by Maxim Teslenko */
14569 int Move_TreeLen (Param *param, int chain, RandLong *seed, MrBFlt *lnPriorRatio, MrBFlt *lnProposalRatio, MrBFlt *mvp)
14571 /* change all branch lengths */
14573 MrBFlt begin_tl, treescaler, tuning, maxV, minV, brlensPrExp=0.0;
14577 int i,branch_counter, isVPriorExp;
14579 tuning = mvp[0]; /* Larget & Simon's tuning parameter lambda */
14581 mp = &modelParams[param->relParts[0]];
14583 /* max and min brlen */
14584 if (param->paramId == BRLENS_UNI)
14586 minV = mp->brlensUni[0];
14587 maxV = mp->brlensUni[1];
14590 else if (param->paramId == BRLENS_GamDir)
14596 else if (param->paramId == BRLENS_iGmDir)
14602 else if (param->paramId == BRLENS_twoExp)
14612 brlensPrExp = mp->brlensExp;
14617 t = GetTree (param, chain, state[chain]);
14619 assert (t->isRooted == NO);
14621 /* Dirichlet or twoExp prior */
14622 if (isVPriorExp > 1)
14623 (*lnPriorRatio) = -LogDirPrior(t, mp, isVPriorExp);
14625 treescaler = exp(tuning * (RandomNumber(seed) - 0.5));
14630 for (i=0; i<t->nNodes; i++)
14632 p = t->allDownPass[i];
14633 if (p->anc != NULL)
14635 if (p->length*treescaler < minV || p->length*treescaler > maxV)
14640 begin_tl += p->length;
14644 assert (branch_counter==t->nNodes-1);
14646 /* iterate scaling over all branches */
14647 for (i=0; i < t->nNodes; i++)
14649 p = t->allDownPass[i];
14650 if (p->anc != NULL)
14652 /* set new length */
14653 p->length *= treescaler;
14655 /* set flags for update of transition probabilities at p */
14657 p->anc->upDateCl = YES;
14661 /* calculate proposal ratio */
14662 (*lnProposalRatio) = branch_counter * log(treescaler);
14664 /* update prior if exponential prior on branch lengths */
14665 if (param->paramId == BRLENS_EXP)
14666 (*lnPriorRatio) = brlensPrExp * (begin_tl* (1 - treescaler));
14667 /* Dirichlet or twoExp prior */
14668 else if (isVPriorExp > 1)
14669 (*lnPriorRatio) += LogDirPrior(t, mp, isVPriorExp);
14675 /*-----------------------------------------------------------------------------------
14677 | Move_TreeStretch: Shrink or grow a clock tree
14679 -------------------------------------------------------------------------------------*/
14680 int Move_TreeStretch (Param *param, int chain, RandLong *seed, MrBFlt *lnPriorRatio, MrBFlt *lnProposalRatio, MrBFlt *mvp)
14682 int i, j, *nEvents, numChangedNodes;
14683 MrBFlt minV, maxV, tuning, factor, lambda=0.0, x,
14684 *brlens=NULL, nu=0.0, igrvar=0.0, *tk02Rate=NULL, *igrRate=NULL;
14690 Calibration *calibrationPtr;
14692 tuning = mvp[0]; /* Larget & Simon tuning parameter lambda */
14694 (*lnProposalRatio) = (*lnPriorRatio) = 0.0;
14696 m = &modelSettings[param->relParts[0]];
14697 mp = &modelParams[param->relParts[0]];
14700 t = GetTree (param, chain, state[chain]);
14701 oldT = GetTree (param, chain, 1^state[chain]);
14703 /* min and max branch lengths in relative time and substitution units */
14707 /* determine multiplication factor */
14708 factor = exp(tuning * (RandomNumber(seed) - 0.5));
14710 /* multiply all changeable ages and node depths by this factor */
14711 numChangedNodes = 0;
14712 for (i=0; i<t->nNodes-1; i++)
14714 p = t->allDownPass[i];
14716 /* skip extant tip and fixed calibration */
14717 if (p->left == NULL && p->isDated == NO)
14719 if (p->isDated == YES)
14720 calibrationPtr = p->calibration;
14721 else if (p->anc->anc == NULL && (!strcmp(mp->clockPr,"Uniform") || !strcmp(mp->clockPr,"Fossilization")))
14722 calibrationPtr = &mp->treeAgePr;
14724 calibrationPtr = NULL;
14725 if (calibrationPtr != NULL && calibrationPtr->prior == fixed)
14728 /* now stretch the node */
14729 if (calibrationPtr != NULL)
14732 if (p->age < calibrationPtr->min || p->age > calibrationPtr->max)
14738 p->nodeDepth *= factor;
14741 /* deal with ancestral fossils */
14742 if (p->left != NULL)
14744 if (p->left->length < TIME_MIN)
14746 p->left->length = 0.0;
14747 p->nodeDepth = p->left->nodeDepth;
14748 if (calibrationPtr != NULL)
14750 assert (p->left->calibration != NULL);
14751 p->age = p->left->age;
14752 if (p->age < calibrationPtr->min || p->age > calibrationPtr->max)
14760 if (p->right->length < TIME_MIN)
14762 p->right->length = 0.0;
14763 p->nodeDepth = p->right->nodeDepth;
14764 if (calibrationPtr != NULL)
14766 assert (p->right->calibration != NULL);
14767 p->age = p->right->age;
14768 if (p->age < calibrationPtr->min || p->age > calibrationPtr->max)
14776 assert (!(p->left->length == 0.0 && p->right->length == 0.0));
14781 for (i=0; i<t->nNodes-1; i++)
14783 p = t->allDownPass[i];
14784 if (p->left != NULL)
14786 if (p->left->length > 0.0)
14787 p->left->length = p->nodeDepth - p->left->nodeDepth;
14788 if (p->right->length > 0.0)
14789 p->right->length = p->nodeDepth - p->right->nodeDepth;
14793 /* check that all branch lengths are proper, which need not be the case */
14794 for (i = 0; i < t->nNodes -2; i++)
14796 p = t->allDownPass[i];
14797 q = oldT->allDownPass[i];
14798 if (p->length < 0.0 || p->length > maxV || (q->length > minV && p->length < minV) || (q->length < TIME_MIN && p->length > TIME_MIN))
14799 { /* consider ancestral fossil (brl=0) in fossilized bd tree */
14805 /* calculate proposal ratio */
14806 (*lnProposalRatio) = numChangedNodes * log(factor);
14808 /* calculate prior ratio */
14809 if (LogClockTreePriorRatio(param, chain, &x) == ERROR)
14811 (*lnPriorRatio) += x;
14813 /* adjust proposal and prior ratio for relaxed clock models */
14814 for (i=0; i<param->nSubParams; i++)
14816 subParm = param->subParams[i];
14817 if (subParm->paramType == P_CPPEVENTS)
14819 nEvents = subParm->nEvents[2*chain+state[chain]];
14820 lambda = *GetParamVals (modelSettings[subParm->relParts[0]].cppRate, chain, state[chain]);
14821 /* proposal ratio */
14822 for (j=0; j<t->nNodes-2; j++)
14824 p = t->allDownPass[j];
14825 q = oldT->allDownPass[j];
14826 (*lnProposalRatio) += nEvents[p->index ] * log (p->length / q->length);
14829 (*lnPriorRatio) += lambda * (TreeLen(oldT) - TreeLen(t));
14830 /* update effective evolutionary lengths */
14831 if (UpdateCppEvolLengths (subParm, t->root->left, chain) == ERROR)
14837 else if ( subParm->paramType == P_TK02BRANCHRATES ||
14838 (subParm->paramType == P_MIXEDBRCHRATES && *GetParamIntVals(subParm, chain, state[chain]) == RCL_TK02))
14840 if (subParm->paramType == P_TK02BRANCHRATES)
14841 nu = *GetParamVals (modelSettings[subParm->relParts[0]].tk02var, chain, state[chain]);
14843 nu = *GetParamVals (modelSettings[subParm->relParts[0]].mixedvar, chain, state[chain]);
14844 tk02Rate = GetParamVals (subParm, chain, state[chain]);
14845 brlens = GetParamSubVals (subParm, chain, state[chain]);
14847 /* prior ratio and update of brlens */
14848 for (j=0; j<t->nNodes-2; j++)
14850 p = t->allDownPass[j];
14851 q = oldT->allDownPass[j];
14852 if (p->length > 0.0) // not ancestral fossil
14854 (*lnPriorRatio) -= LnProbTK02LogNormal (tk02Rate[q->anc->index], nu*q->length, tk02Rate[q->index]);
14855 (*lnPriorRatio) += LnProbTK02LogNormal (tk02Rate[p->anc->index], nu*p->length, tk02Rate[p->index]);
14856 brlens[p->index] = p->length * (tk02Rate[p->anc->index]+tk02Rate[p->index])/2.0;
14857 if (brlens[p->index] < RELBRLENS_MIN || brlens[p->index] > RELBRLENS_MAX)
14865 else if ( subParm->paramType == P_IGRBRANCHRATES ||
14866 (subParm->paramType == P_MIXEDBRCHRATES && *GetParamIntVals(subParm, chain, state[chain]) == RCL_IGR))
14868 if (subParm->paramType == P_IGRBRANCHRATES)
14869 igrvar = *GetParamVals (modelSettings[subParm->relParts[0]].igrvar, chain, state[chain]);
14871 igrvar = *GetParamVals (modelSettings[subParm->relParts[0]].mixedvar, chain, state[chain]);
14872 igrRate = GetParamVals (subParm, chain, state[chain]);
14873 brlens = GetParamSubVals (subParm, chain, state[chain]);
14875 /* prior ratio and update of igr branch lengths and rates (stretched in the same way as tree) */
14876 for (j=0; j<t->nNodes-2; j++)
14878 p = t->allDownPass[j];
14879 q = oldT->allDownPass[j];
14880 if (p->length > 0.0) // not ancestral fossil
14882 (*lnPriorRatio) -= LnProbGamma (q->length/igrvar, q->length/igrvar, igrRate[q->index]);
14883 (*lnPriorRatio) += LnProbGamma (p->length/igrvar, p->length/igrvar, igrRate[p->index]);
14884 brlens[p->index] = p->length * igrRate[p->index];
14885 if (brlens[p->index] < RELBRLENS_MIN || brlens[p->index] > RELBRLENS_MAX)
14895 TouchAllTreeNodes(m, chain);
14897 #if defined (DEBUG_TREESTRETCH)
14898 printf ("After treestretch:\n");
14899 printf ("Old tree height: %f -- New tree height: %f -- lnPriorRatio = %f -- lnProposalRatio = %f\n",
14900 oldT->root->left->nodeDepth, t->root->left->nodeDepth, (*lnPriorRatio), (*lnProposalRatio));
14907 /* Generalized normal move for real random variables */
14908 int Move_RealNormal (Param *param, int chain, RandLong *seed, MrBFlt *lnPriorRatio, MrBFlt *lnProposalRatio, MrBFlt *mvp)
14911 MrBFlt oldX, newX, tuning, minX, maxX, u, z;
14913 /* get tuning parameter */
14916 /* get minimum and maximum values for X */
14920 /* get old value of X */
14921 newX = oldX = *GetParamVals(param, chain, state[chain]);
14924 u = RandomNumber(seed);
14925 z = PointNormal(u);
14926 newX = oldX + z * tuning;
14928 /* check that new value is valid */
14929 if (newX < minX || newX > maxX)
14935 /* get proposal ratio */
14936 (*lnProposalRatio) = 0.0;
14938 /* get prior ratio */
14939 (*lnPriorRatio) = param->LnPriorRatio(newX, oldX, param->priorParams);
14941 /* copy new value back */
14942 *GetParamVals(param, chain, state[chain]) = newX;
14944 /* Set update flags for tree nodes if relevant */
14945 if (param->affectsLikelihood == YES)
14947 for (i=0; i<param->nRelParts; i++)
14948 TouchAllTreeNodes(&modelSettings[param->relParts[i]],chain);
14955 /* Generalized slider move for real random variables */
14956 int Move_RealSlider (Param *param, int chain, RandLong *seed, MrBFlt *lnPriorRatio, MrBFlt *lnProposalRatio, MrBFlt *mvp)
14959 MrBFlt oldX, newX, window, minX, maxX, u;
14961 /* get size of window, centered on current value */
14964 /* get minimum and maximum values for X */
14968 /* get old value of X */
14969 newX = oldX = *GetParamVals(param, chain, state[chain]);
14972 u = RandomNumber(seed);
14973 newX = oldX + window * (u - 0.5);
14975 /* check that new value is valid */
14980 newX = 2* minX - newX;
14981 else if (newX > maxX)
14982 newX = 2 * maxX - newX;
14985 } while (isValid == NO);
14987 /* get proposal ratio */
14988 (*lnProposalRatio) = 0.0;
14990 /* get prior ratio */
14991 (*lnPriorRatio) = param->LnPriorRatio(newX, oldX, param->priorParams);
14993 /* copy new value back */
14994 *GetParamVals(param, chain, state[chain]) = newX;
14996 /* Set update flags for tree nodes if relevant */
14997 if (param->affectsLikelihood == YES)
14999 for (i=0; i<param->nRelParts; i++)
15000 TouchAllTreeNodes(&modelSettings[param->relParts[i]],chain);
15007 void TouchAllTreeNodes (ModelInfo *m, int chain)
15013 t = GetTree(m->brlens, chain, state[chain]);
15014 for (i=0; i<t->nNodes; i++)
15016 p = t->allDownPass[i];
15020 m->upDateAll = YES;