https://mooseframework.inl.gov
Loading...
Searching...
No Matches
Sampler.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
10// STL includes
11#include <iterator>
12
13// MOOSE includes
14#include "Sampler.h"
15
18{
22 params.addClassDescription("A base class for distribution sampling.");
23
24 ExecFlagEnum & exec_enum = params.set<ExecFlagEnum>("execute_on", true);
26 exec_enum = {EXEC_INITIAL};
27
28 params.addParam<unsigned int>("seed", 0, "Random number generator initial seed");
29 params.registerBase("Sampler");
30 params.registerSystemAttributeName("Sampler");
31
32 // Define the allowable limits for data returned by getSamples/getLocalSamples/getSampleRow
33 // to prevent system for going over allowable limits. The DenseMatrix object uses unsigned int
34 // for size definition, so as start the limits will be based the max of unsigned int. Note,
35 // the values here are the limits of the number of items in the complete container. dof_id_type
36 // is used just in case in the future we need more.
37 params.addParam<dof_id_type>("limit_get_global_samples",
38 0.1 * std::numeric_limits<unsigned int>::max(),
39 "The maximum allowed number of items in the DenseMatrix returned by "
40 "getGlobalSamples method.");
41 params.addParam<dof_id_type>(
42 "limit_get_local_samples",
43 0.1 * std::numeric_limits<unsigned int>::max(),
44 "The maximum allowed number of items in the DenseMatrix returned by getLocalSamples method.");
45 params.addParam<dof_id_type>(
46 "limit_get_row",
47 0.1 * std::numeric_limits<unsigned int>::max(),
48 "The maximum allowed number of items in the std::vector returned by getSampleRow method.");
49
50 params.addParam<unsigned int>(
51 "min_procs_per_row",
52 1,
53 "This will ensure that the sampler is partitioned properly when "
54 "'MultiApp/*/min_procs_per_app' is specified. It is not recommended to use otherwise.");
55 params.addParam<unsigned int>(
56 "max_procs_per_row",
57 std::numeric_limits<unsigned int>::max(),
58 "This will ensure that the sampler is partitioned properly when "
59 "'MultiApp/*/max_procs_per_app' is specified. It is not recommended to use otherwise.");
60 return params;
61}
62
64 : MooseObject(parameters),
65 SetupInterface(this),
68 SamplerInterface(this),
71 Restartable(this, "Samplers"),
72 _min_procs_per_row(getParam<unsigned int>("min_procs_per_row") > n_processors()
73 ? n_processors()
74 : getParam<unsigned int>("min_procs_per_row")),
75 _max_procs_per_row(getParam<unsigned int>("max_procs_per_row")),
76 _generators(
77 declareRecoverableData<std::vector<std::unique_ptr<MooseRandomStateless>>>("generators")),
78 _n_local_rows(declareRecoverableData<dof_id_type>("n_local_rows")),
79 _local_row_begin(declareRecoverableData<dof_id_type>("local_row_begin")),
80 _local_row_end(declareRecoverableData<dof_id_type>("local_row_end")),
81 _n_rows(declareRecoverableData<dof_id_type>("n_rows")),
82 _n_cols(declareRecoverableData<dof_id_type>("n_cols")),
83 _n_seeds(1),
84 _initialized(false),
85 _needs_reinit(true),
86 _has_executed(declareRecoverableData<bool>("has_executed")),
87 _limit_get_global_samples(getParam<dof_id_type>("limit_get_global_samples")),
88 _limit_get_local_samples(getParam<dof_id_type>("limit_get_local_samples")),
89 _limit_get_row(getParam<dof_id_type>("limit_get_row")),
90 _rank_config(
91 declareRecoverableData<std::pair<LocalRankConfig, LocalRankConfig>>("rank_config")),
92 _auto_advance_generators(true)
93{
94}
95
96void
98{
99 // The init() method is private so it is un-likely to be called, but just in case the following
100 // was added to help avoid future mistakes.
101 if (_initialized)
102 mooseError("The Sampler::init() method is called automatically and should not be called.");
103
104 // Initialize the parallel partition of sample to return
105 reinit();
106
107 // Seed the "master" seed generator
108 const unsigned int seed = getParam<unsigned int>("seed");
109 MooseRandom seed_generator;
110 seed_generator.seed(0, seed);
111
112 // See the "secondary" generator that will be used for the random number generation
113 _generators.resize(_n_seeds);
114 for (std::size_t i = 0; i < _n_seeds; ++i)
115 {
116 const auto gseed = seed_generator.randl(0);
117 _generators[i] = std::make_unique<MooseRandomStateless>(gseed);
118 }
119
120 // Mark class as initialized, which locks out certain methods
121 _initialized = true;
122}
123
124void
126{
127 _rank_config.first = constructRankConfig(false);
128 _rank_config.second = constructRankConfig(true);
129 if (_rank_config.first.num_local_sims != _rank_config.second.num_local_sims ||
130 _rank_config.first.first_local_sim_index != _rank_config.second.first_local_sim_index ||
131 _rank_config.first.is_first_local_rank != _rank_config.second.is_first_local_rank)
132 mooseError("Sampler has inconsistent partitionings for normal and batch mode.");
133
134 _n_local_rows = _rank_config.first.is_first_local_rank ? _rank_config.first.num_local_sims : 0;
135 _local_row_begin = _rank_config.first.first_local_sim_index;
137
138 // Update reinit() flag (see execute method)
139 _needs_reinit = false;
140}
141
143Sampler::constructRankConfig(bool batch_mode) const
144{
145 return rankConfig(
147}
148
149void
150Sampler::setNumberOfRows(dof_id_type n_rows)
151{
152 if (n_rows == 0)
153 mooseError("The number of rows cannot be zero.");
154
155 _needs_reinit = true;
156 _n_rows = n_rows;
157}
158
159void
160Sampler::setNumberOfCols(dof_id_type n_cols)
161{
162 if (n_cols == 0)
163 mooseError("The number of columns cannot be zero.");
164
165 _needs_reinit = true;
166 _n_cols = n_cols;
167}
168
169void
171{
172 if (_initialized)
173 mooseError("The 'setNumberOfRandomSeeds()' method can not be called after the Sampler has been "
174 "initialized; "
175 "this method should be called in the constructor of the Sampler object.");
176
177 if (n_seeds == 0)
178 mooseError("The number of seeds must be larger than zero.");
179
180 _n_seeds = n_seeds;
181}
182
183void
185{
186 executeSetUp();
187 if (_needs_reinit)
188 reinit();
189
190 if (_has_executed)
192
194 _has_executed = true;
195}
196
197DenseMatrix<Real>
199{
200 TIME_SECTION("getGlobalSamples", 1, "Retrieving Global Samples");
201
203
205 paramError("limit_get_global_samples",
206 "The number of entries in the DenseMatrix (",
208 ") exceeds the allowed limit of ",
210 ".");
211
212 DenseMatrix<Real> output(_n_rows, _n_cols);
213 computeSampleMatrix(output);
214 return output;
215}
216
217DenseMatrix<Real>
219{
220 TIME_SECTION("getLocalSamples", 1, "Retrieving Local Samples");
221
223
225 paramError("limit_get_local_samples",
226 "The number of entries in the DenseMatrix (",
228 ") exceeds the allowed limit of ",
230 ".");
231
232 DenseMatrix<Real> output(_n_local_rows, _n_cols);
233 if (_n_local_rows == 0)
234 return output;
235
237 return output;
238}
239
240std::vector<Real>
241Sampler::getSampleRow(dof_id_type row_index) const
242{
245 paramError("limit_get_row",
246 "The number of entries in the std::vector (",
247 _n_cols,
248 ") exceeds the allowed limit of ",
250 ".");
251 mooseAssert(row_index < _n_rows,
252 "Requested row " + std::to_string(row_index) + " is greater than sampler size.");
253
254 std::vector<Real> row(_n_cols, 0);
255 computeSampleRow(row_index, row);
256 return row;
257}
258
259Real
260Sampler::getSample(dof_id_type row_index, dof_id_type col_index) const
261{
263 mooseAssert(row_index < _n_rows,
264 "Requested row " + std::to_string(row_index) + " is greater than sampler size.");
265 mooseAssert(col_index < _n_cols, "Column index out of range.");
266 return computeSample(row_index, col_index);
267}
268
269void
270Sampler::computeSampleMatrix(DenseMatrix<Real> & matrix)
271{
272 TIME_SECTION("computeSampleMatrix", 2, "Computing Sample Matrix");
273
274 for (dof_id_type i = 0; i < _n_rows; ++i)
275 {
276 std::vector<Real> row(_n_cols, 0);
277 computeSampleRow(i, row);
278 mooseAssert(row.size() == _n_cols, "The row of sample data is not sized correctly.");
279 std::copy(row.begin(), row.end(), matrix.get_values().begin() + i * _n_cols);
280 }
281}
282
283void
284Sampler::computeLocalSampleMatrix(DenseMatrix<Real> & matrix)
285{
286 TIME_SECTION("computeLocalSampleMatrix", 2, "Computing Local Sample Matrix");
287
288 for (dof_id_type i = _local_row_begin; i < _local_row_end; ++i)
289 {
290 std::vector<Real> row(_n_cols, 0);
291 computeSampleRow(i, row);
292 mooseAssert(row.size() == _n_cols, "The row of sample data is not sized correctly.");
293 std::copy(
294 row.begin(), row.end(), matrix.get_values().begin() + ((i - _local_row_begin) * _n_cols));
295 }
296}
297
298void
299Sampler::computeSampleRow(dof_id_type i, std::vector<Real> & data) const
300{
301 for (dof_id_type j = 0; j < _n_cols; ++j)
302 data[j] = computeSample(i, j);
303}
304
305void
307{
308 TIME_SECTION("advanceGenerators", 2, "Advancing Generators");
309
310 for (std::size_t j = 0; j < _generators.size(); ++j)
312}
313void
314Sampler::advanceGenerator(const unsigned int seed_index, const dof_id_type count)
315{
316 mooseAssert(seed_index < _generators.size(), "The seed number index does not exists.");
317 _generators[seed_index]->advance(count);
318}
319
320void
326
327void
329{
331}
332
333Real
334Sampler::getRand(std::size_t n, unsigned int index) const
335{
336 mooseAssert(index < _generators.size(), "The seed number index does not exists.");
337 return _generators[index]->rand(n);
338}
339
340unsigned int
341Sampler::getRandl(std::size_t n, unsigned int lower, unsigned int upper, unsigned int index) const
342{
343 mooseAssert(index < _generators.size(), "The seed number index does not exists.");
344 return _generators[index]->randl(n, lower, upper);
345}
346
347dof_id_type
349{
351 return _n_rows;
352}
353
354dof_id_type
356{
358 return _n_cols;
359}
360
361dof_id_type
367
368dof_id_type
374
375dof_id_type
377{
379 return _local_row_end;
380}
381
382void
384{
385 if (_needs_reinit)
386 mooseError("A call to 'setNumberOfRows()/Columns()' was made after initialization, as such the "
387 "expected Sampler output has changed and a new sample must be created. However, a "
388 "call to Sampler::reinit() was not performed. The renit() method is automatically "
389 "called during Sampler execution, which occurs according to the 'execute_on' "
390 "settings of the Sampler object. An adjustment to this parameter may be required. "
391 "It is recommended that calls to 'setNumberOfRows()/Columns() occur within the "
392 "Sampler::executeSetUp() method; this will ensure that the reinitialize is handled "
393 "correctly. Have a nice day.");
394}
const ExecFlagType EXEC_PRE_MULTIAPP_SETUP
Definition Moose.C:57
const ExecFlagType EXEC_INITIAL
Definition Moose.C:31
unsigned int count
Definition MortarUtils.C:53
LocalRankConfig rankConfig(processor_id_type rank, processor_id_type nprocs, dof_id_type napps, processor_id_type min_app_procs, processor_id_type max_app_procs, bool batch_mode=false)
Returns app partitioning information relevant to the given rank for a multiapp scenario with the give...
Definition MultiApp.C:1388
void ErrorVector unsigned int
Interface for objects that need to use distributions.
static InputParameters validParams()
A MultiMooseEnum object to hold "execute_on" flags.
void addAvailableFlags(const ExecFlagType &flag, Args... flags)
Add additional execute_on flags to the list of possible flags.
The main MOOSE class responsible for handling user-defined parameters in almost every MOOSE system.
void registerSystemAttributeName(const std::string &value)
This method is used to define the MOOSE system name that is used by the TheWarehouse object for stori...
void addParam(const std::string &name, const S &value, const std::string &doc_string)
These methods add an optional parameter and a documentation string to the InputParameters object.
void registerBase(const std::string &value)
This method must be called from every base "Moose System" to create linkage with the Action System.
void addClassDescription(const std::string &doc_string)
This method adds a description of the class that will be displayed in the input file syntax dump.
T & set(const std::string &name, bool quiet_mode=false)
Returns a writable reference to the named parameters.
void paramError(const std::string &param, Args... args) const
Emits an error prefixed with the file and line number of the given param (from the input file) along ...
Definition MooseBase.h:457
void mooseError(Args &&... args) const
Emits an error prefixed with object name and type and optionally a file path to the top-level block p...
Definition MooseBase.h:271
Every object that can be built by the factory should be derived from this class.
Definition MooseObject.h:31
static InputParameters validParams()
Definition MooseObject.C:25
A deterministic, indexable random number generator built on top of the randistrs library.
This class encapsulates a useful, consistent, cross-platform random number generator with multiple ut...
Definition MooseRandom.h:38
static uint32_t randl()
This method returns the next random number (long format) from the generator.
Definition MooseRandom.h:71
static void seed(unsigned int seed)
The method seeds the random number generator.
Definition MooseRandom.h:44
Interface for objects interacting with the PerfGraph.
Interface to allow object to consume Reporter values.
A class for creating restricted objects.
Definition Restartable.h:29
Interface for objects that need to use samplers.
virtual void advanceGenerator(const unsigned int seed_index, const dof_id_type count)
Definition Sampler.C:314
void checkReinitStatus() const
Helper function for reinit() errors.
Definition Sampler.C:383
void setNumberOfCols(dof_id_type n_cols)
Definition Sampler.C:160
const dof_id_type _limit_get_local_samples
Max number of entries for matrix returned by getLocalSamples.
Definition Sampler.h:309
Real getSample(dof_id_type row_index, dof_id_type col_index) const
Return a single sample value by global row and column index.
Definition Sampler.C:260
Real getRand(std::size_t n, unsigned int index=0) const
Get nth random number from the generator.
Definition Sampler.C:334
const dof_id_type _limit_get_global_samples
Max number of entries for matrix returned by getGlobalSamples.
Definition Sampler.h:306
void reinit()
Definition Sampler.C:125
void advanceGeneratorsInternal(const dof_id_type count)
Advance method for internal use that considers the auto advance flag.
Definition Sampler.C:321
bool & _has_executed
Flag for initial execute to allow the first set of random numbers to be always be the same.
Definition Sampler.h:303
bool _initialized
Flag to indicate if the init method for this class was called.
Definition Sampler.h:297
DenseMatrix< Real > getLocalSamples()
Definition Sampler.C:218
dof_id_type getNumberOfLocalRows() const
Definition Sampler.C:362
const dof_id_type _max_procs_per_row
The maximum number of processors that are associated with a set of rows.
Definition Sampler.h:239
void execute()
Advance MooseRandomStateless generators so that new calls to sample methods will create new numbers.
Definition Sampler.C:184
std::vector< std::unique_ptr< MooseRandomStateless > > & _generators
Random number generators, don't give users access. Control it via the interface from this class.
Definition Sampler.h:276
unsigned int getRandl(std::size_t n, unsigned int lower, unsigned int upper, unsigned int index=0) const
Get nth random integer from the generator within the specified range [lower, upper)
Definition Sampler.C:341
dof_id_type & _local_row_end
Global row index for end of data for this processor.
Definition Sampler.h:285
dof_id_type & _local_row_begin
Global row index for start of data for this processor.
Definition Sampler.h:282
dof_id_type getLocalRowEnd() const
Definition Sampler.C:376
void init()
Functions called by MOOSE to setup the Sampler for use.
Definition Sampler.C:97
dof_id_type getLocalRowBegin() const
Return the beginning/end local row index for this processor.
Definition Sampler.C:369
bool _auto_advance_generators
Flag for disabling automatic generator advancing.
Definition Sampler.h:319
virtual void executeSetUp()
Callbacks for before and after execute.
Definition Sampler.h:226
std::vector< Real > getSampleRow(dof_id_type row_index) const
Return a single sample row by global row.
Definition Sampler.C:241
virtual LocalRankConfig constructRankConfig(bool batch_mode) const
This is where the sampler partitioning is defined.
Definition Sampler.C:143
dof_id_type getNumberOfRows() const
Return the number of samples.
Definition Sampler.C:348
const dof_id_type _limit_get_row
Max number of entries for matrix returned by getSampleRow.
Definition Sampler.h:312
virtual void advanceGenerators(const dof_id_type count)
Method for advancing the random number generator(s) by the supplied number or calls to rand().
Definition Sampler.C:306
virtual void executeTearDown()
Definition Sampler.h:227
dof_id_type & _n_cols
Total number of columns in the sample matrix.
Definition Sampler.h:291
virtual void computeSampleMatrix(DenseMatrix< Real > &matrix)
Methods to populate the global or local sample matrix.
Definition Sampler.C:270
virtual void computeSampleRow(dof_id_type i, std::vector< Real > &data) const
Method to populate a complete row of sample data.
Definition Sampler.C:299
virtual Real computeSample(dof_id_type row_index, dof_id_type col_index) const =0
Base class must override this method to supply the sample distribution data.
void setAutoAdvanceGenerators(const bool state)
Definition Sampler.C:328
bool _needs_reinit
Flag to indicate if the reinit method should be called during execute.
Definition Sampler.h:300
static InputParameters validParams()
Definition Sampler.C:17
virtual void computeLocalSampleMatrix(DenseMatrix< Real > &matrix)
Definition Sampler.C:284
std::size_t _n_seeds
Number of seeds.
Definition Sampler.h:294
dof_id_type getNumberOfCols() const
Definition Sampler.C:355
void setNumberOfRows(dof_id_type n_rows)
These methods must be called within the constructor of child classes to define the size of the matrix...
Definition Sampler.C:150
dof_id_type & _n_rows
Total number of rows in the sample matrix.
Definition Sampler.h:288
dof_id_type & _n_local_rows
Number of rows for this processor.
Definition Sampler.h:279
const dof_id_type _min_procs_per_row
The minimum number of processors that are associated with a set of rows.
Definition Sampler.h:237
Sampler(const InputParameters &parameters)
Definition Sampler.C:63
std::pair< LocalRankConfig, LocalRankConfig > & _rank_config
The partitioning of the sampler matrix, built in reinit() first is for normal mode and second is for ...
Definition Sampler.h:316
void setNumberOfRandomSeeds(std::size_t number)
Set the number of seeds required by the sampler.
Definition Sampler.C:170
DenseMatrix< Real > getGlobalSamples()
Return the sampled complete or distributed sample data.
Definition Sampler.C:198
static InputParameters validParams()
processor_id_type processor_id() const
processor_id_type n_processors() const
Holds app partitioning information relevant to the a particular rank for a multiapp scenario.
Definition MultiApp.h:47