ViewVC Help
View File | Revision Log | Show Annotations | Root Listing
root/cvsroot/UserCode/cbrown/Development/Plotting/Modules/EdgeLimit.C
Revision: 1.16
Committed: Thu Jun 13 13:43:33 2013 UTC (11 years, 10 months ago) by buchmann
Content type: text/plain
Branch: MAIN
Changes since 1.15: +34 -16 lines
Log Message:
Also added situation after OF fit only in a separate plot

File Contents

# User Rev Content
1 buchmann 1.1 #include <iostream>
2    
3 buchmann 1.10 #include <TVirtualIndex.h>
4    
5 buchmann 1.2 #include <RooRealVar.h>
6     #include <RooArgSet.h>
7     #include <RooDataSet.h>
8 buchmann 1.4 #include <RooMCStudy.h>
9     #include <RooCategory.h>
10    
11 buchmann 1.5 #include <RooPlot.h>
12     #include <RooSimultaneous.h>
13     #include <RooAddPdf.h>
14     #include <RooFitResult.h>
15     #include <RooVoigtian.h>
16     #include <RooMsgService.h>
17    
18 buchmann 1.3 #include <RooStats/ModelConfig.h>
19     #include "RooStats/ProfileLikelihoodCalculator.h"
20     #include "RooStats/LikelihoodInterval.h"
21     #include "RooStats/HypoTestResult.h"
22     #include "RooStats/SimpleLikelihoodRatioTestStat.h"
23     #include "RooStats/ProfileLikelihoodTestStat.h"
24     #include "RooStats/HybridCalculatorOriginal.h"
25     #include "RooStats/HypoTestInverterOriginal.h"
26    
27 buchmann 1.5 //#include "ParametrizedEdge.C"
28 buchmann 1.8 #include "EdgeModules/RooSUSYTPdf.cxx"
29     #include "EdgeModules/RooSUSYBkgPdf.cxx"
30 buchmann 1.5
31 buchmann 1.2
32 buchmann 1.1 using namespace std;
33     using namespace PlottingSetup;
34    
35    
36 buchmann 1.2
37    
38 buchmann 1.1 ShapeDroplet LimitsFromEdge(float low_fullCLs, float high_CLs, TTree *events, string addcut, string name, string mcjzb, string datajzb, vector<float> jzbbins, float jzbpeakerrormc, float jzbpeakerrordata) {
39     write_error(__FUNCTION__,"Not implemented edge limits yet (returning crap)");
40     ShapeDroplet beta;beta.observed=-12345;beta.SignalIntegral=1;return beta;
41     }
42    
43    
44     void PrepareEdgeShapes(string mcjzb, string datajzb, vector<float> jzbbins, float jzbpeakerrordata) {
45     write_error(__FUNCTION__,"Not implemented edge shape storage yet");
46     }
47    
48    
49 buchmann 1.2 ///------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
50    
51    
52     namespace EdgeFitter {
53    
54     void DoEdgeFit(string mcjzb, string datajzb, float DataPeakError, float MCPeakError, float jzb_cut, int icut, int is_data, TCut cut, TTree*);
55     void DoEdgeFit(string mcjzb, string datajzb, float DataPeakError, float MCPeakError, vector<float> jzb_cut, int is_data, TCut cut, TTree*);
56 buchmann 1.7 void getMedianLimit(RooWorkspace *ws,vector<RooDataSet> theToys,float &median,float &sigmaDown, float &sigmaUp, float &twoSigmaDown, float &twoSigmaUp);
57 buchmann 1.2 void InitializeVariables(float _mllmin, float _mllmax, float _jzbmax, TCut _cut);
58     void PrepareDatasets(int);
59 buchmann 1.15 void DrawDatasetContent(int);
60 buchmann 1.5 void DoFit(int is_data, float jzb_cut);
61 buchmann 1.2 string RandomStorageFile();
62     Yield Get_Z_estimate(float,int);
63     Yield Get_T_estimate(float,int);
64 buchmann 1.7 float calcExclusion(RooWorkspace *ws, RooDataSet data, bool calcExclusion);
65     vector<RooDataSet> generateToys(RooWorkspace *ws, int nToys);
66 buchmann 1.4 void prepareLimits(RooWorkspace *ws, bool ComputeBands);
67     TGraph* prepareLM(float mass, float nEv);
68 buchmann 1.2
69     float jzbmax;
70     float mllmin;
71     float mllmax;
72     TCut cut;
73    
74     RooDataSet* AllData;
75 buchmann 1.10 RooDataSet* SFSample;
76     RooDataSet* OFSample;
77 buchmann 1.2
78 buchmann 1.6 bool MarcoDebug=true;
79 buchmann 1.11
80     float FixedMEdge=-1;
81     float FixedMEdgeChi2=-1;
82    
83 buchmann 1.14 bool RejectPointIfNoConvergence=false;
84    
85     string Mode="UndefinedMode";
86    
87 buchmann 1.2 }
88    
89 buchmann 1.4 TGraph* EdgeFitter::prepareLM(float mass, float nEv) {
90     float massLM[1];
91     massLM[0]=mass;
92     float accEffLM[1];
93     accEffLM[0]=nEv/PlottingSetup::luminosity;
94     TGraph *lm = new TGraph(1, massLM, accEffLM);
95     lm->GetXaxis()->SetNoExponent(true);
96     lm->GetXaxis()->SetTitle("m_{cut} [GeV]");
97     lm->GetYaxis()->SetTitle("#sigma #times A [pb] 95% CL UL");
98     lm->GetXaxis()->SetLimits(0.,300.);
99     lm->GetYaxis()->SetRangeUser(0.,0.08);
100     lm->SetMarkerStyle(34);
101     lm->SetMarkerColor(kRed);
102     return lm;
103     }
104    
105 buchmann 1.7 vector<RooDataSet> EdgeFitter::generateToys(RooWorkspace *ws, int nToys) {
106 buchmann 1.10 ws->ls();
107 buchmann 1.4 ws->var("nSig")->setVal(0.);
108     ws->var("nSig")->setConstant(true);
109     RooFitResult* fit = ws->pdf("combModel")->fitTo(*ws->data("data_obs"),RooFit::Save());
110 buchmann 1.7 vector<RooDataSet> theToys;
111 buchmann 1.4
112     RooMCStudy mcEE(*ws->pdf("combModel"),RooArgSet(*ws->var("inv")),RooFit::Slice(*ws->cat("cat"),"EE"));
113     mcEE.generate(nToys,44,true);
114     RooMCStudy mcMM(*ws->pdf("combModel"),RooArgSet(*ws->var("inv")),RooFit::Slice(*ws->cat("cat"),"MM"));
115     mcMM.generate(nToys,44,true);
116     RooMCStudy mcOSOF(*ws->pdf("combModel"),RooArgSet(*ws->var("inv")),RooFit::Slice(*ws->cat("cat"),"OSOF"));
117     mcOSOF.generate(nToys,44,true);
118    
119 buchmann 1.10 RooRealVar mll("m_{ll}","m_{ll}",mllmin,mllmax,"GeV/c^{2}");
120 buchmann 1.4 RooRealVar id1("id1","id1",0,1,"GeV/c^{2}");
121     RooRealVar id2("id2","id2",0,1,"GeV/c^{2}");
122     RooRealVar jzb("jzb","jzb",-jzbmax,jzbmax,"GeV/c");
123     RooRealVar weight("weight","weight",0,1000,"");
124     RooArgSet observables(mll,jzb,id1,id2,weight);
125    
126     for(int i=0;i<nToys;i++) {
127     RooDataSet* toyEE = (RooDataSet*)mcEE.genData(i);
128     RooDataSet* toyMM = (RooDataSet*)mcMM.genData(i);
129     RooDataSet* toyOSOF = (RooDataSet*)mcOSOF.genData(i);
130     stringstream toyname;
131     toyname << "theToy_" << i;
132     write_warning(__FUNCTION__,"Problem while adding toys");
133 buchmann 1.7 RooDataSet toyData = RooDataSet(toyname.str().c_str(),toyname.str().c_str(),observables,RooFit::Index(const_cast<RooCategory&>(*ws->cat("cat"))),RooFit::Import("OSOF",*toyOSOF),RooFit::Import("EE",*toyEE),RooFit::Import("MM",*toyMM));
134     theToys.push_back(toyData);
135 buchmann 1.4 }
136     ws->var("nSig")->setVal(17.0);
137     ws->var("nSig")->setConstant(false);
138     return theToys;
139     }
140    
141 buchmann 1.7 void EdgeFitter::getMedianLimit(RooWorkspace *ws,vector<RooDataSet> theToys,float &median,float &sigmaDown, float &sigmaUp, float &twoSigmaDown, float &twoSigmaUp) {
142 buchmann 1.4 TH1F *gauLimit = new TH1F("gausLimit","gausLimit",60,0.,80./PlottingSetup::luminosity);
143     vector<float> theLimits;
144 buchmann 1.9 for(int itoy=0;itoy<(int)theToys.size();itoy++) {
145 buchmann 1.7 float theLimit = calcExclusion(ws,theToys[itoy],false);
146 buchmann 1.4 if(theLimit > 0 ) gauLimit->Fill(theLimit);
147     }
148     const Int_t nQ = 4;
149     Double_t yQ[nQ] = {0.,0.,0.,0.};
150     Double_t xQ[nQ] = {0.022750132,0.1586552539,0.84134474609999998,0.977249868};
151     gauLimit->GetQuantiles(nQ,yQ,xQ);
152     median = gauLimit->GetMean();
153     // median = median1(gauLimit);
154     twoSigmaDown = abs(yQ[0]-median);
155     sigmaDown = abs(yQ[1]-median);
156     sigmaUp = abs(yQ[2]-median);
157     twoSigmaUp = abs(yQ[3]-median);
158     cout << median * PlottingSetup::luminosity << " " << sigmaUp * PlottingSetup::luminosity << endl;
159     }
160    
161     void EdgeFitter::prepareLimits(RooWorkspace *ws, bool ComputeBands) {
162     if(ComputeBands) {
163 buchmann 1.7 vector<RooDataSet> theToys = EdgeFitter::generateToys(ws,50);
164 buchmann 1.4 vector<float> medVals;
165     vector<float> medLimits;
166     vector<float> sigmaLimitsDown;
167     vector<float> sigmaLimitsUp;
168     vector<float> twoSigmaLimitsDown;
169     vector<float> twoSigmaLimitsUp;
170     for(int i=20;i<=320;i+=40) {
171     ws->var("nSig")->setVal(10.0);
172     medVals.push_back((float)i);
173     ws->var("m0")->setVal((float)i);
174     ws->var("m0")->setConstant(true);
175     float Smedian,SsigmaDown,SsigmaUp,StwoSigmaDown,StwoSigmaUp;
176     EdgeFitter::getMedianLimit(ws,theToys,Smedian,SsigmaDown,SsigmaUp,StwoSigmaDown,StwoSigmaUp);
177     medLimits.push_back(Smedian);
178     sigmaLimitsDown.push_back(SsigmaDown);
179     sigmaLimitsUp.push_back(SsigmaUp);
180     twoSigmaLimitsDown.push_back(StwoSigmaDown);
181     twoSigmaLimitsUp.push_back(StwoSigmaUp);
182     }
183     write_warning(__FUNCTION__,"Still need to store limits");
184     } else {
185     vector<float> theVals;
186     vector<float> theLimits;
187     for(int i=20;i<300;i+=5) {
188     ws->var("nSig")->setVal(0.0);
189     theVals.push_back((float)i);
190     ws->var("m0")->setVal((float)i);
191     ws->var("m0")->setConstant(true);
192 buchmann 1.7 // theLimits.push_back(calcExclusion(ws,(RooDataSet)*ws->data("data_obs"),true));
193     write_error(__FUNCTION__,"Error while casting roo data set");
194 buchmann 1.4 }
195    
196 buchmann 1.7 for(int i=0;i<(int)theLimits.size();i++) {
197 buchmann 1.4 if((theLimits[i]<2.0/PlottingSetup::luminosity)||(theLimits[i]>40.0/PlottingSetup::luminosity)) {
198     cout << i << " : " << theVals[i] << endl;
199     theLimits[i] = (theLimits[i+2]+theLimits[i-2])/2.0;
200     write_warning(__FUNCTION__,"Need to store limits");
201     }
202     write_warning(__FUNCTION__,"Need to store limits");
203     }
204     }
205     }
206    
207    
208 buchmann 1.7 float EdgeFitter::calcExclusion(RooWorkspace *ws, RooDataSet data, bool LoadDataObs) {
209     int numberOfToys=50;
210 buchmann 1.3 RooRealVar mu("mu","nSig",0,10000,"");
211     RooArgSet poi = RooArgSet(mu);
212     RooArgSet *nullParams = (RooArgSet*)poi.snapshot();
213     nullParams->setRealValue("nSig",0);
214     RooStats::ModelConfig *model = new RooStats::ModelConfig();
215     model->SetWorkspace(*ws);
216     model->SetPdf("combModel");
217     model->SetParametersOfInterest(poi);
218 buchmann 1.7 // if(LoadDataObs) data = (RooDataSet)*ws->data("data_obs");
219 buchmann 1.3
220 buchmann 1.7 RooStats::ProfileLikelihoodCalculator plc(data, *model);
221 buchmann 1.3 plc.SetNullParameters(*nullParams);
222     plc.SetTestSize(0.05);
223 buchmann 1.7
224 buchmann 1.3 RooStats::LikelihoodInterval* interval = plc.GetInterval();
225     RooStats::HypoTestResult *htr = plc.GetHypoTest();
226     double theLimit = interval->UpperLimit( mu );
227 buchmann 1.7 // double significance = htr->Significance();
228 buchmann 1.3
229     ws->defineSet("obs","nB");
230     ws->defineSet("poi","nSig");
231    
232     RooStats::ModelConfig b_model = RooStats::ModelConfig("B_model", ws);
233     b_model.SetPdf(*ws->pdf("combModel"));
234     b_model.SetObservables(*ws->set("obs"));
235     b_model.SetParametersOfInterest(*ws->set("poi"));
236     ws->var("nSig")->setVal(0.0); //# important!
237     b_model.SetSnapshot(*ws->set("poi"));
238    
239     RooStats::ModelConfig sb_model = RooStats::ModelConfig("S+B_model", ws);
240     sb_model.SetPdf(*ws->pdf("combModel"));
241     sb_model.SetObservables(*ws->set("obs"));
242     sb_model.SetParametersOfInterest(*ws->set("poi"));
243     ws->var("nSig")->setVal(64.0); //# important!
244     sb_model.SetSnapshot(*ws->set("poi"));
245    
246     RooStats::SimpleLikelihoodRatioTestStat slrts = RooStats::SimpleLikelihoodRatioTestStat(*b_model.GetPdf(),*sb_model.GetPdf());
247     slrts.SetNullParameters(*b_model.GetSnapshot());
248     slrts.SetAltParameters(*sb_model.GetSnapshot());
249     RooStats::ProfileLikelihoodTestStat profll = RooStats::ProfileLikelihoodTestStat(*b_model.GetPdf());
250    
251 buchmann 1.7 RooStats::HybridCalculatorOriginal hc = RooStats::HybridCalculatorOriginal(data, sb_model, b_model,0,0);
252 buchmann 1.3 hc.SetTestStatistic(2);
253 buchmann 1.7 hc.SetNumberOfToys(numberOfToys);
254 buchmann 1.3
255     RooStats::HypoTestInverterOriginal hcInv = RooStats::HypoTestInverterOriginal(hc,*ws->var("nSig"));
256     hcInv.SetTestSize(0.05);
257     hcInv.UseCLs(true);
258     hcInv.RunFixedScan(5,theLimit-0.5,theLimit+0.5);;
259     RooStats::HypoTestInverterResult* hcInt = hcInv.GetInterval();
260     float ulError = hcInt->UpperLimitEstimatedError();
261     theLimit = hcInt->UpperLimit();
262     cout << "Found upper limit : " << theLimit << "+/-" << ulError << endl;
263    
264     return theLimit/PlottingSetup::luminosity;
265    
266     }
267    
268 buchmann 1.2 TTree* SkimTree(int isample) {
269 buchmann 1.15 string TreeName = allsamples.collection[isample].filename;
270     TTree* newTree = new TTree("NanoTree",TreeName.c_str());
271    
272     float mll,edgeWeight;
273     int id1,id2;
274    
275     newTree->Branch("edgeWeight",&edgeWeight,"edgeWeight/F");
276     newTree->Branch("mll",&mll,"mll/F");
277     newTree->Branch("id1",&id1,"id1/I");
278     newTree->Branch("id2",&id2,"id2/I");
279    
280 buchmann 1.2 float xsweight=1.0;
281     if(allsamples.collection[isample].is_data==false) xsweight=luminosity*allsamples.collection[isample].weight;
282     if(EdgeFitter::MarcoDebug) {
283     cout << " Original tree contains " << allsamples.collection[isample].events->GetEntries() << endl;
284     cout << " Going to reduce it with cut " << EdgeFitter::cut << endl;
285     }
286 buchmann 1.15
287 buchmann 1.6 float tmll;
288 buchmann 1.15 int tid1,tid2;
289 buchmann 1.6 allsamples.collection[isample].events->SetBranchAddress("mll",&tmll);
290 buchmann 1.15 allsamples.collection[isample].events->SetBranchAddress("id1",&tid1);
291     allsamples.collection[isample].events->SetBranchAddress("id2",&tid2);
292 buchmann 1.6
293 buchmann 1.2 TTreeFormula *select = new TTreeFormula("select", EdgeFitter::cut, allsamples.collection[isample].events);
294 buchmann 1.10 TTreeFormula *Weight = new TTreeFormula("Weight", cutWeight, allsamples.collection[isample].events);
295 buchmann 1.15
296 buchmann 1.2 float wgt=1.0;
297     for (Int_t entry = 0 ; entry < allsamples.collection[isample].events->GetEntries() ; entry++) {
298     allsamples.collection[isample].events->LoadTree(entry);
299     if (select->EvalInstance()) {
300     allsamples.collection[isample].events->GetEntry(entry);
301 buchmann 1.15 mll=tmll;
302     id1=tid1;
303     id2=tid2;
304 buchmann 1.10 wgt=Weight->EvalInstance();
305 buchmann 1.6 edgeWeight=wgt*xsweight;
306 buchmann 1.2 newTree->Fill();
307     }
308     }
309    
310     if(EdgeFitter::MarcoDebug) cout << " Reduced tree contains " << newTree->GetEntries() << " entries " << endl;
311     return newTree;
312     }
313    
314     void EdgeFitter::InitializeVariables(float _mllmin, float _mllmax, float _jzbmax, TCut _cut) {
315     mllmin=_mllmin;
316     mllmax=_mllmax;
317     jzbmax=_jzbmax;
318     cut=_cut;
319     }
320 buchmann 1.10
321     TTree* MergeTrees(vector<TTree*> trees) {
322 buchmann 1.15 TTree * newtree = (TTree*)trees[0]->CloneTree(0);
323 buchmann 1.10 trees[0]->GetListOfClones()->Remove(newtree);
324     trees[0]->ResetBranchAddresses();
325     newtree->ResetBranchAddresses();
326    
327 buchmann 1.15 for(int itree=0;itree<trees.size();itree++) {
328 buchmann 1.10 newtree->CopyAddresses(trees[itree]);
329     Long64_t nentries = trees[itree]->GetEntries();
330     for (Long64_t iEntry=0;iEntry<nentries;iEntry++) {
331     trees[itree]->GetEntry(iEntry);
332     newtree->Fill();
333     }
334     trees[itree]->ResetBranchAddresses(); // Disconnect from new tree
335     if (newtree->GetTreeIndex()) {
336     newtree->GetTreeIndex()->Append(trees[itree]->GetTreeIndex(),kTRUE);
337     }
338     if (newtree && newtree->GetTreeIndex()) {
339     newtree->GetTreeIndex()->Append(0,kFALSE); // Force the sorting
340     }
341     }
342     return newtree;
343     }
344    
345    
346    
347 buchmann 1.2 void EdgeFitter::PrepareDatasets(int is_data) {
348 buchmann 1.5 write_warning(__FUNCTION__,"Need to make this function ready for scans as well (use signal from scan samples)");
349 buchmann 1.15 TFile *tempout = new TFile("tempout.root","RECREATE");
350 buchmann 1.10 vector<TTree*> SkimmedTrees;
351     TTree *SkimmedTree[(int)allsamples.collection.size()];
352 buchmann 1.7 for(int isample=0;isample<(int)allsamples.collection.size();isample++) {
353 buchmann 1.2 if(!allsamples.collection[isample].is_active) continue;
354     if(is_data==1&&allsamples.collection[isample].is_data==false) continue;//kick all samples that aren't data if we're looking for data.
355     if(is_data==1&&allsamples.collection[isample].is_data==false) continue;//kick all samples that aren't data if we're looking for data.
356     if(is_data!=1&&allsamples.collection[isample].is_data==true) continue;//kick all data samples when looking for MC
357     if(is_data!=2&&allsamples.collection[isample].is_signal==true) continue;//remove signal sample if we don't want it.
358     if(EdgeFitter::MarcoDebug) cout << "Considering : " << allsamples.collection[isample].samplename << endl;
359 buchmann 1.15 SkimmedTree[isample] = SkimTree(isample);
360     tempout->cd();
361     SkimmedTree[isample]->Write();
362     SkimmedTrees.push_back(SkimmedTree[isample]);
363 buchmann 1.2 }
364 buchmann 1.10
365     TTree *completetree = MergeTrees(SkimmedTrees);
366    
367 buchmann 1.6 if(EdgeFitter::MarcoDebug) cout << "Complete tree now contains " << completetree->GetEntries() << " entries " << endl;
368 buchmann 1.2
369 buchmann 1.10 RooRealVar mll("mll","m_{ll}",mllmin,mllmax,"GeV/c^{2}");
370 buchmann 1.2 RooRealVar id1("id1","id1",0,1,"GeV/c^{2}");
371     RooRealVar id2("id2","id2",0,1,"GeV/c^{2}");
372 buchmann 1.6 RooRealVar edgeWeight("edgeWeight","edgeWeight",0,1000,"");
373     RooArgSet observables(mll,id1,id2,edgeWeight);
374 buchmann 1.2
375     string title="CMS Data";
376     if(is_data!=1) title="CMS SIMULATION";
377 buchmann 1.6 RooDataSet LAllData("LAllData",title.c_str(),completetree,observables,"","edgeWeight");
378 buchmann 1.15 tempout->cd();
379 buchmann 1.2 completetree->Write();
380 buchmann 1.15 tempout->Close();
381    
382 buchmann 1.2
383 buchmann 1.10 EdgeFitter::SFSample = (RooDataSet*)LAllData.reduce("id1==id2");
384     EdgeFitter::OFSample = (RooDataSet*)LAllData.reduce("id1!=id2");
385 buchmann 1.2 EdgeFitter::AllData = (RooDataSet*)LAllData.reduce("id1!=id2||id1==id2");
386    
387 buchmann 1.10 SFSample->SetName("SFSample");
388     OFSample->SetName("OFSample");
389 buchmann 1.2 AllData->SetName("AllData");
390    
391     if(EdgeFitter::MarcoDebug) {
392 buchmann 1.15 cout << "Number of events in data sample = " << AllData->sumEntries() << endl;
393     cout << "Number of events in eemm sample = " << SFSample->sumEntries() << endl;
394     cout << "Number of events in em sample = " << OFSample->sumEntries() << endl;
395 buchmann 1.2 }
396 buchmann 1.6
397 buchmann 1.2 }
398    
399 buchmann 1.15 void EdgeFitter::DrawDatasetContent(int is_data) {
400     RooRealVar mll("mll","m_{ll}",mllmin,mllmax,"GeV/c^{2}");
401     RooPlot* frame1 = mll.frame(RooFit::Bins(int((mllmax-mllmin)/5.0)),RooFit::Title("SF sample")) ;
402     frame1->GetXaxis()->CenterTitle(1);
403     frame1->GetYaxis()->CenterTitle(1);
404     SFSample->plotOn(frame1,RooFit::Name("SFdata")) ;
405    
406     RooPlot* frame2 = mll.frame(RooFit::Bins(int((mllmax-mllmin)/5.0)),RooFit::Title("OF sample")) ;
407     frame2->GetXaxis()->CenterTitle(1);
408     frame2->GetYaxis()->CenterTitle(1);
409     OFSample->plotOn(frame2,RooFit::Name("OFdata")) ;
410    
411     TCanvas* cSFdata = new TCanvas("cSFdata","cSFdata") ;
412     cSFdata->cd() ;
413     gPad->SetLeftMargin(0.15);
414     frame1->GetYaxis()->SetTitleOffset(1.4);
415     frame1->Draw();
416     if(is_data==data) DrawPrelim();
417     else DrawPrelim(PlottingSetup::luminosity,true);
418     CompleteSave(cSFdata,"Edge/SF_NoFit");
419    
420     TCanvas* cOFdata = new TCanvas("cOFdata","cOFdata") ;
421     cOFdata->cd() ;
422     gPad->SetLeftMargin(0.15);
423 buchmann 1.16 frame2->SetMaximum(frame1->GetMaximum());
424 buchmann 1.15 frame2->GetYaxis()->SetTitleOffset(1.4);
425     frame2->Draw();
426     if(is_data==data) DrawPrelim();
427     else DrawPrelim(PlottingSetup::luminosity,true);
428     CompleteSave(cOFdata,"Edge/OF_NoFit");
429     }
430    
431 buchmann 1.10 string WriteWithError(float central, float error, int digits) {
432     float ref=central;
433     if(ref<0) ref=-central;
434     int HighestSigDigit = 0;
435     if(ref>1) HighestSigDigit = int(log(ref)/log(10))+1;
436     else HighestSigDigit = int(log(ref)/(log(10)));
437    
438     float divider=pow(10.0,(double(HighestSigDigit-digits)));
439    
440     stringstream result;
441     result << divider*int(central/divider+0.5) << " #pm " << divider*int(error/divider+0.5);
442     return result.str();
443     }
444    
445    
446 buchmann 1.2 string EdgeFitter::RandomStorageFile() {
447     TRandom3 *r = new TRandom3(0);
448     int rho = (int)r->Uniform(1,10000000);
449     stringstream RandomFile;
450     RandomFile << PlottingSetup::cbafbasedir << "/exchange/TempEdgeFile_" << rho << ".root";
451     delete r;
452     return RandomFile.str();
453     }
454    
455     Yield EdgeFitter::Get_Z_estimate(float jzb_cut, int icut) {
456     if(MarcoDebug) write_error(__FUNCTION__,"Returning random Z yield");
457     Yield a(123,45,67); return a;
458     return PlottingSetup::allresults.predictions[icut].Zbkg;
459     }
460    
461     Yield EdgeFitter::Get_T_estimate(float jzb_cut, int icut) {
462     if(MarcoDebug) write_error(__FUNCTION__,"Returning random TTbar yield");
463     Yield a(1234,56,78); return a;
464     return PlottingSetup::allresults.predictions[icut].Flavorsym;
465     }
466    
467 buchmann 1.5 void EdgeFitter::DoFit(int is_data, float jzb_cut) {
468 buchmann 1.16
469     stringstream prefix;
470     if(is_data==data) prefix << "data_";
471     if(is_data==mc) prefix << "mc_";
472     if(is_data==mcwithsignal) prefix << "mcwithS_";
473    
474     prefix << EdgeFitter::Mode << "_" << jzb_cut;
475    
476    
477    
478 buchmann 1.10 RooRealVar mll("mll","m_{ll}",mllmin,mllmax,"GeV/c^{2}");
479 buchmann 1.6 RooRealVar edgeWeight("edgeWeight","edgeWeight",0,1000,"");
480 buchmann 1.5 RooCategory sample("sample","sample") ;
481 buchmann 1.10 sample.defineType("SF");
482 buchmann 1.5 //sample.defineType("mm");
483 buchmann 1.10 sample.defineType("OF");
484 buchmann 1.6
485 buchmann 1.10 //RooDataSet combData("combData","combined data",mll,Index(sample),Import("SF",*SFSample),Import("mm",*mmSample),Import("OF",*OFSample));
486     RooDataSet combData("combData","combined data",RooArgSet(mll,edgeWeight),RooFit::Index(sample),RooFit::Import("SF",*SFSample),RooFit::Import("OF",*OFSample),RooFit::WeightVar(edgeWeight));
487 buchmann 1.6
488 buchmann 1.5
489     //First we make a fit to opposite flavor
490 buchmann 1.10 RooRealVar fttbarOF("fttbarOF", "fttbarOF", 100, 0, 10000);
491     RooRealVar par1ttbarOF("par1ttbarOF", "par1ttbarOF", 1.6, 0.01, 4.0);
492     RooRealVar par2ttbarOF("par2ttbarOF", "par2ttbarOF", 1.0);
493     RooRealVar par3ttbarOF("par3ttbarOF", "par3ttbarOF", 0.028, 0.001, 1.0);
494     RooRealVar par4ttbarOF("par4ttbarOF", "par4ttbarOF", 2.0);
495     RooSUSYBkgPdf ttbarOF("ttbarOF","ttbarOF", mll , par1ttbarOF, par2ttbarOF, par3ttbarOF, par4ttbarOF);
496     RooAddPdf model_OF("model_OF","model_OF", ttbarOF, fttbarOF);
497 buchmann 1.5 RooSimultaneous simPdfOF("simPdfOF","simultaneous pdf", sample) ;
498 buchmann 1.10 simPdfOF.addPdf(model_OF,"OF");
499 buchmann 1.14 RooFitResult *resultOF = simPdfOF.fitTo(combData, RooFit::Save(),RooFit::Extended(),RooFit::Minos(true));
500     //resultOF->Print();
501    
502 buchmann 1.16
503     RooPlot* frameO = mll.frame(RooFit::Bins(int((mllmax-mllmin)/5.0)),RooFit::Title("OF sample"));
504     frameO->GetXaxis()->CenterTitle(1);
505     frameO->GetYaxis()->CenterTitle(1);
506     combData.plotOn(frameO,RooFit::Name("OFdata"),RooFit::Cut("sample==sample::OF")) ;
507     simPdfOF.plotOn(frameO,RooFit::Slice(sample,"OF"),RooFit::Name("FullFit"),RooFit::ProjWData(sample,combData), RooFit::LineColor(kBlack)) ;
508     simPdfOF.plotOn(frameO,RooFit::Slice(sample,"OF"),RooFit::Name("TTbarOFonly"),RooFit::Components("ttbarOF"),RooFit::ProjWData(sample,combData),RooFit::LineStyle(kDashed)) ;
509    
510     TCanvas* pof = new TCanvas("pof","pof") ;
511     pof->cd() ;
512     gPad->SetLeftMargin(0.15);
513     frameO->GetYaxis()->SetTitleOffset(1.4);
514     frameO->Draw();
515     if(is_data==data) DrawPrelim();
516     else DrawPrelim(PlottingSetup::luminosity,true);
517     if(EdgeFitter::FixedMEdge>=0) CompleteSave(pof,"Edge/"+prefix.str()+"_OF__OFFitonly_"+any2string(EdgeFitter::FixedMEdge),false,false);
518     else CompleteSave(pof,"Edge/"+prefix.str()+"_OF__OFFitonly",false,false);
519     delete pof;
520    
521    
522    
523 buchmann 1.14 if(resultOF->covQual()!=3) {
524     write_error(__FUNCTION__,"OF fit did not converge!!! Cannot continue!");
525     cout << "covQual is " << resultOF->covQual() << endl;
526     EdgeFitter::FixedMEdgeChi2=-1;
527     if(EdgeFitter::RejectPointIfNoConvergence) return;
528     } else {
529     write_info(__FUNCTION__,"OF fit converged");
530     }
531 buchmann 1.5
532 buchmann 1.10 RooRealVar* resultOFpar1_ = (RooRealVar*) resultOF->floatParsFinal().find("par1ttbarOF");
533 buchmann 1.5 float resultOFpar1 = resultOFpar1_->getVal();
534 buchmann 1.10 //RooRealVar* resultOFpar2_ = (RooRealVar*) resultOF->floatParsFinal().find("par2ttbarOF");
535 buchmann 1.5 //float resultOFpar2 = resultOFpar2_->getVal();
536     //cout << "caca2.txt" << endl;
537    
538 buchmann 1.10 RooRealVar* resultOFpar3_ = (RooRealVar*) resultOF->floatParsFinal().find("par3ttbarOF");
539 buchmann 1.5 float resultOFpar3 = resultOFpar3_->getVal();
540    
541 buchmann 1.10 //RooRealVar* resultOFpar4_ = (RooRealVar*) resultOF->floatParsFinal().find("par4ttbarOF");
542 buchmann 1.5 //float resultOFpar4 = resultOFpar4_->getVal();
543     //cout << "caca4.txt" << endl;
544 buchmann 1.11
545     float StartingMedge=70;
546     if(EdgeFitter::FixedMEdge>0) StartingMedge=EdgeFitter::FixedMEdge;
547 buchmann 1.5
548    
549     // Now same flavor
550 buchmann 1.10 RooRealVar fzSF("fzSF", "fzSF", 5, 0, 100000);
551     RooRealVar meanzSF("meanzSF", "meanzSF", 91.1876, 89, 95);
552     //RooRealVar sigmazSF("sigmazSF", "sigmazSF", 0.5);
553     RooRealVar sigmazSF("sigmazSF", "sigmazSF", 5, 0.5, 5);
554     RooRealVar widthzSF("widthzSF", "widthzSF", 2.94);
555    
556     RooRealVar fttbarSF("fttbarSF", "fttbarSF", 100, 0, 100000);
557 buchmann 1.14 RooRealVar par1ttbarSF("par1ttbarSF", "par1ttbarSF", 1.02*resultOFpar1, 0, 100);
558 buchmann 1.10 RooRealVar par2ttbarSF("par2ttbarSF", "par2ttbarSF", 1.0);
559     RooRealVar par3ttbarSF("par3ttbarSF", "par3ttbarSF", resultOFpar3, 0, 100);
560     RooRealVar par4ttbarSF("par4ttbarSF", "par4ttbarSF", 2.0);
561 buchmann 1.5
562 buchmann 1.10 RooRealVar fsignalSF("fsignalSF", "fsignalSF", 10, 0, 300);
563     RooRealVar par1signalSF("par1signalSF", "par1signalSF", 45, 20, 100);
564     RooRealVar par2signalSF("par2signalSF", "par2signalSF", 2, 1, 10);
565 buchmann 1.11 RooRealVar par3signalSF("par3signalSF", "par3signalSF", StartingMedge, 0, 300);
566 buchmann 1.5
567 buchmann 1.10 RooVoigtian zSF("zSF", "zSF", mll, meanzSF, widthzSF, sigmazSF);
568 buchmann 1.5
569 buchmann 1.11 if(EdgeFitter::FixedMEdge>0) par3signalSF.setConstant();
570 buchmann 1.5
571 buchmann 1.14 /* par1ttbarOF.setConstant(1);
572     par2ttbarOF.setConstant(1);
573     par3ttbarOF.setConstant(1);
574     par4ttbarOF.setConstant(1);
575     fttbarOF.setConstant(1);*/
576    
577 buchmann 1.10 RooSUSYBkgPdf ttbarSF("ttbarSF","ttbarSF", mll , par1ttbarSF, par2ttbarSF, par3ttbarSF, par4ttbarSF);
578     //RooSUSYTPdf signalSF("signalSF","signalSF", mll , par1signalSF, par2signalSF, par3signalSF);
579     RooSUSYTPdf signalSF("signalSF","signalSF", mll , par1signalSF, sigmazSF, par3signalSF);
580    
581     /* par1ttbarSF.setConstant(true);
582     par2ttbarSF.setConstant(true);
583     par3ttbarSF.setConstant(true);
584     par4ttbarSF.setConstant(true);*/
585    
586 buchmann 1.5
587 buchmann 1.10 //RooAddPdf model_SF("model_SF","model_SF", RooArgList(zSF, ttbarSF, signalSF), RooArgList(fzSF, fttbarSF, fsignalSF));
588     RooAddPdf model_SF("model_SF","model_SF", RooArgList(zSF, ttbarSF, signalSF), RooArgList(fzSF, fttbarSF, fsignalSF));
589 buchmann 1.15 // RooAddPdf model_OF("model_OF","model_OF", RooArgList(ttbarSF), RooArgList(fttbarSF));
590 buchmann 1.5
591    
592     RooSimultaneous simPdf("simPdf","simultaneous pdf",sample) ;
593 buchmann 1.10 simPdf.addPdf(model_SF,"SF") ;
594 buchmann 1.14 simPdf.addPdf(model_OF,"OF") ;
595 buchmann 1.5
596 buchmann 1.14 RooFitResult *result = simPdf.fitTo(combData, RooFit::Save(), RooFit::Extended(),RooFit::Minos(true));
597    
598     if(result->covQual()!=3) {
599     write_error(__FUNCTION__,"Full fit did not converge!!! Cannot continue!");
600     cout << "covQual is " << result->covQual() << endl;
601     EdgeFitter::FixedMEdgeChi2=-1;
602     if(EdgeFitter::RejectPointIfNoConvergence) return;
603     } else {
604     write_info(__FUNCTION__,"Full fit converged");
605     }
606    
607     // result->Print();
608 buchmann 1.5
609 buchmann 1.10 RooPlot* frame1 = mll.frame(RooFit::Bins(int((mllmax-mllmin)/5.0)),RooFit::Title("EE sample")) ;
610     frame1->GetXaxis()->CenterTitle(1);
611 buchmann 1.14 frame1->GetYaxis()->CenterTitle(1);
612 buchmann 1.11 combData.plotOn(frame1,RooFit::Name("SFdata"),RooFit::Cut("sample==sample::SF")) ;
613     simPdf.plotOn(frame1,RooFit::Slice(sample,"SF"),RooFit::Name("FullFit"),RooFit::ProjWData(sample,combData), RooFit::LineColor(kBlack)) ;
614     simPdf.plotOn(frame1,RooFit::Slice(sample,"SF"),RooFit::Name("TTbarSFonly"),RooFit::Components("ttbarSF"),RooFit::ProjWData(sample,combData),RooFit::LineStyle(kDashed)) ;
615     simPdf.plotOn(frame1,RooFit::Slice(sample,"SF"),RooFit::Name("DYSFonly"),RooFit::Components("zSF"), RooFit::ProjWData(sample, combData), RooFit::LineStyle(kDashed), RooFit::LineColor(kRed));
616     simPdf.plotOn(frame1,RooFit::Slice(sample,"SF"),RooFit::Name("SignalSFonly"),RooFit::Components("signalSF"), RooFit::ProjWData(sample, combData), RooFit::LineStyle(kDashed), RooFit::LineColor(kGreen));
617    
618 buchmann 1.12 EdgeFitter::FixedMEdgeChi2 = frame1->chiSquare("FullFit", "SFdata", 3);
619 buchmann 1.11
620 buchmann 1.5
621     cout << "Result : " << endl;
622 buchmann 1.10 cout << "f signal : " << fsignalSF.getVal() << " +/- " << fsignalSF.getError() << endl;
623     cout << "f ttbar : " << fttbarSF.getVal() << " +/- " << fttbarSF.getError() << endl;
624     cout << "f tt OF : " << fttbarOF.getVal() << " +/- " << fttbarOF.getError() << endl;
625     cout << "f z SF : " << fzSF.getVal() << " +/- " << fzSF.getError() << endl;
626 buchmann 1.12 cout << "#Chi^{2}/NDF : " << EdgeFitter::FixedMEdgeChi2 << endl;
627 buchmann 1.5
628     // The same plot for the cointrol sample slice
629 buchmann 1.10 RooPlot* frame3 = mll.frame(RooFit::Bins(int((mllmax-mllmin)/5.0)),RooFit::Title("OF sample")) ;
630     frame3->GetXaxis()->CenterTitle(1);
631 buchmann 1.14 frame3->GetYaxis()->CenterTitle(1);
632 buchmann 1.10 frame3->SetMaximum(frame1->GetMaximum());
633     combData.plotOn(frame3,RooFit::Cut("sample==sample::OF")) ;
634 buchmann 1.16 simPdf.plotOn(frame3,RooFit::Slice(sample,"OF"),RooFit::ProjWData(sample,combData), RooFit::LineColor(kBlack)) ;
635     simPdf.plotOn(frame3,RooFit::Slice(sample,"OF"),RooFit::Components("ttbarOF"),RooFit::ProjWData(sample,combData),RooFit::LineStyle(kDashed)) ;
636 buchmann 1.5
637    
638     TCanvas* c = new TCanvas("rf501_simultaneouspdf","rf403_simultaneouspdf") ;
639     c->cd() ;
640     gPad->SetLeftMargin(0.15);
641     frame1->GetYaxis()->SetTitleOffset(1.4);
642     frame1->Draw();
643     if(is_data==data) DrawPrelim();
644     else DrawPrelim(PlottingSetup::luminosity,true);
645 buchmann 1.10 stringstream infotext;
646 buchmann 1.14 infotext << "#splitline{Fit results (" << EdgeFitter::Mode << ">" << jzb_cut << "): }{#splitline{";
647 buchmann 1.15 infotext << "N(Data) = " << EdgeFitter::SFSample->sumEntries() << "}{#splitline{";
648 buchmann 1.10 infotext << "N(Z+Jets) = " << WriteWithError(fzSF.getVal(),fzSF.getError(),3) << "}{#splitline{";
649     infotext << "N(t#bar{t}) = " << WriteWithError(fttbarSF.getVal(),fttbarSF.getError(),3) << "}{#splitline{";
650     infotext << "N(signal) = " << WriteWithError(fsignalSF.getVal(),fsignalSF.getError(),3) << "}{";
651     infotext << "m_{edge} = " << WriteWithError(par3signalSF.getVal(),par3signalSF.getError(),3) << "}}}}}";
652    
653     TLatex *infobox = new TLatex(0.57,0.75,infotext.str().c_str());
654     infobox->SetNDC();
655     infobox->SetTextSize(0.03);
656     infobox->Draw();
657 buchmann 1.14 if(EdgeFitter::FixedMEdge>=0) CompleteSave(c,"Edge/"+prefix.str()+"_SF__MEdgeFix_"+any2string(EdgeFitter::FixedMEdge),false,false);
658     else CompleteSave(c,"Edge/"+prefix.str()+"_SF",false,false);
659 buchmann 1.5 delete c;
660    
661     TCanvas* e = new TCanvas("rf501_simultaneouspdfem","rf403_simultaneouspdfem") ;
662     e->cd();
663     gPad->SetLeftMargin(0.15);
664     frame3->GetYaxis()->SetTitleOffset(1.4);
665     frame3->Draw();
666     if(is_data==data) DrawPrelim();
667     else DrawPrelim(PlottingSetup::luminosity,true);
668 buchmann 1.14 if(EdgeFitter::FixedMEdge>=0) CompleteSave(e,"Edge/"+prefix.str()+"_OF__MEdgeFix_"+any2string(EdgeFitter::FixedMEdge),false,false);
669     else CompleteSave(e,"Edge/"+prefix.str()+"_OF",false,false);
670 buchmann 1.5 delete e;
671    
672 buchmann 1.6
673    
674    
675 buchmann 1.5 /* TCanvas* f = new TCanvas("rf501_simultaneouspdfem","rf403_simultaneouspdfem") ;
676     f->cd();
677     gPad->SetLeftMargin(0.15);
678     frame4->GetYaxis()->SetTitleOffset(1.4);
679     frame4->Draw();
680     if(is_data==data) DrawPrelim();
681     else DrawPrelim(PlottingSetup::luminosity,true);
682 buchmann 1.10 CompleteSave(f,"Edge/"+prefix.str()+"_SF");
683 buchmann 1.5 delete f;*/
684 buchmann 1.7
685 buchmann 1.10
686     /*
687     float maxZ=200;
688     RooWorkspace* wspace = new RooWorkspace();
689     stringstream mllvar;
690     mllvar << "mll[" << (mllmax-mllmin)/2 << "," << mllmin << "," << mllmax << "]";
691     wspace->factory(mllvar.str().c_str());
692     wspace->var("mll")->setBins(30);
693     wspace->factory("nSig[1.,0.,100.]");
694     wspace->factory(("nZ[0.04.,0.,"+any2string(maxZ)+"]").c_str());
695     wspace->factory("rME[1.12,1.05,1.19]");
696     wspace->factory("effUncert[1.]");
697     EdgeFitter::prepareLimits(wspace, true);
698     */
699    
700     write_warning(__FUNCTION__," A lot missing here to calculate limits");
701    
702 buchmann 1.5 }
703    
704 buchmann 1.2 void EdgeFitter::DoEdgeFit(string mcjzb, string datajzb, float DataPeakError, float MCPeakError, float jzb_cut, int icut, int is_data, TCut cut, TTree *signalevents=0) {
705    
706 buchmann 1.5 TCut _cut(cut&&PlottingSetup::basiccut&&PlottingSetup::passtrig);
707    
708     TFile *f = new TFile("workingfile.root","RECREATE");
709    
710     EdgeFitter::InitializeVariables(PlottingSetup::iMllLow,PlottingSetup::iMllHigh,PlottingSetup::jzbHigh,_cut);
711 buchmann 1.2
712     EdgeFitter::PrepareDatasets(is_data);
713 buchmann 1.5
714 buchmann 1.15 EdgeFitter::DrawDatasetContent(is_data);
715    
716 buchmann 1.5 RooFit::MsgLevel msglevel = RooMsgService::instance().globalKillBelow();
717     RooMsgService::instance().setGlobalKillBelow(RooFit::FATAL);
718 buchmann 1.11
719    
720 buchmann 1.14 bool ScanMassRange=false;
721 buchmann 1.12
722 buchmann 1.11
723    
724     if(ScanMassRange) {
725 buchmann 1.12 TFile *fscan = new TFile("fscan.root","UPDATE");
726     TGraph *gr = new TGraph();
727     stringstream GrName;
728 buchmann 1.14 GrName << "ScanGraphFor_" << EdgeFitter::Mode << "_" << jzb_cut;
729 buchmann 1.12 gr->SetName(GrName.str().c_str());
730    
731 buchmann 1.11 int i=0;
732 buchmann 1.13 for(float tempMedge=10;tempMedge<=300;tempMedge+=5.0) {
733 buchmann 1.14 write_info(__FUNCTION__,"Now testing Medge="+any2string(tempMedge)+" for "+EdgeFitter::Mode+">"+any2string(jzb_cut));
734 buchmann 1.11 EdgeFitter::FixedMEdge=tempMedge;
735     EdgeFitter::DoFit(is_data, jzb_cut);
736 buchmann 1.14 if(EdgeFitter::FixedMEdgeChi2<0) continue;
737 buchmann 1.11 gr->SetPoint(i,tempMedge,EdgeFitter::FixedMEdgeChi2);
738 buchmann 1.12 i++;
739 buchmann 1.11 }
740    
741     TCanvas *ScanCan = new TCanvas("ScanCan","ScanCan",500,500);
742     gr->GetXaxis()->SetTitle("m_{edge}");
743     gr->GetXaxis()->CenterTitle();
744 buchmann 1.12 gr->GetYaxis()->SetTitle("#Chi^{2} / NDF");
745 buchmann 1.11 gr->GetYaxis()->CenterTitle();
746 buchmann 1.13 gr->GetYaxis()->SetTitleOffset(0.95);
747     gr->GetXaxis()->SetTitleOffset(0.9);
748     gr->SetLineColor(kBlue);
749     gr->SetTitle("");
750     gr->Draw("AL");
751 buchmann 1.11 stringstream ScanCanSave;
752 buchmann 1.14 ScanCanSave << "Edge/MEdgeScan_"+EdgeFitter::Mode+"_" << jzb_cut;
753 buchmann 1.12 if(is_data) DrawPrelim();
754     else DrawMCPrelim();
755 buchmann 1.13 CompleteSave(ScanCan,ScanCanSave.str());
756     fscan->cd();
757     gr->Write();
758 buchmann 1.11 delete ScanCan;
759 buchmann 1.12 fscan->Close();
760 buchmann 1.11 } else {
761     EdgeFitter::DoFit(is_data, jzb_cut);
762     }
763    
764    
765    
766    
767 buchmann 1.5 EdgeFitter::DoFit(is_data, jzb_cut);
768     RooMsgService::instance().setGlobalKillBelow(msglevel);
769    
770 buchmann 1.2
771     f->Close();
772    
773     }
774    
775     void DoEdgeFit(string mcjzb, string datajzb, float DataPeakError, float MCPeakError, vector<float> jzb_cut, int is_data, TCut cut, TTree *signalevents=0) {
776 buchmann 1.14
777     EdgeFitter::Mode="JZB";
778     if(mcjzb=="met[4]") EdgeFitter::Mode="MET";
779    
780 buchmann 1.7 for(int icut=0;icut<(int)jzb_cut.size();icut++) {
781 buchmann 1.2 stringstream addcut;
782     if(is_data==1) addcut << "(" << datajzb << ">" << jzb_cut[icut] << ")";
783     if(is_data!=1) addcut << "(" << mcjzb << ">" << jzb_cut[icut] << ")";
784     TCut jcut(addcut.str().c_str());
785    
786 buchmann 1.5
787 buchmann 1.2 EdgeFitter::DoEdgeFit(mcjzb, datajzb, DataPeakError, MCPeakError, jzb_cut[icut], icut, is_data, jcut&&cut, signalevents);
788    
789     }
790     }