forked from stmrnku/mrbayes3parallel
-
Notifications
You must be signed in to change notification settings - Fork 0
/
utils.c
14029 lines (12218 loc) · 399 KB
/
utils.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* MrBayes 3
*
* (c) 2002-2013
*
* John P. Huelsenbeck
* Dept. Integrative Biology
* University of California, Berkeley
* Berkeley, CA 94720-3140
* johnh@berkeley.edu
*
* Fredrik Ronquist
* Swedish Museum of Natural History
* Box 50007
* SE-10405 Stockholm, SWEDEN
* fredrik.ronquist@nrm.se
*
* With important contributions by
*
* Paul van der Mark (paulvdm@sc.fsu.edu)
* Maxim Teslenko (maxim.teslenko@nrm.se)
*
* and by many users (run 'acknowledgments' to see more info)
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details (www.gnu.org).
*
*/
#include "bayes.h"
#include "best.h"
#include "command.h"
#include "mcmc.h"
#include "model.h"
#include "utils.h"
const char* const svnRevisionUtilsC = "$Rev: 1062 $"; /* Revision keyword which is expended/updated by svn on each commit/update */
#define MAX_GAMMA_CATS 20
#define PI 3.14159265358979324
#define PIOVER2 1.57079632679489662
#define POINTGAMMA(prob,alpha,beta) PointChi2(prob,2.0*(alpha))/(2.0*(beta))
#define PAI2 6.283185307
#define TINY 1.0e-20
#define EVALUATE_COMPLEX_NUMBERS 2
#if !defined(MAX)
#define MAX(a,b) (((a) > (b)) ? (a) : (b))
#endif
#if !defined(MIN)
#define MIN(a,b) (((a) < (b)) ? (a) : (b))
#endif
#define SQUARE(a) ((a)*(a))
/* local global variable */
char noLabel[] = "";
/* local prototypes */
void DatedNodeDepths (TreeNode *p, MrBFlt *nodeDepths, int *index);
void DatedNodes (TreeNode *p, TreeNode **datedTips, int *index);
int NConstrainedTips (TreeNode *p);
int NDatedTips (TreeNode *p);
void PrintNode (char **s, int *len, TreeNode *p, int isRooted);
void ResetPolyNode (PolyNode *p);
void ResetTreeNode (TreeNode *p);
void SetNodeDepths (Tree *t);
void AddTwoMatrices (int dim, MrBFlt **a, MrBFlt **b, MrBFlt **result);
void BackSubstitutionRow (int dim, MrBFlt **u, MrBFlt *b);
void Balanc (int dim, MrBFlt **a, int *low, int *high, MrBFlt *scale);
void BalBak (int dim, int low, int high, MrBFlt *scale, int m, MrBFlt **z);
MrBFlt BetaCf (MrBFlt a, MrBFlt b, MrBFlt x);
MrBFlt BetaQuantile (MrBFlt alpha, MrBFlt beta, MrBFlt x);
MrBFlt CdfBinormal (MrBFlt h1, MrBFlt h2, MrBFlt r);
MrBFlt CdfNormal (MrBFlt x);
complex Complex (MrBFlt a, MrBFlt b);
MrBFlt ComplexAbsoluteValue (complex a);
complex ComplexAddition (complex a, complex b);
complex ComplexConjugate (complex a);
complex ComplexDivision (complex a, complex b);
void ComplexDivision2 (MrBFlt ar, MrBFlt ai, MrBFlt br, MrBFlt bi, MrBFlt *cr, MrBFlt *ci);
complex ComplexExponentiation (complex a);
int ComplexInvertMatrix (int dim, complex **a, MrBFlt *dwork, int *indx, complex **aInverse, complex *col);
complex ComplexLog (complex a);
void ComplexLUBackSubstitution (int dim, complex **a, int *indx, complex *b);
int ComplexLUDecompose (int dim, complex **a, MrBFlt *vv, int *indx, MrBFlt *pd);
complex ComplexMultiplication (complex a, complex b);
complex ComplexSquareRoot (complex a);
complex ComplexSubtraction (complex a, complex b);
int ComputeEigenSystem (int dim, MrBFlt **a, MrBFlt *v, MrBFlt *vi, MrBFlt **u, int *iwork, MrBFlt *dwork);
void ComputeLandU (int dim, MrBFlt **aMat, MrBFlt **lMat, MrBFlt **uMat);
void ComputeMatrixExponential (int dim, MrBFlt **a, int qValue, MrBFlt **f);
void DivideByTwos (int dim, MrBFlt **a, int power);
MrBFlt D_sign (MrBFlt a, MrBFlt b);
int EigensForRealMatrix (int dim, MrBFlt **a, MrBFlt *wr, MrBFlt *wi, MrBFlt **z, int *iv1, MrBFlt *fv1);
void ElmHes (int dim, int low, int high, MrBFlt **a, int *interchanged);
void ElTran (int dim, int low, int high, MrBFlt **a, int *interchanged, MrBFlt **z);
void Exchange (int j, int k, int l, int m, int n, MrBFlt **a, MrBFlt *scale);
MrBFlt Factorial (int x);
void ForwardSubstitutionRow (int dim, MrBFlt **L, MrBFlt *b);
MrBFlt GammaRandomVariable (MrBFlt a, MrBFlt b, RandLong *seed);
void GaussianElimination (int dim, MrBFlt **a, MrBFlt **bMat, MrBFlt **xMat);
int Hqr2 (int dim, int low, int high, MrBFlt **h, MrBFlt *wr, MrBFlt *wi, MrBFlt **z);
MrBFlt IncompleteBetaFunction (MrBFlt alpha, MrBFlt beta, MrBFlt x);
MrBFlt IncompleteGamma (MrBFlt x, MrBFlt alpha, MrBFlt LnGamma_alpha);
int InvertMatrix (int dim, MrBFlt **a, MrBFlt *col, int *indx, MrBFlt **aInv);
MrBFlt LBinormal (MrBFlt h1, MrBFlt h2, MrBFlt r);
int LogBase2Plus1 (MrBFlt x);
void LUBackSubstitution (int dim, MrBFlt **a, int *indx, MrBFlt *b);
int LUDecompose (int dim, MrBFlt **a, MrBFlt *vv, int *indx, MrBFlt *pd);
void MultiplyMatrixByScalar (int dim, MrBFlt **a, MrBFlt scalar, MrBFlt **result);
MrBFlt PointChi2 (MrBFlt prob, MrBFlt v);
void PrintComplexVector (int dim, complex *vec);
void PrintSquareComplexMatrix (int dim, complex **m);
void PrintSquareDoubleMatrix (int dim, MrBFlt **matrix);
void PrintSquareIntegerMatrix (int dim, int **matrix);
complex ProductOfRealAndComplex (MrBFlt a, complex b);
MrBFlt RndGamma (MrBFlt s, RandLong *seed);
MrBFlt RndGamma1 (MrBFlt s, RandLong *seed);
MrBFlt RndGamma2 (MrBFlt s, RandLong *seed);
int SetQvalue (MrBFlt tol);
void SetToIdentity (int dim, MrBFlt **matrix);
MrBFlt Tha (MrBFlt h1, MrBFlt h2, MrBFlt a1, MrBFlt a2);
void TiProbsUsingEigens (int dim, MrBFlt *cijk, MrBFlt *eigenVals, MrBFlt v, MrBFlt r, MrBFlt **tMat, MrBFlt **fMat, MrBFlt **sMat);
void TiProbsUsingPadeApprox (int dim, MrBFlt **qMat, MrBFlt v, MrBFlt r, MrBFlt **tMat, MrBFlt **fMat, MrBFlt **sMat);
MrBFlt QuantileLogNormal (MrBFlt prob, MrBFlt mu, MrBFlt sigma);
int DiscreteLogNormal (MrBFlt *rK, MrBFlt sigma, int K, int median);
MrBFlt LogNormalPoint (MrBFlt x, MrBFlt mu, MrBFlt sigma);
/* AddBitfield: Add bitfield to list of bitfields. The function uses global variable nLongsNeeded. */
int AddBitfield (BitsLong ***list, int listLen, int *set, int setLen)
{
int i, nLongsNeeded;
nLongsNeeded = (setLen - 1) / nBitsInALong + 1;
(*list) = (BitsLong **) SafeRealloc ((void *)(*list), ((size_t)listLen+1)*sizeof(BitsLong *));
if (!(*list))
return ERROR;
(*list)[listLen] = (BitsLong *) SafeMalloc ((size_t)nLongsNeeded*sizeof(BitsLong));
if (!(*list)[listLen])
return ERROR;
ClearBits ((*list)[listLen], nLongsNeeded);
for (i=0; i<setLen; i++)
if (set[i] == YES)
SetBit(i, (*list)[listLen]);
return NO_ERROR;
}
#if defined (SSE_ENABLED)
void * AlignedMalloc (size_t size, size_t alignment)
{
void *mem;
#if defined GCC_SSE /* gcc compiler */
if (posix_memalign (&mem, alignment, size))
return 0;
#elif defined ICC_SSE /* icc compiler */
mem = _mm_malloc (size, alignment);
#elif defined MS_VCPP_SSE /* ms visual */
mem = _aligned_malloc (size, alignment);
#else
mem = malloc (size);
#endif
return mem;
}
void AlignedSafeFree (void **ptr)
{
#if defined ICC_SSE /* icc compiler */
_mm_free (*ptr);
#elif defined MS_VCPP_SSE /* ms visual */
_aligned_free (*ptr);
#else
free (*ptr);
#endif
(*ptr) = NULL;
}
#endif
#if defined (AVX_ENABLED)
void * AlignedMalloc (size_t size, size_t alignment)
{
void *mem;
#if defined GCC_AVX
if (posix_memalign (&mem, alignment, size))
return 0;
#elif defined ICC_AVX
mem = _mm_malloc(size, alignment);
#elif defined MS_VCPP_AVX
mem = _aligned_malloc (size, alignment);
#else
mem =malloc (size);
#endif
return mem;
}
void AlignedSafeFree (void **ptr)
{
#if defined ICC_AVX /* icc compiler */
_mm_free (*ptr);
#elif defined MS_VCPP_AVX /* ms visual */
_aligned_free (*ptr);
#else
free (*ptr);
#endif
(*ptr) = NULL;
}
#endif
int AreBitfieldsEqual (BitsLong *p, BitsLong *q, int length)
{
int i;
for (i=0; i<length; i++)
{
if (p[i] != q[i])
return NO;
}
return YES;
}
/*----------------------------------------------------------------
|
| Bit: return 1 if bit n is set in BitsLong *p
| else return 0
|
-----------------------------------------------------------------*/
int Bit (int n, BitsLong *p)
{
BitsLong x, bitsLongOne;
bitsLongOne = 1;
p += n / nBitsInALong;
x = bitsLongOne << (n % nBitsInALong);
if ((x & (*p)) == 0)
return 0;
else
return 1;
}
/* ClearBit: Clear one bit in a bitfield */
void ClearBit (int i, BitsLong *bits)
{
BitsLong x, bitsLongOne=1;
bits += i / nBitsInALong;
x = bitsLongOne << (i % nBitsInALong);
x ^= bitsLongWithAllBitsSet;
(*bits) &= x;
}
/* ClearBits: Clear all bits in a bitfield */
void ClearBits (BitsLong *bits, int nLongs)
{
int i;
for (i=0; i<nLongs; i++)
bits[i] = 0;
}
/* Copy bitfields */
void CopyBits (BitsLong *dest, BitsLong *source, int length)
{
int i;
for (i=0; i<length; i++)
dest[i] = source[i];
}
/* CopyResults: copy results from one file to another up to lastGen*/
int CopyResults (FILE *toFile, char *fromFileName, int lastGen)
{
int longestLine;
char *strBuf, *strCpy, *word;
FILE *fromFile;
if ((fromFile = OpenBinaryFileR(fromFileName)) == NULL)
return ERROR;
longestLine = LongestLine(fromFile)+10;
SafeFclose(&fromFile);
strBuf = (char *) SafeCalloc (2*(longestLine+2),sizeof(char));
strCpy = strBuf + longestLine + 2;
if ((fromFile = OpenTextFileR(fromFileName)) == NULL)
return ERROR;
while (fgets(strBuf,longestLine,fromFile)!=NULL)
{
strncpy (strCpy,strBuf,longestLine);
word = strtok(strCpy," ");
/* atoi returns 0 when word is not integer number */
if (atoi(word)>lastGen)
break;
fprintf (toFile,"%s",strBuf);
fflush (toFile);
}
SafeFclose(&fromFile);
free(strBuf);
return (NO_ERROR);
}
/* CopyProcessSsFile: copy results from one file to another up to lastStep. Also marginalLnLSS is collected for processed steps*/
int CopyProcessSsFile (FILE *toFile, char *fromFileName, int lastStep, MrBFlt *marginalLnLSS, MrBFlt * splitfreqSS)
{
int longestLine, run, curStep, i;
double tmp;
char *strBuf, *strCpy, *word, *tmpcp;
FILE *fromFile;
if ((fromFile = OpenBinaryFileR(fromFileName)) == NULL)
return ERROR;
longestLine = LongestLine(fromFile)+10;
SafeFclose(&fromFile);
strBuf = (char *) SafeCalloc (2*(longestLine+2),sizeof(char));
strCpy = strBuf + longestLine + 2;
if ((fromFile = OpenTextFileR(fromFileName)) == NULL)
return ERROR;
while (fgets(strBuf,longestLine,fromFile)!=NULL)
{
strncpy (strCpy,strBuf,longestLine);
word = strtok(strCpy," \t\n");
/* atoi returns 0 when word is not integer number */
if (atoi(word)>lastStep)
break;
fprintf (toFile,"%s",strBuf);
fflush (toFile);
curStep = atoi(word);
if (curStep > 0)
{
strtok(NULL,"\t\n"); /*skip power*/
for (run=0; run<chainParams.numRuns; run++)
{
tmpcp = strtok(NULL,"\t\n");
if (tmpcp == NULL)
{
MrBayesPrint ("%s Error: In .ss file not enough ellements on the string :%s \n", spacer, strBuf);
return ERROR;
}
tmp = atof(tmpcp);
if (tmp == 0.0)
{
MrBayesPrint ("%s Error: Value of some step contribution is 0.0 or not a number in .ss file. Sting:%s \n", spacer, strBuf);
return ERROR;
}
marginalLnLSS[run]+=tmp;
}
for (i=0; i<numTopologies; i++)
{
tmpcp = strtok(NULL,"\t\n");
if (tmpcp == NULL)
{
MrBayesPrint ("%s Error: In .ss file not enough ellements on the string :%s \n", spacer, strBuf);
return ERROR;
}
tmp = atof(tmpcp);
splitfreqSS[i*chainParams.numStepsSS + curStep-1] = tmp;
}
}
}
SafeFclose(&fromFile);
free(strBuf);
return (NO_ERROR);
}
/* CopyTreeResults: copy tree results upto lastGen from one file to another. numTrees is return containing number of trees that were copied. */
int CopyTreeResults (FILE *toFile, char *fromFileName, int lastGen, int *numTrees)
{
int longestLine;
char *strBuf, *strCpy, *word;
FILE *fromFile;
(*numTrees) = 0;
if ((fromFile = OpenBinaryFileR(fromFileName)) == NULL)
return ERROR;
longestLine = LongestLine(fromFile)+10;
SafeFclose(&fromFile);
strBuf = (char *) SafeCalloc (2*(longestLine+2),sizeof(char));
strCpy = strBuf + longestLine + 2;
if ((fromFile = OpenTextFileR(fromFileName)) == NULL)
return ERROR;
while (fgets(strBuf,longestLine,fromFile)!=NULL)
{
strncpy (strCpy,strBuf,longestLine);
word = strtok(strCpy," ");
if (strcmp(word,"tree")==0)
{
word = strtok(NULL," ");
/* atoi returns 0 when word is not integer number,
4 is offset to get rid of "rep." in tree name */
if (atoi(word+4)>lastGen)
break;
(*numTrees)++;
fprintf (toFile,"%s",strBuf);
}
else if (*numTrees == 0) /* do not print the end statement */
fprintf (toFile,"%s",strBuf);
fflush (toFile);
}
SafeFclose(&fromFile);
free(strBuf);
return (NO_ERROR);
}
/* FirstTaxonInPartition: Find index of first taxon in partition */
int FirstTaxonInPartition (BitsLong *partition, int length)
{
int i, j, nBits, taxon;
BitsLong x, bitsLongOne=1;
nBits = sizeof(BitsLong) * 8;
taxon = 0;
for (i=0; i<length; i++)
{
x = bitsLongOne;
for (j=0; j<nBits; j++)
{
if (partition[i] & x)
return taxon;
taxon++;
x <<= 1;
}
}
return taxon;
}
/* FirstTree: Return file position of first tree after current position */
long FirstTree (FILE *fp, char *lineBuf, int longestLine)
{
long firstTree;
char *word;
do {
firstTree = ftell(fp);
if ((fgets (lineBuf, longestLine, fp)) == NULL)
return 0;
word = strtok (lineBuf, " ");
} while (strcmp(word,"tree")!=0);
return (firstTree);
}
int Flip01 (int x)
{
if (x == 0)
return (1);
else
return (0);
}
void FlipBits (BitsLong *partition, int length, BitsLong *mask)
{
int i;
for (i=0; i<length; i++)
{
partition[i] ^= mask[i];
}
}
/*-----------------------------------------------------------------
|
| FlipOneBit: flip bit n in BitsLong *p
|
------------------------------------------------------------------*/
void FlipOneBit (int n, BitsLong *p)
{
BitsLong x, bitsLongOne=1;
p += n/nBitsInALong;
x = bitsLongOne << (n % nBitsInALong);
(*p) ^= x;
}
/* Convert from 0-based growth function over six states to model index */
int FromGrowthFxnToIndex(int *growthFxn)
{
int i, j, k, max, fxn[6];
/* set local growth fxn to lexicographical max */
for (i=0; i<6; i++)
fxn[i] = i;
/* decrease until we reach growthFxn */
for (k=202; k>=0; k--)
{
for (i=0; i<6; i++)
{
if (fxn[i] != growthFxn[i])
break;
}
if (i == 6)
break;
/* get next growth fxn */
for (i=5; i>=0; i--)
{
fxn[i]--;
if (fxn[i] >= 0)
break;
}
if (i < 0)
return -1; /* error */
else if (i < 5)
{
max = 0;
for (j=0; j<=i; j++)
{
if (fxn[j] > max)
max = fxn[j];
}
fxn[++i] = max + 1;
for (++i; i<6; i++)
fxn[i] = fxn[i-1] + 1;
}
}
return k;
}
/* Convert from model index to 0-based growth function over six states */
void FromIndexToGrowthFxn(int index, int *growthFxn)
{
int i, j, max, k;
/* set growth fxn to lexicographical max */
for (i=0; i<6; i++)
growthFxn[i] = i;
/* decrease until we reach index */
for (k=202; k>index; k--)
{
for (i=5; i>=0; i--)
{
growthFxn[i]--;
if (growthFxn[i] >= 0)
break;
}
if (i < 0)
return; /* ERROR */
else if (i < 5)
{
max = 0;
for (j=0; j<=i; j++)
{
if (growthFxn[j] > max)
max = growthFxn[j];
}
growthFxn[++i] = max + 1;
for (++i; i<6; i++)
growthFxn[i] = growthFxn[i-1] + 1;
}
}
}
/* GetIntSummary: Get summary statistics for a number of runs (int version) */
void GetIntSummary (int **vals, int nRows, int *rowCount, Stat *theStats, int HPD)
{
int i, j, nVals;
MrBFlt *theValues, *p;
nVals = 0;
for (i=0; i<nRows; i++)
nVals += rowCount[i];
theValues = (MrBFlt *) SafeCalloc (nVals, sizeof(MrBFlt));
/* extract values */
p = theValues;
for (i=0; i<nRows; i++)
{
for (j=0; j<rowCount[i]; j++)
{
(*p++) = (MrBFlt) (vals[i][j]);
}
}
/* get statistics */
MeanVariance (theValues, nVals, &(theStats->mean), &(theStats->var));
if (HPD == YES)
LowerUpperMedian (theValues, nVals, &(theStats->lower), &(theStats->upper), &(theStats->median));
else
LowerUpperMedian (theValues, nVals, &(theStats->lower), &(theStats->upper), &(theStats->median));
free (theValues);
}
/* Get k from 0-based growth function */
int GetKFromGrowthFxn(int *growthFxn)
{
int i, k=0;
for (i=0; i<6; i++)
if (growthFxn[i] > k)
k = growthFxn[i];
return k+1;
}
/* GetSummary: Get summary statistics for a number of runs */
void GetSummary (MrBFlt **vals, int nRows, int *rowCount, Stat *theStats, int HPD)
{
int i, nVals;
MrBFlt *theValues, *p, *ESS;
nVals = 0;
for (i=0; i<nRows; i++)
nVals += rowCount[i];
theValues = (MrBFlt *) SafeMalloc ((size_t)nVals * sizeof(MrBFlt));
/* extract values */
p = theValues;
for (i=0; i<nRows; i++)
{
memcpy ((void *)(p), (void *)(vals[i]), (size_t)rowCount[i] * sizeof(MrBFlt));
p += rowCount[i];
}
/* get statistics */
MeanVariance (theValues, nVals, &(theStats->mean), &(theStats->var));
if (HPD == YES)
LowerUpperMedianHPD (theValues, nVals, &(theStats->lower), &(theStats->upper), &(theStats->median));
else
LowerUpperMedian (theValues, nVals, &(theStats->lower), &(theStats->upper), &(theStats->median));
if (nRows > 1)
theStats->PSRF = PotentialScaleReduction (vals, nRows, rowCount);
ESS = (MrBFlt *) SafeMalloc ((size_t)nRows * sizeof(MrBFlt));
EstimatedSampleSize (vals, nRows, rowCount, ESS);
theStats->avrESS = theStats->minESS = ESS[0];
for (i=1; i<nRows; i++)
{
theStats->avrESS += ESS[i];
if (theStats->minESS > ESS[i])
{
theStats->minESS = ESS[i];
}
}
theStats->avrESS /=nRows;
free (ESS);
free (theValues);
}
/* HarmonicArithmeticMean: Calculate harmonic and arithmetic mean from log values */
int HarmonicArithmeticMeanOnLogs (MrBFlt *vals, int nVals, MrBFlt *mean, MrBFlt *harm_mean)
{
int i, reliable;
MrBFlt a, x, y, scaler, n;
reliable = YES;
scaler = vals[nVals-1];
a = n = 0.0;
for (i=0; i<nVals; i++)
{
y = vals[i];
y -= scaler;
if (y > 400.0)
{
if (y > 5000.0)
{
reliable = NO;
continue;
}
a /= exp(y - 100.0);
scaler += y - 100.0;
y = 100.0;
}
x = (MrBFlt) exp(y);
if (n < 0.5)
a = x;
else
{
a += x;
}
n += 1.0;
}
/* arithmetic mean */
(*mean) = (MrBFlt) log(a/n) + scaler;
scaler = (MrBFlt) (0.0 - vals[nVals-1]);
a = n = 0.0;
for (i=0; i<nVals; i++)
{
y = (MrBFlt) (0.0 - vals[i]);
y -= scaler;
if (y > 400.0)
{
if (y > 5000.0)
{
reliable = NO;
continue;
}
a /= exp(y - 100.0);
scaler += y - 100.0;
y = 100.0;
}
x = (MrBFlt) exp(y);
if (n < 0.5)
a = x;
else
{
a += x;
}
n += (MrBFlt) 1.0;
}
/* harmonic mean */
(*harm_mean) = - (MrBFlt) log(a/n) - scaler;
if (reliable == YES)
return (NO_ERROR);
else
return (ERROR);
}
/* IsBitSet: Is bit i set in BitsLong *bits ? */
int IsBitSet (int i, BitsLong *bits)
{
BitsLong x, bitsLongOne=1;
bits += i / nBitsInALong;
x = bitsLongOne << (i % nBitsInALong);
if ((*bits) & x)
return (YES);
else
return (NO);
}
/* IsConsistentWith: Is token consistent with expected word, case insensitive ? */
int IsConsistentWith (const char *token, const char *expected)
{
int i, len;
if (strlen(token) > strlen(expected))
return NO;
len = (int) strlen (token);
for (i=0; i<len; i++)
{
if (tolower(token[i]) != tolower(expected[i]))
return NO;
}
return YES;
}
/* IsPartCompatible: Determine whether two partitions are nonoverlapping or nested (compatible) or
incompatible (partially overlapping) */
int IsPartCompatible (BitsLong *smaller, BitsLong *larger, int length)
{
int i;
/* test first if they overlap */
for (i=0; i<length; i++)
if ((smaller[i]&larger[i]) != 0)
break;
/* if they overlap, they must be nested */
if (i != length) /* potentially incompatible */
{
for (i=0; i<length; i++)
if ((smaller[i]|larger[i]) != larger[i])
break;
}
if (i == length) /* passed either one of the tests */
return YES;
else
return NO;
}
/* IsPartNested: Test whether smaller partition is nested in larger partition */
int IsPartNested (BitsLong *smaller, BitsLong *larger, int length)
{
int i;
for (i=0; i<length; i++)
if ((smaller[i] | larger[i]) != larger[i])
break;
if (i == length)
return YES;
else
return NO;
}
/* IsSectionEmpty: Test whether section of two bitfields is empty */
int IsSectionEmpty (BitsLong *bitField1, BitsLong *bitField2, int length)
{
int i;
for (i=0; i<length; i++)
if ((bitField1[i] & bitField2[i]) != 0)
return NO;
return YES;
}
/* IsSectionEmpty: Test whether union of bitField1 and bitField2 equal to bitField3*/
int IsUnionEqThird (BitsLong *bitField1, BitsLong *bitField2, BitsLong *bitField3, int length)
{
int i;
for (i=0; i<length; i++)
if ((bitField1[i] | bitField2[i]) != bitField3[i])
return NO;
return YES;
}
/* LastBlock: Return file position of last block in file */
long LastBlock (FILE *fp, char *lineBuf, int longestLine)
{
long lastBlock;
char *word;
lastBlock = 0L;
rewind (fp);
while ((fgets (lineBuf, longestLine, fp)) != NULL)
{
word = strtok (lineBuf, " ");
if (strcmp (word, "begin") == 0)
lastBlock = ftell (fp);
}
return lastBlock;
}
int LineTermType (FILE *fp)
{
int ch, nextCh, term;
term = LINETERM_UNIX; /* default if no line endings are found */
while ((ch = getc(fp)) != EOF)
{
if ((ch == '\n') || (ch == '\r'))
{
if (ch == '\n')
term = LINETERM_UNIX;
else /* ch = '\r' */
{
/* First test below handles one-line MAC file */
if (((nextCh = getc(fp)) == EOF) || (nextCh != '\n'))
term = LINETERM_MAC;
else
term = LINETERM_DOS;
}
break;
}
}
(void)fseek(fp, 0L, 0); /* rewind */
return (term);
}
/*The longest line in a file including line terminating characters present in binary mode.*/
int LongestLine (FILE *fp)
{
int ch, lineLength, longest;
longest = 0;
lineLength = 0;
ch = fgetc(fp);
while (ch != EOF)
{
if ((ch != '\n') && (ch != '\r'))
{
ch = fgetc(fp);
lineLength++;
continue;
}
if (ch == '\r')
{
if ((ch = fgetc(fp)) == '\n')
{
/* windows \r\n */
lineLength++;
ch = fgetc(fp);
}
else
{
/* old mac \r */
}
}
else /*unix, linux,new mac or text mode read \n*/
{
ch = fgetc(fp);
}
if (lineLength > longest)
longest = lineLength;
lineLength = 0;
/*
if ((ch == '\n') || (ch == '\r'))
{
if (lineLength > longest)
longest = lineLength;
lineLength = 0;
}
else
lineLength++;
*/
}
rewind (fp); /* rewind */
return (longest+1); /*+1 to accommodate last character*/
}
/* LowerUpperMedian: Determine median and 95 % credible interval */
void LowerUpperMedian (MrBFlt *vals, int nVals, MrBFlt *lower, MrBFlt *upper, MrBFlt *median)
{
SortMrBFlt (vals, 0, nVals-1);
*lower = vals[(int)(0.025*nVals)];
*upper = vals[(int)(0.975*nVals)];
*median = vals[nVals/2];
}
/* LowerUpperMedianHPD: Use a simple way to determine HPD */