/* Affine-invariant MCMC method of Goodman and Weare 2010. Here we analyze a one-dimensional Gaussian. */ #include #include #include #include #define amult 2.0 /* Parameter for selection of multiplier */ #define Nmult 30 /* Number of walkers = Nmult times number of parameters */ #define Ndat 28 /* Number of data points */ #define dLogl 8.0 /* Threshold for convergence */ #define Nconv 50 /* Spread of steps to test convergence */ #define dlogltol 20.0 /* Require for convergence that walkers be this close */ #define Maxsteps 10000 /* Maximum number of steps allowed */ #define Ncolumn 4 /* Number of columns of data */ #define PI 3.14159265359 void initialize(double **y, double *logl, int Nparam, int Nwalker); void mcmc(double **y, double *logl, int N, int Nparam, int Nwalker, char *datfile); double loglikelihood(double *z, int Nparam); int inbounds(double *z, int Nparam); void stepprint(double **y, double *logl, int Nparam, int Nwalker, char *datfile); int converged,Nstep; int try,success; double *limmin,*limmax; double *ybest,loglbest; double **loglhistory; double **datax; int main(int argc, char *argv[]) { int j,i,N,M,Nparam,Nwalker; char **name; double **y,*logl; FILE *limits,*data,*acceptfrac; srand48(getpid()); Nparam=atoi(argv[3]); ybest=calloc(Nparam,sizeof(double)); limmin=calloc(Nparam,sizeof(double)); limmax=calloc(Nparam,sizeof(double)); limits=fopen("limits.dat","r"); for (i=0; ilimmax[j]) bound=0; } return bound; } void stepprint(double **y, double *logl, int Nparam, int Nwalker, char *datfile) { int i,istretch,j,*accept; double **ycand,Z,x,*loglcand; FILE *dat; dat=fopen(datfile,"a"); accept=calloc(Nwalker,sizeof(int)); ycand=calloc(Nwalker,sizeof(double *)); for (i=0; iloglbest) { loglbest=loglcand[i]; for (j=0; j=Nconv) { if (loglhistory[i][Nstep]>loglhistory[i][Nstep-Nconv]+dLogl) converged=0; } } /* If we think we might have converged, next step is to see whether all of the walkers have log likelihoods within some tolerance of the best logl. */ if (converged==1 && Nstep>=Nconv) /* Possible convergence; let's check */ { for (i=0; i