Logo ROOT  
Reference Guide
 
Loading...
Searching...
No Matches
RooHistPdf.cxx
Go to the documentation of this file.
1/*****************************************************************************
2 * Project: RooFit *
3 * Package: RooFitCore *
4 * @(#)root/roofit:$Id$
5 * Authors: *
6 * WV, Wouter Verkerke, UC Santa Barbara, verkerke@slac.stanford.edu *
7 * DK, David Kirkby, UC Irvine, dkirkby@uci.edu *
8 * *
9 * Copyright (c) 2000-2005, Regents of the University of California *
10 * and Stanford University. All rights reserved. *
11 * *
12 * Redistribution and use in source and binary forms, *
13 * with or without modification, are permitted according to the terms *
14 * listed in LICENSE (http://roofit.sourceforge.net/license.txt) *
15 *****************************************************************************/
16
17/**
18\file RooHistPdf.cxx
19\class RooHistPdf
20\ingroup Roofitcore
21
22A probability density function sampled from a
23multidimensional histogram. The histogram distribution is explicitly
24normalized by RooHistPdf and can have an arbitrary number of real or
25discrete dimensions.
26
27A p.d.f. cannot be negative. If the input histogram contains bins with
28negative content, the bin contents are clipped to zero and the bin errors are kept the same.
29The input histogram is not modified.
30**/
31
32#include "RooCategory.h"
33#include "RooCurve.h"
34#include "RooDataHist.h"
35#include "RooFitImplHelpers.h"
36#include "RooGlobalFunc.h"
37#include "RooHistPdf.h"
38#include "RooMsgService.h"
39#include "RooRealVar.h"
40#include "RooWorkspace.h"
41
42#include "TError.h"
43#include "TBuffer.h"
44
45#include <algorithm>
46#include <cmath>
47#include <ostream>
48
49////////////////////////////////////////////////////////////////////////////////
50/// Constructor from a RooDataHist. RooDataHist dimensions
51/// can be either real or discrete. See RooDataHist::RooDataHist for details on the binning.
52/// RooHistPdf neither owns or clone 'dhist' and the user must ensure the input histogram exists
53/// for the entire life span of this PDF.
54/// The only exception is a 'dhist' that contains bins with negative content: those are set to
55/// zero in an internally-owned clone that is used instead (see clampNegativeBins()).
56
57RooHistPdf::RooHistPdf(const char *name, const char *title, const RooArgSet& vars,
58 const RooDataHist& dhist, Int_t intOrder) :
59 RooAbsPdf(name,title),
60 _pdfObsList("pdfObs","List of p.d.f. observables",this),
61 _dataHist(const_cast<RooDataHist*>(&dhist)),
62 _intOrder(intOrder)
63{
65 _pdfObsList.add(vars) ;
66
67 // Verify that vars and dhist.get() have identical contents
68 const RooArgSet* dvars = dhist.get() ;
69 if (vars.size()!=dvars->size()) {
70 coutE(InputArguments) << "RooHistPdf::ctor(" << GetName()
71 << ") ERROR variable list and RooDataHist must contain the same variables." << std::endl ;
72 assert(0) ;
73 }
74 for (const auto arg : vars) {
75 if (!dvars->find(arg->GetName())) {
76 coutE(InputArguments) << "RooHistPdf::ctor(" << GetName()
77 << ") ERROR variable list and RooDataHist must contain the same variables." << std::endl ;
78 assert(0) ;
79 }
80 }
81
82
83 // Adjust ranges of _histObsList to those of _dataHist
84 for (const auto hobs : _histObsList) {
85 // Guaranteed to succeed, since checked above in constructor
86 RooAbsArg* dhobs = dhist.get()->find(hobs->GetName()) ;
87 RooRealVar* dhreal = dynamic_cast<RooRealVar*>(dhobs) ;
88 if (dhreal){
89 (static_cast<RooRealVar*>(hobs))->setRange(dhreal->getMin(),dhreal->getMax()) ;
90 }
91 }
92
94}
95
96
97
98
99////////////////////////////////////////////////////////////////////////////////
100/// Constructor from a RooDataHist. The first list of observables are the p.d.f.
101/// observables, which may any RooAbsReal (function or variable). The second list
102/// are the corresponding observables in the RooDataHist which must be of type
103/// RooRealVar or RooCategory This constructor thus allows to apply a coordinate transformation
104/// on the histogram data to be applied.
105
106RooHistPdf::RooHistPdf(const char *name, const char *title, const RooArgList& pdfObs,
107 const RooArgList& histObs, const RooDataHist& dhist, Int_t intOrder) :
108 RooAbsPdf(name,title),
109 _pdfObsList("pdfObs","List of p.d.f. observables",this),
110 _dataHist(const_cast<RooDataHist*>(&dhist)),
111 _intOrder(intOrder)
112{
113 _histObsList.addClone(histObs) ;
114 _pdfObsList.add(pdfObs) ;
115
116 // Verify that vars and dhist.get() have identical contents
117 const RooArgSet* dvars = dhist.get() ;
118 if (histObs.size()!=dvars->size()) {
119 coutE(InputArguments) << "RooHistPdf::ctor(" << GetName()
120 << ") ERROR histogram variable list and RooDataHist must contain the same variables." << std::endl ;
121 throw(std::string("RooHistPdf::ctor() ERROR: histogram variable list and RooDataHist must contain the same variables")) ;
122 }
123
124 for (const auto arg : histObs) {
125 if (!dvars->find(arg->GetName())) {
126 coutE(InputArguments) << "RooHistPdf::ctor(" << GetName()
127 << ") ERROR variable list and RooDataHist must contain the same variables." << std::endl ;
128 throw(std::string("RooHistPdf::ctor() ERROR: histogram variable list and RooDataHist must contain the same variables")) ;
129 }
130 if (!arg->isFundamental()) {
131 coutE(InputArguments) << "RooHistPdf::ctor(" << GetName()
132 << ") ERROR all elements of histogram observables set must be of type RooRealVar or RooCategory." << std::endl ;
133 throw(std::string("RooHistPdf::ctor() ERROR all elements of histogram observables set must be of type RooRealVar or RooCategory.")) ;
134 }
135 }
136
137
138 // Adjust ranges of _histObsList to those of _dataHist
139 for (const auto hobs : _histObsList) {
140 // Guaranteed to succeed, since checked above in constructor
141 RooAbsArg* dhobs = dhist.get()->find(hobs->GetName()) ;
142 RooRealVar* dhreal = dynamic_cast<RooRealVar*>(dhobs) ;
143 if (dhreal){
144 (static_cast<RooRealVar*>(hobs))->setRange(dhreal->getMin(),dhreal->getMax()) ;
145 }
146 }
147
149}
150
151RooHistPdf::RooHistPdf(const char *name, const char *title, const RooArgSet &vars, std::unique_ptr<RooDataHist> dhist,
152 int intOrder)
153 : RooHistPdf{name, title, vars, *dhist, intOrder}
154{
155 initializeOwnedDataHist(std::move(dhist));
156}
157RooHistPdf::RooHistPdf(const char *name, const char *title, const RooArgList &pdfObs, const RooArgList &histObs,
158 std::unique_ptr<RooDataHist> dhist, int intOrder)
159 : RooHistPdf{name, title, pdfObs, histObs, *dhist, intOrder}
160{
161 initializeOwnedDataHist(std::move(dhist));
162}
163
164
165////////////////////////////////////////////////////////////////////////////////
166/// Copy constructor
167
168RooHistPdf::RooHistPdf(const RooHistPdf& other, const char* name) :
169 RooAbsPdf(other,name),
170 _pdfObsList("pdfObs",this,other._pdfObsList),
171 _dataHist(other._dataHist),
172 _intOrder(other._intOrder),
173 _cdfBoundaries(other._cdfBoundaries),
174 _totVolume(other._totVolume),
175 _unitNorm(other._unitNorm)
176{
178}
179
181 if (_ownedDataHist) return _ownedDataHist.get();
182 _ownedDataHist.reset(static_cast<RooDataHist*>(_dataHist->Clone(newname)));
184 return _dataHist;
185}
186
188{
189 const std::size_t nBins = _dataHist->numEntries();
190
191 std::size_t nNegative = 0;
192 double sumNegative = 0.;
193 for (std::size_t i = 0; i < nBins; ++i) {
194 if (_dataHist->weight(i) < 0.) {
195 ++nNegative;
196 sumNegative += _dataHist->weight(i);
197 }
198 }
199 if (nNegative == 0) {
200 return;
201 }
202
203 coutW(InputArguments) << "RooHistPdf::ctor(" << GetName() << ") WARNING: input histogram \"" << _dataHist->GetName()
204 << "\" contains " << nNegative
205 << " bins with negative content (sum of negative contents: " << sumNegative
206 << "). A p.d.f. cannot be negative, so these bins contents are clipped to zero while "
207 "preserving the error. The input "
208 "histogram is not modified. To avoid this message, remove the negative bin contents "
209 "before constructing the RooHistPdf."
210 << std::endl;
211
213 const bool hasSumW2 = dh->sumW2Array() != nullptr;
214 for (std::size_t i = 0; i < nBins; ++i) {
215 if (dh->weight(i) < 0.) {
216 // Keep the original bin error: clamping the content is a
217 // normalization-consistency measure, not a statement that the bin is
218 // now known exactly. The error still quantifies the statistical
219 // uncertainty of the original bin content estimate (e.g. whether the
220 // negative content is compatible with a fluctuation around zero),
221 // and setting it to zero would introduce undercoverage, which is
222 // always undesired. It would also irreversibly discard information
223 // for anyone retrieving the histogram via dataHist(), including any
224 // future per-bin MC-stat treatment, where a zero error would wrongly
225 // fix the bin at exactly zero.
226 const double wgtErr = hasSumW2 ? std::sqrt(std::max(dh->weightSquared(i), 0.)) : 0.;
227 dh->set(i, 0., wgtErr);
228 }
229 }
230}
231
233{
234 std::span<double> output = ctx.output();
235
236 // For interpolation and histograms of higher dimension, use base function
237 if (_pdfObsList.size() > 1) {
239 return;
240 }
241
242 auto xVals = ctx.at(_pdfObsList[0]);
243 _dataHist->weights(output.data(), xVals, _intOrder, true, _cdfBoundaries);
244 for (auto &ret : output) {
245 ret = std::max(ret, 0.0);
246 }
247}
248
249
250////////////////////////////////////////////////////////////////////////////////
251/// Return the current value: The value of the bin enclosing the current coordinates
252/// of the observables, normalized by the histograms contents. Interpolation
253/// is applied if the RooHistPdf is configured to do that.
254
256{
257 // Transfer values from
258 for (unsigned int i=0; i < _pdfObsList.size(); ++i) {
259 RooAbsArg* harg = _histObsList[i];
260 RooAbsArg* parg = _pdfObsList[i];
261
262 if (harg != parg) {
263 parg->syncCache() ;
264 harg->copyCache(parg,true) ;
265 if (!harg->inRange(nullptr)) {
266 return 0 ;
267 }
268 }
269 }
270
272
273 return std::max(ret, 0.0);
274}
275
276////////////////////////////////////////////////////////////////////////////////
277/// Return the total volume spanned by the observables of the RooHistPdf
278
280{
281 // Return previously calculated value, if any
282 if (_totVolume>0) {
283 return _totVolume ;
284 }
285 _totVolume = 1. ;
286
287 for (const auto arg : _histObsList) {
288 RooRealVar* real = dynamic_cast<RooRealVar*>(arg) ;
289 if (real) {
290 _totVolume *= (real->getMax()-real->getMin()) ;
291 } else {
292 RooCategory* cat = dynamic_cast<RooCategory*>(arg) ;
293 if (cat) {
294 _totVolume *= cat->numTypes() ;
295 }
296 }
297 }
298
299 return _totVolume ;
300}
301
302namespace {
303
304bool fullRange(const RooAbsArg& x, const RooAbsArg& y ,const char* range)
305{
306 const RooAbsRealLValue *_x = dynamic_cast<const RooAbsRealLValue*>(&x);
307 const RooAbsRealLValue *_y = dynamic_cast<const RooAbsRealLValue*>(&y);
308 if (!_x || !_y) return false;
309 if (!range || !strlen(range) || !_x->hasRange(range) ||
310 _x->getBinningPtr(range)->isParameterized()) {
311 // parameterized ranges may be full range now, but that might change,
312 // so return false
313 if (range && strlen(range) && _x->getBinningPtr(range)->isParameterized())
314 return false;
315 return (_x->getMin() == _y->getMin() && _x->getMax() == _y->getMax());
316 }
317 return (_x->getMin(range) == _y->getMin() && _x->getMax(range) == _y->getMax());
318}
319
320bool okayForAnalytical(RooAbsArg const& obs, RooArgSet const& allVars)
321{
322 auto lobs = dynamic_cast<RooAbsRealLValue const*>(&obs);
323 if(lobs == nullptr) return false;
324
325 bool isOkayForAnalyticalInt = false;
326
327 for(RooAbsArg *var : allVars) {
328 if(obs.dependsOn(*var)) {
329 if(!lobs->isJacobianOK(*var)) return false;
330 isOkayForAnalyticalInt = true;
331 }
332 }
333
334 return isOkayForAnalyticalInt;
335}
336
337} // namespace
338
339
341 RooArgSet& analVars,
342 const char* rangeName,
343 RooArgSet const& histObsList,
344 RooArgSet const& pdfObsList,
345 Int_t intOrder)
346{
347 // First make list of pdf observables to histogram observables
348 // and select only those for which the integral is over the full range
349
350 Int_t code = 0;
351 Int_t frcode = 0;
352 bool directSubRange = false;
353 for (unsigned int n=0; n < pdfObsList.size() && n < histObsList.size(); ++n) {
354 const auto pa = pdfObsList[n];
355 const auto ha = histObsList[n];
356
357 if (okayForAnalytical(*pa, allVars)) {
358 code |= 2 << n;
359 analVars.add(*pa);
360 if (fullRange(*pa, *ha, rangeName)) {
361 frcode |= 2 << n;
362 } else if (pa->isFundamental()) {
363 // Sub-range integral over the histogram observable itself (no transform).
364 directSubRange = true;
365 }
366 }
367 }
368
369 if (code == frcode) {
370 // integrate over full range of all observables - use bit 0 to indicate
371 // full range integration over all observables
372 code |= 1;
373 }
374
375 // the full range. For interpolated histograms (intOrder > 0), fall back to
376 // numerical integration over a direct sub-range of the histogram observable.
377 // A derived (non-fundamental) observable, such as a linear transform used to
378 // renormalize the components of a RooMomentMorphFuncND, keeps the analytical
379 // path it relies on.
380 if (intOrder > 0 && directSubRange) {
381 analVars.removeAll();
382 return 0;
383 }
384 return (code >= 2) ? code : 0;
385}
386
387
389 const char* rangeName,
390 RooArgSet const& histObsList,
391 RooArgSet const& pdfObsList,
392 RooDataHist& dataHist,
393 bool histFuncMode) {
394 // Simplest scenario, full-range integration over all dependents
395 if (((2 << histObsList.size()) - 1) == code) {
396 return dataHist.sum(histFuncMode);
397 }
398
399 // Partial integration scenario, retrieve set of variables, calculate partial
400 // sum, figure out integration ranges (if needed)
401 RooArgSet intSet;
402 std::map<const RooAbsArg*, std::pair<double, double> > ranges;
403 for (unsigned int n=0; n < pdfObsList.size() && n < histObsList.size(); ++n) {
404 const auto pa = pdfObsList[n];
405 const auto ha = histObsList[n];
406
407 if (code & (2 << n)) {
408 intSet.add(*ha);
409 }
410 if (!(code & 1)) {
411 ranges[ha] = RooHelpers::getRangeOrBinningInterval(pa, rangeName);
412 }
413 // WVE must sync hist slice list values to pdf slice list
414 // Transfer values from
415 if (ha != pa) {
416 pa->syncCache();
417 ha->copyCache(pa,true);
418 }
419 }
420
421 double ret = (code & 1) ? dataHist.sum(intSet,histObsList,true,!histFuncMode) :
422 dataHist.sum(intSet,histObsList,true,!histFuncMode, ranges);
423
424 return ret ;
425}
426
427////////////////////////////////////////////////////////////////////////////////
428/// Determine integration scenario. If no interpolation is used,
429/// RooHistPdf can perform all integrals over its dependents
430/// analytically via partial or complete summation of the input
431/// histogram. If interpolation is used on the integral over
432/// all histogram observables is supported
433
434Int_t RooHistPdf::getAnalyticalIntegral(RooArgSet& allVars, RooArgSet& analVars, const char* rangeName) const
435{
436 return getAnalyticalIntegral(allVars, analVars, rangeName, _histObsList, _pdfObsList, _intOrder);
437}
438
439
440////////////////////////////////////////////////////////////////////////////////
441/// Return integral identified by 'code'. The actual integration
442/// is deferred to RooDataHist::sum() which implements partial
443/// or complete summation over the histograms contents.
444
445double RooHistPdf::analyticalIntegral(Int_t code, const char* rangeName) const
446{
447 return analyticalIntegral(code, rangeName, _histObsList, _pdfObsList, *_dataHist, false);
448}
449
450
451bool RooHistPdf::forceAnalyticalInt(RooArgSet const& pdfObsList, const RooAbsArg& dep)
452{
453 bool isOkayForAnalyticalInt = false;
454
455 for (RooAbsArg * obs : pdfObsList) {
456 if(obs->dependsOn(dep)) {
457 // If the observable doesn't depend linearly on the integration
458 // variable we will not do analytical integration.
459 auto lvalue = dynamic_cast<RooAbsRealLValue const*>(obs);
460 if(!(lvalue && lvalue->isJacobianOK(dep))) return false;
461 isOkayForAnalyticalInt = true;
462 }
463 }
464
465 return isOkayForAnalyticalInt;
466}
467
468
470{
471 return forceAnalyticalInt(_pdfObsList, dep);
472}
473
474////////////////////////////////////////////////////////////////////////////////
475/// Return the histogram bin boundaries mapped to the coordinates of the plot
476/// observable `obs`. This handles the case where the p.d.f. observable is a
477/// transformation of the plot observable (for example a shift like
478/// `x_shifted = x - shift`), so that the returned boundaries are the positions
479/// of the histogram bin edges as they appear when the p.d.f. is plotted as a
480/// function of `obs`.
481///
482/// Returns an empty vector if no corresponding histogram observable can be
483/// located, or if a non-invertible transformation is detected.
484
485std::vector<double> RooHistPdf::histogramBoundariesInPlotObs(RooDataHist const &dataHist, RooArgSet const &pdfObsList,
486 RooArgSet const &histObsList, RooAbsRealLValue &obs,
487 double xlo, double xhi)
488{
489 std::vector<double> result;
490
491 // The histogram observable for `obs` belongs to the p.d.f. observable with
492 // the same name, or else to the first one that is a function of `obs`.
493 RooAbsArg *histObs = nullptr;
494 RooAbsArg *pdfObs = nullptr;
495 bool useTransform = false;
496 for (unsigned int i = 0; i < pdfObsList.size(); ++i) {
497 if (std::string(obs.GetName()) == pdfObsList[i]->GetName()) {
498 histObs = histObsList[i];
499 break;
500 }
501 }
502 if (!histObs) {
503 for (unsigned int i = 0; i < pdfObsList.size(); ++i) {
504 auto *po = dynamic_cast<RooAbsReal *>(pdfObsList[i]);
505 if (po && po->dependsOn(obs)) {
506 histObs = histObsList[i];
507 pdfObs = pdfObsList[i];
508 useTransform = true;
509 break;
510 }
511 }
512 }
513 if (!histObs) {
514 return result;
515 }
516
517 auto *lval = dynamic_cast<RooAbsLValue *>(dataHist.get()->find(histObs->GetName()));
518 if (!lval) {
519 return result;
520 }
521
522 const RooAbsBinning *binning = lval->getBinningPtr(nullptr);
523 const int nBoundaries = binning->numBoundaries();
524 const double *rawBoundaries = binning->array();
525
526 if (!useTransform) {
527 result.assign(rawBoundaries, rawBoundaries + nBoundaries);
528 return result;
529 }
530
531 // Invert `pdfObs = T(obs)` with a linear approximation of `T` on the plot
532 // range, which is exact for linear transformations. Inverting with the
533 // setVal() of an l-value like RooLinearVar would throw for boundaries that
534 // map outside the range of `obs`.
535 auto *pdfObsReal = static_cast<RooAbsReal *>(pdfObs);
536 const double probeLo = std::max(xlo, obs.getMin());
537 const double probeHi = std::min(xhi, obs.getMax());
538 if (probeHi > probeLo) {
539 // Restore `obs` with assign(), because setVal() throws if an outer
540 // integral has set it outside of its default range.
541 RooArgSet obsLeaves;
542 obs.leafNodeServerList(&obsLeaves);
543 RooArgSet obsSaved;
544 obsLeaves.snapshot(obsSaved, false);
545 auto evalAt = [&](double val) {
546 obs.setVal(val);
547 return pdfObsReal->getVal();
548 };
549 const double probeMid = 0.5 * (probeLo + probeHi);
550 const double plo = evalAt(probeLo);
551 const double phi = evalAt(probeHi);
552 const double pmid = evalAt(probeMid);
553 obsLeaves.assign(obsSaved);
554 const double slope = (phi - plo) / (probeHi - probeLo);
555
556 // The midpoint reveals non-linear transformations.
557 const double pmidLinear = plo + slope * (probeMid - probeLo);
558 const double scale = std::max(std::abs(plo), std::abs(phi));
559 if (std::abs(pmid - pmidLinear) > 1e-7 * (scale > 0.0 ? scale : 1.0)) {
560 oocoutW(nullptr, Plotting)
561 << "RooHistPdf::histogramBoundariesInPlotObs: the histogram observable '" << pdfObsReal->GetName()
562 << "' appears to be a non-linear transformation of the plot observable '" << obs.GetName()
563 << "'. The bin boundaries used for plotting and integration are approximated assuming a linear "
564 "relation and may be placed incorrectly."
565 << std::endl;
566 }
567
568 if (slope != 0.0) {
569 result.reserve(nBoundaries);
570 for (int i = 0; i < nBoundaries; ++i) {
571 result.push_back(probeLo + (rawBoundaries[i] - plo) / slope);
572 }
573 }
574 }
575
576 // The transformation may reverse the order (negative slope).
577 std::sort(result.begin(), result.end());
578 return result;
579}
580
581////////////////////////////////////////////////////////////////////////////////
582/// Return sampling hint for making curves of (projections) of this function
583/// as the recursive division strategy of RooCurve cannot deal efficiently
584/// with the vertical lines that occur in a non-interpolated histogram
585
586std::list<double>* RooHistPdf::plotSamplingHint(RooAbsRealLValue& obs, double xlo, double xhi) const
587{
589}
590
591
592std::list<double>* RooHistPdf::plotSamplingHint(RooDataHist const& dataHist,
593 RooArgSet const& pdfObsList,
594 RooArgSet const& histObsList,
595 int intOrder,
596 RooAbsRealLValue& obs,
597 double xlo,
598 double xhi)
599{
600 // No hints are required when interpolation is used
601 if (intOrder>0) {
602 return nullptr;
603 }
604
605 const std::vector<double> boundaries = histogramBoundariesInPlotObs(dataHist, pdfObsList, histObsList, obs, xlo, xhi);
606 if (boundaries.empty()) {
607 return nullptr;
608 }
609
610 // Use the helper function from RooCurve to make sure to get sampling hints
611 // that work with the RooFitPlotting.
612 return RooCurve::plotSamplingHintForBinBoundaries(boundaries, xlo, xhi);
613}
614
615////////////////////////////////////////////////////////////////////////////////
616/// Return the histogram bin boundaries in the plot-observable coordinate,
617/// used for example by the RooBinIntegrator and the binned likelihood.
618
619std::list<double>* RooHistPdf::binBoundaries(RooAbsRealLValue& obs, double xlo, double xhi) const
620{
621 // No hints are required when interpolation is used
622 if (_intOrder>0) {
623 return nullptr;
624 }
625
626 const std::vector<double> boundaries =
628 if (boundaries.empty()) {
629 return nullptr;
630 }
631
632 auto hint = new std::list<double>;
633 for (double b : boundaries) {
634 if (b >= xlo && b <= xhi) {
635 hint->push_back(b);
636 }
637 }
638
639 return hint;
640}
641
642
643
644
645////////////////////////////////////////////////////////////////////////////////
646/// Only handle case of maximum in all variables
647
649{
650 std::unique_ptr<RooAbsCollection> common{_pdfObsList.selectCommon(vars)};
651 if (common->size()==_pdfObsList.size()) {
652 return 1;
653 }
654 return 0 ;
655}
656
657
658////////////////////////////////////////////////////////////////////////////////
659
660double RooHistPdf::maxVal(Int_t code) const
661{
662 R__ASSERT(code==1) ;
663
664 double max(-1) ;
665 for (Int_t i=0 ; i<_dataHist->numEntries() ; i++) {
666 double wgt = _dataHist->weight(i) ;
667 if (wgt>max) max=wgt ;
668 }
669
670 return max*1.05 ;
671}
672
673
674
675
676////////////////////////////////////////////////////////////////////////////////
677
679{
680 if (std::abs(dh1.sumEntries()-dh2.sumEntries())>1e-8) return false ;
681 if (dh1.numEntries() != dh2.numEntries()) return false ;
682 for (int i=0 ; i < dh1.numEntries() ; i++) {
683 if (std::abs(dh1.weight(i)-dh2.weight(i))>1e-8) return false ;
684 }
685 return true ;
686}
687
688
689
690////////////////////////////////////////////////////////////////////////////////
691/// Check if our datahist is already in the workspace
692
694{
695 for(auto const& data : ws.allData()) {
696 // If your dataset is already in this workspace nothing needs to be done
697 if (data == _dataHist) {
698 return false ;
699 }
700 }
701
702 // Check if dataset with given name already exists
703 if (RooAbsData* wsdata = ws.embeddedData(_dataHist->GetName())) {
704
705 // Yes it exists - now check if it is identical to our internal histogram
706 if (wsdata->InheritsFrom(RooDataHist::Class())) {
707
708 // Check if histograms are identical
709 if (areIdentical(static_cast<RooDataHist&>(*wsdata),*_dataHist)) {
710
711 // Exists and is of correct type, and identical -- adjust internal pointer to WS copy
712 _dataHist = static_cast<RooDataHist*>(wsdata) ;
713 } else {
714
715 // not identical, clone rename and import
716 auto uniqueName = std::string(_dataHist->GetName()) + "_" + GetName();
717 bool flag = ws.import(*_dataHist,RooFit::Rename(uniqueName.c_str()),RooFit::Embedded()) ;
718 if (flag) {
719 coutE(ObjectHandling) << " RooHistPdf::importWorkspaceHook(" << GetName() << ") unable to import clone of underlying RooDataHist with unique name " << uniqueName << ", abort" << std::endl ;
720 return true ;
721 }
722 _dataHist = static_cast<RooDataHist*>(ws.embeddedData(uniqueName)) ;
723 }
724
725 } else {
726
727 // Exists and is NOT of correct type: clone rename and import
728 auto uniqueName = std::string(_dataHist->GetName()) + "_" + GetName();
729 bool flag = ws.import(*_dataHist,RooFit::Rename(uniqueName.c_str()),RooFit::Embedded()) ;
730 if (flag) {
731 coutE(ObjectHandling) << " RooHistPdf::importWorkspaceHook(" << GetName() << ") unable to import clone of underlying RooDataHist with unique name " << uniqueName << ", abort" << std::endl ;
732 return true ;
733 }
734 _dataHist = static_cast<RooDataHist*>(ws.embeddedData(uniqueName));
735
736 }
737 return false ;
738 }
739
740 // We need to import our datahist into the workspace
742
743 // Redirect our internal pointer to the copy in the workspace
744 _dataHist = static_cast<RooDataHist*>(ws.embeddedData(_dataHist->GetName())) ;
745 return false ;
746}
747
748
749////////////////////////////////////////////////////////////////////////////////
750/// Stream an object of class RooHistPdf.
751
753{
754 if (R__b.IsReading()) {
756 // WVE - interim solution - fix proxies here
757 //_proxyList.Clear() ;
758 //registerProxy(_pdfObsList) ;
759 } else {
761 }
762}
#define b(i)
Definition RSha256.hxx:100
#define e(i)
Definition RSha256.hxx:103
#define oocoutW(o, a)
#define coutW(a)
#define coutE(a)
#define R__ASSERT(e)
Checks condition e and reports a fatal error if it's false.
Definition TError.h:139
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize void data
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize void char Point_t Rectangle_t WindowAttributes_t Float_t Float_t Float_t Int_t Int_t UInt_t UInt_t Rectangle_t result
char name[80]
Definition TGX11.cxx:142
Common abstract base class for objects that represent a value and a "shape" in RooFit.
Definition RooAbsArg.h:77
virtual void copyCache(const RooAbsArg *source, bool valueOnly=false, bool setValDirty=true)=0
bool dependsOn(const RooAbsCollection &serverList, const RooAbsArg *ignoreArg=nullptr, bool valueOnly=false) const
Test whether we depend on (ie, are served by) any object in the specified collection.
virtual void syncCache(const RooArgSet *nset=nullptr)=0
friend void RooRefArray::Streamer(TBuffer &)
virtual bool inRange(const char *) const
Definition RooAbsArg.h:301
void leafNodeServerList(RooAbsCollection *list, const RooAbsArg *arg=nullptr, bool recurseNonDerived=false) const
Fill supplied list with all leaf nodes of the arg tree, starting with ourself as top node.
Abstract base class for RooRealVar binning definitions.
virtual bool isParameterized() const
Interface function.
virtual Int_t numBoundaries() const =0
virtual double * array() const =0
Int_t numTypes(const char *=nullptr) const
Return number of types defined (in range named rangeName if rangeName!=nullptr)
virtual void removeAll()
Remove all arguments from our set, deleting them if we own them.
const char * GetName() const override
Returns name of object.
virtual bool add(const RooAbsArg &var, bool silent=false)
Add the specified argument to list.
void assign(const RooAbsCollection &other) const
Sets the value, cache and constant attribute of any argument in our set that also appears in the othe...
Storage_t::size_type size() const
virtual RooAbsArg * addClone(const RooAbsArg &var, bool silent=false)
Add a clone of the specified argument to list.
RooAbsArg * find(const char *name) const
Find object with given name in list.
Abstract base class for binned and unbinned datasets.
Definition RooAbsData.h:55
virtual Int_t numEntries() const
Return number of entries in dataset, i.e., count unweighted entries.
Abstract base class for objects that are lvalues, i.e.
Abstract interface for all probability density functions.
Definition RooAbsPdf.h:32
Abstract base class for objects that represent a real value that may appear on the left hand side of ...
virtual double getMax(const char *name=nullptr) const
Get maximum of currently defined range.
virtual void setVal(double value)=0
Set the current value of the object. Needs to be overridden by implementations.
virtual double getMin(const char *name=nullptr) const
Get minimum of currently defined range.
const RooAbsBinning * getBinningPtr(const char *rangeName) const override
bool hasRange(const char *name) const override
Check if variable has a binning with given name.
Abstract base class for objects that represent a real value and implements functionality common to al...
Definition RooAbsReal.h:63
virtual void doEval(RooFit::EvalContext &) const
Base function for computing multiple values of a RooAbsReal.
RooArgList is a container object that can hold multiple RooAbsArg objects.
Definition RooArgList.h:22
RooArgSet is a container object that can hold multiple RooAbsArg objects.
Definition RooArgSet.h:24
RooArgSet * snapshot(bool deepCopy=true) const
Use RooAbsCollection::snapshot(), but return as RooArgSet.
Definition RooArgSet.h:159
RooArgSet * selectCommon(const RooAbsCollection &refColl) const
Use RooAbsCollection::selecCommon(), but return as RooArgSet.
Definition RooArgSet.h:154
Object to represent discrete states.
Definition RooCategory.h:28
bool add(const RooAbsArg &var, bool valueServer, bool shapeServer, bool silent)
Overloaded RooCollection_t::add() method insert object into set and registers object as server to own...
static std::list< double > * plotSamplingHintForBinBoundaries(std::span< const double > boundaries, double xlo, double xhi)
Returns sampling hints for a histogram with given boundaries.
Definition RooCurve.cxx:901
Container class to hold N-dimensional binned data.
Definition RooDataHist.h:40
double sum(bool correctForBinSize, bool inverseCorr=false) const
Return the sum of the weights of all bins in the histogram.
void weights(double *output, std::span< double const > xVals, int intOrder, bool correctForBinSize, bool cdfBoundaries)
A vectorized version of RooDataHist::weight() for one dimensional histograms with up to one dimension...
static TClass * Class()
TObject * Clone(const char *newname="") const override
Make a clone of an object using the Streamer facility.
Definition RooDataHist.h:61
double const * sumW2Array() const
double weight(std::size_t i) const
Return weight of i-th bin.
void set(std::size_t binNumber, double weight, double wgtErr)
Set bin content of bin that was last loaded with get(std::size_t).
double weightSquared(std::size_t i) const
Return squared weight sum of i-th bin.
double weightFast(const RooArgSet &bin, int intOrder, bool correctForBinSize, bool cdfBoundaries)
A faster version of RooDataHist::weight that assumes the passed arguments are aligned with the histog...
const RooArgSet * get() const override
Get bin centre of current bin.
Definition RooDataHist.h:82
double sumEntries() const override
Sum the weights of all bins.
std::span< const double > at(RooAbsArg const *arg, RooAbsArg const *caller=nullptr)
std::span< double > output()
A probability density function sampled from a multidimensional histogram.
Definition RooHistPdf.h:30
RooArgSet _histObsList
List of observables defining dimensions of histogram.
Definition RooHistPdf.h:112
Int_t _intOrder
Interpolation order.
Definition RooHistPdf.h:116
bool forceAnalyticalInt(const RooAbsArg &dep) const override
bool areIdentical(const RooDataHist &dh1, const RooDataHist &dh2)
RooDataHist * _dataHist
Unowned pointer to underlying histogram.
Definition RooHistPdf.h:114
bool _cdfBoundaries
Use boundary conditions for CDFs.
Definition RooHistPdf.h:117
std::list< double > * binBoundaries(RooAbsRealLValue &, double, double) const override
Return the histogram bin boundaries in the plot-observable coordinate, used for example by the RooBin...
static std::vector< double > histogramBoundariesInPlotObs(RooDataHist const &dataHist, RooArgSet const &pdfObsList, RooArgSet const &histObsList, RooAbsRealLValue &obs, double xlo, double xhi)
Return the histogram bin boundaries mapped to the coordinates of the plot observable obs.
double totVolume() const
Return the total volume spanned by the observables of the RooHistPdf.
void initializeOwnedDataHist(std::unique_ptr< RooDataHist > &&dataHist)
Definition RooHistPdf.h:153
bool importWorkspaceHook(RooWorkspace &ws) override
Check if our datahist is already in the workspace.
static TClass * Class()
RooSetProxy _pdfObsList
List of observables mapped onto histogram observables.
Definition RooHistPdf.h:113
void clampNegativeBins()
double maxVal(Int_t code) const override
Return maximum value for set of observables identified by code assigned in getMaxVal.
double analyticalIntegral(Int_t code, const char *rangeName=nullptr) const override
Return integral identified by 'code'.
std::list< double > * plotSamplingHint(RooAbsRealLValue &obs, double xlo, double xhi) const override
Return sampling hint for making curves of (projections) of this function as the recursive division st...
RooDataHist & dataHist()
Definition RooHistPdf.h:42
Int_t getMaxVal(const RooArgSet &vars) const override
Only handle case of maximum in all variables.
double _totVolume
! Total volume of space (product of ranges of observables)
Definition RooHistPdf.h:118
RooDataHist * cloneAndOwnDataHist(const char *newname="")
Replaces underlying RooDataHist with a clone, which is now owned, and returns the clone.
std::unique_ptr< RooDataHist > _ownedDataHist
! Owned pointer to underlying histogram
Definition RooHistPdf.h:115
void doEval(RooFit::EvalContext &) const override
Base function for computing multiple values of a RooAbsReal.
Int_t getAnalyticalIntegral(RooArgSet &allVars, RooArgSet &analVars, const char *rangeName=nullptr) const override
Determine integration scenario.
double evaluate() const override
Return the current value: The value of the bin enclosing the current coordinates of the observables,...
bool _unitNorm
Assume contents is unit normalized (for use as pdf cache)
Definition RooHistPdf.h:119
Variable that can be changed from the outside.
Definition RooRealVar.h:37
void setRange(const char *name, double min, double max, bool shared=true)
Set a fit or plotting range.
Persistable container for RooFit projects.
RooAbsData * embeddedData(RooStringView name) const
Retrieve dataset (binned or unbinned) with given name. A null pointer is returned if not found.
std::list< RooAbsData * > allData() const
Return list of all dataset in the workspace.
bool import(const RooAbsArg &arg, const RooCmdArg &arg1={}, const RooCmdArg &arg2={}, const RooCmdArg &arg3={}, const RooCmdArg &arg4={}, const RooCmdArg &arg5={}, const RooCmdArg &arg6={}, const RooCmdArg &arg7={}, const RooCmdArg &arg8={}, const RooCmdArg &arg9={})
Import a RooAbsArg object, e.g.
Buffer base class used for serializing objects.
Definition TBuffer.h:43
virtual Int_t ReadClassBuffer(const TClass *cl, void *pointer, const TClass *onfile_class=nullptr)=0
Bool_t IsReading() const
Definition TBuffer.h:86
virtual Int_t WriteClassBuffer(const TClass *cl, void *pointer)=0
const char * GetName() const override
Returns name of object.
Definition TNamed.h:49
RooCmdArg Rename(const char *suffix)
RooCmdArg Embedded(bool flag=true)
Double_t y[n]
Definition legend1.C:17
Double_t x[n]
Definition legend1.C:17
const Int_t n
Definition legend1.C:16
std::pair< double, double > getRangeOrBinningInterval(RooAbsArg const *arg, const char *rangeName)