]> git.donarmstrong.com Git - mrbayes.git/blob - src/proposal.c
import mrbayes
[mrbayes.git] / src / proposal.c
1 /*
2  *  MrBayes 3
3  *
4  *  (c) 2002-2013
5  *
6  *  John P. Huelsenbeck
7  *  Dept. Integrative Biology
8  *  University of California, Berkeley
9  *  Berkeley, CA 94720-3140
10  *  johnh@berkeley.edu
11  *
12  *  Fredrik Ronquist
13  *  Swedish Museum of Natural History
14  *  Box 50007
15  *  SE-10405 Stockholm, SWEDEN
16  *  fredrik.ronquist@nrm.se
17  *
18  *  With important contributions by
19  *
20  *  Paul van der Mark (paulvdm@sc.fsu.edu)
21  *  Maxim Teslenko (maxim.teslenko@nrm.se)
22  *
23  *  and by many users (run 'acknowledgments' to see more info)
24  *
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.
29  *
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).
34  *
35  */
36
37 #include "bayes.h"
38 #include "best.h"
39 #include "command.h"
40 #include "mcmc.h"
41 #include "model.h"
42 #include "proposal.h"
43 #include "utils.h"
44
45 const char* const svnRevisionProposalC = "$Rev: 1069 $";   /* Revision keyword which is expanded/updated by svn on each commit/update */
46
47 /* debugging compiler statements */
48 #undef  DEBUG_LOCAL
49 #undef  DEBUG_UNROOTED_SLIDER
50 #undef  DEBUG_ParsSPR
51 #undef  DEBUG_ExtSS
52 #undef  DEBUG_CSLIDER
53 #undef  DEBUG_ExtSPRClock
54 #undef  DEBUG_ParsSPRClock
55 #undef  DEBUG_ExtTBR
56 #undef  DEBUG_NNIClock
57 #undef  DEBUG_SPLITMERGE
58 #undef  DEBUG_FBDPR
59
60
61 extern int *chainId;
62
63 void TouchAllTreeNodes (ModelInfo *m, int chain);
64
65
66 int Move_Aamodel (Param *param, int chain, RandLong *seed, MrBFlt *lnPriorRatio, MrBFlt *lnProposalRatio, MrBFlt *mvp)
67 {
68     /* Change amino acid model for model mixing 
69        amino acid model ID's
70         AAMODEL_POISSON         0
71         AAMODEL_JONES           1
72         AAMODEL_DAY             2
73         AAMODEL_MTREV           3
74         AAMODEL_MTMAM           4
75         AAMODEL_WAG             5
76         AAMODEL_RTREV           6 
77         AAMODEL_CPREV           7 
78         AAMODEL_VT              8
79         AAMODEL_BLOSUM          9 */
80
81     int         i, oldM, newM;
82     MrBFlt      *bs, *subValue;
83     ModelParams *mp;
84     
85     /* get model params */
86     mp = &modelParams[param->relParts[0]];
87
88     subValue = GetParamSubVals(param, chain, state[chain]);
89
90     /* get old value of model */
91     newM = oldM = (int)*GetParamVals(param, chain, state[chain]);
92     
93     /* get a new model ID */
94     do
95         {
96         newM = (int)(RandomNumber(seed) * 10);
97         } while (newM == oldM);
98
99     /* set proposal ratio */
100     *lnProposalRatio = 0.0;
101     
102     /* set prior ratio */
103     *lnPriorRatio = subValue[newM] - subValue[oldM];
104     
105     /* copy new amino acid model ID back */
106     *GetParamVals(param, chain, state[chain]) = (MrBFlt)newM;
107     
108     /* set amino acid frequencies */
109     bs = GetParamSubVals (modelSettings[param->relParts[0]].stateFreq, chain, state[chain]);
110     if (newM == AAMODEL_POISSON)
111         {
112         for (i=0; i<mp->nStates; i++)
113             bs[i] = 1.0 / 20.0;
114         }
115     else if (newM == AAMODEL_JONES)
116         {
117         for (i=0; i<mp->nStates; i++)
118             bs[i] = jonesPi[i];
119         }
120     else if (newM == AAMODEL_DAY)
121         {
122         for (i=0; i<mp->nStates; i++)
123             bs[i] = dayhoffPi[i];
124         }
125     else if (newM == AAMODEL_MTREV)
126         {
127         for (i=0; i<mp->nStates; i++)
128             bs[i] = mtrev24Pi[i];
129         }
130     else if (newM == AAMODEL_MTMAM)
131         {
132         for (i=0; i<mp->nStates; i++)
133             bs[i] = mtmamPi[i];
134         }
135     else if (newM == AAMODEL_WAG)
136         {
137         for (i=0; i<mp->nStates; i++)
138             bs[i] = wagPi[i];
139         }
140     else if (newM == AAMODEL_RTREV)
141         {
142         for (i=0; i<mp->nStates; i++)
143             bs[i] = rtrevPi[i];
144         }
145     else if (newM == AAMODEL_CPREV)
146         {
147         for (i=0; i<mp->nStates; i++)
148             bs[i] = cprevPi[i];
149         }
150     else if (newM == AAMODEL_VT)
151         {
152         for (i=0; i<mp->nStates; i++)
153             bs[i] = vtPi[i];
154         }
155     else if (newM == AAMODEL_BLOSUM)
156         {
157         for (i=0; i<mp->nStates; i++)
158             bs[i] = blosPi[i];
159         }
160
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);
165
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;
169
170     return (NO_ERROR);
171     MrBayesPrint ("%lf", *mvp); /* just because I am tired of seeing the unused parameter error msg */
172 }
173
174
175 int Move_AddDeleteCPPEvent (Param *param, int chain, RandLong *seed, MrBFlt *lnPriorRatio, MrBFlt *lnProposalRatio, MrBFlt *mvp)
176 {
177     /* add or delete one Poisson process event */
178     
179     int         i, k, addEvent, *nEvents, numEvents;
180     MrBFlt      sigma, m, lognormalLnProb, **position, **rateMultiplier, length, pos, rate;
181     TreeNode    *p, *q;
182     ModelInfo   *model;
183     Tree        *t;
184
185     /* get the model settings */
186     model = &modelSettings[param->relParts[0]];
187
188     /* get cpp rate */
189     rate = *GetParamVals (model->cppRate, chain, state[chain]);
190     
191     /* get sigma of lognormal of rate multipliers */
192     sigma = *GetParamVals (model->cppMultDev, chain, state[chain]);
193
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]];
198
199     /* get tree */
200     t = GetTree (param, chain, state[chain]);
201
202     /* pick a branch */
203     do
204         {
205         p = t->allDownPass[(int)(RandomNumber(seed) * (t->nNodes -2))];
206         } while (p->anc == NULL || (p->anc->anc == NULL));
207
208     /* get number of events for convenience */
209     numEvents = nEvents[p->index];
210
211     /* add or delete ? */
212     addEvent = NO;
213     if (numEvents == 0)
214         addEvent = YES;
215     else if (RandomNumber(seed) < 0.5)
216         addEvent = YES;
217     
218     if (addEvent == NO)
219         {
220         /* delete event */
221
222         /* choose random event */
223         k = (int) (RandomNumber(seed) * numEvents);
224         
225         /* save multiplier to be deleted */
226         m = rateMultiplier[p->index][k];
227
228         /* rearrange and reduce */
229         for (i=k; i<numEvents-1; i++)
230             {
231             position[p->index][i] = position[p->index][i+1];
232             rateMultiplier[p->index][i] = rateMultiplier[p->index][i+1];
233             }
234         if (numEvents-1 > 0)
235             {
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);
239             }
240         else
241             {
242             free (position[p->index]);
243             free (rateMultiplier[p->index]);
244             position[p->index] = rateMultiplier[p->index] = NULL;
245             }
246         /* update number of events */
247         nEvents[p->index]--;
248         }
249     else /* if (addEvent == YES) */
250         {
251         /* add event */
252
253         /* generate new multiplier */
254         m = LogNormalRandomVariable (0.0, sigma, seed);
255
256         /* generate new position */
257         pos = RandomNumber(seed);
258
259         /* find place in current array */
260         for (k=0; k<numEvents; k++)
261             {
262             if (position[p->index][k] > pos)
263                 break;
264             }
265
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--)
271             {
272             position[p->index][i] = position[p->index][i-1];
273             rateMultiplier[p->index][i] = rateMultiplier[p->index][i-1];
274             }
275         position[p->index][k] = pos;
276         rateMultiplier[p->index][k] = m;
277
278         /* update number of events */
279         nEvents[p->index]++;
280         }
281     
282     /* the CPP process is relative to expected substitutions */
283     length = p->length;
284     
285     lognormalLnProb = LnProbLogNormal(0.0, sigma, m);
286     if (addEvent == YES)
287         (*lnPriorRatio) = lognormalLnProb + log (rate); 
288     else
289         (*lnPriorRatio) = -(lognormalLnProb + log(rate));
290
291     if (addEvent == YES)
292         /* note that nEvents[p->index] now contains k+1 after addition */
293         (*lnProposalRatio) = log (length / ((double) nEvents[p->index])) - lognormalLnProb;
294     else
295         /* note that nEvents[p->index] contains k after deletion */
296         (*lnProposalRatio) = log ((double)(nEvents[p->index]+1) / length) + lognormalLnProb;
297
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);
303
304     /* update evolLengths in subtree above new event */
305     if (UpdateCppEvolLengths (param, p, chain)==ERROR)
306         {
307         abortMove=YES;
308         return (NO_ERROR);
309         }
310     
311     /* set update of cond likes down to root */
312     /* crown tree update flags set in UpdateCppEvolLengths */
313     q = p->anc;
314     while (q->anc != NULL)
315         {
316         q->upDateCl = YES;
317         q = q->anc;
318         }
319
320     return (NO_ERROR);
321     MrBayesPrint ("%lf", *mvp); /* just because I am tired of seeing the unused parameter error msg */
322 }
323
324
325 int Move_Adgamma (Param *param, int chain, RandLong *seed, MrBFlt *lnPriorRatio, MrBFlt *lnProposalRatio, MrBFlt *mvp)
326 {
327     /* Change correlation parameter (-1, 1) of adgamma model */
328
329     int         i, isValidP;
330     MrBFlt      oldP, newP, window, minP, maxP, ran, *markovTiValues;
331     ModelParams *mp;
332
333     /* get size of window, centered on current rho */
334     window = mvp[0];
335
336     /* get model params */
337     mp = &modelParams[param->relParts[0]];
338     
339     /* get minimum and maximum values for rho */
340     minP = mp->corrUni[0];
341     maxP = mp->corrUni[1];
342
343     /* get address of markovTi */
344     markovTiValues = GetParamSubVals (param, chain, state[chain]);
345
346     /* get old value of rho */
347     newP = oldP = *GetParamVals(param, chain, state[chain]);
348
349     /* change value for rho */
350     ran = RandomNumber(seed);
351      if (maxP-minP < window)
352         {
353         window = maxP-minP;
354         }
355     newP = oldP + window * (ran - 0.5);
356     
357     /* check that new value is valid */
358     isValidP = NO;
359     do
360         {
361         if (newP < minP)
362             newP = 2* minP - newP;
363         else if (newP > maxP)
364             newP = 2 * maxP - newP;
365         else
366             isValidP = YES;
367         } while (isValidP == NO);
368
369     /* get proposal ratio */
370     *lnProposalRatio = 0.0;
371     
372     /* get prior ratio */
373     *lnPriorRatio = 0.0;
374     
375     /* copy new rho value back */
376     *GetParamVals(param, chain, state[chain]) = newP;
377
378     /* fill in new Markov trans probs */
379     AutodGamma (markovTiValues, newP, mp->numGammaCats);
380         
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);
385
386     /* Update flags for divisions already set */
387
388     return (NO_ERROR);
389 }
390
391
392 int Move_Beta (Param *param, int chain, RandLong *seed, MrBFlt *lnPriorRatio, MrBFlt *lnProposalRatio, MrBFlt *mvp)
393 {
394     /* change symmetric Dirichlet variance using multiplier */
395
396     int         i, j, k, isValidB, isPriorExp, nStates;
397     MrBFlt      oldB, newB, minB, maxB, priorExp=0.0, *bs, ran, factor, tuning,
398                 x, y;
399     ModelParams *mp;
400
401     /* get tuning parameter */
402     tuning = mvp[0];    /* multiplier tuning parameter lambda */
403
404     /* get model paramaters */
405     mp = &modelParams[param->relParts[0]];
406
407     /* get prior, minimum and maximum values for rate     */
408     if (!strcmp(mp->symPiPr,"Uniform"))
409         {
410         isPriorExp = NO;
411         minB = mp->symBetaUni[0];
412         maxB = mp->symBetaUni[1];
413         }
414     else
415         {
416         isPriorExp = YES;
417         priorExp = mp->symBetaExp;
418         minB = SYMPI_MIN;
419         maxB = SYMPI_MAX;
420         }
421
422     /* get old value of symDir */
423     oldB = *GetParamVals(param, chain, state[chain]);
424
425     /* change value */
426     ran = RandomNumber(seed);
427     factor = exp(tuning * (ran - 0.5));
428     newB = oldB * factor;
429
430     /* check validity */
431     isValidB = NO;
432     do
433         {
434         if (newB < minB)
435             newB = minB * minB / newB;
436         else if (newB > maxB)
437             newB = maxB * maxB / newB;
438         else
439             isValidB = YES;
440         } while (isValidB == NO);
441
442     /* set new value of symDir */
443     *GetParamVals(param, chain, state[chain]) = newB;
444
445     /* get proposal ratio */
446     *lnProposalRatio = log (newB / oldB);
447
448     /* get prior ratio */
449     if (isPriorExp == YES)
450         {
451         *lnPriorRatio = priorExp * (oldB - newB);
452         }
453     else
454         *lnPriorRatio = 0.0;
455
456     /* fill in the new betacat frequencies */
457     bs = GetParamStdStateFreqs(param, chain, state[chain]);
458     k = mp->numBetaCats;
459     BetaBreaks (newB, newB, bs, k);
460     k *= 2;
461     for (i=k-2; i>0; i-=2)
462         {
463         bs[i] = bs[i/2];
464         }
465     for (i=1; i<k; i+=2)
466         {
467         bs[i] = 1.0 - bs[i-1];
468         }
469         
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++)
473         {
474         /* get number of states */
475         nStates = param->sympinStates[i];
476
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++)
481             {
482             x += (newB-1.0)*log(bs[j]);
483             y += (oldB-1.0)*log(bs[j]);
484             }
485         (*lnPriorRatio) += x - y;
486
487         /* update pointer to state freqs */
488         bs += nStates;
489         }
490         
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);
496         
497     /* may need to hit update flag for cijks if we have multistate characters */
498     for (i=0; i<param->nRelParts; i++)
499         {
500         if (modelSettings[param->relParts[i]].nCijkParts > 0)
501             modelSettings[param->relParts[i]].upDateCijk = YES;
502         }
503
504     return (NO_ERROR);
505 }
506
507
508 int Move_BrLen (Param *param, int chain, RandLong *seed, MrBFlt *lnPriorRatio, MrBFlt *lnProposalRatio, MrBFlt *mvp)
509 {
510     /* change one branch length */
511
512     MrBFlt      tuning, maxV, minV, m, newM, brlensPrExp=0.0;
513     TreeNode    *p;
514     ModelParams *mp;
515     Tree        *t;
516     int isVPriorExp;
517     
518     tuning = mvp[0]; /* Larget & Simon's tuning parameter lambda */
519
520     mp = &modelParams[param->relParts[0]];
521
522     /* max and min brlen */
523     if (param->paramId == BRLENS_UNI)
524         {
525         minV = mp->brlensUni[0];
526         maxV = mp->brlensUni[1];
527         isVPriorExp = NO;
528         }
529     else if (param->paramId == BRLENS_GamDir)
530         {
531         minV = BRLENS_MIN;
532         maxV = BRLENS_MAX;
533         isVPriorExp = 2;
534         }
535     else if (param->paramId == BRLENS_iGmDir)
536         {
537         minV = BRLENS_MIN;
538         maxV = BRLENS_MAX;
539         isVPriorExp = 3;
540         }
541     else if (param->paramId == BRLENS_twoExp)
542         {
543         minV = BRLENS_MIN;
544         maxV = BRLENS_MAX;
545         isVPriorExp = 4;
546         }
547     else
548         {
549         minV = BRLENS_MIN;
550         maxV = BRLENS_MAX;
551         brlensPrExp = mp->brlensExp;
552         isVPriorExp = YES;  
553         }
554
555     /* get tree */
556     t = GetTree (param, chain, state[chain]);
557
558     /* Dirichlet or twoExp prior */
559     if (isVPriorExp > 1)
560         (*lnPriorRatio) = -LogDirPrior(t, mp, isVPriorExp);
561
562     /* pick a branch */
563     do  {
564         p = t->allDownPass[(int)(RandomNumber(seed) * t->nNodes)];
565         }
566     while (p->anc == NULL || (t->isRooted == YES && p->anc->anc == NULL));
567
568     /* determine new length */
569     m = p->length;
570     newM = m * exp(tuning * (RandomNumber(seed) - 0.5));
571
572     /* reflect new length if necessary */
573     while (newM < minV || newM > maxV)
574         {
575         if (newM < minV)
576             newM = minV * minV / newM;
577         else if (newM > maxV)
578             newM = maxV * maxV / newM;
579         }
580     p->length = newM;
581
582     /* calculate proposal ratio */
583     /* must be based on new length after reflection */
584     (*lnProposalRatio) = log(newM / m);
585
586     /* set flags for update of transition probabilities at p */
587     p->upDateTi = YES;
588
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)  
592         p->upDateCl = YES;
593
594     /* set flags for update of cond likes from p->anc and down to root */
595     while (p->anc->anc != NULL)
596         {
597         p = p->anc;
598         p->upDateCl = YES; 
599         }
600
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);
607
608     return (NO_ERROR);
609 }
610
611
612 int Move_ClockRate_M (Param *param, int chain, RandLong *seed, MrBFlt *lnPriorRatio, MrBFlt *lnProposalRatio, MrBFlt *mvp)
613 {
614     /* change clock rate using multiplier */
615     
616     int             i, j, k, *nEvents;
617     MrBFlt          oldRate, newRate, factor, lambda, nu, igrvar, *brlens, *igrRate, *tk02Rate,
618                     N, newTheta, oldTheta, growth, newLnPrior, oldLnPrior;
619     Tree            *t, *oldT;
620     TreeNode        *p, *q;
621     Param           *treeParam, *subParm;
622     ModelParams     *mp;
623     ModelInfo       *m;
624     
625     /* get old value of clock rate */
626     oldRate = *GetParamVals(param, chain, state[chain]);
627
628     /* Rely on general algorithm to change the value */
629     Move_PosRealMultiplier(param, chain, seed, lnPriorRatio, lnProposalRatio, mvp);
630     if (abortMove == YES)
631         return NO_ERROR;
632
633     /* get new value of clock rate */
634     newRate = *GetParamVals(param, chain, state[chain]);
635
636     /* calculate factor */
637     factor = newRate / oldRate;
638
639     /* clock rate applies to all clock trees */
640     for (i = 0; i < numTrees; i++)
641         {
642         t = GetTreeFromIndex(i, chain, state[chain]);
643         if (t->isClock == NO)
644             continue;
645         if (!strcmp(modelParams[t->relParts[0]].clockPr, "Fixed"))
646             continue;
647
648         oldT = GetTreeFromIndex(i, chain, 1^state[chain]);
649         treeParam = modelSettings[t->relParts[0]].brlens;
650         
651         /* adjust the node depths and lengths */
652         for (j = 0; j < t->nNodes-1; j++)
653             {
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 */
662                 abortMove = YES;
663                 return (NO_ERROR);
664                 }
665             }
666
667         /* prior ratio for coalecent tree, as theta is changed */
668         mp = &modelParams[t->relParts[0]];
669         if (!strcmp(mp->clockPr,"Coalescence"))
670             {
671             m = &modelSettings[t->relParts[0]];
672             N = *GetParamVals(m->popSize, chain, state[chain]);
673             if (!strcmp(mp->ploidy, "Diploid"))
674                 N *= 4.0;
675             else if (!strcmp(mp->ploidy, "Zlinked"))
676                 N *= 3.0;
677             else
678                 N *= 2.0;
679             oldTheta = N * oldRate;
680             newTheta = N * newRate;
681             if (!strcmp(mp->growthPr, "Fixed"))
682                 growth = mp->growthFix;
683             else
684                 growth = *GetParamVals(m->growthRate, chain, state[chain]);
685
686             if (LnCoalescencePriorPr (oldT, &oldLnPrior, oldTheta, growth) == ERROR)
687                 {
688                 MrBayesPrint ("%s   Problem calculating prior for coalescent process\n", spacer);
689                 return (ERROR);
690                 }
691             if (LnCoalescencePriorPr (t, &newLnPrior, newTheta, growth) == ERROR)
692                 {
693                 MrBayesPrint ("%s   Problem calculating prior for coalescent process\n", spacer);
694                 return (ERROR);
695                 }
696             (*lnPriorRatio) += newLnPrior - oldLnPrior;
697             }
698             
699         /* adjust proposal and prior ratio for relaxed clock models */
700         for (k = 0; k < treeParam->nSubParams; k++)
701             {
702             subParm = treeParam->subParams[k];
703             if (subParm->paramType == P_CPPEVENTS)
704                 {
705                 nEvents = subParm->nEvents[2*chain+state[chain]];
706                 lambda = *GetParamVals (modelSettings[subParm->relParts[0]].cppRate, chain, state[chain]);
707                 /* proposal ratio */
708                 for (j=0; j<t->nNodes-2; j++)
709                     {
710                     p = t->allDownPass[j];
711                     q = oldT->allDownPass[j];
712                     (*lnProposalRatio) += nEvents[p->index ] * log (p->length  / q->length);
713                     }
714                 /* prior ratio */
715                 (*lnPriorRatio) += lambda * (TreeLen(oldT) - TreeLen(t));
716                 /* update effective evolutionary lengths */
717                 if (UpdateCppEvolLengths (subParm, t->root->left, chain) == ERROR)
718                     {
719                     abortMove = YES;
720                     return (NO_ERROR);
721                     }
722                 }
723             else if ( subParm->paramType == P_TK02BRANCHRATES ||
724                      (subParm->paramType == P_MIXEDBRCHRATES && *GetParamIntVals(subParm, chain, state[chain]) == RCL_TK02))
725                 {
726                 if (subParm->paramType == P_TK02BRANCHRATES)
727                     nu = *GetParamVals (modelSettings[subParm->relParts[0]].tk02var, chain, state[chain]);
728                 else
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]);
732
733                 /* no proposal ratio effect */
734
735                 /* prior ratio and update of brlens */
736                 for (j = 0; j < t->nNodes-2; j++)
737                     {
738                     p = t->allDownPass[j];
739                     q = oldT->allDownPass[j];
740                     if (p->length > 0.0)  // not ancestral fossil
741                         {
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]);
744                         
745                         brlens[p->index] = p->length * (tk02Rate[p->anc->index]+tk02Rate[p->index])/2.0;
746                         }
747                     }
748                 }
749             else if ( subParm->paramType == P_IGRBRANCHRATES ||
750                      (subParm->paramType == P_MIXEDBRCHRATES && *GetParamIntVals(subParm, chain, state[chain]) == RCL_IGR))
751                 {
752                 if (subParm->paramType == P_IGRBRANCHRATES)
753                     igrvar = *GetParamVals (modelSettings[subParm->relParts[0]].igrvar, chain, state[chain]);
754                 else
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]);
758             
759                 /* prior ratio and update of brlens */
760                 for (j = 0; j < t->nNodes-2; j++)
761                     {
762                     p = t->allDownPass[j];
763                     q = oldT->allDownPass[j];
764                     if (p->length > 0.0)  // not ancestral fossil
765                         {
766                         (*lnPriorRatio) -= LnProbGamma (q->length/igrvar, q->length/igrvar, igrRate[q->index]);
767                         (*lnPriorRatio) += LnProbGamma (p->length/igrvar, p->length/igrvar, igrRate[p->index]);
768
769                         brlens[p->index] = igrRate[p->index] * p->length;
770                         }
771                     }
772                 }
773             }
774         }
775  
776     return (NO_ERROR);
777 }
778
779
780 int Move_CPPEventPosition (Param *param, int chain, RandLong *seed, MrBFlt *lnPriorRatio, MrBFlt *lnProposalRatio, MrBFlt *mvp)
781 {
782     /* move the position of one CPP event */
783
784     int         i, j, k, *nEvents;
785     MrBFlt      pos, temp, **position, **rateMultiplier;
786     TreeNode    *p=NULL, *q;
787     Tree        *t;
788
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]];
793
794     /* get tree */
795     t = GetTree (param, chain, state[chain]);
796
797     /* pick a branch and an event */
798     for (i=j=0; i<t->nNodes - 2; i++)
799         {
800         p = t->allDownPass[i];
801         j += nEvents[p->index];
802         }       
803     if (j == 0)
804         {
805         abortMove = YES;
806         return (NO_ERROR);
807         }
808     k = (int) (RandomNumber(seed) * j);
809     for (i=j=0; i<t->nNodes - 2; i++)
810         {
811         p = t->allDownPass[i];
812         j += nEvents[p->index];
813         if (j > k)
814             break;
815         }       
816     if (position[p->index] == NULL)
817         getchar();
818
819     /* find local index */
820     k = k - (j - nEvents[p->index]);
821
822     /* find new position */
823     pos = RandomNumber(seed);
824     if (pos < POS_MIN || 1.0 - pos < POS_MIN)
825         {
826         abortMove = YES;
827         return (NO_ERROR);
828         }
829     position[p->index][k] = pos;
830
831     /* sort events; bubble sort for now */
832     for (i=0; i<nEvents[p->index]; i++)
833         {
834         for (j=i+1; j<nEvents[p->index]; j++)
835             {
836             if (position[p->index][j] < position[p->index][i])
837                 {
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;
844                 }
845             }
846         }
847
848     /* calculate prior and proposal ratio */
849     (*lnPriorRatio) = (*lnProposalRatio) = 0.0;
850
851     /* update branch evolution lengths */
852     if (UpdateCppEvolLengths (param, p, chain) == ERROR)
853         {
854         abortMove = YES;
855         return (NO_ERROR);
856         }
857
858     /* set update of cond likes down to root */
859     /* update of crowntree set in UpdateCppEvolLengths */
860     q = p->anc;
861     while (q->anc != NULL)
862         {
863         q->upDateCl = YES;
864         q = q->anc;
865         }
866
867     return (NO_ERROR);
868     MrBayesPrint ("%lf", *mvp); /* just because I am tired of seeing the unused parameter error msg */
869 }
870
871
872 int Move_CPPRate (Param *param, int chain, RandLong *seed, MrBFlt *lnPriorRatio, MrBFlt *lnProposalRatio, MrBFlt *mvp)
873 {
874     /* move the CPP rate (lambda) using multiplier */
875
876     int         i, j, *nEvents, sumEvents;
877     MrBFlt      oldLambda, newLambda, treeLength, tuning;
878     Model       *mp;
879     TreeNode    *p;
880     Tree        *t;
881
882     /* get tuning parameter */
883     tuning = mvp[0];
884
885     /* get model params */
886     mp = &modelParams[param->relParts[0]];
887
888     /* get the CPP rate */
889     oldLambda = *GetParamVals (param, chain, state[chain]);
890
891     /* set new value */
892     newLambda = oldLambda * exp ((0.5 - RandomNumber(seed))*tuning);
893     
894     /* reflect if necessary */
895     while (newLambda < CPPLAMBDA_MIN || newLambda > CPPLAMBDA_MAX)
896         {
897         if (newLambda < CPPLAMBDA_MIN)
898             newLambda = CPPLAMBDA_MIN * CPPLAMBDA_MIN / newLambda;
899         if (newLambda > CPPLAMBDA_MAX)
900             newLambda = CPPLAMBDA_MAX * CPPLAMBDA_MAX / newLambda;
901         }
902     
903     /* store new value */
904     (*GetParamVals (param, chain, state[chain])) = newLambda;
905
906     /* calculate prior ratio */
907     (*lnPriorRatio) = 0.0;
908     for (i=0; i<param->nSubParams; i++)
909         {
910         nEvents = param->subParams[i]->nEvents[2*chain+state[chain]];
911         sumEvents = 0;
912         t = GetTree (param->subParams[i], chain, state[chain]); 
913         treeLength = 0.0;
914         for (j=0; j<t->nNodes-2; j++)
915             {
916             p = t->allDownPass[j];
917             sumEvents += nEvents[p->index];
918             treeLength += p->length;
919             }
920         (*lnPriorRatio) += (oldLambda - newLambda) * treeLength;
921         (*lnPriorRatio) += sumEvents * log (newLambda / oldLambda);
922         }
923
924     /* adjust for prior on cppRate */
925     if (!strcmp(mp->cppRatePr,"Exponential"))
926         (*lnPriorRatio) +=  mp->cppRateExp * (oldLambda - newLambda);
927
928     /* calculate proposal ratio */
929     (*lnProposalRatio) = log (newLambda / oldLambda);
930
931     /* we do not need to update likelihoods */
932     for (i=0; i<param->nRelParts; i++)
933         {
934         modelSettings[param->relParts[i]].upDateCl = NO;
935         }
936
937     return (NO_ERROR);
938 }
939
940
941 int Move_CPPRateMultiplier_M (Param *param, int chain, RandLong *seed, MrBFlt *lnPriorRatio, MrBFlt *lnProposalRatio, MrBFlt *mvp)
942 {
943     /* move one CPP rate multiplier using multiplier */
944
945     int         i, j, k, *nEvents;
946     MrBFlt      newRateMultiplier, oldRateMultiplier, tuning, minM, maxM, sigma, **rateMultiplier;
947     TreeNode    *p = NULL;
948     ModelInfo   *m;
949     Tree        *t;
950     TreeNode    *q;
951
952     /* get the tuning parameter */
953     tuning = mvp[0];
954     
955     /* get the model settings */
956     m = &modelSettings[param->relParts[0]];
957
958     /* get tree */
959     t = GetTree (param, chain, state[chain]);
960
961     /* get CPP event data */
962     nEvents = param->nEvents[2*chain+state[chain]];
963     rateMultiplier = param->rateMult[2*chain+state[chain]];
964
965     /* get minimum and maximum of CPP rate multiplier */
966     minM = param->min;
967     maxM = param->max;
968     
969     /* pick a branch and a rateMultiplier */
970     for (i=j=0; i<t->nNodes - 2; i++)
971         {
972         p = t->allDownPass[i];
973         j += nEvents[p->index];
974         }       
975     if (j == 0)
976         {
977         abortMove = YES;
978         return (NO_ERROR);
979         }
980     k = (int) (RandomNumber(seed) * j);
981     for (i=j=0; i<t->nNodes - 2; i++)
982         {
983         p = t->allDownPass[i];
984         j += nEvents[p->index];
985         if (j > k)
986             break;
987         }
988
989     /* find local index */
990     k = nEvents[p->index] - (j - k);
991
992     /* find new rateMultiplier */
993     oldRateMultiplier = rateMultiplier[p->index][k];
994     newRateMultiplier = oldRateMultiplier * (exp (0.5 - RandomNumber(seed) * tuning));
995
996     /* reflect if necessary */
997     while (newRateMultiplier < minM || newRateMultiplier > maxM)
998         {
999         if (newRateMultiplier < minM)
1000             newRateMultiplier = minM * minM / newRateMultiplier;
1001         if (newRateMultiplier > maxM)
1002             newRateMultiplier = maxM * maxM / newRateMultiplier;
1003         }
1004
1005     rateMultiplier[p->index][k] = newRateMultiplier;
1006     
1007     /* calculate prior ratio */
1008     sigma = *GetParamVals (m->cppMultDev, chain, state[chain]);
1009     (*lnPriorRatio) = LnRatioLogNormal (0.0, sigma, newRateMultiplier, oldRateMultiplier);
1010
1011     /* calculate proposal ratio */
1012     (*lnProposalRatio) = log (newRateMultiplier / oldRateMultiplier);
1013
1014     /* update branch evolution lengths */
1015     if (UpdateCppEvolLengths (param, p, chain)==ERROR)
1016         {
1017         abortMove = YES;
1018         return (NO_ERROR);
1019         }
1020
1021     /* set update of cond likes down to root */
1022     /* update of crowntree set in UpdateCppEvolLengths */
1023     q = p->anc;
1024     while (q->anc != NULL)
1025         {
1026         q->upDateCl = YES;
1027         q = q->anc;
1028         }
1029
1030     return (NO_ERROR);
1031 }
1032
1033
1034 int Move_CPPRateMultiplierRnd (Param *param, int chain, RandLong *seed, MrBFlt *lnPriorRatio, MrBFlt *lnProposalRatio, MrBFlt *mvp)
1035 {
1036     /* move one CPP rate multiplier by redrawing from prior */
1037
1038     int         i, j, k, *nEvents;
1039     MrBFlt      sigma, newRateMultiplier, oldRateMultiplier, **rateMultiplier;
1040     TreeNode    *p=NULL, *q;
1041     ModelInfo   *m;
1042     Tree        *t;
1043
1044     /* get the model settings */
1045     m = &modelSettings[param->relParts[0]];
1046
1047     /* get the CPP event data */
1048     nEvents = param->nEvents[2*chain+state[chain]];
1049     rateMultiplier = param->rateMult[2*chain+state[chain]];
1050
1051     /* get tree */
1052     t = GetTree (param, chain, state[chain]);
1053
1054     /* pick a branch and a rateMultiplier */
1055     for (i=j=0; i<t->nNodes - 2; i++)
1056         {
1057         p = t->allDownPass[i];
1058         j += nEvents[p->index];
1059         }       
1060     if (j == 0)
1061         {
1062         abortMove = YES;
1063         return (NO_ERROR);
1064         }
1065     k = (int) (RandomNumber(seed) * j);
1066     for (i=j=0; i<t->nNodes - 2; i++)
1067         {
1068         p = t->allDownPass[i];
1069         j += nEvents[p->index];
1070         if (j > k)
1071             break;
1072         }
1073
1074     /* find local index */
1075     k = nEvents[p->index] - (j - k);
1076
1077     /* record old rate multiplier */
1078     oldRateMultiplier = rateMultiplier[p->index][k];
1079
1080     /* find stdev of lognormal */
1081     sigma = *GetParamVals (m->cppMultDev, chain, state[chain]);
1082
1083     /* set new value */
1084     do {
1085         newRateMultiplier = LogNormalRandomVariable (0.0, sigma, seed);
1086         } while (newRateMultiplier < param->min || newRateMultiplier > param->max);
1087     rateMultiplier[p->index][k] = newRateMultiplier;
1088
1089     /* calculate prior ratio */
1090     (*lnPriorRatio) = LnRatioLogNormal(0.0, sigma, newRateMultiplier, oldRateMultiplier);
1091         
1092     /* calculate proposal ratio */
1093     (*lnProposalRatio) += LnRatioLogNormal (0.0, sigma, oldRateMultiplier, newRateMultiplier);
1094
1095     /* update branch evolution lengths */
1096     if (UpdateCppEvolLengths (param, p, chain) == ERROR)
1097         {
1098         abortMove = YES;
1099         return (NO_ERROR);
1100         }
1101
1102     /* set update of cond likes down to root */
1103     /* update of crowntree set in UpdateCppEvolLengths */
1104     q = p->anc;
1105     while (q->anc != NULL)
1106         {
1107         q->upDateCl = YES;
1108         q = q->anc;
1109         }
1110
1111     return (NO_ERROR);
1112     MrBayesPrint ("%lf", *mvp); /* just because I am tired of seeing the unused parameter error msg */
1113 }
1114
1115
1116 int Move_AddBranch (Param *param, int chain, RandLong *seed, MrBFlt *lnPriorRatio, MrBFlt *lnProposalRatio, MrBFlt *mvp)
1117 {
1118     /* Move an ancestral fossil (brl = 0) to fossil tip (brl > 0)
1119
1120        __|__              __|__
1121       |     |            |     |
1122             |       -->       q|___
1123             |       -->        |   |
1124            q|___p              |   |p
1125            r|                 r|
1126      
1127        1. Pich a fossil among those with brl = 0 (prob = 1/k)
1128        2. Propose brl from a uniform(0, ?) distribution
1129      */
1130     
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;
1135     Tree        *t;
1136     ModelParams *mp;
1137     ModelInfo   *m;
1138     Param       *subParm;
1139     Calibration *calibrationPtr = NULL;
1140     
1141     (*lnProposalRatio) = (*lnPriorRatio) = 0.0;
1142
1143     /* get tree */
1144     t = GetTree (param, chain, state[chain]);
1145     
1146     /* get number of ancestral and tip fossils */
1147     kFossil = mFossil = 0;
1148     for (i = 0; i < t->nNodes -1; i++)
1149         {
1150         p = t->allDownPass[i];
1151         p->marked = NO;  // reset marked node
1152         if (p->left == NULL && p->right == NULL && p->nodeDepth > 0.0)
1153             {
1154             if (p->length > 0.0)
1155                 {
1156                 mFossil++;        // count tip fossil
1157                 }
1158             else
1159                 {
1160                 p->marked = YES;  // mark  anc fossil
1161                 kFossil++;        // count anc fossil
1162                 }
1163             }
1164         }
1165     if (kFossil == 0)  // no ancestral fossil, nothing to do
1166         {
1167         abortMove = YES;
1168         return (NO_ERROR);
1169         }
1170
1171     /* get model params and model info */
1172     mp = &modelParams[param->relParts[0]];
1173     m = &modelSettings[param->relParts[0]];
1174     
1175     /* get clock rate */
1176     clockRate = *(GetParamVals(m->clockRate, chain, state[chain]));
1177     
1178     /* pick an ancestral fossil randomly */
1179     j = (int) (RandomNumber(seed) * kFossil);
1180     for (i = k = 0; i < t->nNodes -1; i++)
1181         {
1182         p = t->allDownPass[i];
1183         if (p->marked == YES)
1184             k++;
1185         if (k > j)
1186             break;
1187         }
1188     /* now p is pointing to the ancestral fossil
1189        whose brl needs to be changed to >0. let's do it! */
1190     q = p->anc;
1191     if (q->left == p)
1192         r = q->right;
1193     else
1194         r = q->left;
1195
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;
1200     else
1201         maxDepth = q->anc->nodeDepth - BRLENS_MIN;
1202     
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;
1207     
1208     if (calibrationPtr != NULL)
1209         {
1210         if (calibrationPtr->prior == fixed || calibrationPtr->min * clockRate > minDepth)
1211             {
1212             abortMove = YES;
1213             return (NO_ERROR);
1214             }
1215         if (calibrationPtr->max * clockRate < maxDepth)
1216             maxDepth = calibrationPtr->max * clockRate;
1217         }
1218     if (minDepth >= maxDepth)
1219         {
1220         abortMove = YES;
1221         return (NO_ERROR);
1222         }
1223     
1224     /* record old lengths and depths */
1225     oldQLength = q->length;
1226     oldRLength = r->length;
1227     // oldDepth = q->nodeDepth;
1228     
1229     /* propose the branch length leading to the fossil */
1230     newLength = (RandomNumber(seed)) * (maxDepth - minDepth);
1231     
1232     /* adjust brls and depths, set flags for update of trans probs */
1233     p->length   = newLength;
1234     p->upDateTi = YES;
1235     q->nodeDepth += newLength;
1236     if (q->anc->anc != NULL)
1237         {
1238         q->length  -= newLength;
1239         q->upDateTi = YES;
1240         }
1241     r->length += newLength;
1242     r->upDateTi = YES;
1243     // newDepth = q->nodeDepth;
1244
1245     /* adjust age of q if dated */
1246     if (calibrationPtr != NULL)
1247         {
1248         q->age = q->nodeDepth / clockRate;
1249         }
1250     
1251     /* set flags for update of cond likes from p/r to root */
1252     r->upDateCl = YES;
1253     q = p;
1254     while (q->anc != NULL)
1255         {
1256         q->upDateCl = YES;
1257         q = q->anc;
1258         }
1259     q = p->anc;
1260
1261     /* calculate prior ratio */
1262     if (LogClockTreePriorRatio(param, chain, &x) == ERROR)
1263         return (ERROR);
1264     (*lnPriorRatio) += x;
1265     
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);
1272     
1273     /* add the Jacobian term */
1274     (*lnProposalRatio) += log((maxDepth - minDepth) / clockRate);
1275             
1276     /* adjust proposal and prior ratio for relaxed clock models */
1277     for (i=0; i<param->nSubParams; i++)
1278         {
1279         subParm = param->subParams[i];
1280         if (subParm->paramType == P_CPPEVENTS)
1281             {
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);
1284             return (ERROR);
1285             }
1286         else if ( subParm->paramType == P_TK02BRANCHRATES ||
1287                  (subParm->paramType == P_MIXEDBRCHRATES && *GetParamIntVals(subParm, chain, state[chain]) == RCL_TK02))
1288             {
1289             if (subParm->paramType == P_TK02BRANCHRATES)
1290                 nu = *GetParamVals (modelSettings[subParm->relParts[0]].tk02var, chain, state[chain]);
1291             else
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]);
1295             
1296             /* prior ratio */
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)
1302                 {
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]);
1305                 }
1306             
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)
1311                 {
1312                 brlens[q->index] = q->length * (tk02Rate[q->index]+tk02Rate[q->anc->index])/2.0;
1313                 }
1314             }
1315         else if ( subParm->paramType == P_IGRBRANCHRATES ||
1316                  (subParm->paramType == P_MIXEDBRCHRATES && *GetParamIntVals(subParm, chain, state[chain]) == RCL_IGR))
1317             {
1318             if (subParm->paramType == P_IGRBRANCHRATES)
1319                 igrvar = *GetParamVals (modelSettings[subParm->relParts[0]].igrvar, chain, state[chain]);
1320             else
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]);
1324             
1325             /* prior ratio */
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)
1331                 {
1332                 (*lnPriorRatio) -= LnProbGamma (oldQLength/igrvar, oldQLength/igrvar, igrRate[q->index]);
1333                 (*lnPriorRatio) += LnProbGamma (q->length /igrvar, q->length /igrvar, igrRate[q->index]);
1334                 }
1335             
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)
1340                 {
1341                 brlens[q->index] = igrRate[q->index] * q->length;
1342                 }
1343             }
1344         }
1345     
1346     return (NO_ERROR);
1347     MrBayesPrint ("%lf", *mvp); /* just because I am tired of seeing the unused parameter error msg */
1348 }
1349
1350
1351 int Move_DelBranch (Param *param, int chain, RandLong *seed, MrBFlt *lnPriorRatio, MrBFlt *lnProposalRatio, MrBFlt *mvp)
1352 {
1353     /* Move a fossil tip (brl > 0) to be ancestral (brl =0)
1354
1355        __|__              __|__
1356       |     |            |     |
1357            q|___     -->       |
1358             |   |    -->       |
1359             |   |p            q|___p
1360            r|                 r|
1361          
1362        1. Pich a fossil among those with brl > 0 (prob = 1/m)
1363        2. Set brl = 0
1364      */
1365     
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;
1370     Tree        *t;
1371     ModelParams *mp;
1372     ModelInfo   *m;
1373     Param       *subParm;
1374     Calibration *calibrationPtr = NULL;
1375
1376     (*lnProposalRatio) = (*lnPriorRatio) = 0.0;
1377
1378     /* get tree */
1379     t = GetTree (param, chain, state[chain]);
1380     
1381     /* get number of ancestral and tip fossils */
1382     kFossil = mFossil = 0;
1383     for (i = 0; i < t->nNodes -1; i++)
1384         {
1385         p = t->allDownPass[i];
1386         p->marked = NO;  // reset marked node
1387         if (p->left == NULL && p->right == NULL && p->nodeDepth > 0.0)
1388             {
1389             if (p->length > 0.0)
1390                 {
1391                 p->marked = YES;  // mark  tip fossil
1392                 mFossil++;        // count tip fossil
1393                 }
1394             else
1395                 {
1396                 kFossil++;        // count anc fossil
1397                 }
1398             }
1399         }
1400     if (mFossil == 0)  // no tip fossil, nothing to do
1401         {
1402         abortMove = YES;
1403         return (NO_ERROR);
1404         }
1405     
1406     /* get model params and model info */
1407     mp = &modelParams[param->relParts[0]];
1408     m = &modelSettings[param->relParts[0]];
1409     
1410     /* get clock rate */
1411     clockRate = *(GetParamVals(m->clockRate, chain, state[chain]));
1412
1413     /* pick a tip fossil randomly */
1414     j = (int) (RandomNumber(seed) * mFossil);
1415     for (i = k = 0; i < t->nNodes -1; i++)
1416         {
1417         p = t->allDownPass[i];
1418         if (p->marked == YES)
1419             k++;
1420         if (k > j)
1421             break;
1422         }
1423     /* now p is pointing to the fossil tip
1424        whose brl needs to be changed to 0. let's do it */
1425     q = p->anc;
1426     if (q->left == p)
1427         r = q->right;
1428     else
1429         r = q->left;
1430
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;
1435     else
1436         maxDepth = q->anc->nodeDepth - BRLENS_MIN;
1437     
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;
1442     
1443     if (calibrationPtr != NULL)
1444         {
1445         if (calibrationPtr->prior == fixed || calibrationPtr->min * clockRate > minDepth)
1446             {
1447             abortMove = YES;
1448             return (NO_ERROR);
1449             }
1450         if (calibrationPtr->max * clockRate < maxDepth)
1451             maxDepth = calibrationPtr->max * clockRate;
1452         }
1453     if (r->nodeDepth > p->nodeDepth -BRLENS_MIN || minDepth >= maxDepth)
1454         {  /* the sister node (another fossil) is older than the current fossil */
1455         abortMove = YES;
1456         return (NO_ERROR);
1457         }
1458
1459     /* record old lengths and depths */
1460     oldPLength = p->length;
1461     oldQLength = q->length;
1462     oldRLength = r->length;
1463     // oldDepth = q->nodeDepth;
1464
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)
1469         {
1470         q->length += p->length;
1471         q->upDateTi = YES;
1472         }
1473     r->length  -= p->length;
1474     r->upDateTi = YES;
1475     p->length   = 0.0;
1476     p->upDateTi = YES;
1477     // newDepth = q->nodeDepth;
1478     
1479     /* adjust age of q if dated */
1480     if (calibrationPtr != NULL)
1481         {
1482         q->age = q->nodeDepth / clockRate;
1483         }
1484     
1485     /* set flags for update of cond likes from p/r to root */
1486     r->upDateCl = YES;
1487     q = p;
1488     while (q->anc != NULL)
1489         {
1490         q->upDateCl = YES;
1491         q = q->anc;
1492         }
1493     q = p->anc;
1494
1495     /* calculate prior ratio */
1496     if (LogClockTreePriorRatio(param, chain, &x) == ERROR)
1497         return (ERROR);
1498     (*lnPriorRatio) += x;
1499     
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);
1506
1507     /* add the Jacobian term */
1508     (*lnProposalRatio) -= log((maxDepth - minDepth) / clockRate);
1509
1510     /* adjust proposal and prior ratio for relaxed clock models */
1511     for (i=0; i<param->nSubParams; i++)
1512         {
1513         subParm = param->subParams[i];
1514         if (subParm->paramType == P_CPPEVENTS)
1515             {
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);
1518             return (ERROR);
1519             }
1520         else if ( subParm->paramType == P_TK02BRANCHRATES ||
1521                  (subParm->paramType == P_MIXEDBRCHRATES && *GetParamIntVals(subParm, chain, state[chain]) == RCL_TK02))
1522            {
1523             if (subParm->paramType == P_TK02BRANCHRATES)
1524                 nu = *GetParamVals (modelSettings[subParm->relParts[0]].tk02var, chain, state[chain]);
1525             else
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]);
1529             
1530             /* prior ratio */
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)
1535                 {
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]);
1538                 }
1539             
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)
1544                 {
1545                 brlens[q->index] = q->length * (tk02Rate[q->index]+tk02Rate[q->anc->index])/2.0;
1546                 }
1547             }
1548         else if ( subParm->paramType == P_IGRBRANCHRATES ||
1549                  (subParm->paramType == P_MIXEDBRCHRATES && *GetParamIntVals(subParm, chain, state[chain]) == RCL_IGR))
1550             {
1551             if (subParm->paramType == P_IGRBRANCHRATES)
1552                 igrvar = *GetParamVals (modelSettings[subParm->relParts[0]].igrvar, chain, state[chain]);
1553             else
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]);
1557             
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)
1562                 {
1563                 (*lnPriorRatio) -= LnProbGamma (oldQLength/igrvar, oldQLength/igrvar, igrRate[q->index]);
1564                 (*lnPriorRatio) += LnProbGamma (q->length /igrvar, q->length /igrvar, igrRate[q->index]);
1565                 }
1566             
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)
1571                 {
1572                 brlens[q->index] = igrRate[q->index] * q->length;
1573                 }
1574             }
1575         }
1576
1577     return (NO_ERROR);
1578     MrBayesPrint ("%lf", *mvp); /* just because I am tired of seeing the unused parameter error msg */
1579 }
1580
1581
1582 int Move_Extinction (Param *param, int chain, RandLong *seed, MrBFlt *lnPriorRatio, MrBFlt *lnProposalRatio, MrBFlt *mvp)
1583 {
1584     /* change relative extinction rate using sliding window */
1585     
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;
1589     char        *sS;
1590     ModelParams *mp;
1591     ModelInfo   *m;
1592     Tree        *t;
1593
1594     /* get size of window, centered on current value */
1595     window = mvp[0];
1596
1597     /* get model params and settings */
1598     mp = &modelParams[param->relParts[0]];
1599     m = &modelSettings[param->relParts[0]];
1600     
1601     /* get minimum and maximum values */
1602     minM = 0.0;
1603     maxM = 0.99999;
1604
1605     /* get pointer to value to be changed */
1606     valIndex = (int)(RandomNumber(seed) * param->nValues);
1607     valPtr = GetParamVals(param, chain, state[chain]) + valIndex;
1608     
1609     /* get old value */
1610     oldM = *valPtr;
1611
1612     /* change value */
1613     if (window > maxM-minM)
1614         window = maxM-minM;
1615     newM = oldM + window * (RandomNumber(seed) - 0.5);
1616     
1617     /* check that new value is valid */
1618     isValidM = NO;
1619     do  {
1620         if (newM < minM)
1621             newM = 2 * minM - newM;
1622         else if (newM > maxM)
1623             newM = 2 * maxM - newM;
1624         else
1625             isValidM = YES;
1626         } while (isValidM == NO);
1627
1628     /* get proposal ratio */
1629     *lnProposalRatio = 0.0;
1630     
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]);
1638     
1639     if (!strcmp(mp->clockPr,"Birthdeath"))
1640         {
1641         if (LnBirthDeathPriorPr (t, clockRate, &oldLnPrior, *sR, *eR, sS, sF) == ERROR)
1642             {
1643             MrBayesPrint ("%s   Problem calculating prior for birth-death process\n", spacer);
1644             return (ERROR);
1645             }
1646         *valPtr = newM;  // update with new value
1647         if (LnBirthDeathPriorPr (t, clockRate, &newLnPrior, *sR, *eR, sS, sF) == ERROR)
1648             {
1649             MrBayesPrint ("%s   Problem calculating prior for birth-death process\n", spacer);
1650             return (ERROR);
1651             }
1652         }
1653     else if (!strcmp(mp->clockPr,"Fossilization"))
1654         {
1655         fR = GetParamVals (m->fossilizationRates, chain, state[chain]);
1656         if (LnFossilizationPriorPr (t, clockRate, &oldLnPrior, sR, eR, sF, fR, sS) == ERROR)
1657             {
1658             MrBayesPrint ("%s   Problem calculating prior for fossilized birth-death process\n", spacer);
1659             return (ERROR);
1660             }
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)
1664             {
1665             MrBayesPrint ("%s   Problem calculating prior for fossilized birth-death process\n", spacer);
1666             return (ERROR);
1667             }
1668         }
1669     else {
1670         MrBayesPrint ("%s   Move_Extinction not applicable\n", spacer);
1671         return (ERROR);
1672         }
1673     
1674     /* get proportions */
1675     oldProp[0] = oldM;
1676     oldProp[1] = 1.0 - oldM;
1677     newProp[0] = newM;
1678     newProp[1] = 1.0 - newM;
1679     
1680     /* adjust prior ratio according to beta distribution */
1681     alphaDir = mp->extinctionBeta;
1682     x = y = 0.0;
1683     for (i=0; i<2; i++)
1684         x += (alphaDir[i]-1.0)*log(newProp[i]);
1685     for (i=0; i<2; i++)
1686         y += (alphaDir[i]-1.0)*log(oldProp[i]);
1687     (*lnPriorRatio) = x - y + newLnPrior - oldLnPrior;
1688     
1689     return (NO_ERROR);
1690 }
1691
1692
1693 int Move_Fossilization (Param *param, int chain, RandLong *seed, MrBFlt *lnPriorRatio, MrBFlt *lnProposalRatio, MrBFlt *mvp)
1694 {
1695     /* change fossilization rate using sliding window */
1696     
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;
1700     char        *sS;
1701     ModelParams *mp;
1702     ModelInfo   *m;
1703     Tree        *t;
1704     
1705     /* get size of window, centered on current value */
1706     window = mvp[0];
1707     
1708     /* get model params and settings */
1709     mp = &modelParams[param->relParts[0]];
1710     m = &modelSettings[param->relParts[0]];
1711     
1712     /* get minimum and maximum values */
1713     minM = 0.00001;
1714     maxM = 1.0;
1715     
1716     /* get pointer to value to be changed */
1717     valIndex = (int)(RandomNumber(seed) * param->nValues);
1718     valPtr = GetParamVals(param, chain, state[chain]) + valIndex;
1719
1720     /* get old value */
1721     oldM = *valPtr;
1722     
1723     /* change value */
1724     if (window > maxM-minM)
1725         window = maxM-minM;
1726     newM = oldM + window * (RandomNumber(seed) - 0.5);
1727     
1728     /* check that new value is valid */
1729     isValidM = NO;
1730     do  {
1731         if (newM < minM)
1732             newM = 2 * minM - newM;
1733         else if (newM > maxM)
1734             newM = 2 * maxM - newM;
1735         else
1736             isValidM = YES;
1737         } while (isValidM == NO);
1738     
1739     /* get proposal ratio */
1740     *lnProposalRatio = 0.0;
1741     
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]);
1750
1751     if (LnFossilizationPriorPr (t, clockRate, &oldLnPrior, sR, eR, sF, fR, sS) == ERROR)
1752         {
1753         MrBayesPrint ("%s   Problem calculating prior for fossilized birth-death process\n", spacer);
1754         return (ERROR);
1755         }
1756     *valPtr = newM;  // update with new value
1757     if (LnFossilizationPriorPr (t, clockRate, &newLnPrior, sR, eR, sF, fR, sS) == ERROR)
1758         {
1759         MrBayesPrint ("%s   Problem calculating prior for fossilized birth-death process\n", spacer);
1760         return (ERROR);
1761         }
1762     
1763     /* get proportions */
1764     oldProp[0] = oldM;
1765     oldProp[1] = 1.0 - oldM;
1766     newProp[0] = newM;
1767     newProp[1] = 1.0 - newM;
1768
1769     /* adjust prior ratio according to beta distribution */
1770     alphaDir = mp->fossilizationBeta;
1771     x = y = 0.0;
1772     for (i=0; i<2; i++)
1773         x += (alphaDir[i]-1.0)*log(newProp[i]);
1774     for (i=0; i<2; i++)
1775         y += (alphaDir[i]-1.0)*log(oldProp[i]);
1776     (*lnPriorRatio) = x - y + newLnPrior - oldLnPrior;            
1777     
1778     return (NO_ERROR);
1779 }
1780
1781
1782 int Move_ExtSPR (Param *param, int chain, RandLong *seed, MrBFlt *lnPriorRatio, MrBFlt *lnProposalRatio, MrBFlt *mvp)
1783 {
1784     /* Change topology (and branch lengths) using SPR (unrooted) with extension probability.
1785        Pick either external or internal branches instead of just internal branches. */
1786     
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;
1791     Tree        *t;
1792     ModelParams *mp;
1793     
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 */
1797
1798     (*lnProposalRatio) = (*lnPriorRatio) = 0.0;
1799
1800     /* get tree */
1801     t = GetTree (param, chain, state[chain]);
1802
1803     /* get model params */
1804     mp = &modelParams[param->relParts[0]];
1805     
1806     /* max and min brlen */
1807     if (param->subParams[0]->paramId == BRLENS_UNI)
1808         {
1809         minV = mp->brlensUni[0] > BRLENS_MIN ? mp->brlensUni[0] : BRLENS_MIN;
1810         maxV = mp->brlensUni[1] < BRLENS_MAX ? mp->brlensUni[1] : BRLENS_MAX;
1811         isVPriorExp = NO;
1812         }
1813     else if (param->subParams[0]->paramId == BRLENS_GamDir)
1814         {
1815         minV = BRLENS_MIN;
1816         maxV = BRLENS_MAX;
1817         isVPriorExp = 2;
1818         }
1819     else if (param->subParams[0]->paramId == BRLENS_iGmDir)
1820         {
1821         minV = BRLENS_MIN;
1822         maxV = BRLENS_MAX;
1823         isVPriorExp = 3;
1824         }
1825     else if (param->subParams[0]->paramId == BRLENS_twoExp)
1826         {
1827         minV = BRLENS_MIN;
1828         maxV = BRLENS_MAX;
1829         isVPriorExp = 4;
1830         }
1831     else  /* (param->subParams[0]->paramId == BRLENS_EXP) */
1832         {
1833         minV = BRLENS_MIN;
1834         maxV = BRLENS_MAX;
1835         brlensExp = mp->brlensExp;
1836         isVPriorExp = YES;
1837         }
1838
1839     /* Dirichlet or twoExp prior */
1840     if (isVPriorExp > 1)
1841         (*lnPriorRatio) = -LogDirPrior(t, mp, isVPriorExp);
1842     
1843     topologyHasChanged = NO;
1844
1845 #   if defined (DEBUG_ExtSPR)
1846     printf ("Before:\n");
1847     ShowNodes (t->root, 2, NO);
1848     getchar();
1849 #   endif
1850     
1851     /* pick a random branch */
1852     do  {
1853         p = t->allDownPass[(int)(RandomNumber(seed) * (t->nNodes -1))];
1854         q = p->anc->right;  if (q == p) q = p->anc->left;
1855         i = j = 0;
1856         if (p->left == NULL)
1857             j = 2;
1858         if (p->anc->anc == NULL)
1859             i = 2;
1860         if (p->anc->anc != NULL && (p->anc->isLocked == YES || p->anc->anc->anc == NULL))
1861             i++;
1862         if (p->anc->anc != NULL && (q->isLocked == YES || q->left == NULL))
1863             i++;
1864         if (p->left != NULL && (p->left->isLocked == YES || p->left->left == NULL))
1865             j++;
1866         if (p->left != NULL && (p->right->isLocked == YES || p->right->left == NULL))
1867             j++;
1868         } while (i == 2 && j == 2);
1869     
1870     /* change in root tree ? */
1871     if (j == 2)
1872         moveInRoot = YES;
1873     else if (i == 2)
1874         moveInRoot = NO;
1875     else if (RandomNumber(seed) < 0.5)
1876         moveInRoot = YES;
1877     else
1878         moveInRoot = NO;
1879
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;
1886
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 */
1890     v = p;
1891     u = p->anc;
1892
1893     /* modify length of middle branch */
1894     m = v->length;
1895     x = m * exp(tuning * (RandomNumber(seed) - 0.5));
1896     while (x < minV || x > maxV)
1897         {
1898         if (x < minV) x = minV * minV / x;
1899         if (x > maxV) x = maxV * maxV / x;
1900         }
1901     v->length = x;
1902     v->upDateTi = YES;
1903
1904     /* update proposal and prior ratio based on length modification */
1905     (*lnProposalRatio) += log (x / m);
1906     if (isVPriorExp == YES)
1907         (*lnPriorRatio) += brlensExp * (m - x);
1908
1909     /* move around in root subtree */
1910     nRootNodes = 0;
1911     if (moveInRoot == YES)
1912         {
1913         /* mark nodes in root part */
1914         /* also determine direction of move in root part */
1915         if (u->left == v)
1916             a = u->right;
1917         else
1918             a = u->left;
1919         b = u->anc;
1920         if (u->anc->anc == NULL || u->isLocked == YES)
1921             directionUp = YES;
1922         else if (a->left == NULL || a->isLocked == YES)
1923             directionUp = NO;
1924         else if (RandomNumber(seed) < 0.5)
1925             directionUp = YES;
1926         else
1927             directionUp = NO;
1928         /* cut root part*/
1929         if (directionUp == NO)
1930             {
1931             b = a;  /* switch a and b */
1932             a = u->anc;
1933             b->anc = a;
1934             if (a->left == u)
1935                 a->left = b;
1936             else
1937                 a->right = b;
1938             }
1939         else  // if (directionUp == YES)
1940             {
1941             a->anc = b;
1942             if (b->left == u)
1943                 b->left = a;
1944             else
1945                 b->right = a;
1946             y = a->length;
1947             a->length = u->length;
1948             u->length = y;
1949             a->upDateTi = YES;
1950             u->upDateTi = YES;
1951             }
1952
1953         for (nRootNodes=0; RandomNumber(seed)<extensionProb || nRootNodes==0; nRootNodes++) 
1954             {
1955             if (directionUp == YES) 
1956                 {   /* going up tree */
1957                 if (a->left == NULL || a->isLocked == YES)
1958                     break;      /* can't go further */
1959                 b = a;
1960                 if (RandomNumber(seed) < 0.5)
1961                     a = a->left;
1962                 else
1963                     a = a->right;
1964                 if (u->isLocked == YES)
1965                     {
1966                     b->isLocked = YES;
1967                     u->isLocked = NO;
1968                     b->lockID = u->lockID;
1969                     u->lockID = 0;
1970                     }
1971                 }
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)
1977                     {
1978                     directionUp = YES; /* switch direction */
1979                     /* find sister of a */
1980                     if (a->left == b) 
1981                         {
1982                         b = a;
1983                         a = a->right;
1984                         }
1985                     else 
1986                         {  
1987                         b = a;
1988                         a = a->left;
1989                         }
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 */
1992                     }   
1993                 else 
1994                     {   /* continue down */
1995                     b = a;
1996                     a = a->anc;
1997                     b->upDateCl = YES; 
1998                     if (b->isLocked == YES)
1999                         {
2000                         u->isLocked = YES;
2001                         b->isLocked = NO;
2002                         u->lockID = b->lockID;
2003                         b->lockID = 0;
2004                         }
2005                     }
2006                 }
2007             }
2008             
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;
2015         
2016         /* modify branch length */
2017         m = u->length;
2018         x = m * exp(tuning * (RandomNumber(seed) - 0.5));
2019         while (x < minV || x > maxV)
2020             {
2021             if (x < minV) x = minV * minV / x;
2022             if (x > maxV) x = maxV * maxV / x;
2023             }
2024         u->length = x;
2025         u->upDateTi = YES;
2026
2027         /* update proposal and prior ratio based on length modification */
2028         (*lnProposalRatio) += log (x / m);
2029         if (isVPriorExp == YES)
2030             (*lnPriorRatio) += brlensExp * (m - x);
2031
2032         /* combine the subtrees */
2033         if (directionUp == YES)
2034             {
2035             u->anc = b;
2036             if (u->left == v)
2037                 u->right = a;
2038             else 
2039                 u->left = a;
2040             a->anc = u;
2041             if (b->left == a)
2042                 b->left = u;
2043             else
2044                 b->right = u;
2045             }
2046         else  // if (directionUp == NO)
2047             {
2048             u->anc = a;
2049             if (u->left == v)
2050                 u->right = b;
2051             else 
2052                 u->left = b;
2053             b->anc = u;
2054             if (a->left == b)
2055                 a->left = u;
2056             else
2057                 a->right = u;
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) */
2060             y = u->length;
2061             u->length = b->length;
2062             b->length = y;
2063             b->upDateTi = YES;
2064             u->upDateTi = YES;
2065             }
2066         }
2067
2068     /* move around in crown subtree */
2069     nCrownNodes = 0;
2070     if (moveInRoot == NO)
2071         {
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)
2077             directionLeft = NO;
2078         else if (RandomNumber(seed) < 0.5)
2079             directionLeft = YES;
2080         else
2081             directionLeft = NO;
2082         if (directionLeft == YES)
2083             {
2084             c = v->left;
2085             d = v->right;
2086             }
2087         else
2088             {
2089             c = v->right;
2090             d = v->left;
2091             }
2092
2093         /* store brlen nodes and brlen to move */
2094         x = c->length;
2095
2096         /* cut and reconnect crown part */
2097         c->anc = d;
2098         d->anc = c;
2099     
2100         for (nCrownNodes=0; RandomNumber(seed)<extensionProb || nCrownNodes==0; nCrownNodes++) 
2101             {
2102             if (c->left == NULL || c->isLocked == YES)
2103                 break;  /* can't go further */
2104             if (RandomNumber(seed) < 0.5)
2105                 {
2106                 /* rotate c anticlockwise - prepare pointers for move left */
2107                 c->anc = c->left;  /* the root will be in the direction we are heading */
2108                 c->left = c->right;
2109                 c->right = d;
2110                 }
2111             else 
2112                 {
2113                 /* rotate c clockwise - prepare pointers for move right */
2114                 c->anc = c->right;  /* the root will be in the direction we are heading */
2115                 c->right = c->left;
2116                 c->left = d;  
2117                 }
2118             /* OK - let's move! c->anc points in the right direction
2119                don't forget to move the branch lengths as well */
2120             d = c;
2121             c = c->anc;
2122             d->length = c->length;  /* also rotate other info ?? */
2123             d->upDateCl = YES; 
2124             d->upDateTi = YES;
2125             }
2126             
2127         topologyHasChanged = YES;
2128         /* check if stop constrained */
2129         if (c->left == NULL || c->isLocked == YES)
2130             isStopConstrained = YES;
2131         
2132         /* combine the subtrees */
2133         c->anc = v;
2134         d->anc = v;
2135         if (directionLeft == YES)
2136             {
2137             v->left = c;
2138             v->right = d;
2139             }
2140         else
2141             {
2142             v->left = d;
2143             v->right = c;
2144             }
2145         
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 */
2148         d->length = x;
2149         
2150         /* modify branch length */
2151         m = d->length;
2152         x = m * exp(tuning * (RandomNumber(seed) - 0.5));
2153         while (x < minV || x > maxV)
2154             {
2155             if (x < minV) x = minV * minV / x;
2156             if (x > maxV) x = maxV * maxV / x;
2157             }
2158         d->length = x;
2159         d->upDateTi = YES;
2160
2161         /* update proposal and prior ratio based on length modification */
2162         (*lnProposalRatio) += log (x / m);
2163         if (isVPriorExp == YES)
2164             (*lnPriorRatio) += brlensExp * (m - x);
2165         }
2166
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));
2172
2173     /* set flags for update of cond likes from v and down to root */
2174     p = v;
2175     while (p->anc != NULL)
2176         {
2177         p->upDateCl = YES;
2178         p = p->anc;
2179         }
2180
2181     /* get down pass sequence if tree topology has changed */
2182     if (topologyHasChanged == YES)
2183         {
2184         GetDownPass (t);
2185         }
2186
2187     /* Dirichlet or twoExp prior */
2188     if (isVPriorExp > 1)
2189         (*lnPriorRatio) += LogDirPrior(t, mp, isVPriorExp);
2190
2191 #   if defined (DEBUG_ExtSPR)
2192     printf ("After:\n");
2193     ShowNodes (t->root, 2, NO);
2194     getchar();
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);
2201     getchar();
2202 #   endif
2203
2204     return (NO_ERROR);
2205 }
2206
2207
2208 int Move_ExtSPR1 (Param *param, int chain, RandLong *seed, MrBFlt *lnPriorRatio, MrBFlt *lnProposalRatio, MrBFlt *mvp)
2209 {
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). */
2212     
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];
2217     Tree        *t;
2218     ModelParams *mp;
2219     
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 */
2223
2224     (*lnProposalRatio) = (*lnPriorRatio) = 0.0;
2225
2226     /* get tree */
2227     t = GetTree (param, chain, state[chain]);
2228
2229     /* get model params */
2230     mp = &modelParams[param->relParts[0]];
2231     
2232     /* max and min brlen */
2233     if (param->subParams[0]->paramId == BRLENS_UNI)
2234         {
2235         minV = mp->brlensUni[0] > BRLENS_MIN ? mp->brlensUni[0] : BRLENS_MIN;
2236         maxV = mp->brlensUni[1] < BRLENS_MAX ? mp->brlensUni[1] : BRLENS_MAX;
2237         isVPriorExp = NO;
2238         }
2239     else if (param->subParams[0]->paramId == BRLENS_GamDir)
2240         {
2241         minV = BRLENS_MIN;
2242         maxV = BRLENS_MAX;
2243         isVPriorExp = 2;
2244         }
2245     else if (param->subParams[0]->paramId == BRLENS_iGmDir)
2246         {
2247         minV = BRLENS_MIN;
2248         maxV = BRLENS_MAX;
2249         isVPriorExp = 3;
2250         }
2251     else if (param->subParams[0]->paramId == BRLENS_twoExp)
2252         {
2253         minV = BRLENS_MIN;
2254         maxV = BRLENS_MAX;
2255         isVPriorExp = 4;
2256         }
2257     else
2258         {
2259         minV = BRLENS_MIN;
2260         maxV = BRLENS_MAX;
2261         brlensExp = mp->brlensExp;
2262         isVPriorExp = YES;
2263         }
2264
2265     /* Dirichlet or twoExp prior */
2266     if (isVPriorExp > 1)
2267         (*lnPriorRatio) = -LogDirPrior(t, mp, isVPriorExp);
2268     
2269     topologyHasChanged = NO;
2270
2271 #   if defined (DEBUG_ExtSPR)
2272     printf ("Before:\n");
2273     ShowNodes (t->root, 2, NO);
2274     getchar();
2275 #   endif
2276     
2277     /* pick an internal branch that is free to move in either end
2278        (i and j keep track of number of locked directions) */
2279     do  {
2280         p = t->intDownPass[(int)(RandomNumber(seed) * (t->nIntNodes-1))];
2281         if (p->anc->left == p)
2282             a = p->anc->right;
2283         else
2284             a = p->anc->left;
2285         i = j = 0;
2286         if (a->isLocked == YES || a->left == NULL)
2287             i++;
2288         if (p->anc->isLocked == YES || p->anc->anc->anc == NULL)
2289             i++;
2290         if (p->left->isLocked == YES || p->left->left == NULL)
2291             j++;
2292         if (p->right->isLocked == YES || p->right->left == NULL)
2293             j++;
2294         } while (i == 2 && j == 2);
2295         
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 */
2301     v = p;
2302     u = p->anc;
2303
2304     /* store brlen node */
2305     brlenNode[3] = v;
2306
2307     /* change in root tree ? */
2308     if (j == 2)
2309         moveInRoot = YES;
2310     else if (i == 2)
2311         moveInRoot = NO;
2312     else if (RandomNumber(seed) < 0.5)
2313         moveInRoot = YES;
2314     else
2315         moveInRoot = NO;
2316
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;
2323
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)
2329         directionLeft = NO;
2330     else if (RandomNumber(seed) < 0.5)
2331         directionLeft = YES;
2332     else
2333         directionLeft = NO;
2334     if (directionLeft == YES)
2335         {
2336         c = v->left;
2337         d = v->right;
2338         }
2339     else
2340         {
2341         c = v->right;
2342         d = v->left;
2343         }
2344
2345     /* store brlen nodes and brlen to move */
2346     brlenNode[0] = d;
2347     brlenNode[1] = c;
2348     x = c->length;
2349
2350     /* cut and reconnect crown part */
2351     c->anc = d;
2352     d->anc = c;
2353     
2354     /* mark nodes in root part */
2355     /* also determine direction of move in root part */
2356     if (u->left == v)
2357         a = u->right;
2358     else
2359         a = u->left;
2360     b = u->anc;
2361     if (u->anc->anc == NULL || u->isLocked == YES)
2362         directionUp = YES;
2363     else if (a->left == NULL || a->isLocked == YES)
2364         directionUp = NO;
2365     else if (RandomNumber(seed) < 0.5)
2366         directionUp = YES;
2367     else
2368         directionUp = NO;
2369     if (directionUp == NO)
2370         {
2371         /* switch a and b */
2372         b = a;
2373         a = u->anc;
2374         }
2375
2376     /* store brlen nodes */
2377     if (directionUp == YES)
2378         {
2379         brlenNode[4] = u;
2380         brlenNode[5] = a;
2381         }
2382     else
2383         {
2384         brlenNode[4] = b;
2385         brlenNode[5] = u;
2386         }
2387
2388     /* cut root part*/
2389     if (directionUp == NO)
2390         {
2391         b->anc = a;
2392         if (a->left == u)
2393             a->left = b;
2394         else
2395             a->right = b;
2396         }
2397     else 
2398         {
2399         a->anc = b;
2400         if (b->left == u)
2401             b->left = a;
2402         else
2403             b->right = a;
2404         y = a->length;
2405         a->length = u->length;
2406         u->length = y;
2407         a->upDateTi = YES;
2408         u->upDateTi = YES;
2409         }
2410
2411     /* move around in root subtree */
2412     nRootNodes = 0;
2413     if (moveInRoot == YES)
2414         {
2415         for (nRootNodes=0; RandomNumber(seed)<extensionProb || nRootNodes==0; nRootNodes++) 
2416             {
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;
2422                 b = a;
2423                 if (RandomNumber(seed) < 0.5)
2424                     a = a->left;
2425                 else
2426                     a = a->right;
2427                 if (u->isLocked == YES)
2428                     {
2429                     b->isLocked = YES;
2430                     u->isLocked = NO;
2431                     b->lockID = u->lockID;
2432                     u->lockID = 0;
2433                     }
2434                 }
2435             else 
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) 
2441                     {
2442                     directionUp = YES; /* switch direction */
2443                     /* find sister of a */
2444                     if (a->left == b) 
2445                         {
2446                         b = a;
2447                         a = a->right;
2448                         }
2449                     else 
2450                         {  
2451                         b = a;
2452                         a = a->left;
2453                         }
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 */
2457                     }   
2458                 else 
2459                     {   /* continue down */
2460                     b = a;
2461                     a = a->anc;
2462                     b->upDateCl = YES; 
2463                     if (b->isLocked == YES)
2464                         {
2465                         u->isLocked = YES;
2466                         b->isLocked = NO;
2467                         u->lockID = b->lockID;
2468                         b->lockID = 0;
2469                         }
2470                     }
2471                 }
2472             }
2473         /* check whether stop is constrained */
2474         if (directionUp == YES) 
2475             {
2476             if (a->left == NULL || a->isLocked == YES) 
2477                 isStopConstrained = YES;
2478             }
2479         else 
2480             {
2481             if (a->anc  == NULL || u->isLocked == YES)
2482                 isStopConstrained = YES;
2483             }
2484         }
2485
2486     /* store brlen nodes */
2487     if (nRootNodes > 0)
2488         {
2489         if (directionUp == YES)
2490             {
2491             brlenNode[6] = a;
2492             brlenNode[5] = u;
2493             }
2494         else
2495             {
2496             brlenNode[6] = u;
2497             brlenNode[5] = b;
2498             }
2499         }
2500
2501     /* move around in crown subtree */
2502     nCrownNodes = 0;
2503     if (moveInRoot == NO)       
2504         {
2505         for (nCrownNodes=0; RandomNumber(seed)<extensionProb || nCrownNodes==0; nCrownNodes++) 
2506             {
2507             if (c->left == NULL || c->isLocked == YES)
2508                 break;  /* can't go further */
2509             topologyHasChanged = YES;
2510             if (RandomNumber(seed) < 0.5) 
2511                 {
2512                 /* rotate c anticlockwise - prepare pointers for move left */
2513                 c->anc = c->left;  /* the root will be in the direction we are heading */
2514                 c->left = c->right;
2515                 c->right = d;
2516                 }
2517             else 
2518                 {
2519                 /* rotate c clockwise - prepare pointers for move right */
2520                 c->anc = c->right;  /* the root will be in the direction we are heading */
2521                 c->right = c->left;
2522                 c->left = d;  
2523                 }
2524             /* OK - let's move!; c->anc points in the right direction
2525             don't forget to move the branch lengths as well */
2526             d = c;
2527             c = c->anc;
2528             d->length = c->length;
2529             d->upDateCl = YES; 
2530             d->upDateTi = YES;
2531             }
2532         /* check if stop constrained */
2533         if (c->left == NULL || c->isLocked == YES)
2534             isStopConstrained = YES;
2535         }
2536
2537     /* store brlen nodes */
2538     if (nCrownNodes > 0)
2539         {
2540         brlenNode[2] = c;
2541         brlenNode[1] = d;
2542         }
2543
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));
2549
2550     /* combine the subtrees */
2551     c->anc = v;
2552     d->anc = v;
2553     if (directionLeft == YES) 
2554         {
2555         v->left = c;
2556         v->right = d;
2557         }
2558     else 
2559         {
2560         v->left = d;
2561         v->right = c;
2562         }
2563
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)
2569         {
2570         d->length = x;
2571         d->upDateTi = YES;
2572         }
2573     else
2574         {
2575         c->length = x;
2576         }
2577
2578     if (directionUp == YES) 
2579         {
2580         u->anc = b;
2581         if (u->left == v)
2582             u->right = a;
2583         else 
2584             u->left = a;
2585         a->anc = u;
2586         if (b->left == a)
2587             b->left = u;
2588         else
2589             b->right = u;
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) 
2598             {
2599             x = u->length;
2600             u->length = a->length;
2601             a->length = x;
2602             a->upDateTi = NO;
2603             u->upDateTi = NO;
2604             }
2605         }
2606     else 
2607         {
2608         u->anc = a;
2609         if (u->left == v)
2610             u->right = b;
2611         else 
2612             u->left = b;
2613         b->anc = u;
2614         if (a->left == b)
2615             a->left = u;
2616         else
2617             a->right = u;
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) */
2622         if (nRootNodes > 0) 
2623             {
2624             x = u->length;
2625             u->length = b->length;
2626             b->length = x;
2627             b->upDateTi = YES;
2628             u->upDateTi = YES;
2629             }
2630         }
2631     
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)
2637         {
2638         if (x < minV)
2639             x = minV * minV / x;
2640         else if (x > maxV)
2641             x = maxV * maxV / x;
2642         }
2643     brlenNode[3]->length = x;
2644     brlenNode[3]->upDateTi = YES;
2645
2646     /* update proposal and prior ratio based on length modification */
2647     (*lnProposalRatio) += log (x / m);
2648     if (isVPriorExp == YES)
2649         (*lnPriorRatio) += brlensExp * (m - x);
2650
2651     if (moveInRoot == NO)
2652         {
2653         /* if no move in crown, then select randomly, otherwise always the moved branch */
2654         if (nCrownNodes == 0 && RandomNumber(seed) < 0.5)
2655             p = brlenNode[0];
2656         else
2657             p = brlenNode[1];
2658
2659         /* modify branch length */
2660         m = p->length;
2661         x = m * exp(tuning * (RandomNumber(seed) - 0.5));
2662         while (x < minV || x > maxV)
2663             {
2664             if (x < minV)
2665                 x = minV * minV / x;
2666             else if (x > maxV)
2667                 x = maxV * maxV / x;
2668             }
2669         p->length = x;
2670         p->upDateTi = YES;
2671
2672         /* update proposal and prior ratio based on length modification */
2673         (*lnProposalRatio) += log (x / m);
2674         if (isVPriorExp == YES)
2675             (*lnPriorRatio) += brlensExp * (m - x);
2676         }
2677             
2678     if (moveInRoot == YES)
2679         {
2680         /* if no move in root, then select randomly, otherwise always the moved branch */
2681         if (nRootNodes == 0 && RandomNumber(seed) < 0.5)
2682             p = brlenNode[4];
2683         else
2684             p = brlenNode[5];
2685         
2686         /* modify branch length but not if 'root' branch in rooted tree */
2687         if (t->isRooted == NO || p->anc->anc != NULL)
2688             {
2689             m = p->length;
2690             x = m * exp(tuning * (RandomNumber(seed) - 0.5));
2691             while (x < minV || x > maxV)
2692                 {
2693                 if (x < minV)
2694                     x = minV * minV / x;
2695                 else if (x > maxV)
2696                     x = maxV * maxV / x;
2697                 }
2698             p->length = x;
2699             p->upDateTi = YES;
2700
2701             /* update proposal and prior ratio based on length modification */
2702             (*lnProposalRatio) += log (x / m);
2703             if (isVPriorExp == YES)
2704                 (*lnPriorRatio) += brlensExp * (m - x); 
2705             }
2706         }
2707
2708     /* set flags for update of cond likes from v and down to root */
2709     p = v;
2710     while (p->anc != NULL)
2711         {
2712         p->upDateCl = YES;
2713         p = p->anc;
2714         }
2715
2716     /* get down pass sequence if tree topology has changed */
2717     if (topologyHasChanged == YES)
2718         {
2719         GetDownPass (t);
2720         }
2721
2722     /* Dirichlet or twoExp prior */
2723     if (isVPriorExp > 1)
2724         (*lnPriorRatio) += LogDirPrior(t, mp, isVPriorExp);
2725
2726 #   if defined (DEBUG_ExtSPR)
2727     printf ("After:\n");
2728     ShowNodes (t->root, 2, NO);
2729     getchar();
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);
2736     getchar();
2737 #   endif
2738
2739     return (NO_ERROR);
2740 }
2741
2742
2743 int Move_ExtSPRClock (Param *param, int chain, RandLong *seed, MrBFlt *lnPriorRatio, MrBFlt *lnProposalRatio, MrBFlt *mvp)
2744 {
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.
2749
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.
2756        
2757        On the ending branch, the attachment point is reinserted randomly
2758        along the branch (below the minimum age of the node). */
2759     
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;
2766     Tree        *t;
2767     ModelInfo   *m;
2768     Param       *subParm;
2769
2770     extensionProb = mvp[0]; /* extension probability */
2771
2772     (*lnProposalRatio) = (*lnPriorRatio) = 0.0;
2773
2774     /* get tree */
2775     t = GetTree (param, chain, state[chain]);
2776  
2777     /* get model params and model info */
2778     m = &modelSettings[param->relParts[0]];
2779     
2780     /* get clock rate */
2781     clockRate = *GetParamVals (m->clockRate, chain, state[chain]);
2782
2783     /* get min and max branch lengths in relative time and substitution units */
2784     minV = BRLENS_MIN;
2785
2786 #   if defined (DEBUG_ExtSPRClock)
2787     printf ("Before:\n");
2788     ShowNodes (t->root, 2, YES);
2789     getchar();
2790 #   endif
2791     
2792     /* pick a branch */
2793     do  {
2794         p = t->allDownPass[(int)(RandomNumber(seed) * (t->nNodes - 2))];
2795         a = p->anc->left;
2796         b = p->anc->right;
2797         }
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 */
2802     
2803     /* set up pointers for nodes around the picked branch */
2804     v = p;
2805     u = p->anc;
2806     if (u->left == v)
2807         a = u->right;
2808     else
2809         a = u->left;
2810     b = u->anc;
2811     oldA = a;
2812
2813     /* record branch length for insertion in back move */
2814     if (v->length > 0.0)  /* side branch, not anc fossil */
2815         {
2816         if (v->nodeDepth > a->nodeDepth)
2817             oldBrlen = b->nodeDepth - v->nodeDepth - 2.0*minV;
2818         else
2819             oldBrlen = b->nodeDepth - a->nodeDepth - 2.0*minV;
2820         }
2821     else  /* ancestral fossil */
2822         {
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);
2825         oldBrlen = y - x;
2826         }
2827     v1 = a->length;
2828     v2 = u->length;
2829     v3 = v->length;
2830
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++)
2833         {
2834         subParm = param->subParams[0]->subParams[i];
2835         if (subParm->paramType == P_CPPEVENTS)
2836             {
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];
2844             if (n2 > 0)
2845                 {
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));
2848                 }
2849             for (j=0; j<n1; j++)
2850                 position[a->index][j] *= v1 / (v1+v2);
2851             for (j=n1; j<n1+n2; j++)
2852                 {
2853                 position[a->index][j] = (position[u->index][j-n1] * v2 + v1) / (v1+v2);
2854                 rateMultiplier[a->index][j] = rateMultiplier[u->index][j-n1];
2855                 }
2856             nEvents[a->index] = n1+n2;
2857             nEvents[u->index] = 0;
2858             if (n2 > 0)
2859                 {
2860                 free (position[u->index]);
2861                 free (rateMultiplier[u->index]);
2862                 position[u->index] = rateMultiplier[u->index] = NULL;
2863                 }
2864             }   /* end CPP events parm */
2865         else if ( subParm->paramType == P_TK02BRANCHRATES ||
2866                  (subParm->paramType == P_MIXEDBRCHRATES && *GetParamIntVals(subParm, chain, state[chain]) == RCL_TK02))
2867             {
2868             /* adjust prior ratio */
2869             if (subParm->paramType == P_TK02BRANCHRATES)
2870                 nu = *GetParamVals (modelSettings[subParm->relParts[0]].tk02var, chain, state[chain]);
2871             else
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]);
2879             
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))
2886             {
2887             if (subParm->paramType == P_IGRBRANCHRATES)
2888                 igrvar = *GetParamVals (modelSettings[subParm->relParts[0]].igrvar, chain, state[chain]);
2889             else
2890                 igrvar = *GetParamVals (modelSettings[subParm->relParts[0]].mixedvar, chain, state[chain]);
2891             igrRate = GetParamVals (subParm, chain, state[chain]);
2892
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]);
2899
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);
2903             }
2904         }   /* next subparameter */
2905
2906     /* cut tree */
2907     a->anc = b;
2908     if (b->left == u)
2909         b->left = a;
2910     else
2911         b->right = a;
2912     a->length += u->length;
2913     a->upDateTi = YES;
2914
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)
2917         {
2918         isStartLocked = YES;
2919         directionUp = NO;
2920         }
2921     else
2922         {
2923         isStartLocked = NO;
2924         if (RandomNumber(seed) < 0.5)
2925             directionUp = YES;
2926         else
2927             directionUp = NO;
2928         }
2929         
2930     /* move around in root subtree */
2931     for (nRootNodes=0; nRootNodes==0 || RandomNumber(seed)<extensionProb; nRootNodes++) 
2932         {
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;
2938             b = a;
2939             if (a->left->length < TIME_MIN)
2940                 a = a->right;
2941             else if (a->right->length < TIME_MIN)
2942                 a = a->left;
2943             else if (RandomNumber(seed) < 0.5)
2944                 a = a->left;
2945             else
2946                 a = a->right;
2947             }
2948         else 
2949             {   /* going down tree */
2950             topologyHasChanged = YES;
2951             if (RandomNumber(seed) < 0.5 || b->anc->anc == NULL || b->isLocked == YES)
2952                 {
2953                 directionUp = YES; /* switch direction */
2954                 /* find sister of a */
2955                 if (b->left == a)
2956                     a = b->right;
2957                 else
2958                     a = b->left;
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 */
2962                 }   
2963             else 
2964                 {   /* continue down */
2965                 a = b;
2966                 b = b->anc;
2967                 a->upDateCl = YES;
2968                 }
2969             }
2970         }
2971         
2972     /* determine whether the forward move was or would have been stopped by constraints */
2973     isStopLocked = NO;
2974     if (directionUp == YES)
2975         {
2976         if (a->left == NULL || a->isLocked == YES || a->nodeDepth < v->nodeDepth + minV)
2977             isStopLocked = YES;
2978         }
2979
2980     /* reattach u */
2981     if (u->left == v)
2982         u->right = a;
2983     else
2984         u->left = a;
2985     a->anc = u;
2986     u->anc = b;
2987     if (b->left == a)
2988         b->left = u;
2989     else
2990         b->right = u;
2991
2992     if (v->length > 0.0)  /* side branch, not anc fossil */
2993         {
2994         if (a->nodeDepth > v->nodeDepth)
2995             newBrlen = b->nodeDepth - a->nodeDepth - 2.0*minV;
2996         else
2997             newBrlen = b->nodeDepth - v->nodeDepth - 2.0*minV;
2998         }
2999     else  /* ancestral fossil */
3000         {
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);
3003         newBrlen = y - x;
3004         }
3005     if (newBrlen <= 0.0)
3006         {
3007         abortMove = YES;
3008         return (NO_ERROR);
3009         }
3010     
3011     /* adjust lengths */
3012     if (v->length > 0.0)  /* side branch, not anc fossil */
3013         {
3014         u->nodeDepth = b->nodeDepth - minV - RandomNumber(seed) * newBrlen;
3015         v->length = u->nodeDepth - v->nodeDepth;
3016         }
3017     else  /* ancestral fossil */
3018         {
3019         u->nodeDepth = y - RandomNumber(seed) * newBrlen;
3020         v->nodeDepth = u->nodeDepth;
3021         v->age = u->age = u->nodeDepth / clockRate;
3022         }
3023     u->length = b->nodeDepth - u->nodeDepth;
3024     a->length = u->nodeDepth - a->nodeDepth;
3025     
3026     v3new = v->length;
3027     v4 = a->length;
3028     v5 = u->length;
3029
3030     /* adjust events, prior ratio and proposal ratio for relaxed clock models */
3031     for (i=0; i<param->subParams[0]->nSubParams; i++)
3032         {
3033         subParm = param->subParams[0]->subParams[i];
3034         if (subParm->paramType == P_CPPEVENTS)
3035             {
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++)
3041                 {
3042                 if (position[a->index][j] > v4 / (v4+v5))
3043                     break;
3044                 }
3045             n4 = j;
3046             n5 = nEvents[a->index] - j;
3047             nEvents[u->index] = n5;
3048             if (n5 > 0)
3049                 {
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++)
3053                     {
3054                     position[u->index][j-n4] = (position[a->index][j] * (v4+v5) - v4) / v5;
3055                     rateMultiplier[u->index][j-n4] = rateMultiplier[a->index][j];
3056                     }
3057                 if (n4 > 0)
3058                     {
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);
3063                     }
3064                 else
3065                     {
3066                     free (position[a->index]);
3067                     free (rateMultiplier[a->index]);
3068                     position[a->index] = rateMultiplier[a->index] = NULL;
3069                     }
3070                 nEvents[a->index] = n4;
3071                 }
3072             else
3073                 {
3074                 for (j=0; j<nEvents[a->index]; j++)
3075                     position[a->index][j] *= ((v4+v5) / v4);
3076                 }
3077
3078             /* adjust proposal ratio for length change in v branch*/
3079             (*lnProposalRatio) += n3 * log (v3new / v3);
3080
3081             /* adjust prior ratio for length change */
3082             lambda = *GetParamVals (modelSettings[subParm->relParts[0]].cppRate, chain, state[chain]);
3083             (*lnPriorRatio) += lambda * (v3 - v3new);
3084
3085             /* update effective branch lengths */
3086             if (UpdateCppEvolLengths (subParm, oldA, chain) == ERROR)
3087                 {
3088                 abortMove = YES;
3089                 return (NO_ERROR);
3090                 }
3091             if (UpdateCppEvolLengths (subParm, u, chain) == ERROR)
3092                 {
3093                 abortMove = YES;
3094                 return (NO_ERROR);
3095                 }
3096             }   /* end cpp events parameter */
3097         else if ( subParm->paramType == P_TK02BRANCHRATES ||
3098                  (subParm->paramType == P_MIXEDBRCHRATES && *GetParamIntVals(subParm, chain, state[chain]) == RCL_TK02))
3099             {
3100             /* adjust prior ratio */
3101             if (subParm->paramType == P_TK02BRANCHRATES)
3102                 nu = *GetParamVals (modelSettings[subParm->relParts[0]].tk02var, chain, state[chain]);
3103             else
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]);
3111
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))
3120             {
3121             /* adjust prior ratio */
3122             if (subParm->paramType == P_IGRBRANCHRATES)
3123                 igrvar = *GetParamVals (modelSettings[subParm->relParts[0]].igrvar, chain, state[chain]);
3124             else
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]);
3132
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 */
3140
3141     /* set tiprobs update flags */
3142     a->upDateTi = YES;
3143     u->upDateTi = YES;
3144     v->upDateTi = YES;
3145
3146     /* set flags for update of cond likes from u and down to root */
3147     p = u;
3148     while (p->anc != NULL)
3149         {
3150         p->upDateCl = YES; 
3151         p = p->anc;
3152         }
3153
3154     /* adjust prior ratio for clock tree */
3155     if (LogClockTreePriorRatio(param, chain, &x) == ERROR)
3156         return (ERROR);
3157     (*lnPriorRatio) += x;
3158
3159     if (topologyHasChanged == YES)
3160         {
3161         /* get down pass sequence if tree topology has changed */
3162         GetDownPass (t);
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));
3169         }
3170
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);
3177 #   endif
3178
3179     return (NO_ERROR);
3180 }
3181
3182
3183 int Move_ExtSS (Param *param, int chain, RandLong *seed, MrBFlt *lnPriorRatio, MrBFlt *lnProposalRatio, MrBFlt *mvp)
3184 {
3185     /* Change branch lengths and topology (potentially) using Subtree Swapping (unrooted) 
3186        with extension probability.
3187
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.
3194
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.
3197        
3198        */
3199     
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;
3204     Tree        *t;
3205     ModelParams *mp;
3206
3207     (*lnPriorRatio) = (*lnProposalRatio) = 0.0;
3208
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 */
3212     
3213     /* get tree */
3214     t = GetTree (param, chain, state[chain]);
3215
3216     /* get model params */
3217     mp = &modelParams[param->relParts[0]];
3218     
3219     /* max and min brlen */
3220     if (param->subParams[0]->paramId == BRLENS_UNI)
3221         {
3222         minV = mp->brlensUni[0] > BRLENS_MIN ? mp->brlensUni[0] : BRLENS_MIN;
3223         maxV = mp->brlensUni[1];
3224         isVPriorExp = NO;
3225         }
3226     else if (param->subParams[0]->paramId == BRLENS_GamDir)
3227         {
3228         minV = BRLENS_MIN;
3229         maxV = BRLENS_MAX;
3230         isVPriorExp = 2;
3231         }
3232     else if (param->subParams[0]->paramId == BRLENS_iGmDir)
3233         {
3234         minV = BRLENS_MIN;
3235         maxV = BRLENS_MAX;
3236         isVPriorExp = 3;
3237         }
3238     else if (param->subParams[0]->paramId == BRLENS_twoExp)
3239         {
3240         minV = BRLENS_MIN;
3241         maxV = BRLENS_MAX;
3242         isVPriorExp = 4;
3243         }
3244     else
3245         {
3246         minV = BRLENS_MIN;
3247         maxV = BRLENS_MAX;
3248         brlensExp = mp->brlensExp;
3249         isVPriorExp = YES;
3250         }
3251
3252     /* Dirichlet or twoExp prior */
3253     if (isVPriorExp > 1)
3254         (*lnPriorRatio) = -LogDirPrior(t, mp, isVPriorExp);
3255
3256     topologyHasChanged = NO;
3257
3258     /* unmark all tree */
3259     for (i=0; i<t->nNodes; i++)
3260         {
3261         p = t->allDownPass[i];
3262         p->marked = NO;
3263         }
3264
3265     /* pick a branch */
3266     do
3267         {
3268         p = t->allDownPass[(int)(RandomNumber(seed) * t->nNodes)];
3269         } while (p->anc == NULL);
3270         
3271     /* set up pointers for nodes around the picked branch */
3272     v = p;
3273     u = p->anc;
3274
3275     /* check the possible move directions */
3276     numFree = 0;
3277     if (v->left != NULL && v->left->isLocked == NO)
3278         numFree ++;
3279     if (v->right != NULL && v->right->isLocked == NO)
3280         numFree++;
3281     if (u->anc != NULL && u->isLocked == NO)
3282         numFree++;
3283     if (u->left == v)
3284         {
3285         if (u->right != NULL && u->right->isLocked == NO)
3286             numFree++;
3287         }
3288     else
3289         {
3290         if (u->left != NULL && u->left->isLocked == NO)
3291             numFree++;
3292         }
3293
3294     /* select one of them randomly */
3295     i = (int) (RandomNumber(seed) * numFree) + 1;
3296     numFree = 0;
3297     a = b = c = d = p;
3298     directionLeft = directionUp = moveInRoot = NO;
3299     if (v->left != NULL && v->left->isLocked == NO)
3300         {
3301         numFree ++;
3302         if (i == numFree)
3303             {
3304             moveInRoot = NO;
3305             directionLeft = YES;
3306             c = v->left;
3307             d = v;
3308             }
3309         }
3310     if (v->right != NULL && v->right->isLocked == NO)
3311         {
3312         numFree ++;
3313         if (i == numFree)
3314             {
3315             moveInRoot = NO;
3316             directionLeft = NO;
3317             c = v->right;
3318             d = v;
3319             }
3320         }
3321     if (u->anc != NULL && u->isLocked == NO)
3322         {
3323         numFree ++;
3324         if (i == numFree)
3325             {
3326             moveInRoot = YES;
3327             directionUp = NO;
3328             a = u->anc;
3329             b = u;
3330             }
3331         }
3332     if (u->left == v)
3333         {
3334         if (u->right != NULL && u->right->isLocked == NO)
3335             {
3336             numFree ++;
3337             if (i == numFree)
3338                 {
3339                 moveInRoot = YES;
3340                 directionUp = YES;
3341                 a = u->right;
3342                 b = u;
3343                 }
3344             }
3345         }
3346     else
3347         {
3348         if (u->left != NULL && u->left->isLocked == NO)
3349             {
3350             numFree ++;
3351             if (i == numFree)
3352                 {
3353                 moveInRoot = YES;
3354                 directionUp = YES;
3355                 a = u->left;
3356                 b = u;
3357                 }
3358             }
3359         }
3360
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);
3367     getchar();
3368 #   endif
3369     
3370     /* move around and potentially swap in root subtree */
3371     nRootNodes = 0;
3372     if (moveInRoot == YES)
3373         {
3374         for (nRootNodes=0; nRootNodes==0 || RandomNumber(seed)<extensionProb; nRootNodes++) 
3375             {
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;
3381                 b = a;
3382                 if (RandomNumber(seed) < 0.5)
3383                     a = a->left;
3384                 else
3385                     a = a->right;
3386                 }
3387             else 
3388                 {   /* going down tree */
3389                 if (a->anc == NULL || a->isLocked == YES)
3390                     break;      /* can't go further */
3391                 topologyHasChanged = YES;
3392                 b->marked = YES;
3393
3394                 if (RandomNumber(seed) < 0.5) 
3395                     {
3396                     directionUp = YES; /* switch direction */
3397                     /* find sister of a */
3398                     if (a->left == b) 
3399                         {
3400                         b = a;
3401                         a = a->right;
3402                         }
3403                     else 
3404                         {  
3405                         b = a;
3406                         a = a->left;
3407                         }
3408                     }   
3409                 else 
3410                     {   /* continue down */
3411                     b = a;
3412                     a = a->anc;
3413                     }
3414                 }
3415             }
3416         /* swap the root subtrees */
3417         if (nRootNodes > 0)
3418             {
3419             if (directionUp == YES)
3420                 {
3421                 v->anc = b;
3422                 a->anc = u;
3423                 if (b->left == a)
3424                     b->left = v;
3425                 else if (b->right == a)
3426                     b->right = v;
3427                 if (u->left == v)
3428                     u->left = a;
3429                 else
3430                     u->right = a;
3431                 }
3432             else
3433                 {
3434                 /* rotate the nodes from b to u*/
3435                 p = b;
3436                 q = a;
3437                 x = b->length;
3438                 while (p->left->marked == YES || p->right->marked == YES)
3439                     {                   
3440                     if (p->left->marked == YES) 
3441                         {
3442                         /* rotate p anticlockwise - prepare pointers for move left */
3443                         p->anc = p->left;  /* the root will be in the direction we are heading */
3444                         p->left = p->right;
3445                         p->right = q;
3446                         }
3447                     else 
3448                         {
3449                         /* rotate p clockwise - prepare pointers for move right */
3450                         p->anc = p->right;  /* the root will be in the direction we are heading */
3451                         p->right = p->left;
3452                         p->left = q;  
3453                         }
3454                     /* OK - let's move!; p->anc points in the right direction
3455                     don't forget to move the branch lengths as well */
3456                     q = p;
3457                     p = p->anc;
3458                     q->length = p->length;
3459                     q->upDateTi = YES;
3460                     }
3461                 /* rotations finished, take care of u */
3462                 if (u->left == v)
3463                     u->left = u->anc;
3464                 else
3465                     u->right = u->anc;
3466                 u->length = x;
3467                 /* now swap the subtrees of u and b */
3468                 if (a->left == b)
3469                     a->left = u;
3470                 else
3471                     a->right = u;
3472                 u->anc = a;
3473                 v->anc = b;
3474                 if (b->left == a)
3475                     b->left = v;
3476                 else
3477                     b->right = v;
3478                 }
3479             }
3480         }
3481
3482     /* move around and potentially swap in crown subtree */
3483     nCrownNodes = 0;
3484     if (moveInRoot == NO)       
3485         {
3486         x = v->length;  /* save v length in case there is a move */
3487         for (nCrownNodes=0; nCrownNodes==0 || RandomNumber(seed)<extensionProb; nCrownNodes++) 
3488             {
3489             if (c->left == NULL || c->isLocked == YES)
3490                 break;  /* can't go further */
3491
3492             topologyHasChanged = YES;
3493             
3494             /* prepare d for move */
3495             d->anc = c;
3496             d->length = c->length;
3497             d->upDateTi = YES;
3498             d->upDateCl = YES;
3499             if (d->isLocked == YES)
3500                 {
3501                 c->isLocked = YES;
3502                 d->isLocked = NO;
3503                 c->lockID = d->lockID;
3504                 d->lockID = -1;
3505                 }
3506             
3507             /* go left or right with equal probability */
3508             if (RandomNumber(seed) < 0.5) 
3509                 {
3510                 /* rotate c anticlockwise - prepare pointers for move left */
3511                 c->anc = c->left;  /* the root will be in the direction we are heading */
3512                 c->left = c->right;
3513                 c->right = d;
3514                 }
3515             else 
3516                 {
3517                 /* rotate c clockwise - prepare pointers for move right */
3518                 c->anc = c->right;  /* the root will be in the direction we are heading */
3519                 c->right = c->left;
3520                 c->left = d;
3521                 }
3522             /* OK - let's move!; c->anc points in the right direction */
3523             d = c;
3524             c = c->anc;
3525             }
3526
3527         /* swap the crown subtrees */
3528         if (nCrownNodes > 0)
3529             {
3530             d->anc = u;
3531             d->length = x;
3532             if (u->left == v)
3533                 u->left = d;
3534             else
3535                 u->right = d;
3536
3537             c->anc = v;
3538             if (directionLeft == YES)
3539                 v->left = c;
3540             else
3541                 v->right = c;
3542             }
3543         }
3544
3545     /* modify branch lengths */
3546     if (nCrownNodes > 0)
3547         {
3548         p = c;
3549         q = d;
3550         }
3551     else if (nRootNodes > 0)
3552         {
3553         if (directionUp == YES)
3554             {
3555             p = v;
3556             q = a;
3557             }
3558         else
3559             {
3560             p = v;
3561             q = u;
3562             }
3563         }
3564     else
3565         {
3566         p = v;
3567         if (RandomNumber(seed) < 0.5)
3568             {
3569             if (RandomNumber(seed) < 0.5)
3570                 q = u;
3571             else
3572                 {
3573                 if (u->left == v)
3574                     q = u->right;
3575                 else
3576                     q = u->left;
3577                 }
3578             }
3579         else
3580             {
3581             if (RandomNumber(seed) < 0.5)
3582                 q = v->left;
3583             else
3584                 q = v->right;
3585             }
3586         }
3587
3588     if (p != NULL)
3589         {
3590         m = p->length;
3591         x = m * exp(tuning * (RandomNumber(seed) - 0.5));
3592         while (x < minV || x > maxV)
3593             {
3594             if (x < minV)
3595                 x = minV * minV / x;
3596             else if (x > maxV)
3597                 x = maxV * maxV / x;
3598             }
3599         p->length = x;
3600         p->upDateTi = YES;
3601
3602         /* update proposal and prior ratio based on length modification */
3603         (*lnProposalRatio) += log (x / m);
3604         if (isVPriorExp == YES)
3605             (*lnPriorRatio) += brlensExp * (m - x);
3606         }
3607
3608     if (q != NULL && q->anc != NULL)
3609         {
3610         m = q->length;
3611         x = m * exp(tuning * (RandomNumber(seed) - 0.5));
3612         while (x < minV || x > maxV)
3613             {
3614             if (x < minV)
3615                 x = minV * minV / x;
3616             else if (x > maxV)
3617                 x = maxV * maxV / x;
3618             }
3619         q->length = x;
3620         q->upDateTi = YES;
3621
3622         /* update proposal and prior ratio based on length modification */
3623         (*lnProposalRatio) += log (x / m);
3624         if (isVPriorExp == YES)
3625             (*lnPriorRatio) += brlensExp * (m - x);
3626         }
3627
3628     /* set flags for update of cond likes from v and down to root */
3629     p = v;
3630     while (p->anc != NULL)
3631         {
3632         p->upDateCl = YES;
3633         p = p->anc;
3634         }
3635
3636     if (topologyHasChanged == YES)
3637         {
3638         /* set flags for update of cond likes from u and down to root */
3639         p = u;
3640         while (p->anc != NULL)
3641             {
3642             p->upDateCl = YES;
3643             p = p->anc;
3644             }
3645         }
3646
3647     /* get down pass sequence if tree topology has changed */
3648     if (topologyHasChanged == YES)
3649         {
3650         GetDownPass (t);
3651         }
3652
3653     /* Dirichlet or twoExp prior */
3654     if (isVPriorExp > 1)
3655         (*lnPriorRatio) += LogDirPrior(t, mp, isVPriorExp);
3656     
3657 #   if defined (DEBUG_ExtSS)
3658     printf ("After:\n");
3659     ShowNodes (t->root, 2, NO);
3660     getchar();
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);
3668     getchar();
3669 #   endif
3670
3671     return (NO_ERROR);
3672 }
3673
3674
3675 int Move_ExtSSClock (Param *param, int chain, RandLong *seed, MrBFlt *lnPriorRatio, MrBFlt *lnProposalRatio, MrBFlt *mvp)
3676 {
3677     /* Change branch lengths and topology (potentially) using SS-type move 
3678        with extension probability (rather than window, attachment rate or similar). */
3679
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 */
3687     
3688     int         i, *nEvents, numFreeOld, numFreeNew;
3689     MrBFlt      x, oldALength, oldCLength, extensionProb, igrvar, *igrRate,
3690                 *tk02Rate, *brlens, nu, ran, cumulativeProb, forwardProb,
3691                 backwardProb, minV;
3692     TreeNode    *p, *q, *a, *c;
3693     Tree        *t;
3694     Param       *subParm;
3695
3696     extensionProb = mvp[0]; /* extension probability */
3697
3698     (*lnProposalRatio) = (*lnPriorRatio) = 0.0;
3699
3700     /* get tree */
3701     t = GetTree (param, chain, state[chain]);
3702
3703     /* get min and max brlens in relative time and subst units */
3704     minV = BRLENS_MIN;
3705
3706     /* calculate the number of free nodes */
3707     numFreeOld = t->nNodes-2;
3708     if (t->nConstraints > 1)
3709         {
3710         numFreeOld = 0;
3711         for (i=0; i<t->nNodes-2; i++)
3712             {
3713             p = t->allDownPass[i];
3714             if (p->anc->left == p)
3715                 q = p->anc->right;
3716             else
3717                 q = p->anc->left;
3718             if (p->anc->isLocked == NO || q->isLocked == NO)
3719                 numFreeOld++;
3720             }
3721         }
3722
3723     /* pick a branch */
3724     do  {
3725         p = t->allDownPass[(int)(RandomNumber(seed) * (t->nNodes -2))];
3726         if (p->anc->left == p)
3727             q = p->anc->right;
3728         else
3729             q = p->anc->left;
3730         }
3731     while ((p->anc->isLocked == YES && q->isLocked == YES) || p->length < TIME_MIN || q->length < TIME_MIN);
3732     /* choose subtree that can be swapped */
3733
3734     /* set up pointers for nodes around the picked branch */
3735     a = p;
3736     if (p->anc->left == p)
3737         q = p->anc->right;
3738     else
3739         q = p->anc->left;
3740     if (p->anc->anc->left == p->anc)
3741         c = p->anc->anc->right;
3742     else
3743         c = p->anc->anc->left;
3744
3745     /* record branch length */
3746     oldALength = a->length;
3747
3748     /* reset scratch variables */
3749     for (i=0; i<t->nNodes-1; i++)
3750         {
3751         p = t->allDownPass[i];
3752         p->x = -1;
3753         p->y = NO;
3754         }
3755
3756     /* calculate distance from picked node */
3757     p = a->anc;
3758     p->x = 0;
3759     while (p->isLocked == NO && p->anc != NULL)
3760         {
3761         p->anc->x = p->x + 1;
3762         p = p->anc;
3763         }
3764     for (i=t->nIntNodes-2; i>=0; i--)
3765         {
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;
3769         }
3770
3771     /* mark the free nodes and calculate the total score */
3772     cumulativeProb = 0.0; 
3773     for (i=0; i<t->nNodes-2; i++)
3774         {
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)
3777             {
3778             p->y = YES;
3779             p->d = pow(0.5 * extensionProb, p->anc->x);
3780             cumulativeProb += p->d;
3781             }
3782         else
3783             p->d = 0.0;
3784         }
3785
3786     /* find the target node */
3787     ran = RandomNumber(seed) * cumulativeProb;
3788     x = 0.0;
3789     for (i=0; i<t->nNodes-2; i++)
3790         {
3791         p = t->allDownPass[i];
3792         if (p->y == YES)
3793             {
3794             x += p->d;
3795             if (x > ran)
3796                 break;
3797             }
3798         }
3799     if (i == t->nNodes - 2)
3800         {
3801         abortMove = YES;
3802         return (NO_ERROR);
3803         }
3804
3805     /* record first forward prob */
3806     forwardProb = p->d / cumulativeProb;
3807
3808     /* record partner swap branch */
3809     c = p;
3810     oldCLength = c->length;
3811
3812     /* calculate second forward prob */
3813
3814     /* reset scratch variables */
3815     for (i=0; i<t->nNodes-1; i++)
3816         {
3817         p = t->allDownPass[i];
3818         p->x = -1;
3819         p->y = NO;
3820         }
3821
3822     /* calculate distance from picked node */
3823     p = c->anc;
3824     p->x = 0;
3825     while (p->isLocked == NO && p->anc != NULL)
3826         {
3827         p->anc->x = p->x + 1;
3828         p = p->anc;
3829         }
3830     for (i=t->nIntNodes-1; i>=0; i--)
3831         {
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;
3835         }
3836
3837     /* mark the free nodes and calculate the total score */
3838     cumulativeProb = 0.0; 
3839     for (i=0; i<t->nNodes-2; i++)
3840         {
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)
3843             {
3844             p->y = YES;
3845             p->d = pow(0.5 * extensionProb, p->anc->x);
3846             cumulativeProb += p->d;
3847             }
3848         else
3849             p->d = 0.0;
3850         }
3851
3852     /* now we can calculate second forward prob */
3853     forwardProb += a->d / cumulativeProb;
3854
3855     /* swap subtrees */
3856     if (a->anc->left == a)
3857         a->anc->left = c;
3858     else
3859         a->anc->right = c;
3860     if (c->anc->left == c)
3861         c->anc->left = a;
3862     else
3863         c->anc->right = a;
3864     p = a->anc;
3865     a->anc = c->anc;
3866     c->anc = p;
3867     a->length = a->anc->nodeDepth - a->nodeDepth;
3868     c->length = c->anc->nodeDepth - c->nodeDepth;
3869
3870     /* get down pass sequence */
3871     GetDownPass (t);
3872
3873     /* set tiprobs update flags */
3874     a->upDateTi = YES;
3875     c->upDateTi = YES;
3876
3877     /* set flags for update of cond likes from a->anc and down to root */
3878     p = a->anc;
3879     while (p->anc != NULL)
3880         {
3881         p->upDateCl = YES; 
3882         p = p->anc;
3883         }
3884
3885     /* set flags for update of cond likes from c->anc and down to root */
3886     p = c->anc;
3887     while (p->anc != NULL)
3888         {
3889         p->upDateCl = YES; 
3890         p = p->anc;
3891         }
3892
3893     /* adjust prior ratio for clock tree */
3894     if (LogClockTreePriorRatio(param, chain, &x) == ERROR)
3895         return (ERROR);
3896     (*lnPriorRatio) += x;
3897
3898     /* calculate first backward prob */
3899
3900     /* reset scratch variables */
3901     for (i=0; i<t->nNodes-1; i++)
3902         {
3903         p = t->allDownPass[i];
3904         p->x = -1;
3905         p->y = NO;
3906         }
3907
3908     /* calculate distance from picked node */
3909     p = a->anc;
3910     p->x = 0;
3911     while (p->isLocked == NO && p->anc != NULL)
3912         {
3913         p->anc->x = p->x + 1;
3914         p = p->anc;
3915         }
3916     for (i=t->nIntNodes-1; i>=0; i--)
3917         {
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;
3921         }
3922
3923     /* mark the free nodes and calculate the total score */
3924     cumulativeProb = 0.0; 
3925     for (i=0; i<t->nNodes-2; i++)
3926         {
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)
3929             {
3930             p->y = YES;
3931             p->d = pow(0.5 * extensionProb, p->anc->x);
3932             cumulativeProb += p->d;
3933             }
3934         else
3935             p->d = 0.0;
3936         }
3937
3938     /* calculate first backward prob */
3939     backwardProb = c->d / cumulativeProb;
3940
3941     /* calculate second backward prob */
3942
3943     /* reset scratch variables */
3944     for (i=0; i<t->nNodes-1; i++)
3945         {
3946         p = t->allDownPass[i];
3947         p->x = -1;
3948         p->y = NO;
3949         }
3950
3951     /* calculate distance from picked node */
3952     p = c->anc;
3953     p->x = 0;
3954     while (p->isLocked == NO && p->anc != NULL)
3955         {
3956         p->anc->x = p->x + 1;
3957         p = p->anc;
3958         }
3959     for (i=t->nIntNodes-1; i>=0; i--)
3960         {
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;
3964         }
3965
3966     /* mark the free nodes and calculate the total score */
3967     cumulativeProb = 0.0; 
3968     for (i=0; i<t->nNodes-2; i++)
3969         {
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)
3972             {
3973             p->y = YES;
3974             p->d = pow(0.5 * extensionProb, p->anc->x);
3975             cumulativeProb += p->d;
3976             }
3977         else
3978             p->d = 0.0;
3979         }
3980
3981     /* calculate second backward prob */
3982     backwardProb += a->d / cumulativeProb;
3983
3984     /* now we can calculate proposal ratio */
3985     (*lnProposalRatio) += log (backwardProb / forwardProb);
3986
3987     /* adjust for number of free nodes */
3988     numFreeNew = t->nNodes-2;
3989     if (t->nConstraints > 1)
3990         {
3991         numFreeNew = 0;
3992         for (i=0; i<t->nNodes-2; i++)
3993             {
3994             p = t->allDownPass[i];
3995             if (p->anc->left == p)
3996                 q = p->anc->right;
3997             else
3998                 q = p->anc->left;
3999             if (p->anc->isLocked == NO || q->isLocked == NO)
4000                 numFreeNew++;
4001             }
4002         (*lnProposalRatio) += log(numFreeOld / numFreeNew);
4003         }
4004
4005     /* adjust proposal and prior ratio for relaxed clock models */
4006     for (i=0; i<param->subParams[0]->nSubParams; i++)
4007         {
4008         subParm = param->subParams[0]->subParams[i];
4009         if (subParm->paramType == P_CPPEVENTS)
4010             {
4011             nEvents = subParm->nEvents[2*chain+state[chain]];
4012
4013             /* proposal ratio */
4014             (*lnProposalRatio) += nEvents[a->index] * log (a->length / oldALength);
4015             (*lnProposalRatio) += nEvents[c->index] * log (c->length / oldCLength);
4016
4017             /* prior ratio: no effect because tree length is the same */
4018
4019             /* update effective evolutionary lengths */
4020             if (UpdateCppEvolLengths (subParm, a, chain) == ERROR || UpdateCppEvolLengths (subParm, c, chain) == ERROR)
4021                 {
4022                 abortMove = YES;
4023                 return (NO_ERROR);
4024                 }
4025             }
4026         else if ( subParm->paramType == P_TK02BRANCHRATES ||
4027                  (subParm->paramType == P_MIXEDBRCHRATES && *GetParamIntVals(subParm, chain, state[chain]) == RCL_TK02))
4028             {
4029             if (subParm->paramType == P_TK02BRANCHRATES)
4030                 nu = *GetParamVals (modelSettings[subParm->relParts[0]].tk02var, chain, state[chain]);
4031             else
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]);
4035
4036             /* no proposal ratio effect */
4037
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;
4045             }
4046         else if ( subParm->paramType == P_IGRBRANCHRATES ||
4047                  (subParm->paramType == P_MIXEDBRCHRATES && *GetParamIntVals(subParm, chain, state[chain]) == RCL_IGR))
4048             {
4049             /* get relevant parameters */
4050             if (subParm->paramType == P_IGRBRANCHRATES)
4051                 igrvar = *GetParamVals (modelSettings[subParm->relParts[0]].igrvar, chain, state[chain]);
4052             else
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]);
4056
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;
4064             }
4065         }
4066     
4067     assert (*lnPriorRatio == *lnPriorRatio);
4068
4069     return (NO_ERROR);
4070 }
4071
4072
4073 int Move_ExtTBR (Param *param, int chain, RandLong *seed, MrBFlt *lnPriorRatio, MrBFlt *lnProposalRatio, MrBFlt *mvp)
4074 {
4075     /* Change topology (and branch lengths) using TBR with extension probability. */
4076
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.
4082
4083        This move type has been tested on all combinations of rooted and unrooted,
4084        constrained and unconstrained trees */
4085     
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;
4090     Tree        *t;
4091     ModelParams *mp;
4092
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 */
4096     
4097     (*lnProposalRatio) = (*lnPriorRatio) = 0.0;
4098
4099     /* get tree */
4100     t = GetTree (param, chain, state[chain]);
4101
4102     /* get model params */
4103     mp = &modelParams[param->relParts[0]];
4104     
4105     /* max and min brlen */
4106     if (param->subParams[0]->paramId == BRLENS_UNI)
4107         {
4108         minV = mp->brlensUni[0] > BRLENS_MIN ? mp->brlensUni[0] : BRLENS_MIN;
4109         maxV = mp->brlensUni[1] < BRLENS_MAX ? mp->brlensUni[1] : BRLENS_MAX;
4110         isVPriorExp = NO;
4111         }
4112     else if (param->subParams[0]->paramId == BRLENS_GamDir)
4113         {
4114         minV = BRLENS_MIN;
4115         maxV = BRLENS_MAX;
4116         isVPriorExp = 2;
4117         }
4118     else if (param->subParams[0]->paramId == BRLENS_iGmDir)
4119         {
4120         minV = BRLENS_MIN;
4121         maxV = BRLENS_MAX;
4122         isVPriorExp = 3;
4123         }
4124     else if (param->subParams[0]->paramId == BRLENS_twoExp)
4125         {
4126         minV = BRLENS_MIN;
4127         maxV = BRLENS_MAX;
4128         isVPriorExp = 4;
4129         }
4130     else
4131         {
4132         minV = BRLENS_MIN;
4133         maxV = BRLENS_MAX;
4134         brlensExp = mp->brlensExp;
4135         isVPriorExp = YES;
4136         }
4137
4138     /* Dirichlet or twoExp prior */
4139     if (isVPriorExp > 1)
4140         (*lnPriorRatio) = -LogDirPrior(t, mp, isVPriorExp);
4141
4142     topologyHasChanged = NO;
4143
4144 #   if defined (DEBUG_ExtTBR)
4145     printf ("Before:\n");
4146     ShowNodes (t->root, 2, NO);
4147     getchar();
4148 #   endif
4149     
4150     /* pick an internal branch */
4151     do  {
4152         p = t->intDownPass[(int)(RandomNumber(seed) * (t->nIntNodes-1))];
4153         if (p->anc->left == p)
4154             a = p->anc->right;
4155         else
4156             a = p->anc->left;
4157         i = j = 0;
4158         if (a->isLocked == YES || a->left == NULL)
4159             i++;
4160         if (p->anc->isLocked == YES || p->anc->anc->anc == NULL)
4161             i++;
4162         if (p->left->isLocked == YES || p->left->left == NULL)
4163             j++;
4164         if (p->right->isLocked == YES || p->right->left == NULL)
4165             j++;
4166         } while (i == 2 && j == 2);
4167
4168     /* determine whether to move first step unconditionally in root or in crown */
4169     if (j == 2)
4170         alwaysMoveRoot = YES;
4171     else if (i == 2)
4172         alwaysMoveRoot = NO;
4173     else if (RandomNumber(seed) < 0.5)
4174         alwaysMoveRoot = YES;
4175     else
4176         alwaysMoveRoot = NO;
4177
4178     /* determine any starting constraints */
4179     isCrownStartConstrained = isRootStartConstrained = NO;
4180     if (i >= 1)
4181         isRootStartConstrained = YES;
4182     if (j >= 1)
4183         isCrownStartConstrained = YES;
4184
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 */
4190     v = p;
4191     u = p->anc;
4192
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)
4198         directionLeft = NO;
4199     else if (RandomNumber(seed) < 0.5)
4200         directionLeft = YES;
4201     else
4202         directionLeft = NO;
4203     if (directionLeft == YES)
4204         {
4205         c = v->left;
4206         d = v->right;
4207         }
4208     else
4209         {
4210         c = v->right;
4211         d = v->left;
4212         }
4213
4214     /* cut and reconnect crown part */
4215     c->anc = d;
4216     d->anc = c;
4217     
4218     /* record c length and adjust with multiplier using reflection */
4219     m = c->length;
4220     x = c->length * exp(tuning * (RandomNumber(seed) - 0.5));       /* save the modified dangling branch for later use */
4221     while (x < minV || x > maxV)
4222         {
4223         if (x < minV) x = minV * minV / x;
4224         if (x > maxV) x = maxV * maxV / x;
4225         }
4226     
4227     /* calculate proposal and prior ratio based on length modification */
4228     (*lnProposalRatio) = log (x / m);
4229     if (isVPriorExp == YES)
4230         (*lnPriorRatio) = brlensExp * (m - x);
4231
4232     /* record v length and adjust with multiplier using reflection*/
4233     m = v->length;
4234     v->length *= exp(tuning * (RandomNumber(seed) - 0.5));
4235     while (v->length < minV || v->length > maxV)
4236         {
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;
4241         }
4242     v->upDateTi = YES;
4243
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);
4248
4249     /* mark nodes in root part */
4250     /* also determine direction of move in root part */
4251     if (u->left == v)
4252         a = u->right;
4253     else
4254         a = u->left;
4255     b = u->anc;
4256     if (u->anc->anc == NULL || u->isLocked == YES)
4257         directionUp = YES;
4258     else if (a->left == NULL || a->isLocked == YES)
4259         directionUp = NO;
4260     else if (RandomNumber(seed) < 0.5)
4261         directionUp = YES;
4262     else
4263         directionUp = NO;
4264     if (directionUp == NO)
4265         {
4266         /* switch a and b */
4267         b = a;
4268         a = u->anc;
4269         }
4270
4271     /* cut root part */
4272     if (directionUp == NO)
4273         {
4274         b->anc = a;
4275         if (a->left == u)
4276             a->left = b;
4277         else
4278             a->right = b;
4279         }
4280     else 
4281         {
4282         a->anc = b;
4283         if (b->left == u)
4284             b->left = a;
4285         else
4286             b->right = a;
4287         y = a->length;
4288         a->length = u->length;
4289         u->length = y;
4290         a->upDateTi = YES;
4291         }
4292
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) 
4296         {
4297         m = u->length;
4298         u->length *= exp(tuning * (RandomNumber(seed) - 0.5));
4299         while (u->length < minV || u->length > maxV)
4300             {
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;
4305             }
4306
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);
4311         }
4312     u->upDateTi = YES;
4313
4314     /* move around in root subtree */
4315     for (nRootNodes=0; (alwaysMoveRoot == YES && nRootNodes == 0) || RandomNumber(seed) < extensionProb; nRootNodes++)
4316         {
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;
4322             b = a;
4323             if (RandomNumber(seed) < 0.5)
4324                 a = a->left;
4325             else
4326                 a = a->right;
4327             if (u->isLocked == YES)
4328                 {
4329                 b->isLocked = YES;
4330                 u->isLocked = NO;
4331                 b->lockID = u->lockID;
4332                 u->lockID = 0;
4333                 }
4334             }
4335         else 
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) 
4341                 {
4342                 directionUp = YES; /* switch direction */
4343                 /* find sister of a */
4344                 if (a->left == b) 
4345                     {
4346                     b = a;
4347                     a = a->right;
4348                     }
4349                 else 
4350                     {  
4351                     b = a;
4352                     a = a->left;
4353                     }
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 */
4357                 }   
4358             else 
4359                 {   /* continue down */
4360                 b = a;
4361                 a = a->anc;
4362                 b->upDateCl = YES; 
4363                 if (b->isLocked == YES)
4364                     {
4365                     u->isLocked = YES;
4366                     b->isLocked = NO;
4367                     u->lockID = b->lockID;
4368                     b->lockID = 0;
4369                     }
4370                 }
4371             }
4372         }
4373
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;
4380     if (nRootNodes > 0)
4381         {
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));
4386         }
4387
4388     /* move around in crown subtree */
4389     for (nCrownNodes=0; (alwaysMoveRoot == NO && nCrownNodes == 0) || RandomNumber(seed) < extensionProb; nCrownNodes++)
4390         {
4391         if (c->left == NULL || c->isLocked == YES)
4392             break;  /* can't go further */
4393         topologyHasChanged = YES;
4394         if (RandomNumber(seed) < 0.5) 
4395             {
4396             /* rotate c anticlockwise - prepare pointers for move left */
4397             c->anc = c->left;  /* the root will be in the direction we are heading */
4398             c->left = c->right;
4399             c->right = d;
4400             }
4401         else 
4402             {
4403             /* rotate c clockwise - prepare pointers for move right */
4404             c->anc = c->right;  /* the root will be in the direction we are heading */
4405             c->right = c->left;
4406             c->left = d;  
4407             }
4408         /* OK - let's move!; c->anc points in the right direction
4409         don't forget to move the branch lengths as well */
4410         d = c;
4411         c = c->anc;
4412         d->length = c->length;
4413         d->upDateCl = YES; 
4414         d->upDateTi = YES;
4415         }
4416
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)
4422         {
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));
4427         }
4428
4429     /* combine the subtrees */
4430     c->anc = v;
4431     d->anc = v;
4432     if (directionLeft == YES) 
4433         {
4434         v->left = c;
4435         v->right = d;
4436         }
4437     else 
4438         {
4439         v->left = d;
4440         v->right = c;
4441         }
4442
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)
4448         {
4449         d->length = x;
4450         d->upDateTi = YES;
4451         }
4452     else
4453         {
4454         c->length = x;
4455         c->upDateTi = YES;
4456         }
4457
4458     if (directionUp == YES) 
4459         {
4460         u->anc = b;
4461         if (u->left == v)
4462             u->right = a;
4463         else 
4464             u->left = a;
4465         a->anc = u;
4466         if (b->left == a)
4467             b->left = u;
4468         else
4469             b->right = u;
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) 
4478             {
4479             y = u->length;
4480             u->length = a->length;
4481             a->length = y;
4482             a->upDateTi = YES;
4483             u->upDateTi = NO;   /* u retains its old length */
4484             }
4485         }
4486     else 
4487         {
4488         u->anc = a;
4489         if (u->left == v)
4490             u->right = b;
4491         else
4492             u->left = b;
4493         b->anc = u;
4494         if (a->left == b)
4495             a->left = u;
4496         else
4497             a->right = u;
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) */
4502         if (nRootNodes > 0) 
4503             {
4504             y = u->length;
4505             u->length = b->length;
4506             b->length = y;
4507             b->upDateTi = YES;
4508             }
4509         }
4510         
4511     /* set flags for update of cond likes from v and down to root */
4512     p = v;
4513     while (p->anc != NULL)
4514         {
4515         p->upDateCl = YES;
4516         p = p->anc;
4517         }
4518
4519     /* get down pass sequence if tree topology has changed */
4520     if (topologyHasChanged == YES)
4521         {
4522         GetDownPass (t);
4523         }
4524     
4525     /* Dirichlet or twoExp prior */
4526     if (isVPriorExp > 1)
4527         (*lnPriorRatio) += LogDirPrior(t, mp, isVPriorExp);
4528
4529 #   if defined (DEBUG_ExtTBR)
4530     printf ("After:\n");
4531     ShowNodes (t->root, 2, NO);
4532     getchar();
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);
4539     getchar();
4540 #   endif
4541
4542     return (NO_ERROR);
4543 }
4544
4545
4546 /*----------------------------------------------------------------
4547 |
4548 |   Move_GeneRate_Dir: Change gene rate multiplier using Dirichlet
4549 |      proposal.
4550 |
4551 ----------------------------------------------------------------*/
4552 int Move_GeneRate_Dir (Param *param, int chain, RandLong *seed, MrBFlt *lnPriorRatio, MrBFlt *lnProposalRatio, MrBFlt *mvp)
4553 {
4554     int         i, nRates, isValid;
4555     MrBFlt      alphaPi, *value, *subValue, numSites, *alphaDir, x, y, sum,
4556                 rate_pot, *dirParm, *oldRate, *newRate;
4557
4558     /* allocate memory */
4559     dirParm = (MrBFlt *) SafeCalloc (3*(numTopologies-1), sizeof(MrBFlt));
4560     oldRate = dirParm + numCurrentDivisions;
4561     newRate = dirParm + 2*numCurrentDivisions;
4562
4563     /* get number of rates */
4564     nRates = param->nValues;
4565
4566     /* get pointer to rates and number of uncompressed chars */
4567     value = GetParamVals(param, chain, state[chain]);
4568     subValue = GetParamSubVals(param, chain, state[chain]);
4569
4570     /* get Dirichlet parameters */
4571     alphaDir = subValue + nRates;
4572
4573     /* calculate old ratesum proportions */
4574     numSites = 0.0;
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;
4579     
4580     /* get so called alphaPi parameter */
4581     alphaPi = mvp[0] * nRates;
4582     
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;
4586     
4587     /* get new values */
4588     DirichletRandomVariable (dirParm, newRate, nRates, seed);
4589
4590     /* check new values. we rely on newRate be already normalized  */
4591     while (1)
4592         {
4593         sum = 0.0;
4594         rate_pot = 1.0;
4595         isValid=1;
4596         for (i=0; i<nRates; i++)
4597             {
4598             if (newRate[i] <= DIR_MIN)
4599                 {
4600                 if (newRate[i] < DIR_MIN)
4601                     {
4602                     newRate[i] = DIR_MIN;
4603                     isValid=0;
4604                     }
4605                 rate_pot -= DIR_MIN;
4606                 }
4607             else
4608                 sum += newRate[i];
4609             }
4610         if (isValid==1) break;
4611         for (i=0; i<nRates; i++)
4612             {
4613             if (newRate[i]!=DIR_MIN)
4614                 newRate[i] = rate_pot * newRate[i] / sum;
4615             }
4616         }
4617
4618     /* calculate and copy new rate ratio values back */
4619     for (i=0; i<nRates; i++)
4620         value[i] = newRate[i] * (numSites / subValue[i]);
4621     
4622     /* get proposal ratio */
4623     sum = 0.0;
4624     for (i=0; i<nRates; i++)
4625         sum += newRate[i]*alphaPi;
4626     x = LnGamma(sum);
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]);
4631     sum = 0.0;
4632     for (i=0; i<nRates; i++)
4633         sum += oldRate[i]*alphaPi;
4634     y = LnGamma(sum);
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;
4640
4641     /* get prior ratio */
4642     x = y = 0.0;
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;
4648
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);
4653         
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;
4658
4659     free (dirParm);
4660
4661     return (NO_ERROR);
4662 }
4663
4664
4665 int Move_RateShape_M (Param *param, int chain, RandLong *seed, MrBFlt *lnPriorRatio, MrBFlt *lnProposalRatio, MrBFlt *mvp)
4666 {
4667     /* change gamma/lnorm shape parameter using multiplier */
4668     
4669     int         i, isAPriorExp, isValidA;
4670     MrBFlt      oldA, newA, minA, maxA, alphaExp=0.0, ran, factor, tuning, *rates;
4671     ModelParams *mp;
4672
4673     /* get tuning parameter */
4674     tuning = mvp[0];
4675
4676     /* get model params */
4677     mp = &modelParams[param->relParts[0]];
4678     
4679     /* get minimum and maximum values for alpha */
4680     if (param->paramId == SHAPE_UNI)
4681         {
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;
4688         isAPriorExp = NO;
4689         }
4690     else
4691         {
4692         minA = MIN_SHAPE_PARAM;
4693         maxA = MAX_SHAPE_PARAM;
4694         alphaExp = mp->shapeExp;
4695         isAPriorExp = YES;
4696         }
4697
4698     /* get old value of alpha */
4699     oldA = *GetParamVals(param, chain, state[chain]);
4700
4701     /* change value for alpha */
4702     ran = RandomNumber(seed);
4703     factor = exp(tuning * (ran - 0.5));
4704     newA = oldA * factor;
4705
4706     /* check validity */
4707     isValidA = NO;
4708     do  {
4709         if (newA < minA)
4710             newA = minA * minA / newA;
4711         else if (newA > maxA)
4712             newA = maxA * maxA / newA;
4713         else
4714             isValidA = YES;
4715         } while (isValidA == NO);
4716
4717     /* get proposal ratio */
4718     *lnProposalRatio = log(newA / oldA);
4719     
4720     /* get prior ratio */
4721     if (isAPriorExp == NO)
4722         *lnPriorRatio = 0.0;
4723     else
4724         *lnPriorRatio = -alphaExp * (newA - oldA);
4725     
4726     /* copy new alpha value back */
4727     *GetParamVals(param, chain, state[chain]) = newA;
4728     
4729     /* now, update rate category information */
4730     rates = GetParamSubVals (param, chain, state[chain]);
4731     
4732     if(!strcmp(mp->ratesModel, "LNorm"))
4733         {
4734         if (DiscreteLogNormal (rates, newA, mp->numGammaCats, 1) == ERROR)
4735             return (ERROR);
4736         }
4737     else  /* gamma rate */
4738         {
4739         if (DiscreteGamma (rates, newA, newA, mp->numGammaCats, 0) == ERROR)
4740             return (ERROR);
4741         }
4742
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);
4747         
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;
4752
4753     return (NO_ERROR);
4754 }
4755
4756
4757 int Move_Growth_M (Param *param, int chain, RandLong *seed, MrBFlt *lnPriorRatio, MrBFlt *lnProposalRatio, MrBFlt *mvp)
4758 {
4759     MrBFlt          oldG, newG, lambda, minG, maxG, ran, oldLnPrior, newLnPrior, curTheta;
4760     ModelParams     *mp;
4761     ModelInfo       *m;
4762     Tree            *t;
4763
4764     /* get tuning parameter */
4765     lambda = mvp[0];
4766
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"))
4772         curTheta *= 4.0;
4773     else if (!strcmp(mp->ploidy, "Zlinked"))
4774         curTheta *= 3.0;
4775     else
4776         curTheta *= 2.0;
4777     
4778     /* get minimum and maximum values for growth */
4779     minG = param->min;
4780     maxG = param->max;
4781     
4782     /* get old value of theta */
4783     newG = oldG = *GetParamVals(param, chain, state[chain]);
4784     if (newG < minG)
4785         newG = oldG = minG;
4786
4787     /* change value of growth */
4788     ran = RandomNumber(seed);
4789     newG = oldG * exp (lambda * (ran - 0.5));
4790     
4791     /* check that new value is valid */
4792     while (newG < minG || newG > maxG)
4793         {
4794         if (newG < minG)
4795             newG = minG * minG / newG;
4796         else if (newG > maxG)
4797             newG = maxG * maxG / newG;
4798         }
4799     
4800     /* get proposal ratio */
4801     (*lnProposalRatio) = log (newG / oldG);
4802     
4803     /* get prior ratio */
4804     t = GetTree(modelSettings[param->relParts[0]].brlens,chain,state[chain]);
4805     if (LnCoalescencePriorPr (t, &oldLnPrior, curTheta, oldG) == ERROR)
4806         {
4807         MrBayesPrint ("%s   Problem calculating prior for coalescent process\n", spacer);
4808         return (ERROR);
4809         }
4810     if (LnCoalescencePriorPr (t, &newLnPrior, curTheta, newG) == ERROR)
4811         {
4812         MrBayesPrint ("%s   Problem calculating prior for coalescent process\n", spacer);
4813         return (ERROR);
4814         }
4815     (*lnPriorRatio) = newLnPrior - oldLnPrior + param->LnPriorRatio(newG, oldG, param->priorParams);
4816
4817     /* copy new growth value back */
4818     *GetParamVals(param, chain, state[chain]) = newG;
4819
4820     return (NO_ERROR);
4821 }
4822
4823
4824 int Move_IgrBranchRate (Param *param, int chain, RandLong *seed, MrBFlt *lnPriorRatio, MrBFlt *lnProposalRatio, MrBFlt *mvp)
4825 {
4826     /* move one IGR relaxed clock branch rate using multiplier */
4827
4828     int         i;
4829     MrBFlt      newRate, oldRate, tuning, minR, maxR, igrvar, *igrRate, *brlens;
4830     TreeNode    *p = NULL;
4831     ModelInfo   *m;
4832     Tree        *t;
4833     TreeNode    *q;
4834
4835     /* get the tuning parameter */
4836     tuning = mvp[0];
4837     
4838     /* get the model settings */
4839     m = &modelSettings[param->relParts[0]];
4840
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]);
4844
4845     /* get tree */
4846     t = GetTree (param, chain, state[chain]);
4847
4848     /* get minimum and maximum rate */
4849     minR = RATE_MIN;
4850     maxR = RATE_MAX;
4851     
4852     /* randomly pick a branch */
4853     do  {
4854         i = (int) (RandomNumber(seed) * (t->nNodes -2));
4855         p = t->allDownPass[i];
4856         }
4857     while (p->length < TIME_MIN);  // not ancestral fossil
4858     
4859     /* find new rate using multiplier */
4860     oldRate = igrRate[p->index];
4861     newRate = oldRate * exp ((0.5 - RandomNumber(seed)) * tuning);
4862     
4863     /* reflect if necessary */
4864     while (newRate < minR || newRate > maxR)
4865         {
4866         if (newRate < minR)
4867             newRate = minR * minR / newRate;
4868         if (newRate > maxR)
4869             newRate = maxR * maxR / newRate;
4870         }
4871     
4872     igrRate[p->index] = newRate;
4873
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);
4878
4879     /* calculate proposal ratio */
4880     (*lnProposalRatio) = log (newRate / oldRate);
4881     
4882     /* update branch evolution lengths */
4883     brlens[p->index] = newRate * p->length;
4884
4885     /* set update of transition probability */
4886     p->upDateTi = YES;
4887
4888     /* set update of cond likes down to root */
4889     q = p->anc;
4890     while (q->anc != NULL)
4891         {
4892         q->upDateCl = YES;
4893         q = q->anc;
4894         }
4895
4896     return (NO_ERROR);
4897 }
4898
4899
4900 int Move_IgrBranchRate2 (Param *param, int chain, RandLong *seed, MrBFlt *lnPriorRatio, MrBFlt *lnProposalRatio, MrBFlt *mvp)
4901 {
4902     /* move one IGR relaxed clock branch rate using sliding window */
4903     
4904     int         i;
4905     MrBFlt      newRate, oldRate, window, minR, maxR, igrvar, *igrRate, *brlens;
4906     TreeNode    *p = NULL;
4907     ModelInfo   *m;
4908     Tree        *t;
4909     TreeNode    *q;
4910     
4911     /* get the tuning parameter */
4912     window = mvp[0];
4913     
4914     /* get the model settings */
4915     m = &modelSettings[param->relParts[0]];
4916     
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]);
4920     
4921     /* get tree */
4922     t = GetTree (param, chain, state[chain]);
4923     
4924     /* get minimum and maximum rate */
4925     minR = RATE_MIN;
4926     maxR = RATE_MAX;
4927     
4928     /* randomly pick a branch */
4929     do  {
4930         i = (int) (RandomNumber(seed) * (t->nNodes -2));
4931         p = t->allDownPass[i];
4932         }
4933     while (p->length < TIME_MIN);  // not ancestral fossil
4934     
4935     /* find new rate using multiplier */
4936     oldRate = igrRate[p->index];
4937     newRate = oldRate + window * (RandomNumber(seed) - 0.5);
4938     
4939     /* reflect if necessary */
4940     while (newRate < minR || newRate > maxR)
4941         {
4942         if (newRate < minR)
4943             newRate = 2 * minR - newRate;
4944         if (newRate > maxR)
4945             newRate = 2 * maxR - newRate;
4946         }
4947     
4948     igrRate[p->index] = newRate;
4949     
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);
4954     
4955     /* calculate proposal ratio */
4956     (*lnProposalRatio) = 0.0;
4957     
4958     /* update branch evolution lengths */
4959     brlens[p->index] = newRate * p->length;
4960     
4961     /* set update of transition probability */
4962     p->upDateTi = YES;
4963     
4964     /* set update of cond likes down to root */
4965     q = p->anc;
4966     while (q->anc != NULL)
4967         {
4968         q->upDateCl = YES;
4969         q = q->anc;
4970         }
4971     
4972     return (NO_ERROR);
4973 }
4974
4975
4976 int Move_IgrVar (Param *param, int chain, RandLong *seed, MrBFlt *lnPriorRatio, MrBFlt *lnProposalRatio, MrBFlt *mvp)
4977 {
4978     /* move the variance of the IGR relaxed clock model using multiplier */
4979
4980     int         i, j;
4981     MrBFlt      oldIgrvar, newIgrvar, minIgrvar, maxIgrvar, tuning, *igrRate;
4982     Model       *mp;
4983     TreeNode    *p;
4984     Tree        *t;
4985
4986     /* get tuning parameter */
4987     tuning = mvp[0];
4988
4989     /* get model params */
4990     mp = &modelParams[param->relParts[0]];
4991
4992     /* get the min and max values */
4993     minIgrvar = IGRVAR_MIN;
4994     maxIgrvar = IGRVAR_MAX;
4995     if (!strcmp(mp->igrvarPr,"Uniform"))
4996         {
4997         minIgrvar = (mp->igrvarUni[0] < IGRVAR_MIN) ? IGRVAR_MIN : mp->igrvarUni[0];
4998         maxIgrvar = (mp->igrvarUni[1] > IGRVAR_MAX) ? IGRVAR_MAX : mp->igrvarUni[1];
4999         }
5000     
5001     /* get the igr variance */
5002     oldIgrvar = *GetParamVals (param, chain, state[chain]);
5003
5004     /* set new value */
5005     newIgrvar = oldIgrvar * exp ((0.5 - RandomNumber(seed))*tuning);
5006     
5007     /* reflect if necessary */
5008     while (newIgrvar < minIgrvar || newIgrvar > maxIgrvar)
5009         {
5010         if (newIgrvar < minIgrvar)
5011             newIgrvar = minIgrvar * minIgrvar / newIgrvar;
5012         if (newIgrvar > maxIgrvar)
5013             newIgrvar = maxIgrvar * maxIgrvar / newIgrvar;
5014         }
5015     
5016     /* store new value */
5017     (*GetParamVals (param, chain, state[chain])) = newIgrvar;
5018
5019     /* calculate prior ratio */
5020     for (i=0; i<param->nSubParams; i++)
5021         {
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++)
5025             {
5026             p = t->allDownPass[j];
5027             if (p->length > 0.0)  // not ancestral fossil
5028                 {
5029                 (*lnPriorRatio) -= LnProbGamma (p->length/oldIgrvar, p->length/oldIgrvar, igrRate[p->index]);
5030                 (*lnPriorRatio) += LnProbGamma (p->length/newIgrvar, p->length/newIgrvar, igrRate[p->index]);
5031                 }
5032             }
5033         }
5034
5035     /* take prior on Igrvar into account */
5036     if (!strcmp(mp->igrvarPr,"Exponential"))
5037         (*lnPriorRatio) += mp->igrvarExp * (oldIgrvar - newIgrvar);
5038     
5039     /* calculate proposal ratio */
5040     (*lnProposalRatio) = log (newIgrvar / oldIgrvar);
5041
5042     /* we do not need to update likelihoods */
5043     for (i=0; i<param->nRelParts; i++)
5044         {
5045         modelSettings[param->relParts[i]].upDateCl = NO;
5046         }
5047
5048     return (NO_ERROR);
5049 }
5050
5051
5052 int Move_MixedBranchRate (Param *param, int chain, RandLong *seed, MrBFlt *lnPriorRatio, MrBFlt *lnProposalRatio, MrBFlt *mvp)
5053 {
5054     /* move one relaxed clock branch rate using multiplier */
5055     
5056     int         i, *rclModel=NULL;
5057     MrBFlt      newRate, oldRate, tuning, minR, maxR, mxvar, *mxRate, *brlens;
5058     TreeNode    *p = NULL, *q;
5059     ModelInfo   *m;
5060     Tree        *t;
5061     
5062     /* get the tuning parameter */
5063     tuning = mvp[0];
5064     
5065     /* get the model settings */
5066     m = &modelSettings[param->relParts[0]];
5067     
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]);
5072
5073     /* get tree */
5074     t = GetTree (param, chain, state[chain]);
5075     
5076     /* get minimum and maximum rate */
5077     minR = RATE_MIN;
5078     maxR = RATE_MAX;
5079     
5080     /* randomly pick a length */
5081     do  {
5082         i = (int) (RandomNumber(seed) * (t->nNodes -2));
5083         p = t->allDownPass[i];
5084         }
5085     while (p->length < TIME_MIN);  // not ancestral fossil
5086     
5087     /* find new rate using multiplier */
5088     oldRate = mxRate[p->index];
5089     newRate = oldRate * exp ((0.5 - RandomNumber(seed)) * tuning);
5090     
5091     /* reflect if necessary */
5092     while (newRate < minR || newRate > maxR)
5093         {
5094         if (newRate < minR)
5095             newRate = minR * minR / newRate;
5096         if (newRate > maxR)
5097             newRate = maxR * maxR / newRate;
5098         }
5099     
5100     mxRate[p->index] = newRate;
5101
5102     /* calculate prior ratio */
5103     mxvar = *GetParamVals (m->mixedvar, chain, state[chain]);
5104
5105     if (*rclModel == RCL_TK02)
5106         {
5107         (*lnPriorRatio) += LnRatioTK02LogNormal (mxRate[p->anc->index], mxvar*p->length, newRate, oldRate);
5108         if (p->left != NULL)
5109             {
5110             if (p->left->length > 0.0)
5111                 {
5112                 (*lnPriorRatio) -= LnProbTK02LogNormal (oldRate, mxvar*p->left->length,  mxRate[p->left->index ]);
5113                 (*lnPriorRatio) += LnProbTK02LogNormal (newRate, mxvar*p->left->length,  mxRate[p->left->index ]);
5114                 }
5115             if (p->right->length > 0.0)
5116                 {
5117                 (*lnPriorRatio) -= LnProbTK02LogNormal (oldRate, mxvar*p->right->length, mxRate[p->right->index]);
5118                 (*lnPriorRatio) += LnProbTK02LogNormal (newRate, mxvar*p->right->length, mxRate[p->right->index]);
5119                 }
5120             }
5121         
5122         /* update branch evolution lengths */
5123         brlens[p->index] = p->length * (newRate + mxRate[p->anc->index]) / 2.0;
5124         if (p->left != NULL)
5125             {
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;
5128             }
5129         
5130         /* set update of ti probs */
5131         p->upDateTi = YES;
5132         if (p->left != NULL)
5133             {
5134             p->left ->upDateTi = YES;
5135             p->right->upDateTi = YES;
5136             }
5137         }
5138     else if (*rclModel == RCL_IGR)
5139         {
5140         (*lnPriorRatio) -= LnProbGamma (p->length/mxvar, p->length/mxvar, oldRate);
5141         (*lnPriorRatio) += LnProbGamma (p->length/mxvar, p->length/mxvar, newRate);
5142         
5143         brlens[p->index] = newRate * p->length;
5144
5145         /* set update of transition probability */
5146         p->upDateTi = YES;
5147         }
5148     
5149     /* calculate proposal ratio */
5150     (*lnProposalRatio) = log (newRate / oldRate);
5151     
5152     /* set update of cond likes down to root */
5153     p->upDateCl = YES;
5154     q = p->anc;
5155     while (q->anc != NULL)
5156         {
5157         q->upDateCl = YES;
5158         q = q->anc;
5159         }
5160     
5161     return (NO_ERROR);
5162 }
5163
5164
5165 int Move_MixedVar (Param *param, int chain, RandLong *seed, MrBFlt *lnPriorRatio, MrBFlt *lnProposalRatio, MrBFlt *mvp)
5166 {
5167     /* move the variance of the mixed relaxed clock models using multiplier */
5168
5169     int         i, j, *rclModel=NULL;
5170     MrBFlt      oldVar, newVar, minVar, maxVar, tuning, *igrRate, *tk02Rate;
5171     Model       *mp;
5172     TreeNode    *p;
5173     Tree        *t;
5174     
5175     /* get tuning parameter */
5176     tuning = mvp[0];
5177     
5178     /* get model params */
5179     mp = &modelParams[param->relParts[0]];
5180
5181     /* get the min and max values */
5182     minVar = MIXEDVAR_MIN;
5183     maxVar = MIXEDVAR_MAX;
5184     if (!strcmp(mp->mixedvarPr,"Uniform"))
5185         {
5186         minVar = (mp->mixedvarUni[0] < MIXEDVAR_MIN) ? MIXEDVAR_MIN : mp->mixedvarUni[0];
5187         maxVar = (mp->mixedvarUni[1] > MIXEDVAR_MAX) ? MIXEDVAR_MAX : mp->mixedvarUni[1];
5188         }
5189     
5190     /* get the variance */
5191     oldVar = *GetParamVals (param, chain, state[chain]);
5192     
5193     /* set new value */
5194     newVar = oldVar * exp ((0.5 - RandomNumber(seed))*tuning);
5195     
5196     /* reflect if necessary */
5197     while (newVar < minVar || newVar > maxVar)
5198         {
5199         if (newVar < minVar)
5200             newVar = minVar * minVar / newVar;
5201         if (newVar > maxVar)
5202             newVar = maxVar * maxVar / newVar;
5203         }
5204     
5205     /* store new value */
5206     (*GetParamVals (param, chain, state[chain])) = newVar;
5207     
5208     /* calculate prior ratio */
5209     for (i=0; i<param->nSubParams; i++)
5210         {
5211         rclModel = GetParamIntVals (param->subParams[i], chain, state[chain]);
5212
5213         if (*rclModel == RCL_TK02)
5214             {
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++)
5218                 {
5219                 p = t->allDownPass[j];
5220                 if (p->length > 0.0)  // not ancestral fossil
5221                     {
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]);
5224                     }
5225                 }
5226             }
5227         else if (*rclModel == RCL_IGR)
5228             {
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++)
5232                 {
5233                 p = t->allDownPass[j];
5234                 if (p->length > 0.0)  // not ancestral fossil
5235                     {
5236                     (*lnPriorRatio) -= LnProbGamma (p->length/oldVar, p->length/oldVar, igrRate[p->index]);
5237                     (*lnPriorRatio) += LnProbGamma (p->length/newVar, p->length/newVar, igrRate[p->index]);
5238                     }
5239                 }
5240             }
5241         }
5242
5243     /* take prior on Mixedvar into account */
5244     if (!strcmp(mp->mixedvarPr,"Exponential"))
5245         (*lnPriorRatio) += mp->mixedvarExp * (oldVar - newVar);
5246     
5247     /* calculate proposal ratio */
5248     (*lnProposalRatio) = log (newVar / oldVar);
5249     
5250     /* we do not need to update likelihoods */
5251     for (i=0; i<param->nRelParts; i++)
5252         {
5253         modelSettings[param->relParts[i]].upDateCl = NO;
5254         }
5255     
5256     return (NO_ERROR);
5257 }
5258
5259
5260 int Move_RelaxedClockModel (Param *param, int chain, RandLong *seed, MrBFlt *lnPriorRatio, MrBFlt *lnProposalRatio, MrBFlt *mvp)
5261 {
5262     /* rjMCMC move between TK02 (correlated lognormal) and IGR (independent gamma rate)  
5263      //chi */
5264     
5265     int         i, *rclModel;
5266     MrBFlt      *mxvar, *mxRate, *brlens, ratio, tk02var, igrvar;
5267     Tree        *t;
5268     TreeNode    *p = NULL;
5269     ModelInfo   *m;
5270     Model       *mp;
5271
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]);
5279     
5280     /* get current value of model indicator */
5281     rclModel = GetParamIntVals(param, chain, state[chain]);
5282
5283     /* get tk02/igr var ratio */
5284     ratio = mvp[0];
5285
5286     (*lnPriorRatio) = (*lnProposalRatio) = 0.0;
5287     
5288     /* rjMCMC between models: Pr(TK02) = Pr(IGR) = 1/2 */
5289     /* the current model is TK02, move to IGR */
5290     if ((*rclModel) == RCL_TK02)
5291         {
5292         /* move the var parameter */
5293         tk02var = (*mxvar);
5294      // ratio  *= RandomNumber(seed);
5295         igrvar  = tk02var / ratio;
5296         if (igrvar < IGRVAR_MIN || igrvar > IGRVAR_MAX)
5297             {
5298             abortMove = YES;
5299             return (NO_ERROR);
5300             }
5301         
5302         /* take prior on Mixedvar into account */
5303         if (!strcmp(mp->mixedvarPr,"Exponential"))
5304             (*lnPriorRatio) += mp->mixedvarExp * (tk02var - igrvar);
5305
5306         /* match the rates and change the effective branch lengths */
5307         for (i = 0; i < t->nNodes -2; i++)
5308             {
5309             p = t->allDownPass[i];
5310             if (p->length > 0.0)  // not ancestral fossil
5311                 {
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]);
5314
5315                 brlens[p->index] = mxRate[p->index] * p->length;
5316                 }
5317             }
5318         
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);
5322             
5323         /* switch model */
5324         (*rclModel) = RCL_IGR;
5325         (*mxvar) = igrvar;
5326         }
5327     /* the current model is IGR, move to TK02 */
5328     else
5329         {
5330         /* move the var parameter */
5331         igrvar  = (*mxvar);
5332      // ratio  *= RandomNumber(seed);
5333         tk02var = igrvar * ratio;
5334         if (tk02var < TK02VAR_MIN || tk02var > TK02VAR_MAX)
5335             {
5336             abortMove = YES;
5337             return (NO_ERROR);
5338             }
5339
5340         /* take prior on Mixedvar into account */
5341         if (!strcmp(mp->mixedvarPr,"Exponential"))
5342             (*lnPriorRatio) += mp->mixedvarExp * (igrvar - tk02var);
5343     
5344         /* match the rates and change the effective branch lengths */
5345         for (i = 0; i < t->nNodes -2; i++)
5346             {
5347             p = t->allDownPass[i];
5348             if (p->length > 0.0)  // not ancestral fossil
5349                 {
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]);
5352
5353                 brlens[p->index] = p->length * (mxRate[p->index] + mxRate[p->anc->index]) /2.0;
5354                 }
5355             }
5356             
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);
5360             
5361         /* switch model */
5362         (*rclModel) = RCL_TK02;
5363         (*mxvar) = tk02var;
5364         }
5365
5366     /* since effective branch lengths are updated, we need to update likelihood calculation */
5367     TouchAllTreeNodes(m, chain);
5368
5369     return (NO_ERROR);
5370     MrBayesPrint ("%lf", *seed); /* just because I am tired of seeing the unused parameter error msg */
5371 }
5372
5373
5374 /*----------------------------------------------------------------
5375 |
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):
5379 |
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.
5384 |
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
5393 |
5394 ----------------------------------------------------------------*/
5395 int Move_Local (Param *param, int chain, RandLong *seed, MrBFlt *lnPriorRatio, MrBFlt *lnProposalRatio, MrBFlt *mvp)
5396 {
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;
5401     Tree        *t;
5402     ModelParams *mp;
5403
5404     tuning = mvp[0]; /* Larget & Simon's tuning parameter lambda */
5405     
5406     /* get tree */
5407     t = GetTree (param, chain, state[chain]);
5408
5409     /* get model params */
5410     mp = &modelParams[param->relParts[0]];
5411     
5412     /* max and min brlen */
5413     if (param->subParams[0]->paramId == BRLENS_UNI)
5414         {
5415         minV = mp->brlensUni[0] > BRLENS_MIN ? mp->brlensUni[0] : BRLENS_MIN;
5416         maxV = mp->brlensUni[1];
5417         isVPriorExp = NO;
5418         }
5419     else if (param->subParams[0]->paramId == BRLENS_GamDir)
5420         {
5421         minV = BRLENS_MIN;
5422         maxV = BRLENS_MAX;
5423         isVPriorExp = 2;
5424         }
5425     else if (param->subParams[0]->paramId == BRLENS_iGmDir)
5426         {
5427         minV = BRLENS_MIN;
5428         maxV = BRLENS_MAX;
5429         isVPriorExp = 3;
5430         }
5431     else if (param->subParams[0]->paramId == BRLENS_twoExp)
5432         {
5433         minV = BRLENS_MIN;
5434         maxV = BRLENS_MAX;
5435         isVPriorExp = 4;
5436         }
5437     else
5438         {
5439         minV = BRLENS_MIN;
5440         maxV = BRLENS_MAX;
5441         brlensExp = mp->brlensExp;
5442         isVPriorExp = YES;
5443         }
5444
5445     /* Dirichlet or twoExp prior */
5446     if (isVPriorExp > 1)
5447         (*lnPriorRatio) = -LogDirPrior(t, mp, isVPriorExp);
5448     
5449     topologyHasChanged = NO;
5450
5451 #   if defined (DEBUG_LOCAL)
5452     printf ("Before:\n");
5453     ShowNodes (t->root, 2, NO);
5454     getchar();
5455 #   endif
5456     
5457     /* pick an internal branch */
5458     do
5459         {
5460         v = t->intDownPass[(int)(RandomNumber(seed)*t->nIntNodes)];
5461         } while (v->anc->anc == NULL);
5462         
5463     /* set up pointers for crown part */
5464     if (RandomNumber(seed) < 0.5)
5465         {
5466         c = v->left;
5467         d = v->right;
5468         }
5469     else
5470         {
5471         c = v->right;
5472         d = v->left;
5473         }
5474
5475     /* set up pointers for root part */
5476     u = v->anc;
5477     if (RandomNumber(seed) < 0.5 || (t->isRooted == YES && u->anc->anc == NULL))
5478         {
5479         directionUp = YES;
5480         if (u->left == v)
5481             a = u->right;
5482         else
5483             a = u->left;
5484         b = u->anc;
5485         }
5486     else
5487         {
5488         directionUp = NO;
5489         if (u->left == v)
5490             b = u->right;
5491         else
5492             b = u->left;
5493         a = u->anc;
5494         }
5495
5496     /* store old and new path length as well as old x and y */
5497     oldM = c->length + v->length;
5498     if (directionUp == YES)
5499         {
5500         oldM += a->length;
5501         x = a->length;
5502         }
5503     else
5504         {
5505         oldM += u->length;
5506         x = u->length;
5507         }
5508
5509     y = x + v->length;
5510
5511     /* pick dangly to move */
5512     if (RandomNumber(seed) < 0.5)
5513         moveX = YES;
5514     else
5515         moveX = NO;
5516
5517     /* find new m value */
5518     newM = exp(tuning * (RandomNumber(seed) - 0.5)) * oldM;
5519
5520     /* pick dangly to move and
5521        pick new attachment point */
5522     if (moveX == YES)
5523         {
5524         /* choose new x */
5525
5526         /* first update y */
5527         newY = y * (newM / oldM);
5528
5529         /* find reinsertion point */
5530         if (v->isLocked == YES) 
5531             {
5532             newX = RandomNumber(seed) *  newY;
5533             }
5534         else
5535             {
5536             newX = RandomNumber(seed) * newM;
5537             }
5538         }
5539     else
5540         {
5541         /* choose new y */
5542
5543         /* first update x */
5544         newX = x * (newM / oldM);
5545
5546         /* find reinsertion point */
5547         if (v->isLocked == YES)
5548             {
5549             newY = RandomNumber(seed) * (newM - newX) + newX;
5550             }
5551         else
5552             {
5553             newY = RandomNumber(seed) * newM;
5554             }
5555         }
5556
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);
5562
5563     /* make topology move if necessary and then set branch lengths */
5564     if (newX > newY)
5565         {
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)
5568             {
5569             abortMove = YES;
5570             return NO_ERROR;
5571             }
5572
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 */
5578         if (u->left == v)
5579             u->left = c;
5580         else
5581             u->right = c;
5582         c->anc = u;
5583         if (directionUp == YES)
5584             {
5585             /* place v and d below a */
5586             if (v->left == d)
5587                 v->right = a;
5588             else
5589                 v->left = a;
5590             a->anc = v;
5591             if (u->left == a)
5592                 u->left = v;
5593             else
5594                 u->right = v;
5595             /* v->anc is already u */
5596             /* adjust lengths */
5597             c->length = newM - newX;
5598             v->length = newX - newY;
5599             a->length = newY;
5600             }
5601         else
5602             {
5603             /* place v and d below u */
5604             if (u->isLocked == YES)
5605                 {
5606                 v->isLocked = YES;
5607                 u->isLocked = NO;
5608                 v->lockID = u->lockID;
5609                 u->lockID = 0;
5610                 }
5611             if (v->left == d)
5612                 v->right = u;
5613             else
5614                 v->left = u;
5615             u->anc = v;
5616             v->anc = a;
5617             if (a->left == u)
5618                 a->left = v;
5619             else
5620                 a->right = v;
5621             /* adjust lengths */
5622             c->length = newM - newX;
5623             u->length = newX - newY;
5624             v->length = newY;
5625             }
5626         }
5627     else
5628         {
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)
5631             {
5632             abortMove = YES;
5633             return NO_ERROR;
5634             }
5635
5636         /* topology has not changed */
5637         c->length = newM - newY;
5638         v->length = newY - newX;
5639         if (directionUp == YES)
5640             a->length = newX;
5641         else
5642             u->length = newX;
5643         }
5644                 
5645     /* set update of transition probs */
5646     c->upDateTi = YES;
5647     v->upDateTi = YES;
5648     if (directionUp == YES)
5649         a->upDateTi = YES;
5650     else
5651         u->upDateTi = YES;
5652         
5653     /* set flags for update of cond likes from v and u down to root */
5654     v->upDateCl = YES; 
5655     u->upDateCl = YES; 
5656     if (directionUp == YES)
5657         v = b;
5658     else
5659         v = a;
5660     while (v->anc != NULL)
5661         {
5662         v->upDateCl = YES; 
5663         v = v->anc;
5664         }
5665
5666     /* get downpass sequence if tree topology has changed */
5667     if (topologyHasChanged == YES)
5668         {
5669         GetDownPass (t);
5670         }
5671         
5672     /* Dirichlet or twoExp prior */
5673     if (isVPriorExp > 1)
5674         (*lnPriorRatio) += LogDirPrior(t, mp, isVPriorExp);
5675     
5676 #   if defined (DEBUG_LOCAL)
5677     printf ("After:\n");
5678     ShowNodes (t->root, 2, NO);
5679     getchar();
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);
5684     getchar();
5685 #   endif
5686
5687     return (NO_ERROR);
5688 }
5689
5690
5691 /*----------------------------------------------------------------
5692 |
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):
5696 |
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.
5701 |
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.
5707 |
5708 ----------------------------------------------------------------*/
5709 int Move_LocalClock (Param *param, int chain, RandLong *seed, MrBFlt *lnPriorRatio, MrBFlt *lnProposalRatio, MrBFlt *mvp)
5710 {
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;
5717     Tree            *t;
5718     Param           *subParm;
5719
5720     /* get tree */
5721     t = GetTree (param, chain, state[chain]);
5722
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);
5730             return ERROR;
5731         }
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);
5734             return ERROR;
5735         }
5736     }
5737 #endif
5738
5739     topologyHasChanged = NO;
5740
5741 #   if defined (DEBUG_LOCAL)
5742     printf ("Before:\n");
5743     ShowNodes (t->root, 2, YES);
5744 #   endif
5745
5746     /* set up pointers */
5747     do
5748         {
5749         u = t->intDownPass[(int)(RandomNumber(seed)*(t->nIntNodes-1))];
5750         } while (u->anc->anc == NULL);
5751     v = u->anc;
5752     a = u->left;
5753     b = u->right;
5754     if (v->left == u)
5755         c = v->right;
5756     else
5757         c = v->left;
5758     vIsRoot = NO;
5759     if (v->anc->anc != NULL)
5760         w = v->anc;
5761     else
5762         vIsRoot = YES;
5763     
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);
5770         
5771     /* get distances from root of move (w or v) to nodes a, b, and c */
5772     if (vIsRoot == NO)
5773         h1 = h2 = h3 = v->length;
5774     else
5775         h1 = h2 = h3 = 0.0;
5776     h1 += u->length + a->length;
5777     h2 += u->length + b->length;
5778     h3 += c->length;
5779     h[0] = h1;
5780     h[1] = h2;
5781     h[2] = h3;
5782     
5783     /* we also need the distances between u <-> v and c <-> v to calculate the hastings' term */
5784     distUv = u->length;
5785     distCv = c->length;
5786         
5787     /* sort distances (simply make three comparisons and swap values, if necessary) */
5788     if (h[0] > h[1])
5789         {
5790         tempD = h[1];
5791         h[1] = h[0];
5792         h[0] = tempD;
5793         }
5794     if (h[0] > h[2])
5795         {
5796         tempD = h[2];
5797         h[2] = h[0];
5798         h[0] = tempD;
5799         }
5800     if (h[1] > h[2])
5801         {
5802         tempD = h[2];
5803         h[2] = h[1];
5804         h[1] = tempD;
5805         }
5806         
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)
5811         {
5812         ran = RandomNumber(seed);
5813         if (ran < 0.33333333)
5814             deepestChild = a;
5815         else if (ran > 0.66666666)
5816             deepestChild = b;
5817         else
5818             deepestChild = c;
5819         }
5820     else if (AreDoublesEqual (h1, h2, 0.00000001) == YES && AreDoublesEqual (h1, h3, 0.00000001) == NO && AreDoublesEqual (h2, h3, 0.00000001) == NO)
5821         {
5822         if (h1 < h3)
5823             {
5824             ran = RandomNumber(seed);
5825             if (ran < 0.5)
5826                 deepestChild = a;
5827             else
5828                 deepestChild = b;
5829             }
5830         else
5831             deepestChild = c;
5832         }
5833     else if (AreDoublesEqual (h1, h2, 0.00000001) == NO && AreDoublesEqual (h1, h3, 0.00000001) == YES && AreDoublesEqual (h2, h3, 0.00000001) == NO)
5834         {
5835         if (h1 < h2)
5836             {
5837             ran = RandomNumber(seed);
5838             if (ran < 0.5)
5839                 deepestChild = a;
5840             else
5841                 deepestChild = c;
5842             }
5843         else
5844             deepestChild = b;
5845         }
5846     else if (AreDoublesEqual (h1, h2, 0.00000001) == NO && AreDoublesEqual (h1, h3, 0.00000001) == NO && AreDoublesEqual (h2, h3, 0.00000001) == YES)
5847         {
5848         if (h2 < h1)
5849             {
5850             ran = RandomNumber(seed);
5851             if (ran < 0.5)
5852                 deepestChild = b;
5853             else
5854                 deepestChild = c;
5855             }
5856         else
5857             deepestChild = a;
5858         }
5859     else
5860         {
5861         if (h1 < h2 && h1 < h3)
5862             deepestChild = a;
5863         else if (h2 < h1 && h2 < h3)
5864             deepestChild = b;
5865         else
5866             deepestChild = c;
5867         }
5868     
5869     /* get x and y */
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)
5873         {
5874         /* this proposal is wasted, change nothing */
5875         if (vIsRoot == NO)
5876             {
5877             y = v->length;
5878             x = y + u->length;
5879             }
5880         else
5881             {
5882             y = 0.0;
5883             x = u->length;
5884             }
5885         }
5886     else if (u->isDated == YES && v->isDated == NO)
5887         {
5888         /* we can only change the position of v */
5889         if (vIsRoot == NO)
5890             {
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;
5893             if (x > h[0])
5894                 x = h[0];
5895             y = RandomNumber(seed) * x;
5896             }
5897         else
5898             {
5899             /* v is root: we leave tree height unchanged so we cannot change anything */
5900             x = u->length;
5901             y = 0.0;
5902             }
5903         }
5904     else if (u->isDated == NO && v->isDated == YES)
5905         {
5906         /* we can only change the position of u */
5907         if (vIsRoot == NO)
5908             y = v->length;
5909         else
5910             y = 0.0;
5911         if (u->isLocked == YES)
5912             {
5913             if (h1 > h2)
5914                 {
5915                 x = y + RandomNumber(seed) * (h2 - y);
5916                 }
5917             else
5918                 {
5919                 x = y + RandomNumber(seed) * (h1 - y);
5920                 }
5921             }
5922         else
5923             {
5924             x = y + RandomNumber(seed) * (h[1] - y);
5925             }
5926         }
5927     /* if we reach the statements down here, neither u nor v is dated */
5928     else if (u->isLocked == YES)
5929         {
5930         if (h1 > h2)
5931             {
5932             y = RandomNumber(seed) * h[0];
5933             x = y + RandomNumber(seed) * (h2 - y);
5934             }
5935         else
5936             {
5937             y = RandomNumber(seed) * h[0];
5938             x = y + RandomNumber(seed) * (h1 - y);
5939             }
5940         }
5941     else if (vIsRoot == NO)
5942         {
5943         /* this is the standard variant for nonroot v */
5944         x = RandomNumber(seed) * h[1];
5945         y = RandomNumber(seed) * h[0];
5946         }
5947     else
5948         {
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;
5955           h[0] += diff;
5956           h[1] += diff;
5957           h[2] += diff;*/
5958         /* set y to 0.0 and select new x */
5959         y = 0.0;
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);*/
5965         }
5966         
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)
5971         cSister = YES;
5972     else if (MaximumValue (x, y) < h[0])
5973         {
5974         ran = RandomNumber(seed);
5975         if (ran < 0.33333333)
5976             aSister = YES;
5977         else if (ran > 0.66666666)
5978             bSister = YES;
5979         else 
5980             cSister = YES;
5981         }
5982     else
5983         {
5984         if (deepestChild == a)
5985             aSister = YES;
5986         else if (deepestChild == b)
5987             bSister = YES;
5988         else 
5989             cSister = YES;
5990         }
5991     
5992     /* adjust lengths of nodes u and v */
5993     u->length = MaximumValue (x, y) - MinimumValue (x, y);
5994     v->length = MinimumValue (x, y);
5995     if (vIsRoot == NO)
5996         v->nodeDepth = w->nodeDepth - v->length;
5997     u->nodeDepth = v->nodeDepth - u->length;
5998     
5999     /* adjust pointers and lengths of nodes a, b, and c */
6000     topologyHasChanged = NO;
6001     if (cSister == YES)
6002         {
6003         if (v->left == u)
6004             v->right = c;
6005         else
6006             v->left = c;
6007         u->left = a;
6008         u->right = b;
6009         a->anc = b->anc = u;
6010         c->anc = v;
6011         a->length = u->nodeDepth - a->nodeDepth;
6012         b->length = u->nodeDepth - b->nodeDepth;
6013         c->length = v->nodeDepth - c->nodeDepth;
6014         }
6015     else if (bSister == YES)
6016         {
6017         if (v->left == u)
6018             v->right = b;
6019         else
6020             v->left = b;
6021         u->left = a;
6022         u->right = c;
6023         a->anc = c->anc = u;
6024         b->anc = v;
6025         a->length = u->nodeDepth - a->nodeDepth;
6026         b->length = v->nodeDepth - b->nodeDepth;
6027         c->length = u->nodeDepth - c->nodeDepth;
6028         topologyHasChanged = YES;
6029         }
6030     else if (aSister == YES)
6031         {
6032         if (v->left == u)
6033             v->right = a;
6034         else
6035             v->left = a;
6036         u->left = b;
6037         u->right = c;
6038         b->anc = c->anc = u;
6039         a->anc = v;
6040         a->length = v->nodeDepth - a->nodeDepth;
6041         b->length = u->nodeDepth - b->nodeDepth;
6042         c->length = u->nodeDepth - c->nodeDepth;
6043         topologyHasChanged = YES;
6044         }
6045
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)
6048         {
6049         abortMove = YES;
6050         return NO_ERROR;
6051         }
6052
6053     /* calculate the proposal ratio due to asymmetric topology changes */
6054     if (u->isLocked == NO)
6055         {
6056         if (v->isDated == YES || vIsRoot == YES)
6057             {
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);
6062             }
6063         else
6064             {
6065             /* note that Larget and Simon did not have the correct Hastings ratio
6066                for this case */
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);
6071             }
6072         }
6073
6074     /* set update of transition probs */
6075     a->upDateTi = b->upDateTi = c->upDateTi = u->upDateTi = YES;
6076     if (vIsRoot == NO)
6077         v->upDateTi = YES;
6078
6079     /* set flags for update of cond likes from u down to root */
6080     p = u;
6081     while (p->anc != NULL)
6082         {
6083         p->upDateCl = YES;
6084         p = p->anc;
6085         }
6086         
6087     /* get downpass sequence if tree topology has changed */
6088     if (topologyHasChanged == YES)
6089         GetDownPass (t);
6090         
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++)
6094         {
6095         subParm = param->subParams[0]->subParams[i];
6096         if (subParm->paramType == P_CPPEVENTS)
6097             {
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);
6107             /* prior ratio */
6108             (*lnPriorRatio) += lambda * ((oldTreeLength - newTreeLength)/t->root->left->nodeDepth);
6109             /* update effective evolutionary lengths */
6110             if (v->anc->anc == NULL || v->isDated == YES)
6111                 {
6112                 if (UpdateCppEvolLengths (subParm, v->left, chain) == ERROR ||
6113                     UpdateCppEvolLengths (subParm, v->right, chain) == ERROR)
6114                     {
6115                     abortMove = YES;
6116                     return (NO_ERROR);
6117                     }
6118                 }
6119             else
6120                 {
6121                 if (UpdateCppEvolLengths (subParm, v, chain) == ERROR)
6122                     {
6123                     abortMove = YES;
6124                     return (NO_ERROR);
6125                     }
6126                 }
6127             }
6128         else if ( subParm->paramType == P_TK02BRANCHRATES ||
6129                  (subParm->paramType == P_MIXEDBRCHRATES && *GetParamIntVals(subParm, chain, state[chain]) == RCL_TK02))
6130             {
6131             if (subParm->paramType == P_TK02BRANCHRATES)
6132                 nu = *GetParamVals (modelSettings[subParm->relParts[0]].tk02var, chain, state[chain]);
6133             else
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)
6153                 {
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;
6157                 }
6158             }
6159         else if ( subParm->paramType == P_IGRBRANCHRATES ||
6160                  (subParm->paramType == P_MIXEDBRCHRATES && *GetParamIntVals(subParm, chain, state[chain]) == RCL_IGR))
6161             {
6162             /* to do */
6163             }
6164         }
6165
6166     /* calculate and adjust prior ratio for clock tree */
6167     if (LogClockTreePriorRatio (param, chain, &x) == ERROR)
6168         return (ERROR);
6169     (*lnPriorRatio) += x;
6170     
6171 #   if defined (DEBUG_LOCAL)
6172     printf ("After:\n");
6173     ShowNodes (t->root, 2, YES);
6174     printf ("Has topology changed? %d\n",topologyHasChanged);
6175
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);
6181             return ERROR;
6182         }
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);
6185             return ERROR;
6186         }
6187     }
6188 #endif
6189
6190     return (NO_ERROR);
6191     MrBayesPrint ("%lf", *mvp); /* just because I am tired of seeing the unused parameter error msg */
6192 }
6193
6194
6195 #if 0
6196 /*--------------------------------------------------------------------
6197 |
6198 |   Move_LSPR: Change topology using move based on likelihood scores
6199 |
6200 |--------------------------------------------------------------------*/
6201 int Move_LSPR (Param *param, int chain, RandLong *seed, MrBFlt *lnPriorRatio, MrBFlt *lnProposalRatio, MrBFlt *mvp)
6202 {
6203     /* Change branch lengths and topology (potentially) using SPR-type move 
6204        biased according to likelihood scores. NOT work for constrained trees. */
6205     
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;
6213     Tree        *t;
6214     ModelParams *mp;
6215     ModelInfo   *m = NULL;
6216
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 */
6220
6221     (*lnProposalRatio) = (*lnPriorRatio) = 0.0;
6222
6223     /* get model params and model info */
6224     mp = &modelParams[param->relParts[0]];
6225     m = &modelSettings[param->relParts[0]];
6226     
6227     /* get tree */
6228     t = GetTree (param, chain, state[chain]);
6229
6230     /* max and min brlen */
6231     if (param->subParams[0]->paramId == BRLENS_UNI)
6232         {
6233         minV = mp->brlensUni[0] > BRLENS_MIN ? mp->brlensUni[0] : BRLENS_MIN;
6234         maxV = mp->brlensUni[1];
6235         isVPriorExp = NO;
6236         }
6237     else
6238         {
6239         minV = BRLENS_MIN;
6240         maxV = BRLENS_MAX;
6241         brlensExp = mp->brlensExp;
6242         isVPriorExp = YES;
6243         }
6244
6245 #   if defined (DEBUG_MLSPR)
6246     printf ("Before:\n");
6247     ShowNodes (t->root, 2, YES);
6248     getchar();
6249 #   endif
6250     
6251     /* set topologyHasChanged to NO */
6252     topologyHasChanged = NO;
6253     
6254     /* reset node variables that will be used */
6255     for (i=0; i<t->nNodes; i++)
6256         {
6257         p = t->allDownPass[i];
6258         p->marked = NO;
6259         p->x = 0;
6260         p->d = 0.0;
6261         }
6262
6263     /* pick a random branch */
6264     do
6265         {
6266         p = t->allDownPass[(int)(RandomNumber(seed)*(t->nNodes - 1))];
6267         } while (p->anc->anc == NULL || p->anc->isLocked == YES);
6268         
6269     /* set up pointers for nodes around the picked branch */
6270     v = p;
6271     u = p->anc;
6272     if (u->left == v)
6273         a = u->right;
6274     else
6275         a = u->left;
6276     b = u->anc;
6277     vLeft = v->left;
6278     vRight = vRight;
6279
6280     /* store the branch lengths */
6281     aLength = a->length;
6282     uLength = u->length;
6283     vLength = v->length;
6284     if (v->left != NULL)
6285         {
6286         vLeftLength = v->left->length;
6287         vRightLength = v->right->length;
6288         }
6289     else
6290         vLeftLength = vRightLength = 0.0;
6291
6292     /* get the ML branch lengths */
6293     /* set initial branch lengths */
6294     /* cycle through using Newton Raphson and reoptimization a fixed number of iterations */
6295     for (i=0; i<5; i++)
6296         {
6297         }
6298     
6299     /* get variance of lognormal */
6300     
6301     /* clip tree */
6302     a->anc = b;
6303     if (b->left == u)
6304         b->left = a;
6305     else
6306         b->right = a;
6307
6308     /* count distance to root */
6309     q = b;
6310     nNodes = 0;
6311     while (q->anc != NULL)
6312         {
6313         nNodes++;
6314         q = q->anc;
6315         }
6316     
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)
6321         {
6322         free (tempCondLikes);
6323         free (tempCondLikePtr);
6324         return (ERROR);
6325         }
6326
6327     /* shift pointers over */
6328     q = b;
6329     j = 0;
6330     while (q->anc != NULL)
6331         {
6332         tempCondLikePtr[j] = m->condLike[chain][q->index][q->clSpace];
6333         m->condLike[chain][q->index][q->clSpace] = tempCondLikes + j*m->numChars*m->numModelStates; 
6334         j++;
6335         q = q->anc;
6336         }
6337
6338     /* set length to 0.1 for now; test ML brlen later */
6339     aLength = a->length;
6340     a->length = 0.1;
6341     uLength = u->length;
6342     u->length = 0.1;
6343     vLength = v->length;
6344     v->length = 0.1;
6345
6346     /* get downpass cond likes for the root part */
6347     q = b;
6348     while (q->anc != NULL)
6349         m->condLikeDown (q, division, chain);
6350
6351     /* get final pass cond likes for the root part */
6352     GetLikeFPRootPath (a);
6353
6354     /* get downpass parsimony states for the crown part */
6355     GetParsDP (t, v, chain);
6356
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--)
6360         {
6361         p = t->allDownPass[i];
6362         if (p->anc->marked == YES && p != u)
6363             p->marked = YES;
6364         }
6365
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));
6369     if (!nSitesOfPat)
6370         {
6371         MrBayesPrint ("%s   Problem allocating nSitesOfPat in Move_LSPR\n", spacer);
6372         free (tempCondLikes);
6373         free (tempCondLikePtr);
6374         return (ERROR);
6375         }
6376     for (i=0; i<numCompressedChars; i++)
6377         {
6378         nSitesOfPat[i] = globalNSitesOfPat[i];
6379         for (j=0; j<globalNSitesOfPat[i]; j++)
6380             {
6381             ran = RandomNumber(seed);
6382             if (ran < decreaseProb)
6383                 nSitesOfPat[i]--;
6384             else if (ran > 1.0 - increaseProb)
6385                 nSitesOfPat[i]++;
6386             }
6387         }
6388
6389     /* cycle through the possibilities and record ln likelihood of each in p->d */
6390     minLength = 0.0;
6391     for (i=0; i<t->nNodes; i++)
6392         {
6393         p = t->allDownPass[i];
6394         if (p->marked == NO)
6395             continue;
6396         /* find the parsimony length */
6397         p->d = 0.0;
6398         for (n=0; n<t->nRelParts; n++)
6399             {
6400             division = t->relParts[n];
6401             
6402             /* Find model settings */
6403             m = &modelSettings[division];
6404
6405             nStates = m->numModelStates;
6406             if (m->dataType == STANDARD)
6407                 nStates = 2;
6408             rateMult = GetRate(division, chain);
6409
6410             divFactor = warpFactor + log(nStates-1) - log (3) - log(rateMult);
6411
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;
6416         
6417             length = 0.0;
6418             for (j=0; j<m->numChars; j++)
6419                 {
6420                 x = (pP[j] | pA[j]) & pV[j];
6421                 if (x == 0)
6422                     length += nSitesOfPat[j];
6423                 }
6424             p->d += divFactor * length;
6425             }
6426         if (i == 0)
6427             minLength = p->d;
6428         else if (p->d < minLength)
6429             minLength = p->d;
6430         if (p == a)
6431             curLength = p->d;
6432         }
6433
6434     /* find the sum given the warp factor */
6435     sum = 0.0;
6436     for (i=0; i<t->nNodes; i++)
6437         {
6438         p = t->allDownPass[i];
6439         if (p->marked == YES)
6440             {
6441             p->d = exp (minLength - p->d);
6442             sum += p->d;
6443             }
6444         }
6445
6446     /* generate a random uniform */
6447     ran = RandomNumber(seed);
6448
6449     /* select the appropriate reattachment point */
6450     cumulativeProb = 0.0;
6451     for (i=0; i<t->nNodes; i++)
6452         {
6453         p = t->allDownPass[i];
6454         if (p->marked == YES)
6455             {
6456             c = p;
6457             cumulativeProb += p->d / sum;
6458             if (cumulativeProb > ran)
6459                 break;
6460             }
6461         }
6462     if (c->marked != YES)
6463         {
6464         printf ("Could not select node\n");
6465         getchar();
6466         }
6467
6468     /* calculate the proposal ratio */
6469     if (c == a)
6470         (*lnProposalRatio) = 0.0;
6471     else
6472         (*lnProposalRatio) = c->d - curLength;
6473
6474     /* reattach */
6475     d = c->anc;
6476     c->anc = u;
6477     if (u->left == v)
6478         u->right = c;
6479     else
6480         u->left = c;
6481     if (d->left == c)
6482         d->left = u;
6483     else
6484         d->right = u;
6485     u->anc = d;
6486
6487     /* reassign branch lengths */
6488     if (c != a)
6489         {
6490         topologyHasChanged = YES;
6491         if (RandomNumber(seed) < 0.5)
6492             {
6493             x = u->length;
6494             u->length = a->length;
6495             a->length = x;
6496             }
6497         if (RandomNumber(seed) < 0.5)
6498             {
6499             x = c->length;
6500             c->length = u->length;
6501             u->length = x;
6502             }
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)
6506             {
6507             if (x < minV)
6508                 x = minV * minV / x;
6509             else if (x > maxV)
6510                 x = maxV * maxV / x;
6511             }
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);
6516         c->length = x;
6517         }
6518     
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)
6522         {
6523         if (x < minV)
6524             x = minV * minV / x;
6525         else if (x > maxV)
6526             x = maxV * maxV / x;
6527         }
6528
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);
6533     a->length = x;
6534
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)
6538         {
6539         if (x < minV)
6540             x = minV * minV / x;
6541         else if (x > maxV)
6542             x = maxV * maxV / x;
6543         }
6544
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);
6549     u->length = x;
6550
6551     /* set tiprobs update flags */
6552     a->upDateTi = YES;
6553     u->upDateTi = YES;
6554     c->upDateTi = YES;  /* could be same as a but that does not matter */
6555
6556     /* set flags for update of cond likes from u and down to root */
6557     p = u;
6558     while (p->anc != NULL)
6559         {
6560         p->upDateCl = YES; 
6561         p = p->anc;
6562         }
6563
6564     /* set flags for update of cond likes from b and down to root */
6565     p = b;
6566     while (p->anc != NULL && p->upDateCl == NO)
6567         {
6568         p->upDateCl = YES; 
6569         p = p->anc;
6570         }
6571
6572     /* get down pass sequence if tree topology has changed */
6573     if (topologyHasChanged == YES)
6574         {
6575         GetDownPass (t);
6576         }
6577
6578     free (nSitesOfPat);
6579
6580 #   if defined (DEBUG_MLSPR)
6581     printf ("After:\n");
6582     ShowNodes (t->root, 2, YES);
6583     getchar();
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);
6588     getchar();
6589 #   endif
6590
6591     return (NO_ERROR);
6592 }
6593
6594
6595 /*--------------------------------------------------------------------
6596 |
6597 |  Move_LSPR1: Change topology using move based on likelihood scores
6598 |
6599 |--------------------------------------------------------------------*/
6600 int Move_LSPR1 (Param *param, int chain, RandLong *seed, MrBFlt *lnPriorRatio, MrBFlt *lnProposalRatio, MrBFlt *mvp)
6601 {
6602     /* Change branch lengths and topology (potentially) using SPR-type move 
6603        biased according to likelihood scores. NOT work for constrained trees. */
6604     
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;
6612     Tree        *t;
6613     ModelParams *mp;
6614     ModelInfo   *m = NULL;
6615
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 */
6619
6620     (*lnProposalRatio) = (*lnPriorRatio) = 0.0;
6621
6622     /* get model params and model info */
6623     mp = &modelParams[param->relParts[0]];
6624     m = &modelSettings[param->relParts[0]];
6625     
6626     /* get tree */
6627     t = GetTree (param, chain, state[chain]);
6628
6629     /* max and min brlen */
6630     if (param->subParams[0]->paramId == BRLENS_UNI)
6631         {
6632         minV = mp->brlensUni[0] > BRLENS_MIN ? mp->brlensUni[0] : BRLENS_MIN;
6633         maxV = mp->brlensUni[1];
6634         isVPriorExp = NO;
6635         }
6636     else
6637         {
6638         minV = BRLENS_MIN;
6639         maxV = BRLENS_MAX;
6640         brlensExp = mp->brlensExp;
6641         isVPriorExp = YES;
6642         }
6643
6644 #   if defined (DEBUG_MLSPR)
6645     printf ("Before:\n");
6646     ShowNodes (t->root, 2, YES);
6647     getchar();
6648 #   endif
6649     
6650     /* set topologyHasChanged to NO */
6651     topologyHasChanged = NO;
6652     
6653     /* reset node variables that will be used */
6654     for (i=0; i<t->nNodes; i++)
6655         {
6656         p = t->allDownPass[i];
6657         p->marked = NO;
6658         p->x = 0;
6659         p->d = 0.0;
6660         }
6661
6662     /* pick a random branch */
6663     do
6664         {
6665         p = t->allDownPass[(int)(RandomNumber(seed)*(t->nNodes - 1))];
6666         } while (p->anc->anc == NULL || p->anc->isLocked == YES);
6667         
6668     /* set up pointers for nodes around the picked branch */
6669     v = p;
6670     u = p->anc;
6671     if (u->left == v)
6672         a = u->right;
6673     else
6674         a = u->left;
6675     b = u->anc;
6676     vLeft = v->left;
6677     vRight = vRight;
6678
6679     /* store the branch lengths */
6680     aLength = a->length;
6681     uLength = u->length;
6682     vLength = v->length;
6683     if (v->left != NULL)
6684         {
6685         vLeftLength = v->left->length;
6686         vRightLength = v->right->length;
6687         }
6688     else
6689         vLeftLength = vRightLength = 0.0;
6690
6691     /* save DP cond likes */
6692     /* count distance to root */
6693     q = b;
6694     nNodes = 0;
6695     while (q->anc != NULL)
6696         {
6697         nNodes++;
6698         q = q->anc;
6699         }
6700     
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)
6705         {
6706         free (tempCondLikes);
6707         free (tempCondLikePtr);
6708         return (ERROR);
6709         }
6710
6711     /* shift pointers over */
6712     q = b;
6713     j = 0;
6714     while (q->anc != NULL)
6715         {
6716         tempCondLikePtr[j] = m->condLike[chain][q->index][q->clSpace];
6717         m->condLike[chain][q->index][q->clSpace] = tempCondLikes + j*m->numChars*m->numModelStates; 
6718         j++;
6719         q = q->anc;
6720         }
6721     
6722     /* get cond like uppass up to b */
6723     getLikeUPRootPath (t, b);
6724
6725     /* get ML branch lengths */
6726     NRBrlenOptimizer (t, v, 5, 3);
6727
6728     /* cycle through using Newton Raphson and reoptimization a fixed number of iterations */
6729     for (i=0; i<numIterations; i++)
6730         {
6731         if (v->left != NULL)
6732             {
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);
6738             }
6739         if (u->left == v)
6740             getBaseLikeUpLeft (t, u);
6741         else
6742             getBaseLikeUpRight (t, u);
6743         NewtonRaphsonBrlen (t, v, chain);
6744         if (u->left == v)
6745             getBaseLikeUpRight (t, u);
6746         else
6747             getBaseLikeUpLeft (t, u);
6748         NewtonRaphsonBrlen (t, a->length, chain);
6749         m->CondLikeDown (t, u);
6750         if (b->left == u)
6751             getBaseLikeUpLeft (t, b);
6752         else
6753             getBaseLikeUpRight (t, b);
6754         NewtonRaphsonBrlen (t, u->length, chain);
6755         getLikeUp(t, u);
6756         getLikeUp(t, v);
6757         }
6758     
6759     /* get variance of lognormal for forward move */
6760     f = log (a->length) - log (aLength);
6761     fvar = f*f;
6762     f = log (v->length) - log (vLength);
6763     fvar += f*f;
6764     f = log (u->length) - log (uLength);
6765     fvar += f*f;
6766     if (v->left != NULL)
6767         {
6768         f = log (v->left->length) - log (vLeftLength);
6769         fvar += f*f;
6770         f = log (v->right->length) - log (vRightLength);
6771         fvar += f*f;
6772         fvar /= 5.0;
6773         }
6774     else
6775         fvar /= 3.0;
6776
6777     /* clip tree */
6778     a->anc = b;
6779     if (b->left == u)
6780         b->left = a;
6781     else
6782         b->right = a;
6783
6784     /* get ML branch length for a */
6785     NewtonRaphsonBrlen (t, a, chain, 3);
6786
6787     /* propose new length for a */
6788     f = PointNormal(RandomNumber(seed));
6789     f *= fvar;
6790     f += log (a->length);
6791     a->length = f;
6792
6793     /* get downpass cond likes for the root part */
6794     q = b;
6795     while (q->anc != NULL)
6796         m->condLikeDown (q, division, chain);
6797
6798     /* get uppass cond likes for the root part */
6799     GetLikeUp (t, t->root->left);
6800
6801     /* cycle through the possibilities and record ln likelihood of each in p->d */
6802     for (i=0; i<t->nNodes; i++)
6803         {
6804         p = t->allDownPass[i];
6805         if (p->marked == NO)
6806             continue;
6807         /* attach crown tree here */
6808         pLength = p->length;
6809         /* find ml branch lengths */
6810         NewtonRaphsonBrlens5 (t, v, chain, 5, 3);
6811         /* find score */
6812         m->CondLikeDown (t, v);
6813         m->CondLikeRoot (t, u);
6814         m->Likelihood (t, u, &lnL);
6815         p->d = lnL * warp;
6816         if (i == 0)
6817             maxLnL = p->d;
6818         else if (p->d > maxLnL)
6819             maxLnL = p->d;
6820         if (p == a)
6821             curLnL = p->d;
6822         /* detach crown tree */
6823         /* restore p->length */
6824         p->length = pLength;
6825         }
6826
6827     /* find the sum given the warp factor */
6828     sum = 0.0;
6829     for (i=0; i<t->nNodes; i++)
6830         {
6831         p = t->allDownPass[i];
6832         if (p->marked == YES)
6833             {
6834             p->d = exp (maxLnL - p->d);
6835             sum += p->d;
6836             }
6837         }
6838
6839     /* generate a random uniform */
6840     ran = RandomNumber(seed);
6841
6842     /* select the appropriate reattachment point */
6843     cumulativeProb = 0.0;
6844     for (i=0; i<t->nNodes; i++)
6845         {
6846         p = t->allDownPass[i];
6847         if (p->marked == YES)
6848             {
6849             c = p;
6850             cumulativeProb += p->d / sum;
6851             if (cumulativeProb > ran)
6852                 break;
6853             }
6854         }
6855     if (c->marked != YES)
6856         {
6857         printf ("Could not select node\n");
6858         getchar();
6859         }
6860
6861     /* calculate the proposal ratio based on biased reattachment */
6862     if (c == a)
6863         (*lnProposalRatio) = 0.0;
6864     else
6865         (*lnProposalRatio) = (maxLnL - log(c->d)) - curLnL;
6866
6867     /* reattach */
6868     if (c != a)
6869         topologyHasChanged = YES;
6870     d = c->anc;
6871     c->anc = u;
6872     if (u->left == v)
6873         u->right = c;
6874     else
6875         u->left = c;
6876     if (d->left == c)
6877         d->left = u;
6878     else
6879         d->right = u;
6880     u->anc = d;
6881
6882     /* optimize branch lengths */
6883     NewtonRaphsonBrlens5 (t, v, chain, 5, 5);
6884
6885     /* calculate variance of lognormal for back move */
6886     f = log (a->length) - log (aLength);
6887     fvarNew = f*f;
6888     f = log (v->length) - log (vLength);
6889     fvarNew += f*f;
6890     f = log (u->length) - log (uLength);
6891     fvarNew += f*f;
6892     if (v->left != NULL)
6893         {
6894         f = log (v->left->length) - log (vLeftLength);
6895         fvarNew += f*f;
6896         f = log (v->right->length) - log (vRightLength);
6897         fvarNew += f*f;
6898         fvarNew /= 5.0;
6899         }
6900     else
6901         fvarNew /= 3.0;
6902     
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)
6908         {
6909         v->left->length = fvar * PointNormal(RandomNumber(seed)) + log(v->left->length);
6910         v->right->length = fvar * PointNormal(RandomNumber(seed)) + log(v->right->length);
6911         }
6912
6913     /* calculate proposal ratio for branch lengths */
6914
6915     /* set tiprobs update flags */
6916     a->upDateTi = YES;
6917     u->upDateTi = YES;
6918     c->upDateTi = YES;  /* could be same as a but that does not matter */
6919     v->upDateTi = YES;
6920     if (v->left != NULL)
6921         {
6922         v->left->upDateTi = YES;
6923         v->right->upDateTi = YES;
6924         }
6925
6926     /* set flags for update of cond likes from v and down to root */
6927     q = v;
6928     while (q->anc != NULL)
6929         {
6930         q->upDateCl = YES; 
6931         q = q->anc;
6932         }
6933
6934     /* set flags for update of cond likes from b and down to root */
6935     q = b;
6936     while (q->anc != NULL && q->upDateCl == NO)
6937         {
6938         q->upDateCl = YES; 
6939         q = q->anc;
6940         }
6941
6942     /* get down pass sequence if tree topology has changed */
6943     if (topologyHasChanged == YES)
6944         {
6945         GetDownPass (t);
6946         }
6947
6948     /* restore old conditional likelihoods */
6949
6950 #   if defined (DEBUG_MLSPR)
6951     printf ("After:\n");
6952     ShowNodes (t->root, 2, YES);
6953     getchar();
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);
6958     getchar();
6959 #   endif
6960
6961     return (NO_ERROR);
6962 }
6963 #endif
6964
6965
6966 /* Move_NNI, change topology using NNI move */
6967 int Move_NNI (Param *param, int chain, RandLong *seed, MrBFlt *lnPriorRatio, MrBFlt *lnProposalRatio, MrBFlt *mvp)
6968 {
6969     TreeNode    *p, *u, *v, *a, *b, *c;
6970     Tree        *t;
6971     
6972     (*lnProposalRatio) = (*lnPriorRatio) = 0.0;
6973
6974     /* get tree */
6975     t = GetTree (param, chain, state[chain]);
6976
6977     /* pick an internal branch */
6978     do  {
6979         p = t->intDownPass[(int)(RandomNumber(seed) * t->nIntNodes)];
6980         }
6981     while (p->anc->anc == NULL || p->isLocked == YES);
6982         
6983     /* set up area of rearrangement */
6984     u = p;
6985     v = u->anc;
6986     a = u->left;
6987     b = u->right;
6988     if (v->left == u)
6989         c = v->right;
6990     else
6991         c = v->left;
6992         
6993     /* change topology */
6994     if (RandomNumber(seed) < 0.5)
6995         {
6996         if (v->left == u)
6997             v->right = b;
6998         else
6999             v->left = b;
7000         u->left = a;
7001         u->right = c;
7002         a->anc = c->anc = u;
7003         b->anc = v;
7004         }
7005     else
7006         {
7007         if (v->left == u)
7008             v->right = a;
7009         else
7010             v->left = a;
7011         u->left = b;
7012         u->right = c;
7013         b->anc = c->anc = u;
7014         a->anc = v;
7015         }
7016
7017     /* set update of cond likes */
7018     while (p->anc != NULL)
7019         {
7020         p->upDateCl = YES; 
7021         p = p->anc;
7022         }
7023     
7024     GetDownPass (t);
7025     
7026     return (NO_ERROR);
7027     MrBayesPrint ("%lf", *mvp); /* just because I am tired of seeing the unused parameter error msg */
7028 }
7029
7030
7031 int Move_NNIClock (Param *param, int chain, RandLong *seed, MrBFlt *lnPriorRatio, MrBFlt *lnProposalRatio, MrBFlt *mvp)
7032 {
7033     /* Change clock tree using NNI move */
7034     
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;
7038     Tree        *t;
7039     Param       *subParm;
7040
7041     /* no tuning parameter */
7042
7043     /* make absolutely sure the proposal ratio and prior ratio are reset */
7044     (*lnProposalRatio) = (*lnPriorRatio) = 0.0;
7045
7046     /* get tree */
7047     t = GetTree (param, chain, state[chain]);
7048
7049 #   if defined (DEBUG_NNIClock)
7050     printf ("Before:\n");
7051     ShowNodes (t->root, 2, YES);
7052     getchar();
7053 #   endif
7054     
7055     /* count number of free interior branches */
7056     numFreeOld = 0;
7057     for (i=0; i<t->nIntNodes-1; i++)
7058         {
7059         p = t->intDownPass[i];
7060         if (p->anc->left == p)
7061             q = p->anc->right;
7062         else
7063             q = p->anc->left;
7064         if (p->isLocked == NO && p->nodeDepth >= q->nodeDepth + BRLENS_MIN)
7065             numFreeOld++;
7066         }
7067
7068     /* In extremely constrained trees, it might be impossible to change the tree before nodes have changed in position */
7069     if (numFreeOld == 0)
7070         {
7071         abortMove = YES;
7072         return (NO_ERROR);
7073         }
7074
7075     /* pick an interior branch, around which it is possible to make an NNI */
7076     do  {
7077         p = t->intDownPass[(int)(RandomNumber(seed) * (t->nIntNodes-1))];
7078         if (p->anc->left == p)
7079             q = p->anc->right;
7080         else
7081             q = p->anc->left;
7082         }
7083     while (p->isLocked == YES || p->nodeDepth < q->nodeDepth + BRLENS_MIN);
7084         
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)
7088         a = p->right;
7089     else if (p->right->length < TIME_MIN)
7090         a = p->left;
7091     else if (RandomNumber(seed) < 0.5)
7092         a = p->left;
7093     else
7094         a = p->right;
7095     v = p;
7096     u = p->anc;
7097     if (u->left == v)
7098         c = u->right;
7099     else
7100         c = u->left;
7101
7102     /* record branch lengths */
7103     oldALength = a->length;
7104     oldCLength = c->length;
7105     
7106     /* make topology change */
7107     a->anc = u;
7108     c->anc = v;
7109     if (v->left == a)
7110         v->left = c;
7111     else
7112         v->right = c;
7113     if (u->left == c)
7114         u->left = a;
7115     else
7116         u->right = a;
7117
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);
7123
7124     /* no reassignment of CPP events or branch rates necessary */
7125
7126     /* set tiprobs update flags */
7127     a->upDateTi = YES;
7128     c->upDateTi = YES;
7129
7130     /* set flags for update of cond likes from v and down to root */
7131     p = v;
7132     while (p->anc != NULL)
7133         {
7134         p->upDateCl = YES;
7135         p = p->anc;
7136         }
7137
7138     /* get down pass sequence */
7139     GetDownPass (t);
7140
7141     /* count number of free interior branches after the move */
7142     numFreeNew = 0;
7143     for (i=0; i<t->nIntNodes-1; i++)
7144         {
7145         p = t->intDownPass[i];
7146         if (p->anc->left == p)
7147             q = p->anc->right;
7148         else
7149             q = p->anc->left;
7150         if (p->isLocked == NO && p->nodeDepth >= q->nodeDepth + BRLENS_MIN)
7151             numFreeNew++;
7152         }
7153         
7154     /* get proposal ratio if number of free branches has changed */
7155     if (numFreeNew != numFreeOld)
7156         (*lnProposalRatio) = log((MrBFlt)numFreeOld / (MrBFlt)numFreeNew);
7157
7158     /* calculate and adjust prior ratio for clock trees */
7159     if (LogClockTreePriorRatio(param, chain, &x) == ERROR)
7160         return (ERROR);
7161     (*lnPriorRatio) += x;
7162
7163     /* adjust proposal and prior ratio for relaxed clock models */
7164     for (i=0; i<param->subParams[0]->nSubParams; i++)
7165         {
7166         subParm = param->subParams[0]->subParams[i];
7167         if (subParm->paramType == P_CPPEVENTS)
7168             {
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)
7176                 {
7177                 abortMove = YES;
7178                 return (NO_ERROR);
7179                 }
7180             }
7181         else if ( subParm->paramType == P_TK02BRANCHRATES ||
7182                  (subParm->paramType == P_MIXEDBRCHRATES && *GetParamIntVals(subParm, chain, state[chain]) == RCL_TK02))
7183             {
7184             if (subParm->paramType == P_TK02BRANCHRATES)
7185                 nu = *GetParamVals (modelSettings[subParm->relParts[0]].tk02var, chain, state[chain]);
7186             else
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;
7197             }
7198         else if ( subParm->paramType == P_IGRBRANCHRATES ||
7199                  (subParm->paramType == P_MIXEDBRCHRATES && *GetParamIntVals(subParm, chain, state[chain]) == RCL_IGR))
7200             {
7201             if (subParm->paramType == P_IGRBRANCHRATES)
7202                 igrvar = *GetParamVals (modelSettings[subParm->relParts[0]].igrvar, chain, state[chain]);
7203             else
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;
7214             }
7215         }
7216     
7217 #   if defined (DEBUG_NNIClock)
7218     printf ("After:\n");
7219     ShowNodes (t->root, 2, YES);
7220     getchar();
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);
7224     getchar();
7225 #   endif
7226
7227     return (NO_ERROR);
7228     MrBayesPrint ("%lf", *mvp); /* just because I am tired of seeing the unused parameter error msg */
7229 }
7230
7231
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)
7234 {
7235     int         i, brIndex, moveType;
7236     TreeNode    *p, *u, *v, *a, *b, *c;
7237     Tree        *t;
7238     
7239     (*lnPriorRatio) = (*lnProposalRatio) = 0.0;
7240         
7241     /* get first tree */
7242     t = GetTree (param, chain, state[chain]);
7243
7244     /* pick an internal branch */
7245     do
7246         {
7247         brIndex = (int) (RandomNumber(seed) * t->nIntNodes);
7248         p = t->intDownPass[brIndex];
7249         } while (p->anc->anc == NULL || p->isLocked == YES);
7250         
7251     /* decide on how to change the tree */
7252     if (RandomNumber(seed) < 0.5)
7253         moveType = 0;
7254     else
7255         moveType = 1;
7256     
7257     /* cycle through trees */
7258     for (i=0; i<param->nSubParams; i++)
7259         {
7260         /* get tree */
7261         t = GetTree (param->subParams[i], chain, state[chain]);
7262             
7263         /* find p */
7264         p = t->intDownPass[brIndex];
7265
7266         /* set up area of rearrangement */
7267         u = p;
7268         v = u->anc;
7269         a = u->left;
7270         b = u->right;
7271         if (v->left == u)
7272             c = v->right;
7273         else
7274             c = v->left;
7275
7276         /* change topology */
7277         if (moveType == 0)
7278             {
7279             if (v->left == u)
7280                 v->right = b;
7281             else
7282                 v->left = b;
7283             u->left = a;
7284             u->right = c;
7285             a->anc = c->anc = u;
7286             b->anc = v;
7287             }
7288         else if (moveType == 1)
7289             {
7290             if (v->left == u)
7291                 v->right = a;
7292             else
7293                 v->left = a;
7294             u->left = b;
7295             u->right = c;
7296             b->anc = c->anc = u;
7297             a->anc = v;
7298             }
7299
7300         /* set update of ti probs */
7301         a->upDateTi = YES;
7302         b->upDateTi = YES;
7303         c->upDateTi = YES;
7304         u->upDateTi = YES;
7305         v->upDateTi = YES;
7306         
7307         /* set update of conditional likelihoods */
7308         while (p->anc != NULL)
7309             {
7310             p->upDateCl = YES; 
7311             p = p->anc;
7312             }
7313
7314         /* reset tree downpass sequences */
7315         GetDownPass (t);
7316         
7317         }
7318     
7319     return (NO_ERROR);
7320     MrBayesPrint ("%lf", *mvp); /* just because I am tired of seeing the unused parameter error msg */
7321 }
7322
7323
7324 /*-----------------------------------------------------------------------------------
7325 |
7326 |   Move_NodeSlider: move the position of one node without changing topology
7327 |
7328 -------------------------------------------------------------------------------------*/
7329 int Move_NodeSlider (Param *param, int chain, RandLong *seed, MrBFlt *lnPriorRatio, MrBFlt *lnProposalRatio, MrBFlt *mvp)
7330 {
7331     MrBFlt      tuning, maxV, minV, oldM, newM, brlensPrExp=0.0, newMin, newMax, oldMin, oldMax;
7332     TreeNode    *p, *q;
7333     ModelParams *mp;
7334     Tree        *t;
7335     int isVPriorExp;
7336     
7337     tuning = mvp[0]; /* Larget & Simon's tuning parameter lambda */
7338
7339     mp = &modelParams[param->relParts[0]];
7340
7341     /* max and min brlen (time) */
7342     if (param->paramId == BRLENS_UNI)
7343         {
7344         minV = mp->brlensUni[0] > BRLENS_MIN ? mp->brlensUni[0] : BRLENS_MIN;
7345         maxV = mp->brlensUni[1];
7346         isVPriorExp = NO;
7347         }
7348     else if (param->paramId == BRLENS_GamDir)
7349         {
7350         minV = BRLENS_MIN;
7351         maxV = BRLENS_MAX;
7352         isVPriorExp = 2;
7353         }
7354     else if (param->paramId == BRLENS_iGmDir)
7355         {
7356         minV = BRLENS_MIN;
7357         maxV = BRLENS_MAX;
7358         isVPriorExp = 3;
7359         }
7360     else if (param->paramId == BRLENS_twoExp)
7361         {
7362         minV = BRLENS_MIN;
7363         maxV = BRLENS_MAX;
7364         isVPriorExp = 4;
7365         }
7366     else
7367         {
7368         minV = BRLENS_MIN;
7369         maxV = BRLENS_MAX;
7370         brlensPrExp = mp->brlensExp;
7371         isVPriorExp = YES;
7372         }
7373     
7374     /* get tree */
7375     t = GetTree (param, chain, state[chain]);
7376
7377     /* Dirichlet or twoExp prior */
7378     if (isVPriorExp > 1)
7379         (*lnPriorRatio) = -LogDirPrior(t, mp, isVPriorExp);
7380
7381     /* pick an interior branch */
7382     do  {
7383         p = t->intDownPass[(int)(RandomNumber(seed) * t->nIntNodes)];
7384         }
7385     while (p->anc == NULL || (t->isRooted == YES && p->anc->anc == NULL));
7386
7387     /* pick one descendant branch */
7388     if (RandomNumber(seed) < 0.5)
7389         q = p->left;
7390     else
7391         q = p->right;
7392     
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)
7397         {
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;
7402         }
7403
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;
7409
7410     q->length = newMin + RandomNumber(seed) * (newMax - newMin);
7411     p->length = newM - q->length;
7412
7413     /* the proposal ratio for two sliding windows */
7414     (*lnProposalRatio) = log ((newMax - newMin) / (oldMax - oldMin));
7415     
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);
7422
7423     /* set flags for update of transition probabilities at p and q */
7424     p->upDateTi = YES;
7425     q->upDateTi = YES;
7426     p->upDateCl = YES;
7427
7428     /* set flags for update of cond likes from p->anc and down to root */
7429     while (p->anc->anc != NULL)
7430         {
7431         p = p->anc;
7432         p->upDateCl = YES;
7433         }
7434
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);
7441
7442     return (NO_ERROR);
7443     
7444 }
7445
7446
7447 /*-----------------------------------------------------------------------------------
7448 |
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.
7451 |
7452 -------------------------------------------------------------------------------------*/
7453 int Move_NodeSliderClock (Param *param, int chain, RandLong *seed, MrBFlt *lnPriorRatio, MrBFlt *lnProposalRatio, MrBFlt *mvp)
7454 {
7455     int         i, *nEvents;
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;
7459     TreeNode    *p, *q;
7460     ModelParams *mp;
7461     ModelInfo   *m;
7462     Tree        *t;
7463     Param       *subParm;
7464     Calibration *calibrationPtr;
7465
7466     window = mvp[0]; /* window size */
7467  
7468     m = &modelSettings[param->relParts[0]];
7469     mp = &modelParams[param->relParts[0]];
7470
7471     /* get tree */
7472     t = GetTree (param, chain, state[chain]);
7473
7474     /* get clock rate */
7475     if (m->clockRate == NULL)
7476         clockRate = 1.0;
7477     else
7478         clockRate = *GetParamVals (m->clockRate, chain, state[chain]);
7479
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))
7483         i = t->nNodes - 2;
7484     else
7485         i = t->nNodes - 1;
7486
7487     /* pick a node that can be changed in position */
7488     do  {
7489         p = t->allDownPass[(int)(RandomNumber(seed) * i)];
7490         }
7491     while ((p->left == NULL && p->isDated == NO) ||
7492            (p->left == NULL && p->length < TIME_MIN) ||
7493            (p->isDated == YES && p->calibration->prior == fixed));
7494
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);
7501     getchar();
7502 #endif
7503
7504     /* store values needed later for prior calculation (relaxed clocks) */
7505     oldPLength = p->length;
7506     if (p->left != NULL)
7507         {
7508         oldLeftLength = p->left->length;
7509         oldRightLength = p->right->length;
7510         }
7511     else
7512         oldLeftLength = oldRightLength = 0.0;
7513
7514     /* determine lower and upper bound */
7515     if (p->left == NULL)
7516         minDepth = 0.0;
7517     else      // internal node
7518         {
7519         if (p->left->length > 0.0)
7520             minL = p->left->nodeDepth + BRLENS_MIN;
7521         else  // ancestral fossil
7522             {
7523             assert (p->left->calibration != NULL);
7524             minL = p->left->calibration->min * clockRate;
7525             }
7526         if (p->right->length > 0.0)
7527             minR = p->right->nodeDepth + BRLENS_MIN;
7528         else  // ancestral fossil
7529             {
7530             assert (p->right->calibration != NULL);
7531             minR = p->right->calibration->min * clockRate;
7532             }
7533         if (minL > minR)
7534             minDepth = minL;
7535         else
7536             minDepth = minR;
7537         }
7538     
7539     if (p->anc->anc == NULL)
7540         maxDepth = TREEHEIGHT_MAX;
7541     else
7542         maxDepth = p->anc->nodeDepth - BRLENS_MIN;
7543     if (p->left != NULL && p->left->length < TIME_MIN)
7544         {
7545         assert (p->left->calibration != NULL);
7546         if (maxDepth > p->left->calibration->max * clockRate)
7547             maxDepth = p->left->calibration->max * clockRate;
7548         }
7549     if (p->right != NULL && p->right->length < TIME_MIN)
7550         {
7551         assert (p->right->calibration != NULL);
7552         if (maxDepth > p->right->calibration->max * clockRate)
7553             maxDepth = p->right->calibration->max * clockRate;
7554         }
7555     
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;
7560     else
7561         calibrationPtr = NULL;
7562     if (calibrationPtr != NULL)
7563         {
7564         if (maxDepth > calibrationPtr->max * clockRate)
7565             maxDepth = calibrationPtr->max * clockRate;
7566         if (minDepth < calibrationPtr->min * clockRate)
7567             minDepth = calibrationPtr->min * clockRate;
7568         }
7569
7570     /* abort if impossible */
7571     if (minDepth > maxDepth -BRLENS_MIN)
7572         {
7573         abortMove = YES;
7574         return (NO_ERROR);
7575         }
7576
7577     /* save some reflection time */
7578     if (maxDepth-minDepth < window)
7579         {
7580         window = maxDepth-minDepth;
7581         }
7582
7583     /* pick the new node depth */
7584     oldDepth = p->nodeDepth;
7585     newDepth = oldDepth + (RandomNumber(seed) - 0.5) * window;
7586  
7587     /* reflect the new node depth */
7588     while (newDepth < minDepth || newDepth > maxDepth)
7589         {
7590         if (newDepth < minDepth)
7591             newDepth = 2.0 * minDepth - newDepth;
7592         if (newDepth > maxDepth)
7593             newDepth = 2.0 * maxDepth - newDepth;
7594         }
7595
7596     p->nodeDepth = newDepth;
7597
7598     /* determine new branch lengths around p and set update of transition probabilities */
7599     if (p->left != NULL)
7600         {
7601         if (p->left->length > 0.0) {
7602             p->left->length = p->nodeDepth - p->left->nodeDepth;
7603             p->left->upDateTi = YES;
7604             }
7605         else
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;
7610             }
7611         else
7612             p->right->nodeDepth = p->nodeDepth;
7613         }
7614     if (p->anc->anc != NULL)
7615         {
7616         p->length = p->anc->nodeDepth - p->nodeDepth;
7617         p->upDateTi = YES;
7618         }
7619
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;
7627
7628     /* set flags for update of cond likes from p and down to root */
7629     q = p;
7630     while (q->anc != NULL)
7631         {
7632         q->upDateCl = YES;
7633         q = q->anc;
7634         }
7635
7636     /* calculate proposal ratio */
7637     (*lnProposalRatio) = (*lnPriorRatio) = 0.0;
7638
7639     /* calculate and adjust prior ratio for clock tree */
7640     if (LogClockTreePriorRatio (param, chain, &x) == ERROR)
7641         return (ERROR);
7642     (*lnPriorRatio) += x;
7643
7644     /* adjust proposal and prior ratio for relaxed clock models */
7645     for (i=0; i<param->nSubParams; i++)
7646         {
7647         subParm = param->subParams[i];
7648         if (subParm->paramType == P_CPPEVENTS)
7649             {
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)
7654                 {
7655                 (*lnProposalRatio) += nEvents[p->left->index ] * log (p->left->length  / oldLeftLength);
7656                 (*lnProposalRatio) += nEvents[p->right->index] * log (p->right->length / oldRightLength);
7657                 }
7658             if (p->anc->anc != NULL)
7659                 (*lnProposalRatio) += nEvents[p->index] * log (p->length / oldPLength);
7660
7661             /* prior ratio */
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);
7668
7669             /* update effective evolutionary lengths */
7670             if (UpdateCppEvolLengths (subParm, p, chain) == ERROR)
7671                 {
7672                 abortMove = YES;
7673                 return (NO_ERROR);
7674                 }
7675             }
7676         else if ( subParm->paramType == P_TK02BRANCHRATES ||
7677                  (subParm->paramType == P_MIXEDBRCHRATES && *GetParamIntVals(subParm, chain, state[chain]) == RCL_TK02))
7678             {
7679             if (subParm->paramType == P_TK02BRANCHRATES)
7680                 nu = *GetParamVals (modelSettings[subParm->relParts[0]].tk02var, chain, state[chain]);
7681             else
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]);
7685
7686             /* prior ratio & update effective evolutionary lengths */
7687             if (p->left != NULL)
7688                 {
7689                 if (p->left->length > 0.0)
7690                     {
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;
7694                     }
7695                 if (p->right->length > 0.0)
7696                     {
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;
7700                     }
7701                 }
7702             if (p->anc->anc != NULL)
7703                 {
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;
7707                 }
7708             }
7709         else if ( subParm->paramType == P_IGRBRANCHRATES ||
7710                  (subParm->paramType == P_MIXEDBRCHRATES && *GetParamIntVals(subParm, chain, state[chain]) == RCL_IGR))
7711             {
7712             if (subParm->paramType == P_IGRBRANCHRATES)
7713                 igrvar = *GetParamVals (modelSettings[subParm->relParts[0]].igrvar, chain, state[chain]);
7714             else
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]);
7718                 
7719             /* prior ratio & update effective evolutionary lengths */
7720             if (p->left != NULL)
7721                 {
7722                 if (p->left->length > 0.0)
7723                     {
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;
7727                     }
7728                 if (p->right->length > 0.0)
7729                     {
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;
7733                     }
7734                 }
7735             if (p->anc->anc != NULL)
7736                 {
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;
7740                 }
7741             }
7742         }
7743
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);
7749     getchar();
7750 #endif
7751
7752     return (NO_ERROR);
7753 }
7754
7755
7756 int Move_Nu (Param *param, int chain, RandLong *seed, MrBFlt *lnPriorRatio, MrBFlt *lnProposalRatio, MrBFlt *mvp)
7757 {
7758     /* move the variance of the TK02 relaxed clock lognormal using multiplier */
7759
7760     int         i, j;
7761     MrBFlt      oldNu, newNu, minNu, maxNu, tuning, *tk02Rate;
7762     Model       *mp;
7763     TreeNode    *p;
7764     Tree        *t;
7765
7766     /* get tuning parameter */
7767     tuning = mvp[0];
7768
7769     /* get model params */
7770     mp = &modelParams[param->relParts[0]];
7771
7772     /* get the min and max values */
7773     minNu = TK02VAR_MIN;
7774     maxNu = TK02VAR_MAX;
7775     if (!strcmp(mp->tk02varPr,"Uniform"))
7776         {
7777         minNu = (mp->tk02varUni[0] < TK02VAR_MIN) ? TK02VAR_MIN : mp->tk02varUni[0];
7778         maxNu = (mp->tk02varUni[1] > TK02VAR_MAX) ? TK02VAR_MAX : mp->tk02varUni[1];
7779         }
7780     
7781     /* get the TK02 lognormal variance */
7782     oldNu = *GetParamVals (param, chain, state[chain]);
7783
7784     /* set new value */
7785     newNu = oldNu * exp ((0.5 - RandomNumber(seed))*tuning);
7786     
7787     /* reflect if necessary */
7788     while (newNu < minNu || newNu > maxNu)
7789         {
7790         if (newNu < minNu)
7791             newNu = minNu * minNu / newNu;
7792         if (newNu > maxNu)
7793             newNu = maxNu * maxNu / newNu;
7794         }
7795     
7796     /* store new value */
7797     (*GetParamVals (param, chain, state[chain])) = newNu;
7798
7799     /* calculate prior ratio */
7800     for (i=0; i<param->nSubParams; i++)
7801         {
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++)
7805             {
7806             p = t->allDownPass[j];
7807             if (p->length > 0.0)  // not ancestral fossil
7808                 {
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]);
7811                 }
7812             }
7813         }
7814
7815     /* take prior on nu into account */
7816     if (!strcmp(mp->tk02varPr,"Exponential"))
7817         (*lnPriorRatio) += mp->tk02varExp * (oldNu - newNu);
7818     
7819     /* calculate proposal ratio */
7820     (*lnProposalRatio) = log (newNu / oldNu);
7821
7822     /* we do not need to update likelihoods */
7823     for (i=0; i<param->nRelParts; i++)
7824         {
7825         modelSettings[param->relParts[i]].upDateCl = NO;
7826         }
7827
7828     return (NO_ERROR);
7829 }
7830
7831
7832 /*----------------------------------------------------------------
7833 |
7834 |   Move_Omega: Change the nonysnonymous/synonymous rate ratio
7835 |      Note that this is appropriate when omegavar=equal
7836 |
7837 ----------------------------------------------------------------*/
7838 int Move_Omega (Param *param, int chain, RandLong *seed, MrBFlt *lnPriorRatio, MrBFlt *lnProposalRatio, MrBFlt *mvp)
7839 {
7840     /* change omega using sliding window */
7841     
7842     int         i, isValidO;
7843     MrBFlt      oldO, newO, window, minO, maxO, ran, *alphaDir, oldPropRatio, newPropRatio, x, y;
7844     ModelParams *mp;
7845
7846     /* get size of window, centered on current omega value */
7847     window = mvp[0];
7848     
7849     /* get model params */
7850     mp = &modelParams[param->relParts[0]];
7851     
7852     /* get minimum and maximum values for omega */
7853     minO = OMEGA_MIN;
7854     maxO = OMEGA_MAX;
7855
7856     /* get old value of omega */
7857     oldO = *GetParamVals(param, chain, state[chain]);
7858
7859     /* get Dirichlet parameters */
7860     alphaDir = mp->tRatioDir;
7861
7862     /* change value for omega */
7863     ran = RandomNumber(seed);
7864     if (maxO-minO < window)
7865         {
7866         window = maxO-minO;
7867         }
7868     newO = oldO + window * (ran - 0.5);
7869     
7870     /* check that new value is valid */
7871     isValidO = NO;
7872     do  {
7873         if (newO < minO)
7874             newO = 2.0 * minO - newO;
7875         else if (newO > maxO)
7876             newO = 2.0 * maxO - newO;
7877         else
7878             isValidO = YES;
7879         }
7880     while (isValidO == NO);
7881
7882     /* get proposal ratio */
7883     *lnProposalRatio = 0.0;
7884     
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;
7891     
7892     /* copy new omega value back */
7893     *GetParamVals(param, chain, state[chain]) = newO;
7894
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);
7899
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
7903        the cijk flag. */
7904     for (i=0; i<param->nRelParts; i++)
7905         modelSettings[param->relParts[i]].upDateCijk = YES;
7906
7907     return (NO_ERROR);
7908 }
7909
7910
7911 /*----------------------------------------------------------------
7912 |
7913 |   Move_Omega_M: Change the nonysnonymous/synonymous rate ratio
7914 |      using multiplier. Note that this is appropriate when
7915 |      omegavar=equal
7916 |
7917 ----------------------------------------------------------------*/
7918 int Move_Omega_M (Param *param, int chain, RandLong *seed, MrBFlt *lnPriorRatio, MrBFlt *lnProposalRatio, MrBFlt *mvp)
7919 {
7920     /* change omega using multiplier */
7921     
7922     int         i, isValidO;
7923     MrBFlt      oldO, newO, minO, maxO, tuning, ran, factor, *alphaDir, oldPropRatio, newPropRatio, x, y;
7924     ModelParams *mp;
7925
7926     /* get model params */
7927     mp = &modelParams[param->relParts[0]];
7928
7929     /* get tuning parameter */
7930     tuning = mvp[0];
7931
7932     /* get minimum and maximum values for omega */
7933     minO = OMEGA_MIN;
7934     maxO = OMEGA_MAX;
7935
7936     /* get old value of omega */
7937     oldO = *GetParamVals(param, chain, state[chain]);
7938
7939     /* get Dirichlet parameters */
7940     alphaDir = mp->omegaDir;
7941
7942     /* change value for omega */
7943     ran = RandomNumber(seed);
7944     factor = exp(tuning * (ran - 0.5));
7945     newO = oldO * factor;
7946     
7947     /* check that new value is valid */
7948     isValidO = NO;
7949     do
7950         {
7951         if (newO < minO)
7952             newO = minO * minO / newO;
7953         else if (newO > maxO)
7954             newO = maxO * maxO / newO;
7955         else
7956             isValidO = YES;
7957         } while (isValidO == NO);
7958
7959     /* get proposal ratio */
7960     *lnProposalRatio = log(newO / oldO);
7961     
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;
7968     
7969     /* copy new omega value back */
7970     *GetParamVals(param, chain, state[chain]) = newO;
7971
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);
7976
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
7980        the cijk flag. */
7981     for (i=0; i<param->nRelParts; i++)
7982         modelSettings[param->relParts[i]].upDateCijk = YES;
7983
7984     return (NO_ERROR);
7985 }
7986
7987
7988 /*----------------------------------------------------------------
7989 |
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
7993 |
7994 ----------------------------------------------------------------*/
7995 int Move_OmegaBeta_M (Param *param, int chain, RandLong *seed, MrBFlt *lnPriorRatio, MrBFlt *lnProposalRatio, MrBFlt *mvp)
7996 {
7997     int         i, isValidVal, whichParam;
7998     MrBFlt      oldVal, newVal, minVal, maxVal, *vals, *subVals, tuning, ran, factor;
7999     ModelParams *mp;
8000     
8001     /* do we pick alpha or beta of the Beta distribution to change */
8002     if (RandomNumber(seed) < 0.5)
8003         whichParam = 0;
8004     else
8005         whichParam = 1;
8006
8007     /* get model params */
8008     mp = &modelParams[param->relParts[0]];
8009
8010     /* get tuning parameter */
8011     tuning = mvp[0];
8012
8013     /* get minimum and maximum values for omega */
8014     minVal = 0.05;
8015     maxVal = 100.0;
8016
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];
8021
8022     /* change value for alpha/beta */
8023     ran = RandomNumber(seed);
8024     factor = exp(tuning * (ran - 0.5));
8025     newVal = oldVal * factor;
8026     
8027     /* check that new value is valid */
8028     isValidVal = NO;
8029     do
8030         {
8031         if (newVal < minVal)
8032             newVal = minVal * minVal / newVal;
8033         else if (newVal > maxVal)
8034             newVal = maxVal * maxVal / newVal;
8035         else
8036             isValidVal = YES;
8037         } while (isValidVal == NO);
8038
8039     /* get proposal ratio */
8040     *lnProposalRatio = log(newVal / oldVal);
8041     
8042     /* get prior ratio */
8043     if (!strcmp(mp->m10betapr, "Exponential"))
8044         (*lnPriorRatio) = (log(mp->m10betaExp) - newVal * mp->m10betaExp) - (log(mp->m10betaExp) - oldVal * mp->m10betaExp);
8045     else
8046         (*lnPriorRatio) = 0.0;
8047     
8048     /* copy new omega value back */
8049     subVals[mp->numM10BetaCats + mp->numM10GammaCats + 4 + whichParam] = newVal;
8050     
8051     /* update the omega values */
8052     BetaBreaks (subVals[mp->numM10BetaCats + mp->numM10GammaCats + 4], subVals[mp->numM10BetaCats + mp->numM10GammaCats + 5], &vals[0], mp->numM10BetaCats);
8053
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);
8058
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
8062        the cijk flag. */
8063     for (i=0; i<param->nRelParts; i++)
8064         modelSettings[param->relParts[i]].upDateCijk = YES;
8065
8066     return (NO_ERROR);
8067 }
8068
8069
8070 /*----------------------------------------------------------------
8071 |
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
8075 |
8076 ----------------------------------------------------------------*/
8077 int Move_OmegaGamma_M (Param *param, int chain, RandLong *seed, MrBFlt *lnPriorRatio, MrBFlt *lnProposalRatio, MrBFlt *mvp)
8078 {
8079     int         i, isValidVal, whichParam;
8080     MrBFlt      oldVal, newVal, minVal, maxVal, *vals, *subVals, tuning, ran, factor, quantile95;
8081     ModelParams *mp;
8082     
8083     /* do we pick alpha or beta of the Gamma distribution to change */
8084     if (RandomNumber(seed) < 0.5)
8085         whichParam = 0;
8086     else
8087         whichParam = 1;
8088
8089     /* get model params */
8090     mp = &modelParams[param->relParts[0]];
8091
8092     /* get tuning parameter */
8093     tuning = mvp[0];
8094
8095     /* get minimum and maximum values for omega */
8096     minVal = 0.05;
8097     maxVal = 100.0;
8098
8099     /* get values */
8100     vals = GetParamVals(param, chain, state[chain]);
8101     subVals = GetParamSubVals(param, chain, state[chain]);
8102     oldVal = subVals[mp->numM10BetaCats + mp->numM10GammaCats + 6 + whichParam];
8103
8104     /* change value for alpha/beta */
8105     do
8106         {
8107         ran = RandomNumber(seed);
8108         factor = exp(tuning * (ran - 0.5));
8109         newVal = oldVal * factor;
8110         
8111         /* check that new value is valid */
8112         isValidVal = NO;
8113         do
8114             {
8115             if (newVal < minVal)
8116                 newVal = minVal * minVal / newVal;
8117             else if (newVal > maxVal)
8118                 newVal = maxVal * maxVal / newVal;
8119             else
8120                 isValidVal = YES;
8121             } while (isValidVal == NO);
8122
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]);
8126         else
8127             quantile95 = QuantileGamma (0.95, subVals[mp->numM10BetaCats + mp->numM10GammaCats + 6], newVal);
8128
8129         } while (quantile95 > 100.0);
8130         
8131     /* get proposal ratio */
8132     *lnProposalRatio = log(newVal / oldVal);
8133     
8134     /* get prior ratio */
8135     if (!strcmp(mp->m10gammapr, "Exponential"))
8136         (*lnPriorRatio) = (log(mp->m10gammaExp) - newVal * mp->m10gammaExp) - (log(mp->m10gammaExp) - oldVal * mp->m10gammaExp);
8137     else
8138         (*lnPriorRatio) = 0.0;
8139     
8140     /* copy new value back */
8141     subVals[mp->numM10BetaCats + mp->numM10GammaCats + 6 + whichParam] = newVal;
8142     
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)
8146         return (ERROR);
8147     for (i=0; i<mp->numM10GammaCats; i++)
8148         vals[mp->numM10BetaCats + i] += 1.0;
8149
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);
8154
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
8158        the cijk flag. */
8159     for (i=0; i<param->nRelParts; i++)
8160         modelSettings[param->relParts[i]].upDateCijk = YES;
8161
8162     return (NO_ERROR);
8163 }
8164
8165
8166 int Move_OmegaCat (Param *param, int chain, RandLong *seed, MrBFlt *lnPriorRatio, MrBFlt *lnProposalRatio, MrBFlt *mvp)
8167 {
8168     int         i, localNumCats, numBetaAndGammaCats;
8169     MrBFlt      dirichletParameters[3], *newSubVals, *oldSubVals, *newFreqs, *oldFreqs, *priorParams, sum, alpha, x, y;
8170     ModelParams *mp;
8171
8172     /* get model params */
8173     mp = &modelParams[param->relParts[0]];
8174
8175     /* how many categories are there */
8176     localNumCats = 3;
8177     numBetaAndGammaCats = 0;
8178     if (!strcmp(mp->omegaVar, "M10"))
8179         {
8180         localNumCats = 2;
8181         numBetaAndGammaCats = mp->numM10BetaCats + mp->numM10GammaCats;
8182         }
8183         
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"))
8188         {
8189         newFreqs = newSubVals + numBetaAndGammaCats;
8190         oldFreqs = oldSubVals + numBetaAndGammaCats;
8191         priorParams = newSubVals + (numBetaAndGammaCats + 2);
8192         }
8193     else
8194         {
8195         newFreqs = newSubVals + 0;
8196         oldFreqs = oldSubVals + 0;
8197         priorParams = newFreqs + 3;
8198         }
8199
8200     /* get parameter of proposal mechanism */
8201     alpha = mvp[0];
8202
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;
8206
8207     /* get the new category frequencies */
8208     DirichletRandomVariable (dirichletParameters, newFreqs, localNumCats, seed);
8209     sum = 0.0;
8210     for (i=0; i<localNumCats; i++)
8211         {
8212         if (newFreqs[i] < 0.0001)
8213             newFreqs[i] = 0.0001;
8214         sum += newFreqs[i];
8215         }
8216     for (i=0; i<localNumCats; i++)
8217         newFreqs[i] /= sum;
8218         
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"))
8222         {
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;
8227         }
8228
8229     /* get proposal ratio */
8230     sum = 0.0;
8231     for (i=0; i<localNumCats; i++)
8232         sum += newFreqs[i]*alpha;
8233     x = LnGamma(sum);
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]);
8238     sum = 0.0;
8239     for (i=0; i<localNumCats; i++)
8240         sum += oldFreqs[i]*alpha;
8241     y = LnGamma(sum);
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;
8247
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;
8255         
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);
8260
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;
8264
8265     return (NO_ERROR);
8266 }
8267
8268
8269 /*----------------------------------------------------------------
8270 |
8271 |   Move_OmegaM3: Change the nonysnonymous/synonymous rate ratio
8272 |      of one class of the M3 model
8273 |
8274 ----------------------------------------------------------------*/
8275 int Move_OmegaM3 (Param *param, int chain, RandLong *seed, MrBFlt *lnPriorRatio, MrBFlt *lnProposalRatio, MrBFlt *mvp)
8276 {
8277     int         i, isValidO, whichOmega;
8278     MrBFlt      newO, window, minO, maxO, ran, *value, *oldValue, x, y;
8279
8280     /* get size of window, centered on current omega value */
8281     window = mvp[0];
8282
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);
8287     
8288     /* get minimum and maximum values for omega */
8289     if (whichOmega == 0)
8290         minO = 0.0;
8291     else
8292         minO = value[whichOmega-1];
8293     if (whichOmega == 2)
8294         maxO = OMEGA_MAX;
8295     else
8296         maxO = value[whichOmega+1];
8297
8298     /* change value for omega */
8299     ran = RandomNumber(seed);
8300      if (maxO-minO < window)
8301         {
8302         window = maxO-minO;
8303         }
8304     newO = oldValue[whichOmega] + window * (ran - 0.5);
8305     
8306     /* check that new value is valid */
8307     isValidO = NO;
8308     do
8309         {
8310         if (newO < minO)
8311             newO = 2* minO - newO;
8312         else if (newO > maxO)
8313             newO = 2 * maxO - newO;
8314         else
8315             isValidO = YES;
8316         } while (isValidO == NO);
8317
8318     /* copy new omega value back */
8319     value[whichOmega] = newO;
8320
8321     /* get proposal ratio */
8322     *lnProposalRatio = 0.0;
8323     
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;
8328
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);
8333
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;
8337
8338     return (NO_ERROR);
8339 }
8340
8341
8342 /*----------------------------------------------------------------
8343 |
8344 |   Move_OmegaNeu: Change the nonysnonymous/synonymous rate ratio
8345 |      for neutral sites
8346 |
8347 ----------------------------------------------------------------*/
8348 int Move_OmegaNeu (Param *param, int chain, RandLong *seed, MrBFlt *lnPriorRatio, MrBFlt *lnProposalRatio, MrBFlt *mvp)
8349 {
8350     int         i, isOPriorExp, isValidO;
8351     MrBFlt      oldO, newO, window, minO, maxO, ran, *value, x, y;
8352
8353     /* get size of window, centered on current omega value */
8354     window = mvp[0];
8355
8356     /* get old value of omega */
8357     value = GetParamVals(param, chain, state[chain]);
8358     newO = oldO = value[1];
8359
8360     /* get minimum and maximum values for omega */
8361     minO = value[0];
8362     maxO = value[2];
8363     
8364     /* the only way we would be updating the middle category (omega2) is
8365        if we have an exponential prior on all three omegas */
8366     isOPriorExp = YES;
8367
8368     /* change value for omega */
8369     ran = RandomNumber(seed);
8370     if (maxO-minO < window)
8371         {
8372         window = maxO-minO;
8373         }
8374     newO = oldO + window * (ran - 0.5);
8375     
8376     /* check that new value is valid */
8377     isValidO = NO;
8378     do
8379         {
8380         if (newO < minO)
8381             newO = 2 * minO - newO;
8382         else if (newO > maxO)
8383             newO = 2 * maxO - newO;
8384         else
8385             isValidO = YES;
8386         } while (isValidO == NO);
8387
8388     /* get proposal ratio */
8389     *lnProposalRatio = 0.0;
8390     
8391     /* copy new omega value back */
8392     value[1] = newO;
8393
8394     /* get prior ratio */
8395     if (isOPriorExp == NO)
8396         {
8397         *lnPriorRatio = 0.0;
8398         }
8399     else
8400         {
8401         x = LogOmegaPrior (value[0], newO, value[2]);
8402         y = LogOmegaPrior (value[0], oldO, value[2]);
8403         *lnPriorRatio = x - y;
8404         }
8405
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);
8410
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;
8414
8415     return (NO_ERROR);
8416 }
8417
8418
8419 /*----------------------------------------------------------------
8420 |
8421 |   Move_OmegaPos: Change the nonysnonymous/synonymous rate ratio
8422 |      for positively selected sites
8423 |
8424 ----------------------------------------------------------------*/
8425 int Move_OmegaPos (Param *param, int chain, RandLong *seed, MrBFlt *lnPriorRatio, MrBFlt *lnProposalRatio, MrBFlt *mvp)
8426 {
8427     int         i, isValidO, omegaUni, omegaExp1, omegaExp2;
8428     MrBFlt      oldO, newO, window, minO=0.0, maxO=0.0, ran, *value, x, y;
8429     ModelParams *mp;
8430
8431     /* get size of window, centered on current omega value */
8432     window = mvp[0];
8433
8434     /* get model params */
8435     mp = &modelParams[param->relParts[0]];
8436
8437     /* get old value of omega */
8438     value = GetParamVals(param, chain, state[chain]);
8439     newO = oldO = value[2];
8440     
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)
8444         omegaUni = YES;
8445     else if (param->paramId == OMEGA_BED || param->paramId == OMEGA_BEF || param->paramId == OMEGA_FED || param->paramId == OMEGA_FEF)
8446         omegaExp1 = YES;
8447     else if (param->paramId == OMEGA_ED || param->paramId == OMEGA_EF)
8448         omegaExp2 = YES;
8449         
8450     /* get minimum and maximum values for omega */
8451     if (omegaUni == YES)
8452         {
8453         minO = mp->ny98omega3Uni[0];
8454         if (minO < value[1])
8455             minO = value[1];
8456         maxO = mp->ny98omega3Uni[1];
8457         if (maxO > KAPPA_MAX)
8458             maxO = KAPPA_MAX;
8459         }
8460     else if (omegaExp1 == YES || omegaExp2 == YES)
8461         {
8462         minO = value[1];
8463         maxO = KAPPA_MAX;
8464         }
8465
8466     /* change value for omega */
8467     ran = RandomNumber(seed);
8468     if (maxO-minO < window)
8469         {
8470         window = maxO-minO;
8471         }
8472     newO = oldO + window * (ran - 0.5);
8473     
8474     /* check that new value is valid */
8475     isValidO = NO;
8476     do
8477         {
8478         if (newO < minO)
8479             newO = 2* minO - newO;
8480         else if (newO > maxO)
8481             newO = 2 * maxO - newO;
8482         else
8483             isValidO = YES;
8484         } while (isValidO == NO);
8485
8486     /* get proposal ratio */
8487     *lnProposalRatio = 0.0;
8488     
8489     /* copy new omega value back */
8490     value[2] = newO;
8491
8492     /* get prior ratio (part 2) */
8493     if (omegaUni == YES)
8494         {
8495         *lnPriorRatio = 0.0;
8496         }
8497     else if (omegaExp1 == YES)
8498         {
8499         *lnPriorRatio = mp->ny98omega3Exp * (oldO - newO);
8500         }
8501     else if (omegaExp2 == YES)
8502         {
8503         x = LogOmegaPrior (value[0], value[1], newO);
8504         y = LogOmegaPrior (value[0], value[1], oldO);
8505         *lnPriorRatio = x - y;
8506         }
8507
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);
8512
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;
8516
8517     return (NO_ERROR);
8518 }
8519
8520
8521 /*----------------------------------------------------------------
8522 |
8523 |   Move_OmegaPur: Change the nonysnonymous/synonymous rate ratio
8524 |      for purifying selection sites
8525 |
8526 ----------------------------------------------------------------*/
8527 int Move_OmegaPur (Param *param, int chain, RandLong *seed, MrBFlt *lnPriorRatio, MrBFlt *lnProposalRatio, MrBFlt *mvp)
8528 {
8529     int         i, isOPriorExp, isValidO;
8530     MrBFlt      oldO, newO, window, minO, maxO, ran, *value, x, y;
8531
8532     /* get size of window, centered on current omega value */
8533     window = mvp[0];
8534
8535     /* get old value of omega */
8536     value = GetParamVals(param, chain, state[chain]);
8537     newO = oldO = value[0];
8538     
8539     /* get minimum and maximum values for omega */
8540     minO = 0.0;
8541     maxO = value[1];
8542     
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) 
8546         isOPriorExp = NO;
8547     else
8548         isOPriorExp = YES;
8549
8550     /* change value for omega */
8551     ran = RandomNumber(seed);
8552     if (maxO-minO < window)
8553         {
8554         window = maxO-minO;
8555         }
8556     newO = oldO + window * (ran - 0.5);
8557     
8558     /* check that new value is valid */
8559     isValidO = NO;
8560     do
8561         {
8562         if (newO < minO)
8563             newO = 2* minO - newO;
8564         else if (newO > maxO)
8565             newO = 2 * maxO - newO;
8566         else
8567             isValidO = YES;
8568         } while (isValidO == NO);
8569
8570     /* get proposal ratio */
8571     *lnProposalRatio = 0.0;
8572     
8573     /* copy new omega value back */
8574     value[0] = newO;
8575
8576     /* get prior ratio (part 2) */
8577     if (isOPriorExp == NO)
8578         {
8579         *lnPriorRatio = 0.0;
8580         }
8581     else
8582         {
8583         x = LogOmegaPrior (newO, value[1], value[2]);
8584         y = LogOmegaPrior (oldO, value[1], value[2]);
8585         *lnPriorRatio = x - y;
8586         }
8587
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);
8592
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;
8596
8597     return (NO_ERROR);
8598 }
8599
8600
8601 /*----------------------------------------------------------------
8602 |
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.
8609 |
8610 |      Programmed by FR 2004-10-23--
8611 |
8612 ----------------------------------------------------------------*/
8613 int Move_ParsEraser1 (Param *param, int chain, RandLong *seed, MrBFlt *lnPriorRatio, MrBFlt *lnProposalRatio, MrBFlt *mvp)
8614 {
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;
8620     TreeNode    *p=NULL;
8621     Tree        *t, *subtree, *subtree1, memTree[2];
8622     ModelParams *mp;
8623     ModelInfo   *m;
8624     TreeInfo    tInfo;
8625
8626     /* set pointers to NULL */
8627     subtree = subtree1 = NULL;
8628     brlensCur = NULL;
8629     for (i=0; i<2; i++)
8630         {
8631         memTree[i].allDownPass = NULL;
8632         memTree[i].intDownPass = NULL;
8633         memTree[i].nodes = NULL;
8634         }
8635     tInfo.leaf = NULL;
8636
8637     /* Set alpha Pi for Dirichlet p generator */
8638     alphaPi = mvp[0];
8639     alphaPi = 0.05;
8640     
8641     /* Set the parsimony warp factor */
8642     warp = mvp[1];
8643     warp = 0.2;
8644     
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
8651                   etc               */  
8652     nSubTerminals = (int) (RandomNumber(seed) * 4) + 4;
8653     nSubTerminals = 7;
8654
8655     /* initialize log prior and log proposal probabilities */
8656     *lnPriorRatio = *lnProposalRatio = 0.0;
8657     
8658     /* get tree */
8659     t = GetTree (param, chain, state[chain]);
8660
8661     /* get model params */
8662     mp = &modelParams[param->relParts[0]];
8663     
8664     /* max and min brlen */
8665     if (param->subParams[0]->paramId == BRLENS_UNI)
8666         {
8667         minV = mp->brlensUni[0] > BRLENS_MIN ? mp->brlensUni[0] : BRLENS_MIN;
8668         maxV = mp->brlensUni[1];
8669         isVPriorExp = NO;
8670         }
8671     else
8672         {
8673         minV = BRLENS_MIN;
8674         maxV = BRLENS_MAX;
8675         brlensExp = mp->brlensExp;
8676         isVPriorExp = YES;
8677         }
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)));
8680
8681     /* allocate some memory for this move */
8682     brlensCur = (MrBFlt *) SafeMalloc (8 * nSubTerminals * sizeof (MrBFlt));
8683     if (!brlensCur)
8684         {
8685         MrBayesPrint ("%s   ERROR: Could not allocate brlensCur\n", spacer);
8686         goto errorExit;
8687         }
8688     brlensNew = brlensCur + 2*nSubTerminals;
8689     parslensCur = brlensCur + 4 * nSubTerminals;
8690     parslensNew = brlensCur + 6 * nSubTerminals;
8691
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)
8699         {
8700         MrBayesPrint ("%s   ERROR: Could not allocate subtree\n", spacer);
8701         goto errorExit;
8702         }
8703
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)
8711         {
8712         MrBayesPrint ("%s   ERROR: Could not allocate subtree1\n", spacer);
8713         goto errorExit;
8714         }
8715
8716     tInfo.leaf = (TreeNode **) SafeCalloc (t->nNodes, sizeof(TreeNode *));
8717     if (!tInfo.leaf)
8718         {
8719         MrBayesPrint ("%s   ERROR: Could not allocate tInfo.leaf\n", spacer);
8720         goto errorExit;
8721         }
8722     tInfo.vertex = tInfo.leaf + t->nNodes - t->nIntNodes;
8723
8724     /* Select a random embedded subtree with nSubTerminals terminals */
8725     if (GetRandomEmbeddedSubtree (t, nSubTerminals, seed, &nEmbeddedTrees) == ERROR)
8726         {
8727         MrBayesPrint ("%s   ERROR: Could not get subtree\n", spacer);
8728         goto errorExit;
8729         }
8730
8731     /* Set update flags (We'd better do it before the marked nodes disappear) */
8732     for (i=0; i<t->nIntNodes; i++)
8733         {
8734         p = t->intDownPass[i];
8735         if (p->marked == YES)
8736             {
8737             p->upDateCl = YES; 
8738             p->upDateTi = YES;
8739             }
8740         else if (p->left->upDateCl == YES || p->right->upDateCl == YES)
8741                 p->upDateCl = YES; 
8742         }
8743
8744     /* Fill in subtrees */
8745     CopyTreeToSubtree (t, subtree); 
8746     CopyTreeToSubtree (t, subtree1);
8747
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++)
8751         {
8752         p = t->intDownPass[i];
8753         if (p->marked == YES && p->anc->marked == NO)
8754             break;
8755         }
8756     GetParsimonySubtreeRootstate (t, p->anc, chain);
8757
8758     /* Get parsimony length of current tree */
8759     curLength = GetParsimonyLength (subtree, chain);
8760     
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;
8765
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;
8770     tInfo.warp = warp;
8771     ExhaustiveParsimonySearch (subtree, chain, &tInfo);
8772         
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); */
8778     /* getchar(); */
8779
8780     /* Get length of that tree */
8781
8782     newLength = GetParsimonyLength (subtree1, chain);
8783
8784     /* Get the parsimony branch lengths of the new subtree */
8785     GetParsimonyBrlens (subtree1, chain, parslensNew);
8786
8787     /* Find the maximum length of a branch */
8788     maxLen = 0.0;
8789     for (i=0; i<t->nRelParts; i++)
8790         {
8791         j = t->relParts[i];
8792         m = &modelSettings[j];
8793         maxLen += m->numUncompressedChars;
8794         }
8795     
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++)
8801         {
8802         minLenCur += parslensCur[i];
8803         minLenNew += parslensNew[i];
8804         }
8805     for (i=0; i<subtree1->nNodes-1; i++)
8806         {
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)
8813             {
8814             abortMove = YES;
8815             return NO_ERROR;
8816             }
8817
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));
8827         }
8828
8829     /* Store the new Markov branch lengths */
8830     for (i=0; i<subtree1->nNodes-1; i++)
8831         brlensNew[i] = subtree1->allDownPass[i]->length;
8832
8833     /* Calculate the proposal ratio */
8834     (*lnProposalRatio) = lnJacobian + lnRandomRatio + log (warp/3.0) * (curLength - newLength) + log (1.0-warp) * (newLength - curLength);
8835
8836     /* Calculate the prior ratio */
8837     if (isVPriorExp == YES)
8838         {
8839         newM = oldM = 0.0;
8840         for (i=0; i<subtree->nNodes-1; i++)
8841             {
8842             oldM += brlensCur[i];
8843             newM += brlensNew[i];
8844             }
8845         (*lnPriorRatio) += brlensExp * (oldM - newM);
8846         }
8847
8848     /* Copy subtree into tree */
8849     CopySubtreeToTree (subtree1, t);
8850     /* ShowNodes (subtree1->root, 0, NO); */
8851     /* ShowNodes (t->root, 0, NO); */
8852
8853     /* Update node sequences */
8854     GetDownPass (t);
8855     
8856     /* correct for difference in number of embedded subtrees */
8857     if (GetRandomEmbeddedSubtree (t, nSubTerminals, seed, &i) == ERROR)
8858         {
8859         MrBayesPrint ("%s   Could not count number of subtrees in Move_ParsEraser1\n", spacer);
8860         goto errorExit;
8861         }
8862     if (i != nEmbeddedTrees)
8863         (*lnProposalRatio) += log ((MrBFlt) nEmbeddedTrees / (MrBFlt) i);
8864
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);
8872     free (brlensCur);
8873     free (tInfo.leaf);
8874
8875     return (NO_ERROR);
8876
8877 errorExit:
8878
8879     free (subtree->allDownPass);
8880     free (subtree->intDownPass);
8881     free (subtree->nodes);
8882     free (subtree1->allDownPass);
8883     free (subtree1->intDownPass);
8884     free (subtree1->nodes);
8885     free (brlensCur);
8886     free (tInfo.leaf);
8887
8888     return (ERROR);
8889 }
8890
8891
8892 int Move_ParsSPR (Param *param, int chain, RandLong *seed, MrBFlt *lnPriorRatio, MrBFlt *lnProposalRatio, MrBFlt *mvp)
8893 {
8894     /* Change topology (and branch lengths) using SPR (asymmetric) biased according to parsimony scores. */
8895
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;
8903     Tree        *t;
8904     ModelParams *mp;
8905     ModelInfo   *m = NULL;
8906
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 */
8911
8912     (*lnProposalRatio) = (*lnPriorRatio) = 0.0;
8913
8914     /* get model params and model info */
8915     mp = &modelParams[param->relParts[0]];
8916     m = &modelSettings[param->relParts[0]];
8917     
8918     /* get tree */
8919     t = GetTree (param, chain, state[chain]);
8920
8921     /* max and min brlen */
8922     if (param->subParams[0]->paramId == BRLENS_UNI)
8923         {
8924         minV = mp->brlensUni[0] > BRLENS_MIN ? mp->brlensUni[0] : BRLENS_MIN;
8925         maxV = mp->brlensUni[1] < BRLENS_MAX ? mp->brlensUni[1] : BRLENS_MAX;
8926         isVPriorExp = NO;
8927         }
8928     else if (param->subParams[0]->paramId == BRLENS_GamDir)
8929         {
8930         minV = BRLENS_MIN;
8931         maxV = BRLENS_MAX;
8932         isVPriorExp = 2;
8933         }
8934     else if (param->subParams[0]->paramId == BRLENS_iGmDir)
8935         {
8936         minV = BRLENS_MIN;
8937         maxV = BRLENS_MAX;
8938         isVPriorExp = 3;
8939         }
8940     else if (param->subParams[0]->paramId == BRLENS_twoExp)
8941         {
8942         minV = BRLENS_MIN;
8943         maxV = BRLENS_MAX;
8944         isVPriorExp = 4;
8945         }
8946     else
8947         {
8948         minV = BRLENS_MIN;
8949         maxV = BRLENS_MAX;
8950         brlensExp = mp->brlensExp;
8951         isVPriorExp = YES;
8952         }
8953
8954     /* Dirichlet or twoExp prior */
8955     if (isVPriorExp > 1)
8956         (*lnPriorRatio) = -LogDirPrior(t, mp, isVPriorExp);
8957
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);
8962     getchar();
8963 #   endif
8964     
8965     /* set topologyHasChanged to NO */
8966     topologyHasChanged = NO;
8967     
8968     /* reset node variables that will be used */
8969     for (i=0; i<t->nNodes; i++)
8970         {
8971         p = t->allDownPass[i];
8972         p->marked = NO;
8973         p->d = 0;
8974         }
8975
8976     /* pick a random branch */
8977     p = t->allDownPass[(int)(RandomNumber(seed) * (t->nNodes -2))];
8978     q = p->anc->right;
8979     if (q == p)
8980         q = p->anc->left;
8981     if ((p->anc->anc->anc == NULL || p->anc->isLocked == YES) && (q->left == NULL || q->isLocked == YES))
8982         {
8983         abortMove = YES;
8984         return (NO_ERROR);
8985         }
8986         
8987     /* set up pointers for nodes around the picked branch */
8988     v = p;
8989     u = p->anc;
8990     if (u->left == v)
8991         a = u->right;
8992     else
8993         a = u->left;
8994     b = u->anc;
8995
8996     /* clip tree */
8997     a->anc = b;
8998     if (b->left == u)
8999         b->left = a;
9000     else
9001         b->right = a;
9002
9003     /* get final parsimony states for the root part */
9004     GetParsDP (t, t->root->left, chain);
9005     GetParsFP (t, t->root->left, chain);
9006
9007     /* get downpass parsimony states for the crown part */
9008     GetParsDP (t, v, chain);
9009
9010     /* mark all nodes in the root part of the tree, taking constraints into account */
9011     /* first mark a */
9012     a->marked = YES;
9013     /* then move down towards root */
9014     if (u->isLocked == NO)
9015         {
9016         p = a->anc;
9017         while (p->anc != NULL)
9018             {
9019             p->marked = YES;
9020             if (p->isLocked == YES)
9021                 break;
9022             p = p->anc;
9023             }
9024         }
9025
9026     /* finally move up */
9027     for (i=t->nNodes-2; i>=0; i--)
9028         {
9029         p = t->allDownPass[i];
9030         if (p->marked == NO && p->anc->marked == YES && p->anc->isLocked == NO && p != u)
9031             p->marked = YES;
9032         }
9033
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));
9037     if (!nSitesOfPat)
9038         {
9039         MrBayesPrint ("%s   Problem allocating nSitesOfPat in Move_ParsSPR\n", spacer);
9040         return (ERROR);
9041         }
9042     for (i=0; i<numCompressedChars; i++)
9043         {
9044         nSitesOfPat[i] = globalNSitesOfPat[i];
9045         for (j=0; j<globalNSitesOfPat[i]; j++)
9046             {
9047             ran = RandomNumber(seed);
9048             if (ran < decreaseProb)
9049                 nSitesOfPat[i]--;
9050             else if (ran > 1.0 - increaseProb)
9051                 nSitesOfPat[i]++;
9052             }
9053         }
9054
9055     /* cycle through the possibilities and record the parsimony length */
9056     for (i=0; i<t->nNodes; i++)
9057         {
9058         p = t->allDownPass[i];
9059         if (p->marked == NO)
9060             continue;
9061         /* find the parsimony length */
9062         p->d = 0.0;
9063         for (n=0; n<t->nRelParts; n++)
9064             {
9065             division = t->relParts[n];
9066             
9067             /* Find model settings */
9068             m = &modelSettings[division];
9069
9070             /* find nSitesOfPat */
9071             nSites = nSitesOfPat + m->compCharStart;
9072
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];
9077         
9078             length = 0.0;
9079             if (m->nParsIntsPerSite == 1)
9080                 {
9081                 for (j=0; j<m->numChars; j++)
9082                     {
9083                     y[0] = (pP[j] | pA[j]) & pV[j];
9084                     if (y[0] == 0)
9085                         length += nSites[j];
9086                     }
9087                 }
9088             else /* if (m->nParsIntsPerSite == 2) */
9089                 {
9090                 for (j=0; j<2*m->numChars; j+=2)
9091                     {
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];
9096                     }
9097                 }
9098
9099             /* find nStates and ratemult */
9100             nStates = m->numModelStates;
9101             if (m->dataType == STANDARD)
9102                 nStates = 2;
9103             rateMult = GetRate(division, chain);
9104
9105             /* get division warp factor */
9106             divFactor = - warpFactor * log((1.0/nStates) - exp(-nStates/(nStates-1)*v_typical*rateMult)/nStates);
9107
9108             p->d += divFactor * length;
9109             }
9110         }
9111
9112     /* find the min length and the sum for the forward move */    
9113     minLength = -1.0;
9114     for (i=0; i<t->nNodes; i++)
9115         {
9116         p = t->allDownPass[i];
9117         if (p->marked == NO || p == a)
9118             continue;
9119         if (minLength < 0.0 || p->d < minLength)
9120             minLength = p->d;
9121         }
9122     sum1 = 0.0; tempc = 0.0;
9123     for (i=0; i<t->nNodes; i++)
9124         {
9125         p = t->allDownPass[i];
9126         if (p->marked == YES && p != a)
9127             {
9128             /* Kahan summation to reduce numerical error */
9129             tempy = exp (minLength - p->d) - tempc;
9130             tempsum = sum1 + tempy;
9131             tempc = (tempsum - sum1) - tempy;
9132             sum1 = tempsum;
9133             }
9134         }
9135     
9136     /* generate a random uniform */
9137     ran = RandomNumber(seed) * sum1;
9138
9139     /* select the appropriate reattachment point */
9140     cumulativeProb = 0.0; tempc = 0.0;
9141     for (i=0; i<t->nNodes; i++)
9142         {
9143         p = t->allDownPass[i];
9144         if (p->marked == YES && p != a)
9145             {
9146             c = p;
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)
9153                 break;
9154             }
9155         }
9156
9157     /* calculate the proposal ratio */
9158     (*lnProposalRatio) = c->d - minLength + log(sum1);
9159
9160     /* find the min length and the sum for the backward move */
9161     minLength = -1.0;
9162     for (i=0; i<t->nNodes; i++)
9163         {
9164         p = t->allDownPass[i];
9165         if (p->marked == NO || p == c)
9166             continue;
9167         if (minLength < 0.0 || p->d < minLength)
9168             minLength = p->d;
9169         }
9170     sum2 = 0.0; tempc = 0.0;
9171     for (i=0; i<t->nNodes; i++)
9172         {
9173         p = t->allDownPass[i];
9174         if (p->marked == YES && p != c)
9175             {
9176             /* Kahan summation to reduce numerical error */
9177             tempy = exp (minLength - p->d) - tempc;
9178             tempsum = sum2 + tempy;
9179             tempc = (tempsum - sum2) - tempy;
9180             sum2 = tempsum;
9181             }
9182         }
9183
9184     /* calculate the proposal ratio */
9185     (*lnProposalRatio) += minLength - a->d - log(sum2);
9186
9187     /* reattach */
9188     d = c->anc;
9189     c->anc = u;
9190     if (u->left == v)
9191         u->right = c;
9192     else
9193         u->left = c;
9194     if (d->left == c)
9195         d->left = u;
9196     else
9197         d->right = u;
9198     u->anc = d;
9199
9200     /* c cannot be a, as a is skiped in the selection for reattachment point */
9201     assert (c != a);
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)
9205         {
9206         u->isLocked = NO;
9207         a->isLocked = YES;
9208         a->lockID = u->lockID;
9209         u->lockID = -1;
9210         }
9211     /* if c is on root path and locked, we need to transfer lock to u */
9212     p = b;
9213     while (p != NULL)
9214         {
9215         if (p == c)
9216             break;
9217         p = p->anc;
9218         }
9219     if (p == c && c->isLocked == YES)
9220         {
9221         u->isLocked = YES;
9222         u->lockID = c->lockID;
9223         c->isLocked = NO;
9224         c->lockID = -1;
9225         }
9226
9227     /* reassign branch lengths */
9228     p = c;
9229     while (p->anc->anc != NULL)
9230         {
9231         if (p == a)
9232             break;
9233         p = p->anc;
9234         }
9235     if (p == a)
9236         {
9237         /* c is descendant to a so move a->length and not u->length */
9238         x = u->length;
9239         u->length = a->length;
9240         a->length = x;
9241         }
9242     p = a;
9243     while (p->anc->anc != NULL)
9244         {
9245         if (p == c)
9246             break;
9247         p = p->anc;
9248         }
9249     if (p == c)
9250         {
9251         /* c is ancestor to a so insert above instead of below */
9252         x = c->length;
9253         c->length = u->length;
9254         u->length = x;
9255         }
9256
9257     topologyHasChanged = YES;
9258
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)
9262         {
9263         if (x < minV)
9264             x = minV * minV / x;
9265         else if (x > maxV)
9266             x = maxV * maxV / x;
9267         }
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);
9272     c->length = x;
9273     
9274     /* hit a length with multiplier */
9275     x = a->length * exp(tuning * (RandomNumber(seed) - 0.5));
9276     while (x < minV || x > maxV)
9277         {
9278         if (x < minV)
9279             x = minV * minV / x;
9280         else if (x > maxV)
9281             x = maxV * maxV / x;
9282         }
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);
9287     a->length = x;
9288
9289     /* hit u length with multiplier */
9290     x = u->length * exp(tuning * (RandomNumber(seed) - 0.5));
9291     while (x < minV || x > maxV)
9292         {
9293         if (x < minV)
9294             x = minV * minV / x;
9295         else if (x > maxV)
9296             x = maxV * maxV / x;
9297         }
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);
9302     u->length = x;
9303
9304     /* set tiprobs update flags */
9305     a->upDateTi = YES;
9306     u->upDateTi = YES;
9307     c->upDateTi = YES;  /* could be same as a but that does not matter */
9308
9309     /* set flags for update of cond likes from u and down to root */
9310     p = u;
9311     while (p->anc != NULL)
9312         {
9313         p->upDateCl = YES;
9314         p = p->anc;
9315         }
9316
9317     /* set flags for update of cond likes from b and down to root */
9318     p = b;
9319     while (p->anc != NULL && p->upDateCl == NO)
9320         {
9321         p->upDateCl = YES; 
9322         p = p->anc;
9323         }
9324
9325     /* get down pass sequence if tree topology has changed */
9326     if (topologyHasChanged == YES)
9327         {
9328         GetDownPass (t);
9329         }
9330
9331     /* Dirichlet or twoExp prior */
9332     if (isVPriorExp > 1)
9333         (*lnPriorRatio) += LogDirPrior(t, mp, isVPriorExp);
9334     
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);
9340     getchar();
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);
9344     getchar();
9345 #   endif
9346
9347     free (nSitesOfPat);
9348
9349     return (NO_ERROR);
9350 }
9351
9352
9353 int Move_ParsSPR1 (Param *param, int chain, RandLong *seed, MrBFlt *lnPriorRatio, MrBFlt *lnProposalRatio, MrBFlt *mvp)
9354 {
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} */
9357     
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;
9364     Tree        *t;
9365     ModelParams *mp;
9366     ModelInfo   *m=NULL;
9367     
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 */
9373     
9374     (*lnProposalRatio) = (*lnPriorRatio) = 0.0;
9375     
9376     /* get model params and model info */
9377     mp = &modelParams[param->relParts[0]];
9378     m = &modelSettings[param->relParts[0]];
9379     
9380     /* get tree */
9381     t = GetTree (param, chain, state[chain]);
9382     
9383     /* max and min brlen */
9384     if (param->subParams[0]->paramId == BRLENS_UNI)
9385         {
9386         minV = mp->brlensUni[0] > BRLENS_MIN ? mp->brlensUni[0] : BRLENS_MIN;
9387         maxV = mp->brlensUni[1] < BRLENS_MAX ? mp->brlensUni[1] : BRLENS_MAX;
9388         isVPriorExp = NO;
9389         }
9390     else if (param->subParams[0]->paramId == BRLENS_GamDir)
9391         {
9392         minV = BRLENS_MIN;
9393         maxV = BRLENS_MAX;
9394         isVPriorExp = 2;
9395         }
9396     else if (param->subParams[0]->paramId == BRLENS_iGmDir)
9397         {
9398         minV = BRLENS_MIN;
9399         maxV = BRLENS_MAX;
9400         isVPriorExp = 3;
9401         }
9402     else if (param->subParams[0]->paramId == BRLENS_twoExp)
9403         {
9404         minV = BRLENS_MIN;
9405         maxV = BRLENS_MAX;
9406         isVPriorExp = 4;
9407         }
9408     else
9409         {
9410         minV = BRLENS_MIN;
9411         maxV = BRLENS_MAX;
9412         brlensExp = mp->brlensExp;
9413         isVPriorExp = YES;
9414         }
9415
9416     /* Dirichlet or twoExp prior */
9417     if (isVPriorExp > 1)
9418         (*lnPriorRatio) = -LogDirPrior(t, mp, isVPriorExp);
9419     
9420     /* set topologyHasChanged to NO */
9421     topologyHasChanged = NO;
9422     
9423     /* pick a random branch */
9424     do  {
9425         p = t->allDownPass[(int)(RandomNumber(seed) * (t->nNodes -1))];
9426         q = p->anc->right;  if (q == p) q = p->anc->left;
9427         i = j = 0;
9428         if (p->left == NULL)
9429             j = 2;
9430         if (p->anc->anc == NULL)
9431             i = 2;
9432         if (p->anc->anc != NULL && (p->anc->isLocked == YES || p->anc->anc->anc == NULL))
9433             i++;
9434         if (p->anc->anc != NULL && (q->isLocked == YES || q->left == NULL))
9435             i++;
9436         if (p->left != NULL && (p->left->isLocked == YES || p->left->left == NULL))
9437             j++;
9438         if (p->left != NULL && (p->right->isLocked == YES || p->right->left == NULL))
9439             j++;
9440         } while (i == 2 && j == 2);
9441     
9442     /* determine moving direction */
9443     if (j == 2)
9444         moveInRoot = YES;
9445     else if (i == 2)
9446         moveInRoot = NO;
9447     else if (RandomNumber(seed) < 0.5)
9448         moveInRoot = YES;
9449     else
9450         moveInRoot = NO;
9451
9452     /* set up pointers for nodes around the picked branch */
9453     /* should never change u, v, a, b, c, d pointers */
9454     v = p;
9455     u = p->anc;
9456     if (u->left == v)
9457         a = u->right;
9458     else
9459         a = u->left;
9460     b = u->anc;
9461     c = v->left;
9462     d = v->right;
9463
9464     /* reset node variables that will be used */
9465     for (i=0; i<t->nNodes; i++)
9466         {
9467         p = t->allDownPass[i];
9468         p->x = 0;
9469         p->marked = NO;
9470         }
9471
9472     /* mark nodes nNeighbor away in root (negative) or crown (positive) respecting constraints */
9473     nRoot = nCrown = 1;
9474     if (moveInRoot == YES)
9475         {
9476         /* clip root part of tree */
9477         a->anc = b;
9478         if (b->left == u)
9479             b->left = a;
9480         else
9481             b->right = a;
9482     
9483         /* mark the root part */
9484         if (u->isLocked == NO )
9485             {
9486             p = a; q = b; n = 0;
9487             while (q->anc != NULL)
9488                 {
9489                 q->marked = YES;
9490                 q->x = n;    // temporary, for MarkDistance below
9491                 if (q->left == p)
9492                     MarkDistance(q->right, YES, nNeighbor, &nRoot);
9493                 else
9494                     MarkDistance(q->left,  YES, nNeighbor, &nRoot);
9495                 q->x = --n;  // final
9496                 nRoot++;
9497                 if (q->isLocked == YES || abs(q->x) >= nNeighbor)
9498                     break;
9499                 p = q; q = q->anc;
9500                 }
9501             }
9502         if (a->isLocked == NO)
9503             {
9504             MarkDistance(a->left,  YES, nNeighbor, &nRoot);
9505             MarkDistance(a->right, YES, nNeighbor, &nRoot);
9506             }
9507             
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);
9514         }
9515     else  /* moveInRoot == NO */
9516         {
9517         /* clip crown part of tree */
9518         c->anc = d;
9519         d->anc = c;
9520
9521         /* mark the crown part */
9522         if (c->isLocked == NO)
9523             {
9524             MarkDistance(c->left,  NO, nNeighbor, &nCrown);
9525             MarkDistance(c->right, NO, nNeighbor, &nCrown);
9526             }
9527         if (d->isLocked == NO)
9528             {
9529             MarkDistance(d->left,  NO, nNeighbor, &nCrown);
9530             MarkDistance(d->right, NO, nNeighbor, &nCrown);
9531             }
9532         
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;
9537             else             b->right = 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;
9542             else             b->right = u;
9543             }
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);
9549         }
9550     
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++)
9556         {
9557         nSitesOfPat[i] = globalNSitesOfPat[i];
9558     /*  for (j=0; j<globalNSitesOfPat[i]; j++)
9559             {
9560             ran = RandomNumber(seed);
9561             if (ran < decreaseProb)
9562                 nSitesOfPat[i]--;
9563             else if (ran > 1.0 - increaseProb)
9564                 nSitesOfPat[i]++;
9565             }  // this is slow at the moment */
9566         }
9567
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;
9574     
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)
9581             pRoot[i++] = p;
9582         if (p->marked == YES && p->x > 0)
9583             pCrown[j++] = p;
9584         }
9585     assert (i==nRoot && j==nCrown);
9586     
9587     /* cycle through the possibilities and record the parsimony length */
9588     for (j=0; j<nCrown; j++)
9589         {
9590         for (i=0; i<nRoot; i++)
9591             {
9592             parLength[i+j*nRoot] = 0.0;
9593             for (n=0; n<t->nRelParts; n++)
9594                 {
9595                 division = t->relParts[n];
9596                 
9597                 /* Find model settings */
9598                 m = &modelSettings[division];
9599                 
9600                 /* find nSitesOfPat */
9601                 nSites = nSitesOfPat + m->compCharStart;
9602                 
9603                 /* find parsimony length for each candidate position */
9604                 length = 0.0;
9605                 if (moveInRoot == YES)
9606                     {
9607                     pA = m->parsSets[pRoot[i]->index];
9608                     pB = m->parsSets[pRoot[i]->anc->index];
9609                     pP = m->parsSets[v->index];
9610                     
9611                     if (m->nParsIntsPerSite == 1)
9612                         {
9613                         for (k=0; k<m->numChars; k++)
9614                             {
9615                             y[0] = (pA[k] | pB[k]) & pP[k];
9616                             if (y[0] == 0)
9617                                 length += nSites[k];
9618                             }
9619                         }
9620                     else /* if (m->nParsIntsPerSite == 2) */
9621                         {
9622                         for (k=0; k<2*m->numChars; k+=2)
9623                             {
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];
9628                             }
9629                         }
9630                     }
9631                 else if (u->anc == NULL)
9632                     {
9633                     pP = m->parsSets[u->index];
9634                     pC = m->parsSets[pCrown[j]->index];
9635                     pD = m->parsSets[pCrown[j]->anc->index];
9636                     
9637                     if (m->nParsIntsPerSite == 1)
9638                         {
9639                         for (k=0; k<m->numChars; k++)
9640                             {
9641                             y[0] = pP[k] & (pC[k] | pD[k]);
9642                             if (y[0] == 0)
9643                                 length += nSites[k];
9644                             }
9645                         }
9646                     else /* if (m->nParsIntsPerSite == 2) */
9647                         {
9648                         for (k=0; k<2*m->numChars; k+=2)
9649                             {
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];
9654                             }
9655                         }
9656                     }
9657                 else
9658                     {
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];
9663                     
9664                     if (m->nParsIntsPerSite == 1)
9665                         {
9666                         for (k=0; k<m->numChars; k++)
9667                             {
9668                             y[0] = (pA[k] | pB[k]) & (pC[k] | pD[k]);
9669                             if (y[0] == 0)
9670                                 length += nSites[k];
9671                             }
9672                         }
9673                     else /* if (m->nParsIntsPerSite == 2) */
9674                         {
9675                         for (k=0; k<2*m->numChars; k+=2)
9676                             {
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];
9681                             }
9682                         }
9683                     }
9684                 
9685                 /* get division warp factor */
9686                 parLength[i+j*nRoot] += warpFactor * length;
9687                 }
9688             }
9689         }
9690     
9691     /* find the min length and the sum for the forward move */
9692     minLength = -1.0;
9693     for (j=0; j<nCrown; j++)
9694         for (i=0; i<nRoot; i++)
9695             {
9696             if (i == 0 && j == 0)  // exclude original position
9697                 continue;
9698             if (minLength > parLength[i+j*nRoot] || minLength < 0.0)
9699                 minLength = parLength[i+j*nRoot];
9700             }
9701     sum1 = 0.0; tempc = 0.0;
9702     for (j=0; j<nCrown; j++)
9703         for (i=0; i<nRoot; i++)
9704             {
9705             if (i == 0 && j == 0)  // exclude original position
9706                 continue;
9707             /* Kahan summation to reduce numerical error */
9708             tempy = exp(minLength - parLength[i+j*nRoot]) - tempc;
9709             tempsum = sum1 + tempy;  tempc = (tempsum - sum1) - tempy;
9710             sum1 = tempsum;
9711             // sum1 += exp(minLength - parLength[i+j*nRoot]);
9712             // printf("%d %d %lf\n", i, j, exp(minLength - parLength[i+j*nRoot]));
9713             }
9714
9715     /* generate a random uniform */
9716     ran = RandomNumber(seed) * sum1;
9717     
9718     /* select the appropriate reattachment point */
9719     newA = a; newC = c;
9720     prob = 0.0; tempc = 0.0;
9721     for (j=0; j<nCrown; j++)
9722         for (i=0; i<nRoot; i++)
9723             {
9724             if (i == 0 && j == 0)  // exclude original position
9725                 continue;
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;
9730             prob = tempsum;
9731             if (prob > ran) {
9732                 /* proposed new attaching position */
9733                 newA = pRoot[i];
9734                 newC = pCrown[j];
9735                 goto outLoop;
9736                 }
9737             }
9738 outLoop:;
9739     iA = i; jC = j;
9740     
9741     /* calculate the proposal ratio */
9742     (*lnProposalRatio) = parLength[i+j*nRoot] - minLength + log(sum1);
9743     
9744     /* find the min length and the sum for the backward move */
9745     minLength = -1.0;
9746     for (j=0; j<nCrown; j++)
9747         for (i=0; i<nRoot; i++)
9748             {
9749             if (i == iA && j == jC)  // exclude new position
9750                 continue;
9751             if (minLength > parLength[i+j*nRoot] || minLength < 0.0)
9752                 minLength = parLength[i+j*nRoot];
9753             }
9754     sum2 = 0.0; tempc = 0.0;
9755     for (j=0; j<nCrown; j++)
9756         for (i=0; i<nRoot; i++)
9757             {
9758             if (i == iA && j == jC)  // exclude new position
9759                 continue;
9760             /* Kahan summation to reduce numerical error */
9761             tempy = exp(minLength - parLength[i+j*nRoot]) - tempc;
9762             tempsum = sum2 + tempy;  tempc = (tempsum - sum2) - tempy;
9763             sum2 = tempsum;
9764             // sum2 += exp (minLength - parLength[i+j*nRoot]);
9765             // printf("%d %d %lf\n", i, j, exp(minLength - parLength[i+j*nRoot]));
9766             }
9767     
9768     /* calculate the proposal ratio */
9769     (*lnProposalRatio) += minLength - parLength[0] - log(sum2);
9770     
9771     if (moveInRoot == YES)  /* root part has changed */
9772         {
9773         /* reattach the root part */
9774         newB = newA->anc;
9775         newA->anc = u;
9776         if (u->left == v)
9777             u->right = newA;
9778         else
9779             u->left = newA;
9780         u->anc = newB;
9781         if (newB->left == newA)
9782             newB->left = u;
9783         else
9784             newB->right = u;
9785
9786         /* if u is locked, then we have moved upwards and need to leave the u lock behind */
9787         if (u->isLocked == YES)
9788             {
9789             u->isLocked = NO;
9790             a->isLocked = YES;
9791             a->lockID = u->lockID;
9792             u->lockID = -1;
9793             }
9794         
9795         p = newA;
9796         while (p->anc != NULL)
9797             {
9798             if (p == a) break;
9799             p = p->anc;
9800             }
9801         if (p == a)
9802             {
9803             /* newA is descendant to a so move a->length not u->length */
9804             x = u->length;
9805             u->length = a->length;
9806             a->length = x;
9807             }
9808
9809         p = b;
9810         while (p->anc != NULL)
9811             {
9812             if (p == newA) break;
9813             p = p->anc;
9814             }
9815         if (p == newA)
9816             {
9817             /* newA is ancestor to a so insert above instead of below */
9818             x = newA->length;
9819             newA->length = u->length;
9820             u->length = x;
9821             /* newA is on root path and locked, we need to transfer lock to u */
9822             if (newA->isLocked == YES) {
9823                 u->isLocked = YES;
9824                 u->lockID = newA->lockID;
9825                 newA->isLocked = NO;
9826                 newA->lockID = -1;
9827                 }
9828             }
9829         
9830         /* hit a length with multiplier */
9831         x = a->length * exp(tuning * (RandomNumber(seed) - 0.5));
9832         while (x < minV || x > maxV)
9833             {
9834             if (x < minV) x = minV * minV / x;
9835             if (x > maxV) x = maxV * maxV / x;
9836             }
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);
9841         a->length = x;
9842
9843         /* hit u length with multiplier */
9844         x = u->length * exp(tuning * (RandomNumber(seed) - 0.5));
9845         while (x < minV || x > maxV)
9846             {
9847             if (x < minV) x = minV * minV / x;
9848             if (x > maxV) x = maxV * maxV / x;
9849             }
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);
9854         u->length = x;
9855
9856         /* hit newA length with multiplier */
9857         x = newA->length * exp(tuning * (RandomNumber(seed) - 0.5));
9858         while (x < minV || x > maxV)
9859             {
9860             if (x < minV) x = minV * minV / x;
9861             if (x > maxV) x = maxV * maxV / x;
9862             }
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);
9867         newA->length = x;
9868          
9869         /* set tiprobs update flags */
9870         newA->upDateTi = YES;
9871         a->upDateTi = YES;
9872         u->upDateTi = YES;
9873             
9874         /* set flags for update of cond likes */
9875         p = u;
9876         while (p->anc != NULL)
9877             {
9878             p->upDateCl = YES;
9879             p = p->anc;
9880             }
9881         p = b;
9882         while (p->anc != NULL)
9883             {
9884             p->upDateCl = YES;
9885             p = p->anc;
9886             }
9887         }
9888     
9889     if (moveInRoot == NO)  /* crown part has changed */
9890         {
9891         r = newC;
9892         q = newB = newC->anc;
9893         /* rotate nodes from newC to c or d (whichever is closest) */
9894         tempc = r->length;
9895         while (r != c && r != d)
9896             {
9897             p = q->anc;
9898             /* rotate pointers of q */
9899             if (q->left == r)
9900                 q->left = p;
9901             else
9902                 q->right = p;
9903             q->anc = r;
9904             /* swap q and old */
9905             tempy = q->length;
9906             q->length = tempc;
9907             q->upDateTi = YES;
9908             tempc = tempy;
9909             /* make sure we get q and r initialized for next round */
9910             r = q;
9911             q = p;
9912             }
9913         newB->length = tempc;
9914             
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)
9918             {
9919             if (x < minV) x = minV * minV / x;
9920             if (x > maxV) x = maxV * maxV / x;
9921             }        
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);
9926         q->length = x;
9927         q->upDateTi = YES;
9928
9929         /* hit newB length with multiplier */
9930         x = newB->length * exp(tuning * (RandomNumber(seed) - 0.5));
9931         while (x < minV || x > maxV)
9932             {
9933             if (x < minV) x = minV * minV / x;
9934             if (x > maxV) x = maxV * maxV / x;
9935             }
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);
9940         newB->length = x;
9941         newB->upDateTi = YES;
9942
9943         /* hit newC length with multiplier */
9944         x = newC->length * exp(tuning * (RandomNumber(seed) - 0.5));
9945         while (x < minV || x > maxV)
9946             {
9947             if (x < minV) x = minV * minV / x;
9948             if (x > maxV) x = maxV * maxV / x;
9949             }
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);
9954         newC->length = x;
9955         newC->upDateTi = YES;
9956  
9957         /* reattach the crown part */
9958         v->left = newC;
9959         v->right = newB;
9960         newC->anc = newB->anc = v;
9961         
9962         /* set flags for update of cond likes */
9963         p = newC;
9964         while (p->anc != NULL)
9965             {
9966             p->upDateCl = YES;
9967             p = p->anc;
9968             }
9969         p = r;
9970         while (p->anc != NULL)
9971             {
9972             p->upDateCl = YES;
9973             p = p->anc;
9974             }
9975         }
9976     
9977     topologyHasChanged = YES;
9978
9979     /* get down pass sequence if tree topology has changed */
9980     if (topologyHasChanged == YES)
9981         {
9982         GetDownPass (t);
9983         }
9984     
9985     /* Dirichlet or twoExp prior */
9986     if (isVPriorExp > 1)
9987         (*lnPriorRatio) += LogDirPrior(t, mp, isVPriorExp);
9988     
9989     /* free up local memory */
9990     free (parLength); free (pRoot); free (pCrown); free (nSitesOfPat);
9991     
9992     return (NO_ERROR);
9993     
9994 errorExit:
9995     MrBayesPrint ("%s   Problem allocating memory in Move_ParsSPR\n", spacer);
9996     free (parLength); free (pRoot); free (pCrown); free (nSitesOfPat);
9997     
9998     return (ERROR);
9999 }
10000
10001
10002 int Move_ParsSPR2 (Param *param, int chain, RandLong *seed, MrBFlt *lnPriorRatio, MrBFlt *lnProposalRatio, MrBFlt *mvp)
10003 {
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 */
10006     
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;
10013     Tree        *t;
10014     ModelParams *mp;
10015     ModelInfo   *m=NULL;
10016     
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 */
10022     
10023     (*lnProposalRatio) = (*lnPriorRatio) = 0.0;
10024     
10025     /* get model params and model info */
10026     mp = &modelParams[param->relParts[0]];
10027     m = &modelSettings[param->relParts[0]];
10028     
10029     /* get tree */
10030     t = GetTree (param, chain, state[chain]);
10031     
10032     /* max and min brlen */
10033     if (param->subParams[0]->paramId == BRLENS_UNI)
10034         {
10035         minV = mp->brlensUni[0] > BRLENS_MIN ? mp->brlensUni[0] : BRLENS_MIN;
10036         maxV = mp->brlensUni[1] < BRLENS_MAX ? mp->brlensUni[1] : BRLENS_MAX;
10037         isVPriorExp = NO;
10038         }
10039     else if (param->subParams[0]->paramId == BRLENS_GamDir)
10040         {
10041         minV = BRLENS_MIN;
10042         maxV = BRLENS_MAX;
10043         isVPriorExp = 2;
10044         }
10045     else if (param->subParams[0]->paramId == BRLENS_iGmDir)
10046         {
10047         minV = BRLENS_MIN;
10048         maxV = BRLENS_MAX;
10049         isVPriorExp = 3;
10050         }
10051     else if (param->subParams[0]->paramId == BRLENS_twoExp)
10052         {
10053         minV = BRLENS_MIN;
10054         maxV = BRLENS_MAX;
10055         isVPriorExp = 4;
10056         }
10057     else
10058         {
10059         minV = BRLENS_MIN;
10060         maxV = BRLENS_MAX;
10061         brlensExp = mp->brlensExp;
10062         isVPriorExp = YES;
10063         }
10064
10065     /* Dirichlet or twoExp prior */
10066     if (isVPriorExp > 1)
10067         (*lnPriorRatio) = -LogDirPrior(t, mp, isVPriorExp);
10068     
10069     /* set topologyHasChanged to NO */
10070     topologyHasChanged = NO;
10071     
10072     /* pick a random branch */
10073     do  {
10074         p = t->allDownPass[(int)(RandomNumber(seed) * (t->nNodes -1))];
10075         q = p->anc->right;  if (q == p) q = p->anc->left;
10076         i = j = 0;
10077         if (p->left == NULL)
10078             j = 2;
10079         if (p->anc->anc == NULL)
10080             i = 2;
10081         if (p->anc->anc != NULL && (p->anc->isLocked == YES || p->anc->anc->anc == NULL))
10082             i++;
10083         if (p->anc->anc != NULL && (q->isLocked == YES || q->left == NULL))
10084             i++;
10085         if (p->left != NULL && (p->left->isLocked == YES || p->left->left == NULL))
10086             j++;
10087         if (p->left != NULL && (p->right->isLocked == YES || p->right->left == NULL))
10088             j++;
10089         } while (i == 2 && j == 2);
10090     
10091     /* pick an internal branch
10092     do  {
10093         p = t->intDownPass[(int)(RandomNumber(seed)*(t->nIntNodes-1))];
10094         q = p->anc->left;  if (q == p)  q = p->anc->right;
10095         i = j = 0;
10096         if (q->isLocked == YES || q->left == NULL)
10097             i++;
10098         if (p->anc->isLocked == YES || p->anc->anc->anc == NULL)
10099             i++;
10100         if (p->left->isLocked == YES || p->left->left == NULL)
10101             j++;
10102         if (p->right->isLocked == YES || p->right->left == NULL)
10103             j++;
10104         } while (i == 2 && j == 2);
10105     */
10106
10107     /* determine moving direction */
10108     if (j == 2)
10109         moveInRoot = YES;
10110     else if (i == 2)
10111         moveInRoot = NO;
10112     else if (RandomNumber(seed) < 0.5)
10113         moveInRoot = YES;
10114     else
10115         moveInRoot = NO;
10116
10117     /* set up pointers for nodes around the picked branch */
10118     /* should never change u, v, a, b, c, d pointers */
10119     v = p;
10120     u = p->anc;
10121     if (u->left == v)
10122         a = u->right;
10123     else
10124         a = u->left;
10125     b = u->anc;
10126     c = v->left;
10127     d = v->right;
10128
10129     /* reset node variables that will be used */
10130     for (i=0; i<t->nNodes; i++)
10131         {
10132         p = t->allDownPass[i];
10133         p->x = 0;
10134         p->marked = NO;
10135         }
10136
10137     /* mark nodes nNeighbor away in root (negative) or crown (positive) respecting constraints */
10138     nRoot = nCrown = 1;
10139     if (moveInRoot == YES)
10140         {
10141         /* clip root part of tree */
10142         a->anc = b;
10143         if (b->left == u)
10144             b->left = a;
10145         else
10146             b->right = a;
10147     
10148         /* mark the root part */
10149         if (u->isLocked == NO )
10150             {
10151             p = a; q = b; n = 0;
10152             while (q->anc != NULL)
10153                 {
10154                 q->marked = YES;
10155                 q->x = n;    // temporary, for MarkDistance below
10156                 if (q->left == p)
10157                     MarkDistance(q->right, YES, nNeighbor, &nRoot);
10158                 else
10159                     MarkDistance(q->left,  YES, nNeighbor, &nRoot);
10160                 q->x = --n;  // final
10161                 nRoot++;
10162                 if (q->isLocked == YES || abs(q->x) >= nNeighbor)
10163                     break;
10164                 p = q; q = q->anc;
10165                 }
10166             }
10167         if (a->isLocked == NO)
10168             {
10169             MarkDistance(a->left,  YES, nNeighbor, &nRoot);
10170             MarkDistance(a->right, YES, nNeighbor, &nRoot);
10171             }
10172             
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);
10179         }
10180     else  /* moveInRoot == NO */
10181         {
10182         /* clip crown part of tree */
10183         c->anc = d;
10184         d->anc = c;
10185
10186         /* mark the crown part */
10187         if (c->isLocked == NO)
10188             {
10189             MarkDistance(c->left,  NO, nNeighbor, &nCrown);
10190             MarkDistance(c->right, NO, nNeighbor, &nCrown);
10191             }
10192         if (d->isLocked == NO)
10193             {
10194             MarkDistance(d->left,  NO, nNeighbor, &nCrown);
10195             MarkDistance(d->right, NO, nNeighbor, &nCrown);
10196             }
10197         
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;
10202             else             b->right = 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;
10207             else             b->right = u;
10208             }
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);
10214         }
10215     
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++)
10221         {
10222         nSitesOfPat[i] = globalNSitesOfPat[i];
10223     /*  for (j=0; j<globalNSitesOfPat[i]; j++)
10224             {
10225             ran = RandomNumber(seed);
10226             if (ran < decreaseProb)
10227                 nSitesOfPat[i]--;
10228             else if (ran > 1.0 - increaseProb)
10229                 nSitesOfPat[i]++;
10230             }  // this is slow at the moment */
10231         }
10232
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;
10239     
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)
10246             pRoot[i++] = p;
10247         if (p->marked == YES && p->x > 0)
10248             pCrown[j++] = p;
10249         }
10250     assert (i==nRoot && j==nCrown);
10251     
10252     /* cycle through the possibilities and record the parsimony length */
10253     for (j=0; j<nCrown; j++)
10254         {
10255         for (i=0; i<nRoot; i++)
10256             {
10257             parLength[i+j*nRoot] = 0.0;
10258             for (n=0; n<t->nRelParts; n++)
10259                 {
10260                 division = t->relParts[n];
10261                 
10262                 /* Find model settings */
10263                 m = &modelSettings[division];
10264                 
10265                 /* find nSitesOfPat */
10266                 nSites = nSitesOfPat + m->compCharStart;
10267                 
10268                 /* find parsimony length for each candidate position */
10269                 length = 0.0;
10270                 if (moveInRoot == YES)
10271                     {
10272                     pA = m->parsSets[pRoot[i]->index];
10273                     pB = m->parsSets[pRoot[i]->anc->index];
10274                     pP = m->parsSets[v->index];
10275                     
10276                     if (m->nParsIntsPerSite == 1)
10277                         {
10278                         for (k=0; k<m->numChars; k++)
10279                             {
10280                             y[0] = (pA[k] | pB[k]) & pP[k];
10281                             if (y[0] == 0)
10282                                 length += nSites[k];
10283                             }
10284                         }
10285                     else /* if (m->nParsIntsPerSite == 2) */
10286                         {
10287                         for (k=0; k<2*m->numChars; k+=2)
10288                             {
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];
10293                             }
10294                         }
10295                     }
10296                 else if (u->anc == NULL)
10297                     {
10298                     pP = m->parsSets[u->index];
10299                     pC = m->parsSets[pCrown[j]->index];
10300                     pD = m->parsSets[pCrown[j]->anc->index];
10301                     
10302                     if (m->nParsIntsPerSite == 1)
10303                         {
10304                         for (k=0; k<m->numChars; k++)
10305                             {
10306                             y[0] = pP[k] & (pC[k] | pD[k]);
10307                             if (y[0] == 0)
10308                                 length += nSites[k];
10309                             }
10310                         }
10311                     else /* if (m->nParsIntsPerSite == 2) */
10312                         {
10313                         for (k=0; k<2*m->numChars; k+=2)
10314                             {
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];
10319                             }
10320                         }
10321                     }
10322                 else
10323                     {
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];
10328                     
10329                     if (m->nParsIntsPerSite == 1)
10330                         {
10331                         for (k=0; k<m->numChars; k++)
10332                             {
10333                             y[0] = (pA[k] | pB[k]) & (pC[k] | pD[k]);
10334                             if (y[0] == 0)
10335                                 length += nSites[k];
10336                             }
10337                         }
10338                     else /* if (m->nParsIntsPerSite == 2) */
10339                         {
10340                         for (k=0; k<2*m->numChars; k+=2)
10341                             {
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];
10346                             }
10347                         }
10348                     }
10349                 
10350                 /* find nStates and ratemult */
10351                 nStates = m->numModelStates;
10352                 if (m->dataType == STANDARD)
10353                     nStates = 2;
10354                 v_typical = length/m->numUncompressedChars + 0.0001;
10355                 
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;
10359                 }
10360             }
10361         }
10362     
10363     /* find the min length and the sum for the forward move */
10364     minLength = -1.0;
10365     for (j=0; j<nCrown; j++)
10366         for (i=0; i<nRoot; i++)
10367             {
10368             if (i == 0 && j == 0)  // exclude original position
10369                 continue;
10370             if (minLength > parLength[i+j*nRoot] || minLength < 0.0)
10371                 minLength = parLength[i+j*nRoot];
10372             }
10373     sum1 = 0.0; tempc = 0.0;
10374     for (j=0; j<nCrown; j++)
10375         for (i=0; i<nRoot; i++)
10376             {
10377             if (i == 0 && j == 0)  // exclude original position
10378                 continue;
10379             /* Kahan summation to reduce numerical error */
10380             tempy = exp(minLength - parLength[i+j*nRoot]) - tempc;
10381             tempsum = sum1 + tempy;  tempc = (tempsum - sum1) - tempy;
10382             sum1 = tempsum;
10383             // sum1 += exp(minLength - parLength[i+j*nRoot]);
10384             // printf("%d %d %lf\n", i, j, exp(minLength - parLength[i+j*nRoot]));
10385             }
10386
10387     /* generate a random uniform */
10388     ran = RandomNumber(seed) * sum1;
10389     
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++)
10395             {
10396             if (i == 0 && j == 0)  // exclude original position
10397                 continue;
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;
10402             prob = tempsum;
10403             if (prob > ran) {
10404                 /* proposed new attaching position */
10405                 newA = pRoot[i];
10406                 newC = pCrown[j];
10407                 goto outLoop;
10408                 }
10409             }
10410 outLoop:;
10411     iA = i; jC = j;
10412     
10413     /* calculate the proposal ratio */
10414     (*lnProposalRatio) = parLength[i+j*nRoot] - minLength + log(sum1);
10415     
10416     /* find the min length and the sum for the backward move */
10417     minLength = -1.0;
10418     for (j=0; j<nCrown; j++)
10419         for (i=0; i<nRoot; i++)
10420             {
10421             if (i == iA && j == jC)  // exclude new position
10422                 continue;
10423             if (minLength > parLength[i+j*nRoot] || minLength < 0.0)
10424                 minLength = parLength[i+j*nRoot];
10425             }
10426     sum2 = 0.0; tempc = 0.0;
10427     for (j=0; j<nCrown; j++)
10428         for (i=0; i<nRoot; i++)
10429             {
10430             if (i == iA && j == jC)  // exclude new position
10431                 continue;
10432             /* Kahan summation to reduce numerical error */
10433             tempy = exp(minLength - parLength[i+j*nRoot]) - tempc;
10434             tempsum = sum2 + tempy;  tempc = (tempsum - sum2) - tempy;
10435             sum2 = tempsum;
10436             // sum2 += exp (minLength - parLength[i+j*nRoot]);
10437             // printf("%d %d %lf\n", i, j, exp(minLength - parLength[i+j*nRoot]));
10438             }
10439     
10440     /* calculate the proposal ratio */
10441     (*lnProposalRatio) += minLength - parLength[0] - log(sum2);
10442     
10443     if (moveInRoot == YES)  /* root part has changed */
10444         {
10445         /* reattach the root part */
10446         newB = newA->anc;
10447         newA->anc = u;
10448         if (u->left == v)
10449             u->right = newA;
10450         else
10451             u->left = newA;
10452         u->anc = newB;
10453         if (newB->left == newA)
10454             newB->left = u;
10455         else
10456             newB->right = u;
10457
10458         /* if u is locked, then we have moved upwards and need to leave the u lock behind */
10459         if (u->isLocked == YES)
10460             {
10461             u->isLocked = NO;
10462             a->isLocked = YES;
10463             a->lockID = u->lockID;
10464             u->lockID = -1;
10465             }
10466         
10467         p = newA;
10468         while (p->anc != NULL)
10469             {
10470             if (p == a) break;
10471             p = p->anc;
10472             }
10473         if (p == a)
10474             {
10475             /* newA is descendant to a so move a->length not u->length */
10476             x = u->length;
10477             u->length = a->length;
10478             a->length = x;
10479             }
10480
10481         p = b;
10482         while (p->anc != NULL)
10483             {
10484             if (p == newA) break;
10485             p = p->anc;
10486             }
10487         if (p == newA)
10488             {
10489             /* newA is ancestor to a so insert above instead of below */
10490             x = newA->length;
10491             newA->length = u->length;
10492             u->length = x;
10493             /* newA is on root path and locked, we need to transfer lock to u */
10494             if (newA->isLocked == YES) {
10495                 u->isLocked = YES;
10496                 u->lockID = newA->lockID;
10497                 newA->isLocked = NO;
10498                 newA->lockID = -1;
10499                 }
10500             }
10501         
10502         /* hit a length with multiplier */
10503         x = a->length * exp(tuning * (RandomNumber(seed) - 0.5));
10504         while (x < minV || x > maxV)
10505             {
10506             if (x < minV) x = minV * minV / x;
10507             if (x > maxV) x = maxV * maxV / x;
10508             }
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);
10513         a->length = x;
10514
10515         /* hit u length with multiplier */
10516         x = u->length * exp(tuning * (RandomNumber(seed) - 0.5));
10517         while (x < minV || x > maxV)
10518             {
10519             if (x < minV) x = minV * minV / x;
10520             if (x > maxV) x = maxV * maxV / x;
10521             }
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);
10526         u->length = x;
10527
10528         /* hit newA length with multiplier */
10529         x = newA->length * exp(tuning * (RandomNumber(seed) - 0.5));
10530         while (x < minV || x > maxV)
10531             {
10532             if (x < minV) x = minV * minV / x;
10533             if (x > maxV) x = maxV * maxV / x;
10534             }
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);
10539         newA->length = x;
10540          
10541         /* set tiprobs update flags */
10542         newA->upDateTi = YES;
10543         a->upDateTi = YES;
10544         u->upDateTi = YES;
10545             
10546         /* set flags for update of cond likes */
10547         p = u;
10548         while (p->anc != NULL)
10549             {
10550             p->upDateCl = YES;
10551             p = p->anc;
10552             }
10553         p = b;
10554         while (p->anc != NULL)
10555             {
10556             p->upDateCl = YES;
10557             p = p->anc;
10558             }
10559         }
10560     
10561     if (moveInRoot == NO)  /* crown part has changed */
10562         {
10563         r = newC;
10564         q = newB = newC->anc;
10565         /* rotate nodes from newC to c or d (whichever is closest) */
10566         tempc = r->length;
10567         while (r != c && r != d)
10568             {
10569             p = q->anc;
10570             /* rotate pointers of q */
10571             if (q->left == r)
10572                 q->left = p;
10573             else
10574                 q->right = p;
10575             q->anc = r;
10576             /* swap q and old */
10577             tempy = q->length;
10578             q->length = tempc;
10579             q->upDateTi = YES;
10580             tempc = tempy;
10581             /* make sure we get q and r initialized for next round */
10582             r = q;
10583             q = p;
10584             }
10585         newB->length = tempc;
10586             
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)
10590             {
10591             if (x < minV) x = minV * minV / x;
10592             if (x > maxV) x = maxV * maxV / x;
10593             }        
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);
10598         q->length = x;
10599         q->upDateTi = YES;
10600
10601         /* hit newB length with multiplier */
10602         x = newB->length * exp(tuning * (RandomNumber(seed) - 0.5));
10603         while (x < minV || x > maxV)
10604             {
10605             if (x < minV) x = minV * minV / x;
10606             if (x > maxV) x = maxV * maxV / x;
10607             }
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);
10612         newB->length = x;
10613         newB->upDateTi = YES;
10614
10615         /* hit newC length with multiplier */
10616         x = newC->length * exp(tuning * (RandomNumber(seed) - 0.5));
10617         while (x < minV || x > maxV)
10618             {
10619             if (x < minV) x = minV * minV / x;
10620             if (x > maxV) x = maxV * maxV / x;
10621             }
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);
10626         newC->length = x;
10627         newC->upDateTi = YES;
10628  
10629         /* reattach the crown part */
10630         v->left = newC;
10631         v->right = newB;
10632         newC->anc = newB->anc = v;
10633         
10634         /* set flags for update of cond likes */
10635         p = newC;
10636         while (p->anc != NULL)
10637             {
10638             p->upDateCl = YES;
10639             p = p->anc;
10640             }
10641         p = r;
10642         while (p->anc != NULL)
10643             {
10644             p->upDateCl = YES;
10645             p = p->anc;
10646             }
10647         }
10648     
10649     topologyHasChanged = YES;
10650
10651     /* get down pass sequence if tree topology has changed */
10652     if (topologyHasChanged == YES)
10653         {
10654         GetDownPass (t);
10655         }
10656     
10657     /* Dirichlet or twoExp prior */
10658     if (isVPriorExp > 1)
10659         (*lnPriorRatio) += LogDirPrior(t, mp, isVPriorExp);
10660     
10661     /* free up local memory */
10662     free (parLength); free (pRoot); free (pCrown); free (nSitesOfPat);
10663     
10664     return (NO_ERROR);
10665     
10666 errorExit:
10667     MrBayesPrint ("%s   Problem allocating memory in Move_ParsSPR\n", spacer);
10668     free (parLength); free (pRoot); free (pCrown); free (nSitesOfPat);
10669     
10670     return (ERROR);
10671 }
10672
10673
10674 int Move_ParsSPRClock (Param *param, int chain, RandLong *seed, MrBFlt *lnPriorRatio, MrBFlt *lnProposalRatio, MrBFlt *mvp)
10675 {
10676     /* Change branch lengths and topology (potentially) using SPR-type move, parsimony-biased */
10677
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. */
10682     
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;
10692     Tree        *t;
10693     ModelInfo   *m=NULL;
10694     Param       *subParm;
10695
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 */
10699
10700     (*lnProposalRatio) = (*lnPriorRatio) = 0.0;
10701
10702     /* get tree */
10703     t = GetTree (param, chain, state[chain]);
10704
10705     /* get model params and model info */
10706     m = &modelSettings[param->relParts[0]];
10707     
10708     /* get min and max brlen in relative time and subst units */
10709     minV = BRLENS_MIN;
10710
10711 #   if defined (DEBUG_ParsSPRClock)
10712     printf ("Before:\n");
10713     ShowNodes (t->root, 2, YES);
10714     getchar();
10715 #   endif
10716     
10717     /* pick a branch */
10718     do  {
10719         p = t->allDownPass[(int)(RandomNumber(seed) * (t->nNodes - 2))];
10720         a = p->anc->left;
10721         b = p->anc->right;
10722         }
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 */
10726
10727     /* set up pointers for nodes around the picked branch */
10728     v = p;
10729     u = p->anc;
10730     if (u->left == v)
10731         a = u->right;
10732     else
10733         a = u->left;
10734     b = u->anc;
10735
10736     /* record branch length for insertion in back move */
10737     if (v->length > 0.0)  /* side branch, not anc fossil */
10738         {
10739         if (v->nodeDepth > a->nodeDepth)
10740             oldBrlen = b->nodeDepth - v->nodeDepth - 2.0*minV;
10741         else
10742             oldBrlen = b->nodeDepth - a->nodeDepth - 2.0*minV;
10743         }
10744     v1 = a->length;
10745     v2 = u->length;
10746     v3 = v->length;
10747
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++)
10750         {
10751         subParm = param->subParams[0]->subParams[i];
10752         if (subParm->paramType == P_CPPEVENTS)
10753             {
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];
10760             if (n2 > 0)
10761                 {
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));
10764                 }
10765             for (j=0; j<n1; j++)
10766                 position[a->index][j] *= v1 / (v1+v2);
10767             for (j=n1; j<n1+n2; j++)
10768                 {
10769                 position[a->index][j] = (position[u->index][j-n1] * v2 + v1) / (v1+v2);
10770                 rateMultiplier[a->index][j] = rateMultiplier[u->index][j-n1];
10771                 }
10772             nEvents[a->index] = n1+n2;
10773             nEvents[u->index] = 0;
10774             if (n2 > 0)
10775                 {
10776                 free (position[u->index]);
10777                 free (rateMultiplier[u->index]);
10778                 position[u->index] = rateMultiplier[u->index] = NULL;
10779                 }
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))
10786             {
10787             /* adjust prior ratio */
10788             if (subParm->paramType == P_TK02BRANCHRATES)
10789                 nu = *GetParamVals (modelSettings[subParm->relParts[0]].tk02var, chain, state[chain]);
10790             else
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]);
10798             
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))
10805             {
10806             if (subParm->paramType == P_IGRBRANCHRATES)
10807                 igrvar = *GetParamVals (modelSettings[subParm->relParts[0]].igrvar, chain, state[chain]);
10808             else
10809                 igrvar = *GetParamVals (modelSettings[subParm->relParts[0]].mixedvar, chain, state[chain]);
10810             igrRate = GetParamVals (subParm, chain, state[chain]);
10811
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]);
10818
10819             /* adjust effective branch lengths */
10820             brlens = GetParamSubVals (subParm, chain, state[chain]);
10821             brlens[a->index] = igrRate[a->index] * (a->length + u->length);
10822             }
10823         }   /* next subparameter */
10824
10825     /* cut tree */
10826     a->anc = b;
10827     if (b->left == u)
10828         b->left = a;
10829     else
10830         b->right = a;
10831     a->length += u->length;
10832     a->upDateTi = YES;
10833
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);
10838
10839     /* get downpass parsimony states for the crown part */
10840     GetParsDP (t, v, chain);
10841
10842     /* reset node variables that will be used */
10843     for (i=0; i<t->nNodes; i++)
10844         {
10845         p = t->allDownPass[i];
10846         p->marked = NO;
10847         p->d = 0.0;
10848         }
10849
10850     /* mark nodes in the root part of the tree, first mark a */
10851     a->marked = YES;
10852     /* then move down towards root taking constraints into account */
10853     p = b;
10854     while (p->isLocked == NO && p->anc->anc != NULL)
10855         {
10856         p->marked = YES;
10857         p = p->anc;
10858         }
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--)
10864         {
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)
10868             p->marked = YES;
10869         }
10870
10871     /* unmark nodes if the picked branch is 0 (ancestral fossil) */
10872     if (v->length < TIME_MIN)
10873         {
10874         n = 0;
10875         for (i=0; i<t->nNodes-1; i++)
10876             {
10877             p = t->allDownPass[i];
10878             if (p->nodeDepth > v->nodeDepth - minV || p->anc->nodeDepth < v->nodeDepth + minV)
10879                 p->marked = NO;
10880             if (p->marked == YES)
10881                 n++;
10882             }
10883         if (n < 2)  /* no new position to move */
10884             {
10885             abortMove = YES;
10886             return (NO_ERROR);
10887             }
10888         }
10889     
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));
10893     if (!nSitesOfPat)
10894         {
10895         MrBayesPrint ("%s   Problem allocating nSitesOfPat in Move_ParsSPRClock\n", spacer);
10896         return (ERROR);
10897         }
10898     for (i=0; i<numCompressedChars; i++)
10899         {
10900         nSitesOfPat[i] = globalNSitesOfPat[i];
10901         for (j=0; j<globalNSitesOfPat[i]; j++)
10902             {
10903             ran = RandomNumber(seed);
10904             if (ran < decreaseProb)
10905                 nSitesOfPat[i]--;
10906             else if (ran > 1.0 - increaseProb)
10907                 nSitesOfPat[i]++;
10908             }
10909         }
10910
10911     /* cycle through the possibilities and record the parsimony length */
10912     for (i=0; i<t->nNodes; i++)
10913         {
10914         p = t->allDownPass[i];
10915         if (p->marked == NO)
10916             continue;
10917         /* find the parsimony length */
10918         p->d = 0.0;
10919         for (n=0; n<t->nRelParts; n++)
10920             {
10921             division = t->relParts[n];
10922             
10923             /* Find model settings */
10924             m = &modelSettings[division];
10925
10926             /* find nStates and ratemult */
10927             nStates = m->numModelStates;
10928             if (m->dataType == STANDARD)
10929                 nStates = 2;
10930             rateMult = GetRate(division, chain);
10931
10932             /* find nSitesOfPat */
10933             nSites = nSitesOfPat + m->compCharStart;
10934
10935             /* get division warp factor */
10936             divFactor = - warpFactor * log((1.0/nStates) - exp(-nStates/(nStates-1)*v_typical*rateMult)/nStates);
10937
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     ];
10942             
10943             length = 0.0;
10944             if (m->nParsIntsPerSite == 1)
10945                 {
10946                 for (j=0; j<m->numChars; j++)
10947                     {
10948                     y[0] = (pP[j] | pA[j]) & pV[j];
10949                     if (y[0] == 0)
10950                         length += nSites[j];
10951                     }
10952                 }
10953             else /* if (m->nParsIntsPerSite == 2) */
10954                 {
10955                 for (j=0; j<2*m->numChars; j+=2)
10956                     {
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];
10961                     }
10962                 }
10963             p->d += divFactor * length;
10964             }
10965         }
10966
10967     /* find the min length and the sum for the forward move */
10968     minLength = -1.0;
10969     for (i=0; i<t->nNodes; i++)
10970         {
10971         p = t->allDownPass[i];
10972         if (p->marked == NO || p == a)
10973             continue;
10974         if (minLength < 0.0 || p->d < minLength)
10975             minLength = p->d;
10976         }
10977     sum1 = 0.0;
10978     for (i=0; i<t->nNodes; i++)
10979         {
10980         p = t->allDownPass[i];
10981         if (p->marked == YES && p != a)
10982             sum1 += exp (minLength - p->d);
10983         }
10984
10985     /* generate a random uniform */
10986     ran = RandomNumber(seed) * sum1;
10987
10988     /* select the appropriate reattachment point (not a!) */
10989     cumulativeProb = 0.0;
10990     for (i=0; i<t->nNodes; i++)
10991         {
10992         p = t->allDownPass[i];
10993         if (p->marked == YES && p != a)
10994             {
10995             c = p;
10996             cumulativeProb += exp (minLength - p->d);
10997             if (cumulativeProb > ran)
10998                 break;
10999             }
11000         }
11001
11002     /* calculate the proposal ratio */
11003     (*lnProposalRatio) = c->d - minLength + log(sum1);
11004
11005     /* find the min length and the sum for the backward move */
11006     minLength = -1.0;
11007     for (i=0; i<t->nNodes; i++)
11008         {
11009         p = t->allDownPass[i];
11010         if (p->marked == NO || p == c)
11011             continue;
11012         if (minLength < 0.0 || p->d < minLength)
11013             minLength = p->d;
11014         }
11015     sum2 = 0.0;
11016     for (i=0; i<t->nNodes; i++)
11017         {
11018         p = t->allDownPass[i];
11019         if (p->marked == YES && p != c)
11020             sum2 += exp (minLength - p->d);
11021         }
11022     
11023     /* calculate the proposal ratio */
11024     (*lnProposalRatio) += minLength - a->d - log(sum2);
11025
11026     /* reattach u */
11027     d = c->anc;
11028     c->anc = u;
11029     if (u->left == v)
11030         u->right = c;
11031     else
11032         u->left = c;
11033     u->anc = d;
11034     if (d->left == c)
11035         d->left = u;
11036     else
11037         d->right = u;
11038
11039     if (v->length > 0.0)  /* side branch, not anc fossil */
11040         {
11041         if (c->nodeDepth > v->nodeDepth)
11042             newBrlen = d->nodeDepth - c->nodeDepth - 2.0*minV;
11043         else
11044             newBrlen = d->nodeDepth - v->nodeDepth - 2.0*minV;
11045         if (newBrlen <= 0.0)
11046             {
11047             abortMove = YES;
11048             free (nSitesOfPat);
11049             return (NO_ERROR);
11050             }
11051
11052         /* adjust lengths */
11053         u->nodeDepth = d->nodeDepth - minV - RandomNumber(seed) * newBrlen;
11054         v->length = u->nodeDepth - v->nodeDepth;
11055             
11056         /* calculate proposal ratio for tree change */
11057         (*lnProposalRatio) += log (newBrlen / oldBrlen);
11058         }
11059     u->length = d->nodeDepth - u->nodeDepth;
11060     c->length = u->nodeDepth - c->nodeDepth;
11061     
11062     v3new = v->length;
11063     v4 = c->length;
11064     v5 = u->length;
11065
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++)
11068         {
11069         subParm = param->subParams[0]->subParams[i];
11070         if (subParm->paramType == P_CPPEVENTS)
11071             {
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++)
11076                 {
11077                 if (position[c->index][j] > v4 / (v4+v5))
11078                     break;
11079                 }
11080             n4 = j;
11081             n5 = nEvents[c->index] - j;
11082             nEvents[u->index] = n5;
11083             if (n5 > 0)
11084                 {
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++)
11088                     {
11089                     position[u->index][j-n4] = (position[c->index][j] * (v4+v5) - v4) / v5;
11090                     rateMultiplier[u->index][j-n4] = rateMultiplier[c->index][j];
11091                     }
11092                 if (n4 > 0)
11093                     {
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);
11098                     }
11099                 else
11100                     {
11101                     free (position[c->index]);
11102                     free (rateMultiplier[c->index]);
11103                     position[c->index] = rateMultiplier[c->index] = NULL;
11104                     }
11105                 nEvents[c->index] = n4;
11106                 }
11107             else
11108                 {
11109                 for (j=0; j<nEvents[c->index]; j++)
11110                     position[c->index][j] *= ((v4+v5) / v4);
11111                 }
11112
11113             /* adjust proposal ratio */
11114             (*lnProposalRatio) += n3 * log (v3new / v3);
11115
11116             /* adjust prior ratio */
11117             lambda = *GetParamVals (modelSettings[subParm->relParts[0]].cppRate, chain, state[chain]);
11118             (*lnPriorRatio) += lambda * (v3 - v3new);
11119
11120             /* update effective branch lengths */
11121             if (UpdateCppEvolLengths (subParm, a, chain) == ERROR)
11122                 {
11123                 abortMove = YES;
11124                 free (nSitesOfPat);
11125                 return (NO_ERROR);
11126                 }
11127
11128             if (UpdateCppEvolLengths (subParm, u, chain) == ERROR)
11129                 {
11130                 abortMove = YES;
11131                 free (nSitesOfPat);
11132                 return (NO_ERROR);
11133                 }
11134             }   /* end cpp events parameter */
11135         else if ( subParm->paramType == P_TK02BRANCHRATES ||
11136                  (subParm->paramType == P_MIXEDBRCHRATES && *GetParamIntVals(subParm, chain, state[chain]) == RCL_TK02))
11137             {
11138             /* adjust prior ratio */
11139             if (subParm->paramType == P_TK02BRANCHRATES)
11140                 nu = *GetParamVals (modelSettings[subParm->relParts[0]].tk02var, chain, state[chain]);
11141             else
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]);
11149
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))
11158             {
11159             /* adjust prior ratio */
11160             if (subParm->paramType == P_IGRBRANCHRATES)
11161                 igrvar = *GetParamVals (modelSettings[subParm->relParts[0]].igrvar, chain, state[chain]);
11162             else
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]);
11170
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 */
11178
11179     /* set tiprobs update flags */
11180     c->upDateTi = YES;
11181     u->upDateTi = YES;
11182     v->upDateTi = YES;
11183
11184     /* set flags for update of cond likes down to root */
11185     p = u;
11186     while (p->anc != NULL)
11187         {
11188         p->upDateCl = YES; 
11189         p = p->anc;
11190         }
11191     p = b;
11192     while (p->anc != NULL)
11193         {
11194         p->upDateCl = YES; 
11195         p = p->anc;
11196         }
11197
11198     /* get down pass sequence */
11199     GetDownPass (t);
11200
11201     /* adjust prior ratio for clock tree */
11202     if (LogClockTreePriorRatio (param, chain, &x) == ERROR)
11203         {
11204         free (nSitesOfPat);
11205         return (ERROR);
11206         }
11207     (*lnPriorRatio) += x;
11208
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);
11213     getchar();
11214 #   endif
11215
11216     free (nSitesOfPat);
11217     return (NO_ERROR);
11218 }
11219
11220
11221 int Move_ParsTBR1 (Param *param, int chain, RandLong *seed, MrBFlt *lnPriorRatio, MrBFlt *lnProposalRatio, MrBFlt *mvp)
11222 {
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. */
11225     
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;
11232     Tree        *t;
11233     ModelParams *mp;
11234     ModelInfo   *m=NULL;
11235     
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 */
11241
11242     (*lnProposalRatio) = (*lnPriorRatio) = 0.0;
11243     
11244     /* get model params and model info */
11245     mp = &modelParams[param->relParts[0]];
11246     m = &modelSettings[param->relParts[0]];
11247     
11248     /* get tree */
11249     t = GetTree (param, chain, state[chain]);
11250     
11251     /* max and min brlen */
11252     if (param->subParams[0]->paramId == BRLENS_UNI)
11253         {
11254         minV = mp->brlensUni[0] > BRLENS_MIN ? mp->brlensUni[0] : BRLENS_MIN;
11255         maxV = mp->brlensUni[1] < BRLENS_MAX ? mp->brlensUni[1] : BRLENS_MAX;
11256         isVPriorExp = NO;
11257         }
11258     else if (param->subParams[0]->paramId == BRLENS_GamDir)
11259         {
11260         minV = BRLENS_MIN;
11261         maxV = BRLENS_MAX;
11262         isVPriorExp = 2;
11263         }
11264     else if (param->subParams[0]->paramId == BRLENS_iGmDir)
11265         {
11266         minV = BRLENS_MIN;
11267         maxV = BRLENS_MAX;
11268         isVPriorExp = 3;
11269         }
11270     else if (param->subParams[0]->paramId == BRLENS_twoExp)
11271         {
11272         minV = BRLENS_MIN;
11273         maxV = BRLENS_MAX;
11274         isVPriorExp = 4;
11275         }
11276     else
11277         {
11278         minV = BRLENS_MIN;
11279         maxV = BRLENS_MAX;
11280         brlensExp = mp->brlensExp;
11281         isVPriorExp = YES;
11282         }
11283
11284     /* Dirichlet or twoExp prior */
11285     if (isVPriorExp > 1)
11286         (*lnPriorRatio) = -LogDirPrior(t, mp, isVPriorExp);
11287     
11288     /* set topologyHasChanged to NO */
11289     topologyHasChanged = NO;
11290     
11291     /* reset node variables that will be used */
11292     for (i=0; i<t->nNodes; i++)
11293         {
11294         p = t->allDownPass[i];
11295         p->x = 0;
11296         p->marked = NO;
11297         }
11298
11299     /* pick an internal branch */
11300     do  {
11301         p = t->intDownPass[(int)(RandomNumber(seed)*(t->nIntNodes-1))];
11302         q = p->anc->left;
11303         if (q == p)  q = p->anc->right;
11304         i = j = 0;
11305         if (q->isLocked == YES || q->left == NULL)
11306             i++;
11307         if (p->anc->isLocked == YES || p->anc->anc->anc == NULL)
11308             i++;
11309         if (p->left->isLocked == YES || p->left->left == NULL)
11310             j++;
11311         if (p->right->isLocked == YES || p->right->left == NULL)
11312             j++;
11313         }
11314     while (i == 2 && j == 2);
11315     
11316     /* set up pointers for nodes around the picked branch */
11317     v = p;            u = p->anc;
11318     c = p->left;      d = p->right;
11319     if (u->left == v) a = u->right;
11320     else              a = u->left;
11321     b = u->anc;
11322     /* clip root part of tree */
11323     a->anc = b;
11324     if (b->left == u) b->left = a;
11325     else              b->right = a;
11326     /* clip crown part of tree */
11327     c->anc = d;
11328     d->anc = c;
11329     /* should never change u, v, a, b, c, d pointers */
11330
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)
11335         {
11336         p = a; q = b; n = 0;
11337         while (q->anc != NULL)
11338             {
11339             q->marked = YES;
11340             q->x = n;    // temporary, for MarkDistance below
11341             if (q->left == p)
11342                 MarkDistance(q->right, YES, nNeighbor, &nRoot);
11343             else
11344                 MarkDistance(q->left,  YES, nNeighbor, &nRoot);
11345             q->x = --n;  // final
11346             nRoot++;
11347             if (q->isLocked == YES || abs(q->x) >= nNeighbor)
11348                 break;
11349             p = q; q = q->anc;
11350             }
11351         }
11352     /* then move up in root part */
11353     a->marked = YES; nRoot++;
11354     if (a->isLocked == NO)
11355         {
11356         MarkDistance(a->left,  YES, nNeighbor, &nRoot);
11357         MarkDistance(a->right, YES, nNeighbor, &nRoot);
11358         }
11359     /* finally in crown part */
11360     c->marked = YES; nCrown++;
11361     if (c->isLocked == NO)
11362         {
11363         MarkDistance(c->left,  NO, nNeighbor, &nCrown);
11364         MarkDistance(c->right, NO, nNeighbor, &nCrown);
11365         }
11366     if (d->isLocked == NO)
11367         {
11368         MarkDistance(d->left,  NO, nNeighbor, &nCrown);
11369         MarkDistance(d->right, NO, nNeighbor, &nCrown);
11370         }
11371
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)
11384             pRoot[i++] = p;
11385         if (p->marked == YES && p->x > 0)
11386             pCrown[j++] = p;
11387         }
11388     assert (i==nRoot && j==nCrown);
11389
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);
11398
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++)
11404         {
11405         nSitesOfPat[i] = globalNSitesOfPat[i];
11406     /*  for (j=0; j<globalNSitesOfPat[i]; j++)
11407             {
11408             ran = RandomNumber(seed);
11409             if (ran < decreaseProb)
11410                 nSitesOfPat[i]--;
11411             else if (ran > 1.0 - increaseProb)
11412                 nSitesOfPat[i]++;
11413             }  // this is not used at the moment */
11414         }
11415
11416     /* cycle through the possibilities and record the parsimony length */
11417     for (j=0; j<nCrown; j++)
11418         {
11419         for (i=0; i<nRoot; i++)
11420             {
11421             parLength[i+j*nRoot] = 0.0;
11422             for (n=0; n<t->nRelParts; n++)
11423                 {
11424                 division = t->relParts[n];
11425                 
11426                 /* Find model settings */
11427                 m = &modelSettings[division];
11428                 
11429                 /* find nSitesOfPat */
11430                 nSites = nSitesOfPat + m->compCharStart;
11431                     
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];
11437                     
11438                 length = 0.0;
11439                 if (m->nParsIntsPerSite == 1)
11440                     {
11441                     for (k=0; k<m->numChars; k++)
11442                         {
11443                         y[0] = (pC[k] | pD[k]) & (pA[k] | pB[k]);
11444                         if (y[0] == 0)
11445                             length += nSites[k];
11446                         }
11447                     }
11448                 else /* if (m->nParsIntsPerSite == 2) */
11449                     {
11450                     for (k=0; k<2*m->numChars; k+=2)
11451                         {
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];
11456                         }
11457                     }
11458                 parLength[i+j*nRoot] += warpFactor * length;
11459                 }
11460             }
11461         }
11462
11463     /* find the min length and the sum for the forward move */
11464     minLength = -1.0;
11465     for (j=0; j<nCrown; j++)
11466         for (i=0; i<nRoot; i++)
11467             {
11468             if (i == 0 && j == 0)  // exclude original position
11469                 continue;
11470             if (minLength > parLength[i+j*nRoot] || minLength < 0.0)
11471                 minLength = parLength[i+j*nRoot];
11472             }
11473     sum1 = 0.0; tempc = 0.0;
11474     for (j=0; j<nCrown; j++)
11475         for (i=0; i<nRoot; i++)
11476             {
11477             if (i == 0 && j == 0)  // exclude original position
11478                 continue;
11479             /* Kahan summation to reduce numerical error */
11480             tempy = exp(minLength - parLength[i+j*nRoot]) - tempc;
11481             tempsum = sum1 + tempy;  tempc = (tempsum - sum1) - tempy;
11482             sum1 = tempsum;
11483             // sum1 += exp(minLength - parLength[i+j*nRoot]);
11484             // printf("%d %d %lf\n", i, j, exp(minLength - parLength[i+j*nRoot]));
11485             }
11486
11487     /* generate a random uniform */
11488     ran = RandomNumber(seed) * sum1;
11489
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++)
11495             {
11496             if (i == 0 && j == 0)  // exclude original position
11497                 continue;
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;
11502             prob = tempsum;
11503             if (prob > ran) {
11504                 /* proposed new attaching position */
11505                 newA = pRoot[i];
11506                 newC = pCrown[j];
11507                 goto outLoop;
11508                 }
11509             }
11510 outLoop:;
11511     iA = i; jC = j;
11512
11513     /* calculate the proposal ratio */
11514     (*lnProposalRatio) = parLength[i+j*nRoot] - minLength + log(sum1);
11515
11516     /* find the min length and the sum for the backward move */
11517     minLength = -1.0;
11518     for (j=0; j<nCrown; j++)
11519         for (i=0; i<nRoot; i++)
11520             {
11521             if (i == iA && j == jC)  // exclude new position
11522                 continue;
11523             if (minLength > parLength[i+j*nRoot] || minLength < 0.0)
11524                 minLength = parLength[i+j*nRoot];
11525             }
11526     sum2 = 0.0; tempc = 0.0;
11527     for (j=0; j<nCrown; j++)
11528         for (i=0; i<nRoot; i++)
11529             {
11530             if (i == iA && j == jC)  // exclude new position
11531                 continue;
11532             /* Kahan summation to reduce numerical error */
11533             tempy = exp(minLength - parLength[i+j*nRoot]) - tempc;
11534             tempsum = sum2 + tempy;  tempc = (tempsum - sum2) - tempy;
11535             sum2 = tempsum;
11536             // sum2 += exp (minLength - parLength[i+j*nRoot]);
11537             // printf("%d %d %lf\n", i, j, exp(minLength - parLength[i+j*nRoot]));
11538             }
11539
11540     /* calculate the proposal ratio */
11541     (*lnProposalRatio) += minLength - parLength[0] - log(sum2);
11542
11543     /* reattach the root part */
11544     newB = newA->anc;
11545     newA->anc = u;
11546     if (u->left == v)
11547         u->right = newA;
11548     else
11549         u->left = newA;
11550     u->anc = newB;
11551     if (newB->left == newA)
11552         newB->left = u;
11553     else
11554         newB->right = u;
11555
11556     /* transfer lock and reassign branch lengths, if necessary */
11557     if (newA != a)
11558         {
11559         /* if u is locked, then we have moved upwards and need to leave the u lock behind */
11560         if (u->isLocked == YES)
11561             {
11562             u->isLocked = NO;
11563             a->isLocked = YES;
11564             a->lockID = u->lockID;
11565             u->lockID = -1;
11566             }
11567
11568         p = newA;
11569         while (p->anc != NULL)
11570             {
11571             if (p == a) break;
11572             p = p->anc;
11573             }
11574         if (p == a)
11575             {
11576             /* newA is descendant to a so move a->length not u->length */
11577             x = u->length;
11578             u->length = a->length;
11579             a->length = x;
11580             }
11581
11582         p = b;
11583         while (p->anc != NULL)
11584             {
11585             if (p == newA) break;
11586             p = p->anc;
11587             }
11588         if (p == newA)
11589             {
11590             /* newA is ancestor to a so insert above instead of below */
11591             x = newA->length;
11592             newA->length = u->length;
11593             u->length = x;
11594             /* newA is on root path and locked, we need to transfer lock to u */
11595             if (newA->isLocked == YES) {
11596                 u->isLocked = YES;
11597                 u->lockID = newA->lockID;
11598                 newA->isLocked = NO;
11599                 newA->lockID = -1;
11600                 }
11601             }
11602             
11603         /* hit u length with multiplier */
11604         x = u->length * exp(tuning * (RandomNumber(seed) - 0.5));
11605         while (x < minV || x > maxV)
11606             {
11607             if (x < minV) x = minV * minV / x;
11608             if (x > maxV) x = maxV * maxV / x;
11609             }
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);
11614         u->length = x;
11615
11616         /* set tiprobs update flags */
11617         u->upDateTi = YES;
11618         newA->upDateTi = YES;
11619         a->upDateTi = YES;
11620         }
11621     
11622     r = newC;
11623     q = newB = newC->anc;
11624     if (newC != c)  // crown part has changed
11625         {
11626         /* rotate nodes from newC to c or d (whichever is closest) */
11627         tempc = r->length;
11628         while (r != c && r != d)
11629             {
11630             p = q->anc;
11631             /* rotate pointers of q */
11632             if (q->left == r)
11633                 q->left = p;
11634             else
11635                 q->right = p;
11636             q->anc = r;
11637             /* swap q and old */
11638             tempy = q->length;
11639             q->length = tempc;
11640             q->upDateTi = YES;
11641             tempc = tempy;
11642             /* make sure we get q and r initialized for next round */
11643             r = q;
11644             q = p;
11645             }
11646         newB->length = tempc;
11647         
11648         /* hit newB length with multiplier */
11649         x = newB->length * exp(tuning * (RandomNumber(seed) - 0.5));
11650         while (x < minV || x > maxV)
11651             {
11652             if (x < minV) x = minV * minV / x;
11653             if (x > maxV) x = maxV * maxV / x;
11654             }
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);
11659         newB->length = x;
11660         newB->upDateTi = YES;
11661         }
11662     
11663     /* reattach the crown part */
11664     v->left = newC;
11665     v->right = newB;
11666     newC->anc = newB->anc = v;
11667     
11668     topologyHasChanged = YES;
11669     
11670     /* hit v length with multiplier */
11671     x = v->length * exp(tuning * (RandomNumber(seed) - 0.5));
11672     while (x < minV || x > maxV)
11673         {
11674         if (x < minV) x = minV * minV / x;
11675         if (x > maxV) x = maxV * maxV / x;
11676         }
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);
11681     v->length = x;
11682     v->upDateTi = YES;
11683  
11684     /* set flags for update of cond likes */
11685     p = u;
11686     while (p->anc != NULL)
11687         {
11688         p->upDateCl = YES;
11689         p = p->anc;
11690         }
11691     p = b;
11692     while (p->anc != NULL)
11693         {
11694         p->upDateCl = YES;
11695         p = p->anc;
11696         }
11697     p = newC;
11698     while (p->anc != NULL)
11699         {
11700         p->upDateCl = YES;
11701         p = p->anc;
11702         }
11703     p = r;
11704     while (p->anc != NULL)
11705         {
11706         p->upDateCl = YES;
11707         p = p->anc;
11708         }
11709     
11710     /* get down pass sequence if tree topology has changed */
11711     if (topologyHasChanged == YES)
11712         {
11713         GetDownPass (t);
11714         }
11715
11716     /* Dirichlet or twoExp prior */
11717     if (isVPriorExp > 1)
11718         (*lnPriorRatio) += LogDirPrior(t, mp, isVPriorExp);
11719     
11720     /* free up local memory */
11721     free (parLength); free (pRoot); free (pCrown); free (nSitesOfPat);
11722
11723     return (NO_ERROR);
11724
11725 errorExit:
11726     MrBayesPrint ("%s   Problem allocating memory in Move_ParsTBR\n", spacer);
11727     free (parLength); free (pRoot); free (pCrown); free (nSitesOfPat);
11728
11729     return (ERROR);
11730 }
11731
11732
11733 int Move_ParsTBR2 (Param *param, int chain, RandLong *seed, MrBFlt *lnPriorRatio, MrBFlt *lnProposalRatio, MrBFlt *mvp)
11734 {
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. */
11737     
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;
11744     Tree        *t;
11745     ModelParams *mp;
11746     ModelInfo   *m=NULL;
11747     
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 */
11753
11754     (*lnProposalRatio) = (*lnPriorRatio) = 0.0;
11755     
11756     /* get model params and model info */
11757     mp = &modelParams[param->relParts[0]];
11758     m = &modelSettings[param->relParts[0]];
11759     
11760     /* get tree */
11761     t = GetTree (param, chain, state[chain]);
11762     
11763     /* max and min brlen */
11764     if (param->subParams[0]->paramId == BRLENS_UNI)
11765         {
11766         minV = mp->brlensUni[0] > BRLENS_MIN ? mp->brlensUni[0] : BRLENS_MIN;
11767         maxV = mp->brlensUni[1] < BRLENS_MAX ? mp->brlensUni[1] : BRLENS_MAX;
11768         isVPriorExp = NO;
11769         }
11770     else if (param->subParams[0]->paramId == BRLENS_GamDir)
11771         {
11772         minV = BRLENS_MIN;
11773         maxV = BRLENS_MAX;
11774         isVPriorExp = 2;
11775         }
11776     else if (param->subParams[0]->paramId == BRLENS_iGmDir)
11777         {
11778         minV = BRLENS_MIN;
11779         maxV = BRLENS_MAX;
11780         isVPriorExp = 3;
11781         }
11782     else if (param->subParams[0]->paramId == BRLENS_twoExp)
11783         {
11784         minV = BRLENS_MIN;
11785         maxV = BRLENS_MAX;
11786         isVPriorExp = 4;
11787         }
11788     else
11789         {
11790         minV = BRLENS_MIN;
11791         maxV = BRLENS_MAX;
11792         brlensExp = mp->brlensExp;
11793         isVPriorExp = YES;
11794         }
11795
11796     /* Dirichlet or twoExp prior */
11797     if (isVPriorExp > 1)
11798         (*lnPriorRatio) = -LogDirPrior(t, mp, isVPriorExp);
11799     
11800     /* set topologyHasChanged to NO */
11801     topologyHasChanged = NO;
11802     
11803     /* reset node variables that will be used */
11804     for (i=0; i<t->nNodes; i++)
11805         {
11806         p = t->allDownPass[i];
11807         p->x = 0;
11808         p->marked = NO;
11809         }
11810
11811     /* pick an internal branch */
11812     do  {
11813         p = t->intDownPass[(int)(RandomNumber(seed)*(t->nIntNodes-1))];
11814         q = p->anc->left;
11815         if (q == p)  q = p->anc->right;
11816         i = j = 0;
11817         if (q->isLocked == YES || q->left == NULL)
11818             i++;
11819         if (p->anc->isLocked == YES || p->anc->anc->anc == NULL)
11820             i++;
11821         if (p->left->isLocked == YES || p->left->left == NULL)
11822             j++;
11823         if (p->right->isLocked == YES || p->right->left == NULL)
11824             j++;
11825         }
11826     while (i == 2 && j == 2);
11827     
11828     /* set up pointers for nodes around the picked branch */
11829     v = p;            u = p->anc;
11830     c = p->left;      d = p->right;
11831     if (u->left == v) a = u->right;
11832     else              a = u->left;
11833     b = u->anc;
11834     /* clip root part of tree */
11835     a->anc = b;
11836     if (b->left == u) b->left = a;
11837     else              b->right = a;
11838     /* clip crown part of tree */
11839     c->anc = d;
11840     d->anc = c;
11841     /* should never change u, v, a, b, c, d pointers */
11842
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)
11847         {
11848         p = a; q = b; n = 0;
11849         while (q->anc != NULL)
11850             {
11851             q->marked = YES;
11852             q->x = n;    // temporary, for MarkDistance below
11853             if (q->left == p)
11854                 MarkDistance(q->right, YES, nNeighbor, &nRoot);
11855             else
11856                 MarkDistance(q->left,  YES, nNeighbor, &nRoot);
11857             q->x = --n;  // final
11858             nRoot++;
11859             if (q->isLocked == YES || abs(q->x) >= nNeighbor)
11860                 break;
11861             p = q; q = q->anc;
11862             }
11863         }
11864     /* then move up in root part */
11865     a->marked = YES; nRoot++;
11866     if (a->isLocked == NO)
11867         {
11868         MarkDistance(a->left,  YES, nNeighbor, &nRoot);
11869         MarkDistance(a->right, YES, nNeighbor, &nRoot);
11870         }
11871     /* finally in crown part */
11872     c->marked = YES; nCrown++;
11873     if (c->isLocked == NO)
11874         {
11875         MarkDistance(c->left,  NO, nNeighbor, &nCrown);
11876         MarkDistance(c->right, NO, nNeighbor, &nCrown);
11877         }
11878     if (d->isLocked == NO)
11879         {
11880         MarkDistance(d->left,  NO, nNeighbor, &nCrown);
11881         MarkDistance(d->right, NO, nNeighbor, &nCrown);
11882         }
11883
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)
11896             pRoot[i++] = p;
11897         if (p->marked == YES && p->x > 0)
11898             pCrown[j++] = p;
11899         }
11900     assert (i==nRoot && j==nCrown);
11901
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);
11910
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++)
11916         {
11917         nSitesOfPat[i] = globalNSitesOfPat[i];
11918     /*  for (j=0; j<globalNSitesOfPat[i]; j++)
11919             {
11920             ran = RandomNumber(seed);
11921             if (ran < decreaseProb)
11922                 nSitesOfPat[i]--;
11923             else if (ran > 1.0 - increaseProb)
11924                 nSitesOfPat[i]++;
11925             }  // this is not used at the moment */
11926         }
11927
11928     /* cycle through the possibilities and record the parsimony length */
11929     for (j=0; j<nCrown; j++)
11930         {
11931         for (i=0; i<nRoot; i++)
11932             {
11933             parLength[i+j*nRoot] = 0.0;
11934             for (n=0; n<t->nRelParts; n++)
11935                 {
11936                 division = t->relParts[n];
11937                 
11938                 /* Find model settings */
11939                 m = &modelSettings[division];
11940                 
11941                 /* find nSitesOfPat */
11942                 nSites = nSitesOfPat + m->compCharStart;
11943                 
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];
11949                     
11950                 length = 0.0;
11951                 if (m->nParsIntsPerSite == 1)
11952                     {
11953                     for (k=0; k<m->numChars; k++)
11954                         {
11955                         y[0] = (pC[k] | pD[k]) & (pA[k] | pB[k]);
11956                         if (y[0] == 0)
11957                             length += nSites[k];
11958                         }
11959                     }
11960                 else /* if (m->nParsIntsPerSite == 2) */
11961                     {
11962                     for (k=0; k<2*m->numChars; k+=2)
11963                         {
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];
11968                         }
11969                     }
11970                     
11971                 /* find nStates and ratemult */
11972                 nStates = m->numModelStates;
11973                 if (m->dataType == STANDARD)
11974                     nStates = 2;
11975                 v_typical = length/m->numUncompressedChars + 0.0001;
11976                 
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;
11980                 }
11981             }
11982         }
11983
11984     /* find the min length and the sum for the forward move */
11985     minLength = -1.0;
11986     for (j=0; j<nCrown; j++)
11987         for (i=0; i<nRoot; i++)
11988             {
11989             if (i == 0 && j == 0)  // exclude original position
11990                 continue;
11991             if (minLength > parLength[i+j*nRoot] || minLength < 0.0)
11992                 minLength = parLength[i+j*nRoot];
11993             }
11994     sum1 = 0.0; tempc = 0.0;
11995     for (j=0; j<nCrown; j++)
11996         for (i=0; i<nRoot; i++)
11997             {
11998             if (i == 0 && j == 0)  // exclude original position
11999                 continue;
12000             /* Kahan summation to reduce numerical error */
12001             tempy = exp(minLength - parLength[i+j*nRoot]) - tempc;
12002             tempsum = sum1 + tempy;  tempc = (tempsum - sum1) - tempy;
12003             sum1 = tempsum;
12004             // sum1 += exp(minLength - parLength[i+j*nRoot]);
12005             // printf("%d %d %lf\n", i, j, exp(minLength - parLength[i+j*nRoot]));
12006             }
12007
12008     /* generate a random uniform */
12009     ran = RandomNumber(seed) * sum1;
12010
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++)
12016             {
12017             if (i == 0 && j == 0)  // exclude original position
12018                 continue;
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;
12023             prob = tempsum;
12024             if (prob > ran) {
12025                 /* proposed new attaching position */
12026                 newA = pRoot[i];
12027                 newC = pCrown[j];
12028                 goto outLoop;
12029                 }
12030             }
12031 outLoop:;
12032     iA = i; jC = j;
12033
12034     /* calculate the proposal ratio */
12035     (*lnProposalRatio) = parLength[i+j*nRoot] - minLength + log(sum1);
12036
12037     /* find the min length and the sum for the backward move */
12038     minLength = -1.0;
12039     for (j=0; j<nCrown; j++)
12040         for (i=0; i<nRoot; i++)
12041             {
12042             if (i == iA && j == jC)  // exclude new position
12043                 continue;
12044             if (minLength > parLength[i+j*nRoot] || minLength < 0.0)
12045                 minLength = parLength[i+j*nRoot];
12046             }
12047     sum2 = 0.0; tempc = 0.0;
12048     for (j=0; j<nCrown; j++)
12049         for (i=0; i<nRoot; i++)
12050             {
12051             if (i == iA && j == jC)  // exclude new position
12052                 continue;
12053             /* Kahan summation to reduce numerical error */
12054             tempy = exp(minLength - parLength[i+j*nRoot]) - tempc;
12055             tempsum = sum2 + tempy;  tempc = (tempsum - sum2) - tempy;
12056             sum2 = tempsum;
12057             // sum2 += exp (minLength - parLength[i+j*nRoot]);
12058             // printf("%d %d %lf\n", i, j, exp(minLength - parLength[i+j*nRoot]));
12059             }
12060
12061     /* calculate the proposal ratio */
12062     (*lnProposalRatio) += minLength - parLength[0] - log(sum2);
12063
12064     /* reattach the root part */
12065     newB = newA->anc;
12066     newA->anc = u;
12067     if (u->left == v)
12068         u->right = newA;
12069     else
12070         u->left = newA;
12071     u->anc = newB;
12072     if (newB->left == newA)
12073         newB->left = u;
12074     else
12075         newB->right = u;
12076
12077     /* transfer lock and reassign branch lengths, if necessary */
12078     if (newA != a)
12079         {
12080         /* if u is locked, then we have moved upwards and need to leave the u lock behind */
12081         if (u->isLocked == YES)
12082             {
12083             u->isLocked = NO;
12084             a->isLocked = YES;
12085             a->lockID = u->lockID;
12086             u->lockID = -1;
12087             }
12088
12089         p = newA;
12090         while (p->anc != NULL)
12091             {
12092             if (p == a) break;
12093             p = p->anc;
12094             }
12095         if (p == a)
12096             {
12097             /* newA is descendant to a so move a->length not u->length */
12098             x = u->length;
12099             u->length = a->length;
12100             a->length = x;
12101             }
12102
12103         p = b;
12104         while (p->anc != NULL)
12105             {
12106             if (p == newA) break;
12107             p = p->anc;
12108             }
12109         if (p == newA)
12110             {
12111             /* newA is ancestor to a so insert above instead of below */
12112             x = newA->length;
12113             newA->length = u->length;
12114             u->length = x;
12115             /* newA is on root path and locked, we need to transfer lock to u */
12116             if (newA->isLocked == YES) {
12117                 u->isLocked = YES;
12118                 u->lockID = newA->lockID;
12119                 newA->isLocked = NO;
12120                 newA->lockID = -1;
12121                 }
12122             }
12123             
12124         /* hit u length with multiplier */
12125         x = u->length * exp(tuning * (RandomNumber(seed) - 0.5));
12126         while (x < minV || x > maxV)
12127             {
12128             if (x < minV) x = minV * minV / x;
12129             if (x > maxV) x = maxV * maxV / x;
12130             }
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);
12135         u->length = x;
12136
12137         /* set tiprobs update flags */
12138         u->upDateTi = YES;
12139         newA->upDateTi = YES;
12140         a->upDateTi = YES;
12141         }
12142     
12143     r = newC;
12144     q = newB = newC->anc;
12145     if (newC != c)  // crown part has changed
12146         {
12147         /* rotate nodes from newC to c or d (whichever is closest) */
12148         tempc = r->length;
12149         while (r != c && r != d)
12150             {
12151             p = q->anc;
12152             /* rotate pointers of q */
12153             if (q->left == r)
12154                 q->left = p;
12155             else
12156                 q->right = p;
12157             q->anc = r;
12158             /* swap q and old */
12159             tempy = q->length;
12160             q->length = tempc;
12161             q->upDateTi = YES;
12162             tempc = tempy;
12163             /* make sure we get q and r initialized for next round */
12164             r = q;
12165             q = p;
12166             }
12167         newB->length = tempc;
12168         
12169         /* hit newB length with multiplier */
12170         x = newB->length * exp(tuning * (RandomNumber(seed) - 0.5));
12171         while (x < minV || x > maxV)
12172             {
12173             if (x < minV) x = minV * minV / x;
12174             if (x > maxV) x = maxV * maxV / x;
12175             }
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);
12180         newB->length = x;
12181         newB->upDateTi = YES;
12182         }
12183     
12184     /* reattach the crown part */
12185     v->left = newC;
12186     v->right = newB;
12187     newC->anc = newB->anc = v;
12188     
12189     topologyHasChanged = YES;
12190     
12191     /* hit v length with multiplier */
12192     x = v->length * exp(tuning * (RandomNumber(seed) - 0.5));
12193     while (x < minV || x > maxV)
12194         {
12195         if (x < minV) x = minV * minV / x;
12196         if (x > maxV) x = maxV * maxV / x;
12197         }
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);
12202     v->length = x;
12203     v->upDateTi = YES;
12204  
12205     /* set flags for update of cond likes */
12206     p = u;
12207     while (p->anc != NULL)
12208         {
12209         p->upDateCl = YES;
12210         p = p->anc;
12211         }
12212     p = b;
12213     while (p->anc != NULL)
12214         {
12215         p->upDateCl = YES;
12216         p = p->anc;
12217         }
12218     p = newC;
12219     while (p->anc != NULL)
12220         {
12221         p->upDateCl = YES;
12222         p = p->anc;
12223         }
12224     p = r;
12225     while (p->anc != NULL)
12226         {
12227         p->upDateCl = YES;
12228         p = p->anc;
12229         }
12230     
12231     /* get down pass sequence if tree topology has changed */
12232     if (topologyHasChanged == YES)
12233         {
12234         GetDownPass (t);
12235         }
12236
12237     /* Dirichlet or twoExp prior */
12238     if (isVPriorExp > 1)
12239         (*lnPriorRatio) += LogDirPrior(t, mp, isVPriorExp);
12240     
12241     /* free up local memory */
12242     free (parLength); free (pRoot); free (pCrown); free (nSitesOfPat);
12243
12244     return (NO_ERROR);
12245
12246 errorExit:
12247     MrBayesPrint ("%s   Problem allocating memory in Move_ParsTBR\n", spacer);
12248     free (parLength); free (pRoot); free (pCrown); free (nSitesOfPat);
12249
12250     return (ERROR);
12251 }
12252
12253
12254 int Move_Pinvar (Param *param, int chain, RandLong *seed, MrBFlt *lnPriorRatio, MrBFlt *lnProposalRatio, MrBFlt *mvp)
12255 {
12256     /* change proportion of invariable sites (pInvar) */
12257
12258     int             i, c, isValidP, *rateCat, nGammaCats;
12259     MrBFlt          oldP, newP, window, minP, maxP, ran, lnInvarRatio, lnVarRatio;
12260     CLFlt           *nSitesOfPat;
12261     ModelParams     *mp;
12262     ModelInfo       *m;
12263
12264     /* get size of window, centered on current pInvar value */
12265     window = mvp[0];
12266
12267     /* get model params */
12268     mp = &modelParams[param->relParts[0]];
12269     
12270     /* get minimum and maximum values for pInvar */
12271     minP = mp->pInvarUni[0];
12272     maxP = mp->pInvarUni[1];
12273
12274     /* get old value of pInvar */
12275     newP = oldP = *GetParamVals(param, chain, state[chain]);
12276
12277     /* change value for pInvar */
12278     ran = RandomNumber(seed);
12279     if (maxP-minP < window)
12280         {
12281         window = maxP-minP;
12282         }
12283
12284     newP = oldP + window * (ran - 0.5);
12285
12286     /* check validity */
12287     isValidP = NO;
12288     do
12289         {
12290         if (newP < minP)
12291             newP = 2* minP - newP;
12292         else if (newP > maxP)
12293             newP = 2 * maxP - newP;
12294         else
12295             isValidP = YES;
12296         } while (isValidP == NO);
12297
12298     /* get proposal ratio */
12299     *lnProposalRatio = 0.0;
12300     
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++)
12306         {
12307         m = &modelSettings[param->relParts[i]];
12308         if (m->gibbsGamma == YES)
12309             {
12310             /* find rate category index and number of gamma categories */
12311             rateCat = m->tiIndex + chain * m->numChars;
12312             nGammaCats = m->numGammaCats;
12313
12314             /* find nSitesOfPat */
12315             nSitesOfPat = numSitesOfPat + (chainId[chain] % chainParams.numChains)*numCompressedChars + m->compCharStart;
12316             
12317             /* loop over characters */
12318             for (c=0; c<m->numChars; c++)
12319                 {
12320                 if (rateCat[c] < nGammaCats)
12321                     *lnPriorRatio += lnVarRatio * nSitesOfPat[c];
12322                 else
12323                     *lnPriorRatio += lnInvarRatio * nSitesOfPat[c];
12324                 }
12325             }
12326         }
12327     
12328     /* copy new pInvar value back */
12329     *GetParamVals(param, chain, state[chain]) = newP;
12330
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);
12335     
12336     /* However, you do need to update cijk flags if this is a covarion model */
12337     /* TO DO */
12338     
12339     return (NO_ERROR);
12340 }
12341
12342
12343 int Move_PopSize_M (Param *param, int chain, RandLong *seed, MrBFlt *lnPriorRatio, MrBFlt *lnProposalRatio, MrBFlt *mvp)
12344 {
12345     int             isValidN, valIndex;
12346     MrBFlt          *valPtr, oldN, newN, tuning, minN, maxN, ran, oldLnPrior, newLnPrior, growth,
12347                     oldT, newT, clockRate;
12348     ModelParams     *mp;
12349     ModelInfo       *m;
12350     Tree            *t;
12351
12352     /* get multiplier tuning parameter */
12353     tuning = mvp[0];
12354
12355     /* get model params */
12356     mp = &modelParams[param->relParts[0]];
12357     
12358     /* get model settings */
12359     m = &modelSettings[param->relParts[0]];
12360
12361     /* get minimum and maximum values for population size */
12362     if (param->paramId == POPSIZE_UNI)
12363         {
12364         minN = mp->popSizeUni[0];
12365         maxN = mp->popSizeUni[1];
12366         }
12367     else
12368         {
12369         minN = 0.00001;
12370         maxN = 10000000;
12371         }
12372
12373     /* get pointer to value to be changed */
12374     valIndex = (int)(RandomNumber(seed) * param->nValues);
12375     valPtr = GetParamVals(param, chain, state[chain]) + valIndex;
12376
12377     /* get old value of population size */
12378     oldN = *valPtr;
12379
12380     /* get old prior for species tree coalescence */
12381     if (m->brlens->paramId == BRLENS_CLOCK_SPCOAL)
12382         {
12383         oldLnPrior = LnSpeciesTreeProb(chain);
12384         }
12385     
12386     /* change value for theta */
12387     ran = RandomNumber(seed);
12388     newN = oldN * exp(tuning * (ran - 0.5));
12389     
12390     /* check that new value is valid */
12391     isValidN = NO;
12392     do {
12393         if (newN < minN)
12394             newN = 2* minN - newN;
12395         else if (newN > maxN)
12396             newN = 2 * maxN - newN;
12397         else
12398             isValidN = YES;
12399         }
12400     while (isValidN == NO);
12401
12402     /* copy new population size value back */
12403     (*valPtr) = newN;
12404
12405     /* get proposal ratio */
12406     *lnProposalRatio = log (newN / oldN);
12407     
12408     /* get prior ratio */
12409     if (m->brlens->paramId == BRLENS_CLOCK_SPCOAL)
12410         {
12411         newLnPrior = LnSpeciesTreeProb(chain);
12412         }
12413     else
12414         {
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"))
12419             clockRate *= 4.0;
12420         else if (!strcmp(mp->ploidy, "Zlinked"))
12421             clockRate *= 3.0;
12422         else
12423             clockRate *= 2.0;
12424         newT = oldN * clockRate;
12425         oldT = newN * clockRate;
12426         if (!strcmp(mp->growthPr, "Fixed"))
12427             growth = mp->growthFix;
12428         else
12429             growth = *(GetParamVals (m->growthRate, chain, state[chain]));
12430         if (LnCoalescencePriorPr (t, &oldLnPrior, oldT, growth) == ERROR)
12431             {
12432             MrBayesPrint ("%s   Problem calculating prior for coalescent process\n", spacer);
12433             return (ERROR);
12434             }
12435         if (LnCoalescencePriorPr (t, &newLnPrior, newT, growth) == ERROR)
12436             {
12437             MrBayesPrint ("%s   Problem calculating prior for coalescent process\n", spacer);
12438             return (ERROR);
12439             }
12440         }
12441
12442     (*lnPriorRatio) = param->LnPriorRatio(newN, oldN, param->priorParams);
12443     (*lnPriorRatio) += newLnPrior - oldLnPrior;
12444
12445     return (NO_ERROR);
12446 }
12447
12448
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)
12451 {
12452     int         i;
12453     MrBFlt      oldX, newX, minX, maxX, tuning, u, z;
12454
12455     /* get tuning parameter */
12456     tuning = mvp[0];
12457
12458     /* get minimum and maximum values for X */
12459     minX = param->min;
12460     maxX = param->max;
12461
12462     /* get old value of X */
12463     newX = oldX = *GetParamVals(param, chain, state[chain]);
12464
12465     /* change value of X */
12466     u = RandomNumber(seed);
12467     z = PointNormal(u);
12468
12469     newX = exp (log(oldX) + z * tuning);
12470     
12471     /* check that new value is valid */
12472     if (newX < minX || newX > maxX) {
12473         abortMove = YES;
12474         return (NO_ERROR);
12475     }
12476     
12477     /* get proposal ratio */
12478     (*lnProposalRatio) = log (newX / oldX);
12479     
12480     /* get prior ratio */
12481     (*lnPriorRatio) = param->LnPriorRatio(newX, oldX, param->priorParams);
12482     
12483     /* copy new value back */
12484     (*GetParamVals(param, chain, state[chain])) = newX;
12485
12486     /* Set update flags for tree nodes if relevant */
12487     if (param->affectsLikelihood == YES)
12488         {
12489         for (i=0; i<param->nRelParts; i++)
12490             TouchAllTreeNodes(&modelSettings[param->relParts[i]],chain);
12491         }
12492
12493     return (NO_ERROR);
12494 }
12495
12496
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)
12499 {
12500     int         i, isValid;
12501     MrBFlt      oldX, newX, minX, maxX, tuning, ran, factor;
12502
12503     /* get tuning parameter */
12504     tuning = mvp[0];
12505
12506     /* get minimum and maximum values for X */
12507     minX = param->min;
12508     maxX = param->max;
12509
12510     /* get old value of X */
12511     newX = oldX = *GetParamVals(param, chain, state[chain]);
12512
12513     /* change value of X */
12514     ran = RandomNumber(seed);
12515     factor = exp(tuning * (ran - 0.5));
12516     newX = oldX * factor;
12517     
12518     /* check that new value is valid */
12519     isValid = NO;
12520     do
12521         {
12522         if (newX < minX)
12523             newX = minX * minX / newX;
12524         else if (newX > maxX)
12525             newX = maxX * maxX / newX;
12526         else
12527             isValid = YES;
12528         } while (isValid == NO);
12529
12530     /* get proposal ratio */
12531     (*lnProposalRatio) = log (newX / oldX);
12532     
12533     /* get prior ratio */
12534     (*lnPriorRatio) = param->LnPriorRatio(newX, oldX, param->priorParams);
12535     
12536     /* copy new value back */
12537     *(GetParamVals(param, chain, state[chain])) = newX;
12538
12539     /* Set update flags for tree nodes if relevant */
12540     if (param->affectsLikelihood == YES)
12541         {
12542         for (i=0; i<param->nRelParts; i++)
12543             TouchAllTreeNodes(&modelSettings[param->relParts[i]],chain);
12544         }
12545
12546     return (NO_ERROR);
12547 }
12548
12549
12550 /*----------------------------------------------------------------
12551 |
12552 |   Move_RateMult_Dir: Change rate multiplier using Dirichlet
12553 |      proposal.
12554 |
12555 ----------------------------------------------------------------*/
12556 int Move_RateMult_Dir (Param *param, int chain, RandLong *seed, MrBFlt *lnPriorRatio, MrBFlt *lnProposalRatio, MrBFlt *mvp)
12557 {
12558     int         i, nRates, isValid;
12559     MrBFlt      alphaPi, *value, *subValue, numSites, *alphaDir, x, y, sum,
12560                 rate_pot, *dirParm, *oldRate, *newRate;
12561
12562     /* allocate memory */
12563     dirParm = (MrBFlt *) SafeCalloc (3*numCurrentDivisions, sizeof(MrBFlt));
12564     oldRate = dirParm + numCurrentDivisions;
12565     newRate = dirParm + 2*numCurrentDivisions;
12566
12567     /* get number of rates */
12568     nRates = param->nValues;
12569
12570     /* get pointer to rates and number of uncompressed chars */
12571     value = GetParamVals(param, chain, state[chain]);
12572     subValue = GetParamSubVals(param, chain, state[chain]);
12573
12574     /* get Dirichlet parameters */
12575     alphaDir = subValue + nRates;
12576
12577     /* calculate old ratesum proportions */
12578     numSites = 0.0;
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;
12583     
12584     /* get alphaPi tuning parameter */
12585     alphaPi = mvp[0] * nRates;
12586
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;
12590     
12591     /* get new values */
12592     DirichletRandomVariable (dirParm, newRate, nRates, seed);
12593     
12594     /* check new values. we rely on newRate be already normalized  */
12595     while (1)
12596         {
12597         sum = 0.0;
12598         rate_pot = 1.0;
12599         isValid=1;
12600         for (i=0; i<nRates; i++)
12601             {
12602             if (newRate[i] <= DIR_MIN)
12603                 {
12604                 if (newRate[i] < DIR_MIN)
12605                     {
12606                     newRate[i] = DIR_MIN;
12607                     isValid=0;
12608                     }
12609                 rate_pot -= DIR_MIN;
12610                 }
12611             else
12612                 sum += newRate[i];
12613             }
12614         if (isValid==1) break;
12615         for (i=0; i<nRates; i++)
12616             {
12617             if (newRate[i]!=DIR_MIN)
12618                 newRate[i] = rate_pot * newRate[i] / sum;
12619             }
12620         }
12621
12622     /* calculate and copy new rate ratio values back */
12623     for (i=0; i<nRates; i++)
12624         value[i] = newRate[i] * (numSites / subValue[i]);
12625     
12626     /* get proposal ratio */
12627     sum = 0.0;
12628     for (i=0; i<nRates; i++)
12629         sum += newRate[i]*alphaPi;
12630     x = LnGamma(sum);
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]);
12635     sum = 0.0;
12636     for (i=0; i<nRates; i++)
12637         sum += oldRate[i]*alphaPi;
12638     y = LnGamma(sum);
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;
12644
12645     /* get prior ratio */
12646     x = y = 0.0;
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;
12652
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);
12657         
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;
12662
12663     free (dirParm);
12664
12665     return (NO_ERROR);
12666 }
12667
12668
12669 /*----------------------------------------------------------------
12670 |
12671 |   Move_RateMult_Slider: Change rate multiplier using slider
12672 |      proposal.
12673 |
12674 ----------------------------------------------------------------*/
12675 int Move_RateMult_Slider (Param *param, int chain, RandLong *seed, MrBFlt *lnPriorRatio, MrBFlt *lnProposalRatio, MrBFlt *mvp)
12676 {
12677     int         i, indexI, indexJ, nRates;
12678     MrBFlt      delta, *value, *subValue, sum, numSites, *alphaDir, x, y,
12679                 oldRate[2], newRate[2], min, max;
12680
12681     /* get number of rates */
12682     nRates = param->nValues;
12683
12684     /* get pointer to rates and number of uncompressed chars */
12685     value = GetParamVals(param, chain, state[chain]);
12686     subValue = GetParamSubVals(param, chain, state[chain]);
12687
12688     /* get Dirichlet prior parameters */
12689     alphaDir = subValue + nRates;
12690
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;
12696
12697     /* calculate old ratesum proportions */
12698     numSites = 0.0;
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];
12704     
12705     /* get delta tuning parameter */
12706     delta = mvp[0];
12707
12708     /* reflect */
12709     min = DIR_MIN / sum;
12710     max = 1.0 - min;
12711     if (delta > max-min) /* we do it to avoid following long while loop in case if delta is high */
12712         delta = max-min;
12713
12714     x = oldRate[0] / sum;
12715     y = x + delta * (RandomNumber(seed) - 0.5);
12716     while (y < min || y > max)
12717         {
12718         if (y < min)
12719             y = 2.0 * min - y;
12720         if (y > max)
12721             y = 2.0 * max - y;
12722         }
12723     
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];
12729
12730     /* get proposal ratio */
12731     (*lnProposalRatio) = 0.0;
12732
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]));
12736
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);
12741         
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;
12746
12747     return (NO_ERROR);
12748 }
12749
12750
12751 /*----------------------------------------------------------------
12752 |
12753 |   Move_Revmat_Dir: Change rate matrix using Dirichlet proposal
12754 |      mechanism.
12755 |
12756 ----------------------------------------------------------------*/
12757 int Move_Revmat_Dir (Param *param, int chain, RandLong *seed, MrBFlt *lnPriorRatio, MrBFlt *lnProposalRatio, MrBFlt *mvp)
12758 {
12759     /* change revMat using Dirichlet proposal */
12760     
12761     int             i, nRates,isValid;
12762     MrBFlt          oldRate[200], newRate[200], dirParm[200], *value, sum, x, y, rate_pot, *alphaDir, alphaPi;
12763     ModelParams     *mp;
12764     ModelInfo       *m;
12765
12766     /* get model params and settings */
12767     mp = &modelParams[param->relParts[0]];
12768     m  = &modelSettings[param->relParts[0]];
12769
12770     /* get rates and nRates */
12771     value = GetParamVals(param, chain, state[chain]);
12772     nRates = param->nValues;
12773
12774     /* get so called alpha_pi parameter and adjust for number of components */
12775     alphaPi = mvp[0] * nRates;
12776
12777     /* get Dirichlet parameters */
12778     if (m->dataType == PROTEIN)
12779         alphaDir = mp->aaRevMatDir;
12780     else
12781         alphaDir = mp->revMatDir;
12782
12783     /* copy old rates */
12784     for (i=0; i<nRates; i++)
12785         oldRate[i] = value[i];
12786     
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;
12790     
12791     /* get new values */
12792     DirichletRandomVariable (dirParm, newRate, nRates, seed);
12793
12794     /* check new values. we rely on newRate be already normalized  */
12795     while (1)
12796         {
12797         sum = 0.0;
12798         rate_pot = 1.0;
12799         isValid=1;
12800         for (i=0; i<nRates; i++)
12801             {
12802             if (newRate[i] <= RATE_MIN)
12803                 {
12804                 if (newRate[i] < RATE_MIN)
12805                     {
12806                     newRate[i] = RATE_MIN;
12807                     isValid=0;
12808                     }
12809                 rate_pot -= RATE_MIN;
12810                 }
12811             else
12812                 sum += newRate[i];
12813             }
12814         if (isValid==1) break;
12815         for (i=0; i<nRates; i++)
12816             {
12817             if (newRate[i]!=RATE_MIN)
12818                 newRate[i] = rate_pot * newRate[i] / sum;
12819             }
12820         }
12821
12822     /* copy new rate ratio values back */
12823     for (i=0; i<nRates; i++)
12824         value[i] = newRate[i];
12825     
12826     /* get proposal ratio */
12827     sum = 0.0;
12828     for (i=0; i<nRates; i++)
12829         sum += newRate[i]*alphaPi;
12830     x = LnGamma(sum);
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]);
12835     sum = 0.0;
12836     for (i=0; i<nRates; i++)
12837         sum += oldRate[i]*alphaPi;
12838     y = LnGamma(sum);
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;
12844
12845     /* get prior ratio */
12846     x = y = 0.0;
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;
12852
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);
12857         
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;
12861
12862     return (NO_ERROR);
12863 }
12864
12865
12866 /*----------------------------------------------------------------
12867 |
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
12871 |      to 6, not to 1.
12872 |
12873 ----------------------------------------------------------------*/
12874 int Move_Revmat_DirMix (Param *param, int chain, RandLong *seed, MrBFlt *lnPriorRatio, MrBFlt *lnProposalRatio, MrBFlt *mvp)
12875 {
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;
12878     ModelParams *mp;
12879
12880     /* get model params and settings */
12881     mp = &modelParams[param->relParts[0]];
12882
12883     /* get growthFunction and nRates */
12884     value     = GetParamVals (param, chain, state[chain]);
12885     growthFxn = GetParamIntVals (param, chain, state[chain]);
12886     nRates    = GetKFromGrowthFxn(growthFxn);
12887
12888     /* we can't do anything if there is only one rate */
12889     if (nRates == 1)
12890         {
12891         abortMove = YES;
12892         return (NO_ERROR);
12893         }
12894
12895     /* extract unique rates from value vector */
12896     for (i=0; i<nRates; i++)
12897         oldRate[i] = 0.0;
12898     for (i=0; i<6; i++)
12899         oldRate[growthFxn[i]] += value[i];
12900
12901     /* get so called alpha_pi parameter and adjust for number of components */
12902     alphaPi = mvp[0] * nRates;
12903
12904     /* get symmetric dirichlet parameter */
12905     symDir  = mp->revMatSymDir;
12906
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;
12910
12911     /* get new values */
12912     DirichletRandomVariable (dirParm, newRate, nRates, seed);
12913
12914     /* check new values. we rely on newRate be already normalized  */
12915     while (1)
12916         {
12917         sum = 0.0;
12918         rate_pot = 1.0;
12919         isValid=1;
12920         for (i=0; i<nRates; i++)
12921             {
12922             if (newRate[i] <= RATE_MIN)
12923                 {
12924                 if (newRate[i] < RATE_MIN)
12925                     {
12926                     newRate[i] = RATE_MIN;
12927                     isValid=0;
12928                     }
12929                 rate_pot -= RATE_MIN;
12930                 }
12931             else
12932                 sum += newRate[i];
12933             }
12934         if (isValid==1) break;
12935         for (i=0; i<nRates; i++)
12936             {
12937             if (newRate[i]!=RATE_MIN)
12938                 newRate[i] = rate_pot * newRate[i] / sum;
12939             }
12940         }
12941
12942     /* copy new unique rate ratio values back into the value array */
12943     for (i=0; i<nRates; i++)
12944         {
12945         k = 0;
12946         for (j=i; j<6; j++)
12947             {
12948             if (growthFxn[j] == i)
12949                 k++;
12950             }
12951         for (j=i; j<6; j++)
12952             {
12953             if (growthFxn[j] == i)
12954                 value[j] = newRate[i] / (MrBFlt) k;
12955             }
12956         }
12957     
12958     /* get proposal ratio */
12959     sum = 0.0;
12960     for (i=0; i<nRates; i++)
12961         sum += newRate[i]*alphaPi;
12962     x = LnGamma(sum);
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]);
12967     sum = 0.0;
12968     for (i=0; i<nRates; i++)
12969         sum += oldRate[i]*alphaPi;
12970     y = LnGamma(sum);
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;
12976
12977     /* get group sizes, needed for prior ratio */
12978     for (i=0; i<nRates; i++)
12979         groupSize[i] = 0;
12980     for (i=0; i<6; i++)
12981         groupSize[growthFxn[i]]++;
12982
12983     /* get prior ratio */
12984     x = y = 0.0;
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;
12990
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);
12995         
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;
12999
13000     return (NO_ERROR);
13001 }
13002
13003
13004 /*----------------------------------------------------------------
13005 |
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.
13014 |
13015 ----------------------------------------------------------------*/
13016 int Move_Revmat_Slider (Param *param, int chain, RandLong *seed, MrBFlt *lnPriorRatio, MrBFlt *lnProposalRatio, MrBFlt *mvp)
13017 {
13018     int         i, j, nRates;
13019     MrBFlt      delta, *newRate, *oldRate, *priorAlpha, x, y, sum, min, max;
13020     ModelParams *mp;
13021     ModelInfo   *m;
13022
13023     /* get model params and settings */
13024     mp = &modelParams[param->relParts[0]];
13025     m  = &modelSettings[param->relParts[0]];
13026
13027     /* get Dirichlet parameters */
13028     if (m->dataType == PROTEIN)
13029         priorAlpha = mp->aaRevMatDir;
13030     else
13031         priorAlpha = mp->revMatDir;
13032
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);
13037
13038     /* choose a pair to change */
13039     i = (int) (RandomNumber(seed) * nRates);
13040     j = (int) (RandomNumber(seed) * (nRates-1));
13041     if (i == j)
13042         j = nRates-1;
13043     
13044     /* find new proportion */
13045     sum = oldRate[i] + oldRate[j];
13046
13047     /* get window size */
13048     delta = mvp[0];
13049
13050     /* reflect */
13051     min = RATE_MIN / sum;
13052     max = 1.0 - min;
13053     if (delta > max-min) /* we do it to avoid following long while loop in case if delta is high */
13054         delta = max-min;
13055
13056     x = oldRate[i] / sum;
13057     y = x + delta * (RandomNumber(seed) - 0.5);
13058     while (y < min || y > max)
13059         {
13060         if (y < min)
13061             y = 2.0 * min - y;
13062         if (y > max)
13063             y = 2.0 * max - y;
13064         }
13065     
13066     /* set the new values */
13067     newRate[i] = y * sum;
13068     newRate[j] = sum - newRate[i];
13069
13070     /* get proposal ratio */
13071     (*lnProposalRatio) = 0.0;
13072
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]));
13076
13077     /* Set update for entire tree */
13078     for (i=0; i<param->nRelParts; i++)
13079         TouchAllTreeNodes(&modelSettings[param->relParts[i]],chain);
13080         
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;
13087
13088     return (NO_ERROR);
13089 }
13090
13091
13092 /*----------------------------------------------------------------
13093 |
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.
13098 |
13099 ----------------------------------------------------------------*/
13100 int Move_Revmat_SplitMerge1 (Param *param, int chain, RandLong *seed, MrBFlt *lnPriorRatio, MrBFlt *lnProposalRatio, MrBFlt *mvp)
13101 {
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;
13107     ModelParams *mp;
13108
13109     /* get model params and settings */
13110     mp = &modelParams[param->relParts[0]];
13111
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 */
13120
13121     /* get the old rates */
13122     for (i=0; i<nOldRates; i++)
13123         oldRate[i] = 0.0;
13124     for (i=0; i<6; i++)
13125         oldRate[oldGrowthFxn[i]] += oldValue[i];
13126
13127     /* decide whether to split or merge */
13128     if (nOldRates == 1)
13129         merge = NO;
13130     else if (nOldRates == 6)
13131         merge = YES;
13132     else if (RandomNumber(seed) < 0.5)
13133         merge = YES;
13134     else
13135         merge = NO;
13136
13137     /* now split or merge */
13138     R = R_i = R_j = 0.0;
13139     if (merge == YES)
13140         {
13141         /* merge two rates */
13142         nNewRates = nOldRates - 1;
13143
13144         /* determine split and merge probs */
13145         if (nNewRates == 1)
13146             prob_split = 1.0;
13147         else
13148             prob_split = 0.5;
13149         if (nOldRates == 6)
13150             prob_merge = 1.0;
13151         else
13152             prob_merge = 0.5;
13153
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;
13159
13160         /* make sure index_i is lower index */
13161         if (index_i > index_j)
13162             {
13163             i = index_i;
13164             index_i = index_j;
13165             index_j = i;
13166             }
13167
13168         /* find group sizes */
13169         n_i = n_j = 0;
13170         for (i=0; i<6; i++)
13171             {
13172             if (oldGrowthFxn[i] == index_i)
13173                 n_i++;
13174             else if (oldGrowthFxn[i] == index_j)
13175                 n_j++;
13176             }
13177
13178         /* adjust growth function */
13179         for (i=0; i<6; i++)
13180             {
13181             if (oldGrowthFxn[i] == index_j)
13182                 newGrowthFxn[i] = index_i;
13183             else if (oldGrowthFxn[i] > index_j)
13184                 newGrowthFxn[i] = oldGrowthFxn[i] - 1;
13185             else
13186                 newGrowthFxn[i] = oldGrowthFxn[i];
13187             }
13188
13189         /* find the new rates */
13190         for (i=0; i<nNewRates; i++)
13191             {
13192             if (i == index_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];
13198             }
13199
13200         /* copy new unique rate values back into the value array */
13201         for (i=0; i<nNewRates; i++)
13202             {
13203             k = 0;
13204             for (j=i; j<6; j++)
13205                 {
13206                 if (newGrowthFxn[j] == i)
13207                     k++;
13208                 }
13209             for (j=i; j<6; j++)
13210                 {
13211                 if (newGrowthFxn[j] == i)
13212                     newValue[j] = newRate[i] / (MrBFlt) k;
13213                 }
13214             }
13215
13216         /* get the new and old rates (sum over parts) */
13217         R_i = oldRate[index_i];
13218         R_j = oldRate[index_j];
13219         R   = R_i + R_j;
13220
13221         /* check group sizes after merge (before split in back move) */
13222         for (i=0; i<nNewRates; i++)
13223             groupSize[i] = 0;
13224         for (i=0; i<6; i++)
13225             groupSize[newGrowthFxn[i]]++;
13226         nCompositeRates = 0;
13227         for (i=0; i<nNewRates; i++)
13228             {
13229             if (groupSize[i] > 1)
13230                 nCompositeRates++;
13231             }
13232
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);
13236
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))));
13239
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;
13251
13252         /* Jacobian for the rate proportion */
13253         (*lnProposalRatio) -= log(R);
13254         }
13255     else
13256         {
13257         /* split two rates */
13258         nNewRates = nOldRates + 1;
13259
13260         /* determine split and merge probs */
13261         if (nNewRates == 6)
13262             prob_merge = 1.0;
13263         else
13264             prob_merge = 0.5;
13265         if (nOldRates == 1)
13266             prob_split = 1.0;
13267         else
13268             prob_split = 0.5;
13269
13270         /* check group sizes before split */
13271         for (i=0; i<nOldRates; i++)
13272             groupSize[i] = 0;
13273         for (i=0; i<6; i++)
13274             groupSize[oldGrowthFxn[i]]++;
13275         nCompositeRates = 0;
13276         for (i=0; i<nOldRates; i++)
13277             {
13278             if (groupSize[i] > 1)
13279                 nCompositeRates++;
13280             }
13281
13282         /* randomly select a rate with two or more components to split */
13283         k = (int) (RandomNumber(seed) * nCompositeRates);
13284
13285         for (i=j=0; i<nOldRates; i++)
13286             {
13287             if (groupSize[i] > 1)
13288                 {
13289                 if (k == j)
13290                     break;
13291                 j++;
13292                 }
13293             }
13294         assert (i < nOldRates && groupSize[i] > 1);
13295         index_i = i;
13296
13297         /* adjust growth function */
13298         do {
13299             foundFirstI = foundFirstJ = NO;
13300             k = 0;
13301             index_j = -1;
13302             for (i=0; i<6; i++)
13303                 {
13304                 if (oldGrowthFxn[i] == index_i)
13305                     {
13306                     if (foundFirstI == NO)
13307                         {
13308                         newGrowthFxn[i] = index_i;
13309                         foundFirstI = YES;
13310                         }
13311                     else
13312                         {
13313                         if (RandomNumber(seed) < 0.5)
13314                             {
13315                             if (foundFirstJ == NO)
13316                                 {
13317                                 foundFirstJ = YES;
13318                                 index_j = k + 1;    /* one more than previous max */
13319                                 newGrowthFxn[i] = index_j;
13320                                 }
13321                             else
13322                                 {
13323                                 newGrowthFxn[i] = index_j;
13324                                 }
13325                             }
13326                         else
13327                             newGrowthFxn[i] = index_i;
13328                         }
13329                     }
13330                 else if (foundFirstJ == YES && oldGrowthFxn[i] >= index_j)
13331                     newGrowthFxn[i] = oldGrowthFxn[i] + 1;
13332                 else
13333                     newGrowthFxn[i] = oldGrowthFxn[i];
13334                 if (foundFirstJ == NO && oldGrowthFxn[i] > k)
13335                     k = oldGrowthFxn[i];
13336                 }
13337             } while (foundFirstJ == NO);
13338
13339         /* find group sizes */
13340         n_i = n_j = 0;
13341         for (i=0; i<6; i++)
13342             {
13343             if (newGrowthFxn[i] == index_i)
13344                 n_i++;
13345             else if (newGrowthFxn[i] == index_j)
13346                 n_j++;
13347             }
13348
13349         /* find old rate */
13350         R = oldRate[index_i];
13351
13352         /* propose new rates */
13353         dirParm[0] = alphaPi * n_i;
13354         dirParm[1] = alphaPi * n_j;
13355
13356         DirichletRandomVariable(dirParm, rateProps, 2, seed);
13357         R_i = rateProps[0] * R;
13358         R_j = rateProps[1] * R;
13359
13360         if (R_i/n_i < RATE_MIN)
13361             {
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);
13367             }
13368         else if (R_j/n_j < RATE_MIN)
13369             {
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);
13375             }
13376
13377         /* set the new rates */
13378         for (i=0; i<nNewRates; i++)
13379             {
13380             if (i == index_i)
13381                 newRate[i] = R_i;
13382             else if (i == index_j)
13383                 newRate[i] = R_j;
13384             else if (i > index_j)
13385                 newRate[i] = oldRate[i-1];
13386             else
13387                 newRate[i] = oldRate[i];
13388             }
13389
13390         /* copy new unique rate values back into the value array */
13391         for (i=0; i<nNewRates; i++)
13392             {
13393             k = 0;
13394             for (j=i; j<6; j++)
13395                 {
13396                 if (newGrowthFxn[j] == i)
13397                     k++;
13398                 }
13399             for (j=i; j<6; j++)
13400                 {
13401                 if (newGrowthFxn[j] == i)
13402                     newValue[j] = newRate[i] / (MrBFlt) k;
13403                 }
13404             }
13405
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);;
13409
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)));
13412         
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;
13420
13421         /* Jacobian for rate proportion */
13422         (*lnProposalRatio) += log (R);
13423         }
13424
13425 #if defined (DEBUG_SPLITMERGE)
13426     if (*lnPriorRatio != *lnPriorRatio)
13427         {
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);
13435         getchar();
13436         }
13437 #endif
13438
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);
13443         
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;
13447
13448     return (NO_ERROR);
13449 }
13450
13451
13452 /*----------------------------------------------------------------
13453 |
13454 |   Move_Revmat_SplitMerge2: Componentwise split or merge move.
13455 |
13456 ----------------------------------------------------------------*/
13457 int Move_Revmat_SplitMerge2 (Param *param, int chain, RandLong *seed, MrBFlt *lnPriorRatio, MrBFlt *lnProposalRatio, MrBFlt *mvp)
13458 {
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;
13463     ModelParams *mp;
13464
13465     /* get model params and settings */
13466     mp = &modelParams[param->relParts[0]];
13467
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 */
13475
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)
13480         index_j = 5;
13481     groupIndex_i = oldGrowthFxn[index_i];
13482     groupIndex_j = oldGrowthFxn[index_j];
13483
13484     if (oldGrowthFxn[index_i] != oldGrowthFxn[index_j])
13485         {
13486         /* the rates are different, so merge them */
13487
13488         /* calculate n_i, n_j, R_i and R_j before merge */
13489         n_i = n_j = 0;
13490         R_i = R_j = 0.0;
13491         for (i=0; i<6; i++)
13492             {
13493             if (oldGrowthFxn[i] == groupIndex_i)
13494                 {
13495                 n_i++;
13496                 R_i += oldValue[i];
13497                 }
13498             if (oldGrowthFxn[i] == groupIndex_j)
13499                 {
13500                 n_j++;
13501                 R_j += oldValue[i];
13502                 }
13503             }
13504
13505         /* merge component rates by adding j to i */
13506         newGrowthFxn[index_j] = oldGrowthFxn[index_i];
13507
13508         /* select a new rate for r_j */
13509         if (n_j == 1)
13510             r_j = oldValue[index_j];
13511         else
13512             {
13513             dirParm[0] = alphaPi * 1;
13514             dirParm[1] = alphaPi * (n_j - 1);
13515
13516             DirichletRandomVariable(dirParm, rateProps, 2, seed);
13517             r_j = rateProps[0] * R_j;
13518
13519             if (R_j - r_j < RATE_MIN)
13520                 {
13521                 r_j = R_j - RATE_MIN;
13522                 rateProps[0] = r_j/R_j;
13523                 rateProps[1] = 1 - rateProps[0];
13524                 }
13525             }
13526
13527         /* update new growth function */
13528         UpdateGrowthFxn(newGrowthFxn);
13529
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++)
13533             {
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);
13538             else
13539                 newValue[i] = oldValue[i];
13540             }
13541
13542         /* calculate prior ratio */
13543         if (n_j > 1)
13544             {
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);
13550             }
13551         else
13552             {
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);
13558             }
13559
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);
13563
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;
13575
13576         /* adjust for Beta proposal in forward move */
13577         if (n_j > 1)
13578             {
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;
13589             }
13590
13591         /* Jacobian */
13592         (*lnProposalRatio) -= log (R_i + r_j);
13593         if (n_j > 1)
13594             (*lnProposalRatio) += log (R_j);
13595         }
13596     else
13597         {
13598         /* split component rates because they are the same */
13599
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;
13605
13606         /* update growth function and group indices */
13607         UpdateGrowthFxn(newGrowthFxn);
13608         groupIndex_i = newGrowthFxn[index_i];
13609         groupIndex_j = newGrowthFxn[index_j];
13610
13611         /* calculate n_i, n_j, R_i and R_j after split */
13612         n_i = n_j = 0;
13613         R_i = R_j = 0.0;
13614         for (i=0; i<6; i++)
13615             {
13616             if (i == index_j)
13617                 {
13618                 R_i += oldValue[i];
13619                 n_i++;
13620                 }
13621             else if (newGrowthFxn[i] == groupIndex_i)
13622                 {
13623                 n_i++;
13624                 R_i += oldValue[i];
13625                 }
13626             else if (newGrowthFxn[i] == groupIndex_j)
13627                 {
13628                 n_j++;
13629                 R_j += oldValue[i];
13630                 }
13631             }
13632
13633         /* select a new rate for r_j */
13634         dirParm[0] = alphaPi * 1;
13635         dirParm[1] = alphaPi * (n_i - 1);
13636
13637         DirichletRandomVariable(dirParm, rateProps, 2, seed);
13638         r_j = rateProps[0] * R_i;
13639
13640         if (R_i-r_j < RATE_MIN)
13641             {
13642             r_j = R_i - RATE_MIN;
13643             rateProps[0] = r_j/R_i;
13644             rateProps[1] = 1 - rateProps[0];
13645             }
13646
13647         /* update n_i, n_j, R_i and R_j after split */
13648         n_i -= 1;
13649         n_j += 1;
13650         R_i -= r_j;
13651         R_j += r_j;
13652
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++)
13656             {
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);
13661             else
13662                 newValue[i] = oldValue[i];
13663             }
13664
13665         /* calculate prior ratio */
13666         if (n_j > 1)
13667             {
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);
13673             }
13674         else
13675             {
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);
13681             }
13682
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);
13686
13687         /* adjust for Beta proposal in back move */
13688         if (n_j > 1)
13689             {
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;
13700             }
13701
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;
13713
13714         /* Jacobian */
13715         (*lnProposalRatio) += log (R_i + r_j);
13716         if (n_j > 1)
13717             (*lnProposalRatio) -= log (R_j);
13718         }
13719
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);
13724         
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;
13728
13729     return (NO_ERROR);
13730 }
13731
13732
13733 int Move_Speciation (Param *param, int chain, RandLong *seed, MrBFlt *lnPriorRatio, MrBFlt *lnProposalRatio, MrBFlt *mvp)
13734 {
13735     /* change speciation rate using sliding window */
13736     
13737     int         isLPriorExp, isValidL, valIndex;
13738     MrBFlt      *valPtr, oldL, newL, minL, maxL, lambdaExp=0.0, *sR, *eR, sF, *fR, oldLnPrior, newLnPrior,
13739                 window, clockRate;
13740     char        *sS;
13741     ModelParams *mp;
13742     ModelInfo   *m;
13743     Tree        *t;
13744
13745     /* get size of window, centered on current value */
13746     window = mvp[0];
13747
13748     /* get model params and settings */
13749     mp = &modelParams[param->relParts[0]];
13750     m = &modelSettings[param->relParts[0]];
13751     
13752     /* get minimum and maximum values */
13753     if (param->paramId == SPECRATE_UNI)
13754         {
13755         minL = mp->speciationUni[0];
13756         maxL = mp->speciationUni[1];
13757         isLPriorExp = NO;
13758         }
13759     else
13760         {
13761         minL = 0.000001;
13762         maxL = 1000.0;
13763         lambdaExp = mp->speciationExp;
13764         isLPriorExp = YES;
13765         }
13766
13767     /* get pointer to value to be changed */
13768     valIndex = (int)(RandomNumber(seed) * param->nValues);
13769     valPtr = GetParamVals(param, chain, state[chain]) + valIndex;
13770     
13771     /* get old value */
13772     oldL = *valPtr;
13773
13774     /* change value */
13775     if (maxL-minL < window)
13776         window = maxL-minL;
13777     newL = oldL + window * (RandomNumber(seed) - 0.5);
13778     
13779     /* check that new value is valid */
13780     isValidL = NO;
13781     do  {
13782         if (newL < minL)
13783             newL = 2 * minL - newL;
13784         else if (newL > maxL)
13785             newL = 2 * maxL - newL;
13786         else
13787             isValidL = YES;
13788         } while (isValidL == NO);
13789
13790     /* get proposal ratio */
13791     *lnProposalRatio = 0.0;
13792     
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]);
13800     
13801     if (!strcmp(mp->clockPr,"Birthdeath"))
13802         {
13803         if (LnBirthDeathPriorPr (t, clockRate, &oldLnPrior, *sR, *eR, sS, sF) == ERROR)
13804             {
13805             MrBayesPrint ("%s   Problem calculating prior for birth-death process\n", spacer);
13806             return (ERROR);
13807             }
13808         *valPtr = newL;  // update with new value
13809         if (LnBirthDeathPriorPr (t, clockRate, &newLnPrior, *sR, *eR, sS, sF) == ERROR)
13810             {
13811             MrBayesPrint ("%s   Problem calculating prior for birth-death process\n", spacer);
13812             return (ERROR);
13813             }
13814         }
13815     else if (!strcmp(mp->clockPr,"Fossilization"))
13816         {
13817         fR = GetParamVals (m->fossilizationRates, chain, state[chain]);
13818         if (LnFossilizationPriorPr (t, clockRate, &oldLnPrior, sR, eR, sF, fR, sS) == ERROR)
13819             {
13820             MrBayesPrint ("%s   Problem calculating prior for fossilized birth-death process\n", spacer);
13821             return (ERROR);
13822             }
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)
13826             {
13827             MrBayesPrint ("%s   Problem calculating prior for fossilized birth-death process\n", spacer);
13828             return (ERROR);
13829             }
13830         }
13831     else {
13832         MrBayesPrint ("%s   Move_Speciation not applicable\n", spacer);
13833         return (ERROR);
13834         }
13835
13836     if (isLPriorExp == NO)
13837         *lnPriorRatio = newLnPrior - oldLnPrior;
13838     else
13839         *lnPriorRatio = -lambdaExp * (newL - oldL) + (newLnPrior - oldLnPrior);
13840     
13841     return (NO_ERROR);
13842 }
13843
13844
13845 int Move_Speciation_M (Param *param, int chain, RandLong *seed, MrBFlt *lnPriorRatio, MrBFlt *lnProposalRatio, MrBFlt *mvp)
13846 {
13847     /* change speciation rate using multiplier */
13848     
13849     int         isLPriorExp, isValidL, valIndex;
13850     MrBFlt      *valPtr, oldL, newL, minL, maxL, lambdaExp=0.0, *sR, *eR, sF, *fR, oldLnPrior, newLnPrior,
13851                 tuning, clockRate;
13852     char        *sS;
13853     ModelParams *mp;
13854     ModelInfo   *m;
13855     Tree        *t;
13856
13857     /* get tuning parameter */
13858     tuning = mvp[0];
13859
13860     /* get model params and settings */
13861     mp = &modelParams[param->relParts[0]];
13862     m = &modelSettings[param->relParts[0]];
13863     
13864     /* get minimum and maximum values */
13865     if (param->paramId == SPECRATE_UNI)
13866         {
13867         minL = mp->speciationUni[0];
13868         maxL = mp->speciationUni[1];
13869         isLPriorExp = NO;
13870         }
13871     else
13872         {
13873         minL = 0.000001;
13874         maxL = 1000.0;
13875         lambdaExp = mp->speciationExp;
13876         isLPriorExp = YES;
13877         }
13878
13879     /* get pointer to value to be changed */
13880     valIndex = (int)(RandomNumber(seed) * param->nValues);
13881     valPtr = GetParamVals(param, chain, state[chain]) + valIndex;
13882     
13883     /* get old value */
13884     oldL = *valPtr;
13885
13886     /* change value */
13887     newL = oldL * exp(tuning * (RandomNumber(seed) - 0.5));
13888     
13889     /* check that new value is valid */
13890     isValidL = NO;
13891     do  {
13892         if (newL < minL)
13893             newL = minL * minL / newL;
13894         else if (newL > maxL)
13895             newL = maxL * maxL / newL;
13896         else
13897             isValidL = YES;
13898         } while (isValidL == NO);
13899
13900     /* get proposal ratio */
13901     *lnProposalRatio = log (newL / oldL);
13902     
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]);
13910     
13911     if (!strcmp(mp->clockPr,"Birthdeath"))
13912         {
13913         if (LnBirthDeathPriorPr (t, clockRate, &oldLnPrior, *sR, *eR, sS, sF) == ERROR)
13914             {
13915             MrBayesPrint ("%s   Problem calculating prior for birth-death process\n", spacer);
13916             return (ERROR);
13917             }
13918         *valPtr = newL;  // update with new value
13919         if (LnBirthDeathPriorPr (t, clockRate, &newLnPrior, *sR, *eR, sS, sF) == ERROR)
13920             {
13921             MrBayesPrint ("%s   Problem calculating prior for birth-death process\n", spacer);
13922             return (ERROR);
13923             }
13924         }
13925     else if (!strcmp(mp->clockPr,"Fossilization"))
13926         {
13927         fR = GetParamVals (m->fossilizationRates, chain, state[chain]);
13928         if (LnFossilizationPriorPr (t, clockRate, &oldLnPrior, sR, eR, sF, fR, sS) == ERROR)
13929             {
13930             MrBayesPrint ("%s   Problem calculating prior for fossilized birth-death process\n", spacer);
13931             return (ERROR);
13932             }
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)
13936             {
13937             MrBayesPrint ("%s   Problem calculating prior for fossilized birth-death process\n", spacer);
13938             return (ERROR);
13939             }
13940         }
13941     else {
13942         MrBayesPrint ("%s   Move_Speciation_M not applicable\n", spacer);
13943         return (ERROR);
13944         }
13945
13946     if (isLPriorExp == NO)
13947         *lnPriorRatio = newLnPrior - oldLnPrior;
13948     else
13949         *lnPriorRatio = -lambdaExp * (newL - oldL) + (newLnPrior - oldLnPrior);
13950     
13951     return (NO_ERROR);
13952 }
13953
13954
13955 int Move_Statefreqs (Param *param, int chain, RandLong *seed, MrBFlt *lnPriorRatio, MrBFlt *lnProposalRatio, MrBFlt *mvp)
13956 {
13957     /* change pi */
13958     int         i, nStates, isValid;
13959     MrBFlt      dirichletParameters[64], *newPi, *oldPi, *priorAlpha, sum, alphaPi, x, y;
13960
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);
13966         
13967     /* tuning parameter */
13968     alphaPi = mvp[0]*nStates;
13969
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;
13973
13974     do  {
13975         DirichletRandomVariable (dirichletParameters, newPi, nStates, seed);
13976         isValid = YES;
13977         for (i=0; i<nStates; i++)
13978             {
13979             if (newPi[i] < PI_MIN)
13980                 {
13981                 isValid = NO;
13982                 break;
13983                 }
13984             }
13985         } while (isValid == NO);
13986
13987     /* get proposal ratio */
13988     sum = 0.0;
13989     for (i=0; i<nStates; i++)
13990         sum += newPi[i]*alphaPi;
13991     x = LnGamma(sum);
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]);
13996     sum = 0.0;
13997     for (i=0; i<nStates; i++)
13998         sum += oldPi[i]*alphaPi;
13999     y = LnGamma(sum);
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;
14005
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;
14013         
14014     /* Touch the entire tree */
14015     for (i=0; i<param->nRelParts; i++)
14016         TouchAllTreeNodes(&modelSettings[param->relParts[i]],chain);
14017         
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;
14024
14025     return (NO_ERROR);
14026 }
14027
14028
14029 /*----------------------------------------------------------------
14030 |
14031 |   Move_Statefreqs_Slider: Change state frequencies using Slider proposal
14032 |       mechanism.
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.
14040 |
14041 ----------------------------------------------------------------*/
14042 int Move_Statefreqs_Slider (Param *param, int chain, RandLong *seed, MrBFlt *lnPriorRatio, MrBFlt *lnProposalRatio, MrBFlt *mvp)
14043 {
14044     int         i, j, nStates, isValid;
14045     MrBFlt      delta, *newPi, *oldPi, *priorAlpha, x, y, sum, min, max;
14046
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);
14052
14053     /* get window size */
14054     delta = mvp[0];
14055
14056     /* choose a pair to change */
14057     i = (int) (RandomNumber(seed) * nStates);
14058     j = (int) (RandomNumber(seed) * (nStates-1));
14059     if (i == j)
14060         j = nStates-1;
14061     
14062     /* find new proportion */
14063     sum = oldPi[i] + oldPi[j];
14064
14065     /* reflect */
14066     isValid = NO;
14067     min = PI_MIN / sum;
14068     max = 1.0 - min;
14069
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 */
14072         {
14073         delta = max-min;
14074         }
14075     y = x + delta * (RandomNumber(seed) - 0.5);
14076
14077     do {
14078         if (y < min)
14079             y = 2.0 * min - y;
14080         else if (y > max)
14081             y = 2.0 * max - y;
14082         else
14083             isValid = YES;
14084         } while (isValid == NO);
14085
14086     /* set the new values */
14087     newPi[i] = y * sum;
14088     newPi[j] = sum - newPi[i];
14089
14090     /* get proposal ratio */
14091     *lnProposalRatio = 0.0;
14092
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;
14100
14101     /* Set update for entire tree */
14102     for (i=0; i<param->nRelParts; i++)
14103         TouchAllTreeNodes(&modelSettings[param->relParts[i]],chain);
14104         
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;
14111
14112     return (NO_ERROR);
14113 }
14114
14115
14116 int Move_StatefreqsSymDirMultistate (Param *param, int chain, RandLong *seed, MrBFlt *lnPriorRatio, MrBFlt *lnProposalRatio, MrBFlt *mvp)
14117 {
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;
14124     Model   *mp;
14125
14126     /* tuning parameters */
14127     alphaPi = mvp[0];
14128
14129     /* get model paramaters */
14130     mp = &modelParams[param->relParts[0]];
14131
14132     /* select one character at random */
14133     charIndex = (int) (RandomNumber(seed) * param->nSympi);
14134     
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++)
14142         {
14143         oldPi += param->sympinStates[i];
14144         newPi += param->sympinStates[i];
14145         }
14146     nStates = param->sympinStates[charIndex];
14147     
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;
14151
14152     DirichletRandomVariable (dirichletParameters, newPi, nStates, seed);
14153
14154     sum = 0.0;
14155     for (i=0; i<nStates; i++)
14156         {
14157         if (newPi[i] < 0.0001)
14158             newPi[i] = 0.0001;
14159         sum += newPi[i];
14160         }
14161     for (i=0; i<nStates; i++)
14162         newPi[i] /= sum;
14163
14164     /* get proposal ratio */
14165     sum = 0.0;
14166     for (i=0; i<nStates; i++)
14167         sum += newPi[i]*alphaPi;
14168     x = LnGamma(sum);
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]);
14173     sum = 0.0;
14174     for (i=0; i<nStates; i++)
14175         sum += oldPi[i]*alphaPi;
14176     y = LnGamma(sum);
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;
14182
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;
14190         
14191     for (i=0; i<param->nRelParts; i++)
14192         TouchAllTreeNodes(&modelSettings[param->relParts[i]],chain);
14193         
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;
14198
14199     return (NO_ERROR);
14200 }
14201
14202
14203 int Move_SwitchRate (Param *param, int chain, RandLong *seed, MrBFlt *lnPriorRatio, MrBFlt *lnProposalRatio, MrBFlt *mvp)
14204 {
14205     /* change switch rate of covarion model using sliding window */
14206     
14207     int         i, isSPriorExp, isValidS, whichRate;
14208     MrBFlt      oldS, newS, window, minS, maxS, sExp=0.0, ran, *value;
14209     ModelParams *mp;
14210
14211     /* decide which switching rate to change */
14212     if (RandomNumber(seed) < 0.5)
14213         whichRate = 0;
14214     else
14215         whichRate = 1;
14216         
14217     /* get size of window, centered on current switching rates value */
14218     window = mvp[0];
14219
14220     /* get model params */
14221     mp = &modelParams[param->relParts[0]];
14222     
14223     /* get minimum and maximum values for switching rate */
14224     if (param->paramId == SWITCH_UNI)
14225         {
14226         minS = mp->covswitchUni[0];
14227         maxS = mp->covswitchUni[1];
14228         isSPriorExp = NO;
14229         }
14230     else
14231         {
14232         minS = 0.01;
14233         maxS = KAPPA_MAX;
14234         sExp = mp->covswitchExp;
14235         isSPriorExp = YES;
14236         }
14237
14238     /* get old value of switching rate */
14239     value = GetParamVals(param, chain, state[chain]);
14240     newS = oldS = value[whichRate];
14241
14242     /* change value for switching rate */
14243     ran = RandomNumber(seed);
14244     if (maxS-minS < window)
14245         {
14246         window = maxS-minS;
14247         }
14248     newS = oldS + window * (ran - 0.5);
14249     
14250     /* check that new value is valid */
14251     isValidS = NO;
14252     do
14253         {
14254         if (newS < minS)
14255             newS = 2* minS - newS;
14256         else if (newS > maxS)
14257             newS = 2 * maxS - newS;
14258         else
14259             isValidS = YES;
14260         } while (isValidS == NO);
14261
14262     /* get proposal ratio */
14263     *lnProposalRatio = 0.0;
14264     
14265     /* get prior ratio */
14266     if (isSPriorExp == NO)
14267         *lnPriorRatio = 0.0;
14268     else
14269         *lnPriorRatio = -sExp * (newS - oldS);
14270     
14271     /* copy new switching rate value back */
14272     value[whichRate] = newS;
14273
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);
14278
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
14282        the cijk flag. */
14283     for (i=0; i<param->nRelParts; i++)
14284         modelSettings[param->relParts[i]].upDateCijk = YES;
14285
14286     return (NO_ERROR);
14287 }
14288
14289
14290 int Move_SwitchRate_M (Param *param, int chain, RandLong *seed, MrBFlt *lnPriorRatio, MrBFlt *lnProposalRatio, MrBFlt *mvp)
14291 {
14292     /* change switch rate of covarion model using multiplier */
14293
14294     int         i, isSPriorExp, isValidS, whichRate;
14295     MrBFlt      oldS, newS, minS, maxS, sExp=0.0, tuning, ran, factor, *value;
14296     ModelParams *mp;
14297
14298     /* decide which switching rate to change */
14299     if (RandomNumber(seed) < 0.5)
14300         whichRate = 0;
14301     else
14302         whichRate = 1;
14303         
14304     /* get tuning parameter */
14305     tuning = mvp[0];
14306
14307     /* get model params */
14308     mp = &modelParams[param->relParts[0]];
14309     
14310     /* get minimum and maximum values for switching rate */
14311     if (param->paramId == SWITCH_UNI)
14312         {
14313         minS = mp->covswitchUni[0];
14314         maxS = mp->covswitchUni[1];
14315         isSPriorExp = NO;
14316         }
14317     else
14318         {
14319         minS = 0.01;
14320         maxS = KAPPA_MAX;
14321         sExp = mp->covswitchExp;
14322         isSPriorExp = YES;
14323         }
14324
14325     /* get old value of switching rate */
14326     value = GetParamVals(param, chain, state[chain]);
14327     newS = oldS = value[whichRate];
14328
14329     /* change value for switching rate */
14330     ran = RandomNumber(seed);
14331     factor = exp(tuning * (ran - 0.5));
14332     newS = oldS * factor;
14333     
14334     /* check that new value is valid */
14335     isValidS = NO;
14336     do
14337         {
14338         if (newS < minS)
14339             newS = minS * minS / newS;
14340         else if (newS > maxS)
14341             newS = maxS * maxS / newS;
14342         else
14343             isValidS = YES;
14344         } while (isValidS == NO);
14345
14346     /* get proposal ratio */
14347     *lnProposalRatio = log (newS / oldS);
14348     
14349     /* get prior ratio */
14350     if (isSPriorExp == NO)
14351         *lnPriorRatio = 0.0;
14352     else
14353         *lnPriorRatio = -sExp * (newS - oldS);
14354     
14355     /* copy new switching rate value back */
14356     value[whichRate] = newS;
14357
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);
14362
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
14366        the cijk flag. */
14367     for (i=0; i<param->nRelParts; i++)
14368         modelSettings[param->relParts[i]].upDateCijk = YES;
14369
14370     return (NO_ERROR);
14371 }
14372
14373
14374 int Move_TK02BranchRate (Param *param, int chain, RandLong *seed, MrBFlt *lnPriorRatio, MrBFlt *lnProposalRatio, MrBFlt *mvp)
14375 {
14376     /* move one TK02 relaxed clock branch rate using multiplier */
14377     
14378     int         i;
14379     MrBFlt      newRate, oldRate, tuning, minR, maxR, nu, *tk02Rate, *brlens;
14380     TreeNode    *p = NULL;
14381     ModelInfo   *m;
14382     Tree        *t;
14383     TreeNode    *q;
14384     
14385     /* get model settings */
14386     m = &modelSettings[param->relParts[0]];
14387     
14388     /* get the tuning parameter */
14389     tuning = mvp[0];
14390     
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]);
14394     
14395     /* get tree */
14396     t = GetTree (param, chain, state[chain]);
14397     
14398     /* get minimum and maximum rate */
14399     minR = RATE_MIN;
14400     maxR = RATE_MAX;
14401     
14402     /* randomly pick a rate */
14403     do  {
14404         i = (int) (RandomNumber(seed) * (t->nNodes -2));
14405         p = t->allDownPass[i];
14406         }
14407     while (p->length < TIME_MIN);  // not ancestral fossil
14408     
14409     /* find new rate */
14410     oldRate = tk02Rate[p->index];
14411     newRate = oldRate * exp ((0.5 - RandomNumber(seed)) * tuning);
14412     
14413     /* reflect if necessary */
14414     while (newRate < minR || newRate > maxR)
14415         {
14416         if (newRate < minR)
14417             newRate = minR * minR / newRate;
14418         if (newRate > maxR)
14419             newRate = maxR * maxR / newRate;
14420         }
14421     
14422     tk02Rate[p->index] = newRate;
14423     
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)
14428         {
14429         if (p->left->length > 0.0)
14430             {
14431             (*lnPriorRatio) -= LnProbTK02LogNormal (oldRate, nu*p->left->length,  tk02Rate[p->left->index ]);
14432             (*lnPriorRatio) += LnProbTK02LogNormal (newRate, nu*p->left->length,  tk02Rate[p->left->index ]);
14433             }
14434         if (p->right->length > 0.0)
14435             {
14436             (*lnPriorRatio) -= LnProbTK02LogNormal (oldRate, nu*p->right->length, tk02Rate[p->right->index]);
14437             (*lnPriorRatio) += LnProbTK02LogNormal (newRate, nu*p->right->length, tk02Rate[p->right->index]);
14438             }
14439         }
14440     
14441     /* calculate proposal ratio */
14442     (*lnProposalRatio) = log (newRate / oldRate);
14443     
14444     /* update branch evolution lengths */
14445     brlens[p->index] = p->length * (newRate + tk02Rate[p->anc->index]) / 2.0;
14446     if (p->left != NULL)
14447         {
14448         if (p->left->length > 0.0)
14449             {
14450             brlens[p->left->index] = p->left->length  * (tk02Rate[p->left->index] + newRate) / 2.0;
14451             }
14452         if (p->right->length > 0.0)
14453             {
14454             brlens[p->right->index] = p->right->length * (tk02Rate[p->right->index] + newRate) / 2.0;
14455             }
14456         }
14457     
14458     /* set update of ti probs */
14459     p->upDateTi = YES;
14460     if (p->left != NULL)
14461         {
14462         p->left ->upDateTi = YES;
14463         p->right->upDateTi = YES;
14464         }
14465     
14466     /* set update of cond likes down to root */
14467     /* update of crowntree set in UpdateCppEvolLengths */
14468     p->upDateCl = YES;
14469     q = p->anc;
14470     while (q->anc != NULL)
14471         {
14472         q->upDateCl = YES;
14473         q = q->anc;
14474         }
14475     
14476     return (NO_ERROR);
14477 }
14478
14479
14480 int Move_Tratio_Dir (Param *param, int chain, RandLong *seed, MrBFlt *lnPriorRatio, MrBFlt *lnProposalRatio, MrBFlt *mvp)
14481 {
14482     /* change tratio using Dirichlet proposal */
14483     
14484     int         i;
14485     MrBFlt      oldK, alphaPi, *alphaDir, oldProp[2], newProp[2], dirParm[2], sum, x, y;
14486     ModelParams *mp;
14487
14488     /* get model params */
14489     mp = &modelParams[param->relParts[0]];
14490
14491     /* get so called alphaPi parameter */
14492     alphaPi = mvp[0];
14493
14494     /* get old value of kappa */
14495     oldK = *GetParamVals(param, chain, state[chain]);
14496
14497     /* get Dirichlet parameters */
14498     alphaDir = mp->tRatioDir;
14499
14500     /* calculate old ratesum proportions */
14501     oldProp[0] = oldK / (oldK + 1.0);
14502     oldProp[1] = 1.0 - oldProp[0];
14503     
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;
14507     
14508     /* get new values */
14509     DirichletRandomVariable (dirParm, newProp, 2, seed);
14510
14511     if (newProp[0] < DIR_MIN)
14512         {
14513         newProp[0] = DIR_MIN;
14514         newProp[1] = 1.0-DIR_MIN;
14515         }
14516     else if (newProp[1] < DIR_MIN)
14517         {
14518         newProp[1] = DIR_MIN;
14519         newProp[0] = 1.0-DIR_MIN;
14520         }
14521
14522     /* calculate and copy new kappa value back */
14523     *GetParamVals(param, chain, state[chain]) = newProp[0] / newProp[1];
14524
14525     /* get proposal ratio */
14526     sum = 0.0;
14527     for (i=0; i<2; i++)
14528         sum += newProp[i]*alphaPi;
14529     x = LnGamma(sum);
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]);
14534     sum = 0.0;
14535     for (i=0; i<2; i++)
14536         sum += oldProp[i]*alphaPi;
14537     y = LnGamma(sum);
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;
14543
14544     /* get prior ratio */
14545     x = y = 0.0;
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;
14551         
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);
14556
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
14560        the cijk flag. */
14561     for (i=0; i<param->nRelParts; i++)
14562         modelSettings[param->relParts[i]].upDateCijk = YES;
14563
14564     return (NO_ERROR);
14565 }
14566
14567
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)
14570 {
14571     /* change all branch lengths */
14572
14573     MrBFlt      begin_tl, treescaler, tuning, maxV, minV, brlensPrExp=0.0;
14574     TreeNode    *p;
14575     ModelParams *mp;
14576     Tree        *t;
14577     int i,branch_counter,  isVPriorExp;
14578
14579     tuning = mvp[0]; /* Larget & Simon's tuning parameter lambda */
14580
14581     mp = &modelParams[param->relParts[0]];
14582
14583     /* max and min brlen */
14584     if (param->paramId == BRLENS_UNI)
14585         {
14586         minV = mp->brlensUni[0];
14587         maxV = mp->brlensUni[1];
14588         isVPriorExp = NO;
14589         }
14590     else if (param->paramId == BRLENS_GamDir)
14591         {
14592         minV = BRLENS_MIN;
14593         maxV = BRLENS_MAX;
14594         isVPriorExp = 2;
14595         }
14596     else if (param->paramId == BRLENS_iGmDir)
14597         {
14598         minV = BRLENS_MIN;
14599         maxV = BRLENS_MAX;
14600         isVPriorExp = 3;
14601         }
14602     else if (param->paramId == BRLENS_twoExp)
14603         {
14604         minV = BRLENS_MIN;
14605         maxV = BRLENS_MAX;
14606         isVPriorExp = 4;
14607         }
14608     else
14609         {
14610         minV = BRLENS_MIN;
14611         maxV = BRLENS_MAX;
14612         brlensPrExp = mp->brlensExp;
14613         isVPriorExp = YES;
14614         }
14615
14616     /* get tree */
14617     t = GetTree (param, chain, state[chain]);
14618
14619     assert (t->isRooted == NO);
14620
14621     /* Dirichlet or twoExp prior */
14622     if (isVPriorExp > 1)
14623         (*lnPriorRatio) = -LogDirPrior(t, mp, isVPriorExp);
14624
14625     treescaler = exp(tuning * (RandomNumber(seed) - 0.5));
14626     
14627     begin_tl = 0.0;
14628     branch_counter=0;
14629
14630     for (i=0; i<t->nNodes; i++)
14631         {
14632         p = t->allDownPass[i];
14633         if (p->anc != NULL)
14634             {
14635             if (p->length*treescaler < minV || p->length*treescaler > maxV)
14636                 {
14637                 abortMove = YES;
14638                 return NO_ERROR;
14639                 }
14640             begin_tl += p->length;
14641             branch_counter++;               
14642             }
14643         }
14644     assert (branch_counter==t->nNodes-1);
14645     
14646     /* iterate scaling over all branches */
14647     for (i=0; i < t->nNodes; i++)
14648         {
14649         p = t->allDownPass[i];
14650         if (p->anc != NULL)
14651             {
14652             /* set new length */
14653             p->length *= treescaler;
14654
14655             /* set flags for update of transition probabilities at p */
14656             p->upDateTi = YES;
14657             p->anc->upDateCl = YES; 
14658             }
14659         }
14660
14661     /* calculate proposal ratio */
14662     (*lnProposalRatio) = branch_counter * log(treescaler);
14663
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);
14670
14671     return (NO_ERROR);
14672 }
14673
14674
14675 /*-----------------------------------------------------------------------------------
14676 |
14677 |   Move_TreeStretch: Shrink or grow a clock tree
14678 |
14679 -------------------------------------------------------------------------------------*/
14680 int Move_TreeStretch (Param *param, int chain, RandLong *seed, MrBFlt *lnPriorRatio, MrBFlt *lnProposalRatio, MrBFlt *mvp)
14681 {
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;
14685     TreeNode    *p, *q;
14686     ModelParams *mp;
14687     ModelInfo   *m;
14688     Tree        *t, *oldT;
14689     Param       *subParm;
14690     Calibration *calibrationPtr;
14691
14692     tuning = mvp[0]; /* Larget & Simon tuning parameter lambda */
14693  
14694     (*lnProposalRatio) = (*lnPriorRatio) = 0.0;
14695
14696     m = &modelSettings[param->relParts[0]];
14697     mp = &modelParams[param->relParts[0]];
14698
14699     /* get trees */
14700     t = GetTree (param, chain, state[chain]);
14701     oldT = GetTree (param, chain, 1^state[chain]);
14702
14703     /* min and max branch lengths in relative time and substitution units */
14704     minV = BRLENS_MIN;
14705     maxV = BRLENS_MAX;
14706
14707     /* determine multiplication factor */
14708     factor = exp(tuning * (RandomNumber(seed) - 0.5));
14709
14710     /* multiply all changeable ages and node depths by this factor */
14711     numChangedNodes = 0;
14712     for (i=0; i<t->nNodes-1; i++)
14713         {
14714         p = t->allDownPass[i];
14715             
14716         /* skip extant tip and fixed calibration */
14717         if (p->left == NULL && p->isDated == NO)
14718             continue;
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;
14723         else
14724             calibrationPtr = NULL;
14725         if (calibrationPtr != NULL && calibrationPtr->prior == fixed)
14726             continue;
14727         
14728         /* now stretch the node */
14729         if (calibrationPtr != NULL)
14730             {
14731             p->age *= factor;
14732             if (p->age < calibrationPtr->min || p->age > calibrationPtr->max)
14733                 {
14734                 abortMove = YES;
14735                 return (NO_ERROR);
14736                 }
14737             }
14738         p->nodeDepth *= factor;
14739         numChangedNodes++;
14740         
14741         /* deal with ancestral fossils */
14742         if (p->left != NULL)
14743             {
14744             if (p->left->length < TIME_MIN)
14745                 {
14746                 p->left->length = 0.0;
14747                 p->nodeDepth = p->left->nodeDepth;
14748                 if (calibrationPtr != NULL)
14749                     {
14750                     assert (p->left->calibration != NULL);
14751                     p->age = p->left->age;
14752                     if (p->age < calibrationPtr->min || p->age > calibrationPtr->max)
14753                         {
14754                         abortMove = YES;
14755                         return (NO_ERROR);
14756                         }
14757                     }
14758                 numChangedNodes--;
14759                 }
14760             if (p->right->length < TIME_MIN)
14761                 {
14762                 p->right->length = 0.0;
14763                 p->nodeDepth = p->right->nodeDepth;
14764                 if (calibrationPtr != NULL)
14765                     {
14766                     assert (p->right->calibration != NULL);
14767                     p->age = p->right->age;
14768                     if (p->age < calibrationPtr->min || p->age > calibrationPtr->max)
14769                         {
14770                         abortMove = YES;
14771                         return (NO_ERROR);
14772                         }
14773                     }
14774                 numChangedNodes--;
14775                 }
14776             assert (!(p->left->length == 0.0 && p->right->length == 0.0));
14777             }
14778         }
14779     
14780     /* update brls */
14781     for (i=0; i<t->nNodes-1; i++)
14782         {
14783         p = t->allDownPass[i];
14784         if (p->left != NULL)
14785             {
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;
14790             }
14791         }
14792
14793     /* check that all branch lengths are proper, which need not be the case */
14794     for (i = 0; i < t->nNodes -2; i++)
14795         {
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 */
14800             abortMove = YES;
14801             return NO_ERROR;
14802             }
14803         }
14804
14805     /* calculate proposal ratio */
14806     (*lnProposalRatio) = numChangedNodes * log(factor);
14807
14808     /* calculate prior ratio */
14809     if (LogClockTreePriorRatio(param, chain, &x) == ERROR)
14810         return ERROR;
14811     (*lnPriorRatio) += x;
14812
14813     /* adjust proposal and prior ratio for relaxed clock models */
14814     for (i=0; i<param->nSubParams; i++)
14815         {
14816         subParm = param->subParams[i];
14817         if (subParm->paramType == P_CPPEVENTS)
14818             {
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++)
14823                 {
14824                 p = t->allDownPass[j];
14825                 q = oldT->allDownPass[j];
14826                 (*lnProposalRatio) += nEvents[p->index ] * log (p->length  / q->length);
14827                 }
14828             /* prior ratio */
14829             (*lnPriorRatio) += lambda * (TreeLen(oldT) - TreeLen(t));
14830             /* update effective evolutionary lengths */
14831             if (UpdateCppEvolLengths (subParm, t->root->left, chain) == ERROR)
14832                 {
14833                 abortMove = YES;
14834                 return (NO_ERROR);
14835                 }
14836             }
14837         else if ( subParm->paramType == P_TK02BRANCHRATES ||
14838                  (subParm->paramType == P_MIXEDBRCHRATES && *GetParamIntVals(subParm, chain, state[chain]) == RCL_TK02))
14839             {
14840             if (subParm->paramType == P_TK02BRANCHRATES)
14841                 nu = *GetParamVals (modelSettings[subParm->relParts[0]].tk02var, chain, state[chain]);
14842             else
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]);
14846
14847             /* prior ratio and update of brlens */
14848             for (j=0; j<t->nNodes-2; j++)
14849                 {
14850                 p = t->allDownPass[j];
14851                 q = oldT->allDownPass[j];
14852                 if (p->length > 0.0)  // not ancestral fossil
14853                     {
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)
14858                         {
14859                         abortMove = YES;
14860                         return (NO_ERROR);
14861                         }
14862                     }
14863                 }
14864             }
14865         else if ( subParm->paramType == P_IGRBRANCHRATES ||
14866                  (subParm->paramType == P_MIXEDBRCHRATES && *GetParamIntVals(subParm, chain, state[chain]) == RCL_IGR))
14867             {
14868             if (subParm->paramType == P_IGRBRANCHRATES)
14869                 igrvar = *GetParamVals (modelSettings[subParm->relParts[0]].igrvar, chain, state[chain]);
14870             else
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]);
14874             
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++)
14877                 {
14878                 p = t->allDownPass[j];
14879                 q = oldT->allDownPass[j];
14880                 if (p->length > 0.0)  // not ancestral fossil
14881                     {
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)
14886                         {
14887                         abortMove = YES;
14888                         return (NO_ERROR);
14889                         }
14890                     }
14891                 }
14892             }
14893         }
14894
14895     TouchAllTreeNodes(m, chain);
14896
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));
14901 #endif
14902
14903     return (NO_ERROR);
14904 }
14905
14906
14907 /* Generalized normal move for real random variables */
14908 int Move_RealNormal (Param *param, int chain, RandLong *seed, MrBFlt *lnPriorRatio, MrBFlt *lnProposalRatio, MrBFlt *mvp)
14909 {
14910     int             i;
14911     MrBFlt          oldX, newX, tuning, minX, maxX, u, z;
14912
14913     /* get tuning parameter */
14914     tuning = mvp[0];
14915
14916     /* get minimum and maximum values for X */
14917     minX = param->min;
14918     maxX = param->max;
14919
14920     /* get old value of X */
14921     newX = oldX = *GetParamVals(param, chain, state[chain]);
14922
14923     /* change value */
14924     u = RandomNumber(seed);
14925     z = PointNormal(u);
14926     newX = oldX + z * tuning;
14927     
14928     /* check that new value is valid */
14929     if (newX < minX || newX > maxX)
14930         {
14931         abortMove = YES;
14932         return (NO_ERROR);
14933         }
14934
14935     /* get proposal ratio */
14936     (*lnProposalRatio) = 0.0;
14937     
14938     /* get prior ratio */
14939     (*lnPriorRatio) = param->LnPriorRatio(newX, oldX, param->priorParams);
14940
14941     /* copy new value back */
14942     *GetParamVals(param, chain, state[chain]) = newX;
14943
14944     /* Set update flags for tree nodes if relevant */
14945     if (param->affectsLikelihood == YES)
14946         {
14947         for (i=0; i<param->nRelParts; i++)
14948             TouchAllTreeNodes(&modelSettings[param->relParts[i]],chain);
14949         }
14950
14951     return (NO_ERROR);
14952 }
14953
14954
14955 /* Generalized slider move for real random variables */
14956 int Move_RealSlider (Param *param, int chain, RandLong *seed, MrBFlt *lnPriorRatio, MrBFlt *lnProposalRatio, MrBFlt *mvp)
14957 {
14958     int             i, isValid;
14959     MrBFlt          oldX, newX, window, minX, maxX, u;
14960
14961     /* get size of window, centered on current value */
14962     window = mvp[0];
14963
14964     /* get minimum and maximum values for X */
14965     minX = param->min;
14966     maxX = param->max;
14967
14968     /* get old value of X */
14969     newX = oldX = *GetParamVals(param, chain, state[chain]);
14970
14971     /* change value */
14972     u = RandomNumber(seed);
14973     newX = oldX + window * (u - 0.5);
14974     
14975     /* check that new value is valid */
14976     isValid = NO;
14977     do
14978         {
14979         if (newX < minX)
14980             newX = 2* minX - newX;
14981         else if (newX > maxX)
14982             newX = 2 * maxX - newX;
14983         else
14984             isValid = YES;
14985         } while (isValid == NO);
14986
14987     /* get proposal ratio */
14988     (*lnProposalRatio) = 0.0;
14989     
14990     /* get prior ratio */
14991     (*lnPriorRatio) = param->LnPriorRatio(newX, oldX, param->priorParams);
14992
14993     /* copy new value back */
14994     *GetParamVals(param, chain, state[chain]) = newX;
14995
14996     /* Set update flags for tree nodes if relevant */
14997     if (param->affectsLikelihood == YES)
14998         {
14999         for (i=0; i<param->nRelParts; i++)
15000             TouchAllTreeNodes(&modelSettings[param->relParts[i]],chain);
15001         }
15002
15003     return (NO_ERROR);
15004 }
15005
15006
15007 void TouchAllTreeNodes (ModelInfo *m, int chain)
15008 {
15009     int         i;
15010     Tree        *t;
15011     TreeNode    *p;
15012     
15013     t = GetTree(m->brlens, chain, state[chain]);
15014     for (i=0; i<t->nNodes; i++)
15015         {
15016         p = t->allDownPass[i];
15017         p->upDateCl = YES;
15018         p->upDateTi = YES;
15019         }
15020     m->upDateAll = YES;
15021 }
15022