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
70See 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 "RooFormulaUtils.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 "RooFitImplHelpers.h"
102
103#include "ROOT/StringUtils.hxx"
104
105#include "Math/Util.h"
106#include "TTree.h"
107#include "TFile.h"
108#include "TBuffer.h"
109#include "strlcpy.h"
110
111#include <cstdio>
112#include <iostream>
113#include <memory>
114#include <fstream>
115
116
117using std::endl, std::string, std::map, std::list, std::ifstream, std::ofstream, std::ostream;
118
119
121
122////////////////////////////////////////////////////////////////////////////////
123/// Default constructor for persistence
124
128
129namespace {
130
131struct FinalizeVarsOutput {
132 RooArgSet finalVars;
133 std::unique_ptr<RooRealVar> weight;
134 std::string weightVarName;
135 RooArgSet errorSet;
136};
137
138FinalizeVarsOutput finalizeVars(RooArgSet const &vars,
139 RooAbsArg * indexCat,
140 const char* wgtVarName,
143 RooArgSet * errorSet)
144{
145 FinalizeVarsOutput out;
146 out.finalVars.add(vars);
147
148 // Gather all imported weighted datasets to infer the weight variable name
149 // and whether we need weight errors
150 std::vector<RooAbsData*> weightedImpDatasets;
151 if(impData && impData->isWeighted()) weightedImpDatasets.push_back(impData);
153 if(data->isWeighted()) {
154 weightedImpDatasets.push_back(data);
155 }
156 }
157
158 bool needsWeightErrors = false;
159
160 // Figure out if the weight needs to store errors
162 if(dynamic_cast<RooDataHist const*>(data)) {
163 needsWeightErrors = true;
164 }
165 }
166
167 if (indexCat) {
168 out.finalVars.add(*indexCat, true);
169 }
170
171 out.weightVarName = wgtVarName ? wgtVarName : "";
172
173 if(out.weightVarName.empty()) {
174 // Even if no weight variable is specified, we want to have one if we are
175 // importing weighted datasets
177 if(auto ds = dynamic_cast<RooDataSet const*>(data)) {
178 // If the imported data is a RooDataSet, we take over its weight variable name
179 out.weightVarName = ds->weightVar()->GetName();
180 break;
181 } else {
182 out.weightVarName = RooFit::WeightVar().getString(0); // to get the default weight variable name
183 // Don't break here! The next imported data might be a RooDataSet,
184 // and in that case we want to take over its weight name instead of
185 // using the default one.
186 }
187 }
188 }
189
190 // If the weight variable is required but is not in the set, create and add
191 // it on the fly
192 RooAbsArg * wgtVar = out.finalVars.find(out.weightVarName.c_str());
193 if (!out.weightVarName.empty() && !wgtVar) {
194 const char* name = out.weightVarName.c_str();
195 out.weight = std::make_unique<RooRealVar>(name, name, 1.0);
196 wgtVar = out.weight.get();
197 out.finalVars.add(*out.weight);
198 }
199
201 out.errorSet.add(*wgtVar);
202 }
203
204 // Combine the error set figured out by finalizeVars and the ones passed by the user
205 if(errorSet) out.errorSet.add(*errorSet, /*silent=*/true);
206
207 return out;
208}
209
210// generating an unbinned dataset from a binned one
211std::unique_ptr<RooDataSet> makeDataSetFromDataHist(RooDataHist const &hist)
212{
213 using namespace RooFit;
214
216 const char* wgtName = wgtVarCmdArg.getString(0);
217 // Instantiate weight variable here such that we can pass it to StoreError()
219
220 RooArgSet vars{*hist.get(), wgtVar};
221
222 // We have to explicitly store the errors that are implied by the sum of weights squared.
223 auto data = std::make_unique<RooDataSet>(hist.GetName(), hist.GetTitle(), vars, wgtVarCmdArg, StoreError(wgtVar));
224 for (int i = 0; i < hist.numEntries(); ++i) {
225 data->add(*hist.get(i), hist.weight(i), std::sqrt(hist.weightSquared(i)));
226 }
227
228 return data;
229}
230
231} // namespace
232
233////////////////////////////////////////////////////////////////////////////////
234/// Construct an unbinned dataset from a RooArgSet defining the dimensions of the data space. Optionally, data
235/// can be imported at the time of construction.
236///
237/// <table>
238/// <tr><th> %RooCmdArg <th> Effect
239/// <tr><td> Import(TTree&) <td> Import contents of given TTree. Only branches of the TTree that have names
240/// corresponding to those of the RooAbsArgs that define the RooDataSet are
241/// imported.
242/// <tr><td> ImportFromFile(const char* fileName, const char* treeName) <td> Import tree with given name from file with given name.
243/// <tr><td> Import(RooAbsData&)
244/// <td> Import contents of given RooDataSet or RooDataHist. Only observables that are common with the definition of this dataset will be imported
245/// <tr><td> Index(RooCategory&) <td> Prepare import of datasets into a N+1 dimensional RooDataSet
246/// where the extra discrete dimension labels the source of the imported histogram.
247/// <tr><td> Import(const char*, RooAbsData&)
248/// <td> Import a RooDataSet or RooDataHist to be associated with the given state name of the index category
249/// specified in Index(). If the given state name is not yet defined in the index
250/// category it will be added on the fly. The import command can be specified multiple times.
251/// <tr><td> Link(const char*, RooDataSet&) <td> Link contents of supplied RooDataSet to this dataset for given index category state name.
252/// In this mode, no data is copied and the linked dataset must be remain live for the duration
253/// of this dataset. Note that link is active for both reading and writing, so modifications
254/// to the aggregate dataset will also modify its components. Link() and Import() are mutually exclusive.
255/// <tr><td> OwnLinked() <td> Take ownership of all linked datasets
256/// <tr><td> Import(std::map<string,RooAbsData*>&) <td> As above, but allows specification of many imports in a single operation
257/// <tr><td> Link(std::map<string,RooDataSet*>&) <td> As above, but allows specification of many links in a single operation
258/// <tr><td> Cut(const char*) <br>
259/// Cut(RooFormulaVar&)
260/// <td> Apply the given cut specification when importing data
261/// <tr><td> CutRange(const char*) <td> Only accept events in the observable range with the given name
262/// <tr><td> WeightVar(const char*) <br>
263/// WeightVar(const RooAbsArg&)
264/// <td> Interpret the given variable as event weight rather than as observable
265/// <tr><td> StoreError(const RooArgSet&) <td> Store symmetric error along with value for given subset of observables
266/// <tr><td> StoreAsymError(const RooArgSet&) <td> Store asymmetric error along with value for given subset of observables
267/// <tr><td> `GlobalObservables(const RooArgSet&)` <td> Define the set of global observables to be stored in this RooDataSet.
268/// A snapshot of the passed RooArgSet is stored, meaning the values wont't change unexpectedly.
269/// </table>
270///
271
273 const RooCmdArg& arg4,const RooCmdArg& arg5,const RooCmdArg& arg6,const RooCmdArg& arg7,const RooCmdArg& arg8) :
274 RooAbsData(name,title,{})
275{
276
277 // Define configuration for this method
278 RooCmdConfig pc("RooDataSet::ctor(" + std::string(GetName()) + ")");
279 pc.defineInt("ownLinked","OwnLinked",0) ;
280 pc.defineObject("impTree","ImportTree",0) ;
281 pc.defineObject("impData","ImportData",0) ;
282 pc.defineObject("indexCat","IndexCat",0) ;
283 pc.defineObject("impSliceData","ImportDataSlice",0,nullptr,true) ; // array
284 pc.defineString("impSliceState","ImportDataSlice",0,"",true) ; // array
285 pc.defineObject("lnkSliceData","LinkDataSlice",0,nullptr,true) ; // array
286 pc.defineString("lnkSliceState","LinkDataSlice",0,"",true) ; // array
287 pc.defineString("cutSpec","CutSpec",0,"") ;
288 pc.defineObject("cutVar","CutVar",0) ;
289 pc.defineString("cutRange","CutRange",0,"") ;
290 pc.defineString("wgtVarName","WeightVarName",0,"") ;
291 pc.defineInt("newWeight1","WeightVarName",0,0) ;
292 pc.defineString("fname","ImportFromFile",0,"") ;
293 pc.defineString("tname","ImportFromFile",1,"") ;
294 pc.defineObject("wgtVar","WeightVar",0) ;
295 pc.defineInt("newWeight2","WeightVar",0,0) ;
296 pc.defineObject("dummy1","ImportDataSliceMany",0) ;
297 pc.defineObject("dummy2","LinkDataSliceMany",0) ;
298 pc.defineSet("errorSet","StoreError",0) ;
299 pc.defineSet("asymErrSet","StoreAsymError",0) ;
300 pc.defineSet("glObs","GlobalObservables",0,nullptr) ;
301 pc.defineMutex("ImportTree","ImportData","ImportDataSlice","LinkDataSlice","ImportFromFile") ;
302 pc.defineMutex("CutSpec","CutVar") ;
303 pc.defineMutex("WeightVarName","WeightVar") ;
304 pc.defineDependency("ImportDataSlice","IndexCat") ;
305 pc.defineDependency("LinkDataSlice","IndexCat") ;
306 pc.defineDependency("OwnLinked","LinkDataSlice") ;
307
308
310 l.Add((TObject*)&arg1) ; l.Add((TObject*)&arg2) ;
311 l.Add((TObject*)&arg3) ; l.Add((TObject*)&arg4) ;
312 l.Add((TObject*)&arg5) ; l.Add((TObject*)&arg6) ;
313 l.Add((TObject*)&arg7) ; l.Add((TObject*)&arg8) ;
314
315 // Process & check varargs
316 pc.process(l) ;
317 if (!pc.ok(true)) {
318 const std::string errMsg = "Error in RooDataSet constructor: command argument list could not be processed";
319 coutE(InputArguments) << errMsg << std::endl;
320 throw std::invalid_argument(errMsg);
321 }
322
323 if(pc.getSet("glObs")) setGlobalObservables(*pc.getSet("glObs"));
324
325 // Extract relevant objects
326 TTree* impTree = static_cast<TTree*>(pc.getObject("impTree")) ;
327 auto impData = static_cast<RooAbsData*>(pc.getObject("impData")) ;
328 RooFormulaVar* cutVar = static_cast<RooFormulaVar*>(pc.getObject("cutVar")) ;
329 const char* cutSpec = pc.getString("cutSpec","",true) ;
330 const char* cutRange = pc.getString("cutRange","",true) ;
331 const char* wgtVarName = pc.getString("wgtVarName","",true) ;
332 RooRealVar* wgtVar = static_cast<RooRealVar*>(pc.getObject("wgtVar")) ;
333 const char* impSliceNames = pc.getString("impSliceState","",true) ;
334 const RooLinkedList& impSliceData = pc.getObjectList("impSliceData") ;
335 const char* lnkSliceNames = pc.getString("lnkSliceState","",true) ;
336 const RooLinkedList& lnkSliceData = pc.getObjectList("lnkSliceData") ;
337 RooCategory* indexCat = static_cast<RooCategory*>(pc.getObject("indexCat")) ;
338 RooArgSet* asymErrorSet = pc.getSet("asymErrSet") ;
339 const char* fname = pc.getString("fname") ;
340 const char* tname = pc.getString("tname") ;
341 Int_t ownLinked = pc.getInt("ownLinked") ;
342 Int_t newWeight = pc.getInt("newWeight1") + pc.getInt("newWeight2") ;
343
344 // Lookup name of weight variable if it was specified by object reference
345 if(wgtVar) {
346 wgtVarName = wgtVar->GetName();
347 }
348
349 auto finalVarsInfo = finalizeVars(vars,indexCat,wgtVarName,impData,impSliceData, pc.getSet("errorSet"));
350 initializeVars(finalVarsInfo.finalVars);
351 if(!finalVarsInfo.weightVarName.empty()) {
352 wgtVarName = finalVarsInfo.weightVarName.c_str();
353 }
354
355 RooArgSet* errorSet = finalVarsInfo.errorSet.empty() ? nullptr : &finalVarsInfo.errorSet;
356
357 // Case 1 --- Link multiple dataset as slices
358 if (lnkSliceNames) {
359
360 // Make import mapping if index category is specified
362 if (indexCat) {
363 char tmp[64000];
364 strlcpy(tmp, lnkSliceNames, 64000);
365 char *token = strtok(tmp, ",");
366 auto hiter = lnkSliceData.begin();
367 while (token) {
368 hmap[token] = static_cast<RooAbsData *>(*hiter);
369 token = strtok(nullptr, ",");
370 ++hiter;
371 }
372 }
373
374 // Initialize RooDataSet with optional weight variable
375 initialize(nullptr) ;
376
378 RooCategory* icat = static_cast<RooCategory*> (indexCat ? _vars.find(indexCat->GetName()) : nullptr ) ;
379 if (!icat) {
380 throw std::string("RooDataSet::RooDataSet() ERROR in constructor, cannot find index category") ;
381 }
382 for (map<string,RooAbsData*>::iterator hiter = hmap.begin() ; hiter!=hmap.end() ; ++hiter) {
383 // Define state labels in index category (both in provided indexCat and in internal copy in dataset)
384 if (indexCat && !indexCat->hasLabel(hiter->first)) {
385 indexCat->defineType(hiter->first) ;
386 coutI(InputArguments) << "RooDataSet::ctor(" << GetName() << ") defining state \"" << hiter->first << "\" in index category " << indexCat->GetName() << std::endl ;
387 }
388 if (icat && !icat->hasLabel(hiter->first)) {
389 icat->defineType(hiter->first) ;
390 }
391 icat->setLabel(hiter->first.c_str()) ;
392 storeMap[icat->getCurrentLabel()]=hiter->second->store() ;
393
394 // Take ownership of slice if requested
395 if (ownLinked) {
396 addOwnedComponent(hiter->first.c_str(),*hiter->second) ;
397 }
398 }
399
400 // Create composite datastore
401 _dstore = std::make_unique<RooCompositeDataStore>(name,title,_vars,*icat,storeMap) ;
402
403 return;
404 }
405
406 // Create empty datastore
407 RooTreeDataStore* tstore = nullptr;
408 if (defaultStorageType==Tree) {
409 _dstore = std::make_unique<RooTreeDataStore>(name,title,_vars,wgtVarName) ;
410 tstore = static_cast<RooTreeDataStore*>(_dstore.get());
411 } else if (defaultStorageType==Vector) {
412 if (wgtVarName && newWeight) {
413 RooAbsArg* wgttmp = _vars.find(wgtVarName) ;
414 if (wgttmp) {
415 wgttmp->setAttribute("NewWeight") ;
416 }
417 }
418 _dstore = std::make_unique<RooVectorDataStore>(name,title,_vars,wgtVarName) ;
419 }
420
421
422 // Make import mapping if index category is specified
423 std::map<string,RooAbsData*> hmap ;
424 if (indexCat) {
425 auto hiter = impSliceData.begin() ;
426 for (const auto& token : ROOT::Split(impSliceNames, ",")) {
427
428 if (!indexCat->hasLabel(token)) {
429 std::stringstream errorMsgStream;
430 errorMsgStream << "RooDataSet::RooDataSet(\"" << GetName() << "\") "
431 << "you are providing import data for the category state \"" << token
432 << "\", but the index category \"" << indexCat->GetName() << "\" has no such state!";
433 const std::string errorMsg = errorMsgStream.str();
434 coutE(InputArguments) << errorMsg << std::endl;
435 throw std::invalid_argument(errorMsg);
436 }
437
438 hmap[token] = static_cast<RooDataSet*>(*hiter);
439 ++hiter;
440 }
441 }
442
443 // process StoreError requests
444 if (errorSet) {
445 std::unique_ptr<RooArgSet> intErrorSet{_vars.selectCommon(*errorSet)};
446 intErrorSet->setAttribAll("StoreError") ;
447 for(RooAbsArg* arg : *intErrorSet) {
448 arg->attachToStore(*_dstore) ;
449 }
450 }
451 if (asymErrorSet) {
452 std::unique_ptr<RooArgSet> intAsymErrorSet{_vars.selectCommon(*asymErrorSet)};
453 intAsymErrorSet->setAttribAll("StoreAsymError") ;
454 for(RooAbsArg* arg : *intAsymErrorSet) {
455 arg->attachToStore(*_dstore) ;
456 }
457 }
458
459 // Initialize RooDataSet with optional weight variable
461
462 // Import one or more datasets
463 std::unique_ptr<RooFormulaVar> cutVarTmp;
464
465 if (indexCat) {
466 // Case 2 --- Import multiple RooDataSets as slices
467 loadValuesFromSlices(*indexCat, hmap, cutRange, cutVar, cutSpec);
468 } else if (impData) {
469 // Case 3 --- Import RooDataSet
470 std::unique_ptr<RooDataSet> impDataSet;
471
472 // If we are importing a RooDataHist, first convert it to a RooDataSet
473 if(impData->InheritsFrom(RooDataHist::Class())) {
474 impDataSet = makeDataSetFromDataHist(static_cast<RooDataHist const &>(*impData));
475 impData = impDataSet.get();
476 }
477 if (cutSpec) {
478 cutVarTmp = std::make_unique<RooFormulaVar>(cutSpec, cutSpec, *impData->get(), /*checkVariables=*/false);
479 cutVar = cutVarTmp.get();
480 }
481 _dstore->loadValues(impData->store(), cutVar, cutRange);
482
483 } else if (impTree || (fname && strlen(fname))) {
484 // Case 4 --- Import TTree from memory / file
485 std::unique_ptr<TFile> file;
486
487 if (impTree == nullptr) {
488 file.reset(TFile::Open(fname));
489 if (!file) {
490 std::stringstream ss;
491 ss << "RooDataSet::ctor(" << GetName() << ") ERROR file '" << fname
492 << "' cannot be opened or does not exist";
493 const std::string errMsg = ss.str();
494 coutE(InputArguments) << errMsg << std::endl;
495 throw std::invalid_argument(errMsg);
496 }
497
498 file->GetObject(tname, impTree);
499 if (!impTree) {
500 std::stringstream ss;
501 ss << "RooDataSet::ctor(" << GetName() << ") ERROR file '" << fname
502 << "' does not contain a TTree named '" << tname << "'";
503 const std::string errMsg = ss.str();
504 coutE(InputArguments) << errMsg << std::endl;
505 throw std::invalid_argument(errMsg);
506 }
507 }
508
509 if (cutSpec) {
510 cutVarTmp = std::make_unique<RooFormulaVar>(cutSpec, cutSpec, _vars, /*checkVariables=*/false);
511 cutVar = cutVarTmp.get();
512 }
513
514 if (tstore) {
515 tstore->loadValues(impTree, cutVar, cutRange);
516 } else {
518 tmpstore.loadValues(impTree, cutVar, cutRange);
519 _dstore->append(tmpstore);
520 }
521 }
522}
523
524////////////////////////////////////////////////////////////////////////////////
525/// Copy constructor
526
529{
530 initialize(other._wgtVar ? other._wgtVar->GetName() : nullptr);
531}
532
533////////////////////////////////////////////////////////////////////////////////
534/// Return an empty clone of this dataset. If vars is not null, only the variables in vars
535/// are added to the definition of the empty clone
536
537RooFit::OwningPtr<RooAbsData> RooDataSet::emptyClone(const char* newName, const char* newTitle, const RooArgSet* vars, const char* wgtVarName) const
538{
539 bool useOldWeight = _wgtVar && (wgtVarName == nullptr || strcmp(wgtVarName, _wgtVar->GetName()) == 0);
540
541 if(newName == nullptr) newName = GetName();
542 if(newTitle == nullptr) newTitle = GetTitle();
544
546 if(vars == nullptr) {
547 vars2.add(_vars);
548 } else {
549 for(RooAbsArg *var : *vars) {
550 // We should take the variables from the original dataset if
551 // available, such that we can query the "StoreError" and
552 // "StoreAsymError" attributes.
553 auto varInData = _vars.find(*var);
554 vars2.add(varInData ? *varInData : *var);
555 }
556 // We also need to add the weight variable of the original dataset if
557 // it's not added yet, again to query the error attributes correctly.
558 if(useOldWeight && !vars2.find(wgtVarName)) vars2.add(*_wgtVar);
559 }
560
561 RooArgSet errorSet;
563
564 for(RooAbsArg *var : vars2) {
565 if(var->getAttribute("StoreError")) errorSet.add(*var);
566 if(var->getAttribute("StoreAsymError")) asymErrorSet.add(*var);
567 }
568
569 using namespace RooFit;
570 return RooFit::makeOwningPtr<RooAbsData>(std::make_unique<RooDataSet>(
571 newName, newTitle, vars2, WeightVar(wgtVarName), StoreError(errorSet), StoreAsymError(asymErrorSet)));
572}
573
574
575
576////////////////////////////////////////////////////////////////////////////////
577/// Initialize the dataset. If wgtVarName is not null, interpret the observable
578/// with that name as event weight
579
581{
584 _wgtVar = nullptr ;
585 if (wgtVarName) {
587 if (!wgt) {
588 coutE(DataHandling) << "RooDataSet::RooDataSet(" << GetName() << "): designated weight variable "
589 << wgtVarName << " not found in set of variables, no weighting will be assigned" << std::endl ;
590 throw std::invalid_argument("RooDataSet::initialize() weight variable could not be initialised.");
591 } else if (!dynamic_cast<RooRealVar*>(wgt)) {
592 coutE(DataHandling) << "RooDataSet::RooDataSet(" << GetName() << "): designated weight variable "
593 << wgtVarName << " is not of type RooRealVar, no weighting will be assigned" << std::endl ;
594 throw std::invalid_argument("RooDataSet::initialize() weight variable could not be initialised.");
595 } else {
597 _wgtVar = static_cast<RooRealVar*>(wgt) ;
598 }
599 }
600}
601
602
603
604////////////////////////////////////////////////////////////////////////////////
605/// Implementation of RooAbsData virtual method that drives the RooAbsData::reduce() methods
606
607std::unique_ptr<RooAbsData> RooDataSet::reduceEng(const RooArgSet &varSubset, const RooFormulaVar *cutVar,
608 const char *cutRange, std::size_t nStart, std::size_t nStop) const
609{
610 checkInit();
612 if (_wgtVar) {
613 tmp.add(*_wgtVar);
614 }
615
616 auto createEmptyClone = [&]() { return emptyClone(GetName(), GetTitle(), &tmp); };
617
618 std::unique_ptr<RooAbsData> out{createEmptyClone()};
619
620 if (!cutRange || strchr(cutRange, ',') == nullptr) {
621 auto &ds = static_cast<RooDataSet &>(*out);
622 ds._dstore = _dstore->reduce(ds.GetName(), ds.GetTitle(), ds._vars, cutVar, cutRange, nStart, nStop);
623 } else {
624 // Composite case: multiple ranges
625 auto tokens = ROOT::Split(cutRange, ",");
627 std::stringstream errMsg;
628 errMsg << "Error in RooAbsData::reduce! The ranges " << cutRange << " are overlapping!";
629 throw std::runtime_error(errMsg.str());
630 }
631 for (const auto &token : tokens) {
632 std::unique_ptr<RooAbsData> appendedData{createEmptyClone()};
633 auto &ds = static_cast<RooDataSet &>(*appendedData);
634 ds._dstore = _dstore->reduce(ds.GetName(), ds.GetTitle(), ds._vars, cutVar, token.c_str(), nStart, nStop);
635 static_cast<RooDataSet &>(*out).append(ds);
636 }
637 }
638 return out;
639}
640
641
642
643////////////////////////////////////////////////////////////////////////////////
644/// Destructor
645
650
651
652
653////////////////////////////////////////////////////////////////////////////////
654/// Return binned clone of this dataset
655
657{
658 std::string title;
659 std::string name;
660 if (newName) {
661 name = newName ;
662 } else {
663 name = std::string(GetName()) + "_binned" ;
664 }
665 if (newTitle) {
666 title = newTitle ;
667 } else {
668 title = std::string(GetTitle()) + "_binned" ;
669 }
670
671 return RooFit::makeOwningPtr(std::make_unique<RooDataHist>(name,title,*get(),*this));
672}
673
674
675
676////////////////////////////////////////////////////////////////////////////////
677/// Return event weight of current event
678
679double RooDataSet::weight() const
680{
681 return store()->weight() ;
682}
683
684
685
686////////////////////////////////////////////////////////////////////////////////
687/// Return squared event weight of the current event. If this RooDataSet has no
688/// weight errors set, this will be the same as `weight() * weight()`, like
689/// expected for an unbinned dataset. When weight errors are set, it is assumed
690/// that the RooDataSet represents a weighted binned dataset and
691/// weightSquared() is the corresponding sum of weight squares for the bin.
692
694{
695 const double w = store()->weight();
696 const double e = weightError();
697 return e > 0.0 ? e * e : w * w;
698}
699
700
701////////////////////////////////////////////////////////////////////////////////
702/// \see RooAbsData::getWeightBatch().
703std::span<const double> RooDataSet::getWeightBatch(std::size_t first, std::size_t len, bool sumW2 /*=false*/) const {
704
705 std::size_t nEntries = this->numEntries(); // for the casting to std::size_t
706
707 if(first + len > nEntries) {
708 throw std::runtime_error("RooDataSet::getWeightBatch(): requested range not valid for dataset.");
709 }
710
711 std::span<const double> allWeights = _dstore->getWeightBatch(0, numEntries());
712 if(allWeights.empty()) return {};
713
714 if(!sumW2) return {&*(std::cbegin(allWeights) + first), len};
715
716 // Treat the sumW2 case with a result buffer, first reset buffer if the
717 // number of entries doesn't match with the dataset anymore
718 if(_sumW2Buffer && _sumW2Buffer->size() != nEntries) _sumW2Buffer.reset();
719
720 if (!_sumW2Buffer) {
721 _sumW2Buffer = std::make_unique<std::vector<double>>();
722 _sumW2Buffer->reserve(nEntries);
723
724 for (std::size_t i = 0; i < nEntries; ++i) {
725 get(i);
726 _sumW2Buffer->push_back(weightSquared());
727 }
728 }
729
730 return std::span<const double>(&*(_sumW2Buffer->begin() + first), len);
731}
732
733
734////////////////////////////////////////////////////////////////////////////////
735/// \copydoc RooAbsData::weightError(double&,double&,RooAbsData::ErrorType) const
736/// \param etype error type
737void RooDataSet::weightError(double& lo, double& hi, ErrorType etype) const
738{
739 store()->weightError(lo,hi,etype) ;
740}
741
742
743////////////////////////////////////////////////////////////////////////////////
744/// \copydoc RooAbsData::weightError(RooAbsData::ErrorType)
745/// \param etype error type
747{
748 return store()->weightError(etype) ;
749}
750
751
752////////////////////////////////////////////////////////////////////////////////
753/// Return RooArgSet with coordinates of event 'index'
754
756{
758 return ret ? &_varsNoWgt : nullptr ;
759}
760
761
762////////////////////////////////////////////////////////////////////////////////
763
765{
766 return store()->sumEntries() ;
767}
768
769
770////////////////////////////////////////////////////////////////////////////////
771/// Return the sum of weights in all entries matching cutSpec (if specified)
772/// and in named range cutRange (if specified)
773
774double RooDataSet::sumEntries(const char* cutSpec, const char* cutRange) const
775{
776 // Setup a formula evaluator for cutSpec if it is present
777 std::unique_ptr<RooFormulaEvaluator> select = nullptr;
778 if (cutSpec && strlen(cutSpec) > 0) {
779 select = RooFormulaUtils::makeFormulaEvaluator("select", cutSpec, *get());
780 }
781
782 // Shortcut for unweighted unselected datasets
783 if (!select && !cutRange && !isWeighted()) {
784 return numEntries() ;
785 }
786
787 // Otherwise sum the weights in the event
789 for (int i = 0 ; i<numEntries() ; i++) {
790 get(i) ;
791 if (select && RooFormulaUtils::evalFormula(*select, _vars) == 0.)
792 continue;
793 if (cutRange && !_vars.allInRange(cutRange)) continue ;
794 sumw += weight();
795 }
796
797 return sumw.Sum() ;
798}
799
800
801
802
803////////////////////////////////////////////////////////////////////////////////
804/// Return true if dataset contains weighted events
805
807{
808 return store() ? store()->isWeighted() : false;
809}
810
811
812
813////////////////////////////////////////////////////////////////////////////////
814/// Returns true if histogram contains bins with entries with a non-integer weight
815
817{
818 // Return false if we have no weights
819 if (!_wgtVar) return false ;
820
821 // Now examine individual weights
822 for (int i=0 ; i<numEntries() ; i++) {
823 get(i) ;
824 if (std::abs(weight()-Int_t(weight()))>1e-10) return true ;
825 }
826 // If sum of weights is less than number of events there are negative (integer) weights
827 if (sumEntries()<numEntries()) return true ;
828
829 return false ;
830}
831
832
833
834
835////////////////////////////////////////////////////////////////////////////////
836/// Return a RooArgSet with the coordinates of the current event
837
839{
840 return &_varsNoWgt ;
841}
842
843
844
845////////////////////////////////////////////////////////////////////////////////
846/// Add a data point, with its coordinates specified in the 'data' argset, to the data set.
847/// Any variables present in 'data' but not in the dataset will be silently ignored.
848/// \param[in] data Data point.
849/// \param[in] wgt Event weight. Defaults to 1. The current value of the weight variable is
850/// ignored.
851/// \note To obtain weighted events, a variable must be designated `WeightVar` in the constructor.
852/// \param[in] wgtError Optional weight error.
853/// \note This requires including the weight variable in the set of `StoreError` variables when constructing
854/// the dataset.
855
856void RooDataSet::add(const RooArgSet& data, double wgt, double wgtError)
857{
858 checkInit() ;
859
860 const double oldW = _wgtVar ? _wgtVar->getVal() : 0.;
861
863
864 if (_wgtVar) {
865 _wgtVar->setVal(wgt) ;
866 if (wgtError!=0.) {
868 }
869 } else if ((wgt != 1. || wgtError != 0.) && _errorMsgCount < 5) {
870 ccoutE(DataHandling) << "An event weight/error was passed but no weight variable was defined"
871 << " in the dataset '" << GetName() << "'. The weight will be ignored." << std::endl;
873 }
874
876 && wgtError != 0.
877 && std::abs(wgt*wgt - wgtError)/wgtError > 1.E-15 //Exception for standard wgt^2 errors, which need not be stored.
878 && _errorMsgCount < 5 && !_wgtVar->getAttribute("StoreError")) {
879 coutE(DataHandling) << "An event weight error was passed to the RooDataSet '" << GetName()
880 << "', but the weight variable '" << _wgtVar->GetName()
881 << "' does not store errors. Check `StoreError` in the RooDataSet constructor." << std::endl;
883 }
884
885 fill();
886
887 // Restore weight state
888 if (_wgtVar) {
891 }
892}
893
894
895
896
897////////////////////////////////////////////////////////////////////////////////
898/// Add a data point, with its coordinates specified in the 'data' argset, to the data set.
899/// Any variables present in 'data' but not in the dataset will be silently ignored.
900/// \param[in] indata Data point.
901/// \param[in] inweight Event weight. The current value of the weight variable is ignored.
902/// \note To obtain weighted events, a variable must be designated `WeightVar` in the constructor.
903/// \param[in] weightErrorLo Asymmetric weight error.
904/// \param[in] weightErrorHi Asymmetric weight error.
905/// \note This requires including the weight variable in the set of `StoreAsymError` variables when constructing
906/// the dataset.
907
909{
910 checkInit() ;
911
912 const double oldW = _wgtVar ? _wgtVar->getVal() : 0.;
913
915 if (_wgtVar) {
918 } else if (inweight != 1. && _errorMsgCount < 5) {
919 ccoutE(DataHandling) << "An event weight was given but no weight variable was defined"
920 << " in the dataset '" << GetName() << "'. The weight will be ignored." << std::endl;
922 }
923
925 && _errorMsgCount < 5 && !_wgtVar->getAttribute("StoreAsymError")) {
926 coutE(DataHandling) << "An event weight error was passed to the RooDataSet '" << GetName()
927 << "', but the weight variable '" << _wgtVar->GetName()
928 << "' does not store errors. Check `StoreAsymError` in the RooDataSet constructor." << std::endl;
930 }
931
932 fill();
933
934 // Restore weight state
935 if (_wgtVar) {
938 }
939}
940
941
942
943
944
945////////////////////////////////////////////////////////////////////////////////
946/// Add a data point, with its coordinates specified in the 'data' argset, to the data set.
947/// \attention The order and type of the input variables are **assumed** to be the same as
948/// for the RooArgSet returned by RooDataSet::get(). Input values will just be written
949/// into the internal data columns by ordinal position.
950/// \param[in] data Data point.
951/// \param[in] wgt Event weight. Defaults to 1. The current value of the weight variable is
952/// ignored.
953/// \note To obtain weighted events, a variable must be designated `WeightVar` in the constructor.
954/// \param[in] wgtError Optional weight error.
955/// \note This requires including the weight variable in the set of `StoreError` variables when constructing
956/// the dataset.
957
958void RooDataSet::addFast(const RooArgSet& data, double wgt, double wgtError)
959{
960 checkInit() ;
961
962 const double oldW = _wgtVar ? _wgtVar->getVal() : 0.;
963
964 _varsNoWgt.assignFast(data,_dstore->dirtyProp());
965 if (_wgtVar) {
966 _wgtVar->setVal(wgt) ;
967 if (wgtError!=0.) {
969 }
970 } else if (wgt != 1. && _errorMsgCount < 5) {
971 ccoutE(DataHandling) << "An event weight was given but no weight variable was defined"
972 << " in the dataset '" << GetName() << "'. The weight will be ignored." << std::endl;
974 }
975
976 fill();
977
979 && wgtError != 0. && wgtError != wgt*wgt //Exception for standard weight error, which need not be stored
980 && _errorMsgCount < 5 && !_wgtVar->getAttribute("StoreError")) {
981 coutE(DataHandling) << "An event weight error was passed to the RooDataSet '" << GetName()
982 << "', but the weight variable '" << _wgtVar->GetName()
983 << "' does not store errors. Check `StoreError` in the RooDataSet constructor." << std::endl;
985 }
987 _doWeightErrorCheck = false;
988 }
989
990 if (_wgtVar) {
993 }
994}
995
996
997
998////////////////////////////////////////////////////////////////////////////////
999
1002{
1003 checkInit() ;
1005 if (data1) dsetList.push_back(data1) ;
1006 if (data2) dsetList.push_back(data2) ;
1007 if (data3) dsetList.push_back(data3) ;
1008 if (data4) dsetList.push_back(data4) ;
1009 if (data5) dsetList.push_back(data5) ;
1010 if (data6) dsetList.push_back(data6) ;
1011 return merge(dsetList) ;
1012}
1013
1014
1015
1016////////////////////////////////////////////////////////////////////////////////
1017/// Merge columns of supplied data set(s) with this data set. All
1018/// data sets must have equal number of entries. In case of
1019/// duplicate columns the column of the last dataset in the list
1020/// prevails
1021
1023{
1024
1025 checkInit() ;
1026 // Sanity checks: data sets must have the same size
1027 for (list<RooDataSet*>::iterator iter = dsetList.begin() ; iter != dsetList.end() ; ++iter) {
1028 if (numEntries()!=(*iter)->numEntries()) {
1029 coutE(InputArguments) << "RooDataSet::merge(" << GetName() << ") ERROR: datasets have different size" << std::endl ;
1030 return true ;
1031 }
1032 }
1033
1034 // Extend vars with elements of other dataset
1036 for (list<RooDataSet*>::iterator iter = dsetList.begin() ; iter != dsetList.end() ; ++iter) {
1037 _vars.addClone((*iter)->_vars,true) ;
1038 dstoreList.push_back((*iter)->store()) ;
1039 }
1040
1041 // Merge data stores
1043 mergedStore->SetName(_dstore->GetName()) ;
1044 mergedStore->SetTitle(_dstore->GetTitle()) ;
1045
1046 // Replace current data store with merged store
1047 _dstore.reset(mergedStore);
1048
1049 initialize(_wgtVar?_wgtVar->GetName():nullptr) ;
1050 return false ;
1051}
1052
1053
1054////////////////////////////////////////////////////////////////////////////////
1055/// Add all data points of given data set to this data set.
1056/// Observable in 'data' that are not in this dataset
1057/// with not be transferred
1058
1060{
1061 checkInit() ;
1062 _dstore->append(*data._dstore) ;
1063}
1064
1065
1066
1067////////////////////////////////////////////////////////////////////////////////
1068/// Add a column with the values of the given (function) argument
1069/// to this dataset. The function value is calculated for each
1070/// event using the observable values of each event in case the
1071/// function depends on variables with names that are identical
1072/// to the observable names in the dataset
1073
1075{
1076 checkInit() ;
1077 std::unique_ptr<RooAbsArg> ret{_dstore->addColumn(var,adjustRange)};
1078 RooAbsArg* retPtr = ret.get();
1079 _vars.addOwned(std::move(ret));
1080 initialize(_wgtVar?_wgtVar->GetName():nullptr) ;
1081 return retPtr;
1082}
1083
1084
1085////////////////////////////////////////////////////////////////////////////////
1086/// Special plot method for 'X-Y' datasets used in \f$ \chi^2 \f$ fitting.
1087/// For general plotting, see RooAbsData::plotOn().
1088///
1089/// These datasets
1090/// have one observable (X) and have weights (Y) and associated errors.
1091/// <table>
1092/// <tr><th> Contents options <th> Effect
1093/// <tr><td> YVar(RooRealVar& var) <td> Designate specified observable as 'y' variable
1094/// If not specified, the event weight will be the y variable
1095/// <tr><th> Histogram drawing options <th> Effect
1096/// <tr><td> DrawOption(const char* opt) <td> Select ROOT draw option for resulting TGraph object
1097/// <tr><td> LineStyle(Int_t style) <td> Select line style by ROOT line style code, default is solid
1098/// <tr><td> LineColor(Int_t color) <td> Select line color by ROOT color code, default is black
1099/// <tr><td> LineWidth(Int_t width) <td> Select line with in pixels, default is 3
1100/// <tr><td> MarkerStyle(Int_t style) <td> Select the ROOT marker style, default is 21
1101/// <tr><td> MarkerColor(Int_t color) <td> Select the ROOT marker color, default is black
1102/// <tr><td> MarkerSize(double size) <td> Select the ROOT marker size
1103/// <tr><td> Rescale(double factor) <td> Apply global rescaling factor to histogram
1104/// <tr><th> Misc. other options <th> Effect
1105/// <tr><td> Name(const chat* name) <td> Give curve specified name in frame. Useful if curve is to be referenced later
1106/// <tr><td> Invisible(bool flag) <td> Add curve to frame, but do not display. Useful in combination AddTo()
1107/// </table>
1108
1110 const RooCmdArg& arg3, const RooCmdArg& arg4,
1111 const RooCmdArg& arg5, const RooCmdArg& arg6,
1112 const RooCmdArg& arg7, const RooCmdArg& arg8) const
1113{
1114 checkInit() ;
1115
1116 RooLinkedList argList ;
1117 argList.Add((TObject*)&arg1) ; argList.Add((TObject*)&arg2) ;
1118 argList.Add((TObject*)&arg3) ; argList.Add((TObject*)&arg4) ;
1119 argList.Add((TObject*)&arg5) ; argList.Add((TObject*)&arg6) ;
1120 argList.Add((TObject*)&arg7) ; argList.Add((TObject*)&arg8) ;
1121
1122 // Process named arguments
1123 RooCmdConfig pc("RooDataSet::plotOnXY(" + std::string(GetName()) + ")");
1124 pc.defineString("drawOption","DrawOption",0,"P") ;
1125 pc.defineString("histName","Name",0,"") ;
1126 pc.defineInt("lineColor","LineColor",0,-999) ;
1127 pc.defineInt("lineStyle","LineStyle",0,-999) ;
1128 pc.defineInt("lineWidth","LineWidth",0,-999) ;
1129 pc.defineInt("markerColor","MarkerColor",0,-999) ;
1130 pc.defineInt("markerStyle","MarkerStyle",0,8) ;
1131 pc.defineDouble("markerSize","MarkerSize",0,-999) ;
1132 pc.defineInt("fillColor","FillColor",0,-999) ;
1133 pc.defineInt("fillStyle","FillStyle",0,-999) ;
1134 pc.defineInt("histInvisible","Invisible",0,0) ;
1135 pc.defineDouble("scaleFactor","Rescale",0,1.) ;
1136 pc.defineObject("xvar","XVar",0,nullptr) ;
1137 pc.defineObject("yvar","YVar",0,nullptr) ;
1138
1139
1140 // Process & check varargs
1141 pc.process(argList) ;
1142 if (!pc.ok(true)) {
1143 return frame ;
1144 }
1145
1146 // Extract values from named arguments
1147 const char* drawOptions = pc.getString("drawOption") ;
1148 Int_t histInvisible = pc.getInt("histInvisible") ;
1149 const char* histName = pc.getString("histName",nullptr,true) ;
1150 double scaleFactor = pc.getDouble("scaleFactor") ;
1151
1152 RooRealVar* xvar = static_cast<RooRealVar*>(_vars.find(frame->getPlotVar()->GetName())) ;
1153
1154 // Determine Y variable (default is weight, if present)
1155 RooRealVar* yvar = static_cast<RooRealVar*>(pc.getObject("yvar")) ;
1156
1157 // Sanity check. XY plotting only applies to weighted datasets if no YVar is specified
1158 if (!_wgtVar && !yvar) {
1159 coutE(InputArguments) << "RooDataSet::plotOnXY(" << GetName() << ") ERROR: no YVar() argument specified and dataset is not weighted" << std::endl ;
1160 return nullptr ;
1161 }
1162
1163 RooRealVar* dataY = yvar ? static_cast<RooRealVar*>(_vars.find(yvar->GetName())) : nullptr ;
1164 if (yvar && !dataY) {
1165 coutE(InputArguments) << "RooDataSet::plotOnXY(" << GetName() << ") ERROR on YVar() argument, dataset does not contain a variable named " << yvar->GetName() << std::endl ;
1166 return nullptr ;
1167 }
1168
1169
1170 // Make RooHist representing XY contents of data
1171 RooHist* graph = new RooHist ;
1172 if (histName) {
1173 graph->SetName(histName) ;
1174 } else {
1175 graph->SetName(("hxy_" + std::string(GetName())).c_str());
1176 }
1177
1178 for (int i=0 ; i<numEntries() ; i++) {
1179 get(i) ;
1180 double x = xvar->getVal() ;
1181 double exlo = xvar->getErrorLo() ;
1182 double exhi = xvar->getErrorHi() ;
1183 double y;
1184 double eylo;
1185 double eyhi;
1186 if (!dataY) {
1187 y = weight() ;
1189 } else {
1190 y = dataY->getVal() ;
1191 eylo = dataY->getErrorLo() ;
1192 eyhi = dataY->getErrorHi() ;
1193 }
1194 graph->addBinWithXYError(x,y,-1*exlo,exhi,-1*eylo,eyhi,scaleFactor) ;
1195 }
1196
1197 // Adjust style options according to named arguments
1198 Int_t lineColor = pc.getInt("lineColor") ;
1199 Int_t lineStyle = pc.getInt("lineStyle") ;
1200 Int_t lineWidth = pc.getInt("lineWidth") ;
1201 Int_t markerColor = pc.getInt("markerColor") ;
1202 Int_t markerStyle = pc.getInt("markerStyle") ;
1203 Size_t markerSize = pc.getDouble("markerSize") ;
1204 Int_t fillColor = pc.getInt("fillColor") ;
1205 Int_t fillStyle = pc.getInt("fillStyle") ;
1206
1207 if (lineColor!=-999) graph->SetLineColor(lineColor) ;
1208 if (lineStyle!=-999) graph->SetLineStyle(lineStyle) ;
1209 if (lineWidth!=-999) graph->SetLineWidth(lineWidth) ;
1210 if (markerColor!=-999) graph->SetMarkerColor(markerColor) ;
1211 if (markerStyle!=-999) graph->SetMarkerStyle(markerStyle) ;
1212 if (markerSize!=-999) graph->SetMarkerSize(markerSize) ;
1213 if (fillColor!=-999) graph->SetFillColor(fillColor) ;
1214 if (fillStyle!=-999) graph->SetFillStyle(fillStyle) ;
1215
1216 // Add graph to frame
1217 frame->addPlotable(graph,drawOptions,histInvisible) ;
1218
1219 return frame ;
1220}
1221
1222
1223
1224
1225////////////////////////////////////////////////////////////////////////////////
1226/// Read given list of ascii files, and construct a data set, using the given
1227/// ArgList as structure definition.
1228/// \param fileList Multiple file names, comma separated. Each
1229/// file is optionally prefixed with 'commonPath' if such a path is
1230/// provided
1231///
1232/// \param varList Specify the dimensions of the dataset to be built.
1233/// This list describes the order in which these dimensions appear in the
1234/// ascii files to be read.
1235/// Each line in the ascii file should contain N white-space separated
1236/// tokens, with N the number of args in `varList`. Any text beyond
1237/// N tokens will be ignored with a warning message.
1238/// (NB: This is the default output of RooArgList::writeToStream())
1239///
1240/// \param verbOpt `Q` be quiet, `D` debug mode (verbose)
1241///
1242/// \param commonPath All filenames in `fileList` will be prefixed with this optional path.
1243///
1244/// \param indexCatName Interpret the data as belonging to category `indexCatName`.
1245/// When multiple files are read, a RooCategory arg in `varList` can
1246/// optionally be designated to hold information about the source file
1247/// of each data point. This feature is enabled by giving the name
1248/// of the (already existing) category variable in `indexCatName`.
1249///
1250/// \attention If the value of any of the variables on a given line exceeds the
1251/// fit range associated with that dimension, the entire line will be
1252/// ignored. A warning message is printed in each case, unless the
1253/// `Q` verbose option is given. The number of events read and skipped
1254/// is always summarized at the end.
1255///
1256/// If no further information is given a label name 'fileNNN' will
1257/// be assigned to each event, where NNN is the sequential number of
1258/// the source file in `fileList`.
1259///
1260/// Alternatively, it is possible to override the default label names
1261/// of the index category by specifying them in the fileList string:
1262/// When instead of `file1.txt,file2.txt` the string
1263/// `file1.txt:FOO,file2.txt:BAR` is specified, a state named "FOO"
1264/// is assigned to the index category for each event originating from
1265/// file1.txt. The labels FOO,BAR may be predefined in the index
1266/// category via defineType(), but don't have to be.
1267///
1268/// Finally, one can also assign the same label to multiple files,
1269/// either by specifying `file1.txt:FOO,file2,txt:FOO,file3.txt:BAR`
1270/// or `file1.txt,file2.txt:FOO,file3.txt:BAR`.
1271///
1272
1274 const char *verbOpt, const char* commonPath,
1275 const char* indexCatName) {
1276 // Make working copy of variables list
1277 RooArgList variables(varList) ;
1278
1279 // Append blinding state category to variable list if not already there
1280 bool ownIsBlind(true) ;
1281 RooAbsArg* blindState = variables.find("blindState") ;
1282 if (!blindState) {
1283 blindState = new RooCategory("blindState","Blinding State") ;
1284 variables.add(*blindState) ;
1285 } else {
1286 ownIsBlind = false ;
1287 if (blindState->IsA()!=RooCategory::Class()) {
1288 oocoutE(nullptr,DataHandling) << "RooDataSet::read: ERROR: variable list already contains"
1289 << "a non-RooCategory blindState member" << std::endl ;
1290 return nullptr ;
1291 }
1292 oocoutW(nullptr,DataHandling) << "RooDataSet::read: WARNING: recycling existing "
1293 << "blindState category in variable list" << std::endl ;
1294 }
1295 RooCategory* blindCat = static_cast<RooCategory*>(blindState) ;
1296
1297 // Configure blinding state category
1298 blindCat->setAttribute("Dynamic") ;
1299 blindCat->defineType("Normal",0) ;
1300 blindCat->defineType("Blind",1) ;
1301
1302 // parse the option string
1304 opts.ToLower();
1305 bool verbose= !opts.Contains("q");
1306 bool debug= opts.Contains("d");
1307
1308 auto data = std::make_unique<RooDataSet>("dataset", fileList, variables);
1309 if (ownIsBlind) { variables.remove(*blindState) ; delete blindState ; }
1310 if(!data) {
1311 oocoutE(nullptr,DataHandling) << "RooDataSet::read: unable to create a new dataset"
1312 << std::endl;
1313 return nullptr;
1314 }
1315
1316 // Redirect blindCat to point to the copy stored in the data set
1317 blindCat = static_cast<RooCategory*>(data->_vars.find("blindState")) ;
1318
1319 // Find index category, if requested
1320 RooCategory *indexCat = nullptr;
1321 //RooCategory *indexCatOrig = 0;
1322 if (indexCatName) {
1323 RooAbsArg* tmp = nullptr;
1324 tmp = data->_vars.find(indexCatName) ;
1325 if (!tmp) {
1326 oocoutE(data.get(),DataHandling) << "RooDataSet::read: no index category named "
1327 << indexCatName << " in supplied variable list" << std::endl ;
1328 return nullptr;
1329 }
1330 if (tmp->IsA()!=RooCategory::Class()) {
1331 oocoutE(data.get(),DataHandling) << "RooDataSet::read: variable " << indexCatName
1332 << " is not a RooCategory" << std::endl ;
1333 return nullptr;
1334 }
1335 indexCat = static_cast<RooCategory*>(tmp);
1336
1337 // Prevent RooArgSet from attempting to read in indexCat
1338 indexCat->setAttribute("Dynamic") ;
1339 }
1340
1341
1342 Int_t outOfRange(0) ;
1343
1344 // Loop over all names in comma separated list
1345 Int_t fileSeqNum(0);
1346 for (const auto& filename : ROOT::Split(std::string(fileList), ", ")) {
1347 // Determine index category number, if this option is active
1348 if (indexCat) {
1349
1350 // Find and detach optional file category name
1351 const char *catname = strchr(filename.c_str(),':');
1352
1353 if (catname) {
1354 // Use user category name if provided
1355 catname++ ;
1356
1357 if (indexCat->hasLabel(catname)) {
1358 // Use existing category index
1359 indexCat->setLabel(catname);
1360 } else {
1361 // Register cat name
1362 indexCat->defineType(catname,fileSeqNum) ;
1363 indexCat->setIndex(fileSeqNum) ;
1364 }
1365 } else {
1366 // Assign autogenerated name
1367 char newLabel[128] ;
1368 snprintf(newLabel,128,"file%03d",fileSeqNum) ;
1369 if (indexCat->defineType(newLabel,fileSeqNum)) {
1370 oocoutE(data.get(), DataHandling) << "RooDataSet::read: Error, cannot register automatic type name " << newLabel
1371 << " in index category " << indexCat->GetName() << std::endl ;
1372 return nullptr ;
1373 }
1374 // Assign new category number
1375 indexCat->setIndex(fileSeqNum) ;
1376 }
1377 }
1378
1379 oocoutI(data.get(), DataHandling) << "RooDataSet::read: reading file " << filename << std::endl ;
1380
1381 // Prefix common path
1383 fullName.Append(filename) ;
1384 ifstream file(fullName) ;
1385
1386 if (!file.good()) {
1387 oocoutE(data.get(), DataHandling) << "RooDataSet::read: unable to open '"
1388 << filename << "'. Returning nullptr now." << std::endl;
1389 return nullptr;
1390 }
1391
1392 // double value;
1393 Int_t line(0) ;
1394 bool haveBlindString(false) ;
1395
1396 while(file.good() && !file.eof()) {
1397 line++;
1398 if(debug) oocxcoutD(data.get(),DataHandling) << "reading line " << line << std::endl;
1399
1400 // process comment lines
1401 if (file.peek() == '#') {
1402 if(debug) oocxcoutD(data.get(),DataHandling) << "skipping comment on line " << line << std::endl;
1403 } else {
1404 // Read single line
1405 bool readError = variables.readFromStream(file,true,verbose) ;
1406 data->_vars.assign(variables) ;
1407
1408 // Stop on read error
1409 if(!file.good()) {
1410 oocoutE(data.get(), DataHandling) << "RooDataSet::read(static): read error at line " << line << std::endl ;
1411 break;
1412 }
1413
1414 if (readError) {
1415 outOfRange++ ;
1416 } else {
1417 blindCat->setIndex(haveBlindString) ;
1418 data->fill(); // store this event
1419 }
1420 }
1421
1422 // Skip all white space (including empty lines).
1423 while (isspace(file.peek())) {
1424 char dummy;
1425 file >> std::noskipws >> dummy >> std::skipws;
1426 }
1427 }
1428
1429 file.close();
1430
1431 // get next file name
1432 fileSeqNum++ ;
1433 }
1434
1435 if (indexCat) {
1436 // Copy dynamically defined types from new data set to indexCat in original list
1437 assert(dynamic_cast<RooCategory*>(variables.find(indexCatName)));
1438 const auto origIndexCat = static_cast<RooCategory*>(variables.find(indexCatName));
1439 for (const auto& nameIdx : *indexCat) {
1440 origIndexCat->defineType(nameIdx.first, nameIdx.second);
1441 }
1442 }
1443 oocoutI(data.get(),DataHandling) << "RooDataSet::read: read " << data->numEntries()
1444 << " events (ignored " << outOfRange << " out of range events)" << std::endl;
1445
1446 return data.release();
1447}
1448
1449
1450
1451
1452////////////////////////////////////////////////////////////////////////////////
1453/// Write the contents of this dataset to an ASCII file with the specified name.
1454/// Each event will be written as a single line containing the written values
1455/// of each observable in the order they were declared in the dataset and
1456/// separated by whitespaces
1457
1458bool RooDataSet::write(const char* filename) const
1459{
1460 // Open file for writing
1461 ofstream ofs(filename) ;
1462 if (ofs.fail()) {
1463 coutE(DataHandling) << "RooDataSet::write(" << GetName() << ") cannot create file " << filename << std::endl ;
1464 return true ;
1465 }
1466
1467 // Write all lines as arglist in compact mode
1468 coutI(DataHandling) << "RooDataSet::write(" << GetName() << ") writing ASCII file " << filename << std::endl ;
1469 return write(ofs);
1470}
1471
1472////////////////////////////////////////////////////////////////////////////////
1473/// Write the contents of this dataset to the stream.
1474/// Each event will be written as a single line containing the written values
1475/// of each observable in the order they were declared in the dataset and
1476/// separated by whitespaces
1477
1478bool RooDataSet::write(ostream & ofs) const {
1479 checkInit();
1480
1481 for (Int_t i=0; i<numEntries(); ++i) {
1482 get(i)->writeToStream(ofs,true);
1483 }
1484
1485 if (ofs.fail()) {
1486 coutW(DataHandling) << "RooDataSet::write(" << GetName() << "): WARNING error(s) have occurred in writing" << std::endl ;
1487 }
1488
1489 return ofs.fail() ;
1490}
1491
1492
1493////////////////////////////////////////////////////////////////////////////////
1494/// Print info about this dataset to the specified output stream.
1495///
1496/// Standard: number of entries
1497/// Shape: list of variables we define & were generated with
1498
1499void RooDataSet::printMultiline(ostream& os, Int_t contents, bool verbose, TString indent) const
1500{
1501 checkInit() ;
1502 RooAbsData::printMultiline(os,contents,verbose,indent) ;
1503 if (_wgtVar) {
1504 os << indent << " Dataset variable \"" << _wgtVar->GetName() << "\" is interpreted as the event weight" << std::endl ;
1505 }
1506}
1507
1508
1509////////////////////////////////////////////////////////////////////////////////
1510/// Print value of the dataset, i.e. the sum of weights contained in the dataset
1511
1512void RooDataSet::printValue(ostream& os) const
1513{
1514 os << numEntries() << " entries" ;
1515 if (isWeighted()) {
1516 os << " (" << sumEntries() << " weighted)" ;
1517 }
1518}
1519
1520
1521
1522////////////////////////////////////////////////////////////////////////////////
1523/// Print argument of dataset, i.e. the observable names
1524
1525void RooDataSet::printArgs(ostream& os) const
1526{
1527 os << "[" ;
1528 bool first(true) ;
1529 for(RooAbsArg* arg : _varsNoWgt) {
1530 if (first) {
1531 first=false ;
1532 } else {
1533 os << "," ;
1534 }
1535 os << arg->GetName() ;
1536 }
1537 if (_wgtVar) {
1538 os << ",weight:" << _wgtVar->GetName() ;
1539 }
1540 os << "]" ;
1541}
1542
1543
1544
1545////////////////////////////////////////////////////////////////////////////////
1546/// Change the name of this dataset into the given name
1547
1548void RooDataSet::SetName(const char *name)
1549{
1550 if (_dir) _dir->GetList()->Remove(this);
1551 // We need to use the function from RooAbsData, because it already overrides TNamed::SetName
1553 if (_dir) _dir->GetList()->Add(this);
1554}
1555
1556
1557////////////////////////////////////////////////////////////////////////////////
1558/// Change the title of this dataset into the given name
1559
1560void RooDataSet::SetNameTitle(const char *name, const char* title)
1561{
1562 SetName(name);
1563 SetTitle(title);
1564}
1565
1566
1567////////////////////////////////////////////////////////////////////////////////
1568/// Stream an object of class RooDataSet.
1569
1571{
1572 if (R__b.IsReading()) {
1573
1574 UInt_t R__s;
1575 UInt_t R__c;
1576 Version_t R__v = R__b.ReadVersion(&R__s, &R__c);
1577
1578 if (R__v > 1) {
1579
1580 // Use new-style streaming for version >1
1581 R__b.ReadClassBuffer(RooDataSet::Class(), this, R__v, R__s, R__c);
1582
1583 } else {
1584
1585 // Legacy dataset conversion happens here. Legacy RooDataSet inherits from RooTreeData
1586 // which in turn inherits from RooAbsData. Manually stream RooTreeData contents on
1587 // file here and convert it into a RooTreeDataStore which is installed in the
1588 // new-style RooAbsData base class
1589
1590 // --- This is the contents of the streamer code of RooTreeData version 1 ---
1591 UInt_t R__s1;
1592 UInt_t R__c1;
1593 Version_t R__v1 = R__b.ReadVersion(&R__s1, &R__c1);
1594 if (R__v1) {
1595 }
1596
1598 TTree *X_tree(nullptr);
1599 R__b >> X_tree;
1601 X_truth.Streamer(R__b);
1603 X_blindString.Streamer(R__b);
1604 R__b.CheckByteCount(R__s1, R__c1, TClass::GetClass("RooTreeData"));
1605 // --- End of RooTreeData-v1 streamer
1606
1607 // Construct RooTreeDataStore from X_tree and complete initialization of new-style RooAbsData
1608 _dstore = std::make_unique<RooTreeDataStore>(X_tree, _vars);
1609 _dstore->SetName(GetName());
1610 _dstore->SetTitle(GetTitle());
1611 _dstore->checkInit();
1612
1613 // This is the contents of the streamer code of RooDataSet version 1
1616 R__b >> _wgtVar;
1617 R__b.CheckByteCount(R__s, R__c, RooDataSet::IsA());
1618 }
1619 } else {
1620 R__b.WriteClassBuffer(RooDataSet::Class(), this);
1621 }
1622}
1623
1624
1625
1626////////////////////////////////////////////////////////////////////////////////
1627/// Convert vector-based storage to tree-based storage. This implementation overrides the base class
1628/// implementation because the latter doesn't transfer weights.
1630{
1632 _dstore = std::make_unique<RooTreeDataStore>(GetName(), GetTitle(), _vars, *_dstore, nullptr, _wgtVar ? _wgtVar->GetName() : nullptr);
1634 }
1635}
1636
1637
1638namespace {
1639
1640 // Compile-time test if we can still use TStrings for the constructors of
1641 // RooDataClasses, either for both name and title or for only one of them.
1642 TString tstr = "tstr";
1643 const char * cstr = "cstr";
1644 RooRealVar x{"x", "x", 1.0};
1645 RooArgSet vars{x};
1646 RooDataSet d1(tstr, tstr, vars);
1647 RooDataSet d2(tstr, cstr, vars);
1648 RooDataSet d3(cstr, tstr, vars);
1649
1650} // namespace
1651
1652
1653void RooDataSet::loadValuesFromSlices(RooCategory &indexCat, std::map<std::string, RooAbsData *> const &slices,
1654 const char *rangeName, RooFormulaVar const *cutVar, const char *cutSpec)
1655{
1656
1657 if (cutVar && cutSpec) {
1658 throw std::invalid_argument("Only one of cutVar or cutSpec should be not a nullptr!");
1659 }
1660
1661 auto &indexCatInData = *static_cast<RooCategory *>(_vars.find(indexCat.GetName()));
1662
1663 for (auto const &item : slices) {
1664 std::unique_ptr<RooDataSet> sliceDataSet;
1665 RooAbsData* sliceData = item.second;
1666
1667 // If we are importing a RooDataHist, first convert it to a RooDataSet
1668 if(sliceData->InheritsFrom(RooDataHist::Class())) {
1670 sliceData = sliceDataSet.get();
1671 }
1672
1673 // Define state labels in index category (both in provided indexCat and in internal copy in dataset)
1674 if (!indexCat.hasLabel(item.first)) {
1675 indexCat.defineType(item.first);
1676 coutI(InputArguments) << "RooDataSet::ctor(" << GetName() << ") defining state \"" << item.first
1677 << "\" in index category " << indexCat.GetName() << std::endl;
1678 }
1679 if (!indexCatInData.hasLabel(item.first)) {
1680 indexCatInData.defineType(item.first);
1681 }
1682 indexCatInData.setLabel(item.first.c_str());
1683 std::unique_ptr<RooFormulaVar> cutVarTmp;
1684 if (cutSpec) {
1685 cutVarTmp = std::make_unique<RooFormulaVar>(cutSpec, cutSpec, *sliceData->get(), /*checkVariables=*/false);
1686 cutVar = cutVarTmp.get();
1687 }
1688 _dstore->loadValues(sliceData->store(), cutVar, rangeName);
1689 }
1690}
1691
1692/**
1693 * \brief Prints the contents of the RooDataSet to the specified output stream.
1694 *
1695 * This function iterates through all events (rows) of the dataset and prints
1696 * the value of each observable, along with the event's weight.
1697 * It is designed to be robust, handling empty or invalid datasets gracefully,
1698 * and works for datasets of any dimension.
1699 *
1700 * \param os The output stream (e.g., std::cout) to write the contents to.
1701 */
1702void RooDataSet::printContents(std::ostream& os) const
1703{
1704 os << "Contents of RooDataSet \"" << GetName() << "\"" << std::endl;
1705
1706 if (numEntries() == 0) {
1707 os << "(dataset is empty)" << std::endl;
1708 return;
1709 }
1710
1711 if (get() == nullptr || get()->empty()) {
1712 os << "(dataset has no observables)" << std::endl;
1713 return;
1714 }
1715
1716 for (int i = 0; i < numEntries(); ++i) {
1717 const RooArgSet* row = get(i); // reuses internal buffers
1718 os << " Entry " << i << ": ";
1719
1720 bool first = true;
1721 for (const auto* var : *row) {
1722 if (!first) os << ", ";
1723 first = false;
1724
1725 os << var->GetName() << "=";
1726 if (auto realVar = dynamic_cast<const RooRealVar*>(var)) {
1727 os << realVar->getVal();
1728 } else if (auto catVar = dynamic_cast<const RooCategory*>(var)) {
1729 os << catVar->getLabel();
1730 } else {
1731 os << "(unsupported type)"; //added as a precaution
1732 }
1733 }
1734
1735 os << ", weight=" << weight();
1736
1737 double lo, hi;
1738 weightError(lo, hi);
1739 if (lo != 0.0 || hi != 0.0) {
1740 os << " ±[" << lo << "," << hi << "]";
1741 }
1742
1743 os << std::endl;
1744 }
1745}
#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)
int Int_t
Signed integer 4 bytes (int)
Definition RtypesCore.h:60
float Size_t
Attribute size (float)
Definition RtypesCore.h:104
short Version_t
Class version identifier (short)
Definition RtypesCore.h:80
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:142
#define hi
The Kahan summation is a compensated summation algorithm, which significantly reduces numerical error...
Definition Util.h:141
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:76
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:55
virtual const RooArgSet * get() const
Definition RooAbsData.h:99
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:75
void checkInit() const
std::unique_ptr< RooAbsDataStore > _dstore
Data storage implementation.
Definition RooAbsData.h:347
virtual void fill()
RooArgSet _vars
Dimensions of this data set.
Definition RooAbsData.h:344
virtual Int_t numEntries() const
Return number of entries in dataset, i.e., count unweighted entries.
StorageType storageType
Definition RooAbsData.h:298
void Streamer(TBuffer &) override
Stream an object of class RooAbsData.
double getVal(const RooArgSet *normalisationSet=nullptr) const
Evaluate object.
Definition RooAbsReal.h:107
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:32
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:126
bool _doWeightErrorCheck
! When adding events with weights, check that weights can actually be stored.
Definition RooDataSet.h:134
static void cleanup()
RooArgSet _varsNoWgt
Vars without weight variable.
Definition RooDataSet.h:125
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.
void printContents(std::ostream &os=std::cout) const override
Print the contents of the dataset to the specified output stream.
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:138
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
~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:136
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:133
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.
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
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:506
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:476
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:61
void removeAsymError()
Definition RooRealVar.h:66
void setAsymError(double lo, double hi)
Definition RooRealVar.h:67
void removeError()
Definition RooRealVar.h:62
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:40
virtual void SetFillStyle(Style_t fstyle)
Set the fill area style.
Definition TAttFill.h:42
virtual void SetLineStyle(Style_t lstyle)
Set the line style.
Definition TAttLine.h:46
virtual void SetLineWidth(Width_t lwidth)
Set the line width.
Definition TAttLine.h:47
virtual void SetLineColor(Color_t lcolor)
Set the line color.
Definition TAttLine.h:44
virtual void SetMarkerStyle(Style_t mstyle=1)
Set the marker style.
virtual void SetMarkerSize(Size_t msize=1)
Set the marker size.
virtual void SetMarkerColor(Color_t mcolor=1)
Set the marker color.
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:2999
virtual TList * GetList() const
Definition TDirectory.h:223
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:3801
void SetName(const char *name="") override
Set graph name.
Definition TGraph.cxx:2425
virtual void SetTitle(const char *title="")
Set the title of the TNamed.
Definition TNamed.cxx:173
const char * GetName() const override
Returns name of object.
Definition TNamed.h:49
const char * GetTitle() const override
Returns title of object.
Definition TNamed.h:50
Mother of all ROOT objects.
Definition TObject.h:42
Basic string class.
Definition TString.h:137
A TTree represents a columnar dataset.
Definition TTree.h:89
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
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:73
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