7 * Dept. Integrative Biology
8 * University of California, Berkeley
9 * Berkeley, CA 94720-3140
13 * Swedish Museum of Natural History
15 * SE-10405 Stockholm, SWEDEN
16 * fredrik.ronquist@nrm.se
18 * With important contributions by
20 * Paul van der Mark (paulvdm@sc.fsu.edu)
21 * Maxim Teslenko (maxim.teslenko@nrm.se)
23 * and by many users (run 'acknowledgments' to see more info)
25 * This program is free software; you can redistribute it and/or
26 * modify it under the terms of the GNU General Public License
27 * as published by the Free Software Foundation; either version 2
28 * of the License, or (at your option) any later version.
30 * This program is distributed in the hope that it will be useful,
31 * but WITHOUT ANY WARRANTY; without even the implied warranty of
32 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
33 * GNU General Public License for more details (www.gnu.org).
44 const char* const svnRevisionUtilsC = "$Rev: 1062 $"; /* Revision keyword which is expended/updated by svn on each commit/update */
46 #define MAX_GAMMA_CATS 20
47 #define PI 3.14159265358979324
48 #define PIOVER2 1.57079632679489662
49 #define POINTGAMMA(prob,alpha,beta) PointChi2(prob,2.0*(alpha))/(2.0*(beta))
50 #define PAI2 6.283185307
52 #define EVALUATE_COMPLEX_NUMBERS 2
54 #define MAX(a,b) (((a) > (b)) ? (a) : (b))
57 #define MIN(a,b) (((a) < (b)) ? (a) : (b))
59 #define SQUARE(a) ((a)*(a))
61 /* local global variable */
64 /* local prototypes */
65 void DatedNodeDepths (TreeNode *p, MrBFlt *nodeDepths, int *index);
66 void DatedNodes (TreeNode *p, TreeNode **datedTips, int *index);
67 int NConstrainedTips (TreeNode *p);
68 int NDatedTips (TreeNode *p);
69 void PrintNode (char **s, int *len, TreeNode *p, int isRooted);
70 void ResetPolyNode (PolyNode *p);
71 void ResetTreeNode (TreeNode *p);
72 void SetNodeDepths (Tree *t);
74 void AddTwoMatrices (int dim, MrBFlt **a, MrBFlt **b, MrBFlt **result);
75 void BackSubstitutionRow (int dim, MrBFlt **u, MrBFlt *b);
76 void Balanc (int dim, MrBFlt **a, int *low, int *high, MrBFlt *scale);
77 void BalBak (int dim, int low, int high, MrBFlt *scale, int m, MrBFlt **z);
78 MrBFlt BetaCf (MrBFlt a, MrBFlt b, MrBFlt x);
79 MrBFlt BetaQuantile (MrBFlt alpha, MrBFlt beta, MrBFlt x);
80 MrBFlt CdfBinormal (MrBFlt h1, MrBFlt h2, MrBFlt r);
81 MrBFlt CdfNormal (MrBFlt x);
82 complex Complex (MrBFlt a, MrBFlt b);
83 MrBFlt ComplexAbsoluteValue (complex a);
84 complex ComplexAddition (complex a, complex b);
85 complex ComplexConjugate (complex a);
86 complex ComplexDivision (complex a, complex b);
87 void ComplexDivision2 (MrBFlt ar, MrBFlt ai, MrBFlt br, MrBFlt bi, MrBFlt *cr, MrBFlt *ci);
88 complex ComplexExponentiation (complex a);
89 int ComplexInvertMatrix (int dim, complex **a, MrBFlt *dwork, int *indx, complex **aInverse, complex *col);
90 complex ComplexLog (complex a);
91 void ComplexLUBackSubstitution (int dim, complex **a, int *indx, complex *b);
92 int ComplexLUDecompose (int dim, complex **a, MrBFlt *vv, int *indx, MrBFlt *pd);
93 complex ComplexMultiplication (complex a, complex b);
94 complex ComplexSquareRoot (complex a);
95 complex ComplexSubtraction (complex a, complex b);
96 int ComputeEigenSystem (int dim, MrBFlt **a, MrBFlt *v, MrBFlt *vi, MrBFlt **u, int *iwork, MrBFlt *dwork);
97 void ComputeLandU (int dim, MrBFlt **aMat, MrBFlt **lMat, MrBFlt **uMat);
98 void ComputeMatrixExponential (int dim, MrBFlt **a, int qValue, MrBFlt **f);
99 void DivideByTwos (int dim, MrBFlt **a, int power);
100 MrBFlt D_sign (MrBFlt a, MrBFlt b);
101 int EigensForRealMatrix (int dim, MrBFlt **a, MrBFlt *wr, MrBFlt *wi, MrBFlt **z, int *iv1, MrBFlt *fv1);
102 void ElmHes (int dim, int low, int high, MrBFlt **a, int *interchanged);
103 void ElTran (int dim, int low, int high, MrBFlt **a, int *interchanged, MrBFlt **z);
104 void Exchange (int j, int k, int l, int m, int n, MrBFlt **a, MrBFlt *scale);
105 MrBFlt Factorial (int x);
106 void ForwardSubstitutionRow (int dim, MrBFlt **L, MrBFlt *b);
107 MrBFlt GammaRandomVariable (MrBFlt a, MrBFlt b, RandLong *seed);
108 void GaussianElimination (int dim, MrBFlt **a, MrBFlt **bMat, MrBFlt **xMat);
109 int Hqr2 (int dim, int low, int high, MrBFlt **h, MrBFlt *wr, MrBFlt *wi, MrBFlt **z);
110 MrBFlt IncompleteBetaFunction (MrBFlt alpha, MrBFlt beta, MrBFlt x);
111 MrBFlt IncompleteGamma (MrBFlt x, MrBFlt alpha, MrBFlt LnGamma_alpha);
112 int InvertMatrix (int dim, MrBFlt **a, MrBFlt *col, int *indx, MrBFlt **aInv);
113 MrBFlt LBinormal (MrBFlt h1, MrBFlt h2, MrBFlt r);
114 int LogBase2Plus1 (MrBFlt x);
115 void LUBackSubstitution (int dim, MrBFlt **a, int *indx, MrBFlt *b);
116 int LUDecompose (int dim, MrBFlt **a, MrBFlt *vv, int *indx, MrBFlt *pd);
117 void MultiplyMatrixByScalar (int dim, MrBFlt **a, MrBFlt scalar, MrBFlt **result);
118 MrBFlt PointChi2 (MrBFlt prob, MrBFlt v);
119 void PrintComplexVector (int dim, complex *vec);
120 void PrintSquareComplexMatrix (int dim, complex **m);
121 void PrintSquareDoubleMatrix (int dim, MrBFlt **matrix);
122 void PrintSquareIntegerMatrix (int dim, int **matrix);
123 complex ProductOfRealAndComplex (MrBFlt a, complex b);
124 MrBFlt RndGamma (MrBFlt s, RandLong *seed);
125 MrBFlt RndGamma1 (MrBFlt s, RandLong *seed);
126 MrBFlt RndGamma2 (MrBFlt s, RandLong *seed);
127 int SetQvalue (MrBFlt tol);
128 void SetToIdentity (int dim, MrBFlt **matrix);
129 MrBFlt Tha (MrBFlt h1, MrBFlt h2, MrBFlt a1, MrBFlt a2);
130 void TiProbsUsingEigens (int dim, MrBFlt *cijk, MrBFlt *eigenVals, MrBFlt v, MrBFlt r, MrBFlt **tMat, MrBFlt **fMat, MrBFlt **sMat);
131 void TiProbsUsingPadeApprox (int dim, MrBFlt **qMat, MrBFlt v, MrBFlt r, MrBFlt **tMat, MrBFlt **fMat, MrBFlt **sMat);
133 MrBFlt QuantileLogNormal (MrBFlt prob, MrBFlt mu, MrBFlt sigma);
134 int DiscreteLogNormal (MrBFlt *rK, MrBFlt sigma, int K, int median);
135 MrBFlt LogNormalPoint (MrBFlt x, MrBFlt mu, MrBFlt sigma);
137 /* AddBitfield: Add bitfield to list of bitfields. The function uses global variable nLongsNeeded. */
138 int AddBitfield (BitsLong ***list, int listLen, int *set, int setLen)
142 nLongsNeeded = (setLen - 1) / nBitsInALong + 1;
144 (*list) = (BitsLong **) SafeRealloc ((void *)(*list), ((size_t)listLen+1)*sizeof(BitsLong *));
148 (*list)[listLen] = (BitsLong *) SafeMalloc ((size_t)nLongsNeeded*sizeof(BitsLong));
149 if (!(*list)[listLen])
152 ClearBits ((*list)[listLen], nLongsNeeded);
153 for (i=0; i<setLen; i++)
155 SetBit(i, (*list)[listLen]);
161 #if defined (SSE_ENABLED)
162 void * AlignedMalloc (size_t size, size_t alignment)
166 #if defined GCC_SSE /* gcc compiler */
167 if (posix_memalign (&mem, alignment, size))
169 #elif defined ICC_SSE /* icc compiler */
170 mem = _mm_malloc (size, alignment);
171 #elif defined MS_VCPP_SSE /* ms visual */
172 mem = _aligned_malloc (size, alignment);
181 void AlignedSafeFree (void **ptr)
184 #if defined ICC_SSE /* icc compiler */
186 #elif defined MS_VCPP_SSE /* ms visual */
187 _aligned_free (*ptr);
197 int AreBitfieldsEqual (BitsLong *p, BitsLong *q, int length)
201 for (i=0; i<length; i++)
211 /*----------------------------------------------------------------
213 | Bit: return 1 if bit n is set in BitsLong *p
216 -----------------------------------------------------------------*/
217 int Bit (int n, BitsLong *p)
219 BitsLong x, bitsLongOne;
223 p += n / nBitsInALong;
224 x = bitsLongOne << (n % nBitsInALong);
234 /* ClearBit: Clear one bit in a bitfield */
235 void ClearBit (int i, BitsLong *bits)
237 BitsLong x, bitsLongOne=1;
239 bits += i / nBitsInALong;
241 x = bitsLongOne << (i % nBitsInALong);
242 x ^= bitsLongWithAllBitsSet;
248 /* ClearBits: Clear all bits in a bitfield */
249 void ClearBits (BitsLong *bits, int nLongs)
253 for (i=0; i<nLongs; i++)
259 void CopyBits (BitsLong *dest, BitsLong *source, int length)
263 for (i=0; i<length; i++)
268 /* CopyResults: copy results from one file to another up to lastGen*/
269 int CopyResults (FILE *toFile, char *fromFileName, int lastGen)
272 char *strBuf, *strCpy, *word;
275 if ((fromFile = OpenBinaryFileR(fromFileName)) == NULL)
278 longestLine = LongestLine(fromFile)+10;
279 SafeFclose(&fromFile);
280 strBuf = (char *) SafeCalloc (2*(longestLine+2),sizeof(char));
281 strCpy = strBuf + longestLine + 2;
283 if ((fromFile = OpenTextFileR(fromFileName)) == NULL)
286 while (fgets(strBuf,longestLine,fromFile)!=NULL)
288 strncpy (strCpy,strBuf,longestLine);
289 word = strtok(strCpy," ");
290 /* atoi returns 0 when word is not integer number */
291 if (atoi(word)>lastGen)
293 fprintf (toFile,"%s",strBuf);
297 SafeFclose(&fromFile);
303 /* CopyProcessSsFile: copy results from one file to another up to lastStep. Also marginalLnLSS is collected for processed steps*/
304 int CopyProcessSsFile (FILE *toFile, char *fromFileName, int lastStep, MrBFlt *marginalLnLSS, MrBFlt * splitfreqSS)
306 int longestLine, run, curStep, i;
308 char *strBuf, *strCpy, *word, *tmpcp;
311 if ((fromFile = OpenBinaryFileR(fromFileName)) == NULL)
314 longestLine = LongestLine(fromFile)+10;
315 SafeFclose(&fromFile);
316 strBuf = (char *) SafeCalloc (2*(longestLine+2),sizeof(char));
317 strCpy = strBuf + longestLine + 2;
319 if ((fromFile = OpenTextFileR(fromFileName)) == NULL)
322 while (fgets(strBuf,longestLine,fromFile)!=NULL)
324 strncpy (strCpy,strBuf,longestLine);
325 word = strtok(strCpy," \t\n");
326 /* atoi returns 0 when word is not integer number */
327 if (atoi(word)>lastStep)
329 fprintf (toFile,"%s",strBuf);
331 curStep = atoi(word);
334 strtok(NULL,"\t\n"); /*skip power*/
335 for (run=0; run<chainParams.numRuns; run++)
337 tmpcp = strtok(NULL,"\t\n");
340 MrBayesPrint ("%s Error: In .ss file not enough ellements on the string :%s \n", spacer, strBuf);
346 MrBayesPrint ("%s Error: Value of some step contribution is 0.0 or not a number in .ss file. Sting:%s \n", spacer, strBuf);
349 marginalLnLSS[run]+=tmp;
351 for (i=0; i<numTopologies; i++)
353 tmpcp = strtok(NULL,"\t\n");
356 MrBayesPrint ("%s Error: In .ss file not enough ellements on the string :%s \n", spacer, strBuf);
360 splitfreqSS[i*chainParams.numStepsSS + curStep-1] = tmp;
365 SafeFclose(&fromFile);
371 /* CopyTreeResults: copy tree results upto lastGen from one file to another. numTrees is return containing number of trees that were copied. */
372 int CopyTreeResults (FILE *toFile, char *fromFileName, int lastGen, int *numTrees)
375 char *strBuf, *strCpy, *word;
380 if ((fromFile = OpenBinaryFileR(fromFileName)) == NULL)
383 longestLine = LongestLine(fromFile)+10;
384 SafeFclose(&fromFile);
385 strBuf = (char *) SafeCalloc (2*(longestLine+2),sizeof(char));
386 strCpy = strBuf + longestLine + 2;
388 if ((fromFile = OpenTextFileR(fromFileName)) == NULL)
391 while (fgets(strBuf,longestLine,fromFile)!=NULL)
393 strncpy (strCpy,strBuf,longestLine);
394 word = strtok(strCpy," ");
395 if (strcmp(word,"tree")==0)
397 word = strtok(NULL," ");
398 /* atoi returns 0 when word is not integer number,
399 4 is offset to get rid of "rep." in tree name */
400 if (atoi(word+4)>lastGen)
403 fprintf (toFile,"%s",strBuf);
405 else if (*numTrees == 0) /* do not print the end statement */
406 fprintf (toFile,"%s",strBuf);
410 SafeFclose(&fromFile);
416 /* FirstTaxonInPartition: Find index of first taxon in partition */
417 int FirstTaxonInPartition (BitsLong *partition, int length)
419 int i, j, nBits, taxon;
420 BitsLong x, bitsLongOne=1;
422 nBits = sizeof(BitsLong) * 8;
425 for (i=0; i<length; i++)
428 for (j=0; j<nBits; j++)
430 if (partition[i] & x)
441 /* FirstTree: Return file position of first tree after current position */
442 long FirstTree (FILE *fp, char *lineBuf, int longestLine)
448 firstTree = ftell(fp);
449 if ((fgets (lineBuf, longestLine, fp)) == NULL)
451 word = strtok (lineBuf, " ");
452 } while (strcmp(word,"tree")!=0);
467 void FlipBits (BitsLong *partition, int length, BitsLong *mask)
471 for (i=0; i<length; i++)
473 partition[i] ^= mask[i];
478 /*-----------------------------------------------------------------
480 | FlipOneBit: flip bit n in BitsLong *p
482 ------------------------------------------------------------------*/
483 void FlipOneBit (int n, BitsLong *p)
485 BitsLong x, bitsLongOne=1;
488 x = bitsLongOne << (n % nBitsInALong);
493 /* Convert from 0-based growth function over six states to model index */
494 int FromGrowthFxnToIndex(int *growthFxn)
496 int i, j, k, max, fxn[6];
498 /* set local growth fxn to lexicographical max */
502 /* decrease until we reach growthFxn */
503 for (k=202; k>=0; k--)
507 if (fxn[i] != growthFxn[i])
513 /* get next growth fxn */
522 return -1; /* error */
533 fxn[i] = fxn[i-1] + 1;
541 /* Convert from model index to 0-based growth function over six states */
542 void FromIndexToGrowthFxn(int index, int *growthFxn)
546 /* set growth fxn to lexicographical max */
550 /* decrease until we reach index */
551 for (k=202; k>index; k--)
556 if (growthFxn[i] >= 0)
567 if (growthFxn[j] > max)
570 growthFxn[++i] = max + 1;
572 growthFxn[i] = growthFxn[i-1] + 1;
578 /* GetIntSummary: Get summary statistics for a number of runs (int version) */
579 void GetIntSummary (int **vals, int nRows, int *rowCount, Stat *theStats, int HPD)
582 MrBFlt *theValues, *p;
585 for (i=0; i<nRows; i++)
586 nVals += rowCount[i];
588 theValues = (MrBFlt *) SafeCalloc (nVals, sizeof(MrBFlt));
592 for (i=0; i<nRows; i++)
594 for (j=0; j<rowCount[i]; j++)
596 (*p++) = (MrBFlt) (vals[i][j]);
601 MeanVariance (theValues, nVals, &(theStats->mean), &(theStats->var));
603 LowerUpperMedian (theValues, nVals, &(theStats->lower), &(theStats->upper), &(theStats->median));
605 LowerUpperMedian (theValues, nVals, &(theStats->lower), &(theStats->upper), &(theStats->median));
611 /* Get k from 0-based growth function */
612 int GetKFromGrowthFxn(int *growthFxn)
617 if (growthFxn[i] > k)
624 /* GetSummary: Get summary statistics for a number of runs */
625 void GetSummary (MrBFlt **vals, int nRows, int *rowCount, Stat *theStats, int HPD)
628 MrBFlt *theValues, *p, *ESS;
631 for (i=0; i<nRows; i++)
632 nVals += rowCount[i];
634 theValues = (MrBFlt *) SafeMalloc ((size_t)nVals * sizeof(MrBFlt));
638 for (i=0; i<nRows; i++)
640 memcpy ((void *)(p), (void *)(vals[i]), (size_t)rowCount[i] * sizeof(MrBFlt));
645 MeanVariance (theValues, nVals, &(theStats->mean), &(theStats->var));
647 LowerUpperMedianHPD (theValues, nVals, &(theStats->lower), &(theStats->upper), &(theStats->median));
649 LowerUpperMedian (theValues, nVals, &(theStats->lower), &(theStats->upper), &(theStats->median));
651 theStats->PSRF = PotentialScaleReduction (vals, nRows, rowCount);
653 ESS = (MrBFlt *) SafeMalloc ((size_t)nRows * sizeof(MrBFlt));
655 EstimatedSampleSize (vals, nRows, rowCount, ESS);
656 theStats->avrESS = theStats->minESS = ESS[0];
657 for (i=1; i<nRows; i++)
659 theStats->avrESS += ESS[i];
660 if (theStats->minESS > ESS[i])
662 theStats->minESS = ESS[i];
665 theStats->avrESS /=nRows;
672 /* HarmonicArithmeticMean: Calculate harmonic and arithmetic mean from log values */
673 int HarmonicArithmeticMeanOnLogs (MrBFlt *vals, int nVals, MrBFlt *mean, MrBFlt *harm_mean)
676 MrBFlt a, x, y, scaler, n;
680 scaler = vals[nVals-1];
682 for (i=0; i<nVals; i++)
709 /* arithmetic mean */
710 (*mean) = (MrBFlt) log(a/n) + scaler;
712 scaler = (MrBFlt) (0.0 - vals[nVals-1]);
714 for (i=0; i<nVals; i++)
716 y = (MrBFlt) (0.0 - vals[i]);
742 (*harm_mean) = - (MrBFlt) log(a/n) - scaler;
751 /* IsBitSet: Is bit i set in BitsLong *bits ? */
752 int IsBitSet (int i, BitsLong *bits)
754 BitsLong x, bitsLongOne=1;
756 bits += i / nBitsInALong;
758 x = bitsLongOne << (i % nBitsInALong);
767 /* IsConsistentWith: Is token consistent with expected word, case insensitive ? */
768 int IsConsistentWith (const char *token, const char *expected)
772 if (strlen(token) > strlen(expected))
775 len = (int) strlen (token);
777 for (i=0; i<len; i++)
779 if (tolower(token[i]) != tolower(expected[i]))
787 /* IsPartCompatible: Determine whether two partitions are nonoverlapping or nested (compatible) or
788 incompatible (partially overlapping) */
789 int IsPartCompatible (BitsLong *smaller, BitsLong *larger, int length)
793 /* test first if they overlap */
794 for (i=0; i<length; i++)
795 if ((smaller[i]&larger[i]) != 0)
798 /* if they overlap, they must be nested */
799 if (i != length) /* potentially incompatible */
801 for (i=0; i<length; i++)
802 if ((smaller[i]|larger[i]) != larger[i])
806 if (i == length) /* passed either one of the tests */
813 /* IsPartNested: Test whether smaller partition is nested in larger partition */
814 int IsPartNested (BitsLong *smaller, BitsLong *larger, int length)
818 for (i=0; i<length; i++)
819 if ((smaller[i] | larger[i]) != larger[i])
829 /* IsSectionEmpty: Test whether section of two bitfields is empty */
830 int IsSectionEmpty (BitsLong *bitField1, BitsLong *bitField2, int length)
834 for (i=0; i<length; i++)
835 if ((bitField1[i] & bitField2[i]) != 0)
842 /* IsSectionEmpty: Test whether union of bitField1 and bitField2 equal to bitField3*/
843 int IsUnionEqThird (BitsLong *bitField1, BitsLong *bitField2, BitsLong *bitField3, int length)
847 for (i=0; i<length; i++)
848 if ((bitField1[i] | bitField2[i]) != bitField3[i])
855 /* LastBlock: Return file position of last block in file */
856 long LastBlock (FILE *fp, char *lineBuf, int longestLine)
864 while ((fgets (lineBuf, longestLine, fp)) != NULL)
866 word = strtok (lineBuf, " ");
867 if (strcmp (word, "begin") == 0)
868 lastBlock = ftell (fp);
875 int LineTermType (FILE *fp)
877 int ch, nextCh, term;
879 term = LINETERM_UNIX; /* default if no line endings are found */
880 while ((ch = getc(fp)) != EOF)
882 if ((ch == '\n') || (ch == '\r'))
885 term = LINETERM_UNIX;
888 /* First test below handles one-line MAC file */
889 if (((nextCh = getc(fp)) == EOF) || (nextCh != '\n'))
897 (void)fseek(fp, 0L, 0); /* rewind */
903 /*The longest line in a file including line terminating characters present in binary mode.*/
904 int LongestLine (FILE *fp)
906 int ch, lineLength, longest;
913 if ((ch != '\n') && (ch != '\r'))
921 if ((ch = fgetc(fp)) == '\n')
932 else /*unix, linux,new mac or text mode read \n*/
937 if (lineLength > longest)
938 longest = lineLength;
941 if ((ch == '\n') || (ch == '\r'))
943 if (lineLength > longest)
944 longest = lineLength;
951 rewind (fp); /* rewind */
953 return (longest+1); /*+1 to accommodate last character*/
957 /* LowerUpperMedian: Determine median and 95 % credible interval */
958 void LowerUpperMedian (MrBFlt *vals, int nVals, MrBFlt *lower, MrBFlt *upper, MrBFlt *median)
961 SortMrBFlt (vals, 0, nVals-1);
963 *lower = vals[(int)(0.025*nVals)];
964 *upper = vals[(int)(0.975*nVals)];
965 *median = vals[nVals/2];
970 /* LowerUpperMedianHPD: Use a simple way to determine HPD */
971 void LowerUpperMedianHPD (MrBFlt *vals, int nVals, MrBFlt *lower, MrBFlt *upper, MrBFlt *median)
973 int i, width, theStart;
974 MrBFlt f, g, interval;
976 SortMrBFlt (vals, 0, nVals-1);
978 width = (int)(nVals * 0.95 + 0.5);
980 interval = vals[width-1] - vals[0];
981 for (i=1; i<nVals-width; i++)
985 if (g - f < interval)
992 *lower = vals[theStart];
993 *upper = vals[theStart+width-1];
994 *median = vals[nVals/2];
998 MrBFlt MaximumValue (MrBFlt x, MrBFlt y)
1007 MrBFlt MinimumValue (MrBFlt x, MrBFlt y)
1016 /* NOTE!!!! The result of this function should be used before consequtive call to it again.
1017 It means NEVER use it like this: printf ("%s %s", MbPrintNum (a),MbPrintNum (b)) */
1018 char *MbPrintNum (MrBFlt num)
1022 if (scientific == YES)
1023 sprintf (s,"%.*le", precision, num);
1025 sprintf (s,"%.*lf", precision, num);
1031 void MeanVariance (MrBFlt *vals, int nVals, MrBFlt *mean, MrBFlt *var)
1034 MrBFlt a, aOld, s, x;
1037 for (i=0; i<nVals; i++)
1041 a += (x - a) / (MrBFlt) (i + 1);
1042 s += (x - a) * (x - aOld);
1052 (*var) = s / (nVals - 1);
1056 /* Compute mean and variance of log scaled values.
1057 @param vals pointer to values in log scale
1058 @param nVals number of "vals", minimum 1
1059 @param mean adress of variable where computed mean is returned by the function
1060 @param var adress of variable where computed variance is returned by the function. Could be set to NULL if this value need not to be returened.
1061 @param varEst adress of variable where computed estimate of the population variance is returned, could be set to NULL if this value need not to be returened.
1062 Could be set to NULL if this value need not to be returened.
1063 Note: We devide by nVals or by (nVals-1) when var and varEst is calculated from the sum of square differences. */
1064 void MeanVarianceLog (MrBFlt *vals, int nVals, MrBFlt *mean, MrBFlt *var, MrBFlt *varEst)
1067 MrBFlt a, aOld, s, x, y, scaler;
1070 scaler = vals[nVals-1];
1071 for (i=0; i<nVals; i++)
1077 a /= exp(y - 100.0);
1078 s /= exp(2*(y - 100));
1079 scaler += y - 100.0;
1086 a += (x - a) / (MrBFlt) (i + 1);
1087 s += (x - a) * (x - aOld);
1091 (*mean) = log(a) + scaler;
1099 (*var) = log(s / nVals) + 2*scaler;
1108 (*varEst) = log(s / (nVals+1)) + 2*scaler;
1113 void MrBayesPrint (char *format, ...)
1117 # if defined (MPI_ENABLED)
1122 va_start (ptr, format);
1123 vprintf (format, ptr);
1127 if (logToFile == YES)
1129 if (logFileFp == NULL)
1130 printf ("%s Could not print log output to file\n", spacer);
1133 va_start (ptr, format);
1134 vfprintf (logFileFp, format, ptr);
1141 if (chainParams.redirect == NO)
1145 va_start (ptr, format);
1146 vprintf (format, ptr);
1150 if (logToFile == YES)
1152 if (logFileFp == NULL)
1154 printf ("%s Could not print log output to file\n", spacer);
1159 va_start (ptr, format);
1160 vfprintf (logFileFp, format, ptr);
1170 void MrBayesPrintf (FILE *f, char *format, ...)
1174 # if defined (MPI_ENABLED)
1177 va_start (ptr, format);
1178 vfprintf (f, format, ptr);
1183 va_start (ptr, format);
1184 vfprintf (f, format, ptr);
1191 /** Next taxon in partition, for cycling over set bits in bit fields */
1192 int NextTaxonInPartition(int currentTaxon, BitsLong *partition, int length)
1195 BitsLong x, bitsLongOne=1;
1197 taxon = currentTaxon + 1;
1198 i = taxon / nBitsInALong;
1199 x = (bitsLongOne << taxon % nBitsInALong);
1200 for (j=taxon%nBitsInALong; j<nBitsInALong; j++)
1202 if (partition[i] & x)
1208 for (i++; i<length; i++)
1211 for (j=0; j<nBitsInALong; j++)
1213 if (partition[i] & x)
1224 /* NBits: count bits in an int */
1229 for (n=0; x != 0; n++)
1236 /* NumBits: Count bits in a bitfield */
1237 int NumBits (BitsLong *x, int len)
1242 for (i=0; i<len; i++)
1255 FILE *OpenBinaryFileR (char *name)
1260 strcpy(fileName, workingDir);
1261 strncat(fileName, name, 199 - strlen(fileName));
1263 if ((fp = fopen (fileName, "rb")) == NULL)
1265 MrBayesPrint ("%s Could not open file \"%s\"\n", spacer, name);
1273 FILE *OpenTextFileR (char *name)
1278 strcpy(fileName, workingDir);
1279 strncat(fileName, name, 199 - strlen(fileName));
1281 if ((fp = fopen (fileName, "r")) == NULL)
1283 MrBayesPrint ("%s Could not open file \"%s\"\n", spacer, fileName);
1291 FILE *OpenTextFileRQuait (char *name)
1296 strcpy(fileName, workingDir);
1297 strncat(fileName, name, 199 - strlen(fileName));
1299 if ((fp = fopen (fileName, "r")) == NULL)
1308 FILE *OpenTextFileA (char *name)
1313 strcpy(fileName, workingDir);
1314 strncat(fileName, name, 199 - strlen(fileName));
1316 if ((fp = fopen (fileName, "a+")) == NULL)
1318 MrBayesPrint ("%s Could not open file \"%s\"\n", spacer, name);
1326 FILE *OpenTextFileW (char *name)
1331 strcpy(fileName, workingDir);
1332 strncat(fileName, name, 199 - strlen(fileName));
1334 if ((fp = fopen (fileName, "w+")) == NULL)
1336 MrBayesPrint ("%s Could not open file \"%s\"\n", spacer, name);
1345 \param vals[0..nRuns][count[]] All records for all runs
1346 \param nRuns Number of runs
1347 \param count[0..nRuns] Number of records in each run
1350 MrBFlt PotentialScaleReduction (MrBFlt **vals, int nRuns, int *count)
1353 MrBFlt aW, aOldW, sW, sWj, aB, aOldB, sB, x, R2, weight;
1355 aB = sB = sW = sWj = 0.0;
1357 for (j=0; j<nRuns; j++)
1365 for (i=1; i<count[j]; i++)
1369 aW += (x - aW) / (MrBFlt) (i + 1);
1370 sWj += (x - aW) * (x - aOldW);
1372 sW += sWj / (MrBFlt)(count[j] - 1);
1375 aB += (x - aB) / (MrBFlt) (j + 1);
1377 sB += (x - aB) * (x - aOldB);
1380 sB = sB / (MrBFlt) (nRuns - 1);
1381 sW = sW / (MrBFlt) (nRuns);
1383 weight = (MrBFlt) nVals / (MrBFlt) nRuns;
1386 R2 = ((weight - 1.0) / weight) + ((MrBFlt)(nRuns + 1) / (MrBFlt) (nRuns)) * (sB / sW);
1395 \param vals[0..nRuns][count[]] All records for all runs
1396 \param nRuns Number of runs
1397 \param count[0..nRuns] Number of records in each run
1398 \param returnESS[0..nRuns] Is an arry in which the routine returns ESS values for each run.
1400 void EstimatedSampleSize (MrBFlt **vals, int nRuns, int *count, MrBFlt *returnESS)
1402 int i, j, lag, maxLag, samples;
1403 MrBFlt *values, mean, del1, del2, varStat=0.0;
1404 MrBFlt gammaStat[2000];
1406 for (i=0; i<nRuns; i++)
1411 for (j=0; j<samples; j++)
1417 maxLag = ((samples - 1) > 2000)?2000:(samples - 1);
1419 for (lag = 0; lag < maxLag; lag++)
1422 for (j = 0; j < samples - lag; j++)
1424 del1 = values[j] - mean;
1425 del2 = values[j + lag] - mean;
1426 gammaStat[lag] += (del1 * del2);
1429 gammaStat[lag] /= ((MrBFlt) (samples - lag));
1433 varStat = gammaStat[0];
1435 else if (lag % 2 == 0)
1437 if (gammaStat[lag - 1] + gammaStat[lag] > 0)
1439 varStat += 2.0 * (gammaStat[lag - 1] + gammaStat[lag]);
1445 returnESS[i] = (gammaStat[0] * samples) / varStat;
1450 /* SafeCalloc: Print error if out of memory */
1451 void *SafeCalloc(size_t n, size_t s) {
1464 MrBayesPrint ("%s Out of memory. Most probable course for the problem is that MrBayes reached\n", spacer);
1465 MrBayesPrint ("%s the limit of allowed memory for a process in your Operating System. Consult\n", spacer);
1466 MrBayesPrint ("%s documentation of your OS how to extend the limit, or use 64 bit version OS \n", spacer);
1467 MrBayesPrint ("%s and compile 64 bit version of MrBayes. \n", spacer);
1468 MrBayesPrint ("%s Segmentation fault may follow. \n", spacer);
1476 int SafeFclose(FILE **fp) {
1478 # if defined MPI_ENABLED
1481 if (fp!=NULL && (*fp)!=NULL)
1484 # if defined MPI_ENABLED
1491 /* SafeFree: Set pointer to freed space to NULL */
1492 void SafeFree (void **ptr)
1500 /* SafeMalloc: Print error if out of memory; clear memory */
1501 void *SafeMalloc (size_t s)
1514 MrBayesPrint ("%s Out of memory. Most probable course for the problem is that MrBayes reached\n", spacer);
1515 MrBayesPrint ("%s the limit of allowed memory for a process in your Operating System. Consult\n", spacer);
1516 MrBayesPrint ("%s documentation of your OS how to extend the limit, or use 64 bit version OS \n", spacer);
1517 MrBayesPrint ("%s and compile 64 bit version of MrBayes. \n", spacer);
1518 MrBayesPrint ("%s Segmentation fault may follow. \n", spacer);
1522 return memset(ptr,0,s);
1526 /* SafeRealloc: Print error if out of memory */
1527 void *SafeRealloc (void *ptr, size_t s)
1541 ptr = realloc (ptr, s);
1545 MrBayesPrint ("%s Out of memory. Most probable course for the problem is that MrBayes reached\n", spacer);
1546 MrBayesPrint ("%s the limit of allowed memory for a process in your Operating System. Consult\n", spacer);
1547 MrBayesPrint ("%s documentation of your OS how to extend the limit, or use 64 bit version OS \n", spacer);
1548 MrBayesPrint ("%s and compile 64 bit version of MrBayes. \n", spacer);
1549 MrBayesPrint ("%s Segmentation fault may follow. \n", spacer);
1557 /* SafeStrcat: Allocate or reallocate target to fit result; assumes ptr is NULL if not allocated */
1558 char *SafeStrcat (char **target, const char *source)
1560 if (*target == NULL)
1561 *target = (char *) SafeCalloc (strlen(source)+1, sizeof(char));
1563 *target = (char *) SafeRealloc ((void *)*target, (strlen(source)+strlen(*target)+1)*sizeof(char));
1566 strcat(*target, source);
1572 /* SafeStrcpy: Allocate or reallocate target to fit result; assumes ptr is NULL if not allocated */
1573 char *SafeStrcpy (char **target, const char *source)
1575 *target = (char *) SafeRealloc ((void *)*target, (strlen(source)+1)*sizeof(char));
1578 strcpy(*target,source);
1584 /* SetBit: Set a particular bit in a series of longs */
1585 void SetBit (int i, BitsLong *bits)
1587 BitsLong x, bitsLongOne=1;
1589 bits += i / nBitsInALong;
1591 x = bitsLongOne << (i % nBitsInALong);
1597 void SortInts (int *item, int *assoc, int count, int descendingOrder)
1599 SortInts2 (item, assoc, 0, count-1, descendingOrder);
1603 void SortInts2 (int *item, int *assoc, int left, int right, int descendingOrder)
1605 register int i, j, x, y;
1607 if (descendingOrder == YES)
1611 x = item[(left+right)/2];
1614 while (item[i] > x && i < right)
1616 while (x > item[j] && j > left)
1627 assoc[i] = assoc[j];
1635 SortInts2 (item, assoc, left, j, descendingOrder);
1637 SortInts2 (item, assoc, i, right, descendingOrder);
1643 x = item[(left+right)/2];
1646 while (item[i] < x && i < right)
1648 while (x < item[j] && j > left)
1659 assoc[i] = assoc[j];
1667 SortInts2 (item, assoc, left, j, descendingOrder);
1669 SortInts2 (item, assoc, i, right, descendingOrder);
1674 /* SortMrBFlt: Sort in increasing order */
1675 void SortMrBFlt (MrBFlt *item, int left, int right)
1682 x = item[(left+right)/2];
1685 while (item[i] < x && i < right)
1687 while (x < item[j] && j > left)
1700 SortMrBFlt (item, left, j);
1702 SortMrBFlt (item, i, right);
1706 /* StrCmpCaseInsensitive: Case insensitive string comparison */
1707 int StrCmpCaseInsensitive (char *s, char *t)
1711 if (strlen(s) < strlen(t))
1712 minLen = (int) strlen(s);
1714 minLen = (int) strlen(t);
1716 for (i=0; i<minLen; i++)
1717 if (tolower(s[i])!= tolower(t[i]))
1720 if (s[i] == '\0' && t[i] == '\0')
1722 else if (tolower(s[i]) > tolower(t[i]))
1729 /* StripComments: Strip possibly nested comments from the string s.
1730 Example: s="text1[text2[text3]]"-> s="text1" */
1731 void StripComments (char *s)
1737 for (t=s; *s != '\0'; s++)
1758 FILE *TestOpenTextFileR (char *name)
1762 strcpy(fileName, workingDir);
1763 strncat(fileName, name, 99 - strlen(fileName));
1765 return fopen (fileName, "r");
1771 | UpdateGrowthFxn: We expect a set of unique indexes from 0 to 5
1772 | indicating a partition of 6 rates into sets. We make sure
1773 | the indices correspond to a restricted growth function here.
1775 -----------------------*/
1776 void UpdateGrowthFxn(int *growthFxn)
1778 int i, j, max, fxn[6];
1790 if (growthFxn[j] == growthFxn[i])
1797 growthFxn[i] = fxn[i];
1801 int UpperTriangIndex(int i, int j, int size)
1804 return (2*size - i - 3) * i / 2 + j - 1;
1806 return (2*size - j - 3) * j / 2 + i - 1;
1810 int WantTo (const char *msg)
1815 MrBayesPrint ("%s %s? (yes/no): ", spacer, msg);
1817 for (i=0; i<10; i++)
1819 if (fgets (s, 98, stdin) == NULL)
1821 MrBayesPrint ("%s Failed to retrieve answer; will take that as a no\n", spacer);
1825 /* Strip away the newline */
1826 s[strlen(s)-1] = '\0';
1829 if (IsConsistentWith (s, "yes") == YES)
1831 else if (IsConsistentWith (s, "no") == YES)
1834 MrBayesPrint ("%s Enter yes or no: ", spacer);
1837 MrBayesPrint ("%s MrBayes does not understand; will take that as a no\n", spacer);
1843 /* the following are moved from tree.c */
1844 /* AddToTreeList: Add tree at end of tree list */
1845 int AddToTreeList (TreeList *treeList, Tree *tree)
1847 TreeListElement *listElement = (TreeListElement *) SafeCalloc (1, sizeof(TreeListElement));
1851 listElement->order = (int *) SafeCalloc (tree->nIntNodes-1, sizeof(int));
1852 if (!listElement->order)
1854 listElement->next = NULL;
1856 if (treeList->last == NULL)
1857 treeList->last = treeList->first = listElement;
1860 treeList->last->next = listElement;
1861 treeList->last = listElement;
1865 StoreRTopology (tree, listElement->order);
1867 StoreUTopology (tree, listElement->order);
1873 /* AllocatePolyTree: Allocate memory space for a polytomous tree */
1874 PolyTree *AllocatePolyTree (int numTaxa)
1879 pt = (PolyTree *) SafeCalloc (1, sizeof (PolyTree));
1883 pt->memNodes = 2*numTaxa;
1884 pt->nodes = (PolyNode *) SafeCalloc (2*numTaxa, sizeof(PolyNode));
1885 pt->allDownPass = (PolyNode **) SafeCalloc (3*numTaxa, sizeof (PolyNode *));
1886 pt->intDownPass = pt->allDownPass + 2*numTaxa;
1887 if (pt->nodes == NULL || pt->allDownPass == NULL)
1890 free (pt->allDownPass);
1895 /* initialize nodes and set index and memoryIndex */
1896 for (i=0; i<2*numTaxa; i++)
1898 ResetPolyNode(&pt->nodes[i]);
1899 pt->nodes[i].memoryIndex = i;
1900 pt->nodes[i].index = i;
1903 /* initialize tree properties */
1904 pt->nNodes = pt->nIntNodes = 0;
1909 pt->isCalibrated = NO;
1911 pt->clockRate = 0.0;
1912 strcpy(pt->name,"");
1914 /* initialize bitsets */
1917 /* initialize relaxed clock parameters */
1920 pt->position = NULL;
1921 pt->rateMult = NULL;
1922 pt->eSetName = NULL;
1925 pt->effectiveBrLen = NULL;
1926 pt->bSetName = NULL;
1928 /* initialize population size set parameters */
1929 pt->popSizeSet = NO;
1931 pt->popSizeSetName = NULL;
1937 /* AllocatePolyTreeRelClockParams: Allocate space for relaxed clock parameters */
1938 int AllocatePolyTreeRelClockParams (PolyTree *pt, int nBSets, int nESets)
1942 /* free previous clock params if any */
1943 FreePolyTreeRelClockParams (pt);
1945 /* set number of sets */
1946 pt->nBSets = nBSets;
1947 pt->nESets = nESets;
1949 /* we do not allocate space for the actual names here; these will be NULL pointers */
1951 /* take care of branch params */
1954 pt->bSetName = (char **) SafeCalloc (pt->nBSets, sizeof (char *));
1955 pt->effectiveBrLen = (MrBFlt **) SafeCalloc (pt->nBSets, sizeof (MrBFlt *));
1956 for (i=0; i<pt->nBSets; i++)
1957 pt->effectiveBrLen[i] = (MrBFlt *) SafeCalloc (pt->memNodes, sizeof(MrBFlt));
1960 /* take care of breakpoint params */
1963 pt->eSetName = (char **) SafeCalloc (pt->nESets, sizeof(char *));
1964 pt->nEvents = (int **) SafeCalloc (pt->nESets, sizeof(int *));
1965 pt->position = (MrBFlt ***) SafeCalloc (pt->nESets, sizeof(MrBFlt **));
1966 pt->rateMult = (MrBFlt ***) SafeCalloc (pt->nESets, sizeof(MrBFlt **));
1967 for (i=0; i<pt->nESets; i++)
1969 pt->nEvents[i] = (int *) SafeCalloc (pt->memNodes, sizeof(int));
1970 pt->position[i] = (MrBFlt **) SafeCalloc (pt->memNodes, sizeof(MrBFlt *));
1971 pt->rateMult[i] = (MrBFlt **) SafeCalloc (pt->memNodes, sizeof(MrBFlt *));
1979 /* AllocatePolyTreePartitions: Allocate space for and set partitions for polytomous tree */
1980 int AllocatePolyTreePartitions (PolyTree *pt)
1982 int i, nLongsNeeded, numTaxa;
1984 /* get some handy numbers */
1985 numTaxa = pt->memNodes/2;
1986 nLongsNeeded = (numTaxa -1) / nBitsInALong + 1;
1988 /* allocate space */
1989 pt->bitsets = (BitsLong *) SafeRealloc ((void *)pt->bitsets, pt->memNodes*nLongsNeeded*sizeof(BitsLong));
1990 if (pt->bitsets == NULL)
1992 for (i=0; i<pt->memNodes*nLongsNeeded; i++)
1995 /* set node partition pointers */
1996 for (i=0; i<pt->memNodes; i++)
1997 pt->nodes[i].partition = pt->bitsets + i*nLongsNeeded;
1999 /* clear and set partitions; if the tree is empty, nothing is set */
2000 ResetPolyTreePartitions(pt);
2006 /* AllocateTree: Allocate memory space for a tree (unrooted or rooted) */
2007 Tree *AllocateTree (int numTaxa)
2012 t = (Tree *) SafeCalloc (1, sizeof (Tree));
2016 /* initialize basic tree properties */
2017 t->memNodes = 2*numTaxa;
2018 strcpy (t->name, "");
2023 t->checkConstraints = NO;
2024 t->nConstraints = 0;
2026 t->isCalibrated = NO;
2027 t->nNodes = t->nIntNodes = 0;
2031 /* initialize pointers */
2034 t->constraints = NULL;
2036 /* allocate and initialize nodes and node arrays (enough for both rooted and unrooted trees) */
2039 if ((t->nodes = (TreeNode *) SafeCalloc (2*numTaxa, sizeof (TreeNode))) == NULL)
2044 if ((t->allDownPass = (TreeNode **) SafeCalloc (3*numTaxa, sizeof (TreeNode *))) == NULL)
2050 t->intDownPass = t->allDownPass + t->memNodes;
2052 /* initialize nodes and set index and memoryIndex */
2053 for (i=0; i<t->memNodes; i++)
2055 ResetTreeNode(&t->nodes[i]);
2056 t->nodes[i].memoryIndex = i;
2057 t->nodes[i].index = i;
2064 /* AllocateFixedTree: Allocate memory space for a fixed unrooted or rooted tree */
2065 Tree *AllocateFixedTree (int numTaxa, int isRooted)
2070 t = (Tree *) SafeCalloc (1, sizeof (Tree));
2074 /* initialize basic tree properties */
2075 if (isRooted == YES)
2076 t->memNodes = 2*numTaxa;
2078 t->memNodes = 2*numTaxa - 2;
2079 strcpy (t->name, "");
2081 t->isRooted = isRooted;
2084 t->checkConstraints = NO;
2085 t->nConstraints = 0;
2087 t->isCalibrated = NO;
2088 t->nNodes = t->nIntNodes = 0;
2092 /* initialize pointers */
2095 t->constraints = NULL;
2097 /* allocate and initialize nodes and node arrays (enough for both rooted and unrooted trees) */
2100 t->nNodes = 2*numTaxa;
2101 t->nIntNodes = numTaxa - 1;
2105 t->nNodes = 2*numTaxa - 2;
2106 t->nIntNodes = numTaxa - 2;
2108 if ((t->nodes = (TreeNode *) SafeCalloc (t->nNodes, sizeof (TreeNode))) == NULL)
2113 if ((t->allDownPass = (TreeNode **) SafeCalloc (t->nNodes + t->nIntNodes, sizeof (TreeNode *))) == NULL)
2119 t->intDownPass = t->allDownPass + t->nNodes;
2121 /* initialize nodes and set index and memoryIndex */
2122 for (i=0; i<t->memNodes; i++)
2124 ResetTreeNode(&t->nodes[i]);
2125 t->nodes[i].memoryIndex = i;
2126 t->nodes[i].index = i;
2133 /* AllocateTreePartitions: Allocate space for and set partitions for tree */
2134 int AllocateTreePartitions (Tree *t)
2136 int i, nLongsNeeded, numTaxa;
2139 /* get some handy numbers */
2140 if (t->isRooted == YES)
2141 numTaxa = t->nNodes - t->nIntNodes - 1;
2143 numTaxa = t->nNodes - t->nIntNodes;
2144 nLongsNeeded = (numTaxa - 1) / nBitsInALong + 1;
2146 /* reallocate space */
2147 t->bitsets = (BitsLong *) SafeRealloc ((void *)(t->bitsets), (size_t)(t->nNodes) * (size_t)nLongsNeeded * sizeof(BitsLong));
2151 /* clear bit fields */
2152 for (i=0; i<t->nNodes*nLongsNeeded; i++)
2155 /* set node pointers to bit fields */
2156 for (i=0; i<t->nNodes; i++)
2158 p = t->allDownPass[i];
2159 p->partition = t->bitsets + i*nLongsNeeded;
2162 /* set partition specifiers for terminals */
2163 ResetTreePartitions(t);
2169 int AreTopologiesSame (Tree *t1, Tree *t2)
2171 int i, j, k, nLongsNeeded, nTaxa;
2175 if (t1->nNodes != t2->nNodes)
2177 if (t1->nIntNodes != t2->nIntNodes)
2180 if (t1->isRooted == YES)
2181 nTaxa = t1->nNodes - t1->nIntNodes - 1;
2183 nTaxa = t1->nNodes - t1->nIntNodes;
2185 /* allocate space for mask */
2186 nLongsNeeded = (nTaxa - 1) / nBitsInALong + 1;
2187 mask = (BitsLong *) SafeCalloc (nLongsNeeded, sizeof(BitsLong));
2190 for (i=0; i<nTaxa; i++)
2193 /* allocate and set partition pointers */
2194 AllocateTreePartitions (t1);
2195 AllocateTreePartitions (t2);
2197 /* check for congruence */
2198 for (i=0; i<t1->nIntNodes; i++)
2200 p = t1->intDownPass[i];
2201 if (t1->isRooted == NO && IsBitSet(t2->root->index,p->partition))
2202 FlipBits(p->partition,nLongsNeeded, mask);
2203 for (j=0; j<t2->nIntNodes; j++)
2205 q = t2->intDownPass[j];
2206 for (k=0; k<nLongsNeeded; k++)
2208 if (p->partition[k] != q->partition[k])
2211 if (k == nLongsNeeded)
2214 if (j == t2->nIntNodes)
2216 FreeTreePartitions (t1);
2217 FreeTreePartitions (t2);
2223 FreeTreePartitions (t1);
2224 FreeTreePartitions (t2);
2230 int AreTreesSame (Tree *t1, Tree *t2)
2232 int i, j, k, nLongsNeeded, nTaxa;
2236 extern void ShowNodes(TreeNode*, int, int);
2238 if (t1->nNodes != t2->nNodes)
2240 if (t1->nIntNodes != t2->nIntNodes)
2243 if (t1->isRooted == YES)
2244 nTaxa = t1->nNodes - t1->nIntNodes - 1;
2246 nTaxa = t1->nNodes - t1->nIntNodes;
2248 /* allocate space for mask */
2249 nLongsNeeded = (nTaxa - 1) / nBitsInALong + 1;
2250 mask = (BitsLong *) SafeCalloc (nLongsNeeded, sizeof(BitsLong));
2253 for (i=0; i<nTaxa; i++)
2256 /* allocate and set partition pointers */
2257 AllocateTreePartitions (t1);
2258 AllocateTreePartitions (t2);
2260 /* check for congruence */
2261 for (i=0; i<t1->nNodes; i++)
2263 p = t1->allDownPass[i];
2264 if (p->anc == NULL && t1->isRooted == YES)
2266 if (t1->isRooted == NO && IsBitSet(t2->root->index,p->partition))
2267 FlipBits(p->partition,nLongsNeeded, mask);
2268 for (j=0; j<t2->nNodes; j++)
2270 q = t2->allDownPass[j];
2271 for (k=0; k<nLongsNeeded; k++)
2273 if (p->partition[k] != q->partition[k])
2276 if (k == nLongsNeeded && AreDoublesEqual (p->length, q->length, 0.000001) == YES)
2278 else if (k == nLongsNeeded)
2280 FreeTreePartitions (t1);
2281 FreeTreePartitions (t2);
2286 if (j == t2->nNodes)
2288 FreeTreePartitions (t1);
2289 FreeTreePartitions (t2);
2295 FreeTreePartitions (t1);
2296 FreeTreePartitions (t2);
2302 /*----------------------------------------------------------------
2304 | BuildConstraintTree: Build constraint tree. The tree t is
2305 | needed only to hold information about constraints and
2308 ----------------------------------------------------------------*/
2309 int BuildConstraintTree (Tree *t, PolyTree *pt, char **localTaxonNames)
2311 int i, j, k, constraintId, nLongsNeeded, nextNode;
2312 BitsLong *constraintPartition, *mask;
2313 PolyNode *pp, *qq, *rr, *ss, *tt;
2315 pt->isRooted = t->isRooted;
2317 nLongsNeeded = (numLocalTaxa - 1) / nBitsInALong + 1;
2318 constraintPartition = (BitsLong *) SafeCalloc (2*nLongsNeeded, sizeof(BitsLong));
2319 if (!constraintPartition)
2321 MrBayesPrint ("%s Problems allocating constraintPartition in BuildConstraintTree", spacer);
2324 mask = constraintPartition + nLongsNeeded;
2326 /* calculate mask (needed to take care of unused bits when flipping partitions) */
2327 for (i=0; i<numLocalTaxa; i++)
2330 /* reset all nodes */
2331 for (i=0; i<2*numLocalTaxa; i++)
2335 pp->calibration = NULL;
2343 pt->root = &pt->nodes[numLocalTaxa];
2344 for (i=0; i<numLocalTaxa; i++)
2349 if (i == numLocalTaxa - 1)
2352 pp->sib = &pt->nodes[i+1];
2356 pp->left = &pt->nodes[0];
2357 pp->anc = pp->sib = NULL;
2358 pt->nNodes = numLocalTaxa + 1;
2361 /* make sure the outgroup is the right-most node */
2362 pt->nodes[localOutGroup].index = numLocalTaxa - 1;
2363 pt->nodes[numLocalTaxa - 1].index = localOutGroup;
2365 /* allocate and set partition specifiers in bush */
2366 GetPolyDownPass(pt);
2367 AllocatePolyTreePartitions(pt);
2369 /* set terminal taxon labels */
2370 for (i=0; i<pt->nNodes; i++)
2372 pp = pt->allDownPass[i];
2373 if (pp->index < numLocalTaxa)
2374 strcpy (pp->label, localTaxonNames[pp->index]);
2377 /* resolve the bush according to constraints */
2378 /* for now, satisfy all constraints */
2379 /* for now, bail out if constraints are not compatible */
2380 /* Eventually, we might want to be build a parsimony (WAB) or compatibility (WIB) matrix and
2381 draw a starting tree from the universe according to the score of the tree. A simple way of accomplishing
2382 approximately this is to use sequential addition, with probabilities in each step determined
2383 by the parsimony or compatibility score of the different possibilities. */
2384 nextNode = numLocalTaxa + 1;
2386 for (constraintId=0; constraintId<numDefinedConstraints; constraintId++)
2388 if (t->constraints[constraintId] == NO || definedConstraintsType[constraintId] != HARD)
2391 /* initialize bits in partition to add; get rid of deleted taxa in the process */
2392 ClearBits(constraintPartition, nLongsNeeded);
2393 for (i=j=0; i<numTaxa; i++)
2395 if (taxaInfo[i].isDeleted == YES)
2397 if (IsBitSet(i, definedConstraint[constraintId]) == YES)
2398 SetBit(j, constraintPartition);
2401 assert (j == numLocalTaxa);
2403 /* make sure outgroup is outside constrained partition if the tree is unrooted */
2404 if (t->isRooted == NO && IsBitSet(localOutGroup, constraintPartition))
2405 FlipBits(constraintPartition, nLongsNeeded, mask);
2407 /* check that partition should be included */
2408 k = NumBits(constraintPartition, nLongsNeeded);
2411 MrBayesPrint ("%s WARNING: Constraint '%s' refers only to deleted taxa\n", spacer, constraintNames[constraintId]);
2412 MrBayesPrint ("%s and will be disregarded\n", spacer);
2413 t->constraints[constraintId] = NO;
2418 MrBayesPrint ("%s WARNING: Constraint '%s' refers to a single tip and\n", spacer, constraintNames[constraintId]);
2419 MrBayesPrint ("%s will be disregarded\n", spacer);
2420 t->constraints[constraintId] = NO;
2424 /* check if root in rooted tree (we allow this to enable inference of ancestral states) */
2425 if (k == numLocalTaxa && t->isRooted == YES)
2427 if (pt->root->isLocked == YES) {
2428 MrBayesPrint ("%s WARNING: Constraint '%s' is a duplicate of another constraint\n", spacer, constraintNames[constraintId]);
2429 MrBayesPrint ("%s and will be ignored\n", spacer);
2430 t->constraints[constraintId] = NO;
2433 pt->root->isLocked = YES;
2434 pt->root->lockID = constraintId;
2439 /* check if interior root in unrooted tree (we allow this to enable inference of ancestral states) */
2440 if ((k == numLocalTaxa - 1 || k == numLocalTaxa) && t->isRooted == NO)
2442 if (pt->root->isLocked == YES) {
2443 MrBayesPrint ("%s WARNING: Constraint '%s' is a duplicate of another constraint\n", spacer, constraintNames[constraintId]);
2444 MrBayesPrint ("%s and will be ignored\n", spacer);
2445 t->constraints[constraintId] = NO;
2448 pt->root->isLocked = YES;
2449 pt->root->lockID = constraintId;
2454 /* find first included terminal */
2455 k = FirstTaxonInPartition (constraintPartition, nLongsNeeded);
2456 for (i=0; pt->nodes[i].index != k; i++)
2460 /* go down until node is not included in constraint */
2464 } while (IsPartNested(pp->partition, constraintPartition, nLongsNeeded));
2466 /* check that the node has not yet been included */
2467 for (i=0; i<nLongsNeeded; i++)
2469 if (qq->partition[i] != constraintPartition[i])
2472 if (i==nLongsNeeded)
2474 MrBayesPrint ("%s WARNING: Constraint '%s' is a duplicate of another constraint\n", spacer, constraintNames[constraintId]);
2475 MrBayesPrint ("%s and will be ignored\n", spacer);
2476 t->constraints[constraintId] = NO;
2480 /* create a new node */
2481 tt = &pt->nodes[nextNode++];
2484 tt->lockID = constraintId;
2486 for (i=0; i<nLongsNeeded; i++)
2487 tt->partition[i] = constraintPartition[i];
2491 /* sort descendant nodes in two connected groups: included and excluded */
2492 /* if there is a descendant that overlaps (incompatible) then return error */
2496 if (IsPartNested(qq->partition, constraintPartition, nLongsNeeded))
2505 else if (IsPartCompatible(qq->partition, constraintPartition, nLongsNeeded))
2515 free (constraintPartition);
2519 } while (qq != NULL);
2521 rr->sib = ss->sib = NULL;
2524 /* relabel interior nodes */
2525 GetPolyDownPass(pt);
2526 for (i=0; i<pt->nIntNodes; i++)
2527 pt->intDownPass[i]->index = i + numLocalTaxa;
2530 free (constraintPartition);
2531 FreePolyTreePartitions(pt);
2536 /*----------------------------------------------
2538 | BuildRandomRTopology: Builds a random rooted
2539 | topology. Will set indices in t->nodes
2540 | such that they are from 0 to n-1 for the n tips
2541 | and from n to 2n-2 for the n-1 interior
2542 | nodes. Last is root. Does not touch labels
2545 ----------------------------------------------*/
2546 int BuildRandomRTopology (Tree *t, RandLong *seed)
2549 TreeNode *p, *q, *r;
2551 nTips = t->nNodes - t->nIntNodes - 1;
2553 for (i=0; i<t->nNodes; i++)
2557 p->left = p->right = p->anc = NULL;
2560 /* connect the first two tip nodes */
2563 p = &t->nodes[nTips];
2564 q->anc = r->anc = p;
2567 q = &t->nodes[2*nTips-1];
2571 for (i=2; i<nTips; i++)
2574 r = &t->nodes[i-2+nTips+1];
2577 j = (int) (RandomNumber(seed) * (2 * i - 1));
2581 p = &t->nodes[j-i + nTips];
2586 if (p->anc->left == p)
2594 /* set root and get downpass */
2595 t->root = &t->nodes[2*nTips-1];
2598 /* relabel interior nodes */
2599 for (i=0; i<t->nIntNodes; i++)
2600 t->intDownPass[i]->index = i+nTips;
2606 /*----------------------------------------------
2608 | BuildRandomUTopology: Builds a random unrooted
2609 | topology. Assumes that indices are set
2610 | in t->nodes from 0 to n-1 for the n tips
2611 | and from n to 2n-3 for the n-2 interior
2612 | nodes. Move the calculation root after
2613 | this routine to get the right root.
2615 ----------------------------------------------*/
2616 int BuildRandomUTopology (Tree *t, RandLong *seed)
2619 TreeNode *p, *q, *r;
2621 nTips = t->nNodes - t->nIntNodes;
2623 for (i=0; i<t->nNodes; i++)
2627 p->left = p->right = p->anc = NULL;
2630 /* connect the first three nodes, assuming 0 is calc root */
2633 p = &t->nodes[nTips];
2634 q->anc = r->anc = p;
2641 for (i=3; i<nTips; i++)
2644 r = &t->nodes[i - 3 + nTips + 1];
2647 j = (int) (RandomNumber(seed) * (2 * i - 3));
2651 p = &t->nodes[j+1-i + nTips];
2654 if (p->anc->left == p)
2661 t->root = &t->nodes[0];
2666 /* relabel interior nodes */
2667 for (i=0; i<t->nIntNodes; i++)
2668 t->intDownPass[i]->index = i+nTips;
2674 /*----------------------------------------------------------------
2676 | CheckConstraints: Check that tree complies with constraints
2678 ----------------------------------------------------------------*/
2679 int CheckConstraints (Tree *t)
2681 int a, i, j, k, nLongsNeeded;
2682 BitsLong *constraintPartition, *mask;
2685 if (t->checkConstraints == NO)
2688 /* allocate space */
2689 nLongsNeeded = (numLocalTaxa - 1) / nBitsInALong + 1;
2690 constraintPartition = (BitsLong *) SafeCalloc (2*nLongsNeeded, sizeof(BitsLong));
2691 if (!constraintPartition)
2693 MrBayesPrint ("%s Problems allocating constraintPartition in CheckConstraints", spacer);
2696 mask = constraintPartition + nLongsNeeded;
2698 /* set mask (needed to reset unused bits when flipping partitions) */
2699 for (i=0; i<numLocalTaxa; i++)
2702 if (AllocateTreePartitions(t) == ERROR)
2704 MrBayesPrint ("%s Problems allocating tree partitions in CheckConstraints", spacer);
2708 for (a=0; a<numDefinedConstraints; a++)
2710 if (t->constraints[a] == NO || definedConstraintsType[a] != HARD)
2713 /* set bits in partition to check */
2714 ClearBits(constraintPartition, nLongsNeeded);
2715 for (j=k=0; j<numTaxa; j++)
2717 if (taxaInfo[j].isDeleted == YES)
2719 if (IsBitSet(j, definedConstraint[a]) == YES)
2720 SetBit(k, constraintPartition);
2724 /* make sure outgroup is outside constrained partition if unrooted tree */
2725 if (t->isRooted == NO && IsBitSet(localOutGroup, constraintPartition))
2726 FlipBits(constraintPartition, nLongsNeeded, mask);
2728 /* find the locked node */
2729 for (i=j=0; i<t->nNodes; i++)
2731 if (t->allDownPass[i]->isLocked == YES && t->allDownPass[i]->lockID == a)
2733 p = t->allDownPass[i];
2740 MrBayesPrint ("%s Tree has %d locks with id %d identifying constraint '%s'\n", spacer, j, a, constraintNames[a]);
2741 free (constraintPartition);
2742 FreeTreePartitions(t);
2746 /* check that locked node is correct */
2747 for (i=0; i<nLongsNeeded; i++)
2749 if (p->partition[i] != constraintPartition[i])
2751 MrBayesPrint ("%s Lock %d is set for the wrong node [this is a bug]\n", spacer, a);
2752 free (constraintPartition);
2753 FreeTreePartitions(t);
2759 FreeTreePartitions (t);
2760 free (constraintPartition);
2765 /*----------------------------------------------------------------
2767 | CheckSetConstraints: Check and set tree constraints
2769 ----------------------------------------------------------------*/
2770 int CheckSetConstraints (Tree *t)
2772 int a, i, j, k, nLongsNeeded, foundIt, numLocks;
2773 BitsLong *constraintPartition, *mask;
2776 if (t->checkConstraints == NO)
2779 /* reset all existing locks, if any */
2780 for (i=0; i<t->nNodes; i++)
2782 p = t->allDownPass[i];
2785 if (p->left != NULL)
2787 p->calibration = NULL;
2793 /* allocate space */
2794 if (AllocateTreePartitions (t) == ERROR)
2796 MrBayesPrint ("%s Problems allocating tree bitsets", spacer);
2800 nLongsNeeded = ((numLocalTaxa - 1) / nBitsInALong) + 1;
2801 constraintPartition = (BitsLong *) SafeCalloc (2*nLongsNeeded, sizeof(BitsLong));
2802 if (!constraintPartition)
2804 MrBayesPrint ("%s Problems allocating constraintPartition", spacer);
2805 FreeTreePartitions(t);
2808 mask = constraintPartition + nLongsNeeded;
2810 /* set mask (needed to take care of unused bits when flipping partitions) */
2811 for (i=0; i<numLocalTaxa; i++)
2815 for (a=0; a<numDefinedConstraints; a++)
2817 if (modelParams[t->relParts[0]].activeConstraints[a] == NO || definedConstraintsType[a] != HARD)
2820 /* set bits in partition to add */
2821 ClearBits(constraintPartition, nLongsNeeded);
2822 for (i=j=0; i<numTaxa; i++)
2824 if (taxaInfo[i].isDeleted == YES)
2826 if (IsBitSet(i, definedConstraint[a]) == YES)
2827 SetBit(j, constraintPartition);
2831 /* make sure outgroup is outside constrained partition (marked 0) */
2832 if (t->isRooted == NO && IsBitSet(localOutGroup, constraintPartition) == YES)
2833 FlipBits(constraintPartition, nLongsNeeded, mask);
2835 /* skip partition if uninformative */
2836 k = NumBits(constraintPartition, nLongsNeeded);
2837 if (k == 0 || k == 1)
2840 /* find the node that should be locked */
2842 for (i=0; i<t->nIntNodes; i++)
2844 p = t->intDownPass[i];
2845 for (j=0; j<nLongsNeeded; j++)
2847 if (p->partition[j] != constraintPartition[j])
2851 if (j == nLongsNeeded)
2856 if (nodeCalibration[a].prior != unconstrained)
2859 p->calibration = &nodeCalibration[a];
2868 MrBayesPrint ("%s Tree breaks constraint '%s'\n", spacer, constraintNames[a]);
2869 FreeTreePartitions (t);
2870 free (constraintPartition);
2875 if (numLocks != t->nLocks)
2877 MrBayesPrint ("%s Inconsistent lock settings. This is a bug, please report it.\n", spacer);
2878 FreeTreePartitions (t);
2879 free (constraintPartition);
2884 FreeTreePartitions(t);
2885 free (constraintPartition);
2890 /*-----------------------------------------------------------------------
2892 | ColorClusters: Recursive function to color the clusters in a tree by
2893 | assigning numbers to them in their variable x
2895 ------------------------------------------------------------------------*/
2896 void ColorClusters (TreeNode *p, int *index)
2900 if (p->isLocked == YES || p->anc == NULL || p->anc->anc == NULL)
2901 p->x = (++(*index));
2904 ColorClusters(p->left, index);
2905 ColorClusters(p->right, index);
2910 /* CopyPolyNodes: Copies everything except pointers and memoryIndex */
2911 void CopyPolyNodes (PolyNode *p, PolyNode *q, int nLongsNeeded)
2913 p->index = q->index;
2915 p->length = q->length;
2918 p->isDated = q->isDated;
2919 p->calibration = q->calibration;
2921 p->isLocked = q->isLocked;
2922 p->lockID = q->lockID;
2923 strcpy (p->label, q->label);
2924 if (nLongsNeeded!=0)
2926 assert (p->partition);
2927 assert (q->partition);
2928 memcpy (p->partition,q->partition, nLongsNeeded*sizeof(BitsLong));
2930 p->support = q->support;
2935 void CopySubtreeToTree (Tree *subtree, Tree *t)
2938 TreeNode *p, *q=NULL, *r;
2940 for (i=/*j=*/0; i<subtree->nNodes - 1; i++)
2942 p = subtree->allDownPass[i];
2944 for (k=0; k<t->nNodes; k++)
2946 q = t->allDownPass[k];
2947 if (q->index == p->index)
2950 q->length = p->length;
2952 if (p->left != NULL && p->right != NULL)
2954 for (k=0; k<t->nNodes; k++)
2956 r = t->allDownPass[k];
2957 if (r->index == p->left->index)
2962 else if (r->index == p->right->index)
2973 for (k=0; k<t->nNodes; k++)
2975 q = t->allDownPass[k];
2976 if (q->index == p->index)
2980 if (q->left->marked == YES)
2982 for (k=0; k<t->nIntNodes; k++)
2984 r = t->intDownPass[k];
2985 if (r->index == p->left->index)
2992 else if (q->right->marked == YES)
2994 for (k=0; k<t->nIntNodes; k++)
2996 r = t->intDownPass[k];
2997 if (r->index == p->left->index)
3007 /*-----------------------------------------------------------------
3009 | CopyToPolyTreeFromPolyTree: copies second tree to first tree
3011 -----------------------------------------------------------------*/
3012 int CopyToPolyTreeFromPolyTree (PolyTree *to, PolyTree *from)
3014 int i, j, k, nLongsNeeded;
3017 /* check we have enough memory */
3018 assert (to->memNodes >= from->nNodes);
3019 if (from->bitsets==NULL || to->bitsets==NULL)
3025 assert (to->memNodes >= from->memNodes);/*Otherwise partition length woould not be long enough for nodes in "to" */
3026 nLongsNeeded = (from->memNodes/2 - 1) / nBitsInALong + 1;
3030 for (i=0; i<from->nNodes; i++)
3033 p = from->nodes + i;
3037 q->anc = to->nodes + p->anc->memoryIndex;
3044 if (p->left != NULL)
3045 q->left = to->nodes + p->left->memoryIndex;
3050 q->sib = to->nodes + p->sib->memoryIndex;
3054 /* Copy everything else except memoryIndex */
3055 CopyPolyNodes (q, p, nLongsNeeded);
3058 /* fill node arrays */
3059 /* copy tree properties */
3060 to->nNodes = from->nNodes;
3061 to->nIntNodes = from->nIntNodes;
3062 to->isRooted = from->isRooted;
3063 to->isClock = from->isClock;
3064 to->isRelaxed = from->isRelaxed;
3065 to->clockRate = from->clockRate;
3066 strcpy (to->name, from->name);
3068 GetPolyDownPass (to);
3070 /* copy partitions */
3074 AllocatePolyTreePartitions(to);
3076 ResetPolyTreePartitions(to);
3079 /* copy relaxed clock parameters */
3080 FreePolyTreeRelClockParams (to);
3082 if (from->nBSets + from->nESets > 0)
3083 AllocatePolyTreeRelClockParams (to, from->nBSets, from->nESets);
3085 for (i=0; i<to->nBSets; i++)
3087 to->bSetName[i] = (char *) SafeCalloc (strlen(from->bSetName[i])+2, sizeof(char));
3088 strcpy (to->bSetName[i], from->bSetName[i]);
3089 for (j=0; j<from->nNodes; j++)
3090 to->effectiveBrLen[i][j] = from->effectiveBrLen[i][j];
3093 for (i=0; i<to->nESets; i++)
3095 to->eSetName[i] = (char *) SafeCalloc (strlen(from->eSetName[i])+2, sizeof(char));
3096 strcpy (to->eSetName[i], from->eSetName[i]);
3097 for (j=0; j<from->nNodes; j++)
3099 to->nEvents[i][j] = from->nEvents[i][j];
3100 if (to->nEvents[i][j] > 0)
3102 to->position[i][j] = (MrBFlt *) SafeCalloc (to->nEvents[i][j], sizeof (MrBFlt));
3103 to->rateMult[i][j] = (MrBFlt *) SafeCalloc (to->nEvents[i][j], sizeof (MrBFlt));
3104 for (k=0; k<to->nEvents[i][j]; k++)
3106 to->position[i][j][k] = from->position[i][j][k];
3107 to->rateMult[i][j][k] = from->rateMult[i][j][k];
3113 /* copy population size parameters */
3114 FreePolyTreePopSizeParams(to);
3115 to->popSizeSet = from->popSizeSet;
3116 if (to->popSizeSet == YES)
3118 to->popSize = (MrBFlt *) SafeCalloc (to->nNodes, sizeof(MrBFlt));
3119 for (i=0; i<to->nNodes; i++)
3120 to->popSize[i] = from->popSize[i];
3121 to->popSizeSetName = (char *) SafeCalloc (strlen(from->popSizeSetName) + 1, sizeof(char));
3122 strcpy (to->popSizeSetName, from->popSizeSetName);
3129 /*-----------------------------------------------------------------
3131 | CopyToSpeciesTreeFromPolyTree: copies second tree (polytomous) to
3132 | first tree, which is a species tree. The species tree needs to
3133 | be allocated enough space first to hold the resulting tree.
3135 -----------------------------------------------------------------*/
3136 int CopyToSpeciesTreeFromPolyTree (Tree *to, PolyTree *from)
3141 # if defined (DEBUG_SPECIESTREE)
3145 /* make sure assumptions are correct */
3146 assert (from->isRooted == YES);
3147 assert (from->isClock == YES);
3148 assert (from->nNodes - from->nIntNodes == numSpecies);
3149 assert (to->memNodes == 2*numSpecies);
3150 assert (to->nIntNodes == from->nIntNodes);
3151 assert (to->nNodes == from->nNodes + 1);
3153 /* make sure indices are set correctly for from nodes */
3154 # if defined (DEBUG_SPECIESTREE)
3155 for (i=0; i<from->nNodes; i++)
3157 for (j=0; j<from->nNodes; j++)
3159 p = from->allDownPass[j];
3163 assert (j != from->nNodes);
3164 assert (!(p->left == NULL && p->index >= numSpecies));
3169 for (i=0; i<from->nNodes; i++)
3172 p = from->allDownPass[i];
3173 q = to->nodes + p->index;
3176 q->anc = to->nodes + p->anc->index;
3180 if (p->left != NULL)
3181 q->left = to->nodes + p->left->index;
3185 if (p->left != NULL)
3186 q->right = to->nodes + p->left->sib->index;
3190 q->nodeDepth = p->depth;
3192 q->length = p->length;
3193 q->index = p->index;
3194 if (q->index < numSpecies)
3195 q->label = speciesNameSets[speciespartitionNum].names[q->index];
3202 q = to->nodes + p->index;
3203 q1 = to->nodes + from->nNodes; /* get the 'extra' root node that polytomous trees do not use */
3205 q1->index = from->nNodes;
3207 q1->right = q1->anc = NULL;
3211 q1->calibration = NULL;
3218 /* a user tree might not come with node depths set */
3219 if (to->root->left->nodeDepth == 0.0)
3222 /* set partitions */
3224 ResetTreePartitions(to);
3230 /*-----------------------------------------------------------------
3232 | CopyToTreeFromPolyTree: copies second tree (polytomous) to first
3233 | tree (used to initialize constrained starting trees, e.g.).
3234 | An unrooted source tree will be rooted on outgroup
3235 | An unrooted source tree that needs to be copied to
3236 | a rooted target tree will be randomly rooted on a node below
3237 | all defined constraints. The to tree needs to be allocated
3238 | enough space first to hold the resulting tree.
3240 -----------------------------------------------------------------*/
3241 int CopyToTreeFromPolyTree (Tree *to, PolyTree *from)
3247 /* refuse to arbitrarily root an input tree */
3248 assert (!(from->isRooted == NO && to->isRooted == YES));
3249 if ((from->isRooted == NO) && (to->isRooted == YES))
3251 MrBayesPrint ("%s Failed to copy trees due to difference in rootedness of source and destination. \n", spacer);
3255 /* make sure assumptions are in order */
3256 assert (to->memNodes >= from->nNodes + (to->isRooted == NO ? 0 : 1));
3257 assert (localOutGroup >= 0 && localOutGroup < numLocalTaxa);
3258 assert (numLocalTaxa == from->nNodes - from->nIntNodes);
3259 assert (!(from->isRooted == YES && from->nNodes != 2*from->nIntNodes + 1));
3260 assert (!(from->isRooted == NO && from->nNodes != 2*from->nIntNodes + 2));
3262 /* make sure indices are set correctly for from nodes */
3263 for (i=0; i<from->nNodes; i++)
3265 for (j=0; j<from->nNodes; j++)
3267 p = from->allDownPass[j];
3271 assert (j != from->nNodes);
3272 assert (!(p->left == NULL && p->index >= numLocalTaxa));
3275 /* deal with root */
3276 if (to->isRooted == NO && from->isRooted == YES)
3279 /* make sure calculation root is set correctly */
3280 if (to->isRooted == NO && MovePolyCalculationRoot (from, localOutGroup) == ERROR)
3284 for (i=0; i<from->nNodes; i++)
3287 p = from->allDownPass[i];
3288 q = to->nodes + p->index;
3291 q->anc = to->nodes + p->anc->index;
3295 if (p->left != NULL)
3296 q->left = to->nodes + p->left->index;
3300 if (p->left != NULL)
3301 q->right = to->nodes + p->left->sib->index;
3305 q->isLocked = p->isLocked;
3306 q->lockID = p->lockID;
3307 q->isDated = p->isDated;
3308 q->calibration = p->calibration;
3310 q->nodeDepth = p->depth;
3311 q->length = p->length;
3312 q->index = p->index;
3313 if (q->index < numLocalTaxa)
3314 q->label = localTaxonNames[q->index];
3320 if (to->isRooted == NO)
3323 q = to->nodes + p->index;
3324 q->anc = to->root = to->nodes + p->left->sib->sib->index;
3325 q->length = to->root->length;
3326 to->root->length = 0.0;
3328 to->root->right = to->root->anc = NULL;
3333 q = to->nodes + p->index;
3334 q1 = to->nodes + from->nNodes; /* get the 'extra' root node that polytomous trees do not use */
3336 q1->index = from->nNodes;
3338 q1->right = q1->anc = NULL;
3342 q1->calibration = NULL;
3350 /* set node depths */
3351 if (to->isRooted == YES && to->root->left->nodeDepth == 0.0)
3354 /* set partitions */
3356 ResetTreePartitions(to);
3358 /* relaxed clock parameters are not stored in binary trees but in separate parameters */
3364 /*-----------------------------------------------------------------
3366 | CopyToTreeFromTree: copies second tree to first tree
3367 | (used to initialize brlen sets for same topology)
3368 | Note: partition information of nodes are not copied if
3369 | either "from" or "to" tree does not have bitsets allocated
3371 -----------------------------------------------------------------*/
3372 int CopyToTreeFromTree (Tree *to, Tree *from)
3374 int i, numTaxa, nLongsNeeded;
3377 numTaxa = from->nNodes - from->nIntNodes - (from->isRooted == YES ? 1 : 0);
3378 nLongsNeeded = (numTaxa - 1) / nBitsInALong + 1;
3379 if (from->bitsets==NULL || to->bitsets==NULL)
3382 /* check that there is enough memory */
3383 assert (to->memNodes >= from->nNodes);
3385 /* copy nodes (use index of p as memoryIndex for q) */
3386 for (i=0; i<from->nNodes; i++)
3389 p = from->nodes + i;
3390 q = to->nodes + p->index;
3393 q->anc = to->nodes + p->anc->index;
3400 if (p->left != NULL)
3401 q->left = to->nodes + p->left->index;
3405 if (p->right != NULL)
3406 q->right = to->nodes + p->right->index;
3410 CopyTreeNodes (q, p, nLongsNeeded);
3413 /* create new node arrays */
3414 to->nNodes = from->nNodes;
3415 to->nIntNodes = from->nIntNodes;
3418 /* copy tree properties (these should be constant most of them) */
3419 strcpy (to->name, from->name);
3420 to->isRooted = from->isRooted;
3421 to->isClock = from->isClock;
3422 to->isCalibrated = from->isCalibrated;
3423 to->checkConstraints = from->checkConstraints;
3424 to->nConstraints = from->nConstraints;
3425 to->constraints = from->constraints;
3426 to->nLocks = from->nLocks;
3427 to->nRelParts = from->nRelParts;
3428 to->relParts = from->relParts;
3430 /* copy partitions */
3434 AllocateTreePartitions(to);
3436 ResetTreePartitions(to);
3443 /* Copy node q to node p */
3444 void CopyTreeNodes (TreeNode *p, TreeNode *q, int nLongsNeeded)
3446 /* copies everything except pointers and memoryIndex */
3447 p->label = q->label;
3448 p->index = q->index;
3449 p->upDateCl = q->upDateCl;
3450 p->upDateTi = q->upDateTi;
3451 p->scalerNode = q->scalerNode;
3452 p->isLocked = q->isLocked;
3453 p->lockID = q->lockID;
3454 p->isDated = q->isDated;
3455 p->marked = q->marked;
3459 p->length = q->length;
3460 p->nodeDepth = q->nodeDepth;
3461 p->calibration = q->calibration;
3463 if (nLongsNeeded != 0)
3465 assert (p->partition);
3466 assert (q->partition);
3467 memcpy (p->partition, q->partition, nLongsNeeded*sizeof(BitsLong));
3472 void CopyTreeToSubtree (Tree *t, Tree *subtree)
3475 TreeNode *p, *q, *r;
3477 for (i=j=0; i<t->nNodes; i++)
3479 p = t->allDownPass[i];
3480 if (p->marked == NO)
3483 q = &subtree->nodes[j++];
3484 q->index = p->index;
3485 q->length = p->length;
3486 if (p->left == NULL || p->left->marked == NO)
3487 q->left = q->right = NULL;
3490 for (k=0; k<j-1; k++)
3492 r = &subtree->nodes[k];
3493 if (r->index == p->left->index)
3498 else if (r->index == p->right->index)
3506 if (p->anc->marked == NO)
3508 r = &subtree->nodes[j++];
3510 r->anc = r->right = NULL;
3514 r->index = p->anc->index;
3519 GetDownPass (subtree);
3521 subtree->isRooted = t->isRooted;
3522 subtree->nRelParts = t->nRelParts;
3523 subtree->relParts = t->relParts;
3527 /* DatedNodeDepths: Recursive function to get node depths */
3528 void DatedNodeDepths (TreeNode *p, MrBFlt *nodeDepths, int *index)
3532 if (p->left == NULL || p->isDated == YES)
3533 nodeDepths[(*index)++] = p->nodeDepth;
3536 DatedNodeDepths (p->left, nodeDepths, index);
3537 DatedNodeDepths (p->right, nodeDepths, index);
3543 /* DatedNodes: Recursive function to get dated tips or interior nodes */
3544 void DatedNodes (TreeNode *p, TreeNode **datedNodes, int *index)
3548 if (p->left != NULL && p->isDated == NO)
3550 DatedNodes (p->left, datedNodes, index);
3551 DatedNodes (p->right, datedNodes, index);
3553 datedNodes[(*index)++] = p;
3558 /* Deroot: Deroot a rooted polytomous tree with branch lengths */
3559 int Deroot (PolyTree *pt)
3561 PolyNode *p, *q, *r, tempNode;
3566 if (p->left->sib->sib != NULL)
3567 return (ERROR); /* tree is not rooted or it is polytomous */
3569 if (p != &pt->nodes[pt->nNodes-1])
3571 q = &pt->nodes[pt->nNodes-1];
3572 /* now swap content of p and q including pointers */
3576 /* swap back memoryindex */
3577 p->memoryIndex = q->memoryIndex;
3578 q->memoryIndex = tempNode.memoryIndex;
3579 /* all pointers to q should be pointers to p */
3580 for (i=0; i<pt->nNodes; i++)
3590 /* all pointers to p should be pointers to q; all these are anc pointers from the descendants of the root */
3592 for (r=q->left; r!=NULL; r=r->sib)
3594 /* finally set p to the new root */
3598 /* make sure the left of the old root is interior and can be used as new root */
3599 if (p->left->left == NULL)
3609 pt->root->left->sib->sib = p->left->sib;
3610 p->left->sib->length += pt->root->length;
3611 pt->root->length = 0.0;
3612 pt->root->sib = NULL;
3613 pt->root->anc = NULL;
3618 GetPolyDownPass(pt);
3624 /* EraseTreeList: Erase all trees in treeList */
3625 void EraseTreeList (TreeList *treeList)
3627 TreeListElement *listElement;
3628 TreeListElement *previous;
3630 listElement = treeList->first;
3631 if (listElement != NULL)
3634 free (listElement->order);
3635 previous = listElement;
3636 listElement = listElement->next;
3639 while (listElement != NULL);
3641 treeList->first = treeList->last = NULL;
3645 void UpdateTreeWithClockrate (Tree *t, MrBFlt clockRate)
3650 if (t->fromUserTree == NO)
3653 for (i=0; i<t->nNodes; i++)
3655 p = t->allDownPass[i];
3656 p->nodeDepth = p->age * clockRate;
3659 /* calculate branch lengths */
3660 for (i=0; i<t->nNodes; i++)
3662 p = t->allDownPass[i];
3665 if (p->anc->anc != NULL)
3667 p->length = p->anc->nodeDepth - p->nodeDepth;
3670 p->length = 0.0; //not a problem for root node.
3676 for (i=0; i<t->nNodes-1; i++)
3678 p = t->allDownPass[i];
3679 p->age = p->nodeDepth / clockRate;
3685 /*----------------------------------------------------------------
3687 | findAllowedClockrate: Finds the range of clock rates allowed for the tree.
3689 | @param t - tree to check (IN)
3690 | @minClockRate - adress where minimum allowed clock rate is stored (OUT)
3691 | @maxClockRate - adress where maximum allowed clock rate is stored (OUT)
3693 ----------------------------------------------------------------*/
3694 void findAllowedClockrate (Tree *t, MrBFlt *minClockRate, MrBFlt *maxClockRate)
3698 MrBFlt min, max, tmp;
3703 *minClockRate = 2.0;
3704 *maxClockRate = 1.0;
3706 if (t->fromUserTree == NO)
3708 for (i=0; i<t->nNodes-1; i++)
3710 p = t->allDownPass[i];
3711 if (p->anc->anc != NULL)
3713 tmp = BRLENS_MIN/(p->anc->age - p->age);
3718 tmp = BRLENS_MAX/(p->anc->age - p->age);
3729 IsCalibratedClockSatisfied (t,minClockRate,maxClockRate, 0.001);
3734 /* FreePolyTree: Free memory space for a polytomous tree (unrooted or rooted) */
3735 void FreePolyTree (PolyTree *pt)
3739 FreePolyTreePartitions(pt);
3740 FreePolyTreeRelClockParams(pt);
3741 FreePolyTreePopSizeParams(pt);
3742 free (pt->allDownPass);
3749 /* FreePolyTreePartitions: Free memory space for polytomous tree partitions */
3750 void FreePolyTreePartitions (PolyTree *pt)
3753 if (pt != NULL && pt->bitsets != NULL)
3755 for (i=0; i<pt->memNodes; i++)
3756 pt->nodes[i].partition = NULL;
3763 /* FreePolyTreePopSizeParams: Free population size set parameters of polytree */
3764 void FreePolyTreePopSizeParams (PolyTree *pt)
3766 if (pt->popSizeSet == YES)
3769 free (pt->popSizeSetName);
3771 pt->popSizeSet = NO;
3773 pt->popSizeSetName = NULL;
3777 /* FreePolyTreeRelClockParams: Free relaxed clock parameters of polytree */
3778 void FreePolyTreeRelClockParams (PolyTree *pt)
3782 /* free breakpoint clock parameters */
3783 for (i=0; i<pt->nESets; i++)
3785 for (j=0; j<pt->memNodes; j++)
3787 if (pt->nEvents[i][j] > 0)
3789 free (pt->position[i][j]);
3790 free (pt->rateMult[i][j]);
3793 free (pt->eSetName[i]);
3794 free (pt->nEvents[i]);
3795 free (pt->position[i]);
3796 free (pt->rateMult[i]);
3799 free (pt->position);
3800 free (pt->rateMult);
3801 free (pt->eSetName);
3804 pt->position = NULL;
3805 pt->rateMult = NULL;
3806 pt->eSetName = NULL;
3808 /* free branch clock parameters */
3809 for (i=0; i<pt->nBSets; i++)
3811 free (pt->bSetName[i]);
3812 free (pt->effectiveBrLen[i]);
3814 free (pt->effectiveBrLen);
3815 free (pt->bSetName);
3817 pt->effectiveBrLen = NULL;
3818 pt->bSetName = NULL;
3822 /* FreeTree: Free memory space for a tree (unrooted or rooted) */
3823 void FreeTree (Tree *t)
3829 free (t->allDownPass);
3836 /* FreeTreePartitions: Free memory space for tree partitions */
3837 void FreeTreePartitions (Tree *t)
3841 if (t != NULL && t->bitsets != NULL)
3845 for (i=0; i<t->memNodes; i++)
3846 t->nodes[i].partition = NULL;
3851 /*-------------------------------------------------------------------------------------------
3853 | GetDatedNodeDepths: Get an array containing the node depths of the dated tips,
3854 | internal or external, plus dated root
3856 ---------------------------------------------------------------------------------------------*/
3857 void GetDatedNodeDepths (TreeNode *p, MrBFlt *nodeDepths)
3863 nodeDepths[index++] = p->nodeDepth; /* include root node depth */
3864 if (p->left != NULL)
3866 DatedNodeDepths (p->left, nodeDepths, &index);
3867 DatedNodeDepths (p->right, nodeDepths, &index);
3872 /*-------------------------------------------------------------------------------------------
3874 | GetDatedNodes: Get an array containing the dated tips,
3875 | internal or external, and all interior nodes in the same subtree
3877 ---------------------------------------------------------------------------------------------*/
3878 void GetDatedNodes (TreeNode *p, TreeNode **datedNodes)
3886 DatedNodes (p->left, datedNodes, &index);
3887 DatedNodes (p->right, datedNodes, &index);
3892 /* get down pass for tree t (wrapper function) */
3893 void GetDownPass (Tree *t)
3898 GetNodeDownPass (t, t->root, &i, &j);
3902 /* get the actual down pass sequences */
3903 void GetNodeDownPass (Tree *t, TreeNode *p, int *i, int *j)
3907 GetNodeDownPass (t, p->left, i, j);
3908 GetNodeDownPass (t, p->right, i, j);
3909 if (p->left != NULL && p->right != NULL && p->anc != NULL)
3911 t->intDownPass[(*i)++] = p;
3912 t->allDownPass[(*j)++] = p;
3914 else if (p->left == NULL && p->right == NULL && p->anc != NULL)
3916 t->allDownPass[(*j)++] = p;
3918 else if (p->left != NULL && p->right == NULL && p->anc == NULL)
3920 t->allDownPass[(*j)++] = p;
3926 /* GetPolyAges: Get PolyTree node ages */
3927 void GetPolyAges (PolyTree *t)
3932 GetPolyDepths (t); /* just to make sure... */
3934 for (i=0; i<t->nNodes; i++)
3936 p = t->allDownPass[i];
3937 p->age = p->depth / t->clockRate;
3942 /* GetPolyDepths: Get PolyTree node depths */
3943 void GetPolyDepths (PolyTree *t)
3949 maxDepth = t->root->depth = 0.0;
3951 for (i=t->nNodes-2; i>=0; i--)
3953 p = t->allDownPass[i];
3954 p->depth = p->anc->depth + p->length;
3955 if (p->depth > maxDepth)
3956 maxDepth = p->depth;
3959 for (i=0; i<t->nNodes; i++)
3961 p = t->allDownPass[i];
3962 p->depth = maxDepth - p->depth;
3967 /* get down pass for polytomous tree t (wrapper function) */
3968 void GetPolyDownPass (PolyTree *t)
3973 GetPolyNodeDownPass (t, t->root, &i, &j);
3974 assert (t->nIntNodes==j);
3978 /* get the actual down pass sequences for a polytomous tree */
3979 void GetPolyNodeDownPass (PolyTree *t, PolyNode *p, int *i, int *j)
3983 if (p->left != NULL)
3985 for (q=p->left; q!=NULL; q=q->sib)
3986 GetPolyNodeDownPass(t, q, i, j);
3989 t->allDownPass[(*i)++] = p;
3990 if (p->left != NULL)
3991 t->intDownPass[(*j)++] = p;
3995 /* GetFromTreeList: Get first tree from a tree list and remove it from the list*/
3996 int GetFromTreeList (TreeList *treeList, Tree *tree)
3998 TreeListElement *listElement;
4000 if (treeList->first == NULL)
4002 MrBayesPrint ("%s Tree list empty\n", spacer);
4005 if (tree->isRooted == YES)
4006 RetrieveRTopology (tree, treeList->first->order);
4009 RetrieveUTopology (tree, treeList->first->order);
4010 if (localOutGroup != 0)
4011 MoveCalculationRoot (tree, localOutGroup);
4014 listElement = treeList->first;
4015 treeList->first = listElement->next;
4017 free (listElement->order);
4024 /*------------------------------------------------------------------
4026 | InitBrlens: This routine will set all branch lengths of a
4027 | nonclock tree to the value given by 'v'.
4029 ------------------------------------------------------------------*/
4030 int InitBrlens (Tree *t, MrBFlt v)
4035 for (i=0; i<t->nNodes; i++)
4037 p = t->allDownPass[i];
4038 if (p->anc != NULL && !(t->isRooted == YES && p->anc->anc == NULL))
4049 @param levUp is the number of edges between the "node" and the most resent calibrated predecessor +1,
4050 for the calibrated nodes it should be 1
4051 @param calibrUp is the age of the most resent calibrated predecessor
4052 @return age of the node
4054 MrBFlt SetNodeCalibratedAge(TreeNode *node, unsigned levUp, MrBFlt calibrUp)
4058 if (node->age != -1.0)
4060 if (node->right != NULL)
4061 SetNodeCalibratedAge (node->right, 2, node->age);
4062 if (node->left != NULL)
4063 SetNodeCalibratedAge (node->left, 2, node->age);
4067 r = SetNodeCalibratedAge (node->right, levUp+1, calibrUp);
4068 l = SetNodeCalibratedAge (node->left, levUp+1, calibrUp);
4072 assert (calibrUp - r > 0.0);
4073 return node->age = r + (calibrUp - r)/levUp;
4077 assert (calibrUp - l > 0.0);
4078 return node->age = l + (calibrUp - l)/levUp;
4083 /*-------------------------------------------------------------------
4085 | InitCalibratedBrlens: This routine will build a clock tree
4086 | consistent with calibration constraints on terminal
4087 | taxa and/or constrained interior nodes. At least one
4088 | node should be calibrated.
4089 | If not possible to build such a tree, ERROR
4092 --------------------------------------------------------------------*/
4093 int InitCalibratedBrlens (Tree *t, MrBFlt clockRate, RandLong *seed)
4098 MrBFlt treeAgeMin, treeAgeMax;
4099 Calibration *calibrationPtr;
4101 # ifdef DEBUG_CALIBRATION
4102 printf ("Before initializing calibrated brlens\n");
4103 ShowNodes(t->root, 0, YES);
4106 if (t->isRooted == NO)
4108 MrBayesPrint ("%s Tree is unrooted\n", spacer);
4112 /* Check whether root has age constraints */
4113 mp = &modelParams[t->relParts[0]];
4115 treeAgeMax = POS_INFINITY;
4116 if (t->root->left->isDated == YES)
4118 treeAgeMin = t->root->left->calibration->min;
4119 treeAgeMax = t->root->left->calibration->max;
4121 else if (!strcmp(mp->clockPr, "Uniform") || !strcmp(mp->clockPr, "Fossilization"))
4123 if (mp->treeAgePr.min > treeAgeMin)
4124 treeAgeMin = mp->treeAgePr.min;
4125 if (mp->treeAgePr.max < treeAgeMax)
4126 treeAgeMax = mp->treeAgePr.max;
4129 /* date all nodes from top to bottom with min. age as nodeDepth*/
4130 for (i=0; i<t->nNodes; i++)
4132 p = t->allDownPass[i];
4135 if (p->left == NULL && p->right == NULL)
4137 if (p->isDated == NO)
4144 if (p->calibration->prior == fixed)
4145 p->nodeDepth = p->age = p->calibration->priorParams[0];
4147 p->nodeDepth = p->age = p->calibration->min;
4152 if (p->left->nodeDepth > p->right->nodeDepth)
4153 p->nodeDepth = p->left->nodeDepth;
4155 p->nodeDepth = p->right->nodeDepth;
4156 if (p->isDated == YES || (p->anc->anc == NULL && (!strcmp(mp->clockPr,"Uniform") || !strcmp(mp->clockPr,"Fossilization"))))
4158 if (p->isDated == NO)
4159 calibrationPtr = &mp->treeAgePr;
4161 calibrationPtr = p->calibration;
4163 if (calibrationPtr->max <= p->nodeDepth)
4165 if (p->isDated == NO)
4166 MrBayesPrint ("%s Calibration inconsistency for root node\n", spacer);
4168 MrBayesPrint ("%s Calibration inconsistency for node '%s'\n", spacer, constraintNames[p->lockID]);
4169 MrBayesPrint ("%s Cannot make a tree where the node is %s\n", spacer, calibrationPtr->name);
4174 if (calibrationPtr->min < p->nodeDepth)
4175 p->age = p->nodeDepth;
4177 p->age = p->nodeDepth = calibrationPtr->min;
4186 /* try to make root node deeper than minimum age */
4188 if (p->nodeDepth==0.0) p->nodeDepth = 1.0;
4189 if (p->nodeDepth * 1.5 < treeAgeMax)
4190 p->nodeDepth = p->age = 1.5 * p->nodeDepth;
4192 p->nodeDepth = p->age = treeAgeMax;
4194 SetNodeCalibratedAge (p, 1, p->age);
4196 /* Setup node depths */
4197 for (i=0; i<t->nNodes; i++)
4199 p = t->allDownPass[i];
4200 p->nodeDepth = p->age * clockRate;
4201 assert (!(p->left == NULL && p->calibration == NULL && p->nodeDepth != 0.0));
4204 /* calculate branch lengths */
4205 for (i=0; i<t->nNodes; i++)
4207 p = t->allDownPass[i];
4210 if (p->anc->anc != NULL)
4212 p->length = p->anc->nodeDepth - p->nodeDepth;
4213 if (p->length < BRLENS_MIN)
4215 //MrBayesPrint ("%s Restrictions of node calibration and clockrate makes some branch lenghts too small.\n", spacer);
4218 if (p->length > BRLENS_MAX)
4220 //MrBayesPrint ("%s Restrictions of node calibration and clockrate makes some branch lenghts too long.\n", spacer);
4225 p->length = 0.0; //not a problem for root node.
4229 # ifdef DEBUG_CALIBRATION
4231 ShowNodes (t->root, 0, YES);
4236 MrBayesPrint ("%lf", *seed); /* just because I am tired of seeing the unused parameter error msg */
4240 /*-------------------------------------------------------
4242 | InitClockBrlens: This routine will initialize
4243 | a clock tree by setting the root to depth 1.0
4244 | and then assigning node depths according to
4245 | the relative node depth measured in terms of the
4246 | maximum number of branches to the tip from each
4249 --------------------------------------------------------*/
4250 int InitClockBrlens (Tree *t)
4252 int i, maxBrSegments=0;
4255 if (t->isRooted == NO)
4257 MrBayesPrint ("%s Tree is unrooted\n", spacer);
4261 /* calculate maximum number of branch segments above root */
4262 for (i=0; i<t->nNodes; i++)
4264 p = t->allDownPass[i];
4267 if (p->left == NULL && p->right == NULL)
4273 if (p->left->x > p->right->x)
4274 p->x = p->left->x + 1;
4276 p->x = p->right->x + 1;
4278 if (p->anc->anc == NULL)
4279 maxBrSegments = p->x;
4283 /* assign node depths */
4284 for (i=0; i<t->nNodes; i++)
4286 p = t->allDownPass[i];
4288 p->nodeDepth = (MrBFlt) (p->x) / (MrBFlt) maxBrSegments;
4293 /* calculate branch lengths */
4294 for (i=0; i<t->nNodes; i++)
4296 p = t->allDownPass[i];
4299 if (p->anc->anc != NULL)
4300 p->length = p->anc->nodeDepth - p->nodeDepth;
4310 int GetRandomEmbeddedSubtree (Tree *t, int nTerminals, RandLong *seed, int *nEmbeddedTrees)
4312 int i, j, k, n, ran, *pP, *pL, *pR, nLeaves, *nSubTrees;
4313 TreeNode *p=NULL, **leaf;
4315 /* Calculate number of leaves in subtree (number of terminals minus the root) */
4316 nLeaves = nTerminals - 1;
4318 /* Initialize all flags */
4319 for (i=0; i<t->nNodes; i++)
4321 p = t->allDownPass[i];
4327 /* Allocate memory */
4328 nSubTrees = (int *) SafeCalloc (nTerminals * t->nNodes, sizeof(int));
4331 leaf = (TreeNode **) SafeMalloc (nLeaves * sizeof (TreeNode *));
4338 /* Calculate how many embedded trees rooted at each node */
4339 (*nEmbeddedTrees) = 0;
4340 for (i=0; i<t->nNodes-1; i++)
4342 p = t->allDownPass[i];
4343 if (p->left == NULL)
4346 nSubTrees[p->index*nTerminals + 1] = 1;
4350 pL = nSubTrees + p->left->index*nTerminals;
4351 pR = nSubTrees + p->right->index*nTerminals;
4352 pP = nSubTrees + p->index*nTerminals;
4354 for (j=2; j<=nLeaves; j++)
4358 pP[j] += pL[k] * pR[j-k];
4362 (*nEmbeddedTrees) += p->x;
4366 /* Randomly select one embedded tree of the right size */
4367 ran = (int) (RandomNumber(seed) * (*nEmbeddedTrees));
4369 /* Find the interior root corresponding to this tree */
4370 for (i=j=0; i<t->nIntNodes; i++)
4372 p = t->intDownPass[i];
4378 /* Find one random embedded tree with this root */
4385 /* select a node with more than one descendant */
4393 /* break it into descendants */
4394 pL = nSubTrees + p->left->index*nTerminals;
4395 pR = nSubTrees + p->right->index*nTerminals;
4396 pP = nSubTrees + p->index*nTerminals;
4397 ran = (int) (RandomNumber(seed) * pP[p->y]);
4399 for (j=1; j<p->y; j++)
4401 k += pL[j] * pR[p->y-j];
4407 p->right->y = p->y - j;
4408 p->left->marked = YES;
4409 p->right->marked = YES;
4411 leaf[n++] = p->right;
4421 /*-----------------------------------------------------------------------------
4423 | IsCalibratedClockSatisfied: This routine SETS (not just checks as name suggested) calibrated clock tree nodes age, depth. based on branch lengthes
4424 | and checks that user defined brlens satisfy the specified calibration(s) up to tolerance tol
4425 | TODO: clock rate is devived here and used to set ages but clockrate parameter is not updated here (make sure that it does not produce inconsistancy)
4427 |------------------------------------------------------------------------------*/
4428 int IsCalibratedClockSatisfied (Tree *t,MrBFlt *minClockRate,MrBFlt *maxClockRate , MrBFlt tol)
4430 int i, j, maxRateConstrained, minRateConstrained, isViolated;
4431 MrBFlt f, maxHeight, minRate=0, maxRate=0, ageToAdd, *x, *y, clockRate;
4432 TreeNode *p, *q, *r, *s;
4434 /* By defauult assume the tree does not have allowed range of clockrate */
4435 *minClockRate = 2.0;
4436 *maxClockRate = 1.0;
4438 if (t->isRooted == NO)
4441 x = (MrBFlt *) SafeCalloc (2*t->nNodes, sizeof (MrBFlt));
4444 MrBayesPrint ("%s Out of memory in IsCalibratedClockSatisfied\n", spacer);
4450 /* reset node depth and age, and set minimum (x) and maximum (y) age of each node */
4451 for (i=0; i<t->nNodes; i++)
4453 p = t->allDownPass[i];
4455 p->nodeDepth = -1.0;
4456 if (p->isDated == YES)
4458 assert (p->calibration->prior != unconstrained);
4459 x[p->index] = p->calibration->min;
4460 y[p->index] = p->calibration->max;
4462 else if (p->left == NULL && p->right == NULL)
4463 x[p->index] = y[p->index] = 0.0;
4466 x[p->index] = y[p->index] = -1.0;
4470 /* calculate node heights in branch length units */
4471 /* node depth will be set from the root for now */
4474 for (i=t->nNodes-3; i>=0; i--)
4476 p = t->allDownPass[i];
4477 p->nodeDepth = p->anc->nodeDepth + p->length;
4480 /* find maximum height of tree */
4482 for (i=0; i<t->nNodes-1; i++)
4484 p = t->allDownPass[i];
4485 if (p->left == NULL && p->right == NULL)
4487 if (p->nodeDepth > maxHeight)
4489 maxHeight = p->nodeDepth;
4494 /* calculate node depth from tip of tree */
4495 for (i=0; i<t->nNodes-1; i++)
4497 p = t->allDownPass[i];
4498 p->nodeDepth = maxHeight - p->nodeDepth;
4501 /* check potentially constraining calibrations */
4502 /* and find minimum and maximum possible rate */
4503 maxRateConstrained = NO;
4504 minRateConstrained = NO;
4506 for (i=0; i<t->nNodes-1; i++)
4508 p = t->allDownPass[i];
4509 if (x[p->index] < 0.0 && y[p->index] < 0.0)
4511 for (j=i+1; j<t->nNodes-1; j++)
4513 q = t->allDownPass[j];
4514 if (x[q->index] < 0.0 && y[q->index] < 0.0)
4516 if (p->nodeDepth == q->nodeDepth) // becouse clock rate could be as low as possible we can not take approximate equality.
4518 /* same depth so they must share a possible age */
4519 if ((x[p->index] != -1.0 && y[q->index] !=-1.0 && AreDoublesEqual (x[p->index], y[q->index], tol) == NO && x[p->index] > y[q->index]) ||
4520 (y[p->index] != -1.0 && x[q->index] !=-1.0 && AreDoublesEqual (y[p->index], x[q->index], tol) == NO && y[p->index] < x[q->index]))
4528 if (p->nodeDepth > q->nodeDepth)
4538 if (x[r->index] >= 0.0 && y[s->index] >= 0.0)
4540 f = (r->nodeDepth - s->nodeDepth) / (x[r->index] - y[s->index]);
4541 if (f <= 0.0 || x[r->index] == y[s->index])
4543 if (AreDoublesEqual (r->nodeDepth, s->nodeDepth, tol*0.1) == YES)
4545 if ((r->calibration != NULL && r->calibration->prior != fixed) || (s->calibration != NULL && s->calibration->prior != fixed))
4550 if (maxRateConstrained == NO)
4552 maxRateConstrained = YES;
4555 else if (f < maxRate)
4558 if (y[r->index] >= 0.0 && x[s->index] >= 0.0)
4560 f = (r->nodeDepth - s->nodeDepth) / (y[r->index] - x[s->index]);
4561 if (f <= 0.0 || y[r->index] == x[s->index])
4563 if (AreDoublesEqual (r->nodeDepth, s->nodeDepth, tol*0.1) == YES)
4568 if (minRateConstrained == NO)
4570 minRateConstrained = YES;
4573 else if (f > minRate)
4578 if (isViolated == YES)
4582 /* check if outright violation */
4583 if (isViolated == YES)
4585 MrBayesPrint ("%s Branch lengths do not satisfy the calibration(s)\n", spacer);
4590 /* Allow tollerance */
4591 if (minRateConstrained == YES && maxRateConstrained == YES && AreDoublesEqual (minRate, maxRate, tol) == YES && minRate > maxRate)
4596 if (minRateConstrained == YES)
4597 *minClockRate = minRate;
4599 *minClockRate = 0.0;
4601 if (maxRateConstrained == YES)
4602 *maxClockRate = maxRate;
4604 *maxClockRate = MRBFLT_MAX;
4606 /* check that minimum and maximum rates are consistent */
4607 if (minRateConstrained == YES && maxRateConstrained == YES && minRate > maxRate)
4609 MrBayesPrint ("%s Branch lengths do not satisfy the calibration(s)\n", spacer);
4614 /* date all nodes based on a suitable rate */
4615 if (minRateConstrained == YES)
4616 clockRate = minRate;
4617 else if (maxRateConstrained == YES)
4618 clockRate = 0.5 * maxRate;
4621 for (i=0; i<t->nNodes-1; i++)
4623 p = t->allDownPass[i];
4624 p->age = p->nodeDepth / clockRate;
4627 /* check if there is an age to add (I guess this is here because when max rate is close to minrate and we have numerical precision inacuracy) */
4629 for (i=0; i<t->nNodes-1; i++)
4631 p = t->allDownPass[i];
4632 if (x[p->index] > 0.0 && x[p->index] > p->age)
4634 f = x[p->index] - p->age;
4640 /* add extra length if any */
4641 if (AreDoublesEqual (ageToAdd, 0.0, 0.00000001) == NO)
4643 for (i=0; i<t->nNodes-1; i++)
4645 p = t->allDownPass[i];
4652 /* reset node depths to ensure that non-dated tips have node depth 0.0 */
4659 int IsClockSatisfied (Tree *t, MrBFlt tol)
4661 int i, foundFirstLength, isClockLike;
4662 MrBFlt firstLength=0.0, length;
4665 if (t->isRooted == NO)
4668 foundFirstLength = NO;
4670 for (i=0; i<t->nNodes; i++)
4672 p = t->allDownPass[i];
4673 if (p->left == NULL && p->right == NULL)
4675 if (p->isDated == YES)
4678 length = p->nodeDepth;
4683 while (q->anc != NULL)
4685 if (q->anc->anc != NULL)
4686 length += q->length;
4689 if (foundFirstLength == NO)
4691 firstLength = length;
4692 foundFirstLength = YES;
4696 if (AreDoublesEqual (firstLength, length, tol) == NO)
4698 MrBayesPrint ("%s Node (%s) is not at the same depth as some other tip taking colibration into account. \n", spacer, p->label);
4704 if (firstLength < BRLENS_MIN)
4707 return (isClockLike);
4711 /* Check that tree obeys topology constraints and that node depths and ages are consistent */
4712 int IsTreeConsistent (Param *param, int chain, int state)
4717 MrBFlt b, r, rAnc, clockRate;
4720 if (param->paramType != P_TOPOLOGY && param->paramType != P_BRLENS && param->paramType != P_SPECIESTREE)
4723 tree = GetTree(param, chain, state);
4724 if (modelSettings[param->relParts[0]].clockRate != NULL)
4725 clockRate = *GetParamVals(modelSettings[param->relParts[0]].clockRate, chain, state);
4729 if (CheckConstraints(tree)==ERROR) {
4730 printf ("Tree does not obey constraints\n");
4734 /* check that the last few indices are not taken in a rooted tree */
4735 if (tree->isRooted == YES && tree->root->index != tree->nNodes - 1)
4737 printf ("Problem with root index\n");
4740 if (tree->isRooted == YES && tree->root->left->index != tree->nNodes - 2)
4742 printf ("Problem with interior root index\n");
4746 if (tree->isClock == NO)
4748 for (i=0; i<tree->nNodes-1; i++)
4750 p = tree->allDownPass[i];
4751 if (p->length <= 0.0)
4753 if (p->length == 0.0)
4754 printf ("Node %d has zero branch length %f\n", p->index, p->length);
4756 printf ("Node %d has negative branch length %f\n", p->index, p->length);
4765 /* Check that lengths and depths are consistent */
4766 for (i=0; i<tree->nNodes-2; i++) {
4767 p = tree->allDownPass[i];
4768 if (p->length < 0.0) {
4769 printf ("Node %d has negative branch length %f\n", p->index, p->length);
4772 if (fabs(p->anc->nodeDepth - p->nodeDepth - p->length) > 0.000001) {
4773 printf ("Node %d has length %f but nodeDepth %f and ancNodeDepth %f\n",
4774 p->index, p->length, p->nodeDepth, p->anc->nodeDepth);
4777 if (p->left == NULL && p->isDated == NO && p->nodeDepth != 0.0) {
4778 printf ("Node %d is an autodated tip (0.0) but has node depth %lf\n",
4779 p->index, p->nodeDepth);
4784 /* Check that ages and calibrations are consistent */
4785 if (tree->isCalibrated == YES)
4787 for (i=0; i<tree->nNodes-1; i++)
4789 p = tree->allDownPass[i];
4790 if (p->isDated == YES) {
4791 if (fabs((p->age - p->nodeDepth/clockRate)/p->age) > 0.000001)
4793 printf ("Node %d has age %f but nodeDepth %f when clock rate is %f\n",
4794 p->index, p->age, p->nodeDepth, clockRate);
4797 if (p->calibration->prior == fixed && fabs((p->age - p->calibration->priorParams[0])/p->age) > 0.000001)
4799 printf ("Node %d has age %f but should be fixed to age %f\n",
4800 p->index, p->age, p->calibration->priorParams[0]);
4803 else if (p->calibration->prior == uniform &&
4804 ((p->age - p->calibration->min)/p->age < -0.000001 || (p->age - p->calibration->max)/p->age > 0.000001))
4806 printf ("Node %d has age %f but should be in the interval [%f,%f]\n",
4807 p->index, p->age, p->calibration->min, p->calibration->max);
4810 else if ((p->age - p->calibration->min)/p->age < -0.000001)
4812 printf ("Node %d has age %f but should be at least of age %f\n",
4813 p->index, p->age, p->calibration->min);
4816 else if ((p->age - p->calibration->max)/p->age > 0.000001)
4818 printf ("Node %d has age %f but should be no older than %f\n",
4819 p->index, p->age, p->calibration->max);
4826 for (i=0; i<param->nSubParams; i++)
4828 subParm = param->subParams[i];
4829 if (subParm->paramId == TK02BRANCHRATES || (subParm->paramId == MIXEDBRCHRATES && *GetParamIntVals(subParm, chain, state) == RCL_TK02))
4831 rAnc = GetParamVals(subParm, chain, state)[tree->root->left->index];
4832 if (fabs(rAnc - 1.0) > 1E-6)
4834 printf ("%s TK02 relaxed clock mismatch in root rate, which is %e\n", spacer, rAnc);
4837 for (j=0; j<tree->nNodes-2; j++)
4839 p = tree->allDownPass[j];
4840 b = GetParamSubVals(subParm, chain, state)[p->index];
4841 r = GetParamVals(subParm, chain, state)[p->index];
4842 rAnc = GetParamVals(subParm, chain, state)[p->anc->index];
4843 if (fabs(p->length * (r + rAnc) / 2.0 - b) > 0.000001)
4845 printf ("%s TK02 relaxed clock mismatch in branch %d\n", spacer, p->index);
4850 else if (subParm->paramId == IGRBRANCHRATES || (subParm->paramId == MIXEDBRCHRATES && *GetParamIntVals(subParm, chain, state) == RCL_IGR))
4852 for (j=0; j<tree->nNodes-2; j++)
4854 p = tree->allDownPass[j];
4855 b = GetParamSubVals(subParm, chain, state)[p->index];
4856 r = GetParamVals(subParm, chain, state)[p->index];
4857 if (fabs(p->length * r - b) > 0.000001)
4859 printf ("%s Igr relaxed clock mismatch in branch %d\n", spacer, p->index);
4866 if (param->paramType == P_SPECIESTREE)
4867 return (IsSpeciesTreeConsistent(GetTree(param, chain, state), chain));
4873 /* LabelTree: Label tree; remove previous labels if any */
4874 int LabelTree (Tree *t, char **taxonNames)
4879 nTaxa = t->nNodes - t->nIntNodes;
4880 if (t->isRooted == YES)
4883 /* erase previous labels, if any */
4884 for (i=0; i<t->nNodes; i++)
4886 p = t->allDownPass[i];
4888 t->nodes[i].label = noLabel;
4892 for (i=0; i<t->nNodes; i++)
4895 if (p->left == NULL || (t->isRooted == NO && p->anc == NULL))
4897 if (p->marked == YES || p->index < 0 || p->index >= nTaxa)
4899 MrBayesPrint ("%s Taxon node index repeated or out of range\n", spacer);
4903 p->label = taxonNames[p->index];
4906 else if (p->index > 0 && p->index < nTaxa)
4908 MrBayesPrint ("%s Terminal taxon index set for interior node\n", spacer);
4917 /*-------------------------------------------------------------------------------------------
4919 | Mark: This routine will mark up a subtree rooted at p
4921 ---------------------------------------------------------------------------------------------*/
4922 void Mark (TreeNode *p)
4933 /*-------------------------------------------------------------------------------------------
4935 | MarkDistance: This routine will mark up an unconstrained subtree rooted at p within dist
4936 | The distance will be positive in the crown part and negative in the root part.
4938 ---------------------------------------------------------------------------------------------*/
4939 void MarkDistance (TreeNode *p, int YESorNO, int dist, int *n)
4941 if (p == NULL || p->anc == NULL)
4945 if (YESorNO == YES) // in root part
4946 p->x = p->anc->x -1;
4947 else // in crown part
4948 p->x = p->anc->x +1;
4951 if (p->isLocked == NO && abs(p->x) < dist)
4953 MarkDistance (p->left, YESorNO, dist, n);
4954 MarkDistance (p->right,YESorNO, dist, n);
4959 /*-------------------------------------------------------------------------------------------
4961 | MarkUnconstrained: This routine will mark up an unconstrained subtree rooted at p
4963 ---------------------------------------------------------------------------------------------*/
4964 void MarkUnconstrained (TreeNode *p)
4969 if (p->isLocked == NO)
4971 MarkUnconstrained (p->left);
4972 MarkUnconstrained (p->right);
4978 /*-------------------------------------------------------------------------------------------
4980 | MoveCalculationRoot: This routine will move the calculation root to the terminal with
4983 ---------------------------------------------------------------------------------------------*/
4984 int MoveCalculationRoot (Tree *t, int outgroup)
4987 TreeNode *p, *q, *r;
4989 if (t->isRooted == YES || outgroup < 0 || outgroup > t->nNodes - t->nIntNodes - (t->isRooted == YES ? 1 : 0))
4991 MrBayesPrint ("%s Problem moving calculation root\n", spacer);
4995 if (t->root->index == outgroup)
4996 return (NO_ERROR); /* nothing to do */
4998 /* mark the path to the new calculation root */
4999 for (i=0; i<t->nNodes; i++)
5001 p = t->allDownPass[i];
5002 if (p->left == NULL && p->right == NULL)
5004 if (p->index == outgroup)
5011 if (p->left->marked == YES || p->right->marked == YES)
5018 /* rotate the tree to use the specified calculation root */
5022 q->left = q->right = NULL;
5023 q->length = p->length;
5024 while (p->left != NULL && p->right != NULL)
5026 if (p->left->marked == YES)
5031 p->length = r->length;
5035 else /* if (p->right->marked == YES) */
5040 p->length = r->length;
5046 p->right = p->anc = NULL;
5056 /*-------------------------------------------------------------------------------------------
5058 | MovePolyCalculationRoot: This routine will move the calculation root to the terminal with
5059 | index outgroup and place it as the right-most descendant of the root node
5061 ---------------------------------------------------------------------------------------------*/
5062 int MovePolyCalculationRoot (PolyTree *t, int outgroup)
5065 PolyNode *p = NULL, *q, *r;
5067 /* check if tree is rooted, in which case calculation root is irrelevant */
5068 if (t->root->left->sib->sib == NULL)
5071 if (outgroup < 0 || outgroup > t->nNodes - t->nIntNodes)
5073 MrBayesPrint ("%s Outgroup index is out of range\n", spacer);
5077 if (t->root->left->sib->sib->sib != NULL)
5079 MrBayesPrint ("%s Root has more than three descendants\n", spacer);
5083 /* check if rerooting actually necessary */
5084 if (t->root->left->sib->sib->index == outgroup)
5087 /* mark the path to the new calculation root */
5088 for (i=0; i<t->nNodes; i++)
5090 p = t->allDownPass[i];
5091 if (p->index == outgroup)
5094 if (p->left != NULL)
5096 MrBayesPrint ("%s Outgroup index set for internal node\n", spacer);
5097 for (i=0; i<t->nNodes; i++)
5098 printf ("%d -- %d\n", i, t->allDownPass[i]->index);
5103 /* mark path to current root */
5104 for (i=0; i<t->nNodes; i++)
5105 t->allDownPass[i]->mark = NO;
5113 /* rotate the tree to use the specified calculation root */
5117 /* find marked descendant */
5118 for (q=p->left; q->mark == NO; q=q->sib)
5120 if (q->index == outgroup)
5122 /* add old root to descendants of that node */
5123 for (r=q->left; r->sib!=NULL; r=r->sib)
5126 p->sib = NULL; /* should not be needed */
5128 p->length = q->length;
5129 /* remove that node from descendants of old root node */
5134 for (r=p->left; r->sib!=q; r=r->sib)
5136 r->sib = r->sib->sib;
5138 /* make new node root */
5145 /* p is now the new root */
5148 /* finally make sure calculation root is last node among root's descendants */
5149 for (q=p->left; q->sib!=NULL; q=q->sib)
5151 if (q->index != outgroup)
5153 if (p->left->index == outgroup)
5156 p->left = p->left->sib;
5161 for (r=p->left; r->sib->index!=outgroup; r=r->sib)
5164 r->sib = r->sib->sib;
5169 GetPolyDownPass (t);
5176 @return the number of levels for the tree rooted at the "node"
5178 int NrSubTreeLevels(TreeNode *node)
5187 r = NrSubTreeLevels (node->right);
5188 l = NrSubTreeLevels (node->left);
5190 return ((r>l)?(r):(l))+1;
5194 /*-------------------------------------------------------------------------------------------
5196 | NumConstrainedTips: This routine will return the number of constrained tips, internal or external
5198 ---------------------------------------------------------------------------------------------*/
5199 int NumConstrainedTips (TreeNode *p)
5205 if (p->left == NULL)
5208 i += NConstrainedTips (p->left);
5209 i += NConstrainedTips (p->right);
5215 /* NConstrainedTips: Recursive function to get the number of constrained tips */
5216 int NConstrainedTips (TreeNode *p)
5222 if (p->left == NULL || p->isLocked == YES)
5226 i += NConstrainedTips (p->left);
5227 i += NConstrainedTips (p->right);
5234 /*-------------------------------------------------------------------------------------------
5236 | NumDatedTips: This routine will return the number of dated tips, internal or external
5238 ---------------------------------------------------------------------------------------------*/
5239 int NumDatedTips (TreeNode *p)
5243 assert (p != NULL && p->left != NULL);
5245 i += NDatedTips (p->left);
5246 i += NDatedTips (p->right);
5252 /* NDatedTips: recursive function to get the number of dated tips */
5253 int NDatedTips (TreeNode *p)
5259 if (p->left == NULL || p->isDated == YES)
5263 i += NDatedTips (p->left);
5264 i += NDatedTips (p->right);
5270 /* OrderTips: Order tips in a polytomous tree */
5271 void OrderTips (PolyTree *t)
5274 PolyNode *p, *q, *r, *pl, *ql, *rl;
5276 /* label by minimum index */
5277 for (i=0; i<t->nNodes; i++)
5279 p = t->allDownPass[i];
5280 if (p->left == NULL)
5282 if (t->isRooted == NO && p->index == localOutGroup)
5290 for (q=p->left; q!=NULL; q=q->sib)
5300 for (i=0; i<t->nNodes; i++)
5302 p = t->allDownPass[i];
5303 if (p->left == NULL || p->anc == NULL)
5305 for (ql=NULL, q=p->left; q->sib!=NULL; ql=q, q=q->sib)
5307 for (rl=q, r=q->sib; r!=NULL; rl=r, r=r->sib)
5313 if (r == q->sib) /* swap adjacent q and r */
5321 else /* swap separated q and r */
5341 /* PrintNodes: Print a list of tree nodes, pointers and length */
5342 void PrintNodes (Tree *t)
5347 printf ("Node\tleft\tright\tanc\tlength\n");
5348 for (i=0; i<t->nNodes; i++)
5351 printf ("%d\t%d\t%d\t%d\t%f\t%f\n",
5353 p->left == NULL ? -1 : p->left->index,
5354 p->right == NULL ? -1 : p->right->index,
5355 p->anc == NULL ? -1 : p->anc->index,
5360 if (t->root == NULL)
5361 printf ("root: NULL\n");
5363 printf ("root: %d\n", t->root->index);
5365 printf ("allDownPass:");
5366 for (i=0; i<t->nNodes; i++)
5368 p = t->allDownPass[i];
5370 printf (" %d", p->index);
5374 printf ("\nintDownPass: ");
5375 for (i=0; i<t->nIntNodes; i++)
5377 p = t->intDownPass[i];
5379 printf (" %d\t", p->index);
5387 /* PrintPolyNodes: Print a list of polytomous tree nodes, pointers and length */
5388 void PrintPolyNodes (PolyTree *pt)
5393 printf ("Node\tleft\tsib\tanc\tlength\tlabel\n");
5394 for (i=0; i<pt->memNodes; i++)
5397 printf ("%d\t%d\t%d\t%d\t%f\t%s\n",
5399 p->left == NULL ? -1 : p->left->index,
5400 p->sib == NULL ? -1 : p->sib->index,
5401 p->anc == NULL ? -1 : p->anc->index,
5405 printf ("root: %d\n", pt->root->index);
5410 for (i=0; i<pt->nBSets; i++)
5412 printf ("Effective branch length set '%s'\n", pt->bSetName[i]);
5413 for (j=0; j<pt->nNodes; j++)
5415 printf ("%d:%f", j, pt->effectiveBrLen[pt->nBSets][j]);
5416 if (j != pt->nNodes-1)
5425 for (i=0; i<pt->nESets; i++)
5427 printf ("Cpp event set '%s'\n", pt->eSetName[i]);
5428 for (j=0; j<pt->nNodes; j++)
5430 if (pt->nEvents[i*pt->nNodes+j] > 0)
5432 printf ("\tNode %d -- %d:(", j, pt->nEvents[i][j]);
5433 for (k=0; k<pt->nEvents[i][j]; k++)
5435 printf ("%f %f", pt->position[i][j][k], pt->rateMult[i][j][k]);
5436 if (k != pt->nEvents[i][j]-1)
5450 /* PrintTranslateBlock: Print a translate block to file fp for tree t */
5451 void PrintTranslateBlock (FILE *fp, Tree *t)
5455 if (t->isRooted == NO)
5456 nTaxa = t->nNodes - t->nIntNodes;
5458 nTaxa = t->nNodes - t->nIntNodes - 1;
5460 fprintf (fp, "\ttranslate\n");
5462 for (i=0; i<nTaxa; i++)
5464 for (j=0; j<t->nNodes; j++)
5465 if (t->allDownPass[j]->index == i)
5468 fprintf (fp, "\t\t%d\t%s;\n", i+1, t->allDownPass[j]->label);
5470 fprintf (fp, "\t\t%d\t%s,\n", i+1, t->allDownPass[j]->label);
5476 Update relaxed clock parameter of the branch of a node with index "b" after node with index "a" is removed.
5477 i.e. make branch of node with index "b" be a concatenation of its original branch and the branch of node with index "a"
5478 Relaxed clock parameter of node with index "a" become invalid in the process.
5479 Note: For Non-clock models the routine has no effect.
5488 void AppendRelaxedBranch (int a,int b,PolyTree *t)
5492 for (i=0; i<t->nBSets; i++)
5494 t->effectiveBrLen[i][b] += t->effectiveBrLen[i][a];
5497 for (i=0; i<t->nESets; i++)
5499 len=t->nEvents[i][a]+t->nEvents[i][b];
5500 t->position[i][a] = (MrBFlt *) SafeRealloc ((void *)t->position[i][a], len*sizeof(MrBFlt));
5501 t->rateMult[i][a] = (MrBFlt *) SafeRealloc ((void *)t->rateMult[i][a], len*sizeof(MrBFlt));
5502 memcpy (t->position[i][a]+t->nEvents[i][a], t->position[i][b], t->nEvents[i][b]*sizeof(MrBFlt));
5503 memcpy (t->rateMult[i][a]+t->nEvents[i][a], t->rateMult[i][b], t->nEvents[i][b]*sizeof(MrBFlt));
5504 free(t->position[i][b]);
5505 free(t->rateMult[i][b]);
5506 t->position[i][b] = t->position[i][a];
5507 t->rateMult[i][b] = t->rateMult[i][a];
5508 t->position[i][a] = NULL;
5509 t->rateMult[i][a] = NULL;
5510 t->nEvents[i][a] = 0;
5511 t->nEvents[i][b] = len;
5518 Swap relaxed clock paramiters of the branch of nodes with index "a" and "b".
5520 void SwapRelaxedBranchInfo (int a,int b,PolyTree *t)
5525 for (i=0; i<t->nBSets; i++)
5527 tmp = t->effectiveBrLen[i][a];
5528 t->effectiveBrLen[i][a] = t->effectiveBrLen[i][b];
5529 t->effectiveBrLen[i][b] = tmp;
5531 if (t->popSizeSet == YES)
5533 tmp = t->popSize[a];
5534 t->popSize[a]=t->popSize[b];
5535 t->popSize[b] = tmp;
5538 for (i=0; i<t->nESets; i++)
5540 tmpp = t->position[i][a];
5541 t->position[i][a] = t->position[i][b];
5542 t->position[i][b] = tmpp;
5543 tmpp = t->rateMult[i][a];
5544 t->rateMult[i][a] = t->rateMult[i][b];
5545 t->rateMult[i][b] = tmpp;
5546 j = t->nEvents[i][a];
5547 t->nEvents[i][a] = t->nEvents[i][b];
5548 t->nEvents[i][b] = j;
5553 /*-------------------------------------------------------------------------------------------
5555 | PrunePolyTree: This routine will prune a polytomous tree according to the currently
5556 | included taxa. NB! All tree nodes cannot be accessed by cycling over the
5557 | pt->nodes array after the deletion, because some spaces will be occupied by deleted
5558 | nodes and pt->nNodes is no longer the length of this array
5559 | (if proper re-arangment of pt->nodes needed then remove "#if 0" and make changes to p->x, see below).
5561 ---------------------------------------------------------------------------------------------*/
5562 int PrunePolyTree (PolyTree *pt)
5564 int i, j, numDeleted, numTermPruned, numIntPruned, index;
5565 PolyNode *p = NULL, *q=NULL, *r=NULL, *qa;
5568 for (i=0; i<pt->nNodes; i++)
5570 p = pt->allDownPass[i];
5571 CheckString (taxaNames, numTaxa, p->label, &index);
5572 if (p->left == NULL && taxaInfo[index].isDeleted == YES)
5576 if (numDeleted == 0)
5581 if (pt->nNodes - pt->nIntNodes - numDeleted < 3)
5583 MrBayesPrint ("%s Pruned tree has less than three taxa in it\n", spacer);
5586 if (pt->nNodes - pt->nIntNodes < numLocalTaxa)
5588 MrBayesPrint ("%s Tree to be pruned does not include all taxa\n", spacer);
5592 /* prune away one node at a time */
5595 for (i=0; i<pt->nNodes; i++)
5597 p = pt->allDownPass[i];
5598 if (p->left != NULL)
5600 CheckString (taxaNames, numTaxa, p->label, &index);
5601 if (taxaInfo[index].isDeleted == YES)
5604 for (q=p->anc->left; q!=NULL; q=q->sib)
5611 /* p is the left of its ancestor */
5612 assert (p->anc->left == p);
5613 p->anc->left = p->sib;
5617 /* p is q->sib; this also works if p->sib is NULL */
5620 /* if only one child left, delete ancestral node */
5622 for (q=p->anc->left; q!=NULL; q=q->sib)
5626 /* p->anc->left is only child left; make p->anc be p->anc->left and accommodate its length */
5630 if (q->left == NULL)
5632 AppendRelaxedBranch (qa->index, q->index, pt);
5633 qa->index = q->index;
5634 qa->length += q->length;
5635 strcpy(qa->label, q->label);
5637 /* To make sure that q is not treated as the representer of the tip it represented before. i.e. make condition if (p->left != NULL) true */
5638 q->left = (struct pNode*)1;
5642 if (qa->anc != NULL)
5644 AppendRelaxedBranch (qa->index, q->index, pt);
5645 qa->length += q->length;
5647 qa->index = q->index;
5649 for (r=q->left; r!= NULL; r=r->sib)
5653 /* if unrooted, then root node has to have more then 2 children, thus the following check */
5654 if (j == 2 && pt->isRooted == NO && p->anc->anc == NULL)
5657 r=p->anc; /*r is the root with only 2 children*/
5658 if (r->left->left != NULL)
5659 {/* Make r->left new root by attaching "right" child of r to children of r->left */
5660 for (q=r->left->left; q->sib!=NULL; q=q->sib)
5662 q->sib = r->left->sib;
5663 r->left->sib->anc = q->anc;
5664 r->left->sib->length += q->anc->length;
5665 r->left->sib = NULL;
5666 r->left->anc = NULL;
5670 {/* Make "right" child of r (r->left->sib) the new root by attaching r->left to children of r->"right" */
5671 for (q=r->left->sib->left; q->sib!=NULL; q=q->sib)
5674 r->left->anc = q->anc;
5675 r->left->length += q->anc->length;
5676 r->left->sib = NULL;
5685 /* place unused space at the end of pt->nodes array. If activated this code p->x has to be set to non 0 value for all p that are deleted. */
5686 for (i=0; i<pt->nNodes; i++)
5691 for (j=i+1; j<pt->nNodes; j++)
5697 if (j != pt->nNodes)
5699 /* swap nodes; quite difficult! */
5700 CopyPolyNodes (p, q, nLongsNeeded);
5704 for (k=0; k<pt->nNodes; k++)
5719 /* correct number of nodes */
5720 pt->nNodes -= (numTermPruned + numIntPruned);
5721 pt->nIntNodes -= numIntPruned;
5723 /* get downpass; note that the deletion procedure does not change the root in rooted case */
5725 GetPolyNodeDownPass (pt, pt->root, &i, &j);
5726 assert (i==pt->nNodes);
5727 assert (j==pt->nIntNodes);
5733 /*--------------------------------------------------------------------
5735 | RandPerturb: Randomly perturb a tree by nPert NNIs
5737 ---------------------------------------------------------------------*/
5738 int RandPerturb (Tree *t, int nPert, RandLong *seed)
5741 TreeNode *p, *q, *a, *b, *c;
5743 if (t->nConstraints >= t->nIntNodes)
5745 MrBayesPrint ("%s User tree cannot be perturbed because all nodes are locked\n", spacer);
5749 for (i=0; i<nPert; i++)
5753 whichNode = (int)(RandomNumber(seed) * (t->nIntNodes - 1));
5754 p = t->intDownPass[whichNode];
5755 } while (p->isLocked == YES);
5765 if (RandomNumber(seed) < 0.5)
5790 if (t->isCalibrated == YES)
5791 InitCalibratedBrlens (t, 0.0001, seed);
5792 else if (t->isClock == YES)
5793 InitClockBrlens (t);
5798 if (t->checkConstraints == YES && CheckConstraints (t) == NO_ERROR)
5800 MrBayesPrint ("%s Broke constraints when perturbing tree\n", spacer);
5809 | Reorder array of nodes "nodeArray" such that first nodes in it could be paired with "w" to create imediat common ancestor and this ancesor node would not vialate any constraint.
5811 | @param w Reference node as described
5812 | @param nodeArray A set of node to order as described
5813 | @param activeConstraints Array containing indeces of active constraints in the set of defined constraints
5814 | @param nLongsNeeded Length of partition information (in BitsLong) in a node and constraint deffinition.
5815 | @param isRooted Do constraints apply to rootet tree YES or NO
5817 | @return Number of nodes in "nodeArray" that could be paired with "w" to create imediat common ancestor and this ancesor node would not vialate any constraint
5819 int ConstraintAllowedSet(PolyNode *w, PolyNode **nodeArray, int nodeArraySize, int *activeConstraints, int activeConstraintsSize, int nLongsNeeded, int isRooted)
5821 int i, j, k, FirstEmpty;
5822 BitsLong **constraintPartition;
5825 for (j=0; j<activeConstraintsSize; j++)
5827 k=activeConstraints[j];
5829 if (definedConstraintsType[k] == PARTIAL)
5831 if ((IsPartNested(definedConstraintPruned[k], w->partition, nLongsNeeded) == YES) ||
5832 (isRooted == NO && IsPartNested(definedConstraintTwoPruned[k], w->partition, nLongsNeeded) == YES))
5833 continue;/* all nodes are compartable because condition of the constraint has to be sutsfied in the subtree rooted at w*/
5835 FirstEmpty = IsSectionEmpty(definedConstraintPruned[k], w->partition, nLongsNeeded);
5836 if (FirstEmpty == YES && IsSectionEmpty(definedConstraintTwoPruned[k], w->partition, nLongsNeeded) == YES)
5837 continue; /* all nodes are compartable becouse w does not contain any constraint taxa*/
5839 assert (FirstEmpty^IsSectionEmpty(definedConstraintTwoPruned[k], w->partition, nLongsNeeded));
5841 if (FirstEmpty == YES)
5842 {/*w->partition has intersection with definedConstraintTwoPruned[k], thus remove all nodes from nodeArray that intersect with definedConstraintPruned[k]*/
5843 constraintPartition=definedConstraintPruned;
5846 {/*w->partition has intersection with definedConstraintPruned[k], thus remove all nodes from nodeArray that intersect with definedConstraintTwoPruned[k]*/
5847 constraintPartition=definedConstraintTwoPruned;
5850 for (i=0;i<nodeArraySize;i++)
5852 if (IsSectionEmpty(constraintPartition[k], nodeArray[i]->partition, nLongsNeeded) == NO &&
5853 ((FirstEmpty == NO && isRooted== YES) || IsPartNested(constraintPartition[k], nodeArray[i]->partition, nLongsNeeded) == NO))
5854 /*second part of if statment is to bail out "nodeArray[i]" when "w" contains nodes for example from definedConstraintPruned and "nodeArray[i]" have definedConstraintTwoPruned fully nested in it
5855 This bail out not applicable if t->isRooted== YES Since we should create a rooting node for the first set of taxa in the constraint.
5856 Note that such case possible because we may have hard constraint node that fully nest definedConstraintTwoPruned but also having taxa from definedConstraintPruned keeping constraint active.*/
5859 nodeArray[i]=nodeArray[--nodeArraySize];
5860 nodeArray[nodeArraySize]=tmp;
5867 assert (definedConstraintsType[k] == NEGATIVE);
5868 if (isRooted == YES || IsBitSet(localOutGroup, definedConstraintPruned[k])==NO)
5869 constraintPartition=definedConstraintPruned;
5871 constraintPartition=definedConstraintTwoPruned;
5873 if (IsSectionEmpty(constraintPartition[k], w->partition, nLongsNeeded)==YES)
5876 for (i=0;i<nodeArraySize;i++)
5878 if (IsUnionEqThird (w->partition, nodeArray[i]->partition, constraintPartition[k], nLongsNeeded) == YES)
5881 nodeArray[i]=nodeArray[--nodeArraySize];
5882 nodeArray[nodeArraySize]=tmp;
5887 }/*end if NEGATIVE*/
5890 return nodeArraySize;
5895 | Check if "partition" violate any constraint.
5897 | @param partiton Partition to check
5898 | @param activeConstraints Array containing indeces of active constraints in the set of defined constraints
5899 | @param nLongsNeeded Length of partition information (in BitsLong) in a node and constraint deffinition
5900 | @param isRooted Do constraints apply to rootet tree YES or NO
5902 | @return Index of first violated constraint in activeConstraints array, -1 if no constraint is violated.
5904 int ViolatedConstraint(BitsLong *partition, int *activeConstraints, int activeConstraintsSize, int nLongsNeeded, int isRooted)
5907 BitsLong **constraintPartition;
5909 for (j=0; j<activeConstraintsSize; j++)
5911 k=activeConstraints[j];
5912 assert (definedConstraintsType[k] != HARD);
5914 if (definedConstraintsType[k] == PARTIAL)
5916 if ((IsSectionEmpty(definedConstraintPruned[k], partition, nLongsNeeded) == NO) &&
5917 (IsSectionEmpty(definedConstraintTwoPruned[k], partition, nLongsNeeded) == NO) &&
5918 (IsPartNested(definedConstraintPruned[k], partition, nLongsNeeded) == NO) &&
5919 !(isRooted == NO && IsPartNested(definedConstraintTwoPruned[k], partition, nLongsNeeded) == YES))
5924 assert (definedConstraintsType[k] == NEGATIVE);
5925 if (isRooted == YES || IsBitSet(localOutGroup, definedConstraintPruned[k])==NO)
5926 constraintPartition=definedConstraintPruned;
5928 constraintPartition=definedConstraintTwoPruned;
5930 if (IsUnionEqThird (partition, partition, constraintPartition[k], nLongsNeeded) == YES)
5932 }/*end if NEGATIVE*/
5940 | Remove from activeConstraints references to constraints that become satisfied if PolyNode "w" exist, i.e. they do not need to be checked furter thus become not active
5942 | @param activeConstraints Array containing indeces of active constraints in the set of defined constraints
5943 | @param nLongsNeeded Length of partition information (in BitsLong) in a node and constraint deffinition.
5944 | @param isRooted Do constraints apply to rootet tree YES or NO
5946 | @return Size of pruned "activeConstraints" array
5948 int PruneActiveConstraints (PolyNode *w, int *activeConstraints, int activeConstraintsSize, int nLongsNeeded, int isRooted)
5951 BitsLong **constraintPartition;
5954 for (j=0; j<activeConstraintsSize; j++)
5956 k=activeConstraints[j];
5958 if (definedConstraintsType[k] == PARTIAL)
5960 if ((IsPartNested(definedConstraintPruned[k], w->partition, nLongsNeeded) == YES && IsSectionEmpty(definedConstraintTwoPruned[k], w->partition, nLongsNeeded)) ||
5961 (isRooted == NO && IsPartNested(definedConstraintTwoPruned[k], w->partition, nLongsNeeded) == YES && IsSectionEmpty(definedConstraintPruned[k], w->partition, nLongsNeeded)))
5963 //tmp = activeConstraints[j];
5964 activeConstraints[j]=activeConstraints[--activeConstraintsSize];
5965 //activeConstraints[activeConstraintsSize]=tmp;
5971 assert (definedConstraintsType[k] == NEGATIVE);
5972 if (isRooted == YES || IsBitSet(localOutGroup, definedConstraintPruned[k])==NO)
5973 constraintPartition=definedConstraintPruned;
5975 constraintPartition=definedConstraintTwoPruned;
5977 if (IsPartNested(constraintPartition[k], w->partition, nLongsNeeded)==NO && IsSectionEmpty(constraintPartition[k], w->partition, nLongsNeeded)==NO)
5979 //tmp = activeConstraints[j];
5980 activeConstraints[j]=activeConstraints[--activeConstraintsSize];
5981 //activeConstraints[activeConstraintsSize]=tmp;
5984 }/*end if NEGATIVE*/
5987 return activeConstraintsSize;
5991 /*--------------------------------------------------------------------
5993 | RandResolve: Randomly resolve a polytomous tree
5995 | @param tt is a tree which contains information about applicable constraints. If it is set to NULL then no constraints will be used.
5996 | If t!=NULL then partitions of nodes of polytree should be allocated for example by AllocatePolyTreePartitions (t);
5997 | @return NO_ERROR on succes, ABORT if could not resolve a tree without vialating some consraint, ERROR if any other error occur
5998 ---------------------------------------------------------------------*/
5999 int RandResolve (Tree *tt, PolyTree *t, RandLong *seed, int destinationIsRooted)
6001 int i, j, k, nextNode, stopNode, rand1, rand2, nTaxa, nLongsNeeded, tmp;
6002 PolyNode *p=NULL, *q, *r, *u, *w1, *w2;
6003 int nodeArrayAllowedSize, nodeArraySize, activeConstraintsSize;
6004 PolyNode **nodeArray;
6005 int *activeConstraints;
6007 assert (tt==NULL || t->bitsets!=NULL); /* partition fields of t nodes need to be allocated if constraints are used*/
6008 nTaxa = t->nNodes - t->nIntNodes; /* different from numLocalTaxa potentially if a species tree */
6009 assert (nTaxa <= t->memNodes/2); /* allocated tree has to be big enough*/
6010 nLongsNeeded = (nTaxa - 1) / nBitsInALong + 1; /* allocated lenght of partitions is t->memNodes/2 bits but only first nTaxa bits are used */
6012 nodeArray = t->allDownPass; /*temporary use t->allDownPass for different purpose. It get properly reset at the end. */
6013 activeConstraints = tempActiveConstraints;
6014 activeConstraintsSize = 0;
6016 /* collect constraints to consider if applicable*/
6017 if (tt!=NULL && tt->constraints!=NULL)
6019 for (k=0; k<numDefinedConstraints; k++)
6021 if (tt->constraints[k] == YES && definedConstraintsType[k] != HARD)
6022 activeConstraints[activeConstraintsSize++]=k;
6026 /* count immediate descendants */
6028 for (i=0; i<t->nIntNodes; i++)
6030 p = t->intDownPass[i];
6031 tmp=ViolatedConstraint(p->partition, activeConstraints, activeConstraintsSize, nLongsNeeded, t->isRooted);
6034 assert (p->isLocked == YES);
6035 MrBayesPrint ("%s Could not build a constraint tree since hard constraint \"%s\" and constraint \"%s\" are incompatible\n", spacer, constraintNames[p->lockID], constraintNames[activeConstraints[tmp]]);
6038 activeConstraintsSize = PruneActiveConstraints (p, activeConstraints, activeConstraintsSize, nLongsNeeded, t->isRooted);
6040 for (q=p->left; q!=NULL; q=q->sib)
6045 /* add one node at a time */
6046 if (destinationIsRooted == NO)
6047 stopNode = 2*nTaxa - 2;
6049 stopNode = 2*nTaxa - 1;
6050 for (nextNode=t->nNodes; nextNode < stopNode; nextNode++)
6052 /* find a polytomy to break */
6053 for (i=0; i<t->nIntNodes; i++)
6055 p = t->intDownPass[i];
6056 if (destinationIsRooted == YES && p->x > 2)
6058 if (destinationIsRooted == NO && ((p->anc != NULL && p->x > 2) || (p->anc == NULL && p->x > 3)))
6062 /* if we can't find one, there's an error */
6063 if (i == t->nIntNodes)
6069 /*Collect initial list of candidate nodes to join*/
6070 for (q = p->left; q!= NULL; q = q->sib)
6072 nodeArray[nodeArraySize++]=q;
6074 assert (nodeArraySize==p->x);
6076 /* identify two descendants randomly */
6077 /* make sure we do not select outgroup if it is an unrooted tree */
6078 if (p->anc == NULL && destinationIsRooted == NO)
6083 /* Pick first node */
6084 rand1 = (int) (RandomNumber(seed) * nodeArraySize);
6085 w1 = nodeArray[rand1];
6086 nodeArray[rand1] = nodeArray[--nodeArraySize];
6088 if (nodeArraySize==0)
6089 return ABORT; /* Potentaily here we could instead revert by removing last added node and try again. */
6091 /* Move all nodes in nodeArray which can be paired with w to the begining of array */
6092 nodeArrayAllowedSize=ConstraintAllowedSet(w1, nodeArray, nodeArraySize, activeConstraints, activeConstraintsSize, nLongsNeeded, t->isRooted);
6093 /* TODO optimization for Maxim (if not Maxim remove it if you still see it): if nodeArrayAllowedSize==0 then set w1->y */
6094 } while (nodeArrayAllowedSize == 0);
6096 rand2 = (int) (RandomNumber(seed) *nodeArrayAllowedSize);
6097 w2 = nodeArray[rand2];
6099 /* create a new node */
6100 u = &t->nodes[nextNode];
6106 for (j=0; j<nLongsNeeded; j++)
6107 u->partition[j] = w1->partition[j] | w2->partition[j] ;
6108 activeConstraintsSize = PruneActiveConstraints (u, activeConstraints, activeConstraintsSize, nLongsNeeded, t->isRooted);
6115 /* connect tree together */
6117 for (q = p->left; q!= NULL; q = q->sib)
6119 if (q != w1 && q != w2)
6133 GetPolyDownPass (t);
6136 /* relabel interior nodes (important that last indices are at the bottom!) */
6137 for (i=0; i<t->nIntNodes; i++)
6139 p = t->intDownPass[i];
6140 p->index = nTaxa + i;
6146 /* ResetTreeNode: Reset tree node except for memory index */
6147 void ResetTreeNode (TreeNode *p)
6149 /* do not change memoryIndex; that is set once and for all when tree is allocated */
6161 p->calibration = NULL;
6167 p->partition = NULL;
6171 /* ResetPolyNode: Reset all values of one node in a polytree */
6172 void ResetPolyNode (PolyNode *p)
6174 /* we reset everything here except memoryIndex, which should be immutable */
6178 p->anc = p->left = p->sib = NULL;
6179 p->calibration = NULL;
6184 strcpy (p->label,"");
6186 p->partition = NULL;
6187 p->partitionIndex = 0;
6193 /* ResetPolyTree: Reset polytomous tree to pristine state but keep relevant memory. */
6194 void ResetPolyTree (PolyTree *pt)
6196 int i, maxTaxa, nLongsNeeded;
6199 for (i=0; i<pt->memNodes; i++)
6200 ResetPolyNode (&pt->nodes[i]);
6202 /* empty node arrays and tree properties but keep space */
6203 for (i=0; i<pt->nNodes; i++)
6204 pt->allDownPass[i] = NULL;
6205 for (i=0; i<pt->nIntNodes; i++)
6206 pt->intDownPass[i] = NULL;
6214 pt->clockRate = 0.0;
6216 /* empty bitsets but keep space and pointers */
6219 maxTaxa = pt->memNodes / 2;
6220 nLongsNeeded = (maxTaxa - 1) / nBitsInALong + 1;
6221 for (i=0; i<pt->memNodes*nLongsNeeded; i++)
6223 for (i=0; i<pt->memNodes; i++)
6224 pt->nodes[i].partition = pt->bitsets + i*nLongsNeeded;
6227 /* empty relaxed clock parameters */
6228 FreePolyTreeRelClockParams (pt);
6230 /* empty population size set parameters */
6231 FreePolyTreePopSizeParams (pt);
6235 /* ResetPolyTreePartitions: Reset and set bit patterns describing partitions */
6236 void ResetPolyTreePartitions (PolyTree *pt)
6238 int i, j, numTaxa, nLongsNeeded;
6241 /* get some handy numbers */
6242 numTaxa = pt->memNodes/2;
6243 nLongsNeeded = (numTaxa - 1) / nBitsInALong + 1;
6245 /* reset bits describing partitions */
6246 for (i=0; i<pt->memNodes*nLongsNeeded; i++)
6251 /* set bits describing partitions */
6252 for (i=0; i<pt->nNodes; i++)
6254 assert (pt->allDownPass != NULL && pt->allDownPass[i] != NULL);
6255 assert (pt->allDownPass[i]->partition != NULL);
6257 pp = pt->allDownPass[i];
6258 if (pp->left == NULL)
6260 SetBit (pp->index, pp->partition);
6262 if (pp->anc != NULL)
6264 for (j=0; j<nLongsNeeded; j++)
6265 pp->anc->partition[j] |= pp->partition[j];
6271 /*----------------------------------------------
6273 | ResetRootHeight: Reset node heights in a clock
6274 | tree to fit a new root height. Assumes
6275 | node depths and lengths set correctly.
6277 -----------------------------------------------*/
6278 int ResetRootHeight (Tree *t, MrBFlt rootHeight)
6282 MrBFlt factor, x, y;
6284 if (t->isClock == NO)
6287 /* make sure node depths are set */
6288 for (i=0; i<t->nNodes-1; i++)
6290 p = t->allDownPass[i];
6291 if (p->left == NULL)
6295 x = p->left->nodeDepth + p->left->length;
6296 y = p->right->nodeDepth + p->right->length;
6303 for (i=t->nNodes-3; i>=0; i--)
6305 p = t->allDownPass[i];
6306 p->nodeDepth = p->anc->nodeDepth - p->length;
6309 /* now reset node depths and branch lengths */
6310 factor = rootHeight / t->root->left->nodeDepth;
6311 t->root->left->nodeDepth = rootHeight;
6312 for (i=t->nNodes-2; i>=0; i--)
6314 p = t->allDownPass[i];
6315 p->nodeDepth *= factor;
6316 p->length *= factor;
6323 /*----------------------------------------------
6325 | ResetTipIndices: reset tip indices to be from
6326 | 0 to number of included taxa, in same order
6327 | as in the original taxon set.
6329 -----------------------------------------------*/
6330 void ResetTipIndices(PolyTree *pt)
6335 for (i=j=0; i<numTaxa; i++)
6337 for (k=0; k<pt->nNodes; k++)
6339 p = pt->allDownPass[k];
6340 if (StrCmpCaseInsensitive(p->label,taxaNames[i]) == 0)
6345 assert (p->left == NULL);
6347 SwapRelaxedBranchInfo (p->index, j, pt);
6348 for (m=0; m<pt->nNodes; m++)
6350 if (pt->allDownPass[m]->index==j)
6352 pt->allDownPass[m]->index=p->index;
6364 /*----------------------------------------------
6366 | ResetTopology: rebuild the tree t to fit the
6367 | Newick string s. Everyting except topology
6368 | is left in the same state in t.
6370 -----------------------------------------------*/
6371 int ResetTopology (Tree *t, char *s)
6374 int i, j, k, inLength;
6377 /* set all pointers to NULL */
6378 for (i=0; i<t->memNodes; i++)
6381 p->anc = p->right = p->left = NULL;
6386 /* start out assuming that the tree is rooted; we will detect below if it is not */
6389 for (i=0, j=1; *s!='\0'; s++)
6391 if (*s == ',' || *s == ')' || *s == ':')
6393 if (p->right == NULL && inLength == NO)
6412 if (p->anc->right == NULL)
6419 else /* if p->anc->right == p (near 'root' of unrooted trees) */
6436 else if (inLength == NO)
6442 /* attach root to rooted tree */
6443 if (t->isRooted == YES)
6451 /* relabel interior nodes, find number of nodes and root */
6453 t->nIntNodes = t->nNodes/2 - 1;
6455 if (t->isRooted == NO)
6456 j = t->nNodes - t->nIntNodes;
6458 j = t->nNodes - t->nIntNodes - 1;
6460 for (i=0; i<t->nNodes; i++)
6475 /*-----------------------------------------------------------------
6477 | ResetBrlensFromTree: copies brlens and depths from second tree (vTree) to
6478 | first tree (used to initialize brlen sets for same topology)
6480 -----------------------------------------------------------------*/
6481 int ResetBrlensFromTree (Tree *tree, Tree *vTree)
6483 int i, j, k, nLongsNeeded, numTips;
6487 if (tree->isRooted != vTree->isRooted)
6490 if (AreTopologiesSame (tree, vTree) == NO)
6493 /* allocate and set up partitions */
6494 AllocateTreePartitions (vTree);
6495 AllocateTreePartitions (tree);
6496 numTips = tree->nNodes - tree->nIntNodes - (tree->isRooted == YES ? 1 : 0);
6497 nLongsNeeded = (int) ((numTips - 1) / nBitsInALong) + 1;
6499 /*copy lengths and nodeDepthes*/
6500 for (i=0; i<vTree->nNodes; i++)
6502 p = vTree->allDownPass[i];
6503 for (j=0; j<tree->nNodes; j++)
6505 q = tree->allDownPass[j];
6506 for (k=0; k<nLongsNeeded; k++)
6507 if (p->partition[k] != q->partition[k])
6509 if (k==nLongsNeeded)
6511 q->length = p->length;
6512 if (tree->isRooted == YES)
6513 q->nodeDepth = p->nodeDepth;
6518 if (tree->isRooted == YES)
6520 /*Next compute height for the root. */
6521 for (i=0; i<tree->nNodes-1; i++)
6523 p = tree->allDownPass[i];
6524 if (p->left == NULL)
6528 d1 = p->left->nodeDepth + p->left->length;
6529 d2 = p->right->nodeDepth + p->right->length;
6536 for (i=tree->nNodes-3; i>=0; i--)
6538 p = tree->allDownPass[i];
6539 if (p->left==NULL && p->calibration==NULL)
6540 continue; /* leave at 0.0 */
6541 p->nodeDepth = p->anc->nodeDepth - p->length;
6545 FreeTreePartitions(tree);
6546 FreeTreePartitions(vTree);
6552 /* ResetIntNodeIndices: Set int node indices in downpass order from numTaxa to 2*numTaxa-2 */
6553 void ResetIntNodeIndices (PolyTree *t)
6557 index = t->nNodes - t->nIntNodes;
6559 for (i=0; i<t->nIntNodes; i++)
6561 if (t->intDownPass[i]->index != index)
6563 SwapRelaxedBranchInfo (t->intDownPass[i]->index, index, t);
6564 for (m=0; m<t->nIntNodes; m++)
6566 if (t->intDownPass[m]->index==index)
6568 t->intDownPass[m]->index=t->intDownPass[i]->index;
6572 t->intDownPass[i]->index = index;
6579 /* ResetTopologyFromTree: use top to set topology in tree */
6580 int ResetTopologyFromTree (Tree *tree, Tree *top)
6583 TreeNode *p, *q, *r, *p1;
6586 tree->isRooted = top->isRooted;
6587 tree->nNodes = top->nNodes;
6588 tree->nIntNodes = top->nIntNodes;
6590 /* set all pointers to NULL */
6591 for (i=0; i<tree->nNodes; i++)
6593 p = &tree->nodes[i];
6594 p->anc = p->right = p->left = NULL;
6597 /* now copy topology */
6598 for (i=0; i<top->nIntNodes; i++)
6600 p1 = top->intDownPass[i];
6603 for (j=0; j<tree->nNodes; j++)
6604 if (tree->nodes[j].index == k)
6606 p = &tree->nodes[j];
6608 k = p1->left->index;
6609 for (j=0; j<tree->nNodes; j++)
6610 if (tree->nodes[j].index == k)
6612 q = &tree->nodes[j];
6614 k = p1->right->index;
6615 for (j=0; j<tree->nNodes; j++)
6616 if (tree->nodes[j].index == k)
6618 r = &tree->nodes[j];
6622 q->anc = r->anc = p;
6625 /* arrange the root */
6626 k = top->root->index;
6627 for (j=0; j<tree->nNodes; j++)
6628 if (tree->nodes[j].index == k)
6630 p = &tree->nodes[j];
6632 k = top->root->left->index;
6633 for (j=0; j<tree->nNodes; j++)
6634 if (tree->nodes[j].index == k)
6636 q = &tree->nodes[j];
6639 p->right = p->anc = NULL;
6648 /* ResetTopologyFromPolyTree: use polytree top to set topology in tree */
6649 int ResetTopologyFromPolyTree (Tree *tree, PolyTree *top)
6652 TreeNode *p, *q, *r;
6655 if (tree->isRooted != top->isRooted)
6658 /* set all pointers to NULL */
6659 for (i=0; i<tree->nNodes; i++)
6661 p = &tree->nodes[i];
6662 p->anc = p->right = p->left = NULL;
6665 /* now copy topology */
6666 for (i=0; i<top->nIntNodes; i++)
6668 p1 = top->intDownPass[i];
6671 for (j=0; j<tree->nNodes; j++)
6672 if (tree->nodes[j].index == k)
6674 p = &tree->nodes[j];
6676 k = p1->left->index;
6677 for (j=0; j<tree->nNodes; j++)
6678 if (tree->nodes[j].index == k)
6680 q = &tree->nodes[j];
6682 k = p1->left->sib->index;
6683 for (j=0; j<tree->nNodes; j++)
6684 if (tree->nodes[j].index == k)
6686 r = &tree->nodes[j];
6690 q->anc = r->anc = p;
6693 /* arrange the root */
6694 if (top->isRooted == YES)
6696 k = top->root->index;
6697 for (j=0; j<tree->nNodes; j++)
6698 if (tree->nodes[j].index == k)
6700 p = &tree->nodes[j];
6703 for (j=0; j<tree->nNodes; j++)
6704 if (tree->nodes[j].index == k)
6706 q = &tree->nodes[j];
6713 else /* if (top->isRooted == NO) */
6715 k = top->root->index;
6716 for (j=0; j<tree->nNodes; j++)
6717 if (tree->nodes[j].index == k)
6719 p = &tree->nodes[j];
6722 for (p1=top->root->left; p1!=NULL; p1=p1->sib)
6726 assert (p1 != NULL);
6730 q = &tree->nodes[p1->index];
6731 k = p1->anc->left->sib->sib->index; /* index of missing child */
6733 p->left = &tree->nodes[k];
6734 else if (p->right == q)
6735 p->right = &tree->nodes[k];
6737 q->anc = q->right = NULL;
6748 /* ResetTreePartitions: Reset bitsets describing tree partitions */
6749 void ResetTreePartitions (Tree *t)
6751 int i, j, numTaxa, nLongsNeeded;
6754 /* get some handy numbers */
6755 numTaxa = t->nNodes - t->nIntNodes - (t->isRooted == YES ? 1 : 0);
6756 nLongsNeeded = (numTaxa - 1) / nBitsInALong + 1;
6758 /* reset bits describing partitions */
6759 for (i=0; i<t->nNodes; i++)
6761 assert (t->allDownPass != NULL && t->allDownPass[i] != NULL);
6762 assert (t->allDownPass[i]->partition != NULL);
6764 p = t->allDownPass[i];
6765 for (j=0; j<nLongsNeeded; j++)
6766 p->partition[j] = 0;
6769 /* set bits describing partitions */
6770 for (i=0; i<t->nNodes; i++)
6772 p = t->allDownPass[i];
6773 if (p->left == NULL || (p->anc == NULL && t->isRooted == NO))
6774 SetBit (p->index, p->partition);
6775 else if (p->anc != NULL)
6777 for (j=0; j<nLongsNeeded; j++)
6778 p->partition[j] = p->left->partition[j] | p->right->partition[j];
6784 /*-------------------------------------------------------
6786 | RetrieveRTopology: This routine will rebuild a rooted
6787 | tree from the order array created by StoreRTopology.
6788 | All tree information except the structure will
6791 --------------------------------------------------------*/
6792 int RetrieveRTopology (Tree *t, int *order)
6795 TreeNode *p, *q, *r;
6797 numTaxa = t->nNodes - t->nIntNodes - 1;
6799 /* sort the tips in the t->allDownPass array */
6801 for (i=0; i<t->nNodes; i++, p++)
6802 t->allDownPass[p->index] = p;
6804 /* make sure the root has index 2*numTaxa-1 */
6805 q = t->allDownPass[t->nNodes-1];
6806 q->anc = q->right = NULL;
6809 /* connect the first two tips */
6810 p = t->allDownPass[numTaxa];
6814 q = t->allDownPass[0];
6815 r = t->allDownPass[1];
6818 q->anc = r->anc = p;
6820 /* add one tip at a time */
6821 for (i=2; i<numTaxa; i++)
6823 p = t->allDownPass[i];
6824 q = t->allDownPass[numTaxa-1+i];
6825 r = t->allDownPass[*(order++)];
6830 if (r->anc->left == r)
6840 /* relabel interior nodes (root is correctly labeled already) */
6841 for (i=0; i<t->nIntNodes; i++)
6842 t->intDownPass[i]->index = i+numTaxa;
6848 /*-------------------------------------------------------
6850 | RetrieveRTree: This routine will rebuild a rooted
6851 | tree from the arrays created by StoreRTree.
6852 | All tree information except the structure and
6853 | branch lengths will remain unaltered.
6855 --------------------------------------------------------*/
6856 int RetrieveRTree (Tree *t, int *order, MrBFlt *brlens)
6859 TreeNode *p, *q, *r;
6861 numTaxa = t->nNodes - t->nIntNodes - 1;
6863 /* sort the tips in the t->allDownPass array */
6865 for (i=0; i<t->nNodes; i++, p++)
6866 t->allDownPass[p->index] = p;
6868 /* make sure that root has index 2*numTaxa-1 */
6869 q = t->allDownPass[t->nNodes-1];
6870 q->anc = q->right = NULL;
6874 /* connect the first three tips */
6875 p = t->allDownPass[numTaxa];
6879 q = t->allDownPass[0];
6880 r = t->allDownPass[1];
6883 q->anc = r->anc = p;
6884 q->length = *(brlens++);
6885 r->length = *(brlens++);
6887 /* add one tip at a time */
6888 for (i=2; i<numTaxa; i++)
6890 p = t->allDownPass[i];
6891 q = t->allDownPass[numTaxa-1+i];
6892 r = t->allDownPass[*(order++)];
6897 if (r->anc->left == r)
6902 if (q->anc->anc != NULL)
6903 q->length = *(brlens++);
6906 r->length = *(brlens++);
6909 p->length = *(brlens++);
6915 /* relabel interior nodes (root is correctly labeled already) */
6916 for (i=0; i<t->nIntNodes; i++)
6917 t->intDownPass[i]->index = i+numTaxa;
6919 /* set the node depths */
6926 /*-------------------------------------------------------
6928 | RetrieveRTreeWithIndices: This routine will rebuild a rooted
6929 | tree from the arrays created by StoreRTreeWithIndices.
6930 | All tree information except the structure, branch lengths
6931 | and node indices will remain unaltered.
6933 --------------------------------------------------------*/
6934 int RetrieveRTreeWithIndices (Tree *t, int *order, MrBFlt *brlens)
6937 TreeNode *p, *q, *r;
6939 extern void ShowNodes (TreeNode *, int, int);
6941 numTaxa = t->nNodes - t->nIntNodes - 1;
6943 /* sort the tips in the t->allDownPass array */
6945 for (i=0; i<t->nNodes; i++, p++)
6946 t->allDownPass[p->index] = p;
6948 /* make sure that root has index 2*numTaxa-1 */
6949 q = t->allDownPass[t->nNodes-1];
6950 q->anc = q->right = NULL;
6954 /* connect the first three 'tips' with interior node, index from order array */
6955 p = t->allDownPass[numTaxa];
6960 q = t->allDownPass[0];
6961 r = t->allDownPass[1];
6964 q->anc = r->anc = p;
6965 q->length = *(brlens++);
6966 r->length = *(brlens++);
6968 /* add one tip at a time */
6969 for (i=2; i<numTaxa; i++)
6971 p = t->allDownPass[i];
6972 assert (*order >= numTaxa && *order < 2*numTaxa - 1);
6973 q = t->allDownPass[numTaxa-1+i];
6975 r = t->allDownPass[*(order++)];
6980 if (r->anc->left == r)
6985 if (q->anc->anc != NULL)
6986 q->length = *(brlens++);
6989 r->length = *(brlens++);
6992 p->length = *(brlens++);
6998 /* relabel interior nodes using labels in scratch variable x */
6999 for (i=0; i<t->nIntNodes; i++)
7001 p = t->intDownPass[i];
7005 /* set the node depths */
7012 /*-------------------------------------------------------
7014 | RetrieveUTopology: This routine will rebuild an unrooted
7015 | tree from the order array created by StoreUTopology.
7016 | All tree information except the structure
7017 | will remain unaltered.
7019 --------------------------------------------------------*/
7020 int RetrieveUTopology (Tree *t, int *order)
7023 TreeNode *p, *q, *r;
7026 numTips = t->nNodes - t->nIntNodes;
7027 for (i=0; i<t->nNodes; i++)
7028 t->nodes[i].left = t->nodes[i].right = t->nodes[i].anc = NULL;
7030 /* sort the tips in the t->allDownPass array */
7032 for (i=0; i<t->nNodes; i++, p++)
7033 t->allDownPass[p->index] = p;
7035 /* make sure root has index 0 */
7036 q = t->allDownPass[0];
7037 q->anc = q->right = NULL;
7040 /* connect the first three tips */
7041 p = t->allDownPass[numTips];
7044 q = t->allDownPass[1];
7045 r = t->allDownPass[2];
7048 q->anc = r->anc = p;
7050 /* add one tip at a time */
7051 for (i=3; i<numTips; i++)
7053 p = t->allDownPass[i];
7054 q = t->allDownPass[numTips-2+i];
7055 r = t->allDownPass[order[i-3]];
7060 if (r->anc->left == r)
7070 /* relabel interior nodes (root is correctly labeled already) */
7071 for (i=0; i<t->nIntNodes; i++)
7072 t->intDownPass[i]->index = i+numTips;
7078 /*-------------------------------------------------------
7080 | RetrieveUTree: This routine will rebuild an unrooted
7081 | tree from the arrays created by StoreUTree.
7082 | All tree information except the structure and
7083 | branch lengths will remain unaltered.
7085 --------------------------------------------------------*/
7086 int RetrieveUTree (Tree *t, int *order, MrBFlt *brlens)
7089 TreeNode *p, *q, *r;
7092 numTips = t->nNodes - t->nIntNodes;
7093 for (i=0; i<t->nNodes; i++)
7094 t->nodes[i].left = t->nodes[i].right = t->nodes[i].anc = NULL;
7096 /* sort the tips in the t->allDownPass array */
7098 for (i=0; i<t->nNodes; i++, p++)
7099 t->allDownPass[p->index] = p;
7101 /* make sure that root has index 0 */
7102 q = t->allDownPass[0];
7103 q->anc = q->right = NULL;
7106 /* connect the first three tips */
7107 p = t->allDownPass[numTips];
7110 p->length = *(brlens++);
7111 q = t->allDownPass[1];
7112 r = t->allDownPass[2];
7115 q->anc = r->anc = p;
7116 q->length = *(brlens++);
7117 r->length = *(brlens++);
7119 /* add one tip at a time */
7120 for (i=3; i<numTips; i++)
7122 p = t->allDownPass[i];
7123 q = t->allDownPass[numTips-2+i];
7124 r = t->allDownPass[order[i-3]];
7129 if (r->anc->left == r)
7134 q->length = *(brlens++);
7135 p->length = *(brlens++);
7141 /* relabel interior nodes (root is correctly labeled already) */
7142 for (i=0; i<t->nIntNodes; i++)
7143 t->intDownPass[i]->index = i+numTips;
7149 void SetDatedNodeAges (Param *param, int chain, int state)
7157 extern void ShowNodes(TreeNode *,int,int);
7159 t = GetTree (param, chain, state);
7160 m = &modelSettings[t->relParts[0]];
7162 if (m->clockRate == NULL)
7165 clockRate = *GetParamVals(m->clockRate, chain, state);
7167 for (i=0; i<t->nNodes-1; i++)
7169 p = t->allDownPass[i];
7170 if (p->isDated == YES)
7171 p->age = p->nodeDepth / clockRate;
7178 void SetNodeDepths (Tree *t)
7184 extern void ShowNodes(TreeNode *,int,int);
7186 for (i=0; i<t->nNodes-1; i++)
7188 p = t->allDownPass[i];
7189 if (p->left == NULL)
7193 d1 = p->left->nodeDepth + p->left->length;
7194 d2 = p->right->nodeDepth + p->right->length;
7195 //assert (!(t->isCalibrated == NO && AreDoublesEqual(d1,d2,0.00001)==NO)); // may not work if we set startval topology of strict clock tree by non clock tree.
7203 for (i=t->nNodes-3; i>=0; i--)
7205 p = t->allDownPass[i];
7206 if (p->left == NULL && p->calibration == NULL)
7209 p->nodeDepth = p->anc->nodeDepth - p->length;
7214 /* Set ages of a clock tree according to depth and clockrate. Check that resulting ages are consistant with calibration.
7215 | return YES if tree is age consistent, No otherwise.
7217 int SetTreeNodeAges (Param *param, int chain, int state)
7224 if (param->paramType != P_TOPOLOGY && param->paramType != P_BRLENS && param->paramType != P_SPECIESTREE)
7227 tree = GetTree(param, chain, state);
7228 if (modelSettings[param->relParts[0]].clockRate != NULL)
7229 clockRate = *GetParamVals(modelSettings[param->relParts[0]].clockRate, chain, state);
7235 /* Check that lengths and depths are consistant. That would work for the case when we set up branch length from starting tree */
7236 for (i=0; i<tree->nNodes-1; i++) {
7237 p = tree->allDownPass[i];
7238 p->age = p->nodeDepth / clockRate;
7241 /* Check that ages and calibrations are consistent */
7242 if (tree->isCalibrated == YES)
7244 for (i=0; i<tree->nNodes-1; i++)
7246 p = tree->allDownPass[i];
7247 if (p->isDated == YES) {
7248 if (p->calibration->prior == fixed && fabs((p->age - p->calibration->priorParams[0])/p->age) > 0.000001)
7250 printf ("Node %d has age %f but should be fixed to age %f\n",
7251 p->index, p->age, p->calibration->priorParams[0]);
7254 else if (p->calibration->prior == uniform && (p->age < p->calibration->min || p->age > p->calibration->max))
7256 printf ("Node %d has age %f but should be in the interval [%f,%f]\n",
7257 p->index, p->age, p->calibration->min, p->calibration->max);
7260 else if (p->age < p->calibration->min)
7262 printf ("Node %d has age %f but should be minimally of age %f\n",
7263 p->index, p->age, p->calibration->min);
7266 else if (p->age > p->calibration->max)
7268 printf ("Node %d has age %f but should be maximally of age %f\n",
7269 p->index, p->age, p->calibration->max);
7280 int ShowPolyNodes (PolyTree *pt)
7285 /* this is the tree, on a node-by-node basis */
7286 printf (" memnodes = %d nNodes = %d nIntNodes = %d root = %d\n", pt->memNodes, pt->nNodes, pt->nIntNodes, pt->root->index);
7287 printf (" isRooted = %d\n", pt->isRooted);
7288 printf (" no. index (left sib anc) -- locked/free -- label (p->x)\n");
7289 for (i=0; i<pt->memNodes; i++)
7292 if (!(p->left == NULL && p->sib == NULL && p->anc == NULL))
7294 printf ("%4d -- %4d ", i, p->index);
7295 if (p->left != NULL)
7296 printf ("(%4d ", p->left->index);
7301 printf ("%4d ", p->sib->index);
7306 printf ("%4d)", p->anc->index);
7310 if (p->isLocked == YES)
7311 printf ("-- locked -- ");
7313 printf ("-- free --");
7315 if (p->left == NULL && p->anc != NULL)
7316 printf (" \"%s\" (%d)\n", p->label, p->x);
7318 printf (" \"\" (%d)\n", p->x);
7326 /* ShowTree: Show tree on screen */
7327 int ShowTree (Tree *t)
7329 int i, j, k, x, nLines, nLevels, levelDepth, from, to;
7330 char treeLine[SCREENWIDTH2], labelLine[100];
7333 /* get coordinates */
7336 for (i=0; i<t->nNodes; i++)
7338 p = t->allDownPass[i];
7339 if (p->left == NULL && p->right == NULL)
7346 else if (p->left != NULL && p->right != NULL && p->anc != NULL)
7348 p->x = p->left->x + (p->right->x - p->left->x) / 2;
7349 if (p->left->y > p->right->y)
7350 p->y = p->left->y + 1;
7352 p->y = p->right->y + 1;
7362 /* print tree out, line-by-line */
7363 levelDepth = SCREENWIDTH / t->root->left->y;
7364 nLevels = t->root->left->y;
7365 for (j=0; j<=nLines-2; j++)
7367 for (i=0; i<SCREENWIDTH2-2; i++)
7369 treeLine[SCREENWIDTH-1] = '\n';
7372 for (i=0; i<t->nNodes; i++)
7374 p = t->allDownPass[i];
7375 if (p->left == NULL && p->x == j)
7377 strcpy (labelLine, p->label);
7381 for (i=0; i<t->nNodes; i++)
7383 p = t->allDownPass[i];
7386 if (p->anc->anc != NULL)
7390 from = (nLevels - p->anc->y) * levelDepth;
7391 to = (nLevels - p->y) * levelDepth;
7394 if (to >= SCREENWIDTH)
7397 for (k=from; k<to; k++)
7399 if (p->anc->left == p)
7400 treeLine[from] = '/';
7402 treeLine[from] = '\\';
7403 if (p->left != NULL)
7407 if (p->anc->anc == t->root && p->anc->right == p)
7409 if (t->isRooted == NO)
7412 treeLine[from] = '\\';
7417 if (p->left != NULL && p->right != NULL)
7419 if (j < p->x && j > p->left->x)
7421 from = (nLevels - p->y) * levelDepth;
7422 treeLine[from] = '|';
7424 else if (j > p->x && j < p->right->x && p->left != NULL)
7426 from = (nLevels - p->y) * levelDepth;
7427 treeLine[from] = '|';
7436 treeLine[0] = '|'; /* temp */
7438 else if (j < p->x && j > p->left->x)
7442 else if (j > p->x && j < p->right->x)
7446 if (t->isRooted == NO)
7448 if (j > p->x && j <= nLines-2)
7450 if (j == p->right->x)
7461 treeLine[SCREENWIDTH-1] = '\0';
7463 MrBayesPrint (" %s %s\n", treeLine, labelLine);
7465 MrBayesPrint (" %s \n", treeLine);
7468 if (t->isRooted == NO)
7470 for (i=0; i<SCREENWIDTH; i++)
7472 treeLine[SCREENWIDTH-1] = '\0';
7473 MrBayesPrint (" |\n");
7474 for (k=0; k<SCREENWIDTH; k++)
7476 treeLine[SCREENWIDTH-1] = '\0';
7478 strcpy (labelLine, t->root->label);
7479 labelLine[19] = '\0';
7480 MrBayesPrint (" %s %s\n", treeLine, labelLine);
7483 # if defined (DEBUG_CONSTRAINTS)
7484 for (i=0; i<t->nNodes; i++)
7485 printf ("%d -- %s\n", t->allDownPass[i]->index + 1, t->allDownPass[i]->isLocked == YES ? "locked" : "free");
7492 /*-------------------------------------------------------
7494 | StoreRPolyTopology: Same as StoreRTopology but for
7495 | binary polytree source trees.
7497 --------------------------------------------------------*/
7498 int StoreRPolyTopology (PolyTree *t, int *order)
7503 /* find number of taxa */
7504 numTaxa = t->nNodes - t->nIntNodes;
7506 /* first get the terminal taxon positions and store
7507 them in the order array. */
7508 for (i=0; i<t->nNodes; i++)
7510 p = t->allDownPass[i];
7511 /* we do not need to worry about the first two taxa */
7512 if (p->index > 1 && p->index < numTaxa)
7513 order[p->index-2] = i;
7516 /* label the interior nodes with the correct index */
7517 for (i=0; i<t->nNodes; i++)
7519 p = t->allDownPass[i];
7520 if (p->left == NULL)
7521 p->x = p->y = p->index;
7524 if (p->left->y < p->left->sib->y)
7527 p->x = p->left->sib->y + numTaxa - 1;
7531 p->y = p->left->sib->y;
7532 p->x = p->left->y + numTaxa - 1;
7537 /* break the tree into pieces */
7538 for (i=0; i<numTaxa-2; i++)
7540 /* find the next node to remove */
7541 p = t->allDownPass[order[numTaxa-3-i]];
7545 order[numTaxa-3-i] = q->left->sib->x;
7546 p->sib->anc = q->anc;
7549 p->sib->left->sib->sib = p->sib->sib;
7552 else if (q->anc->left == q)
7554 q->anc->left = q->left->sib;
7555 p->sib->sib = q->sib;
7558 q->anc->left->sib = q->left->sib;
7562 order[numTaxa-3-i] = q->left->x;
7563 q->left->anc = q->anc;
7566 q->left->left->sib->sib = p->sib;
7567 q->left->sib = NULL;
7569 else if (q->anc->left == q)
7571 q->anc->left = q->left;
7572 q->anc->left->sib = q->sib;
7576 q->anc->left->sib = q->left;
7577 q->left->sib = NULL;
7586 /*-------------------------------------------------------
7588 | StoreRPolyTree: Same as StoreRTree but for
7589 | binary rooted polytree source trees.
7591 --------------------------------------------------------*/
7592 int StoreRPolyTree (PolyTree *t, int *order, MrBFlt *brlens)
7597 /* find number of taxa */
7598 numTaxa = t->nNodes - t->nIntNodes;
7600 /* first get the terminal taxon positions and store
7601 them in the order array. */
7602 for (i=0; i<t->nNodes; i++)
7604 p = t->allDownPass[i];
7605 /* we do not need to worry about the first two taxa */
7606 if (p->index > 1 && p->index < numTaxa)
7607 order[p->index-2] = i;
7610 /* label the interior nodes with the correct index */
7611 for (i=0; i<t->nNodes; i++)
7613 p = t->allDownPass[i];
7614 if (p->left == NULL)
7615 p->x = p->y = p->index;
7618 if (p->left->y < p->left->sib->y)
7621 p->x = p->left->sib->y + numTaxa - 1;
7625 p->y = p->left->sib->y;
7626 p->x = p->left->y + numTaxa - 1;
7631 /* break the tree into pieces */
7632 j = t->nNodes - 2; /* index of first branch length */
7633 for (i=0; i<numTaxa-2; i++)
7635 /* find the next node to remove */
7636 p = t->allDownPass[order[numTaxa-3-i]];
7638 brlens[j--] = p->length;
7639 brlens[j--] = q->length;
7642 order[numTaxa-3-i] = q->left->sib->x;
7643 p->sib->anc = q->anc;
7646 p->sib->left->sib->sib = p->sib->sib;
7649 else if (q->anc->left == q)
7651 q->anc->left = q->left->sib;
7652 p->sib->sib = q->sib;
7655 q->anc->left->sib = q->left->sib;
7659 order[numTaxa-3-i] = q->left->x;
7660 q->left->anc = q->anc;
7663 q->left->left->sib->sib = p->sib;
7664 q->left->sib = NULL;
7666 else if (q->anc->left == q)
7668 q->anc->left = q->left;
7669 q->anc->left->sib = q->sib;
7673 q->anc->left->sib = q->left;
7674 q->left->sib = NULL;
7679 /* store the last two lengths; index 0 and 1 */
7681 brlens[p->left->index] = p->left->length;
7682 brlens[p->left->sib->index] = p->left->sib->length;
7688 /*-------------------------------------------------------
7690 | StoreRTopology: This routine will break a rooted tree
7691 | into an array of ints describing the structure
7692 | of the tree. The tree will be destroyed
7693 | in the process (the node pointers, that is).
7694 | However, the tree is not deleted.
7696 --------------------------------------------------------*/
7697 int StoreRTopology (Tree *t, int *order)
7702 /* find number of taxa */
7703 numTaxa = t->nNodes - t->nIntNodes - 1;
7705 /* first get the terminal taxon positions and store
7706 them in the order array. */
7707 for (i=0; i<t->nNodes; i++)
7709 p = t->allDownPass[i];
7710 /* we do not need to worry about the first two taxa */
7711 if (p->index > 1 && p->index < numTaxa)
7712 order[p->index-2] = i;
7715 /* label the interior nodes with the correct index */
7716 for (i=0; i<t->nNodes; i++)
7718 p = t->allDownPass[i];
7719 if (p->left == NULL)
7720 p->x = p->y = p->index;
7721 else if (p->right != NULL)
7723 if (p->left->y < p->right->y)
7726 p->x = p->right->y + numTaxa - 1;
7731 p->x = p->left->y + numTaxa - 1;
7736 /* break the tree into pieces */
7737 for (i=0; i<numTaxa-2; i++)
7739 /* find the next node to remove */
7740 p = t->allDownPass[order[numTaxa-3-i]];
7744 order[numTaxa-3-i] = q->right->x;
7745 q->right->anc = q->anc;
7746 if (q->anc->left == q)
7747 q->anc->left = q->right;
7749 q->anc->right = q->right;
7753 order[numTaxa-3-i] = q->left->x;
7754 q->left->anc = q->anc;
7755 if (q->anc->left == q)
7756 q->anc->left = q->left;
7758 q->anc->right = q->left;
7766 /*-------------------------------------------------------
7768 | StoreRTree: This routine will break a rooted tree
7769 | into an array of ints describing the structure
7770 | of the tree and an array of doubles storing
7771 | the branch lengths. The tree will be
7772 | destroyed in the process (the node pointers,
7773 | that is). However, the tree is not deleted.
7775 --------------------------------------------------------*/
7776 int StoreRTree (Tree *t, int *order, MrBFlt *brlens)
7781 extern void ShowNodes (TreeNode *p, int indent, int isRooted);
7783 /* find number of taxa */
7784 numTaxa = t->nNodes - t->nIntNodes - 1;
7786 /* first get the terminal taxon positions and store
7787 them in the order array. */
7788 for (i=0; i<t->nNodes; i++)
7790 p = t->allDownPass[i];
7791 /* we do not need to worry about the first two taxa */
7792 if (p->index > 1 && p->index < numTaxa)
7793 order[p->index-2] = i;
7796 /* label the interior nodes with the correct index */
7797 for (i=0; i<t->nNodes; i++)
7799 p = t->allDownPass[i];
7800 if (p->left == NULL)
7801 p->x = p->y = p->index;
7802 else if (p->right != NULL)
7804 if (p->left->y < p->right->y)
7807 p->x = p->right->y + numTaxa - 1;
7812 p->x = p->left->y + numTaxa - 1;
7817 /* break the tree into pieces */
7818 j = 2 * numTaxa - 3;
7819 for (i=0; i<numTaxa-2; i++)
7821 /* find the next node to remove */
7822 p = t->allDownPass[order[numTaxa-3-i]];
7824 brlens[j--] = p->length;
7827 if (q->anc->anc != NULL)
7828 brlens[j--] = q->length;
7830 brlens[j--] = q->right->length;
7831 order[numTaxa-3-i] = q->right->x;
7832 q->right->anc = q->anc;
7833 if (q->anc->left == q)
7834 q->anc->left = q->right;
7836 q->anc->right = q->right;
7840 if (q->anc->anc != NULL)
7841 brlens[j--] = q->length;
7843 brlens[j--] = q->left->length;
7844 order[numTaxa-3-i] = q->left->x;
7845 q->left->anc = q->anc;
7846 if (q->anc->left == q)
7847 q->anc->left = q->left;
7849 q->anc->right = q->left;
7853 /* store the final two branch lengths in the right order; they have indices 0 and 1 */
7855 brlens[p->left->index] = p->left->length;
7856 brlens[p->right->index] = p->right->length;
7862 /*-------------------------------------------------------
7864 | StoreRTreeWithIndices: This routine will break a rooted
7865 | tree into an array of ints describing the structure
7866 | of the tree and the interior node indices, and an array
7867 | of doubles storing the branch lengths. The tree will be
7868 | destroyed in the process (the node pointers,
7869 | that is). However, the tree is not deleted.
7871 --------------------------------------------------------*/
7872 int StoreRTreeWithIndices (Tree *t, int *order, MrBFlt *brlens)
7874 int i, j, k, numTaxa;
7877 extern void ShowNodes (TreeNode *p, int indent, int isRooted);
7879 /* find number of taxa */
7880 numTaxa = t->nNodes - t->nIntNodes - 1;
7882 /* first get the terminal taxon positions and store
7883 them in the order array. */
7884 for (i=0; i<t->nNodes; i++)
7886 p = t->allDownPass[i];
7887 /* we do not need to worry about the first two taxa */
7888 if (p->index > 1 && p->index < numTaxa)
7889 order[p->index-2] = i;
7892 /* label the interior nodes with the correct index */
7893 for (i=0; i<t->nNodes; i++)
7895 p = t->allDownPass[i];
7896 if (p->left == NULL)
7897 p->x = p->y = p->index;
7898 else if (p->right != NULL)
7900 if (p->left->y < p->right->y)
7903 p->x = p->right->y + numTaxa - 1;
7908 p->x = p->left->y + numTaxa - 1;
7913 /* break the tree into pieces */
7914 j = 2 * numTaxa - 3;
7915 k = 2*(numTaxa - 2);
7916 for (i=0; i<numTaxa-2; i++)
7918 /* find the next node to remove */
7919 p = t->allDownPass[order[numTaxa-3-i]];
7921 brlens[j--] = p->length;
7924 if (q->anc->anc != NULL)
7925 brlens[j--] = q->length;
7927 brlens[j--] = q->right->length;
7928 order[k--] = q->right->x;
7929 order[k--] = q->index;
7930 q->right->anc = q->anc;
7931 if (q->anc->left == q)
7932 q->anc->left = q->right;
7934 q->anc->right = q->right;
7938 if (q->anc->anc != NULL)
7939 brlens[j--] = q->length;
7941 brlens[j--] = q->left->length;
7942 order[k--] = q->left->x;
7943 order[k--] = q->index;
7944 q->left->anc = q->anc;
7945 if (q->anc->left == q)
7946 q->anc->left = q->left;
7948 q->anc->right = q->left;
7952 /* store the final two branch lengths in the right order; they have indices 0 and 1 */
7954 order[k] = p->index;
7955 brlens[p->left->index] = p->left->length;
7956 brlens[p->right->index] = p->right->length;
7962 /*-------------------------------------------------------
7964 | StoreUPolyTopology: Same as StoreUTopology but for
7965 | binary polytree source.
7967 --------------------------------------------------------*/
7968 int StoreUPolyTopology (PolyTree *t, int *order)
7973 /* check if the tree is rooted on taxon 0 */
7974 if (t->root->left->sib->sib->index != 0)
7975 MovePolyCalculationRoot (t, 0);
7977 /* rearrange the root */
7978 t->root->anc = t->root->left->sib->sib;
7979 t->root->left->sib->sib = NULL;
7980 t->root->anc->left = t->root;
7981 t->root->anc->sib = NULL;
7982 t->root->anc->anc = NULL;
7983 t->root = t->root->anc;
7985 /* find number of tips */
7986 numTips = t->nNodes - t->nIntNodes;
7988 /* first get the terminal taxon positions and store
7989 them in the order array. */
7990 for (i=0; i<t->nNodes; i++)
7992 p = t->allDownPass[i];
7993 /* we do not need to worry about the first three taxa */
7994 if (p->index > 2 && p->index < numTips)
7995 order[p->index-3] = i;
7998 /* label the interior nodes with the correct index */
7999 for (i=0; i<t->nNodes; i++)
8001 p = t->allDownPass[i];
8002 if (p->left == NULL || p->anc == NULL)
8003 p->x = p->y = p->index;
8006 if (p->left->y < p->left->sib->y)
8009 p->x = p->left->sib->y + numTips - 2;
8013 p->y = p->left->sib->y;
8014 p->x = p->left->y + numTips - 2;
8019 /* break the tree into pieces */
8020 for (i=0; i<numTips-3; i++)
8022 /* find the next node to remove */
8023 p = t->allDownPass[order[numTips-4-i]];
8027 order[numTips-4-i] = q->left->sib->x;
8028 p->sib->anc = q->anc;
8029 if (q->anc->left == q)
8031 q->anc->left = p->sib;
8032 p->sib->sib = q->sib;
8036 q->anc->left->sib = p->sib;
8037 p->sib->sib = q->sib;
8042 order[numTips-4-i] = q->left->x;
8043 q->left->anc = q->anc;
8044 if (q->anc->left == q)
8046 q->anc->left = q->left;
8047 q->left->sib = q->sib;
8051 q->anc->left->sib = q->left;
8052 q->left->sib = q->sib;
8061 /*-------------------------------------------------------
8063 | StoreUPolyTree: Same as StoreUTopology but for
8064 | binary polytree source.
8066 --------------------------------------------------------*/
8067 int StoreUPolyTree (PolyTree *t, int *order, MrBFlt *brlens)
8072 /* check if the tree is rooted on taxon 0 */
8073 if (t->root->left->sib->sib->index != 0)
8074 MovePolyCalculationRoot (t, 0);
8076 /* rearrange the root */
8077 t->root->anc = t->root->left->sib->sib;
8078 t->root->left->sib->sib = NULL;
8079 t->root->anc->left = t->root;
8080 t->root->anc->sib = NULL;
8081 t->root->anc->anc = NULL;
8082 t->root = t->root->anc;
8084 /* find number of tips */
8085 numTips = t->nNodes - t->nIntNodes;
8087 /* first get the terminal taxon positions and store
8088 them in the order array. */
8089 for (i=0; i<t->nNodes; i++)
8091 p = t->allDownPass[i];
8092 /* we do not need to worry about the first three taxa */
8093 if (p->index > 2 && p->index < numTips)
8094 order[p->index-3] = i;
8097 /* label the interior nodes with the correct index */
8098 for (i=0; i<t->nNodes; i++)
8100 p = t->allDownPass[i];
8101 if (p->left == NULL || p->anc == NULL)
8102 p->x = p->y = p->index;
8105 if (p->left->y < p->left->sib->y)
8108 p->x = p->left->sib->y + numTips - 2;
8112 p->y = p->left->sib->y;
8113 p->x = p->left->y + numTips - 2;
8118 /* break the tree into pieces */
8120 for (i=0; i<numTips-3; i++)
8122 /* find the next node to remove */
8123 p = t->allDownPass[order[numTips-4-i]];
8124 assert (p->index > 2 && p->index < numTips);
8125 assert (p->anc->anc != NULL);
8127 brlens[j--] = p->length;
8128 brlens[j--] = q->length;
8131 order[numTips-4-i] = q->left->sib->x;
8132 p->sib->anc = q->anc;
8133 if (q->anc->left == q)
8135 q->anc->left = p->sib;
8136 p->sib->sib = q->sib;
8140 q->anc->left->sib = p->sib;
8141 p->sib->sib = q->sib;
8146 order[numTips-4-i] = q->left->x;
8147 q->left->anc = q->anc;
8148 if (q->anc->left == q)
8150 q->anc->left = q->left;
8151 q->left->sib = q->sib;
8155 q->anc->left->sib = q->left;
8156 q->left->sib = q->sib;
8161 /* store last three branch lengths, index 0, 1, 2 */
8163 assert (q->index == 0);
8164 brlens[q->index] = q->length;
8166 assert (q->index == 1 || q->index == 2);
8167 brlens[q->index] = q->length;
8169 assert (q->index == 1 || q->index == 2);
8170 brlens[q->index] = q->length;
8176 /*-------------------------------------------------------
8178 | StoreUTopology: This routine will break an unrooted tree
8179 | into an array of ints describing the structure
8180 | of the tree. The tree will be destroyed
8181 | in the process (the node pointers, that is).
8182 | However, the tree is not deleted.
8184 --------------------------------------------------------*/
8185 int StoreUTopology (Tree *t, int *order)
8190 /* check if the tree is rooted on taxon 0 */
8191 if (t->root->index != 0)
8192 MoveCalculationRoot (t, 0);
8194 /* find number of tips */
8195 numTips = t->nNodes - t->nIntNodes;
8197 /* first get the terminal taxon positions and store
8198 them in the order array. */
8199 for (i=0; i<t->nNodes; i++)
8201 p = t->allDownPass[i];
8202 /* we do not need to worry about the first three taxa */
8203 if (p->index > 2 && p->index < numTips)
8204 order[p->index-3] = i;
8207 /* label the interior nodes with the correct index */
8208 for (i=0; i<t->nNodes; i++)
8210 p = t->allDownPass[i];
8211 if (p->left == NULL)
8212 p->x = p->y = p->index;
8213 else if (p->right != NULL)
8215 if (p->left->y < p->right->y)
8218 p->x = p->right->y + numTips - 2;
8223 p->x = p->left->y + numTips - 2;
8228 /* break the tree into pieces */
8229 for (i=0; i<numTips-3; i++)
8231 /* find the next node to remove */
8232 p = t->allDownPass[order[numTips-4-i]];
8236 order[numTips-4-i] = q->right->x;
8237 q->right->anc = q->anc;
8238 if (q->anc->left == q)
8239 q->anc->left = q->right;
8241 q->anc->right = q->right;
8245 order[numTips-4-i] = q->left->x;
8246 q->left->anc = q->anc;
8247 if (q->anc->left == q)
8248 q->anc->left = q->left;
8250 q->anc->right = q->left;
8258 /*-------------------------------------------------------
8260 | StoreUTree: This routine will break an unrooted tree
8261 | into an array of ints describing the structure
8262 | of the tree and an array of doubles storing
8263 | the branch lengths. The tree will be
8264 | destroyed in the process (the node pointers,
8265 | that is). However, the tree is not deleted.
8267 --------------------------------------------------------*/
8268 int StoreUTree (Tree *t, int *order, MrBFlt *brlens)
8273 /* check if the tree is rooted on taxon 0 */
8274 if (t->root->index != 0)
8275 MoveCalculationRoot(t, 0);
8277 /* find number of tips */
8278 numTips = t->nNodes - t->nIntNodes;
8280 /* first get the terminal taxon positions and store
8281 them in the order array. */
8282 for (i=0; i<t->nNodes; i++)
8284 p = t->allDownPass[i];
8285 /* we do not need to worry about the first three taxa */
8286 if (p->index > 2 && p->index < numTips)
8287 order[p->index-3] = i;
8290 /* label the interior nodes with the correct index */
8291 for (i=0; i<t->nNodes; i++)
8293 p = t->allDownPass[i];
8294 if (p->left == NULL)
8295 p->x = p->y = p->index;
8296 else if (p->right != NULL)
8298 if (p->left->y < p->right->y)
8301 p->x = p->right->y + numTips - 2;
8306 p->x = p->left->y + numTips - 2;
8311 /* break the tree into pieces */
8312 j = 2 * numTips - 4;
8313 for (i=0; i<numTips-3; i++)
8315 /* find the next node to remove */
8316 p = t->allDownPass[order[numTips-4-i]];
8318 brlens[j--] = p->length;
8319 brlens[j--] = q->length;
8322 order[numTips-4-i] = q->right->x;
8323 q->right->anc = q->anc;
8324 if (q->anc->left == q)
8325 q->anc->left = q->right;
8327 q->anc->right = q->right;
8331 order[numTips-4-i] = q->left->x;
8332 q->left->anc = q->anc;
8333 if (q->anc->left == q)
8334 q->anc->left = q->left;
8336 q->anc->right = q->left;
8340 /* store the final three branch lengths */
8341 /* we need to check the rotation of the tree to
8342 store the brlens in the right order (after node index) */
8344 if (p->right->index == 2)
8346 brlens[j--] = p->right->length;
8347 brlens[j--] = p->left->length;
8351 brlens[j--] = p->left->length;
8352 brlens[j--] = p->right->length;
8354 brlens[j--] = p->length;
8360 /* TreeLength: Calculate tree length */
8361 MrBFlt TreeLen (Tree *t)
8366 if (t->isRooted == NO)
8367 numLenNodes = t->nNodes - 1;
8369 numLenNodes = t->nNodes - 2;
8371 for (i=0; i<numLenNodes; i++)
8372 len += t->allDownPass[i]->length;
8378 /*-------------------------------------------------------------------------------------------
8380 | Unmark: This routine will unmark a subtree rooted at p
8382 ---------------------------------------------------------------------------------------------*/
8383 void Unmark (TreeNode *p)
8394 void WriteEventTree (TreeNode *p, int chain, Param *param)
8397 MrBFlt brlen, *position, *rateMult;
8401 if (p->left == NULL && p->right == NULL)
8403 printf ("%d:%s", p->index + 1, MbPrintNum(p->length));
8404 if (param->paramType == P_CPPEVENTS)
8406 nEvents = param->nEvents[2*chain+state[chain]][p->index];
8409 printf ("[&E %s %d: (", param->name, nEvents);
8410 position = param->position[2*chain+state[chain]][p->index];
8411 rateMult = param->rateMult[2*chain+state[chain]][p->index];
8412 for (j=0; j<nEvents; j++)
8414 printf ("%s %s", MbPrintNum(position[j]), MbPrintNum(rateMult[j]));
8421 printf ("[&E %s 0]", param->name);
8423 brlen = GetParamSubVals (param, chain, state[chain])[p->index];
8424 // brlen = (GetParamSubVals (param, chain, state[chain])[p->index] + GetParamVals (param, chain, state[chain])[p->anc->index]) / 2.0;
8425 printf ("[&B %s %s]", param->name, MbPrintNum(brlen));
8431 WriteEventTree(p->left, chain, param);
8433 WriteEventTree(p->right, chain, param);
8436 if (p->anc->anc != NULL)
8438 printf ("):%s", MbPrintNum(p->length));
8439 if (param->paramType == P_CPPEVENTS)
8441 nEvents = param->nEvents[2*chain+state[chain]][p->index];
8444 printf ("[&E %s %d: (", param->name, nEvents);
8445 position = param->position[2*chain+state[chain]][p->index];
8446 rateMult = param->rateMult[2*chain+state[chain]][p->index];
8447 for (j=0; j<nEvents; j++)
8449 printf ("%s %s", MbPrintNum(position[j]), MbPrintNum(rateMult[j]));
8456 printf ("[&E %s 0]", param->name);
8458 brlen = GetParamSubVals (param, chain, state[chain])[p->index];
8459 // brlen = (GetParamSubVals (param, chain, state[chain])[p->index] + GetParamVals (param, chain, state[chain])[p->anc->index]) / 2.0;
8460 printf ("[&B %s %s]", param->name, MbPrintNum(brlen));
8470 void WriteEventTreeToPrintString (TreeNode *p, int chain, Param *param, int printAll)
8473 int i, j, nEvents, tempStrSize = TEMPSTRSIZE;
8474 MrBFlt brlen, *position, *rateMult;
8476 tempStr = (char *) SafeMalloc((size_t)tempStrSize * sizeof(char));
8478 MrBayesPrint ("%s Problem allocating tempString (%d)\n", spacer, tempStrSize * sizeof(char));
8482 if (p->left == NULL && p->right == NULL)
8484 SafeSprintf (&tempStr, &tempStrSize, "%d:%s", p->index + 1, MbPrintNum(p->length));
8485 AddToPrintString (tempStr);
8486 for (i=0; i<param->nSubParams; i++)
8488 if (param->subParams[i]->paramType == P_CPPEVENTS)
8490 nEvents = param->subParams[i]->nEvents[2*chain+state[chain]][p->index];
8493 SafeSprintf (&tempStr, &tempStrSize, "[&E %s %d", param->subParams[i]->name, nEvents);
8494 AddToPrintString (tempStr);
8495 position = param->subParams[i]->position[2*chain+state[chain]][p->index];
8496 rateMult = param->subParams[i]->rateMult[2*chain+state[chain]][p->index];
8497 if (printAll == YES)
8499 SafeSprintf (&tempStr, &tempStrSize, ": (");
8500 AddToPrintString (tempStr);
8501 for (j=0; j<nEvents; j++)
8503 SafeSprintf (&tempStr, &tempStrSize, "%s", MbPrintNum(position[j]));
8504 AddToPrintString (tempStr);
8505 SafeSprintf (&tempStr, &tempStrSize, " %s", MbPrintNum(rateMult[j]));
8506 AddToPrintString (tempStr);
8508 AddToPrintString (",");
8510 AddToPrintString (")");
8513 AddToPrintString ("]");
8517 SafeSprintf (&tempStr, &tempStrSize, "[&E %s 0]", param->subParams[i]->name);
8518 AddToPrintString (tempStr);
8521 else if (param->subParams[i]->paramType != P_CPPEVENTS)
8523 /* other relaxed clock models */
8524 brlen = GetParamSubVals (param->subParams[i], chain, state[chain])[p->index];
8525 SafeSprintf (&tempStr, &tempStrSize, "[&B %s %s]", param->subParams[i]->name, MbPrintNum(brlen));
8526 AddToPrintString (tempStr);
8533 AddToPrintString ("(");
8534 WriteEventTreeToPrintString (p->left, chain, param, printAll);
8535 AddToPrintString (",");
8536 WriteEventTreeToPrintString (p->right, chain, param, printAll);
8539 if (p->anc->anc != NULL)
8541 SafeSprintf (&tempStr, &tempStrSize, "):%s", MbPrintNum(p->length));
8542 AddToPrintString (tempStr);
8543 for (i=0; i<param->nSubParams; i++)
8545 if (param->subParams[i]->paramType == P_CPPEVENTS)
8547 nEvents = param->subParams[i]->nEvents[2*chain+state[chain]][p->index];
8550 SafeSprintf (&tempStr, &tempStrSize, "[&E %s %d", param->subParams[i]->name, nEvents);
8551 AddToPrintString (tempStr);
8552 position = param->subParams[i]->position[2*chain+state[chain]][p->index];
8553 rateMult = param->subParams[i]->rateMult[2*chain+state[chain]][p->index];
8554 if (printAll == YES)
8556 SafeSprintf (&tempStr, &tempStrSize, ": (");
8557 AddToPrintString (tempStr);
8558 for (j=0; j<nEvents; j++)
8560 SafeSprintf (&tempStr, &tempStrSize, "%s", MbPrintNum(position[j]));
8561 AddToPrintString (tempStr);
8562 SafeSprintf (&tempStr, &tempStrSize, " %s", MbPrintNum(rateMult[j]));
8563 AddToPrintString (tempStr);
8565 AddToPrintString (",");
8567 AddToPrintString (")");
8570 AddToPrintString ("]");
8574 SafeSprintf (&tempStr, &tempStrSize, "[&E %s 0]", param->subParams[i]->name);
8575 AddToPrintString (tempStr);
8578 else if (param->subParams[i]->paramType != P_CPPEVENTS)
8580 /* other relaxed clock models */
8581 brlen = GetParamSubVals (param->subParams[i], chain, state[chain])[p->index];
8582 SafeSprintf (&tempStr, &tempStrSize, "[&B %s %s]", param->subParams[i]->name, MbPrintNum(brlen));
8583 AddToPrintString (tempStr);
8588 AddToPrintString(")");
8596 void WriteEvolTree (TreeNode *p, int chain, Param *param)
8602 length = GetParamSubVals(param, chain, state[chain]);
8603 if (p->left == NULL && p->right == NULL)
8605 printf ("%d:%s", p->index + 1, MbPrintNum(length[p->index]));
8611 WriteEvolTree(p->left, chain, param);
8613 WriteEvolTree(p->right, chain, param);
8616 if (p->anc->anc != NULL)
8617 printf ("):%s", MbPrintNum(length[p->index]));
8626 void WriteNoEvtTreeToPrintString (TreeNode *p, int chain, Param *param, int showBrlens, int isRooted)
8629 int i, tempStrSize = TEMPSTRSIZE, nEvents;
8632 tempStr = (char *) SafeMalloc((size_t)tempStrSize * sizeof(char));
8634 MrBayesPrint ("%s Problem allocating tempString (%d)\n", spacer, tempStrSize * sizeof(char));
8638 if (p->left == NULL && p->right == NULL)
8640 if (showBrlens == YES)
8642 SafeSprintf (&tempStr, &tempStrSize, "%d:%s", p->index + 1, MbPrintNum(p->length));
8645 SafeSprintf (&tempStr, &tempStrSize, "%d", p->index + 1);
8646 AddToPrintString (tempStr);
8647 if (param->paramType == P_BRLENS)
8649 for (i=0; i<param->nSubParams; i++)
8651 if (param->subParams[i]->paramType == P_CPPEVENTS)
8653 nEvents = param->subParams[i]->nEvents[2*chain+state[chain]][p->index];
8654 SafeSprintf (&tempStr, &tempStrSize, "[&E %s %d]", param->subParams[i]->name, nEvents);
8655 AddToPrintString (tempStr);
8657 brlen = GetParamSubVals (param->subParams[i], chain, state[chain])[p->index];
8658 SafeSprintf (&tempStr, &tempStrSize, "[&B %s %s]", param->subParams[i]->name, MbPrintNum(brlen));
8659 AddToPrintString (tempStr);
8662 else if (param->paramType == P_SPECIESTREE && modelSettings[param->relParts[0]].popSize->nValues > 1)
8664 N = GetParamVals (modelSettings[param->relParts[0]].popSize, chain, state[chain])[p->index];
8665 SafeSprintf (&tempStr, &tempStrSize, "[&N %s %s]", modelSettings[param->relParts[0]].popSize->name, MbPrintNum(N));
8666 AddToPrintString (tempStr);
8672 AddToPrintString ("(");
8673 WriteNoEvtTreeToPrintString (p->left, chain, param, showBrlens, isRooted);
8675 AddToPrintString (",");
8676 WriteNoEvtTreeToPrintString (p->right, chain, param, showBrlens, isRooted);
8679 if (p->anc->anc == NULL && isRooted == NO)
8681 if (showBrlens == YES)
8682 SafeSprintf (&tempStr, &tempStrSize, ",%d:%s)", p->anc->index + 1, MbPrintNum(p->length));
8684 SafeSprintf (&tempStr, &tempStrSize, ",%d)", p->anc->index + 1);
8685 AddToPrintString (tempStr);
8687 else if (p->anc->anc != NULL)
8689 if (showBrlens == YES)
8690 SafeSprintf (&tempStr, &tempStrSize, "):%s", MbPrintNum(p->length));
8692 SafeSprintf (&tempStr, &tempStrSize, ")");
8693 AddToPrintString (tempStr);
8694 if (param->paramType == P_BRLENS)
8696 for (i=0; i<param->nSubParams; i++)
8698 if (param->subParams[i]->paramType == P_CPPEVENTS)
8700 nEvents = param->subParams[i]->nEvents[2*chain+state[chain]][p->index];
8701 SafeSprintf (&tempStr, &tempStrSize, "[&E %s %d]", param->subParams[i]->name, nEvents);
8702 AddToPrintString (tempStr);
8704 brlen = GetParamSubVals (param->subParams[i], chain, state[chain])[p->index];
8705 SafeSprintf (&tempStr, &tempStrSize, "[&B %s %s]", param->subParams[i]->name, MbPrintNum(brlen));
8706 AddToPrintString (tempStr);
8709 else if (param->paramType == P_SPECIESTREE && modelSettings[param->relParts[0]].popSize->nValues > 1)
8711 N = GetParamVals (modelSettings[param->relParts[0]].popSize, chain, state[chain])[p->index];
8712 SafeSprintf (&tempStr, &tempStrSize, "[&N %s %s]", modelSettings[param->relParts[0]].popSize->name, MbPrintNum(N));
8713 AddToPrintString (tempStr);
8716 else if (param->paramType == P_SPECIESTREE && modelSettings[param->relParts[0]].popSize->nValues > 1)
8718 N = GetParamVals (modelSettings[param->relParts[0]].popSize, chain, state[chain])[p->index];
8719 SafeSprintf (&tempStr, &tempStrSize, ")[&N %s %s]", modelSettings[param->relParts[0]].popSize->name, MbPrintNum(N));
8720 AddToPrintString (tempStr);
8723 AddToPrintString(")");
8731 /* WriteTopologyToFile: Simply write topology to file */
8732 void WriteTopologyToFile (FILE *fp, TreeNode *p, int isRooted)
8736 if (p->left == NULL && p->right == NULL)
8737 fprintf (fp, "%d", p->index + 1);
8742 WriteTopologyToFile (fp, p->left, isRooted);
8745 WriteTopologyToFile (fp, p->right, isRooted);
8748 if (p->anc->anc == NULL && isRooted == NO)
8749 fprintf (fp, ",%d", p->anc->index + 1);
8757 /* the following are moved from mbmath.c */
8758 /*---------------------------------------------------------------------------------
8762 | Takes the sum of two matrices, "a" and "b", and puts the results in a matrix
8765 ---------------------------------------------------------------------------------*/
8766 void AddTwoMatrices (int dim, MrBFlt **a, MrBFlt **b, MrBFlt **result)
8770 for (row=0; row<dim; row++)
8772 for (col=0; col<dim; col++)
8774 result[row][col] = a[row][col] + b[row][col];
8780 /*---------------------------------------------------------------------------------
8782 | AllocateSquareComplexMatrix
8784 | Allocate memory for a square (dim X dim) complex matrix.
8786 ---------------------------------------------------------------------------------*/
8787 complex **AllocateSquareComplexMatrix (int dim)
8792 m = (complex **) SafeMalloc ((size_t)dim * sizeof(complex*));
8795 MrBayesPrint ("%s Error: Problem allocating a square complex matrix.\n", spacer);
8798 m[0]=(complex *) SafeMalloc ((size_t)dim * (size_t)dim *sizeof(complex));
8801 MrBayesPrint ("%s Error: Problem allocating a square complex matrix.\n", spacer);
8806 m[i] = m[i-1] + dim;
8813 /*---------------------------------------------------------------------------------
8815 | AllocateSquareDoubleMatrix
8817 | Allocate memory for a square (dim X dim) matrix of doubles.
8819 ---------------------------------------------------------------------------------*/
8820 MrBFlt **AllocateSquareDoubleMatrix (int dim)
8825 m = (MrBFlt **) SafeMalloc ((size_t)dim * sizeof(MrBFlt*));
8828 MrBayesPrint ("%s Error: Problem allocating a square matrix of doubles.\n", spacer);
8831 m[0] = (MrBFlt *) SafeMalloc ((size_t)dim * (size_t)dim * sizeof(MrBFlt));
8834 MrBayesPrint ("%s Error: Problem allocating a square matrix of doubles.\n", spacer);
8837 for (i=1; i<dim; i++)
8839 m[i] = m[i-1] + dim;
8846 /*---------------------------------------------------------------------------------
8848 | AllocateSquareIntegerMatrix
8850 | Allocate memory for a square (dim X dim) matrix of integers.
8852 ---------------------------------------------------------------------------------*/
8853 int **AllocateSquareIntegerMatrix (int dim)
8857 m = (int **) SafeMalloc ((size_t)dim * sizeof(int*));
8860 MrBayesPrint ("%s Error: Problem allocating a square matrix of integers.\n", spacer);
8863 m[0] = (int *) SafeMalloc ((size_t)dim * (size_t)dim * sizeof(int));
8866 MrBayesPrint ("%s Error: Problem allocating a square matrix of integers.\n", spacer);
8869 for (i=1; i<dim; i++)
8871 m[i] = m[i-1] + dim;
8878 /*---------------------------------------------------------------------------------
8882 | Auto-discrete-gamma distribution of rates over sites, K equal-probable
8883 | categories, with the mean for each category used.
8884 | This routine calculates M[], using rho and K (numGammaCats)
8886 ---------------------------------------------------------------------------------*/
8887 int AutodGamma (MrBFlt *M, MrBFlt rho, int K)
8890 MrBFlt point[MAX_GAMMA_CATS], x, y, large = 20.0, sum;
8892 for (i=0; i<K-1; i++)
8893 point[i] = PointNormal ((i + 1.0) / K);
8898 x = (i < K-1 ? point[i]:large);
8899 y = (j < K-1 ? point[j]:large);
8900 M[i * K + j] = CdfBinormal (x, y, rho);
8903 for (i1=0; i1<2*K-1; i1++)
8905 for (i2=0; i2<K*K; i2++)
8909 if (AreDoublesEqual(i+j, 2*(K-1.0)-i1, ETA)==NO)
8917 y += M[(i-1)*K+(j-1)];
8918 M[i*K+j] = (M[i*K+j] + y) * K;
8934 // MrBayesPrint ("rho = %lf\n", rho);
8935 // for (i=0; i<K; i++)
8937 // for (j=0; j<K; j++)
8938 // MrBayesPrint ("%lf ", M[i*K + j]);
8939 // MrBayesPrint ("\n");
8946 /*---------------------------------------------------------------------------------
8948 | BackSubstitutionRow
8950 ---------------------------------------------------------------------------------*/
8951 void BackSubstitutionRow (int dim, MrBFlt **u, MrBFlt *b)
8956 b[dim-1] /= u[dim-1][dim-1];
8957 for (i=dim-2; i>=0; i--)
8960 for (j=i+1; j<dim; j++)
8961 dotProduct += u[i][j] * b[j];
8962 b[i] = (b[i] - dotProduct) / u[i][i];
8967 /*---------------------------------------------------------------------------------
8971 | This subroutine balances a real matrix and isolates
8972 | eigenvalues whenever possible.
8976 | * dim is the order of the matrix
8978 | * a contains the input matrix to be balanced
8982 | * a contains the balanced matrix.
8984 | * low and high are two integers such that a(i,j)
8985 | is equal to zero if
8986 | (1) i is greater than j and
8987 | (2) j=1,...,low-1 or i=igh+1,...,n.
8989 | * scale contains information determining the
8990 | permutations and scaling factors used.
8992 | Suppose that the principal submatrix in rows pLow through pHigh
8993 | has been balanced, that p(j) denotes the index interchanged
8994 | with j during the permutation step, and that the elements
8995 | of the diagonal matrix used are denoted by d(i,j). Then
8996 | scale(j) = p(j), for j = 1,...,pLow-1
8997 | = d(j,j), j = pLow,...,pHigh
8998 | = p(j) j = pHigh+1,...,dim.
8999 | The order in which the interchanges are made is dim to pHigh+1,
9002 | Note that 1 is returned for pHigh if pHigh is zero formally.
9004 | The algol procedure exc contained in balance appears in
9005 | balanc in line. (Note that the algol roles of identifiers
9006 | k,l have been reversed.)
9008 | This routine is a translation of the Algol procedure from
9009 | Handbook for Automatic Computation, vol. II, Linear Algebra,
9010 | by Wilkinson and Reinsch, Springer-Verlag.
9012 | This function was converted from FORTRAN by D. L. Swofford.
9014 ---------------------------------------------------------------------------------*/
9015 void Balanc (int dim, MrBFlt **a, int *low, int *high, MrBFlt *scale)
9017 int i, j, k, l, m, noconv;
9018 MrBFlt c, f, g, r, s, b2;
9020 b2 = FLT_RADIX * FLT_RADIX;
9024 for (j=l; j>=0; j--)
9026 for (i=0; i<=l; i++)
9030 if (AreDoublesEqual(a[j][i],0.0, ETA)==NO)
9035 /* bug that DLS caught */
9037 Exchange(j, k, l, m, dim, a, scale);
9043 Exchange(j, k, l, m, dim, a, scale);
9050 for (j=k; j<=l; j++)
9052 for (i=k; i<=l; i++)
9056 if (AreDoublesEqual(a[i][j], 0.0, ETA)==NO)
9061 Exchange(j, k, l, m, dim, a, scale);
9067 for (i=k; i<=l; i++)
9072 for (i=k; i<=l; i++)
9076 for (j=k; j<=l; j++)
9084 if (AreDoublesEqual(c,0.0,ETA)==NO && AreDoublesEqual(r,0.0,ETA)==NO)
9100 if ((c + r) / f < s * .95)
9105 for (j=k; j<dim; j++)
9107 for (j=0; j<=l; j++)
9119 /* begin f2c version of code:
9120 balanc.f -- translated by f2c (version 19971204) */
9121 int balanc (int *nm, int *n, MrBFlt *a, int *low, int *igh, MrBFlt *scale)
9125 /* System generated locals */
9126 int a_dim1, a_offset, i__1, i__2;
9129 /* Local variables */
9131 static MrBFlt c__, f, g;
9132 static MrBFlt i__, j, k, l, m;
9133 static MrBFlt r__, s, radix, b2;
9135 static logical noconv;
9137 /* parameter adjustments */
9140 a_offset = a_dim1 + 1;
9151 /* .......... in-line procedure for row and column exchange .......... */
9153 scale[m] = (MrBFlt) j;
9158 for (i__ = 1; i__ <= i__1; ++i__)
9160 f = a[i__ + j * a_dim1];
9161 a[i__ + j * a_dim1] = a[i__ + m * a_dim1];
9162 a[i__ + m * a_dim1] = f;
9167 for (i__ = k; i__ <= i__1; ++i__)
9169 f = a[j + i__ * a_dim1];
9170 a[j + i__ * a_dim1] = a[m + i__ * a_dim1];
9171 a[m + i__ * a_dim1] = f;
9184 /* .......... search for rows isolating an eigenvalue and push them down .......... */
9190 /* .......... for j=l step -1 until 1 do -- .......... */
9193 for (jj = 1; jj <= i__1; ++jj)
9197 for (i__ = 1; i__ <= i__2; ++i__)
9201 if (a[j + i__ * a_dim1] != 0.)
9214 /* .......... search for columns isolating an eigenvalue and push them left .......... */
9220 for (j = k; j <= i__1; ++j)
9223 for (i__ = k; i__ <= i__2; ++i__)
9227 if (a[i__ + j * a_dim1] != 0.)
9239 /* .......... now balance the submatrix in rows k to l .......... */
9241 for (i__ = k; i__ <= i__1; ++i__)
9246 /* .......... iterative loop for norm reduction .......... */
9251 for (i__ = k; i__ <= i__1; ++i__)
9256 for (j = k; j <= i__2; ++j)
9260 c__ += (d__1 = a[j + i__ * a_dim1], abs(d__1));
9261 r__ += (d__1 = a[i__ + j * a_dim1], abs(d__1));
9266 /* .......... guard against zero c or r due to underflow .......... */
9267 if (c__ == 0. || r__ == 0.)
9287 /* .......... now balance .......... */
9289 if ((c__ + r__) / f >= s * .95)
9296 for (j = k; j <= i__2; ++j)
9299 a[i__ + j * a_dim1] *= g;
9303 for (j = 1; j <= i__2; ++j)
9306 a[j + i__ * a_dim1] *= f;
9322 /* end f2c version of code */
9328 /*---------------------------------------------------------------------------------
9332 | This subroutine forms the eigenvectors of a real general
9333 | matrix by back transforming those of the corresponding
9334 | balanced matrix determined by balance.
9338 | * dim is the order of the matrix
9340 | * low and high are integers determined by balance
9342 | * scale contains information determining the permutations
9343 | and scaling factors used by balance
9345 | * m is the number of columns of z to be back transformed
9347 | * z contains the real and imaginary parts of the eigen-
9348 | vectors to be back transformed in its first m columns
9352 | * z contains the real and imaginary parts of the
9353 | transformed eigenvectors in its first m columns
9355 | This routine is a translation of the Algol procedure from
9356 | Handbook for Automatic Computation, vol. II, Linear Algebra,
9357 | by Wilkinson and Reinsch, Springer-Verlag.
9359 ---------------------------------------------------------------------------------*/
9360 void BalBak (int dim, int low, int high, MrBFlt *scale, int m, MrBFlt **z)
9365 if (m != 0) /* change "==" to "!=" to eliminate a goto statement */
9367 if (high != low) /* change "==" to "!=" to eliminate a goto statement */
9369 for (i=low; i<=high; i++)
9376 for (ii=0; ii<dim; ii++)
9379 if ((i < low) || (i > high)) /* was (i >= lo) && (i<= hi) but this */
9380 { /* eliminates a goto statement */
9384 if (k != i) /* change "==" to "!=" to eliminate a goto statement */
9386 for (j = 0; j < m; j++)
9398 /* begin f2c version of code:
9399 balbak.f -- translated by f2c (version 19971204) */
9400 int balbak (int *nm, int *n, int *low, int *igh, MrBFlt *scale, int *m, MrBFlt *z__)
9404 /* system generated locals */
9405 int z_dim1, z_offset, i__1, i__2;
9407 /* Local variables */
9408 static int i__, j, k;
9412 /* parameter adjustments */
9415 z_offset = z_dim1 + 1;
9425 for (i__ = *low; i__ <= i__1; ++i__)
9428 /* .......... left hand eigenvectors are back transformed */
9429 /* if the foregoing statement is replaced by */
9430 /* s=1.0d0/scale(i) ........... */
9432 for (j = 1; j <= i__2; ++j)
9435 z__[i__ + j * z_dim1] *= s;
9441 /* .........for i=low-1 step -1 until 1, igh+1 step 1 until n do -- .......... */
9444 for (ii = 1; ii <= i__1; ++ii)
9447 if (i__ >= *low && i__ <= *igh)
9451 k = (integer) scale[i__];
9456 for (j = 1; j <= i__2; ++j)
9458 s = z__[i__ + j * z_dim1];
9459 z__[i__ + j * z_dim1] = z__[k + j * z_dim1];
9460 z__[k + j * z_dim1] = s;
9471 /* end f2c version of code */
9477 void BetaBreaks (MrBFlt alpha, MrBFlt beta, MrBFlt *values, int K)
9480 MrBFlt r, quantile, lower, upper;
9482 r = (1.0 / K) * 0.5;
9485 r = (upper - lower) * 0.5 + lower;
9488 quantile = BetaQuantile (alpha, beta, r);
9489 values[i] = quantile;
9498 MrBayesPrint ("%4d %lf %lf\n", i, values[i]);
9504 MrBFlt BetaCf (MrBFlt a, MrBFlt b, MrBFlt x)
9507 MrBFlt aa, c, d, del, h, qab, qam, qap;
9513 d = 1.0 - qab * x / qap;
9514 if (fabs(d) < (1.0e-30))
9518 for (m=1; m<=100; m++)
9521 aa = m * (b-m) * x / ((qam+m2) * (a+m2));
9523 if (fabs(d) < (1.0e-30))
9526 if (fabs(c) < (1.0e-30))
9530 aa = -(a+m) * (qab+m) * x / ((a+m2) * (qap+m2));
9532 if (fabs(d) < (1.0e-30))
9535 if (fabs(c) < (1.0e-30))
9540 if (fabs(del - 1.0) < (3.0e-7))
9545 MrBayesPrint ("%s Error in BetaCf.\n", spacer);
9552 MrBFlt BetaQuantile (MrBFlt alpha, MrBFlt beta, MrBFlt x)
9554 int i, stopIter, direction, nswitches;
9555 MrBFlt curPos, curFraction, increment;
9561 curFraction = IncompleteBetaFunction (alpha, beta, curPos);
9562 if (curFraction > x)
9567 while (stopIter == NO)
9569 curFraction = IncompleteBetaFunction (alpha, beta, curPos);
9570 if (curFraction > x && direction == DOWN)
9572 /* continue going down */
9573 while (curPos - increment <= 0.0)
9577 curPos -= increment;
9579 else if (curFraction > x && direction == UP)
9581 /* switch directions, and go down */
9584 while (curPos - increment <= 0.0)
9589 curPos -= increment;
9591 else if (curFraction < x && direction == UP)
9593 /* continue going up */
9594 while (curPos + increment >= 1.0)
9598 curPos += increment;
9600 else if (curFraction < x && direction == DOWN)
9602 /* switch directions, and go up */
9605 while (curPos + increment >= 1.0)
9610 curPos += increment;
9616 if (i > 1000 || nswitches > 20)
9625 /*---------------------------------------------------------------------------------
9629 | This function precalculates the product of the eigenvectors and their
9630 | inverse for faster calculation of transition probabilities. The output
9631 | is a vector of precalculated values. The input is the eigenvectors (u) and
9632 | the inverse of the eigenvector matrix (v).
9634 ---------------------------------------------------------------------------------*/
9635 void CalcCijk (int dim, MrBFlt *c_ijk, MrBFlt **u, MrBFlt **v)
9637 register int i, j, k;
9641 for (i=0; i<dim; i++)
9642 for (j=0; j<dim; j++)
9643 for (k=0; k<dim; k++)
9644 *pc++ = u[i][k] * v[k][j];
9648 /*---------------------------------------------------------------------------------
9652 | F(h1,h2,r) = prob(x<h1, y<h2), where x and y are standard binormal.
9654 ---------------------------------------------------------------------------------*/
9655 MrBFlt CdfBinormal (MrBFlt h1, MrBFlt h2, MrBFlt r)
9657 return (LBinormal(h1, h2, r) + CdfNormal(h1) + CdfNormal(h2) - 1.0);
9661 /*---------------------------------------------------------------------------------
9665 | Calculates the cumulative density distribution (CDF) for the normal using:
9667 | Hill, I. D. 1973. The normal integral. Applied Statistics, 22:424-427.
9670 ---------------------------------------------------------------------------------*/
9671 MrBFlt CdfNormal (MrBFlt x)
9674 MrBFlt p, limit = 10.0, t = 1.28, y = x*x/2.0;
9682 return (invers ? 0 : 1);
9684 p = 0.5 - x * (0.398942280444 - 0.399903438504 * y /
9685 (y + 5.75885480458 - 29.8213557808 /
9686 (y + 2.62433121679 + 48.6959930692 /
9687 (y + 5.92885724438))));
9689 p = 0.398942280385 * exp(-y) /
9690 (x - 3.8052e-8 + 1.00000615302 /
9691 (x + 3.98064794e-4 + 1.98615381364 /
9692 (x - 0.151679116635 + 5.29330324926 /
9693 (x + 4.8385912808 - 15.1508972451 /
9694 (x + 0.742380924027 + 30.789933034 /
9695 (x + 3.99019417011))))));
9697 return (invers ? p : 1-p);
9701 /*---------------------------------------------------------------------------------
9705 | Returns a complex number with specified real and imaginary parts.
9707 ---------------------------------------------------------------------------------*/
9708 complex Complex (MrBFlt a, MrBFlt b)
9719 /*---------------------------------------------------------------------------------
9721 | ComplexAbsoluteValue
9723 | Returns the complex absolute value (modulus) of a complex number.
9725 ---------------------------------------------------------------------------------*/
9726 MrBFlt ComplexAbsoluteValue (complex a)
9728 MrBFlt x, y, answer, temp;
9732 if (AreDoublesEqual(x, 0.0, ETA)==YES) /* x == 0.0 */
9734 else if (AreDoublesEqual(y, 0.0, ETA)==YES) /* y == 0.0 */
9739 answer = x * sqrt(1.0 + temp * temp);
9744 answer = y * sqrt(1.0 + temp * temp);
9751 /*---------------------------------------------------------------------------------
9755 | Returns the complex sum of two complex numbers.
9757 ---------------------------------------------------------------------------------*/
9758 complex ComplexAddition (complex a, complex b)
9769 /*---------------------------------------------------------------------------------
9773 | Returns the complex conjugate of a complex number.
9775 ---------------------------------------------------------------------------------*/
9776 complex ComplexConjugate (complex a)
9787 /*---------------------------------------------------------------------------------
9791 | Returns the complex quotient of two complex numbers.
9793 ---------------------------------------------------------------------------------*/
9794 complex ComplexDivision (complex a, complex b)
9799 if (fabs(b.re) >= fabs(b.im))
9802 den = b.re + r * b.im;
9803 c.re = (a.re + r * a.im) / den;
9804 c.im = (a.im - r * a.re) / den;
9809 den = b.im + r * b.re;
9810 c.re = (a.re * r + a.im) / den;
9811 c.im = (a.im * r - a.re) / den;
9818 /*---------------------------------------------------------------------------------
9822 | Returns the complex quotient of two complex numbers. It does not require that
9823 | the numbers be in a complex structure.
9825 ---------------------------------------------------------------------------------*/
9826 void ComplexDivision2 (MrBFlt ar, MrBFlt ai, MrBFlt br, MrBFlt bi, MrBFlt *cr, MrBFlt *ci)
9828 MrBFlt s, ais, bis, ars, brs;
9830 s = fabs(br) + fabs(bi);
9835 s = brs*brs + bis*bis;
9836 *cr = (ars*brs + ais*bis) / s;
9837 *ci = (ais*brs - ars*bis) / s;
9841 /*---------------------------------------------------------------------------------
9843 | ComplexExponentiation
9845 | Returns the complex exponential of a complex number.
9847 ---------------------------------------------------------------------------------*/
9848 complex ComplexExponentiation (complex a)
9853 if (AreDoublesEqual(a.im,0.0, ETA)==YES) /* == 0 */
9857 c.im = c.re*sin(a.im);
9865 /*---------------------------------------------------------------------------------
9867 | ComplexInvertMatrix
9869 | Inverts a matrix of complex numbers using the LU-decomposition method.
9870 | The program has the following variables:
9872 | a -- the matrix to be inverted
9873 | aInverse -- the results of the matrix inversion
9874 | dim -- the dimension of the square matrix a and its inverse
9875 | dwork -- a work vector of doubles
9876 | indx -- a work vector of integers
9877 | col -- carries the results of the back substitution
9879 | The function returns YES (1) or NO (0) if the results are singular.
9881 ---------------------------------------------------------------------------------*/
9882 int ComplexInvertMatrix (int dim, complex **a, MrBFlt *dwork, int *indx, complex **aInverse, complex *col)
9884 int isSingular, i, j;
9886 isSingular = ComplexLUDecompose (dim, a, dwork, indx, (MrBFlt *)NULL);
9888 if (isSingular == 0)
9890 for (j=0; j<dim; j++)
9892 for (i=0; i<dim; i++)
9893 col[i] = Complex (0.0, 0.0);
9894 col[j] = Complex (1.0, 0.0);
9895 ComplexLUBackSubstitution (dim, a, indx, col);
9896 for (i=0; i<dim; i++)
9897 aInverse[i][j] = col[i];
9901 return (isSingular);
9905 /*---------------------------------------------------------------------------------
9907 | ComplexExponentiation
9909 | Returns the complex exponential of a complex number.
9911 ---------------------------------------------------------------------------------*/
9912 complex ComplexLog (complex a)
9916 c.re = log(ComplexAbsoluteValue(a));
9917 if (AreDoublesEqual(a.re,0.0,ETA)==YES) /* == 0.0 */
9923 c.im = atan2(a.im, a.re);
9930 /*---------------------------------------------------------------------------------
9932 | ComplexLUBackSubstitution
9934 | Perform back-substitution into a LU-decomposed matrix to obtain
9937 ---------------------------------------------------------------------------------*/
9938 void ComplexLUBackSubstitution (int dim, complex **a, int *indx, complex *b)
9940 int i, ip, j, ii = -1;
9943 for (i = 0; i < dim; i++)
9950 for (j = ii; j <= i - 1; j++)
9951 sum = ComplexSubtraction (sum, ComplexMultiplication (a[i][j], b[j]));
9953 else if (AreDoublesEqual(sum.re,0.0,ETA)==NO || AreDoublesEqual(sum.im, 0.0, ETA)==NO) /* 2x != 0.0 */
9957 for (i = dim - 1; i >= 0; i--)
9960 for (j = i + 1; j < dim; j++)
9961 sum = ComplexSubtraction (sum, ComplexMultiplication (a[i][j], b[j]));
9962 b[i] = ComplexDivision (sum, a[i][i]);
9967 /*---------------------------------------------------------------------------------
9969 | ComplexLUDecompose
9971 | Replaces the matrix a with its LU-decomposition.
9972 | The program has the following variables:
9975 | dim -- the dimension of the square matrix a and its inverse
9976 | vv -- a work vector of doubles
9977 | indx -- row permutation according to partitial pivoting sequence
9978 | pd -- 1 if number of row interchanges was even, -1 if number of
9979 | row interchanges was odd. Can be NULL.
9981 | The function returns YES (1) or NO (0) if the results are singular.
9983 ---------------------------------------------------------------------------------*/
9984 int ComplexLUDecompose (int dim, complex **a, MrBFlt *vv, int *indx, MrBFlt *pd)
9987 MrBFlt big, dum, temp, d;
9993 for (i = 0; i < dim; i++)
9996 for (j = 0; j < dim; j++)
9998 if ((temp = ComplexAbsoluteValue (a[i][j])) > big)
10001 if (AreDoublesEqual(big, 0.0, ETA)==YES) /* == 0.0 */
10003 MrBayesPrint ("%s Error: Problem in ComplexLUDecompose\n", spacer);
10009 for (j = 0; j < dim; j++)
10011 for (i = 0; i < j; i++)
10014 for (k = 0; k < i; k++)
10015 sum = ComplexSubtraction (sum, ComplexMultiplication (a[i][k], a[k][j]));
10019 for (i = j; i < dim; i++)
10022 for (k = 0; k < j; k++)
10023 sum = ComplexSubtraction (sum, ComplexMultiplication (a[i][k], a[k][j]));
10025 dum = vv[i] * ComplexAbsoluteValue (sum);
10034 for (k = 0; k < dim; k++)
10037 a[imax][k] = a[j][k];
10044 if (AreDoublesEqual(a[j][j].re, 0.0, ETA)==YES && AreDoublesEqual(a[j][j].im, 0.0, ETA)==YES) /* 2x == 0.0 */
10045 a[j][j] = Complex (1.0e-20, 1.0e-20);
10048 cdum = ComplexDivision (Complex(1.0, 0.0), a[j][j]);
10049 for (i = j + 1; i < dim; i++)
10050 a[i][j] = ComplexMultiplication (a[i][j], cdum);
10061 /*---------------------------------------------------------------------------------
10063 | ComplexMultiplication
10065 | Returns the complex product of two complex numbers.
10067 ---------------------------------------------------------------------------------*/
10068 complex ComplexMultiplication (complex a, complex b)
10072 c.re = a.re * b.re - a.im * b.im;
10073 c.im = a.im * b.re + a.re * b.im;
10079 /*---------------------------------------------------------------------------------
10081 | ComplexSquareRoot
10083 | Returns the complex square root of a complex number.
10085 ---------------------------------------------------------------------------------*/
10086 complex ComplexSquareRoot (complex a)
10091 if (AreDoublesEqual(a.re, 0.0, ETA)==YES && AreDoublesEqual(a.im, 0.0, ETA)==YES) /* 2x == 0.0 */
10104 w = sqrt(x) * sqrt(0.5 * (1.0 + sqrt(1.0 + r * r)));
10109 w = sqrt(y) * sqrt(0.5 * (r + sqrt(1.0 + r * r)));
10114 c.im = a.im / (2.0 * w);
10118 c.im = (a.im >= 0.0) ? w : -w;
10119 c.re = a.im / (2.0 * c.im);
10126 /*---------------------------------------------------------------------------------
10128 | ComplexSubtraction
10130 | Returns the complex difference of two complex numbers.
10132 ---------------------------------------------------------------------------------*/
10133 complex ComplexSubtraction (complex a, complex b)
10137 c.re = a.re - b.re;
10138 c.im = a.im - b.im;
10144 /*---------------------------------------------------------------------------------
10146 | ComputeEigenSystem
10148 | Calculates the eigenvalues, eigenvectors, and the inverse of the eigenvectors
10149 | for a matrix of real numbers.
10151 ---------------------------------------------------------------------------------*/
10152 int ComputeEigenSystem (int dim, MrBFlt **a, MrBFlt *v, MrBFlt *vi, MrBFlt **u, int *iwork, MrBFlt *dwork)
10156 rc = EigensForRealMatrix (dim, a, v, vi, u, iwork, dwork);
10157 if (rc != NO_ERROR)
10159 MrBayesPrint ("%s Error in ComputeEigenSystem.\n", spacer);
10162 for (i=0; i<dim; i++)
10164 if (AreDoublesEqual(vi[i], 0.0, ETA)==NO) /* != 0.0 */
10165 return (EVALUATE_COMPLEX_NUMBERS);
10172 /*---------------------------------------------------------------------------------
10176 | This function computes the L and U decomposition of a matrix. Basically,
10177 | we find matrices lMat and uMat such that
10179 | lMat * uMat = aMat
10181 ---------------------------------------------------------------------------------*/
10182 void ComputeLandU (int dim, MrBFlt **aMat, MrBFlt **lMat, MrBFlt **uMat)
10184 int i, j, k, m, row, col;
10186 for (j=0; j<dim; j++)
10188 for (k=0; k<j; k++)
10189 for (i=k+1; i<j; i++)
10190 aMat[i][j] = aMat[i][j] - aMat[i][k] * aMat[k][j];
10192 for (k=0; k<j; k++)
10193 for (i=j; i<dim; i++)
10194 aMat[i][j] = aMat[i][j] - aMat[i][k]*aMat[k][j];
10196 for (m=j+1; m<dim; m++)
10197 aMat[m][j] /= aMat[j][j];
10200 for (row=0; row<dim; row++)
10202 for (col=0; col<dim; col++)
10206 uMat[row][col] = aMat[row][col];
10207 lMat[row][col] = (row == col ? 1.0 : 0.0);
10211 lMat[row][col] = aMat[row][col];
10212 uMat[row][col] = 0.0;
10219 /*---------------------------------------------------------------------------------
10221 | ComputeMatrixExponential
10223 | The method approximates the matrix exponential, f = e^a, using
10224 | the algorithm 11.3.1, described in:
10226 | Golub, G. H., and C. F. Van Loan. 1996. Matrix Computations, Third Edition.
10227 | The Johns Hopkins University Press, Baltimore, Maryland.
10229 | The method has the advantage of error control. The error is controlled by
10230 | setting qValue appropriately (using the function SetQValue).
10232 ---------------------------------------------------------------------------------*/
10233 void ComputeMatrixExponential (int dim, MrBFlt **a, int qValue, MrBFlt **f)
10235 int i, j, k, negativeFactor;
10236 MrBFlt maxAValue, c, **d, **n, **x, **cX;
10238 d = AllocateSquareDoubleMatrix (dim);
10239 n = AllocateSquareDoubleMatrix (dim);
10240 x = AllocateSquareDoubleMatrix (dim);
10241 cX = AllocateSquareDoubleMatrix (dim);
10243 SetToIdentity (dim, d);
10244 SetToIdentity (dim, n);
10245 SetToIdentity (dim, x);
10248 for (i=0; i<dim; i++)
10249 maxAValue = MAX (maxAValue, a[i][i]);
10251 j = MAX (0, LogBase2Plus1 (maxAValue));
10253 DivideByTwos (dim, a, j);
10256 for (k=1; k<=qValue; k++)
10258 c = c * (qValue - k + 1.0) / ((2.0 * qValue - k + 1.0) * k);
10261 MultiplyMatrices (dim, a, x, x);
10264 MultiplyMatrixByScalar (dim, x, c, cX);
10265 AddTwoMatrices (dim, n, cX, n);
10267 /* D = D + (-1)^k*cX */
10268 negativeFactor = (k % 2 == 0 ? 1 : -1);
10269 if (negativeFactor == -1)
10270 MultiplyMatrixByScalar (dim, cX, negativeFactor, cX);
10271 AddTwoMatrices (dim, d, cX, d);
10274 GaussianElimination (dim, d, n, f);
10276 for (k = 0; k < j; k++)
10277 MultiplyMatrices (dim, f, f, f);
10279 for (i=0; i<dim; i++)
10281 for (j=0; j<dim; j++)
10284 f[i][j] = fabs(f[i][j]);
10288 FreeSquareDoubleMatrix (d);
10289 FreeSquareDoubleMatrix (n);
10290 FreeSquareDoubleMatrix (x);
10291 FreeSquareDoubleMatrix (cX);
10295 /*---------------------------------------------------------------------------------
10297 | CopyComplexMatrices
10299 | Copies the contents of one matrix of complex numbers to another matrix.
10301 ---------------------------------------------------------------------------------*/
10302 void CopyComplexMatrices (int dim, complex **from, complex **to)
10306 for (i=0; i<dim; i++)
10308 for (j=0; j<dim; j++)
10310 to[i][j].re = from[i][j].re;
10311 to[i][j].im = from[i][j].im;
10317 /*---------------------------------------------------------------------------------
10319 | CopyDoubleMatrices
10321 | Copies the contents of one matrix of doubles to another matrix.
10323 ---------------------------------------------------------------------------------*/
10324 void CopyDoubleMatrices (int dim, MrBFlt **from, MrBFlt **to)
10328 for (i=0; i<dim; i++)
10330 for (j=0; j<dim; j++)
10332 to[i][j] = from[i][j];
10338 /*---------------------------------------------------------------------------------
10340 | DirichletRandomVariable
10342 | Generate a Dirichlet-distributed random variable. The parameter of the
10343 | Dirichlet is contained in the vector alp. The random variable is contained
10346 ---------------------------------------------------------------------------------*/
10347 void DirichletRandomVariable (MrBFlt *alp, MrBFlt *z, int n, RandLong *seed)
10353 for (i=0; i<n; i++)
10355 z[i] = RndGamma (alp[i], seed) / 1.0;
10358 for (i=0; i<n; i++)
10363 /*---------------------------------------------------------------------------------
10367 | Discretization of gamma distribution with equal proportions in each
10370 ---------------------------------------------------------------------------------*/
10371 int DiscreteGamma (MrBFlt *rK, MrBFlt alfa, MrBFlt beta, int K, int median)
10374 MrBFlt gap05 = 1.0/(2.0*K), t, factor = alfa/beta*K, lnga1;
10378 for (i=0; i<K; i++)
10379 rK[i] = POINTGAMMA((i*2.0+1.0)*gap05, alfa, beta);
10380 for (i=0,t=0; i<K; i++)
10382 for (i=0; i<K; i++)
10383 rK[i] *= factor / t;
10387 lnga1 = LnGamma(alfa+1);
10388 /* calculate the points in the gamma distribution */
10389 for (i=0; i<K-1; i++)
10390 rK[i] = POINTGAMMA((i+1.0)/K, alfa, beta);
10391 /* calculate the cumulative values */
10392 for (i=0; i<K-1; i++)
10393 rK[i] = IncompleteGamma(rK[i] * beta, alfa + 1.0, lnga1);
10395 /* calculate the relative values and rescale */
10396 for (i=K-1; i>0; i--)
10408 /*---------------------------------------------------------------------------------
10410 | DiscreteLogNormal
10412 | Discretization of lognormal distribution with equal proportions in each
10415 | LBH Notes: K = # of rate classes
10416 | *rK = pointer to output rate class matrix
10417 | alfa = alpha param
10418 | beta = beta param
10419 | median = flag to use media or not (1 = use median, 0 = mean?)
10421 ---------------------------------------------------------------------------------*/
10422 int DiscreteLogNormal (MrBFlt *rK, MrBFlt sigma, int K, int median)
10426 MrBFlt sigmaL = sqrt(sigma);
10427 MrBFlt mu = -1.0*((0.5*pow(sigmaL,2.0)));
10430 for (i=0; i<K; i++) {
10431 rK[i] = QuantileLogNormal( ((2.0*i + 1) / (2.0 * K)), mu, sigmaL);
10433 for (i=0,t=0.0; i<K; i++) {
10437 for (i=0; i<K; i++)
10442 mu = -1.0*((0.5*pow(sigmaL,2.0)));
10443 /* Mean set to 1.0 so factor = K */
10445 for (i=0; i<K-1; i++) {
10446 rK[i] = QuantileLogNormal(((i + 1.0) / (K)), mu, sigmaL);
10448 for (i=0; i<K-1; i++) {
10449 //rK[i] = LogNormalPoint(rK[i], mu, sigma);
10450 //rK[i] = QuantileLogNormal(rK[i], mu, sigma);
10451 //rK[i] = CdfNormal((log(rK[i])-mu)/sigma);
10452 rK[i] = 1 - (1.0 * CdfNormal((mu + pow(sigmaL,2.0) - log(rK[i]))/sigmaL));
10455 for (i=K-1; i>0; i--) {
10466 /* LogNormal Quantile Function */
10467 MrBFlt QuantileLogNormal (MrBFlt prob, MrBFlt mu, MrBFlt sigma)
10469 MrBFlt a = 0.0, b = 0.0;
10470 a = PointNormal((0.5*(2.0*prob-1.0))+0.5) / sqrt(2.0);
10471 b = mu+(sqrt(2.0)* sigma * a);
10476 /* LogNormal Point Function */
10477 MrBFlt LogNormalPoint (MrBFlt x, MrBFlt mu, MrBFlt sigma)
10479 if(x <= 0.0) return(0.0);
10480 MrBFlt a = LnProbLogNormal(mu, sigma, x);
10485 /*---------------------------------------------------------------------------------
10489 | Divides all of the elements of the matrix a by 2^power.
10491 ---------------------------------------------------------------------------------*/
10492 void DivideByTwos (int dim, MrBFlt **a, int power)
10494 int divisor = 1, i, row, col;
10496 for (i=0; i<power; i++)
10497 divisor = divisor * 2;
10499 for (row=0; row<dim; row++)
10500 for (col=0; col<dim; col++)
10501 a[row][col] /= divisor;
10505 /*---------------------------------------------------------------------------------
10509 | This function is called from "Hqr2".
10511 ---------------------------------------------------------------------------------*/
10512 MrBFlt D_sign (MrBFlt a, MrBFlt b)
10516 x = (a >= 0 ? a : -a);
10518 return (b >= 0 ? x : -x);
10522 /*---------------------------------------------------------------------------------
10526 | The matrix of interest is a. The ouptut is the real and imaginary parts of the
10527 | eigenvalues (wr and wi). z contains the real and imaginary parts of the
10528 | eigenvectors. iv2 and fv1 are working vectors.
10530 ---------------------------------------------------------------------------------*/
10531 int EigensForRealMatrix (int dim, MrBFlt **a, MrBFlt *wr, MrBFlt *wi, MrBFlt **z, int *iv1, MrBFlt *fv1)
10533 static int is1, is2;
10536 Balanc (dim, a, &is1, &is2, fv1);
10537 ElmHes (dim, is1, is2, a, iv1);
10538 ElTran (dim, is1, is2, a, iv1, z);
10539 ierr = Hqr2 (dim, is1, is2, a, wr, wi, z);
10541 BalBak (dim, is1, is2, fv1, dim, z);
10547 /*---------------------------------------------------------------------------------
10551 | Given a real general matrix, this subroutine
10552 | reduces a submatrix situated in rows and columns
10553 | low through high to upper Hessenberg form by
10554 | stabilized elementary similarity transformations.
10558 | * dim is the order of the matrix
10560 | * low and high are integers determined by the balancing
10561 | subroutine balanc. if balanc has not been used,
10562 | set low=1, high=dim.
10564 | * a contains the input matrix.
10568 | * a contains the hessenberg matrix. The multipliers
10569 | which were used in the reduction are stored in the
10570 | remaining triangle under the hessenberg matrix.
10572 | * interchanged contains information on the rows and columns
10573 | interchanged in the reduction.
10575 | Only elements low through high are used.
10577 ---------------------------------------------------------------------------------*/
10578 void ElmHes (int dim, int low, int high, MrBFlt **a, int *interchanged)
10580 int i, j, m, la, mm1, kp1, mp1;
10586 return; /* remove goto statement, which exits at bottom of function */
10588 for (m=kp1; m<=la; m++)
10594 for (j=m; j<=high; j++)
10596 if (fabs(a[j][mm1]) > fabs(x)) /* change direction of inequality */
10597 { /* remove goto statement */
10603 interchanged[m] = i;
10604 if (i != m) /* change "==" to "!=", eliminating goto statement */
10606 /* interchange rows and columns of a */
10607 for (j=mm1; j<dim; j++)
10613 for (j=0; j<=high; j++)
10621 if (AreDoublesEqual(x, 0.0, ETA)==NO) /* change "==" to "!=", eliminating goto statement */
10625 for (i=mp1; i<=high; i++)
10628 if (AreDoublesEqual(y, 0.0, ETA)==NO) /* != 0.0 */
10632 for (j = m; j < dim; j++)
10633 a[i][j] -= y * a[m][j];
10634 for (j = 0; j <= high; j++)
10635 a[j][m] += y * a[j][i];
10642 /* begin f2c version of code:
10643 elmhes.f -- translated by f2c (version 19971204) */
10644 int elmhes (int *nm, int *n, int *low, int *igh, MrBFlt *a, int *int__)
10648 /*system generated locals */
10649 int a_dim1, a_offset, i__1, i__2, i__3;
10652 /* local variables */
10653 static int i__, j, m;
10654 static MrBFlt x, y;
10655 static int la, mm1, kp1, mp1;
10657 /* parameter adjustments */
10659 a_offset = a_dim1 + 1;
10663 /* function body */
10670 for (m = kp1; m <= i__1; ++m)
10676 for (j = m; j <= i__2; ++j)
10678 if ((d__1 = a[j + mm1 * a_dim1], abs(d__1)) <= abs(x))
10680 x = a[j + mm1 * a_dim1];
10690 /* .......... interchange rows and columns of a.......... */
10692 for (j = mm1; j <= i__2; ++j)
10694 y = a[i__ + j * a_dim1];
10695 a[i__ + j * a_dim1] = a[m + j * a_dim1];
10696 a[m + j * a_dim1] = y;
10701 for (j = 1; j <= i__2; ++j)
10703 y = a[j + i__ * a_dim1];
10704 a[j + i__ * a_dim1] = a[j + m * a_dim1];
10705 a[j + m * a_dim1] = y;
10709 /* .......... end interchange .......... */
10716 for (i__ = mp1; i__ <= i__2; ++i__)
10718 y = a[i__ + mm1 * a_dim1];
10722 a[i__ + mm1 * a_dim1] = y;
10725 for (j = m; j <= i__3; ++j)
10728 a[i__ + j * a_dim1] -= y * a[m + j * a_dim1];
10732 for (j = 1; j <= i__3; ++j)
10735 a[j + m * a_dim1] += y * a[j + i__ * a_dim1];
10750 /* end f2c version of code */
10756 /*---------------------------------------------------------------------------------
10760 | This subroutine accumulates the stabilized elementary
10761 | similarity transformations used in the reduction of a
10762 | real general matrix to upper Hessenberg form by ElmHes.
10766 | * dim is the order of the matrix.
10768 | * low and high are integers determined by the balancing
10769 | subroutine balanc. If Balanc has not been used,
10770 | set low=0, high=dim-1.
10772 | * a contains the multipliers which were used in the
10773 | reduction by ElmHes in its lower triangle
10774 | below the subdiagonal.
10776 | * interchanged contains information on the rows and columns
10777 | interchanged in the reduction by ElmHes.
10778 | only elements low through high are used.
10782 | * z contains the transformation matrix produced in the
10783 | reduction by ElmHes.
10785 | This routine is a translation of the Algol procedure from
10786 | Handbook for Automatic Computation, vol. II, Linear Algebra,
10787 | by Wilkinson and Reinsch, Springer-Verlag.
10789 ---------------------------------------------------------------------------------*/
10790 void ElTran (int dim, int low, int high, MrBFlt **a, int *interchanged, MrBFlt **z)
10794 /* initialize z to identity matrix */
10795 for (j=0; j<dim; j++)
10797 for (i=0; i<dim; i++)
10801 for (mp=high-1; mp>=low+1; mp--) /* there were a number of additional */
10802 { /* variables (kl, la, m, mm, mp1) that */
10803 for (i=mp+1; i<=high; i++) /* have been eliminated here simply by */
10804 z[i][mp] = a[i][mp-1]; /* initializing variables appropriately */
10805 i = interchanged[mp]; /* in the loops */
10806 if (i != mp) /* change "==" to "!=" to eliminate a goto statement */
10808 for (j=mp; j<=high; j++)
10810 z[mp][j] = z[i][j];
10818 /* begin f2c version of code:
10819 eltran.f -- translated by f2c (version 19971204) */
10820 int eltran (int *nm, int *n, int *low, int *igh, MrBFlt *a, int *int__, MrBFlt *z__)
10824 /* system generated locals */
10825 int a_dim1, a_offset, z_dim1, z_offset, i__1, i__2;
10827 /* local variables */
10828 static int i__, j, kl, mm, mp, mp1;
10830 /* .......... initialize z to identity matrix .......... */
10832 /* parameter adjustments */
10834 z_offset = z_dim1 + 1;
10838 a_offset = a_dim1 + 1;
10841 /* function Body */
10843 for (j = 1; j <= i__1; ++j)
10846 for (i__ = 1; i__ <= i__2; ++i__)
10849 z__[i__ + j * z_dim1] = 0.0;
10851 z__[j + j * z_dim1] = 1.0;
10855 kl = *igh - *low - 1;
10859 /* .......... for mp=igh-1 step -1 until low+1 do -- .......... */
10861 for (mm = 1; mm <= i__1; ++mm)
10866 for (i__ = mp1; i__ <= i__2; ++i__)
10869 z__[i__ + mp * z_dim1] = a[i__ + (mp - 1) * a_dim1];
10875 for (j = mp; j <= i__2; ++j)
10877 z__[mp + j * z_dim1] = z__[i__ + j * z_dim1];
10878 z__[i__ + j * z_dim1] = 0.;
10881 z__[i__ + mp * z_dim1] = 1.;
10890 /* end f2c version of code */
10896 /*---------------------------------------------------------------------------------
10900 ---------------------------------------------------------------------------------*/
10901 void Exchange (int j, int k, int l, int m, int n, MrBFlt **a, MrBFlt *scale)
10906 scale[m] = (MrBFlt)j;
10909 for (i = 0; i <= l; i++)
10915 for (i = k; i < n; i++)
10925 /*---------------------------------------------------------------------------------
10931 ---------------------------------------------------------------------------------*/
10932 MrBFlt Factorial (int x)
10938 for (i=0; i<x; i++)
10947 /*---------------------------------------------------------------------------------
10949 | ForwardSubstitutionRow
10951 ---------------------------------------------------------------------------------*/
10952 void ForwardSubstitutionRow (int dim, MrBFlt **L, MrBFlt *b)
10957 b[0] = b[0] / L[0][0];
10958 for (i=1; i<dim; i++)
10961 for (j=0; j<i; j++)
10962 dotProduct += L[i][j] * b[j];
10963 b[i] = (b[i] - dotProduct) / L[i][i];
10968 /*---------------------------------------------------------------------------------
10970 | FreeSquareComplexMatrix
10972 | Frees a matrix of complex numbers.
10974 ---------------------------------------------------------------------------------*/
10975 void FreeSquareComplexMatrix (complex **m)
10977 free((char *) (m[0]));
10978 free((char *) (m));
10982 /*---------------------------------------------------------------------------------
10984 | FreeSquareDoubleMatrix
10986 | Frees a matrix of doubles.
10988 ---------------------------------------------------------------------------------*/
10989 void FreeSquareDoubleMatrix (MrBFlt **m)
10991 free((char *) (m[0]));
10992 free((char *) (m));
10996 /*---------------------------------------------------------------------------------
10998 | FreeSquareIntegerMatrix
11000 | Frees a matrix of integers.
11002 ---------------------------------------------------------------------------------*/
11003 void FreeSquareIntegerMatrix (int **m)
11005 free((char *) (m[0]));
11006 free((char *) (m));
11010 /*---------------------------------------------------------------------------------
11012 | GammaRandomVariable
11014 | This function generates a gamma-distributed random variable with parameters
11015 | a and b. The mean is E(X) = a / b and the variance is Var(X) = a / b^2.
11017 ---------------------------------------------------------------------------------*/
11018 MrBFlt GammaRandomVariable (MrBFlt a, MrBFlt b, RandLong *seed)
11020 return (RndGamma (a, seed) / b);
11024 /*---------------------------------------------------------------------------------
11026 | GaussianElimination
11028 ---------------------------------------------------------------------------------*/
11029 void GaussianElimination (int dim, MrBFlt **a, MrBFlt **bMat, MrBFlt **xMat)
11032 MrBFlt *bVec, **lMat, **uMat;
11034 lMat = AllocateSquareDoubleMatrix (dim);
11035 uMat = AllocateSquareDoubleMatrix (dim);
11036 bVec = (MrBFlt *) SafeMalloc ((size_t)dim * sizeof(MrBFlt));
11039 MrBayesPrint ("%s Error: Problem allocating bVec\n", spacer);
11043 ComputeLandU (dim, a, lMat, uMat);
11045 for (k=0; k<dim; k++)
11048 for (i=0; i<dim; i++)
11049 bVec[i] = bMat[i][k];
11051 /* Answer of Ly = b (which is solving for y) is copied into b. */
11052 ForwardSubstitutionRow (dim, lMat, bVec);
11054 /* Answer of Ux = y (solving for x and the y was copied into b above)
11055 is also copied into b. */
11056 BackSubstitutionRow (dim, uMat, bVec);
11058 for (i=0; i<dim; i++)
11059 xMat[i][k] = bVec[i];
11063 FreeSquareDoubleMatrix (lMat);
11064 FreeSquareDoubleMatrix (uMat);
11069 /*---------------------------------------------------------------------------------
11073 | returns NO if non complex eigendecomposition, YES if complex eigendecomposition, ABORT if an error has occured
11075 ---------------------------------------------------------------------------------*/
11076 int GetEigens (int dim, MrBFlt **q, MrBFlt *eigenValues, MrBFlt *eigvalsImag, MrBFlt **eigvecs, MrBFlt **inverseEigvecs, complex **Ceigvecs, complex **CinverseEigvecs)
11078 int i, j, rc, *iWork, isComplex;
11079 MrBFlt **tempWork, *dWork;
11080 complex **cWork, *Ccol;
11082 /* allocate memory */
11083 dWork = (MrBFlt *) SafeMalloc ((size_t)dim * sizeof(MrBFlt));
11084 iWork = (int *) SafeMalloc ((size_t)dim * sizeof(int));
11085 if (!dWork || !iWork)
11087 MrBayesPrint ("%s Error: Problem in GetEigens\n", spacer);
11091 /* calculate eigenvalues and eigenvectors */
11093 rc = ComputeEigenSystem (dim, q, eigenValues, eigvalsImag, eigvecs, iWork, dWork);
11094 if (rc != NO_ERROR)
11096 if (rc == EVALUATE_COMPLEX_NUMBERS)
11102 /* invert eigenvectors */
11103 if (isComplex == NO)
11105 tempWork = AllocateSquareDoubleMatrix (dim);
11106 CopyDoubleMatrices (dim, eigvecs, tempWork);
11107 InvertMatrix (dim, tempWork, dWork, iWork, inverseEigvecs);
11108 FreeSquareDoubleMatrix (tempWork);
11110 else if (isComplex == YES)
11112 for (i=0; i<dim; i++)
11114 if (fabs(eigvalsImag[i])<1E-20) /* == 0.0 */
11116 for (j=0; j<dim; j++)
11118 Ceigvecs[j][i].re = eigvecs[j][i];
11119 Ceigvecs[j][i].im = 0.0;
11122 else if (eigvalsImag[i] > 0)
11124 for (j=0; j<dim; j++)
11126 Ceigvecs[j][i].re = eigvecs[j][i];
11127 Ceigvecs[j][i].im = eigvecs[j][i + 1];
11130 else if (eigvalsImag[i] < 0)
11132 for (j=0; j<dim; j++)
11134 Ceigvecs[j][i].re = eigvecs[j][i-1];
11135 Ceigvecs[j][i].im = -eigvecs[j][i];
11139 Ccol = (complex *) SafeMalloc ((size_t)dim * sizeof(complex));
11142 MrBayesPrint ("%s Error: Problem in GetEigens\n", spacer);
11145 cWork = AllocateSquareComplexMatrix (dim);
11146 CopyComplexMatrices (dim, Ceigvecs, cWork);
11147 ComplexInvertMatrix (dim, cWork, dWork, iWork, CinverseEigvecs, Ccol);
11149 FreeSquareComplexMatrix (cWork);
11155 return (isComplex);
11159 /*---------------------------------------------------------------------------------
11163 | This subroutine finds the eigenvalues and eigenvectors
11164 | of a real upper Hessenberg matrix by the QR method. The
11165 | eigenvectors of a real general matrix can also be found
11166 | if ElmHes and ElTran or OrtHes and OrTran have
11167 | been used to reduce this general matrix to Hessenberg form
11168 | and to accumulate the similarity transformations.
11172 | * dim is the order of the matrix.
11174 | * low and high are integers determined by the balancing
11175 | subroutine balanc. If balanc has not been used,
11176 | set low=0, high=dim-1.
11178 | * h contains the upper hessenberg matrix. Information about
11179 | the transformations used in the reduction to Hessenberg
11180 | form by ElmHes or OrtHes, if performed, is stored
11181 | in the remaining triangle under the Hessenberg matrix.
11185 | * h has been destroyed.
11187 | * wr and wi contain the real and imaginary parts,
11188 | respectively, of the eigenvalues. The eigenvalues
11189 | are unordered except that complex conjugate pairs
11190 | of values appear consecutively with the eigenvalue
11191 | having the positive imaginary part first. If an
11192 | error exit is made, the eigenvalues should be correct
11193 | for indices j,...,dim-1.
11195 | * z contains the transformation matrix produced by ElTran
11196 | after the reduction by ElmHes, or by OrTran after the
11197 | reduction by OrtHes, if performed. If the eigenvectors
11198 | of the Hessenberg matrix are desired, z must contain the
11201 | Calls ComplexDivision2 for complex division.
11203 | This function returns:
11204 | zero for normal return,
11205 | j if the limit of 30*n iterations is exhausted
11206 | while the j-th eigenvalue is being sought.
11208 | This subroutine is a translation of the ALGOL procedure HQR2,
11209 | Num. Math. 14, 219,231(1970) by Martin, Peters, and Wilkinson.
11210 | Handbook for Automatic Computation, vol. II - Linear Algebra,
11211 | pp. 357-391 (1971).
11213 ---------------------------------------------------------------------------------*/
11214 int Hqr2 (int dim, int low, int high, MrBFlt **h, MrBFlt *wr, MrBFlt *wi, MrBFlt **z)
11216 int i, j, k, l, m, na, en, notlas, mp2, itn, its, enm2, twoRoots;
11217 MrBFlt norm, p=0.0, q=0.0, r=0.0, s=0.0, t, w=0.0, x, y=0.0, ra, sa, vi, vr, zz=0.0, tst1, tst2;
11220 k = 0; /* used for array indexing. FORTRAN version: k = 1 */
11222 /* store roots isolated by balance, and compute matrix norm */
11223 for (i=0; i<dim; i++)
11225 for (j=k; j<dim; j++)
11226 norm += fabs(h[i][j]);
11229 if ((i < low) || (i > high))
11239 /* search for next eigenvalues */
11240 while (en >= low) /* changed from an "if (en < lo)" to eliminate a goto statement */
11249 for (l=en; l>low; l--) /* changed indexing, got rid of lo, ll */
11251 s = fabs(h[l-1][l-1]) + fabs(h[l][l]);
11252 if (AreDoublesEqual(s, 0.0, ETA)==YES) /* == 0.0 */
11255 tst2 = tst1 + fabs(h[l][l-1]);
11256 if (fabs(tst2 - tst1) < ETA) /* tst2 == tst1 */
11257 break; /* changed to break to remove a goto statement */
11262 if (l == en) /* changed to break to remove a goto statement */
11265 w = h[en][na] * h[na][en];
11266 if (l == na) /* used to return to other parts of the code */
11274 /* form exceptional shift */
11275 if ((its == 10) || (its == 20)) /* changed to remove a goto statement */
11278 for (i = low; i <= en; i++)
11280 s = fabs(h[en][na]) + fabs(h[na][enm2]);
11283 w = -0.4375 * s * s;
11288 /* look for two consecutive small sub-diagonal elements */
11289 for (m=enm2; m>=l; m--)
11291 /* removed m = enm2 + l - mm and above loop to remove variables */
11295 p = (r * s - w) / h[m+1][m] + h[m][m+1];
11296 q = h[m+1][m+1] - zz - r - s;
11298 s = fabs(p) + fabs(q) + fabs(r);
11303 break; /* changed to break to remove a goto statement */
11304 tst1 = fabs(p) * (fabs(h[m-1][m-1]) + fabs(zz) + fabs(h[m+1][m+1]));
11305 tst2 = tst1 + fabs(h[m][m-1]) * (fabs(q) + fabs(r));
11306 if (fabs(tst2 - tst1) < ETA) /* tst2 == tst1 */
11307 break; /* changed to break to remove a goto statement */
11311 for (i = mp2; i <= en; i++)
11314 if (i != mp2) /* changed "==" to "!=" to remove a goto statement */
11318 /* MrBFlt QR step involving rows l to en and columns m to en */
11319 for (k=m; k<=na; k++)
11321 notlas = (k != na);
11322 if (k != m) /* changed "==" to "!=" to remove a goto statement */
11329 x = fabs(p) + fabs(q) + fabs(r);
11330 if (x < ETA) /* == 0.0 */
11331 continue; /* changed to continue remove a goto statement */
11337 /*s = sqrt(p*p+q*q+r*r);
11338 sgn = (p<0)?-1:(p>0);
11339 s = sgn*sqrt(p*p+q*q+r*r);*/
11340 s = D_sign(sqrt(p*p + q*q + r*r), p);
11341 if (k != m) /* changed "==" to "!=" to remove a goto statement */
11342 h[k][k-1] = -s * x;
11343 else if (l != m) /* else if gets rid of another goto statement */
11344 h[k][k-1] = -h[k][k-1];
11351 if (!notlas) /* changed to !notlas to remove goto statement (see **) */
11353 /* row modification */
11354 for (j=k; j<dim; j++)
11356 p = h[k][j] + q * h[k+1][j];
11358 h[k+1][j] -= p * y;
11360 j = MIN(en, k + 3);
11362 /* column modification */
11363 for (i=0; i<=j; i++)
11365 p = x * h[i][k] + y * h[i][k+1];
11367 h[i][k+1] -= p * q;
11370 /* accumulate transformations */
11371 for (i=low; i<=high; i++)
11373 p = x * z[i][k] + y * z[i][k+1];
11375 z[i][k+1] -= p * q;
11378 else /* (**) also put in else */
11380 /* row modification */
11381 for (j=k; j<dim; j++)
11383 p = h[k][j] + q * h[k+1][j] + r * h[k+2][j];
11385 h[k+1][j] -= p * y;
11386 h[k+2][j] -= p * zz;
11388 j = MIN(en, k + 3);
11390 /* column modification */
11391 for (i = 0; i <= j; i++)
11393 p = x * h[i][k] + y * h[i][k+1] + zz * h[i][k+2];
11395 h[i][k+1] -= p * q;
11396 h[i][k+2] -= p * r;
11399 /* accumulate transformations */
11400 for (i = low; i <= high; i++)
11402 p = x * z[i][k] + y * z[i][k+1] + zz * z[i][k+2];
11404 z[i][k+1] -= p * q;
11405 z[i][k+2] -= p * r;
11413 /* two roots found */
11416 zz = sqrt(fabs(q));
11420 if (q >= -1e-12) /* change "<" to ">=", and also change "0.0" to */
11421 { /* a small number (Swofford's change) */
11423 zz = p + D_sign(zz, p);
11426 if (fabs(zz) > ETA) /* != 0.0 */
11431 s = fabs(x) + fabs(zz);
11434 r = sqrt(p*p + q*q);
11438 /* row modification */
11439 for (j=na; j<dim; j++)
11442 h[na][j] = q * zz + p * h[en][j];
11443 h[en][j] = q * h[en][j] - p * zz;
11446 /* column modification */
11447 for (i = 0; i <= en; i++)
11450 h[i][na] = q * zz + p * h[i][en];
11451 h[i][en] = q * h[i][en] - p * zz;
11454 /* accumulate transformations */
11455 for (i = low; i <= high; i++)
11458 z[i][na] = q * zz + p * z[i][en];
11459 z[i][en] = q * z[i][en] - p * zz;
11474 /* one root found */
11476 wr[en] = h[en][en];
11482 if (fabs(norm) < ETA) /* == 0.0 */
11483 return (0); /* was a goto end of function */
11485 for (en=dim-1; en>=0; en--)
11487 /*en = n - nn - 1; and change for loop */
11494 /* last vector component chosen imaginary so that eigenvector
11495 matrix is triangular */
11497 if (fabs(h[en][na]) > fabs(h[na][en]))
11499 h[na][na] = q / h[en][na];
11500 h[na][en] = -(h[en][en] - p) / h[en][na];
11503 ComplexDivision2 (0.0, -h[na][en], h[na][na] - p, q, &h[na][na], &h[na][en]);
11508 if (enm2 >= 0) /* changed direction to remove goto statement */
11510 for (i=enm2; i>=0; i--)
11516 for (j=m; j<=en; j++)
11518 ra += h[i][j] * h[j][na];
11519 sa += h[i][j] * h[j][en];
11522 if (wi[i] < 0.0) /* changed direction to remove goto statement */
11531 if (fabs(wi[i])<ETA) /* == 0.0 */ /* changed direction to remove goto statement */
11532 ComplexDivision2 (-ra, -sa, w, q, &h[i][na], &h[i][en]);
11535 /* solve complex equations */
11538 vr = (wr[i] - p) * (wr[i] - p) + wi[i] * wi[i] - q * q;
11539 vi = (wr[i] - p) * 2.0 * q;
11540 if ((fabs(vr)<ETA) && (fabs(vi)<ETA))
11542 tst1 = norm * (fabs(w) + fabs(q) + fabs(x) + fabs(y) + fabs(zz));
11548 while (tst2 > tst1); /* made into a do/while loop */
11550 ComplexDivision2 (x * r - zz * ra + q * sa, x * s - zz * sa - q * ra, vr, vi, &h[i][na], &h[i][en]);
11551 if (fabs(x) > fabs(zz) + fabs(q)) /* changed direction to remove goto statement */
11553 h[i+1][na] = (-ra - w * h[i][na] + q * h[i][en]) / x;
11554 h[i+1][en] = (-sa - w * h[i][en] - q * h[i][na]) / x;
11557 ComplexDivision2 (-r - y * h[i][na], -s - y * h[i][en], zz, q, &h[i+1][na], &h[i+1][en]);
11560 /* overflow control */
11561 tst1 = fabs(h[i][na]);
11562 tst2 = fabs(h[i][en]);
11563 t = MAX(tst1, tst2);
11564 if (t > ETA) /* t != 0.0 */
11567 tst2 = tst1 + 1.0 / tst1;
11570 for (j = i; j <= en; j++)
11581 else if (fabs(q)<ETA)
11588 for (i=na; i>=0; i--)
11592 for (j = m; j <= en; j++)
11593 r += h[i][j] * h[j][en];
11594 if (wi[i] < 0.0) /* changed direction to remove goto statement */
11598 continue; /* changed to continue to remove goto statement */
11603 if (fabs(wi[i])<ETA) /* changed to remove goto statement */
11606 if (fabs(t)<ETA) /* changed to remove goto statement */
11614 while (tst2 > tst1);
11620 /* solve real equations */
11623 q = (wr[i] - p) * (wr[i] - p) + wi[i] * wi[i];
11624 t = (x * s - zz * r) / q;
11626 if (fabs(x) > fabs(zz)) /* changed direction to remove goto statement */
11627 h[i+1][en] = (-r - w * t) / x;
11629 h[i+1][en] = (-s - y * t) / zz;
11632 /* overflow control */
11633 t = fabs(h[i][en]);
11637 tst2 = tst1 + 1. / tst1;
11640 for (j = i; j <= en; j++)
11650 for (i=0; i<dim; i++)
11652 if ((i < low) || (i > high)) /* changed to rid goto statement */
11654 for (j=i; j<dim; j++)
11659 /* multiply by transformation matrix to give vectors of original
11661 for (j=dim-1; j>=low; j--)
11664 for (i=low; i<=high; i++)
11667 for (k = low; k <= m; k++)
11668 zz += z[i][k] * h[k][j];
11676 int hqr2 (int *nm, int *n, int *low, int *igh, MrBFlt *h__, MrBFlt *wr, MrBFlt *wi, MrBFlt *z__, int *ierr)
11680 /* system generated locals */
11681 int h_dim1, h_offset, z_dim1, z_offset, i__1, i__2, i__3;
11682 MrBFlt d__1, d__2, d__3, d__4;
11684 /* builtin functions */
11685 MrBFlt sqrt(doublereal), d_sign(doublereal *, doublereal *);
11687 /* Local variables */
11688 static MrBFlt norm;
11689 static int i__, j, k, l, m;
11690 static MrBFlt p, q, r__, s, t, w, x, y;
11691 static int na, ii, en, jj;
11692 static MrBFlt ra, sa;
11693 static int ll, mm, nn;
11694 static MrBFlt vi, vr, zz;
11695 static logical notlas;
11696 static int mp2, itn, its, enm2;
11697 static MrBFlt tst1, tst2;
11699 /* parameter adjustments */
11701 z_offset = z_dim1 + 1;
11706 h_offset = h_dim1 + 1;
11709 /* function Body */
11714 /* .......... store roots isolated by balanc and compute matrix norm .......... */
11716 for (i__ = 1; i__ <= i__1; ++i__)
11719 for (j = k; j <= i__2; ++j)
11722 norm += (d__1 = h__[i__ + j * h_dim1], abs(d__1));
11725 if (i__ >= *low && i__ <= *igh)
11727 wr[i__] = h__[i__ + i__ * h_dim1];
11737 /* ..........search for next eigenvalues.......... */
11745 /* ..........look for single small sub-diagonal element for l=en step -1 until low do -- .......... */
11748 for (ll = *low; ll <= i__1; ++ll)
11750 l = en + *low - ll;
11753 s = (d__1 = h__[l - 1 + (l - 1) * h_dim1], abs(d__1)) + (d__2 = h__[l + l * h_dim1], abs(d__2));
11757 tst2 = tst1 + (d__1 = h__[l + (l - 1) * h_dim1], abs(d__1));
11763 /* .......... form shift .......... */
11765 x = h__[en + en * h_dim1];
11768 y = h__[na + na * h_dim1];
11769 w = h__[en + na * h_dim1] * h__[na + en * h_dim1];
11774 if (its != 10 && its != 20)
11777 /* .......... form exceptional shift .......... */
11781 for (i__ = *low; i__ <= i__1; ++i__)
11784 h__[i__ + i__ * h_dim1] -= x;
11787 s = (d__1 = h__[en + na * h_dim1], abs(d__1)) + (d__2 = h__[na + enm2 * h_dim1], abs(d__2));
11790 w = s * -0.4375 * s;
11795 /* .......... look for two consecutive small sub-diagonal elements for m=en-2 step -1 until l do -- .......... */
11797 for (mm = l; mm <= i__1; ++mm)
11800 zz = h__[m + m * h_dim1];
11803 p = (r__ * s - w) / h__[m + 1 + m * h_dim1] + h__[m + (m + 1) * h_dim1];
11804 q = h__[m + 1 + (m + 1) * h_dim1] - zz - r__ - s;
11805 r__ = h__[m + 2 + (m + 1) * h_dim1];
11806 s = abs(p) + abs(q) + abs(r__);
11812 tst1 = abs(p) * ((d__1 = h__[m - 1 + (m - 1) * h_dim1], abs(d__1)) +
11813 abs(zz) + (d__2 = h__[m + 1 + (m + 1) * h_dim1], abs(d__2)));
11814 tst2 = tst1 + (d__1 = h__[m + (m - 1) * h_dim1], abs(d__1)) * (abs(q) + abs(r__));
11823 for (i__ = mp2; i__ <= i__1; ++i__)
11825 h__[i__ + (i__ - 2) * h_dim1] = 0.0;
11828 h__[i__ + (i__ - 3) * h_dim1] = 0.;
11833 /* .......... MrBFlt qr step involving rows l to en and columns m to en .......... */
11835 for (k = m; k <= i__1; ++k)
11840 p = h__[k + (k - 1) * h_dim1];
11841 q = h__[k + 1 + (k - 1) * h_dim1];
11844 r__ = h__[k + 2 + (k - 1) * h_dim1];
11845 x = abs(p) + abs(q) + abs(r__);
11852 d__1 = sqrt(p * p + q * q + r__ * r__);
11853 s = d_sign(&d__1, &p);
11856 h__[k + (k - 1) * h_dim1] = -s * x;
11861 h__[k + (k - 1) * h_dim1] = -h__[k + (k - 1) * h_dim1];
11873 /* .......... row modification .......... */
11875 for (j = k; j <= i__2; ++j)
11877 p = h__[k + j * h_dim1] + q * h__[k + 1 + j * h_dim1];
11878 h__[k + j * h_dim1] -= p * x;
11879 h__[k + 1 + j * h_dim1] -= p * y;
11883 /* computing MIN */
11884 i__2 = en, i__3 = k + 3;
11885 j = min(i__2,i__3);
11887 /* .......... column modification .......... */
11889 for (i__ = 1; i__ <= i__2; ++i__)
11891 p = x * h__[i__ + k * h_dim1] + y * h__[i__ + (k + 1) * h_dim1];
11892 h__[i__ + k * h_dim1] -= p;
11893 h__[i__ + (k + 1) * h_dim1] -= p * q;
11897 /* .......... accumulate transformations .......... */
11899 for (i__ = *low; i__ <= i__2; ++i__)
11901 p = x * z__[i__ + k * z_dim1] + y * z__[i__ + (k + 1) * z_dim1];
11902 z__[i__ + k * z_dim1] -= p;
11903 z__[i__ + (k + 1) * z_dim1] -= p * q;
11909 /* .......... row modification .......... */
11911 for (j = k; j <= i__2; ++j)
11913 p = h__[k + j * h_dim1] + q * h__[k + 1 + j * h_dim1] + r__ * h__[k + 2 + j * h_dim1];
11914 h__[k + j * h_dim1] -= p * x;
11915 h__[k + 1 + j * h_dim1] -= p * y;
11916 h__[k + 2 + j * h_dim1] -= p * zz;
11920 /* computing MIN */
11921 i__2 = en, i__3 = k + 3;
11922 j = min(i__2,i__3);
11924 /* .......... column modification .......... */
11926 for (i__ = 1; i__ <= i__2; ++i__)
11928 p = x * h__[i__ + k * h_dim1] + y * h__[i__ + (k + 1) * h_dim1] +
11929 zz * h__[i__ + (k + 2) * h_dim1];
11930 h__[i__ + k * h_dim1] -= p;
11931 h__[i__ + (k + 1) * h_dim1] -= p * q;
11932 h__[i__ + (k + 2) * h_dim1] -= p * r__;
11936 /* .......... accumulate transformations .......... */
11938 for (i__ = *low; i__ <= i__2; ++i__)
11940 p = x * z__[i__ + k * z_dim1] + y * z__[i__ + (k + 1) * z_dim1] + zz * z__[i__ + (k + 2) * z_dim1];
11941 z__[i__ + k * z_dim1] -= p;
11942 z__[i__ + (k + 1) * z_dim1] -= p * q;
11943 z__[i__ + (k + 2) * z_dim1] -= p * r__;
11952 /* .......... one root found .......... */
11954 h__[en + en * h_dim1] = x + t;
11955 wr[en] = h__[en + en * h_dim1];
11960 /* .......... two roots found .......... */
11964 zz = sqrt((abs(q)));
11965 h__[en + en * h_dim1] = x + t;
11966 x = h__[en + en * h_dim1];
11967 h__[na + na * h_dim1] = y + t;
11971 /* .......... real pair .......... */
11972 zz = p + d_sign(&zz, &p);
11977 wr[en] = x - w / zz;
11981 x = h__[en + na * h_dim1];
11982 s = abs(x) + abs(zz);
11985 r__ = sqrt(p * p + q * q);
11989 /* .......... row modification .......... */
11991 for (j = na; j <= i__1; ++j)
11993 zz = h__[na + j * h_dim1];
11994 h__[na + j * h_dim1] = q * zz + p * h__[en + j * h_dim1];
11995 h__[en + j * h_dim1] = q * h__[en + j * h_dim1] - p * zz;
11999 /* .......... column modification .......... */
12001 for (i__ = 1; i__ <= i__1; ++i__)
12003 zz = h__[i__ + na * h_dim1];
12004 h__[i__ + na * h_dim1] = q * zz + p * h__[i__ + en * h_dim1];
12005 h__[i__ + en * h_dim1] = q * h__[i__ + en * h_dim1] - p * zz;
12009 /* .......... accumulate transformations .......... */
12011 for (i__ = *low; i__ <= i__1; ++i__)
12013 zz = z__[i__ + na * z_dim1];
12014 z__[i__ + na * z_dim1] = q * zz + p * z__[i__ + en * z_dim1];
12015 z__[i__ + en * z_dim1] = q * z__[i__ + en * z_dim1] - p * zz;
12020 /* .......... complex pair .......... */
12030 /* .......... all roots found. backsubstitute to find vectors of upper triangular form .......... */
12035 /* .......... for en=n step -1 until 1 do -- .......... */
12037 for (nn = 1; nn <= i__1; ++nn)
12050 /* .......... real vector .......... */
12053 h__[en + en * h_dim1] = 1.0;
12057 /* .......... for i=en-1 step -1 until 1 do -- .......... */
12059 for (ii = 1; ii <= i__2; ++ii)
12062 w = h__[i__ + i__ * h_dim1] - p;
12066 for (j = m; j <= i__3; ++j)
12069 r__ += h__[i__ + j * h_dim1] * h__[j + en * h_dim1];
12072 if (wi[i__] >= 0.0)
12079 if (wi[i__] != 0.0)
12092 h__[i__ + en * h_dim1] = -r__ / t;
12095 /* .......... solve real equations .......... */
12097 x = h__[i__ + (i__ + 1) * h_dim1];
12098 y = h__[i__ + 1 + i__ * h_dim1];
12099 q = (wr[i__] - p) * (wr[i__] - p) + wi[i__] * wi[i__];
12100 t = (x * s - zz * r__) / q;
12101 h__[i__ + en * h_dim1] = t;
12102 if (abs(x) <= abs(zz))
12104 h__[i__ + 1 + en * h_dim1] = (-r__ - w * t) / x;
12107 h__[i__ + 1 + en * h_dim1] = (-s - y * t) / zz;
12109 /* .......... overflow control .......... */
12111 t = (d__1 = h__[i__ + en * h_dim1], abs(d__1));
12115 tst2 = tst1 + 1.0 / tst1;
12119 for (j = i__; j <= i__3; ++j)
12121 h__[j + en * h_dim1] /= t;
12129 /* .......... end real vector .......... */
12132 /* .......... complex vector .......... */
12136 /* .......... last vector component chosen imaginary so that eigenvector matrix is triangular .......... */
12137 if ((d__1 = h__[en + na * h_dim1], abs(d__1)) <= (d__2 = h__[na + en *
12138 h_dim1], abs(d__2)))
12140 h__[na + na * h_dim1] = q / h__[en + na * h_dim1];
12141 h__[na + en * h_dim1] = -(h__[en + en * h_dim1] - p) / h__[en + na * h_dim1];
12144 d__1 = -h__[na + en * h_dim1];
12145 d__2 = h__[na + na * h_dim1] - p;
12146 cdiv_(&c_b49, &d__1, &d__2, &q, &h__[na + na * h_dim1], &h__[na + en *
12149 h__[en + na * h_dim1] = 0.0;
12150 h__[en + en * h_dim1] = 1.0;
12155 /* .......... for i=en-2 step -1 until 1 do -- .......... */
12157 for (ii = 1; ii <= i__2; ++ii)
12160 w = h__[i__ + i__ * h_dim1] - p;
12165 for (j = m; j <= i__3; ++j)
12167 ra += h__[i__ + j * h_dim1] * h__[j + na * h_dim1];
12168 sa += h__[i__ + j * h_dim1] * h__[j + en * h_dim1];
12172 if (wi[i__] >= 0.0)
12180 if (wi[i__] != 0.0)
12184 cdiv_(&d__1, &d__2, &w, &q, &h__[i__ + na * h_dim1], &h__[i__ + en * h_dim1]);
12187 /* .......... solve complex equations .......... */
12189 x = h__[i__ + (i__ + 1) * h_dim1];
12190 y = h__[i__ + 1 + i__ * h_dim1];
12191 vr = (wr[i__] - p) * (wr[i__] - p) + wi[i__] * wi[i__] - q * q;
12192 vi = (wr[i__] - p) * 2.0 * q;
12193 if (vr != 0.0 || vi != 0.0)
12195 tst1 = norm * (abs(w) + abs(q) + abs(x) + abs(y) + abs(zz));
12203 d__1 = x * r__ - zz * ra + q * sa;
12204 d__2 = x * s - zz * sa - q * ra;
12205 cdiv_(&d__1, &d__2, &vr, &vi, &h__[i__ + na * h_dim1], &h__[i__ + en * h_dim1]);
12206 if (abs(x) <= abs(zz) + abs(q))
12208 h__[i__ + 1 + na * h_dim1] = (-ra - w * h__[i__ + na * h_dim1] + q * h__[i__ + en * h_dim1]) / x;
12209 h__[i__ + 1 + en * h_dim1] = (-sa - w * h__[i__ + en * h_dim1] - q * h__[i__ + na * h_dim1]) / x;
12212 d__1 = -r__ - y * h__[i__ + na * h_dim1];
12213 d__2 = -s - y * h__[i__ + en * h_dim1];
12214 cdiv_(&d__1, &d__2, &zz, &q, &h__[i__ + 1 + na * h_dim1], &h__[i__ + 1 + en * h_dim1]);
12216 /* .......... overflow control .......... */
12218 /* Computing MAX */
12219 d__3 = (d__1 = h__[i__ + na * h_dim1], abs(d__1)), d__4 = (d__2 = h__[i__ + en * h_dim1], abs(d__2));
12220 t = max(d__3,d__4);
12224 tst2 = tst1 + 1.0 / tst1;
12228 for (j = i__; j <= i__3; ++j)
12230 h__[j + na * h_dim1] /= t;
12231 h__[j + en * h_dim1] /= t;
12237 /* .......... end complex vector .......... */
12241 /* .......... end back substitution vectors of isolated roots .......... */
12243 for (i__ = 1; i__ <= i__1; ++i__)
12245 if (i__ >= *low && i__ <= *igh)
12248 for (j = i__; j <= i__2; ++j)
12251 z__[i__ + j * z_dim1] = h__[i__ + j * h_dim1];
12257 /* .......... multiply by transformation matrix to give vectors of original full matrix. */
12258 /* for j=n step -1 until low do -- .......... */
12260 for (jj = *low; jj <= i__1; ++jj)
12262 j = *n + *low - jj;
12266 for (i__ = *low; i__ <= i__2; ++i__)
12270 for (k = *low; k <= i__3; ++k)
12273 zz += z__[i__ + k * z_dim1] * h__[k + j * h_dim1];
12276 z__[i__ + j * z_dim1] = zz;
12282 /* .......... set error -- all eigenvalues have not converged after 30*n iterations .......... */
12289 /* end f2c version of code */
12295 MrBFlt IncompleteBetaFunction (MrBFlt alpha, MrBFlt beta, MrBFlt x)
12297 MrBFlt bt, gm1, gm2, gm3, temp;
12299 if (x < 0.0 || x > 1.0)
12301 MrBayesPrint ("%s Error: Problem in IncompleteBetaFunction.\n", spacer);
12304 if (fabs(x) < ETA || fabs(x-1.0)<ETA) /* x == 0.0 || x == 1.0 */
12310 gm1 = LnGamma (alpha + beta);
12311 gm2 = LnGamma (alpha);
12312 gm3 = LnGamma (beta);
12313 temp = gm1 - gm2 - gm3 + (alpha) * log(x) + (beta) * log(1.0 - x);
12316 if (x < (alpha + 1.0)/(alpha + beta + 2.0))
12317 return (bt * BetaCf(alpha, beta, x) / alpha);
12319 return (1.0 - bt * BetaCf(beta, alpha, 1.0-x) / beta);
12323 /*---------------------------------------------------------------------------------
12327 | Returns the incomplete gamma ratio I(x,alpha) where x is the upper
12328 | limit of the integration and alpha is the shape parameter. Returns (-1)
12331 | Bhattacharjee, G. P. 1970. The incomplete gamma integral. Applied
12332 | Statistics, 19:285-287 (AS32)
12334 ---------------------------------------------------------------------------------*/
12335 MrBFlt IncompleteGamma (MrBFlt x, MrBFlt alpha, MrBFlt LnGamma_alpha)
12338 MrBFlt p = alpha, g = LnGamma_alpha,
12339 accurate = 1e-8, overflow = 1e30,
12340 factor, gin = 0.0, rn = 0.0, a = 0.0, b = 0.0, an = 0.0,
12341 dif = 0.0, term = 0.0, pn[6];
12345 if (x < 0 || p <= 0)
12348 factor = exp(p*log(x)-x-g);
12358 if (term > accurate)
12376 for (i=0; i<2; i++)
12377 pn[i+4] = b*pn[i+2]-an*pn[i];
12378 if (fabs(pn[5]) < ETA)
12381 dif = fabs(gin-rn);
12384 if (dif<=accurate*rn)
12389 for (i=0; i<4; i++)
12391 if (fabs(pn[4]) < overflow)
12393 for (i=0; i<4; i++)
12397 gin = 1.0-factor*gin;
12403 /*---------------------------------------------------------------------------------
12407 | Calculates aInv = a^{-1} using LU-decomposition. The input matrix a is
12408 | destroyed in the process. The program returns an error if the matrix is
12409 | singular. col and indx are work vectors.
12411 ---------------------------------------------------------------------------------*/
12412 int InvertMatrix (int dim, MrBFlt **a, MrBFlt *col, int *indx, MrBFlt **aInv)
12416 rc = LUDecompose (dim, a, col, indx, (MrBFlt *)NULL);
12419 for (j = 0; j < dim; j++)
12421 for (i = 0; i < dim; i++)
12424 LUBackSubstitution (dim, a, indx, col);
12425 for (i = 0; i < dim; i++)
12426 aInv[i][j] = col[i];
12434 /*---------------------------------------------------------------------------------
12438 | L(h1,h2,r) = prob(x>h1, y>h2), where x and y are standard binormal,
12439 | with r=corr(x,y), error < 2e-7.
12441 | Drezner Z., and G.O. Wesolowsky (1990) On the computation of the
12442 | bivariate normal integral. J. Statist. Comput. Simul. 35:101-107.
12444 ---------------------------------------------------------------------------------*/
12445 MrBFlt LBinormal (MrBFlt h1, MrBFlt h2, MrBFlt r)
12448 MrBFlt x[]={0.04691008, 0.23076534, 0.5, 0.76923466, 0.95308992};
12449 MrBFlt w[]={0.018854042, 0.038088059, 0.0452707394,0.038088059,0.018854042};
12450 MrBFlt Lh=0.0, r1, r2, r3, rr, aa, ab, h3, h5, h6, h7, h12, temp1, temp2, exp1, exp2;
12452 h12 = (h1 * h1 + h2 * h2) / 2.0;
12453 if (fabs(r) >= 0.7)
12460 h7 = exp(-h3 / 2.0);
12461 if (fabs(r-1.0)>ETA) /* fabs(r) != 1.0 */
12464 h5 = h6 * h6 / 2.0;
12467 ab = 3.0 - 2.0 * aa * h5;
12469 if (temp1 < -100.0)
12473 Lh = 0.13298076 * h6 * ab * (1.0 - CdfNormal(h6)) - exp1 * (ab + aa * r2) * 0.053051647;
12474 for (i=0; i<5; i++)
12478 r2 = sqrt(1.0 - rr);
12480 if (temp1 < -100.0)
12484 temp2 = -h3 / (1.0 + r2);
12485 if (temp2 < -100.0)
12489 Lh -= w[i] * exp1 * (exp2 / r2 / h7 - 1.0 - aa * rr);
12493 Lh = Lh * r3 * h7 + (1.0 - CdfNormal(MAX(h1, h2)));
12495 Lh = (h1 < h2 ? CdfNormal(h2) - CdfNormal(h1) : 0) - Lh * r3 * h7;
12502 for (i=0; i<5; i++)
12505 r2 = 1.0 - r1 * r1;
12506 temp1 = (r1 * h3 - h12) / r2;
12507 if (temp1 < -100.0)
12511 Lh += w[i] * exp1 / sqrt(r2);
12514 Lh = (1.0 - CdfNormal(h1)) * (1.0 - CdfNormal(h2)) + r * Lh;
12520 /*---------------------------------------------------------------------------------
12522 | LnFactorial: Calculates the log of the factorial for an integer
12524 ---------------------------------------------------------------------------------*/
12525 MrBFlt LnFactorial (int value)
12532 for (i = 2; i<=value; i++)
12539 /*---------------------------------------------------------------------------------
12543 | Calculates the log of the gamma function. The Gamma function is equal
12546 | Gamma(alp) = {integral from 0 to infinity} t^{alp-1} e^-t dt
12548 | The result is accurate to 10 decimal places. Stirling's formula is used
12549 | for the central polynomial part of the procedure.
12551 | Pike, M. C. and I. D. Hill. 1966. Algorithm 291: Logarithm of the gamma
12552 | function. Communications of the Association for Computing
12553 | Machinery, 9:684.
12555 ---------------------------------------------------------------------------------*/
12556 MrBFlt LnGamma (MrBFlt alp)
12558 MrBFlt x = alp, f = 0.0, z;
12570 return (f + (x-0.5)*log(x) - x + 0.918938533204673 +
12571 (((-0.000595238095238*z+0.000793650793651)*z-0.002777777777778)*z +0.083333333333333)/x);
12575 /* Calculate probability of a realization for exponential random variable */
12576 MrBFlt LnPriorProbExponential (MrBFlt val, MrBFlt *params)
12578 return log(params[0]) - params[0] * val;
12582 /* Calculate probability of a realization for exponential random variable; parameter mean and not rate */
12583 MrBFlt LnPriorProbExponential_Param_Mean (MrBFlt val, MrBFlt *params)
12585 return - log(params[0]) - val / params[0];
12589 /* Calculate probability of a realization for a fixed variable */
12590 MrBFlt LnPriorProbFix (MrBFlt val, MrBFlt *params)
12592 if (fabs((val - params[0])/val) < 1E-5)
12595 return NEG_INFINITY;
12599 /* Calculate probability of a realization for gamma random variable */
12600 MrBFlt LnPriorProbGamma (MrBFlt val, MrBFlt *params)
12602 return (params[0] - 1) * log(val) + params[0] * log(params[1]) - params[1] * val - LnGamma(params[0]);
12606 /* Calculate probability of a realization for gamma random variable; parameters mean and sd */
12607 MrBFlt LnPriorProbGamma_Param_Mean_Sd (MrBFlt val, MrBFlt *params)
12609 MrBFlt alpha, beta;
12611 beta = params[0] / (params[1]*params[1]);
12612 alpha = params[0] * beta;
12614 return (alpha - 1) * log(val) + alpha * log(beta) - beta * val - LnGamma(alpha);
12618 /* Calculate probability of a realization for lognormal random variable */
12619 MrBFlt LnPriorProbLognormal (MrBFlt val, MrBFlt *params)
12623 z = (log(val) - params[0]) / params[1];
12625 return - log(params[1] * val * sqrt(2.0 * PI)) - z * z / 2.0;
12629 /* Calculate probability of a realization for lognormal random variable; parameters mean and sd on linear scale */
12630 MrBFlt LnPriorProbLognormal_Param_Mean_Sd (MrBFlt val, MrBFlt *params)
12632 MrBFlt z, mean_log, sd_log;
12634 sd_log = sqrt (log((params[1]*params[1])/(params[0]*params[0]) + 1));
12635 mean_log = log(params[0]) - sd_log * sd_log / 2.0;
12637 z= (log(val) - mean_log) / sd_log;
12639 return - log(sd_log * val * sqrt(2.0 * PI)) - z * z / 2.0;
12643 /* Calculate probability of a realization for normal random variable */
12644 MrBFlt LnPriorProbNormal (MrBFlt val, MrBFlt *params)
12648 z = (val - params[0]) / params[1];
12650 return - log(params[1] * sqrt(2.0 * PI)) - z * z / 2.0;
12654 /* Calculate probability of a realization for an offset exponential random variable */
12655 MrBFlt LnPriorProbOffsetExponential (MrBFlt val, MrBFlt *params)
12657 return log(params[1]) - params[1] * (val - params[0]);
12661 /* Calculate probability of a realization for an offset exponential random variable; parameters offset and mean */
12662 MrBFlt LnPriorProbOffsetExponential_Param_Offset_Mean (MrBFlt val, MrBFlt *params)
12666 x = val - params[0];
12667 rate = 1.0 / (params[1] - params[0]);
12669 return log(rate) - rate * x;
12673 /* Calculate probability of a realization for an offset gamma random variable */
12674 MrBFlt LnPriorProbOffsetGamma (MrBFlt val, MrBFlt *params)
12676 MrBFlt x, alpha, beta;
12678 x = val - params[0];
12682 return (alpha - 1) * log(x) + alpha * log(beta) - beta * x - LnGamma(alpha);
12686 /* Calculate probability of a realization for an offset gamma random variable; parameters offset, mean and sd */
12687 MrBFlt LnPriorProbOffsetGamma_Param_Offset_Mean_Sd (MrBFlt val, MrBFlt *params)
12689 MrBFlt x, mean, sd, alpha, beta;
12691 x = val - params[0];
12692 mean = params[1] - params[0];
12695 beta = mean / (sd*sd);
12696 alpha = mean * beta;
12698 return (alpha - 1) * log(x) + alpha * log(beta) - beta * x - LnGamma(alpha);
12702 /* Calculate probability of a realization for an offset lognormal random variable */
12703 MrBFlt LnPriorProbOffsetLognormal (MrBFlt val, MrBFlt *params)
12705 MrBFlt x, mean_log, sd_log, z;
12707 x = val - params[0];
12708 mean_log = params[1] - params[0];
12709 sd_log = params[2];
12711 z = (log(x) - mean_log) / sd_log;
12713 return - log(sd_log * x * sqrt(2.0 * PI)) - z * z / 2.0;
12717 /* Calculate probability of a realization for an offset lognormal random variable; parameters offset, mean and sd */
12718 MrBFlt LnPriorProbOffsetLognormal_Param_Offset_Mean_Sd (MrBFlt val, MrBFlt *params)
12720 MrBFlt x, mean, sd, mean_log, sd_log, z;
12722 x = val - params[0];
12723 mean = params[1] - params[0];
12725 sd_log = sqrt (log((sd*sd)/(mean*mean) + 1));
12726 mean_log = log(mean) - sd_log * sd_log / 2.0;
12728 z = (log(x) - mean_log) / sd_log;
12730 return - log(sd_log * x * sqrt(2.0 * PI)) - z * z / 2.0;
12734 /* Calculate probability of a realization for truncated (only positive values) normal random variable */
12735 MrBFlt LnPriorProbTruncatedNormal (MrBFlt val, MrBFlt *params)
12737 MrBFlt z, z_0, normConst;
12739 z = (val - params[0]) / params[1];
12740 z_0 = (0.0 - params[0]) / params[1];
12741 normConst = CdfNormal(z_0);
12743 return - log(params[1] * sqrt(2.0 * PI)) - z * z / 2.0 - log(1.0 - normConst);
12747 /* Calculate probability of a realization for arbitrarily truncated normal random variable; parameters truncation point, mean and sd */
12748 MrBFlt LnPriorProbTruncatedNormal_Param_Trunc_Mean_Sd (MrBFlt val, MrBFlt *params)
12750 MrBFlt z, z_trunc, normConst;
12752 z = (val - params[1]) / params[2];
12753 z_trunc = (params[0] - params[1]) / params[2];
12754 normConst = CdfNormal(z_trunc);
12756 return - log(params[2] * sqrt(2.0 * PI)) - z * z / 2.0 - log(1.0 - normConst);
12760 /* Calculate probability of a realization for uniform random variable */
12761 MrBFlt LnPriorProbUniform (MrBFlt val, MrBFlt *params)
12763 return - log(params[1] - params[0]);
12764 MrBayesPrint ("%lf", val); /* just because I am tired of seeing the unused parameter error msg */
12768 /* Calculate probability ratio of realizations for exponential random variable */
12769 MrBFlt LnProbRatioExponential (MrBFlt newX, MrBFlt oldX, MrBFlt *params)
12771 return params[0] * (oldX - newX);
12775 /* Calculate probability ratio of realizations for exponential random variable; parameter mean and not rate */
12776 MrBFlt LnProbRatioExponential_Param_Mean (MrBFlt newX, MrBFlt oldX, MrBFlt *params)
12778 return (oldX - newX) / params[0];
12782 /* Calculate probability of a realization for a fixed variable */
12783 MrBFlt LnProbRatioFix (MrBFlt newX, MrBFlt oldX, MrBFlt *params)
12785 if (fabs((newX - params[0])/newX) < 1E-5 && fabs((oldX - params[0])/oldX) < 1E-5)
12788 return NEG_INFINITY;
12792 /* Calculate probability ratio of realizations for gamma random variable */
12793 MrBFlt LnProbRatioGamma (MrBFlt newX, MrBFlt oldX, MrBFlt *params)
12795 MrBFlt alpha, beta;
12800 return (alpha - 1.0) * (log(newX) - log(oldX)) - beta * (newX - oldX);
12804 /* Calculate probability ratio of realizations for gamma random variable; parameters mean and sd */
12805 MrBFlt LnProbRatioGamma_Param_Mean_Sd (MrBFlt newX, MrBFlt oldX, MrBFlt *params)
12807 MrBFlt alpha, beta;
12809 beta = params[0] / (params[1]*params[1]);
12810 alpha = params[0] * beta;
12812 return (alpha - 1.0) * (log(newX) - log(oldX)) - beta * (newX - oldX);
12816 /* Calculate probability ratio of realizations for log normal random variable */
12817 MrBFlt LnProbRatioLognormal (MrBFlt newX, MrBFlt oldX, MrBFlt *params)
12821 newZ = (log(newX) - params[0]) / params[1];
12822 oldZ = (log(oldX) - params[0]) / params[1];
12824 return (oldZ * oldZ - newZ * newZ) / 2.0 + log(oldX) - log(newX);
12828 /* Calculate probability ratio of realizations for log normal random variable; parameters mean and sd */
12829 MrBFlt LnProbRatioLognormal_Param_Mean_Sd (MrBFlt newX, MrBFlt oldX, MrBFlt *params)
12831 MrBFlt newZ, oldZ, mean_log, sd_log;
12833 sd_log = sqrt (log((params[1]*params[1])/(params[0]*params[0]) + 1));
12834 mean_log = log(params[0]) - sd_log * sd_log / 2.0;
12836 newZ = (log(newX) - mean_log) / sd_log;
12837 oldZ = (log(oldX) - mean_log) / sd_log;
12839 return (oldZ * oldZ - newZ * newZ) / 2.0 + log(oldX) - log(newX);
12843 /* Calculate probability ratio of realizations for normal random variable */
12844 MrBFlt LnProbRatioNormal (MrBFlt newX, MrBFlt oldX, MrBFlt *params)
12848 newZ = (newX - params[0]) / params[1];
12849 oldZ = (oldX - params[0]) / params[1];
12851 return (oldZ * oldZ - newZ * newZ) / 2.0;
12855 /* Calculate probability ratio of realizations for offset exponential random variable */
12856 MrBFlt LnProbRatioOffsetExponential (MrBFlt newX, MrBFlt oldX, MrBFlt *params)
12858 return params[1] * (oldX - newX);
12862 /* Calculate probability ratio of realizations for offset exponential random variable; parameters offset and mean */
12863 MrBFlt LnProbRatioOffsetExponential_Param_Offset_Mean (MrBFlt newX, MrBFlt oldX, MrBFlt *params)
12865 return (oldX - newX) / (params[1] - params[0]);
12869 /* Calculate probability ratio of realizations for offset gamma random variable */
12870 MrBFlt LnProbRatioOffsetGamma (MrBFlt newX, MrBFlt oldX, MrBFlt *params)
12872 MrBFlt alpha, beta, newZ, oldZ;
12876 newZ = newX - params[0];
12877 oldZ = oldX - params[0];
12879 return (alpha - 1.0) * (log(newZ) - log(oldZ)) - beta * (newZ - oldZ);
12883 /* Calculate probability ratio of realizations for offset gamma random variable; parameters offset, mean and sd */
12884 MrBFlt LnProbRatioOffsetGamma_Param_Offset_Mean_Sd (MrBFlt newX, MrBFlt oldX, MrBFlt *params)
12886 MrBFlt mean, sd, alpha, beta;
12888 mean = params[1] - params[0];
12891 beta = mean / (sd*sd);
12892 alpha = mean * beta;
12897 return (alpha - 1.0) * (log(newX) - log(oldX)) - beta * (newX - oldX);
12901 /* Calculate probability ratio of realizations for offset lognormal random variable */
12902 MrBFlt LnProbRatioOffsetLognormal (MrBFlt newX, MrBFlt oldX, MrBFlt *params)
12904 MrBFlt newZ, oldZ, mean_log, sd_log;
12906 sd_log = params[2];
12907 mean_log = params[1];
12909 newZ = (log(newX-params[0]) - mean_log) / sd_log;
12910 oldZ = (log(oldX-params[0]) - mean_log) / sd_log;
12912 return (oldZ * oldZ - newZ * newZ) / 2.0 + log(oldX-params[0]) - log(newX-params[0]);
12916 /* Calculate probability ratio of realizations for offset lognormal random variable; parameters offset, mean and sd */
12917 MrBFlt LnProbRatioOffsetLognormal_Param_Offset_Mean_Sd (MrBFlt newX, MrBFlt oldX, MrBFlt *params)
12919 MrBFlt newZ, oldZ, mean, sd, mean_log, sd_log;
12921 mean = params[1] - params[0];
12923 sd_log = sqrt (log((sd*sd)/(mean*mean) + 1));
12924 mean_log = log(mean) - sd_log * sd_log / 2.0;
12928 newZ = (log(newX) - mean_log) / sd_log;
12929 oldZ = (log(oldX) - mean_log) / sd_log;
12931 return (oldZ * oldZ - newZ * newZ) / 2.0 - log(newX / oldX);
12935 /* Calculate probability ratio of realizations for truncated normal random variable */
12936 MrBFlt LnProbRatioTruncatedNormal (MrBFlt newX, MrBFlt oldX, MrBFlt *params)
12940 newZ = (newX - params[0]) / params[1];
12941 oldZ = (oldX - params[0]) / params[1];
12943 return (oldZ * oldZ - newZ * newZ) / 2.0;
12947 /* Calculate probability ratio of realizations for arbitrarily truncated normal random variable; parameters truncation point, mean and sd */
12948 MrBFlt LnProbRatioTruncatedNormal_Param_Trunc_Mean_Sd (MrBFlt newX, MrBFlt oldX, MrBFlt *params)
12952 newZ = (newX - params[1]) / params[2];
12953 oldZ = (oldX - params[1]) / params[2];
12955 return (oldZ * oldZ - newZ * newZ) / 2.0;
12959 /* Calculate probability ratio of realizations for uniform random variable */
12960 MrBFlt LnProbRatioUniform (MrBFlt newX, MrBFlt oldX, MrBFlt *params)
12963 MrBayesPrint ("%lf %lf", newX, oldX); /* just because I am tired of seeing the unused parameter error msg */
12964 MrBayesPrint ("%lf", *params);
12968 /* Log probability for a value drawn from a gamma distribution */
12969 MrBFlt LnProbGamma (MrBFlt alpha, MrBFlt beta, MrBFlt x)
12973 lnProb = (alpha-1.0)*log(x) + alpha*log(beta) - x*beta - LnGamma(alpha);
12979 /* Log probability for a value drawn from a truncated gamma distribution */
12980 MrBFlt LnProbTruncGamma (MrBFlt alpha, MrBFlt beta, MrBFlt x, MrBFlt min, MrBFlt max)
12984 lnProb = (alpha-1.0)*log(x) + alpha*log(beta) - x*beta - LnGamma(alpha);
12986 lnProb -= log (IncompleteGamma (max*beta, alpha, LnGamma(alpha)) - IncompleteGamma (min*beta, alpha, LnGamma(alpha)));
12992 /* Log probability for a value drawn from a lognormal distribution */
12993 MrBFlt LnProbLogNormal (MrBFlt exp, MrBFlt sd, MrBFlt x)
12997 z = (log(x) - exp) / sd;
12999 lnProb = - log (x * sd * sqrt (2.0 * PI)) - (z * z / 2.0);
13005 /* Log ratio for two values drawn from a lognormal distribution */
13006 MrBFlt LnRatioLogNormal (MrBFlt exp, MrBFlt sd, MrBFlt xNew, MrBFlt xOld)
13010 newZ = (log(xNew) - exp) / sd;
13011 oldZ = (log(xOld) - exp) / sd;
13013 return (oldZ * oldZ - newZ * newZ) / 2.0 + log(xOld) - log(xNew);
13017 /* Log probability for a value drawn from a lognormal distribution;
13018 parameters are mean and variance of value (not of log value) */
13019 MrBFlt LnProbTK02LogNormal (MrBFlt mean, MrBFlt var, MrBFlt x)
13021 MrBFlt z, lnProb, mu, sigma;
13023 sigma = sqrt(log(1.0 + (var / (mean*mean))));
13024 mu = log(mean) - sigma * sigma / 2.0;
13026 z = (log(x) - mu) / sigma;
13028 lnProb = - log (x * sigma * sqrt (2.0 * PI)) - (z * z / 2.0);
13034 /* Log ratio for two values drawn from a lognormal distribution */
13035 MrBFlt LnRatioTK02LogNormal (MrBFlt mean, MrBFlt var, MrBFlt xNew, MrBFlt xOld)
13037 MrBFlt newZ, oldZ, mu, sigma;
13039 sigma = sqrt(log(1.0 + (var / (mean*mean))));
13040 mu = log(mean) - sigma * sigma / 2.0;
13042 newZ = (log(xNew) - mu) / sigma;
13043 oldZ = (log(xOld) - mu) / sigma;
13045 return (oldZ * oldZ - newZ * newZ) / 2.0 + log(xOld) - log(xNew);
13049 /*---------------------------------------------------------------------------------
13053 | This function is called from ComputeMatrixExponential.
13055 ---------------------------------------------------------------------------------*/
13056 int LogBase2Plus1 (MrBFlt x)
13060 while (x > 1.0 - 1.0e-07)
13070 /*---------------------------------------------------------------------------------
13072 | LogNormalRandomVariable
13074 | Draw a random variable from a lognormal distribution.
13076 ---------------------------------------------------------------------------------*/
13077 MrBFlt LogNormalRandomVariable (MrBFlt mean, MrBFlt sd, RandLong *seed)
13081 x = PointNormal(RandomNumber(seed));
13090 /*---------------------------------------------------------------------------------
13092 | LUBackSubstitution
13094 | Back substitute into an LU-decomposed matrix.
13096 ---------------------------------------------------------------------------------*/
13097 void LUBackSubstitution (int dim, MrBFlt **a, int *indx, MrBFlt *b)
13099 int i, ip, j, ii = -1;
13102 for (i=0; i<dim; i++)
13109 for (j=ii; j<=i-1; j++)
13110 sum -= a[i][j] * b[j];
13112 else if (fabs(sum)>ETA)
13116 for (i=dim-1; i>=0; i--)
13119 for (j=i+1; j<dim; j++)
13120 sum -= a[i][j] * b[j];
13121 b[i] = sum / a[i][i];
13126 /*---------------------------------------------------------------------------------
13130 | Calculate the LU-decomposition of the matrix a. The matrix a is replaced.
13132 ---------------------------------------------------------------------------------*/
13133 int LUDecompose (int dim, MrBFlt **a, MrBFlt *vv, int *indx, MrBFlt *pd)
13135 int i, imax=0, j, k;
13136 MrBFlt big, dum, sum, temp, d;
13139 for (i=0; i<dim; i++)
13142 for (j = 0; j < dim; j++)
13144 if ((temp = fabs(a[i][j])) > big)
13149 MrBayesPrint ("%s Error: Problem in LUDecompose\n", spacer);
13154 for (j=0; j<dim; j++)
13156 for (i = 0; i < j; i++)
13159 for (k = 0; k < i; k++)
13160 sum -= a[i][k] * a[k][j];
13164 for (i=j; i<dim; i++)
13167 for (k = 0; k < j; k++)
13168 sum -= a[i][k] * a[k][j];
13170 dum = vv[i] * fabs(sum);
13179 for (k=0; k<dim; k++)
13182 a[imax][k] = a[j][k];
13189 if (fabs(a[j][j])<ETA)
13193 dum = 1.0 / (a[j][j]);
13194 for (i=j+1; i<dim; i++)
13205 /*---------------------------------------------------------------------------------
13209 | Multiply matrix a by matrix b and put the results in matrix result.
13211 ---------------------------------------------------------------------------------*/
13212 void MultiplyMatrices (int dim, MrBFlt **a, MrBFlt **b, MrBFlt **result)
13214 register int i, j, k;
13217 temp = AllocateSquareDoubleMatrix (dim);
13219 for (i=0; i<dim; i++)
13221 for (j=0; j<dim; j++)
13224 for (k=0; k<dim; k++)
13226 temp[i][j] += a[i][k] * b[k][j];
13230 for (i=0; i<dim; i++)
13232 for (j=0; j<dim; j++)
13234 result[i][j] = temp[i][j];
13238 FreeSquareDoubleMatrix (temp);
13242 /*---------------------------------------------------------------------------------
13244 | MultiplyMatrixByScalar
13246 | Multiply the elements of matrix a by a scalar.
13248 ---------------------------------------------------------------------------------*/
13249 void MultiplyMatrixByScalar (int dim, MrBFlt **a, MrBFlt scalar, MrBFlt **result)
13253 for (row=0; row<dim; row++)
13254 for (col=0; col<dim; col++)
13255 result[row][col] = a[row][col] * scalar;
13259 /*---------------------------------------------------------------------------------
13261 | MultiplyMatrixNTimes
13263 ---------------------------------------------------------------------------------*/
13264 int MultiplyMatrixNTimes (int dim, MrBFlt **Mat, int power, MrBFlt **Result)
13267 int k, numSquares, numRemaining;
13268 MrBFlt **TempIn, **TempOut;
13272 MrBayesPrint ("%s Error: Power cannot be a negative number.\n", spacer);
13275 else if (power == 0)
13277 for (i=0; i<dim; i++)
13278 for (j=0; j<dim; j++)
13279 Result[i][j] = 1.0;
13283 TempIn = AllocateSquareDoubleMatrix (dim);
13284 TempOut = AllocateSquareDoubleMatrix (dim);
13286 /* how many times can I multiply the matrices together */
13288 while (pow (2.0, (MrBFlt)(numSquares)) < power)
13290 numRemaining = power - (int)(pow(2.0, (MrBFlt)(numSquares)));
13292 /* now, multiply matrix by power of 2's */
13293 CopyDoubleMatrices (dim, Mat, TempIn);
13294 for (k=0; k<numSquares; k++)
13296 MultiplyMatrices (dim, TempIn, TempIn, TempOut);
13297 CopyDoubleMatrices (dim, TempOut, TempIn);
13300 /* TempIn is Mat^numSquares. Now, multiply it by Mat numRemaining times */
13301 for (k=0; k<numRemaining; k++)
13303 MultiplyMatrices (dim, TempIn, Mat, TempOut);
13304 CopyDoubleMatrices (dim, TempOut, TempIn);
13308 CopyDoubleMatrices (dim, TempIn, Result);
13310 FreeSquareDoubleMatrix (TempIn);
13311 FreeSquareDoubleMatrix (TempOut);
13318 /*---------------------------------------------------------------------------------
13322 | Returns z so that Prob(x < z) = prob where x is Chi2 distributed with df=v.
13323 | Returns -1 if in error. 0.000002 < prob < 0.999998.
13325 ---------------------------------------------------------------------------------*/
13326 MrBFlt PointChi2 (MrBFlt prob, MrBFlt v)
13328 MrBFlt e = 0.5e-6, aa = 0.6931471805, p = prob, g,
13329 xx, c, ch, a = 0.0, q = 0.0, p1 = 0.0, p2 = 0.0, t = 0.0,
13330 x = 0.0, b = 0.0, s1, s2, s3, s4, s5, s6;
13332 if (p < 0.000002 || p > 0.999998 || v <= 0.0)
13334 g = LnGamma (v/2.0);
13337 if (v >= -1.24*log(p))
13339 ch = pow((p*xx*exp(g+xx*aa)), 1.0/xx);
13350 p1 = 1.0+ch*(4.67+ch);
13351 p2 = ch*(6.73+ch*(6.66+ch));
13352 t = -0.5+(4.67+2.0*ch)/p1 - (6.73+ch*(13.32+3.0*ch))/p2;
13353 ch -= (1.0-exp(a+g+0.5*ch+c*aa)*p2/p1)/t;
13354 if (fabs(q/ch-1.0)-0.01 <= 0.0)
13359 x = PointNormal (p);
13361 ch = v*pow((x*sqrt(p1)+1.0-p1), 3.0);
13362 if (ch > 2.2*v+6.0)
13363 ch = -2.0*(log(1.0-p)-c*log(0.5*ch)+g);
13367 if ((t = IncompleteGamma (p1, xx, g)) < 0.0)
13369 MrBayesPrint ("%s Error: Problem in PointChi2", spacer);
13373 t = p2*exp(xx*aa+g+p1-c*log(ch));
13376 s1 = (210.0+a*(140.0+a*(105.0+a*(84.0+a*(70.0+60.0*a))))) / 420.0;
13377 s2 = (420.0+a*(735.0+a*(966.0+a*(1141.0+1278.0*a))))/2520.0;
13378 s3 = (210.0+a*(462.0+a*(707.0+932.0*a)))/2520.0;
13379 s4 = (252.0+a*(672.0+1182.0*a)+c*(294.0+a*(889.0+1740.0*a)))/5040.0;
13380 s5 = (84.0+264.0*a+c*(175.0+606.0*a)) / 2520.0;
13381 s6 = (120.0+c*(346.0+127.0*c)) / 5040.0;
13382 ch += t*(1+0.5*t*s1-b*c*(s1-b*(s2-b*(s3-b*(s4-b*(s5-b*s6))))));
13383 if (fabs(q/ch-1.0) > e)
13389 /*---------------------------------------------------------------------------------
13393 | Returns z so That Prob{x<z} = prob where x ~ N(0,1) and
13394 | (1e-12) < prob < 1-(1e-12). Returns (-9999) if in error.
13396 | Odeh, R. E. and J. O. Evans. 1974. The percentage points of the normal
13397 | distribution. Applied Statistics, 22:96-97 (AS70).
13401 | Wichura, M. J. 1988. Algorithm AS 241: The percentage points of the
13402 | normal distribution. 37:477-484.
13403 | Beasley, JD & S. G. Springer. 1977. Algorithm AS 111: The percentage
13404 | points of the normal distribution. 26:118-121.
13406 ---------------------------------------------------------------------------------*/
13407 MrBFlt PointNormal (MrBFlt prob)
13409 MrBFlt a0 = -0.322232431088, a1 = -1.0, a2 = -0.342242088547, a3 = -0.0204231210245,
13410 a4 = -0.453642210148e-4, b0 = 0.0993484626060, b1 = 0.588581570495,
13411 b2 = 0.531103462366, b3 = 0.103537752850, b4 = 0.0038560700634,
13412 y, z = 0, p = prob, p1;
13414 p1 = (p<0.5 ? p : 1-p);
13417 y = sqrt (log(1/(p1*p1)));
13418 z = y + ((((y*a4+a3)*y+a2)*y+a1)*y+a0) / ((((y*b4+b3)*y+b2)*y+b1)*y+b0);
13420 return (p<0.5 ? -z : z);
13424 /*---------------------------------------------------------------------------------
13426 | PrintComplexVector
13428 | Prints a vector of dim complex numbers.
13430 ---------------------------------------------------------------------------------*/
13431 void PrintComplexVector (int dim, complex *vec)
13435 MrBayesPrint ("{");
13436 for (i = 0; i < (dim - 1); i++)
13438 MrBayesPrint ("%lf + %lfi, ", vec[i].re, vec[i].im);
13440 MrBayesPrint("\n ");
13442 MrBayesPrint ("%lf + %lfi}\n", vec[dim - 1].re, vec[dim - 1].im);
13446 /*---------------------------------------------------------------------------------
13448 | PrintSquareComplexMatrix
13450 | Prints a square matrix of complex numbers.
13452 ---------------------------------------------------------------------------------*/
13453 void PrintSquareComplexMatrix (int dim, complex **m)
13457 MrBayesPrint ("{");
13458 for (row = 0; row < (dim - 1); row++)
13460 MrBayesPrint ("{");
13461 for (col = 0; col < (dim - 1); col++)
13463 MrBayesPrint ("%lf + %lfi, ", m[row][col].re, m[row][col].im);
13465 MrBayesPrint ("\n ");
13467 MrBayesPrint ("%lf + %lfi},\n",
13468 m[row][dim - 1].re, m[row][dim - 1].im);
13470 MrBayesPrint ("{");
13471 for (col = 0; col < (dim - 1); col++)
13473 MrBayesPrint ("%lf + %lfi, ", m[dim - 1][col].re, m[dim - 1][col].im);
13475 MrBayesPrint ("\n ");
13477 MrBayesPrint ("%lf + %lfi}}", m[dim - 1][dim - 1].re, m[dim - 1][dim - 1].im);
13478 MrBayesPrint ("\n");
13482 /*---------------------------------------------------------------------------------
13484 | PrintSquareDoubleMatrix
13486 | Prints a square matrix of doubles.
13488 ---------------------------------------------------------------------------------*/
13489 void PrintSquareDoubleMatrix (int dim, MrBFlt **matrix)
13493 for (i=0; i<dim; i++)
13495 for (j=0; j<dim; j++)
13496 MrBayesPrint ("%1.6lf ", matrix[i][j]);
13497 MrBayesPrint ("\n");
13502 /*---------------------------------------------------------------------------------
13504 | PrintSquareIntegerMatrix
13506 | Prints a square matrix of integers.
13508 ---------------------------------------------------------------------------------*/
13509 void PrintSquareIntegerMatrix (int dim, int **matrix)
13513 for (i=0; i<dim; i++)
13515 for (j=0; j<dim; j++)
13516 MrBayesPrint ("%d ", matrix[i][j]);
13517 MrBayesPrint ("\n");
13522 /*---------------------------------------------------------------------------------
13524 | ProductOfRealAndComplex
13526 | Returns the complex product of a real and complex number.
13528 ---------------------------------------------------------------------------------*/
13529 complex ProductOfRealAndComplex (MrBFlt a, complex b)
13540 /*---------------------------------------------------------------------------------
13542 | PsiExp: Returns psi (also called digamma) exponentiated
13543 | Algorithm from http://lib.stat.cmu.edu/apstat/103
13545 ---------------------------------------------------------------------------------*/
13546 MrBFlt PsiExp (MrBFlt alpha)
13548 MrBFlt digamma, y, r, s, c, s3, s4, s5, d1;
13552 s3 = 8.333333333333333333333333e-02;
13553 s4 = 8.333333333333333333333333e-03;
13554 s5 = 3.968253968e-03;
13555 d1 = -0.577215664901532860606512; /* negative of Euler's constant */
13564 digamma = d1 - 1.0 / y;
13565 return (exp (digamma));
13570 digamma -= 1.0 / y;
13575 digamma += (log (y) - 0.5 * r);
13577 digamma -= r * (s3 - r * (s4 - r * s5));
13579 return (exp (digamma));
13583 /*---------------------------------------------------------------------------------
13585 | PsiGammaLnProb: Calculates the log probability of a PsiGamma distributed
13588 ---------------------------------------------------------------------------------*/
13589 MrBFlt PsiGammaLnProb (MrBFlt alpha, MrBFlt value)
13591 MrBFlt beta, lnProb;
13593 beta = PsiExp (alpha);
13595 lnProb = alpha * log (beta) - LnGamma (alpha) + (alpha - 1.0) * log (value) - beta * value;
13601 /*---------------------------------------------------------------------------------
13603 | PsiGammaLnRatio: Calculates the log prob ratio of two PsiGamma distributed
13606 ---------------------------------------------------------------------------------*/
13607 MrBFlt PsiGammaLnRatio (MrBFlt alpha, MrBFlt numerator, MrBFlt denominator)
13609 MrBFlt beta, lnRatio;
13611 beta = PsiExp (alpha);
13613 lnRatio = (alpha - 1.0) * (log (numerator) - log (denominator)) - beta * (numerator - denominator);
13619 /*---------------------------------------------------------------------------------
13621 | PsiGammaRandomVariable: Returns a random draw from the PsiGamma
13623 ---------------------------------------------------------------------------------*/
13624 MrBFlt PsiGammaRandomVariable (MrBFlt alpha, RandLong *seed)
13626 return GammaRandomVariable (alpha, PsiExp(alpha), seed);
13630 /*---------------------------------------------------------------------------------
13634 ---------------------------------------------------------------------------------*/
13635 MrBFlt QuantileGamma (MrBFlt x, MrBFlt alfa, MrBFlt beta)
13639 quantile = POINTGAMMA(x, alfa, beta);
13645 /*---------------------------------------------------------------------------------
13649 | This pseudorandom number generator is described in:
13650 | Park, S. K. and K. W. Miller. 1988. Random number generators: good
13651 | ones are hard to find. Communications of the ACM, 31(10):1192-1201.
13653 ---------------------------------------------------------------------------------*/
13654 MrBFlt RandomNumber (RandLong *seed)
13656 RandLong lo, hi, test;
13658 hi = (*seed) / 127773;
13659 lo = (*seed) % 127773;
13660 test = 16807 * lo - 2836 * hi;
13664 *seed = test + 2147483647;
13665 return ((MrBFlt)(*seed) / (MrBFlt)2147483647);
13669 /*---------------------------------------------------------------------------------
13673 ---------------------------------------------------------------------------------*/
13674 MrBFlt RndGamma (MrBFlt s, RandLong *seed)
13679 puts ("Gamma parameter less than zero\n");
13682 r = RndGamma1 (s, seed);
13684 r = RndGamma2 (s, seed);
13685 else /* 0-log() == -1 * log(), but =- looks confusing */
13686 r -= log(RandomNumber(seed));
13692 /*---------------------------------------------------------------------------------
13696 ---------------------------------------------------------------------------------*/
13697 MrBFlt RndGamma1 (MrBFlt s, RandLong *seed)
13699 MrBFlt r, x=0.0, tiny=1e-37, w;
13700 static MrBFlt a, p, uf, ss=10.0, d;
13702 if (fabs(s-ss)>ETA) /* s != ss */
13705 p = a / (a + s * exp(-a));
13706 uf = p * pow(tiny / a, s);
13712 r = RandomNumber(seed);
13714 x = a - log((1.0 - r) / (1.0 - p)), w = a * log(x) - d;
13716 x = a * pow(r / p, 1.0 / s), w = x;
13719 r = RandomNumber(seed);
13720 if (1.0 - r <= w && r > 0.0)
13721 if (r*(w + 1.0) >= 1.0 || -log(r) <= w)
13730 /*---------------------------------------------------------------------------------
13734 ---------------------------------------------------------------------------------*/
13735 MrBFlt RndGamma2 (MrBFlt s, RandLong *seed)
13737 MrBFlt r , d, f, g, x;
13738 static MrBFlt b, h, ss=0.0;
13740 if (fabs(s-ss)>ETA) /* s != ss */
13743 h = sqrt(3.0 * s - 0.75);
13748 r = RandomNumber(seed);
13750 f = (r - 0.5) * h / sqrt(g);
13754 r = RandomNumber(seed);
13755 d = 64 * r * r * g * g * g;
13756 if (d * x < x - 2.0 * f * f || log(d) < 2.0 * (b * log(x / b) - f))
13764 /*---------------------------------------------------------------------------------
13768 | The Pade method for calculating the matrix exponential, tMat = e^{qMat * v},
13769 | has an error, e(p,q), that can be controlled by setting p and q to appropriate
13770 | values. The error is:
13772 | e(p,q) = 2^(3-(p+q)) * ((p!*q!) / (p+q)! * (p+q+1)!)
13774 | Setting p = q will minimize the error for a given amount of work. This function
13775 | assumes that p = q. The function takes in as a parameter the desired tolerance
13776 | for the accuracy of the matrix exponentiation, and returns qV = p = q, that
13777 | will achieve the tolerance. The Pade approximation method is described in:
13779 | Golub, G. H., and C. F. Van Loan. 1996. Matrix Computations, Third Edition.
13780 | The Johns Hopkins University Press, Baltimore, Maryland.
13782 | The function is called from TiProbsUsingPadeApprox.
13784 ---------------------------------------------------------------------------------*/
13785 int SetQvalue (MrBFlt tol)
13790 x = pow(2.0, 3.0 - (0 + 0)) * Factorial(0) * Factorial (0) / (Factorial(0+0) * Factorial (0+0+1));
13795 x = pow(2.0, 3.0 - (qV + qV)) * Factorial(qV) * Factorial (qV) / (Factorial(qV+qV) * Factorial (qV+qV+1));
13802 /*---------------------------------------------------------------------------------
13806 | Make a dim X dim identity matrix.
13808 ---------------------------------------------------------------------------------*/
13809 void SetToIdentity (int dim, MrBFlt **matrix)
13813 for (row=0; row<dim; row++)
13814 for (col=0; col<dim; col++)
13815 matrix[row][col] = (row == col ? 1.0 : 0.0);
13819 /*---------------------------------------------------------------------------------
13823 | Calculate Owen's (1956) T(h,a) function, -inf <= h, a <= inf,
13824 | where h = h1/h2, a = a1/a2, from the program of:
13826 | Young, J. C. and C. E. Minder. 1974. Algorithm AS 76. An integral
13827 | useful in calculating non-central t and bivariate normal
13828 | probabilities. Appl. Statist., 23:455-457. [Correction: Appl.
13829 | Statist., 28:113 (1979). Remarks: Appl. Statist. 27:379 (1978),
13830 | 28: 113 (1979), 34:100-101 (1985), 38:580-582 (1988)]
13834 | Johnson, N. L. and S. Kotz. 1972. Distributions in statistics:
13835 | multivariate distributions. Wiley and Sons. New York. pp. 93-100.
13837 ---------------------------------------------------------------------------------*/
13838 MrBFlt Tha (MrBFlt h1, MrBFlt h2, MrBFlt a1, MrBFlt a2)
13841 MrBFlt U[] = {0.0744372, 0.2166977, 0.3397048, 0.4325317, 0.4869533},
13842 R[] = {0.1477621, 0.1346334, 0.1095432, 0.0747257, 0.0333357},
13843 pai2 = 6.283185307, tv1 = 1e-35, tv2 = 15.0, tv3 = 15.0, tv4 = 1e-5,
13844 a, h, rt, t, x1, x2, r1, r2, s, k, sign = 1.0;
13846 if (fabs(h2) < tv1)
13849 if (fabs(a2) < tv1)
13853 t = (1.0 - t) / 2.0;
13856 return (t*(a1 >= 0.0 ? 1.0 : -1.0));
13864 if (h > tv2 || a < tv1)
13867 return (atan(a)/pai2*sign);
13868 if (h < 0.3 && a > 7.0) /* (Boys RJ, 1989) */
13870 x1 = exp(-k*k/2.0)/k;
13871 x2 = (CdfNormal(k)-0.5)*sqrt(pai2);
13872 t = 0.25 - (x1+x2)/pai2*h + ((1.0+2.0/(k*k))*x1+x2)/(6.0*pai2)*h*h*h;
13873 return (MAX(t,0)*sign);
13878 if (log(1.0+s)-t*s >= tv3)
13882 for (;;) /* truncation point by Newton iteration */
13884 x2 = x1 + (t*s+tv3-log(s+1.0)) / (2.0*x1*(1.0/(s+1.0)-t));
13886 if (fabs(x2-x1) < tv4)
13891 for (i=0,rt=0; i<ng; i++) /* Gauss quadrature */
13893 r1 = 1.0+s*SQUARE(0.5+U[i]);
13894 r2 = 1.0+s*SQUARE(0.5-U[i]);
13895 rt+= R[i]*(exp(t*r1)/r1 + exp(t*r2)/r2);
13898 return (MAX(rt*x2/pai2,0)*sign);
13902 /*---------------------------------------------------------------------------------
13904 | TiProbsUsingEigens
13906 ---------------------------------------------------------------------------------*/
13907 void TiProbsUsingEigens (int dim, MrBFlt *cijk, MrBFlt *eigenVals, MrBFlt v, MrBFlt r, MrBFlt **tMat, MrBFlt **fMat, MrBFlt **sMat)
13910 MrBFlt sum, sumF, sumS, *ptr, EigValexp[192];
13912 for (s=0; s<dim; s++)
13913 EigValexp[s] = exp(eigenVals[s] * v * r);
13916 for (i=0; i<dim; i++)
13918 for (j=0; j<dim; j++)
13921 for (s=0; s<dim; s++)
13922 sum += (*ptr++) * EigValexp[s];
13923 tMat[i][j] = (sum < 0.0) ? 0.0 : sum;
13928 for (i=0; i<dim; i++)
13931 for (j=0; j<dim; j++)
13935 if (sum > 1.0001 || sum < 0.9999)
13937 MrBayesPrint ("%s Warning: Transition probabilities do not sum to 1.0 (%lf)\n", spacer, sum);
13942 if (fMat != NULL && sMat != NULL)
13945 for (i=0; i<dim; i++)
13947 for (j=0; j<dim; j++)
13950 for (s=0; s<dim; s++)
13952 sumF += (*ptr) * eigenVals[s] * r * EigValexp[s];
13953 sumS += (*ptr++) * eigenVals[s] * eigenVals[s] * r * r * EigValexp[s];
13963 /*---------------------------------------------------------------------------------
13965 | TiProbsUsingPadeApprox
13967 | The method approximates the matrix exponential, tMat = e^{qMat * v}, using
13968 | the Pade approximation method, described in:
13970 | Golub, G. H., and C. F. Van Loan. 1996. Matrix Computations, Third Edition.
13971 | The Johns Hopkins University Press, Baltimore, Maryland.
13973 | The method approximates the matrix exponential with accuracy tol.
13975 ---------------------------------------------------------------------------------*/
13976 void TiProbsUsingPadeApprox (int dim, MrBFlt **qMat, MrBFlt v, MrBFlt r, MrBFlt **tMat, MrBFlt **fMat, MrBFlt **sMat)
13983 a = AllocateSquareDoubleMatrix (dim);
13985 MultiplyMatrixByScalar (dim, qMat, v * r, a);
13987 qValue = SetQvalue (tol);
13989 ComputeMatrixExponential (dim, a, qValue, tMat);
13991 FreeSquareDoubleMatrix (a);
13993 if (fMat != NULL && sMat != NULL)
13995 MultiplyMatrices (dim, qMat, tMat, fMat);
13996 MultiplyMatrices (dim, qMat, fMat, sMat);