Logo ROOT  
Reference Guide
 
Loading...
Searching...
No Matches
RooCustomizer.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 * \class RooCustomizer
19 *
20 * RooCustomizer is a factory class to produce clones
21 * of a prototype composite PDF object with the same structure but
22 * different leaf servers (parameters or dependents).
23 *
24 * RooCustomizer supports two kinds of modifications:
25 *
26 * - replaceArg(leaf_arg, repl_arg):
27 * Replaces each occurence of leaf_arg with repl_arg in the composite pdf.
28 *
29 * - splitArg(split_arg):
30 * Build multiple clones of the same prototype. Each
31 * occurrence of split_arg is replaced with a clone of split_arg
32 * named split_arg_[MCstate], where [MCstate] is the name of the
33 * 'master category state' that indexes the clones to be built.
34 *
35 *
36 * ### Example: Change the decay constant of an exponential for each run
37 *
38 * Splitting is particularly useful when building simultaneous fits to
39 * subsets of the data sample with different background properties.
40 * In such a case, the user builds a single prototype PDF representing
41 * the structure of the signal and background and splits the dataset
42 * into categories with different background properties. Using
43 * RooCustomizer a PDF for each subfit can be constructed from the
44 * prototype that has same structure and signal parameters, but
45 * different instances of the background parameters: e.g.
46 * ```
47 * ...
48 * RooExponential bg("bg","background",x,alpha) ;
49 * RooGaussian sig("sig","signal",x,mean,sigma) ;
50 * RooAddPdf pdf("pdf","pdf",sig,bg,sigfrac) ;
51 *
52 * RooDataSet data("data","dataset",RooArgSet(x,runblock),...)
53 *
54 * RooCategory runblock("runblock","run block") ;
55 * runblock.defineType("run1") ;
56 * runblock.defineType("run2") ;
57 *
58 * RooArgSet splitLeafs;
59 * RooCustomizer cust(pdf,runblock,splitLeafs);
60 * cust.splitArg(alpha,runblock);
61 *
62 * RooAbsPdf* pdf_run1 = cust.build("run1") ;
63 * RooAbsPdf* pdf_run2 = cust.build("run2") ;
64 *
65 * RooSimultaneous simpdf("simpdf","simpdf",RooArgSet(*pdf_run1,*pdf_run2))
66 * ```
67 * If the master category state is a super category, leafs may be split
68 * by any subset of that master category. E.g. if the master category
69 * is 'A x B', leafs may be split by A, B or AxB.
70 *
71 * In addition to replacing leaf nodes, RooCustomizer clones all branch
72 * nodes that depend directly or indirectly on modified leaf nodes, so
73 * that the input pdf is untouched by each build operation.
74 *
75 * The customizer owns all the branch nodes including the returned top
76 * level node, so the customizer should live as longs as the cloned
77 * composites are needed.
78 *
79 * Any leaf nodes that are created by the customizer will be put into
80 * the leaf list that is passed into the customizers constructor (splitLeafs in
81 * the above example. The list owner is responsible for deleting these leaf
82 * nodes after the customizer is deleted.
83 *
84 *
85 * ## Advanced techniques
86 *
87 * ### Reuse nodes to customise a different PDF
88 * By default, the customizer clones the prototype leaf node when splitting a leaf,
89 * but the user can feed pre-defined split leafs in leaf list. These leafs
90 * must have the name `<split_leaf>_<splitcat_label>` to be picked up. The list
91 * of pre-supplied leafs may be partial, any missing split leafs will be auto
92 * generated.
93 *
94 * Another common construction is to have two prototype PDFs, each to be customized
95 * by a separate customizer instance, that share parameters. To ensure that
96 * the customized clones also share their respective split leafs, i.e.
97 * ```
98 * PDF1(x,y, A) and PDF2(z, A) ---> PDF1_run1(x,y, A_run1) and PDF2_run1(x,y, A_run1)
99 * PDF1_run2(x,y, A_run2) and PDF2_run2(x,y, A_run2)
100 * ```
101 * feed the same split leaf list into both customizers. In that case, the second customizer
102 * will pick up the split leafs instantiated by the first customizer and the link between
103 * the two PDFs is retained.
104 *
105 * ### Customising with pre-defined leafs
106 * If leaf nodes are provided in the sets, the customiser will use them. This is a complete
107 * example that customises the `yield` parameter, and splits (automatically clones) the
108 * mean of the Gaussian. This is a short version of the tutorial rf514_RooCustomizer.C.
109 * ```
110 * RooRealVar E("Energy","Energy",0,3000);
111 *
112 * RooRealVar meanG("meanG","meanG", peak[1]);
113 * RooRealVar fwhm("fwhm", "fwhm", 5/(2*Sqrt(2*Log(2))));
114 * RooGaussian gauss("gauss", "gauss", E, meanG, fwhm);
115 *
116 * RooPolynomial linear("linear","linear",E,RooArgList());
117 *
118 * RooRealVar yieldSig("yieldSig", "yieldSig", 1, 0, 1.E4);
119 * RooRealVar yieldBkg("yieldBkg", "yieldBkg", 1, 0, 1.E4);
120 *
121 * RooAddPdf model("model","model",
122 * RooArgList(gauss,linear),
123 * RooArgList(yieldSig, yieldBkg));
124 *
125 * RooCategory sample("sample","sample");
126 * sample.defineType("BBG1m2T");
127 * sample.defineType("BBG2m2T");
128 *
129 *
130 * RooArgSet customisedLeafs;
131 * RooArgSet allLeafs;
132 *
133 * RooRealVar mass("M", "M", 1, 0, 12000);
134 * RooFormulaVar yield1("yieldSig_BBG1m2T","sigy1","M/3.360779",mass);
135 * RooFormulaVar yield2("yieldSig_BBG2m2T","sigy2","M/2",mass);
136 * allLeafs.add(yield1);
137 * allLeafs.add(yield2);
138 *
139 *
140 * RooCustomizer cust(model, sample, customisedLeafs, &allLeafs);
141 * cust.splitArg(yieldSig, sample);
142 * cust.splitArg(meanG, sample);
143 *
144 * auto pdf1 = cust.build("BBG1m2T");
145 * auto pdf2 = cust.build("BBG2m2T");
146 * ```
147*/
148
149
150#include "RooCustomizer.h"
151
152#include "RooFactoryWSTool.h"
153#include "RooAbsCategoryLValue.h"
154#include "RooAbsCategory.h"
155#include "RooAbsArg.h"
156#include "RooAbsPdf.h"
157#include "RooArgSet.h"
158#include "RooArgList.h"
159#include "RooMsgService.h"
160#include "RooHelpers.h"
161
162#include <iostream>
163#include "strtok.h"
164#include "strlcpy.h"
165
166#include "RooWorkspace.h"
167#include "RooGlobalFunc.h"
168#include "RooConstVar.h"
169#include "RooRealConstant.h"
170
171
172#ifndef _WIN32
173#include <strings.h>
174#endif
175
176
177using namespace std;
178
179
180namespace {
181
182/// Factory interface
183class CustIFace : public RooFactoryWSTool::IFace {
184public:
185 ~CustIFace() override {} ;
186 std::string create(RooFactoryWSTool& ft, const char* typeName, const char* instanceName, std::vector<std::string> args) override ;
187} ;
188
189
190static Int_t init();
191
192Int_t dummy = init() ;
193
194static Int_t init()
195{
196 RooFactoryWSTool::IFace* iface = new CustIFace ;
198 (void) dummy;
199 return 0 ;
200}
201
202}
203
204////////////////////////////////////////////////////////////////////////////////
205/// Constructor with a prototype and masterCat index category.
206/// Customizers created by this constructor offer both the
207/// replaceArg() and splitArg() functionality.
208/// \param[in] pdf Proto PDF to be customised.
209/// \param[in] masterCat Category to be used for splitting.
210/// \param[in,out] splitLeafs All nodes created in
211/// the customisation process are added to this set.
212/// The user can provide nodes that are *taken*
213/// from the set if they have a name that matches `<parameterNameToBeReplaced>_<category>`.
214/// \note The set needs to own its contents if they are user-provided.
215/// Use *e.g.*
216/// ```
217/// RooArgSet customisedLeafs;
218/// auto yield1 = new RooFormulaVar("yieldSig_BBG1m2T","sigy1","M/3.360779",mass);
219/// customisedLeafs.addOwned(*yield1);
220/// ```
221/// \param[in,out] splitLeafsAll All leafs that are used when customising are collected here.
222/// If this set already contains leaves, they will be used for customising if the names match
223/// as above.
224///
225
227 RooArgSet& splitLeafs, RooArgSet* splitLeafsAll) :
228 _sterile(false),
229 _owning(true),
230 _masterPdf((RooAbsArg*)&pdf),
231 _masterCat((RooAbsCategoryLValue*)&masterCat),
232 _masterBranchList("masterBranchList"),
233 _masterLeafList("masterLeafList"),
234 _internalCloneBranchList("cloneBranchList"),
235 _cloneNodeListAll(splitLeafsAll),
236 _cloneNodeListOwned(&splitLeafs)
237{
239
240 initialize() ;
241}
242
243
244
245////////////////////////////////////////////////////////////////////////////////
246/// Sterile Constructor. Customizers created by this constructor
247/// offer only the replace() method. The supplied 'name' is used as
248/// suffix for any cloned branch nodes
249
251 _sterile(true),
252 _owning(false),
253 _name(name),
254 _masterPdf((RooAbsArg*)&pdf),
255 _masterCat(0),
256 _masterBranchList("masterBranchList"),
257 _masterLeafList("masterLeafList"),
258 _internalCloneBranchList("cloneBranchList"),
259 _cloneNodeListAll(0),
260 _cloneNodeListOwned(0)
261{
263
264 initialize() ;
265}
266
267
268
269
270////////////////////////////////////////////////////////////////////////////////
271/// Initialize the customizer
272
274{
277}
278
279
280
281////////////////////////////////////////////////////////////////////////////////
282/// Destructor
283
285{
286
287}
288
289
290
291
292////////////////////////////////////////////////////////////////////////////////
293/// Split all arguments in 'set' into individualized clones for each
294/// defined state of 'splitCat'. The 'splitCats' category must be
295/// subset of or equal to the master category supplied in the
296/// customizer constructor.
297///
298/// Splitting is only available on customizers created with a master index category
299
300void RooCustomizer::splitArgs(const RooArgSet& set, const RooAbsCategory& splitCat)
301{
302 if (_sterile) {
303 oocoutE(nullptr, InputArguments) << "RooCustomizer::splitArgs(" << _name
304 << ") ERROR cannot set spitting rules on this sterile customizer" << endl ;
305 return ;
306 }
307
308 for (auto arg : set) {
309 splitArg(*arg,splitCat) ;
310 }
311}
312
313
314
315////////////////////////////////////////////////////////////////////////////////
316/// Split all argument 'arg' into individualized clones for each
317/// defined state of 'splitCat'. The 'splitCats' category must be
318/// subset of or equal to the master category supplied in the
319/// customizer constructor.
320///
321/// Splitting is only available on customizers created with a master index category
322
323void RooCustomizer::splitArg(const RooAbsArg& arg, const RooAbsCategory& splitCat)
324{
325 if (_splitArgList.FindObject(arg.GetName())) {
326 oocoutE(nullptr, InputArguments) << "RooCustomizer(" << _masterPdf->GetName() << ") ERROR: multiple splitting rules defined for "
327 << arg.GetName() << " only using first rule" << endl ;
328 return ;
329 }
330
331 if (_sterile) {
332 oocoutE(nullptr, InputArguments) << "RooCustomizer::splitArg(" << _name
333 << ") ERROR cannot set spitting rules on this sterile customizer" << endl ;
334 return ;
335 }
336
337 _splitArgList.Add((RooAbsArg*)&arg) ;
338 _splitCatList.Add((RooAbsCategory*)&splitCat) ;
339}
340
341
342
343////////////////////////////////////////////////////////////////////////////////
344/// Replace any occurence of arg 'orig' with arg 'subst'
345
346void RooCustomizer::replaceArg(const RooAbsArg& orig, const RooAbsArg& subst)
347{
348 if (_replaceArgList.FindObject(orig.GetName())) {
349 oocoutE(nullptr, InputArguments) << "RooCustomizer(" << _masterPdf->GetName() << ") ERROR: multiple replacement rules defined for "
350 << orig.GetName() << " only using first rule" << endl ;
351 return ;
352 }
353
354 _replaceArgList.Add((RooAbsArg*)&orig) ;
355 _replaceSubList.Add((RooAbsArg*)&subst) ;
356}
357
358
359
360////////////////////////////////////////////////////////////////////////////////
361/// Build a clone of the prototype executing all registered 'replace' rules.
362/// If verbose is set, a message is printed for each leaf or branch node
363/// modification. The returned head node owns all cloned branch nodes
364/// that were created in the cloning process.
365
367{
368 // Execute build
369 RooAbsArg* ret = doBuild(_name.Length()>0?_name.Data():0,verbose) ;
370
371 // Make root object own all cloned nodes
372
373 // First make list of all objects that were created
374 RooArgSet allOwned ;
376 allOwned.add(*_cloneNodeListOwned) ;
377 }
378 allOwned.add(*_cloneBranchList) ;
379
380 // Remove head node from list
381 allOwned.remove(*ret) ;
382
383 // If list with owned objects is not empty, assign
384 // head node as owner
385 if (allOwned.getSize()>0) {
386 ret->addOwnedComponents(allOwned) ;
387 }
388
389 return ret ;
390}
391
392
393
394////////////////////////////////////////////////////////////////////////////////
395/// Build a clone of the prototype executing all registered 'replace'
396/// rules and 'split' rules for the masterCat state named
397/// 'masterCatState'. If verbose is set a message is printed for
398/// each leaf or branch node modification. The returned composite arg
399/// is owned by the customizer. This function cannot be called on
400/// customizer build with the sterile constructor.
401
402RooAbsArg* RooCustomizer::build(const char* masterCatState, bool verbose)
403{
404 if (_sterile) {
405 oocoutE(nullptr, InputArguments) << "RooCustomizer::build(" << _name
406 << ") ERROR cannot use leaf spitting build() on this sterile customizer" << endl ;
407 return 0 ;
408 }
409
410 // Set masterCat to given state
411 if (_masterCat->setLabel(masterCatState)) {
412 oocoutE(nullptr, InputArguments) << "RooCustomizer::build(" << _masterPdf->GetName() << "): ERROR label '" << masterCatState
413 << "' not defined for master splitting category " << _masterCat->GetName() << endl ;
414 return 0 ;
415 }
416
417 return doBuild(masterCatState,verbose) ;
418}
419
420
421
422////////////////////////////////////////////////////////////////////////////////
423/// Back-end implementation of the p.d.f building functionality
424
425RooAbsArg* RooCustomizer::doBuild(const char* masterCatState, bool verbose)
426{
427 // Find nodes that must be split according to provided description, Clone nodes, change their names
428 RooArgSet masterNodesToBeSplit("masterNodesToBeSplit") ;
429 RooArgSet masterNodesToBeReplaced("masterNodesToBeReplaced") ;
430 RooArgSet masterReplacementNodes("masterReplacementNodes") ;
431 RooArgSet clonedMasterNodes("clonedMasterNodes") ;
432
433
434 RooArgSet nodeList(_masterLeafList) ;
435 nodeList.add(_masterBranchList) ;
436
437 // cout << "loop over " << nodeList.getSize() << " nodes" << endl ;
438 for (auto node : nodeList) {
439 RooAbsArg* theSplitArg = !_sterile?(RooAbsArg*) _splitArgList.FindObject(node->GetName()):0 ;
440 if (theSplitArg) {
442 if (verbose) {
443 oocoutI(nullptr, ObjectHandling) << "RooCustomizer::build(" << _masterPdf->GetName()
444 << "): tree node " << node->GetName() << " is split by category " << splitCat->GetName() << endl ;
445 }
446
447 TString newName(node->GetName()) ;
448 if (masterCatState) {
449 newName.Append("_") ;
450 newName.Append(splitCat->getCurrentLabel()) ;
451 }
452
453 // Check if this node instance already exists
454 RooAbsArg* specNode = _cloneNodeListAll ? _cloneNodeListAll->find(newName) : _cloneNodeListOwned->find(newName) ;
455 if (specNode) {
456
457 // Copy instance to one-time use list for this build
458 clonedMasterNodes.add(*specNode) ;
459 if (verbose) {
460 oocoutI(nullptr, ObjectHandling) << "RooCustomizer::build(" << _masterPdf->GetName()
461 << ") Adding existing node specialization " << newName << " to clonedMasterNodes" << endl ;
462 }
463
464 // Affix attribute with old name to clone to support name changing server redirect
465 TString nameAttrib("ORIGNAME:") ;
466 nameAttrib.Append(node->GetName()) ;
467 specNode->setAttribute(nameAttrib) ;
468
469 if (!specNode->getStringAttribute("origName")) {
470 specNode->setStringAttribute("origName",node->GetName()) ;
471 }
472
473
474
475 } else {
476
477 if (node->isDerived()) {
478 oocoutW(nullptr, ObjectHandling) << "RooCustomizer::build(" << _masterPdf->GetName()
479 << "): WARNING: branch node " << node->GetName() << " is split but has no pre-defined specializations" << endl ;
480 }
481
482 TString newTitle(node->GetTitle()) ;
483 newTitle.Append(" (") ;
484 newTitle.Append(splitCat->getCurrentLabel()) ;
485 newTitle.Append(")") ;
486
487 // Create a new clone
488 RooAbsArg* clone = (RooAbsArg*) node->Clone(newName.Data()) ;
489 clone->removeStringAttribute("factory_tag") ;
490 clone->SetTitle(newTitle) ;
491
492 // Affix attribute with old name to clone to support name changing server redirect
493 TString nameAttrib("ORIGNAME:") ;
494 nameAttrib.Append(node->GetName()) ;
495 clone->setAttribute(nameAttrib) ;
496
497 if (!clone->getStringAttribute("origName")) {
498 clone->setStringAttribute("origName",node->GetName()) ;
499 }
500
501 // Add to one-time use list and life-time use list
502 clonedMasterNodes.add(*clone) ;
503 if (_owning) {
504 _cloneNodeListOwned->addOwned(std::unique_ptr<RooAbsArg>{clone});
505 } else {
506 _cloneNodeListOwned->add(*clone) ;
507 }
508 if (_cloneNodeListAll) {
509 _cloneNodeListAll->add(*clone) ;
510 }
511 }
512 masterNodesToBeSplit.add(*node) ;
513 }
514
515 RooAbsArg* ReplaceArg = (RooAbsArg*) _replaceArgList.FindObject(node->GetName()) ;
516 if (ReplaceArg) {
517 RooAbsArg* substArg = (RooAbsArg*) _replaceSubList.At(_replaceArgList.IndexOf(ReplaceArg)) ;
518 if (verbose) {
519 oocoutI(nullptr, ObjectHandling) << "RooCustomizer::build(" << _masterPdf->GetName()
520 << "): tree node " << node->GetName() << " will be replaced by " << substArg->GetName() << endl ;
521 }
522
523 // Affix attribute with old name to support name changing server redirect
524 TString nameAttrib("ORIGNAME:") ;
525 nameAttrib.Append(node->GetName()) ;
526 substArg->setAttribute(nameAttrib) ;
527
528 // Add to list
529 masterNodesToBeReplaced.add(*node) ;
530 masterReplacementNodes.add(*substArg) ;
531 }
532 }
533
534 // Find branches that are affected by splitting and must be cloned
535 RooArgSet masterBranchesToBeCloned("masterBranchesToBeCloned") ;
536 for (auto branch : _masterBranchList) {
537
538 // If branch is split itself, don't handle here
539 if (masterNodesToBeSplit.find(branch->GetName())) {
540 if (verbose) {
541 oocoutI(nullptr, ObjectHandling) << "RooCustomizer::build(" << _masterPdf->GetName() << ") Branch node " << branch->GetName() << " is already split" << endl ;
542 }
543 continue ;
544 }
545 if (masterNodesToBeReplaced.find(branch->GetName())) {
546 if (verbose) {
547 oocoutI(nullptr, ObjectHandling) << "RooCustomizer::build(" << _masterPdf->GetName() << ") Branch node " << branch->GetName() << " is already replaced" << endl ;
548 }
549 continue ;
550 }
551
552 if (branch->dependsOn(masterNodesToBeSplit)) {
553 if (verbose) {
554 oocoutI(nullptr, ObjectHandling) << "RooCustomizer::build(" << _masterPdf->GetName() << ") Branch node "
555 << branch->ClassName() << "::" << branch->GetName() << " cloned: depends on a split parameter" << endl ;
556 }
557 masterBranchesToBeCloned.add(*branch) ;
558 } else if (branch->dependsOn(masterNodesToBeReplaced)) {
559 if (verbose) {
560 oocoutI(nullptr, ObjectHandling) << "RooCustomizer::build(" << _masterPdf->GetName() << ") Branch node "
561 << branch->ClassName() << "::" << branch->GetName() << " cloned: depends on a replaced parameter" << endl ;
562 }
563 masterBranchesToBeCloned.add(*branch) ;
564 }
565 }
566
567 // Clone branches, changes their names
568 RooAbsArg* cloneTopPdf = 0;
569 RooArgSet clonedMasterBranches("clonedMasterBranches") ;
570
571 for (auto branch : masterBranchesToBeCloned) {
572 TString newName(branch->GetName()) ;
573 if (masterCatState) {
574 newName.Append("_") ;
575 newName.Append(masterCatState) ;
576 }
577
578 // Affix attribute with old name to clone to support name changing server redirect
579 RooAbsArg* clone = (RooAbsArg*) branch->Clone(newName.Data()) ;
580 clone->removeStringAttribute("factory_tag") ;
581 TString nameAttrib("ORIGNAME:") ;
582 nameAttrib.Append(branch->GetName()) ;
583 clone->setAttribute(nameAttrib) ;
584
585 if (!clone->getStringAttribute("origName")) {
586 clone->setStringAttribute("origName",branch->GetName()) ;
587 }
588
589 clonedMasterBranches.add(*clone) ;
590
591 // Save pointer to clone of top-level pdf
592 if (branch==_masterPdf) cloneTopPdf=(RooAbsArg*)clone ;
593 }
594
595 if (_owning) {
596 _cloneBranchList->addOwned(clonedMasterBranches) ;
597 } else {
598 _cloneBranchList->add(clonedMasterBranches) ;
599 }
600
601 // Reconnect cloned branches to each other and to cloned nodess
602 for (auto branch : clonedMasterBranches) {
603 branch->redirectServers(clonedMasterBranches,false,true) ;
604 branch->redirectServers(clonedMasterNodes,false,true) ;
605 branch->redirectServers(masterReplacementNodes,false,true) ;
606 }
607
608 return cloneTopPdf ? cloneTopPdf : _masterPdf ;
609}
610
611
612////////////////////////////////////////////////////////////////////////////////
613/// Print arguments of customizer, i.e. input p.d.f and input master category (if any)
614
615void RooCustomizer::printArgs(ostream& os) const
616{
617 os << "[ masterPdf=" << _masterPdf->GetName() ;
618 if (_masterCat) {
619 os << " masterCat=" << _masterCat->GetName() ;
620 }
621 os << " ]" ;
622}
623
624
625
626////////////////////////////////////////////////////////////////////////////////
627/// Print customizer configuration details
628
629void RooCustomizer::printMultiline(ostream& os, Int_t /*content*/, bool /*verbose*/, TString indent) const
630{
631 os << indent << "RooCustomizer for " << _masterPdf->GetName() << (_sterile?" (sterile)":"") << endl ;
632
633 Int_t i, nsplit = _splitArgList.GetSize() ;
634 if (nsplit>0) {
635 os << indent << " Splitting rules:" << endl ;
636 for (i=0 ; i<nsplit ; i++) {
637 os << indent << " " << _splitArgList.At(i)->GetName() << " is split by " << _splitCatList.At(i)->GetName() << endl ;
638 }
639 }
640
641 Int_t nrepl = _replaceArgList.GetSize() ;
642 if (nrepl>0) {
643 os << indent << " Replacement rules:" << endl ;
644 for (i=0 ; i<nrepl ; i++) {
645 os << indent << " " << _replaceSubList.At(i)->GetName() << " replaces " << _replaceArgList.At(i)->GetName() << endl ;
646 }
647 }
648
649 return ;
650}
651
652
653
654////////////////////////////////////////////////////////////////////////////////
655/// Install the input RooArgSet as container in which all cloned branches
656/// will be stored
657
659{
660 _cloneBranchList = &cloneBranchSet ;
662}
663
664
666 return static_cast<RooAbsPdf&>(*_masterPdf);
667}
668
669
670namespace {
671
672////////////////////////////////////////////////////////////////////////////////
673
674std::string CustIFace::create(RooFactoryWSTool& ft, const char* typeName, const char* instanceName, std::vector<std::string> args)
675{
676 // Check number of arguments
677 if (args.size()<2) {
678 throw string(Form("RooCustomizer::CustIFace::create() ERROR: expect at least 2 arguments for EDIT: the input object and at least one $Replace() rule")) ;
679 }
680
681 if (string(typeName)!="EDIT") {
682 throw string(Form("RooCustomizer::CustIFace::create() ERROR: unknown type requested: %s",typeName)) ;
683 }
684
685 // Check that first arg exists as RooAbsArg
686 RooAbsArg* arg = ft.ws().arg(args[0].c_str()) ;
687 if (!arg) {
688 throw string(Form("RooCustomizer::CustIFace::create() ERROR: input RooAbsArg %s does not exist",args[0].c_str())) ;
689 }
690
691 // If name of new object is same as original, execute in sterile mode (i.e no suffixes attached), and rename original nodes in workspace upon import
692 if (args[0]==instanceName) {
693 instanceName=0 ;
694 }
695
696 // Create a customizer
697 RooCustomizer cust(*arg,instanceName) ;
698
699 for (unsigned int i=1 ; i<args.size() ; i++) {
700 char buf[1024] ;
701 strlcpy(buf,args[i].c_str(),1024) ;
702 char* sep = strchr(buf,'=') ;
703 if (!sep) {
704 throw string(Form("RooCustomizer::CustIFace::create() ERROR: unknown argument: %s, expect form orig=subst",args[i].c_str())) ;
705 }
706 *sep = 0 ;
707 RooAbsArg* orig = ft.ws().arg(buf) ;
708 RooAbsArg* subst(0) ;
709 if (string(sep+1).find("$REMOVE")==0) {
710
711 // Create a removal dummy ;
713
714 // If removal instructed was annotated with target node, encode these in removal dummy
715 char* sep2 = strchr(sep+1,'(') ;
716 if (sep2) {
717 char buf2[1024] ;
718 strlcpy(buf2,sep2+1,1024) ;
719 char* saveptr ;
720 char* tok = R__STRTOK_R(buf2,",)",&saveptr) ;
721 while(tok) {
722 //cout << "$REMOVE is restricted to " << tok << endl ;
723 subst->setAttribute(Form("REMOVE_FROM_%s",tok)) ;
724 tok = R__STRTOK_R(0,",)",&saveptr) ;
725 }
726 } else {
727 // Otherwise mark as universal removal node
728 subst->setAttribute("REMOVE_ALL") ;
729 }
730
731 } else {
732 subst = ft.ws().arg(sep+1) ;
733 }
734// if (!orig) {
735// throw string(Form("RooCustomizer::CustIFace::create() ERROR: $Replace() input RooAbsArg %s does not exist",buf)) ;
736// }
737// if (!subst) {
738// throw string(Form("RooCustomizer::CustIFace::create() ERROR: $Replace() replacement RooAbsArg %s does not exist",sep+1)) ;
739// }
740 if (orig && subst) {
741 cust.replaceArg(*orig,*subst) ;
742 } else {
743 oocoutW(nullptr,ObjectHandling) << "RooCustomizer::CustIFace::create() WARNING: input or replacement of a replacement operation not found, operation ignored"<< endl ;
744 }
745 }
746
747 // Build the desired edited object
748 RooAbsArg* targ = cust.build(false) ;
749 if (!targ) {
750 throw string(Form("RooCustomizer::CustIFace::create() ERROR in customizer build, object %snot created",instanceName)) ;
751 }
752
753 // Import the object into the workspace
754 if (instanceName) {
755 // Set the desired name of the top level node
756 targ->SetName(instanceName) ;
757 // Now import everything. What we didn't touch gets recycled, everything else was cloned here:
758 ft.ws().import(cust.cloneBranchList(), RooFit::Silence(true), RooFit::RecycleConflictNodes(true), RooFit::NoRecursion(false));
759 } else {
760 ft.ws().import(cust.cloneBranchList(), RooFit::Silence(true), RooFit::RenameConflictNodes("orig",1), RooFit::NoRecursion(true));
761 }
762
763 return string(instanceName?instanceName:targ->GetName()) ;
764}
765
766} // namespace
#define oocoutW(o, a)
#define oocoutE(o, a)
#define oocoutI(o, a)
static void indent(ostringstream &buf, int indent_level)
char name[80]
Definition TGX11.cxx:110
char * Form(const char *fmt,...)
Formats a string in a circular formatting buffer.
Definition TString.cxx:2467
RooAbsArg is the common abstract base class for objects that represent a value and a "shape" in RooFi...
Definition RooAbsArg.h:74
void setStringAttribute(const Text_t *key, const Text_t *value)
Associate string 'value' to this object under key 'key'.
void SetName(const char *name) override
Set the name of the TNamed.
bool addOwnedComponents(const RooAbsCollection &comps)
Take ownership of the contents of 'comps'.
const Text_t * getStringAttribute(const Text_t *key) const
Get string attribute mapped under key 'key'.
void removeStringAttribute(const Text_t *key)
Delete a string attribute with a given key.
void setAttribute(const Text_t *name, bool value=true)
Set (default) or clear a named boolean attribute of this object.
void branchNodeServerList(RooAbsCollection *list, const RooAbsArg *arg=nullptr, bool recurseNonDerived=false) const
Fill supplied list with all branch nodes of the arg tree starting with ourself as top node.
TObject * Clone(const char *newname=nullptr) const override
Make a clone of an object using the Streamer facility.
Definition RooAbsArg.h:86
void leafNodeServerList(RooAbsCollection *list, const RooAbsArg *arg=nullptr, bool recurseNonDerived=false) const
Fill supplied list with all leaf nodes of the arg tree, starting with ourself as top node.
RooAbsCategoryLValue is the common abstract base class for objects that represent a discrete value th...
virtual bool setLabel(const char *label, bool printError=true)=0
Change category state by specifying a state name.
A space to attach TBranches.
virtual const char * getCurrentLabel() const
Return label string of current state.
virtual bool add(const RooAbsArg &var, bool silent=false)
Add the specified argument to list.
virtual bool addOwned(RooAbsArg &var, bool silent=false)
Add an argument and transfer the ownership to the collection.
void useHashMapForFind(bool flag) const
RooAbsArg * find(const char *name) const
Find object with given name in list.
RooArgSet is a container object that can hold multiple RooAbsArg objects.
Definition RooArgSet.h:55
RooCustomizer is a factory class to produce clones of a prototype composite PDF object with the same ...
TString _name
Name of this object.
TList _splitArgList
List of RooAbsArgs to be split.
void splitArg(const RooAbsArg &arg, const RooAbsCategory &splitCat)
Split all argument 'arg' into individualized clones for each defined state of 'splitCat'.
void setCloneBranchSet(RooArgSet &cloneBranchSet)
Releases ownership of list of cloned branch nodes.
RooArgSet * _cloneNodeListAll
List of all cloned nodes.
void replaceArg(const RooAbsArg &orig, const RooAbsArg &subst)
Replace any occurence of arg 'orig' with arg 'subst'.
RooAbsArg * _masterPdf
Pointer to input p.d.f.
bool _owning
If true we own all created components.
TList _replaceSubList
List of replacement RooAbsArgs.
RooAbsArg * build(const char *masterCatState, bool verbose=false)
Build a clone of the prototype executing all registered 'replace' rules and 'split' rules for the mas...
RooArgSet * _cloneBranchList
Pointer to list of cloned branches used.
RooCustomizer(const RooAbsArg &pdf, const RooAbsCategoryLValue &masterCat, RooArgSet &splitLeafListOwned, RooArgSet *splitLeafListAll=nullptr)
Constructor with a prototype and masterCat index category.
RooArgSet _masterBranchList
List of branch nodes.
RooArgSet _masterLeafList
List of leaf nodes.
~RooCustomizer()
Destructor.
RooArgSet _internalCloneBranchList
List of branches of internal clone.
void initialize()
Initialize the customizer.
RooAbsCategoryLValue * _masterCat
Pointer to input master category.
void splitArgs(const RooArgSet &argSet, const RooAbsCategory &splitCat)
Split all arguments in 'set' into individualized clones for each defined state of 'splitCat'.
void printMultiline(std::ostream &os, Int_t content, bool verbose=false, TString indent="") const
Print customizer configuration details.
RooAbsArg * doBuild(const char *masterCatState, bool verbose)
Back-end implementation of the p.d.f building functionality.
TList _replaceArgList
List of RooAbsArgs to be replaced.
bool _sterile
If true we do not have as associated master category.
RooAbsPdf const & pdf() const
TList _splitCatList
List of categories to be used for above splits.
RooArgSet * _cloneNodeListOwned
List of owned cloned nodes.
void printArgs(std::ostream &os) const
Print arguments of customizer, i.e. input p.d.f and input master category (if any)
virtual std::string create(RooFactoryWSTool &ft, const char *typeName, const char *instanceName, std::vector< std::string > args)=0
RooFactoryWSTool is a class similar to TTree::MakeClass() that generates skeleton code for RooAbsPdf ...
RooWorkspace & ws()
static void registerSpecial(const char *typeName, RooFactoryWSTool::IFace *iface)
Register foreign special objects in factory.
static RooConstVar & removalDummy()
Create a dummy node used in node-removal operations.
bool import(const RooAbsArg &arg, const RooCmdArg &arg1=RooCmdArg(), const RooCmdArg &arg2=RooCmdArg(), const RooCmdArg &arg3=RooCmdArg(), const RooCmdArg &arg4=RooCmdArg(), const RooCmdArg &arg5=RooCmdArg(), const RooCmdArg &arg6=RooCmdArg(), const RooCmdArg &arg7=RooCmdArg(), const RooCmdArg &arg8=RooCmdArg(), const RooCmdArg &arg9=RooCmdArg())
Import a RooAbsArg object, e.g.
RooAbsArg * arg(RooStringView name) const
Return RooAbsArg with given name. A null pointer is returned if none is found.
virtual Int_t GetSize() const
Return the capacity of the collection, i.e.
TObject * FindObject(const char *name) const override
Find an object in this list using its name.
Definition TList.cxx:578
void Add(TObject *obj) override
Definition TList.h:81
TObject * At(Int_t idx) const override
Returns the object at position idx. Returns 0 if idx is out of range.
Definition TList.cxx:357
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
virtual const char * GetName() const
Returns name of object.
Definition TObject.cxx:439
virtual Int_t IndexOf(const TObject *obj) const
Return index of object in collection.
Basic string class.
Definition TString.h:139
Ssiz_t Length() const
Definition TString.h:421
const char * Data() const
Definition TString.h:380
TString & Append(const char *cs)
Definition TString.h:576
RooCmdArg RecycleConflictNodes(bool flag=true)
RooCmdArg Silence(bool flag=true)
RooCmdArg NoRecursion(bool flag=true)
RooCmdArg RenameConflictNodes(const char *suffix, bool renameOrigNodes=false)
void(off) SmallVectorTemplateBase< T
void init()
Inspect hardware capabilities, and load the optimal library for RooFit computations.