-
Notifications
You must be signed in to change notification settings - Fork 5
/
RooUnfoldTestHarness.icc
1058 lines (951 loc) · 36.7 KB
/
RooUnfoldTestHarness.icc
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
//=====================================================================-*-C++-*-
// File and Version Information:
// $Id$
//
// Description:
// Test Harness class for the RooUnfold package using toy MC generated
// according to PDFs defined in RooUnfoldTestPdf.icc or RooUnfoldTestPdfRooFit.icc.
//
// Authors: Tim Adye <[email protected]> and Fergus Wilson <[email protected]>
//
//==============================================================================
#ifndef ROOUNFOLDTESTHARNESS_ICC
#define ROOUNFOLDTESTHARNESS_ICC
#include "RooUnfoldTestHarness.h"
#ifndef NOROOFIT
#define USE_ROOFIT
#endif
#include <cfloat>
#include <algorithm>
#if !defined(__CINT__) || defined(__MAKECINT__)
#include <iostream>
#include "TROOT.h"
#include "TString.h"
#include "TStyle.h"
#include "TCanvas.h"
#include "TLegend.h"
#include "TRandom.h"
#include "TPostScript.h"
#include "TH1D.h"
#include "TH2D.h"
#include "TF1.h"
#include "TFile.h"
#include "TVectorD.h"
#include "TLine.h"
#include "TNtuple.h"
#include "TProfile.h"
#include "RooUnfoldErrors.h"
#include "RooUnfoldParms.h"
#include "RooUnfoldResponse.h"
#include "RooUnfold.h"
#ifdef USE_TUNFOLD_H
#include "RooUnfoldTUnfold.h"
#endif
#include "TPaveText.h"
#include "TLatex.h"
#endif
#include "ArgVars.h"
//==============================================================================
// MC generation routine: RooUnfoldTestPdf()
//==============================================================================
#ifdef USE_ROOFIT
#include "RooUnfoldTestPdfRooFit.icc"
#include "RooRandom.h"
#else
#include "RooUnfoldTestPdf.icc"
#endif
#if !defined(__CINT__) || defined(__MAKECINT__)
using std::cout;
using std::cerr;
using std::endl;
#endif
//==============================================================================
// Test parameters
//==============================================================================
void RooUnfoldTestHarness::Parms (ArgVars& args)
{
TString methodHelp, methodHelp2, stageHelp; // TString::Form seems to be limited to 4 parameters in CINT.
methodHelp.Form ("unfolding method: %d=none, %d=Bayes, %d=SVD, ",
RooUnfold::kNone, RooUnfold::kBayes, RooUnfold::kSVD);
methodHelp2.Form("%d=bin-by-bin, %d=TUnfold, %d=invert, %d=IDS",
RooUnfold::kBinByBin, RooUnfold::kTUnfold, RooUnfold::kInvert, RooUnfold::kIDS);
methodHelp += methodHelp2;
stageHelp.Form ("1=train (writes %s.root), 2=test (reads), 0=both (default)", GetName());
args.Add ("method", &method, RooUnfold::kBayes, methodHelp.Data());
args.Add ("stage", &stage, 0, stageHelp.Data());
args.Add ("ftrainx", &ftrainx, 0, "training X PDF: 0=flat, 1=top-hat, 2=Gaussian, 3=double exp, 4=B-W, 5=double B-W, 6=exp, 7=Gaussian+exp");
args.Add ("ftestx", &ftestx, 5, "test X PDF");
args.Add ("ntx", &ntx, 40, "#truth X bins");
args.Add ("ntest", &ntest, 10000, "#events to use for testing");
args.Add ("ntrain", &ntrain, 100000, "#events to use for training");
args.Add ("xlo", &xlo, 0.0, "X range minimum");
args.Add ("xhi", &xhi, 10.0, "X range maximum");
args.Add ("regparm", ®parm, -1e30, "regularisation parameter (default: Bayes niter=3, SVD kterm=ntx/2)", "");
#ifdef USE_TUNFOLD_H
args.Add ("regmethod",®method, 2, "TUnfold regularisation method (0=none, 1=size, 2=derivative, 3=curvature)");
#endif
args.Add ("onepage", &onepage, 4, "number of plots to include on the page, or 0 for all plots on separate pages");
args.Add ("doerror", &doerror, RooUnfold::kCovariance,
"error treatment (0=none, 1=error propagation, 2=covariance propagation, 3=toy MC)");
args.Add ("dosys", &dosys, 0, "include systematic errors from response matrix: 0=stat only, 1=stat+sys, 2=sys only");
args.Add ("nmx", &nmx, -1, "#measured X bins", "ntx");
args.Add ("mtrainx", &mtrainx, 5.0, "training signal PDF X mean");
args.Add ("wtrainx", &wtrainx, 1.2, "training signal PDF X width");
args.Add ("btrainx", &btrainx, 0.2, "training X PDF background fraction");
args.Add ("mtestx", &mtestx, 5.5, "test signal PDF X mean");
args.Add ("wtestx", &wtestx, 1.0, "test signal PDF X width");
args.Add ("btestx", &btestx, 0.3, "test X PDF background fraction");
args.Add ("doeff", &doeff, 1, "include efficiencies in the response model");
args.Add ("effxlo", &effxlo, 0.5, "efficiency at xlo");
args.Add ("effxhi", &effxhi, 0.9, "efficiency at xhi");
args.Add ("xbias", &xbias, -1.0, "shift in X");
args.Add ("xsmear", &xsmear, 0.5, "X smearing width in bins");
args.Add ("addfakes",&addfakes, 0, "include fakes in the response model");
args.Add ("fakexlo", &fakexlo, 0.2, "fraction of fakes at xlo");
args.Add ("fakexhi", &fakexhi, 0.5, "fraction of fakes at xhi");
args.Add ("bincorr", &bincorr, 0.0, "correlation between neighbouring measured bins");
args.Add ("overflow",&overflow, 0, "0=unfolding ignores under/overflow bins, 1=unfolding uses under/overflow bins, 2=fill under/overflows into first/last bins");
args.Add ("addbias", &addbias, -1, "apply systematic shift/rotation (disabled by default for bin-by-bin/invert methods)", "1");
args.Add ("wpaper", &wpaper, 0, "paper width", "");
args.Add ("hpaper", &hpaper, 0, "paper height", "");
args.Add ("verbose", &verbose, 1, "debug level: 0=warnings, 1=verbose, 2=debug, 3=detailed");
args.Add ("draw", &dodraw, 1, "draw results");
args.Add ("ntoys", &ntoys, -1, "number of toys for error calculation (doerror=3) or plots (ploterrors=1, default ntoys=500)", "50");
args.Add ("ploterrors",&ploterrors, 0, "plot error comparison (ploterrors=1) and chi2 (ploterrors=2)?");
args.Add ("plotparms",&plotparms, 0, "plot errors for different regularisation parameters?");
args.Add ("minparm", &minparm, -1e30, "minimum value in regparm scan (with plotparms=1)", "");
args.Add ("maxparm", &maxparm, -1e30, "maximum value in regparm scan (with plotparms=1)", "");
args.Add ("stepsize",&stepsize, 0, "step size in regparm scan (with plotparms=1)", "");
args.Add ("name", &setname, GetName(), "name for output files (name.root and name.ps)");
args.Add ("seed", &seed, -1, "random number seed for test distributions and RooUnfold toy error calculation (use seed=0 for a different seed on each run)", "");
args.Add ("fit", &dofit, 0, "parametric fit of folded function to measured distribution");
}
//==============================================================================
// Run tests
//==============================================================================
Int_t RooUnfoldTestHarness::Run()
{
Init();
if (error) return error;
CheckParms();
if (error) return error;
if (dodraw) SetupCanvas();
error= RunTests();
if (dodraw) {
ps->Close();
delete ps; ps= 0;
}
TFile f (rootfile, "update");
const TNamed* objs[] = { unfold, hTrain, hTrainTrue, hTrainFake, hTrue, hMeas, hFake,
hReco, hRes, hPulls, hPDFx, hTestPDFx,
hResmat, hCorr, hMeasCorr, hUnfErr, hToyErr, fitFunc, trueFunc, ntChi2,
hParmChi2, hParmErr, hParmRes, hParmRms };
for (size_t i= 0; i<sizeof(objs)/sizeof(objs[0]); i++) {
if (objs[i]) f.WriteTObject (objs[i], objs[i]->GetName());
}
f.Close();
return error;
}
void RooUnfoldTestHarness::SetupCanvas()
{
gROOT->SetStyle("Plain");
gStyle->SetOptStat(0);
gStyle->SetPalette(1,0);
if (!onepage) gStyle->SetOptTitle(0);
if (onepage < 3) gStyle->SetHistLineWidth(2);
if (onepage) {
if (wpaper>0) gStyle->SetCanvasDefW (wpaper);
if (hpaper>0) gStyle->SetCanvasDefH (hpaper);
canvas= new TCanvas (GetName(), GetName(), 1);
} else
canvas= new TCanvas (GetName(), GetName(), wpaper, hpaper);
TString psfile(GetName());
psfile += ".ps";
ps= new TPostScript (psfile, 112);
bool grid= false;
if (onepage==2) {
gStyle->SetPadTopMargin(0.05);
gStyle->SetPadRightMargin(0.02);
gStyle->SetPadBottomMargin(0.08);
gStyle->SetPadLeftMargin(0.06);
canvas->Divide(1,2);
TPad* pad1= (TPad*) canvas->GetPad(1);
TPad* pad2= (TPad*) canvas->GetPad(2);
pad1->SetPad (pad1->GetXlowNDC(), .3, pad1->GetXlowNDC()+pad1->GetWNDC(), pad1->GetYlowNDC()+pad1->GetHNDC());
pad2->SetPad (pad2->GetXlowNDC(), pad2->GetYlowNDC(), pad2->GetXlowNDC()+pad2->GetWNDC(), .3);
if (grid) {
pad1->SetGrid(1);
pad2->SetGrid(1);
}
} else if (onepage>=6) {
if (grid) canvas->SetGrid();
canvas->Divide(2,(onepage+1)/2);
} else if (onepage>=3) {
canvas->Divide(1,onepage);
} else if (grid)
canvas->SetGrid(1);
ipad= 0;
}
Int_t RooUnfoldTestHarness::RunTests()
{
if (stage != 2) {
TString name("response"), title;
title.Form ("Test %dD", dim);
response= new RooUnfoldResponse (name, title);
if (!response) return 3;
if (overflow==1) response->UseOverflow();
if (verbose>=0) cout << "==================================== TRAIN ====================================" << endl;
if (!Train()) return 4;
TFile f (rootfile, "recreate");
f.WriteTObject (response, "response");
f.Close();
}
if (stage != 1) {
if (!response) {
cout << "Read 'response' object from " << rootfile << endl;
TFile f (rootfile);
f.GetObject ("response", response);
f.Close();
if (!response) {
cerr << "could not read 'response' object from " << rootfile << endl;
return 5;
}
}
if (verbose>=0) cout << "==================================== TEST =====================================" << endl;
if (!Test()) return 6;
if (verbose>=0) cout << "==================================== UNFOLD ===================================" << endl;
if (!Unfold()) {
if (dofit) Fit();
if (dodraw) Results();
return 7;
}
if (dofit) Fit();
if (dodraw) {
if (!plotparms){
if (stage == 0) TrainResults();
Results();
}
if (ploterrors) PlotErrors();
if (plotparms) PlotParms();
}
}
return 0;
}
//==============================================================================
// Train: create response matrix
//==============================================================================
Int_t RooUnfoldTestHarness::Train()
{
TVectorD xtrue(ntrain);
hPDFx= Generate (xtrue, "trainpdfx", "Training PDF X", ntx, ftrainx, ntrain, xlo, xhi, mtrainx, wtrainx, btrainx, xbias, xsmear);
if (!hPDFx) return 0;
hTrainTrue= new TH1D ("traintrue", "Training", ntx, xlo, xhi);
hTrainTrue->SetLineColor(kBlue);
hTrain= new TH1D ("train", "Training Measured", nmx, xlo, xhi);
hTrain->SetLineColor(kRed);
hResmat= new TH2D ("resmat", "Response Matrix", nmx, xlo, xhi, ntx, xlo, xhi);
response->Setup (nmx, xlo, xhi, ntx, xlo, xhi);
// or: response->Setup (hTrain, hTrainTrue);
for (Int_t i= 0; i<ntrain; i++) {
Double_t xt= (*&xtrue)[i]; // work round CINT crash on xtrue[i] (MacOSX x86_64 ROOT bug #75874)
Double_t xto= Overflow (xt, ntx, xlo, xhi);
hTrainTrue->Fill (xto);
if (Eff (xt, xlo, xhi, effxlo, effxhi)) {
Double_t x= Smear (xt, ntx, xlo, xhi, xbias, xsmear);
Double_t xo= Overflow (x, nmx, xlo, xhi);
hTrain ->Fill (xo);
hResmat ->Fill (xo, xto);
response->Fill (xo, xto);
} else {
response->Miss (xto);
}
}
TVectorD xfake;
Int_t nfake= Fakes (xfake, nmx, ntrain, xlo, xhi, fakexlo, fakexhi);
if (nfake>0) {
hTrainFake= new TH1D ("trainfake", "Training Fakes", nmx, xlo, xhi);
hTrainFake->SetLineColor(93);
for (Int_t i= 0; i<nfake; i++) {
Double_t xf= (*&xfake)[i];
hTrain ->Fill (xf);
hTrainFake->Fill (xf);
response ->Fake (xf);
}
}
// or: response->Setup (hTrain, hTrainTrue, hResmat);
// or: response->Setup (0, 0, hResmat); // if no inefficiency or fakes
if (verbose>=2) response->Print();
return 1;
}
void RooUnfoldTestHarness::TrainResults()
{
if (mscalex!=1.0) {
// should really use Sumw2() for these, but we don't show errors
hTrain->Scale(mscalex,"nosw2");
if (hTrainFake) hTrainFake->Scale(mscalex,"nosw2");
}
setmax (hTrainTrue, hPDFx, hTrain, hTrainFake);
if (onepage && (onepage<4 || ipad>=onepage)) return;
if (onepage) canvas->cd(++ipad);
hTrainTrue->Draw();
hPDFx ->Draw("LSAME");
hTrain->Draw("SAME");
if (hTrainFake) hTrainFake->Draw("SAME");
if (!onepage) Legend (lTrain, hPDFx, hTrainTrue, hTrainFake, hTrain);
canvas->Update();
}
//==============================================================================
// Test distribution
//==============================================================================
Int_t RooUnfoldTestHarness::Test()
{
TVectorD xtest(ntest);
hTestPDFx= Generate (xtest, "pdfx", "PDF X", ntx, ftestx, ntest, xlo, xhi, mtestx, wtestx, btestx, xbias, xsmear);
if (!hTestPDFx) return 0;
hTrue= new TH1D ("truth", "Test", ntx, xlo, xhi);
hTrue->SetLineColor(kBlue);
hMeas= new TH1D ("meas", "Test Measured", nmx, xlo, xhi);
hMeas->SetLineColor(kRed);
for (Int_t i=0; i<ntest ; i++) {
Double_t xt= (*&xtest)[i];
Double_t xto= Overflow (xt, ntx, xlo, xhi);
hTrue->Fill(xto);
if (Eff (xt, xlo, xhi, effxlo, effxhi)) {
Double_t x = Smear (xt, ntx, xlo, xhi, xbias, xsmear);
Double_t xo= Overflow (x, nmx, xlo, xhi);
hMeas->Fill(xo);
}
}
TVectorD xfake;
Int_t nfake= Fakes (xfake, nmx, ntest, xlo, xhi, fakexlo, fakexhi);
if (nfake>0) {
hFake= new TH1D ("fake", "Test Fakes", nmx, xlo, xhi);
hFake->SetLineColor(93);
for (Int_t i= 0; i<nfake; i++) {
Double_t xf= (*&xfake)[i];
hMeas->Fill (xf);
hFake->Fill (xf);
}
}
return 1;
}
//==============================================================================
// Add bin correlations to measured errors
//==============================================================================
void RooUnfoldTestHarness::SetMeasuredCov ()
{
if (bincorr==0.0) return;
TMatrixD cov= unfold->GetMeasuredCov(); // initially diagonal
if (bincorr!=999.0) { // use bincorr=999 to test with truely diagonal matrix
Double_t corr= bincorr;
for (Int_t k=1; k<nmbins; k++) {
for (Int_t i=k; i<nmbins; i++)
cov(i,i-k)= cov(i-k,i)= corr*cov(i,i);
corr *= bincorr;
if (corr==0.0) break;
}
}
unfold->SetMeasuredCov (cov);
hMeasCorr= CorrelationHist (cov, "measCor", "Measured correlation matrix",
response->Hresponse()->GetXaxis()->GetXmin(),
response->Hresponse()->GetXaxis()->GetXmax());
}
//==============================================================================
// Unfold
//==============================================================================
Int_t RooUnfoldTestHarness::Unfold ()
{
if (verbose>=0) cout << "Create RooUnfold object for method " << method << endl;
unfold= RooUnfold::New ((RooUnfold::Algorithm)method, response, hMeas, regparm, "unfold");
if (!unfold) return 0;
unfold->SetVerbose (verbose);
if (ntoys<0) ntoys= (ploterrors) ? 500 : 50;
unfold->SetNToys(ntoys);
unfold->IncludeSystematics(dosys);
SetMeasuredCov();
#ifdef USE_TUNFOLD_H
if (method == RooUnfold::kTUnfold) (dynamic_cast<RooUnfoldTUnfold*>(unfold))->SetRegMethod((TUnfold::ERegMode)regmethod);
#endif
if (verbose>=0) {cout << "Created "; unfold->Print();}
hReco= unfold->Hreco((RooUnfold::ErrorTreatment)doerror);
if (!hReco) return 0;
hReco->SetName("reco");
hReco->SetLineColor(kBlack); // otherwise inherits style from hTrainTrue
if (verbose>=0) unfold->PrintTable (cout, hTrue, (RooUnfold::ErrorTreatment)doerror);
if (verbose>=2 && doerror>=RooUnfold::kCovariance) {
TMatrixD covmat= unfold->Ereco((RooUnfold::ErrorTreatment)doerror);
TMatrixD errmat(ntbins,ntbins);
for (Int_t i=0; i<ntbins; i++)
for (Int_t j=0; j<ntbins; j++)
errmat(i,j)= covmat(i,j)>=0 ? sqrt(covmat(i,j)) : -sqrt(-covmat(i,j));
RooUnfoldResponse::PrintMatrix(errmat,"covariance matrix");
}
// Calculate pulls and residuals
hRes= dynamic_cast<TH1*>(hReco->Clone ("res"));
hRes ->Reset();
hRes ->SetTitle ("Residuals");
hPulls= dynamic_cast<TH1*>(hReco->Clone ("pulls"));
hPulls->Reset();
hPulls->SetTitle ("Pulls");
for (Int_t i= 1; i<=ntbins; i++) {
if ((hReco->GetBinContent(i)!=0.0 || (doerror && hReco->GetBinError(i)>0.0)) &&
(hTrue->GetBinContent(i)!=0.0 || (doerror && hTrue->GetBinError(i)>0.0))) {
Double_t res= hReco->GetBinContent(i) - hTrue->GetBinContent(i);
Double_t err= hReco->GetBinError (i);
hRes->SetBinContent (i, res);
hRes->SetBinError (i, err);
if (err>0.0) {
hPulls->SetBinContent (i, res/err);
hPulls->SetBinError (i, 1.0);
}
}
}
hCorr= CorrelationHist (unfold->Ereco((RooUnfold::ErrorTreatment)doerror),
"corr", "Unfolded correlation matrix",
response->Hresponse()->GetYaxis()->GetXmin(),
response->Hresponse()->GetYaxis()->GetXmax());
return 1;
}
//==============================================================================
// Show results
//==============================================================================
void RooUnfoldTestHarness::Results()
{
if (mscalex!=1.0) {
// should really use Sumw2() for these, but we don't show errors
hMeas->Scale(mscalex,"nosw2");
if (hFake) hFake->Scale(mscalex,"nosw2");
if (fitFunc) fitFunc->GetHistogram()->Scale(mscalex,"nosw2");
}
setmax (hTrue, hTestPDFx, hMeas, hFake);
if (hReco) {
hReco->SetMarkerStyle(kFullDotLarge);
setmax (hTrue, hReco);
}
if (onepage && ipad>=onepage) return;
if (onepage) canvas->cd(++ipad);
hTrue ->Draw();
hTestPDFx->Draw("LSAME");
if (fitFunc) fitFunc->GetHistogram()->Draw("SAME");
if (trueFunc) trueFunc->Draw("LSAME");
hMeas ->Draw("SAME");
if (hFake) hFake->Draw("SAME");
if (hReco) hReco->Draw("SAME P");
Legend (lTest, hTestPDFx, hTrue, hFake, hMeas, hReco, fitFunc, trueFunc);
canvas->Update();
if (!hReco) return;
if (ploterrors>=2) return;
if (onepage && ipad>=onepage) return;
if (onepage) canvas->cd(++ipad);
hRes->SetMarkerStyle(kFullDotLarge);
hRes->Draw();
TLine().DrawLine(hRes->GetBinLowEdge(1), 0.0, hRes->GetBinLowEdge(ntx+1), 0.0); // draw a line at y=0;
canvas->Update();
if (ploterrors) return;
if (onepage && ipad>=onepage) return;
if (onepage) canvas->cd(++ipad);
gPad->Divide(2,1);
gPad->cd(1);
if (hMeasCorr) {
hMeasCorr->Draw("COLZ");
canvas->cd(ipad);
gPad->cd(2);
}
hCorr->Draw("COLZ");
canvas->Update();
if (onepage && ipad>=onepage) return;
if (onepage) canvas->cd(++ipad);
hPulls->SetMarkerStyle(kFullDotLarge);
hPulls->Draw("P");
TLine().DrawLine(hPulls->GetBinLowEdge(1), 0.0, hPulls->GetBinLowEdge(ntx+1), 0.0); // draw a line at pull=0;
canvas->Update();
}
void RooUnfoldTestHarness::PlotErrors()
{
if (onepage && ipad>=onepage) return;
if (onepage) canvas->cd(++ipad);
TH1* t= 0;
if (ploterrors>=2) t=hTrue;
errors= new RooUnfoldErrors(ntoys,unfold,t);
hToyErr=errors->RMSResiduals();
hUnfErr=errors->UnfoldingError();
setmax(hUnfErr,hToyErr);
hUnfErr->Draw("HIST");
hToyErr->Draw("P SAME");
lErrors= new TLegend (0.75, 0.75, 0.894, 0.89);
lErrors->SetTextSize(0.05);
lErrors->SetTextFont(42);
lErrors->AddEntry (hUnfErr, "Unfolding errors", "L");
lErrors->AddEntry (hToyErr, "Toy MC RMS", "P");
lErrors->Draw();
canvas->Update();
if (ploterrors<2) return;
if (onepage && ipad>=onepage) return;
if (onepage) canvas->cd(++ipad);
ntChi2= errors->Chi2();
Double_t good_chi= ntChi2->Draw("chi2","abs(chi2)<1e10");
if (ntoys>good_chi){
TString chi;
chi+=(ntoys-good_chi);
chi += (" bad #chi^{2}s");
TPaveText* pave=new TPaveText;
pave->SetFillColor(0);
pave->SetX1NDC(0.7);
pave->SetX2NDC(0.9);
pave->SetY1NDC(0.7);
pave->SetY2NDC(0.9);
TText *t1=pave->AddText(chi);
t1->SetTextSize(0.07);
pave->Draw();
}
canvas->Update();
}
void RooUnfoldTestHarness::PlotParms()
{
if (onepage && ipad>=onepage) return;
if (onepage) canvas->cd(++ipad);
parms= new RooUnfoldParms(unfold,(RooUnfold::ErrorTreatment)doerror,hTrue);
if (maxparm>minparm) parms->SetMaxParm(maxparm);
if (minparm!=-1e30) parms->SetMinParm(minparm);
if (stepsize>0) parms->SetStepSizeParm(stepsize);
hParmChi2= parms->GetChi2();
hParmChi2->Draw("P");
canvas->Update();
if (onepage && ipad>=onepage) return;
if (onepage) canvas->cd(++ipad);
hParmErr= parms->GetRMSError();
hParmErr->Draw("P");
canvas->Update();
if (onepage && ipad>=onepage) return;
if (onepage) canvas->cd(++ipad);
hParmRes= parms->GetMeanResiduals();
hParmRes->Draw("P");
canvas->Update();
if (onepage && ipad>=onepage) return;
if (onepage) canvas->cd(++ipad);
hParmRms= parms->GetRMSResiduals();
hParmRms->Draw("P");
canvas->Update();
}
//==============================================================================
// Parametric Fit - an alternative to unfolding
//==============================================================================
TF1* RooUnfoldTestHarness::FitFunc (Int_t fpdf, TH1* h, Double_t mean, Double_t width, Double_t bkg)
{
// Implement PDFs as TF1 functions. These should match the functions defined in
// RooUnfoldTestPdf.icc or RooUnfoldTestPdfRooFit.icc.
static const Double_t pi= atan2 (0.0, -1.0);
if (bkg<0.0) bkg= 0.0;
if (bkg>1.0) bkg= 1.0;
if (fpdf==0) bkg= 0.0;
Int_t nb= h->GetNbinsX();
const Double_t nx= h->GetEntries(), xlo= h->GetXaxis()->GetXmin(), xhi= h->GetXaxis()->GetXmax();
const Double_t xwidth= xhi-xlo, unorm= nx * (xwidth / nb);
const Double_t norm= unorm*(1.0-bkg), bnorm= unorm*bkg/xwidth;
TF1* f=0;
switch (fpdf) {
case 0: {
f= new TF1 ("trueFunc", "[0]", xlo, xhi);
f->SetParameters (0, norm / xwidth);
break;
}
case 1: {
const Double_t fnorm= norm / (6.0*width), xw=0.1*xwidth/nb;
// Fit can't cope with a pure step function, so add a slope
f= new TF1 ("trueFunc",
Form("[0]*(ROOT::Math::gaussian_cdf((x-[2]+[3])/(%g)) - ROOT::Math::gaussian_cdf((x-[2]-[3])/(%g))) + [1]",xw,xw),
xlo, xhi);
f->SetParNames ("norm", "bkg", "low", "width");
f->SetParameters (fnorm, bnorm, mean, 3.0*width);
f->SetParLimits (0, 0.0, 10.0*fnorm);
f->SetParLimits (1, 0.0, 10.0*bnorm);
f->SetParLimits (2, xlo, xhi);
f->SetParLimits (3, 0.0, xhi-xlo);
break;
}
case 2: {
const Double_t fnorm= norm / (sqrt(2*pi) * width);
f= new TF1 ("trueFunc", "[0]*exp(-0.5*((x-[2])/[3])**2) + [1]", xlo, xhi);
f->SetParNames ("norm", "bkg", "mean", "width");
f->SetParameters (fnorm, bnorm, mean, width);
f->SetParLimits (0, 0.0, 10.0*fnorm);
f->SetParLimits (1, 0.0, 10.0*bnorm);
f->SetParLimits (2, xlo, xhi);
f->SetParLimits (3, 0.0, 5.0*(xhi-xlo));
break;
}
case 3: {
const Double_t fnorm= norm / (2.0*width);
f= new TF1 ("trueFunc", "[0]*exp(-abs(x-[2])/[3]) + [1]", xlo, xhi);
f->SetParNames ("norm", "bkg", "mean", "width");
f->SetParameters (fnorm, bnorm, mean, width);
f->SetParLimits (0, 0.0, 10.0*fnorm);
f->SetParLimits (1, 0.0, 10.0*bnorm);
f->SetParLimits (2, xlo, xhi);
f->SetParLimits (3, 0.0, 5.0*(xhi-xlo));
break;
}
case 4: {
const Double_t fnorm= norm * width / (2*pi);
f= new TF1 ("trueFunc", "[0]/((x-[2])**2+0.25*[3]**2) + [1]", xlo, xhi);
f->SetParNames ("norm", "bkg", "mean", "width");
f->SetParameters (fnorm, bnorm, mean, width);
f->SetParLimits (0, 0.0, 10.0*fnorm);
f->SetParLimits (1, 0.0, 10.0*bnorm);
f->SetParLimits (2, xlo, xhi);
f->SetParLimits (3, 0.0, 5.0*(xhi-xlo));
break;
}
case 5: {
const Double_t fnorm= norm * width / (4*pi);
f= new TF1 ("trueFunc", "[0]*(1.0/((x-[2])**2+0.25*[4]**2) + 1.0/((x-[3])**2+0.25*[4]**2)) + [1]", xlo, xhi);
f->SetParNames ("norm", "bkg", "mean1", "mean2", "width");
f->SetParameters (fnorm, bnorm, mean-width, mean+width, width);
f->SetParLimits (0, 0.0, 10.0*fnorm);
f->SetParLimits (1, 0.0, 10.0*bnorm);
f->SetParLimits (2, xlo, xhi);
f->SetParLimits (3, xlo, xhi);
f->SetParLimits (4, 0.0, 5.0*(xhi-xlo));
break;
}
case 6: {
const Double_t tau = mean-xlo;
const Double_t fnorm= norm / (tau * (exp(-xlo/tau) - exp(-xhi/tau)));
f= new TF1 ("trueFunc", "[0]*exp(-x/[2]) + [1]", xlo, xhi);
f->SetParNames ("norm", "bkg", "tau");
f->SetParameters (fnorm, bnorm, tau);
f->SetParLimits (0, 0.0, 10.0*fnorm);
f->SetParLimits (1, 0.0, 10.0*bnorm);
f->SetParLimits (2, 0.0, 10.0*tau);
break;
}
case 7: {
const Double_t tau = mean-xlo;
const Double_t mywidth = width/4.0;
const Double_t fexp = 0.9;
const Double_t rnorm= norm / (sqrt(2*pi) * mywidth);
const Double_t enorm= norm / (tau * (exp(-xlo/tau) - exp(-xhi/tau)));
f= new TF1 ("trueFunc", "[0]*exp(-0.5*((x-[3])/[4])**2) + [2]*exp(-x/[5]) + [1]", xlo, xhi);
f->SetParNames ("G-norm", "bkg", "E-norm", "mean", "width", "tau");
f->SetParameters ((1.0-fexp)*rnorm, bnorm, fexp*enorm, mean, width, tau);
f->SetParLimits (0, 0.0, 10.0*rnorm);
f->SetParLimits (1, 0.0, 10.0*enorm);
f->SetParLimits (2, 0.0, 10.0*bnorm);
f->SetParLimits (3, xlo, xhi);
f->SetParLimits (4, 0.0, 5.0*(xhi-xlo));
f->SetParLimits (5, 0.0, 10.0*tau);
break;
}
default:
cerr << "PDF " << fpdf << " not defined" << endl;
}
// if (f) f->Print();
return f;
}
void RooUnfoldTestHarness::Fit ()
{
trueFunc= FitFunc (ftestx, hTrue, mtestx+0.3, wtestx*1.4, btestx*0.7); // add some fudge to challenge fit
if (!trueFunc) return;
trueFunc->SetLineColor(kGreen+3);
trueFunc->SetNpx(std::max(10*ntbins,100));
fitFunc= response->MakeFoldingFunction (trueFunc, 1e-12, verbose>=3);
if (!fitFunc) return;
fitFunc->SetLineColor(800);
hMeas->Fit (fitFunc, (verbose>=2 ? "NV" : verbose>=1 ? "N" : "NQ"));
}
//==============================================================================
// Generate PDF using RooUnfoldTestPdf
//==============================================================================
TH1D* RooUnfoldTestHarness::Generate (TVectorD& x, const char* name, const char* title,
Int_t nt, Int_t fpdf, Int_t nx, Double_t lo, Double_t hi,
Double_t mean, Double_t width, Double_t bkg,
Double_t /* bias */, Double_t /* smear */)
{
TH1D* hPDF= new TH1D (name, title, nbPDF, lo, hi);
hPDF->SetLineColor(kGreen);
hPDF->SetLineWidth(2);
if (overflow == 1) {
// Fill under/overflow bins too
Double_t xbin= (hi-lo) / Double_t(nt);
lo -= xbin;
hi += xbin;
}
if (verbose >= 1) cout << "Generate values in range " << lo << " to " << hi << endl;
if (!RooUnfoldTestPdf (fpdf, nx, lo, hi, x, hPDF, mean, width, bkg, verbose)) return 0;
hPDF->Scale (nbPDF/Double_t(nt), "nosw2");
return hPDF;
}
//==============================================================================
// Generate fakes using a linear PDF from (x0,y0) to (x1,y1)
//==============================================================================
Int_t RooUnfoldTestHarness::Fakes (TVectorD& x, Int_t nm, Int_t nx, Double_t x0, Double_t x1, Double_t y0, Double_t y1) const
{
if (!addfakes || (y0<=0.0 && y1<=0.0)) return 0;
if (overflow == 1) {
// Fill under/overflow bins too
Double_t xw= x1-x0;
if (xw<=0) return 0;
Double_t xbin= xw / Double_t(nm), ybin= (y1-y0)*(xbin/xw);
x0 -= xbin;
x1 += xbin;
y0 -= ybin;
y1 += ybin;
}
// Reduce x-range to remove negative PDF
Double_t yw= y1-y0;
if (y0<0.0) {
x0= (x0*y1-x1*y0) / yw;
y0= 0.0;
yw= y1;
}
if (y1<0.0) {
x1= (x0*y1-x1*y0) / yw;
y1= 0.0;
yw= -y0;
}
Double_t xw= x1-x0;
if (xw<=0.0) return 0;
if (yw==0.0) {
// uniform PDF
nx= Int_t(nx*y0+0.5); // scale number of events by y0
if (nx<=0) return 0;
if (verbose >= 1) cout << "Generate " << nx << " fakes in range " << x0 << " to " << x1 << endl;
x.ResizeTo(nx);
for (Int_t i=0; i<nx; i++)
(*&x)[i]= x0 + xw*gRandom->Rndm();
return nx;
} else {
// linear PDF
Double_t c= x1*y0-x0*y1;
Double_t N= 0.5*yw*(x1+x0) + c;
Double_t xa= -c/yw, xb= (c*c)/(yw*yw) + x0*x0 + 2.0*c*x0/yw, yb= 2.0*N*(xw/yw);
nx= Int_t(nx*(N/xw)+0.5); // scale number of events by integral/xw
if (nx<=0) return 0;
if (verbose >= 1) cout << "Generate " << nx << " fakes in range " << x0 << " to " << x1 << endl;
x.ResizeTo(nx);
Int_t nnx= 0;
for (Int_t i=0; i<nx; i++) {
Double_t u= gRandom->Rndm();
Double_t xc2= xb + yb*u;
if (xc2<0.0) continue;
Double_t xc= sqrt(xc2), xp= xa+xc, xn= xa-xc;
Double_t xv;
if (xp>=x0 && xp<x1) xv= xp; // which root to take? Maybe always this +ve one.
else if (xn>=x0 && xn<x1) xv= xn;
else continue;
(*&x)[nnx++]= xv;
}
if (nnx < nx) {
if (verbose >= 0) cout << "Trouble generating " << nx-nnx << " fakes (of " << nx << ")" << endl;
nx= nnx;
x.ResizeTo(nx);
}
}
return nx;
}
//==============================================================================
// Gaussian smearing, systematic translation, and variable inefficiency
//==============================================================================
bool RooUnfoldTestHarness::Eff (Double_t x, Double_t lo, Double_t hi, Double_t efflo, Double_t effhi) const
{
// Apply an efficiency function to the truth.
// Efficiency: 30% at x=lo, 90% at x=hi.
if (!doeff || (efflo>=1.0 && effhi>=1.0)) return true;
Double_t xwidth = (hi-lo);
Double_t slope = (effhi-efflo) / xwidth;
Double_t yeff= (efflo + slope * (x-lo)); // efficiency
// MC test: if random number < eff then accept
return (gRandom->Rndm() < yeff);
}
Double_t RooUnfoldTestHarness::Smear (Double_t x, Int_t nt, Double_t lo, Double_t hi, Double_t bias, Double_t smear) const
{
// Apply a gaussian smearing and systematic translation to the truth.
Double_t xsigma = (hi-lo) * smear / Double_t(nt); // smear sigma
if (!addbias || x < lo || x > hi)
bias= 0.0;
else {
// actual bias is a quartic with maximum of "bias" in mid-range,
// dropping to 0 at edges so we don't shift events in/out of range
// (except a bit by smearing)
Double_t xm= (2*x-(hi+lo)) / (hi-lo), xm2= xm*xm;
bias *= 1.0-(xm2*xm2);
}
Double_t delta= xsigma <= 0.0 ? bias : gRandom->Gaus (bias, xsigma); // bias and smear
if (verbose>=3) cout << "SMEAR " << x << " " << xsmear << " " << xsigma << endl;
return x+delta;
}
Double_t RooUnfoldTestHarness::Overflow (Double_t x, Int_t nb, Double_t lo, Double_t hi) const
{
if (overflow!=2) return x;
else if (x < lo) return lo + (hi-lo) / Double_t(2*nb);
else if (!(x < hi)) return hi - (hi-lo) / Double_t(2*nb);
else return x;
}
//==============================================================================
// Constructors and destructor
//==============================================================================
RooUnfoldTestHarness::RooUnfoldTestHarness (const char* name)
: TNamed(name,name)
{
Reset();
SetDefaults();
}
RooUnfoldTestHarness::RooUnfoldTestHarness (const char* name, int argc, const char* const* argv)
: TNamed(name,name)
{
Reset();
error= SetArgs (argc, argv);
}
RooUnfoldTestHarness::RooUnfoldTestHarness (const char* name, const char* args)
: TNamed(name,name)
{
Reset();
const char* const argv[]= { name, args };
error= SetArgs (2, argv, true);
}
RooUnfoldTestHarness::~RooUnfoldTestHarness()
{
delete errors; errors= 0;
delete parms; parms= 0;
delete response; response= 0;
delete unfold; unfold= 0;
delete canvas; canvas= 0;
delete ps; ps= 0;
}
//==============================================================================
// Utility routines
//==============================================================================
void RooUnfoldTestHarness::Reset()
{
errors= 0;
parms= 0;
response= 0;
unfold= 0;
canvas= 0;
ps= 0;
hPDFx= hTestPDFx= 0;
hTrain= hTrainTrue= hTrainFake= hTrue= hMeas= hFake= hReco= hRes= hPulls=
hUnfErr= hToyErr= hParmChi2= hParmErr= hParmRes= hParmRms= 0;
hResmat= hCorr= hMeasCorr= 0;
fitFunc= trueFunc= 0;
ntChi2= 0;
lTrain= lTest= lErrors= 0;
error= ipad= 0;
dim= 1;
nbPDF= 500;
wpaper= hpaper= 0;
}
void RooUnfoldTestHarness::SetDefaults()
{
ArgVars args;
Parms (args);
args.SetDefaults();
}
int RooUnfoldTestHarness::SetArgs (int argc, const char* const* argv, bool split)
{
ArgVars args;
Parms (args);
return args.SetArgs (argc, argv, split);
}
void RooUnfoldTestHarness::Init()
{
if (setname.Length()>0) SetName (setname);
rootfile= GetName();
rootfile += ".root";
if (nmx==-1) nmx= ntx;
if (overflow==2) {
Double_t xwid= (xhi-xlo) / ntx;
xlo -= xwid;
xhi += xwid;
ntx += 2;
nmx += 2;
}
mscalex= (nmx==ntx) ? 1.0 : Double_t(nmx)/Double_t(ntx);
ntbins= ntx;
nmbins= nmx;
if (onepage) {
if (hpaper==0) hpaper= 900;
} else {
if (wpaper==0) wpaper= 750;
if (hpaper==0) hpaper= 300;
}
if (seed>=0) {
gRandom->SetSeed(seed); // seed=0, uses a unique (UUID) seed each job (see TRandom3::SetSeed)
#ifdef USE_ROOFIT
RooRandom::randomGenerator()->SetSeed(seed ? seed+8243 : 0);
#endif
}
}
Int_t RooUnfoldTestHarness::CheckParms()
{
if (addbias==-1)
addbias= (method==RooUnfold::kBinByBin || method==RooUnfold::kInvert) ? 0 : 1; // bin-by-bin/invert methods can't handle bias
if (verbose>=0) PrintParms (cout);
if (xlo >= xhi) {cout << "Error: xlo (" << xlo << ") >= xhi(" << xhi << ")" << endl; error = 2;}
if (ntest<=0) {cout << "Error: ntest (" << ntest << ") <= 0" << endl; error = 2;}
if (ntrain<=0) {cout << "Error: ntrain (" << ntrain << ") <= 0" << endl; error = 2;}
if (nmx<=0) {cout << "Error: nmx (" << nmx << ") <= 0" << endl; error = 2;}
if (ntx<=0) {cout << "Error: ntx (" << ntx << ") <= 0" << endl; error = 2;}
if (ftestx<0) {cout << "Error: ftestx (" << ftestx << ") < 0" << endl; error = 2;}
if (ftrainx<0) {cout << "Error: ftrainx ("<< ftrainx<< ") < 0" << endl; error = 2;}
return error;
}
void RooUnfoldTestHarness::PrintParms (std::ostream& o) const
{
ArgVars args;
const_cast<RooUnfoldTestHarness*>(this)->Parms (args);
o << GetName() << " ";
args.Print (o);