-
Notifications
You must be signed in to change notification settings - Fork 5
/
mcmc.c
19086 lines (17370 loc) · 699 KB
/
mcmc.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
*
* Fredrik Ronquist
* Swedish Museum of Natural History
* Box 50007
* SE-10405 Stockholm, SWEDEN
*
* With important contributions by
*
* Paul van der Mark ([email protected])
* Maxim Teslenko ([email protected])
*
* 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 "likelihood.h"
#include "mbbeagle.h"
#include "mcmc.h"
#include "model.h"
#include "proposal.h"
#include "sumpt.h"
#include "utils.h"
#if defined(__MWERKS__)
#include "SIOUX.h"
#endif
#include <signal.h>
const char* const svnRevisionMcmcC = "$Rev: 1072 $"; /* Revision keyword which is expanded/updated by svn on each commit/update */
#if defined (WIN_VERSION) && !defined (__GNUC__)
#define VISUAL
#else
typedef void (*sighandler_t) (int);
#endif
#define RESCALE_FREQ 1 /* node cond like rescaling frequency */
#define SCALER_REFRESH_FREQ 1 /* generations between refreshing scaler nodes */
#define GIBBS_SAMPLE_FREQ 100 /* generations between gibbs sampling of gamma cats */
#define MAX_SMALL_JUMP 10 /* threshold for precalculating trans probs of adgamma model */
#define BIG_JUMP 100 /* threshold for using stationary approximation */
#define MAX_RUNS 120 /* maximum number of independent runs */
#define PFILE 0
#define TFILE 1
#define CALFILE 2
#define MCMCFILE 3
#define MAXTUNINGPARAM 10000 /* limit to ensure convergence for autotuning */
#define SAMPLE_ALL_SS /* if defined makes ss sample every generation instead of every sample frequency */
#define BEAGLE_RESCALE_FREQ 160
#define BEAGLE_RESCALE_FREQ_DOUBLE 10 /* The factor by which BEAGLE_RESCALE_FREQ get multiplied if double presition is used */
#define TARGETLENDELTA 100
/* debugging compiler statements */
#undef DEBUG_SETUPTERMSTATE
#undef DEBUG_RUNCHAIN
#undef DEBUG_NOSHORTCUTS
#undef DEBUG_NOSCALING
#undef DEBUG_TIPROBS_STD
#undef DEBUG_RUN_WITHOUT_DATA
#undef DEBUG_CONSTRAINTS
#undef DEBUG_LNLIKELIHOOD /* slow if defined!! */
#undef DEBUG_LIKELIHOOD
#undef DEBUG_FBDPR // #undef FBDPR_CondOnN
#undef SHOW_MOVE
#if defined (MPI_ENABLED)
#define ERROR_TEST2(failString,X1,X2) \
MPI_Allreduce (&nErrors, &sumErrors, 1, MPI_INT, MPI_SUM, MPI_COMM_WORLD);\
if (sumErrors > 0)\
{\
MrBayesPrint ("%s "failString"\n", spacer);\
X1;X2;\
}
#else
#define ERROR_TEST2(failString,X1,X2) \
if (nErrors > 0)\
{\
MrBayesPrint ("%s "failString"\n", spacer);\
X1;X2;\
}
#endif
/* local (to this file) data types */
typedef struct pfnode
{
struct pfnode *left;
struct pfnode *right;
int *count;
BitsLong *partition;
} PFNODE;
/* local prototypes */
int AddTreeSamples (int from, int to, int saveToList);
PFNODE *AddPartition (PFNODE *r, BitsLong *p, int runId);
int AddTreeToPartitionCounters (Tree *tree, int treeId, int runId);
int AttemptSwap (int swapA, int swapB, RandLong *seed);
void BuildExhaustiveSearchTree (Tree *t, int chain, int nTaxInTree, TreeInfo *tInfo);
int BuildStepwiseTree (Tree *t, int chain, RandLong *seed);
int CalcLikeAdgamma (int d, Param *param, int chain, MrBFlt *lnL);
void CalcPartFreqStats (PFNODE *p, STATS *stat);
void CalcTopoConvDiagn (int numSamples);
#ifdef VISUAL
BOOL WINAPI CatchInterrupt (DWORD signum);
#else
void CatchInterrupt (int signum);
#endif
int CheckTemperature (void);
void CloseMBPrintFiles (void);
PFNODE *CompactTree (PFNODE *p);
int ConfirmAbortRun(void);
void CopyParams (int chain);
void CopyPFNodeDown (PFNODE *p);
void CopySiteScalers (ModelInfo *m, int chain);
void CopyTrees (int chain);
int ExtendChainQuery (void);
int FillNumSitesOfPat (void);
TreeNode *FindBestNode (Tree *t, TreeNode *p, TreeNode *addNode, CLFlt *minLength, int chain);
void FlipCijkSpace (ModelInfo *m, int chain);
void FlipCondLikeSpace (ModelInfo *m, int chain, int nodeIndex);
void FlipNodeScalerSpace (ModelInfo *m, int chain, int nodeIndex);
void FlipSiteScalerSpace (ModelInfo *m, int chain);
void FlipTiProbsSpace (ModelInfo *m, int chain, int nodeIndex);
void FreeChainMemory (void);
MrBFlt GetFitchPartials (ModelInfo *m, int chain, int source1, int source2, int destination);
void GetStamp (void);
void GetSwappers (int *swapA, int *swapB, int curGen);
void GetTempDownPassSeq (TreeNode *p, int *i, TreeNode **dp);
MrBFlt GibbsSampleGamma (int chain, int division, RandLong *seed);
int InitAdGamma(void);
int InitChainCondLikes (void);
int InitClockBrlens (Tree *t);
int InitEigenSystemInfo (ModelInfo *m);
int InitInvCondLikes (void);
int InitParsSets (void);
int InitPrintParams (void);
int IsPFNodeEmpty (PFNODE *p);
PFNODE *LargestNonemptyPFNode (PFNODE *p, int *i, int j);
MrBFlt LogLike (int chain);
MrBFlt LogPrior (int chain);
int LnBirthDeathPriorPrRandom (Tree *t, MrBFlt clockRate, MrBFlt *prob, MrBFlt sR, MrBFlt eR, MrBFlt sF);
int LnBirthDeathPriorPrDiversity (Tree *t, MrBFlt clockRate, MrBFlt *prob, MrBFlt sR, MrBFlt eR, MrBFlt sF);
int LnBirthDeathPriorPrCluster (Tree *t, MrBFlt clockRate, MrBFlt *prob, MrBFlt sR, MrBFlt eR, MrBFlt sF);
int LnFossilizedBDPriorFossilTip (Tree *t, MrBFlt clockRate, MrBFlt *prob, MrBFlt sR, MrBFlt eR, MrBFlt sF, MrBFlt fR);
int LnFossilizedBDPriorRandom (Tree *t, MrBFlt clockRate, MrBFlt *prob, MrBFlt *sR, MrBFlt *eR, MrBFlt sF, MrBFlt *fR);
int LnFossilizedBDPriorDiversity (Tree *t, MrBFlt clockRate, MrBFlt *prob, MrBFlt *sR, MrBFlt *eR, MrBFlt sF, MrBFlt *fR);
MrBFlt LnP0 (MrBFlt t, MrBFlt l, MrBFlt m);
MrBFlt LnP0Subsample (MrBFlt t, MrBFlt l, MrBFlt m, MrBFlt f);
MrBFlt LnP1 (MrBFlt t, MrBFlt l, MrBFlt m);
MrBFlt LnP1Subsample (MrBFlt t, MrBFlt l, MrBFlt m, MrBFlt f);
MrBFlt LnP0_fossil (MrBFlt t, MrBFlt lambda, MrBFlt mu, MrBFlt psi, MrBFlt c1, MrBFlt c2);
MrBFlt LnP1_fossil (MrBFlt t, MrBFlt rho, MrBFlt c1, MrBFlt c2);
MrBFlt LnQi_fossil (MrBFlt t, MrBFlt *t_f, int sl, MrBFlt *c1, MrBFlt *c2);
MrBFlt LnPi_fossil (MrBFlt t, MrBFlt *t_f, int sl, MrBFlt *c1, MrBFlt *c2, MrBFlt *lambda, MrBFlt *mu, MrBFlt *psi);
int NewtonRaphsonBrlen (Tree *t, TreeNode *p, int chain);
void NodeToNodeDistances (Tree *t, TreeNode *fromNode);
int PickProposal (RandLong *seed, int chainIndex);
int NumCppEvents (Param *p, int chain);
int PosSelProbs (TreeNode *p, int division, int chain);
#if defined (SSE_ENABLED)
int PosSelProbs_SSE (TreeNode *p, int division, int chain);
#endif
int PreparePrintFiles (void);
int PrintAncStates_Bin (TreeNode *p, int division, int chain);
int PrintAncStates_Gen (TreeNode *p, int division, int chain);
int PrintAncStates_NUC4 (TreeNode *p, int division, int chain);
int PrintAncStates_Std (TreeNode *p, int division, int chain);
int PrintCalTree (int curGen, Tree *tree);
int PrintCheckPoint (int gen);
int PrintMCMCDiagnosticsToFile (int curGen);
#if defined (MPI_ENABLED)
int PrintMPISlaves (FILE *fp);
#endif
void PrintParamValues (Param *p, int chain, char *s);
int PrintParsMatrix (void);
int PrintSiteRates_Gen (TreeNode *p, int division, int chain);
int PrintSiteRates_Std (TreeNode *p, int division, int chain);
int PrintStates (int curGen, int coldId);
int PrintStatesToFiles (int n);
int PrintSwapInfo (void);
int PrintTermState (void);
void PrintTiProbs (CLFlt *tP, MrBFlt *bs, int nStates);
int PrintTopConvInfo (void);
void PrintToScreen (int curGen, int startGen, time_t endingT, time_t startingT);
int PrintTree (int curGen, Param *treeParam, int chain, int showBrlens, MrBFlt clockRate);
MrBFlt PropAncFossil (Param *param, int chain);
#if defined (MPI_ENABLED)
int ReassembleMoveInfo (void);
int ReassembleParamVals (int *curId);
int ReassembleSwapInfo (void);
int ReassembleTuningParams (void);
void RedistributeMoveInfo (void);
int RedistributeParamVals (void);
int RedistributeTuningParams (void);
#endif
int RemovePartition (PFNODE *r, BitsLong *p, int runId);
int RemoveTreeFromPartitionCounters (Tree *tree, int treeId, int runId);
int RemoveTreeSamples (int from, int to);
int ReopenMBPrintFiles (void);
void ResetChainIds (void);
void ResetFlips(int chain);
int ResetScalers (void);
void ResetSiteScalers (ModelInfo *m, int chain);
int ReusePreviousResults(int *numSamples, int);
int RunChain (RandLong *seed);
int SafeSprintf (char **target, int *targetLen, char *fmt, ...);
void SetChainIds (void);
void SetFileNames (void);
int SetLikeFunctions (void);
int SetLocalChainsAndDataSplits (void);
int SetModelInfo (void);
int SetMoves (void);
int SetBinaryQMatrix (MrBFlt **a, int whichChain, int division);
int SetNucQMatrix (MrBFlt **a, int n, int whichChain, int division, MrBFlt rateMult, MrBFlt *rA, MrBFlt *rS);
int SetProteinQMatrix (MrBFlt **a, int n, int whichChain, int division, MrBFlt rateMult);
int SetStdQMatrix (MrBFlt **a, int nStates, MrBFlt *bs, int cType);
int SetUpPartitionCounters (void);
int SetUpTermState (void);
int SetUsedMoves (void);
int ShowMoveSummary (void);
void ShowValuesForChain (int chn);
int SiteOmegas (TreeNode *p, int division, int chain);
#if defined (SSE_ENABLED)
int SiteOmegas_SSE (TreeNode *p, int division, int chain);
#endif
PFNODE *SmallestNonemptyPFNode (PFNODE *p, int *i, int j);
PFNODE *Talloc (void);
void Tfree (PFNODE *r);
MrBFlt Temperature (int x);
void TouchAllCijks (int chain);
void TouchAllPartitions (void);
void TouchAllTrees (int chain);
void TouchEverything (int chain);
/* globals */
int *bsIndex; /* compressed std stat freq index */
Chain chainParams; /* parameters of Markov chain */
int *compCharPos; /* char position in compressed matrix */
int *compColPos; /* column position in compressed matrix */
BitsLong *compMatrix; /* compressed character matrix */
int compMatrixRowSize; /* row size of compressed matrix */
char inputFileName[100]; /* input (NEXUS) file name */
MoveType moveTypes[NUM_MOVE_TYPES]; /* holds information on the move types */
int numCompressedChars; /* number of compressed characters */
int numMoveTypes; /* the number of move types */
CLFlt *numSitesOfPat; /* no. sites of each pattern */
int *origChar; /* index from compressed char to original char */
char stamp[11]; /* holds a unique identifier for each analysis */
MrBFlt *stdStateFreqs; /* std char state frequencies */
int *stdType; /* compressed std char type: ord, unord, irrev */
int *tiIndex; /* compressed std char ti index */
#if defined (BEAGLE_ENABLED)
int recalcScalers; /* shoud we recalculate scalers for current state YES/NO */
#endif
/* local (to this file) variables */
int numLocalChains; /* number of Markov chains */
int *chainId = NULL; /* information on the id (0 ...) of the chain */
MrBFlt *curLnL = NULL; /* stores log likelihood */
MrBFlt *curLnPr = NULL; /* stores log prior probability */
int stepRelativeBurninSS; /* Should we use relative burn in within each step or not */
MrBFlt powerSS; /* power (betta) in power posterior destribution used in SS */
MrBFlt *marginalLnLSS = NULL; /* marginal liklihood obtained using stepppingstone sampling */
MrBFlt *stepAcumulatorSS = NULL; /* accumulates liklihoods for current step in SS */
MrBFlt *stepScalerSS = NULL; /* scaler of stepAcumulatorSS in log scale in SS */
MrBFlt *splitfreqSS = NULL; /* array holding split frequencis for each step in SS */
int *sympiIndex; /* sympi state freq index for multistate chars */
int stdStateFreqsRowSize; /* row size for std state frequencies */
int *weight; /* weight of each compressed char */
int *chainTempId; /* info ton temp, change to float holding temp? */
int state[MAX_CHAINS]; /* state of chain */
int augmentData; /* are data being augmented for any division? */
int *nAccepted; /* counter of accepted moves */
int *termState = NULL; /* stores character states of tips */
int *isPartAmbig = NULL; /* records whether tips are partially ambiguous */
BitsLong **parsPtrSpace = NULL; /* space holding pointers to parsimony sets */
BitsLong ***parsPtr = NULL; /* pointers to pars state sets for chain & node */
CLFlt *parsNodeLengthSpace = NULL; /* space for parsimony node lengths */
CLFlt **parsNodeLen = NULL; /* pointers to pars node lengths for chains */
char *printString; /* string for printing to a file */
size_t printStringSize; /* length of printString */
MCMCMove **usedMoves; /* vector of pointers to used moves */
int numUsedMoves; /* the number of moves used by chain */
Param **printParam; /* vector of pointers to normal params to print */
int numPrintParams; /* the number of normal params to print */
Param **printTreeParam; /* vector of pointers to tree params to print */
Param **topologyParam; /* vector of pointers to topology params */
int numPrintTreeParams; /* the number of tree params to print */
int codon[6][64]; /* holds info on amino acids coded in code */
int chainHasAdgamma; /* indicates if chain has adgamma HMMs */
int inferPosSel; /* indicates if positive selection is inferred */
MrBFlt *posSelProbs; /* probs. for positive selection */
int hasMarkovTi[MAX_SMALL_JUMP]; /* vector marking size of observed HMM jumps */
int *siteJump; /* vector of sitejumps for adgamma model */
MrBFlt **rateProbs; /* pointers to rate probs used by adgamma model */
MrBFlt *rateProbSpace; /* space for rate probs used by adgamma model */
int rateProbRowSize; /* size of rate probs for one chain one state */
MrBFlt **markovTi[MAX_SMALL_JUMP]; /* trans prob matrices used in calc of adgamma */
MrBFlt **markovTiN; /* trans prob matrices used in calc of adgamma */
int whichReweightNum; /* used for setting reweighting of char pats */
int ***swapInfo; /* keeps track of attempts & successes of swaps */
int tempIndex; /* keeps track of which user temp is specified */
int abortMove; /* flag determining whether to abort move */
PFNODE **partFreqTreeRoot; /* root of tree(s) holding partition freqs */
int nLongsNeeded; /* number of longs needed for partitions */
BitsLong **partition; /* matrix holding partitions */
MrBFlt *maxLnL0 = NULL; /* maximum likelihood */
FILE *fpMcmc = NULL; /* pointer to .mcmc file */
FILE **fpParm = NULL; /* pointer to .p file(s) */
FILE ***fpTree = NULL; /* pointer to .t file(s) */
FILE *fpSS = NULL; /* pointer to .ss file */
static int requestAbortRun; /* flag for aborting mcmc analysis */
int *topologyPrintIndex; /* print file index of each topology */
int *printTreeTopologyIndex; /* topology index of each tree print file */
int numPreviousGen; /* number of generations in run to append to */
#if defined (MPI_ENABLED)
int lowestLocalRunId; /* lowest local run Id */
int highestLocalRunId; /* highest local run Id */
#endif
#if defined (PRINT_DUMP)
FILE **fpDump = NULL; /* pointer to .dump file(s) */
#endif
/* AddPartition: Add a partition to the tree keeping track of partition frequencies */
PFNODE *AddPartition (PFNODE *r, BitsLong *p, int runId)
{
int i, comp;
if (r == NULL)
{
/* new partition */
r = Talloc (); /* create a new node */
if (r == NULL)
return NULL;
for (i=0; i<nLongsNeeded; i++)
r->partition[i] = p[i];
for (i=0; i<chainParams.numRuns; i++)
r->count[i] = 0;
r->count[runId] = 1;
r->left = r->right = NULL;
}
else
{
for (i=0; i<nLongsNeeded; i++)
{
if (r->partition[i] != p[i])
break;
}
if (i == nLongsNeeded)
comp = 0;
else if (r->partition[i] < p[i])
comp = -1;
else
comp = 1;
if (comp == 0) /* repeated partition */
r->count[runId]++;
else if (comp < 0) /* greater than -> into left subtree */
{
if ((r->left = AddPartition (r->left, p, runId)) == NULL)
{
Tfree (r);
return NULL;
}
}
else
{
/* smaller than -> into right subtree */
if ((r->right = AddPartition (r->right, p, runId)) == NULL)
{
Tfree (r);
return NULL;
}
}
}
return r;
}
int AddToPrintString (char *tempStr)
{
size_t len1, len2;
len1 = strlen(printString);
len2 = strlen(tempStr);
if (len1 + len2 + 5 > printStringSize)
{
printStringSize += len1 + len2 - printStringSize + 200;
printString = (char*)SafeRealloc((void*)printString, printStringSize * sizeof(char));
if (!printString)
{
MrBayesPrint ("%s Problem reallocating printString (%d)\n", spacer, printStringSize * sizeof(char));
goto errorExit;
}
}
strcat(printString, tempStr);
// printf ("printString(%d) -> \"%s\"\n", printStringSize, printString);
return (NO_ERROR);
errorExit:
return (ERROR);
}
/* AddTreeSamples: Add tree samples from .t files to partition counters. if saveToList == YES then also save trees in tree list */
int AddTreeSamples (int from, int to, int saveToList)
{
int i, j, k, longestLine;
BitsLong lastBlock;
char *word, *s, *lineBuf;
FILE *fp;
Tree *t;
char *tempStr;
int tempStrSize = TEMPSTRSIZE;
if (from > to)
return (NO_ERROR);
# if defined (MPI_ENABLED)
if (proc_id != 0)
return (NO_ERROR);
# endif
tempStr = (char *) SafeMalloc((size_t)tempStrSize * sizeof(char));
if (!tempStr)
{
MrBayesPrint ("%s Problem allocating tempString (%d)\n", spacer, tempStrSize * sizeof(char));
return (ERROR);
}
for (i=0; i<numTopologies; i++)
{
t = chainParams.dtree;
for (j=0; j<chainParams.numRuns; j++)
{
if (numPrintTreeParams == 1)
{
if (chainParams.numRuns == 1)
SafeSprintf (&tempStr, &tempStrSize, "%s.t", chainParams.chainFileName);
else
SafeSprintf (&tempStr, &tempStrSize, "%s.run%d.t", chainParams.chainFileName, j+1);
}
else
{
if (chainParams.numRuns == 1)
SafeSprintf (&tempStr, &tempStrSize, "%s.tree%d.t", chainParams.chainFileName, i+1);
else
SafeSprintf (&tempStr, &tempStrSize, "%s.tree%d.run%d.t", chainParams.chainFileName, i+1, j+1);
}
if ((fp = OpenBinaryFileR (tempStr)) == NULL)
{
MrBayesPrint ("%s Problem openning file %s.\n", spacer, tempStr);
free (tempStr);
return (ERROR);
}
longestLine = LongestLine (fp);
SafeFclose (&fp);
if ((fp = OpenTextFileR (tempStr)) == NULL)
{
free (tempStr);
return (ERROR);
}
lineBuf = (char *) SafeCalloc (longestLine + 10, sizeof (char));
if (!lineBuf)
{
SafeFclose (&fp);
free (tempStr);
return (ERROR);
}
lastBlock = LastBlock (fp, lineBuf, longestLine);
fseek (fp, lastBlock, SEEK_SET);
for (k=1; k<=to; k++)
{
do {
if (fgets (lineBuf, longestLine, fp) == NULL)
{
SafeFclose (&fp);
free (lineBuf);
free (tempStr);
return ERROR;
}
word = strtok (lineBuf, " ");
} while (strcmp (word, "tree") != 0);
if (k>=from)
{
s = strtok (NULL, ";");
while (*s != '(')
s++;
StripComments(s);
if (ResetTopology (t, s) == ERROR)
{
SafeFclose (&fp);
free (lineBuf);
free (tempStr);
return ERROR;
}
if (AddTreeToPartitionCounters (t, i, j) == ERROR)
{
SafeFclose (&fp);
free (lineBuf);
free (tempStr);
return ERROR;
}
if (saveToList == YES)
if (AddToTreeList(&chainParams.treeList[numTopologies*j+i],t) == ERROR)
return (ERROR);
}
}
SafeFclose (&fp);
free (lineBuf);
} /* next run */
} /* next tree */
free (tempStr);
return (NO_ERROR);
}
/* AddTreeToPartitionCounters: Break a tree into partitions and add those to counters */
int AddTreeToPartitionCounters (Tree *tree, int treeId, int runId)
{
int i, j, nTaxa;
TreeNode *p;
if (tree->isRooted == YES)
nTaxa = tree->nNodes - tree->nIntNodes - 1;
else
nTaxa = tree->nNodes - tree->nIntNodes;
for (i=0; i<nTaxa; i++)
{
ClearBits(partition[i], nLongsNeeded);
SetBit(i, partition[i]);
}
for (i=0; i<tree->nIntNodes-1; i++)
{
p = tree->intDownPass[i];
assert (p->index >= tree->nNodes - tree->nIntNodes - (tree->isRooted == YES ? 1 : 0));
for (j=0; j<nLongsNeeded; j++)
{
partition[p->index][j] = partition[p->left->index][j] | partition[p->right->index][j];
}
if ((partFreqTreeRoot[treeId] = AddPartition (partFreqTreeRoot[treeId], partition[p->index], runId)) == NULL)
{
MrBayesPrint ("%s Could not allocate space for new partition in AddTreeToPartitionCounters\n", spacer);
return ERROR;
}
}
return NO_ERROR;
}
int AttemptSwap (int swapA, int swapB, RandLong *seed)
{
int d, tempX, reweightingChars, isSwapSuccessful, chI, chJ, runId;
MrBFlt tempA, tempB, lnLikeA, lnLikeB, lnPriorA, lnPriorB, lnR, r,
lnLikeStateAonDataB=0.0, lnLikeStateBonDataA=0.0, lnL;
ModelInfo *m;
Tree *tree;
# if defined (MPI_ENABLED)
int numChainsForProc, tempIdA=0, tempIdB=0, proc, procIdForA=0, procIdForB=0, tempIdMy=0, procIdPartner=0,
whichElementA=0, whichElementB=0, lower, upper, areWeA, doISwap, ierror,
myId, partnerId, i, run;
MrBFlt swapRan;
MPI_Status status[2];
MPI_Request request[2];
# endif
# if defined (MPI_ENABLED)
/* get the number of chains handled by this proc */
/* the number will be corrected further down for unbalanced scenarios */
numChainsForProc = (int) (chainParams.numChains * chainParams.numRuns / num_procs);
# endif
/* are we using character reweighting? */
reweightingChars = NO;
if ((chainParams.weightScheme[0] + chainParams.weightScheme[1]) > 0.00001)
reweightingChars = YES;
# if defined (MPI_ENABLED)
/* figure out processors involved in swap */
lower = upper = 0;
for (proc=0; proc<num_procs; proc++)
{
/* assign or increment chain id */
if (proc < (chainParams.numChains * chainParams.numRuns) % num_procs)
upper += numChainsForProc+1;
else
upper += numChainsForProc;
/* if swapA lies between lower and upper
* chain id's we know that this is the proc
* swapA is in */
if (swapA >= lower && swapA < upper)
{
procIdForA = proc;
whichElementA = swapA - lower;
}
if (swapB >= lower && swapB < upper)
{
procIdForB = proc;
whichElementB = swapB - lower;
}
lower = upper;
}
/* NOTE: at this point, procIdForA and procIdForB *
* store the proc id's of swapping procs. Also, *
* whichElementA and whichElementB store the *
* chainId[] index of swapping procs */
/* figure out if I am involved in the swap */
doISwap = areWeA = NO;
if (proc_id == procIdForA)
{
doISwap = YES;
areWeA = YES;
}
else if (proc_id == procIdForB)
{
doISwap = YES;
}
/* chain's that do not swap, continue to the next iteration */
if (doISwap == YES)
{
/* no need to communicate accross processors if swapping chains are in the same proc */
if (procIdForA == procIdForB)
{
if (reweightingChars == YES)
{
/* use character reweighting */
lnLikeStateAonDataB = 0.0;
for (d=0; d<numCurrentDivisions; d++)
{
m = &modelSettings[d];
tree = GetTree(m->brlens, whichElementA, state[whichElementA]);
lnL = 0.0;
m->Likelihood (tree->root->left, d, whichElementA, &lnL, chainId[whichElementB] % chainParams.numChains);
lnLikeStateAonDataB += lnL;
}
lnLikeStateBonDataA = 0.0;
for (d=0; d<numCurrentDivisions; d++)
{
m = &modelSettings[d];
tree = GetTree(m->brlens, whichElementB, state[whichElementB]);
lnL = 0.0;
m->Likelihood (tree->root->left, d, whichElementB, &lnL, chainId[whichElementA] % chainParams.numChains);
lnLikeStateBonDataA += lnL;
}
}
/*curLnPr[whichElementA] = LogPrior(whichElementA);
curLnPr[whichElementB] = LogPrior(whichElementB);*/
/* then do the serial thing - simply swap chain id's */
tempA = Temperature (chainId[whichElementA]);
tempB = Temperature (chainId[whichElementB]);
lnLikeA = curLnL[whichElementA];
lnLikeB = curLnL[whichElementB];
if (chainParams.isSS == YES)
{
lnLikeA *= powerSS;
lnLikeB *= powerSS;
}
lnPriorA = curLnPr[whichElementA];
lnPriorB = curLnPr[whichElementB];
if (reweightingChars == YES)
{
if (chainParams.isSS == YES)
lnR = (tempB * (lnLikeStateAonDataB*powerSS + lnPriorA) + tempA * (lnLikeStateBonDataA*powerSS + lnPriorB)) - (tempA * (lnLikeA + lnPriorA) + tempB * (lnLikeB + lnPriorB));
else
lnR = (tempB * (lnLikeStateAonDataB + lnPriorA) + tempA * (lnLikeStateBonDataA + lnPriorB)) - (tempA * (lnLikeA + lnPriorA) + tempB * (lnLikeB + lnPriorB));
}
else
lnR = (tempB * (lnLikeA + lnPriorA) + tempA * (lnLikeB + lnPriorB)) - (tempA * (lnLikeA + lnPriorA) + tempB * (lnLikeB + lnPriorB));
if (lnR < -100.0)
r = 0.0;
else if (lnR > 0.0)
r = 1.0;
else
r = exp(lnR);
isSwapSuccessful = NO;
if (RandomNumber(seed) < r)
{
/* swap chain id's (heats) */
tempX = chainId[whichElementA];
chainId[whichElementA] = chainId[whichElementB];
chainId[whichElementB] = tempX;
if (reweightingChars == YES)
{
curLnL[whichElementA] = lnLikeStateAonDataB;
curLnL[whichElementB] = lnLikeStateBonDataA;
}
isSwapSuccessful = YES;
}
chI = chainId[whichElementA];
chJ = chainId[whichElementB];
if (chainId[whichElementB] < chainId[whichElementA])
{
chI = chainId[whichElementB];
chJ = chainId[whichElementA];
}
runId = chI / chainParams.numChains;
chI = chI % chainParams.numChains;
chJ = chJ % chainParams.numChains;
swapInfo[runId][chJ][chI]++;
if (isSwapSuccessful == YES)
swapInfo[runId][chI][chJ]++;
}
/* we need to communicate across processors */
else
{
if (reweightingChars == YES)
{
/* If we are reweighting characters, then we need to do an additional communication to
figure out the chainId's of the partner. We need to have this information so we can
properly calculate likelihoods with switched observations. */
if (areWeA == YES)
{
lnLikeStateAonDataB = 0.0;
myId = chainId[whichElementA];
ierror = MPI_Isend (&myId, 1, MPI_INT, procIdForB, 0, MPI_COMM_WORLD, &request[0]);
if (ierror != MPI_SUCCESS)
{
return (ERROR);
}
ierror = MPI_Irecv (&partnerId, 1, MPI_INT, procIdForB, 0, MPI_COMM_WORLD, &request[1]);
if (ierror != MPI_SUCCESS)
{
return (ERROR);
}
ierror = MPI_Waitall (2, request, status);
if (ierror != MPI_SUCCESS)
{
return (ERROR);
}
for (d=0; d<numCurrentDivisions; d++)
{
m = &modelSettings[d];
tree = GetTree(m->brlens, whichElementA, state[whichElementA]);
lnL = 0.0;
m->Likelihood (tree->root->left, d, whichElementA, &lnL, partnerId);
lnLikeStateAonDataB = lnL;
}
}
else
{
lnLikeStateBonDataA = 0.0;
myId = chainId[whichElementB];
ierror = MPI_Isend (&myId, 1, MPI_INT, procIdForA, 0, MPI_COMM_WORLD, &request[0]);
if (ierror != MPI_SUCCESS)
{
return (ERROR);
}
ierror = MPI_Irecv (&partnerId, 1, MPI_INT, procIdForA, 0, MPI_COMM_WORLD, &request[1]);
if (ierror != MPI_SUCCESS)
{
return (ERROR);
}
ierror = MPI_Waitall (2, request, status);
if (ierror != MPI_SUCCESS)
{
return (ERROR);
}
for (d=0; d<numCurrentDivisions; d++)
{
m = &modelSettings[d];
tree = GetTree(m->brlens, whichElementB, state[whichElementB]);
lnL = 0.0;
m->Likelihood (tree->root->left, d, whichElementB, &lnL, partnerId);
lnLikeStateBonDataA = lnL;
}
}
}
if (areWeA == YES)
{
/*curLnPr[whichElementA] = LogPrior(whichElementA);*/
/* we are processor A */
tempIdA = chainId[whichElementA];
lnLikeA = curLnL[whichElementA];
lnPriorA = curLnPr[whichElementA];
swapRan = RandomNumber(seed);
myStateInfo[0] = lnLikeA;
myStateInfo[1] = lnPriorA;
myStateInfo[2] = tempIdA;
myStateInfo[3] = swapRan;
myStateInfo[4] = 0.0;
if (reweightingChars == YES)
{
myStateInfo[2] = lnLikeStateAonDataB;
tempIdB = partnerId;
}
ierror = MPI_Isend (&myStateInfo, 5, MPI_DOUBLE, procIdForB, 0, MPI_COMM_WORLD, &request[0]);
if (ierror != MPI_SUCCESS)
{
return (ERROR);
}
ierror = MPI_Irecv (&partnerStateInfo, 5, MPI_DOUBLE, procIdForB, 0, MPI_COMM_WORLD, &request[1]);
if (ierror != MPI_SUCCESS)
{
return (ERROR);
}
ierror = MPI_Waitall (2, request, status);
if (ierror != MPI_SUCCESS)
{
return (ERROR);
}
lnLikeA = curLnL[whichElementA];
lnLikeB = partnerStateInfo[0];
if (chainParams.isSS == YES)
{
lnLikeA *= powerSS;
lnLikeB *= powerSS;
}
lnPriorA = curLnPr[whichElementA];
lnPriorB = partnerStateInfo[1];
if (reweightingChars == YES)
lnLikeStateBonDataA = partnerStateInfo[2];
else
tempIdB = partnerStateInfo[2];
tempA = Temperature (tempIdA);
tempB = Temperature (tempIdB);
if (reweightingChars == YES)
{
if (chainParams.isSS == YES)
lnR = (tempB * (lnLikeStateAonDataB*powerSS + lnPriorA) + tempA * (lnLikeStateBonDataA*powerSS + lnPriorB)) - (tempA * (lnLikeA + lnPriorA) + tempB * (lnLikeB + lnPriorB));
else
lnR = (tempB * (lnLikeStateAonDataB + lnPriorA) + tempA * (lnLikeStateBonDataA + lnPriorB)) - (tempA * (lnLikeA + lnPriorA) + tempB * (lnLikeB + lnPriorB));
}
else
lnR = (tempB * (lnLikeA + lnPriorA) + tempA * (lnLikeB + lnPriorB)) - (tempA * (lnLikeA + lnPriorA) + tempB * (lnLikeB + lnPriorB));
if (lnR < -100.0)
r = 0.0;
else if (lnR > 0.0)
r = 1.0;
else
r = exp(lnR);
/* process A's random number is used to make the swap decision */
isSwapSuccessful = NO;
if (swapRan < r)
{
/* swap chain id's (heats) */
isSwapSuccessful = YES;
tempIdMy = chainId[whichElementA];
procIdPartner = procIdForB;
if (reweightingChars == YES)
chainId[whichElementA] = tempIdB;
else
chainId[whichElementA] = (int)(partnerStateInfo[2]);
if (reweightingChars == YES)
{
curLnL[whichElementA] = lnLikeStateAonDataB;
}
}
/* only processor A keeps track of the swap success/failure */
chI = tempIdA;
chJ = tempIdB;
if (tempIdB < tempIdA)
{
chI = tempIdB;
chJ = tempIdA;
}
runId = chI / chainParams.numChains;
chI = chI % chainParams.numChains;
chJ = chJ % chainParams.numChains;
swapInfo[runId][chJ][chI]++;
if (isSwapSuccessful == YES)
{
swapInfo[runId][chI][chJ]++;
/* exchange the move info */
for (i=0; i<numUsedMoves; i++)
{
myStateInfo[0] = usedMoves[i]->nAccepted[tempIdA];
myStateInfo[1] = usedMoves[i]->nTried[tempIdA];
myStateInfo[2] = usedMoves[i]->nBatches[tempIdA];
myStateInfo[3] = usedMoves[i]->nTotAccepted[tempIdA];
myStateInfo[4] = usedMoves[i]->nTotTried[tempIdA];
myStateInfo[5] = usedMoves[i]->lastAcceptanceRate[tempIdA];
if (usedMoves[i]->moveType->numTuningParams > 0)
myStateInfo[6] = usedMoves[i]->tuningParam[tempIdA][0];
else
myStateInfo[6] = 0.0;
ierror = MPI_Isend (&myStateInfo, 7, MPI_DOUBLE, procIdForB, 0, MPI_COMM_WORLD, &request[0]);
if (ierror != MPI_SUCCESS)
{
return (ERROR);
}
ierror = MPI_Irecv (&partnerStateInfo, 7, MPI_DOUBLE, procIdForB, 0, MPI_COMM_WORLD, &request[1]);
if (ierror != MPI_SUCCESS)
{
return (ERROR);
}
ierror = MPI_Waitall (2, request, status);
if (ierror != MPI_SUCCESS)
{
return (ERROR);
}
usedMoves[i]->nAccepted[tempIdB] = (int)partnerStateInfo[0];
usedMoves[i]->nTried[tempIdB] = (int)partnerStateInfo[1];
usedMoves[i]->nBatches[tempIdB] = (int)partnerStateInfo[2];
usedMoves[i]->nTotAccepted[tempIdB] = (int)partnerStateInfo[3];
usedMoves[i]->nTotTried[tempIdB] = (int)partnerStateInfo[4];
usedMoves[i]->lastAcceptanceRate[tempIdB] = partnerStateInfo[5];
if (usedMoves[i]->moveType->numTuningParams > 0)
usedMoves[i]->tuningParam[tempIdB][0] = partnerStateInfo[6];
usedMoves[i]->nAccepted[tempIdA] = 0;
usedMoves[i]->nTried[tempIdA] = 0;
usedMoves[i]->nBatches[tempIdA] = 0;
usedMoves[i]->lastAcceptanceRate[tempIdA] = 0.0;
usedMoves[i]->nTotAccepted[tempIdA] = 0;
usedMoves[i]->nTotTried[tempIdA] = 0;
if (usedMoves[i]->moveType->numTuningParams > 0)
usedMoves[i]->tuningParam[tempIdA][0] = 0.0;
}
}
}
else
{
/*curLnPr[whichElementB] = LogPrior(whichElementB);*/
/* we are processor B */
tempIdB = chainId[whichElementB];
lnLikeB = curLnL[whichElementB];
lnPriorB = curLnPr[whichElementB];
swapRan = -1.0;
myStateInfo[0] = lnLikeB;
myStateInfo[1] = lnPriorB;
myStateInfo[2] = tempIdB;
myStateInfo[3] = swapRan;
myStateInfo[4] = 0.0;
if (reweightingChars == YES)
{
myStateInfo[2] = lnLikeStateBonDataA;
tempIdA = partnerId;
}
ierror = MPI_Isend (&myStateInfo, 5, MPI_DOUBLE, procIdForA, 0, MPI_COMM_WORLD, &request[0]);
if (ierror != MPI_SUCCESS)
{
return (ERROR);
}
ierror = MPI_Irecv (&partnerStateInfo, 5, MPI_DOUBLE, procIdForA, 0, MPI_COMM_WORLD, &request[1]);