https://mooseframework.inl.gov
Loading...
Searching...
No Matches
AdaptiveImportanceSampler.C
Go to the documentation of this file.
1//* This file is part of the MOOSE framework
2//* https://mooseframework.inl.gov
3//*
4//* All rights reserved, see COPYRIGHT for full restrictions
5//* https://github.com/idaholab/moose/blob/master/COPYRIGHT
6//*
7//* Licensed under LGPL 2.1, please see LICENSE for details
8//* https://www.gnu.org/licenses/lgpl-2.1.html
9
12#include "Distribution.h"
13#include "Normal.h"
14#include "Uniform.h"
15
16registerMooseObjectAliased("StochasticToolsApp", AdaptiveImportanceSampler, "AdaptiveImportance");
17
20{
22 params.addClassDescription("Adaptive Importance Sampler.");
23 params.addRequiredParam<std::vector<DistributionName>>(
24 "distributions",
25 "The distribution names to be sampled, the number of distributions provided defines the "
26 "number of columns per matrix.");
27 params.addRequiredParam<ReporterName>("inputs_reporter", "Reporter with input parameters.");
28 params.addRequiredParam<std::vector<Real>>("proposal_std",
29 "Standard deviations of the proposal distributions");
30 params.addRequiredParam<Real>("output_limit", "Limiting values of the VPPs");
31 params.addRequiredParam<std::vector<Real>>(
32 "initial_values", "Initial input values to get the importance sampler started");
34 "num_samples_train",
35 "num_samples_train>0",
36 "Number of samples to learn the importance distribution");
38 "num_importance_sampling_steps",
39 "num_importance_sampling_steps>0",
40 "Number of importance sampling steps (after the importance distribution has been trained)");
41 params.addRequiredParam<Real>(
42 "std_factor", "Factor to be multiplied to the standard deviation of the importance samples");
43 params.addParam<bool>("use_absolute_value", false, "Use absolute value of the sub app output");
44 params.addParam<unsigned int>(
45 "num_random_seeds",
46 100000,
47 "Initialize a certain number of random seeds. Change from the default only if you have to.");
48 params.addParam<ReporterName>("flag_sample",
49 "Flag samples if the surrogate prediction was inadequate.");
50 return params;
51}
52
54 : Sampler(parameters),
56 _proposal_std(getParam<std::vector<Real>>("proposal_std")),
57 _initial_values(getParam<std::vector<Real>>("initial_values")),
58 _output_limit(getParam<Real>("output_limit")),
59 _num_samples_train(getParam<int>("num_samples_train")),
60 _num_importance_sampling_steps(getParam<int>("num_importance_sampling_steps")),
61 _std_factor(getParam<Real>("std_factor")),
62 _use_absolute_value(getParam<bool>("use_absolute_value")),
63 _num_random_seeds(getParam<unsigned int>("num_random_seeds")),
64 _is_sampling_completed(declareRecoverableData<bool>("is_sampling_completed", false)),
65 _inputs(getReporterValue<std::vector<std::vector<Real>>>("inputs_reporter")),
66 _prev_value(declareRecoverableData<std::vector<Real>>("prev_value")),
67 _mean_sto(declareRecoverableData<std::vector<Real>>("mean_sto")),
68 _std_sto(declareRecoverableData<std::vector<Real>>("std_sto")),
69 _inputs_sto(declareRecoverableData<std::vector<std::vector<Real>>>("inputs_sto")),
70 _retraining_steps(declareRecoverableData<int>("retraining_steps", 0)),
71 _gp_flag(isParamValid("flag_sample") ? &getReporterValue<std::vector<bool>>("flag_sample")
72 : nullptr)
73{
74 // Filling the `distributions` vector with the user-provided distributions.
75 for (const DistributionName & name : getParam<std::vector<DistributionName>>("distributions"))
77
78 /* Adaptive Importance Sampling (AdaptiveImportanceSampler) relies on a Markov Chain Monte Carlo
79 (MCMC) algorithm. As such, in MOOSE, any use of MCMC algorithms requires that the `num_steps`
80 parameter in the main App's executioner would control the total number of samples. Therefore,
81 the `num_rows` parameter typically used by exisiting non-MCMC samplers to set the total number
82 of samples has no use here and is fixed to 1.*/
84
85 // Setting the number of columns in the sampler matrix (equal to the number of distributions).
87
88 /* `inputs_sto` is a member variable that aids in forming the importance distribution.
89 One dimension of this variable is equal to the number of distributions. The other dimension
90 of the variable, at the last step, is equal to the number of samples the user desires.*/
91 _inputs_sto.resize(_distributions.size());
92
93 // Mapping all the input distributions to a standard normal space
94 for (unsigned int i = 0; i < _distributions.size(); ++i)
95 _inputs_sto[i].push_back(Normal::quantile(_distributions[i]->cdf(_initial_values[i]), 0, 1));
96
97 /* `prev_value` is a member variable for tracking the previously accepted samples in the
98 MCMC algorithm and proposing the next sample.*/
99 _prev_value.resize(_distributions.size());
100
101 // Storage for means of input values for proposing the next sample
102 _mean_sto.resize(_distributions.size());
103
104 // Storage for standard deviations of input values for proposing the next sample
105 _std_sto.resize(_distributions.size());
106
109}
110
111void
113{
114 const bool sample = _t_step > 1;
115 const bool gp_flag = _gp_flag ? (*_gp_flag)[0] : false;
116
117 if (sample && _is_sampling_completed)
118 mooseError("Internal bug: the adaptive sampling is supposed to be completed but another sample "
119 "has been requested.");
120
122 {
123 /* This is the importance distribution training step. Markov Chains are set up
124 to sample from the importance region or the failure region using the Metropolis
125 algorithm. Given that the previous sample resulted in a model failure, the next
126 sample is proposed such that it is very likely to result in a model failure as well.
127 The `initial_values` and `proposal_std` parameters provided by the user affects the
128 formation of the importance distribution. */
129 if (sample && !gp_flag)
130 {
131 for (dof_id_type j = 0; j < _distributions.size(); ++j)
132 _prev_value[j] = Normal::quantile(_distributions[j]->cdf(_inputs[j][0]), 0.0, 1.0);
133 Real acceptance_ratio = 0.0;
134 for (dof_id_type i = 0; i < _distributions.size(); ++i)
135 acceptance_ratio += std::log(Normal::pdf(_prev_value[i], 0.0, 1.0)) -
136 std::log(Normal::pdf(_inputs_sto[i].back(), 0.0, 1.0));
137 if (acceptance_ratio > std::log(getRand(0, _t_step)))
138 {
139 for (dof_id_type i = 0; i < _distributions.size(); ++i)
140 _inputs_sto[i].push_back(_prev_value[i]);
141 }
142 else
143 {
144 for (dof_id_type i = 0; i < _distributions.size(); ++i)
145 _inputs_sto[i].push_back(_inputs_sto[i].back());
146 }
147 for (dof_id_type i = 0; i < _distributions.size(); ++i)
148 _prev_value[i] =
150 }
151 }
152 else if (sample && !gp_flag)
153 {
154 /* This is the importance sampling step using the importance distribution created
155 in the previous step. Once the importance distribution is known, sampling from
156 it is similar to a regular Monte Carlo sampling. */
157 for (dof_id_type i = 0; i < _distributions.size(); ++i)
158 {
159 if (_t_step == _num_samples_train + 1)
160 {
163 }
164 _prev_value[i] =
166 }
167
168 // check if we have performed all the importance sampling steps
171 }
172
173 // When the GP fails, the current time step is 'wasted' and the retraining step doesn't
174 // happen until the next time step. Therefore, keep track of the number of retraining steps
175 // to increase the total number of steps taken.
176 if (sample && gp_flag && _t_step > _num_samples_train)
178}
179
180Real
181AdaptiveImportanceSampler::computeSample(dof_id_type /*row_index*/, dof_id_type col_index) const
182{
183 return _distributions[col_index]->quantile(Normal::cdf(_prev_value[col_index], 0.0, 1.0));
184}
registerMooseObjectAliased("StochasticToolsApp", AdaptiveImportanceSampler, "AdaptiveImportance")
void ErrorVector unsigned int
A class used to perform Adaptive Importance Sampling using a Markov Chain Monte Carlo algorithm.
std::vector< Real > & _prev_value
For proposing the next sample in the MCMC algorithm.
std::vector< const Distribution * > _distributions
Storage for distribution objects to be utilized.
int & _retraining_steps
Number of retraining performed.
const std::vector< bool > *const _gp_flag
Indicate whether GP prediction is good or bad to influence next proposed sample.
std::vector< Real > & _mean_sto
Storage for means of input values for proposing the next sample.
const unsigned int & _num_random_seeds
Initialize a certain number of random seeds. Change from the default only if you have to.
std::vector< Real > & _std_sto
Storage for standard deviations of input values for proposing the next sample.
bool & _is_sampling_completed
True if the sampling is completed.
virtual Real computeSample(dof_id_type row_index, dof_id_type col_index) const override
Return the sample for the given row (the sample index) and column (the parameter index)
const int & _num_importance_sampling_steps
Number of importance sampling steps (after the importance distribution has been trained)
AdaptiveImportanceSampler(const InputParameters &parameters)
virtual void executeSetUp() override
static InputParameters validParams()
const int & _num_samples_train
Number of samples to train the importance sampler.
const Real & _std_factor
Factor to be multiplied to the standard deviation of the proposal distribution.
std::vector< std::vector< Real > > & _inputs_sto
Storage for previously accepted samples by the decision reporter system.
const std::vector< Real > & _initial_values
Initial values values vector to start the importance sampler.
const std::vector< std::vector< Real > > & _inputs
Storage for the inputs vector obtained from the reporter.
const std::vector< Real > & _proposal_std
The proposal distribution standard deviations.
const Distribution & getDistributionByName(const DistributionName &name) const
void addRequiredRangeCheckedParam(const std::string &name, const std::string &parsed_function, const std::string &doc_string)
void addRequiredParam(const std::string &name, const std::string &doc_string)
void addParam(const std::string &name, const std::initializer_list< typename T::value_type > &value, const std::string &doc_string)
void addClassDescription(const std::string &doc_string)
const std::string & name() const
void mooseError(Args &&... args) const
virtual Real cdf(const Real &x) const override
Definition Normal.C:74
virtual Real pdf(const Real &x) const override
Definition Normal.C:68
virtual Real quantile(const Real &p) const override
Definition Normal.C:80
void setNumberOfCols(dof_id_type n_cols)
Real getRand(std::size_t n, unsigned int index=0) const
void setAutoAdvanceGenerators(const bool state)
static InputParameters validParams()
void setNumberOfRows(dof_id_type n_rows)
void setNumberOfRandomSeeds(std::size_t number)
Real computeSTD(const std::vector< Real > &data, const unsigned int &start_index)
compute the standard deviation of a data vector by only considering values from a specific index.
Real computeMean(const std::vector< Real > &data, const unsigned int &start_index)
compute the mean of a data vector by only considering values from a specific index.