ViewVC Help
View File | Revision Log | Show Annotations | Root Listing
root/cvsroot/UserCode/cbrown/Development/Plotting/Modules/EdgeLimit.C
Revision: 1.14
Committed: Wed Jun 12 13:50:28 2013 UTC (11 years, 10 months ago) by buchmann
Content type: text/plain
Branch: MAIN
Changes since 1.13: +53 -17 lines
Log Message:
Made edge formalism accessible to lowMET region as well (i.e. adapted all functions so they can use MET instead of JZB); added detection of non-convergence (can be configured to lead to the point being ignored)

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