-
Notifications
You must be signed in to change notification settings - Fork 389
/
Combine.cc
1316 lines (1201 loc) · 66.1 KB
/
Combine.cc
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
/**************************************
Simple multiChannel significance & limit calculator
***************************************/
#include "../interface/Combine.h"
#include <cstring>
#include <cerrno>
#include <iostream>
#include <cstdlib>
#include <cmath>
#include <vector>
#include <string>
#include <stdexcept>
#include <algorithm>
#include <unistd.h>
#include <errno.h>
#include <sstream>
#include <TCanvas.h>
#include <TFile.h>
#include <TFileCacheRead.h>
#include <TGraphErrors.h>
#include <TIterator.h>
#include <TLine.h>
#include <TMath.h>
#include <TString.h>
#include <TSystem.h>
#include <TStopwatch.h>
#include <TTree.h>
#include <RooAbsData.h>
#include <RooAbsPdf.h>
#include <RooArgSet.h>
#include <RooCustomizer.h>
#include <RooDataHist.h>
#include <RooDataSet.h>
#include <RooFitResult.h>
#include <RooMsgService.h>
#include <RooPlot.h>
#include <RooRandom.h>
#include <RooRealVar.h>
#include <RooUniform.h>
#include <RooGaussian.h>
#include <RooWorkspace.h>
#include <RooCategory.h>
#include <RooStats/HLFactory.h>
#include <RooStats/RooStatsUtils.h>
#include <RooStats/ModelConfig.h>
#include <boost/filesystem.hpp>
#include <boost/program_options.hpp>
#include <boost/algorithm/string/predicate.hpp>
#include <boost/algorithm/string.hpp>
#include <regex>
#include "../interface/LimitAlgo.h"
#include "../interface/utils.h"
#include "../interface/CloseCoutSentry.h"
#include "../interface/RooSimultaneousOpt.h"
#include "../interface/ToyMCSamplerOpt.h"
#include "../interface/AsimovUtils.h"
#include "../interface/CascadeMinimizer.h"
#include "../interface/ProfilingTools.h"
#include "../interface/RooMultiPdf.h"
#include "../interface/CMSHistFunc.h"
#include "../interface/CMSHistSum.h"
#include "../interface/CombineLogger.h"
using namespace RooStats;
using namespace RooFit;
using namespace std;
LimitAlgo * algo, * hintAlgo;
Float_t t_cpu_, t_real_;
Float_t g_quantileExpected_ = -1.0;
TDirectory *outputFile = 0;
TDirectory *writeToysHere = 0;
TDirectory *readToysFromHere = 0;
int verbose = 1;
bool withSystematics = 1;
bool expectSignalSet_ = false;
bool doSignificance_ = 0;
bool expectSignalSet = 0;
bool lowerLimit_ = 0;
float cl = 0.95;
bool bypassFrequentistFit_ = false;
bool g_fillTree_ = true;
TTree *Combine::tree_ = 0;
std::string setPhysicsModelParameterExpression_ = "";
std::string setPhysicsModelParameterRangeExpression_ = "";
std::string defineBackgroundOnlyModelParameterExpression_ = "";
std::string Combine::trackParametersNameString_="";
std::string Combine::trackErrorsNameString_="";
std::string Combine::textToWorkspaceString_="";
std::vector<std::pair<RooAbsReal*,float> > Combine::trackedParametersMap_;
std::vector<std::pair<RooRealVar*,float> > Combine::trackedErrorsMap_;
Combine::Combine() :
statOptions_("Common statistics options"),
ioOptions_("Common input-output options"),
miscOptions_("Common miscellaneous options"),
rMin_(std::numeric_limits<float>::quiet_NaN()),
rMax_(std::numeric_limits<float>::quiet_NaN()) {
namespace po = boost::program_options;
statOptions_.add_options()
//("systematics,S", po::value<bool>(&withSystematics)->default_value(true), "Include constrained systematic uncertainties, -S 0 will ignore systematics constraint terms in the datacard.")
("cl,C", po::value<float>(&cl)->default_value(0.95), "Confidence Level")
("rMin", po::value<float>(&rMin_), "Override minimum value for signal strength (default is 0)")
("rMax", po::value<float>(&rMax_), "Override maximum value for signal strength (default is 20)")
("prior", po::value<std::string>(&prior_)->default_value("flat"), "Prior to use, for methods that require it and if it's not already in the input file: 'flat' (default), '1/sqrt(r)', or a custom expression that uses @0 as the parameter of interest")
("significance", "Compute significance instead of upper limit (works only for some methods)")
("lowerLimit", "Compute the lower limit instead of the upper limit (works only for some methods)")
("hintStatOnly", "Ignore systematics when computing the hint")
("toysNoSystematics", "Generate all toys with the central value of the nuisance parameters, without fluctuating them")
("toysFrequentist", "Generate all toys in the frequentist way. Note that this affects the toys generated by option '-t' that happen in the main loop, not the ones within the Hybrid(New) algorithm.")
("expectSignal", po::value<float>(&expectSignal_)->default_value(0.), "If set to non-zero, generate *signal* toys instead of background ones, with the specified signal strength.")
("expectSignalMass", po::value<float>(&expectSignalMass_)->default_value(-99.), "If set to non-zero, generate *signal* toys instead of background ones, with the specified mass.")
("unbinned,U", "Generate unbinned datasets instead of binned ones (works only for extended pdfs)")
("generateBinnedWorkaround", "Make binned datasets generating unbinned ones and then binnning them. Workaround for a bug in RooFit.")
("setParameters", po::value<string>(&setPhysicsModelParameterExpression_)->default_value(""), "Set the values of relevant physics model parameters. Give a comma separated list of parameter value assignments. Example: CV=1.0,CF=1.0")
("setParameterRanges", po::value<string>(&setPhysicsModelParameterRangeExpression_)->default_value(""), "Set the range of relevant physics model parameters. Give a colon separated list of parameter ranges. Example: CV=0.0,2.0:CF=0.0,5.0")
("defineBackgroundOnlyModelParameters", po::value<string>(&defineBackgroundOnlyModelParameterExpression_)->default_value(""), "If no background only (null) model is explicitly provided in physics model, one will be defined as these values of the POIs (default is r=0)")
("redefineSignalPOIs", po::value<string>(&redefineSignalPOIs_)->default_value(""), "Redefines the POIs to be this comma-separated list of variables from the workspace.")
("freezeParameters", po::value<string>(&freezeNuisances_)->default_value(""), "Set as constant all these parameters. use --freezeParameters allConstrainedNuisances to freeze all constrained nuisance parameters (i.e doesn't include rateParams etc)")
("freezeNuisanceGroups", po::value<string>(&freezeNuisanceGroups_)->default_value(""), "Set as constant all these groups of nuisance parameters.")
("freezeWithAttributes", po::value<string>(&freezeWithAttributes_)->default_value(""), "Set as constant all variables carrying one of these attribute strings.")
;
ioOptions_.add_options()
("saveWorkspace", "Save workspace to output root file")
("workspaceName,w", po::value<std::string>(&workspaceName_)->default_value("w"), "Workspace name, when reading it from or writing it to a rootfile.")
("snapshotName", po::value<std::string>(&snapshotName_)->default_value(""), "Default snapshot name for pre-fit snapshot for reading or writing to workspace")
("modelConfigName", po::value<std::string>(&modelConfigName_)->default_value("ModelConfig"), "ModelConfig name, when reading it from or writing it to a rootfile.")
("modelConfigNameB", po::value<std::string>(&modelConfigNameB_)->default_value("%s_bonly"), "Name of the ModelConfig for b-only hypothesis.\n"
"If not present, it will be made from the singal model taking zero signal strength.\n"
"A '%s' in the name will be replaced with the modelConfigName.")
("bypassFrequentistFit", "Skip actual minimization for constructing frequentist toys (eg because loaded snapshot already corresponds to desired postfit)")
("overrideSnapshotMass", "Override MH loaded from a snapshot with the one passed on the command line")
("validateModel,V", "Perform some sanity checks on the model and abort if they fail.")
("saveToys", "Save results of toy MC in output file")
("floatAllNuisances", po::value<bool>(&floatAllNuisances_)->default_value(false), "Make all nuisance parameters floating")
("floatParameters", po::value<string>(&floatNuisances_)->default_value(""), "Set to floating these parameters (note freeze will take priority over float), also accepts regexp with syntax 'rgx{<my regexp>}' or 'var{<my regexp>}'")
("freezeAllGlobalObs", po::value<bool>(&freezeAllGlobalObs_)->default_value(true), "Make all global observables constant")
;
miscOptions_.add_options()
("optimizeSimPdf", po::value<bool>(&optSimPdf_)->default_value(true), "Turn on special optimizations of RooSimultaneous. On by default, you can turn it off if it doesn't work for your workspace.")
("noMCbonly", po::value<bool>(&noMCbonly_)->default_value(false), "Don't create a background-only modelConfig")
("noDefaultPrior", po::value<bool>(&noDefaultPrior_)->default_value(false), "Don't create a default uniform prior")
("rebuildSimPdf", po::value<bool>(&rebuildSimPdf_)->default_value(false), "Rebuild simultaneous pdf from scratch to make sure constraints are correct (not needed in CMS workspaces)")
("compile", "Compile expressions instead of interpreting them")
("tempDir", po::value<bool>(&makeTempDir_)->default_value(false), "Run the program from a temporary directory (automatically on for text datacards or if 'compile' is activated)")
("guessGenMode", "Guess if to generate binned or unbinned based on dataset")
("genBinnedChannels", po::value<std::string>(&genAsBinned_)->default_value(genAsBinned_), "Flag the given channels to be generated binned (irrespectively of how they were flagged at workspace creation)")
("genUnbinnedChannels", po::value<std::string>(&genAsUnbinned_)->default_value(genAsUnbinned_), "Flag the given channels to be generated unbinned (irrespectively of how they were flagged at workspace creation)")
("text2workspace", boost::program_options::value<std::string>(&textToWorkspaceString_)->default_value(""), "Pass along options to text2workspace (default = none)")
("trackParameters", boost::program_options::value<std::string>(&trackParametersNameString_)->default_value(""), "Keep track of parameters in workspace, also accepts regexp with syntax 'rgx{<my regexp>}' (default = none)")
("trackErrors", boost::program_options::value<std::string>(&trackErrorsNameString_)->default_value(""), "Keep track of errors on parameters in workspace, also accepts regexp with syntax 'rgx{<my regexp>}' (default = none)")
;
}
void Combine::applyOptions(const boost::program_options::variables_map &vm) {
/*if(withSystematics) {
std::cout << ">>> including systematics" << std::endl;
} else {
std::cout << ">>> no systematics included" << std::endl;
}
*/
unbinned_ = vm.count("unbinned");
generateBinnedWorkaround_ = vm.count("generateBinnedWorkaround");
if (unbinned_ && generateBinnedWorkaround_) throw std::logic_error("You can't set generateBinnedWorkaround and unbinned options at the same time");
guessGenMode_ = vm.count("guessGenMode");
compiledExpr_ = vm.count("compile"); if (compiledExpr_) makeTempDir_ = true;
doSignificance_ = vm.count("significance");
lowerLimit_ = vm.count("lowerLimit");
hintUsesStatOnly_ = vm.count("hintStatOnly");
saveWorkspace_ = vm.count("saveWorkspace");
toysNoSystematics_ = vm.count("toysNoSystematics");
//if (!withSystematics) toysNoSystematics_ = true; // if no systematics, also don't expect them for the toys
toysFrequentist_ = vm.count("toysFrequentist");
if (toysNoSystematics_ && toysFrequentist_) throw std::logic_error("You can't set toysNoSystematics and toysFrequentist options at the same time");
if (modelConfigNameB_.find("%s") != std::string::npos) {
char modelBName[1024];
sprintf(modelBName, modelConfigNameB_.c_str(), modelConfigName_.c_str());
modelConfigNameB_ = modelBName;
}
bypassFrequentistFit_ = vm.count("bypassFrequentistFit");
overrideSnapshotMass_ = vm.count("overrideSnapshotMass");
mass_ = vm["mass"].as<float>();
saveToys_ = vm.count("saveToys");
validateModel_ = vm.count("validateModel");
const std::string &method = vm["method"].as<std::string>();
if (!(vm["expectSignal"].defaulted())) expectSignalSet_=true;
else expectSignalSet_=false;
if (method == "MultiDimFit" || ( method == "FitDiagnostics" && vm.count("justFit")) || method == "MarkovChainMC") {
//CMSDAS new default,
if (vm["noMCbonly"].defaulted()) noMCbonly_ = 1;
if (vm["noDefaultPrior"].defaulted()) noDefaultPrior_ = 1;
}
if (!vm["prior"].defaulted()) noDefaultPrior_ = 0;
if( vm.count("LoadLibrary") ) {
librariesToLoad_ = vm["LoadLibrary"].as<std::vector<std::string> >();
}
if (vm.count("keyword-value") ) {
modelPoints_ = vm["keyword-value"].as<std::vector<std::string> >();
}
makeToyGenSnapshot_ = (method == "FitDiagnostics" && !vm.count("justFit"));
}
std::string Combine::parseRegex(std::string instr, const RooArgSet *nuisances, RooWorkspace *w) {
// expand regexps inside the "rgx{}" option
while (instr.find("rgx{") != std::string::npos) {
size_t pos1 = instr.find("rgx{");
size_t pos2 = instr.find("}",pos1);
std::string prestr = instr.substr(0,pos1);
std::string poststr = instr.substr(pos2+1,instr.size()-pos2);
std::string reg_esp = instr.substr(pos1+4,pos2-pos1-4);
std::regex rgx( reg_esp, std::regex::ECMAScript);
std::string matchingParams="";
std::unique_ptr<TIterator> iter(nuisances->createIterator());
for (RooAbsArg *a = (RooAbsArg*) iter->Next(); a != 0; a = (RooAbsArg*) iter->Next()) {
const std::string &target = a->GetName();
std::smatch match;
if (std::regex_match(target, match, rgx)) {
matchingParams = matchingParams + target + ",";
}
}
instr = prestr+matchingParams+poststr;
instr = boost::replace_all_copy(instr, ",,", ",");
}
// expand regexps inside the "var{}" option
while (instr.find("var{") != std::string::npos) {
size_t pos1 = instr.find("var{");
size_t pos2 = instr.find("}",pos1);
std::string prestr = instr.substr(0,pos1);
std::string poststr = instr.substr(pos2+1,instr.size()-pos2);
std::string reg_esp = instr.substr(pos1+4,pos2-pos1-4);
std::regex rgx( reg_esp, std::regex::ECMAScript);
std::string matchingParams="";
std::unique_ptr<TIterator> iter(w->componentIterator());
for (RooAbsArg *a = (RooAbsArg*) iter->Next(); a != 0; a = (RooAbsArg*) iter->Next()) {
if ( ! (a->IsA()->InheritsFrom(RooRealVar::Class()) || a->IsA()->InheritsFrom(RooCategory::Class()))) continue;
const std::string &target = a->GetName();
// std::cout<<"var "<<target<<std::endl;
std::smatch match;
if (std::regex_match(target, match, rgx)) {
matchingParams = matchingParams + target + ",";
}
}
instr = prestr+matchingParams+poststr;
instr = boost::replace_all_copy(instr, ",,", ",");
}
return instr;
}
bool Combine::mklimit(RooWorkspace *w, RooStats::ModelConfig *mc_s, RooStats::ModelConfig *mc_b, RooAbsData &data, double &limit, double &limitErr) {
TStopwatch timer;
bool ret = false;
try {
double hint = 0, hintErr = 0; bool hashint = false;
if (hintAlgo) {
if (hintUsesStatOnly_ ) { //&& withSystematics) {
//withSystematics = false;
hashint = hintAlgo->run(w, mc_s, mc_b, data, hint, hintErr, 0);
//withSystematics = true;
} else {
hashint = hintAlgo->run(w, mc_s, mc_b, data, hint, hintErr, 0);
}
w->loadSnapshot("clean");
}
limitErr = 0; // start with 0, as some algorithms don't compute it
ret = algo->run(w, mc_s, mc_b, data, limit, limitErr, (hashint ? &hint : 0));
} catch (std::exception &ex) {
std::cerr << "Caught exception " << ex.what() << std::endl;
return false;
}
/* if ((ret == false) && (verbose > 3)) {
std::cout << "Failed for method " << algo->name() << "\n";
std::cout << " --- DATA ---\n";
utils::printRAD(&data);
std::cout << " --- MODEL ---\n";
w->Print("V");
} */
timer.Stop(); t_cpu_ = timer.CpuTime()/60.; t_real_ = timer.RealTime()/60.;
printf("Done in %.2f min (cpu), %.2f min (real)\n", t_cpu_, t_real_);
return ret;
}
void Combine::run(TString hlfFile, const std::string &dataset, double &limit, double &limitErr, int &iToy, TTree *tree, int nToys) {
ToCleanUp garbageCollect; // use this to close and delete temporary files
TString tmpDir = "", tmpFile = "", pwd(gSystem->pwd());
if (makeTempDir_) {
tmpDir = "roostats-XXXXXX"; tmpFile = "model";
mkdtemp(const_cast<char *>(tmpDir.Data()));
gSystem->cd(tmpDir.Data());
garbageCollect.path = tmpDir.Data(); // request that we delete this dir when done
} else if (!hlfFile.EndsWith(".hlf") && !hlfFile.EndsWith(".root")) {
char buff[99]; snprintf(buff, 98, "roostats-XXXXXX");
int fd = mkstemp(buff); close(fd);
tmpFile = buff;
unlink(tmpFile); // this is to be deleted, since we'll use tmpFile+".root"
}
bool isTextDatacard = false, isBinary = hlfFile.EndsWith(".root");
TString fileToLoad = ((hlfFile[0] == '/' || hlfFile.Contains("://")) ? hlfFile : pwd+"/"+hlfFile);
if (!(fileToLoad.Contains("://") && isBinary) && !boost::filesystem::exists(fileToLoad.Data())) throw std::invalid_argument(("File "+fileToLoad+" does not exist").Data());
if (hlfFile.EndsWith(".hlf") || isBinary) {
// nothing to do
} else {
TString txtFile = fileToLoad.Data();
//TString options = TString::Format(" -m %f -D %s", mass_, dataset.c_str());
TString options = TString::Format(" -m %f", mass_);
//if (!withSystematics) options += " --stat ";
if (compiledExpr_) options += " --compiled ";
if (verbose > 1) options += TString::Format(" --verbose %d", verbose-1);
if (algo->name() == "FitDiagnostics" || algo->name() == "MultiDimFit") options += " --for-fits";
for(auto lib2l : librariesToLoad_ ) { options += TString::Format(" --LoadLibrary %s", lib2l.c_str() ); }
for(auto mp : modelPoints_) {options += TString::Format(" --keyword-value %s", mp.c_str() ) ;}
//-- Text mode: old default
//int status = gSystem->Exec("text2workspace.py "+options+" '"+txtFile+"' -o "+tmpFile+".hlf");
//isTextDatacard = true; fileToLoad = tmpFile+".hlf";
//-- Binary mode: new default
int status = gSystem->Exec("text2workspace.py "+options+" '"+txtFile+"' -b -o "+tmpFile+".root "+textToWorkspaceString_);
isBinary = true; fileToLoad = tmpFile+".root";
if (status != 0 || !boost::filesystem::exists(fileToLoad.Data())) {
throw std::invalid_argument("Failed to convert the input datacard from LandS to RooStats format. The lines above probably contain more information about the error.");
}
garbageCollect.file = fileToLoad;
}
if (getenv("CMSSW_BASE")) {
gSystem->AddIncludePath(TString::Format(" -I%s/src ", getenv("CMSSW_BASE")));
if (verbose > 3) std::cout << "Adding " << getenv("CMSSW_BASE") << "/src to include path" << std::endl;
}
if (getenv("ROOFITSYS")) {
gSystem->AddIncludePath(TString::Format(" -I%s/include ", getenv("ROOFITSYS")));
if (verbose > 3) std::cout << "Adding " << getenv("ROOFITSYS") << "/include to include path" << std::endl;
}
if (verbose <= 2) RooMsgService::instance().setGlobalKillBelow(RooFit::ERROR);
// Load the model, but going in a temporary directory to avoid polluting the current one with garbage from 'cexpr'
RooWorkspace *w = 0; RooStats::ModelConfig *mc = 0, *mc_bonly = 0;
std::unique_ptr<RooStats::HLFactory> hlf(nullptr);
if (isBinary) {
TFile *fIn = TFile::Open(fileToLoad);
if (!fIn) throw std::runtime_error(("Could not open file "+fileToLoad).Data());
garbageCollect.tfile = fIn; // request that we close this file when done
w = dynamic_cast<RooWorkspace *>(fIn->Get(workspaceName_.c_str()));
if (fIn->GetCacheRead()) {
fIn->GetCacheRead()->Close();
}
if (w == 0) {
std::cerr << "Could not find workspace '" << workspaceName_ << "' in file " << fileToLoad << std::endl; fIn->ls();
throw std::invalid_argument("Missing Workspace");
}
if (verbose > 3) { std::cout << "Input workspace '" << workspaceName_ << "': \n"; w->Print("V"); }
RooRealVar *MH = w->var("MH");
if (MH!=0) {
if (verbose > 2) std::cerr << "Setting variable 'MH' in workspace to the higgs mass " << mass_ << std::endl;
MH->setVal(mass_);
}
mc = dynamic_cast<RooStats::ModelConfig *>(w->genobj(modelConfigName_.c_str()));
mc_bonly = dynamic_cast<RooStats::ModelConfig *>(w->genobj(modelConfigNameB_.c_str()));
if (mc == 0) {
std::cerr << "Could not find ModelConfig '" << modelConfigName_ << "' in workspace '" << workspaceName_ << "' in file " << fileToLoad << std::endl;
throw std::invalid_argument("Missing ModelConfig");
} else if (verbose > 3) { std::cout << "Workspace has a ModelConfig for signal called '" << modelConfigName_ << "', with contents:\n"; mc->Print("V"); }
if (verbose > 3) { std::cout << "Input ModelConfig '" << modelConfigName_ << "': \n"; mc->Print("V"); }
const RooArgSet *POI = mc->GetParametersOfInterest();
if (POI == 0 || POI->getSize() == 0) throw std::invalid_argument("ModelConfig '"+modelConfigName_+"' does not define parameters of interest.");
if (POI->getSize() > 1) std::cerr << "ModelConfig '" << modelConfigName_ << "' defines more than one parameter of interest. This is not supported in some statistical methods." << std::endl;
if (mc->GetObservables() == 0) throw std::invalid_argument("ModelConfig '"+modelConfigName_+"' does not define observables.");
if (mc->GetPdf() == 0) throw std::invalid_argument("ModelConfig '"+modelConfigName_+"' does not define a pdf.");
if (auto pdf = dynamic_cast<RooSimultaneous*>(mc->GetPdf()); pdf!=nullptr && dynamic_cast<RooSimultaneousOpt*>(pdf)==nullptr) {
if (rebuildSimPdf_) {
pdf = utils::rebuildSimPdf(*mc->GetObservables(), pdf);
w->import(*pdf);
mc->SetPdf(*pdf);
}
if (optSimPdf_) {
RooSimultaneousOpt *optpdf = new RooSimultaneousOpt(*pdf, TString(mc->GetPdf()->GetName())+"_opt");
w->import(*optpdf);
mc->SetPdf(*optpdf);
}
}
if (expectSignalSet_ && POI->getSize() > 1 ) std::cerr << "ModelConfig '" << modelConfigName_ << "' defines more than one parameter of interest and you have set --expectSignal=" << expectSignal_ << ", which combine will likely interpret incorrectly. You should use --setParameters instead of --expectSignal." << std::endl;
if (mc_bonly == 0 && !noMCbonly_) {
std::cerr << "Missing background ModelConfig '" << modelConfigNameB_ << "' in workspace '" << workspaceName_ << "' in file " << fileToLoad << std::endl;
RooCustomizer make_model_s(*mc->GetPdf(),"_model_bonly_");
if (defineBackgroundOnlyModelParameterExpression_ != "") {
std::cerr << "Will make one from the signal ModelConfig " << modelConfigName_ << " setting " << std::endl;
vector<string> SetParameterExpressionList;
boost::split(SetParameterExpressionList, defineBackgroundOnlyModelParameterExpression_, boost::is_any_of(","));
for (UInt_t p = 0; p < SetParameterExpressionList.size(); ++p) {
vector<string> SetParameterExpression;
boost::split(SetParameterExpression, SetParameterExpressionList[p], boost::is_any_of("="));
if (SetParameterExpression.size() != 2) {
std::cout << "Error parsing background model parameter expression : " << SetParameterExpressionList[p] << endl;
} else {
std::string expr = SetParameterExpression[0];
double expval = atof(SetParameterExpression[1].c_str());
w->factory(Form("_%s_background_only_[%g]",expr.c_str(),expval));
make_model_s.replaceArg(*POI->selectByName(expr.c_str())->first(), *w->var(Form("_%s_background_only_",expr.c_str())));
std::cerr << " " << expr << " to " << expval << std::endl;
}
}
} else {
std::cerr << "Will make one from the signal ModelConfig '" << modelConfigName_ << "' setting signal strenth '" << POI->first()->GetName() << "' to zero" << std::endl;
w->factory("_zero_[0]");
make_model_s.replaceArg(*POI->first(), *w->var("_zero_"));
}
RooAbsPdf *model_b = dynamic_cast<RooAbsPdf *>(make_model_s.build());
model_b->SetName("_model_bonly_");
w->import(*model_b);
mc_bonly = new RooStats::ModelConfig(*mc);
mc_bonly->SetPdf(*model_b);
}
// Specific settings should be executed before user specified ranges!
RooRealVar *r = (RooRealVar*)POI->first();
if (!isnan(rMin_)) r->setMin(rMin_);
if (!isnan(rMax_)) r->setMax(rMax_);
if (!isnan(rMin_) || !isnan(rMax_)) {
r->setVal(0.5*(r->getMin() + r->getMax()));
}
if (snapshotName_ != "") {
bool loaded = w->loadSnapshot(snapshotName_.c_str());
assert(loaded);
if (MH){
//make sure mass value used is really the one from the loaded snapshot unless explicitly requested to override it
if (overrideSnapshotMass_) {
MH->setVal(mass_);
}
else {
mass_ = MH->getVal();
}
}
}
if (setPhysicsModelParameterRangeExpression_ != "") {
utils::setModelParameterRanges( setPhysicsModelParameterRangeExpression_, w->allVars());
}
//*********************************************
//set physics model parameters after loading the snapshot
//*********************************************
if (setPhysicsModelParameterExpression_ != "" && !runtimedef::get("SETPARAMETERS_AFTER_NLL")) {
RooArgSet allParams(w->allVars());
//if (w->genobj("discreteParams")) allParams.add(*(RooArgSet*)w->genobj("discreteParams"));
allParams.add(w->allCats());
utils::setModelParameters( setPhysicsModelParameterExpression_, allParams);
// also allow for "discrete" parameters to be set
// Possible that MH value was re-set above, so make sure mass is set to the correct value and not over-ridden later.
if (w->var("MH")) mass_ = w->var("MH")->getVal();
}
} else {
std::cerr << "HLF not validated" << std::endl;
assert(0);
hlf.reset(new RooStats::HLFactory("factory", fileToLoad));
w = hlf->GetWs();
if (w == 0) {
std::cerr << "Could not read HLF from file " << (hlfFile[0] == '/' ? hlfFile : pwd+"/"+hlfFile) << std::endl;
return;
}
RooRealVar *MH = w->var("MH");
if (MH==0) {
std::cerr << "Could not find MH var in workspace '" << workspaceName_ << "' in file " << fileToLoad << std::endl;
throw std::invalid_argument("Missing MH");
}
MH->setVal(mass_);
if (w->set("observables") == 0) throw std::invalid_argument("The model must define a RooArgSet 'observables'");
if (w->set("POI") == 0) throw std::invalid_argument("The model must define a RooArgSet 'POI' for the parameters of interest");
if (w->pdf("model_b") == 0) throw std::invalid_argument("The model must define a RooAbsPdf 'model_b'");
if (w->pdf("model_s") == 0) throw std::invalid_argument("The model must define a RooAbsPdf 'model_s'");
// create ModelConfig
mc = new RooStats::ModelConfig(modelConfigName_.c_str(),"signal",w);
mc->SetPdf(*w->pdf("model_s"));
mc->SetObservables(*w->set("observables"));
mc->SetParametersOfInterest(*w->set("POI"));
if (w->set("nuisances")) mc->SetNuisanceParameters(*w->set("nuisances"));
if (w->set("globalObservables")) mc->SetGlobalObservables(*w->set("globalObservables"));
if (w->pdf("prior")) mc->SetNuisanceParameters(*w->pdf("prior"));
w->import(*mc, modelConfigName_.c_str());
mc_bonly = new RooStats::ModelConfig(modelConfigNameB_.c_str(),"background",w);
mc_bonly->SetPdf(*w->pdf("model_b"));
mc_bonly->SetObservables(*w->set("observables"));
mc_bonly->SetParametersOfInterest(*w->set("POI"));
if (w->set("nuisances")) mc_bonly->SetNuisanceParameters(*w->set("nuisances"));
if (w->set("globalObservables")) mc_bonly->SetGlobalObservables(*w->set("globalObservables"));
if (w->pdf("prior")) mc_bonly->SetNuisanceParameters(*w->pdf("prior"));
w->import(*mc_bonly, modelConfigNameB_.c_str());
if (setPhysicsModelParameterExpression_ != "") {
utils::setModelParameters( setPhysicsModelParameterExpression_, w->allVars());
}
}
gSystem->cd(pwd);
if (verbose <= 2) RooMsgService::instance().setGlobalKillBelow(RooFit::WARNING);
const RooArgSet * observables = mc->GetObservables(); // not null
const RooArgSet * POI = mc->GetParametersOfInterest(); // not null
const RooArgSet * nuisances = mc->GetNuisanceParameters(); // note: may be null
if (dynamic_cast<RooRealVar*>(POI->first()) == 0) throw std::invalid_argument("First parameter of interest is not a RooRealVar");
if (nuisances && runtimedef::get("ADD_DISCRETE_FALLBACK")) {
RooArgSet newNuis;
std::string startswith = "u_CMS_Hgg_env_pdf_";
TIterator *np = nuisances->createIterator();
while (RooRealVar *arg = (RooRealVar*)np->Next()) {
if (std::string(arg->GetName()).compare(0, startswith.size(), startswith)) {
newNuis.add(*arg);
} else {
std::cout << "Removed nuisance from set: " << arg->GetName() << "\n";
}
}
if (newNuis.getSize() < nuisances->getSize()) {
mc->SetNuisanceParameters(newNuis);
if (mc_bonly) mc_bonly->SetNuisanceParameters(newNuis);
nuisances = mc->GetNuisanceParameters();
}
}
if (dataset.find(":") != std::string::npos) {
std::string filename, wspname, dname;
switch (std::count(dataset.begin(), dataset.end(), ':')) {
case 2: // file:wsp:dataset
filename = dataset.substr( 0, dataset.find(":"));
wspname = dataset.substr( dataset.find(":")+1, dataset.rfind(":")-dataset.find(":")-1);
dname = dataset.substr(dataset.rfind(":")+1, std::string::npos);
if (verbose) std::cout << "Will read dataset '" << dname << "' from workspace '" << wspname << "' of file '" << filename << "'" << std::endl;
break;
case 1:
filename = dataset.substr( 0, dataset.find(":"));
dname = dataset.substr(dataset.find(":")+1, std::string::npos);
if (verbose) std::cout << "Will read dataset '" << dname << "' from file '" << filename << "'" << std::endl;
break;
default:
throw std::invalid_argument("The dataset must be a name, or file:name or file:workspace:name");
}
if (filename == "" || dname == ":") throw std::invalid_argument("The dataset must be a name, or file:name or file:workspace:name");
TDirectory *pwd = gDirectory;
TFile *file = TFile::Open(filename.c_str());
RooAbsData *data = 0;
if (file == 0) throw std::invalid_argument(std::string("Cannot open input file: ") + filename);
if (wspname.empty()) {
data = (RooAbsData *) file->Get(dname.c_str());
if (data == 0) throw std::invalid_argument(std::string("Cannot find a dataset named ")+dname+" in file "+filename);
} else {
RooWorkspace *win = (RooWorkspace *) file->Get(wspname.c_str());
if (win == 0) throw std::invalid_argument(std::string("Cannot find a workspace named ")+wspname+" in file "+filename);
data = (RooAbsData *) win->data(dname.c_str());
if (data == 0) throw std::invalid_argument(std::string("Cannot find a dataset named ")+dname+" in file "+filename+", workspace "+wspname);
}
w->import(*data, RooFit::Rename(dataset.c_str()));
file->Close();
pwd->cd();
}
if (w->data(dataset.c_str()) == 0) {
if (isTextDatacard) { // that's ok: the observables are pre-set to the observed values
RooDataSet *data_obs = new RooDataSet(dataset.c_str(), dataset.c_str(), *observables);
data_obs->add(*observables);
w->import(*data_obs);
} else {
TFile *fIn = TFile::Open(fileToLoad);
garbageCollect.tfile = fIn; // request that we close this file when done
RooDataSet *data_obs = dynamic_cast<RooDataSet*> (fIn->Get(dataset.c_str()));
if(data_obs){
data_obs->SetName(dataset.c_str());
w->import(*data_obs);
} else {
std::cout << "Dataset " << dataset.c_str() << " not found." << std::endl;
}
}
}
if (verbose < -1) {
RooMsgService::instance().setStreamStatus(0,kFALSE);
RooMsgService::instance().setStreamStatus(1,kFALSE);
RooMsgService::instance().setGlobalKillBelow(RooFit::FATAL);
}
if (redefineSignalPOIs_ != "") {
RooArgSet newPOIs(w->argSet(redefineSignalPOIs_.c_str()));
TIterator *np = newPOIs.createIterator();
while (RooRealVar *arg = (RooRealVar*)np->Next()) {
RooRealVar *rrv = dynamic_cast<RooRealVar *>(arg);
if (rrv == 0) { std::cerr << "MultiDimFit: Parameter of interest " << arg->GetName() << " which is not a RooRealVar will be ignored" << std::endl; continue; }
arg->setConstant(0);
// also set ignoreConstraint flag for constraint PDF
if ( w->pdf(Form("%s_Pdf",arg->GetName())) ) w->pdf(Form("%s_Pdf",arg->GetName()))->setAttribute("ignoreConstraint");
}
if (verbose > 0) { std::cout << "Redefining the POIs to be: "; newPOIs.Print(""); }
mc->SetParametersOfInterest(newPOIs);
POI = mc->GetParametersOfInterest();
if (nuisances) {
RooArgSet newNuis(*nuisances);
newNuis.remove(*POI);
if (newNuis.getSize() < nuisances->getSize()) {
mc->SetNuisanceParameters(newNuis);
if (mc_bonly) mc_bonly->SetNuisanceParameters(newNuis);
nuisances = mc->GetNuisanceParameters();
}
}
}
// Always reset the POIs to floating (post-fit workspaces can actually have them frozen in some cases, in any case they can be re-frozen in the next step
TIterator *pois = POI->createIterator();
while (RooRealVar *arg = (RooRealVar*)pois->Next()) {
arg->setConstant(0);
}
if (floatNuisances_ != "") {
floatNuisances_ = parseRegex(floatNuisances_, nuisances, w);
RooArgSet toFloat;
if (floatNuisances_=="all") {
toFloat.add(*nuisances);
} else {
std::vector<std::string> nuisToFloat;
boost::split(nuisToFloat, floatNuisances_, boost::is_any_of(","), boost::token_compress_on);
for (int k=0; k<(int)nuisToFloat.size(); k++) {
if (nuisToFloat[k]=="") continue;
else if(nuisToFloat[k]=="all") {
toFloat.add(*nuisances);
continue;
}
else if (!w->fundArg(nuisToFloat[k].c_str())) {
std::cout<<"WARNING: cannot float nuisance parameter "<<nuisToFloat[k].c_str()<<" if it doesn't exist!"<<std::endl;
continue;
}
const RooAbsArg *arg = (RooAbsArg*)w->fundArg(nuisToFloat[k].c_str());
toFloat.add(*arg);
}
}
if (verbose > 0) {
//std::cout << "Floating the following parameters: "; toFloat.Print("");
CombineLogger::instance().log("Combine.cc",__LINE__,"Floating the following parameters:",__func__);
std::unique_ptr<TIterator> iter(toFloat.createIterator());
for (RooAbsArg *a = (RooAbsArg*) iter->Next(); a != 0; a = (RooAbsArg*) iter->Next()) {
CombineLogger::instance().log("Combine.cc",__LINE__,a->GetName(),__func__);
}
}
utils::setAllConstant(toFloat, false);
}
if (freezeNuisances_ != "") {
freezeNuisances_ = parseRegex(freezeNuisances_, nuisances, w);
RooArgSet toFreeze;
if (freezeNuisances_=="allConstrainedNuisances") {
toFreeze.add(*nuisances);
} else {
std::vector<std::string> nuisToFreeze;
boost::split(nuisToFreeze, freezeNuisances_, boost::is_any_of(","), boost::token_compress_on);
for (int k=0; k<(int)nuisToFreeze.size(); k++) {
if (nuisToFreeze[k]=="") continue;
else if(nuisToFreeze[k]=="allConstrainedNuisances") {
toFreeze.add(*nuisances);
continue;
}
else if (!w->fundArg(nuisToFreeze[k].c_str())) {
std::cout<<"WARNING: cannot freeze nuisance parameter "<<nuisToFreeze[k].c_str()<<" if it doesn't exist!"<<std::endl;
continue;
}
const RooAbsArg *arg = (RooAbsArg*)w->fundArg(nuisToFreeze[k].c_str());
toFreeze.add(*arg);
}
}
if (verbose > 0) {
//std::cout << "Freezing the following parameters: "; toFreeze.Print("");
CombineLogger::instance().log("Combine.cc",__LINE__,"Freezing the following parameters: ",__func__);
std::unique_ptr<TIterator> iter(toFreeze.createIterator());
for (RooAbsArg *a = (RooAbsArg*) iter->Next(); a != 0; a = (RooAbsArg*) iter->Next()) {
CombineLogger::instance().log("Combine.cc",__LINE__,a->GetName(),__func__);
}
}
utils::setAllConstant(toFreeze, true);
if (nuisances) {
RooArgSet newnuis(*nuisances);
newnuis.remove(toFreeze, /*silent=*/true, /*byname=*/true);
mc->SetNuisanceParameters(newnuis);
if (mc_bonly) mc_bonly->SetNuisanceParameters(newnuis);
nuisances = mc->GetNuisanceParameters();
}
}
if (freezeNuisanceGroups_ != "") {
std::vector<string> nuisanceGroups;
boost::algorithm::split(nuisanceGroups,freezeNuisanceGroups_,boost::algorithm::is_any_of(","));
for (std::vector<string>::iterator ng_it=nuisanceGroups.begin();ng_it!=nuisanceGroups.end();ng_it++){
bool freeze_complement=false;
if (boost::algorithm::starts_with((*ng_it),"^")){
freeze_complement=true;
(*ng_it).erase(0,1);
}
if (!w->set(Form("group_%s",(*ng_it).c_str()))){
std::cerr << "Unknown nuisance group: " << (*ng_it) << std::endl;
throw std::invalid_argument("Unknown nuisance group name");
}
RooArgSet groupNuisances(*(w->set(Form("group_%s",(*ng_it).c_str()))));
RooArgSet toFreeze;
if (freeze_complement) {
RooArgSet still_floating(*mc->GetNuisanceParameters());
still_floating.remove(groupNuisances,true,true);
toFreeze.add(still_floating);
} else {
toFreeze.add(groupNuisances);
}
if (verbose > 0) { std::cout << "Freezing the following nuisance parameters: "; toFreeze.Print(""); }
utils::setAllConstant(toFreeze, true);
if (nuisances) {
RooArgSet newnuis(*nuisances);
newnuis.remove(toFreeze, /*silent=*/true, /*byname=*/true);
mc->SetNuisanceParameters(newnuis);
if (mc_bonly) mc_bonly->SetNuisanceParameters(newnuis);
nuisances = mc->GetNuisanceParameters();
}
}
}
if (freezeWithAttributes_ != "") {
std::vector<string> nuisanceAttrs;
boost::algorithm::split(nuisanceAttrs,freezeWithAttributes_,boost::algorithm::is_any_of(","));
for (auto const& attr : nuisanceAttrs) {
RooArgSet toFreeze;
if (nuisances) {
RooAbsArg *arg = nullptr;
auto iter = nuisances->createIterator();
while ((arg = (RooAbsArg*)iter->Next())) {
if (arg->attributes().count(attr)) toFreeze.add(*arg);
}
if (verbose > 0) { std::cout << "Freezing the following nuisance parameters: "; toFreeze.Print(""); }
utils::setAllConstant(toFreeze, true);
RooArgSet newnuis(*nuisances);
newnuis.remove(toFreeze, /*silent=*/true, /*byname=*/true);
mc->SetNuisanceParameters(newnuis);
if (mc_bonly) mc_bonly->SetNuisanceParameters(newnuis);
nuisances = mc->GetNuisanceParameters();
}
}
}
if (mc->GetPriorPdf() == 0 && !noDefaultPrior_) {
if (prior_ == "flat") {
RooAbsPdf *prior = new RooUniform("prior","prior",*POI);
w->import(*prior);
mc->SetPriorPdf(*prior);
} else if (prior_ == "1/sqrt(r)") {
std::cout << "Will use prior 1/sqrt(" << POI->first()->GetName() << std::endl;
TString priorExpr = TString::Format("EXPR::prior(\"1/sqrt(@0)\",%s)", POI->first()->GetName());
w->factory(priorExpr.Data());
mc->SetPriorPdf(*w->pdf("prior"));
} else if (prior_.find("@0") != std::string::npos) {
std::cout << "Will use prior: " << prior_ << std::endl;
std::string passInfo = "EXPR::prior(\"" + prior_ +"\",%s)";
TString priorExpr = TString::Format(passInfo.c_str(), POI->first()->GetName());
w->factory(priorExpr.Data());
mc->SetPriorPdf(*w->pdf("prior"));
} else if (!prior_.empty() && w->pdf(prior_.c_str()) != 0) {
std::cout << "Will use prior '" << prior_ << "' in from the input workspace" << std::endl;
mc->SetPriorPdf(*w->pdf(prior_.c_str()));
} else {
std::cerr << "Unknown prior '" << prior_ << "'. It's not 'flat' '1/sqrt(r)' or the name of a pdf in the model.\n" << std::endl;
throw std::invalid_argument("Bad prior");
}
}
if (nuisances == 0) withSystematics = false;
/*
if (withSystematics && nuisances == 0) {
std::cout << "The model has no constrained nuisance parameters. Please run the limit tool with no systematics (option -S 0)." << std::endl;
std::cout << "To make things easier, I will assume you have done it." << std::endl;
if (verbose) Logger::instance().log(std::string(Form("Combine.cc: %d -- The signal model has no constrained nuisance parameters so I have assumed you don't need a pdf for them. Please re-run with -S 0 to be sure!",__LINE__)),Logger::kLogLevelInfo,__func__);
withSystematics = false;
} else if (!withSystematics && nuisances != 0) {
std::cout << "Will set nuisance parameters to constants: " ;
utils::setAllConstant(*nuisances, true);
}
*/
bool validModel = validateModel_ ? utils::checkModel(*mc, false) : true;
if (validateModel_ && verbose) std::cout << "Sanity checks on the model: " << (validModel ? "OK" : "FAIL") << std::endl;
// make sure these things are set consistently with what we expect
if (floatAllNuisances_ && mc->GetNuisanceParameters()) utils::setAllConstant(*mc->GetNuisanceParameters(), false);
if (freezeAllGlobalObs_ && mc->GetGlobalObservables()) utils::setAllConstant(*mc->GetGlobalObservables(), true);
if (floatAllNuisances_ && mc_bonly && mc_bonly->GetNuisanceParameters()) utils::setAllConstant(*mc_bonly->GetNuisanceParameters(), false);
if (freezeAllGlobalObs_ && mc_bonly && mc_bonly->GetGlobalObservables()) utils::setAllConstant(*mc_bonly->GetGlobalObservables(), true);
// Setup the CascadeMinimizer with discrete nuisances
addDiscreteNuisances(w);
// and give him the regular nuisances too
addNuisances(nuisances);
addFloatingParameters(w->allVars());
addPOI(POI);
tree_ = tree;
// Set up additional branches
addBranches(trackParametersNameString_,w,trackedParametersMap_,"Param");
addBranches(trackErrorsNameString_,w,trackedErrorsMap_,"Error");
// Should have the PDF at this point, if not something is really odd?
if (!(mc->GetPdf())){
std::cerr << " FATAL ERROR! PDF not found in ModelConfig. \n Try to build the workspace first with text2workspace.py and run with the binary output." << std::endl;
assert(0);
}
// Print list of channel masks
RooSimultaneousOpt *simopt = dynamic_cast<RooSimultaneousOpt*>(mc->GetPdf());
if (simopt && simopt->channelMasks().getSize() > 0) {
int nChnMasks = simopt->channelMasks().getSize();
int nActiveMasks = 0;
for (int iMask=0; iMask < nChnMasks; iMask++){
if (dynamic_cast<RooRealVar*>(simopt->channelMasks().at(iMask))->getVal() > 0) nActiveMasks++;
}
std::cout << ">>> "<<nActiveMasks<<" out of "<<nChnMasks<<" channels masked\n"<<std::endl;
if (verbose >= 2) {
std::cout << ">>> Channel masks:\n";
simopt->channelMasks().Print("v");
}
}
bool isExtended = mc->GetPdf()->canBeExtended();
RooRealVar *MH = w->var("MH");
RooAbsData *dobs = w->data(dataset.c_str());
// Generate with signal model if r or other physics model parameters are defined
RooAbsPdf *genPdf = (expectSignalSet_ || setPhysicsModelParameterExpression_ != "" || !mc_bonly) ? mc->GetPdf() : (mc_bonly ? mc_bonly->GetPdf() : 0);
RooRealVar *weightVar_ = 0; // will be needed for toy generation in some cases
if (guessGenMode_ && genPdf && genPdf->InheritsFrom("RooSimultaneous") && (dobs != 0)) {
utils::guessChannelMode(dynamic_cast<RooSimultaneous&>(*mc->GetPdf()), *dobs, verbose);
if (mc_bonly) utils::guessChannelMode(dynamic_cast<RooSimultaneous&>(*mc_bonly->GetPdf()), *dobs, 0);
}
if (!genAsBinned_.empty() || !genAsUnbinned_.empty()) {
RooSimultaneous *sim = dynamic_cast<RooSimultaneous*>(genPdf);
if (!sim) throw std::invalid_argument("Options genBinnedChannels and genUnbinnedChannels only work for RooSimultaneous pdfs");
utils::setChannelGenModes(*sim, genAsBinned_, genAsUnbinned_, verbose);
}
// With the value of r we have to handle four cases:
// 1) --expectSignal given and r appears in --setPhysicsModelParameters --> prefer expectSignal value but warn user
// 2) --expectSignal given and r not in --setPhysicsModelParameters --> use --expectSignal value
// 3) --expectSignal not given and r appears in --setPhysicsModelParameters --> use --setPhysicsModelParameters value
// 4) --expectSignal not given and r not in --setPhysicsModelParameters --> use default --expectSignal value
if (nToys != 0) {
if (POI->find("r")) {
// Was r also specified in --setPhysicsModelParameters?
bool rInParamExp = false;
if (setPhysicsModelParameterExpression_ != "") {
vector<string> SetParameterExpressionList;
boost::split(SetParameterExpressionList, setPhysicsModelParameterExpression_, boost::is_any_of(","));
for (UInt_t p = 0; p < SetParameterExpressionList.size(); ++p) {
vector<string> SetParameterExpression;
boost::split(SetParameterExpression, SetParameterExpressionList[p], boost::is_any_of("="));
if (SetParameterExpression.size() == 2 && SetParameterExpression[0] == "r") {
rInParamExp = true;
break;
}
}
}
// Set the value of r in cases 1), 2) and 4)
if (expectSignalSet_ || (!expectSignalSet_ && !rInParamExp && snapshotName_=="" )) {
((RooRealVar*)POI->find("r"))->setVal(expectSignal_);
}
if (expectSignalSet_ && rInParamExp) {
std::cerr << "Warning: A value of r is specified in both the --setParameters "
"and --expectSignal options. The argument of --expectSignal will take "
"precedence\n";
}
if (MH && expectSignalMass_>0.) {
MH->setVal(expectSignalMass_);
}
} else if (expectSignalSet_) {
std::cerr << "Warning: option --expectSignal only applies to models with "
"the POI \"r\", use --setParameters to set the "
"values of the POIs for toy generation in this model\n";
}
}
if (runtimedef::get("FAST_VERTICAL_MORPH")) {
CMSHistFunc::EnableFastVertical();
CMSHistSum::EnableFastVertical();
}
// Warn the user that they might be using funky values of POIs
if (!expectSignalSet_ && setPhysicsModelParameterExpression_ == "" && !(POI->getSize()==1 && POI->find("r"))) {
std::cerr << "Warning! -- You haven't picked default values for the Parameters of Interest (either with --expectSignal or --setParameters) for generating toys. Combine will use the 'B-only' ModelConfig to generate, which may lead to undesired behaviour if not using the default Physics Model" << std::endl;
}
// Ok now we're ready to go lets save a "clean snapshot" for the current parameters state
// w->allVars() misses the RooCategories, useful for some things - so need to include them. Set up a utils function for that
if (nToys <= 0 && runtimedef::get("NO_INITIAL_SNAP")) {
if (verbose >= 3) std::cout << "Skipping snapshot" << std::endl;
} else {
if (verbose >= 3) std::cout << "Saving snapshot 'clean'" << std::endl;
w->saveSnapshot("clean", utils::returnAllVars(w));
if (verbose >= 3) std::cout << "Saved snapshot 'clean'" << std::endl;
}
if (nToys <= 0) { // observed or asimov
if (makeToyGenSnapshot_) w->saveSnapshot("toyGenSnapshot",utils::returnAllVars(w));
iToy = nToys;
if (iToy == -1) {
if (readToysFromHere != 0){
dobs = dynamic_cast<RooAbsData *>(readToysFromHere->Get("toys/toy_asimov"));
if (dobs == 0) {
std::cerr << "Toy toy_asimov not found in " << readToysFromHere->GetName() << ". List follows:\n";
readToysFromHere->ls();
return;
}
if (toysFrequentist_ && mc->GetGlobalObservables()) {
RooAbsCollection *snap = dynamic_cast<RooAbsCollection *>(readToysFromHere->Get("toys/toy_asimov_snapshot"));
if (!snap) {
std::cerr << "Snapshot of global observables toy_asimov_snapshot not found in " << readToysFromHere->GetName() << ". List follows:\n";
readToysFromHere->ls();
return;
}
RooArgSet gobs(*mc->GetGlobalObservables());
gobs.assignValueOnly(*snap);
w->saveSnapshot("clean", utils::returnAllVars(w));
}
}
else{
if (genPdf == 0) throw std::invalid_argument("You can't generate background-only toys if you have no background-only pdf in the workspace and you have set --noMCbonly");
if (toysFrequentist_) {
w->saveSnapshot("reallyClean", utils::returnAllVars(w));
if (dobs == 0) throw std::invalid_argument("Frequentist Asimov datasets can't be generated without a real dataset to fit");
RooArgSet gobsAsimov;
utils::setAllConstant(*mc->GetParametersOfInterest(), true); // Fix poi, before fit
double poiVal = 0.;
if (mc->GetParametersOfInterest()->getSize()) {
poiVal = dynamic_cast<RooRealVar *>(mc->GetParametersOfInterest()->first())->getVal();
}
dobs = asimovutils::asimovDatasetWithFit(mc, *dobs, gobsAsimov, !bypassFrequentistFit_, poiVal, verbose);
if (mc->GetGlobalObservables()) {
RooArgSet gobs(*mc->GetGlobalObservables());
gobs = gobsAsimov;
}
utils::setAllConstant(*mc->GetParametersOfInterest(), false);
w->saveSnapshot("clean", utils::returnAllVars(w));
} else {
toymcoptutils::SimPdfGenInfo newToyMC(*genPdf, *observables, !unbinned_);
// print the values of the parameters used to generate the toy
if (verbose > 2) {
CombineLogger::instance().log("Combine.cc",__LINE__, "Generate Asimov toy from parameter values ... ",__func__);
std::unique_ptr<TIterator> iter(genPdf->getParameters((const RooArgSet*)0)->createIterator());
for (RooAbsArg *a = (RooAbsArg *) iter->Next(); a != 0; a = (RooAbsArg *) iter->Next()) {
TString varstring = utils::printRooArgAsString(a);
CombineLogger::instance().log("Combine.cc",__LINE__,varstring.Data(),__func__);
}
}
// Also save the current state of the tree here but specify the quantile as -2 (i.e not the default, something specific to the toys)
if (saveToys_) commitPoint(false,-2);
dobs = newToyMC.generateAsimov(weightVar_,verbose); // as simple as that
}
}
} else if (dobs == 0) {
std::cerr << "No observed data '" << dataset << "' in the workspace. Cannot compute limit.\n" << std::endl;