LALInference 4.1.9.1-eeff03c
LALInferenceMCMC.c
Go to the documentation of this file.
1/*
2 * LALInferenceMCMC.c: Bayesian Followup function testing site
3 *
4 * Copyright (C) 2011 Ilya Mandel, Vivien Raymond, Christian Roever,
5 * Marc van der Sluys, John Veitch, Will M. Farr, and Ben Farr
6 *
7 *
8 * This program is free software; you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation; either version 2 of the License, or
11 * (at your option) any later version.
12 *
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
17 *
18 * You should have received a copy of the GNU General Public License
19 * along with with program; see the file COPYING. If not, write to the
20 * Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
21 * MA 02110-1301 USA
22 */
23
24
25#include <stdio.h>
26#include <lal/Date.h>
27#include <lal/GenerateInspiral.h>
28#include <lal/LALInference.h>
29#include <lal/FrequencySeries.h>
30#include <lal/Units.h>
31#include <lal/StringInput.h>
32#include <lal/TimeSeries.h>
34#include <lal/LALInferencePrior.h>
35#include <lal/LALInferenceTemplate.h>
36#include <lal/LALInferenceProposal.h>
37#include <lal/LALInferenceLikelihood.h>
38#include <lal/LALInferenceReadData.h>
39#include <lal/LALInferenceInit.h>
40#include <lal/LALInferenceCalibrationErrors.h>
41
42#include <mpi.h>
43
44
50
51REAL8 **parseMCMCoutput(char ***params, UINT4 *nInPar, UINT4 *nInSamps, char *infilename, UINT4 burnin);
52
53/********** Initialise MCMC structures *********/
54
55/************************************************/
56/* Set the starting seed of rank 0, and give the rest of the threads
57 a seed based on it. This is a cut-and-paste from kombine, which needs
58 to be unified in LALInference when MPI-enabled.*/
60 INT4 i, randomseed;
61 INT4 mpi_rank;
62
63 mpi_rank = LALInferenceGetINT4Variable(run_state->algorithmParams, "mpirank");
64
65 /* Broadcast rank=0's randomseed to everyone */
66 randomseed = LALInferenceGetINT4Variable(run_state->algorithmParams, "random_seed");
67 MPI_Bcast(&randomseed, 1, MPI_INT, 0, MPI_COMM_WORLD);
68 LALInferenceSetVariable(run_state->algorithmParams, "random_seed", &randomseed);
69
70 if (mpi_rank == 0)
71 printf(" initialize(): random seed: %u\n", randomseed);
72
73 /* Now make sure each MPI-thread is running with un-correlated
74 jumps. Re-seed this process with the ith output of
75 the RNG stream from the rank 0 thread. Otherwise the
76 random stream is the same across all threads. */
77 for (i = 0; i < mpi_rank; i++)
78 randomseed = gsl_rng_get(run_state->GSLrandom);
79
80 gsl_rng_set(run_state->GSLrandom, randomseed);
81
82 return;
83}
84
86 char help[]="\
87 ----------------------------------------------\n\
88 --- MCMC Algorithm Parameters ----------------\n\
89 ----------------------------------------------\n\
90 (--nsteps n) Maximum number of steps to take (1e7)\n\
91 (--neff N) Number of independent samples to collect (nsteps)\n\
92 (--skip n) Number of steps between writing samples to file (2000)\n\
93 (--adapt-tau) Adaptation decay power, results in adapt length of 10^tau (5)\n\
94 (--no-adapt) Do not adapt run\n\
95 (--randomseed seed) Random seed of sampling distribution (random)\n\
96 \n\
97 ----------------------------------------------\n\
98 --- Parallel Tempering Algorithm Parameters --\n\
99 ----------------------------------------------\n\
100 (--adapt-temps) Adapt the spacing between temperatures for uniform swap acceptance\n\
101 (--temp-skip N) Number of steps between temperature swap proposals (100)\n\
102 (--tempKill N) Iteration number to stop temperature swapping (Niter)\n\
103 (--ntemps N) Number of temperature chains in ladder (as many as needed)\n\
104 (--temp-min T) Lowest temperature for parallel tempering (1.0)\n\
105 (--temp-max T) Highest temperature for parallel tempering (50.0)\n\
106 (--anneal) Anneal hot temperature linearly to T=1.0\n\
107 (--annealStart N) Iteration number to start annealing (5*10^5)\n\
108 (--annealLength N) Number of iterations to anneal all chains to T=1.0 (1*10^5)\n\
109 \n\
110 ----------------------------------------------\n\
111 --- Noise Model ------------------------------\n\
112 ----------------------------------------------\n\
113 (--psd-fit) Run with PSD fitting\n\
114 (--psdNblock) Number of noise parameters per IFO channel (8)\n\
115 (--psdFlatPrior) Use flat prior on psd parameters (Gaussian)\n\
116 (--glitch-fit) Run with glitch fitting\n\
117 (--glitchNmax) Maximum number of glitch basis functions per IFO (20)\n\
118 \n\
119 ----------------------------------------------\n\
120 --- Output -----------------------------------\n\
121 ----------------------------------------------\n\
122 (--data-dump) Output waveforms to file\n\
123 (--adapt-verbose) Output parameter jump sizes and acceptance rate stats to file\n\
124 (--temp-verbose) Output temperature swapping stats to file\n\
125 (--prop-verbose) Output proposal stats to file\n\
126 (--prop-track) Output proposal parameters\n\
127 (--outfile file) Write output files <file>.<chain_number> \n\
128 (PTMCMC.output.<random_seed>.<mpi_thread>)\n\
129 ----------------------------------------------\n\
130 --- Checkpointing-----------------------------\n\
131 ----------------------------------------------\n\
132 (--resume) Allow jobs to resume partially completed run\n\
133 (--checkpoint-exit-code N) Exit with code N when checkpoint is complete.\n\
134 For use with condor's +SuccessCheckpointExitCode option\n\
135 \n";
136 INT4 mpi_rank, mpi_size;
137 INT4 ntemps_per_thread;
138 INT4 noAdapt;
139 INT4 i, ndim;
140 INT4 count_vectors = 0;
141 ProcessParamsTable *command_line = NULL, *ppt = NULL;
142 LALInferenceThreadState *thread = NULL;
143 LALInferenceModel *model;
144 REAL8 *ladder;
145
146 /* Send help if runState was not allocated */
147 if(runState == NULL || LALInferenceGetProcParamVal(runState->commandLine, "--help")) {
148 fprintf(stdout, "%s", help);
149 LALInferenceInitCBCThreads(runState,0);
150 return XLAL_FAILURE;
151 }
152
153 command_line = runState->commandLine;
154
155 MPI_Comm_rank(MPI_COMM_WORLD, &mpi_rank);
156 MPI_Comm_size(MPI_COMM_WORLD, &mpi_size);
157
158 /* Set up the appropriate functions for the MCMC algorithm */
159 runState->algorithm = &PTMCMCAlgorithm;
160
161 /* Choose the appropriate swapping method */
162 if (LALInferenceGetProcParamVal(command_line, "--varyFlow")) {
163 /* Metropolis-coupled MCMC Swap (assumes likelihood function differs between chains).*/
164 //runState->parallelSwap = &LALInferenceMCMCMCswap;
165 fprintf(stderr, "ERROR: MCMCMC sampling hasn't been brought up-to-date since restructuring.\n");
166 return XLAL_FAILURE;
167 } else {
168 /* Standard parallel tempering swap. */
169 runState->parallelSwap = &LALInferencePTswap;
170 }
171
172 /* Store flags to keep from checking the command line all the time */
173 LALInferenceVariables *algorithm_params = runState->algorithmParams;
174
175 /* Print more stuff */
176 INT4 verbose = 0;
177 if (LALInferenceGetProcParamVal(command_line, "--verbose"))
178 verbose = 1;
179
180 INT4 propVerbose = 0;
181 if (LALInferenceGetProcParamVal(command_line, "--prop-verbose"))
182 propVerbose = 1;
183
184 INT4 propTrack = 0;
185 if (LALInferenceGetProcParamVal(command_line, "--prop-track"))
186 propTrack = 1;
187
188 /* Keep track of time if benchmarking */
189 INT4 benchmark = 0;
190 if (LALInferenceGetProcParamVal(command_line, "--benchmark"))
191 benchmark = 1;
192
193 /* Number of steps between ensemble updates */
194 INT4 nsteps = 100000000;
195 ppt = LALInferenceGetProcParamVal(command_line, "--nsteps");
196 if (ppt)
197 nsteps = atoi(ppt->value);
198
199 /* Number of independent samples to collect. Default behavior (Neff=0)
200 is to not calculate Neff and just got *nsteps* iterations. */
201 INT4 neff = nsteps;
202 ppt = LALInferenceGetProcParamVal(command_line, "--Neff");
203 if (ppt) {
204 printf("WARNING: --Neff has been deprecated in favor of --neff\n");
205 } else {
206 ppt = LALInferenceGetProcParamVal(command_line, "--neff");
207 }
208 if (ppt)
209 neff = atoi(ppt->value);
210
211 /* Print sample every skip iterations */
212 INT4 skip = 2000;
213 ppt = LALInferenceGetProcParamVal(command_line, "--skip");
214 if (ppt)
215 skip = atoi(ppt->value);
216
217 /* Iterations between proposed temperature swaps */
218 INT4 Tskip = 100;
219 ppt = LALInferenceGetProcParamVal(command_line, "--temp-skip");
220 if (ppt)
221 Tskip = atoi(ppt->value);
222
223 /* Counter for triggering PT swaps */
224 INT4 nsteps_until_swap = Tskip;
225
226 /* Allow user to restrict size of temperature ladder */
227 INT4 ntemps = 0;
228 ppt = LALInferenceGetProcParamVal(command_line, "--ntemp");
229 if (ppt)
230 printf("WARNING: --ntemp has been deprecated in favor of --ntemps\n");
231 else
232 ppt = LALInferenceGetProcParamVal(command_line, "--ntemps");
233 if (ppt)
234 ntemps = atoi(ppt->value);
235
236 /* Adapt temperature spacing to maintain uniform swap acceptance rate */
237 INT4 adapt_temps = 0;
238 ppt = LALInferenceGetProcParamVal(command_line, "--adapt-temps");
239 if (ppt)
240 adapt_temps = 1;
241
242 /* Starting temperature of the ladder */
243 REAL8 tempMin = 1.0;
244 ppt = LALInferenceGetProcParamVal(command_line, "--temp-min");
245 if (ppt)
246 tempMin = strtod(ppt->value, (char **)NULL);
247
248 /* Starting temperature of the ladder */
249 REAL8 tempMax = 50.0;
250 ppt = LALInferenceGetProcParamVal(command_line, "--temp-max");
251 if (ppt)
252 tempMax = strtod(ppt->value, (char **)NULL);
253
254 /* Limit the size of the differential evolution buffer */
255 INT4 de_buffer_limit = 1000000;
256 ppt = LALInferenceGetProcParamVal(command_line, "--differential-buffer-limit");
257 if (ppt)
258 de_buffer_limit = atoi(ppt->value);
259
260 /* Network SNR of trigger */
261 REAL8 trigSNR = 0.0;
262 ppt = LALInferenceGetProcParamVal(command_line, "--trigger-snr");
263 if (ppt)
264 trigSNR = strtod(ppt->value, (char **)NULL);
265
266 /* Variable for tracking autocorrelation length */
267 INT4 acl = INT_MAX;
268
269 /* Print out temperature swapping info */
270 INT4 temp_verbose = 0;
271 if (LALInferenceGetProcParamVal(command_line, "--temp-verbose"))
272 temp_verbose = 1;
273
274 /* Print out adaptation info */
275 INT4 adapt_verbose = 0;
276 if (LALInferenceGetProcParamVal(command_line, "--adapt-verbose"))
277 adapt_verbose = 1;
278
279 /* Output SNRs */
280 INT4 outputSNRs = 0;
281 if (LALInferenceGetProcParamVal(command_line, "--output-snrs"))
282 outputSNRs = 1;
283
284 /* Save everything in the run state */
286 LALInferenceAddINT4Variable(algorithm_params, "prop_verbose", propVerbose, LALINFERENCE_PARAM_OUTPUT);
287 LALInferenceAddINT4Variable(algorithm_params, "prop_track", propTrack, LALINFERENCE_PARAM_OUTPUT);
288 LALInferenceAddINT4Variable(algorithm_params, "benchmark", benchmark, LALINFERENCE_PARAM_OUTPUT);
289 LALInferenceAddINT4Variable(algorithm_params, "nsteps", nsteps, LALINFERENCE_PARAM_OUTPUT);
290 LALInferenceAddINT4Variable(algorithm_params, "skip", skip, LALINFERENCE_PARAM_OUTPUT);
291 LALInferenceAddINT4Variable(algorithm_params, "neff", neff, LALINFERENCE_PARAM_OUTPUT);
292 LALInferenceAddINT4Variable(algorithm_params, "tskip", Tskip, LALINFERENCE_PARAM_OUTPUT);
293 LALInferenceAddINT4Variable(algorithm_params, "nsteps_until_swap", nsteps_until_swap, LALINFERENCE_PARAM_OUTPUT);
294 LALInferenceAddINT4Variable(algorithm_params, "mpirank", mpi_rank, LALINFERENCE_PARAM_OUTPUT);
295 LALInferenceAddINT4Variable(algorithm_params, "mpisize", mpi_size, LALINFERENCE_PARAM_OUTPUT);
296 LALInferenceAddINT4Variable(algorithm_params, "ntemps", ntemps, LALINFERENCE_PARAM_OUTPUT);
297 LALInferenceAddINT4Variable(algorithm_params, "adapt_temps", adapt_temps, LALINFERENCE_PARAM_OUTPUT);
298 LALInferenceAddREAL8Variable(algorithm_params, "temp_min", tempMin, LALINFERENCE_PARAM_OUTPUT);
299 LALInferenceAddREAL8Variable(algorithm_params, "temp_max", tempMax, LALINFERENCE_PARAM_OUTPUT);
300 LALInferenceAddINT4Variable(algorithm_params, "de_buffer_limit", de_buffer_limit, LALINFERENCE_PARAM_OUTPUT);
301 LALInferenceAddREAL8Variable(algorithm_params, "trigger_snr", trigSNR, LALINFERENCE_PARAM_OUTPUT);
302 LALInferenceAddINT4Variable(algorithm_params, "temp_verbose", temp_verbose, LALINFERENCE_PARAM_OUTPUT);
303 LALInferenceAddINT4Variable(algorithm_params, "adapt_verbose", adapt_verbose, LALINFERENCE_PARAM_OUTPUT);
304 LALInferenceAddINT4Variable(algorithm_params, "output_snrs", outputSNRs, LALINFERENCE_PARAM_OUTPUT);
305
306 /* Make a single model just to count dimensions */
307 model = LALInferenceInitCBCModel(runState);
309
310 /* Build the temperature ladder */
311 ladder = LALInferenceBuildHybridTempLadder(runState, ndim);
312 ntemps_per_thread = LALInferenceGetINT4Variable(runState->algorithmParams, "ntemps_per_thread");
313
314 /* Add some settings settings to runstate proposal args so their copied to threads */
316 LALInferenceAddINT4Variable(runState->proposalArgs, "output_snrs", outputSNRs, LALINFERENCE_PARAM_OUTPUT);
317
318 /* Parse proposal args for runSTate and initialize the walkers on this MPI thread */
319 LALInferenceInitCBCThreads(runState, ntemps_per_thread);
320
321 /* Establish the random state across MPI threads */
322 init_mpi_randomstate(runState);
323
324 /* Add common fixed parameters to output */
325
327
328 /* Give a new set of proposal args to each thread */
329 for (i=0; i<runState->nthreads; i++) {
330 thread = &runState->threads[i];
331
332 thread->id = mpi_rank*ntemps_per_thread + i;
333 thread->temperature = ladder[thread->id];
334
338
340
343 }
344
345 /* Grab adaptation settings from the last thread and add to algorithm params */
346 noAdapt = LALInferenceGetINT4Variable(thread->proposalArgs, "no_adapt");
347
348 INT4 adaptTau = 0;
349 if (LALInferenceCheckVariable(thread->proposalArgs, "adaptTau"))
350 adaptTau = LALInferenceGetINT4Variable(thread->proposalArgs, "adaptTau");
351
352 LALInferenceAddINT4Variable(algorithm_params, "adaptTau",
353 adaptTau, LALINFERENCE_PARAM_OUTPUT);
354
355 INT4 adaptLength = 0;
356 if (LALInferenceCheckVariable(thread->proposalArgs, "adaptLength"))
357 adaptLength = LALInferenceGetINT4Variable(thread->proposalArgs, "adaptLength");
358
359 LALInferenceAddINT4Variable(algorithm_params, "adaptLength",
360 adaptLength, LALINFERENCE_PARAM_OUTPUT);
361
362 LALInferenceAddINT4Variable(algorithm_params, "no_adapt",
364
365 /* Set counters to negative numbers, indicating adaptation is happening */
366 for (i=0; i<runState->nthreads; i++)
367 runState->threads[i].step = -adaptLength;
368
369 XLALFree(ladder);
370 return XLAL_SUCCESS;
371}
372
373
375 REAL8 temp, tempMin, tempMax, tempDelta;
376 REAL8 targetHotLike;
377 REAL8 trigSNR, networkSNRsqrd=0.0;
378 REAL8 *ladder=NULL;
379 INT4 flexible_tempmax=0;
380 INT4 adapt_temps;
381 INT4 ntemps, ntemps_per_thread;
382 INT4 mpi_rank, mpi_size;
383 INT4 t;
385
386 mpi_rank = LALInferenceGetINT4Variable(runState->algorithmParams, "mpirank");
387 mpi_size = LALInferenceGetINT4Variable(runState->algorithmParams, "mpisize");
388
389 adapt_temps = LALInferenceGetINT4Variable(runState->algorithmParams, "adapt_temps");
390 ntemps = LALInferenceGetINT4Variable(runState->algorithmParams, "ntemps");
391 tempMin = LALInferenceGetREAL8Variable(runState->algorithmParams, "temp_min");
392 tempMax = LALInferenceGetREAL8Variable(runState->algorithmParams, "temp_max");
393 trigSNR = LALInferenceGetREAL8Variable(runState->algorithmParams, "trigger_snr");
394
395 /* Targeted max 'experienced' log(likelihood) of hottest chain */
396 targetHotLike = ndim/2.;
397
398 /* Set maximum temperature (command line value take precidence) */
399 if (LALInferenceGetProcParamVal(runState->commandLine,"--temp-max")) {
400 if (mpi_rank==0)
401 fprintf(stdout,"Using tempMax specified by commandline: %f.\n", tempMax);
402 } else if (trigSNR > 0) {
403 networkSNRsqrd = trigSNR * trigSNR;
404 tempMax = networkSNRsqrd/(2*targetHotLike);
405
406 if (mpi_rank==0)
407 fprintf(stdout,"Trigger SNR of %f specified, setting max temperature to %f.\n", trigSNR, tempMax);
408
409 } else {
410 /* Determine network SNR if injection was done */
411 ifo = runState->data;
412 while (ifo != NULL) {
413 networkSNRsqrd += ifo->SNR * ifo->SNR;
414 ifo = ifo->next;
415 }
416
417 if (networkSNRsqrd > 0.0) {
418 tempMax = networkSNRsqrd/(2*targetHotLike);
419 if (mpi_rank==0)
420 fprintf(stdout,"Injecting SNR of %f, setting tempMax to %f.\n", sqrt(networkSNRsqrd), tempMax);
421
422 /* If all else fails, use the default */
423 } else {
424 if (mpi_rank==0) {
425 fprintf(stdout, "No --trigger-snr or --temp-max specified, and ");
426 fprintf(stdout, "not injecting a signal. Setting max temperature");
427 fprintf(stdout, "to default of %f.\n", tempMax);
428 }
429 }
430 }
431
432 LALInferenceSetVariable(runState->algorithmParams, "temp_max", &tempMax);
433
434 if (tempMin > tempMax) {
435 fprintf(stdout,"WARNING: temp_min > temp_max. Forcing temp_min=1.0.\n");
436 tempMin = 1.0;
437
438 LALInferenceSetVariable(runState->algorithmParams, "temp_min", &tempMin);
439 }
440
441 /* Construct temperature ladder */
442
443 /* If ntemps wasn't specified, figure out how big the ladder should be
444 to fill between the min and max with the calculated tempDelta */
445 if (ntemps == 0) {
446 flexible_tempmax = 1;
447 tempDelta = 1. + sqrt(2./(REAL8)ndim);
448
449 t = 1;
450 temp = tempMin;
451 while (temp < tempMax) {
452 t++;
453 temp = tempMin * pow(tempDelta, t);
454 }
455
456 ntemps = t;
457 }
458
459 ntemps_per_thread = ntemps / mpi_size;
460
461 /* Increase ntemps to distribute evenly across MPI threads */
462 if (ntemps % mpi_size != 0.0) {
463 /* Round up to have consistent number of walkers across MPI threads */
464 ntemps_per_thread = (INT4)ceil((REAL8)ntemps / (REAL8)mpi_size);
465 ntemps = mpi_size * ntemps_per_thread;
466 }
467
470 LALInferenceAddINT4Variable(runState->algorithmParams, "ntemps_per_thread",
471 ntemps_per_thread, LALINFERENCE_PARAM_OUTPUT);
472
473 if (flexible_tempmax)
474 tempDelta = 1. + sqrt(2./(REAL8)ndim);
475 else
476 tempDelta = pow(tempMax/tempMin, 1.0/(REAL8)(ntemps-1));
477
478 ladder = XLALCalloc(ntemps, sizeof(REAL8));
479 for (t=0; t<ntemps; ++t)
480 ladder[t] = tempMin * pow(tempDelta, t);
481
482 /* If adapting temperatures and user didn't specify a max, set the hottest temperature
483 * to infinity */
484 if (adapt_temps && !LALInferenceGetProcParamVal(runState->commandLine, "--temp-max"))
485 ladder[ntemps-1] = INFINITY;
486
487 return ladder;
488}
489
490
491REAL8 **parseMCMCoutput(char ***params, UINT4 *nInPar, UINT4 *nInSamps, char *infileName, UINT4 burnin) {
492 char str[999];
493 char header[999];
494 char *word;
495 UINT4 nread;
496 UINT4 i=0, j=0, nCols=0, nPar=0, par=0, col=0;
497 UINT4 cycle=0;
498 REAL8 val=0;
499
500 const char *non_params[] = {"cycle","logpost","logprior","logl","loglH1","loglL1","loglV1","",NULL};
501
502 FILE *infile = fopen(infileName,"r");
503
504 fgets(str, 999, infile);
505 strcpy(header, str);
506 word = strtok(header, " \t");
507 // Find column headers
508 while (strcmp(word,"cycle")) {
509 fgets(str, 999, infile);
510 strcpy(header, str);
511 word = strtok(header, " \t");
512 }
513
514 // Read in column names and check if they are parameters
515 strcpy(header, str);
516 word = strtok(header, " \t");
517 while (word != NULL) {
518 nCols++;
519 word = strtok(NULL, " \t");
520 }
521 // FIXME Remove a false column due to trailing whitespace
522 nCols--;
523
524 UINT4 is_param[nCols];
525
526 strcpy(header, str);
527 word = strtok(header, " \t");
528 for (i=0; i<nCols; i++) {
529 j=0;
530 is_param[i] = 1;
531 nPar++;
532 while (non_params[j] != NULL) {
533 if (!strcmp(non_params[j],word)) {
534 is_param[i] = 0;
535 nPar--;
536 break;
537 }
538 j++;
539 }
540 word = strtok(NULL, " \t");
541 }
542
543 char** in_params = XLALMalloc((nPar)*sizeof(char *));
544
545 word = strtok(str, " \t");
546 // Already assumed cycle is the first column, so skip it
547 par=0;
548 for (i=1; i<nCols; i++) {
549 char *param_name = strtok(NULL, " \t");
550 if (is_param[i]) {
551 in_params[par] = param_name;
552 par++;
553 }
554 }
555
556 printf("Reading the following params from %s:\n", infileName);
557 for (par=0; par<nPar; par++)
558 printf("\t%s\n",in_params[par]);
559
560 // Move past burnin
561 INT4 ch;
562 if (burnin > 0) {
563 while (cycle <= burnin) {
564 fscanf(infile, "%i", &cycle);
565 for (j=1;j<nCols;j++)
566 fscanf(infile, "%lg", &val);
567 }
568
569 // Make sure at end of line
570 ch = getc(infile);
571 while (ch != '\n') ch = getc(infile);
572 }
573
574 // Determine number of samples after burnin
575 unsigned long startPostBurnin = ftell(infile);
576 UINT4 nSamples=0;
577
578 while ( (ch = getc(infile)) != EOF) {
579 if (ch=='\n')
580 ++nSamples;
581 }
582 fseek(infile,startPostBurnin,SEEK_SET);
583 printf("%i samples read from %s.\n", nSamples, infileName);
584
585 // Read in samples
586 REAL8 **sampleArray;
587 sampleArray = (REAL8**) XLALMalloc(nSamples * sizeof(REAL8*));
588
589 for (i = 0; i < nSamples; i++) {
590 sampleArray[i] = XLALMalloc(nPar * sizeof(REAL8));
591
592 nread = fscanf(infile, "%i", &cycle);
593 if (nread != 1) {
594 fprintf(stderr, "Cannot read sample from file (in %s, line %d)\n",
595 __FILE__, __LINE__);
596 exit(1);
597 }
598
599 par=0;
600 for (col = 1; col < nCols; col++) {
601 nread = fscanf(infile, "%lg", &val);
602 if (nread != 1) {
603 fprintf(stderr, "Cannot read sample from file (in %s, line %d)\n",
604 __FILE__, __LINE__);
605 exit(1);
606 }
607
608 if (is_param[col]) {
609 sampleArray[i][par] = val;
610 par++;
611 }
612 }
613 }
614
615 *params = in_params;
616 *nInPar = nPar;
617 *nInSamps = nSamples;
618 return sampleArray;
619}
620
622 INT4 n;
623 INT4 fileargc=1;
624 char *pch;
625 ProcessParamsTable *procParams = NULL;
626 char *fileargv[99], str[999], buffer[99];
627 FILE *infile;
628
629 infile = fopen(infileName, "r");
630 if (infile==NULL) {
631 fprintf(stderr,"Cannot read %s/n", infileName);
632 exit (1);
633 }
634
635 n = sprintf(buffer, "lalinference_mcmcmpi_from_file_%s", infileName);
636 fileargv[0] = (char*)XLALCalloc(n+1, sizeof(char*));
637 fileargv[0] = buffer;
638
639 fgets(str, 999, infile);
640 fgets(str, 999, infile);
641 fclose(infile);
642
643 pch = strtok (str," ");
644 while (pch != NULL) {
645 if (strcmp(pch, "Command") != 0 && strcmp(pch, "line:") != 0) {
646 n = strlen(pch);
647 fileargv[fileargc] = (char*)XLALCalloc(n+1, sizeof(char*));
648 fileargv[fileargc] = pch;
649
650 fileargc++;
651 if(fileargc>=99) {
652 fprintf(stderr,"Too many arguments in file %s\n",infileName);
653 exit (1);
654 }
655 }
656 pch = strtok (NULL, " ");
657 }
658
659 /* In order to get rid of the '\n' than fgets returns when reading the command line. */
660 fileargv[fileargc-1][strlen(fileargv[fileargc-1])-1] = '\0';
661 procParams = LALInferenceParseCommandLine(fileargc, fileargv);
662
663 return procParams;
664}
665
666
667int main(int argc, char *argv[]){
668 INT4 mpirank;
669 ProcessParamsTable *procParams = NULL, *ppt = NULL;
670 LALInferenceRunState *runState = NULL;
672
673 MPI_Init(&argc, &argv);
674 MPI_Comm_rank(MPI_COMM_WORLD, &mpirank);
675
676 if (mpirank == 0) fprintf(stdout," ========== LALInference_MCMC ==========\n");
677
678 /* Read command line and parse */
679 procParams = LALInferenceParseCommandLine(argc, argv);
680
681 ppt = LALInferenceGetProcParamVal(procParams, "--continue-run");
682 if (ppt)
683 procParams = LALInferenceContinueMCMC(ppt->value);
684
685 /* initialise runstate based on command line */
686 /* This includes reading in the data */
687 /* And performing any injections specified */
688 /* And allocating memory */
689 runState = LALInferenceInitRunState(procParams);
690
691 if (runState == NULL) {
692 if (!LALInferenceGetProcParamVal(procParams, "--help")) {
693 fprintf(stderr, "run_state not allocated (%s, line %d).\n",
694 __FILE__, __LINE__);
695 }
696 } else {
697 data = runState->data;
698 }
699
700 /* Perform injections if data successful read or created */
701 if (runState){
703 }
704
705 /* Simulate calibration errors.
706 * NOTE: this must be called after both ReadData and (if relevant)
707 * injectInspiralTD/FD are called! */
709
710 /* Handle PTMCMC setup */
711 init_ptmcmc(runState);
712
713 /* Choose the prior */
714 LALInferenceInitCBCPrior(runState);
715
716 /* Choose the likelihood */
718
719 /* Draw starting positions */
720 LALInferenceDrawThreads(runState);
721
722 /* If just asking for --help, stop here */
723 if (LALInferenceGetProcParamVal(procParams, "--help")) {
724 return XLAL_SUCCESS;
725 }
726
727 if (runState == NULL)
728 return XLAL_FAILURE;
729
730 /* Call MCMC algorithm */
731 if (mpirank == 0) printf("sampling...\n");
732 runState->algorithm(runState);
733
734 if (mpirank == 0) printf(" ========== main(): finished. ==========\n");
735 MPI_Finalize();
736
737 return XLAL_SUCCESS;
738}
ProcessParamsTable * LALInferenceParseCommandLine(int argc, char *argv[])
void LALInferenceApplyCalibrationErrors(LALInferenceIFOData *IFOdata, ProcessParamsTable *commandLine)
LALInferenceModel * LALInferenceInitCBCModel(LALInferenceRunState *state)
Initialise state variables needed for LALInferenceNest or LALInferenceMCMC to run on a CBC signal.
LALInferenceRunState * LALInferenceInitRunState(ProcessParamsTable *command_line)
void LALInferenceInitCBCThreads(LALInferenceRunState *run_state, INT4 nthreads)
void LALInferenceDrawThreads(LALInferenceRunState *run_state)
void initializeMCMC(LALInferenceRunState *runState)
int main(int argc, char *argv[])
ProcessParamsTable * LALInferenceContinueMCMC(char *infileName)
REAL8 ** parseMCMCoutput(char ***params, UINT4 *nInPar, UINT4 *nInSamps, char *infilename, UINT4 burnin)
void init_mpi_randomstate(LALInferenceRunState *run_state)
REAL8 * LALInferenceBuildHybridTempLadder(LALInferenceRunState *runState, INT4 ndim)
INT4 init_ptmcmc(LALInferenceRunState *runState)
void LALInferencePTswap(LALInferenceRunState *runState, FILE *swapfile)
void PTMCMCAlgorithm(struct tagLALInferenceRunState *runState)
Implements the parallel tempered MCMC algorithm.
void LALInferenceAddPTMCMCMetaInfo(LALInferenceRunState *runState)
Markov-Chain Monte Carlo sampler written for LALInference.
void LALInferenceInjectInspiralSignal(LALInferenceIFOData *IFOdata, ProcessParamsTable *commandLine)
ProcessParamsTable * ppt
int j
#define fscanf
#define fprintf
sigmaKerr data[0]
double REAL8
uint32_t UINT4
int32_t INT4
INT4 LALInferenceGetVariableDimensionNonFixedChooseVectors(LALInferenceVariables *vars, INT4 count_vectors)
Get number of dimensions in vars which are not fixed to a certain value, with a flag for skipping cou...
Definition: LALInference.c:260
REAL8 LALInferenceGetREAL8Variable(LALInferenceVariables *vars, const char *name)
void LALInferenceAddREAL8Variable(LALInferenceVariables *vars, const char *name, REAL8 value, LALInferenceParamVaryType vary)
INT4 LALInferenceGetINT4Variable(LALInferenceVariables *vars, const char *name)
ProcessParamsTable * LALInferenceGetProcParamVal(ProcessParamsTable *procparams, const char *name)
Returns the element of the process params table with "name".
void LALInferenceAddINT4Variable(LALInferenceVariables *vars, const char *name, INT4 value, LALInferenceParamVaryType vary)
int LALInferenceCheckVariable(LALInferenceVariables *vars, const char *name)
Checks for name being present in vars returns 1(==true) or 0.
Definition: LALInference.c:525
void LALInferenceSetVariable(LALInferenceVariables *vars, const char *name, const void *value)
Set a variable named name in vars with a value.
Definition: LALInference.c:352
@ LALINFERENCE_PARAM_OUTPUT
A parameter that never changes, functions should respect this.
Definition: LALInference.h:131
void LALInferenceInitLikelihood(LALInferenceRunState *runState)
Initialisation function which reads runState->commaneLine and sets up the likelihood function accordi...
void LALInferenceInitCBCPrior(LALInferenceRunState *runState)
Initialize the prior based on command line arguments.
LALInferenceProposalCycle * LALInferenceSetupDefaultInspiralProposalCycle(LALInferenceVariables *propArgs)
A reasonable default proposal.
LALInferenceVariables * LALInferenceParseProposalArgs(LALInferenceRunState *runState)
Go through all logic for deciding proposals to use.
void LALInferenceRandomizeProposalCycle(LALInferenceProposalCycle *cycle, gsl_rng *rng)
Randomizes the order of the proposals in the proposal cycle.
REAL8 LALInferenceCyclicProposal(LALInferenceThreadState *thread, LALInferenceVariables *currentParams, LALInferenceVariables *proposedParams)
Proposes a jump from the next proposal in the proposal cycle.
void * XLALMalloc(size_t n)
void * XLALCalloc(size_t m, size_t n)
void XLALFree(void *p)
XLAL_SUCCESS
XLAL_FAILURE
header
help
Structure to contain IFO data.
Definition: LALInference.h:625
REAL8 SNR
The epoch of this observation (the time of the first sample)
Definition: LALInference.h:653
struct tagLALInferenceIFOData * next
ROQ data.
Definition: LALInference.h:659
Structure to constain a model and its parameters.
Definition: LALInference.h:436
LALInferenceVariables * params
Definition: LALInference.h:437
Structure containing inference run state This includes pointers to the function types required to run...
Definition: LALInference.h:592
ProcessParamsTable * commandLine
Definition: LALInference.h:593
LALInferenceVariables * proposalArgs
The data from the interferometers.
Definition: LALInference.h:602
LALInferenceVariables * algorithmParams
Any special arguments for the prior function.
Definition: LALInference.h:604
INT4 nthreads
Array of live points for Nested Sampling.
Definition: LALInference.h:606
struct tagLALInferenceIFOData * data
Log sample, i.e.
Definition: LALInference.h:601
LALInferenceThreadState * threads
Definition: LALInference.h:612
LALInferenceAlgorithm algorithm
A function that returns a new set of variables for the model.
Definition: LALInference.h:595
LALInferenceSwapRoutine parallelSwap
Number of threads stored in threads.
Definition: LALInference.h:607
Structure containing chain-specific variables.
Definition: LALInference.h:541
LALInferenceProposalFunction proposal
Step counter for this thread.
Definition: LALInference.h:546
LALInferenceProposalCycle * cycle
The proposal cycle.
Definition: LALInference.h:547
LALInferenceVariables * proposalArgs
Definition: LALInference.h:551
REAL8 temperature
Array containing multiple proposal densities.
Definition: LALInference.h:550
The LALInferenceVariables structure to contain a set of parameters Implemented as a linked list of LA...
Definition: LALInference.h:170
CHAR value[LIGOMETA_VALUE_MAX]