www.mooseframework.org
Sampler.C
Go to the documentation of this file.
1 //* This file is part of the MOOSE framework
2 //* https://www.mooseframework.org
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 #include "MooseRandom.h"
16 #include "Distribution.h"
17 
18 template <>
21 {
23  params += validParams<SetupInterface>();
25  params.addClassDescription("A base class for distribution sampling.");
26 
27  ExecFlagEnum & exec_enum = params.set<ExecFlagEnum>("execute_on", true);
29 
30  params.addRequiredParam<std::vector<DistributionName>>(
31  "distributions", "The names of distributions that you want to sample.");
32  params.addParam<unsigned int>("seed", 0, "Random number generator initial seed");
33  params.registerBase("Sampler");
34  return params;
35 }
36 
37 Sampler::Sampler(const InputParameters & parameters)
38  : MooseObject(parameters),
39  SetupInterface(this),
41  _distribution_names(getParam<std::vector<DistributionName>>("distributions")),
42  _seed(getParam<unsigned int>("seed")),
43  _total_rows(0)
44 {
45  for (const DistributionName & name : _distribution_names)
48 }
49 
50 void
52 {
53  // Get the samples then save the state so that subsequent calls to getSamples returns the same
54  // random numbers until this execute command is called again.
55  std::vector<DenseMatrix<Real>> data = getSamples();
57  reinit(data);
58 }
59 
60 void
61 Sampler::reinit(const std::vector<DenseMatrix<Real>> & data)
62 {
63  // Update offsets and total number of rows
64  _total_rows = 0;
65  _offsets.clear();
66  _offsets.reserve(data.size() + 1);
67  _offsets.push_back(_total_rows);
68  for (const DenseMatrix<Real> & mat : data)
69  {
70  _total_rows += mat.m();
71  _offsets.push_back(_total_rows);
72  }
73 
74  // Update parallel information
76  _total_rows, n_processors(), processor_id(), _local_rows, _local_row_begin, _local_row_end);
77 }
78 
79 std::vector<DenseMatrix<Real>>
81 {
83  sampleSetUp();
84  std::vector<DenseMatrix<Real>> output = sample();
86 
87  if (_sample_names.empty())
88  {
89  _sample_names.resize(output.size());
90  for (MooseIndex(output) i = 0; i < output.size(); ++i)
91  _sample_names[i] = "sample_" + std::to_string(i);
92  }
93  mooseAssert(output.size() == _sample_names.size(),
94  "The number of sample names must match the number of samples returned.");
95 
96  mooseAssert(output.size() > 0,
97  "It is not acceptable to return an empty vector of sample matrices.");
98 
99  return output;
100 }
101 
102 double
103 Sampler::rand(const unsigned int index)
104 {
105  mooseAssert(index < _generator.size(), "The seed number index does not exists.");
106  return _generator.rand(index);
107 }
108 
109 void
110 Sampler::setNumberOfRequiedRandomSeeds(const std::size_t & number)
111 {
112  if (number == 0)
113  mooseError("The number of seeds must be larger than zero.");
114 
115  // Seed the "master" seed generator
117 
118  // See the "slave" generator that will be used for the random number generation
119  for (std::size_t i = 0; i < number; ++i)
121 
123 }
124 
125 void
126 Sampler::setSampleNames(const std::vector<std::string> & names)
127 {
128  _sample_names = names;
129 
130  // Use assert because to check the size a getSamples call is required, which you don't
131  // want to do if you don't need it.
132  mooseAssert(getSamples().size() == _sample_names.size(),
133  "The number of sample names must match the number of samples returned.");
134 }
135 
137 Sampler::getLocation(dof_id_type global_index)
138 {
139  if (_offsets.empty())
140  reinit(getSamples());
141 
142  mooseAssert(_offsets.size() > 1,
143  "The getSamples method returned an empty vector, if you are seeing this you have "
144  "done something to bypass another assert in the 'getSamples' method that should "
145  "prevent this message.");
146 
147  // The lower_bound method returns the first value "which does not compare less than" the value and
148  // upper_bound performs "which compares greater than." The upper_bound -1 method is used here
149  // because lower_bound will provide the wrong index, but the method here will provide the correct
150  // index, see the Sampler.GetLocation test in moose/unit/src/Sampler.C for an example.
151  std::vector<unsigned int>::iterator iter =
152  std::upper_bound(_offsets.begin(), _offsets.end(), global_index) - 1;
153  return Sampler::Location(std::distance(_offsets.begin(), iter), global_index - *iter);
154 }
155 
156 dof_id_type
158 {
159  if (_total_rows == 0)
160  reinit(getSamples());
161  return _total_rows;
162 }
163 
167 dof_id_type
169 {
170  if (_total_rows == 0)
171  reinit(getSamples());
172  return _local_rows;
173 }
174 
178 dof_id_type
180 {
181  if (_total_rows == 0)
182  reinit(getSamples());
183  return _local_row_begin;
184 }
185 
189 dof_id_type
191 {
192  if (_total_rows == 0)
193  reinit(getSamples());
194  return _local_row_end;
195 }
static uint32_t randl()
This method returns the next random number (long format) from the generator.
Definition: MooseRandom.h:70
double rand(unsigned int index=0)
Get the next random number from the generator.
Definition: Sampler.C:103
dof_id_type _local_row_begin
Global row index for start of data for this processor.
Definition: Sampler.h:201
A MultiMooseEnum object to hold "execute_on" flags.
Definition: ExecFlagEnum.h:24
static double rand()
This method returns the next random number (double format) from the generator.
Definition: MooseRandom.h:49
MooseRandom _generator
Random number generator, don&#39;t give users access we want to control it via the interface from this cl...
Definition: Sampler.h:183
void setSampleNames(const std::vector< std::string > &names)
Set the sample names.
Definition: Sampler.C:126
virtual void sampleSetUp()
Setup method called prior and after looping through distributions.
Definition: Sampler.h:80
void saveState()
This method saves the current state of all generators which can be restored at a later time (i...
Definition: MooseRandom.h:125
std::vector< unsigned int > _offsets
Data offsets for computing location based on global row index.
Definition: Sampler.h:192
The main MOOSE class responsible for handling user-defined parameters in almost every MOOSE system...
void addAvailableFlags(const ExecFlagType &flag, Args... flags)
Add additional execute_on flags to the list of possible flags.
Definition: ExecFlagEnum.h:84
InputParameters validParams< SetupInterface >()
void mooseError(Args &&... args) const
Definition: MooseObject.h:147
void linearPartitionItems(dof_id_type num_items, dof_id_type num_chunks, dof_id_type chunk_id, dof_id_type &num_local_items, dof_id_type &local_items_begin, dof_id_type &local_items_end)
Linearly partition a number of items.
Definition: MooseUtils.C:689
Sampler(const InputParameters &parameters)
Definition: Sampler.C:37
Simple object for storing the sampler location (see SamplerTransientMultiApp and SamplerFullSolveMult...
Definition: Sampler.h:51
virtual std::vector< DenseMatrix< Real > > sample()=0
Base class must override this method to supply the sample distribution data.
std::vector< Distribution const * > _distributions
Map used to store the perturbed parameters and their corresponding distributions. ...
Definition: Sampler.h:172
void setNumberOfRequiedRandomSeeds(const std::size_t &number)
Set the number of seeds required by the sampler.
Definition: Sampler.C:110
Every object that can be built by the factory should be derived from this class.
Definition: MooseObject.h:42
dof_id_type _total_rows
Total number of rows.
Definition: Sampler.h:195
const ExecFlagType EXEC_PRE_MULTIAPP_SETUP
dof_id_type getTotalNumberOfRows()
Return the number of samples.
Definition: Sampler.C:157
Interface for objects that need to use distributions.
const unsigned int & _seed
Initial random number seed.
Definition: Sampler.h:189
std::vector< std::string > _sample_names
Sample names.
Definition: Sampler.h:178
Sampler::Location getLocation(dof_id_type global_index)
Return the Sample::Location for the given multi app index.
Definition: Sampler.C:137
virtual void sampleTearDown()
Definition: Sampler.h:81
void reinit(const std::vector< DenseMatrix< Real >> &data)
Reinitialize the offsets and row counts.
Definition: Sampler.C:61
MooseRandom _seed_generator
Seed generator.
Definition: Sampler.h:186
dof_id_type getLocalRowEnd()
Return the ending local row index for this processor.
Definition: Sampler.C:190
void restoreState()
This method restores the last saved generator state.
Definition: MooseRandom.h:138
std::size_t size()
Return the number of states.
Definition: MooseRandom.h:151
InputParameters validParams< MooseObject >()
Definition: MooseObject.C:25
dof_id_type _local_row_end
Global row index for end of data for this processor.
Definition: Sampler.h:204
InputParameters validParams< DistributionInterface >()
const Distribution & getDistributionByName(const DistributionName &name) const
Get a distribution with a given name.
static void seed(unsigned int seed)
The method seeds the random number generator.
Definition: MooseRandom.h:43
dof_id_type _local_rows
Number of global rows for this processor.
Definition: Sampler.h:198
std::vector< DenseMatrix< Real > > getSamples()
Return the sampled distribution data.
Definition: Sampler.C:80
const std::string & name() const
Get the name of the object.
Definition: MooseObject.h:59
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...
const std::vector< DistributionName > & _distribution_names
Distribution names.
Definition: Sampler.h:175
void execute()
Store the state of the MooseRandom generator so that new calls to getSamples will create new numbers...
Definition: Sampler.C:51
dof_id_type getLocalNumerOfRows()
Return the number of rows local to this processor.
Definition: Sampler.C:168
dof_id_type getLocalRowBegin()
Return the beginning local row index for this processor.
Definition: Sampler.C:179
InputParameters validParams< Sampler >()
Definition: Sampler.C:20