49#include <unordered_map>
60 if (exclLVBranches.
empty())
72 for (
const auto client : server->valueClients()) {
74 if (!(exclLVBranches.
find(client->GetName()) == client)) {
75 if (allBranches.
find(client->GetName()) == client) {
76 if (!servesExclusively(client, exclLVBranches, allBranches)) {
87 return (numLVServ == 1);
91 ServerToAdd(
RooAbsArg *theArg,
bool isShape) : arg{theArg}, isShapeServer{isShape} {}
93 bool isShapeServer =
false;
96void addObservableToServers(
RooAbsReal const &function,
RooAbsArg &leaf, std::vector<ServerToAdd> &serversToAdd,
97 const char *rangeName)
100 if (leaflv && leaflv->getBinning(rangeName).isParameterized()) {
103 <<
" has parameterized binning, add value dependence of boundary objects rather than shape of leaf"
105 if (leaflv->getBinning(rangeName).lowBoundFunc()) {
106 serversToAdd.emplace_back(leaflv->getBinning(rangeName).lowBoundFunc(),
false);
108 if (leaflv->getBinning(rangeName).highBoundFunc()) {
109 serversToAdd.emplace_back(leaflv->getBinning(rangeName).highBoundFunc(),
false);
113 <<
" as shape dependent" << std::endl;
114 serversToAdd.emplace_back(&leaf,
true);
118void addParameterToServers(
RooAbsReal const &function,
RooAbsArg &leaf, std::vector<ServerToAdd> &serversToAdd,
121 if (!isShapeServer) {
123 <<
" as value dependent" << std::endl;
126 <<
" as shape dependent" << std::endl;
128 serversToAdd.emplace_back(&leaf, isShapeServer);
131enum class MarkedState { Dependent, Independent, AlreadyAdded };
134void unmarkDepValueClients(
RooAbsArg const &dep, std::unordered_map<RooAbsArg const *, std::size_t>
const &indexMap,
135 std::vector<MarkedState> &marked)
137 auto found = indexMap.find(&dep);
138 if (found == indexMap.end())
140 marked[found->second] = MarkedState::Dependent;
144 std::vector<RooAbsArg const *> stack{&dep};
145 while (!stack.empty()) {
148 for (
RooAbsArg *client : arg->valueClients()) {
149 auto foundClient = indexMap.find(client);
150 if (foundClient != indexMap.end() && marked[foundClient->second] != MarkedState::Dependent) {
151 marked[foundClient->second] = MarkedState::Dependent;
152 stack.push_back(client);
158std::vector<ServerToAdd>
159getValueAndShapeServers(
RooAbsReal const &function,
RooArgSet const &depList,
const char *rangeName)
161 std::vector<ServerToAdd> serversToAdd;
173 std::unordered_map<RooAbsArg const *, std::size_t> indexMap;
174 std::unordered_map<TNamed const *, std::size_t> indexMapByName;
175 indexMap.reserve(allArgs.size());
176 indexMapByName.reserve(allArgs.size());
177 for (std::size_t i = 0; i < allArgs.size(); ++i) {
178 indexMap.emplace(allArgs[i], i);
179 indexMapByName.emplace(allArgs[i]->namePtr(), i);
185 RooArgSet allValueArgs{allValueArgsList};
188 std::vector<MarkedState> marked(allArgs.size(), MarkedState::Independent);
190 if (
auto foundFunc = indexMap.find(&function); foundFunc != indexMap.end()) {
191 marked[foundFunc->second] = MarkedState::Dependent;
200 unmarkDepValueClients(*depInArgs, indexMap, marked);
201 addObservableToServers(function, *depInArgs, serversToAdd, rangeName);
207 for (std::size_t i = 0; i < allArgs.size(); ++i) {
208 if (marked[i] == MarkedState::Dependent) {
209 for (
RooAbsArg *server : allArgs[i]->servers()) {
210 auto found = indexMapByName.find(server->
namePtr());
211 if (found != indexMapByName.end() && marked[found->second] == MarkedState::Independent) {
212 addParameterToServers(function, *server, serversToAdd, !allValueArgs.find(*server));
213 marked[found->second] = MarkedState::AlreadyAdded;
236 if (intDep->namePtr() != branch->namePtr() && branch->dependsOnValue(*intDep)) {
242 filteredIntDeps.
add(*intDep);
246 for (
const auto arg : function.servers()) {
262 if ((realArgLV && filteredIntDeps.
find(realArgLV->
GetName()) &&
270 bool overlapOK =
true;
271 for (
const auto otherArg : function.servers()) {
277 if (arg->
overlaps(*otherArg,
true)) {
291 anIntOKDepList.
add(*arg,
true);
294 <<
" is suitable for analytical integration (if supported by p.d.f)" << std::endl;
325 const char* rangeName) :
328 _respectCompSelect{!_globalSelectComp},
329 _sumList(
"!sumList",
"Categories to be summed numerically",this,false,false),
330 _intList(
"!intList",
"Variables to be integrated numerically",this,false,false),
331 _anaList(
"!anaList",
"Variables to be integrated analytically",this,false,false),
332 _jacList(
"!jacList",
"Jacobian product term",this,false,false),
333 _facList(
"!facList",
"Variables independent of function",this,false,true),
334 _function(
"!func",
"Function to be integrated",this,false,false),
336 _sumCat(
"!sumCat",
"SuperCategory for summation",this,false,false),
360 oocxcoutI(&function,Integration) <<
"RooRealIntegral::ctor(" <<
GetName() <<
") Constructing integral of function "
361 << function.
GetName() <<
" over observables" << depList <<
" with normalization "
363 << (rangeName?rangeName:
"<none>") << std::endl ;
393 for (
auto arg : intDepList) {
400 std::unique_ptr<RooAbsArg> argClone{
static_cast<RooAbsArg*
>(arg->
Clone())};
407 oocxcoutI(&function,Integration) << function.
GetName() <<
": Factorizing observables are " <<
_facList << std::endl ;
418 RooArgSet exclLVBranches(
"exclLVBranches") ;
428 for (
RooAbsArg *branch : branchListVDAll) {
429 if (branch != &function) {
433 branchListVD.
add(*branch,
true);
437 for (
auto branch: branchList) {
440 if ((realArgLV && (realArgLV->
isJacobianOK(intDepList)!=0)) || catArgLV) {
441 exclLVBranches.
add(*branch) ;
444 exclLVBranches.
remove(depList,
true,
true) ;
448 RooArgSet exclLVServers(
"exclLVServers") ;
452 bool converged(
false) ;
457 std::vector<RooAbsArg*> toBeRemoved;
458 for (
auto server : exclLVServers) {
459 if (!servesExclusively(server,exclLVBranches,branchListVD)) {
460 toBeRemoved.push_back(server);
464 exclLVServers.
remove(toBeRemoved.begin(), toBeRemoved.end());
468 for (std::size_t i=0; i < exclLVBranches.
size(); ++i) {
469 const RooAbsArg* branch = exclLVBranches[i];
473 bsList.
remove(exclLVServers,
true,
true) ;
474 if (!bsList.
empty()) {
475 exclLVBranches.
remove(*branch,
true,
true) ;
484 for (std::size_t i=0; i < exclLVBranches.
size(); ++i) {
485 const RooAbsArg* branch = exclLVBranches[i];
487 exclLVBranches.
remove(*branch,
true,
true) ;
495 intDepList.
remove(exclLVServers) ;
496 intDepList.
add(exclLVBranches) ;
506 for (
auto arg : intDepList) {
508 anIntOKDepList.
add(*arg) ;
512 if (!anIntOKDepList.
empty()) {
513 oocxcoutI(&function,Integration) << function.
GetName() <<
": Observables that function forcibly requires to be integrated internally " << anIntOKDepList << std::endl ;
522 auto serversToAdd = getValueAndShapeServers(function, depList, rangeName);
523 fillAnIntOKDepList(function, intDepList, anIntOKDepList, branchListVD);
540 oocxcoutI(&function,Integration) << function.
GetName() <<
": Function integrated observables " <<
_anaList <<
" internally with code " <<
_mode << std::endl ;
566 std::unique_ptr<RooArgSet> argDepList{arg->
getObservables(&intDepList)};
567 for (
const auto argDep : *argDepList) {
578 if (!exclLVServers.
empty()) {
580 intDepList.
remove(exclLVBranches) ;
581 intDepList.
add(exclLVServers) ;
587 for (
const auto arg : function.
servers()) {
599 auto argDeps = std::unique_ptr<RooArgSet>(arg->
getObservables(&intDepList));
603 for (
const auto dep : *argDeps) {
613 oocxcoutI(&function,Integration) << function.
GetName() <<
": Observables " <<
_anaList <<
" are analytically integrated with code " <<
_mode << std::endl ;
616 oocxcoutI(&function,Integration) << function.
GetName() <<
": Observables " <<
_intList <<
" are numerically integrated" << std::endl ;
619 oocxcoutI(&function,Integration) << function.
GetName() <<
": Observables " <<
_sumList <<
" are numerically summed" << std::endl ;
654 for(
auto const& toAdd : serversToAdd) {
655 addServer(*toAdd.arg, !toAdd.isShapeServer, toAdd.isShapeServer);
672 for (
const auto leaf : leafSet) {
714 coutE(Integration) <<
ClassName() <<
"::" <<
GetName() <<
": failed to create valid integrand." << std::endl;
724 coutE(Integration) <<
ClassName() <<
"::" <<
GetName() <<
": failed to create valid integrator." << std::endl;
728 cxcoutI(NumericIntegration) <<
"RooRealIntegral::init(" <<
GetName() <<
") using numeric integrator "
729 << integratorName <<
" to calculate Int" <<
_intList << std::endl ;
732 cxcoutI(NumericIntegration) <<
"RooRealIntegral::init(" <<
GetName() <<
") evaluation requires " <<
_intList.
size() <<
"-D numeric integration step. Evaluation may be slow, sufficient numeric precision for fitting & minimization is not guaranteed" << std::endl ;
744 _valid(other._valid),
745 _respectCompSelect(other._respectCompSelect),
746 _sumList(
"!sumList", this, other._sumList),
747 _intList(
"!intList", this, other._intList),
748 _anaList(
"!anaList", this, other._anaList),
749 _jacList(
"!jacList", this, other._jacList),
750 _facList(
"!facList", this, other._facList),
751 _function(
"!func", this, other._function),
752 _iconfig(other._iconfig),
753 _sumCat(
"!sumCat", this, other._sumCat),
755 _intOperMode(other._intOperMode),
756 _rangeName(other._rangeName)
791 std::unique_ptr<RooArgSet> tmp;
797 tmp = std::make_unique<RooArgSet>();
800 newNormSet = tmp.get();
844 <<
":evaluate: cannot initialize numerical integrator" << std::endl;
852 for (
auto *arg : serverList) {
871 cxcoutD(Tracing) <<
"RooRealIntegral::evaluate_analytic(" <<
GetName()
903 retVal *= argLV->numTypes() ;
916 ccxcoutD(Tracing) <<
"raw*fact = " << retVal << std::endl ;
934 jacProd *= arg->jacobian() ;
939 return std::abs(jacProd) ;
952 for (
const auto& nameIdx : *sumCat) {
985 bool mustReplaceAll,
bool nameChange,
bool isRecursive)
1008 _params = std::make_unique<RooArgSet>(
"params") ;
1059 os <<
"d[Ana]" << tmp <<
" ";
1065 if (!tmp2.
empty()) {
1066 os <<
" d[Num]" << tmp2 <<
" ";
1076 os <<
indent <<
"--- RooRealIntegral ---" << std::endl;
1077 os <<
indent <<
" Integrates ";
1081 os <<
indent <<
" operating mode is "
1083 os <<
indent <<
" Summed discrete args are " <<
_sumList << std::endl ;
1084 os <<
indent <<
" Numerically integrated args are " <<
_intList << std::endl;
1085 os <<
indent <<
" Analytically integrated args using mode " <<
_mode <<
" are " <<
_anaList << std::endl ;
1086 os <<
indent <<
" Arguments included in Jacobian are " <<
_jacList << std::endl ;
1087 os <<
indent <<
" Factorized arguments are " <<
_facList << std::endl ;
1088 os <<
indent <<
" Function normalization set " ;
1114std::unique_ptr<RooAbsArg>
size_t size(const MatrixT &matrix)
retrieve the size of a square matrix
int Int_t
Signed integer 4 bytes (int)
static void indent(ostringstream &buf, int indent_level)
static unsigned int total
char * Form(const char *fmt,...)
Formats a string in a circular formatting buffer.
Common abstract base class for objects that represent a value and a "shape" in RooFit.
RooExpensiveObjectCache & expensiveObjectCache() const
bool overlaps(const RooAbsArg &testArg, bool valueOnly=false) const
Test if any of the nodes of tree are shared with that of the given tree.
void Print(Option_t *options=nullptr) const override
Print the object to the defaultPrintStream().
bool dependsOn(const RooAbsCollection &serverList, const RooAbsArg *ignoreArg=nullptr, bool valueOnly=false) const
Test whether we depend on (ie, are served by) any object in the specified collection.
const TNamed * namePtr() const
De-duplicated pointer to this object's name.
virtual void syncCache(const RooArgSet *nset=nullptr)=0
void setOperMode(OperMode mode, bool recurseADirty=true)
Set the operation mode of this node.
bool isShapeServer(const RooAbsArg &arg) const
Check if this is serving shape to arg.
RooFit::OwningPtr< RooArgSet > getObservables(const RooArgSet &set, bool valueOnly=true) const
Given a set of possible observables, return the observables that this PDF depends on.
virtual void setExpensiveObjectCache(RooExpensiveObjectCache &cache)
bool addOwnedComponents(const RooAbsCollection &comps)
Take ownership of the contents of 'comps'.
virtual bool isLValue() const
Is this argument an l-value, i.e., can it appear on the left-hand side of an assignment expression?...
virtual std::unique_ptr< RooAbsArg > compileForNormSet(RooArgSet const &normSet, RooFit::Detail::CompileContext &ctx) const
const RefCountList_t & servers() const
List of all servers of this object.
bool dependsOnValue(const RooAbsCollection &serverList, const RooAbsArg *ignoreArg=nullptr) const
Check whether this object depends on values from an element in the serverList.
void addServer(RooAbsArg &server, bool valueProp=true, bool shapeProp=false, std::size_t refCount=1)
Register another RooAbsArg as a server to us, ie, declare that we depend on it.
virtual bool isDerived() const
Does value or shape of this arg depend on any other arg?
bool getAttribute(const Text_t *name) const
Check if a named attribute is set. By default, all attributes are unset.
bool isValueOrShapeDirtyAndClear() const
void setProxyNormSet(const RooArgSet *nset)
Forward a change in the cached normalization argset to all the registered proxies.
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.
RefCountList_t _serverList
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.
virtual bool isFundamental() const
Is this object a fundamental type that can be added to a dataset? Fundamental-type subclasses overrid...
bool isValueServer(const RooAbsArg &arg) const
Check if this is serving values to arg.
void treeNodeServerList(RooAbsCollection *list, const RooAbsArg *arg=nullptr, bool doBranch=true, bool doLeaf=true, bool valueOnly=false, bool recurseNonDerived=false) const
Fill supplied list with nodes of the arg tree, following all server links, starting with ourself as t...
OperMode operMode() const
Query the operation mode of this node.
Abstract base class for objects that represent a discrete value that can be set from the outside,...
Abstract container object that can hold multiple RooAbsArg objects.
bool contains(const char *name) const
Check if collection contains an argument with a specific name.
RooFit::UniqueId< RooAbsCollection > const & uniqueId() const
Returns a unique ID that is different for every instantiated RooAbsCollection.
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.
void sortTopologically()
Sort collection topologically: the servers of any RooAbsArg will be before that RooAbsArg in the coll...
virtual bool add(const RooAbsArg &var, bool silent=false)
Add the specified argument to list.
void assign(const RooAbsCollection &other) const
Sets the value, cache and constant attribute of any argument in our set that also appears in the othe...
Storage_t::size_type size() const
RooAbsArg * first() const
void reserve(Storage_t::size_type count)
RooAbsArg * find(const char *name) const
Find object with given name in list.
Abstract base class for objects that are lvalues, i.e.
Abstract base class for objects that represent a real value that may appear on the left hand side of ...
virtual bool isJacobianOK(const RooArgSet &depList) const
Abstract base class for objects that represent a real value and implements functionality common to al...
double getVal(const RooArgSet *normalisationSet=nullptr) const
Evaluate object.
virtual Int_t getAnalyticalIntegralWN(RooArgSet &allVars, RooArgSet &analVars, const RooArgSet *normSet, const char *rangeName=nullptr) const
Variant of getAnalyticalIntegral that is also passed the normalization set that should be applied to ...
void printMultiline(std::ostream &os, Int_t contents, bool verbose=false, TString indent="") const override
Structure printing.
bool redirectServersHook(const RooAbsCollection &newServerList, bool mustReplaceAll, bool nameChange, bool isRecursiveStep) override
Function that is called at the end of redirectServers().
virtual bool forceAnalyticalInt(const RooAbsArg &) const
double _value
Cache for current value of object.
double traceEval(const RooArgSet *set) const
Calculate current value of object, with error tracing wrapper.
RooFit::UniqueId< RooArgSet >::Value_t _lastNormSetId
!
virtual double analyticalIntegralWN(Int_t code, const RooArgSet *normSet, const char *rangeName=nullptr) const
Implements the actual analytical integral(s) advertised by getAnalyticalIntegral.
const RooNumIntConfig * getIntegratorConfig() const
Return the numeric integration configuration used for this object.
virtual bool isBinnedDistribution(const RooArgSet &) const
Tests if the distribution is binned. Unless overridden by derived classes, this always returns false.
RooFit::OwningPtr< RooAbsReal > createIntegral(const RooArgSet &iset, 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
Create an object that represents the integral of the function over one or more observables listed in ...
RooArgList is a container object that can hold multiple RooAbsArg objects.
bool _valueServer
If true contents is value server of owner.
bool isValueServer() const
Returns true of contents is value server of owner.
RooArgSet is a container object that can hold multiple RooAbsArg objects.
RooArgSet * snapshot(bool deepCopy=true) const
Use RooAbsCollection::snapshot(), but return as RooArgSet.
void removeAll() override
Remove all argument inset using remove(const RooAbsArg&).
bool addOwned(RooAbsArg &var, bool silent=false) override
Overloaded RooCollection_t::addOwned() method insert object into owning set and registers object as s...
bool add(const RooAbsArg &var, bool valueServer, bool shapeServer, bool silent)
Overloaded RooCollection_t::add() method insert object into set and registers object as server to own...
Represents a constant real-valued object.
Registry for const char* names.
static const char * str(const TNamed *ptr)
Return C++ string corresponding to given TNamed pointer.
Holds the configuration parameters of the various numeric integrators used by RooRealIntegral.
std::unique_ptr< RooAbsIntegrator > createIntegrator(RooAbsFunc &func, const RooNumIntConfig &config, int ndim=0, bool isBinned=false) const
Construct a numeric integrator instance that operates on function 'func' and is configured with 'conf...
std::string getIntegratorName(RooAbsFunc &func, const RooNumIntConfig &config, int ndim=0, bool isBinned=false) const
static RooNumIntFactory & instance()
Static method returning reference to singleton instance of factory.
virtual void printStream(std::ostream &os, Int_t contents, StyleOption style, TString indent="") const
Print description of object on ostream, printing contents set by contents integer,...
Performs hybrid numerical/analytical integrals of RooAbsReal objects.
RooNumIntConfig * _iconfig
bool initNumIntegrator() const
(Re)Initialize numerical integration engine if necessary.
RooArgSet const * funcNormSet() const
RooFit::OwningPtr< RooAbsReal > createIntegral(const RooArgSet &iset, const RooArgSet *nset=nullptr, const RooNumIntConfig *cfg=nullptr, const char *rangeName=nullptr) const override
Create an object that represents the integral of the function over one or more observables listed in ...
void setAllowComponentSelection(bool allow)
Set component selection to be allowed/forbidden.
RooRealProxy _function
Function being integrated.
RooArgSet intVars() const
RooSetProxy _intList
Set of continuous observables over which is integrated numerically.
virtual double sum() const
Perform summation of list of category dependents to be integrated.
RooSetProxy _facList
Set of observables on which function does not depends, which are integrated nevertheless.
std::unique_ptr< RooArgSet > _params
! cache for set of parameters
static void setCacheAllNumeric(Int_t ndim)
Global switch to cache all integral values that integrate at least ndim dimensions numerically.
IntOperMode _intOperMode
integration operation mode
double evaluate() const override
Perform the integration and return the result.
const RooArgSet & parameters() const
std::unique_ptr< RooAbsFunc > _numIntegrand
!
void addNumIntDep(RooAbsArg const &arg)
Sort numeric integration variables in summation and integration lists.
RooSetProxy _jacList
Set of lvalue observables over which is analytically integration that have a non-unit Jacobian.
bool isValidReal(double value, bool printError=false) const override
Check if current value is valid.
double getValV(const RooArgSet *set=nullptr) const override
Return value of object.
RooSetProxy _anaList
Set of observables over which is integrated/summed analytically.
bool _restartNumIntEngine
!
bool redirectServersHook(const RooAbsCollection &newServerList, bool mustReplaceAll, bool nameChange, bool isRecursive) override
Intercept server redirects and reconfigure internal object accordingly.
RooSetProxy _sumList
Set of discrete observable over which is summed numerically.
~RooRealIntegral() override
void printMetaArgs(std::ostream &os) const override
Customized printing of arguments of a RooRealIntegral to more intuitively reflect the contents of the...
void printMultiline(std::ostream &os, Int_t contents, bool verbose=false, TString indent="") const override
Print the state of this object to the specified output stream.
std::unique_ptr< RooAbsIntegrator > _numIntEngine
!
virtual double integrate() const
Perform hybrid numerical/analytical integration over all real-valued dependents.
virtual double jacobianProduct() const
Return product of jacobian terms originating from analytical integration.
static Int_t getCacheAllNumeric()
Return minimum dimensions of numeric integration for which values are cached.
static Int_t _cacheAllNDim
! Cache all integrals with given numeric dimension
RooArgSet const * actualFuncNormSet() const
std::unique_ptr< RooArgSet > _funcNormSet
Optional normalization set passed to function.
std::unique_ptr< RooAbsArg > compileForNormSet(RooArgSet const &normSet, RooFit::Detail::CompileContext &ctx) const override
void autoSelectDirtyMode()
Set appropriate cache operation mode for integral depending on cache operation mode of server objects...
const char * intRange() const
bool getAllowComponentSelection() const
Check if component selection is allowed.
Joins several RooAbsCategoryLValue objects into a single category.
bool setIndex(value_type index, bool printError=true) override
Set the value of the super category to the specified index.
bool inRange(const char *rangeName) const override
Check that all input category states are in the given range.
bool setArg(T &newRef)
Change object held in proxy into newRef.
The TNamed class is the base class for all named ROOT classes.
const char * GetName() const override
Returns name of object.
virtual const char * ClassName() const
Returns name of class to which the object belongs.
TString & Append(const char *cs)
T * OwningPtr
An alias for raw pointers for indicating that the return type of a RooFit function is an owning point...
constexpr Value_t value() const
Return numerical value of ID.