ViewVC Help
View File | Revision Log | Show Annotations | Root Listing
root/cvsroot/UserCode/cbrown/Development/Plotting/Modules/EdgeLimit.C
Revision: 1.18
Committed: Thu Jun 13 15:46:06 2013 UTC (11 years, 10 months ago) by buchmann
Content type: text/plain
Branch: MAIN
Changes since 1.17: +45 -28 lines
Log Message:
Added a lot of dout's instead of cout's so the log would be a bit more verbose; deactivated scan for closure tests; added apple strudel warning; fixed Z parameter range for mc

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