|
SedSat3 1.1.6
Sediment Source Apportionment Tool - Advanced statistical methods for environmental pollution research
|
Markov Chain Monte Carlo sampler for Bayesian parameter estimation. More...
#include <MCMC/MCMC.h>


Public Member Functions | |
| CMCMC (void) | |
| Default constructor. | |
| CMCMC (int nn, int nn_chains) | |
| Constructor with chain configuration. | |
| CMCMC (T *system) | |
| Constructor with model pointer. | |
| bool | SetProperty (const string &varname, const string &value) |
| Set MCMC properties from string key-value pairs. | |
| ~CMCMC (void) | |
| Destructor. | |
| void | initialize (CMBTimeSeriesSet *results, bool random=false) |
| Initialize MCMC chains with starting parameter values. | |
| void | initialize (vector< double > par) |
| Initialize all chains with specific parameter values. | |
| bool | step (int k, int chain_counter) |
| Perform single MCMC step for one chain. | |
| bool | step (int k, int nsamps, const string &filename, CMBTimeSeriesSet *results=nullptr, ProgressReporter *_rtw=0) |
| Perform multiple MCMC steps with progress tracking and output. | |
| vector< double > | perturb (int k, int chain_counter) |
| Generate proposed parameter values by perturbing current state. | |
| void | UpdateProposalCovariance (int upto) |
| Re-estimates the proposal covariance from samples burn-in..upto. | |
| void | SetRandomSeed (std::uint64_t seed) |
| Sets the master seed for the chains' random streams. | |
| std::uint64_t | RandomSeed () const |
| The master seed of the current run. | |
| void | writeoutput (string filename) |
| Write MCMC results to output file. | |
| double | posterior (vector< double > par, int chain_counter) |
| Calculate log-posterior probability for given parameters. | |
| void | model (T *Model1, vector< double > par) |
| Evaluate model with given parameters. | |
| int | getparamno (int i, int ts) const |
| Get parameter index for a specific variable and time series. | |
| int | get_act_paramno (int i) |
| Get active parameter number (legacy, may be unused). | |
| int | get_time_series (int i) |
| Get time series index for parameter (legacy, may be unused). | |
| Parameter * | parameter (int i) |
| Get pointer to specific parameter. | |
| Observation * | observation (int i) |
| Get pointer to specific observation. | |
| CVector | sensitivity (double d, vector< double > par) |
| Calculate sensitivity of model output to parameters. | |
| CVector | sensitivity_ln (double d, vector< double > par) |
| Calculate log-space sensitivity (for lognormal parameters). | |
| CMatrix | sensitivity_mat_lumped (double d, vector< double > par) |
| Calculate lumped sensitivity matrix. | |
| TimeSeriesSet< double > | prior_distribution (int n_bins) |
| Generate histogram of prior distributions. | |
| int | readfromfile (const string &filename) |
| Read MCMC state from file to continue previous run. | |
| TimeSeriesSet< double > | model (vector< double > par) |
| Evaluate model for given parameters and return predictions. | |
| void | ProduceRealizations (TimeSeriesSet< double > &MCMCout) |
| Generate posterior predictive realizations. | |
| void | get_outputpercentiles (TimeSeriesSet< double > &MCMCout) |
| Calculate percentiles of model outputs from MCMC samples. | |
| void | SetRunTimeWindow (ProgressReporter *_rtw) |
| Set progress window for GUI updates. | |
| void | Perform () |
| Main entry point to run complete MCMC analysis. | |
Public Attributes | |
| T * | Model |
| Pointer to the model object being calibrated. | |
| T | Model_out |
| Output model state after MCMC completion. | |
| _MCMC_settings | MCMC_Settings |
| MCMC algorithm configuration settings. | |
| vector< vector< double > > | Params |
| Parameter values for all samples and chains. | |
| vector< double > | pertcoeff |
| Perturbation coefficients for each parameter. | |
| vector< double > | logp |
| Log-posterior values for current state of each chain. | |
| vector< double > | logp1 |
| Log-posterior values for proposed states. | |
| vector< double > | u |
| Uniform random values for Metropolis-Hastings accept/reject. | |
| vector< vector< double > > | proposal_chol_ |
| Cholesky factor of the proposal covariance; empty until the first update. | |
| unsigned int | last_covariance_update_ = 0 |
| vector< CVector > | temp_predicted |
| Temporary storage for predicted model outputs. | |
| CMBTimeSeriesSet | predicted |
| Model predictions as time series set. | |
| vector< T > | CopiedModels |
| Copies of model object for parallel chain evaluation. | |
| vector< int > | params |
| Parameter indices for model evaluation. | |
| TimeSeriesSet< double > | MData |
| Measured data (observations) for likelihood calculation. | |
| _MCMC_file_names | FileInformation |
| File paths for MCMC input/output. | |
| vector< bool > | apply_to_all |
| Flags indicating if parameter applies to all entities. | |
| vector< Parameter > * | parameters = nullptr |
| Pointer to vector of Parameter objects. | |
| vector< Observation > * | observations = nullptr |
| Pointer to vector of Observation objects. | |
| ProgressReporter * | rtw = nullptr |
| Pointer to progress window for GUI updates. | |
| vector< vector< TimeSeriesSet< double > > > | BTCout_obs |
| Posterior predictive samples for observations. | |
| vector< vector< TimeSeriesSet< double > > > | BTCout_obs_noise |
| Posterior predictive samples with simulated measurement noise. | |
| vector< vector< TimeSeriesSet< double > > > | BTCout_obs_prcntle |
| Percentiles of posterior predictive distribution. | |
| vector< vector< TimeSeriesSet< double > > > | BTCout_obs_prcntle_noise |
| Percentiles of posterior predictive distribution with noise. | |
| vector< CMatrix > | global_sens_lumped |
| Global sensitivity analysis results (lumped). | |
| TimeSeriesSet< double > | paramsList |
| List of all parameter samples from MCMC. | |
| TimeSeriesSet< double > | realized_paramsList |
| Parameter samples for posterior predictive realizations. | |
| vector< double > | calc_output_percentiles |
| Percentiles to calculate for output distributions. | |
| double | accepted_count = 0 |
| Count of accepted proposals. | |
| std::uint64_t | random_seed_ = 0 |
| Master seed for the chains' random streams; see SetRandomSeed(). | |
| bool | random_seed_set_ = false |
| vector< RandomStream > | chain_streams_ |
| One random stream per chain, so no generator is shared between threads. | |
| double | total_count = 0 |
| Count of total proposals (accepted + rejected). | |
| string | last_error |
| Last error message from MCMC execution. | |
Private Member Functions | |
| int_value_pair | Min (const vector< double > &vec, int current_counter, int n_chains) |
| Find minimum value and its chain index. | |
| int_value_pair | Max (const vector< double > &vec, int current_counter, int n_chains) |
| Find maximum value and its chain index. | |
Markov Chain Monte Carlo sampler for Bayesian parameter estimation.
The CMCMC class implements a sophisticated Metropolis-Hastings MCMC algorithm with advanced features for Bayesian inference in sediment source fingerprinting.
MCMC generates samples from the posterior distribution p(θ|data) ∝ p(data|θ) × p(θ) using a random walk with accept/reject steps:
MCMC provides fully Bayesian estimates of source contributions with uncertainty:
Log-posterior calculation:
Where:
| T | Model class type (e.g., SourceSinkData) that provides:
|
Example usage:
| CMCMC< T >::CMCMC | ( | void | ) |
| CMCMC< T >::CMCMC | ( | int | nn, |
| int | nn_chains ) |
Constructor with chain configuration.
| nn | Number of parameters |
| nn_chains | Number of parallel chains |
Initializes MCMC with specified dimensions and chain count.
| CMCMC< T >::CMCMC | ( | T * | system | ) |
Constructor with model pointer.
| system | Pointer to model object to be calibrated |
Preferred constructor that links MCMC to a specific model instance.
Definition at line 719 of file MCMC.hpp.
References FileInformation, MCMC_Settings, Model, observations, parameters, params, and pertcoeff.
| int CMCMC< T >::get_act_paramno | ( | int | i | ) |
Get active parameter number (legacy, may be unused).
| i | Parameter index |
| void CMCMC< T >::get_outputpercentiles | ( | TimeSeriesSet< double > & | MCMCout | ) |
Calculate percentiles of model outputs from MCMC samples.
| MCMCout | TimeSeriesSet containing MCMC samples |
Computes credible intervals (percentiles specified in calc_output_percentiles) for all model outputs, providing uncertainty bounds on predictions.
Definition at line 879 of file MCMC.hpp.
References BTCout_obs, BTCout_obs_noise, BTCout_obs_prcntle, BTCout_obs_prcntle_noise, calc_output_percentiles, FileInformation, MCMC_Settings, Model, and ProduceRealizations().
| int CMCMC< T >::get_time_series | ( | int | i | ) |
Get time series index for parameter (legacy, may be unused).
| i | Parameter index |
| int CMCMC< T >::getparamno | ( | int | i, |
| int | ts ) const |
Get parameter index for a specific variable and time series.
| i | Variable index |
| ts | Time series index |
Referenced by initialize().
| void CMCMC< T >::initialize | ( | CMBTimeSeriesSet * | results, |
| bool | random = false ) |
Initialize MCMC chains with starting parameter values.
| results | Pointer to results structure to store output (optional) |
| random | If true, randomize initial values within parameter ranges |
Sets up chains at initial parameter values. If random=true and noinipurt=false, adds random perturbations to explore different starting regions.
Definition at line 214 of file MCMC.hpp.
References chain_streams_, CopiedModels, DrawRandomSeed(), high, last_covariance_update_, log, logp, logp1, low, MCMC_Settings, Model, parameter(), parameters, Params, pertcoeff, posterior(), predicted, proposal_chol_, random_seed_, random_seed_set_, and temp_predicted.
Referenced by Conductor::ExecuteTestCMBBayesian(), SourceSinkData::MCMC(), and Perform().
Initialize all chains with specific parameter values.
| par | Vector of parameter values [p1, p2, ..., pn] |
All chains start at the same parameter values (may be perturbed if noinipurt=false).
Definition at line 302 of file MCMC.hpp.
References chain_streams_, DrawRandomSeed(), getparamno(), high, log, logp, logp1, low, MCMC_Settings, parameter(), Params, pertcoeff, posterior(), random_seed_, random_seed_set_, and sensitivity().
|
private |
Find maximum value and its chain index.
| vec | Vector of values (one per chain) |
| current_counter | Current sample number |
| n_chains | Number of chains |
Utility for tracking worst (lowest likelihood) chain.
Definition at line 970 of file MCMC.hpp.
References int_value_pair::counter, and int_value_pair::value.
|
private |
Find minimum value and its chain index.
| vec | Vector of values (one per chain) |
| current_counter | Current sample number |
| n_chains | Number of chains |
Utility for tracking best (highest likelihood) chain.
Definition at line 954 of file MCMC.hpp.
References int_value_pair::counter, and int_value_pair::value.
Evaluate model with given parameters.
| Model1 | Pointer to model object to evaluate |
| par | Parameter values to use |
Sets parameters in model and computes predictions. Used within posterior() for likelihood calculation.
Definition at line 197 of file MCMC.hpp.
References MCMC_Settings.
Evaluate model for given parameters and return predictions.
| par | Parameter values |
Wrapper for model evaluation that returns predictions in convenient format.
Definition at line 53 of file MCMC.hpp.
References MCMC_Settings, and Model.
| Observation * CMCMC< T >::observation | ( | int | i | ) |
Get pointer to specific observation.
| i | Observation index |
Definition at line 47 of file MCMC.hpp.
References observations.
Get pointer to specific parameter.
| i | Parameter index |
Definition at line 40 of file MCMC.hpp.
References parameters.
Referenced by initialize(), initialize(), posterior(), prior_distribution(), and UpdateProposalCovariance().
| void CMCMC< T >::Perform | ( | ) |
Main entry point to run complete MCMC analysis.
Executes full MCMC workflow:
Definition at line 908 of file MCMC.hpp.
References initialize(), and MCMC_Settings.
Generate proposed parameter values by perturbing current state.
| k | Chain index to perturb |
Proposal distribution: θ* ~ N(θ_current, diag(pertcoeff²)) Respects parameter bounds by reflecting or rejecting out-of-bounds proposals.
Definition at line 498 of file MCMC.hpp.
References chain_streams_, MCMC_Settings, pertcoeff, proposal_chol_, RandomStream::StandardNormal(), and step().
Referenced by step().
Calculate log-posterior probability for given parameters.
| par | Parameter vector [θ1, θ2, ..., θn] |
| chain_counter | Chain index for thread-safe model evaluation |
Computes:
Definition at line 179 of file MCMC.hpp.
References CopiedModels, MCMC_Settings, parameter(), and temp_predicted.
Referenced by initialize(), initialize(), and sensitivity().
| TimeSeriesSet< double > CMCMC< T >::prior_distribution | ( | int | n_bins | ) |
Generate histogram of prior distributions.
| n_bins | Number of bins for histogram |
Creates visual representation of priors for plotting and comparison with posteriors.
Definition at line 793 of file MCMC.hpp.
References log, MCMC_Settings, and parameter().
| void CMCMC< T >::ProduceRealizations | ( | TimeSeriesSet< double > & | MCMCout | ) |
Generate posterior predictive realizations.
| MCMCout | TimeSeriesSet containing MCMC samples |
Samples parameters from posterior and evaluates model to create posterior predictive distribution for uncertainty quantification.
Number of realizations set by MCMC_Settings.number_of_post_estimate_realizations.
Definition at line 835 of file MCMC.hpp.
Referenced by get_outputpercentiles().
|
inline |
Read MCMC state from file to continue previous run.
| filename | Path to file containing saved MCMC state |
Restores:
Allows resuming long MCMC runs without starting over.
Definition at line 767 of file MCMC.hpp.
References logp, logp1, MCMC_Settings, Params, and pertcoeff.
Calculate sensitivity of model output to parameters.
| d | Finite difference step size (fractional) |
| par | Current parameter values |
Computes numerical derivatives using forward finite differences: S_i = (model(θ + δθ_i) - model(θ)) / δθ_i
Used for sensitivity-based proposal adaptation.
Definition at line 737 of file MCMC.hpp.
References MCMC_Settings, and posterior().
Referenced by initialize().
Calculate lumped sensitivity matrix.
| d | Finite difference step size |
| par | Current parameter values |
Computes full Jacobian matrix of model outputs with respect to parameters. Used for global sensitivity analysis and identifiability assessment.
Set MCMC properties from string key-value pairs.
| varname | Property name (e.g., "number_of_samples", "acceptance_rate") |
| value | Property value as string |
Allows configuration from text files or user input.
Definition at line 75 of file MCMC.hpp.
References FileInformation, last_error, and MCMC_Settings.
Referenced by Conductor::ExecuteTestCMBBayesian(), and SourceSinkData::MCMC().
| void CMCMC< T >::SetRandomSeed | ( | std::uint64_t | seed | ) |
Sets the master seed for the chains' random streams.
Chain i draws from RandomStream(seed, i), so the same seed and settings give the same samples however many threads run the chains. Call before initialize(); if it is not called, initialize() draws a seed from the operating system. RandomSeed() returns the seed used either way.
Definition at line 706 of file MCMC.hpp.
References random_seed_, and random_seed_set_.
Referenced by Conductor::ExecuteTestCMBBayesian(), and SourceSinkData::MCMC().
| void CMCMC< T >::SetRunTimeWindow | ( | ProgressReporter * | _rtw | ) |
Set progress window for GUI updates.
| _rtw | Pointer to ProgressReporter object |
Links MCMC to a progress dialog for real-time status updates.
| bool CMCMC< T >::step | ( | int | k, |
| int | chain_counter ) |
Perform single MCMC step for one chain.
| k | Sample iteration number |
| chain_counter | Index of chain to advance |
Executes one Metropolis-Hastings update:
Definition at line 367 of file MCMC.hpp.
References MCMC_Settings, and perturb().
Referenced by Conductor::ExecuteTestCMBBayesian(), SourceSinkData::MCMC(), and perturb().
| bool CMCMC< T >::step | ( | int | k, |
| int | nsamps, | ||
| const string & | filename, | ||
| CMBTimeSeriesSet * | results = nullptr, | ||
| ProgressReporter * | _rtw = 0 ) |
Perform multiple MCMC steps with progress tracking and output.
| k | Starting sample number |
| nsamps | Number of samples to generate |
| filename | Output file for saving samples |
| results | Pointer to results structure (optional) |
| _rtw | Pointer to progress window for GUI updates (optional) |
Runs the main MCMC loop with:
Definition at line 540 of file MCMC.hpp.
References rtw.
| void CMCMC< T >::UpdateProposalCovariance | ( | int | upto | ) |
Re-estimates the proposal covariance from samples burn-in..upto.
Stores its Cholesky factor in proposal_chol_; keeps the previous factor when there are too few samples or the matrix is not positive definite.
Definition at line 411 of file MCMC.hpp.
References log, MCMC_Settings, parameter(), and Params.
Write MCMC results to output file.
| filename | Path to output file |
Saves:
Format is typically tab-delimited text for easy import into analysis software.
| double CMCMC< T >::accepted_count = 0 |
Posterior predictive samples for observations.
Model predictions at sampled parameter values. Structure: BTCout_obs[observation][realization]
Definition at line 775 of file MCMC.h.
Referenced by get_outputpercentiles().
Posterior predictive samples with simulated measurement noise.
As BTCout_obs but with added observation errors sampled from measurement uncertainty distributions.
Definition at line 783 of file MCMC.h.
Referenced by get_outputpercentiles().
Percentiles of posterior predictive distribution.
Credible intervals for model predictions (e.g., 2.5%, 50%, 97.5% percentiles).
Definition at line 790 of file MCMC.h.
Referenced by get_outputpercentiles().
Percentiles of posterior predictive distribution with noise.
Credible intervals including measurement uncertainty.
Definition at line 797 of file MCMC.h.
Referenced by get_outputpercentiles().
Percentiles to calculate for output distributions.
Vector of percentile values (0-1 scale) to compute. Typical: {0.025, 0.16, 0.5, 0.84, 0.975} for 95% and 68% intervals.
Definition at line 846 of file MCMC.h.
Referenced by get_outputpercentiles().
| vector<RandomStream> CMCMC< T >::chain_streams_ |
One random stream per chain, so no generator is shared between threads.
Definition at line 869 of file MCMC.h.
Referenced by initialize(), initialize(), and perturb().
Copies of model object for parallel chain evaluation.
Each chain gets its own model copy to allow thread-safe parallel execution. Dimensions: [number_of_chains]
Definition at line 570 of file MCMC.h.
Referenced by initialize(), and posterior().
| _MCMC_file_names CMCMC< T >::FileInformation |
File paths for MCMC input/output.
Configuration structure containing output directory and filenames.
Definition at line 607 of file MCMC.h.
Referenced by CMCMC(), get_outputpercentiles(), and SetProperty().
| unsigned int CMCMC< T >::last_covariance_update_ = 0 |
Definition at line 533 of file MCMC.h.
Referenced by initialize().
Last error message from MCMC execution.
If MCMC fails or encounters issues, error description is stored here.
Definition at line 883 of file MCMC.h.
Referenced by SetProperty().
Log-posterior values for current state of each chain.
Dimensions: [number_of_chains] Updated after each MCMC step.
Definition at line 440 of file MCMC.h.
Referenced by ~CMCMC(), initialize(), initialize(), and readfromfile().
Log-posterior values for proposed states.
Temporary storage for evaluating proposed parameter values. Dimensions: [number_of_chains]
Definition at line 448 of file MCMC.h.
Referenced by ~CMCMC(), initialize(), initialize(), and readfromfile().
| _MCMC_settings CMCMC< T >::MCMC_Settings |
MCMC algorithm configuration settings.
All tuning parameters and flags controlling MCMC behavior. Modify before calling Perform() or initialize().
Definition at line 416 of file MCMC.h.
Referenced by CMCMC(), get_outputpercentiles(), initialize(), initialize(), model(), model(), Perform(), perturb(), posterior(), prior_distribution(), readfromfile(), sensitivity(), SetProperty(), step(), and UpdateProposalCovariance().
| TimeSeriesSet<double> CMCMC< T >::MData |
| T* CMCMC< T >::Model |
Pointer to the model object being calibrated.
The model provides likelihood evaluation and predictions. For SedSat3, this is typically a SourceSinkData object.
Definition at line 359 of file MCMC.h.
Referenced by CMCMC(), Conductor::ExecuteTestCMBBayesian(), get_outputpercentiles(), initialize(), SourceSinkData::MCMC(), and model().
| T CMCMC< T >::Model_out |
| vector<Observation>* CMCMC< T >::observations = nullptr |
Pointer to vector of Observation objects.
Contains observed tracer concentrations and measurement uncertainties. Must be set before running MCMC.
Definition at line 678 of file MCMC.h.
Referenced by CMCMC(), and observation().
Pointer to vector of Parameter objects.
Contains prior distributions, ranges, and names for all parameters. Must be set before running MCMC.
Definition at line 670 of file MCMC.h.
Referenced by CMCMC(), initialize(), and parameter().
Parameter values for all samples and chains.
Storage structure: Params[chain_index][parameter_index] Dimensions: [number_of_chains][number_of_parameters]
Definition at line 424 of file MCMC.h.
Referenced by ~CMCMC(), initialize(), initialize(), readfromfile(), and UpdateProposalCovariance().
| TimeSeriesSet<double> CMCMC< T >::paramsList |
Perturbation coefficients for each parameter.
Adaptive proposal standard deviations, one per parameter. Updated during sampling to achieve target acceptance rate.
Definition at line 432 of file MCMC.h.
Referenced by CMCMC(), initialize(), initialize(), perturb(), and readfromfile().
| CMBTimeSeriesSet CMCMC< T >::predicted |
Model predictions as time series set.
Contains predicted tracer concentrations for plotting and comparison with observations.
Definition at line 562 of file MCMC.h.
Referenced by initialize(), and SourceSinkData::MCMC().
Cholesky factor of the proposal covariance; empty until the first update.
Definition at line 532 of file MCMC.h.
Referenced by initialize(), and perturb().
| std::uint64_t CMCMC< T >::random_seed_ = 0 |
Master seed for the chains' random streams; see SetRandomSeed().
Definition at line 865 of file MCMC.h.
Referenced by initialize(), initialize(), RandomSeed(), and SetRandomSeed().
| bool CMCMC< T >::random_seed_set_ = false |
Definition at line 866 of file MCMC.h.
Referenced by initialize(), initialize(), and SetRandomSeed().
| TimeSeriesSet<double> CMCMC< T >::realized_paramsList |
| ProgressReporter* CMCMC< T >::rtw = nullptr |
Temporary storage for predicted model outputs.
Used during likelihood evaluation to store model predictions for each chain without modifying the main model object.
Definition at line 554 of file MCMC.h.
Referenced by initialize(), and posterior().
| double CMCMC< T >::total_count = 0 |