]> git.donarmstrong.com Git - mrbayes.git/blob - src/mcmc.c
import mrbayes
[mrbayes.git] / src / mcmc.c
1 /*
2  *  MrBayes 3
3  *
4  *  (c) 2002-2013
5  *
6  *  John P. Huelsenbeck
7  *  Dept. Integrative Biology
8  *  University of California, Berkeley
9  *  Berkeley, CA 94720-3140
10  *  johnh@berkeley.edu
11  *
12  *  Fredrik Ronquist
13  *  Swedish Museum of Natural History
14  *  Box 50007
15  *  SE-10405 Stockholm, SWEDEN
16  *  fredrik.ronquist@nrm.se
17  *
18  *  With important contributions by
19  *
20  *  Paul van der Mark (paulvdm@sc.fsu.edu)
21  *  Maxim Teslenko (maxim.teslenko@nrm.se)
22  *
23  *  and by many users (run 'acknowledgments' to see more info)
24  *
25  * This program is free software; you can redistribute it and/or
26  * modify it under the terms of the GNU General Public License
27  * as published by the Free Software Foundation; either version 2
28  * of the License, or (at your option) any later version.
29  *
30  * This program is distributed in the hope that it will be useful,
31  * but WITHOUT ANY WARRANTY; without even the implied warranty of
32  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
33  * GNU General Public License for more details (www.gnu.org).
34  *
35  */
36
37 #include "bayes.h"
38 #include "best.h"
39 #include "command.h"
40 #include "likelihood.h"
41 #include "mbbeagle.h"
42 #include "mcmc.h"
43 #include "model.h"
44 #include "proposal.h"
45 #include "sumpt.h"
46 #include "utils.h"
47 #if defined(__MWERKS__)
48 #include "SIOUX.h"
49 #endif
50 #include <signal.h>
51
52 const char* const svnRevisionMcmcC = "$Rev: 1072 $";   /* Revision keyword which is expanded/updated by svn on each commit/update */
53
54 #if defined (WIN_VERSION) && !defined (__GNUC__)
55 #define VISUAL
56 #else
57 typedef void (*sighandler_t) (int);
58 #endif
59
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 */
66 #define PFILE                       0
67 #define TFILE                       1
68 #define CALFILE                     2
69 #define MCMCFILE                    3
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
75
76 /* debugging compiler statements */
77 #undef  DEBUG_SETUPTERMSTATE
78 #undef  DEBUG_RUNCHAIN
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
87 #undef  SHOW_MOVE
88
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);\
92     if (sumErrors > 0)\
93         {\
94         MrBayesPrint ("%s   "failString"\n", spacer);\
95         X1;X2;\
96         }
97 #else
98 #define ERROR_TEST2(failString,X1,X2) \
99     if (nErrors > 0)\
100         {\
101         MrBayesPrint ("%s   "failString"\n", spacer);\
102         X1;X2;\
103         }
104 #endif
105
106 /* local (to this file) data types */
107 typedef struct pfnode
108     {
109     struct pfnode   *left;
110     struct pfnode   *right;
111     int             *count;
112     BitsLong        *partition;
113     } PFNODE;
114
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);
125 #ifdef    VISUAL
126 BOOL      WINAPI CatchInterrupt (DWORD signum);
127 #else  
128 void      CatchInterrupt (int signum);
129 #endif  
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);
184 #endif
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);
195 #endif
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);
217 #endif
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);
234 int       SetMoves (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);
247 #endif
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);
256
257 /* globals */
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                 */
274
275 #if defined (BEAGLE_ENABLED)
276 int             recalcScalers;               /* shoud we recalculate scalers for current state YES/NO */
277 #endif
278
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    */
339
340 #if defined (MPI_ENABLED)
341 int             lowestLocalRunId;            /* lowest local run Id                          */
342 int             highestLocalRunId;           /* highest local run Id                         */
343 #endif
344
345 #if defined (PRINT_DUMP)
346 FILE            **fpDump = NULL;             /* pointer to .dump file(s)                     */
347 #endif
348
349 /* AddPartition: Add a partition to the tree keeping track of partition frequencies */
350 PFNODE *AddPartition (PFNODE *r, BitsLong *p, int runId)
351 {
352     int     i, comp;
353     
354     if (r == NULL)
355         {
356         /* new partition */
357         r = Talloc ();                  /* create a new node */
358         if (r == NULL)
359             return NULL;
360         for (i=0; i<nLongsNeeded; i++)
361             r->partition[i] = p[i];
362         for (i=0; i<chainParams.numRuns; i++)
363             r->count[i] = 0;
364         r->count[runId] = 1;
365         r->left = r->right = NULL;
366         }
367     else
368         {
369         for (i=0; i<nLongsNeeded; i++)
370             {
371             if (r->partition[i] != p[i])
372                 break;
373             }
374         
375         if (i == nLongsNeeded)
376             comp = 0;
377         else if (r->partition[i] < p[i])
378             comp = -1;
379         else
380             comp = 1;
381         
382         if (comp == 0)          /* repeated partition */
383             r->count[runId]++;
384         else if (comp < 0)      /* greater than -> into left subtree */
385             {
386             if ((r->left = AddPartition (r->left, p, runId)) == NULL)
387                 {
388                 Tfree (r);
389                 return NULL;
390                 }
391             }
392         else
393             {
394             /* smaller than -> into right subtree */
395             if ((r->right = AddPartition (r->right, p, runId)) == NULL)
396                 {
397                 Tfree (r);
398                 return NULL;
399                 }
400             }
401         }
402
403     return r;
404 }
405
406
407 int AddToPrintString (char *tempStr)
408 {
409     size_t  len1, len2;
410     
411     len1 = strlen(printString);
412     len2 = strlen(tempStr);
413     if (len1 + len2 + 5 > printStringSize)
414         {
415         printStringSize += len1 + len2 - printStringSize + 200;
416         printString = (char*)SafeRealloc((void*)printString, printStringSize * sizeof(char));
417         if (!printString)
418             {
419             MrBayesPrint ("%s   Problem reallocating printString (%d)\n", spacer, printStringSize * sizeof(char));
420             goto errorExit;
421             }
422         }
423     strcat(printString, tempStr);   
424     // printf ("printString(%d) -> \"%s\"\n", printStringSize, printString);
425     return (NO_ERROR);
426     
427     errorExit:
428         return (ERROR);
429 }
430
431
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)
434 {
435     int     i, j, k, longestLine;
436     BitsLong    lastBlock;
437     char    *word, *s, *lineBuf;
438     FILE    *fp;
439     Tree    *t;
440     char    *tempStr;
441     int     tempStrSize = TEMPSTRSIZE;
442
443     if (from > to)
444         return (NO_ERROR);
445
446 #   if defined (MPI_ENABLED)
447     if (proc_id != 0)
448         return (NO_ERROR);
449 #   endif
450
451     tempStr = (char *) SafeMalloc((size_t)tempStrSize * sizeof(char));
452     if (!tempStr)
453         {
454         MrBayesPrint ("%s   Problem allocating tempString (%d)\n", spacer, tempStrSize * sizeof(char));
455         return (ERROR);
456         }
457
458     for (i=0; i<numTopologies; i++)
459         {
460         t = chainParams.dtree;
461
462         for (j=0; j<chainParams.numRuns; j++)
463             {
464             if (numPrintTreeParams == 1)
465                 {
466                 if (chainParams.numRuns == 1)
467                     SafeSprintf (&tempStr, &tempStrSize, "%s.t", chainParams.chainFileName);
468                 else
469                     SafeSprintf (&tempStr, &tempStrSize, "%s.run%d.t", chainParams.chainFileName, j+1);
470                 }
471             else
472                 {
473                 if (chainParams.numRuns == 1)
474                     SafeSprintf (&tempStr, &tempStrSize, "%s.tree%d.t", chainParams.chainFileName, i+1);
475                 else
476                     SafeSprintf (&tempStr, &tempStrSize, "%s.tree%d.run%d.t", chainParams.chainFileName, i+1, j+1);
477                 }
478
479             if ((fp = OpenBinaryFileR (tempStr)) == NULL) 
480                 {
481                 MrBayesPrint ("%s   Problem openning file %s.\n", spacer, tempStr);
482                 free (tempStr);
483                 return (ERROR);
484                 }
485
486             longestLine = LongestLine (fp);
487             SafeFclose (&fp);
488
489             if ((fp = OpenTextFileR (tempStr)) == NULL) 
490                 {
491                 free (tempStr);
492                 return (ERROR);
493                 }
494
495             lineBuf = (char *) SafeCalloc (longestLine + 10, sizeof (char));
496             if (!lineBuf)
497                 {
498                 SafeFclose (&fp);
499                 free (tempStr);
500                 return (ERROR);
501                 }
502
503             lastBlock = LastBlock (fp, lineBuf, longestLine);
504             fseek (fp, lastBlock, SEEK_SET);
505
506             for (k=1; k<=to; k++)
507                 {
508                 do {
509                     if (fgets (lineBuf, longestLine, fp) == NULL) 
510                         {
511                         SafeFclose (&fp);
512                         free (lineBuf);
513                         free (tempStr);
514                         return ERROR;
515                         }
516                     word = strtok (lineBuf, " ");
517                     } while (strcmp (word, "tree") != 0);
518                 if (k>=from)
519                     {
520                     s = strtok (NULL, ";");
521                     while (*s != '(')
522                         s++;
523                     StripComments(s);
524                     if (ResetTopology (t, s) == ERROR)
525                         {
526                         SafeFclose (&fp);
527                         free (lineBuf);
528                         free (tempStr);
529                         return ERROR;
530                         }
531                     if (AddTreeToPartitionCounters (t, i, j) == ERROR)
532                         {
533                         SafeFclose (&fp);
534                         free (lineBuf);
535                         free (tempStr);
536                         return ERROR;
537                         }
538                     if (saveToList == YES)
539                         if (AddToTreeList(&chainParams.treeList[numTopologies*j+i],t) == ERROR)
540                             return (ERROR);
541                     }
542                 }
543             SafeFclose (&fp);
544             free (lineBuf);
545             } /* next run */
546         } /* next tree */
547     free (tempStr);
548     return (NO_ERROR);
549 }
550
551
552 /* AddTreeToPartitionCounters: Break a tree into partitions and add those to counters */
553 int AddTreeToPartitionCounters (Tree *tree, int treeId, int runId)
554 {
555     int         i, j, nTaxa;
556     TreeNode    *p;
557
558     if (tree->isRooted == YES)
559         nTaxa = tree->nNodes - tree->nIntNodes - 1;
560     else
561         nTaxa = tree->nNodes - tree->nIntNodes;
562
563     for (i=0; i<nTaxa; i++)
564         {
565         ClearBits(partition[i], nLongsNeeded);
566         SetBit(i, partition[i]);
567         }
568
569     for (i=0; i<tree->nIntNodes-1; i++)
570         {
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++)
574             {
575             partition[p->index][j] = partition[p->left->index][j] | partition[p->right->index][j];
576             }
577
578         if ((partFreqTreeRoot[treeId] = AddPartition (partFreqTreeRoot[treeId], partition[p->index], runId)) == NULL)
579             {
580             MrBayesPrint ("%s   Could not allocate space for new partition in AddTreeToPartitionCounters\n", spacer);
581             return ERROR;
582             }
583         }
584
585     return NO_ERROR;
586 }
587
588
589 int AttemptSwap (int swapA, int swapB, RandLong *seed)
590 {
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;
594     ModelInfo       *m;
595     Tree            *tree;
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;
600     MrBFlt          swapRan;
601     MPI_Status      status[2];
602     MPI_Request     request[2];
603 #   endif
604
605 #   if defined (MPI_ENABLED)
606
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);
610
611 #   endif
612
613     /* are we using character reweighting? */
614     reweightingChars = NO;
615     if ((chainParams.weightScheme[0] + chainParams.weightScheme[1]) > 0.00001)
616         reweightingChars = YES;
617             
618 #   if defined (MPI_ENABLED)
619
620     /* figure out processors involved in swap */
621     lower = upper = 0;
622     for (proc=0; proc<num_procs; proc++)
623         {
624         /* assign or increment chain id */
625         if (proc < (chainParams.numChains * chainParams.numRuns) % num_procs)
626             upper += numChainsForProc+1;
627         else
628             upper += numChainsForProc;
629
630         /* if swapA lies between lower and upper
631             * chain id's we know that this is the proc
632             * swapA is in */
633         if (swapA >= lower && swapA < upper)
634             {
635             procIdForA = proc;
636             whichElementA = swapA - lower;
637             }
638         if (swapB >= lower && swapB < upper)
639             {
640             procIdForB = proc;
641             whichElementB = swapB - lower;
642             }
643         lower = upper;
644         }
645
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              */
650
651     /* figure out if I am involved in the swap */
652     doISwap = areWeA = NO;
653     if (proc_id == procIdForA)
654         {
655         doISwap = YES;
656         areWeA = YES;
657         }
658     else if (proc_id == procIdForB)
659         {
660         doISwap = YES;
661         }
662
663     /* chain's that do not swap, continue to the next iteration */  
664     if (doISwap == YES)
665         {
666         
667         /* no need to communicate accross processors if swapping chains are in the same proc */
668         if (procIdForA == procIdForB)
669             {
670             if (reweightingChars == YES)
671                 {
672                 /* use character reweighting */
673                 lnLikeStateAonDataB = 0.0;
674                 for (d=0; d<numCurrentDivisions; d++)
675                     {
676                     m = &modelSettings[d];
677                     tree = GetTree(m->brlens, whichElementA, state[whichElementA]);
678                     lnL = 0.0;
679                     m->Likelihood (tree->root->left, d, whichElementA, &lnL, chainId[whichElementB] % chainParams.numChains);
680                     lnLikeStateAonDataB += lnL;
681                     }
682                 lnLikeStateBonDataA = 0.0;
683                 for (d=0; d<numCurrentDivisions; d++)
684                     {
685                     m = &modelSettings[d];
686                     tree = GetTree(m->brlens, whichElementB, state[whichElementB]);
687                     lnL = 0.0;
688                     m->Likelihood (tree->root->left, d, whichElementB, &lnL, chainId[whichElementA] % chainParams.numChains);
689                     lnLikeStateBonDataA += lnL;
690                     }
691                 }
692
693             /*curLnPr[whichElementA] = LogPrior(whichElementA);
694             curLnPr[whichElementB] = LogPrior(whichElementB);*/
695
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)
702                 {
703                 lnLikeA *= powerSS;
704                 lnLikeB *= powerSS;
705                 }
706             lnPriorA = curLnPr[whichElementA];
707             lnPriorB = curLnPr[whichElementB];
708             if (reweightingChars == YES)
709                 {
710                 if (chainParams.isSS == YES)
711                     lnR = (tempB * (lnLikeStateAonDataB*powerSS + lnPriorA) + tempA * (lnLikeStateBonDataA*powerSS + lnPriorB)) - (tempA * (lnLikeA + lnPriorA) + tempB * (lnLikeB + lnPriorB));
712                 else
713                     lnR = (tempB * (lnLikeStateAonDataB + lnPriorA) + tempA * (lnLikeStateBonDataA + lnPriorB)) - (tempA * (lnLikeA + lnPriorA) + tempB * (lnLikeB + lnPriorB));
714                 }
715             else
716                 lnR = (tempB * (lnLikeA + lnPriorA) + tempA * (lnLikeB + lnPriorB)) - (tempA * (lnLikeA + lnPriorA) + tempB * (lnLikeB + lnPriorB));
717             if (lnR <  -100.0)
718                 r =  0.0;
719             else if (lnR > 0.0)
720                 r =  1.0;
721             else
722                 r =  exp(lnR);
723
724             isSwapSuccessful = NO;
725             if (RandomNumber(seed) < r)
726                 {
727                 /* swap chain id's (heats) */
728                 tempX = chainId[whichElementA];
729                 chainId[whichElementA] = chainId[whichElementB];
730                 chainId[whichElementB] = tempX;
731                 if (reweightingChars == YES)
732                     {
733                     curLnL[whichElementA] = lnLikeStateAonDataB;
734                     curLnL[whichElementB] = lnLikeStateBonDataA;
735                     }
736                 isSwapSuccessful = YES;
737                 }
738                 
739             chI = chainId[whichElementA];
740             chJ = chainId[whichElementB];
741             if (chainId[whichElementB] < chainId[whichElementA])
742                 {
743                 chI = chainId[whichElementB];
744                 chJ = chainId[whichElementA];
745                 }
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]++;
752             }
753         /* we need to communicate across processors */
754         else
755             {
756             if (reweightingChars == YES)
757                 {
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. */
761                 if (areWeA == YES)
762                     {
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)
767                         {
768                         return (ERROR);
769                         }
770                     ierror = MPI_Irecv (&partnerId, 1, MPI_INT, procIdForB, 0, MPI_COMM_WORLD, &request[1]);
771                     if (ierror != MPI_SUCCESS)
772                         {
773                         return (ERROR);
774                         }
775                     ierror = MPI_Waitall (2, request, status);
776                     if (ierror != MPI_SUCCESS)
777                         {
778                         return (ERROR);
779                         }
780                     for (d=0; d<numCurrentDivisions; d++)
781                         {
782                         m = &modelSettings[d];
783                         tree = GetTree(m->brlens, whichElementA, state[whichElementA]);
784                         lnL = 0.0;
785                         m->Likelihood (tree->root->left, d, whichElementA, &lnL, partnerId);
786                         lnLikeStateAonDataB = lnL;
787                         }
788                     }
789                 else
790                     {
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)
795                         {
796                         return (ERROR);
797                         }
798                     ierror = MPI_Irecv (&partnerId, 1, MPI_INT, procIdForA, 0, MPI_COMM_WORLD, &request[1]);
799                     if (ierror != MPI_SUCCESS)
800                         {
801                         return (ERROR);
802                         }
803                     ierror = MPI_Waitall (2, request, status);
804                     if (ierror != MPI_SUCCESS)
805                         {
806                         return (ERROR);
807                         }
808                     for (d=0; d<numCurrentDivisions; d++)
809                         {
810                         m = &modelSettings[d];
811                         tree = GetTree(m->brlens, whichElementB, state[whichElementB]);
812                         lnL = 0.0;
813                         m->Likelihood (tree->root->left, d, whichElementB, &lnL, partnerId);
814                         lnLikeStateBonDataA = lnL;
815                         }
816                     }
817                 }
818
819             if (areWeA == YES)
820                 {
821                 /*curLnPr[whichElementA] = LogPrior(whichElementA);*/
822
823                 /* we are processor A */
824                 tempIdA = chainId[whichElementA];
825                 lnLikeA = curLnL[whichElementA];
826                 lnPriorA = curLnPr[whichElementA];
827                 swapRan = RandomNumber(seed);
828
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)
835                     {
836                     myStateInfo[2] = lnLikeStateAonDataB;
837                     tempIdB = partnerId;
838                     }
839                     
840                 ierror = MPI_Isend (&myStateInfo, 5, MPI_DOUBLE, procIdForB, 0, MPI_COMM_WORLD, &request[0]);
841                 if (ierror != MPI_SUCCESS)
842                     {
843                     return (ERROR);
844                     }
845                 ierror = MPI_Irecv (&partnerStateInfo, 5, MPI_DOUBLE, procIdForB, 0, MPI_COMM_WORLD, &request[1]);
846                 if (ierror != MPI_SUCCESS)
847                     {
848                     return (ERROR);
849                     }
850                 ierror = MPI_Waitall (2, request, status);
851                 if (ierror != MPI_SUCCESS)
852                     {
853                     return (ERROR);
854                     }
855
856                 lnLikeA = curLnL[whichElementA];
857                 lnLikeB = partnerStateInfo[0];
858                 if (chainParams.isSS == YES)
859                     {
860                     lnLikeA *= powerSS;
861                     lnLikeB *= powerSS;
862                     }
863                 lnPriorA = curLnPr[whichElementA];
864                 lnPriorB = partnerStateInfo[1];
865                 if (reweightingChars == YES)
866                     lnLikeStateBonDataA = partnerStateInfo[2];
867                 else
868                     tempIdB = partnerStateInfo[2];
869                 
870                 tempA = Temperature (tempIdA);
871                 tempB = Temperature (tempIdB);
872
873                 if (reweightingChars == YES)
874                     {
875                     if (chainParams.isSS == YES)
876                         lnR = (tempB * (lnLikeStateAonDataB*powerSS + lnPriorA) + tempA * (lnLikeStateBonDataA*powerSS + lnPriorB)) - (tempA * (lnLikeA + lnPriorA) + tempB * (lnLikeB + lnPriorB));
877                     else
878                         lnR = (tempB * (lnLikeStateAonDataB + lnPriorA) + tempA * (lnLikeStateBonDataA + lnPriorB)) - (tempA * (lnLikeA + lnPriorA) + tempB * (lnLikeB + lnPriorB));
879                     }
880                 else
881                     lnR = (tempB * (lnLikeA + lnPriorA) + tempA * (lnLikeB + lnPriorB)) - (tempA * (lnLikeA + lnPriorA) + tempB * (lnLikeB + lnPriorB));
882                 if (lnR < -100.0)
883                     r = 0.0;
884                 else if (lnR > 0.0)
885                     r = 1.0;
886                 else
887                     r = exp(lnR);
888
889                 /* process A's random number is used to make the swap decision */
890                 isSwapSuccessful = NO;
891                 if (swapRan < r)
892                     {
893                     /* swap chain id's (heats) */
894                     isSwapSuccessful = YES;
895                     tempIdMy = chainId[whichElementA];
896                     procIdPartner = procIdForB;
897
898                     if (reweightingChars == YES)
899                         chainId[whichElementA] = tempIdB;
900                     else
901                         chainId[whichElementA] = (int)(partnerStateInfo[2]);
902                     if (reweightingChars == YES)
903                         {
904                         curLnL[whichElementA] = lnLikeStateAonDataB;
905                         }
906                     }
907                     
908                 /* only processor A keeps track of the swap success/failure */
909                 chI = tempIdA;
910                 chJ = tempIdB;
911                 if (tempIdB < tempIdA)
912                     {
913                     chI = tempIdB;
914                     chJ = tempIdA;
915                     }
916                 runId = chI / chainParams.numChains;
917                 chI = chI % chainParams.numChains;
918                 chJ = chJ % chainParams.numChains;
919                 swapInfo[runId][chJ][chI]++;
920                 if (isSwapSuccessful == YES)
921                     {
922                     swapInfo[runId][chI][chJ]++;
923                     /* exchange the move info */
924                     for (i=0; i<numUsedMoves; i++)
925                         {
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];
934                         else
935                             myStateInfo[6] = 0.0;
936
937                         ierror = MPI_Isend (&myStateInfo, 7, MPI_DOUBLE, procIdForB, 0, MPI_COMM_WORLD, &request[0]);
938                         if (ierror != MPI_SUCCESS)
939                             {
940                             return (ERROR);
941                             }
942                         ierror = MPI_Irecv (&partnerStateInfo, 7, MPI_DOUBLE, procIdForB, 0, MPI_COMM_WORLD, &request[1]);
943                         if (ierror != MPI_SUCCESS)
944                             {
945                             return (ERROR);
946                             }
947                         ierror = MPI_Waitall (2, request, status);
948                         if (ierror != MPI_SUCCESS)
949                             {
950                             return (ERROR);
951                             }
952
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];
961
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;
970                 
971                         }
972                     }
973                 }
974             else
975                 {
976                 /*curLnPr[whichElementB] = LogPrior(whichElementB);*/
977
978                 /* we are processor B */
979                 tempIdB  = chainId[whichElementB];
980                 lnLikeB  = curLnL[whichElementB];
981                 lnPriorB = curLnPr[whichElementB];
982                 swapRan  = -1.0;
983
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)
990                     {
991                     myStateInfo[2] = lnLikeStateBonDataA;
992                     tempIdA = partnerId;
993                     }
994
995                 ierror = MPI_Isend (&myStateInfo, 5, MPI_DOUBLE, procIdForA, 0, MPI_COMM_WORLD, &request[0]);
996                 if (ierror != MPI_SUCCESS)
997                     {
998                     return (ERROR);
999                     }
1000                 ierror = MPI_Irecv (&partnerStateInfo, 5, MPI_DOUBLE, procIdForA, 0, MPI_COMM_WORLD, &request[1]);
1001                 if (ierror != MPI_SUCCESS)
1002                     {
1003                     return (ERROR);
1004                     }
1005                 ierror = MPI_Waitall (2, request, status);
1006                 if (ierror != MPI_SUCCESS)
1007                     {
1008                     return (ERROR);
1009                     }
1010
1011                 lnLikeB = curLnL[whichElementB];
1012                 lnLikeA = partnerStateInfo[0];
1013                 lnPriorB = curLnPr[whichElementB];
1014                 lnPriorA = partnerStateInfo[1];
1015                 if (reweightingChars == YES)
1016                     lnLikeStateAonDataB = partnerStateInfo[2];
1017                 else
1018                     tempIdA = partnerStateInfo[2];
1019
1020                 tempB = Temperature (tempIdB);
1021                 tempA = Temperature (tempIdA);
1022
1023                 if (chainParams.isSS == YES)
1024                     {
1025                     lnLikeA *= powerSS;
1026                     lnLikeB *= powerSS;
1027                     }
1028
1029                 if (reweightingChars == YES)
1030                     {
1031                     if (chainParams.isSS == YES)
1032                         lnR = (tempB * (lnLikeStateAonDataB*powerSS + lnPriorA) + tempA * (lnLikeStateBonDataA*powerSS + lnPriorB)) - (tempA * (lnLikeA + lnPriorA) + tempB * (lnLikeB + lnPriorB));
1033                     else
1034                         lnR = (tempB * (lnLikeStateAonDataB + lnPriorA) + tempA * (lnLikeStateBonDataA + lnPriorB)) - (tempA * (lnLikeA + lnPriorA) + tempB * (lnLikeB + lnPriorB));
1035                     }
1036                 else
1037                     lnR = (tempB * (lnLikeA + lnPriorA) + tempA * (lnLikeB + lnPriorB)) - (tempA * (lnLikeA + lnPriorA) + tempB * (lnLikeB + lnPriorB));
1038                 if (lnR < -100.0)
1039                     r = 0.0;
1040                 else if (lnR > 0.0)
1041                     r = 1.0;
1042                 else
1043                     r = exp(lnR);
1044
1045                 /* we use process A's random number to make the swap decision */
1046                 isSwapSuccessful = NO;
1047                 if (partnerStateInfo[3] < r)
1048                     {
1049                     isSwapSuccessful = YES;
1050                     tempIdMy = chainId[whichElementB];
1051                     procIdPartner = procIdForA;
1052
1053                     if (reweightingChars == YES)
1054                         chainId[whichElementB] = tempIdA;
1055                     else
1056                         chainId[whichElementB] = (int)(partnerStateInfo[2]);
1057                     if (reweightingChars == YES)
1058                         {
1059                         curLnL[whichElementB] = lnLikeStateBonDataA;
1060                         }
1061                     /* swap the move info */
1062                     for (i=0; i<numUsedMoves; i++)
1063                         {
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];
1072                         else
1073                             myStateInfo[6] = 0.0;
1074
1075                         ierror = MPI_Isend (&myStateInfo, 7, MPI_DOUBLE, procIdForA, 0, MPI_COMM_WORLD, &request[0]);
1076                         if (ierror != MPI_SUCCESS)
1077                             {
1078                             return (ERROR);
1079                             }
1080                         ierror = MPI_Irecv (&partnerStateInfo, 7, MPI_DOUBLE, procIdForA, 0, MPI_COMM_WORLD, &request[1]);
1081                         if (ierror != MPI_SUCCESS)
1082                             {
1083                             return (ERROR);
1084                             }
1085                         ierror = MPI_Waitall (2, request, status);
1086                         if (ierror != MPI_SUCCESS)
1087                             {
1088                             return (ERROR);
1089                             }
1090
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];
1099
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;
1108                         }
1109                     }
1110                 }
1111
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)))
1114                 {
1115                     run = tempIdMy/chainParams.numChains;
1116
1117                     myStateInfo[0] = tempIdMy;
1118                     myStateInfo[1] = marginalLnLSS   [ run ];
1119                     myStateInfo[2] = stepAcumulatorSS[ run ];
1120                     myStateInfo[3] = stepScalerSS    [ run ];
1121
1122                     ierror = MPI_Isend (&myStateInfo, 4, MPI_DOUBLE, procIdPartner, 0, MPI_COMM_WORLD, &request[0]);
1123                     if (ierror != MPI_SUCCESS)
1124                         {
1125                         return (ERROR);
1126                         }
1127
1128                     ierror = MPI_Irecv (&partnerStateInfo, 4, MPI_DOUBLE, procIdPartner, 0, MPI_COMM_WORLD, &request[1]);
1129                     if (ierror != MPI_SUCCESS)
1130                         {
1131                         return (ERROR);
1132                         }
1133                     ierror = MPI_Waitall (2, request, status);
1134                     if (ierror != MPI_SUCCESS)
1135                         {
1136                         return (ERROR);
1137                         }
1138
1139                     /*we swap chains from the same run*/
1140                     assert (run == (int)partnerStateInfo[0]/chainParams.numChains);
1141
1142                     /*If my chain is the cold chain then send current SS values of corresponding run*/
1143                     if (tempIdMy % chainParams.numChains == 0)
1144                         {
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;
1150                         }
1151                     else if ((int)partnerStateInfo[0] % chainParams.numChains == 0)
1152                         {
1153                         marginalLnLSS   [ run ] = (MrBFlt) partnerStateInfo[1];
1154                         stepAcumulatorSS[ run ] = (MrBFlt) partnerStateInfo[2];
1155                         stepScalerSS    [ run ] = (MrBFlt) partnerStateInfo[3];
1156                         }
1157                 }
1158
1159             }
1160         }
1161 #   else
1162     if (reweightingChars == YES)
1163         {
1164         /* use character reweighting */
1165         lnLikeStateAonDataB = 0.0;
1166         for (d=0; d<numCurrentDivisions; d++)
1167             {
1168             m = &modelSettings[d];
1169             tree = GetTree(m->brlens, swapA, state[swapA]);
1170             lnL = 0.0;
1171             m->Likelihood (tree->root->left, d, swapA, &lnL, chainId[swapB] % chainParams.numChains);
1172             lnLikeStateAonDataB += lnL;
1173             }
1174         lnLikeStateBonDataA = 0.0;
1175         for (d=0; d<numCurrentDivisions; d++)
1176             {
1177             m = &modelSettings[d];
1178             tree = GetTree(m->brlens, swapB, state[swapB]);
1179             lnL = 0.0;
1180             m->Likelihood (tree->root->left, d, swapB, &lnL, chainId[swapA] % chainParams.numChains);
1181             lnLikeStateBonDataA += lnL;
1182             }
1183         }
1184
1185     assert (fabs((curLnPr[swapA]-LogPrior(swapA))/curLnPr[swapA]) < 0.0001);
1186     assert (fabs((curLnPr[swapB]-LogPrior(swapB))/curLnPr[swapB]) < 0.0001);
1187
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];
1194
1195     if (chainParams.isSS == YES)
1196         {
1197         lnLikeA *= powerSS;
1198         lnLikeB *= powerSS;
1199         }
1200
1201     if (reweightingChars == YES)
1202         {
1203         if (chainParams.isSS == YES)
1204             lnR = (tempB * (lnLikeStateAonDataB*powerSS + lnPriorA) + tempA * (lnLikeStateBonDataA*powerSS + lnPriorB)) - (tempA * (lnLikeA + lnPriorA) + tempB * (lnLikeB + lnPriorB));
1205         else
1206             lnR = (tempB * (lnLikeStateAonDataB + lnPriorA) + tempA * (lnLikeStateBonDataA + lnPriorB)) - (tempA * (lnLikeA + lnPriorA) + tempB * (lnLikeB + lnPriorB));
1207         }
1208     else
1209         lnR = (tempB * (lnLikeA + lnPriorA) + tempA * (lnLikeB + lnPriorB)) - (tempA * (lnLikeA + lnPriorA) + tempB * (lnLikeB + lnPriorB));
1210     if (lnR < -100.0)
1211         r = 0.0;
1212     else if (lnR > 0.0)
1213         r =  1.0;
1214     else
1215         r =  exp (lnR);
1216
1217     isSwapSuccessful = NO;
1218     if (RandomNumber(seed) < r)
1219         {
1220         tempX = chainId[swapA];
1221         chainId[swapA] = chainId[swapB];
1222         chainId[swapB] = tempX;
1223
1224         if (reweightingChars == YES)
1225             {
1226             curLnL[swapA] = lnLikeStateAonDataB;
1227             curLnL[swapB] = lnLikeStateBonDataA;
1228             }
1229         isSwapSuccessful = YES;
1230         }
1231         
1232     chI = chainId[swapA];
1233     chJ = chainId[swapB];
1234     if (chainId[swapB] < chainId[swapA])
1235         {
1236         chI = chainId[swapB];
1237         chJ = chainId[swapA];
1238         }
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]++;
1245 #   endif
1246     
1247     return (NO_ERROR);
1248 }
1249
1250
1251 /* Autotune Dirichlet move */
1252 void AutotuneDirichlet (MrBFlt acceptanceRate, MrBFlt targetRate, int batch, MrBFlt *alphaPi, MrBFlt minTuning, MrBFlt maxTuning)
1253 {
1254     MrBFlt delta, logTuning, newTuning;
1255
1256     delta = 1.0 / sqrt(batch);
1257     delta = 0.01 < delta ? 0.01 : delta;
1258
1259     logTuning = log(*alphaPi);
1260
1261     if (acceptanceRate > targetRate)
1262         logTuning -= delta;
1263     else
1264         logTuning += delta;
1265
1266     newTuning = exp(logTuning);
1267     if (newTuning > minTuning && newTuning < maxTuning)
1268         *alphaPi = newTuning;
1269 }
1270
1271
1272 /* Autotune multiplier move */
1273 void AutotuneMultiplier (MrBFlt acceptanceRate, MrBFlt targetRate, int batch, MrBFlt *lambda, MrBFlt minTuning, MrBFlt maxTuning)
1274 {
1275     MrBFlt delta, logTuning, newTuning;
1276
1277     delta = 1.0 / sqrt(batch);
1278     delta = 0.01 < delta ? 0.01 : delta;
1279
1280     logTuning = log(*lambda);
1281
1282     if (acceptanceRate > targetRate)
1283         logTuning += delta;
1284     else
1285         logTuning -= delta;
1286
1287     newTuning = exp(logTuning);
1288     if (newTuning > minTuning && newTuning < maxTuning)
1289         *lambda = newTuning;
1290 }
1291
1292
1293 /* Autotune sliding window move */
1294 void AutotuneSlider (MrBFlt acceptanceRate, MrBFlt targetRate, int batch, MrBFlt *width, MrBFlt minTuning, MrBFlt maxTuning)
1295 {
1296     MrBFlt delta, logTuning, newTuning;
1297
1298     delta = 1.0 / sqrt(batch);
1299     delta = 0.01 < delta ? 0.01 : delta;
1300
1301     logTuning = log(*width);
1302
1303     if (acceptanceRate > targetRate)
1304         logTuning += delta;
1305     else
1306         logTuning -= delta;
1307
1308     newTuning = exp(logTuning);
1309     if (newTuning > minTuning && newTuning < maxTuning)
1310         *width = newTuning;
1311 }
1312
1313
1314 void BuildExhaustiveSearchTree (Tree *t, int chain, int nTaxInTree, TreeInfo *tInfo)
1315 {
1316     int         i;
1317     TreeNode    *p, *q, *r;
1318         
1319     if (nTaxInTree == t->nIntNodes + 1) {
1320         
1321         /* Get downpass */
1322         GetDownPass (t);
1323
1324         /* Calculate cost of this tree and add to counter */
1325         tInfo->curScore = GetParsimonyLength (t, chain);
1326         if (tInfo->curScore < tInfo->minScore)
1327             {
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;
1331             }
1332         else
1333             tInfo->totalScore += pow (tInfo->warp/3.0, tInfo->curScore - tInfo->minScore) * pow (1.0-tInfo->warp, tInfo->minScore - tInfo->curScore);
1334     }
1335
1336     else {
1337
1338         /* find node to connect */
1339         q=tInfo->leaf[nTaxInTree];
1340
1341         /* add using this ancestral node */
1342         p=tInfo->vertex[nTaxInTree-1];
1343         q->anc=p;
1344         p->right=q;
1345
1346         for (i=0;i<2*nTaxInTree-1;i++) {
1347             /* find node to connect to */
1348             if (i>=nTaxInTree)
1349                 r=tInfo->vertex[i-nTaxInTree];
1350             else
1351                 r=tInfo->leaf[i];
1352
1353             /* add to this node */
1354             p->left=r;
1355             if (r->anc==NULL)
1356                 p->anc=NULL;
1357             else {
1358                 p->anc=r->anc;
1359                 if (r->anc->left==r)
1360                     r->anc->left=p;
1361                 else
1362                     r->anc->right=p;
1363             }
1364             r->anc=p;
1365
1366             /* next level */
1367             BuildExhaustiveSearchTree (t, chain, nTaxInTree+1, tInfo);
1368
1369             if (tInfo->stopScore > 0.0 && tInfo->totalScore >= tInfo->stopScore)
1370                 return;
1371
1372             /* restore tree before trying next possibility */
1373             r->anc=p->anc;
1374             if (r->anc!=NULL) {
1375                 if (r->anc->left==p)
1376                     r->anc->left=r;
1377                 else
1378                     r->anc->right=r;
1379             }
1380         }
1381     }
1382 }
1383
1384
1385 /*------------------------------------------------------------------
1386 |
1387 |   BuildParsTrees: Fill in trees using random add seq with parsimony
1388 |
1389 ------------------------------------------------------------------*/
1390 int BuildParsTrees (RandLong *seed, int fromChain, int toChain)
1391 {
1392     int         k, chn;
1393     Param       *p, *q;
1394     Tree        *tree;
1395
1396     /* Build starting trees for state 0 */
1397     for (chn=fromChain; chn<toChain; chn++)
1398         {
1399         for (k=0; k<numParams; k++)
1400             {
1401             p = &params[k];
1402             if (p->paramType == P_TOPOLOGY)
1403                 {
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)
1414                     {
1415                     MrBayesPrint ("%s   Tree %s is fixed so a parsimony-based starting tree is not built\n", spacer, p->name);
1416                     return (NO_ERROR);
1417                     }
1418                 /* constrained topology */
1419                 else if (tree->nConstraints > 0)
1420                     {
1421                     MrBayesPrint ("%s   Tree %s is constrained and parsimony-based starting trees are not implemented for constrained trees (yet)\n", spacer, p->name);
1422                     return (NO_ERROR);
1423                     }
1424                 /* random topology */
1425                 else
1426                     {
1427                     if (BuildStepwiseTree (tree, chn, &globalSeed) == ERROR)
1428                         return (ERROR);
1429                     }
1430                 if (InitializeTreeCalibrations (tree) == ERROR)
1431                     return (ERROR);
1432                 FillTopologySubParams(p, chn, 0, seed);
1433                 }
1434             }
1435         }
1436
1437     return (NO_ERROR);
1438 }
1439
1440
1441 /* build (starting) topology stepwise */
1442 int BuildStepwiseTree (Tree *t, int chain, RandLong *seed) {
1443
1444     int         i, j, nTips;
1445     TreeNode    *p, *q, *r;
1446     CLFlt        length;
1447
1448     // Allocate parsimony matrix if not done already
1449
1450     /* get the tips */
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;
1457     }
1458     nTips = j;
1459
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));
1463         j += i;
1464         p = t->allDownPass[i];
1465         t->allDownPass[i] = t->allDownPass[j];
1466         t->allDownPass[j] = p;
1467     }
1468
1469     /* build first tree */
1470     j = 0;
1471     q = t->allDownPass[0];
1472     r = t->allDownPass[1];
1473     p = t->intDownPass[j++];
1474     q->anc   = p;
1475     r->anc   = p;
1476     p->left  = q;
1477     p->right = r;
1478     q = t->allDownPass[nTips-1];
1479     q->anc   = NULL;
1480     q->right = NULL;
1481     q->left = p;
1482     p->anc = q;
1483     t->root = q;
1484
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);
1492         p->left = q;
1493         p->right = r;
1494         p->anc = q->anc;
1495         if (q->anc->left == q)
1496             q->anc->left = p;
1497         else
1498             q->anc->right = p;
1499         q->anc = p;
1500         r->anc = p;
1501     }
1502
1503     /* take care of the root */
1504     if (t->isRooted == YES) {
1505         r = t->root;
1506         q = t->allDownPass[t->nNodes-1];
1507         p = t->intDownPass[j];
1508         q->anc = q->right = NULL;
1509         q->left = p;
1510         p->anc = q;
1511         p->left = r->left;
1512         p->right = r;
1513         p->left->anc = p;
1514         r->left = r->right = NULL;
1515         r->anc = p;
1516         t->root = q;
1517     }
1518     GetDownPass (t);
1519
1520     return (NO_ERROR);
1521 }
1522
1523
1524 /*------------------------------------------------------------------
1525 |
1526 |   CalcLikeAdgamma: calc likelihood for one adgamma correlation HMM
1527 |
1528 -------------------------------------------------------------------*/
1529 int CalcLikeAdgamma (int d, Param *param, int chain, MrBFlt *lnL)
1530 {
1531     int             c, i, j, nRates, posit, lastCharId;
1532     MrBFlt          logScaler, max, prob, *F,
1533                     *oldF, *tempF, fSpace[2][MAX_GAMMA_CATS];
1534     MrBFlt          *rP;
1535     CLFlt           freq, *lnScaler;
1536     ModelInfo       *m;
1537     ModelParams     *mp;
1538     BitsLong        *inHMM;
1539     
1540     /* find nRates for first division in HMM */
1541     m = &modelSettings[d];
1542     mp = &modelParams[d];
1543     nRates = m->numGammaCats;
1544
1545     /* calculate rate category frequencies */
1546     freq = (CLFlt) ((CLFlt) 1.0 / nRates);
1547
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++];
1553     
1554     /* precalculate Markov trans probs up to largest small jump */
1555     /* but only if needed                                       */
1556     for (i=1; i<MAX_SMALL_JUMP; i++)
1557         {
1558         if (hasMarkovTi[i] == YES)
1559             {
1560             if (hasMarkovTi[i-1] == YES || i == 1)
1561                 MultiplyMatrices(nRates, markovTi[i-1], markovTi[0], markovTi[i]);
1562             else
1563                 MultiplyMatrixNTimes(nRates, markovTi[0], i+1, markovTi[i]);
1564             }
1565         }
1566         
1567     /* find site scaler for this chain and state */
1568     lnScaler = m->scalers[m->siteScalerIndex[chain]];
1569     
1570     /* find rate probs for this chain and state */
1571     rP = rateProbs[chain] + state[chain] * rateProbRowSize;
1572
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++)
1576         {
1577         if (modelSettings[param->relParts[i]].shape ==
1578             modelSettings[d].shape)
1579             {
1580             SetBit(param->relParts[i], inHMM);
1581             }
1582         }
1583     
1584     /* Perform the so-called forward algorithm of HMMs  */  
1585     /* set up the space for f(c,i) */
1586     F = fSpace[0];
1587     oldF = fSpace[1];
1588
1589     for (c=0; c<numChar; c++)
1590         {
1591         if (IsBitSet(partitionId[c][partitionNum] - 1, inHMM) == YES)
1592             break;
1593         }
1594
1595     /* fill in fi(0) */
1596     max = 0.0;
1597     m = &modelSettings[partitionId[c][partitionNum] - 1];
1598     posit = m->rateProbStart + (compCharPos[c] - m->compCharStart) * m->numGammaCats;
1599
1600     for (i=0; i<nRates; i++)
1601         {
1602         F[i] = rP[posit++];
1603         if (F[i] > max)
1604             max = F[i];
1605         }
1606
1607     for (i=0; i<nRates; i++)
1608         F[i] /= max;
1609
1610     /* set logscaler to the value from the first character */
1611     logScaler = lnScaler[compCharPos[c]] +  log(max);
1612
1613     /* now step along the sequence to the end */
1614     lastCharId = charInfo[c].charId;
1615     for (c++; c<numChar; c++)
1616         {
1617         /* skip if excluded */
1618         if (charInfo[c].isExcluded == YES)
1619             continue;
1620
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)
1623             continue;
1624         else
1625             lastCharId = charInfo[c].charId;
1626         
1627         /* skip if not in HMM */
1628         if (IsBitSet(partitionId[c][partitionNum] - 1, inHMM) == NO)
1629             continue;
1630         
1631         /* switch F and oldF, since the previous F is now old */
1632         tempF = F;
1633         F = oldF;
1634         oldF = tempF;
1635
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;
1639                 
1640         /* calculate the HMM forward probs fi(x) at site x in HMM */
1641         if (siteJump[c] <= MAX_SMALL_JUMP)
1642             {
1643             max = 0.0;
1644             for (i=0; i<nRates; i++)
1645                 {
1646                 prob = 0.0;
1647                 for (j=0; j<nRates; j++)
1648                     prob += markovTi[siteJump[c]-1][i][j] * oldF[j];
1649                 F[i] = rP[posit++] * prob;
1650                 if (F[i] > max)
1651                     max = F[i];
1652                 }
1653             }
1654         else if (siteJump[c] < BIG_JUMP)    /* intermediate jump, calculate trans probs */
1655             {
1656             MultiplyMatrixNTimes(nRates, markovTi[0], siteJump[c], markovTiN);
1657             max = 0.0;
1658             for (i=0; i<nRates; i++)
1659                 {
1660                 prob = 0.0;
1661                 for (j=0; j<nRates; j++)
1662                     prob += markovTiN[i][j] * oldF[j];
1663                 F[i] = rP[posit++] * prob;
1664                 if (F[i] > max)
1665                     max = F[i];
1666                 }
1667             }
1668         else    /* big jump, use stationary freqs */
1669             {
1670             max = 0.0;
1671             for (i=0; i<nRates; i++)
1672                 {
1673                 prob = 0.0;
1674                 for (j=0; j<nRates; j++)
1675                     prob += (oldF[j] / freq);
1676                 F[i] = rP[posit++] * prob;
1677                 if (F[i] > max)
1678                     max = F[i];
1679                 }
1680             }
1681
1682         /* rescale and adjust total scaler with HMM scaler and site scaler */
1683         for (i=0; i<nRates; i++)
1684             F[i] /= max;
1685
1686         logScaler += lnScaler[compCharPos[c]] +  log(max);
1687
1688         }
1689     
1690     /* now pull the rate probs together at the end, F contains the vals needed */
1691     prob =  0.0;
1692     for (i=0; i<nRates; i++)
1693         prob += (freq * F[i]);
1694
1695     (*lnL) = logScaler +  log(prob);
1696
1697     free (inHMM);
1698
1699     return (NO_ERROR);
1700 }
1701
1702
1703 /* CalcPartFreqStats: Calculate standard deviation of partition frequencies */
1704 void CalcPartFreqStats (PFNODE *p, STATS *stat)
1705 {
1706     int     i, j, n, min;
1707     MrBFlt  f, sum, sumsq, stdev;
1708
1709     n = chainParams.numRuns;
1710     min = (int)(chainParams.minPartFreq * stat->numSamples);
1711     if ((MrBFlt)min != chainParams.minPartFreq * stat->numSamples)
1712         min++;
1713
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);
1719
1720     for (i=0; i<n; i++)
1721         {
1722         if (p->count[i] >= min)
1723             break;
1724         }
1725
1726     if (i == n)
1727         return;
1728
1729     sum = 0.0;
1730     sumsq = 0.0;
1731     for (i=0; i<n; i++)
1732         {
1733         f = (MrBFlt) (p->count[i]) / (MrBFlt) (stat->numSamples);
1734         sum += f;
1735         sumsq += f * f;
1736         }
1737     
1738     f = (sumsq - sum * sum / n) / (n - 1);
1739     if (f < 0.0)
1740         stdev = 0.0;
1741     else
1742         stdev = sqrt (f);
1743     
1744     stat->sum += stdev;
1745     if (stdev > stat->max)
1746         stat->max = stdev;
1747
1748     stat->numPartitions++;
1749
1750     if (chainParams.allComps == YES)
1751         {
1752         for (i=0; i<n; i++)
1753             {
1754             for (j=i+1; j<n; j++)
1755                 {
1756                 if (p->count[i] < min && p->count[j] < min)
1757                     continue;
1758
1759                 sum = 0.0;
1760                 sumsq = 0.0;
1761
1762                 f = (MrBFlt) (p->count[i]) / (MrBFlt) (stat->numSamples);
1763                 sum += f;
1764                 sumsq += f * f;
1765                 
1766                 f = (MrBFlt) (p->count[j]) / (MrBFlt) (stat->numSamples);
1767                 sum += f;
1768                 sumsq += f * f;
1769
1770                 f = (sumsq - sum * sum / 2.0);
1771                 if (f < 0.0)
1772                     stdev = 0.0;
1773                 else
1774                     stdev = sqrt (f);
1775                 
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;
1780                 stat->pair[j][i]++;
1781                 }
1782             }
1783         }
1784 }
1785
1786
1787 /*----------------------------------------------------------------
1788 |
1789 |   CalcTopoConvDiagn: Calculate average and max standard deviation
1790 |                 in clade credibility (partition frequency) values
1791 |
1792 ----------------------------------------------------------------*/
1793 void CalcTopoConvDiagn (int numSamples)
1794 {
1795     int     i, j, n;
1796     STATS   *stat;
1797     
1798     for (n=0; n<numTopologies; n++)
1799         {
1800         stat = &chainParams.stat[n];
1801         stat->numSamples = numSamples;
1802         stat->numPartitions = 0.0;
1803         stat->sum = 0.0;
1804         stat->max = 0.0;
1805
1806         if (chainParams.allComps == YES)
1807             {
1808             for (i=0; i<chainParams.numRuns; i++)
1809                 for (j=0; j<chainParams.numRuns; j++)
1810                     stat->pair[i][j] = 0.0;
1811             }
1812     
1813         CalcPartFreqStats (partFreqTreeRoot[n], stat);
1814         
1815         stat->avgStdDev = stat->sum / stat->numPartitions;
1816         }
1817 }
1818
1819
1820 /* used in DoCompRefTree */
1821 void PartFreq (PFNODE *p, STATS *stat, int *ntrees)
1822 {
1823     int     i, n = chainParams.numRuns;
1824     MrBFlt  f, sum, sumsq, stdev;
1825     
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);
1831     
1832     sum = sumsq = 0.0;
1833     for (i=0; i<chainParams.numRuns; i++)
1834         {
1835         f = (MrBFlt)(p->count[i]) / (MrBFlt)ntrees[i];
1836         sum += f;
1837         sumsq += f * f;
1838         }
1839     
1840     f = (sumsq - sum * sum / n) / (n - 1);
1841     if (f < 0.0)
1842         stdev = 0.0;
1843     else
1844         stdev = sqrt (f);
1845     
1846     stat->sum += stdev;
1847     if (stat->max < stdev)
1848         stat->max = stdev;
1849     
1850     stat->numPartitions++;
1851 }
1852 void CalcTopoConvDiagn2 (int *nTrees)
1853 {
1854     int     n;
1855     STATS   *stat;
1856     
1857     for (n=0; n<numTopologies; n++)
1858         {
1859         stat = &chainParams.stat[n];
1860         stat->numPartitions = 0.0;
1861         stat->sum = stat->max = 0.0;
1862     
1863         PartFreq (partFreqTreeRoot[n], stat, nTrees);
1864         
1865         stat->avgStdDev = stat->sum / stat->numPartitions;
1866         }
1867 }
1868
1869
1870 int CheckTemperature (void)
1871 {
1872     if (chainParams.userDefinedTemps == YES)
1873             {
1874           if (AreDoublesEqual(chainParams.userTemps[0], 1.0, ETA)==NO)
1875             {
1876             MrBayesPrint ("%s   The first user-defined temperature must be 1.0.\n", spacer);
1877             return (ERROR);
1878             }
1879         }
1880
1881     return (NO_ERROR);
1882 }
1883
1884
1885 void CloseMBPrintFiles (void)
1886 {
1887     int     i, n;
1888
1889 #   if defined (MPI_ENABLED)
1890     if (proc_id != 0)
1891         return;
1892 #   endif
1893
1894     for (n=0; n<chainParams.numRuns; n++)
1895         {
1896         SafeFclose (&fpParm[n]);
1897 #if defined (PRINT_DUMP)
1898         SafeFclose (&fpDump[n]);
1899 #endif
1900
1901         for (i=0; i<numTrees; i++)
1902             {
1903             if (fpTree[n][i])
1904                 {
1905                 fprintf (fpTree[n][i], "end;\n");
1906                 SafeFclose (&fpTree[n][i]);
1907                 }
1908             }
1909         }
1910
1911     if (chainParams.mcmcDiagn == YES)
1912         SafeFclose (&fpMcmc);
1913
1914     if (chainParams.isSS == YES)
1915         SafeFclose (&fpSS);
1916 }
1917
1918
1919 /* CompactTree: prune partition tree */
1920 PFNODE *CompactTree (PFNODE *p)
1921 {
1922     int         i, j;
1923     PFNODE      *q, *r;
1924
1925     if (p == NULL)
1926         return NULL;
1927     
1928     i = j = 0;
1929     if (IsPFNodeEmpty(p) == YES)
1930         {
1931         /* steal info from terminal on the way up */
1932         q = SmallestNonemptyPFNode (p->left, &i, 0);
1933         r = LargestNonemptyPFNode (p->right, &j, 0);
1934
1935         if (q != NULL || r != NULL)
1936             {
1937             if (i < j)
1938                 q = r;
1939         
1940             for (i=0; i<chainParams.numRuns; i++)
1941                 {
1942                 p->count[i] = q->count[i];
1943                 q->count[i] = 0;
1944                 }
1945             for (i=0; i<nLongsNeeded; i++)
1946                 p->partition[i] = q->partition[i];
1947             }
1948         }
1949
1950     p->left = CompactTree (p->left);
1951     p->right = CompactTree (p->right);
1952
1953     /* delete on the way down if empty */
1954     if (IsPFNodeEmpty(p) == YES)
1955         {
1956         Tfree (p);
1957         return NULL;
1958         }
1959     else
1960         return p;
1961 }
1962
1963
1964 /*-----------------------------------------------------------------
1965 |
1966 |   CopyParams: copy parameters of touched divisions
1967 |
1968 -----------------------------------------------------------------*/
1969 void CopyParams (int chain)
1970 {
1971     int         i, j, k, fromState, toState, *fromInt, *toInt;
1972     MrBFlt      *from, *to;
1973     ModelInfo   *m;
1974     Param       *p;
1975
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++)
1980         {
1981         p = &params[i];
1982
1983         from = GetParamVals (p, chain, state[chain]);
1984         to = GetParamVals (p, chain, (state[chain] ^ 1));
1985
1986         for (j=0; j<p->nValues; j++)
1987             to[j] = from[j];
1988
1989         from = GetParamSubVals (p, chain, state[chain]);
1990         to = GetParamSubVals (p, chain, (state[chain] ^ 1));
1991
1992         for (j=0; j<p->nSubValues; j++)
1993             to[j] = from[j];
1994
1995         fromInt = GetParamIntVals (p, chain, state[chain]);
1996         toInt = GetParamIntVals (p, chain, (state[chain] ^ 1));
1997
1998         for (j=0; j<p->nIntValues; j++)
1999             toInt[j] = fromInt[j];
2000
2001         if (p->nStdStateFreqs > 0)
2002             {
2003             from = GetParamStdStateFreqs (p, chain, state[chain]);
2004             to = GetParamStdStateFreqs (p, chain, state[chain] ^ 1);
2005             for (j=0; j<p->nStdStateFreqs; j++)
2006                 to[j] = from[j];
2007             }
2008
2009         if (p->paramType == P_CPPEVENTS)
2010             {
2011             fromState = 2*chain + state[chain];
2012             toState   = 2*chain + (state[chain] ^ 1);
2013             for (j=0; j<2*numLocalTaxa-2; j++)
2014                 {
2015                 if (p->nEvents[toState][j] != p->nEvents[fromState][j])
2016                     {
2017                     if (p->nEvents[fromState][j] == 0)
2018                         {
2019                         free (p->position[toState][j]);
2020                         p->position[toState][j] = NULL;
2021                         free (p->rateMult[toState][j]);
2022                         p->rateMult[toState][j] = NULL;
2023                         }
2024                     else if (p->nEvents[toState][j] == 0)
2025                         {
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));
2028                         }
2029                     else
2030                         {
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));
2033                         }
2034                     p->nEvents[toState][j] = p->nEvents[fromState][j];
2035                     }
2036                 if (p->nEvents[fromState][j] > 0)
2037                     {
2038                     for (k=0; k<p->nEvents[fromState][j]; k++)
2039                         {
2040                         p->position[toState][j][k] = p->position[fromState][j][k];
2041                         p->rateMult[toState][j][k] = p->rateMult[fromState][j][k];
2042                         }
2043                     }
2044                 }
2045             }
2046         }
2047
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++)
2053         {
2054         m = &modelSettings[i];
2055         m->lnLike[toState] = m->lnLike[fromState];
2056         if (m->parsModelId == YES)
2057             m->parsTreeLength[toState] = m->parsTreeLength[fromState];
2058         m->upDateCl = NO;
2059         m->upDateCijk = NO;
2060         m->upDateAll = NO;
2061         }
2062         
2063     return;
2064 }
2065
2066
2067 /* CopySiteScalers: Copy site scalers from scratch space into current space */
2068 void CopySiteScalers (ModelInfo *m, int chain)
2069 {
2070     CLFlt       *from, *to;
2071 #   if defined (BEAGLE_ENABLED)
2072     int         i, j;
2073 #   endif
2074
2075 #   if defined (BEAGLE_ENABLED)
2076     if (m->useBeagle == YES)
2077         {
2078         j = m->siteScalerScratchIndex;
2079         for (i=0; i<m->nCijkParts; i++)
2080             {
2081             beagleResetScaleFactors (m->beagleInstance,
2082                                      m->siteScalerIndex[chain] + i);
2083             beagleAccumulateScaleFactors (m->beagleInstance,
2084                                           &j,
2085                                           1,
2086                                           m->siteScalerIndex[chain] + i);
2087             j++;
2088             }
2089         return;
2090         }
2091 #   endif
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));
2095 }
2096
2097
2098 /*-----------------------------------------------------------------
2099 |
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
2104 |
2105 -----------------------------------------------------------------*/
2106 void CopyTrees (int chain)
2107 {
2108     int         i, j, n, nTaxa, nLongsNeeded;
2109     TreeNode    *p, *q;
2110     Tree        *from, *to;
2111
2112     /* reset division update flags */
2113     for (i=0; i<numCurrentDivisions; i++)
2114         modelSettings[i].upDateCl = NO;
2115
2116     for (n=0; n<numTrees; n++)
2117         {
2118         from = GetTreeFromIndex (n, chain, state[chain]);       
2119         to = GetTreeFromIndex (n, chain, (state[chain] ^ 1));
2120         if (from->bitsets != NULL && to->bitsets != NULL)
2121             {
2122             if (from->isRooted == NO)
2123                 nTaxa = from->nNodes - from->nIntNodes;
2124             else
2125                 nTaxa = from->nNodes - from->nIntNodes - 1;
2126             nLongsNeeded = (int)((nTaxa - 1) / nBitsInALong) + 1;
2127             }
2128         else
2129             nLongsNeeded = 0;
2130
2131         /* copy nodes */
2132         for (j=0; j<from->nNodes; j++)
2133             {
2134             /* copy pointers */
2135             p  = from->nodes + j;
2136             q  = to->nodes + j;
2137
2138             if (p->anc != NULL)
2139                 q->anc = to->nodes + p->anc->memoryIndex;
2140             else
2141                 q->anc = NULL;
2142
2143             if (p->left != NULL)    
2144                 q->left = to->nodes + p->left->memoryIndex;
2145             else
2146                 q->left = NULL;
2147
2148             if (p->right != NULL)   
2149                 q->right = to->nodes + p->right->memoryIndex;
2150             else
2151                 q->right = NULL;
2152
2153             CopyTreeNodes (q, p, nLongsNeeded);
2154             q->upDateCl = q->upDateTi = NO;     /* reset update flags */
2155             }
2156         
2157         for (i=0; i<from->nIntNodes; i++)
2158             {
2159             to->intDownPass[i] = to->nodes + from->intDownPass[i]->memoryIndex;
2160             }
2161         for (i=0; i<from->nNodes; i++)
2162             {
2163             to->allDownPass[i] = to->nodes + from->allDownPass[i]->memoryIndex;
2164             }
2165
2166         to->root = to->nodes + from->root->memoryIndex;
2167
2168         /* rest of tree info is constant and need not be copied */
2169         }
2170     
2171     return;
2172 }
2173
2174
2175 #ifdef VISUAL
2176 BOOL WINAPI CatchInterrupt (DWORD signum)
2177 {
2178     /* set up signal handler to do the same */
2179     MrBayesPrint ("\n   Ctrl-C detected\n");
2180     requestAbortRun = YES;
2181     return TRUE;
2182 }
2183 #else
2184 void CatchInterrupt (int signum)
2185 {
2186     /* set up signal handler to do the same */
2187     signal (signum, CatchInterrupt);
2188     requestAbortRun = YES;
2189     MrBayesPrint ("\n   Ctrl-C detected\n");
2190 }
2191 #endif
2192
2193
2194 /*----------------------------------------------------------------
2195 |
2196 |   DebugNodeScalers: Calculate node scalers sum
2197 |
2198 -----------------------------------------------------------------*/
2199 CLFlt DebugNodeScalers (TreeNode *p, int division, int chain)
2200 {
2201     int             c;
2202     CLFlt           *scP;
2203     CLFlt           sum=0.0;
2204     ModelInfo       *m;
2205     
2206     m = &modelSettings[division];
2207
2208     /* find scalers */
2209     scP = m->scalers[m->nodeScalerIndex[chain][p->index]];
2210
2211     /* remove scalers */
2212     for (c=0; c<m->numChars; c++)
2213         sum += scP[c];
2214
2215     return sum;
2216 }
2217
2218
2219 /*----------------------------------------------------------------
2220 |
2221 |   DebugTreeScalers: Calculate DebugNodeScalers for each node and printit
2222 |
2223 -----------------------------------------------------------------*/
2224 void DebugTreeScalers(int chain, int d)
2225 {
2226     int i;
2227     TreeNode        *p;
2228     ModelInfo       *m;
2229     Tree            *tree;
2230     
2231     m = &modelSettings[d];
2232     tree = GetTree(m->brlens, chain, state[chain]);
2233     
2234     if (m->parsModelId == NO)
2235         {
2236         for (i=0; i<tree->nIntNodes; i++)
2237             {
2238             p = tree->intDownPass[i];
2239             
2240             if (p->scalerNode == YES)
2241                 {
2242                 printf ("Node:%d Sum scalers:%f\n",p->index,DebugNodeScalers(p, d, chain));
2243                 }
2244             }
2245         }
2246 }
2247
2248
2249 int DoMcmc (void)
2250 {
2251     RandLong    seed;
2252     int         rc, i, j, run;
2253     char        c;
2254     FILE        *tempFile;
2255     char        temp[20];
2256     char        *strBuf,*tmpcp;
2257     double      tmp;
2258
2259 #   if defined (BEST_MPI_ENABLED)
2260     Tree        *tree;
2261 #   endif
2262
2263 #   if !defined (VISUAL) && !defined (MPI_ENABLED)
2264     sighandler_t sigint_oldhandler, sigterm_oldhandler;
2265 #   endif
2266
2267     numPreviousGen = 0;     /* Make sure this is reset */
2268
2269     /* Check to see that we have a data matrix. Otherwise, the MCMC is rather
2270        pointless. */
2271     if (defMatrix == NO)
2272         {
2273         MrBayesPrint ("%s   A character matrix must be defined first\n", spacer);
2274         goto errorExit;
2275         }
2276
2277     if (setUpAnalysisSuccess == NO)
2278         {
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);
2281         goto errorExit;
2282         }
2283
2284     /* set file names */
2285     sumtParams.numRuns  = chainParams.numRuns;
2286     sumpParams.numRuns  = chainParams.numRuns;
2287     sumssParams.numRuns = chainParams.numRuns;
2288     
2289     if (fileNameChanged == YES)
2290         {
2291         SetFileNames();
2292         fileNameChanged = NO;
2293         }
2294
2295     MrBayesPrint ("%s   Running Markov chain\n", spacer);
2296     
2297     /* Check the chain temperature parameters */
2298     if (CheckTemperature () == ERROR)
2299         goto errorExit;
2300     
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);
2311     if (seed < 0)
2312         seed = -seed;
2313 #   else
2314     seed = globalSeed;
2315 #   endif
2316
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. */
2321     GetStamp ();
2322     
2323     MrBayesPrint ("%s   Seed = %d\n", spacer, seed);
2324     MrBayesPrint ("%s   Swapseed = %d\n", spacer, swapSeed);
2325
2326     /* Show the model to make sure the user sees it before running the analysis */
2327     if (ShowModel() == ERROR)
2328         goto errorExit;
2329     MrBayesPrint ("\n");
2330
2331     /* Warn the user or stop analysis in case the model is strange */
2332     if (CheckModel() == ERROR)
2333         goto errorExit;
2334                 
2335     /* Determine the number of local chains and data splits */
2336     if (SetLocalChainsAndDataSplits() == ERROR)
2337         goto errorExit;
2338
2339     /* Set up the moves to be used */
2340     if (SetUsedMoves () == ERROR)
2341         goto errorExit;
2342
2343     /* Check to see that we have at least one move. Otherwise, the MCMC is rather
2344        pointless. */
2345     if (numUsedMoves == 0)
2346         {
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);
2350         goto errorExit;
2351         }
2352
2353     /* Show summary table of moves that will be used */ 
2354     if (ShowMoveSummary () == ERROR)
2355         goto errorExit;
2356
2357     /* Set the likelihood function pointers. */
2358     if (SetLikeFunctions () == ERROR)
2359         goto errorExit;
2360
2361     /* Set up number of characters of each character pattern. */
2362     if (FillNumSitesOfPat () == ERROR)
2363         goto errorExit;
2364
2365     /* Initialize parsimony sets. */
2366     if (InitParsSets() == ERROR)
2367         goto errorExit;
2368
2369     /* Set up a terminal state index matrix for local compression. */
2370     if (SetUpTermState() == ERROR)
2371         goto errorExit;
2372
2373     /* Initialize conditional likelihoods and transition probabilities for chain (the working space). */
2374     if (InitChainCondLikes () == ERROR)
2375         goto errorExit;
2376
2377     /* Initialize adgamma conditional likelihoods */
2378     if (InitAdGamma () == ERROR)
2379         goto errorExit;
2380     
2381     /* Initialize invariable conditional likelihoods. */
2382     if (InitInvCondLikes() == ERROR)
2383         goto errorExit;
2384
2385     /* Allocate BEST chain variables */
2386     if (numTopologies > 1 && !strcmp(modelParams[0].topologyPr,"Speciestree"))
2387         AllocateBestChainVariables();
2388
2389     /* allocate SS memory for the chains if needed */
2390     if (chainParams.isSS == YES)
2391         {
2392         if (memAllocs[ALLOC_SS] == YES)
2393             {
2394             MrBayesPrint ("%s   SS is already allocated\n", spacer);
2395             goto errorExit;
2396             }
2397         else if ((marginalLnLSS = (MrBFlt *) SafeCalloc (chainParams.numRuns, sizeof(MrBFlt))) == NULL)
2398             {
2399             MrBayesPrint ("%s   Problem allocating marginalLnLSS\n", spacer);
2400             goto errorExit;
2401             }
2402         else if ((stepScalerSS = (MrBFlt *) SafeCalloc (chainParams.numRuns, sizeof(MrBFlt))) == NULL)
2403             {
2404             MrBayesPrint ("%s   Problem allocating stepScalerSS\n", spacer);
2405             free (marginalLnLSS);
2406             goto errorExit;
2407             }
2408         else if ((stepAcumulatorSS = (MrBFlt *) SafeCalloc (chainParams.numRuns, sizeof(MrBFlt))) == NULL)
2409             {
2410             MrBayesPrint ("%s   Problem allocating stepAcumulatorSS\n", spacer);
2411             free (stepScalerSS);
2412             free (marginalLnLSS);
2413             goto errorExit;
2414             }
2415         else if ((splitfreqSS = (MrBFlt *) SafeCalloc (chainParams.numStepsSS*numTopologies, sizeof(MrBFlt))) == NULL)
2416             {
2417             MrBayesPrint ("%s   Problem allocating splitfreqSS\n", spacer);
2418             free (stepScalerSS);
2419             free (marginalLnLSS);
2420             free (stepAcumulatorSS);
2421             goto errorExit;
2422             }
2423         else
2424             memAllocs[ALLOC_SS] = YES;
2425         }
2426
2427     /* Either append to previous run or deal with starting values */
2428     if (chainParams.append == YES)
2429         {
2430         /* Continue old run */
2431        
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)
2437             {
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);
2440             goto errorExit;
2441             }
2442
2443         if (DoExecute () == ERROR)
2444             goto errorExit;
2445
2446         /* Get number of generations to start from and SS information if needed */
2447         temp[0] = '\0';
2448         numPreviousGen = 0;
2449 #   if defined (MPI_ENABLED)
2450         if (proc_id == 0) {
2451 #   endif
2452         tempFile = OpenBinaryFileR (inputFileName);
2453         do { c = fgetc(tempFile);
2454             } while (c!=':' && c!=EOF);
2455         if (c!=EOF)
2456             {
2457             do { c = fgetc(tempFile);
2458                 } while (c!=':' && c!=EOF);
2459             }
2460         if (c!=EOF)
2461             {
2462             do { c = fgetc(tempFile);
2463                 } while (!isdigit(c) && c!=EOF);
2464             }
2465         if (c!=EOF)
2466             {
2467             i=0;
2468             while (c >= '0' && c <= '9' && i < 18)
2469                 {
2470                 temp[i++] = c;
2471                 c = fgetc(tempFile);
2472                 }
2473             temp[i] = '\0';
2474             numPreviousGen = atoi(temp);
2475             }
2476         if (chainParams.isSS==YES && c!=EOF)
2477             {
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)
2482                 {
2483                 MrBayesPrint ("%s   Error: Reading SsAcumulators from .ckp file fails.\n", spacer);
2484                 free(strBuf);
2485                 goto errorExit;
2486                 }
2487
2488             tmpcp=strtok(strBuf," "); 
2489             for (run=0; run<chainParams.numRuns; run++)
2490                 {
2491                 if (tmpcp == NULL)
2492                     {
2493                     MrBayesPrint ("%s   Error: Not enough values in SsAcumulators comment of .ckp file.   \n", spacer);
2494                     free(strBuf);
2495                     goto errorExit;
2496                     }
2497                     
2498                 tmp=atof(tmpcp);
2499                 stepScalerSS[run]=tmp-10;
2500                 stepAcumulatorSS[run]=exp(10);
2501                 tmpcp=strtok(NULL," ]");
2502                 }
2503                       
2504             free(strBuf);
2505             }
2506 #   if defined (MPI_ENABLED)
2507         }
2508         MPI_Bcast (&numPreviousGen, 1, MPI_INT, 0, MPI_COMM_WORLD);
2509 #   endif
2510         if (numPreviousGen == 0)
2511             {
2512             MrBayesPrint ("%s   Could not find the number of generations in previous run.\n", spacer);
2513             goto errorExit;
2514             }
2515         else if (numPreviousGen >= chainParams.numGen)
2516             {
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);
2519             goto errorExit;
2520             }
2521         else
2522             MrBayesPrint ("%s   Using samples up to generation %d from previous analysis.\n", spacer, numPreviousGen);
2523         }
2524     else
2525         {
2526         /* New run */
2527         
2528         /* deal with starting param values */
2529         if (!strcmp(chainParams.startParams,"Reset"))
2530             {
2531             MrBayesPrint ("%s   Resetting starting values for substitution model parameters\n", spacer);
2532             FillNormalParams (&seed, 0, numLocalChains);
2533             }
2534
2535         /* deal with starting treeparam values */
2536         if (!strcmp(chainParams.startTree,"Random"))
2537             {
2538             MrBayesPrint ("%s   Resetting starting trees and tree parameters\n", spacer);
2539             FillTreeParams (&seed, 0, numLocalChains);
2540             }
2541         else if (!strcmp(chainParams.startTree,"Parsimony"))
2542             {
2543             MrBayesPrint ("%s   Rebuilding starting trees using random addition sequences and parsimony\n", spacer);
2544             BuildParsTrees (&seed, 0, numLocalChains);
2545             }
2546
2547         /* Perturb start trees if requested */
2548         if (chainParams.numStartPerts > 0)
2549             {
2550             MrBayesPrint ("%s   Randomly perturbing starting trees\n", spacer);
2551             for (i=0; i<numTrees; i++)
2552                 {
2553                 for (j=0; j<numGlobalChains; j++)
2554                     RandPerturb (GetTreeFromIndex(i, j, 0), chainParams.numStartPerts, &seed);
2555                 }
2556             }
2557         }
2558
2559     /* Set clockRate if we have calibration */
2560     for (j=0; j<numGlobalChains; j++)
2561         {
2562         if (UpdateClockRate(0.0, j) == ERROR) 
2563             goto errorExit;
2564         }
2565     /*
2566     for (i=0; i<numParams; i++)
2567         {
2568         for (j=0; j<numGlobalChains; j++)
2569             assert (IsTreeConsistent(&params[i], j, 0) == YES);
2570         }  */
2571
2572     /* Initialize vectors of print parameters */
2573     if (InitPrintParams () == ERROR)
2574         goto errorExit;
2575     
2576     /*! setup a signal handler to catch interrupts, ignore failure */
2577 #   ifdef VISUAL
2578     SetConsoleCtrlHandler (CatchInterrupt, TRUE);
2579 #   else
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);
2584 #       endif
2585 #   endif
2586     requestAbortRun = NO;
2587
2588     /* Run the Markov chain. */
2589     rc = RunChain (&seed);
2590     if (rc == ERROR)
2591         {
2592 #   ifdef VISUAL
2593         SetConsoleCtrlHandler (CatchInterrupt, FALSE);
2594 #   else
2595 #       if !defined (MPI_ENABLED)
2596         signal(SIGINT, sigint_oldhandler);
2597         signal(SIGTERM, sigterm_oldhandler);
2598 #       endif
2599 #   endif
2600         goto errorExit;
2601         }
2602     else if (rc == ABORT)
2603         {
2604         ResetChainIds();
2605         FreeChainMemory();
2606 #   ifdef VISUAL
2607         SetConsoleCtrlHandler (CatchInterrupt, FALSE);
2608 #   else
2609 #       if !defined (MPI_ENABLED)
2610         signal(SIGINT, sigint_oldhandler);
2611         signal(SIGTERM, sigterm_oldhandler);
2612 #       endif
2613 #   endif
2614         return ABORT;
2615         }
2616         
2617     /*! restore the default signal handler */
2618 #   ifdef VISUAL
2619     SetConsoleCtrlHandler (CatchInterrupt, FALSE);
2620 #   else
2621 #       if !defined (MPI_ENABLED)
2622     signal(SIGINT, sigint_oldhandler);
2623     signal(SIGTERM, sigterm_oldhandler);
2624 #       endif
2625 #   endif
2626
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. */
2629     globalSeed = seed;
2630
2631     /* Free up all memory allocated for the chain. */
2632     FreeChainMemory ();
2633     
2634     return (NO_ERROR);
2635     
2636     errorExit:
2637         FreeChainMemory ();
2638         return (ERROR);
2639 }
2640
2641
2642 int DoMcmcp (void)
2643 {
2644     if (defMatrix == NO)
2645         {
2646         MrBayesPrint ("%s   A character matrix must be defined first\n", spacer);
2647         return (ERROR);
2648         }
2649
2650     sumtParams.numRuns = chainParams.numRuns;
2651     sumpParams.numRuns = chainParams.numRuns;
2652     
2653     if (fileNameChanged == YES)
2654         {
2655         SetFileNames();
2656         fileNameChanged = NO;
2657         }
2658
2659     MrBayesPrint ("%s   Successfully set chain parameters\n", spacer);
2660
2661     return (NO_ERROR);
2662 }
2663
2664
2665 int DoSsParm (char *parmName, char *tkn)
2666 {
2667     int         tempI;
2668     MrBFlt      tempD;
2669     char        tempStr[5];
2670     static int  negBurninss;
2671
2672     if (defMatrix == NO)
2673         {
2674         MrBayesPrint ("%s   A character matrix must be defined first\n", spacer);
2675         return (ERROR);
2676         }
2677
2678     if (expecting == Expecting(PARAMETER))
2679         {
2680         expecting = Expecting(EQUALSIGN);
2681         }
2682     else
2683         {
2684         if (!strcmp(parmName, "Burninss"))
2685             {
2686             if (expecting == Expecting(EQUALSIGN))
2687                 {
2688                 negBurninss = NO;
2689                 expecting = Expecting(NUMBER) | Expecting(DASH);
2690                 }
2691             else if (expecting == Expecting(DASH))
2692                 {
2693                 negBurninss = YES;
2694                 expecting = Expecting(NUMBER);
2695                 }
2696             else if (expecting == Expecting(NUMBER))
2697                 {
2698                 sscanf (tkn, "%d", &tempI);
2699                 if (negBurninss == NO)
2700                     chainParams.burninSS = tempI;
2701                 else
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);
2705                 }
2706             else 
2707                 {
2708                 return (ERROR);
2709                 }         
2710             }
2711         else if (!strcmp(parmName, "Nsteps"))
2712             {
2713             if (expecting == Expecting(EQUALSIGN))
2714                 expecting = Expecting(NUMBER);
2715             else if (expecting == Expecting(NUMBER))
2716                 {
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);
2721                 }
2722             else 
2723                 {
2724                 return (ERROR);
2725                 }                
2726             }
2727         else if (!strcmp(parmName, "FromPrior"))
2728             {
2729             if (expecting == Expecting(EQUALSIGN))
2730                 expecting = Expecting(ALPHA);
2731             else if (expecting == Expecting(ALPHA))
2732                 {
2733                 if (IsArgValid(tkn, tempStr) == NO_ERROR)
2734                     {
2735                     if (!strcmp(tempStr, "Yes"))
2736                         chainParams.startFromPriorSS = YES;
2737                     else
2738                         chainParams.startFromPriorSS = NO;
2739                     }
2740                 else
2741                     {
2742                     MrBayesPrint ("%s   Invalid argument for FromPrior parameter\n", spacer);
2743                     return (ERROR);
2744                     }
2745                 MrBayesPrint ("%s   Setting FromPrior=%s\n", spacer, (chainParams.startFromPriorSS==YES)?"Yes":"No");
2746                 expecting = Expecting(PARAMETER) | Expecting(SEMICOLON);
2747                 }
2748             else 
2749                 {
2750                 return (ERROR);
2751                 }                
2752             }
2753         else if (!strcmp(parmName, "Alpha"))
2754             {
2755             if (expecting == Expecting(EQUALSIGN))
2756                 expecting = Expecting(NUMBER);
2757             else if (expecting == Expecting(NUMBER))
2758                 {
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);
2763                 }
2764             else 
2765                 {
2766                 return (ERROR);
2767                 }                
2768             }
2769         else
2770             {
2771             return (ERROR);
2772             }
2773         }
2774     return (NO_ERROR);
2775 }
2776
2777
2778 int DoMcmcParm (char *parmName, char *tkn)
2779 {
2780     int         tempI;
2781     MrBFlt      tempD;
2782     char        *tempStr;
2783     int         tempStrSize = TEMPSTRSIZE;
2784     
2785     tempStr = (char *) SafeMalloc((size_t)tempStrSize * sizeof(char));
2786     if (!tempStr)
2787         {
2788         MrBayesPrint ("%s   Problem allocating tempString (%d)\n", spacer, tempStrSize * sizeof(char));
2789         return (ERROR);
2790         }
2791     *tempStr='\0';
2792
2793     if (defMatrix == NO)
2794         {
2795         MrBayesPrint ("%s   A character matrix must be defined first\n", spacer);
2796         return (ERROR);
2797         }
2798
2799     if (expecting == Expecting(PARAMETER))
2800         {
2801         expecting = Expecting(EQUALSIGN);
2802         }
2803     else
2804         {
2805         /* set Seed (globalSeed) ***************************************************************/
2806         if (!strcmp(parmName, "Seed"))
2807             {
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);
2810                 free (tempStr);
2811                 return (ERROR);
2812             /*
2813             if (expecting == Expecting(EQUALSIGN))
2814                 expecting = Expecting(NUMBER);
2815             else if (expecting == Expecting(NUMBER))
2816                 {
2817                 sscanf (tkn, "%d", &tempI);
2818                 globalSeed = tempI;
2819                 MrBayesPrint ("%s   Setting seed to %ld\n", spacer, globalSeed);
2820                 expecting = Expecting(PARAMETER) | Expecting(SEMICOLON);
2821                 }
2822             else 
2823                 {
2824                 free (tempStr);
2825                 return (ERROR);
2826                 }
2827                 */
2828             }
2829         /* set Swapseed (global variable swapSeed) ***************************************************************/
2830         else if (!strcmp(parmName, "Swapseed"))
2831             {
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);
2834                 free (tempStr);
2835                 return (ERROR);
2836                 /*
2837             if (expecting == Expecting(EQUALSIGN))
2838                 expecting = Expecting(NUMBER);
2839             else if (expecting == Expecting(NUMBER))
2840                 {
2841                 sscanf (tkn, "%d", &tempI);
2842                 swapSeed = tempI;
2843                 MrBayesPrint ("%s   Setting swapseed to %ld\n", spacer, swapSeed);
2844                 expecting = Expecting(PARAMETER) | Expecting(SEMICOLON);
2845                 }
2846             else
2847                 {
2848                 free (tempStr);
2849                 return (ERROR);
2850                 }
2851                 */
2852             }
2853         /* set run ID */
2854         /* this setting is provided for GRID use only, so that identical runs can be generated */
2855         else if (!strcmp(parmName, "Runidseed"))
2856             {
2857             if (expecting == Expecting(EQUALSIGN))
2858                 expecting = Expecting(NUMBER);
2859             else if (expecting == Expecting(NUMBER))
2860                 {
2861                 sscanf (tkn, "%d", &tempI);
2862                 runIDSeed = tempI;
2863                 MrBayesPrint ("%s   Setting run ID [stamp] seed to %ld [for GRID use]\n", spacer, runIDSeed);
2864                 expecting = Expecting(PARAMETER) | Expecting(SEMICOLON);
2865                 }
2866             else
2867                 {
2868                 free (tempStr);
2869                 return (ERROR);
2870                 }
2871             }
2872         /* set Ngen (numGen) ******************************************************************/
2873         else if (!strcmp(parmName, "Ngen"))
2874             {
2875             if (expecting == Expecting(EQUALSIGN))
2876                 expecting = Expecting(NUMBER);
2877             else if (expecting == Expecting(NUMBER))
2878                 {
2879                 sscanf (tkn, "%d", &tempI);
2880                 if (tempI < 1)
2881                     {
2882                     MrBayesPrint ("%s   Too few generations\n", spacer);
2883                     return (ERROR);
2884                     }
2885                 chainParams.numGen = tempI;
2886                 MrBayesPrint ("%s   Setting number of generations to %d\n", spacer, chainParams.numGen);
2887                 expecting = Expecting(PARAMETER) | Expecting(SEMICOLON);
2888                 }
2889             else
2890                 {
2891                 free (tempStr);
2892                 return (ERROR);
2893                 }
2894             }
2895         /* set Samplefreq (sampleFreq) ********************************************************/
2896         else if (!strcmp(parmName, "Samplefreq"))
2897             {
2898             if (expecting == Expecting(EQUALSIGN))
2899                 expecting = Expecting(NUMBER);
2900             else if (expecting == Expecting(NUMBER))
2901                 {
2902                 sscanf (tkn, "%d", &tempI);
2903                 if (tempI < 1)
2904                     {
2905                     MrBayesPrint ("%s   Sampling chain too infrequently\n", spacer);
2906                     free (tempStr);
2907                     return (ERROR);
2908                     }
2909                 chainParams.sampleFreq = tempI;
2910                 MrBayesPrint ("%s   Setting sample frequency to %d\n", spacer, chainParams.sampleFreq);
2911                 expecting = Expecting(PARAMETER) | Expecting(SEMICOLON);
2912                 }
2913             else
2914                 {
2915                 free (tempStr);
2916                 return (ERROR);
2917                 }
2918             }
2919         /* set Printfreq (printFreq) **********************************************************/
2920         else if (!strcmp(parmName, "Printfreq"))
2921             {
2922             if (expecting == Expecting(EQUALSIGN))
2923                 expecting = Expecting(NUMBER);
2924             else if (expecting == Expecting(NUMBER))
2925                 {
2926                 sscanf (tkn, "%d", &tempI);
2927                 if (tempI < 1)
2928                     {
2929                     MrBayesPrint ("%s   Printing to screen too infrequently\n", spacer);
2930                     free(tempStr);
2931                     return (ERROR);
2932                     }
2933                 chainParams.printFreq = tempI;
2934                 MrBayesPrint ("%s   Setting print frequency to %d\n", spacer, chainParams.printFreq);
2935                 expecting = Expecting(PARAMETER) | Expecting(SEMICOLON);
2936                 }
2937             else
2938                 {
2939                 free(tempStr);
2940                 return (ERROR);
2941                 }
2942             }
2943         /* set Printmax (printMax) **********************************************************/
2944         else if (!strcmp(parmName, "Printmax"))
2945             {
2946             if (expecting == Expecting(EQUALSIGN))
2947                 expecting = Expecting(NUMBER);
2948             else if (expecting == Expecting(NUMBER))
2949                 {
2950                 sscanf (tkn, "%d", &tempI);
2951                 if (tempI < 1)
2952                     {
2953                     MrBayesPrint ("%s   You need to print at least one chain\n", spacer);
2954                     return (ERROR);
2955                     }
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);
2959                 }
2960             else
2961                 {
2962                 free(tempStr);
2963                 return (ERROR);
2964                 }
2965             }
2966         /* set Printall (printAll) ********************************************************/
2967         else if (!strcmp(parmName, "Printall"))
2968             {
2969             if (expecting == Expecting(EQUALSIGN))
2970                 expecting = Expecting(ALPHA);
2971             else if (expecting == Expecting(ALPHA))
2972                 {
2973                 if (IsArgValid(tkn, tempStr) == NO_ERROR)
2974                     {
2975                     if (!strcmp(tempStr, "Yes"))
2976                         chainParams.printAll = YES;
2977                     else
2978                         chainParams.printAll = NO;
2979                     }
2980                 else
2981                     {
2982                     MrBayesPrint ("%s   Invalid argument for Printall\n", spacer);
2983                     free (tempStr);
2984                     return (ERROR);
2985                     }
2986                 if (chainParams.allChains == YES)
2987                     MrBayesPrint ("%s   Printing all chains to screen\n", spacer);
2988                 else
2989                     MrBayesPrint ("%s   Printing only cold chains to screen\n", spacer);
2990                 expecting = Expecting(PARAMETER) | Expecting(SEMICOLON);
2991                 }
2992             else
2993                 {
2994                 free(tempStr);
2995                 return (ERROR);
2996                 }
2997             }
2998         /* set Swapfreq (swapFreq) ************************************************************/
2999         else if (!strcmp(parmName, "Swapfreq"))
3000             {
3001             if (expecting == Expecting(EQUALSIGN))
3002                 expecting = Expecting(NUMBER);
3003             else if (expecting == Expecting(NUMBER))
3004                 {
3005                 sscanf (tkn, "%d", &tempI);
3006                 if (tempI < 1)
3007                     {
3008                     MrBayesPrint ("%s   Swapping states too infrequently\n", spacer);
3009                     free(tempStr);
3010                     return (ERROR);
3011                     }
3012                 chainParams.swapFreq = tempI;
3013                 MrBayesPrint ("%s   Setting swap frequency to %d\n", spacer, chainParams.swapFreq);
3014                 expecting = Expecting(PARAMETER) | Expecting(SEMICOLON);
3015                 }
3016             else
3017                 {
3018                 free (tempStr);
3019                 return (ERROR);
3020                 }
3021             }
3022         /* set Nswaps (numSwaps) ************************************************************/
3023         else if (!strcmp(parmName, "Nswaps"))
3024             {
3025             if (expecting == Expecting(EQUALSIGN))
3026                 expecting = Expecting(NUMBER);
3027             else if (expecting == Expecting(NUMBER))
3028                 {
3029                 sscanf (tkn, "%d", &tempI);
3030                 if (tempI < 1)
3031                     {
3032                     MrBayesPrint ("%s   There must be at least one swap per swapping cycle\n", spacer);
3033                     free (tempStr);
3034                     return (ERROR);
3035                     }
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);
3039                 }
3040             else
3041                 {
3042                 free(tempStr);
3043                 return (ERROR);
3044                 }
3045             }
3046         /* set Allchains (allChains) ********************************************************/
3047         else if (!strcmp(parmName, "Allchains"))
3048             {
3049             if (expecting == Expecting(EQUALSIGN))
3050                 expecting = Expecting(ALPHA);
3051             else if (expecting == Expecting(ALPHA))
3052                 {
3053                 if (IsArgValid(tkn, tempStr) == NO_ERROR)
3054                     {
3055                     if (!strcmp(tempStr, "Yes"))
3056                         chainParams.allChains = YES;
3057                     else
3058                         chainParams.allChains = NO;
3059                     }
3060                 else
3061                     {
3062                     MrBayesPrint ("%s   Invalid argument for Allchains\n", spacer);
3063                     free (tempStr);
3064                     return (ERROR);
3065                     }
3066                 if (chainParams.allChains == YES)
3067                     MrBayesPrint ("%s   Calculating MCMC diagnostics for all chains\n", spacer);
3068                 else
3069                     MrBayesPrint ("%s   Calculating MCMC diagnostics only for cold chain(s)\n", spacer);
3070                 expecting = Expecting(PARAMETER) | Expecting(SEMICOLON);
3071                 }
3072             else
3073                 {
3074                 free (tempStr);
3075                 return (ERROR);
3076                 }
3077             }
3078         /* set Allcomps (allComps) ************************************************************/
3079         else if (!strcmp(parmName, "Allcomps"))
3080             {
3081             if (expecting == Expecting(EQUALSIGN))
3082                 expecting = Expecting(ALPHA);
3083             else if (expecting == Expecting(ALPHA))
3084                 {
3085                 if (IsArgValid(tkn, tempStr) == NO_ERROR)
3086                     {
3087                     if (!strcmp(tempStr, "Yes"))
3088                         chainParams.allComps = YES;
3089                     else
3090                         chainParams.allComps = NO;
3091                     }
3092                 else
3093                     {
3094                     MrBayesPrint ("%s   Invalid argument for Allcomps\n", spacer);
3095                     free (tempStr);
3096                     return (ERROR);
3097                     }
3098                 if (chainParams.allComps == YES)
3099                     MrBayesPrint ("%s   Calculating MCMC diagnostics for all pairwise run comparisons\n", spacer);
3100                 else
3101                     MrBayesPrint ("%s   Only calculating overall MCMC diagnostics\n", spacer);
3102                 expecting = Expecting(PARAMETER) | Expecting(SEMICOLON);
3103                 }
3104             else
3105                 {
3106                 free(tempStr);
3107                 return (ERROR);
3108                 }
3109             }
3110         /* set Mcmcdiagn (mcmcDiagn) ********************************************************/
3111         else if (!strcmp(parmName, "Mcmcdiagn"))
3112             {
3113             if (expecting == Expecting(EQUALSIGN))
3114                 expecting = Expecting(ALPHA);
3115             else if (expecting == Expecting(ALPHA))
3116                 {
3117                 if (IsArgValid(tkn, tempStr) == NO_ERROR)
3118                     {
3119                     if (!strcmp(tempStr, "Yes"))
3120                         chainParams.mcmcDiagn = YES;
3121                     else
3122                         chainParams.mcmcDiagn = NO;
3123                     }
3124                 else
3125                     {
3126                     MrBayesPrint ("%s   Invalid argument for mcmc diagnostics\n", spacer);
3127                     free(tempStr);
3128                     return (ERROR);
3129                     }
3130                 if (chainParams.mcmcDiagn == YES)
3131                     MrBayesPrint ("%s   Setting calculation of MCMC diagnostics ('Mcmcdiagn') to yes\n", spacer);
3132                 else
3133                     MrBayesPrint ("%s   Setting calculation of MCMC diagnostics ('Mcmcdiagn') to no\n", spacer);
3134                 expecting = Expecting(PARAMETER) | Expecting(SEMICOLON);
3135                 }
3136             else
3137                 {
3138                 free(tempStr);
3139                 return (ERROR);
3140                 }
3141             }
3142         /* set Diagnfreq (diagnFreq) ************************************************************/
3143         else if (!strcmp(parmName, "Diagnfreq"))
3144             {
3145             if (expecting == Expecting(EQUALSIGN))
3146                 expecting = Expecting(NUMBER);
3147             else if (expecting == Expecting(NUMBER))
3148                 {
3149                 sscanf (tkn, "%d", &tempI);
3150                 if (tempI < 1)
3151                     {
3152                     MrBayesPrint ("%s   Diagnosing MCMC behavior too infrequently\n", spacer);
3153                     free(tempStr);
3154                     return (ERROR);
3155                     }
3156                 chainParams.diagnFreq = tempI;
3157                 MrBayesPrint ("%s   Setting diagnosing frequency to %d\n", spacer, chainParams.diagnFreq);
3158                 expecting = Expecting(PARAMETER) | Expecting(SEMICOLON);
3159                 }
3160             else 
3161                 {
3162                 free(tempStr);
3163                 return (ERROR);
3164                 }
3165             }
3166         /* set Savetrees (saveTrees) ********************************************************/
3167         else if (!strcmp(parmName, "Savetrees"))
3168             {
3169             if (expecting == Expecting(EQUALSIGN))
3170                 expecting = Expecting(ALPHA);
3171             else if (expecting == Expecting(ALPHA))
3172                 {
3173                 if (IsArgValid(tkn, tempStr) == NO_ERROR)
3174                     {
3175                     if (!strcmp(tempStr, "Yes"))
3176                         chainParams.saveTrees = YES;
3177                     else
3178                         chainParams.saveTrees = NO;
3179                     }
3180                 else
3181                     {
3182                     MrBayesPrint ("%s   Invalid argument for Savetrees\n", spacer);
3183                     free(tempStr);
3184                     return (ERROR);
3185                     }
3186                 if (chainParams.saveTrees == YES)
3187                     MrBayesPrint ("%s   Saving trees for MCMC diagnostics in memory (if needed)\n", spacer);
3188                 else
3189                     MrBayesPrint ("%s   Not saving trees for MCMC diagnostics in memory\n", spacer);
3190                 expecting = Expecting(PARAMETER) | Expecting(SEMICOLON);
3191                 }
3192             else
3193                 {
3194                 free(tempStr);
3195                 return (ERROR);
3196                 }
3197             }
3198         /* set Diagnstat (diagnStat) ********************************************************/
3199         else if (!strcmp(parmName, "Diagnstat"))
3200             {
3201             if (expecting == Expecting(EQUALSIGN))
3202                 expecting = Expecting(ALPHA);
3203             else if (expecting == Expecting(ALPHA))
3204                 {
3205                 if (IsArgValid(tkn, tempStr) == NO_ERROR)
3206                     {
3207                     if (!strcmp(tempStr, "Avgstddev"))
3208                         chainParams.diagnStat = AVGSTDDEV;
3209                     else /* if (!strcmp(tempStr, "Maxstddev")) */
3210                         chainParams.diagnStat = MAXSTDDEV;
3211                     }
3212                 else
3213                     {
3214                     MrBayesPrint ("%s   Invalid argument for Savetrees\n", spacer);
3215                     free(tempStr);
3216                     return (ERROR);
3217                     }
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);
3223                 }
3224             else
3225                 {
3226                 free(tempStr);
3227                 return (ERROR);
3228                 }
3229             }
3230         /* set Checkpoint (checkPoint) ********************************************************/
3231         else if (!strcmp(parmName, "Checkpoint"))
3232             {
3233             if (expecting == Expecting(EQUALSIGN))
3234                 expecting = Expecting(ALPHA);
3235             else if (expecting == Expecting(ALPHA))
3236                 {
3237                 if (IsArgValid(tkn, tempStr) == NO_ERROR)
3238                     {
3239                     if (!strcmp(tempStr, "Yes"))
3240                         chainParams.checkPoint = YES;
3241                     else
3242                         chainParams.checkPoint = NO;
3243                     }
3244                 else
3245                     {
3246                     MrBayesPrint ("%s   Invalid argument for 'Checkpoint' (check-pointing)\n", spacer);
3247                     free(tempStr);
3248                     return (ERROR);
3249                     }
3250                 if (chainParams.checkPoint == YES)
3251                     MrBayesPrint ("%s   Setting check-pointing ('Checkpoint') to yes\n", spacer);
3252                 else
3253                     MrBayesPrint ("%s   Setting check-pointing ('Checkpoint') to no\n", spacer);
3254                 expecting = Expecting(PARAMETER) | Expecting(SEMICOLON);
3255                 }
3256             else
3257                 {
3258                 free(tempStr);
3259                 return (ERROR);
3260                 }
3261             }
3262         /* set Checkfreq (checkFreq) ************************************************************/
3263         else if (!strcmp(parmName, "Checkfreq"))
3264             {
3265             if (expecting == Expecting(EQUALSIGN))
3266                 expecting = Expecting(NUMBER);
3267             else if (expecting == Expecting(NUMBER))
3268                 {
3269                 sscanf (tkn, "%d", &tempI);
3270                 if (tempI < 100)
3271                     {
3272                     MrBayesPrint ("%s   Check-pointing frequency must be at least 100\n", spacer);
3273                     free(tempStr);
3274                     return (ERROR);
3275                     }
3276                 chainParams.checkFreq = tempI;
3277                 MrBayesPrint ("%s   Setting check-pointing frequency to %d\n", spacer, chainParams.checkFreq);
3278                 expecting = Expecting(PARAMETER) | Expecting(SEMICOLON);
3279                 }
3280             else 
3281                 {
3282                 free(tempStr);
3283                 return (ERROR);
3284                 }
3285             }
3286         /* set Minpartfreq (minPartFreq) ************************************************************/
3287         else if (!strcmp(parmName, "Minpartfreq"))
3288             {
3289             if (expecting == Expecting(EQUALSIGN))
3290                 expecting = Expecting(NUMBER);
3291             else if (expecting == Expecting(NUMBER))
3292                 {
3293                 sscanf (tkn, "%lf", &tempD);
3294                 if (tempD < 0.01)
3295                     {
3296                     MrBayesPrint ("%s   Minimum partition frequency too low (< 0.01)\n", spacer);
3297                     free (tempStr);
3298                     return (ERROR);
3299                     }
3300                 if (tempD > 0.8)
3301                     {
3302                     MrBayesPrint ("%s   Minimum partition frequency too high (> 0.8)\n", spacer);
3303                     free (tempStr);
3304                     return (ERROR);
3305                     }
3306                 chainParams.minPartFreq = tempD;
3307                 MrBayesPrint ("%s   Setting minimum partition frequency to %.2f\n", spacer, chainParams.minPartFreq);
3308                 expecting = Expecting(PARAMETER) | Expecting(SEMICOLON);
3309                 }
3310             else 
3311                 {
3312                 free(tempStr);
3313                 return (ERROR);
3314                 }
3315             }
3316         /* set Nruns (numRuns) ****************************************************************/
3317         else if (!strcmp(parmName, "Nruns"))
3318             {
3319             if (expecting == Expecting(EQUALSIGN))
3320                 expecting = Expecting(NUMBER);
3321             else if (expecting == Expecting(NUMBER))
3322                 {
3323                 sscanf (tkn, "%d", &tempI);
3324                 if (tempI < 1)
3325                     {
3326                     MrBayesPrint ("%s   Too few runs (minimum of 1 run)\n", spacer);
3327                     free(tempStr);
3328                     return (ERROR);
3329                     }
3330                 if (tempI > MAX_RUNS)
3331                     {
3332                     MrBayesPrint ("%s   Too many runs (maximum of %d runs)\n", spacer, MAX_RUNS);
3333                     free(tempStr);
3334                     return (ERROR);
3335                     }
3336                 if (ChangeNumRuns (chainParams.numRuns, tempI) == ERROR)
3337                     return (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);
3342                 }
3343             else
3344                 {
3345                 free(tempStr);
3346                 return (ERROR);
3347                 }
3348             }
3349         /* set Nchains (numChains) ************************************************************/
3350         else if (!strcmp(parmName, "Nchains"))
3351             {
3352             if (expecting == Expecting(EQUALSIGN))
3353                 expecting = Expecting(NUMBER);
3354             else if (expecting == Expecting(NUMBER))
3355                 {
3356                 sscanf (tkn, "%d", &tempI);
3357                 if (tempI < 1)
3358                     {
3359                     MrBayesPrint ("%s   Too few chains (minimum of 1 chain)\n", spacer);
3360                     free(tempStr);
3361                     return (ERROR);
3362                     }
3363                 if (tempI > MAX_CHAINS)
3364                     {
3365                     MrBayesPrint ("%s   Too many chains (maximum of %d chains)\n", spacer, MAX_CHAINS);
3366                     free(tempStr);
3367                     return (ERROR);
3368                     }
3369                 if (ChangeNumChains (chainParams.numChains, tempI) == ERROR)
3370                     return (ERROR);
3371                 chainParams.numChains = tempI;
3372                 MrBayesPrint ("%s   Setting number of chains to %d\n", spacer, chainParams.numChains);
3373                 expecting = Expecting(PARAMETER) | Expecting(SEMICOLON);
3374                 }
3375             else
3376                 {
3377                 free(tempStr);
3378                 return (ERROR);
3379                 }
3380             }
3381         /* set Temp (chainTemp) ***************************************************************/
3382         else if (!strcmp(parmName, "Temp"))
3383             {
3384             if (expecting == Expecting(EQUALSIGN))
3385                 {
3386                 tempIndex = 0;
3387                 expecting = Expecting(NUMBER) | Expecting(LEFTPAR);
3388                 }
3389             else if (expecting == Expecting(LEFTPAR))
3390                 {
3391                 chainParams.userDefinedTemps = YES;
3392                 expecting = Expecting(NUMBER);
3393                 }
3394             else if (expecting == Expecting(RIGHTPAR))
3395                 {
3396                 MrBayesPrint ("%s   Setting user-defined temperatures\n", spacer);
3397                 expecting = Expecting(PARAMETER) | Expecting(SEMICOLON);
3398                 }
3399             else if (expecting == Expecting(COMMA))
3400                 {
3401                 expecting = Expecting(NUMBER);
3402                 }
3403             else if (expecting == Expecting(NUMBER))
3404                 {
3405                 if (chainParams.userDefinedTemps == NO)
3406                     {
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);
3411                     }
3412                 else
3413                     {
3414                     if (tempIndex >= MAX_CHAINS)
3415                         {
3416                         MrBayesPrint ("%s   Too many user-defined temperatures (%d maximum)\n", spacer, MAX_CHAINS);
3417                         free(tempStr);
3418                         return (ERROR);
3419                         }
3420                     sscanf (tkn, "%lf", &tempD);
3421                     chainParams.userTemps[tempIndex++] = tempD;
3422                     expecting = Expecting(COMMA) | Expecting(RIGHTPAR);
3423                     }
3424                 }
3425             else
3426                 {
3427                 free(tempStr);
3428                 return (ERROR);
3429                 }
3430             }
3431         /* set Reweight (weightScheme) ********************************************************/
3432         else if (!strcmp(parmName, "Reweight"))
3433             {
3434             if (expecting == Expecting(EQUALSIGN))
3435                 expecting = Expecting(LEFTPAR);
3436             else if (expecting == Expecting(LEFTPAR))
3437                 {
3438                 expecting = Expecting(NUMBER);
3439                 whichReweightNum = 0;
3440                 }
3441             else if (expecting == Expecting(NUMBER))
3442                 {
3443                 if (whichReweightNum < 0 || whichReweightNum > 2)
3444                     {
3445                     free(tempStr);
3446                     return (ERROR);
3447                     }
3448                 sscanf (tkn, "%lf", &tempD);
3449                 chainParams.weightScheme[whichReweightNum] = tempD;
3450                 if (whichReweightNum < 2)
3451                     {
3452                     if (tempD < 0.0 || tempD > 100.0)
3453                         {
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;
3457                         free(tempStr);
3458                         return (ERROR);
3459                         }
3460                     }
3461                 else
3462                     {
3463                     if (tempD <= 0.0 || tempD > 1.0)
3464                         {
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;
3468                         free(tempStr);
3469                         return (ERROR);
3470                         }
3471                     }
3472                 if (whichReweightNum == 0)
3473                     {
3474                     expecting = Expecting(COMMA);
3475                     }
3476                 else if (whichReweightNum == 1)
3477                     {
3478                     if (chainParams.weightScheme[0] + chainParams.weightScheme[1] > 100.0)
3479                         {
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;
3483                         free(tempStr);
3484                         return (ERROR);
3485                         }
3486                     expecting = Expecting(COMMA) | Expecting(RIGHTPAR);
3487                     }
3488                 else
3489                     {
3490                     expecting = Expecting(RIGHTPAR);
3491                     }
3492                 whichReweightNum++;
3493                 }
3494             else if ((expecting & Expecting(COMMA)) == Expecting(COMMA))
3495                 expecting = Expecting(NUMBER);
3496             else if ((expecting & Expecting(RIGHTPAR)) == Expecting(RIGHTPAR))
3497                 {
3498                 if (chainParams.weightScheme[0] >= 100.0)
3499                     {
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;
3503                     free(tempStr);
3504                     return (ERROR);
3505                     }
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);
3509                 }
3510             else
3511                 {
3512                 free(tempStr);
3513                 return (ERROR);
3514                 }
3515             }
3516         /* set Filename (chainFileName) *******************************************************/
3517         else if (!strcmp(parmName, "Filename"))
3518             {
3519             if (expecting == Expecting(EQUALSIGN))
3520                 {
3521                 expecting = Expecting(ALPHA);
3522                 readWord = YES;
3523                 }
3524             else if (expecting == Expecting(ALPHA))
3525                 {
3526                 sscanf (tkn, "%s", tempStr);
3527                 if (strlen(tempStr)>99)
3528                     {
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));
3532                     return (ERROR);
3533                     }
3534                 strcpy (chainParams.chainFileName, tempStr);
3535                 fileNameChanged = YES;
3536                 expecting = Expecting(PARAMETER) | Expecting(SEMICOLON);
3537                 }
3538             else
3539                 {
3540                 free(tempStr);
3541                 return (ERROR);
3542                 }
3543             }
3544         /* set Relburnin (relativeBurnin) ********************************************************/
3545         else if (!strcmp(parmName, "Relburnin"))
3546             {
3547             if (expecting == Expecting(EQUALSIGN))
3548                 expecting = Expecting(ALPHA);
3549             else if (expecting == Expecting(ALPHA))
3550                 {
3551                 if (IsArgValid(tkn, tempStr) == NO_ERROR)
3552                     {
3553                     if (!strcmp(tempStr, "Yes"))
3554                         chainParams.relativeBurnin = YES;
3555                     else
3556                         chainParams.relativeBurnin = NO;
3557                     }
3558                 else
3559                     {
3560                     MrBayesPrint ("%s   Invalid argument for Relburnin\n", spacer);
3561                     free(tempStr);
3562                     return (ERROR);
3563                     }
3564                 if (chainParams.relativeBurnin == YES)
3565                     MrBayesPrint ("%s   Using relative burnin (a fraction of samples discarded).\n", spacer);
3566                 else
3567                     MrBayesPrint ("%s   Using absolute burnin (a fixed number of samples discarded).\n", spacer);
3568                 expecting = Expecting(PARAMETER) | Expecting(SEMICOLON);
3569                 }
3570             else
3571                 {
3572                 free (tempStr);
3573                 return (ERROR);
3574                 }
3575             }
3576         /* set Burnin (chainBurnIn) ***********************************************************/
3577         else if (!strcmp(parmName, "Burnin"))
3578             {
3579             if (expecting == Expecting(EQUALSIGN))
3580                 expecting = Expecting(NUMBER);
3581             else if (expecting == Expecting(NUMBER))
3582                 {
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);
3587                 }
3588             else
3589                 {
3590                 free(tempStr);
3591                 return (ERROR);
3592                 }
3593             }
3594         /* set Burninfrac (burninFraction) ************************************************************/
3595         else if (!strcmp(parmName, "Burninfrac"))
3596             {
3597             if (expecting == Expecting(EQUALSIGN))
3598                 expecting = Expecting(NUMBER);
3599             else if (expecting == Expecting(NUMBER))
3600                 {
3601                 sscanf (tkn, "%lf", &tempD);
3602                 if (tempD < 0.01)
3603                     {
3604                     MrBayesPrint ("%s   Burnin fraction too low (< 0.01)\n", spacer);
3605                     free(tempStr);
3606                     return (ERROR);
3607                     }
3608                 if (tempD > 0.50)
3609                     {
3610                     MrBayesPrint ("%s   Burnin fraction too high (> 0.50)\n", spacer);
3611                     free(tempStr);
3612                     return (ERROR);
3613                     }
3614                 chainParams.burninFraction = tempD;
3615                 MrBayesPrint ("%s   Setting burnin fraction to %.2f\n", spacer, chainParams.burninFraction);
3616                 expecting = Expecting(PARAMETER) | Expecting(SEMICOLON);
3617                 }
3618             else 
3619                 {
3620                 free(tempStr);
3621                 return (ERROR);
3622                 }
3623             }
3624         /* set Stoprule (stopRule) ********************************************************/
3625         else if (!strcmp(parmName, "Stoprule"))
3626             {
3627             if (expecting == Expecting(EQUALSIGN))
3628                 expecting = Expecting(ALPHA);
3629             else if (expecting == Expecting(ALPHA))
3630                 {
3631                 if (IsArgValid(tkn, tempStr) == NO_ERROR)
3632                     {
3633                     if (!strcmp(tempStr, "Yes"))
3634                         chainParams.stopRule = YES;
3635                     else
3636                         chainParams.stopRule = NO;
3637                     }
3638                 else
3639                     {
3640                     MrBayesPrint ("%s   Invalid argument for Stoprule\n", spacer);
3641                     free(tempStr);
3642                     return (ERROR);
3643                     }
3644                 if (chainParams.stopRule == YES)
3645                     MrBayesPrint ("%s   Using stopping rule.\n", spacer);
3646                 else
3647                     MrBayesPrint ("%s   Not using stopping rule.\n", spacer);
3648                 expecting = Expecting(PARAMETER) | Expecting(SEMICOLON);
3649                 }
3650             else
3651                 {
3652                 free(tempStr);
3653                 return (ERROR);
3654                 }
3655             }
3656         /* set Stopval (stopVal) ************************************************************/
3657         else if (!strcmp(parmName, "Stopval"))
3658             {
3659             if (expecting == Expecting(EQUALSIGN))
3660                 expecting = Expecting(NUMBER);
3661             else if (expecting == Expecting(NUMBER))
3662                 {
3663                 sscanf (tkn, "%lf", &tempD);
3664                 if (tempD < 0.000001)
3665                     {
3666                     MrBayesPrint ("%s   Stop value too low (< 0.000001)\n", spacer);
3667                     free(tempStr);
3668                     return (ERROR);
3669                     }
3670                 if (tempD > 0.20)
3671                     {
3672                     MrBayesPrint ("%s   Stop value too high (> 0.20)\n", spacer);
3673                     free(tempStr);
3674                     return (ERROR);
3675                     }
3676                 chainParams.stopVal = tempD;
3677                 MrBayesPrint ("%s   Setting burnin fraction to %.2f\n", spacer, chainParams.burninFraction);
3678                 expecting = Expecting(PARAMETER) | Expecting(SEMICOLON);
3679                 }
3680             else 
3681                 {
3682                 free(tempStr);
3683                 return (ERROR);
3684                 }
3685             }
3686         /* set Starttree (startTree) **************************************************/
3687         else if (!strcmp(parmName, "Starttree"))
3688             {
3689             if (expecting == Expecting(EQUALSIGN))
3690                 expecting = Expecting(ALPHA);
3691             else if (expecting == Expecting(ALPHA))
3692                 {
3693                 if (IsArgValid(tkn, tempStr) == NO_ERROR)
3694                     {
3695                     if (!strcmp(tempStr,"User"))
3696                         {
3697                         MrBayesPrint ("%s   The 'user' setting of 'Starttree' is deprecated. Set starting trees using 'Startvals' instead.\n", spacer);
3698                         free (tempStr);
3699                         return (ERROR);
3700                         }
3701                     else
3702                         strcpy(chainParams.startTree, tempStr);
3703                     }
3704                 else
3705                     {
3706                     MrBayesPrint ("%s   Invalid 'Starttree' argument '%s'. This is a bug -- please report.\n", spacer, tempStr);
3707                     free(tempStr);
3708                     return (ERROR);
3709                     }
3710                 MrBayesPrint ("%s   Setting 'Starttree' to \"%s\"\n", spacer, chainParams.startTree);
3711                 expecting = Expecting(PARAMETER) | Expecting(SEMICOLON);
3712                 }
3713             else
3714                 {
3715                 free(tempStr);
3716                 return (ERROR);
3717                 }
3718             }
3719         /* set Startingtrees (deprecated) **************************************************/
3720         else if (!strcmp(parmName, "Startingtrees"))
3721             {
3722             free (tempStr);
3723             MrBayesPrint ("%s   Parameter 'Startingtrees' is deprecated. Use the 'Starttree' parameter or the 'Startvals' command instead.\n", spacer);
3724             return (ERROR);
3725             }
3726         /* set Nperts (numStartPerts) *********************************************************/
3727         else if (!strcmp(parmName, "Nperts"))
3728             {
3729             if (expecting == Expecting(EQUALSIGN))
3730                 expecting = Expecting(NUMBER);
3731             else if (expecting == Expecting(NUMBER))
3732                 {
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);
3737                 }
3738             else
3739                 {
3740                 free(tempStr);
3741                 return (ERROR);
3742                 }
3743             }
3744         /* set Startparams (startParams) **************************************************/
3745         else if (!strcmp(parmName, "Startparams"))
3746             {
3747             if (expecting == Expecting(EQUALSIGN))
3748                 expecting = Expecting(ALPHA);
3749             else if (expecting == Expecting(ALPHA))
3750                 {
3751                 if (IsArgValid(tkn, tempStr) == NO_ERROR)
3752                     strcpy(chainParams.startParams, tempStr);
3753                 else
3754                     {
3755                     MrBayesPrint ("%s   Invalid 'Startparams' argument\n", spacer);
3756                     free(tempStr);
3757                     return (ERROR);
3758                     }
3759                 MrBayesPrint ("%s   Setting 'Startparams' to \"%s\"\n", spacer, chainParams.startParams);
3760                 expecting = Expecting(PARAMETER) | Expecting(SEMICOLON);
3761                 }
3762             else
3763                 {
3764                 free(tempStr);
3765                 return (ERROR);
3766                 }
3767             }
3768         /* set Savebrlens (saveBrlens) ********************************************************/
3769         else if (!strcmp(parmName, "Savebrlens"))
3770             {
3771             if (expecting == Expecting(EQUALSIGN))
3772                 expecting = Expecting(ALPHA);
3773             else if (expecting == Expecting(ALPHA))
3774                 {
3775                 if (IsArgValid(tkn, tempStr) == NO_ERROR)
3776                     {
3777                     if (!strcmp(tempStr, "Yes"))
3778                         ; /* This is the only option in version 3.2 */
3779                     else
3780                         MrBayesPrint ("%s   WARNING: Ignoring savebrlens setting; since version 3.2, branch lengths are always saved\n", spacer);
3781                     }
3782                 else
3783                     {
3784                     MrBayesPrint ("%s   Invalid argument for savebrlens\n", spacer);
3785                     free(tempStr);
3786                     return (ERROR);
3787                     }
3788                 expecting = Expecting(PARAMETER) | Expecting(SEMICOLON);
3789                 }
3790             }
3791         /* set Redirect (redirect) ********************************************************/
3792         else if (!strcmp(parmName, "Redirect"))
3793             {
3794             if (expecting == Expecting(EQUALSIGN))
3795                 expecting = Expecting(ALPHA);
3796             else if (expecting == Expecting(ALPHA))
3797                 {
3798                 if (IsArgValid(tkn, tempStr) == NO_ERROR)
3799                     {
3800                     if (!strcmp(tempStr, "Yes"))
3801                         chainParams.redirect = YES;
3802                     else
3803                         chainParams.redirect = NO;
3804                     }
3805                 else
3806                     {
3807                     MrBayesPrint ("%s   Invalid argument for redirecting output\n", spacer);
3808                     free(tempStr);
3809                     return (ERROR);
3810                     }
3811                 if (chainParams.redirect == YES)
3812                     MrBayesPrint ("%s   Setting program to redirect output\n", spacer);
3813                 else
3814                     MrBayesPrint ("%s   Setting program not to redirect output\n", spacer);
3815                 expecting = Expecting(PARAMETER) | Expecting(SEMICOLON);
3816                 }
3817             else
3818                 {
3819                 free(tempStr);
3820                 return (ERROR);
3821                 }
3822             }
3823         /* set Data (runWithData) ************************************************************/
3824         else if (!strcmp(parmName, "Data"))
3825             {
3826             if (expecting == Expecting(EQUALSIGN))
3827                 expecting = Expecting(ALPHA);
3828             else if (expecting == Expecting(ALPHA))
3829                 {
3830                 if (IsArgValid(tkn, tempStr) == NO_ERROR)
3831                     {
3832                     if (!strcmp(tempStr, "Yes"))
3833                         chainParams.runWithData = YES;
3834                     else
3835                         chainParams.runWithData = NO;
3836                     }
3837                 else
3838                     {
3839                     MrBayesPrint ("%s   Invalid argument for Data\n", spacer);
3840                     free(tempStr);
3841                     return (ERROR);
3842                     }
3843                 if (chainParams.runWithData == NO)
3844                     MrBayesPrint ("%s   Running without data (WARNING: use this only for checking priors!)\n", spacer);
3845                 else
3846                     MrBayesPrint ("%s   Running with data (standard analysis)\n", spacer);
3847                 expecting = Expecting(PARAMETER) | Expecting(SEMICOLON);
3848                 }
3849             else
3850                 {
3851                 free(tempStr);
3852                 return (ERROR);
3853                 }
3854             }
3855         /* set Ordertaxa (chainParams.orderTaxa) *********************************************/
3856         else if (!strcmp(parmName, "Ordertaxa"))
3857             {
3858             if (expecting == Expecting(EQUALSIGN))
3859                 expecting = Expecting(ALPHA);
3860             else if (expecting == Expecting(ALPHA))
3861                 {
3862                 if (IsArgValid(tkn, tempStr) == NO_ERROR)
3863                     {
3864                     if (!strcmp(tempStr, "Yes"))
3865                         chainParams.orderTaxa = YES;
3866                     else
3867                         chainParams.orderTaxa = NO;
3868                     }
3869                 else
3870                     {
3871                     MrBayesPrint ("%s   Invalid argument for ordertaxa\n", spacer);
3872                     free(tempStr);
3873                     return (ERROR);
3874                     }
3875                 if (chainParams.orderTaxa == YES)
3876                     MrBayesPrint ("%s   Setting ordertaxa to yes\n", spacer);
3877                 else
3878                     MrBayesPrint ("%s   Setting ordertaxa to no\n", spacer);
3879                 expecting = Expecting(PARAMETER) | Expecting(SEMICOLON);
3880                 }
3881             else
3882                 {
3883                 free(tempStr);
3884                 return (ERROR);
3885                 }
3886             }
3887         /* set Append (chainParams.append) *********************************************/
3888         else if (!strcmp(parmName, "Append"))
3889             {
3890             if (expecting == Expecting(EQUALSIGN))
3891                 expecting = Expecting(ALPHA);
3892             else if (expecting == Expecting(ALPHA))
3893                 {
3894                 if (IsArgValid(tkn, tempStr) == NO_ERROR)
3895                     {
3896                     if (!strcmp(tempStr, "Yes"))
3897                         chainParams.append = YES;
3898                     else
3899                         chainParams.append = NO;
3900                     }
3901                 else
3902                     {
3903                     MrBayesPrint ("%s   Invalid argument for append\n", spacer);
3904                     free(tempStr);
3905                     return (ERROR);
3906                     }
3907                 if (chainParams.append == YES)
3908                     MrBayesPrint ("%s   Setting append to yes\n", spacer);
3909                 else
3910                     MrBayesPrint ("%s   Setting append to no\n", spacer);
3911                 expecting = Expecting(PARAMETER) | Expecting(SEMICOLON);
3912                 }
3913             else
3914                 {
3915                 free(tempStr);
3916                 return (ERROR);
3917                 }
3918             }
3919         /* set Autotune (chainParams.autotune) *********************************************/
3920         else if (!strcmp(parmName, "Autotune"))
3921             {
3922             if (expecting == Expecting(EQUALSIGN))
3923                 expecting = Expecting(ALPHA);
3924             else if (expecting == Expecting(ALPHA))
3925                 {
3926                 if (IsArgValid(tkn, tempStr) == NO_ERROR)
3927                     {
3928                     if (!strcmp(tempStr, "Yes"))
3929                         chainParams.autotune = YES;
3930                     else
3931                         chainParams.autotune = NO;
3932                     }
3933                 else
3934                     {
3935                     MrBayesPrint ("%s   Invalid argument for Autotune\n", spacer);
3936                     free(tempStr);
3937                     return (ERROR);
3938                     }
3939                 if (chainParams.autotune == YES)
3940                     MrBayesPrint ("%s   Setting Autotune to yes\n", spacer);
3941                 else
3942                     MrBayesPrint ("%s   Setting Autotune to no\n", spacer);
3943                 expecting = Expecting(PARAMETER) | Expecting(SEMICOLON);
3944                 }
3945             else
3946                 {
3947                 free(tempStr);
3948                 return (ERROR);
3949                 }
3950             }
3951         /* set Tunefreq (tuneFreq) ************************************************************/
3952         else if (!strcmp(parmName, "Tunefreq"))
3953             {
3954             if (expecting == Expecting(EQUALSIGN))
3955                 expecting = Expecting(NUMBER);
3956             else if (expecting == Expecting(NUMBER))
3957                 {
3958                 sscanf (tkn, "%d", &tempI);
3959                 if (tempI < 10)
3960                     {
3961                     MrBayesPrint ("%s   Autotuning frequency must be at least 10\n", spacer);
3962                     free(tempStr);
3963                     return (ERROR);
3964                     }
3965                 chainParams.tuneFreq = tempI;
3966                 MrBayesPrint ("%s   Setting autotuning frequency to %d\n", spacer, chainParams.tuneFreq);
3967                 expecting = Expecting(PARAMETER) | Expecting(SEMICOLON);
3968                 }
3969             else 
3970                 {
3971                 free(tempStr);
3972                 return (ERROR);
3973                 }
3974             }
3975         /* set Swapadjacent (swapAdjacentOnly) **************************************************/
3976         else if (!strcmp(parmName, "Swapadjacent"))
3977             {
3978             if (expecting == Expecting(EQUALSIGN))
3979                 expecting = Expecting(ALPHA);
3980             else if (expecting == Expecting(ALPHA))
3981                 {
3982                 if (IsArgValid(tkn, tempStr) == NO_ERROR)
3983                     {
3984                     if (!strcmp(tempStr, "Yes"))
3985                         chainParams.swapAdjacentOnly = YES;
3986                     else
3987                         chainParams.swapAdjacentOnly = NO;
3988                     }
3989                 else
3990                     {
3991                     MrBayesPrint ("%s   Invalid argument for Swapadjacent\n", spacer);
3992                     free(tempStr);
3993                     return (ERROR);
3994                     }
3995                 if (chainParams.swapAdjacentOnly == YES)
3996                     MrBayesPrint ("%s   Setting program to attempt swaps only between chains of adjacent temperatures\n", spacer);
3997                 else
3998                     MrBayesPrint ("%s   Setting program to attempt all possible swaps between chains\n", spacer);
3999                 expecting = Expecting(PARAMETER) | Expecting(SEMICOLON);
4000                 }
4001             else
4002                 {
4003                 free(tempStr);
4004                 return (ERROR);
4005                 }
4006             }
4007         else
4008             {
4009             free(tempStr);
4010             return (ERROR);
4011             }
4012         }
4013     free(tempStr);
4014     return (NO_ERROR);
4015 }
4016
4017
4018 int DoSs (void)
4019 {
4020     int ret, oldBurnin;
4021
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);
4025         return ERROR;
4026         }
4027
4028     oldBurnin = chainParams.burninSS;;
4029     stepRelativeBurninSS = chainParams.relativeBurnin;
4030
4031     chainParams.relativeBurnin = YES;
4032  
4033     if (chainParams.burninSS < 0)
4034         chainParams.burninSS =  chainParams.numGen / ((chainParams.numStepsSS-chainParams.burninSS)*chainParams.sampleFreq);
4035     chainParams.isSS = YES;
4036
4037     ret=DoMcmc();
4038
4039     chainParams.isSS = NO;
4040     chainParams.burninSS = oldBurnin;
4041     chainParams.relativeBurnin = stepRelativeBurninSS;
4042
4043     return ret;
4044 }
4045
4046
4047 int DoSsp (void)
4048 {
4049     return NO_ERROR;
4050 }
4051
4052
4053 int ExhaustiveParsimonySearch (Tree *t, int chain, TreeInfo *tInfo)
4054 {
4055     int         i, j, k;
4056     TreeNode    *p;
4057     
4058     for (i=j=k=0; i<t->nNodes; i++)
4059         {
4060         p = t->allDownPass[i];
4061         if (p->left == NULL || p->right == NULL)
4062             tInfo->leaf[j++] = p;
4063         else
4064             tInfo->vertex[k++] = p;
4065         }
4066
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];
4072
4073     BuildExhaustiveSearchTree (t, chain, 2, tInfo);
4074
4075     return (NO_ERROR);
4076 }
4077
4078
4079 int ExtendChainQuery ()
4080 {
4081     int             extendChain, additionalCycles;
4082     char            s[100];
4083     
4084 #   if defined (MPI_ENABLED)
4085     if (proc_id == 0)
4086         {
4087         MrBayesPrint ("\n");
4088         extendChain = WantTo ("Continue with analysis");
4089         }
4090     MPI_Bcast (&extendChain, 1, MPI_INT, 0, MPI_COMM_WORLD);
4091     if (extendChain == YES)
4092         {
4093         if (proc_id == 0)
4094             {
4095             additionalCycles = 0;
4096             do
4097                 {
4098                 if (additionalCycles < 0)
4099                     MrBayesPrint ("%s      Number must be greater than or equal to 0: ", spacer);
4100                 else
4101                     MrBayesPrint ("%s      Additional number of generations: ", spacer);
4102
4103                 if (fgets (s, 100, stdin) == NULL)
4104                     {
4105                     printf ("Error in function: %s at line: %d in file: %s", __FUNCTION__, __LINE__, __FILE__);
4106                     }
4107                 sscanf (s, "%d", &additionalCycles);
4108
4109                 } while (additionalCycles < 0);
4110             MrBayesPrint ("\n");
4111             }
4112         MPI_Bcast (&additionalCycles, 1, MPI_INT, 0, MPI_COMM_WORLD);
4113             
4114         return (additionalCycles);
4115         }
4116     else
4117         return (0);
4118 #   else
4119     MrBayesPrint ("\n");
4120     extendChain = WantTo ("Continue with analysis");
4121     
4122     if (extendChain == YES)
4123         {
4124         additionalCycles = 0;
4125         do
4126             {
4127             if (additionalCycles < 0)
4128                 MrBayesPrint ("%s      Number must be greater than or equal to 0: ", spacer);
4129             else
4130                 MrBayesPrint ("%s      Additional number of generations: ", spacer);
4131
4132             if (fgets (s, 20, stdin) == NULL)
4133                 {
4134                 printf ("Error in function: %s at line: %d in file: %s", __FUNCTION__, __LINE__, __FILE__);
4135                 }
4136             sscanf (s, "%d", &additionalCycles);
4137
4138             } while (additionalCycles < 0);
4139         MrBayesPrint ("\n");
4140         return (additionalCycles);
4141         }
4142     else
4143         return (0);
4144 #   endif
4145
4146 }
4147
4148
4149 int FillNumSitesOfPat (void)
4150 {
4151     int         i, j, n, *increased, *decreased, nToDecrease, nToIncrease, whichToChange;
4152     MrBFlt      ran, sum;
4153     CLFlt       wtIncrement;
4154     
4155     wtIncrement = (CLFlt) chainParams.weightScheme[2];
4156     increased = decreased = NULL;
4157     
4158     /* reallocate numSitesOfPat */
4159     if (memAllocs[ALLOC_NUMSITESOFPAT] == NO)
4160         {
4161         MrBayesPrint ("%s   numSitesOfPat is not allocated\n", spacer);
4162         goto errorExit;
4163         }
4164     memAllocs[ALLOC_NUMSITESOFPAT] = NO;
4165     numSitesOfPat = (CLFlt *) SafeRealloc((void *) numSitesOfPat, numCompressedChars * chainParams.numChains * sizeof(MrBFlt));
4166     if (!numSitesOfPat)
4167         {
4168         MrBayesPrint ("%s   Problem reallocating numSitesOfPat (%d)\n", spacer, numCompressedChars * chainParams.numChains * sizeof(MrBFlt));
4169         goto errorExit;
4170         }
4171     memAllocs[ALLOC_NUMSITESOFPAT] = YES;
4172
4173     /* copy first numCompressedChars into the remaining bits */
4174     if (chainParams.numChains > 1)
4175         {
4176         for (i=0; i<numCompressedChars; i++)
4177             {
4178             for (j=1; j<chainParams.numChains; j++)
4179                 {
4180                 numSitesOfPat[j * numCompressedChars + i] = numSitesOfPat[i];
4181                 }
4182             }
4183         }   
4184         
4185     /* reweight characters for each chain */
4186     if (chainParams.numChains > 1)
4187         {
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);
4190
4191         /* check that we don't have an HMM */
4192         if (chainHasAdgamma == YES && chainParams.weightScheme[0] + chainParams.weightScheme[1] > 0.0001)
4193             {
4194             MrBayesPrint ("%s   Reweighting of characters is not allowed with an autocorrelated gamma model\n", spacer);
4195             goto errorExit;
4196             }
4197         
4198         /* how many characters */
4199         n = 0;
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)
4205             {
4206             MrBayesPrint ("%s      Decreasing weight of %d characters\n", spacer, nToDecrease);
4207             MrBayesPrint ("%s      Increasing weight of %d characters\n", spacer, nToIncrease);
4208             }
4209         
4210         /* allocate memory */
4211         increased = (int *)SafeMalloc(2 * (size_t)numCompressedChars * sizeof(int));
4212         if (!increased)
4213             {
4214             MrBayesPrint ("%s   Problem reallocating increased (%d)\n", spacer, numCompressedChars * chainParams.numChains * sizeof(int));
4215             goto errorExit;
4216             }
4217         decreased = increased + numCompressedChars;
4218
4219         /* reweight characters for each chain */
4220         for (j=1; j<chainParams.numChains; j++)
4221             {
4222             for (i=0; i<numCompressedChars; i++)
4223                 increased[i] = decreased[i] = 0;
4224
4225             /* decrease weight of characters */
4226             for (i=0; i<nToDecrease; i++)
4227                 {
4228                 do
4229                     {
4230                     ran = RandomNumber(&swapSeed);
4231                     sum = 0.0;
4232                     for (whichToChange=0; whichToChange<numCompressedChars; whichToChange++)
4233                         {
4234                         sum += numSitesOfPat[0 * numCompressedChars + whichToChange] / n;
4235                         if (ran < sum)
4236                             break;
4237                         }
4238                     if (whichToChange < 0 || whichToChange >= numCompressedChars)
4239                         continue;
4240                     } while (decreased[whichToChange] >= numSitesOfPat[0 * numCompressedChars + whichToChange]);
4241                 decreased[whichToChange]++;
4242                 numSitesOfPat[j * numCompressedChars + whichToChange] -= wtIncrement;
4243                 if (numSitesOfPat[j * numCompressedChars + whichToChange] < 0)
4244                     {
4245                     MrBayesPrint ("%s   Problem reweighting characters\n", spacer);
4246                     goto errorExit;
4247                     }
4248                 }
4249
4250             /* increase weight of characters */
4251             for (i=0; i<nToDecrease; i++)
4252                 {
4253                 do
4254                     {
4255                     ran = RandomNumber(&swapSeed);
4256                     sum = 0.0;
4257                     for (whichToChange=0; whichToChange<numCompressedChars; whichToChange++)
4258                         {
4259                         sum += numSitesOfPat[0 * numCompressedChars + whichToChange] / n;
4260                         if (ran < sum)
4261                             break;
4262                         }
4263                     if (whichToChange < 0 || whichToChange >= numCompressedChars)
4264                         continue;
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)
4269                     {
4270                     MrBayesPrint ("%s   Problem reweighting characters\n", spacer);
4271                     goto errorExit;
4272                     }
4273                 }
4274
4275             }
4276             
4277         /* free allocated memory */
4278         free (increased);
4279         }
4280         
4281 #   if 0
4282     /* print site patterns for each chain */
4283     for (i=0; i<numCompressedChars; i++)
4284         {
4285         MrBayesPrint ("%4d -- ", i);
4286         for (j=0; j<chainParams.numChains; j++)
4287             {
4288             MrBayesPrint ("%4.1lf ", numSitesOfPat[j * numCompressedChars + i]);
4289             }
4290         MrBayesPrint ("\n");
4291         }
4292 #   endif
4293
4294     return (NO_ERROR);
4295     
4296     errorExit:
4297         if (increased)
4298             free (increased);
4299         return (ERROR);
4300 }
4301
4302
4303 /* FindBestNode: Recursive function for finding best attachment point */
4304 TreeNode *FindBestNode (Tree *t, TreeNode *p, TreeNode *addNode, CLFlt *minLength, int chain) {
4305
4306     int         c, n, division;
4307     TreeNode    *q=NULL, *r=NULL;
4308     BitsLong    *pA, *pP, *pX;
4309     CLFlt       *nSitesOfPat, fpLength, length;
4310     ModelInfo   *m;
4311
4312     /* Calculate length, looping over divisions */
4313     fpLength = 0;
4314     for (n=0; n<t->nRelParts; n++)
4315         {
4316         division = t->relParts[n];
4317
4318         /* Find model settings */
4319         m = &modelSettings[division];
4320
4321         /* Find number of site patterns */
4322         nSitesOfPat = numSitesOfPat + ((1 % chainParams.numChains) * numCompressedChars) + m->compCharStart;
4323
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];
4328
4329         for (c=0; c<m->numChars; c++)
4330             {
4331             if (((pP[c] | pA[c])&pX[c]) == 0)
4332                 fpLength += nSitesOfPat[c];
4333             }
4334         }
4335
4336     /* If tip, this is the best node and its length is the min length */
4337     if (p->left == NULL)
4338         {
4339         *minLength = fpLength;
4340         return p;
4341         }
4342
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;
4349             q = r;
4350         }
4351     }
4352
4353     /* Return best node and min length */
4354     if (*minLength < fpLength)
4355         return q;
4356     else /* This node is the best */
4357         {
4358         *minLength = fpLength;
4359         return p;
4360         }
4361 }
4362
4363
4364 /* FlipCijkSpace: Flip space for cijks with scratch area */
4365 void FlipCijkSpace (ModelInfo* m, int chain)
4366 {
4367     int         temp;
4368
4369     temp                = m->cijkIndex[chain];
4370     m->cijkIndex[chain] = m->cijkScratchIndex;
4371     m->cijkScratchIndex = temp;
4372 }
4373
4374
4375 /* FlipCondLikeSpace: Flip space for conditional likelihoods with scratch area */
4376 void FlipCondLikeSpace (ModelInfo* m, int chain, int nodeIndex)
4377 {
4378     int         temp;
4379
4380     temp                               = m->condLikeIndex[chain][nodeIndex];
4381     m->condLikeIndex[chain][nodeIndex] = m->condLikeScratchIndex[nodeIndex];
4382     m->condLikeScratchIndex[nodeIndex] = temp;
4383 }
4384
4385
4386 /* FlipNodeScalerSpace: Flip space for node scalers and scaler flag with scratch area */
4387 void FlipNodeScalerSpace (ModelInfo* m, int chain, int nodeIndex)
4388 {
4389     int         temp;
4390
4391     temp                                 = m->nodeScalerIndex[chain][nodeIndex];
4392     m->nodeScalerIndex[chain][nodeIndex] = m->nodeScalerScratchIndex[nodeIndex];
4393     m->nodeScalerScratchIndex[nodeIndex] = temp;
4394
4395     temp                                 = m->scalersSet[chain][nodeIndex];
4396     m->scalersSet[chain][nodeIndex]      = m->scalersSetScratch[nodeIndex];
4397     m->scalersSetScratch[nodeIndex]      = temp;
4398 }
4399
4400
4401 /* FlipSiteScalerSpace: Flip space for ln site scalers */
4402 void FlipSiteScalerSpace (ModelInfo *m, int chain)
4403 {
4404     int  temp;
4405
4406 #   if defined (BEAGLE_ENABLED)
4407     int *tempp;
4408 #   endif
4409
4410     temp = m->siteScalerIndex[chain];
4411     m->siteScalerIndex[chain] = m->siteScalerScratchIndex;
4412     m->siteScalerScratchIndex = temp;
4413
4414 #   if defined (BEAGLE_ENABLED)
4415     if (m->useBeagle == YES)
4416         {
4417         tempp = m->isScalerNode[chain];
4418         m->isScalerNode[chain] = m->isScalerNodeScratch ;
4419         m->isScalerNodeScratch = tempp;
4420         }
4421 #   endif
4422 }
4423
4424
4425 /* FlipTiProbsSpace: Flip space for ti probs with scratch area */
4426 void FlipTiProbsSpace (ModelInfo* m, int chain, int nodeIndex)
4427 {
4428     int         temp;
4429
4430     temp                              = m->tiProbsIndex[chain][nodeIndex];
4431     m->tiProbsIndex[chain][nodeIndex] = m->tiProbsScratchIndex[nodeIndex];
4432     m->tiProbsScratchIndex[nodeIndex] = temp;
4433 }
4434
4435
4436 void FreeChainMemory (void)
4437 {
4438     int         i, j, k, nRateCats;
4439     ModelInfo   *m;
4440
4441     /* free model variables for Gibbs gamma */
4442     for (i=0; i<numCurrentDivisions; i++)
4443         {
4444         if (modelSettings[i].gibbsGamma == YES)
4445             {
4446             if (modelSettings[i].pInvar != NULL)
4447                 nRateCats = modelSettings[i].numGammaCats + 1;
4448             else
4449                 nRateCats = modelSettings[i].numGammaCats;
4450             for (j=0; j<numLocalChains; j++)
4451                 {
4452                 for (k=0; k<nRateCats; k++)
4453                     {
4454                     free(modelSettings[i].catLnScaler[j][k]);
4455                     free(modelSettings[i].catLike[j][k]);
4456                     }
4457                 free (modelSettings[i].catLnScaler[j]);
4458                 free (modelSettings[i].catLike[j]);
4459                 }
4460             free (modelSettings[i].tiIndex);
4461             free (modelSettings[i].catLike);
4462             free (modelSettings[i].catLnScaler);
4463             }
4464         }
4465
4466     /* free parsimony sets and node lens */
4467     for (i=0; i<numCurrentDivisions; i++)
4468         {
4469         m = &modelSettings[i];
4470         if (m->parsSets)
4471             {
4472             for (j=0; j<m->numParsSets; j++)
4473                 free (m->parsSets[j]);
4474             free (m->parsSets);
4475             m->parsSets = NULL;
4476             }
4477         if (m->parsNodeLens)
4478             {
4479             free(m->parsNodeLens);
4480             m->parsNodeLens = NULL;
4481             }
4482         }
4483
4484     /* free model variables for conditional likelihoods */
4485     for (i=0; i<numCurrentDivisions; i++)
4486         {
4487         m = &modelSettings[i];
4488         if (m->condLikes)
4489             {
4490             for (j=0; j<m->numCondLikes; j++)
4491                 {
4492 #   if defined (SSE_ENABLED)
4493                 if (m->useSSE == YES)
4494                     AlignedSafeFree ((void **)(&m->condLikes[j]));
4495                 else
4496                     free (m->condLikes[j]);
4497 #   else
4498                 free (m->condLikes[j]);
4499 #   endif
4500                 }
4501             free (m->condLikes);
4502             m->condLikes = NULL;
4503             }
4504
4505         if (m->scalers)
4506             {
4507             for (j=0; j<m->numScalers; j++)
4508 #   if defined (SSE_ENABLED)
4509             if (m->useSSE == YES)
4510                 AlignedSafeFree ((void **)(&m->scalers[j]));
4511             else
4512                 free (m->scalers[j]);
4513 #   else
4514                 free (m->scalers[j]);
4515
4516 #   endif
4517             free (m->scalers);
4518             m->scalers = NULL;
4519             }
4520
4521         if (m->clP)
4522             {
4523             free (m->clP);
4524             m->clP = NULL;
4525             }
4526 #   if defined (SSE_ENABLED)
4527         if (m->useSSE == YES)
4528             {
4529             if (m->clP_SSE)
4530                 {
4531                 free (m->clP_SSE);
4532                 m->clP_SSE = NULL;
4533                 }
4534             if (m->lnL_SSE)
4535                 AlignedSafeFree ((void **)(&m->lnL_SSE));
4536             if (m->lnLI_SSE)
4537                 AlignedSafeFree ((void **)(&m->lnLI_SSE));
4538             }
4539 #   endif
4540
4541         if (m->tiProbs)
4542             {
4543             for (j=0; j<m->numTiProbs; j++)
4544                 free (m->tiProbs[j]);
4545             free (m->tiProbs);
4546             m->tiProbs = NULL;
4547             }
4548                 
4549         if (m->cijks)
4550             {
4551             for (j=0; j<numLocalChains+1; j++)
4552                 free (m->cijks[j]);
4553             free (m->cijks);
4554             m->cijks = NULL;
4555             }
4556
4557         if (m->condLikeIndex)
4558             {
4559             for (j=0; j<numLocalChains; j++)
4560                 free (m->condLikeIndex[j]);
4561             free (m->condLikeIndex);
4562             m->condLikeIndex = NULL;
4563             }
4564
4565         if (m->condLikeScratchIndex)
4566             {
4567             free (m->condLikeScratchIndex);
4568             m->condLikeScratchIndex=NULL;
4569             }
4570
4571         if (m->tiProbsIndex)
4572             {
4573             for (j=0; j<numLocalChains; j++)
4574                 free (m->tiProbsIndex[j]);
4575             free (m->tiProbsIndex);
4576             m->tiProbsIndex = NULL;
4577             }
4578         if (m->tiProbsScratchIndex)
4579             {
4580             free (m->tiProbsScratchIndex);
4581             m->tiProbsScratchIndex = NULL;
4582             }
4583         if (m->nodeScalerIndex)
4584             {
4585             for (j=0; j<numLocalChains; j++)
4586                 free (m->nodeScalerIndex[j]);
4587             free (m->nodeScalerIndex);
4588             m->nodeScalerIndex = NULL;
4589             }
4590         if (m->nodeScalerScratchIndex)
4591             {
4592             free (m->nodeScalerScratchIndex);
4593             m->nodeScalerScratchIndex = NULL;
4594             }
4595         if (m->scalersSet)
4596             {
4597             for (j=0; j<numLocalChains; j++)
4598                 free (m->scalersSet[j]);
4599             free (m->scalersSet);
4600             m->scalersSet = NULL;
4601             }
4602         if (m->scalersSetScratch)
4603             {
4604             free (m->scalersSetScratch);
4605             m->scalersSetScratch = NULL;
4606             }
4607         if (m->siteScalerIndex)
4608             {
4609             free (m->siteScalerIndex);
4610             m->siteScalerIndex = NULL;
4611             }
4612         if (m->cijkIndex)
4613             {
4614             free (m->cijkIndex);
4615             m->cijkIndex = NULL;
4616             }
4617         if (m->ancStateCondLikes)
4618             {
4619             free (m->ancStateCondLikes);
4620             m->ancStateCondLikes = NULL;
4621             }
4622
4623 #   if defined (BEAGLE_ENABLED)
4624         if (m->useBeagle == NO)
4625             continue;
4626
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));
4638
4639         m->isScalerNodeScratch += numLocalTaxa;
4640         SafeFree((void **)&(m->isScalerNodeScratch)); 
4641         for (j=0; j<numLocalChains; j++)
4642             {
4643             m->isScalerNode[j] += numLocalTaxa;
4644             SafeFree((void **)&(m->isScalerNode[j]));
4645             }
4646         SafeFree((void **)(&m->isScalerNode));
4647
4648         SafeFree((void **)(&m->beagleComputeCount));
4649         SafeFree((void **)(&m->succesCount));
4650         SafeFree((void **)(&m->rescaleFreq));
4651
4652 #   endif
4653         }
4654
4655     if (memAllocs[ALLOC_CURLNL] == YES) /*alloc in RunChain()*/
4656         {
4657         free (maxLnL0); 
4658         free (curLnL);
4659         memAllocs[ALLOC_CURLNL] = NO;
4660         }
4661     if (memAllocs[ALLOC_SS] == YES) /*alloc in mcmc()*/
4662         {
4663         free (marginalLnLSS);
4664         free (stepScalerSS);
4665         free (stepAcumulatorSS);
4666         free (splitfreqSS);
4667         memAllocs[ALLOC_SS] = NO;
4668         }
4669     if (memAllocs[ALLOC_CURLNPR] == YES) /*alloc in RunChain()*/
4670         {
4671         free (curLnPr); 
4672         memAllocs[ALLOC_CURLNPR] = NO;
4673         }
4674     if (memAllocs[ALLOC_CHAINID] == YES) /*alloc in RunChain()*/
4675         {
4676         free (chainId); 
4677         memAllocs[ALLOC_CHAINID] = NO;
4678         }
4679     if (memAllocs[ALLOC_USEDMOVES] == YES) /*alloc in setUsedMoves()*/
4680         {
4681         free (usedMoves);
4682         memAllocs[ALLOC_USEDMOVES] = NO;
4683         }
4684     if (memAllocs[ALLOC_TERMSTATE] == YES) /*alloc in SetUpTermState()*/
4685         {
4686         free (termState);
4687         termState = NULL;  
4688         memAllocs[ALLOC_TERMSTATE] = NO;
4689         }
4690     if (memAllocs[ALLOC_ISPARTAMBIG] == YES) /*alloc in SetUpTermState()*/
4691         {
4692         free (isPartAmbig);
4693         isPartAmbig = NULL;
4694         memAllocs[ALLOC_ISPARTAMBIG] = NO;
4695         }
4696     if (memAllocs[ALLOC_PRELIKES] == YES) /*alloc in InitCondLike()*/
4697         {
4698         free (preLikeL);
4699         preLikeL = NULL;
4700         memAllocs[ALLOC_PRELIKES] = NO;
4701         }
4702     if (memAllocs[ALLOC_RATEPROBS] == YES) /*alloc in InitAdGamma() */
4703         {
4704         free (rateProbSpace);
4705         free (rateProbs);
4706         rateProbs = NULL;
4707         memAllocs[ALLOC_RATEPROBS] = NO;
4708         }
4709     if (memAllocs[ALLOC_SITEJUMP] == YES) /*alloc in InitAdGamma() */
4710         {
4711         free (siteJump);
4712         siteJump = NULL;
4713         memAllocs[ALLOC_SITEJUMP] = NO;
4714         }
4715     if (memAllocs[ALLOC_MARKOVTIS] == YES)  /*alloc in InitAdGamma() */
4716         {
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;
4722         }
4723     if (memAllocs[ALLOC_SWAPINFO] == YES) /*alloc in RunChain()*/
4724         {
4725         for (i=0; i<chainParams.numRuns; i++)
4726             FreeSquareIntegerMatrix(swapInfo[i]);
4727         free (swapInfo);
4728         memAllocs[ALLOC_SWAPINFO] = NO;
4729         }
4730     if (memAllocs[ALLOC_POSSELPROBS] == YES) /*alloc in PrintStates() <- RunChain()*/
4731         {
4732         free (posSelProbs);
4733         memAllocs[ALLOC_POSSELPROBS] = NO;
4734         }
4735     if (memAllocs[ALLOC_PFCOUNTERS] == YES) /*alloc in SetUpParitionCounters() <- RunChain()*/
4736         {
4737         free (partition[0]);
4738         free (partition);
4739         for (i=0; i<numTopologies; i++)
4740             Tfree (partFreqTreeRoot[i]);
4741         free (partFreqTreeRoot);
4742         memAllocs[ALLOC_PFCOUNTERS] = NO;
4743         }
4744     if (memAllocs[ALLOC_FILEPOINTERS] == YES) /* alloc in (PreparePrintFiles(), ReusePreviousResults()) <- RunChain() */
4745         {
4746         CloseMBPrintFiles ();
4747         if (fpTree != NULL)
4748             {
4749             free (fpTree[0]);
4750             free (fpTree);
4751             }
4752         if (fpParm != NULL)
4753             free (fpParm);
4754         fpParm = NULL;
4755         fpTree = NULL;
4756         fpMcmc = NULL;
4757         fpSS = NULL;
4758         memAllocs[ALLOC_FILEPOINTERS] = NO;
4759         }
4760     if (memAllocs[ALLOC_STATS] == YES) /* alloc in RunChain() */
4761         {
4762         if (chainParams.allComps == YES)
4763             {
4764             for (i=0; i<numTopologies; i++)
4765                 FreeSquareDoubleMatrix (chainParams.stat[i].pair);
4766             }
4767         free (chainParams.stat);
4768         memAllocs[ALLOC_STATS] = NO;
4769         }
4770     if (memAllocs[ALLOC_DIAGNTREE] == YES)
4771         {
4772         FreeTree (chainParams.dtree);
4773         memAllocs[ALLOC_DIAGNTREE] = NO;
4774         }
4775     if (memAllocs[ALLOC_PRINTPARAM] == YES)
4776         {
4777         free (printParam);
4778         free (topologyPrintIndex);
4779         memAllocs[ALLOC_PRINTPARAM] = NO;
4780         }
4781     if (memAllocs[ALLOC_TFILEPOS] == YES)
4782         {
4783         free (chainParams.tFilePos);
4784         chainParams.tFilePos = NULL;
4785         memAllocs[ALLOC_TFILEPOS] = NO;
4786         }
4787     if (memAllocs[ALLOC_TREELIST] == YES)
4788         {
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;
4794         }
4795     if (memAllocs[ALLOC_BEST] == YES)
4796         {
4797         FreeBestChainVariables();
4798         memAllocs[ALLOC_BEST] = NO;
4799         }
4800 }
4801
4802
4803 MrBFlt GetFitchPartials (ModelInfo *m, int chain, int source1, int source2, int destination)
4804 {
4805     int         c, i;
4806     BitsLong    x[2], *pS1, *pS2, *pD;
4807     MrBFlt      length = 0.0;
4808     CLFlt       *nSitesOfPat;
4809     
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);
4814
4815     /* find parsimony sets for the nodes */
4816     pS1 = m->parsSets[source1    ];
4817     pS2 = m->parsSets[source2    ];
4818     pD  = m->parsSets[destination];
4819         
4820     /* Find number of site patterns */
4821     nSitesOfPat = numSitesOfPat + ((1 % chainParams.numChains) * numCompressedChars) + m->compCharStart;//chainId[chain]
4822
4823     if (m->nParsIntsPerSite == 1)
4824         {
4825         for (c=0; c<m->numChars; c++)
4826             {
4827             x[0] = pS1[c] & pS2[c];
4828             if (x[0] == 0)
4829                 {
4830                 length += nSitesOfPat[c];
4831                 x[0] = pS1[c] | pS2[c];
4832                 }
4833             pD[c] = x[0];
4834             }
4835         }
4836     else /* if (m->nParsIntsPerSite == 2) */
4837         {
4838         assert (m->nParsIntsPerSite == 2);
4839         for (c=i=0; c<m->numChars; c++)
4840             {
4841             x[0] = pS1[i]   & pS2[i];
4842             x[1] = pS1[i+1] & pS2[i+1];
4843             if ((x[0] | x[1]) == 0)
4844                 {
4845                 length += nSitesOfPat[c];
4846                 x[0] = pS1[i]   | pS2[i];
4847                 x[1] = pS1[i+1] | pS2[i+1];
4848                 }
4849             pD[i++] = x[0];
4850             pD[i++] = x[1];
4851             }
4852         }
4853
4854     return length;
4855     MrBayesPrint ("%d", chain); /* just because I am tired of seeing the unused parameter error msg */
4856 }
4857
4858
4859 MrBFlt GetParsDP (Tree *t, TreeNode *p, int chain)
4860 {
4861     int             n, division;
4862     MrBFlt          length;
4863     ModelInfo       *m;
4864
4865     length = 0.0;
4866     if (p->left != NULL)
4867         {
4868         length += GetParsDP (t, p->left, chain);
4869         length += GetParsDP (t, p->right, chain);
4870
4871         for (n=0; n<t->nRelParts; n++)
4872             {
4873             division = t->relParts[n];
4874             
4875             /* Find model settings */
4876             m = &modelSettings[division];
4877
4878             /* Get Fitch partials and length */
4879             length += GetFitchPartials(m,
4880                                        chain,
4881                                        p->left->index,
4882                                        p->right->index,
4883                                        p->index);
4884             }
4885         }
4886
4887     return length;
4888 }
4889
4890
4891 void GetParsFP (Tree *t, TreeNode *p, int chain)
4892 {
4893     int             i, c, n, division;
4894     BitsLong        *pL, *pR, *pP, *pA, x[2];
4895     ModelInfo       *m;
4896
4897     if (p->left != NULL)
4898         {
4899         for (n=0; n<t->nRelParts; n++)
4900             {
4901             division = t->relParts[n];
4902             
4903             /* Find model settings */
4904             m = &modelSettings[division];
4905             assert (m->nParsIntsPerSite == 1 || m->nParsIntsPerSite == 2);
4906
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  ];
4912             
4913             if (m->nParsIntsPerSite == 1)
4914                 {
4915                 for (c=0; c<m->numChars; c++)
4916                     {
4917                     x[0] = pP[c] & pA[c];
4918
4919                     if (x[0] != 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. */
4926                         else
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 */
4931                         }
4932                     pP[c] = x[0];
4933                     }
4934                 }
4935             else /* if (m->nParsIntsPerSite == 2) */
4936                 {
4937                 for (c=i=0; c<m->numChars; c++)
4938                     {
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])
4942                         {
4943                         x[0] = pL[i] & pR[i];
4944                         x[1] = pL[i+1] & pR[i+1];
4945                         if ((x[0] | x[1]) != 0)
4946                             {
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] ;
4949                             }
4950                         else
4951                             {
4952                             x[0] = pP[i] | pA[i];
4953                             x[1] = pP[i+1] | pA[i+1];
4954                             }
4955                         }
4956                     pP[i++] = x[0];
4957                     pP[i++] = x[1];
4958                     }
4959                 }
4960             }
4961         GetParsFP (t, p->left, chain);
4962         GetParsFP (t, p->right, chain);
4963         }
4964 }
4965
4966
4967 int GetParsimonyBrlens (Tree *t, int chain, MrBFlt *brlens)
4968 {
4969     int             c, i, j, n, division;
4970     BitsLong        *pP, *pA;
4971     CLFlt           *nSitesOfPat;
4972     TreeNode        *p;
4973     ModelInfo       *m;
4974
4975     /* Reset all brlens */
4976     for (i=0; i<t->nNodes-1; i++)
4977         brlens[i] = 0.0;
4978     
4979     /* Get final parsimony state sets */
4980     GetParsDP(t, t->root->left, chain);
4981     GetParsFP(t, t->root, chain);
4982     
4983     /* Get all branch lengths, looping over divisions */
4984     for (n=0; n<t->nRelParts; n++)      
4985         {
4986         division = t->relParts[n];
4987
4988         /* Find model settings */
4989         m = &modelSettings[division];
4990
4991         /* Find number of site patterns */
4992         nSitesOfPat = numSitesOfPat + ((chainId[chain] % chainParams.numChains) * numCompressedChars) + m->compCharStart;
4993
4994         /* Record branch lengths in downpass */
4995         for (i=0; i<t->nNodes-1; i++)
4996             {
4997             p = t->allDownPass[i];
4998
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];
5002             
5003             if (m->nParsIntsPerSite == 1)
5004                 {
5005                 for (c=0; c<m->numChars; c++)
5006                     {
5007                     if ((pP[c] & pA[c]) == 0)
5008                         brlens[i] += nSitesOfPat[c];
5009                     }
5010                 }
5011             else
5012                 {
5013                 for (c=j=0; c<m->numChars; c++, j+=2)
5014                     {
5015                     if ((pP[j] & pA[j]) == 0 && (pP[j+1] & pA[j+1]) == 0)
5016                         brlens[i] += nSitesOfPat[c];
5017                     }
5018                 }
5019             }
5020         }
5021
5022     return (NO_ERROR);
5023 }
5024
5025
5026 MrBFlt GetParsimonyLength (Tree *t, int chain)
5027 {
5028     int             c, i, n, division;
5029     BitsLong        *pP, *pA;
5030     CLFlt           *nSitesOfPat;
5031     MrBFlt          length;
5032     TreeNode        *p;
5033     ModelInfo       *m;
5034
5035     /* Get length down to internal root */
5036     length = GetParsDP(t, t->root->left, chain);
5037
5038     /* return if rooted */
5039     if (t->isRooted == NO)
5040         return length;
5041
5042     /* add in the last terminal if not rooted */
5043     for (n=0; n<t->nRelParts; n++)      
5044         {
5045         division = t->relParts[n];
5046
5047         /* Find model settings */
5048         m = &modelSettings[division];
5049
5050         /* Find number of site patterns */
5051         nSitesOfPat = numSitesOfPat + ((chainId[chain] % chainParams.numChains) * numCompressedChars) + m->compCharStart;
5052
5053         /* Deal with last branch */
5054         p = t->intDownPass[t->nIntNodes-1];
5055
5056         /* find downpass parsimony sets for the node and its environment */
5057         pP    = m->parsSets[p->index     ];
5058         pA    = m->parsSets[p->anc->index];
5059         
5060         if (m->nParsIntsPerSite == 1)
5061             {
5062             for (c=0; c<m->numChars; c++)
5063                 {
5064                 if ((pP[c] & pA[c]) == 0)
5065                     {
5066                     length += nSitesOfPat[c];
5067                     }
5068                 }
5069             }
5070         else /* if (m->nParsIntsPerSite == 2) */
5071             {
5072             for (c=i=0; c<m->numChars; c++, i+=2)
5073                 {
5074                 if ((pP[i] & pA[i]) == 0 && (pP[i+1] & pA[i+1]) == 0)
5075                     {
5076                     length += nSitesOfPat[c];
5077                     }
5078                 }
5079             }
5080         }
5081
5082     return length;
5083 }
5084
5085
5086 void GetParsimonySubtreeRootstate (Tree *t, TreeNode *root, int chain)
5087 {
5088     int             c, i, n, division;
5089     BitsLong        *pD, *pP, *pA, x[2];
5090     TreeNode        *p;
5091     ModelInfo       *m;
5092
5093     /* Loop over divisions */
5094     for (n=0; n<t->nRelParts; n++)
5095         {
5096         division = t->relParts[n];
5097             
5098         /* Find model settings */
5099         m = &modelSettings[division];
5100         assert (m->nParsIntsPerSite == 1 || m->nParsIntsPerSite == 2);
5101
5102         for (i=0; i<t->nNodes; i++)
5103             {
5104             p = t->allDownPass[i];
5105             p->marked = NO;
5106             }
5107
5108         p = root;
5109         while (p->anc != NULL)
5110             {
5111             p->marked = YES;
5112             p = p->anc;
5113             }
5114
5115         /* Make uppass node by node */
5116         for (i=t->nIntNodes-1; i>=0; i--)
5117             {
5118             p = t->intDownPass[i];
5119
5120             /* continue if no work needs to be done */
5121             if (p->marked == NO)
5122                 continue;
5123
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];
5128             else
5129                 pD = m->parsSets[p->left->index ];
5130             pA     = m->parsSets[p->anc->index  ];
5131             
5132             if (m->nParsIntsPerSite == 1)
5133                 {
5134                 for (c=0; c<m->numChars; c++)
5135                     {
5136                     x[0] = pD[c] & pA[c];
5137                     if (x[0] == 0)
5138                         {
5139                         x[0] = (pD[c] | pA[c]);
5140                         }
5141                     pP[c] = x[0];
5142                     }
5143                 }
5144             else if (m->nParsIntsPerSite == 2)
5145                 {
5146                 for (c=i=0; c<m->numChars; c++, i+=2)
5147                     {
5148                     x[0] = pD[i  ] & pA[i  ];
5149                     x[1] = pD[i+1] & pA[i+1];
5150                     if (x[0] + x[1] == 0)
5151                         {
5152                         x[0] = (pD[i  ] | pA[i  ]);
5153                         x[1] = (pD[i+1] | pA[i+1]);
5154                         }
5155                     pP[i  ] = x[0];
5156                     pP[i+1] = x[1];
5157                     }
5158                 }
5159             if (p == root)
5160                 break;
5161             }
5162         }
5163
5164     return;
5165     MrBayesPrint ("%d", chain); /* just because I am tired of seeing the unused parameter error msg */
5166 }
5167
5168
5169 /* GetRate: retrieve the base rate for the division and chain in current state */
5170 MrBFlt GetRate (int division, int chain)
5171 {
5172     Param   *p;
5173     MrBFlt  *values, rate;
5174     int     i;
5175
5176     rate = 0.0;
5177
5178     p = modelSettings[division].rateMult;
5179     values = GetParamVals (p, chain, state[chain]);
5180     if (p->nValues == 1)
5181         rate = values[0];
5182     else
5183         {
5184         for (i=0; i<p->nRelParts; i++)
5185             {
5186             if (p->relParts[i] == division)
5187                 {
5188                 rate = values[i];
5189                 break;
5190                 }
5191             }
5192         }
5193
5194     p = modelSettings[division].geneTreeRateMult;
5195     if (p != NULL)
5196         {
5197         values = GetParamVals (p, chain, state[chain]);
5198         for (i=0; i<p->nRelParts; i++)
5199             {
5200             if (p->relParts[i] == division)
5201                 {
5202                 rate *= values[i];
5203                 break;
5204                 }
5205             }
5206         }
5207     
5208     return rate;
5209 }
5210
5211
5212 void GetStamp (void)
5213 {
5214     int     i;
5215
5216     for (i=0; i<10; i++)
5217         stamp[i] = '0' + (int)(RandomNumber(&runIDSeed) * 10);
5218     stamp[10] = '\0';
5219
5220     MrBayesPrint ("%s   MCMC stamp = %s\n", spacer, stamp);
5221 }
5222
5223
5224 void GetSwappers (int *swapA, int *swapB, int run)
5225 {
5226     int         i;
5227     
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)
5231
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;
5238
5239 #   else
5240
5241     if (chainParams.swapAdjacentOnly == NO)
5242         {
5243         (*swapA) = (int) (RandomNumber(&swapSeed) * chainParams.numChains);
5244         (*swapB) = (int) (RandomNumber(&swapSeed) * (chainParams.numChains - 1));
5245         if ((*swapB) == (*swapA))
5246             (*swapB) = chainParams.numChains - 1;
5247         }
5248     else
5249         {
5250         (*swapA) = (int) (RandomNumber(&swapSeed) * (chainParams.numChains - 1));
5251         (*swapB) = (*swapA) + 1;
5252         }
5253 #   endif
5254
5255     i = run * chainParams.numChains;
5256     (*swapA) += i;
5257     (*swapB) += i;
5258
5259     return;
5260 }
5261
5262
5263 void GetTempDownPassSeq (TreeNode *p, int *i, TreeNode **dp)
5264 {
5265     if (p != NULL)
5266         {
5267         GetTempDownPassSeq (p->left,  i, dp);
5268         GetTempDownPassSeq (p->right, i, dp);
5269         dp[(*i)++] = p;
5270         }
5271 }
5272
5273
5274 MrBFlt GibbsSampleGamma (int chain, int division, RandLong *seed)
5275 {
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;
5280     ModelInfo       *m;
5281     Tree            *t;
5282     TreeNode        *p;
5283
5284     m = &modelSettings[division];
5285
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];
5291
5292     /* find tree scaler */
5293     lnScaler = m->scalers[m->siteScalerIndex[chain]];
5294     
5295     /* find category like array and associated sccaler */
5296     catLike = m->catLike[chain];
5297     catLnScaler = m->catLnScaler[chain];
5298     
5299     /* find rate category index */
5300     rateCat = m->tiIndex + chain*m->numChars;
5301     
5302     /* find number of rate cats and gamma cats */
5303     nRateCats = nGammaCats = m->numGammaCats;
5304     if (m->pInvar != NULL)
5305         nRateCats++;
5306
5307     /* find tree */
5308     t = GetTree (m->brlens, chain, state[chain]);
5309
5310     /* find invar cond likes (if we have invariable rate category) */
5311     clInvar = m->invCondLikes;
5312
5313     /* get pInvar */
5314     if (m->pInvar == NULL)
5315         pInvar = 0.0;
5316     else
5317         pInvar = (CLFlt) *GetParamVals (m->pInvar, chain, state[chain]);
5318     freq = ((CLFlt)1.0 - pInvar) / nGammaCats;
5319
5320     /* get chain temperature */
5321     temp = Temperature (chainId[chain]);
5322     id = chainId[chain] % chainParams.numChains;
5323
5324     /* calculate rate probs */
5325     for (k=0; k<nGammaCats; k++)
5326         {
5327         FlipSiteScalerSpace(m, chain);
5328         ResetSiteScalers(m, chain);
5329         for (c=0; c<m->numChars; c++)
5330             rateCat[c] = k;
5331         for (i=0; i<t->nIntNodes; i++)
5332             {
5333             p = t->intDownPass[i];
5334             if (t->isRooted == NO && p->anc->anc == NULL)
5335                 m->CondLikeRoot (p, division, chain);
5336             else
5337                 m->CondLikeDown (p, division, chain);
5338             if (p->scalerNode == YES)
5339                 m->CondLikeScaler (p, division, chain);
5340             }
5341         /* find root conditional likes */
5342         p = t->root->left;
5343         clRoot = m->condLikes[m->condLikeIndex[chain][p->index]];
5344         for (c=0; c<m->numChars; c++)
5345             {
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];
5351             clRoot += nStates;
5352             }
5353         FlipSiteScalerSpace(m, chain);
5354         }
5355
5356     /* fill in the invar cond likes if needed */
5357     if (m->pInvar != NULL)
5358         {
5359         k = nGammaCats;
5360         for (c=0; c<m->numChars; c++)
5361             {
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;
5366             clInvar += nStates;
5367             catLnScaler[k][c] = 0.0;
5368             }
5369         }
5370
5371     /* Now Gibbs sample the rate categories */
5372     for (c=0; c<m->numChars; c++)
5373         {
5374         /* find max scaler */
5375         maxLnScaler = catLnScaler[0][c];
5376         for (k=1; k<nRateCats; k++)
5377             {
5378             if (catLnScaler[k][c] > maxLnScaler && catLike[k][c] > 0.0)
5379                 maxLnScaler = catLnScaler[k][c];
5380             }
5381         /* scale values */
5382         for (k=0; k<nRateCats; k++)
5383             {
5384             f = catLnScaler[k][c] - maxLnScaler;
5385             if (f < -100.0)
5386                 catLike[k][c] = 0.0;
5387             else
5388                 {
5389                 catLike[k][c] *= (CLFlt) exp (f);
5390                 /* take the temperature into account */
5391                 if (id != 0)
5392                     catLike[k][c] = (CLFlt) pow(catLike[k][c], temp);
5393                 }
5394             }
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++)
5401             {
5402             if (ran < catLike[k][c])
5403                 break;
5404             }
5405         rateCat[c] = k;
5406         }
5407
5408     /* recalculate everything */
5409     FlipSiteScalerSpace(m, chain);
5410     ResetSiteScalers(m, chain);
5411     for (i=0; i<t->nIntNodes; i++)
5412         {
5413         p = t->intDownPass[i];
5414         if (t->isRooted == NO && p->anc->anc == NULL)
5415             m->CondLikeRoot (p, division, chain);
5416         else
5417             m->CondLikeDown (p, division, chain);
5418         if (p->scalerNode == YES)
5419             m->CondLikeScaler (p, division, chain);
5420         }
5421     lnL = 0.0;
5422     m->Likelihood (t->root->left, division, chain, &lnL, (chainId[chain] % chainParams.numChains));
5423     
5424     deltaLnL = lnL - m->lnLike[2*chain + state[chain]];
5425     m->lnLike[2*chain + state[chain]] =  lnL;
5426
5427     return (deltaLnL);
5428 }
5429
5430
5431 /*------------------------------------------------------------------------
5432 |
5433 |   InitAdGamma: initialize variables for adgamma model.
5434 |
5435 -------------------------------------------------------------------------*/
5436 int InitAdGamma (void)
5437 {
5438     int         d, c, i, j, k, maxRates, *corrModel;
5439     ModelInfo   *m;
5440     
5441     /* take care of adgamma model */
5442     if (chainHasAdgamma == NO)
5443         return (NO_ERROR);
5444     
5445     MrBayesPrint ("%s   Initializing autocorrelated discrete gamma model\n", spacer);
5446     
5447     /* allocate corr space */
5448     corrModel = (int *) SafeCalloc (numCurrentDivisions, sizeof(int));
5449     if (!corrModel)
5450         return ERROR;
5451     
5452     /* allocate siteJump */
5453     if (memAllocs[ALLOC_SITEJUMP] == YES)
5454         {
5455         MrBayesPrint ("%s   siteJump not free in InitAdGamma\n", spacer);
5456         free (corrModel);
5457         return ERROR;
5458         }
5459     siteJump = (int *) SafeCalloc (numChar, sizeof(int));
5460     if (siteJump)
5461         memAllocs[ALLOC_SITEJUMP] = YES;
5462     else
5463         {
5464         MrBayesPrint ("%s   Problem allocating siteJump in InitAdGamma (%d ints)\n", spacer, numChar);
5465         free (corrModel);
5466         return ERROR;
5467         }
5468     
5469     /* reset vector indicating the matrices needed */
5470     for (i=0; i<MAX_SMALL_JUMP; i++)
5471         hasMarkovTi[i] = NO;
5472     
5473     /* fill in siteJump */
5474     for (i=0; i<numCurrentDivisions; i++)
5475         corrModel[i] = 0;
5476
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;
5481
5482     for (d=0; d<numCurrentDivisions; d++)
5483         {
5484         m = &modelSettings[d];
5485         
5486         if (m->correlation == NULL || m->mark == YES)
5487             continue;
5488         
5489         m->mark = YES;
5490         for (i=0; i<m->correlation->nRelParts; i++)
5491             {
5492             if (modelSettings[m->correlation->relParts[i]].shape == 
5493                 modelSettings[d].shape)
5494                 {
5495                 modelSettings[m->correlation->relParts[i]].mark = YES;
5496                 corrModel[m->correlation->relParts[i]] = k;
5497                 }
5498             }
5499         k++;
5500
5501         if (m->numGammaCats > maxRates)
5502             maxRates = m->numGammaCats;
5503
5504         }
5505
5506     for (c=0; c<numChar; c++)
5507         {
5508         if (charInfo[c].isExcluded == YES)
5509             continue;
5510         
5511         if ((k=corrModel[partitionId[c][partitionNum] - 1]) == 0)
5512             continue;
5513
5514         /* How far back is last char in this HMM? */
5515         for (j=c-1; j>=0; j--)
5516             {
5517             if (corrModel[partitionId[j][partitionNum] - 1] == k)
5518                 break;
5519             }
5520
5521         if (j<0)
5522             siteJump[c] = 0;
5523         else if (charInfo[j].bigBreakAfter == YES)
5524             siteJump[c] = BIG_JUMP;
5525         else
5526             {
5527             siteJump[c] = c - j;
5528             hasMarkovTi[c-j-1] = YES;
5529             }
5530         }
5531
5532     /* check if any HMM is empty */
5533     k=0;
5534     for (i=0; i<numCurrentDivisions; i++)
5535         {
5536         if (corrModel[i] > k)
5537             k = corrModel[i];
5538         }
5539     for (i=1; i<=k; i++)
5540         {
5541         for (c=j=0; c<numChar; c++)
5542             {
5543             if (charInfo[c].isExcluded == NO && corrModel[partitionId[c][partitionNum] - 1] == i)
5544                 j = c;
5545             }
5546         if (j == 0)
5547             {
5548             MrBayesPrint ("%s   ERROR: HMM model %d is empty.\n",spacer,i);
5549             free (corrModel);
5550             return (ERROR);
5551             }
5552         }
5553
5554     /* allocate MarkovTis (space needed for calculations) */
5555     if (memAllocs[ALLOC_MARKOVTIS] == YES)
5556         {
5557         MrBayesPrint ("%s   markovTis not free in InitAdGamma\n", spacer);
5558         free (corrModel);
5559         return ERROR;
5560         }
5561
5562     for (i=0; i<MAX_SMALL_JUMP; i++)
5563         {
5564         if (hasMarkovTi[i] == YES || i == 0)    /* base matrix always needed */
5565             {
5566             markovTi[i] = AllocateSquareDoubleMatrix(maxRates);
5567             if (markovTi[i] == NULL)
5568                 break;
5569             }
5570         else
5571             markovTi[i] = NULL;
5572         }
5573
5574     markovTiN = AllocateSquareDoubleMatrix(maxRates);
5575     if (i >= MAX_SMALL_JUMP && markovTiN)
5576         memAllocs[ALLOC_MARKOVTIS] = YES;
5577     else
5578         {
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);
5585         free (corrModel);
5586         return ERROR;
5587         }
5588
5589     /* allocate space for rateProbs needed by adgamma model */
5590
5591     /* calculate size needed */
5592     i = 0;
5593     for (j=0; j<numCurrentDivisions; j++)
5594         {
5595         m = &modelSettings[j];
5596         if (m->correlation != NULL)
5597             {
5598             m->rateProbStart = i;
5599             i += m->numGammaCats * m->numChars;
5600             }
5601         }
5602     rateProbRowSize = i;
5603
5604     /* allocate space */
5605     if (memAllocs[ALLOC_RATEPROBS] == YES)
5606         {
5607         MrBayesPrint ("%s   Space for rate probs not free in InitAdGamma\n", spacer);
5608         free (corrModel);
5609         return ERROR;
5610         }
5611     rateProbSpace = (MrBFlt *) SafeMalloc (2 * numLocalChains * rateProbRowSize * sizeof(MrBFlt));
5612     rateProbs = (MrBFlt **) SafeMalloc (numLocalChains * sizeof(MrBFlt *));
5613     if (!rateProbSpace || !rateProbs)
5614         {
5615         MrBayesPrint ("%s   Problem allocating rate probs\n", spacer);
5616         if (rateProbSpace) 
5617             free (rateProbSpace);
5618         if (rateProbs) 
5619             free (rateProbs);
5620         free (corrModel);
5621         return ERROR;
5622         }
5623     else
5624         memAllocs[ALLOC_RATEPROBS] = YES;
5625
5626     /* set chain rateProbs pointers */
5627     for (i=j=0; i<numLocalChains; i++)
5628         {
5629         rateProbs[i] = rateProbSpace + j;
5630         j += 2 * rateProbRowSize;
5631         }
5632
5633     free (corrModel);
5634
5635     return (NO_ERROR);
5636 }
5637
5638
5639 /*------------------------------------------------------------------------
5640 |
5641 |   InitAugmentedModels: allocate and initialize space for augmented
5642 |      models
5643 |
5644 -------------------------------------------------------------------------*/
5645 int InitAugmentedModels (void)
5646 {
5647     int         d, i, j, useAugmentedModels, nRateCats;
5648     ModelInfo   *m;
5649
5650     useAugmentedModels = NO;
5651     for (d=0; d<numCurrentDivisions; d++)
5652         {
5653         if (modelSettings[d].gibbsGamma == YES)
5654                 useAugmentedModels = YES;
5655         }
5656     
5657     if (useAugmentedModels == NO)
5658         return (NO_ERROR);
5659     
5660     MrBayesPrint ("%s   Initializing variables for model augmentation\n", spacer);
5661     
5662     for (d=0; d<numCurrentDivisions; d++)
5663         {
5664         m = &modelSettings[d];
5665         if (m->gibbsGamma == NO)
5666                 continue;
5667         m->tiIndex = (int *) SafeMalloc (numLocalChains * m->numChars * sizeof (int));
5668         if (!m->tiIndex)
5669             return ERROR;
5670         m->catLike = (CLFlt ***) SafeMalloc (numLocalChains * sizeof (CLFlt **));
5671         if (!m->catLike)
5672             return ERROR;
5673         m->catLnScaler = (CLFlt ***) SafeMalloc (numLocalChains * sizeof (CLFlt **));
5674         if (!m->catLnScaler)
5675             return ERROR;
5676         if (m->pInvar == NULL)
5677             nRateCats = m->numGammaCats;
5678         else
5679             nRateCats = m->numGammaCats + 1;
5680         for (i=0; i<numLocalChains; i++)
5681             {
5682             m->catLike[i] = (CLFlt **) SafeCalloc (nRateCats, sizeof (CLFlt *));
5683             if (!m->catLike[i])
5684                 return ERROR;
5685             m->catLnScaler[i] = (CLFlt **) SafeCalloc (nRateCats, sizeof (CLFlt *));
5686             if (!m->catLnScaler[i])
5687                 return ERROR;
5688             for (j=0; j<nRateCats; j++)
5689                 {
5690                 m->catLike[i][j] = (CLFlt *) SafeCalloc (m->numChars, sizeof (CLFlt));
5691                 if (!m->catLike[i][j])
5692                     return ERROR;
5693                 m->catLnScaler[i][j] = (CLFlt *) SafeCalloc (m->numChars, sizeof (CLFlt));
5694                 if (!m->catLnScaler[i][j])
5695                     return ERROR;
5696                 }
5697             }
5698         }
5699
5700     return NO_ERROR;
5701 }
5702
5703
5704 /*------------------------------------------------------------------------
5705 |
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.
5712 |
5713 -------------------------------------------------------------------------*/
5714 int InitChainCondLikes (void)
5715 {
5716     int         c, d, i, j, k, s, t, numReps, condLikesUsed, nIntNodes, nNodes, useBeagle,
5717                 clIndex, tiIndex, scalerIndex, indexStep;
5718     BitsLong    *charBits;
5719     CLFlt       *cL;
5720     ModelInfo   *m;
5721 #   if defined (SSE_ENABLED)
5722     int         j1;
5723 #   endif
5724 #   if defined (BEAGLE_ENABLED)
5725     double      *nSitesOfPat;
5726     MrBFlt      freq;
5727 #   endif
5728
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 */
5731     condLikesUsed = NO;
5732     for (d=0; d<numCurrentDivisions; d++)
5733         {
5734         m = &modelSettings[d];
5735
5736         MrBayesPrint ("%s   Division %d has %d unique site patterns\n", spacer, d+1, m->numChars);
5737
5738         /* initialize model settings for chain cond likes */
5739         m->condLikeLength = 0;
5740         m->numCondLikes = 0;
5741
5742         if (m->parsModelId == YES)
5743             continue;
5744
5745         condLikesUsed = YES;
5746
5747         /* figure out length of cond like array */
5748         if (m->dataType == STANDARD)
5749             {
5750 #   if defined (BEAGLE_ENABLED)
5751             m->useBeagle = NO;
5752 #   endif
5753             for (c=0; c<m->numChars; c++)
5754                 {
5755                 numReps = m->numGammaCats;
5756                 if (m->nStates[c] == 2)
5757                     numReps *= m->numBetaCats;
5758                 m->condLikeLength += m->nStates[c] * numReps;
5759                 }
5760             }
5761         else
5762             {
5763             if (m->gibbsGamma == YES)
5764                 m->condLikeLength = m->numChars * m->numModelStates;
5765             else
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)
5770                 {
5771                 if (m->printAncStates == YES || m->printSiteRates == YES || m->printPosSel ==YES || m->printSiteOmegas==YES)
5772                     {
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);
5775                     }                
5776                 else if (m->gibbsGamma == NO)
5777                     m->useBeagle = YES;
5778                 }
5779 #   endif
5780             }
5781         
5782         /* find size of tree */
5783         nIntNodes = GetTree(m->brlens, 0, 0)->nIntNodes;
5784         nNodes = GetTree(m->brlens, 0, 0)->nNodes;
5785
5786         /* figure out number of cond like arrays */
5787         m->numCondLikes = (numLocalChains + 1) * (nIntNodes);
5788         m->numCondLikes += numLocalTaxa;
5789         /*
5790 #   if !defined (DEBUG_NOSHORTCUTS)
5791         for (i=0; i<numLocalTaxa; i++)
5792             {
5793             if (m->isPartAmbig[i] == NO && m->dataType != STANDARD)
5794                 m->numCondLikes--;
5795             }
5796 #   endif
5797         */
5798
5799         /* figure out number of node and site scalers */
5800         m->numScalers = (numLocalChains + 1) * (nIntNodes + 1);   /* add 1 for site scalers */
5801
5802         /* figure out length of ti prob array and number of ti prob arrays */
5803         m->tiProbLength = 0;
5804         if (m->dataType == STANDARD)
5805             {
5806             m->numTiCats = 0;   /* We do not have repeated similar transition probability matrices */
5807             if (m->stateFreq->paramId == SYMPI_EQUAL)
5808                 {
5809                 for (k=0; k<9; k++)
5810                     {
5811                     if (m->isTiNeeded[k] == YES)
5812                         m->tiProbLength += (k + 2) * (k + 2) * m->numGammaCats;
5813                     }
5814                 for (k=9; k<13; k++)
5815                     {
5816                     if (m->isTiNeeded[k] == YES)
5817                         m->tiProbLength += (k - 6) * (k - 6) * m->numGammaCats;
5818                     }
5819                 for (k=13; k<18; k++)
5820                     {
5821                     if (m->isTiNeeded[k] == YES)
5822                          m->tiProbLength += (k - 11) * (k - 11) * m->numGammaCats;
5823                     }
5824                 }
5825             else
5826                 {
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++)
5831                     {
5832                     if (m->nStates[c] > 2 && (m->cType[c] == UNORD || m->cType[c] == ORD))
5833                         {
5834                         m->tiProbLength += (m->nStates[c] * m->nStates[c]) * m->numGammaCats;
5835                         }
5836                     }
5837                 }
5838             }
5839         else
5840             {
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;
5843             }
5844         m->numTiProbs = (numLocalChains + 1) * nNodes;
5845         
5846         /* set info about eigen systems */
5847         if (InitEigenSystemInfo (m) == ERROR)
5848             return (ERROR);
5849         }
5850
5851     /* check if conditional likelihoods are needed */
5852     if (condLikesUsed == YES)
5853         MrBayesPrint ("%s   Initializing conditional likelihoods\n", spacer);
5854     else
5855         return NO_ERROR;
5856
5857     /* allocate space and fill in info for tips */
5858     for (d=0; d<numCurrentDivisions; d++)
5859         {
5860         m = &modelSettings[d];
5861        
5862         /* allocate space for conditional likelihoods */
5863         useBeagle = NO;
5864 #   if defined (BEAGLE_ENABLED)
5865         if (m->useBeagle == YES)
5866             {
5867             if (InitBeagleInstance(m, d) != ERROR)
5868                 useBeagle = YES;
5869             else
5870                 m->useBeagle = NO;
5871             }
5872 #   endif
5873         //m->useSSE = NO;
5874 #   if defined (SSE_ENABLED)
5875         /*if (useBeagle == NO && m->dataType != STANDARD)
5876             m->useSSE = YES;*/
5877         if (useBeagle == YES)
5878             m->useSSE = NO;
5879
5880 #   endif
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);
5885
5886         if (useBeagle == NO)
5887             {
5888             /* allocate cond like space */
5889             m->condLikes = (CLFlt**) SafeMalloc(m->numCondLikes * sizeof(CLFlt*));
5890             if (!m->condLikes)
5891                 return (ERROR);
5892             for (i=0; i<m->numCondLikes; i++)
5893                 {
5894 #   if defined (SSE_ENABLED)
5895                 if (m->useSSE == YES)
5896                     {
5897                     /* calculate number SSE chars */
5898                     m->numSSEChars = ((m->numChars - 1) / FLOATS_PER_VEC) + 1;
5899
5900                     /* allocate space with padding (m->condLikeLength is without padding) */
5901                     if (m->gibbsGamma == YES)
5902                         numReps = 1;
5903                     else
5904                         numReps = m->numGammaCats * m->numOmegaCats;
5905                     k = m->numSSEChars * FLOATS_PER_VEC * m->numModelStates * numReps;
5906                     
5907                     m->condLikes[i] = (CLFlt*) AlignedMalloc (k * sizeof(CLFlt), 16);
5908                     if (!m->condLikes[i])
5909                         return (ERROR);
5910
5911                     /* start by filling all with 0.0f; pad when filling in tips */
5912                     for (j=0; j<k; j++)
5913                         m->condLikes[i][j] = 0.0f;
5914                     }
5915                 else
5916                     {
5917                     m->condLikes[i] = (CLFlt*) SafeMalloc(m->condLikeLength * sizeof(CLFlt));
5918                     if (!m->condLikes[i])
5919                         return (ERROR);
5920                     }
5921 #   else
5922                 m->condLikes[i] = (CLFlt*) SafeMalloc(m->condLikeLength * sizeof(CLFlt));
5923                 if (!m->condLikes[i])
5924                     return (ERROR);
5925 #   endif
5926                 }
5927
5928             /* allocate scaler space and pointers for scaling */
5929             m->scalers = (CLFlt**) SafeMalloc(m->numScalers * sizeof(CLFlt*));
5930             if (!m->scalers)
5931                 return (ERROR);
5932             for (i=0; i<m->numScalers; i++)
5933                 {
5934 #   if defined (SSE_ENABLED)
5935                 if (m->useSSE == YES)
5936                     {
5937                     /* allocate space with padding */
5938                     m->scalers[i] = (CLFlt*) AlignedMalloc (m->numSSEChars * FLOATS_PER_VEC * sizeof(CLFlt), 16);
5939                     if (!m->scalers[i])
5940                         return (ERROR);
5941                     for (j=0; j<m->numSSEChars*FLOATS_PER_VEC; j++)
5942                         m->scalers[i][j] = 0.0f;
5943                     }
5944                 else
5945                     {
5946                     m->scalers[i] = (CLFlt*) SafeMalloc (m->numChars * sizeof(CLFlt));
5947                     if (!m->scalers[i])
5948                         return (ERROR);
5949                     }
5950 #   else
5951                 m->scalers[i] = (CLFlt*) SafeMalloc (m->numChars * sizeof(CLFlt));
5952                 if (!m->scalers[i])
5953                     return (ERROR);
5954 #   endif
5955                 }
5956
5957             /* allocate stuff for facilitating scaling and accumulation of cond likes */
5958             if (m->dataType == STANDARD)
5959                 {
5960                 m->clP = (CLFlt **) SafeMalloc(m->numGammaCats * sizeof(CLFlt *));
5961                 if (!m->clP)
5962                     return (ERROR);
5963                 }
5964             else
5965                 {
5966                 m->clP = (CLFlt **) SafeMalloc(m->numTiCats * sizeof(CLFlt *));
5967                 if (!m->clP)
5968                     return (ERROR);
5969 #   if defined (SSE_ENABLED)
5970                 if (m->useSSE == YES)
5971                     {
5972                     m->clP_SSE = (__m128 **) SafeMalloc(m->numTiCats * sizeof(__m128 *));
5973                     if (!m->clP_SSE)
5974                         return (ERROR);
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)
5978                         return (ERROR);
5979                     }
5980 #   endif
5981                 }
5982
5983             /* allocate tiprob space */
5984             m->tiProbs = (CLFlt**) SafeMalloc(m->numTiProbs * sizeof(CLFlt*));
5985             if (!m->tiProbs)
5986                 return (ERROR);
5987             for (i=0; i<m->numTiProbs; i++)
5988                 {
5989                 m->tiProbs[i] = (CLFlt*) SafeMalloc(m->tiProbLength * sizeof(CLFlt));
5990                 if (!m->tiProbs[i])
5991                     return (ERROR);
5992                 }
5993             }
5994
5995         /* allocate eigen system space (needed also for Beagle version */
5996         if (m->nCijkParts > 0)
5997             {
5998             m->cijks = (MrBFlt**) SafeMalloc((numLocalChains + 1) * sizeof(MrBFlt*));
5999             if (!m->cijks)
6000                 return ERROR;
6001             for (i=0; i<numLocalChains+1; i++)
6002                 {
6003                 m->cijks[i] = (MrBFlt*) SafeMalloc(m->cijkLength * sizeof(MrBFlt));
6004                 if (!m->cijks[i])
6005                     return (ERROR);
6006                 }
6007             }
6008
6009         /* get size of tree */
6010         nIntNodes = GetTree(m->brlens,0,0)->nIntNodes;
6011         nNodes = GetTree(m->brlens,0,0)->nNodes;
6012
6013             
6014         /* allocate and set indices from tree nodes to cond like arrays */
6015         m->condLikeIndex = (int **) SafeMalloc (numLocalChains * sizeof(int *));
6016         if (!m->condLikeIndex)
6017             return (ERROR);
6018         for (i=0; i<numLocalChains; i++)
6019             {
6020             m->condLikeIndex[i] = (int *) SafeMalloc (nNodes * sizeof(int));
6021             if (!m->condLikeIndex[i])
6022                 return (ERROR);
6023             }
6024         for (i=0; i<numLocalChains; i++)
6025             for (j=0; j<nNodes; j++)
6026                 m->condLikeIndex[i][j] = -1;
6027
6028         /* set up indices for terminal nodes */
6029         clIndex = 0;
6030         if (useBeagle == YES)
6031             indexStep = m->nCijkParts;
6032         else
6033             indexStep = 1;
6034         for (i=0; i<numLocalTaxa; i++)
6035             {
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)
6039                 continue;
6040             */
6041 #   endif
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.*/
6045             }
6046
6047         /* reserve private space for parsimony-based moves if parsimony model is used */
6048         if (m->parsModelId == YES && m->parsimonyBasedMove == YES)
6049             clIndex += nIntNodes;
6050
6051         /* set up indices for internal nodes */
6052         for (j=0; j<numLocalChains; j++)
6053             {
6054             for (i=0; i<nIntNodes; i++)
6055                 {
6056                 m->condLikeIndex[j][i+numLocalTaxa] = clIndex;
6057                 clIndex += indexStep;
6058                 }
6059             }
6060
6061         /* allocate and set up scratch cond like indices */
6062         m->condLikeScratchIndex = (int *) SafeMalloc (nNodes * sizeof(int));
6063         if (!m->condLikeScratchIndex)
6064             return (ERROR);
6065         for (i=0; i<nNodes; i++)
6066             m->condLikeScratchIndex[i] = -1;
6067         for (i=0; i<nIntNodes; i++)
6068             {
6069             m->condLikeScratchIndex[i+numLocalTaxa] = clIndex;
6070             clIndex += indexStep;
6071             }
6072
6073         /* allocate and set indices from tree edges to ti prob arrays */
6074         m->tiProbsIndex = (int **) SafeMalloc (numLocalChains * sizeof(int *));
6075         if (!m->tiProbsIndex)
6076             return (ERROR);
6077         for (i=0; i<numLocalChains; i++)
6078             {
6079             m->tiProbsIndex[i] = (int *) SafeMalloc (nNodes * sizeof(int));
6080             if (!m->tiProbsIndex[i])
6081                 return (ERROR);
6082             }
6083
6084         /* set up indices for nodes */
6085         tiIndex = 0;
6086         for (i=0; i<numLocalChains; i++)
6087             {
6088             for (j=0; j<nNodes; j++)
6089                 {
6090                 m->tiProbsIndex[i][j] = tiIndex;
6091                 tiIndex += indexStep;
6092                 }
6093             }
6094
6095         /* allocate and set up scratch transition prob indices */
6096         m->tiProbsScratchIndex = (int *) SafeMalloc (nNodes * sizeof(int));
6097         if (!m->tiProbsScratchIndex)
6098             return (ERROR);
6099         for (i=0; i<nNodes; i++)
6100             {
6101             m->tiProbsScratchIndex[i] = tiIndex;
6102             tiIndex += indexStep;
6103             }
6104
6105         /* allocate and set up node scaler indices */
6106         scalerIndex = 0;
6107         m->nodeScalerIndex = (int **) SafeMalloc (numLocalChains * sizeof(int *));
6108         if (!m->nodeScalerIndex)
6109             return (ERROR);
6110         for (i=0; i<numLocalChains; i++)
6111             {
6112             m->nodeScalerIndex[i] = (int *) SafeMalloc (nNodes * sizeof(int));
6113             if (!m->nodeScalerIndex[i])
6114                 return (ERROR);
6115             for (j=0; j<nNodes; j++)
6116                 m->nodeScalerIndex[i][j] = -1;
6117             for (j=0; j<nIntNodes; j++)
6118                 {
6119                 m->nodeScalerIndex[i][j+numLocalTaxa] = scalerIndex;
6120                 scalerIndex += indexStep;
6121                 }
6122             }
6123         m->nodeScalerScratchIndex = (int *) SafeMalloc (nNodes * sizeof (int));
6124         if (!m->nodeScalerScratchIndex)
6125             return (ERROR);
6126         for (i=0; i<nNodes; i++)
6127             m->nodeScalerScratchIndex[i] = -1;
6128         for (i=0; i<nIntNodes; i++)
6129             {
6130             m->nodeScalerScratchIndex[i+numLocalTaxa] = scalerIndex;
6131             scalerIndex += indexStep;
6132             }
6133
6134         /* allocate and set up node scaler flags */
6135         m->scalersSet = (int **) SafeMalloc (numLocalChains * sizeof(int *));
6136         if (!m->scalersSet)
6137             return (ERROR);
6138         for (i=0; i<numLocalChains; i++)
6139             {
6140             m->scalersSet[i] = (int *) SafeMalloc (nNodes * sizeof(int));
6141             if (!m->scalersSet[i])
6142                 return (ERROR);
6143             for (j=0; j<nNodes; j++)
6144                 m->scalersSet[i][j] = NO;
6145             }
6146         m->scalersSetScratch = (int *) SafeMalloc (nNodes * sizeof (int));
6147         if (!m->scalersSetScratch)
6148             return (ERROR);
6149         for (i=0; i<nNodes; i++)
6150             m->scalersSetScratch[i] = NO;
6151
6152         /* allocate and set up site scaler indices */
6153         m->siteScalerIndex = (int *) SafeMalloc (numLocalChains * sizeof(int));
6154         if (!m->siteScalerIndex)
6155             return (ERROR);
6156         for (i=0; i<numLocalChains; i++)
6157             {
6158             m->siteScalerIndex[i] = scalerIndex;
6159             scalerIndex += indexStep;
6160             }
6161         m->siteScalerScratchIndex = scalerIndex;
6162
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)
6166             {
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++)
6174                {
6175                m->rescaleFreq[i] = t;
6176                }
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++)
6182                {
6183                m->isScalerNode[i] = (int*) SafeMalloc(nIntNodes * sizeof(int)) - numLocalTaxa;
6184                }
6185             }
6186 #   endif
6187
6188         /* allocate and set up cijk indices */
6189         if (m->nCijkParts > 0)
6190             {
6191             m->cijkIndex = (int *) SafeMalloc (numLocalChains * sizeof(int));
6192             if (!m->cijkIndex)
6193                 return (ERROR);
6194             for (i=0; i<numLocalChains; i++)
6195                 m->cijkIndex[i] = i*indexStep;
6196             m->cijkScratchIndex = numLocalChains*indexStep;
6197             }
6198
6199 #   if defined (BEAGLE_ENABLED)
6200             /* Set up nSitesOfPat for Beagle */
6201             if (m->useBeagle == YES)
6202                 {
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,
6207                                         nSitesOfPat);
6208                 free (nSitesOfPat);
6209                 nSitesOfPat = NULL;
6210
6211                 /* find category frequencies */
6212                 if (m->pInvar == NO)
6213                     {
6214                     freq =  1.0 /  m->numGammaCats;
6215                     
6216                     /* set category frequencies in beagle instance */
6217                     if (m->numOmegaCats <= 1)
6218                         {
6219                         for (i=0; i<m->numGammaCats; i++)
6220                             m->inWeights[i] = freq;
6221                         for (i=0; i< (numLocalChains); i++) {
6222                             beagleSetCategoryWeights(m->beagleInstance,
6223                                                      m->cijkIndex[i],
6224                                                      m->inWeights);
6225                             }
6226                         beagleSetCategoryWeights(m->beagleInstance,
6227                                                  m->cijkScratchIndex,
6228                                                  m->inWeights);
6229                         }
6230                     }
6231                 
6232                 /* Set up scalers for Beagle */
6233                 for (i=0; i<m->numScalers*m->nCijkParts; i++)
6234                     beagleResetScaleFactors(m->beagleInstance, i);
6235                 }
6236 #   endif
6237
6238         /* fill in tip conditional likelihoods */
6239         if (m->dataType == STANDARD)
6240             {
6241             clIndex = 0;
6242             for (i=0; i<numLocalTaxa; i++)
6243                 {
6244                 cL = m->condLikes[clIndex++];
6245                 for (t=0; t<m->numGammaCats;t++)
6246                     {
6247                     charBits = m->parsSets[i];
6248                     for (c=0; c<m->numChars; c++)
6249                         {                   
6250                         if (m->nStates[c] == 2)
6251                             numReps = m->numBetaCats;
6252                         else
6253                             numReps = 1;
6254                         for (k=0; k<numReps; k++)
6255                             {
6256                             for (s=0; s<m->nStates[c]; s++)
6257                                 {
6258                                 if (IsBitSet(s, charBits))
6259                                     (*cL) = 1.0;
6260                                 cL++;
6261                                 }
6262                             }
6263                         charBits += m->nParsIntsPerSite;
6264                         }
6265                     }
6266                 }
6267             }
6268         else if (useBeagle == NO)
6269             {
6270             if (m->gibbsGamma == YES)
6271                 numReps = m->numTiCats / m->numGammaCats;
6272             else
6273                 numReps = m->numTiCats;
6274
6275             clIndex = 0;
6276             for (i=0; i<numLocalTaxa; i++)
6277                 {
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)
6281                     continue;
6282                 */
6283 #   endif
6284                 cL = m->condLikes[clIndex++];
6285 #   if defined (SSE_ENABLED)
6286                 if (m->useSSE == YES)
6287                     {
6288                     for (k=0; k<numReps; k++)
6289                         {
6290                         charBits = m->parsSets[i];
6291                         for (c=0; c<m->numChars/FLOATS_PER_VEC; c++)
6292                             {
6293                             for (j=0; j<m->numModelStates/m->numStates; j++)
6294                                 {
6295                                 for (s=0; s<m->numStates; s++)
6296                                     {
6297                                     for (j1=0; j1<FLOATS_PER_VEC; j1++)
6298                                         {
6299                                         if (IsBitSet(s, charBits + j1*m->nParsIntsPerSite))
6300                                             (*cL) = 1.0;
6301                                         cL++;
6302                                         }
6303                                     }
6304                                 }   
6305                             charBits += FLOATS_PER_VEC * m->nParsIntsPerSite;
6306                             }
6307                         if (m->numChars % FLOATS_PER_VEC > 0)
6308                             {
6309                             /* add last characters and padd */
6310                             for (j=0; j<m->numModelStates/m->numStates; j++)
6311                                 {
6312                                 for (s=0; s<m->numStates; s++)
6313                                     {
6314                                     for (j1=0; j1<m->numChars%FLOATS_PER_VEC; j1++)
6315                                         {
6316                                         if (IsBitSet(s, charBits + j1*m->nParsIntsPerSite))
6317                                             (*cL) = 1.0;
6318                                         cL++;
6319                                         }
6320                                     for (; j1<FLOATS_PER_VEC; j1++)
6321                                         {
6322                                         (*cL) = 1.0;
6323                                         cL++;
6324                                         }
6325                                     }
6326                                 }
6327                             }
6328                         }
6329                     }
6330                 else
6331                     {
6332                     for (k=0; k<numReps; k++)
6333                         {
6334                         charBits = m->parsSets[i];
6335                         for (c=0; c<m->numChars; c++)
6336                             {
6337                             for (j=0; j<m->numModelStates/m->numStates; j++)
6338                                 {
6339                                 for (s=0; s<m->numStates; s++)
6340                                     {
6341                                     if (IsBitSet(s, charBits))
6342                                         (*cL) = 1.0;
6343                                     cL++;
6344                                     }
6345                                 }
6346                                 charBits += m->nParsIntsPerSite;
6347                             }
6348                         }
6349                     }
6350
6351 #   else
6352                 for (k=0; k<numReps; k++)
6353                     {
6354                     charBits = m->parsSets[i];
6355                     for (c=0; c<m->numChars; c++)
6356                         {
6357                         for (j=0; j<m->numModelStates/m->numStates; j++)
6358                             {
6359                             for (s=0; s<m->numStates; s++)
6360                                 {
6361                                 if (IsBitSet(s, charBits))
6362                                     (*cL) = 1.0;
6363                                 cL++;
6364                                 }
6365                             }
6366                             charBits += m->nParsIntsPerSite;
6367                         }
6368                     }
6369 #   endif
6370                 }
6371             }
6372
6373         if (m->printAncStates == YES)
6374             {
6375             m->ancStateCondLikes = (CLFlt *) SafeMalloc (m->condLikeLength * sizeof(CLFlt));
6376             if (!m->ancStateCondLikes)
6377                 return (ERROR);
6378             }
6379         }
6380     /* allocate space for precalculated likelihoods */
6381     j = 0;
6382     for (d=0; d<numCurrentDivisions; d++)
6383         {
6384         m = &modelSettings[d];
6385         if (m->dataType == STANDARD || m->parsModelId == YES)
6386             continue;
6387
6388         i = (m->numModelStates + 1) * m->numModelStates * m->numTiCats;
6389         if (i > j)
6390             j = i;
6391         }
6392     if (j > 0) /* don't bother allocating precalculated likelihoods if we only have parsimony model or morphological characters */
6393         {
6394         if (memAllocs[ALLOC_PRELIKES] == YES)
6395             {
6396             MrBayesPrint ("%s   Space for preLikes not free in InitChainCondLikes\n", spacer);
6397             return ERROR;
6398             }
6399         preLikeL = (CLFlt *) SafeMalloc (3 * j * sizeof(CLFlt));
6400         if (!preLikeL)
6401             {
6402             MrBayesPrint ("%s   Problem allocating preLikes\n", spacer);
6403             return ERROR;
6404             }
6405         memAllocs[ALLOC_PRELIKES] = YES;
6406         preLikeR = preLikeL + j;
6407         preLikeA = preLikeR + j;
6408         }
6409
6410     return NO_ERROR;
6411 }
6412
6413
6414 /*------------------------------------------------------------------------
6415 |
6416 |   InitEigenSystemInfo: set info about eigen decompositions
6417 |
6418 -------------------------------------------------------------------------*/
6419 int InitEigenSystemInfo (ModelInfo *m)
6420 {
6421     int         ts;
6422     
6423     if (m->dataType == STANDARD)
6424         {
6425         /* dealt with in ProcessStdChars */
6426         return (NO_ERROR);
6427         }
6428
6429     m->cijkLength = 0;
6430     m->nCijkParts = 0;
6431     if (m->dataType == PROTEIN)
6432         {
6433         ts = m->numModelStates;
6434         m->cijkLength = (ts * ts * ts) + (2 * ts);
6435         m->nCijkParts = 1;
6436         if (m->switchRates != NULL) /* covarion model */
6437             {
6438             m->cijkLength *= m->numGammaCats;
6439             m->nCijkParts = m->numGammaCats;
6440             }
6441         }
6442     else if (m->dataType == DNA || m->dataType == RNA)
6443         {
6444         if (m->nucModelId == NUCMODEL_4BY4)
6445             {
6446             if (m->switchRates==NULL && m->nst != 6 && m->nst != NST_MIXED)
6447                 {
6448                 m->cijkLength = 0;
6449                 m->nCijkParts = 0;
6450 #   if defined (BEAGLE_ENABLED)
6451                 ts = m->numModelStates;
6452                 m->cijkLength = (ts * ts * ts) + (2 * ts);
6453                 m->nCijkParts = 1;
6454 #   endif
6455                 }
6456             else
6457                 {
6458                 ts = m->numModelStates;
6459                 m->cijkLength = (ts * ts * ts) + (2 * ts);
6460                 m->nCijkParts = 1;
6461                 }
6462             if (m->switchRates != NULL)
6463                 {
6464                 m->cijkLength *= m->numGammaCats;
6465                 m->nCijkParts = m->numGammaCats;
6466                 }
6467             }
6468         else if (m->nucModelId == NUCMODEL_DOUBLET)
6469             {
6470             ts = m->numModelStates;
6471             m->cijkLength = (ts * ts * ts) + (2 * ts);
6472             m->nCijkParts = 1;
6473             }
6474         else if (m->nucModelId == NUCMODEL_CODON)
6475             {
6476             ts = m->numModelStates;
6477             m->cijkLength = (ts * ts * ts) + (2 * ts);
6478             m->cijkLength *= m->numOmegaCats;
6479             m->nCijkParts = m->numOmegaCats;
6480             }
6481         else
6482             {
6483             MrBayesPrint ("%s   ERROR: Something is wrong if you are here.\n", spacer);
6484             return ERROR;
6485             }
6486         }
6487 #   if defined (BEAGLE_ENABLED)
6488     else if (m->dataType == RESTRICTION)
6489         {
6490                 assert (m->numModelStates == 2);
6491                 ts = 2;
6492                 m->cijkLength = (ts * ts * ts) + (2 * ts);
6493                 m->nCijkParts = 1;
6494         }
6495 #   endif
6496     return (NO_ERROR);
6497 }
6498
6499
6500 /*------------------------------------------------------------------------
6501 |
6502 |   InitFinalStateCondLikes: allocate space for final conditional
6503 |       likelihoods if needed
6504 |
6505 -------------------------------------------------------------------------*/
6506 int InitFinalStateCondLikes (void)
6507 {
6508     int         d;
6509     ModelInfo   *m;
6510     
6511     for (d=0; d<numCurrentDivisions; d++)
6512         {
6513         m = &modelSettings[d];
6514         if (m->printAncStates == YES)
6515             {
6516             m->ancStateCondLikes = (CLFlt *) SafeMalloc (m->condLikeLength * sizeof(CLFlt));
6517             if (!m->ancStateCondLikes)
6518                 return ERROR;
6519             }
6520         }
6521     return (NO_ERROR);
6522 }
6523
6524
6525 /*------------------------------------------------------------------------
6526 |
6527 |   InitInvCondLikes: allocate and initialize invariable conditional
6528 |       likelihoods if needed
6529 |
6530 |       NB! Fills in invariable cond likes for all hidden states; this
6531 |       is convenient although some space is wasted
6532 |
6533 -------------------------------------------------------------------------*/
6534 int InitInvCondLikes (void)
6535 {
6536     int         c, d, i, s, isConstant, usingInvCondLikes;
6537     BitsLong    *charBits;
6538     CLFlt       *cI;
6539     ModelInfo   *m;
6540
6541 #   if defined (SSE_ENABLED)
6542     int         c1;
6543 #   endif
6544
6545     /* allocate space for invariable cond likes */
6546     usingInvCondLikes = NO;
6547     for (d=0; d<numCurrentDivisions; d++)
6548         {
6549         m = &modelSettings[d];
6550
6551         if (m->pInvar == NULL)
6552             continue;
6553
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;
6560 #   else
6561         m->invCondLikes = (CLFlt *) SafeMalloc (m->numChars * m->numModelStates * sizeof(CLFlt));
6562 #   endif
6563         if (!m->invCondLikes)
6564             return ERROR;
6565         }
6566     
6567     if (usingInvCondLikes == NO)
6568         return NO_ERROR;
6569     
6570     MrBayesPrint ("%s   Initializing invariable-site conditional likelihoods\n", spacer);
6571         
6572     /* fill in invariable-site conditional likelihoods */
6573     for (d=0; d<numCurrentDivisions; d++)
6574         {
6575
6576         m = &modelSettings[d];
6577         
6578         if (m->pInvar == NULL)
6579             continue;
6580         
6581         cI = m->invCondLikes;
6582         if (m->dataType == STANDARD)
6583             {
6584             for (c=0; c<m->numChars; c++)
6585                 {
6586                 for (s=0; s<m->nStates[c]; s++)
6587                     {
6588                     isConstant = YES;
6589                     for (i=0; i<numLocalTaxa; i++)
6590                         {
6591                         charBits = &m->parsSets[i][c*m->nParsIntsPerSite];
6592                         if (IsBitSet(s, charBits) == NO)
6593                             {
6594                             isConstant = NO;
6595                             break;
6596                             }
6597                         }
6598                     if (isConstant == YES)
6599                         *cI = 1.0;
6600                     else
6601                         *cI = 0.0;
6602                     cI++;
6603                     }
6604                 }
6605             }
6606         else    /* all other models for which pInvar is applicable */
6607             {
6608             assert (m->numModelStates == m->numStates);
6609 #   if defined (SSE_ENABLED)
6610              for (c=0; c<m->numChars/FLOATS_PER_VEC; c++)
6611                 {
6612                 for (s=0; s<m->numModelStates; s++)
6613                     {
6614                     for (c1=0; c1<FLOATS_PER_VEC; c1++)
6615                         {
6616                         isConstant = YES;
6617                         //charBits = parsMatrix + m->parsMatrixStart + ((c * FLOATS_PER_VEC) + c1) * m->nParsIntsPerSite;
6618                         for (i=0; i<numLocalTaxa; i++)
6619                             {
6620                             charBits = &m->parsSets[i][((c * FLOATS_PER_VEC) + c1) *m->nParsIntsPerSite];
6621                             if (IsBitSet(s, charBits) == NO)
6622                                 {
6623                                 isConstant = NO;
6624                                 break;
6625                                 }
6626                             //charBits += parsMatrixRowSize;
6627                             }
6628                         if (isConstant == YES)
6629                             *cI = 1.0;
6630                         cI++;
6631                         }
6632                     }
6633                 }
6634              if (m->numChars % FLOATS_PER_VEC != 0)
6635                 {
6636                 for (s=0; s<m->numModelStates; s++)
6637                     {
6638                     for (c1=0; c1<m->numChars%FLOATS_PER_VEC; c1++)
6639                         {
6640                         isConstant = YES;
6641                         //charBits = parsMatrix + m->parsMatrixStart + (((m->numChars / FLOATS_PER_VEC) * FLOATS_PER_VEC) + c1) * m->nParsIntsPerSite;
6642                         for (i=0; i<numLocalTaxa; i++)
6643                             {
6644                             charBits = &m->parsSets[i][(((m->numChars / FLOATS_PER_VEC) * FLOATS_PER_VEC) + c1) *m->nParsIntsPerSite];
6645                             if (IsBitSet(s, charBits) == NO)
6646                                 {
6647                                 isConstant = NO;
6648                                 break;
6649                                 }
6650                             //charBits += parsMatrixRowSize;
6651                             }
6652                         if (isConstant == YES)
6653                             *cI = 1.0;
6654                         cI++;
6655                         }
6656                     for (; c1<FLOATS_PER_VEC; c1++)
6657                         {
6658                         *cI = 1.0;
6659                         cI++;
6660                         }
6661                     }
6662                 }
6663 #   else
6664             for (c=0; c<m->numChars; c++)
6665                 {
6666                 for (s=0; s<m->numModelStates; s++)
6667                     {
6668                     isConstant = YES;
6669                     for (i=0; i<numLocalTaxa; i++)
6670                         {
6671                         charBits = &m->parsSets[i][c*m->nParsIntsPerSite];
6672                         if (IsBitSet(s, charBits) == NO)
6673                             {
6674                             isConstant = NO;
6675                             break;
6676                             }
6677                         }
6678                     if (isConstant == YES)
6679                         *cI = 1.0;
6680                     cI++;
6681                     }
6682                 }
6683 #   endif
6684             }
6685         }   /* next division */
6686
6687 #   if 0
6688     invCondLikeSize = 0;
6689     for (d=0; d<numCurrentDivisions; d++)
6690         {
6691         m = &modelSettings[d];
6692         if (m->pInvar == NULL)
6693             continue;
6694         cI = m->invCondLikes;
6695         if (m->dataType == STANDARD)
6696             {
6697             }
6698         else
6699             {
6700             for (c=0; c<m->numChars; c++)
6701                 {
6702                 printf ("%4d -- ", c);
6703                 for (s=0; s<m->numModelStates; s++)
6704                     {
6705                     printf ("%1.0lf", *cI);
6706                     cI++;
6707                     }
6708                 printf ("\n");
6709                 }
6710             }
6711         }
6712 #   endif
6713         
6714     return NO_ERROR;
6715 }
6716
6717
6718 /*------------------------------------------------------------------------
6719 |
6720 |   InitParsSets: allocate space for and set parsimony state sets
6721 |
6722 -------------------------------------------------------------------------*/
6723 int InitParsSets (void)
6724 {
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;
6728     ModelInfo       *m;
6729     ModelParams     *mp;
6730
6731     bitsLongOne = 1;
6732
6733     /* this variable determines how many parsimony states are used           */
6734     /* to represent continuous characters (determines weight of these chars) */
6735     nParsStatesForCont = 3;
6736
6737     /* find number and size of parsimony sets and node lengths */
6738     for (d=0; d<numCurrentDivisions; d++)
6739         {
6740         m  = &modelSettings[d];
6741         mp = &modelParams[d];
6742
6743         /* find how many parsimony ints (BitsLong) are needed for each model site */
6744         if (mp->dataType == CONTINUOUS)
6745             {
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;
6750             }
6751         else
6752             m->nParsIntsPerSite = 1 + m->numStates / nBitsInALong;
6753
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;
6757         
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;
6764
6765         if (m->parsModelId == YES)
6766             m->numParsNodeLens = (numLocalChains + 1) * nNodes;
6767         else
6768             m->numParsNodeLens = 0;
6769         }
6770         
6771     /* then allocate space for the sets and node lengths */
6772     for (d=0; d<numCurrentDivisions; d++)
6773         {
6774         m = &modelSettings[d];
6775         mp = &modelParams[d];
6776
6777         m->parsSets = (BitsLong **) SafeCalloc (m->numParsSets, sizeof(BitsLong*));
6778         if (!m->parsSets)
6779             return (ERROR);
6780         for (i=0; i<m->numParsSets; i++)
6781             {
6782             m->parsSets[i] = (BitsLong *) SafeCalloc (m->numChars*m->nParsIntsPerSite, sizeof(BitsLong));
6783             if (!m->parsSets[i])
6784                 return (ERROR);
6785             }
6786
6787         if (m->numParsNodeLens > 0)
6788             {
6789             m->parsNodeLens = (CLFlt *) SafeCalloc (m->numParsNodeLens, sizeof(CLFlt));
6790             if (!m->parsNodeLens)
6791                 return (ERROR);
6792             }
6793         }
6794     
6795     /* finally fill in tip parsimony sets */
6796     for (d=0; d<numCurrentDivisions; d++)
6797         {
6798         m = &modelSettings[d];
6799         mp = &modelParams[d];
6800
6801         if (mp->dataType == CONTINUOUS)
6802             {
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++)
6806                 {
6807                 for (c=0, j=m->compMatrixStart; j<m->compMatrixStop; j++, c++)
6808                     {
6809                     x = compMatrix[pos(i,j,compMatrixRowSize)];
6810
6811                     for (k=0; k<m->nParsIntsPerSite; k++)
6812                         {
6813                         if (x > (unsigned int)(k + 1) * 1000 / (m->nParsIntsPerSite + 1))
6814                             m->parsSets[i][c*m->nParsIntsPerSite + k] = 1;
6815                         else
6816                             m->parsSets[i][c*m->nParsIntsPerSite + k] = 2;
6817                         }
6818                     }
6819                 }
6820             }
6821         else if (m->nCharsPerSite == 1 && m->nParsIntsPerSite == 1)
6822             {
6823             allAmbig = (bitsLongOne<<mp->nStates) - 1UL;
6824             for (i=0; i<numLocalTaxa; i++)
6825                 {
6826                 for (c=0, j=m->compMatrixStart; j<m->compMatrixStop; j++, c++)
6827                     {
6828                     x = compMatrix[pos(i,j,compMatrixRowSize)];
6829
6830                     if (x == MISSING || x == GAP)
6831                         m->parsSets[i][c] = allAmbig;
6832                     else
6833                         m->parsSets[i][c] = x;
6834                     }
6835                 }
6836             }
6837         else if (!strcmp(mp->nucModel, "Doublet") && (mp->dataType == DNA || mp->dataType == RNA))
6838             {
6839             allAmbig = 15;
6840             for (i=0; i<numLocalTaxa; i++)
6841                 {
6842                 for (c=0, j=m->compMatrixStart; j<m->compMatrixStop; j+=m->nCharsPerSite, c++)
6843                     {
6844                     /* fetch the original values x1 and x2 */
6845                     x1 = compMatrix[pos(i,j,compMatrixRowSize)];
6846                     if (x1 == MISSING || x1 == GAP)
6847                         x1 = allAmbig;
6848                     x2 = compMatrix[pos(i,j+1,compMatrixRowSize)];
6849                     if (x2 == MISSING || x2 == GAP)
6850                         x2 = allAmbig;
6851                     /* squeeze them together in the new value x */
6852                     x = 0;
6853                     for (nuc1=0; nuc1<4; nuc1++)
6854                         {
6855                         for (nuc2=0; nuc2<4; nuc2++)
6856                             {
6857                             if (IsBitSet(nuc1,&x1) == YES && IsBitSet(nuc2, &x2) == YES)
6858                                 x |= (bitsLongOne<<(nuc1*4 + nuc2));
6859                             }
6860                         }
6861                     
6862                     m->parsSets[i][c] = x;
6863                     }
6864                 }
6865             }
6866         else if (!strcmp(mp->nucModel, "Codon") && (mp->dataType == DNA || mp->dataType == RNA))
6867             {
6868             allAmbig = 15;
6869             for (i=0; i<numLocalTaxa; i++)
6870                 {
6871                 for (c=0, j=m->compMatrixStart; j<m->compMatrixStop; j+=m->nCharsPerSite, c++)
6872                     {
6873                     /* fetch the original values x1, x2, and x3*/
6874                     x1 = compMatrix[pos(i,j,compMatrixRowSize)];
6875                     if (x1 == MISSING || x1 == GAP)
6876                         x1 = allAmbig;
6877                     x2 = compMatrix[pos(i,j+1,compMatrixRowSize)];
6878                     if (x2 == MISSING || x2 == GAP)
6879                         x2 = allAmbig;
6880                     x3 = compMatrix[pos(i,j+2,compMatrixRowSize)];
6881                     if (x3 == MISSING || x3 == GAP)
6882                         x3 = allAmbig;
6883
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++)
6890                                 {
6891                                 if (mp->codon[allNucCode] != 21)
6892                                     {
6893                                     if (IsBitSet(nuc1, &x1) == YES && IsBitSet(nuc2, &x2) == YES && IsBitSet(nuc3, &x3) == YES)
6894                                         SetBit(codingNucCode, longPtr);
6895                                     codingNucCode++;
6896                                     }
6897                                 allNucCode++;
6898                                 }
6899                     }
6900                 }
6901             }
6902         else if (!strcmp(mp->nucModel, "Protein") && (mp->dataType == DNA || mp->dataType == RNA))
6903             {
6904             allAmbig = 15;
6905             for (i=0; i<numLocalTaxa; i++)
6906                 {
6907                 for (c=0, j=m->compMatrixStart; j<m->compMatrixStop; j+=m->nCharsPerSite, c++)
6908                     {
6909                     /* fetch the original values x1, x2, and x3*/
6910                     x1 = compMatrix[pos(i,j,compMatrixRowSize)];
6911                     if (x1 == MISSING || x1 == GAP)
6912                         x1 = allAmbig;
6913                     x2 = compMatrix[pos(i,j+1,compMatrixRowSize)];
6914                     if (x2 == MISSING || x2 == GAP)
6915                         x2 = allAmbig;
6916                     x3 = compMatrix[pos(i,j+2,compMatrixRowSize)];
6917                     if (x3 == MISSING || x3 == GAP)
6918                         x3 = allAmbig;
6919
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 */
6922                     allNucCode = 0;
6923                     for (nuc1=0; nuc1<4; nuc1++)
6924                         for (nuc2=0; nuc2<4; nuc2++)
6925                             for (nuc3=0; nuc3<4; nuc3++)
6926                                 {
6927                                 if (mp->codon[allNucCode] != 21)
6928                                     {
6929                                     if (IsBitSet(nuc1, &x1) == YES && IsBitSet(nuc2, &x2) == YES && IsBitSet(nuc3, &x3) == YES)
6930                                         SetBit(mp->codon[allNucCode]-1, longPtr);
6931                                     }
6932                                 allNucCode++;
6933                                 }
6934                     }
6935                 }
6936             }
6937         else
6938             {
6939             MrBayesPrint ("%s   Unrecognized data format during bitset compression\n", spacer);
6940             return ERROR;
6941             }
6942         }
6943     
6944     return (NO_ERROR);
6945 }
6946
6947
6948 /*------------------------------------------------
6949 |
6950 |   InitPrintParams: Set up arrays of print para-
6951 |      meters and print tree parameters
6952 |
6953 ------------------------------------------------*/
6954 int InitPrintParams (void)
6955 {
6956     int     i, j, k, k1=0;
6957     Param   *p;
6958
6959     /* count number of model params to print */
6960     numPrintParams = 0;
6961     for (i=0; i<numParams; i++)
6962         {
6963         p = &params[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)
6972             numPrintParams++;
6973         }
6974
6975     /* count number of tree params to print */
6976     numPrintTreeParams = 0;
6977     for (i=0; i<numParams; i++)
6978         {
6979         p = &params[i];
6980         if (p->paramType == P_TOPOLOGY)
6981             {
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++;
6986             }
6987         else if (p->paramType == P_BRLENS)
6988             {
6989             /* print only if brlens (or events) requested for at least one partition */
6990             if (p->printParam == YES || p->nPrintSubParams > 0)
6991                 numPrintTreeParams++;
6992             }
6993         else if (p->paramType == P_SPECIESTREE)
6994             {
6995             /* always print if printParam set to YES */
6996             if (p->printParam == YES)
6997                 numPrintTreeParams++;
6998             }
6999         }
7000
7001     /* allocate space */
7002     printParam = (Param **) SafeCalloc (numPrintParams + numPrintTreeParams + numTopologies, sizeof(Param *));
7003     topologyPrintIndex = (int *) SafeCalloc (numTopologies + numPrintTreeParams, sizeof(int)); 
7004     if (!printParam || !topologyPrintIndex)
7005         {
7006         free (printParam);
7007         free (topologyPrintIndex);
7008         MrBayesPrint ("%s   Could not allocate printParam vector in InitPrintParams\n", spacer);
7009         return (ERROR);
7010         }
7011     printTreeParam = printParam + numPrintParams;
7012     topologyParam = printTreeParam + numPrintTreeParams;
7013     printTreeTopologyIndex = topologyPrintIndex + numTopologies;
7014     memAllocs[ALLOC_PRINTPARAM] = YES;
7015
7016     /* assign normal print params */
7017     for (i=j=0; i<numParams; i++)
7018         {
7019         p = &params[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;
7029         }
7030     
7031     /* assign tree print params */
7032     for (i=j=k=0; i<numParams; i++)
7033         {
7034         p = &params[i];
7035         if (p->paramType == P_TOPOLOGY)
7036             {
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++;
7041             }
7042         else if (p->paramType == P_BRLENS)
7043             {
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;
7047             }
7048         else if (p->paramType == P_SPECIESTREE)
7049             {
7050             if (p->printParam == YES)
7051                 printTreeParam[k++] = p;
7052             }
7053         }
7054
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++)
7059         {
7060         p = &params[i];
7061         if (p->paramType == P_SPECIESTREE)
7062             {
7063             topologyParam[j] = p;
7064             for (k=0; k<numPrintTreeParams; k++)
7065                 if (printTreeParam[k] == p)
7066                     break;
7067             topologyPrintIndex[j] = k;
7068             printTreeTopologyIndex[k] = j;
7069             j++;
7070             }
7071         else if (p->paramType == P_TOPOLOGY)
7072             {
7073             topologyParam[j] = p;
7074             for (k=0; k<numPrintTreeParams; k++)
7075                 if (printTreeParam[k] == p)
7076                     break;
7077             if (k<numPrintTreeParams)
7078                 {
7079                 topologyPrintIndex[j] = k;
7080                 printTreeTopologyIndex[k] = j;
7081                 }
7082             else
7083                 {
7084                 for (k=0; k<p->nSubParams; k++)
7085                     {
7086                     for (k1=0; k1<numPrintTreeParams; k1++)
7087                         if (printTreeParam[k1] == p->subParams[k])
7088                             break;
7089                     if (k1 < numPrintTreeParams)
7090                         break;
7091                     }
7092                 topologyPrintIndex[j] = k1;
7093                 printTreeTopologyIndex[k1] = j;
7094                 }
7095             j++;
7096             }
7097         }
7098
7099     return (NO_ERROR);
7100 }
7101
7102
7103 int IsPFNodeEmpty (PFNODE *p)
7104 {
7105     int i;
7106
7107     for (i=0; i<chainParams.numRuns; i++)
7108         {
7109         if (p->count[i] > 0)
7110             break;
7111         }
7112     if (i == chainParams.numRuns)
7113         return YES;
7114     else
7115         return NO;
7116 }
7117
7118
7119 /* LargestNonemptyPFNode: recursive function to largest nonempty node in a subtree */
7120 PFNODE *LargestNonemptyPFNode (PFNODE *p, int *i, int j)
7121 {
7122     PFNODE *q;
7123
7124     ++j;
7125     if (p == NULL)
7126         return NULL;
7127     
7128     q = LargestNonemptyPFNode (p->left, i, j);
7129     
7130     if (q != NULL)
7131         {
7132         return q;
7133         }
7134     else if (IsPFNodeEmpty (p) == NO)
7135         {
7136         *i = j;
7137         return p;
7138         }
7139     else
7140         {
7141         return LargestNonemptyPFNode (p->right, i, j);
7142         }
7143 }
7144
7145
7146 /* ln prior ratio for clock trees */
7147 int LogClockTreePriorRatio (Param *param, int chain, MrBFlt *lnPriorRatio)
7148 {
7149     MrBFlt          oldLnPrior, newLnPrior, theta, N, growth, clockRate, sF, *sR, *eR, *fR;
7150     char            *sS;
7151     Model           *mp;
7152     ModelInfo       *m;
7153     Tree            *newTree, *oldTree;
7154     TreeNode        *p, *q=NULL;
7155     int             i, j;
7156
7157     (*lnPriorRatio) = 0.0;
7158     
7159     mp = &modelParams[param->relParts[0]];
7160     m  = &modelSettings[param->relParts[0]];
7161     
7162     newTree = GetTree (m->brlens, chain, state[chain]);
7163     oldTree = GetTree (m->brlens, chain, state[chain] ^ 1);
7164
7165     if (m->clockRate != NULL)
7166         clockRate = *GetParamVals(m->clockRate, chain, state[chain]);
7167     else
7168         clockRate = 1.0;
7169     
7170     /* calculate prior ratio on brlens of clock tree */
7171     if (!strcmp(mp->clockPr,"Coalescence"))
7172         {
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;
7180         else
7181             theta = 2 * N * clockRate;
7182         /* deal with growth */
7183         if (!strcmp(mp->growthPr, "Fixed"))
7184             growth = mp->growthFix;
7185         else
7186             growth = *(GetParamVals (m->growthRate, chain, state[chain]));
7187         if (LnCoalescencePriorPr (oldTree, &oldLnPrior, theta, growth) == ERROR)
7188             {
7189             MrBayesPrint ("%s   Problem calculating prior for coalescence process\n", spacer);
7190             return (ERROR);
7191             }
7192         if (LnCoalescencePriorPr (newTree, &newLnPrior, theta, growth) == ERROR)
7193             {
7194             MrBayesPrint ("%s   Problem calculating prior for coalescence process\n", spacer);
7195             return (ERROR);
7196             }
7197         (*lnPriorRatio) = (newLnPrior - oldLnPrior);
7198         }
7199     else if (!strcmp(mp->clockPr,"Birthdeath"))
7200         {
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)
7207             {
7208             MrBayesPrint ("%s   Problem calculating prior for birth-death process\n", spacer);
7209             return (ERROR);
7210             }
7211         if (LnBirthDeathPriorPr (newTree, clockRate, &newLnPrior, *sR, *eR, sS, sF) == ERROR)
7212             {
7213             MrBayesPrint ("%s   Problem calculating prior for birth-death process\n", spacer);
7214             return (ERROR);
7215             }
7216         (*lnPriorRatio) = (newLnPrior - oldLnPrior);
7217         }
7218     else if (!strcmp(mp->clockPr,"Fossilization"))
7219         {
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)
7227             {
7228             MrBayesPrint ("%s   Problem calculating prior for fossilized birth-death process\n", spacer);
7229             return (ERROR);
7230             }
7231         if (LnFossilizationPriorPr (newTree, clockRate, &newLnPrior, sR, eR, sF, fR, sS) == ERROR)
7232             {
7233             MrBayesPrint ("%s   Problem calculating prior for fossilized birth-death process\n", spacer);
7234             return (ERROR);
7235             }
7236         (*lnPriorRatio) = (newLnPrior - oldLnPrior);
7237         }
7238     else if (!strcmp(mp->clockPr,"Uniform"))
7239         {
7240         oldLnPrior = LnUniformPriorPr(oldTree, clockRate);
7241         newLnPrior = LnUniformPriorPr(newTree, clockRate);
7242         (*lnPriorRatio) = (newLnPrior - oldLnPrior);
7243         }
7244     else if (!strcmp(mp->clockPr,"Speciestreecoalescence"))
7245         {
7246         // Defer this calculation to the BEST code
7247         }
7248
7249     assert (*lnPriorRatio > NEG_INFINITY);
7250
7251     /* take care of calibrations */
7252     if (newTree->isCalibrated == YES)
7253         {
7254         for (i=0; i<newTree->nNodes-1; i++)
7255             {
7256             p = newTree->allDownPass[i];
7257             if (p->isDated == NO)
7258                 continue;
7259             for (j=0; j<oldTree->nNodes-1; j++)
7260                 {
7261                 q = oldTree->allDownPass[j];
7262                 if (p->lockID == q->lockID)
7263                     break;
7264                 }
7265             assert (j != oldTree->nNodes-1);
7266             if (p->isDated == YES && p->calibration->prior != fixed)
7267                 {
7268                 (*lnPriorRatio) += p->calibration->LnPriorRatio(p->age, q->age, p->calibration->priorParams);
7269                 }
7270             }
7271         }
7272
7273     return (NO_ERROR);
7274 }
7275
7276
7277 /*-----------------------------------------------------------------
7278 |
7279 |   LogLike: calculate the log likelihood of the new state of the chain
7280 |
7281 -----------------------------------------------------------------*/
7282 MrBFlt LogLike (int chain)
7283 {
7284     int             i, d;
7285     ModelInfo       *m;
7286     MrBFlt          chainLnLike, lnL;
7287                         
7288     /* initialize chain cond like */
7289     chainLnLike = 0.0;
7290     
7291     if (chainParams.runWithData == NO)
7292         return (chainLnLike);
7293
7294 #   if defined (DEBUG_RUN_WITHOUT_DATA)
7295     return (chainLnLike);
7296 #   endif
7297
7298 #   if defined (THREADS_ENABLED)
7299     if (tryToUseThreads && ScheduleLogLikeForAllDivisions()) 
7300         {
7301         /* Launch all divisions that require updating simultaneously */
7302         chainLnLike = LaunchLogLikeForAllDivisionsInParallel(chain);
7303         } 
7304     else 
7305         {
7306         /* Launch divisions in series */
7307 #   endif
7308         
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++)
7313         {
7314         
7315 #   if defined (BEST_MPI_ENABLED)
7316         if (isDivisionActive[d] == NO)
7317             continue;
7318 #   endif
7319         m = &modelSettings[d];
7320         if (m->upDateCl == YES) 
7321             {   
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]]));
7325             }
7326         if (abortMove == YES)
7327             return MRBFLT_NEG_MAX;
7328         chainLnLike += m->lnLike[2*chain + state[chain]];   
7329         }
7330         
7331 #   if defined (THREADS_ENABLED)
7332         }
7333 #   endif
7334
7335     /* unmark all divisions */
7336     if (chainHasAdgamma == YES)
7337         {
7338         for (d=0; d<numCurrentDivisions; d++)
7339             {
7340             m = &modelSettings[d];
7341             m->mark = NO;
7342             }
7343         
7344         /* update HMM likelihoods if appropriate */
7345         for (d=0; d<numCurrentDivisions; d++)
7346             {
7347 #   if defined (BEST_MPI_ENABLED)
7348             if (isDivisionActive[d] == NO)
7349                 continue;
7350 #   endif
7351             m = &modelSettings[d];
7352             
7353             if (m->upDateCl == YES && m->correlation != NULL && m->mark != YES)
7354                 {
7355                 lnL = 0.0;
7356                 CalcLikeAdgamma(d, m->correlation, chain, &lnL);
7357
7358                 /* store the value for the cases where the HMM is not touched */
7359                 m->lnLike[2*chain + state[chain]] =  lnL;
7360                 
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 */
7363                 chainLnLike += lnL;
7364                 
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++)
7368                     {
7369                     if (modelSettings[m->correlation->relParts[i]].shape == modelSettings[d].shape)
7370                         {
7371                         modelSettings[m->correlation->relParts[i]].mark = YES;
7372                         }
7373                     }
7374                 }
7375             }
7376         }
7377
7378     return (chainLnLike);   
7379 }
7380
7381
7382 MrBFlt LogOmegaPrior (MrBFlt w1, MrBFlt w2, MrBFlt w3)
7383 {
7384
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. */
7395        
7396     MrBFlt  lnProb;
7397     
7398     lnProb = log(36.0) - 4.0 * log(1.0 + w1 + w2 + w3);
7399      
7400     return (lnProb);
7401 }
7402
7403  
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)                                                       */
7409 /*                                                                                                               */
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 /* ------------------------------------------------------------------------------------------------------------- */
7416
7417 /* external (tip): 1, internal: 0 */
7418 #define IsTip(Node) (Node->index < numTaxa || (Node->anc)->index < numTaxa)
7419
7420 MrBFlt LogDirPrior (Tree *t, ModelParams *mp, int PV)
7421 {
7422     /* ln prior prob. under Dirichlet priors and twoExp prior
7423      //chi */
7424
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;
7428     TreeNode  *p;
7429     
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)
7433         {
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];
7439     
7440         for (i = 0; i < t->nNodes; i++)
7441             {
7442             p = t->allDownPass[i];
7443             if (p->anc != NULL)
7444                 {
7445                 treeL += p->length;
7446                 nb[IsTip(p)]++;
7447                 tb[IsTip(p)] += log(p->length);
7448                 }
7449             }
7450         lnprior += (a-1)*tb[1] + (a*c -1)*tb[0];
7451         if (PV == 2)
7452             lnprior += (aT - a*nb[1] - a*c*nb[0]) * log(treeL) - bT*treeL;
7453         else
7454             lnprior += (-aT - a*nb[1] - a*c*nb[0]) * log(treeL) - bT/treeL;
7455         }
7456     /* or 4: twoExp prior */
7457     else if (PV == 4)
7458         {
7459         for (i = 0; i < t->nNodes; i++) {
7460             p = t->allDownPass[i];
7461             if (p->anc != NULL)
7462                 {
7463                 nb[IsTip(p)]++;
7464                 tb[IsTip(p)] += p->length;
7465                 }
7466             }
7467         for (i = 0; i < 2; i++)
7468             lnprior += nb[i] * log(mp->brlens2Exp[i]) - tb[i] * (mp->brlens2Exp[i]);
7469         }
7470     
7471     return lnprior;
7472 }
7473
7474
7475 MrBFlt LogPrior (int chain)
7476 {
7477     int             i, j, c, n, nStates, *nEvents, sumEvents, *ist, nRates, nParts[6];
7478     const int       *rateCat;
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;
7481     char            *sS;
7482     CLFlt           *nSitesOfPat;
7483     Param           *p;
7484     ModelParams     *mp;
7485     ModelInfo       *m;
7486     Tree            *t;
7487     TreeNode        *branch, *q;
7488     
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. */
7491
7492     lnPrior = 0.0;
7493     for (n=0; n<numParams; n++)
7494         {
7495         p = &params[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)
7502             continue;
7503 #   endif
7504         
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]];
7509
7510         if (p->paramType == P_TRATIO)
7511             {
7512             /* tratio parameter */
7513             if (p->paramId == TRATIO_DIR)
7514                 {
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]);
7521                 for (i=0; i<2; i++)
7522                     x += (alphaDir[i]-1.0)*log(newProp[i]);
7523                 lnPrior += x;
7524                 }
7525             }
7526         else if (p->paramType == P_REVMAT)
7527             {
7528             /* revmat parameter */
7529             if (p->paramId == REVMAT_DIR)
7530                 {
7531                 if (p->nValues == 6)
7532                     alphaDir = mp->revMatDir;
7533                 else /* if (p->nValues == 190) */
7534                     alphaDir = mp->aaRevMatDir;
7535                 sum = 0.0;
7536                 for (i=0; i<p->nValues; i++)
7537                     sum += alphaDir[i];
7538                 x = LnGamma(sum);
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]);
7543                 lnPrior += x;
7544                 }
7545             else if (p->paramId == REVMAT_MIX)
7546                 {
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++)
7553                     {
7554                     newProp[i] = 0.0;
7555                     nParts[i] = 0;
7556                     }
7557                 for (i=0; i<6; i++)
7558                     {
7559                     nParts[ist[i]]++;
7560                     newProp[ist[i]] += st[i];
7561                     }
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);
7571                 lnPrior += x;
7572                 }
7573             else
7574                 {
7575                 /* fixed or empirical */
7576                 }
7577             }
7578         else if (p->paramType == P_OMEGA)
7579             {
7580             /* account for prior on omega proportion if 1 omega category */
7581             if (p->paramId == OMEGA_DIR)
7582                 {
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]);
7588                 for (i=0; i<2; i++)
7589                     x += (alphaDir[i]-1.0)*log(newProp[i]);
7590                 lnPrior += x;
7591                 }
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)
7597                 {
7598                 alphaDir = mp->codonCatDir;             
7599                 x = 0.0;
7600                 for (i=0; i<3; i++)
7601                     x += (alphaDir[i]-1.0)*log(sst[i]);
7602                 lnPrior += x;
7603                 }
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)
7608                 {
7609                 alphaDir = mp->ny98omega1Beta;
7610                 newProp[0] = st[0] / (st[0] + 1.0);
7611                 newProp[1] = 1.0 - newProp[0];
7612                 x = 0.0;
7613                 for (i=0; i<2; i++)
7614                     x += (alphaDir[i]-1.0)*log(newProp[i]);
7615                 lnPrior += x;
7616                 }
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)
7620                 {
7621                 lnPrior += log(1.0) - log(mp->ny98omega3Uni[1] - mp->ny98omega3Uni[0]);
7622                 }
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)
7626                 {
7627                 lnPrior += (log(mp->ny98omega3Exp) - mp->ny98omega3Exp * st[2]);
7628                 }
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)
7631                 {
7632                 lnPrior += LogOmegaPrior (st[0], st[1], st[2]);
7633                 }
7634             }
7635         else if (p->paramType == P_PI)
7636             {
7637             /* state frequencies parameter */
7638             if (p->paramId == PI_DIR)
7639                 {
7640                 nStates = p->nSubValues;
7641                 sum = 0.0;
7642                 for (i=0; i<nStates; i++)
7643                     sum += st[i];
7644                 x = LnGamma(sum);
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]);
7649                 lnPrior += x;
7650                 }
7651             else if (p->paramId == SYMPI_EXP || p->paramId == SYMPI_EXP_MS)
7652                 {
7653                 lnPrior += - mp->symBetaExp * st[0] + log(mp->symBetaExp);
7654                 }
7655             else if (p->paramId == SYMPI_UNI || p->paramId == SYMPI_UNI_MS)
7656                 {
7657                 lnPrior += log(1.0) - log(mp->symBetaUni[1] - mp->symBetaUni[0]);
7658                 }                
7659             if (p->paramId == SYMPI_EXP_MS || p->paramId == SYMPI_UNI_MS || p->paramId == SYMPI_FIX_MS)
7660                 {
7661                 sst = GetParamStdStateFreqs(p, chain, state[chain]);
7662                 sst += 2*m->numBetaCats;
7663                 for (i=0; i<p->nSympi; i++)
7664                     {
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]);
7669                     lnPrior += x;
7670                     sst += nStates;
7671                     }
7672                 }
7673             }
7674         else if (p->paramType == P_SHAPE)
7675             {
7676             /* gamma/lnorm shape parameter */
7677             if (p->paramId == SHAPE_UNI)
7678                 {
7679                 lnPrior += log(1.0) - log(mp->shapeUni[1] - mp->shapeUni[0]);
7680                 }
7681             else if (p->paramId == SHAPE_EXP)
7682                 {
7683                 lnPrior += log(mp->shapeExp) - mp->shapeExp * st[0];
7684                 }
7685             for (i=0; i<p->nRelParts; i++)
7686                 {
7687                 m = &modelSettings[p->relParts[i]];
7688                 if (m->gibbsGamma == YES)
7689                     {
7690                     if (m->pInvar == NULL)
7691                         lnPrior += log(1.0/m->numGammaCats) * m->numUncompressedChars;
7692                     else
7693                         {
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++)
7699                             {
7700                             if (rateCat[c] < m->numGammaCats)
7701                                 lnPrior += log(freq) * nSitesOfPat[c];
7702                             else
7703                                 lnPrior += log(pInvar) * nSitesOfPat[c];
7704                             }
7705                         }
7706                     }
7707                 }
7708             }
7709         else if (p->paramType == P_PINVAR)
7710             {
7711             /* proportion of invariable sites parameter */
7712             lnPrior += log(1.0) - log(mp->pInvarUni[1] - mp->pInvarUni[0]);
7713             }
7714         else if (p->paramType == P_CORREL)
7715             {
7716             /* adGamma model parameter */
7717             lnPrior += log(1.0) - log(mp->corrUni[1] - mp->corrUni[0]);
7718             }
7719         else if (p->paramType == P_SWITCH)
7720             {
7721             /* switching rate parameter of covarion model */
7722             if (p->paramId == SWITCH_UNI)
7723                 {
7724                 lnPrior += log(1.0) - log(mp->covswitchUni[1] - mp->covswitchUni[0]);
7725                 }
7726             else if (p->paramId == SWITCH_EXP)
7727                 {
7728                 lnPrior += log(mp->covswitchExp) - mp->covswitchExp * st[0];
7729                 }
7730             }
7731         else if (p->paramType == P_RATEMULT && p->nValues > 1)
7732             {
7733             nStates = p->nValues;
7734             sum = 0.0;
7735             for (i=0; i<nStates; i++)
7736                 sum += sst[i+nStates];
7737             x = LnGamma(sum);
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++)
7744                 sum += sst[i];
7745             for (i=0; i<nStates; i++) {
7746                 if (i < nStates-1)
7747                     x += (sst[i+nStates]) * log(sst[i]/sum);
7748                 else
7749                     x += (sst[i+nStates] - 1.0) * log(sst[i]/sum);
7750                 }
7751             lnPrior += x;
7752             }
7753         else if (p->paramType == P_GENETREERATE && p->nValues > 1)
7754             {
7755             nStates = p->nValues;
7756             sum = 0.0;
7757             for (i=0; i<nStates; i++)
7758                 sum += sst[i+nStates];
7759             x = LnGamma(sum);
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++)
7766                 sum += sst[i];
7767             for (i=0; i<nStates; i++) {
7768                 if (i < nStates-1)
7769                     x += (sst[i+nStates]) * log(sst[i]/sum);
7770                 else
7771                     x += (sst[i+nStates] - 1.0) * log(sst[i]/sum);
7772                 }
7773             lnPrior += x;
7774             }
7775         else if (p->paramType == P_TOPOLOGY)
7776             {
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
7780             // parameter.
7781             t = GetTree (p, chain, state[chain]);
7782             if (t->isClock == YES)
7783                 continue;   /* prior probability taken care of in the brlens parameter */
7784             if (t->nLocks > 0)
7785                 {
7786                 for (i=0; i<t->nNodes-1; i++)
7787                     {
7788                     branch = t->allDownPass[i];
7789                     if (branch->left == NULL)
7790                         branch->x = 1;
7791                     else
7792                         branch->x = branch->left->x + branch->right->x;
7793                     if (branch->isLocked == YES || branch->anc->anc == NULL)
7794                         {
7795                         for (j = 2*branch->x - 3; j>=1; j-=2)
7796                             {
7797                             lnPrior -= log ((MrBFlt)j);
7798                             }
7799                         branch->x = 1;
7800                         }
7801                     }
7802                 }
7803             else
7804                 {
7805                 for (j = 2*(t->nNodes-t->nIntNodes)-5; j>=1; j-=2)
7806                     {
7807                     lnPrior -= log ((MrBFlt)j);
7808                     }
7809                 }
7810             }
7811         else if (p->paramType == P_BRLENS)
7812             {
7813             /* branch lengths */
7814             t = GetTree (p, chain, state[chain]);
7815             if (t->isClock == YES)
7816                 {
7817                 if (p->paramId == BRLENS_CLOCK_UNI)
7818                     {
7819                     /* uniformly distributed branch lengths */
7820                     clockRate = *(GetParamVals (m->clockRate, chain, state[chain]));
7821                     lnPrior += LnUniformPriorPr(t, clockRate);
7822                     }
7823                 else if (p->paramId == BRLENS_CLOCK_COAL)
7824                     {
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;
7832                     else
7833                         theta = 2.0 * popSize * clockRate;
7834                     if (!strcmp(mp->growthPr, "Fixed"))
7835                         growth = mp->growthFix;
7836                     else
7837                         growth = *(GetParamVals (m->growthRate, chain, state[chain]));
7838                     if (LnCoalescencePriorPr (t, &x, theta, growth) == ERROR)
7839                         {
7840                         MrBayesPrint ("%s   Problem calculating prior for coalescence process\n", spacer);
7841                         }
7842                     lnPrior += x;
7843                     }
7844                 else if (p->paramId == BRLENS_CLOCK_BD)
7845                     {
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]));
7853                     else
7854                         clockRate = 1.0;
7855                     if (LnBirthDeathPriorPr (t, clockRate, &x, *sR, *eR, sS, sF) == ERROR)
7856                         {
7857                         MrBayesPrint ("%s   Problem calculating prior for birth-death process\n", spacer);
7858                         }
7859                     lnPrior += x;
7860                     }
7861                 else if (p->paramId == BRLENS_CLOCK_FOSSIL)
7862                     {
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]));
7871                     else
7872                         clockRate = 1.0;
7873                     if (LnFossilizationPriorPr (t, clockRate, &x, sR, eR, sF, fR, sS) == ERROR)
7874                         {
7875                         MrBayesPrint ("%s   Problem calculating prior for fossilized birth-death process\n", spacer);
7876                         }
7877                     lnPrior += x;
7878                     }
7879                 else if (p->paramId == BRLENS_CLOCK_SPCOAL)
7880                     {
7881                     /* delegate this calculation to the P_SPECIESTREE parameter */
7882                     }
7883                 if (t->isCalibrated == YES)
7884                     {
7885                     /* take care of calibrations */
7886                     for (i=0; i<t->nNodes-1; i++)
7887                         {
7888                         q = t->allDownPass[i];
7889                         if (q->isDated == YES && q->calibration->prior != fixed)
7890                             {
7891                             lnPrior += q->calibration->LnPriorProb(q->age, q->calibration->priorParams);
7892                             }
7893                         }
7894                     }
7895                 }
7896             else
7897                 {
7898                 if (p->paramId == BRLENS_UNI)
7899                     {
7900                     for (i=0; i<t->nNodes; i++)
7901                         {
7902                         branch = t->allDownPass[i];
7903                         if (branch->anc != NULL)
7904                             lnPrior += log(1.0) - log(mp->brlensUni[1] - BRLENS_MIN);
7905                         }
7906                     }
7907                 else if (p->paramId == BRLENS_EXP)
7908                     {
7909                     for (i=0; i<t->nNodes; i++)
7910                         {
7911                         branch = t->allDownPass[i];
7912                         if (branch->anc != NULL)
7913                             lnPrior += log(mp->brlensExp) - mp->brlensExp * branch->length;
7914                         }
7915                     }
7916                 /* Dirichlet priors */
7917                 else if (p->paramId == BRLENS_GamDir)  
7918                     {
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]);
7923                     } 
7924                 else if (p->paramId == BRLENS_iGmDir)
7925                     {
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]);
7930                     }
7931                 /* twoExp prior */
7932                 else if (p->paramId == BRLENS_twoExp)
7933                     lnPrior += LogDirPrior(t, mp, 4);
7934                 }
7935             }
7936         else if (p->paramType == P_SPECRATE)
7937             {
7938             /* speciation rate parameter */
7939             if (p->paramId == SPECRATE_UNI)
7940                 {
7941                 for (i=0; i<p->nValues; i++)
7942                     lnPrior += log(1.0) - log(mp->speciationUni[1] - mp->speciationUni[0]);
7943                 }
7944             else if (p->paramId == SPECRATE_EXP)
7945                 {
7946                 for (i=0; i<p->nValues; i++)
7947                     lnPrior += log(mp->speciationExp) - mp->speciationExp * st[i];
7948                 }
7949             }
7950         else if (p->paramType == P_EXTRATE)
7951             {
7952             /* extinction rate parameter */
7953             if (p->paramId == EXTRATE_BETA)
7954                 {
7955                 for (i=0; i<p->nValues; i++)
7956                     {
7957                     alphaDir = mp->extinctionBeta;
7958                     newProp[0] =  st[i];
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]);
7962                     }
7963                 }
7964             }
7965         else if (p->paramType == P_FOSLRATE)
7966             {
7967             /* fossilization rate parameter */
7968             if (p->paramId == FOSLRATE_BETA)
7969                 {
7970                 for (i=0; i<p->nValues; i++)
7971                     {
7972                     alphaDir = mp->fossilizationBeta;
7973                     newProp[0] =  st[i];
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]);
7978                     }
7979                 }
7980             }
7981         else if (p->paramType == P_POPSIZE)
7982             {
7983             /* neutral coalescence population size parameter; one value, or one value per branch of species tree */
7984             for (i=0; i<p->nValues; i++)
7985                 {
7986                 lnPrior += p->LnPriorProb(st[i], p->priorParams);
7987                 }
7988             }
7989         else if (p->paramType == P_AAMODEL)
7990             {
7991             lnPrior += sst[(int)st[0]];
7992             }
7993         else if (p->paramType == P_BRCORR)
7994             {
7995
7996             }
7997         else if (p->paramType == P_BRSIGMA)
7998             {
7999
8000             }
8001         else if (p->paramType == P_GROWTH)
8002             {
8003             /* population growth parameter */
8004             if (p->paramId == GROWTH_UNI)
8005                 {
8006                 lnPrior += log(1.0) - log(mp->growthUni[1] - mp->growthUni[0]);
8007                 }
8008             else if (p->paramId == GROWTH_EXP)
8009                 {
8010                 lnPrior += log(mp->growthExp) - mp->growthExp * st[0];
8011                 }
8012             }
8013         else if (p->paramType == P_CPPRATE)
8014             {
8015             /* rate (lambda) of comp poisson process of relaxed clock */
8016             if (p->paramId == CPPRATE_EXP)
8017                 {
8018                 lnPrior += log (mp->cppRateExp) - mp->cppRateExp * st[0];
8019                 }
8020             }
8021         else if (p->paramType == P_CPPMULTDEV)
8022             {
8023             /* standard deviation (log) of lognormal distribution of rate multipliers for cpp relaxed clock */
8024             /* only fixed value allowed currently */
8025             }
8026         else if (p->paramType == P_CPPEVENTS)
8027             {
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]];
8033             /* cpp events */
8034             sumEvents = 0;
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++)
8041                 {
8042                 for (j=0; j<nEvents[i]; j++)
8043                     lnPrior += LnProbLogNormal (0.0, sigma, rateMultiplier[i][j]);
8044                 }
8045             for (i=0; i<t->nNodes-2; i++)
8046                 {
8047                 branch = t->allDownPass[i];
8048                 assert (fabs(branch->length - (branch->anc->nodeDepth - branch->nodeDepth)) < 0.000001);
8049                 }
8050             }
8051         else if (p->paramType == P_TK02VAR)
8052             {
8053             /* variance of rates (nu) in Thorne-Kishino model */
8054             if (p->paramId == TK02VAR_EXP)
8055                 {
8056                 lnPrior += log (mp->tk02varExp) - mp->tk02varExp * st[0];
8057                 }
8058             else if (p->paramId == TK02VAR_UNI)
8059                 {
8060                 lnPrior += log(1.0) - log (mp->tk02varUni[1] - mp->tk02varUni[0]);
8061                 }
8062             }
8063         else if (p->paramType == P_TK02BRANCHRATES || (p->paramType == P_MIXEDBRCHRATES && *GetParamIntVals(p, chain, state[chain]) == RCL_TK02))
8064             {
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]);
8069             else
8070                 nu = *GetParamVals (m->mixedvar, chain, state[chain]);
8071             for (i=0; i<t->nNodes-2; i++)
8072                 {
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]);
8076                 }
8077             }
8078         else if (p->paramType == P_IGRVAR)
8079             {
8080             /* variance of rates in independent gamma rates model */
8081             if (p->paramId == IGRVAR_EXP)
8082                 {
8083                 lnPrior += log (mp->igrvarExp) - mp->igrvarExp * st[0];
8084                 }
8085             else if (p->paramId == IGRVAR_UNI)
8086                 {
8087                 lnPrior += log(1.0) - log (mp->igrvarUni[1] - mp->igrvarUni[0]);
8088                 }
8089             }
8090         else if (p->paramType == P_IGRBRANCHRATES || (p->paramType == P_MIXEDBRCHRATES && *GetParamIntVals(p, chain, state[chain]) == RCL_IGR))
8091             {
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]);
8096             else
8097                 igrvar = *GetParamVals (m->mixedvar, chain, state[chain]);
8098             for (i=0; i<t->nNodes-2; i++)
8099                 {
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);
8105                 }
8106             }
8107         else if (p->paramType == P_MIXEDVAR)
8108             {
8109             /* hyper prior of rates in mixed rel clock model */
8110             if (p->paramId == MIXEDVAR_EXP)
8111                 {
8112                 lnPrior += log (mp->mixedvarExp) - mp->mixedvarExp * st[0];
8113                 }
8114             else if (p->paramId == MIXEDVAR_UNI)
8115                 {
8116                 lnPrior += log(1.0) - log (mp->mixedvarUni[1] - mp->mixedvarUni[0]);
8117                 }
8118             }
8119         else if (p->paramType == P_CLOCKRATE)
8120             {
8121             /* base rate of molecular clock */
8122             lnPrior += p->LnPriorProb(st[0], p->priorParams);
8123             }
8124         else if (p->paramType == P_SPECIESTREE)
8125             {
8126             /* calculate prior */
8127             lnPrior += LnSpeciesTreeProb(chain);
8128             }
8129         }
8130     assert (lnPrior == lnPrior);
8131
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);
8136 #   endif
8137
8138     return (lnPrior);
8139 }
8140
8141
8142 int LnBirthDeathPriorPr (Tree *t, MrBFlt clockRate, MrBFlt *prob, MrBFlt sR, MrBFlt eR, char *sS, MrBFlt sF)
8143 {
8144     if (!strcmp(sS, "Random")) 
8145         {
8146         return LnBirthDeathPriorPrRandom (t, clockRate, prob, sR, eR, sF);
8147         }
8148     else if (!strcmp(sS, "Diversity")) 
8149         {
8150         return LnBirthDeathPriorPrDiversity (t, clockRate, prob, sR, eR, sF);
8151         }
8152     else if (!strcmp(sS, "Cluster")) 
8153         {
8154         return LnBirthDeathPriorPrCluster (t, clockRate, prob, sR, eR, sF);
8155         }
8156     else 
8157         {
8158         MrBayesPrint ("%s   ERROR: Sampling strategy for birth-death process not implemented\n", spacer);
8159         return (ERROR);
8160         }
8161 }
8162
8163
8164 /*---------------------------------------------------------------------------------
8165 |
8166 |   LnBirthDeathPriorPrRandom
8167 |
8168 |   We assume a rooted tree that satisfies the molecular clock constraint. The
8169 |   tree is labelled as follows:
8170 |
8171 |                                      t_4 (age of tips)
8172 |     \         \         \        /            
8173 |      \         \         \      /              
8174 |       \         \         \    /         
8175 |        \         \         \  /          
8176 |         \         \         \/       t_3 
8177 |          \         \        /            
8178 |           \         \      /             
8179 |            \         \    /              
8180 |             \         \  /               
8181 |              \         \/            t_2  
8182 |               \        /                 
8183 |                \      /                  
8184 |                 \    /                        
8185 |                  \  /                         
8186 |                   \/                 t_1 (age of most recent common ancestor)
8187 |    
8188 |
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:
8194 |
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
8202 |
8203 |   See:
8204 |   Tanja Stadler (2009) On incomplete sampling under birth-death models and
8205 |   connections to the sampling-based coalescent. Journal of Theoretical Biology
8206 |   261: 58-66.
8207 |
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:
8211 |
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):
8214 |
8215 |
8216 |              n! * p1(t_1)    n-1
8217 |   f(T|n) = --------------- * prod (b * p1(t_i))
8218 |             (1 - p0(t_1))    i=1
8219 |
8220 |
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)
8224 |
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:
8229 |
8230 |              n * p1(t_1)     n-1
8231 |   f(T|n) = --------------- * prod (b * p1(t_i))
8232 |             (1 - p0(t_1))    i=1
8233 |
8234 |
8235 |   To translate this to a density on distinct labeled trees, the density needs to be multiplied by
8236 |   (2^(n-1) / n!).
8237 |
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)):
8240 |
8241 |                  n          n-1          f*b      
8242 |   f(T|n) = -------------- * prod -----------------
8243 |            (1 + f*b*t_1)    i=1   (1 + f*b*t_i)^2
8244 |
8245 ---------------------------------------------------------------------------------*/
8246 int LnBirthDeathPriorPrRandom (Tree *t, MrBFlt clockRate, MrBFlt *prob, MrBFlt sR, MrBFlt eR, MrBFlt sF)
8247 {
8248     int             i, nTaxa;
8249     MrBFlt          *nt, lambda, mu, rho;
8250     TreeNode        *p;
8251
8252     /* allocate space for the speciation times */
8253     nt = (MrBFlt *)SafeMalloc((size_t)(t->nIntNodes) * sizeof(MrBFlt));
8254     if (!nt)
8255         {
8256         MrBayesPrint ("\n   ERROR: Problem allocating nt\n");
8257         return (ERROR);
8258         }
8259
8260     /* transform to standard variables */
8261     rho    = sF;
8262     lambda = sR / (1.0 - eR);
8263     mu     = eR * lambda;
8264
8265     /* get the node times and put them into a vector */
8266     for (i=0; i<t->nIntNodes; i++)
8267         {
8268         p = t->intDownPass[i];
8269         nt[i] = p->nodeDepth / clockRate;
8270         }
8271     nTaxa = t->nIntNodes + 1;
8272
8273     /* calculate probability of tree using standard variables */
8274     if (AreDoublesEqual(lambda,mu,ETA)==NO)
8275         {
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 */
8282         }
8283     else
8284         {
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 */
8290         }
8291
8292     /* free memory */
8293     free (nt);
8294     
8295     return (NO_ERROR);
8296 }
8297
8298
8299 /*---------------------------------------------------------------------------------
8300  |
8301  |   LnBirthDeathPriorPrDiversity
8302  |
8303  |   Eq.5 in Hohna et al. 2011 MBE
8304  |
8305  ---------------------------------------------------------------------------------*/
8306 int LnBirthDeathPriorPrDiversity (Tree *t, MrBFlt clockRate, MrBFlt *prob, MrBFlt sR, MrBFlt eR, MrBFlt sF)
8307 {
8308     int             i, nTaxa, n, m;
8309     MrBFlt          *nt, lambda, mu, nt_min;
8310     TreeNode        *p;
8311     
8312     /* allocate space for the speciation times */
8313     nt = (MrBFlt *)SafeMalloc((size_t)(t->nIntNodes) * sizeof(MrBFlt));
8314     if (!nt)
8315         {
8316         MrBayesPrint ("\n   ERROR: Problem allocating nt\n");
8317         return (ERROR);
8318         }
8319     
8320     /* transform to standard variables */
8321     lambda = sR / (1.0 - eR);
8322     mu     = eR * lambda;
8323     
8324     n      = t->nIntNodes+1;
8325     m      = (int)floor(n/sF+0.5); /* equal to round(n/sF) plus it is compatible with MS Visual Studio */
8326     
8327     /* get the node times and put them into a vector */
8328     for (i=0; i<t->nIntNodes; i++)
8329         {
8330         p = t->intDownPass[i];
8331         nt[i] = p->nodeDepth / clockRate;
8332         }
8333     nTaxa = t->nIntNodes + 1;
8334
8335     /* find the youngest interal node */
8336     nt_min = nt[0];
8337     for (i=0; i<t->nIntNodes-1; i++)
8338         {
8339         if (nt_min > nt[i])
8340             nt_min = nt[i];
8341         }
8342     
8343     /* calculate probability of tree using standard variables */
8344     if (AreDoublesEqual(lambda,mu,ETA)==NO)
8345         {
8346         // birth rate != death rate
8347         MrBFlt p0_t1;
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 */
8354         }
8355     else
8356         {
8357         MrBayesPrint ("\n   ERROR: Critical branchin process for diversity sampling not implemented\n");
8358         return (ERROR);
8359         }
8360
8361     /* condition on tmrca ??? */
8362
8363     /* free memory */
8364     free (nt);
8365     
8366     return (NO_ERROR);
8367 }
8368
8369
8370 /*---------------------------------------------------------------------------------
8371  |
8372  |   LnBirthDeathPriorPrCluster
8373  |
8374  |   Eq.7 in Hohna et al. 2011 MBE
8375  |
8376  ---------------------------------------------------------------------------------*/
8377 int LnBirthDeathPriorPrCluster (Tree *t, MrBFlt clockRate, MrBFlt *prob, MrBFlt sR, MrBFlt eR, MrBFlt sF)
8378 {
8379     int             i, nTaxa, n, m;
8380     MrBFlt          *nt, lambda, mu, nt_max;
8381     TreeNode        *p;
8382     
8383     /* allocate space for the speciation times */
8384     nt = (MrBFlt *)SafeMalloc((size_t)(t->nIntNodes) * sizeof(MrBFlt));
8385     if (!nt)
8386         {
8387         MrBayesPrint ("\n   ERROR: Problem allocating nt\n");
8388         return (ERROR);
8389         }
8390     
8391     /* transform to standard variables */
8392     lambda = sR / (1.0 - eR);
8393     mu     = eR * lambda;
8394     
8395     n      = t->nIntNodes+1;
8396     m      = (int)floor(n/sF+0.5); /* equal to round(n/sF) plus it is compatible with MS Visual Studio */
8397     
8398     /* get the node times and put them into a vector */
8399     for (i=0; i<t->nIntNodes; i++)
8400         {
8401         p = t->intDownPass[i];
8402         nt[i] = p->nodeDepth / clockRate;
8403         }
8404     nTaxa = t->nIntNodes + 1;
8405     
8406     /* find the second oldest interal node */
8407     nt_max = nt[0];
8408     for (i=0; i<t->nIntNodes-1; i++)
8409         {
8410         if (nt_max < nt[i])
8411             nt_max = nt[i];
8412         }
8413
8414     /* calculate probability of tree using standard variables */
8415     if (AreDoublesEqual(lambda,mu,ETA)==NO)
8416         {
8417         // birth rate != death rate
8418         MrBFlt p0_t1;
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 */
8425         }
8426     else
8427         {
8428         MrBayesPrint ("\n   ERROR: Critical branchin process for cluster sampling not implemented\n");
8429         return (ERROR);
8430         }
8431
8432     /* condition on tmrca ??? */
8433
8434     /* free memory */
8435     free (nt);
8436     
8437     return (NO_ERROR);
8438 }
8439
8440
8441 /*
8442  |
8443  | The probability of having zero lineages remaining after time t in the
8444  | birth-death process.
8445  |
8446  | param: t - speciation time
8447  | param: b - birth rate
8448  | param: d - death rate
8449  | return: log probability of zero remaining lineages
8450  |
8451  */
8452 MrBFlt LnP0 (MrBFlt t, MrBFlt b, MrBFlt d)
8453 {
8454     MrBFlt      p0t;
8455     
8456     p0t = d*(1.0-exp((d-b)*t)) / (b -d*exp((d-b)*t));
8457     
8458     return (log(p0t));
8459 }
8460
8461 /*
8462  |
8463  | The probability of having zero lineages remaining after time t in the
8464  | birth-death process.
8465  |
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
8471  |
8472  */
8473 MrBFlt LnP0Subsample (MrBFlt t, MrBFlt b, MrBFlt d, MrBFlt f)
8474 {
8475     MrBFlt      p0t;
8476     
8477     p0t = (f*d + (b*(1.0-f) - d)*exp((d-b)*t)) / (f*b + (b*(1.0-f)-d)*exp((d-b)*t));
8478     
8479     return (log(p0t));
8480 }
8481
8482 /*
8483  |
8484  | The probability of having one lineage remaining after time t
8485  | in the birth-death process.
8486  |
8487  | param: t - speciation time
8488  | param: b - birth rate
8489  | param: d - death rate
8490  | return: log probability of one remaining lineage
8491  |
8492  */
8493 MrBFlt LnP1 (MrBFlt t, MrBFlt b, MrBFlt d)
8494 {
8495     MrBFlt      p0t;
8496     
8497     p0t = 2.0 * log(b-d) - (b-d)*t;
8498     
8499     p0t -= 2.0 * log(b - d*exp((d-b)*t));
8500     
8501     return p0t;
8502 }
8503
8504 /*
8505  |
8506  | The probability of having one lineage remaining after time t
8507  | in the birth-death process.
8508  |
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
8514  |
8515  */
8516 MrBFlt LnP1Subsample (MrBFlt t, MrBFlt b, MrBFlt d, MrBFlt f)
8517 {
8518     MrBFlt      p0t;
8519     
8520     p0t = (b-d) / (f*b + (b*(1.0-f)-d)*exp((d-b)*t));
8521     
8522     return (2.0*log(p0t) + (d-b)*t);
8523 }
8524
8525
8526 /* probability that an individual alive at time t before today has
8527    no sampled extinct or extant descendants
8528  */
8529 MrBFlt LnP0_fossil (MrBFlt t, MrBFlt lambda, MrBFlt mu, MrBFlt psi, MrBFlt c1, MrBFlt c2)
8530 {
8531     MrBFlt other;
8532     
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));
8536     
8537     return log(0.5) + log(lambda + mu + psi + c1 * other) - log(lambda);
8538 }
8539
8540 /* probability that an individual alive at time t before today has
8541    precisely one sampled extant descendant and no sampled extinct descendant
8542  */
8543 MrBFlt LnP1_fossil (MrBFlt t, MrBFlt rho, MrBFlt c1, MrBFlt c2)
8544 {
8545     MrBFlt other;
8546     
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);
8550     
8551     return log(4.0) + log(rho) - c1 *t - log(other);
8552 }
8553
8554
8555 /* return which time interval t is in */
8556 int Slice_i (MrBFlt t, MrBFlt *t_f, int sl)
8557 {
8558     int i = 0;
8559     assert (t > 0.0 && sl >= 0);
8560
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)
8563         {
8564         i++;
8565         if (i > sl)
8566             return sl;
8567         }
8568     return i;
8569 }
8570
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
8573  */
8574 MrBFlt  LnQi_fossil (MrBFlt t, MrBFlt *t_f, int sl, MrBFlt *c1, MrBFlt *c2)
8575 {
8576     MrBFlt lnq;
8577     int i = Slice_i (t, t_f, sl);
8578     
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)));
8581     
8582     return lnq;
8583 }
8584
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)
8587  */
8588 MrBFlt  LnPi_fossil (MrBFlt t, MrBFlt *t_f, int sl, MrBFlt *c1, MrBFlt *c2, MrBFlt *lambda, MrBFlt *mu, MrBFlt *psi)
8589 {
8590     MrBFlt other;
8591     int i = Slice_i (t, t_f, sl);
8592     
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]);
8596 }
8597
8598
8599 int LnFossilizationPriorPr (Tree *t, MrBFlt clockRate, MrBFlt *prob, MrBFlt *sR, MrBFlt *eR, MrBFlt sF, MrBFlt *fR, char *sS)
8600 {
8601     /* fossilization priors 
8602      //chi */
8603     
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);
8610     else
8611         {
8612         MrBayesPrint ("%s   Sampling strategy %s for fossilized birth-death process not implemented\n", spacer, sS);
8613         return (ERROR);
8614         }
8615 }
8616
8617
8618 /*---------------------------------------------------------------------------------
8619  |
8620  |                                          time  ___  0
8621  |     \                            /            |
8622  |      \                          /             |___  y2
8623  |       \                   \    /              |
8624  |        \                   \  /               |
8625  |         \                   \/         x3  ___|
8626  |          \                  /                 |___  y1
8627  |           \         \      /                  |
8628  |            \         \    /                   |
8629  |             \         \  /                    |
8630  |              \         \/              x2  ___|
8631  |               \        /                      |
8632  |                \      /                       |
8633  |                 \    /                        |
8634  |                  \  /                         |
8635  |                   \/                   x1  ___|
8636  |
8637  |
8638  |   T:   oriented tree
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
8645  |
8646  |
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)
8650  |
8651  |   f(tmrca) ~ uniform, gamma, etc (see treeAge).
8652  |
8653  ---------------------------------------------------------------------------------*/
8654 int LnFossilizedBDPriorFossilTip (Tree *t, MrBFlt clockRate, MrBFlt *prob, MrBFlt sR, MrBFlt eR, MrBFlt sF, MrBFlt fR)
8655 {
8656     /* special case: upon sampling the lineage is dead and won't produce descendants. Each extinct sample is a tip */
8657     
8658     int         i, n, m;
8659     MrBFlt      x, lambda, rho, psi, tmrca, c1, c2, hatP0;
8660     TreeNode    *p;
8661     Model       *mp;
8662     
8663     /* sR = lambda-mu-psi, eR = (mu+psi)/lambda, fR = psi/(mu+psi) */
8664     lambda = sR / (1.0 - eR);
8665     psi    = lambda * eR * fR;
8666     rho    = sF;
8667     
8668     tmrca = t->root->left->nodeDepth / clockRate;
8669     c1 = sqrt(sR*sR + 4 *lambda *psi);
8670     c2 = (2 *lambda *rho - sR) / c1;
8671
8672     /* calculate prior prob of the fbd tree */
8673     (*prob) = 0.0;
8674
8675     for (n = m = i = 0; i < t->nNodes -1; i++)
8676         {
8677         p = t->allDownPass[i];
8678         x = p->nodeDepth / clockRate;
8679
8680         if (p->left != NULL && p->right != NULL)  // internal
8681             {
8682             if (p != t->root->left)
8683                 (*prob) += log(lambda) + LnP1_fossil(x, rho, c1, c2);
8684             }
8685         else if (p->left == NULL && p->right == NULL)  // tip
8686             {
8687             if (p->nodeDepth > 0.0)
8688                 {
8689                 (*prob) += log(psi) - LnP1_fossil(x, rho, c1, c2);
8690                 m++;
8691                 }
8692             else
8693                 n++;
8694             }
8695         }
8696
8697     /* p_0 (t |psi=0, mu->mu+psi) */
8698     hatP0 = 1.0 - rho*sR / (rho*lambda + (sR - rho*lambda) * exp(-sR*tmrca));
8699     
8700     (*prob) += 2.0 * (LnP1_fossil(tmrca, rho, c1, c2) - log(1 - hatP0));
8701     
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);
8706     
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);
8709
8710     return (NO_ERROR);
8711 }
8712
8713
8714 /*---------------------------------------------------------------------------------
8715  |
8716  |   LnFossilizedBDPriorRandom
8717  |
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.
8722  |
8723  |
8724  |                                       0  _____________  t3, rho3
8725  |     \                            /          |
8726  |      \                          /           |___  y2
8727  |       \                   \    /   _________|_________  t2, rho2
8728  |        \                   \  /             |
8729  |         \                   \/       x3  ___|
8730  |          \                  /               |___  y1
8731  |           \         \      /                |
8732  |           _\         \    /        _________|_________  t1, rho1
8733  |             \         \  /                  |
8734  |              \         \/            x2  ___|
8735  |               \        /                    |
8736  |                \      /                     |
8737  |                 \    /                      |
8738  |                  \  /                       |
8739  |                   \/                 x1  ___|_________  t_mrca
8740  |
8741  |
8742  |    sl = 2, t1 > t2 > t3 = 0
8743  |    E = 2, K = 1, M = 2
8744  |
8745  ---------------------------------------------------------------------------------*/
8746 int LnFossilizedBDPriorRandom (Tree *t, MrBFlt clockRate, MrBFlt *prob, MrBFlt *sR, MrBFlt *eR, MrBFlt sF, MrBFlt *fR)
8747 {
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). */
8751     
8752     int         i, j, sl, K, M, E;
8753     MrBFlt      x, *lambda, *mu, *rho, *psi, *t_f, tmrca, *c1, *c2, *p_t;
8754     TreeNode    *p;
8755     Model       *mp;
8756     
8757     mp = &modelParams[t->relParts[0]];
8758     
8759     /* time of most recent common ancestor */
8760     tmrca = t->root->left->nodeDepth / clockRate;
8761     
8762     /* get the number of fossil slice sampling events, s >= 0 */
8763     sl = mp->sampleFSNum;
8764     
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));
8773     /* A_i, B_i, ... */
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));
8777     
8778     if (!lambda || !mu || !psi || !rho || !t_f || !c1 || !c2 || !p_t)
8779         {
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);
8783         }
8784     
8785     /* initialization */
8786     for (i = 0; i <= sl; i++)
8787         {
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]);
8792         if (i < sl) {
8793             rho[i] = mp->sampleFSProb[i];
8794             t_f[i] = mp->sampleFSTime[i];
8795             }
8796         }
8797     rho[sl] = sF;
8798     t_f[sl] = 0.0;
8799
8800     if (sl > 0)  assert (mp->sampleFSTime[0] < tmrca);
8801     for (i = sl; i >= 0; i--)
8802         {
8803         c1[i] = sqrt(pow(lambda[i]-mu[i]-psi[i], 2) + 4*lambda[i]*psi[i]);
8804         if (i == sl)
8805             c2[i] = ((1 - 2* (1-rho[i])) *lambda[i] +mu[i] +psi[i]) /c1[i];
8806         else
8807             c2[i] = ((1 - 2* (1-rho[i]) *p_t[i+1]) *lambda[i] +mu[i] +psi[i]) /c1[i];
8808         if (i > 0)
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];
8811         else
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];
8814         }
8815     
8816 #   ifdef DEBUG_FBDPR
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]);
8821 #   endif
8822     
8823     /* calculate prior prob of the fbd tree */
8824     (*prob) = 0.0;
8825     
8826     for (K = M = E = 0, i = 0; i < t->nNodes -1; i++)
8827         {
8828         p = t->allDownPass[i];
8829         x = p->nodeDepth / clockRate;
8830         
8831         if (p->left != NULL && p->right != NULL)  // internal
8832             {
8833             if (p->left->length > 0.0 && p->right->length > 0.0)
8834                 {
8835                 if (p != t->root->left)
8836                     (*prob) += log(lambda[Slice_i(x, t_f, sl)]) + LnQi_fossil(x, t_f, sl, c1,c2);
8837                 }
8838             else
8839                 {
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] */
8843                     {
8844                     (*prob) += log(psi[Slice_i(x, t_f, sl)]);
8845                     }
8846                 else              /* fossil ancestor at silice time t[j] */
8847                 if (rho[j] > 0.0 && rho[j] < 1.0)
8848                     {
8849                     (*prob) += log(rho[j]) - log(1 - rho[j]);
8850                     }
8851                 K++;              /* number of fossil ancestors */
8852                 }
8853             }
8854         else if (p->left == NULL && p->length > 0.0)  // tip
8855             {
8856             if (p->nodeDepth > 0.0)
8857                 {
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] */
8861                     {
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)]);
8865                     }
8866                 else              /* fossil tip at silice time t[j] */
8867                     {
8868                     (*prob) += log(p_t[j+1]);
8869                     if (rho[j] > 0.0)  (*prob) += log(rho[j]);
8870                     }
8871                 M++;              /* number of fossil tips */
8872                 }
8873             else
8874                 {
8875                 if (rho[sl] > 0.0)
8876                     {
8877                     (*prob) += log(rho[sl]);
8878                     }
8879                 E++;              /* number of extant taxa */
8880                 }
8881             }
8882         
8883         for (j = 0; j < sl; j++)  /* degree-two vertices at silice time t_j */
8884             {
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))
8887                     {
8888                     (*prob) += LnQi_fossil(t_f[j], t_f, sl, c1,c2);
8889                     if (rho[j] < 1.0)  (*prob) += log(1 - rho[j]);
8890                     }
8891             }
8892         }
8893     
8894     (*prob) += 2.0 * (LnQi_fossil(tmrca, t_f, sl, c1,c2) - log(1- p_t[0]));
8895     
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);
8899     
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)
8902     
8903 #   ifdef DEBUG_FBDPR
8904     printf ("K=%d M=%d E=%d\n", K, M, E);
8905     printf ("prob=%lf\n", *prob);
8906 #   endif
8907     
8908     /* free memory */
8909     free(lambda); free(mu); free(psi); free(rho);
8910     free(t_f); free(c1); free(c2); free(p_t);
8911     
8912     return (NO_ERROR);
8913 }
8914
8915
8916 /*---------------------------------------------------------------------------------
8917  |
8918  |   LnFossilizedBDPriorDiversity
8919  | 
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.
8922  |
8923  ---------------------------------------------------------------------------------*/
8924 int LnFossilizedBDPriorDiversity (Tree *t, MrBFlt clockRate, MrBFlt *prob, MrBFlt *sR, MrBFlt *eR, MrBFlt sF, MrBFlt *fR)
8925 {
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. */
8929     
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;
8932     TreeNode    *p;
8933     Model       *mp;
8934     
8935     mp = &modelParams[t->relParts[0]];
8936     
8937     /* time of most recent common ancestor */
8938     tmrca = t->root->left->nodeDepth / clockRate;
8939     
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;
8942     
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));
8951     /* A_i, B_i, ... */
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));
8955     
8956     if (!lambda || !mu || !psi || !rho || !t_f || !c1 || !c2 || !p_t)
8957         {
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);
8961         }
8962     
8963     /* get time of youngest fossil and internal node */
8964     t_min = x_min = tmrca;
8965     for (i = 0; i < t->nNodes -1; i++)
8966         {
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;
8975         }
8976
8977     /* lower the cutoff time if not compatible */
8978     if (x_min > t_min)
8979         x_min = t_min;
8980     if (sl > 1 && mp->sampleFSTime[sl-2] < x_min)
8981         x_min = mp->sampleFSTime[sl-2];
8982     
8983     /* initialization (sl >= 1) */
8984     for (i = 0; i < sl; i++)
8985         {
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]);
8990         }
8991     lambda[sl] = lambda[sl-1];
8992     mu[sl] = mu[sl-1];
8993     psi[sl] = 0.0;  // psi = 0 in [0, x_cut]
8994     for (i = 0; i < sl-1; i++)
8995         {
8996         rho[i] = mp->sampleFSProb[i];
8997         t_f[i] = mp->sampleFSTime[i];
8998         }
8999     rho[sl-1] = 0.0;
9000     t_f[sl-1] = x_min * 0.95; // x_cut
9001     rho[sl]   = 1.0;          // not sF
9002     t_f[sl]   = 0.0;
9003     
9004     if (sl > 1)  assert (mp->sampleFSTime[0] < tmrca);
9005     for (i = sl; i >= 0; i--)
9006         {
9007         c1[i] = sqrt(pow(lambda[i]-mu[i]-psi[i], 2) + 4*lambda[i]*psi[i]);
9008         if (i == sl)
9009             c2[i] = ((1 - 2* (1-rho[i])) *lambda[i] +mu[i] +psi[i]) /c1[i];
9010         else
9011             c2[i] = ((1 - 2* (1-rho[i]) *p_t[i+1]) *lambda[i] +mu[i] +psi[i]) /c1[i];
9012         if (i > 0)
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];
9015         else
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];
9018         }
9019     
9020 #   ifdef DEBUG_FBDPR
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]);
9025 #   endif
9026     
9027     /* first calculate prob of the fbd tree assuming complete sampling */
9028     (*prob) = 0.0;
9029     
9030     for (K = M = E = 0, i = 0; i < t->nNodes -1; i++)
9031         {
9032         p = t->allDownPass[i];
9033         x = p->nodeDepth / clockRate;
9034         
9035         if (p->left != NULL && p->right != NULL)  // internal
9036             {
9037             if (p->left->length > 0.0 && p->right->length > 0.0)
9038                 {
9039                 if (p != t->root->left)
9040                     (*prob) += log(lambda[Slice_i(x, t_f, sl)]) + LnQi_fossil(x, t_f, sl, c1,c2);
9041                 }
9042             else
9043                 {
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] */
9047                     {
9048                     (*prob) += log(psi[Slice_i(x, t_f, sl)]);
9049                     }
9050                 else              /* fossil ancestor at silice time t[j] */
9051                 if (rho[j] > 0.0 && rho[j] < 1.0)
9052                     {
9053                     (*prob) += log(rho[j]) - log(1 - rho[j]);
9054                     }
9055                 K++;              /* number of fossil ancestors */
9056                 }
9057             }
9058         else if (p->left == NULL && p->length > 0.0)  // tip
9059             {
9060             if (p->nodeDepth > 0.0)
9061                 {
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] */
9065                     {
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)]);
9069                     }
9070                 else              /* fossil tip at silice time t[j] */
9071                     {
9072                     (*prob) += log(p_t[j+1]);
9073                     if (rho[j] > 0.0)  (*prob) += log(rho[j]);
9074                     }
9075                 M++;              /* number of fossil tips */
9076                 }
9077             else
9078                 {
9079                 //  (*prob) += log(rho[sl]);  // rho[sl] == 1
9080                 E++;              /* number of extant taxa */
9081                 }
9082             }
9083         
9084         for (j = 0; j < sl; j++)  /* degree-two vertices at silice time t_j */
9085             {
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))
9088                     {
9089                     (*prob) += LnQi_fossil(t_f[j], t_f, sl, c1,c2);
9090                     if (rho[j] < 1.0)  (*prob) += log(1 - rho[j]);
9091                     }
9092             }
9093         }
9094     
9095     (*prob) += 2.0 * (LnQi_fossil(tmrca, t_f, sl, c1,c2) - log(1- p_t[0]));
9096     
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 */
9099     
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])));
9102     
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);
9106     
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)
9109     
9110 #   ifdef DEBUG_FBDPR
9111     printf ("K=%d M=%d E=%d\n", K, M, E);
9112     printf ("prob=%lf\n", *prob);
9113 #   endif
9114     
9115     /* free memory */
9116     free(lambda); free(mu); free(psi); free(rho);
9117     free(t_f); free(c1); free(c2); free(p_t);
9118     
9119     return (NO_ERROR);
9120 }
9121
9122
9123 /*---------------------------------------------------------------------------------
9124 |
9125 |   LnCoalescencePriorPr
9126 |
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:
9131 |
9132 |                                      t_4 ___  
9133 |     \         \         \        /            \
9134 |      \         \         \      /             | 
9135 |   I_4 \         \         \    /              | g_4
9136 |        \         \         \  /               |
9137 |         \         \         \/       t_3 ___  /
9138 |          \         \        /                 \
9139 |           \         \      /                  |
9140 |   I_3      \         \    /                   | g_3
9141 |             \         \  /                    |
9142 |              \         \/            t_2 ___  / 
9143 |               \        /                      \
9144 |                \      /                       |
9145 |   I_2           \    /                        | g_2
9146 |                  \  /                         |
9147 |                   \/                 t_1 ___  /
9148 |    
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.
9156 |
9157 |   The probability of the coalescence tree is:
9158 |   
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)
9160 |
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.
9165 |
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. 
9168 |
9169 |   2010-03-23
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.
9176 |
9177 ---------------------------------------------------------------------------------*/
9178 int LnCoalescencePriorPr (Tree *t, MrBFlt *prob, MrBFlt theta, MrBFlt growth)
9179 {
9180     int             i, j, k, nNodes;
9181     MrBFlt          *ct, tempD, lastCoalescenceTime, coalescenceTime, intervalLength;
9182     TreeNode        *p;
9183
9184     /* allocate space for the coalescence times */
9185     ct = (MrBFlt *)SafeMalloc((size_t)(t->nIntNodes) * sizeof(MrBFlt));
9186     if (!ct)
9187         {
9188         MrBayesPrint ("\n   ERROR: Problem allocating ct\n");
9189         return (ERROR);
9190         }
9191
9192     /* get the coalescence times and put them into a vector */
9193     for (i=j=0; i<t->nIntNodes; i++)
9194         {
9195         p = t->intDownPass[i];
9196         if (p->anc != NULL)
9197             ct[j++] = p->nodeDepth;  // Don't divide clockRate here, as mu is already in theta
9198         }
9199     nNodes = j;
9200
9201     /* sort the coalescence times */
9202     SortMrBFlt (ct, 0, nNodes-1);
9203     
9204     /*for (i=0, k=numLocalTaxa; i<nNodes; i++)
9205         {
9206         printf ("%4d -- %2d %lf\n", i, k, ct[i]);
9207         k--;
9208         }*/
9209         
9210     /* calculate probability of the tree */
9211     if (AreDoublesEqual (growth, 0.0, 0.000001) == YES)
9212         {
9213         /* use this if there is no population growth */
9214         tempD = lastCoalescenceTime = 0.0;
9215         for (i=0, k=numLocalTaxa; i<nNodes; i++)
9216             {
9217             coalescenceTime = ct[i];
9218             intervalLength = coalescenceTime - lastCoalescenceTime;
9219             lastCoalescenceTime = ct[i];
9220             tempD += - (k * (k-1) * intervalLength) / (theta);
9221             k--;
9222             }
9223         (*prob) = (numLocalTaxa - 1) * log(2.0 / theta) + tempD;
9224         }
9225     else
9226         {
9227         /* use this if the population is growing exponentially */
9228         tempD = lastCoalescenceTime = 0.0;
9229         for (i=0, k=numLocalTaxa; i<nNodes; i++)
9230             {
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];
9235             k--;
9236             }
9237         (*prob) = (numLocalTaxa - 1) * log(2.0 / theta) + tempD;
9238         }
9239
9240     /* printf ("coal pr = %lf theta = %lf, nNodes = %d, nt = %d tempD = %lf\n", *prob, theta, nNodes, numLocalTaxa, tempD); */
9241
9242     /* free memory */
9243     free (ct);
9244     
9245     return (NO_ERROR);
9246 }
9247
9248
9249 /*---------------------------------------------------------------------------------
9250 |
9251 |   LnUniformPriorPr
9252 |
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
9255 |   follows:
9256 |                                                interval between tip dates 
9257 |    t_0                          t_1      time  ____  0 (interval between t_0 and t_1, duration 0) 
9258 |     \                            /            |  
9259 |      \                  t_2     /             |___   1 (interval between t_1 and t_2)
9260 |       \                   \    /              | 
9261 |        \                   \  /               |
9262 |         \                   \/        0.33 ___|      2 (interval between t_2 and t_3)
9263 |          \        t_3       /                 |___ 
9264 |           \         \      /                  |
9265 |            \         \    /                   | 
9266 |             \         \  /                    |
9267 |              \   t_4   \/             0.67 ___| 
9268 |               \     \  /                      |      3 (interval between t_3 and root)
9269 |                \     \/                       |
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.
9273 |    
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.
9278 |
9279 ---------------------------------------------------------------------------------*/
9280 MrBFlt LnUniformPriorPr (Tree *t, MrBFlt clockRate)
9281 {
9282     int         i, j, k, *nLineages=NULL, nDatedTips, nLineagesIn, nLineagesOut, nTips;
9283     MrBFlt      lnProb, treeAge, *nodeDepths=NULL;
9284     TreeNode    *p, *root;
9285     Model       *mp;
9286
9287     lnProb      = 0.0;
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);
9291
9292     /* Calculate number of tips for convenience */
9293     nTips   = t->nNodes - t->nIntNodes - 1;
9294
9295     /* First take tree age into account f(t_0) */
9296     if (t->root->left->isDated == YES)
9297         {
9298         lnProb += 0.0;  /* calibrations are dealt with separately in calling function */
9299         }
9300     else
9301         {
9302         lnProb += mp->treeAgePr.LnPriorProb(treeAge, mp->treeAgePr.priorParams);
9303         }
9304
9305     /* If tree is not calibrated or only root is calibrated, it is easy */
9306     for (i=j=0; i<t->nNodes-2; i++)
9307         {
9308         if (t->allDownPass[i]->isDated == YES)
9309             j++;
9310         }
9311     if (j == 0)
9312         {
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);
9316         return lnProb;
9317         }
9318
9319     /* We have a tree with interior or tip calibrations */
9320
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. */
9327     i = 0;
9328     ColorClusters (t->root->left, &i);
9329
9330     /* Get the probability for each subtree */
9331     for (i=0; i<t->nIntNodes; i++)
9332         {
9333         p = t->intDownPass[i];
9334         
9335         /* Skip unless this is the root of a subtree */
9336         if (p->anc->anc != NULL && p->isDated != YES)
9337             continue;
9338
9339         /* Save the root of the subtree */
9340         root = p;
9341
9342         /* Create an array containing the sorted times */
9343
9344         /* Allocate space for node depths */
9345         nDatedTips = NumDatedTips (root);
9346         nodeDepths = (MrBFlt *) SafeRealloc ((void *)nodeDepths, (nDatedTips+1)*sizeof(MrBFlt));
9347
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 */
9353
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);
9358
9359         /* Get probability due to sorting of interior node depths */
9360         
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++)
9364             nLineages[j] = j+1;
9365         
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++)
9371             {
9372             p = t->intDownPass[j];
9373             if (p->x != root->x || p == root || p->isDated == YES)
9374                 continue;
9375             for (k=0; k<nDatedTips; k++)
9376                 if (p->nodeDepth < nodeDepths[k+1])
9377                         nLineages[k]--;
9378             }
9379         
9380         /* Now get the density effect of the sorting constraints */
9381         for (j=1; j<nDatedTips-1; j++)
9382             {
9383             nLineagesIn = nLineages[j-1] + 1;
9384             if (j==nDatedTips-2)
9385                 nLineagesOut = 2;    /* skip the last segment and jump directly to root */
9386             else
9387                 nLineagesOut = nLineages[j];
9388             /* only calculate if ln different from 0 */
9389             if (nLineagesIn > 1 && nLineagesIn - nLineagesOut >= 1)
9390                 {
9391                 lnProb += LnFactorial (nLineagesIn-1) - LnFactorial(nLineagesOut-1);
9392                 }
9393             }
9394
9395         /* Finally get the effect of the number of possible coalescent histories */
9396         for (j=1; j<nDatedTips; j++)
9397             {
9398             nLineagesIn = nLineages[j-1] + 1;
9399             nLineagesOut = nLineages[j];
9400             if (nLineagesIn != nLineagesOut)
9401                 {
9402                 lnProb += log(2.0) * (nLineagesIn - nLineagesOut);
9403                 lnProb += LnFactorial (nLineagesOut) + LnFactorial (nLineagesOut-1);
9404                 lnProb -= LnFactorial (nLineagesIn)  + LnFactorial (nLineagesIn-1);
9405                 }
9406             }
9407
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;
9411
9412         }
9413
9414     free (nodeDepths);
9415     free (nLineages);
9416
9417     assert (lnProb > NEG_INFINITY);
9418
9419     return lnProb;
9420 }
9421
9422
9423 /*------------------------------------------------------------------------
9424 |
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
9428 |      depths instead.
9429 |
9430 ------------------------------------------------------------------------*/
9431 int NewtonRaphsonBrlen (Tree *t, TreeNode *p, int chain)
9432 {
9433     int         c, i, j, s, k, n, d, division, nIterations, maxNumIterations,
9434                 index, *rateCat, r;
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;
9440     ModelInfo   *m;
9441
9442     /* TODO: Standard model (also check RES for ascertainment bias) */
9443     tolerance = 0.001;
9444     maxNumIterations = 5;
9445     
9446     nIterations = 0;
9447     do {
9448         /* reset f'(v) and f''(v) sums */
9449         sumLike1 = sumLike2 = 0.0;
9450         
9451         /* cycle over character partitions */
9452         for (d=0; d<t->nRelParts; d++)
9453             {
9454             division = t->relParts[d];
9455
9456             /* get pointer to model */
9457             m = &modelSettings[division];
9458             
9459             /* get number of model states */
9460             n = m->numModelStates;
9461             
9462             /* find conditional likelihoods */
9463             clP = m->condLikes[m->condLikeIndex[chain][p->index     ]];
9464             clA = m->condLikes[m->condLikeIndex[chain][p->anc->index]];
9465             
9466             /* get state frequencies */
9467             pi = GetParamSubVals (m->stateFreq, chain, state[chain]);
9468     
9469             /* get base rate */
9470             theRate = 1.0;
9471             baseRate = GetRate (division, chain);
9472
9473             /* get category rates */
9474             if (m->shape == NULL)
9475                 catRate = &theRate;
9476             else
9477                 catRate = GetParamSubVals (m->shape, chain, state[chain]);
9478     
9479             /* find category frequencies and some additional stuff for the invar model */
9480             if (m->pInvar == NULL)
9481                 freq =  (CLFlt) (1.0 /  m->numGammaCats);
9482             else
9483                 {
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]];
9490                 }
9491
9492             /* find the branch lengths times any correction factor to make them
9493                in terms of expected number of substitutions per character */
9494             length = p->length;
9495             if (m->dataType == DNA || m->dataType == RNA)
9496                 {
9497                 if (m->nucModelId == NUCMODEL_DOUBLET)
9498                     length *= 2.0;
9499                 else if (m->nucModelId == NUCMODEL_CODON)
9500                     length *= 3.0;
9501                 }
9502
9503             /* find nSitesOfPat */
9504             nSitesOfPat = numSitesOfPat + ((chainId[chain] % chainParams.numChains)*numCompressedChars) + m->compCharStart;
9505             
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);
9511
9512             /* allocate space for first and second derivatives */
9513             tiP1 = (CLFlt *) SafeCalloc (2*m->tiProbLength, sizeof (CLFlt));
9514             if (!tiP1)
9515                 return (ERROR);
9516             tiP2 = tiP1 + m->tiProbLength;
9517             
9518             /* calculate first and second derivatives of P(v): P'(v) and P''(v) */
9519             index = 0;
9520             if (m->TiProbs == &TiProbs_Fels || m->TiProbs == &TiProbs_Res)
9521                 {
9522                 /* calculate beta */
9523                 sum = 0.0;
9524                 for (i=0; i<m->numModelStates; i++)
9525                     for (j=i+1; j<m->numModelStates; j++)
9526                         sum += pi[i]*pi[j];
9527                 beta = 0.5 / sum;
9528
9529                 /* calculate derivatives */
9530                 for (k=0; k<m->numGammaCats; k++)
9531                     {
9532                     v = length * catRate[k] * baseRate;
9533                     expBetaV = exp (- beta * v);
9534                     for (i=0; i<m->numModelStates; i++)
9535                         {
9536                         for (j=0; j<m->numModelStates; j++)
9537                             {
9538                             if (i == j)
9539                                 {
9540                                 x = - beta * (1.0 - pi[j]) * expBetaV;
9541                                 tiP1[index] = (CLFlt) x;
9542                                 tiP2[index] = (CLFlt) (- beta * x);
9543                                 }
9544                             else
9545                                 {
9546                                 x = beta * pi[j] * expBetaV;
9547                                 tiP1[index] = (CLFlt) x;
9548                                 tiP2[index] = (CLFlt) (- beta * x);
9549                                 }
9550                             index++;
9551                             }
9552                         }
9553                     }
9554                 }
9555             else if (m->TiProbs == &TiProbs_Hky)
9556                 {
9557                 /* get kappa */
9558                 kappa =  *GetParamVals (m->tRatio, chain, state[chain]);
9559     
9560                 /* calculate beta */
9561                 sum = 0.0;
9562                 for (i=0; i<m->numModelStates; i++)
9563                     {
9564                     for (j=i+1; j<m->numModelStates; j++)
9565                         {
9566                         if (j - i == 2)
9567                             sum += kappa * pi[i] * pi[j];
9568                         else
9569                             sum += pi[i] * pi[j];
9570                         }
9571                     }
9572                 beta = 0.5 / sum;
9573
9574                 /* calculate derivatives */
9575                 for (k=0; k<m->numGammaCats; k++)
9576                     {
9577                     v = length * catRate[k] * baseRate;
9578                     expBetaV = exp (- beta * v);
9579                     for (i=0; i<m->numModelStates; i++)
9580                         {
9581                         for (j=0; j<m->numModelStates; j++)
9582                             {
9583                             s = (j + 2) % 4;
9584                             bigPi = pi[j] + pi[s];
9585                             w = (1.0 + bigPi * (kappa - 1.0)) * beta;
9586                             expWV = exp (- w * v);
9587                             if (i == j)
9588                                 {
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);
9593                                 }
9594                             else if (abs(i-j) == 2)
9595                                 {
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);
9600                                 }
9601                             else
9602                                 {
9603                                 x = beta * pi[j] * expBetaV;
9604                                 tiP1[index] = (CLFlt) x;
9605                                 tiP2[index] = (CLFlt) (- beta * x);
9606                                 }
9607                             index++;
9608                             }
9609                         }
9610                     }
9611                 }
9612             else if (m->TiProbs == &TiProbs_Gen || m->TiProbs == &TiProbs_GenCov)
9613                 {
9614                 /* get eigenvalues and cijk pointers */
9615                 eigenValues = m->cijks[m->cijkIndex[chain]];
9616                 cijk        = eigenValues + (2 * n);
9617
9618                 /* calculate P'(v) and P''(v) */
9619                 for (k=0; k<m->numGammaCats; k++)
9620                     {
9621                     v = length * catRate[k];
9622                     for (s=0; s<n; s++)
9623                         expLambdaV[s] =  exp(eigenValues[s] * v);
9624                     ptr = cijk;
9625                     for (i=0; i<n; i++)
9626                         {
9627                         for (j=0; j<n; j++)
9628                             {
9629                             sum1 = sum2 = 0.0;
9630                             for (s=0; s<n; s++)
9631                                 {
9632                                 if (fabs(eigenValues[s]) > 0.000001)
9633                                     {
9634                                     x = eigenValues[s] * (*ptr++) * expLambdaV[s];
9635                                     sum1 += x;
9636                                     sum2 += eigenValues[s] * x;
9637                                     }
9638                                 else
9639                                     ptr += n;
9640                                 }
9641                             tiP1[index] = (CLFlt) ((sum1 < 0.0) ? 0.0 : sum);
9642                             tiP2[index] = (CLFlt) ((sum2 < 0.0) ? 0.0 : sum);
9643                             index++;
9644                             }
9645                         }
9646                     }
9647                 }
9648             else if (m->TiProbs == &TiProbs_GenCov)
9649                 {
9650                 /* get eigenvalues and cijk pointers */
9651                 eigenValues = m->cijks[m->cijkIndex[chain]];
9652                 cijk        = eigenValues + (2 * n);
9653
9654                 /* calculate P'(v) and P''(v) */
9655                 for (k=0; k<m->numTiCats; k++)
9656                     {
9657                     if (m->numGammaCats > 1)
9658                         v = length * catRate[k];
9659                     else
9660                         v = length;
9661                     for (s=0; s<n; s++)
9662                         expLambdaV[s] =  exp(eigenValues[s] * v);
9663                     for (i=0; i<n; i++)
9664                         {
9665                         for (j=0; j<n; j++)
9666                             {
9667                             sum1 = sum2 = 0.0;
9668                             for (s=0; s<n; s++)
9669                                 {
9670                                 if (fabs(eigenValues[s]) > 0.000001)
9671                                     {
9672                                     x = eigenValues[s] * (*cijk++) * expLambdaV[s];
9673                                     sum1 += x;
9674                                     sum2 += eigenValues[s] * x;
9675                                     }
9676                                 }
9677                             tiP1[index] = (CLFlt) ((sum1 < 0.0) ? 0.0 : sum);
9678                             tiP2[index] = (CLFlt) ((sum2 < 0.0) ? 0.0 : sum);
9679                             index++;
9680                             }
9681                         }
9682                     /* get new eigenvalues and cijks */
9683                     eigenValues += m->cijkLength / m->nCijkParts;
9684                     cijk         = eigenValues + 2 * n;
9685                     }
9686                 }
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)
9691                 {
9692                 /* find rate category index */
9693                 rateCat = m->tiIndex + chain*m->numChars;
9694                 for (c=0; c<m->numChars; c++)
9695                     {
9696                     like = like1 = like2 = 0.0;
9697                     r = rateCat[c];
9698                     if (r < m->numGammaCats)
9699                         {
9700                         index = r*m->numModelStates*m->numModelStates;
9701                         for (j=0; j<n; j++)
9702                             {
9703                             CLsum = CLsum1 = CLsum2 = 0.0;
9704                             for (i=0; i<n; i++, index++)
9705                                 {
9706                                 CLsum += clP[i] * tiP[index];
9707                                 CLsum1 += clP[i] * tiP1[index];
9708                                 CLsum2 += clP[i] * tiP2[index];
9709                                 }
9710                             like += CLsum * (CLFlt) pi[j] * clA[j];
9711                             like1 += CLsum1 * (CLFlt) pi[j] * clA[j];
9712                             like2 += CLsum2 * (CLFlt) pi[j] * clA[j];
9713                             }
9714                         like *= freq;
9715                         sumLike1 += nSitesOfPat[c] * (like1 / like);
9716                         sumLike2 += nSitesOfPat[c] * (like2 * like - like1 * like1) / (like * like);
9717                         }
9718                     clP += n;
9719                     }
9720                 }
9721             else
9722                 {
9723                 for (c=0; c<m->numChars; c++)
9724                     {
9725                     like = like1 = like2 = 0.0;
9726                     index = 0;
9727                     for (k=0; k<m->numTiCats; k++)
9728                         {
9729                         for (j=0; j<n; j++)
9730                             {
9731                             CLsum = CLsum1 = CLsum2 = 0.0;
9732                             for (i=0; i<n; i++, index++)
9733                                 {
9734                                 CLsum += clP[i] * tiP[index];
9735                                 CLsum1 += clP[i] * tiP1[index];
9736                                 CLsum2 += clP[i] * tiP2[index];
9737                                 }
9738                             like += CLsum * (CLFlt) pi[j] * clA[j];
9739                             like1 += CLsum1 * (CLFlt) pi[j] * clA[j];
9740                             like2 += CLsum2 * (CLFlt) pi[j] * clA[j];
9741                             }
9742                         clP += n;
9743                         }
9744                     like *= freq;
9745                     if (m->pInvar != NULL)
9746                         {
9747                         /* get right like; like1 and like2 not affected */;
9748                         for (i=0; i<n; i++)
9749                             likeI += (*clInvar++) * pi[i];
9750                         likeI *= pInvar;
9751                         if (lnScaler[c] < -200.0)
9752                             {
9753                             /* we are not going to be able to exponentiate the scaling factor */
9754                             if (likeI > 1E-70)
9755                                 {
9756                                 /* forget about like; it is going to be insignificant compared to likeI */
9757                                 like = (CLFlt) likeI;
9758                                 }
9759                             else
9760                                 {
9761                                 /* treat likeI as if 0.0, that is, ignore it completely */
9762                                 like = like + (CLFlt)(0.0);
9763                                 }
9764                             }
9765                         else    /* take both likeI and like into account */
9766                             like = like + (CLFlt) (likeI * exp (-lnScaler[c]));
9767                         }
9768                     sumLike1 += nSitesOfPat[c] * (like1 / like);
9769                     sumLike2 += nSitesOfPat[c] * (like2 * like - like1 * like1) / (like * like);
9770                     }
9771                 }
9772             free (tiP1);
9773             }
9774         vOld = p->length;
9775         p->length -= sumLike2 / sumLike1;
9776         nIterations++;
9777         } while (fabs(p->length - vOld) > tolerance && nIterations < maxNumIterations);
9778
9779     return (NO_ERROR);
9780 }
9781
9782
9783 void NodeToNodeDistances (Tree *t, TreeNode *fromNode)
9784 {
9785     int             i;
9786     TreeNode        *p;
9787     
9788     /* set all distances to 0.0 and also set marks on all nodes to NO */
9789     for (i=0; i<t->nNodes; i++)
9790         {
9791         p = t->allDownPass[i];
9792         p->x = NO;
9793         p->d = 0.0;
9794         }
9795         
9796     /* find distances, and mark path, below "fromNode" */
9797     for (i=0; i<t->nNodes; i++)
9798         {
9799         p = t->allDownPass[i];
9800         if (p == fromNode)
9801             {
9802             p->x = YES;
9803             }
9804         if (p->left != NULL && p->right != NULL && p->anc != NULL)
9805             {
9806             if (p->left->x == YES)
9807                 {
9808                 p->x = YES;
9809                 p->d = p->left->d + p->left->length;
9810                 }
9811             else if (p->right->x == YES)
9812                 {
9813                 p->x = YES;
9814                 p->d = p->right->d + p->right->length;
9815                 }
9816             }
9817         }
9818         
9819     /* find all other distances */
9820     for (i=t->nNodes-1; i>=0; i--)
9821         {
9822         p = t->allDownPass[i];
9823         if (p->anc == NULL)
9824             {
9825             if (p == fromNode)
9826                 p->d = 0.0;
9827             else
9828                 p->d = p->left->d + p->left->length;
9829             }
9830         else
9831             {
9832             if (p->x == NO)
9833                 {
9834                 p->d = p->anc->d + p->length;
9835                 }
9836             }
9837         }
9838 }
9839
9840
9841 int NumCppEvents (Param *p, int chain)
9842 {
9843     int         i, *nEvents, sumEvents;
9844
9845     nEvents = p->nEvents[2*chain+state[chain]];
9846     
9847     sumEvents = 0;
9848     for (i=0; i<2*numLocalTaxa-2; i++)
9849         sumEvents += nEvents[i];
9850
9851     return (sumEvents);
9852 }
9853
9854
9855 /*----------------------------------------------------------------------
9856 |
9857 |   OpenNewMBPrintFile: Open a file the first time for printing
9858 |
9859 ------------------------------------------------------------------------*/
9860 FILE *OpenNewMBPrintFile (char *fileName)
9861 {
9862     int     overWrite;
9863     FILE    *fp;
9864
9865     /* Open file, use noWarn to determine if the user should be prompted
9866        to have the file over-written or appended. */
9867     if (noWarn == YES)
9868         {
9869         /* overwrite or append file, if already present */
9870         if ((fp = TestOpenTextFileR(fileName)) != NULL)
9871             {
9872             SafeFclose (&fp);
9873             if (autoOverwrite == NO)
9874                 {
9875                 MrBayesPrint ("%s   Appending to file \"%s\"\n", spacer, fileName); 
9876                 return (OpenTextFileA(fileName));
9877                 }
9878             else 
9879                 MrBayesPrint ("%s   Overwriting file \"%s\"\n", spacer, fileName);      
9880             }
9881             return (OpenTextFileW(fileName));
9882         }   
9883     else
9884         {
9885         /* prompt user if file is already present */
9886         if ((fp = TestOpenTextFileR(fileName)) != NULL)
9887             {
9888             SafeFclose (&fp);
9889             MrBayesPrint ("\n");
9890             MrBayesPrint ("%s   File \"%s\" already exists\n", spacer, fileName);
9891             overWrite = WantTo ("Overwrite information in this file");
9892             
9893             if (overWrite == YES)
9894                 {
9895                 MrBayesPrint ("%s   Overwriting file \"%s\"\n", spacer, fileName);
9896                 return (OpenTextFileW(fileName));
9897                 }
9898             else
9899                 {
9900                 MrBayesPrint ("%s   Appending to file \"%s\"\n", spacer, fileName);
9901                 return (OpenTextFileA(fileName));
9902                 }
9903             }
9904
9905         else
9906             {
9907             /* file is not present */
9908             return (OpenTextFileW(fileName));
9909             }
9910         }
9911 }
9912
9913
9914 int PickProposal (RandLong *seed, int chainIndex)
9915 {
9916     MrBFlt      ran;
9917     int         i;
9918
9919     ran = RandomNumber(seed);
9920     
9921     for (i=0; usedMoves[i]->cumProposalProb[chainIndex] <= ran; i++);
9922         
9923     return i;
9924 }
9925
9926
9927 /* Calculate positive selection probabilities */
9928 int PosSelProbs (TreeNode *p, int division, int chain)
9929 {
9930     int             c, j, k, nStates;
9931     MrBFlt          catLike, *like, *bs, *omegaCatFreq, *omega,
9932                     posProb, *ps, sum;
9933     CLFlt           **clP;
9934     ModelInfo       *m;
9935     
9936     /* find model partition */
9937     m = &modelSettings[division];
9938
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));
9942     if (!clP || !like)
9943         {
9944         MrBayesPrint ("%s   ERROR: Out of memory in PosSelProbs\n", spacer);
9945         return (ERROR);
9946         }
9947     
9948     /* number of states */
9949     nStates = m->numModelStates;
9950
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;
9955     
9956     /* find base frequencies */
9957     bs = GetParamSubVals (m->stateFreq, chain, state[chain]);
9958     
9959     /* find category frequencies */
9960     omegaCatFreq = GetParamSubVals (m->omega, chain, state[chain]);
9961     
9962     /* get category omegas */
9963     omega = GetParamVals (m->omega, chain, state[chain]);
9964
9965     /* find posSelProbs */
9966     ps = posSelProbs + m->compCharStart;
9967     for (c=0; c<m->numChars; c++)
9968         {
9969         sum = 0.0;
9970         for (k=0; k<m->numOmegaCats; k++)
9971             {
9972             like[k] = 0.0;
9973             catLike = 0.0;
9974             for (j=0; j<nStates; j++)
9975                 catLike += clP[k][j] * bs[j];
9976             like[k] = catLike * omegaCatFreq[k];
9977             sum += like[k];
9978             clP[k] += nStates;
9979             }
9980         posProb = 0.0;
9981         for (k=0; k<m->numOmegaCats; k++)
9982             {
9983             if (omega[k] > 1.0)
9984                 posProb += like[k] / sum;
9985             }
9986         ps[c] = posProb;
9987         }
9988
9989     free (clP);
9990     free (like);
9991     
9992     return NO_ERROR;
9993 }
9994
9995
9996 #if defined (SSE_ENABLED)
9997 /* Calculate positive selection probabilities (SSE version) */
9998 int PosSelProbs_SSE (TreeNode *p, int division, int chain)
9999 {
10000     int             i, c1, c2, j, k, nStates;
10001     CLFlt           **catLike, *siteLike;
10002     MrBFlt          *bs, *omegaCatFreq, *omega,
10003                     posProb, *ps;
10004     __m128          m1, m2, *clPtr, **clP, mSiteLike, *mCatLike;
10005     ModelInfo       *m;
10006     
10007     /* find model partition */
10008     m = &modelSettings[division];
10009     
10010     /* number of states */
10011     nStates = m->numModelStates;
10012     
10013     /* find base frequencies */
10014     bs = GetParamSubVals (m->stateFreq, chain, state[chain]);
10015     
10016     /* find category frequencies */
10017     omegaCatFreq = GetParamSubVals (m->omega, chain, state[chain]);
10018     
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)
10025         {
10026         MrBayesPrint ("%s   ERROR: Out of memory in PosSelProbs_SSE\n", spacer);
10027         return (ERROR);
10028         }
10029
10030     /* find conditional likelihood pointers */
10031     clPtr = (__m128 *) m->condLikes[m->condLikeIndex[chain][p->index]];
10032     clP   = m->clP_SSE;
10033     for (k=0; k<m->numOmegaCats; k++)
10034         {
10035         clP[k] = clPtr;
10036         clPtr += m->numSSEChars * nStates;
10037         catLike[k] = (CLFlt *) (&(mCatLike[k]));
10038         }
10039     siteLike = (CLFlt *) (&mSiteLike);
10040     
10041     /* find posSelProbs */
10042     ps = posSelProbs + m->compCharStart;
10043     for (c1=c2=0; c1<m->numSSEChars; c1++)
10044         {
10045         mSiteLike = _mm_setzero_ps ();
10046         for (k=0; k<m->numOmegaCats; k++)
10047             {
10048             mCatLike[k] = _mm_setzero_ps();
10049             m1 = _mm_setzero_ps ();
10050             for (j=0; j<nStates; j++)
10051                 {
10052                 m2 = _mm_mul_ps (clP[k][j], _mm_set1_ps ((CLFlt)bs[j]));
10053                 m1 = _mm_add_ps (m1, m2);
10054                 }
10055             mCatLike[k] = _mm_mul_ps (m1, _mm_set1_ps ((CLFlt)omegaCatFreq[k]));
10056             mSiteLike = _mm_add_ps (mSiteLike, mCatLike[k]);
10057             clP[k] += nStates;
10058             }
10059
10060         for (i=0; i<FLOATS_PER_VEC && c2 < m->numChars; ++i, ++c2)
10061             {
10062             posProb = 0.0;
10063             for (k=0; k<m->numOmegaCats; k++)
10064                 {
10065                 if (omega[k] > 1.0)
10066                     {
10067                     posProb += catLike[k][i] / siteLike[i];
10068                     }
10069                 }
10070             ps[c2] = posProb;
10071             }
10072         }
10073     
10074     free (catLike);
10075     free (mCatLike);
10076     
10077     return NO_ERROR;
10078 }
10079 #endif
10080
10081
10082 /* Calculate omega values for each site */
10083 int SiteOmegas (TreeNode *p, int division, int chain)
10084 {
10085     int             c, j, k, nStates;
10086     MrBFlt          catLike, *like, *bs, *omegaCatFreq, *omega,
10087                     siteOmega, *ps, sum;
10088     CLFlt           **clP;
10089     ModelInfo       *m;
10090     
10091     /* find model partition */
10092     m = &modelSettings[division];
10093     
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));
10097     if (!clP || !like)
10098         {
10099         MrBayesPrint ("%s   ERROR: Out of memory in SiteOmegas\n", spacer);
10100         return (ERROR);
10101         }
10102     
10103     /* number of states */
10104     nStates = m->numModelStates;
10105
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;
10110     
10111     /* find base frequencies */
10112     bs = GetParamSubVals (m->stateFreq, chain, state[chain]);
10113     
10114     /* find category frequencies */
10115     omegaCatFreq = GetParamSubVals (m->omega, chain, state[chain]);
10116     
10117     /* get category omegas */
10118     omega = GetParamVals (m->omega, chain, state[chain]);
10119
10120     /* find site omegas (using posSelProbs space) */
10121     ps = posSelProbs + m->compCharStart;
10122     for (c=0; c<m->numChars; c++)
10123         {
10124         sum = 0.0;
10125         for (k=0; k<m->numOmegaCats; k++)
10126             {
10127             like[k] = 0.0;
10128             catLike = 0.0;
10129             for (j=0; j<nStates; j++)
10130                 catLike += clP[k][j] * bs[j];
10131             like[k] = catLike * omegaCatFreq[k];
10132             sum += like[k];
10133             clP[k] += nStates;
10134             }
10135         siteOmega = 0.0;
10136         for (k=0; k<m->numOmegaCats; k++)
10137             {
10138             siteOmega += (like[k]/sum) * omega[k];
10139             }
10140         ps[c] = siteOmega;
10141         }
10142
10143     free (clP);
10144     free (like);
10145     
10146     return NO_ERROR;
10147 }
10148
10149
10150 #if defined (SSE_ENABLED)
10151 /* Calculate omega values for each site (SSE version) */
10152 int SiteOmegas_SSE (TreeNode *p, int division, int chain)
10153 {
10154     int             i, c1, c2, j, k, nStates;
10155     CLFlt           **catLike, *siteLike;
10156     MrBFlt          *bs, *omegaCatFreq, *omega,
10157                     siteOmega, *ps;
10158     __m128          m1, m2, *clPtr, **clP, mSiteLike, *mCatLike;
10159     ModelInfo       *m;
10160     
10161     /* find model partition */
10162     m = &modelSettings[division];
10163     
10164     /* number of states */
10165     nStates = m->numModelStates;
10166     
10167     /* find base frequencies */
10168     bs = GetParamSubVals (m->stateFreq, chain, state[chain]);
10169     
10170     /* find category frequencies */
10171     omegaCatFreq = GetParamSubVals (m->omega, chain, state[chain]);
10172     
10173     /* get category omegas */
10174     omega = GetParamVals (m->omega, chain, state[chain]);
10175
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)
10180         {
10181         MrBayesPrint ("%s   ERROR: Out of memory in SiteOmegas_SSE\n", spacer);
10182         return (ERROR);
10183         }
10184     
10185     /* find conditional likelihood pointers */
10186     clPtr = (__m128 *) m->condLikes[m->condLikeIndex[chain][p->index]];
10187     clP   = m->clP_SSE;
10188     for (k=0; k<m->numOmegaCats; k++)
10189         {
10190         clP[k] = clPtr;
10191         clPtr += m->numSSEChars * nStates;
10192         catLike[k] = (CLFlt *) (&(mCatLike[k]));
10193         }
10194     siteLike = (CLFlt *) (&mSiteLike);
10195     
10196     /* find site omegas (using posSelProbs space) */
10197     ps = posSelProbs + m->compCharStart;
10198     for (c1=c2=0; c1<m->numSSEChars; c1++)
10199         {
10200         mSiteLike = _mm_setzero_ps ();
10201         for (k=0; k<m->numOmegaCats; k++)
10202             {
10203             mCatLike[k] = _mm_setzero_ps();
10204             m1 = _mm_setzero_ps ();
10205             for (j=0; j<nStates; j++)
10206                 {
10207                 m2 = _mm_mul_ps (clP[k][j], _mm_set1_ps ((CLFlt)bs[j]));
10208                 m1 = _mm_add_ps (m1, m2);
10209                 }
10210             mCatLike[k] = _mm_mul_ps (m1, _mm_set1_ps ((CLFlt)omegaCatFreq[k]));
10211             mSiteLike = _mm_add_ps (mSiteLike, mCatLike[k]);
10212             clP[k] += nStates;
10213             }
10214         
10215         for (i=0; i<FLOATS_PER_VEC && c2 < m->numChars; ++i, ++c2)
10216             {
10217             siteOmega = 0.0;
10218             for (k=0; k<m->numOmegaCats; k++)
10219                 {
10220                 siteOmega += (catLike[k][i] / siteLike[i]) * omega[k];
10221                 }
10222             ps[c2] = siteOmega;
10223             }
10224         }
10225     
10226     free (catLike);
10227     free (mCatLike);
10228     
10229     return NO_ERROR;
10230 }
10231 #endif
10232
10233
10234 /*----------------------------------------------------------------------
10235 |
10236 |   PreparePrintFiles: Prepare .t, .p, and .mcmc files for printing
10237 |
10238 ------------------------------------------------------------------------*/
10239 int PreparePrintFiles (void)
10240 {
10241     int         i, n, previousResults, oldAutoOverwrite, oldNoWarn;
10242     char        localFileName[100], fileName[220], bkupName[220];
10243     FILE        *tempFile;
10244
10245 #if defined (MPI_ENABLED)
10246     if (proc_id != 0)
10247         return (NO_ERROR);
10248 #endif
10249
10250     oldNoWarn        = noWarn;
10251     oldAutoOverwrite = autoOverwrite;
10252
10253     /* Allocate space for file pointers */
10254     if (memAllocs[ALLOC_FILEPOINTERS] == YES)
10255         {
10256         MrBayesPrint ("%s   File pointers already allocated in PreparePrintFiles\n", spacer);
10257         return ERROR;
10258         }
10259     fpMcmc = NULL;
10260     fpSS = NULL;
10261     fpParm = NULL;
10262     fpTree = NULL;  
10263     fpParm = (FILE **) SafeCalloc (chainParams.numRuns, sizeof (FILE *));
10264     if (fpParm == NULL)
10265         {
10266         MrBayesPrint ("%s   Could not allocate fpParm in PreparePrintFiles\n", spacer);
10267         return ERROR;
10268         }
10269     memAllocs[ALLOC_FILEPOINTERS] = YES;
10270     fpTree = (FILE ***) SafeCalloc (chainParams.numRuns, sizeof (FILE **));
10271     if (fpTree == NULL)
10272         {
10273         MrBayesPrint ("%s   Could not allocate fpTree in PreparePrintFiles\n", spacer);
10274         return ERROR;
10275         }
10276     fpTree[0] = (FILE **) SafeCalloc (numTrees*chainParams.numRuns, sizeof (FILE *));
10277     if (fpTree[0] == NULL)
10278         {
10279         MrBayesPrint ("%s   Could not allocate fpTree[0] in PreparePrintFiles\n", spacer);
10280         return ERROR;
10281         }
10282     for (i=1; i<chainParams.numRuns; i++)
10283         fpTree[i] = fpTree[0] + i*numTrees;
10284
10285     /* Get root of local file name */
10286     strcpy (localFileName, chainParams.chainFileName);
10287
10288     /* Determine whether to overwrite files */
10289     if (noWarn == NO)
10290         {
10291         previousResults = NO;
10292         if (chainParams.mcmcDiagn == YES)
10293             {
10294             sprintf (fileName, "%s.mcmc", localFileName);
10295             if ((tempFile = TestOpenTextFileR(fileName)) != NULL)
10296                 {
10297                 fclose(tempFile);
10298                 previousResults = YES;
10299                 }
10300             }
10301         for (n=0; n<chainParams.numRuns; n++)
10302             {
10303             if (chainParams.numRuns == 1)
10304                 sprintf (fileName, "%s.p", localFileName);
10305             else
10306                 sprintf (fileName, "%s.run%d.p", localFileName, n+1);
10307             if ((tempFile = TestOpenTextFileR(fileName)) != NULL)
10308                 {
10309                 fclose(tempFile);
10310                 previousResults = YES;
10311                 }
10312
10313             for (i=0; i<numTrees; i++)
10314                 {
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);
10321                 else
10322                     sprintf (fileName, "%s.tree%d.run%d.t", localFileName, i+1, n+1);
10323                 if ((tempFile = TestOpenTextFileR(fileName)) != NULL)
10324                     {
10325                     fclose(tempFile);
10326                     previousResults = YES;
10327                     }
10328                 }
10329             }
10330         if (previousResults == YES)
10331             {
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)
10335                 {
10336                 MrBayesPrint("\n");
10337                 noWarn = YES;
10338                 autoOverwrite = YES;
10339                 }
10340             else
10341                 {
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);
10346                 return ERROR;
10347                 }
10348             }
10349         }
10350
10351     /* Prepare the .mcmc file */
10352     if (chainParams.mcmcDiagn == YES)
10353         {
10354         sprintf (fileName, "%s.mcmc", chainParams.chainFileName);
10355         if ((fpMcmc = OpenNewMBPrintFile (fileName)) == NULL)
10356             {
10357             noWarn = oldNoWarn;
10358             autoOverwrite = oldAutoOverwrite;
10359             return (ERROR);
10360             }
10361         }
10362     
10363     /* Prepare the .p and .t files */
10364     for (n=0; n<chainParams.numRuns; n++)
10365         {
10366         if (chainParams.numRuns == 1)
10367             sprintf (fileName, "%s.p", localFileName);
10368         else
10369             sprintf (fileName, "%s.run%d.p", localFileName, n+1);
10370         if ((fpParm[n] = OpenNewMBPrintFile (fileName)) == NULL)
10371             {
10372             noWarn = oldNoWarn;
10373             autoOverwrite = oldAutoOverwrite;
10374             return (ERROR);
10375             }
10376
10377         for (i=0; i<numTrees; i++)
10378             {
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);
10385             else
10386                 sprintf (fileName, "%s.tree%d.run%d.t", localFileName, i+1, n+1);
10387             if ((fpTree[n][i] = OpenNewMBPrintFile (fileName)) == NULL)
10388                 {
10389                 noWarn = oldNoWarn;
10390                 autoOverwrite = oldAutoOverwrite;
10391                 return (ERROR);
10392                 }
10393             }
10394         }
10395
10396     /* Prepare the .ss file */
10397     if (chainParams.isSS == YES)
10398         {
10399         sprintf (fileName, "%s.ss", chainParams.chainFileName);
10400         if ((fpSS = OpenNewMBPrintFile (fileName)) == NULL)
10401             {
10402             noWarn = oldNoWarn;
10403             autoOverwrite = oldAutoOverwrite;
10404             return (ERROR);
10405             }
10406         }
10407
10408     /* Remove previous chekpoint file if present */
10409     sprintf (fileName, "%s%s.ckp", workingDir, chainParams.chainFileName);
10410     strcpy (bkupName, fileName);
10411     strcat (bkupName, "~");
10412     remove (bkupName);
10413     rename (fileName, bkupName);
10414     
10415 #   if defined (PRINT_DUMP)
10416     fpDump = (FILE **) SafeCalloc (chainParams.numRuns, sizeof (FILE *));
10417
10418     for (n=0; n<chainParams.numRuns; n++)
10419         {
10420         if (chainParams.numRuns == 1)
10421             sprintf (fileName, "%s.dump", localFileName);
10422         else
10423             sprintf (fileName, "%s.run%d.dump", localFileName, n+1);
10424         
10425         if ((fpDump[n] = OpenNewMBPrintFile (fileName)) == NULL)
10426             return (ERROR);
10427         }
10428 #   endif
10429
10430     return (NO_ERROR);
10431 }
10432
10433
10434 /*----------------------------------------------------------------
10435 |
10436 |   PrintAncStates_Bin: print ancestral states after final pass
10437 |       Binary model with or without rate variation
10438 |
10439 -----------------------------------------------------------------*/
10440 int PrintAncStates_Bin (TreeNode *p, int division, int chain)
10441 {
10442     int             c, i, k;
10443     MrBFlt          *bs, freq;
10444     CLFlt           *clFP, *cL, sum, **clP;
10445     char            *tempStr;
10446     int             tempStrSize = TEMPSTRSIZE;
10447     ModelInfo       *m;
10448     
10449     tempStr = (char *) SafeMalloc((size_t)tempStrSize * sizeof(char));
10450     if (!tempStr)
10451         {
10452         MrBayesPrint ("%s   Problem allocating tempString (%d)\n", spacer, tempStrSize * sizeof(char));
10453         return (ERROR);
10454         }
10455
10456     /* find model settings for this division */
10457     m = &modelSettings[division];
10458
10459     /* find state frequencies */
10460     bs = GetParamSubVals (m->stateFreq, chain, state[chain]);
10461     
10462     /* find frequencies of rate categories */
10463     freq =  1.0 /  m->numGammaCats;
10464     
10465     /* find the conditional likelihoods from the final pass */
10466     clFP = m->condLikes[m->condLikeScratchIndex[p->index]];
10467
10468     clP = m->clP;
10469     for (k=0; k<m->numGammaCats; k++)
10470         {
10471         clP[k] =  clFP;
10472         clFP += m->numChars * m->numModelStates;
10473         }
10474
10475     /* find the preallocated working space */
10476     cL = m->ancStateCondLikes;
10477     
10478     /* cycle over the compressed characters */
10479     for (c=0; c<m->numChars; c++)
10480         {
10481         cL[0] = cL[1] = 0.0;
10482         for (k=0; k<m->numGammaCats; k++)
10483             {
10484             cL[0] += clP[k][0];
10485             cL[1] += clP[k][1];
10486             clP[k]+=2;
10487             }
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);
10494         cL[0] /= sum;
10495         cL[1] /= sum;
10496         assert (cL[0]==cL[0]);
10497         assert (cL[1]==cL[1]);
10498         cL += 2;
10499         }
10500
10501     /* print the resulting conditional likelihoods cycling over uncompressed chars */
10502     for (c=0; c<numChar; c++)
10503         {
10504         if (charInfo[c].isExcluded == YES || partitionId[c][partitionNum] != division+1)
10505             continue;
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);
10512         }
10513
10514     free (tempStr);
10515     return NO_ERROR;
10516 }
10517
10518
10519 /*----------------------------------------------------------------
10520 |
10521 |   PrintAncStates_Gen: print ancestral states after final pass
10522 |       General model with or without rate variation
10523 |
10524 -----------------------------------------------------------------*/
10525 int PrintAncStates_Gen (TreeNode *p, int division, int chain)
10526 {
10527     int             c, i, k, nStates, hasPInvar, nGammaCats;
10528     const int       *rateCat;
10529     MrBFlt          *bsVals;
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;
10534     ModelInfo       *m;
10535     
10536     tempStr = (char *) SafeMalloc((size_t)tempStrSize * sizeof(char));
10537     if (!tempStr)
10538         {
10539         MrBayesPrint ("%s   Problem allocating tempString (%d)\n", spacer, tempStrSize * sizeof(char));
10540         return (ERROR);
10541         }
10542
10543     if (!strcmp(modelParams[division].nucModel,"Codon") || !strcmp(modelParams[division].nucModel,"Protein") || !strcmp(modelParams[division].nucModel,"Doublet"))
10544         {
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));
10548         }
10549     else
10550         {
10551         printedChar = NULL;
10552         }
10553
10554         
10555     /* find model settings for this division */
10556     m = &modelSettings[division];
10557
10558     /* find number of states */
10559     nStates = m->numModelStates;
10560     
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];
10565
10566     /* find invar cond likes */
10567     if (m->pInvar == NULL)
10568         hasPInvar = NO;
10569     else
10570         {
10571         hasPInvar = YES;
10572         clInvar = m->invCondLikes;
10573         pInvar = (CLFlt) *GetParamVals (m->pInvar, chain, state[chain]); 
10574         }
10575
10576     /* find number of rate categories */
10577     nGammaCats = m->numGammaCats;
10578
10579     /* find frequencies of rate categories (only relevant if gibbsGamma == NO) */
10580     freq = ((CLFlt)1.0 - pInvar) / nGammaCats;
10581     
10582     /* find site scaler */
10583     lnScaler = m->scalers[m->siteScalerIndex[chain]];
10584     
10585     /* find rate category index */
10586     rateCat = m->tiIndex + chain*m->numChars;
10587
10588     /* find the conditional likelihoods from the final pass */
10589     clFP = m->condLikes[m->condLikeScratchIndex[p->index]];
10590     
10591     /* find the preallocated working space */
10592     cL = m->ancStateCondLikes;
10593     
10594     /* cycle over the compressed characters */
10595     if (m->gibbsGamma == YES)
10596         {
10597         for (c=0; c<m->numChars; c++)
10598             {
10599             sum = 0.0;
10600             if (rateCat[c] < nGammaCats)
10601                 {
10602                 for (i=0; i<nStates; i++)
10603                     {
10604                     cL[i] = *(clFP++) * bs[i];
10605                     sum += cL[i];
10606                     }
10607                 clInvar += nStates;
10608                 }
10609             else
10610                 {
10611                 for (i=0; i<nStates; i++)
10612                     {
10613                     cL[i] = *(clInvar++) * bs[i];
10614                     sum += cL[i];
10615                     }
10616                 clFP += nStates;
10617                 }
10618             for (i=0; i<nStates; i++)
10619                 cL[i] /= sum;
10620             cL += nStates;
10621             }
10622         }
10623     else
10624         {
10625         /* find conditional likelihood pointers */
10626         clP = (const CLFlt**)m->clP;
10627         for (k=0; k<m->numGammaCats; k++)
10628             {
10629             clP[k] = clFP;
10630             clFP += m->numChars * m->numModelStates;
10631             }
10632         for (c=0; c<m->numChars; c++)
10633             {
10634             for (i=0; i<nStates; i++)
10635                 cL[i] = 0.0;
10636             for (k=0; k<nGammaCats; k++)
10637                 {
10638                 for (i=0; i<nStates; i++)
10639                     cL[i] += *(clP[k]++);
10640                 }
10641             for (i=0; i<nStates; i++)
10642                 cL[i] *= bs[i];
10643
10644             if (hasPInvar == YES && pInvar > 0)
10645                 {
10646                 sum = 0.0;
10647                 for (i=0; i<nStates; i++)
10648                     sum += clInvar[i];
10649                 if (sum > 0.0)
10650                     {
10651                     if (lnScaler[c] < -100.0)
10652                         {
10653                         /* only invar cond likes are relevant */
10654                         for (i=0; i<nStates; i++)
10655                             cL[i] = clInvar[i] * bs[i] * pInvar;
10656                         }
10657                     else
10658                         {
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;
10662                         }
10663                     }
10664                 clInvar += nStates;
10665                 }
10666             
10667             sum = 0.0;
10668             for (i=0; i<nStates; i++)
10669                 sum += cL[i];
10670             assert (sum > 0.0);
10671             for (i=0; i<nStates; i++)
10672                 cL[i] /= sum;
10673             cL += nStates;
10674             }
10675         }
10676
10677     /* print the resulting conditional likelihoods cycling over uncompressed chars */
10678     if (printedChar)
10679         for (c=0; c<numChar; c++)
10680             printedChar[c] = NO;
10681
10682     for (c=0; c<numChar; c++)
10683         {
10684         if (charInfo[c].isExcluded == YES || partitionId[c][partitionNum] != division+1 || (printedChar &&
10685             printedChar[c] == YES))
10686             continue;
10687         i = compCharPos[c] - m->compCharStart;
10688         cL = m->ancStateCondLikes + (i*nStates);
10689         if (printedChar)
10690             {
10691             for (i=c+1; i<numChar; i++)
10692                 if (charInfo[c].charId == charInfo[i].charId)
10693                     printedChar[i] = YES;
10694             }
10695         for (i=0; i<nStates; i++)
10696             {
10697             SafeSprintf (&tempStr, &tempStrSize, "\t%s", MbPrintNum(cL[i]));
10698             if (AddToPrintString (tempStr) == ERROR) return (ERROR);
10699             }
10700         }
10701     free (tempStr);
10702     free (printedChar);
10703     return NO_ERROR;
10704 }
10705
10706
10707 /*----------------------------------------------------------------
10708 |
10709 |   PrintAncStates_NUC4: print ancestral states after final pass
10710 |       4-state nucleotide model with or without rate variation
10711 |
10712 -----------------------------------------------------------------*/
10713 int PrintAncStates_NUC4 (TreeNode *p, int division, int chain)
10714 {
10715     int             c, i, k, *rateCat, hasPInvar, nGammaCats;
10716     MrBFlt          *bsVals;
10717     CLFlt           *cL, sum, pInvar=0.0, bs[4], freq, f;
10718     const CLFlt     *clFP, *clInvar=NULL, *lnScaler,**clP;
10719     char            *tempStr;
10720     int             tempStrSize = TEMPSTRSIZE;
10721     ModelInfo       *m;
10722     
10723     tempStr = (char *) SafeMalloc((size_t)tempStrSize * sizeof(char));
10724     if (!tempStr)
10725         {
10726         MrBayesPrint ("%s   Problem allocating tempString (%d)\n", spacer, tempStrSize * sizeof(char));
10727         return (ERROR);
10728         }
10729
10730     /* find model settings for this division */
10731     m = &modelSettings[division];
10732
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];
10739
10740     /* find invar cond likes */
10741     if (m->pInvar == NULL)
10742         hasPInvar = NO;
10743     else
10744         {
10745         hasPInvar = YES;
10746         clInvar = m->invCondLikes;
10747         pInvar = (CLFlt) *GetParamVals (m->pInvar, chain, state[chain]); 
10748         }
10749
10750     /* find number of rate categories */
10751     nGammaCats = m->numGammaCats;
10752
10753     /* find frequencies of rate categories (only relevant if gibbsGamma == NO) */
10754     if (hasPInvar == NO)
10755         freq =  (CLFlt) 1.0 /  nGammaCats;
10756     else
10757         freq = ((CLFlt)1.0 - pInvar) / nGammaCats;
10758     
10759     /* find site scaler */
10760     lnScaler = m->scalers[m->siteScalerIndex[chain]];
10761     
10762     /* find rate category index */
10763     rateCat = m->tiIndex + chain*m->numChars;
10764
10765     /* find the conditional likelihoods from the final pass */
10766     clFP = m->condLikes[m->condLikeScratchIndex[p->index]];
10767     
10768     /* find the preallocated working space */
10769     cL = m->ancStateCondLikes;
10770     
10771     /* cycle over the compressed characters */
10772     if (m->gibbsGamma == YES)
10773         {
10774         for (c=0; c<m->numChars; c++)
10775             {
10776             if (rateCat[c] < nGammaCats)
10777                 {
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];
10782                 }
10783             else
10784                 {
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];
10789                 }
10790             sum = cL[A] + cL[C] + cL[G] + cL[T];
10791             cL[A] /= sum;
10792             cL[C] /= sum;
10793             cL[G] /= sum;
10794             cL[T] /= sum;
10795             clInvar += 4;
10796             clFP += 4;
10797             cL += 4;
10798             }
10799         }
10800     else
10801         {
10802         /* find conditional likelihood pointers */
10803         clP = (const CLFlt**)m->clP;
10804         for (k=0; k<m->numGammaCats; k++)
10805             {
10806             clP[k] = clFP;
10807             clFP += m->numChars * m->numModelStates;
10808             }
10809
10810         for (c=0; c<m->numChars; c++)
10811             {
10812             cL[A] = cL[C] = cL[G] = cL[T] = 0.0;
10813             for (k=0; k<nGammaCats; k++)
10814                 {
10815                 cL[A] += clP[k][A];
10816                 cL[C] += clP[k][C];
10817                 cL[G] += clP[k][G];
10818                 cL[T] += clP[k][T];
10819                 clP[k] += 4;
10820                 }
10821             cL[A] *= bs[A];
10822             cL[C] *= bs[C];
10823             cL[G] *= bs[G];
10824             cL[T] *= bs[T];
10825             if (hasPInvar == YES)
10826                 {
10827                 sum = clInvar[A] + clInvar[C] + clInvar[G] + clInvar[T];
10828                 if (sum > 0.0)
10829                     {
10830                     if (lnScaler[c] < -100.0)
10831                         {
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;
10837                         }
10838                     else
10839                         {
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;
10845                         }
10846                     }
10847                 clInvar += 4;
10848                 }
10849             sum = cL[A] + cL[C] + cL[G] + cL[T];
10850             cL[A] /= sum;
10851             cL[C] /= sum;
10852             cL[G] /= sum;
10853             cL[T] /= sum;
10854             cL += 4;
10855             }
10856         }
10857
10858     /* print the resulting conditional likelihoods cycling over uncompressed chars */
10859     for (c=0; c<numChar; c++)
10860         {
10861         if (charInfo[c].isExcluded == YES || partitionId[c][partitionNum] != division+1)
10862             continue;
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;
10873         }
10874     free (tempStr);
10875     return NO_ERROR;
10876 }
10877
10878
10879 /*----------------------------------------------------------------
10880 |
10881 |   PrintAncStates_Std: print ancestral states after final pass
10882 |       Standard model with or without rate variation
10883 |
10884 -----------------------------------------------------------------*/
10885 int PrintAncStates_Std (TreeNode *p, int division, int chain)
10886 {
10887     int             c, i, j, k, s, nStates, numReps;
10888     MrBFlt          *bsBase, *bs, freq;
10889     CLFlt           *clFP, *cL, sum,** clP;
10890     char            *tempStr;
10891     int             tempStrSize = TEMPSTRSIZE;
10892     ModelInfo       *m;
10893     
10894     tempStr = (char *) SafeMalloc((size_t)tempStrSize * sizeof(char));
10895     if (!tempStr)
10896         {
10897         MrBayesPrint ("%s   Problem allocating tempString (%d)\n", spacer, tempStrSize * sizeof(char));
10898         return (ERROR);
10899         }
10900
10901     /* find model settings for this division */
10902     m = &modelSettings[division];
10903
10904     /* find state frequencies, base index */
10905     bsBase = GetParamStdStateFreqs (m->stateFreq, chain, state[chain]);
10906     
10907     /* find the conditional likelihoods from the final pass */
10908     clFP = m->condLikes[m->condLikeScratchIndex[p->index]];
10909
10910     numReps=0;
10911     for (c=0; c<m->numChars; c++)
10912         {
10913         if (m->nStates[c] == 2)
10914                 numReps += m->numBetaCats * 2;
10915             else
10916                 numReps += m->nStates[c];
10917         }
10918
10919     /* find conditional likelihood pointers */
10920     clP = m->clP;
10921     for (k=0; k<m->numGammaCats; k++)
10922         {
10923         clP[k] = clFP;
10924         clFP += numReps;
10925         }
10926
10927     /* find the preallocated working space */
10928     cL = m->ancStateCondLikes;
10929     
10930     /* cycle over the compressed characters */
10931     for (c=0; c<m->numChars; c++)
10932         {
10933         nStates = m->nStates[c];
10934         bs = bsBase + m->bsIndex[c];
10935
10936         for (s=0; s<nStates; s++)
10937             cL[s] = 0.0;
10938
10939         if (nStates == 2)
10940             {
10941             freq = 1.0 / (m->numBetaCats * m->numGammaCats);
10942             for (i=0; i<m->numBetaCats; i++)
10943                 {
10944                 for (k=0; k<m->numGammaCats; k++)
10945                     {
10946                     for (s=0; s<nStates; s++)
10947                         cL[s] += clP[k][s] * (CLFlt)(bs[s] * freq);
10948                     clP[k] += nStates;
10949                     }
10950                 bs += nStates;
10951                 }
10952            }
10953         else
10954             {
10955             freq = 1.0 / (m->numGammaCats);
10956             for (k=0; k<m->numGammaCats; k++)
10957                 {
10958                 for (s=0; s<nStates; s++)
10959                     cL[s] += clP[k][s] * (CLFlt)(bs[s] * freq);
10960                 clP[k] += nStates;
10961                 }
10962             }
10963
10964         sum = 0.0;
10965         for (s=0; s<nStates; s++)
10966             sum += cL[s];
10967
10968         assert (sum != 0.0);
10969
10970         for (s=0; s<nStates; s++) 
10971             cL[s] /= sum;
10972
10973         cL += nStates;
10974         }
10975
10976     /* print the resulting conditional likelihoods cycling over uncompressed chars */
10977     for (c=0; c<numChar; c++)
10978         {
10979         if (charInfo[c].isExcluded == YES || partitionId[c][partitionNum] != division+1)
10980             continue;
10981         
10982         k = compCharPos[c] - m->compCharStart;
10983         for (i=j=0; i<k; i++)
10984             j += m->nStates[i];
10985         cL = m->ancStateCondLikes + j;
10986
10987         for (i=0; i<m->nStates[k]; i++)
10988             {
10989             SafeSprintf (&tempStr, &tempStrSize, "\t%s", MbPrintNum(cL[i]));
10990             if (AddToPrintString (tempStr) == ERROR) return (ERROR);
10991             }
10992         }
10993     free (tempStr);
10994     return NO_ERROR;
10995 }
10996
10997
10998 /*-----------------------------------------------------------------------
10999 |
11000 |   PrintCheckPoint: Print checkpoint to file
11001 |
11002 ------------------------------------------------------------------------*/
11003 int PrintCheckPoint (int gen)
11004 {
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;
11010     Tree        *t;
11011     FILE        *fp = NULL;
11012     MCMCMove    *mv;
11013     /*ModelInfo *m = NULL;*/
11014
11015 #if defined (MPI_ENABLED)
11016     int         sumErrors=0,ierror;
11017     MrBFlt      r, sum;
11018 #endif
11019
11020     /* use high precision for checkpointing */
11021     oldPrecision = precision;
11022     precision = 15;
11023
11024     /* allocate tempString */
11025     if ((tempString = (char *) SafeCalloc (tempStrSize, sizeof(char))) == NULL)
11026         nErrors++;
11027
11028 #if defined (MPI_ENABLED)
11029     if (proc_id == 0)
11030         {
11031 #endif
11032     if (nErrors == 0)
11033         {
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, "~");
11040
11041         /* shift check-point files */
11042         remove (oldBkupFileName);
11043         rename (bkupFileName, oldBkupFileName);
11044         rename (ckpFileName, bkupFileName);
11045
11046         /* create new ckp file */
11047         if ((fp = OpenTextFileW (ckpFileName)) == NULL)
11048             {
11049             MrBayesPrint ("%s   Problem opening checkpoint file\n", spacer);
11050             nErrors++;
11051             }
11052         }
11053     
11054 #if defined (MPI_ENABLED)
11055         } /* end of if (proc_id == 0)*/
11056 #endif
11057
11058     ERROR_TEST2("",free(tempString),return(ERROR));
11059     
11060     /* write file header */
11061     MrBayesPrintf (fp, "#NEXUS\n[ID: %s]\n[generation: %d]\n", stamp, gen);
11062
11063     if (chainParams.isSS == YES)
11064         {
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++)
11069             {
11070             if (stepAcumulatorSS[j]==0)
11071                 r=0;
11072             else
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)
11076                 {
11077                 MrBayesPrint ("%s   Problem with MPI_Reduce\n", spacer);
11078                 return ERROR;
11079                 }
11080             if (proc_id == 0)
11081                 {
11082                 MrBayesPrintf (fp, " %.4f", sum);
11083                 }
11084             }
11085 #       else
11086         for (j=0; j<chainParams.numRuns ; j++)
11087             {
11088             MrBayesPrintf (fp, " %.4f", log (stepAcumulatorSS[j]) + stepScalerSS[j]);
11089             }
11090 #       endif
11091         MrBayesPrintf (fp, "]\n");
11092         }
11093
11094 #if defined (MPI_ENABLED)
11095 if (proc_id == 0)
11096     {
11097 #endif
11098     MrBayesPrintf (fp, "\nbegin trees;\n\ttranslate\n");
11099
11100     /* remove old bkup file ('~~') */
11101     remove (oldBkupFileName);
11102
11103     /* write translate block */
11104     for (i=0; i<numLocalTaxa; i++)
11105         {
11106         if (i == numLocalTaxa - 1)
11107             MrBayesPrintf (fp, "      %2d %s;\n", i+1, localTaxonNames[i]);
11108         else
11109             MrBayesPrintf (fp, "      %2d %s,\n", i+1, localTaxonNames[i]);
11110         }
11111    
11112 #if defined (MPI_ENABLED)
11113     }
11114 #endif
11115
11116     /* allocate space for print string */
11117     printStringSize = tempStrSize;
11118     printString = (char *) SafeCalloc ((size_t)printStringSize, sizeof(char));
11119     if (!printString)
11120         nErrors++;
11121     else
11122         strcpy(printString,"");
11123
11124     ERROR_TEST2("Memory allocation error",free(tempString),return(ERROR));
11125     /*
11126 #   if defined (MPI_ENABLED)
11127     MPI_Allreduce (&nErrors, &sumErrors, 1, MPI_INT, MPI_SUM, MPI_COMM_WORLD);
11128     if (sumErrors > 0)
11129         {
11130         MrBayesPrint ("%s   Memory allocation error on at least one processor\n", spacer);
11131         free (tempString);
11132         return ERROR;
11133         }
11134 #   else
11135     if (nErrors > 0)
11136         {
11137         free (tempString);
11138         return ERROR;
11139         }
11140 #   endif
11141 */
11142     /* print trees (but not species trees) */
11143     for (i=0; i<numParams; i++)
11144         {
11145         p = &params[i];
11146         if (p->paramType != P_BRLENS && p->paramType != P_TOPOLOGY)
11147             continue;
11148         if (p->paramType == P_TOPOLOGY && p->subParams[0] != p)
11149             continue;
11150         hasEvents = NO;
11151         for (j=0; j<numLocalChains; j++)
11152             {
11153             t = GetTree (p, j, state[j]);
11154             /* write the tree preamble */
11155             if (nErrors == 0 && SafeSprintf (&tempString, &tempStrSize, "\ttree %s", t->name) == ERROR)
11156                 nErrors++;
11157             if (nErrors == 0 && AddToPrintString (tempString) == ERROR)
11158                 nErrors++;
11159             if (p->paramType == P_BRLENS && p->nSubParams > 0)
11160                 {
11161                 for (k=0; k<p->nSubParams; k++)
11162                     {
11163                     subParm = p->subParams[k];
11164                     if (subParm->paramType == P_CPPEVENTS)
11165                         {
11166                         hasEvents = YES;
11167                         if (SafeSprintf (&tempString, &tempStrSize, " [&E %s]", subParm->name) == ERROR) nErrors++;
11168                         if (nErrors == 0 && AddToPrintString (tempString) == ERROR) nErrors++;
11169                         }
11170                     if (nErrors == 0 && (subParm->paramType == P_CPPEVENTS || subParm->paramType == P_TK02BRANCHRATES ||
11171                                          subParm->paramType == P_IGRBRANCHRATES || subParm->paramType == P_MIXEDBRCHRATES))
11172                         {
11173                         if (subParm->paramType == P_MIXEDBRCHRATES)
11174                             {
11175                             id = *GetParamIntVals(subParm, j, state[j]);
11176                             if (SafeSprintf (&tempString, &tempStrSize, " [&B %s %d]", subParm->name, id) == ERROR) nErrors++;
11177                             }
11178                         else
11179                             if (SafeSprintf (&tempString, &tempStrSize, " [&B %s]", subParm->name) == ERROR) nErrors++;
11180                         if (nErrors == 0 && AddToPrintString (tempString) == ERROR) nErrors++;
11181                         }
11182                     }
11183                 }
11184
11185             if (t->isRooted == YES && t->isClock == NO)
11186                 SafeSprintf (&tempString, &tempStrSize, " = ");
11187             else if (t->isRooted == YES && t->isClock == YES)
11188                 {
11189                 clockRate = *GetParamVals(modelSettings[p->relParts[0]].clockRate, j, state[j]);
11190                 SafeSprintf (&tempString, &tempStrSize, " = [&R] [&clockrate = %s] ", MbPrintNum(clockRate));
11191                 }
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 */
11196             if (nErrors == 0)
11197                 {
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);
11202                 else
11203                     WriteEventTreeToPrintString (t->root->left, j, p, YES);
11204                 if (AddToPrintString (";\n") == ERROR)
11205                     nErrors++;
11206                 }
11207             }
11208         MrBayesPrintf (fp, "%s", printString);
11209 #if defined (MPI_ENABLED)
11210         MPI_Allreduce (&nErrors, &sumErrors, 1, MPI_INT, MPI_SUM, MPI_COMM_WORLD);
11211         if (sumErrors > 0)
11212             {
11213             MrBayesPrint ("%s   Print error on at least one processor\n", spacer);
11214             goto errorExit;
11215             }
11216         if (PrintMPISlaves(fp) == ERROR)
11217             goto errorExit;
11218 #else
11219         if (nErrors > 0)
11220             goto errorExit;
11221 #endif
11222         strcpy (printString, "");
11223         strcpy (tempString, "");
11224         }
11225     MrBayesPrintf (fp, "end;\n\n");
11226
11227     /* print species trees */
11228     if (strcmp(modelParams[0].topologyPr,"Speciestree") == 0)
11229         {
11230         /* get the first species tree */
11231         for (i=0; i<numParams; i++)
11232             {
11233             p = &params[i];
11234             if (p->paramType == P_SPECIESTREE)
11235                 break;
11236             }
11237         t = GetTree(p, 0, state[0]);
11238
11239 #if defined (MPI_ENABLED)
11240 if (proc_id == 0)
11241         {
11242 #endif
11243         /* write the block header and translate block */
11244         MrBayesPrintf (fp, "\nbegin trees;\n");
11245         PrintTranslateBlock (fp, t);
11246 #if defined (MPI_ENABLED)
11247         }
11248 #endif
11249
11250         for (j=0; j<numLocalChains; j++)
11251             {
11252             t = GetTree (p, j, state[j]);
11253
11254             /* write the tree preamble */
11255             if (nErrors == 0 && SafeSprintf (&tempString, &tempStrSize, "\ttree %s", t->name) == ERROR)
11256                 nErrors++;
11257             if (nErrors == 0 && AddToPrintString (tempString) == ERROR)
11258                 nErrors++;
11259                 
11260             subParm = modelSettings[p->relParts[0]].popSize;
11261             if (subParm->nValues > 1)
11262                 {
11263                 if (SafeSprintf (&tempString, &tempStrSize, " [&N %s]", subParm->name) == ERROR) nErrors++;
11264                 if (nErrors == 0 && AddToPrintString (tempString) == ERROR) nErrors++;
11265                 }
11266
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++;
11270
11271             /* write the tree in (extended) Newick format */
11272             if (nErrors == 0)
11273                 {
11274                 WriteNoEvtTreeToPrintString (t->root->left, j, p, YES, t->isRooted);
11275                 if (AddToPrintString (";\n") == ERROR)
11276                 nErrors++;
11277                 }
11278             }
11279         MrBayesPrintf (fp, "%s", printString);
11280 #if defined (MPI_ENABLED)
11281         MPI_Allreduce (&nErrors, &sumErrors, 1, MPI_INT, MPI_SUM, MPI_COMM_WORLD);
11282         if (sumErrors > 0)
11283             {
11284             MrBayesPrint ("%s   Print error on at least one processor\n", spacer);
11285             goto errorExit;
11286             }
11287         if (PrintMPISlaves(fp) == ERROR)
11288             goto errorExit;
11289 #else
11290         if (nErrors > 0)
11291             goto errorExit;
11292 #endif
11293         strcpy (printString, "");
11294         strcpy (tempString, "");
11295         MrBayesPrintf (fp, "end;\n\n");
11296         }
11297             
11298     /* start startvals block */
11299     MrBayesPrintf (fp,"begin mrbayes;\n");
11300     MrBayesPrintf (fp, "\tstartvals\n");
11301
11302     /* first print topology values */
11303     for (i=0; i<numParams; i++)
11304         {
11305         p = &params[i];
11306         if (p->paramType == P_TOPOLOGY)
11307             {
11308             for (j=0; j<numLocalChains; j++)
11309                 {
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)
11314                     nErrors++;
11315                 if (nErrors == 0 && AddToPrintString (tempString) == ERROR)
11316                     nErrors++;
11317                 }
11318             MrBayesPrintf (fp, "%s", printString);
11319 #   if defined (MPI_ENABLED)
11320             MPI_Allreduce (&nErrors, &sumErrors, 1, MPI_INT, MPI_SUM, MPI_COMM_WORLD);
11321             if (sumErrors > 0)
11322                 {
11323                 MrBayesPrint ("%s   Print error on at least one processor\n", spacer);
11324                 goto errorExit;
11325                 }
11326             if (PrintMPISlaves(fp) == ERROR)
11327                 goto errorExit;
11328 #   else
11329             if (nErrors > 0)
11330                 goto errorExit;
11331 #   endif
11332             strcpy (printString, "");
11333             strcpy (tempString, "");
11334             }
11335         }
11336
11337     /* now print branch lengths and relaxed clock parameters */
11338     for (i=0; i<numParams; i++)
11339         {
11340         p = &params[i];
11341         if (p->paramType == P_BRLENS)
11342             {
11343             for (j=0; j<numLocalChains; j++)
11344                 {
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)
11349                     nErrors++;
11350                 if (nErrors == 0 && AddToPrintString (tempString) == ERROR)
11351                     nErrors++;
11352                 for (k=0; k<p->nSubParams; k++)
11353                     {
11354                     if (nErrors == 0 && SafeSprintf (&tempString, &tempStrSize, "\t\t%s(%d,%d)=%s\n", p->subParams[k]->name, run, chn, t->name) == ERROR)
11355                         nErrors++;
11356                     if (nErrors == 0 && AddToPrintString (tempString) == ERROR)
11357                         nErrors++;
11358                     }
11359                 }
11360             MrBayesPrintf (fp, "%s", printString);
11361 #   if defined (MPI_ENABLED)
11362             MPI_Allreduce (&nErrors, &sumErrors, 1, MPI_INT, MPI_SUM, MPI_COMM_WORLD);
11363             if (sumErrors > 0)
11364                 {
11365                 MrBayesPrint ("%s   Print error on at least one processor\n", spacer);
11366                 goto errorExit;
11367                 }
11368             if (PrintMPISlaves(fp) == ERROR)
11369                 goto errorExit;
11370 #   else
11371             if (nErrors > 0)
11372                 goto errorExit;
11373 #   endif
11374             strcpy (printString, "");
11375             strcpy (tempString, "");
11376             }
11377         }
11378
11379     /* now print species tree and population size parameters */
11380     for (i=0; i<numParams; i++)
11381         {
11382         p = &params[i];
11383         if (p->paramType == P_SPECIESTREE)
11384             {
11385             for (j=0; j<numLocalChains; j++)
11386                 {
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)
11391                     nErrors++;
11392                 if (nErrors == 0 && AddToPrintString (tempString) == ERROR)
11393                     nErrors++;
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)
11396                     nErrors++;
11397                 if (nErrors == 0 && AddToPrintString (tempString) == ERROR)
11398                     nErrors++;
11399                 }
11400             MrBayesPrintf (fp, "%s", printString);
11401 #   if defined (MPI_ENABLED)
11402             MPI_Allreduce (&nErrors, &sumErrors, 1, MPI_INT, MPI_SUM, MPI_COMM_WORLD);
11403             if (sumErrors > 0)
11404                 {
11405                 MrBayesPrint ("%s   Print error on at least one processor\n", spacer);
11406                 goto errorExit;
11407                 }
11408             if (PrintMPISlaves(fp) == ERROR)
11409                 goto errorExit;
11410 #   else
11411             if (nErrors > 0)
11412                 goto errorExit;
11413 #   endif
11414             strcpy (printString, "");
11415             strcpy (tempString, "");
11416             }
11417         }
11418
11419     /* now print param values */
11420     for (i=0; i<numPrintParams; i++)
11421         {
11422         p = printParam[i];
11423         for (j=0; j<numLocalChains; j++)
11424             {
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)
11428                 {
11429                 value = GetParamSubVals (p, j, state[j]);
11430                 nValues = p->nSubValues;
11431                 }
11432             else
11433                 {
11434                 value = GetParamVals (p, j, state[j]);
11435                 nValues = p->nValues;
11436                 }
11437             if (nErrors == 0 && SafeSprintf (&tempString, &tempStrSize, "\t\t%s(%d,%d)=(%.15le", p->name, run, chn, value[0]) == ERROR)
11438                 nErrors++;
11439             if (nErrors == 0 && AddToPrintString (tempString) == ERROR)
11440                 nErrors++;
11441             for (k=1; k<nValues; k++)
11442                 {
11443                 if (nErrors==0 && SafeSprintf (&tempString, &tempStrSize, ",%.15le", value[k]) == ERROR)
11444                     nErrors++;
11445                 if (nErrors == 0 && AddToPrintString (tempString) == ERROR)
11446                     nErrors++;
11447                 }
11448             /* print int values if present */
11449             if (p->nIntValues > 0)
11450                 {
11451                 intValue = GetParamIntVals (p, j, state[j]);
11452                 nValues  = p->nIntValues;
11453                 for (k=0; k<nValues; k++)
11454                     {
11455                     if (nErrors==0 && SafeSprintf (&tempString, &tempStrSize, ",%d", intValue[k]) == ERROR)
11456                         nErrors++;
11457                     if (nErrors == 0 && AddToPrintString (tempString) == ERROR)
11458                         nErrors++;
11459                     }
11460                 }
11461             /* print extra params for symdir multistate */
11462             if (p->nSympi > 0)
11463                 {
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++)
11468                     {
11469                     for (k1=0; k1<p->sympinStates[k]; k1++)
11470                         {
11471                         if (nErrors==0 && SafeSprintf (&tempString, &tempStrSize, ",%.15le", *value++) == ERROR)
11472                             nErrors++;
11473                         if (nErrors == 0 && AddToPrintString (tempString) == ERROR)
11474                             nErrors++;
11475                         }
11476                     }
11477                 }
11478             /* print extra params for omega */
11479             if (p->paramType == P_OMEGA)
11480                 {
11481                 value = GetParamSubVals (p, j, state[j]);
11482                 nValues = p->nSubValues/2;
11483                 for (k=0; k<nValues; k++)
11484                     {
11485                     if (nErrors==0 && SafeSprintf (&tempString, &tempStrSize, ",%.15le", value[k]) == ERROR)
11486                         nErrors++;
11487                     if (nErrors == 0 && AddToPrintString (tempString) == ERROR)
11488                         nErrors++;
11489                     }
11490                 }
11491             if (nErrors == 0 && AddToPrintString (")\n") == ERROR)
11492                 nErrors++;
11493             }
11494         MrBayesPrintf (fp, "%s", printString);
11495 #if defined (MPI_ENABLED)
11496         MPI_Allreduce (&nErrors, &sumErrors, 1, MPI_INT, MPI_SUM, MPI_COMM_WORLD);
11497         if (sumErrors > 0)
11498             {
11499             MrBayesPrint ("%s   Print error on at least one processor\n", spacer);
11500             goto errorExit;
11501             }
11502         if (PrintMPISlaves(fp) == ERROR)
11503             goto errorExit;
11504 #else
11505         if (nErrors > 0)
11506             goto errorExit;
11507 #endif
11508         strcpy (printString, "");
11509         strcpy (tempString, "");
11510         }
11511     /* end startvals statement */
11512     MrBayesPrintf (fp, "\t;\n");
11513
11514     /* print tuning parameters of moves */
11515     MrBayesPrintf (fp, "\tpropset\n");
11516     for (i=0; i<numUsedMoves; i++)
11517         {
11518         mv = usedMoves[i];
11519         if (mv->moveType->Autotune == NULL)
11520             continue;   /* tuning parameter(s) do not change */
11521         for (j=0; j<numLocalChains; j++)
11522             {
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)
11528                 nErrors++;
11529             if (nErrors == 0 && AddToPrintString (tempString) == ERROR)
11530                 nErrors++;
11531             }
11532         MrBayesPrintf (fp, "%s", printString);
11533 #if defined (MPI_ENABLED)
11534         MPI_Allreduce (&nErrors, &sumErrors, 1, MPI_INT, MPI_SUM, MPI_COMM_WORLD);
11535         if (sumErrors > 0)
11536             {
11537             MrBayesPrint ("%s   Print error on at least one processor\n", spacer);
11538             goto errorExit;
11539             }
11540         if (PrintMPISlaves(fp) == ERROR)
11541             goto errorExit;
11542 #else
11543         if (nErrors > 0)
11544             goto errorExit;
11545 #endif
11546         strcpy (printString, "");
11547         strcpy (tempString, "");
11548         }
11549
11550     /* end propset statement */
11551     MrBayesPrintf (fp, "\t;\n"); 
11552     
11553     /* end mrbayes block */
11554     MrBayesPrintf (fp, "end;\n\n");
11555
11556     /* change precision back */
11557     precision = oldPrecision;
11558     
11559     SafeFclose (&fp);
11560     free (tempString);
11561     free (printString);
11562     printStringSize = 0;
11563     return (NO_ERROR);
11564
11565 errorExit:
11566     precision = oldPrecision;
11567     free (tempString);
11568     free (printString);
11569     printString = NULL;
11570     printStringSize = 0;
11571     SafeFclose (&fp);
11572     return (ERROR);
11573 }
11574
11575
11576 /*----------------------------------------------------------------------
11577 |
11578 |   PrintMCMCDiagnosticsToFile: Print acceptance ratios, swapping
11579 |      frequencies, and convergence diagnostics to file.
11580 |
11581 ------------------------------------------------------------------------*/
11582 int PrintMCMCDiagnosticsToFile (int curGen)
11583 {
11584     int         i, j, n;
11585     MCMCMove    *theMove;
11586     char        *diagnstat;
11587
11588     /* Simply print header if curGen == 0 */
11589     if (curGen == 0)
11590         {
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";
11604         else
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);
11614
11615         MrBayesPrintf (fpMcmc, "Gen");
11616         for (n=0; n<chainParams.numRuns; n++)
11617             {
11618             if (chainParams.allChains == YES)
11619                 {
11620                 for (i=0; i<chainParams.numChains; i++)
11621                     {
11622                     for (j=0; j<numUsedMoves; j++)
11623                         {
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);
11630                         }
11631                     }
11632                 }
11633             else
11634                 {
11635                 for (i=0; i<numUsedMoves; i++)
11636                     {
11637                     theMove = usedMoves[i];
11638                     if (chainParams.numRuns == 1)
11639                         {
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]);
11643                         }
11644                     else
11645                         {
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);
11649                         }
11650                     }
11651                 }
11652             if (chainParams.numChains > 1)
11653                 {
11654                 for (i=0; i<chainParams.numChains; i++)
11655                     {
11656                     for (j=i+1; j<chainParams.numChains; j++)
11657                         {
11658                         if (chainParams.numRuns == 1)
11659                             MrBayesPrintf (fpMcmc, "\tSwap(%d<>%d)$acc", i+1, j+1);
11660                         else
11661                             MrBayesPrintf (fpMcmc, "\tSwap(%d<>%d)$acc(%d)", i+1, j+1, n+1);
11662                         }
11663                     }
11664                 }
11665             }
11666
11667         if (chainParams.numRuns > 1)
11668             {
11669             for (n=0; n<numTopologies; n++)
11670                 {
11671                 if (numTopologies == 1)
11672                     {
11673                     if (chainParams.diagnStat == AVGSTDDEV)
11674                         MrBayesPrintf (fpMcmc, "\tAvgStdDev(s)");
11675                     else
11676                         MrBayesPrintf (fpMcmc, "\tMaxStdDev(s)");
11677                     }
11678                 else
11679                     {
11680                     if (chainParams.diagnStat == AVGSTDDEV)
11681                         MrBayesPrintf (fpMcmc, "\tAvgStdDev(s.tree%d)", n+1);
11682                     else
11683                         MrBayesPrintf (fpMcmc, "\tMaxStdDev(s.tree%d)", n+1);
11684                     }
11685
11686                 if (chainParams.allComps == YES)
11687                     {
11688                     for (i=0; i<chainParams.numRuns; i++)
11689                         {
11690                         for (j=i+1; j<chainParams.numRuns; j++)
11691                             {
11692                             if (numTopologies == 1)
11693                                 {
11694                                 if (chainParams.diagnStat == AVGSTDDEV)
11695                                     MrBayesPrintf (fpMcmc, "\tAvgStdDev(s)(run%d_run%d)", i+1,j+1);
11696                                 else
11697                                     MrBayesPrintf (fpMcmc, "\tMaxStdDev(s)(run%d_run%d)", i+1, j+1);
11698                                 }
11699                             else
11700                                 {
11701                                 if (chainParams.diagnStat == AVGSTDDEV)
11702                                     MrBayesPrintf (fpMcmc, "\tAvgStdDev(s.tree%d)(run%d_run%d)", n+1, i+1, j+1);
11703                                 else
11704                                     MrBayesPrintf (fpMcmc, "\tMaxStdDev(s.tree%d)(run%d_run%d)", n+1, i+1, j+1);
11705                                 }
11706                             }
11707                         }
11708                     }
11709                 }
11710             }
11711         MrBayesPrintf (fpMcmc, "\n");
11712         fflush (fpMcmc);
11713         return (NO_ERROR);
11714         }
11715
11716 #if defined (MPI_ENABLED)
11717     /* Reassemble info if MPI version */
11718     if (ReassembleMoveInfo() == ERROR)
11719         return (ERROR);
11720     if (chainParams.numChains > 1 && ReassembleSwapInfo() == ERROR)
11721         return (ERROR);
11722     if (proc_id != 0)
11723         return (NO_ERROR);
11724 #endif
11725
11726     MrBayesPrintf (fpMcmc, "%d", curGen);
11727
11728     for (n=0; n<chainParams.numRuns; n++)
11729         {
11730         if (chainParams.allChains == YES)
11731             {
11732             for (j=n*chainParams.numChains; j<(n+1)*chainParams.numChains; j++)
11733                 {
11734                 for (i=0; i<numUsedMoves; i++)
11735                     {
11736                     theMove = usedMoves[i];
11737                     if (theMove->nBatches[j] < 1)
11738                         MrBayesPrintf (fpMcmc, "\tNA");
11739                     else
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]);
11743                     }
11744                 }
11745             }
11746         else
11747             {
11748             j = n*chainParams.numChains;
11749             for (i=0; i<numUsedMoves; i++)
11750                 {
11751                 theMove = usedMoves[i];
11752                 if (theMove->nBatches[j] < 1)
11753                     MrBayesPrintf (fpMcmc, "\tNA");
11754                 else
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]);
11758                 }
11759             }
11760         if (chainParams.numChains > 1)
11761             {
11762             for (i=0; i<chainParams.numChains; i++)
11763                 {
11764                 for (j=i+1; j<chainParams.numChains; j++)
11765                     {
11766                     MrBayesPrintf (fpMcmc, "\t%.6f", (MrBFlt) swapInfo[n][i][j] / (MrBFlt) swapInfo[n][j][i]);
11767                     }
11768                 }
11769             }
11770         }
11771
11772     if (chainParams.numRuns > 1)
11773         {
11774         for (n=0; n<numTopologies; n++)
11775             {
11776             if (chainParams.relativeBurnin == NO && curGen < chainParams.chainBurnIn * chainParams.sampleFreq)
11777                 MrBayesPrintf (fpMcmc, "\tNA");
11778             else
11779                 {
11780                 if (chainParams.diagnStat == AVGSTDDEV)
11781                     MrBayesPrintf (fpMcmc, "\t%.6f", chainParams.stat[n].avgStdDev);
11782                 else
11783                     MrBayesPrintf (fpMcmc, "\t%.6f", chainParams.stat[n].max);
11784                 }
11785             if (chainParams.allComps == YES)
11786                 {
11787                 for (i=0; i<chainParams.numRuns; i++)
11788                     {
11789                     for (j=i+1; j<chainParams.numRuns; j++)
11790                         {
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]);
11797                         }
11798                     }
11799                 }
11800             }
11801         }
11802
11803     MrBayesPrintf (fpMcmc, "\n");
11804     fflush (fpMcmc);
11805
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();
11810 #endif
11811
11812     return (NO_ERROR);
11813 }
11814
11815
11816 /*-----------------------------------------------------------------------
11817 |
11818 |   PrintMPISlaves: Print strings from MPI slave nodes
11819 |
11820 ------------------------------------------------------------------------*/
11821 #if defined (MPI_ENABLED)
11822 int PrintMPISlaves (FILE *fp)
11823 {
11824     char        *s=NULL;
11825     int         i, len, ierror, nErrors, sumErrors, tag;
11826     MPI_Status  status;
11827
11828     nErrors = sumErrors = tag = 0;
11829     if (proc_id==0)
11830         {
11831         s = (char *) SafeCalloc (100, sizeof(char));
11832         // if (s!=NULL)
11833         //    lenS = 100;
11834         // else
11835         //    lenS = 0;
11836         }
11837
11838     for (i=1; i<num_procs; i++)
11839         {
11840         /* communicate length */
11841         if (proc_id == 0)
11842             {
11843             /* receive size */
11844             ierror = MPI_Recv (&len, 1, MPI_INT, i, tag, MPI_COMM_WORLD, &status);
11845             if (ierror != MPI_SUCCESS)
11846                 {
11847                 MrBayesPrint ("%s   Problem receiving string length from proc_id = %d\n", spacer, i);
11848                 nErrors++;
11849                 }
11850             }
11851         else if (proc_id == i)
11852             {
11853             /* send size */
11854             len = (int)strlen(printString);
11855             ierror = MPI_Send (&len, 1, MPI_INT, 0, tag, MPI_COMM_WORLD);
11856             if (ierror != MPI_SUCCESS)
11857                 {
11858                 MrBayesPrint ("%s   Problem sending string length from proc_id = %d\n", spacer, i);
11859                 nErrors++;
11860                 }
11861             }
11862         /* reallocate string s on processor 0 if necessary */
11863         if (nErrors == 0 && proc_id == 0 && len+5 > strlen(s))
11864             {
11865             if ((s = (char *) SafeRealloc ((void *)s, ((size_t)len+5)*sizeof(char))) == NULL)
11866                 {
11867                 MrBayesPrint ("%s   Problem reallocating %d chars to string 's' on proc 0 in PrintMPISlaves()\n", spacer, len+5);
11868                 nErrors++;
11869                 }
11870             }
11871         /* communicate and print string */
11872         if (nErrors == 0)
11873             {
11874             if (proc_id == 0)
11875                 {
11876                 /* receive string */
11877                 ierror = MPI_Recv (s, len+1, MPI_CHAR, i, tag, MPI_COMM_WORLD, &status);
11878                 if (ierror != MPI_SUCCESS)
11879                     {
11880                     MrBayesPrint ("%s   Problem receiving printString from proc_id = %d\n", spacer, i);
11881                     nErrors++;
11882                     }
11883                 /* print string */
11884                 if (nErrors == 0)
11885                     MrBayesPrintf (fp, "%s", s);
11886                 }
11887             else if (proc_id == i)
11888                 {
11889                 /* send string */
11890                 ierror = MPI_Send (printString, len+1, MPI_CHAR, 0, tag, MPI_COMM_WORLD);
11891                 if (ierror != MPI_SUCCESS)
11892                     {
11893                     MrBayesPrint ("%s   Problem sending printString from proc_id = %d\n", spacer, i);
11894                     nErrors++;
11895                     }
11896                 }
11897             }
11898         if (nErrors > 0)
11899             break;
11900         }
11901
11902     if (proc_id == 0)
11903         {
11904         free (s);
11905         s = NULL;
11906         }
11907
11908     MPI_Allreduce (&nErrors, &sumErrors, 1, MPI_INT, MPI_SUM, MPI_COMM_WORLD);
11909     if (sumErrors > 0)
11910         {
11911         MrBayesPrint ("%s   Problem with the printing in PrintMPISlaves().\n", spacer);
11912         return (ERROR);
11913         }
11914
11915     return (NO_ERROR);
11916 }
11917 #endif
11918
11919
11920 /*----------------------------------------------------------------------
11921 |
11922 |   PrintParamValues: print parameter values and subvalues for param
11923 |
11924 ----------------------------------------------------------------------*/
11925 void PrintParamValues (Param *p, int chain, char *s)
11926 {
11927     int         j;
11928     MrBFlt      *value0, *value1;
11929     
11930     if (p == NULL)
11931         MrBayesPrint ("%s   %s = NULL\n", spacer, s);
11932     else
11933         {
11934         if (p->nValues > 0)
11935             {
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]);
11940             }
11941         if (p->nSubValues > 0)
11942             {
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]);
11947             }
11948         }
11949     MrBayesPrint ("\n\n");
11950
11951     return;
11952 }
11953
11954
11955 /*----------------------------------------------------------------------
11956 |
11957 |   PrintParsMatrix: Print parsimony (bitset) matrix
11958 |       using hexadecimal representation
11959 |
11960 |
11961 ------------------------------------------------------------------------*/
11962 int PrintParsMatrix (void)
11963 {
11964     int             i, j=0, k, c, d, printWidth, nextColumn, nChars, inputChar;
11965     BitsLong        x, y, bitsLongOne;
11966     char            ch;
11967     ModelInfo       *m;
11968
11969     bitsLongOne = 1;
11970
11971     printWidth = 79;
11972
11973     for (d=0; d<numCurrentDivisions; d++)
11974         {
11975         MrBayesPrint ("\nParsimony (bitset) matrix for division %d\n\n", d+1);
11976
11977         m = &modelSettings[d];
11978
11979         nChars = 1 + (int) (log((bitsLongOne << m->numStates) - 1) / log(16));
11980     
11981         for (c=0; c<m->numChars; c++)
11982             {
11983             MrBayesPrint ("Parsimony sets for character %d -- \n", (c / m->nParsIntsPerSite));
11984             for (i=0; i<numTaxa; i++)
11985                 {
11986                 MrBayesPrint ("%-10.10s   ", taxaNames[i]);
11987                 j = c*m->nParsIntsPerSite;
11988                 for (nextColumn=13; nextColumn < printWidth; nextColumn+=nChars + 1)
11989                     {
11990                     if (j >= m->numChars*m->nParsIntsPerSite)
11991                         break;
11992                     x = m->parsSets[i][j];
11993                     for (k=8 - nChars; k<8; k++)
11994                         {
11995                         y = (x >> (4* (7 - k))) & 15;
11996                         // if (y > 16) printf ("y is too big %ld\n",y);
11997                         if (y < 10)
11998                             ch = (char) y + '0';
11999                         else
12000                             ch = (char) y - 10 + 'A';
12001                         MrBayesPrint("%c", ch);
12002                         }
12003                     MrBayesPrint(" ");
12004                     j++;
12005                     }
12006                 MrBayesPrint ("\n");
12007                 }
12008             MrBayesPrint("\n");
12009             printf ("Do you want to stop (y/n)?\n");
12010             inputChar = getchar();
12011             if (inputChar == 'y' || inputChar == 'Y')
12012                 return NO_ERROR;
12013             else
12014                 MrBayesPrint ("\n");
12015             }
12016         }   /* next division */
12017
12018     return NO_ERROR;
12019 }
12020
12021
12022 /*------------------------------------------------------------------
12023 |
12024 |   PrintSiteRates_Gen: general n-state models with rate variation
12025 |
12026 -------------------------------------------------------------------*/
12027 int PrintSiteRates_Gen (TreeNode *p, int division, int chain)
12028 {
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;
12034     char            *tempStr;
12035     int             tempStrSize = TEMPSTRSIZE;
12036     ModelInfo       *m;
12037     
12038     tempStr = (char *) SafeMalloc((size_t)tempStrSize * sizeof(char));
12039     if (!tempStr)
12040         {
12041         MrBayesPrint ("%s   Problem allocating tempString (%d)\n", spacer, tempStrSize * sizeof(char));
12042         return (ERROR);
12043         }
12044
12045     /* find model settings and nStates, pInvar, invar cond likes */
12046     m = &modelSettings[division];
12047     nStates = m->numModelStates;
12048     if (m->pInvar == NULL)
12049         {
12050         hasPInvar = NO;
12051         }
12052     else
12053         {
12054         hasPInvar = YES;
12055         pInvar =  *(GetParamVals (m->pInvar, chain, state[chain]));
12056         clInvar = m->invCondLikes;
12057         }
12058
12059     /* find conditional likelihood pointer */
12060     clP = m->condLikes[m->condLikeIndex[chain][p->index]];
12061     
12062     /* use scratch space for root node for temporary calculations */
12063     siteRates = m->condLikes[m->condLikeScratchIndex[p->index]];
12064     
12065     /* find site scaler */
12066     lnScaler = m->scalers[m->siteScalerIndex[chain]];
12067     
12068     /* find base frequencies */
12069     bs = GetParamSubVals (m->stateFreq, chain, state[chain]);
12070
12071     /* if covarion model, adjust base frequencies */
12072     if (m->switchRates != NULL)
12073         {
12074         /* find the stationary frequencies */
12075         swr = GetParamVals(m->switchRates, chain, state[chain]);
12076         s01 = swr[0];
12077         s10 = swr[1];
12078         probOn = s01 / (s01 + s10);
12079         probOff = 1.0 - probOn;
12080
12081         /* now adjust the base frequencies; on-state stored first in cond likes */
12082         for (j=0; j<nStates/2; j++)
12083             {
12084             covBF[j] = bs[j] * probOn;
12085             covBF[j+nStates/2] = bs[j] * probOff;
12086             }
12087
12088         /* finally set bs pointer to adjusted values */
12089         bs = covBF;
12090         }
12091
12092     /* find category frequencies */
12093     if (hasPInvar == NO)
12094         freq = 1.0 /  m->numGammaCats;
12095     else
12096         freq = (1.0 - pInvar) /  m->numGammaCats;
12097
12098     /* get rate multipliers (for gamma & partition specific rates) */
12099     baseRate = GetRate (division, chain);
12100     
12101     /* compensate for invariable sites */
12102     if (hasPInvar == YES)
12103         baseRate /= (1.0 - pInvar);
12104         
12105     /* get category rates */
12106     catRate = GetParamSubVals (m->shape, chain, state[chain]);
12107
12108     /* loop over characters */
12109     if (hasPInvar == NO)
12110         {
12111         /* no invariable category */
12112         for (c=0; c<m->numChars; c++)
12113             {
12114             siteLike = 0.0;
12115             siteRates[c] = 0.0;
12116             for (k=0; k<m->numGammaCats; k++)
12117                 {
12118                 catLike = 0.0;
12119                 for (j=0; j<nStates; j++)
12120                     catLike += (*(clP++)) * bs[j];
12121                 siteRates[c] += (CLFlt) (catLike * catRate[k]);
12122                 siteLike += catLike;
12123                 }
12124             siteRates[c] *= (CLFlt) (baseRate / siteLike);  /* category frequencies and site scaler cancel out */
12125             }
12126         }
12127     else
12128         {
12129         /* has invariable category */
12130         for (c=0; c<m->numChars; c++)
12131             {
12132             siteLike = invLike = 0.0;
12133             siteRates[c] = 0.0;
12134             for (k=0; k<m->numGammaCats; k++)
12135                 {
12136                 catLike = 0.0;
12137                 for (j=0; j<nStates; j++)
12138                     catLike += (*(clP++)) * bs[j];
12139                 siteRates[c] += (CLFlt) (catLike * catRate[k]);
12140                 siteLike += catLike;
12141                 }
12142             siteLike *= freq;
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 */
12149             }
12150         }
12151         
12152     /* print the resulting site rates cycling over uncompressed chars */
12153     for (c=0; c<numChar; c++)
12154         {
12155         if (charInfo[c].isExcluded == YES || partitionId[c][partitionNum] != division+1)
12156             continue;
12157         j = compCharPos[c] - m->compCharStart;
12158         SafeSprintf (&tempStr, &tempStrSize, "\t%s", MbPrintNum(siteRates[j]));
12159         if (AddToPrintString (tempStr) == ERROR) return (ERROR);
12160         }
12161
12162     free (tempStr);
12163     return NO_ERROR;
12164 }
12165
12166
12167 /*------------------------------------------------------------------
12168 |
12169 |   PrintSiteRates_Std: standard model with rate variation
12170 |
12171 -------------------------------------------------------------------*/
12172 int PrintSiteRates_Std (TreeNode *p, int division, int chain)
12173 {
12174     int             c, j, k, nStates;
12175     MrBFlt          siteLike, catLike, *bs, *catRate, baseRate;
12176     CLFlt           *clP, *siteRates;
12177     char            *tempStr;
12178     int             tempStrSize = TEMPSTRSIZE;
12179     ModelInfo       *m;
12180     
12181     tempStr = (char *) SafeMalloc((size_t)tempStrSize * sizeof(char));
12182     if (!tempStr)
12183         {
12184         MrBayesPrint ("%s   Problem allocating tempString (%d)\n", spacer, tempStrSize * sizeof(char));
12185         return (ERROR);
12186         }
12187
12188     /* find model settings */
12189     m = &modelSettings[division];
12190
12191     /* find conditional likelihood pointer */
12192     clP = m->condLikes[m->condLikeIndex[chain][p->index]];
12193     
12194     /* use scratch space for root node for temporary calculations */
12195     siteRates = m->condLikes[m->condLikeScratchIndex[p->index]];
12196     
12197     /* find base frequencies */
12198     bs = GetParamStdStateFreqs (m->stateFreq, chain, state[chain]);
12199
12200     /* get rate multiplier */
12201     baseRate = GetRate (division, chain);
12202     
12203     /* get category rates */
12204     catRate = GetParamSubVals (m->shape, chain, state[chain]);
12205
12206     /* loop over characters */
12207     for (c=0; c<m->numChars; c++)
12208         {
12209         siteLike = 0.0;
12210         siteRates[c] = 0.0;
12211         nStates = m->nStates[c];
12212         for (k=0; k<m->numGammaCats; k++)
12213             {
12214             catLike = 0.0;
12215             for (j=0; j<nStates; j++)
12216                 catLike += (*(clP++)) * bs[j];
12217             siteRates[c] += (CLFlt) (catLike * catRate[k]);
12218             siteLike += catLike;
12219             }
12220         siteRates[c] *= (CLFlt)(baseRate / siteLike);   /* category frequencies and site scaler cancel out */
12221         }
12222         
12223     /* print the resulting site rates cycling over uncompressed chars */
12224     for (c=0; c<numChar; c++)
12225         {
12226         if (charInfo[c].isExcluded == YES || partitionId[c][partitionNum] != division+1)
12227             continue;
12228         j = compCharPos[c] - m->compCharStart;
12229         SafeSprintf (&tempStr, &tempStrSize, "\t%s", MbPrintNum(siteRates[j]));
12230         if (AddToPrintString (tempStr) == ERROR) return (ERROR);
12231         }
12232
12233     free (tempStr);
12234     return NO_ERROR;
12235 }
12236
12237
12238 int PrintStates (int curGen, int coldId)
12239 {
12240     int             d, i, j, k, k1, compressedCharPosition, *printedChar=NULL, origAlignmentChars[3];
12241     char            *partString=NULL, stateString[4];
12242     MrBFlt          *st, *sst, sum;
12243     Param           *p;
12244     ModelInfo       *m;
12245     Tree            *tree;
12246     TreeNode        *node;
12247     ModelParams     *mp;
12248     char            *tempStr;
12249     int             tempStrSize;
12250
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));
12255
12256     if (!printString)
12257         {
12258         MrBayesPrint ("%s   Problem allocating printString (%d)\n", spacer, printStringSize * sizeof(char));
12259         goto errorExit;
12260         }
12261     if (!tempStr)
12262         {
12263         MrBayesPrint ("%s   Problem allocating tempString (%d)\n", spacer, tempStrSize * sizeof(char));
12264         goto errorExit;
12265         }
12266     
12267     *printString = '\0';
12268     *tempStr = '\0';
12269
12270     /* Allocate memory, temporarily, in case we infer positive selection probs, site omegas, or site rates */
12271     if (inferPosSel == YES || inferSiteOmegas == YES)
12272         {
12273         if (memAllocs[ALLOC_POSSELPROBS] == YES)
12274             {
12275             MrBayesPrint ("%s   posSelProbs not free in PrintStates\n", spacer);
12276             goto errorExit;
12277             }
12278         posSelProbs = (MrBFlt *)SafeMalloc((size_t)numCompressedChars * sizeof(MrBFlt));
12279         if (!posSelProbs)
12280             {
12281             MrBayesPrint ("%s   Problem allocating posSelProbs (%d)\n", spacer, numCompressedChars * sizeof(MrBFlt));
12282             goto errorExit;
12283             }
12284         for (i=0; i<numCompressedChars; i++)
12285             posSelProbs[i] =  -10.0;
12286         memAllocs[ALLOC_POSSELPROBS] = YES;
12287         }
12288     if (inferPosSel == YES || inferSiteOmegas == YES || inferSiteRates == YES || inferAncStates == YES)
12289         {
12290         printedChar = (int *)SafeMalloc((size_t)numChar * sizeof(int));
12291         if (!printedChar)
12292             {
12293             MrBayesPrint ("%s   Problem allocating printedChar (%d)\n", spacer, numChar * sizeof(int));
12294             goto errorExit;
12295             }
12296         for (i=0; i<numChar; i++)
12297             printedChar[i] = NO;
12298         }
12299
12300     /* Set up the header to the file. */
12301     if (curGen == 0)
12302         {
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;
12311
12312         for (i=0; i<numParams; i++)
12313             {
12314             p = &params[i];
12315             if (p->paramType == P_BRLENS)
12316                 {
12317                 /* print tree lengths or heights for all trees */
12318                 tree = GetTree (p, coldId, state[coldId]);
12319                 if (tree->isRooted == YES)
12320                     {
12321                     if (FillRelPartsString(p, &partString) == YES)
12322                         SafeSprintf (&tempStr, &tempStrSize, "\tTH%s\tTL%s", partString, partString);
12323                     else
12324                         SafeSprintf (&tempStr, &tempStrSize, "\tTH\tTL");
12325                     if (AddToPrintString (tempStr) == ERROR) goto errorExit;
12326                     }
12327                 else
12328                     {
12329                     if (FillRelPartsString(p, &partString) == YES)
12330                         SafeSprintf (&tempStr, &tempStrSize, "\tTL%s", partString);
12331                     else
12332                         SafeSprintf (&tempStr, &tempStrSize, "\tTL");
12333                     if (AddToPrintString (tempStr) == ERROR) goto errorExit;
12334                     }
12335                 /* print # cpp events, or relaxed clock model indicator */
12336                 for (j=0; j<p->nSubParams; j++)
12337                     {
12338                     if (p->subParams[j]->paramType == P_CPPEVENTS)
12339                         {
12340                         if (FillRelPartsString(p->subParams[j], &partString) == YES)
12341                             SafeSprintf (&tempStr, &tempStrSize, "\tn_CPP%s", partString);
12342                         else
12343                             SafeSprintf (&tempStr, &tempStrSize, "\tn_CPP");
12344                         if (AddToPrintString (tempStr) == ERROR) goto errorExit;
12345                         }
12346                     else if (p->subParams[j]->paramType == P_MIXEDBRCHRATES)
12347                         {
12348                         if (FillRelPartsString(p->subParams[j], &partString) == YES)
12349                             SafeSprintf (&tempStr, &tempStrSize, "\tm_RCl%s", partString);
12350                         else
12351                             SafeSprintf (&tempStr, &tempStrSize, "\tm_RCl");
12352                         if (AddToPrintString (tempStr) == ERROR) goto errorExit;
12353                         }
12354                     }
12355                 }
12356             /* print proportion of ancestral fossils */
12357             else if (p->paramType == P_FOSLRATE)
12358                 {
12359                 if (FillRelPartsString(p, &partString) == YES)
12360                     {
12361                     SafeSprintf (&tempStr, &tempStrSize, "\tprop_ancfossil%s", partString);
12362                     if (AddToPrintString (tempStr) == ERROR) goto errorExit;
12363                     }
12364                 else
12365                     {
12366                     SafeSprintf (&tempStr, &tempStrSize, "\tprop_ancfossil");
12367                     if (AddToPrintString (tempStr) == ERROR) goto errorExit;
12368                     }
12369                 }
12370             }
12371
12372         /* print ordinary parameters header */
12373         for (i=0; i<numPrintParams; i++)
12374             {
12375             p = printParam[i];
12376             SafeSprintf (&tempStr, &tempStrSize, "\t%s", p->paramHeader);
12377             if (AddToPrintString (tempStr) == ERROR) goto errorExit;
12378             }
12379             
12380         /* print substitution model parameters header */
12381         if (inferSiteRates == YES)
12382             {
12383             for (i=0; i<numChar; i++)
12384                 printedChar[i] = NO;
12385     
12386             for (i=0; i<numChar; i++)
12387                 { 
12388                 if (charInfo[i].isExcluded == YES)
12389                     continue;
12390                 if (printedChar[i] == YES)
12391                     continue;
12392                 d = partitionId[i][partitionNum] - 1;
12393                 m = &modelSettings[d];
12394                 mp = &modelParams[d];
12395                 if (m->printSiteRates == YES)
12396                     {
12397                     if (m->nCharsPerSite == 1)
12398                         {
12399                         SafeSprintf (&tempStr, &tempStrSize, "\tr(%d)", i+1);
12400                         if (AddToPrintString (tempStr) == ERROR) goto errorExit;
12401                         }
12402                     else
12403                         {
12404                         origAlignmentChars[0] = i;
12405                         k = 1;
12406                         for (j=i+1; j<numChar; j++)
12407                             {
12408                             if (compCharPos[i] == compCharPos[j])
12409                                 {
12410                                 if (k > m->nCharsPerSite)
12411                                     return (ERROR);
12412                                 origAlignmentChars[k++] = j;
12413                                 printedChar[j] = YES;
12414                                 }
12415                             }
12416                         if (k != m->nCharsPerSite)
12417                             return (ERROR);
12418                         SafeSprintf (&tempStr, &tempStrSize, "\tr(%d,", origAlignmentChars[0]);
12419                         if (AddToPrintString (tempStr) == ERROR) goto errorExit;
12420                         for (j=1; j<k-1; j++)
12421                             {
12422                             SafeSprintf (&tempStr, &tempStrSize, "%d,", origAlignmentChars[j]);
12423                             if (AddToPrintString (tempStr) == ERROR) goto errorExit;
12424                             }
12425                         SafeSprintf (&tempStr, &tempStrSize, "%d)", origAlignmentChars[k-1]);
12426                         if (AddToPrintString (tempStr) == ERROR) goto errorExit;
12427                         }
12428                     }
12429                 }
12430             }
12431
12432         if (inferPosSel == YES)
12433             {
12434             for (i=0; i<numChar; i++)
12435                 printedChar[i] = NO;
12436             for (d=0; d<numCurrentDivisions; d++)
12437                 {
12438                 m = &modelSettings[d];
12439                 tree = GetTree(m->brlens, coldId, state[coldId]);
12440                 if (m->printPosSel == YES)
12441                     {
12442                     if (m->PosSelProbs (tree->root->left, d, coldId) == ERROR)
12443                         goto errorExit;
12444                     }
12445                 }
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++)
12449                 {
12450                 compressedCharPosition = compCharPos[i];
12451                 if (!(posSelProbs[compressedCharPosition] < 0.0) && printedChar[i] == NO && charInfo[i].isExcluded == NO)
12452                     {
12453                     for (j=k=0; j<numChar; j++)
12454                         {
12455                         if (charInfo[j].charId == charInfo[i].charId)
12456                             {
12457                             origAlignmentChars[k++] = j;
12458                             printedChar[j] = YES;
12459                             }
12460                         }
12461                     SafeSprintf (&tempStr, &tempStrSize, "\tpr+(%d,%d,%d)", origAlignmentChars[0]+1, origAlignmentChars[1]+1, origAlignmentChars[2]+1);
12462                     if (AddToPrintString (tempStr) == ERROR) goto errorExit;
12463                     }
12464                 }   
12465             for (i=0; i<numChar; i++)
12466                 printedChar[i] = NO;
12467             }
12468             
12469         if (inferSiteOmegas == YES)
12470             {
12471             for (i=0; i<numChar; i++)
12472                 printedChar[i] = NO;
12473             for (d=0; d<numCurrentDivisions; d++)
12474                 {
12475                 m = &modelSettings[d];
12476                 tree = GetTree(m->brlens, coldId, state[coldId]);
12477                 if (m->printSiteOmegas == YES)
12478                     {
12479                     if (m->SiteOmegas (tree->root->left, d, coldId) == ERROR)
12480                         goto errorExit;
12481                     }
12482                 }
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++)
12486                 {
12487                 compressedCharPosition = compCharPos[i];
12488                 if (posSelProbs[compressedCharPosition] >= 0.0 && printedChar[i] == NO && charInfo[i].isExcluded == NO)
12489                     {
12490                     for (j=k=0; j<numChar; j++)
12491                         {
12492                         if (charInfo[j].charId == charInfo[i].charId)
12493                             {
12494                             origAlignmentChars[k++] = j;
12495                             printedChar[j] = YES;
12496                             }
12497                         }
12498                     SafeSprintf (&tempStr, &tempStrSize, "\tomega(%d,%d,%d)", origAlignmentChars[0]+1, origAlignmentChars[1]+1, origAlignmentChars[2]+1);
12499                     if (AddToPrintString (tempStr) == ERROR) goto errorExit;
12500                     }
12501                 }   
12502             for (i=0; i<numChar; i++)
12503                 printedChar[i] = NO;
12504             }
12505             
12506         if (inferAncStates == YES)
12507             {
12508             for (j=0; j<numChar; j++)
12509                 printedChar[j] = NO;
12510             for (d=0; d<numCurrentDivisions; d++)
12511                 {
12512                 m = &modelSettings[d];
12513                 mp = &modelParams[d];
12514                 if (m->printAncStates != YES)
12515                     continue;
12516                 for (i=0; i<numDefinedConstraints; i++)
12517                     {
12518                     if (mp->activeConstraints[i] == NO || definedConstraintsType[i] != HARD)
12519                         continue;
12520                     for (j=0; j<numChar; j++)
12521                         {
12522                         if (partitionId[j][partitionNum] - 1 != d || charInfo[j].isExcluded == YES || printedChar[j] == YES)
12523                             continue;
12524                         if (mp->dataType == STANDARD)
12525                             {
12526                             for (k=0; k<m->nStates[compCharPos[j] - m->compCharStart]; k++)
12527                                 {
12528                                 SafeSprintf (&tempStr, &tempStrSize, "\tp(%c){%d@%s}", m->StateCode(k), j+1, constraintNames[i]);
12529                                 if (AddToPrintString (tempStr) == ERROR) goto errorExit;
12530                                 }
12531                             }
12532                         else if ((mp->dataType == DNA || mp->dataType == RNA) && !strcmp(mp->nucModel,"Codon"))
12533                             {
12534                             origAlignmentChars[0] = j+1;
12535                             k1 = 1;
12536                             for (k=j+1; k<numChar; k++)
12537                                 {
12538                                 if (charInfo[k].charId == charInfo[j].charId)
12539                                     {
12540                                     origAlignmentChars[k1++] = k+1;
12541                                     printedChar[k] = YES;
12542                                     }
12543                                 }
12544                             for (k=0; k<m->numStates; k++)
12545                                 {
12546                                 State_CODON(stateString, k, d);
12547                                 SafeSprintf (&tempStr, &tempStrSize, "\tp(%s){%d,%d,%d@%s}",
12548                                     stateString,
12549                                     origAlignmentChars[0],
12550                                     origAlignmentChars[1],
12551                                     origAlignmentChars[2],
12552                                     constraintNames[i]);
12553                                 if (AddToPrintString (tempStr) == ERROR) goto errorExit;
12554                                 }
12555                             }
12556                         else if ((mp->dataType == DNA || mp->dataType == RNA) && !strcmp(mp->nucModel,"Doublet"))
12557                             {
12558                             origAlignmentChars[0] = j+1;
12559                             k1 = 1;
12560                             for (k=j+1; k<numChar; k++)
12561                                 {
12562                                 if (charInfo[k].charId == charInfo[j].charId)
12563                                     {
12564                                     origAlignmentChars[k1++] = k+1;
12565                                     printedChar[k] = YES;
12566                                     }
12567                                 }
12568                             for (k=0; k<m->numStates; k++)
12569                                 {
12570                                 State_DOUBLET(stateString, k);
12571                                 SafeSprintf (&tempStr, &tempStrSize, "\tp(%s){%d,%d@%s}",
12572                                     stateString,
12573                                     origAlignmentChars[0],
12574                                     origAlignmentChars[1],
12575                                     constraintNames[i]);
12576                                 if (AddToPrintString (tempStr) == ERROR) goto errorExit;
12577                                 }
12578                             }
12579                         else if ((mp->dataType == DNA || mp->dataType == RNA) && !strcmp(mp->nucModel,"Protein"))
12580                             {
12581                             origAlignmentChars[0] = j+1;
12582                             k1 = 1;
12583                             for (k=j+1; k<numChar; k++)
12584                                 {
12585                                 if (charInfo[k].charId == charInfo[j].charId)
12586                                     {
12587                                     origAlignmentChars[k1++] = k+1;
12588                                     printedChar[k] = YES;
12589                                     }
12590                                 }
12591                             for (k=0; k<m->numStates; k++)
12592                                 {
12593                                 SafeSprintf (&tempStr, &tempStrSize, "\tp(%c){%d,%d,%d@%s}",
12594                                     m->StateCode(k),
12595                                     origAlignmentChars[0],
12596                                     origAlignmentChars[1],
12597                                     origAlignmentChars[2],
12598                                     constraintNames[i]);
12599                                 if (AddToPrintString (tempStr) == ERROR) goto errorExit;
12600                                 }
12601                             }
12602                         else
12603                             {
12604                             for (k=0; k<m->numStates; k++)
12605                                 {
12606                                 SafeSprintf (&tempStr, &tempStrSize, "\tp(%c){%d@%s}", m->StateCode(k), j+1, constraintNames[i]);
12607                                 if (AddToPrintString (tempStr) == ERROR) goto errorExit;
12608                                 }
12609                             }
12610                         }
12611                     }
12612                 }
12613             }
12614             
12615         SafeSprintf (&tempStr, &tempStrSize, "\n");
12616         if (AddToPrintString (tempStr) == ERROR) goto errorExit;
12617         }
12618         
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;
12626
12627     for (i=0; i<numParams; i++)
12628         {
12629         p = &params[i];
12630         if (p->paramType == P_BRLENS)
12631             {
12632             /* print tree lengths or heights for all trees */
12633             tree = GetTree (p, coldId, state[coldId]);
12634             if (tree->isRooted == NO)
12635                 {
12636                 SafeSprintf (&tempStr, &tempStrSize, "\t%s", MbPrintNum(TreeLength(p, coldId)));
12637                 if (AddToPrintString (tempStr) == ERROR) goto errorExit;
12638                 }
12639             else
12640                 {
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;
12645                 }
12646             /* print # cpp events, or relaxed clock model indicator */
12647             for (j=0; j<p->nSubParams; j++)
12648                 {
12649                 if (p->subParams[j]->paramType == P_CPPEVENTS)
12650                     {
12651                     SafeSprintf (&tempStr, &tempStrSize, "\t%d", NumCppEvents(p->subParams[j],coldId));
12652                     if (AddToPrintString (tempStr) == ERROR) goto errorExit;
12653                     }
12654                 else if (p->subParams[j]->paramType == P_MIXEDBRCHRATES)
12655                     {
12656                     SafeSprintf (&tempStr, &tempStrSize, "\t%d", *GetParamIntVals(p->subParams[j],coldId,state[coldId]));
12657                     if (AddToPrintString (tempStr) == ERROR) goto errorExit;
12658                     }
12659                 }
12660             }
12661         else if (p->paramType == P_FOSLRATE)
12662             {
12663             /* print proportion of ancestral fossils */
12664             SafeSprintf (&tempStr, &tempStrSize, "\t%s", MbPrintNum(PropAncFossil(p, coldId)));
12665             if (AddToPrintString (tempStr) == ERROR) goto errorExit;
12666             }
12667         }
12668
12669     /* print ordinary parameters */
12670     for (i=0; i<numPrintParams; i++)
12671         {
12672         p = printParam[i];
12673
12674         /* get model params and settings */
12675         mp = &modelParams[p->relParts[0]];
12676         m  = &modelSettings[p->relParts[0]];
12677         
12678         st  = GetParamVals (p, coldId, state[coldId]);
12679         sst = GetParamSubVals (p, coldId, state[coldId]);
12680
12681         if (p->paramId == SYMPI_EXP_MS || p->paramId == SYMPI_UNI_MS || p->paramId == SYMPI_FIX_MS)
12682             {
12683             /* We print symmetric dirichlet alpha value if not fixed and then multistate character state frequencies */
12684             if (p->paramId != SYMPI_FIX_MS)
12685                 {
12686                 SafeSprintf (&tempStr, &tempStrSize, "\t%s", MbPrintNum(st[0]));
12687                 if (AddToPrintString (tempStr) == ERROR) goto errorExit;
12688                 }
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++)
12693                 {
12694                 for (k=0; k<p->sympinStates[j]; k++)
12695                     {
12696                     SafeSprintf (&tempStr, &tempStrSize, "\t%s", MbPrintNum(*sst++));
12697                     if (AddToPrintString (tempStr) == ERROR) goto errorExit;
12698                     }
12699                 }
12700             }
12701         else if (p->paramType == P_PI)
12702             {
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++)
12705                 {
12706                 SafeSprintf (&tempStr, &tempStrSize, "\t%s", MbPrintNum(sst[j]));
12707                 if (AddToPrintString (tempStr) == ERROR) goto errorExit;
12708                 }
12709             }
12710         else if (p->paramType == P_TRATIO && !strcmp(mp->tratioFormat,"Dirichlet"))
12711             {
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;
12716             }
12717         else if (p->paramType == P_REVMAT)
12718             {
12719             if (!strcmp(mp->revmatFormat,"Ratio"))
12720                 {
12721                 sum = st[p->nValues-1];
12722                 for (j=0; j<p->nValues; j++)
12723                     {
12724                     SafeSprintf (&tempStr, &tempStrSize, "\t%s", MbPrintNum(st[j] / sum));
12725                     if (AddToPrintString (tempStr) == ERROR) goto errorExit;
12726                     }
12727                 }
12728             else
12729                 {
12730                 /* we already have rate proportions */
12731                 for (j=0; j<p->nValues; j++)
12732                     {
12733                     SafeSprintf (&tempStr, &tempStrSize, "\t%s", MbPrintNum(st[j]));
12734                     if (AddToPrintString (tempStr) == ERROR) goto errorExit;
12735                     }
12736                 }
12737             if (p->paramId == REVMAT_MIX)
12738                 {
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;
12744                 }
12745             }
12746         else if (p->paramType == P_RATEMULT)
12747             {
12748             if (!strcmp(mp->ratemultFormat,"Ratio"))
12749                 {
12750                 for (j=0; j<p->nValues; j++)
12751                     {
12752                     SafeSprintf (&tempStr, &tempStrSize, "\t%s", MbPrintNum(st[j] / st[0]));
12753                     if (AddToPrintString (tempStr) == ERROR) goto errorExit;
12754                     }
12755                 }
12756             else if (!strcmp(mp->ratemultFormat, "Dirichlet"))
12757                 {
12758                 sum = 0.0;
12759                 for (j=0; j<p->nValues; j++)
12760                     sum += st[j];
12761                 for (j=0; j<p->nValues; j++)
12762                     {
12763                     SafeSprintf (&tempStr, &tempStrSize, "\t%s", MbPrintNum(st[j] / sum));
12764                     if (AddToPrintString (tempStr) == ERROR) goto errorExit;
12765                     }
12766                 }
12767             else
12768                 {
12769                 for (j=0; j<p->nValues; j++)
12770                     {
12771                     SafeSprintf (&tempStr, &tempStrSize, "\t%s", MbPrintNum(st[j]));
12772                     if (AddToPrintString (tempStr) == ERROR) goto errorExit;
12773                     }
12774                 }
12775             }
12776         else if (p->paramType == P_AAMODEL)
12777             {
12778             for (j=0; j<p->nValues; j++)
12779                 {
12780                 SafeSprintf (&tempStr, &tempStrSize, "\t%d", (int)st[j]);
12781                 if (AddToPrintString (tempStr) == ERROR) goto errorExit;
12782                 }
12783             }
12784         else
12785             {
12786             /* run of the mill parameter */
12787             for (j=0; j<p->nValues; j++)
12788                 {
12789                 SafeSprintf (&tempStr, &tempStrSize, "\t%s", MbPrintNum(st[j]));
12790                 if (AddToPrintString (tempStr) == ERROR) goto errorExit;
12791                 }
12792             }
12793
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)
12795             {
12796             /* OK, we also need to print subvalues for the category frequencies in a NY98-like model. */
12797             if (!strcmp(mp->omegaVar, "M10"))
12798                 {
12799                 for (j=0; j<4; j++)
12800                     {
12801                     SafeSprintf (&tempStr, &tempStrSize, "\t%s", MbPrintNum(sst[mp->numM10BetaCats + mp->numM10GammaCats + 4 + j]));
12802                     if (AddToPrintString (tempStr) == ERROR) goto errorExit;
12803                     }
12804                 for (j=0; j<2; j++)
12805                     {
12806                     SafeSprintf (&tempStr, &tempStrSize, "\t%s", MbPrintNum(sst[mp->numM10BetaCats + mp->numM10GammaCats + j]));
12807                     if (AddToPrintString (tempStr) == ERROR) goto errorExit;
12808                     }
12809                 }
12810             else
12811                 {
12812                 for (j=0; j<3; j++)
12813                     {
12814                     SafeSprintf (&tempStr, &tempStrSize, "\t%s", MbPrintNum(sst[j]));
12815                     if (AddToPrintString (tempStr) == ERROR) goto errorExit;
12816                     }
12817                 }
12818             }
12819         }
12820         
12821     /* if user wants site rates, we print those here */
12822     if (inferSiteRates == YES)
12823         {
12824         for (d=0; d<numCurrentDivisions; d++)
12825             {
12826             m = &modelSettings[d];
12827             if (m->printSiteRates == YES)
12828                 {
12829                 mp = &modelParams[d];
12830                 tree = GetTree (m->brlens, coldId, state[coldId]);
12831                 node = tree->root->left;
12832                 m->PrintSiteRates (node, d, coldId);
12833                 }
12834             }
12835         }
12836
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)
12840         {
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++)
12844             {
12845             m = &modelSettings[d];
12846             tree = GetTree(m->brlens, coldId, state[coldId]);
12847             if (m->printPosSel == YES)
12848                 {
12849                 if (m->PosSelProbs (tree->root->left, d, coldId) == ERROR)
12850                     {
12851                     goto errorExit;
12852                     }
12853                 }
12854             }
12855
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++)
12860             {
12861             compressedCharPosition = compCharPos[i];
12862             if (!(posSelProbs[compressedCharPosition] < 0.0) && printedChar[i] == NO && charInfo[i].isExcluded == NO)
12863                 {
12864                 for (j=k=0; j<numChar; j++)
12865                     {
12866                     if (charInfo[j].charId == charInfo[i].charId)
12867                         {
12868                         origAlignmentChars[k++] = j;
12869                         printedChar[j] = YES;
12870                         }
12871                     }
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]); */
12876                 }
12877             }
12878         }
12879     
12880     /* If the user wants omega values for each site, we print those here. */
12881     if (inferSiteOmegas == YES)
12882         {
12883         /* loop over the divisions, calculating the omega value for each site */
12884         for (d=0; d<numCurrentDivisions; d++)
12885             {
12886             m = &modelSettings[d];
12887             tree = GetTree(m->brlens, coldId, state[coldId]);
12888             if (m->printSiteOmegas == YES)
12889                 {
12890                 if (m->SiteOmegas (tree->root->left, d, coldId) == ERROR)
12891                     {
12892                     goto errorExit;
12893                     }
12894                 }
12895             }
12896
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++)
12902             {
12903             compressedCharPosition = compCharPos[i];
12904             if (posSelProbs[compressedCharPosition] >= 0.0 && printedChar[i] == NO && charInfo[i].isExcluded == NO)
12905                 {
12906                 for (j=k=0; j<numChar; j++)
12907                     {
12908                     if (charInfo[j].charId == charInfo[i].charId)
12909                         {
12910                         origAlignmentChars[k++] = j;
12911                         printedChar[j] = YES;
12912                         }
12913                     }
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]); */
12918                 }
12919             }
12920         }
12921      
12922     /* free memory for positive selection probs or site omegas */
12923     if (inferPosSel == YES || inferSiteOmegas == YES)
12924         {
12925         if (memAllocs[ALLOC_POSSELPROBS] == YES)
12926             free (posSelProbs);
12927         memAllocs[ALLOC_POSSELPROBS] = NO;
12928         free (printedChar);
12929         }
12930
12931     /* if user wants ancestral states for constrained nodes, we obtain and print those here */
12932     if (inferAncStates == YES)
12933         {
12934         for (d=0; d<numCurrentDivisions; d++)
12935             {
12936             m = &modelSettings[d];
12937             if (m->printAncStates == YES)
12938                 {
12939                 mp = &modelParams[d];
12940                 tree = GetTree (m->brlens, coldId, state[coldId]);
12941                 for (i=j=tree->nIntNodes - 1; i>=0; i--)
12942                     {
12943                     node = tree->intDownPass[i];
12944                     m->CondLikeUp (node, d, coldId);
12945                     }
12946                 for (k=0; k<numDefinedConstraints; k++)
12947                     {
12948                     if (mp->activeConstraints[k] == NO || definedConstraintsType[k] != HARD)
12949                         continue;
12950                     for (i=tree->nIntNodes-1; i>=0; i--)
12951                         {
12952                         node = tree->intDownPass[i];
12953                         if (node->isLocked == YES && k == node->lockID)
12954                             m->PrintAncStates (node, d, coldId);
12955                         }
12956                     }
12957                 }
12958             }
12959         }
12960
12961     SafeSprintf (&tempStr, &tempStrSize, "\n");
12962     if (AddToPrintString (tempStr) == ERROR) goto errorExit;
12963     
12964     free (tempStr);
12965     SafeFree ((void **)&partString);
12966     
12967     return (NO_ERROR);
12968     
12969     errorExit:
12970         if (printedChar)
12971             free (printedChar);
12972         if (memAllocs[ALLOC_POSSELPROBS] == YES)
12973             free (posSelProbs);
12974         memAllocs[ALLOC_POSSELPROBS] = NO;
12975         free (tempStr);
12976         SafeFree ((void **)&partString);
12977         return (ERROR);
12978 }
12979
12980
12981 /*----------------------------------------------------------------------
12982 |
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.
12987 |
12988 ------------------------------------------------------------------------*/
12989 int PrintStatesToFiles (int curGen)
12990 {
12991     int             i, j, chn, coldId, runId;
12992     MrBFlt          clockRate;
12993     Tree            *tree=NULL;
12994     Param           *param;
12995 #   if defined (MPI_ENABLED)
12996     int             id, x, doesThisProcHaveId, procWithChain, ierror, tag, nErrors, sumErrors;
12997     MPI_Status      status;
12998 #   endif
12999
13000 #   if !defined (MPI_ENABLED)
13001
13002     /* print parameter values and trees (single-processor version) */
13003     for (chn=0; chn<numLocalChains; chn++)
13004         {
13005         if ((chainId[chn] % chainParams.numChains) == 0)
13006             {
13007             coldId = chn;
13008             runId = chainId[chn] / chainParams.numChains;
13009
13010             /* print parameter values */
13011             if (PrintStates (curGen, coldId) == ERROR)
13012                 return (ERROR);
13013             fprintf (fpParm[runId], "%s", printString);
13014             fflush (fpParm[runId]);
13015             free(printString);
13016
13017             /* print trees */
13018             for (i=0; i<numPrintTreeParams; i++)
13019                 {
13020                 param = printTreeParam[i];
13021                 tree = GetTree(param, coldId, state[coldId]);
13022                 if (param->paramType == P_TOPOLOGY)
13023                     {
13024                     if (tree->isClock == YES)
13025                         clockRate = *GetParamVals(modelSettings[tree->relParts[0]].clockRate, coldId, state[coldId]);
13026                     else
13027                         clockRate = 0.0;
13028                     if (PrintTree (curGen, param, coldId, NO, clockRate) == ERROR)
13029                         return (ERROR);
13030                     }
13031                 else
13032                     {
13033                     if (tree->isClock == YES)
13034                         clockRate = *GetParamVals(modelSettings[tree->relParts[0]].clockRate, coldId, state[coldId]);
13035                     else
13036                         clockRate = 0.0;
13037                     if (PrintTree (curGen, param, coldId, YES, clockRate) == ERROR)
13038                         return (ERROR);
13039                     }
13040
13041                 fprintf (fpTree[runId][i], "%s", printString);
13042                 fflush (fpTree[runId][i]);
13043                 free(printString);
13044
13045                 j = printTreeTopologyIndex[i];
13046                 if (j<numTopologies)
13047                     {
13048                     if (chainParams.mcmcDiagn == YES && chainParams.numRuns > 1)
13049                         {
13050                         if (chainParams.relativeBurnin == YES || curGen >= chainParams.chainBurnIn * chainParams.sampleFreq)
13051                             {
13052                             if (AddTreeToPartitionCounters (tree, j, runId) == ERROR)
13053                                 return ERROR;
13054                             if (chainParams.relativeBurnin == YES && chainParams.saveTrees == YES && (noWarn == NO || curGen <= chainParams.stopTreeGen))
13055                                 {
13056                                 ResetTopologyFromTree (chainParams.dtree, tree);
13057                                 if (AddToTreeList (&chainParams.treeList[numTopologies*runId+j], chainParams.dtree) == ERROR)
13058                                     return (ERROR);
13059                                 }
13060                             }
13061                         }
13062                     }
13063                 }
13064             }
13065         }
13066 #   else
13067     /* print parameter values and trees (parallel version) */
13068     
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)
13072         {
13073         MrBayesPrint ("%s   Problem at chain barrier.\n", spacer);
13074         return ERROR;
13075         }
13076     tag = nErrors = 0;
13077         
13078     /* Loop over runs. */
13079     for (runId=0; runId<chainParams.numRuns; runId++)
13080         {
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, ...
13083            are cold. */
13084         id = runId * chainParams.numChains;
13085         
13086         /* Does this processor have the chain? */
13087         doesThisProcHaveId = NO;
13088         coldId = 0;
13089         for (chn=0; chn<numLocalChains; chn++)
13090             {
13091             if (chainId[chn] == id)
13092                 {
13093                 doesThisProcHaveId = YES;
13094                 coldId = chn;
13095                 break;
13096                 }
13097             }
13098         
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. */
13104         x = 0;
13105         if (doesThisProcHaveId == YES)
13106             x = proc_id;
13107         ierror = MPI_Allreduce (&x, &procWithChain, 1, MPI_INT, MPI_SUM, MPI_COMM_WORLD);
13108         if (ierror != MPI_SUCCESS)
13109             {
13110             MrBayesPrint ("%s   Problem finding processor with chain to print.\n", spacer);
13111             return (ERROR);
13112             }
13113
13114         /* ****************************************************************************************************/
13115         /* print parameter values *****************************************************************************/
13116         
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)
13120             {
13121             if (PrintStates (curGen, coldId) == ERROR)
13122                 nErrors++;
13123             }
13124         MPI_Allreduce (&nErrors, &sumErrors, 1, MPI_INT, MPI_SUM, MPI_COMM_WORLD);
13125         if (sumErrors > 0)
13126             {
13127             MrBayesPrint ("%s   Problem with PrintStates.\n", spacer);
13128             return ERROR;
13129             }
13130         
13131         /* First communication: Send/receive the length of the printString. */
13132         if (proc_id == 0 || proc_id == procWithChain)
13133             {
13134             if (procWithChain != 0)
13135                 {
13136                 if (proc_id == procWithChain)
13137                     {
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)
13141                         nErrors++;
13142                     }
13143                 else
13144                     {
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)
13149                         {
13150                         MrBayesPrint ("%s   Problem receiving printStringSize from proc_id = %d\n", spacer, procWithChain);
13151                         nErrors++;
13152                         }
13153                     printString = (char *)SafeMalloc((size_t)printStringSize * sizeof(char));
13154                     if (!printString)
13155                         {
13156                         MrBayesPrint ("%s   Problem allocating printString (%d)\n", spacer, printStringSize * sizeof(char));
13157                         nErrors++;
13158                         }
13159                     strcpy (printString, "");
13160                     }
13161                 }
13162             }
13163         MPI_Allreduce (&nErrors, &sumErrors, 1, MPI_INT, MPI_SUM, MPI_COMM_WORLD);
13164         if (sumErrors > 0)
13165             {
13166             MrBayesPrint ("%s   Problem with first communication (states).\n", spacer);
13167             return ERROR;
13168             }
13169
13170         /* Second communication: Send/receive the printString. */
13171         if (proc_id == 0 || proc_id == procWithChain)
13172             {
13173             if (procWithChain != 0)
13174                 {                   
13175                 if (proc_id == procWithChain)
13176                     {
13177                     /* Send the printString to proc_id = 0. After we send the string to proc_id = 0, we can
13178                        free it. */
13179                     ierror = MPI_Send (&printString[0], (int)printStringSize, MPI_CHAR, 0, tag, MPI_COMM_WORLD);
13180                     if (ierror != MPI_SUCCESS)
13181                         nErrors++;
13182                     free(printString);
13183                     }
13184                 else
13185                     {
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)
13189                         {
13190                         MrBayesPrint ("%s   Problem receiving printString from proc_id = %d\n", spacer, procWithChain);
13191                         nErrors++;
13192                         }
13193                     }
13194                 }
13195             }
13196         MPI_Allreduce (&nErrors, &sumErrors, 1, MPI_INT, MPI_SUM, MPI_COMM_WORLD);
13197         if (sumErrors > 0)
13198             {
13199             MrBayesPrint ("%s   Problem with second communication (states).\n", spacer);
13200             return ERROR;
13201             }
13202
13203         /* Print the string with the parameter information if we are proc_id = 0. */
13204         if (proc_id == 0)
13205             {
13206             fprintf (fpParm[runId], "%s", printString);
13207             fflush (fpParm[runId]);
13208             free(printString);
13209             }
13210
13211         /* ****************************************************************************************************/
13212         /* print trees ****************************************************************************************/
13213
13214         for (i=0; i<numPrintTreeParams; i++)
13215             {
13216             /* Print trees to file. */
13217
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)
13221                 {
13222                 param = printTreeParam[i];
13223                 tree = GetTree(param, coldId, state[coldId]);
13224                 if (param->paramType == P_TOPOLOGY)
13225                     {
13226                     if (tree->isClock == YES)
13227                         clockRate = *GetParamVals(modelSettings[tree->relParts[0]].clockRate, coldId, state[coldId]);
13228                     else
13229                         clockRate = 0.0;
13230                     if (PrintTree (curGen, param, coldId, NO, clockRate) == ERROR)
13231                         nErrors++;
13232                     }
13233                 else
13234                     {
13235                     if (tree->isClock == YES)
13236                         clockRate = *GetParamVals(modelSettings[tree->relParts[0]].clockRate, coldId, state[coldId]);
13237                     else
13238                         clockRate = 0.0;
13239                     if (PrintTree (curGen, param, coldId, YES, clockRate) == ERROR)
13240                         nErrors++;
13241                     }
13242                 }
13243             MPI_Allreduce (&nErrors, &sumErrors, 1, MPI_INT, MPI_SUM, MPI_COMM_WORLD);
13244             if (sumErrors > 0)
13245                 {
13246                 MrBayesPrint ("%s   Problem with printing trees.\n", spacer);
13247                 return ERROR;
13248                 }
13249                 
13250             /* First communication: Send/receive the length of the printString. */
13251             if (proc_id == 0 || proc_id == procWithChain)
13252                 {
13253                 if (procWithChain != 0)
13254                     {
13255                     if (proc_id == procWithChain)
13256                         {
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)
13260                             nErrors++;
13261                         }
13262                     else
13263                         {
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)
13268                             {
13269                             MrBayesPrint ("%s   Problem receiving printStringSize from proc_id = %d\n", spacer, procWithChain);
13270                             nErrors++;
13271                             }
13272                         printString = (char *)SafeMalloc((size_t)printStringSize * sizeof(char));
13273                         if (!printString)
13274                             {
13275                             MrBayesPrint ("%s   Problem allocating printString (%d)\n", spacer, printStringSize * sizeof(char));
13276                             nErrors++;
13277                             }
13278                         strcpy (printString, "");
13279                         }
13280                     }
13281                 }
13282             MPI_Allreduce (&nErrors, &sumErrors, 1, MPI_INT, MPI_SUM, MPI_COMM_WORLD);
13283             if (sumErrors > 0)
13284                 {
13285                 MrBayesPrint ("%s   Problem with first communication (states).\n", spacer);
13286                 return ERROR;
13287                 }
13288
13289             /* Second communication: Send/receive the printString. */
13290             if (proc_id == 0 || proc_id == procWithChain)
13291                 {
13292                 if (procWithChain != 0)
13293                     {                   
13294                     if (proc_id == procWithChain)
13295                         {
13296                         /* Send the printString to proc_id = 0. After we send the string to proc_id = 0, we can
13297                            free it. */
13298                         ierror = MPI_Send (&printString[0], (int)printStringSize, MPI_CHAR, 0, tag, MPI_COMM_WORLD);
13299                         if (ierror != MPI_SUCCESS)
13300                             nErrors++;
13301                         free(printString);
13302                         }
13303                     else
13304                         {
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)
13308                             {
13309                             MrBayesPrint ("%s   Problem receiving printString from proc_id = %d\n", spacer, procWithChain);
13310                             nErrors++;
13311                             }
13312                         }
13313                     }
13314                 }
13315             MPI_Allreduce (&nErrors, &sumErrors, 1, MPI_INT, MPI_SUM, MPI_COMM_WORLD);
13316             if (sumErrors > 0)
13317                 {
13318                 MrBayesPrint ("%s   Problem with second communication (states).\n", spacer);
13319                 return ERROR;
13320                 }
13321
13322             /* Print the string with the parameter information if we are proc_id = 0. */
13323             if (proc_id == 0)
13324                 {
13325                 fprintf (fpTree[runId][i], "%s", printString);
13326                 fflush (fpTree[runId][i]);
13327                 j = printTreeTopologyIndex[i];
13328                 if (j < numTopologies)
13329                     {
13330                     if (chainParams.numRuns > 1 && chainParams.mcmcDiagn == YES)
13331                         {
13332                         if (chainParams.relativeBurnin == YES || curGen >= chainParams.chainBurnIn * chainParams.sampleFreq)
13333                             {
13334                             char *s = NULL;
13335                             StripComments (printString);
13336                             /* if it is the first tree, we strip out the translate block first (twice) */
13337                             if (curGen==0) {
13338                                 if (strtok (printString, ";")==NULL) /* get translate lock */
13339                                     return (ERROR);
13340                                 if (strtok (NULL, ";")==NULL)
13341                                     return (ERROR);
13342                                 if (strtok (NULL, "\n\t\r ")==NULL) /* get 'tree' */
13343                                     return (ERROR);
13344                                 }
13345                             else {
13346                                 if (strtok (printString, "\n\t\r ")==NULL) /* get 'tree' */
13347                                     return (ERROR);
13348                                 }
13349                             if (strtok (NULL, " =")==NULL)  /* get 'rep.xxxx' */
13350                                 return (ERROR);
13351                             if ((s = strtok (NULL, " =;"))==NULL)  /* get Newick string */
13352                                 return (ERROR);
13353                             ResetTopology (chainParams.dtree, s);
13354                             if (AddTreeToPartitionCounters (chainParams.dtree, j, runId) == ERROR)
13355                                 return ERROR;
13356                             if (chainParams.relativeBurnin == YES && chainParams.saveTrees == YES && (noWarn == NO || curGen <= chainParams.stopTreeGen))
13357                                 {
13358                                 if (AddToTreeList (&chainParams.treeList[runId*numTopologies+j], chainParams.dtree) == ERROR)
13359                                     return (ERROR);
13360                                 }
13361                             }
13362                         }
13363                     }
13364                 free(printString);
13365                 }
13366             }
13367
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)
13371             {
13372             MrBayesPrint ("%s   Problem at chain barrier.\n", spacer);
13373             return ERROR;
13374             }
13375         }
13376 #   endif
13377         
13378     return (NO_ERROR);
13379 }
13380
13381
13382 int PrintSwapInfo (void)
13383 {
13384     int         i, j, n, maxNumExchanges, len, maxLen, reweightingChars=0;
13385     char        *tempStr;
13386     int             tempStrSize;
13387
13388     if (chainParams.numChains == 1)
13389         return NO_ERROR;
13390
13391 #   if defined (MPI_ENABLED)
13392     if (ReassembleSwapInfo() == ERROR)
13393         return ERROR;
13394     if (proc_id != 0)
13395         return NO_ERROR;
13396 #   endif
13397
13398     tempStrSize = TEMPSTRSIZE;
13399     tempStr = (char *) SafeMalloc((size_t)tempStrSize * sizeof(char));
13400     if (!tempStr)
13401         {
13402         MrBayesPrint ("%s   Problem allocating tempString (%d)\n", spacer, tempStrSize * sizeof(char));
13403         return (ERROR);
13404         }
13405
13406     for (n=0; n<chainParams.numRuns; n++)
13407         {
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);
13415         if (maxLen < 4)
13416             maxLen = 4;
13417             
13418         reweightingChars = NO;
13419         if ((chainParams.weightScheme[0] + chainParams.weightScheme[1]) > 0.00001)
13420             reweightingChars = YES;
13421
13422         if (chainParams.numRuns == 1)
13423             MrBayesPrint ("\n%s   Chain swap information:\n\n", spacer);
13424         else
13425             MrBayesPrint ("\n%s   Chain swap information for run %d:\n\n", spacer, n+1);
13426
13427         MrBayesPrint ("%s          ", spacer);
13428         for (j=0; j<chainParams.numChains; j++)
13429             {
13430             SafeSprintf (&tempStr, &tempStrSize, "%d", j+1);
13431             len = (int) strlen(tempStr);
13432             MrBayesPrint ("%*c %d ", maxLen-len, ' ', j+1);
13433             }
13434         MrBayesPrint ("\n");
13435         
13436         MrBayesPrint ("%s        --", spacer);
13437         for (j=0; j<chainParams.numChains; j++)
13438             {
13439             MrBayesPrint ("--");
13440             for (i=0; i<maxLen; i++)
13441                 MrBayesPrint ("-");
13442             }
13443         MrBayesPrint ("\n");
13444         
13445         for (i=0; i<chainParams.numChains; i++)
13446             {
13447             MrBayesPrint ("%s   %4d | ", spacer, i+1);
13448             for (j=0; j<chainParams.numChains; j++)
13449                 {
13450                 if (i < j)
13451                     {
13452                     if (swapInfo[n][j][i] <= 0)
13453                         {
13454                         MrBayesPrint ("%*c%s ", maxLen-3, ' ', " NA ");
13455                         }
13456                     else
13457                         {
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]);
13461                         }
13462                     }
13463                 else if (i == j)
13464                     {
13465                     MrBayesPrint ("%*c ", maxLen+1, ' ');
13466                     }
13467                 else
13468                     {
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]);
13472                     }
13473                 }
13474             MrBayesPrint ("\n");
13475             }
13476         }
13477
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);
13480         
13481     MrBayesPrint ("\n%s   Chain information:\n\n", spacer);
13482     MrBayesPrint ("%s     ID -- Heat ", spacer);
13483     if (reweightingChars == YES)
13484         MrBayesPrint ("%% Dn %% Up\n");
13485     else
13486         MrBayesPrint ("\n");
13487     
13488     MrBayesPrint ("%s    -----------", spacer);
13489     if (reweightingChars == YES)
13490         MrBayesPrint ("----------\n");
13491     else
13492         MrBayesPrint ("\n");
13493     for (i=0; i<chainParams.numChains; i++)
13494         {
13495         MrBayesPrint ("%s   %4d -- %1.2lf ", spacer, i+1, Temperature (i)/*1.0 / (1.0 + chainParams.chainTemp * i)*/);
13496         if (reweightingChars == YES)
13497             {
13498             if (i == 0)
13499                 {
13500                 MrBayesPrint ("  0%%   0%% (cold chain)\n");
13501                 }
13502             else
13503                 {
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]);
13510                 }
13511             }
13512         else
13513             {
13514             if (i == 0)
13515                 MrBayesPrint (" (cold chain)\n");
13516             else
13517                 MrBayesPrint ("\n");
13518             }
13519         }
13520     if (chainParams.userDefinedTemps == NO)
13521         {
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);
13524         }
13525     if (reweightingChars == YES)
13526         MrBayesPrint ("%s   Reweighting increment = %1.2lf\n", spacer, chainParams.weightScheme[2]);
13527     MrBayesPrint ("\n");
13528         
13529     free (tempStr);
13530     return (NO_ERROR);
13531 }
13532
13533
13534 /*----------------------------------------------------------------------
13535 |
13536 |   PrintTermState: Print terminal state index matrix
13537 |
13538 ------------------------------------------------------------------------*/
13539 int PrintTermState (void)
13540 {
13541     int             i, j=0, c, d, printWidth, nextColumn, nDigits, nReps;
13542     ModelInfo       *m;
13543     ModelParams     *mp;
13544
13545     printWidth = 79;
13546
13547     for (d=0; d<numCurrentDivisions; d++)
13548         {
13549         MrBayesPrint ("\nTerminal state index matrix for division %d\n\n", d+1);
13550
13551         m = &modelSettings[d];
13552         mp = &modelParams[d];
13553
13554         if (!strcmp(mp->covarionModel, "Yes"))
13555             nReps = 2;
13556         else
13557             nReps = 1;
13558
13559         nDigits = 1 + (int)(log10(mp->nStates * mp->nStates * nReps));
13560     
13561         for (c=m->compCharStart; c<m->compCharStop; c=j)
13562             {
13563             for (i=0; i<numTaxa; i++)
13564                 {
13565                 MrBayesPrint ("%-10.10s   ", taxaNames[i]);
13566                 j = c;
13567                 for (nextColumn=13; nextColumn < printWidth; nextColumn+=nDigits + 1)
13568                     {
13569                     if (j >= m->compCharStop)
13570                         break;
13571                     MrBayesPrint ("%*d ",nDigits, m->termState[i][j-c]);
13572                     j++;
13573                     }
13574                 MrBayesPrint ("\n");
13575                 }
13576             MrBayesPrint("\n");
13577             }
13578         }   /* next division */
13579
13580     return NO_ERROR;
13581 }
13582
13583
13584 /*--------------------------------------------------
13585 |
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
13589 |       reversibility
13590 |
13591 ---------------------------------------------------*/
13592 void PrintTiProbs (CLFlt *tP, MrBFlt *bs, int nStates)
13593 {
13594     int     i, j;
13595     CLFlt   *tiP, sum;
13596
13597     tiP = tP;
13598
13599     printf ("\nTransition matrix\n");
13600     for (i=0; i<nStates; i++)
13601         {
13602         printf ("\t%d", i);
13603         }
13604     printf ("\tsum\n");
13605
13606     for (i=0; i<nStates; i++)
13607         {
13608         printf ("%d\t", i);
13609         sum = 0.0;
13610         for (j=0; j<nStates; j++)
13611             {
13612             printf ("\t%.6f",tP[j]);
13613             sum += tP[j];
13614             }
13615         printf ("\t%.6f\n",sum);
13616         tP += nStates;
13617         }
13618
13619     printf ("\nStationary state frequencies\n");
13620     for (i=0; i<nStates; i++)
13621         printf ("%d -- %f\n",i,bs[i]);
13622     
13623     printf ("\nTime reversibility\n");
13624
13625     printf ("State 1\tState 2\tforward\tbackward\tabs diff\n");
13626     for (i=0; i<nStates; i++)
13627         {
13628         for (j=i+1; j<nStates; j++)
13629             {
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]));
13632             }
13633         }
13634
13635     getchar();
13636     return;
13637 }
13638
13639
13640 int PrintTopConvInfo (void)
13641 {
13642     int         i, j, n, len, maxLen;
13643     char        *tempStr;
13644     int         tempStrSize;
13645     MrBFlt      maxNumPartitions;
13646     STATS       *stat;
13647
13648     if (chainParams.numRuns == 1)
13649         return NO_ERROR;
13650
13651 #   if defined (MPI_ENABLED)
13652     if (proc_id != 0)
13653         return (NO_ERROR);
13654 #   endif
13655
13656     tempStrSize = TEMPSTRSIZE;
13657     tempStr = (char *) SafeMalloc((size_t)tempStrSize * sizeof(char));
13658     if (!tempStr)
13659         {
13660         MrBayesPrint ("%s   Problem allocating tempString (%d)\n", spacer, tempStrSize * sizeof(char));
13661         return (ERROR);
13662         }
13663
13664     for (n=0; n<numTopologies; n++)
13665         {
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);
13674         if (maxLen < 5)
13675             maxLen = 5;
13676         
13677         if (numTopologies == 1)
13678             {
13679             if (chainParams.diagnStat == AVGSTDDEV)
13680                 MrBayesPrint ("%s   Pairwise average standard deviation of split frequencies (upper triangle)\n", spacer);
13681             else
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);
13684             }
13685         else
13686             {
13687             if (chainParams.diagnStat == AVGSTDDEV)
13688                 MrBayesPrint ("%s   Pairwise average standard deviation of split frequencies in topology %d (upper triangle)\n", spacer, n);
13689             else
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);
13692             }
13693
13694         MrBayesPrint ("%s          ", spacer);
13695         for (j=0; j<chainParams.numRuns; j++)
13696             {
13697             SafeSprintf (&tempStr, &tempStrSize, "%d", j+1);
13698             len = (int) strlen(tempStr);
13699             MrBayesPrint ("%*c %d ", maxLen-len, ' ', j+1);
13700             }
13701         MrBayesPrint ("\n");
13702     
13703         MrBayesPrint ("%s        --", spacer);
13704         for (j=0; j<chainParams.numRuns; j++)
13705             {
13706             MrBayesPrint ("--");
13707             for (i=0; i<maxLen; i++)
13708                 MrBayesPrint ("-");
13709             }
13710         MrBayesPrint ("\n");
13711     
13712         for (i=0; i<chainParams.numRuns; i++)
13713             {
13714             MrBayesPrint ("%s   %4d | ", spacer, i+1);
13715             for (j=0; j<chainParams.numRuns; j++)
13716                 {
13717                 if (i < j)
13718                     {
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);
13725                     }
13726                 else if (i == j)
13727                     {
13728                     MrBayesPrint ("%*c ", maxLen+1, ' ');
13729                     }
13730                 else
13731                     {
13732                     SafeSprintf (&tempStr, &tempStrSize, "%d", (int) stat->pair[i][j]);
13733                     len = (int) strlen(tempStr);
13734                     MrBayesPrint ("%*c%s ", maxLen-len+1, ' ', tempStr);
13735                     }
13736                 }
13737             MrBayesPrint ("\n");
13738             }
13739     
13740         MrBayesPrint ("\n");
13741         }
13742
13743     free (tempStr);
13744     return (NO_ERROR);
13745 }
13746
13747
13748 void PrintToScreen (int curGen, int startGen, time_t endingT, time_t startingT)
13749 {
13750     int         i, chn, nHours, nMins, nSecs;
13751     MrBFlt      timePerGen;
13752
13753 #   if defined (MPI_ENABLED)
13754     int         numLocalColdChains, numFirstAndLastCold;
13755     
13756     if (curGen == 0)
13757         {
13758         if (chainParams.isSS == NO && chainParams.mcmcDiagn == YES && chainParams.numRuns > 1)
13759             {
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);
13763             else
13764                 MrBayesPrint ("%s   Using an absolute burnin of %d samples for diagnostics\n", spacer, chainParams.chainBurnIn);
13765             }
13766         MrBayesPrint ("\n");
13767         MrBayesPrint ("%s   Chain results (%d generations requested):\n\n", spacer, chainParams.numGen);
13768         }
13769     MrBayesPrint ("%s   %4d -- ", spacer, curGen);
13770     numLocalColdChains = numFirstAndLastCold = 0;
13771     for (chn=0; chn<numLocalChains; chn++)
13772         {
13773         if ((chainId[chn] % chainParams.numChains) == 0)
13774             {
13775             numLocalColdChains++;
13776             if (chn == 0 || chn == numLocalChains - 1)
13777                 numFirstAndLastCold++;
13778             }
13779         }
13780
13781     i = 1;
13782     for (chn=0; chn<numLocalChains; chn++)
13783         {
13784         if (i > chainParams.printMax)   
13785             {
13786             if (i == chainParams.printMax +1)
13787                 {
13788                 i++;
13789                 if (numLocalColdChains > 0 && numLocalColdChains > numFirstAndLastCold)
13790                     MrBayesPrint ("[...%d more local chains...] ", numLocalChains - chainParams.printMax);
13791                 else
13792                     MrBayesPrint ("(...%d more local chains...) ", numLocalChains - chainParams.printMax);
13793                 continue;
13794                 }
13795             else
13796                 continue;
13797             }
13798         if ((chainId[chn] % chainParams.numChains) == 0)
13799             {
13800             i++;
13801             if (chainParams.printAll == YES)
13802                 MrBayesPrint ("[%1.3lf] ", curLnL[chn]);
13803             else
13804                 MrBayesPrint ("[%1.3lf] .. ", curLnL[chn]);
13805             }
13806         else if (chainParams.printAll == YES)
13807             {
13808             i++;
13809             MrBayesPrint ("(%1.3lf) ", curLnL[chn]);
13810             }
13811         if (chn < numLocalChains - 1 && (chainId[chn] / chainParams.numChains != chainId[chn+1] / chainParams.numChains))
13812             MrBayesPrint ("* ");
13813         }
13814         
13815     if (numLocalColdChains == chainParams.numRuns)
13816         MrBayesPrint ("(...%d remote chains...) ", (chainParams.numChains*chainParams.numRuns) - numLocalChains);
13817     else
13818         MrBayesPrint ("[...%d remote chains...] ", (chainParams.numChains*chainParams.numRuns) - numLocalChains);
13819
13820     if (curGen > 0)
13821         {
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);
13829         }
13830     MrBayesPrint ("\n");
13831     fflush (stdout);
13832     
13833 #   else
13834
13835     if (curGen == 0)
13836         {
13837         if (chainParams.isSS == NO && chainParams.mcmcDiagn == YES && chainParams.numRuns > 1)
13838             {
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);
13842             else
13843                 MrBayesPrint ("%s   Using an absolute burnin of %d samples for diagnostics\n", spacer, chainParams.chainBurnIn);
13844             }
13845         MrBayesPrint ("\n");
13846         MrBayesPrint ("%s   Chain results (%d generations requested):\n\n", spacer, chainParams.numGen);
13847         }
13848     MrBayesPrint ("%s   %5d -- ", spacer, curGen);
13849     if (numLocalChains == 1)
13850         MrBayesPrint ("%1.3lf ", curLnL[0]);
13851     else
13852         {
13853         i = 0;
13854         for (chn=0; chn<numLocalChains; chn++)
13855             {
13856             if (i >= chainParams.printMax)
13857                 {
13858                 if (i == chainParams.printMax)
13859                     MrBayesPrint (".. ");
13860                 i++;
13861                 continue;
13862                 }
13863             if (chainParams.numChains == 1)
13864                 {
13865                 MrBayesPrint ("%1.3lf ", curLnL[chn]);
13866                 i++;
13867                 }
13868             else if (chainId[chn] % chainParams.numChains == 0)
13869                 {
13870                 if (chainParams.printAll == YES)
13871                     MrBayesPrint ("[%1.3lf] ", curLnL[chn]);
13872                 else
13873                     MrBayesPrint ("[%1.3lf][%d] .. ", curLnL[chn], chn % chainParams.numChains + 1);
13874                 i++;
13875                 }
13876             else if (chainParams.printAll == YES)
13877                 {
13878                 MrBayesPrint ("(%1.3lf) ", curLnL[chn]);
13879                 i++;
13880                 }
13881             if (chn < numLocalChains - 1 && (chainId[chn] / chainParams.numChains != chainId[chn+1] / chainParams.numChains)
13882                 && i < chainParams.printMax - 1)
13883                 MrBayesPrint ("* ");
13884             }
13885         }
13886         
13887     if (curGen > 0)
13888         {
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);
13896         }
13897     MrBayesPrint ("\n");
13898     
13899     fflush (stdout);
13900     
13901 #   endif
13902         
13903 }
13904
13905
13906 int PrintTree (int curGen, Param *treeParam, int chain, int showBrlens, MrBFlt clockRate)
13907 {
13908     int             i, tempStrSize;
13909     char            *tempStr;
13910     Tree            *tree;
13911     TreeNode        *p=NULL, *q;
13912     Param           *subParm;
13913
13914     /* allocate the print string */
13915     printStringSize = 200;
13916     printString = (char *)SafeMalloc((size_t)printStringSize * sizeof(char));
13917     if (!printString)
13918         {
13919         MrBayesPrint ("%s   Problem allocating printString (%d)\n", spacer, printStringSize * sizeof(char));
13920         return (ERROR);
13921         }
13922     *printString = '\0';
13923
13924     tempStrSize = TEMPSTRSIZE;
13925     tempStr = (char *) SafeMalloc((size_t)tempStrSize * sizeof(char));
13926     if (!tempStr)
13927         {
13928         MrBayesPrint ("%s   Problem allocating tempString (%d)\n", spacer, tempStrSize * sizeof(char));
13929         return (ERROR);
13930         }
13931
13932     /* get tree */
13933     tree = GetTree(treeParam, chain, state[chain]);
13934
13935     /* order the taxa */
13936     if (chainParams.orderTaxa == YES)
13937         {
13938         for (i=0; i<tree->nNodes-1; i++)
13939             {
13940             p = tree->allDownPass[i];
13941             if (p->left == NULL)
13942                 {
13943                 if (p->index == localOutGroup)
13944                     p->x = -1;
13945                 else
13946                     p->x = p->index;
13947                 }
13948             else if (p->left->x < p->right->x)
13949                 p->x = p->left->x;
13950             else
13951                 p->x = p->right->x;
13952             }
13953         for (i=0; i<tree->nIntNodes; i++)
13954             {
13955             if (p->left->x > p->right->x)
13956                 {
13957                 q = p->left;
13958                 p->left = p->right;
13959                 p->right = q;
13960                 }
13961             }
13962         }
13963     
13964     /* print the translate block information and the top of the file */
13965     if (curGen == 0)
13966         {
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)
13975             {
13976             SafeSprintf (&tempStr, &tempStrSize, "]\n");
13977             if (AddToPrintString (tempStr) == ERROR) return(ERROR);
13978             }
13979         else if (numCurrentDivisions == tree->nRelParts)
13980             {
13981             SafeSprintf (&tempStr, &tempStrSize, "{all}]\n");
13982             if (AddToPrintString (tempStr) == ERROR) return(ERROR);
13983             }
13984         else
13985             {
13986             SafeSprintf (&tempStr, &tempStrSize, "{%d", tree->relParts[0]+1);
13987             if (AddToPrintString (tempStr) == ERROR) return(ERROR);
13988             for (i=1; i<tree->nRelParts; i++)
13989                 {
13990                 SafeSprintf (&tempStr, &tempStrSize, ",%d", tree->relParts[i]+1);
13991                 if (AddToPrintString (tempStr) == ERROR) return(ERROR);
13992                 }
13993             SafeSprintf (&tempStr, &tempStrSize, "}]\n");
13994             if (AddToPrintString (tempStr) == ERROR) return(ERROR);
13995             }
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)
14001             {
14002             for (i=0; i<numSpecies; i++)
14003                 {
14004                 if (i != numSpecies - 1)
14005                     SafeSprintf (&tempStr, &tempStrSize, "      %2d %s,\n", i+1, speciesNameSets[speciespartitionNum].names[i]);
14006                 else
14007                     SafeSprintf (&tempStr, &tempStrSize, "      %2d %s;\n", i+1, speciesNameSets[speciespartitionNum].names[i]);
14008                 if (AddToPrintString (tempStr) == ERROR) return(ERROR);
14009                 }
14010             }
14011         else
14012             {
14013             for (i=0; i<numLocalTaxa; i++)
14014                 {
14015                 if (i != numLocalTaxa - 1)
14016                     SafeSprintf (&tempStr, &tempStrSize, "      %2d %s,\n", i+1, localTaxonNames[i]);
14017                 else
14018                     SafeSprintf (&tempStr, &tempStrSize, "      %2d %s;\n", i+1, localTaxonNames[i]);
14019                 if (AddToPrintString (tempStr) == ERROR) return(ERROR);
14020                 }
14021             }
14022         }
14023     
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)
14028         {
14029         for (i=0; i<treeParam->nSubParams; i++)
14030             {
14031             subParm = treeParam->subParams[i];
14032             if (subParm->paramType == P_CPPEVENTS)
14033                 {
14034                 if (SafeSprintf (&tempStr, &tempStrSize, " [&E %s]", subParm->name) == ERROR) return (ERROR);
14035                 if (AddToPrintString (tempStr) == ERROR) return(ERROR);
14036                 }
14037             //  if (subParm->paramType == P_MIXEDBRCHRATES)
14038             //  {
14039             //  id = *GetParamIntVals(subParm, chain, state[chain]);
14040             //  if (SafeSprintf (&tempStr, &tempStrSize, " [&B %s %d]", subParm->name, id) == ERROR) return (ERROR);
14041             //  }
14042             else
14043                 if (SafeSprintf (&tempStr, &tempStrSize, " [&B %s]", subParm->name) == ERROR) return (ERROR);
14044             if (AddToPrintString (tempStr) == ERROR) return(ERROR);
14045             }
14046         }
14047     subParm = modelSettings[treeParam->relParts[0]].popSize;
14048     if (treeParam->paramType == P_SPECIESTREE && subParm->nValues > 1)
14049         {
14050         if (SafeSprintf (&tempStr, &tempStrSize, " [&N %s]", subParm->name) == ERROR) return (ERROR);
14051         if (AddToPrintString (tempStr) == ERROR) return(ERROR);
14052         }
14053
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);
14065
14066     free (tempStr); 
14067     return (NO_ERROR);
14068 }
14069
14070
14071 #if defined (MPI_ENABLED)
14072 int ReassembleMoveInfo (void)
14073 {
14074     int             i, n, ierror;
14075     double          x[7], sum[7];
14076     MCMCMove        *mv;
14077
14078     for (n=0; n<numGlobalChains; n++)
14079         {
14080         for (i=0; i<numUsedMoves; i++)
14081             {
14082             mv = usedMoves[i];
14083
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];
14093
14094             ierror = MPI_Allreduce (&x, &sum, 7, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);
14095             if (ierror != MPI_SUCCESS)
14096                 return (ERROR);
14097
14098             if (proc_id == 0)
14099                 {
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];
14108                 }
14109             }
14110         }
14111
14112     return (NO_ERROR);
14113 }
14114
14115
14116 int ReassembleParamVals (int *curId)
14117 {
14118     int             i, j, k, orderLen, nBrlens, lower, upper, numChainsForProc, proc, ierror, *y, *order, *id, *nEvents;
14119     MrBFlt          *x, *brlens, **position, **rateMult;
14120     MPI_Status      status;
14121     MPI_Request     request;
14122     Tree            *tree;
14123     Param           *p;
14124
14125     extern MrBFlt   *paramValues;
14126     extern int      paramValsRowSize;
14127     extern int      intValsRowSize;
14128
14129     for (i=0; i<numLocalChains; i++)
14130         curId[i] = chainId[i];
14131
14132     numChainsForProc = numGlobalChains / num_procs;
14133     if (numGlobalChains % num_procs > 0)
14134         lower = upper = numChainsForProc+1;
14135     else
14136         lower = upper = numChainsForProc;
14137
14138     for (proc=1; proc<num_procs; proc++, lower=upper)
14139         {
14140         if (proc < numGlobalChains % num_procs)
14141             upper += numChainsForProc+1;
14142         else
14143             upper += numChainsForProc;
14144         
14145         /* chain ids */
14146         if (proc_id == 0)
14147             {
14148         id = curId + lower;
14149             ierror = MPI_Irecv (id, upper-lower, MPI_INT, proc, 0, MPI_COMM_WORLD, &request);
14150             if (ierror != MPI_SUCCESS)
14151                 {
14152                 return (ERROR);
14153                 }
14154             ierror = MPI_Waitall (1, &request, &status);
14155             if (ierror != MPI_SUCCESS)
14156                 {
14157                 return (ERROR);
14158                 }
14159             }
14160         else if (proc_id == proc)
14161             {
14162             id = curId;
14163             ierror = MPI_Isend (id, upper-lower, MPI_INT, 0, 0, MPI_COMM_WORLD, &request);
14164             if (ierror != MPI_SUCCESS)
14165                 {
14166                 return (ERROR);
14167                 }
14168             ierror = MPI_Waitall (1, &request, &status);
14169             if (ierror != MPI_SUCCESS)
14170                 {
14171                 return (ERROR);
14172                 }
14173             }
14174         
14175         /* chain states */
14176         if (proc_id == 0)
14177             {
14178             ierror = MPI_Irecv (state+lower, upper-lower, MPI_CHAR, proc, 0, MPI_COMM_WORLD, &request);
14179             if (ierror != MPI_SUCCESS)
14180                 {
14181                 return (ERROR);
14182                 }
14183             ierror = MPI_Waitall (1, &request, &status);
14184             if (ierror != MPI_SUCCESS)
14185                 {
14186                 return (ERROR);
14187                 }
14188             }
14189         else if (proc_id == proc)
14190             {
14191             ierror = MPI_Isend (state, upper-lower, MPI_CHAR, 0, 0, MPI_COMM_WORLD, &request);
14192             if (ierror != MPI_SUCCESS)
14193                 {
14194                 return (ERROR);
14195                 }
14196             ierror = MPI_Waitall (1, &request, &status);
14197             if (ierror != MPI_SUCCESS)
14198                 {
14199                 return (ERROR);
14200                 }
14201             }
14202
14203         /* normal parameter values */
14204         if (proc_id == 0)
14205             {
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)
14209                 {
14210                 return (ERROR);
14211                 }
14212             ierror = MPI_Waitall (1, &request, &status);
14213             if (ierror != MPI_SUCCESS)
14214                 {
14215                 return (ERROR);
14216                 }
14217             if (intValsRowSize > 0)
14218                 {
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)
14222                     {
14223                     return (ERROR);
14224                     }
14225                 ierror = MPI_Waitall (1, &request, &status);
14226                 if (ierror != MPI_SUCCESS)
14227                     {
14228                     return (ERROR);
14229                     }
14230                 }
14231             }
14232         else if (proc_id == proc)
14233             {
14234             x = paramValues;
14235             ierror = MPI_Isend (x, paramValsRowSize*2*(upper-lower), MPI_DOUBLE, 0, 0, MPI_COMM_WORLD, &request);
14236             if (ierror != MPI_SUCCESS)
14237                 {
14238                 return (ERROR);
14239                 }
14240             ierror = MPI_Waitall (1, &request, &status);
14241             if (ierror != MPI_SUCCESS)
14242                 {
14243                 return (ERROR);
14244                 }
14245             if (intValsRowSize > 0)
14246                 {
14247                 y = intValues;
14248                 ierror = MPI_Isend (y, intValsRowSize*2*(upper-lower), MPI_INT, 0, 0, MPI_COMM_WORLD, &request);
14249                 if (ierror != MPI_SUCCESS)
14250                     {
14251                     return (ERROR);
14252                     }
14253                 ierror = MPI_Waitall (1, &request, &status);
14254                 if (ierror != MPI_SUCCESS)
14255                     {
14256                     return (ERROR);
14257                     }
14258                 }
14259             }
14260
14261         /* std state frequencies */
14262         if (stdStateFreqsRowSize > 0)
14263             {
14264             if (proc_id == 0)
14265                 {
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)
14269                     {
14270                     return (ERROR);
14271                     }
14272                 ierror = MPI_Waitall (1, &request, &status);
14273                 if (ierror != MPI_SUCCESS)
14274                     {
14275                     return (ERROR);
14276                     }
14277                 }
14278             else if (proc_id == proc)
14279                 {
14280                 x = stdStateFreqs;
14281                 ierror = MPI_Isend (x, stdStateFreqsRowSize*2*(upper-lower), MPI_DOUBLE, 0, 0, MPI_COMM_WORLD, &request);
14282                 if (ierror != MPI_SUCCESS)
14283                     {
14284                     return (ERROR);
14285                     }
14286                 ierror = MPI_Waitall (1, &request, &status);
14287                 if (ierror != MPI_SUCCESS)
14288                     {
14289                     return (ERROR);
14290                     }
14291                 }
14292             }
14293         
14294         /* mcmc trees */
14295         brlens = (MrBFlt *) SafeCalloc (2*numLocalTaxa, sizeof(MrBFlt));
14296         order  = (int *)    SafeCalloc (2*numLocalTaxa,   sizeof(int));
14297         for (i=lower; i<upper; i++)
14298             {
14299             for (j=0; j<numTrees; j++)
14300                 {
14301                 tree = GetTreeFromIndex(j,0,0);
14302                 orderLen = 2*tree->nIntNodes - 1;
14303                 nBrlens = tree->nNodes - 1;
14304                 if (proc_id == 0)
14305                     {
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)
14309                         {
14310                         return (ERROR);
14311                         }
14312                     ierror = MPI_Waitall (1, &request, &status);
14313                     if (ierror != MPI_SUCCESS)
14314                         {
14315                         return (ERROR);
14316                         }
14317                     ierror = MPI_Irecv (brlens, nBrlens, MPI_DOUBLE, proc, 0, MPI_COMM_WORLD, &request);
14318                     if (ierror != MPI_SUCCESS)
14319                         {
14320                         return (ERROR);
14321                         }
14322                     ierror = MPI_Waitall (1, &request, &status);
14323                     if (ierror != MPI_SUCCESS)
14324                         {
14325                         return (ERROR);
14326                         }
14327                     if (tree->isRooted == YES)
14328                         RetrieveRTreeWithIndices(tree, order, brlens);
14329                     else
14330                         {
14331                         RetrieveUTree(tree, order, brlens);
14332                         if (localOutGroup!=0)
14333                             MoveCalculationRoot(tree,localOutGroup);
14334                         }
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]);
14340                     }
14341                 else if (proc_id == proc)
14342                     {
14343                     tree = GetTreeFromIndex(j,i-lower,state[i-lower]);
14344                     if (tree->isRooted == YES)
14345                         StoreRTreeWithIndices(tree, order, brlens);
14346                     else
14347                         StoreUTree(tree, order, brlens);
14348                     ierror = MPI_Isend (order, orderLen, MPI_INT, 0, 0, MPI_COMM_WORLD, &request);
14349                     if (ierror != MPI_SUCCESS)
14350                         {
14351                         return (ERROR);
14352                         }
14353                     ierror = MPI_Waitall (1, &request, &status);
14354                     if (ierror != MPI_SUCCESS)
14355                         {
14356                         return (ERROR);
14357                         }
14358                     ierror = MPI_Isend (brlens, nBrlens, MPI_DOUBLE, 0, 0, MPI_COMM_WORLD, &request);
14359                     if (ierror != MPI_SUCCESS)
14360                         {
14361                         return (ERROR);
14362                         }
14363                     ierror = MPI_Waitall (1, &request, &status);
14364                     if (ierror != MPI_SUCCESS)
14365                         {
14366                         return (ERROR);
14367                         }
14368                     }
14369                 }
14370             }
14371         free (brlens);
14372         free (order);
14373
14374         /* CPP event parameters */
14375         for (i=lower; i<upper; i++)
14376             {
14377             for (j=0; j<numParams; j++)
14378                 {
14379                 p = &params[j];
14380                 if (p->paramType == P_CPPEVENTS)
14381                     {
14382                     if (proc_id == proc)
14383                         {
14384                         /* get pointers */
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]];
14388
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)
14392                             return (ERROR);
14393                         ierror = MPI_Waitall (1, &request, &status);
14394                         if (ierror != MPI_SUCCESS)
14395                             return (ERROR);
14396
14397                         /* send events and clear pointers */
14398                         for (k=0; k<2*numLocalTaxa; k++)
14399                             {
14400                             if (nEvents[k] > 0)
14401                                 {
14402                                 ierror = MPI_Isend (position[k], nEvents[k], MPI_DOUBLE, 0, 0, MPI_COMM_WORLD, &request);
14403                                 if (ierror != MPI_SUCCESS)
14404                                     return (ERROR);
14405                                 ierror = MPI_Waitall (1, &request, &status);
14406                                 if (ierror != MPI_SUCCESS)
14407                                     return (ERROR);
14408
14409                                 ierror = MPI_Isend (rateMult[k], nEvents[k], MPI_DOUBLE, 0, 0, MPI_COMM_WORLD, &request);
14410                                 if (ierror != MPI_SUCCESS)
14411                                     return (ERROR);
14412                                 ierror = MPI_Waitall (1, &request, &status);
14413                                 if (ierror != MPI_SUCCESS)
14414                                     return (ERROR);
14415
14416                                 free(position[k]);
14417                                 free(rateMult[k]);
14418                                 position[k] = NULL;
14419                                 rateMult[k] = NULL;
14420                                 nEvents[k] = 0;
14421                                 }
14422                             }
14423                         }
14424                     else if (proc_id == 0)
14425                         {
14426                         /* find pointers */
14427                         nEvents = p->nEvents[2*i];
14428                         position = p->position[2*i];
14429                         rateMult = p->rateMult[2*i];
14430
14431                         /* clear previous events */
14432                         for (k=0; k<2*numLocalTaxa; k++)
14433                             {
14434                             if (nEvents[k] > 0)
14435                                 {
14436                                 free (position[k]);
14437                                 free (rateMult[k]);
14438                                 position[k] = NULL;
14439                                 rateMult[k] = NULL;
14440                                 nEvents[k] = 0;
14441                                 }
14442                             }
14443
14444                         /* receive events */
14445                         ierror = MPI_Irecv (nEvents, 2*numLocalTaxa, MPI_INT, proc, 0, MPI_COMM_WORLD, &request);
14446                         if (ierror != MPI_SUCCESS)
14447                             return (ERROR);
14448                         ierror = MPI_Waitall (1, &request, &status);
14449                         if (ierror != MPI_SUCCESS)
14450                             return (ERROR);
14451
14452                         for (k=0; k<2*numLocalTaxa; k++)
14453                             {
14454                             if (nEvents[k] > 0)
14455                                 {
14456                                 position[k] = (MrBFlt *) SafeCalloc (nEvents[k], sizeof(MrBFlt));
14457                                 rateMult[k] = (MrBFlt *) SafeCalloc (nEvents[k], sizeof(MrBFlt));
14458
14459                                 ierror = MPI_Irecv (position[k], nEvents[k], MPI_DOUBLE, proc, 0, MPI_COMM_WORLD, &request);
14460                                 if (ierror != MPI_SUCCESS)
14461                                     return (ERROR);
14462                                 ierror = MPI_Waitall (1, &request, &status);
14463                                 if (ierror != MPI_SUCCESS)
14464                                     return (ERROR);
14465
14466                                 ierror = MPI_Irecv (rateMult[k], nEvents[k], MPI_DOUBLE, proc, 0, MPI_COMM_WORLD, &request);
14467                                 if (ierror != MPI_SUCCESS)
14468                                     return (ERROR);
14469                                 ierror = MPI_Waitall (1, &request, &status);
14470                                 if (ierror != MPI_SUCCESS)
14471                                     return (ERROR);
14472                                 }
14473                             }
14474                         }
14475                     }
14476                 }
14477             } 
14478         }
14479
14480     return (NO_ERROR);
14481 }
14482
14483
14484 int ReassembleSwapInfo (void)
14485 {
14486     int i, j, n, x, sum, ierror;
14487     
14488     for (n=0; n<chainParams.numRuns; n++)
14489         {
14490         for (i=0; i<chainParams.numChains; i++)
14491             {
14492             for (j=0; j<chainParams.numChains; j++)
14493                 {
14494                 if (i != j)
14495                     {
14496                     if (proc_id == 0)
14497                         x = 0;
14498                     else
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)
14502                         return (ERROR);
14503                     if (proc_id == 0)
14504                         swapInfo[n][i][j] += sum;
14505                     else
14506                         swapInfo[n][i][j] = 0;
14507                     }
14508                 }
14509             }
14510         }
14511
14512     return (NO_ERROR);
14513 }
14514
14515
14516 int ReassembleTuningParams (void)
14517 {
14518     int        i, j, k, lower, ierror;
14519     MrBFlt     *x, *sum;
14520     
14521     x = (MrBFlt *) SafeCalloc (2*numUsedMoves, sizeof(MrBFlt));
14522     sum = x + numUsedMoves;
14523
14524     lower = numGlobalChains / num_procs;
14525     if (numGlobalChains % num_procs != 0)
14526         lower++;
14527
14528     for (i=lower; i<numGlobalChains; i++)
14529         {
14530         for (j=0; j<numLocalChains; j++)
14531             {
14532             if (chainId[j] == i)
14533                 break;
14534             }
14535
14536         for (k=0; k<numUsedMoves; k++)
14537             {
14538             if (j != numLocalChains && usedMoves[k]->moveType->numTuningParams > 0) /* we have the tuning parameter of interest */
14539                 x[k] = usedMoves[k]->tuningParam[i][0];
14540             else
14541                 x[k] = 0.0;
14542             }
14543
14544         ierror = MPI_Allreduce (x, sum, numUsedMoves, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);
14545         if (ierror != MPI_SUCCESS)
14546             {
14547             free (x);
14548             return (ERROR);
14549             }
14550
14551         if (proc_id == 0)
14552             {
14553             for (k=0; k<numUsedMoves; k++)
14554                 {
14555                 if (usedMoves[k]->moveType->numTuningParams > 0)
14556                     usedMoves[k]->tuningParam[i][0] = sum[k];
14557                 }
14558             }
14559         }
14560
14561     free (x);
14562     return (NO_ERROR);
14563 }
14564
14565
14566 void RedistributeMoveInfo (void)
14567 {
14568     int         i, j, k;
14569     MCMCMove    *mv;
14570
14571     /* Leave if not processor 0, because then we already have the necessary info since
14572        it was not deleted in ReassembleMoveInfo */
14573     if (proc_id != 0)
14574         return;
14575
14576     /* If we are processor 0, simply delete the unnecessary information */
14577     for (i=0; i<numGlobalChains; i++)
14578         {
14579         for (j=0; j<numLocalChains; j++)
14580             if (chainId[j] == i)
14581                 break;
14582         
14583         if (j == numLocalChains)
14584             {
14585             /* we do not have this chain, so delete the move info */
14586             for (k=0; k<numUsedMoves; k++)
14587                 {
14588                 mv = usedMoves[k];
14589
14590                 /* reset counts */
14591                 mv->nAccepted[i] = 0;
14592                 mv->nTried[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;            
14599                 }
14600             }
14601         }
14602 }
14603
14604
14605 int RedistributeParamVals (void)
14606 {
14607     int             i, j, k, orderLen, nBrlens, lower, upper, numChainsForProc, proc, ierror, *y, *order, *nEvents;
14608     MrBFlt          *x, *brlens, **position, **rateMult;
14609     MPI_Status      status;
14610     MPI_Request     request;
14611     Tree            *tree;
14612     Param           *p;
14613
14614     extern MrBFlt   *paramValues;
14615     extern int      paramValsRowSize;
14616     extern int      intValsRowSize;
14617
14618     numChainsForProc = numGlobalChains / num_procs;
14619     if (numGlobalChains % num_procs > 0)
14620         lower = upper = numChainsForProc+1;
14621     else
14622         lower = upper = numChainsForProc;
14623
14624     for (proc=1; proc<num_procs; proc++, lower=upper)
14625         {
14626         if (proc < numGlobalChains % num_procs)
14627             upper += numChainsForProc+1;
14628         else
14629             upper += numChainsForProc;
14630         
14631         /* normal parameter values */
14632         if (proc_id == 0)
14633             {
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)
14637                 {
14638                 return (ERROR);
14639                 }
14640             ierror = MPI_Waitall (1, &request, &status);
14641             if (ierror != MPI_SUCCESS)
14642                 {
14643                 return (ERROR);
14644                 }
14645             if (intValsRowSize > 0)
14646                 {
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)
14650                     {
14651                     return (ERROR);
14652                     }
14653                 ierror = MPI_Waitall (1, &request, &status);
14654                 if (ierror != MPI_SUCCESS)
14655                     {
14656                     return (ERROR);
14657                     }
14658                 }
14659             }
14660         else if (proc_id == proc)
14661             {
14662             x = paramValues;
14663             ierror = MPI_Irecv (x, paramValsRowSize*2*(upper-lower), MPI_DOUBLE, 0, 0, MPI_COMM_WORLD, &request);
14664             if (ierror != MPI_SUCCESS)
14665                 {
14666                 return (ERROR);
14667                 }
14668             ierror = MPI_Waitall (1, &request, &status);
14669             if (ierror != MPI_SUCCESS)
14670                 {
14671                 return (ERROR);
14672                 }
14673             if (intValsRowSize > 0)
14674                 {
14675                 y = intValues;
14676                 ierror = MPI_Irecv (y, intValsRowSize*2*(upper-lower), MPI_INT, 0, 0, MPI_COMM_WORLD, &request);
14677                 if (ierror != MPI_SUCCESS)
14678                     {
14679                     return (ERROR);
14680                     }
14681                 ierror = MPI_Waitall (1, &request, &status);
14682                 if (ierror != MPI_SUCCESS)
14683                     {
14684                     return (ERROR);
14685                     }
14686                 }
14687             }
14688         
14689         /* mcmc trees */
14690         brlens = (MrBFlt *) SafeCalloc (2*numLocalTaxa, sizeof(MrBFlt));
14691         order  = (int *)    SafeCalloc (2*numLocalTaxa,   sizeof(int));
14692         for (i=lower; i<upper; i++)
14693             {
14694             for (j=0; j<numTrees; j++)
14695                 {
14696                 tree = GetTreeFromIndex(j,0,0);
14697                 orderLen = 2*tree->nIntNodes - 1;
14698                 nBrlens = tree->nNodes - 1;
14699                 if (proc_id == 0)
14700                     {
14701                     tree = GetTreeFromIndex(j,i,0);
14702                     if (tree->isRooted == YES)
14703                         StoreRTreeWithIndices(tree, order, brlens);
14704                     else
14705                         StoreUTree(tree, order, brlens);
14706                     ierror = MPI_Isend (order, orderLen, MPI_INT, proc, 0, MPI_COMM_WORLD, &request);
14707                     if (ierror != MPI_SUCCESS)
14708                         {
14709                         return (ERROR);
14710                         }
14711                     ierror = MPI_Waitall (1, &request, &status);
14712                     if (ierror != MPI_SUCCESS)
14713                         {
14714                         return (ERROR);
14715                         }
14716                     ierror = MPI_Isend (brlens, nBrlens, MPI_DOUBLE, proc, 0, MPI_COMM_WORLD, &request);
14717                     if (ierror != MPI_SUCCESS)
14718                         {
14719                         return (ERROR);
14720                         }
14721                    ierror = MPI_Waitall (1, &request, &status);
14722                    if (ierror != MPI_SUCCESS)
14723                         {
14724                         return (ERROR);
14725                         }
14726                     }
14727                 else if (proc_id == proc)
14728                     {
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)
14732                         {
14733                         return (ERROR);
14734                         }
14735                     ierror = MPI_Waitall (1, &request, &status);
14736                     if (ierror != MPI_SUCCESS)
14737                         {
14738                         return (ERROR);
14739                         }
14740                     ierror = MPI_Irecv (brlens, nBrlens, MPI_DOUBLE, 0, 0, MPI_COMM_WORLD, &request);
14741                     if (ierror != MPI_SUCCESS)
14742                         {
14743                         return (ERROR);
14744                         }
14745                     ierror = MPI_Waitall (1, &request, &status);
14746                     if (ierror != MPI_SUCCESS)
14747                         {
14748                         return (ERROR);
14749                         }
14750                     if (tree->isRooted == YES)
14751                         RetrieveRTreeWithIndices(tree, order, brlens);
14752                     else
14753                         {    
14754                         RetrieveUTree(tree, order, brlens);
14755                         if (localOutGroup != 0)
14756                             MoveCalculationRoot(tree,localOutGroup);
14757                         }
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);
14766                     }
14767                 }
14768             }
14769         free (brlens);
14770         free (order);
14771
14772         /* CPP relaxed clock  parameters */
14773         for (i=lower; i<upper; i++)
14774             {
14775             for (j=0; j<numParams; j++)
14776                 {
14777                 p = &params[j];
14778                 if (p->paramType == P_CPPEVENTS)
14779                     {
14780                     if (proc_id == 0)
14781                         {
14782                         /* get pointers */
14783                         nEvents = p->nEvents[2*i];
14784                         position = p->position[2*i];
14785                         rateMult = p->rateMult[2*i];
14786
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)
14790                             return (ERROR);
14791                         ierror = MPI_Waitall (1, &request, &status);
14792                         if (ierror != MPI_SUCCESS)
14793                             return (ERROR);
14794
14795                         /* send events and clear pointers */
14796                         for (k=0; k<2*numLocalTaxa; k++)
14797                             {
14798                             if (nEvents[k] > 0)
14799                                 {
14800                                 ierror = MPI_Isend (position[k], nEvents[k], MPI_DOUBLE, proc, 0, MPI_COMM_WORLD, &request);
14801                                 if (ierror != MPI_SUCCESS)
14802                                     return (ERROR);
14803                                 ierror = MPI_Waitall (1, &request, &status);
14804                                 if (ierror != MPI_SUCCESS)
14805                                     return (ERROR);
14806
14807                                 ierror = MPI_Isend (rateMult[k], nEvents[k], MPI_DOUBLE, proc, 0, MPI_COMM_WORLD, &request);
14808                                 if (ierror != MPI_SUCCESS)
14809                                     return (ERROR);
14810                                 ierror = MPI_Waitall (1, &request, &status);
14811                                 if (ierror != MPI_SUCCESS)
14812                                     return (ERROR);
14813
14814                                 free(position[k]);
14815                                 free(rateMult[k]);
14816                                 position[k] = NULL;
14817                                 rateMult[k] = NULL;
14818                                 nEvents[k] = 0;
14819                                 }
14820                             }
14821                         }
14822                     else if (proc_id == proc)
14823                         {
14824                         /* find pointers */
14825                         nEvents = p->nEvents[2*(i-lower)];
14826                         position = p->position[2*(i-lower)];
14827                         rateMult = p->rateMult[2*(i-lower)];
14828
14829                         /* clear previous events */
14830                         for (k=0; k<2*numLocalTaxa; k++)
14831                             {
14832                             if (nEvents[k] > 0)
14833                                 {
14834                                 free (position[k]);
14835                                 free (rateMult[k]);
14836                                 position[k] = NULL;
14837                                 rateMult[k] = NULL;
14838                                 nEvents[k] = 0;
14839                                 }
14840                             }
14841
14842                         /* receive events */
14843                         ierror = MPI_Irecv (nEvents, 2*numLocalTaxa, MPI_INT, 0, 0, MPI_COMM_WORLD, &request);
14844                         if (ierror != MPI_SUCCESS)
14845                             return (ERROR);
14846                         ierror = MPI_Waitall (1, &request, &status);
14847                         if (ierror != MPI_SUCCESS)
14848                             return (ERROR);
14849                         for (k=0; k<2*numLocalTaxa; k++)
14850                             {
14851                             if (nEvents[k] > 0)
14852                                 {
14853                                 position[k] = (MrBFlt *) SafeCalloc (nEvents[k], sizeof(MrBFlt));
14854                                 rateMult[k] = (MrBFlt *) SafeCalloc (nEvents[k], sizeof(MrBFlt));
14855
14856                                 ierror = MPI_Irecv (position[k], nEvents[k], MPI_DOUBLE, 0, 0, MPI_COMM_WORLD, &request);
14857                                 if (ierror != MPI_SUCCESS)
14858                                     return (ERROR);
14859                                 ierror = MPI_Waitall (1, &request, &status);
14860                                 if (ierror != MPI_SUCCESS)
14861                                     return (ERROR);
14862
14863                                 ierror = MPI_Irecv (rateMult[k], nEvents[k], MPI_DOUBLE, 0, 0, MPI_COMM_WORLD, &request);
14864                                 if (ierror != MPI_SUCCESS)
14865                                     return (ERROR);
14866                                 ierror = MPI_Waitall (1, &request, &status);
14867                                 if (ierror != MPI_SUCCESS)
14868                                     return (ERROR);
14869                                 }
14870                             }
14871                        }
14872                    }
14873                 }
14874             }
14875
14876         /* update evolutionary branch lengths or rates (because node indices have changed) */
14877         if (proc_id == proc)
14878             {
14879             for (i=0; i<upper-lower; i++)
14880                 {
14881                 for (j=0; j<numParams; j++)
14882                     {
14883                     p = &params[j];
14884                     if (p->paramType == P_CPPEVENTS)
14885                         {
14886                         tree = GetTree(p, i, 0);
14887                         UpdateCppEvolLengths (p, tree->root->left, i);
14888                         }
14889                     else if (p->paramType == P_TK02BRANCHRATES || (p->paramType == P_MIXEDBRCHRATES && *GetParamIntVals(p, i, 0) == RCL_TK02))
14890                         {
14891                         tree = GetTree (p, i, 0);
14892                         UpdateTK02EvolLengths (p, tree, i);
14893                         }
14894                     else if (p->paramType == P_IGRBRANCHRATES || (p->paramType == P_MIXEDBRCHRATES && *GetParamIntVals(p, i, 0) == RCL_IGR))
14895                         {
14896                         tree = GetTree(p, i, 0);
14897                         UpdateIgrBrachLengths (p, tree, i);
14898                         }
14899                     }
14900                 }
14901             }
14902         }
14903
14904     return (NO_ERROR);
14905 }
14906
14907
14908 int RedistributeTuningParams (void)
14909 {
14910     int     i, j, k, lower, ierror;
14911     MrBFlt  *x, *sum;
14912     
14913     x = (MrBFlt *) SafeCalloc (2*numUsedMoves, sizeof(MrBFlt));
14914     sum = x + numUsedMoves;
14915
14916     lower = numGlobalChains / num_procs;
14917     if (numGlobalChains % num_procs != 0)
14918         lower++;
14919
14920     if (proc_id != 0)
14921         {
14922         for (i=0; i<numGlobalChains; i++)
14923             {
14924             for (k=0; k<numUsedMoves; k++)
14925                                 {
14926                                 if (usedMoves[k]->moveType->numTuningParams > 0)
14927                         usedMoves[k]->tuningParam[i][0] = 0.0;
14928                                 }
14929         }
14930         }
14931
14932     for (i=lower; i<numGlobalChains; i++)
14933         {
14934         for (j=0; j<numLocalChains; j++)
14935             {
14936             if (chainId[j] == i)
14937                 break;
14938             }
14939
14940         for (k=0; k<numUsedMoves; k++)
14941             {
14942             if (proc_id == 0 && usedMoves[k]->moveType->numTuningParams > 0) /* we have the tuning parameter of interest */
14943         {
14944                 x[k] = usedMoves[k]->tuningParam[i][0];
14945         usedMoves[k]->tuningParam[i][0]=0.0;
14946         }
14947             else
14948                 x[k] = 0.0;
14949         }
14950
14951         ierror = MPI_Allreduce (x, sum, numUsedMoves, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);
14952         if (ierror != MPI_SUCCESS)
14953             {
14954             free (x);
14955             return (ERROR);
14956             }
14957
14958         if (j != numLocalChains)   /* we have the chain of interest */
14959             {
14960             for (k=0; k<numUsedMoves; k++)
14961                 {
14962                 if (usedMoves[k]->moveType->numTuningParams > 0)
14963                     usedMoves[k]->tuningParam[i][0] = sum[k];
14964                 }
14965             }
14966         }
14967
14968     free (x);
14969     return (NO_ERROR);
14970 }
14971
14972 #endif
14973
14974
14975 /* RemovePartition: Remove a partition from the tree keeping track of partition frequencies */
14976 int RemovePartition (PFNODE *r, BitsLong *p, int runId)
14977 {
14978     int     i, comp;
14979     
14980     if (r == NULL)
14981         {
14982         return (ERROR);
14983         }
14984     else
14985         {
14986         for (i=0; i<nLongsNeeded; i++)
14987             {
14988             if (r->partition[i] != p[i])
14989                 break;
14990             }
14991         
14992         if (i == nLongsNeeded)
14993             comp = 0;
14994         else if (r->partition[i] < p[i])
14995             comp = -1;
14996         else
14997             comp = 1;
14998         
14999         if (comp == 0)          /* match */
15000             {
15001             if (r->count[runId] == 0)
15002                 return ERROR;
15003             else
15004                 r->count[runId]--;
15005             }
15006         else if (comp < 0)      /* greater than -> into left subtree */
15007             {
15008             if ((RemovePartition (r->left, p, runId)) == ERROR)
15009                 return ERROR;
15010             }
15011         else
15012             {
15013             /* less than -> into right subtree */
15014             if ((RemovePartition (r->right, p, runId)) == ERROR)
15015                 return ERROR;
15016             }
15017         }
15018
15019     return (NO_ERROR);
15020 }
15021
15022
15023 /* RemoveTreeFromPartitionCounters: Break a tree into partitions and remove those from counters */
15024 int RemoveTreeFromPartitionCounters (Tree *tree, int treeId, int runId)
15025 {
15026     int         i, j, nTaxa;
15027     TreeNode    *p;
15028
15029     if (tree->isRooted == YES)
15030         nTaxa = tree->nNodes - tree->nIntNodes - 1;
15031     else
15032         nTaxa = tree->nNodes - tree->nIntNodes;
15033
15034     for (i=0; i<nTaxa; i++)
15035         {
15036         ClearBits(partition[i], nLongsNeeded);
15037         SetBit(i, partition[i]);
15038         }
15039
15040     for (i=0; i<tree->nIntNodes-1; i++)
15041         {
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++)
15045             {
15046             partition[p->index][j] = partition[p->left->index][j] | partition[p->right->index][j];
15047             }
15048         
15049         if ((RemovePartition (partFreqTreeRoot[treeId], partition[p->index], runId)) == ERROR)
15050             {
15051             MrBayesPrint ("%s   Could not remove partition %d in RemoveTreeFromPartitionCounters\n", spacer, p->index);
15052             ShowParts(stdout,partition[p->index],numLocalTaxa);
15053             return ERROR;
15054             }
15055         }
15056
15057     return NO_ERROR;
15058 }
15059
15060
15061 /* RemoveTreeSamples: Remove tree samples from partition counters */
15062 int RemoveTreeSamples (int from, int to)
15063 {
15064     int         i, j, k, longestLine, line;
15065     char        c, *s, *lineBuf=0;
15066     FILE        *fp;
15067     Tree        *t;
15068     TreeList    *treeList;
15069     char        *tempStr;
15070     int         tempStrSize = TEMPSTRSIZE;
15071
15072 #   if defined (MPI_ENABLED)
15073     if (proc_id != 0)
15074         return (NO_ERROR);
15075 #   endif
15076
15077     tempStr = (char *) SafeMalloc((size_t)tempStrSize * sizeof(char));
15078     if (!tempStr)
15079         {
15080         MrBayesPrint ("%s   Problem allocating tempString (%d)\n", spacer, tempStrSize * sizeof(char));
15081         return (ERROR);
15082         }
15083
15084     if (chainParams.saveTrees == YES)
15085         {
15086         for (i=0; i<numTopologies; i++)
15087             {
15088             t = chainParams.dtree;
15089             if (topologyParam[i]->tree[0]->isRooted == YES)
15090                 t->isRooted = YES;
15091             else
15092                 t->isRooted = NO;
15093
15094             for (j=0; j<chainParams.numRuns; j++)
15095                 {               
15096                 treeList = &chainParams.treeList[j*numTopologies + i];
15097                 
15098                 for (k=from; k<=to; k++)
15099                     {
15100                     GetFromTreeList (treeList, t);
15101                     if (RemoveTreeFromPartitionCounters (t, i, j) == ERROR)
15102                         {
15103                         SafeFclose (&fp);
15104                         free (tempStr);
15105                         free (lineBuf);
15106                         return (ERROR);
15107                         }
15108                     }
15109                 }
15110             }
15111         }
15112     else
15113         {
15114         for (i=0; i<numTopologies; i++)
15115             {
15116             t = chainParams.dtree;
15117
15118             for (j=0; j<chainParams.numRuns; j++)
15119                 {
15120                 if (numPrintTreeParams == 1)
15121                     {
15122                     if (chainParams.numRuns == 1)
15123                         SafeSprintf (&tempStr, &tempStrSize, "%s.t", chainParams.chainFileName);
15124                     else
15125                         SafeSprintf (&tempStr, &tempStrSize, "%s.run%d.t", chainParams.chainFileName, j+1);
15126                     }
15127                 else
15128                     {
15129                     if (chainParams.numRuns == 1)
15130                         SafeSprintf (&tempStr, &tempStrSize, "%s.tree%d.t", chainParams.chainFileName, topologyPrintIndex[i]+1);
15131                     else
15132                         SafeSprintf (&tempStr, &tempStrSize, "%s.tree%d.run%d.t", chainParams.chainFileName, topologyPrintIndex[i]+1, j+1);
15133                     }
15134
15135                 if ((fp = OpenTextFileR (tempStr)) == NULL)
15136                         {
15137                         free (tempStr);
15138                         return (ERROR);
15139                         }
15140                 
15141                 if (from == 1)
15142                     {
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]);
15148                     free(lineBuf);
15149                     lineBuf = NULL;
15150                     }
15151                 fsetpos (fp, &chainParams.tFilePos[j*numTopologies+i]);
15152
15153                 longestLine = 0;
15154                 for (k=0; k<=to-from; k++)
15155                     {
15156                     line = 0;
15157                     do {
15158                         line++;
15159                         } while ((c = fgetc(fp)) != '\r' && c != '\n');
15160                     
15161                     if (line > longestLine)
15162                         longestLine = line;
15163                     
15164                     while ((c = fgetc(fp)) == '\r' || c == '\n')
15165                         ;
15166                     }
15167
15168                 lineBuf = (char *) SafeCalloc (longestLine + 10, sizeof (char));
15169                 if (!lineBuf)
15170                     {
15171                     SafeFclose (&fp);
15172                     free (tempStr);
15173                     return (ERROR);
15174                     }
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');
15182
15183                 for (k=from; k<=to; k++)
15184                     {
15185                     if (fgets (lineBuf, longestLine + 5, fp) == NULL) 
15186                         {
15187                         free (tempStr);
15188                         free (lineBuf);
15189                         return ERROR;
15190                         }
15191
15192                     s = strtok (lineBuf, " ");
15193                     for (s = strtok (NULL, ";"); *s != '('; s++)
15194                         ;
15195                     
15196                     StripComments (s);
15197                     if (ResetTopology (t, s) == ERROR)
15198                         {
15199                         SafeFclose (&fp);
15200                         free (tempStr);
15201                         free (lineBuf);
15202                         return (ERROR);
15203                         }
15204                     
15205                     if (RemoveTreeFromPartitionCounters (t, i, j) == ERROR)
15206                         {
15207                         SafeFclose (&fp);
15208                         free (tempStr);
15209                         free (lineBuf);
15210                         return (ERROR);
15211                         }
15212                     }
15213                 fgetpos (fp, &chainParams.tFilePos[j*numTopologies+i]);
15214                 free (lineBuf);
15215                 SafeFclose (&fp);
15216                 }
15217             }
15218         }
15219
15220     /* remove unnecessary nodes from the tree holding partition counters */
15221     for (i=0; i<numTopologies; i++)
15222         {
15223         partFreqTreeRoot[i] = CompactTree (partFreqTreeRoot[i]);
15224         }
15225
15226     free (tempStr);
15227     return (NO_ERROR);
15228 }
15229
15230
15231 int ReopenMBPrintFiles (void)
15232 {
15233     int     i, n;
15234     char    fileName[120], localFileName[100];
15235     
15236     /* Take care of the mpi procs that do not have a file */
15237 #   if defined (MPI_ENABLED)
15238     if (proc_id != 0)
15239         return (NO_ERROR);
15240 #   endif
15241
15242     /* Get root of local file name */
15243     strcpy (localFileName, chainParams.chainFileName);
15244
15245     /* Reopen the .p and .t files */
15246     for (n=0; n<chainParams.numRuns; n++)
15247         {
15248         if (chainParams.numRuns == 1)
15249             sprintf (fileName, "%s.p", localFileName);
15250         else
15251             sprintf (fileName, "%s.run%d.p", localFileName, n+1);
15252
15253         if ((fpParm[n] = OpenTextFileA (fileName)) == NULL)
15254             return (ERROR);
15255
15256         for (i=0; i<numTrees; i++)
15257             {
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);
15264             else
15265                 sprintf (fileName, "%s.tree%d.run%d.t", localFileName, i+1, n+1);
15266
15267             if ((fpTree[n][i] = OpenTextFileA (fileName)) == NULL)
15268                 return (ERROR);
15269             }
15270         }
15271
15272     /* Reopen the .mcmc file */
15273     if (chainParams.mcmcDiagn == YES)
15274         {
15275         sprintf (fileName, "%s.mcmc", localFileName);
15276
15277         if ((fpMcmc = OpenTextFileA (fileName)) == NULL)
15278             return (ERROR);
15279         }
15280     
15281 #   if defined (PRINT_DUMP)
15282     for (n=0; n<chainParams.numRuns; n++)
15283         {
15284         if (chainParams.numRuns == 1)
15285             sprintf (fileName, "%s.dump", localFileName);
15286         else
15287             sprintf (fileName, "%s.run%d.dump", localFileName, n+1);
15288
15289         if ((fpDump[n] = OpenTextFileA (fileName)) == NULL)
15290             return (ERROR);
15291         }
15292 #   endif
15293
15294     return (NO_ERROR);
15295 }
15296
15297
15298 int ConfirmAbortRun(void)
15299 {
15300     char c, line[100];
15301     int  ret=0, i;
15302
15303     /* reset requestAbortRun */
15304     requestAbortRun = NO;
15305
15306     MrBayesPrint("   Do you really want to stop the run (y/n)?");
15307     if (fgets (line,98,stdin) == NULL)
15308         {
15309         printf ("Error in function: %s at line: %d in file: %s", __FUNCTION__, __LINE__, __FILE__);
15310         }
15311     for (i=0; (c=line[i])!='\0' && !isgraph(c); i++)
15312         ;
15313     if (c == 'y' || c == 'Y')
15314         ret=1;
15315     else 
15316         {
15317         MrBayesPrint("   Mcmc run continued ...\n\n");
15318         ret=0;
15319         }
15320     return ret;
15321 }
15322
15323
15324 /*-------------------------------------------------------------------
15325 |
15326 |   ResetChainIds: Make sure parameter values are swapped back 
15327 |       at the end of a Metropolis-coupled MCMC run
15328 |
15329 --------------------------------------------------------------------*/
15330 void ResetChainIds (void)
15331 {
15332     int     j, k, k1, tempId, *curId, toChn, fromChn, *to, *from, *swap;
15333     Param   *p;
15334     MrBFlt  *fromVals, *toVals, *swapVals, **fromPosition, **toPosition,
15335             **swapPosition, **fromRateMult, **toRateMult, **swapRateMult;
15336     Tree    *toTree, *fromTree, *swapTree;
15337
15338     curId = (int *) SafeCalloc (numGlobalChains, sizeof(int));
15339
15340 #if defined (MPI_ENABLED)
15341     ReassembleParamVals(curId);
15342     ReassembleTuningParams();
15343     SetChainIds();
15344     if (proc_id != 0)
15345     {
15346         /* reset state */
15347         for (j=0; j<numLocalChains; j++)
15348             state[j] = 0;
15349         free (curId);
15350     return;
15351         }
15352 #else
15353     for (j=0; j<numGlobalChains; j++)
15354         curId[j] = chainId[j];
15355     SetChainIds();
15356 #endif
15357     
15358     for (toChn=0; toChn<numGlobalChains; toChn++)
15359         {
15360         if (curId[toChn] == toChn)
15361             {
15362             if (state[toChn] != 0)
15363                 {
15364                 CopyParams (toChn);
15365                 CopyTrees (toChn);
15366                 state[toChn] ^= 1;
15367                 }
15368             continue;
15369             }
15370
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)
15375                 break;
15376         fromChn = j;
15377
15378         /* normal params */
15379         CopyParams (toChn);
15380         CopyTrees (toChn);
15381         CopyParams (fromChn);
15382         CopyTrees (fromChn);
15383
15384         for (j=0; j<numParams; j++)
15385             {
15386             p = &params[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++)
15391                 {
15392                 toVals[k] = fromVals[k];
15393                 fromVals[k] = swapVals[k];
15394                 }
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++)
15399                 {
15400                 toVals[k] = fromVals[k];
15401                 fromVals[k] = swapVals[k];
15402                 }
15403             if (p->nStdStateFreqs > 0)
15404                 {
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++)
15409                     {
15410                     toVals[k] = fromVals[k];
15411                     fromVals[k] = swapVals[k];
15412                     }
15413                 }
15414             }
15415
15416         /* mcmc trees */
15417         for (j=0; j<numTrees; j++)
15418             {
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);
15427             }
15428         /* CPP relaxed clock params */
15429         for (j=0; j<numParams; j++)
15430             {
15431             p = &params[j];
15432             if (p->paramType == P_CPPEVENTS)
15433                 {
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++)
15444                     {
15445                     if (from[k] > 0)
15446                         {
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++)
15450                             {
15451                             toPosition[k][k1] = fromPosition[k][k1];
15452                             toRateMult[k][k1] = fromRateMult[k][k1];
15453                             }
15454                         }
15455                     else if (to[k] > 0)
15456                         {
15457                         free (toPosition[k]);
15458                         toPosition[k] = NULL;
15459                         free (toRateMult[k]);
15460                         toRateMult[k] = NULL;
15461                         }
15462                     to[k] = from[k];
15463                     if (swap[k] > 0)
15464                         {
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++)
15468                             {
15469                             fromPosition[k][k1] = swapPosition[k][k1];
15470                             fromRateMult[k][k1] = swapRateMult[k][k1];
15471                             }
15472                         }
15473                     else if (from[k] > 0)
15474                         {
15475                         free (fromPosition[k]);
15476                         fromPosition[k] = NULL;
15477                         free (fromRateMult[k]);
15478                         fromRateMult[k] = NULL;
15479                         }
15480                     from[k] = swap[k];
15481                     }
15482                 }   
15483             }
15484         /* reset state of chain */
15485         state[toChn] = 0;
15486
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;
15491         }
15492
15493     free (curId);
15494 }
15495
15496
15497 /* ResetFlips: Reset flipped cond likes etc after rejection */
15498 void ResetFlips (int chain)
15499 {
15500     int         d, i;
15501     ModelInfo   *m;
15502     TreeNode    *p;
15503     Tree        *tree;
15504 #if defined (BEAGLE_ENABLED)
15505     int         *isScalerNode=NULL;
15506 #endif    
15507     
15508     for (d=0; d<numCurrentDivisions; d++)
15509     {
15510         m = &modelSettings[d];
15511 #if defined (BEAGLE_ENABLED)
15512         if (m->useBeagle == YES)
15513             isScalerNode = m->isScalerNode[chain];
15514 #endif
15515         if (m->upDateCl != YES)
15516             continue;
15517         
15518 #if defined (BEAGLE_ENABLED)
15519         if (m->useBeagle == NO || 
15520             beagleScalingScheme == MB_BEAGLE_SCALE_ALWAYS ||
15521             m->rescaleBeagleAll == YES)
15522                 {
15523                 FlipSiteScalerSpace (m, chain);
15524                 if (m->useBeagle == YES && m->rescaleBeagleAll == YES)
15525                     m->rescaleFreq[chain] = m->rescaleFreqOld;
15526                 }
15527 #else
15528         FlipSiteScalerSpace (m, chain);
15529 #endif
15530             
15531         
15532         if (m->upDateCijk == YES && m->nCijkParts > 0)
15533             FlipCijkSpace (m, chain);
15534         
15535         /* cycle over tree */
15536         tree = GetTree (m->brlens, chain, state[chain]);
15537         for (i=0; i<tree->nNodes; i++)
15538             {
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 */
15543                 {
15544                 if (p->upDateCl == YES)
15545                     {
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);
15552 #else
15553                     FlipNodeScalerSpace (m, chain, p->index);
15554 #endif
15555                     }
15556 #if defined (BEAGLE_ENABLED)
15557                 else if (m->rescaleBeagleAll == YES)
15558                     {
15559                     FlipCondLikeSpace (m, chain, p->index);
15560                     if (isScalerNode[p->index] == YES)
15561                         FlipNodeScalerSpace (m, chain, p->index);
15562                     }
15563 #endif
15564                 }
15565             }
15566         
15567         /* division flag and tree node flags are reset when trees are copied */
15568     }
15569 }
15570
15571
15572 /*-------------------------------------------------------------------
15573 |
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]
15578 |
15579 | @param rescaleFreq    effectively represent gaps between rescaling, higher number means more sparse choice of rescaling nodes 
15580 |
15581 --------------------------------------------------------------------*/
15582 int ResetScalersPartition (int *isScalerNode, Tree* t, unsigned rescaleFreq)
15583 {
15584     int         n;
15585     TreeNode    *p;
15586         
15587     /* set the node depth value of terminal nodes to zero; reset scalerNode */
15588     for (n=0; n<t->nNodes; n++)
15589         {
15590         p = t->allDownPass[n];
15591         if (p->left == NULL)
15592             p->x = 0;
15593         }
15594
15595     /* loop over interior nodes */
15596     for (n=0; n<t->nIntNodes; n++)
15597         {
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;
15601
15602         if (p->x > 2 * (int)rescaleFreq)
15603             {
15604             assert (p->left->left != NULL && p->right->left != NULL);
15605             isScalerNode[p->left->index] = YES;
15606             p->left->x = 0;
15607             isScalerNode[p->right->index] = YES;
15608             p->right->x = 0;
15609             p->x = 1;
15610             }
15611         else if (p->x > (int)rescaleFreq)
15612             {
15613             if (p->left->x > p->right->x)
15614                 {
15615                 assert (p->left->left != NULL);
15616                 isScalerNode[p->left->index] = YES;
15617                 p->left->x = 0;
15618                 }
15619             else
15620                 {
15621                 assert (p->right->left != NULL);
15622                 isScalerNode[p->right->index] = YES;
15623                 p->right->x = 0;
15624                 }
15625             p->x = p->left->x + p->right->x + 1;
15626             }
15627         else
15628             isScalerNode[p->index] = NO;
15629         }
15630
15631     return NO_ERROR;
15632 }
15633
15634
15635 /*-------------------------------------------------------------------
15636 |
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
15640 |
15641 --------------------------------------------------------------------*/
15642 int ResetScalers (void)
15643 {
15644     int         i, n, chn;
15645     Tree        *t;
15646     TreeNode    *p;
15647
15648 #if defined (DEBUG_NOSCALING)
15649     return (NO_ERROR);
15650 #endif
15651
15652     for (chn=0; chn<numLocalChains; chn++)
15653         {
15654         for (i=0; i<numTrees; i++)
15655             {
15656             t = GetTreeFromIndex (i, chn, state[chn]);
15657         
15658             /* set the node depth value of terminal nodes to zero; reset scalerNode */
15659             for (n=0; n<t->nNodes; n++)
15660                 {
15661                 p = t->allDownPass[n];
15662                 p->scalerNode = NO;
15663                 if (p->left == NULL)
15664                     p->x = 0;
15665                 }
15666
15667             /* loop over interior nodes */
15668             for (n=0; n<t->nIntNodes; n++)
15669                 {
15670                 p = t->intDownPass[n];
15671
15672                 p->x = p->left->x + p->right->x + 1;
15673
15674                 if (p->x > 2 * RESCALE_FREQ)
15675                     {
15676                     assert (p->left->left != NULL && p->right->left != NULL);
15677                     p->left->scalerNode = YES;
15678                     p->left->x = 0;
15679                     p->right->scalerNode = YES;
15680                     p->right->x = 0;
15681                     p->x = 1;
15682                     }
15683                 else if (p->x > RESCALE_FREQ)
15684                     {
15685                     if (p->left->x > p->right->x)
15686                         {
15687                         assert (p->left->left != NULL);
15688                         p->left->scalerNode = YES;
15689                         p->left->x = 0;
15690                         }
15691                     else
15692                         {
15693                         assert (p->right->left != NULL);
15694                         p->right->scalerNode = YES;
15695                         p->right->x = 0;
15696                         }
15697                     p->x = p->left->x + p->right->x + 1;
15698                     }
15699                 else
15700                     p->scalerNode = NO;
15701                 }
15702             }
15703         }
15704
15705     return NO_ERROR;
15706 }
15707
15708
15709 void ResetSiteScalers (ModelInfo *m, int chain)
15710 {
15711     int     c;
15712     CLFlt   *lnScaler;
15713
15714 #if defined (BEAGLE_ENABLED)
15715     if (m->useBeagle == YES)
15716         {
15717         beagleResetScaleFactors(m->beagleInstance, m->siteScalerIndex[chain]);
15718         return;
15719         }
15720 #endif
15721     lnScaler = m->scalers[m->siteScalerIndex[chain]];
15722     for (c=0; c<m->numChars; c++)
15723         lnScaler[c] = 0.0;
15724 }
15725
15726
15727 /*----------------------------------------------------------------------
15728 |
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
15732 |
15733 ------------------------------------------------------------------------*/
15734 int ReusePreviousResults (int *numSamples, int steps)
15735 {
15736     int         i, n;
15737     char        localFileName[100], fileName[220], bkupName[220];
15738
15739     (*numSamples) = 0;
15740
15741 #   if defined (MPI_ENABLED)
15742     if (proc_id != 0)
15743         return (NO_ERROR);
15744 #   endif
15745
15746     /* Allocate space for file pointers */
15747     if (memAllocs[ALLOC_FILEPOINTERS] == YES)
15748         {
15749         MrBayesPrint ("%s   File pointers already allocated in ReusePreviousResults\n", spacer);
15750         return ERROR;
15751         }
15752     fpMcmc = NULL;
15753     fpSS = NULL;
15754     fpParm = NULL;
15755     fpTree = NULL;  
15756     fpParm = (FILE **) SafeCalloc (chainParams.numRuns, sizeof (FILE *));
15757     if (fpParm == NULL)
15758         {
15759         MrBayesPrint ("%s   Could not allocate fpParm in ReusePreviousResults\n", spacer);
15760         return ERROR;
15761         }
15762     memAllocs[ALLOC_FILEPOINTERS] = YES;
15763     fpTree = (FILE ***) SafeCalloc (chainParams.numRuns, sizeof (FILE **));
15764     if (fpTree == NULL)
15765         {
15766         MrBayesPrint ("%s   Could not allocate fpTree in ReusePreviousResults\n", spacer);
15767         return ERROR;
15768         }
15769     fpTree[0] = (FILE **) SafeCalloc (numTrees*chainParams.numRuns, sizeof (FILE *));
15770     if (fpTree[0] == NULL)
15771         {
15772         MrBayesPrint ("%s   Could not allocate fpTree[0] in ReusePreviousResults\n", spacer);
15773         return ERROR;
15774         }
15775     for (i=1; i<chainParams.numRuns; i++)
15776         fpTree[i] = fpTree[0] + i*numTrees;
15777
15778     /* Get root of local file name */
15779     strcpy (localFileName, chainParams.chainFileName);
15780
15781     /* Store old and prepare new .p and .t files */
15782     for (n=0; n<chainParams.numRuns; n++)
15783         {
15784         if (chainParams.numRuns == 1)
15785             sprintf (fileName, "%s%s.p", workingDir, localFileName);
15786         else
15787             sprintf (fileName, "%s%s.run%d.p", workingDir, localFileName, n+1);
15788         strcpy(bkupName,fileName);
15789         strcat(bkupName,"~");
15790         remove(bkupName);
15791         if (rename(fileName,bkupName) != 0)
15792             {
15793             MrBayesPrint ("%s   Could not rename file %s\n", spacer, fileName);
15794             return ERROR;
15795             }
15796
15797         if ((fpParm[n] = OpenNewMBPrintFile (fileName+strlen(workingDir))) == NULL)
15798             return (ERROR);
15799         else if (CopyResults(fpParm[n],bkupName+strlen(workingDir),numPreviousGen) == ERROR)
15800             return (ERROR);
15801
15802         for (i=0; i<numTrees; i++)
15803             {
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);
15810             else
15811                 sprintf (fileName, "%s%s.tree%d.run%d.t", workingDir, localFileName, i+1, n+1);
15812             strcpy(bkupName,fileName);
15813             strcat(bkupName,"~");
15814             remove(bkupName);
15815             if (rename(fileName,bkupName) != 0)
15816                 {
15817                 MrBayesPrint ("%s   Could not rename file %s\n", spacer, fileName);
15818                 return ERROR;
15819                 }
15820             if ((fpTree[n][i] = OpenNewMBPrintFile (fileName+strlen(workingDir))) == NULL)
15821                 return (ERROR);
15822             else if (CopyTreeResults(fpTree[n][i],bkupName+strlen(workingDir),numPreviousGen,numSamples) == ERROR)
15823                 return (ERROR);
15824             }
15825         }
15826
15827     /* Store old and prepare new .ss file */
15828     if (chainParams.isSS == YES)
15829         {
15830         sprintf (fileName, "%s%s.ss", workingDir, chainParams.chainFileName);
15831         strcpy(bkupName,fileName);
15832         strcat(bkupName,"~");
15833         remove(bkupName);
15834         if (rename(fileName,bkupName) != 0)
15835             {
15836             MrBayesPrint ("%s   Could not rename file %s\n", spacer, fileName);
15837             return ERROR;
15838             }
15839         if ((fpSS = OpenNewMBPrintFile (fileName+strlen(workingDir))) == NULL)
15840             return (ERROR);
15841         else if (CopyProcessSsFile(fpSS,bkupName+strlen(workingDir),steps,marginalLnLSS,splitfreqSS)==ERROR)
15842             return (ERROR);
15843         }
15844
15845     /* Store old and prepare new .mcmc file */
15846     if (chainParams.mcmcDiagn == YES)
15847         {
15848         sprintf (fileName, "%s%s.mcmc", workingDir, chainParams.chainFileName);
15849         strcpy(bkupName,fileName);
15850         strcat(bkupName,"~");
15851         remove(bkupName);
15852         if (rename(fileName,bkupName) != 0)
15853             {
15854             MrBayesPrint ("%s   Could not rename file %s\n", spacer, fileName);
15855             return ERROR;
15856             }
15857         if ((fpMcmc = OpenNewMBPrintFile (fileName+strlen(workingDir))) == NULL)
15858             return (ERROR);
15859         else if (CopyResults(fpMcmc,bkupName+strlen(workingDir),numPreviousGen)==ERROR)
15860             return (ERROR);
15861         }
15862     
15863 #   if defined (PRINT_DUMP)
15864     fpDump = (FILE **) SafeCalloc (chainParams.numRuns, sizeof (FILE *));
15865     
15866     for (n=0; n<chainParams.numRuns; n++)
15867         {
15868         if (chainParams.numRuns == 1)
15869             sprintf (fileName, "%s.dump", localFileName);
15870         else
15871             sprintf (fileName, "%s.run%d.dump", localFileName, n+1);
15872         
15873         if ((fpDump[n] = OpenTextFileA (fileName)) == NULL)
15874             return (ERROR);
15875     }
15876 #   endif
15877
15878     return (NO_ERROR);
15879 }
15880
15881
15882 int RunChain (RandLong *seed)
15883 {
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];
15896
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;
15901 #       endif
15902     ModelInfo   *m;
15903     ResetScalersNeeded = NO;
15904     
15905     for (i=0; i<numCurrentDivisions; i++)
15906         {
15907         m = &modelSettings[i];
15908         if (m->useBeagle == NO || beagleScalingScheme == MB_BEAGLE_SCALE_ALWAYS)
15909             {
15910             ResetScalersNeeded =YES;
15911             break;
15912             }
15913         }
15914 #   endif
15915
15916 #   if defined (MPI_ENABLED)
15917     int         ierror, sumErrors;
15918     MrBFlt      best, sum=0.0;
15919     MPI_Status  status;
15920 #   endif
15921 #   if defined (DEBUG_RUNCHAIN)
15922     ModelInfo   *m;
15923 #   endif
15924     
15925     /* set nErrors to 0 */
15926     nErrors = 0;
15927     if (numLocalTaxa < 4)
15928         {
15929         for (i=0; i<numTrees; i++)
15930             if (GetTreeFromIndex(i, 0, 0)->isRooted == NO)
15931                 break;
15932         if (i < numTrees && numLocalTaxa < 4)
15933             {
15934             MrBayesPrint ("%s   There must be at least four taxa in the analysis\n", spacer);
15935             return (ERROR);
15936             }
15937         else if (i == numTrees && numLocalTaxa < 3)
15938             {
15939             MrBayesPrint ("%s   There must be at least three taxa in the analysis\n", spacer);
15940             return (ERROR);
15941             }
15942         }
15943
15944     /* allocate some memory for the chains */
15945     if (memAllocs[ALLOC_CURLNL] == YES)
15946         {
15947         MrBayesPrint ("%s   curLnL is already allocated\n", spacer);
15948         nErrors++;
15949         }
15950     else if ((curLnL = (MrBFlt *)SafeMalloc((size_t)numLocalChains * sizeof(MrBFlt))) == NULL)
15951         {
15952         MrBayesPrint ("%s   Problem allocating curLnL (%d)\n", spacer, numLocalChains * sizeof(MrBFlt));
15953         nErrors++;
15954         }
15955     else if ((maxLnL0 = (MrBFlt *) SafeCalloc ((size_t)(chainParams.numRuns) * (size_t)(chainParams.numChains), sizeof(MrBFlt))) == NULL)
15956         {
15957         MrBayesPrint ("%s   Problem allocating maxLnL0\n", spacer, numLocalChains * sizeof(MrBFlt));
15958         free (curLnL);
15959         nErrors++;
15960         }
15961     else
15962         memAllocs[ALLOC_CURLNL] = YES;
15963 #   if defined (MPI_ENABLED)
15964     MPI_Allreduce (&nErrors, &sumErrors, 1, MPI_INT, MPI_SUM, MPI_COMM_WORLD);
15965     if (sumErrors > 0)
15966         {
15967         MrBayesPrint ("%s   Memory allocation error on at least one processor\n", spacer);
15968         return ERROR;
15969         }
15970 #   else
15971     if (nErrors > 0)
15972         return ERROR;
15973 #   endif
15974
15975     if (memAllocs[ALLOC_CURLNPR] == YES)
15976         {
15977         MrBayesPrint ("%s   curLnPr is already allocated\n", spacer);
15978         nErrors++;
15979         }
15980     else if ((curLnPr = (MrBFlt *)SafeMalloc((size_t)numLocalChains * sizeof(MrBFlt))) == NULL)
15981         {
15982         MrBayesPrint ("%s   Problem allocating curLnPr (%d)\n", spacer, numLocalChains * sizeof(MrBFlt));
15983         nErrors++;
15984         }
15985     else
15986         memAllocs[ALLOC_CURLNPR] = YES;
15987 #   if defined (MPI_ENABLED)
15988     MPI_Allreduce (&nErrors, &sumErrors, 1, MPI_INT, MPI_SUM, MPI_COMM_WORLD);
15989     if (sumErrors > 0)
15990         {
15991         MrBayesPrint ("%s   Memory allocation error on at least one processor\n", spacer);
15992         return ERROR;
15993         }
15994 #   else
15995     if (nErrors > 0)
15996         return ERROR;
15997 #   endif
15998
15999     if (memAllocs[ALLOC_CHAINID] == YES)
16000         {
16001         MrBayesPrint ("%s   chainId is already allocated\n", spacer);
16002         nErrors++;
16003         }
16004     else if ((chainId = (int *)SafeMalloc((size_t)numLocalChains * sizeof(int))) == NULL)
16005         {
16006         MrBayesPrint ("%s   Problem allocating chainId (%d)\n", spacer, numLocalChains * sizeof(int));
16007         nErrors++;
16008         }
16009     else
16010         memAllocs[ALLOC_CHAINID] = YES;
16011 #   if defined (MPI_ENABLED)
16012     MPI_Allreduce (&nErrors, &sumErrors, 1, MPI_INT, MPI_SUM, MPI_COMM_WORLD);
16013     if (sumErrors > 0)
16014         {
16015         MrBayesPrint ("%s   Memory allocation error on at least one processor\n", spacer);
16016         return ERROR;
16017         }
16018 #   else
16019     if (nErrors > 0)
16020         return ERROR;
16021 #   endif
16022
16023     if (memAllocs[ALLOC_SWAPINFO] == YES)
16024         {
16025         MrBayesPrint ("%s   swapInfo is already allocated\n", spacer);
16026         nErrors++;
16027         }
16028     else if ((swapInfo = (int ***) SafeCalloc (chainParams.numRuns, sizeof (int **))) == NULL)
16029         {
16030         MrBayesPrint ("%s   Problem allocating swapInfo\n", spacer);
16031         nErrors++;
16032         }
16033     else
16034         {
16035         for (n=0; n<chainParams.numRuns; n++)
16036             {
16037             swapInfo[n] = AllocateSquareIntegerMatrix (chainParams.numChains);
16038             if (!swapInfo[n])
16039                 {
16040                 MrBayesPrint ("%s   Problem allocating swapInfo[%d]\n", spacer, n);
16041                 for (i=0; i<n; i++)
16042                     free (swapInfo[i]);
16043                 free (swapInfo);
16044                 nErrors++;
16045                 break;
16046                 }
16047             }
16048         memAllocs[ALLOC_SWAPINFO] = YES;
16049         }
16050 #   if defined (MPI_ENABLED)
16051     MPI_Allreduce (&nErrors, &sumErrors, 1, MPI_INT, MPI_SUM, MPI_COMM_WORLD);
16052     if (sumErrors > 0)
16053         {
16054         MrBayesPrint ("%s   Memory allocation error on at least one processor\n", spacer);
16055         return ERROR;
16056         }
16057 #   else
16058     if (nErrors > 0)
16059         return ERROR;
16060 #   endif
16061
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;
16066
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)
16070         {
16071         if (SetUpPartitionCounters () == ERROR)
16072             nErrors++;
16073 #   if defined (MPI_ENABLED)
16074         if (proc_id == 0)
16075             {
16076 #   endif
16077         if (chainParams.relativeBurnin == YES)
16078             {
16079             /* we have to remove trees later on */
16080             if (chainParams.saveTrees == YES)
16081                 {
16082                 if (chainParams.treeList)
16083                     nErrors++;
16084                 else 
16085                     {
16086                     chainParams.treeList = (TreeList *) SafeCalloc (chainParams.numRuns*numTopologies, sizeof (TreeList));
16087                     if (!chainParams.treeList)
16088                         nErrors++;
16089                     }
16090                 if (nErrors == 0)
16091                     memAllocs[ALLOC_TREELIST] = YES;
16092                 if (noWarn == YES)
16093                     chainParams.stopTreeGen = (int) (chainParams.numGen * chainParams.burninFraction);
16094                 else
16095                     chainParams.stopTreeGen = chainParams.numGen;
16096                 }
16097             else /* if (chainParams.saveTrees == NO) */
16098                 {
16099                 chainParams.tFilePos = (fpos_t*) SafeRealloc ((void *)chainParams.tFilePos, chainParams.numRuns*numTopologies*sizeof (fpos_t));
16100                 if (!chainParams.tFilePos)
16101                     nErrors++;
16102                 else
16103                     memAllocs[ALLOC_TFILEPOS] = YES;
16104                 }
16105             }
16106 #   if defined (MPI_ENABLED)
16107             }
16108 #   endif
16109 #   if defined (MPI_ENABLED)
16110         if (proc_id == 0)
16111             {
16112             if ((chainParams.stat = (STATS *) SafeCalloc (numTopologies, sizeof (STATS))) == NULL)
16113                 nErrors++;
16114             else
16115                 {
16116                 memAllocs[ALLOC_STATS] = YES;
16117                 for (i=0; i<numTopologies; i++)
16118                     chainParams.stat[i].pair = NULL;
16119                 }
16120
16121             if ((chainParams.dtree = AllocateTree (numLocalTaxa)) == NULL)
16122                 {
16123                 nErrors++;
16124                 }
16125             else
16126                 memAllocs[ALLOC_DIAGNTREE] = YES;
16127
16128             if (chainParams.allComps == YES)
16129                 {
16130                 for (i=0; i<numTopologies; i++)
16131                     {
16132                     if ((chainParams.stat[i].pair = AllocateSquareDoubleMatrix (chainParams.numRuns)) == NULL)
16133                         {
16134                         nErrors++;
16135                         break;
16136                         }
16137                     }
16138                 }
16139             }
16140         MPI_Allreduce (&nErrors, &sumErrors, 1, MPI_INT, MPI_SUM, MPI_COMM_WORLD);
16141         if (sumErrors > 0)
16142             {
16143             MrBayesPrint ("%s   Memory allocation error on at least one processor\n", spacer);
16144             return ERROR;
16145             }
16146 #   else
16147         if ((chainParams.stat = (STATS *) SafeCalloc (numTopologies, sizeof (STATS))) == NULL)
16148             return ERROR;
16149         else
16150             {
16151             memAllocs[ALLOC_STATS] = YES;
16152             for (i=0; i<numTopologies; i++)
16153                 chainParams.stat[i].pair = NULL;
16154             }
16155             
16156         if ((chainParams.dtree = AllocateTree (numLocalTaxa)) == NULL)
16157             {
16158             MrBayesPrint ("%s   Could not allocate chainParams.dtree in RunChain\n", spacer);
16159             return ERROR;
16160             }
16161         else
16162             memAllocs[ALLOC_DIAGNTREE] = YES;
16163         
16164         if (chainParams.allComps == YES)
16165             {
16166             for (i=0; i<numTopologies; i++)
16167                 {
16168                 if ((chainParams.stat[i].pair = AllocateSquareDoubleMatrix (chainParams.numRuns)) == NULL)
16169                     {
16170                     MrBayesPrint ("%s   Could not allocate chainParams.stat.pair in RunChain\n", spacer);
16171                     return ERROR;
16172                     }
16173                 }
16174             }
16175 #   endif
16176         }
16177
16178     /* get chain IDs */
16179     SetChainIds ();
16180     
16181     /* distribute parameter starting values and tuning parameters for MPI version */
16182 #   if defined (MPI_ENABLED)
16183     RedistributeParamVals();
16184     RedistributeTuningParams();
16185 #   endif
16186
16187 #   if defined (TIMING_ANALIZ)
16188     CPUCondLikeDown = 0;
16189     CPUScalers = 0;
16190     CPUScalersRemove = 0;
16191     CPUCondLikeRoot = 0;
16192     CPULilklihood = 0;
16193 #   endif
16194
16195     /* initialize likelihoods and prior                  */
16196     /* touch everything and calculate initial cond likes */
16197 #   if defined (BEAGLE_ENABLED)
16198     if (ResetScalersNeeded)
16199         ResetScalers();
16200 #   else
16201     ResetScalers();
16202 #   endif
16203     TouchAllPartitions ();
16204     for (chn=0; chn<numLocalChains; chn++)
16205         {
16206         if (chn % chainParams.numChains == 0)
16207             {
16208             if (chainParams.numRuns == 1)
16209                 MrBayesPrint ("\n%s   Initial log likelihoods and log prior probs:\n", spacer);
16210             else
16211                 MrBayesPrint ("\n%s   Initial log likelihoods and log prior probs for run %d:\n", spacer, chn / chainParams.numChains + 1);
16212             }
16213         TouchAllTrees (chn);
16214         TouchAllCijks (chn);
16215         curLnL[chn] = LogLike(chn);
16216         curLnPr[chn] = LogPrior(chn);
16217         for (i=0; i<numCurrentDivisions; i++)
16218             {
16219             if (modelSettings[i].gibbsGamma == YES)
16220                 curLnL[chn] += GibbsSampleGamma (chn, i, seed);
16221             }
16222         MrBayesPrint ("%s      Chain %d -- %.6lf -- %.6lf\n", spacer, (chn % chainParams.numChains) + 1, curLnL[chn], curLnPr[chn]);
16223         }
16224     MrBayesPrint("\n");
16225
16226 #   if defined (MPI_ENABLED)
16227     if (num_procs > 2)
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);
16231 #   endif
16232
16233     /* All steps are assumed to have the same length. */
16234     if (chainParams.isSS == YES)
16235         {
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;
16242         else
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);
16253         else
16254             {
16255             MrBayesPrint ("%s   Sampling from posterior to prior, i.e. first step samples from close to \n", spacer);
16256             MrBayesPrint ("%s   posterior.                                                              \n", spacer);
16257             }
16258         if (numGenOld != chainParams.numGen)
16259             {
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);
16263             }
16264         MrBayesPrint ("\n");
16265         if ((numGenInStepSS-numGenInStepBurninSS)/chainParams.sampleFreq < 1)
16266             {
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*/
16271             }
16272         if (numPreviousGen==0 || numPreviousGen < chainParams.burninSS * chainParams.sampleFreq)
16273             {
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)
16279                 {
16280                 // powerSS = BetaQuantile (chainParams.alphaSS, 1.0, (MrBFlt)(chainParams.numStepsSS-1-stepIndexSS)/(MrBFlt)chainParams.numStepsSS);
16281                 powerSS = 0.0;
16282                 stepLengthSS = BetaQuantile (chainParams.alphaSS, 1.0, (MrBFlt)(chainParams.numStepsSS-stepIndexSS)/(MrBFlt)chainParams.numStepsSS)-powerSS;
16283                 }
16284             else
16285                 {
16286                 powerSS = BetaQuantile (chainParams.alphaSS, 1.0, (MrBFlt)stepIndexSS/(MrBFlt)chainParams.numStepsSS);
16287                 stepLengthSS = 1.0-powerSS;
16288                 }
16289             samplesCountSS=0;
16290             }
16291         else
16292             {
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)
16300                 {
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;
16303                 }
16304             else
16305                 {
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;
16308                 }
16309 #   ifdef SAMPLE_ALL_SS
16310             samplesCountSS  = (numPreviousGen-lastStepEndSS-numGenInStepBurninSS);
16311 #   else
16312             samplesCountSS  = (numPreviousGen-lastStepEndSS-numGenInStepBurninSS)/chainParams.sampleFreq;
16313 #   endif
16314             if (samplesCountSS < 0)
16315                 samplesCountSS=0;
16316
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. */
16319             }
16320
16321         if (samplesCountSS == 0) /* in appended case it also can happen */
16322             {
16323             for (run=0; run<chainParams.numRuns; run++)
16324                 {
16325                 marginalLnLSS[run] = 0.0;
16326                 stepScalerSS[run] = 0.0;
16327                 stepAcumulatorSS[run] = 0.0;
16328                 }
16329  
16330             for (chn=0; chn<numLocalChains; chn++)
16331                 {
16332                 if (chainId[chn] % chainParams.numChains == 0)
16333                     {
16334                     run = chainId[chn] / chainParams.numChains;
16335                     stepScalerSS[run] = curLnL[chn]*stepLengthSS;
16336                     }
16337                 }      
16338             }
16339         }
16340
16341     /* Append to previous analysis if this is requested, otherwise just open new print files */
16342     if (chainParams.append == YES)
16343         {
16344 #   if defined (MPI_ENABLED)
16345     if (proc_id == 0) {
16346 #   endif
16347         /* We get the number of samples in i */
16348         if (ReusePreviousResults(&i, chainParams.numStepsSS-stepIndexSS-1) == ERROR || i < 2)
16349             nErrors++;
16350         else if (chainParams.numRuns > 1 && chainParams.mcmcDiagn == YES)  /* we potentially need to add tree samples for conv diagn */
16351             {
16352             /* Add tree samples to partition counters */
16353             if (chainParams.relativeBurnin == YES)
16354                 {
16355                 if (numPreviousGen/(i-1) != chainParams.sampleFreq)
16356                     {
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);
16363                     nErrors++;
16364                     }
16365                 if (chainParams.isSS == NO)
16366                     {
16367                     if (noWarn == YES)
16368                         {
16369                         /* We definitely know the final number of generations */
16370                         j = (chainParams.numGen/chainParams.sampleFreq)+1;
16371                         j = (int) (j*chainParams.burninFraction);
16372                         }
16373                     else /* User may extend chain so save all trees if saving trees */
16374                         j = i;
16375                     if (j < i)
16376                         {
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 */
16380                         }
16381                     else
16382                         {
16383                         if (AddTreeSamples(1,i,chainParams.saveTrees) == ERROR) nErrors++;
16384                         }
16385                     }
16386                 else
16387                     {
16388                     if (SetFilePositions(removeTo) == ERROR) nErrors++;
16389                     if (AddTreeSamples(removeTo+1,i,chainParams.saveTrees) == ERROR) nErrors++;
16390                     }
16391                 }
16392             else if (chainParams.chainBurnIn < i)
16393                 {
16394                 if (AddTreeSamples(chainParams.chainBurnIn,i-1,chainParams.saveTrees) == ERROR) nErrors++;
16395                 }
16396             }
16397         if (nErrors == 0)
16398             {
16399             if (chainParams.isSS == NO && chainParams.mcmcDiagn == YES && chainParams.numRuns > 1)
16400                 {
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);
16404                 else
16405                     MrBayesPrint ("%s   Using an absolute burnin of %d samples for diagnostics\n", spacer, chainParams.chainBurnIn);
16406                 }
16407             MrBayesPrint ("\n");
16408             MrBayesPrint ("%s   Chain results (continued from previous run; %d generations requested):\n\n", spacer, chainParams.numGen);
16409             }
16410 #   if defined (MPI_ENABLED)
16411         }
16412 #   endif
16413
16414         if (chainParams.autotune == YES)
16415             {
16416             for (i=0; i<numLocalChains; i++)
16417                 {
16418                 for (j=0; j<numUsedMoves; j++)
16419                     {
16420                     if (j==0)
16421                         f = usedMoves[j]->cumProposalProb[chainId[i]];
16422                     else
16423                         f = usedMoves[j]->cumProposalProb[chainId[i]] - usedMoves[j-1]->cumProposalProb[chainId[i]];
16424                     if (usedMoves[j]->targetRate[chainId[i]] > 0.0)
16425                         {
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]];
16429                         }
16430                     else
16431                         {
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;
16435                         }
16436                     }
16437                 }
16438             }
16439 #   if defined (MPI_ENABLED)
16440         if (chainParams.isSS == YES)
16441             {
16442             MPI_Bcast (marginalLnLSS, chainParams.numRuns, MPI_DOUBLE, 0, MPI_COMM_WORLD);
16443
16444             if (samplesCountSS != 0)
16445                 {
16446                 MPI_Bcast (stepScalerSS, chainParams.numRuns, MPI_DOUBLE, 0, MPI_COMM_WORLD);
16447                 MPI_Bcast (stepAcumulatorSS, chainParams.numRuns, MPI_DOUBLE, 0, MPI_COMM_WORLD);
16448                 }
16449             /*Set to zero all runs that we are not responsable for*/
16450             for (run=0; run<chainParams.numRuns; run++)
16451                 {
16452                 for (chn=0; chn<numLocalChains; chn++)
16453                     {
16454                     if (chainId[chn] % chainParams.numChains == 0 && run == chainId[chn] / chainParams.numChains)
16455                         break;
16456                     }
16457                 if (chn<numLocalChains)
16458                     continue;
16459
16460                 marginalLnLSS[run] = 0.0;
16461                 stepScalerSS[run] = 0.0;
16462                 stepAcumulatorSS[run] = 0.0;    
16463                 }
16464             }
16465
16466         MPI_Allreduce (&nErrors, &sumErrors, 1, MPI_INT, MPI_SUM, MPI_COMM_WORLD);
16467         if (sumErrors > 0)
16468             {
16469             MrBayesPrint ("%s    Error appending to previous run\n", spacer);
16470             return ERROR;
16471             }            
16472 #   else
16473         if (nErrors == 1)
16474             {
16475             MrBayesPrint ("%s    Error appending to previous run\n", spacer);
16476             return ERROR;
16477             }
16478 #   endif
16479         }
16480     else
16481         {
16482         if (PreparePrintFiles() == ERROR)
16483             nErrors++;
16484         }
16485
16486 #   if defined (MPI_ENABLED)
16487     MPI_Allreduce (&nErrors, &sumErrors, 1, MPI_INT, MPI_SUM, MPI_COMM_WORLD);
16488     if (sumErrors > 0)
16489         {
16490         MrBayesPrint ("%s   Error preparing print files on at least one processor\n", spacer);
16491         CloseMBPrintFiles();
16492         return ERROR;
16493         }
16494 #   else
16495     if (nErrors > 0)
16496         {
16497         MrBayesPrint ("%s   Error preparing print files\n", spacer);
16498         CloseMBPrintFiles();
16499         return ERROR;
16500         }
16501 #   endif
16502
16503     if (chainParams.relativeBurnin == NO)
16504         lastDiagnostics = chainParams.chainBurnIn;
16505     else
16506         lastDiagnostics = 0;
16507     stopChain = NO;
16508
16509     for (i=0; i<chainParams.numRuns; i++)
16510         maxLnL0[i] = -100000000.0;
16511
16512     startingT=time(0);
16513     CPUTime = 0.0;
16514     previousCPUTime = clock();
16515
16516     /* print headers and starting states */
16517     if (numPreviousGen==0)
16518         {
16519         /* make sure we print headers */
16520         PrintToScreen(0, 0, time(0), startingT);
16521         if (PrintStatesToFiles (0) == ERROR)
16522             {
16523             MrBayesPrint("%s   Error in printing headers to files\n");
16524 #   if defined (MPI_ENABLED)
16525             nErrors++;
16526 #   else
16527             return ERROR;
16528 #   endif
16529             }
16530 #   if defined (MPI_ENABLED)
16531         MPI_Allreduce (&nErrors, &sumErrors, 1, MPI_INT, MPI_SUM, MPI_COMM_WORLD);
16532         if (sumErrors > 0)
16533             {
16534             MrBayesPrint ("%s   Aborting run.\n");
16535             return ERROR;
16536             }
16537 #   endif
16538
16539         if (chainParams.mcmcDiagn == YES)
16540             {
16541             if (PrintMCMCDiagnosticsToFile (0) == ERROR)
16542                 {
16543                 MrBayesPrint ("%s   Problem printing mcmc diagnostics headers to file\n", spacer);
16544 #   if defined (MPI_ENABLED)
16545                 nErrors++;
16546 #   else
16547                 return (ERROR);
16548 #   endif
16549                 }
16550 #   if defined (MPI_ENABLED)
16551             MPI_Allreduce (&nErrors, &sumErrors, 1, MPI_INT, MPI_SUM, MPI_COMM_WORLD);
16552             if (sumErrors > 0)
16553                 {
16554                 MrBayesPrint ("%s   Aborting run.\n");
16555                 return ERROR;
16556                 }
16557 #   endif
16558         
16559             if (chainParams.isSS == YES && chainParams.burninSS == 0 && chainParams.numRuns > 1)
16560                 {
16561                 /* Remove first sample (generation 0) from diagnostics */
16562                 removeTo=1;
16563                 if (RemoveTreeSamples (1,1) == ERROR)
16564                     {
16565                      MrBayesPrint("%s   Problem removing tree samples\n");
16566 #   if defined (MPI_ENABLED)
16567                        nErrors++;
16568 #   else
16569                       return ERROR;
16570 #   endif
16571                     }
16572 #   if defined (MPI_ENABLED)
16573                 MPI_Allreduce (&nErrors, &sumErrors, 1, MPI_INT, MPI_SUM, MPI_COMM_WORLD);
16574                 if (sumErrors > 0)
16575                     {
16576                     MrBayesPrint ("%s   Aborting run.\n");
16577                     return ERROR;
16578                     }
16579 #   endif
16580                 }
16581             }
16582         if (chainParams.isSS == YES)
16583             {
16584             if (chainParams.burninSS == 0)
16585                 MrBayesPrint("%s   Sampling step 1 out of %d steps...\n\n",spacer, chainParams.numStepsSS);
16586
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");
16595             else
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)
16601                 {
16602                 for (j=0; j<numTopologies; j++)
16603                     MrBayesPrintf (fpSS, "\taSplit%d", j);
16604                 }
16605             else
16606                 {
16607                 for (j=0; j<numTopologies; j++)
16608                     MrBayesPrintf (fpSS, "\tmSplit%d", j);
16609                 }
16610             MrBayesPrintf (fpSS, "\n");
16611             }
16612         }
16613
16614     for (n=numPreviousGen+1; n<=chainParams.numGen; n++) /* begin run chain */
16615         {
16616         currentCPUTime = clock();
16617         if (currentCPUTime - previousCPUTime > 10 * CLOCKS_PER_SEC)
16618             {
16619             CPUTime += (currentCPUTime - previousCPUTime) / (MrBFlt) (CLOCKS_PER_SEC);
16620             previousCPUTime = currentCPUTime;
16621             }
16622
16623         /*! requestAbortRun is set by the signal handler when it receives a CTRL-C (serial version only) */
16624         if (requestAbortRun == YES && ConfirmAbortRun() == 1)
16625             return ABORT;
16626
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)
16632             ResetScalers();
16633 #   else
16634         if (n % SCALER_REFRESH_FREQ == 0)
16635             ResetScalers();
16636 #   endif
16637
16638         // RandLong oldSeed = *seed;  /* record the old seed for debugging */
16639         for (chn=0; chn<numLocalChains; chn++)
16640             {
16641             /* Do Gibbs resampling of rate categories for current state if time to do so */
16642             for (i=0; i<numCurrentDivisions; i++)
16643                 {
16644                 if (modelSettings[i].gibbsGamma == YES && n % modelSettings[i].gibbsFreq == 0)
16645                     curLnL[chn] += GibbsSampleGamma (chn, i, seed);
16646                 }
16647
16648             /* First copy everything from current state of chain to new state.   */
16649             /* The global variable state[chain] gives state.                     */
16650
16651             /* copy all touched trees and reset update flags                     */
16652             CopyTrees (chn);
16653
16654             /* copy all model parameters */
16655             CopyParams (chn);
16656
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 */
16660
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);
16666 #   endif
16667
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]);
16674             else
16675                 PickBestProposal(chainId[chn]);
16676 #   endif
16677
16678             /* set prior and proposal ratios */
16679             lnProposalRatio = 0.0;
16680             lnPriorRatio = 0.0;
16681
16682             /* reset abort move flag */
16683             abortMove = NO;
16684             
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;
16689
16690 #   ifndef NDEBUG
16691             if (IsTreeConsistent(theMove->parm, chn, state[chn]) != YES)
16692                 {
16693                 printf ("IsTreeConsistent failed before a move!\n");
16694                 return ERROR;
16695                 }
16696 #   endif
16697 #   if defined (DEBUG_CONSTRAINTS)
16698             if (theMove->parm->paramType == P_TOPOLOGY && DoesTreeSatisfyConstraints(GetTree (theMove->parm, chn, state[chn]))!=YES)
16699                 {
16700                 printf ("DEBUG ERROR: DoesTreeSatisfyConstraints failed before a move\n");
16701                 return ERROR;
16702                 }
16703 #   endif
16704             /* make move */
16705             if ((theMove->moveFxn)(theMove->parm, chn, seed, &lnPriorRatio, &lnProposalRatio, theMove->tuningParam[chainId[chn]]) == ERROR)
16706                 {
16707                 printf ("%s   Error in move %s\n", spacer, theMove->name);
16708 #   if defined (MPI_ENABLED)
16709                 nErrors++;
16710 #   else
16711                 return ERROR;
16712 #   endif
16713                 }
16714
16715             if (theMove->parm->paramType == P_TOPOLOGY && DoesTreeSatisfyConstraints(GetTree (theMove->parm, chn, state[chn])) != YES)
16716                 {
16717 #   if defined (DEBUG_CONSTRAINTS)
16718                 if (DoesTreeSatisfyConstraints(GetTree (theMove->parm, chn, state[chn]))==ABORT)
16719                     {
16720                     printf ("DEBUG ERROR: DoesTreeSatisfyConstraints failed after move '%s'\n", theMove->name);
16721                     }
16722 #   endif
16723                 abortMove = YES;
16724                 }
16725
16726             /* abortMove is set to YES if the calculation fails because the likelihood is too small */
16727             if (abortMove == NO)
16728                 lnLike = LogLike(chn);
16729
16730             /* calculate acceptance probability */
16731             if (abortMove == NO)
16732                 {
16733                 lnLikelihoodRatio = lnLike - curLnL[chn];
16734                 lnPrior = curLnPr[chn] + lnPriorRatio;
16735
16736 #   ifndef NDEBUG
16737                 /* We check various aspects of calculations in debug version of code */
16738                 if (IsTreeConsistent(theMove->parm, chn, state[chn]) != YES)
16739                     {
16740                     printf ("DEBUG ERROR: IsTreeConsistent failed after move '%s'\n", theMove->name);
16741                     return ERROR;
16742                     }
16743                 if (lnPriorRatio != lnPriorRatio)
16744                     {
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);
16747                     return ERROR;
16748                     }
16749                 if (fabs((lnPrior-LogPrior(chn))/lnPrior) > 0.0001)
16750                     {
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);
16753                     return ERROR;
16754                     }
16755                 if (lnProposalRatio != lnProposalRatio)
16756                     {
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);
16759                     return ERROR;
16760                     }
16761                 if (lnLike != lnLike)
16762                     {
16763                     printf ("DEBUG ERROR: Log likelihood nan after move '%s'\n", theMove->name);
16764                     // printf ("Seed: %ld\n", oldSeed);  state[chn] ^= 1;  PrintCheckPoint (n);
16765                     return ERROR;
16766                     }
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)
16771                     {
16772                     printf ("DEBUG ERROR: Log likelihood incorrect after move '%s'\n", theMove->name);
16773                     return ERROR;
16774                     }
16775 #       endif
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)
16778                     {
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);
16781                     return (ERROR);
16782                     }
16783 #   endif
16784
16785                 /* heat */
16786                 lnLikelihoodRatio *= Temperature (chainId[chn]);
16787                 lnPriorRatio      *= Temperature (chainId[chn]);
16788
16789                 if (chainParams.isSS == YES)
16790                     lnLikelihoodRatio *= powerSS;
16791
16792                 /* calculate the acceptance probability */
16793                 if (lnLikelihoodRatio + lnPriorRatio + lnProposalRatio < -100.0)
16794                     r = 0.0;
16795                 else if (lnLikelihoodRatio + lnPriorRatio + lnProposalRatio > 0.0)
16796                     r = 1.0;
16797                 else
16798                     r = exp(lnLikelihoodRatio + lnPriorRatio + lnProposalRatio);
16799                 }
16800
16801             /* decide to accept or reject the move */
16802             acceptMove = NO;
16803             i = chainId[chn];
16804             theMove->nTried[i]++;
16805             theMove->nTotTried[i]++;
16806             if (abortMove == NO && RandomNumber(seed) < r)
16807                 {
16808                 acceptMove = YES;
16809                 theMove->nAccepted[i]++;
16810                 theMove->nTotAccepted[i]++;
16811                 }
16812
16813             /* update the chain */
16814             if (acceptMove == NO)
16815                 {
16816                 /* the new state did not work out so shift chain back */
16817                 if (abortMove == NO)
16818                     ResetFlips(chn);
16819                 state[chn] ^= 1;
16820 #   if defined (BEAGLE_ENABLED)
16821                 if (recalcScalers == YES)
16822                     {
16823                     recalculateScalers(chn);
16824                     recalcScalers = NO;
16825                     }
16826 #   endif
16827                 }
16828             else
16829                 {
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;
16834                 }
16835
16836             /* check if time to autotune */
16837             if (theMove->nTried[i] >= chainParams.tuneFreq)
16838                 {
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)
16844                     {
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]);
16851                     }
16852                 }
16853
16854             /* ShowValuesForChain (chn); */
16855
16856             if (curLnL[chn] > maxLnL0[chainId[chn]])
16857                 maxLnL0[chainId[chn]] = curLnL[chn];
16858
16859             }
16860
16861         /* attempt swap(s) Non-blocking for MPI if no swap with external process. */
16862         if (chainParams.numChains > 1 && n % chainParams.swapFreq == 0)
16863             {
16864             for (i = 0; i<chainParams.numRuns; i++)
16865                 {
16866                 for (j = 0; j<chainParams.numSwaps; j++)
16867                     GetSwappers (&swapA, &swapB, i);
16868                 if (AttemptSwap (swapA, swapB, seed) == ERROR)
16869                     {
16870                     MrBayesPrint ("%s   Unsuccessful swap of states\n", spacer);
16871 #   if defined (MPI_ENABLED)
16872                     nErrors++;
16873 #   else
16874                     return ERROR;
16875 #   endif
16876                     }
16877                 }
16878             }
16879
16880         /* print information to screen. Non-blocking for MPI */
16881         if (n % chainParams.printFreq == 0)
16882             {
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);
16888 #   endif
16889             }
16890
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)
16894             {
16895 #   if defined (MPI_ENABLED)
16896             MPI_Allreduce (&nErrors, &sumErrors, 1, MPI_INT, MPI_SUM, MPI_COMM_WORLD);
16897             if (sumErrors > 0)
16898                 {
16899                 MrBayesPrint ("%s   Aborting run.\n");
16900                 return ERROR;
16901                 }
16902 #   endif
16903             if (PrintStatesToFiles (n) == ERROR)
16904                 {
16905                 MrBayesPrint("%s   Error in printing states to files\n");
16906 #   if defined (MPI_ENABLED)
16907                 nErrors++;
16908 #   else
16909                 return ERROR;
16910 #   endif
16911                 }
16912 #   if defined (MPI_ENABLED)
16913             MPI_Allreduce (&nErrors, &sumErrors, 1, MPI_INT, MPI_SUM, MPI_COMM_WORLD);
16914             if (sumErrors > 0)
16915                 {
16916                 MrBayesPrint ("%s   Aborting run.\n");
16917                 return ERROR;
16918                 }
16919 #   endif
16920             }
16921
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)))
16926             {
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)))
16930                 {
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)
16936                     {
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)
16940                         {
16941                         if (RemoveTreeSamples (removeFrom+1, removeTo) == ERROR)
16942                             {
16943                             MrBayesPrint("%s   Problem removing tree samples\n");
16944 #   if defined (MPI_ENABLED)
16945                             nErrors++;
16946 #   else
16947                             return ERROR;
16948 #   endif
16949                             }
16950                         }
16951 #   if defined (MPI_ENABLED)
16952                     MPI_Allreduce (&nErrors, &sumErrors, 1, MPI_INT, MPI_SUM, MPI_COMM_WORLD);
16953                     if (sumErrors > 0)
16954                         {
16955                         MrBayesPrint ("%s   Aborting run.\n");
16956                         return ERROR;
16957                         }
16958 #   endif
16959                     }
16960
16961                 lastDiagnostics = (n/chainParams.sampleFreq)+1; /* +1 because we always have start tree sampled*/
16962                 if (chainParams.relativeBurnin == YES)
16963                     {
16964                     i = lastDiagnostics - removeTo;
16965                     }
16966                 else
16967                     i = lastDiagnostics - chainParams.chainBurnIn;
16968 #   if defined (MPI_ENABLED)
16969                 if (proc_id == 0)
16970                     {
16971 #   endif
16972                 /* calculate statistics */
16973                 CalcTopoConvDiagn (i);
16974                 /* output statistics */
16975                 if (numTopologies == 1)
16976                     {
16977                     f = -1.0;
16978                     if (chainParams.stat[0].numPartitions == 0)
16979                         {
16980                         MrBayesPrint ("%s   Average standard deviation of split frequencies: NA (no splits above min. frequency)\n", spacer);
16981                         }
16982                     else if (chainParams.diagnStat == AVGSTDDEV)
16983                         {
16984                         f = chainParams.stat[0].avgStdDev;
16985                         MrBayesPrint ("%s   Average standard deviation of split frequencies: %.6f\n", spacer, f);
16986                         }
16987                     else
16988                         {
16989                         f = chainParams.stat[0].max;
16990                         MrBayesPrint ("%s   Max standard deviation of split frequencies: %.6f\n", spacer, f);
16991                         }
16992                     if (chainParams.isSS == YES)
16993                         splitfreqSS[chainParams.numStepsSS-stepIndexSS-1] = f;
16994                     if (chainParams.stat[0].numPartitions > 0 && f <= chainParams.stopVal)
16995                         stopChain = YES;
16996                     if (n < chainParams.numGen - chainParams.printFreq && (chainParams.stopRule == NO || stopChain == NO))
16997                         MrBayesPrint ("\n");
16998                     }
16999                 else
17000                     {
17001                     stopChain = YES;
17002                     for (i=0; i<numTopologies; i++)
17003                         {
17004                         f=-1.0;
17005                         if (chainParams.stat[i].numPartitions == 0)
17006                             {
17007                             if (strcmp(modelParams[0].topologyPr,"Speciestree") == 0)
17008                                 {
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);
17011                                 else
17012                                     MrBayesPrint ("%s   Average standard deviation of split frequencies for gene tree %d: NA (no splits above min. frequency)\n", spacer, i+1);
17013                                 }
17014                             else
17015                                 MrBayesPrint ("%s   Average standard deviation of split frequencies for topology %d: NA (no splits above min. frequency)\n", spacer, i+1);
17016                             }
17017                         else if (chainParams.diagnStat == AVGSTDDEV)
17018                             {
17019                             f = chainParams.stat[i].avgStdDev;
17020                             if (strcmp(modelParams[0].topologyPr,"Speciestree") == 0)
17021                                 {
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);
17024                                 else
17025                                     MrBayesPrint ("%s   Average standard deviation of split frequencies for gene tree %d: %.6f\n", spacer, i+1, f);
17026                                 }
17027                             else
17028                                 MrBayesPrint ("%s   Average standard deviation of split frequencies for topology %d: %.6f\n", spacer, i+1, f);
17029                             }
17030                         else
17031                             {
17032                             f = chainParams.stat[i].max;
17033                             if (strcmp(modelParams[0].topologyPr,"Speciestree") == 0)
17034                                 {
17035                                 if (i == numTopologies-1)
17036                                     MrBayesPrint ("%s   Max standard deviation of split frequencies for species tree: %.6f\n", spacer, f);
17037                                 else
17038                                     MrBayesPrint ("%s   Max standard deviation of split frequencies for gene tree %d: %.6f\n", spacer, i+1, f);
17039                                 }
17040                             else
17041                                 MrBayesPrint ("%s   Max standard deviation of split frequencies for topology %d: %.6f\n", spacer, i+1, f);
17042                             }
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)
17046                             stopChain = NO;
17047                         }
17048                     if (n < chainParams.numGen - chainParams.printFreq && (chainParams.stopRule == NO || stopChain == NO))
17049                         MrBayesPrint ("\n");
17050                     }
17051                 if (chainParams.allComps == YES)
17052                     PrintTopConvInfo ();
17053 #   if defined (MPI_ENABLED)
17054                     }
17055                 ierror = MPI_Bcast (&stopChain, 1, MPI_INT, 0, MPI_COMM_WORLD);
17056                 if (ierror != MPI_SUCCESS)
17057                     {
17058                     MrBayesPrint ("%s   Problem broadcasting stop value\n", spacer);
17059                     nErrors++;
17060                     }
17061 #   endif
17062                 }
17063
17064             /* part of the following function needs to be performed by all MPI processors. Blocking for MPI. */
17065             if (PrintMCMCDiagnosticsToFile (n) == ERROR)
17066                 {
17067                 MrBayesPrint ("%s   Problem printing mcmc diagnostics to file\n", spacer);
17068 #   if defined (MPI_ENABLED)
17069                 nErrors++;
17070 #   else
17071                 return (ERROR);
17072 #   endif
17073                 }
17074 #   if defined (MPI_ENABLED)
17075             MPI_Allreduce (&nErrors, &sumErrors, 1, MPI_INT, MPI_SUM, MPI_COMM_WORLD);
17076             if (sumErrors > 0)
17077                 {
17078                 MrBayesPrint ("%s   Aborting run.\n");
17079                 return ERROR;
17080                 }
17081 #   endif
17082             }
17083
17084         /* check if time to break because stopVal reached */
17085         if (chainParams.isSS == NO && (chainParams.stopRule == YES && stopChain == YES))
17086             {
17087             MrBayesPrint ("\n%s   Analysis stopped because convergence diagnostic hit stop value.\n", spacer);
17088             break;
17089             }
17090             
17091         /* user may want to extend chain */
17092         if (chainParams.isSS == NO && (n == chainParams.numGen && autoClose == NO))
17093             {
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 */
17103             }
17104
17105         /* Do stepping sampling staf if needed */
17106         if (chainParams.isSS == YES && n >= chainParams.burninSS*chainParams.sampleFreq)
17107             {
17108 #   ifndef SAMPLE_ALL_SS
17109             if ((n-lastStepEndSS) % chainParams.sampleFreq == 0)
17110 #   endif
17111                 {
17112                 if (n > chainParams.burninSS*chainParams.sampleFreq && (n-lastStepEndSS > numGenInStepBurninSS))
17113                     { /* do sampling */
17114                     for (chn=0; chn<numLocalChains; chn++)
17115                         {
17116                         if (chainId[chn] % chainParams.numChains == 0)
17117                             {
17118                             run = chainId[chn] / chainParams.numChains;
17119                             if (curLnL[chn]*stepLengthSS > stepScalerSS[run] + 200.0)
17120                                 {
17121                                 // adjust scaler;
17122                                 stepAcumulatorSS[run] /= exp (curLnL[chn]*stepLengthSS - 100.0 - stepScalerSS[run]); 
17123                                 stepScalerSS[run]= curLnL[chn]*stepLengthSS - 100.0;
17124                                 }
17125                             stepAcumulatorSS[run] += exp (curLnL[chn]*stepLengthSS - stepScalerSS[run]);
17126                             }
17127                         }
17128                     samplesCountSS++;
17129                     }
17130                 }
17131
17132             if ((n-lastStepEndSS) == numGenInStepBurninSS)
17133                 {
17134                 /* Remove all previouse samples from diagnostics */
17135                 if (chainParams.mcmcDiagn == YES && chainParams.numRuns > 1)
17136                     {
17137                     removeFrom = removeTo;
17138                     removeTo = (int)(n/chainParams.sampleFreq); /* (n/chainParams.sampleFreq+1) is the current number of samples including 0 one*/
17139                     removeTo++;
17140                     if (removeFrom < removeTo)
17141                         {
17142                         if (RemoveTreeSamples (removeFrom+1, removeTo) == ERROR)
17143                             {
17144                             nErrors++;
17145                             }
17146                         ERROR_TEST2("Problem removing tree samples",return(ERROR),);
17147                         }
17148                     }               
17149                 }
17150
17151             if ((n-lastStepEndSS) % numGenInStepSS == 0)      /* prepare sample of next step */
17152                 {
17153                 assert (n-lastStepEndSS <= numGenInStepSS);
17154                 lastStepEndSS=n;
17155
17156                 if (n > chainParams.burninSS*chainParams.sampleFreq)
17157                     {
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++)
17162                         {
17163                         if (stepAcumulatorSS[j]==0)
17164                             r=0;
17165                         else
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)
17169                             {
17170                             MrBayesPrint ("%s   Problem with MPI_Reduce\n", spacer);
17171                             return ERROR;
17172                             }
17173                         if (proc_id == 0)
17174                             {
17175                             MrBayesPrintf (fpSS, "\t%.6f", sum);
17176                             }
17177                         }
17178 #   else
17179                     for (j=0; j<chainParams.numRuns ; j++)
17180                         {
17181                         MrBayesPrintf (fpSS, "\t%.6f", log (stepAcumulatorSS[j]/samplesCountSS) + stepScalerSS[j]);
17182                         }
17183 #   endif
17184                     if (chainParams.mcmcDiagn == YES && chainParams.numRuns > 1)
17185                         {
17186                         for (i=0; i<numTopologies; i++)
17187                             {
17188                             MrBayesPrintf (fpSS, "\t%.6f",splitfreqSS[i*chainParams.numStepsSS+chainParams.numStepsSS-stepIndexSS-1]);
17189                             }
17190                         }
17191                     else{
17192                         for (i=0; i<numTopologies; i++)
17193                             {
17194                             MrBayesPrintf (fpSS, "\t-2.0");
17195                             }
17196
17197                         }
17198
17199                     MrBayesPrintf (fpSS, "\n");
17200                     fflush (fpSS);
17201
17202                     stepIndexSS--;
17203
17204                     if (chainParams.startFromPriorSS==YES)
17205                         {
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;
17208                         }
17209                     else
17210                         {
17211                         stepLengthSS = powerSS; 
17212                         powerSS = BetaQuantile (chainParams.alphaSS, 1.0, (MrBFlt)stepIndexSS/(MrBFlt)chainParams.numStepsSS);
17213                         stepLengthSS -= powerSS;
17214                         }
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++)
17218                         {
17219                         if (chainId[chn] % chainParams.numChains == 0)
17220                             {
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;
17226                             }
17227                         }
17228                     samplesCountSS=0;
17229                     }
17230                 else
17231                     {
17232                     MrBayesPrint("\n%s   Sampling step 1 out of %d steps...\n\n",spacer, chainParams.numStepsSS);
17233                     }
17234
17235                 if (chainParams.backupCheckSS !=0 && (chainParams.numStepsSS-stepIndexSS-1)% chainParams.backupCheckSS == 0)
17236                     {
17237                     /* print check-point file. Blocking for MPI */
17238                     ERROR_TEST2("Error before printing checkpoint",return(ERROR),);
17239                     if (PrintCheckPoint (n) == ERROR)
17240                         {
17241                         nErrors++;
17242                         }
17243                     ERROR_TEST2("Error in printing checkpoint",return(ERROR),);
17244                        
17245 #   if defined (MPI_ENABLED)
17246                 if (proc_id == 0)
17247                     {
17248 #   endif
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)
17253                         {
17254                         MrBayesPrint ("%s   Could not rename file %s to %s\n", spacer, ckpFileName, bkupFileName);
17255                         return ERROR;
17256                         }
17257                     strcpy (bkupFileName, ckpFileName);
17258                     strcat (bkupFileName, "~");
17259                     rename (bkupFileName,ckpFileName);
17260 #   if defined (MPI_ENABLED)
17261                     } /* end of if (proc_id == 0)*/
17262 #   endif
17263                     }
17264                 }             
17265             }
17266
17267         /* print check-point file. Blocking for MPI */
17268         if (chainParams.checkPoint == YES && (n % chainParams.checkFreq == 0))
17269             {
17270             ERROR_TEST2("Error before printing checkpoint",return(ERROR),);
17271             if (PrintCheckPoint (n) == ERROR)
17272                 {
17273                 nErrors++;
17274                 }
17275             ERROR_TEST2("Error in printing checkpoint",return(ERROR),);
17276             }
17277
17278         } /* end run chain */
17279     endingT = time(0);
17280     currentCPUTime = clock();
17281     CPUTime += (currentCPUTime - previousCPUTime) / (MrBFlt) CLOCKS_PER_SEC;
17282
17283     CloseMBPrintFiles (); /* redundant because files closed in FreeChainMemory but kept here as a safeguard in case of future changes */
17284
17285 #   if defined (BEAGLE_ENABLED)
17286 #       ifdef DEBUG_BEAGLE
17287     ResetScalers ();
17288     beagleScalingSchemeOld = beagleScalingScheme;
17289     beagleScalingScheme = MB_BEAGLE_SCALE_ALWAYS;
17290     for (chn=0; chn<numLocalChains; chn++)
17291         {
17292         if (chn % chainParams.numChains == 0)
17293             {
17294             if (chainParams.numRuns == 1)
17295                 MrBayesPrint ("%s   Final log likelihoods and log prior probs (stored and calculated):\n", spacer);
17296             else
17297                 MrBayesPrint ("%s   Final log likelihoods and log prior probs for run %d (stored and calculated):\n", spacer, chn / chainParams.numChains + 1);
17298             }
17299         TouchEverything (chn);
17300         for (i=0; i<numCurrentDivisions; i++)
17301             {
17302             if (modelSettings[i].gibbsGamma == YES)
17303                 curLnL[chn] += GibbsSampleGamma (chn, i, seed);
17304             }
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));
17307         }
17308     beagleScalingScheme = beagleScalingSchemeOld;
17309 #       endif
17310 #   endif
17311
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. */
17315     ResetChainIds ();
17316
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);
17332     else
17333         MrBayesPrint ("%s   Analysis completed in less than 1 second\n", spacer);
17334
17335 #   if defined (MPI_ENABLED)
17336     MrBayesPrint ("%s   Analysis used %1.2f seconds of CPU time on processor 0\n", spacer, (MrBFlt) CPUTime);
17337 #   else
17338     MrBayesPrint ("%s   Analysis used %1.2f seconds of CPU time\n", spacer, (MrBFlt) CPUTime);
17339 #   endif
17340
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)
17345         {
17346         MrBayesPrint ("%s   Problem at chain barrier\n", spacer);
17347         return (ERROR);
17348         }
17349     for (j=0; j<numGlobalChains; j++)
17350         {
17351         best = maxLnL0[j];
17352         for (i=1; i<num_procs; i++)
17353             {
17354             if (proc_id == 0)
17355                 {
17356                 ierror = MPI_Recv (&maxLnL0[j], 1, MPI_DOUBLE, i, i, MPI_COMM_WORLD, &status);
17357                 if (ierror != MPI_SUCCESS)
17358                     { 
17359                     MrBayesPrint ("%s   Problem with MPI_Recv", spacer);
17360                     return ERROR;
17361                     }
17362                 if (maxLnL0[j] > best)
17363                     best = maxLnL0[j];
17364                 }
17365             else if (proc_id == i)
17366                 {
17367                 ierror = MPI_Send (&maxLnL0[j], 1, MPI_DOUBLE, 0, i, MPI_COMM_WORLD);
17368                 if (ierror != MPI_SUCCESS)
17369                     {
17370                     MrBayesPrint ("%s   Problem with MPI_Send\n", spacer);
17371                     return ERROR;
17372                     }
17373                 }
17374             }
17375         maxLnL0[j] = best;
17376         }
17377
17378     /* Collecting  marginal log likelihoods if SS is used */
17379     if (chainParams.isSS == YES)
17380         {
17381         for (j=0; j<chainParams.numRuns ; j++)
17382             {
17383             ierror = MPI_Reduce (&marginalLnLSS[j],&r, 1, MPI_DOUBLE, MPI_SUM, 0, MPI_COMM_WORLD);
17384             if (ierror != MPI_SUCCESS)
17385                 {
17386                 MrBayesPrint ("%s   Problem with MPI_Send\n", spacer);
17387                 return ERROR;
17388                 }
17389             if (proc_id == 0)
17390                 {
17391                 marginalLnLSS[j]=r;
17392                 }
17393             }
17394         }
17395 #   endif
17396
17397     if (chainParams.numRuns == 1)
17398         {
17399         if (chainParams.numChains == 1)
17400             MrBayesPrint ("%s   Log likelihood of best state was %1.2lf\n", spacer, maxLnL0[0]);
17401         else
17402             MrBayesPrint ("%s   Log likelihood of best state for \"cold\" chain was %1.2lf\n", spacer, maxLnL0[0]);
17403         }
17404     else
17405         {
17406         for (j=0; j<chainParams.numRuns*chainParams.numChains; j++)
17407             {
17408             if (j % chainParams.numChains == 0)
17409                 {
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]);
17412                 else
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]);
17414                 }
17415             }
17416         }
17417
17418     if (chainParams.isSS == YES)
17419         {
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++)
17426             {
17427             MrBayesPrint ("%s       %3d    %9.2f   \n", spacer, j+1, marginalLnLSS[j]);
17428             }
17429         MrBayesPrint ("%s       ------------------------------\n",spacer);
17430         if (chainParams.numRuns > 1)
17431             {
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);     
17436             }
17437         MrBayesPrint ("%s   More statistics on stepping-stone sampling is dumped to %s.ss file.\n", spacer, chainParams.chainFileName);
17438
17439         if (chainParams.mcmcDiagn == YES)
17440             {
17441             if ((tempX = (MrBFlt *) SafeCalloc (chainParams.numStepsSS, sizeof(MrBFlt))) == NULL)
17442                 {
17443                 nErrors++;
17444                 }
17445             ERROR_TEST2("Problem allocating memory", return(ERROR),);
17446
17447             for (i=0; i<chainParams.numStepsSS; i++)
17448                 {
17449                 tempX[i]=i+1;
17450                 }
17451             MrBayesPrint ("\n");
17452
17453             if (numTopologies > 1)
17454                 {
17455                 if (chainParams.diagnStat == AVGSTDDEV)
17456                     MrBayesPrint ("   Plots of average standard deviation of split frequencies across steps for different topology.");
17457                 else
17458                     MrBayesPrint ("   Plots of max standard deviation of split frequencies across steps for different topology.");
17459                 }
17460             else
17461                 {
17462                 if (chainParams.diagnStat == AVGSTDDEV)
17463                     MrBayesPrint ("   Plot of average standard deviation of split frequencies across steps.");
17464                 else
17465                     MrBayesPrint ("   Plot of max standard deviation of split frequencies across steps.");
17466                 }
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)
17471                 {
17472                 for (i=0; i<numTopologies; i++)
17473                     {
17474                     MrBayesPrint ("%s   Topology %d.\n", spacer, i+1);
17475                     PrintPlot (tempX, splitfreqSS+i*chainParams.numStepsSS, chainParams.numStepsSS);
17476                     }
17477                 }
17478             else
17479                 PrintPlot (tempX, splitfreqSS, chainParams.numStepsSS);
17480
17481             free(tempX);
17482             }
17483         }
17484
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)
17489         nErrors++;
17490     MPI_Allreduce (&nErrors, &sumErrors, 1, MPI_INT, MPI_SUM, MPI_COMM_WORLD);
17491     if (sumErrors > 0)
17492         {
17493         MrBayesPrint ("%s   ReassembleMoveInfo failed\n", spacer);
17494         return ERROR;
17495         }
17496 #   endif
17497
17498     /* print acceptance rates for the moves */
17499     for (j=0; j<chainParams.numChains*chainParams.numRuns; j++)
17500         {
17501         if (chainParams.numChains == 1)
17502             {
17503             if (chainParams.numRuns == 1)
17504                 MrBayesPrint ("%s   Acceptance rates for the moves:\n", spacer);
17505             else
17506                 MrBayesPrint ("%s   Acceptance rates for the moves in run %d:\n", spacer, j/chainParams.numChains+1);
17507             }
17508         else if (j % chainParams.numChains == 0)
17509             {
17510             if (chainParams.numRuns == 1)
17511                 MrBayesPrint ("\n%s   Acceptance rates for the moves in the \"cold\" chain:\n", spacer);
17512             else
17513                 MrBayesPrint ("\n%s   Acceptance rates for the moves in the \"cold\" chain of run %d:\n", spacer, j/chainParams.numChains+1);
17514             }
17515         else if (chainParams.allChains == YES)
17516             {
17517             if (chainParams.numRuns == 1)
17518                 MrBayesPrint ("\n%s   Acceptance rates for the moves in chain %d (heated):\n\n", spacer, j+1);
17519             else
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);
17521             }
17522
17523         if (j % chainParams.numChains == 0 || chainParams.allChains == YES)
17524             {
17525             MrBayesPrint ("%s      With prob.   (last %d)   chain accepted proposals by move\n", spacer, chainParams.tuneFreq);
17526
17527             for (i=0; i<numUsedMoves; i++)
17528                 {
17529                 mv = usedMoves[i];
17530                 if (mv->nBatches[j] < 1)
17531                     MrBayesPrint ("%s          NA           NA       %s\n",
17532                     spacer, mv->name);
17533                 else
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],
17537                     mv->name);
17538                 }
17539             }
17540         }
17541
17542 #   if defined MPI_ENABLED
17543     /* Redistribute move info in case it is needed in a follow-up run */
17544     RedistributeMoveInfo();
17545 #   endif
17546     
17547     /* output information on the success of the chain state swap proposals */
17548     if (PrintSwapInfo () == ERROR)
17549         nErrors++;
17550 #   if defined (MPI_ENABLED)
17551     MPI_Allreduce (&nErrors, &sumErrors, 1, MPI_INT, MPI_SUM, MPI_COMM_WORLD);
17552     if (sumErrors > 0)
17553         {
17554         MrBayesPrint ("%s   PrintSwapInfo failed\n", spacer);
17555         return ERROR;
17556         }
17557 #   else
17558     if (nErrors > 1)
17559         {
17560         MrBayesPrint ("%s   PrintSwapInfo failed\n", spacer);
17561         return ERROR;
17562         }
17563 #   endif
17564
17565 #   if defined (MPI_ENABLED)
17566     if (proc_id != 0)
17567         return (NO_ERROR);
17568 #   endif
17569
17570     if (chainParams.isSS == NO && (chainParams.numRuns > 1 && chainParams.mcmcDiagn == YES))
17571         {
17572         f = 0.0;
17573         for (i=0; i<numTrees; i++)
17574             {
17575             if (chainParams.stat[i].avgStdDev > f)
17576                 f = chainParams.stat[i].avgStdDev;
17577             }
17578         if (f > 0.10)
17579             {
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);
17587             }
17588         }
17589     
17590     return (NO_ERROR);
17591 }
17592
17593
17594 int SafeSprintf (char **target, int *targetLen, char *fmt, ...)
17595 {
17596     va_list    argp;
17597     int        retval;
17598
17599     while (1) {
17600         /* try to print in the available space */
17601         va_start(argp, fmt);
17602 #   ifdef VISUAL
17603         retval = _vsnprintf (*target, *targetLen, fmt, argp);
17604 #   else
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
17612            treatment.  FR  */
17613         retval = vsnprintf (*target, *targetLen, fmt, argp);
17614 #   endif
17615         va_end(argp);
17616
17617         /* if it worked, retval will be in interval [0,*targetLen-1], else -1 or true length */
17618         if (retval > -1 && retval < *targetLen)
17619             return NO_ERROR;
17620
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;
17626
17627         /* reallocate target */
17628         *target = SafeRealloc ((void *)*target, *targetLen);
17629         if (*target == NULL)
17630             return ERROR;
17631         }
17632 }
17633
17634
17635 void SetChainIds (void)
17636 {
17637     /* Fill <chainId[]> with the global chain number.
17638        Ex. For proc_0, chain[0] = 0;
17639              chain[1] = 1;
17640              chain[2] = 2; (numchains = 3)
17641        For proc_1, chain[0] = 3;
17642              chain[1] = 4; (numchains = 2)
17643        etc... 
17644     */
17645
17646 #   if defined (MPI_ENABLED)
17647
17648     int     i, proc, numChainsForProc, numGlobalChains;
17649     int     id;
17650     int     remainder;
17651
17652     /* calculate global number of chains */
17653     numGlobalChains = chainParams.numChains * chainParams.numRuns;
17654     
17655     /* there are <remainder> chains left over after
17656        load balancing the chains */
17657     remainder = numGlobalChains % num_procs;
17658
17659     /* get the number of chains handled by this proc */
17660     numChainsForProc = (int) (numGlobalChains / num_procs);
17661
17662     /* we must distribute the remaining chains (causing
17663        the chain load between procs to become unbalanced) */
17664     if (proc_id < remainder) 
17665         numChainsForProc++;
17666
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) */
17670
17671     id = 0;
17672     for (proc=0; proc<num_procs; proc++)
17673         {
17674         /* assign or increment chain id */
17675         if (proc == proc_id)
17676             {
17677             for (i=0; i<numChainsForProc; i++)
17678                 chainId[i] = id++;
17679             }
17680         else
17681             {
17682             /* procs below the remainder have 1 more chain
17683                than procs above */
17684             if (proc < remainder) 
17685                 {
17686                 for (i=0; i<(numGlobalChains / num_procs) + 1; i++)
17687                     id++;
17688                 }
17689             /* procs above the remainder have one less chain
17690                than procs below */
17691             else
17692                 {
17693                 for (i=0; i<(numGlobalChains / num_procs); i++)
17694                     id++;
17695                 }
17696             }
17697         }
17698 #   else
17699
17700     int chn;
17701     
17702     for (chn=0; chn<numLocalChains; chn++)
17703         chainId[chn] = chn;
17704
17705 #   endif
17706         
17707 }
17708
17709
17710 /* It sets chainParams.tFilePos[] to point immidiatly after sampled tree in position "samplePos" for all .t files. */
17711 int SetFilePositions (int samplePos)
17712 {
17713     int i, j, k, longestLine;
17714     BitsLong    lastBlock;
17715     char    *lineBuf;
17716     FILE    *fp;
17717     char    *tempStr;
17718     int     tempStrSize = TEMPSTRSIZE;
17719
17720 #   if defined (MPI_ENABLED)
17721     if (proc_id != 0)
17722         return (NO_ERROR);
17723 #   endif
17724
17725     tempStr = (char *) SafeMalloc((size_t)tempStrSize * sizeof(char));
17726     if (!tempStr)
17727         {
17728         MrBayesPrint ("%s   Problem allocating tempString (%d)\n", spacer, tempStrSize * sizeof(char));
17729         return (ERROR);
17730         }
17731
17732     for (i=0; i<numTopologies; i++)
17733         {
17734         for (j=0; j<chainParams.numRuns; j++)
17735             {
17736             if (numPrintTreeParams == 1)
17737                 {
17738                 if (chainParams.numRuns == 1)
17739                     SafeSprintf (&tempStr, &tempStrSize, "%s.t", chainParams.chainFileName);
17740                 else
17741                     SafeSprintf (&tempStr, &tempStrSize, "%s.run%d.t", chainParams.chainFileName, j+1);
17742                 }
17743             else
17744                 {
17745                 if (chainParams.numRuns == 1)
17746                     SafeSprintf (&tempStr, &tempStrSize, "%s.tree%d.t", chainParams.chainFileName, i+1);
17747                 else
17748                     SafeSprintf (&tempStr, &tempStrSize, "%s.tree%d.run%d.t", chainParams.chainFileName, i+1, j+1);
17749                 }
17750
17751             if ((fp = OpenBinaryFileR (tempStr)) == NULL) 
17752                 {
17753                 MrBayesPrint ("%s   Problem openning file %s.\n", spacer, tempStr);
17754                 free (tempStr);
17755                 return (ERROR);
17756                 }
17757
17758             longestLine = LongestLine (fp);
17759             SafeFclose (&fp);
17760
17761             if ((fp = OpenTextFileR (tempStr)) == NULL) 
17762                 {
17763                 free (tempStr);
17764                 return (ERROR);
17765                 }
17766
17767             lineBuf = (char *) SafeCalloc (longestLine + 10, sizeof (char));
17768             if (!lineBuf)
17769                 {
17770                 SafeFclose (&fp);
17771                 free (tempStr);
17772                 return (ERROR);
17773                 }
17774
17775             lastBlock = LastBlock (fp, lineBuf, longestLine);
17776             fseek (fp, lastBlock, SEEK_SET);
17777             fseek (fp, FirstTree(fp, lineBuf, longestLine), SEEK_SET);
17778
17779             for (k=0; k<samplePos; k++)
17780                 {
17781                 if (fgets (lineBuf, longestLine + 5, fp) == NULL) 
17782                     {
17783                     MrBayesPrint ("%s   Not enough records in file %s.\n", spacer, tempStr);
17784                     SafeFclose (&fp);
17785                     free (tempStr);
17786                     free (lineBuf);
17787                     return ERROR;
17788                     }
17789                 }
17790             fgetpos (fp, &chainParams.tFilePos[j*numTopologies+i]);
17791
17792             SafeFclose (&fp);
17793             free (lineBuf);
17794             } /* next run */
17795         } /* next tree */
17796     free (tempStr);
17797     return (NO_ERROR);
17798 }
17799
17800
17801 /* SetFileNames: Set file names */
17802 void SetFileNames (void)
17803 {
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)
17809         {
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);
17814         }
17815     else /* if (chainParams.numRuns > 1) */
17816         {
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);
17821         }
17822 }
17823
17824
17825 /*----------------------------------------------------------------------------
17826 |
17827 |   SetLikeFunctions: This function will set up the pointers from each
17828 |       data division to the relevant likelihood functions
17829 |
17830 -----------------------------------------------------------------------------*/
17831 int SetLikeFunctions (void)
17832 {
17833     int         i;
17834
17835     ModelInfo   *m;
17836
17837     /* couple divisions with likelihood functions */
17838     for (i=0; i<numCurrentDivisions; i++)
17839         {
17840         m = &modelSettings[i];
17841         m->useSSE= NO;
17842         
17843         if (m->dataType == DNA || m->dataType == RNA)
17844             {
17845             if (m->parsModelId == YES)
17846                 {
17847                 m->Likelihood = &Likelihood_Pars;
17848                 }
17849             else
17850                 {
17851                 if (m->nucModelId == NUCMODEL_4BY4)
17852                     {
17853                     if (m->numModelStates > 4)
17854                         {
17855                         /* covariotide model */
17856                         /* TODO: allow autocorrelated rates */
17857                         if (m->gibbsGamma == YES)
17858                             {
17859                             m->CondLikeDown = &CondLikeDown_Gen_GibbsGamma;
17860                             m->CondLikeRoot = &CondLikeRoot_Gen_GibbsGamma;
17861                             m->CondLikeScaler = &CondLikeScaler_Gen_GibbsGamma;
17862                             m->Likelihood = &Likelihood_Gen_GibbsGamma;
17863                             }
17864                         else
17865                             {
17866                             m->CondLikeDown = &CondLikeDown_Gen;
17867                             m->CondLikeRoot = &CondLikeRoot_Gen;
17868                             m->CondLikeScaler = &CondLikeScaler_Gen;
17869                             m->Likelihood = &Likelihood_Gen;
17870                             }
17871                         if (m->correlation != NULL)
17872                             m->Likelihood = &Likelihood_Adgamma;
17873                         else
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;
17881                         }
17882                     else
17883                         {
17884 #   if defined (SSE_ENABLED)
17885                         if (m->printAncStates == YES || m->printSiteRates == YES)
17886                             {
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);
17889                             }
17890
17891                         m->CondLikeUp = &CondLikeUp_NUC4;
17892                         m->PrintAncStates = &PrintAncStates_NUC4;
17893                         m->PrintSiteRates = &PrintSiteRates_Gen;
17894
17895                         if (m->gibbsGamma == YES)
17896                             {
17897                             m->CondLikeDown = &CondLikeDown_NUC4_GibbsGamma;
17898                             m->CondLikeRoot = &CondLikeRoot_NUC4_GibbsGamma;
17899                             m->CondLikeScaler = &CondLikeScaler_NUC4_GibbsGamma;
17900                             }
17901                         else if (m->correlation != NULL || m->printAncStates == YES || m->printSiteRates == YES)
17902                             {
17903                             m->CondLikeDown = &CondLikeDown_NUC4;
17904                             m->CondLikeRoot = &CondLikeRoot_NUC4;
17905                             m->CondLikeScaler = &CondLikeScaler_NUC4;
17906                             }
17907                         else
17908                             {
17909                             m->useSSE= YES;
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;
17918                             }
17919
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;
17926                         else
17927                             m->Likelihood = &Likelihood_NUC4_SSE;
17928 #   else
17929                         if (m->gibbsGamma == YES)
17930                             {
17931                             m->CondLikeDown = &CondLikeDown_NUC4_GibbsGamma;
17932                             m->CondLikeRoot = &CondLikeRoot_NUC4_GibbsGamma;
17933                             m->CondLikeScaler = &CondLikeScaler_NUC4_GibbsGamma;
17934                             }
17935                         else
17936                             {
17937                             m->CondLikeDown = &CondLikeDown_NUC4;
17938                             m->CondLikeRoot = &CondLikeRoot_NUC4;
17939                             m->CondLikeScaler = &CondLikeScaler_NUC4;
17940                             }
17941
17942                         if (m->correlation != NULL)
17943                             m->Likelihood = &Likelihood_Adgamma;
17944                         else if (m->gibbsGamma == YES)
17945                             m->Likelihood = &Likelihood_NUC4_GibbsGamma;
17946                         else
17947                             m->Likelihood = &Likelihood_NUC4;
17948
17949                         m->CondLikeUp = &CondLikeUp_NUC4;
17950                         m->PrintAncStates = &PrintAncStates_NUC4;
17951                         m->PrintSiteRates = &PrintSiteRates_Gen;
17952 #   endif
17953                         if (m->nst == 1)
17954                             m->TiProbs = &TiProbs_Fels;
17955                         else if (m->nst == 2)
17956                             m->TiProbs = &TiProbs_Hky;
17957                         else
17958                             m->TiProbs = &TiProbs_Gen;
17959                         m->StateCode = &StateCode_NUC4;
17960                         }
17961                     }
17962                 else if (m->nucModelId == NUCMODEL_DOUBLET)
17963                     {
17964                     if (m->gibbsGamma == YES)
17965                         {
17966                         m->CondLikeDown = &CondLikeDown_Gen_GibbsGamma;
17967                         m->CondLikeRoot = &CondLikeRoot_Gen_GibbsGamma;
17968                         m->CondLikeScaler = &CondLikeScaler_Gen_GibbsGamma;
17969                         m->Likelihood = &Likelihood_Gen_GibbsGamma;
17970                         }
17971                     else
17972                         {
17973                         m->CondLikeDown = &CondLikeDown_Gen;
17974                         m->CondLikeRoot = &CondLikeRoot_Gen;
17975                         m->CondLikeScaler = &CondLikeScaler_Gen;
17976                         m->Likelihood = &Likelihood_Gen;
17977                         }
17978                     if (m->nst == 1)
17979                         m->TiProbs = &TiProbs_Gen;
17980                     else if (m->nst == 2)
17981                         m->TiProbs = &TiProbs_Gen;
17982                     else
17983                         m->TiProbs = &TiProbs_Gen;
17984                     m->CondLikeUp = &CondLikeUp_Gen;
17985                     m->PrintAncStates = &PrintAncStates_Gen;
17986                     m->PrintSiteRates = &PrintSiteRates_Gen;
17987                     }
17988                 else if (m->nucModelId == NUCMODEL_CODON)
17989                     {
17990                     /* codon models */
17991                     if (m->numOmegaCats == 1)
17992                         {
17993                         if (m->gibbsGamma == YES)
17994                             {
17995                             m->CondLikeDown = &CondLikeDown_Gen_GibbsGamma;
17996                             m->CondLikeRoot = &CondLikeRoot_Gen_GibbsGamma;
17997                             m->CondLikeScaler = &CondLikeScaler_Gen_GibbsGamma;
17998                             m->Likelihood = &Likelihood_Gen_GibbsGamma;
17999                             }
18000                         else
18001                             {
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)
18008                                 {
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);
18011                                 }
18012                             else
18013                                 {
18014                                 m->useSSE= YES;
18015                                 m->CondLikeDown = &CondLikeDown_Gen_SSE;
18016                                 m->CondLikeRoot = &CondLikeRoot_Gen_SSE;
18017                                 m->CondLikeScaler = &CondLikeScaler_Gen_SSE;
18018                                 m->Likelihood = &Likelihood_Gen_SSE;
18019                                 }
18020 #   endif
18021                             }
18022                         }
18023                     else
18024                         {
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)
18033                             {
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);
18036                             }
18037                         else
18038                             {
18039                             m->useSSE= YES;
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;
18046                             }
18047 #   endif
18048                         }
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;
18055                     }
18056                 else /* if (m->nucModelId == NUCMODEL_AA) */
18057                     {
18058                     if (m->gibbsGamma == YES)
18059                         {
18060                         m->CondLikeDown = &CondLikeDown_Gen_GibbsGamma;
18061                         m->CondLikeRoot = &CondLikeRoot_Gen_GibbsGamma;
18062                         m->CondLikeScaler = &CondLikeScaler_Gen_GibbsGamma;
18063                         m->Likelihood = &Likelihood_Gen_GibbsGamma;
18064                         }
18065                     else
18066                         {
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)
18073                             {
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);
18076                             }
18077                         else
18078                             {
18079                             m->useSSE= YES;
18080                             m->CondLikeDown = &CondLikeDown_Gen_SSE;
18081                             m->CondLikeRoot = &CondLikeRoot_Gen_SSE;
18082                             m->CondLikeScaler = &CondLikeScaler_Gen_SSE;
18083                             m->Likelihood = &Likelihood_Gen_SSE;
18084                             }
18085 #   endif
18086                         }
18087                     if (m->nCijkParts > 1)
18088                         m->TiProbs = &TiProbs_GenCov;
18089                     else
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;
18095                     }
18096                 }
18097             }
18098         else if (m->dataType == PROTEIN)
18099             {
18100             if (m->parsModelId == YES)
18101                 {
18102                 m->Likelihood = &Likelihood_Pars;
18103                 }
18104             else
18105                 {
18106                 /* TODO: allow autocorrelated rates for covarion model */
18107                 if (m->gibbsGamma == YES)
18108                     {
18109                     m->CondLikeDown = &CondLikeDown_Gen_GibbsGamma;
18110                     m->CondLikeRoot = &CondLikeRoot_Gen_GibbsGamma;
18111                     m->CondLikeScaler = &CondLikeScaler_Gen_GibbsGamma;
18112                     m->Likelihood = &Likelihood_Gen_GibbsGamma;
18113                     }
18114                 else
18115                     {
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)
18122                         {
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);
18125                         }
18126                     else
18127                         {
18128                         m->useSSE= YES;
18129                         m->CondLikeDown = &CondLikeDown_Gen_SSE;
18130                         m->CondLikeRoot = &CondLikeRoot_Gen_SSE;
18131                         m->CondLikeScaler = &CondLikeScaler_Gen_SSE;
18132                         m->Likelihood = &Likelihood_Gen_SSE;
18133                         }
18134 #   endif
18135                     }
18136                 if (m->correlation != NULL)
18137                     {
18138                     if (m->gibbsGamma == YES)
18139                         {
18140                         MrBayesPrint ("%s   Adgamma model cannot be used with Gibbs sampling of rate categories\n", spacer);
18141                         return (ERROR);
18142                         }
18143                     else
18144                         m->Likelihood = &Likelihood_Adgamma;
18145                     }
18146                 if (m->numModelStates > 20 && m->nCijkParts > 1)
18147                     m->TiProbs = &TiProbs_GenCov;
18148                 else
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;
18154                 }
18155             }
18156         else if (m->dataType == RESTRICTION)
18157             {
18158             if (m->parsModelId == YES)
18159                 {
18160                 m->Likelihood = &Likelihood_Pars;
18161                 }
18162             else
18163                 {
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)
18170                     {
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);
18173                     }
18174                 else
18175                     {
18176                     m->useSSE= YES;
18177                     m->CondLikeDown   = &CondLikeDown_Bin_SSE;
18178                     m->CondLikeRoot   = &CondLikeRoot_Bin_SSE;
18179                     m->CondLikeScaler = &CondLikeScaler_Gen_SSE;
18180                     m->Likelihood     = &Likelihood_Res_SSE;
18181                     }
18182 #   endif
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;
18188                 }
18189             }
18190         else if (m->dataType == STANDARD)
18191             {
18192             if (m->parsModelId == YES)
18193                 {
18194                 if (m->numModelStates == 2)
18195                     {
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 */
18198                     }
18199                 else
18200                     m->Likelihood = &Likelihood_ParsStd;
18201                 }
18202             else
18203                 {
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;
18213                 }
18214             }       
18215         else if (m->dataType == CONTINUOUS)
18216             {
18217             
18218             }       
18219         else
18220             {
18221             MrBayesPrint ("%s   ERROR: Data should be one of these types!\n", spacer);
18222             return ERROR;
18223             }
18224         
18225         }
18226
18227     return NO_ERROR;
18228 }
18229
18230
18231 /* Determine number of chains and data splits to be handled by MPI processors or threads */
18232 int SetLocalChainsAndDataSplits(void)
18233 {
18234 #   if defined (MPI_ENABLED)
18235     
18236     /* tell user how many chains each processor has been assigned */
18237     if (num_procs <= numGlobalChains)
18238         {
18239         if (numGlobalChains % num_procs != 0)
18240             {
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);
18243             /* 
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);
18247             */
18248             MrBayesPrint ("%s   Please change your MPI settings.\n", spacer, num_procs);
18249             return ERROR;
18250             }
18251         numLocalChains = numGlobalChains / num_procs;
18252         MrBayesPrint ("%s   Number of chains per MPI processor = %d\n", spacer, numLocalChains);
18253         }
18254     else
18255         {
18256         MrBayesPrint ("%s   There must be at least as many chains as MPI processors\n", spacer);
18257         return (ERROR);
18258         }
18259         /* 
18260         {
18261         if (num_procs % numGlobalChains != 0)
18262             {
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);
18267             return ERROR;
18268             }
18269         numLocalChains = 1;
18270         // numMPIDataSplits = num_procs / numGlobalChains;
18271         // MrBayesPrint ("%s   Number of MPI data splits per chain = %d\n", spacer, numMPIDataSplits);
18272         }
18273         */
18274 #   else
18275
18276     numLocalChains = numGlobalChains;
18277
18278 #   endif
18279
18280 #   if defined (THREADS_ENABLED)
18281
18282     if (numLocalChains > 1)
18283         {
18284         /* Use pthreads to divide chains and possibly do data splits */
18285         }
18286     else
18287         {
18288         /* Use pthreads for data splits */
18289         }
18290 #   endif
18291
18292     return (NO_ERROR);
18293 }
18294
18295
18296 /*----------------------------------------------------------------------------
18297 |
18298 |   ShowMoveSummary: Show summary of moves that will be used in MCMC sampling
18299 |
18300 -----------------------------------------------------------------------------*/
18301 int ShowMoveSummary (void)
18302 {
18303     int         i, run, chain, areRunsSame, areChainsSame, chainIndex;
18304     MCMCMove    *mv;
18305     MrBFlt      prob;
18306     
18307     /* first find out if the probabilities are different in different runs */           
18308     areRunsSame = YES;
18309     for (run=1; run<chainParams.numRuns; run++)
18310         {
18311         for (chain=0; chain<chainParams.numChains; chain++)
18312             {
18313             chainIndex = run*chainParams.numChains + chain;
18314             for (i=0; i<numUsedMoves; i++)
18315                 {
18316                 mv = usedMoves[i];
18317                 if (AreDoublesEqual (mv->relProposalProb[chainIndex], mv->relProposalProb[chain], 0.000001) == NO)
18318                     {
18319                     areRunsSame = NO;
18320                     break;
18321                     }
18322                 }
18323             if (areRunsSame == NO)
18324                 break;
18325             }
18326         if (areRunsSame == NO)
18327             break;
18328         }
18329
18330     /* now print values */
18331     for (run=0; run<chainParams.numRuns; run++)
18332         {
18333         if (areRunsSame == YES && run >= 1)
18334             break;
18335
18336         /* find out if chains are different within this run */
18337         areChainsSame = YES;
18338         for (chain=1; chain<chainParams.numChains; chain++)
18339             {
18340             chainIndex = run*chainParams.numChains + chain;
18341             for (i=0; i<numUsedMoves; i++)
18342                 {
18343                 mv = usedMoves[i];
18344                 if (AreDoublesEqual (mv->relProposalProb[chainIndex], mv->relProposalProb[chainIndex-chain], 0.000001) == NO)
18345                     {
18346                     areChainsSame = NO;
18347                     break;
18348                     }
18349                 }
18350             if (areChainsSame == NO)
18351                 break;
18352             }
18353
18354         for (chain=0; chain<chainParams.numChains; chain++)
18355             {
18356             if (areChainsSame == YES && chain >= 1)
18357                 break;
18358             
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);
18369
18370             chainIndex = run*chainParams.numChains + chain;
18371             MrBayesPrint ("%s      With prob.  Chain will use move\n", spacer);
18372             for (i=0; i<numUsedMoves; i++)
18373                 {
18374                 mv = usedMoves[i];
18375                 prob = mv->cumProposalProb[chainIndex];
18376                 if (i > 0)
18377                     prob -= usedMoves[i-1]->cumProposalProb[chainIndex];
18378                 if (AreDoublesEqual(prob,0.0,0.000001) == YES)
18379                     continue;
18380                 MrBayesPrint ("%s       %6.2f %%   %s\n", spacer, 100*prob, mv->name);
18381                 }
18382             MrBayesPrint ("\n");
18383             }   /* next chain */
18384         }   /* next run */
18385
18386     return (NO_ERROR);
18387 }
18388
18389
18390 /*----------------------------------------------------------------------
18391 |
18392 |   SetUpPartitionCounters: Set up partitions and the root of the
18393 |      partition frequency tree                         
18394 |
18395 |----------------------------------------------------------------------*/
18396 int SetUpPartitionCounters (void)
18397 {
18398     int     i;
18399     
18400 #   if defined (MPI_ENABLED)
18401     /* we only keep partition counters on proc 0 in the MPI version */
18402     if (proc_id != 0)
18403         return (NO_ERROR);
18404 #   endif
18405     nLongsNeeded = 1 + (numLocalTaxa - 1) / nBitsInALong;
18406     
18407     if (memAllocs[ALLOC_PFCOUNTERS] == YES)
18408         {
18409         MrBayesPrint ("%s   ERROR: pfcounters not free in SetUpPartitionCounters\n", spacer);
18410         return ERROR;
18411         }
18412     partition = (BitsLong **) SafeCalloc (2*numLocalTaxa, sizeof (BitsLong *));
18413     if (partition == NULL)
18414         {
18415         MrBayesPrint ("%s   Failed to allocate partition in SetUpPartitionCounters\n", spacer);
18416         return ERROR;
18417         }
18418     partition[0] = (BitsLong *) SafeCalloc (2*numLocalTaxa * nLongsNeeded, sizeof(BitsLong));
18419     if (partition[0] == NULL)
18420         {
18421         free (partition);
18422         MrBayesPrint ("%s   Failed to allocate partition[0] in SetUpPartitionCounters\n", spacer);
18423         return ERROR;
18424         }
18425     partFreqTreeRoot = (PFNODE **) SafeCalloc (numTopologies, sizeof (PFNODE *));
18426     if (partFreqTreeRoot == NULL)
18427         {
18428         free (partition);
18429         free (partition[0]);
18430         MrBayesPrint ("%s   Failed to allocate partFreqTreeRoot in SetUpPartitionCounters\n", spacer);
18431         return ERROR;
18432         }
18433     memAllocs[ALLOC_PFCOUNTERS] = YES;
18434
18435     for (i=1; i<2*numLocalTaxa; i++)
18436         {
18437         partition[i] = partition[0] + i*nLongsNeeded;
18438         }
18439     
18440     for (i=0; i<numLocalTaxa; i++)
18441         SetBit (i, partition[i]);
18442
18443     for (i=0; i<numTopologies; i++)
18444         partFreqTreeRoot[i] = NULL;
18445
18446     return NO_ERROR;
18447 }
18448
18449
18450 /*----------------------------------------------------------------------
18451 |
18452 |   SetupTermState: create matrix holding unambiguous states for
18453 |       terminals (used for local compression on terminal branches)
18454 |
18455 -----------------------------------------------------------------------*/
18456 int SetUpTermState (void)
18457 {
18458     int         i, k, n, c, d, x=0, *termStatePtr;
18459     BitsLong    *p;
18460     ModelInfo   *m;
18461     ModelParams *mp;
18462     int         numComprChars = 0;
18463
18464     /* allocate space for termState and isPartAmbig */
18465     if (memAllocs[ALLOC_TERMSTATE] == YES || memAllocs[ALLOC_ISPARTAMBIG] == YES)
18466         {
18467         MrBayesPrint ("%s   termState or isPartAmbig is not free in SetupTermState\n", spacer);
18468         return ERROR;
18469         }
18470
18471 #   if defined SSE_ENABLED
18472     for (d=0; d<numCurrentDivisions; d++)
18473         {
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;
18478         else
18479             numComprChars += m->numChars;
18480         }
18481 #   else
18482     numComprChars = numCompressedChars;
18483 #   endif
18484
18485     termState = (int *) SafeCalloc (numLocalTaxa * numComprChars, sizeof(int));
18486     if (termState)
18487         memAllocs[ALLOC_TERMSTATE] = YES;
18488     else
18489         {
18490         MrBayesPrint ("%s   Problem allocating termState\n", spacer);
18491         return (ERROR);
18492         }
18493     isPartAmbig = (int *) SafeCalloc (numLocalTaxa*numCurrentDivisions, sizeof(int));
18494     if (isPartAmbig)
18495         memAllocs[ALLOC_ISPARTAMBIG] = YES;
18496     else
18497         {
18498         MrBayesPrint ("%s   Problem allocating isPartAmbig\n", spacer);
18499         return (ERROR);
18500         }
18501
18502     /*initialize isPartAmbig */
18503     for (i=0; i<numLocalTaxa*numCurrentDivisions; i++)
18504         isPartAmbig[i] = NO;
18505
18506     /* loop over divisions */
18507     termStatePtr = termState;
18508     for (d=0; d<numCurrentDivisions; d++)
18509         {
18510         m = &modelSettings[d];
18511         mp = &modelParams[d];
18512
18513         /* don't do anything for continuous data */
18514         if (mp->dataType == CONTINUOUS)
18515             continue;
18516         
18517         m->termState   = (int **) SafeCalloc (numLocalTaxa, sizeof(int *));
18518         if (!m->termState)
18519             {
18520             MrBayesPrint("%s   Problems allocating termState pointers for division %d\n", spacer, d+1);
18521             return ERROR;
18522             }
18523
18524 #   if defined SSE_ENABLED
18525         if (m->dataType != STANDARD && m->gibbsGamma == NO)
18526             numComprChars = m->numSSEChars * FLOATS_PER_VEC;
18527         else
18528             numComprChars = m->numChars;
18529
18530 #   else
18531             numComprChars = m->numChars;
18532 #   endif
18533
18534         for (i=0; i<numLocalTaxa; i++)
18535             {
18536             m->termState[i] = termStatePtr;
18537             termStatePtr += numComprChars;
18538             }
18539
18540         m->isPartAmbig = isPartAmbig + numLocalTaxa * d;
18541
18542         for (i=0; i<numLocalTaxa; i++)
18543             {
18544             p = m->parsSets[i];
18545             for (c=0; c<m->numChars; c++)
18546                 {
18547                 for (k=n=0; k<m->numStates; k++)
18548                     {
18549                     if (IsBitSet(k, p))
18550                         {
18551                         x = k;
18552                         n++;
18553                         }
18554                     }
18555                 /* find appropriate index */
18556                 if (n == 1)
18557                     m->termState[i][c] = x * m->numModelStates;
18558                 else if (n == m->numStates)
18559                     m->termState[i][c] = m->numStates * m->numModelStates;
18560                 else
18561                     m->isPartAmbig[i] = YES;
18562
18563                 p += m->nParsIntsPerSite;
18564                 }
18565             for (; c<numComprChars; c++)
18566                 {
18567                 /* Setting to fully ambig state all padding chars */
18568                 m->termState[i][c] = m->numStates * m->numModelStates;
18569                 }
18570             }
18571         }
18572
18573     /* print the termState matrix */
18574 #   if  defined (DEBUG_SETUPTERMSTATE)
18575     PrintTermState();
18576     getchar();
18577 #   endif
18578
18579     return NO_ERROR;
18580 }
18581
18582
18583 /*----------------------------------------------------------------------------
18584 |
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
18589 |
18590 -----------------------------------------------------------------------------*/
18591 int SetUsedMoves (void)
18592 {
18593     int         i, j, moveIndex, numGlobalChains;
18594     MrBFlt      prob, sum, cumSum;
18595
18596     /* first count moves */
18597     numUsedMoves = 0;
18598     numGlobalChains = chainParams.numChains * chainParams.numRuns;
18599     for (i=0; i<numApplicableMoves; i++)
18600         {
18601         prob = 0.0;
18602         for (j=0; j<numGlobalChains; j++)
18603             {
18604             if (moves[i]->relProposalProb[j] > prob)
18605                 prob = moves[i]->relProposalProb[j];
18606             }
18607         if (prob > 0.000001)
18608             numUsedMoves++;
18609         }
18610     
18611     /* allocate space */
18612     if (memAllocs[ALLOC_USEDMOVES] == YES)
18613         {
18614         MrBayesPrint ("%s   Memory problem: usedMoves not free in SetUsedMoves\n", spacer);
18615         return (ERROR);
18616         }
18617     usedMoves = (MCMCMove **) SafeMalloc (numUsedMoves * sizeof (MCMCMove *));
18618     if (!usedMoves)
18619         {
18620         MrBayesPrint ("%s   Problem allocating usedMoves\n", spacer);
18621         return (ERROR);
18622         }
18623     memAllocs[ALLOC_USEDMOVES] = YES;
18624         
18625     /* set move pointers */
18626     moveIndex = 0;
18627     for (i=0; i<numApplicableMoves; i++)
18628         {
18629         prob = 0.0;
18630         for (j=0; j<numGlobalChains; j++)
18631             {
18632             if (moves[i]->relProposalProb[j] > prob)
18633                 prob = moves[i]->relProposalProb[j];
18634             }
18635         if (prob > 0.000001)
18636             usedMoves[moveIndex++] = moves[i];
18637         }
18638     
18639     if (moveIndex != numUsedMoves)
18640         {
18641         MrBayesPrint ("%s   Problem finding the used moves\n", spacer);
18642         return (ERROR);
18643         }
18644
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++)
18649         {
18650         if (usedMoves[i]->moveType->parsimonyBased == YES)
18651             {
18652             for (j=0; j<usedMoves[i]->parm->nRelParts; j++)
18653                 modelSettings[usedMoves[i]->parm->relParts[j]].parsimonyBasedMove = YES;
18654             }       
18655         }
18656
18657     /* set cumulative proposal probabilities */
18658     for (j=0; j<numGlobalChains; j++)
18659         {
18660         sum = 0.0;
18661         for (i=0; i<numUsedMoves; i++)
18662             {
18663             sum += usedMoves[i]->relProposalProb[j];
18664             }
18665         cumSum = 0.0;
18666         for (i=0; i<numUsedMoves; i++)
18667             {
18668             cumSum += usedMoves[i]->relProposalProb[j];
18669             usedMoves[i]->cumProposalProb[j] = cumSum / sum;
18670             }
18671         }
18672
18673     /* reset acceptance probability values */
18674     for (i=0; i<numUsedMoves; i++)
18675         {
18676         for (j=0; j<numGlobalChains; j++)
18677             {
18678             usedMoves[i]->nAccepted[j] = 0;
18679             usedMoves[i]->nTried[j] = 0;
18680             usedMoves[i]->nTotAccepted[j] = 0;
18681             usedMoves[i]->nTotTried[j] = 0;
18682             }
18683         }
18684
18685     return (NO_ERROR);
18686 }
18687
18688
18689 void ShowValuesForChain (int chn)
18690 {
18691     int             i;
18692     char            s[100];
18693         
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]);
18698     
18699     strcat (spacer, "   ");
18700
18701     /* tRatio */
18702     for (i=0; i<numCurrentDivisions; i++)
18703         {
18704         sprintf (s, "tRatio[%d]", i);
18705         PrintParamValues (modelSettings[i].tRatio, chn, s);
18706         }
18707
18708     /* revMat */
18709     for (i=0; i<numCurrentDivisions; i++)
18710         {
18711         sprintf (s, "revMat[%d]", i);
18712         PrintParamValues (modelSettings[i].revMat, chn, s);
18713         }
18714
18715     /* stateFreq */
18716     for (i=0; i<numCurrentDivisions; i++)
18717         {
18718         sprintf (s, "stateFreq[%d]", i);
18719         PrintParamValues (modelSettings[i].stateFreq, chn, s);
18720         }
18721
18722     /* omega */
18723     for (i=0; i<numCurrentDivisions; i++)
18724         {
18725         sprintf (s, "omega[%d]", i);
18726         PrintParamValues (modelSettings[i].omega, chn, s);
18727         }
18728
18729     /* shape */
18730     for (i=0; i<numCurrentDivisions; i++)
18731         {
18732         sprintf (s, "shape[%d]", i);
18733         PrintParamValues (modelSettings[i].shape, chn, s);
18734         }
18735
18736     /* pInvar */
18737     for (i=0; i<numCurrentDivisions; i++)
18738         {
18739         sprintf (s, "pInvar[%d]", i);
18740         PrintParamValues (modelSettings[i].pInvar, chn, s);
18741         }
18742
18743     /* correlation */
18744     for (i=0; i<numCurrentDivisions; i++)
18745         {
18746         sprintf (s, "correlation[%d]", i);
18747         PrintParamValues (modelSettings[i].correlation, chn, s);
18748         }
18749
18750     /* switchRates */
18751     for (i=0; i<numCurrentDivisions; i++)
18752         {
18753         sprintf (s, "switchRates[%d]", i);
18754         PrintParamValues (modelSettings[i].switchRates, chn, s);
18755         }
18756
18757     /* rateMult */
18758     for (i=0; i<numCurrentDivisions; i++)
18759         {
18760         sprintf (s, "rateMult[%d]", i);
18761         PrintParamValues (modelSettings[i].rateMult, chn, s);
18762         }
18763
18764     /* speciationRates */
18765     for (i=0; i<numCurrentDivisions; i++)
18766         {
18767         sprintf (s, "speciationRates[%d]", i);
18768         PrintParamValues (modelSettings[i].speciationRates, chn, s);
18769         }
18770
18771     /* extinctionRates */
18772     for (i=0; i<numCurrentDivisions; i++)
18773         {
18774         sprintf (s, "extinctionRates[%d]", i);
18775         PrintParamValues (modelSettings[i].extinctionRates, chn, s);
18776         }
18777
18778     /* fossilizationRates */
18779     for (i=0; i<numCurrentDivisions; i++)
18780         {
18781         sprintf (s, "fossilizationRates[%d]", i);
18782         PrintParamValues (modelSettings[i].fossilizationRates, chn, s);
18783         }
18784
18785     /* popSize */
18786     for (i=0; i<numCurrentDivisions; i++)
18787         {
18788         sprintf (s, "popSize[%d]", i);
18789         PrintParamValues (modelSettings[i].popSize, chn, s);
18790         }
18791
18792     /* topology */
18793     for (i=0; i<numCurrentDivisions; i++)
18794         {
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));
18799         }
18800         
18801     /* brlens */
18802     for (i=0; i<numCurrentDivisions; i++)
18803         {
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));
18808         }
18809
18810     spacer[strlen(spacer) - 3] = '\0';
18811
18812 #   if  0
18813     for (i=0; i<sizeOfParamValues; i++)
18814         MrBayesPrint ("%4d -- %lf\n", i, paramValues[i]);
18815 #   endif
18816 }
18817
18818
18819 /* SmallestNonemptyPFNode: recursive function to smallest nonempty node in a subtree */
18820 PFNODE *SmallestNonemptyPFNode (PFNODE *p, int *i, int j)
18821 {
18822     PFNODE *q;
18823
18824     ++j;
18825     if (p == NULL)
18826         return NULL;
18827     
18828     q = SmallestNonemptyPFNode (p->right, i, j);
18829     
18830     if (q != NULL)
18831         {
18832         return q;
18833         }
18834     else if (IsPFNodeEmpty (p) == NO)
18835         {
18836         *i = j;
18837         return p;
18838         }
18839     else
18840         {
18841         return SmallestNonemptyPFNode (p->left, i, j);
18842         }
18843 }
18844
18845
18846 /* Talloc: Allocate space for a new node in the tree keeping track of partition frequencies */
18847 PFNODE *Talloc (void)
18848 {
18849     PFNODE  *temp;
18850
18851     temp = (PFNODE *) SafeMalloc (sizeof(PFNODE));
18852     if (temp == NULL)
18853         return NULL;
18854
18855     temp->partition = (BitsLong *) SafeCalloc (nLongsNeeded, sizeof (BitsLong));
18856     if (temp->partition == NULL)
18857         {
18858         free (temp);
18859         return NULL;
18860         }
18861
18862     temp->count = (int *) SafeCalloc (chainParams.numRuns, sizeof (int));
18863     if (temp->count == NULL)
18864         {
18865         free (temp->partition);
18866         free (temp);
18867         return NULL;
18868         }
18869
18870     return temp; 
18871 }
18872
18873
18874 MrBFlt Temperature (int id)
18875 {
18876     /* let id be number of chain in run */
18877     id %= chainParams.numChains;
18878     
18879     if (chainParams.userDefinedTemps == YES)
18880         {
18881         return (chainParams.userTemps[id]);
18882         }
18883     else
18884         {
18885         return (1.0 / (1.0 + chainParams.chainTemp * id));
18886         }
18887 }
18888
18889
18890 /* Tfree: Free space for partition frequency counter tree */
18891 void Tfree (PFNODE *r)
18892 {
18893     if (r != NULL)
18894         {
18895         if (r->left != NULL)
18896             Tfree (r->left);
18897         if (r->right != NULL)
18898             Tfree (r->right);
18899
18900         free (r->partition);
18901         free (r->count);
18902         free (r);
18903         }
18904 }
18905
18906
18907 void TouchAllCijks (int chain)
18908 {
18909     int i;
18910
18911     for (i=0; i<numCurrentDivisions; i++)
18912         {
18913         if (modelSettings[i].nCijkParts >= 1)
18914             modelSettings[i].upDateCijk = YES;
18915         }
18916
18917     return;
18918     MrBayesPrint ("%d", chain); /* just because I am tired of seeing the unused parameter error msg */
18919 }
18920
18921
18922 void TouchAllPartitions (void)
18923 {
18924     int i;
18925
18926     for (i=0; i<numCurrentDivisions; i++)
18927         {
18928         modelSettings[i].upDateCl = YES;
18929         }
18930
18931     return;
18932 }
18933
18934
18935 void TouchAllTrees (int chain)
18936 {
18937     int         i, j;
18938     Tree        *t;
18939     TreeNode    *p;
18940
18941     for (i=0; i<numTrees; i++)
18942         {
18943         t = GetTreeFromIndex (i, chain, state[chain]);
18944         for (j=0; j<t->nNodes; j++)
18945             {
18946             p = t->allDownPass[j];
18947             p->upDateCl = YES;
18948             p->upDateTi = YES;
18949             }
18950         }
18951
18952     for (i=0; i<numCurrentDivisions; i++)
18953         modelSettings[i].upDateAll = YES;
18954
18955     return;
18956 }
18957
18958
18959 /* Touch all update flags so we recalculate likelihood from scratch */
18960 void TouchEverything (int chain)
18961 {
18962     int         i, j;
18963     Tree        *t;
18964     TreeNode    *p;
18965
18966     for (i=0; i<numCurrentDivisions; i++)
18967         {
18968         if (modelSettings[i].nCijkParts >= 1)
18969             modelSettings[i].upDateCijk = YES;
18970         modelSettings[i].upDateCl = YES;
18971         modelSettings[i].upDateAll = YES;
18972         }
18973
18974     for (i=0; i<numTrees; i++)
18975         {
18976         t = GetTreeFromIndex (i, chain, state[chain]);
18977         for (j=0; j<t->nNodes; j++)
18978             {
18979             p = t->allDownPass[j];
18980             p->upDateCl = YES;
18981             p->upDateTi = YES;
18982             }
18983         }
18984
18985     return;
18986 }
18987
18988
18989 /*------------------------------------------------------------------
18990 |
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.
18995 |
18996 -------------------------------------------------------------------*/
18997 MrBFlt TreeLength (Param *param, int chain)
18998 {
18999     int             i, j;
19000     MrBFlt          tl;
19001     Tree            *t;
19002     TreeNode        *p;
19003
19004     if (param->paramId == BRLENS_PARSIMONY)
19005         {
19006         tl = 0.0;
19007         for (j=0; j<param->nRelParts; j++)
19008             tl += modelSettings[param->relParts[j]].parsTreeLength[2*chain+state[chain]];
19009         }
19010     else
19011         {
19012         /* get tree */
19013         t = GetTree (param, chain, state[chain]);
19014         
19015         /* loop over all branches of the tree */
19016         tl = 0.0;
19017         for (i=0; i<t->nNodes; i++)
19018             {
19019             p = t->allDownPass[i];
19020             if (p->anc != NULL)
19021                 {
19022                 if (p->anc->anc == NULL && t->isRooted == NO)
19023                     {
19024                     tl += p->length;
19025                     }
19026                 else
19027                     {
19028                     tl += p->length;
19029                     }
19030                 }
19031             }
19032         }
19033                 
19034     return (tl);
19035 }
19036
19037
19038 /* proportion of ancestral fossils in a FBD tree */
19039 MrBFlt PropAncFossil (Param *param, int chain)
19040 {
19041     int             i, m, k;
19042     Tree            *t;
19043     TreeNode        *p;
19044  
19045     t = GetTree (param, chain, state[chain]);
19046     
19047     if (t->isRooted == NO)
19048         return 0.0;
19049     
19050     /* count # of tip and ancestral fossils */
19051     m = k = 0;
19052     for (i = 0; i < t->nNodes -2; i++)
19053         {
19054         p = t->allDownPass[i];
19055         if (p->left == NULL && p->right == NULL && p->nodeDepth > 0.0)
19056             {
19057             if (p->length > 0.0)
19058                 m++;
19059             else
19060                 k++;
19061             }
19062         }
19063     
19064     if (k == 0)
19065         return 0.0;
19066     else
19067         return (MrBFlt)k / (m+k);
19068 }
19069