Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions roofit/roofitcore/inc/RooHistPdf.h
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
#include "RooDataHist.h"

#include <list>
#include <vector>

class RooRealVar;
class RooAbsReal;
Expand Down Expand Up @@ -145,6 +146,10 @@ class RooHistPdf : public RooAbsPdf {
double xlo,
double xhi);

static std::vector<double> histogramBoundariesInPlotObs(RooDataHist const &dataHist, RooArgSet const &pdfObsList,
RooArgSet const &histObsList, RooAbsRealLValue &obs,
double xlo, double xhi);

inline void initializeOwnedDataHist(std::unique_ptr<RooDataHist> &&dataHist)
{
// The constructor may already have taken ownership of a sanitized clone
Expand Down
31 changes: 23 additions & 8 deletions roofit/roofitcore/src/RooBinIntegrator.cxx
Original file line number Diff line number Diff line change
Expand Up @@ -83,18 +83,35 @@ RooBinIntegrator::RooBinIntegrator(const RooAbsFunc &function, int numBins)
for (UInt_t i=0 ; i<_function->getDimension() ; i++) {
_xmin[i]= _function->getMinLimit(i);
_xmax[i]= _function->getMaxLimit(i);
}
updateBinBoundaries(/*warnIfNoBinning=*/true);
checkLimits();

}


////////////////////////////////////////////////////////////////////////////////
/// Retrieve the bin boundaries from the integrand. They can depend on the
/// parameters, e.g. for a RooHistPdf whose observable is a shifted variable,
/// so this is done for each integral.

// Retrieve bin configuration from integrand
void RooBinIntegrator::updateBinBoundaries(bool warnIfNoBinning)
{
_binb.resize(_function->getDimension());
for (UInt_t i=0 ; i<_function->getDimension() ; i++) {
std::unique_ptr<list<double>> tmp{ _function->binBoundaries(i) };
if (!tmp) {
oocoutW(nullptr,Integration) << "RooBinIntegrator::RooBinIntegrator WARNING: integrand provide no binning definition observable #"
<< i << " substituting default binning of " << _numBins << " bins" << std::endl ;
if (warnIfNoBinning) {
oocoutW(nullptr,Integration) << "RooBinIntegrator::RooBinIntegrator WARNING: integrand provide no binning definition observable #"
<< i << " substituting default binning of " << _numBins << " bins" << std::endl ;
}
tmp = std::make_unique<list<double>>( );
for (Int_t j=0 ; j<=_numBins ; j++) {
tmp->push_back(_xmin[i]+j*(_xmax[i]-_xmin[i])/_numBins) ;
}
}
std::vector<double> binb{tmp->begin(), tmp->end()};
std::vector<double> &binb = _binb[i];
binb.assign(tmp->begin(), tmp->end());

// The bin boundaries provided by the integrand only include the boundaries
// that lie strictly inside the integration range. To integrate correctly
Expand All @@ -106,11 +123,7 @@ RooBinIntegrator::RooBinIntegrator(const RooAbsFunc &function, int numBins)
if (binb.back() < _xmax[i]) {
binb.push_back(_xmax[i]);
}
_binb.emplace_back(std::move(binb));

}
checkLimits();

}


Expand Down Expand Up @@ -177,6 +190,8 @@ double RooBinIntegrator::integral(const double *)
assert(isValid());
if (_function->getDimension() < 1) return 0.;

updateBinBoundaries(/*warnIfNoBinning=*/false);

ROOT::Math::KahanSum<double> sum;

recursive_integration(0,1.,sum);
Expand Down
1 change: 1 addition & 0 deletions roofit/roofitcore/src/RooBinIntegrator.h
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,7 @@ class RooBinIntegrator : public RooAbsIntegrator {

bool _useIntegrandLimits = false; ///< If true limits of function binding are used

void updateBinBoundaries(bool warnIfNoBinning);
void recursive_integration(const UInt_t d, const double delta, ROOT::Math::KahanSum<double>& sum);

std::vector<double> _x; ///<! do not persist, store here N-dimensional evaluation point when integrating
Expand Down
88 changes: 15 additions & 73 deletions roofit/roofitcore/src/RooHistFunc.cxx
Original file line number Diff line number Diff line change
Expand Up @@ -318,11 +318,11 @@ std::list<double>* RooHistFunc::plotSamplingHint(RooAbsRealLValue& obs, double x
return RooHistPdf::plotSamplingHint(*_dataHist, _depList, _histObsList, _intOrder, obs, xlo, xhi);
}


////////////////////////////////////////////////////////////////////////////////
/// Return sampling hint for making curves of (projections) of this function
/// as the recursive division strategy of RooCurve cannot deal efficiently
/// with the vertical lines that occur in a non-interpolated histogram
/// Return the histogram bin boundaries mapped into the plot-observable
/// coordinate. Handles the case where the function observable is a
/// transformation (shift, scale, ...) of the plot observable so that the
/// returned boundaries are placed at the correct positions in the plot.

std::list<double>* RooHistFunc::binBoundaries(RooAbsRealLValue& obs, double xlo, double xhi) const
{
Expand All @@ -331,79 +331,21 @@ std::list<double>* RooHistFunc::binBoundaries(RooAbsRealLValue& obs, double xlo,
return nullptr ;
}

// Find histogram observable corresponding to pdf observable
RooAbsArg* hobs(nullptr) ;
for (auto i = 0u; i < _histObsList.size(); ++i) {
const auto harg = _histObsList[i];
const auto parg = _depList[i];
if (std::string(parg->GetName())==obs.GetName()) {
hobs=harg ;
}
const std::vector<double> boundaries =
RooHistPdf::histogramBoundariesInPlotObs(*_dataHist, _depList, _histObsList, obs, xlo, xhi);
if (boundaries.empty()) {
return nullptr;
}

RooAbsRealLValue* transform = nullptr;
if (!hobs) {

// Considering alternate: input observable is histogram observable and pdf observable is transformation in terms of it
RooAbsArg* pobs = nullptr;
for (auto i = 0u; i < _histObsList.size(); ++i) {
const auto harg = _histObsList[i];
const auto parg = _depList[i];
if (std::string(harg->GetName())==obs.GetName()) {
pobs=parg ;
hobs=harg ;
}
}

// Not found, or check that matching pdf observable is an l-value dependent on histogram observable fails
if (!hobs || !(pobs->dependsOn(obs) && dynamic_cast<RooAbsRealLValue*>(pobs))) {
std::cout << "RooHistFunc::binBoundaries(" << GetName() << ") obs = " << obs.GetName() << " hobs is not found, returning null" << std::endl ;
return nullptr ;
}

// Now we are in business - we are in a situation where the pdf observable LV(x), mapping to a histogram observable x
// We can return bin boundaries by mapping the histogram boundaties through the inverse of the LV(x) transformation
transform = dynamic_cast<RooAbsRealLValue*>(pobs) ;
}


// Check that observable is in dataset, if not no hint is generated
RooAbsArg* xtmp = _dataHist->get()->find(hobs->GetName()) ;
if (!xtmp) {
std::cout << "RooHistFunc::binBoundaries(" << GetName() << ") hobs = " << hobs->GetName() << " is not found in dataset?" << std::endl ;
_dataHist->get()->Print("v") ;
return nullptr ;
}
RooAbsLValue* lvarg = dynamic_cast<RooAbsLValue*>(_dataHist->get()->find(hobs->GetName())) ;
if (!lvarg) {
std::cout << "RooHistFunc::binBoundaries(" << GetName() << ") hobs = " << hobs->GetName() << " but is not an LV, returning null" << std::endl ;
return nullptr ;
}

// Retrieve position of all bin boundaries
const RooAbsBinning* binning = lvarg->getBinningPtr(nullptr);
double* boundaries = binning->array() ;

auto hint = new std::list<double> ;

double delta = (xhi-xlo)*1e-8 ;

// Construct array with pairs of points positioned epsilon to the left and
// right of the bin boundaries
for (Int_t i=0 ; i<binning->numBoundaries() ; i++) {
if (boundaries[i]>xlo-delta && boundaries[i]<xhi+delta) {

double boundary = boundaries[i] ;
if (transform) {
transform->setVal(boundary) ;
hint->push_back(obs.getVal()) ;
} else {
hint->push_back(boundary) ;
}
}
auto hint = new std::list<double>;
const double delta = (xhi - xlo) * 1e-8;
for (double b : boundaries) {
if (b > xlo - delta && b < xhi + delta) {
hint->push_back(b);
}
}

return hint ;
return hint;
}


Expand Down
172 changes: 121 additions & 51 deletions roofit/roofitcore/src/RooHistPdf.cxx
Original file line number Diff line number Diff line change
Expand Up @@ -471,6 +471,112 @@ bool RooHistPdf::forceAnalyticalInt(const RooAbsArg& dep) const
return forceAnalyticalInt(_pdfObsList, dep);
}

////////////////////////////////////////////////////////////////////////////////
/// Return the histogram bin boundaries mapped to the coordinates of the plot
/// observable `obs`. This handles the case where the p.d.f. observable is a
/// transformation of the plot observable (for example a shift like
/// `x_shifted = x - shift`), so that the returned boundaries are the positions
/// of the histogram bin edges as they appear when the p.d.f. is plotted as a
/// function of `obs`.
///
/// Returns an empty vector if no corresponding histogram observable can be
/// located, or if a non-invertible transformation is detected.

std::vector<double> RooHistPdf::histogramBoundariesInPlotObs(RooDataHist const &dataHist, RooArgSet const &pdfObsList,
RooArgSet const &histObsList, RooAbsRealLValue &obs,
double xlo, double xhi)
{
std::vector<double> result;

// The histogram observable for `obs` belongs to the p.d.f. observable with
// the same name, or else to the first one that is a function of `obs`.
RooAbsArg *histObs = nullptr;
RooAbsArg *pdfObs = nullptr;
bool useTransform = false;
for (unsigned int i = 0; i < pdfObsList.size(); ++i) {
if (std::string(obs.GetName()) == pdfObsList[i]->GetName()) {
histObs = histObsList[i];
break;
}
}
if (!histObs) {
for (unsigned int i = 0; i < pdfObsList.size(); ++i) {
auto *po = dynamic_cast<RooAbsReal *>(pdfObsList[i]);
if (po && po->dependsOn(obs)) {
histObs = histObsList[i];
pdfObs = pdfObsList[i];
useTransform = true;
break;
}
}
}
if (!histObs) {
return result;
}

auto *lval = dynamic_cast<RooAbsLValue *>(dataHist.get()->find(histObs->GetName()));
if (!lval) {
return result;
}

const RooAbsBinning *binning = lval->getBinningPtr(nullptr);
const int nBoundaries = binning->numBoundaries();
const double *rawBoundaries = binning->array();

if (!useTransform) {
result.assign(rawBoundaries, rawBoundaries + nBoundaries);
return result;
}

// Invert `pdfObs = T(obs)` with a linear approximation of `T` on the plot
// range, which is exact for linear transformations. Inverting with the
// setVal() of an l-value like RooLinearVar would throw for boundaries that
// map outside the range of `obs`.
auto *pdfObsReal = static_cast<RooAbsReal *>(pdfObs);
const double probeLo = std::max(xlo, obs.getMin());
const double probeHi = std::min(xhi, obs.getMax());
if (probeHi > probeLo) {
// Restore `obs` with assign(), because setVal() throws if an outer
// integral has set it outside of its default range.
RooArgSet obsLeaves;
obs.leafNodeServerList(&obsLeaves);
RooArgSet obsSaved;
obsLeaves.snapshot(obsSaved, false);
auto evalAt = [&](double val) {
obs.setVal(val);
return pdfObsReal->getVal();
};
const double probeMid = 0.5 * (probeLo + probeHi);
const double plo = evalAt(probeLo);
const double phi = evalAt(probeHi);
const double pmid = evalAt(probeMid);
obsLeaves.assign(obsSaved);
const double slope = (phi - plo) / (probeHi - probeLo);

// The midpoint reveals non-linear transformations.
const double pmidLinear = plo + slope * (probeMid - probeLo);
const double scale = std::max(std::abs(plo), std::abs(phi));
if (std::abs(pmid - pmidLinear) > 1e-7 * (scale > 0.0 ? scale : 1.0)) {
oocoutW(nullptr, Plotting)
<< "RooHistPdf::histogramBoundariesInPlotObs: the histogram observable '" << pdfObsReal->GetName()
<< "' appears to be a non-linear transformation of the plot observable '" << obs.GetName()
<< "'. The bin boundaries used for plotting and integration are approximated assuming a linear "
"relation and may be placed incorrectly."
<< std::endl;
}

if (slope != 0.0) {
result.reserve(nBoundaries);
for (int i = 0; i < nBoundaries; ++i) {
result.push_back(probeLo + (rawBoundaries[i] - plo) / slope);
}
}
}

// The transformation may reverse the order (negative slope).
std::sort(result.begin(), result.end());
return result;
}

////////////////////////////////////////////////////////////////////////////////
/// Return sampling hint for making curves of (projections) of this function
Expand All @@ -496,40 +602,19 @@ std::list<double>* RooHistPdf::plotSamplingHint(RooDataHist const& dataHist,
return nullptr;
}

// Check that observable is in dataset, if not no hint is generated
RooAbsArg* dhObs = nullptr;
for (unsigned int i=0; i < pdfObsList.size(); ++i) {
RooAbsArg* histObs = histObsList[i];
RooAbsArg* pdfObs = pdfObsList[i];
if (std::string(obs.GetName())==pdfObs->GetName()) {
dhObs = dataHist.get()->find(histObs->GetName()) ;
break;
}
const std::vector<double> boundaries = histogramBoundariesInPlotObs(dataHist, pdfObsList, histObsList, obs, xlo, xhi);
if (boundaries.empty()) {
return nullptr;
}

if (!dhObs) {
return nullptr;
}
RooAbsLValue* lval = dynamic_cast<RooAbsLValue*>(dhObs) ;
if (!lval) {
return nullptr;
}

// Retrieve position of all bin boundaries

const RooAbsBinning* binning = lval->getBinningPtr(nullptr);
std::span<const double> boundaries{binning->array(), static_cast<std::size_t>(binning->numBoundaries())};

// Use the helper function from RooCurve to make sure to get sampling hints
// that work with the RooFitPlotting.
return RooCurve::plotSamplingHintForBinBoundaries(boundaries, xlo, xhi);
}


////////////////////////////////////////////////////////////////////////////////
/// Return sampling hint for making curves of (projections) of this function
/// as the recursive division strategy of RooCurve cannot deal efficiently
/// with the vertical lines that occur in a non-interpolated histogram
/// Return the histogram bin boundaries in the plot-observable coordinate,
/// used for example by the RooBinIntegrator and the binned likelihood.

std::list<double>* RooHistPdf::binBoundaries(RooAbsRealLValue& obs, double xlo, double xhi) const
{
Expand All @@ -538,35 +623,20 @@ std::list<double>* RooHistPdf::binBoundaries(RooAbsRealLValue& obs, double xlo,
return nullptr;
}

// Check that observable is in dataset, if not no hint is generated. The pdf
// observable can be named differently, e.g. when it was prefixed for a
// RooSimultaneous channel in the likelihood.
RooAbsArg *dhObs = _dataHist->get()->find(obs.GetName());
for (unsigned int i = 0; !dhObs && i < _pdfObsList.size(); ++i) {
if (std::string(obs.GetName()) == _pdfObsList[i]->GetName()) {
dhObs = _dataHist->get()->find(_histObsList[i]->GetName());
}
}
RooAbsLValue *lvarg = dynamic_cast<RooAbsLValue *>(dhObs);
if (!lvarg) {
return nullptr ;
const std::vector<double> boundaries =
histogramBoundariesInPlotObs(*_dataHist, _pdfObsList, _histObsList, obs, xlo, xhi);
if (boundaries.empty()) {
return nullptr;
}

// Retrieve position of all bin boundaries
const RooAbsBinning* binning = lvarg->getBinningPtr(nullptr);
double* boundaries = binning->array() ;

auto hint = new std::list<double> ;

// Construct array with pairs of points positioned epsilon to the left and
// right of the bin boundaries
for (Int_t i=0 ; i<binning->numBoundaries() ; i++) {
if (boundaries[i]>=xlo && boundaries[i]<=xhi) {
hint->push_back(boundaries[i]) ;
}
auto hint = new std::list<double>;
for (double b : boundaries) {
if (b >= xlo && b <= xhi) {
hint->push_back(b);
}
}

return hint ;
return hint;
}


Expand Down
Loading
Loading