ViewVC Help
View File | Revision Log | Show Annotations | Root Listing
root/cvsroot/UserCode/cbrown/Development/Plotting/Modules/EdgeLimit.C
Revision: 1.15
Committed: Thu Jun 13 11:41:33 2013 UTC (11 years, 10 months ago) by buchmann
Content type: text/plain
Branch: MAIN
Changes since 1.14: +73 -26 lines
Log Message:
Replaced simple skimming by additional slimming (only keep mll,id1,id2,and edgeWeight); before fitting produce a histogram showing sf & of

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 cout << "Quick overview of tree addresses : " << endl;
323     for(int i=0;i<(int)trees.size();i++) {
324     cout << "Tree " << i << " : " << trees[i] << endl;
325     }
326     cout << "Address of first tree : " << trees[0] << endl;
327     TTree * newtree = (TTree*)trees[0]->CloneTree(0);
328 buchmann 1.10 trees[0]->GetListOfClones()->Remove(newtree);
329     trees[0]->ResetBranchAddresses();
330     newtree->ResetBranchAddresses();
331    
332 buchmann 1.15 for(int itree=0;itree<trees.size();itree++) {
333 buchmann 1.10 newtree->CopyAddresses(trees[itree]);
334     Long64_t nentries = trees[itree]->GetEntries();
335     for (Long64_t iEntry=0;iEntry<nentries;iEntry++) {
336     trees[itree]->GetEntry(iEntry);
337     newtree->Fill();
338     }
339     trees[itree]->ResetBranchAddresses(); // Disconnect from new tree
340     if (newtree->GetTreeIndex()) {
341     newtree->GetTreeIndex()->Append(trees[itree]->GetTreeIndex(),kTRUE);
342     }
343     if (newtree && newtree->GetTreeIndex()) {
344     newtree->GetTreeIndex()->Append(0,kFALSE); // Force the sorting
345     }
346     }
347     return newtree;
348     }
349    
350    
351    
352 buchmann 1.2 void EdgeFitter::PrepareDatasets(int is_data) {
353 buchmann 1.5 write_warning(__FUNCTION__,"Need to make this function ready for scans as well (use signal from scan samples)");
354 buchmann 1.15 TFile *tempout = new TFile("tempout.root","RECREATE");
355 buchmann 1.10 vector<TTree*> SkimmedTrees;
356     TTree *SkimmedTree[(int)allsamples.collection.size()];
357 buchmann 1.7 for(int isample=0;isample<(int)allsamples.collection.size();isample++) {
358 buchmann 1.2 if(!allsamples.collection[isample].is_active) continue;
359     if(is_data==1&&allsamples.collection[isample].is_data==false) continue;//kick all samples that aren't data if we're looking for data.
360     if(is_data==1&&allsamples.collection[isample].is_data==false) continue;//kick all samples that aren't data if we're looking for data.
361     if(is_data!=1&&allsamples.collection[isample].is_data==true) continue;//kick all data samples when looking for MC
362     if(is_data!=2&&allsamples.collection[isample].is_signal==true) continue;//remove signal sample if we don't want it.
363     if(EdgeFitter::MarcoDebug) cout << "Considering : " << allsamples.collection[isample].samplename << endl;
364 buchmann 1.15 SkimmedTree[isample] = SkimTree(isample);
365     tempout->cd();
366     SkimmedTree[isample]->Write();
367     SkimmedTrees.push_back(SkimmedTree[isample]);
368 buchmann 1.2 }
369 buchmann 1.10
370     TTree *completetree = MergeTrees(SkimmedTrees);
371    
372 buchmann 1.6 if(EdgeFitter::MarcoDebug) cout << "Complete tree now contains " << completetree->GetEntries() << " entries " << endl;
373 buchmann 1.2
374 buchmann 1.10 RooRealVar mll("mll","m_{ll}",mllmin,mllmax,"GeV/c^{2}");
375 buchmann 1.2 RooRealVar id1("id1","id1",0,1,"GeV/c^{2}");
376     RooRealVar id2("id2","id2",0,1,"GeV/c^{2}");
377 buchmann 1.6 RooRealVar edgeWeight("edgeWeight","edgeWeight",0,1000,"");
378     RooArgSet observables(mll,id1,id2,edgeWeight);
379 buchmann 1.2
380     string title="CMS Data";
381     if(is_data!=1) title="CMS SIMULATION";
382 buchmann 1.6 RooDataSet LAllData("LAllData",title.c_str(),completetree,observables,"","edgeWeight");
383 buchmann 1.15 tempout->cd();
384 buchmann 1.2 completetree->Write();
385 buchmann 1.15 tempout->Close();
386    
387 buchmann 1.2
388 buchmann 1.10 EdgeFitter::SFSample = (RooDataSet*)LAllData.reduce("id1==id2");
389     EdgeFitter::OFSample = (RooDataSet*)LAllData.reduce("id1!=id2");
390 buchmann 1.2 EdgeFitter::AllData = (RooDataSet*)LAllData.reduce("id1!=id2||id1==id2");
391    
392 buchmann 1.10 SFSample->SetName("SFSample");
393     OFSample->SetName("OFSample");
394 buchmann 1.2 AllData->SetName("AllData");
395    
396     if(EdgeFitter::MarcoDebug) {
397 buchmann 1.15 cout << "Number of events in data sample = " << AllData->sumEntries() << endl;
398     cout << "Number of events in eemm sample = " << SFSample->sumEntries() << endl;
399     cout << "Number of events in em sample = " << OFSample->sumEntries() << endl;
400 buchmann 1.2 }
401 buchmann 1.6
402 buchmann 1.2 }
403    
404 buchmann 1.15 void EdgeFitter::DrawDatasetContent(int is_data) {
405     RooRealVar mll("mll","m_{ll}",mllmin,mllmax,"GeV/c^{2}");
406     RooPlot* frame1 = mll.frame(RooFit::Bins(int((mllmax-mllmin)/5.0)),RooFit::Title("SF sample")) ;
407     frame1->GetXaxis()->CenterTitle(1);
408     frame1->GetYaxis()->CenterTitle(1);
409     SFSample->plotOn(frame1,RooFit::Name("SFdata")) ;
410    
411     RooPlot* frame2 = mll.frame(RooFit::Bins(int((mllmax-mllmin)/5.0)),RooFit::Title("OF sample")) ;
412     frame2->GetXaxis()->CenterTitle(1);
413     frame2->GetYaxis()->CenterTitle(1);
414     OFSample->plotOn(frame2,RooFit::Name("OFdata")) ;
415    
416     TCanvas* cSFdata = new TCanvas("cSFdata","cSFdata") ;
417     cSFdata->cd() ;
418     gPad->SetLeftMargin(0.15);
419     frame1->GetYaxis()->SetTitleOffset(1.4);
420     frame1->Draw();
421     if(is_data==data) DrawPrelim();
422     else DrawPrelim(PlottingSetup::luminosity,true);
423     CompleteSave(cSFdata,"Edge/SF_NoFit");
424    
425     TCanvas* cOFdata = new TCanvas("cOFdata","cOFdata") ;
426     cOFdata->cd() ;
427     gPad->SetLeftMargin(0.15);
428     frame2->GetYaxis()->SetTitleOffset(1.4);
429     frame2->Draw();
430     if(is_data==data) DrawPrelim();
431     else DrawPrelim(PlottingSetup::luminosity,true);
432     CompleteSave(cOFdata,"Edge/OF_NoFit");
433     }
434    
435 buchmann 1.10 string WriteWithError(float central, float error, int digits) {
436     float ref=central;
437     if(ref<0) ref=-central;
438     int HighestSigDigit = 0;
439     if(ref>1) HighestSigDigit = int(log(ref)/log(10))+1;
440     else HighestSigDigit = int(log(ref)/(log(10)));
441    
442     float divider=pow(10.0,(double(HighestSigDigit-digits)));
443    
444     stringstream result;
445     result << divider*int(central/divider+0.5) << " #pm " << divider*int(error/divider+0.5);
446     return result.str();
447     }
448    
449    
450 buchmann 1.2 string EdgeFitter::RandomStorageFile() {
451     TRandom3 *r = new TRandom3(0);
452     int rho = (int)r->Uniform(1,10000000);
453     stringstream RandomFile;
454     RandomFile << PlottingSetup::cbafbasedir << "/exchange/TempEdgeFile_" << rho << ".root";
455     delete r;
456     return RandomFile.str();
457     }
458    
459     Yield EdgeFitter::Get_Z_estimate(float jzb_cut, int icut) {
460     if(MarcoDebug) write_error(__FUNCTION__,"Returning random Z yield");
461     Yield a(123,45,67); return a;
462     return PlottingSetup::allresults.predictions[icut].Zbkg;
463     }
464    
465     Yield EdgeFitter::Get_T_estimate(float jzb_cut, int icut) {
466     if(MarcoDebug) write_error(__FUNCTION__,"Returning random TTbar yield");
467     Yield a(1234,56,78); return a;
468     return PlottingSetup::allresults.predictions[icut].Flavorsym;
469     }
470    
471 buchmann 1.5 void EdgeFitter::DoFit(int is_data, float jzb_cut) {
472 buchmann 1.10 RooRealVar mll("mll","m_{ll}",mllmin,mllmax,"GeV/c^{2}");
473 buchmann 1.6 RooRealVar edgeWeight("edgeWeight","edgeWeight",0,1000,"");
474 buchmann 1.5 RooCategory sample("sample","sample") ;
475 buchmann 1.10 sample.defineType("SF");
476 buchmann 1.5 //sample.defineType("mm");
477 buchmann 1.10 sample.defineType("OF");
478 buchmann 1.6
479 buchmann 1.10 //RooDataSet combData("combData","combined data",mll,Index(sample),Import("SF",*SFSample),Import("mm",*mmSample),Import("OF",*OFSample));
480     RooDataSet combData("combData","combined data",RooArgSet(mll,edgeWeight),RooFit::Index(sample),RooFit::Import("SF",*SFSample),RooFit::Import("OF",*OFSample),RooFit::WeightVar(edgeWeight));
481 buchmann 1.6
482 buchmann 1.5
483     //First we make a fit to opposite flavor
484 buchmann 1.10 RooRealVar fttbarOF("fttbarOF", "fttbarOF", 100, 0, 10000);
485     RooRealVar par1ttbarOF("par1ttbarOF", "par1ttbarOF", 1.6, 0.01, 4.0);
486     RooRealVar par2ttbarOF("par2ttbarOF", "par2ttbarOF", 1.0);
487     RooRealVar par3ttbarOF("par3ttbarOF", "par3ttbarOF", 0.028, 0.001, 1.0);
488     RooRealVar par4ttbarOF("par4ttbarOF", "par4ttbarOF", 2.0);
489     RooSUSYBkgPdf ttbarOF("ttbarOF","ttbarOF", mll , par1ttbarOF, par2ttbarOF, par3ttbarOF, par4ttbarOF);
490     RooAddPdf model_OF("model_OF","model_OF", ttbarOF, fttbarOF);
491 buchmann 1.5 RooSimultaneous simPdfOF("simPdfOF","simultaneous pdf", sample) ;
492 buchmann 1.10 simPdfOF.addPdf(model_OF,"OF");
493 buchmann 1.14 RooFitResult *resultOF = simPdfOF.fitTo(combData, RooFit::Save(),RooFit::Extended(),RooFit::Minos(true));
494     //resultOF->Print();
495    
496     if(resultOF->covQual()!=3) {
497     write_error(__FUNCTION__,"OF fit did not converge!!! Cannot continue!");
498     cout << "covQual is " << resultOF->covQual() << endl;
499     EdgeFitter::FixedMEdgeChi2=-1;
500     if(EdgeFitter::RejectPointIfNoConvergence) return;
501     } else {
502     write_info(__FUNCTION__,"OF fit converged");
503     }
504 buchmann 1.5
505 buchmann 1.10 RooRealVar* resultOFpar1_ = (RooRealVar*) resultOF->floatParsFinal().find("par1ttbarOF");
506 buchmann 1.5 float resultOFpar1 = resultOFpar1_->getVal();
507 buchmann 1.10 //RooRealVar* resultOFpar2_ = (RooRealVar*) resultOF->floatParsFinal().find("par2ttbarOF");
508 buchmann 1.5 //float resultOFpar2 = resultOFpar2_->getVal();
509     //cout << "caca2.txt" << endl;
510    
511 buchmann 1.10 RooRealVar* resultOFpar3_ = (RooRealVar*) resultOF->floatParsFinal().find("par3ttbarOF");
512 buchmann 1.5 float resultOFpar3 = resultOFpar3_->getVal();
513    
514 buchmann 1.10 //RooRealVar* resultOFpar4_ = (RooRealVar*) resultOF->floatParsFinal().find("par4ttbarOF");
515 buchmann 1.5 //float resultOFpar4 = resultOFpar4_->getVal();
516     //cout << "caca4.txt" << endl;
517 buchmann 1.11
518     float StartingMedge=70;
519     if(EdgeFitter::FixedMEdge>0) StartingMedge=EdgeFitter::FixedMEdge;
520 buchmann 1.5
521    
522     // Now same flavor
523 buchmann 1.10 RooRealVar fzSF("fzSF", "fzSF", 5, 0, 100000);
524     RooRealVar meanzSF("meanzSF", "meanzSF", 91.1876, 89, 95);
525     //RooRealVar sigmazSF("sigmazSF", "sigmazSF", 0.5);
526     RooRealVar sigmazSF("sigmazSF", "sigmazSF", 5, 0.5, 5);
527     RooRealVar widthzSF("widthzSF", "widthzSF", 2.94);
528    
529     RooRealVar fttbarSF("fttbarSF", "fttbarSF", 100, 0, 100000);
530 buchmann 1.14 RooRealVar par1ttbarSF("par1ttbarSF", "par1ttbarSF", 1.02*resultOFpar1, 0, 100);
531 buchmann 1.10 RooRealVar par2ttbarSF("par2ttbarSF", "par2ttbarSF", 1.0);
532     RooRealVar par3ttbarSF("par3ttbarSF", "par3ttbarSF", resultOFpar3, 0, 100);
533     RooRealVar par4ttbarSF("par4ttbarSF", "par4ttbarSF", 2.0);
534 buchmann 1.5
535 buchmann 1.10 RooRealVar fsignalSF("fsignalSF", "fsignalSF", 10, 0, 300);
536     RooRealVar par1signalSF("par1signalSF", "par1signalSF", 45, 20, 100);
537     RooRealVar par2signalSF("par2signalSF", "par2signalSF", 2, 1, 10);
538 buchmann 1.11 RooRealVar par3signalSF("par3signalSF", "par3signalSF", StartingMedge, 0, 300);
539 buchmann 1.5
540 buchmann 1.10 RooVoigtian zSF("zSF", "zSF", mll, meanzSF, widthzSF, sigmazSF);
541 buchmann 1.5
542 buchmann 1.11 if(EdgeFitter::FixedMEdge>0) par3signalSF.setConstant();
543 buchmann 1.5
544 buchmann 1.14 /* par1ttbarOF.setConstant(1);
545     par2ttbarOF.setConstant(1);
546     par3ttbarOF.setConstant(1);
547     par4ttbarOF.setConstant(1);
548     fttbarOF.setConstant(1);*/
549    
550 buchmann 1.10 RooSUSYBkgPdf ttbarSF("ttbarSF","ttbarSF", mll , par1ttbarSF, par2ttbarSF, par3ttbarSF, par4ttbarSF);
551     //RooSUSYTPdf signalSF("signalSF","signalSF", mll , par1signalSF, par2signalSF, par3signalSF);
552     RooSUSYTPdf signalSF("signalSF","signalSF", mll , par1signalSF, sigmazSF, par3signalSF);
553    
554     /* par1ttbarSF.setConstant(true);
555     par2ttbarSF.setConstant(true);
556     par3ttbarSF.setConstant(true);
557     par4ttbarSF.setConstant(true);*/
558    
559 buchmann 1.5
560 buchmann 1.10 //RooAddPdf model_SF("model_SF","model_SF", RooArgList(zSF, ttbarSF, signalSF), RooArgList(fzSF, fttbarSF, fsignalSF));
561     RooAddPdf model_SF("model_SF","model_SF", RooArgList(zSF, ttbarSF, signalSF), RooArgList(fzSF, fttbarSF, fsignalSF));
562 buchmann 1.15 // RooAddPdf model_OF("model_OF","model_OF", RooArgList(ttbarSF), RooArgList(fttbarSF));
563 buchmann 1.5
564    
565     RooSimultaneous simPdf("simPdf","simultaneous pdf",sample) ;
566 buchmann 1.10 simPdf.addPdf(model_SF,"SF") ;
567 buchmann 1.14 simPdf.addPdf(model_OF,"OF") ;
568 buchmann 1.5
569 buchmann 1.14 RooFitResult *result = simPdf.fitTo(combData, RooFit::Save(), RooFit::Extended(),RooFit::Minos(true));
570    
571     if(result->covQual()!=3) {
572     write_error(__FUNCTION__,"Full fit did not converge!!! Cannot continue!");
573     cout << "covQual is " << result->covQual() << endl;
574     EdgeFitter::FixedMEdgeChi2=-1;
575     if(EdgeFitter::RejectPointIfNoConvergence) return;
576     } else {
577     write_info(__FUNCTION__,"Full fit converged");
578     }
579    
580     // result->Print();
581 buchmann 1.5
582 buchmann 1.10 RooPlot* frame1 = mll.frame(RooFit::Bins(int((mllmax-mllmin)/5.0)),RooFit::Title("EE sample")) ;
583     frame1->GetXaxis()->CenterTitle(1);
584 buchmann 1.14 frame1->GetYaxis()->CenterTitle(1);
585 buchmann 1.11 combData.plotOn(frame1,RooFit::Name("SFdata"),RooFit::Cut("sample==sample::SF")) ;
586     simPdf.plotOn(frame1,RooFit::Slice(sample,"SF"),RooFit::Name("FullFit"),RooFit::ProjWData(sample,combData), RooFit::LineColor(kBlack)) ;
587     simPdf.plotOn(frame1,RooFit::Slice(sample,"SF"),RooFit::Name("TTbarSFonly"),RooFit::Components("ttbarSF"),RooFit::ProjWData(sample,combData),RooFit::LineStyle(kDashed)) ;
588     simPdf.plotOn(frame1,RooFit::Slice(sample,"SF"),RooFit::Name("DYSFonly"),RooFit::Components("zSF"), RooFit::ProjWData(sample, combData), RooFit::LineStyle(kDashed), RooFit::LineColor(kRed));
589     simPdf.plotOn(frame1,RooFit::Slice(sample,"SF"),RooFit::Name("SignalSFonly"),RooFit::Components("signalSF"), RooFit::ProjWData(sample, combData), RooFit::LineStyle(kDashed), RooFit::LineColor(kGreen));
590    
591 buchmann 1.12 EdgeFitter::FixedMEdgeChi2 = frame1->chiSquare("FullFit", "SFdata", 3);
592 buchmann 1.11
593 buchmann 1.5
594     cout << "Result : " << endl;
595 buchmann 1.10 cout << "f signal : " << fsignalSF.getVal() << " +/- " << fsignalSF.getError() << endl;
596     cout << "f ttbar : " << fttbarSF.getVal() << " +/- " << fttbarSF.getError() << endl;
597     cout << "f tt OF : " << fttbarOF.getVal() << " +/- " << fttbarOF.getError() << endl;
598     cout << "f z SF : " << fzSF.getVal() << " +/- " << fzSF.getError() << endl;
599 buchmann 1.12 cout << "#Chi^{2}/NDF : " << EdgeFitter::FixedMEdgeChi2 << endl;
600 buchmann 1.5
601     // The same plot for the cointrol sample slice
602 buchmann 1.10 RooPlot* frame3 = mll.frame(RooFit::Bins(int((mllmax-mllmin)/5.0)),RooFit::Title("OF sample")) ;
603     frame3->GetXaxis()->CenterTitle(1);
604 buchmann 1.14 frame3->GetYaxis()->CenterTitle(1);
605 buchmann 1.10 frame3->SetMaximum(frame1->GetMaximum());
606     combData.plotOn(frame3,RooFit::Cut("sample==sample::OF")) ;
607     simPdfOF.plotOn(frame3,RooFit::Slice(sample,"OF"),RooFit::ProjWData(sample,combData), RooFit::LineColor(kBlack)) ;
608     simPdfOF.plotOn(frame3,RooFit::Slice(sample,"OF"),RooFit::Components("ttbarOF"),RooFit::ProjWData(sample,combData),RooFit::LineStyle(kDashed)) ;
609    
610 buchmann 1.5
611     stringstream prefix;
612     if(is_data==data) prefix << "data_";
613     if(is_data==mc) prefix << "mc_";
614     if(is_data==mcwithsignal) prefix << "mcwithS_";
615    
616 buchmann 1.14 prefix << EdgeFitter::Mode << "_" << jzb_cut;
617 buchmann 1.5
618    
619    
620     TCanvas* c = new TCanvas("rf501_simultaneouspdf","rf403_simultaneouspdf") ;
621     c->cd() ;
622     gPad->SetLeftMargin(0.15);
623     frame1->GetYaxis()->SetTitleOffset(1.4);
624     frame1->Draw();
625     if(is_data==data) DrawPrelim();
626     else DrawPrelim(PlottingSetup::luminosity,true);
627 buchmann 1.10 stringstream infotext;
628 buchmann 1.14 infotext << "#splitline{Fit results (" << EdgeFitter::Mode << ">" << jzb_cut << "): }{#splitline{";
629 buchmann 1.15 infotext << "N(Data) = " << EdgeFitter::SFSample->sumEntries() << "}{#splitline{";
630 buchmann 1.10 infotext << "N(Z+Jets) = " << WriteWithError(fzSF.getVal(),fzSF.getError(),3) << "}{#splitline{";
631     infotext << "N(t#bar{t}) = " << WriteWithError(fttbarSF.getVal(),fttbarSF.getError(),3) << "}{#splitline{";
632     infotext << "N(signal) = " << WriteWithError(fsignalSF.getVal(),fsignalSF.getError(),3) << "}{";
633     infotext << "m_{edge} = " << WriteWithError(par3signalSF.getVal(),par3signalSF.getError(),3) << "}}}}}";
634    
635     TLatex *infobox = new TLatex(0.57,0.75,infotext.str().c_str());
636     infobox->SetNDC();
637     infobox->SetTextSize(0.03);
638     infobox->Draw();
639 buchmann 1.14 if(EdgeFitter::FixedMEdge>=0) CompleteSave(c,"Edge/"+prefix.str()+"_SF__MEdgeFix_"+any2string(EdgeFitter::FixedMEdge),false,false);
640     else CompleteSave(c,"Edge/"+prefix.str()+"_SF",false,false);
641 buchmann 1.5 delete c;
642    
643     TCanvas* e = new TCanvas("rf501_simultaneouspdfem","rf403_simultaneouspdfem") ;
644     e->cd();
645     gPad->SetLeftMargin(0.15);
646     frame3->GetYaxis()->SetTitleOffset(1.4);
647     frame3->Draw();
648     if(is_data==data) DrawPrelim();
649     else DrawPrelim(PlottingSetup::luminosity,true);
650 buchmann 1.14 if(EdgeFitter::FixedMEdge>=0) CompleteSave(e,"Edge/"+prefix.str()+"_OF__MEdgeFix_"+any2string(EdgeFitter::FixedMEdge),false,false);
651     else CompleteSave(e,"Edge/"+prefix.str()+"_OF",false,false);
652 buchmann 1.5 delete e;
653    
654 buchmann 1.6
655    
656    
657 buchmann 1.5 /* TCanvas* f = new TCanvas("rf501_simultaneouspdfem","rf403_simultaneouspdfem") ;
658     f->cd();
659     gPad->SetLeftMargin(0.15);
660     frame4->GetYaxis()->SetTitleOffset(1.4);
661     frame4->Draw();
662     if(is_data==data) DrawPrelim();
663     else DrawPrelim(PlottingSetup::luminosity,true);
664 buchmann 1.10 CompleteSave(f,"Edge/"+prefix.str()+"_SF");
665 buchmann 1.5 delete f;*/
666 buchmann 1.7
667 buchmann 1.10
668     /*
669     float maxZ=200;
670     RooWorkspace* wspace = new RooWorkspace();
671     stringstream mllvar;
672     mllvar << "mll[" << (mllmax-mllmin)/2 << "," << mllmin << "," << mllmax << "]";
673     wspace->factory(mllvar.str().c_str());
674     wspace->var("mll")->setBins(30);
675     wspace->factory("nSig[1.,0.,100.]");
676     wspace->factory(("nZ[0.04.,0.,"+any2string(maxZ)+"]").c_str());
677     wspace->factory("rME[1.12,1.05,1.19]");
678     wspace->factory("effUncert[1.]");
679     EdgeFitter::prepareLimits(wspace, true);
680     */
681    
682     write_warning(__FUNCTION__," A lot missing here to calculate limits");
683    
684 buchmann 1.5 }
685    
686 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) {
687    
688 buchmann 1.5 TCut _cut(cut&&PlottingSetup::basiccut&&PlottingSetup::passtrig);
689    
690     TFile *f = new TFile("workingfile.root","RECREATE");
691    
692     EdgeFitter::InitializeVariables(PlottingSetup::iMllLow,PlottingSetup::iMllHigh,PlottingSetup::jzbHigh,_cut);
693 buchmann 1.2
694     EdgeFitter::PrepareDatasets(is_data);
695 buchmann 1.5
696 buchmann 1.15 EdgeFitter::DrawDatasetContent(is_data);
697    
698 buchmann 1.5 RooFit::MsgLevel msglevel = RooMsgService::instance().globalKillBelow();
699     RooMsgService::instance().setGlobalKillBelow(RooFit::FATAL);
700 buchmann 1.11
701    
702 buchmann 1.14 bool ScanMassRange=false;
703 buchmann 1.12
704 buchmann 1.11
705    
706     if(ScanMassRange) {
707 buchmann 1.12 TFile *fscan = new TFile("fscan.root","UPDATE");
708     TGraph *gr = new TGraph();
709     stringstream GrName;
710 buchmann 1.14 GrName << "ScanGraphFor_" << EdgeFitter::Mode << "_" << jzb_cut;
711 buchmann 1.12 gr->SetName(GrName.str().c_str());
712    
713 buchmann 1.11 int i=0;
714 buchmann 1.13 for(float tempMedge=10;tempMedge<=300;tempMedge+=5.0) {
715 buchmann 1.14 write_info(__FUNCTION__,"Now testing Medge="+any2string(tempMedge)+" for "+EdgeFitter::Mode+">"+any2string(jzb_cut));
716 buchmann 1.11 EdgeFitter::FixedMEdge=tempMedge;
717     EdgeFitter::DoFit(is_data, jzb_cut);
718 buchmann 1.14 if(EdgeFitter::FixedMEdgeChi2<0) continue;
719 buchmann 1.11 gr->SetPoint(i,tempMedge,EdgeFitter::FixedMEdgeChi2);
720 buchmann 1.12 i++;
721 buchmann 1.11 }
722    
723     TCanvas *ScanCan = new TCanvas("ScanCan","ScanCan",500,500);
724     gr->GetXaxis()->SetTitle("m_{edge}");
725     gr->GetXaxis()->CenterTitle();
726 buchmann 1.12 gr->GetYaxis()->SetTitle("#Chi^{2} / NDF");
727 buchmann 1.11 gr->GetYaxis()->CenterTitle();
728 buchmann 1.13 gr->GetYaxis()->SetTitleOffset(0.95);
729     gr->GetXaxis()->SetTitleOffset(0.9);
730     gr->SetLineColor(kBlue);
731     gr->SetTitle("");
732     gr->Draw("AL");
733 buchmann 1.11 stringstream ScanCanSave;
734 buchmann 1.14 ScanCanSave << "Edge/MEdgeScan_"+EdgeFitter::Mode+"_" << jzb_cut;
735 buchmann 1.12 if(is_data) DrawPrelim();
736     else DrawMCPrelim();
737 buchmann 1.13 CompleteSave(ScanCan,ScanCanSave.str());
738     fscan->cd();
739     gr->Write();
740 buchmann 1.11 delete ScanCan;
741 buchmann 1.12 fscan->Close();
742 buchmann 1.11 } else {
743     EdgeFitter::DoFit(is_data, jzb_cut);
744     }
745    
746    
747    
748    
749 buchmann 1.5 EdgeFitter::DoFit(is_data, jzb_cut);
750     RooMsgService::instance().setGlobalKillBelow(msglevel);
751    
752 buchmann 1.2
753     f->Close();
754    
755     }
756    
757     void DoEdgeFit(string mcjzb, string datajzb, float DataPeakError, float MCPeakError, vector<float> jzb_cut, int is_data, TCut cut, TTree *signalevents=0) {
758 buchmann 1.14
759     EdgeFitter::Mode="JZB";
760     if(mcjzb=="met[4]") EdgeFitter::Mode="MET";
761    
762 buchmann 1.7 for(int icut=0;icut<(int)jzb_cut.size();icut++) {
763 buchmann 1.2 stringstream addcut;
764     if(is_data==1) addcut << "(" << datajzb << ">" << jzb_cut[icut] << ")";
765     if(is_data!=1) addcut << "(" << mcjzb << ">" << jzb_cut[icut] << ")";
766     TCut jcut(addcut.str().c_str());
767    
768 buchmann 1.5
769 buchmann 1.2 EdgeFitter::DoEdgeFit(mcjzb, datajzb, DataPeakError, MCPeakError, jzb_cut[icut], icut, is_data, jcut&&cut, signalevents);
770    
771     }
772     }