UQTk: Uncertainty Quantification Toolkit 3.1.5
mcmc.h
Go to the documentation of this file.
1/* =====================================================================================
2
3 The UQ Toolkit (UQTk) version 3.1.5
4 Copyright (2024) NTESS
5 https://www.sandia.gov/UQToolkit/
6 https://github.com/sandialabs/UQTk
7
8 Copyright 2024 National Technology & Engineering Solutions of Sandia, LLC (NTESS).
9 Under the terms of Contract DE-NA0003525 with NTESS, the U.S. Government
10 retains certain rights in this software.
11
12 This file is part of The UQ Toolkit (UQTk)
13
14 UQTk is open source software: you can redistribute it and/or modify
15 it under the terms of BSD 3-Clause License
16
17 UQTk is distributed in the hope that it will be useful,
18 but WITHOUT ANY WARRANTY; without even the implied warranty of
19 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 BSD 3 Clause License for more details.
21
22 You should have received a copy of the BSD 3 Clause License
23 along with UQTk. If not, see https://choosealicense.com/licenses/bsd-3-clause/.
24
25 Questions? Contact the UQTk Developers at https://github.com/sandialabs/UQTk/discussions
26 Sandia National Laboratories, Livermore, CA, USA
27===================================================================================== */
31
32#ifndef UQTKMCMC_H_SEEN
33#define UQTKMCMC_H_SEEN
34
35#include "dsfmt_add.h"
36#include "arrayio.h"
37#include "arraytools.h"
38
39#include <iostream>
40#include <string.h>
41#include <stdio.h>
42#include <sstream>
43
44using namespace std; // needed for python string conversion
45
47public:
48 virtual double eval(Array1D<double>&){
49 return 3.14;
50 };
51 virtual ~LogPosteriorBase(){};
52};
53
54class base{
55public:
56 virtual double fun(double* x, int n){return 0.0;}
57};
58
59class main{
60public:
62
64 b_ = &b;
65 }
66};
67//*****************************************
68
72class MCMC{
73public:
74 // Struct for the chain state
75 struct chainstate{
76 int step;
78 double alfa;
79 double post;
80 };
81
82 // Constructors:
83
85 MCMC(double (*logposterior)(Array1D<double>&, void *), void *postinfo);
89 MCMC();
90
91 // Set or initialization functions:
92
94 void setWriteFlag(int I);
96 void setFcnAccept(void (*fcnAccept)(void *));
97 void setFcnReject(void (*fcnReject)(void *));
99 void setChainDim(int chdim);
102 void initChainPropCov(Array2D<double>& propcov);
107 void setOutputInfo(string outtype, string file,int freq_file, int freq_screen);
109 void namesPrepended();
111 void setSeed(int seed);
113 void setLower(double lower, int i);
115 void setUpper(double upper, int i);
117 void setDefaultDomain();
119 void setPostInfo(void *postinfo);
120
121 // Get functions:
122
124 void getChainPropCov(Array2D<double>& propcov);
126 string getFilename();
128 int getWriteFlag();
130 void getSamples(int burnin, int every,Array2D<double>& samples);
132 void getSamples(Array2D<double>& samples);
134 void getFcnAccept(void (*fcnAccept)(void *));
135 void getFcnReject(void (*fcnReject)(void *));
137 string getOutputType();
139 int getFileFreq();
141 int getScreenFreq();
143 bool getNamesPrepended();
145 int getSeed();
147 double getLower(int i);
149 double getUpper(int i);
151 bool getDimInit();
153 void getPostInfo(void *post);
155 bool getPropCovInit();
157 bool getOutputInit();
159 int getLastWrite();
161 bool getFcnAcceptInit();
162 bool getFcnRejectInit();
164 virtual int getNSubSteps(){return 1;};
166 int getLowerFlag(int i);
167 int getUpperFlag(int i);
169 void getAcceptRatio(double * accrat);
171 double getAcceptRatio();
173 int GetChainDim() const;
174
175 // Chain Functions:
176
178 void resetChainState();
180 void resetChainFilename(string filename);
182 void parseBinChain(string filename, Array1D<chainstate>& readchain);
184 void writeFullChainTxt(string filename, Array1D<chainstate> fullchain);
186 void getFullChain(Array1D<chainstate>& readchain);
188 void appendMAP();
190 double getMode(Array1D<double>& MAPparams);
192 int getFullChainSize();
193
194 // Functions to make sure the code respects the interface for chainstates:
195
197 void setCurrentStateStep(int i);
201 double getCurrentStatePost();
205 void setCurrentStatePost(double newPost);
207 void setCurrentStateAlfa(double newAlfa);
209 double getModeStatePost();
212
213 // Run functions:
214
216 virtual void runOptim(Array1D<double>& start);
218 virtual void runChain(int ncalls, Array1D<double>& chstart) = 0;
220 virtual void runChain(int ncalls) = 0;
222 void runAcceptFcn();
224 void runRejectFcn();
225
226
227
229 bool newModeFound();
233 bool inDomain(Array1D<double>& m);
235 void writeChainTxt(string filename);
237 void writeChainBin(string filename);
238
240 void setNewMode(bool value);
241
242
243
244protected:
246 void setAcceptRatio(double d);
248 void addCurrentState();
250 void updateMode();
252 void setLastWrite(int i);
253
254 dsfmt_t RandomState;
255
256
257private:
258 int WRITE_FLAG; // Write Flag
259 int FLAG; // Flag
260 LogPosteriorBase* L_; // Pointer to the LogPosterior base passed in through contstructor
267 int chainDim_; // Chain dimensions
268 double (*logPosterior_)(Array1D<double>&, void *) = NULL; // Pointer to log-posterior function
269 void (*fcnAccept_)(void *) = NULL; // Pointer to accept function
270 void (*fcnReject_)(void *) = NULL; // Pointer to reject function
271 void *postInfo_ = NULL; // Void pointer to the posterior info (data)
272 Array2D<double> chcov; // Chain proposal distributions (before the adaptivity starts)
273 int seed_; // Random seed for mcmc
274
275 virtual double probOldNew(Array1D<double>& a, Array1D<double>& b){return 0.0;}; // Evaluate old|new probabilities and new|old probabilities
276 //double evallogMVN_diag(Array1D<double>& x,Array1D<double>& mu,Array1D<double>& sig2); // Evaluate MVN
277
278 chainstate currState_; // The current chain state
279 chainstate modeState_; // The current MAP state
280 Array1D<chainstate> fullChain_; // Array of chain states
281
282 //void updateMode(); // Function to update the chain mode
283
284 int lastwrite_; // Indicates up to which state
285 bool namesPrepend = false;
286
287 bool newMode_ = false; // Flag to indicate whether a new mode is found during the last call of runChain, initalized as false
288
289 double accRatio_ = -1.0; // Acceptance ratio of the chain, initialized as -1.0
290
291 // Flags to indicate whether the corresponding parameters are initialized or not
292 bool chaindimInit_ = false;
293 bool propcovInit_ = false;
294 bool methodInit_ = false;
295 bool outputInit_ = false;
296
297 bool fcnAcceptFlag_ = false; // Flag that indicates whether the accept function is given or not
298 bool fcnRejectFlag_ = false; // Flag that indicates whether the reject function is given or not
299
304
309
310};
311
312#endif /* UQTKMCMC_H_SEEN */
Header file for array read/write utilities.
Header file for array tools.
Stores data of any type T in a 1D array.
Definition Array1D.h:61
Stores data of any type T in a 2D array.
Definition Array2D.h:60
Definition mcmc.h:46
virtual ~LogPosteriorBase()
Definition mcmc.h:51
virtual double eval(Array1D< double > &)
Definition mcmc.h:48
Markov Chain Monte Carlo base class. Implemented the basic and most general MCMC algorithms.
Definition mcmc.h:72
void setCurrentStateStep(int i)
Function to set the step of the current state.
Definition mcmc.cpp:425
Array2D< double > chcov
Definition mcmc.h:272
int getUpperFlag(int i)
Definition mcmc.cpp:571
double getLower(int i)
Get the lower bounds based on an index i.
Definition mcmc.cpp:271
void setFcnAccept(void(*fcnAccept)(void *))
Set the accept and reject functions.
Definition mcmc.cpp:111
void writeFullChainTxt(string filename, Array1D< chainstate > fullchain)
Write an array of chain-states to a file.
Definition mcmc.cpp:368
LogPosteriorBase * L_
Definition mcmc.h:260
bool fcnAcceptFlag_
Definition mcmc.h:297
chainstate currState_
Definition mcmc.h:278
bool inDomain(Array1D< double > &m)
Check if a point is in the domain.
Definition mcmc.cpp:526
Array1D< int > lower_flag_
Lower bound existence flags.
Definition mcmc.h:306
void setLower(double lower, int i)
Set lower bound at the index of i.
Definition mcmc.cpp:185
int GetChainDim() const
Get the MCMC chain dimensionality.
Definition mcmc.cpp:513
Array1D< int > upper_flag_
Upper bound existence flags.
Definition mcmc.h:308
bool fcnRejectFlag_
Definition mcmc.h:298
int chainDim_
Definition mcmc.h:267
dsfmt_t RandomState
Definition mcmc.h:254
void setFcnReject(void(*fcnReject)(void *))
Definition mcmc.cpp:119
string getFilename()
Get the name of the chain file.
Definition mcmc.cpp:217
MCMC()
Dummy Constructor, used for TMCMC.
Definition mcmc.cpp:88
void getFullChain(Array1D< chainstate > &readchain)
Get full chain as an array of chain-states.
Definition mcmc.cpp:402
void setChainDim(int chdim)
Set the dimensions of the chain given an integer.
Definition mcmc.cpp:127
bool getFcnAcceptInit()
Get if the accept and reject functions are initialized.
Definition mcmc.cpp:559
void initChainPropCovDiag(Array1D< double > &sig)
Initialize proposal covariance matrix given its 1d-array diagonal For aMCMC, this matrix is used only...
Definition mcmc.cpp:145
virtual void runChain(int ncalls)=0
Start an MCMC chain with trivial initial condition.
struct MCMC::outputInfo outputinfo_
void writeChainTxt(string filename)
Write the full chain as a text.
Definition mcmc.cpp:575
void runAcceptFcn()
Function to run the accept function.
Definition mcmc.cpp:315
void setCurrentStateState(Array1D< double > &newState)
Function to set the current state's state.
Definition mcmc.cpp:435
void getCurrentStateState(Array1D< double > &state)
Function to get the state of the current state.
Definition mcmc.cpp:430
double getUpper(int i)
Get the upper bounds based on an index i.
Definition mcmc.cpp:275
virtual void runChain(int ncalls, Array1D< double > &chstart)=0
The actual function that generates MCMC.
bool getDimInit()
Get if the Chain Dimensions are initialized.
Definition mcmc.cpp:279
bool propcovInit_
Definition mcmc.h:293
int seed_
Definition mcmc.h:273
int FLAG
Definition mcmc.h:259
int getFullChainSize()
Get the full chain size.
Definition mcmc.cpp:417
void(* fcnAccept_)(void *)
Definition mcmc.h:269
double getModeStatePost()
Function to get the mode state's post.
Definition mcmc.cpp:449
bool getOutputInit()
Get if the output info has been initialized.
Definition mcmc.cpp:292
void addCurrentState()
Function to add the current chain state to the full chain.
Definition mcmc.cpp:421
void initChainPropCov(Array2D< double > &propcov)
Initialize proposal covariance matrix given as a 2d-array For aMCMC, this matrix is used only before ...
Definition mcmc.cpp:135
void getChainPropCov(Array2D< double > &propcov)
Returns proposal covariance matrix.
Definition mcmc.cpp:211
void getFcnAccept(void(*fcnAccept)(void *))
Get the accept and reject functions given a pointer.
Definition mcmc.cpp:241
void setSeed(int seed)
Set random generation seed.
Definition mcmc.cpp:178
double evalLogPosterior(Array1D< double > &m)
Function to evaluate the log-posterior.
Definition mcmc.cpp:517
void setAcceptRatio(double d)
Set the acceptance ratio.
Definition mcmc.cpp:305
string getOutputType()
Get the output file type as a string.
Definition mcmc.cpp:251
int getLowerFlag(int i)
Get function for the lower and upper Flag at index i.
Definition mcmc.cpp:567
bool newModeFound()
Check to see if a new mode was found during last call to runChain.
Definition mcmc.cpp:499
void * postInfo_
Definition mcmc.h:271
Array1D< double > Lower_
Lower bounds.
Definition mcmc.h:301
void getModeStateState(Array1D< double > &state)
Function to get the mode state's state.
Definition mcmc.cpp:458
void getPostInfo(void *post)
Get post info pointer.
Definition mcmc.cpp:283
virtual int getNSubSteps()
Get function for number of sub steps.
Definition mcmc.h:164
void setCurrentStatePost(double newPost)
Function to set the current state's post.
Definition mcmc.cpp:444
virtual double probOldNew(Array1D< double > &a, Array1D< double > &b)
Definition mcmc.h:275
void setPostInfo(void *postinfo)
Set the Posterior Info pointer.
Definition mcmc.cpp:310
Array1D< double > Upper_
Upper bounds.
Definition mcmc.h:303
bool newMode_
Definition mcmc.h:287
void writeChainBin(string filename)
Write the full chain as a binary file.
Definition mcmc.cpp:609
void setNewMode(bool value)
Function to set a new mode value.
Definition mcmc.cpp:554
int WRITE_FLAG
Definition mcmc.h:258
int getFileFreq()
Get the frequency of output to file.
Definition mcmc.cpp:255
void namesPrepended()
Set the indicator to confirm that the names of parameters are prepended in the output file.
Definition mcmc.cpp:171
void setOutputInfo(string outtype, string file, int freq_file, int freq_screen)
Set output specification struct, type('txt' or 'bin'), filename, frequency of outputs to the file and...
Definition mcmc.cpp:159
bool methodInit_
Definition mcmc.h:294
void setCurrentStateAlfa(double newAlfa)
Function to set the current state's alfa.
Definition mcmc.cpp:453
int getWriteFlag()
Get the value of the write flag as an integer.
Definition mcmc.cpp:221
bool outputInit_
Definition mcmc.h:295
bool chaindimInit_
Definition mcmc.h:292
double getMode(Array1D< double > &MAPparams)
Get MAP parameters.
Definition mcmc.cpp:412
void appendMAP()
Append MAP state to the end.
Definition mcmc.cpp:407
virtual void runOptim(Array1D< double > &start)
The optimization routine.
Definition mcmc.cpp:463
double getAcceptRatio()
Get the chain's acceptance ratio as a double.
Definition mcmc.cpp:509
double(* logPosterior_)(Array1D< double > &, void *)
Definition mcmc.h:268
void runRejectFcn()
Function to run the reject function.
Definition mcmc.cpp:320
int getLastWrite()
Get last write.
Definition mcmc.cpp:296
void parseBinChain(string filename, Array1D< chainstate > &readchain)
An auxiliary function to parse the binary file and produce an array of chain-states.
Definition mcmc.cpp:339
void setLastWrite(int i)
Set last write.
Definition mcmc.cpp:300
void getSamples(int burnin, int every, Array2D< double > &samples)
Get samples of the chain with burnin and thining.
Definition mcmc.cpp:225
void getFcnReject(void(*fcnReject)(void *))
Definition mcmc.cpp:246
double accRatio_
Definition mcmc.h:289
int getScreenFreq()
Get the frequency of output to the screen.
Definition mcmc.cpp:259
bool getFcnRejectInit()
Definition mcmc.cpp:563
bool getPropCovInit()
Get if the Prop Cov has been initialized.
Definition mcmc.cpp:288
void(* fcnReject_)(void *)
Definition mcmc.h:270
void resetChainState()
Reset the chain state.
Definition mcmc.cpp:325
double getCurrentStatePost()
Function to get the post of the current state.
Definition mcmc.cpp:440
void setUpper(double upper, int i)
Set upper bound at the index of i.
Definition mcmc.cpp:193
void setDefaultDomain()
Set default unbounded domain.
Definition mcmc.cpp:201
int getSeed()
Get the seed used for random generation.
Definition mcmc.cpp:267
void updateMode()
Function to update the Chain mode.
Definition mcmc.cpp:544
bool namesPrepend
Definition mcmc.h:285
int lastwrite_
Definition mcmc.h:284
void setWriteFlag(int I)
Set the write flag function given an integer.
Definition mcmc.cpp:106
Array1D< chainstate > fullChain_
Definition mcmc.h:280
bool getNamesPrepended()
Get if the names are prepended.
Definition mcmc.cpp:263
void resetChainFilename(string filename)
Reset to a new chain file.
Definition mcmc.cpp:331
chainstate modeState_
Definition mcmc.h:279
Definition mcmc.h:54
virtual double fun(double *x, int n)
Definition mcmc.h:56
Definition mcmc.h:59
base * b_
Definition mcmc.h:61
main(base &b)
Definition mcmc.h:63
Definition mcmc.h:75
double alfa
Definition mcmc.h:78
Array1D< double > state
Definition mcmc.h:77
double post
Definition mcmc.h:79
int step
Definition mcmc.h:76
Definition mcmc.h:261
string filename
Definition mcmc.h:263
int freq_file
Definition mcmc.h:264
string outtype
Definition mcmc.h:262
int freq_screen
Definition mcmc.h:265