7 * Dept. Integrative Biology
8 * University of California, Berkeley
9 * Berkeley, CA 94720-3140
13 * Swedish Museum of Natural History
15 * SE-10405 Stockholm, SWEDEN
16 * fredrik.ronquist@nrm.se
18 * With important contributions by
20 * Paul van der Mark (paulvdm@sc.fsu.edu)
21 * Maxim Teslenko (maxim.teslenko@nrm.se)
23 * and by many users (run 'acknowledgments' to see more info)
25 * This program is free software; you can redistribute it and/or
26 * modify it under the terms of the GNU General Public License
27 * as published by the Free Software Foundation; either version 2
28 * of the License, or (at your option) any later version.
30 * This program is distributed in the hope that it will be useful,
31 * but WITHOUT ANY WARRANTY; without even the implied warranty of
32 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
33 * GNU General Public License for more details (www.gnu.org).
40 #include "likelihood.h"
47 #if defined(__MWERKS__)
52 const char* const svnRevisionMcmcC = "$Rev: 1072 $"; /* Revision keyword which is expanded/updated by svn on each commit/update */
54 #if defined (WIN_VERSION) && !defined (__GNUC__)
57 typedef void (*sighandler_t) (int);
60 #define RESCALE_FREQ 1 /* node cond like rescaling frequency */
61 #define SCALER_REFRESH_FREQ 1 /* generations between refreshing scaler nodes */
62 #define GIBBS_SAMPLE_FREQ 100 /* generations between gibbs sampling of gamma cats */
63 #define MAX_SMALL_JUMP 10 /* threshold for precalculating trans probs of adgamma model */
64 #define BIG_JUMP 100 /* threshold for using stationary approximation */
65 #define MAX_RUNS 120 /* maximum number of independent runs */
70 #define MAXTUNINGPARAM 10000 /* limit to ensure convergence for autotuning */
71 #define SAMPLE_ALL_SS /* if defined makes ss sample every generation instead of every sample frequency */
72 #define BEAGLE_RESCALE_FREQ 160
73 #define BEAGLE_RESCALE_FREQ_DOUBLE 10 /* The factor by which BEAGLE_RESCALE_FREQ get multiplied if double presition is used */
74 #define TARGETLENDELTA 100
76 /* debugging compiler statements */
77 #undef DEBUG_SETUPTERMSTATE
79 #undef DEBUG_NOSHORTCUTS
80 #undef DEBUG_NOSCALING
81 #undef DEBUG_TIPROBS_STD
82 #undef DEBUG_RUN_WITHOUT_DATA
83 #undef DEBUG_CONSTRAINTS
84 #undef DEBUG_LNLIKELIHOOD /* slow if defined!! */
85 #undef DEBUG_LIKELIHOOD
86 #undef DEBUG_FBDPR // #undef FBDPR_CondOnN
89 #if defined (MPI_ENABLED)
90 #define ERROR_TEST2(failString,X1,X2) \
91 MPI_Allreduce (&nErrors, &sumErrors, 1, MPI_INT, MPI_SUM, MPI_COMM_WORLD);\
94 MrBayesPrint ("%s "failString"\n", spacer);\
98 #define ERROR_TEST2(failString,X1,X2) \
101 MrBayesPrint ("%s "failString"\n", spacer);\
106 /* local (to this file) data types */
107 typedef struct pfnode
110 struct pfnode *right;
115 /* local prototypes */
116 int AddTreeSamples (int from, int to, int saveToList);
117 PFNODE *AddPartition (PFNODE *r, BitsLong *p, int runId);
118 int AddTreeToPartitionCounters (Tree *tree, int treeId, int runId);
119 int AttemptSwap (int swapA, int swapB, RandLong *seed);
120 void BuildExhaustiveSearchTree (Tree *t, int chain, int nTaxInTree, TreeInfo *tInfo);
121 int BuildStepwiseTree (Tree *t, int chain, RandLong *seed);
122 int CalcLikeAdgamma (int d, Param *param, int chain, MrBFlt *lnL);
123 void CalcPartFreqStats (PFNODE *p, STATS *stat);
124 void CalcTopoConvDiagn (int numSamples);
126 BOOL WINAPI CatchInterrupt (DWORD signum);
128 void CatchInterrupt (int signum);
130 int CheckTemperature (void);
131 void CloseMBPrintFiles (void);
132 PFNODE *CompactTree (PFNODE *p);
133 int ConfirmAbortRun(void);
134 void CopyParams (int chain);
135 void CopyPFNodeDown (PFNODE *p);
136 void CopySiteScalers (ModelInfo *m, int chain);
137 void CopyTrees (int chain);
138 int ExtendChainQuery (void);
139 int FillNumSitesOfPat (void);
140 TreeNode *FindBestNode (Tree *t, TreeNode *p, TreeNode *addNode, CLFlt *minLength, int chain);
141 void FlipCijkSpace (ModelInfo *m, int chain);
142 void FlipCondLikeSpace (ModelInfo *m, int chain, int nodeIndex);
143 void FlipNodeScalerSpace (ModelInfo *m, int chain, int nodeIndex);
144 void FlipSiteScalerSpace (ModelInfo *m, int chain);
145 void FlipTiProbsSpace (ModelInfo *m, int chain, int nodeIndex);
146 void FreeChainMemory (void);
147 MrBFlt GetFitchPartials (ModelInfo *m, int chain, int source1, int source2, int destination);
148 void GetStamp (void);
149 void GetSwappers (int *swapA, int *swapB, int curGen);
150 void GetTempDownPassSeq (TreeNode *p, int *i, TreeNode **dp);
151 MrBFlt GibbsSampleGamma (int chain, int division, RandLong *seed);
152 int InitAdGamma(void);
153 int InitChainCondLikes (void);
154 int InitClockBrlens (Tree *t);
155 int InitEigenSystemInfo (ModelInfo *m);
156 int InitInvCondLikes (void);
157 int InitParsSets (void);
158 int InitPrintParams (void);
159 int IsPFNodeEmpty (PFNODE *p);
160 PFNODE *LargestNonemptyPFNode (PFNODE *p, int *i, int j);
161 MrBFlt LogLike (int chain);
162 MrBFlt LogPrior (int chain);
163 int LnBirthDeathPriorPrRandom (Tree *t, MrBFlt clockRate, MrBFlt *prob, MrBFlt sR, MrBFlt eR, MrBFlt sF);
164 int LnBirthDeathPriorPrDiversity (Tree *t, MrBFlt clockRate, MrBFlt *prob, MrBFlt sR, MrBFlt eR, MrBFlt sF);
165 int LnBirthDeathPriorPrCluster (Tree *t, MrBFlt clockRate, MrBFlt *prob, MrBFlt sR, MrBFlt eR, MrBFlt sF);
166 int LnFossilizedBDPriorFossilTip (Tree *t, MrBFlt clockRate, MrBFlt *prob, MrBFlt sR, MrBFlt eR, MrBFlt sF, MrBFlt fR);
167 int LnFossilizedBDPriorRandom (Tree *t, MrBFlt clockRate, MrBFlt *prob, MrBFlt *sR, MrBFlt *eR, MrBFlt sF, MrBFlt *fR);
168 int LnFossilizedBDPriorDiversity (Tree *t, MrBFlt clockRate, MrBFlt *prob, MrBFlt *sR, MrBFlt *eR, MrBFlt sF, MrBFlt *fR);
169 MrBFlt LnP0 (MrBFlt t, MrBFlt l, MrBFlt m);
170 MrBFlt LnP0Subsample (MrBFlt t, MrBFlt l, MrBFlt m, MrBFlt f);
171 MrBFlt LnP1 (MrBFlt t, MrBFlt l, MrBFlt m);
172 MrBFlt LnP1Subsample (MrBFlt t, MrBFlt l, MrBFlt m, MrBFlt f);
173 MrBFlt LnP0_fossil (MrBFlt t, MrBFlt lambda, MrBFlt mu, MrBFlt psi, MrBFlt c1, MrBFlt c2);
174 MrBFlt LnP1_fossil (MrBFlt t, MrBFlt rho, MrBFlt c1, MrBFlt c2);
175 MrBFlt LnQi_fossil (MrBFlt t, MrBFlt *t_f, int sl, MrBFlt *c1, MrBFlt *c2);
176 MrBFlt LnPi_fossil (MrBFlt t, MrBFlt *t_f, int sl, MrBFlt *c1, MrBFlt *c2, MrBFlt *lambda, MrBFlt *mu, MrBFlt *psi);
177 int NewtonRaphsonBrlen (Tree *t, TreeNode *p, int chain);
178 void NodeToNodeDistances (Tree *t, TreeNode *fromNode);
179 int PickProposal (RandLong *seed, int chainIndex);
180 int NumCppEvents (Param *p, int chain);
181 int PosSelProbs (TreeNode *p, int division, int chain);
182 #if defined (SSE_ENABLED)
183 int PosSelProbs_SSE (TreeNode *p, int division, int chain);
185 int PreparePrintFiles (void);
186 int PrintAncStates_Bin (TreeNode *p, int division, int chain);
187 int PrintAncStates_Gen (TreeNode *p, int division, int chain);
188 int PrintAncStates_NUC4 (TreeNode *p, int division, int chain);
189 int PrintAncStates_Std (TreeNode *p, int division, int chain);
190 int PrintCalTree (int curGen, Tree *tree);
191 int PrintCheckPoint (int gen);
192 int PrintMCMCDiagnosticsToFile (int curGen);
193 #if defined (MPI_ENABLED)
194 int PrintMPISlaves (FILE *fp);
196 void PrintParamValues (Param *p, int chain, char *s);
197 int PrintParsMatrix (void);
198 int PrintSiteRates_Gen (TreeNode *p, int division, int chain);
199 int PrintSiteRates_Std (TreeNode *p, int division, int chain);
200 int PrintStates (int curGen, int coldId);
201 int PrintStatesToFiles (int n);
202 int PrintSwapInfo (void);
203 int PrintTermState (void);
204 void PrintTiProbs (CLFlt *tP, MrBFlt *bs, int nStates);
205 int PrintTopConvInfo (void);
206 void PrintToScreen (int curGen, int startGen, time_t endingT, time_t startingT);
207 int PrintTree (int curGen, Param *treeParam, int chain, int showBrlens, MrBFlt clockRate);
208 MrBFlt PropAncFossil (Param *param, int chain);
209 #if defined (MPI_ENABLED)
210 int ReassembleMoveInfo (void);
211 int ReassembleParamVals (int *curId);
212 int ReassembleSwapInfo (void);
213 int ReassembleTuningParams (void);
214 void RedistributeMoveInfo (void);
215 int RedistributeParamVals (void);
216 int RedistributeTuningParams (void);
218 int RemovePartition (PFNODE *r, BitsLong *p, int runId);
219 int RemoveTreeFromPartitionCounters (Tree *tree, int treeId, int runId);
220 int RemoveTreeSamples (int from, int to);
221 int ReopenMBPrintFiles (void);
222 void ResetChainIds (void);
223 void ResetFlips(int chain);
224 int ResetScalers (void);
225 void ResetSiteScalers (ModelInfo *m, int chain);
226 int ReusePreviousResults(int *numSamples, int);
227 int RunChain (RandLong *seed);
228 int SafeSprintf (char **target, int *targetLen, char *fmt, ...);
229 void SetChainIds (void);
230 void SetFileNames (void);
231 int SetLikeFunctions (void);
232 int SetLocalChainsAndDataSplits (void);
233 int SetModelInfo (void);
235 int SetBinaryQMatrix (MrBFlt **a, int whichChain, int division);
236 int SetNucQMatrix (MrBFlt **a, int n, int whichChain, int division, MrBFlt rateMult, MrBFlt *rA, MrBFlt *rS);
237 int SetProteinQMatrix (MrBFlt **a, int n, int whichChain, int division, MrBFlt rateMult);
238 int SetStdQMatrix (MrBFlt **a, int nStates, MrBFlt *bs, int cType);
239 int SetUpPartitionCounters (void);
240 int SetUpTermState (void);
241 int SetUsedMoves (void);
242 int ShowMoveSummary (void);
243 void ShowValuesForChain (int chn);
244 int SiteOmegas (TreeNode *p, int division, int chain);
245 #if defined (SSE_ENABLED)
246 int SiteOmegas_SSE (TreeNode *p, int division, int chain);
248 PFNODE *SmallestNonemptyPFNode (PFNODE *p, int *i, int j);
249 PFNODE *Talloc (void);
250 void Tfree (PFNODE *r);
251 MrBFlt Temperature (int x);
252 void TouchAllCijks (int chain);
253 void TouchAllPartitions (void);
254 void TouchAllTrees (int chain);
255 void TouchEverything (int chain);
258 int *bsIndex; /* compressed std stat freq index */
259 Chain chainParams; /* parameters of Markov chain */
260 int *compCharPos; /* char position in compressed matrix */
261 int *compColPos; /* column position in compressed matrix */
262 BitsLong *compMatrix; /* compressed character matrix */
263 int compMatrixRowSize; /* row size of compressed matrix */
264 char inputFileName[100]; /* input (NEXUS) file name */
265 MoveType moveTypes[NUM_MOVE_TYPES]; /* holds information on the move types */
266 int numCompressedChars; /* number of compressed characters */
267 int numMoveTypes; /* the number of move types */
268 CLFlt *numSitesOfPat; /* no. sites of each pattern */
269 int *origChar; /* index from compressed char to original char */
270 char stamp[11]; /* holds a unique identifier for each analysis */
271 MrBFlt *stdStateFreqs; /* std char state frequencies */
272 int *stdType; /* compressed std char type: ord, unord, irrev */
273 int *tiIndex; /* compressed std char ti index */
275 #if defined (BEAGLE_ENABLED)
276 int recalcScalers; /* shoud we recalculate scalers for current state YES/NO */
279 /* local (to this file) variables */
280 int numLocalChains; /* number of Markov chains */
281 int *chainId = NULL; /* information on the id (0 ...) of the chain */
282 MrBFlt *curLnL = NULL; /* stores log likelihood */
283 MrBFlt *curLnPr = NULL; /* stores log prior probability */
284 int stepRelativeBurninSS; /* Should we use relative burn in within each step or not */
285 MrBFlt powerSS; /* power (betta) in power posterior destribution used in SS */
286 MrBFlt *marginalLnLSS = NULL; /* marginal liklihood obtained using stepppingstone sampling */
287 MrBFlt *stepAcumulatorSS = NULL; /* accumulates liklihoods for current step in SS */
288 MrBFlt *stepScalerSS = NULL; /* scaler of stepAcumulatorSS in log scale in SS */
289 MrBFlt *splitfreqSS = NULL; /* array holding split frequencis for each step in SS */
290 int *sympiIndex; /* sympi state freq index for multistate chars */
291 int stdStateFreqsRowSize; /* row size for std state frequencies */
292 int *weight; /* weight of each compressed char */
293 int *chainTempId; /* info ton temp, change to float holding temp? */
294 int state[MAX_CHAINS]; /* state of chain */
295 int augmentData; /* are data being augmented for any division? */
296 int *nAccepted; /* counter of accepted moves */
297 int *termState = NULL; /* stores character states of tips */
298 int *isPartAmbig = NULL; /* records whether tips are partially ambiguous */
299 BitsLong **parsPtrSpace = NULL; /* space holding pointers to parsimony sets */
300 BitsLong ***parsPtr = NULL; /* pointers to pars state sets for chain & node */
301 CLFlt *parsNodeLengthSpace = NULL; /* space for parsimony node lengths */
302 CLFlt **parsNodeLen = NULL; /* pointers to pars node lengths for chains */
303 char *printString; /* string for printing to a file */
304 size_t printStringSize; /* length of printString */
305 MCMCMove **usedMoves; /* vector of pointers to used moves */
306 int numUsedMoves; /* the number of moves used by chain */
307 Param **printParam; /* vector of pointers to normal params to print */
308 int numPrintParams; /* the number of normal params to print */
309 Param **printTreeParam; /* vector of pointers to tree params to print */
310 Param **topologyParam; /* vector of pointers to topology params */
311 int numPrintTreeParams; /* the number of tree params to print */
312 int codon[6][64]; /* holds info on amino acids coded in code */
313 int chainHasAdgamma; /* indicates if chain has adgamma HMMs */
314 int inferPosSel; /* indicates if positive selection is inferred */
315 MrBFlt *posSelProbs; /* probs. for positive selection */
316 int hasMarkovTi[MAX_SMALL_JUMP]; /* vector marking size of observed HMM jumps */
317 int *siteJump; /* vector of sitejumps for adgamma model */
318 MrBFlt **rateProbs; /* pointers to rate probs used by adgamma model */
319 MrBFlt *rateProbSpace; /* space for rate probs used by adgamma model */
320 int rateProbRowSize; /* size of rate probs for one chain one state */
321 MrBFlt **markovTi[MAX_SMALL_JUMP]; /* trans prob matrices used in calc of adgamma */
322 MrBFlt **markovTiN; /* trans prob matrices used in calc of adgamma */
323 int whichReweightNum; /* used for setting reweighting of char pats */
324 int ***swapInfo; /* keeps track of attempts & successes of swaps */
325 int tempIndex; /* keeps track of which user temp is specified */
326 int abortMove; /* flag determining whether to abort move */
327 PFNODE **partFreqTreeRoot; /* root of tree(s) holding partition freqs */
328 int nLongsNeeded; /* number of longs needed for partitions */
329 BitsLong **partition; /* matrix holding partitions */
330 MrBFlt *maxLnL0 = NULL; /* maximum likelihood */
331 FILE *fpMcmc = NULL; /* pointer to .mcmc file */
332 FILE **fpParm = NULL; /* pointer to .p file(s) */
333 FILE ***fpTree = NULL; /* pointer to .t file(s) */
334 FILE *fpSS = NULL; /* pointer to .ss file */
335 static int requestAbortRun; /* flag for aborting mcmc analysis */
336 int *topologyPrintIndex; /* print file index of each topology */
337 int *printTreeTopologyIndex; /* topology index of each tree print file */
338 int numPreviousGen; /* number of generations in run to append to */
340 #if defined (MPI_ENABLED)
341 int lowestLocalRunId; /* lowest local run Id */
342 int highestLocalRunId; /* highest local run Id */
345 #if defined (PRINT_DUMP)
346 FILE **fpDump = NULL; /* pointer to .dump file(s) */
349 /* AddPartition: Add a partition to the tree keeping track of partition frequencies */
350 PFNODE *AddPartition (PFNODE *r, BitsLong *p, int runId)
357 r = Talloc (); /* create a new node */
360 for (i=0; i<nLongsNeeded; i++)
361 r->partition[i] = p[i];
362 for (i=0; i<chainParams.numRuns; i++)
365 r->left = r->right = NULL;
369 for (i=0; i<nLongsNeeded; i++)
371 if (r->partition[i] != p[i])
375 if (i == nLongsNeeded)
377 else if (r->partition[i] < p[i])
382 if (comp == 0) /* repeated partition */
384 else if (comp < 0) /* greater than -> into left subtree */
386 if ((r->left = AddPartition (r->left, p, runId)) == NULL)
394 /* smaller than -> into right subtree */
395 if ((r->right = AddPartition (r->right, p, runId)) == NULL)
407 int AddToPrintString (char *tempStr)
411 len1 = strlen(printString);
412 len2 = strlen(tempStr);
413 if (len1 + len2 + 5 > printStringSize)
415 printStringSize += len1 + len2 - printStringSize + 200;
416 printString = (char*)SafeRealloc((void*)printString, printStringSize * sizeof(char));
419 MrBayesPrint ("%s Problem reallocating printString (%d)\n", spacer, printStringSize * sizeof(char));
423 strcat(printString, tempStr);
424 // printf ("printString(%d) -> \"%s\"\n", printStringSize, printString);
432 /* AddTreeSamples: Add tree samples from .t files to partition counters. if saveToList == YES then also save trees in tree list */
433 int AddTreeSamples (int from, int to, int saveToList)
435 int i, j, k, longestLine;
437 char *word, *s, *lineBuf;
441 int tempStrSize = TEMPSTRSIZE;
446 # if defined (MPI_ENABLED)
451 tempStr = (char *) SafeMalloc((size_t)tempStrSize * sizeof(char));
454 MrBayesPrint ("%s Problem allocating tempString (%d)\n", spacer, tempStrSize * sizeof(char));
458 for (i=0; i<numTopologies; i++)
460 t = chainParams.dtree;
462 for (j=0; j<chainParams.numRuns; j++)
464 if (numPrintTreeParams == 1)
466 if (chainParams.numRuns == 1)
467 SafeSprintf (&tempStr, &tempStrSize, "%s.t", chainParams.chainFileName);
469 SafeSprintf (&tempStr, &tempStrSize, "%s.run%d.t", chainParams.chainFileName, j+1);
473 if (chainParams.numRuns == 1)
474 SafeSprintf (&tempStr, &tempStrSize, "%s.tree%d.t", chainParams.chainFileName, i+1);
476 SafeSprintf (&tempStr, &tempStrSize, "%s.tree%d.run%d.t", chainParams.chainFileName, i+1, j+1);
479 if ((fp = OpenBinaryFileR (tempStr)) == NULL)
481 MrBayesPrint ("%s Problem openning file %s.\n", spacer, tempStr);
486 longestLine = LongestLine (fp);
489 if ((fp = OpenTextFileR (tempStr)) == NULL)
495 lineBuf = (char *) SafeCalloc (longestLine + 10, sizeof (char));
503 lastBlock = LastBlock (fp, lineBuf, longestLine);
504 fseek (fp, lastBlock, SEEK_SET);
506 for (k=1; k<=to; k++)
509 if (fgets (lineBuf, longestLine, fp) == NULL)
516 word = strtok (lineBuf, " ");
517 } while (strcmp (word, "tree") != 0);
520 s = strtok (NULL, ";");
524 if (ResetTopology (t, s) == ERROR)
531 if (AddTreeToPartitionCounters (t, i, j) == ERROR)
538 if (saveToList == YES)
539 if (AddToTreeList(&chainParams.treeList[numTopologies*j+i],t) == ERROR)
552 /* AddTreeToPartitionCounters: Break a tree into partitions and add those to counters */
553 int AddTreeToPartitionCounters (Tree *tree, int treeId, int runId)
558 if (tree->isRooted == YES)
559 nTaxa = tree->nNodes - tree->nIntNodes - 1;
561 nTaxa = tree->nNodes - tree->nIntNodes;
563 for (i=0; i<nTaxa; i++)
565 ClearBits(partition[i], nLongsNeeded);
566 SetBit(i, partition[i]);
569 for (i=0; i<tree->nIntNodes-1; i++)
571 p = tree->intDownPass[i];
572 assert (p->index >= tree->nNodes - tree->nIntNodes - (tree->isRooted == YES ? 1 : 0));
573 for (j=0; j<nLongsNeeded; j++)
575 partition[p->index][j] = partition[p->left->index][j] | partition[p->right->index][j];
578 if ((partFreqTreeRoot[treeId] = AddPartition (partFreqTreeRoot[treeId], partition[p->index], runId)) == NULL)
580 MrBayesPrint ("%s Could not allocate space for new partition in AddTreeToPartitionCounters\n", spacer);
589 int AttemptSwap (int swapA, int swapB, RandLong *seed)
591 int d, tempX, reweightingChars, isSwapSuccessful, chI, chJ, runId;
592 MrBFlt tempA, tempB, lnLikeA, lnLikeB, lnPriorA, lnPriorB, lnR, r,
593 lnLikeStateAonDataB=0.0, lnLikeStateBonDataA=0.0, lnL;
596 # if defined (MPI_ENABLED)
597 int numChainsForProc, tempIdA=0, tempIdB=0, proc, procIdForA=0, procIdForB=0, tempIdMy=0, procIdPartner=0,
598 whichElementA=0, whichElementB=0, lower, upper, areWeA, doISwap, ierror,
599 myId, partnerId, i, run;
601 MPI_Status status[2];
602 MPI_Request request[2];
605 # if defined (MPI_ENABLED)
607 /* get the number of chains handled by this proc */
608 /* the number will be corrected further down for unbalanced scenarios */
609 numChainsForProc = (int) (chainParams.numChains * chainParams.numRuns / num_procs);
613 /* are we using character reweighting? */
614 reweightingChars = NO;
615 if ((chainParams.weightScheme[0] + chainParams.weightScheme[1]) > 0.00001)
616 reweightingChars = YES;
618 # if defined (MPI_ENABLED)
620 /* figure out processors involved in swap */
622 for (proc=0; proc<num_procs; proc++)
624 /* assign or increment chain id */
625 if (proc < (chainParams.numChains * chainParams.numRuns) % num_procs)
626 upper += numChainsForProc+1;
628 upper += numChainsForProc;
630 /* if swapA lies between lower and upper
631 * chain id's we know that this is the proc
633 if (swapA >= lower && swapA < upper)
636 whichElementA = swapA - lower;
638 if (swapB >= lower && swapB < upper)
641 whichElementB = swapB - lower;
646 /* NOTE: at this point, procIdForA and procIdForB *
647 * store the proc id's of swapping procs. Also, *
648 * whichElementA and whichElementB store the *
649 * chainId[] index of swapping procs */
651 /* figure out if I am involved in the swap */
652 doISwap = areWeA = NO;
653 if (proc_id == procIdForA)
658 else if (proc_id == procIdForB)
663 /* chain's that do not swap, continue to the next iteration */
667 /* no need to communicate accross processors if swapping chains are in the same proc */
668 if (procIdForA == procIdForB)
670 if (reweightingChars == YES)
672 /* use character reweighting */
673 lnLikeStateAonDataB = 0.0;
674 for (d=0; d<numCurrentDivisions; d++)
676 m = &modelSettings[d];
677 tree = GetTree(m->brlens, whichElementA, state[whichElementA]);
679 m->Likelihood (tree->root->left, d, whichElementA, &lnL, chainId[whichElementB] % chainParams.numChains);
680 lnLikeStateAonDataB += lnL;
682 lnLikeStateBonDataA = 0.0;
683 for (d=0; d<numCurrentDivisions; d++)
685 m = &modelSettings[d];
686 tree = GetTree(m->brlens, whichElementB, state[whichElementB]);
688 m->Likelihood (tree->root->left, d, whichElementB, &lnL, chainId[whichElementA] % chainParams.numChains);
689 lnLikeStateBonDataA += lnL;
693 /*curLnPr[whichElementA] = LogPrior(whichElementA);
694 curLnPr[whichElementB] = LogPrior(whichElementB);*/
696 /* then do the serial thing - simply swap chain id's */
697 tempA = Temperature (chainId[whichElementA]);
698 tempB = Temperature (chainId[whichElementB]);
699 lnLikeA = curLnL[whichElementA];
700 lnLikeB = curLnL[whichElementB];
701 if (chainParams.isSS == YES)
706 lnPriorA = curLnPr[whichElementA];
707 lnPriorB = curLnPr[whichElementB];
708 if (reweightingChars == YES)
710 if (chainParams.isSS == YES)
711 lnR = (tempB * (lnLikeStateAonDataB*powerSS + lnPriorA) + tempA * (lnLikeStateBonDataA*powerSS + lnPriorB)) - (tempA * (lnLikeA + lnPriorA) + tempB * (lnLikeB + lnPriorB));
713 lnR = (tempB * (lnLikeStateAonDataB + lnPriorA) + tempA * (lnLikeStateBonDataA + lnPriorB)) - (tempA * (lnLikeA + lnPriorA) + tempB * (lnLikeB + lnPriorB));
716 lnR = (tempB * (lnLikeA + lnPriorA) + tempA * (lnLikeB + lnPriorB)) - (tempA * (lnLikeA + lnPriorA) + tempB * (lnLikeB + lnPriorB));
724 isSwapSuccessful = NO;
725 if (RandomNumber(seed) < r)
727 /* swap chain id's (heats) */
728 tempX = chainId[whichElementA];
729 chainId[whichElementA] = chainId[whichElementB];
730 chainId[whichElementB] = tempX;
731 if (reweightingChars == YES)
733 curLnL[whichElementA] = lnLikeStateAonDataB;
734 curLnL[whichElementB] = lnLikeStateBonDataA;
736 isSwapSuccessful = YES;
739 chI = chainId[whichElementA];
740 chJ = chainId[whichElementB];
741 if (chainId[whichElementB] < chainId[whichElementA])
743 chI = chainId[whichElementB];
744 chJ = chainId[whichElementA];
746 runId = chI / chainParams.numChains;
747 chI = chI % chainParams.numChains;
748 chJ = chJ % chainParams.numChains;
749 swapInfo[runId][chJ][chI]++;
750 if (isSwapSuccessful == YES)
751 swapInfo[runId][chI][chJ]++;
753 /* we need to communicate across processors */
756 if (reweightingChars == YES)
758 /* If we are reweighting characters, then we need to do an additional communication to
759 figure out the chainId's of the partner. We need to have this information so we can
760 properly calculate likelihoods with switched observations. */
763 lnLikeStateAonDataB = 0.0;
764 myId = chainId[whichElementA];
765 ierror = MPI_Isend (&myId, 1, MPI_INT, procIdForB, 0, MPI_COMM_WORLD, &request[0]);
766 if (ierror != MPI_SUCCESS)
770 ierror = MPI_Irecv (&partnerId, 1, MPI_INT, procIdForB, 0, MPI_COMM_WORLD, &request[1]);
771 if (ierror != MPI_SUCCESS)
775 ierror = MPI_Waitall (2, request, status);
776 if (ierror != MPI_SUCCESS)
780 for (d=0; d<numCurrentDivisions; d++)
782 m = &modelSettings[d];
783 tree = GetTree(m->brlens, whichElementA, state[whichElementA]);
785 m->Likelihood (tree->root->left, d, whichElementA, &lnL, partnerId);
786 lnLikeStateAonDataB = lnL;
791 lnLikeStateBonDataA = 0.0;
792 myId = chainId[whichElementB];
793 ierror = MPI_Isend (&myId, 1, MPI_INT, procIdForA, 0, MPI_COMM_WORLD, &request[0]);
794 if (ierror != MPI_SUCCESS)
798 ierror = MPI_Irecv (&partnerId, 1, MPI_INT, procIdForA, 0, MPI_COMM_WORLD, &request[1]);
799 if (ierror != MPI_SUCCESS)
803 ierror = MPI_Waitall (2, request, status);
804 if (ierror != MPI_SUCCESS)
808 for (d=0; d<numCurrentDivisions; d++)
810 m = &modelSettings[d];
811 tree = GetTree(m->brlens, whichElementB, state[whichElementB]);
813 m->Likelihood (tree->root->left, d, whichElementB, &lnL, partnerId);
814 lnLikeStateBonDataA = lnL;
821 /*curLnPr[whichElementA] = LogPrior(whichElementA);*/
823 /* we are processor A */
824 tempIdA = chainId[whichElementA];
825 lnLikeA = curLnL[whichElementA];
826 lnPriorA = curLnPr[whichElementA];
827 swapRan = RandomNumber(seed);
829 myStateInfo[0] = lnLikeA;
830 myStateInfo[1] = lnPriorA;
831 myStateInfo[2] = tempIdA;
832 myStateInfo[3] = swapRan;
833 myStateInfo[4] = 0.0;
834 if (reweightingChars == YES)
836 myStateInfo[2] = lnLikeStateAonDataB;
840 ierror = MPI_Isend (&myStateInfo, 5, MPI_DOUBLE, procIdForB, 0, MPI_COMM_WORLD, &request[0]);
841 if (ierror != MPI_SUCCESS)
845 ierror = MPI_Irecv (&partnerStateInfo, 5, MPI_DOUBLE, procIdForB, 0, MPI_COMM_WORLD, &request[1]);
846 if (ierror != MPI_SUCCESS)
850 ierror = MPI_Waitall (2, request, status);
851 if (ierror != MPI_SUCCESS)
856 lnLikeA = curLnL[whichElementA];
857 lnLikeB = partnerStateInfo[0];
858 if (chainParams.isSS == YES)
863 lnPriorA = curLnPr[whichElementA];
864 lnPriorB = partnerStateInfo[1];
865 if (reweightingChars == YES)
866 lnLikeStateBonDataA = partnerStateInfo[2];
868 tempIdB = partnerStateInfo[2];
870 tempA = Temperature (tempIdA);
871 tempB = Temperature (tempIdB);
873 if (reweightingChars == YES)
875 if (chainParams.isSS == YES)
876 lnR = (tempB * (lnLikeStateAonDataB*powerSS + lnPriorA) + tempA * (lnLikeStateBonDataA*powerSS + lnPriorB)) - (tempA * (lnLikeA + lnPriorA) + tempB * (lnLikeB + lnPriorB));
878 lnR = (tempB * (lnLikeStateAonDataB + lnPriorA) + tempA * (lnLikeStateBonDataA + lnPriorB)) - (tempA * (lnLikeA + lnPriorA) + tempB * (lnLikeB + lnPriorB));
881 lnR = (tempB * (lnLikeA + lnPriorA) + tempA * (lnLikeB + lnPriorB)) - (tempA * (lnLikeA + lnPriorA) + tempB * (lnLikeB + lnPriorB));
889 /* process A's random number is used to make the swap decision */
890 isSwapSuccessful = NO;
893 /* swap chain id's (heats) */
894 isSwapSuccessful = YES;
895 tempIdMy = chainId[whichElementA];
896 procIdPartner = procIdForB;
898 if (reweightingChars == YES)
899 chainId[whichElementA] = tempIdB;
901 chainId[whichElementA] = (int)(partnerStateInfo[2]);
902 if (reweightingChars == YES)
904 curLnL[whichElementA] = lnLikeStateAonDataB;
908 /* only processor A keeps track of the swap success/failure */
911 if (tempIdB < tempIdA)
916 runId = chI / chainParams.numChains;
917 chI = chI % chainParams.numChains;
918 chJ = chJ % chainParams.numChains;
919 swapInfo[runId][chJ][chI]++;
920 if (isSwapSuccessful == YES)
922 swapInfo[runId][chI][chJ]++;
923 /* exchange the move info */
924 for (i=0; i<numUsedMoves; i++)
926 myStateInfo[0] = usedMoves[i]->nAccepted[tempIdA];
927 myStateInfo[1] = usedMoves[i]->nTried[tempIdA];
928 myStateInfo[2] = usedMoves[i]->nBatches[tempIdA];
929 myStateInfo[3] = usedMoves[i]->nTotAccepted[tempIdA];
930 myStateInfo[4] = usedMoves[i]->nTotTried[tempIdA];
931 myStateInfo[5] = usedMoves[i]->lastAcceptanceRate[tempIdA];
932 if (usedMoves[i]->moveType->numTuningParams > 0)
933 myStateInfo[6] = usedMoves[i]->tuningParam[tempIdA][0];
935 myStateInfo[6] = 0.0;
937 ierror = MPI_Isend (&myStateInfo, 7, MPI_DOUBLE, procIdForB, 0, MPI_COMM_WORLD, &request[0]);
938 if (ierror != MPI_SUCCESS)
942 ierror = MPI_Irecv (&partnerStateInfo, 7, MPI_DOUBLE, procIdForB, 0, MPI_COMM_WORLD, &request[1]);
943 if (ierror != MPI_SUCCESS)
947 ierror = MPI_Waitall (2, request, status);
948 if (ierror != MPI_SUCCESS)
953 usedMoves[i]->nAccepted[tempIdB] = (int)partnerStateInfo[0];
954 usedMoves[i]->nTried[tempIdB] = (int)partnerStateInfo[1];
955 usedMoves[i]->nBatches[tempIdB] = (int)partnerStateInfo[2];
956 usedMoves[i]->nTotAccepted[tempIdB] = (int)partnerStateInfo[3];
957 usedMoves[i]->nTotTried[tempIdB] = (int)partnerStateInfo[4];
958 usedMoves[i]->lastAcceptanceRate[tempIdB] = partnerStateInfo[5];
959 if (usedMoves[i]->moveType->numTuningParams > 0)
960 usedMoves[i]->tuningParam[tempIdB][0] = partnerStateInfo[6];
962 usedMoves[i]->nAccepted[tempIdA] = 0;
963 usedMoves[i]->nTried[tempIdA] = 0;
964 usedMoves[i]->nBatches[tempIdA] = 0;
965 usedMoves[i]->lastAcceptanceRate[tempIdA] = 0.0;
966 usedMoves[i]->nTotAccepted[tempIdA] = 0;
967 usedMoves[i]->nTotTried[tempIdA] = 0;
968 if (usedMoves[i]->moveType->numTuningParams > 0)
969 usedMoves[i]->tuningParam[tempIdA][0] = 0.0;
976 /*curLnPr[whichElementB] = LogPrior(whichElementB);*/
978 /* we are processor B */
979 tempIdB = chainId[whichElementB];
980 lnLikeB = curLnL[whichElementB];
981 lnPriorB = curLnPr[whichElementB];
984 myStateInfo[0] = lnLikeB;
985 myStateInfo[1] = lnPriorB;
986 myStateInfo[2] = tempIdB;
987 myStateInfo[3] = swapRan;
988 myStateInfo[4] = 0.0;
989 if (reweightingChars == YES)
991 myStateInfo[2] = lnLikeStateBonDataA;
995 ierror = MPI_Isend (&myStateInfo, 5, MPI_DOUBLE, procIdForA, 0, MPI_COMM_WORLD, &request[0]);
996 if (ierror != MPI_SUCCESS)
1000 ierror = MPI_Irecv (&partnerStateInfo, 5, MPI_DOUBLE, procIdForA, 0, MPI_COMM_WORLD, &request[1]);
1001 if (ierror != MPI_SUCCESS)
1005 ierror = MPI_Waitall (2, request, status);
1006 if (ierror != MPI_SUCCESS)
1011 lnLikeB = curLnL[whichElementB];
1012 lnLikeA = partnerStateInfo[0];
1013 lnPriorB = curLnPr[whichElementB];
1014 lnPriorA = partnerStateInfo[1];
1015 if (reweightingChars == YES)
1016 lnLikeStateAonDataB = partnerStateInfo[2];
1018 tempIdA = partnerStateInfo[2];
1020 tempB = Temperature (tempIdB);
1021 tempA = Temperature (tempIdA);
1023 if (chainParams.isSS == YES)
1029 if (reweightingChars == YES)
1031 if (chainParams.isSS == YES)
1032 lnR = (tempB * (lnLikeStateAonDataB*powerSS + lnPriorA) + tempA * (lnLikeStateBonDataA*powerSS + lnPriorB)) - (tempA * (lnLikeA + lnPriorA) + tempB * (lnLikeB + lnPriorB));
1034 lnR = (tempB * (lnLikeStateAonDataB + lnPriorA) + tempA * (lnLikeStateBonDataA + lnPriorB)) - (tempA * (lnLikeA + lnPriorA) + tempB * (lnLikeB + lnPriorB));
1037 lnR = (tempB * (lnLikeA + lnPriorA) + tempA * (lnLikeB + lnPriorB)) - (tempA * (lnLikeA + lnPriorA) + tempB * (lnLikeB + lnPriorB));
1045 /* we use process A's random number to make the swap decision */
1046 isSwapSuccessful = NO;
1047 if (partnerStateInfo[3] < r)
1049 isSwapSuccessful = YES;
1050 tempIdMy = chainId[whichElementB];
1051 procIdPartner = procIdForA;
1053 if (reweightingChars == YES)
1054 chainId[whichElementB] = tempIdA;
1056 chainId[whichElementB] = (int)(partnerStateInfo[2]);
1057 if (reweightingChars == YES)
1059 curLnL[whichElementB] = lnLikeStateBonDataA;
1061 /* swap the move info */
1062 for (i=0; i<numUsedMoves; i++)
1064 myStateInfo[0] = usedMoves[i]->nAccepted[tempIdB];
1065 myStateInfo[1] = usedMoves[i]->nTried[tempIdB];
1066 myStateInfo[2] = usedMoves[i]->nBatches[tempIdB];
1067 myStateInfo[3] = usedMoves[i]->nTotAccepted[tempIdB];
1068 myStateInfo[4] = usedMoves[i]->nTotTried[tempIdB];
1069 myStateInfo[5] = usedMoves[i]->lastAcceptanceRate[tempIdB];
1070 if (usedMoves[i]->moveType->numTuningParams > 0)
1071 myStateInfo[6] = usedMoves[i]->tuningParam[tempIdB][0];
1073 myStateInfo[6] = 0.0;
1075 ierror = MPI_Isend (&myStateInfo, 7, MPI_DOUBLE, procIdForA, 0, MPI_COMM_WORLD, &request[0]);
1076 if (ierror != MPI_SUCCESS)
1080 ierror = MPI_Irecv (&partnerStateInfo, 7, MPI_DOUBLE, procIdForA, 0, MPI_COMM_WORLD, &request[1]);
1081 if (ierror != MPI_SUCCESS)
1085 ierror = MPI_Waitall (2, request, status);
1086 if (ierror != MPI_SUCCESS)
1091 usedMoves[i]->nAccepted[tempIdA] = (int)partnerStateInfo[0];
1092 usedMoves[i]->nTried[tempIdA] = (int)partnerStateInfo[1];
1093 usedMoves[i]->nBatches[tempIdA] = (int)partnerStateInfo[2];
1094 usedMoves[i]->nTotAccepted[tempIdA] = (int)partnerStateInfo[3];
1095 usedMoves[i]->nTotTried[tempIdA] = (int)partnerStateInfo[4];
1096 usedMoves[i]->lastAcceptanceRate[tempIdA] = partnerStateInfo[5];
1097 if (usedMoves[i]->moveType->numTuningParams > 0)
1098 usedMoves[i]->tuningParam[tempIdA][0] = partnerStateInfo[6];
1100 usedMoves[i]->nAccepted[tempIdB] = 0;
1101 usedMoves[i]->nTried[tempIdB] = 0;
1102 usedMoves[i]->nBatches[tempIdB] = 0;
1103 usedMoves[i]->nTotAccepted[tempIdB] = 0;
1104 usedMoves[i]->nTotTried[tempIdB] = 0;
1105 usedMoves[i]->lastAcceptanceRate[tempIdB] = 0.0;
1106 if (usedMoves[i]->moveType->numTuningParams > 0)
1107 usedMoves[i]->tuningParam[tempIdB][0] = 0.0;
1112 /*We exchange only if swap successful and (my id is cold or patner id is cold)*/
1113 if (chainParams.isSS == YES && isSwapSuccessful == YES && (tempIdMy % chainParams.numChains == 0 || (areWeA == YES && chainId[whichElementA] % chainParams.numChains == 0) || (areWeA == NO && chainId[whichElementB] % chainParams.numChains == 0)))
1115 run = tempIdMy/chainParams.numChains;
1117 myStateInfo[0] = tempIdMy;
1118 myStateInfo[1] = marginalLnLSS [ run ];
1119 myStateInfo[2] = stepAcumulatorSS[ run ];
1120 myStateInfo[3] = stepScalerSS [ run ];
1122 ierror = MPI_Isend (&myStateInfo, 4, MPI_DOUBLE, procIdPartner, 0, MPI_COMM_WORLD, &request[0]);
1123 if (ierror != MPI_SUCCESS)
1128 ierror = MPI_Irecv (&partnerStateInfo, 4, MPI_DOUBLE, procIdPartner, 0, MPI_COMM_WORLD, &request[1]);
1129 if (ierror != MPI_SUCCESS)
1133 ierror = MPI_Waitall (2, request, status);
1134 if (ierror != MPI_SUCCESS)
1139 /*we swap chains from the same run*/
1140 assert (run == (int)partnerStateInfo[0]/chainParams.numChains);
1142 /*If my chain is the cold chain then send current SS values of corresponding run*/
1143 if (tempIdMy % chainParams.numChains == 0)
1145 assert ((int)partnerStateInfo[0] % chainParams.numChains != 0);
1146 assert (partnerStateInfo[1] == 0.0);
1147 marginalLnLSS [ run ] = (MrBFlt) 0.0;
1148 stepAcumulatorSS[ run ] = (MrBFlt) 0.0;
1149 stepScalerSS [ run ] = (MrBFlt) 0.0;
1151 else if ((int)partnerStateInfo[0] % chainParams.numChains == 0)
1153 marginalLnLSS [ run ] = (MrBFlt) partnerStateInfo[1];
1154 stepAcumulatorSS[ run ] = (MrBFlt) partnerStateInfo[2];
1155 stepScalerSS [ run ] = (MrBFlt) partnerStateInfo[3];
1162 if (reweightingChars == YES)
1164 /* use character reweighting */
1165 lnLikeStateAonDataB = 0.0;
1166 for (d=0; d<numCurrentDivisions; d++)
1168 m = &modelSettings[d];
1169 tree = GetTree(m->brlens, swapA, state[swapA]);
1171 m->Likelihood (tree->root->left, d, swapA, &lnL, chainId[swapB] % chainParams.numChains);
1172 lnLikeStateAonDataB += lnL;
1174 lnLikeStateBonDataA = 0.0;
1175 for (d=0; d<numCurrentDivisions; d++)
1177 m = &modelSettings[d];
1178 tree = GetTree(m->brlens, swapB, state[swapB]);
1180 m->Likelihood (tree->root->left, d, swapB, &lnL, chainId[swapA] % chainParams.numChains);
1181 lnLikeStateBonDataA += lnL;
1185 assert (fabs((curLnPr[swapA]-LogPrior(swapA))/curLnPr[swapA]) < 0.0001);
1186 assert (fabs((curLnPr[swapB]-LogPrior(swapB))/curLnPr[swapB]) < 0.0001);
1188 tempA = Temperature (chainId[swapA]);
1189 tempB = Temperature (chainId[swapB]);
1190 lnLikeA = curLnL[swapA];
1191 lnLikeB = curLnL[swapB];
1192 lnPriorA = curLnPr[swapA];
1193 lnPriorB = curLnPr[swapB];
1195 if (chainParams.isSS == YES)
1201 if (reweightingChars == YES)
1203 if (chainParams.isSS == YES)
1204 lnR = (tempB * (lnLikeStateAonDataB*powerSS + lnPriorA) + tempA * (lnLikeStateBonDataA*powerSS + lnPriorB)) - (tempA * (lnLikeA + lnPriorA) + tempB * (lnLikeB + lnPriorB));
1206 lnR = (tempB * (lnLikeStateAonDataB + lnPriorA) + tempA * (lnLikeStateBonDataA + lnPriorB)) - (tempA * (lnLikeA + lnPriorA) + tempB * (lnLikeB + lnPriorB));
1209 lnR = (tempB * (lnLikeA + lnPriorA) + tempA * (lnLikeB + lnPriorB)) - (tempA * (lnLikeA + lnPriorA) + tempB * (lnLikeB + lnPriorB));
1217 isSwapSuccessful = NO;
1218 if (RandomNumber(seed) < r)
1220 tempX = chainId[swapA];
1221 chainId[swapA] = chainId[swapB];
1222 chainId[swapB] = tempX;
1224 if (reweightingChars == YES)
1226 curLnL[swapA] = lnLikeStateAonDataB;
1227 curLnL[swapB] = lnLikeStateBonDataA;
1229 isSwapSuccessful = YES;
1232 chI = chainId[swapA];
1233 chJ = chainId[swapB];
1234 if (chainId[swapB] < chainId[swapA])
1236 chI = chainId[swapB];
1237 chJ = chainId[swapA];
1239 runId = chI / chainParams.numChains;
1240 chI = chI % chainParams.numChains;
1241 chJ = chJ % chainParams.numChains;
1242 swapInfo[runId][chJ][chI]++;
1243 if (isSwapSuccessful == YES)
1244 swapInfo[runId][chI][chJ]++;
1251 /* Autotune Dirichlet move */
1252 void AutotuneDirichlet (MrBFlt acceptanceRate, MrBFlt targetRate, int batch, MrBFlt *alphaPi, MrBFlt minTuning, MrBFlt maxTuning)
1254 MrBFlt delta, logTuning, newTuning;
1256 delta = 1.0 / sqrt(batch);
1257 delta = 0.01 < delta ? 0.01 : delta;
1259 logTuning = log(*alphaPi);
1261 if (acceptanceRate > targetRate)
1266 newTuning = exp(logTuning);
1267 if (newTuning > minTuning && newTuning < maxTuning)
1268 *alphaPi = newTuning;
1272 /* Autotune multiplier move */
1273 void AutotuneMultiplier (MrBFlt acceptanceRate, MrBFlt targetRate, int batch, MrBFlt *lambda, MrBFlt minTuning, MrBFlt maxTuning)
1275 MrBFlt delta, logTuning, newTuning;
1277 delta = 1.0 / sqrt(batch);
1278 delta = 0.01 < delta ? 0.01 : delta;
1280 logTuning = log(*lambda);
1282 if (acceptanceRate > targetRate)
1287 newTuning = exp(logTuning);
1288 if (newTuning > minTuning && newTuning < maxTuning)
1289 *lambda = newTuning;
1293 /* Autotune sliding window move */
1294 void AutotuneSlider (MrBFlt acceptanceRate, MrBFlt targetRate, int batch, MrBFlt *width, MrBFlt minTuning, MrBFlt maxTuning)
1296 MrBFlt delta, logTuning, newTuning;
1298 delta = 1.0 / sqrt(batch);
1299 delta = 0.01 < delta ? 0.01 : delta;
1301 logTuning = log(*width);
1303 if (acceptanceRate > targetRate)
1308 newTuning = exp(logTuning);
1309 if (newTuning > minTuning && newTuning < maxTuning)
1314 void BuildExhaustiveSearchTree (Tree *t, int chain, int nTaxInTree, TreeInfo *tInfo)
1317 TreeNode *p, *q, *r;
1319 if (nTaxInTree == t->nIntNodes + 1) {
1324 /* Calculate cost of this tree and add to counter */
1325 tInfo->curScore = GetParsimonyLength (t, chain);
1326 if (tInfo->curScore < tInfo->minScore)
1328 tInfo->totalScore *= pow ((tInfo->warp/3.0) / (1.0 - tInfo->warp), tInfo->minScore - tInfo->curScore);
1329 tInfo->totalScore += 1.0;
1330 tInfo->minScore = tInfo->curScore;
1333 tInfo->totalScore += pow (tInfo->warp/3.0, tInfo->curScore - tInfo->minScore) * pow (1.0-tInfo->warp, tInfo->minScore - tInfo->curScore);
1338 /* find node to connect */
1339 q=tInfo->leaf[nTaxInTree];
1341 /* add using this ancestral node */
1342 p=tInfo->vertex[nTaxInTree-1];
1346 for (i=0;i<2*nTaxInTree-1;i++) {
1347 /* find node to connect to */
1349 r=tInfo->vertex[i-nTaxInTree];
1353 /* add to this node */
1359 if (r->anc->left==r)
1367 BuildExhaustiveSearchTree (t, chain, nTaxInTree+1, tInfo);
1369 if (tInfo->stopScore > 0.0 && tInfo->totalScore >= tInfo->stopScore)
1372 /* restore tree before trying next possibility */
1375 if (r->anc->left==p)
1385 /*------------------------------------------------------------------
1387 | BuildParsTrees: Fill in trees using random add seq with parsimony
1389 ------------------------------------------------------------------*/
1390 int BuildParsTrees (RandLong *seed, int fromChain, int toChain)
1396 /* Build starting trees for state 0 */
1397 for (chn=fromChain; chn<toChain; chn++)
1399 for (k=0; k<numParams; k++)
1402 if (p->paramType == P_TOPOLOGY)
1404 assert (p->nSubParams == 1);
1405 q = p->subParams[0];
1406 tree = GetTree (q, chn, 0);
1407 /* fixed topology */
1408 if (p->paramId == TOPOLOGY_RCL_FIXED ||
1409 p->paramId == TOPOLOGY_RCCL_FIXED ||
1410 p->paramId == TOPOLOGY_CL_FIXED ||
1411 p->paramId == TOPOLOGY_CCL_FIXED ||
1412 p->paramId == TOPOLOGY_NCL_FIXED ||
1413 p->paramId == TOPOLOGY_PARSIMONY_FIXED)
1415 MrBayesPrint ("%s Tree %s is fixed so a parsimony-based starting tree is not built\n", spacer, p->name);
1418 /* constrained topology */
1419 else if (tree->nConstraints > 0)
1421 MrBayesPrint ("%s Tree %s is constrained and parsimony-based starting trees are not implemented for constrained trees (yet)\n", spacer, p->name);
1424 /* random topology */
1427 if (BuildStepwiseTree (tree, chn, &globalSeed) == ERROR)
1430 if (InitializeTreeCalibrations (tree) == ERROR)
1432 FillTopologySubParams(p, chn, 0, seed);
1441 /* build (starting) topology stepwise */
1442 int BuildStepwiseTree (Tree *t, int chain, RandLong *seed) {
1445 TreeNode *p, *q, *r;
1448 // Allocate parsimony matrix if not done already
1451 for (i=j=0; i<t->nNodes; i++) {
1452 p = t->allDownPass[i];
1453 if (p->left == NULL && p->right == NULL)
1454 t->allDownPass[j++] = p;
1455 else if (p->right == NULL && p->anc == NULL && t->isRooted == NO)
1456 t->allDownPass[j++] = p;
1460 /* order the tips randomly, use last as root */
1461 for (i=0; i<nTips-1; i++) {
1462 j = (int) (RandomNumber(seed)*(nTips-1-i));
1464 p = t->allDownPass[i];
1465 t->allDownPass[i] = t->allDownPass[j];
1466 t->allDownPass[j] = p;
1469 /* build first tree */
1471 q = t->allDownPass[0];
1472 r = t->allDownPass[1];
1473 p = t->intDownPass[j++];
1478 q = t->allDownPass[nTips-1];
1485 /* add nodes one at a time */
1486 for (i=2; i<nTips-1; i++) {
1487 r = t->allDownPass[i];
1488 p = t->intDownPass[j++];
1489 GetParsDP(t, t->root->left, chain);
1490 GetParsFP(t, t->root->left, chain);
1491 q = FindBestNode(t, t->root->left, r, &length, chain);
1495 if (q->anc->left == q)
1503 /* take care of the root */
1504 if (t->isRooted == YES) {
1506 q = t->allDownPass[t->nNodes-1];
1507 p = t->intDownPass[j];
1508 q->anc = q->right = NULL;
1514 r->left = r->right = NULL;
1524 /*------------------------------------------------------------------
1526 | CalcLikeAdgamma: calc likelihood for one adgamma correlation HMM
1528 -------------------------------------------------------------------*/
1529 int CalcLikeAdgamma (int d, Param *param, int chain, MrBFlt *lnL)
1531 int c, i, j, nRates, posit, lastCharId;
1532 MrBFlt logScaler, max, prob, *F,
1533 *oldF, *tempF, fSpace[2][MAX_GAMMA_CATS];
1535 CLFlt freq, *lnScaler;
1540 /* find nRates for first division in HMM */
1541 m = &modelSettings[d];
1542 mp = &modelParams[d];
1543 nRates = m->numGammaCats;
1545 /* calculate rate category frequencies */
1546 freq = (CLFlt) ((CLFlt) 1.0 / nRates);
1548 /* find Markov trans probs */
1549 F = GetParamSubVals (param,chain, state[chain]);
1550 for (i=posit=0; i<nRates; i++)
1551 for (j=0; j<nRates; j++)
1552 markovTi[0][i][j] = F[posit++];
1554 /* precalculate Markov trans probs up to largest small jump */
1555 /* but only if needed */
1556 for (i=1; i<MAX_SMALL_JUMP; i++)
1558 if (hasMarkovTi[i] == YES)
1560 if (hasMarkovTi[i-1] == YES || i == 1)
1561 MultiplyMatrices(nRates, markovTi[i-1], markovTi[0], markovTi[i]);
1563 MultiplyMatrixNTimes(nRates, markovTi[0], i+1, markovTi[i]);
1567 /* find site scaler for this chain and state */
1568 lnScaler = m->scalers[m->siteScalerIndex[chain]];
1570 /* find rate probs for this chain and state */
1571 rP = rateProbs[chain] + state[chain] * rateProbRowSize;
1573 /* set bit vector indicating divisions in this HMM */
1574 inHMM = (BitsLong *) SafeCalloc (((param->nRelParts/nBitsInALong) + 1), sizeof(BitsLong));
1575 for (i=0; i<param->nRelParts; i++)
1577 if (modelSettings[param->relParts[i]].shape ==
1578 modelSettings[d].shape)
1580 SetBit(param->relParts[i], inHMM);
1584 /* Perform the so-called forward algorithm of HMMs */
1585 /* set up the space for f(c,i) */
1589 for (c=0; c<numChar; c++)
1591 if (IsBitSet(partitionId[c][partitionNum] - 1, inHMM) == YES)
1597 m = &modelSettings[partitionId[c][partitionNum] - 1];
1598 posit = m->rateProbStart + (compCharPos[c] - m->compCharStart) * m->numGammaCats;
1600 for (i=0; i<nRates; i++)
1607 for (i=0; i<nRates; i++)
1610 /* set logscaler to the value from the first character */
1611 logScaler = lnScaler[compCharPos[c]] + log(max);
1613 /* now step along the sequence to the end */
1614 lastCharId = charInfo[c].charId;
1615 for (c++; c<numChar; c++)
1617 /* skip if excluded */
1618 if (charInfo[c].isExcluded == YES)
1621 /* skip if part of same codon in translated protein model */
1622 if ((mp->dataType == DNA || mp->dataType == RNA) && m->dataType == PROTEIN && charInfo[c].charId == lastCharId)
1625 lastCharId = charInfo[c].charId;
1627 /* skip if not in HMM */
1628 if (IsBitSet(partitionId[c][partitionNum] - 1, inHMM) == NO)
1631 /* switch F and oldF, since the previous F is now old */
1636 /* find the position of the rate probs */
1637 m = &modelSettings[partitionId[c][partitionNum] - 1];
1638 posit = m->rateProbStart + (compCharPos[c] - m->compCharStart) * m->numGammaCats;
1640 /* calculate the HMM forward probs fi(x) at site x in HMM */
1641 if (siteJump[c] <= MAX_SMALL_JUMP)
1644 for (i=0; i<nRates; i++)
1647 for (j=0; j<nRates; j++)
1648 prob += markovTi[siteJump[c]-1][i][j] * oldF[j];
1649 F[i] = rP[posit++] * prob;
1654 else if (siteJump[c] < BIG_JUMP) /* intermediate jump, calculate trans probs */
1656 MultiplyMatrixNTimes(nRates, markovTi[0], siteJump[c], markovTiN);
1658 for (i=0; i<nRates; i++)
1661 for (j=0; j<nRates; j++)
1662 prob += markovTiN[i][j] * oldF[j];
1663 F[i] = rP[posit++] * prob;
1668 else /* big jump, use stationary freqs */
1671 for (i=0; i<nRates; i++)
1674 for (j=0; j<nRates; j++)
1675 prob += (oldF[j] / freq);
1676 F[i] = rP[posit++] * prob;
1682 /* rescale and adjust total scaler with HMM scaler and site scaler */
1683 for (i=0; i<nRates; i++)
1686 logScaler += lnScaler[compCharPos[c]] + log(max);
1690 /* now pull the rate probs together at the end, F contains the vals needed */
1692 for (i=0; i<nRates; i++)
1693 prob += (freq * F[i]);
1695 (*lnL) = logScaler + log(prob);
1703 /* CalcPartFreqStats: Calculate standard deviation of partition frequencies */
1704 void CalcPartFreqStats (PFNODE *p, STATS *stat)
1707 MrBFlt f, sum, sumsq, stdev;
1709 n = chainParams.numRuns;
1710 min = (int)(chainParams.minPartFreq * stat->numSamples);
1711 if ((MrBFlt)min != chainParams.minPartFreq * stat->numSamples)
1714 /* recursively compute partition frequencies for all subpartitions */
1715 if (p->left != NULL)
1716 CalcPartFreqStats (p->left, stat);
1717 if (p->right != NULL)
1718 CalcPartFreqStats (p->right, stat);
1722 if (p->count[i] >= min)
1733 f = (MrBFlt) (p->count[i]) / (MrBFlt) (stat->numSamples);
1738 f = (sumsq - sum * sum / n) / (n - 1);
1745 if (stdev > stat->max)
1748 stat->numPartitions++;
1750 if (chainParams.allComps == YES)
1754 for (j=i+1; j<n; j++)
1756 if (p->count[i] < min && p->count[j] < min)
1762 f = (MrBFlt) (p->count[i]) / (MrBFlt) (stat->numSamples);
1766 f = (MrBFlt) (p->count[j]) / (MrBFlt) (stat->numSamples);
1770 f = (sumsq - sum * sum / 2.0);
1776 if (chainParams.diagnStat == AVGSTDDEV)
1777 stat->pair[i][j] += stdev;
1778 else if (stdev > stat->pair[i][j])
1779 stat->pair[i][j] = stdev;
1787 /*----------------------------------------------------------------
1789 | CalcTopoConvDiagn: Calculate average and max standard deviation
1790 | in clade credibility (partition frequency) values
1792 ----------------------------------------------------------------*/
1793 void CalcTopoConvDiagn (int numSamples)
1798 for (n=0; n<numTopologies; n++)
1800 stat = &chainParams.stat[n];
1801 stat->numSamples = numSamples;
1802 stat->numPartitions = 0.0;
1806 if (chainParams.allComps == YES)
1808 for (i=0; i<chainParams.numRuns; i++)
1809 for (j=0; j<chainParams.numRuns; j++)
1810 stat->pair[i][j] = 0.0;
1813 CalcPartFreqStats (partFreqTreeRoot[n], stat);
1815 stat->avgStdDev = stat->sum / stat->numPartitions;
1820 /* used in DoCompRefTree */
1821 void PartFreq (PFNODE *p, STATS *stat, int *ntrees)
1823 int i, n = chainParams.numRuns;
1824 MrBFlt f, sum, sumsq, stdev;
1826 /* recursively compute partition frequencies for all subpartitions */
1827 if (p->left != NULL)
1828 PartFreq (p->left, stat, ntrees);
1829 if (p->right != NULL)
1830 PartFreq (p->right, stat, ntrees);
1833 for (i=0; i<chainParams.numRuns; i++)
1835 f = (MrBFlt)(p->count[i]) / (MrBFlt)ntrees[i];
1840 f = (sumsq - sum * sum / n) / (n - 1);
1847 if (stat->max < stdev)
1850 stat->numPartitions++;
1852 void CalcTopoConvDiagn2 (int *nTrees)
1857 for (n=0; n<numTopologies; n++)
1859 stat = &chainParams.stat[n];
1860 stat->numPartitions = 0.0;
1861 stat->sum = stat->max = 0.0;
1863 PartFreq (partFreqTreeRoot[n], stat, nTrees);
1865 stat->avgStdDev = stat->sum / stat->numPartitions;
1870 int CheckTemperature (void)
1872 if (chainParams.userDefinedTemps == YES)
1874 if (AreDoublesEqual(chainParams.userTemps[0], 1.0, ETA)==NO)
1876 MrBayesPrint ("%s The first user-defined temperature must be 1.0.\n", spacer);
1885 void CloseMBPrintFiles (void)
1889 # if defined (MPI_ENABLED)
1894 for (n=0; n<chainParams.numRuns; n++)
1896 SafeFclose (&fpParm[n]);
1897 #if defined (PRINT_DUMP)
1898 SafeFclose (&fpDump[n]);
1901 for (i=0; i<numTrees; i++)
1905 fprintf (fpTree[n][i], "end;\n");
1906 SafeFclose (&fpTree[n][i]);
1911 if (chainParams.mcmcDiagn == YES)
1912 SafeFclose (&fpMcmc);
1914 if (chainParams.isSS == YES)
1919 /* CompactTree: prune partition tree */
1920 PFNODE *CompactTree (PFNODE *p)
1929 if (IsPFNodeEmpty(p) == YES)
1931 /* steal info from terminal on the way up */
1932 q = SmallestNonemptyPFNode (p->left, &i, 0);
1933 r = LargestNonemptyPFNode (p->right, &j, 0);
1935 if (q != NULL || r != NULL)
1940 for (i=0; i<chainParams.numRuns; i++)
1942 p->count[i] = q->count[i];
1945 for (i=0; i<nLongsNeeded; i++)
1946 p->partition[i] = q->partition[i];
1950 p->left = CompactTree (p->left);
1951 p->right = CompactTree (p->right);
1953 /* delete on the way down if empty */
1954 if (IsPFNodeEmpty(p) == YES)
1964 /*-----------------------------------------------------------------
1966 | CopyParams: copy parameters of touched divisions
1968 -----------------------------------------------------------------*/
1969 void CopyParams (int chain)
1971 int i, j, k, fromState, toState, *fromInt, *toInt;
1976 /* copy all params */
1977 /* now done for all vars, can also be done for only touched vars */
1978 /* but then m->upDateCl must be kept separate for each chain! */
1979 for (i=0; i<numParams; i++)
1983 from = GetParamVals (p, chain, state[chain]);
1984 to = GetParamVals (p, chain, (state[chain] ^ 1));
1986 for (j=0; j<p->nValues; j++)
1989 from = GetParamSubVals (p, chain, state[chain]);
1990 to = GetParamSubVals (p, chain, (state[chain] ^ 1));
1992 for (j=0; j<p->nSubValues; j++)
1995 fromInt = GetParamIntVals (p, chain, state[chain]);
1996 toInt = GetParamIntVals (p, chain, (state[chain] ^ 1));
1998 for (j=0; j<p->nIntValues; j++)
1999 toInt[j] = fromInt[j];
2001 if (p->nStdStateFreqs > 0)
2003 from = GetParamStdStateFreqs (p, chain, state[chain]);
2004 to = GetParamStdStateFreqs (p, chain, state[chain] ^ 1);
2005 for (j=0; j<p->nStdStateFreqs; j++)
2009 if (p->paramType == P_CPPEVENTS)
2011 fromState = 2*chain + state[chain];
2012 toState = 2*chain + (state[chain] ^ 1);
2013 for (j=0; j<2*numLocalTaxa-2; j++)
2015 if (p->nEvents[toState][j] != p->nEvents[fromState][j])
2017 if (p->nEvents[fromState][j] == 0)
2019 free (p->position[toState][j]);
2020 p->position[toState][j] = NULL;
2021 free (p->rateMult[toState][j]);
2022 p->rateMult[toState][j] = NULL;
2024 else if (p->nEvents[toState][j] == 0)
2026 p->position[toState][j] = (MrBFlt *) SafeCalloc (p->nEvents[fromState][j], sizeof (MrBFlt));
2027 p->rateMult[toState][j] = (MrBFlt *) SafeCalloc (p->nEvents[fromState][j], sizeof (MrBFlt));
2031 p->position[toState][j] = (MrBFlt *) SafeRealloc ((void *)p->position[toState][j], p->nEvents[fromState][j] * sizeof (MrBFlt));
2032 p->rateMult[toState][j] = (MrBFlt *) SafeRealloc ((void *)p->rateMult[toState][j], p->nEvents[fromState][j] * sizeof (MrBFlt));
2034 p->nEvents[toState][j] = p->nEvents[fromState][j];
2036 if (p->nEvents[fromState][j] > 0)
2038 for (k=0; k<p->nEvents[fromState][j]; k++)
2040 p->position[toState][j][k] = p->position[fromState][j][k];
2041 p->rateMult[toState][j][k] = p->rateMult[fromState][j][k];
2048 /* copy division params (model settings) for chain */
2049 /* reset division update flags */
2050 fromState = 2 * chain + state[chain];
2051 toState = 2 * chain + (state[chain] ^ 1);
2052 for (i=0; i<numCurrentDivisions; i++)
2054 m = &modelSettings[i];
2055 m->lnLike[toState] = m->lnLike[fromState];
2056 if (m->parsModelId == YES)
2057 m->parsTreeLength[toState] = m->parsTreeLength[fromState];
2067 /* CopySiteScalers: Copy site scalers from scratch space into current space */
2068 void CopySiteScalers (ModelInfo *m, int chain)
2071 # if defined (BEAGLE_ENABLED)
2075 # if defined (BEAGLE_ENABLED)
2076 if (m->useBeagle == YES)
2078 j = m->siteScalerScratchIndex;
2079 for (i=0; i<m->nCijkParts; i++)
2081 beagleResetScaleFactors (m->beagleInstance,
2082 m->siteScalerIndex[chain] + i);
2083 beagleAccumulateScaleFactors (m->beagleInstance,
2086 m->siteScalerIndex[chain] + i);
2092 from = m->scalers[m->siteScalerScratchIndex];
2093 to = m->scalers[m->siteScalerIndex[chain]];
2094 memcpy ((void*) to, (void*) from, (size_t)(m->numChars) * sizeof(CLFlt));
2098 /*-----------------------------------------------------------------
2100 | CopyTrees: copies touched trees for chain
2101 | resets division and node update flags in the process
2102 | Note: partition information of nodes are not copied if
2103 | either source or destination tree does not have bitsets allocated
2105 -----------------------------------------------------------------*/
2106 void CopyTrees (int chain)
2108 int i, j, n, nTaxa, nLongsNeeded;
2112 /* reset division update flags */
2113 for (i=0; i<numCurrentDivisions; i++)
2114 modelSettings[i].upDateCl = NO;
2116 for (n=0; n<numTrees; n++)
2118 from = GetTreeFromIndex (n, chain, state[chain]);
2119 to = GetTreeFromIndex (n, chain, (state[chain] ^ 1));
2120 if (from->bitsets != NULL && to->bitsets != NULL)
2122 if (from->isRooted == NO)
2123 nTaxa = from->nNodes - from->nIntNodes;
2125 nTaxa = from->nNodes - from->nIntNodes - 1;
2126 nLongsNeeded = (int)((nTaxa - 1) / nBitsInALong) + 1;
2132 for (j=0; j<from->nNodes; j++)
2135 p = from->nodes + j;
2139 q->anc = to->nodes + p->anc->memoryIndex;
2143 if (p->left != NULL)
2144 q->left = to->nodes + p->left->memoryIndex;
2148 if (p->right != NULL)
2149 q->right = to->nodes + p->right->memoryIndex;
2153 CopyTreeNodes (q, p, nLongsNeeded);
2154 q->upDateCl = q->upDateTi = NO; /* reset update flags */
2157 for (i=0; i<from->nIntNodes; i++)
2159 to->intDownPass[i] = to->nodes + from->intDownPass[i]->memoryIndex;
2161 for (i=0; i<from->nNodes; i++)
2163 to->allDownPass[i] = to->nodes + from->allDownPass[i]->memoryIndex;
2166 to->root = to->nodes + from->root->memoryIndex;
2168 /* rest of tree info is constant and need not be copied */
2176 BOOL WINAPI CatchInterrupt (DWORD signum)
2178 /* set up signal handler to do the same */
2179 MrBayesPrint ("\n Ctrl-C detected\n");
2180 requestAbortRun = YES;
2184 void CatchInterrupt (int signum)
2186 /* set up signal handler to do the same */
2187 signal (signum, CatchInterrupt);
2188 requestAbortRun = YES;
2189 MrBayesPrint ("\n Ctrl-C detected\n");
2194 /*----------------------------------------------------------------
2196 | DebugNodeScalers: Calculate node scalers sum
2198 -----------------------------------------------------------------*/
2199 CLFlt DebugNodeScalers (TreeNode *p, int division, int chain)
2206 m = &modelSettings[division];
2209 scP = m->scalers[m->nodeScalerIndex[chain][p->index]];
2211 /* remove scalers */
2212 for (c=0; c<m->numChars; c++)
2219 /*----------------------------------------------------------------
2221 | DebugTreeScalers: Calculate DebugNodeScalers for each node and printit
2223 -----------------------------------------------------------------*/
2224 void DebugTreeScalers(int chain, int d)
2231 m = &modelSettings[d];
2232 tree = GetTree(m->brlens, chain, state[chain]);
2234 if (m->parsModelId == NO)
2236 for (i=0; i<tree->nIntNodes; i++)
2238 p = tree->intDownPass[i];
2240 if (p->scalerNode == YES)
2242 printf ("Node:%d Sum scalers:%f\n",p->index,DebugNodeScalers(p, d, chain));
2256 char *strBuf,*tmpcp;
2259 # if defined (BEST_MPI_ENABLED)
2263 # if !defined (VISUAL) && !defined (MPI_ENABLED)
2264 sighandler_t sigint_oldhandler, sigterm_oldhandler;
2267 numPreviousGen = 0; /* Make sure this is reset */
2269 /* Check to see that we have a data matrix. Otherwise, the MCMC is rather
2271 if (defMatrix == NO)
2273 MrBayesPrint ("%s A character matrix must be defined first\n", spacer);
2277 if (setUpAnalysisSuccess == NO)
2279 MrBayesPrint ("%s The analysis could not be started because there was an error during its setup.\n", spacer);
2280 MrBayesPrint ("%s Refer to error messages printed during model set up to adress the problem.\n", spacer);
2284 /* set file names */
2285 sumtParams.numRuns = chainParams.numRuns;
2286 sumpParams.numRuns = chainParams.numRuns;
2287 sumssParams.numRuns = chainParams.numRuns;
2289 if (fileNameChanged == YES)
2292 fileNameChanged = NO;
2295 MrBayesPrint ("%s Running Markov chain\n", spacer);
2297 /* Check the chain temperature parameters */
2298 if (CheckTemperature () == ERROR)
2301 /* Set the chain random number seeds here. We have two seeds. One
2302 (called swapSeed) is only used to determine which two chains
2303 will swap states in the next trial. The other (called seed) is
2304 the seed for our work-horse pseudorandom number generator. Note
2305 that if we are doing MPI, we want the swap seed to be the same
2306 for every processor. This is taken care of when we initialize
2307 things in the program. If we are doing MPI, we also want to make
2308 certain that seed is different for every processor. */
2309 # if defined (MPI_ENABLED)
2310 seed = globalSeed + (proc_id + 1);
2317 /* Get a unique identifier (stamp) for this run. This is used as
2318 an identifier for each mcmc analysis. It uses runIDSeed to initialize
2319 the stamp. All of the processors should have the same seed, so
2320 this should be safe. */
2323 MrBayesPrint ("%s Seed = %d\n", spacer, seed);
2324 MrBayesPrint ("%s Swapseed = %d\n", spacer, swapSeed);
2326 /* Show the model to make sure the user sees it before running the analysis */
2327 if (ShowModel() == ERROR)
2329 MrBayesPrint ("\n");
2331 /* Warn the user or stop analysis in case the model is strange */
2332 if (CheckModel() == ERROR)
2335 /* Determine the number of local chains and data splits */
2336 if (SetLocalChainsAndDataSplits() == ERROR)
2339 /* Set up the moves to be used */
2340 if (SetUsedMoves () == ERROR)
2343 /* Check to see that we have at least one move. Otherwise, the MCMC is rather
2345 if (numUsedMoves == 0)
2347 MrBayesPrint ("%s No move is currently switched on.\n", spacer);
2348 MrBayesPrint ("%s There must be at least one move to run an MCMC analysis.\n", spacer);
2349 MrBayesPrint ("%s Switch on moves using the 'propset' command.\n", spacer);
2353 /* Show summary table of moves that will be used */
2354 if (ShowMoveSummary () == ERROR)
2357 /* Set the likelihood function pointers. */
2358 if (SetLikeFunctions () == ERROR)
2361 /* Set up number of characters of each character pattern. */
2362 if (FillNumSitesOfPat () == ERROR)
2365 /* Initialize parsimony sets. */
2366 if (InitParsSets() == ERROR)
2369 /* Set up a terminal state index matrix for local compression. */
2370 if (SetUpTermState() == ERROR)
2373 /* Initialize conditional likelihoods and transition probabilities for chain (the working space). */
2374 if (InitChainCondLikes () == ERROR)
2377 /* Initialize adgamma conditional likelihoods */
2378 if (InitAdGamma () == ERROR)
2381 /* Initialize invariable conditional likelihoods. */
2382 if (InitInvCondLikes() == ERROR)
2385 /* Allocate BEST chain variables */
2386 if (numTopologies > 1 && !strcmp(modelParams[0].topologyPr,"Speciestree"))
2387 AllocateBestChainVariables();
2389 /* allocate SS memory for the chains if needed */
2390 if (chainParams.isSS == YES)
2392 if (memAllocs[ALLOC_SS] == YES)
2394 MrBayesPrint ("%s SS is already allocated\n", spacer);
2397 else if ((marginalLnLSS = (MrBFlt *) SafeCalloc (chainParams.numRuns, sizeof(MrBFlt))) == NULL)
2399 MrBayesPrint ("%s Problem allocating marginalLnLSS\n", spacer);
2402 else if ((stepScalerSS = (MrBFlt *) SafeCalloc (chainParams.numRuns, sizeof(MrBFlt))) == NULL)
2404 MrBayesPrint ("%s Problem allocating stepScalerSS\n", spacer);
2405 free (marginalLnLSS);
2408 else if ((stepAcumulatorSS = (MrBFlt *) SafeCalloc (chainParams.numRuns, sizeof(MrBFlt))) == NULL)
2410 MrBayesPrint ("%s Problem allocating stepAcumulatorSS\n", spacer);
2411 free (stepScalerSS);
2412 free (marginalLnLSS);
2415 else if ((splitfreqSS = (MrBFlt *) SafeCalloc (chainParams.numStepsSS*numTopologies, sizeof(MrBFlt))) == NULL)
2417 MrBayesPrint ("%s Problem allocating splitfreqSS\n", spacer);
2418 free (stepScalerSS);
2419 free (marginalLnLSS);
2420 free (stepAcumulatorSS);
2424 memAllocs[ALLOC_SS] = YES;
2427 /* Either append to previous run or deal with starting values */
2428 if (chainParams.append == YES)
2430 /* Continue old run */
2432 /* Get starting values from checkpoint file */
2433 MrBayesPrint ("%s Getting values from previous run\n", spacer);
2434 strcpy(inputFileName, chainParams.chainFileName);
2435 strcat(inputFileName, ".ckp");
2436 if (OpenTextFileR(inputFileName) == NULL)
2438 MrBayesPrint ("%s Could not find the checkpoint file '%s'.\n", spacer, inputFileName);
2439 MrBayesPrint ("%s Make sure it is in the working directory.\n", spacer);
2443 if (DoExecute () == ERROR)
2446 /* Get number of generations to start from and SS information if needed */
2449 # if defined (MPI_ENABLED)
2452 tempFile = OpenBinaryFileR (inputFileName);
2453 do { c = fgetc(tempFile);
2454 } while (c!=':' && c!=EOF);
2457 do { c = fgetc(tempFile);
2458 } while (c!=':' && c!=EOF);
2462 do { c = fgetc(tempFile);
2463 } while (!isdigit(c) && c!=EOF);
2468 while (c >= '0' && c <= '9' && i < 18)
2471 c = fgetc(tempFile);
2474 numPreviousGen = atoi(temp);
2476 if (chainParams.isSS==YES && c!=EOF)
2478 do { c = fgetc(tempFile);
2479 } while (c!=':' && c!=EOF);
2480 strBuf = (char *) SafeCalloc (chainParams.numRuns*20,sizeof(char));
2481 if (fgets(strBuf,chainParams.numRuns*20,tempFile)==NULL)
2483 MrBayesPrint ("%s Error: Reading SsAcumulators from .ckp file fails.\n", spacer);
2488 tmpcp=strtok(strBuf," ");
2489 for (run=0; run<chainParams.numRuns; run++)
2493 MrBayesPrint ("%s Error: Not enough values in SsAcumulators comment of .ckp file. \n", spacer);
2499 stepScalerSS[run]=tmp-10;
2500 stepAcumulatorSS[run]=exp(10);
2501 tmpcp=strtok(NULL," ]");
2506 # if defined (MPI_ENABLED)
2508 MPI_Bcast (&numPreviousGen, 1, MPI_INT, 0, MPI_COMM_WORLD);
2510 if (numPreviousGen == 0)
2512 MrBayesPrint ("%s Could not find the number of generations in previous run.\n", spacer);
2515 else if (numPreviousGen >= chainParams.numGen)
2517 MrBayesPrint ("%s The specified number of generations (%d) was already finished in\n", spacer, chainParams.numGen);
2518 MrBayesPrint ("%s the previous run you are trying to append to.\n", spacer);
2522 MrBayesPrint ("%s Using samples up to generation %d from previous analysis.\n", spacer, numPreviousGen);
2528 /* deal with starting param values */
2529 if (!strcmp(chainParams.startParams,"Reset"))
2531 MrBayesPrint ("%s Resetting starting values for substitution model parameters\n", spacer);
2532 FillNormalParams (&seed, 0, numLocalChains);
2535 /* deal with starting treeparam values */
2536 if (!strcmp(chainParams.startTree,"Random"))
2538 MrBayesPrint ("%s Resetting starting trees and tree parameters\n", spacer);
2539 FillTreeParams (&seed, 0, numLocalChains);
2541 else if (!strcmp(chainParams.startTree,"Parsimony"))
2543 MrBayesPrint ("%s Rebuilding starting trees using random addition sequences and parsimony\n", spacer);
2544 BuildParsTrees (&seed, 0, numLocalChains);
2547 /* Perturb start trees if requested */
2548 if (chainParams.numStartPerts > 0)
2550 MrBayesPrint ("%s Randomly perturbing starting trees\n", spacer);
2551 for (i=0; i<numTrees; i++)
2553 for (j=0; j<numGlobalChains; j++)
2554 RandPerturb (GetTreeFromIndex(i, j, 0), chainParams.numStartPerts, &seed);
2559 /* Set clockRate if we have calibration */
2560 for (j=0; j<numGlobalChains; j++)
2562 if (UpdateClockRate(0.0, j) == ERROR)
2566 for (i=0; i<numParams; i++)
2568 for (j=0; j<numGlobalChains; j++)
2569 assert (IsTreeConsistent(¶ms[i], j, 0) == YES);
2572 /* Initialize vectors of print parameters */
2573 if (InitPrintParams () == ERROR)
2576 /*! setup a signal handler to catch interrupts, ignore failure */
2578 SetConsoleCtrlHandler (CatchInterrupt, TRUE);
2580 # if !defined (MPI_ENABLED)
2581 /* we do not want to mess with the signal handling in MPI version */
2582 sigint_oldhandler = signal(SIGINT, CatchInterrupt);
2583 sigterm_oldhandler = signal(SIGTERM, CatchInterrupt);
2586 requestAbortRun = NO;
2588 /* Run the Markov chain. */
2589 rc = RunChain (&seed);
2593 SetConsoleCtrlHandler (CatchInterrupt, FALSE);
2595 # if !defined (MPI_ENABLED)
2596 signal(SIGINT, sigint_oldhandler);
2597 signal(SIGTERM, sigterm_oldhandler);
2602 else if (rc == ABORT)
2607 SetConsoleCtrlHandler (CatchInterrupt, FALSE);
2609 # if !defined (MPI_ENABLED)
2610 signal(SIGINT, sigint_oldhandler);
2611 signal(SIGTERM, sigterm_oldhandler);
2617 /*! restore the default signal handler */
2619 SetConsoleCtrlHandler (CatchInterrupt, FALSE);
2621 # if !defined (MPI_ENABLED)
2622 signal(SIGINT, sigint_oldhandler);
2623 signal(SIGTERM, sigterm_oldhandler);
2627 /* Reset the global seed at end of chain. We don't want successive
2628 chains to all start with the same random number seed. */
2631 /* Free up all memory allocated for the chain. */
2644 if (defMatrix == NO)
2646 MrBayesPrint ("%s A character matrix must be defined first\n", spacer);
2650 sumtParams.numRuns = chainParams.numRuns;
2651 sumpParams.numRuns = chainParams.numRuns;
2653 if (fileNameChanged == YES)
2656 fileNameChanged = NO;
2659 MrBayesPrint ("%s Successfully set chain parameters\n", spacer);
2665 int DoSsParm (char *parmName, char *tkn)
2670 static int negBurninss;
2672 if (defMatrix == NO)
2674 MrBayesPrint ("%s A character matrix must be defined first\n", spacer);
2678 if (expecting == Expecting(PARAMETER))
2680 expecting = Expecting(EQUALSIGN);
2684 if (!strcmp(parmName, "Burninss"))
2686 if (expecting == Expecting(EQUALSIGN))
2689 expecting = Expecting(NUMBER) | Expecting(DASH);
2691 else if (expecting == Expecting(DASH))
2694 expecting = Expecting(NUMBER);
2696 else if (expecting == Expecting(NUMBER))
2698 sscanf (tkn, "%d", &tempI);
2699 if (negBurninss == NO)
2700 chainParams.burninSS = tempI;
2702 chainParams.burninSS = -tempI;
2703 MrBayesPrint ("%s Setting burnin for stepping-stone sampling to %d\n", spacer, chainParams.burninSS);
2704 expecting = Expecting(PARAMETER) | Expecting(SEMICOLON);
2711 else if (!strcmp(parmName, "Nsteps"))
2713 if (expecting == Expecting(EQUALSIGN))
2714 expecting = Expecting(NUMBER);
2715 else if (expecting == Expecting(NUMBER))
2717 sscanf (tkn, "%d", &tempI);
2718 chainParams.numStepsSS = tempI;
2719 MrBayesPrint ("%s Setting number of steps in stepping-stone sampling to %d\n", spacer, chainParams.numStepsSS);
2720 expecting = Expecting(PARAMETER) | Expecting(SEMICOLON);
2727 else if (!strcmp(parmName, "FromPrior"))
2729 if (expecting == Expecting(EQUALSIGN))
2730 expecting = Expecting(ALPHA);
2731 else if (expecting == Expecting(ALPHA))
2733 if (IsArgValid(tkn, tempStr) == NO_ERROR)
2735 if (!strcmp(tempStr, "Yes"))
2736 chainParams.startFromPriorSS = YES;
2738 chainParams.startFromPriorSS = NO;
2742 MrBayesPrint ("%s Invalid argument for FromPrior parameter\n", spacer);
2745 MrBayesPrint ("%s Setting FromPrior=%s\n", spacer, (chainParams.startFromPriorSS==YES)?"Yes":"No");
2746 expecting = Expecting(PARAMETER) | Expecting(SEMICOLON);
2753 else if (!strcmp(parmName, "Alpha"))
2755 if (expecting == Expecting(EQUALSIGN))
2756 expecting = Expecting(NUMBER);
2757 else if (expecting == Expecting(NUMBER))
2759 sscanf (tkn, "%lf", &tempD);
2760 chainParams.alphaSS = tempD;
2761 MrBayesPrint ("%s Setting alpha in stepping-stone sampling to %lf\n", spacer, chainParams.alphaSS);
2762 expecting = Expecting(PARAMETER) | Expecting(SEMICOLON);
2778 int DoMcmcParm (char *parmName, char *tkn)
2783 int tempStrSize = TEMPSTRSIZE;
2785 tempStr = (char *) SafeMalloc((size_t)tempStrSize * sizeof(char));
2788 MrBayesPrint ("%s Problem allocating tempString (%d)\n", spacer, tempStrSize * sizeof(char));
2793 if (defMatrix == NO)
2795 MrBayesPrint ("%s A character matrix must be defined first\n", spacer);
2799 if (expecting == Expecting(PARAMETER))
2801 expecting = Expecting(EQUALSIGN);
2805 /* set Seed (globalSeed) ***************************************************************/
2806 if (!strcmp(parmName, "Seed"))
2808 MrBayesPrint ("%s Error: Setting \"Seed\" in mcmc command is depricated. Use \"set\" command instead.\n", spacer);
2809 MrBayesPrint ("%s For more information type \"help set\";\n", spacer);
2813 if (expecting == Expecting(EQUALSIGN))
2814 expecting = Expecting(NUMBER);
2815 else if (expecting == Expecting(NUMBER))
2817 sscanf (tkn, "%d", &tempI);
2819 MrBayesPrint ("%s Setting seed to %ld\n", spacer, globalSeed);
2820 expecting = Expecting(PARAMETER) | Expecting(SEMICOLON);
2829 /* set Swapseed (global variable swapSeed) ***************************************************************/
2830 else if (!strcmp(parmName, "Swapseed"))
2832 MrBayesPrint ("%s Error: Setting \"Swapseed\" in mcmc command is depricated. Use \"set\" command instead.\n", spacer);
2833 MrBayesPrint ("%s For more information type \"help set\";\n", spacer);
2837 if (expecting == Expecting(EQUALSIGN))
2838 expecting = Expecting(NUMBER);
2839 else if (expecting == Expecting(NUMBER))
2841 sscanf (tkn, "%d", &tempI);
2843 MrBayesPrint ("%s Setting swapseed to %ld\n", spacer, swapSeed);
2844 expecting = Expecting(PARAMETER) | Expecting(SEMICOLON);
2854 /* this setting is provided for GRID use only, so that identical runs can be generated */
2855 else if (!strcmp(parmName, "Runidseed"))
2857 if (expecting == Expecting(EQUALSIGN))
2858 expecting = Expecting(NUMBER);
2859 else if (expecting == Expecting(NUMBER))
2861 sscanf (tkn, "%d", &tempI);
2863 MrBayesPrint ("%s Setting run ID [stamp] seed to %ld [for GRID use]\n", spacer, runIDSeed);
2864 expecting = Expecting(PARAMETER) | Expecting(SEMICOLON);
2872 /* set Ngen (numGen) ******************************************************************/
2873 else if (!strcmp(parmName, "Ngen"))
2875 if (expecting == Expecting(EQUALSIGN))
2876 expecting = Expecting(NUMBER);
2877 else if (expecting == Expecting(NUMBER))
2879 sscanf (tkn, "%d", &tempI);
2882 MrBayesPrint ("%s Too few generations\n", spacer);
2885 chainParams.numGen = tempI;
2886 MrBayesPrint ("%s Setting number of generations to %d\n", spacer, chainParams.numGen);
2887 expecting = Expecting(PARAMETER) | Expecting(SEMICOLON);
2895 /* set Samplefreq (sampleFreq) ********************************************************/
2896 else if (!strcmp(parmName, "Samplefreq"))
2898 if (expecting == Expecting(EQUALSIGN))
2899 expecting = Expecting(NUMBER);
2900 else if (expecting == Expecting(NUMBER))
2902 sscanf (tkn, "%d", &tempI);
2905 MrBayesPrint ("%s Sampling chain too infrequently\n", spacer);
2909 chainParams.sampleFreq = tempI;
2910 MrBayesPrint ("%s Setting sample frequency to %d\n", spacer, chainParams.sampleFreq);
2911 expecting = Expecting(PARAMETER) | Expecting(SEMICOLON);
2919 /* set Printfreq (printFreq) **********************************************************/
2920 else if (!strcmp(parmName, "Printfreq"))
2922 if (expecting == Expecting(EQUALSIGN))
2923 expecting = Expecting(NUMBER);
2924 else if (expecting == Expecting(NUMBER))
2926 sscanf (tkn, "%d", &tempI);
2929 MrBayesPrint ("%s Printing to screen too infrequently\n", spacer);
2933 chainParams.printFreq = tempI;
2934 MrBayesPrint ("%s Setting print frequency to %d\n", spacer, chainParams.printFreq);
2935 expecting = Expecting(PARAMETER) | Expecting(SEMICOLON);
2943 /* set Printmax (printMax) **********************************************************/
2944 else if (!strcmp(parmName, "Printmax"))
2946 if (expecting == Expecting(EQUALSIGN))
2947 expecting = Expecting(NUMBER);
2948 else if (expecting == Expecting(NUMBER))
2950 sscanf (tkn, "%d", &tempI);
2953 MrBayesPrint ("%s You need to print at least one chain\n", spacer);
2956 chainParams.printMax = tempI;
2957 MrBayesPrint ("%s Setting maximum number of chains to print to screen to %d\n", spacer, chainParams.printMax);
2958 expecting = Expecting(PARAMETER) | Expecting(SEMICOLON);
2966 /* set Printall (printAll) ********************************************************/
2967 else if (!strcmp(parmName, "Printall"))
2969 if (expecting == Expecting(EQUALSIGN))
2970 expecting = Expecting(ALPHA);
2971 else if (expecting == Expecting(ALPHA))
2973 if (IsArgValid(tkn, tempStr) == NO_ERROR)
2975 if (!strcmp(tempStr, "Yes"))
2976 chainParams.printAll = YES;
2978 chainParams.printAll = NO;
2982 MrBayesPrint ("%s Invalid argument for Printall\n", spacer);
2986 if (chainParams.allChains == YES)
2987 MrBayesPrint ("%s Printing all chains to screen\n", spacer);
2989 MrBayesPrint ("%s Printing only cold chains to screen\n", spacer);
2990 expecting = Expecting(PARAMETER) | Expecting(SEMICOLON);
2998 /* set Swapfreq (swapFreq) ************************************************************/
2999 else if (!strcmp(parmName, "Swapfreq"))
3001 if (expecting == Expecting(EQUALSIGN))
3002 expecting = Expecting(NUMBER);
3003 else if (expecting == Expecting(NUMBER))
3005 sscanf (tkn, "%d", &tempI);
3008 MrBayesPrint ("%s Swapping states too infrequently\n", spacer);
3012 chainParams.swapFreq = tempI;
3013 MrBayesPrint ("%s Setting swap frequency to %d\n", spacer, chainParams.swapFreq);
3014 expecting = Expecting(PARAMETER) | Expecting(SEMICOLON);
3022 /* set Nswaps (numSwaps) ************************************************************/
3023 else if (!strcmp(parmName, "Nswaps"))
3025 if (expecting == Expecting(EQUALSIGN))
3026 expecting = Expecting(NUMBER);
3027 else if (expecting == Expecting(NUMBER))
3029 sscanf (tkn, "%d", &tempI);
3032 MrBayesPrint ("%s There must be at least one swap per swapping cycle\n", spacer);
3036 chainParams.numSwaps = tempI;
3037 MrBayesPrint ("%s Setting number of swaps per swapping cycle to %d\n", spacer, chainParams.numSwaps);
3038 expecting = Expecting(PARAMETER) | Expecting(SEMICOLON);
3046 /* set Allchains (allChains) ********************************************************/
3047 else if (!strcmp(parmName, "Allchains"))
3049 if (expecting == Expecting(EQUALSIGN))
3050 expecting = Expecting(ALPHA);
3051 else if (expecting == Expecting(ALPHA))
3053 if (IsArgValid(tkn, tempStr) == NO_ERROR)
3055 if (!strcmp(tempStr, "Yes"))
3056 chainParams.allChains = YES;
3058 chainParams.allChains = NO;
3062 MrBayesPrint ("%s Invalid argument for Allchains\n", spacer);
3066 if (chainParams.allChains == YES)
3067 MrBayesPrint ("%s Calculating MCMC diagnostics for all chains\n", spacer);
3069 MrBayesPrint ("%s Calculating MCMC diagnostics only for cold chain(s)\n", spacer);
3070 expecting = Expecting(PARAMETER) | Expecting(SEMICOLON);
3078 /* set Allcomps (allComps) ************************************************************/
3079 else if (!strcmp(parmName, "Allcomps"))
3081 if (expecting == Expecting(EQUALSIGN))
3082 expecting = Expecting(ALPHA);
3083 else if (expecting == Expecting(ALPHA))
3085 if (IsArgValid(tkn, tempStr) == NO_ERROR)
3087 if (!strcmp(tempStr, "Yes"))
3088 chainParams.allComps = YES;
3090 chainParams.allComps = NO;
3094 MrBayesPrint ("%s Invalid argument for Allcomps\n", spacer);
3098 if (chainParams.allComps == YES)
3099 MrBayesPrint ("%s Calculating MCMC diagnostics for all pairwise run comparisons\n", spacer);
3101 MrBayesPrint ("%s Only calculating overall MCMC diagnostics\n", spacer);
3102 expecting = Expecting(PARAMETER) | Expecting(SEMICOLON);
3110 /* set Mcmcdiagn (mcmcDiagn) ********************************************************/
3111 else if (!strcmp(parmName, "Mcmcdiagn"))
3113 if (expecting == Expecting(EQUALSIGN))
3114 expecting = Expecting(ALPHA);
3115 else if (expecting == Expecting(ALPHA))
3117 if (IsArgValid(tkn, tempStr) == NO_ERROR)
3119 if (!strcmp(tempStr, "Yes"))
3120 chainParams.mcmcDiagn = YES;
3122 chainParams.mcmcDiagn = NO;
3126 MrBayesPrint ("%s Invalid argument for mcmc diagnostics\n", spacer);
3130 if (chainParams.mcmcDiagn == YES)
3131 MrBayesPrint ("%s Setting calculation of MCMC diagnostics ('Mcmcdiagn') to yes\n", spacer);
3133 MrBayesPrint ("%s Setting calculation of MCMC diagnostics ('Mcmcdiagn') to no\n", spacer);
3134 expecting = Expecting(PARAMETER) | Expecting(SEMICOLON);
3142 /* set Diagnfreq (diagnFreq) ************************************************************/
3143 else if (!strcmp(parmName, "Diagnfreq"))
3145 if (expecting == Expecting(EQUALSIGN))
3146 expecting = Expecting(NUMBER);
3147 else if (expecting == Expecting(NUMBER))
3149 sscanf (tkn, "%d", &tempI);
3152 MrBayesPrint ("%s Diagnosing MCMC behavior too infrequently\n", spacer);
3156 chainParams.diagnFreq = tempI;
3157 MrBayesPrint ("%s Setting diagnosing frequency to %d\n", spacer, chainParams.diagnFreq);
3158 expecting = Expecting(PARAMETER) | Expecting(SEMICOLON);
3166 /* set Savetrees (saveTrees) ********************************************************/
3167 else if (!strcmp(parmName, "Savetrees"))
3169 if (expecting == Expecting(EQUALSIGN))
3170 expecting = Expecting(ALPHA);
3171 else if (expecting == Expecting(ALPHA))
3173 if (IsArgValid(tkn, tempStr) == NO_ERROR)
3175 if (!strcmp(tempStr, "Yes"))
3176 chainParams.saveTrees = YES;
3178 chainParams.saveTrees = NO;
3182 MrBayesPrint ("%s Invalid argument for Savetrees\n", spacer);
3186 if (chainParams.saveTrees == YES)
3187 MrBayesPrint ("%s Saving trees for MCMC diagnostics in memory (if needed)\n", spacer);
3189 MrBayesPrint ("%s Not saving trees for MCMC diagnostics in memory\n", spacer);
3190 expecting = Expecting(PARAMETER) | Expecting(SEMICOLON);
3198 /* set Diagnstat (diagnStat) ********************************************************/
3199 else if (!strcmp(parmName, "Diagnstat"))
3201 if (expecting == Expecting(EQUALSIGN))
3202 expecting = Expecting(ALPHA);
3203 else if (expecting == Expecting(ALPHA))
3205 if (IsArgValid(tkn, tempStr) == NO_ERROR)
3207 if (!strcmp(tempStr, "Avgstddev"))
3208 chainParams.diagnStat = AVGSTDDEV;
3209 else /* if (!strcmp(tempStr, "Maxstddev")) */
3210 chainParams.diagnStat = MAXSTDDEV;
3214 MrBayesPrint ("%s Invalid argument for Savetrees\n", spacer);
3218 if (chainParams.diagnStat == AVGSTDDEV)
3219 MrBayesPrint ("%s Setting diagnostics statistic to Avgstddev\n", spacer);
3220 else /* if (chainParams.diagnStat == MAXSTDDEV) */
3221 MrBayesPrint ("%s Setting diagnostics statistic to Maxstddev\n", spacer);
3222 expecting = Expecting(PARAMETER) | Expecting(SEMICOLON);
3230 /* set Checkpoint (checkPoint) ********************************************************/
3231 else if (!strcmp(parmName, "Checkpoint"))
3233 if (expecting == Expecting(EQUALSIGN))
3234 expecting = Expecting(ALPHA);
3235 else if (expecting == Expecting(ALPHA))
3237 if (IsArgValid(tkn, tempStr) == NO_ERROR)
3239 if (!strcmp(tempStr, "Yes"))
3240 chainParams.checkPoint = YES;
3242 chainParams.checkPoint = NO;
3246 MrBayesPrint ("%s Invalid argument for 'Checkpoint' (check-pointing)\n", spacer);
3250 if (chainParams.checkPoint == YES)
3251 MrBayesPrint ("%s Setting check-pointing ('Checkpoint') to yes\n", spacer);
3253 MrBayesPrint ("%s Setting check-pointing ('Checkpoint') to no\n", spacer);
3254 expecting = Expecting(PARAMETER) | Expecting(SEMICOLON);
3262 /* set Checkfreq (checkFreq) ************************************************************/
3263 else if (!strcmp(parmName, "Checkfreq"))
3265 if (expecting == Expecting(EQUALSIGN))
3266 expecting = Expecting(NUMBER);
3267 else if (expecting == Expecting(NUMBER))
3269 sscanf (tkn, "%d", &tempI);
3272 MrBayesPrint ("%s Check-pointing frequency must be at least 100\n", spacer);
3276 chainParams.checkFreq = tempI;
3277 MrBayesPrint ("%s Setting check-pointing frequency to %d\n", spacer, chainParams.checkFreq);
3278 expecting = Expecting(PARAMETER) | Expecting(SEMICOLON);
3286 /* set Minpartfreq (minPartFreq) ************************************************************/
3287 else if (!strcmp(parmName, "Minpartfreq"))
3289 if (expecting == Expecting(EQUALSIGN))
3290 expecting = Expecting(NUMBER);
3291 else if (expecting == Expecting(NUMBER))
3293 sscanf (tkn, "%lf", &tempD);
3296 MrBayesPrint ("%s Minimum partition frequency too low (< 0.01)\n", spacer);
3302 MrBayesPrint ("%s Minimum partition frequency too high (> 0.8)\n", spacer);
3306 chainParams.minPartFreq = tempD;
3307 MrBayesPrint ("%s Setting minimum partition frequency to %.2f\n", spacer, chainParams.minPartFreq);
3308 expecting = Expecting(PARAMETER) | Expecting(SEMICOLON);
3316 /* set Nruns (numRuns) ****************************************************************/
3317 else if (!strcmp(parmName, "Nruns"))
3319 if (expecting == Expecting(EQUALSIGN))
3320 expecting = Expecting(NUMBER);
3321 else if (expecting == Expecting(NUMBER))
3323 sscanf (tkn, "%d", &tempI);
3326 MrBayesPrint ("%s Too few runs (minimum of 1 run)\n", spacer);
3330 if (tempI > MAX_RUNS)
3332 MrBayesPrint ("%s Too many runs (maximum of %d runs)\n", spacer, MAX_RUNS);
3336 if (ChangeNumRuns (chainParams.numRuns, tempI) == ERROR)
3338 chainParams.numRuns = tempI;
3339 fileNameChanged = YES;
3340 MrBayesPrint ("%s Setting number of runs to %d\n", spacer, chainParams.numRuns);
3341 expecting = Expecting(PARAMETER) | Expecting(SEMICOLON);
3349 /* set Nchains (numChains) ************************************************************/
3350 else if (!strcmp(parmName, "Nchains"))
3352 if (expecting == Expecting(EQUALSIGN))
3353 expecting = Expecting(NUMBER);
3354 else if (expecting == Expecting(NUMBER))
3356 sscanf (tkn, "%d", &tempI);
3359 MrBayesPrint ("%s Too few chains (minimum of 1 chain)\n", spacer);
3363 if (tempI > MAX_CHAINS)
3365 MrBayesPrint ("%s Too many chains (maximum of %d chains)\n", spacer, MAX_CHAINS);
3369 if (ChangeNumChains (chainParams.numChains, tempI) == ERROR)
3371 chainParams.numChains = tempI;
3372 MrBayesPrint ("%s Setting number of chains to %d\n", spacer, chainParams.numChains);
3373 expecting = Expecting(PARAMETER) | Expecting(SEMICOLON);
3381 /* set Temp (chainTemp) ***************************************************************/
3382 else if (!strcmp(parmName, "Temp"))
3384 if (expecting == Expecting(EQUALSIGN))
3387 expecting = Expecting(NUMBER) | Expecting(LEFTPAR);
3389 else if (expecting == Expecting(LEFTPAR))
3391 chainParams.userDefinedTemps = YES;
3392 expecting = Expecting(NUMBER);
3394 else if (expecting == Expecting(RIGHTPAR))
3396 MrBayesPrint ("%s Setting user-defined temperatures\n", spacer);
3397 expecting = Expecting(PARAMETER) | Expecting(SEMICOLON);
3399 else if (expecting == Expecting(COMMA))
3401 expecting = Expecting(NUMBER);
3403 else if (expecting == Expecting(NUMBER))
3405 if (chainParams.userDefinedTemps == NO)
3407 sscanf (tkn, "%lf", &tempD);
3408 chainParams.chainTemp = tempD;
3409 MrBayesPrint ("%s Setting heating parameter to %lf\n", spacer, chainParams.chainTemp);
3410 expecting = Expecting(PARAMETER) | Expecting(SEMICOLON);
3414 if (tempIndex >= MAX_CHAINS)
3416 MrBayesPrint ("%s Too many user-defined temperatures (%d maximum)\n", spacer, MAX_CHAINS);
3420 sscanf (tkn, "%lf", &tempD);
3421 chainParams.userTemps[tempIndex++] = tempD;
3422 expecting = Expecting(COMMA) | Expecting(RIGHTPAR);
3431 /* set Reweight (weightScheme) ********************************************************/
3432 else if (!strcmp(parmName, "Reweight"))
3434 if (expecting == Expecting(EQUALSIGN))
3435 expecting = Expecting(LEFTPAR);
3436 else if (expecting == Expecting(LEFTPAR))
3438 expecting = Expecting(NUMBER);
3439 whichReweightNum = 0;
3441 else if (expecting == Expecting(NUMBER))
3443 if (whichReweightNum < 0 || whichReweightNum > 2)
3448 sscanf (tkn, "%lf", &tempD);
3449 chainParams.weightScheme[whichReweightNum] = tempD;
3450 if (whichReweightNum < 2)
3452 if (tempD < 0.0 || tempD > 100.0)
3454 MrBayesPrint ("%s The reweighting parameter must be between 0 and 100\n", spacer);
3455 chainParams.weightScheme[0] = chainParams.weightScheme[1] = 0.0;
3456 chainParams.weightScheme[2] = 1.0;
3463 if (tempD <= 0.0 || tempD > 1.0)
3465 MrBayesPrint ("%s The reweighting increment must be between 0 and 1\n", spacer);
3466 chainParams.weightScheme[0] = chainParams.weightScheme[1] = 0.0;
3467 chainParams.weightScheme[2] = 1.0;
3472 if (whichReweightNum == 0)
3474 expecting = Expecting(COMMA);
3476 else if (whichReweightNum == 1)
3478 if (chainParams.weightScheme[0] + chainParams.weightScheme[1] > 100.0)
3480 MrBayesPrint ("%s The sum of the reweighting parameters cannot exceed 100 %%\n", spacer);
3481 chainParams.weightScheme[0] = chainParams.weightScheme[1] = 0.0;
3482 chainParams.weightScheme[2] = 1.0;
3486 expecting = Expecting(COMMA) | Expecting(RIGHTPAR);
3490 expecting = Expecting(RIGHTPAR);
3494 else if ((expecting & Expecting(COMMA)) == Expecting(COMMA))
3495 expecting = Expecting(NUMBER);
3496 else if ((expecting & Expecting(RIGHTPAR)) == Expecting(RIGHTPAR))
3498 if (chainParams.weightScheme[0] >= 100.0)
3500 MrBayesPrint ("%s Cannot decrease weight of all characters\n", spacer);
3501 chainParams.weightScheme[0] = chainParams.weightScheme[1] = 0.0;
3502 chainParams.weightScheme[2] = 1.0;
3506 MrBayesPrint ("%s Setting reweighting parameter to (%1.2lf v, %1.2lf ^) increment = %1.2lf\n",
3507 spacer, chainParams.weightScheme[0], chainParams.weightScheme[1], chainParams.weightScheme[2]);
3508 expecting = Expecting(PARAMETER) | Expecting(SEMICOLON);
3516 /* set Filename (chainFileName) *******************************************************/
3517 else if (!strcmp(parmName, "Filename"))
3519 if (expecting == Expecting(EQUALSIGN))
3521 expecting = Expecting(ALPHA);
3524 else if (expecting == Expecting(ALPHA))
3526 sscanf (tkn, "%s", tempStr);
3527 if (strlen(tempStr)>99)
3529 MrBayesPrint ("%s Maximum allowed length of chain file name is 99 characters. The given name:\n", spacer);
3530 MrBayesPrint ("%s '%s'\n", spacer,tempStr);
3531 MrBayesPrint ("%s has %d characters.\n", spacer,strlen(tempStr));
3534 strcpy (chainParams.chainFileName, tempStr);
3535 fileNameChanged = YES;
3536 expecting = Expecting(PARAMETER) | Expecting(SEMICOLON);
3544 /* set Relburnin (relativeBurnin) ********************************************************/
3545 else if (!strcmp(parmName, "Relburnin"))
3547 if (expecting == Expecting(EQUALSIGN))
3548 expecting = Expecting(ALPHA);
3549 else if (expecting == Expecting(ALPHA))
3551 if (IsArgValid(tkn, tempStr) == NO_ERROR)
3553 if (!strcmp(tempStr, "Yes"))
3554 chainParams.relativeBurnin = YES;
3556 chainParams.relativeBurnin = NO;
3560 MrBayesPrint ("%s Invalid argument for Relburnin\n", spacer);
3564 if (chainParams.relativeBurnin == YES)
3565 MrBayesPrint ("%s Using relative burnin (a fraction of samples discarded).\n", spacer);
3567 MrBayesPrint ("%s Using absolute burnin (a fixed number of samples discarded).\n", spacer);
3568 expecting = Expecting(PARAMETER) | Expecting(SEMICOLON);
3576 /* set Burnin (chainBurnIn) ***********************************************************/
3577 else if (!strcmp(parmName, "Burnin"))
3579 if (expecting == Expecting(EQUALSIGN))
3580 expecting = Expecting(NUMBER);
3581 else if (expecting == Expecting(NUMBER))
3583 sscanf (tkn, "%d", &tempI);
3584 chainParams.chainBurnIn = tempI;
3585 MrBayesPrint ("%s Setting chain burn-in to %d\n", spacer, chainParams.chainBurnIn);
3586 expecting = Expecting(PARAMETER) | Expecting(SEMICOLON);
3594 /* set Burninfrac (burninFraction) ************************************************************/
3595 else if (!strcmp(parmName, "Burninfrac"))
3597 if (expecting == Expecting(EQUALSIGN))
3598 expecting = Expecting(NUMBER);
3599 else if (expecting == Expecting(NUMBER))
3601 sscanf (tkn, "%lf", &tempD);
3604 MrBayesPrint ("%s Burnin fraction too low (< 0.01)\n", spacer);
3610 MrBayesPrint ("%s Burnin fraction too high (> 0.50)\n", spacer);
3614 chainParams.burninFraction = tempD;
3615 MrBayesPrint ("%s Setting burnin fraction to %.2f\n", spacer, chainParams.burninFraction);
3616 expecting = Expecting(PARAMETER) | Expecting(SEMICOLON);
3624 /* set Stoprule (stopRule) ********************************************************/
3625 else if (!strcmp(parmName, "Stoprule"))
3627 if (expecting == Expecting(EQUALSIGN))
3628 expecting = Expecting(ALPHA);
3629 else if (expecting == Expecting(ALPHA))
3631 if (IsArgValid(tkn, tempStr) == NO_ERROR)
3633 if (!strcmp(tempStr, "Yes"))
3634 chainParams.stopRule = YES;
3636 chainParams.stopRule = NO;
3640 MrBayesPrint ("%s Invalid argument for Stoprule\n", spacer);
3644 if (chainParams.stopRule == YES)
3645 MrBayesPrint ("%s Using stopping rule.\n", spacer);
3647 MrBayesPrint ("%s Not using stopping rule.\n", spacer);
3648 expecting = Expecting(PARAMETER) | Expecting(SEMICOLON);
3656 /* set Stopval (stopVal) ************************************************************/
3657 else if (!strcmp(parmName, "Stopval"))
3659 if (expecting == Expecting(EQUALSIGN))
3660 expecting = Expecting(NUMBER);
3661 else if (expecting == Expecting(NUMBER))
3663 sscanf (tkn, "%lf", &tempD);
3664 if (tempD < 0.000001)
3666 MrBayesPrint ("%s Stop value too low (< 0.000001)\n", spacer);
3672 MrBayesPrint ("%s Stop value too high (> 0.20)\n", spacer);
3676 chainParams.stopVal = tempD;
3677 MrBayesPrint ("%s Setting burnin fraction to %.2f\n", spacer, chainParams.burninFraction);
3678 expecting = Expecting(PARAMETER) | Expecting(SEMICOLON);
3686 /* set Starttree (startTree) **************************************************/
3687 else if (!strcmp(parmName, "Starttree"))
3689 if (expecting == Expecting(EQUALSIGN))
3690 expecting = Expecting(ALPHA);
3691 else if (expecting == Expecting(ALPHA))
3693 if (IsArgValid(tkn, tempStr) == NO_ERROR)
3695 if (!strcmp(tempStr,"User"))
3697 MrBayesPrint ("%s The 'user' setting of 'Starttree' is deprecated. Set starting trees using 'Startvals' instead.\n", spacer);
3702 strcpy(chainParams.startTree, tempStr);
3706 MrBayesPrint ("%s Invalid 'Starttree' argument '%s'. This is a bug -- please report.\n", spacer, tempStr);
3710 MrBayesPrint ("%s Setting 'Starttree' to \"%s\"\n", spacer, chainParams.startTree);
3711 expecting = Expecting(PARAMETER) | Expecting(SEMICOLON);
3719 /* set Startingtrees (deprecated) **************************************************/
3720 else if (!strcmp(parmName, "Startingtrees"))
3723 MrBayesPrint ("%s Parameter 'Startingtrees' is deprecated. Use the 'Starttree' parameter or the 'Startvals' command instead.\n", spacer);
3726 /* set Nperts (numStartPerts) *********************************************************/
3727 else if (!strcmp(parmName, "Nperts"))
3729 if (expecting == Expecting(EQUALSIGN))
3730 expecting = Expecting(NUMBER);
3731 else if (expecting == Expecting(NUMBER))
3733 sscanf (tkn, "%d", &tempI);
3734 chainParams.numStartPerts = tempI;
3735 MrBayesPrint ("%s Setting number of perturbations to start tree to %d\n", spacer, chainParams.numStartPerts);
3736 expecting = Expecting(PARAMETER) | Expecting(SEMICOLON);
3744 /* set Startparams (startParams) **************************************************/
3745 else if (!strcmp(parmName, "Startparams"))
3747 if (expecting == Expecting(EQUALSIGN))
3748 expecting = Expecting(ALPHA);
3749 else if (expecting == Expecting(ALPHA))
3751 if (IsArgValid(tkn, tempStr) == NO_ERROR)
3752 strcpy(chainParams.startParams, tempStr);
3755 MrBayesPrint ("%s Invalid 'Startparams' argument\n", spacer);
3759 MrBayesPrint ("%s Setting 'Startparams' to \"%s\"\n", spacer, chainParams.startParams);
3760 expecting = Expecting(PARAMETER) | Expecting(SEMICOLON);
3768 /* set Savebrlens (saveBrlens) ********************************************************/
3769 else if (!strcmp(parmName, "Savebrlens"))
3771 if (expecting == Expecting(EQUALSIGN))
3772 expecting = Expecting(ALPHA);
3773 else if (expecting == Expecting(ALPHA))
3775 if (IsArgValid(tkn, tempStr) == NO_ERROR)
3777 if (!strcmp(tempStr, "Yes"))
3778 ; /* This is the only option in version 3.2 */
3780 MrBayesPrint ("%s WARNING: Ignoring savebrlens setting; since version 3.2, branch lengths are always saved\n", spacer);
3784 MrBayesPrint ("%s Invalid argument for savebrlens\n", spacer);
3788 expecting = Expecting(PARAMETER) | Expecting(SEMICOLON);
3791 /* set Redirect (redirect) ********************************************************/
3792 else if (!strcmp(parmName, "Redirect"))
3794 if (expecting == Expecting(EQUALSIGN))
3795 expecting = Expecting(ALPHA);
3796 else if (expecting == Expecting(ALPHA))
3798 if (IsArgValid(tkn, tempStr) == NO_ERROR)
3800 if (!strcmp(tempStr, "Yes"))
3801 chainParams.redirect = YES;
3803 chainParams.redirect = NO;
3807 MrBayesPrint ("%s Invalid argument for redirecting output\n", spacer);
3811 if (chainParams.redirect == YES)
3812 MrBayesPrint ("%s Setting program to redirect output\n", spacer);
3814 MrBayesPrint ("%s Setting program not to redirect output\n", spacer);
3815 expecting = Expecting(PARAMETER) | Expecting(SEMICOLON);
3823 /* set Data (runWithData) ************************************************************/
3824 else if (!strcmp(parmName, "Data"))
3826 if (expecting == Expecting(EQUALSIGN))
3827 expecting = Expecting(ALPHA);
3828 else if (expecting == Expecting(ALPHA))
3830 if (IsArgValid(tkn, tempStr) == NO_ERROR)
3832 if (!strcmp(tempStr, "Yes"))
3833 chainParams.runWithData = YES;
3835 chainParams.runWithData = NO;
3839 MrBayesPrint ("%s Invalid argument for Data\n", spacer);
3843 if (chainParams.runWithData == NO)
3844 MrBayesPrint ("%s Running without data (WARNING: use this only for checking priors!)\n", spacer);
3846 MrBayesPrint ("%s Running with data (standard analysis)\n", spacer);
3847 expecting = Expecting(PARAMETER) | Expecting(SEMICOLON);
3855 /* set Ordertaxa (chainParams.orderTaxa) *********************************************/
3856 else if (!strcmp(parmName, "Ordertaxa"))
3858 if (expecting == Expecting(EQUALSIGN))
3859 expecting = Expecting(ALPHA);
3860 else if (expecting == Expecting(ALPHA))
3862 if (IsArgValid(tkn, tempStr) == NO_ERROR)
3864 if (!strcmp(tempStr, "Yes"))
3865 chainParams.orderTaxa = YES;
3867 chainParams.orderTaxa = NO;
3871 MrBayesPrint ("%s Invalid argument for ordertaxa\n", spacer);
3875 if (chainParams.orderTaxa == YES)
3876 MrBayesPrint ("%s Setting ordertaxa to yes\n", spacer);
3878 MrBayesPrint ("%s Setting ordertaxa to no\n", spacer);
3879 expecting = Expecting(PARAMETER) | Expecting(SEMICOLON);
3887 /* set Append (chainParams.append) *********************************************/
3888 else if (!strcmp(parmName, "Append"))
3890 if (expecting == Expecting(EQUALSIGN))
3891 expecting = Expecting(ALPHA);
3892 else if (expecting == Expecting(ALPHA))
3894 if (IsArgValid(tkn, tempStr) == NO_ERROR)
3896 if (!strcmp(tempStr, "Yes"))
3897 chainParams.append = YES;
3899 chainParams.append = NO;
3903 MrBayesPrint ("%s Invalid argument for append\n", spacer);
3907 if (chainParams.append == YES)
3908 MrBayesPrint ("%s Setting append to yes\n", spacer);
3910 MrBayesPrint ("%s Setting append to no\n", spacer);
3911 expecting = Expecting(PARAMETER) | Expecting(SEMICOLON);
3919 /* set Autotune (chainParams.autotune) *********************************************/
3920 else if (!strcmp(parmName, "Autotune"))
3922 if (expecting == Expecting(EQUALSIGN))
3923 expecting = Expecting(ALPHA);
3924 else if (expecting == Expecting(ALPHA))
3926 if (IsArgValid(tkn, tempStr) == NO_ERROR)
3928 if (!strcmp(tempStr, "Yes"))
3929 chainParams.autotune = YES;
3931 chainParams.autotune = NO;
3935 MrBayesPrint ("%s Invalid argument for Autotune\n", spacer);
3939 if (chainParams.autotune == YES)
3940 MrBayesPrint ("%s Setting Autotune to yes\n", spacer);
3942 MrBayesPrint ("%s Setting Autotune to no\n", spacer);
3943 expecting = Expecting(PARAMETER) | Expecting(SEMICOLON);
3951 /* set Tunefreq (tuneFreq) ************************************************************/
3952 else if (!strcmp(parmName, "Tunefreq"))
3954 if (expecting == Expecting(EQUALSIGN))
3955 expecting = Expecting(NUMBER);
3956 else if (expecting == Expecting(NUMBER))
3958 sscanf (tkn, "%d", &tempI);
3961 MrBayesPrint ("%s Autotuning frequency must be at least 10\n", spacer);
3965 chainParams.tuneFreq = tempI;
3966 MrBayesPrint ("%s Setting autotuning frequency to %d\n", spacer, chainParams.tuneFreq);
3967 expecting = Expecting(PARAMETER) | Expecting(SEMICOLON);
3975 /* set Swapadjacent (swapAdjacentOnly) **************************************************/
3976 else if (!strcmp(parmName, "Swapadjacent"))
3978 if (expecting == Expecting(EQUALSIGN))
3979 expecting = Expecting(ALPHA);
3980 else if (expecting == Expecting(ALPHA))
3982 if (IsArgValid(tkn, tempStr) == NO_ERROR)
3984 if (!strcmp(tempStr, "Yes"))
3985 chainParams.swapAdjacentOnly = YES;
3987 chainParams.swapAdjacentOnly = NO;
3991 MrBayesPrint ("%s Invalid argument for Swapadjacent\n", spacer);
3995 if (chainParams.swapAdjacentOnly == YES)
3996 MrBayesPrint ("%s Setting program to attempt swaps only between chains of adjacent temperatures\n", spacer);
3998 MrBayesPrint ("%s Setting program to attempt all possible swaps between chains\n", spacer);
3999 expecting = Expecting(PARAMETER) | Expecting(SEMICOLON);
4022 if (chainParams.numGen/chainParams.sampleFreq <= chainParams.burninSS)
4023 {/*Do not change print out to generations vs samples because of danger of overflow*/
4024 MrBayesPrint ("%s ERROR: Burnin %d samples is too large compared with requested total %d samples (%d generations).\n", spacer ,chainParams.burninSS, chainParams.numGen/chainParams.sampleFreq, chainParams.numGen);
4028 oldBurnin = chainParams.burninSS;;
4029 stepRelativeBurninSS = chainParams.relativeBurnin;
4031 chainParams.relativeBurnin = YES;
4033 if (chainParams.burninSS < 0)
4034 chainParams.burninSS = chainParams.numGen / ((chainParams.numStepsSS-chainParams.burninSS)*chainParams.sampleFreq);
4035 chainParams.isSS = YES;
4039 chainParams.isSS = NO;
4040 chainParams.burninSS = oldBurnin;
4041 chainParams.relativeBurnin = stepRelativeBurninSS;
4053 int ExhaustiveParsimonySearch (Tree *t, int chain, TreeInfo *tInfo)
4058 for (i=j=k=0; i<t->nNodes; i++)
4060 p = t->allDownPass[i];
4061 if (p->left == NULL || p->right == NULL)
4062 tInfo->leaf[j++] = p;
4064 tInfo->vertex[k++] = p;
4067 tInfo->leaf[0]->anc = tInfo->leaf[1]->anc = tInfo->vertex[0];
4068 tInfo->vertex[0]->left = tInfo->leaf[0];
4069 tInfo->vertex[0]->right = tInfo->leaf[1];
4070 tInfo->leaf[t->nIntNodes+1]->left = tInfo->vertex[0];
4071 tInfo->vertex[0]->anc = tInfo->leaf[t->nIntNodes+1];
4073 BuildExhaustiveSearchTree (t, chain, 2, tInfo);
4079 int ExtendChainQuery ()
4081 int extendChain, additionalCycles;
4084 # if defined (MPI_ENABLED)
4087 MrBayesPrint ("\n");
4088 extendChain = WantTo ("Continue with analysis");
4090 MPI_Bcast (&extendChain, 1, MPI_INT, 0, MPI_COMM_WORLD);
4091 if (extendChain == YES)
4095 additionalCycles = 0;
4098 if (additionalCycles < 0)
4099 MrBayesPrint ("%s Number must be greater than or equal to 0: ", spacer);
4101 MrBayesPrint ("%s Additional number of generations: ", spacer);
4103 if (fgets (s, 100, stdin) == NULL)
4105 printf ("Error in function: %s at line: %d in file: %s", __FUNCTION__, __LINE__, __FILE__);
4107 sscanf (s, "%d", &additionalCycles);
4109 } while (additionalCycles < 0);
4110 MrBayesPrint ("\n");
4112 MPI_Bcast (&additionalCycles, 1, MPI_INT, 0, MPI_COMM_WORLD);
4114 return (additionalCycles);
4119 MrBayesPrint ("\n");
4120 extendChain = WantTo ("Continue with analysis");
4122 if (extendChain == YES)
4124 additionalCycles = 0;
4127 if (additionalCycles < 0)
4128 MrBayesPrint ("%s Number must be greater than or equal to 0: ", spacer);
4130 MrBayesPrint ("%s Additional number of generations: ", spacer);
4132 if (fgets (s, 20, stdin) == NULL)
4134 printf ("Error in function: %s at line: %d in file: %s", __FUNCTION__, __LINE__, __FILE__);
4136 sscanf (s, "%d", &additionalCycles);
4138 } while (additionalCycles < 0);
4139 MrBayesPrint ("\n");
4140 return (additionalCycles);
4149 int FillNumSitesOfPat (void)
4151 int i, j, n, *increased, *decreased, nToDecrease, nToIncrease, whichToChange;
4155 wtIncrement = (CLFlt) chainParams.weightScheme[2];
4156 increased = decreased = NULL;
4158 /* reallocate numSitesOfPat */
4159 if (memAllocs[ALLOC_NUMSITESOFPAT] == NO)
4161 MrBayesPrint ("%s numSitesOfPat is not allocated\n", spacer);
4164 memAllocs[ALLOC_NUMSITESOFPAT] = NO;
4165 numSitesOfPat = (CLFlt *) SafeRealloc((void *) numSitesOfPat, numCompressedChars * chainParams.numChains * sizeof(MrBFlt));
4168 MrBayesPrint ("%s Problem reallocating numSitesOfPat (%d)\n", spacer, numCompressedChars * chainParams.numChains * sizeof(MrBFlt));
4171 memAllocs[ALLOC_NUMSITESOFPAT] = YES;
4173 /* copy first numCompressedChars into the remaining bits */
4174 if (chainParams.numChains > 1)
4176 for (i=0; i<numCompressedChars; i++)
4178 for (j=1; j<chainParams.numChains; j++)
4180 numSitesOfPat[j * numCompressedChars + i] = numSitesOfPat[i];
4185 /* reweight characters for each chain */
4186 if (chainParams.numChains > 1)
4188 if (chainParams.weightScheme[0] + chainParams.weightScheme[1] > 0.0001)
4189 MrBayesPrint ("%s Reweighting of characters for chains 1 to %d\n", spacer, chainParams.numChains);
4191 /* check that we don't have an HMM */
4192 if (chainHasAdgamma == YES && chainParams.weightScheme[0] + chainParams.weightScheme[1] > 0.0001)
4194 MrBayesPrint ("%s Reweighting of characters is not allowed with an autocorrelated gamma model\n", spacer);
4198 /* how many characters */
4200 for (i=0; i<numCompressedChars; i++)
4201 n += (int)numSitesOfPat[0 * numCompressedChars + i];
4202 nToDecrease = (int)(n * chainParams.weightScheme[0] / 100.0);
4203 nToIncrease = (int)(n * chainParams.weightScheme[1] / 100.0);
4204 if (chainParams.weightScheme[0] + chainParams.weightScheme[1] > 0.0001)
4206 MrBayesPrint ("%s Decreasing weight of %d characters\n", spacer, nToDecrease);
4207 MrBayesPrint ("%s Increasing weight of %d characters\n", spacer, nToIncrease);
4210 /* allocate memory */
4211 increased = (int *)SafeMalloc(2 * (size_t)numCompressedChars * sizeof(int));
4214 MrBayesPrint ("%s Problem reallocating increased (%d)\n", spacer, numCompressedChars * chainParams.numChains * sizeof(int));
4217 decreased = increased + numCompressedChars;
4219 /* reweight characters for each chain */
4220 for (j=1; j<chainParams.numChains; j++)
4222 for (i=0; i<numCompressedChars; i++)
4223 increased[i] = decreased[i] = 0;
4225 /* decrease weight of characters */
4226 for (i=0; i<nToDecrease; i++)
4230 ran = RandomNumber(&swapSeed);
4232 for (whichToChange=0; whichToChange<numCompressedChars; whichToChange++)
4234 sum += numSitesOfPat[0 * numCompressedChars + whichToChange] / n;
4238 if (whichToChange < 0 || whichToChange >= numCompressedChars)
4240 } while (decreased[whichToChange] >= numSitesOfPat[0 * numCompressedChars + whichToChange]);
4241 decreased[whichToChange]++;
4242 numSitesOfPat[j * numCompressedChars + whichToChange] -= wtIncrement;
4243 if (numSitesOfPat[j * numCompressedChars + whichToChange] < 0)
4245 MrBayesPrint ("%s Problem reweighting characters\n", spacer);
4250 /* increase weight of characters */
4251 for (i=0; i<nToDecrease; i++)
4255 ran = RandomNumber(&swapSeed);
4257 for (whichToChange=0; whichToChange<numCompressedChars; whichToChange++)
4259 sum += numSitesOfPat[0 * numCompressedChars + whichToChange] / n;
4263 if (whichToChange < 0 || whichToChange >= numCompressedChars)
4265 } while ((increased[whichToChange] + decreased[whichToChange]) >= numSitesOfPat[0 * numCompressedChars + whichToChange]);
4266 increased[whichToChange]++;
4267 numSitesOfPat[j * numCompressedChars + whichToChange] += wtIncrement;
4268 if (numSitesOfPat[j * numCompressedChars + whichToChange] < 0)
4270 MrBayesPrint ("%s Problem reweighting characters\n", spacer);
4277 /* free allocated memory */
4282 /* print site patterns for each chain */
4283 for (i=0; i<numCompressedChars; i++)
4285 MrBayesPrint ("%4d -- ", i);
4286 for (j=0; j<chainParams.numChains; j++)
4288 MrBayesPrint ("%4.1lf ", numSitesOfPat[j * numCompressedChars + i]);
4290 MrBayesPrint ("\n");
4303 /* FindBestNode: Recursive function for finding best attachment point */
4304 TreeNode *FindBestNode (Tree *t, TreeNode *p, TreeNode *addNode, CLFlt *minLength, int chain) {
4307 TreeNode *q=NULL, *r=NULL;
4308 BitsLong *pA, *pP, *pX;
4309 CLFlt *nSitesOfPat, fpLength, length;
4312 /* Calculate length, looping over divisions */
4314 for (n=0; n<t->nRelParts; n++)
4316 division = t->relParts[n];
4318 /* Find model settings */
4319 m = &modelSettings[division];
4321 /* Find number of site patterns */
4322 nSitesOfPat = numSitesOfPat + ((1 % chainParams.numChains) * numCompressedChars) + m->compCharStart;
4324 /* Find final-pass parsimony sets for the node and its ancestor */
4325 pP = m->parsSets[p->index ];
4326 pA = m->parsSets[p->anc->index ];
4327 pX = m->parsSets[addNode->index];
4329 for (c=0; c<m->numChars; c++)
4331 if (((pP[c] | pA[c])&pX[c]) == 0)
4332 fpLength += nSitesOfPat[c];
4336 /* If tip, this is the best node and its length is the min length */
4337 if (p->left == NULL)
4339 *minLength = fpLength;
4343 /* Find best node and min length above this node */
4344 if (p->left != NULL) {
4345 q = FindBestNode(t, p->left, addNode, minLength, chain);
4346 r = FindBestNode(t, p->right, addNode, &length, chain);
4347 if (length < *minLength) {
4348 *minLength = length;
4353 /* Return best node and min length */
4354 if (*minLength < fpLength)
4356 else /* This node is the best */
4358 *minLength = fpLength;
4364 /* FlipCijkSpace: Flip space for cijks with scratch area */
4365 void FlipCijkSpace (ModelInfo* m, int chain)
4369 temp = m->cijkIndex[chain];
4370 m->cijkIndex[chain] = m->cijkScratchIndex;
4371 m->cijkScratchIndex = temp;
4375 /* FlipCondLikeSpace: Flip space for conditional likelihoods with scratch area */
4376 void FlipCondLikeSpace (ModelInfo* m, int chain, int nodeIndex)
4380 temp = m->condLikeIndex[chain][nodeIndex];
4381 m->condLikeIndex[chain][nodeIndex] = m->condLikeScratchIndex[nodeIndex];
4382 m->condLikeScratchIndex[nodeIndex] = temp;
4386 /* FlipNodeScalerSpace: Flip space for node scalers and scaler flag with scratch area */
4387 void FlipNodeScalerSpace (ModelInfo* m, int chain, int nodeIndex)
4391 temp = m->nodeScalerIndex[chain][nodeIndex];
4392 m->nodeScalerIndex[chain][nodeIndex] = m->nodeScalerScratchIndex[nodeIndex];
4393 m->nodeScalerScratchIndex[nodeIndex] = temp;
4395 temp = m->scalersSet[chain][nodeIndex];
4396 m->scalersSet[chain][nodeIndex] = m->scalersSetScratch[nodeIndex];
4397 m->scalersSetScratch[nodeIndex] = temp;
4401 /* FlipSiteScalerSpace: Flip space for ln site scalers */
4402 void FlipSiteScalerSpace (ModelInfo *m, int chain)
4406 # if defined (BEAGLE_ENABLED)
4410 temp = m->siteScalerIndex[chain];
4411 m->siteScalerIndex[chain] = m->siteScalerScratchIndex;
4412 m->siteScalerScratchIndex = temp;
4414 # if defined (BEAGLE_ENABLED)
4415 if (m->useBeagle == YES)
4417 tempp = m->isScalerNode[chain];
4418 m->isScalerNode[chain] = m->isScalerNodeScratch ;
4419 m->isScalerNodeScratch = tempp;
4425 /* FlipTiProbsSpace: Flip space for ti probs with scratch area */
4426 void FlipTiProbsSpace (ModelInfo* m, int chain, int nodeIndex)
4430 temp = m->tiProbsIndex[chain][nodeIndex];
4431 m->tiProbsIndex[chain][nodeIndex] = m->tiProbsScratchIndex[nodeIndex];
4432 m->tiProbsScratchIndex[nodeIndex] = temp;
4436 void FreeChainMemory (void)
4438 int i, j, k, nRateCats;
4441 /* free model variables for Gibbs gamma */
4442 for (i=0; i<numCurrentDivisions; i++)
4444 if (modelSettings[i].gibbsGamma == YES)
4446 if (modelSettings[i].pInvar != NULL)
4447 nRateCats = modelSettings[i].numGammaCats + 1;
4449 nRateCats = modelSettings[i].numGammaCats;
4450 for (j=0; j<numLocalChains; j++)
4452 for (k=0; k<nRateCats; k++)
4454 free(modelSettings[i].catLnScaler[j][k]);
4455 free(modelSettings[i].catLike[j][k]);
4457 free (modelSettings[i].catLnScaler[j]);
4458 free (modelSettings[i].catLike[j]);
4460 free (modelSettings[i].tiIndex);
4461 free (modelSettings[i].catLike);
4462 free (modelSettings[i].catLnScaler);
4466 /* free parsimony sets and node lens */
4467 for (i=0; i<numCurrentDivisions; i++)
4469 m = &modelSettings[i];
4472 for (j=0; j<m->numParsSets; j++)
4473 free (m->parsSets[j]);
4477 if (m->parsNodeLens)
4479 free(m->parsNodeLens);
4480 m->parsNodeLens = NULL;
4484 /* free model variables for conditional likelihoods */
4485 for (i=0; i<numCurrentDivisions; i++)
4487 m = &modelSettings[i];
4490 for (j=0; j<m->numCondLikes; j++)
4492 # if defined (SSE_ENABLED)
4493 if (m->useSSE == YES)
4494 AlignedSafeFree ((void **)(&m->condLikes[j]));
4496 free (m->condLikes[j]);
4498 free (m->condLikes[j]);
4501 free (m->condLikes);
4502 m->condLikes = NULL;
4507 for (j=0; j<m->numScalers; j++)
4508 # if defined (SSE_ENABLED)
4509 if (m->useSSE == YES)
4510 AlignedSafeFree ((void **)(&m->scalers[j]));
4512 free (m->scalers[j]);
4514 free (m->scalers[j]);
4526 # if defined (SSE_ENABLED)
4527 if (m->useSSE == YES)
4535 AlignedSafeFree ((void **)(&m->lnL_SSE));
4537 AlignedSafeFree ((void **)(&m->lnLI_SSE));
4543 for (j=0; j<m->numTiProbs; j++)
4544 free (m->tiProbs[j]);
4551 for (j=0; j<numLocalChains+1; j++)
4557 if (m->condLikeIndex)
4559 for (j=0; j<numLocalChains; j++)
4560 free (m->condLikeIndex[j]);
4561 free (m->condLikeIndex);
4562 m->condLikeIndex = NULL;
4565 if (m->condLikeScratchIndex)
4567 free (m->condLikeScratchIndex);
4568 m->condLikeScratchIndex=NULL;
4571 if (m->tiProbsIndex)
4573 for (j=0; j<numLocalChains; j++)
4574 free (m->tiProbsIndex[j]);
4575 free (m->tiProbsIndex);
4576 m->tiProbsIndex = NULL;
4578 if (m->tiProbsScratchIndex)
4580 free (m->tiProbsScratchIndex);
4581 m->tiProbsScratchIndex = NULL;
4583 if (m->nodeScalerIndex)
4585 for (j=0; j<numLocalChains; j++)
4586 free (m->nodeScalerIndex[j]);
4587 free (m->nodeScalerIndex);
4588 m->nodeScalerIndex = NULL;
4590 if (m->nodeScalerScratchIndex)
4592 free (m->nodeScalerScratchIndex);
4593 m->nodeScalerScratchIndex = NULL;
4597 for (j=0; j<numLocalChains; j++)
4598 free (m->scalersSet[j]);
4599 free (m->scalersSet);
4600 m->scalersSet = NULL;
4602 if (m->scalersSetScratch)
4604 free (m->scalersSetScratch);
4605 m->scalersSetScratch = NULL;
4607 if (m->siteScalerIndex)
4609 free (m->siteScalerIndex);
4610 m->siteScalerIndex = NULL;
4614 free (m->cijkIndex);
4615 m->cijkIndex = NULL;
4617 if (m->ancStateCondLikes)
4619 free (m->ancStateCondLikes);
4620 m->ancStateCondLikes = NULL;
4623 # if defined (BEAGLE_ENABLED)
4624 if (m->useBeagle == NO)
4627 beagleFinalizeInstance(m->beagleInstance);
4628 SafeFree((void **)(&m->logLikelihoods));
4629 SafeFree((void **)(&m->inRates));
4630 SafeFree((void **)(&m->branchLengths));
4631 SafeFree((void **)(&m->tiProbIndices));
4632 SafeFree((void **)(&m->inWeights));
4633 SafeFree((void **)(&m->bufferIndices));
4634 SafeFree((void **)(&m->eigenIndices));
4635 SafeFree((void **)(&m->childBufferIndices));
4636 SafeFree((void **)(&m->childTiProbIndices));
4637 SafeFree((void **)(&m->cumulativeScaleIndices));
4639 m->isScalerNodeScratch += numLocalTaxa;
4640 SafeFree((void **)&(m->isScalerNodeScratch));
4641 for (j=0; j<numLocalChains; j++)
4643 m->isScalerNode[j] += numLocalTaxa;
4644 SafeFree((void **)&(m->isScalerNode[j]));
4646 SafeFree((void **)(&m->isScalerNode));
4648 SafeFree((void **)(&m->beagleComputeCount));
4649 SafeFree((void **)(&m->succesCount));
4650 SafeFree((void **)(&m->rescaleFreq));
4655 if (memAllocs[ALLOC_CURLNL] == YES) /*alloc in RunChain()*/
4659 memAllocs[ALLOC_CURLNL] = NO;
4661 if (memAllocs[ALLOC_SS] == YES) /*alloc in mcmc()*/
4663 free (marginalLnLSS);
4664 free (stepScalerSS);
4665 free (stepAcumulatorSS);
4667 memAllocs[ALLOC_SS] = NO;
4669 if (memAllocs[ALLOC_CURLNPR] == YES) /*alloc in RunChain()*/
4672 memAllocs[ALLOC_CURLNPR] = NO;
4674 if (memAllocs[ALLOC_CHAINID] == YES) /*alloc in RunChain()*/
4677 memAllocs[ALLOC_CHAINID] = NO;
4679 if (memAllocs[ALLOC_USEDMOVES] == YES) /*alloc in setUsedMoves()*/
4682 memAllocs[ALLOC_USEDMOVES] = NO;
4684 if (memAllocs[ALLOC_TERMSTATE] == YES) /*alloc in SetUpTermState()*/
4688 memAllocs[ALLOC_TERMSTATE] = NO;
4690 if (memAllocs[ALLOC_ISPARTAMBIG] == YES) /*alloc in SetUpTermState()*/
4694 memAllocs[ALLOC_ISPARTAMBIG] = NO;
4696 if (memAllocs[ALLOC_PRELIKES] == YES) /*alloc in InitCondLike()*/
4700 memAllocs[ALLOC_PRELIKES] = NO;
4702 if (memAllocs[ALLOC_RATEPROBS] == YES) /*alloc in InitAdGamma() */
4704 free (rateProbSpace);
4707 memAllocs[ALLOC_RATEPROBS] = NO;
4709 if (memAllocs[ALLOC_SITEJUMP] == YES) /*alloc in InitAdGamma() */
4713 memAllocs[ALLOC_SITEJUMP] = NO;
4715 if (memAllocs[ALLOC_MARKOVTIS] == YES) /*alloc in InitAdGamma() */
4717 for (i=0; i<MAX_SMALL_JUMP; i++)
4718 if (markovTi[i] != NULL)
4719 FreeSquareDoubleMatrix(markovTi[i]);
4720 FreeSquareDoubleMatrix(markovTiN);
4721 memAllocs[ALLOC_MARKOVTIS] = NO;
4723 if (memAllocs[ALLOC_SWAPINFO] == YES) /*alloc in RunChain()*/
4725 for (i=0; i<chainParams.numRuns; i++)
4726 FreeSquareIntegerMatrix(swapInfo[i]);
4728 memAllocs[ALLOC_SWAPINFO] = NO;
4730 if (memAllocs[ALLOC_POSSELPROBS] == YES) /*alloc in PrintStates() <- RunChain()*/
4733 memAllocs[ALLOC_POSSELPROBS] = NO;
4735 if (memAllocs[ALLOC_PFCOUNTERS] == YES) /*alloc in SetUpParitionCounters() <- RunChain()*/
4737 free (partition[0]);
4739 for (i=0; i<numTopologies; i++)
4740 Tfree (partFreqTreeRoot[i]);
4741 free (partFreqTreeRoot);
4742 memAllocs[ALLOC_PFCOUNTERS] = NO;
4744 if (memAllocs[ALLOC_FILEPOINTERS] == YES) /* alloc in (PreparePrintFiles(), ReusePreviousResults()) <- RunChain() */
4746 CloseMBPrintFiles ();
4758 memAllocs[ALLOC_FILEPOINTERS] = NO;
4760 if (memAllocs[ALLOC_STATS] == YES) /* alloc in RunChain() */
4762 if (chainParams.allComps == YES)
4764 for (i=0; i<numTopologies; i++)
4765 FreeSquareDoubleMatrix (chainParams.stat[i].pair);
4767 free (chainParams.stat);
4768 memAllocs[ALLOC_STATS] = NO;
4770 if (memAllocs[ALLOC_DIAGNTREE] == YES)
4772 FreeTree (chainParams.dtree);
4773 memAllocs[ALLOC_DIAGNTREE] = NO;
4775 if (memAllocs[ALLOC_PRINTPARAM] == YES)
4778 free (topologyPrintIndex);
4779 memAllocs[ALLOC_PRINTPARAM] = NO;
4781 if (memAllocs[ALLOC_TFILEPOS] == YES)
4783 free (chainParams.tFilePos);
4784 chainParams.tFilePos = NULL;
4785 memAllocs[ALLOC_TFILEPOS] = NO;
4787 if (memAllocs[ALLOC_TREELIST] == YES)
4789 for (i=0; i<chainParams.numRuns * numTopologies; i++)
4790 EraseTreeList (&chainParams.treeList[i]);
4791 free (chainParams.treeList);
4792 chainParams.treeList = NULL;
4793 memAllocs[ALLOC_TREELIST] = NO;
4795 if (memAllocs[ALLOC_BEST] == YES)
4797 FreeBestChainVariables();
4798 memAllocs[ALLOC_BEST] = NO;
4803 MrBFlt GetFitchPartials (ModelInfo *m, int chain, int source1, int source2, int destination)
4806 BitsLong x[2], *pS1, *pS2, *pD;
4807 MrBFlt length = 0.0;
4810 assert (m->nParsIntsPerSite <= 2 && m->nParsIntsPerSite > 0);
4811 assert (source1 >= 0 && source1 < m->numParsSets);
4812 assert (source2 >= 0 && source2 < m->numParsSets);
4813 assert (destination >= 0 && destination < m->numParsSets);
4815 /* find parsimony sets for the nodes */
4816 pS1 = m->parsSets[source1 ];
4817 pS2 = m->parsSets[source2 ];
4818 pD = m->parsSets[destination];
4820 /* Find number of site patterns */
4821 nSitesOfPat = numSitesOfPat + ((1 % chainParams.numChains) * numCompressedChars) + m->compCharStart;//chainId[chain]
4823 if (m->nParsIntsPerSite == 1)
4825 for (c=0; c<m->numChars; c++)
4827 x[0] = pS1[c] & pS2[c];
4830 length += nSitesOfPat[c];
4831 x[0] = pS1[c] | pS2[c];
4836 else /* if (m->nParsIntsPerSite == 2) */
4838 assert (m->nParsIntsPerSite == 2);
4839 for (c=i=0; c<m->numChars; c++)
4841 x[0] = pS1[i] & pS2[i];
4842 x[1] = pS1[i+1] & pS2[i+1];
4843 if ((x[0] | x[1]) == 0)
4845 length += nSitesOfPat[c];
4846 x[0] = pS1[i] | pS2[i];
4847 x[1] = pS1[i+1] | pS2[i+1];
4855 MrBayesPrint ("%d", chain); /* just because I am tired of seeing the unused parameter error msg */
4859 MrBFlt GetParsDP (Tree *t, TreeNode *p, int chain)
4866 if (p->left != NULL)
4868 length += GetParsDP (t, p->left, chain);
4869 length += GetParsDP (t, p->right, chain);
4871 for (n=0; n<t->nRelParts; n++)
4873 division = t->relParts[n];
4875 /* Find model settings */
4876 m = &modelSettings[division];
4878 /* Get Fitch partials and length */
4879 length += GetFitchPartials(m,
4891 void GetParsFP (Tree *t, TreeNode *p, int chain)
4893 int i, c, n, division;
4894 BitsLong *pL, *pR, *pP, *pA, x[2];
4897 if (p->left != NULL)
4899 for (n=0; n<t->nRelParts; n++)
4901 division = t->relParts[n];
4903 /* Find model settings */
4904 m = &modelSettings[division];
4905 assert (m->nParsIntsPerSite == 1 || m->nParsIntsPerSite == 2);
4907 /* find parsimony sets for the node and its environment */
4908 pL = m->parsSets[p->left->index ];
4909 pR = m->parsSets[p->right->index];
4910 pP = m->parsSets[p->index ];
4911 pA = m->parsSets[p->anc->index ];
4913 if (m->nParsIntsPerSite == 1)
4915 for (c=0; c<m->numChars; c++)
4917 x[0] = pP[c] & pA[c];
4920 { /* means that we allow change of state from p to a */
4921 if ((pL[c] & pR[c]) != 0)
4922 x[0] = ((pL[c] | pR[c]) & pA[c]) | pP[c] ;
4923 /* We still allow only one change from both children of p through p to a.
4924 So state from a that belong to one of the children of p can be added to pP[c],
4925 if p assume the state then the only change would be on the other child. */
4927 x[0] = pP[c] | pA[c];
4928 /* Here we allow two change from both children of p through p to a.
4929 Adding pA[c] to pP[c] means that if p assume state exclusive in a then even if
4930 both children will be in different state from p we still get optimal parsimony */
4935 else /* if (m->nParsIntsPerSite == 2) */
4937 for (c=i=0; c<m->numChars; c++)
4939 x[0] = pP[i] & pA[i];
4940 x[1] = pP[i+1] & pA[i+1];
4941 if (x[0] != pA[i] || x[1] != pA[i+1])
4943 x[0] = pL[i] & pR[i];
4944 x[1] = pL[i+1] & pR[i+1];
4945 if ((x[0] | x[1]) != 0)
4947 x[0] = ((pL[i] | pR[i]) & pA[i]) | pP[i] ;
4948 x[1] = ((pL[i+1] | pR[i+1]) & pA[i+1]) | pP[i+1] ;
4952 x[0] = pP[i] | pA[i];
4953 x[1] = pP[i+1] | pA[i+1];
4961 GetParsFP (t, p->left, chain);
4962 GetParsFP (t, p->right, chain);
4967 int GetParsimonyBrlens (Tree *t, int chain, MrBFlt *brlens)
4969 int c, i, j, n, division;
4975 /* Reset all brlens */
4976 for (i=0; i<t->nNodes-1; i++)
4979 /* Get final parsimony state sets */
4980 GetParsDP(t, t->root->left, chain);
4981 GetParsFP(t, t->root, chain);
4983 /* Get all branch lengths, looping over divisions */
4984 for (n=0; n<t->nRelParts; n++)
4986 division = t->relParts[n];
4988 /* Find model settings */
4989 m = &modelSettings[division];
4991 /* Find number of site patterns */
4992 nSitesOfPat = numSitesOfPat + ((chainId[chain] % chainParams.numChains) * numCompressedChars) + m->compCharStart;
4994 /* Record branch lengths in downpass */
4995 for (i=0; i<t->nNodes-1; i++)
4997 p = t->allDownPass[i];
4999 /* Find final-pass parsimony sets for the node and its ancestor */
5000 pP = m->parsSets[p->index ];
5001 pA = m->parsSets[p->anc->index];
5003 if (m->nParsIntsPerSite == 1)
5005 for (c=0; c<m->numChars; c++)
5007 if ((pP[c] & pA[c]) == 0)
5008 brlens[i] += nSitesOfPat[c];
5013 for (c=j=0; c<m->numChars; c++, j+=2)
5015 if ((pP[j] & pA[j]) == 0 && (pP[j+1] & pA[j+1]) == 0)
5016 brlens[i] += nSitesOfPat[c];
5026 MrBFlt GetParsimonyLength (Tree *t, int chain)
5028 int c, i, n, division;
5035 /* Get length down to internal root */
5036 length = GetParsDP(t, t->root->left, chain);
5038 /* return if rooted */
5039 if (t->isRooted == NO)
5042 /* add in the last terminal if not rooted */
5043 for (n=0; n<t->nRelParts; n++)
5045 division = t->relParts[n];
5047 /* Find model settings */
5048 m = &modelSettings[division];
5050 /* Find number of site patterns */
5051 nSitesOfPat = numSitesOfPat + ((chainId[chain] % chainParams.numChains) * numCompressedChars) + m->compCharStart;
5053 /* Deal with last branch */
5054 p = t->intDownPass[t->nIntNodes-1];
5056 /* find downpass parsimony sets for the node and its environment */
5057 pP = m->parsSets[p->index ];
5058 pA = m->parsSets[p->anc->index];
5060 if (m->nParsIntsPerSite == 1)
5062 for (c=0; c<m->numChars; c++)
5064 if ((pP[c] & pA[c]) == 0)
5066 length += nSitesOfPat[c];
5070 else /* if (m->nParsIntsPerSite == 2) */
5072 for (c=i=0; c<m->numChars; c++, i+=2)
5074 if ((pP[i] & pA[i]) == 0 && (pP[i+1] & pA[i+1]) == 0)
5076 length += nSitesOfPat[c];
5086 void GetParsimonySubtreeRootstate (Tree *t, TreeNode *root, int chain)
5088 int c, i, n, division;
5089 BitsLong *pD, *pP, *pA, x[2];
5093 /* Loop over divisions */
5094 for (n=0; n<t->nRelParts; n++)
5096 division = t->relParts[n];
5098 /* Find model settings */
5099 m = &modelSettings[division];
5100 assert (m->nParsIntsPerSite == 1 || m->nParsIntsPerSite == 2);
5102 for (i=0; i<t->nNodes; i++)
5104 p = t->allDownPass[i];
5109 while (p->anc != NULL)
5115 /* Make uppass node by node */
5116 for (i=t->nIntNodes-1; i>=0; i--)
5118 p = t->intDownPass[i];
5120 /* continue if no work needs to be done */
5121 if (p->marked == NO)
5124 /* find downpass and uppass parsimony sets for the node and its environment */
5125 pP = m->parsSets[p->index ];
5126 if (p->left->marked == YES)
5127 pD = m->parsSets[p->right->index];
5129 pD = m->parsSets[p->left->index ];
5130 pA = m->parsSets[p->anc->index ];
5132 if (m->nParsIntsPerSite == 1)
5134 for (c=0; c<m->numChars; c++)
5136 x[0] = pD[c] & pA[c];
5139 x[0] = (pD[c] | pA[c]);
5144 else if (m->nParsIntsPerSite == 2)
5146 for (c=i=0; c<m->numChars; c++, i+=2)
5148 x[0] = pD[i ] & pA[i ];
5149 x[1] = pD[i+1] & pA[i+1];
5150 if (x[0] + x[1] == 0)
5152 x[0] = (pD[i ] | pA[i ]);
5153 x[1] = (pD[i+1] | pA[i+1]);
5165 MrBayesPrint ("%d", chain); /* just because I am tired of seeing the unused parameter error msg */
5169 /* GetRate: retrieve the base rate for the division and chain in current state */
5170 MrBFlt GetRate (int division, int chain)
5173 MrBFlt *values, rate;
5178 p = modelSettings[division].rateMult;
5179 values = GetParamVals (p, chain, state[chain]);
5180 if (p->nValues == 1)
5184 for (i=0; i<p->nRelParts; i++)
5186 if (p->relParts[i] == division)
5194 p = modelSettings[division].geneTreeRateMult;
5197 values = GetParamVals (p, chain, state[chain]);
5198 for (i=0; i<p->nRelParts; i++)
5200 if (p->relParts[i] == division)
5212 void GetStamp (void)
5216 for (i=0; i<10; i++)
5217 stamp[i] = '0' + (int)(RandomNumber(&runIDSeed) * 10);
5220 MrBayesPrint ("%s MCMC stamp = %s\n", spacer, stamp);
5224 void GetSwappers (int *swapA, int *swapB, int run)
5228 /* this works for both the serial and parallel versions because the swapSeed is identical for all
5229 processors, ensuring they all get the same sequence of chainIds to swap */
5230 # if defined (MPI_ENABLED)
5232 /* For now, we wonly allow random swaps in the MPI version. Other schemes require
5233 tagging of messages, or a dedicated server node doing message processing. */
5234 (*swapA) = (int) (RandomNumber(&swapSeed) * chainParams.numChains);
5235 (*swapB) = (int) (RandomNumber(&swapSeed) * (chainParams.numChains - 1));
5236 if ((*swapB) == (*swapA))
5237 (*swapB) = chainParams.numChains - 1;
5241 if (chainParams.swapAdjacentOnly == NO)
5243 (*swapA) = (int) (RandomNumber(&swapSeed) * chainParams.numChains);
5244 (*swapB) = (int) (RandomNumber(&swapSeed) * (chainParams.numChains - 1));
5245 if ((*swapB) == (*swapA))
5246 (*swapB) = chainParams.numChains - 1;
5250 (*swapA) = (int) (RandomNumber(&swapSeed) * (chainParams.numChains - 1));
5251 (*swapB) = (*swapA) + 1;
5255 i = run * chainParams.numChains;
5263 void GetTempDownPassSeq (TreeNode *p, int *i, TreeNode **dp)
5267 GetTempDownPassSeq (p->left, i, dp);
5268 GetTempDownPassSeq (p->right, i, dp);
5274 MrBFlt GibbsSampleGamma (int chain, int division, RandLong *seed)
5276 int c, i, k, *rateCat, nStates, nRateCats, nGammaCats, id;
5277 CLFlt **catLike, **catLnScaler, *lnScaler, maxLnScaler,
5278 *clRoot, f, bs[64], *clInvar, pInvar, freq;
5279 MrBFlt ran, lnL, *bsVals, deltaLnL, temp;
5284 m = &modelSettings[division];
5286 /* find base frequencies */
5287 bsVals = GetParamSubVals (m->stateFreq, chain, state[chain]);
5288 nStates = m->numModelStates;
5289 for (i=0; i<nStates; i++)
5290 bs[i] = (CLFlt) bsVals[i];
5292 /* find tree scaler */
5293 lnScaler = m->scalers[m->siteScalerIndex[chain]];
5295 /* find category like array and associated sccaler */
5296 catLike = m->catLike[chain];
5297 catLnScaler = m->catLnScaler[chain];
5299 /* find rate category index */
5300 rateCat = m->tiIndex + chain*m->numChars;
5302 /* find number of rate cats and gamma cats */
5303 nRateCats = nGammaCats = m->numGammaCats;
5304 if (m->pInvar != NULL)
5308 t = GetTree (m->brlens, chain, state[chain]);
5310 /* find invar cond likes (if we have invariable rate category) */
5311 clInvar = m->invCondLikes;
5314 if (m->pInvar == NULL)
5317 pInvar = (CLFlt) *GetParamVals (m->pInvar, chain, state[chain]);
5318 freq = ((CLFlt)1.0 - pInvar) / nGammaCats;
5320 /* get chain temperature */
5321 temp = Temperature (chainId[chain]);
5322 id = chainId[chain] % chainParams.numChains;
5324 /* calculate rate probs */
5325 for (k=0; k<nGammaCats; k++)
5327 FlipSiteScalerSpace(m, chain);
5328 ResetSiteScalers(m, chain);
5329 for (c=0; c<m->numChars; c++)
5331 for (i=0; i<t->nIntNodes; i++)
5333 p = t->intDownPass[i];
5334 if (t->isRooted == NO && p->anc->anc == NULL)
5335 m->CondLikeRoot (p, division, chain);
5337 m->CondLikeDown (p, division, chain);
5338 if (p->scalerNode == YES)
5339 m->CondLikeScaler (p, division, chain);
5341 /* find root conditional likes */
5343 clRoot = m->condLikes[m->condLikeIndex[chain][p->index]];
5344 for (c=0; c<m->numChars; c++)
5346 catLike[k][c] = 0.0;
5347 for (i=0; i<nStates; i++)
5348 catLike[k][c] += bs[i]*clRoot[i];
5349 catLike[k][c] *= freq;
5350 catLnScaler[k][c] = lnScaler[c];
5353 FlipSiteScalerSpace(m, chain);
5356 /* fill in the invar cond likes if needed */
5357 if (m->pInvar != NULL)
5360 for (c=0; c<m->numChars; c++)
5362 catLike[k][c] = 0.0;
5363 for (i=0; i<nStates; i++)
5364 catLike[k][c] += bs[i]*clInvar[i];
5365 catLike[k][c] *= pInvar;
5367 catLnScaler[k][c] = 0.0;
5371 /* Now Gibbs sample the rate categories */
5372 for (c=0; c<m->numChars; c++)
5374 /* find max scaler */
5375 maxLnScaler = catLnScaler[0][c];
5376 for (k=1; k<nRateCats; k++)
5378 if (catLnScaler[k][c] > maxLnScaler && catLike[k][c] > 0.0)
5379 maxLnScaler = catLnScaler[k][c];
5382 for (k=0; k<nRateCats; k++)
5384 f = catLnScaler[k][c] - maxLnScaler;
5386 catLike[k][c] = 0.0;
5389 catLike[k][c] *= (CLFlt) exp (f);
5390 /* take the temperature into account */
5392 catLike[k][c] = (CLFlt) pow(catLike[k][c], temp);
5395 /* get cumulative sum */
5396 for (k=1; k<nRateCats; k++)
5397 catLike[k][c] += catLike[k-1][c];
5398 /* randomly sample a category; multiply by total to avoid scaling probs */
5399 ran = RandomNumber(seed) * catLike[nRateCats-1][c];
5400 for (k=0; k<nRateCats; k++)
5402 if (ran < catLike[k][c])
5408 /* recalculate everything */
5409 FlipSiteScalerSpace(m, chain);
5410 ResetSiteScalers(m, chain);
5411 for (i=0; i<t->nIntNodes; i++)
5413 p = t->intDownPass[i];
5414 if (t->isRooted == NO && p->anc->anc == NULL)
5415 m->CondLikeRoot (p, division, chain);
5417 m->CondLikeDown (p, division, chain);
5418 if (p->scalerNode == YES)
5419 m->CondLikeScaler (p, division, chain);
5422 m->Likelihood (t->root->left, division, chain, &lnL, (chainId[chain] % chainParams.numChains));
5424 deltaLnL = lnL - m->lnLike[2*chain + state[chain]];
5425 m->lnLike[2*chain + state[chain]] = lnL;
5431 /*------------------------------------------------------------------------
5433 | InitAdGamma: initialize variables for adgamma model.
5435 -------------------------------------------------------------------------*/
5436 int InitAdGamma (void)
5438 int d, c, i, j, k, maxRates, *corrModel;
5441 /* take care of adgamma model */
5442 if (chainHasAdgamma == NO)
5445 MrBayesPrint ("%s Initializing autocorrelated discrete gamma model\n", spacer);
5447 /* allocate corr space */
5448 corrModel = (int *) SafeCalloc (numCurrentDivisions, sizeof(int));
5452 /* allocate siteJump */
5453 if (memAllocs[ALLOC_SITEJUMP] == YES)
5455 MrBayesPrint ("%s siteJump not free in InitAdGamma\n", spacer);
5459 siteJump = (int *) SafeCalloc (numChar, sizeof(int));
5461 memAllocs[ALLOC_SITEJUMP] = YES;
5464 MrBayesPrint ("%s Problem allocating siteJump in InitAdGamma (%d ints)\n", spacer, numChar);
5469 /* reset vector indicating the matrices needed */
5470 for (i=0; i<MAX_SMALL_JUMP; i++)
5471 hasMarkovTi[i] = NO;
5473 /* fill in siteJump */
5474 for (i=0; i<numCurrentDivisions; i++)
5477 k = 1; /* index to corr model, 0 means no corr model */
5478 maxRates = 0; /* max no. rates */
5479 for (d=0; d<numCurrentDivisions; d++)
5480 modelSettings[d].mark = NO;
5482 for (d=0; d<numCurrentDivisions; d++)
5484 m = &modelSettings[d];
5486 if (m->correlation == NULL || m->mark == YES)
5490 for (i=0; i<m->correlation->nRelParts; i++)
5492 if (modelSettings[m->correlation->relParts[i]].shape ==
5493 modelSettings[d].shape)
5495 modelSettings[m->correlation->relParts[i]].mark = YES;
5496 corrModel[m->correlation->relParts[i]] = k;
5501 if (m->numGammaCats > maxRates)
5502 maxRates = m->numGammaCats;
5506 for (c=0; c<numChar; c++)
5508 if (charInfo[c].isExcluded == YES)
5511 if ((k=corrModel[partitionId[c][partitionNum] - 1]) == 0)
5514 /* How far back is last char in this HMM? */
5515 for (j=c-1; j>=0; j--)
5517 if (corrModel[partitionId[j][partitionNum] - 1] == k)
5523 else if (charInfo[j].bigBreakAfter == YES)
5524 siteJump[c] = BIG_JUMP;
5527 siteJump[c] = c - j;
5528 hasMarkovTi[c-j-1] = YES;
5532 /* check if any HMM is empty */
5534 for (i=0; i<numCurrentDivisions; i++)
5536 if (corrModel[i] > k)
5539 for (i=1; i<=k; i++)
5541 for (c=j=0; c<numChar; c++)
5543 if (charInfo[c].isExcluded == NO && corrModel[partitionId[c][partitionNum] - 1] == i)
5548 MrBayesPrint ("%s ERROR: HMM model %d is empty.\n",spacer,i);
5554 /* allocate MarkovTis (space needed for calculations) */
5555 if (memAllocs[ALLOC_MARKOVTIS] == YES)
5557 MrBayesPrint ("%s markovTis not free in InitAdGamma\n", spacer);
5562 for (i=0; i<MAX_SMALL_JUMP; i++)
5564 if (hasMarkovTi[i] == YES || i == 0) /* base matrix always needed */
5566 markovTi[i] = AllocateSquareDoubleMatrix(maxRates);
5567 if (markovTi[i] == NULL)
5574 markovTiN = AllocateSquareDoubleMatrix(maxRates);
5575 if (i >= MAX_SMALL_JUMP && markovTiN)
5576 memAllocs[ALLOC_MARKOVTIS] = YES;
5579 MrBayesPrint ("%s Problem allocating MarkovTis in InitAdGamma (%d MrBFlt)\n", spacer, 2 * MAX_GAMMA_CATS * MAX_GAMMA_CATS);
5580 for (i=0; i<MAX_SMALL_JUMP; i++)
5581 if (markovTi[i] != NULL)
5582 FreeSquareDoubleMatrix (markovTi[i]);
5583 if (markovTiN != NULL)
5584 FreeSquareDoubleMatrix(markovTiN);
5589 /* allocate space for rateProbs needed by adgamma model */
5591 /* calculate size needed */
5593 for (j=0; j<numCurrentDivisions; j++)
5595 m = &modelSettings[j];
5596 if (m->correlation != NULL)
5598 m->rateProbStart = i;
5599 i += m->numGammaCats * m->numChars;
5602 rateProbRowSize = i;
5604 /* allocate space */
5605 if (memAllocs[ALLOC_RATEPROBS] == YES)
5607 MrBayesPrint ("%s Space for rate probs not free in InitAdGamma\n", spacer);
5611 rateProbSpace = (MrBFlt *) SafeMalloc (2 * numLocalChains * rateProbRowSize * sizeof(MrBFlt));
5612 rateProbs = (MrBFlt **) SafeMalloc (numLocalChains * sizeof(MrBFlt *));
5613 if (!rateProbSpace || !rateProbs)
5615 MrBayesPrint ("%s Problem allocating rate probs\n", spacer);
5617 free (rateProbSpace);
5624 memAllocs[ALLOC_RATEPROBS] = YES;
5626 /* set chain rateProbs pointers */
5627 for (i=j=0; i<numLocalChains; i++)
5629 rateProbs[i] = rateProbSpace + j;
5630 j += 2 * rateProbRowSize;
5639 /*------------------------------------------------------------------------
5641 | InitAugmentedModels: allocate and initialize space for augmented
5644 -------------------------------------------------------------------------*/
5645 int InitAugmentedModels (void)
5647 int d, i, j, useAugmentedModels, nRateCats;
5650 useAugmentedModels = NO;
5651 for (d=0; d<numCurrentDivisions; d++)
5653 if (modelSettings[d].gibbsGamma == YES)
5654 useAugmentedModels = YES;
5657 if (useAugmentedModels == NO)
5660 MrBayesPrint ("%s Initializing variables for model augmentation\n", spacer);
5662 for (d=0; d<numCurrentDivisions; d++)
5664 m = &modelSettings[d];
5665 if (m->gibbsGamma == NO)
5667 m->tiIndex = (int *) SafeMalloc (numLocalChains * m->numChars * sizeof (int));
5670 m->catLike = (CLFlt ***) SafeMalloc (numLocalChains * sizeof (CLFlt **));
5673 m->catLnScaler = (CLFlt ***) SafeMalloc (numLocalChains * sizeof (CLFlt **));
5674 if (!m->catLnScaler)
5676 if (m->pInvar == NULL)
5677 nRateCats = m->numGammaCats;
5679 nRateCats = m->numGammaCats + 1;
5680 for (i=0; i<numLocalChains; i++)
5682 m->catLike[i] = (CLFlt **) SafeCalloc (nRateCats, sizeof (CLFlt *));
5685 m->catLnScaler[i] = (CLFlt **) SafeCalloc (nRateCats, sizeof (CLFlt *));
5686 if (!m->catLnScaler[i])
5688 for (j=0; j<nRateCats; j++)
5690 m->catLike[i][j] = (CLFlt *) SafeCalloc (m->numChars, sizeof (CLFlt));
5691 if (!m->catLike[i][j])
5693 m->catLnScaler[i][j] = (CLFlt *) SafeCalloc (m->numChars, sizeof (CLFlt));
5694 if (!m->catLnScaler[i][j])
5704 /*------------------------------------------------------------------------
5706 | InitChainCondLikes: (1) calculate size of cond like arrays, tiprob arrays
5707 | and scaler arrays; (2) allocate space for cond like, tiprob and
5708 | scaler arrays; (3) allocate and set node indices pointing to
5709 | cond like and scaler arrays; (4) initialize tip cond likes;
5710 | (5) allocate space for precalculated cond likes; (6) allocate
5711 | space for adgamma probs, if used.
5713 -------------------------------------------------------------------------*/
5714 int InitChainCondLikes (void)
5716 int c, d, i, j, k, s, t, numReps, condLikesUsed, nIntNodes, nNodes, useBeagle,
5717 clIndex, tiIndex, scalerIndex, indexStep;
5721 # if defined (SSE_ENABLED)
5724 # if defined (BEAGLE_ENABLED)
5725 double *nSitesOfPat;
5729 /* Figure out how large cond like array is needed, and how many cond like, scaler and tiprob arrays are needed.
5730 Also check for possible use of Beagle */
5732 for (d=0; d<numCurrentDivisions; d++)
5734 m = &modelSettings[d];
5736 MrBayesPrint ("%s Division %d has %d unique site patterns\n", spacer, d+1, m->numChars);
5738 /* initialize model settings for chain cond likes */
5739 m->condLikeLength = 0;
5740 m->numCondLikes = 0;
5742 if (m->parsModelId == YES)
5745 condLikesUsed = YES;
5747 /* figure out length of cond like array */
5748 if (m->dataType == STANDARD)
5750 # if defined (BEAGLE_ENABLED)
5753 for (c=0; c<m->numChars; c++)
5755 numReps = m->numGammaCats;
5756 if (m->nStates[c] == 2)
5757 numReps *= m->numBetaCats;
5758 m->condLikeLength += m->nStates[c] * numReps;
5763 if (m->gibbsGamma == YES)
5764 m->condLikeLength = m->numChars * m->numModelStates;
5766 m->condLikeLength = m->numChars * m->numGammaCats * m->numOmegaCats * m->numModelStates;
5767 # if defined (BEAGLE_ENABLED)
5768 /* tentatively decide on whether to use Beagle */
5769 if (tryToUseBEAGLE == YES)
5771 if (m->printAncStates == YES || m->printSiteRates == YES || m->printPosSel ==YES || m->printSiteOmegas==YES)
5773 MrBayesPrint ("%s Non-beagle version of conditional likelihood calculator will be used for division %d due to\n", spacer, d+1);
5774 MrBayesPrint ("%s request of reporting 'ancestral states', 'site rates', 'pos selection' or 'site omegas'.\n", spacer);
5776 else if (m->gibbsGamma == NO)
5782 /* find size of tree */
5783 nIntNodes = GetTree(m->brlens, 0, 0)->nIntNodes;
5784 nNodes = GetTree(m->brlens, 0, 0)->nNodes;
5786 /* figure out number of cond like arrays */
5787 m->numCondLikes = (numLocalChains + 1) * (nIntNodes);
5788 m->numCondLikes += numLocalTaxa;
5790 # if !defined (DEBUG_NOSHORTCUTS)
5791 for (i=0; i<numLocalTaxa; i++)
5793 if (m->isPartAmbig[i] == NO && m->dataType != STANDARD)
5799 /* figure out number of node and site scalers */
5800 m->numScalers = (numLocalChains + 1) * (nIntNodes + 1); /* add 1 for site scalers */
5802 /* figure out length of ti prob array and number of ti prob arrays */
5803 m->tiProbLength = 0;
5804 if (m->dataType == STANDARD)
5806 m->numTiCats = 0; /* We do not have repeated similar transition probability matrices */
5807 if (m->stateFreq->paramId == SYMPI_EQUAL)
5811 if (m->isTiNeeded[k] == YES)
5812 m->tiProbLength += (k + 2) * (k + 2) * m->numGammaCats;
5814 for (k=9; k<13; k++)
5816 if (m->isTiNeeded[k] == YES)
5817 m->tiProbLength += (k - 6) * (k - 6) * m->numGammaCats;
5819 for (k=13; k<18; k++)
5821 if (m->isTiNeeded[k] == YES)
5822 m->tiProbLength += (k - 11) * (k - 11) * m->numGammaCats;
5827 /* deal with unequal state frequencies */
5828 if (m->isTiNeeded[0] == YES)
5829 m->tiProbLength += 4 * m->numGammaCats * m->numBetaCats;
5830 for (c=0; c<m->numChars; c++)
5832 if (m->nStates[c] > 2 && (m->cType[c] == UNORD || m->cType[c] == ORD))
5834 m->tiProbLength += (m->nStates[c] * m->nStates[c]) * m->numGammaCats;
5841 m->numTiCats = m->numGammaCats * m->numBetaCats * m->numOmegaCats; /* A single partition has either gamma, beta or omega categories */
5842 m->tiProbLength = m->numModelStates * m->numModelStates * m->numTiCats;
5844 m->numTiProbs = (numLocalChains + 1) * nNodes;
5846 /* set info about eigen systems */
5847 if (InitEigenSystemInfo (m) == ERROR)
5851 /* check if conditional likelihoods are needed */
5852 if (condLikesUsed == YES)
5853 MrBayesPrint ("%s Initializing conditional likelihoods\n", spacer);
5857 /* allocate space and fill in info for tips */
5858 for (d=0; d<numCurrentDivisions; d++)
5860 m = &modelSettings[d];
5862 /* allocate space for conditional likelihoods */
5864 # if defined (BEAGLE_ENABLED)
5865 if (m->useBeagle == YES)
5867 if (InitBeagleInstance(m, d) != ERROR)
5874 # if defined (SSE_ENABLED)
5875 /*if (useBeagle == NO && m->dataType != STANDARD)
5877 if (useBeagle == YES)
5881 if (useBeagle == NO && m->useSSE == NO)
5882 MrBayesPrint ("%s Using standard non-SSE likelihood calculator for division %d (%s-precision)\n", spacer, d+1, (sizeof(CLFlt) == 4 ? "single" : "double"));
5883 else if (useBeagle == NO && m->useSSE == YES)
5884 MrBayesPrint ("%s Using standard SSE likelihood calculator for division %d (single-precision)\n", spacer, d+1);
5886 if (useBeagle == NO)
5888 /* allocate cond like space */
5889 m->condLikes = (CLFlt**) SafeMalloc(m->numCondLikes * sizeof(CLFlt*));
5892 for (i=0; i<m->numCondLikes; i++)
5894 # if defined (SSE_ENABLED)
5895 if (m->useSSE == YES)
5897 /* calculate number SSE chars */
5898 m->numSSEChars = ((m->numChars - 1) / FLOATS_PER_VEC) + 1;
5900 /* allocate space with padding (m->condLikeLength is without padding) */
5901 if (m->gibbsGamma == YES)
5904 numReps = m->numGammaCats * m->numOmegaCats;
5905 k = m->numSSEChars * FLOATS_PER_VEC * m->numModelStates * numReps;
5907 m->condLikes[i] = (CLFlt*) AlignedMalloc (k * sizeof(CLFlt), 16);
5908 if (!m->condLikes[i])
5911 /* start by filling all with 0.0f; pad when filling in tips */
5913 m->condLikes[i][j] = 0.0f;
5917 m->condLikes[i] = (CLFlt*) SafeMalloc(m->condLikeLength * sizeof(CLFlt));
5918 if (!m->condLikes[i])
5922 m->condLikes[i] = (CLFlt*) SafeMalloc(m->condLikeLength * sizeof(CLFlt));
5923 if (!m->condLikes[i])
5928 /* allocate scaler space and pointers for scaling */
5929 m->scalers = (CLFlt**) SafeMalloc(m->numScalers * sizeof(CLFlt*));
5932 for (i=0; i<m->numScalers; i++)
5934 # if defined (SSE_ENABLED)
5935 if (m->useSSE == YES)
5937 /* allocate space with padding */
5938 m->scalers[i] = (CLFlt*) AlignedMalloc (m->numSSEChars * FLOATS_PER_VEC * sizeof(CLFlt), 16);
5941 for (j=0; j<m->numSSEChars*FLOATS_PER_VEC; j++)
5942 m->scalers[i][j] = 0.0f;
5946 m->scalers[i] = (CLFlt*) SafeMalloc (m->numChars * sizeof(CLFlt));
5951 m->scalers[i] = (CLFlt*) SafeMalloc (m->numChars * sizeof(CLFlt));
5957 /* allocate stuff for facilitating scaling and accumulation of cond likes */
5958 if (m->dataType == STANDARD)
5960 m->clP = (CLFlt **) SafeMalloc(m->numGammaCats * sizeof(CLFlt *));
5966 m->clP = (CLFlt **) SafeMalloc(m->numTiCats * sizeof(CLFlt *));
5969 # if defined (SSE_ENABLED)
5970 if (m->useSSE == YES)
5972 m->clP_SSE = (__m128 **) SafeMalloc(m->numTiCats * sizeof(__m128 *));
5975 m->lnL_SSE = AlignedMalloc (m->numSSEChars * FLOATS_PER_VEC * sizeof(CLFlt*), 16);
5976 m->lnLI_SSE = AlignedMalloc (m->numSSEChars * FLOATS_PER_VEC * sizeof(CLFlt*), 16);
5977 if (!m->lnL_SSE || !m->lnLI_SSE)
5983 /* allocate tiprob space */
5984 m->tiProbs = (CLFlt**) SafeMalloc(m->numTiProbs * sizeof(CLFlt*));
5987 for (i=0; i<m->numTiProbs; i++)
5989 m->tiProbs[i] = (CLFlt*) SafeMalloc(m->tiProbLength * sizeof(CLFlt));
5995 /* allocate eigen system space (needed also for Beagle version */
5996 if (m->nCijkParts > 0)
5998 m->cijks = (MrBFlt**) SafeMalloc((numLocalChains + 1) * sizeof(MrBFlt*));
6001 for (i=0; i<numLocalChains+1; i++)
6003 m->cijks[i] = (MrBFlt*) SafeMalloc(m->cijkLength * sizeof(MrBFlt));
6009 /* get size of tree */
6010 nIntNodes = GetTree(m->brlens,0,0)->nIntNodes;
6011 nNodes = GetTree(m->brlens,0,0)->nNodes;
6014 /* allocate and set indices from tree nodes to cond like arrays */
6015 m->condLikeIndex = (int **) SafeMalloc (numLocalChains * sizeof(int *));
6016 if (!m->condLikeIndex)
6018 for (i=0; i<numLocalChains; i++)
6020 m->condLikeIndex[i] = (int *) SafeMalloc (nNodes * sizeof(int));
6021 if (!m->condLikeIndex[i])
6024 for (i=0; i<numLocalChains; i++)
6025 for (j=0; j<nNodes; j++)
6026 m->condLikeIndex[i][j] = -1;
6028 /* set up indices for terminal nodes */
6030 if (useBeagle == YES)
6031 indexStep = m->nCijkParts;
6034 for (i=0; i<numLocalTaxa; i++)
6036 # if !defined (DEBUG_NOSHORTCUTS)
6037 /* TODO: Untill CondLikeRoot_XXX are fixed (case 4 when one of the children is non-ambig) we allocate space for non-ambig tips. if fixed also uncoment down the function */
6038 /* if (useBeagle == NO && useSSE == NO && m->isPartAmbig[i] == NO && m->dataType != STANDARD)
6042 for (j=0; j<numLocalChains; j++)
6043 m->condLikeIndex[j][i] = clIndex;
6044 clIndex += 1; /* even for multiple omega cat we need only one set of conditional likelihoods for terminals for all chains.*/
6047 /* reserve private space for parsimony-based moves if parsimony model is used */
6048 if (m->parsModelId == YES && m->parsimonyBasedMove == YES)
6049 clIndex += nIntNodes;
6051 /* set up indices for internal nodes */
6052 for (j=0; j<numLocalChains; j++)
6054 for (i=0; i<nIntNodes; i++)
6056 m->condLikeIndex[j][i+numLocalTaxa] = clIndex;
6057 clIndex += indexStep;
6061 /* allocate and set up scratch cond like indices */
6062 m->condLikeScratchIndex = (int *) SafeMalloc (nNodes * sizeof(int));
6063 if (!m->condLikeScratchIndex)
6065 for (i=0; i<nNodes; i++)
6066 m->condLikeScratchIndex[i] = -1;
6067 for (i=0; i<nIntNodes; i++)
6069 m->condLikeScratchIndex[i+numLocalTaxa] = clIndex;
6070 clIndex += indexStep;
6073 /* allocate and set indices from tree edges to ti prob arrays */
6074 m->tiProbsIndex = (int **) SafeMalloc (numLocalChains * sizeof(int *));
6075 if (!m->tiProbsIndex)
6077 for (i=0; i<numLocalChains; i++)
6079 m->tiProbsIndex[i] = (int *) SafeMalloc (nNodes * sizeof(int));
6080 if (!m->tiProbsIndex[i])
6084 /* set up indices for nodes */
6086 for (i=0; i<numLocalChains; i++)
6088 for (j=0; j<nNodes; j++)
6090 m->tiProbsIndex[i][j] = tiIndex;
6091 tiIndex += indexStep;
6095 /* allocate and set up scratch transition prob indices */
6096 m->tiProbsScratchIndex = (int *) SafeMalloc (nNodes * sizeof(int));
6097 if (!m->tiProbsScratchIndex)
6099 for (i=0; i<nNodes; i++)
6101 m->tiProbsScratchIndex[i] = tiIndex;
6102 tiIndex += indexStep;
6105 /* allocate and set up node scaler indices */
6107 m->nodeScalerIndex = (int **) SafeMalloc (numLocalChains * sizeof(int *));
6108 if (!m->nodeScalerIndex)
6110 for (i=0; i<numLocalChains; i++)
6112 m->nodeScalerIndex[i] = (int *) SafeMalloc (nNodes * sizeof(int));
6113 if (!m->nodeScalerIndex[i])
6115 for (j=0; j<nNodes; j++)
6116 m->nodeScalerIndex[i][j] = -1;
6117 for (j=0; j<nIntNodes; j++)
6119 m->nodeScalerIndex[i][j+numLocalTaxa] = scalerIndex;
6120 scalerIndex += indexStep;
6123 m->nodeScalerScratchIndex = (int *) SafeMalloc (nNodes * sizeof (int));
6124 if (!m->nodeScalerScratchIndex)
6126 for (i=0; i<nNodes; i++)
6127 m->nodeScalerScratchIndex[i] = -1;
6128 for (i=0; i<nIntNodes; i++)
6130 m->nodeScalerScratchIndex[i+numLocalTaxa] = scalerIndex;
6131 scalerIndex += indexStep;
6134 /* allocate and set up node scaler flags */
6135 m->scalersSet = (int **) SafeMalloc (numLocalChains * sizeof(int *));
6138 for (i=0; i<numLocalChains; i++)
6140 m->scalersSet[i] = (int *) SafeMalloc (nNodes * sizeof(int));
6141 if (!m->scalersSet[i])
6143 for (j=0; j<nNodes; j++)
6144 m->scalersSet[i][j] = NO;
6146 m->scalersSetScratch = (int *) SafeMalloc (nNodes * sizeof (int));
6147 if (!m->scalersSetScratch)
6149 for (i=0; i<nNodes; i++)
6150 m->scalersSetScratch[i] = NO;
6152 /* allocate and set up site scaler indices */
6153 m->siteScalerIndex = (int *) SafeMalloc (numLocalChains * sizeof(int));
6154 if (!m->siteScalerIndex)
6156 for (i=0; i<numLocalChains; i++)
6158 m->siteScalerIndex[i] = scalerIndex;
6159 scalerIndex += indexStep;
6161 m->siteScalerScratchIndex = scalerIndex;
6163 # if defined (BEAGLE_ENABLED)
6164 /* used only with Beagle advanced dynamic rescaling where we set scaler nodes for each partition */
6165 if (m->useBeagle == YES)
6167 m->succesCount = (int*) SafeMalloc((numLocalChains) * sizeof(int));
6168 m->rescaleFreq = (int*) SafeMalloc((numLocalChains) * sizeof(int));
6169 m->beagleComputeCount = (long *) SafeMalloc(sizeof(long) * numLocalChains);
6170 t=BEAGLE_RESCALE_FREQ/m->numModelStates;
6171 if (beagleFlags & BEAGLE_FLAG_PRECISION_DOUBLE) /*if double presition is used*/
6172 t*=BEAGLE_RESCALE_FREQ_DOUBLE;
6173 for (i=0; i<numLocalChains; i++)
6175 m->rescaleFreq[i] = t;
6177 m->isScalerNode = (int**) SafeMalloc((numLocalChains) * sizeof(int*));
6178 /* we will use m->isScalerNode[chain][node->index] to determine whether the node is scaled or not. We do it only for internal nodes whose indexes start from numLocalTaxa thus we skew the pointer */
6179 m->isScalerNodeScratch = (int*) SafeMalloc(nIntNodes * sizeof(int)) - numLocalTaxa;
6180 assert (NO == 0); /* SafeMalloc set the allocated memmory to 0 while we need to set it to NO */
6181 for (i=0; i<numLocalChains; i++)
6183 m->isScalerNode[i] = (int*) SafeMalloc(nIntNodes * sizeof(int)) - numLocalTaxa;
6188 /* allocate and set up cijk indices */
6189 if (m->nCijkParts > 0)
6191 m->cijkIndex = (int *) SafeMalloc (numLocalChains * sizeof(int));
6194 for (i=0; i<numLocalChains; i++)
6195 m->cijkIndex[i] = i*indexStep;
6196 m->cijkScratchIndex = numLocalChains*indexStep;
6199 # if defined (BEAGLE_ENABLED)
6200 /* Set up nSitesOfPat for Beagle */
6201 if (m->useBeagle == YES)
6203 nSitesOfPat = (double *) SafeMalloc (m->numChars * sizeof(double));
6204 for (c=0; c<m->numChars; c++)
6205 nSitesOfPat[c] = numSitesOfPat[m->compCharStart + c];
6206 beagleSetPatternWeights(m->beagleInstance,
6211 /* find category frequencies */
6212 if (m->pInvar == NO)
6214 freq = 1.0 / m->numGammaCats;
6216 /* set category frequencies in beagle instance */
6217 if (m->numOmegaCats <= 1)
6219 for (i=0; i<m->numGammaCats; i++)
6220 m->inWeights[i] = freq;
6221 for (i=0; i< (numLocalChains); i++) {
6222 beagleSetCategoryWeights(m->beagleInstance,
6226 beagleSetCategoryWeights(m->beagleInstance,
6227 m->cijkScratchIndex,
6232 /* Set up scalers for Beagle */
6233 for (i=0; i<m->numScalers*m->nCijkParts; i++)
6234 beagleResetScaleFactors(m->beagleInstance, i);
6238 /* fill in tip conditional likelihoods */
6239 if (m->dataType == STANDARD)
6242 for (i=0; i<numLocalTaxa; i++)
6244 cL = m->condLikes[clIndex++];
6245 for (t=0; t<m->numGammaCats;t++)
6247 charBits = m->parsSets[i];
6248 for (c=0; c<m->numChars; c++)
6250 if (m->nStates[c] == 2)
6251 numReps = m->numBetaCats;
6254 for (k=0; k<numReps; k++)
6256 for (s=0; s<m->nStates[c]; s++)
6258 if (IsBitSet(s, charBits))
6263 charBits += m->nParsIntsPerSite;
6268 else if (useBeagle == NO)
6270 if (m->gibbsGamma == YES)
6271 numReps = m->numTiCats / m->numGammaCats;
6273 numReps = m->numTiCats;
6276 for (i=0; i<numLocalTaxa; i++)
6278 # if !defined (DEBUG_NOSHORTCUTS) && !defined (SSE_ENABLED)
6279 /* TODO: Untill CondLikeRoot_XXX are fixed (case 4 when one of the children is non-ambig) we allocate space for non-ambig tips. if fixed also uncomment up the function */
6280 /* if (m->isPartAmbig[i] == NO && m->dataType != RESTRICTION)
6284 cL = m->condLikes[clIndex++];
6285 # if defined (SSE_ENABLED)
6286 if (m->useSSE == YES)
6288 for (k=0; k<numReps; k++)
6290 charBits = m->parsSets[i];
6291 for (c=0; c<m->numChars/FLOATS_PER_VEC; c++)
6293 for (j=0; j<m->numModelStates/m->numStates; j++)
6295 for (s=0; s<m->numStates; s++)
6297 for (j1=0; j1<FLOATS_PER_VEC; j1++)
6299 if (IsBitSet(s, charBits + j1*m->nParsIntsPerSite))
6305 charBits += FLOATS_PER_VEC * m->nParsIntsPerSite;
6307 if (m->numChars % FLOATS_PER_VEC > 0)
6309 /* add last characters and padd */
6310 for (j=0; j<m->numModelStates/m->numStates; j++)
6312 for (s=0; s<m->numStates; s++)
6314 for (j1=0; j1<m->numChars%FLOATS_PER_VEC; j1++)
6316 if (IsBitSet(s, charBits + j1*m->nParsIntsPerSite))
6320 for (; j1<FLOATS_PER_VEC; j1++)
6332 for (k=0; k<numReps; k++)
6334 charBits = m->parsSets[i];
6335 for (c=0; c<m->numChars; c++)
6337 for (j=0; j<m->numModelStates/m->numStates; j++)
6339 for (s=0; s<m->numStates; s++)
6341 if (IsBitSet(s, charBits))
6346 charBits += m->nParsIntsPerSite;
6352 for (k=0; k<numReps; k++)
6354 charBits = m->parsSets[i];
6355 for (c=0; c<m->numChars; c++)
6357 for (j=0; j<m->numModelStates/m->numStates; j++)
6359 for (s=0; s<m->numStates; s++)
6361 if (IsBitSet(s, charBits))
6366 charBits += m->nParsIntsPerSite;
6373 if (m->printAncStates == YES)
6375 m->ancStateCondLikes = (CLFlt *) SafeMalloc (m->condLikeLength * sizeof(CLFlt));
6376 if (!m->ancStateCondLikes)
6380 /* allocate space for precalculated likelihoods */
6382 for (d=0; d<numCurrentDivisions; d++)
6384 m = &modelSettings[d];
6385 if (m->dataType == STANDARD || m->parsModelId == YES)
6388 i = (m->numModelStates + 1) * m->numModelStates * m->numTiCats;
6392 if (j > 0) /* don't bother allocating precalculated likelihoods if we only have parsimony model or morphological characters */
6394 if (memAllocs[ALLOC_PRELIKES] == YES)
6396 MrBayesPrint ("%s Space for preLikes not free in InitChainCondLikes\n", spacer);
6399 preLikeL = (CLFlt *) SafeMalloc (3 * j * sizeof(CLFlt));
6402 MrBayesPrint ("%s Problem allocating preLikes\n", spacer);
6405 memAllocs[ALLOC_PRELIKES] = YES;
6406 preLikeR = preLikeL + j;
6407 preLikeA = preLikeR + j;
6414 /*------------------------------------------------------------------------
6416 | InitEigenSystemInfo: set info about eigen decompositions
6418 -------------------------------------------------------------------------*/
6419 int InitEigenSystemInfo (ModelInfo *m)
6423 if (m->dataType == STANDARD)
6425 /* dealt with in ProcessStdChars */
6431 if (m->dataType == PROTEIN)
6433 ts = m->numModelStates;
6434 m->cijkLength = (ts * ts * ts) + (2 * ts);
6436 if (m->switchRates != NULL) /* covarion model */
6438 m->cijkLength *= m->numGammaCats;
6439 m->nCijkParts = m->numGammaCats;
6442 else if (m->dataType == DNA || m->dataType == RNA)
6444 if (m->nucModelId == NUCMODEL_4BY4)
6446 if (m->switchRates==NULL && m->nst != 6 && m->nst != NST_MIXED)
6450 # if defined (BEAGLE_ENABLED)
6451 ts = m->numModelStates;
6452 m->cijkLength = (ts * ts * ts) + (2 * ts);
6458 ts = m->numModelStates;
6459 m->cijkLength = (ts * ts * ts) + (2 * ts);
6462 if (m->switchRates != NULL)
6464 m->cijkLength *= m->numGammaCats;
6465 m->nCijkParts = m->numGammaCats;
6468 else if (m->nucModelId == NUCMODEL_DOUBLET)
6470 ts = m->numModelStates;
6471 m->cijkLength = (ts * ts * ts) + (2 * ts);
6474 else if (m->nucModelId == NUCMODEL_CODON)
6476 ts = m->numModelStates;
6477 m->cijkLength = (ts * ts * ts) + (2 * ts);
6478 m->cijkLength *= m->numOmegaCats;
6479 m->nCijkParts = m->numOmegaCats;
6483 MrBayesPrint ("%s ERROR: Something is wrong if you are here.\n", spacer);
6487 # if defined (BEAGLE_ENABLED)
6488 else if (m->dataType == RESTRICTION)
6490 assert (m->numModelStates == 2);
6492 m->cijkLength = (ts * ts * ts) + (2 * ts);
6500 /*------------------------------------------------------------------------
6502 | InitFinalStateCondLikes: allocate space for final conditional
6503 | likelihoods if needed
6505 -------------------------------------------------------------------------*/
6506 int InitFinalStateCondLikes (void)
6511 for (d=0; d<numCurrentDivisions; d++)
6513 m = &modelSettings[d];
6514 if (m->printAncStates == YES)
6516 m->ancStateCondLikes = (CLFlt *) SafeMalloc (m->condLikeLength * sizeof(CLFlt));
6517 if (!m->ancStateCondLikes)
6525 /*------------------------------------------------------------------------
6527 | InitInvCondLikes: allocate and initialize invariable conditional
6528 | likelihoods if needed
6530 | NB! Fills in invariable cond likes for all hidden states; this
6531 | is convenient although some space is wasted
6533 -------------------------------------------------------------------------*/
6534 int InitInvCondLikes (void)
6536 int c, d, i, s, isConstant, usingInvCondLikes;
6541 # if defined (SSE_ENABLED)
6545 /* allocate space for invariable cond likes */
6546 usingInvCondLikes = NO;
6547 for (d=0; d<numCurrentDivisions; d++)
6549 m = &modelSettings[d];
6551 if (m->pInvar == NULL)
6554 usingInvCondLikes = YES;
6555 # if defined (SSE_ENABLED)
6556 c1 = m->numSSEChars * FLOATS_PER_VEC * m->numModelStates;
6557 m->invCondLikes = (CLFlt *) AlignedMalloc (c1 * sizeof(CLFlt), 16);
6558 for (i=0; i<c1; i++)
6559 m->invCondLikes[i] = 0.0f;
6561 m->invCondLikes = (CLFlt *) SafeMalloc (m->numChars * m->numModelStates * sizeof(CLFlt));
6563 if (!m->invCondLikes)
6567 if (usingInvCondLikes == NO)
6570 MrBayesPrint ("%s Initializing invariable-site conditional likelihoods\n", spacer);
6572 /* fill in invariable-site conditional likelihoods */
6573 for (d=0; d<numCurrentDivisions; d++)
6576 m = &modelSettings[d];
6578 if (m->pInvar == NULL)
6581 cI = m->invCondLikes;
6582 if (m->dataType == STANDARD)
6584 for (c=0; c<m->numChars; c++)
6586 for (s=0; s<m->nStates[c]; s++)
6589 for (i=0; i<numLocalTaxa; i++)
6591 charBits = &m->parsSets[i][c*m->nParsIntsPerSite];
6592 if (IsBitSet(s, charBits) == NO)
6598 if (isConstant == YES)
6606 else /* all other models for which pInvar is applicable */
6608 assert (m->numModelStates == m->numStates);
6609 # if defined (SSE_ENABLED)
6610 for (c=0; c<m->numChars/FLOATS_PER_VEC; c++)
6612 for (s=0; s<m->numModelStates; s++)
6614 for (c1=0; c1<FLOATS_PER_VEC; c1++)
6617 //charBits = parsMatrix + m->parsMatrixStart + ((c * FLOATS_PER_VEC) + c1) * m->nParsIntsPerSite;
6618 for (i=0; i<numLocalTaxa; i++)
6620 charBits = &m->parsSets[i][((c * FLOATS_PER_VEC) + c1) *m->nParsIntsPerSite];
6621 if (IsBitSet(s, charBits) == NO)
6626 //charBits += parsMatrixRowSize;
6628 if (isConstant == YES)
6634 if (m->numChars % FLOATS_PER_VEC != 0)
6636 for (s=0; s<m->numModelStates; s++)
6638 for (c1=0; c1<m->numChars%FLOATS_PER_VEC; c1++)
6641 //charBits = parsMatrix + m->parsMatrixStart + (((m->numChars / FLOATS_PER_VEC) * FLOATS_PER_VEC) + c1) * m->nParsIntsPerSite;
6642 for (i=0; i<numLocalTaxa; i++)
6644 charBits = &m->parsSets[i][(((m->numChars / FLOATS_PER_VEC) * FLOATS_PER_VEC) + c1) *m->nParsIntsPerSite];
6645 if (IsBitSet(s, charBits) == NO)
6650 //charBits += parsMatrixRowSize;
6652 if (isConstant == YES)
6656 for (; c1<FLOATS_PER_VEC; c1++)
6664 for (c=0; c<m->numChars; c++)
6666 for (s=0; s<m->numModelStates; s++)
6669 for (i=0; i<numLocalTaxa; i++)
6671 charBits = &m->parsSets[i][c*m->nParsIntsPerSite];
6672 if (IsBitSet(s, charBits) == NO)
6678 if (isConstant == YES)
6685 } /* next division */
6688 invCondLikeSize = 0;
6689 for (d=0; d<numCurrentDivisions; d++)
6691 m = &modelSettings[d];
6692 if (m->pInvar == NULL)
6694 cI = m->invCondLikes;
6695 if (m->dataType == STANDARD)
6700 for (c=0; c<m->numChars; c++)
6702 printf ("%4d -- ", c);
6703 for (s=0; s<m->numModelStates; s++)
6705 printf ("%1.0lf", *cI);
6718 /*------------------------------------------------------------------------
6720 | InitParsSets: allocate space for and set parsimony state sets
6722 -------------------------------------------------------------------------*/
6723 int InitParsSets (void)
6725 int c, i, j, k, d, nParsStatesForCont, nIntNodes, nNodes,
6726 nuc1, nuc2, nuc3, codingNucCode, allNucCode;
6727 BitsLong allAmbig, x, x1, x2, x3, *longPtr, bitsLongOne;
6733 /* this variable determines how many parsimony states are used */
6734 /* to represent continuous characters (determines weight of these chars) */
6735 nParsStatesForCont = 3;
6737 /* find number and size of parsimony sets and node lengths */
6738 for (d=0; d<numCurrentDivisions; d++)
6740 m = &modelSettings[d];
6741 mp = &modelParams[d];
6743 /* find how many parsimony ints (BitsLong) are needed for each model site */
6744 if (mp->dataType == CONTINUOUS)
6746 /* scale continuous characters down to an ordered parsimony character */
6747 /* with nParsStatesForCont states, represent this character as a set */
6748 /* of binary characters by additive binary coding */
6749 m->nParsIntsPerSite = nParsStatesForCont - 1;
6752 m->nParsIntsPerSite = 1 + m->numStates / nBitsInALong;
6754 /* Calculate number of nodes and number of internal nodes */
6755 nIntNodes = GetTree(m->brlens,0,0)->nIntNodes;
6756 nNodes = GetTree(m->brlens,0,0)->nNodes;
6758 /* Calculate number of parsimony sets */
6759 m->numParsSets = numLocalTaxa;
6760 if (m->parsimonyBasedMove == YES || !strcmp(chainParams.startTree, "Parsimony"))
6761 m->numParsSets += nIntNodes;
6762 if (m->parsModelId == YES)
6763 m->numParsSets += (numLocalChains + 1) * nIntNodes;
6765 if (m->parsModelId == YES)
6766 m->numParsNodeLens = (numLocalChains + 1) * nNodes;
6768 m->numParsNodeLens = 0;
6771 /* then allocate space for the sets and node lengths */
6772 for (d=0; d<numCurrentDivisions; d++)
6774 m = &modelSettings[d];
6775 mp = &modelParams[d];
6777 m->parsSets = (BitsLong **) SafeCalloc (m->numParsSets, sizeof(BitsLong*));
6780 for (i=0; i<m->numParsSets; i++)
6782 m->parsSets[i] = (BitsLong *) SafeCalloc (m->numChars*m->nParsIntsPerSite, sizeof(BitsLong));
6783 if (!m->parsSets[i])
6787 if (m->numParsNodeLens > 0)
6789 m->parsNodeLens = (CLFlt *) SafeCalloc (m->numParsNodeLens, sizeof(CLFlt));
6790 if (!m->parsNodeLens)
6795 /* finally fill in tip parsimony sets */
6796 for (d=0; d<numCurrentDivisions; d++)
6798 m = &modelSettings[d];
6799 mp = &modelParams[d];
6801 if (mp->dataType == CONTINUOUS)
6803 /* Note: This is only a placeholder since continuous characters are not implemented yet.
6804 Using additive parsimony would be more efficient than using multiple binary chars as here. */
6805 for (i=0; i<numLocalTaxa; i++)
6807 for (c=0, j=m->compMatrixStart; j<m->compMatrixStop; j++, c++)
6809 x = compMatrix[pos(i,j,compMatrixRowSize)];
6811 for (k=0; k<m->nParsIntsPerSite; k++)
6813 if (x > (unsigned int)(k + 1) * 1000 / (m->nParsIntsPerSite + 1))
6814 m->parsSets[i][c*m->nParsIntsPerSite + k] = 1;
6816 m->parsSets[i][c*m->nParsIntsPerSite + k] = 2;
6821 else if (m->nCharsPerSite == 1 && m->nParsIntsPerSite == 1)
6823 allAmbig = (bitsLongOne<<mp->nStates) - 1UL;
6824 for (i=0; i<numLocalTaxa; i++)
6826 for (c=0, j=m->compMatrixStart; j<m->compMatrixStop; j++, c++)
6828 x = compMatrix[pos(i,j,compMatrixRowSize)];
6830 if (x == MISSING || x == GAP)
6831 m->parsSets[i][c] = allAmbig;
6833 m->parsSets[i][c] = x;
6837 else if (!strcmp(mp->nucModel, "Doublet") && (mp->dataType == DNA || mp->dataType == RNA))
6840 for (i=0; i<numLocalTaxa; i++)
6842 for (c=0, j=m->compMatrixStart; j<m->compMatrixStop; j+=m->nCharsPerSite, c++)
6844 /* fetch the original values x1 and x2 */
6845 x1 = compMatrix[pos(i,j,compMatrixRowSize)];
6846 if (x1 == MISSING || x1 == GAP)
6848 x2 = compMatrix[pos(i,j+1,compMatrixRowSize)];
6849 if (x2 == MISSING || x2 == GAP)
6851 /* squeeze them together in the new value x */
6853 for (nuc1=0; nuc1<4; nuc1++)
6855 for (nuc2=0; nuc2<4; nuc2++)
6857 if (IsBitSet(nuc1,&x1) == YES && IsBitSet(nuc2, &x2) == YES)
6858 x |= (bitsLongOne<<(nuc1*4 + nuc2));
6862 m->parsSets[i][c] = x;
6866 else if (!strcmp(mp->nucModel, "Codon") && (mp->dataType == DNA || mp->dataType == RNA))
6869 for (i=0; i<numLocalTaxa; i++)
6871 for (c=0, j=m->compMatrixStart; j<m->compMatrixStop; j+=m->nCharsPerSite, c++)
6873 /* fetch the original values x1, x2, and x3*/
6874 x1 = compMatrix[pos(i,j,compMatrixRowSize)];
6875 if (x1 == MISSING || x1 == GAP)
6877 x2 = compMatrix[pos(i,j+1,compMatrixRowSize)];
6878 if (x2 == MISSING || x2 == GAP)
6880 x3 = compMatrix[pos(i,j+2,compMatrixRowSize)];
6881 if (x3 == MISSING || x3 == GAP)
6884 /* squeeze them together in the new long string pointed to by longPtr */
6885 longPtr = &m->parsSets[i][c*m->nParsIntsPerSite];
6886 allNucCode = codingNucCode = 0;
6887 for (nuc1=0; nuc1<4; nuc1++)
6888 for (nuc2=0; nuc2<4; nuc2++)
6889 for (nuc3=0; nuc3<4; nuc3++)
6891 if (mp->codon[allNucCode] != 21)
6893 if (IsBitSet(nuc1, &x1) == YES && IsBitSet(nuc2, &x2) == YES && IsBitSet(nuc3, &x3) == YES)
6894 SetBit(codingNucCode, longPtr);
6902 else if (!strcmp(mp->nucModel, "Protein") && (mp->dataType == DNA || mp->dataType == RNA))
6905 for (i=0; i<numLocalTaxa; i++)
6907 for (c=0, j=m->compMatrixStart; j<m->compMatrixStop; j+=m->nCharsPerSite, c++)
6909 /* fetch the original values x1, x2, and x3*/
6910 x1 = compMatrix[pos(i,j,compMatrixRowSize)];
6911 if (x1 == MISSING || x1 == GAP)
6913 x2 = compMatrix[pos(i,j+1,compMatrixRowSize)];
6914 if (x2 == MISSING || x2 == GAP)
6916 x3 = compMatrix[pos(i,j+2,compMatrixRowSize)];
6917 if (x3 == MISSING || x3 == GAP)
6920 /* squeeze them together in the new long string pointed to by longPtr */
6921 longPtr = &m->parsSets[i][c*m->nParsIntsPerSite]; /* m->nParsIntsPerSite should be 1 */
6923 for (nuc1=0; nuc1<4; nuc1++)
6924 for (nuc2=0; nuc2<4; nuc2++)
6925 for (nuc3=0; nuc3<4; nuc3++)
6927 if (mp->codon[allNucCode] != 21)
6929 if (IsBitSet(nuc1, &x1) == YES && IsBitSet(nuc2, &x2) == YES && IsBitSet(nuc3, &x3) == YES)
6930 SetBit(mp->codon[allNucCode]-1, longPtr);
6939 MrBayesPrint ("%s Unrecognized data format during bitset compression\n", spacer);
6948 /*------------------------------------------------
6950 | InitPrintParams: Set up arrays of print para-
6951 | meters and print tree parameters
6953 ------------------------------------------------*/
6954 int InitPrintParams (void)
6959 /* count number of model params to print */
6961 for (i=0; i<numParams; i++)
6964 if (p->printParam == YES &&
6965 p->paramType != P_TOPOLOGY &&
6966 p->paramType != P_BRLENS &&
6967 p->paramType != P_SPECIESTREE &&
6968 p->paramType != P_CPPEVENTS &&
6969 p->paramType != P_TK02BRANCHRATES &&
6970 p->paramType != P_IGRBRANCHRATES &&
6971 p->paramType != P_MIXEDBRCHRATES)
6975 /* count number of tree params to print */
6976 numPrintTreeParams = 0;
6977 for (i=0; i<numParams; i++)
6980 if (p->paramType == P_TOPOLOGY)
6982 /* always print parsimony topology (printParam == YES), otherwise */
6983 /* print topology only if brlens never requested (nPrintSubParams == 0)*/
6984 if (p->printParam == YES || p->nPrintSubParams == 0)
6985 numPrintTreeParams++;
6987 else if (p->paramType == P_BRLENS)
6989 /* print only if brlens (or events) requested for at least one partition */
6990 if (p->printParam == YES || p->nPrintSubParams > 0)
6991 numPrintTreeParams++;
6993 else if (p->paramType == P_SPECIESTREE)
6995 /* always print if printParam set to YES */
6996 if (p->printParam == YES)
6997 numPrintTreeParams++;
7001 /* allocate space */
7002 printParam = (Param **) SafeCalloc (numPrintParams + numPrintTreeParams + numTopologies, sizeof(Param *));
7003 topologyPrintIndex = (int *) SafeCalloc (numTopologies + numPrintTreeParams, sizeof(int));
7004 if (!printParam || !topologyPrintIndex)
7007 free (topologyPrintIndex);
7008 MrBayesPrint ("%s Could not allocate printParam vector in InitPrintParams\n", spacer);
7011 printTreeParam = printParam + numPrintParams;
7012 topologyParam = printTreeParam + numPrintTreeParams;
7013 printTreeTopologyIndex = topologyPrintIndex + numTopologies;
7014 memAllocs[ALLOC_PRINTPARAM] = YES;
7016 /* assign normal print params */
7017 for (i=j=0; i<numParams; i++)
7020 if (p->printParam == YES &&
7021 p->paramType != P_TOPOLOGY &&
7022 p->paramType != P_BRLENS &&
7023 p->paramType != P_SPECIESTREE &&
7024 p->paramType != P_CPPEVENTS &&
7025 p->paramType != P_TK02BRANCHRATES &&
7026 p->paramType != P_IGRBRANCHRATES &&
7027 p->paramType != P_MIXEDBRCHRATES)
7028 printParam[j++] = p;
7031 /* assign tree print params */
7032 for (i=j=k=0; i<numParams; i++)
7035 if (p->paramType == P_TOPOLOGY)
7037 /* always print parsimony topology (printParam == YES), otherwise */
7038 /* print topology only if brlens never requested (nPrintSubParams == 0)*/
7039 if (p->printParam == YES || p->nPrintSubParams == 0)
7040 numPrintTreeParams++;
7042 else if (p->paramType == P_BRLENS)
7044 /* print only if brlens (or events) requested for at least one partition */
7045 if (p->printParam == YES || p->nPrintSubParams > 0)
7046 printTreeParam[k++] = p;
7048 else if (p->paramType == P_SPECIESTREE)
7050 if (p->printParam == YES)
7051 printTreeParam[k++] = p;
7055 /* find topologies, topology file index, and printtree topology index */
7056 for (i=0; i<numPrintTreeParams; i++)
7057 printTreeTopologyIndex[i] = numTopologies;
7058 for (i=j=0; i<numParams; i++)
7061 if (p->paramType == P_SPECIESTREE)
7063 topologyParam[j] = p;
7064 for (k=0; k<numPrintTreeParams; k++)
7065 if (printTreeParam[k] == p)
7067 topologyPrintIndex[j] = k;
7068 printTreeTopologyIndex[k] = j;
7071 else if (p->paramType == P_TOPOLOGY)
7073 topologyParam[j] = p;
7074 for (k=0; k<numPrintTreeParams; k++)
7075 if (printTreeParam[k] == p)
7077 if (k<numPrintTreeParams)
7079 topologyPrintIndex[j] = k;
7080 printTreeTopologyIndex[k] = j;
7084 for (k=0; k<p->nSubParams; k++)
7086 for (k1=0; k1<numPrintTreeParams; k1++)
7087 if (printTreeParam[k1] == p->subParams[k])
7089 if (k1 < numPrintTreeParams)
7092 topologyPrintIndex[j] = k1;
7093 printTreeTopologyIndex[k1] = j;
7103 int IsPFNodeEmpty (PFNODE *p)
7107 for (i=0; i<chainParams.numRuns; i++)
7109 if (p->count[i] > 0)
7112 if (i == chainParams.numRuns)
7119 /* LargestNonemptyPFNode: recursive function to largest nonempty node in a subtree */
7120 PFNODE *LargestNonemptyPFNode (PFNODE *p, int *i, int j)
7128 q = LargestNonemptyPFNode (p->left, i, j);
7134 else if (IsPFNodeEmpty (p) == NO)
7141 return LargestNonemptyPFNode (p->right, i, j);
7146 /* ln prior ratio for clock trees */
7147 int LogClockTreePriorRatio (Param *param, int chain, MrBFlt *lnPriorRatio)
7149 MrBFlt oldLnPrior, newLnPrior, theta, N, growth, clockRate, sF, *sR, *eR, *fR;
7153 Tree *newTree, *oldTree;
7154 TreeNode *p, *q=NULL;
7157 (*lnPriorRatio) = 0.0;
7159 mp = &modelParams[param->relParts[0]];
7160 m = &modelSettings[param->relParts[0]];
7162 newTree = GetTree (m->brlens, chain, state[chain]);
7163 oldTree = GetTree (m->brlens, chain, state[chain] ^ 1);
7165 if (m->clockRate != NULL)
7166 clockRate = *GetParamVals(m->clockRate, chain, state[chain]);
7170 /* calculate prior ratio on brlens of clock tree */
7171 if (!strcmp(mp->clockPr,"Coalescence"))
7173 /* coalescence prior */
7174 /* first calculate theta as 4*N*mu, 3*N*mu or 2*N*mu */
7175 N = *(GetParamVals (m->popSize, chain, state[chain]));
7176 if (!strcmp(mp->ploidy, "Diploid"))
7177 theta = 4 * N * clockRate;
7178 else if (!strcmp(mp->ploidy, "Zlinked"))
7179 theta = 3 * N * clockRate;
7181 theta = 2 * N * clockRate;
7182 /* deal with growth */
7183 if (!strcmp(mp->growthPr, "Fixed"))
7184 growth = mp->growthFix;
7186 growth = *(GetParamVals (m->growthRate, chain, state[chain]));
7187 if (LnCoalescencePriorPr (oldTree, &oldLnPrior, theta, growth) == ERROR)
7189 MrBayesPrint ("%s Problem calculating prior for coalescence process\n", spacer);
7192 if (LnCoalescencePriorPr (newTree, &newLnPrior, theta, growth) == ERROR)
7194 MrBayesPrint ("%s Problem calculating prior for coalescence process\n", spacer);
7197 (*lnPriorRatio) = (newLnPrior - oldLnPrior);
7199 else if (!strcmp(mp->clockPr,"Birthdeath"))
7201 /* birth-death prior */
7202 sR = GetParamVals (m->speciationRates, chain, state[chain]);
7203 eR = GetParamVals (m->extinctionRates, chain, state[chain]);
7204 sS = mp->sampleStrat;
7205 sF = mp->sampleProb;
7206 if (LnBirthDeathPriorPr (oldTree, clockRate, &oldLnPrior, *sR, *eR, sS, sF) == ERROR)
7208 MrBayesPrint ("%s Problem calculating prior for birth-death process\n", spacer);
7211 if (LnBirthDeathPriorPr (newTree, clockRate, &newLnPrior, *sR, *eR, sS, sF) == ERROR)
7213 MrBayesPrint ("%s Problem calculating prior for birth-death process\n", spacer);
7216 (*lnPriorRatio) = (newLnPrior - oldLnPrior);
7218 else if (!strcmp(mp->clockPr,"Fossilization"))
7220 /* fossilized birth-death prior */
7221 sR = GetParamVals (m->speciationRates, chain, state[chain]);
7222 eR = GetParamVals (m->extinctionRates, chain, state[chain]);
7223 sF = mp->sampleProb;
7224 fR = GetParamVals (m->fossilizationRates, chain, state[chain]);
7225 sS = mp->sampleStrat;
7226 if (LnFossilizationPriorPr (oldTree, clockRate, &oldLnPrior, sR, eR, sF, fR, sS) == ERROR)
7228 MrBayesPrint ("%s Problem calculating prior for fossilized birth-death process\n", spacer);
7231 if (LnFossilizationPriorPr (newTree, clockRate, &newLnPrior, sR, eR, sF, fR, sS) == ERROR)
7233 MrBayesPrint ("%s Problem calculating prior for fossilized birth-death process\n", spacer);
7236 (*lnPriorRatio) = (newLnPrior - oldLnPrior);
7238 else if (!strcmp(mp->clockPr,"Uniform"))
7240 oldLnPrior = LnUniformPriorPr(oldTree, clockRate);
7241 newLnPrior = LnUniformPriorPr(newTree, clockRate);
7242 (*lnPriorRatio) = (newLnPrior - oldLnPrior);
7244 else if (!strcmp(mp->clockPr,"Speciestreecoalescence"))
7246 // Defer this calculation to the BEST code
7249 assert (*lnPriorRatio > NEG_INFINITY);
7251 /* take care of calibrations */
7252 if (newTree->isCalibrated == YES)
7254 for (i=0; i<newTree->nNodes-1; i++)
7256 p = newTree->allDownPass[i];
7257 if (p->isDated == NO)
7259 for (j=0; j<oldTree->nNodes-1; j++)
7261 q = oldTree->allDownPass[j];
7262 if (p->lockID == q->lockID)
7265 assert (j != oldTree->nNodes-1);
7266 if (p->isDated == YES && p->calibration->prior != fixed)
7268 (*lnPriorRatio) += p->calibration->LnPriorRatio(p->age, q->age, p->calibration->priorParams);
7277 /*-----------------------------------------------------------------
7279 | LogLike: calculate the log likelihood of the new state of the chain
7281 -----------------------------------------------------------------*/
7282 MrBFlt LogLike (int chain)
7286 MrBFlt chainLnLike, lnL;
7288 /* initialize chain cond like */
7291 if (chainParams.runWithData == NO)
7292 return (chainLnLike);
7294 # if defined (DEBUG_RUN_WITHOUT_DATA)
7295 return (chainLnLike);
7298 # if defined (THREADS_ENABLED)
7299 if (tryToUseThreads && ScheduleLogLikeForAllDivisions())
7301 /* Launch all divisions that require updating simultaneously */
7302 chainLnLike = LaunchLogLikeForAllDivisionsInParallel(chain);
7306 /* Launch divisions in series */
7309 /* Cycle through divisions and recalculate tis and cond likes as necessary. */
7310 /* Code below does not try to avoid recalculating ti probs for divisions */
7311 /* that could share ti probs with other divisions. */
7312 for (d=0; d<numCurrentDivisions; d++)
7315 # if defined (BEST_MPI_ENABLED)
7316 if (isDivisionActive[d] == NO)
7319 m = &modelSettings[d];
7320 if (m->upDateCl == YES)
7322 /* Work has been delegated to a separate function so we can wrap */
7323 /* a thread around it */
7324 LaunchLogLikeForDivision(chain, d, &(m->lnLike[2 * chain + state[chain]]));
7326 if (abortMove == YES)
7327 return MRBFLT_NEG_MAX;
7328 chainLnLike += m->lnLike[2*chain + state[chain]];
7331 # if defined (THREADS_ENABLED)
7335 /* unmark all divisions */
7336 if (chainHasAdgamma == YES)
7338 for (d=0; d<numCurrentDivisions; d++)
7340 m = &modelSettings[d];
7344 /* update HMM likelihoods if appropriate */
7345 for (d=0; d<numCurrentDivisions; d++)
7347 # if defined (BEST_MPI_ENABLED)
7348 if (isDivisionActive[d] == NO)
7351 m = &modelSettings[d];
7353 if (m->upDateCl == YES && m->correlation != NULL && m->mark != YES)
7356 CalcLikeAdgamma(d, m->correlation, chain, &lnL);
7358 /* store the value for the cases where the HMM is not touched */
7359 m->lnLike[2*chain + state[chain]] = lnL;
7361 /* add it to chainLnLike - it was not added above since the division */
7362 /* lnL was set to zero after the update call to Likelihood_Adgamma */
7365 /* set mark for other divisions in the HMM
7366 (i.e., those with the same correlation parameter AND the same shape parameter) */
7367 for (i=0; i<m->correlation->nRelParts; i++)
7369 if (modelSettings[m->correlation->relParts[i]].shape == modelSettings[d].shape)
7371 modelSettings[m->correlation->relParts[i]].mark = YES;
7378 return (chainLnLike);
7382 MrBFlt LogOmegaPrior (MrBFlt w1, MrBFlt w2, MrBFlt w3)
7385 /* This function returns the log prior probability of
7386 the ratio on three omegas. Here, we have three
7387 nonsynonymous/synonymous rate ratios, denoted w1, w2,
7388 and w3. They have the property that w1 < w2 < w3.
7389 Remember that w1 = dN1/dS, w2 = dN2/dS, and
7390 w3 = dN3/dS. We assume that dN1, dN2, dN3, and dS
7391 are all independent draws from the same exponential
7392 distribution, and that dN1, dN2, and dN3 are the
7393 order statistics. The w1, w2, and w3, then, are
7394 all scaled to the same dS r.v. */
7398 lnProb = log(36.0) - 4.0 * log(1.0 + w1 + w2 + w3);
7404 /* ------------------------------------------------------------------------------------------------------------- */
7405 /* Joint distribution of branch lengths t under gamma-Dirichlet prior: */
7406 /* (Zhang et al. 2012, Eq. 4; Rannala et al. 2012, Eq. 36): */
7407 /* ln[f(t|aT,bT,a,c)] = (aT - a*s - a*c*(s-3)) * ln(T) - bT * T + (a-1) * sum[ln(t_j)] + (a*c-1) * sum[ln(t_k)] */
7408 /* + aT * ln(bT) - lnG(aT) - lnB(a,c) */
7410 /* Joint distribution of branch lengths t under invgamma-Dirichlet prior: */
7411 /* (Zhang et al. 2012, Eq. 6; Rannala et al. 2012, Eq. 39): */
7412 /* ln[f(t|aT,bT,a,c)] = (-aT - a*s - a*c*(s-3)) * ln(T) - bT / T + (a-1) * sum[ln(t_j)] + (a*c-1) * sum[ln(t_k)] */
7413 /* + aT * ln(bT) - lnG(aT) - lnB(a,c) */
7414 /* also see DoCitations() */
7415 /* ------------------------------------------------------------------------------------------------------------- */
7417 /* external (tip): 1, internal: 0 */
7418 #define IsTip(Node) (Node->index < numTaxa || (Node->anc)->index < numTaxa)
7420 MrBFlt LogDirPrior (Tree *t, ModelParams *mp, int PV)
7422 /* ln prior prob. under Dirichlet priors and twoExp prior
7425 int i, nb[2] = {0,0};
7426 MrBFlt lnprior = 0.0, tb[2] = {0,0}, treeL = 0.0;
7427 MrBFlt aT, bT, a, c;
7430 /* Not safe, should define Marcos. YES or NO should never be defined to 2 or 3 or 4! */
7431 /* PV is 2 or 3: Dirichlet priors */
7432 if (PV == 2 || PV == 3)
7434 /* partially for calculating lnPriorRatio, full part is in LogPrior() */
7435 aT = mp->brlensDir[0];
7436 bT = mp->brlensDir[1];
7437 a = mp->brlensDir[2];
7438 c = mp->brlensDir[3];
7440 for (i = 0; i < t->nNodes; i++)
7442 p = t->allDownPass[i];
7447 tb[IsTip(p)] += log(p->length);
7450 lnprior += (a-1)*tb[1] + (a*c -1)*tb[0];
7452 lnprior += (aT - a*nb[1] - a*c*nb[0]) * log(treeL) - bT*treeL;
7454 lnprior += (-aT - a*nb[1] - a*c*nb[0]) * log(treeL) - bT/treeL;
7456 /* or 4: twoExp prior */
7459 for (i = 0; i < t->nNodes; i++) {
7460 p = t->allDownPass[i];
7464 tb[IsTip(p)] += p->length;
7467 for (i = 0; i < 2; i++)
7468 lnprior += nb[i] * log(mp->brlens2Exp[i]) - tb[i] * (mp->brlens2Exp[i]);
7475 MrBFlt LogPrior (int chain)
7477 int i, j, c, n, nStates, *nEvents, sumEvents, *ist, nRates, nParts[6];
7479 MrBFlt *st, *sst, lnPrior, sum, x, clockRate, theta, popSize, growth, *alphaDir, newProp[190],
7480 sF, *sR, *eR, *fR, freq, pInvar, lambda, sigma, nu, igrvar, **rateMultiplier;
7487 TreeNode *branch, *q;
7489 /* In the stepping-stone method, constants that appear in prior probability density functions must be fully specified.
7490 It is not necessary for Bayesian MCMC analyses because such constants cancel out. */
7493 for (n=0; n<numParams; n++)
7496 # if defined (MPI_BEST_ENABLED)
7497 /* We skip all parameters that are not handled on this processor. The scheme used here
7498 requires that parameters either be unique to one partition (processor) or that they
7499 are shared across all partitions and that the first processor has all the relevant
7500 information about that parameter. */
7501 if (isDivisionActive[p->relParts[0]] == NO)
7505 st = GetParamVals (p, chain, state[chain]);
7506 sst = GetParamSubVals (p, chain, state[chain]);
7507 mp = &modelParams[p->relParts[0]];
7508 m = &modelSettings[p->relParts[0]];
7510 if (p->paramType == P_TRATIO)
7512 /* tratio parameter */
7513 if (p->paramId == TRATIO_DIR)
7515 alphaDir = mp->tRatioDir;
7516 /* we convert here from the ratio parameterization used in the parameter
7517 struct to the simplex parameterization used for the prior */
7518 newProp[0] = st[0] / (st[0] + 1.0);
7519 newProp[1] = (1.0 - newProp[0]);
7520 x = LnGamma(alphaDir[0]+alphaDir[1]) - LnGamma(alphaDir[0]) - LnGamma(alphaDir[1]);
7522 x += (alphaDir[i]-1.0)*log(newProp[i]);
7526 else if (p->paramType == P_REVMAT)
7528 /* revmat parameter */
7529 if (p->paramId == REVMAT_DIR)
7531 if (p->nValues == 6)
7532 alphaDir = mp->revMatDir;
7533 else /* if (p->nValues == 190) */
7534 alphaDir = mp->aaRevMatDir;
7536 for (i=0; i<p->nValues; i++)
7539 for (i=0; i<p->nValues; i++)
7540 x -= LnGamma(alphaDir[i]);
7541 for (i=0; i<p->nValues; i++)
7542 x += (alphaDir[i] - 1.0) * log(st[i]);
7545 else if (p->paramId == REVMAT_MIX)
7547 assert (p->nValues == 6);
7548 alphaDir = &mp->revMatSymDir;
7549 ist = GetParamIntVals(p, chain, state[chain]); /* the growth fxn */
7550 nRates = GetKFromGrowthFxn(ist);
7551 /* get the actual rate proportions of the current groups */
7552 for (i=0; i<nRates; i++)
7560 newProp[ist[i]] += st[i];
7562 /* now we calculate probability as usual, with alpha
7563 parameter multiplied by number of parts */
7564 x = LnGamma(6.0 * alphaDir[0]);
7565 for (i=0; i<nRates; i++)
7566 x -= LnGamma(nParts[i] * alphaDir[0]);
7567 for (i=0; i<nRates; i++)
7568 x += (nParts[i] * alphaDir[0] - 1.0) * log(newProp[i]);
7569 /* finally take model probability into account */
7570 x += log (1.0 / 203);
7575 /* fixed or empirical */
7578 else if (p->paramType == P_OMEGA)
7580 /* account for prior on omega proportion if 1 omega category */
7581 if (p->paramId == OMEGA_DIR)
7583 alphaDir = mp->omegaDir;
7584 /* convert from ratio parameterization to simplex representation */
7585 newProp[0] = st[0] / (st[0] + 1.0);
7586 newProp[1] = 1.0 - newProp[0];
7587 x = LnGamma(alphaDir[0]+alphaDir[1]) - LnGamma(alphaDir[0]) - LnGamma(alphaDir[1]);
7589 x += (alphaDir[i]-1.0)*log(newProp[i]);
7592 /* account for stationary state frequencies of M3 and ny98 omega categories */
7593 if (p->paramId == OMEGA_BUD || p->paramId == OMEGA_BED ||
7594 p->paramId == OMEGA_BFD || p->paramId == OMEGA_FUD ||
7595 p->paramId == OMEGA_FED || p->paramId == OMEGA_FFD ||
7596 p->paramId == OMEGA_ED || p->paramId == OMEGA_FD)
7598 alphaDir = mp->codonCatDir;
7601 x += (alphaDir[i]-1.0)*log(sst[i]);
7604 /* account for beta prior on omeganeg in NY98 */
7605 if (p->paramId == OMEGA_BUD || p->paramId == OMEGA_BUF ||
7606 p->paramId == OMEGA_BED || p->paramId == OMEGA_BEF ||
7607 p->paramId == OMEGA_BFD || p->paramId == OMEGA_BFF)
7609 alphaDir = mp->ny98omega1Beta;
7610 newProp[0] = st[0] / (st[0] + 1.0);
7611 newProp[1] = 1.0 - newProp[0];
7614 x += (alphaDir[i]-1.0)*log(newProp[i]);
7617 /* account for omegapos in NY98 with uniform prior prob */
7618 if (p->paramId == OMEGA_BUD || p->paramId == OMEGA_BUF ||
7619 p->paramId == OMEGA_FUD || p->paramId == OMEGA_FUF)
7621 lnPrior += log(1.0) - log(mp->ny98omega3Uni[1] - mp->ny98omega3Uni[0]);
7623 /* account for omegapos in NY98 with exponential prior prob */
7624 if (p->paramId == OMEGA_BED || p->paramId == OMEGA_BEF ||
7625 p->paramId == OMEGA_FED || p->paramId == OMEGA_FEF)
7627 lnPrior += (log(mp->ny98omega3Exp) - mp->ny98omega3Exp * st[2]);
7629 /* account for omegas in M3, which can only be exponential; if fixed, ln prior prob is 0 */
7630 if (p->paramId == OMEGA_EF || p->paramId == OMEGA_ED)
7632 lnPrior += LogOmegaPrior (st[0], st[1], st[2]);
7635 else if (p->paramType == P_PI)
7637 /* state frequencies parameter */
7638 if (p->paramId == PI_DIR)
7640 nStates = p->nSubValues;
7642 for (i=0; i<nStates; i++)
7645 for (i=0; i<nStates; i++)
7646 x -= LnGamma(st[i]);
7647 for (i=0; i<nStates; i++)
7648 x += (st[i] - 1.0)*log(sst[i]);
7651 else if (p->paramId == SYMPI_EXP || p->paramId == SYMPI_EXP_MS)
7653 lnPrior += - mp->symBetaExp * st[0] + log(mp->symBetaExp);
7655 else if (p->paramId == SYMPI_UNI || p->paramId == SYMPI_UNI_MS)
7657 lnPrior += log(1.0) - log(mp->symBetaUni[1] - mp->symBetaUni[0]);
7659 if (p->paramId == SYMPI_EXP_MS || p->paramId == SYMPI_UNI_MS || p->paramId == SYMPI_FIX_MS)
7661 sst = GetParamStdStateFreqs(p, chain, state[chain]);
7662 sst += 2*m->numBetaCats;
7663 for (i=0; i<p->nSympi; i++)
7665 nStates = p->sympinStates[i];
7666 x = LnGamma(nStates*st[0]) - nStates*LnGamma(st[0]);
7667 for (j=0; j<nStates; j++)
7668 x += (st[0] - 1.0)*log(sst[j]);
7674 else if (p->paramType == P_SHAPE)
7676 /* gamma/lnorm shape parameter */
7677 if (p->paramId == SHAPE_UNI)
7679 lnPrior += log(1.0) - log(mp->shapeUni[1] - mp->shapeUni[0]);
7681 else if (p->paramId == SHAPE_EXP)
7683 lnPrior += log(mp->shapeExp) - mp->shapeExp * st[0];
7685 for (i=0; i<p->nRelParts; i++)
7687 m = &modelSettings[p->relParts[i]];
7688 if (m->gibbsGamma == YES)
7690 if (m->pInvar == NULL)
7691 lnPrior += log(1.0/m->numGammaCats) * m->numUncompressedChars;
7694 rateCat = m->tiIndex + chain * m->numChars;
7695 pInvar = *GetParamVals (m->pInvar, chain, state[chain]);
7696 nSitesOfPat = numSitesOfPat + m->compCharStart;
7697 freq = (1.0 - pInvar)/m->numGammaCats;
7698 for (c=0; c<m->numChars; c++)
7700 if (rateCat[c] < m->numGammaCats)
7701 lnPrior += log(freq) * nSitesOfPat[c];
7703 lnPrior += log(pInvar) * nSitesOfPat[c];
7709 else if (p->paramType == P_PINVAR)
7711 /* proportion of invariable sites parameter */
7712 lnPrior += log(1.0) - log(mp->pInvarUni[1] - mp->pInvarUni[0]);
7714 else if (p->paramType == P_CORREL)
7716 /* adGamma model parameter */
7717 lnPrior += log(1.0) - log(mp->corrUni[1] - mp->corrUni[0]);
7719 else if (p->paramType == P_SWITCH)
7721 /* switching rate parameter of covarion model */
7722 if (p->paramId == SWITCH_UNI)
7724 lnPrior += log(1.0) - log(mp->covswitchUni[1] - mp->covswitchUni[0]);
7726 else if (p->paramId == SWITCH_EXP)
7728 lnPrior += log(mp->covswitchExp) - mp->covswitchExp * st[0];
7731 else if (p->paramType == P_RATEMULT && p->nValues > 1)
7733 nStates = p->nValues;
7735 for (i=0; i<nStates; i++)
7736 sum += sst[i+nStates];
7738 for (i=0; i<nStates; i++)
7739 x -= LnGamma(sst[i+nStates]);
7740 for (i=0; i<nStates; i++)
7741 x += (sst[i+nStates] - 1.0) * log(st[i]);
7742 sum = 0.0; // the constant
7743 for (i=0; i<nStates; i++)
7745 for (i=0; i<nStates; i++) {
7747 x += (sst[i+nStates]) * log(sst[i]/sum);
7749 x += (sst[i+nStates] - 1.0) * log(sst[i]/sum);
7753 else if (p->paramType == P_GENETREERATE && p->nValues > 1)
7755 nStates = p->nValues;
7757 for (i=0; i<nStates; i++)
7758 sum += sst[i+nStates];
7760 for (i=0; i<nStates; i++)
7761 x -= LnGamma(sst[i+nStates]);
7762 for (i=0; i<nStates; i++)
7763 x += (sst[i+nStates] - 1.0) * log(st[i]);
7764 sum = 0.0; // the constant
7765 for (i=0; i<nStates; i++)
7767 for (i=0; i<nStates; i++) {
7769 x += (sst[i+nStates]) * log(sst[i]/sum);
7771 x += (sst[i+nStates] - 1.0) * log(sst[i]/sum);
7775 else if (p->paramType == P_TOPOLOGY)
7777 // Note that a topology can have several unlinked branch length subparameters but only
7778 // one set of clock branch lengths. To find all the branch length subparameters of a
7779 // topology, cycle through the p->subParams, which will contain at least one branch length
7781 t = GetTree (p, chain, state[chain]);
7782 if (t->isClock == YES)
7783 continue; /* prior probability taken care of in the brlens parameter */
7786 for (i=0; i<t->nNodes-1; i++)
7788 branch = t->allDownPass[i];
7789 if (branch->left == NULL)
7792 branch->x = branch->left->x + branch->right->x;
7793 if (branch->isLocked == YES || branch->anc->anc == NULL)
7795 for (j = 2*branch->x - 3; j>=1; j-=2)
7797 lnPrior -= log ((MrBFlt)j);
7805 for (j = 2*(t->nNodes-t->nIntNodes)-5; j>=1; j-=2)
7807 lnPrior -= log ((MrBFlt)j);
7811 else if (p->paramType == P_BRLENS)
7813 /* branch lengths */
7814 t = GetTree (p, chain, state[chain]);
7815 if (t->isClock == YES)
7817 if (p->paramId == BRLENS_CLOCK_UNI)
7819 /* uniformly distributed branch lengths */
7820 clockRate = *(GetParamVals (m->clockRate, chain, state[chain]));
7821 lnPrior += LnUniformPriorPr(t, clockRate);
7823 else if (p->paramId == BRLENS_CLOCK_COAL)
7825 /* coalescence prior */
7826 popSize = *(GetParamVals (m->popSize, chain, state[chain]));
7827 clockRate = *(GetParamVals (m->clockRate, chain, state[chain]));
7828 if (strcmp(mp->ploidy, "Diploid") == 0)
7829 theta = 4.0 * popSize * clockRate;
7830 else if (strcmp(mp->ploidy, "Zlinked") == 0)
7831 theta = 3.0 * popSize * clockRate;
7833 theta = 2.0 * popSize * clockRate;
7834 if (!strcmp(mp->growthPr, "Fixed"))
7835 growth = mp->growthFix;
7837 growth = *(GetParamVals (m->growthRate, chain, state[chain]));
7838 if (LnCoalescencePriorPr (t, &x, theta, growth) == ERROR)
7840 MrBayesPrint ("%s Problem calculating prior for coalescence process\n", spacer);
7844 else if (p->paramId == BRLENS_CLOCK_BD)
7846 /* birth-death prior */
7847 sR = GetParamVals (m->speciationRates, chain, state[chain]);
7848 eR = GetParamVals (m->extinctionRates, chain, state[chain]);
7849 sS = mp->sampleStrat;
7850 sF = mp->sampleProb;
7851 if (m->clockRate != NULL)
7852 clockRate = *(GetParamVals (m->clockRate, chain, state[chain]));
7855 if (LnBirthDeathPriorPr (t, clockRate, &x, *sR, *eR, sS, sF) == ERROR)
7857 MrBayesPrint ("%s Problem calculating prior for birth-death process\n", spacer);
7861 else if (p->paramId == BRLENS_CLOCK_FOSSIL)
7863 /* fossilized birth-death prior */
7864 sR = GetParamVals (m->speciationRates, chain, state[chain]);
7865 eR = GetParamVals (m->extinctionRates, chain, state[chain]);
7866 sF = mp->sampleProb;
7867 fR = GetParamVals (m->fossilizationRates, chain, state[chain]);
7868 sS = mp->sampleStrat;
7869 if (m->clockRate != NULL)
7870 clockRate = *(GetParamVals (m->clockRate, chain, state[chain]));
7873 if (LnFossilizationPriorPr (t, clockRate, &x, sR, eR, sF, fR, sS) == ERROR)
7875 MrBayesPrint ("%s Problem calculating prior for fossilized birth-death process\n", spacer);
7879 else if (p->paramId == BRLENS_CLOCK_SPCOAL)
7881 /* delegate this calculation to the P_SPECIESTREE parameter */
7883 if (t->isCalibrated == YES)
7885 /* take care of calibrations */
7886 for (i=0; i<t->nNodes-1; i++)
7888 q = t->allDownPass[i];
7889 if (q->isDated == YES && q->calibration->prior != fixed)
7891 lnPrior += q->calibration->LnPriorProb(q->age, q->calibration->priorParams);
7898 if (p->paramId == BRLENS_UNI)
7900 for (i=0; i<t->nNodes; i++)
7902 branch = t->allDownPass[i];
7903 if (branch->anc != NULL)
7904 lnPrior += log(1.0) - log(mp->brlensUni[1] - BRLENS_MIN);
7907 else if (p->paramId == BRLENS_EXP)
7909 for (i=0; i<t->nNodes; i++)
7911 branch = t->allDownPass[i];
7912 if (branch->anc != NULL)
7913 lnPrior += log(mp->brlensExp) - mp->brlensExp * branch->length;
7916 /* Dirichlet priors */
7917 else if (p->paramId == BRLENS_GamDir)
7919 lnPrior += LogDirPrior(t, mp, 2);
7920 lnPrior += (mp->brlensDir[0]) * log(mp->brlensDir[1]) - LnGamma(mp->brlensDir[0])
7921 + LnGamma (mp->brlensDir[2] * numTaxa + mp->brlensDir[2] * mp->brlensDir[3] * (numTaxa-3))
7922 - numTaxa * LnGamma(mp->brlensDir[2]) - (numTaxa-3) * LnGamma(mp->brlensDir[2] * mp->brlensDir[3]);
7924 else if (p->paramId == BRLENS_iGmDir)
7926 lnPrior += LogDirPrior(t, mp, 3);
7927 lnPrior += (mp->brlensDir[0]) * log(mp->brlensDir[1]) - LnGamma(mp->brlensDir[0])
7928 + LnGamma (mp->brlensDir[2] * numTaxa + mp->brlensDir[2] * mp->brlensDir[3] * (numTaxa-3))
7929 - numTaxa * LnGamma(mp->brlensDir[2]) - (numTaxa-3) * LnGamma(mp->brlensDir[2] * mp->brlensDir[3]);
7932 else if (p->paramId == BRLENS_twoExp)
7933 lnPrior += LogDirPrior(t, mp, 4);
7936 else if (p->paramType == P_SPECRATE)
7938 /* speciation rate parameter */
7939 if (p->paramId == SPECRATE_UNI)
7941 for (i=0; i<p->nValues; i++)
7942 lnPrior += log(1.0) - log(mp->speciationUni[1] - mp->speciationUni[0]);
7944 else if (p->paramId == SPECRATE_EXP)
7946 for (i=0; i<p->nValues; i++)
7947 lnPrior += log(mp->speciationExp) - mp->speciationExp * st[i];
7950 else if (p->paramType == P_EXTRATE)
7952 /* extinction rate parameter */
7953 if (p->paramId == EXTRATE_BETA)
7955 for (i=0; i<p->nValues; i++)
7957 alphaDir = mp->extinctionBeta;
7959 newProp[1] = (1.0 - newProp[0]);
7960 lnPrior += LnGamma(alphaDir[0]+alphaDir[1]) - LnGamma(alphaDir[0]) - LnGamma(alphaDir[1]);
7961 lnPrior += (alphaDir[0]-1.0)*log(newProp[0]) + (alphaDir[1]-1.0)*log(newProp[1]);
7965 else if (p->paramType == P_FOSLRATE)
7967 /* fossilization rate parameter */
7968 if (p->paramId == FOSLRATE_BETA)
7970 for (i=0; i<p->nValues; i++)
7972 alphaDir = mp->fossilizationBeta;
7974 newProp[1] = (1.0 - newProp[0]);
7975 // if (newProp[0] > 0.0) /* to avoid psi=0 in [0, x_cut] under diversified sampling */
7976 lnPrior += LnGamma(alphaDir[0]+alphaDir[1]) - LnGamma(alphaDir[0]) - LnGamma(alphaDir[1]);
7977 lnPrior += (alphaDir[0]-1.0)*log(newProp[0]) + (alphaDir[1]-1.0)*log(newProp[1]);
7981 else if (p->paramType == P_POPSIZE)
7983 /* neutral coalescence population size parameter; one value, or one value per branch of species tree */
7984 for (i=0; i<p->nValues; i++)
7986 lnPrior += p->LnPriorProb(st[i], p->priorParams);
7989 else if (p->paramType == P_AAMODEL)
7991 lnPrior += sst[(int)st[0]];
7993 else if (p->paramType == P_BRCORR)
7997 else if (p->paramType == P_BRSIGMA)
8001 else if (p->paramType == P_GROWTH)
8003 /* population growth parameter */
8004 if (p->paramId == GROWTH_UNI)
8006 lnPrior += log(1.0) - log(mp->growthUni[1] - mp->growthUni[0]);
8008 else if (p->paramId == GROWTH_EXP)
8010 lnPrior += log(mp->growthExp) - mp->growthExp * st[0];
8013 else if (p->paramType == P_CPPRATE)
8015 /* rate (lambda) of comp poisson process of relaxed clock */
8016 if (p->paramId == CPPRATE_EXP)
8018 lnPrior += log (mp->cppRateExp) - mp->cppRateExp * st[0];
8021 else if (p->paramType == P_CPPMULTDEV)
8023 /* standard deviation (log) of lognormal distribution of rate multipliers for cpp relaxed clock */
8024 /* only fixed value allowed currently */
8026 else if (p->paramType == P_CPPEVENTS)
8028 /* events of CPP relaxed clock process */
8029 lambda = *GetParamVals (m->cppRate, chain, state[chain]);
8030 sigma = *GetParamVals (m->cppMultDev, chain, state[chain]);
8031 nEvents = p->nEvents[2*chain+state[chain]];
8032 rateMultiplier = p->rateMult[2*chain+state[chain]];
8035 for (i=0; i<2*numLocalTaxa-2; i++)
8036 sumEvents += nEvents[i];
8037 t = GetTree (p, chain, state[chain]);
8038 lnPrior += - lambda * TreeLength (p, chain) + (sumEvents * log (lambda));
8039 /* rate multipliers */
8040 for (i=0; i<2*numLocalTaxa-2; i++)
8042 for (j=0; j<nEvents[i]; j++)
8043 lnPrior += LnProbLogNormal (0.0, sigma, rateMultiplier[i][j]);
8045 for (i=0; i<t->nNodes-2; i++)
8047 branch = t->allDownPass[i];
8048 assert (fabs(branch->length - (branch->anc->nodeDepth - branch->nodeDepth)) < 0.000001);
8051 else if (p->paramType == P_TK02VAR)
8053 /* variance of rates (nu) in Thorne-Kishino model */
8054 if (p->paramId == TK02VAR_EXP)
8056 lnPrior += log (mp->tk02varExp) - mp->tk02varExp * st[0];
8058 else if (p->paramId == TK02VAR_UNI)
8060 lnPrior += log(1.0) - log (mp->tk02varUni[1] - mp->tk02varUni[0]);
8063 else if (p->paramType == P_TK02BRANCHRATES || (p->paramType == P_MIXEDBRCHRATES && *GetParamIntVals(p, chain, state[chain]) == RCL_TK02))
8065 /* branch rates of Thorne-Kishino model */
8066 t = GetTree (p, chain, state[chain]);
8067 if (p->paramType == P_TK02BRANCHRATES)
8068 nu = *GetParamVals (m->tk02var, chain, state[chain]);
8070 nu = *GetParamVals (m->mixedvar, chain, state[chain]);
8071 for (i=0; i<t->nNodes-2; i++)
8073 branch = t->allDownPass[i];
8074 if (branch->length > 0.0) // not ancestral fossil
8075 lnPrior += LnProbTK02LogNormal (st[branch->anc->index], nu*branch->length, st[branch->index]);
8078 else if (p->paramType == P_IGRVAR)
8080 /* variance of rates in independent gamma rates model */
8081 if (p->paramId == IGRVAR_EXP)
8083 lnPrior += log (mp->igrvarExp) - mp->igrvarExp * st[0];
8085 else if (p->paramId == IGRVAR_UNI)
8087 lnPrior += log(1.0) - log (mp->igrvarUni[1] - mp->igrvarUni[0]);
8090 else if (p->paramType == P_IGRBRANCHRATES || (p->paramType == P_MIXEDBRCHRATES && *GetParamIntVals(p, chain, state[chain]) == RCL_IGR))
8092 /* branch rates of independent branch rate model */
8093 t = GetTree (p, chain, state[chain]);
8094 if (p->paramType == P_IGRBRANCHRATES)
8095 igrvar = *GetParamVals (m->igrvar, chain, state[chain]);
8097 igrvar = *GetParamVals (m->mixedvar, chain, state[chain]);
8098 for (i=0; i<t->nNodes-2; i++)
8100 branch = t->allDownPass[i];
8101 if (branch->length > 0.0) // not ancestral fossil
8102 lnPrior += LnProbGamma (branch->length/igrvar, branch->length/igrvar, st[branch->index]);
8103 assert (fabs(sst[branch->index] - branch->length * st[branch->index]) < BRLENS_MIN);
8104 assert (fabs(branch->length - (branch->anc->nodeDepth - branch->nodeDepth)) < BRLENS_MIN);
8107 else if (p->paramType == P_MIXEDVAR)
8109 /* hyper prior of rates in mixed rel clock model */
8110 if (p->paramId == MIXEDVAR_EXP)
8112 lnPrior += log (mp->mixedvarExp) - mp->mixedvarExp * st[0];
8114 else if (p->paramId == MIXEDVAR_UNI)
8116 lnPrior += log(1.0) - log (mp->mixedvarUni[1] - mp->mixedvarUni[0]);
8119 else if (p->paramType == P_CLOCKRATE)
8121 /* base rate of molecular clock */
8122 lnPrior += p->LnPriorProb(st[0], p->priorParams);
8124 else if (p->paramType == P_SPECIESTREE)
8126 /* calculate prior */
8127 lnPrior += LnSpeciesTreeProb(chain);
8130 assert (lnPrior == lnPrior);
8132 # if defined (BEST_MPI_ENABLED)
8133 /* Assemble prior probabilities across processors */
8134 myLnPrior = lnPrior;
8135 MPI_AllReduce (&myLnPrior, &lnPrior, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);
8142 int LnBirthDeathPriorPr (Tree *t, MrBFlt clockRate, MrBFlt *prob, MrBFlt sR, MrBFlt eR, char *sS, MrBFlt sF)
8144 if (!strcmp(sS, "Random"))
8146 return LnBirthDeathPriorPrRandom (t, clockRate, prob, sR, eR, sF);
8148 else if (!strcmp(sS, "Diversity"))
8150 return LnBirthDeathPriorPrDiversity (t, clockRate, prob, sR, eR, sF);
8152 else if (!strcmp(sS, "Cluster"))
8154 return LnBirthDeathPriorPrCluster (t, clockRate, prob, sR, eR, sF);
8158 MrBayesPrint ("%s ERROR: Sampling strategy for birth-death process not implemented\n", spacer);
8164 /*---------------------------------------------------------------------------------
8166 | LnBirthDeathPriorPrRandom
8168 | We assume a rooted tree that satisfies the molecular clock constraint. The
8169 | tree is labelled as follows:
8186 | \/ t_1 (age of most recent common ancestor)
8189 | This function calculates the probability of such a tree under the neutral
8190 | birth death prior with constant birth and death rates, conditioned on
8191 | a particular time of the first split, t_1, and a particular number of
8192 | species, n. We assume rho-sampling, that is, a constant sampling pro-
8193 | bability rho, which is known, across tips of the tree. Variables:
8195 | T: the unlabeled oriented tree, which is equivalent to a set of unordered
8196 | speciation times from a point process
8197 | tau: the labeled unoriented tree
8198 | b: birth (speciation) rate
8199 | d: death (extintion) rate
8200 | f: sampling fraction
8201 | n: number of species in the sampled tree
8204 | Tanja Stadler (2009) On incomplete sampling under birth-death models and
8205 | connections to the sampling-based coalescent. Journal of Theoretical Biology
8208 | We use f(T|n), which is derived from f(T|n,t_or) using Stadler's approach,
8209 | in which the time of origin of the tree is associated with a uniform prior
8210 | and integrated out of the density. We then have:
8212 | We have the following distribution for ordered bifurcation times (cf.
8213 | equation 5 in Stadler, 2009, simplified here using the p0 and p1 functions):
8217 | f(T|n) = --------------- * prod (b * p1(t_i))
8221 | where t_1 = time of most recent common ancestor
8222 | p0(t) = prob. of no descendants surviving and being sampled after time t (see LnP0 function below)
8223 | p1(t) = prob. of one descendant surviving and being sampled after time t (see LnP1 function below)
8225 | To get the distribution on oriented trees, this density needs to be divided by the
8226 | number of ways of ordering n-1 bifurcation times, (n-1)!, since each way of ordering
8227 | the bifurcation times corresponds to a distinct oriented tree. The result is the following
8228 | density on oritented trees:
8231 | f(T|n) = --------------- * prod (b * p1(t_i))
8235 | To translate this to a density on distinct labeled trees, the density needs to be multiplied by
8238 | For the critical process where the speciation and extinction rates are equal, we obtain the
8239 | following result in the limit (cf. equation 6 in Stadler (2009)):
8242 | f(T|n) = -------------- * prod -----------------
8243 | (1 + f*b*t_1) i=1 (1 + f*b*t_i)^2
8245 ---------------------------------------------------------------------------------*/
8246 int LnBirthDeathPriorPrRandom (Tree *t, MrBFlt clockRate, MrBFlt *prob, MrBFlt sR, MrBFlt eR, MrBFlt sF)
8249 MrBFlt *nt, lambda, mu, rho;
8252 /* allocate space for the speciation times */
8253 nt = (MrBFlt *)SafeMalloc((size_t)(t->nIntNodes) * sizeof(MrBFlt));
8256 MrBayesPrint ("\n ERROR: Problem allocating nt\n");
8260 /* transform to standard variables */
8262 lambda = sR / (1.0 - eR);
8265 /* get the node times and put them into a vector */
8266 for (i=0; i<t->nIntNodes; i++)
8268 p = t->intDownPass[i];
8269 nt[i] = p->nodeDepth / clockRate;
8271 nTaxa = t->nIntNodes + 1;
8273 /* calculate probability of tree using standard variables */
8274 if (AreDoublesEqual(lambda,mu,ETA)==NO)
8276 // birth rate != death rate, see equation (5) in Stadler (2009) and above
8277 (*prob) = log(nTaxa) + log(lambda - mu) - (lambda - mu) * nt[t->nIntNodes-1];
8278 (*prob) -= log(rho*lambda + (lambda*(1.0 - rho) - mu)*exp((mu - lambda)*nt[t->nIntNodes-1]));
8279 for (i=0; i<t->nIntNodes; i++)
8280 (*prob) += log(rho*lambda) + LnP1Subsample(nt[i], lambda, mu, rho);
8281 (*prob) += (nTaxa - 1.0) * log(2.0) - LnFactorial(nTaxa); /* conversion to labeled tree from oriented tree */
8285 // birth rate == death rate -> the critical branching process
8286 (*prob) = log(nTaxa/(1.0 + rho*lambda*nt[t->nIntNodes-1]));
8287 for (i=0; i<t->nIntNodes; i++)
8288 (*prob) += log(rho*lambda) - 2.0 * log(1.0 + rho*lambda*nt[i]);
8289 (*prob) += (nTaxa - 1.0) * log(2.0) - LnFactorial(nTaxa); /* conversion to labeled tree from oriented tree */
8299 /*---------------------------------------------------------------------------------
8301 | LnBirthDeathPriorPrDiversity
8303 | Eq.5 in Hohna et al. 2011 MBE
8305 ---------------------------------------------------------------------------------*/
8306 int LnBirthDeathPriorPrDiversity (Tree *t, MrBFlt clockRate, MrBFlt *prob, MrBFlt sR, MrBFlt eR, MrBFlt sF)
8309 MrBFlt *nt, lambda, mu, nt_min;
8312 /* allocate space for the speciation times */
8313 nt = (MrBFlt *)SafeMalloc((size_t)(t->nIntNodes) * sizeof(MrBFlt));
8316 MrBayesPrint ("\n ERROR: Problem allocating nt\n");
8320 /* transform to standard variables */
8321 lambda = sR / (1.0 - eR);
8325 m = (int)floor(n/sF+0.5); /* equal to round(n/sF) plus it is compatible with MS Visual Studio */
8327 /* get the node times and put them into a vector */
8328 for (i=0; i<t->nIntNodes; i++)
8330 p = t->intDownPass[i];
8331 nt[i] = p->nodeDepth / clockRate;
8333 nTaxa = t->nIntNodes + 1;
8335 /* find the youngest interal node */
8337 for (i=0; i<t->nIntNodes-1; i++)
8343 /* calculate probability of tree using standard variables */
8344 if (AreDoublesEqual(lambda,mu,ETA)==NO)
8346 // birth rate != death rate
8348 p0_t1 = LnP0(nt[t->nIntNodes-1], lambda, mu);
8349 (*prob) = log(nTaxa); // we need to add here the binomial coefficient
8350 (*prob) += (m-n) * (LnP0(nt_min, lambda, mu) - p0_t1);
8351 for (i=0; i<t->nIntNodes-1; i++)
8352 (*prob) += (LnP1(nt[i], lambda, mu) - p0_t1);
8353 (*prob) += (nTaxa - 1.0) * log(2.0) - LnFactorial(nTaxa); /* conversion to labeled tree from oriented tree */
8357 MrBayesPrint ("\n ERROR: Critical branchin process for diversity sampling not implemented\n");
8361 /* condition on tmrca ??? */
8370 /*---------------------------------------------------------------------------------
8372 | LnBirthDeathPriorPrCluster
8374 | Eq.7 in Hohna et al. 2011 MBE
8376 ---------------------------------------------------------------------------------*/
8377 int LnBirthDeathPriorPrCluster (Tree *t, MrBFlt clockRate, MrBFlt *prob, MrBFlt sR, MrBFlt eR, MrBFlt sF)
8380 MrBFlt *nt, lambda, mu, nt_max;
8383 /* allocate space for the speciation times */
8384 nt = (MrBFlt *)SafeMalloc((size_t)(t->nIntNodes) * sizeof(MrBFlt));
8387 MrBayesPrint ("\n ERROR: Problem allocating nt\n");
8391 /* transform to standard variables */
8392 lambda = sR / (1.0 - eR);
8396 m = (int)floor(n/sF+0.5); /* equal to round(n/sF) plus it is compatible with MS Visual Studio */
8398 /* get the node times and put them into a vector */
8399 for (i=0; i<t->nIntNodes; i++)
8401 p = t->intDownPass[i];
8402 nt[i] = p->nodeDepth / clockRate;
8404 nTaxa = t->nIntNodes + 1;
8406 /* find the second oldest interal node */
8408 for (i=0; i<t->nIntNodes-1; i++)
8414 /* calculate probability of tree using standard variables */
8415 if (AreDoublesEqual(lambda,mu,ETA)==NO)
8417 // birth rate != death rate
8419 p0_t1 = LnP0(nt[t->nIntNodes-1], lambda, mu);
8420 (*prob) = log(nTaxa); // we need to add here the binomial coefficient
8421 (*prob) += (m-n) * (LnP0(nt_max, lambda, mu) - p0_t1);
8422 for (i=0; i<t->nIntNodes-1; i++)
8423 (*prob) += (LnP1(nt[i], lambda, mu) - p0_t1);
8424 (*prob) += (nTaxa - 1.0) * log(2.0) - LnFactorial(nTaxa); /* conversion to labeled tree from oriented tree */
8428 MrBayesPrint ("\n ERROR: Critical branchin process for cluster sampling not implemented\n");
8432 /* condition on tmrca ??? */
8443 | The probability of having zero lineages remaining after time t in the
8444 | birth-death process.
8446 | param: t - speciation time
8447 | param: b - birth rate
8448 | param: d - death rate
8449 | return: log probability of zero remaining lineages
8452 MrBFlt LnP0 (MrBFlt t, MrBFlt b, MrBFlt d)
8456 p0t = d*(1.0-exp((d-b)*t)) / (b -d*exp((d-b)*t));
8463 | The probability of having zero lineages remaining after time t in the
8464 | birth-death process.
8466 | param: t - speciation time
8467 | param: b - birth rate
8468 | param: d - death rate
8469 | param: f - sample frequency
8470 | return: log probability of zero remaining lineages
8473 MrBFlt LnP0Subsample (MrBFlt t, MrBFlt b, MrBFlt d, MrBFlt f)
8477 p0t = (f*d + (b*(1.0-f) - d)*exp((d-b)*t)) / (f*b + (b*(1.0-f)-d)*exp((d-b)*t));
8484 | The probability of having one lineage remaining after time t
8485 | in the birth-death process.
8487 | param: t - speciation time
8488 | param: b - birth rate
8489 | param: d - death rate
8490 | return: log probability of one remaining lineage
8493 MrBFlt LnP1 (MrBFlt t, MrBFlt b, MrBFlt d)
8497 p0t = 2.0 * log(b-d) - (b-d)*t;
8499 p0t -= 2.0 * log(b - d*exp((d-b)*t));
8506 | The probability of having one lineage remaining after time t
8507 | in the birth-death process.
8509 | param: t - speciation time
8510 | param: b - birth rate
8511 | param: d - death rate
8512 | param: f - sample frequency
8513 | return: log probability of one remaining lineage
8516 MrBFlt LnP1Subsample (MrBFlt t, MrBFlt b, MrBFlt d, MrBFlt f)
8520 p0t = (b-d) / (f*b + (b*(1.0-f)-d)*exp((d-b)*t));
8522 return (2.0*log(p0t) + (d-b)*t);
8526 /* probability that an individual alive at time t before today has
8527 no sampled extinct or extant descendants
8529 MrBFlt LnP0_fossil (MrBFlt t, MrBFlt lambda, MrBFlt mu, MrBFlt psi, MrBFlt c1, MrBFlt c2)
8533 // c1 = sqrt(pow(lambda-mu-psi, 2) + 4*lambda*psi);
8534 // c2 = (-lambda + mu + 2*lambda*rho + psi) / c1;
8535 other = (exp(-c1 *t) * (1 - c2) - (1 + c2)) / (exp(-c1 *t) * (1 - c2) + (1 + c2));
8537 return log(0.5) + log(lambda + mu + psi + c1 * other) - log(lambda);
8540 /* probability that an individual alive at time t before today has
8541 precisely one sampled extant descendant and no sampled extinct descendant
8543 MrBFlt LnP1_fossil (MrBFlt t, MrBFlt rho, MrBFlt c1, MrBFlt c2)
8547 // c1 = sqrt(pow(lambda-mu-psi, 2) + 4*lambda*psi);
8548 // c2 = (-lambda + mu + 2*lambda*rho + psi) / c1;
8549 other = 2.0 * (1- c2*c2) * exp(-c1 *t) + pow(1-c2, 2) * exp(-2 *c1 *t) + pow(1+c2, 2);
8551 return log(4.0) + log(rho) - c1 *t - log(other);
8555 /* return which time interval t is in */
8556 int Slice_i (MrBFlt t, MrBFlt *t_f, int sl)
8559 assert (t > 0.0 && sl >= 0);
8561 /* we need some tolerance here, for t[i] < t <= t[i-1] to return i */
8562 while (t < t_f[i] + BRLENS_MIN/5)
8571 /* probability density of an individual at time t giving rise to an edge
8572 between time t and t_i with q_i(t_i) = 1
8574 MrBFlt LnQi_fossil (MrBFlt t, MrBFlt *t_f, int sl, MrBFlt *c1, MrBFlt *c2)
8577 int i = Slice_i (t, t_f, sl);
8579 lnq = log(4.0) +c1[i] *(t_f[i] -t);
8580 lnq -= 2.0 * log(1 +c2[i] +(1 -c2[i]) *exp(c1[i] *(t_f[i] -t)));
8585 /* an individual at time t has no sampled descendants when the process is stopped
8586 (i.e., at time t_s), with t_i < t <= t_{i-1} (i = 1,..,s)
8588 MrBFlt LnPi_fossil (MrBFlt t, MrBFlt *t_f, int sl, MrBFlt *c1, MrBFlt *c2, MrBFlt *lambda, MrBFlt *mu, MrBFlt *psi)
8591 int i = Slice_i (t, t_f, sl);
8593 other = lambda[i] +mu[i] +psi[i] -c1[i] * (1 +c2[i] -(1 -c2[i]) *exp(c1[i] *(t_f[i] -t)))
8594 / (1 +c2[i] +(1 -c2[i]) *exp(c1[i] *(t_f[i] -t)));
8595 return log(other) - log(2 *lambda[i]);
8599 int LnFossilizationPriorPr (Tree *t, MrBFlt clockRate, MrBFlt *prob, MrBFlt *sR, MrBFlt *eR, MrBFlt sF, MrBFlt *fR, char *sS)
8601 /* fossilization priors
8604 if (!strcmp(sS, "FossilTip"))
8605 return LnFossilizedBDPriorFossilTip (t, clockRate, prob, *sR, *eR, sF, *fR);
8606 else if (!strcmp(sS, "Random"))
8607 return LnFossilizedBDPriorRandom (t, clockRate, prob, sR, eR, sF, fR);
8608 else if (!strcmp(sS, "Diversity"))
8609 return LnFossilizedBDPriorDiversity (t, clockRate, prob, sR, eR, sF, fR);
8612 MrBayesPrint ("%s Sampling strategy %s for fossilized birth-death process not implemented\n", spacer, sS);
8618 /*---------------------------------------------------------------------------------
8639 | b: birth (speciation) rate
8640 | d: death (extintion) rate
8641 | p: extant sampling rate
8642 | q: fossil sampling rate
8643 | n: number of extant taxa
8644 | m: number of fossil tips
8647 | [p1(x1)]^2 n+m-1 m q
8648 | f(T|tmrca) = ---------------- * prod b*p1(xi) * prod ----- .
8649 | [1 - ^p0(x1)]^2 i=2 i=1 p1(yi)
8651 | f(tmrca) ~ uniform, gamma, etc (see treeAge).
8653 ---------------------------------------------------------------------------------*/
8654 int LnFossilizedBDPriorFossilTip (Tree *t, MrBFlt clockRate, MrBFlt *prob, MrBFlt sR, MrBFlt eR, MrBFlt sF, MrBFlt fR)
8656 /* special case: upon sampling the lineage is dead and won't produce descendants. Each extinct sample is a tip */
8659 MrBFlt x, lambda, rho, psi, tmrca, c1, c2, hatP0;
8663 /* sR = lambda-mu-psi, eR = (mu+psi)/lambda, fR = psi/(mu+psi) */
8664 lambda = sR / (1.0 - eR);
8665 psi = lambda * eR * fR;
8668 tmrca = t->root->left->nodeDepth / clockRate;
8669 c1 = sqrt(sR*sR + 4 *lambda *psi);
8670 c2 = (2 *lambda *rho - sR) / c1;
8672 /* calculate prior prob of the fbd tree */
8675 for (n = m = i = 0; i < t->nNodes -1; i++)
8677 p = t->allDownPass[i];
8678 x = p->nodeDepth / clockRate;
8680 if (p->left != NULL && p->right != NULL) // internal
8682 if (p != t->root->left)
8683 (*prob) += log(lambda) + LnP1_fossil(x, rho, c1, c2);
8685 else if (p->left == NULL && p->right == NULL) // tip
8687 if (p->nodeDepth > 0.0)
8689 (*prob) += log(psi) - LnP1_fossil(x, rho, c1, c2);
8697 /* p_0 (t |psi=0, mu->mu+psi) */
8698 hatP0 = 1.0 - rho*sR / (rho*lambda + (sR - rho*lambda) * exp(-sR*tmrca));
8700 (*prob) += 2.0 * (LnP1_fossil(tmrca, rho, c1, c2) - log(1 - hatP0));
8702 /* condition on tmrca, calibrations are dealt with separately */
8703 mp = &modelParams[t->relParts[0]];
8704 if (t->root->left->isDated == NO)
8705 (*prob) += mp->treeAgePr.LnPriorProb(tmrca, mp->treeAgePr.priorParams);
8707 /* conversion to labeled tree from oriented tree , constant for a given dataset */
8708 (*prob) += (n + m - 1) * log(2.0) - LnFactorial(n) - LnFactorial(m);
8714 /*---------------------------------------------------------------------------------
8716 | LnFossilizedBDPriorRandom
8718 | Gavryushkina, A., D. Welch, T. Stadler, and A. Drummond. 2014.
8719 | Bayesian inference of sampled ancestor trees for epidemiology and fossil calibration. PLoS Comp. Biol.
8720 | Zhang C., T. Stadler, S. Klopfstein, T. A. Heath, and F. Ronquist. 2015.
8721 | Total-Evidence Dating under the Fossilized Birth-Death Process. Syst. Biol.
8724 | 0 _____________ t3, rho3
8727 | \ \ / _________|_________ t2, rho2
8732 | _\ \ / _________|_________ t1, rho1
8739 | \/ x1 ___|_________ t_mrca
8742 | sl = 2, t1 > t2 > t3 = 0
8743 | E = 2, K = 1, M = 2
8745 ---------------------------------------------------------------------------------*/
8746 int LnFossilizedBDPriorRandom (Tree *t, MrBFlt clockRate, MrBFlt *prob, MrBFlt *sR, MrBFlt *eR, MrBFlt sF, MrBFlt *fR)
8748 /* Fossils in the past are sampled with piecewise constant rates,
8749 also in several time slices each with a seperate probability.
8750 Extant taxa are sampled uniformly at random at time 0 (present). */
8752 int i, j, sl, K, M, E;
8753 MrBFlt x, *lambda, *mu, *rho, *psi, *t_f, tmrca, *c1, *c2, *p_t;
8757 mp = &modelParams[t->relParts[0]];
8759 /* time of most recent common ancestor */
8760 tmrca = t->root->left->nodeDepth / clockRate;
8762 /* get the number of fossil slice sampling events, s >= 0 */
8763 sl = mp->sampleFSNum;
8765 /* alloc memory for time of each slice, t_f[sl] = 0 */
8766 t_f = (MrBFlt *)SafeMalloc((size_t)(sl+1) * sizeof(MrBFlt));
8767 /* lambda, mu, psi */
8768 lambda = (MrBFlt *)SafeMalloc((size_t)(sl+1) * sizeof(MrBFlt));
8769 mu = (MrBFlt *)SafeMalloc((size_t)(sl+1) * sizeof(MrBFlt));
8770 psi = (MrBFlt *)SafeMalloc((size_t)(sl+1) * sizeof(MrBFlt));
8771 /* for sampling prob in each slice, including extant */
8772 rho = (MrBFlt *)SafeMalloc((size_t)(sl+1) * sizeof(MrBFlt));
8774 c1 = (MrBFlt *)SafeMalloc((size_t)(sl+1) * sizeof(MrBFlt));
8775 c2 = (MrBFlt *)SafeMalloc((size_t)(sl+1) * sizeof(MrBFlt));
8776 p_t = (MrBFlt *)SafeMalloc((size_t)(sl+1) * sizeof(MrBFlt));
8778 if (!lambda || !mu || !psi || !rho || !t_f || !c1 || !c2 || !p_t)
8780 MrBayesPrint ("%s ERROR: Problem allocating memory in LnFossilizedBDPriorRandom\n", spacer);
8781 free(lambda); free(mu); free(psi); free(rho);
8782 free(t_f); free(c1); free(c2); free(p_t);
8785 /* initialization */
8786 for (i = 0; i <= sl; i++)
8788 /* sR = lambda-mu, eR = mu/lambda, fR = psi/(mu+psi) */
8789 lambda[i] = sR[i] / (1.0 - eR[i]);
8790 mu[i] = lambda[i] * eR[i];
8791 psi[i] = mu[i] * fR[i] / (1.0 - fR[i]);
8793 rho[i] = mp->sampleFSProb[i];
8794 t_f[i] = mp->sampleFSTime[i];
8800 if (sl > 0) assert (mp->sampleFSTime[0] < tmrca);
8801 for (i = sl; i >= 0; i--)
8803 c1[i] = sqrt(pow(lambda[i]-mu[i]-psi[i], 2) + 4*lambda[i]*psi[i]);
8805 c2[i] = ((1 - 2* (1-rho[i])) *lambda[i] +mu[i] +psi[i]) /c1[i];
8807 c2[i] = ((1 - 2* (1-rho[i]) *p_t[i+1]) *lambda[i] +mu[i] +psi[i]) /c1[i];
8809 p_t[i] = (lambda[i] +mu[i] +psi[i] -c1[i] * (1 +c2[i] -(1 -c2[i]) *exp(c1[i] *(t_f[i] -t_f[i-1])))
8810 / (1 +c2[i] +(1 -c2[i]) *exp(c1[i] *(t_f[i] -t_f[i-1])))) *0.5/lambda[i];
8812 p_t[i] = (lambda[i] +mu[i] +psi[i] -c1[i] * (1 +c2[i] -(1 -c2[i]) *exp(c1[i] *(t_f[i] -tmrca)))
8813 / (1 +c2[i] +(1 -c2[i]) *exp(c1[i] *(t_f[i] -tmrca)))) *0.5/lambda[i];
8817 for (i = 0; i <= sl; i++)
8818 printf ("%d: lambad=%lf mu=%lf psi=%lf t=%lf rho=%lf\n",i+1, lambda[i], mu[i], psi[i], t_f[i], rho[i]);
8819 for (i = 0; i <= sl; i++)
8820 printf ("%d: A=%lf B=%lf p%d(t%d)=%lf\n", i+1, c1[i], c2[i], i+1, i, p_t[i]);
8823 /* calculate prior prob of the fbd tree */
8826 for (K = M = E = 0, i = 0; i < t->nNodes -1; i++)
8828 p = t->allDownPass[i];
8829 x = p->nodeDepth / clockRate;
8831 if (p->left != NULL && p->right != NULL) // internal
8833 if (p->left->length > 0.0 && p->right->length > 0.0)
8835 if (p != t->root->left)
8836 (*prob) += log(lambda[Slice_i(x, t_f, sl)]) + LnQi_fossil(x, t_f, sl, c1,c2);
8840 for (j = 0; j < sl; j++)
8841 if (AreDoublesEqual(p->nodeDepth, t_f[j]*clockRate, BRLENS_MIN/5) == YES) break;
8842 if (j == sl) /* fossil ancestor between t[j-1] and t[j] */
8844 (*prob) += log(psi[Slice_i(x, t_f, sl)]);
8846 else /* fossil ancestor at silice time t[j] */
8847 if (rho[j] > 0.0 && rho[j] < 1.0)
8849 (*prob) += log(rho[j]) - log(1 - rho[j]);
8851 K++; /* number of fossil ancestors */
8854 else if (p->left == NULL && p->length > 0.0) // tip
8856 if (p->nodeDepth > 0.0)
8858 for (j = 0; j < sl; j++)
8859 if (AreDoublesEqual(p->nodeDepth, t_f[j]*clockRate, BRLENS_MIN/5) == YES) break;
8860 if (j == sl) /* fossil tip between t[j-1] and t[j] */
8862 (*prob) += LnPi_fossil(x, t_f, sl, c1,c2, lambda,mu,psi)
8863 - LnQi_fossil(x, t_f, sl, c1,c2);
8864 (*prob) += log(psi[Slice_i(x, t_f, sl)]);
8866 else /* fossil tip at silice time t[j] */
8868 (*prob) += log(p_t[j+1]);
8869 if (rho[j] > 0.0) (*prob) += log(rho[j]);
8871 M++; /* number of fossil tips */
8877 (*prob) += log(rho[sl]);
8879 E++; /* number of extant taxa */
8883 for (j = 0; j < sl; j++) /* degree-two vertices at silice time t_j */
8885 if (p->length > 0.0)
8886 if ((p->nodeDepth +BRLENS_MIN/10 < t_f[j]*clockRate) && (t_f[j]*clockRate < p->anc->nodeDepth +BRLENS_MIN/10))
8888 (*prob) += LnQi_fossil(t_f[j], t_f, sl, c1,c2);
8889 if (rho[j] < 1.0) (*prob) += log(1 - rho[j]);
8894 (*prob) += 2.0 * (LnQi_fossil(tmrca, t_f, sl, c1,c2) - log(1- p_t[0]));
8896 /* condition on tmrca, calibrations are dealt with separately */
8897 if (t->root->left->isDated == NO)
8898 (*prob) += mp->treeAgePr.LnPriorProb(tmrca, mp->treeAgePr.priorParams);
8900 /* conversion to labeled tree from oriented tree */
8901 (*prob) += (M + E - 1) * log(2.0); // - LnFactorial(E + M + K) (# permutation is constant given data)
8904 printf ("K=%d M=%d E=%d\n", K, M, E);
8905 printf ("prob=%lf\n", *prob);
8909 free(lambda); free(mu); free(psi); free(rho);
8910 free(t_f); free(c1); free(c2); free(p_t);
8916 /*---------------------------------------------------------------------------------
8918 | LnFossilizedBDPriorDiversity
8920 | Zhang C., T. Stadler, S. Klopfstein, T. A. Heath, and F. Ronquist. 2015.
8921 | Total-Evidence Dating under the Fossilized Birth-Death Process. Syst. Biol.
8923 ---------------------------------------------------------------------------------*/
8924 int LnFossilizedBDPriorDiversity (Tree *t, MrBFlt clockRate, MrBFlt *prob, MrBFlt *sR, MrBFlt *eR, MrBFlt sF, MrBFlt *fR)
8926 /* Fossils in the past are sampled with piecewise constant rates,
8927 also in several time slices each with a seperate probability.
8928 Extant taxa are sampled with prop sF to maximize diversity. */
8930 int i, j, sl, K, M, E;
8931 MrBFlt x, x_min, t_min, M_x, *lambda, *mu, *rho, *psi, *t_f, tmrca, *c1, *c2, *p_t;
8935 mp = &modelParams[t->relParts[0]];
8937 /* time of most recent common ancestor */
8938 tmrca = t->root->left->nodeDepth / clockRate;
8940 /* get the number of fossil slice sampling events, plus 1 extra slice (x_cut) to shift psi to 0 */
8941 sl = mp->sampleFSNum + 1;
8943 /* alloc memory for time of each slice */
8944 t_f = (MrBFlt *)SafeMalloc((size_t)(sl+1) * sizeof(MrBFlt));
8945 /* lambda, mu, psi */
8946 lambda = (MrBFlt *)SafeMalloc((size_t)(sl+1) * sizeof(MrBFlt));
8947 mu = (MrBFlt *)SafeMalloc((size_t)(sl+1) * sizeof(MrBFlt));
8948 psi = (MrBFlt *)SafeMalloc((size_t)(sl+1) * sizeof(MrBFlt));
8949 /* for sampling prob in each slice, including extant */
8950 rho = (MrBFlt *)SafeMalloc((size_t)(sl+1) * sizeof(MrBFlt));
8952 c1 = (MrBFlt *)SafeMalloc((size_t)(sl+1) * sizeof(MrBFlt));
8953 c2 = (MrBFlt *)SafeMalloc((size_t)(sl+1) * sizeof(MrBFlt));
8954 p_t = (MrBFlt *)SafeMalloc((size_t)(sl+1) * sizeof(MrBFlt));
8956 if (!lambda || !mu || !psi || !rho || !t_f || !c1 || !c2 || !p_t)
8958 MrBayesPrint ("%s ERROR: Problem allocating memory in LnFossilizedBDPriorDiversity\n", spacer);
8959 free(lambda); free(mu); free(psi); free(rho);
8960 free(t_f); free(c1); free(c2); free(p_t);
8963 /* get time of youngest fossil and internal node */
8964 t_min = x_min = tmrca;
8965 for (i = 0; i < t->nNodes -1; i++)
8967 p = t->allDownPass[i];
8968 if (p->left == NULL && p->nodeDepth > 0.0) //fossil
8969 if (t_min > p->nodeDepth / clockRate)
8970 t_min = p->nodeDepth / clockRate;
8971 if (p->left != NULL && p->right != NULL &&
8972 p->left->length > 0.0 && p->right->length > 0.0)
8973 if (x_min > p->nodeDepth / clockRate)
8974 x_min = p->nodeDepth / clockRate;
8977 /* lower the cutoff time if not compatible */
8980 if (sl > 1 && mp->sampleFSTime[sl-2] < x_min)
8981 x_min = mp->sampleFSTime[sl-2];
8983 /* initialization (sl >= 1) */
8984 for (i = 0; i < sl; i++)
8986 /* sR = lambda-mu, eR = mu/lambda, fR = psi/(mu+psi) */
8987 lambda[i] = sR[i] / (1.0 - eR[i]);
8988 mu[i] = lambda[i] * eR[i];
8989 psi[i] = mu[i] * fR[i] / (1.0 - fR[i]);
8991 lambda[sl] = lambda[sl-1];
8993 psi[sl] = 0.0; // psi = 0 in [0, x_cut]
8994 for (i = 0; i < sl-1; i++)
8996 rho[i] = mp->sampleFSProb[i];
8997 t_f[i] = mp->sampleFSTime[i];
9000 t_f[sl-1] = x_min * 0.95; // x_cut
9001 rho[sl] = 1.0; // not sF
9004 if (sl > 1) assert (mp->sampleFSTime[0] < tmrca);
9005 for (i = sl; i >= 0; i--)
9007 c1[i] = sqrt(pow(lambda[i]-mu[i]-psi[i], 2) + 4*lambda[i]*psi[i]);
9009 c2[i] = ((1 - 2* (1-rho[i])) *lambda[i] +mu[i] +psi[i]) /c1[i];
9011 c2[i] = ((1 - 2* (1-rho[i]) *p_t[i+1]) *lambda[i] +mu[i] +psi[i]) /c1[i];
9013 p_t[i] = (lambda[i] +mu[i] +psi[i] -c1[i] * (1 +c2[i] -(1 -c2[i]) *exp(c1[i] *(t_f[i] -t_f[i-1])))
9014 / (1 +c2[i] +(1 -c2[i]) *exp(c1[i] *(t_f[i] -t_f[i-1])))) *0.5/lambda[i];
9016 p_t[i] = (lambda[i] +mu[i] +psi[i] -c1[i] * (1 +c2[i] -(1 -c2[i]) *exp(c1[i] *(t_f[i] -tmrca)))
9017 / (1 +c2[i] +(1 -c2[i]) *exp(c1[i] *(t_f[i] -tmrca)))) *0.5/lambda[i];
9021 for (i = 0; i <= sl; i++)
9022 printf ("%d: lambad=%lf mu=%lf psi=%lf t=%lf rho=%lf\n",i+1, lambda[i], mu[i], psi[i], t_f[i], rho[i]);
9023 for (i = 0; i <= sl; i++)
9024 printf ("%d: A=%lf B=%lf p%d(t%d)=%lf\n", i+1, c1[i], c2[i], i+1, i, p_t[i]);
9027 /* first calculate prob of the fbd tree assuming complete sampling */
9030 for (K = M = E = 0, i = 0; i < t->nNodes -1; i++)
9032 p = t->allDownPass[i];
9033 x = p->nodeDepth / clockRate;
9035 if (p->left != NULL && p->right != NULL) // internal
9037 if (p->left->length > 0.0 && p->right->length > 0.0)
9039 if (p != t->root->left)
9040 (*prob) += log(lambda[Slice_i(x, t_f, sl)]) + LnQi_fossil(x, t_f, sl, c1,c2);
9044 for (j = 0; j < sl; j++)
9045 if (AreDoublesEqual(p->nodeDepth, t_f[j]*clockRate, BRLENS_MIN/5) == YES) break;
9046 if (j == sl) /* fossil ancestor between t[j-1] and t[j] */
9048 (*prob) += log(psi[Slice_i(x, t_f, sl)]);
9050 else /* fossil ancestor at silice time t[j] */
9051 if (rho[j] > 0.0 && rho[j] < 1.0)
9053 (*prob) += log(rho[j]) - log(1 - rho[j]);
9055 K++; /* number of fossil ancestors */
9058 else if (p->left == NULL && p->length > 0.0) // tip
9060 if (p->nodeDepth > 0.0)
9062 for (j = 0; j < sl; j++)
9063 if (AreDoublesEqual(p->nodeDepth, t_f[j]*clockRate, BRLENS_MIN/5) == YES) break;
9064 if (j == sl) /* fossil tip between t[j-1] and t[j] */
9066 (*prob) += LnPi_fossil(x, t_f, sl, c1,c2, lambda,mu,psi)
9067 - LnQi_fossil(x, t_f, sl, c1,c2);
9068 (*prob) += log(psi[Slice_i(x, t_f, sl)]);
9070 else /* fossil tip at silice time t[j] */
9072 (*prob) += log(p_t[j+1]);
9073 if (rho[j] > 0.0) (*prob) += log(rho[j]);
9075 M++; /* number of fossil tips */
9079 // (*prob) += log(rho[sl]); // rho[sl] == 1
9080 E++; /* number of extant taxa */
9084 for (j = 0; j < sl; j++) /* degree-two vertices at silice time t_j */
9086 if (p->length > 0.0)
9087 if ((p->nodeDepth +BRLENS_MIN/10 < t_f[j]*clockRate) && (t_f[j]*clockRate < p->anc->nodeDepth +BRLENS_MIN/10))
9089 (*prob) += LnQi_fossil(t_f[j], t_f, sl, c1,c2);
9090 if (rho[j] < 1.0) (*prob) += log(1 - rho[j]);
9095 (*prob) += 2.0 * (LnQi_fossil(tmrca, t_f, sl, c1,c2) - log(1- p_t[0]));
9097 /* number of extant taxa not sampled */
9098 M_x = (int)floor(E/sF + 0.5) - E; /* equal to round(E/sF) plus it is compatible with MS Visual Studio */
9100 /* then calculate the prob of the fbd tree assuming diversified sampling of extant */
9101 (*prob) += M_x * (log(lambda[sl] * (1.0 - exp((mu[sl]-lambda[sl])*t_f[sl-1]))) - log(lambda[sl] - mu[sl] * exp((mu[sl]-lambda[sl])*t_f[sl-1])));
9103 /* condition on tmrca, calibrations are dealt with separately */
9104 if (t->root->left->isDated == NO)
9105 (*prob) += mp->treeAgePr.LnPriorProb(tmrca, mp->treeAgePr.priorParams);
9107 /* conversion to labeled tree from oriented tree */
9108 (*prob) += (M + E - 1) * log(2.0); // - LnFactorial(E + M + K) (# permutation is constant given data)
9111 printf ("K=%d M=%d E=%d\n", K, M, E);
9112 printf ("prob=%lf\n", *prob);
9116 free(lambda); free(mu); free(psi); free(rho);
9117 free(t_f); free(c1); free(c2); free(p_t);
9123 /*---------------------------------------------------------------------------------
9125 | LnCoalescencePriorPr
9127 | This function calculates the probability of a tree under the neutral
9128 | coalescence prior with a (potentially) exponentially growing population.
9129 | We assume a rooted tree that satisfies the molecular clock constraint. The
9130 | Tree is labelled as follows:
9149 | Each interval on the tree is specified by successive coalescence events.
9150 | These intervals are denoted I_2, I_3, I_4, ..., with the subscript denoting
9151 | how many lineages exist in that interval. The time of each coalescence event
9152 | is designated t_1, t_2, t_3, ..., where the subscript denotes the number
9153 | of lineages that exist after the coalescence (t_3, for instance, would be
9154 | the time of the coalescence that went from four lineages to three lineages).
9155 | The duration of the i-th interval is designated g_i.
9157 | The probability of the coalescence tree is:
9159 | prob = (k_C_2 / (N(t_k + t_k))) * exp(-integral_(from x=t_k, to g_k + t_k) (k_C_2 / N(x)) dx)
9161 | where N(x) = N(0) * exp(-r*x). For the constant population size case,
9162 | N(0) = N_e. r is the population growth parameter for the exponentially
9163 | growing population. Here, theta = N(0) * mu when organisms are haploid and
9164 | theta = 2 * N(0) * mu when the organism is diploid.
9166 | Below, ct holds the n - 1 coalescence times (t_i, above) sorted from the
9167 | smallest to the largest. Remember that t_4 < t_3 < t_2, etc.
9170 | The original function (described above) was incorrect in that it used theta = 2 * N * mu
9171 | in one part of the equation and theta = 4 * N * mu in another. It is now corrected to
9172 | consistently use theta = 4 * N * mu, which is the standard for diploid populations
9173 | and theta = 2 * N * mu for haploid populations. The calculations are the same for the
9174 | diploid and haploid cases, only the interpretation is different. See, e.g., Felsenstein
9175 | (2004; Inferring Phylogenies). -- Fredrik.
9177 ---------------------------------------------------------------------------------*/
9178 int LnCoalescencePriorPr (Tree *t, MrBFlt *prob, MrBFlt theta, MrBFlt growth)
9180 int i, j, k, nNodes;
9181 MrBFlt *ct, tempD, lastCoalescenceTime, coalescenceTime, intervalLength;
9184 /* allocate space for the coalescence times */
9185 ct = (MrBFlt *)SafeMalloc((size_t)(t->nIntNodes) * sizeof(MrBFlt));
9188 MrBayesPrint ("\n ERROR: Problem allocating ct\n");
9192 /* get the coalescence times and put them into a vector */
9193 for (i=j=0; i<t->nIntNodes; i++)
9195 p = t->intDownPass[i];
9197 ct[j++] = p->nodeDepth; // Don't divide clockRate here, as mu is already in theta
9201 /* sort the coalescence times */
9202 SortMrBFlt (ct, 0, nNodes-1);
9204 /*for (i=0, k=numLocalTaxa; i<nNodes; i++)
9206 printf ("%4d -- %2d %lf\n", i, k, ct[i]);
9210 /* calculate probability of the tree */
9211 if (AreDoublesEqual (growth, 0.0, 0.000001) == YES)
9213 /* use this if there is no population growth */
9214 tempD = lastCoalescenceTime = 0.0;
9215 for (i=0, k=numLocalTaxa; i<nNodes; i++)
9217 coalescenceTime = ct[i];
9218 intervalLength = coalescenceTime - lastCoalescenceTime;
9219 lastCoalescenceTime = ct[i];
9220 tempD += - (k * (k-1) * intervalLength) / (theta);
9223 (*prob) = (numLocalTaxa - 1) * log(2.0 / theta) + tempD;
9227 /* use this if the population is growing exponentially */
9228 tempD = lastCoalescenceTime = 0.0;
9229 for (i=0, k=numLocalTaxa; i<nNodes; i++)
9231 coalescenceTime = ct[i];
9232 intervalLength = coalescenceTime - lastCoalescenceTime;
9233 tempD += growth * coalescenceTime + (((k * (k-1)) / (theta * growth)) * (exp(growth * lastCoalescenceTime) - exp(growth * coalescenceTime)));
9234 lastCoalescenceTime = ct[i];
9237 (*prob) = (numLocalTaxa - 1) * log(2.0 / theta) + tempD;
9240 /* printf ("coal pr = %lf theta = %lf, nNodes = %d, nt = %d tempD = %lf\n", *prob, theta, nNodes, numLocalTaxa, tempD); */
9249 /*---------------------------------------------------------------------------------
9253 | This function calculates the probability of a calibrated clock tree under the
9254 | uniform prior probability distribution on node depths. The tree is labeled as
9256 | interval between tip dates
9257 | t_0 t_1 time ____ 0 (interval between t_0 and t_1, duration 0)
9259 | \ t_2 / |___ 1 (interval between t_1 and t_2)
9262 | \ \/ 0.33 ___| 2 (interval between t_2 and t_3)
9267 | \ t_4 \/ 0.67 ___|
9268 | \ \ / | 3 (interval between t_3 and root)
9270 | \ / | Note that t_4 is irrelevant for intervals
9271 | \ / | because we need not have a single coalescent
9272 | \/ 1.00 ___|___ event beneath t_4 except for the root.
9274 | The probability depends on the number of nodes falling in each interval between
9275 | tip dates, the time interval on which each node depth can vary (if it is interior
9276 | node number i, it can vary on the interval (t_{i+1},1)). Finally, the probability
9277 | is multiplied by the number of coalescent histories compatible with the node order.
9279 ---------------------------------------------------------------------------------*/
9280 MrBFlt LnUniformPriorPr (Tree *t, MrBFlt clockRate)
9282 int i, j, k, *nLineages=NULL, nDatedTips, nLineagesIn, nLineagesOut, nTips;
9283 MrBFlt lnProb, treeAge, *nodeDepths=NULL;
9288 mp = &modelParams[t->relParts[0]];
9289 treeAge = t->root->left->nodeDepth / clockRate;
9290 assert (t->root->left->isDated == NO || AreDoublesEqual(treeAge, t->root->left->age, 0.000001) == YES);
9292 /* Calculate number of tips for convenience */
9293 nTips = t->nNodes - t->nIntNodes - 1;
9295 /* First take tree age into account f(t_0) */
9296 if (t->root->left->isDated == YES)
9298 lnProb += 0.0; /* calibrations are dealt with separately in calling function */
9302 lnProb += mp->treeAgePr.LnPriorProb(treeAge, mp->treeAgePr.priorParams);
9305 /* If tree is not calibrated or only root is calibrated, it is easy */
9306 for (i=j=0; i<t->nNodes-2; i++)
9308 if (t->allDownPass[i]->isDated == YES)
9313 /* Calculate simple probability f(tau|t_0) */
9314 lnProb += (nTips - 1.0)*log(2.0) - LnFactorial(nTips) - log(nTips-1.0) - (nTips - 2.0)*log(treeAge);
9315 assert (lnProb > NEG_INFINITY);
9319 /* We have a tree with interior or tip calibrations */
9321 /* Color subtrees by assigning an index 1,...,k to the x variable of each node,
9322 where k is the total number of separate subtrees. A subtree is characterized
9323 by having all interior nodes being unconstrained and all tips being either
9324 terminals or constrained interior nodes. The root of a subtree may be the
9325 root of the tree, or an interior node that is constrained and dated, or an
9326 interior node that is constrained but not dated. */
9328 ColorClusters (t->root->left, &i);
9330 /* Get the probability for each subtree */
9331 for (i=0; i<t->nIntNodes; i++)
9333 p = t->intDownPass[i];
9335 /* Skip unless this is the root of a subtree */
9336 if (p->anc->anc != NULL && p->isDated != YES)
9339 /* Save the root of the subtree */
9342 /* Create an array containing the sorted times */
9344 /* Allocate space for node depths */
9345 nDatedTips = NumDatedTips (root);
9346 nodeDepths = (MrBFlt *) SafeRealloc ((void *)nodeDepths, (nDatedTips+1)*sizeof(MrBFlt));
9348 /* Get the dated node depths and sort them. The call to GetDatedNodeDepths also
9349 returns the root node depth into nodeDepths, which is convenient. For now, this
9350 only works for dated tips, not for constrained but undated interior nodes. */
9351 GetDatedNodeDepths (root, nodeDepths);
9352 SortMrBFlt (nodeDepths, 0, nDatedTips); /* use index of left and right in call */
9354 /* Get probability due to the uniform node depths; we do not use first and last tip depth
9355 for obvious reasons (see figure above) */
9356 for (j=1; j<nDatedTips-1; j++)
9357 lnProb -= log ((root->nodeDepth - nodeDepths[j]) / clockRate);
9359 /* Get probability due to sorting of interior node depths */
9361 /* First get the potential number of lineages leaving each interval j at time nodeDepths[j+1] */
9362 nLineages = (int *) SafeRealloc ((void *)nLineages, nDatedTips*sizeof(int));
9363 for (j=0; j<nDatedTips; j++)
9366 /* Subtract interior nodes so that we get the real number of lineages leaving each interval.
9367 The number of lineages entering each interval is always 1 + the number of lineages
9368 leaving the previous interval. We utilize the fact here that the last node depth is the
9369 root node depth and is held in nodeDepths[nDatedTips] */
9370 for (j=0; j<t->nIntNodes; j++)
9372 p = t->intDownPass[j];
9373 if (p->x != root->x || p == root || p->isDated == YES)
9375 for (k=0; k<nDatedTips; k++)
9376 if (p->nodeDepth < nodeDepths[k+1])
9380 /* Now get the density effect of the sorting constraints */
9381 for (j=1; j<nDatedTips-1; j++)
9383 nLineagesIn = nLineages[j-1] + 1;
9384 if (j==nDatedTips-2)
9385 nLineagesOut = 2; /* skip the last segment and jump directly to root */
9387 nLineagesOut = nLineages[j];
9388 /* only calculate if ln different from 0 */
9389 if (nLineagesIn > 1 && nLineagesIn - nLineagesOut >= 1)
9391 lnProb += LnFactorial (nLineagesIn-1) - LnFactorial(nLineagesOut-1);
9395 /* Finally get the effect of the number of possible coalescent histories */
9396 for (j=1; j<nDatedTips; j++)
9398 nLineagesIn = nLineages[j-1] + 1;
9399 nLineagesOut = nLineages[j];
9400 if (nLineagesIn != nLineagesOut)
9402 lnProb += log(2.0) * (nLineagesIn - nLineagesOut);
9403 lnProb += LnFactorial (nLineagesOut) + LnFactorial (nLineagesOut-1);
9404 lnProb -= LnFactorial (nLineagesIn) + LnFactorial (nLineagesIn-1);
9408 /* Last but not least, change color of root so that it can be a tip in the next
9409 subtree (if we wanted to use the colors). */
9410 root->x = root->anc->x;
9417 assert (lnProb > NEG_INFINITY);
9423 /*------------------------------------------------------------------------
9425 | NewtonRaphsonBrlen: Find one maximum likelihood branch length using
9426 | the Newton-Raphson method. This function assumes that the tree is
9427 | a non-clock tree. For clock trees, you have to optimize the node
9430 ------------------------------------------------------------------------*/
9431 int NewtonRaphsonBrlen (Tree *t, TreeNode *p, int chain)
9433 int c, i, j, s, k, n, d, division, nIterations, maxNumIterations,
9435 MrBFlt vOld, *pi, *cijk, *eigenValues, *catRate, baseRate, length, theRate, tolerance,
9436 expLambdaV[64], pInvar=0.0, likeI=0.0, sum=0.0, sum1, sum2, beta, w, v, x, y, expBetaV,
9437 expWV, kappa, bigPi, *ptr;
9438 CLFlt *nSitesOfPat, *clP, *clA, *tiP, *tiP1, *tiP2, like, like1, like2, CLsum, CLsum1, CLsum2,
9439 freq, sumLike1, sumLike2, *lnScaler=NULL, *clInvar=NULL;
9442 /* TODO: Standard model (also check RES for ascertainment bias) */
9444 maxNumIterations = 5;
9448 /* reset f'(v) and f''(v) sums */
9449 sumLike1 = sumLike2 = 0.0;
9451 /* cycle over character partitions */
9452 for (d=0; d<t->nRelParts; d++)
9454 division = t->relParts[d];
9456 /* get pointer to model */
9457 m = &modelSettings[division];
9459 /* get number of model states */
9460 n = m->numModelStates;
9462 /* find conditional likelihoods */
9463 clP = m->condLikes[m->condLikeIndex[chain][p->index ]];
9464 clA = m->condLikes[m->condLikeIndex[chain][p->anc->index]];
9466 /* get state frequencies */
9467 pi = GetParamSubVals (m->stateFreq, chain, state[chain]);
9471 baseRate = GetRate (division, chain);
9473 /* get category rates */
9474 if (m->shape == NULL)
9477 catRate = GetParamSubVals (m->shape, chain, state[chain]);
9479 /* find category frequencies and some additional stuff for the invar model */
9480 if (m->pInvar == NULL)
9481 freq = (CLFlt) (1.0 / m->numGammaCats);
9484 /* invariable sites model */
9485 pInvar = * GetParamVals(m->pInvar, chain, state[chain]);
9486 freq = (CLFlt) ((1.0 - pInvar) / m->numGammaCats);
9487 baseRate /= (1.0 - pInvar);
9488 clInvar = m->invCondLikes;
9489 lnScaler = m->scalers[m->siteScalerIndex[chain]];
9492 /* find the branch lengths times any correction factor to make them
9493 in terms of expected number of substitutions per character */
9495 if (m->dataType == DNA || m->dataType == RNA)
9497 if (m->nucModelId == NUCMODEL_DOUBLET)
9499 else if (m->nucModelId == NUCMODEL_CODON)
9503 /* find nSitesOfPat */
9504 nSitesOfPat = numSitesOfPat + ((chainId[chain] % chainParams.numChains)*numCompressedChars) + m->compCharStart;
9506 /* get tiProbs for current length; use the scratch location */
9507 FlipTiProbsSpace(m, chain, p->index);
9508 m->TiProbs (p, division, chain);
9509 tiP = m->tiProbs[m->tiProbsIndex[chain][p->index]];
9510 FlipTiProbsSpace(m, chain, p->index);
9512 /* allocate space for first and second derivatives */
9513 tiP1 = (CLFlt *) SafeCalloc (2*m->tiProbLength, sizeof (CLFlt));
9516 tiP2 = tiP1 + m->tiProbLength;
9518 /* calculate first and second derivatives of P(v): P'(v) and P''(v) */
9520 if (m->TiProbs == &TiProbs_Fels || m->TiProbs == &TiProbs_Res)
9522 /* calculate beta */
9524 for (i=0; i<m->numModelStates; i++)
9525 for (j=i+1; j<m->numModelStates; j++)
9529 /* calculate derivatives */
9530 for (k=0; k<m->numGammaCats; k++)
9532 v = length * catRate[k] * baseRate;
9533 expBetaV = exp (- beta * v);
9534 for (i=0; i<m->numModelStates; i++)
9536 for (j=0; j<m->numModelStates; j++)
9540 x = - beta * (1.0 - pi[j]) * expBetaV;
9541 tiP1[index] = (CLFlt) x;
9542 tiP2[index] = (CLFlt) (- beta * x);
9546 x = beta * pi[j] * expBetaV;
9547 tiP1[index] = (CLFlt) x;
9548 tiP2[index] = (CLFlt) (- beta * x);
9555 else if (m->TiProbs == &TiProbs_Hky)
9558 kappa = *GetParamVals (m->tRatio, chain, state[chain]);
9560 /* calculate beta */
9562 for (i=0; i<m->numModelStates; i++)
9564 for (j=i+1; j<m->numModelStates; j++)
9567 sum += kappa * pi[i] * pi[j];
9569 sum += pi[i] * pi[j];
9574 /* calculate derivatives */
9575 for (k=0; k<m->numGammaCats; k++)
9577 v = length * catRate[k] * baseRate;
9578 expBetaV = exp (- beta * v);
9579 for (i=0; i<m->numModelStates; i++)
9581 for (j=0; j<m->numModelStates; j++)
9584 bigPi = pi[j] + pi[s];
9585 w = (1.0 + bigPi * (kappa - 1.0)) * beta;
9586 expWV = exp (- w * v);
9589 x = - beta * ((pi[j]/bigPi) - pi[j]) * expBetaV;
9590 y = - w * (pi[s]/bigPi) * expWV;
9591 tiP1[index] = (CLFlt) (x + y);
9592 tiP2[index] = (CLFlt) (- beta * x - w * y);
9594 else if (abs(i-j) == 2)
9596 x = - beta * pi[j] * ((pi[j]/bigPi) - pi[j]) * expBetaV;
9597 y = w * (pi[j]/bigPi) * expWV;
9598 tiP1[index] = (CLFlt) (x + y);
9599 tiP2[index] = (CLFlt) (- beta * x - w * y);
9603 x = beta * pi[j] * expBetaV;
9604 tiP1[index] = (CLFlt) x;
9605 tiP2[index] = (CLFlt) (- beta * x);
9612 else if (m->TiProbs == &TiProbs_Gen || m->TiProbs == &TiProbs_GenCov)
9614 /* get eigenvalues and cijk pointers */
9615 eigenValues = m->cijks[m->cijkIndex[chain]];
9616 cijk = eigenValues + (2 * n);
9618 /* calculate P'(v) and P''(v) */
9619 for (k=0; k<m->numGammaCats; k++)
9621 v = length * catRate[k];
9623 expLambdaV[s] = exp(eigenValues[s] * v);
9632 if (fabs(eigenValues[s]) > 0.000001)
9634 x = eigenValues[s] * (*ptr++) * expLambdaV[s];
9636 sum2 += eigenValues[s] * x;
9641 tiP1[index] = (CLFlt) ((sum1 < 0.0) ? 0.0 : sum);
9642 tiP2[index] = (CLFlt) ((sum2 < 0.0) ? 0.0 : sum);
9648 else if (m->TiProbs == &TiProbs_GenCov)
9650 /* get eigenvalues and cijk pointers */
9651 eigenValues = m->cijks[m->cijkIndex[chain]];
9652 cijk = eigenValues + (2 * n);
9654 /* calculate P'(v) and P''(v) */
9655 for (k=0; k<m->numTiCats; k++)
9657 if (m->numGammaCats > 1)
9658 v = length * catRate[k];
9662 expLambdaV[s] = exp(eigenValues[s] * v);
9670 if (fabs(eigenValues[s]) > 0.000001)
9672 x = eigenValues[s] * (*cijk++) * expLambdaV[s];
9674 sum2 += eigenValues[s] * x;
9677 tiP1[index] = (CLFlt) ((sum1 < 0.0) ? 0.0 : sum);
9678 tiP2[index] = (CLFlt) ((sum2 < 0.0) ? 0.0 : sum);
9682 /* get new eigenvalues and cijks */
9683 eigenValues += m->cijkLength / m->nCijkParts;
9684 cijk = eigenValues + 2 * n;
9687 /* calculate f(v), f'(v) and f''(v) for this partition */
9688 /* note that the scalers are irrelevant because they disappear when
9689 we take the derivative of the log likelihood */
9690 if (m->gibbsGamma == YES)
9692 /* find rate category index */
9693 rateCat = m->tiIndex + chain*m->numChars;
9694 for (c=0; c<m->numChars; c++)
9696 like = like1 = like2 = 0.0;
9698 if (r < m->numGammaCats)
9700 index = r*m->numModelStates*m->numModelStates;
9703 CLsum = CLsum1 = CLsum2 = 0.0;
9704 for (i=0; i<n; i++, index++)
9706 CLsum += clP[i] * tiP[index];
9707 CLsum1 += clP[i] * tiP1[index];
9708 CLsum2 += clP[i] * tiP2[index];
9710 like += CLsum * (CLFlt) pi[j] * clA[j];
9711 like1 += CLsum1 * (CLFlt) pi[j] * clA[j];
9712 like2 += CLsum2 * (CLFlt) pi[j] * clA[j];
9715 sumLike1 += nSitesOfPat[c] * (like1 / like);
9716 sumLike2 += nSitesOfPat[c] * (like2 * like - like1 * like1) / (like * like);
9723 for (c=0; c<m->numChars; c++)
9725 like = like1 = like2 = 0.0;
9727 for (k=0; k<m->numTiCats; k++)
9731 CLsum = CLsum1 = CLsum2 = 0.0;
9732 for (i=0; i<n; i++, index++)
9734 CLsum += clP[i] * tiP[index];
9735 CLsum1 += clP[i] * tiP1[index];
9736 CLsum2 += clP[i] * tiP2[index];
9738 like += CLsum * (CLFlt) pi[j] * clA[j];
9739 like1 += CLsum1 * (CLFlt) pi[j] * clA[j];
9740 like2 += CLsum2 * (CLFlt) pi[j] * clA[j];
9745 if (m->pInvar != NULL)
9747 /* get right like; like1 and like2 not affected */;
9749 likeI += (*clInvar++) * pi[i];
9751 if (lnScaler[c] < -200.0)
9753 /* we are not going to be able to exponentiate the scaling factor */
9756 /* forget about like; it is going to be insignificant compared to likeI */
9757 like = (CLFlt) likeI;
9761 /* treat likeI as if 0.0, that is, ignore it completely */
9762 like = like + (CLFlt)(0.0);
9765 else /* take both likeI and like into account */
9766 like = like + (CLFlt) (likeI * exp (-lnScaler[c]));
9768 sumLike1 += nSitesOfPat[c] * (like1 / like);
9769 sumLike2 += nSitesOfPat[c] * (like2 * like - like1 * like1) / (like * like);
9775 p->length -= sumLike2 / sumLike1;
9777 } while (fabs(p->length - vOld) > tolerance && nIterations < maxNumIterations);
9783 void NodeToNodeDistances (Tree *t, TreeNode *fromNode)
9788 /* set all distances to 0.0 and also set marks on all nodes to NO */
9789 for (i=0; i<t->nNodes; i++)
9791 p = t->allDownPass[i];
9796 /* find distances, and mark path, below "fromNode" */
9797 for (i=0; i<t->nNodes; i++)
9799 p = t->allDownPass[i];
9804 if (p->left != NULL && p->right != NULL && p->anc != NULL)
9806 if (p->left->x == YES)
9809 p->d = p->left->d + p->left->length;
9811 else if (p->right->x == YES)
9814 p->d = p->right->d + p->right->length;
9819 /* find all other distances */
9820 for (i=t->nNodes-1; i>=0; i--)
9822 p = t->allDownPass[i];
9828 p->d = p->left->d + p->left->length;
9834 p->d = p->anc->d + p->length;
9841 int NumCppEvents (Param *p, int chain)
9843 int i, *nEvents, sumEvents;
9845 nEvents = p->nEvents[2*chain+state[chain]];
9848 for (i=0; i<2*numLocalTaxa-2; i++)
9849 sumEvents += nEvents[i];
9855 /*----------------------------------------------------------------------
9857 | OpenNewMBPrintFile: Open a file the first time for printing
9859 ------------------------------------------------------------------------*/
9860 FILE *OpenNewMBPrintFile (char *fileName)
9865 /* Open file, use noWarn to determine if the user should be prompted
9866 to have the file over-written or appended. */
9869 /* overwrite or append file, if already present */
9870 if ((fp = TestOpenTextFileR(fileName)) != NULL)
9873 if (autoOverwrite == NO)
9875 MrBayesPrint ("%s Appending to file \"%s\"\n", spacer, fileName);
9876 return (OpenTextFileA(fileName));
9879 MrBayesPrint ("%s Overwriting file \"%s\"\n", spacer, fileName);
9881 return (OpenTextFileW(fileName));
9885 /* prompt user if file is already present */
9886 if ((fp = TestOpenTextFileR(fileName)) != NULL)
9889 MrBayesPrint ("\n");
9890 MrBayesPrint ("%s File \"%s\" already exists\n", spacer, fileName);
9891 overWrite = WantTo ("Overwrite information in this file");
9893 if (overWrite == YES)
9895 MrBayesPrint ("%s Overwriting file \"%s\"\n", spacer, fileName);
9896 return (OpenTextFileW(fileName));
9900 MrBayesPrint ("%s Appending to file \"%s\"\n", spacer, fileName);
9901 return (OpenTextFileA(fileName));
9907 /* file is not present */
9908 return (OpenTextFileW(fileName));
9914 int PickProposal (RandLong *seed, int chainIndex)
9919 ran = RandomNumber(seed);
9921 for (i=0; usedMoves[i]->cumProposalProb[chainIndex] <= ran; i++);
9927 /* Calculate positive selection probabilities */
9928 int PosSelProbs (TreeNode *p, int division, int chain)
9930 int c, j, k, nStates;
9931 MrBFlt catLike, *like, *bs, *omegaCatFreq, *omega,
9936 /* find model partition */
9937 m = &modelSettings[division];
9939 /* allocate space for conditional likelihood pointer array and site likelihood array */
9940 clP = (CLFlt **) calloc (m->numOmegaCats, sizeof(CLFlt *));
9941 like = (MrBFlt *) calloc (m->numOmegaCats, sizeof(MrBFlt));
9944 MrBayesPrint ("%s ERROR: Out of memory in PosSelProbs\n", spacer);
9948 /* number of states */
9949 nStates = m->numModelStates;
9951 /* find conditional likelihoods */
9952 clP[0] = m->condLikes[m->condLikeIndex[chain][p->index]];
9953 for (k=1; k<m->numOmegaCats; k++)
9954 clP[k] = clP[0] + k*m->numModelStates*m->numChars;
9956 /* find base frequencies */
9957 bs = GetParamSubVals (m->stateFreq, chain, state[chain]);
9959 /* find category frequencies */
9960 omegaCatFreq = GetParamSubVals (m->omega, chain, state[chain]);
9962 /* get category omegas */
9963 omega = GetParamVals (m->omega, chain, state[chain]);
9965 /* find posSelProbs */
9966 ps = posSelProbs + m->compCharStart;
9967 for (c=0; c<m->numChars; c++)
9970 for (k=0; k<m->numOmegaCats; k++)
9974 for (j=0; j<nStates; j++)
9975 catLike += clP[k][j] * bs[j];
9976 like[k] = catLike * omegaCatFreq[k];
9981 for (k=0; k<m->numOmegaCats; k++)
9984 posProb += like[k] / sum;
9996 #if defined (SSE_ENABLED)
9997 /* Calculate positive selection probabilities (SSE version) */
9998 int PosSelProbs_SSE (TreeNode *p, int division, int chain)
10000 int i, c1, c2, j, k, nStates;
10001 CLFlt **catLike, *siteLike;
10002 MrBFlt *bs, *omegaCatFreq, *omega,
10004 __m128 m1, m2, *clPtr, **clP, mSiteLike, *mCatLike;
10007 /* find model partition */
10008 m = &modelSettings[division];
10010 /* number of states */
10011 nStates = m->numModelStates;
10013 /* find base frequencies */
10014 bs = GetParamSubVals (m->stateFreq, chain, state[chain]);
10016 /* find category frequencies */
10017 omegaCatFreq = GetParamSubVals (m->omega, chain, state[chain]);
10019 /* get category omegas */
10020 omega = GetParamVals (m->omega, chain, state[chain]);
10021 /* allocate space for category likelihood arrays */
10022 catLike = (CLFlt **) calloc (m->numOmegaCats, sizeof(CLFlt *));
10023 mCatLike = (__m128 *) calloc (m->numOmegaCats, sizeof(__m128));
10024 if (!catLike || !mCatLike)
10026 MrBayesPrint ("%s ERROR: Out of memory in PosSelProbs_SSE\n", spacer);
10030 /* find conditional likelihood pointers */
10031 clPtr = (__m128 *) m->condLikes[m->condLikeIndex[chain][p->index]];
10033 for (k=0; k<m->numOmegaCats; k++)
10036 clPtr += m->numSSEChars * nStates;
10037 catLike[k] = (CLFlt *) (&(mCatLike[k]));
10039 siteLike = (CLFlt *) (&mSiteLike);
10041 /* find posSelProbs */
10042 ps = posSelProbs + m->compCharStart;
10043 for (c1=c2=0; c1<m->numSSEChars; c1++)
10045 mSiteLike = _mm_setzero_ps ();
10046 for (k=0; k<m->numOmegaCats; k++)
10048 mCatLike[k] = _mm_setzero_ps();
10049 m1 = _mm_setzero_ps ();
10050 for (j=0; j<nStates; j++)
10052 m2 = _mm_mul_ps (clP[k][j], _mm_set1_ps ((CLFlt)bs[j]));
10053 m1 = _mm_add_ps (m1, m2);
10055 mCatLike[k] = _mm_mul_ps (m1, _mm_set1_ps ((CLFlt)omegaCatFreq[k]));
10056 mSiteLike = _mm_add_ps (mSiteLike, mCatLike[k]);
10060 for (i=0; i<FLOATS_PER_VEC && c2 < m->numChars; ++i, ++c2)
10063 for (k=0; k<m->numOmegaCats; k++)
10065 if (omega[k] > 1.0)
10067 posProb += catLike[k][i] / siteLike[i];
10082 /* Calculate omega values for each site */
10083 int SiteOmegas (TreeNode *p, int division, int chain)
10085 int c, j, k, nStates;
10086 MrBFlt catLike, *like, *bs, *omegaCatFreq, *omega,
10087 siteOmega, *ps, sum;
10091 /* find model partition */
10092 m = &modelSettings[division];
10094 /* allocate space for conditional likelihood pointer array and site likelihood array */
10095 clP = (CLFlt **) calloc (m->numOmegaCats, sizeof(CLFlt *));
10096 like = (MrBFlt *) calloc (m->numOmegaCats, sizeof(MrBFlt));
10099 MrBayesPrint ("%s ERROR: Out of memory in SiteOmegas\n", spacer);
10103 /* number of states */
10104 nStates = m->numModelStates;
10106 /* find conditional likelihoods */
10107 clP[0] = m->condLikes[m->condLikeIndex[chain][p->index]];
10108 for (k=1; k<m->numOmegaCats; k++)
10109 clP[k] = clP[0] + k*m->numModelStates*m->numChars;
10111 /* find base frequencies */
10112 bs = GetParamSubVals (m->stateFreq, chain, state[chain]);
10114 /* find category frequencies */
10115 omegaCatFreq = GetParamSubVals (m->omega, chain, state[chain]);
10117 /* get category omegas */
10118 omega = GetParamVals (m->omega, chain, state[chain]);
10120 /* find site omegas (using posSelProbs space) */
10121 ps = posSelProbs + m->compCharStart;
10122 for (c=0; c<m->numChars; c++)
10125 for (k=0; k<m->numOmegaCats; k++)
10129 for (j=0; j<nStates; j++)
10130 catLike += clP[k][j] * bs[j];
10131 like[k] = catLike * omegaCatFreq[k];
10136 for (k=0; k<m->numOmegaCats; k++)
10138 siteOmega += (like[k]/sum) * omega[k];
10150 #if defined (SSE_ENABLED)
10151 /* Calculate omega values for each site (SSE version) */
10152 int SiteOmegas_SSE (TreeNode *p, int division, int chain)
10154 int i, c1, c2, j, k, nStates;
10155 CLFlt **catLike, *siteLike;
10156 MrBFlt *bs, *omegaCatFreq, *omega,
10158 __m128 m1, m2, *clPtr, **clP, mSiteLike, *mCatLike;
10161 /* find model partition */
10162 m = &modelSettings[division];
10164 /* number of states */
10165 nStates = m->numModelStates;
10167 /* find base frequencies */
10168 bs = GetParamSubVals (m->stateFreq, chain, state[chain]);
10170 /* find category frequencies */
10171 omegaCatFreq = GetParamSubVals (m->omega, chain, state[chain]);
10173 /* get category omegas */
10174 omega = GetParamVals (m->omega, chain, state[chain]);
10176 /* allocate space for category likelihood arrays */
10177 catLike = (CLFlt **) calloc (m->numOmegaCats, sizeof(CLFlt *));
10178 mCatLike = (__m128 *) calloc (m->numOmegaCats, sizeof(__m128));
10179 if (!catLike || !mCatLike)
10181 MrBayesPrint ("%s ERROR: Out of memory in SiteOmegas_SSE\n", spacer);
10185 /* find conditional likelihood pointers */
10186 clPtr = (__m128 *) m->condLikes[m->condLikeIndex[chain][p->index]];
10188 for (k=0; k<m->numOmegaCats; k++)
10191 clPtr += m->numSSEChars * nStates;
10192 catLike[k] = (CLFlt *) (&(mCatLike[k]));
10194 siteLike = (CLFlt *) (&mSiteLike);
10196 /* find site omegas (using posSelProbs space) */
10197 ps = posSelProbs + m->compCharStart;
10198 for (c1=c2=0; c1<m->numSSEChars; c1++)
10200 mSiteLike = _mm_setzero_ps ();
10201 for (k=0; k<m->numOmegaCats; k++)
10203 mCatLike[k] = _mm_setzero_ps();
10204 m1 = _mm_setzero_ps ();
10205 for (j=0; j<nStates; j++)
10207 m2 = _mm_mul_ps (clP[k][j], _mm_set1_ps ((CLFlt)bs[j]));
10208 m1 = _mm_add_ps (m1, m2);
10210 mCatLike[k] = _mm_mul_ps (m1, _mm_set1_ps ((CLFlt)omegaCatFreq[k]));
10211 mSiteLike = _mm_add_ps (mSiteLike, mCatLike[k]);
10215 for (i=0; i<FLOATS_PER_VEC && c2 < m->numChars; ++i, ++c2)
10218 for (k=0; k<m->numOmegaCats; k++)
10220 siteOmega += (catLike[k][i] / siteLike[i]) * omega[k];
10222 ps[c2] = siteOmega;
10234 /*----------------------------------------------------------------------
10236 | PreparePrintFiles: Prepare .t, .p, and .mcmc files for printing
10238 ------------------------------------------------------------------------*/
10239 int PreparePrintFiles (void)
10241 int i, n, previousResults, oldAutoOverwrite, oldNoWarn;
10242 char localFileName[100], fileName[220], bkupName[220];
10245 #if defined (MPI_ENABLED)
10250 oldNoWarn = noWarn;
10251 oldAutoOverwrite = autoOverwrite;
10253 /* Allocate space for file pointers */
10254 if (memAllocs[ALLOC_FILEPOINTERS] == YES)
10256 MrBayesPrint ("%s File pointers already allocated in PreparePrintFiles\n", spacer);
10263 fpParm = (FILE **) SafeCalloc (chainParams.numRuns, sizeof (FILE *));
10264 if (fpParm == NULL)
10266 MrBayesPrint ("%s Could not allocate fpParm in PreparePrintFiles\n", spacer);
10269 memAllocs[ALLOC_FILEPOINTERS] = YES;
10270 fpTree = (FILE ***) SafeCalloc (chainParams.numRuns, sizeof (FILE **));
10271 if (fpTree == NULL)
10273 MrBayesPrint ("%s Could not allocate fpTree in PreparePrintFiles\n", spacer);
10276 fpTree[0] = (FILE **) SafeCalloc (numTrees*chainParams.numRuns, sizeof (FILE *));
10277 if (fpTree[0] == NULL)
10279 MrBayesPrint ("%s Could not allocate fpTree[0] in PreparePrintFiles\n", spacer);
10282 for (i=1; i<chainParams.numRuns; i++)
10283 fpTree[i] = fpTree[0] + i*numTrees;
10285 /* Get root of local file name */
10286 strcpy (localFileName, chainParams.chainFileName);
10288 /* Determine whether to overwrite files */
10291 previousResults = NO;
10292 if (chainParams.mcmcDiagn == YES)
10294 sprintf (fileName, "%s.mcmc", localFileName);
10295 if ((tempFile = TestOpenTextFileR(fileName)) != NULL)
10298 previousResults = YES;
10301 for (n=0; n<chainParams.numRuns; n++)
10303 if (chainParams.numRuns == 1)
10304 sprintf (fileName, "%s.p", localFileName);
10306 sprintf (fileName, "%s.run%d.p", localFileName, n+1);
10307 if ((tempFile = TestOpenTextFileR(fileName)) != NULL)
10310 previousResults = YES;
10313 for (i=0; i<numTrees; i++)
10315 if (numTrees == 1 && chainParams.numRuns == 1)
10316 sprintf (fileName, "%s.t", localFileName);
10317 else if (numTrees > 1 && chainParams.numRuns == 1)
10318 sprintf (fileName, "%s.tree%d.t", localFileName, i+1);
10319 else if (numTrees == 1 && chainParams.numRuns > 1)
10320 sprintf (fileName, "%s.run%d.t", localFileName, n+1);
10322 sprintf (fileName, "%s.tree%d.run%d.t", localFileName, i+1, n+1);
10323 if ((tempFile = TestOpenTextFileR(fileName)) != NULL)
10326 previousResults = YES;
10330 if (previousResults == YES)
10332 MrBayesPrint("\n");
10333 MrBayesPrint("%s There are results from a previous run saved using the same filename(s).\n", spacer);
10334 if (WantTo("Do you want to overwrite these results") == YES)
10336 MrBayesPrint("\n");
10338 autoOverwrite = YES;
10342 MrBayesPrint("\n");
10343 MrBayesPrint("%s Please specify a different file name before running the mcmc analysis.\n", spacer);
10344 MrBayesPrint("%s You can do that using 'mcmc filename=<name>'. You can also move or\n", spacer);
10345 MrBayesPrint("%s rename the old result files.\n", spacer);
10351 /* Prepare the .mcmc file */
10352 if (chainParams.mcmcDiagn == YES)
10354 sprintf (fileName, "%s.mcmc", chainParams.chainFileName);
10355 if ((fpMcmc = OpenNewMBPrintFile (fileName)) == NULL)
10357 noWarn = oldNoWarn;
10358 autoOverwrite = oldAutoOverwrite;
10363 /* Prepare the .p and .t files */
10364 for (n=0; n<chainParams.numRuns; n++)
10366 if (chainParams.numRuns == 1)
10367 sprintf (fileName, "%s.p", localFileName);
10369 sprintf (fileName, "%s.run%d.p", localFileName, n+1);
10370 if ((fpParm[n] = OpenNewMBPrintFile (fileName)) == NULL)
10372 noWarn = oldNoWarn;
10373 autoOverwrite = oldAutoOverwrite;
10377 for (i=0; i<numTrees; i++)
10379 if (numTrees == 1 && chainParams.numRuns == 1)
10380 sprintf (fileName, "%s.t", localFileName);
10381 else if (numTrees > 1 && chainParams.numRuns == 1)
10382 sprintf (fileName, "%s.tree%d.t", localFileName, i+1);
10383 else if (numTrees == 1 && chainParams.numRuns > 1)
10384 sprintf (fileName, "%s.run%d.t", localFileName, n+1);
10386 sprintf (fileName, "%s.tree%d.run%d.t", localFileName, i+1, n+1);
10387 if ((fpTree[n][i] = OpenNewMBPrintFile (fileName)) == NULL)
10389 noWarn = oldNoWarn;
10390 autoOverwrite = oldAutoOverwrite;
10396 /* Prepare the .ss file */
10397 if (chainParams.isSS == YES)
10399 sprintf (fileName, "%s.ss", chainParams.chainFileName);
10400 if ((fpSS = OpenNewMBPrintFile (fileName)) == NULL)
10402 noWarn = oldNoWarn;
10403 autoOverwrite = oldAutoOverwrite;
10408 /* Remove previous chekpoint file if present */
10409 sprintf (fileName, "%s%s.ckp", workingDir, chainParams.chainFileName);
10410 strcpy (bkupName, fileName);
10411 strcat (bkupName, "~");
10413 rename (fileName, bkupName);
10415 # if defined (PRINT_DUMP)
10416 fpDump = (FILE **) SafeCalloc (chainParams.numRuns, sizeof (FILE *));
10418 for (n=0; n<chainParams.numRuns; n++)
10420 if (chainParams.numRuns == 1)
10421 sprintf (fileName, "%s.dump", localFileName);
10423 sprintf (fileName, "%s.run%d.dump", localFileName, n+1);
10425 if ((fpDump[n] = OpenNewMBPrintFile (fileName)) == NULL)
10434 /*----------------------------------------------------------------
10436 | PrintAncStates_Bin: print ancestral states after final pass
10437 | Binary model with or without rate variation
10439 -----------------------------------------------------------------*/
10440 int PrintAncStates_Bin (TreeNode *p, int division, int chain)
10444 CLFlt *clFP, *cL, sum, **clP;
10446 int tempStrSize = TEMPSTRSIZE;
10449 tempStr = (char *) SafeMalloc((size_t)tempStrSize * sizeof(char));
10452 MrBayesPrint ("%s Problem allocating tempString (%d)\n", spacer, tempStrSize * sizeof(char));
10456 /* find model settings for this division */
10457 m = &modelSettings[division];
10459 /* find state frequencies */
10460 bs = GetParamSubVals (m->stateFreq, chain, state[chain]);
10462 /* find frequencies of rate categories */
10463 freq = 1.0 / m->numGammaCats;
10465 /* find the conditional likelihoods from the final pass */
10466 clFP = m->condLikes[m->condLikeScratchIndex[p->index]];
10469 for (k=0; k<m->numGammaCats; k++)
10472 clFP += m->numChars * m->numModelStates;
10475 /* find the preallocated working space */
10476 cL = m->ancStateCondLikes;
10478 /* cycle over the compressed characters */
10479 for (c=0; c<m->numChars; c++)
10481 cL[0] = cL[1] = 0.0;
10482 for (k=0; k<m->numGammaCats; k++)
10484 cL[0] += clP[k][0];
10485 cL[1] += clP[k][1];
10488 cL[0] *= (CLFlt) (bs[0] * freq);
10489 cL[1] *= (CLFlt) (bs[1] * freq);
10490 sum = cL[0] + cL[1];
10491 assert (cL[0]==cL[0]);
10492 assert (cL[1]==cL[1]);
10493 assert (sum<9999999999999999999999999999999.0);
10496 assert (cL[0]==cL[0]);
10497 assert (cL[1]==cL[1]);
10501 /* print the resulting conditional likelihoods cycling over uncompressed chars */
10502 for (c=0; c<numChar; c++)
10504 if (charInfo[c].isExcluded == YES || partitionId[c][partitionNum] != division+1)
10506 i = compCharPos[c] - m->compCharStart;
10507 cL = m->ancStateCondLikes + (i*2);
10508 SafeSprintf (&tempStr, &tempStrSize, "\t%s", MbPrintNum(cL[0]));
10509 if (AddToPrintString (tempStr) == ERROR) return (ERROR);
10510 SafeSprintf (&tempStr, &tempStrSize, "\t%s", MbPrintNum(cL[1]));
10511 if (AddToPrintString (tempStr) == ERROR) return (ERROR);
10519 /*----------------------------------------------------------------
10521 | PrintAncStates_Gen: print ancestral states after final pass
10522 | General model with or without rate variation
10524 -----------------------------------------------------------------*/
10525 int PrintAncStates_Gen (TreeNode *p, int division, int chain)
10527 int c, i, k, nStates, hasPInvar, nGammaCats;
10528 const int *rateCat;
10530 CLFlt *cL, sum, pInvar=0.0, freq, f, bs[64];
10531 const CLFlt *clFP, *clInvar=NULL, *lnScaler, **clP;
10532 char *tempStr, *printedChar;
10533 int tempStrSize = TEMPSTRSIZE;
10536 tempStr = (char *) SafeMalloc((size_t)tempStrSize * sizeof(char));
10539 MrBayesPrint ("%s Problem allocating tempString (%d)\n", spacer, tempStrSize * sizeof(char));
10543 if (!strcmp(modelParams[division].nucModel,"Codon") || !strcmp(modelParams[division].nucModel,"Protein") || !strcmp(modelParams[division].nucModel,"Doublet"))
10545 assert (modelParams[division].dataType == DNA || modelParams[division].dataType == RNA);
10546 /* Note that we can have matrix with Protein datatype which is not and should not be covered here */
10547 printedChar = (char *) SafeMalloc (numChar*sizeof(char));
10551 printedChar = NULL;
10555 /* find model settings for this division */
10556 m = &modelSettings[division];
10558 /* find number of states */
10559 nStates = m->numModelStates;
10561 /* find state frequencies */
10562 bsVals = GetParamSubVals (m->stateFreq, chain, state[chain]);
10563 for (i=0; i<nStates; i++)
10564 bs[i] = (CLFlt) bsVals[i];
10566 /* find invar cond likes */
10567 if (m->pInvar == NULL)
10572 clInvar = m->invCondLikes;
10573 pInvar = (CLFlt) *GetParamVals (m->pInvar, chain, state[chain]);
10576 /* find number of rate categories */
10577 nGammaCats = m->numGammaCats;
10579 /* find frequencies of rate categories (only relevant if gibbsGamma == NO) */
10580 freq = ((CLFlt)1.0 - pInvar) / nGammaCats;
10582 /* find site scaler */
10583 lnScaler = m->scalers[m->siteScalerIndex[chain]];
10585 /* find rate category index */
10586 rateCat = m->tiIndex + chain*m->numChars;
10588 /* find the conditional likelihoods from the final pass */
10589 clFP = m->condLikes[m->condLikeScratchIndex[p->index]];
10591 /* find the preallocated working space */
10592 cL = m->ancStateCondLikes;
10594 /* cycle over the compressed characters */
10595 if (m->gibbsGamma == YES)
10597 for (c=0; c<m->numChars; c++)
10600 if (rateCat[c] < nGammaCats)
10602 for (i=0; i<nStates; i++)
10604 cL[i] = *(clFP++) * bs[i];
10607 clInvar += nStates;
10611 for (i=0; i<nStates; i++)
10613 cL[i] = *(clInvar++) * bs[i];
10618 for (i=0; i<nStates; i++)
10625 /* find conditional likelihood pointers */
10626 clP = (const CLFlt**)m->clP;
10627 for (k=0; k<m->numGammaCats; k++)
10630 clFP += m->numChars * m->numModelStates;
10632 for (c=0; c<m->numChars; c++)
10634 for (i=0; i<nStates; i++)
10636 for (k=0; k<nGammaCats; k++)
10638 for (i=0; i<nStates; i++)
10639 cL[i] += *(clP[k]++);
10641 for (i=0; i<nStates; i++)
10644 if (hasPInvar == YES && pInvar > 0)
10647 for (i=0; i<nStates; i++)
10651 if (lnScaler[c] < -100.0)
10653 /* only invar cond likes are relevant */
10654 for (i=0; i<nStates; i++)
10655 cL[i] = clInvar[i] * bs[i] * pInvar;
10659 f = (CLFlt) exp(lnScaler[c]) * freq;
10660 for (i=0; i<nStates; i++)
10661 cL[i] = clInvar[i] * bs[i] * pInvar + cL[i] * f;
10664 clInvar += nStates;
10668 for (i=0; i<nStates; i++)
10670 assert (sum > 0.0);
10671 for (i=0; i<nStates; i++)
10677 /* print the resulting conditional likelihoods cycling over uncompressed chars */
10679 for (c=0; c<numChar; c++)
10680 printedChar[c] = NO;
10682 for (c=0; c<numChar; c++)
10684 if (charInfo[c].isExcluded == YES || partitionId[c][partitionNum] != division+1 || (printedChar &&
10685 printedChar[c] == YES))
10687 i = compCharPos[c] - m->compCharStart;
10688 cL = m->ancStateCondLikes + (i*nStates);
10691 for (i=c+1; i<numChar; i++)
10692 if (charInfo[c].charId == charInfo[i].charId)
10693 printedChar[i] = YES;
10695 for (i=0; i<nStates; i++)
10697 SafeSprintf (&tempStr, &tempStrSize, "\t%s", MbPrintNum(cL[i]));
10698 if (AddToPrintString (tempStr) == ERROR) return (ERROR);
10702 free (printedChar);
10707 /*----------------------------------------------------------------
10709 | PrintAncStates_NUC4: print ancestral states after final pass
10710 | 4-state nucleotide model with or without rate variation
10712 -----------------------------------------------------------------*/
10713 int PrintAncStates_NUC4 (TreeNode *p, int division, int chain)
10715 int c, i, k, *rateCat, hasPInvar, nGammaCats;
10717 CLFlt *cL, sum, pInvar=0.0, bs[4], freq, f;
10718 const CLFlt *clFP, *clInvar=NULL, *lnScaler,**clP;
10720 int tempStrSize = TEMPSTRSIZE;
10723 tempStr = (char *) SafeMalloc((size_t)tempStrSize * sizeof(char));
10726 MrBayesPrint ("%s Problem allocating tempString (%d)\n", spacer, tempStrSize * sizeof(char));
10730 /* find model settings for this division */
10731 m = &modelSettings[division];
10733 /* find state frequencies */
10734 bsVals = GetParamSubVals (m->stateFreq, chain, state[chain]);
10735 bs[A] = (CLFlt) bsVals[A];
10736 bs[C] = (CLFlt) bsVals[C];
10737 bs[G] = (CLFlt) bsVals[G];
10738 bs[T] = (CLFlt) bsVals[T];
10740 /* find invar cond likes */
10741 if (m->pInvar == NULL)
10746 clInvar = m->invCondLikes;
10747 pInvar = (CLFlt) *GetParamVals (m->pInvar, chain, state[chain]);
10750 /* find number of rate categories */
10751 nGammaCats = m->numGammaCats;
10753 /* find frequencies of rate categories (only relevant if gibbsGamma == NO) */
10754 if (hasPInvar == NO)
10755 freq = (CLFlt) 1.0 / nGammaCats;
10757 freq = ((CLFlt)1.0 - pInvar) / nGammaCats;
10759 /* find site scaler */
10760 lnScaler = m->scalers[m->siteScalerIndex[chain]];
10762 /* find rate category index */
10763 rateCat = m->tiIndex + chain*m->numChars;
10765 /* find the conditional likelihoods from the final pass */
10766 clFP = m->condLikes[m->condLikeScratchIndex[p->index]];
10768 /* find the preallocated working space */
10769 cL = m->ancStateCondLikes;
10771 /* cycle over the compressed characters */
10772 if (m->gibbsGamma == YES)
10774 for (c=0; c<m->numChars; c++)
10776 if (rateCat[c] < nGammaCats)
10778 cL[A] = clFP[A] * (CLFlt) bs[A];
10779 cL[C] = clFP[C] * (CLFlt) bs[C];
10780 cL[G] = clFP[G] * (CLFlt) bs[G];
10781 cL[T] = clFP[T] * (CLFlt) bs[T];
10785 cL[A] = clInvar[A] * (CLFlt) bs[A];
10786 cL[C] = clInvar[C] * (CLFlt) bs[C];
10787 cL[G] = clInvar[G] * (CLFlt) bs[G];
10788 cL[T] = clInvar[T] * (CLFlt) bs[T];
10790 sum = cL[A] + cL[C] + cL[G] + cL[T];
10802 /* find conditional likelihood pointers */
10803 clP = (const CLFlt**)m->clP;
10804 for (k=0; k<m->numGammaCats; k++)
10807 clFP += m->numChars * m->numModelStates;
10810 for (c=0; c<m->numChars; c++)
10812 cL[A] = cL[C] = cL[G] = cL[T] = 0.0;
10813 for (k=0; k<nGammaCats; k++)
10815 cL[A] += clP[k][A];
10816 cL[C] += clP[k][C];
10817 cL[G] += clP[k][G];
10818 cL[T] += clP[k][T];
10825 if (hasPInvar == YES)
10827 sum = clInvar[A] + clInvar[C] + clInvar[G] + clInvar[T];
10830 if (lnScaler[c] < -100.0)
10832 /* only invar cond likes are relevant */
10833 cL[A] = clInvar[A] * bs[A] * pInvar;
10834 cL[C] = clInvar[C] * bs[C] * pInvar;
10835 cL[G] = clInvar[G] * bs[G] * pInvar;
10836 cL[T] = clInvar[T] * bs[T] * pInvar;
10840 f = (CLFlt)exp(lnScaler[c]) * freq;
10841 cL[A] = clInvar[A] * bs[A] * pInvar + cL[A] * f;
10842 cL[C] = clInvar[C] * bs[C] * pInvar + cL[C] * f;
10843 cL[G] = clInvar[G] * bs[G] * pInvar + cL[G] * f;
10844 cL[T] = clInvar[T] * bs[T] * pInvar + cL[T] * f;
10849 sum = cL[A] + cL[C] + cL[G] + cL[T];
10858 /* print the resulting conditional likelihoods cycling over uncompressed chars */
10859 for (c=0; c<numChar; c++)
10861 if (charInfo[c].isExcluded == YES || partitionId[c][partitionNum] != division+1)
10863 i = compCharPos[c] - m->compCharStart;
10864 cL = m->ancStateCondLikes + (i*4);
10865 SafeSprintf (&tempStr, &tempStrSize, "\t%s", MbPrintNum(cL[A]));
10866 if (AddToPrintString (tempStr) == ERROR) return ERROR;
10867 SafeSprintf (&tempStr, &tempStrSize, "\t%s", MbPrintNum(cL[C]));
10868 if (AddToPrintString (tempStr) == ERROR) return ERROR;
10869 SafeSprintf (&tempStr, &tempStrSize, "\t%s", MbPrintNum(cL[G]));
10870 if (AddToPrintString (tempStr) == ERROR) return ERROR;
10871 SafeSprintf (&tempStr, &tempStrSize, "\t%s", MbPrintNum(cL[T]));
10872 if (AddToPrintString (tempStr) == ERROR) return ERROR;
10879 /*----------------------------------------------------------------
10881 | PrintAncStates_Std: print ancestral states after final pass
10882 | Standard model with or without rate variation
10884 -----------------------------------------------------------------*/
10885 int PrintAncStates_Std (TreeNode *p, int division, int chain)
10887 int c, i, j, k, s, nStates, numReps;
10888 MrBFlt *bsBase, *bs, freq;
10889 CLFlt *clFP, *cL, sum,** clP;
10891 int tempStrSize = TEMPSTRSIZE;
10894 tempStr = (char *) SafeMalloc((size_t)tempStrSize * sizeof(char));
10897 MrBayesPrint ("%s Problem allocating tempString (%d)\n", spacer, tempStrSize * sizeof(char));
10901 /* find model settings for this division */
10902 m = &modelSettings[division];
10904 /* find state frequencies, base index */
10905 bsBase = GetParamStdStateFreqs (m->stateFreq, chain, state[chain]);
10907 /* find the conditional likelihoods from the final pass */
10908 clFP = m->condLikes[m->condLikeScratchIndex[p->index]];
10911 for (c=0; c<m->numChars; c++)
10913 if (m->nStates[c] == 2)
10914 numReps += m->numBetaCats * 2;
10916 numReps += m->nStates[c];
10919 /* find conditional likelihood pointers */
10921 for (k=0; k<m->numGammaCats; k++)
10927 /* find the preallocated working space */
10928 cL = m->ancStateCondLikes;
10930 /* cycle over the compressed characters */
10931 for (c=0; c<m->numChars; c++)
10933 nStates = m->nStates[c];
10934 bs = bsBase + m->bsIndex[c];
10936 for (s=0; s<nStates; s++)
10941 freq = 1.0 / (m->numBetaCats * m->numGammaCats);
10942 for (i=0; i<m->numBetaCats; i++)
10944 for (k=0; k<m->numGammaCats; k++)
10946 for (s=0; s<nStates; s++)
10947 cL[s] += clP[k][s] * (CLFlt)(bs[s] * freq);
10955 freq = 1.0 / (m->numGammaCats);
10956 for (k=0; k<m->numGammaCats; k++)
10958 for (s=0; s<nStates; s++)
10959 cL[s] += clP[k][s] * (CLFlt)(bs[s] * freq);
10965 for (s=0; s<nStates; s++)
10968 assert (sum != 0.0);
10970 for (s=0; s<nStates; s++)
10976 /* print the resulting conditional likelihoods cycling over uncompressed chars */
10977 for (c=0; c<numChar; c++)
10979 if (charInfo[c].isExcluded == YES || partitionId[c][partitionNum] != division+1)
10982 k = compCharPos[c] - m->compCharStart;
10983 for (i=j=0; i<k; i++)
10984 j += m->nStates[i];
10985 cL = m->ancStateCondLikes + j;
10987 for (i=0; i<m->nStates[k]; i++)
10989 SafeSprintf (&tempStr, &tempStrSize, "\t%s", MbPrintNum(cL[i]));
10990 if (AddToPrintString (tempStr) == ERROR) return (ERROR);
10998 /*-----------------------------------------------------------------------
11000 | PrintCheckPoint: Print checkpoint to file
11002 ------------------------------------------------------------------------*/
11003 int PrintCheckPoint (int gen)
11005 int i, j, k, k1, nErrors=0, run, chn, nValues, tempStrSize = TEMPSTRSIZE,
11006 hasEvents, *intValue, id, oldPrecision;
11007 char bkupFileName[220], oldBkupFileName[220], ckpFileName[220], *tempString=NULL;
11008 MrBFlt *value, clockRate;
11009 Param *p = NULL, *subParm = NULL;
11013 /*ModelInfo *m = NULL;*/
11015 #if defined (MPI_ENABLED)
11016 int sumErrors=0,ierror;
11020 /* use high precision for checkpointing */
11021 oldPrecision = precision;
11024 /* allocate tempString */
11025 if ((tempString = (char *) SafeCalloc (tempStrSize, sizeof(char))) == NULL)
11028 #if defined (MPI_ENABLED)
11034 /* figure out check-point file names */
11035 sprintf(ckpFileName, "%s.ckp", chainParams.chainFileName);
11036 strcpy (bkupFileName, ckpFileName);
11037 strcat (bkupFileName, "~");
11038 strcpy (oldBkupFileName, bkupFileName);
11039 strcat (oldBkupFileName, "~");
11041 /* shift check-point files */
11042 remove (oldBkupFileName);
11043 rename (bkupFileName, oldBkupFileName);
11044 rename (ckpFileName, bkupFileName);
11046 /* create new ckp file */
11047 if ((fp = OpenTextFileW (ckpFileName)) == NULL)
11049 MrBayesPrint ("%s Problem opening checkpoint file\n", spacer);
11054 #if defined (MPI_ENABLED)
11055 } /* end of if (proc_id == 0)*/
11058 ERROR_TEST2("",free(tempString),return(ERROR));
11060 /* write file header */
11061 MrBayesPrintf (fp, "#NEXUS\n[ID: %s]\n[generation: %d]\n", stamp, gen);
11063 if (chainParams.isSS == YES)
11065 /* dump to .ckp file current step contribution */
11066 MrBayesPrintf (fp, "[SsAcumulators:");
11067 # if defined (MPI_ENABLED)
11068 for (j=0; j<chainParams.numRuns ; j++)
11070 if (stepAcumulatorSS[j]==0)
11073 r = log (stepAcumulatorSS[j]) + stepScalerSS[j];
11074 ierror = MPI_Reduce (&r,&sum, 1, MPI_DOUBLE, MPI_SUM, 0, MPI_COMM_WORLD);
11075 if (ierror != MPI_SUCCESS)
11077 MrBayesPrint ("%s Problem with MPI_Reduce\n", spacer);
11082 MrBayesPrintf (fp, " %.4f", sum);
11086 for (j=0; j<chainParams.numRuns ; j++)
11088 MrBayesPrintf (fp, " %.4f", log (stepAcumulatorSS[j]) + stepScalerSS[j]);
11091 MrBayesPrintf (fp, "]\n");
11094 #if defined (MPI_ENABLED)
11098 MrBayesPrintf (fp, "\nbegin trees;\n\ttranslate\n");
11100 /* remove old bkup file ('~~') */
11101 remove (oldBkupFileName);
11103 /* write translate block */
11104 for (i=0; i<numLocalTaxa; i++)
11106 if (i == numLocalTaxa - 1)
11107 MrBayesPrintf (fp, " %2d %s;\n", i+1, localTaxonNames[i]);
11109 MrBayesPrintf (fp, " %2d %s,\n", i+1, localTaxonNames[i]);
11112 #if defined (MPI_ENABLED)
11116 /* allocate space for print string */
11117 printStringSize = tempStrSize;
11118 printString = (char *) SafeCalloc ((size_t)printStringSize, sizeof(char));
11122 strcpy(printString,"");
11124 ERROR_TEST2("Memory allocation error",free(tempString),return(ERROR));
11126 # if defined (MPI_ENABLED)
11127 MPI_Allreduce (&nErrors, &sumErrors, 1, MPI_INT, MPI_SUM, MPI_COMM_WORLD);
11130 MrBayesPrint ("%s Memory allocation error on at least one processor\n", spacer);
11142 /* print trees (but not species trees) */
11143 for (i=0; i<numParams; i++)
11146 if (p->paramType != P_BRLENS && p->paramType != P_TOPOLOGY)
11148 if (p->paramType == P_TOPOLOGY && p->subParams[0] != p)
11151 for (j=0; j<numLocalChains; j++)
11153 t = GetTree (p, j, state[j]);
11154 /* write the tree preamble */
11155 if (nErrors == 0 && SafeSprintf (&tempString, &tempStrSize, "\ttree %s", t->name) == ERROR)
11157 if (nErrors == 0 && AddToPrintString (tempString) == ERROR)
11159 if (p->paramType == P_BRLENS && p->nSubParams > 0)
11161 for (k=0; k<p->nSubParams; k++)
11163 subParm = p->subParams[k];
11164 if (subParm->paramType == P_CPPEVENTS)
11167 if (SafeSprintf (&tempString, &tempStrSize, " [&E %s]", subParm->name) == ERROR) nErrors++;
11168 if (nErrors == 0 && AddToPrintString (tempString) == ERROR) nErrors++;
11170 if (nErrors == 0 && (subParm->paramType == P_CPPEVENTS || subParm->paramType == P_TK02BRANCHRATES ||
11171 subParm->paramType == P_IGRBRANCHRATES || subParm->paramType == P_MIXEDBRCHRATES))
11173 if (subParm->paramType == P_MIXEDBRCHRATES)
11175 id = *GetParamIntVals(subParm, j, state[j]);
11176 if (SafeSprintf (&tempString, &tempStrSize, " [&B %s %d]", subParm->name, id) == ERROR) nErrors++;
11179 if (SafeSprintf (&tempString, &tempStrSize, " [&B %s]", subParm->name) == ERROR) nErrors++;
11180 if (nErrors == 0 && AddToPrintString (tempString) == ERROR) nErrors++;
11185 if (t->isRooted == YES && t->isClock == NO)
11186 SafeSprintf (&tempString, &tempStrSize, " = ");
11187 else if (t->isRooted == YES && t->isClock == YES)
11189 clockRate = *GetParamVals(modelSettings[p->relParts[0]].clockRate, j, state[j]);
11190 SafeSprintf (&tempString, &tempStrSize, " = [&R] [&clockrate = %s] ", MbPrintNum(clockRate));
11192 else /* if (t->isRooted == NO) */
11193 SafeSprintf (&tempString, &tempStrSize, " = ");
11194 if (nErrors == 0 && AddToPrintString (tempString) == ERROR) nErrors++;
11195 /* write the tree in (extended) Newick format */
11198 if (p->paramType == P_TOPOLOGY)
11199 WriteNoEvtTreeToPrintString (t->root->left, j, p, NO, t->isRooted);
11200 else if (hasEvents == NO)
11201 WriteNoEvtTreeToPrintString (t->root->left, j, p, YES, t->isRooted);
11203 WriteEventTreeToPrintString (t->root->left, j, p, YES);
11204 if (AddToPrintString (";\n") == ERROR)
11208 MrBayesPrintf (fp, "%s", printString);
11209 #if defined (MPI_ENABLED)
11210 MPI_Allreduce (&nErrors, &sumErrors, 1, MPI_INT, MPI_SUM, MPI_COMM_WORLD);
11213 MrBayesPrint ("%s Print error on at least one processor\n", spacer);
11216 if (PrintMPISlaves(fp) == ERROR)
11222 strcpy (printString, "");
11223 strcpy (tempString, "");
11225 MrBayesPrintf (fp, "end;\n\n");
11227 /* print species trees */
11228 if (strcmp(modelParams[0].topologyPr,"Speciestree") == 0)
11230 /* get the first species tree */
11231 for (i=0; i<numParams; i++)
11234 if (p->paramType == P_SPECIESTREE)
11237 t = GetTree(p, 0, state[0]);
11239 #if defined (MPI_ENABLED)
11243 /* write the block header and translate block */
11244 MrBayesPrintf (fp, "\nbegin trees;\n");
11245 PrintTranslateBlock (fp, t);
11246 #if defined (MPI_ENABLED)
11250 for (j=0; j<numLocalChains; j++)
11252 t = GetTree (p, j, state[j]);
11254 /* write the tree preamble */
11255 if (nErrors == 0 && SafeSprintf (&tempString, &tempStrSize, "\ttree %s", t->name) == ERROR)
11257 if (nErrors == 0 && AddToPrintString (tempString) == ERROR)
11260 subParm = modelSettings[p->relParts[0]].popSize;
11261 if (subParm->nValues > 1)
11263 if (SafeSprintf (&tempString, &tempStrSize, " [&N %s]", subParm->name) == ERROR) nErrors++;
11264 if (nErrors == 0 && AddToPrintString (tempString) == ERROR) nErrors++;
11267 clockRate = *GetParamVals(modelSettings[p->relParts[0]].clockRate, j, state[j]);
11268 SafeSprintf (&tempString, &tempStrSize, " = [&R] [&clockrate = %s] ", MbPrintNum(clockRate));
11269 if (nErrors == 0 && AddToPrintString (tempString) == ERROR) nErrors++;
11271 /* write the tree in (extended) Newick format */
11274 WriteNoEvtTreeToPrintString (t->root->left, j, p, YES, t->isRooted);
11275 if (AddToPrintString (";\n") == ERROR)
11279 MrBayesPrintf (fp, "%s", printString);
11280 #if defined (MPI_ENABLED)
11281 MPI_Allreduce (&nErrors, &sumErrors, 1, MPI_INT, MPI_SUM, MPI_COMM_WORLD);
11284 MrBayesPrint ("%s Print error on at least one processor\n", spacer);
11287 if (PrintMPISlaves(fp) == ERROR)
11293 strcpy (printString, "");
11294 strcpy (tempString, "");
11295 MrBayesPrintf (fp, "end;\n\n");
11298 /* start startvals block */
11299 MrBayesPrintf (fp,"begin mrbayes;\n");
11300 MrBayesPrintf (fp, "\tstartvals\n");
11302 /* first print topology values */
11303 for (i=0; i<numParams; i++)
11306 if (p->paramType == P_TOPOLOGY)
11308 for (j=0; j<numLocalChains; j++)
11310 t = GetTree (p, j, state[j]);
11311 run = (chainId[j] / chainParams.numChains) + 1;
11312 chn = (chainId[j] % chainParams.numChains) + 1;
11313 if (nErrors == 0 && SafeSprintf (&tempString, &tempStrSize, "\t\t%s(%d,%d)=%s\n", p->name, run, chn, t->name) == ERROR)
11315 if (nErrors == 0 && AddToPrintString (tempString) == ERROR)
11318 MrBayesPrintf (fp, "%s", printString);
11319 # if defined (MPI_ENABLED)
11320 MPI_Allreduce (&nErrors, &sumErrors, 1, MPI_INT, MPI_SUM, MPI_COMM_WORLD);
11323 MrBayesPrint ("%s Print error on at least one processor\n", spacer);
11326 if (PrintMPISlaves(fp) == ERROR)
11332 strcpy (printString, "");
11333 strcpy (tempString, "");
11337 /* now print branch lengths and relaxed clock parameters */
11338 for (i=0; i<numParams; i++)
11341 if (p->paramType == P_BRLENS)
11343 for (j=0; j<numLocalChains; j++)
11345 t = GetTree (p, j, state[j]);
11346 run = (chainId[j] / chainParams.numChains) + 1;
11347 chn = (chainId[j] % chainParams.numChains) + 1;
11348 if (nErrors == 0 && SafeSprintf (&tempString, &tempStrSize, "\t\t%s(%d,%d)=%s\n", p->name, run, chn, t->name) == ERROR)
11350 if (nErrors == 0 && AddToPrintString (tempString) == ERROR)
11352 for (k=0; k<p->nSubParams; k++)
11354 if (nErrors == 0 && SafeSprintf (&tempString, &tempStrSize, "\t\t%s(%d,%d)=%s\n", p->subParams[k]->name, run, chn, t->name) == ERROR)
11356 if (nErrors == 0 && AddToPrintString (tempString) == ERROR)
11360 MrBayesPrintf (fp, "%s", printString);
11361 # if defined (MPI_ENABLED)
11362 MPI_Allreduce (&nErrors, &sumErrors, 1, MPI_INT, MPI_SUM, MPI_COMM_WORLD);
11365 MrBayesPrint ("%s Print error on at least one processor\n", spacer);
11368 if (PrintMPISlaves(fp) == ERROR)
11374 strcpy (printString, "");
11375 strcpy (tempString, "");
11379 /* now print species tree and population size parameters */
11380 for (i=0; i<numParams; i++)
11383 if (p->paramType == P_SPECIESTREE)
11385 for (j=0; j<numLocalChains; j++)
11387 t = GetTree (p, j, state[j]);
11388 run = (chainId[j] / chainParams.numChains) + 1;
11389 chn = (chainId[j] % chainParams.numChains) + 1;
11390 if (nErrors == 0 && SafeSprintf (&tempString, &tempStrSize, "\t\t%s(%d,%d)=%s\n", p->name, run, chn, t->name) == ERROR)
11392 if (nErrors == 0 && AddToPrintString (tempString) == ERROR)
11394 if (modelSettings[p->relParts[0]].popSize->nValues > 1)
11395 if (nErrors == 0 && SafeSprintf (&tempString, &tempStrSize, "\t\t%s(%d,%d)=%s\n", modelSettings[p->relParts[0]].popSize->name, run, chn, t->name) == ERROR)
11397 if (nErrors == 0 && AddToPrintString (tempString) == ERROR)
11400 MrBayesPrintf (fp, "%s", printString);
11401 # if defined (MPI_ENABLED)
11402 MPI_Allreduce (&nErrors, &sumErrors, 1, MPI_INT, MPI_SUM, MPI_COMM_WORLD);
11405 MrBayesPrint ("%s Print error on at least one processor\n", spacer);
11408 if (PrintMPISlaves(fp) == ERROR)
11414 strcpy (printString, "");
11415 strcpy (tempString, "");
11419 /* now print param values */
11420 for (i=0; i<numPrintParams; i++)
11423 for (j=0; j<numLocalChains; j++)
11425 run = (chainId[j] / chainParams.numChains) + 1;
11426 chn = (chainId[j] % chainParams.numChains) + 1;
11427 if (p->paramType == P_PI && modelSettings[p->relParts[0]].dataType != STANDARD)
11429 value = GetParamSubVals (p, j, state[j]);
11430 nValues = p->nSubValues;
11434 value = GetParamVals (p, j, state[j]);
11435 nValues = p->nValues;
11437 if (nErrors == 0 && SafeSprintf (&tempString, &tempStrSize, "\t\t%s(%d,%d)=(%.15le", p->name, run, chn, value[0]) == ERROR)
11439 if (nErrors == 0 && AddToPrintString (tempString) == ERROR)
11441 for (k=1; k<nValues; k++)
11443 if (nErrors==0 && SafeSprintf (&tempString, &tempStrSize, ",%.15le", value[k]) == ERROR)
11445 if (nErrors == 0 && AddToPrintString (tempString) == ERROR)
11448 /* print int values if present */
11449 if (p->nIntValues > 0)
11451 intValue = GetParamIntVals (p, j, state[j]);
11452 nValues = p->nIntValues;
11453 for (k=0; k<nValues; k++)
11455 if (nErrors==0 && SafeSprintf (&tempString, &tempStrSize, ",%d", intValue[k]) == ERROR)
11457 if (nErrors == 0 && AddToPrintString (tempString) == ERROR)
11461 /* print extra params for symdir multistate */
11464 value = GetParamStdStateFreqs (p, j, state[j]);
11465 if (p->hasBinaryStd == YES)
11466 value += 2 * modelSettings[p->relParts[0]].numBetaCats;
11467 for (k=0; k<p->nSympi; k++)
11469 for (k1=0; k1<p->sympinStates[k]; k1++)
11471 if (nErrors==0 && SafeSprintf (&tempString, &tempStrSize, ",%.15le", *value++) == ERROR)
11473 if (nErrors == 0 && AddToPrintString (tempString) == ERROR)
11478 /* print extra params for omega */
11479 if (p->paramType == P_OMEGA)
11481 value = GetParamSubVals (p, j, state[j]);
11482 nValues = p->nSubValues/2;
11483 for (k=0; k<nValues; k++)
11485 if (nErrors==0 && SafeSprintf (&tempString, &tempStrSize, ",%.15le", value[k]) == ERROR)
11487 if (nErrors == 0 && AddToPrintString (tempString) == ERROR)
11491 if (nErrors == 0 && AddToPrintString (")\n") == ERROR)
11494 MrBayesPrintf (fp, "%s", printString);
11495 #if defined (MPI_ENABLED)
11496 MPI_Allreduce (&nErrors, &sumErrors, 1, MPI_INT, MPI_SUM, MPI_COMM_WORLD);
11499 MrBayesPrint ("%s Print error on at least one processor\n", spacer);
11502 if (PrintMPISlaves(fp) == ERROR)
11508 strcpy (printString, "");
11509 strcpy (tempString, "");
11511 /* end startvals statement */
11512 MrBayesPrintf (fp, "\t;\n");
11514 /* print tuning parameters of moves */
11515 MrBayesPrintf (fp, "\tpropset\n");
11516 for (i=0; i<numUsedMoves; i++)
11519 if (mv->moveType->Autotune == NULL)
11520 continue; /* tuning parameter(s) do not change */
11521 for (j=0; j<numLocalChains; j++)
11523 run = (chainId[j] / chainParams.numChains) + 1;
11524 chn = (chainId[j] % chainParams.numChains) + 1;
11525 /* format is: <move_name>$<tuning_param_name>(<run>,<chain>)=<number> */
11526 if (nErrors == 0 && SafeSprintf (&tempString, &tempStrSize, "\t\t%s$%s(%d,%d)=%.15le\n",
11527 mv->name, mv->moveType->shortTuningName[0], run, chn, mv->tuningParam[chainId[j]][0]) == ERROR)
11529 if (nErrors == 0 && AddToPrintString (tempString) == ERROR)
11532 MrBayesPrintf (fp, "%s", printString);
11533 #if defined (MPI_ENABLED)
11534 MPI_Allreduce (&nErrors, &sumErrors, 1, MPI_INT, MPI_SUM, MPI_COMM_WORLD);
11537 MrBayesPrint ("%s Print error on at least one processor\n", spacer);
11540 if (PrintMPISlaves(fp) == ERROR)
11546 strcpy (printString, "");
11547 strcpy (tempString, "");
11550 /* end propset statement */
11551 MrBayesPrintf (fp, "\t;\n");
11553 /* end mrbayes block */
11554 MrBayesPrintf (fp, "end;\n\n");
11556 /* change precision back */
11557 precision = oldPrecision;
11561 free (printString);
11562 printStringSize = 0;
11566 precision = oldPrecision;
11568 free (printString);
11569 printString = NULL;
11570 printStringSize = 0;
11576 /*----------------------------------------------------------------------
11578 | PrintMCMCDiagnosticsToFile: Print acceptance ratios, swapping
11579 | frequencies, and convergence diagnostics to file.
11581 ------------------------------------------------------------------------*/
11582 int PrintMCMCDiagnosticsToFile (int curGen)
11588 /* Simply print header if curGen == 0 */
11591 // MrBayesPrintf (fpMcmc, "[LEGEND:]\n");
11592 MrBayesPrintf (fpMcmc, "[ID: %s]\n", stamp);
11593 MrBayesPrintf (fpMcmc, "[ Gen -- Generation]\n");
11594 if (chainParams.allChains == YES)
11595 MrBayesPrintf (fpMcmc, "[ <name1>(<name2>)$acc_run2_chn3 -- Acceptance rate of move <name1> changing parameter <name2> in run 2, chain 3]\n");
11596 else /* if (chainParams.allChains == NO) */
11597 MrBayesPrintf (fpMcmc, "[ <name1>(<name2>)$acc_run2 -- Acceptance rate of move <name1> changing parameter 1 in run 2]\n");
11598 if (chainParams.numChains > 1 && chainParams.numRuns > 1)
11599 MrBayesPrintf (fpMcmc, "[ Swap(1<>2)$acc_run3 -- Acceptance rate of swaps between chains 1 and 2 in run 3]\n");
11600 else if (chainParams.numChains > 1 && chainParams.numRuns == 1)
11601 MrBayesPrintf (fpMcmc, "[ Swap(1<>2)$acc -- Acceptance rate of swaps between chains 1 and 2]\n");
11602 if (chainParams.diagnStat == AVGSTDDEV)
11603 diagnstat = "Average";
11605 diagnstat = "Maximum";
11606 if (chainParams.numRuns > 1 && numTopologies == 1 && chainParams.allComps == NO)
11607 MrBayesPrintf (fpMcmc, "[ StdDev(s) -- %s standard deviation of split frequencies]\n", diagnstat);
11608 else if (chainParams.numRuns > 1 && numTopologies == 1 && chainParams.allComps == YES)
11609 MrBayesPrintf (fpMcmc, "[ StdDev(s)(run1-run2) -- %s standard deviation of split frequencies between runs 1 and 2]\n", diagnstat);
11610 else if (chainParams.numRuns > 1 && numTopologies > 1 && chainParams.allComps == NO)
11611 MrBayesPrintf (fpMcmc, "[ StdDev(s.tree1) -- %s standard deviation of split frequencies for topology 1]\n", diagnstat);
11612 else if (chainParams.numRuns > 1 && numTopologies > 1 && chainParams.allComps == YES)
11613 MrBayesPrintf (fpMcmc, "[ StdDev(s.tree1)(run1-run2) -- %s standard deviation of split frequencies between runs 1 and 2 for topology 1]\n", diagnstat);
11615 MrBayesPrintf (fpMcmc, "Gen");
11616 for (n=0; n<chainParams.numRuns; n++)
11618 if (chainParams.allChains == YES)
11620 for (i=0; i<chainParams.numChains; i++)
11622 for (j=0; j<numUsedMoves; j++)
11624 theMove = usedMoves[j];
11625 MrBayesPrintf (fpMcmc, "\t%s(%s)$acc_run%d_chn%d", theMove->moveType->shortName,
11626 theMove->parm->name, n+1, i+1);
11627 if (theMove->moveType->Autotune != NULL && chainParams.autotune == YES)
11628 MrBayesPrintf (fpMcmc, "\t%s(%s)$%s_run%d_chn%d", theMove->moveType->shortName,
11629 theMove->parm->name, theMove->moveType->shortTuningName[0], n+1, i+1);
11635 for (i=0; i<numUsedMoves; i++)
11637 theMove = usedMoves[i];
11638 if (chainParams.numRuns == 1)
11640 MrBayesPrintf (fpMcmc, "\t%s(%s)$acc", theMove->moveType->shortName, theMove->parm->name);
11641 if (theMove->moveType->Autotune != NULL && chainParams.autotune == YES)
11642 MrBayesPrintf (fpMcmc, "\t%s(%s)$%s", theMove->moveType->shortName, theMove->parm->name, theMove->moveType->shortTuningName[0]);
11646 MrBayesPrintf (fpMcmc, "\t%s(%s)$acc_run%d", theMove->moveType->shortName, theMove->parm->name, n+1);
11647 if (theMove->moveType->Autotune != NULL && chainParams.autotune == YES)
11648 MrBayesPrintf (fpMcmc, "\t%s(%s)$%s_run%d", theMove->moveType->shortName, theMove->parm->name, theMove->moveType->shortTuningName[0], n+1);
11652 if (chainParams.numChains > 1)
11654 for (i=0; i<chainParams.numChains; i++)
11656 for (j=i+1; j<chainParams.numChains; j++)
11658 if (chainParams.numRuns == 1)
11659 MrBayesPrintf (fpMcmc, "\tSwap(%d<>%d)$acc", i+1, j+1);
11661 MrBayesPrintf (fpMcmc, "\tSwap(%d<>%d)$acc(%d)", i+1, j+1, n+1);
11667 if (chainParams.numRuns > 1)
11669 for (n=0; n<numTopologies; n++)
11671 if (numTopologies == 1)
11673 if (chainParams.diagnStat == AVGSTDDEV)
11674 MrBayesPrintf (fpMcmc, "\tAvgStdDev(s)");
11676 MrBayesPrintf (fpMcmc, "\tMaxStdDev(s)");
11680 if (chainParams.diagnStat == AVGSTDDEV)
11681 MrBayesPrintf (fpMcmc, "\tAvgStdDev(s.tree%d)", n+1);
11683 MrBayesPrintf (fpMcmc, "\tMaxStdDev(s.tree%d)", n+1);
11686 if (chainParams.allComps == YES)
11688 for (i=0; i<chainParams.numRuns; i++)
11690 for (j=i+1; j<chainParams.numRuns; j++)
11692 if (numTopologies == 1)
11694 if (chainParams.diagnStat == AVGSTDDEV)
11695 MrBayesPrintf (fpMcmc, "\tAvgStdDev(s)(run%d_run%d)", i+1,j+1);
11697 MrBayesPrintf (fpMcmc, "\tMaxStdDev(s)(run%d_run%d)", i+1, j+1);
11701 if (chainParams.diagnStat == AVGSTDDEV)
11702 MrBayesPrintf (fpMcmc, "\tAvgStdDev(s.tree%d)(run%d_run%d)", n+1, i+1, j+1);
11704 MrBayesPrintf (fpMcmc, "\tMaxStdDev(s.tree%d)(run%d_run%d)", n+1, i+1, j+1);
11711 MrBayesPrintf (fpMcmc, "\n");
11716 #if defined (MPI_ENABLED)
11717 /* Reassemble info if MPI version */
11718 if (ReassembleMoveInfo() == ERROR)
11720 if (chainParams.numChains > 1 && ReassembleSwapInfo() == ERROR)
11726 MrBayesPrintf (fpMcmc, "%d", curGen);
11728 for (n=0; n<chainParams.numRuns; n++)
11730 if (chainParams.allChains == YES)
11732 for (j=n*chainParams.numChains; j<(n+1)*chainParams.numChains; j++)
11734 for (i=0; i<numUsedMoves; i++)
11736 theMove = usedMoves[i];
11737 if (theMove->nBatches[j] < 1)
11738 MrBayesPrintf (fpMcmc, "\tNA");
11740 MrBayesPrintf (fpMcmc, "\t%.6f", theMove->lastAcceptanceRate[j]);
11741 if (theMove->moveType->Autotune != NULL && chainParams.autotune == YES)
11742 MrBayesPrintf (fpMcmc, "\t%.6e", theMove->tuningParam[j][0]);
11748 j = n*chainParams.numChains;
11749 for (i=0; i<numUsedMoves; i++)
11751 theMove = usedMoves[i];
11752 if (theMove->nBatches[j] < 1)
11753 MrBayesPrintf (fpMcmc, "\tNA");
11755 MrBayesPrintf (fpMcmc, "\t%.6f", theMove->lastAcceptanceRate[j]);
11756 if (theMove->moveType->Autotune != NULL && chainParams.autotune == YES)
11757 MrBayesPrintf (fpMcmc, "\t%.6e", theMove->tuningParam[j][0]);
11760 if (chainParams.numChains > 1)
11762 for (i=0; i<chainParams.numChains; i++)
11764 for (j=i+1; j<chainParams.numChains; j++)
11766 MrBayesPrintf (fpMcmc, "\t%.6f", (MrBFlt) swapInfo[n][i][j] / (MrBFlt) swapInfo[n][j][i]);
11772 if (chainParams.numRuns > 1)
11774 for (n=0; n<numTopologies; n++)
11776 if (chainParams.relativeBurnin == NO && curGen < chainParams.chainBurnIn * chainParams.sampleFreq)
11777 MrBayesPrintf (fpMcmc, "\tNA");
11780 if (chainParams.diagnStat == AVGSTDDEV)
11781 MrBayesPrintf (fpMcmc, "\t%.6f", chainParams.stat[n].avgStdDev);
11783 MrBayesPrintf (fpMcmc, "\t%.6f", chainParams.stat[n].max);
11785 if (chainParams.allComps == YES)
11787 for (i=0; i<chainParams.numRuns; i++)
11789 for (j=i+1; j<chainParams.numRuns; j++)
11791 if (chainParams.relativeBurnin == NO && curGen < chainParams.chainBurnIn * chainParams.sampleFreq)
11792 MrBayesPrintf (fpMcmc, "\tNA");
11793 else if (chainParams.diagnStat == AVGSTDDEV)
11794 MrBayesPrintf (fpMcmc, "\t%.6f", chainParams.stat[n].pair[i][j] / chainParams.stat[n].pair[j][i]);
11795 else /*if (chainParams.diagnStat == MAXSTDDEV) */
11796 MrBayesPrintf (fpMcmc, "\t%.6f", chainParams.stat[n].pair[i][j]);
11803 MrBayesPrintf (fpMcmc, "\n");
11806 #if defined MPI_ENABLED
11807 /* Redistribute the move info in the parallel version, so that
11808 swapping occurs correctly; only necessary on processor 0 */
11809 RedistributeMoveInfo();
11816 /*-----------------------------------------------------------------------
11818 | PrintMPISlaves: Print strings from MPI slave nodes
11820 ------------------------------------------------------------------------*/
11821 #if defined (MPI_ENABLED)
11822 int PrintMPISlaves (FILE *fp)
11825 int i, len, ierror, nErrors, sumErrors, tag;
11828 nErrors = sumErrors = tag = 0;
11831 s = (char *) SafeCalloc (100, sizeof(char));
11838 for (i=1; i<num_procs; i++)
11840 /* communicate length */
11844 ierror = MPI_Recv (&len, 1, MPI_INT, i, tag, MPI_COMM_WORLD, &status);
11845 if (ierror != MPI_SUCCESS)
11847 MrBayesPrint ("%s Problem receiving string length from proc_id = %d\n", spacer, i);
11851 else if (proc_id == i)
11854 len = (int)strlen(printString);
11855 ierror = MPI_Send (&len, 1, MPI_INT, 0, tag, MPI_COMM_WORLD);
11856 if (ierror != MPI_SUCCESS)
11858 MrBayesPrint ("%s Problem sending string length from proc_id = %d\n", spacer, i);
11862 /* reallocate string s on processor 0 if necessary */
11863 if (nErrors == 0 && proc_id == 0 && len+5 > strlen(s))
11865 if ((s = (char *) SafeRealloc ((void *)s, ((size_t)len+5)*sizeof(char))) == NULL)
11867 MrBayesPrint ("%s Problem reallocating %d chars to string 's' on proc 0 in PrintMPISlaves()\n", spacer, len+5);
11871 /* communicate and print string */
11876 /* receive string */
11877 ierror = MPI_Recv (s, len+1, MPI_CHAR, i, tag, MPI_COMM_WORLD, &status);
11878 if (ierror != MPI_SUCCESS)
11880 MrBayesPrint ("%s Problem receiving printString from proc_id = %d\n", spacer, i);
11885 MrBayesPrintf (fp, "%s", s);
11887 else if (proc_id == i)
11890 ierror = MPI_Send (printString, len+1, MPI_CHAR, 0, tag, MPI_COMM_WORLD);
11891 if (ierror != MPI_SUCCESS)
11893 MrBayesPrint ("%s Problem sending printString from proc_id = %d\n", spacer, i);
11908 MPI_Allreduce (&nErrors, &sumErrors, 1, MPI_INT, MPI_SUM, MPI_COMM_WORLD);
11911 MrBayesPrint ("%s Problem with the printing in PrintMPISlaves().\n", spacer);
11920 /*----------------------------------------------------------------------
11922 | PrintParamValues: print parameter values and subvalues for param
11924 ----------------------------------------------------------------------*/
11925 void PrintParamValues (Param *p, int chain, char *s)
11928 MrBFlt *value0, *value1;
11931 MrBayesPrint ("%s %s = NULL\n", spacer, s);
11934 if (p->nValues > 0)
11936 value0 = GetParamVals (p, chain, 0);
11937 value1 = GetParamVals (p, chain, 1);
11938 for (j=0; j<p->nValues; j++)
11939 MrBayesPrint ("%s hyper [%s] = (%lf %lf)\n", spacer, s, value0[j], value1[j]);
11941 if (p->nSubValues > 0)
11943 value0 = GetParamSubVals (p, chain, 0);
11944 value1 = GetParamSubVals (p, chain, 1);
11945 for (j=0; j<p->nSubValues; j++)
11946 MrBayesPrint ("%s %s = (%lf %lf)\n", spacer, s, value0[j], value1[j]);
11949 MrBayesPrint ("\n\n");
11955 /*----------------------------------------------------------------------
11957 | PrintParsMatrix: Print parsimony (bitset) matrix
11958 | using hexadecimal representation
11961 ------------------------------------------------------------------------*/
11962 int PrintParsMatrix (void)
11964 int i, j=0, k, c, d, printWidth, nextColumn, nChars, inputChar;
11965 BitsLong x, y, bitsLongOne;
11973 for (d=0; d<numCurrentDivisions; d++)
11975 MrBayesPrint ("\nParsimony (bitset) matrix for division %d\n\n", d+1);
11977 m = &modelSettings[d];
11979 nChars = 1 + (int) (log((bitsLongOne << m->numStates) - 1) / log(16));
11981 for (c=0; c<m->numChars; c++)
11983 MrBayesPrint ("Parsimony sets for character %d -- \n", (c / m->nParsIntsPerSite));
11984 for (i=0; i<numTaxa; i++)
11986 MrBayesPrint ("%-10.10s ", taxaNames[i]);
11987 j = c*m->nParsIntsPerSite;
11988 for (nextColumn=13; nextColumn < printWidth; nextColumn+=nChars + 1)
11990 if (j >= m->numChars*m->nParsIntsPerSite)
11992 x = m->parsSets[i][j];
11993 for (k=8 - nChars; k<8; k++)
11995 y = (x >> (4* (7 - k))) & 15;
11996 // if (y > 16) printf ("y is too big %ld\n",y);
11998 ch = (char) y + '0';
12000 ch = (char) y - 10 + 'A';
12001 MrBayesPrint("%c", ch);
12006 MrBayesPrint ("\n");
12008 MrBayesPrint("\n");
12009 printf ("Do you want to stop (y/n)?\n");
12010 inputChar = getchar();
12011 if (inputChar == 'y' || inputChar == 'Y')
12014 MrBayesPrint ("\n");
12016 } /* next division */
12022 /*------------------------------------------------------------------
12024 | PrintSiteRates_Gen: general n-state models with rate variation
12026 -------------------------------------------------------------------*/
12027 int PrintSiteRates_Gen (TreeNode *p, int division, int chain)
12029 int c, j, k, nStates, hasPInvar;
12030 MrBFlt freq, siteLike, invLike, catLike, pInvar=0.0, *bs,
12031 *catRate, baseRate;
12032 MrBFlt s01, s10, probOn, probOff, *swr, covBF[40];
12033 CLFlt *lnScaler, *clP, *siteRates, *clInvar=NULL;
12035 int tempStrSize = TEMPSTRSIZE;
12038 tempStr = (char *) SafeMalloc((size_t)tempStrSize * sizeof(char));
12041 MrBayesPrint ("%s Problem allocating tempString (%d)\n", spacer, tempStrSize * sizeof(char));
12045 /* find model settings and nStates, pInvar, invar cond likes */
12046 m = &modelSettings[division];
12047 nStates = m->numModelStates;
12048 if (m->pInvar == NULL)
12055 pInvar = *(GetParamVals (m->pInvar, chain, state[chain]));
12056 clInvar = m->invCondLikes;
12059 /* find conditional likelihood pointer */
12060 clP = m->condLikes[m->condLikeIndex[chain][p->index]];
12062 /* use scratch space for root node for temporary calculations */
12063 siteRates = m->condLikes[m->condLikeScratchIndex[p->index]];
12065 /* find site scaler */
12066 lnScaler = m->scalers[m->siteScalerIndex[chain]];
12068 /* find base frequencies */
12069 bs = GetParamSubVals (m->stateFreq, chain, state[chain]);
12071 /* if covarion model, adjust base frequencies */
12072 if (m->switchRates != NULL)
12074 /* find the stationary frequencies */
12075 swr = GetParamVals(m->switchRates, chain, state[chain]);
12078 probOn = s01 / (s01 + s10);
12079 probOff = 1.0 - probOn;
12081 /* now adjust the base frequencies; on-state stored first in cond likes */
12082 for (j=0; j<nStates/2; j++)
12084 covBF[j] = bs[j] * probOn;
12085 covBF[j+nStates/2] = bs[j] * probOff;
12088 /* finally set bs pointer to adjusted values */
12092 /* find category frequencies */
12093 if (hasPInvar == NO)
12094 freq = 1.0 / m->numGammaCats;
12096 freq = (1.0 - pInvar) / m->numGammaCats;
12098 /* get rate multipliers (for gamma & partition specific rates) */
12099 baseRate = GetRate (division, chain);
12101 /* compensate for invariable sites */
12102 if (hasPInvar == YES)
12103 baseRate /= (1.0 - pInvar);
12105 /* get category rates */
12106 catRate = GetParamSubVals (m->shape, chain, state[chain]);
12108 /* loop over characters */
12109 if (hasPInvar == NO)
12111 /* no invariable category */
12112 for (c=0; c<m->numChars; c++)
12115 siteRates[c] = 0.0;
12116 for (k=0; k<m->numGammaCats; k++)
12119 for (j=0; j<nStates; j++)
12120 catLike += (*(clP++)) * bs[j];
12121 siteRates[c] += (CLFlt) (catLike * catRate[k]);
12122 siteLike += catLike;
12124 siteRates[c] *= (CLFlt) (baseRate / siteLike); /* category frequencies and site scaler cancel out */
12129 /* has invariable category */
12130 for (c=0; c<m->numChars; c++)
12132 siteLike = invLike = 0.0;
12133 siteRates[c] = 0.0;
12134 for (k=0; k<m->numGammaCats; k++)
12137 for (j=0; j<nStates; j++)
12138 catLike += (*(clP++)) * bs[j];
12139 siteRates[c] += (CLFlt) (catLike * catRate[k]);
12140 siteLike += catLike;
12143 siteRates[c] *= (CLFlt) freq;
12144 for (j=0; j<nStates; j++)
12145 invLike += (*(clInvar++)) * bs[j];
12146 siteLike += (invLike / exp (lnScaler[c]) * pInvar);
12147 /* we do not need to add the invariable category into siteRates before rescaling because the rate is 0.0 */
12148 siteRates[c] *= (CLFlt) (baseRate / siteLike); /* site scaler cancels out; category frequencies dealt with above */
12152 /* print the resulting site rates cycling over uncompressed chars */
12153 for (c=0; c<numChar; c++)
12155 if (charInfo[c].isExcluded == YES || partitionId[c][partitionNum] != division+1)
12157 j = compCharPos[c] - m->compCharStart;
12158 SafeSprintf (&tempStr, &tempStrSize, "\t%s", MbPrintNum(siteRates[j]));
12159 if (AddToPrintString (tempStr) == ERROR) return (ERROR);
12167 /*------------------------------------------------------------------
12169 | PrintSiteRates_Std: standard model with rate variation
12171 -------------------------------------------------------------------*/
12172 int PrintSiteRates_Std (TreeNode *p, int division, int chain)
12174 int c, j, k, nStates;
12175 MrBFlt siteLike, catLike, *bs, *catRate, baseRate;
12176 CLFlt *clP, *siteRates;
12178 int tempStrSize = TEMPSTRSIZE;
12181 tempStr = (char *) SafeMalloc((size_t)tempStrSize * sizeof(char));
12184 MrBayesPrint ("%s Problem allocating tempString (%d)\n", spacer, tempStrSize * sizeof(char));
12188 /* find model settings */
12189 m = &modelSettings[division];
12191 /* find conditional likelihood pointer */
12192 clP = m->condLikes[m->condLikeIndex[chain][p->index]];
12194 /* use scratch space for root node for temporary calculations */
12195 siteRates = m->condLikes[m->condLikeScratchIndex[p->index]];
12197 /* find base frequencies */
12198 bs = GetParamStdStateFreqs (m->stateFreq, chain, state[chain]);
12200 /* get rate multiplier */
12201 baseRate = GetRate (division, chain);
12203 /* get category rates */
12204 catRate = GetParamSubVals (m->shape, chain, state[chain]);
12206 /* loop over characters */
12207 for (c=0; c<m->numChars; c++)
12210 siteRates[c] = 0.0;
12211 nStates = m->nStates[c];
12212 for (k=0; k<m->numGammaCats; k++)
12215 for (j=0; j<nStates; j++)
12216 catLike += (*(clP++)) * bs[j];
12217 siteRates[c] += (CLFlt) (catLike * catRate[k]);
12218 siteLike += catLike;
12220 siteRates[c] *= (CLFlt)(baseRate / siteLike); /* category frequencies and site scaler cancel out */
12223 /* print the resulting site rates cycling over uncompressed chars */
12224 for (c=0; c<numChar; c++)
12226 if (charInfo[c].isExcluded == YES || partitionId[c][partitionNum] != division+1)
12228 j = compCharPos[c] - m->compCharStart;
12229 SafeSprintf (&tempStr, &tempStrSize, "\t%s", MbPrintNum(siteRates[j]));
12230 if (AddToPrintString (tempStr) == ERROR) return (ERROR);
12238 int PrintStates (int curGen, int coldId)
12240 int d, i, j, k, k1, compressedCharPosition, *printedChar=NULL, origAlignmentChars[3];
12241 char *partString=NULL, stateString[4];
12242 MrBFlt *st, *sst, sum;
12251 /* allocate the print string */
12252 printStringSize = tempStrSize = TEMPSTRSIZE;
12253 printString = (char *)SafeMalloc((size_t)printStringSize * sizeof(char));
12254 tempStr = (char *) SafeMalloc((size_t)tempStrSize * sizeof(char));
12258 MrBayesPrint ("%s Problem allocating printString (%d)\n", spacer, printStringSize * sizeof(char));
12263 MrBayesPrint ("%s Problem allocating tempString (%d)\n", spacer, tempStrSize * sizeof(char));
12267 *printString = '\0';
12270 /* Allocate memory, temporarily, in case we infer positive selection probs, site omegas, or site rates */
12271 if (inferPosSel == YES || inferSiteOmegas == YES)
12273 if (memAllocs[ALLOC_POSSELPROBS] == YES)
12275 MrBayesPrint ("%s posSelProbs not free in PrintStates\n", spacer);
12278 posSelProbs = (MrBFlt *)SafeMalloc((size_t)numCompressedChars * sizeof(MrBFlt));
12281 MrBayesPrint ("%s Problem allocating posSelProbs (%d)\n", spacer, numCompressedChars * sizeof(MrBFlt));
12284 for (i=0; i<numCompressedChars; i++)
12285 posSelProbs[i] = -10.0;
12286 memAllocs[ALLOC_POSSELPROBS] = YES;
12288 if (inferPosSel == YES || inferSiteOmegas == YES || inferSiteRates == YES || inferAncStates == YES)
12290 printedChar = (int *)SafeMalloc((size_t)numChar * sizeof(int));
12293 MrBayesPrint ("%s Problem allocating printedChar (%d)\n", spacer, numChar * sizeof(int));
12296 for (i=0; i<numChar; i++)
12297 printedChar[i] = NO;
12300 /* Set up the header to the file. */
12303 SafeSprintf (&tempStr, &tempStrSize, "[ID: %s]\n", stamp);
12304 if (AddToPrintString (tempStr) == ERROR) goto errorExit;
12305 SafeSprintf (&tempStr, &tempStrSize, "Gen");
12306 if (AddToPrintString (tempStr) == ERROR) goto errorExit;
12307 SafeSprintf (&tempStr, &tempStrSize, "\tLnL");
12308 if (AddToPrintString (tempStr) == ERROR) goto errorExit;
12309 SafeSprintf (&tempStr, &tempStrSize, "\tLnPr");
12310 if (AddToPrintString (tempStr) == ERROR) goto errorExit;
12312 for (i=0; i<numParams; i++)
12315 if (p->paramType == P_BRLENS)
12317 /* print tree lengths or heights for all trees */
12318 tree = GetTree (p, coldId, state[coldId]);
12319 if (tree->isRooted == YES)
12321 if (FillRelPartsString(p, &partString) == YES)
12322 SafeSprintf (&tempStr, &tempStrSize, "\tTH%s\tTL%s", partString, partString);
12324 SafeSprintf (&tempStr, &tempStrSize, "\tTH\tTL");
12325 if (AddToPrintString (tempStr) == ERROR) goto errorExit;
12329 if (FillRelPartsString(p, &partString) == YES)
12330 SafeSprintf (&tempStr, &tempStrSize, "\tTL%s", partString);
12332 SafeSprintf (&tempStr, &tempStrSize, "\tTL");
12333 if (AddToPrintString (tempStr) == ERROR) goto errorExit;
12335 /* print # cpp events, or relaxed clock model indicator */
12336 for (j=0; j<p->nSubParams; j++)
12338 if (p->subParams[j]->paramType == P_CPPEVENTS)
12340 if (FillRelPartsString(p->subParams[j], &partString) == YES)
12341 SafeSprintf (&tempStr, &tempStrSize, "\tn_CPP%s", partString);
12343 SafeSprintf (&tempStr, &tempStrSize, "\tn_CPP");
12344 if (AddToPrintString (tempStr) == ERROR) goto errorExit;
12346 else if (p->subParams[j]->paramType == P_MIXEDBRCHRATES)
12348 if (FillRelPartsString(p->subParams[j], &partString) == YES)
12349 SafeSprintf (&tempStr, &tempStrSize, "\tm_RCl%s", partString);
12351 SafeSprintf (&tempStr, &tempStrSize, "\tm_RCl");
12352 if (AddToPrintString (tempStr) == ERROR) goto errorExit;
12356 /* print proportion of ancestral fossils */
12357 else if (p->paramType == P_FOSLRATE)
12359 if (FillRelPartsString(p, &partString) == YES)
12361 SafeSprintf (&tempStr, &tempStrSize, "\tprop_ancfossil%s", partString);
12362 if (AddToPrintString (tempStr) == ERROR) goto errorExit;
12366 SafeSprintf (&tempStr, &tempStrSize, "\tprop_ancfossil");
12367 if (AddToPrintString (tempStr) == ERROR) goto errorExit;
12372 /* print ordinary parameters header */
12373 for (i=0; i<numPrintParams; i++)
12376 SafeSprintf (&tempStr, &tempStrSize, "\t%s", p->paramHeader);
12377 if (AddToPrintString (tempStr) == ERROR) goto errorExit;
12380 /* print substitution model parameters header */
12381 if (inferSiteRates == YES)
12383 for (i=0; i<numChar; i++)
12384 printedChar[i] = NO;
12386 for (i=0; i<numChar; i++)
12388 if (charInfo[i].isExcluded == YES)
12390 if (printedChar[i] == YES)
12392 d = partitionId[i][partitionNum] - 1;
12393 m = &modelSettings[d];
12394 mp = &modelParams[d];
12395 if (m->printSiteRates == YES)
12397 if (m->nCharsPerSite == 1)
12399 SafeSprintf (&tempStr, &tempStrSize, "\tr(%d)", i+1);
12400 if (AddToPrintString (tempStr) == ERROR) goto errorExit;
12404 origAlignmentChars[0] = i;
12406 for (j=i+1; j<numChar; j++)
12408 if (compCharPos[i] == compCharPos[j])
12410 if (k > m->nCharsPerSite)
12412 origAlignmentChars[k++] = j;
12413 printedChar[j] = YES;
12416 if (k != m->nCharsPerSite)
12418 SafeSprintf (&tempStr, &tempStrSize, "\tr(%d,", origAlignmentChars[0]);
12419 if (AddToPrintString (tempStr) == ERROR) goto errorExit;
12420 for (j=1; j<k-1; j++)
12422 SafeSprintf (&tempStr, &tempStrSize, "%d,", origAlignmentChars[j]);
12423 if (AddToPrintString (tempStr) == ERROR) goto errorExit;
12425 SafeSprintf (&tempStr, &tempStrSize, "%d)", origAlignmentChars[k-1]);
12426 if (AddToPrintString (tempStr) == ERROR) goto errorExit;
12432 if (inferPosSel == YES)
12434 for (i=0; i<numChar; i++)
12435 printedChar[i] = NO;
12436 for (d=0; d<numCurrentDivisions; d++)
12438 m = &modelSettings[d];
12439 tree = GetTree(m->brlens, coldId, state[coldId]);
12440 if (m->printPosSel == YES)
12442 if (m->PosSelProbs (tree->root->left, d, coldId) == ERROR)
12446 /* for (i=0; i<numChar; i++)
12447 printf ("%4d -- %3d %3d\n", i, compCharPos[i], compColPos[i]); */
12448 for (i=0; i<numChar; i++)
12450 compressedCharPosition = compCharPos[i];
12451 if (!(posSelProbs[compressedCharPosition] < 0.0) && printedChar[i] == NO && charInfo[i].isExcluded == NO)
12453 for (j=k=0; j<numChar; j++)
12455 if (charInfo[j].charId == charInfo[i].charId)
12457 origAlignmentChars[k++] = j;
12458 printedChar[j] = YES;
12461 SafeSprintf (&tempStr, &tempStrSize, "\tpr+(%d,%d,%d)", origAlignmentChars[0]+1, origAlignmentChars[1]+1, origAlignmentChars[2]+1);
12462 if (AddToPrintString (tempStr) == ERROR) goto errorExit;
12465 for (i=0; i<numChar; i++)
12466 printedChar[i] = NO;
12469 if (inferSiteOmegas == YES)
12471 for (i=0; i<numChar; i++)
12472 printedChar[i] = NO;
12473 for (d=0; d<numCurrentDivisions; d++)
12475 m = &modelSettings[d];
12476 tree = GetTree(m->brlens, coldId, state[coldId]);
12477 if (m->printSiteOmegas == YES)
12479 if (m->SiteOmegas (tree->root->left, d, coldId) == ERROR)
12483 /* for (i=0; i<numChar; i++)
12484 printf ("%4d -- %3d %3d\n", i, compCharPos[i], compColPos[i]); */
12485 for (i=0; i<numChar; i++)
12487 compressedCharPosition = compCharPos[i];
12488 if (posSelProbs[compressedCharPosition] >= 0.0 && printedChar[i] == NO && charInfo[i].isExcluded == NO)
12490 for (j=k=0; j<numChar; j++)
12492 if (charInfo[j].charId == charInfo[i].charId)
12494 origAlignmentChars[k++] = j;
12495 printedChar[j] = YES;
12498 SafeSprintf (&tempStr, &tempStrSize, "\tomega(%d,%d,%d)", origAlignmentChars[0]+1, origAlignmentChars[1]+1, origAlignmentChars[2]+1);
12499 if (AddToPrintString (tempStr) == ERROR) goto errorExit;
12502 for (i=0; i<numChar; i++)
12503 printedChar[i] = NO;
12506 if (inferAncStates == YES)
12508 for (j=0; j<numChar; j++)
12509 printedChar[j] = NO;
12510 for (d=0; d<numCurrentDivisions; d++)
12512 m = &modelSettings[d];
12513 mp = &modelParams[d];
12514 if (m->printAncStates != YES)
12516 for (i=0; i<numDefinedConstraints; i++)
12518 if (mp->activeConstraints[i] == NO || definedConstraintsType[i] != HARD)
12520 for (j=0; j<numChar; j++)
12522 if (partitionId[j][partitionNum] - 1 != d || charInfo[j].isExcluded == YES || printedChar[j] == YES)
12524 if (mp->dataType == STANDARD)
12526 for (k=0; k<m->nStates[compCharPos[j] - m->compCharStart]; k++)
12528 SafeSprintf (&tempStr, &tempStrSize, "\tp(%c){%d@%s}", m->StateCode(k), j+1, constraintNames[i]);
12529 if (AddToPrintString (tempStr) == ERROR) goto errorExit;
12532 else if ((mp->dataType == DNA || mp->dataType == RNA) && !strcmp(mp->nucModel,"Codon"))
12534 origAlignmentChars[0] = j+1;
12536 for (k=j+1; k<numChar; k++)
12538 if (charInfo[k].charId == charInfo[j].charId)
12540 origAlignmentChars[k1++] = k+1;
12541 printedChar[k] = YES;
12544 for (k=0; k<m->numStates; k++)
12546 State_CODON(stateString, k, d);
12547 SafeSprintf (&tempStr, &tempStrSize, "\tp(%s){%d,%d,%d@%s}",
12549 origAlignmentChars[0],
12550 origAlignmentChars[1],
12551 origAlignmentChars[2],
12552 constraintNames[i]);
12553 if (AddToPrintString (tempStr) == ERROR) goto errorExit;
12556 else if ((mp->dataType == DNA || mp->dataType == RNA) && !strcmp(mp->nucModel,"Doublet"))
12558 origAlignmentChars[0] = j+1;
12560 for (k=j+1; k<numChar; k++)
12562 if (charInfo[k].charId == charInfo[j].charId)
12564 origAlignmentChars[k1++] = k+1;
12565 printedChar[k] = YES;
12568 for (k=0; k<m->numStates; k++)
12570 State_DOUBLET(stateString, k);
12571 SafeSprintf (&tempStr, &tempStrSize, "\tp(%s){%d,%d@%s}",
12573 origAlignmentChars[0],
12574 origAlignmentChars[1],
12575 constraintNames[i]);
12576 if (AddToPrintString (tempStr) == ERROR) goto errorExit;
12579 else if ((mp->dataType == DNA || mp->dataType == RNA) && !strcmp(mp->nucModel,"Protein"))
12581 origAlignmentChars[0] = j+1;
12583 for (k=j+1; k<numChar; k++)
12585 if (charInfo[k].charId == charInfo[j].charId)
12587 origAlignmentChars[k1++] = k+1;
12588 printedChar[k] = YES;
12591 for (k=0; k<m->numStates; k++)
12593 SafeSprintf (&tempStr, &tempStrSize, "\tp(%c){%d,%d,%d@%s}",
12595 origAlignmentChars[0],
12596 origAlignmentChars[1],
12597 origAlignmentChars[2],
12598 constraintNames[i]);
12599 if (AddToPrintString (tempStr) == ERROR) goto errorExit;
12604 for (k=0; k<m->numStates; k++)
12606 SafeSprintf (&tempStr, &tempStrSize, "\tp(%c){%d@%s}", m->StateCode(k), j+1, constraintNames[i]);
12607 if (AddToPrintString (tempStr) == ERROR) goto errorExit;
12615 SafeSprintf (&tempStr, &tempStrSize, "\n");
12616 if (AddToPrintString (tempStr) == ERROR) goto errorExit;
12619 /* now print parameter values */
12620 SafeSprintf (&tempStr, &tempStrSize, "%d", curGen);
12621 if (AddToPrintString (tempStr) == ERROR) goto errorExit;
12622 SafeSprintf (&tempStr, &tempStrSize, "\t%s", MbPrintNum(curLnL[coldId]));
12623 if (AddToPrintString (tempStr) == ERROR) goto errorExit;
12624 SafeSprintf (&tempStr, &tempStrSize, "\t%s", MbPrintNum(curLnPr[coldId]));
12625 if (AddToPrintString (tempStr) == ERROR) goto errorExit;
12627 for (i=0; i<numParams; i++)
12630 if (p->paramType == P_BRLENS)
12632 /* print tree lengths or heights for all trees */
12633 tree = GetTree (p, coldId, state[coldId]);
12634 if (tree->isRooted == NO)
12636 SafeSprintf (&tempStr, &tempStrSize, "\t%s", MbPrintNum(TreeLength(p, coldId)));
12637 if (AddToPrintString (tempStr) == ERROR) goto errorExit;
12641 SafeSprintf (&tempStr, &tempStrSize, "\t%s", MbPrintNum(tree->root->left->nodeDepth));
12642 if (AddToPrintString (tempStr) == ERROR) goto errorExit;
12643 SafeSprintf (&tempStr, &tempStrSize, "\t%s", MbPrintNum(TreeLength(p, coldId)));
12644 if (AddToPrintString (tempStr) == ERROR) goto errorExit;
12646 /* print # cpp events, or relaxed clock model indicator */
12647 for (j=0; j<p->nSubParams; j++)
12649 if (p->subParams[j]->paramType == P_CPPEVENTS)
12651 SafeSprintf (&tempStr, &tempStrSize, "\t%d", NumCppEvents(p->subParams[j],coldId));
12652 if (AddToPrintString (tempStr) == ERROR) goto errorExit;
12654 else if (p->subParams[j]->paramType == P_MIXEDBRCHRATES)
12656 SafeSprintf (&tempStr, &tempStrSize, "\t%d", *GetParamIntVals(p->subParams[j],coldId,state[coldId]));
12657 if (AddToPrintString (tempStr) == ERROR) goto errorExit;
12661 else if (p->paramType == P_FOSLRATE)
12663 /* print proportion of ancestral fossils */
12664 SafeSprintf (&tempStr, &tempStrSize, "\t%s", MbPrintNum(PropAncFossil(p, coldId)));
12665 if (AddToPrintString (tempStr) == ERROR) goto errorExit;
12669 /* print ordinary parameters */
12670 for (i=0; i<numPrintParams; i++)
12674 /* get model params and settings */
12675 mp = &modelParams[p->relParts[0]];
12676 m = &modelSettings[p->relParts[0]];
12678 st = GetParamVals (p, coldId, state[coldId]);
12679 sst = GetParamSubVals (p, coldId, state[coldId]);
12681 if (p->paramId == SYMPI_EXP_MS || p->paramId == SYMPI_UNI_MS || p->paramId == SYMPI_FIX_MS)
12683 /* We print symmetric dirichlet alpha value if not fixed and then multistate character state frequencies */
12684 if (p->paramId != SYMPI_FIX_MS)
12686 SafeSprintf (&tempStr, &tempStrSize, "\t%s", MbPrintNum(st[0]));
12687 if (AddToPrintString (tempStr) == ERROR) goto errorExit;
12689 sst = GetParamStdStateFreqs (p, coldId, state[coldId]);
12690 if (p->hasBinaryStd == YES)
12691 sst += 2 * m->numBetaCats;
12692 for (j=0; j<p->nSympi; j++)
12694 for (k=0; k<p->sympinStates[j]; k++)
12696 SafeSprintf (&tempStr, &tempStrSize, "\t%s", MbPrintNum(*sst++));
12697 if (AddToPrintString (tempStr) == ERROR) goto errorExit;
12701 else if (p->paramType == P_PI)
12703 /* We print the subvalues if we are dealing with state frequencies (state frequencies are held in subvalues). */
12704 for (j=0; j<p->nSubValues; j++)
12706 SafeSprintf (&tempStr, &tempStrSize, "\t%s", MbPrintNum(sst[j]));
12707 if (AddToPrintString (tempStr) == ERROR) goto errorExit;
12710 else if (p->paramType == P_TRATIO && !strcmp(mp->tratioFormat,"Dirichlet"))
12712 SafeSprintf (&tempStr, &tempStrSize, "\t%s", MbPrintNum(st[0] / (1.0 + st[0])));
12713 if (AddToPrintString (tempStr) == ERROR) goto errorExit;
12714 SafeSprintf (&tempStr, &tempStrSize, "\t%s", MbPrintNum(1.0 / (1.0 + st[0])));
12715 if (AddToPrintString (tempStr) == ERROR) goto errorExit;
12717 else if (p->paramType == P_REVMAT)
12719 if (!strcmp(mp->revmatFormat,"Ratio"))
12721 sum = st[p->nValues-1];
12722 for (j=0; j<p->nValues; j++)
12724 SafeSprintf (&tempStr, &tempStrSize, "\t%s", MbPrintNum(st[j] / sum));
12725 if (AddToPrintString (tempStr) == ERROR) goto errorExit;
12730 /* we already have rate proportions */
12731 for (j=0; j<p->nValues; j++)
12733 SafeSprintf (&tempStr, &tempStrSize, "\t%s", MbPrintNum(st[j]));
12734 if (AddToPrintString (tempStr) == ERROR) goto errorExit;
12737 if (p->paramId == REVMAT_MIX)
12739 /* add model index and k for nst=mixed */
12740 SafeSprintf (&tempStr, &tempStrSize, "\t%d", FromGrowthFxnToIndex(GetParamIntVals(p, coldId, state[coldId])));
12741 if (AddToPrintString (tempStr) == ERROR) goto errorExit;
12742 SafeSprintf (&tempStr, &tempStrSize, "\t%d", GetKFromGrowthFxn(GetParamIntVals(p, coldId, state[coldId])));
12743 if (AddToPrintString (tempStr) == ERROR) goto errorExit;
12746 else if (p->paramType == P_RATEMULT)
12748 if (!strcmp(mp->ratemultFormat,"Ratio"))
12750 for (j=0; j<p->nValues; j++)
12752 SafeSprintf (&tempStr, &tempStrSize, "\t%s", MbPrintNum(st[j] / st[0]));
12753 if (AddToPrintString (tempStr) == ERROR) goto errorExit;
12756 else if (!strcmp(mp->ratemultFormat, "Dirichlet"))
12759 for (j=0; j<p->nValues; j++)
12761 for (j=0; j<p->nValues; j++)
12763 SafeSprintf (&tempStr, &tempStrSize, "\t%s", MbPrintNum(st[j] / sum));
12764 if (AddToPrintString (tempStr) == ERROR) goto errorExit;
12769 for (j=0; j<p->nValues; j++)
12771 SafeSprintf (&tempStr, &tempStrSize, "\t%s", MbPrintNum(st[j]));
12772 if (AddToPrintString (tempStr) == ERROR) goto errorExit;
12776 else if (p->paramType == P_AAMODEL)
12778 for (j=0; j<p->nValues; j++)
12780 SafeSprintf (&tempStr, &tempStrSize, "\t%d", (int)st[j]);
12781 if (AddToPrintString (tempStr) == ERROR) goto errorExit;
12786 /* run of the mill parameter */
12787 for (j=0; j<p->nValues; j++)
12789 SafeSprintf (&tempStr, &tempStrSize, "\t%s", MbPrintNum(st[j]));
12790 if (AddToPrintString (tempStr) == ERROR) goto errorExit;
12794 if (p->paramType == P_OMEGA && p->paramId != OMEGA_DIR && p->paramId != OMEGA_FIX && p->paramId != OMEGA_FFF && p->paramId != OMEGA_FF && p->paramId != OMEGA_10FFF)
12796 /* OK, we also need to print subvalues for the category frequencies in a NY98-like model. */
12797 if (!strcmp(mp->omegaVar, "M10"))
12799 for (j=0; j<4; j++)
12801 SafeSprintf (&tempStr, &tempStrSize, "\t%s", MbPrintNum(sst[mp->numM10BetaCats + mp->numM10GammaCats + 4 + j]));
12802 if (AddToPrintString (tempStr) == ERROR) goto errorExit;
12804 for (j=0; j<2; j++)
12806 SafeSprintf (&tempStr, &tempStrSize, "\t%s", MbPrintNum(sst[mp->numM10BetaCats + mp->numM10GammaCats + j]));
12807 if (AddToPrintString (tempStr) == ERROR) goto errorExit;
12812 for (j=0; j<3; j++)
12814 SafeSprintf (&tempStr, &tempStrSize, "\t%s", MbPrintNum(sst[j]));
12815 if (AddToPrintString (tempStr) == ERROR) goto errorExit;
12821 /* if user wants site rates, we print those here */
12822 if (inferSiteRates == YES)
12824 for (d=0; d<numCurrentDivisions; d++)
12826 m = &modelSettings[d];
12827 if (m->printSiteRates == YES)
12829 mp = &modelParams[d];
12830 tree = GetTree (m->brlens, coldId, state[coldId]);
12831 node = tree->root->left;
12832 m->PrintSiteRates (node, d, coldId);
12837 /* If the user wants to infer sites that are under positive selection, then we need to print out the posterior
12838 probability that each site is a positively selected one here. */
12839 if (inferPosSel == YES)
12841 /* loop over the divisions, calculating the probability of being in the positively
12842 selected class for each relevant partition */
12843 for (d=0; d<numCurrentDivisions; d++)
12845 m = &modelSettings[d];
12846 tree = GetTree(m->brlens, coldId, state[coldId]);
12847 if (m->printPosSel == YES)
12849 if (m->PosSelProbs (tree->root->left, d, coldId) == ERROR)
12856 /* print the probabilities for the appropriate sites in the original alignment */
12857 for (i=0; i<numChar; i++)
12858 printedChar[i] = NO;
12859 for (i=0; i<numChar; i++)
12861 compressedCharPosition = compCharPos[i];
12862 if (!(posSelProbs[compressedCharPosition] < 0.0) && printedChar[i] == NO && charInfo[i].isExcluded == NO)
12864 for (j=k=0; j<numChar; j++)
12866 if (charInfo[j].charId == charInfo[i].charId)
12868 origAlignmentChars[k++] = j;
12869 printedChar[j] = YES;
12872 SafeSprintf (&tempStr, &tempStrSize, "\t%s", MbPrintNum(posSelProbs[compressedCharPosition]));
12873 if (AddToPrintString (tempStr) == ERROR) goto errorExit;
12874 /* printf ("%4d -> (%3d,%3d,%3d) %1.25le\n", i, origAlignmentChars[0]+1, origAlignmentChars[1]+1,
12875 origAlignmentChars[2]+1, posSelProbs[compressedCharPosition]); */
12880 /* If the user wants omega values for each site, we print those here. */
12881 if (inferSiteOmegas == YES)
12883 /* loop over the divisions, calculating the omega value for each site */
12884 for (d=0; d<numCurrentDivisions; d++)
12886 m = &modelSettings[d];
12887 tree = GetTree(m->brlens, coldId, state[coldId]);
12888 if (m->printSiteOmegas == YES)
12890 if (m->SiteOmegas (tree->root->left, d, coldId) == ERROR)
12897 /* print the site omegas for the appropriate sites in the original alignment */
12898 /* note that we use posSelProbs to pass values between SiteOmegas and this function */
12899 for (i=0; i<numChar; i++)
12900 printedChar[i] = NO;
12901 for (i=0; i<numChar; i++)
12903 compressedCharPosition = compCharPos[i];
12904 if (posSelProbs[compressedCharPosition] >= 0.0 && printedChar[i] == NO && charInfo[i].isExcluded == NO)
12906 for (j=k=0; j<numChar; j++)
12908 if (charInfo[j].charId == charInfo[i].charId)
12910 origAlignmentChars[k++] = j;
12911 printedChar[j] = YES;
12914 SafeSprintf (&tempStr, &tempStrSize, "\t%s", MbPrintNum(posSelProbs[compressedCharPosition]));
12915 if (AddToPrintString (tempStr) == ERROR) goto errorExit;
12916 /* printf ("%4d -> (%3d,%3d,%3d) %1.25le\n", i, origAlignmentChars[0]+1, origAlignmentChars[1]+1,
12917 origAlignmentChars[2]+1, posSelProbs[compressedCharPosition]); */
12922 /* free memory for positive selection probs or site omegas */
12923 if (inferPosSel == YES || inferSiteOmegas == YES)
12925 if (memAllocs[ALLOC_POSSELPROBS] == YES)
12926 free (posSelProbs);
12927 memAllocs[ALLOC_POSSELPROBS] = NO;
12928 free (printedChar);
12931 /* if user wants ancestral states for constrained nodes, we obtain and print those here */
12932 if (inferAncStates == YES)
12934 for (d=0; d<numCurrentDivisions; d++)
12936 m = &modelSettings[d];
12937 if (m->printAncStates == YES)
12939 mp = &modelParams[d];
12940 tree = GetTree (m->brlens, coldId, state[coldId]);
12941 for (i=j=tree->nIntNodes - 1; i>=0; i--)
12943 node = tree->intDownPass[i];
12944 m->CondLikeUp (node, d, coldId);
12946 for (k=0; k<numDefinedConstraints; k++)
12948 if (mp->activeConstraints[k] == NO || definedConstraintsType[k] != HARD)
12950 for (i=tree->nIntNodes-1; i>=0; i--)
12952 node = tree->intDownPass[i];
12953 if (node->isLocked == YES && k == node->lockID)
12954 m->PrintAncStates (node, d, coldId);
12961 SafeSprintf (&tempStr, &tempStrSize, "\n");
12962 if (AddToPrintString (tempStr) == ERROR) goto errorExit;
12965 SafeFree ((void **)&partString);
12971 free (printedChar);
12972 if (memAllocs[ALLOC_POSSELPROBS] == YES)
12973 free (posSelProbs);
12974 memAllocs[ALLOC_POSSELPROBS] = NO;
12976 SafeFree ((void **)&partString);
12981 /*----------------------------------------------------------------------
12983 | PrintStatesToFiles: Print trees and model parameters to files. We
12984 | only come into this function if it is the first cycle of the chain
12985 | or if we hit a cycle number evenly divisible by the sample frequency,
12986 | or this is the last cycle of the chain.
12988 ------------------------------------------------------------------------*/
12989 int PrintStatesToFiles (int curGen)
12991 int i, j, chn, coldId, runId;
12995 # if defined (MPI_ENABLED)
12996 int id, x, doesThisProcHaveId, procWithChain, ierror, tag, nErrors, sumErrors;
13000 # if !defined (MPI_ENABLED)
13002 /* print parameter values and trees (single-processor version) */
13003 for (chn=0; chn<numLocalChains; chn++)
13005 if ((chainId[chn] % chainParams.numChains) == 0)
13008 runId = chainId[chn] / chainParams.numChains;
13010 /* print parameter values */
13011 if (PrintStates (curGen, coldId) == ERROR)
13013 fprintf (fpParm[runId], "%s", printString);
13014 fflush (fpParm[runId]);
13018 for (i=0; i<numPrintTreeParams; i++)
13020 param = printTreeParam[i];
13021 tree = GetTree(param, coldId, state[coldId]);
13022 if (param->paramType == P_TOPOLOGY)
13024 if (tree->isClock == YES)
13025 clockRate = *GetParamVals(modelSettings[tree->relParts[0]].clockRate, coldId, state[coldId]);
13028 if (PrintTree (curGen, param, coldId, NO, clockRate) == ERROR)
13033 if (tree->isClock == YES)
13034 clockRate = *GetParamVals(modelSettings[tree->relParts[0]].clockRate, coldId, state[coldId]);
13037 if (PrintTree (curGen, param, coldId, YES, clockRate) == ERROR)
13041 fprintf (fpTree[runId][i], "%s", printString);
13042 fflush (fpTree[runId][i]);
13045 j = printTreeTopologyIndex[i];
13046 if (j<numTopologies)
13048 if (chainParams.mcmcDiagn == YES && chainParams.numRuns > 1)
13050 if (chainParams.relativeBurnin == YES || curGen >= chainParams.chainBurnIn * chainParams.sampleFreq)
13052 if (AddTreeToPartitionCounters (tree, j, runId) == ERROR)
13054 if (chainParams.relativeBurnin == YES && chainParams.saveTrees == YES && (noWarn == NO || curGen <= chainParams.stopTreeGen))
13056 ResetTopologyFromTree (chainParams.dtree, tree);
13057 if (AddToTreeList (&chainParams.treeList[numTopologies*runId+j], chainParams.dtree) == ERROR)
13067 /* print parameter values and trees (parallel version) */
13069 /* Wait for all of the processors to get to this point before starting the printing. */
13070 ierror = MPI_Barrier (MPI_COMM_WORLD);
13071 if (ierror != MPI_SUCCESS)
13073 MrBayesPrint ("%s Problem at chain barrier.\n", spacer);
13078 /* Loop over runs. */
13079 for (runId=0; runId<chainParams.numRuns; runId++)
13081 /* Get the ID of the chain we want to print. Remember, the ID's should be numbered
13082 0, 1, 2, ..., numChains X numRuns. Chains numbered 0, numChains, 2 X numChains, ...
13084 id = runId * chainParams.numChains;
13086 /* Does this processor have the chain? */
13087 doesThisProcHaveId = NO;
13089 for (chn=0; chn<numLocalChains; chn++)
13091 if (chainId[chn] == id)
13093 doesThisProcHaveId = YES;
13099 /* Tell all the processors which has the chain we want to print. We do this using the MPI_AllReduce
13100 function. If the processor does not have the chain, then it initializes x = 0. If it does
13101 have the chain, then x = proc_id. When the value of x is summed over all the processors, the sum
13102 should be the proc_id of the processor with the chain. Possible values are 0, 1, 2, num_procs-1.
13103 Note that every processor knows procWithChain because we are using MPI_Allreduce, instead of MPI_Reduce. */
13105 if (doesThisProcHaveId == YES)
13107 ierror = MPI_Allreduce (&x, &procWithChain, 1, MPI_INT, MPI_SUM, MPI_COMM_WORLD);
13108 if (ierror != MPI_SUCCESS)
13110 MrBayesPrint ("%s Problem finding processor with chain to print.\n", spacer);
13114 /* ****************************************************************************************************/
13115 /* print parameter values *****************************************************************************/
13117 /* Fill printString with the contents to be printed on proc_id = 0. Note
13118 that printString is allocated in the function. */
13119 if (doesThisProcHaveId == YES)
13121 if (PrintStates (curGen, coldId) == ERROR)
13124 MPI_Allreduce (&nErrors, &sumErrors, 1, MPI_INT, MPI_SUM, MPI_COMM_WORLD);
13127 MrBayesPrint ("%s Problem with PrintStates.\n", spacer);
13131 /* First communication: Send/receive the length of the printString. */
13132 if (proc_id == 0 || proc_id == procWithChain)
13134 if (procWithChain != 0)
13136 if (proc_id == procWithChain)
13138 /* Find out how large the string is, and send the information to proc_id = 0. */
13139 ierror = MPI_Send (&printStringSize, 1, MPI_LONG, 0, tag, MPI_COMM_WORLD);
13140 if (ierror != MPI_SUCCESS)
13145 /* Receive the length of the string from proc_id = procWithChain, and then allocate
13146 printString to be that length. */
13147 ierror = MPI_Recv (&printStringSize, 1, MPI_LONG, procWithChain, tag, MPI_COMM_WORLD, &status);
13148 if (ierror != MPI_SUCCESS)
13150 MrBayesPrint ("%s Problem receiving printStringSize from proc_id = %d\n", spacer, procWithChain);
13153 printString = (char *)SafeMalloc((size_t)printStringSize * sizeof(char));
13156 MrBayesPrint ("%s Problem allocating printString (%d)\n", spacer, printStringSize * sizeof(char));
13159 strcpy (printString, "");
13163 MPI_Allreduce (&nErrors, &sumErrors, 1, MPI_INT, MPI_SUM, MPI_COMM_WORLD);
13166 MrBayesPrint ("%s Problem with first communication (states).\n", spacer);
13170 /* Second communication: Send/receive the printString. */
13171 if (proc_id == 0 || proc_id == procWithChain)
13173 if (procWithChain != 0)
13175 if (proc_id == procWithChain)
13177 /* Send the printString to proc_id = 0. After we send the string to proc_id = 0, we can
13179 ierror = MPI_Send (&printString[0], (int)printStringSize, MPI_CHAR, 0, tag, MPI_COMM_WORLD);
13180 if (ierror != MPI_SUCCESS)
13186 /* Receive the printString from proc_id = procWithChain. */
13187 ierror = MPI_Recv (&printString[0], (int)printStringSize, MPI_CHAR, procWithChain, tag, MPI_COMM_WORLD, &status);
13188 if (ierror != MPI_SUCCESS)
13190 MrBayesPrint ("%s Problem receiving printString from proc_id = %d\n", spacer, procWithChain);
13196 MPI_Allreduce (&nErrors, &sumErrors, 1, MPI_INT, MPI_SUM, MPI_COMM_WORLD);
13199 MrBayesPrint ("%s Problem with second communication (states).\n", spacer);
13203 /* Print the string with the parameter information if we are proc_id = 0. */
13206 fprintf (fpParm[runId], "%s", printString);
13207 fflush (fpParm[runId]);
13211 /* ****************************************************************************************************/
13212 /* print trees ****************************************************************************************/
13214 for (i=0; i<numPrintTreeParams; i++)
13216 /* Print trees to file. */
13218 /* Fill printString with the contents to be printed on proc_id = 0. Note
13219 that printString is allocated in the function. */
13220 if (doesThisProcHaveId == YES)
13222 param = printTreeParam[i];
13223 tree = GetTree(param, coldId, state[coldId]);
13224 if (param->paramType == P_TOPOLOGY)
13226 if (tree->isClock == YES)
13227 clockRate = *GetParamVals(modelSettings[tree->relParts[0]].clockRate, coldId, state[coldId]);
13230 if (PrintTree (curGen, param, coldId, NO, clockRate) == ERROR)
13235 if (tree->isClock == YES)
13236 clockRate = *GetParamVals(modelSettings[tree->relParts[0]].clockRate, coldId, state[coldId]);
13239 if (PrintTree (curGen, param, coldId, YES, clockRate) == ERROR)
13243 MPI_Allreduce (&nErrors, &sumErrors, 1, MPI_INT, MPI_SUM, MPI_COMM_WORLD);
13246 MrBayesPrint ("%s Problem with printing trees.\n", spacer);
13250 /* First communication: Send/receive the length of the printString. */
13251 if (proc_id == 0 || proc_id == procWithChain)
13253 if (procWithChain != 0)
13255 if (proc_id == procWithChain)
13257 /* Find out how large the string is, and send the information to proc_id = 0. */
13258 ierror = MPI_Send (&printStringSize, 1, MPI_LONG, 0, tag, MPI_COMM_WORLD);
13259 if (ierror != MPI_SUCCESS)
13264 /* Receive the length of the string from proc_id = procWithChain, and then allocate
13265 printString to be that length. */
13266 ierror = MPI_Recv (&printStringSize, 1, MPI_LONG, procWithChain, tag, MPI_COMM_WORLD, &status);
13267 if (ierror != MPI_SUCCESS)
13269 MrBayesPrint ("%s Problem receiving printStringSize from proc_id = %d\n", spacer, procWithChain);
13272 printString = (char *)SafeMalloc((size_t)printStringSize * sizeof(char));
13275 MrBayesPrint ("%s Problem allocating printString (%d)\n", spacer, printStringSize * sizeof(char));
13278 strcpy (printString, "");
13282 MPI_Allreduce (&nErrors, &sumErrors, 1, MPI_INT, MPI_SUM, MPI_COMM_WORLD);
13285 MrBayesPrint ("%s Problem with first communication (states).\n", spacer);
13289 /* Second communication: Send/receive the printString. */
13290 if (proc_id == 0 || proc_id == procWithChain)
13292 if (procWithChain != 0)
13294 if (proc_id == procWithChain)
13296 /* Send the printString to proc_id = 0. After we send the string to proc_id = 0, we can
13298 ierror = MPI_Send (&printString[0], (int)printStringSize, MPI_CHAR, 0, tag, MPI_COMM_WORLD);
13299 if (ierror != MPI_SUCCESS)
13305 /* Receive the printString from proc_id = procWithChain. */
13306 ierror = MPI_Recv (&printString[0], (int)printStringSize, MPI_CHAR, procWithChain, tag, MPI_COMM_WORLD, &status);
13307 if (ierror != MPI_SUCCESS)
13309 MrBayesPrint ("%s Problem receiving printString from proc_id = %d\n", spacer, procWithChain);
13315 MPI_Allreduce (&nErrors, &sumErrors, 1, MPI_INT, MPI_SUM, MPI_COMM_WORLD);
13318 MrBayesPrint ("%s Problem with second communication (states).\n", spacer);
13322 /* Print the string with the parameter information if we are proc_id = 0. */
13325 fprintf (fpTree[runId][i], "%s", printString);
13326 fflush (fpTree[runId][i]);
13327 j = printTreeTopologyIndex[i];
13328 if (j < numTopologies)
13330 if (chainParams.numRuns > 1 && chainParams.mcmcDiagn == YES)
13332 if (chainParams.relativeBurnin == YES || curGen >= chainParams.chainBurnIn * chainParams.sampleFreq)
13335 StripComments (printString);
13336 /* if it is the first tree, we strip out the translate block first (twice) */
13338 if (strtok (printString, ";")==NULL) /* get translate lock */
13340 if (strtok (NULL, ";")==NULL)
13342 if (strtok (NULL, "\n\t\r ")==NULL) /* get 'tree' */
13346 if (strtok (printString, "\n\t\r ")==NULL) /* get 'tree' */
13349 if (strtok (NULL, " =")==NULL) /* get 'rep.xxxx' */
13351 if ((s = strtok (NULL, " =;"))==NULL) /* get Newick string */
13353 ResetTopology (chainParams.dtree, s);
13354 if (AddTreeToPartitionCounters (chainParams.dtree, j, runId) == ERROR)
13356 if (chainParams.relativeBurnin == YES && chainParams.saveTrees == YES && (noWarn == NO || curGen <= chainParams.stopTreeGen))
13358 if (AddToTreeList (&chainParams.treeList[runId*numTopologies+j], chainParams.dtree) == ERROR)
13368 /* Have all of the chains wait here, until the string has been successfully printed on proc_id = 0. */
13369 ierror = MPI_Barrier (MPI_COMM_WORLD);
13370 if (ierror != MPI_SUCCESS)
13372 MrBayesPrint ("%s Problem at chain barrier.\n", spacer);
13382 int PrintSwapInfo (void)
13384 int i, j, n, maxNumExchanges, len, maxLen, reweightingChars=0;
13388 if (chainParams.numChains == 1)
13391 # if defined (MPI_ENABLED)
13392 if (ReassembleSwapInfo() == ERROR)
13398 tempStrSize = TEMPSTRSIZE;
13399 tempStr = (char *) SafeMalloc((size_t)tempStrSize * sizeof(char));
13402 MrBayesPrint ("%s Problem allocating tempString (%d)\n", spacer, tempStrSize * sizeof(char));
13406 for (n=0; n<chainParams.numRuns; n++)
13408 maxNumExchanges = 0;
13409 for (i=0; i<chainParams.numChains; i++)
13410 for (j=0; j<chainParams.numChains; j++)
13411 if (i > j && swapInfo[n][i][j] > maxNumExchanges)
13412 maxNumExchanges = swapInfo[n][i][j];
13413 SafeSprintf (&tempStr, &tempStrSize, "%d", maxNumExchanges);
13414 maxLen = (int) strlen(tempStr);
13418 reweightingChars = NO;
13419 if ((chainParams.weightScheme[0] + chainParams.weightScheme[1]) > 0.00001)
13420 reweightingChars = YES;
13422 if (chainParams.numRuns == 1)
13423 MrBayesPrint ("\n%s Chain swap information:\n\n", spacer);
13425 MrBayesPrint ("\n%s Chain swap information for run %d:\n\n", spacer, n+1);
13427 MrBayesPrint ("%s ", spacer);
13428 for (j=0; j<chainParams.numChains; j++)
13430 SafeSprintf (&tempStr, &tempStrSize, "%d", j+1);
13431 len = (int) strlen(tempStr);
13432 MrBayesPrint ("%*c %d ", maxLen-len, ' ', j+1);
13434 MrBayesPrint ("\n");
13436 MrBayesPrint ("%s --", spacer);
13437 for (j=0; j<chainParams.numChains; j++)
13439 MrBayesPrint ("--");
13440 for (i=0; i<maxLen; i++)
13441 MrBayesPrint ("-");
13443 MrBayesPrint ("\n");
13445 for (i=0; i<chainParams.numChains; i++)
13447 MrBayesPrint ("%s %4d | ", spacer, i+1);
13448 for (j=0; j<chainParams.numChains; j++)
13452 if (swapInfo[n][j][i] <= 0)
13454 MrBayesPrint ("%*c%s ", maxLen-3, ' ', " NA ");
13458 SafeSprintf (&tempStr, &tempStrSize, "%1.2lf", (MrBFlt)swapInfo[n][i][j]/swapInfo[n][j][i]);
13459 len = (int) strlen(tempStr);
13460 MrBayesPrint ("%*c%1.2lf ", maxLen-len+1, ' ', (MrBFlt)swapInfo[n][i][j]/swapInfo[n][j][i]);
13465 MrBayesPrint ("%*c ", maxLen+1, ' ');
13469 SafeSprintf (&tempStr, &tempStrSize, "%d", swapInfo[n][i][j]);
13470 len = (int) strlen(tempStr);
13471 MrBayesPrint ("%*c%d ", maxLen-len+1, ' ', swapInfo[n][i][j]);
13474 MrBayesPrint ("\n");
13478 MrBayesPrint ("\n%s Upper diagonal: Proportion of successful state exchanges between chains\n", spacer);
13479 MrBayesPrint ("%s Lower diagonal: Number of attempted state exchanges between chains\n", spacer);
13481 MrBayesPrint ("\n%s Chain information:\n\n", spacer);
13482 MrBayesPrint ("%s ID -- Heat ", spacer);
13483 if (reweightingChars == YES)
13484 MrBayesPrint ("%% Dn %% Up\n");
13486 MrBayesPrint ("\n");
13488 MrBayesPrint ("%s -----------", spacer);
13489 if (reweightingChars == YES)
13490 MrBayesPrint ("----------\n");
13492 MrBayesPrint ("\n");
13493 for (i=0; i<chainParams.numChains; i++)
13495 MrBayesPrint ("%s %4d -- %1.2lf ", spacer, i+1, Temperature (i)/*1.0 / (1.0 + chainParams.chainTemp * i)*/);
13496 if (reweightingChars == YES)
13500 MrBayesPrint (" 0%% 0%% (cold chain)\n");
13504 SafeSprintf (&tempStr, &tempStrSize, "%d", (int)chainParams.weightScheme[0]);
13505 len = (int) strlen(tempStr);
13506 MrBayesPrint ("%*c%d%% ", 3-len, ' ', (int)chainParams.weightScheme[0]);
13507 SafeSprintf (&tempStr, &tempStrSize, "%d", (int)chainParams.weightScheme[1]);
13508 len = (int) strlen(tempStr);
13509 MrBayesPrint ("%*c%d%% \n", 3-len, ' ', (int)chainParams.weightScheme[1]);
13515 MrBayesPrint (" (cold chain)\n");
13517 MrBayesPrint ("\n");
13520 if (chainParams.userDefinedTemps == NO)
13522 MrBayesPrint ("\n%s Heat = 1 / (1 + T * (ID - 1))\n", spacer);
13523 MrBayesPrint ("%s (where T = %1.2lf is the temperature and ID is the chain number)\n", spacer, chainParams.chainTemp);
13525 if (reweightingChars == YES)
13526 MrBayesPrint ("%s Reweighting increment = %1.2lf\n", spacer, chainParams.weightScheme[2]);
13527 MrBayesPrint ("\n");
13534 /*----------------------------------------------------------------------
13536 | PrintTermState: Print terminal state index matrix
13538 ------------------------------------------------------------------------*/
13539 int PrintTermState (void)
13541 int i, j=0, c, d, printWidth, nextColumn, nDigits, nReps;
13547 for (d=0; d<numCurrentDivisions; d++)
13549 MrBayesPrint ("\nTerminal state index matrix for division %d\n\n", d+1);
13551 m = &modelSettings[d];
13552 mp = &modelParams[d];
13554 if (!strcmp(mp->covarionModel, "Yes"))
13559 nDigits = 1 + (int)(log10(mp->nStates * mp->nStates * nReps));
13561 for (c=m->compCharStart; c<m->compCharStop; c=j)
13563 for (i=0; i<numTaxa; i++)
13565 MrBayesPrint ("%-10.10s ", taxaNames[i]);
13567 for (nextColumn=13; nextColumn < printWidth; nextColumn+=nDigits + 1)
13569 if (j >= m->compCharStop)
13571 MrBayesPrint ("%*d ",nDigits, m->termState[i][j-c]);
13574 MrBayesPrint ("\n");
13576 MrBayesPrint("\n");
13578 } /* next division */
13584 /*--------------------------------------------------
13586 | PrintTiProbs: This function is for debugging of
13587 | tiProbs; it will print a square matrix of
13588 | tiProbs, check row sums, and check for time
13591 ---------------------------------------------------*/
13592 void PrintTiProbs (CLFlt *tP, MrBFlt *bs, int nStates)
13599 printf ("\nTransition matrix\n");
13600 for (i=0; i<nStates; i++)
13602 printf ("\t%d", i);
13604 printf ("\tsum\n");
13606 for (i=0; i<nStates; i++)
13608 printf ("%d\t", i);
13610 for (j=0; j<nStates; j++)
13612 printf ("\t%.6f",tP[j]);
13615 printf ("\t%.6f\n",sum);
13619 printf ("\nStationary state frequencies\n");
13620 for (i=0; i<nStates; i++)
13621 printf ("%d -- %f\n",i,bs[i]);
13623 printf ("\nTime reversibility\n");
13625 printf ("State 1\tState 2\tforward\tbackward\tabs diff\n");
13626 for (i=0; i<nStates; i++)
13628 for (j=i+1; j<nStates; j++)
13630 printf ("%d\t%d\t%.6f\t%.6f\t%.6f\n", i, j, tiP[i*nStates+j]*bs[i],
13631 tiP[j*nStates+i]*bs[j], fabs(tiP[i*nStates+j]*bs[i] - tiP[j*nStates+i]*bs[j]));
13640 int PrintTopConvInfo (void)
13642 int i, j, n, len, maxLen;
13645 MrBFlt maxNumPartitions;
13648 if (chainParams.numRuns == 1)
13651 # if defined (MPI_ENABLED)
13656 tempStrSize = TEMPSTRSIZE;
13657 tempStr = (char *) SafeMalloc((size_t)tempStrSize * sizeof(char));
13660 MrBayesPrint ("%s Problem allocating tempString (%d)\n", spacer, tempStrSize * sizeof(char));
13664 for (n=0; n<numTopologies; n++)
13666 stat = &(chainParams.stat[n]);
13667 maxNumPartitions = 0.0;
13668 for (i=0; i<chainParams.numRuns; i++)
13669 for (j=0; j<chainParams.numRuns; j++)
13670 if (i > j && stat->pair[i][j] > maxNumPartitions)
13671 maxNumPartitions = stat->pair[i][j];
13672 SafeSprintf (&tempStr, &tempStrSize, "%d", (int) maxNumPartitions);
13673 maxLen = (int) strlen(tempStr);
13677 if (numTopologies == 1)
13679 if (chainParams.diagnStat == AVGSTDDEV)
13680 MrBayesPrint ("%s Pairwise average standard deviation of split frequencies (upper triangle)\n", spacer);
13682 MrBayesPrint ("%s Pairwise maximum standard deviation of split frequencies (upper triangle)\n", spacer);
13683 MrBayesPrint ("%s and number of qualifying splits for each comparison (lower triangle):\n\n", spacer);
13687 if (chainParams.diagnStat == AVGSTDDEV)
13688 MrBayesPrint ("%s Pairwise average standard deviation of split frequencies in topology %d (upper triangle)\n", spacer, n);
13690 MrBayesPrint ("%s Pairwise maximum standard deviation of split frequencies in topology %d (upper triangle)\n", spacer, n);
13691 MrBayesPrint ("%s and number of qualifying splits for each comparison (lower triangle):\n\n", spacer);
13694 MrBayesPrint ("%s ", spacer);
13695 for (j=0; j<chainParams.numRuns; j++)
13697 SafeSprintf (&tempStr, &tempStrSize, "%d", j+1);
13698 len = (int) strlen(tempStr);
13699 MrBayesPrint ("%*c %d ", maxLen-len, ' ', j+1);
13701 MrBayesPrint ("\n");
13703 MrBayesPrint ("%s --", spacer);
13704 for (j=0; j<chainParams.numRuns; j++)
13706 MrBayesPrint ("--");
13707 for (i=0; i<maxLen; i++)
13708 MrBayesPrint ("-");
13710 MrBayesPrint ("\n");
13712 for (i=0; i<chainParams.numRuns; i++)
13714 MrBayesPrint ("%s %4d | ", spacer, i+1);
13715 for (j=0; j<chainParams.numRuns; j++)
13719 if (chainParams.diagnStat == AVGSTDDEV)
13720 SafeSprintf (&tempStr, &tempStrSize, "%1.3lf", (MrBFlt) (stat->pair[i][j]) / (MrBFlt) (stat->pair[j][i]));
13721 else /* if (chainParams.diagnStat == MAXSTDDEV) */
13722 SafeSprintf (&tempStr, &tempStrSize, "%1.3lf", stat->pair[i][j]);
13723 len = (int) strlen(tempStr);
13724 MrBayesPrint ("%*c%s ", maxLen-len+1, ' ', tempStr);
13728 MrBayesPrint ("%*c ", maxLen+1, ' ');
13732 SafeSprintf (&tempStr, &tempStrSize, "%d", (int) stat->pair[i][j]);
13733 len = (int) strlen(tempStr);
13734 MrBayesPrint ("%*c%s ", maxLen-len+1, ' ', tempStr);
13737 MrBayesPrint ("\n");
13740 MrBayesPrint ("\n");
13748 void PrintToScreen (int curGen, int startGen, time_t endingT, time_t startingT)
13750 int i, chn, nHours, nMins, nSecs;
13753 # if defined (MPI_ENABLED)
13754 int numLocalColdChains, numFirstAndLastCold;
13758 if (chainParams.isSS == NO && chainParams.mcmcDiagn == YES && chainParams.numRuns > 1)
13760 MrBayesPrint ("\n");
13761 if (chainParams.relativeBurnin == YES)
13762 MrBayesPrint ("%s Using a relative burnin of %.1f %% for diagnostics\n", spacer, 100.0*chainParams.burninFraction);
13764 MrBayesPrint ("%s Using an absolute burnin of %d samples for diagnostics\n", spacer, chainParams.chainBurnIn);
13766 MrBayesPrint ("\n");
13767 MrBayesPrint ("%s Chain results (%d generations requested):\n\n", spacer, chainParams.numGen);
13769 MrBayesPrint ("%s %4d -- ", spacer, curGen);
13770 numLocalColdChains = numFirstAndLastCold = 0;
13771 for (chn=0; chn<numLocalChains; chn++)
13773 if ((chainId[chn] % chainParams.numChains) == 0)
13775 numLocalColdChains++;
13776 if (chn == 0 || chn == numLocalChains - 1)
13777 numFirstAndLastCold++;
13782 for (chn=0; chn<numLocalChains; chn++)
13784 if (i > chainParams.printMax)
13786 if (i == chainParams.printMax +1)
13789 if (numLocalColdChains > 0 && numLocalColdChains > numFirstAndLastCold)
13790 MrBayesPrint ("[...%d more local chains...] ", numLocalChains - chainParams.printMax);
13792 MrBayesPrint ("(...%d more local chains...) ", numLocalChains - chainParams.printMax);
13798 if ((chainId[chn] % chainParams.numChains) == 0)
13801 if (chainParams.printAll == YES)
13802 MrBayesPrint ("[%1.3lf] ", curLnL[chn]);
13804 MrBayesPrint ("[%1.3lf] .. ", curLnL[chn]);
13806 else if (chainParams.printAll == YES)
13809 MrBayesPrint ("(%1.3lf) ", curLnL[chn]);
13811 if (chn < numLocalChains - 1 && (chainId[chn] / chainParams.numChains != chainId[chn+1] / chainParams.numChains))
13812 MrBayesPrint ("* ");
13815 if (numLocalColdChains == chainParams.numRuns)
13816 MrBayesPrint ("(...%d remote chains...) ", (chainParams.numChains*chainParams.numRuns) - numLocalChains);
13818 MrBayesPrint ("[...%d remote chains...] ", (chainParams.numChains*chainParams.numRuns) - numLocalChains);
13822 timePerGen = (MrBFlt) ((MrBFlt)(endingT-startingT)/(MrBFlt)(curGen-startGen));
13823 nSecs = (int)((chainParams.numGen - curGen) * timePerGen);
13824 nHours = nSecs / 3600;
13825 nSecs = nSecs % 3600;
13826 nMins = nSecs / 60;
13827 nSecs = nSecs % 60;
13828 MrBayesPrint ("-- %d:%0.2d:%0.2d", nHours, nMins, nSecs);
13830 MrBayesPrint ("\n");
13837 if (chainParams.isSS == NO && chainParams.mcmcDiagn == YES && chainParams.numRuns > 1)
13839 MrBayesPrint ("\n");
13840 if (chainParams.relativeBurnin == YES)
13841 MrBayesPrint ("%s Using a relative burnin of %.1f %% for diagnostics\n", spacer, 100.0*chainParams.burninFraction);
13843 MrBayesPrint ("%s Using an absolute burnin of %d samples for diagnostics\n", spacer, chainParams.chainBurnIn);
13845 MrBayesPrint ("\n");
13846 MrBayesPrint ("%s Chain results (%d generations requested):\n\n", spacer, chainParams.numGen);
13848 MrBayesPrint ("%s %5d -- ", spacer, curGen);
13849 if (numLocalChains == 1)
13850 MrBayesPrint ("%1.3lf ", curLnL[0]);
13854 for (chn=0; chn<numLocalChains; chn++)
13856 if (i >= chainParams.printMax)
13858 if (i == chainParams.printMax)
13859 MrBayesPrint (".. ");
13863 if (chainParams.numChains == 1)
13865 MrBayesPrint ("%1.3lf ", curLnL[chn]);
13868 else if (chainId[chn] % chainParams.numChains == 0)
13870 if (chainParams.printAll == YES)
13871 MrBayesPrint ("[%1.3lf] ", curLnL[chn]);
13873 MrBayesPrint ("[%1.3lf][%d] .. ", curLnL[chn], chn % chainParams.numChains + 1);
13876 else if (chainParams.printAll == YES)
13878 MrBayesPrint ("(%1.3lf) ", curLnL[chn]);
13881 if (chn < numLocalChains - 1 && (chainId[chn] / chainParams.numChains != chainId[chn+1] / chainParams.numChains)
13882 && i < chainParams.printMax - 1)
13883 MrBayesPrint ("* ");
13889 timePerGen = (MrBFlt) ((MrBFlt)(endingT-startingT)/(MrBFlt)(curGen-startGen));
13890 nSecs = (int)((chainParams.numGen - curGen) * timePerGen);
13891 nHours = nSecs / 3600;
13892 nSecs = nSecs % 3600;
13893 nMins = nSecs / 60;
13894 nSecs = nSecs % 60;
13895 MrBayesPrint ("-- %d:%0.2d:%0.2d", nHours, nMins, nSecs);
13897 MrBayesPrint ("\n");
13906 int PrintTree (int curGen, Param *treeParam, int chain, int showBrlens, MrBFlt clockRate)
13908 int i, tempStrSize;
13911 TreeNode *p=NULL, *q;
13914 /* allocate the print string */
13915 printStringSize = 200;
13916 printString = (char *)SafeMalloc((size_t)printStringSize * sizeof(char));
13919 MrBayesPrint ("%s Problem allocating printString (%d)\n", spacer, printStringSize * sizeof(char));
13922 *printString = '\0';
13924 tempStrSize = TEMPSTRSIZE;
13925 tempStr = (char *) SafeMalloc((size_t)tempStrSize * sizeof(char));
13928 MrBayesPrint ("%s Problem allocating tempString (%d)\n", spacer, tempStrSize * sizeof(char));
13933 tree = GetTree(treeParam, chain, state[chain]);
13935 /* order the taxa */
13936 if (chainParams.orderTaxa == YES)
13938 for (i=0; i<tree->nNodes-1; i++)
13940 p = tree->allDownPass[i];
13941 if (p->left == NULL)
13943 if (p->index == localOutGroup)
13948 else if (p->left->x < p->right->x)
13951 p->x = p->right->x;
13953 for (i=0; i<tree->nIntNodes; i++)
13955 if (p->left->x > p->right->x)
13958 p->left = p->right;
13964 /* print the translate block information and the top of the file */
13967 /* print #NEXUS and translation block information */
13968 SafeSprintf (&tempStr, &tempStrSize, "#NEXUS\n");
13969 if (AddToPrintString (tempStr) == ERROR) return(ERROR);
13970 SafeSprintf (&tempStr, &tempStrSize, "[ID: %s]\n", stamp);
13971 if (AddToPrintString (tempStr) == ERROR) return(ERROR);
13972 SafeSprintf (&tempStr, &tempStrSize, "[Param: tree");
13973 if (AddToPrintString (tempStr) == ERROR) return(ERROR);
13974 if (numCurrentDivisions == 1)
13976 SafeSprintf (&tempStr, &tempStrSize, "]\n");
13977 if (AddToPrintString (tempStr) == ERROR) return(ERROR);
13979 else if (numCurrentDivisions == tree->nRelParts)
13981 SafeSprintf (&tempStr, &tempStrSize, "{all}]\n");
13982 if (AddToPrintString (tempStr) == ERROR) return(ERROR);
13986 SafeSprintf (&tempStr, &tempStrSize, "{%d", tree->relParts[0]+1);
13987 if (AddToPrintString (tempStr) == ERROR) return(ERROR);
13988 for (i=1; i<tree->nRelParts; i++)
13990 SafeSprintf (&tempStr, &tempStrSize, ",%d", tree->relParts[i]+1);
13991 if (AddToPrintString (tempStr) == ERROR) return(ERROR);
13993 SafeSprintf (&tempStr, &tempStrSize, "}]\n");
13994 if (AddToPrintString (tempStr) == ERROR) return(ERROR);
13996 SafeSprintf (&tempStr, &tempStrSize, "begin trees;\n");
13997 if (AddToPrintString (tempStr) == ERROR) return(ERROR);
13998 SafeSprintf (&tempStr, &tempStrSize, " translate\n");
13999 if (AddToPrintString (tempStr) == ERROR) return(ERROR);
14000 if (treeParam->paramType == P_SPECIESTREE)
14002 for (i=0; i<numSpecies; i++)
14004 if (i != numSpecies - 1)
14005 SafeSprintf (&tempStr, &tempStrSize, " %2d %s,\n", i+1, speciesNameSets[speciespartitionNum].names[i]);
14007 SafeSprintf (&tempStr, &tempStrSize, " %2d %s;\n", i+1, speciesNameSets[speciespartitionNum].names[i]);
14008 if (AddToPrintString (tempStr) == ERROR) return(ERROR);
14013 for (i=0; i<numLocalTaxa; i++)
14015 if (i != numLocalTaxa - 1)
14016 SafeSprintf (&tempStr, &tempStrSize, " %2d %s,\n", i+1, localTaxonNames[i]);
14018 SafeSprintf (&tempStr, &tempStrSize, " %2d %s;\n", i+1, localTaxonNames[i]);
14019 if (AddToPrintString (tempStr) == ERROR) return(ERROR);
14024 /* write the tree preamble */
14025 if (SafeSprintf (&tempStr, &tempStrSize, " tree gen.%d", curGen) == ERROR) return (ERROR);
14026 if (AddToPrintString (tempStr) == ERROR) return(ERROR);
14027 if (treeParam->paramType == P_BRLENS && treeParam->nSubParams > 0)
14029 for (i=0; i<treeParam->nSubParams; i++)
14031 subParm = treeParam->subParams[i];
14032 if (subParm->paramType == P_CPPEVENTS)
14034 if (SafeSprintf (&tempStr, &tempStrSize, " [&E %s]", subParm->name) == ERROR) return (ERROR);
14035 if (AddToPrintString (tempStr) == ERROR) return(ERROR);
14037 // if (subParm->paramType == P_MIXEDBRCHRATES)
14039 // id = *GetParamIntVals(subParm, chain, state[chain]);
14040 // if (SafeSprintf (&tempStr, &tempStrSize, " [&B %s %d]", subParm->name, id) == ERROR) return (ERROR);
14043 if (SafeSprintf (&tempStr, &tempStrSize, " [&B %s]", subParm->name) == ERROR) return (ERROR);
14044 if (AddToPrintString (tempStr) == ERROR) return(ERROR);
14047 subParm = modelSettings[treeParam->relParts[0]].popSize;
14048 if (treeParam->paramType == P_SPECIESTREE && subParm->nValues > 1)
14050 if (SafeSprintf (&tempStr, &tempStrSize, " [&N %s]", subParm->name) == ERROR) return (ERROR);
14051 if (AddToPrintString (tempStr) == ERROR) return(ERROR);
14054 /* write the tree in (extended) Newick format */
14055 if (tree->isRooted == YES && tree->isCalibrated == NO)
14056 SafeSprintf (&tempStr, &tempStrSize, " = [&R] ");
14057 else if (tree->isRooted == YES && tree->isCalibrated == YES)
14058 SafeSprintf (&tempStr, &tempStrSize, " = [&R] [&clockrate=%s] ", MbPrintNum(clockRate));
14059 else /* if (tree->isRooted == NO) */
14060 SafeSprintf (&tempStr, &tempStrSize, " = [&U] ");
14061 if (AddToPrintString (tempStr) == ERROR) return(ERROR);
14062 WriteNoEvtTreeToPrintString (tree->root->left, chain, treeParam, showBrlens, tree->isRooted);
14063 SafeSprintf (&tempStr, &tempStrSize, ";\n");
14064 if (AddToPrintString (tempStr) == ERROR) return(ERROR);
14071 #if defined (MPI_ENABLED)
14072 int ReassembleMoveInfo (void)
14075 double x[7], sum[7];
14078 for (n=0; n<numGlobalChains; n++)
14080 for (i=0; i<numUsedMoves; i++)
14084 /* collect counts */
14085 x[0] = mv->nAccepted[n];
14086 x[1] = mv->nTried[n];
14087 x[2] = mv->nBatches[n];
14088 x[3] = mv->nTotAccepted[n];
14089 x[4] = mv->nTotTried[n];
14090 x[5] = mv->lastAcceptanceRate[n];
14091 if (mv->moveType->Autotune != NULL)
14092 x[6]=mv->tuningParam[n][0];
14094 ierror = MPI_Allreduce (&x, &sum, 7, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);
14095 if (ierror != MPI_SUCCESS)
14100 mv->nAccepted[n] = (int)sum[0];
14101 mv->nTried[n] = (int)sum[1];
14102 mv->nBatches[n] = (int)sum[2];
14103 mv->nTotAccepted[n] = (int)sum[3];
14104 mv->nTotTried[n] = (int)sum[4];
14105 mv->lastAcceptanceRate[n] = (MrBFlt)sum[5];
14106 if (mv->moveType->Autotune != NULL)
14107 mv->tuningParam[n][0]=(MrBFlt)sum[6];
14116 int ReassembleParamVals (int *curId)
14118 int i, j, k, orderLen, nBrlens, lower, upper, numChainsForProc, proc, ierror, *y, *order, *id, *nEvents;
14119 MrBFlt *x, *brlens, **position, **rateMult;
14121 MPI_Request request;
14125 extern MrBFlt *paramValues;
14126 extern int paramValsRowSize;
14127 extern int intValsRowSize;
14129 for (i=0; i<numLocalChains; i++)
14130 curId[i] = chainId[i];
14132 numChainsForProc = numGlobalChains / num_procs;
14133 if (numGlobalChains % num_procs > 0)
14134 lower = upper = numChainsForProc+1;
14136 lower = upper = numChainsForProc;
14138 for (proc=1; proc<num_procs; proc++, lower=upper)
14140 if (proc < numGlobalChains % num_procs)
14141 upper += numChainsForProc+1;
14143 upper += numChainsForProc;
14148 id = curId + lower;
14149 ierror = MPI_Irecv (id, upper-lower, MPI_INT, proc, 0, MPI_COMM_WORLD, &request);
14150 if (ierror != MPI_SUCCESS)
14154 ierror = MPI_Waitall (1, &request, &status);
14155 if (ierror != MPI_SUCCESS)
14160 else if (proc_id == proc)
14163 ierror = MPI_Isend (id, upper-lower, MPI_INT, 0, 0, MPI_COMM_WORLD, &request);
14164 if (ierror != MPI_SUCCESS)
14168 ierror = MPI_Waitall (1, &request, &status);
14169 if (ierror != MPI_SUCCESS)
14178 ierror = MPI_Irecv (state+lower, upper-lower, MPI_CHAR, proc, 0, MPI_COMM_WORLD, &request);
14179 if (ierror != MPI_SUCCESS)
14183 ierror = MPI_Waitall (1, &request, &status);
14184 if (ierror != MPI_SUCCESS)
14189 else if (proc_id == proc)
14191 ierror = MPI_Isend (state, upper-lower, MPI_CHAR, 0, 0, MPI_COMM_WORLD, &request);
14192 if (ierror != MPI_SUCCESS)
14196 ierror = MPI_Waitall (1, &request, &status);
14197 if (ierror != MPI_SUCCESS)
14203 /* normal parameter values */
14206 x = paramValues + 2*paramValsRowSize*lower;
14207 ierror = MPI_Irecv (x, paramValsRowSize*2*(upper-lower), MPI_DOUBLE, proc, 0, MPI_COMM_WORLD, &request);
14208 if (ierror != MPI_SUCCESS)
14212 ierror = MPI_Waitall (1, &request, &status);
14213 if (ierror != MPI_SUCCESS)
14217 if (intValsRowSize > 0)
14219 y = intValues + 2*intValsRowSize*lower;
14220 ierror = MPI_Irecv (y, intValsRowSize*2*(upper-lower), MPI_INT, proc, 0, MPI_COMM_WORLD, &request);
14221 if (ierror != MPI_SUCCESS)
14225 ierror = MPI_Waitall (1, &request, &status);
14226 if (ierror != MPI_SUCCESS)
14232 else if (proc_id == proc)
14235 ierror = MPI_Isend (x, paramValsRowSize*2*(upper-lower), MPI_DOUBLE, 0, 0, MPI_COMM_WORLD, &request);
14236 if (ierror != MPI_SUCCESS)
14240 ierror = MPI_Waitall (1, &request, &status);
14241 if (ierror != MPI_SUCCESS)
14245 if (intValsRowSize > 0)
14248 ierror = MPI_Isend (y, intValsRowSize*2*(upper-lower), MPI_INT, 0, 0, MPI_COMM_WORLD, &request);
14249 if (ierror != MPI_SUCCESS)
14253 ierror = MPI_Waitall (1, &request, &status);
14254 if (ierror != MPI_SUCCESS)
14261 /* std state frequencies */
14262 if (stdStateFreqsRowSize > 0)
14266 x = stdStateFreqs + 2*stdStateFreqsRowSize*lower;
14267 ierror = MPI_Irecv (x, stdStateFreqsRowSize*2*(upper-lower), MPI_DOUBLE, proc, 0, MPI_COMM_WORLD, &request);
14268 if (ierror != MPI_SUCCESS)
14272 ierror = MPI_Waitall (1, &request, &status);
14273 if (ierror != MPI_SUCCESS)
14278 else if (proc_id == proc)
14281 ierror = MPI_Isend (x, stdStateFreqsRowSize*2*(upper-lower), MPI_DOUBLE, 0, 0, MPI_COMM_WORLD, &request);
14282 if (ierror != MPI_SUCCESS)
14286 ierror = MPI_Waitall (1, &request, &status);
14287 if (ierror != MPI_SUCCESS)
14295 brlens = (MrBFlt *) SafeCalloc (2*numLocalTaxa, sizeof(MrBFlt));
14296 order = (int *) SafeCalloc (2*numLocalTaxa, sizeof(int));
14297 for (i=lower; i<upper; i++)
14299 for (j=0; j<numTrees; j++)
14301 tree = GetTreeFromIndex(j,0,0);
14302 orderLen = 2*tree->nIntNodes - 1;
14303 nBrlens = tree->nNodes - 1;
14306 tree = GetTreeFromIndex(j,i,state[i]);
14307 ierror = MPI_Irecv (order, orderLen, MPI_INT, proc, 0, MPI_COMM_WORLD, &request);
14308 if (ierror != MPI_SUCCESS)
14312 ierror = MPI_Waitall (1, &request, &status);
14313 if (ierror != MPI_SUCCESS)
14317 ierror = MPI_Irecv (brlens, nBrlens, MPI_DOUBLE, proc, 0, MPI_COMM_WORLD, &request);
14318 if (ierror != MPI_SUCCESS)
14322 ierror = MPI_Waitall (1, &request, &status);
14323 if (ierror != MPI_SUCCESS)
14327 if (tree->isRooted == YES)
14328 RetrieveRTreeWithIndices(tree, order, brlens);
14331 RetrieveUTree(tree, order, brlens);
14332 if (localOutGroup!=0)
14333 MoveCalculationRoot(tree,localOutGroup);
14335 /* since we only transferred some info, there are additional things we need to
14336 consider, like constraints and calibrations; tree names are OK on proc 0 */
14337 InitializeTreeCalibrations(tree);
14338 CheckSetConstraints(tree);
14339 SetDatedNodeAges(modelSettings[tree->relParts[0]].brlens, i, state[i]);
14341 else if (proc_id == proc)
14343 tree = GetTreeFromIndex(j,i-lower,state[i-lower]);
14344 if (tree->isRooted == YES)
14345 StoreRTreeWithIndices(tree, order, brlens);
14347 StoreUTree(tree, order, brlens);
14348 ierror = MPI_Isend (order, orderLen, MPI_INT, 0, 0, MPI_COMM_WORLD, &request);
14349 if (ierror != MPI_SUCCESS)
14353 ierror = MPI_Waitall (1, &request, &status);
14354 if (ierror != MPI_SUCCESS)
14358 ierror = MPI_Isend (brlens, nBrlens, MPI_DOUBLE, 0, 0, MPI_COMM_WORLD, &request);
14359 if (ierror != MPI_SUCCESS)
14363 ierror = MPI_Waitall (1, &request, &status);
14364 if (ierror != MPI_SUCCESS)
14374 /* CPP event parameters */
14375 for (i=lower; i<upper; i++)
14377 for (j=0; j<numParams; j++)
14380 if (p->paramType == P_CPPEVENTS)
14382 if (proc_id == proc)
14385 nEvents = p->nEvents[2*(i-lower)+state[i-lower]];
14386 position = p->position[2*(i-lower)+state[i-lower]];
14387 rateMult = p->rateMult[2*(i-lower)+state[i-lower]];
14389 /* send number of events */
14390 ierror = MPI_Isend (nEvents, 2*numLocalTaxa, MPI_INT, 0, 0, MPI_COMM_WORLD, &request);
14391 if (ierror != MPI_SUCCESS)
14393 ierror = MPI_Waitall (1, &request, &status);
14394 if (ierror != MPI_SUCCESS)
14397 /* send events and clear pointers */
14398 for (k=0; k<2*numLocalTaxa; k++)
14400 if (nEvents[k] > 0)
14402 ierror = MPI_Isend (position[k], nEvents[k], MPI_DOUBLE, 0, 0, MPI_COMM_WORLD, &request);
14403 if (ierror != MPI_SUCCESS)
14405 ierror = MPI_Waitall (1, &request, &status);
14406 if (ierror != MPI_SUCCESS)
14409 ierror = MPI_Isend (rateMult[k], nEvents[k], MPI_DOUBLE, 0, 0, MPI_COMM_WORLD, &request);
14410 if (ierror != MPI_SUCCESS)
14412 ierror = MPI_Waitall (1, &request, &status);
14413 if (ierror != MPI_SUCCESS)
14418 position[k] = NULL;
14419 rateMult[k] = NULL;
14424 else if (proc_id == 0)
14426 /* find pointers */
14427 nEvents = p->nEvents[2*i];
14428 position = p->position[2*i];
14429 rateMult = p->rateMult[2*i];
14431 /* clear previous events */
14432 for (k=0; k<2*numLocalTaxa; k++)
14434 if (nEvents[k] > 0)
14436 free (position[k]);
14437 free (rateMult[k]);
14438 position[k] = NULL;
14439 rateMult[k] = NULL;
14444 /* receive events */
14445 ierror = MPI_Irecv (nEvents, 2*numLocalTaxa, MPI_INT, proc, 0, MPI_COMM_WORLD, &request);
14446 if (ierror != MPI_SUCCESS)
14448 ierror = MPI_Waitall (1, &request, &status);
14449 if (ierror != MPI_SUCCESS)
14452 for (k=0; k<2*numLocalTaxa; k++)
14454 if (nEvents[k] > 0)
14456 position[k] = (MrBFlt *) SafeCalloc (nEvents[k], sizeof(MrBFlt));
14457 rateMult[k] = (MrBFlt *) SafeCalloc (nEvents[k], sizeof(MrBFlt));
14459 ierror = MPI_Irecv (position[k], nEvents[k], MPI_DOUBLE, proc, 0, MPI_COMM_WORLD, &request);
14460 if (ierror != MPI_SUCCESS)
14462 ierror = MPI_Waitall (1, &request, &status);
14463 if (ierror != MPI_SUCCESS)
14466 ierror = MPI_Irecv (rateMult[k], nEvents[k], MPI_DOUBLE, proc, 0, MPI_COMM_WORLD, &request);
14467 if (ierror != MPI_SUCCESS)
14469 ierror = MPI_Waitall (1, &request, &status);
14470 if (ierror != MPI_SUCCESS)
14484 int ReassembleSwapInfo (void)
14486 int i, j, n, x, sum, ierror;
14488 for (n=0; n<chainParams.numRuns; n++)
14490 for (i=0; i<chainParams.numChains; i++)
14492 for (j=0; j<chainParams.numChains; j++)
14499 x = swapInfo[n][i][j];
14500 ierror = MPI_Allreduce (&x, &sum, 1, MPI_INT, MPI_SUM, MPI_COMM_WORLD);
14501 if (ierror != MPI_SUCCESS)
14504 swapInfo[n][i][j] += sum;
14506 swapInfo[n][i][j] = 0;
14516 int ReassembleTuningParams (void)
14518 int i, j, k, lower, ierror;
14521 x = (MrBFlt *) SafeCalloc (2*numUsedMoves, sizeof(MrBFlt));
14522 sum = x + numUsedMoves;
14524 lower = numGlobalChains / num_procs;
14525 if (numGlobalChains % num_procs != 0)
14528 for (i=lower; i<numGlobalChains; i++)
14530 for (j=0; j<numLocalChains; j++)
14532 if (chainId[j] == i)
14536 for (k=0; k<numUsedMoves; k++)
14538 if (j != numLocalChains && usedMoves[k]->moveType->numTuningParams > 0) /* we have the tuning parameter of interest */
14539 x[k] = usedMoves[k]->tuningParam[i][0];
14544 ierror = MPI_Allreduce (x, sum, numUsedMoves, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);
14545 if (ierror != MPI_SUCCESS)
14553 for (k=0; k<numUsedMoves; k++)
14555 if (usedMoves[k]->moveType->numTuningParams > 0)
14556 usedMoves[k]->tuningParam[i][0] = sum[k];
14566 void RedistributeMoveInfo (void)
14571 /* Leave if not processor 0, because then we already have the necessary info since
14572 it was not deleted in ReassembleMoveInfo */
14576 /* If we are processor 0, simply delete the unnecessary information */
14577 for (i=0; i<numGlobalChains; i++)
14579 for (j=0; j<numLocalChains; j++)
14580 if (chainId[j] == i)
14583 if (j == numLocalChains)
14585 /* we do not have this chain, so delete the move info */
14586 for (k=0; k<numUsedMoves; k++)
14591 mv->nAccepted[i] = 0;
14593 mv->nBatches[i] = 0;
14594 mv->nTotAccepted[i] = 0;
14595 mv->nTotTried[i] = 0;
14596 mv->lastAcceptanceRate[i] = 0;
14597 if (mv->moveType->Autotune != NULL)
14598 mv->tuningParam[i][0]=0.0;
14605 int RedistributeParamVals (void)
14607 int i, j, k, orderLen, nBrlens, lower, upper, numChainsForProc, proc, ierror, *y, *order, *nEvents;
14608 MrBFlt *x, *brlens, **position, **rateMult;
14610 MPI_Request request;
14614 extern MrBFlt *paramValues;
14615 extern int paramValsRowSize;
14616 extern int intValsRowSize;
14618 numChainsForProc = numGlobalChains / num_procs;
14619 if (numGlobalChains % num_procs > 0)
14620 lower = upper = numChainsForProc+1;
14622 lower = upper = numChainsForProc;
14624 for (proc=1; proc<num_procs; proc++, lower=upper)
14626 if (proc < numGlobalChains % num_procs)
14627 upper += numChainsForProc+1;
14629 upper += numChainsForProc;
14631 /* normal parameter values */
14634 x = paramValues + 2*paramValsRowSize*lower;
14635 ierror = MPI_Isend (x, paramValsRowSize*2*(upper-lower), MPI_DOUBLE, proc, 0, MPI_COMM_WORLD, &request);
14636 if (ierror != MPI_SUCCESS)
14640 ierror = MPI_Waitall (1, &request, &status);
14641 if (ierror != MPI_SUCCESS)
14645 if (intValsRowSize > 0)
14647 y = intValues + 2*intValsRowSize*lower;
14648 ierror = MPI_Isend (y, intValsRowSize*2*(upper-lower), MPI_INT, proc, 0, MPI_COMM_WORLD, &request);
14649 if (ierror != MPI_SUCCESS)
14653 ierror = MPI_Waitall (1, &request, &status);
14654 if (ierror != MPI_SUCCESS)
14660 else if (proc_id == proc)
14663 ierror = MPI_Irecv (x, paramValsRowSize*2*(upper-lower), MPI_DOUBLE, 0, 0, MPI_COMM_WORLD, &request);
14664 if (ierror != MPI_SUCCESS)
14668 ierror = MPI_Waitall (1, &request, &status);
14669 if (ierror != MPI_SUCCESS)
14673 if (intValsRowSize > 0)
14676 ierror = MPI_Irecv (y, intValsRowSize*2*(upper-lower), MPI_INT, 0, 0, MPI_COMM_WORLD, &request);
14677 if (ierror != MPI_SUCCESS)
14681 ierror = MPI_Waitall (1, &request, &status);
14682 if (ierror != MPI_SUCCESS)
14690 brlens = (MrBFlt *) SafeCalloc (2*numLocalTaxa, sizeof(MrBFlt));
14691 order = (int *) SafeCalloc (2*numLocalTaxa, sizeof(int));
14692 for (i=lower; i<upper; i++)
14694 for (j=0; j<numTrees; j++)
14696 tree = GetTreeFromIndex(j,0,0);
14697 orderLen = 2*tree->nIntNodes - 1;
14698 nBrlens = tree->nNodes - 1;
14701 tree = GetTreeFromIndex(j,i,0);
14702 if (tree->isRooted == YES)
14703 StoreRTreeWithIndices(tree, order, brlens);
14705 StoreUTree(tree, order, brlens);
14706 ierror = MPI_Isend (order, orderLen, MPI_INT, proc, 0, MPI_COMM_WORLD, &request);
14707 if (ierror != MPI_SUCCESS)
14711 ierror = MPI_Waitall (1, &request, &status);
14712 if (ierror != MPI_SUCCESS)
14716 ierror = MPI_Isend (brlens, nBrlens, MPI_DOUBLE, proc, 0, MPI_COMM_WORLD, &request);
14717 if (ierror != MPI_SUCCESS)
14721 ierror = MPI_Waitall (1, &request, &status);
14722 if (ierror != MPI_SUCCESS)
14727 else if (proc_id == proc)
14729 tree = GetTreeFromIndex(j,i-lower,0);
14730 ierror = MPI_Irecv (order, orderLen, MPI_INT, 0, 0, MPI_COMM_WORLD, &request);
14731 if (ierror != MPI_SUCCESS)
14735 ierror = MPI_Waitall (1, &request, &status);
14736 if (ierror != MPI_SUCCESS)
14740 ierror = MPI_Irecv (brlens, nBrlens, MPI_DOUBLE, 0, 0, MPI_COMM_WORLD, &request);
14741 if (ierror != MPI_SUCCESS)
14745 ierror = MPI_Waitall (1, &request, &status);
14746 if (ierror != MPI_SUCCESS)
14750 if (tree->isRooted == YES)
14751 RetrieveRTreeWithIndices(tree, order, brlens);
14754 RetrieveUTree(tree, order, brlens);
14755 if (localOutGroup != 0)
14756 MoveCalculationRoot(tree,localOutGroup);
14758 /* since we only transferred some info, there are additional things we need to
14759 consider, like names, constraints and calibrations */
14760 InitializeTreeCalibrations(tree);
14761 CheckSetConstraints(tree);
14762 SetDatedNodeAges(modelSettings[tree->relParts[0]].brlens, i-lower, 0);
14763 strcpy(tree->name, GetTreeFromIndex(j, i, 0)->name);
14764 tree = GetTreeFromIndex(j,i-lower,1);
14765 strcpy(tree->name, GetTreeFromIndex(j, i, 0)->name);
14772 /* CPP relaxed clock parameters */
14773 for (i=lower; i<upper; i++)
14775 for (j=0; j<numParams; j++)
14778 if (p->paramType == P_CPPEVENTS)
14783 nEvents = p->nEvents[2*i];
14784 position = p->position[2*i];
14785 rateMult = p->rateMult[2*i];
14787 /* send number of events */
14788 ierror = MPI_Isend (nEvents, 2*numLocalTaxa, MPI_INT, proc, 0, MPI_COMM_WORLD, &request);
14789 if (ierror != MPI_SUCCESS)
14791 ierror = MPI_Waitall (1, &request, &status);
14792 if (ierror != MPI_SUCCESS)
14795 /* send events and clear pointers */
14796 for (k=0; k<2*numLocalTaxa; k++)
14798 if (nEvents[k] > 0)
14800 ierror = MPI_Isend (position[k], nEvents[k], MPI_DOUBLE, proc, 0, MPI_COMM_WORLD, &request);
14801 if (ierror != MPI_SUCCESS)
14803 ierror = MPI_Waitall (1, &request, &status);
14804 if (ierror != MPI_SUCCESS)
14807 ierror = MPI_Isend (rateMult[k], nEvents[k], MPI_DOUBLE, proc, 0, MPI_COMM_WORLD, &request);
14808 if (ierror != MPI_SUCCESS)
14810 ierror = MPI_Waitall (1, &request, &status);
14811 if (ierror != MPI_SUCCESS)
14816 position[k] = NULL;
14817 rateMult[k] = NULL;
14822 else if (proc_id == proc)
14824 /* find pointers */
14825 nEvents = p->nEvents[2*(i-lower)];
14826 position = p->position[2*(i-lower)];
14827 rateMult = p->rateMult[2*(i-lower)];
14829 /* clear previous events */
14830 for (k=0; k<2*numLocalTaxa; k++)
14832 if (nEvents[k] > 0)
14834 free (position[k]);
14835 free (rateMult[k]);
14836 position[k] = NULL;
14837 rateMult[k] = NULL;
14842 /* receive events */
14843 ierror = MPI_Irecv (nEvents, 2*numLocalTaxa, MPI_INT, 0, 0, MPI_COMM_WORLD, &request);
14844 if (ierror != MPI_SUCCESS)
14846 ierror = MPI_Waitall (1, &request, &status);
14847 if (ierror != MPI_SUCCESS)
14849 for (k=0; k<2*numLocalTaxa; k++)
14851 if (nEvents[k] > 0)
14853 position[k] = (MrBFlt *) SafeCalloc (nEvents[k], sizeof(MrBFlt));
14854 rateMult[k] = (MrBFlt *) SafeCalloc (nEvents[k], sizeof(MrBFlt));
14856 ierror = MPI_Irecv (position[k], nEvents[k], MPI_DOUBLE, 0, 0, MPI_COMM_WORLD, &request);
14857 if (ierror != MPI_SUCCESS)
14859 ierror = MPI_Waitall (1, &request, &status);
14860 if (ierror != MPI_SUCCESS)
14863 ierror = MPI_Irecv (rateMult[k], nEvents[k], MPI_DOUBLE, 0, 0, MPI_COMM_WORLD, &request);
14864 if (ierror != MPI_SUCCESS)
14866 ierror = MPI_Waitall (1, &request, &status);
14867 if (ierror != MPI_SUCCESS)
14876 /* update evolutionary branch lengths or rates (because node indices have changed) */
14877 if (proc_id == proc)
14879 for (i=0; i<upper-lower; i++)
14881 for (j=0; j<numParams; j++)
14884 if (p->paramType == P_CPPEVENTS)
14886 tree = GetTree(p, i, 0);
14887 UpdateCppEvolLengths (p, tree->root->left, i);
14889 else if (p->paramType == P_TK02BRANCHRATES || (p->paramType == P_MIXEDBRCHRATES && *GetParamIntVals(p, i, 0) == RCL_TK02))
14891 tree = GetTree (p, i, 0);
14892 UpdateTK02EvolLengths (p, tree, i);
14894 else if (p->paramType == P_IGRBRANCHRATES || (p->paramType == P_MIXEDBRCHRATES && *GetParamIntVals(p, i, 0) == RCL_IGR))
14896 tree = GetTree(p, i, 0);
14897 UpdateIgrBrachLengths (p, tree, i);
14908 int RedistributeTuningParams (void)
14910 int i, j, k, lower, ierror;
14913 x = (MrBFlt *) SafeCalloc (2*numUsedMoves, sizeof(MrBFlt));
14914 sum = x + numUsedMoves;
14916 lower = numGlobalChains / num_procs;
14917 if (numGlobalChains % num_procs != 0)
14922 for (i=0; i<numGlobalChains; i++)
14924 for (k=0; k<numUsedMoves; k++)
14926 if (usedMoves[k]->moveType->numTuningParams > 0)
14927 usedMoves[k]->tuningParam[i][0] = 0.0;
14932 for (i=lower; i<numGlobalChains; i++)
14934 for (j=0; j<numLocalChains; j++)
14936 if (chainId[j] == i)
14940 for (k=0; k<numUsedMoves; k++)
14942 if (proc_id == 0 && usedMoves[k]->moveType->numTuningParams > 0) /* we have the tuning parameter of interest */
14944 x[k] = usedMoves[k]->tuningParam[i][0];
14945 usedMoves[k]->tuningParam[i][0]=0.0;
14951 ierror = MPI_Allreduce (x, sum, numUsedMoves, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);
14952 if (ierror != MPI_SUCCESS)
14958 if (j != numLocalChains) /* we have the chain of interest */
14960 for (k=0; k<numUsedMoves; k++)
14962 if (usedMoves[k]->moveType->numTuningParams > 0)
14963 usedMoves[k]->tuningParam[i][0] = sum[k];
14975 /* RemovePartition: Remove a partition from the tree keeping track of partition frequencies */
14976 int RemovePartition (PFNODE *r, BitsLong *p, int runId)
14986 for (i=0; i<nLongsNeeded; i++)
14988 if (r->partition[i] != p[i])
14992 if (i == nLongsNeeded)
14994 else if (r->partition[i] < p[i])
14999 if (comp == 0) /* match */
15001 if (r->count[runId] == 0)
15006 else if (comp < 0) /* greater than -> into left subtree */
15008 if ((RemovePartition (r->left, p, runId)) == ERROR)
15013 /* less than -> into right subtree */
15014 if ((RemovePartition (r->right, p, runId)) == ERROR)
15023 /* RemoveTreeFromPartitionCounters: Break a tree into partitions and remove those from counters */
15024 int RemoveTreeFromPartitionCounters (Tree *tree, int treeId, int runId)
15029 if (tree->isRooted == YES)
15030 nTaxa = tree->nNodes - tree->nIntNodes - 1;
15032 nTaxa = tree->nNodes - tree->nIntNodes;
15034 for (i=0; i<nTaxa; i++)
15036 ClearBits(partition[i], nLongsNeeded);
15037 SetBit(i, partition[i]);
15040 for (i=0; i<tree->nIntNodes-1; i++)
15042 p = tree->intDownPass[i];
15043 assert (p->index >= tree->nNodes - tree->nIntNodes - (tree->isRooted == YES ? 1 : 0));
15044 for (j=0; j<nLongsNeeded; j++)
15046 partition[p->index][j] = partition[p->left->index][j] | partition[p->right->index][j];
15049 if ((RemovePartition (partFreqTreeRoot[treeId], partition[p->index], runId)) == ERROR)
15051 MrBayesPrint ("%s Could not remove partition %d in RemoveTreeFromPartitionCounters\n", spacer, p->index);
15052 ShowParts(stdout,partition[p->index],numLocalTaxa);
15061 /* RemoveTreeSamples: Remove tree samples from partition counters */
15062 int RemoveTreeSamples (int from, int to)
15064 int i, j, k, longestLine, line;
15065 char c, *s, *lineBuf=0;
15068 TreeList *treeList;
15070 int tempStrSize = TEMPSTRSIZE;
15072 # if defined (MPI_ENABLED)
15077 tempStr = (char *) SafeMalloc((size_t)tempStrSize * sizeof(char));
15080 MrBayesPrint ("%s Problem allocating tempString (%d)\n", spacer, tempStrSize * sizeof(char));
15084 if (chainParams.saveTrees == YES)
15086 for (i=0; i<numTopologies; i++)
15088 t = chainParams.dtree;
15089 if (topologyParam[i]->tree[0]->isRooted == YES)
15094 for (j=0; j<chainParams.numRuns; j++)
15096 treeList = &chainParams.treeList[j*numTopologies + i];
15098 for (k=from; k<=to; k++)
15100 GetFromTreeList (treeList, t);
15101 if (RemoveTreeFromPartitionCounters (t, i, j) == ERROR)
15114 for (i=0; i<numTopologies; i++)
15116 t = chainParams.dtree;
15118 for (j=0; j<chainParams.numRuns; j++)
15120 if (numPrintTreeParams == 1)
15122 if (chainParams.numRuns == 1)
15123 SafeSprintf (&tempStr, &tempStrSize, "%s.t", chainParams.chainFileName);
15125 SafeSprintf (&tempStr, &tempStrSize, "%s.run%d.t", chainParams.chainFileName, j+1);
15129 if (chainParams.numRuns == 1)
15130 SafeSprintf (&tempStr, &tempStrSize, "%s.tree%d.t", chainParams.chainFileName, topologyPrintIndex[i]+1);
15132 SafeSprintf (&tempStr, &tempStrSize, "%s.tree%d.run%d.t", chainParams.chainFileName, topologyPrintIndex[i]+1, j+1);
15135 if ((fp = OpenTextFileR (tempStr)) == NULL)
15143 longestLine = LongestLine(fp);
15144 lineBuf = (char *) SafeCalloc (longestLine+2,sizeof(char));
15145 fseek (fp, LastBlock(fp, lineBuf, longestLine), SEEK_SET);
15146 fseek (fp, FirstTree(fp, lineBuf, longestLine), SEEK_SET);
15147 fgetpos (fp, &chainParams.tFilePos[j*numTopologies+i]);
15151 fsetpos (fp, &chainParams.tFilePos[j*numTopologies+i]);
15154 for (k=0; k<=to-from; k++)
15159 } while ((c = fgetc(fp)) != '\r' && c != '\n');
15161 if (line > longestLine)
15162 longestLine = line;
15164 while ((c = fgetc(fp)) == '\r' || c == '\n')
15168 lineBuf = (char *) SafeCalloc (longestLine + 10, sizeof (char));
15175 fsetpos (fp, &chainParams.tFilePos[j*numTopologies+i]);
15176 /* The fsetpos and fgetpos pair are affected by writing to the file,
15177 at least on Windows systems. The effect is to put the subsequent
15178 fsetpos back a few positions. The following code will deal with this
15179 problem without affecting systems where this does not happen. */
15180 do { c = fgetc(fp);
15181 } while (c != 't');
15183 for (k=from; k<=to; k++)
15185 if (fgets (lineBuf, longestLine + 5, fp) == NULL)
15192 s = strtok (lineBuf, " ");
15193 for (s = strtok (NULL, ";"); *s != '('; s++)
15197 if (ResetTopology (t, s) == ERROR)
15205 if (RemoveTreeFromPartitionCounters (t, i, j) == ERROR)
15213 fgetpos (fp, &chainParams.tFilePos[j*numTopologies+i]);
15220 /* remove unnecessary nodes from the tree holding partition counters */
15221 for (i=0; i<numTopologies; i++)
15223 partFreqTreeRoot[i] = CompactTree (partFreqTreeRoot[i]);
15231 int ReopenMBPrintFiles (void)
15234 char fileName[120], localFileName[100];
15236 /* Take care of the mpi procs that do not have a file */
15237 # if defined (MPI_ENABLED)
15242 /* Get root of local file name */
15243 strcpy (localFileName, chainParams.chainFileName);
15245 /* Reopen the .p and .t files */
15246 for (n=0; n<chainParams.numRuns; n++)
15248 if (chainParams.numRuns == 1)
15249 sprintf (fileName, "%s.p", localFileName);
15251 sprintf (fileName, "%s.run%d.p", localFileName, n+1);
15253 if ((fpParm[n] = OpenTextFileA (fileName)) == NULL)
15256 for (i=0; i<numTrees; i++)
15258 if (numTrees == 1 && chainParams.numRuns == 1)
15259 sprintf (fileName, "%s.t", localFileName);
15260 else if (numTrees > 1 && chainParams.numRuns == 1)
15261 sprintf (fileName, "%s.tree%d.t", localFileName, i+1);
15262 else if (numTrees == 1 && chainParams.numRuns > 1)
15263 sprintf (fileName, "%s.run%d.t", localFileName, n+1);
15265 sprintf (fileName, "%s.tree%d.run%d.t", localFileName, i+1, n+1);
15267 if ((fpTree[n][i] = OpenTextFileA (fileName)) == NULL)
15272 /* Reopen the .mcmc file */
15273 if (chainParams.mcmcDiagn == YES)
15275 sprintf (fileName, "%s.mcmc", localFileName);
15277 if ((fpMcmc = OpenTextFileA (fileName)) == NULL)
15281 # if defined (PRINT_DUMP)
15282 for (n=0; n<chainParams.numRuns; n++)
15284 if (chainParams.numRuns == 1)
15285 sprintf (fileName, "%s.dump", localFileName);
15287 sprintf (fileName, "%s.run%d.dump", localFileName, n+1);
15289 if ((fpDump[n] = OpenTextFileA (fileName)) == NULL)
15298 int ConfirmAbortRun(void)
15303 /* reset requestAbortRun */
15304 requestAbortRun = NO;
15306 MrBayesPrint(" Do you really want to stop the run (y/n)?");
15307 if (fgets (line,98,stdin) == NULL)
15309 printf ("Error in function: %s at line: %d in file: %s", __FUNCTION__, __LINE__, __FILE__);
15311 for (i=0; (c=line[i])!='\0' && !isgraph(c); i++)
15313 if (c == 'y' || c == 'Y')
15317 MrBayesPrint(" Mcmc run continued ...\n\n");
15324 /*-------------------------------------------------------------------
15326 | ResetChainIds: Make sure parameter values are swapped back
15327 | at the end of a Metropolis-coupled MCMC run
15329 --------------------------------------------------------------------*/
15330 void ResetChainIds (void)
15332 int j, k, k1, tempId, *curId, toChn, fromChn, *to, *from, *swap;
15334 MrBFlt *fromVals, *toVals, *swapVals, **fromPosition, **toPosition,
15335 **swapPosition, **fromRateMult, **toRateMult, **swapRateMult;
15336 Tree *toTree, *fromTree, *swapTree;
15338 curId = (int *) SafeCalloc (numGlobalChains, sizeof(int));
15340 #if defined (MPI_ENABLED)
15341 ReassembleParamVals(curId);
15342 ReassembleTuningParams();
15347 for (j=0; j<numLocalChains; j++)
15353 for (j=0; j<numGlobalChains; j++)
15354 curId[j] = chainId[j];
15358 for (toChn=0; toChn<numGlobalChains; toChn++)
15360 if (curId[toChn] == toChn)
15362 if (state[toChn] != 0)
15364 CopyParams (toChn);
15371 /* we need to swap all values */
15372 /* first find the chain to swap with */
15373 for (j=toChn+1; j<numGlobalChains; j++)
15374 if (curId[j] == toChn)
15378 /* normal params */
15379 CopyParams (toChn);
15381 CopyParams (fromChn);
15382 CopyTrees (fromChn);
15384 for (j=0; j<numParams; j++)
15387 toVals = GetParamVals (p, toChn, 0);
15388 swapVals = GetParamVals (p, toChn, 1);
15389 fromVals = GetParamVals (p, fromChn, state[fromChn]);
15390 for (k=0; k<p->nValues; k++)
15392 toVals[k] = fromVals[k];
15393 fromVals[k] = swapVals[k];
15395 toVals = GetParamSubVals (p, toChn, 0);
15396 swapVals = GetParamSubVals (p, toChn, 1);
15397 fromVals = GetParamSubVals (p, fromChn, state[fromChn]);
15398 for (k=0; k<p->nSubValues; k++)
15400 toVals[k] = fromVals[k];
15401 fromVals[k] = swapVals[k];
15403 if (p->nStdStateFreqs > 0)
15405 toVals = GetParamStdStateFreqs (p, toChn, 0);
15406 swapVals = GetParamStdStateFreqs (p, toChn, 1);
15407 fromVals = GetParamStdStateFreqs (p, fromChn, state[fromChn]);
15408 for (k=0; k<p->nStdStateFreqs; k++)
15410 toVals[k] = fromVals[k];
15411 fromVals[k] = swapVals[k];
15417 for (j=0; j<numTrees; j++)
15419 toTree = GetTreeFromIndex(j, toChn, 0);
15420 swapTree = GetTreeFromIndex(j, toChn, 1);
15421 fromTree = GetTreeFromIndex(j, fromChn, state[fromChn]);
15422 CopyToTreeFromTree (toTree, fromTree);
15423 CopyToTreeFromTree (fromTree, swapTree);
15424 CopyToTreeFromTree (swapTree, toTree);
15425 swapTree = GetTreeFromIndex(j, fromChn, state[fromChn] ^ 1);
15426 CopyToTreeFromTree (swapTree, fromTree);
15428 /* CPP relaxed clock params */
15429 for (j=0; j<numParams; j++)
15432 if (p->paramType == P_CPPEVENTS)
15434 to = p->nEvents[2*toChn];
15435 swap = p->nEvents[2*toChn+1];
15436 from = p->nEvents[2*fromChn+state[fromChn]];
15437 toPosition = p->position[2*toChn];
15438 swapPosition = p->position[2*toChn+1];
15439 fromPosition = p->position[2*fromChn+state[fromChn]];
15440 toRateMult = p->rateMult[2*toChn];
15441 swapRateMult = p->rateMult[2*toChn+1];
15442 fromRateMult = p->rateMult[2*fromChn+state[fromChn]];
15443 for (k=0; k<2*numLocalTaxa; k++)
15447 toPosition[k] = (MrBFlt *) SafeRealloc ((void *)toPosition[k], from[k]*sizeof (MrBFlt));
15448 toRateMult[k] = (MrBFlt *) SafeRealloc ((void *)toRateMult[k], from[k]*sizeof (MrBFlt));
15449 for (k1=0; k1<from[k]; k1++)
15451 toPosition[k][k1] = fromPosition[k][k1];
15452 toRateMult[k][k1] = fromRateMult[k][k1];
15455 else if (to[k] > 0)
15457 free (toPosition[k]);
15458 toPosition[k] = NULL;
15459 free (toRateMult[k]);
15460 toRateMult[k] = NULL;
15465 fromPosition[k] = (MrBFlt *) SafeRealloc ((void *)fromPosition[k], swap[k]*sizeof (MrBFlt));
15466 fromRateMult[k] = (MrBFlt *) SafeRealloc ((void *)fromRateMult[k], swap[k]*sizeof (MrBFlt));
15467 for (k1=0; k1<swap[k]; k1++)
15469 fromPosition[k][k1] = swapPosition[k][k1];
15470 fromRateMult[k][k1] = swapRateMult[k][k1];
15473 else if (from[k] > 0)
15475 free (fromPosition[k]);
15476 fromPosition[k] = NULL;
15477 free (fromRateMult[k]);
15478 fromRateMult[k] = NULL;
15484 /* reset state of chain */
15487 /* make sure that the id is correct for the from chain */
15488 tempId = curId[toChn];
15489 curId[fromChn] = curId[toChn];
15490 curId[toChn] = tempId;
15497 /* ResetFlips: Reset flipped cond likes etc after rejection */
15498 void ResetFlips (int chain)
15504 #if defined (BEAGLE_ENABLED)
15505 int *isScalerNode=NULL;
15508 for (d=0; d<numCurrentDivisions; d++)
15510 m = &modelSettings[d];
15511 #if defined (BEAGLE_ENABLED)
15512 if (m->useBeagle == YES)
15513 isScalerNode = m->isScalerNode[chain];
15515 if (m->upDateCl != YES)
15518 #if defined (BEAGLE_ENABLED)
15519 if (m->useBeagle == NO ||
15520 beagleScalingScheme == MB_BEAGLE_SCALE_ALWAYS ||
15521 m->rescaleBeagleAll == YES)
15523 FlipSiteScalerSpace (m, chain);
15524 if (m->useBeagle == YES && m->rescaleBeagleAll == YES)
15525 m->rescaleFreq[chain] = m->rescaleFreqOld;
15528 FlipSiteScalerSpace (m, chain);
15532 if (m->upDateCijk == YES && m->nCijkParts > 0)
15533 FlipCijkSpace (m, chain);
15535 /* cycle over tree */
15536 tree = GetTree (m->brlens, chain, state[chain]);
15537 for (i=0; i<tree->nNodes; i++)
15539 p = tree->allDownPass[i];
15540 if (p->upDateTi == YES)
15541 FlipTiProbsSpace (m, chain, p->index);
15542 if (p->right != NULL) /* do not flip terminals in case these flags are inappropriately set by moves */
15544 if (p->upDateCl == YES)
15546 FlipCondLikeSpace (m, chain, p->index);
15547 #if defined (BEAGLE_ENABLED)
15548 if (m->useBeagle == NO ||
15549 beagleScalingScheme == MB_BEAGLE_SCALE_ALWAYS ||
15550 (m->rescaleBeagleAll == YES && isScalerNode[p->index] == YES))
15551 FlipNodeScalerSpace (m, chain, p->index);
15553 FlipNodeScalerSpace (m, chain, p->index);
15556 #if defined (BEAGLE_ENABLED)
15557 else if (m->rescaleBeagleAll == YES)
15559 FlipCondLikeSpace (m, chain, p->index);
15560 if (isScalerNode[p->index] == YES)
15561 FlipNodeScalerSpace (m, chain, p->index);
15567 /* division flag and tree node flags are reset when trees are copied */
15572 /*-------------------------------------------------------------------
15574 | ResetScalersPartition: reset scaler nodes of the given tree by appropriately setting isScalerNode array.
15575 | @param isScalerNode is an array which gets set with information about scaler node.
15576 | For each internal node isScalerNode[node->index] is set to YES if it has to be scaler node.
15577 | Note: Only internal nodes can become scaler nodes thus isScalerNode is set only for elemnts in interval [numLocalTaxa, numLocalTaxa+t->nIntNodes]
15579 | @param rescaleFreq effectively represent gaps between rescaling, higher number means more sparse choice of rescaling nodes
15581 --------------------------------------------------------------------*/
15582 int ResetScalersPartition (int *isScalerNode, Tree* t, unsigned rescaleFreq)
15587 /* set the node depth value of terminal nodes to zero; reset scalerNode */
15588 for (n=0; n<t->nNodes; n++)
15590 p = t->allDownPass[n];
15591 if (p->left == NULL)
15595 /* loop over interior nodes */
15596 for (n=0; n<t->nIntNodes; n++)
15598 p = t->intDownPass[n];
15599 assert (((p->index - numLocalTaxa) >= 0) && ((p->index - numLocalTaxa) < t->nIntNodes));
15600 p->x = p->left->x + p->right->x + 1;
15602 if (p->x > 2 * (int)rescaleFreq)
15604 assert (p->left->left != NULL && p->right->left != NULL);
15605 isScalerNode[p->left->index] = YES;
15607 isScalerNode[p->right->index] = YES;
15611 else if (p->x > (int)rescaleFreq)
15613 if (p->left->x > p->right->x)
15615 assert (p->left->left != NULL);
15616 isScalerNode[p->left->index] = YES;
15621 assert (p->right->left != NULL);
15622 isScalerNode[p->right->index] = YES;
15625 p->x = p->left->x + p->right->x + 1;
15628 isScalerNode[p->index] = NO;
15635 /*-------------------------------------------------------------------
15637 | ResetScalers: reset scaler nodes of all trees of all chains
15638 | This scheme ensures that minimally RESCALE_FREQ
15639 | unscaled interior nodes occur before rescaling is done
15641 --------------------------------------------------------------------*/
15642 int ResetScalers (void)
15648 #if defined (DEBUG_NOSCALING)
15652 for (chn=0; chn<numLocalChains; chn++)
15654 for (i=0; i<numTrees; i++)
15656 t = GetTreeFromIndex (i, chn, state[chn]);
15658 /* set the node depth value of terminal nodes to zero; reset scalerNode */
15659 for (n=0; n<t->nNodes; n++)
15661 p = t->allDownPass[n];
15662 p->scalerNode = NO;
15663 if (p->left == NULL)
15667 /* loop over interior nodes */
15668 for (n=0; n<t->nIntNodes; n++)
15670 p = t->intDownPass[n];
15672 p->x = p->left->x + p->right->x + 1;
15674 if (p->x > 2 * RESCALE_FREQ)
15676 assert (p->left->left != NULL && p->right->left != NULL);
15677 p->left->scalerNode = YES;
15679 p->right->scalerNode = YES;
15683 else if (p->x > RESCALE_FREQ)
15685 if (p->left->x > p->right->x)
15687 assert (p->left->left != NULL);
15688 p->left->scalerNode = YES;
15693 assert (p->right->left != NULL);
15694 p->right->scalerNode = YES;
15697 p->x = p->left->x + p->right->x + 1;
15700 p->scalerNode = NO;
15709 void ResetSiteScalers (ModelInfo *m, int chain)
15714 #if defined (BEAGLE_ENABLED)
15715 if (m->useBeagle == YES)
15717 beagleResetScaleFactors(m->beagleInstance, m->siteScalerIndex[chain]);
15721 lnScaler = m->scalers[m->siteScalerIndex[chain]];
15722 for (c=0; c<m->numChars; c++)
15727 /*----------------------------------------------------------------------
15729 | ReusePreviousResults: Save old .p, .t, .ss and .mcmc files with ~ extension,
15730 | then prepare new print files with the relevant old values added in
15731 | The number of samples is returned in numSamples
15733 ------------------------------------------------------------------------*/
15734 int ReusePreviousResults (int *numSamples, int steps)
15737 char localFileName[100], fileName[220], bkupName[220];
15741 # if defined (MPI_ENABLED)
15746 /* Allocate space for file pointers */
15747 if (memAllocs[ALLOC_FILEPOINTERS] == YES)
15749 MrBayesPrint ("%s File pointers already allocated in ReusePreviousResults\n", spacer);
15756 fpParm = (FILE **) SafeCalloc (chainParams.numRuns, sizeof (FILE *));
15757 if (fpParm == NULL)
15759 MrBayesPrint ("%s Could not allocate fpParm in ReusePreviousResults\n", spacer);
15762 memAllocs[ALLOC_FILEPOINTERS] = YES;
15763 fpTree = (FILE ***) SafeCalloc (chainParams.numRuns, sizeof (FILE **));
15764 if (fpTree == NULL)
15766 MrBayesPrint ("%s Could not allocate fpTree in ReusePreviousResults\n", spacer);
15769 fpTree[0] = (FILE **) SafeCalloc (numTrees*chainParams.numRuns, sizeof (FILE *));
15770 if (fpTree[0] == NULL)
15772 MrBayesPrint ("%s Could not allocate fpTree[0] in ReusePreviousResults\n", spacer);
15775 for (i=1; i<chainParams.numRuns; i++)
15776 fpTree[i] = fpTree[0] + i*numTrees;
15778 /* Get root of local file name */
15779 strcpy (localFileName, chainParams.chainFileName);
15781 /* Store old and prepare new .p and .t files */
15782 for (n=0; n<chainParams.numRuns; n++)
15784 if (chainParams.numRuns == 1)
15785 sprintf (fileName, "%s%s.p", workingDir, localFileName);
15787 sprintf (fileName, "%s%s.run%d.p", workingDir, localFileName, n+1);
15788 strcpy(bkupName,fileName);
15789 strcat(bkupName,"~");
15791 if (rename(fileName,bkupName) != 0)
15793 MrBayesPrint ("%s Could not rename file %s\n", spacer, fileName);
15797 if ((fpParm[n] = OpenNewMBPrintFile (fileName+strlen(workingDir))) == NULL)
15799 else if (CopyResults(fpParm[n],bkupName+strlen(workingDir),numPreviousGen) == ERROR)
15802 for (i=0; i<numTrees; i++)
15804 if (numTrees == 1 && chainParams.numRuns == 1)
15805 sprintf (fileName, "%s%s.t", workingDir, localFileName);
15806 else if (numTrees > 1 && chainParams.numRuns == 1)
15807 sprintf (fileName, "%s%s.tree%d.t", workingDir, localFileName, i+1);
15808 else if (numTrees == 1 && chainParams.numRuns > 1)
15809 sprintf (fileName, "%s%s.run%d.t", workingDir, localFileName, n+1);
15811 sprintf (fileName, "%s%s.tree%d.run%d.t", workingDir, localFileName, i+1, n+1);
15812 strcpy(bkupName,fileName);
15813 strcat(bkupName,"~");
15815 if (rename(fileName,bkupName) != 0)
15817 MrBayesPrint ("%s Could not rename file %s\n", spacer, fileName);
15820 if ((fpTree[n][i] = OpenNewMBPrintFile (fileName+strlen(workingDir))) == NULL)
15822 else if (CopyTreeResults(fpTree[n][i],bkupName+strlen(workingDir),numPreviousGen,numSamples) == ERROR)
15827 /* Store old and prepare new .ss file */
15828 if (chainParams.isSS == YES)
15830 sprintf (fileName, "%s%s.ss", workingDir, chainParams.chainFileName);
15831 strcpy(bkupName,fileName);
15832 strcat(bkupName,"~");
15834 if (rename(fileName,bkupName) != 0)
15836 MrBayesPrint ("%s Could not rename file %s\n", spacer, fileName);
15839 if ((fpSS = OpenNewMBPrintFile (fileName+strlen(workingDir))) == NULL)
15841 else if (CopyProcessSsFile(fpSS,bkupName+strlen(workingDir),steps,marginalLnLSS,splitfreqSS)==ERROR)
15845 /* Store old and prepare new .mcmc file */
15846 if (chainParams.mcmcDiagn == YES)
15848 sprintf (fileName, "%s%s.mcmc", workingDir, chainParams.chainFileName);
15849 strcpy(bkupName,fileName);
15850 strcat(bkupName,"~");
15852 if (rename(fileName,bkupName) != 0)
15854 MrBayesPrint ("%s Could not rename file %s\n", spacer, fileName);
15857 if ((fpMcmc = OpenNewMBPrintFile (fileName+strlen(workingDir))) == NULL)
15859 else if (CopyResults(fpMcmc,bkupName+strlen(workingDir),numPreviousGen)==ERROR)
15863 # if defined (PRINT_DUMP)
15864 fpDump = (FILE **) SafeCalloc (chainParams.numRuns, sizeof (FILE *));
15866 for (n=0; n<chainParams.numRuns; n++)
15868 if (chainParams.numRuns == 1)
15869 sprintf (fileName, "%s.dump", localFileName);
15871 sprintf (fileName, "%s.run%d.dump", localFileName, n+1);
15873 if ((fpDump[n] = OpenTextFileA (fileName)) == NULL)
15882 int RunChain (RandLong *seed)
15884 int i, j, n, chn, swapA=0, swapB=0, whichMove, acceptMove;
15885 int lastDiagnostics; // the sample no. when last diagnostic was performed
15886 int removeFrom, removeTo=0;
15887 int stopChain, nErrors;
15888 MrBFlt r=0.0, lnLikelihoodRatio, lnPriorRatio, lnProposalRatio, lnLike=0.0, lnPrior=0.0, f=0.0, CPUTime;
15889 MCMCMove *theMove, *mv;
15890 time_t startingT, endingT, stoppingT1, stoppingT2;
15891 clock_t previousCPUTime, currentCPUTime;
15892 /* Stepping-stone sampling variables */
15893 int run, samplesCountSS=0, stepIndexSS=0, numGenInStepSS=0, numGenOld, lastStepEndSS=0, numGenInStepBurninSS=0;
15894 MrBFlt stepLengthSS=0, meanSS, varSS, *tempX;
15895 char ckpFileName[220], bkupFileName[220];
15897 # if defined (BEAGLE_ENABLED)
15898 int ResetScalersNeeded; //set to YES if we need to reset node->scalerNode, used in old style rescaling;
15899 # ifdef DEBUG_BEAGLE
15900 int beagleScalingSchemeOld;
15903 ResetScalersNeeded = NO;
15905 for (i=0; i<numCurrentDivisions; i++)
15907 m = &modelSettings[i];
15908 if (m->useBeagle == NO || beagleScalingScheme == MB_BEAGLE_SCALE_ALWAYS)
15910 ResetScalersNeeded =YES;
15916 # if defined (MPI_ENABLED)
15917 int ierror, sumErrors;
15918 MrBFlt best, sum=0.0;
15921 # if defined (DEBUG_RUNCHAIN)
15925 /* set nErrors to 0 */
15927 if (numLocalTaxa < 4)
15929 for (i=0; i<numTrees; i++)
15930 if (GetTreeFromIndex(i, 0, 0)->isRooted == NO)
15932 if (i < numTrees && numLocalTaxa < 4)
15934 MrBayesPrint ("%s There must be at least four taxa in the analysis\n", spacer);
15937 else if (i == numTrees && numLocalTaxa < 3)
15939 MrBayesPrint ("%s There must be at least three taxa in the analysis\n", spacer);
15944 /* allocate some memory for the chains */
15945 if (memAllocs[ALLOC_CURLNL] == YES)
15947 MrBayesPrint ("%s curLnL is already allocated\n", spacer);
15950 else if ((curLnL = (MrBFlt *)SafeMalloc((size_t)numLocalChains * sizeof(MrBFlt))) == NULL)
15952 MrBayesPrint ("%s Problem allocating curLnL (%d)\n", spacer, numLocalChains * sizeof(MrBFlt));
15955 else if ((maxLnL0 = (MrBFlt *) SafeCalloc ((size_t)(chainParams.numRuns) * (size_t)(chainParams.numChains), sizeof(MrBFlt))) == NULL)
15957 MrBayesPrint ("%s Problem allocating maxLnL0\n", spacer, numLocalChains * sizeof(MrBFlt));
15962 memAllocs[ALLOC_CURLNL] = YES;
15963 # if defined (MPI_ENABLED)
15964 MPI_Allreduce (&nErrors, &sumErrors, 1, MPI_INT, MPI_SUM, MPI_COMM_WORLD);
15967 MrBayesPrint ("%s Memory allocation error on at least one processor\n", spacer);
15975 if (memAllocs[ALLOC_CURLNPR] == YES)
15977 MrBayesPrint ("%s curLnPr is already allocated\n", spacer);
15980 else if ((curLnPr = (MrBFlt *)SafeMalloc((size_t)numLocalChains * sizeof(MrBFlt))) == NULL)
15982 MrBayesPrint ("%s Problem allocating curLnPr (%d)\n", spacer, numLocalChains * sizeof(MrBFlt));
15986 memAllocs[ALLOC_CURLNPR] = YES;
15987 # if defined (MPI_ENABLED)
15988 MPI_Allreduce (&nErrors, &sumErrors, 1, MPI_INT, MPI_SUM, MPI_COMM_WORLD);
15991 MrBayesPrint ("%s Memory allocation error on at least one processor\n", spacer);
15999 if (memAllocs[ALLOC_CHAINID] == YES)
16001 MrBayesPrint ("%s chainId is already allocated\n", spacer);
16004 else if ((chainId = (int *)SafeMalloc((size_t)numLocalChains * sizeof(int))) == NULL)
16006 MrBayesPrint ("%s Problem allocating chainId (%d)\n", spacer, numLocalChains * sizeof(int));
16010 memAllocs[ALLOC_CHAINID] = YES;
16011 # if defined (MPI_ENABLED)
16012 MPI_Allreduce (&nErrors, &sumErrors, 1, MPI_INT, MPI_SUM, MPI_COMM_WORLD);
16015 MrBayesPrint ("%s Memory allocation error on at least one processor\n", spacer);
16023 if (memAllocs[ALLOC_SWAPINFO] == YES)
16025 MrBayesPrint ("%s swapInfo is already allocated\n", spacer);
16028 else if ((swapInfo = (int ***) SafeCalloc (chainParams.numRuns, sizeof (int **))) == NULL)
16030 MrBayesPrint ("%s Problem allocating swapInfo\n", spacer);
16035 for (n=0; n<chainParams.numRuns; n++)
16037 swapInfo[n] = AllocateSquareIntegerMatrix (chainParams.numChains);
16040 MrBayesPrint ("%s Problem allocating swapInfo[%d]\n", spacer, n);
16041 for (i=0; i<n; i++)
16042 free (swapInfo[i]);
16048 memAllocs[ALLOC_SWAPINFO] = YES;
16050 # if defined (MPI_ENABLED)
16051 MPI_Allreduce (&nErrors, &sumErrors, 1, MPI_INT, MPI_SUM, MPI_COMM_WORLD);
16054 MrBayesPrint ("%s Memory allocation error on at least one processor\n", spacer);
16062 for (n=0; n<chainParams.numRuns; n++)
16063 for (i=0; i<chainParams.numChains; i++)
16064 for (j=0; j<chainParams.numChains; j++)
16065 swapInfo[n][i][j] = 0;
16067 /* set up counters for topological convergence diagnostics */
16068 /* allocate tree used for some topological convergence diagnostics */
16069 if (chainParams.mcmcDiagn == YES && chainParams.numRuns > 1)
16071 if (SetUpPartitionCounters () == ERROR)
16073 # if defined (MPI_ENABLED)
16077 if (chainParams.relativeBurnin == YES)
16079 /* we have to remove trees later on */
16080 if (chainParams.saveTrees == YES)
16082 if (chainParams.treeList)
16086 chainParams.treeList = (TreeList *) SafeCalloc (chainParams.numRuns*numTopologies, sizeof (TreeList));
16087 if (!chainParams.treeList)
16091 memAllocs[ALLOC_TREELIST] = YES;
16093 chainParams.stopTreeGen = (int) (chainParams.numGen * chainParams.burninFraction);
16095 chainParams.stopTreeGen = chainParams.numGen;
16097 else /* if (chainParams.saveTrees == NO) */
16099 chainParams.tFilePos = (fpos_t*) SafeRealloc ((void *)chainParams.tFilePos, chainParams.numRuns*numTopologies*sizeof (fpos_t));
16100 if (!chainParams.tFilePos)
16103 memAllocs[ALLOC_TFILEPOS] = YES;
16106 # if defined (MPI_ENABLED)
16109 # if defined (MPI_ENABLED)
16112 if ((chainParams.stat = (STATS *) SafeCalloc (numTopologies, sizeof (STATS))) == NULL)
16116 memAllocs[ALLOC_STATS] = YES;
16117 for (i=0; i<numTopologies; i++)
16118 chainParams.stat[i].pair = NULL;
16121 if ((chainParams.dtree = AllocateTree (numLocalTaxa)) == NULL)
16126 memAllocs[ALLOC_DIAGNTREE] = YES;
16128 if (chainParams.allComps == YES)
16130 for (i=0; i<numTopologies; i++)
16132 if ((chainParams.stat[i].pair = AllocateSquareDoubleMatrix (chainParams.numRuns)) == NULL)
16140 MPI_Allreduce (&nErrors, &sumErrors, 1, MPI_INT, MPI_SUM, MPI_COMM_WORLD);
16143 MrBayesPrint ("%s Memory allocation error on at least one processor\n", spacer);
16147 if ((chainParams.stat = (STATS *) SafeCalloc (numTopologies, sizeof (STATS))) == NULL)
16151 memAllocs[ALLOC_STATS] = YES;
16152 for (i=0; i<numTopologies; i++)
16153 chainParams.stat[i].pair = NULL;
16156 if ((chainParams.dtree = AllocateTree (numLocalTaxa)) == NULL)
16158 MrBayesPrint ("%s Could not allocate chainParams.dtree in RunChain\n", spacer);
16162 memAllocs[ALLOC_DIAGNTREE] = YES;
16164 if (chainParams.allComps == YES)
16166 for (i=0; i<numTopologies; i++)
16168 if ((chainParams.stat[i].pair = AllocateSquareDoubleMatrix (chainParams.numRuns)) == NULL)
16170 MrBayesPrint ("%s Could not allocate chainParams.stat.pair in RunChain\n", spacer);
16178 /* get chain IDs */
16181 /* distribute parameter starting values and tuning parameters for MPI version */
16182 # if defined (MPI_ENABLED)
16183 RedistributeParamVals();
16184 RedistributeTuningParams();
16187 # if defined (TIMING_ANALIZ)
16188 CPUCondLikeDown = 0;
16190 CPUScalersRemove = 0;
16191 CPUCondLikeRoot = 0;
16195 /* initialize likelihoods and prior */
16196 /* touch everything and calculate initial cond likes */
16197 # if defined (BEAGLE_ENABLED)
16198 if (ResetScalersNeeded)
16203 TouchAllPartitions ();
16204 for (chn=0; chn<numLocalChains; chn++)
16206 if (chn % chainParams.numChains == 0)
16208 if (chainParams.numRuns == 1)
16209 MrBayesPrint ("\n%s Initial log likelihoods and log prior probs:\n", spacer);
16211 MrBayesPrint ("\n%s Initial log likelihoods and log prior probs for run %d:\n", spacer, chn / chainParams.numChains + 1);
16213 TouchAllTrees (chn);
16214 TouchAllCijks (chn);
16215 curLnL[chn] = LogLike(chn);
16216 curLnPr[chn] = LogPrior(chn);
16217 for (i=0; i<numCurrentDivisions; i++)
16219 if (modelSettings[i].gibbsGamma == YES)
16220 curLnL[chn] += GibbsSampleGamma (chn, i, seed);
16222 MrBayesPrint ("%s Chain %d -- %.6lf -- %.6lf\n", spacer, (chn % chainParams.numChains) + 1, curLnL[chn], curLnPr[chn]);
16224 MrBayesPrint("\n");
16226 # if defined (MPI_ENABLED)
16228 MrBayesPrint ("%s There are %d more chains on other processor(s)\n\n", spacer, numGlobalChains - numLocalChains);
16229 else if (num_procs==2)
16230 MrBayesPrint ("%s There are %d more chains on the other processor\n\n", spacer, numGlobalChains - numLocalChains);
16233 /* All steps are assumed to have the same length. */
16234 if (chainParams.isSS == YES)
16236 numGenInStepSS = (chainParams.numGen - chainParams.burninSS*chainParams.sampleFreq)/ chainParams.numStepsSS;
16237 numGenInStepSS = chainParams.sampleFreq*(numGenInStepSS/chainParams.sampleFreq); /*make muliple of chainParams.sampleFreq*/
16238 numGenOld = chainParams.numGen;
16239 chainParams.numGen = (chainParams.burninSS * chainParams.sampleFreq + chainParams.numStepsSS*numGenInStepSS) ;
16240 if (stepRelativeBurninSS==YES)
16241 numGenInStepBurninSS = ((int)(numGenInStepSS*chainParams.burninFraction / chainParams.sampleFreq))*chainParams.sampleFreq;
16243 numGenInStepBurninSS = chainParams.chainBurnIn * chainParams.sampleFreq;
16244 MrBayesPrint ("\n");
16245 MrBayesPrint ("%s Starting stepping-stone sampling to estimate marginal likelihood. \n", spacer);
16246 MrBayesPrint ("%s %d steps will be used with %d generations (%d samples) within each step. \n", spacer, chainParams.numStepsSS, numGenInStepSS, numGenInStepSS/chainParams.sampleFreq);
16247 MrBayesPrint ("%s Total of %d generations (%d samples) will be collected while first \n", spacer, chainParams.numGen, chainParams.numGen/chainParams.sampleFreq);
16248 MrBayesPrint ("%s %d generations (%d samples) will be discarded as initial burnin. \n", spacer, chainParams.burninSS*chainParams.sampleFreq, chainParams.burninSS);
16249 MrBayesPrint ("%s Additionally at the begining of each step %d generations (%d samples) \n", spacer, numGenInStepBurninSS, numGenInStepBurninSS/chainParams.sampleFreq);
16250 MrBayesPrint ("%s will be discarded as burnin. \n", spacer);
16251 if (chainParams.startFromPriorSS==YES)
16252 MrBayesPrint ("%s Sampling from prior to posterior, i.e. first step samples from prior. \n", spacer);
16255 MrBayesPrint ("%s Sampling from posterior to prior, i.e. first step samples from close to \n", spacer);
16256 MrBayesPrint ("%s posterior. \n", spacer);
16258 if (numGenOld != chainParams.numGen)
16260 MrBayesPrint ("%s NOTE: Number of generation of each step is reduced to the closest multi-\n", spacer);
16261 MrBayesPrint ("%s ple of sampling frequency. That is why, in total it will be taken %d \n", spacer, chainParams.numGen);
16262 MrBayesPrint ("%s generations instead of requested %d. \n", spacer, numGenOld);
16264 MrBayesPrint ("\n");
16265 if ((numGenInStepSS-numGenInStepBurninSS)/chainParams.sampleFreq < 1)
16267 MrBayesPrint ("%s There is less then one sample in each step of stepping-stone sampling. \n", spacer);
16268 MrBayesPrint ("%s Please adjust burnin, nuber of generations, sampling frequency or \n", spacer);
16269 MrBayesPrint ("%s numnber of step in order to allow at least one sample per step. \n", spacer);
16270 return ERROR; /*All MPI run will return here since all of them have the same values*/
16272 if (numPreviousGen==0 || numPreviousGen < chainParams.burninSS * chainParams.sampleFreq)
16274 lastStepEndSS = chainParams.burninSS * chainParams.sampleFreq;
16275 stepIndexSS = chainParams.numStepsSS-1;
16276 if (numPreviousGen != 0)
16277 removeTo=(numPreviousGen/chainParams.sampleFreq)+1;
16278 if (chainParams.startFromPriorSS==YES)
16280 // powerSS = BetaQuantile (chainParams.alphaSS, 1.0, (MrBFlt)(chainParams.numStepsSS-1-stepIndexSS)/(MrBFlt)chainParams.numStepsSS);
16282 stepLengthSS = BetaQuantile (chainParams.alphaSS, 1.0, (MrBFlt)(chainParams.numStepsSS-stepIndexSS)/(MrBFlt)chainParams.numStepsSS)-powerSS;
16286 powerSS = BetaQuantile (chainParams.alphaSS, 1.0, (MrBFlt)stepIndexSS/(MrBFlt)chainParams.numStepsSS);
16287 stepLengthSS = 1.0-powerSS;
16293 stepIndexSS = (numPreviousGen-chainParams.burninSS * chainParams.sampleFreq)/numGenInStepSS; /* for now it holds number of steps we fully complited*/
16294 lastStepEndSS = chainParams.burninSS * chainParams.sampleFreq + stepIndexSS*numGenInStepSS;
16295 removeTo = chainParams.burninSS + (stepIndexSS*numGenInStepSS+numGenInStepBurninSS)/chainParams.sampleFreq + 1;
16296 if (numPreviousGen < (removeTo-1)*chainParams.sampleFreq)
16297 removeTo=numPreviousGen/chainParams.sampleFreq+1;
16298 stepIndexSS = chainParams.numStepsSS-1-stepIndexSS;
16299 if (chainParams.startFromPriorSS==YES)
16301 powerSS = BetaQuantile (chainParams.alphaSS, 1.0, (MrBFlt)(chainParams.numStepsSS-1-stepIndexSS)/(MrBFlt)chainParams.numStepsSS);
16302 stepLengthSS = BetaQuantile (chainParams.alphaSS, 1.0, (MrBFlt)(chainParams.numStepsSS-stepIndexSS)/(MrBFlt)chainParams.numStepsSS)-powerSS;
16306 powerSS = BetaQuantile (chainParams.alphaSS, 1.0, (MrBFlt)stepIndexSS/(MrBFlt)chainParams.numStepsSS);
16307 stepLengthSS = BetaQuantile (chainParams.alphaSS, 1.0, (MrBFlt)(stepIndexSS+1)/(MrBFlt)chainParams.numStepsSS)-powerSS;
16309 # ifdef SAMPLE_ALL_SS
16310 samplesCountSS = (numPreviousGen-lastStepEndSS-numGenInStepBurninSS);
16312 samplesCountSS = (numPreviousGen-lastStepEndSS-numGenInStepBurninSS)/chainParams.sampleFreq;
16314 if (samplesCountSS < 0)
16317 MrBayesPrint("%s Continue sampling step %d out of %d steps...\n",spacer, chainParams.numStepsSS-stepIndexSS, chainParams.numStepsSS);
16318 /*marginalLnLSS will be red from file and destributed to other MPI_proc later. stepScalerSS, stepAcumulatorSS are lready red and if (samplesCountSS!=0) they will be redestributed. */
16321 if (samplesCountSS == 0) /* in appended case it also can happen */
16323 for (run=0; run<chainParams.numRuns; run++)
16325 marginalLnLSS[run] = 0.0;
16326 stepScalerSS[run] = 0.0;
16327 stepAcumulatorSS[run] = 0.0;
16330 for (chn=0; chn<numLocalChains; chn++)
16332 if (chainId[chn] % chainParams.numChains == 0)
16334 run = chainId[chn] / chainParams.numChains;
16335 stepScalerSS[run] = curLnL[chn]*stepLengthSS;
16341 /* Append to previous analysis if this is requested, otherwise just open new print files */
16342 if (chainParams.append == YES)
16344 # if defined (MPI_ENABLED)
16345 if (proc_id == 0) {
16347 /* We get the number of samples in i */
16348 if (ReusePreviousResults(&i, chainParams.numStepsSS-stepIndexSS-1) == ERROR || i < 2)
16350 else if (chainParams.numRuns > 1 && chainParams.mcmcDiagn == YES) /* we potentially need to add tree samples for conv diagn */
16352 /* Add tree samples to partition counters */
16353 if (chainParams.relativeBurnin == YES)
16355 if (numPreviousGen/(i-1) != chainParams.sampleFreq)
16357 MrBayesPrint ("%s 1. Use the same sampling frequency as in the previous run to use relative burnin.\n", spacer);
16358 MrBayesPrint ("%s 2. Check (and modify) the number in [generation: number] at line 3 of the .ckp file\n", spacer);
16359 MrBayesPrint ("%s to match the previous number of generations in all the .p and .t files. This may\n", spacer);
16360 MrBayesPrint ("%s happen if checkfreq was smaller than samplefreq.\n", spacer);
16361 MrBayesPrint ("%s 3. Rarely, delete the last sample/line in the .p and .t files to achieve 2. above.\n", spacer);
16362 MrBayesPrint ("%s This may happen if ngen was not divisible by samplefreq.\n", spacer);
16365 if (chainParams.isSS == NO)
16369 /* We definitely know the final number of generations */
16370 j = (chainParams.numGen/chainParams.sampleFreq)+1;
16371 j = (int) (j*chainParams.burninFraction);
16373 else /* User may extend chain so save all trees if saving trees */
16377 if (AddTreeSamples(1,j,chainParams.saveTrees) == ERROR) nErrors++;
16378 if (AddTreeSamples(j+1,i,NO) == ERROR) nErrors++;
16379 /* Since we never need to remove trees from partition counter after total burnin we put NO in the last argument */
16383 if (AddTreeSamples(1,i,chainParams.saveTrees) == ERROR) nErrors++;
16388 if (SetFilePositions(removeTo) == ERROR) nErrors++;
16389 if (AddTreeSamples(removeTo+1,i,chainParams.saveTrees) == ERROR) nErrors++;
16392 else if (chainParams.chainBurnIn < i)
16394 if (AddTreeSamples(chainParams.chainBurnIn,i-1,chainParams.saveTrees) == ERROR) nErrors++;
16399 if (chainParams.isSS == NO && chainParams.mcmcDiagn == YES && chainParams.numRuns > 1)
16401 MrBayesPrint ("\n");
16402 if (chainParams.relativeBurnin == YES)
16403 MrBayesPrint ("%s Using a relative burnin of %.1f %% for diagnostics\n", spacer, 100.0*chainParams.burninFraction);
16405 MrBayesPrint ("%s Using an absolute burnin of %d samples for diagnostics\n", spacer, chainParams.chainBurnIn);
16407 MrBayesPrint ("\n");
16408 MrBayesPrint ("%s Chain results (continued from previous run; %d generations requested):\n\n", spacer, chainParams.numGen);
16410 # if defined (MPI_ENABLED)
16414 if (chainParams.autotune == YES)
16416 for (i=0; i<numLocalChains; i++)
16418 for (j=0; j<numUsedMoves; j++)
16421 f = usedMoves[j]->cumProposalProb[chainId[i]];
16423 f = usedMoves[j]->cumProposalProb[chainId[i]] - usedMoves[j-1]->cumProposalProb[chainId[i]];
16424 if (usedMoves[j]->targetRate[chainId[i]] > 0.0)
16426 /* autotuned move; we assume it was perfectly tuned and start tuning from there at appropriate rate */
16427 usedMoves[j]->nBatches[chainId[i]] = (int) (f*numPreviousGen/chainParams.tuneFreq);
16428 usedMoves[j]->lastAcceptanceRate[chainId[i]] = usedMoves[j]->targetRate[chainId[i]];
16432 /* not autotuned move; no previous batches will result in acceptance rate calculated from new samples */
16433 usedMoves[j]->nBatches[chainId[i]] = 0;
16434 usedMoves[j]->lastAcceptanceRate[chainId[i]] = 0.0;
16439 # if defined (MPI_ENABLED)
16440 if (chainParams.isSS == YES)
16442 MPI_Bcast (marginalLnLSS, chainParams.numRuns, MPI_DOUBLE, 0, MPI_COMM_WORLD);
16444 if (samplesCountSS != 0)
16446 MPI_Bcast (stepScalerSS, chainParams.numRuns, MPI_DOUBLE, 0, MPI_COMM_WORLD);
16447 MPI_Bcast (stepAcumulatorSS, chainParams.numRuns, MPI_DOUBLE, 0, MPI_COMM_WORLD);
16449 /*Set to zero all runs that we are not responsable for*/
16450 for (run=0; run<chainParams.numRuns; run++)
16452 for (chn=0; chn<numLocalChains; chn++)
16454 if (chainId[chn] % chainParams.numChains == 0 && run == chainId[chn] / chainParams.numChains)
16457 if (chn<numLocalChains)
16460 marginalLnLSS[run] = 0.0;
16461 stepScalerSS[run] = 0.0;
16462 stepAcumulatorSS[run] = 0.0;
16466 MPI_Allreduce (&nErrors, &sumErrors, 1, MPI_INT, MPI_SUM, MPI_COMM_WORLD);
16469 MrBayesPrint ("%s Error appending to previous run\n", spacer);
16475 MrBayesPrint ("%s Error appending to previous run\n", spacer);
16482 if (PreparePrintFiles() == ERROR)
16486 # if defined (MPI_ENABLED)
16487 MPI_Allreduce (&nErrors, &sumErrors, 1, MPI_INT, MPI_SUM, MPI_COMM_WORLD);
16490 MrBayesPrint ("%s Error preparing print files on at least one processor\n", spacer);
16491 CloseMBPrintFiles();
16497 MrBayesPrint ("%s Error preparing print files\n", spacer);
16498 CloseMBPrintFiles();
16503 if (chainParams.relativeBurnin == NO)
16504 lastDiagnostics = chainParams.chainBurnIn;
16506 lastDiagnostics = 0;
16509 for (i=0; i<chainParams.numRuns; i++)
16510 maxLnL0[i] = -100000000.0;
16514 previousCPUTime = clock();
16516 /* print headers and starting states */
16517 if (numPreviousGen==0)
16519 /* make sure we print headers */
16520 PrintToScreen(0, 0, time(0), startingT);
16521 if (PrintStatesToFiles (0) == ERROR)
16523 MrBayesPrint("%s Error in printing headers to files\n");
16524 # if defined (MPI_ENABLED)
16530 # if defined (MPI_ENABLED)
16531 MPI_Allreduce (&nErrors, &sumErrors, 1, MPI_INT, MPI_SUM, MPI_COMM_WORLD);
16534 MrBayesPrint ("%s Aborting run.\n");
16539 if (chainParams.mcmcDiagn == YES)
16541 if (PrintMCMCDiagnosticsToFile (0) == ERROR)
16543 MrBayesPrint ("%s Problem printing mcmc diagnostics headers to file\n", spacer);
16544 # if defined (MPI_ENABLED)
16550 # if defined (MPI_ENABLED)
16551 MPI_Allreduce (&nErrors, &sumErrors, 1, MPI_INT, MPI_SUM, MPI_COMM_WORLD);
16554 MrBayesPrint ("%s Aborting run.\n");
16559 if (chainParams.isSS == YES && chainParams.burninSS == 0 && chainParams.numRuns > 1)
16561 /* Remove first sample (generation 0) from diagnostics */
16563 if (RemoveTreeSamples (1,1) == ERROR)
16565 MrBayesPrint("%s Problem removing tree samples\n");
16566 # if defined (MPI_ENABLED)
16572 # if defined (MPI_ENABLED)
16573 MPI_Allreduce (&nErrors, &sumErrors, 1, MPI_INT, MPI_SUM, MPI_COMM_WORLD);
16576 MrBayesPrint ("%s Aborting run.\n");
16582 if (chainParams.isSS == YES)
16584 if (chainParams.burninSS == 0)
16585 MrBayesPrint("%s Sampling step 1 out of %d steps...\n\n",spacer, chainParams.numStepsSS);
16587 /*Printing SS header*/
16588 MrBayesPrintf (fpSS, "[LEGEND: The file contains statistics on the Steppingstone Sampling.]\n");
16589 MrBayesPrintf (fpSS, "[ID: %s]\n", stamp);
16590 MrBayesPrintf (fpSS, "[ Step -- Index of the step ]\n");
16591 MrBayesPrintf (fpSS, "[ Power -- At each step we sample from the distribution with density (Likelihood^Power)*Prior ]\n");
16592 MrBayesPrintf (fpSS, "[ runX -- Contribution to the marginal log likelihood of run X, i.e. marginal log likelihood for run X is the sum across all steps in column runX. ]\n");
16593 if (chainParams.diagnStat == AVGSTDDEV)
16594 MrBayesPrintf (fpSS, "[ aSplitX -- Average standard deviation of split frequencies of tree X. -2.0 is printed if no diagnostics was requested. -1.0 is printed if there were no splits with frequency above minimum.]\n");
16596 MrBayesPrintf (fpSS, "[ mSplitX -- Maximal standard deviation of split frequencies of tree X. -2.0 is printed if no diagnostics was requested. -1.0 is printed if there were no splits with frequency above minimum.]\n");
16597 MrBayesPrintf (fpSS, "Step\tPower");
16598 for (j=0; j<chainParams.numRuns ; j++)
16599 MrBayesPrintf (fpSS, "\trun%d", j+1);
16600 if (chainParams.diagnStat == AVGSTDDEV)
16602 for (j=0; j<numTopologies; j++)
16603 MrBayesPrintf (fpSS, "\taSplit%d", j);
16607 for (j=0; j<numTopologies; j++)
16608 MrBayesPrintf (fpSS, "\tmSplit%d", j);
16610 MrBayesPrintf (fpSS, "\n");
16614 for (n=numPreviousGen+1; n<=chainParams.numGen; n++) /* begin run chain */
16616 currentCPUTime = clock();
16617 if (currentCPUTime - previousCPUTime > 10 * CLOCKS_PER_SEC)
16619 CPUTime += (currentCPUTime - previousCPUTime) / (MrBFlt) (CLOCKS_PER_SEC);
16620 previousCPUTime = currentCPUTime;
16623 /*! requestAbortRun is set by the signal handler when it receives a CTRL-C (serial version only) */
16624 if (requestAbortRun == YES && ConfirmAbortRun() == 1)
16627 /* Refresh scalers every SCALER_REFRESH_FREQ generations. */
16628 /* It is done before copying so we know it will take effect immediately. */
16629 /* However, the actual scalers are recalculated only when really needed. */
16630 # if defined (BEAGLE_ENABLED)
16631 if (ResetScalersNeeded && n % SCALER_REFRESH_FREQ == 0)
16634 if (n % SCALER_REFRESH_FREQ == 0)
16638 // RandLong oldSeed = *seed; /* record the old seed for debugging */
16639 for (chn=0; chn<numLocalChains; chn++)
16641 /* Do Gibbs resampling of rate categories for current state if time to do so */
16642 for (i=0; i<numCurrentDivisions; i++)
16644 if (modelSettings[i].gibbsGamma == YES && n % modelSettings[i].gibbsFreq == 0)
16645 curLnL[chn] += GibbsSampleGamma (chn, i, seed);
16648 /* First copy everything from current state of chain to new state. */
16649 /* The global variable state[chain] gives state. */
16651 /* copy all touched trees and reset update flags */
16654 /* copy all model parameters */
16657 /* shift the state of the chain to the new state */
16658 /* all calculations will be done on this state */
16659 state[chn] ^= 1; /* XORing with 1 switches between 0 and 1 */
16661 /* decide which move to make */
16662 whichMove = PickProposal(seed, chainId[chn]);
16663 theMove = usedMoves[whichMove];
16664 # if defined SHOW_MOVE
16665 printf ("Making move '%s'\n", theMove->name);
16668 # if defined (BEST_MPI_ENABLED)
16669 bestCycleGen = n % (numNonTreeMoves + numTreeMoves + numBestMoves);
16670 if (bestCycleGen < numNonTreeMoves)
16671 PickNonTreeProposal(seed, chainId[chn]);
16672 else if (bestCycleGen < numNonTreeMoves + numTreeMoves)
16673 PickTreeProposal(seed, chainId[chn]);
16675 PickBestProposal(chainId[chn]);
16678 /* set prior and proposal ratios */
16679 lnProposalRatio = 0.0;
16680 lnPriorRatio = 0.0;
16682 /* reset abort move flag */
16685 /* Touch the relevant partitions */
16686 /* as a service to the move functions. */
16687 for (i=0; i<theMove->parm->nRelParts; i++)
16688 modelSettings[theMove->parm->relParts[i]].upDateCl = YES;
16691 if (IsTreeConsistent(theMove->parm, chn, state[chn]) != YES)
16693 printf ("IsTreeConsistent failed before a move!\n");
16697 # if defined (DEBUG_CONSTRAINTS)
16698 if (theMove->parm->paramType == P_TOPOLOGY && DoesTreeSatisfyConstraints(GetTree (theMove->parm, chn, state[chn]))!=YES)
16700 printf ("DEBUG ERROR: DoesTreeSatisfyConstraints failed before a move\n");
16705 if ((theMove->moveFxn)(theMove->parm, chn, seed, &lnPriorRatio, &lnProposalRatio, theMove->tuningParam[chainId[chn]]) == ERROR)
16707 printf ("%s Error in move %s\n", spacer, theMove->name);
16708 # if defined (MPI_ENABLED)
16715 if (theMove->parm->paramType == P_TOPOLOGY && DoesTreeSatisfyConstraints(GetTree (theMove->parm, chn, state[chn])) != YES)
16717 # if defined (DEBUG_CONSTRAINTS)
16718 if (DoesTreeSatisfyConstraints(GetTree (theMove->parm, chn, state[chn]))==ABORT)
16720 printf ("DEBUG ERROR: DoesTreeSatisfyConstraints failed after move '%s'\n", theMove->name);
16726 /* abortMove is set to YES if the calculation fails because the likelihood is too small */
16727 if (abortMove == NO)
16728 lnLike = LogLike(chn);
16730 /* calculate acceptance probability */
16731 if (abortMove == NO)
16733 lnLikelihoodRatio = lnLike - curLnL[chn];
16734 lnPrior = curLnPr[chn] + lnPriorRatio;
16737 /* We check various aspects of calculations in debug version of code */
16738 if (IsTreeConsistent(theMove->parm, chn, state[chn]) != YES)
16740 printf ("DEBUG ERROR: IsTreeConsistent failed after move '%s'\n", theMove->name);
16743 if (lnPriorRatio != lnPriorRatio)
16745 printf ("DEBUG ERROR: Log prior ratio nan after move '%s'\n", theMove->name);
16746 // printf ("Seed: %ld\n", oldSeed); state[chn] ^= 1; PrintCheckPoint (n);
16749 if (fabs((lnPrior-LogPrior(chn))/lnPrior) > 0.0001)
16751 printf ("DEBUG ERROR: Log prior incorrect after move '%s' :%e :%e\n", theMove->name,lnPrior,LogPrior(chn));
16752 // printf ("Seed: %ld\n", oldSeed); state[chn] ^= 1; PrintCheckPoint (n);
16755 if (lnProposalRatio != lnProposalRatio)
16757 printf ("DEBUG ERROR: Log proposal ratio nan after move '%s'\n", theMove->name);
16758 // printf ("Seed: %ld\n", oldSeed); state[chn] ^= 1; PrintCheckPoint (n);
16761 if (lnLike != lnLike)
16763 printf ("DEBUG ERROR: Log likelihood nan after move '%s'\n", theMove->name);
16764 // printf ("Seed: %ld\n", oldSeed); state[chn] ^= 1; PrintCheckPoint (n);
16767 # if defined (DEBUG_LNLIKELIHOOD) /* slow */
16768 ResetFlips(chn); /* needed to return flags so they point to old state */
16769 TouchEverything(chn);
16770 if (fabs((lnLike-LogLike(chn))/lnLike) > 0.0001)
16772 printf ("DEBUG ERROR: Log likelihood incorrect after move '%s'\n", theMove->name);
16776 if (theMove->parm->paramType == P_TOPOLOGY && GetTree (theMove->parm, chn, state[chn])->isClock == YES &&
16777 IsClockSatisfied (GetTree (theMove->parm, chn, state[chn]),0.001) == NO)
16779 printf ("%s Branch lengths of the tree do not satisfy the requirements of a clock tree.\n", spacer);
16780 ShowNodes(GetTree (theMove->parm, chn, state[chn])->root,0,YES);
16786 lnLikelihoodRatio *= Temperature (chainId[chn]);
16787 lnPriorRatio *= Temperature (chainId[chn]);
16789 if (chainParams.isSS == YES)
16790 lnLikelihoodRatio *= powerSS;
16792 /* calculate the acceptance probability */
16793 if (lnLikelihoodRatio + lnPriorRatio + lnProposalRatio < -100.0)
16795 else if (lnLikelihoodRatio + lnPriorRatio + lnProposalRatio > 0.0)
16798 r = exp(lnLikelihoodRatio + lnPriorRatio + lnProposalRatio);
16801 /* decide to accept or reject the move */
16804 theMove->nTried[i]++;
16805 theMove->nTotTried[i]++;
16806 if (abortMove == NO && RandomNumber(seed) < r)
16809 theMove->nAccepted[i]++;
16810 theMove->nTotAccepted[i]++;
16813 /* update the chain */
16814 if (acceptMove == NO)
16816 /* the new state did not work out so shift chain back */
16817 if (abortMove == NO)
16820 # if defined (BEAGLE_ENABLED)
16821 if (recalcScalers == YES)
16823 recalculateScalers(chn);
16824 recalcScalers = NO;
16830 /* if the move is accepted then let the chain stay in the new state */
16831 /* store the likelihood and prior of the chain */
16832 curLnL[chn] = lnLike;
16833 curLnPr[chn] = lnPrior;
16836 /* check if time to autotune */
16837 if (theMove->nTried[i] >= chainParams.tuneFreq)
16839 theMove->lastAcceptanceRate[i] = (MrBFlt) theMove->nAccepted[i] / (MrBFlt) theMove->nTried[i];
16840 theMove->nTried[i] = 0;
16841 theMove->nAccepted[i] = 0;
16842 theMove->nBatches[i]++; /* we only autotune at most 10000 times */
16843 if (chainParams.autotune == YES && theMove->moveType->Autotune != NULL && theMove->nBatches[i] < MAXTUNINGPARAM)
16845 theMove->moveType->Autotune(theMove->lastAcceptanceRate[i],
16846 theMove->targetRate[i],
16847 theMove->nBatches[i],
16848 &theMove->tuningParam[i][0],
16849 theMove->moveType->minimum[0],
16850 theMove->moveType->maximum[0]);
16854 /* ShowValuesForChain (chn); */
16856 if (curLnL[chn] > maxLnL0[chainId[chn]])
16857 maxLnL0[chainId[chn]] = curLnL[chn];
16861 /* attempt swap(s) Non-blocking for MPI if no swap with external process. */
16862 if (chainParams.numChains > 1 && n % chainParams.swapFreq == 0)
16864 for (i = 0; i<chainParams.numRuns; i++)
16866 for (j = 0; j<chainParams.numSwaps; j++)
16867 GetSwappers (&swapA, &swapB, i);
16868 if (AttemptSwap (swapA, swapB, seed) == ERROR)
16870 MrBayesPrint ("%s Unsuccessful swap of states\n", spacer);
16871 # if defined (MPI_ENABLED)
16880 /* print information to screen. Non-blocking for MPI */
16881 if (n % chainParams.printFreq == 0)
16883 PrintToScreen(n, numPreviousGen, time(0), startingT);
16884 # if defined (TIMING_ANALIZ)
16885 MrBayesPrint ("%s Time elapsed:%f CondlikeDownTime:%f CondLikeRoot:%f Likelihood:%f ScalersTime:%f ScalersRemove:%f\n", spacer,
16886 CPUTime, CPUCondLikeDown/(MrBFlt)CLOCKS_PER_SEC, CPUCondLikeRoot/(MrBFlt)CLOCKS_PER_SEC, CPULilklihood/(MrBFlt)CLOCKS_PER_SEC,
16887 CPUScalers/(MrBFlt)CLOCKS_PER_SEC, CPUScalersRemove/(MrBFlt)CLOCKS_PER_SEC);
16891 /* print information to files */
16892 /* this will also add tree samples to topological convergence diagnostic counters */
16893 if (n == chainParams.numGen || n % chainParams.sampleFreq == 0)
16895 # if defined (MPI_ENABLED)
16896 MPI_Allreduce (&nErrors, &sumErrors, 1, MPI_INT, MPI_SUM, MPI_COMM_WORLD);
16899 MrBayesPrint ("%s Aborting run.\n");
16903 if (PrintStatesToFiles (n) == ERROR)
16905 MrBayesPrint("%s Error in printing states to files\n");
16906 # if defined (MPI_ENABLED)
16912 # if defined (MPI_ENABLED)
16913 MPI_Allreduce (&nErrors, &sumErrors, 1, MPI_INT, MPI_SUM, MPI_COMM_WORLD);
16916 MrBayesPrint ("%s Aborting run.\n");
16922 /* print mcmc diagnostics. Blocking for MPI */
16923 if (chainParams.mcmcDiagn == YES && (n % chainParams.diagnFreq == 0
16924 || n == chainParams.numGen
16925 || (chainParams.isSS == YES && (n-lastStepEndSS) % numGenInStepSS == 0)))
16927 if (chainParams.numRuns > 1 &&
16928 ((n > 0 && chainParams.relativeBurnin == YES && (chainParams.isSS == NO || (n > chainParams.burninSS * chainParams.sampleFreq && (n-lastStepEndSS) > numGenInStepBurninSS)))
16929 || (n >= chainParams.chainBurnIn * chainParams.sampleFreq && chainParams.relativeBurnin == NO)))
16931 /* we need some space for coming output */
16932 MrBayesPrint ("\n");
16933 /* remove tree samples if using burninpercentage */
16934 /* the following function returns immediately in MPI if proc_id != 0 */
16935 if (chainParams.relativeBurnin == YES && chainParams.isSS == NO)
16937 removeFrom = removeTo;
16938 removeTo = (int)(chainParams.burninFraction * (n/chainParams.sampleFreq+1)); /* (n/chainParams.sampleFreq+1) is the current number of samples */
16939 if (removeFrom < removeTo)
16941 if (RemoveTreeSamples (removeFrom+1, removeTo) == ERROR)
16943 MrBayesPrint("%s Problem removing tree samples\n");
16944 # if defined (MPI_ENABLED)
16951 # if defined (MPI_ENABLED)
16952 MPI_Allreduce (&nErrors, &sumErrors, 1, MPI_INT, MPI_SUM, MPI_COMM_WORLD);
16955 MrBayesPrint ("%s Aborting run.\n");
16961 lastDiagnostics = (n/chainParams.sampleFreq)+1; /* +1 because we always have start tree sampled*/
16962 if (chainParams.relativeBurnin == YES)
16964 i = lastDiagnostics - removeTo;
16967 i = lastDiagnostics - chainParams.chainBurnIn;
16968 # if defined (MPI_ENABLED)
16972 /* calculate statistics */
16973 CalcTopoConvDiagn (i);
16974 /* output statistics */
16975 if (numTopologies == 1)
16978 if (chainParams.stat[0].numPartitions == 0)
16980 MrBayesPrint ("%s Average standard deviation of split frequencies: NA (no splits above min. frequency)\n", spacer);
16982 else if (chainParams.diagnStat == AVGSTDDEV)
16984 f = chainParams.stat[0].avgStdDev;
16985 MrBayesPrint ("%s Average standard deviation of split frequencies: %.6f\n", spacer, f);
16989 f = chainParams.stat[0].max;
16990 MrBayesPrint ("%s Max standard deviation of split frequencies: %.6f\n", spacer, f);
16992 if (chainParams.isSS == YES)
16993 splitfreqSS[chainParams.numStepsSS-stepIndexSS-1] = f;
16994 if (chainParams.stat[0].numPartitions > 0 && f <= chainParams.stopVal)
16996 if (n < chainParams.numGen - chainParams.printFreq && (chainParams.stopRule == NO || stopChain == NO))
16997 MrBayesPrint ("\n");
17002 for (i=0; i<numTopologies; i++)
17005 if (chainParams.stat[i].numPartitions == 0)
17007 if (strcmp(modelParams[0].topologyPr,"Speciestree") == 0)
17009 if (i == numTopologies-1)
17010 MrBayesPrint ("%s Average standard deviation of split frequencies for species tree (tree %d): NA (no splits above min. frequency)\n", spacer, i+1);
17012 MrBayesPrint ("%s Average standard deviation of split frequencies for gene tree %d: NA (no splits above min. frequency)\n", spacer, i+1);
17015 MrBayesPrint ("%s Average standard deviation of split frequencies for topology %d: NA (no splits above min. frequency)\n", spacer, i+1);
17017 else if (chainParams.diagnStat == AVGSTDDEV)
17019 f = chainParams.stat[i].avgStdDev;
17020 if (strcmp(modelParams[0].topologyPr,"Speciestree") == 0)
17022 if (i == numTopologies-1)
17023 MrBayesPrint ("%s Average standard deviation of split frequencies for species tree (tree %d): %.6f\n", spacer, i+1, f);
17025 MrBayesPrint ("%s Average standard deviation of split frequencies for gene tree %d: %.6f\n", spacer, i+1, f);
17028 MrBayesPrint ("%s Average standard deviation of split frequencies for topology %d: %.6f\n", spacer, i+1, f);
17032 f = chainParams.stat[i].max;
17033 if (strcmp(modelParams[0].topologyPr,"Speciestree") == 0)
17035 if (i == numTopologies-1)
17036 MrBayesPrint ("%s Max standard deviation of split frequencies for species tree: %.6f\n", spacer, f);
17038 MrBayesPrint ("%s Max standard deviation of split frequencies for gene tree %d: %.6f\n", spacer, i+1, f);
17041 MrBayesPrint ("%s Max standard deviation of split frequencies for topology %d: %.6f\n", spacer, i+1, f);
17043 if (chainParams.isSS == YES)
17044 splitfreqSS[i*chainParams.numStepsSS+chainParams.numStepsSS-stepIndexSS-1] = f;
17045 if (chainParams.stat[i].numPartitions == 0 || f > chainParams.stopVal)
17048 if (n < chainParams.numGen - chainParams.printFreq && (chainParams.stopRule == NO || stopChain == NO))
17049 MrBayesPrint ("\n");
17051 if (chainParams.allComps == YES)
17052 PrintTopConvInfo ();
17053 # if defined (MPI_ENABLED)
17055 ierror = MPI_Bcast (&stopChain, 1, MPI_INT, 0, MPI_COMM_WORLD);
17056 if (ierror != MPI_SUCCESS)
17058 MrBayesPrint ("%s Problem broadcasting stop value\n", spacer);
17064 /* part of the following function needs to be performed by all MPI processors. Blocking for MPI. */
17065 if (PrintMCMCDiagnosticsToFile (n) == ERROR)
17067 MrBayesPrint ("%s Problem printing mcmc diagnostics to file\n", spacer);
17068 # if defined (MPI_ENABLED)
17074 # if defined (MPI_ENABLED)
17075 MPI_Allreduce (&nErrors, &sumErrors, 1, MPI_INT, MPI_SUM, MPI_COMM_WORLD);
17078 MrBayesPrint ("%s Aborting run.\n");
17084 /* check if time to break because stopVal reached */
17085 if (chainParams.isSS == NO && (chainParams.stopRule == YES && stopChain == YES))
17087 MrBayesPrint ("\n%s Analysis stopped because convergence diagnostic hit stop value.\n", spacer);
17091 /* user may want to extend chain */
17092 if (chainParams.isSS == NO && (n == chainParams.numGen && autoClose == NO))
17094 stoppingT1 = time(0);
17095 currentCPUTime = clock();
17096 CPUTime += (currentCPUTime - previousCPUTime) / (MrBFlt) CLOCKS_PER_SEC;
17097 previousCPUTime = currentCPUTime;
17098 chainParams.numGen += ExtendChainQuery ();
17099 stoppingT2 = time(0);
17100 startingT += (stoppingT2-stoppingT1);
17101 previousCPUTime = clock();
17102 /* timers should not be increased during the wait for a reply */
17105 /* Do stepping sampling staf if needed */
17106 if (chainParams.isSS == YES && n >= chainParams.burninSS*chainParams.sampleFreq)
17108 # ifndef SAMPLE_ALL_SS
17109 if ((n-lastStepEndSS) % chainParams.sampleFreq == 0)
17112 if (n > chainParams.burninSS*chainParams.sampleFreq && (n-lastStepEndSS > numGenInStepBurninSS))
17113 { /* do sampling */
17114 for (chn=0; chn<numLocalChains; chn++)
17116 if (chainId[chn] % chainParams.numChains == 0)
17118 run = chainId[chn] / chainParams.numChains;
17119 if (curLnL[chn]*stepLengthSS > stepScalerSS[run] + 200.0)
17122 stepAcumulatorSS[run] /= exp (curLnL[chn]*stepLengthSS - 100.0 - stepScalerSS[run]);
17123 stepScalerSS[run]= curLnL[chn]*stepLengthSS - 100.0;
17125 stepAcumulatorSS[run] += exp (curLnL[chn]*stepLengthSS - stepScalerSS[run]);
17132 if ((n-lastStepEndSS) == numGenInStepBurninSS)
17134 /* Remove all previouse samples from diagnostics */
17135 if (chainParams.mcmcDiagn == YES && chainParams.numRuns > 1)
17137 removeFrom = removeTo;
17138 removeTo = (int)(n/chainParams.sampleFreq); /* (n/chainParams.sampleFreq+1) is the current number of samples including 0 one*/
17140 if (removeFrom < removeTo)
17142 if (RemoveTreeSamples (removeFrom+1, removeTo) == ERROR)
17146 ERROR_TEST2("Problem removing tree samples",return(ERROR),);
17151 if ((n-lastStepEndSS) % numGenInStepSS == 0) /* prepare sample of next step */
17153 assert (n-lastStepEndSS <= numGenInStepSS);
17156 if (n > chainParams.burninSS*chainParams.sampleFreq)
17158 /* dump to file current step contribution */
17159 MrBayesPrintf (fpSS, "%3d\t%.4f", chainParams.numStepsSS-stepIndexSS, powerSS);
17160 # if defined (MPI_ENABLED)
17161 for (j=0; j<chainParams.numRuns ; j++)
17163 if (stepAcumulatorSS[j]==0)
17166 r = log (stepAcumulatorSS[j]/samplesCountSS) + stepScalerSS[j];
17167 ierror = MPI_Reduce (&r,&sum, 1, MPI_DOUBLE, MPI_SUM, 0, MPI_COMM_WORLD);
17168 if (ierror != MPI_SUCCESS)
17170 MrBayesPrint ("%s Problem with MPI_Reduce\n", spacer);
17175 MrBayesPrintf (fpSS, "\t%.6f", sum);
17179 for (j=0; j<chainParams.numRuns ; j++)
17181 MrBayesPrintf (fpSS, "\t%.6f", log (stepAcumulatorSS[j]/samplesCountSS) + stepScalerSS[j]);
17184 if (chainParams.mcmcDiagn == YES && chainParams.numRuns > 1)
17186 for (i=0; i<numTopologies; i++)
17188 MrBayesPrintf (fpSS, "\t%.6f",splitfreqSS[i*chainParams.numStepsSS+chainParams.numStepsSS-stepIndexSS-1]);
17192 for (i=0; i<numTopologies; i++)
17194 MrBayesPrintf (fpSS, "\t-2.0");
17199 MrBayesPrintf (fpSS, "\n");
17204 if (chainParams.startFromPriorSS==YES)
17206 powerSS = BetaQuantile (chainParams.alphaSS, 1.0, (MrBFlt)(chainParams.numStepsSS-1-stepIndexSS)/(MrBFlt)chainParams.numStepsSS);
17207 stepLengthSS = BetaQuantile (chainParams.alphaSS, 1.0, (MrBFlt)(chainParams.numStepsSS-stepIndexSS)/(MrBFlt)chainParams.numStepsSS)-powerSS;
17211 stepLengthSS = powerSS;
17212 powerSS = BetaQuantile (chainParams.alphaSS, 1.0, (MrBFlt)stepIndexSS/(MrBFlt)chainParams.numStepsSS);
17213 stepLengthSS -= powerSS;
17215 if (n != chainParams.numGen)
17216 MrBayesPrint("%s Sampling step %d out of %d steps...\n\n",spacer, chainParams.numStepsSS-stepIndexSS, chainParams.numStepsSS);
17217 for (chn=0; chn<numLocalChains; chn++)
17219 if (chainId[chn] % chainParams.numChains == 0)
17221 run = chainId[chn] / chainParams.numChains;
17222 if (samplesCountSS != 0)
17223 marginalLnLSS[run] += log (stepAcumulatorSS[run]/samplesCountSS) + stepScalerSS[run];
17224 stepScalerSS[run] = curLnL[chn]*stepLengthSS;
17225 stepAcumulatorSS[run]=0.0;
17232 MrBayesPrint("\n%s Sampling step 1 out of %d steps...\n\n",spacer, chainParams.numStepsSS);
17235 if (chainParams.backupCheckSS !=0 && (chainParams.numStepsSS-stepIndexSS-1)% chainParams.backupCheckSS == 0)
17237 /* print check-point file. Blocking for MPI */
17238 ERROR_TEST2("Error before printing checkpoint",return(ERROR),);
17239 if (PrintCheckPoint (n) == ERROR)
17243 ERROR_TEST2("Error in printing checkpoint",return(ERROR),);
17245 # if defined (MPI_ENABLED)
17249 /* figure out check-point file names */
17250 sprintf (ckpFileName, "%s%s.ckp", workingDir, chainParams.chainFileName);
17251 sprintf (bkupFileName,"%s.ss%d", ckpFileName,chainParams.numStepsSS-stepIndexSS);
17252 if (rename (ckpFileName, bkupFileName)!=0)
17254 MrBayesPrint ("%s Could not rename file %s to %s\n", spacer, ckpFileName, bkupFileName);
17257 strcpy (bkupFileName, ckpFileName);
17258 strcat (bkupFileName, "~");
17259 rename (bkupFileName,ckpFileName);
17260 # if defined (MPI_ENABLED)
17261 } /* end of if (proc_id == 0)*/
17267 /* print check-point file. Blocking for MPI */
17268 if (chainParams.checkPoint == YES && (n % chainParams.checkFreq == 0))
17270 ERROR_TEST2("Error before printing checkpoint",return(ERROR),);
17271 if (PrintCheckPoint (n) == ERROR)
17275 ERROR_TEST2("Error in printing checkpoint",return(ERROR),);
17278 } /* end run chain */
17280 currentCPUTime = clock();
17281 CPUTime += (currentCPUTime - previousCPUTime) / (MrBFlt) CLOCKS_PER_SEC;
17283 CloseMBPrintFiles (); /* redundant because files closed in FreeChainMemory but kept here as a safeguard in case of future changes */
17285 # if defined (BEAGLE_ENABLED)
17286 # ifdef DEBUG_BEAGLE
17288 beagleScalingSchemeOld = beagleScalingScheme;
17289 beagleScalingScheme = MB_BEAGLE_SCALE_ALWAYS;
17290 for (chn=0; chn<numLocalChains; chn++)
17292 if (chn % chainParams.numChains == 0)
17294 if (chainParams.numRuns == 1)
17295 MrBayesPrint ("%s Final log likelihoods and log prior probs (stored and calculated):\n", spacer);
17297 MrBayesPrint ("%s Final log likelihoods and log prior probs for run %d (stored and calculated):\n", spacer, chn / chainParams.numChains + 1);
17299 TouchEverything (chn);
17300 for (i=0; i<numCurrentDivisions; i++)
17302 if (modelSettings[i].gibbsGamma == YES)
17303 curLnL[chn] += GibbsSampleGamma (chn, i, seed);
17305 MrBayesPrint ("%s Chain %d -- %.6lf -- %.6lf\n", spacer, (chn % chainParams.numChains) + 1, curLnL[chn], curLnPr[chn]);
17306 MrBayesPrint ("%s Chain %d -- %.6lf -- %.6lf\n", spacer, (chn % chainParams.numChains) + 1, LogLike(chn), LogPrior(chn));
17308 beagleScalingScheme = beagleScalingSchemeOld;
17312 /* Make sure current state is reset and values copied back to state 0.
17313 Note that this can be tricky for Metropolis-coupled chains because
17314 the chain ids may necessitate some swapping of values among chains. */
17317 MrBayesPrint ("\n");
17318 if (difftime (endingT, startingT) > 3600.0)
17319 MrBayesPrint ("%s Analysis completed in %d hours %d mins %d seconds\n", spacer,
17320 (int) (difftime(endingT, startingT)/3600),
17321 ((int) (difftime(endingT, startingT))%3600)/60,
17322 (int) (difftime(endingT, startingT))%60);
17323 else if (difftime (endingT, startingT) > 60.0)
17324 MrBayesPrint ("%s Analysis completed in %d mins %d seconds\n", spacer,
17325 (int) (difftime(endingT, startingT)/60),
17326 (int) (difftime(endingT, startingT))%60);
17327 else if (difftime (endingT, startingT) > 2.0)
17328 MrBayesPrint ("%s Analysis completed in %.0f seconds\n", spacer,
17329 difftime(endingT, startingT));
17330 else if (difftime (endingT, startingT) >= 1.0)
17331 MrBayesPrint ("%s Analysis completed in 1 second\n", spacer);
17333 MrBayesPrint ("%s Analysis completed in less than 1 second\n", spacer);
17335 # if defined (MPI_ENABLED)
17336 MrBayesPrint ("%s Analysis used %1.2f seconds of CPU time on processor 0\n", spacer, (MrBFlt) CPUTime);
17338 MrBayesPrint ("%s Analysis used %1.2f seconds of CPU time\n", spacer, (MrBFlt) CPUTime);
17341 # if defined (MPI_ENABLED)
17342 /* find the best likelihoods across all of the processors */
17343 ierror = MPI_Barrier (MPI_COMM_WORLD);
17344 if (ierror != MPI_SUCCESS)
17346 MrBayesPrint ("%s Problem at chain barrier\n", spacer);
17349 for (j=0; j<numGlobalChains; j++)
17352 for (i=1; i<num_procs; i++)
17356 ierror = MPI_Recv (&maxLnL0[j], 1, MPI_DOUBLE, i, i, MPI_COMM_WORLD, &status);
17357 if (ierror != MPI_SUCCESS)
17359 MrBayesPrint ("%s Problem with MPI_Recv", spacer);
17362 if (maxLnL0[j] > best)
17365 else if (proc_id == i)
17367 ierror = MPI_Send (&maxLnL0[j], 1, MPI_DOUBLE, 0, i, MPI_COMM_WORLD);
17368 if (ierror != MPI_SUCCESS)
17370 MrBayesPrint ("%s Problem with MPI_Send\n", spacer);
17378 /* Collecting marginal log likelihoods if SS is used */
17379 if (chainParams.isSS == YES)
17381 for (j=0; j<chainParams.numRuns ; j++)
17383 ierror = MPI_Reduce (&marginalLnLSS[j],&r, 1, MPI_DOUBLE, MPI_SUM, 0, MPI_COMM_WORLD);
17384 if (ierror != MPI_SUCCESS)
17386 MrBayesPrint ("%s Problem with MPI_Send\n", spacer);
17391 marginalLnLSS[j]=r;
17397 if (chainParams.numRuns == 1)
17399 if (chainParams.numChains == 1)
17400 MrBayesPrint ("%s Log likelihood of best state was %1.2lf\n", spacer, maxLnL0[0]);
17402 MrBayesPrint ("%s Log likelihood of best state for \"cold\" chain was %1.2lf\n", spacer, maxLnL0[0]);
17406 for (j=0; j<chainParams.numRuns*chainParams.numChains; j++)
17408 if (j % chainParams.numChains == 0)
17410 if (chainParams.numChains == 1)
17411 MrBayesPrint ("%s Likelihood of best state for run %d was %1.2lf\n", spacer, j/chainParams.numChains+1, maxLnL0[j/chainParams.numChains]);
17413 MrBayesPrint ("%s Likelihood of best state for \"cold\" chain of run %d was %1.2lf\n", spacer, j/chainParams.numChains+1, maxLnL0[j/chainParams.numChains]);
17418 if (chainParams.isSS == YES)
17420 MrBayesPrint ("\n");
17421 MrBayesPrint ("%s Marginal likelihood (in natural log units) estimated using stepping-stone sampling based on\n", spacer);
17422 MrBayesPrint ("%s %d steps with %d generations (%d samples) within each step. \n\n", spacer, chainParams.numStepsSS, numGenInStepSS, numGenInStepSS/chainParams.sampleFreq);
17423 MrBayesPrint ("%s Run Marginal likelihood (ln)\n",spacer);
17424 MrBayesPrint ("%s ------------------------------\n",spacer);
17425 for (j=0; j<chainParams.numRuns; j++)
17427 MrBayesPrint ("%s %3d %9.2f \n", spacer, j+1, marginalLnLSS[j]);
17429 MrBayesPrint ("%s ------------------------------\n",spacer);
17430 if (chainParams.numRuns > 1)
17432 MeanVarianceLog(marginalLnLSS,chainParams.numRuns,&meanSS,&varSS,NULL);
17433 MrBayesPrint ("%s Mean: %9.2f\n\n",spacer,meanSS);
17434 //MrBayesPrint ("%s Mean: %9.2lf Scaled variance: %.2f of Marginal log likelihood estimates among runs.\n",spacer,meanSS,varSS-2*meanSS);
17435 //MrBayesPrint ("%s Note: Scaled variance is given in log units and calculated as \"variance/mean^2\"\n",spacer);
17437 MrBayesPrint ("%s More statistics on stepping-stone sampling is dumped to %s.ss file.\n", spacer, chainParams.chainFileName);
17439 if (chainParams.mcmcDiagn == YES)
17441 if ((tempX = (MrBFlt *) SafeCalloc (chainParams.numStepsSS, sizeof(MrBFlt))) == NULL)
17445 ERROR_TEST2("Problem allocating memory", return(ERROR),);
17447 for (i=0; i<chainParams.numStepsSS; i++)
17451 MrBayesPrint ("\n");
17453 if (numTopologies > 1)
17455 if (chainParams.diagnStat == AVGSTDDEV)
17456 MrBayesPrint (" Plots of average standard deviation of split frequencies across steps for different topology.");
17458 MrBayesPrint (" Plots of max standard deviation of split frequencies across steps for different topology.");
17462 if (chainParams.diagnStat == AVGSTDDEV)
17463 MrBayesPrint (" Plot of average standard deviation of split frequencies across steps.");
17465 MrBayesPrint (" Plot of max standard deviation of split frequencies across steps.");
17467 MrBayesPrint ("\n");
17468 MrBayesPrint (" Points at -1.0 (y-axis) indicate that there were no splits\n");
17469 MrBayesPrint (" above minimum frequency for corresponding step.");
17470 if (numTopologies > 1)
17472 for (i=0; i<numTopologies; i++)
17474 MrBayesPrint ("%s Topology %d.\n", spacer, i+1);
17475 PrintPlot (tempX, splitfreqSS+i*chainParams.numStepsSS, chainParams.numStepsSS);
17479 PrintPlot (tempX, splitfreqSS, chainParams.numStepsSS);
17485 # if defined (MPI_ENABLED)
17486 /* we need to collect the information on the number of accepted moves if
17487 this is a parallel version */
17488 if (ReassembleMoveInfo() == ERROR)
17490 MPI_Allreduce (&nErrors, &sumErrors, 1, MPI_INT, MPI_SUM, MPI_COMM_WORLD);
17493 MrBayesPrint ("%s ReassembleMoveInfo failed\n", spacer);
17498 /* print acceptance rates for the moves */
17499 for (j=0; j<chainParams.numChains*chainParams.numRuns; j++)
17501 if (chainParams.numChains == 1)
17503 if (chainParams.numRuns == 1)
17504 MrBayesPrint ("%s Acceptance rates for the moves:\n", spacer);
17506 MrBayesPrint ("%s Acceptance rates for the moves in run %d:\n", spacer, j/chainParams.numChains+1);
17508 else if (j % chainParams.numChains == 0)
17510 if (chainParams.numRuns == 1)
17511 MrBayesPrint ("\n%s Acceptance rates for the moves in the \"cold\" chain:\n", spacer);
17513 MrBayesPrint ("\n%s Acceptance rates for the moves in the \"cold\" chain of run %d:\n", spacer, j/chainParams.numChains+1);
17515 else if (chainParams.allChains == YES)
17517 if (chainParams.numRuns == 1)
17518 MrBayesPrint ("\n%s Acceptance rates for the moves in chain %d (heated):\n\n", spacer, j+1);
17520 MrBayesPrint ("\n%s Acceptance rates for the moves in chain %d of run %d (heated):\n\n", spacer, j%chainParams.numChains+1, j/chainParams.numChains+1);
17523 if (j % chainParams.numChains == 0 || chainParams.allChains == YES)
17525 MrBayesPrint ("%s With prob. (last %d) chain accepted proposals by move\n", spacer, chainParams.tuneFreq);
17527 for (i=0; i<numUsedMoves; i++)
17530 if (mv->nBatches[j] < 1)
17531 MrBayesPrint ("%s NA NA %s\n",
17534 MrBayesPrint ("%s %6.1f %% (%3.0f %%) %s\n", spacer,
17535 100.0*mv->nTotAccepted[j]/(MrBFlt)(mv->nTotTried[j]),
17536 100.0*mv->lastAcceptanceRate[j],
17542 # if defined MPI_ENABLED
17543 /* Redistribute move info in case it is needed in a follow-up run */
17544 RedistributeMoveInfo();
17547 /* output information on the success of the chain state swap proposals */
17548 if (PrintSwapInfo () == ERROR)
17550 # if defined (MPI_ENABLED)
17551 MPI_Allreduce (&nErrors, &sumErrors, 1, MPI_INT, MPI_SUM, MPI_COMM_WORLD);
17554 MrBayesPrint ("%s PrintSwapInfo failed\n", spacer);
17560 MrBayesPrint ("%s PrintSwapInfo failed\n", spacer);
17565 # if defined (MPI_ENABLED)
17570 if (chainParams.isSS == NO && (chainParams.numRuns > 1 && chainParams.mcmcDiagn == YES))
17573 for (i=0; i<numTrees; i++)
17575 if (chainParams.stat[i].avgStdDev > f)
17576 f = chainParams.stat[i].avgStdDev;
17580 MrBayesPrint ("\n");
17581 MrBayesPrint ("%s ************************* WARNING!! ************************************ \n", spacer);
17582 MrBayesPrint ("%s MrBayes suspects that your runs have not converged because the tree \n", spacer);
17583 MrBayesPrint ("%s samples are very different (average standard deviation of split frequen- \n", spacer);
17584 MrBayesPrint ("%s cies larger than 0.10 (%1.2lf)). MrBayes suggests that you run the ana- \n", spacer, f);
17585 MrBayesPrint ("%s lysis longer or try to improve the MCMC sampling efficiency by fine- \n", spacer);
17586 MrBayesPrint ("%s tuning MCMC proposal or heating parameters. \n", spacer);
17594 int SafeSprintf (char **target, int *targetLen, char *fmt, ...)
17600 /* try to print in the available space */
17601 va_start(argp, fmt);
17603 retval = _vsnprintf (*target, *targetLen, fmt, argp);
17605 /* With SGI IRIX this function returns 0. Allen Smith suggested using
17606 _xpg5_vnsprintf, but this function needs a recent version of IRIX.
17607 For now, I just allocate a large buffer for SGI, so there is no need for
17608 memory reallocation on this kind of machines */
17609 /* It appears to me that the reason for the bug is that the old version of
17610 this function relies on nonstandard return values for vsnprintf. With
17611 the current version of the code, SGI should do fine without special
17613 retval = vsnprintf (*target, *targetLen, fmt, argp);
17617 /* if it worked, retval will be in interval [0,*targetLen-1], else -1 or true length */
17618 if (retval > -1 && retval < *targetLen)
17621 /* readjust length */
17622 if (retval > -1) /* some C compilers will return true length in retval */
17623 *targetLen = retval + 1; /* exactly what is needed */
17624 else /* some C compilers will return -1 on buffer overwrite */
17625 *targetLen += TARGETLENDELTA;
17627 /* reallocate target */
17628 *target = SafeRealloc ((void *)*target, *targetLen);
17629 if (*target == NULL)
17635 void SetChainIds (void)
17637 /* Fill <chainId[]> with the global chain number.
17638 Ex. For proc_0, chain[0] = 0;
17640 chain[2] = 2; (numchains = 3)
17641 For proc_1, chain[0] = 3;
17642 chain[1] = 4; (numchains = 2)
17646 # if defined (MPI_ENABLED)
17648 int i, proc, numChainsForProc, numGlobalChains;
17652 /* calculate global number of chains */
17653 numGlobalChains = chainParams.numChains * chainParams.numRuns;
17655 /* there are <remainder> chains left over after
17656 load balancing the chains */
17657 remainder = numGlobalChains % num_procs;
17659 /* get the number of chains handled by this proc */
17660 numChainsForProc = (int) (numGlobalChains / num_procs);
17662 /* we must distribute the remaining chains (causing
17663 the chain load between procs to become unbalanced) */
17664 if (proc_id < remainder)
17665 numChainsForProc++;
17667 /* NOTE: at this point, procs can have different number of numChainsForProc
17668 (one more for chains < remainder, one less for procs larger than or equal
17669 to the remainder) */
17672 for (proc=0; proc<num_procs; proc++)
17674 /* assign or increment chain id */
17675 if (proc == proc_id)
17677 for (i=0; i<numChainsForProc; i++)
17682 /* procs below the remainder have 1 more chain
17683 than procs above */
17684 if (proc < remainder)
17686 for (i=0; i<(numGlobalChains / num_procs) + 1; i++)
17689 /* procs above the remainder have one less chain
17690 than procs below */
17693 for (i=0; i<(numGlobalChains / num_procs); i++)
17702 for (chn=0; chn<numLocalChains; chn++)
17703 chainId[chn] = chn;
17710 /* It sets chainParams.tFilePos[] to point immidiatly after sampled tree in position "samplePos" for all .t files. */
17711 int SetFilePositions (int samplePos)
17713 int i, j, k, longestLine;
17714 BitsLong lastBlock;
17718 int tempStrSize = TEMPSTRSIZE;
17720 # if defined (MPI_ENABLED)
17725 tempStr = (char *) SafeMalloc((size_t)tempStrSize * sizeof(char));
17728 MrBayesPrint ("%s Problem allocating tempString (%d)\n", spacer, tempStrSize * sizeof(char));
17732 for (i=0; i<numTopologies; i++)
17734 for (j=0; j<chainParams.numRuns; j++)
17736 if (numPrintTreeParams == 1)
17738 if (chainParams.numRuns == 1)
17739 SafeSprintf (&tempStr, &tempStrSize, "%s.t", chainParams.chainFileName);
17741 SafeSprintf (&tempStr, &tempStrSize, "%s.run%d.t", chainParams.chainFileName, j+1);
17745 if (chainParams.numRuns == 1)
17746 SafeSprintf (&tempStr, &tempStrSize, "%s.tree%d.t", chainParams.chainFileName, i+1);
17748 SafeSprintf (&tempStr, &tempStrSize, "%s.tree%d.run%d.t", chainParams.chainFileName, i+1, j+1);
17751 if ((fp = OpenBinaryFileR (tempStr)) == NULL)
17753 MrBayesPrint ("%s Problem openning file %s.\n", spacer, tempStr);
17758 longestLine = LongestLine (fp);
17761 if ((fp = OpenTextFileR (tempStr)) == NULL)
17767 lineBuf = (char *) SafeCalloc (longestLine + 10, sizeof (char));
17775 lastBlock = LastBlock (fp, lineBuf, longestLine);
17776 fseek (fp, lastBlock, SEEK_SET);
17777 fseek (fp, FirstTree(fp, lineBuf, longestLine), SEEK_SET);
17779 for (k=0; k<samplePos; k++)
17781 if (fgets (lineBuf, longestLine + 5, fp) == NULL)
17783 MrBayesPrint ("%s Not enough records in file %s.\n", spacer, tempStr);
17790 fgetpos (fp, &chainParams.tFilePos[j*numTopologies+i]);
17801 /* SetFileNames: Set file names */
17802 void SetFileNames (void)
17804 strcpy (sumtParams.sumtFileName, chainParams.chainFileName);
17805 strcpy (sumtParams.sumtOutfile, chainParams.chainFileName);
17806 strcpy (sumpParams.sumpFileName, chainParams.chainFileName);
17807 strcpy (sumpParams.sumpOutfile, chainParams.chainFileName);
17808 if (chainParams.numRuns == 1)
17810 sprintf (comptreeParams.comptFileName1, "%s.t", chainParams.chainFileName);
17811 sprintf (comptreeParams.comptFileName2, "%s.t", chainParams.chainFileName);
17812 sprintf (plotParams.plotFileName, "%s.p", chainParams.chainFileName);
17813 MrBayesPrint ("%s Setting chain output file names to \"%s.<p/t>\"\n", spacer, chainParams.chainFileName);
17815 else /* if (chainParams.numRuns > 1) */
17817 sprintf (comptreeParams.comptFileName1, "%s.run1.t", chainParams.chainFileName);
17818 sprintf (comptreeParams.comptFileName2, "%s.run2.t", chainParams.chainFileName);
17819 sprintf (plotParams.plotFileName, "%s.run1.p", chainParams.chainFileName);
17820 MrBayesPrint ("%s Setting chain output file names to \"%s.run<i>.<p/t>\"\n", spacer, chainParams.chainFileName);
17825 /*----------------------------------------------------------------------------
17827 | SetLikeFunctions: This function will set up the pointers from each
17828 | data division to the relevant likelihood functions
17830 -----------------------------------------------------------------------------*/
17831 int SetLikeFunctions (void)
17837 /* couple divisions with likelihood functions */
17838 for (i=0; i<numCurrentDivisions; i++)
17840 m = &modelSettings[i];
17843 if (m->dataType == DNA || m->dataType == RNA)
17845 if (m->parsModelId == YES)
17847 m->Likelihood = &Likelihood_Pars;
17851 if (m->nucModelId == NUCMODEL_4BY4)
17853 if (m->numModelStates > 4)
17855 /* covariotide model */
17856 /* TODO: allow autocorrelated rates */
17857 if (m->gibbsGamma == YES)
17859 m->CondLikeDown = &CondLikeDown_Gen_GibbsGamma;
17860 m->CondLikeRoot = &CondLikeRoot_Gen_GibbsGamma;
17861 m->CondLikeScaler = &CondLikeScaler_Gen_GibbsGamma;
17862 m->Likelihood = &Likelihood_Gen_GibbsGamma;
17866 m->CondLikeDown = &CondLikeDown_Gen;
17867 m->CondLikeRoot = &CondLikeRoot_Gen;
17868 m->CondLikeScaler = &CondLikeScaler_Gen;
17869 m->Likelihood = &Likelihood_Gen;
17871 if (m->correlation != NULL)
17872 m->Likelihood = &Likelihood_Adgamma;
17874 m->Likelihood = &Likelihood_Gen;
17875 if (m->nCijkParts == 1)
17876 m->TiProbs = &TiProbs_Gen;
17877 else if (m->nCijkParts > 1)
17878 m->TiProbs = &TiProbs_GenCov;
17879 m->PrintAncStates = &PrintAncStates_NUC4;
17880 m->PrintSiteRates = &PrintSiteRates_Gen;
17884 # if defined (SSE_ENABLED)
17885 if (m->printAncStates == YES || m->printSiteRates == YES)
17887 MrBayesPrint ("%s Non-SSE version of conditional likelihood calculator will be used for division %d\n", spacer, i+1);
17888 MrBayesPrint ("%s due to request of reporting 'ancestral states' or 'site rates'.\n", spacer);
17891 m->CondLikeUp = &CondLikeUp_NUC4;
17892 m->PrintAncStates = &PrintAncStates_NUC4;
17893 m->PrintSiteRates = &PrintSiteRates_Gen;
17895 if (m->gibbsGamma == YES)
17897 m->CondLikeDown = &CondLikeDown_NUC4_GibbsGamma;
17898 m->CondLikeRoot = &CondLikeRoot_NUC4_GibbsGamma;
17899 m->CondLikeScaler = &CondLikeScaler_NUC4_GibbsGamma;
17901 else if (m->correlation != NULL || m->printAncStates == YES || m->printSiteRates == YES)
17903 m->CondLikeDown = &CondLikeDown_NUC4;
17904 m->CondLikeRoot = &CondLikeRoot_NUC4;
17905 m->CondLikeScaler = &CondLikeScaler_NUC4;
17910 m->CondLikeDown = &CondLikeDown_NUC4_SSE;
17911 m->CondLikeRoot = &CondLikeRoot_NUC4_SSE;
17912 m->CondLikeScaler = &CondLikeScaler_NUC4_SSE;
17913 /* Should be sse versions if we want to handle m->printAncStates == YES || inferSiteRates == YES.
17914 For now just set to NULL for early error detection if functions anyway got called by mistake */
17915 m->CondLikeUp = NULL;
17916 m->PrintAncStates = NULL;
17917 m->PrintSiteRates = NULL;
17920 if (m->correlation != NULL)
17921 m->Likelihood = &Likelihood_Adgamma;
17922 else if (m->gibbsGamma == YES)
17923 m->Likelihood = &Likelihood_NUC4_GibbsGamma;
17924 else if (m->printAncStates == YES || inferSiteRates == YES)
17925 m->Likelihood = &Likelihood_NUC4;
17927 m->Likelihood = &Likelihood_NUC4_SSE;
17929 if (m->gibbsGamma == YES)
17931 m->CondLikeDown = &CondLikeDown_NUC4_GibbsGamma;
17932 m->CondLikeRoot = &CondLikeRoot_NUC4_GibbsGamma;
17933 m->CondLikeScaler = &CondLikeScaler_NUC4_GibbsGamma;
17937 m->CondLikeDown = &CondLikeDown_NUC4;
17938 m->CondLikeRoot = &CondLikeRoot_NUC4;
17939 m->CondLikeScaler = &CondLikeScaler_NUC4;
17942 if (m->correlation != NULL)
17943 m->Likelihood = &Likelihood_Adgamma;
17944 else if (m->gibbsGamma == YES)
17945 m->Likelihood = &Likelihood_NUC4_GibbsGamma;
17947 m->Likelihood = &Likelihood_NUC4;
17949 m->CondLikeUp = &CondLikeUp_NUC4;
17950 m->PrintAncStates = &PrintAncStates_NUC4;
17951 m->PrintSiteRates = &PrintSiteRates_Gen;
17954 m->TiProbs = &TiProbs_Fels;
17955 else if (m->nst == 2)
17956 m->TiProbs = &TiProbs_Hky;
17958 m->TiProbs = &TiProbs_Gen;
17959 m->StateCode = &StateCode_NUC4;
17962 else if (m->nucModelId == NUCMODEL_DOUBLET)
17964 if (m->gibbsGamma == YES)
17966 m->CondLikeDown = &CondLikeDown_Gen_GibbsGamma;
17967 m->CondLikeRoot = &CondLikeRoot_Gen_GibbsGamma;
17968 m->CondLikeScaler = &CondLikeScaler_Gen_GibbsGamma;
17969 m->Likelihood = &Likelihood_Gen_GibbsGamma;
17973 m->CondLikeDown = &CondLikeDown_Gen;
17974 m->CondLikeRoot = &CondLikeRoot_Gen;
17975 m->CondLikeScaler = &CondLikeScaler_Gen;
17976 m->Likelihood = &Likelihood_Gen;
17979 m->TiProbs = &TiProbs_Gen;
17980 else if (m->nst == 2)
17981 m->TiProbs = &TiProbs_Gen;
17983 m->TiProbs = &TiProbs_Gen;
17984 m->CondLikeUp = &CondLikeUp_Gen;
17985 m->PrintAncStates = &PrintAncStates_Gen;
17986 m->PrintSiteRates = &PrintSiteRates_Gen;
17988 else if (m->nucModelId == NUCMODEL_CODON)
17991 if (m->numOmegaCats == 1)
17993 if (m->gibbsGamma == YES)
17995 m->CondLikeDown = &CondLikeDown_Gen_GibbsGamma;
17996 m->CondLikeRoot = &CondLikeRoot_Gen_GibbsGamma;
17997 m->CondLikeScaler = &CondLikeScaler_Gen_GibbsGamma;
17998 m->Likelihood = &Likelihood_Gen_GibbsGamma;
18002 m->CondLikeDown = &CondLikeDown_Gen;
18003 m->CondLikeRoot = &CondLikeRoot_Gen;
18004 m->CondLikeScaler = &CondLikeScaler_Gen;
18005 m->Likelihood = &Likelihood_Gen;
18006 # if defined (SSE_ENABLED)
18007 if (m->printAncStates == YES || m->printSiteRates == YES)
18009 MrBayesPrint ("%s Non-SSE version of conditional likelihood calculator will be used for division %d\n", spacer, i+1);
18010 MrBayesPrint ("%s due to request of reporting 'ancestral states' or 'site rates'.\n", spacer);
18015 m->CondLikeDown = &CondLikeDown_Gen_SSE;
18016 m->CondLikeRoot = &CondLikeRoot_Gen_SSE;
18017 m->CondLikeScaler = &CondLikeScaler_Gen_SSE;
18018 m->Likelihood = &Likelihood_Gen_SSE;
18025 m->CondLikeDown = &CondLikeDown_NY98;
18026 m->CondLikeRoot = &CondLikeRoot_NY98;
18027 m->CondLikeScaler = &CondLikeScaler_NY98;
18028 m->Likelihood = &Likelihood_NY98;
18029 m->PosSelProbs = &PosSelProbs;
18030 m->SiteOmegas = &SiteOmegas;
18031 # if defined (SSE_ENABLED)
18032 if (m->printAncStates == YES || m->printSiteRates == YES)
18034 MrBayesPrint ("%s Non-SSE version of conditional likelihood calculator will be used for division %d\n", spacer, i+1);
18035 MrBayesPrint ("%s due to request of reporting 'ancestral states' or 'site rates'.\n", spacer);
18040 m->CondLikeDown = &CondLikeDown_NY98_SSE;
18041 m->CondLikeRoot = &CondLikeRoot_NY98_SSE;
18042 m->CondLikeScaler = &CondLikeScaler_NY98_SSE;
18043 m->Likelihood = &Likelihood_NY98_SSE;
18044 m->PosSelProbs = &PosSelProbs_SSE;
18045 m->SiteOmegas = &SiteOmegas_SSE;
18049 m->TiProbs = &TiProbs_Gen;
18050 if (m->nCijkParts > 1)
18051 m->TiProbs = &TiProbs_GenCov;
18052 m->CondLikeUp = &CondLikeUp_Gen;
18053 m->PrintAncStates = &PrintAncStates_Gen;
18054 m->PrintSiteRates = &PrintSiteRates_Gen;
18056 else /* if (m->nucModelId == NUCMODEL_AA) */
18058 if (m->gibbsGamma == YES)
18060 m->CondLikeDown = &CondLikeDown_Gen_GibbsGamma;
18061 m->CondLikeRoot = &CondLikeRoot_Gen_GibbsGamma;
18062 m->CondLikeScaler = &CondLikeScaler_Gen_GibbsGamma;
18063 m->Likelihood = &Likelihood_Gen_GibbsGamma;
18067 m->CondLikeDown = &CondLikeDown_Gen;
18068 m->CondLikeRoot = &CondLikeRoot_Gen;
18069 m->CondLikeScaler = &CondLikeScaler_Gen;
18070 m->Likelihood = &Likelihood_Gen;
18071 # if defined (SSE_ENABLED)
18072 if (m->printAncStates == YES || m->printSiteRates == YES)
18074 MrBayesPrint ("%s Non-SSE version of conditional likelihood calculator will be used for division %d\n", spacer, i+1);
18075 MrBayesPrint ("%s due to request of reporting 'ancestral states' or 'site rates'.\n", spacer);
18080 m->CondLikeDown = &CondLikeDown_Gen_SSE;
18081 m->CondLikeRoot = &CondLikeRoot_Gen_SSE;
18082 m->CondLikeScaler = &CondLikeScaler_Gen_SSE;
18083 m->Likelihood = &Likelihood_Gen_SSE;
18087 if (m->nCijkParts > 1)
18088 m->TiProbs = &TiProbs_GenCov;
18090 m->TiProbs = &TiProbs_Gen;
18091 m->CondLikeUp = &CondLikeUp_Gen;
18092 m->StateCode = &StateCode_AA;
18093 m->PrintAncStates = &PrintAncStates_Gen;
18094 m->PrintSiteRates = &PrintSiteRates_Gen;
18098 else if (m->dataType == PROTEIN)
18100 if (m->parsModelId == YES)
18102 m->Likelihood = &Likelihood_Pars;
18106 /* TODO: allow autocorrelated rates for covarion model */
18107 if (m->gibbsGamma == YES)
18109 m->CondLikeDown = &CondLikeDown_Gen_GibbsGamma;
18110 m->CondLikeRoot = &CondLikeRoot_Gen_GibbsGamma;
18111 m->CondLikeScaler = &CondLikeScaler_Gen_GibbsGamma;
18112 m->Likelihood = &Likelihood_Gen_GibbsGamma;
18116 m->CondLikeDown = &CondLikeDown_Gen;
18117 m->CondLikeRoot = &CondLikeRoot_Gen;
18118 m->CondLikeScaler = &CondLikeScaler_Gen;
18119 m->Likelihood = &Likelihood_Gen;
18120 # if defined (SSE_ENABLED)
18121 if (m->printAncStates == YES || m->printSiteRates == YES)
18123 MrBayesPrint ("%s Non-SSE version of conditional likelihood calculator will be used for division %d\n", spacer, i+1);
18124 MrBayesPrint ("%s due to request of reporting 'ancestral states' or 'site rates'.\n", spacer);
18129 m->CondLikeDown = &CondLikeDown_Gen_SSE;
18130 m->CondLikeRoot = &CondLikeRoot_Gen_SSE;
18131 m->CondLikeScaler = &CondLikeScaler_Gen_SSE;
18132 m->Likelihood = &Likelihood_Gen_SSE;
18136 if (m->correlation != NULL)
18138 if (m->gibbsGamma == YES)
18140 MrBayesPrint ("%s Adgamma model cannot be used with Gibbs sampling of rate categories\n", spacer);
18144 m->Likelihood = &Likelihood_Adgamma;
18146 if (m->numModelStates > 20 && m->nCijkParts > 1)
18147 m->TiProbs = &TiProbs_GenCov;
18149 m->TiProbs = &TiProbs_Gen;
18150 m->CondLikeUp = &CondLikeUp_Gen;
18151 m->StateCode = &StateCode_AA;
18152 m->PrintAncStates = &PrintAncStates_Gen;
18153 m->PrintSiteRates = &PrintSiteRates_Gen;
18156 else if (m->dataType == RESTRICTION)
18158 if (m->parsModelId == YES)
18160 m->Likelihood = &Likelihood_Pars;
18164 m->CondLikeDown = &CondLikeDown_Bin;
18165 m->CondLikeRoot = &CondLikeRoot_Bin;
18166 m->CondLikeScaler = &CondLikeScaler_Gen;
18167 m->Likelihood = &Likelihood_Res;
18168 # if defined (SSE_ENABLED)
18169 if (m->printAncStates == YES || m->printSiteRates == YES)
18171 MrBayesPrint ("%s Non-SSE version of conditional likelihood calculator will be used for division %d\n", spacer, i+1);
18172 MrBayesPrint ("%s due to request of reporting 'ancestral states' or 'site rates'.\n", spacer);
18177 m->CondLikeDown = &CondLikeDown_Bin_SSE;
18178 m->CondLikeRoot = &CondLikeRoot_Bin_SSE;
18179 m->CondLikeScaler = &CondLikeScaler_Gen_SSE;
18180 m->Likelihood = &Likelihood_Res_SSE;
18183 m->TiProbs = &TiProbs_Res;
18184 m->CondLikeUp = &CondLikeUp_Bin;
18185 m->StateCode = &StateCode_Std;
18186 m->PrintAncStates = &PrintAncStates_Bin;
18187 m->PrintSiteRates = &PrintSiteRates_Gen;
18190 else if (m->dataType == STANDARD)
18192 if (m->parsModelId == YES)
18194 if (m->numModelStates == 2)
18196 m->Likelihood = &Likelihood_Pars; /* this is much faster if number of states do not vary */
18197 m->numStates = 2; /* this is needed for the parsimony calculator */
18200 m->Likelihood = &Likelihood_ParsStd;
18204 m->CondLikeDown = &CondLikeDown_Std;
18205 m->CondLikeRoot = &CondLikeRoot_Std;
18206 m->CondLikeScaler = &CondLikeScaler_Std;
18207 m->Likelihood = &Likelihood_Std;
18208 m->TiProbs = &TiProbs_Std;
18209 m->CondLikeUp = &CondLikeUp_Std;
18210 m->StateCode = &StateCode_Std;
18211 m->PrintAncStates = &PrintAncStates_Std;
18212 m->PrintSiteRates = &PrintSiteRates_Std;
18215 else if (m->dataType == CONTINUOUS)
18221 MrBayesPrint ("%s ERROR: Data should be one of these types!\n", spacer);
18231 /* Determine number of chains and data splits to be handled by MPI processors or threads */
18232 int SetLocalChainsAndDataSplits(void)
18234 # if defined (MPI_ENABLED)
18236 /* tell user how many chains each processor has been assigned */
18237 if (num_procs <= numGlobalChains)
18239 if (numGlobalChains % num_procs != 0)
18241 MrBayesPrint ("%s The total number of chains (%d) must be evenly divisible by\n", spacer, numGlobalChains);
18242 MrBayesPrint ("%s the number of MPI processors (%d).\n", spacer, num_procs);
18244 MrBayesPrint ("%s The total number of chains (%d) must be evenly divisible by\n", spacer, numGlobalChains);
18245 MrBayesPrint ("%s the number of MPI processors (%d), or the number of MPI\n", spacer, num_procs);
18246 MrBayesPrint ("%s processors should be a multiple of the number of chains.\n", spacer, num_procs);
18248 MrBayesPrint ("%s Please change your MPI settings.\n", spacer, num_procs);
18251 numLocalChains = numGlobalChains / num_procs;
18252 MrBayesPrint ("%s Number of chains per MPI processor = %d\n", spacer, numLocalChains);
18256 MrBayesPrint ("%s There must be at least as many chains as MPI processors\n", spacer);
18261 if (num_procs % numGlobalChains != 0)
18263 MrBayesPrint ("%s The number of MPI processors (%d) must be a multiple of the\n", spacer, num_procs);
18264 MrBayesPrint ("%s total number of chains (%d), or the total number of chains\n", spacer, numGlobalChains);
18265 MrBayesPrint ("%s should be evenly divisible by the number of MPI processsors.\n", spacer);
18266 MrBayesPrint ("%s Please change your MPI settings.\n", spacer);
18269 numLocalChains = 1;
18270 // numMPIDataSplits = num_procs / numGlobalChains;
18271 // MrBayesPrint ("%s Number of MPI data splits per chain = %d\n", spacer, numMPIDataSplits);
18276 numLocalChains = numGlobalChains;
18280 # if defined (THREADS_ENABLED)
18282 if (numLocalChains > 1)
18284 /* Use pthreads to divide chains and possibly do data splits */
18288 /* Use pthreads for data splits */
18296 /*----------------------------------------------------------------------------
18298 | ShowMoveSummary: Show summary of moves that will be used in MCMC sampling
18300 -----------------------------------------------------------------------------*/
18301 int ShowMoveSummary (void)
18303 int i, run, chain, areRunsSame, areChainsSame, chainIndex;
18307 /* first find out if the probabilities are different in different runs */
18309 for (run=1; run<chainParams.numRuns; run++)
18311 for (chain=0; chain<chainParams.numChains; chain++)
18313 chainIndex = run*chainParams.numChains + chain;
18314 for (i=0; i<numUsedMoves; i++)
18317 if (AreDoublesEqual (mv->relProposalProb[chainIndex], mv->relProposalProb[chain], 0.000001) == NO)
18323 if (areRunsSame == NO)
18326 if (areRunsSame == NO)
18330 /* now print values */
18331 for (run=0; run<chainParams.numRuns; run++)
18333 if (areRunsSame == YES && run >= 1)
18336 /* find out if chains are different within this run */
18337 areChainsSame = YES;
18338 for (chain=1; chain<chainParams.numChains; chain++)
18340 chainIndex = run*chainParams.numChains + chain;
18341 for (i=0; i<numUsedMoves; i++)
18344 if (AreDoublesEqual (mv->relProposalProb[chainIndex], mv->relProposalProb[chainIndex-chain], 0.000001) == NO)
18346 areChainsSame = NO;
18350 if (areChainsSame == NO)
18354 for (chain=0; chain<chainParams.numChains; chain++)
18356 if (areChainsSame == YES && chain >= 1)
18359 /* now we can print the values */
18360 MrBayesPrint("\n");
18361 if (areRunsSame == YES && areChainsSame == YES)
18362 MrBayesPrint ("%s The MCMC sampler will use the following moves:\n", spacer);
18363 else if (areRunsSame == NO && areChainsSame == YES)
18364 MrBayesPrint ("%s The MCMC sampler will use the following moves for run %d:\n", spacer, run+1);
18365 else if (areRunsSame == YES && areChainsSame == NO)
18366 MrBayesPrint ("%s The MCMC sampler will use the following moves for chain %d:\n", spacer, chain+1);
18367 else if (areRunsSame == NO && areChainsSame == NO)
18368 MrBayesPrint ("%s The MCMC sampler will use the following moves for run %d, chain %d:\n", spacer, run+1, chain+1);
18370 chainIndex = run*chainParams.numChains + chain;
18371 MrBayesPrint ("%s With prob. Chain will use move\n", spacer);
18372 for (i=0; i<numUsedMoves; i++)
18375 prob = mv->cumProposalProb[chainIndex];
18377 prob -= usedMoves[i-1]->cumProposalProb[chainIndex];
18378 if (AreDoublesEqual(prob,0.0,0.000001) == YES)
18380 MrBayesPrint ("%s %6.2f %% %s\n", spacer, 100*prob, mv->name);
18382 MrBayesPrint ("\n");
18390 /*----------------------------------------------------------------------
18392 | SetUpPartitionCounters: Set up partitions and the root of the
18393 | partition frequency tree
18395 |----------------------------------------------------------------------*/
18396 int SetUpPartitionCounters (void)
18400 # if defined (MPI_ENABLED)
18401 /* we only keep partition counters on proc 0 in the MPI version */
18405 nLongsNeeded = 1 + (numLocalTaxa - 1) / nBitsInALong;
18407 if (memAllocs[ALLOC_PFCOUNTERS] == YES)
18409 MrBayesPrint ("%s ERROR: pfcounters not free in SetUpPartitionCounters\n", spacer);
18412 partition = (BitsLong **) SafeCalloc (2*numLocalTaxa, sizeof (BitsLong *));
18413 if (partition == NULL)
18415 MrBayesPrint ("%s Failed to allocate partition in SetUpPartitionCounters\n", spacer);
18418 partition[0] = (BitsLong *) SafeCalloc (2*numLocalTaxa * nLongsNeeded, sizeof(BitsLong));
18419 if (partition[0] == NULL)
18422 MrBayesPrint ("%s Failed to allocate partition[0] in SetUpPartitionCounters\n", spacer);
18425 partFreqTreeRoot = (PFNODE **) SafeCalloc (numTopologies, sizeof (PFNODE *));
18426 if (partFreqTreeRoot == NULL)
18429 free (partition[0]);
18430 MrBayesPrint ("%s Failed to allocate partFreqTreeRoot in SetUpPartitionCounters\n", spacer);
18433 memAllocs[ALLOC_PFCOUNTERS] = YES;
18435 for (i=1; i<2*numLocalTaxa; i++)
18437 partition[i] = partition[0] + i*nLongsNeeded;
18440 for (i=0; i<numLocalTaxa; i++)
18441 SetBit (i, partition[i]);
18443 for (i=0; i<numTopologies; i++)
18444 partFreqTreeRoot[i] = NULL;
18450 /*----------------------------------------------------------------------
18452 | SetupTermState: create matrix holding unambiguous states for
18453 | terminals (used for local compression on terminal branches)
18455 -----------------------------------------------------------------------*/
18456 int SetUpTermState (void)
18458 int i, k, n, c, d, x=0, *termStatePtr;
18462 int numComprChars = 0;
18464 /* allocate space for termState and isPartAmbig */
18465 if (memAllocs[ALLOC_TERMSTATE] == YES || memAllocs[ALLOC_ISPARTAMBIG] == YES)
18467 MrBayesPrint ("%s termState or isPartAmbig is not free in SetupTermState\n", spacer);
18471 # if defined SSE_ENABLED
18472 for (d=0; d<numCurrentDivisions; d++)
18474 m = &modelSettings[d];
18475 m->numSSEChars = ((m->numChars - 1) / FLOATS_PER_VEC) + 1;
18476 if (m->dataType != STANDARD && m->gibbsGamma == NO)
18477 numComprChars += m->numSSEChars * FLOATS_PER_VEC;
18479 numComprChars += m->numChars;
18482 numComprChars = numCompressedChars;
18485 termState = (int *) SafeCalloc (numLocalTaxa * numComprChars, sizeof(int));
18487 memAllocs[ALLOC_TERMSTATE] = YES;
18490 MrBayesPrint ("%s Problem allocating termState\n", spacer);
18493 isPartAmbig = (int *) SafeCalloc (numLocalTaxa*numCurrentDivisions, sizeof(int));
18495 memAllocs[ALLOC_ISPARTAMBIG] = YES;
18498 MrBayesPrint ("%s Problem allocating isPartAmbig\n", spacer);
18502 /*initialize isPartAmbig */
18503 for (i=0; i<numLocalTaxa*numCurrentDivisions; i++)
18504 isPartAmbig[i] = NO;
18506 /* loop over divisions */
18507 termStatePtr = termState;
18508 for (d=0; d<numCurrentDivisions; d++)
18510 m = &modelSettings[d];
18511 mp = &modelParams[d];
18513 /* don't do anything for continuous data */
18514 if (mp->dataType == CONTINUOUS)
18517 m->termState = (int **) SafeCalloc (numLocalTaxa, sizeof(int *));
18520 MrBayesPrint("%s Problems allocating termState pointers for division %d\n", spacer, d+1);
18524 # if defined SSE_ENABLED
18525 if (m->dataType != STANDARD && m->gibbsGamma == NO)
18526 numComprChars = m->numSSEChars * FLOATS_PER_VEC;
18528 numComprChars = m->numChars;
18531 numComprChars = m->numChars;
18534 for (i=0; i<numLocalTaxa; i++)
18536 m->termState[i] = termStatePtr;
18537 termStatePtr += numComprChars;
18540 m->isPartAmbig = isPartAmbig + numLocalTaxa * d;
18542 for (i=0; i<numLocalTaxa; i++)
18544 p = m->parsSets[i];
18545 for (c=0; c<m->numChars; c++)
18547 for (k=n=0; k<m->numStates; k++)
18549 if (IsBitSet(k, p))
18555 /* find appropriate index */
18557 m->termState[i][c] = x * m->numModelStates;
18558 else if (n == m->numStates)
18559 m->termState[i][c] = m->numStates * m->numModelStates;
18561 m->isPartAmbig[i] = YES;
18563 p += m->nParsIntsPerSite;
18565 for (; c<numComprChars; c++)
18567 /* Setting to fully ambig state all padding chars */
18568 m->termState[i][c] = m->numStates * m->numModelStates;
18573 /* print the termState matrix */
18574 # if defined (DEBUG_SETUPTERMSTATE)
18583 /*----------------------------------------------------------------------------
18585 | SetUsedMoves: This function will extract an array of pointers to the moves
18586 | that will actually be used in the MCMC sampling. It also makes sure
18587 | that the parsimonyBased flag is set in the relevant model partitions
18588 | if there are moves used that are based on parsimony scores
18590 -----------------------------------------------------------------------------*/
18591 int SetUsedMoves (void)
18593 int i, j, moveIndex, numGlobalChains;
18594 MrBFlt prob, sum, cumSum;
18596 /* first count moves */
18598 numGlobalChains = chainParams.numChains * chainParams.numRuns;
18599 for (i=0; i<numApplicableMoves; i++)
18602 for (j=0; j<numGlobalChains; j++)
18604 if (moves[i]->relProposalProb[j] > prob)
18605 prob = moves[i]->relProposalProb[j];
18607 if (prob > 0.000001)
18611 /* allocate space */
18612 if (memAllocs[ALLOC_USEDMOVES] == YES)
18614 MrBayesPrint ("%s Memory problem: usedMoves not free in SetUsedMoves\n", spacer);
18617 usedMoves = (MCMCMove **) SafeMalloc (numUsedMoves * sizeof (MCMCMove *));
18620 MrBayesPrint ("%s Problem allocating usedMoves\n", spacer);
18623 memAllocs[ALLOC_USEDMOVES] = YES;
18625 /* set move pointers */
18627 for (i=0; i<numApplicableMoves; i++)
18630 for (j=0; j<numGlobalChains; j++)
18632 if (moves[i]->relProposalProb[j] > prob)
18633 prob = moves[i]->relProposalProb[j];
18635 if (prob > 0.000001)
18636 usedMoves[moveIndex++] = moves[i];
18639 if (moveIndex != numUsedMoves)
18641 MrBayesPrint ("%s Problem finding the used moves\n", spacer);
18645 /* set parsimony flag if applicable */
18646 for (i=0; i<numCurrentDivisions; i++)
18647 modelSettings[i].parsimonyBasedMove = NO;
18648 for (i=0; i<numUsedMoves; i++)
18650 if (usedMoves[i]->moveType->parsimonyBased == YES)
18652 for (j=0; j<usedMoves[i]->parm->nRelParts; j++)
18653 modelSettings[usedMoves[i]->parm->relParts[j]].parsimonyBasedMove = YES;
18657 /* set cumulative proposal probabilities */
18658 for (j=0; j<numGlobalChains; j++)
18661 for (i=0; i<numUsedMoves; i++)
18663 sum += usedMoves[i]->relProposalProb[j];
18666 for (i=0; i<numUsedMoves; i++)
18668 cumSum += usedMoves[i]->relProposalProb[j];
18669 usedMoves[i]->cumProposalProb[j] = cumSum / sum;
18673 /* reset acceptance probability values */
18674 for (i=0; i<numUsedMoves; i++)
18676 for (j=0; j<numGlobalChains; j++)
18678 usedMoves[i]->nAccepted[j] = 0;
18679 usedMoves[i]->nTried[j] = 0;
18680 usedMoves[i]->nTotAccepted[j] = 0;
18681 usedMoves[i]->nTotTried[j] = 0;
18689 void ShowValuesForChain (int chn)
18694 MrBayesPrint ("%s Chain = %d\n", spacer, chn);
18695 MrBayesPrint ("%s numParams = %d\n", spacer, numParams);
18696 MrBayesPrint ("%s numTrees = %d\n", spacer, numTrees);
18697 MrBayesPrint ("%s current state: %d\n", spacer, state[chn]);
18699 strcat (spacer, " ");
18702 for (i=0; i<numCurrentDivisions; i++)
18704 sprintf (s, "tRatio[%d]", i);
18705 PrintParamValues (modelSettings[i].tRatio, chn, s);
18709 for (i=0; i<numCurrentDivisions; i++)
18711 sprintf (s, "revMat[%d]", i);
18712 PrintParamValues (modelSettings[i].revMat, chn, s);
18716 for (i=0; i<numCurrentDivisions; i++)
18718 sprintf (s, "stateFreq[%d]", i);
18719 PrintParamValues (modelSettings[i].stateFreq, chn, s);
18723 for (i=0; i<numCurrentDivisions; i++)
18725 sprintf (s, "omega[%d]", i);
18726 PrintParamValues (modelSettings[i].omega, chn, s);
18730 for (i=0; i<numCurrentDivisions; i++)
18732 sprintf (s, "shape[%d]", i);
18733 PrintParamValues (modelSettings[i].shape, chn, s);
18737 for (i=0; i<numCurrentDivisions; i++)
18739 sprintf (s, "pInvar[%d]", i);
18740 PrintParamValues (modelSettings[i].pInvar, chn, s);
18744 for (i=0; i<numCurrentDivisions; i++)
18746 sprintf (s, "correlation[%d]", i);
18747 PrintParamValues (modelSettings[i].correlation, chn, s);
18751 for (i=0; i<numCurrentDivisions; i++)
18753 sprintf (s, "switchRates[%d]", i);
18754 PrintParamValues (modelSettings[i].switchRates, chn, s);
18758 for (i=0; i<numCurrentDivisions; i++)
18760 sprintf (s, "rateMult[%d]", i);
18761 PrintParamValues (modelSettings[i].rateMult, chn, s);
18764 /* speciationRates */
18765 for (i=0; i<numCurrentDivisions; i++)
18767 sprintf (s, "speciationRates[%d]", i);
18768 PrintParamValues (modelSettings[i].speciationRates, chn, s);
18771 /* extinctionRates */
18772 for (i=0; i<numCurrentDivisions; i++)
18774 sprintf (s, "extinctionRates[%d]", i);
18775 PrintParamValues (modelSettings[i].extinctionRates, chn, s);
18778 /* fossilizationRates */
18779 for (i=0; i<numCurrentDivisions; i++)
18781 sprintf (s, "fossilizationRates[%d]", i);
18782 PrintParamValues (modelSettings[i].fossilizationRates, chn, s);
18786 for (i=0; i<numCurrentDivisions; i++)
18788 sprintf (s, "popSize[%d]", i);
18789 PrintParamValues (modelSettings[i].popSize, chn, s);
18793 for (i=0; i<numCurrentDivisions; i++)
18795 MrBayesPrint ("%s topology[%d] state 0\n", spacer, i);
18796 ShowTree(GetTree (modelSettings[i].topology, chn, 0));
18797 MrBayesPrint ("%s topology[%d] state 1\n", spacer, i);
18798 ShowTree(GetTree (modelSettings[i].topology, chn, 1));
18802 for (i=0; i<numCurrentDivisions; i++)
18804 MrBayesPrint ("%s tree[%d] state 0\n", spacer, i);
18805 ShowTree(GetTree (modelSettings[i].topology, chn, 0));
18806 MrBayesPrint ("%s tree[%d] state 1\n", spacer, i);
18807 ShowTree(GetTree (modelSettings[i].topology, chn, 1));
18810 spacer[strlen(spacer) - 3] = '\0';
18813 for (i=0; i<sizeOfParamValues; i++)
18814 MrBayesPrint ("%4d -- %lf\n", i, paramValues[i]);
18819 /* SmallestNonemptyPFNode: recursive function to smallest nonempty node in a subtree */
18820 PFNODE *SmallestNonemptyPFNode (PFNODE *p, int *i, int j)
18828 q = SmallestNonemptyPFNode (p->right, i, j);
18834 else if (IsPFNodeEmpty (p) == NO)
18841 return SmallestNonemptyPFNode (p->left, i, j);
18846 /* Talloc: Allocate space for a new node in the tree keeping track of partition frequencies */
18847 PFNODE *Talloc (void)
18851 temp = (PFNODE *) SafeMalloc (sizeof(PFNODE));
18855 temp->partition = (BitsLong *) SafeCalloc (nLongsNeeded, sizeof (BitsLong));
18856 if (temp->partition == NULL)
18862 temp->count = (int *) SafeCalloc (chainParams.numRuns, sizeof (int));
18863 if (temp->count == NULL)
18865 free (temp->partition);
18874 MrBFlt Temperature (int id)
18876 /* let id be number of chain in run */
18877 id %= chainParams.numChains;
18879 if (chainParams.userDefinedTemps == YES)
18881 return (chainParams.userTemps[id]);
18885 return (1.0 / (1.0 + chainParams.chainTemp * id));
18890 /* Tfree: Free space for partition frequency counter tree */
18891 void Tfree (PFNODE *r)
18895 if (r->left != NULL)
18897 if (r->right != NULL)
18900 free (r->partition);
18907 void TouchAllCijks (int chain)
18911 for (i=0; i<numCurrentDivisions; i++)
18913 if (modelSettings[i].nCijkParts >= 1)
18914 modelSettings[i].upDateCijk = YES;
18918 MrBayesPrint ("%d", chain); /* just because I am tired of seeing the unused parameter error msg */
18922 void TouchAllPartitions (void)
18926 for (i=0; i<numCurrentDivisions; i++)
18928 modelSettings[i].upDateCl = YES;
18935 void TouchAllTrees (int chain)
18941 for (i=0; i<numTrees; i++)
18943 t = GetTreeFromIndex (i, chain, state[chain]);
18944 for (j=0; j<t->nNodes; j++)
18946 p = t->allDownPass[j];
18952 for (i=0; i<numCurrentDivisions; i++)
18953 modelSettings[i].upDateAll = YES;
18959 /* Touch all update flags so we recalculate likelihood from scratch */
18960 void TouchEverything (int chain)
18966 for (i=0; i<numCurrentDivisions; i++)
18968 if (modelSettings[i].nCijkParts >= 1)
18969 modelSettings[i].upDateCijk = YES;
18970 modelSettings[i].upDateCl = YES;
18971 modelSettings[i].upDateAll = YES;
18974 for (i=0; i<numTrees; i++)
18976 t = GetTreeFromIndex (i, chain, state[chain]);
18977 for (j=0; j<t->nNodes; j++)
18979 p = t->allDownPass[j];
18989 /*------------------------------------------------------------------
18991 | TreeLength: Calculates the tree length as the sum of the lengths
18992 | of all the branches. The tree length is the expected number
18993 | of character state transformations per character over the
18994 | entire phylogenetic tree.
18996 -------------------------------------------------------------------*/
18997 MrBFlt TreeLength (Param *param, int chain)
19004 if (param->paramId == BRLENS_PARSIMONY)
19007 for (j=0; j<param->nRelParts; j++)
19008 tl += modelSettings[param->relParts[j]].parsTreeLength[2*chain+state[chain]];
19013 t = GetTree (param, chain, state[chain]);
19015 /* loop over all branches of the tree */
19017 for (i=0; i<t->nNodes; i++)
19019 p = t->allDownPass[i];
19020 if (p->anc != NULL)
19022 if (p->anc->anc == NULL && t->isRooted == NO)
19038 /* proportion of ancestral fossils in a FBD tree */
19039 MrBFlt PropAncFossil (Param *param, int chain)
19045 t = GetTree (param, chain, state[chain]);
19047 if (t->isRooted == NO)
19050 /* count # of tip and ancestral fossils */
19052 for (i = 0; i < t->nNodes -2; i++)
19054 p = t->allDownPass[i];
19055 if (p->left == NULL && p->right == NULL && p->nodeDepth > 0.0)
19057 if (p->length > 0.0)
19067 return (MrBFlt)k / (m+k);