Logo ROOT  
Reference Guide
RooDataHist.cxx
Go to the documentation of this file.
1 /*****************************************************************************
2  * Project: RooFit *
3  * Package: RooFitCore *
4  * @(#)root/roofitcore:$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 RooDataHist.cxx
19 \class RooDataHist
20 \ingroup Roofitcore
21 
22 The RooDataHist is a container class to hold N-dimensional binned data. Each bin's central
23 coordinates in N-dimensional space are represented by a RooArgSet containing RooRealVar, RooCategory
24 or RooStringVar objects, thus data can be binned in real and/or discrete dimensions.
25 **/
26 
27 #include "RooDataHist.h"
28 
29 #include "RooFit.h"
30 #include "Riostream.h"
31 #include "RooMsgService.h"
32 #include "RooDataHistSliceIter.h"
33 #include "RooAbsLValue.h"
34 #include "RooArgList.h"
35 #include "RooRealVar.h"
36 #include "RooMath.h"
37 #include "RooBinning.h"
38 #include "RooPlot.h"
39 #include "RooHistError.h"
40 #include "RooCategory.h"
41 #include "RooCmdConfig.h"
42 #include "RooLinkedListIter.h"
43 #include "RooTreeDataStore.h"
44 #include "RooVectorDataStore.h"
45 #include "RooTrace.h"
46 #include "RooHelpers.h"
47 #include "RooFormulaVar.h"
48 #include "RooFormula.h"
49 #include "RooUniformBinning.h"
50 #include "RooSpan.h"
51 
52 #include "TH1.h"
53 #include "TTree.h"
54 #include "TBuffer.h"
55 #include "TMath.h"
56 #include "Math/Util.h"
57 
58 using namespace std;
59 
61 
62 
63 ////////////////////////////////////////////////////////////////////////////////
64 /// Default constructor
65 
67  _pbinvCacheMgr(0,10)
68 {
70 }
71 
72 
73 
74 ////////////////////////////////////////////////////////////////////////////////
75 /// Constructor of an empty data hist from a RooArgSet defining the dimensions
76 /// of the data space. The range and number of bins in each dimensions are taken
77 /// from getMin()getMax(),getBins() of each RooAbsArg representing that
78 /// dimension.
79 ///
80 /// For real dimensions, the fit range and number of bins can be set independently
81 /// of the plot range and number of bins, but it is advisable to keep the
82 /// ratio of the plot bin width and the fit bin width an integer value.
83 /// For category dimensions, the fit ranges always comprises all defined states
84 /// and each state is always has its individual bin
85 ///
86 /// To effectively bin real dimensions with variable bin sizes,
87 /// construct a RooThresholdCategory of the real dimension to be binned variably.
88 /// Set the thresholds at the desired bin boundaries, and construct the
89 /// data hist as a function of the threshold category instead of the real variable.
90 RooDataHist::RooDataHist(const char *name, const char *title, const RooArgSet& vars, const char* binningName) :
91  RooAbsData(name,title,vars), _pbinvCacheMgr(0,10)
92 {
93  // Initialize datastore
96 
97  initialize(binningName) ;
98 
100 
101  appendToDir(this,kTRUE) ;
103 }
104 
105 
106 
107 ////////////////////////////////////////////////////////////////////////////////
108 /// Constructor of a data hist from an existing data collection (binned or unbinned)
109 /// The RooArgSet 'vars' defines the dimensions of the histogram.
110 /// The range and number of bins in each dimensions are taken
111 /// from getMin(), getMax(), getBins() of each argument passed.
112 ///
113 /// For real dimensions, the fit range and number of bins can be set independently
114 /// of the plot range and number of bins, but it is advisable to keep the
115 /// ratio of the plot bin width and the fit bin width an integer value.
116 /// For category dimensions, the fit ranges always comprises all defined states
117 /// and each state is always has its individual bin
118 ///
119 /// To effectively bin real dimensions with variable bin sizes,
120 /// construct a RooThresholdCategory of the real dimension to be binned variably.
121 /// Set the thresholds at the desired bin boundaries, and construct the
122 /// data hist as a function of the threshold category instead of the real variable.
123 ///
124 /// If the constructed data hist has less dimensions that in source data collection,
125 /// all missing dimensions will be projected.
126 
127 RooDataHist::RooDataHist(const char *name, const char *title, const RooArgSet& vars, const RooAbsData& data, Double_t wgt) :
128  RooAbsData(name,title,vars), _pbinvCacheMgr(0,10)
129 {
130  // Initialize datastore
132  ((RooAbsDataStore*) new RooVectorDataStore(name,title,_vars)) ;
133 
134  initialize() ;
136 
137  add(data,(const RooFormulaVar*)0,wgt) ;
138  appendToDir(this,kTRUE) ;
140 }
141 
142 
143 
144 ////////////////////////////////////////////////////////////////////////////////
145 /// Constructor of a data hist from a map of TH1,TH2 or TH3 that are collated into a x+1 dimensional
146 /// RooDataHist where the added dimension is a category that labels the input source as defined
147 /// in the histMap argument. The state names used in histMap must correspond to predefined states
148 /// 'indexCat'
149 ///
150 /// The RooArgList 'vars' defines the dimensions of the histogram.
151 /// The ranges and number of bins are taken from the input histogram and must be the same in all histograms
152 
153 RooDataHist::RooDataHist(const char *name, const char *title, const RooArgList& vars, RooCategory& indexCat,
154  map<string,TH1*> histMap, Double_t wgt) :
155  RooAbsData(name,title,RooArgSet(vars,&indexCat)),
156  _pbinvCacheMgr(0,10)
157 {
158  // Initialize datastore
160  ((RooAbsDataStore*) new RooVectorDataStore(name,title,_vars)) ;
161 
162  importTH1Set(vars, indexCat, histMap, wgt, kFALSE) ;
163 
166 }
167 
168 
169 
170 ////////////////////////////////////////////////////////////////////////////////
171 /// Constructor of a data hist from a map of RooDataHists that are collated into a x+1 dimensional
172 /// RooDataHist where the added dimension is a category that labels the input source as defined
173 /// in the histMap argument. The state names used in histMap must correspond to predefined states
174 /// 'indexCat'
175 ///
176 /// The RooArgList 'vars' defines the dimensions of the histogram.
177 /// The ranges and number of bins are taken from the input histogram and must be the same in all histograms
178 
179 RooDataHist::RooDataHist(const char *name, const char *title, const RooArgList& vars, RooCategory& indexCat,
180  map<string,RooDataHist*> dhistMap, Double_t wgt) :
181  RooAbsData(name,title,RooArgSet(vars,&indexCat)),
182  _pbinvCacheMgr(0,10)
183 {
184  // Initialize datastore
186  ((RooAbsDataStore*) new RooVectorDataStore(name,title,_vars)) ;
187 
188  importDHistSet(vars, indexCat, dhistMap, wgt) ;
189 
192 }
193 
194 
195 
196 ////////////////////////////////////////////////////////////////////////////////
197 /// Constructor of a data hist from an TH1,TH2 or TH3
198 /// The RooArgSet 'vars' defines the dimensions of the histogram. The ranges
199 /// and number of bins are taken from the input histogram, and the corresponding
200 /// values are set accordingly on the arguments in 'vars'
201 
202 RooDataHist::RooDataHist(const char *name, const char *title, const RooArgList& vars, const TH1* hist, Double_t wgt) :
203  RooAbsData(name,title,vars), _pbinvCacheMgr(0,10)
204 {
205  // Initialize datastore
207  ((RooAbsDataStore*) new RooVectorDataStore(name,title,_vars)) ;
208 
209  // Check consistency in number of dimensions
210  if (vars.getSize() != hist->GetDimension()) {
211  coutE(InputArguments) << "RooDataHist::ctor(" << GetName() << ") ERROR: dimension of input histogram must match "
212  << "number of dimension variables" << endl ;
213  assert(0) ;
214  }
215 
216  importTH1(vars,*hist,wgt, kFALSE) ;
217 
220 }
221 
222 
223 
224 ////////////////////////////////////////////////////////////////////////////////
225 /// Constructor of a binned dataset from a RooArgSet defining the dimensions
226 /// of the data space. The range and number of bins in each dimensions are taken
227 /// from getMin() getMax(),getBins() of each RooAbsArg representing that
228 /// dimension.
229 ///
230 /// <table>
231 /// <tr><th> Optional Argument <th> Effect
232 /// <tr><td> Import(TH1&, Bool_t impDens) <td> Import contents of the given TH1/2/3 into this binned dataset. The
233 /// ranges and binning of the binned dataset are automatically adjusted to
234 /// match those of the imported histogram.
235 ///
236 /// Please note: for TH1& with unequal binning _only_,
237 /// you should decide if you want to import the absolute bin content,
238 /// or the bin content expressed as density. The latter is default and will
239 /// result in the same histogram as the original TH1. For certain types of
240 /// bin contents (containing efficiencies, asymmetries, or ratio is general)
241 /// you should import the absolute value and set impDens to kFALSE
242 ///
243 ///
244 /// <tr><td> Weight(Double_t) <td> Apply given weight factor when importing histograms
245 ///
246 /// <tr><td> Index(RooCategory&) <td> Prepare import of multiple TH1/1/2/3 into a N+1 dimensional RooDataHist
247 /// where the extra discrete dimension labels the source of the imported histogram
248 /// If the index category defines states for which no histogram is be imported
249 /// the corresponding bins will be left empty.
250 ///
251 /// <tr><td> Import(const char*, TH1&) <td> Import a THx to be associated with the given state name of the index category
252 /// specified in Index(). If the given state name is not yet defined in the index
253 /// category it will be added on the fly. The import command can be specified
254 /// multiple times.
255 /// <tr><td> Import(map<string,TH1*>&) <td> As above, but allows specification of many imports in a single operation
256 ///
257 
258 RooDataHist::RooDataHist(const char *name, const char *title, const RooArgList& vars, const RooCmdArg& arg1, const RooCmdArg& arg2, const RooCmdArg& arg3,
259  const RooCmdArg& arg4,const RooCmdArg& arg5,const RooCmdArg& arg6,const RooCmdArg& arg7,const RooCmdArg& arg8) :
260  RooAbsData(name,title,RooArgSet(vars,(RooAbsArg*)RooCmdConfig::decodeObjOnTheFly("RooDataHist::RooDataHist", "IndexCat",0,0,arg1,arg2,arg3,arg4,arg5,arg6,arg7,arg8))),
261  _pbinvCacheMgr(0,10)
262 {
263  // Initialize datastore
265  ((RooAbsDataStore*) new RooVectorDataStore(name,title,_vars)) ;
266 
267  // Define configuration for this method
268  RooCmdConfig pc(Form("RooDataHist::ctor(%s)",GetName())) ;
269  pc.defineObject("impHist","ImportHisto",0) ;
270  pc.defineInt("impDens","ImportHisto",0) ;
271  pc.defineObject("indexCat","IndexCat",0) ;
272  pc.defineObject("impSliceHist","ImportHistoSlice",0,0,kTRUE) ; // array
273  pc.defineString("impSliceState","ImportHistoSlice",0,"",kTRUE) ; // array
274  pc.defineObject("impSliceDHist","ImportDataHistSlice",0,0,kTRUE) ; // array
275  pc.defineString("impSliceDState","ImportDataHistSlice",0,"",kTRUE) ; // array
276  pc.defineDouble("weight","Weight",0,1) ;
277  pc.defineObject("dummy1","ImportDataHistSliceMany",0) ;
278  pc.defineObject("dummy2","ImportHistoSliceMany",0) ;
279  pc.defineMutex("ImportHisto","ImportHistoSlice","ImportDataHistSlice") ;
280  pc.defineDependency("ImportHistoSlice","IndexCat") ;
281  pc.defineDependency("ImportDataHistSlice","IndexCat") ;
282 
283  RooLinkedList l ;
284  l.Add((TObject*)&arg1) ; l.Add((TObject*)&arg2) ;
285  l.Add((TObject*)&arg3) ; l.Add((TObject*)&arg4) ;
286  l.Add((TObject*)&arg5) ; l.Add((TObject*)&arg6) ;
287  l.Add((TObject*)&arg7) ; l.Add((TObject*)&arg8) ;
288 
289  // Process & check varargs
290  pc.process(l) ;
291  if (!pc.ok(kTRUE)) {
292  assert(0) ;
293  return ;
294  }
295 
296  TH1* impHist = static_cast<TH1*>(pc.getObject("impHist")) ;
297  Bool_t impDens = pc.getInt("impDens") ;
298  Double_t initWgt = pc.getDouble("weight") ;
299  const char* impSliceNames = pc.getString("impSliceState","",kTRUE) ;
300  const RooLinkedList& impSliceHistos = pc.getObjectList("impSliceHist") ;
301  RooCategory* indexCat = static_cast<RooCategory*>(pc.getObject("indexCat")) ;
302  const char* impSliceDNames = pc.getString("impSliceDState","",kTRUE) ;
303  const RooLinkedList& impSliceDHistos = pc.getObjectList("impSliceDHist") ;
304 
305 
306  if (impHist) {
307 
308  // Initialize importing contents from TH1
309  importTH1(vars,*impHist,initWgt, impDens) ;
310 
311  } else if (indexCat) {
312 
313 
314  if (impSliceHistos.GetSize()>0) {
315 
316  // Initialize importing mapped set of TH1s
317  map<string,TH1*> hmap ;
318  TIterator* hiter = impSliceHistos.MakeIterator() ;
319  for (const auto& token : RooHelpers::tokenise(impSliceNames, ",")) {
320  auto histo = static_cast<TH1*>(hiter->Next());
321  assert(histo);
322  hmap[token] = histo;
323  }
324  importTH1Set(vars,*indexCat,hmap,initWgt,kFALSE) ;
325  } else {
326 
327  // Initialize importing mapped set of RooDataHists
328  map<string,RooDataHist*> dmap ;
329  TIterator* hiter = impSliceDHistos.MakeIterator() ;
330  for (const auto& token : RooHelpers::tokenise(impSliceDNames, ",")) {
331  dmap[token] = (RooDataHist*) hiter->Next() ;
332  }
333  importDHistSet(vars,*indexCat,dmap,initWgt) ;
334  }
335 
336 
337  } else {
338 
339  // Initialize empty
340  initialize() ;
341  appendToDir(this,kTRUE) ;
342 
343  }
344 
347 
348 }
349 
350 
351 
352 
353 ////////////////////////////////////////////////////////////////////////////////
354 /// Import data from given TH1/2/3 into this RooDataHist
355 
356 void RooDataHist::importTH1(const RooArgList& vars, const TH1& histo, Double_t wgt, Bool_t doDensityCorrection)
357 {
358  // Adjust binning of internal observables to match that of input THx
359  Int_t offset[3]{0, 0, 0};
360  adjustBinning(vars, histo, offset) ;
361 
362  // Initialize internal data structure
363  initialize() ;
364  appendToDir(this,kTRUE) ;
365 
366  // Define x,y,z as 1st, 2nd and 3rd observable
367  RooRealVar* xvar = (RooRealVar*) _vars.find(vars.at(0)->GetName()) ;
368  RooRealVar* yvar = (RooRealVar*) (vars.at(1) ? _vars.find(vars.at(1)->GetName()) : 0 ) ;
369  RooRealVar* zvar = (RooRealVar*) (vars.at(2) ? _vars.find(vars.at(2)->GetName()) : 0 ) ;
370 
371  // Transfer contents
372  Int_t xmin(0),ymin(0),zmin(0) ;
373  RooArgSet vset(*xvar) ;
374  Double_t volume = xvar->getMax()-xvar->getMin() ;
375  xmin = offset[0] ;
376  if (yvar) {
377  vset.add(*yvar) ;
378  ymin = offset[1] ;
379  volume *= (yvar->getMax()-yvar->getMin()) ;
380  }
381  if (zvar) {
382  vset.add(*zvar) ;
383  zmin = offset[2] ;
384  volume *= (zvar->getMax()-zvar->getMin()) ;
385  }
386  //Double_t avgBV = volume / numEntries() ;
387 // cout << "average bin volume = " << avgBV << endl ;
388 
389  Int_t ix(0),iy(0),iz(0) ;
390  for (ix=0 ; ix < xvar->getBins() ; ix++) {
391  xvar->setBin(ix) ;
392  if (yvar) {
393  for (iy=0 ; iy < yvar->getBins() ; iy++) {
394  yvar->setBin(iy) ;
395  if (zvar) {
396  for (iz=0 ; iz < zvar->getBins() ; iz++) {
397  zvar->setBin(iz) ;
398  Double_t bv = doDensityCorrection ? binVolume(vset) : 1;
399  add(vset,bv*histo.GetBinContent(ix+1+xmin,iy+1+ymin,iz+1+zmin)*wgt,bv*TMath::Power(histo.GetBinError(ix+1+xmin,iy+1+ymin,iz+1+zmin)*wgt,2)) ;
400  }
401  } else {
402  Double_t bv = doDensityCorrection ? binVolume(vset) : 1;
403  add(vset,bv*histo.GetBinContent(ix+1+xmin,iy+1+ymin)*wgt,bv*TMath::Power(histo.GetBinError(ix+1+xmin,iy+1+ymin)*wgt,2)) ;
404  }
405  }
406  } else {
407  Double_t bv = doDensityCorrection ? binVolume(vset) : 1 ;
408  add(vset,bv*histo.GetBinContent(ix+1+xmin)*wgt,bv*TMath::Power(histo.GetBinError(ix+1+xmin)*wgt,2)) ;
409  }
410  }
411 
412 }
413 
414 namespace {
415 bool checkConsistentAxes(const TH1* first, const TH1* second) {
416  return first->GetDimension() == second->GetDimension()
417  && first->GetNbinsX() == second->GetNbinsX()
418  && first->GetNbinsY() == second->GetNbinsY()
419  && first->GetNbinsZ() == second->GetNbinsZ()
420  && first->GetXaxis()->GetXmin() == second->GetXaxis()->GetXmin()
421  && first->GetXaxis()->GetXmax() == second->GetXaxis()->GetXmax()
422  && (first->GetNbinsY() == 1 || (first->GetYaxis()->GetXmin() == second->GetYaxis()->GetXmin()
423  && first->GetYaxis()->GetXmax() == second->GetYaxis()->GetXmax() ) )
424  && (first->GetNbinsZ() == 1 || (first->GetZaxis()->GetXmin() == second->GetZaxis()->GetXmin()
425  && first->GetZaxis()->GetXmax() == second->GetZaxis()->GetXmax() ) );
426 }
427 }
428 
429 
430 ////////////////////////////////////////////////////////////////////////////////
431 /// Import data from given set of TH1/2/3 into this RooDataHist. The category indexCat labels the sources
432 /// in the constructed RooDataHist. The stl map provides the mapping between the indexCat state labels
433 /// and the import source
434 
435 void RooDataHist::importTH1Set(const RooArgList& vars, RooCategory& indexCat, map<string,TH1*> hmap, Double_t wgt, Bool_t doDensityCorrection)
436 {
437  RooCategory* icat = (RooCategory*) _vars.find(indexCat.GetName()) ;
438 
439  TH1* histo(0) ;
440  Bool_t init(kFALSE) ;
441  for (const auto& hiter : hmap) {
442  // Store pointer to first histogram from which binning specification will be taken
443  if (!histo) {
444  histo = hiter.second;
445  } else {
446  if (!checkConsistentAxes(histo, hiter.second)) {
447  coutE(InputArguments) << "Axes of histogram " << hiter.second->GetName() << " are not consistent with first processed "
448  << "histogram " << histo->GetName() << std::endl;
449  throw std::invalid_argument("Axes of inputs for RooDataHist are inconsistent");
450  }
451  }
452  // Define state labels in index category (both in provided indexCat and in internal copy in dataset)
453  if (!indexCat.hasLabel(hiter.first)) {
454  indexCat.defineType(hiter.first) ;
455  coutI(InputArguments) << "RooDataHist::importTH1Set(" << GetName() << ") defining state \"" << hiter.first << "\" in index category " << indexCat.GetName() << endl ;
456  }
457  if (!icat->hasLabel(hiter.first)) {
458  icat->defineType(hiter.first) ;
459  }
460  }
461 
462  // Check consistency in number of dimensions
463  if (histo && (vars.getSize() != histo->GetDimension())) {
464  coutE(InputArguments) << "RooDataHist::importTH1Set(" << GetName() << "): dimension of input histogram must match "
465  << "number of continuous variables" << endl ;
466  throw std::invalid_argument("Inputs histograms for RooDataHist are not compatible with dimensions of variables.");
467  }
468 
469  // Copy bins and ranges from THx to dimension observables
470  Int_t offset[3] ;
471  adjustBinning(vars,*histo,offset) ;
472 
473  // Initialize internal data structure
474  if (!init) {
475  initialize() ;
476  appendToDir(this,kTRUE) ;
477  init = kTRUE ;
478  }
479 
480  // Define x,y,z as 1st, 2nd and 3rd observable
481  RooRealVar* xvar = (RooRealVar*) _vars.find(vars.at(0)->GetName()) ;
482  RooRealVar* yvar = (RooRealVar*) (vars.at(1) ? _vars.find(vars.at(1)->GetName()) : 0 ) ;
483  RooRealVar* zvar = (RooRealVar*) (vars.at(2) ? _vars.find(vars.at(2)->GetName()) : 0 ) ;
484 
485  // Transfer contents
486  Int_t xmin(0),ymin(0),zmin(0) ;
487  RooArgSet vset(*xvar) ;
488  Double_t volume = xvar->getMax()-xvar->getMin() ;
489  xmin = offset[0] ;
490  if (yvar) {
491  vset.add(*yvar) ;
492  ymin = offset[1] ;
493  volume *= (yvar->getMax()-yvar->getMin()) ;
494  }
495  if (zvar) {
496  vset.add(*zvar) ;
497  zmin = offset[2] ;
498  volume *= (zvar->getMax()-zvar->getMin()) ;
499  }
500  Double_t avgBV = volume / numEntries() ;
501 
502  Int_t ic(0),ix(0),iy(0),iz(0) ;
503  for (ic=0 ; ic < icat->numBins(0) ; ic++) {
504  icat->setBin(ic) ;
505  histo = hmap[icat->getCurrentLabel()] ;
506  for (ix=0 ; ix < xvar->getBins() ; ix++) {
507  xvar->setBin(ix) ;
508  if (yvar) {
509  for (iy=0 ; iy < yvar->getBins() ; iy++) {
510  yvar->setBin(iy) ;
511  if (zvar) {
512  for (iz=0 ; iz < zvar->getBins() ; iz++) {
513  zvar->setBin(iz) ;
514  Double_t bv = doDensityCorrection ? binVolume(vset)/avgBV : 1;
515  add(vset,bv*histo->GetBinContent(ix+1+xmin,iy+1+ymin,iz+1+zmin)*wgt,bv*TMath::Power(histo->GetBinError(ix+1+xmin,iy+1+ymin,iz+1+zmin)*wgt,2)) ;
516  }
517  } else {
518  Double_t bv = doDensityCorrection ? binVolume(vset)/avgBV : 1;
519  add(vset,bv*histo->GetBinContent(ix+1+xmin,iy+1+ymin)*wgt,bv*TMath::Power(histo->GetBinError(ix+1+xmin,iy+1+ymin)*wgt,2)) ;
520  }
521  }
522  } else {
523  Double_t bv = doDensityCorrection ? binVolume(vset)/avgBV : 1;
524  add(vset,bv*histo->GetBinContent(ix+1+xmin)*wgt,bv*TMath::Power(histo->GetBinError(ix+1+xmin)*wgt,2)) ;
525  }
526  }
527  }
528 
529 }
530 
531 
532 
533 ////////////////////////////////////////////////////////////////////////////////
534 /// Import data from given set of TH1/2/3 into this RooDataHist. The category indexCat labels the sources
535 /// in the constructed RooDataHist. The stl map provides the mapping between the indexCat state labels
536 /// and the import source
537 
538 void RooDataHist::importDHistSet(const RooArgList& /*vars*/, RooCategory& indexCat, std::map<std::string,RooDataHist*> dmap, Double_t initWgt)
539 {
540  RooCategory* icat = (RooCategory*) _vars.find(indexCat.GetName()) ;
541 
542  for (const auto& diter : dmap) {
543 
544  // Define state labels in index category (both in provided indexCat and in internal copy in dataset)
545  if (!indexCat.hasLabel(diter.first)) {
546  indexCat.defineType(diter.first) ;
547  coutI(InputArguments) << "RooDataHist::importDHistSet(" << GetName() << ") defining state \"" << diter.first << "\" in index category " << indexCat.GetName() << endl ;
548  }
549  if (!icat->hasLabel(diter.first)) {
550  icat->defineType(diter.first) ;
551  }
552  }
553 
554  initialize() ;
555  appendToDir(this,kTRUE) ;
556 
557 
558  for (const auto& diter : dmap) {
559 
560  RooDataHist* dhist = diter.second ;
561 
562  icat->setLabel(diter.first.c_str()) ;
563 
564  // Transfer contents
565  for (Int_t i=0 ; i<dhist->numEntries() ; i++) {
566  _vars = *dhist->get(i) ;
567  add(_vars,dhist->weight()*initWgt, pow(dhist->weightError(SumW2),2) ) ;
568  }
569 
570  }
571 }
572 
573 ////////////////////////////////////////////////////////////////////////////////
574 /// Helper doing the actual work of adjustBinning().
575 
576 void RooDataHist::_adjustBinning(RooRealVar &theirVar, const TAxis &axis,
577  RooRealVar *ourVar, Int_t *offset)
578 {
579  if (!dynamic_cast<RooRealVar*>(ourVar)) {
580  coutE(InputArguments) << "RooDataHist::adjustBinning(" << GetName() << ") ERROR: dimension " << ourVar->GetName() << " must be real" << endl ;
581  assert(0) ;
582  }
583 
584  const double xlo = theirVar.getMin();
585  const double xhi = theirVar.getMax();
586 
587  if (axis.GetXbins()->GetArray()) {
588  RooBinning xbins(axis.GetNbins(), axis.GetXbins()->GetArray());
589 
590  const double tolerance = 1e-6 * xbins.averageBinWidth();
591 
592  // Adjust xlo/xhi to nearest boundary
593  const double xloAdj = xbins.binLow(xbins.binNumber(xlo + tolerance));
594  const double xhiAdj = xbins.binHigh(xbins.binNumber(xhi - tolerance));
595  xbins.setRange(xloAdj, xhiAdj);
596 
597  theirVar.setBinning(xbins);
598 
599  if (true || fabs(xloAdj - xlo) > tolerance || fabs(xhiAdj - xhi) > tolerance) {
600  coutI(DataHandling)<< "RooDataHist::adjustBinning(" << GetName() << "): fit range of variable " << ourVar->GetName() << " expanded to nearest bin boundaries: [" << xlo << "," << xhi << "] --> [" << xloAdj << "," << xhiAdj << "]" << endl;
601  }
602 
603  ourVar->setBinning(xbins);
604 
605  if (offset) {
606  *offset = xbins.rawBinNumber(xloAdj + tolerance);
607  }
608  } else {
609  RooBinning xbins(axis.GetXmin(), axis.GetXmax());
610  xbins.addUniform(axis.GetNbins(), axis.GetXmin(), axis.GetXmax());
611 
612  const double tolerance = 1e-6 * xbins.averageBinWidth();
613 
614  // Adjust xlo/xhi to nearest boundary
615  const double xloAdj = xbins.binLow(xbins.binNumber(xlo + tolerance));
616  const double xhiAdj = xbins.binHigh(xbins.binNumber(xhi - tolerance));
617  xbins.setRange(xloAdj, xhiAdj);
618  theirVar.setRange(xloAdj, xhiAdj);
619 
620  if (fabs(xloAdj - xlo) > tolerance || fabs(xhiAdj - xhi) > tolerance) {
621  coutI(DataHandling)<< "RooDataHist::adjustBinning(" << GetName() << "): fit range of variable " << ourVar->GetName() << " expanded to nearest bin boundaries: [" << xlo << "," << xhi << "] --> [" << xloAdj << "," << xhiAdj << "]" << endl;
622  }
623 
624  RooUniformBinning xbins2(xloAdj, xhiAdj, xbins.numBins());
625  ourVar->setBinning(xbins2);
626 
627  if (offset) {
628  *offset = xbins.rawBinNumber(xloAdj + tolerance);
629  }
630  }
631 }
632 
633 ////////////////////////////////////////////////////////////////////////////////
634 /// Adjust binning specification on first and optionally second and third
635 /// observable to binning in given reference TH1. Used by constructors
636 /// that import data from an external TH1.
637 /// Both the variables in vars and in this RooDataHist are adjusted.
638 /// @param vars List with variables that are supposed to have their binning adjusted.
639 /// @param href Reference histogram that dictates the binning
640 /// @param offset If not nullptr, a possible bin count offset for the axes x,y,z is saved here as Int_t[3]
641 
642 void RooDataHist::adjustBinning(const RooArgList& vars, const TH1& href, Int_t* offset)
643 {
644  auto xvar = static_cast<RooRealVar*>( _vars.find(*vars.at(0)) );
645  _adjustBinning(*static_cast<RooRealVar*>(vars.at(0)), *href.GetXaxis(), xvar, offset ? &offset[0] : nullptr);
646 
647  if (vars.at(1)) {
648  auto yvar = static_cast<RooRealVar*>(_vars.find(*vars.at(1)));
649  if (yvar)
650  _adjustBinning(*static_cast<RooRealVar*>(vars.at(1)), *href.GetYaxis(), yvar, offset ? &offset[1] : nullptr);
651  }
652 
653  if (vars.at(2)) {
654  auto zvar = static_cast<RooRealVar*>(_vars.find(*vars.at(2)));
655  if (zvar)
656  _adjustBinning(*static_cast<RooRealVar*>(vars.at(2)), *href.GetZaxis(), zvar, offset ? &offset[2] : nullptr);
657  }
658 
659 }
660 
661 
662 namespace {
663 /// Clone external weight arrays, unless the external array is nullptr.
664 void cloneArray(double*& ours, const double* theirs, std::size_t n) {
665  if (ours) delete[] ours;
666  ours = nullptr;
667  if (!theirs) return;
668  ours = new double[n];
669  std::copy(theirs, theirs+n, ours);
670 }
671 
672 /// Allocate and initialise an array with desired size and values.
673 void initArray(double*& arr, std::size_t n, double val) {
674  if (arr) delete[] arr;
675  arr = nullptr;
676  if (n == 0) return;
677  arr = new double[n];
678  std::fill(arr, arr+n, val);
679 }
680 }
681 
682 
683 ////////////////////////////////////////////////////////////////////////////////
684 /// Initialization procedure: allocate weights array, calculate
685 /// multipliers needed for N-space to 1-dim array jump table,
686 /// and fill the internal tree with all bin center coordinates
687 
688 void RooDataHist::initialize(const char* binningName, Bool_t fillTree)
689 {
690 
691  // Save real dimensions of dataset separately
692  for (const auto real : _vars) {
693  if (dynamic_cast<RooAbsReal*>(real)) _realVars.add(*real);
694  }
695 
696  _lvvars.clear();
697  _lvbins.clear();
698 
699  // Fill array of LValue pointers to variables
700  for (unsigned int i = 0; i < _vars.size(); ++i) {
701  if (binningName) {
702  RooRealVar* rrv = dynamic_cast<RooRealVar*>(_vars[i]);
703  if (rrv) {
704  rrv->setBinning(rrv->getBinning(binningName));
705  }
706  }
707 
708  auto lvarg = dynamic_cast<RooAbsLValue*>(_vars[i]);
709  assert(lvarg);
710  _lvvars.push_back(lvarg);
711 
712  const RooAbsBinning* binning = lvarg->getBinningPtr(0);
713  _lvbins.emplace_back(binning ? binning->clone() : nullptr);
714  }
715 
716 
717  // Allocate coefficients array
718  _idxMult.resize(_vars.getSize()) ;
719 
720  _arrSize = 1 ;
721  unsigned int n = 0u;
722  for (const auto var : _vars) {
723  auto arg = dynamic_cast<const RooAbsLValue*>(var);
724  assert(arg);
725 
726  // Calculate sub-index multipliers for master index
727  for (unsigned int i = 0u; i<n; i++) {
728  _idxMult[i] *= arg->numBins() ;
729  }
730  _idxMult[n++] = 1 ;
731 
732  // Calculate dimension of weight array
733  _arrSize *= arg->numBins() ;
734  }
735 
736  // Allocate and initialize weight array if necessary
737  if (!_wgt) {
738  initArray(_wgt, _arrSize, 0.);
739  delete[] _errLo; _errLo = nullptr;
740  delete[] _errHi; _errHi = nullptr;
741  delete[] _sumw2; _sumw2 = nullptr;
742  initArray(_binv, _arrSize, 0.);
743 
744  // Refill array pointers in data store when reading
745  // from Streamer
746  if (!fillTree) {
748  }
749  }
750 
751  if (!fillTree) return ;
752 
753  // Fill TTree with bin center coordinates
754  // Calculate plot bins of components from master index
755 
756  for (Int_t ibin=0 ; ibin < _arrSize ; ibin++) {
757  Int_t j(0), idx(0), tmp(ibin) ;
758  Double_t theBinVolume(1) ;
759  for (auto arg2 : _lvvars) {
760  idx = tmp / _idxMult[j] ;
761  tmp -= idx*_idxMult[j++] ;
762  arg2->setBin(idx) ;
763  theBinVolume *= arg2->getBinWidth(idx) ;
764  }
765  _binv[ibin] = theBinVolume ;
766 
767  fill() ;
768  }
769 
770 
771 }
772 
773 
774 ////////////////////////////////////////////////////////////////////////////////
775 
777 {
778  if (!_binbounds.empty()) return;
779  for (auto& it : _lvbins) {
780  _binbounds.push_back(std::vector<Double_t>());
781  if (it) {
782  std::vector<Double_t>& bounds = _binbounds.back();
783  bounds.reserve(2 * it->numBins());
784  for (Int_t i = 0; i < it->numBins(); ++i) {
785  bounds.push_back(it->binLow(i));
786  bounds.push_back(it->binHigh(i));
787  }
788  }
789  }
790 }
791 
792 
793 ////////////////////////////////////////////////////////////////////////////////
794 /// Copy constructor
795 
796 RooDataHist::RooDataHist(const RooDataHist& other, const char* newname) :
797  RooAbsData(other,newname), RooDirItem(), _arrSize(other._arrSize), _idxMult(other._idxMult), _pbinvCacheMgr(other._pbinvCacheMgr,0)
798 {
799  // Allocate and initialize weight array
800  assert(_arrSize == other._arrSize);
801  cloneArray(_wgt, other._wgt, other._arrSize);
802  cloneArray(_errLo, other._errLo, other._arrSize);
803  cloneArray(_errHi, other._errHi, other._arrSize);
804  cloneArray(_binv, other._binv, other._arrSize);
805  cloneArray(_sumw2, other._sumw2, other._arrSize);
806 
807  // Save real dimensions of dataset separately
808  for (const auto arg : _vars) {
809  if (dynamic_cast<RooAbsReal*>(arg) != nullptr) _realVars.add(*arg) ;
810  }
811 
812  // Fill array of LValue pointers to variables
813  for (const auto rvarg : _vars) {
814  auto lvarg = dynamic_cast<RooAbsLValue*>(rvarg);
815  assert(lvarg);
816  _lvvars.push_back(lvarg);
817  const RooAbsBinning* binning = lvarg->getBinningPtr(0);
818  _lvbins.emplace_back(binning ? binning->clone() : 0) ;
819  }
820 
822 
823  appendToDir(this,kTRUE) ;
824 }
825 
826 
827 
828 ////////////////////////////////////////////////////////////////////////////////
829 /// Constructor of a data hist from (part of) an existing data hist. The dimensions
830 /// of the data set are defined by the 'vars' RooArgSet, which can be identical
831 /// to 'dset' dimensions, or a subset thereof. Reduced dimensions will be projected
832 /// in the output data hist. The optional 'cutVar' formula variable can used to
833 /// select the subset of bins to be copied.
834 ///
835 /// For most uses the RooAbsData::reduce() wrapper function, which uses this constructor,
836 /// is the most convenient way to create a subset of an existing data
837 
838 RooDataHist::RooDataHist(const char* name, const char* title, RooDataHist* h, const RooArgSet& varSubset,
839  const RooFormulaVar* cutVar, const char* cutRange, Int_t nStart, Int_t nStop, Bool_t copyCache) :
840  RooAbsData(name,title,varSubset),
841  _pbinvCacheMgr(0,10)
842 {
843  // Initialize datastore
844  _dstore = new RooTreeDataStore(name,title,*h->_dstore,_vars,cutVar,cutRange,nStart,nStop,copyCache) ;
845 
846  initialize(0,kFALSE) ;
847 
848  // Copy weight array etc
849  assert(_arrSize == h->_arrSize);
850  cloneArray(_wgt, h->_wgt, _arrSize);
851  cloneArray(_errLo, h->_errLo, _arrSize);
852  cloneArray(_errHi, h->_errHi, _arrSize);
853  cloneArray(_binv, h->_binv, _arrSize);
854  cloneArray(_sumw2, h->_sumw2, _arrSize);
855 
857 
858  appendToDir(this,kTRUE) ;
860 }
861 
862 
863 ////////////////////////////////////////////////////////////////////////////////
864 /// Construct a clone of this dataset that contains only the cached variables
865 
866 RooAbsData* RooDataHist::cacheClone(const RooAbsArg* newCacheOwner, const RooArgSet* newCacheVars, const char* newName)
867 {
868  checkInit() ;
869 
870  RooDataHist* dhist = new RooDataHist(newName?newName:GetName(),GetTitle(),this,*get(),0,0,0,2000000000,kTRUE) ;
871 
872  RooArgSet* selCacheVars = (RooArgSet*) newCacheVars->selectCommon(dhist->_cachedVars) ;
873  dhist->attachCache(newCacheOwner, *selCacheVars) ;
874  delete selCacheVars ;
875 
876  return dhist ;
877 }
878 
879 
880 
881 ////////////////////////////////////////////////////////////////////////////////
882 /// Implementation of RooAbsData virtual method that drives the RooAbsData::reduce() methods
883 
884 RooAbsData* RooDataHist::reduceEng(const RooArgSet& varSubset, const RooFormulaVar* cutVar, const char* cutRange,
885  std::size_t nStart, std::size_t nStop, Bool_t /*copyCache*/)
886 {
887  checkInit() ;
888  RooArgSet* myVarSubset = (RooArgSet*) _vars.selectCommon(varSubset) ;
889  RooDataHist *rdh = new RooDataHist(GetName(), GetTitle(), *myVarSubset) ;
890  delete myVarSubset ;
891 
892  RooFormulaVar* cloneVar = 0;
893  RooArgSet* tmp(0) ;
894  if (cutVar) {
895  // Deep clone cutVar and attach clone to this dataset
896  tmp = (RooArgSet*) RooArgSet(*cutVar).snapshot() ;
897  if (!tmp) {
898  coutE(DataHandling) << "RooDataHist::reduceEng(" << GetName() << ") Couldn't deep-clone cut variable, abort," << endl ;
899  return 0 ;
900  }
901  cloneVar = (RooFormulaVar*) tmp->find(*cutVar) ;
902  cloneVar->attachDataSet(*this) ;
903  }
904 
905  Double_t lo,hi ;
906  const std::size_t nevt = nStop < static_cast<std::size_t>(numEntries()) ? nStop : static_cast<std::size_t>(numEntries());
907  for (auto i=nStart; i<nevt ; i++) {
908  const RooArgSet* row = get(i) ;
909 
910  Bool_t doSelect(kTRUE) ;
911  if (cutRange) {
912  for (const auto arg : *row) {
913  if (!arg->inRange(cutRange)) {
914  doSelect = kFALSE ;
915  break ;
916  }
917  }
918  }
919  if (!doSelect) continue ;
920 
921  if (!cloneVar || cloneVar->getVal()) {
922  weightError(lo,hi,SumW2) ;
923  rdh->add(*row,weight(),lo*lo) ;
924  }
925  }
926 
927  if (cloneVar) {
928  delete tmp ;
929  }
930 
931  return rdh ;
932 }
933 
934 
935 
936 ////////////////////////////////////////////////////////////////////////////////
937 /// Destructor
938 
940 {
941  delete[] _wgt;
942  delete[] _errLo;
943  delete[] _errHi;
944  delete[] _sumw2;
945  delete[] _binv;
946 
947  removeFromDir(this) ;
949 }
950 
951 
952 
953 
954 ////////////////////////////////////////////////////////////////////////////////
955 /// Calculate bin number of the given coordinates. If only a subset of the internal
956 /// coordinates are passed, the missing coordinates are taken at their current value.
957 /// \param[in] coord Variables that are representing the coordinates.
958 /// \param[in] fast If the variables in `coord` and the ones of the data hist have the
959 /// same size and layout, `fast` can be set to skip checking that all variables are
960 /// present in `coord`.
961 Int_t RooDataHist::getIndex(const RooArgSet& coord, Bool_t fast) const {
962  checkInit() ;
963  return calcTreeIndex(coord, fast);
964 }
965 
966 
967 
968 
969 ////////////////////////////////////////////////////////////////////////////////
970 /// Calculate the bin index corresponding to the coordinates passed as argument.
971 /// \param[in] coords Coordinates. Is `fast == false`, these can be partial.
972 /// \param[in] fast Promise that the coordinates in `coords` have the same order
973 /// as the internal coordinates. In this case, values are looked up only by index.
974 std::size_t RooDataHist::calcTreeIndex(const RooArgSet& coords, bool fast) const
975 {
976  // With fast, caller promises that layout of "coords" is identical to our internal "vars"
977  assert(!fast || _vars.size() == coords.size());
978 
979  if (&_vars == &coords)
980  fast = true;
981 
982  std::size_t masterIdx = 0;
983 
984  for (unsigned int i=0; i < _vars.size(); ++i) {
985  const RooAbsArg* internalVar = _vars[i];
986  const RooAbsBinning* binning = _lvbins[i].get();
987 
988  // Find the variable that we need values from.
989  // That's either the variable directly from the external coordinates
990  // or we find the external one that has the same name as "internalVar".
991  const RooAbsArg* theVar = fast ? coords[i] : coords.find(*internalVar);
992  if (!theVar) {
993  // Variable is not in external coordinates. Use current internal value.
994  theVar = internalVar;
995  }
996 
997  if (binning) {
998  assert(dynamic_cast<const RooAbsReal*>(theVar));
999  const double val = static_cast<const RooAbsReal*>(theVar)->getVal();
1000  masterIdx += _idxMult[i] * binning->binNumber(val);
1001  } else {
1002  // We are a category. No binning.
1003  assert(dynamic_cast<const RooAbsCategoryLValue*>(theVar));
1004  auto cat = static_cast<const RooAbsCategoryLValue*>(theVar);
1005  masterIdx += _idxMult[i] * cat->getBin(static_cast<const char*>(nullptr));
1006  }
1007  }
1008 
1009  return masterIdx ;
1010 }
1011 
1012 
1013 
1014 ////////////////////////////////////////////////////////////////////////////////
1015 /// Debug stuff, should go...
1016 
1018 {
1019  cout << "_arrSize = " << _arrSize << endl ;
1020  for (Int_t i=0 ; i < _arrSize ; i++) {
1021  cout << "wgt[" << i << "] = " << _wgt[i]
1022  << "\tsumw2[" << i << "] = " << (_sumw2 ? _sumw2[i] : -1.)
1023  << "\tvol[" << i << "] = " << _binv[i] << endl ;
1024  }
1025 }
1026 
1027 
1028 
1029 ////////////////////////////////////////////////////////////////////////////////
1030 /// Back end function to plotting functionality. Plot RooDataHist on given
1031 /// frame in mode specified by plot options 'o'. The main purpose of
1032 /// this function is to match the specified binning on 'o' to the
1033 /// internal binning of the plot observable in this RooDataHist.
1034 /// \see RooAbsData::plotOn() for plotting options.
1036 {
1037  checkInit() ;
1038  if (o.bins) return RooAbsData::plotOn(frame,o) ;
1039 
1040  if(0 == frame) {
1041  coutE(InputArguments) << ClassName() << "::" << GetName() << ":plotOn: frame is null" << endl;
1042  return 0;
1043  }
1044  RooAbsRealLValue *var= (RooAbsRealLValue*) frame->getPlotVar();
1045  if(0 == var) {
1046  coutE(InputArguments) << ClassName() << "::" << GetName()
1047  << ":plotOn: frame does not specify a plot variable" << endl;
1048  return 0;
1049  }
1050 
1051  RooRealVar* dataVar = (RooRealVar*) _vars.find(*var) ;
1052  if (!dataVar) {
1053  coutE(InputArguments) << ClassName() << "::" << GetName()
1054  << ":plotOn: dataset doesn't contain plot frame variable" << endl;
1055  return 0;
1056  }
1057 
1058  o.bins = &dataVar->getBinning() ;
1060  return RooAbsData::plotOn(frame,o) ;
1061 }
1062 
1063 
1064 ////////////////////////////////////////////////////////////////////////////////
1065 /// Return the weight at given coordinates with optional interpolation.
1066 /// \param[in] bin Coordinates for which the weight should be calculated.
1067 /// \param[in] intOrder If zero, the bare weight for the bin enclosing the coordinatesis returned.
1068 /// For higher values, the result is interpolated in the real dimensions of the dataset.
1069 /// \param[in] correctForBinSize
1070 /// \param[in] cdfBoundaries
1071 /// \param[in] oneSafe Ignored.
1072 
1073 Double_t RooDataHist::weight(const RooArgSet& bin, Int_t intOrder, Bool_t correctForBinSize, Bool_t cdfBoundaries, Bool_t /*oneSafe*/)
1074 {
1075  checkInit() ;
1076 
1077  // Handle illegal intOrder values
1078  if (intOrder<0) {
1079  coutE(InputArguments) << "RooDataHist::weight(" << GetName() << ") ERROR: interpolation order must be positive" << endl ;
1080  return 0 ;
1081  }
1082 
1083  // Handle no-interpolation case
1084  if (intOrder==0) {
1085  const auto idx = calcTreeIndex(bin, false);
1086  if (correctForBinSize) {
1087  return get_wgt(idx) / _binv[idx];
1088  } else {
1089  return get_wgt(idx);
1090  }
1091  }
1092 
1093  // Handle all interpolation cases
1094  _vars.assignValueOnly(bin) ;
1095 
1096  Double_t wInt(0) ;
1097  if (_realVars.getSize()==1) {
1098 
1099  // 1-dimensional interpolation
1100  const auto real = static_cast<RooRealVar*>(_realVars[static_cast<std::size_t>(0)]);
1101  const RooAbsBinning* binning = real->getBinningPtr(0) ;
1102  wInt = interpolateDim(*real,binning,((RooAbsReal*)bin.find(*real))->getVal(), intOrder, correctForBinSize, cdfBoundaries) ;
1103 
1104  } else if (_realVars.getSize()==2) {
1105 
1106  // 2-dimensional interpolation
1107  const auto realX = static_cast<RooRealVar*>(_realVars[static_cast<std::size_t>(0)]);
1108  const auto realY = static_cast<RooRealVar*>(_realVars[static_cast<std::size_t>(1)]);
1109  Double_t xval = ((RooAbsReal*)bin.find(*realX))->getVal() ;
1110  Double_t yval = ((RooAbsReal*)bin.find(*realY))->getVal() ;
1111 
1112  Int_t ybinC = realY->getBin() ;
1113  Int_t ybinLo = ybinC-intOrder/2 - ((yval<realY->getBinning().binCenter(ybinC))?1:0) ;
1114  Int_t ybinM = realY->numBins() ;
1115 
1116  Int_t i ;
1117  Double_t yarr[10] ;
1118  Double_t xarr[10] ;
1119  const RooAbsBinning* binning = realX->getBinningPtr(0) ;
1120  for (i=ybinLo ; i<=intOrder+ybinLo ; i++) {
1121  Int_t ibin ;
1122  if (i>=0 && i<ybinM) {
1123  // In range
1124  ibin = i ;
1125  realY->setBin(ibin) ;
1126  xarr[i-ybinLo] = realY->getVal() ;
1127  } else if (i>=ybinM) {
1128  // Overflow: mirror
1129  ibin = 2*ybinM-i-1 ;
1130  realY->setBin(ibin) ;
1131  xarr[i-ybinLo] = 2*realY->getMax()-realY->getVal() ;
1132  } else {
1133  // Underflow: mirror
1134  ibin = -i -1;
1135  realY->setBin(ibin) ;
1136  xarr[i-ybinLo] = 2*realY->getMin()-realY->getVal() ;
1137  }
1138  yarr[i-ybinLo] = interpolateDim(*realX,binning,xval,intOrder,correctForBinSize,kFALSE) ;
1139  }
1140 
1141  if (gDebug>7) {
1142  cout << "RooDataHist interpolating data is" << endl ;
1143  cout << "xarr = " ;
1144  for (int q=0; q<=intOrder ; q++) cout << xarr[q] << " " ;
1145  cout << " yarr = " ;
1146  for (int q=0; q<=intOrder ; q++) cout << yarr[q] << " " ;
1147  cout << endl ;
1148  }
1149  wInt = RooMath::interpolate(xarr,yarr,intOrder+1,yval) ;
1150 
1151  } else {
1152 
1153  // Higher dimensional scenarios not yet implemented
1154  coutE(InputArguments) << "RooDataHist::weight(" << GetName() << ") interpolation in "
1155  << _realVars.getSize() << " dimensions not yet implemented" << endl ;
1156  return weight(bin,0) ;
1157 
1158  }
1159 
1160  return wInt ;
1161 }
1162 
1163 
1164 
1165 
1166 ////////////////////////////////////////////////////////////////////////////////
1167 /// Return the error of current weight.
1168 /// \param[out] lo Low error.
1169 /// \param[out] hi High error.
1170 /// \param[in] etype Type of error to compute. May throw if not supported.
1171 /// Supported errors are
1172 /// - `Poisson` Default. Asymmetric Poisson errors (68% CL).
1173 /// - `SumW2` The square root of the sum of weights. (Symmetric).
1174 /// - `None` Return zero.
1176 {
1177  checkInit() ;
1178 
1179  switch (etype) {
1180 
1181  case Auto:
1182  throw std::invalid_argument(Form("RooDataHist::weightError(%s) error type Auto not allowed here",GetName())) ;
1183  break ;
1184 
1185  case Expected:
1186  throw std::invalid_argument(Form("RooDataHist::weightError(%s) error type Expected not allowed here",GetName())) ;
1187  break ;
1188 
1189  case Poisson:
1190  if (get_curWgtErrLo() >= 0) {
1191  // Weight is preset or precalculated
1192  lo = get_curWgtErrLo();
1193  hi = get_curWgtErrHi();
1194  return ;
1195  }
1196 
1197  if (!_errLo || !_errHi) {
1198  // We didn't track asymmetric errors so far, so now we need to allocate
1199  initArray(_errLo, _arrSize, -1.);
1200  initArray(_errHi, _arrSize, -1.);
1202  }
1203 
1204  // Calculate poisson errors
1205  Double_t ym,yp ;
1207  _errLo[_curIndex] = weight()-ym;
1208  _errHi[_curIndex] = yp-weight();
1209  lo = _errLo[_curIndex];
1210  hi = _errHi[_curIndex];
1211  return ;
1212 
1213  case SumW2:
1214  lo = sqrt(get_curSumW2());
1215  hi = lo;
1216  return ;
1217 
1218  case None:
1219  lo = 0 ;
1220  hi = 0 ;
1221  return ;
1222  }
1223 }
1224 
1225 
1226 // wve adjust for variable bin sizes
1227 
1228 ////////////////////////////////////////////////////////////////////////////////
1229 /// Perform boundary safe 'intOrder'-th interpolation of weights in dimension 'dim'
1230 /// at current value 'xval'
1231 
1232 Double_t RooDataHist::interpolateDim(RooRealVar& dim, const RooAbsBinning* binning, Double_t xval, Int_t intOrder, Bool_t correctForBinSize, Bool_t cdfBoundaries)
1233 {
1234  // Fill workspace arrays spanning interpolation area
1235  Int_t fbinC = dim.getBin(*binning) ;
1236  Int_t fbinLo = fbinC-intOrder/2 - ((xval<binning->binCenter(fbinC))?1:0) ;
1237  Int_t fbinM = dim.numBins(*binning) ;
1238 
1239 
1240  Int_t i ;
1241  Double_t yarr[10] ;
1242  Double_t xarr[10] ;
1243  for (i=fbinLo ; i<=intOrder+fbinLo ; i++) {
1244  Int_t ibin ;
1245  if (i>=0 && i<fbinM) {
1246  // In range
1247  ibin = i ;
1248  dim.setBinFast(ibin,*binning) ;
1249  //cout << "INRANGE: dim.getVal(ibin=" << ibin << ") = " << dim.getVal() << endl ;
1250  xarr[i-fbinLo] = dim.getVal() ;
1251  Int_t idx = calcTreeIndex(_vars, true);
1252  yarr[i - fbinLo] = get_wgt(idx);
1253  if (correctForBinSize) yarr[i-fbinLo] /= _binv[idx] ;
1254  } else if (i>=fbinM) {
1255  // Overflow: mirror
1256  ibin = 2*fbinM-i-1 ;
1257  dim.setBinFast(ibin,*binning) ;
1258  //cout << "OVERFLOW: dim.getVal(ibin=" << ibin << ") = " << dim.getVal() << endl ;
1259  if (cdfBoundaries) {
1260  xarr[i-fbinLo] = dim.getMax()+1e-10*(i-fbinM+1) ;
1261  yarr[i-fbinLo] = 1.0 ;
1262  } else {
1263  Int_t idx = calcTreeIndex(_vars, true) ;
1264  xarr[i-fbinLo] = 2*dim.getMax()-dim.getVal() ;
1265  yarr[i - fbinLo] = get_wgt(idx);
1266  if (correctForBinSize)
1267  yarr[i - fbinLo] /= _binv[idx];
1268  }
1269  } else {
1270  // Underflow: mirror
1271  ibin = -i - 1 ;
1272  dim.setBinFast(ibin,*binning) ;
1273  //cout << "UNDERFLOW: dim.getVal(ibin=" << ibin << ") = " << dim.getVal() << endl ;
1274  if (cdfBoundaries) {
1275  xarr[i-fbinLo] = dim.getMin()-ibin*(1e-10) ; ;
1276  yarr[i-fbinLo] = 0.0 ;
1277  } else {
1278  Int_t idx = calcTreeIndex(_vars, true) ;
1279  xarr[i-fbinLo] = 2*dim.getMin()-dim.getVal() ;
1280  yarr[i - fbinLo] = get_wgt(idx);
1281  if (correctForBinSize)
1282  yarr[i - fbinLo] /= _binv[idx];
1283  }
1284  }
1285  //cout << "ibin = " << ibin << endl ;
1286  }
1287 // for (int k=0 ; k<=intOrder ; k++) {
1288 // cout << "k=" << k << " x = " << xarr[k] << " y = " << yarr[k] << endl ;
1289 // }
1290  dim.setBinFast(fbinC,*binning) ;
1291  Double_t ret = RooMath::interpolate(xarr,yarr,intOrder+1,xval) ;
1292  return ret ;
1293 }
1294 
1295 
1296 
1297 
1298 ////////////////////////////////////////////////////////////////////////////////
1299 /// Increment the bin content of the bin enclosing the given coordinates.
1300 ///
1301 /// \param[in] row Coordinates of the bin.
1302 /// \param[in] wgt Increment by this weight.
1303 /// \param[in] sumw2 Optionally, track the sum of squared weights. If a value > 0 or
1304 /// a weight != 1. is passed for the first time, a vector for the squared weights will be allocated.
1305 void RooDataHist::add(const RooArgSet& row, Double_t wgt, Double_t sumw2)
1306 {
1307  checkInit() ;
1308 
1309  if ((sumw2 > 0. || wgt != 1.) && !_sumw2) {
1310  // Receiving a weighted entry. SumW2 != sumw from now on.
1311  _sumw2 = new double[_arrSize];
1312  std::copy(_wgt, _wgt+_arrSize, _sumw2);
1313 
1315  }
1316 
1317  const auto idx = calcTreeIndex(row, false);
1318 
1319  _wgt[idx] += wgt ;
1320  if (_sumw2) _sumw2[idx] += (sumw2 > 0 ? sumw2 : wgt*wgt);
1321 
1322  _cache_sum_valid = false;
1323 }
1324 
1325 
1326 
1327 ////////////////////////////////////////////////////////////////////////////////
1328 /// Set a bin content.
1329 /// \param[in] row Coordinates of the bin to be set.
1330 /// \param[in] wgt New bin content.
1331 /// \param[in] wgtErrLo Low error of the bin content.
1332 /// \param[in] wgtErrHi High error of the bin content.
1333 void RooDataHist::set(const RooArgSet& row, Double_t wgt, Double_t wgtErrLo, Double_t wgtErrHi)
1334 {
1335  checkInit() ;
1336 
1337  if (!_errLo || !_errHi) {
1338  initArray(_errLo, _arrSize, -1.);
1339  initArray(_errHi, _arrSize, -1.);
1341  }
1342 
1343  const auto idx = calcTreeIndex(row, false);
1344 
1345  _wgt[idx] = wgt ;
1346  _errLo[idx] = wgtErrLo ;
1347  _errHi[idx] = wgtErrHi ;
1348 
1349  _cache_sum_valid = false;
1350 }
1351 
1352 
1353 
1354 ////////////////////////////////////////////////////////////////////////////////
1355 /// Set bin content of bin that was last loaded with get(std::size_t).
1356 /// \param[in] binNumber Optional bin number to set. If empty, currently active bin is set.
1357 /// \param[in] wgt New bin content.
1358 /// \param[in] wgtErr Error of the new bin content. If the weight need not have an error, use 0. or a negative number.
1359 void RooDataHist::set(std::size_t binNumber, double wgt, double wgtErr) {
1360  checkInit() ;
1361 
1362  if (wgtErr > 0. && !_sumw2) {
1363  // Receiving a weighted entry. Need to track sumw2 from now on:
1364  cloneArray(_sumw2, _wgt, _arrSize);
1365 
1367  }
1368 
1369  _wgt[binNumber] = wgt ;
1370  if (_errLo) _errLo[binNumber] = wgtErr;
1371  if (_errHi) _errHi[binNumber] = wgtErr;
1372  if (_sumw2) _sumw2[binNumber] = wgtErr*wgtErr;
1373 
1375 }
1376 
1377 
1378 ////////////////////////////////////////////////////////////////////////////////
1379 /// Set bin content of bin that was last loaded with get(std::size_t).
1380 /// \deprecated Prefer set(std::size_t, double, double).
1381 /// \param[in] wgt New bin content.
1382 /// \param[in] wgtErr Optional error of the bin content.
1383 void RooDataHist::set(double wgt, double wgtErr) {
1384  if (_curIndex == std::numeric_limits<std::size_t>::max()) {
1385  _curIndex = calcTreeIndex(_vars, true) ;
1386  }
1387 
1388  set(_curIndex, wgt, wgtErr);
1389 }
1390 
1391 
1392 ////////////////////////////////////////////////////////////////////////////////
1393 /// Set a bin content.
1394 /// \param[in] row Coordinates to compute the bin from.
1395 /// \param[in] wgt New bin content.
1396 /// \param[in] wgtErr Optional error of the bin content.
1397 void RooDataHist::set(const RooArgSet& row, Double_t wgt, Double_t wgtErr) {
1398  set(calcTreeIndex(row, false), wgt, wgtErr);
1399 }
1400 
1401 
1402 
1403 ////////////////////////////////////////////////////////////////////////////////
1404 /// Add all data points contained in 'dset' to this data set with given weight.
1405 /// Optional cut string expression selects the data points to be added and can
1406 /// reference any variable contained in this data set
1407 
1408 void RooDataHist::add(const RooAbsData& dset, const char* cut, Double_t wgt)
1409 {
1410  RooFormulaVar cutVar("select",cut,*dset.get()) ;
1411  add(dset,&cutVar,wgt) ;
1412 }
1413 
1414 
1415 
1416 ////////////////////////////////////////////////////////////////////////////////
1417 /// Add all data points contained in 'dset' to this data set with given weight.
1418 /// Optional RooFormulaVar pointer selects the data points to be added.
1419 
1420 void RooDataHist::add(const RooAbsData& dset, const RooFormulaVar* cutVar, Double_t wgt)
1421 {
1422  checkInit() ;
1423 
1424  RooFormulaVar* cloneVar = 0;
1425  RooArgSet* tmp(0) ;
1426  if (cutVar) {
1427  // Deep clone cutVar and attach clone to this dataset
1428  tmp = (RooArgSet*) RooArgSet(*cutVar).snapshot() ;
1429  if (!tmp) {
1430  coutE(DataHandling) << "RooDataHist::add(" << GetName() << ") Couldn't deep-clone cut variable, abort," << endl ;
1431  return ;
1432  }
1433 
1434  cloneVar = (RooFormulaVar*) tmp->find(*cutVar) ;
1435  cloneVar->attachDataSet(dset) ;
1436  }
1437 
1438 
1439  Int_t i ;
1440  for (i=0 ; i<dset.numEntries() ; i++) {
1441  const RooArgSet* row = dset.get(i) ;
1442  if (!cloneVar || cloneVar->getVal()) {
1443  add(*row,wgt*dset.weight(), wgt*wgt*dset.weightSquared()) ;
1444  }
1445  }
1446 
1447  if (cloneVar) {
1448  delete tmp ;
1449  }
1450 
1452 }
1453 
1454 
1455 
1456 ////////////////////////////////////////////////////////////////////////////////
1457 /// Return the sum of the weights of all bins in the histogram.
1458 ///
1459 /// \param[in] correctForBinSize Multiply the sum of weights in each bin
1460 /// with the N-dimensional bin volume, making the return value
1461 /// the integral over the function represented by this histogram.
1462 /// \param[in] inverseBinCor Divide by the N-dimensional bin volume.
1463 Double_t RooDataHist::sum(Bool_t correctForBinSize, Bool_t inverseBinCor) const
1464 {
1465  checkInit() ;
1466 
1467  // Check if result was cached
1468  const CacheSumState_t cache_code = !correctForBinSize ? kNoBinCorrection : (inverseBinCor ? kInverseBinCorr : kCorrectForBinSize);
1469  if (_cache_sum_valid == static_cast<Int_t>(cache_code)) {
1470  return _cache_sum ;
1471  }
1472 
1474  for (Int_t i=0; i < _arrSize; i++) {
1475  const double theBinVolume = correctForBinSize ? (inverseBinCor ? 1/_binv[i] : _binv[i]) : 1.0 ;
1476  kahanSum += get_wgt(i) * theBinVolume;
1477  }
1478 
1479  // Store result in cache
1480  _cache_sum_valid = cache_code;
1481  _cache_sum = kahanSum;
1482 
1483  return kahanSum;
1484 }
1485 
1486 
1487 
1488 ////////////////////////////////////////////////////////////////////////////////
1489 /// Return the sum of the weights of a multi-dimensional slice of the histogram
1490 /// by summing only over the dimensions specified in sumSet.
1491 ///
1492 /// The coordinates of all other dimensions are fixed to those given in sliceSet
1493 ///
1494 /// If correctForBinSize is specified, the sum of weights
1495 /// is multiplied by the M-dimensional bin volume, (M = N(sumSet)),
1496 /// making the return value the integral over the function
1497 /// represented by this histogram
1498 
1499 Double_t RooDataHist::sum(const RooArgSet& sumSet, const RooArgSet& sliceSet, Bool_t correctForBinSize, Bool_t inverseBinCor)
1500 {
1501  checkInit() ;
1502 
1503  RooArgSet varSave ;
1504  varSave.addClone(_vars) ;
1505 
1506  RooArgSet sliceOnlySet(sliceSet);
1507  sliceOnlySet.remove(sumSet,kTRUE,kTRUE) ;
1508 
1509  _vars = sliceOnlySet;
1510  const std::vector<double>& pbinv = calculatePartialBinVolume(sliceOnlySet);
1511 
1512  // Calculate mask and refence plot bins for non-iterating variables
1513  Bool_t* mask = new Bool_t[_vars.getSize()] ;
1514  Int_t* refBin = new Int_t[_vars.getSize()] ;
1515 
1516  for (unsigned int i = 0; i < _vars.size(); ++i) {
1517  const RooAbsArg* arg = _vars[i];
1518  const RooAbsLValue* argLv = _lvvars[i]; // Same as above, but cross-cast
1519 
1520  if (sumSet.find(*arg)) {
1521  mask[i] = kFALSE ;
1522  } else {
1523  mask[i] = kTRUE ;
1524  refBin[i] = argLv->getBin();
1525  }
1526  }
1527 
1528  // Loop over entire data set, skipping masked entries
1530  for (Int_t ibin=0; ibin < _arrSize; ++ibin) {
1531 
1532  std::size_t tmpibin = ibin;
1533  Bool_t skip(kFALSE) ;
1534 
1535  // Check if this bin belongs in selected slice
1536  for (unsigned int ivar = 0; !skip && ivar < _vars.size(); ++ivar) {
1537  const Int_t idx = tmpibin / _idxMult[ivar] ;
1538  tmpibin -= idx*_idxMult[ivar] ;
1539  if (mask[ivar] && idx!=refBin[ivar])
1540  skip=kTRUE ;
1541  }
1542 
1543  if (!skip) {
1544  const double theBinVolume = correctForBinSize ? (inverseBinCor ? 1/pbinv[_vars.size()] : pbinv[_vars.size()] ) : 1.0 ;
1545  total += get_wgt(ibin) * theBinVolume;
1546  }
1547  }
1548 
1549  delete[] mask ;
1550  delete[] refBin ;
1551 
1552  _vars = varSave ;
1553 
1554  return total;
1555 }
1556 
1557 ////////////////////////////////////////////////////////////////////////////////
1558 /// Return the sum of the weights of a multi-dimensional slice of the histogram
1559 /// by summing only over the dimensions specified in sumSet.
1560 ///
1561 /// The coordinates of all other dimensions are fixed to those given in sliceSet
1562 ///
1563 /// If correctForBinSize is specified, the sum of weights
1564 /// is multiplied by the M-dimensional bin volume, (M = N(sumSet)),
1565 /// or the fraction of it that falls inside the range rangeName,
1566 /// making the return value the integral over the function
1567 /// represented by this histogram.
1568 ///
1569 /// If correctForBinSize is not specified, the weights are multiplied by the
1570 /// fraction of the bin volume that falls inside the range, i.e. a factor of
1571 /// binVolumeInRange/totalBinVolume.
1572 
1573 Double_t RooDataHist::sum(const RooArgSet& sumSet, const RooArgSet& sliceSet,
1574  Bool_t correctForBinSize, Bool_t inverseBinCor,
1575  const std::map<const RooAbsArg*, std::pair<Double_t, Double_t> >& ranges,
1576  std::function<double(int)> getBinScale)
1577 {
1578  checkInit();
1579  checkBinBounds();
1580  RooArgSet varSave;
1581  varSave.addClone(_vars);
1582  {
1583  RooArgSet sliceOnlySet(sliceSet);
1584  sliceOnlySet.remove(sumSet,kTRUE,kTRUE);
1585  _vars = sliceOnlySet;
1586  }
1587 
1588  // Calculate mask and reference plot bins for non-iterating variables,
1589  // and get ranges for iterating variables
1590  std::vector<bool> mask(_vars.getSize());
1591  std::vector<Int_t> refBin(_vars.getSize());
1592  std::vector<Double_t> rangeLo(_vars.getSize(), -std::numeric_limits<Double_t>::infinity());
1593  std::vector<Double_t> rangeHi(_vars.getSize(), +std::numeric_limits<Double_t>::infinity());
1594 
1595  for (std::size_t i = 0; i < _vars.size(); ++i) {
1596  const RooAbsArg* arg = _vars[i];
1597  const RooAbsLValue* argLV = _lvvars[i]; // Same object as above, but cross cast
1598 
1599  RooAbsArg* sumsetv = sumSet.find(*arg);
1600  RooAbsArg* slicesetv = sliceSet.find(*arg);
1601  mask[i] = !sumsetv;
1602  if (mask[i]) {
1603  assert(argLV);
1604  refBin[i] = argLV->getBin();
1605  }
1606 
1607  auto it = ranges.find(sumsetv ? sumsetv : slicesetv);
1608  if (ranges.end() != it) {
1609  rangeLo[i] = it->second.first;
1610  rangeHi[i] = it->second.second;
1611  }
1612  }
1613 
1614  // Loop over entire data set, skipping masked entries
1615  Double_t total(0), carry(0);
1616  for (Int_t ibin = 0; ibin < _arrSize; ++ibin) {
1617  // Check if this bin belongs in selected slice
1618  Bool_t skip(kFALSE);
1619  for (int ivar = 0, tmp = ibin; !skip && ivar < int(_vars.size()); ++ivar) {
1620  const Int_t idx = tmp / _idxMult[ivar];
1621  tmp -= idx*_idxMult[ivar];
1622  if (mask[ivar] && idx!=refBin[ivar]) skip=kTRUE;
1623  }
1624 
1625  if (skip) continue;
1626 
1627  // work out bin volume
1628  Double_t theBinVolume = 1.;
1629  for (Int_t ivar = 0, tmp = ibin; ivar < (int)_vars.size(); ++ivar) {
1630  const Int_t idx = tmp / _idxMult[ivar];
1631  tmp -= idx*_idxMult[ivar];
1632  if (_binbounds[ivar].empty()) continue;
1633  const Double_t binLo = _binbounds[ivar][2 * idx];
1634  const Double_t binHi = _binbounds[ivar][2 * idx + 1];
1635  if (binHi < rangeLo[ivar] || binLo > rangeHi[ivar]) {
1636  // bin is outside of allowed range - effective bin volume is zero
1637  theBinVolume = 0.;
1638  break;
1639  }
1640  theBinVolume *=
1641  (std::min(rangeHi[ivar], binHi) - std::max(rangeLo[ivar], binLo));
1642  }
1643  const Double_t corrPartial = theBinVolume / _binv[ibin];
1644  if (0. == corrPartial) continue;
1645  const Double_t corr = correctForBinSize ? (inverseBinCor ? 1. / _binv[ibin] : _binv[ibin] ) : 1.0;
1646  const Double_t y = getBinScale(ibin)*(get_wgt(ibin) * corr * corrPartial) - carry;
1647  const Double_t t = total + y;
1648  carry = (t - total) - y;
1649  total = t;
1650  }
1651 
1652  _vars = varSave;
1653 
1654  return total;
1655 }
1656 
1657 
1658 
1659 ////////////////////////////////////////////////////////////////////////////////
1660 /// Fill the transient cache with partial bin volumes with up-to-date
1661 /// values for the partial volume specified by observables 'dimSet'
1662 
1663 const std::vector<double>& RooDataHist::calculatePartialBinVolume(const RooArgSet& dimSet) const
1664 {
1665  // Allocate cache if not yet existing
1666  vector<Double_t> *pbinv = _pbinvCacheMgr.getObj(&dimSet) ;
1667  if (pbinv) {
1668  return *pbinv;
1669  }
1670 
1671  pbinv = new vector<Double_t>(_arrSize);
1672 
1673  // Calculate plot bins of components from master index
1674  Bool_t* selDim = new Bool_t[_vars.getSize()] ;
1675  Int_t i(0) ;
1676  for (const auto v : _vars) {
1677  selDim[i++] = dimSet.find(*v) ? kTRUE : kFALSE ;
1678  }
1679 
1680  // Recalculate partial bin volume cache
1681  for (Int_t ibin=0; ibin < _arrSize ;ibin++) {
1682  Int_t idx(0), tmp(ibin) ;
1683  Double_t theBinVolume(1) ;
1684  for (unsigned int j=0; j < _lvvars.size(); ++j) {
1685  const RooAbsLValue* arg = _lvvars[j];
1686  assert(arg);
1687 
1688  idx = tmp / _idxMult[j];
1689  tmp -= idx*_idxMult[j];
1690  if (selDim[j]) {
1691  theBinVolume *= arg->getBinWidth(idx) ;
1692  }
1693  }
1694  (*pbinv)[ibin] = theBinVolume ;
1695  }
1696 
1697  delete[] selDim ;
1698 
1699  // Put in cache (which takes ownership)
1700  _pbinvCacheMgr.setObj(&dimSet,pbinv) ;
1701 
1702  return *pbinv;
1703 }
1704 
1705 
1706 
1707 ////////////////////////////////////////////////////////////////////////////////
1708 /// Return the number of bins
1709 
1711 {
1712  return RooAbsData::numEntries() ;
1713 }
1714 
1715 
1716 
1717 ////////////////////////////////////////////////////////////////////////////////
1718 /// Sum the weights of all bins.
1720 
1721  if (_maskedWeights.empty()) {
1723  } else {
1725  }
1726 }
1727 
1728 
1729 
1730 ////////////////////////////////////////////////////////////////////////////////
1731 /// Return the sum of weights in all entries matching cutSpec (if specified)
1732 /// and in named range cutRange (if specified)
1733 /// Return the
1734 
1735 Double_t RooDataHist::sumEntries(const char* cutSpec, const char* cutRange) const
1736 {
1737  checkInit() ;
1738 
1739  if (cutSpec==0 && cutRange==0) {
1740  return sumEntries();
1741  } else {
1742 
1743  // Setup RooFormulaVar for cutSpec if it is present
1744  RooFormula* select = 0 ;
1745  if (cutSpec) {
1746  select = new RooFormula("select",cutSpec,*get()) ;
1747  }
1748 
1749  // Otherwise sum the weights in the event
1750  ROOT::Math::KahanSum<> kahanSum;
1751  for (Int_t i=0; i < _arrSize; i++) {
1752  get(i) ;
1753  if ((!_maskedWeights.empty() && _maskedWeights[i] == 0.)
1754  || (select && select->eval() == 0.)
1755  || (cutRange && !_vars.allInRange(cutRange)))
1756  continue;
1757 
1758  kahanSum += weight(i);
1759  }
1760 
1761  if (select) delete select ;
1762 
1763  return kahanSum;
1764  }
1765 }
1766 
1767 
1768 
1769 ////////////////////////////////////////////////////////////////////////////////
1770 /// Reset all bin weights to zero
1771 
1773 {
1774  // WVE DO NOT CALL RooTreeData::reset() for binned
1775  // datasets as this will delete the bin definitions
1776 
1777  std::fill(_wgt, _wgt + _arrSize, 0.);
1778  delete[] _errLo; _errLo = nullptr;
1779  delete[] _errHi; _errHi = nullptr;
1780  delete[] _sumw2; _sumw2 = nullptr;
1781 
1783 
1784  _cache_sum_valid = false;
1785 }
1786 
1787 
1788 
1789 ////////////////////////////////////////////////////////////////////////////////
1790 /// Load bin `binNumber`, and return an argset with the coordinates of the bin centre.
1791 /// \note The argset is owned by this data hist, and this function has a side effect, because
1792 /// it alters the currently active bin.
1793 const RooArgSet* RooDataHist::get(Int_t binNumber) const
1794 {
1795  checkInit() ;
1796  _curIndex = binNumber;
1797 
1798  return RooAbsData::get(_curIndex);
1799 }
1800 
1801 
1802 
1803 ////////////////////////////////////////////////////////////////////////////////
1804 /// Return a RooArgSet with whose coordinates denote the bin centre of the bin
1805 /// enclosing the point in `coord`.
1806 /// \note The argset is owned by this data hist, and this function has a side effect, because
1807 /// it alters the currently active bin.
1808 const RooArgSet* RooDataHist::get(const RooArgSet& coord) const {
1809  return get(calcTreeIndex(coord, false));
1810 }
1811 
1812 
1813 
1814 ////////////////////////////////////////////////////////////////////////////////
1815 /// Return the volume of the bin enclosing coordinates 'coord'.
1817  checkInit() ;
1818  return _binv[calcTreeIndex(coord, false)] ;
1819 }
1820 
1821 
1822 ////////////////////////////////////////////////////////////////////////////////
1823 /// Set all the event weight of all bins to the specified value
1824 
1826 {
1827  for (Int_t i=0 ; i<_arrSize ; i++) {
1828  _wgt[i] = value ;
1829  }
1830 
1832 }
1833 
1834 
1835 
1836 ////////////////////////////////////////////////////////////////////////////////
1837 /// Create an iterator over all bins in a slice defined by the subset of observables
1838 /// listed in sliceArg. The position of the slice is given by otherArgs
1839 
1841 {
1842  // Update to current position
1843  _vars = otherArgs ;
1844  _curIndex = calcTreeIndex(_vars, true);
1845 
1846  RooAbsArg* intArg = _vars.find(sliceArg) ;
1847  if (!intArg) {
1848  coutE(InputArguments) << "RooDataHist::sliceIterator() variable " << sliceArg.GetName() << " is not part of this RooDataHist" << endl ;
1849  return 0 ;
1850  }
1851  return new RooDataHistSliceIter(*this,*intArg) ;
1852 }
1853 
1854 
1855 ////////////////////////////////////////////////////////////////////////////////
1856 /// Change the name of the RooDataHist
1857 
1858 void RooDataHist::SetName(const char *name)
1859 {
1860  if (_dir) _dir->GetList()->Remove(this);
1862  if (_dir) _dir->GetList()->Add(this);
1863 }
1864 
1865 
1866 ////////////////////////////////////////////////////////////////////////////////
1867 /// Change the title of this RooDataHist
1868 
1869 void RooDataHist::SetNameTitle(const char *name, const char* title)
1870 {
1871  if (_dir) _dir->GetList()->Remove(this);
1872  TNamed::SetNameTitle(name,title) ;
1873  if (_dir) _dir->GetList()->Add(this);
1874 }
1875 
1876 
1877 ////////////////////////////////////////////////////////////////////////////////
1878 /// Print value of the dataset, i.e. the sum of weights contained in the dataset
1879 
1880 void RooDataHist::printValue(ostream& os) const
1881 {
1882  os << numEntries() << " bins (" << sumEntries() << " weights)" ;
1883 }
1884 
1885 
1886 
1887 
1888 ////////////////////////////////////////////////////////////////////////////////
1889 /// Print argument of dataset, i.e. the observable names
1890 
1891 void RooDataHist::printArgs(ostream& os) const
1892 {
1893  os << "[" ;
1894  Bool_t first(kTRUE) ;
1895  for (const auto arg : _vars) {
1896  if (first) {
1897  first=kFALSE ;
1898  } else {
1899  os << "," ;
1900  }
1901  os << arg->GetName() ;
1902  }
1903  os << "]" ;
1904 }
1905 
1906 
1907 
1908 ////////////////////////////////////////////////////////////////////////////////
1909 /// Compute which bins of the dataset are part of the currently set fit range.
1911 {
1912  checkInit() ;
1913 
1914  _maskedWeights.assign(_wgt, _wgt + _arrSize);
1915 
1916  for (Int_t i=0; i < _arrSize; ++i) {
1917  get(i) ;
1918 
1919  for (const auto arg : _vars) {
1920  if (!arg->inRange(nullptr)) {
1921  _maskedWeights[i] = 0.;
1922  break;
1923  }
1924  }
1925  }
1926 
1927 }
1928 
1929 
1930 
1931 ////////////////////////////////////////////////////////////////////////////////
1932 /// Returns true if dataset contains entries with a non-integer weight.
1933 
1935 {
1936  for (Int_t i=0; i < _arrSize; ++i) {
1937  const double wgt = _wgt[i];
1938  double intpart;
1939  if (fabs(std::modf(wgt, &intpart)) > 1.E-10)
1940  return true;
1941  }
1942 
1943  return false;
1944 }
1945 
1946 
1947 ////////////////////////////////////////////////////////////////////////////////
1948 /// Print the details on the dataset contents
1949 
1950 void RooDataHist::printMultiline(ostream& os, Int_t content, Bool_t verbose, TString indent) const
1951 {
1953 
1954  os << indent << "Binned Dataset " << GetName() << " (" << GetTitle() << ")" << endl ;
1955  os << indent << " Contains " << numEntries() << " bins with a total weight of " << sumEntries() << endl;
1956 
1957  if (!verbose) {
1958  os << indent << " Observables " << _vars << endl ;
1959  } else {
1960  os << indent << " Observables: " ;
1962  }
1963 
1964  if(verbose) {
1965  if (_cachedVars.getSize()>0) {
1966  os << indent << " Caches " << _cachedVars << endl ;
1967  }
1968  }
1969 }
1970 
1971 
1972 
1973 ////////////////////////////////////////////////////////////////////////////////
1974 /// Stream an object of class RooDataHist.
1975 void RooDataHist::Streamer(TBuffer &R__b) {
1976  if (R__b.IsReading()) {
1977 
1978  UInt_t R__s, R__c;
1979  Version_t R__v = R__b.ReadVersion(&R__s, &R__c);
1980 
1981  if (R__v > 2) {
1982  R__b.ReadClassBuffer(RooDataHist::Class(),this,R__v,R__s,R__c);
1983  R__b.CheckByteCount(R__s, R__c, RooDataHist::IsA());
1984  initialize(0, false);
1985  } else {
1986 
1987  // Legacy dataset conversion happens here. Legacy RooDataHist inherits from RooTreeData
1988  // which in turn inherits from RooAbsData. Manually stream RooTreeData contents on
1989  // file here and convert it into a RooTreeDataStore which is installed in the
1990  // new-style RooAbsData base class
1991 
1992  // --- This is the contents of the streamer code of RooTreeData version 2 ---
1993  UInt_t R__s1, R__c1;
1994  Version_t R__v1 = R__b.ReadVersion(&R__s1, &R__c1); if (R__v1) { }
1995 
1996  RooAbsData::Streamer(R__b);
1997  TTree* X_tree(0) ; R__b >> X_tree;
1998  RooArgSet X_truth ; X_truth.Streamer(R__b);
1999  TString X_blindString ; X_blindString.Streamer(R__b);
2000  R__b.CheckByteCount(R__s1, R__c1, TClass::GetClass("RooTreeData"));
2001  // --- End of RooTreeData-v1 streamer
2002 
2003  // Construct RooTreeDataStore from X_tree and complete initialization of new-style RooAbsData
2004  _dstore = new RooTreeDataStore(X_tree,_vars) ;
2005  _dstore->SetName(GetName()) ;
2006  _dstore->SetTitle(GetTitle()) ;
2007  _dstore->checkInit() ;
2008 
2009  RooDirItem::Streamer(R__b);
2010  R__b >> _arrSize;
2011  delete [] _wgt;
2012  _wgt = new Double_t[_arrSize];
2013  R__b.ReadFastArray(_wgt,_arrSize);
2014  delete [] _errLo;
2015  _errLo = new Double_t[_arrSize];
2017  delete [] _errHi;
2018  _errHi = new Double_t[_arrSize];
2020  delete [] _sumw2;
2021  _sumw2 = new Double_t[_arrSize];
2023  delete [] _binv;
2024  _binv = new Double_t[_arrSize];
2025  _realVars.Streamer(R__b);
2026  double tmp;
2027  R__b >> tmp; //_curWeight;
2028  R__b >> tmp; //_curWgtErrLo;
2029  R__b >> tmp; //_curWgtErrHi;
2030  R__b >> tmp; //_curSumW2;
2031  R__b >> tmp; //_curVolume;
2032  R__b >> _curIndex;
2033  R__b.CheckByteCount(R__s, R__c, RooDataHist::IsA());
2034  }
2035 
2036  } else {
2037 
2038  R__b.WriteClassBuffer(RooDataHist::Class(),this);
2039  }
2040 }
2041 
2042 
2043 ////////////////////////////////////////////////////////////////////////////////
2044 /// Return event weights of all events in range [first, first+len).
2045 /// If no contiguous structure of weights is stored, an empty batch is be returned.
2046 /// In this case, the single-value weight() needs to be used to retrieve it.
2047 RooSpan<const double> RooDataHist::getWeightBatch(std::size_t first, std::size_t len) const {
2048  return _maskedWeights.empty() ?
2049  RooSpan<const double>{_wgt + first, len} :
2051 }
2052 
2053 
2054 ////////////////////////////////////////////////////////////////////////////////
2055 /// Write information to retrieve data columns into `evalData.spans`.
2056 /// All spans belonging to variables of this dataset are overwritten. Spans to other
2057 /// variables remain intact.
2058 /// \param[out] evalData Store references to all data batches in this struct's `spans`.
2059 /// The key to retrieve an item is the pointer of the variable that owns the data.
2060 /// \param first Index of first event that ends up in the batch.
2061 /// \param len Number of events in each batch.
2062 void RooDataHist::getBatches(RooBatchCompute::RunContext& evalData, std::size_t begin, std::size_t len) const {
2063  for (auto&& batch : store()->getBatches(begin, len).spans) {
2064  evalData.spans[batch.first] = std::move(batch.second);
2065  }
2066 }
2067 
2068 ////////////////////////////////////////////////////////////////////////////////
2069 /// Hand over pointers to our weight arrays to the data store implementation.
2072 }
RooFormulaVar.h
RooDirItem::removeFromDir
void removeFromDir(TObject *obj)
Remove object from directory it was added to.
Definition: RooDirItem.cxx:43
l
auto * l
Definition: textangle.C:4
RooAbsData::Tree
@ Tree
Definition: RooAbsData.h:248
RooDataHist::_binbounds
std::vector< std::vector< Double_t > > _binbounds
List of used binnings associated with lvalues.
Definition: RooDataHist.h:248
Util.h
RooAbsCategoryLValue::setBin
virtual void setBin(Int_t ibin, const char *rangeName=0)
Set category to i-th fit bin, which is the i-th registered state.
Definition: RooAbsCategoryLValue.cxx:177
RooFormula
RooFormula internally uses ROOT's TFormula to compute user-defined expressions of RooAbsArgs.
Definition: RooFormula.h:34
RooDataHist::_pbinvCacheMgr
RooCacheManager< std::vector< Double_t > > _pbinvCacheMgr
Definition: RooDataHist.h:245
n
const Int_t n
Definition: legend1.C:16
TAxis
Class to manage histogram axis.
Definition: TAxis.h:30
RooLinkedList::MakeIterator
TIterator * MakeIterator(Bool_t forward=kTRUE) const
Create a TIterator for this list.
Definition: RooLinkedList.cxx:747
RooCmdArg
RooCmdArg is a named container for two doubles, two integers two object points and three string point...
Definition: RooCmdArg.h:27
fit1_py.fill
fill
Definition: fit1_py.py:6
first
Definition: first.py:1
RooHelpers.h
kTRUE
const Bool_t kTRUE
Definition: RtypesCore.h:91
RooCmdConfig.h
RooPrintable::kVerbose
@ kVerbose
Definition: RooPrintable.h:34
e
#define e(i)
Definition: RSha256.hxx:103
TDirectory::GetList
virtual TList * GetList() const
Definition: TDirectory.h:176
RooLinkedListIter.h
RooAbsData::PlotOpt
Definition: RooAbsData.h:152
Version_t
short Version_t
Definition: RtypesCore.h:65
RooArgSet::addClone
RooAbsArg * addClone(const RooAbsArg &var, Bool_t silent=kFALSE) override
Add clone of specified element to an owning set.
Definition: RooArgSet.cxx:288
RooMsgService.h
RooDataHist::setAllWeights
void setAllWeights(Double_t value)
Set all the event weight of all bins to the specified value.
Definition: RooDataHist.cxx:1825
RooUniformBinning.h
TNamed::SetNameTitle
virtual void SetNameTitle(const char *name, const char *title)
Set all the TNamed parameters (name and title).
Definition: TNamed.cxx:154
RooDataHist::cacheClone
RooAbsData * cacheClone(const RooAbsArg *newCacheOwner, const RooArgSet *newCacheVars, const char *newName=0) override
Construct a clone of this dataset that contains only the cached variables.
Definition: RooDataHist.cxx:866
RooDataHist::kInverseBinCorr
@ kInverseBinCorr
Definition: RooDataHist.h:250
TNamed::SetName
virtual void SetName(const char *name)
Set the name of the TNamed.
Definition: TNamed.cxx:140
RooDirItem::_dir
TDirectory * _dir
Definition: RooDirItem.h:33
RooAbsData
RooAbsData is the common abstract base class for binned and unbinned datasets.
Definition: RooAbsData.h:49
RooDataHist::weight
double weight(std::size_t i) const
Return weight of i-th bin.
Definition: RooDataHist.h:102
RooAbsRealLValue::getMax
virtual Double_t getMax(const char *name=0) const
Get maximum of currently defined range.
Definition: RooAbsRealLValue.h:89
RooAbsData::SumW2
@ SumW2
Definition: RooAbsData.h:99
RooFit.h
RooFit::InputArguments
@ InputArguments
Definition: RooGlobalFunc.h:68
RooAbsData::printMultiline
void printMultiline(std::ostream &os, Int_t contents, Bool_t verbose=kFALSE, TString indent="") const
Interface for detailed printing of object.
Definition: RooAbsData.cxx:802
RooDataHist::_errLo
double * _errLo
Definition: RooDataHist.h:235
RooBinning
Class RooBinning is an implements RooAbsBinning in terms of an array of boundary values,...
Definition: RooBinning.h:28
TBuffer::ReadFastArray
virtual void ReadFastArray(Bool_t *b, Int_t n)=0
ClassImp
#define ClassImp(name)
Definition: Rtypes.h:364
Form
char * Form(const char *fmt,...)
TNamed::GetTitle
virtual const char * GetTitle() const
Returns title of object.
Definition: TNamed.h:48
RooDataHist::kNoBinCorrection
@ kNoBinCorrection
Definition: RooDataHist.h:250
RooAbsBinning::binNumber
virtual Int_t binNumber(Double_t x) const =0
RooLinkedList::GetSize
Int_t GetSize() const
Definition: RooLinkedList.h:60
RooAbsCollection::assignValueOnly
RooAbsCollection & assignValueOnly(const RooAbsCollection &other, Bool_t oneSafe=kFALSE)
The assignment operator sets the value of any argument in our set that also appears in the other set.
Definition: RooAbsCollection.cxx:330
TBuffer::ReadClassBuffer
virtual Int_t ReadClassBuffer(const TClass *cl, void *pointer, const TClass *onfile_class=0)=0
RooAbsData::_dstore
RooAbsDataStore * _dstore
External variables cached with this data set.
Definition: RooAbsData.h:294
RooAbsData::fill
virtual void fill()
Definition: RooAbsData.cxx:300
coutE
#define coutE(a)
Definition: RooMsgService.h:33
RooArgList
RooArgList is a container object that can hold multiple RooAbsArg objects.
Definition: RooArgList.h:21
TTree
A TTree represents a columnar dataset.
Definition: TTree.h:79
RooAbsData::Auto
@ Auto
Definition: RooAbsData.h:99
RooDirItem
RooDirItem is a utility base class for RooFit objects that are to be attached to ROOT directories.
Definition: RooDirItem.h:22
RooAbsData::weight
virtual Double_t weight() const =0
RooDataHist::importTH1Set
void importTH1Set(const RooArgList &vars, RooCategory &indexCat, std::map< std::string, TH1 * > hmap, Double_t initWgt, Bool_t doDensityCorrection)
Import data from given set of TH1/2/3 into this RooDataHist.
Definition: RooDataHist.cxx:435
RooAbsReal::getVal
Double_t getVal(const RooArgSet *normalisationSet=nullptr) const
Evaluate object.
Definition: RooAbsReal.h:91
RooDataHist::sumEntries
Double_t sumEntries() const override
Sum the weights of all bins.
Definition: RooDataHist.cxx:1719
RooDataHist::importTH1
void importTH1(const RooArgList &vars, const TH1 &histo, Double_t initWgt, Bool_t doDensityCorrection)
Import data from given TH1/2/3 into this RooDataHist.
Definition: RooDataHist.cxx:356
Int_t
int Int_t
Definition: RtypesCore.h:45
TH1::GetBinError
virtual Double_t GetBinError(Int_t bin) const
Return value of error associated to bin number bin.
Definition: TH1.cxx:8903
RooAbsData::defaultStorageType
static StorageType defaultStorageType
Definition: RooAbsData.h:256
RooAbsCollection::remove
virtual Bool_t remove(const RooAbsArg &var, Bool_t silent=kFALSE, Bool_t matchByNameOnly=kFALSE)
Remove the specified argument from our list.
Definition: RooAbsCollection.cxx:584
RooAbsData::PlotOpt::correctForBinWidth
Bool_t correctForBinWidth
Definition: RooAbsData.h:168
RooAbsCollection::find
RooAbsArg * find(const char *name) const
Find object with given name in list.
Definition: RooAbsCollection.cxx:813
TGeant4Unit::pc
static constexpr double pc
Definition: TGeant4SystemOfUnits.h:130
RooDataHist::getWeightBatch
RooSpan< const double > getWeightBatch(std::size_t first, std::size_t len) const override
Return event weights of all events in range [first, first+len).
Definition: RooDataHist.cxx:2047
RooAbsData::store
RooAbsDataStore * store()
Definition: RooAbsData.h:68
coutI
#define coutI(a)
Definition: RooMsgService.h:30
RooDataHist::_binv
double * _binv
Definition: RooDataHist.h:238
indent
static void indent(ostringstream &buf, int indent_level)
Definition: TClingCallFunc.cxx:87
RooHistError::getPoissonInterval
Bool_t getPoissonInterval(Int_t n, Double_t &mu1, Double_t &mu2, Double_t nSigma=1) const
Return a confidence interval for the expected number of events given n observed (unweighted) events.
Definition: RooHistError.cxx:79
RooFormula.h
RooAbsReal
RooAbsReal is the common abstract base class for objects that represent a real value and implements f...
Definition: RooAbsReal.h:61
RooArgList::at
RooAbsArg * at(Int_t idx) const
Return object at given index, or nullptr if index is out of range.
Definition: RooArgList.h:70
TBuffer
Buffer base class used for serializing objects.
Definition: TBuffer.h:43
RooAbsData::checkInit
void checkInit() const
Definition: RooAbsData.cxx:2331
ROOT::Math::KahanSum::Accumulate
static KahanSum< T, N > Accumulate(Iterator begin, Iterator end, T initialValue=T{})
Iterate over a range and return an instance of a KahanSum.
Definition: Util.h:179
TTree.h
TBuffer::CheckByteCount
virtual Int_t CheckByteCount(UInt_t startpos, UInt_t bcnt, const TClass *clss)=0
RooDataHist::weightError
void weightError(Double_t &lo, Double_t &hi, ErrorType etype=Poisson) const override
Return the error of current weight.
Definition: RooDataHist.cxx:1175
TString
Basic string class.
Definition: TString.h:136
RooDataHist::importDHistSet
void importDHistSet(const RooArgList &vars, RooCategory &indexCat, std::map< std::string, RooDataHist * > dmap, Double_t initWgt)
Import data from given set of TH1/2/3 into this RooDataHist.
Definition: RooDataHist.cxx:538
RooAbsLValue::getBin
virtual Int_t getBin(const char *rangeName=0) const =0
RooDataHistSliceIter.h
RooRealVar::setRange
void setRange(const char *name, Double_t min, Double_t max)
Set a fit or plotting range.
Definition: RooRealVar.cxx:526
RooDataHist::SetNameTitle
void SetNameTitle(const char *name, const char *title) override
Change the title of this RooDataHist.
Definition: RooDataHist.cxx:1869
RooDataHist::getBatches
void getBatches(RooBatchCompute::RunContext &evalData, std::size_t begin, std::size_t len) const override
Write information to retrieve data columns into evalData.spans.
Definition: RooDataHist.cxx:2062
TH1::GetZaxis
TAxis * GetZaxis()
Definition: TH1.h:322
RooAbsData::ErrorType
ErrorType
Definition: RooAbsData.h:99
RooAbsCategory::getCurrentLabel
virtual const char * getCurrentLabel() const
Return label string of current state.
Definition: RooAbsCategory.cxx:130
v
@ v
Definition: rootcling_impl.cxx:3635
RooTreeDataStore.h
RooCategory::defineType
bool defineType(const std::string &label)
Define a state with given name.
Definition: RooCategory.cxx:208
RooDataHist::_cache_sum
Double_t _cache_sum
Is cache sum valid? Needs to be Int_t instead of CacheSumState_t for subclasses.
Definition: RooDataHist.h:252
bool
TIterator
Iterator abstract base class.
Definition: TIterator.h:30
RooAbsRealLValue::getMin
virtual Double_t getMin(const char *name=0) const
Get miniminum of currently defined range.
Definition: RooAbsRealLValue.h:86
RooDataHist::registerWeightArraysToDataStore
void registerWeightArraysToDataStore() const
Hand over pointers to our weight arrays to the data store implementation.
Definition: RooDataHist.cxx:2070
RooDataHist::kCorrectForBinSize
@ kCorrectForBinSize
Definition: RooDataHist.h:250
RooDataHist::add
virtual void add(const RooArgSet &row, Double_t wgt=1.0)
Add wgt to the bin content enclosed by the coordinates passed in row.
Definition: RooDataHist.h:68
q
float * q
Definition: THbookFile.cxx:89
RooHistError::instance
static const RooHistError & instance()
Return a reference to a singleton object that is created the first time this method is called.
Definition: RooHistError.cxx:49
TH1::GetDimension
virtual Int_t GetDimension() const
Definition: TH1.h:282
RooCmdConfig
Class RooCmdConfig is a configurable parser for RooCmdArg named arguments.
Definition: RooCmdConfig.h:27
RooDataHist::get_curWgtErrLo
Double_t get_curWgtErrLo() const
Definition: RooDataHist.h:225
RooAbsBinning::binCenter
virtual Double_t binCenter(Int_t bin) const =0
RooDataHist::checkBinBounds
void checkBinBounds() const
Definition: RooDataHist.cxx:776
RooArgSet::snapshot
RooArgSet * snapshot(bool deepCopy=true) const
Use RooAbsCollection::snapshot(), but return as RooArgSet.
Definition: RooArgSet.h:126
RooAbsLValue.h
RooDataHist::_idxMult
std::vector< Int_t > _idxMult
Definition: RooDataHist.h:232
total
static unsigned int total
Definition: TGWin32ProxyDefs.h:40
RooDataHist::_arrSize
Int_t _arrSize
Definition: RooDataHist.h:231
RooDataHist::_realVars
RooArgSet _realVars
Definition: RooDataHist.h:240
RooTrace.h
hi
float type_of_call hi(const int &, const int &)
RooDataHist::binVolume
Double_t binVolume() const
Return volume of current bin.
Definition: RooDataHist.h:170
RooDataHist::_sumw2
double * _sumw2
Definition: RooDataHist.h:237
RooAbsData::Expected
@ Expected
Definition: RooAbsData.h:99
RooDataHist::interpolateDim
Double_t interpolateDim(RooRealVar &dim, const RooAbsBinning *binning, Double_t xval, Int_t intOrder, Bool_t correctForBinSize, Bool_t cdfBoundaries)
Perform boundary safe 'intOrder'-th interpolation of weights in dimension 'dim' at current value 'xva...
Definition: RooDataHist.cxx:1232
RooFit::DataHandling
@ DataHandling
Definition: RooGlobalFunc.h:69
RooAbsData::_vars
RooArgSet _vars
Definition: RooAbsData.h:291
ROOT::Math::fabs
VecExpr< UnaryOp< Fabs< T >, VecExpr< A, T, D >, T >, T, D > fabs(const VecExpr< A, T, D > &rhs)
Definition: UnaryOperators.h:131
RooDataHist::calcTreeIndex
Int_t calcTreeIndex() const
Legacy overload to calculate the tree index from the current value of _vars.
Definition: RooDataHist.h:198
RooAbsCategoryLValue::numBins
virtual Int_t numBins(const char *rangeName) const
Return the number of fit bins ( = number of types )
Definition: RooAbsCategoryLValue.cxx:203
RooDataHist
The RooDataHist is a container class to hold N-dimensional binned data.
Definition: RooDataHist.h:41
RooPrintable::kName
@ kName
Definition: RooPrintable.h:33
RooCategory::setLabel
virtual Bool_t setLabel(const char *label, bool printError=true) override
Set value by specifying the name of the desired state.
Definition: RooCategory.cxx:185
TArrayD::GetArray
const Double_t * GetArray() const
Definition: TArrayD.h:43
RooFormulaVar
A RooFormulaVar is a generic implementation of a real-valued object, which takes a RooArgList of serv...
Definition: RooFormulaVar.h:30
RooDataHist::dump2
void dump2()
Debug stuff, should go...
Definition: RooDataHist.cxx:1017
RooDataHist::get
const RooArgSet * get() const override
Get bin centre of current bin.
Definition: RooDataHist.h:78
RooAbsRealLValue::numBins
virtual Int_t numBins(const char *rangeName=0) const
Definition: RooAbsRealLValue.h:54
TH1::GetBinContent
virtual Double_t GetBinContent(Int_t bin) const
Return content of bin number bin.
Definition: TH1.cxx:4993
TBuffer.h
TAxis::GetXmin
Double_t GetXmin() const
Definition: TAxis.h:133
RooDataHist::_lvvars
std::vector< RooAbsLValue * > _lvvars
Cache manager for arrays of partial bin volumes.
Definition: RooDataHist.h:246
TRACE_DESTROY
#define TRACE_DESTROY
Definition: RooTrace.h:24
RooDataHist::reduceEng
RooAbsData * reduceEng(const RooArgSet &varSubset, const RooFormulaVar *cutVar, const char *cutRange=0, std::size_t nStart=0, std::size_t nStop=std::numeric_limits< std::size_t >::max(), Bool_t copyCache=kTRUE) override
Implementation of RooAbsData virtual method that drives the RooAbsData::reduce() methods.
Definition: RooDataHist.cxx:884
TH1::GetYaxis
TAxis * GetYaxis()
Definition: TH1.h:321
xmin
float xmin
Definition: THbookFile.cxx:95
RooDataHist::getIndex
Int_t getIndex(const RooArgSet &coord, Bool_t fast=false) const
Calculate bin number of the given coordinates.
Definition: RooDataHist.cxx:961
h
#define h(i)
Definition: RSha256.hxx:106
RooDataHist::_adjustBinning
void _adjustBinning(RooRealVar &theirVar, const TAxis &axis, RooRealVar *ourVar, Int_t *offset)
Cache for sum of entries ;.
Definition: RooDataHist.cxx:576
RooDataHist::initialize
void initialize(const char *binningName=0, Bool_t fillTree=kTRUE)
Initialization procedure: allocate weights array, calculate multipliers needed for N-space to 1-dim a...
Definition: RooDataHist.cxx:688
RooMath::interpolate
static Double_t interpolate(Double_t yArr[], Int_t nOrder, Double_t x)
Definition: RooMath.cxx:605
RooAbsData::plotOn
virtual RooPlot * plotOn(RooPlot *frame, const RooCmdArg &arg1=RooCmdArg::none(), const RooCmdArg &arg2=RooCmdArg::none(), const RooCmdArg &arg3=RooCmdArg::none(), const RooCmdArg &arg4=RooCmdArg::none(), const RooCmdArg &arg5=RooCmdArg::none(), const RooCmdArg &arg6=RooCmdArg::none(), const RooCmdArg &arg7=RooCmdArg::none(), const RooCmdArg &arg8=RooCmdArg::none()) const
Definition: RooAbsData.cxx:547
RooDataHist::reset
void reset() override
Reset all bin weights to zero.
Definition: RooDataHist.cxx:1772
TBuffer::WriteClassBuffer
virtual Int_t WriteClassBuffer(const TClass *cl, void *pointer)=0
kFALSE
const Bool_t kFALSE
Definition: RtypesCore.h:92
RooDataHist::printArgs
virtual void printArgs(std::ostream &os) const override
Print argument of dataset, i.e. the observable names.
Definition: RooDataHist.cxx:1891
RooDataHist.h
RooAbsData::get
virtual const RooArgSet * get() const
Definition: RooAbsData.h:92
ROOT::R::function
void function(const Char_t *name_, T fun, const Char_t *docstring=0)
Definition: RExports.h:151
RooArgSet::add
Bool_t add(const RooAbsArg &var, Bool_t silent=kFALSE) override
Add element to non-owning set.
Definition: RooArgSet.cxx:261
RooAbsCollection::selectCommon
RooAbsCollection * selectCommon(const RooAbsCollection &refColl) const
Create a subset of the current collection, consisting only of those elements that are contained as we...
Definition: RooAbsCollection.cxx:700
RooDataHist::printValue
virtual void printValue(std::ostream &os) const override
Print value of the dataset, i.e. the sum of weights contained in the dataset.
Definition: RooDataHist.cxx:1880
RooLinkedList
RooLinkedList is an collection class for internal use, storing a collection of RooAbsArg pointers in ...
Definition: RooLinkedList.h:35
RooPlot.h
TMath::Power
LongDouble_t Power(LongDouble_t x, LongDouble_t y)
Definition: TMath.h:735
RooAbsBinning
RooAbsBinning is the abstract base class for RooRealVar binning definitions.
Definition: RooAbsBinning.h:26
RooUniformBinning
RooUniformBinning is an implementation of RooAbsBinning that provides a uniform binning in 'n' bins b...
Definition: RooUniformBinning.h:23
RooAbsDataStore::setExternalWeightArray
virtual void setExternalWeightArray(const Double_t *, const Double_t *, const Double_t *, const Double_t *)
Definition: RooAbsDataStore.h:86
RooPlot
A RooPlot is a plot frame and a container for graphics objects within that frame.
Definition: RooPlot.h:44
RooDataHist::RooDataHist
RooDataHist()
Default constructor.
Definition: RooDataHist.cxx:66
gDebug
Int_t gDebug
Definition: TROOT.cxx:590
TRACE_CREATE
#define TRACE_CREATE
Definition: RooTrace.h:23
RooDataHist::_lvbins
std::vector< std::unique_ptr< const RooAbsBinning > > _lvbins
List of observables casted as RooAbsLValue.
Definition: RooDataHist.h:247
RooAbsCollection::size
Storage_t::size_type size() const
Definition: RooAbsCollection.h:155
RooAbsData::numEntries
virtual Int_t numEntries() const
Return number of entries in dataset, i.e., count unweighted entries.
Definition: RooAbsData.cxx:307
RooDataHist::adjustBinning
void adjustBinning(const RooArgList &vars, const TH1 &href, Int_t *offset=0)
Adjust binning specification on first and optionally second and third observable to binning in given ...
Definition: RooDataHist.cxx:642
TClass::GetClass
static TClass * GetClass(const char *name, Bool_t load=kTRUE, Bool_t silent=kFALSE)
Static method returning pointer to TClass of the specified class name.
Definition: TClass.cxx:2946
RooCategory.h
y
Double_t y[n]
Definition: legend1.C:17
RooPrintable::kValue
@ kValue
Definition: RooPrintable.h:33
sqrt
double sqrt(double)
RooDataHist::cacheValidEntries
void cacheValidEntries()
Compute which bins of the dataset are part of the currently set fit range.
Definition: RooDataHist.cxx:1910
RooDataHist::_maskedWeights
std::vector< double > _maskedWeights
Definition: RooDataHist.h:241
RooDataHist::isNonPoissonWeighted
Bool_t isNonPoissonWeighted() const override
Returns true if dataset contains entries with a non-integer weight.
Definition: RooDataHist.cxx:1934
RooAbsArg::attachDataSet
void attachDataSet(const RooAbsData &set)
Replace server nodes with names matching the dataset variable names with those data set variables,...
Definition: RooAbsArg.cxx:1516
RooRealVar.h
TNamed::SetTitle
virtual void SetTitle(const char *title="")
Set the title of the TNamed.
Definition: TNamed.cxx:164
RooDirItem::appendToDir
void appendToDir(TObject *obj, Bool_t forceMemoryResident=kFALSE)
Append object to directory.
Definition: RooDirItem.cxx:55
RooDataHist::weight
Double_t weight() const override
Return weight of last bin that was requested with get().
Definition: RooDataHist.h:161
TBuffer::ReadVersion
virtual Version_t ReadVersion(UInt_t *start=0, UInt_t *bcnt=0, const TClass *cl=0)=0
RooDataHist::RooDataHistSliceIter
friend class RooDataHistSliceIter
Definition: RooDataHist.h:193
RooTreeDataStore
RooTreeDataStore is a TTree-backed data storage.
Definition: RooTreeDataStore.h:32
RooDataHist::_curIndex
std::size_t _curIndex
Copy of _wgtVec, but masked events have a weight of zero.
Definition: RooDataHist.h:243
RooAbsData::Poisson
@ Poisson
Definition: RooAbsData.h:99
TIterator::Next
virtual TObject * Next()=0
RooDataHist::printMultiline
virtual void printMultiline(std::ostream &os, Int_t content, Bool_t verbose=kFALSE, TString indent="") const override
Print the details on the dataset contents.
Definition: RooDataHist.cxx:1950
RooAbsData::PlotOpt::bins
RooAbsBinning * bins
Definition: RooAbsData.h:158
unsigned int
ymin
float ymin
Definition: THbookFile.cxx:95
RooDataHist::SetName
void SetName(const char *name) override
Change the name of the RooDataHist.
Definition: RooDataHist.cxx:1858
RooHelpers::tokenise
std::vector< std::string > tokenise(const std::string &str, const std::string &delims, bool returnEmptyToken=true)
Tokenise the string by splitting at the characters in delims.
Definition: RooHelpers.cxx:62
RooDataHist::calculatePartialBinVolume
const std::vector< double > & calculatePartialBinVolume(const RooArgSet &dimSet) const
Fill the transient cache with partial bin volumes with up-to-date values for the partial volume speci...
Definition: RooDataHist.cxx:1663
RooRealVar::getBinning
const RooAbsBinning & getBinning(const char *name=0, Bool_t verbose=kTRUE, Bool_t createOnTheFly=kFALSE) const
Return binning definition with name.
Definition: RooRealVar.cxx:318
RooAbsData::None
@ None
Definition: RooAbsData.h:99
RooAbsRealLValue::getBin
virtual Int_t getBin(const char *rangeName=0) const
Definition: RooAbsRealLValue.h:53
TBuffer::IsReading
Bool_t IsReading() const
Definition: TBuffer.h:86
RooDataHist::sliceIterator
TIterator * sliceIterator(RooAbsArg &sliceArg, const RooArgSet &otherArgs)
Create an iterator over all bins in a slice defined by the subset of observables listed in sliceArg.
Definition: RooDataHist.cxx:1840
RooDataHist::numEntries
Int_t numEntries() const override
Return the number of bins.
Definition: RooDataHist.cxx:1710
RooDataHist::sum
Double_t sum(Bool_t correctForBinSize, Bool_t inverseCorr=kFALSE) const
Return the sum of the weights of all bins in the histogram.
Definition: RooDataHist.cxx:1463
RooAbsDataStore::checkInit
virtual void checkInit() const
Definition: RooAbsDataStore.h:116
RooDataHist::_wgt
double * _wgt
Definition: RooDataHist.h:234
RooPrintable::kExtras
@ kExtras
Definition: RooPrintable.h:33
Double_t
double Double_t
Definition: RtypesCore.h:59
RooAbsRealLValue::setBinFast
virtual void setBinFast(Int_t ibin, const RooAbsBinning &binning)
Set value to center of bin 'ibin' of binning 'rangeName' (or of default binning if no range is specif...
Definition: RooAbsRealLValue.cxx:481
TList::Remove
virtual TObject * Remove(TObject *obj)
Remove object from the list.
Definition: TList.cxx:822
RooCategory
RooCategory is an object to represent discrete states.
Definition: RooCategory.h:27
RooRealVar::setBinning
void setBinning(const RooAbsBinning &binning, const char *name=0)
Add given binning under name 'name' with this variable.
Definition: RooRealVar.cxx:415
RooAbsData::weightSquared
virtual Double_t weightSquared() const =0
RooAbsBinning::clone
virtual RooAbsBinning * clone(const char *name=0) const =0
RooVectorDataStore
RooVectorDataStore uses std::vectors to store data columns.
Definition: RooVectorDataStore.h:37
TList::Add
virtual void Add(TObject *obj)
Definition: TList.h:87
TObject
Mother of all ROOT objects.
Definition: TObject.h:37
RooAbsCategory::hasLabel
bool hasLabel(const std::string &label) const
Check if a state with name label exists.
Definition: RooAbsCategory.h:64
TH1
TH1 is the base class of all histogram classes in ROOT.
Definition: TH1.h:58
name
char name[80]
Definition: TGX11.cxx:110
RooPrintable::kTitle
@ kTitle
Definition: RooPrintable.h:33
RooPrintable::printStream
virtual void printStream(std::ostream &os, Int_t contents, StyleOption style, TString indent="") const
Print description of object on ostream, printing contents set by contents integer,...
Definition: RooPrintable.cxx:75
genreflex::verbose
bool verbose
Definition: rootcling_impl.cxx:133
RooDataHist::~RooDataHist
~RooDataHist() override
Destructor.
Definition: RooDataHist.cxx:939
RooBinning.h
RooDataHist::plotOn
virtual RooPlot * plotOn(RooPlot *frame, const RooCmdArg &arg1=RooCmdArg::none(), const RooCmdArg &arg2=RooCmdArg::none(), const RooCmdArg &arg3=RooCmdArg::none(), const RooCmdArg &arg4=RooCmdArg::none(), const RooCmdArg &arg5=RooCmdArg::none(), const RooCmdArg &arg6=RooCmdArg::none(), const RooCmdArg &arg7=RooCmdArg::none(), const RooCmdArg &arg8=RooCmdArg::none()) const
Definition: RooAbsData.cxx:547
RooAbsArg
RooAbsArg is the common abstract base class for objects that represent a value and a "shape" in RooFi...
Definition: RooAbsArg.h:72
RooAbsRealLValue::getBins
virtual Int_t getBins(const char *name=0) const
Get number of bins of currently defined range.
Definition: RooAbsRealLValue.h:83
RooAbsLValue
Abstract base class for objects that are lvalues, i.e.
Definition: RooAbsLValue.h:26
TNamed::GetName
virtual const char * GetName() const
Returns name of object.
Definition: TNamed.h:47
RooSpan.h
RooDataHist::get_wgt
Double_t get_wgt(std::size_t idx) const
Definition: RooDataHist.h:218
RooDataHist::_errHi
double * _errHi
Definition: RooDataHist.h:236
RooVectorDataStore.h
TAxis::GetXmax
Double_t GetXmax() const
Definition: TAxis.h:134
RooAbsDataStore
RooAbsDataStore is the abstract base class for data collection that use a TTree as internal storage m...
Definition: RooAbsDataStore.h:34
RooAbsData::attachCache
virtual void attachCache(const RooAbsArg *newOwner, const RooArgSet &cachedVars)
Internal method – Attach dataset copied with cache contents to copied instances of functions.
Definition: RooAbsData.cxx:347
RooDataHist::get_curWgtErrHi
Double_t get_curWgtErrHi() const
Definition: RooDataHist.h:226
RooAbsCategoryLValue
RooAbsCategoryLValue is the common abstract base class for objects that represent a discrete value th...
Definition: RooAbsCategoryLValue.h:25
RooAbsCollection::allInRange
Bool_t allInRange(const char *rangeSpec) const
Return true if all contained object report to have their value inside the specified range.
Definition: RooAbsCollection.cxx:1197
Class
void Class()
Definition: Class.C:29
RooAbsLValue::getBinWidth
virtual Double_t getBinWidth(Int_t i, const char *rangeName=0) const =0
RooRealVar
RooRealVar represents a variable that can be changed from the outside.
Definition: RooRealVar.h:39
ROOT::Math::KahanSum
The Kahan summation is a compensated summation algorithm, which significantly reduces numerical error...
Definition: Util.h:122
TH1::GetXaxis
TAxis * GetXaxis()
Get the behaviour adopted by the object about the statoverflows. See EStatOverflows for more informat...
Definition: TH1.h:320
TAxis::GetXbins
const TArrayD * GetXbins() const
Definition: TAxis.h:130
Riostream.h
RooDataHist::CacheSumState_t
CacheSumState_t
list of bin bounds per dimension
Definition: RooDataHist.h:250
pow
double pow(double, double)
RooFormula::eval
Double_t eval(const RooArgSet *nset=0) const
Evalute all parameters/observables, and then evaluate formula.
Definition: RooFormula.cxx:342
RooHistError.h
RooAbsRealLValue
RooAbsRealLValue is the common abstract base class for objects that represent a real value that may a...
Definition: RooAbsRealLValue.h:31
RooArgList.h
TGeant4Unit::second
static constexpr double second
Definition: TGeant4SystemOfUnits.h:151
TH1.h
TObject::ClassName
virtual const char * ClassName() const
Returns name of class to which the object belongs.
Definition: TObject.cxx:130
RooDataHist::_cache_sum_valid
Int_t _cache_sum_valid
Definition: RooDataHist.h:251
RooMath.h
RooDataHist::set
void set(std::size_t binNumber, double weight, double wgtErr)
Set bin content of bin that was last loaded with get(std::size_t).
Definition: RooDataHist.cxx:1359
RooPlot::getPlotVar
RooAbsRealLValue * getPlotVar() const
Definition: RooPlot.h:139
RooBatchCompute::RunContext::spans
std::unordered_map< const RooAbsReal *, RooSpan< const double > > spans
Once an object has computed its value(s), the span pointing to the results is registered here.
Definition: RunContext.h:51
RooBatchCompute::RunContext
Data that has to be passed around when evaluating functions / PDFs.
Definition: RunContext.h:32
RooDataHist::get_curSumW2
Double_t get_curSumW2() const
Definition: RooDataHist.h:227
TAxis::GetNbins
Int_t GetNbins() const
Definition: TAxis.h:121
RooAbsCollection::getSize
Int_t getSize() const
Definition: RooAbsCollection.h:172
RooSpan
A simple container to hold a batch of data values.
Definition: RooSpan.h:34
RooAbsData::_cachedVars
RooArgSet _cachedVars
Definition: RooAbsData.h:292
TMath.h
RooArgSet
RooArgSet is a container object that can hold multiple RooAbsArg objects.
Definition: RooArgSet.h:29
fw3dlego::xbins
const double xbins[xbins_n]
Definition: collection_proxies.C:48
int
RooAbsRealLValue::setBin
virtual void setBin(Int_t ibin, const char *rangeName=0)
Set value to center of bin 'ibin' of binning 'rangeName' (or of default binning if no range is specif...
Definition: RooAbsRealLValue.cxx:433