forked from root-project/root
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRooWorkspace.cxx
More file actions
2948 lines (2359 loc) · 103 KB
/
Copy pathRooWorkspace.cxx
File metadata and controls
2948 lines (2359 loc) · 103 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 *
* *
* 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 RooWorkspace.cxx
\class RooWorkspace
\ingroup Roofitcore
Persistable container for RooFit projects. A workspace
can contain and own variables, p.d.f.s, functions and datasets. All objects
that live in the workspace are owned by the workspace. The `import()` method
enforces consistency of objects upon insertion into the workspace (e.g. no
duplicate object with the same name are allowed) and makes sure all objects
in the workspace are connected to each other. Easy accessor methods like
`pdf()`, `var()` and `data()` allow to refer to the contents of the workspace by
object name. The entire RooWorkspace can be saved into a ROOT TFile and organises
the consistent streaming of its contents without duplication.
If a RooWorkspace contains custom classes, i.e. classes not in the
ROOT distribution, portability of workspaces can be enhanced by
storing the source code of those classes in the workspace as well.
This process is also organized by the workspace through the
`importClassCode()` method.
### Seemingly random crashes when reading large workspaces
When reading or loading workspaces with deeply nested PDFs, one can encounter
ouf-of-memory errors if the stack size is too small. This manifests in crashes
at seemingly random locations, or in the process silently ending.
Unfortunately, ROOT neither recover from this situation, nor warn or give useful
instructions. When suspecting to have run out of stack memory, check
```
ulimit -s
```
and try reading again.
**/
#include <RooWorkspace.h>
#include <RooAbsData.h>
#include <RooAbsPdf.h>
#include <RooAbsStudy.h>
#include <RooCategory.h>
#include <RooCmdConfig.h>
#include <RooConstVar.h>
#include <RooFactoryWSTool.h>
#include <RooLinkedListIter.h>
#include <RooMsgService.h>
#include <RooPlot.h>
#include <RooRandom.h>
#include <RooRealVar.h>
#include <RooResolutionModel.h>
#include <RooTObjWrap.h>
#include <RooWorkspaceHandle.h>
#include "TBuffer.h"
#include "TInterpreter.h"
#include "TClassTable.h"
#include "TBaseClass.h"
#include "TSystem.h"
#include "TRegexp.h"
#include "TROOT.h"
#include "TFile.h"
#include "TH1.h"
#include "TClass.h"
#include "strlcpy.h"
#ifdef ROOFIT_LEGACY_EVAL_BACKEND
#include "RooAbsOptTestStatistic.h"
#endif
#include "ROOT/StringUtils.hxx"
#include <map>
#include <sstream>
#include <string>
#include <iostream>
#include <fstream>
#include <cstring>
namespace {
// Infer from a RooArgSet name whether this set is used internally by
// RooWorkspace to cache things.
bool isCacheSet(std::string const& setName) {
// Check if the setName starts with CACHE_.
return setName.rfind("CACHE_", 0) == 0;
}
} // namespace
using std::string, std::list, std::map, std::vector, std::ifstream, std::ofstream, std::fstream, std::make_unique;
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
list<string> RooWorkspace::_classDeclDirList ;
list<string> RooWorkspace::_classImplDirList ;
string RooWorkspace::_classFileExportDir = ".wscode.%s.%s" ;
bool RooWorkspace::_autoClass = false ;
////////////////////////////////////////////////////////////////////////////////
/// Add `dir` to search path for class declaration (header) files. This is needed
/// to find class headers custom classes are imported into the workspace.
void RooWorkspace::addClassDeclImportDir(const char* dir)
{
_classDeclDirList.push_back(dir) ;
}
////////////////////////////////////////////////////////////////////////////////
/// Add `dir` to search path for class implementation (.cxx) files. This is needed
/// to find class headers custom classes are imported into the workspace.
void RooWorkspace::addClassImplImportDir(const char* dir)
{
_classImplDirList.push_back(dir) ;
}
////////////////////////////////////////////////////////////////////////////////
/// Specify the name of the directory in which embedded source
/// code is unpacked and compiled. The specified string may contain
/// one '%s' token which will be substituted by the workspace name
void RooWorkspace::setClassFileExportDir(const char* dir)
{
if (dir) {
_classFileExportDir = dir ;
} else {
_classFileExportDir = ".wscode.%s.%s" ;
}
}
////////////////////////////////////////////////////////////////////////////////
/// If flag is true, source code of classes not the ROOT distribution
/// is automatically imported if on object of such a class is imported
/// in the workspace
void RooWorkspace::autoImportClassCode(bool flag)
{
_autoClass = flag ;
}
////////////////////////////////////////////////////////////////////////////////
/// Default constructor
RooWorkspace::RooWorkspace() : _classes(this)
{
}
////////////////////////////////////////////////////////////////////////////////
/// Construct empty workspace with given name and title
RooWorkspace::RooWorkspace(const char* name, const char* title) :
TNamed(name,title?title:name), _classes(this)
{
}
////////////////////////////////////////////////////////////////////////////////
/// Construct empty workspace with given name and option to export reference to
/// all workspace contents to a CINT namespace with the same name.
RooWorkspace::RooWorkspace(const char* name, bool /*doCINTExport*/) :
TNamed(name,name), _classes(this)
{
}
////////////////////////////////////////////////////////////////////////////////
/// Workspace copy constructor
RooWorkspace::RooWorkspace(const RooWorkspace& other) :
TNamed(other), _uuid(other._uuid), _classes(other._classes,this)
{
// Copy owned nodes
other._allOwnedNodes.snapshot(_allOwnedNodes,true) ;
// Copy datasets
for(TObject *data2 : other._dataList) _dataList.Add(data2->Clone());
// Copy snapshots
for(auto * snap : static_range_cast<RooArgSet*>(other._snapshots)) {
auto snapClone = new RooArgSet;
snap->snapshot(*snapClone);
snapClone->setName(snap->GetName()) ;
_snapshots.Add(snapClone) ;
}
// Copy named sets
for (map<string,RooArgSet>::const_iterator iter3 = other._namedSets.begin() ; iter3 != other._namedSets.end() ; ++iter3) {
// Make RooArgSet with equivalent content of this workspace
_namedSets[iter3->first].add(*std::unique_ptr<RooArgSet>{_allOwnedNodes.selectCommon(iter3->second)});
}
// Copy generic objects
for(TObject * gobj : other._genObjects) {
_genObjects.Add(gobj->Clone());
}
for(TObject * gobj : allGenericObjects()) {
if (auto handle = dynamic_cast<RooWorkspaceHandle*>(gobj)) {
handle->ReplaceWS(this);
}
}
}
/// TObject::Clone() needs to be overridden.
TObject *RooWorkspace::Clone(const char *newname) const
{
auto out = new RooWorkspace{*this};
if(newname && std::string(newname) != GetName()) {
out->SetName(newname);
}
return out;
}
////////////////////////////////////////////////////////////////////////////////
/// Workspace destructor
RooWorkspace::~RooWorkspace()
{
// Delete contents
_dataList.Delete() ;
if (_dir) {
delete _dir ;
}
_snapshots.Delete() ;
// WVE named sets too?
_genObjects.Delete() ;
_embeddedDataList.Delete();
_views.Delete();
_studyMods.Delete();
}
////////////////////////////////////////////////////////////////////////////////
/// Import a RooAbsArg or RooAbsData set from a workspace in a file. Filespec should be constructed as "filename:wspacename:objectname"
/// The arguments will be passed to the relevant import() or import(RooAbsData&, ...) import calls
/// \note From python, use `Import()`, since `import` is a reserved keyword.
/// \return due to historical reasons: false (0) on success and true (1) on failure
bool RooWorkspace::import(const char* fileSpec,
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 RooCmdArg& arg9)
{
// Parse file/workspace/objectname specification
std::vector<std::string> tokens = ROOT::Split(fileSpec, ":");
// Check that parsing was successful
if (tokens.size() != 3) {
std::ostringstream stream;
for (const auto& token : tokens) {
stream << "\n\t" << token;
}
coutE(InputArguments) << "RooWorkspace(" << GetName() << ") ERROR in file specification, expecting 'filename:wsname:objname', but '" << fileSpec << "' given."
<< "\nTokens read are:" << stream.str() << std::endl;
return true ;
}
const std::string& filename = tokens[0];
const std::string& wsname = tokens[1];
const std::string& objname = tokens[2];
// Check that file can be opened
std::unique_ptr<TFile> f{TFile::Open(filename.c_str())};
if (f==nullptr) {
coutE(InputArguments) << "RooWorkspace(" << GetName() << ") ERROR opening file " << filename << std::endl ;
return false;
}
// That that file contains workspace
RooWorkspace* w = dynamic_cast<RooWorkspace*>(f->Get(wsname.c_str())) ;
if (w==nullptr) {
coutE(InputArguments) << "RooWorkspace(" << GetName() << ") ERROR: No object named " << wsname << " in file " << filename
<< " or object is not a RooWorkspace" << std::endl ;
return false;
}
// Check that workspace contains object and forward to appropriate import method
RooAbsArg* warg = w->arg(objname.c_str()) ;
if (warg) {
bool ret = import(*warg,arg1,arg2,arg3,arg4,arg5,arg6,arg7,arg8,arg9) ;
return ret ;
}
RooAbsData* wdata = w->data(objname.c_str()) ;
if (wdata) {
bool ret = import(*wdata,arg1,arg2,arg3,arg4,arg5,arg6,arg7,arg8,arg9) ;
return ret ;
}
coutE(InputArguments) << "RooWorkspace(" << GetName() << ") ERROR: No RooAbsArg or RooAbsData object named " << objname
<< " in workspace " << wsname << " in file " << filename << std::endl ;
return true ;
}
////////////////////////////////////////////////////////////////////////////////
/// Import multiple RooAbsArg objects into workspace. For details on arguments see documentation
/// of import() method for single RooAbsArg
/// \note From python, use `Import()`, since `import` is a reserved keyword.
/// \return due to historical reasons: false (0) on success and true (1) on failure
bool RooWorkspace::import(const RooArgSet& args,
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 RooCmdArg& arg9)
{
bool ret(false) ;
for(RooAbsArg * oneArg : args) {
ret |= import(*oneArg,arg1,arg2,arg3,arg4,arg5,arg6,arg7,arg8,arg9) ;
}
return ret ;
}
////////////////////////////////////////////////////////////////////////////////
/// Import a RooAbsArg object, e.g. function, p.d.f or variable into the workspace. This import function clones the input argument and will
/// own the clone. If a composite object is offered for import, e.g. a p.d.f with parameters and observables, the
/// complete tree of objects is imported. If any of the _variables_ of a composite object (parameters/observables) are already
/// in the workspace the imported p.d.f. is connected to the already existing variables. If any of the _function_ objects (p.d.f, formulas)
/// to be imported already exists in the workspace an error message is printed and the import of the entire tree of objects is cancelled.
/// Several optional arguments can be provided to modify the import procedure.
///
/// <table>
/// <tr><th> Accepted arguments
/// <tr><td> `RenameConflictNodes(const char* suffix)` <td> Add suffix to branch node name if name conflicts with existing node in workspace
/// <tr><td> `RenameAllNodes(const char* suffix)` <td> Add suffix to all branch node names including top level node.
/// <tr><td> `RenameAllVariables(const char* suffix)` <td> Add suffix to all variables of objects being imported.
/// <tr><td> `RenameAllVariablesExcept(const char* suffix, const char* exceptionList)` <td> Add suffix to all variables names, except ones listed
/// <tr><td> `RenameVariable(const char* inputName, const char* outputName)` <td> Rename a single variable as specified upon import.
/// <tr><td> `RecycleConflictNodes()` <td> If any of the function objects to be imported already exist in the name space, connect the
/// imported expression to the already existing nodes.
/// \attention Use with care! If function definitions do not match, this alters the definition of your function upon import
///
/// <tr><td> `Silence()` <td> Do not issue any info message
/// </table>
///
/// The RenameConflictNodes, RenameNodes and RecycleConflictNodes arguments are mutually exclusive. The RenameVariable argument can be repeated
/// as often as necessary to rename multiple variables. Alternatively, a single RenameVariable argument can be given with
/// two comma separated lists.
/// \note From python, use `Import()`, since `import` is a reserved keyword.
/// \return due to historical reasons: false (0) on success and true (1) on failure
bool RooWorkspace::import(const RooAbsArg& inArg,
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 RooCmdArg& arg9)
{
RooLinkedList args ;
args.Add((TObject*)&arg1) ;
args.Add((TObject*)&arg2) ;
args.Add((TObject*)&arg3) ;
args.Add((TObject*)&arg4) ;
args.Add((TObject*)&arg5) ;
args.Add((TObject*)&arg6) ;
args.Add((TObject*)&arg7) ;
args.Add((TObject*)&arg8) ;
args.Add((TObject*)&arg9) ;
// Select the pdf-specific commands
RooCmdConfig pc("RooWorkspace::import(" + std::string(GetName()) + ")");
pc.defineString("conflictSuffix","RenameConflictNodes",0) ;
pc.defineInt("renameConflictOrig","RenameConflictNodes",0,0) ;
pc.defineString("allSuffix","RenameAllNodes",0) ;
pc.defineString("allVarsSuffix","RenameAllVariables",0) ;
pc.defineString("allVarsExcept","RenameAllVariables",1) ;
pc.defineString("varChangeIn","RenameVar",0,"",true) ;
pc.defineString("varChangeOut","RenameVar",1,"",true) ;
pc.defineString("factoryTag","FactoryTag",0) ;
pc.defineInt("useExistingNodes","RecycleConflictNodes",0,0) ;
pc.defineInt("silence","Silence",0,0) ;
pc.defineInt("noRecursion","NoRecursion",0,0) ;
pc.defineMutex("RenameConflictNodes","RenameAllNodes") ;
pc.defineMutex("RenameConflictNodes","RecycleConflictNodes") ;
pc.defineMutex("RenameAllNodes","RecycleConflictNodes") ;
pc.defineMutex("RenameVariable","RenameAllVariables") ;
// Process and check varargs
pc.process(args) ;
if (!pc.ok(true)) {
return true ;
}
// Decode renaming logic into suffix string and boolean for conflictOnly mode
const char* suffixC = pc.getString("conflictSuffix") ;
const char* suffixA = pc.getString("allSuffix") ;
const char* suffixV = pc.getString("allVarsSuffix") ;
const char* exceptVars = pc.getString("allVarsExcept") ;
const char* varChangeIn = pc.getString("varChangeIn") ;
const char* varChangeOut = pc.getString("varChangeOut") ;
bool renameConflictOrig = pc.getInt("renameConflictOrig") ;
Int_t useExistingNodes = pc.getInt("useExistingNodes") ;
Int_t silence = pc.getInt("silence") ;
Int_t noRecursion = pc.getInt("noRecursion") ;
// Turn zero length strings into null pointers
if (suffixC && strlen(suffixC)==0) suffixC = nullptr ;
if (suffixA && strlen(suffixA)==0) suffixA = nullptr ;
bool conflictOnly = suffixA ? false : true ;
const char* suffix = suffixA ? suffixA : suffixC ;
// Process any change in variable names
std::map<string,string> varMap ;
if (strlen(varChangeIn)>0) {
// Parse comma separated lists into map<string,string>
const std::vector<std::string> tokIn = ROOT::Split(varChangeIn, ", ", /*skipEmpty= */ true);
const std::vector<std::string> tokOut = ROOT::Split(varChangeOut, ", ", /*skipEmpty= */ true);
for (unsigned int i=0; i < tokIn.size(); ++i) {
varMap.insert(std::make_pair(tokIn[i], tokOut[i]));
}
assert(tokIn.size() == tokOut.size());
}
// Process RenameAllVariables argument if specified
// First convert exception list if provided
std::set<string> exceptVarNames ;
if (exceptVars && strlen(exceptVars)) {
const std::vector<std::string> toks = ROOT::Split(exceptVars, ", ", /*skipEmpty= */ true);
exceptVarNames.insert(toks.begin(), toks.end());
}
if (suffixV != nullptr && strlen(suffixV)>0) {
std::unique_ptr<RooArgSet> vars{inArg.getVariables()};
for (const auto v : *vars) {
if (exceptVarNames.find(v->GetName())==exceptVarNames.end()) {
varMap[v->GetName()] = Form("%s_%s",v->GetName(),suffixV) ;
}
}
}
// Scan for overlaps with current contents
RooAbsArg* wsarg = _allOwnedNodes.find(inArg.GetName()) ;
// Check for factory specification match
const char* tagIn = inArg.getStringAttribute("factory_tag") ;
const char* tagWs = wsarg ? wsarg->getStringAttribute("factory_tag") : nullptr ;
bool factoryMatch = (tagIn && tagWs && !strcmp(tagIn,tagWs)) ;
if (factoryMatch) {
((RooAbsArg&)inArg).setAttribute("RooWorkspace::Recycle") ;
}
if (!suffix && wsarg && !useExistingNodes && !(inArg.isFundamental() && !varMap[inArg.GetName()].empty())) {
if (!factoryMatch) {
if (wsarg!=&inArg) {
coutE(ObjectHandling) << "RooWorkSpace::import(" << GetName() << ") ERROR importing object named " << inArg.GetName()
<< ": another instance with same name already in the workspace and no conflict resolution protocol specified" << std::endl ;
return true ;
} else {
if (!silence) {
coutI(ObjectHandling) << "RooWorkSpace::import(" << GetName() << ") Object " << inArg.GetName() << " is already in workspace!" << std::endl ;
}
return true ;
}
} else {
if(!silence) {
coutI(ObjectHandling) << "RooWorkSpace::import(" << GetName() << ") Recycling existing object " << inArg.GetName() << " created with identical factory specification" << std::endl ;
}
}
}
// Make list of conflicting nodes
RooArgSet conflictNodes ;
RooArgSet branchSet ;
if (noRecursion) {
branchSet.add(inArg) ;
} else {
inArg.branchNodeServerList(&branchSet) ;
}
for (const auto branch : branchSet) {
RooAbsArg* wsbranch = _allOwnedNodes.find(branch->GetName()) ;
if (wsbranch && wsbranch!=branch && !branch->getAttribute("RooWorkspace::Recycle") && !useExistingNodes) {
conflictNodes.add(*branch) ;
}
}
// Terminate here if there are conflicts and no resolution protocol
if (!conflictNodes.empty() && !suffix && !useExistingNodes) {
coutE(ObjectHandling) << "RooWorkSpace::import(" << GetName() << ") ERROR object named " << inArg.GetName() << ": component(s) "
<< conflictNodes << " already in the workspace and no conflict resolution protocol specified" << std::endl ;
return true ;
}
// Now create a working copy of the incoming object tree
RooArgSet cloneSet;
cloneSet.useHashMapForFind(true); // Accelerate finding
RooArgSet(inArg).snapshot(cloneSet, !noRecursion);
RooAbsArg* cloneTop = cloneSet.find(inArg.GetName()) ;
// Mark all nodes for renaming if we are not in conflictOnly mode
if (!conflictOnly) {
conflictNodes.removeAll() ;
conflictNodes.add(branchSet) ;
}
// Mark nodes that are to be renamed with special attribute
string topName2 = cloneTop->GetName() ;
if (!renameConflictOrig) {
// Mark all nodes to be imported for renaming following conflict resolution protocol
for (const auto cnode : conflictNodes) {
RooAbsArg* cnode2 = cloneSet.find(cnode->GetName()) ;
string origName = cnode2->GetName() ;
cnode2->SetName(Form("%s_%s",cnode2->GetName(),suffix)) ;
cnode2->SetTitle(Form("%s (%s)",cnode2->GetTitle(),suffix)) ;
string tag = Form("ORIGNAME:%s",origName.c_str()) ;
cnode2->setAttribute(tag.c_str()) ;
if (!cnode2->getStringAttribute("origName")) {
cnode2->setStringAttribute("origName",origName.c_str());
}
// Save name of new top level node for later use
if (cnode2==cloneTop) {
topName2 = cnode2->GetName() ;
}
if (!silence) {
coutI(ObjectHandling) << "RooWorkspace::import(" << GetName()
<< ") Resolving name conflict in workspace by changing name of imported node "
<< origName << " to " << cnode2->GetName() << std::endl ;
}
}
} else {
// Rename all nodes already in the workspace to 'clear the way' for the imported nodes
for (const auto cnode : conflictNodes) {
string origName = cnode->GetName() ;
RooAbsArg* wsnode = _allOwnedNodes.find(origName.c_str()) ;
if (wsnode) {
if (!wsnode->getStringAttribute("origName")) {
wsnode->setStringAttribute("origName",wsnode->GetName()) ;
}
if (!_allOwnedNodes.find(Form("%s_%s",cnode->GetName(),suffix))) {
wsnode->SetName(Form("%s_%s",cnode->GetName(),suffix)) ;
wsnode->SetTitle(Form("%s (%s)",cnode->GetTitle(),suffix)) ;
} else {
// Name with suffix already taken, add additional suffix
for (unsigned int n=1; true; ++n) {
string newname = Form("%s_%s_%d",cnode->GetName(),suffix,n) ;
if (!_allOwnedNodes.find(newname.c_str())) {
wsnode->SetName(newname.c_str()) ;
wsnode->SetTitle(Form("%s (%s %d)",cnode->GetTitle(),suffix,n)) ;
break ;
}
}
}
if (!silence) {
coutI(ObjectHandling) << "RooWorkspace::import(" << GetName()
<< ") Resolving name conflict in workspace by changing name of original node "
<< origName << " to " << wsnode->GetName() << std::endl ;
}
} else {
coutW(ObjectHandling) << "RooWorkspace::import(" << GetName() << ") Internal error: expected to find existing node "
<< origName << " to be renamed, but didn't find it..." << std::endl ;
}
}
}
// Process any change in variable names
if (strlen(varChangeIn)>0 || (suffixV && strlen(suffixV)>0)) {
// Process all changes in variable names
for (const auto cnode : cloneSet) {
if (varMap.find(cnode->GetName())!=varMap.end()) {
string origName = cnode->GetName() ;
cnode->SetName(varMap[cnode->GetName()].c_str()) ;
string tag = Form("ORIGNAME:%s",origName.c_str()) ;
cnode->setAttribute(tag.c_str()) ;
if (!cnode->getStringAttribute("origName")) {
cnode->setStringAttribute("origName",origName.c_str()) ;
}
if (!silence) {
coutI(ObjectHandling) << "RooWorkspace::import(" << GetName() << ") Changing name of variable "
<< origName << " to " << cnode->GetName() << " on request" << std::endl ;
}
if (cnode==cloneTop) {
topName2 = cnode->GetName() ;
}
}
}
}
// Now clone again with renaming effective
RooArgSet cloneSet2;
cloneSet2.useHashMapForFind(true); // Faster finding
RooArgSet(*cloneTop).snapshot(cloneSet2, !noRecursion);
RooAbsArg* cloneTop2 = cloneSet2.find(topName2.c_str()) ;
// Make final check list of conflicting nodes
RooArgSet conflictNodes2 ;
RooArgSet branchSet2 ;
for (const auto branch2 : branchSet2) {
if (_allOwnedNodes.find(branch2->GetName())) {
conflictNodes2.add(*branch2) ;
}
}
// Terminate here if there are conflicts and no resolution protocol
if (!conflictNodes2.empty()) {
coutE(ObjectHandling) << "RooWorkSpace::import(" << GetName() << ") ERROR object named " << inArg.GetName() << ": component(s) "
<< conflictNodes2 << " cause naming conflict after conflict resolution protocol was executed" << std::endl ;
return true ;
}
// Perform any auxiliary imports at this point
for (const auto node : cloneSet2) {
if (node->importWorkspaceHook(*this)) {
coutE(ObjectHandling) << "RooWorkSpace::import(" << GetName() << ") ERROR object named " << node->GetName()
<< " has an error in importing in one or more of its auxiliary objects, aborting" << std::endl ;
return true ;
}
}
RooArgSet recycledNodes ;
RooArgSet nodesToBeDeleted ;
for (const auto node : cloneSet2) {
if (_autoClass) {
if (!_classes.autoImportClass(node->IsA())) {
coutW(ObjectHandling) << "RooWorkspace::import(" << GetName() << ") WARNING: problems import class code of object "
<< node->ClassName() << "::" << node->GetName() << ", reading of workspace will require external definition of class" << std::endl ;
}
}
// Point expensiveObjectCache to copy in this workspace
RooExpensiveObjectCache& oldCache = node->expensiveObjectCache() ;
node->setExpensiveObjectCache(_eocache) ;
_eocache.importCacheObjects(oldCache,node->GetName(),true) ;
// Check if node is already in workspace (can only happen for variables or identical instances, unless RecycleConflictNodes is specified)
RooAbsArg* wsnode = _allOwnedNodes.find(node->GetName()) ;
if (wsnode) {
// Do not import node, add not to list of nodes that require reconnection
if (!silence && useExistingNodes) {
coutI(ObjectHandling) << "RooWorkspace::import(" << GetName() << ") using existing copy of " << node->ClassName()
<< "::" << node->GetName() << " for import of " << cloneTop2->ClassName() << "::"
<< cloneTop2->GetName() << std::endl ;
}
recycledNodes.add(*_allOwnedNodes.find(node->GetName())) ;
// Delete clone of incoming node
nodesToBeDeleted.addOwned(std::unique_ptr<RooAbsArg>{node});
//cout << "WV: recycling existing node " << existingNode << " = " << existingNode->GetName() << " for imported node " << node << std::endl ;
} else {
// Import node
if (!silence) {
coutI(ObjectHandling) << "RooWorkspace::import(" << GetName() << ") importing " << node->ClassName() << "::"
<< node->GetName() << std::endl ;
}
_allOwnedNodes.addOwned(std::unique_ptr<RooAbsArg>{node});
node->setWorkspace(*this);
if (_openTrans) {
_sandboxNodes.add(*node) ;
} else {
if (_dir && node->IsA() != RooConstVar::Class()) {
_dir->InternalAppend(node) ;
}
}
}
}
// Reconnect any nodes that need to be
if (!recycledNodes.empty()) {
for (const auto node : cloneSet2) {
node->redirectServers(recycledNodes) ;
}
}
cloneSet2.releaseOwnership() ;
return false ;
}
////////////////////////////////////////////////////////////////////////////////
/// Import a dataset (RooDataSet or RooDataHist) into the workspace. The workspace will contain a copy of the data.
/// The dataset and its variables can be renamed upon insertion with the options below
///
/// <table>
/// <tr><th> Accepted arguments
/// <tr><td> `Rename(const char* suffix)` <td> Rename dataset upon insertion
/// <tr><td> `RenameVariable(const char* inputName, const char* outputName)` <td> Change names of observables in dataset upon insertion
/// <tr><td> `Silence` <td> Be quiet, except in case of errors
/// \note From python, use `Import()`, since `import` is a reserved keyword.
/// \return due to historical reasons: false (0) on success and true (1) on failure
bool RooWorkspace::import(RooAbsData const& inData,
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 RooCmdArg& arg9)
{
RooLinkedList args ;
args.Add((TObject*)&arg1) ;
args.Add((TObject*)&arg2) ;
args.Add((TObject*)&arg3) ;
args.Add((TObject*)&arg4) ;
args.Add((TObject*)&arg5) ;
args.Add((TObject*)&arg6) ;
args.Add((TObject*)&arg7) ;
args.Add((TObject*)&arg8) ;
args.Add((TObject*)&arg9) ;
// Select the pdf-specific commands
RooCmdConfig pc(Form("RooWorkspace::import(%s)",GetName())) ;
pc.defineString("dsetName","Rename",0,"") ;
pc.defineString("varChangeIn","RenameVar",0,"",true) ;
pc.defineString("varChangeOut","RenameVar",1,"",true) ;
pc.defineInt("embedded","Embedded",0,0) ;
pc.defineInt("silence","Silence",0,0) ;
// Process and check varargs
pc.process(args) ;
if (!pc.ok(true)) {
return true ;
}
// Decode renaming logic into suffix string and boolean for conflictOnly mode
const char* dsetName = pc.getString("dsetName") ;
const char* varChangeIn = pc.getString("varChangeIn") ;
const char* varChangeOut = pc.getString("varChangeOut") ;
bool embedded = pc.getInt("embedded") ;
Int_t silence = pc.getInt("silence") ;
if (!silence)
coutI(ObjectHandling) << "RooWorkspace::import(" << GetName() << ") importing dataset " << inData.GetName() << std::endl ;
// Transform empty string into null pointer
if (dsetName && strlen(dsetName)==0) {
dsetName=nullptr ;
}
RooLinkedList& dataList = embedded ? _embeddedDataList : _dataList ;
if (dataList.size() > 50 && dataList.getHashTableSize() == 0) {
// When the workspaces get larger, traversing the linked list becomes a bottleneck:
dataList.setHashTableSize(200);
}
// Check that no dataset with target name already exists
if (dsetName && dataList.FindObject(dsetName)) {
coutE(ObjectHandling) << "RooWorkspace::import(" << GetName() << ") ERROR dataset with name " << dsetName << " already exists in workspace, import aborted" << std::endl ;
return true ;
}
if (!dsetName && dataList.FindObject(inData.GetName())) {
coutE(ObjectHandling) << "RooWorkspace::import(" << GetName() << ") ERROR dataset with name " << inData.GetName() << " already exists in workspace, import aborted" << std::endl ;
return true ;
}
// Rename dataset if required
RooAbsData* clone ;
if (dsetName) {
if (!silence)
coutI(ObjectHandling) << "RooWorkSpace::import(" << GetName() << ") changing name of dataset from " << inData.GetName() << " to " << dsetName << std::endl ;
clone = static_cast<RooAbsData*>(inData.Clone(dsetName)) ;
} else {
clone = static_cast<RooAbsData*>(inData.Clone(inData.GetName())) ;
}
// Process any change in variable names
if (strlen(varChangeIn)>0) {
// Parse comma separated lists of variable name changes
const std::vector<std::string> tokIn = ROOT::Split(varChangeIn, ",");
const std::vector<std::string> tokOut = ROOT::Split(varChangeOut, ",");
for (unsigned int i=0; i < tokIn.size(); ++i) {
if (!silence)
coutI(ObjectHandling) << "RooWorkSpace::import(" << GetName() << ") changing name of dataset observable " << tokIn[i] << " to " << tokOut[i] << std::endl ;
clone->changeObservableName(tokIn[i].c_str(), tokOut[i].c_str());
}
}
// Now import the dataset observables, unless dataset is embedded
if (!embedded) {
for(RooAbsArg* carg : *clone->get()) {
if (!arg(carg->GetName())) {
import(*carg) ;
}
}
}
dataList.Add(clone) ;
if (_dir) {
_dir->InternalAppend(clone) ;
}
// Set expensive object cache of dataset internal buffers to that of workspace
for(RooAbsArg* carg : *clone->get()) {
carg->setExpensiveObjectCache(expensiveObjectCache()) ;
}
return false ;
}
////////////////////////////////////////////////////////////////////////////////
/// Define a named RooArgSet with given constituents. If importMissing is true, any constituents
/// of aset that are not in the workspace will be imported, otherwise an error is returned
/// for missing components
/// \return due to historical reasons: false (0) on success and true (1) on failure
bool RooWorkspace::defineSet(const char* name, const RooArgSet& aset, bool importMissing)
{
// Check if set was previously defined, if so print warning
map<string,RooArgSet>::iterator i = _namedSets.find(name) ;
if (i!=_namedSets.end()) {
coutW(InputArguments) << "RooWorkspace::defineSet(" << GetName() << ") WARNING redefining previously defined named set " << name << std::endl ;
}
RooArgSet wsargs ;
// Check all constituents of provided set
for (RooAbsArg* sarg : aset) {
// If missing, either import or report error
if (!arg(sarg->GetName())) {
if (importMissing) {
import(*sarg) ;
} else {
coutE(InputArguments) << "RooWorkspace::defineSet(" << GetName() << ") ERROR set constituent \"" << sarg->GetName()
<< "\" is not in workspace and importMissing option is disabled" << std::endl ;
return true ;
}
}
wsargs.add(*arg(sarg->GetName())) ;
}
// Install named set
_namedSets[name].removeAll() ;
_namedSets[name].add(wsargs) ;
return false ;
}
//_____________________________________________________________________________
// \return due to historical reasons: false (0) on success (always)
bool RooWorkspace::defineSetInternal(const char *name, const RooArgSet &aset)
{
// Define a named RooArgSet with given constituents. If importMissing is true, any constituents
// of aset that are not in the workspace will be imported, otherwise an error is returned
// for missing components
// Check if set was previously defined, if so print warning
map<string, RooArgSet>::iterator i = _namedSets.find(name);
if (i != _namedSets.end()) {
coutW(InputArguments) << "RooWorkspace::defineSet(" << GetName()
<< ") WARNING redefining previously defined named set " << name << std::endl;
}
// Install named set
_namedSets[name].removeAll();
_namedSets[name].add(aset);
return false;
}
////////////////////////////////////////////////////////////////////////////////
/// Define a named set in the workspace through a comma separated list of
/// names of objects already in the workspace
/// \return due to historical reasons: false (0) on success and true (1) on failure
bool RooWorkspace::defineSet(const char* name, const char* contentList)
{
// Check if set was previously defined, if so print warning
map<string,RooArgSet>::iterator i = _namedSets.find(name) ;
if (i!=_namedSets.end()) {
coutW(InputArguments) << "RooWorkspace::defineSet(" << GetName() << ") WARNING redefining previously defined named set " << name << std::endl ;
}
RooArgSet wsargs ;
// Check all constituents of provided set
for (const std::string& token : ROOT::Split(contentList, ",")) {
// If missing, either import or report error
if (!arg(token.c_str())) {
coutE(InputArguments) << "RooWorkspace::defineSet(" << GetName() << ") ERROR proposed set constituent \"" << token
<< "\" is not in workspace" << std::endl ;
return true ;
}
wsargs.add(*arg(token.c_str())) ;
}
// Install named set
_namedSets[name].removeAll() ;
_namedSets[name].add(wsargs) ;
return false ;
}
////////////////////////////////////////////////////////////////////////////////
/// Define a named set in the workspace through a comma separated list of
/// names of objects already in the workspace
/// \return due to historical reasons: false (0) on success and true (1) on failure
bool RooWorkspace::extendSet(const char* name, const char* newContents)
{
RooArgSet wsargs ;
// Check all constituents of provided set
for (const std::string& token : ROOT::Split(newContents, ",")) {
// If missing, either import or report error
if (!arg(token.c_str())) {
coutE(InputArguments) << "RooWorkspace::defineSet(" << GetName() << ") ERROR proposed set constituent \"" << token
<< "\" is not in workspace" << std::endl ;
return true ;
}
wsargs.add(*arg(token.c_str())) ;
}
// Extend named set
_namedSets[name].add(wsargs,true) ;
return false ;
}
////////////////////////////////////////////////////////////////////////////////
/// Return pointer to previously defined named set with given nmame
/// If no such set is found a null pointer is returned
const RooArgSet* RooWorkspace::set(RooStringView name)
{
std::map<string,RooArgSet>::iterator i = _namedSets.find(name.c_str());
return (i!=_namedSets.end()) ? &(i->second) : nullptr;
}
////////////////////////////////////////////////////////////////////////////////
/// Rename set to a new name
/// \return due to historical reasons: false (0) on success and true (1) on failure
bool RooWorkspace::renameSet(const char* name, const char* newName)
{
// First check if set exists
if (!set(name)) {
coutE(InputArguments) << "RooWorkspace::renameSet(" << GetName() << ") ERROR a set with name " << name
<< " does not exist" << std::endl ;
return true ;
}
// Check if no set exists with new name
if (set(newName)) {
coutE(InputArguments) << "RooWorkspace::renameSet(" << GetName() << ") ERROR a set with name " << newName
<< " already exists" << std::endl ;
return true ;
}
// Copy entry under 'name' to 'newName'
_namedSets[newName].add(_namedSets[name]) ;
// Remove entry under old name
_namedSets.erase(name) ;
return false ;
}