Logo ROOT  
Reference Guide
 
Loading...
Searching...
No Matches
RooAbsCollection.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 RooAbsCollection.cxx
19\class RooAbsCollection
20\ingroup Roofitcore
21
22Abstract container object that can hold
23multiple RooAbsArg objects. Collections are ordered and can
24contain multiple objects of the same name, (but a derived
25implementation can enforce unique names). The storage of objects is
26implemented using the container denoted by RooAbsCollection::Storage_t.
27**/
28
29#include "RooAbsCollection.h"
30
31#include "TClass.h"
32#include "TRegexp.h"
33#include "RooStreamParser.h"
34#include "RooAbsRealLValue.h"
36#include "RooStringVar.h"
37#include "RooTrace.h"
38#include "RooArgList.h"
39#include "RooLinkedListIter.h"
40#include "RooCmdConfig.h"
41#include "RooRealVar.h"
42#include "RooGlobalFunc.h"
43#include "RooMsgService.h"
44#include "RooFitImplHelpers.h"
45
46#include <strlcpy.h>
47#include <algorithm>
48#include <iomanip>
49#include <iostream>
50#include <fstream>
51#include <memory>
52
54
55namespace RooFit {
56namespace Detail {
57
58/**
59 * Helper for hash-map-assisted finding of elements by name.
60 * Create this helper if finding of elements by name is needed.
61 * Upon creation, this object checks the global
62 * RooNameReg::renameCounter()
63 * and tracks elements of this collection by name. If an element
64 * gets renamed, this counter will be increased, and the name to
65 * object map becomes invalid. In this case, it has to be recreated.
66 */
68
69 /// Initialise empty hash map for fast finding by name.
70 template<typename It_t>
71 HashAssistedFind(It_t first, It_t last) :
72 currentRooNameRegCounter{ RooNameReg::instance().renameCounter() },
74 {
75 nameToItemMap.reserve(std::distance(first, last));
76 for (auto it = first; it != last; ++it) {
77 nameToItemMap.emplace((*it)->namePtr(), *it);
78 }
79 }
80
81 bool isValid() const {
83 }
84
85 RooAbsArg * find(const TNamed * nptr) const {
86 assert(isValid());
87
88 auto item = nameToItemMap.find(nptr);
89 return item != nameToItemMap.end() ? const_cast<RooAbsArg *>(item->second) : nullptr;
90 }
91
92 void replace(const RooAbsArg * out, const RooAbsArg * in) {
93 nameToItemMap.erase(out->namePtr());
94 nameToItemMap.emplace(in->namePtr(), in);
95 }
96
97 void insert(const RooAbsArg * elm) {
98 nameToItemMap.emplace(elm->namePtr(), elm);
99 }
100
101 void erase(const RooAbsArg * elm) {
102 nameToItemMap.erase(elm->namePtr());
103 }
104
105 std::unordered_map<const TNamed *, const RooAbsArg * const> nameToItemMap;
106 const std::size_t & currentRooNameRegCounter;
108};
109
110}
111}
112
113
114////////////////////////////////////////////////////////////////////////////////
115/// Default constructor
116
118{
119 _list.reserve(8);
120}
121
122
123
124////////////////////////////////////////////////////////////////////////////////
125/// Empty collection constructor
128 _name(name)
129{
130 _list.reserve(8);
132
133
134
135////////////////////////////////////////////////////////////////////////////////
136/// Copy constructor. Note that a copy of a collection is always non-owning,
137/// even the source collection is owning. To create an owning copy of
138/// a collection (owning or not), use the snapshot() method.
139
141 TObject(other),
142 RooPrintable(other),
143 _name(name),
144 _allRRV(other._allRRV)
145{
146 RooTrace::create(this) ;
147 if (!name) setName(other.GetName()) ;
148
149 _list.reserve(other._list.size());
150
151 for (auto item : other._list) {
152 insert(item);
153 }
154}
155
156
157////////////////////////////////////////////////////////////////////////////////
158/// Move constructor.
159
161 TObject(other),
162 RooPrintable(other),
163 _list(std::move(other._list)),
164 _ownCont(other._ownCont),
165 _name(std::move(other._name)),
166 _allRRV(other._allRRV),
167 _sizeThresholdForMapSearch(other._sizeThresholdForMapSearch)
168{
169}
170
171
172////////////////////////////////////////////////////////////////////////////////
173/// Destructor
174
176{
177 // Delete all variables in our list if we own them
178 if(_ownCont){
179 deleteList() ;
183 }
184 _hashAssistedFind = nullptr;
185}
186
187
188////////////////////////////////////////////////////////////////////////////////
189/// Delete contents of the list.
190/// The RooAbsArg destructor ensures clients and servers can be deleted in any
191/// order.
192/// Also cleans the hash-map for fast lookups if present.
193
195{
196 if (_hashAssistedFind) {
197 delete _hashAssistedFind;
198 }
199 _hashAssistedFind = nullptr;
200
201 // Built-in delete remaining elements
202 for (auto item : _list) {
203 delete item;
204 }
205 _list.clear();
206}
207
208
209
210////////////////////////////////////////////////////////////////////////////////
211/// Take a snap shot of current collection contents.
212/// An owning collection is returned containing clones of
213/// - Elements in this collection
214/// - External dependents of all elements and recursively any dependents of those dependents
215/// (if deepCopy flag is set)
216///
217/// This is useful to save the values of variables or parameters. It doesn't require
218/// deep copying if the parameters are direct members of the collection.
219///
220/// If deepCopy is specified, the client-server links between the cloned
221/// list elements and the cloned external dependents are reconnected to
222/// each other, making the snapshot a completely self-contained entity.
223///
224///
225
227{
228 // First create empty list
229 TString snapName ;
230 if (TString(GetName()).Length()>0) {
231 snapName.Append("Snapshot of ") ;
232 snapName.Append(GetName()) ;
233 }
234 auto* output = static_cast<RooAbsCollection*>(create(snapName.Data())) ;
235
236 if (snapshot(*output,deepCopy)) {
237 delete output ;
238 return nullptr ;
239 }
240
241 return output ;
242}
243
244
245
246////////////////////////////////////////////////////////////////////////////////
247/// Take a snap shot of current collection contents:
248/// A collection that owns its elements is returned containing clones of
249/// - Elements in this collection
250/// - External dependents of those elements
251/// and recursively any dependents of those dependents
252/// (if deepCopy flag is set)
253///
254/// If deepCopy is specified, the client-server links between the cloned
255/// list elements and the cloned external dependents are reconnected to
256/// each other, making the snapshot a completely self-contained entity.
257///
258///
259
261{
262 return RooHelpers::Detail::snapshotImpl(*this, output, deepCopy, nullptr);
263}
264
265
266////////////////////////////////////////////////////////////////////////////////
267/// Assign values from the elements in `other` to our elements.
268/// \warning This is not a conventional assignment operator. To avoid confusion, prefer using RooAbsCollection::assign().
269
271{
272 assign(other);
273 return *this;
274}
275
276
277////////////////////////////////////////////////////////////////////////////////
278/// Sets the value, cache and constant attribute of any argument in our set
279/// that also appears in the other set. Note that this function changes the
280/// values of the elements in this collection, but is still marked `const` as
281/// it does not change which elements this collection points to.
282
284{
285 if (&other==this) return ;
286
287 for (auto elem : _list) {
288 auto theirs = other.find(*elem);
289 if(!theirs) continue;
290 theirs->syncCache() ;
291 elem->copyCache(theirs) ;
292 elem->setAttribute("Constant",theirs->isConstant()) ;
293 }
294 return ;
295}
296
297
298////////////////////////////////////////////////////////////////////////////////
299/// Sets the value of any argument in our set that also appears in the other set.
300/// \param[in] other Collection holding the arguments to synchronize values with.
301/// \param[in] forceIfSizeOne If set to true and both our collection
302/// and the other collection have a size of one, the arguments are
303/// always synchronized without checking if they have the same name.
304
306{
307 if (&other==this) return *this;
308
309 // Short cut for 1 element assignment
310 if (size()==1 && size() == other.size() && forceIfSizeOne) {
311 other.first()->syncCache() ;
312 first()->copyCache(other.first(),true) ;
313 return *this;
314 }
315
316 for (auto elem : _list) {
317 auto theirs = other.find(*elem);
318 if(!theirs) continue;
319 theirs->syncCache() ;
320 elem->copyCache(theirs,true) ;
321 }
322 return *this;
323}
324
325
326
327////////////////////////////////////////////////////////////////////////////////
328/// Functional equivalent of assign() but assumes this and other collection
329/// have same layout. Also no attributes are copied
330
331void RooAbsCollection::assignFast(const RooAbsCollection& other, bool setValDirty) const
332{
333 if (&other==this) return ;
334 assert(hasSameLayout(other));
335
336 auto iter2 = other._list.begin();
337 for (auto iter1 = _list.begin();
338 iter1 != _list.end() && iter2 != other._list.end();
339 ++iter1, ++iter2) {
340 // Identical size of iterators is documented assumption of method
341
342 if (_allRRV) {
343 // All contents are known to be RooRealVars - fast version of assignment
344 auto ours = static_cast<RooRealVar*>(*iter1);
345 auto theirs = static_cast<RooRealVar*>(*iter2);
346 ours->copyCacheFast(*theirs,setValDirty);
347 } else {
348 (*iter2)->syncCache() ;
349 (*iter1)->copyCache(*iter2,true,setValDirty) ;
350 }
351 }
352
353}
354
355
356////////////////////////////////////////////////////////////////////////////////
357/// Add an argument and transfer the ownership to the collection. Returns `true`
358/// if successful, or `false` if the argument could not be added to the
359/// collection (e.g. in the RooArgSet case when an argument with the same name
360/// is already in the list). This method can only be called on a list that is
361/// flagged as owning all of its contents, or else on an empty list (which will
362/// force the list into that mode).
363///
364/// If the argument you want to add is owned by a `std::unique_ptr`, you should
365/// prefer RooAbsCollection::addOwned(std::unique_ptr<RooAbsArg>, bool).
366
368{
369 if(!canBeAdded(var, silent)) return false;
370
371 // check that we own our variables or else are empty
372 if(!_ownCont && !empty() && !silent) {
373 coutE(ObjectHandling) << ClassName() << "::" << GetName() << "::addOwned: can only add to an owned list" << std::endl;
374 return false;
375 }
376 _ownCont= true;
377
378 insert(&var);
379
380 return true;
381}
382
383
384////////////////////////////////////////////////////////////////////////////////
385/// Add an argument and transfer the ownership to the collection from a
386/// `std::unique_ptr`. Always returns `true`. If the argument can not be added
387/// to the collection (e.g. in the RooArgSet case when an argument with the
388/// same name is already in the list), a `std::runtime_exception` will be
389/// thrown, as nobody is owning the argument anymore. This method can only be
390/// called on a list that is flagged as owning all of its contents, or else on
391/// an empty list (which will force the list into that mode).
392///
393/// If you want to pass an argument that is not owned by a `std::unique_ptr`,
394/// you can use RooAbsCollection::addOwned(RooAbsArg&, bool).
395
396bool RooAbsCollection::addOwned(std::unique_ptr<RooAbsArg> var, bool silent) {
397 bool result = addOwned(*var.release(), silent);
398 if(!result) {
399 auto errMsg = std::string("RooAbsCollection::addOwned could not add the argument to the")
400 + " collection! The ownership would not be well defined if we ignore this.";
401 coutE(ObjectHandling) << errMsg << std::endl;
402 throw std::runtime_error(errMsg);
403 }
404 return result;
405}
406
407
408
409////////////////////////////////////////////////////////////////////////////////
410/// Add a clone of the specified argument to list. Returns a pointer to
411/// the clone if successful, or else zero if a variable of the same name
412/// is already in the list or the list does *not* own its variables (in
413/// this case, try add() instead.) Calling addClone() on an empty list
414/// forces it to take ownership of all its subsequent variables.
415
417{
418 if(!canBeAdded(var, silent)) return nullptr;
419
420 // check that we own our variables or else are empty
421 if(!_ownCont && !empty() && !silent) {
422 coutE(ObjectHandling) << ClassName() << "::" << GetName() << "::addClone: can only add to an owned list" << std::endl;
423 return nullptr;
424 }
425 _ownCont= true;
426
427 // add a pointer to a clone of this variable to our list (we now own it!)
428 auto clone2 = static_cast<RooAbsArg*>(var.Clone());
429 assert(clone2);
430
431 insert(clone2);
432
433 return clone2;
434}
435
436
437
438////////////////////////////////////////////////////////////////////////////////
439/// Add the specified argument to list. Returns true if successful, or
440/// else false if a variable of the same name is already in the list
441/// or the list owns its variables (in this case, try addClone() or addOwned() instead).
442
443bool RooAbsCollection::add(const RooAbsArg& var, bool silent)
444{
445 if(!canBeAdded(var, silent)) return false;
446
447 // check that this isn't a copy of a list
448 if(_ownCont && !silent) {
449 coutE(ObjectHandling) << ClassName() << "::" << GetName() << "::add: cannot add to an owned list" << std::endl;
450 return false;
451 }
452
453 // add a pointer to this variable to our list (we don't own it!)
454 insert(const_cast<RooAbsArg*>(&var)); //FIXME const_cast
455
456 return true;
457}
458
459
460////////////////////////////////////////////////////////////////////////////////
461// Add a collection of arguments to this collection by calling addOwned()
462/// for each element in the source collection. The input list can't be an
463/// owning collection itself, otherwise the arguments would be owned by two
464/// collections.
465///
466/// If you want to transfer arguments from one owning collection to another,
467/// you have two options:
468/// 1. `std::move` the input collection and use
469/// RooAbsCollection::addOwned(RooAbsCollection&&, bool) (preferred)
470/// 2. release the ownership of the input collection first, using
471/// RooAbsCollection::releaseOwnership()
472
473bool RooAbsCollection::addOwned(const RooAbsCollection& list, bool silent)
474{
475 if(list.isOwning()) {
476 throw std::invalid_argument("Passing an owning RooAbsCollection by const& to"
477 " RooAbsCollection::addOwned is forbidden because the ownership"
478 " would be ambiguous! Please std::move() the RooAbsCollection in this case."
479 " Note that the passed RooAbsCollection is invalid afterwards.");
480
481 }
482
483 bool result(false) ;
484 _list.reserve(_list.size() + list._list.size());
485
486 for (auto item : list._list) {
487 result |= addOwned(*item, silent) ;
488 }
489
490 return result;
491}
492
493
494////////////////////////////////////////////////////////////////////////////////
495/// Add a collection of arguments to this collection by calling addOwned()
496/// for each element in the source collection. Unlike
497/// RooAbsCollection::addOwned(const RooAbsCollection&, bool), this function
498/// also accepts owning source collections because their content will be
499/// moved out.
500
502{
503 if(list.isOwning()) {
504 list._ownCont = false;
505 }
506 if(list.empty()) return false;
507
508 bool result = addOwned(list, silent);
509
510 if(!result) {
511 auto errMsg = std::string("RooAbsCollection::addOwned could not add the argument to the")
512 + " collection! The ownership would not be well defined if we ignore this.";
513 coutE(ObjectHandling) << errMsg << std::endl;
514 throw std::runtime_error(errMsg);
515 }
516
517 // So far, comps has only released the ownership, but it is still valid.
518 // However, we don't want users to keep using objects after moving them, so
519 // we make sure to keep our promise that the RooArgSet is really moved.
520 // Just like a `std::unique_ptr` is also reset when moved.
521 list.clear();
522
523 return result;
524}
525
526
527////////////////////////////////////////////////////////////////////////////////
528/// Add a collection of arguments to this collection by calling addOwned()
529/// for each element in the source collection
530
531void RooAbsCollection::addClone(const RooAbsCollection& list, bool silent)
532{
533 _list.reserve(_list.size() + list._list.size());
534
535 for (auto item : list._list) {
536 addClone(*item, silent);
537 }
538}
539
540
541
542////////////////////////////////////////////////////////////////////////////////
543/// Replace any args in our set with args of the same name from the other set
544/// and return true for success. Fails if this list is a copy of another.
545
547{
548 // check that this isn't a copy of a list
549 if(_ownCont) {
550 std::stringstream errMsg;
551 errMsg << "RooAbsCollection: cannot replace variables in a copied list";
552 coutE(ObjectHandling) << errMsg.str() << std::endl;
553 // better than returning "false" and leaving the collection in a broken state:
554 throw std::invalid_argument(errMsg.str());
555 }
556
557 // loop over elements in the other list
558 for (const auto * arg : other._list) {
559 // do we have an arg of the same name in our set?
560 auto found = find(*arg);
561 if (found) replace(*found,*arg);
562 }
563 return true;
564}
565
566
568{
569 // is var1 already in this list?
570 const char *name= var1.GetName();
571 auto var1It = std::find(_list.begin(), _list.end(), &var1);
572
573 if (var1It == _list.end()) {
574 coutE(ObjectHandling) << "RooAbsCollection: variable \"" << name << "\" is not in the list"
575 << " and cannot be replaced" << std::endl;
576 return false;
577 }
578
579
580 // is var2's name already in this list?
581 if (dynamic_cast<RooArgSet*>(this)) {
582 RooAbsArg *other = find(var2);
583 if(other != nullptr && other != &var1) {
584 coutE(ObjectHandling) << "RooAbsCollection: cannot replace \"" << name
585 << "\" with already existing \"" << var2.GetName() << "\"" << std::endl;
586 return false;
587 }
588 }
589
590 // replace var1 with var2
591 if (_hashAssistedFind) {
592 _hashAssistedFind->replace(*var1It, &var2);
593 }
594 *var1It = const_cast<RooAbsArg*>(&var2); //FIXME try to get rid of const_cast
595
596 if (_allRRV && dynamic_cast<const RooRealVar*>(&var2) == nullptr) {
597 _allRRV=false ;
598 }
599
600 return true;
601}
602
603
604////////////////////////////////////////////////////////////////////////////////
605/// Replace var1 with var2 and return true for success. Fails if
606/// this list is a copy of another, if var1 is not already in this set,
607/// or if var2 is already in this set. var1 and var2 do not need to have
608/// the same name.
609
610bool RooAbsCollection::replace(const RooAbsArg &var1, const RooAbsArg &var2)
611{
612 // check that this isn't a copy of a list
613 if (_ownCont) {
614 std::string errMsg = "RooAbsCollection: cannot replace variables in a copied list";
615 coutE(ObjectHandling) << errMsg << std::endl;
616 throw std::runtime_error(errMsg);
617 }
618
619 return replaceImpl(var1, var2);
620}
621
622////////////////////////////////////////////////////////////////////////////////
623/// Replace var1 with var2 and return true for success. Fails if
624/// this list is a copy of another, if var1 is not already in this set,
625/// or if var2 is already in this set. var1 and var2 do not need to have
626/// the same name.
627
628bool RooAbsCollection::replace(RooAbsArg *var1, std::unique_ptr<RooAbsArg> var2)
629{
630 // To accept an owning var2, the collection must be owning.
631 if (!_ownCont) {
632 std::string errMsg =
633 "RooAbsCollection::replace(RooAbsArg *, std::unique_ptr<RooAbsArg>) can't be used on a non-owning collection!";
634 coutE(ObjectHandling) << errMsg << std::endl;
635 throw std::runtime_error(errMsg);
636 }
637
638 bool success = replaceImpl(*var1, *var2.release());
639 if (!success) {
640 auto errMsg = std::string("RooAbsCollection::replace(RooAbsArg *, std::unique_ptr<RooAbsArg>) did not succeed!") +
641 "The ownership would not be well defined if we ignore this.";
642 coutE(ObjectHandling) << errMsg << std::endl;
643 throw std::runtime_error(errMsg);
644 }
645 delete var1;
646 return success;
647}
648
649
650////////////////////////////////////////////////////////////////////////////////
651/// Remove the specified argument from our list. Return false if
652/// the specified argument is not found in our list. An exact pointer
653/// match is required, not just a match by name.
654/// If `matchByNameOnly` is set, items will be looked up by name. In this case, if
655/// the collection also owns the item, it will delete it.
656bool RooAbsCollection::remove(const RooAbsArg& var, bool , bool matchByNameOnly)
657{
658 // is var already in this list?
659 const auto sizeBefore = _list.size();
660
661 if (matchByNameOnly) {
662 const std::string name(var.GetName());
663 auto nameMatch = [&name](const RooAbsArg* elm) {
664 return elm->GetName() == name;
665 };
666 std::set<RooAbsArg*> toBeDeleted;
667
668 if (_ownCont) {
669 std::for_each(_list.begin(), _list.end(), [&toBeDeleted, nameMatch](RooAbsArg* elm){
670 if (nameMatch(elm)) {
671 toBeDeleted.insert(elm);
672 }
673 });
674 }
675
676 _list.erase(std::remove_if(_list.begin(), _list.end(), nameMatch), _list.end());
677
678 for (auto arg : toBeDeleted)
679 delete arg;
680 } else {
681 _list.erase(std::remove(_list.begin(), _list.end(), &var), _list.end());
682 }
683
684 if (_hashAssistedFind && sizeBefore != _list.size()) {
685 _hashAssistedFind->erase(&var);
686 }
687
688 return sizeBefore != _list.size();
689}
690
691
692
693////////////////////////////////////////////////////////////////////////////////
694/// Remove each argument in the input list from our list.
695/// An exact pointer match is required, not just a match by name.
696/// If `matchByNameOnly` is set, items will be looked up by name. In this case, if
697/// the collection also owns the items, it will delete them.
698/// Return false in case of problems.
699
700bool RooAbsCollection::remove(const RooAbsCollection& list, bool /*silent*/, bool matchByNameOnly)
701{
702
703 auto oldSize = _list.size();
704 std::vector<const RooAbsArg*> markedItems;
705
706 if (matchByNameOnly) {
707
708 // Instead of doing two passes on the list as in remove(RooAbsArg&), we do
709 // everything in one pass, by using side effects of the predicate.
710 auto nameMatchAndMark = [&list, &markedItems](const RooAbsArg* elm) {
711 if( list.contains(*elm) ) {
712 markedItems.push_back(elm);
713 return true;
714 }
715 return false;
716 };
717
718 _list.erase(std::remove_if(_list.begin(), _list.end(), nameMatchAndMark), _list.end());
719
720 }
721 else {
722 auto argMatchAndMark = [&list, &markedItems](const RooAbsArg* elm) {
723 if( list.containsInstance(*elm) ) {
724 markedItems.push_back(elm);
725 return true;
726 }
727 return false;
728 };
729
730 _list.erase(std::remove_if(_list.begin(), _list.end(), argMatchAndMark), _list.end());
731 }
732
733 if (_hashAssistedFind && oldSize != _list.size()) {
734 for( auto& var : markedItems ) {
736 }
737 }
738
739 if (matchByNameOnly && _ownCont) {
740 std::set<const RooAbsArg*> toBeDeleted(markedItems.begin(), markedItems.end());
741 for (auto arg : toBeDeleted) {
742 delete arg;
743 }
744 }
745
746 return oldSize != _list.size();
747}
748
749
750
751////////////////////////////////////////////////////////////////////////////////
752/// Remove all arguments from our set, deleting them if we own them.
753/// This effectively restores our object to the state it would have
754/// just after calling the RooAbsCollection(const char*) constructor.
755
757{
758 if (_hashAssistedFind) {
759 delete _hashAssistedFind;
760 }
761 _hashAssistedFind = nullptr;
762
763 if(_ownCont) {
764 deleteList() ;
765 _ownCont= false;
766 }
767 else {
768 _list.clear();
769 }
770}
771
772
773
774////////////////////////////////////////////////////////////////////////////////
775/// Set given attribute in each element of the collection by
776/// calling each elements setAttribute() function.
777
779{
780 for (auto arg : _list) {
781 arg->setAttribute(name, value);
782 }
783}
784
785
786
787
788////////////////////////////////////////////////////////////////////////////////
789/// Create a subset of the current collection, consisting only of those
790/// elements with the specified attribute set. The caller is responsible
791/// for deleting the returned collection
792
794{
795 TString selName(GetName()) ;
796 selName.Append("_selection") ;
797 RooAbsCollection *sel = static_cast<RooAbsCollection*>(create(selName.Data())) ;
798
799 // Scan set contents for matching attribute
800 for (auto arg : _list) {
801 if (arg->getAttribute(name)==value)
802 sel->add(*arg) ;
803 }
804
805 return sel ;
806}
807
808
809////////////////////////////////////////////////////////////////////////////////
810/// Create a subset of the current collection, consisting only of those
811/// elements that are contained as well in the given reference collection.
812/// Returns `true` only if something went wrong.
813/// The complement of this function is getParameters().
814/// \param[in] refColl The collection to check for common elements.
815/// \param[out] outColl Output collection.
816
818{
819 outColl.clear();
820 outColl.setName((std::string(GetName()) + "_selection").c_str());
821
822 // Scan set contents for matching attribute
823 for (auto arg : _list) {
824 if (refColl.find(*arg))
825 outColl.add(*arg) ;
826 }
827
828 return false;
829}
830
831
832////////////////////////////////////////////////////////////////////////////////
833/// Create a subset of the current collection, consisting only of those
834/// elements that are contained as well in the given reference collection.
835/// The caller is responsible for deleting the returned collection
836
838{
839 auto sel = static_cast<RooAbsCollection*>(create("")) ;
840 selectCommon(refColl, *sel);
841 return sel ;
842}
843
844
845////////////////////////////////////////////////////////////////////////////////
846/// Create a subset of the current collection, consisting only of those
847/// elements with names matching the wildcard expressions in nameList,
848/// supplied as a comma separated list
849
850RooAbsCollection* RooAbsCollection::selectByName(const char* nameList, bool verbose) const
851{
852 // Create output set
853 TString selName(GetName()) ;
854 selName.Append("_selection") ;
855 RooAbsCollection *sel = static_cast<RooAbsCollection*>(create(selName.Data())) ;
856
857 const size_t bufSize = strlen(nameList) + 1;
858 std::vector<char> buf(bufSize);
859 strlcpy(buf.data(),nameList,bufSize) ;
860 char* wcExpr = strtok(buf.data(),",") ;
861 while(wcExpr) {
862 TRegexp rexp(wcExpr,true) ;
863 if (verbose) {
864 cxcoutD(ObjectHandling) << "RooAbsCollection::selectByName(" << GetName() << ") processing expression '" << wcExpr << "'" << std::endl;
865 }
866
867 for (auto const* arg : *this) {
868 if (TString(arg->GetName()).Index(rexp)>=0) {
869 if (verbose) {
870 cxcoutD(ObjectHandling) << "RooAbsCollection::selectByName(" << GetName() << ") selected element " << arg->GetName() << std::endl;
871 }
872 sel->add(*arg) ;
873 }
874 }
875 wcExpr = strtok(nullptr,",") ;
876 }
877
878 return sel ;
879}
880
881
882
883
884////////////////////////////////////////////////////////////////////////////////
885/// Check if this and other collection have identically-named contents
886
887bool RooAbsCollection::equals(const RooAbsCollection& otherColl) const
888{
889 // First check equal length
890 if (size() != otherColl.size()) return false ;
891
892 // Then check that each element of our list also occurs in the other list
893 auto compareByNamePtr = [](const RooAbsArg * left, const RooAbsArg * right) {
894 return left->namePtr() == right->namePtr();
895 };
896
897 return std::is_permutation(_list.begin(), _list.end(),
898 otherColl._list.begin(),
899 compareByNamePtr);
900}
901
902
903namespace {
904////////////////////////////////////////////////////////////////////////////////
905/// Linear search through list of stored objects.
906template<class Collection_t>
907RooAbsArg* findUsingNamePointer(const Collection_t& coll, const TNamed* ptr) {
908 auto findByNamePtr = [ptr](const RooAbsArg* elm) {
909 return ptr == elm->namePtr();
910 };
911
912 auto item = std::find_if(coll.begin(), coll.end(), findByNamePtr);
913
914 return item != coll.end() ? *item : nullptr;
915}
916}
917
918
919////////////////////////////////////////////////////////////////////////////////
920/// Find object with given name in list. A null pointer
921/// is returned if no object with the given name is found.
923{
924 if (!name)
925 return nullptr;
926
927 // If an object with such a name exists, its name has been registered.
928 const TNamed* nptr = RooNameReg::known(name);
929 if (!nptr) return nullptr;
930
933 _hashAssistedFind = new HashAssistedFind{_list.begin(), _list.end()};
934 }
935
936 return _hashAssistedFind->find(nptr);
937 }
938
939 return findUsingNamePointer(_list, nptr);
940}
941
942
943
944////////////////////////////////////////////////////////////////////////////////
945/// Find object with given name in list. A null pointer
946/// is returned if no object with the given name is found.
948{
949 const auto nptr = arg.namePtr();
950
953 _hashAssistedFind = new HashAssistedFind{_list.begin(), _list.end()};
954 }
955
956 return _hashAssistedFind->find(nptr);
957 }
958
959 return findUsingNamePointer(_list, nptr);
960}
961
962
963////////////////////////////////////////////////////////////////////////////////
964/// Return index of item with given name, or -1 in case it's not in the collection.
966 const std::string theName(name);
967 auto item = std::find_if(_list.begin(), _list.end(), [&theName](const RooAbsArg * elm){
968 return elm->GetName() == theName;
969 });
970 return item != _list.end() ? item - _list.begin() : -1;
971}
972
973
974////////////////////////////////////////////////////////////////////////////////
975/// Get value of a RooAbsReal stored in set with given name. If none is found, value of defVal is returned.
976/// No error messages are printed unless the verbose flag is set
977
978double RooAbsCollection::getRealValue(const char* name, double defVal, bool verbose) const
979{
980 RooAbsArg* raa = find(name) ;
981 if (!raa) {
982 if (verbose) coutE(InputArguments) << "RooAbsCollection::getRealValue(" << GetName() << ") ERROR no object with name '" << name << "' found" << std::endl;
983 return defVal ;
984 }
985 RooAbsReal* rar = dynamic_cast<RooAbsReal*>(raa) ;
986 if (!rar) {
987 if (verbose) coutE(InputArguments) << "RooAbsCollection::getRealValue(" << GetName() << ") ERROR object '" << name << "' is not of type RooAbsReal" << std::endl;
988 return defVal ;
989 }
990 return rar->getVal() ;
991}
992
993
994
995////////////////////////////////////////////////////////////////////////////////
996/// Set value of a RooAbsRealLValue stored in set with given name to newVal
997/// No error messages are printed unless the verbose flag is set
998
999bool RooAbsCollection::setRealValue(const char* name, double newVal, bool verbose)
1000{
1001 RooAbsArg* raa = find(name) ;
1002 if (!raa) {
1003 if (verbose) coutE(InputArguments) << "RooAbsCollection::setRealValue(" << GetName() << ") ERROR no object with name '" << name << "' found" << std::endl;
1004 return true ;
1005 }
1006 auto* rar = dynamic_cast<RooAbsRealLValue*>(raa) ;
1007 if (!rar) {
1008 if (verbose) coutE(InputArguments) << "RooAbsCollection::setRealValue(" << GetName() << ") ERROR object '" << name << "' is not of type RooAbsRealLValue" << std::endl;
1009 return true;
1010 }
1011 rar->setVal(newVal) ;
1012 return false ;
1013}
1014
1015
1016
1017////////////////////////////////////////////////////////////////////////////////
1018/// Get state name of a RooAbsCategory stored in set with given name. If none is found, value of defVal is returned.
1019/// No error messages are printed unless the verbose flag is set
1020
1021const char* RooAbsCollection::getCatLabel(const char* name, const char* defVal, bool verbose) const
1022{
1023 RooAbsArg* raa = find(name) ;
1024 if (!raa) {
1025 if (verbose) coutE(InputArguments) << "RooAbsCollection::getCatLabel(" << GetName() << ") ERROR no object with name '" << name << "' found" << std::endl;
1026 return defVal ;
1027 }
1028 auto* rac = dynamic_cast<RooAbsCategory*>(raa) ;
1029 if (!rac) {
1030 if (verbose) coutE(InputArguments) << "RooAbsCollection::getCatLabel(" << GetName() << ") ERROR object '" << name << "' is not of type RooAbsCategory" << std::endl;
1031 return defVal ;
1032 }
1033 return rac->getCurrentLabel() ;
1034}
1035
1036
1037
1038////////////////////////////////////////////////////////////////////////////////
1039/// Set state name of a RooAbsCategoryLValue stored in set with given name to newVal.
1040/// No error messages are printed unless the verbose flag is set
1041
1042bool RooAbsCollection::setCatLabel(const char* name, const char* newVal, bool verbose)
1043{
1044 RooAbsArg* raa = find(name) ;
1045 if (!raa) {
1046 if (verbose) coutE(InputArguments) << "RooAbsCollection::setCatLabel(" << GetName() << ") ERROR no object with name '" << name << "' found" << std::endl;
1047 return true ;
1048 }
1049 auto* rac = dynamic_cast<RooAbsCategoryLValue*>(raa) ;
1050 if (!rac) {
1051 if (verbose) coutE(InputArguments) << "RooAbsCollection::setCatLabel(" << GetName() << ") ERROR object '" << name << "' is not of type RooAbsCategory" << std::endl;
1052 return true ;
1053 }
1054 rac->setLabel(newVal) ;
1055 return false ;
1056}
1057
1058
1059
1060////////////////////////////////////////////////////////////////////////////////
1061/// Get index value of a RooAbsCategory stored in set with given name. If none is found, value of defVal is returned.
1062/// No error messages are printed unless the verbose flag is set
1063
1064Int_t RooAbsCollection::getCatIndex(const char* name, Int_t defVal, bool verbose) const
1065{
1066 RooAbsArg* raa = find(name) ;
1067 if (!raa) {
1068 if (verbose) coutE(InputArguments) << "RooAbsCollection::getCatLabel(" << GetName() << ") ERROR no object with name '" << name << "' found" << std::endl;
1069 return defVal ;
1070 }
1071 auto* rac = dynamic_cast<RooAbsCategory*>(raa) ;
1072 if (!rac) {
1073 if (verbose) coutE(InputArguments) << "RooAbsCollection::getCatLabel(" << GetName() << ") ERROR object '" << name << "' is not of type RooAbsCategory" << std::endl;
1074 return defVal ;
1075 }
1076 return rac->getCurrentIndex() ;
1077}
1078
1079
1080
1081////////////////////////////////////////////////////////////////////////////////
1082/// Set index value of a RooAbsCategoryLValue stored in set with given name to newVal.
1083/// No error messages are printed unless the verbose flag is set
1084
1085bool RooAbsCollection::setCatIndex(const char* name, Int_t newVal, bool verbose)
1086{
1087 RooAbsArg* raa = find(name) ;
1088 if (!raa) {
1089 if (verbose) coutE(InputArguments) << "RooAbsCollection::setCatLabel(" << GetName() << ") ERROR no object with name '" << name << "' found" << std::endl;
1090 return true ;
1091 }
1092 auto* rac = dynamic_cast<RooAbsCategoryLValue*>(raa) ;
1093 if (!rac) {
1094 if (verbose) coutE(InputArguments) << "RooAbsCollection::setCatLabel(" << GetName() << ") ERROR object '" << name << "' is not of type RooAbsCategory" << std::endl;
1095 return true ;
1096 }
1097 rac->setIndex(newVal) ;
1098 return false ;
1099}
1100
1101
1102
1103////////////////////////////////////////////////////////////////////////////////
1104/// Get string value of a RooStringVar stored in set with given name. If none is found, value of defVal is returned.
1105/// No error messages are printed unless the verbose flag is set
1106
1107const char* RooAbsCollection::getStringValue(const char* name, const char* defVal, bool verbose) const
1108{
1109 RooAbsArg* raa = find(name) ;
1110 if (!raa) {
1111 if (verbose) coutE(InputArguments) << "RooAbsCollection::getStringValue(" << GetName() << ") ERROR no object with name '" << name << "' found" << std::endl;
1112 return defVal ;
1113 }
1114 auto ras = dynamic_cast<const RooStringVar*>(raa) ;
1115 if (!ras) {
1116 if (verbose) coutE(InputArguments) << "RooAbsCollection::getStringValue(" << GetName() << ") ERROR object '" << name << "' is not of type RooStringVar" << std::endl;
1117 return defVal ;
1118 }
1119
1120 return ras->getVal() ;
1121}
1122
1123
1124
1125////////////////////////////////////////////////////////////////////////////////
1126/// Set string value of a RooStringVar stored in set with given name to newVal.
1127/// No error messages are printed unless the verbose flag is set
1128
1129bool RooAbsCollection::setStringValue(const char* name, const char* newVal, bool verbose)
1130{
1131 RooAbsArg* raa = find(name) ;
1132 if (!raa) {
1133 if (verbose) coutE(InputArguments) << "RooAbsCollection::setStringValue(" << GetName() << ") ERROR no object with name '" << name << "' found" << std::endl;
1134 return true ;
1135 }
1136 auto ras = dynamic_cast<RooStringVar*>(raa);
1137 if (!ras) {
1138 if (verbose) coutE(InputArguments) << "RooAbsCollection::setStringValue(" << GetName() << ") ERROR object '" << name << "' is not of type RooStringVar" << std::endl;
1139 return true ;
1140 }
1141 ras->setVal(newVal);
1142
1143 return false;
1144}
1145
1146////////////////////////////////////////////////////////////////////////////////
1147/// Return comma separated list of contained object names as STL string
1149{
1150 std::string retVal ;
1151 for (auto arg : _list) {
1152 retVal += arg->GetName();
1153 retVal += ",";
1154 }
1155
1156 retVal.erase(retVal.end()-1);
1157
1158 return retVal;
1159}
1160
1161
1162
1163////////////////////////////////////////////////////////////////////////////////
1164/// Return collection name
1165
1166void RooAbsCollection::printName(std::ostream& os) const
1167{
1168 os << GetName() ;
1169}
1170
1171
1172
1173////////////////////////////////////////////////////////////////////////////////
1174/// Return collection title
1175
1176void RooAbsCollection::printTitle(std::ostream& os) const
1177{
1178 os << GetTitle() ;
1179}
1180
1181
1182
1183////////////////////////////////////////////////////////////////////////////////
1184/// Return collection class name
1185
1186void RooAbsCollection::printClassName(std::ostream& os) const
1187{
1188 os << ClassName() ;
1189}
1190
1191
1192
1193////////////////////////////////////////////////////////////////////////////////
1194/// Define default RooPrinable print options for given Print() flag string
1195/// For inline printing only show value of objects, for default print show
1196/// name,class name value and extras of each object. In verbose mode
1197/// also add object address, argument and title
1198
1200{
1201 if (opt && TString(opt)=="I") {
1202 return kValue ;
1203 }
1204 if (opt && TString(opt).Contains("v")) {
1206 }
1207 return kName|kClassName|kValue ;
1208}
1209
1210
1211
1212
1213
1214////////////////////////////////////////////////////////////////////////////////
1215/// Print value of collection, i.e. a comma separated list of contained
1216/// object names
1217
1218void RooAbsCollection::printValue(std::ostream& os) const
1219{
1220 bool first2(true) ;
1221 os << "(" ;
1222 for (auto arg : _list) {
1223 if (!first2) {
1224 os << "," ;
1225 } else {
1226 first2 = false ;
1227 }
1228 if (arg->IsA()->InheritsFrom(RooStringVar::Class())) {
1229 os << '\'' << (static_cast<RooStringVar *>(arg))->getVal() << '\'';
1230 } else {
1231 os << arg->GetName();
1232 }
1233 }
1234 os << ")" ;
1235}
1236
1237
1238
1239////////////////////////////////////////////////////////////////////////////////
1240/// Implement multiline printing of collection, one line for each contained object showing
1241/// the requested content
1242
1243void RooAbsCollection::printMultiline(std::ostream&os, Int_t contents, bool /*verbose*/, TString indent) const
1244{
1245 if (TString(GetName()).Length()>0 && (contents&kCollectionHeader)) {
1246 os << indent << ClassName() << "::" << GetName() << ":" << (_ownCont?" (Owning contents)":"") << std::endl;
1247 }
1248
1249 TString deeper(indent);
1250 deeper.Append(" ");
1251
1252 // Adjust the width of the name field to fit the largest name, if requested
1253 Int_t maxNameLen(1) ;
1254 Int_t nameFieldLengthSaved = RooPrintable::_nameLength ;
1255 if (nameFieldLengthSaved==0) {
1256 for (auto next : _list) {
1257 Int_t len = strlen(next->GetName()) ;
1258 if (len>maxNameLen) maxNameLen = len ;
1259 }
1260 RooPrintable::nameFieldLength(maxNameLen+1) ;
1261 }
1262
1263 unsigned int idx = 0;
1264 for (auto next : _list) {
1265 os << indent << std::setw(3) << ++idx << ") ";
1266 next->printStream(os,contents,kSingleLine,"");
1267 }
1268
1269 // Reset name field length, if modified
1270 RooPrintable::nameFieldLength(nameFieldLengthSaved) ;
1271}
1272
1273
1274
1275////////////////////////////////////////////////////////////////////////////////
1276/// Base contents dumper for debugging purposes
1277
1279{
1280 for (auto arg : _list) {
1281 std::cout << arg << " " << arg->ClassName() << "::" << arg->GetName() << " (" << arg->GetTitle() << ")" << std::endl ;
1282 }
1283}
1284
1285
1286
1287////////////////////////////////////////////////////////////////////////////////
1288/// Output content of collection as LaTex table. By default a table with two columns is created: the left
1289/// column contains the name of each variable, the right column the value.
1290///
1291/// The following optional named arguments can be used to modify the default behavior
1292/// <table>
1293/// <tr><th> Argument <th> Effect
1294/// <tr><td> `Columns(Int_t ncol)` <td> Fold table into multiple columns, i.e. ncol=3 will result in 3 x 2 = 6 total columns
1295/// <tr><td> `Sibling(const RooAbsCollection& other)` <td> Define sibling list.
1296/// The sibling list is assumed to have objects with the same
1297/// name in the same order. If this is not the case warnings will be printed. If a single
1298/// sibling list is specified, 3 columns will be output: the (common) name, the value of this
1299/// list and the value in the sibling list. Multiple sibling lists can be specified by
1300/// repeating the Sibling() command.
1301/// <tr><td> `Format(const char* str)` <td> Classic format string, provided for backward compatibility
1302/// <tr><td> `Format()` <td> Formatting arguments.
1303/// <table>
1304/// <tr><td> const char* what <td> Controls what is shown. "N" adds name, "E" adds error,
1305/// "A" shows asymmetric error, "U" shows unit, "H" hides the value
1306/// <tr><td> `FixedPrecision(int n)` <td> Controls precision, set fixed number of digits
1307/// <tr><td> `AutoPrecision(int n)` <td> Controls precision. Number of shown digits is calculated from error
1308/// and n specified additional digits (1 is sensible default)
1309/// <tr><td> `VerbatimName(bool flag)` <td> Put variable name in a \\verb+ + clause.
1310/// </table>
1311/// <tr><td> `OutputFile(const char* fname)` <td> Send output to file with given name rather than standard output
1312///
1313/// </table>
1314///
1315/// Example use:
1316/// ```
1317/// list.printLatex(Columns(2), Format("NEU",AutoPrecision(1),VerbatimName()) );
1318/// ```
1319
1321 const RooCmdArg& arg3, const RooCmdArg& arg4,
1322 const RooCmdArg& arg5, const RooCmdArg& arg6,
1323 const RooCmdArg& arg7, const RooCmdArg& arg8) const
1324{
1325
1326
1327 // Define configuration for this method
1328 RooCmdConfig pc("RooAbsCollection::printLatex()") ;
1329 pc.defineInt("ncol","Columns",0,1) ;
1330 pc.defineString("outputFile","OutputFile",0,"") ;
1331 pc.defineString("format","Format",0,"NEYVU") ;
1332 pc.defineInt("sigDigit","Format",0,1) ;
1333 pc.defineObject("siblings","Sibling",0,nullptr,true) ;
1334 pc.defineInt("dummy","FormatArgs",0,0) ;
1335 pc.defineMutex("Format","FormatArgs") ;
1336
1337 // Stuff all arguments in a list
1338 RooLinkedList cmdList;
1339 cmdList.Add(const_cast<RooCmdArg*>(&arg1)) ; cmdList.Add(const_cast<RooCmdArg*>(&arg2)) ;
1340 cmdList.Add(const_cast<RooCmdArg*>(&arg3)) ; cmdList.Add(const_cast<RooCmdArg*>(&arg4)) ;
1341 cmdList.Add(const_cast<RooCmdArg*>(&arg5)) ; cmdList.Add(const_cast<RooCmdArg*>(&arg6)) ;
1342 cmdList.Add(const_cast<RooCmdArg*>(&arg7)) ; cmdList.Add(const_cast<RooCmdArg*>(&arg8)) ;
1343
1344 // Process & check varargs
1345 pc.process(arg1,arg2,arg3,arg4,arg5,arg6,arg7,arg8) ;
1346 if (!pc.ok(true)) {
1347 return ;
1348 }
1349
1350 const char* outFile = pc.getString("outputFile") ;
1351 if (outFile && strlen(outFile)) {
1352 std::ofstream ofs(outFile) ;
1353 if (pc.hasProcessed("FormatArgs")) {
1354 auto* formatCmd = static_cast<RooCmdArg*>(cmdList.FindObject("FormatArgs")) ;
1355 formatCmd->addArg(RooFit::LatexTableStyle()) ;
1356 printLatex(ofs,pc.getInt("ncol"),nullptr,0,pc.getObjectList("siblings"),formatCmd) ;
1357 } else {
1358 printLatex(ofs,pc.getInt("ncol"),pc.getString("format"),pc.getInt("sigDigit"),pc.getObjectList("siblings")) ;
1359 }
1360 } else {
1361 if (pc.hasProcessed("FormatArgs")) {
1362 auto* formatCmd = static_cast<RooCmdArg*>(cmdList.FindObject("FormatArgs")) ;
1363 formatCmd->addArg(RooFit::LatexTableStyle()) ;
1364 printLatex(std::cout,pc.getInt("ncol"),nullptr,0,pc.getObjectList("siblings"),formatCmd) ;
1365 } else {
1366 printLatex(std::cout,pc.getInt("ncol"),pc.getString("format"),pc.getInt("sigDigit"),pc.getObjectList("siblings")) ;
1367 }
1368 }
1369}
1370
1371
1372
1373
1374////////////////////////////////////////////////////////////////////////////////
1375/// Internal implementation function of printLatex
1376
1377void RooAbsCollection::printLatex(std::ostream& ofs, Int_t ncol, const char* option, Int_t sigDigit, const RooLinkedList& siblingList, const RooCmdArg* formatCmd) const
1378{
1379 // Count number of rows to print
1380 Int_t nrow = (Int_t) (size() / ncol + 0.99) ;
1381 Int_t i;
1382 Int_t j;
1383 Int_t k;
1384
1385 // Sibling list do not need to print their name as it is supposed to be the same
1386 TString sibOption ;
1387 RooCmdArg sibFormatCmd ;
1388 if (option) {
1389 sibOption = option ;
1390 sibOption.ReplaceAll("N","") ;
1391 sibOption.ReplaceAll("n","") ;
1392 } else {
1393 sibFormatCmd = *formatCmd ;
1394 TString tmp = formatCmd->getString(0) ;
1395 tmp.ReplaceAll("N","") ;
1396 tmp.ReplaceAll("n","") ;
1397 static char buf[100] ;
1398 strlcpy(buf,tmp.Data(),100) ;
1399 sibFormatCmd.setString(0, buf);
1400 }
1401
1402
1403 // Make list of lists ;
1404 RooLinkedList listList ;
1405 listList.Add(const_cast<RooAbsCollection *>(this));
1406 for(auto * col : static_range_cast<RooAbsCollection*>(siblingList)) {
1407 listList.Add(col) ;
1408 }
1409
1410 RooLinkedList listListRRV ;
1411
1412 // Make list of RRV-only components
1413 RooArgList* prevList = nullptr ;
1414 for(auto * col : static_range_cast<RooAbsCollection*>(listList)) {
1415 RooArgList* list = new RooArgList ;
1416 for (auto* arg : *col) {
1417 auto* rrv = dynamic_cast<RooRealVar*>(arg) ;
1418 if (rrv) {
1419 list->add(*rrv) ;
1420 } else {
1421 coutW(InputArguments) << "RooAbsCollection::printLatex: can only print RooRealVar in LateX, skipping non-RooRealVar object named "
1422 << arg->GetName() << std::endl;
1423 }
1424 if (prevList && TString(rrv->GetName()).CompareTo(prevList->at(list->size()-1)->GetName())) {
1425 coutW(InputArguments) << "RooAbsCollection::printLatex: WARNING: naming and/or ordering of sibling list is different" << std::endl;
1426 }
1427 }
1428 listListRRV.Add(list) ;
1429 if (prevList && list->size() != prevList->size()) {
1430 coutW(InputArguments) << "RooAbsCollection::printLatex: ERROR: sibling list(s) must have same length as self" << std::endl;
1431 delete list ;
1432 listListRRV.Delete() ;
1433 return ;
1434 }
1435 prevList = list ;
1436 }
1437
1438 // Construct table header
1439 Int_t nlist = listListRRV.GetSize() ;
1440 TString subheader = "l" ;
1441 for (k=0 ; k<nlist ; k++) subheader += "c" ;
1442
1443 TString header = "\\begin{tabular}{" ;
1444 for (j=0 ; j<ncol ; j++) {
1445 if (j>0) header += "|" ;
1446 header += subheader ;
1447 }
1448 header += "}" ;
1449 ofs << header << std::endl;
1450
1451
1452 // Print contents, delegating actual printing to RooRealVar::format()
1453 for (i=0 ; i<nrow ; i++) {
1454 for (j=0 ; j<ncol ; j++) {
1455 for (k=0 ; k<nlist ; k++) {
1456 RooRealVar* par = static_cast<RooRealVar*>((static_cast<RooArgList*>(listListRRV.At(k)))->at(i+j*nrow)) ;
1457 if (par) {
1458 if (option) {
1459 ofs << *std::unique_ptr<TString>{par->format(sigDigit,(k==0)?option:sibOption.Data())};
1460 } else {
1461 ofs << *std::unique_ptr<TString>{par->format((k==0)?*formatCmd:sibFormatCmd)};
1462 }
1463 }
1464 if (!(j==ncol-1 && k==nlist-1)) {
1465 ofs << " & " ;
1466 }
1467 }
1468 }
1469 ofs << "\\\\" << std::endl;
1470 }
1471
1472 ofs << "\\end{tabular}" << std::endl;
1473 listListRRV.Delete() ;
1474}
1475
1476
1477
1478
1479////////////////////////////////////////////////////////////////////////////////
1480/// Return true if all contained object report to have their
1481/// value inside the specified range
1482
1483bool RooAbsCollection::allInRange(const char* rangeSpec) const
1484{
1485 if (!rangeSpec) return true ;
1486
1487 // Parse rangeSpec specification
1488 std::vector<std::string> cutVec ;
1489 if (rangeSpec && strlen(rangeSpec)>0) {
1490 if (strchr(rangeSpec,',')==nullptr) {
1491 cutVec.push_back(rangeSpec) ;
1492 } else {
1493 const size_t bufSize = strlen(rangeSpec)+1;
1494 std::vector<char> buf(bufSize);
1495 strlcpy(buf.data(),rangeSpec,bufSize) ;
1496 const char* oneRange = strtok(buf.data(),",") ;
1497 while(oneRange) {
1498 cutVec.push_back(oneRange) ;
1499 oneRange = strtok(nullptr,",") ;
1500 }
1501 }
1502 }
1503
1504 // Apply range based selection criteria
1505 bool selectByRange = true ;
1506 for (auto arg : _list) {
1507 bool selectThisArg = false ;
1508 UInt_t icut ;
1509 for (icut=0 ; icut<cutVec.size() ; icut++) {
1510 if (arg->inRange(cutVec[icut].c_str())) {
1511 selectThisArg = true ;
1512 break ;
1513 }
1514 }
1515 if (!selectThisArg) {
1516 selectByRange = false ;
1517 break ;
1518 }
1519 }
1520
1521 return selectByRange ;
1522}
1523
1524////////////////////////////////////////////////////////////////////////////////
1525/// If one of the TObject we have a referenced to is deleted, remove the
1526/// reference.
1527
1529{
1530 if (obj && obj->InheritsFrom(RooAbsArg::Class())) remove(*static_cast<RooAbsArg*>(obj),false,false);
1531}
1532
1533////////////////////////////////////////////////////////////////////////////////
1534/// Sort collection using std::sort and name comparison
1535
1536void RooAbsCollection::sort(bool reverse) {
1537 //Windows seems to need an implementation where two different std::sorts are written
1538 //down in two different blocks. Switching between the two comparators using a ternary
1539 //operator does not compile on windows, although the signature is identical.
1540 if (reverse) {
1541 const auto cmpReverse = [](const RooAbsArg * l, const RooAbsArg * r) {
1542 return strcmp(l->GetName(), r->GetName()) > 0;
1543 };
1544
1545 std::sort(_list.begin(), _list.end(), cmpReverse);
1546 }
1547 else {
1548 const auto cmp = [](const RooAbsArg * l, const RooAbsArg * r) {
1549 return strcmp(l->GetName(), r->GetName()) < 0;
1550 };
1551
1552 std::sort(_list.begin(), _list.end(), cmp);
1553 }
1554}
1555
1556////////////////////////////////////////////////////////////////////////////////
1557/// Sort collection topologically: the servers of any RooAbsArg will be before
1558/// that RooAbsArg in the collection.
1559
1561 std::unordered_set<TNamed const *> seenArgs;
1562 for (std::size_t iArg = 0; iArg < _list.size(); ++iArg) {
1563 RooAbsArg *arg = _list[iArg];
1564 bool movedArg = false;
1565 for (RooAbsArg *server : arg->servers()) {
1566 if (seenArgs.find(server->namePtr()) == seenArgs.end()) {
1567 auto found = std::find_if(_list.begin(), _list.end(),
1568 [server](RooAbsArg *elem) { return elem->namePtr() == server->namePtr(); });
1569 if (found != _list.end()) {
1570 _list.erase(found);
1571 _list.insert(_list.begin() + iArg, server);
1572 movedArg = true;
1573 break;
1574 }
1575 }
1576 }
1577 if (movedArg) {
1578 --iArg;
1579 continue;
1580 }
1581 seenArgs.insert(arg->namePtr());
1582 }
1583}
1584
1585////////////////////////////////////////////////////////////////////////////////
1586/// Insert an element into the owned collections.
1588 _list.push_back(item);
1589
1590 if (_allRRV && dynamic_cast<const RooRealVar*>(item)==nullptr) {
1591 _allRRV= false;
1592 }
1593
1594 if (_hashAssistedFind) {
1596 }
1597}
1598
1599
1600////////////////////////////////////////////////////////////////////////////////
1601/// \param[in] flag Switch hash map on or off.
1603{
1604// Use a ROOT version macro for behavior-changing code in ROOT 6.33, so se can
1605// keep the same RooFit code base in master and in the 6.32 patch release
1606// branch for now.
1607#if ROOT_VERSION_CODE >= ROOT_VERSION(6, 33, 00)
1608 if (flag && !dynamic_cast<RooArgSet const *>(this)) {
1609 // RooArgLists can have duplicate object, so we can't do hash-assisted lookups.
1610 std::stringstream msg;
1611 msg << "RooAbsCollection::useHashMapForFind() ERROR: this collection is not a RooArgSet but a RooArgList, so "
1612 "hash-assisted finding can't be enabled!"
1613 << std::endl;
1614 oocoutE(nullptr, ObjectHandling) << msg.str() << std::endl;
1615 throw std::runtime_error(msg.str());
1616 }
1617#endif
1618 if (flag && !_hashAssistedFind) {
1619 _hashAssistedFind = new HashAssistedFind{_list.begin(), _list.end()};
1620 }
1621 if (!flag && _hashAssistedFind) {
1622 delete _hashAssistedFind;
1623 _hashAssistedFind = nullptr;
1624 }
1625}
1626
1627
1628////////////////////////////////////////////////////////////////////////////////
1629/// Check that all entries where the collections overlap have the same name.
1631 for (unsigned int i=0; i < std::min(_list.size(), other.size()); ++i) {
1632 if (_list[i]->namePtr() != other._list[i]->namePtr())
1633 return false;
1634 }
1635
1636 return true;
1637}
1638
1640{
1641 std::string typeName = klass->GetName();
1642 std::stringstream msg;
1643 msg << "RooAbsCollection::addTyped<" << typeName << ">() ERROR: component " << arg->GetName() << " is not of type "
1644 << typeName;
1645 oocoutE(nullptr, InputArguments) << msg.str() << std::endl;
1646 throw std::invalid_argument(msg.str());
1647}
static Roo_reg_AGKInteg1D instance
#define cxcoutD(a)
#define coutW(a)
#define oocoutE(o, a)
#define coutE(a)
int Int_t
Definition RtypesCore.h:45
char Text_t
Definition RtypesCore.h:62
const char Option_t
Definition RtypesCore.h:66
#define ClassImp(name)
Definition Rtypes.h:382
static void indent(ostringstream &buf, int indent_level)
Option_t Option_t option
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 sel
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 r
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 result
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize void value
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize void char Point_t Rectangle_t WindowAttributes_t Float_t Float_t Float_t Int_t Int_t UInt_t UInt_t Rectangle_t Int_t Int_t Window_t TString Int_t GCValues_t GetPrimarySelectionOwner GetDisplay GetScreen GetColormap GetNativeEvent const char const char dpyName wid window const char font_name cursor keysym reg const char only_if_exist regb h Point_t winding char text const char depth char const char Int_t count const char ColorStruct_t color const char Pixmap_t Pixmap_t PictureAttributes_t attr const char char ret_data h unsigned char height h Atom_t Int_t ULong_t ULong_t unsigned char prop_list Atom_t Atom_t Atom_t Time_t UChar_t len
char name[80]
Definition TGX11.cxx:110
Common abstract base class for objects that represent a value and a "shape" in RooFit.
Definition RooAbsArg.h:77
virtual void copyCache(const RooAbsArg *source, bool valueOnly=false, bool setValDirty=true)=0
const TNamed * namePtr() const
De-duplicated pointer to this object's name.
Definition RooAbsArg.h:504
virtual void syncCache(const RooArgSet *nset=nullptr)=0
const RefCountList_t & servers() const
List of all servers of this object.
Definition RooAbsArg.h:149
TObject * Clone(const char *newname=nullptr) const override
Make a clone of an object using the Streamer facility.
Definition RooAbsArg.h:89
Abstract base class for objects that represent a discrete value that can be set from the outside,...
virtual bool setIndex(value_type index, bool printError=true)=0
Change category state by specifying the index code of the desired state.
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.
Abstract container object that can hold multiple RooAbsArg objects.
RooAbsCollection * selectByAttrib(const char *name, bool value) const
Create a subset of the current collection, consisting only of those elements with the specified attri...
bool equals(const RooAbsCollection &otherColl) const
Check if this and other collection have identically-named contents.
double getRealValue(const char *name, double defVal=0.0, bool verbose=false) const
Get value of a RooAbsReal stored in set with given name.
virtual void removeAll()
Remove all arguments from our set, deleting them if we own them.
void deleteList()
Delete contents of the list.
Int_t getCatIndex(const char *name, Int_t defVal=0, bool verbose=false) const
Get index value of a RooAbsCategory stored in set with given name.
virtual bool remove(const RooAbsArg &var, bool silent=false, bool matchByNameOnly=false)
Remove the specified argument from our list.
void printLatex(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
Output content of collection as LaTex table.
RooAbsCollection & assignValueOnly(const RooAbsCollection &other, bool forceIfSizeOne=false)
Sets the value of any argument in our set that also appears in the other set.
virtual TObject * create(const char *newname) const =0
Int_t defaultPrintContents(Option_t *opt) const override
Define default RooPrinable print options for given Print() flag string For inline printing only show ...
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.
void sortTopologically()
Sort collection topologically: the servers of any RooAbsArg will be before that RooAbsArg in the coll...
const char * getStringValue(const char *name, const char *defVal="", bool verbose=false) const
Get string value of a RooStringVar stored in set with given name.
bool contains(const RooAbsArg &var) const
Check if collection contains an argument with the same name as var.
virtual bool canBeAdded(const RooAbsArg &arg, bool silent) const =0
Determine whether it's possible to add a given RooAbsArg to the collection or not.
RooAbsCollection * snapshot(bool deepCopy=true) const
Take a snap shot of current collection contents.
RooAbsCollection()
Default constructor.
void printValue(std::ostream &os) const override
Print value of collection, i.e.
~RooAbsCollection() override
Destructor.
bool setStringValue(const char *name, const char *newVal="", bool verbose=false)
Set string value of a RooStringVar stored in set with given name to newVal.
HashAssistedFind * _hashAssistedFind
!
const char * GetName() const override
Returns name of object.
virtual bool add(const RooAbsArg &var, bool silent=false)
Add the specified argument to list.
void setAttribAll(const Text_t *name, bool value=true)
Set given attribute in each element of the collection by calling each elements setAttribute() functio...
void printTitle(std::ostream &os) const override
Return collection title.
Int_t index(const RooAbsArg *arg) const
Returns index of given arg, or -1 if arg is not in the collection.
bool _allRRV
All contents are RRV.
bool hasSameLayout(const RooAbsCollection &other) const
Check that all entries where the collections overlap have the same name.
void RecursiveRemove(TObject *obj) override
If one of the TObject we have a referenced to is deleted, remove the reference.
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
virtual bool replace(const RooAbsArg &var1, const RooAbsArg &var2)
Replace var1 with var2 and return true for success.
bool setCatIndex(const char *name, Int_t newVal=0, bool verbose=false)
Set index value of a RooAbsCategoryLValue stored in set with given name to newVal.
void clear()
Clear contents. If the collection is owning, it will also delete the contents.
void printMultiline(std::ostream &os, Int_t contents, bool verbose=false, TString indent="") const override
Implement multiline printing of collection, one line for each contained object showing the requested ...
static void throwAddTypedException(TClass *klass, RooAbsArg *arg)
bool setCatLabel(const char *name, const char *newVal="", bool verbose=false)
Set state name of a RooAbsCategoryLValue stored in set with given name to newVal.
virtual bool addOwned(RooAbsArg &var, bool silent=false)
Add an argument and transfer the ownership to the collection.
Storage_t _list
Actual object storage.
RooAbsCollection * selectByName(const char *nameList, bool verbose=false) const
Create a subset of the current collection, consisting only of those elements with names matching the ...
bool setRealValue(const char *name, double newVal=0.0, bool verbose=false)
Set value of a RooAbsRealLValue stored in set with given name to newVal No error messages are printed...
bool _ownCont
Flag to identify a list that owns its contents.
virtual RooAbsArg * addClone(const RooAbsArg &var, bool silent=false)
Add a clone of the specified argument to list.
void printName(std::ostream &os) const override
Return collection name.
void sort(bool reverse=false)
Sort collection using std::sort and name comparison.
std::size_t _sizeThresholdForMapSearch
!
void dump() const
Base contents dumper for debugging purposes.
bool selectCommon(const RooAbsCollection &refColl, RooAbsCollection &outColl) const
Create a subset of the current collection, consisting only of those elements that are contained as we...
const char * getCatLabel(const char *name, const char *defVal="", bool verbose=false) const
Get state name of a RooAbsCategory stored in set with given name.
virtual bool containsInstance(const RooAbsArg &var) const
Check if this exact instance is in this collection.
void useHashMapForFind(bool flag) const
bool isOwning() const
bool replaceImpl(const RooAbsArg &var1, const RooAbsArg &var2)
std::string contentsString() const
Return comma separated list of contained object names as STL string.
void printClassName(std::ostream &os) const override
Return collection class name.
void setName(const char *name)
RooAbsCollection & operator=(const RooAbsCollection &other)
Assign values from the elements in other to our elements.
void insert(RooAbsArg *)
Insert an element into the owned collections.
RooAbsArg * find(const char *name) const
Find object with given name in list.
Abstract base class for objects that represent a real value that may appear on the left hand side of ...
virtual void setVal(double value)=0
Set the current value of the object. Needs to be overridden by implementations.
Abstract base class for objects that represent a real value and implements functionality common to al...
Definition RooAbsReal.h:59
double getVal(const RooArgSet *normalisationSet=nullptr) const
Evaluate object.
Definition RooAbsReal.h:103
RooArgList is a container object that can hold multiple RooAbsArg objects.
Definition RooArgList.h:22
RooAbsArg * at(Int_t idx) const
Return object at given index, or nullptr if index is out of range.
Definition RooArgList.h:110
RooArgSet is a container object that can hold multiple RooAbsArg objects.
Definition RooArgSet.h:24
Named container for two doubles, two integers two object points and three string pointers that can be...
Definition RooCmdArg.h:26
void addArg(const RooCmdArg &arg)
Utility function to add nested RooCmdArg to payload of this RooCmdArg.
const char * getString(Int_t idx) const
Return string stored in slot idx.
Definition RooCmdArg.h:96
void setString(Int_t idx, const char *value)
Definition RooCmdArg.h:79
Configurable parser for RooCmdArg named arguments.
void defineMutex(const char *head, Args_t &&... tail)
Define arguments where any pair is mutually exclusive.
bool process(const RooCmdArg &arg)
Process given RooCmdArg.
bool hasProcessed(const char *cmdName) const
Return true if RooCmdArg with name 'cmdName' has been processed.
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...
const RooLinkedList & getObjectList(const char *name) const
Return list of objects registered with name 'name'.
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'.
Collection class for internal use, storing a collection of RooAbsArg pointers in a doubly linked list...
Int_t GetSize() const
TObject * At(int index) const
Return object stored in sequential position given by index.
void Delete(Option_t *o=nullptr) override
Remove all elements in collection and delete all elements NB: Collection does not own elements,...
virtual void Add(TObject *arg)
TObject * FindObject(const char *name) const override
Return pointer to object with given name.
Registry for const char* names.
Definition RooNameReg.h:26
static const TNamed * known(const char *stringPtr)
If the name is already known, return its TNamed pointer. Otherwise return 0 (don't register the name)...
A 'mix-in' base class that define the standard RooFit plotting and printing methods.
static Int_t _nameLength
static void nameFieldLength(Int_t newLen)
Set length of field reserved from printing name of RooAbsArgs in multi-line collection printing to gi...
Variable that can be changed from the outside.
Definition RooRealVar.h:37
TString * format(const RooCmdArg &formatArg) const
Format contents of RooRealVar for pretty printing on RooPlot parameter boxes.
void copyCacheFast(const RooRealVar &other, bool setValDirty=true)
Definition RooRealVar.h:131
A RooAbsArg implementing string values.
void setVal(const char *newVal)
const char * getVal() const
static TClass * Class()
static void create(const TObject *obj)
Register creation of object 'obj'.
Definition RooTrace.cxx:123
TClass instances represent classes, structs and namespaces in the ROOT type system.
Definition TClass.h:81
The TNamed class is the base class for all named ROOT classes.
Definition TNamed.h:29
const char * GetName() const override
Returns name of object.
Definition TNamed.h:47
static TClass * Class()
Mother of all ROOT objects.
Definition TObject.h:41
virtual const char * GetName() const
Returns name of object.
Definition TObject.cxx:456
virtual const char * ClassName() const
Returns name of class to which the object belongs.
Definition TObject.cxx:225
virtual Bool_t InheritsFrom(const char *classname) const
Returns kTRUE if object inherits from class "classname".
Definition TObject.cxx:542
virtual const char * GetTitle() const
Returns title of object.
Definition TObject.cxx:500
Regular expression class.
Definition TRegexp.h:31
Basic string class.
Definition TString.h:139
int CompareTo(const char *cs, ECaseCompare cmp=kExact) const
Compare a string to char *cs2.
Definition TString.cxx:457
const char * Data() const
Definition TString.h:376
TString & ReplaceAll(const TString &s1, const TString &s2)
Definition TString.h:704
TString & Append(const char *cs)
Definition TString.h:572
Ssiz_t Index(const char *pat, Ssiz_t i=0, ECaseCompare cmp=kExact) const
Definition TString.h:651
RooCmdArg LatexTableStyle(bool flag=true)
The namespace RooFit contains mostly switches that change the behaviour of functions of PDFs (or othe...
Definition CodegenImpl.h:64
bool snapshotImpl(RooAbsCollection const &input, RooAbsCollection &output, bool deepCopy, RooArgSet const *observables)
Helper for hash-map-assisted finding of elements by name.
RooAbsArg * find(const TNamed *nptr) const
std::unordered_map< const TNamed *, const RooAbsArg *const > nameToItemMap
const std::size_t & currentRooNameRegCounter
void erase(const RooAbsArg *elm)
void replace(const RooAbsArg *out, const RooAbsArg *in)
void insert(const RooAbsArg *elm)
HashAssistedFind(It_t first, It_t last)
Initialise empty hash map for fast finding by name.
TLine l
Definition textangle.C:4
static void output()