-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathFitCrossCheckForLimits.C
4332 lines (3703 loc) · 162 KB
/
FitCrossCheckForLimits.C
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
/*
Author: Romain Madar & Gabriel Facini
Date: 2012-02-16
Email: [email protected], [email protected]
Description : This code allows the check quality of fit performed in the limit derivation.
It works on a generic workspace produced by hist2workspace command. It performs
a global fit and a fit per subchannel automatically. Various control plots (pull
distribution, correlation matrix, distribution before and after fit, ...) are
stored in a the rootfile FitCrossChecks.root. Please use root version >=5.34.17
Updates:
- 2012-09-20 G. Facini
* Get Histograms to plot systematic shapes
* Add plotRelative flag to plot the relative shape difference for a given systematic
* Add drawPlots flag to make eps files
* Toys (still in developpement)
* components post-fit
- 2012-10 R. Madar
* Post-fit NP versus subchannel
* Morphing control plots for each syst x process x subchannel
* Add the stack of different backgrounds in plot after profiling
- 2012-11 R. Madar
* Add the asymmetric error given by minos for the NPs
* Add the -2Log(L) versus each NP
* Add a red color for/summary of suspicious NPs
- 2013-01 N. Morange
* Bugfix. NP not correctly reset to their initial values at the beginning of function calls.
- 2013-03 G. Facini
* Add the -Log(L) for each subchannel & fit for poisson term (1D Response)
- 2013-05 N. Ruthmann
* Add a blind mode with an asimov dataset, or another pseudo-dataset.
- 2015-01 R. Madar
* Change in normalization for pre-fit histogram (due to a change in RooFit version)
*/
// C++
#include <iostream>
#include <fstream>
#include <iomanip>
#include <sstream>
#include <algorithm>
#include <map>
// Root
#include "TFile.h"
#include "TROOT.h"
#include "TSystem.h"
#include "TStyle.h"
#include "TLatex.h"
#include "TCanvas.h"
#include "TList.h"
#include "TMath.h"
#include "TH1.h"
#include "TH2.h"
#include "TF1.h"
#include "TGaxis.h"
#include "TTree.h"
#include "TLeaf.h"
#include "TMarker.h"
// RooFit
#include "RooWorkspace.h"
#include "RooRealVar.h"
#include "RooPlot.h"
#include "RooAbsData.h"
#include "RooHist.h"
#include "RooSimultaneous.h"
#include "RooCategory.h"
#include "RooFitResult.h"
#include "RooAbsData.h"
#include "RooRealSumPdf.h"
#include "Roo1DTable.h"
#include "RooConstVar.h"
#include "RooProduct.h"
#include "RooRandom.h"
#include "TStopwatch.h"
#include "RooNLLVar.h"
#include "RooMsgService.h"
#include "RooMinimizer.h"
// RooStat
#include "RooStats/ModelConfig.h"
#include "RooStats/ProfileInspector.h"
#include "RooStats/ProfileLikelihoodCalculator.h"
#include "RooStats/LikelihoodInterval.h"
#include "RooStats/LikelihoodIntervalPlot.h"
#include "RooStats/ProfileLikelihoodTestStat.h"
#include "RooStats/SamplingDistribution.h"
#include "RooStats/SamplingDistPlot.h"
#include "RooStats/ToyMCSampler.h"
#include "RooStats/RooStatsUtils.h"
using namespace std;
using namespace RooFit;
using namespace RooStats;
struct NPContainer{
TString NPname;
double NPvalue;
double NPerrorHi;
double NPerrorLo;
TString WhichFit;
};
static bool comp_second_abs_decend( const pair< RooRealVar*, float >& i, const pair< RooRealVar*, float >& j ) {
return fabs(i.second) > fabs(j.second);
}
namespace LimitCrossCheck{
// Global variables;
// User configuration one
bool drawPlots(true); // create eps & png files and creat a webpage
bool plotRelative(false); // plot % shift of systematic
bool draw1DResponse(false); // draw 1D response for each NP
bool UseMinosError(false); // compute minos error (if false : use minuit error)
int isBlind(0); // 0: Use observed Data 1: use Asimov data 2: use toydata
double mu_asimov(0.0); // mu value used to generate Asimov dataset (not used if isBlind==0)
double PullMaxAcceptable(1.5); // Threshold to consider a NP[central value] as suspicious
double ErrorMinAcceptable(0.2); // Threshold to consider a NP[error] as suspicious
TString xAxisLabel("Final Distribution"); // set what the x-axis of the distribution is
// not switches
RooWorkspace *w ;
ModelConfig *mc ;
RooAbsData *data ;
TFile *outputfile;
double LumiRelError;
TDirectory *MainDirSyst;
TDirectory *MainDirMorphing;
TDirectory *MainDirFitEachSubChannel;
TDirectory *MainDirFitGlobal;
TDirectory *MainDirModelInspector;
TDirectory *MainDirStatTest;
map <string,double> MapNuisanceParamNom;
map <TString,RooFitResult*> AllFitResults_map;
map <TString,int> AllFitStatus_map;
vector<NPContainer> AllNPafterEachFit_vec;
TString OutputDir;
//Global functions
RooFitResult* FitPDF( ModelConfig* model, RooAbsPdf* fitpdf, RooAbsData* fitdata,
int &MinuitStatus, int &HessStatus, double &Edm,
TString minimType = "Minuit2", bool useMinos = false );
void PlotHistosBeforeFit(double nSigmaToVary, double mu);
void PlotMorphingControlPlots();
void PlotHistosAfterFitEachSubChannel(bool IsConditionnal , double mu);
void PlotHistosAfterFitGlobal(bool IsConditionnal , double mu);
void PlotNPRanking(bool IsConditionnal);
void PlotsNuisanceParametersVSmu();
void PlotsStatisticalTest(double mu_pe, double mu_hyp);
void Plot1DResponse(RooAbsReal* nll, RooRealVar* var, TString cname, TCanvas* can,
TF1* poly, bool IsFloating, TLatex* latex, TDirectory* tdir, RooArgSet* SliceSet = 0);
double FindMuUpperLimit();
void PrintModelObservables();
void PrintNuisanceParameters();
void PrintAllParametersAndValues(RooArgSet para);
void PrintNumberOfEvents(RooAbsPdf *pdf);
void PrintSubChannels();
void PrintSuspiciousNPs();
void PrintFits();
bool IsSimultaneousPdfOK();
bool IsChannelNameOK();
void SetAllNuisanceParaToSigma(double Nsigma);
void SetAllStatErrorToSigma(double Nsigma);
void SetNuisanceParaToSigma(RooRealVar *var, double Nsigma);
void GetNominalValueNuisancePara();
void SetNominalValueNuisancePara();
void SetPOI(double mu);
void SetStyle();
void LegendStyle(TLegend* l);
bool IsAnormFactor(RooRealVar *var);
int GetPosition(RooRealVar* var, TH2D* corrMatrix);
list< pair<RooRealVar*, float> > GetOrderedCorrelations(RooRealVar* var, RooFitResult* fitres);
TCanvas* DrawShift(TString channel, TString var, TString comp, double mu, TH1* d, TH1* n, TH1* p1s, TH1* m1s);
TH2D* GetSubsetOfCorrMatrix(RooRealVar* var, list< pair<RooRealVar*,float> >& pairs, RooFitResult* fitres, int size);
void Initialize(const char* infile , const char* outputdir, const char* workspaceName, const char* modelConfigName, const char* ObsDataName);
void Finalize();
void unfoldConstraints(RooArgSet& initial, RooArgSet& final, RooArgSet& obs, RooArgSet& nuis, int& counter);
RooDataSet* makeAsimovData(double mu_val, bool fluctuateData=false, string* mu_str = NULL);
//======================================================
// ================= Main function =====================
//======================================================
void PlotFitCrossChecks(const char* infile = "WorkspaceForTest1.root",
const char* outputdir = "./results/",
const char* workspaceName = "combined",
const char* modelConfigName = "ModelConfig",
const char* ObsDataName = "obsData"){
Initialize(infile, outputdir, workspaceName, modelConfigName, ObsDataName);
// -----------------------------------------------------------------------------------
// 1 - Plot nominal and +/- Nsigma (for each nuisance paramater) for Data, signal+bkg
// -----------------------------------------------------------------------------------
//PlotHistosBeforeFit(1.0,0.0); // (nSigma,mu)
// -----------------------------------------------------------------------------------
// 2 - Control plots for morphing (ie, -1/0/+1 sigma --> continuous NP)
// -----------------------------------------------------------------------------------
//PlotMorphingControlPlots();
// ----------------------------------------------------------------------------------
// 3 - Plot histograms after unconditional fit (theta and mu fitted at the same time)
// ----------------------------------------------------------------------------------
bool IsConditional = false;
//PlotHistosAfterFitEachSubChannel(IsConditional,0.0);
PlotHistosAfterFitGlobal(IsConditional,0.0);
// --------------------------------------------------------------------------------------------
// 4 - Plot the unconditionnal fitted nuisance paramters value (theta fitted while mu is fixed)
// -------------------------------------------------------------------------------------------
//IsConditional = true;
//PlotHistosAfterFitEachSubChannel(IsConditional, 0.0);
//PlotHistosAfterFitGlobal(IsConditional,0.0);
// -------------------------------------------
// 5 - Plot the nuisance parameters versus mu
// -------------------------------------------
//PlotsNuisanceParametersVSmu(); // This can take time
// -------------------------------------------
// 6 - Plot the pulls and stat test from toys
// -------------------------------------------
//PlotsStatisticalTest(0,0);
Finalize();
return;
}
// ============================================================
// ============ Definition of all the functions ===============
// ============================================================
// ============================================================
// ============ Definition of Fitting Function ================
// ============================================================
RooFitResult* FitPDF( ModelConfig* model, RooAbsPdf* fitpdf, RooAbsData* fitdata,
int &MinuitStatus, int &HessStatus, double &Edm,
TString minimType, bool useMinos ) {
model->Print();
RooArgSet* constrainedParams = fitpdf->getParameters(*data);
RemoveConstantParameters(constrainedParams);
Constrain(*constrainedParams);
const RooArgSet* glbObs = mc->GetGlobalObservables();
RooRealVar * poi = (RooRealVar*) model->GetParametersOfInterest()->first();
cout << "Constant POI " << poi->isConstant() << endl;
cout << "Value of POI " << poi->getVal() << endl;
RooAbsReal * nll = fitpdf->createNLL(*fitdata, Constrain(*constrainedParams), GlobalObservables(*glbObs), Offset(1) );
double nllval = nll->getVal();
std::cout << "initial parameters" << std::endl;
constrainedParams->Print("v");
std::cout << "INITIAL NLL = " << nllval << std::endl;
static int nrItr = 0;
int maxRetries = 3;
ROOT::Math::MinimizerOptions::SetDefaultMinimizer(minimType);
int strat = ROOT::Math::MinimizerOptions::DefaultStrategy();
int save_strat = strat;
RooMinimizer minim(*nll);
minim.setStrategy(strat);
minim.setPrintLevel(1);
minim.setEps(1);
TStopwatch sw; sw.Start();
int status=-99;
HessStatus=-99;
Edm = -99;
RooFitResult * r;
while (nrItr<maxRetries && status!=0 && status!=1){
cout << endl;
cout << endl;
cout << endl;
cout << "Fit try n°" << nrItr+1 << endl;
cout << "======================" << endl;
cout << endl;
ROOT::Math::MinimizerOptions::SetDefaultStrategy(save_strat);
status = minim.minimize(ROOT::Math::MinimizerOptions::DefaultMinimizerType().c_str(),ROOT::Math::MinimizerOptions::DefaultMinimizerAlgo().c_str());
HessStatus= minim.hesse();
r = minim.save();
Edm = r->edm();
//up the strategy
bool FitIsNotGood = ((status!=0 && status!=1) || (HessStatus!=0 && HessStatus!=1) || Edm>1.0);
if (FitIsNotGood && strat<2){
cout << endl;
cout << " *******************************" << endl;
cout << " * Increasing Minuit strategy (was " << strat << ")" << endl;
strat++;
cout << " * Fit failed with : " << endl;
cout << " - minuit status " << status << endl;
cout << " - hess status " << HessStatus << endl;
cout << " - Edm = " << Edm << endl;
cout << " * Retrying with strategy " << strat << endl;
cout << " ********************************" << endl;
cout << endl;
minim.setStrategy(strat);
status = minim.minimize(ROOT::Math::MinimizerOptions::DefaultMinimizerType().c_str(), ROOT::Math::MinimizerOptions::DefaultMinimizerAlgo().c_str());
HessStatus= minim.hesse();
r = minim.save();
Edm = r->edm();
}
FitIsNotGood = ((status!=0 && status!=1) || (HessStatus!=0 && HessStatus!=1) || Edm>1.0);
if (FitIsNotGood && strat < 2){
cout << endl;
cout << " ********************************" << endl;
cout << " * Increasing Minuit strategy (was " << strat << ")" << endl;
strat++;
cout << " * Fit failed with : " << endl;
cout << " - minuit status " << status << endl;
cout << " - hess status " << HessStatus << endl;
cout << " - Edm = " << Edm << endl;
cout << " * Retrying with strategy " << strat << endl;
cout << " ********************************" << endl;
cout << endl;
minim.setStrategy(strat);
status = minim.minimize(ROOT::Math::MinimizerOptions::DefaultMinimizerType().c_str(), ROOT::Math::MinimizerOptions::DefaultMinimizerAlgo().c_str());
r = minim.save();
Edm = r->edm();
}
FitIsNotGood = ((status!=0 && status!=1) || (HessStatus!=0 && HessStatus!=1) || Edm>1.0);
if (FitIsNotGood && strat < 2){
cout << endl;
cout << " *******************************" << endl;
cout << " * Increasing Minuit strategy (was " << strat << ")" << endl;
strat++;
cout << " * Fit failed with : " << endl;
cout << " - minuit status " << status << endl;
cout << " - hess status " << HessStatus << endl;
cout << " - Edm = " << Edm << endl;
cout << " * Retrying with strategy " << strat << endl;
cout << " ********************************" << endl;
cout << endl;
minim.setStrategy(strat);
status = minim.minimize(ROOT::Math::MinimizerOptions::DefaultMinimizerType().c_str(), ROOT::Math::MinimizerOptions::DefaultMinimizerAlgo().c_str());
HessStatus= minim.hesse();
r = minim.save();
Edm = r->edm();
}
if(useMinos) { minim.minos(); }
FitIsNotGood = ((status!=0 && status!=1) || (HessStatus!=0 && HessStatus!=1) || Edm>1.0);
if ( FitIsNotGood) nrItr++;
if (nrItr == maxRetries) {
cout << endl;
cout << endl;
cout << endl;
cout << "***********************************************************" << endl;
cout << "WARNING::Fit failure unresolved with status " << status << endl;
cout << " Please investigate your workspace" << endl;
cout << " Find a wall : you will need it to crash your head on it" << endl;
cout << "***********************************************************" << endl;
cout << endl;
cout << endl;
cout << endl;
MinuitStatus = status;
return r;
}
}
r = minim.save();
cout << endl;
cout << endl;
cout << endl;
cout << "***********************************************************" << endl;
cout << " FIT FINALIZED SUCCESSFULLY : " << endl;
cout << " - minuit status " << status << endl;
cout << " - hess status " << HessStatus << endl;
cout << " - Edm = " << Edm << endl;
cout << " -- " ; sw.Print();
cout << "***********************************************************" << endl;
cout << endl;
cout << endl;
cout << endl;
MinuitStatus = status;
sw.Print();
return r;
} // FitPDF
void PlotHistosBeforeFit(double nSigmaToVary, double mu){
cout << endl << "Plotting Histos Before Fit " << endl;
cout << "\t Plotting relative " << plotRelative << endl;
// Put all parameters to their iniital values
if(!w->loadSnapshot("snapshot_paramsVals_initial")) {
cout << "Cannot load " << "snapshot_paramsVals_initial" << endl;
exit(-1);
}
RooMsgService::instance().setGlobalKillBelow(ERROR);
TString MaindirName("MuIsEqualTo_");
MaindirName += mu;
if(plotRelative) { MaindirName.Append("_relative"); }
TDirectory *MainDir = (TDirectory*) MainDirSyst->mkdir(MaindirName);
gROOT->cd();
// Get the RooSimultaneous PDF
RooSimultaneous *simPdf = (RooSimultaneous*)(mc->GetPdf());
RooRealVar * firstPOI = dynamic_cast<RooRealVar*>(mc->GetParametersOfInterest()->first());
firstPOI->setVal(mu);
RooCategory* channelCat = (RooCategory*) (&simPdf->indexCat());
TIterator* iter = channelCat->typeIterator() ;
RooCatType* tt = NULL;
TString dirName("");
while((tt=(RooCatType*) iter->Next()) ){
cout << endl;
cout << endl;
cout << " -- On category " << tt->GetName() << " " << endl;
ostringstream SubdirName;
SubdirName << tt->GetName();
TDirectory *SubDirChannel = (TDirectory*) MainDir->mkdir(SubdirName.str().c_str());
gROOT->cd();
// Get pdf associated with state from simpdf
RooAbsPdf *pdftmp = simPdf->getPdf(tt->GetName()) ;
RooArgSet *obstmp = pdftmp->getObservables( *mc->GetObservables() ) ;
RooAbsData *datatmp = data->reduce(Form("%s==%s::%s",channelCat->GetName(),channelCat->GetName(),tt->GetName()));
RooRealVar *obs = ((RooRealVar*) obstmp->first());
// Get the bin width
RooRealVar* binWidth = ((RooRealVar*) pdftmp->getVariables()->find(Form("binWidth_obs_x_%s_0",tt->GetName()))) ;
if(!binWidth) { cout << "No bin width!" << tt->GetName() << endl; return; }
cout << " Bin Width : " << binWidth->getVal() << endl;
// First be sure that all nuisance parameters are nominal
SetAllStatErrorToSigma(0.0);
SetAllNuisanceParaToSigma(0.0);
// Look at each component
cout << " Contains the following components : " << endl;
TString modelName(tt->GetName());
modelName.Append("_model");
RooRealSumPdf *pdfmodel = (RooRealSumPdf*) (pdftmp->getComponents())->find(modelName);
RooArgList funcList = pdfmodel->funcList();
RooLinkedListIter funcIter = funcList.iterator() ;
RooProduct* comp = 0;
float total(0);
SetPOI(1); // want to see signal
map<TString, TH1*> nominals;
while( (comp = (RooProduct*) funcIter.Next())) {
cout << " Component : " << comp->GetName() << endl;
cout << "\t" << ( comp->createIntegral(*obs) )->getVal() * binWidth->getVal() << endl;
total += ( comp->createIntegral(*obs) )->getVal() * binWidth->getVal();
}
SetPOI(mu);
cout << " Total (mu = 1) : " << total << endl;
// Loop over nuisance params
TIterator* it = mc->GetNuisanceParameters()->createIterator();
RooRealVar* var = NULL;
bool IsAllStatDone = false;
TString chanName(tt->GetName());
while( (var = (RooRealVar*) it->Next()) ){
string varname = (string) var->GetName();
if ( varname.find("gamma_stat")!=string::npos ){
continue;
}
// one sigma not defined for floating parameters
// is there a more general way of getting to this fact?
if (IsAnormFactor(var)) continue;
// user firendly label / name
TString varName(var->GetName());
varName.ReplaceAll("alpha_Sys","");
varName.ReplaceAll("alpha_","");
dirName = OutputDir+"/"+MainDirSyst->GetName()+"/"+MaindirName+"/"+chanName+"/"+varName;
// Not consider nuisance parameter being not assocaited to systematics
if (MapNuisanceParamNom[varname]!=0.0 &&
MapNuisanceParamNom[varname]!=1.0 ) continue;
cout << endl;
cout << " -- On nuisance parameter : " << var->GetName() << endl;
TString histName("");
// -1 sigma
SetNuisanceParaToSigma(var,-nSigmaToVary);
SetPOI(mu);
histName = chanName+"_"+varName+"_"+TString(plotRelative)+"_m1sigma";
TH1* hm1sigma = pdftmp->createHistogram(histName,*obs);
//hm1sigma->Scale(pdftmp->expectedEvents(*obs)); --> Not needed anymore for root v5-34-17
// +1 sigma
SetNuisanceParaToSigma(var,+nSigmaToVary);
SetPOI(mu);
histName.ReplaceAll("m1sigma","p1sigma");
TH1* hp1sigma = pdftmp->createHistogram(histName,*obs);
//hp1sigma->Scale(pdftmp->expectedEvents(*obs)); --> Not needed anymore for root v5-34-17
// Nominal
SetNuisanceParaToSigma(var,0.0);
SetPOI(mu);
histName.ReplaceAll("p1sigma","nominal");
TH1* hnominal = pdftmp->createHistogram(histName,*obs);
//hnominal->Scale(pdftmp->expectedEvents(*obs)); --> Not needed anymore for root v5-34-17
// Data
histName.ReplaceAll("nominal","data");
TH1* hdata = datatmp->createHistogram(histName,*obs);
for (int ib=0 ; ib<hdata->GetNbinsX()+1 ; ib++) hdata->SetBinError(ib, sqrt(hdata->GetBinContent(ib)));
TString expName("AllBkg(#mu=");
expName += mu;
expName.Append(")");
TCanvas* c2 = DrawShift(chanName,(TString)var->GetName(),expName,mu,hdata,hnominal,hp1sigma,hm1sigma);
SubDirChannel->cd();
c2->Write();
if(drawPlots) {
system(TString("mkdir -vp "+dirName));
c2->Print(dirName+"/totalExpected.eps");
c2->Print(dirName+"/totalExpected.png");
}
c2->Close();
gROOT->cd();
// reset pointer
hdata->~TH1();
hnominal->~TH1();
hp1sigma->~TH1();
hm1sigma->~TH1();
hdata = 0;
hnominal = 0;
hp1sigma = 0;
hm1sigma = 0;
// Loop over components and make these plots for each one
funcIter = funcList.iterator();
while( (comp = (RooProduct*) funcIter.Next()) ) {
TString compName(comp->GetName());
compName.ReplaceAll("L_x_","");
compName.ReplaceAll(chanName,"");
compName.ReplaceAll("__overallSyst_x_StatUncert","");
compName.ReplaceAll("__overallSyst_x_HistSyst","");
compName.ReplaceAll("__overallSyst_x_Exp","");
// Fisrt be sure that all nuisance parameters are nominal
SetAllStatErrorToSigma(0.0);
SetAllNuisanceParaToSigma(0.0);
SetPOI(1); // set to one so do not ignore signal
// -1 sigma
SetNuisanceParaToSigma(var,-nSigmaToVary);
SetPOI(1);
histName = chanName+"_"+varName+"_"+compName+"_"+TString(plotRelative)+"_m1sigma";
hm1sigma = comp->createHistogram(histName,*obs);
hm1sigma->Scale( binWidth->getVal() );
// +1 sigma
SetNuisanceParaToSigma(var,+nSigmaToVary);
SetPOI(1);
histName.ReplaceAll("m1sigma","p1sigma");
hp1sigma = comp->createHistogram(histName,*obs);
hp1sigma->Scale( binWidth->getVal() );
// nominal
SetNuisanceParaToSigma(var,0.0);
SetPOI(1);
histName.ReplaceAll("p1sigma","nominal");
hnominal = comp->createHistogram(histName,*obs);
hnominal->Scale( binWidth->getVal() );
// skip components which are not affected by this nuisance parameter
if(hp1sigma->Integral() == 0 || hm1sigma->Integral() == 0) {
cout << "Integral 0 " << varName << " on " << compName << " in " << chanName
<< " ( " << hp1sigma->Integral() << ", " << hm1sigma->Integral() << " ) " << endl;
continue;
}
// skip components which are not affected by this nuisance parameter
float totUp(0), totDn(0);
for(int b=1; b<hnominal->GetNbinsX()+1; b++) { // no over/under-flow
if(hnominal->GetBinContent(b)>0) {
totUp += pow((hp1sigma->GetBinContent(b)-hnominal->GetBinContent(b))/hnominal->GetBinContent(b),2);
totUp += pow((hm1sigma->GetBinContent(b)-hnominal->GetBinContent(b))/hnominal->GetBinContent(b),2);
}
}
if( totUp < 0.05 && totDn < 0.05 ) {
cout << "No " << varName << " on " << compName << " in " << chanName << " ( " << totUp << ", " << totDn << " ) " << endl;
continue;
}
c2 = DrawShift(chanName,(TString)var->GetName(),compName,mu,0,hnominal,hp1sigma,hm1sigma);
SubDirChannel->cd();
c2->Write();
if(drawPlots) {
//system(TString("mkdir -vp "+dirName));
c2->Print(dirName+"/"+compName+".eps");
c2->Print(dirName+"/"+compName+".png");
}
c2->Close();
gROOT->cd();
// Put everything back to the nominal
SetAllNuisanceParaToSigma(0.0);
SetPOI(mu);
//
hnominal->~TH1();
hp1sigma->~TH1();
hm1sigma->~TH1();
hnominal = 0;
hp1sigma = 0;
hm1sigma = 0;
} // loop over components
// Put everything back to the nominal
SetAllNuisanceParaToSigma(0.0);
SetPOI(mu);
// Stat uncertainty
if (!IsAllStatDone){
// reset pointer
hdata = 0;
hnominal = 0;
hp1sigma = 0;
hm1sigma = 0;
// -1 sigma
SetAllStatErrorToSigma(-nSigmaToVary);
SetAllNuisanceParaToSigma(0.0);
SetPOI(mu);
histName = chanName+"_Stat_"+TString(plotRelative)+"_m1sigma";
hm1sigma = pdftmp->createHistogram(histName,*obs);
//hm1sigma->Scale(pdftmp->expectedEvents(*obs)); --> Not needed anymore for root v5-34-17
// +1 sigma
SetAllStatErrorToSigma(+nSigmaToVary);
SetAllNuisanceParaToSigma(0.0);
SetPOI(mu);
histName.ReplaceAll("m1sigma","p1sigma");
hp1sigma = pdftmp->createHistogram(histName,*obs);
//hp1sigma->Scale(pdftmp->expectedEvents(*obs)); --> Not needed anymore for root v5-34-17
// Nominal
SetAllStatErrorToSigma(0.0);
SetNuisanceParaToSigma(var,0.0);
SetPOI(mu);
histName.ReplaceAll("p1sigma","nominal");
hnominal = pdftmp->createHistogram(histName,*obs);
//hnominal->Scale(pdftmp->expectedEvents(*obs)); --> Not needed anymore for root v5-34-17
// Data
histName.ReplaceAll("nominal","data");
hdata = datatmp->createHistogram(histName,*obs);
for (int ib=0 ; ib<hdata->GetNbinsX()+1 ; ib++) hdata->SetBinError(ib, sqrt(hdata->GetBinContent(ib)));
cout << endl;
cout << " - stat uncertainty : " << endl;
TCanvas* c4 = DrawShift(chanName,"Stat",expName,mu,hdata,hnominal,hp1sigma,hm1sigma);
dirName = OutputDir+"/"+MainDirSyst->GetName()+"/"+MaindirName+"/"+chanName+"/Stat";
SubDirChannel->cd();
c4->Write();
if(drawPlots) {
system(TString("mkdir -vp "+dirName));
c4->Print(dirName+"/totalExpected.eps");
c4->Print(dirName+"/totalExpected.png");
}
c4->Close();
gROOT->cd();
IsAllStatDone=true;
}
}
}
return;
}
// create the canvas and put stuff on it
// to be used when plotting the +/- 1 sigma shifts
TCanvas* DrawShift(TString channel, TString var, TString comp, double mu, TH1* d, TH1* n, TH1* p1s, TH1* m1s) {
cout << " " << comp << endl;
cout << "N(-sigma) = " << m1s->Integral() << endl;
cout << "N(+sigma) = " << p1s->Integral() << endl;
cout << "N(nominal) = " << n->Integral() << endl;
if(d) { cout << "N(Observed) = " << d->Integral() << endl; }
var.ReplaceAll("alpha_Sys","");
var.ReplaceAll("alpha_","");
TString cname = "can_" + channel + "_" + comp + "_" + var + "_mu";
cname += mu;
if(plotRelative) { cname.Append("_relative"); }
cname.ReplaceAll("#","");
cname.ReplaceAll("(","");
cname.ReplaceAll(")","");
cname.ReplaceAll("=","");
TCanvas *canvas = new TCanvas(cname,cname,700,550);
canvas->cd();
TPad *pad1 = new TPad("pad1","pad1",0,0.25,1,1);
pad1->SetBottomMargin(0.009);
pad1->Draw();
TPad *pad2 = new TPad("pad2","pad2",0,0,1,0.25);
pad2->SetTopMargin(0.009);
pad2->SetBottomMargin(0.5);
pad2->Draw();
// style
if(d) {
d->SetLineColor(1);
d->SetLineWidth(1);
d->SetMarkerColor(1);
d->SetMarkerSize(0.9);
d->SetMarkerStyle(20);
}
n->SetLineWidth(2);
p1s->SetLineColor(kRed);
p1s->SetLineWidth(2);
p1s->SetLineStyle(2);
m1s->SetLineColor(kGreen);
m1s->SetLineWidth(2);
m1s->SetLineStyle(2);
float max(0);
float min(0);
// put averages on the plot
float avgUp = ( p1s->Integral() - n->Integral() ) / n->Integral();
float avgDn = ( m1s->Integral() - n->Integral() ) / n->Integral();
// Distribution in the upper pad
pad1->cd();
n->SetTitle(channel);
n->GetXaxis()->SetTitle(xAxisLabel);
max = p1s->GetMaximum();
if(m1s->GetMaximum() > max) { max = m1s->GetMaximum(); }
if(n->GetMaximum() > max) { max = n->GetMaximum(); }
if(d) { if(d->GetMaximum() > max) { max = d->GetMaximum(); } }
n->SetMaximum( 1.2*max );
n->Draw("hist");
if(d) { d->Draw("E1 same"); }
p1s->Draw("hist same");
m1s->Draw("hist same");
// Distribution of the ratio in %
pad2->cd();
TH1F *p1s_ratio = (TH1F*) p1s->Clone();
p1s_ratio->Add(n,-1); p1s_ratio->Divide(n); p1s_ratio->Scale(100);
p1s_ratio->SetLineStyle(1);
TH1F *m1s_ratio = (TH1F*) m1s->Clone();
m1s_ratio->Add(n,-1); m1s_ratio->Divide(n); m1s_ratio->Scale(100);
m1s_ratio->SetLineStyle(1);
max = p1s_ratio->GetMaximum();
if(m1s_ratio->GetMaximum() > max) { max = m1s_ratio->GetMaximum(); }
min = p1s_ratio->GetMinimum();
if(m1s_ratio->GetMinimum() < min) { min = m1s_ratio->GetMinimum(); }
p1s_ratio->SetMaximum( 1.5*max );
p1s_ratio->SetMinimum( min - 0.5*fabs(min) );
p1s_ratio->GetYaxis()->SetNdivisions(004);
p1s_ratio->GetXaxis()->SetTitleFont(43);
p1s_ratio->GetXaxis()->SetTitleSize(16);
p1s_ratio->GetXaxis()->SetTitleOffset(4);
p1s_ratio->GetYaxis()->SetTitleOffset(1.1);
p1s_ratio->GetYaxis()->SetTitleFont(43);
p1s_ratio->GetYaxis()->SetTitleSize(13);
p1s_ratio->GetXaxis()->SetLabelFont(43);
p1s_ratio->GetXaxis()->SetLabelSize(13);
p1s_ratio->GetYaxis()->SetLabelFont(43);
p1s_ratio->GetYaxis()->SetLabelSize(13);
p1s_ratio->SetTitle("");
p1s_ratio->GetYaxis()->SetTitle("Rel. unc. (%)");
p1s_ratio->Draw("hist");
m1s_ratio->Draw("hist same");
if (d){
TH1F *d_ratio = (TH1F*) d->Clone();
d_ratio->Add(n,-1); d_ratio->Divide(n); d_ratio->Scale(100);
d_ratio->Draw("E1 same");
}
// get max and min and draw
// -- old way, just keep for book-keeping --
if(plotRelative) {
// draw percent error bands
p1s->Add(n,-1); p1s->Divide(n); p1s->Scale(100);
m1s->Add(n,-1); m1s->Divide(n); m1s->Scale(100);
p1s->GetYaxis()->SetTitle("Percent Error");
p1s->SetTitle(channel);
p1s->GetXaxis()->SetTitle(xAxisLabel);
max = p1s->GetMaximum();
if(m1s->GetMaximum() > max) { max = m1s->GetMaximum(); }
min = p1s->GetMinimum();
if(m1s->GetMinimum() < min) { min = m1s->GetMinimum(); }
p1s->SetMaximum( 1.5*max );
p1s->SetMinimum( min - 0.5*fabs(min) );
canvas->cd();
p1s->Draw("hist");
m1s->Draw("hist same");
// draw nominal with a seperate axis on a transparent pad
TPad *pad = new TPad("pad","pad",0,0,1,1);
pad->SetFillStyle(4000); //will be transparent
pad->SetFrameFillStyle(4000);
pad->SetLeftMargin(canvas->GetLeftMargin());
pad->SetRightMargin(canvas->GetRightMargin());
pad->SetTopMargin(canvas->GetTopMargin());
pad->SetBottomMargin(canvas->GetBottomMargin());
pad->Draw();
pad->cd();
// new axis
float xloc = n->GetXaxis()->GetBinLowEdge( n->GetNbinsX()+1 );
TGaxis *axis = new TGaxis(xloc,0,xloc,p1s->GetMaximum(),0,n->GetMaximum(),510,"+L");
axis->SetTitle(n->GetYaxis()->GetTitle());
axis->SetTitleColor(kBlue);
axis->SetLabelColor(kBlue);
//axis->SetTitleFont(mFont);
n->SetLineColor(kBlue);
n->SetLineStyle(kDashed);
n->GetYaxis()->SetTitle(""); n->SetTitle(""); n->GetXaxis()->SetTitle("");
//n->Draw("hist ah e");
n->Draw("hist ah");
axis->Draw("same");
pad->Update();
}
// write average shift on canvas
if (!plotRelative) pad1->cd();
TString info(var+" "+comp);
info.Append(Form(" %5.2f, %5.2f",avgUp*100,avgDn*100));
info.Append('%');
TLatex *niceinfo = new TLatex(0.12, 0.85, info);
niceinfo->SetNDC();
niceinfo->SetTextSize(0.045);
niceinfo->Draw("same");
// legend
TLegend *leg = new TLegend(0.67, 0.64, 0.87, 0.86);
LegendStyle(leg);
TString varLegName(var);
varLegName.ReplaceAll("alpha_Sys","");
varLegName.ReplaceAll("alpha_","");
if(!plotRelative && d) { leg->AddEntry( d, "Data", "p" ); }
leg->AddEntry( n, comp, "l" );
leg->AddEntry( p1s, "+#sigma", "l" );
leg->AddEntry( m1s, "-#sigma", "l" );
leg->Draw();
return canvas;
} // DrawShift
void PlotMorphingControlPlots(){
cout << endl << "Plotting Systematic morphing control plots" << endl;
RooMsgService::instance().setGlobalKillBelow(ERROR);
// Put all parameters to their iniital values
if(!w->loadSnapshot("snapshot_paramsVals_initial")) {
cout << "Cannot load " << "snapshot_paramsVals_initial" << endl;
exit(-1);
}
// Get the RooSimultaneous PDF
RooSimultaneous *simPdf = (RooSimultaneous*)(mc->GetPdf());
RooRealVar * firstPOI = dynamic_cast<RooRealVar*>(mc->GetParametersOfInterest()->first());
double mu=0;
firstPOI->setVal(mu);
RooCategory* channelCat = (RooCategory*) (&simPdf->indexCat());
TIterator* iter = channelCat->typeIterator() ;
RooCatType* tt = NULL;
TString dirName("");
while((tt=(RooCatType*) iter->Next()) ){
cout << endl;
cout << endl;
cout << " -- On category " << tt->GetName() << " " << endl;
ostringstream SubdirName;
SubdirName << tt->GetName();
TDirectory *SubDirChannel = (TDirectory*) MainDirMorphing->mkdir(SubdirName.str().c_str());
gROOT->cd();
// Get pdf associated with state from simpdf
RooAbsPdf *pdftmp = simPdf->getPdf(tt->GetName()) ;
RooArgSet *obstmp = pdftmp->getObservables( *mc->GetObservables() ) ;
RooRealVar *obs = ((RooRealVar*) obstmp->first());
// First be sure that all nuisance parameters are nominal
SetAllStatErrorToSigma(0.0);
SetAllNuisanceParaToSigma(0.0);
// Loop over nuisance params
TIterator* it = mc->GetNuisanceParameters()->createIterator();
RooRealVar* var = NULL;
TString chanName(tt->GetName());
while( (var = (RooRealVar*) it->Next()) ){
string varname = (string) var->GetName();
if ( varname.find("gamma_stat")!=string::npos ){
continue;
}
if ( varname.find("ATLAS_norm")!=string::npos ){
continue;
}
if ( varname.find("ATLAS_sampleNorm")!=string::npos ){
continue;
}
// user friendly label / name
TString varName(var->GetName());
varName.ReplaceAll("alpha_Sys","");
varName.ReplaceAll("alpha_","");
// Not consider nuisance parameter being not assocaited to systematics
if (MapNuisanceParamNom[varname]!=0.0 &&
MapNuisanceParamNom[varname]!=1.0 ) continue;
cout << endl;
cout << " -- On nuisance parameter : " << var->GetName() << endl;
TDirectory *SubDirNP = (TDirectory*) SubDirChannel->mkdir(varName);
gROOT->cd();
TString cname = "can_" + (TString)tt->GetName() + "_" + varName;
TCanvas* c2 = new TCanvas( cname );
c2->cd();
TH1* hh = pdftmp->createHistogram("hh_"+cname,*obs,YVar(*var,Binning(60)) ) ;
hh->SetLineColor(kBlue) ;
hh->GetZaxis()->SetTitleOffset(2.5) ; hh->Draw("surf") ;
SubDirNP->cd();
c2->Write();
c2->Close();
gROOT->cd();
// Loop over components and make these plots for each one
TString modelName(tt->GetName());
modelName.Append("_model");
RooRealSumPdf *pdfmodel = (RooRealSumPdf*) (pdftmp->getComponents())->find(modelName);
RooArgList funcList = pdfmodel->funcList();
RooLinkedListIter funcIter = funcList.iterator() ;
RooProduct* comp = 0;
while( (comp = (RooProduct*) funcIter.Next()) ) {
TString compName(comp->GetName());
compName.ReplaceAll("L_x_","");