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{
182 const std::size_t nBins = _dataHist->numEntries();
183
184 std::size_t nNegative = 0;
185 double sumNegative = 0.;
186 for (std::size_t i = 0; i < nBins; ++i) {
187 if (_dataHist->weight(i) < 0.) {
188 ++nNegative;
189 sumNegative += _dataHist->weight(i);
190 }
191 }
192 if (nNegative == 0) {
193 return;
194 }
195
196 coutW(InputArguments) << "RooHistPdf::ctor(" << GetName() << ") WARNING: input histogram \"" << _dataHist->GetName()
197 << "\" contains " << nNegative
198 << " bins with negative content (sum of negative contents: " << sumNegative
199 << "). A p.d.f. cannot be negative, so these bins contents are clipped to zero while "
200 "preserving the error. The input "
201 "histogram is not modified. To avoid this message, remove the negative bin contents "
202 "before constructing the RooHistPdf."
203 << std::endl;
204
205 // We'll mutate the content of the RooDataHist, so we have to create an
206 // internal clone to avoid impacting other places that use the RooDataHist
207 if (!_ownedDataHist) {
208 _ownedDataHist.reset(static_cast<RooDataHist *>(_dataHist->Clone()));
210 }
211
212 const bool hasSumW2 = _dataHist->sumW2Array() != nullptr;
213 for (std::size_t i = 0; i < nBins; ++i) {
214 if (_dataHist->weight(i) < 0.) {
215 // Keep the original bin error: clamping the content is a
216 // normalization-consistency measure, not a statement that the bin is
217 // now known exactly. The error still quantifies the statistical
218 // uncertainty of the original bin content estimate (e.g. whether the
219 // negative content is compatible with a fluctuation around zero),
220 // and setting it to zero would introduce undercoverage, which is
221 // always undesired. It would also irreversibly discard information
222 // for anyone retrieving the histogram via dataHist(), including any
223 // future per-bin MC-stat treatment, where a zero error would wrongly
224 // fix the bin at exactly zero.
225 const double wgtErr = hasSumW2 ? std::sqrt(std::max(_dataHist->weightSquared(i), 0.)) : 0.;
226 _dataHist->set(i, 0., wgtErr);
227 }
228 }
229}
230
232{
233 std::span<double> output = ctx.output();
234
235 // For interpolation and histograms of higher dimension, use base function
236 if (_pdfObsList.size() > 1) {
238 return;
239 }
240
241 auto xVals = ctx.at(_pdfObsList[0]);
242 _dataHist->weights(output.data(), xVals, _intOrder, true, _cdfBoundaries);
243 for (auto &ret : output) {
244 ret = std::max(ret, 0.0);
245 }
246}
247
248
249////////////////////////////////////////////////////////////////////////////////
250/// Return the current value: The value of the bin enclosing the current coordinates
251/// of the observables, normalized by the histograms contents. Interpolation
252/// is applied if the RooHistPdf is configured to do that.
253
255{
256 // Transfer values from
257 for (unsigned int i=0; i < _pdfObsList.size(); ++i) {
258 RooAbsArg* harg = _histObsList[i];
259 RooAbsArg* parg = _pdfObsList[i];
260
261 if (harg != parg) {
262 parg->syncCache() ;
263 harg->copyCache(parg,true) ;
264 if (!harg->inRange(nullptr)) {
265 return 0 ;
266 }
267 }
268 }
269
271
272 return std::max(ret, 0.0);
273}
274
275////////////////////////////////////////////////////////////////////////////////
276/// Return the total volume spanned by the observables of the RooHistPdf
277
279{
280 // Return previously calculated value, if any
281 if (_totVolume>0) {
282 return _totVolume ;
283 }
284 _totVolume = 1. ;
285
286 for (const auto arg : _histObsList) {
287 RooRealVar* real = dynamic_cast<RooRealVar*>(arg) ;
288 if (real) {
289 _totVolume *= (real->getMax()-real->getMin()) ;
290 } else {
291 RooCategory* cat = dynamic_cast<RooCategory*>(arg) ;
292 if (cat) {
293 _totVolume *= cat->numTypes() ;
294 }
295 }
296 }
297
298 return _totVolume ;
299}
300
301namespace {
302
303bool fullRange(const RooAbsArg& x, const RooAbsArg& y ,const char* range)
304{
305 const RooAbsRealLValue *_x = dynamic_cast<const RooAbsRealLValue*>(&x);
306 const RooAbsRealLValue *_y = dynamic_cast<const RooAbsRealLValue*>(&y);
307 if (!_x || !_y) return false;
308 if (!range || !strlen(range) || !_x->hasRange(range) ||
309 _x->getBinningPtr(range)->isParameterized()) {
310 // parameterized ranges may be full range now, but that might change,
311 // so return false
312 if (range && strlen(range) && _x->getBinningPtr(range)->isParameterized())
313 return false;
314 return (_x->getMin() == _y->getMin() && _x->getMax() == _y->getMax());
315 }
316 return (_x->getMin(range) == _y->getMin() && _x->getMax(range) == _y->getMax());
317}
318
319bool okayForAnalytical(RooAbsArg const& obs, RooArgSet const& allVars)
320{
321 auto lobs = dynamic_cast<RooAbsRealLValue const*>(&obs);
322 if(lobs == nullptr) return false;
323
324 bool isOkayForAnalyticalInt = false;
325
326 for(RooAbsArg *var : allVars) {
327 if(obs.dependsOn(*var)) {
328 if(!lobs->isJacobianOK(*var)) return false;
329 isOkayForAnalyticalInt = true;
330 }
331 }
332
333 return isOkayForAnalyticalInt;
334}
335
336} // namespace
337
338
340 RooArgSet& analVars,
341 const char* rangeName,
342 RooArgSet const& histObsList,
343 RooArgSet const& pdfObsList,
344 Int_t intOrder)
345{
346 // First make list of pdf observables to histogram observables
347 // and select only those for which the integral is over the full range
348
349 Int_t code = 0;
350 Int_t frcode = 0;
351 bool directSubRange = false;
352 for (unsigned int n=0; n < pdfObsList.size() && n < histObsList.size(); ++n) {
353 const auto pa = pdfObsList[n];
354 const auto ha = histObsList[n];
355
356 if (okayForAnalytical(*pa, allVars)) {
357 code |= 2 << n;
358 analVars.add(*pa);
359 if (fullRange(*pa, *ha, rangeName)) {
360 frcode |= 2 << n;
361 } else if (pa->isFundamental()) {
362 // Sub-range integral over the histogram observable itself (no transform).
363 directSubRange = true;
364 }
365 }
366 }
367
368 if (code == frcode) {
369 // integrate over full range of all observables - use bit 0 to indicate
370 // full range integration over all observables
371 code |= 1;
372 }
373
374 // the full range. For interpolated histograms (intOrder > 0), fall back to
375 // numerical integration over a direct sub-range of the histogram observable.
376 // A derived (non-fundamental) observable, such as a linear transform used to
377 // renormalize the components of a RooMomentMorphFuncND, keeps the analytical
378 // path it relies on.
379 if (intOrder > 0 && directSubRange) {
380 analVars.removeAll();
381 return 0;
382 }
383 return (code >= 2) ? code : 0;
384}
385
386
388 const char* rangeName,
389 RooArgSet const& histObsList,
390 RooArgSet const& pdfObsList,
391 RooDataHist& dataHist,
392 bool histFuncMode) {
393 // Simplest scenario, full-range integration over all dependents
394 if (((2 << histObsList.size()) - 1) == code) {
395 return dataHist.sum(histFuncMode);
396 }
397
398 // Partial integration scenario, retrieve set of variables, calculate partial
399 // sum, figure out integration ranges (if needed)
400 RooArgSet intSet;
401 std::map<const RooAbsArg*, std::pair<double, double> > ranges;
402 for (unsigned int n=0; n < pdfObsList.size() && n < histObsList.size(); ++n) {
403 const auto pa = pdfObsList[n];
404 const auto ha = histObsList[n];
405
406 if (code & (2 << n)) {
407 intSet.add(*ha);
408 }
409 if (!(code & 1)) {
410 ranges[ha] = RooHelpers::getRangeOrBinningInterval(pa, rangeName);
411 }
412 // WVE must sync hist slice list values to pdf slice list
413 // Transfer values from
414 if (ha != pa) {
415 pa->syncCache();
416 ha->copyCache(pa,true);
417 }
418 }
419
420 double ret = (code & 1) ? dataHist.sum(intSet,histObsList,true,!histFuncMode) :
421 dataHist.sum(intSet,histObsList,true,!histFuncMode, ranges);
422
423 return ret ;
424}
425
426////////////////////////////////////////////////////////////////////////////////
427/// Determine integration scenario. If no interpolation is used,
428/// RooHistPdf can perform all integrals over its dependents
429/// analytically via partial or complete summation of the input
430/// histogram. If interpolation is used on the integral over
431/// all histogram observables is supported
432
433Int_t RooHistPdf::getAnalyticalIntegral(RooArgSet& allVars, RooArgSet& analVars, const char* rangeName) const
434{
435 return getAnalyticalIntegral(allVars, analVars, rangeName, _histObsList, _pdfObsList, _intOrder);
436}
437
438
439////////////////////////////////////////////////////////////////////////////////
440/// Return integral identified by 'code'. The actual integration
441/// is deferred to RooDataHist::sum() which implements partial
442/// or complete summation over the histograms contents.
443
444double RooHistPdf::analyticalIntegral(Int_t code, const char* rangeName) const
445{
446 return analyticalIntegral(code, rangeName, _histObsList, _pdfObsList, *_dataHist, false);
447}
448
449
450bool RooHistPdf::forceAnalyticalInt(RooArgSet const& pdfObsList, const RooAbsArg& dep)
451{
452 bool isOkayForAnalyticalInt = false;
453
454 for (RooAbsArg * obs : pdfObsList) {
455 if(obs->dependsOn(dep)) {
456 // If the observable doesn't depend linearly on the integration
457 // variable we will not do analytical integration.
458 auto lvalue = dynamic_cast<RooAbsRealLValue const*>(obs);
459 if(!(lvalue && lvalue->isJacobianOK(dep))) return false;
460 isOkayForAnalyticalInt = true;
461 }
462 }
463
464 return isOkayForAnalyticalInt;
465}
466
467
469{
470 return forceAnalyticalInt(_pdfObsList, dep);
471}
472
473////////////////////////////////////////////////////////////////////////////////
474/// Return the histogram bin boundaries mapped to the coordinates of the plot
475/// observable `obs`. This handles the case where the p.d.f. observable is a
476/// transformation of the plot observable (for example a shift like
477/// `x_shifted = x - shift`), so that the returned boundaries are the positions
478/// of the histogram bin edges as they appear when the p.d.f. is plotted as a
479/// function of `obs`.
480///
481/// Returns an empty vector if no corresponding histogram observable can be
482/// located, or if a non-invertible transformation is detected.
483
484std::vector<double> RooHistPdf::histogramBoundariesInPlotObs(RooDataHist const &dataHist, RooArgSet const &pdfObsList,
485 RooArgSet const &histObsList, RooAbsRealLValue &obs,
486 double xlo, double xhi)
487{
488 std::vector<double> result;
489
490 // The histogram observable for `obs` belongs to the p.d.f. observable with
491 // the same name, or else to the first one that is a function of `obs`.
492 RooAbsArg *histObs = nullptr;
493 RooAbsArg *pdfObs = nullptr;
494 bool useTransform = false;
495 for (unsigned int i = 0; i < pdfObsList.size(); ++i) {
496 if (std::string(obs.GetName()) == pdfObsList[i]->GetName()) {
497 histObs = histObsList[i];
498 break;
499 }
500 }
501 if (!histObs) {
502 for (unsigned int i = 0; i < pdfObsList.size(); ++i) {
503 auto *po = dynamic_cast<RooAbsReal *>(pdfObsList[i]);
504 if (po && po->dependsOn(obs)) {
505 histObs = histObsList[i];
506 pdfObs = pdfObsList[i];
507 useTransform = true;
508 break;
509 }
510 }
511 }
512 if (!histObs) {
513 return result;
514 }
515
516 auto *lval = dynamic_cast<RooAbsLValue *>(dataHist.get()->find(histObs->GetName()));
517 if (!lval) {
518 return result;
519 }
520
521 const RooAbsBinning *binning = lval->getBinningPtr(nullptr);
522 const int nBoundaries = binning->numBoundaries();
523 const double *rawBoundaries = binning->array();
524
525 if (!useTransform) {
526 result.assign(rawBoundaries, rawBoundaries + nBoundaries);
527 return result;
528 }
529
530 // Invert `pdfObs = T(obs)` with a linear approximation of `T` on the plot
531 // range, which is exact for linear transformations. Inverting with the
532 // setVal() of an l-value like RooLinearVar would throw for boundaries that
533 // map outside the range of `obs`.
534 auto *pdfObsReal = static_cast<RooAbsReal *>(pdfObs);
535 const double probeLo = std::max(xlo, obs.getMin());
536 const double probeHi = std::min(xhi, obs.getMax());
537 if (probeHi > probeLo) {
538 // Restore `obs` with assign(), because setVal() throws if an outer
539 // integral has set it outside of its default range.
540 RooArgSet obsLeaves;
541 obs.leafNodeServerList(&obsLeaves);
542 RooArgSet obsSaved;
543 obsLeaves.snapshot(obsSaved, false);
544 auto evalAt = [&](double val) {
545 obs.setVal(val);
546 return pdfObsReal->getVal();
547 };
548 const double probeMid = 0.5 * (probeLo + probeHi);
549 const double plo = evalAt(probeLo);
550 const double phi = evalAt(probeHi);
551 const double pmid = evalAt(probeMid);
552 obsLeaves.assign(obsSaved);
553 const double slope = (phi - plo) / (probeHi - probeLo);
554
555 // The midpoint reveals non-linear transformations.
556 const double pmidLinear = plo + slope * (probeMid - probeLo);
557 const double scale = std::max(std::abs(plo), std::abs(phi));
558 if (std::abs(pmid - pmidLinear) > 1e-7 * (scale > 0.0 ? scale : 1.0)) {
559 oocoutW(nullptr, Plotting)
560 << "RooHistPdf::histogramBoundariesInPlotObs: the histogram observable '" << pdfObsReal->GetName()
561 << "' appears to be a non-linear transformation of the plot observable '" << obs.GetName()
562 << "'. The bin boundaries used for plotting and integration are approximated assuming a linear "
563 "relation and may be placed incorrectly."
564 << std::endl;
565 }
566
567 if (slope != 0.0) {
568 result.reserve(nBoundaries);
569 for (int i = 0; i < nBoundaries; ++i) {
570 result.push_back(probeLo + (rawBoundaries[i] - plo) / slope);
571 }
572 }
573 }
574
575 // The transformation may reverse the order (negative slope).
576 std::sort(result.begin(), result.end());
577 return result;
578}
579
580////////////////////////////////////////////////////////////////////////////////
581/// Return sampling hint for making curves of (projections) of this function
582/// as the recursive division strategy of RooCurve cannot deal efficiently
583/// with the vertical lines that occur in a non-interpolated histogram
584
585std::list<double>* RooHistPdf::plotSamplingHint(RooAbsRealLValue& obs, double xlo, double xhi) const
586{
588}
589
590
591std::list<double>* RooHistPdf::plotSamplingHint(RooDataHist const& dataHist,
592 RooArgSet const& pdfObsList,
593 RooArgSet const& histObsList,
594 int intOrder,
595 RooAbsRealLValue& obs,
596 double xlo,
597 double xhi)
598{
599 // No hints are required when interpolation is used
600 if (intOrder>0) {
601 return nullptr;
602 }
603
604 const std::vector<double> boundaries = histogramBoundariesInPlotObs(dataHist, pdfObsList, histObsList, obs, xlo, xhi);
605 if (boundaries.empty()) {
606 return nullptr;
607 }
608
609 // Use the helper function from RooCurve to make sure to get sampling hints
610 // that work with the RooFitPlotting.
611 return RooCurve::plotSamplingHintForBinBoundaries(boundaries, xlo, xhi);
612}
613
614////////////////////////////////////////////////////////////////////////////////
615/// Return the histogram bin boundaries in the plot-observable coordinate,
616/// used for example by the RooBinIntegrator and the binned likelihood.
617
618std::list<double>* RooHistPdf::binBoundaries(RooAbsRealLValue& obs, double xlo, double xhi) const
619{
620 // No hints are required when interpolation is used
621 if (_intOrder>0) {
622 return nullptr;
623 }
624
625 const std::vector<double> boundaries =
627 if (boundaries.empty()) {
628 return nullptr;
629 }
630
631 auto hint = new std::list<double>;
632 for (double b : boundaries) {
633 if (b >= xlo && b <= xhi) {
634 hint->push_back(b);
635 }
636 }
637
638 return hint;
639}
640
641
642
643
644////////////////////////////////////////////////////////////////////////////////
645/// Only handle case of maximum in all variables
646
648{
649 std::unique_ptr<RooAbsCollection> common{_pdfObsList.selectCommon(vars)};
650 if (common->size()==_pdfObsList.size()) {
651 return 1;
652 }
653 return 0 ;
654}
655
656
657////////////////////////////////////////////////////////////////////////////////
658
659double RooHistPdf::maxVal(Int_t code) const
660{
661 R__ASSERT(code==1) ;
662
663 double max(-1) ;
664 for (Int_t i=0 ; i<_dataHist->numEntries() ; i++) {
665 double wgt = _dataHist->weight(i) ;
666 if (wgt>max) max=wgt ;
667 }
668
669 return max*1.05 ;
670}
671
672
673
674
675////////////////////////////////////////////////////////////////////////////////
676
678{
679 if (std::abs(dh1.sumEntries()-dh2.sumEntries())>1e-8) return false ;
680 if (dh1.numEntries() != dh2.numEntries()) return false ;
681 for (int i=0 ; i < dh1.numEntries() ; i++) {
682 if (std::abs(dh1.weight(i)-dh2.weight(i))>1e-8) return false ;
683 }
684 return true ;
685}
686
687
688
689////////////////////////////////////////////////////////////////////////////////
690/// Check if our datahist is already in the workspace
691
693{
694 for(auto const& data : ws.allData()) {
695 // If your dataset is already in this workspace nothing needs to be done
696 if (data == _dataHist) {
697 return false ;
698 }
699 }
700
701 // Check if dataset with given name already exists
702 if (RooAbsData* wsdata = ws.embeddedData(_dataHist->GetName())) {
703
704 // Yes it exists - now check if it is identical to our internal histogram
705 if (wsdata->InheritsFrom(RooDataHist::Class())) {
706
707 // Check if histograms are identical
708 if (areIdentical(static_cast<RooDataHist&>(*wsdata),*_dataHist)) {
709
710 // Exists and is of correct type, and identical -- adjust internal pointer to WS copy
711 _dataHist = static_cast<RooDataHist*>(wsdata) ;
712 } else {
713
714 // not identical, clone rename and import
715 auto uniqueName = std::string(_dataHist->GetName()) + "_" + GetName();
716 bool flag = ws.import(*_dataHist,RooFit::Rename(uniqueName.c_str()),RooFit::Embedded()) ;
717 if (flag) {
718 coutE(ObjectHandling) << " RooHistPdf::importWorkspaceHook(" << GetName() << ") unable to import clone of underlying RooDataHist with unique name " << uniqueName << ", abort" << std::endl ;
719 return true ;
720 }
721 _dataHist = static_cast<RooDataHist*>(ws.embeddedData(uniqueName)) ;
722 }
723
724 } else {
725
726 // Exists and is NOT of correct type: clone rename and import
727 auto uniqueName = std::string(_dataHist->GetName()) + "_" + GetName();
728 bool flag = ws.import(*_dataHist,RooFit::Rename(uniqueName.c_str()),RooFit::Embedded()) ;
729 if (flag) {
730 coutE(ObjectHandling) << " RooHistPdf::importWorkspaceHook(" << GetName() << ") unable to import clone of underlying RooDataHist with unique name " << uniqueName << ", abort" << std::endl ;
731 return true ;
732 }
733 _dataHist = static_cast<RooDataHist*>(ws.embeddedData(uniqueName));
734
735 }
736 return false ;
737 }
738
739 // We need to import our datahist into the workspace
741
742 // Redirect our internal pointer to the copy in the workspace
743 _dataHist = static_cast<RooDataHist*>(ws.embeddedData(_dataHist->GetName())) ;
744 return false ;
745}
746
747
748////////////////////////////////////////////////////////////////////////////////
749/// Stream an object of class RooHistPdf.
750
752{
753 if (R__b.IsReading()) {
755 // WVE - interim solution - fix proxies here
756 //_proxyList.Clear() ;
757 //registerProxy(_pdfObsList) ;
758 } else {
760 }
761}
#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
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...
double sum(bool correctForBinSize, bool inverseBinCor=false) const
Return the sum of the weights of all bins in the histogram.
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:108
Int_t _intOrder
Interpolation order.
Definition RooHistPdf.h:112
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:110
bool _cdfBoundaries
Use boundary conditions for CDFs.
Definition RooHistPdf.h:113
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:149
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:109
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:114
std::unique_ptr< RooDataHist > _ownedDataHist
! Owned pointer to underlying histogram
Definition RooHistPdf.h:111
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:115
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)