Logo ROOT  
Reference Guide
 
Loading...
Searching...
No Matches
RooDataSet.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 RooDataSet.cxx
19\class RooDataSet
20\ingroup Roofitcore
21
22Container class to hold unbinned data. The binned equivalent is
23RooDataHist. In RooDataSet, each data point in N-dimensional space is represented
24by a RooArgSet of RooRealVar, RooCategory or RooStringVar objects, which can be
25retrieved using get().
26
27Since RooDataSet saves every event, it allows for fits with highest precision. With a large
28amount of data, however, it could be beneficial to represent them in binned form,
29i.e., RooDataHist. Binning the data will incur a loss of information, though.
30RooDataHist on the other hand may suffer from the curse of dimensionality if a high-dimensional
31problem with a lot of bins on each axis is tackled.
32
33### Inspecting a dataset
34Inspect a dataset using Print() with the "verbose" option:
35```
36dataset->Print("V");
37dataset->get(0)->Print("V");
38dataset->get(1)->Print("V");
39...
40```
41
42### Plotting data.
43See RooAbsData::plotOn().
44
45
46### Storage strategy
47There are two storage backends:
48- RooVectorDataStore (default): std::vectors in memory. They are fast, but they
49cannot be serialised if the dataset exceeds a size of 1 Gb
50- RooTreeDataStore: Uses a TTree under the hood. Note that the TTree is not
51attached to any currently-opened TFile in order to avoid double-ownership.
52 - Enable tree-backed storage similar to this:
53 ```
54 TFile outputFile("filename.root", "RECREATE");
55 RooAbsData::setDefaultStorageType(RooAbsData::Tree);
56 RooDataSet mydata(...);
57 ```
58 - Or convert an existing memory-backed data storage:
59 ```
60 RooDataSet mydata(...);
61
62 TFile outputFile("filename.root", "RECREATE");
63 mydata.convertToTreeStore();
64 ```
65
66For the inverse conversion, see `RooAbsData::convertToVectorStore()`.
67
68
69### Creating a dataset using RDataFrame
70\see RooAbsDataHelper, rf408_RDataFrameToRooFit.C
71
72### Uniquely identifying RooDataSet objects
73
74\warning Before v6.28, it was ensured that no RooDataSet objects on the heap
75were located at an address that had already been used for a RooDataSet before.
76With v6.28, this is not guaranteed anymore. Hence, if your code uses pointer
77comparisons to uniquely identify RooDataSet instances, please consider using
78the new `RooAbsData::uniqueId()`.
79
80
81**/
82
83#include "RooDataSet.h"
84
85#include "RooPlot.h"
86#include "RooAbsReal.h"
87#include "Roo1DTable.h"
88#include "RooCategory.h"
89#include "RooFormula.h"
90#include "RooFormulaVar.h"
91#include "RooArgList.h"
92#include "RooRealVar.h"
93#include "RooDataHist.h"
94#include "RooMsgService.h"
95#include "RooCmdConfig.h"
96#include "RooHist.h"
97#include "RooTreeDataStore.h"
98#include "RooVectorDataStore.h"
100#include "RooSentinel.h"
101#include "RooTrace.h"
102#include "RooFitImplHelpers.h"
103
104#include "ROOT/StringUtils.hxx"
105
106#include "Math/Util.h"
107#include "TTree.h"
108#include "TFile.h"
109#include "TBuffer.h"
110#include "strlcpy.h"
111#include "snprintf.h"
112
113#include <iostream>
114#include <memory>
115#include <fstream>
116
117
118using std::endl, std::string, std::map, std::list, std::ifstream, std::ofstream, std::ostream;
119
120
122
123////////////////////////////////////////////////////////////////////////////////
124/// Default constructor for persistence
125
130
131namespace {
132
133struct FinalizeVarsOutput {
134 RooArgSet finalVars;
135 std::unique_ptr<RooRealVar> weight;
136 std::string weightVarName;
137 RooArgSet errorSet;
138};
139
140FinalizeVarsOutput finalizeVars(RooArgSet const &vars,
141 RooAbsArg * indexCat,
142 const char* wgtVarName,
145 RooArgSet * errorSet)
146{
149
150 // Gather all imported weighted datasets to infer the weight variable name
151 // and whether we need weight errors
152 std::vector<RooAbsData*> weightedImpDatasets;
153 if(impData && impData->isWeighted()) weightedImpDatasets.push_back(impData);
155 if(data->isWeighted()) {
156 weightedImpDatasets.push_back(data);
157 }
158 }
159
160 bool needsWeightErrors = false;
161
162 // Figure out if the weight needs to store errors
164 if(dynamic_cast<RooDataHist const*>(data)) {
165 needsWeightErrors = true;
166 }
167 }
168
169 if (indexCat) {
171 }
172
174
176 // Even if no weight variable is specified, we want to have one if we are
177 // importing weighted datasets
179 if(auto ds = dynamic_cast<RooDataSet const*>(data)) {
180 // If the imported data is a RooDataSet, we take over its weight variable name
182 break;
183 } else {
185 // Don't break here! The next imported data might be a RooDataSet,
186 // and in that case we want to take over its weight name instead of
187 // using the default one.
188 }
189 }
190 }
191
192 // If the weight variable is required but is not in the set, create and add
193 // it on the fly
200 }
201
204 }
205
206 // Combine the error set figured out by finalizeVars and the ones passed by the user
208
210}
211
212// generating an unbinned dataset from a binned one
213std::unique_ptr<RooDataSet> makeDataSetFromDataHist(RooDataHist const &hist)
214{
215 using namespace RooFit;
216
218 const char* wgtName = wgtVarCmdArg.getString(0);
219 // Instantiate weight variable here such that we can pass it to StoreError()
221
222 RooArgSet vars{*hist.get(), wgtVar};
223
224 // We have to explicitly store the errors that are implied by the sum of weights squared.
225 auto data = std::make_unique<RooDataSet>(hist.GetName(), hist.GetTitle(), vars, wgtVarCmdArg, StoreError(wgtVar));
226 for (int i = 0; i < hist.numEntries(); ++i) {
227 data->add(*hist.get(i), hist.weight(i), std::sqrt(hist.weightSquared(i)));
228 }
229
230 return data;
231}
232
233} // namespace
234
235////////////////////////////////////////////////////////////////////////////////
236/// Construct an unbinned dataset from a RooArgSet defining the dimensions of the data space. Optionally, data
237/// can be imported at the time of construction.
238///
239/// <table>
240/// <tr><th> %RooCmdArg <th> Effect
241/// <tr><td> Import(TTree&) <td> Import contents of given TTree. Only branches of the TTree that have names
242/// corresponding to those of the RooAbsArgs that define the RooDataSet are
243/// imported.
244/// <tr><td> ImportFromFile(const char* fileName, const char* treeName) <td> Import tree with given name from file with given name.
245/// <tr><td> Import(RooAbsData&)
246/// <td> Import contents of given RooDataSet or RooDataHist. Only observables that are common with the definition of this dataset will be imported
247/// <tr><td> Index(RooCategory&) <td> Prepare import of datasets into a N+1 dimensional RooDataSet
248/// where the extra discrete dimension labels the source of the imported histogram.
249/// <tr><td> Import(const char*, RooAbsData&)
250/// <td> Import a RooDataSet or RooDataHist to be associated with the given state name of the index category
251/// specified in Index(). If the given state name is not yet defined in the index
252/// category it will be added on the fly. The import command can be specified multiple times.
253/// <tr><td> Link(const char*, RooDataSet&) <td> Link contents of supplied RooDataSet to this dataset for given index category state name.
254/// In this mode, no data is copied and the linked dataset must be remain live for the duration
255/// of this dataset. Note that link is active for both reading and writing, so modifications
256/// to the aggregate dataset will also modify its components. Link() and Import() are mutually exclusive.
257/// <tr><td> OwnLinked() <td> Take ownership of all linked datasets
258/// <tr><td> Import(std::map<string,RooAbsData*>&) <td> As above, but allows specification of many imports in a single operation
259/// <tr><td> Link(std::map<string,RooDataSet*>&) <td> As above, but allows specification of many links in a single operation
260/// <tr><td> Cut(const char*) <br>
261/// Cut(RooFormulaVar&)
262/// <td> Apply the given cut specification when importing data
263/// <tr><td> CutRange(const char*) <td> Only accept events in the observable range with the given name
264/// <tr><td> WeightVar(const char*) <br>
265/// WeightVar(const RooAbsArg&)
266/// <td> Interpret the given variable as event weight rather than as observable
267/// <tr><td> StoreError(const RooArgSet&) <td> Store symmetric error along with value for given subset of observables
268/// <tr><td> StoreAsymError(const RooArgSet&) <td> Store asymmetric error along with value for given subset of observables
269/// <tr><td> `GlobalObservables(const RooArgSet&)` <td> Define the set of global observables to be stored in this RooDataSet.
270/// A snapshot of the passed RooArgSet is stored, meaning the values wont't change unexpectedly.
271/// </table>
272///
273
275 const RooCmdArg& arg4,const RooCmdArg& arg5,const RooCmdArg& arg6,const RooCmdArg& arg7,const RooCmdArg& arg8) :
276 RooAbsData(name,title,{})
277{
279
280 // Define configuration for this method
281 RooCmdConfig pc("RooDataSet::ctor(" + std::string(GetName()) + ")");
282 pc.defineInt("ownLinked","OwnLinked",0) ;
283 pc.defineObject("impTree","ImportTree",0) ;
284 pc.defineObject("impData","ImportData",0) ;
285 pc.defineObject("indexCat","IndexCat",0) ;
286 pc.defineObject("impSliceData","ImportDataSlice",0,nullptr,true) ; // array
287 pc.defineString("impSliceState","ImportDataSlice",0,"",true) ; // array
288 pc.defineObject("lnkSliceData","LinkDataSlice",0,nullptr,true) ; // array
289 pc.defineString("lnkSliceState","LinkDataSlice",0,"",true) ; // array
290 pc.defineString("cutSpec","CutSpec",0,"") ;
291 pc.defineObject("cutVar","CutVar",0) ;
292 pc.defineString("cutRange","CutRange",0,"") ;
293 pc.defineString("wgtVarName","WeightVarName",0,"") ;
294 pc.defineInt("newWeight1","WeightVarName",0,0) ;
295 pc.defineString("fname","ImportFromFile",0,"") ;
296 pc.defineString("tname","ImportFromFile",1,"") ;
297 pc.defineObject("wgtVar","WeightVar",0) ;
298 pc.defineInt("newWeight2","WeightVar",0,0) ;
299 pc.defineObject("dummy1","ImportDataSliceMany",0) ;
300 pc.defineObject("dummy2","LinkDataSliceMany",0) ;
301 pc.defineSet("errorSet","StoreError",0) ;
302 pc.defineSet("asymErrSet","StoreAsymError",0) ;
303 pc.defineSet("glObs","GlobalObservables",0,nullptr) ;
304 pc.defineMutex("ImportTree","ImportData","ImportDataSlice","LinkDataSlice","ImportFromFile") ;
305 pc.defineMutex("CutSpec","CutVar") ;
306 pc.defineMutex("WeightVarName","WeightVar") ;
307 pc.defineDependency("ImportDataSlice","IndexCat") ;
308 pc.defineDependency("LinkDataSlice","IndexCat") ;
309 pc.defineDependency("OwnLinked","LinkDataSlice") ;
310
311
313 l.Add((TObject*)&arg1) ; l.Add((TObject*)&arg2) ;
314 l.Add((TObject*)&arg3) ; l.Add((TObject*)&arg4) ;
315 l.Add((TObject*)&arg5) ; l.Add((TObject*)&arg6) ;
316 l.Add((TObject*)&arg7) ; l.Add((TObject*)&arg8) ;
317
318 // Process & check varargs
319 pc.process(l) ;
320 if (!pc.ok(true)) {
321 const std::string errMsg = "Error in RooDataSet constructor: command argument list could not be processed";
322 coutE(InputArguments) << errMsg << std::endl;
323 throw std::invalid_argument(errMsg);
324 }
325
326 if(pc.getSet("glObs")) setGlobalObservables(*pc.getSet("glObs"));
327
328 // Extract relevant objects
329 TTree* impTree = static_cast<TTree*>(pc.getObject("impTree")) ;
330 auto impData = static_cast<RooAbsData*>(pc.getObject("impData")) ;
331 RooFormulaVar* cutVar = static_cast<RooFormulaVar*>(pc.getObject("cutVar")) ;
332 const char* cutSpec = pc.getString("cutSpec","",true) ;
333 const char* cutRange = pc.getString("cutRange","",true) ;
334 const char* wgtVarName = pc.getString("wgtVarName","",true) ;
335 RooRealVar* wgtVar = static_cast<RooRealVar*>(pc.getObject("wgtVar")) ;
336 const char* impSliceNames = pc.getString("impSliceState","",true) ;
337 const RooLinkedList& impSliceData = pc.getObjectList("impSliceData") ;
338 const char* lnkSliceNames = pc.getString("lnkSliceState","",true) ;
339 const RooLinkedList& lnkSliceData = pc.getObjectList("lnkSliceData") ;
340 RooCategory* indexCat = static_cast<RooCategory*>(pc.getObject("indexCat")) ;
341 RooArgSet* asymErrorSet = pc.getSet("asymErrSet") ;
342 const char* fname = pc.getString("fname") ;
343 const char* tname = pc.getString("tname") ;
344 Int_t ownLinked = pc.getInt("ownLinked") ;
345 Int_t newWeight = pc.getInt("newWeight1") + pc.getInt("newWeight2") ;
346
347 // Lookup name of weight variable if it was specified by object reference
348 if(wgtVar) {
349 wgtVarName = wgtVar->GetName();
350 }
351
352 auto finalVarsInfo = finalizeVars(vars,indexCat,wgtVarName,impData,impSliceData, pc.getSet("errorSet"));
353 initializeVars(finalVarsInfo.finalVars);
354 if(!finalVarsInfo.weightVarName.empty()) {
355 wgtVarName = finalVarsInfo.weightVarName.c_str();
356 }
357
358 RooArgSet* errorSet = finalVarsInfo.errorSet.empty() ? nullptr : &finalVarsInfo.errorSet;
359
360 // Case 1 --- Link multiple dataset as slices
361 if (lnkSliceNames) {
362
363 // Make import mapping if index category is specified
365 if (indexCat) {
367 strlcpy(tmp, lnkSliceNames, 64000);
368 char *token = strtok(tmp, ",");
369 auto hiter = lnkSliceData.begin();
370 while (token) {
371 hmap[token] = static_cast<RooAbsData *>(*hiter);
372 token = strtok(nullptr, ",");
373 ++hiter;
374 }
375 }
376
377 appendToDir(this,true) ;
378
379 // Initialize RooDataSet with optional weight variable
380 initialize(nullptr) ;
381
383 RooCategory* icat = static_cast<RooCategory*> (indexCat ? _vars.find(indexCat->GetName()) : nullptr ) ;
384 if (!icat) {
385 throw std::string("RooDataSet::RooDataSet() ERROR in constructor, cannot find index category") ;
386 }
387 for (map<string,RooAbsData*>::iterator hiter = hmap.begin() ; hiter!=hmap.end() ; ++hiter) {
388 // Define state labels in index category (both in provided indexCat and in internal copy in dataset)
389 if (indexCat && !indexCat->hasLabel(hiter->first)) {
390 indexCat->defineType(hiter->first) ;
391 coutI(InputArguments) << "RooDataSet::ctor(" << GetName() << ") defining state \"" << hiter->first << "\" in index category " << indexCat->GetName() << std::endl ;
392 }
393 if (icat && !icat->hasLabel(hiter->first)) {
394 icat->defineType(hiter->first) ;
395 }
396 icat->setLabel(hiter->first.c_str()) ;
397 storeMap[icat->getCurrentLabel()]=hiter->second->store() ;
398
399 // Take ownership of slice if requested
400 if (ownLinked) {
401 addOwnedComponent(hiter->first.c_str(),*hiter->second) ;
402 }
403 }
404
405 // Create composite datastore
406 _dstore = std::make_unique<RooCompositeDataStore>(name,title,_vars,*icat,storeMap) ;
407
408 return;
409 }
410
411 // Create empty datastore
412 RooTreeDataStore* tstore = nullptr;
413 if (defaultStorageType==Tree) {
414 _dstore = std::make_unique<RooTreeDataStore>(name,title,_vars,wgtVarName) ;
415 tstore = static_cast<RooTreeDataStore*>(_dstore.get());
416 } else if (defaultStorageType==Vector) {
417 if (wgtVarName && newWeight) {
418 RooAbsArg* wgttmp = _vars.find(wgtVarName) ;
419 if (wgttmp) {
420 wgttmp->setAttribute("NewWeight") ;
421 }
422 }
423 _dstore = std::make_unique<RooVectorDataStore>(name,title,_vars,wgtVarName) ;
424 }
425
426
427 // Make import mapping if index category is specified
428 std::map<string,RooAbsData*> hmap ;
429 if (indexCat) {
430 auto hiter = impSliceData.begin() ;
431 for (const auto& token : ROOT::Split(impSliceNames, ",")) {
432 hmap[token] = static_cast<RooDataSet*>(*hiter);
433 ++hiter;
434 }
435 }
436
437 // process StoreError requests
438 if (errorSet) {
439 std::unique_ptr<RooArgSet> intErrorSet{_vars.selectCommon(*errorSet)};
440 intErrorSet->setAttribAll("StoreError") ;
441 for(RooAbsArg* arg : *intErrorSet) {
442 arg->attachToStore(*_dstore) ;
443 }
444 }
445 if (asymErrorSet) {
446 std::unique_ptr<RooArgSet> intAsymErrorSet{_vars.selectCommon(*asymErrorSet)};
447 intAsymErrorSet->setAttribAll("StoreAsymError") ;
448 for(RooAbsArg* arg : *intAsymErrorSet) {
449 arg->attachToStore(*_dstore) ;
450 }
451 }
452
453 appendToDir(this,true) ;
454
455 // Initialize RooDataSet with optional weight variable
457
458 // Import one or more datasets
459 std::unique_ptr<RooFormulaVar> cutVarTmp;
460
461 if (indexCat) {
462 // Case 2 --- Import multiple RooDataSets as slices
463 loadValuesFromSlices(*indexCat, hmap, cutRange, cutVar, cutSpec);
464 } else if (impData) {
465 // Case 3 --- Import RooDataSet
466 std::unique_ptr<RooDataSet> impDataSet;
467
468 // If we are importing a RooDataHist, first convert it to a RooDataSet
469 if(impData->InheritsFrom(RooDataHist::Class())) {
470 impDataSet = makeDataSetFromDataHist(static_cast<RooDataHist const &>(*impData));
471 impData = impDataSet.get();
472 }
473 if (cutSpec) {
474 cutVarTmp = std::make_unique<RooFormulaVar>(cutSpec, cutSpec, *impData->get(), /*checkVariables=*/false);
475 cutVar = cutVarTmp.get();
476 }
477 _dstore->loadValues(impData->store(), cutVar, cutRange);
478
479 } else if (impTree || (fname && strlen(fname))) {
480 // Case 4 --- Import TTree from memory / file
481 std::unique_ptr<TFile> file;
482
483 if (impTree == nullptr) {
484 file.reset(TFile::Open(fname));
485 if (!file) {
486 std::stringstream ss;
487 ss << "RooDataSet::ctor(" << GetName() << ") ERROR file '" << fname
488 << "' cannot be opened or does not exist";
489 const std::string errMsg = ss.str();
490 coutE(InputArguments) << errMsg << std::endl;
491 throw std::invalid_argument(errMsg);
492 }
493
494 file->GetObject(tname, impTree);
495 if (!impTree) {
496 std::stringstream ss;
497 ss << "RooDataSet::ctor(" << GetName() << ") ERROR file '" << fname
498 << "' does not contain a TTree named '" << tname << "'";
499 const std::string errMsg = ss.str();
500 coutE(InputArguments) << errMsg << std::endl;
501 throw std::invalid_argument(errMsg);
502 }
503 }
504
505 if (cutSpec) {
506 cutVarTmp = std::make_unique<RooFormulaVar>(cutSpec, cutSpec, _vars, /*checkVariables=*/false);
507 cutVar = cutVarTmp.get();
508 }
509
510 if (tstore) {
511 tstore->loadValues(impTree, cutVar, cutRange);
512 } else {
514 tmpstore.loadValues(impTree, cutVar, cutRange);
515 _dstore->append(tmpstore);
516 }
517 }
518}
519
520////////////////////////////////////////////////////////////////////////////////
521/// Constructor of a data set from (part of) an existing data
522/// set. The dimensions of the data set are defined by the 'vars'
523/// RooArgSet, which can be identical to 'dset' dimensions, or a
524/// subset thereof. The 'cuts' string is an optional RooFormula
525/// expression and can be used to select the subset of the data
526/// points in 'dset' to be copied. The cut expression can refer to
527/// any variable in the source dataset. For cuts involving variables
528/// other than those contained in the source data set, such as
529/// intermediate formula objects, use the equivalent constructor
530/// accepting RooFormulaVar reference as cut specification.
531///
532/// For most uses the RooAbsData::reduce() wrapper function, which
533/// uses this constructor, is the most convenient way to create a
534/// subset of an existing data
535
537 const RooArgSet& vars, const char *cuts, const char* wgtVarName) :
538 RooAbsData(name,title,vars)
539{
540 // Initialize datastore
541 if(defaultStorageType == Tree) {
542 _dstore = std::make_unique<RooTreeDataStore>(name,title,_vars,*dset->_dstore,cuts,wgtVarName);
543 } else {
544 std::unique_ptr<RooFormulaVar> cutVar;
545 if (cuts && strlen(cuts) != 0) {
546 // Create a RooFormulaVar cut from given cut expression
547 cutVar = std::make_unique<RooFormulaVar>(cuts, cuts, _vars, /*checkVariables=*/false);
548 }
549 _dstore = std::make_unique<RooVectorDataStore>(name,title,
550 /*tds=*/*dset->_dstore,
551 /*vars=*/_vars,
552 /*cutVar=*/cutVar.get(),
553 /*cutRange=*/nullptr,
554 /*nStart=*/0,
555 /*nStop=*/dset->numEntries(),
556 /*wgtVarName=*/wgtVarName);
557 }
558
559 appendToDir(this,true) ;
560
561 if (wgtVarName) {
562 // Use the supplied weight column
564 } else {
565 if (dset->_wgtVar && vars.find(dset->_wgtVar->GetName())) {
566 // Use the weight column of the source data set
567 initialize(dset->_wgtVar->GetName()) ;
568 } else {
569 initialize(nullptr);
570 }
571 }
573}
574
575
576////////////////////////////////////////////////////////////////////////////////
577/// Constructor of a data set from (part of) an existing data
578/// set. The dimensions of the data set are defined by the 'vars'
579/// RooArgSet, which can be identical to 'dset' dimensions, or a
580/// subset thereof. The 'cutVar' formula variable is used to select
581/// the subset of data points to be copied. For subsets without
582/// selection on the data points, or involving cuts operating
583/// exclusively and directly on the data set dimensions, the
584/// equivalent constructor with a string based cut expression is
585/// recommended.
586///
587/// For most uses the RooAbsData::reduce() wrapper function, which
588/// uses this constructor, is the most convenient way to create a
589/// subset of an existing data
590
592 const RooArgSet& vars, const RooFormulaVar& cutVar, const char* wgtVarName)
593 : RooDataSet{name, title, dset, vars, cutVar.expression(), wgtVarName} {}
594
595////////////////////////////////////////////////////////////////////////////////
596/// Copy constructor
597
600{
601 appendToDir(this,true) ;
602 initialize(other._wgtVar?other._wgtVar->GetName():nullptr);
604}
605
606
607////////////////////////////////////////////////////////////////////////////////
608/// Return an empty clone of this dataset. If vars is not null, only the variables in vars
609/// are added to the definition of the empty clone
610
611RooFit::OwningPtr<RooAbsData> RooDataSet::emptyClone(const char* newName, const char* newTitle, const RooArgSet* vars, const char* wgtVarName) const
612{
613 bool useOldWeight = _wgtVar && (wgtVarName == nullptr || strcmp(wgtVarName, _wgtVar->GetName()) == 0);
614
615 if(newName == nullptr) newName = GetName();
616 if(newTitle == nullptr) newTitle = GetTitle();
618
620 if(vars == nullptr) {
621 vars2.add(_vars);
622 } else {
623 for(RooAbsArg *var : *vars) {
624 // We should take the variables from the original dataset if
625 // available, such that we can query the "StoreError" and
626 // "StoreAsymError" attributes.
627 auto varInData = _vars.find(*var);
628 vars2.add(varInData ? *varInData : *var);
629 }
630 // We also need to add the weight variable of the original dataset if
631 // it's not added yet, again to query the error attributes correctly.
632 if(useOldWeight && !vars2.find(wgtVarName)) vars2.add(*_wgtVar);
633 }
634
635 RooArgSet errorSet;
637
638 for(RooAbsArg *var : vars2) {
639 if(var->getAttribute("StoreError")) errorSet.add(*var);
640 if(var->getAttribute("StoreAsymError")) asymErrorSet.add(*var);
641 }
642
643 using namespace RooFit;
644 return RooFit::makeOwningPtr<RooAbsData>(std::make_unique<RooDataSet>(
645 newName, newTitle, vars2, WeightVar(wgtVarName), StoreError(errorSet), StoreAsymError(asymErrorSet)));
646}
647
648
649
650////////////////////////////////////////////////////////////////////////////////
651/// Initialize the dataset. If wgtVarName is not null, interpret the observable
652/// with that name as event weight
653
655{
658 _wgtVar = nullptr ;
659 if (wgtVarName) {
661 if (!wgt) {
662 coutE(DataHandling) << "RooDataSet::RooDataSet(" << GetName() << "): designated weight variable "
663 << wgtVarName << " not found in set of variables, no weighting will be assigned" << std::endl ;
664 throw std::invalid_argument("RooDataSet::initialize() weight variable could not be initialised.");
665 } else if (!dynamic_cast<RooRealVar*>(wgt)) {
666 coutE(DataHandling) << "RooDataSet::RooDataSet(" << GetName() << "): designated weight variable "
667 << wgtVarName << " is not of type RooRealVar, no weighting will be assigned" << std::endl ;
668 throw std::invalid_argument("RooDataSet::initialize() weight variable could not be initialised.");
669 } else {
671 _wgtVar = static_cast<RooRealVar*>(wgt) ;
672 }
673 }
674}
675
676
677
678////////////////////////////////////////////////////////////////////////////////
679/// Implementation of RooAbsData virtual method that drives the RooAbsData::reduce() methods
680
681std::unique_ptr<RooAbsData> RooDataSet::reduceEng(const RooArgSet &varSubset, const RooFormulaVar *cutVar,
682 const char *cutRange, std::size_t nStart, std::size_t nStop) const
683{
684 checkInit();
685 RooArgSet tmp(varSubset);
686 if (_wgtVar) {
687 tmp.add(*_wgtVar);
688 }
689
690 auto createEmptyClone = [&]() { return emptyClone(GetName(), GetTitle(), &tmp); };
691
692 std::unique_ptr<RooAbsData> out{createEmptyClone()};
693
694 if (!cutRange || strchr(cutRange, ',') == nullptr) {
695 auto &ds = static_cast<RooDataSet &>(*out);
696 ds._dstore = _dstore->reduce(ds.GetName(), ds.GetTitle(), ds._vars, cutVar, cutRange, nStart, nStop);
697 ds._cachedVars.add(_dstore->cachedVars());
698 } else {
699 // Composite case: multiple ranges
700 auto tokens = ROOT::Split(cutRange, ",");
702 std::stringstream errMsg;
703 errMsg << "Error in RooAbsData::reduce! The ranges " << cutRange << " are overlapping!";
704 throw std::runtime_error(errMsg.str());
705 }
706 for (const auto &token : tokens) {
707 std::unique_ptr<RooAbsData> appendedData{createEmptyClone()};
708 auto &ds = static_cast<RooDataSet &>(*appendedData);
709 ds._dstore = _dstore->reduce(ds.GetName(), ds.GetTitle(), ds._vars, cutVar, token.c_str(), nStart, nStop);
710 ds._cachedVars.add(_dstore->cachedVars());
711 static_cast<RooDataSet &>(*out).append(ds);
712 }
713 }
714 return out;
715}
716
717
718
719////////////////////////////////////////////////////////////////////////////////
720/// Destructor
721
727
728
729
730////////////////////////////////////////////////////////////////////////////////
731/// Return binned clone of this dataset
732
734{
735 std::string title;
736 std::string name;
737 if (newName) {
738 name = newName ;
739 } else {
740 name = std::string(GetName()) + "_binned" ;
741 }
742 if (newTitle) {
743 title = newTitle ;
744 } else {
745 title = std::string(GetTitle()) + "_binned" ;
746 }
747
748 return RooFit::makeOwningPtr(std::make_unique<RooDataHist>(name,title,*get(),*this));
749}
750
751
752
753////////////////////////////////////////////////////////////////////////////////
754/// Return event weight of current event
755
756double RooDataSet::weight() const
757{
758 return store()->weight() ;
759}
760
761
762
763////////////////////////////////////////////////////////////////////////////////
764/// Return squared event weight of the current event. If this RooDataSet has no
765/// weight errors set, this will be the same as `weight() * weight()`, like
766/// expected for an unbinned dataset. When weight errors are set, it is assumed
767/// that the RooDataSet represents a weighted binned dataset and
768/// weightSquared() is the corresponding sum of weight squares for the bin.
769
771{
772 const double w = store()->weight();
773 const double e = weightError();
774 return e > 0.0 ? e * e : w * w;
775}
776
777
778////////////////////////////////////////////////////////////////////////////////
779/// \see RooAbsData::getWeightBatch().
780std::span<const double> RooDataSet::getWeightBatch(std::size_t first, std::size_t len, bool sumW2 /*=false*/) const {
781
782 std::size_t nEntries = this->numEntries(); // for the casting to std::size_t
783
784 if(first + len > nEntries) {
785 throw std::runtime_error("RooDataSet::getWeightBatch(): requested range not valid for dataset.");
786 }
787
788 std::span<const double> allWeights = _dstore->getWeightBatch(0, numEntries());
789 if(allWeights.empty()) return {};
790
791 if(!sumW2) return {&*(std::cbegin(allWeights) + first), len};
792
793 // Treat the sumW2 case with a result buffer, first reset buffer if the
794 // number of entries doesn't match with the dataset anymore
795 if(_sumW2Buffer && _sumW2Buffer->size() != nEntries) _sumW2Buffer.reset();
796
797 if (!_sumW2Buffer) {
798 _sumW2Buffer = std::make_unique<std::vector<double>>();
799 _sumW2Buffer->reserve(nEntries);
800
801 for (std::size_t i = 0; i < nEntries; ++i) {
802 get(i);
803 _sumW2Buffer->push_back(weightSquared());
804 }
805 }
806
807 return std::span<const double>(&*(_sumW2Buffer->begin() + first), len);
808}
809
810
811////////////////////////////////////////////////////////////////////////////////
812/// \copydoc RooAbsData::weightError(double&,double&,RooAbsData::ErrorType) const
813/// \param etype error type
814void RooDataSet::weightError(double& lo, double& hi, ErrorType etype) const
815{
816 store()->weightError(lo,hi,etype) ;
817}
818
819
820////////////////////////////////////////////////////////////////////////////////
821/// \copydoc RooAbsData::weightError(ErrorType)
822/// \param etype error type
824{
825 return store()->weightError(etype) ;
826}
827
828
829////////////////////////////////////////////////////////////////////////////////
830/// Return RooArgSet with coordinates of event 'index'
831
833{
835 return ret ? &_varsNoWgt : nullptr ;
836}
837
838
839////////////////////////////////////////////////////////////////////////////////
840
842{
843 return store()->sumEntries() ;
844}
845
846
847////////////////////////////////////////////////////////////////////////////////
848/// Return the sum of weights in all entries matching cutSpec (if specified)
849/// and in named range cutRange (if specified)
850
851double RooDataSet::sumEntries(const char* cutSpec, const char* cutRange) const
852{
853 // Setup RooFormulaVar for cutSpec if it is present
854 std::unique_ptr<RooFormula> select = nullptr ;
855 if (cutSpec && strlen(cutSpec) > 0) {
856 select = std::make_unique<RooFormula>("select",cutSpec,*get()) ;
857 }
858
859 // Shortcut for unweighted unselected datasets
860 if (!select && !cutRange && !isWeighted()) {
861 return numEntries() ;
862 }
863
864 // Otherwise sum the weights in the event
866 for (int i = 0 ; i<numEntries() ; i++) {
867 get(i) ;
868 if (select && select->eval()==0.) continue ;
869 if (cutRange && !_vars.allInRange(cutRange)) continue ;
870 sumw += weight();
871 }
872
873 return sumw.Sum() ;
874}
875
876
877
878
879////////////////////////////////////////////////////////////////////////////////
880/// Return true if dataset contains weighted events
881
883{
884 return store() ? store()->isWeighted() : false;
885}
886
887
888
889////////////////////////////////////////////////////////////////////////////////
890/// Returns true if histogram contains bins with entries with a non-integer weight
891
893{
894 // Return false if we have no weights
895 if (!_wgtVar) return false ;
896
897 // Now examine individual weights
898 for (int i=0 ; i<numEntries() ; i++) {
899 get(i) ;
900 if (std::abs(weight()-Int_t(weight()))>1e-10) return true ;
901 }
902 // If sum of weights is less than number of events there are negative (integer) weights
903 if (sumEntries()<numEntries()) return true ;
904
905 return false ;
906}
907
908
909
910
911////////////////////////////////////////////////////////////////////////////////
912/// Return a RooArgSet with the coordinates of the current event
913
915{
916 return &_varsNoWgt ;
917}
918
919
920
921////////////////////////////////////////////////////////////////////////////////
922/// Add a data point, with its coordinates specified in the 'data' argset, to the data set.
923/// Any variables present in 'data' but not in the dataset will be silently ignored.
924/// \param[in] data Data point.
925/// \param[in] wgt Event weight. Defaults to 1. The current value of the weight variable is
926/// ignored.
927/// \note To obtain weighted events, a variable must be designated `WeightVar` in the constructor.
928/// \param[in] wgtError Optional weight error.
929/// \note This requires including the weight variable in the set of `StoreError` variables when constructing
930/// the dataset.
931
932void RooDataSet::add(const RooArgSet& data, double wgt, double wgtError)
933{
934 checkInit() ;
935
936 const double oldW = _wgtVar ? _wgtVar->getVal() : 0.;
937
939
940 if (_wgtVar) {
941 _wgtVar->setVal(wgt) ;
942 if (wgtError!=0.) {
944 }
945 } else if ((wgt != 1. || wgtError != 0.) && _errorMsgCount < 5) {
946 ccoutE(DataHandling) << "An event weight/error was passed but no weight variable was defined"
947 << " in the dataset '" << GetName() << "'. The weight will be ignored." << std::endl;
949 }
950
952 && wgtError != 0.
953 && std::abs(wgt*wgt - wgtError)/wgtError > 1.E-15 //Exception for standard wgt^2 errors, which need not be stored.
954 && _errorMsgCount < 5 && !_wgtVar->getAttribute("StoreError")) {
955 coutE(DataHandling) << "An event weight error was passed to the RooDataSet '" << GetName()
956 << "', but the weight variable '" << _wgtVar->GetName()
957 << "' does not store errors. Check `StoreError` in the RooDataSet constructor." << std::endl;
959 }
960
961 fill();
962
963 // Restore weight state
964 if (_wgtVar) {
967 }
968}
969
970
971
972
973////////////////////////////////////////////////////////////////////////////////
974/// Add a data point, with its coordinates specified in the 'data' argset, to the data set.
975/// Any variables present in 'data' but not in the dataset will be silently ignored.
976/// \param[in] indata Data point.
977/// \param[in] inweight Event weight. The current value of the weight variable is ignored.
978/// \note To obtain weighted events, a variable must be designated `WeightVar` in the constructor.
979/// \param[in] weightErrorLo Asymmetric weight error.
980/// \param[in] weightErrorHi Asymmetric weight error.
981/// \note This requires including the weight variable in the set of `StoreAsymError` variables when constructing
982/// the dataset.
983
985{
986 checkInit() ;
987
988 const double oldW = _wgtVar ? _wgtVar->getVal() : 0.;
989
991 if (_wgtVar) {
994 } else if (inweight != 1. && _errorMsgCount < 5) {
995 ccoutE(DataHandling) << "An event weight was given but no weight variable was defined"
996 << " in the dataset '" << GetName() << "'. The weight will be ignored." << std::endl;
998 }
999
1001 && _errorMsgCount < 5 && !_wgtVar->getAttribute("StoreAsymError")) {
1002 coutE(DataHandling) << "An event weight error was passed to the RooDataSet '" << GetName()
1003 << "', but the weight variable '" << _wgtVar->GetName()
1004 << "' does not store errors. Check `StoreAsymError` in the RooDataSet constructor." << std::endl;
1006 }
1007
1008 fill();
1009
1010 // Restore weight state
1011 if (_wgtVar) {
1014 }
1015}
1016
1017
1018
1019
1020
1021////////////////////////////////////////////////////////////////////////////////
1022/// Add a data point, with its coordinates specified in the 'data' argset, to the data set.
1023/// \attention The order and type of the input variables are **assumed** to be the same as
1024/// for the RooArgSet returned by RooDataSet::get(). Input values will just be written
1025/// into the internal data columns by ordinal position.
1026/// \param[in] data Data point.
1027/// \param[in] wgt Event weight. Defaults to 1. The current value of the weight variable is
1028/// ignored.
1029/// \note To obtain weighted events, a variable must be designated `WeightVar` in the constructor.
1030/// \param[in] wgtError Optional weight error.
1031/// \note This requires including the weight variable in the set of `StoreError` variables when constructing
1032/// the dataset.
1033
1034void RooDataSet::addFast(const RooArgSet& data, double wgt, double wgtError)
1035{
1036 checkInit() ;
1037
1038 const double oldW = _wgtVar ? _wgtVar->getVal() : 0.;
1039
1040 _varsNoWgt.assignFast(data,_dstore->dirtyProp());
1041 if (_wgtVar) {
1042 _wgtVar->setVal(wgt) ;
1043 if (wgtError!=0.) {
1045 }
1046 } else if (wgt != 1. && _errorMsgCount < 5) {
1047 ccoutE(DataHandling) << "An event weight was given but no weight variable was defined"
1048 << " in the dataset '" << GetName() << "'. The weight will be ignored." << std::endl;
1050 }
1051
1052 fill();
1053
1055 && wgtError != 0. && wgtError != wgt*wgt //Exception for standard weight error, which need not be stored
1056 && _errorMsgCount < 5 && !_wgtVar->getAttribute("StoreError")) {
1057 coutE(DataHandling) << "An event weight error was passed to the RooDataSet '" << GetName()
1058 << "', but the weight variable '" << _wgtVar->GetName()
1059 << "' does not store errors. Check `StoreError` in the RooDataSet constructor." << std::endl;
1061 }
1063 _doWeightErrorCheck = false;
1064 }
1065
1066 if (_wgtVar) {
1069 }
1070}
1071
1072
1073
1074////////////////////////////////////////////////////////////////////////////////
1075
1078{
1079 checkInit() ;
1081 if (data1) dsetList.push_back(data1) ;
1082 if (data2) dsetList.push_back(data2) ;
1083 if (data3) dsetList.push_back(data3) ;
1084 if (data4) dsetList.push_back(data4) ;
1085 if (data5) dsetList.push_back(data5) ;
1086 if (data6) dsetList.push_back(data6) ;
1087 return merge(dsetList) ;
1088}
1089
1090
1091
1092////////////////////////////////////////////////////////////////////////////////
1093/// Merge columns of supplied data set(s) with this data set. All
1094/// data sets must have equal number of entries. In case of
1095/// duplicate columns the column of the last dataset in the list
1096/// prevails
1097
1099{
1100
1101 checkInit() ;
1102 // Sanity checks: data sets must have the same size
1103 for (list<RooDataSet*>::iterator iter = dsetList.begin() ; iter != dsetList.end() ; ++iter) {
1104 if (numEntries()!=(*iter)->numEntries()) {
1105 coutE(InputArguments) << "RooDataSet::merge(" << GetName() << ") ERROR: datasets have different size" << std::endl ;
1106 return true ;
1107 }
1108 }
1109
1110 // Extend vars with elements of other dataset
1112 for (list<RooDataSet*>::iterator iter = dsetList.begin() ; iter != dsetList.end() ; ++iter) {
1113 _vars.addClone((*iter)->_vars,true) ;
1114 dstoreList.push_back((*iter)->store()) ;
1115 }
1116
1117 // Merge data stores
1119 mergedStore->SetName(_dstore->GetName()) ;
1120 mergedStore->SetTitle(_dstore->GetTitle()) ;
1121
1122 // Replace current data store with merged store
1123 _dstore.reset(mergedStore);
1124
1125 initialize(_wgtVar?_wgtVar->GetName():nullptr) ;
1126 return false ;
1127}
1128
1129
1130////////////////////////////////////////////////////////////////////////////////
1131/// Add all data points of given data set to this data set.
1132/// Observable in 'data' that are not in this dataset
1133/// with not be transferred
1134
1136{
1137 checkInit() ;
1138 _dstore->append(*data._dstore) ;
1139}
1140
1141
1142
1143////////////////////////////////////////////////////////////////////////////////
1144/// Add a column with the values of the given (function) argument
1145/// to this dataset. The function value is calculated for each
1146/// event using the observable values of each event in case the
1147/// function depends on variables with names that are identical
1148/// to the observable names in the dataset
1149
1151{
1152 checkInit() ;
1153 std::unique_ptr<RooAbsArg> ret{_dstore->addColumn(var,adjustRange)};
1154 RooAbsArg* retPtr = ret.get();
1155 _vars.addOwned(std::move(ret));
1156 initialize(_wgtVar?_wgtVar->GetName():nullptr) ;
1157 return retPtr;
1158}
1159
1160
1161////////////////////////////////////////////////////////////////////////////////
1162/// Add a column with the values of the given list of (function)
1163/// argument to this dataset. Each function value is calculated for
1164/// each event using the observable values of the event in case the
1165/// function depends on variables with names that are identical to
1166/// the observable names in the dataset
1167
1169{
1170 auto * holderSet = new RooArgSet{};
1171 for(RooAbsArg * var : varList) {
1172 holderSet->add(*addColumn(*var));
1173 }
1174 return holderSet;
1175}
1176
1177
1178
1179
1180
1181////////////////////////////////////////////////////////////////////////////////
1182/// Special plot method for 'X-Y' datasets used in \f$ \chi^2 \f$ fitting.
1183/// For general plotting, see RooAbsData::plotOn().
1184///
1185/// These datasets
1186/// have one observable (X) and have weights (Y) and associated errors.
1187/// <table>
1188/// <tr><th> Contents options <th> Effect
1189/// <tr><td> YVar(RooRealVar& var) <td> Designate specified observable as 'y' variable
1190/// If not specified, the event weight will be the y variable
1191/// <tr><th> Histogram drawing options <th> Effect
1192/// <tr><td> DrawOption(const char* opt) <td> Select ROOT draw option for resulting TGraph object
1193/// <tr><td> LineStyle(Int_t style) <td> Select line style by ROOT line style code, default is solid
1194/// <tr><td> LineColor(Int_t color) <td> Select line color by ROOT color code, default is black
1195/// <tr><td> LineWidth(Int_t width) <td> Select line with in pixels, default is 3
1196/// <tr><td> MarkerStyle(Int_t style) <td> Select the ROOT marker style, default is 21
1197/// <tr><td> MarkerColor(Int_t color) <td> Select the ROOT marker color, default is black
1198/// <tr><td> MarkerSize(double size) <td> Select the ROOT marker size
1199/// <tr><td> Rescale(double factor) <td> Apply global rescaling factor to histogram
1200/// <tr><th> Misc. other options <th> Effect
1201/// <tr><td> Name(const chat* name) <td> Give curve specified name in frame. Useful if curve is to be referenced later
1202/// <tr><td> Invisible(bool flag) <td> Add curve to frame, but do not display. Useful in combination AddTo()
1203/// </table>
1204
1206 const RooCmdArg& arg3, const RooCmdArg& arg4,
1207 const RooCmdArg& arg5, const RooCmdArg& arg6,
1208 const RooCmdArg& arg7, const RooCmdArg& arg8) const
1209{
1210 checkInit() ;
1211
1212 RooLinkedList argList ;
1213 argList.Add((TObject*)&arg1) ; argList.Add((TObject*)&arg2) ;
1214 argList.Add((TObject*)&arg3) ; argList.Add((TObject*)&arg4) ;
1215 argList.Add((TObject*)&arg5) ; argList.Add((TObject*)&arg6) ;
1216 argList.Add((TObject*)&arg7) ; argList.Add((TObject*)&arg8) ;
1217
1218 // Process named arguments
1219 RooCmdConfig pc("RooDataSet::plotOnXY(" + std::string(GetName()) + ")");
1220 pc.defineString("drawOption","DrawOption",0,"P") ;
1221 pc.defineString("histName","Name",0,"") ;
1222 pc.defineInt("lineColor","LineColor",0,-999) ;
1223 pc.defineInt("lineStyle","LineStyle",0,-999) ;
1224 pc.defineInt("lineWidth","LineWidth",0,-999) ;
1225 pc.defineInt("markerColor","MarkerColor",0,-999) ;
1226 pc.defineInt("markerStyle","MarkerStyle",0,8) ;
1227 pc.defineDouble("markerSize","MarkerSize",0,-999) ;
1228 pc.defineInt("fillColor","FillColor",0,-999) ;
1229 pc.defineInt("fillStyle","FillStyle",0,-999) ;
1230 pc.defineInt("histInvisible","Invisible",0,0) ;
1231 pc.defineDouble("scaleFactor","Rescale",0,1.) ;
1232 pc.defineObject("xvar","XVar",0,nullptr) ;
1233 pc.defineObject("yvar","YVar",0,nullptr) ;
1234
1235
1236 // Process & check varargs
1237 pc.process(argList) ;
1238 if (!pc.ok(true)) {
1239 return frame ;
1240 }
1241
1242 // Extract values from named arguments
1243 const char* drawOptions = pc.getString("drawOption") ;
1244 Int_t histInvisible = pc.getInt("histInvisible") ;
1245 const char* histName = pc.getString("histName",nullptr,true) ;
1246 double scaleFactor = pc.getDouble("scaleFactor") ;
1247
1248 RooRealVar* xvar = static_cast<RooRealVar*>(_vars.find(frame->getPlotVar()->GetName())) ;
1249
1250 // Determine Y variable (default is weight, if present)
1251 RooRealVar* yvar = static_cast<RooRealVar*>(pc.getObject("yvar")) ;
1252
1253 // Sanity check. XY plotting only applies to weighted datasets if no YVar is specified
1254 if (!_wgtVar && !yvar) {
1255 coutE(InputArguments) << "RooDataSet::plotOnXY(" << GetName() << ") ERROR: no YVar() argument specified and dataset is not weighted" << std::endl ;
1256 return nullptr ;
1257 }
1258
1259 RooRealVar* dataY = yvar ? static_cast<RooRealVar*>(_vars.find(yvar->GetName())) : nullptr ;
1260 if (yvar && !dataY) {
1261 coutE(InputArguments) << "RooDataSet::plotOnXY(" << GetName() << ") ERROR on YVar() argument, dataset does not contain a variable named " << yvar->GetName() << std::endl ;
1262 return nullptr ;
1263 }
1264
1265
1266 // Make RooHist representing XY contents of data
1267 RooHist* graph = new RooHist ;
1268 if (histName) {
1269 graph->SetName(histName) ;
1270 } else {
1271 graph->SetName(("hxy_" + std::string(GetName())).c_str());
1272 }
1273
1274 for (int i=0 ; i<numEntries() ; i++) {
1275 get(i) ;
1276 double x = xvar->getVal() ;
1277 double exlo = xvar->getErrorLo() ;
1278 double exhi = xvar->getErrorHi() ;
1279 double y;
1280 double eylo;
1281 double eyhi;
1282 if (!dataY) {
1283 y = weight() ;
1285 } else {
1286 y = dataY->getVal() ;
1287 eylo = dataY->getErrorLo() ;
1288 eyhi = dataY->getErrorHi() ;
1289 }
1290 graph->addBinWithXYError(x,y,-1*exlo,exhi,-1*eylo,eyhi,scaleFactor) ;
1291 }
1292
1293 // Adjust style options according to named arguments
1294 Int_t lineColor = pc.getInt("lineColor") ;
1295 Int_t lineStyle = pc.getInt("lineStyle") ;
1296 Int_t lineWidth = pc.getInt("lineWidth") ;
1297 Int_t markerColor = pc.getInt("markerColor") ;
1298 Int_t markerStyle = pc.getInt("markerStyle") ;
1299 Size_t markerSize = pc.getDouble("markerSize") ;
1300 Int_t fillColor = pc.getInt("fillColor") ;
1301 Int_t fillStyle = pc.getInt("fillStyle") ;
1302
1303 if (lineColor!=-999) graph->SetLineColor(lineColor) ;
1304 if (lineStyle!=-999) graph->SetLineStyle(lineStyle) ;
1305 if (lineWidth!=-999) graph->SetLineWidth(lineWidth) ;
1306 if (markerColor!=-999) graph->SetMarkerColor(markerColor) ;
1307 if (markerStyle!=-999) graph->SetMarkerStyle(markerStyle) ;
1308 if (markerSize!=-999) graph->SetMarkerSize(markerSize) ;
1309 if (fillColor!=-999) graph->SetFillColor(fillColor) ;
1310 if (fillStyle!=-999) graph->SetFillStyle(fillStyle) ;
1311
1312 // Add graph to frame
1313 frame->addPlotable(graph,drawOptions,histInvisible) ;
1314
1315 return frame ;
1316}
1317
1318
1319
1320
1321////////////////////////////////////////////////////////////////////////////////
1322/// Read given list of ascii files, and construct a data set, using the given
1323/// ArgList as structure definition.
1324/// \param fileList Multiple file names, comma separated. Each
1325/// file is optionally prefixed with 'commonPath' if such a path is
1326/// provided
1327///
1328/// \param varList Specify the dimensions of the dataset to be built.
1329/// This list describes the order in which these dimensions appear in the
1330/// ascii files to be read.
1331/// Each line in the ascii file should contain N white-space separated
1332/// tokens, with N the number of args in `varList`. Any text beyond
1333/// N tokens will be ignored with a warning message.
1334/// (NB: This is the default output of RooArgList::writeToStream())
1335///
1336/// \param verbOpt `Q` be quiet, `D` debug mode (verbose)
1337///
1338/// \param commonPath All filenames in `fileList` will be prefixed with this optional path.
1339///
1340/// \param indexCatName Interpret the data as belonging to category `indexCatName`.
1341/// When multiple files are read, a RooCategory arg in `varList` can
1342/// optionally be designated to hold information about the source file
1343/// of each data point. This feature is enabled by giving the name
1344/// of the (already existing) category variable in `indexCatName`.
1345///
1346/// \attention If the value of any of the variables on a given line exceeds the
1347/// fit range associated with that dimension, the entire line will be
1348/// ignored. A warning message is printed in each case, unless the
1349/// `Q` verbose option is given. The number of events read and skipped
1350/// is always summarized at the end.
1351///
1352/// If no further information is given a label name 'fileNNN' will
1353/// be assigned to each event, where NNN is the sequential number of
1354/// the source file in `fileList`.
1355///
1356/// Alternatively, it is possible to override the default label names
1357/// of the index category by specifying them in the fileList string:
1358/// When instead of `file1.txt,file2.txt` the string
1359/// `file1.txt:FOO,file2.txt:BAR` is specified, a state named "FOO"
1360/// is assigned to the index category for each event originating from
1361/// file1.txt. The labels FOO,BAR may be predefined in the index
1362/// category via defineType(), but don't have to be.
1363///
1364/// Finally, one can also assign the same label to multiple files,
1365/// either by specifying `file1.txt:FOO,file2,txt:FOO,file3.txt:BAR`
1366/// or `file1.txt,file2.txt:FOO,file3.txt:BAR`.
1367///
1368
1370 const char *verbOpt, const char* commonPath,
1371 const char* indexCatName) {
1372 // Make working copy of variables list
1373 RooArgList variables(varList) ;
1374
1375 // Append blinding state category to variable list if not already there
1376 bool ownIsBlind(true) ;
1377 RooAbsArg* blindState = variables.find("blindState") ;
1378 if (!blindState) {
1379 blindState = new RooCategory("blindState","Blinding State") ;
1380 variables.add(*blindState) ;
1381 } else {
1382 ownIsBlind = false ;
1383 if (blindState->IsA()!=RooCategory::Class()) {
1384 oocoutE(nullptr,DataHandling) << "RooDataSet::read: ERROR: variable list already contains"
1385 << "a non-RooCategory blindState member" << std::endl ;
1386 return nullptr ;
1387 }
1388 oocoutW(nullptr,DataHandling) << "RooDataSet::read: WARNING: recycling existing "
1389 << "blindState category in variable list" << std::endl ;
1390 }
1391 RooCategory* blindCat = static_cast<RooCategory*>(blindState) ;
1392
1393 // Configure blinding state category
1394 blindCat->setAttribute("Dynamic") ;
1395 blindCat->defineType("Normal",0) ;
1396 blindCat->defineType("Blind",1) ;
1397
1398 // parse the option string
1400 opts.ToLower();
1401 bool verbose= !opts.Contains("q");
1402 bool debug= opts.Contains("d");
1403
1404 auto data = std::make_unique<RooDataSet>("dataset", fileList, variables);
1405 if (ownIsBlind) { variables.remove(*blindState) ; delete blindState ; }
1406 if(!data) {
1407 oocoutE(nullptr,DataHandling) << "RooDataSet::read: unable to create a new dataset"
1408 << std::endl;
1409 return nullptr;
1410 }
1411
1412 // Redirect blindCat to point to the copy stored in the data set
1413 blindCat = static_cast<RooCategory*>(data->_vars.find("blindState")) ;
1414
1415 // Find index category, if requested
1416 RooCategory *indexCat = nullptr;
1417 //RooCategory *indexCatOrig = 0;
1418 if (indexCatName) {
1419 RooAbsArg* tmp = nullptr;
1420 tmp = data->_vars.find(indexCatName) ;
1421 if (!tmp) {
1422 oocoutE(data.get(),DataHandling) << "RooDataSet::read: no index category named "
1423 << indexCatName << " in supplied variable list" << std::endl ;
1424 return nullptr;
1425 }
1426 if (tmp->IsA()!=RooCategory::Class()) {
1427 oocoutE(data.get(),DataHandling) << "RooDataSet::read: variable " << indexCatName
1428 << " is not a RooCategory" << std::endl ;
1429 return nullptr;
1430 }
1431 indexCat = static_cast<RooCategory*>(tmp);
1432
1433 // Prevent RooArgSet from attempting to read in indexCat
1434 indexCat->setAttribute("Dynamic") ;
1435 }
1436
1437
1438 Int_t outOfRange(0) ;
1439
1440 // Loop over all names in comma separated list
1441 Int_t fileSeqNum(0);
1442 for (const auto& filename : ROOT::Split(std::string(fileList), ", ")) {
1443 // Determine index category number, if this option is active
1444 if (indexCat) {
1445
1446 // Find and detach optional file category name
1447 const char *catname = strchr(filename.c_str(),':');
1448
1449 if (catname) {
1450 // Use user category name if provided
1451 catname++ ;
1452
1453 if (indexCat->hasLabel(catname)) {
1454 // Use existing category index
1455 indexCat->setLabel(catname);
1456 } else {
1457 // Register cat name
1458 indexCat->defineType(catname,fileSeqNum) ;
1459 indexCat->setIndex(fileSeqNum) ;
1460 }
1461 } else {
1462 // Assign autogenerated name
1463 char newLabel[128] ;
1464 snprintf(newLabel,128,"file%03d",fileSeqNum) ;
1465 if (indexCat->defineType(newLabel,fileSeqNum)) {
1466 oocoutE(data.get(), DataHandling) << "RooDataSet::read: Error, cannot register automatic type name " << newLabel
1467 << " in index category " << indexCat->GetName() << std::endl ;
1468 return nullptr ;
1469 }
1470 // Assign new category number
1471 indexCat->setIndex(fileSeqNum) ;
1472 }
1473 }
1474
1475 oocoutI(data.get(), DataHandling) << "RooDataSet::read: reading file " << filename << std::endl ;
1476
1477 // Prefix common path
1479 fullName.Append(filename) ;
1480 ifstream file(fullName) ;
1481
1482 if (!file.good()) {
1483 oocoutE(data.get(), DataHandling) << "RooDataSet::read: unable to open '"
1484 << filename << "'. Returning nullptr now." << std::endl;
1485 return nullptr;
1486 }
1487
1488 // double value;
1489 Int_t line(0) ;
1490 bool haveBlindString(false) ;
1491
1492 while(file.good() && !file.eof()) {
1493 line++;
1494 if(debug) oocxcoutD(data.get(),DataHandling) << "reading line " << line << std::endl;
1495
1496 // process comment lines
1497 if (file.peek() == '#') {
1498 if(debug) oocxcoutD(data.get(),DataHandling) << "skipping comment on line " << line << std::endl;
1499 } else {
1500 // Read single line
1501 bool readError = variables.readFromStream(file,true,verbose) ;
1502 data->_vars.assign(variables) ;
1503
1504 // Stop on read error
1505 if(!file.good()) {
1506 oocoutE(data.get(), DataHandling) << "RooDataSet::read(static): read error at line " << line << std::endl ;
1507 break;
1508 }
1509
1510 if (readError) {
1511 outOfRange++ ;
1512 } else {
1513 blindCat->setIndex(haveBlindString) ;
1514 data->fill(); // store this event
1515 }
1516 }
1517
1518 // Skip all white space (including empty lines).
1519 while (isspace(file.peek())) {
1520 char dummy;
1521 file >> std::noskipws >> dummy >> std::skipws;
1522 }
1523 }
1524
1525 file.close();
1526
1527 // get next file name
1528 fileSeqNum++ ;
1529 }
1530
1531 if (indexCat) {
1532 // Copy dynamically defined types from new data set to indexCat in original list
1533 assert(dynamic_cast<RooCategory*>(variables.find(indexCatName)));
1534 const auto origIndexCat = static_cast<RooCategory*>(variables.find(indexCatName));
1535 for (const auto& nameIdx : *indexCat) {
1536 origIndexCat->defineType(nameIdx.first, nameIdx.second);
1537 }
1538 }
1539 oocoutI(data.get(),DataHandling) << "RooDataSet::read: read " << data->numEntries()
1540 << " events (ignored " << outOfRange << " out of range events)" << std::endl;
1541
1542 return data.release();
1543}
1544
1545
1546
1547
1548////////////////////////////////////////////////////////////////////////////////
1549/// Write the contents of this dataset to an ASCII file with the specified name.
1550/// Each event will be written as a single line containing the written values
1551/// of each observable in the order they were declared in the dataset and
1552/// separated by whitespaces
1553
1554bool RooDataSet::write(const char* filename) const
1555{
1556 // Open file for writing
1557 ofstream ofs(filename) ;
1558 if (ofs.fail()) {
1559 coutE(DataHandling) << "RooDataSet::write(" << GetName() << ") cannot create file " << filename << std::endl ;
1560 return true ;
1561 }
1562
1563 // Write all lines as arglist in compact mode
1564 coutI(DataHandling) << "RooDataSet::write(" << GetName() << ") writing ASCII file " << filename << std::endl ;
1565 return write(ofs);
1566}
1567
1568////////////////////////////////////////////////////////////////////////////////
1569/// Write the contents of this dataset to the stream.
1570/// Each event will be written as a single line containing the written values
1571/// of each observable in the order they were declared in the dataset and
1572/// separated by whitespaces
1573
1574bool RooDataSet::write(ostream & ofs) const {
1575 checkInit();
1576
1577 for (Int_t i=0; i<numEntries(); ++i) {
1578 get(i)->writeToStream(ofs,true);
1579 }
1580
1581 if (ofs.fail()) {
1582 coutW(DataHandling) << "RooDataSet::write(" << GetName() << "): WARNING error(s) have occurred in writing" << std::endl ;
1583 }
1584
1585 return ofs.fail() ;
1586}
1587
1588
1589////////////////////////////////////////////////////////////////////////////////
1590/// Print info about this dataset to the specified output stream.
1591///
1592/// Standard: number of entries
1593/// Shape: list of variables we define & were generated with
1594
1595void RooDataSet::printMultiline(ostream& os, Int_t contents, bool verbose, TString indent) const
1596{
1597 checkInit() ;
1598 RooAbsData::printMultiline(os,contents,verbose,indent) ;
1599 if (_wgtVar) {
1600 os << indent << " Dataset variable \"" << _wgtVar->GetName() << "\" is interpreted as the event weight" << std::endl ;
1601 }
1602}
1603
1604
1605////////////////////////////////////////////////////////////////////////////////
1606/// Print value of the dataset, i.e. the sum of weights contained in the dataset
1607
1608void RooDataSet::printValue(ostream& os) const
1609{
1610 os << numEntries() << " entries" ;
1611 if (isWeighted()) {
1612 os << " (" << sumEntries() << " weighted)" ;
1613 }
1614}
1615
1616
1617
1618////////////////////////////////////////////////////////////////////////////////
1619/// Print argument of dataset, i.e. the observable names
1620
1621void RooDataSet::printArgs(ostream& os) const
1622{
1623 os << "[" ;
1624 bool first(true) ;
1625 for(RooAbsArg* arg : _varsNoWgt) {
1626 if (first) {
1627 first=false ;
1628 } else {
1629 os << "," ;
1630 }
1631 os << arg->GetName() ;
1632 }
1633 if (_wgtVar) {
1634 os << ",weight:" << _wgtVar->GetName() ;
1635 }
1636 os << "]" ;
1637}
1638
1639
1640
1641////////////////////////////////////////////////////////////////////////////////
1642/// Change the name of this dataset into the given name
1643
1644void RooDataSet::SetName(const char *name)
1645{
1646 if (_dir) _dir->GetList()->Remove(this);
1647 // We need to use the function from RooAbsData, because it already overrides TNamed::SetName
1649 if (_dir) _dir->GetList()->Add(this);
1650}
1651
1652
1653////////////////////////////////////////////////////////////////////////////////
1654/// Change the title of this dataset into the given name
1655
1656void RooDataSet::SetNameTitle(const char *name, const char* title)
1657{
1658 SetName(name);
1659 SetTitle(title);
1660}
1661
1662
1663////////////////////////////////////////////////////////////////////////////////
1664/// Stream an object of class RooDataSet.
1665
1667{
1668 if (R__b.IsReading()) {
1669
1670 UInt_t R__s;
1671 UInt_t R__c;
1672 Version_t R__v = R__b.ReadVersion(&R__s, &R__c);
1673
1674 if (R__v > 1) {
1675
1676 // Use new-style streaming for version >1
1677 R__b.ReadClassBuffer(RooDataSet::Class(), this, R__v, R__s, R__c);
1678
1679 } else {
1680
1681 // Legacy dataset conversion happens here. Legacy RooDataSet inherits from RooTreeData
1682 // which in turn inherits from RooAbsData. Manually stream RooTreeData contents on
1683 // file here and convert it into a RooTreeDataStore which is installed in the
1684 // new-style RooAbsData base class
1685
1686 // --- This is the contents of the streamer code of RooTreeData version 1 ---
1687 UInt_t R__s1;
1688 UInt_t R__c1;
1689 Version_t R__v1 = R__b.ReadVersion(&R__s1, &R__c1);
1690 if (R__v1) {
1691 }
1692
1694 TTree *X_tree(nullptr);
1695 R__b >> X_tree;
1697 X_truth.Streamer(R__b);
1699 X_blindString.Streamer(R__b);
1700 R__b.CheckByteCount(R__s1, R__c1, TClass::GetClass("RooTreeData"));
1701 // --- End of RooTreeData-v1 streamer
1702
1703 // Construct RooTreeDataStore from X_tree and complete initialization of new-style RooAbsData
1704 _dstore = std::make_unique<RooTreeDataStore>(X_tree, _vars);
1705 _dstore->SetName(GetName());
1706 _dstore->SetTitle(GetTitle());
1707 _dstore->checkInit();
1708
1709 // This is the contents of the streamer code of RooDataSet version 1
1712 R__b >> _wgtVar;
1713 R__b.CheckByteCount(R__s, R__c, RooDataSet::IsA());
1714 }
1715 } else {
1716 R__b.WriteClassBuffer(RooDataSet::Class(), this);
1717 }
1718}
1719
1720
1721
1722////////////////////////////////////////////////////////////////////////////////
1723/// Convert vector-based storage to tree-based storage. This implementation overrides the base class
1724/// implementation because the latter doesn't transfer weights.
1726{
1728 _dstore = std::make_unique<RooTreeDataStore>(GetName(), GetTitle(), _vars, *_dstore, nullptr, _wgtVar ? _wgtVar->GetName() : nullptr);
1730 }
1731}
1732
1733
1734namespace {
1735
1736 // Compile-time test if we can still use TStrings for the constructors of
1737 // RooDataClasses, either for both name and title or for only one of them.
1738 TString tstr = "tstr";
1739 const char * cstr = "cstr";
1740 RooRealVar x{"x", "x", 1.0};
1741 RooArgSet vars{x};
1742 RooDataSet d1(tstr, tstr, vars);
1743 RooDataSet d2(tstr, cstr, vars);
1744 RooDataSet d3(cstr, tstr, vars);
1745
1746} // namespace
1747
1748
1749void RooDataSet::loadValuesFromSlices(RooCategory &indexCat, std::map<std::string, RooAbsData *> const &slices,
1750 const char *rangeName, RooFormulaVar const *cutVar, const char *cutSpec)
1751{
1752
1753 if (cutVar && cutSpec) {
1754 throw std::invalid_argument("Only one of cutVar or cutSpec should be not a nullptr!");
1755 }
1756
1757 auto &indexCatInData = *static_cast<RooCategory *>(_vars.find(indexCat.GetName()));
1758
1759 for (auto const &item : slices) {
1760 std::unique_ptr<RooDataSet> sliceDataSet;
1761 RooAbsData* sliceData = item.second;
1762
1763 // If we are importing a RooDataHist, first convert it to a RooDataSet
1764 if(sliceData->InheritsFrom(RooDataHist::Class())) {
1766 sliceData = sliceDataSet.get();
1767 }
1768
1769 // Define state labels in index category (both in provided indexCat and in internal copy in dataset)
1770 if (!indexCat.hasLabel(item.first)) {
1771 indexCat.defineType(item.first);
1772 coutI(InputArguments) << "RooDataSet::ctor(" << GetName() << ") defining state \"" << item.first
1773 << "\" in index category " << indexCat.GetName() << std::endl;
1774 }
1775 if (!indexCatInData.hasLabel(item.first)) {
1776 indexCatInData.defineType(item.first);
1777 }
1778 indexCatInData.setLabel(item.first.c_str());
1779 std::unique_ptr<RooFormulaVar> cutVarTmp;
1780 if (cutSpec) {
1781 cutVarTmp = std::make_unique<RooFormulaVar>(cutSpec, cutSpec, *sliceData->get(), /*checkVariables=*/false);
1782 cutVar = cutVarTmp.get();
1783 }
1784 _dstore->loadValues(sliceData->store(), cutVar, rangeName);
1785 }
1786}
#define e(i)
Definition RSha256.hxx:103
ROOT::RRangeCast< T, false, Range_t > static_range_cast(Range_t &&coll)
#define coutI(a)
#define ccoutE(a)
#define oocoutW(o, a)
#define oocxcoutD(o, a)
#define coutW(a)
#define oocoutE(o, a)
#define oocoutI(o, a)
#define coutE(a)
#define TRACE_DESTROY
Definition RooTrace.h:24
#define TRACE_CREATE
Definition RooTrace.h:23
int Int_t
Definition RtypesCore.h:45
float Size_t
Definition RtypesCore.h:89
short Version_t
Definition RtypesCore.h:65
static void indent(ostringstream &buf, int indent_level)
ROOT::Detail::TRangeCast< T, true > TRangeDynCast
TRangeDynCast is an adapter class that allows the typed iteration through a TCollection.
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize void data
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize void char Point_t Rectangle_t WindowAttributes_t Float_t Float_t Float_t Int_t Int_t UInt_t UInt_t Rectangle_t Int_t Int_t Window_t TString Int_t GCValues_t GetPrimarySelectionOwner GetDisplay GetScreen GetColormap GetNativeEvent const char const char dpyName wid window const char font_name cursor keysym reg const char only_if_exist regb h Point_t winding char text const char depth char const char Int_t count const char ColorStruct_t color const char filename
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize void char Point_t Rectangle_t WindowAttributes_t index
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize void char Point_t Rectangle_t WindowAttributes_t Float_t Float_t Float_t Int_t Int_t UInt_t UInt_t Rectangle_t Int_t Int_t Window_t TString Int_t GCValues_t GetPrimarySelectionOwner GetDisplay GetScreen GetColormap GetNativeEvent const char const char dpyName wid window const char font_name cursor keysym reg const char only_if_exist regb h Point_t winding char text const char depth char const char Int_t count const char ColorStruct_t color const char Pixmap_t Pixmap_t PictureAttributes_t attr const char char ret_data h unsigned char height h Atom_t Int_t ULong_t ULong_t unsigned char prop_list Atom_t Atom_t Atom_t Time_t UChar_t len
char name[80]
Definition TGX11.cxx:110
#define hi
#define snprintf
Definition civetweb.c:1540
The Kahan summation is a compensated summation algorithm, which significantly reduces numerical error...
Definition Util.h:122
const_iterator begin() const
const_iterator end() const
Common abstract base class for objects that represent a value and a "shape" in RooFit.
Definition RooAbsArg.h:77
void setAttribute(const Text_t *name, bool value=true)
Set (default) or clear a named boolean attribute of this object.
bool hasLabel(const std::string &label) const
Check if a state with name label exists.
virtual void removeAll()
Remove all arguments from our set, deleting them if we own them.
virtual bool remove(const RooAbsArg &var, bool silent=false, bool matchByNameOnly=false)
Remove the specified argument from our list.
bool allInRange(const char *rangeSpec) const
Return true if all contained object report to have their value inside the specified range.
void assignFast(const RooAbsCollection &other, bool setValDirty=true) const
Functional equivalent of assign() but assumes this and other collection have same layout.
virtual bool add(const RooAbsArg &var, bool silent=false)
Add the specified argument to list.
void assign(const RooAbsCollection &other) const
Sets the value, cache and constant attribute of any argument in our set that also appears in the othe...
virtual bool addOwned(RooAbsArg &var, bool silent=false)
Add an argument and transfer the ownership to the collection.
virtual RooAbsArg * addClone(const RooAbsArg &var, bool silent=false)
Add a clone of the specified argument to list.
RooAbsArg * find(const char *name) const
Find object with given name in list.
Abstract base class for a data collection.
virtual bool isWeighted() const =0
virtual double sumEntries() const
virtual double weightError(RooAbsData::ErrorType etype=RooAbsData::Poisson) const =0
virtual double weight() const =0
Abstract base class for binned and unbinned datasets.
Definition RooAbsData.h:57
virtual const RooArgSet * get() const
Definition RooAbsData.h:101
void printMultiline(std::ostream &os, Int_t contents, bool verbose=false, TString indent="") const override
Interface for detailed printing of object.
void SetName(const char *name) override
Set the name of the TNamed.
RooAbsDataStore * store()
Definition RooAbsData.h:77
void checkInit() const
static StorageType defaultStorageType
Definition RooAbsData.h:314
std::unique_ptr< RooAbsDataStore > _dstore
Data storage implementation.
Definition RooAbsData.h:353
virtual void fill()
RooArgSet _vars
Dimensions of this data set.
Definition RooAbsData.h:350
virtual Int_t numEntries() const
Return number of entries in dataset, i.e., count unweighted entries.
StorageType storageType
Definition RooAbsData.h:316
void Streamer(TBuffer &) override
Stream an object of class RooAbsData.
double getVal(const RooArgSet *normalisationSet=nullptr) const
Evaluate object.
Definition RooAbsReal.h:103
RooArgList is a container object that can hold multiple RooAbsArg objects.
Definition RooArgList.h:22
RooArgSet is a container object that can hold multiple RooAbsArg objects.
Definition RooArgSet.h:24
void Streamer(TBuffer &) override
Stream an object of class TObject.
Object to represent discrete states.
Definition RooCategory.h:28
bool setIndex(Int_t index, bool printError=true) override
Set value by specifying the index code of the desired state.
bool defineType(const std::string &label)
Define a state with given name.
bool setLabel(const char *label, bool printError=true) override
Set value by specifying the name of the desired state.
static TClass * Class()
Named container for two doubles, two integers two object points and three string pointers that can be...
Definition RooCmdArg.h:26
const char * getString(Int_t idx) const
Return string stored in slot idx.
Definition RooCmdArg.h:96
Configurable parser for RooCmdArg named arguments.
bool process(const RooCmdArg &arg)
Process given RooCmdArg.
double getDouble(const char *name, double defaultValue=0.0) const
Return double property registered with name 'name'.
bool defineDouble(const char *name, const char *argName, int doubleNum, double defValue=0.0)
Define double property name 'name' mapped to double in slot 'doubleNum' in RooCmdArg with name argNam...
bool ok(bool verbose) const
Return true of parsing was successful.
bool defineObject(const char *name, const char *argName, int setNum, const TObject *obj=nullptr, bool isArray=false)
Define TObject property name 'name' mapped to object in slot 'setNum' in RooCmdArg with name argName ...
const char * getString(const char *name, const char *defaultValue="", bool convEmptyToNull=false) const
Return string property registered with name 'name'.
bool defineString(const char *name, const char *argName, int stringNum, const char *defValue="", bool appendMode=false)
Define double property name 'name' mapped to double in slot 'stringNum' in RooCmdArg with name argNam...
bool defineInt(const char *name, const char *argName, int intNum, int defValue=0)
Define integer property name 'name' mapped to integer in slot 'intNum' in RooCmdArg with name argName...
int getInt(const char *name, int defaultValue=0) const
Return integer property registered with name 'name'.
TObject * getObject(const char *name, TObject *obj=nullptr) const
Return TObject property registered with name 'name'.
Container class to hold N-dimensional binned data.
Definition RooDataHist.h:40
static TClass * Class()
double weight(std::size_t i) const
Return weight of i-th bin.
double weightSquared(std::size_t i) const
Return squared weight sum of i-th bin.
const RooArgSet * get() const override
Get bin centre of current bin.
Definition RooDataHist.h:82
Container class to hold unbinned data.
Definition RooDataSet.h:34
RooFit::OwningPtr< RooAbsData > emptyClone(const char *newName=nullptr, const char *newTitle=nullptr, const RooArgSet *vars=nullptr, const char *wgtVarName=nullptr) const override
Return an empty clone of this dataset.
RooRealVar * _wgtVar
Pointer to weight variable (if set)
Definition RooDataSet.h:137
bool _doWeightErrorCheck
! When adding events with weights, check that weights can actually be stored.
Definition RooDataSet.h:145
static void cleanup()
RooArgSet _varsNoWgt
Vars without weight variable.
Definition RooDataSet.h:136
void loadValuesFromSlices(RooCategory &indexCat, std::map< std::string, RooAbsData * > const &slices, const char *rangeName, RooFormulaVar const *cutVar, const char *cutSpec)
RooFit::OwningPtr< RooDataHist > binnedClone(const char *newName=nullptr, const char *newTitle=nullptr) const
Return binned clone of this dataset.
void weightError(double &lo, double &hi, ErrorType etype=SumW2) const override
Return the asymmetric errors on the current weight.
const RooArgSet * get() const override
Return a RooArgSet with the coordinates of the current event.
virtual RooPlot * plotOnXY(RooPlot *frame, const RooCmdArg &arg1={}, const RooCmdArg &arg2={}, const RooCmdArg &arg3={}, const RooCmdArg &arg4={}, const RooCmdArg &arg5={}, const RooCmdArg &arg6={}, const RooCmdArg &arg7={}, const RooCmdArg &arg8={}) const
Special plot method for 'X-Y' datasets used in fitting.
void initialize(const char *wgtVarName)
Initialize the dataset.
void printArgs(std::ostream &os) const override
Print argument of dataset, i.e. the observable names.
void SetName(const char *name) override
Change the name of this dataset into the given name.
virtual void addFast(const RooArgSet &row, double weight=1.0, double weightError=0.0)
Add a data point, with its coordinates specified in the 'data' argset, to the data set.
bool merge(RooDataSet *data1, RooDataSet *data2=nullptr, RooDataSet *data3=nullptr, RooDataSet *data4=nullptr, RooDataSet *data5=nullptr, RooDataSet *data6=nullptr)
TClass * IsA() const override
Definition RooDataSet.h:149
virtual RooAbsArg * addColumn(RooAbsArg &var, bool adjustRange=true)
Add a column with the values of the given (function) argument to this dataset.
bool write(const char *filename) const
Write the contents of this dataset to an ASCII file with the specified name.
double sumEntries() const override
Return effective number of entries in dataset, i.e., sum all weights.
std::span< const double > getWeightBatch(std::size_t first, std::size_t len, bool sumW2) const override
virtual RooArgSet * addColumns(const RooArgList &varList)
Add a column with the values of the given list of (function) argument to this dataset.
~RooDataSet() override
Destructor.
bool isNonPoissonWeighted() const override
Returns true if histogram contains bins with entries with a non-integer weight.
void SetNameTitle(const char *name, const char *title) override
Change the title of this dataset into the given name.
void printValue(std::ostream &os) const override
Print value of the dataset, i.e. the sum of weights contained in the dataset.
void append(RooDataSet &data)
Add all data points of given data set to this data set.
RooDataSet()
Default constructor for persistence.
std::unique_ptr< std::vector< double > > _sumW2Buffer
! Buffer for sumW2 in case a batch of values is requested.
Definition RooDataSet.h:147
void Streamer(TBuffer &) override
Stream an object of class RooDataSet.
void add(const RooArgSet &row, double weight, double weightError)
Add one ore more rows of data.
unsigned short _errorMsgCount
! Counter to silence error messages when filling dataset.
Definition RooDataSet.h:144
static TClass * Class()
std::unique_ptr< RooAbsData > reduceEng(const RooArgSet &varSubset, const RooFormulaVar *cutVar, const char *cutRange=nullptr, std::size_t nStart=0, std::size_t nStop=std::numeric_limits< std::size_t >::max()) const override
Implementation of RooAbsData virtual method that drives the RooAbsData::reduce() methods.
void convertToTreeStore() override
Convert vector-based storage to tree-based storage.
Use or if you need to change the weight the universal constructor with the and WeightVar() arguments.")
void printMultiline(std::ostream &os, Int_t contents, bool verbose=false, TString indent="") const override
Print info about this dataset to the specified output stream.
double weightSquared() const override
Return squared event weight of the current event.
double weight() const override
Return event weight of current event.
static RooDataSet * read(const char *filename, const RooArgList &variables, const char *opts="", const char *commonPath="", const char *indexCatName=nullptr)
Read data from a text file and create a dataset from it.
bool isWeighted() const override
Return true if dataset contains weighted events.
Utility base class for RooFit objects that are to be attached to ROOT directories.
Definition RooDirItem.h:22
virtual void Streamer(TBuffer &)
void removeFromDir(TObject *obj)
Remove object from directory it was added to.
TDirectory * _dir
! Associated directory
Definition RooDirItem.h:33
void appendToDir(TObject *obj, bool forceMemoryResident=false)
Append object to directory.
A RooFormulaVar is a generic implementation of a real-valued object, which takes a RooArgList of serv...
Graphical representation of binned data based on the TGraphAsymmErrors class.
Definition RooHist.h:29
void addBinWithXYError(Axis_t binCenter, double n, double exlow, double exhigh, double eylow, double eyhigh, double scaleFactor=1.0)
Add a bin to this histogram with the specified bin contents and error.
Definition RooHist.cxx:497
Collection class for internal use, storing a collection of RooAbsArg pointers in a doubly linked list...
virtual void Add(TObject *arg)
Plot frame and a container for graphics objects within that frame.
Definition RooPlot.h:43
RooAbsRealLValue * getPlotVar() const
Definition RooPlot.h:137
void addPlotable(RooPlotable *plotable, Option_t *drawOptions="", bool invisible=false, bool refreshNorm=false)
Add the specified plotable object to our plot.
Definition RooPlot.cxx:475
Variable that can be changed from the outside.
Definition RooRealVar.h:37
void setVal(double value) override
Set value of variable to 'value'.
void setError(double value)
Definition RooRealVar.h:60
void removeAsymError()
Definition RooRealVar.h:65
void setAsymError(double lo, double hi)
Definition RooRealVar.h:66
void removeError()
Definition RooRealVar.h:61
The RooStringView is a wrapper around a C-style string that can also be constructed from a std::strin...
TTree-backed data storage.
virtual void SetFillColor(Color_t fcolor)
Set the fill area color.
Definition TAttFill.h:38
virtual void SetFillStyle(Style_t fstyle)
Set the fill area style.
Definition TAttFill.h:40
virtual void SetLineStyle(Style_t lstyle)
Set the line style.
Definition TAttLine.h:44
virtual void SetLineWidth(Width_t lwidth)
Set the line width.
Definition TAttLine.h:45
virtual void SetLineColor(Color_t lcolor)
Set the line color.
Definition TAttLine.h:42
virtual void SetMarkerColor(Color_t mcolor=1)
Set the marker color.
Definition TAttMarker.h:39
virtual void SetMarkerStyle(Style_t mstyle=1)
Set the marker style.
Definition TAttMarker.h:41
virtual void SetMarkerSize(Size_t msize=1)
Set the marker size.
Definition TAttMarker.h:46
Buffer base class used for serializing objects.
Definition TBuffer.h:43
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:3069
virtual TList * GetList() const
Definition TDirectory.h:222
static TFile * Open(const char *name, Option_t *option="", const char *ftitle="", Int_t compress=ROOT::RCompressionSetting::EDefaults::kUseCompiledDefault, Int_t netopt=0)
Create / open a file.
Definition TFile.cxx:4130
void SetName(const char *name="") override
Set graph name.
Definition TGraph.cxx:2386
virtual void SetTitle(const char *title="")
Set the title of the TNamed.
Definition TNamed.cxx:164
const char * GetName() const override
Returns name of object.
Definition TNamed.h:47
const char * GetTitle() const override
Returns title of object.
Definition TNamed.h:48
Mother of all ROOT objects.
Definition TObject.h:41
Basic string class.
Definition TString.h:139
A TTree represents a columnar dataset.
Definition TTree.h:79
TLine * line
RooCmdArg StoreError(const RooArgSet &aset)
RooCmdArg WeightVar(const char *name="weight", bool reinterpretAsWeight=false)
Double_t y[n]
Definition legend1.C:17
Double_t x[n]
Definition legend1.C:17
tbb::task_arena is an alias of tbb::interface7::task_arena, which doesn't allow to forward declare tb...
std::vector< std::string > Split(std::string_view str, std::string_view delims, bool skipEmpty=false)
Splits a string at each character in delims.
The namespace RooFit contains mostly switches that change the behaviour of functions of PDFs (or othe...
Definition CodegenImpl.h:64
T * OwningPtr
An alias for raw pointers for indicating that the return type of a RooFit function is an owning point...
Definition Config.h:35
OwningPtr< T > makeOwningPtr(std::unique_ptr< T > &&ptr)
Internal helper to turn a std::unique_ptr<T> into an OwningPtr.
Definition Config.h:40
bool checkIfRangesOverlap(RooArgSet const &observables, std::vector< std::string > const &rangeNames)
void initialize(typename Architecture_t::Matrix_t &A, EInitialization m)
Definition Functions.h:282
TLine l
Definition textangle.C:4