forked from root-project/root
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRooAbsCollection.cxx
More file actions
1648 lines (1322 loc) · 54.5 KB
/
Copy pathRooAbsCollection.cxx
File metadata and controls
1648 lines (1322 loc) · 54.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*****************************************************************************
* Project: RooFit *
* Package: RooFitCore *
* @(#)root/roofitcore:$Id$
* Authors: *
* WV, Wouter Verkerke, UC Santa Barbara, verkerke@slac.stanford.edu *
* DK, David Kirkby, UC Irvine, dkirkby@uci.edu *
* *
* Copyright (c) 2000-2005, Regents of the University of California *
* and Stanford University. All rights reserved. *
* *
* Redistribution and use in source and binary forms, *
* with or without modification, are permitted according to the terms *
* listed in LICENSE (http://roofit.sourceforge.net/license.txt) *
*****************************************************************************/
/**
\file RooAbsCollection.cxx
\class RooAbsCollection
\ingroup Roofitcore
Abstract container object that can hold
multiple RooAbsArg objects. Collections are ordered and can
contain multiple objects of the same name, (but a derived
implementation can enforce unique names). The storage of objects is
implemented using the container denoted by RooAbsCollection::Storage_t.
**/
#include "RooAbsCollection.h"
#include "TClass.h"
#include "TRegexp.h"
#include "RooStreamParser.h"
#include "RooAbsRealLValue.h"
#include "RooAbsCategoryLValue.h"
#include "RooStringVar.h"
#include "RooTrace.h"
#include "RooArgList.h"
#include "RooLinkedListIter.h"
#include "RooCmdConfig.h"
#include "RooRealVar.h"
#include "RooGlobalFunc.h"
#include "RooMsgService.h"
#include "RooFitImplHelpers.h"
#include <strlcpy.h>
#include <algorithm>
#include <iomanip>
#include <iostream>
#include <fstream>
#include <memory>
namespace RooFit {
namespace Detail {
/**
* Helper for hash-map-assisted finding of elements by name.
* Create this helper if finding of elements by name is needed.
* Upon creation, this object checks the global
* RooNameReg::renameCounter()
* and tracks elements of this collection by name. If an element
* gets renamed, this counter will be increased, and the name to
* object map becomes invalid. In this case, it has to be recreated.
*/
struct HashAssistedFind {
/// Initialise empty hash map for fast finding by name.
template<typename It_t>
HashAssistedFind(It_t first, It_t last) :
currentRooNameRegCounter{ RooNameReg::instance().renameCounter() },
rooNameRegCounterWhereMapWasValid{ currentRooNameRegCounter }
{
nameToItemMap.reserve(std::distance(first, last));
for (auto it = first; it != last; ++it) {
nameToItemMap.emplace((*it)->namePtr(), *it);
}
}
bool isValid() const {
return (currentRooNameRegCounter == rooNameRegCounterWhereMapWasValid);
}
RooAbsArg * find(const TNamed * nptr) const {
assert(isValid());
auto item = nameToItemMap.find(nptr);
return item != nameToItemMap.end() ? const_cast<RooAbsArg *>(item->second) : nullptr;
}
void replace(const RooAbsArg * out, const RooAbsArg * in) {
nameToItemMap.erase(out->namePtr());
nameToItemMap.emplace(in->namePtr(), in);
}
void insert(const RooAbsArg * elm) {
nameToItemMap.emplace(elm->namePtr(), elm);
}
void erase(const RooAbsArg * elm) {
nameToItemMap.erase(elm->namePtr());
}
std::unordered_map<const TNamed *, const RooAbsArg * const> nameToItemMap;
const std::size_t & currentRooNameRegCounter;
std::size_t rooNameRegCounterWhereMapWasValid = 0;
};
}
}
////////////////////////////////////////////////////////////////////////////////
/// Default constructor
RooAbsCollection::RooAbsCollection()
{
_list.reserve(8);
}
////////////////////////////////////////////////////////////////////////////////
/// Empty collection constructor
RooAbsCollection::RooAbsCollection(const char *name) :
_name(name)
{
_list.reserve(8);
}
////////////////////////////////////////////////////////////////////////////////
/// Copy constructor. Note that a copy of a collection is always non-owning,
/// even the source collection is owning. To create an owning copy of
/// a collection (owning or not), use the snapshot() method.
RooAbsCollection::RooAbsCollection(const RooAbsCollection& other, const char *name) :
TObject(other),
RooPrintable(other),
_name(name),
_allRRV(other._allRRV)
{
RooTrace::create(this) ;
if (!name) setName(other.GetName()) ;
_list.reserve(other._list.size());
for (auto item : other._list) {
insert(item);
}
}
////////////////////////////////////////////////////////////////////////////////
/// Move constructor.
RooAbsCollection::RooAbsCollection(RooAbsCollection&& other) :
TObject(other),
RooPrintable(other),
_list(std::move(other._list)),
_ownCont(other._ownCont),
_name(std::move(other._name)),
_allRRV(other._allRRV),
_sizeThresholdForMapSearch(other._sizeThresholdForMapSearch)
{
}
////////////////////////////////////////////////////////////////////////////////
/// Destructor
RooAbsCollection::~RooAbsCollection()
{
// Delete all variables in our list if we own them
if(_ownCont){
deleteList() ;
}
if (_hashAssistedFind) {
delete _hashAssistedFind;
}
_hashAssistedFind = nullptr;
}
////////////////////////////////////////////////////////////////////////////////
/// Delete contents of the list.
/// The RooAbsArg destructor ensures clients and servers can be deleted in any
/// order.
/// Also cleans the hash-map for fast lookups if present.
void RooAbsCollection::deleteList()
{
if (_hashAssistedFind) {
delete _hashAssistedFind;
}
_hashAssistedFind = nullptr;
// Built-in delete remaining elements
for (auto item : _list) {
delete item;
}
_list.clear();
}
////////////////////////////////////////////////////////////////////////////////
/// Take a snap shot of current collection contents.
/// An owning collection is returned containing clones of
/// - Elements in this collection
/// - External dependents of all elements and recursively any dependents of those dependents
/// (if deepCopy flag is set)
///
/// This is useful to save the values of variables or parameters. It doesn't require
/// deep copying if the parameters are direct members of the collection.
///
/// If deepCopy is specified, the client-server links between the cloned
/// list elements and the cloned external dependents are reconnected to
/// each other, making the snapshot a completely self-contained entity.
///
///
RooAbsCollection* RooAbsCollection::snapshot(bool deepCopy) const
{
// First create empty list
TString snapName ;
if (TString(GetName()).Length()>0) {
snapName.Append("Snapshot of ") ;
snapName.Append(GetName()) ;
}
auto* output = static_cast<RooAbsCollection*>(create(snapName.Data())) ;
if (snapshot(*output,deepCopy)) {
delete output ;
return nullptr ;
}
return output ;
}
////////////////////////////////////////////////////////////////////////////////
/// Take a snap shot of current collection contents:
/// A collection that owns its elements is returned containing clones of
/// - Elements in this collection
/// - External dependents of those elements
/// and recursively any dependents of those dependents
/// (if deepCopy flag is set)
///
/// If deepCopy is specified, the client-server links between the cloned
/// list elements and the cloned external dependents are reconnected to
/// each other, making the snapshot a completely self-contained entity.
///
///
bool RooAbsCollection::snapshot(RooAbsCollection& output, bool deepCopy) const
{
return RooHelpers::Detail::snapshotImpl(*this, output, deepCopy, nullptr);
}
////////////////////////////////////////////////////////////////////////////////
/// Assign values from the elements in `other` to our elements.
/// \warning This is not a conventional assignment operator. To avoid confusion, prefer using RooAbsCollection::assign().
RooAbsCollection &RooAbsCollection::operator=(const RooAbsCollection& other)
{
assign(other);
return *this;
}
////////////////////////////////////////////////////////////////////////////////
/// Sets the value, cache and constant attribute of any argument in our set
/// that also appears in the other set. Note that this function changes the
/// values of the elements in this collection, but is still marked `const` as
/// it does not change which elements this collection points to.
void RooAbsCollection::assign(const RooAbsCollection& other) const
{
if (&other==this) return ;
for (auto elem : _list) {
auto theirs = other.find(*elem);
if(!theirs) continue;
theirs->syncCache() ;
elem->copyCache(theirs) ;
elem->setAttribute("Constant",theirs->isConstant()) ;
}
return ;
}
////////////////////////////////////////////////////////////////////////////////
/// Sets the value of any argument in our set that also appears in the other set.
/// \param[in] other Collection holding the arguments to synchronize values with.
/// \param[in] forceIfSizeOne If set to true and both our collection
/// and the other collection have a size of one, the arguments are
/// always synchronized without checking if they have the same name.
RooAbsCollection &RooAbsCollection::assignValueOnly(const RooAbsCollection& other, bool forceIfSizeOne)
{
if (&other==this) return *this;
// Short cut for 1 element assignment
if (size()==1 && size() == other.size() && forceIfSizeOne) {
other.first()->syncCache() ;
first()->copyCache(other.first(),true) ;
return *this;
}
for (auto elem : _list) {
auto theirs = other.find(*elem);
if(!theirs) continue;
theirs->syncCache() ;
elem->copyCache(theirs,true) ;
}
return *this;
}
////////////////////////////////////////////////////////////////////////////////
/// Functional equivalent of assign() but assumes this and other collection
/// have same layout. Also no attributes are copied
void RooAbsCollection::assignFast(const RooAbsCollection& other, bool setValDirty) const
{
if (&other==this) return ;
assert(hasSameLayout(other));
auto iter2 = other._list.begin();
for (auto iter1 = _list.begin();
iter1 != _list.end() && iter2 != other._list.end();
++iter1, ++iter2) {
// Identical size of iterators is documented assumption of method
if (_allRRV) {
// All contents are known to be RooRealVars - fast version of assignment
auto ours = static_cast<RooRealVar*>(*iter1);
auto theirs = static_cast<RooRealVar*>(*iter2);
ours->copyCacheFast(*theirs,setValDirty);
} else {
(*iter2)->syncCache() ;
(*iter1)->copyCache(*iter2,true,setValDirty) ;
}
}
}
////////////////////////////////////////////////////////////////////////////////
/// Add an argument and transfer the ownership to the collection. Returns `true`
/// if successful, or `false` if the argument could not be added to the
/// collection (e.g. in the RooArgSet case when an argument with the same name
/// is already in the list). This method can only be called on a list that is
/// flagged as owning all of its contents, or else on an empty list (which will
/// force the list into that mode).
///
/// If the argument you want to add is owned by a `std::unique_ptr`, you should
/// prefer RooAbsCollection::addOwned(std::unique_ptr<RooAbsArg>, bool).
bool RooAbsCollection::addOwned(RooAbsArg& var, bool silent)
{
if(!canBeAdded(var, silent)) return false;
// check that we own our variables or else are empty
if(!_ownCont && !empty() && !silent) {
coutE(ObjectHandling) << ClassName() << "::" << GetName() << "::addOwned: can only add to an owned list" << std::endl;
return false;
}
_ownCont= true;
insert(&var);
return true;
}
////////////////////////////////////////////////////////////////////////////////
/// Add an argument and transfer the ownership to the collection from a
/// `std::unique_ptr`. Always returns `true`. If the argument can not be added
/// to the collection (e.g. in the RooArgSet case when an argument with the
/// same name is already in the list), a `std::runtime_exception` will be
/// thrown, as nobody is owning the argument anymore. This method can only be
/// called on a list that is flagged as owning all of its contents, or else on
/// an empty list (which will force the list into that mode).
///
/// If you want to pass an argument that is not owned by a `std::unique_ptr`,
/// you can use RooAbsCollection::addOwned(RooAbsArg&, bool).
bool RooAbsCollection::addOwned(std::unique_ptr<RooAbsArg> var, bool silent) {
bool result = addOwned(*var.release(), silent);
if(!result) {
auto errMsg = std::string("RooAbsCollection::addOwned could not add the argument to the")
+ " collection! The ownership would not be well defined if we ignore this.";
coutE(ObjectHandling) << errMsg << std::endl;
throw std::runtime_error(errMsg);
}
return result;
}
////////////////////////////////////////////////////////////////////////////////
/// Add a clone of the specified argument to list. Returns a pointer to
/// the clone if successful, or else zero if a variable of the same name
/// is already in the list or the list does *not* own its variables (in
/// this case, try add() instead.) Calling addClone() on an empty list
/// forces it to take ownership of all its subsequent variables.
RooAbsArg *RooAbsCollection::addClone(const RooAbsArg& var, bool silent)
{
if(!canBeAdded(var, silent)) return nullptr;
// check that we own our variables or else are empty
if(!_ownCont && !empty() && !silent) {
coutE(ObjectHandling) << ClassName() << "::" << GetName() << "::addClone: can only add to an owned list" << std::endl;
return nullptr;
}
_ownCont= true;
// add a pointer to a clone of this variable to our list (we now own it!)
auto clone2 = static_cast<RooAbsArg*>(var.Clone());
assert(clone2);
insert(clone2);
return clone2;
}
////////////////////////////////////////////////////////////////////////////////
/// Add the specified argument to list. Returns true if successful, or
/// else false if a variable of the same name is already in the list
/// or the list owns its variables (in this case, try addClone() or addOwned() instead).
bool RooAbsCollection::add(const RooAbsArg& var, bool silent)
{
if(!canBeAdded(var, silent)) return false;
// check that this isn't a copy of a list
if(_ownCont && !silent) {
coutE(ObjectHandling) << ClassName() << "::" << GetName() << "::add: cannot add to an owned list" << std::endl;
return false;
}
// add a pointer to this variable to our list (we don't own it!)
insert(const_cast<RooAbsArg*>(&var)); //FIXME const_cast
return true;
}
////////////////////////////////////////////////////////////////////////////////
// Add a collection of arguments to this collection by calling addOwned()
/// for each element in the source collection. The input list can't be an
/// owning collection itself, otherwise the arguments would be owned by two
/// collections.
///
/// If you want to transfer arguments from one owning collection to another,
/// you have two options:
/// 1. `std::move` the input collection and use
/// RooAbsCollection::addOwned(RooAbsCollection&&, bool) (preferred)
/// 2. release the ownership of the input collection first, using
/// RooAbsCollection::releaseOwnership()
bool RooAbsCollection::addOwned(const RooAbsCollection& list, bool silent)
{
if(list.isOwning()) {
throw std::invalid_argument("Passing an owning RooAbsCollection by const& to"
" RooAbsCollection::addOwned is forbidden because the ownership"
" would be ambiguous! Please std::move() the RooAbsCollection in this case."
" Note that the passed RooAbsCollection is invalid afterwards.");
}
bool result(false) ;
_list.reserve(_list.size() + list._list.size());
for (auto item : list._list) {
result |= addOwned(*item, silent) ;
}
return result;
}
////////////////////////////////////////////////////////////////////////////////
/// Add a collection of arguments to this collection by calling addOwned()
/// for each element in the source collection. Unlike
/// RooAbsCollection::addOwned(const RooAbsCollection&, bool), this function
/// also accepts owning source collections because their content will be
/// moved out.
bool RooAbsCollection::addOwned(RooAbsCollection&& list, bool silent)
{
if(list.isOwning()) {
list._ownCont = false;
}
if(list.empty()) return false;
bool result = addOwned(list, silent);
if(!result) {
auto errMsg = std::string("RooAbsCollection::addOwned could not add the argument to the")
+ " collection! The ownership would not be well defined if we ignore this.";
coutE(ObjectHandling) << errMsg << std::endl;
throw std::runtime_error(errMsg);
}
// So far, comps has only released the ownership, but it is still valid.
// However, we don't want users to keep using objects after moving them, so
// we make sure to keep our promise that the RooArgSet is really moved.
// Just like a `std::unique_ptr` is also reset when moved.
list.clear();
return result;
}
////////////////////////////////////////////////////////////////////////////////
/// Add a collection of arguments to this collection by calling addOwned()
/// for each element in the source collection
void RooAbsCollection::addClone(const RooAbsCollection& list, bool silent)
{
_list.reserve(_list.size() + list._list.size());
for (auto item : list._list) {
addClone(*item, silent);
}
}
////////////////////////////////////////////////////////////////////////////////
/// Replace any args in our set with args of the same name from the other set
/// and return true for success. Fails if this list is a copy of another.
bool RooAbsCollection::replace(const RooAbsCollection &other)
{
// check that this isn't a copy of a list
if(_ownCont) {
std::stringstream errMsg;
errMsg << "RooAbsCollection: cannot replace variables in a copied list";
coutE(ObjectHandling) << errMsg.str() << std::endl;
// better than returning "false" and leaving the collection in a broken state:
throw std::invalid_argument(errMsg.str());
}
// loop over elements in the other list
for (const auto * arg : other._list) {
// do we have an arg of the same name in our set?
auto found = find(*arg);
if (found) replace(*found,*arg);
}
return true;
}
bool RooAbsCollection::replaceImpl(const RooAbsArg& var1, const RooAbsArg& var2)
{
// is var1 already in this list?
const char *name= var1.GetName();
auto var1It = std::find(_list.begin(), _list.end(), &var1);
if (var1It == _list.end()) {
coutE(ObjectHandling) << "RooAbsCollection: variable \"" << name << "\" is not in the list"
<< " and cannot be replaced" << std::endl;
return false;
}
// is var2's name already in this list?
if (dynamic_cast<RooArgSet*>(this)) {
RooAbsArg *other = find(var2);
if(other != nullptr && other != &var1) {
coutE(ObjectHandling) << "RooAbsCollection: cannot replace \"" << name
<< "\" with already existing \"" << var2.GetName() << "\"" << std::endl;
return false;
}
}
// replace var1 with var2
if (_hashAssistedFind) {
_hashAssistedFind->replace(*var1It, &var2);
}
*var1It = const_cast<RooAbsArg*>(&var2); //FIXME try to get rid of const_cast
if (_allRRV && dynamic_cast<const RooRealVar*>(&var2) == nullptr) {
_allRRV=false ;
}
return true;
}
////////////////////////////////////////////////////////////////////////////////
/// Replace var1 with var2 and return true for success. Fails if
/// this list is a copy of another, if var1 is not already in this set,
/// or if var2 is already in this set. var1 and var2 do not need to have
/// the same name.
bool RooAbsCollection::replace(const RooAbsArg &var1, const RooAbsArg &var2)
{
// check that this isn't a copy of a list
if (_ownCont) {
std::string errMsg = "RooAbsCollection: cannot replace variables in a copied list";
coutE(ObjectHandling) << errMsg << std::endl;
throw std::runtime_error(errMsg);
}
return replaceImpl(var1, var2);
}
////////////////////////////////////////////////////////////////////////////////
/// Replace var1 with var2 and return true for success. Fails if
/// this list is a copy of another, if var1 is not already in this set,
/// or if var2 is already in this set. var1 and var2 do not need to have
/// the same name.
bool RooAbsCollection::replace(RooAbsArg *var1, std::unique_ptr<RooAbsArg> var2)
{
// To accept an owning var2, the collection must be owning.
if (!_ownCont) {
std::string errMsg =
"RooAbsCollection::replace(RooAbsArg *, std::unique_ptr<RooAbsArg>) can't be used on a non-owning collection!";
coutE(ObjectHandling) << errMsg << std::endl;
throw std::runtime_error(errMsg);
}
bool success = replaceImpl(*var1, *var2.release());
if (!success) {
auto errMsg = std::string("RooAbsCollection::replace(RooAbsArg *, std::unique_ptr<RooAbsArg>) did not succeed!") +
"The ownership would not be well defined if we ignore this.";
coutE(ObjectHandling) << errMsg << std::endl;
throw std::runtime_error(errMsg);
}
delete var1;
return success;
}
////////////////////////////////////////////////////////////////////////////////
/// Remove the specified argument from our list. Return false if
/// the specified argument is not found in our list. An exact pointer
/// match is required, not just a match by name.
/// If `matchByNameOnly` is set, items will be looked up by name. In this case, if
/// the collection also owns the item, it will delete it.
bool RooAbsCollection::remove(const RooAbsArg& var, bool , bool matchByNameOnly)
{
// is var already in this list?
const auto sizeBefore = _list.size();
if (matchByNameOnly) {
const std::string name(var.GetName());
auto nameMatch = [&name](const RooAbsArg* elm) {
return elm->GetName() == name;
};
std::set<RooAbsArg*> toBeDeleted;
if (_ownCont) {
std::for_each(_list.begin(), _list.end(), [&toBeDeleted, nameMatch](RooAbsArg* elm){
if (nameMatch(elm)) {
toBeDeleted.insert(elm);
}
});
}
_list.erase(std::remove_if(_list.begin(), _list.end(), nameMatch), _list.end());
for (auto arg : toBeDeleted)
delete arg;
} else {
_list.erase(std::remove(_list.begin(), _list.end(), &var), _list.end());
}
if (_hashAssistedFind && sizeBefore != _list.size()) {
_hashAssistedFind->erase(&var);
}
return sizeBefore != _list.size();
}
////////////////////////////////////////////////////////////////////////////////
/// Remove each argument in the input list from our list.
/// An exact pointer match is required, not just a match by name.
/// If `matchByNameOnly` is set, items will be looked up by name. In this case, if
/// the collection also owns the items, it will delete them.
/// Return false in case of problems.
bool RooAbsCollection::remove(const RooAbsCollection& list, bool /*silent*/, bool matchByNameOnly)
{
auto oldSize = _list.size();
std::vector<const RooAbsArg*> markedItems;
if (matchByNameOnly) {
// Instead of doing two passes on the list as in remove(RooAbsArg&), we do
// everything in one pass, by using side effects of the predicate.
auto nameMatchAndMark = [&list, &markedItems](const RooAbsArg* elm) {
if( list.contains(*elm) ) {
markedItems.push_back(elm);
return true;
}
return false;
};
_list.erase(std::remove_if(_list.begin(), _list.end(), nameMatchAndMark), _list.end());
}
else {
auto argMatchAndMark = [&list, &markedItems](const RooAbsArg* elm) {
if( list.containsInstance(*elm) ) {
markedItems.push_back(elm);
return true;
}
return false;
};
_list.erase(std::remove_if(_list.begin(), _list.end(), argMatchAndMark), _list.end());
}
if (_hashAssistedFind && oldSize != _list.size()) {
for( auto& var : markedItems ) {
_hashAssistedFind->erase(var);
}
}
if (matchByNameOnly && _ownCont) {
std::set<const RooAbsArg*> toBeDeleted(markedItems.begin(), markedItems.end());
for (auto arg : toBeDeleted) {
delete arg;
}
}
return oldSize != _list.size();
}
////////////////////////////////////////////////////////////////////////////////
/// Remove all arguments from our set, deleting them if we own them.
/// This effectively restores our object to the state it would have
/// just after calling the RooAbsCollection(const char*) constructor.
void RooAbsCollection::removeAll()
{
if (_hashAssistedFind) {
delete _hashAssistedFind;
}
_hashAssistedFind = nullptr;
if(_ownCont) {
deleteList() ;
_ownCont= false;
}
else {
_list.clear();
}
}
////////////////////////////////////////////////////////////////////////////////
/// Set given attribute in each element of the collection by
/// calling each elements setAttribute() function.
void RooAbsCollection::setAttribAll(const Text_t* name, bool value)
{
for (auto arg : _list) {
arg->setAttribute(name, value);
}
}
////////////////////////////////////////////////////////////////////////////////
/// Create a subset of the current collection, consisting only of those
/// elements with the specified attribute set. The caller is responsible
/// for deleting the returned collection
RooAbsCollection* RooAbsCollection::selectByAttrib(const char* name, bool value) const
{
TString selName(GetName()) ;
selName.Append("_selection") ;
RooAbsCollection *sel = static_cast<RooAbsCollection*>(create(selName.Data())) ;
// Scan set contents for matching attribute
for (auto arg : _list) {
if (arg->getAttribute(name)==value)
sel->add(*arg) ;
}
return sel ;
}
////////////////////////////////////////////////////////////////////////////////
/// Create a subset of the current collection, consisting only of those
/// elements that are contained as well in the given reference collection.
/// Returns `true` only if something went wrong.
/// The complement of this function is getParameters().
/// \param[in] refColl The collection to check for common elements.
/// \param[out] outColl Output collection.
bool RooAbsCollection::selectCommon(const RooAbsCollection& refColl, RooAbsCollection& outColl) const
{
outColl.clear();
outColl.setName((std::string(GetName()) + "_selection").c_str());
// Scan set contents for matching attribute
for (auto arg : _list) {
if (refColl.find(*arg))
outColl.add(*arg) ;
}
return false;
}
////////////////////////////////////////////////////////////////////////////////
/// Create a subset of the current collection, consisting only of those
/// elements that are contained as well in the given reference collection.
/// The caller is responsible for deleting the returned collection
RooAbsCollection* RooAbsCollection::selectCommon(const RooAbsCollection& refColl) const
{
auto sel = static_cast<RooAbsCollection*>(create("")) ;
selectCommon(refColl, *sel);
return sel ;
}
////////////////////////////////////////////////////////////////////////////////
/// Create a subset of the current collection, consisting only of those
/// elements with names matching the wildcard expressions in nameList,
/// supplied as a comma separated list
RooAbsCollection* RooAbsCollection::selectByName(const char* nameList, bool verbose) const
{
// Create output set
TString selName(GetName()) ;
selName.Append("_selection") ;
RooAbsCollection *sel = static_cast<RooAbsCollection*>(create(selName.Data())) ;
const size_t bufSize = strlen(nameList) + 1;
std::vector<char> buf(bufSize);
strlcpy(buf.data(),nameList,bufSize) ;
char* wcExpr = strtok(buf.data(),",") ;
while(wcExpr) {
TRegexp rexp(wcExpr,true) ;
if (verbose) {
cxcoutD(ObjectHandling) << "RooAbsCollection::selectByName(" << GetName() << ") processing expression '" << wcExpr << "'" << std::endl;
}
for (auto const* arg : *this) {
if (TString(arg->GetName()).Index(rexp)>=0) {
if (verbose) {
cxcoutD(ObjectHandling) << "RooAbsCollection::selectByName(" << GetName() << ") selected element " << arg->GetName() << std::endl;
}
sel->add(*arg) ;
}
}
wcExpr = strtok(nullptr,",") ;
}
return sel ;
}
////////////////////////////////////////////////////////////////////////////////
/// Check if this and other collection have identically-named contents
bool RooAbsCollection::equals(const RooAbsCollection& otherColl) const
{
// First check equal length
if (size() != otherColl.size()) return false ;
// Then check that each element of our list also occurs in the other list
auto compareByNamePtr = [](const RooAbsArg * left, const RooAbsArg * right) {
return left->namePtr() == right->namePtr();
};
return std::is_permutation(_list.begin(), _list.end(),
otherColl._list.begin(),
compareByNamePtr);
}
namespace {
////////////////////////////////////////////////////////////////////////////////
/// Linear search through list of stored objects.
template<class Collection_t>
RooAbsArg* findUsingNamePointer(const Collection_t& coll, const TNamed* ptr) {
auto findByNamePtr = [ptr](const RooAbsArg* elm) {
return ptr == elm->namePtr();
};
auto item = std::find_if(coll.begin(), coll.end(), findByNamePtr);
return item != coll.end() ? *item : nullptr;
}
}
////////////////////////////////////////////////////////////////////////////////
/// Find object with given name in list. A null pointer
/// is returned if no object with the given name is found.
RooAbsArg * RooAbsCollection::find(const char *name) const
{
if (!name)
return nullptr;
// If an object with such a name exists, its name has been registered.
const TNamed* nptr = RooNameReg::known(name);
if (!nptr) return nullptr;
if (_hashAssistedFind || _list.size() >= _sizeThresholdForMapSearch) {
if (!_hashAssistedFind || !_hashAssistedFind->isValid()) {
delete _hashAssistedFind;
_hashAssistedFind = new HashAssistedFind{_list.begin(), _list.end()};
}
return _hashAssistedFind->find(nptr);
}
return findUsingNamePointer(_list, nptr);
}
////////////////////////////////////////////////////////////////////////////////
/// Find object with given name in list. A null pointer
/// is returned if no object with the given name is found.
RooAbsArg * RooAbsCollection::find(const RooAbsArg& arg) const
{
const auto nptr = arg.namePtr();
if (_hashAssistedFind || _list.size() >= _sizeThresholdForMapSearch) {
if (!_hashAssistedFind || !_hashAssistedFind->isValid()) {
delete _hashAssistedFind;
_hashAssistedFind = new HashAssistedFind{_list.begin(), _list.end()};
}
return _hashAssistedFind->find(nptr);
}
return findUsingNamePointer(_list, nptr);
}
////////////////////////////////////////////////////////////////////////////////
/// Return index of item with given name, or -1 in case it's not in the collection.
Int_t RooAbsCollection::index(const char* name) const {
const std::string theName(name);
auto item = std::find_if(_list.begin(), _list.end(), [&theName](const RooAbsArg * elm){
return elm->GetName() == theName;
});
return item != _list.end() ? item - _list.begin() : -1;
}
////////////////////////////////////////////////////////////////////////////////
/// Get value of a RooAbsReal stored in set with given name. If none is found, value of defVal is returned.
/// No error messages are printed unless the verbose flag is set
double RooAbsCollection::getRealValue(const char* name, double defVal, bool verbose) const
{
RooAbsArg* raa = find(name) ;
if (!raa) {
if (verbose) coutE(InputArguments) << "RooAbsCollection::getRealValue(" << GetName() << ") ERROR no object with name '" << name << "' found" << std::endl;
return defVal ;
}
RooAbsReal* rar = dynamic_cast<RooAbsReal*>(raa) ;
if (!rar) {
if (verbose) coutE(InputArguments) << "RooAbsCollection::getRealValue(" << GetName() << ") ERROR object '" << name << "' is not of type RooAbsReal" << std::endl;
return defVal ;
}
return rar->getVal() ;
}
////////////////////////////////////////////////////////////////////////////////
/// Set value of a RooAbsRealLValue stored in set with given name to newVal
/// No error messages are printed unless the verbose flag is set
bool RooAbsCollection::setRealValue(const char* name, double newVal, bool verbose)