GooFit  v2.1.3
MonteCarlo.h
Go to the documentation of this file.
1 #pragma once
2 
3 #include <goofit/PDFs/GooPdf.h>
5 #include <goofit/Variable.h>
6 
7 #include <algorithm>
8 #include <numeric>
9 #include <random>
10 
11 namespace GooFit {
12 
13 inline void fillDataSetMC1D(GooPdf &pdf, Observable var, size_t nTotal, unsigned int seed = 0) {
14  // Setup bins
15  UnbinnedDataSet data{var};
17  auto origdata = pdf.getData();
18 
19  if(origdata == nullptr)
20  throw GeneralError("Can't run on a PDF with no DataSet to fill!");
21 
22  pdf.setData(&data);
23  std::vector<double> pdfValues = pdf.getCompProbsAtDataPoints()[0];
24 
25  // Setup random numbers
26  if(seed == 0) {
27  std::random_device rd;
28  seed = rd();
29  }
30  std::mt19937 gen(seed);
31 
32  // Poisson distribution
33  std::poisson_distribution<> d(nTotal);
34  size_t num_events = d(gen);
35 
36  // Uniform distribution
37  std::uniform_real_distribution<> unihalf(-.5, .5);
38  std::uniform_real_distribution<> uniwhole(0.0, 1.0);
39 
40  // CumSum in other languages
41  std::vector<double> integral(pdfValues.size());
42  std::partial_sum(pdfValues.begin(), pdfValues.end(), integral.begin());
43 
44  // Make this a 0-1 fraction by dividing by the end value
45  std::for_each(integral.begin(), integral.end(), [&integral](double &val) { val /= integral.back(); });
46 
47  for(size_t i = 0; i < num_events; i++) {
48  double r = uniwhole(gen);
49 
50  // Binary search for integral[cell-1] < r < integral[cell]
51  size_t j = std::lower_bound(integral.begin(), integral.end(), r) - integral.begin();
52 
53  // Fill in the grid randomly
54  double varValue = data.getValue(var, j) + var.getBinSize() * unihalf(gen);
55 
56  var.setValue(varValue);
57  origdata->addEvent();
58  }
59 
60  pdf.setData(origdata);
61 }
62 
63 } // namespace GooFit
Thrown when a general error is encountered.
Definition: Error.h:10
fptype getBinSize() const
Get the bin size, (upper-lower) / bins.
Definition: Variable.h:133
__host__ DataSet * getData()
void fillWithGrid()
Replace the current dataset with a grid.
__host__ std::vector< std::vector< fptype > > getCompProbsAtDataPoints()
Produce a list of probabilies at points.
void setValue(fptype val)
Set the value.
Definition: Variable.h:70
Special class for observables. Used in DataSets.
Definition: Variable.h:109
fptype getValue(const Observable &var, size_t idx) const
Get the value at a specific variable and event number.
UnbinnedDataSet * data
__host__ void setData(DataSet *data)
void fillDataSetMC1D(GooPdf &pdf, Observable var, size_t nTotal, unsigned int seed=0)
Definition: MonteCarlo.h:13