void fitTopMass(const char * inFileName) { gROOT->SetBatch(true); gSystem->Load("libRooFit"); TFile* inFile = TFile::Open(inFileName); RooRealVar x("mass","M_{top}",100,200); using namespace std; vector<TH1F*> hists; vector<int> nTotal; std::vector<std::pair<float, float> > range; const char* types[] = { "top1","top2","top"}; for( auto type : types ) { hists.push_back ( (TH1F*)inFile->Get(TString::Format("%s_mass_GenJet",type)) ) ; hists.push_back ( (TH1F*)inFile->Get(TString::Format("%s_mass_Jet",type)) ) ; hists.push_back ( (TH1F*)inFile->Get(TString::Format("%s_mass_btagged_Jet",type)) ) ; hists.push_back ( (TH1F*)inFile->Get(TString::Format("%s_mass_charged_Jet",type)) ) ; hists.push_back ( (TH1F*)inFile->Get(TString::Format("%s_mass_btagged_charged_Jet",type)) ) ; } for( int i= 0 ; i<hists.size() ; i++) { if ( hists[i] == nullptr) std::cout<<"Error! Hist is nullptr."<<std::endl; } for( int i = 0 ; i < hists.size() ; i++) { nTotal.push_back(hists[i]->Integral()); } // For top1, for(int i= 0 ; i < 5 ; i++) { range.push_back( make_pair(150,180) ); } // For top2, for(int i= 0 ; i < 5 ; i++) { range.push_back( make_pair(150,180) ); } // For all top, for(int i= 0 ; i < 5 ; i++) { range.push_back( make_pair(150,180) ); } for( int i= 0 ; i< hists.size() ; i++) { std::cout<<"hist["<<i<<"]"<<std::endl; RooDataHist* dh = new RooDataHist("dh","data histogram",x,hists[i]); auto gaus_mean = RooRealVar("gaus_mean","gaus_mean",172.5, 100,200); auto gaus_sigma = RooRealVar("gaus_sigma","gaus_sigma",1, 0,100); auto nGaus = RooRealVar("nGaus","nGaus",nTotal[i]*0.2, 0., nTotal[i]); auto gaus_pdf = RooGaussian("gaus_pdf","Gaussian p.d.f",x,gaus_mean, gaus_sigma); auto expo_tau = RooRealVar("exp_const","exp_const",0,-10000,10000); auto nExp = RooRealVar("nExp","nExp",1,0,nTotal[i]); auto expo_pdf = RooExponential("bkg","bkg p.d.f",x,expo_tau); auto CB_mean = RooRealVar("CB_mean","CB_mean",172.5,100,200); auto CB_sigma = RooRealVar("CB_sigma","CB_sigma",5,0,100); auto CB_alpha = RooRealVar("CB_alpha","CB_alpha",1,0,100); auto CB_n = RooRealVar("CB_n","CB_n",1,0,100); auto nCB = RooRealVar("nCB","nCB",nTotal[i]*0.8,0.,nTotal[i]); auto CB_pdf = RooCBShape("sig","signal p.d.f",x,CB_mean, CB_sigma, CB_alpha, CB_n ); auto BW_mean = RooRealVar("BW_mean","BW_mean",172.5,100,200); auto BW_sigma = RooRealVar("BW_sigma","BW_sigma",10,0,100); auto nBW = RooRealVar("nBW","nBW",nTotal[i]*0.7, 0, nTotal[i]); auto BW_pdf = RooBreitWigner("sig","signal p.d.f",x,BW_mean, BW_sigma ); RooFormulaVar mirrorX("neg_x","-mass", RooArgSet(x)); //RooRealVar landau_mean("lan_mean","Landau_mean",150.5,100,200); RooRealVar landau_mean("lan_mean","Landau_mean",-160,-200,-100); RooRealVar landau_sigma("lan_sigma","Landau_sigma",2.5, 0,100); RooRealVar nLandau("nLan","nlan",nTotal[i]*0.3, 0, nTotal[i]); RooLandau landau_pdf("lx","lx",mirrorX,landau_mean, landau_sigma); //TF1* f1 = new TF1("landau","nLan*ROOT::Math::landau_pdf(-x,lan_sigma,-lan_mean)",100,300); //RooAbsPdf* invlandau_pdf = RooFit::bindPdf(f1,x,nLandau, landau_mean,landau_sigma); //RooGenericPdf invlandau_pdf("invLandau","ROOT::Math::landau_pdf(-x,lan_sigma,-lan_mean)",RooArgSet(x,landau_sigma,landau_mean)); //sig_pdf = cb_pdf; //bkg_pdf = bw_pdf; //nsig = nCB; //nbkg = nBW; //RooFFTConvPdf model("lxg","CB (x) gauss",x,CB_pdf,gaus_pdf); //RooFFTConvPdf model("lxg","CB (x) BW",x,CB_pdf,BW_pdf); //auto model = RooAddPdf("model","model",RooArgList(landau),RooArgList(nlandau)); //auto model = RooAddPdf("model","model",RooArgList(sig_pdf, bkg_pdf),RooArgList(nsig, nbkg)); //auto model = RooAddPdf("model","model",RooArgList(CB_pdf, gaus_pdf),RooArgList(nCB, nGaus)); RooAddPdf* model; RooFitResult * fitResult; TPaveText* t1 = new TPaveText(0.15,0.5,0.45,0.8,"brNDC"); //auto model = RooAddPdf("model","model",RooArgList(CB_pdf, expo_pdf),RooArgList(nCB, nExp)); //auto model = RooAddPdf("model","model",RooArgList(CB_pdf, BW_pdf),RooArgList(nCB, nBW)); //auto model = RooAddPdf("model","model",RooArgList(CB_pdf),RooArgList(nCB)); //auto model = RooAddPdf("model","model",RooArgList(cb_pdf, gaus_pdf),RooArgList(nCB, nGaus)); //auto model = sig_pdf; std::cout<<"Hello"<<std::endl; if ( i< 5 ) { /* model = new RooAddPdf("model","model",RooArgList(BW_pdf),RooArgList(nBW)); fitResult = model->fitTo(*dh, RooFit::Extended(true), RooFit::Save(), RooFit::Range( range[i].first, range[i].second )); t1->AddText(TString::Format("Breit-Wigner ) Mean : %3.3f(+-%3.3f)", BW_mean.getVal(), BW_mean.getError())); t1->AddText(TString::Format("#sigma : %0.3f(+-%0.3f)", BW_sigma.getVal(), BW_sigma.getError())); */ model = new RooAddPdf("model","model",RooArgList(BW_pdf, landau_pdf),RooArgList(nBW, nLandau)); fitResult = model->fitTo(*dh, RooFit::Extended(true), RooFit::Save(), RooFit::Range( range[i].first, range[i].second )); t1->AddText(TString::Format("Breit-Wigner ) Mean : %3.3f(+-%3.3f)", BW_mean.getVal(), BW_mean.getError())); t1->AddText(TString::Format("#sigma : %0.3f(+-%0.3f)", BW_sigma.getVal(), BW_sigma.getError())); t1->AddText(TString::Format("Landau ) Mean : %3.3f(+-%3.3f)", landau_mean.getVal(), landau_mean.getError())); t1->AddText(TString::Format("#sigma : %0.3f(+-%0.3f)", landau_sigma.getVal(), landau_sigma.getError())); } if ( i>=5 && i<10 ) { model = new RooAddPdf("model","model",RooArgList(BW_pdf, landau_pdf),RooArgList(nBW, nLandau)); fitResult = model->fitTo(*dh, RooFit::Extended(true), RooFit::Save(), RooFit::Range( range[i].first, range[i].second )); t1->AddText(TString::Format("Breit-Wigner ) Mean : %3.3f(+-%3.3f)", BW_mean.getVal(), BW_mean.getError())); t1->AddText(TString::Format("#sigma : %0.3f(+-%0.3f)", BW_sigma.getVal(), BW_sigma.getError())); t1->AddText(TString::Format("Landau ) Mean : %3.3f(+-%3.3f)", landau_mean.getVal(), landau_mean.getError())); t1->AddText(TString::Format("#sigma : %0.3f(+-%0.3f)", landau_sigma.getVal(), landau_sigma.getError())); } if ( i>=10 ) { model = new RooAddPdf("model","model",RooArgList(BW_pdf, landau_pdf),RooArgList(nBW, nLandau)); fitResult = model->fitTo(*dh, RooFit::Extended(true), RooFit::Save(), RooFit::Range( range[i].first, range[i].second )); t1->AddText(TString::Format("Breit-Wigner ) Mean : %3.3f(+-%3.3f)", BW_mean.getVal(), BW_mean.getError())); t1->AddText(TString::Format("#sigma : %0.3f(+-%0.3f)", BW_sigma.getVal(), BW_sigma.getError())); t1->AddText(TString::Format("Landau ) Mean : %3.3f(+-%3.3f)", landau_mean.getVal(), landau_mean.getError())); t1->AddText(TString::Format("#sigma : %0.3f(+-%0.3f)", landau_sigma.getVal(), landau_sigma.getError())); } //t1->AddText(TString::Format("Breit-Wigner ) Mean : %3.3f(+-%3.3f)", BW_mean.getVal(), BW_mean.getError())); //t1->AddText(TString::Format("#sigma : %0.3f(+-%0.3f)", BW_sigma.getVal(), BW_sigma.getError())); //t1->AddText(TString::Format("CrystalBall ) Mean : %3.3f(+-%3.3f)", CB_mean.getVal(), CB_mean.getError())); //t1->AddText(TString::Format("#sigma : %0.3f(+-%0.3f) #alpha : %0.2f ", CB_sigma.getVal(), CB_sigma.getError(), CB_alpha.getVal())); t1->Draw(); RooPlot* top_mass_frame = x.frame(); dh->plotOn(top_mass_frame); model->plotOn(top_mass_frame); model->plotOn(top_mass_frame, RooFit::Components(BW_pdf),RooFit::LineStyle(kDashed)); //model.plotOn(top_mass_frame, RooFit::Components(CB_pdf),RooFit::LineStyle(kDashed)); //model.plotOn(top_mass_frame, RooFit::Components(gaus_pdf),RooFit::LineColor(kRed), RooFit::LineStyle(kDashed)); model->plotOn(top_mass_frame, RooFit::Components(landau_pdf),RooFit::LineColor(kRed), RooFit::LineStyle(kDashed)); TString canvas_name = TString::Format("FitResult_%s",hists[i]->GetName()); TCanvas* c1 = new TCanvas(canvas_name.Data(),canvas_name.Data(),800,600); top_mass_frame->addObject(t1); top_mass_frame->Draw(); top_mass_frame->SetTitle(canvas_name.Data()); c1->SaveAs( (TString(c1->GetName())+".png").Data()); c1->SaveAs( (TString("plotCode/")+TString(c1->GetName()).Strip()+".C").Data()); delete c1; delete dh; } }
int scaleSmearFit(TString RDFile, TString MCFile, char BaseName[30]) { cout<<"Processing "<<BaseName<<endl; gStyle->SetPalette(1); //Data and histograms TFile *f_RD = new TFile(RDFile); TFile *f_MC = new TFile(MCFile); TH1D *h1_ZmassDaughEtaRD = (TH1D*)f_RD->Get("h1_ZmassDaughEtaRD")->Clone(); TH1D *h1_ZmassDaughEtaMC[ScaleBins][ScaleBins]; //Variables char histName[30]; RooRealVar zMass("zMass","zMass",60,120); RooRealVar *nMC; RooRealVar nBRD("nBRD","nBRD",5,2000); RooRealVar nSRD("nSRD","nSRD",1000,0,20000); RooRealVar nBMC("nBMC","nBMC",5,2000); RooRealVar nSMC("nSMC","nSMC",1000,0,20000); RooPlot *zmassframe; RooPlot *zmassframeMC; CPlot *plotFit; CPlot *plotFitMC; //zMass.setBins(50); RooFitResult* fitRes; RooFitResult* fitResMC; TCanvas *myCan = MakeCanvas("myCan","myCan",800,600); RooDataHist *ZmassMC; //RooHistPdf *pdfMC; RooAddPdf *pdfMC; RooAddPdf* pdfRD; //RD fitting RooDataHist *ZmassRD = new RooDataHist("ZmassRD","ZmassRD", RooArgSet(zMass),h1_ZmassDaughEtaRD); //CBreitWignerConvCrystalBall ZsignalPdf("ZsigPdf",zMass); //pdfRD=new RooAddPdf("pdfRD","pdfRD",RooArgList(*(ZsignalPdf.model)),RooArgList(nRD)); CVoigtian ZsigRD("ZsigRD",zMass); CErfExpo ZbgRD("ZbgRD",zMass); //CQuadraticExp ZbgRD("ZbgRD",zMass); pdfRD=new RooAddPdf("pdfRD","pdfRD",RooArgList(*(ZsigRD.model),*(ZbgRD.model)),RooArgList(nSRD,nBRD)); pdfRD=new RooAddPdf("pdfRD","pdfRD",RooArgList(*(ZsigRD.model),*(ZbgRD.model)),RooArgList(nSRD,nBRD)); fitRes=pdfRD->fitTo(*ZmassRD,Extended(),Minos(kTRUE),Save(kTRUE)); //fitRes=ZsignalPdf.model->fitTo(*ZmassRD,Minos(kTRUE),Save(kTRUE)); zmassframe=zMass.frame(Bins(60)); ZmassRD->plotOn(zmassframe,MarkerStyle(kFullCircle),MarkerSize(0.9),DrawOption("zp")); //ZsignalPdf.model->plotOn(zmassframe,LineColor(kBlue),DrawOption("l")); pdfRD->plotOn(zmassframe,LineColor(kBlack),DrawOption("l")); pdfRD->plotOn(zmassframe,Components(RooArgSet(*(ZsigRD.model))),LineColor(kBlue),DrawOption("l")); pdfRD->plotOn(zmassframe,Components(RooArgSet(*(ZbgRD.model))),LineColor(kRed),DrawOption("l")); sprintf(histName,"ZmassRD_%s",BaseName); plotFit = new CPlot(histName,zmassframe,"","","Z mass"); plotFit->setOutDir("Plot"); plotFit->Draw(myCan,kTRUE,"png"); //CErfExpo *pdfZbg; //double nLL[41][41]; // 90 0.004 double ScaleWidth = (ScaleH-ScaleL)/(ScaleBins-1); double SmearWidth = (SmearH-SmearL)/(ScaleBins-1); sprintf(histName,"h2_NLL_%s",BaseName); TH2D *h2_NLL = new TH2D(histName,histName, ScaleBins,ScaleL-ScaleWidth/2,ScaleH+ScaleWidth/2, ScaleBins,SmearL-SmearWidth/2,SmearH+SmearWidth/2); //TH2D *h2_NLL = new TH2D("h2_NLL","NLL",41,0.97,1.05,41,0.5,1.5); double x,prob; //RooAbsReal *nll; double nll; double binContent; //*** CVoigtian ZsigMC("ZsigMC",zMass); RooArgSet allArgset(zMass); RooArgSet anaVar; //for(int i(0);i<=0;i++)for(int j(0);j<=0;j++) for(int i(0);i<=ScaleBins-1;i++)for(int j(0);j<=ScaleBins-1;j++) { sprintf(histName,"h1_ZmassDaughEta_%d_%d",i,j); h1_ZmassDaughEtaMC[i][j] = (TH1D*)f_MC->Get(histName)->Clone(histName); ZmassMC = new RooDataHist("ZmassMC","ZmassMC",RooArgSet(zMass),h1_ZmassDaughEtaMC[i][j]); // interpolation order //pdfMC =new RooHistPdf ("pdfMC", "pdfMC", zMass,*ZmassMC, 1); //Using fitting MC nSMC.setVal(285); ZsigMC.mass->setVal(91.37); ZsigMC.sigma->setVal(0.42); ZsigMC.width->setVal(4.4); pdfMC = new RooAddPdf("pdfMC","pdfMC",RooArgList(*(ZsigMC.model)),RooArgList(nSMC)); fitResMC = pdfMC->fitTo(*ZmassMC,Extended(),Minos(kTRUE),Save(kTRUE),SumW2Error(kTRUE));//SumW2Error(kTRUE) default nll=0; //nll= h1_ZmassDaughEtaMC[i][j]->Chi2Test(h1_ZmassDaughEtaRD,"CHI2/NDF"); // code 1000 dataHist sum int intCode = pdfMC->getAnalyticalIntegral(allArgset,anaVar); double norm = pdfMC->analyticalIntegral(intCode); cout<<"norm: code "<<norm<<" : "<<intCode<<"======================"<<endl; //double totalProb(0); //**** for(int k(1);k<=60;k++) { x=h1_ZmassDaughEtaMC[i][j]->GetBinCenter(k); // binContent = h1_ZmassDaughEtaRD->GetBinContent(k); //binContent = h1_ZmassDaughEtaMC[i][j]->GetBinContent(k); zMass=x; //prob = ZsignalPdf.model->evaluate(); binContent = ZsigRD.model->evaluate()*(120-60)/60.*nSRD.getVal(); prob = pdfMC->evaluate()*(120-60)/60.; //cout<<"binCont, prob "<<binContent<<" "<<prob<<endl; //totalProb +=prob; nll+=-binContent*log(prob); //cout<<" x: prob "<<x<<" "<<prob<<endl; } h2_NLL->SetBinContent(i+1,j+1,nll); /***/ // // if( j==0 || j==int(ScaleBins/2)|| j==(ScaleBins-1) ) { //RD MCpdf RDpdf Plot zmassframe =zMass.frame(Bins(60)); ZmassRD->plotOn(zmassframe,MarkerStyle(kFullCircle),MarkerSize(0.9),DrawOption("zp")); pdfRD->plotOn(zmassframe,LineColor(kBlack)); pdfMC->plotOn(zmassframe,LineColor(kBlue)); //pdfRD->plotOn(zmassframe,Components(RooArgSet(*(pdfZbg->model))),LineColor(kRed)); sprintf(histName,"Zmass_%s_%d_%d",BaseName,i,j); plotFit = new CPlot(histName,zmassframe,"","","Z mass"); plotFit->SetLegend(0.68,0.57,0.93,0.8); plotFit->GetLegend()->AddEntry(pdfRD,"RD","f"); plotFit->GetLegend()->AddEntry(pdfMC,"MC","f"); plotFit->setOutDir("Plot"); plotFit->Draw(myCan,kTRUE,"png"); //MC MCPdf Plot zmassframeMC = zMass.frame(Bins(60)); ZmassMC->plotOn(zmassframeMC,LineColor(kBlue),DrawOption("p")); pdfMC->plotOn(zmassframeMC,LineColor(kBlue),DrawOption("l")); sprintf(histName,"ZmassMC_%s_%d_%d",BaseName,i,j); plotFitMC = new CPlot(histName,zmassframeMC,"","","Z mass MC"); plotFitMC->setOutDir("Plot"); plotFitMC->Draw(myCan,kTRUE,"png"); } } //==== //Plot //==== //Zmass---------- //CPlot *plotZmassRD=new CPlot("plotZmassRD","","zMass","Event"); //plotZmassRD->setOutDir("Plot"); //plotZmassRD->AddHist1D(h1_ZmassDaughEtaRD,"",kBlack); //plotZmassRD->SetLegend(0.68,0.57,0.93,0.8); //plotZmassRD->GetLegend()->AddEntry(h1_ZmassDaughEtaRD,"RD Ele","l"); //plotZmassRD->AddTextBox("both lepton at the |Eta|<0.4",0.65,0.80,0.99,0.86,0); //plotZmassRD->Draw(myCan,kTRUE,"png"); //NLL------------ sprintf(histName,"plotNLL_%s",BaseName); CPlot *plotNll=new CPlot(histName,"","Scale","Smear"); plotNll->setOutDir("Plot"); //plotNll->AddHist2D(h2_NLL,"COLZ",kWhite,kBlack); plotNll->AddHist2D(h2_NLL,"SURF3",kWhite,kBlack); plotNll->Draw(myCan,kTRUE,"png"); //****/ return 0; }
int main(int argc, char *argv[]){ OptionParser(argc,argv); TStopwatch sw; sw.Start(); RooMsgService::instance().setGlobalKillBelow(RooFit::ERROR); RooMsgService::instance().setSilentMode(true); system("mkdir -p plots/fTest"); vector<string> procs; split(procs,procString_,boost::is_any_of(",")); TFile *inFile = TFile::Open(filename_.c_str()); RooWorkspace *inWS = (RooWorkspace*)inFile->Get("cms_hgg_workspace"); RooRealVar *mass = (RooRealVar*)inWS->var("CMS_hgg_mass"); //mass->setBins(320); //mass->setRange(mass_-10,mass_+10); //mass->setBins(20); RooRealVar *MH = new RooRealVar("MH","MH",mass_); MH->setVal(mass_); MH->setConstant(true); map<string,pair<int,int> > choices; map<string,vector<RooPlot*> > plotsRV; map<string,vector<RooPlot*> > plotsWV; for (unsigned int p=0; p<procs.size(); p++){ vector<RooPlot*> tempRV; vector<RooPlot*> tempWV; for (int cat=0; cat<ncats_; cat++){ RooPlot *plotRV = mass->frame(Range(mass_-10,mass_+10)); plotRV->SetTitle(Form("%s_cat%d_RV",procs[p].c_str(),cat)); tempRV.push_back(plotRV); RooPlot *plotWV = mass->frame(Range(mass_-10,mass_+10)); plotWV->SetTitle(Form("%s_cat%d_WV",procs[p].c_str(),cat)); tempWV.push_back(plotWV); } plotsRV.insert(pair<string,vector<RooPlot*> >(procs[p],tempRV)); plotsWV.insert(pair<string,vector<RooPlot*> >(procs[p],tempWV)); } vector<int> colors; colors.push_back(kBlue); colors.push_back(kRed); colors.push_back(kGreen+2); colors.push_back(kMagenta+1); for (int cat=0; cat<ncats_; cat++){ for (unsigned int p=0; p<procs.size(); p++){ string proc = procs[p]; RooDataSet *dataRV = (RooDataSet*)inWS->data(Form("sig_%s_mass_m%d_rv_cat%d",proc.c_str(),mass_,cat)); RooDataSet *dataWV = (RooDataSet*)inWS->data(Form("sig_%s_mass_m%d_wv_cat%d",proc.c_str(),mass_,cat)); //mass->setBins(160); //RooDataHist *dataRV = dataRVtemp->binnedClone(); //RooDataHist *dataWV = dataWVtemp->binnedClone(); //RooDataSet *dataRVw = (RooDataSet*)dataRVtemp->reduce(Form("CMS_hgg_mass>=%3d && CMS_hgg_mass<=%3d",mass_-10,mass_+10)); //RooDataSet *dataWVw = (RooDataSet*)dataWVtemp->reduce(Form("CMS_hgg_mass>=%3d && CMS_hgg_mass<=%3d",mass_-10,mass_+10)); //RooDataHist *dataRV = new RooDataHist(Form("roohist_%s",dataRVtemp->GetName()),Form("roohist_%s",dataRVtemp->GetName()),RooArgSet(*mass),*dataRVtemp); //RooDataHist *dataWV = new RooDataHist(Form("roohist_%s",dataWVtemp->GetName()),Form("roohist_%s",dataWVtemp->GetName()),RooArgSet(*mass),*dataWVtemp); //RooDataSet *dataRV = stripWeights(dataRVweight,mass); //RooDataSet *dataWV = stripWeights(dataWVweight,mass); //RooDataSet *data = (RooDataSet*)inWS->data(Form("sig_%s_mass_m%d_cat%d",proc.c_str(),mass_,cat)); int rvChoice=0; int wvChoice=0; // right vertex int order=1; int prev_order=0; int cache_order=0; double thisNll=0.; double prevNll=1.e6; double chi2=0.; double prob=0.; dataRV->plotOn(plotsRV[proc][cat]); //while (prob<0.8) { while (order<5) { RooAddPdf *pdf = buildSumOfGaussians(Form("cat%d_g%d",cat,order),mass,MH,order); RooFitResult *fitRes = pdf->fitTo(*dataRV,Save(true),SumW2Error(true));//,Range(mass_-10,mass_+10)); double myNll=0.; thisNll = fitRes->minNll(); //double myNll = getMyNLL(mass,pdf,dataRV); //thisNll = getMyNLL(mass,pdf,dataRV); //RooAbsReal *nll = pdf->createNLL(*dataRV); //RooMinuit m(*nll); //m.migrad(); //thisNll = nll->getVal(); //plot(Form("plots/fTest/%s_cat%d_g%d_rv",proc.c_str(),cat,order),mass_,mass,dataRV,pdf); pdf->plotOn(plotsRV[proc][cat],LineColor(colors[order-1])); chi2 = 2.*(prevNll-thisNll); //if (chi2<0. && order>1) chi2=0.; int diffInDof = (2*order+(order-1))-(2*prev_order+(prev_order-1)); prob = TMath::Prob(chi2,diffInDof); cout << "\t RV: " << cat << " " << order << " " << diffInDof << " " << prevNll << " " << thisNll << " " << myNll << " " << chi2 << " " << prob << endl; prevNll=thisNll; cache_order=prev_order; prev_order=order; order++; } rvChoice=cache_order; // wrong vertex order=1; prev_order=0; cache_order=0; thisNll=0.; prevNll=1.e6; chi2=0.; prob=0.; dataWV->plotOn(plotsWV[proc][cat]); while (order<4) { //while (prob<0.8) { RooAddPdf *pdf = buildSumOfGaussians(Form("cat%d_g%d",cat,order),mass,MH,order); RooFitResult *fitRes = pdf->fitTo(*dataWV,Save(true),SumW2Error(true));//,Range(mass_-10,mass_+10)); double myNll=0.; thisNll = fitRes->minNll(); //double myNll = getMyNLL(mass,pdf,dataRV); //thisNll = getMyNLL(mass,pdf,dataRV); //RooAbsReal *nll = pdf->createNLL(*dataWV); //RooMinuit m(*nll); //m.migrad(); //thisNll = nll->getVal(); //plot(Form("plots/fTest/%s_cat%d_g%d_wv",proc.c_str(),cat,order),mass_,mass,dataWV,pdf); pdf->plotOn(plotsWV[proc][cat],LineColor(colors[order-1])); chi2 = 2.*(prevNll-thisNll); //if (chi2<0. && order>1) chi2=0.; int diffInDof = (2*order+(order-1))-(2*prev_order+(prev_order-1)); prob = TMath::Prob(chi2,diffInDof); cout << "\t WV: " << cat << " " << order << " " << diffInDof << " " << prevNll << " " << thisNll << " " << myNll << " " << chi2 << " " << prob << endl; prevNll=thisNll; cache_order=prev_order; prev_order=order; order++; } wvChoice=cache_order; choices.insert(pair<string,pair<int,int> >(Form("%s_cat%d",proc.c_str(),cat),make_pair(rvChoice,wvChoice))); } } TLegend *leg = new TLegend(0.6,0.6,0.89,0.89); leg->SetFillColor(0); leg->SetLineColor(0); TH1F *h1 = new TH1F("h1","",1,0,1); h1->SetLineColor(colors[0]); leg->AddEntry(h1,"1st order","L"); TH1F *h2 = new TH1F("h2","",1,0,1); h2->SetLineColor(colors[1]); leg->AddEntry(h2,"2nd order","L"); TH1F *h3 = new TH1F("h3","",1,0,1); h3->SetLineColor(colors[2]); leg->AddEntry(h3,"3rd order","L"); TH1F *h4 = new TH1F("h4","",1,0,1); h4->SetLineColor(colors[3]); leg->AddEntry(h4,"4th order","L"); TCanvas *canv = new TCanvas(); for (map<string,vector<RooPlot*> >::iterator plotIt=plotsRV.begin(); plotIt!=plotsRV.end(); plotIt++){ string proc = plotIt->first; for (int cat=0; cat<ncats_; cat++){ RooPlot *plot = plotIt->second.at(cat); plot->Draw(); leg->Draw(); canv->Print(Form("plots/fTest/rv_%s_cat%d.pdf",proc.c_str(),cat)); } } for (map<string,vector<RooPlot*> >::iterator plotIt=plotsWV.begin(); plotIt!=plotsWV.end(); plotIt++){ string proc = plotIt->first; for (int cat=0; cat<ncats_; cat++){ RooPlot *plot = plotIt->second.at(cat); plot->Draw(); leg->Draw(); canv->Print(Form("plots/fTest/wv_%s_cat%d.pdf",proc.c_str(),cat)); } } delete canv; cout << "Recommended options" << endl; for (map<string,pair<int,int> >::iterator it=choices.begin(); it!=choices.end(); it++){ cout << "\t " << it->first << " - " << it->second.first << " " << it->second.second << endl; } inFile->Close(); return 0; }
double* fitHist(TCanvas *iC, bool iDoMu,int iPlot, std::string iName,TH1D *iData,TH1D *iW,TH1D *iEWK,TH1D *iAntiData,TH1D *iAntiW,TH1D *iAntiEWK,const Double_t METMAX,const Int_t NBINS,const Double_t lumi,const Int_t Ecm,int iAltQCD) { // // Declare fit parameters for signal and background yields // Note: W signal and EWK+top PDFs are constrained to the ratio described in MC // RooRealVar nSig(("nSig"+iName).c_str(),("nSig"+iName).c_str(),0.7*(iData->Integral()),0,iData->Integral()); RooRealVar nQCD(("nQCD"+iName).c_str(),("nQCD"+iName).c_str(),0.3*(iData->Integral()),0,iData->Integral()); RooRealVar cewk(("cewk"+iName).c_str(),("cewk"+iName).c_str(),0.1,0,5) ; cewk.setVal(iEWK->Integral()/iW->Integral()); cewk.setConstant(kTRUE); RooFormulaVar nEWK(("nEWK"+iName).c_str(),("nEWK"+iName).c_str(),("cewk"+iName+"*nSig"+iName).c_str(),RooArgList(nSig,cewk)); RooRealVar nAntiSig(("nAntiSig"+iName).c_str(),("nAntiSig"+iName).c_str(),0.05*(iAntiData->Integral()),0,iAntiData->Integral()); RooRealVar nAntiQCD(("nAntiQCD"+iName).c_str(),("nAntiQCD"+iName).c_str(),0.9 *(iAntiData->Integral()),0,iAntiData->Integral()); RooRealVar dewk (("dewk" +iName).c_str(),("dewk" +iName).c_str(),0.1,0,5) ; dewk.setVal(iAntiEWK->Integral()/iAntiW->Integral()); dewk.setConstant(kTRUE); RooFormulaVar nAntiEWK(("nAntiEWK"+iName).c_str(),("nAntiEWK"+iName).c_str(),("dewk"+iName+"*nAntiSig"+iName).c_str(),RooArgList(nAntiSig,dewk)); // // Construct PDFs for fitting // RooRealVar pfmet(("pfmet"+iName).c_str(),("pfmet"+iName).c_str(),0,METMAX); pfmet.setBins(NBINS); // Signal PDFs RooDataHist wMet (("wMET" +iName).c_str(), ("wMET" +iName).c_str(), RooArgSet(pfmet),iW); RooHistPdf pdfW(( "w"+iName).c_str(), ( "w"+iName).c_str(), pfmet, wMet, 1); RooDataHist awMet (("awMET"+iName).c_str(), ("awMET"+iName).c_str(), RooArgSet(pfmet),iAntiW); RooHistPdf apdfW(("aw"+iName).c_str(), ("aw"+iName).c_str(), pfmet,awMet, 1); // EWK+top PDFs RooDataHist ewkMet (("ewkMET" +iName).c_str(),( "ewkMET"+iName).c_str(), RooArgSet(pfmet),iEWK); RooHistPdf pdfEWK (( "ewk"+iName).c_str(),( "ewk"+iName).c_str(), pfmet,ewkMet, 1); RooDataHist aewkMet(("aewkMET"+iName).c_str(),("aewkMET"+iName).c_str(), RooArgSet(pfmet),iAntiEWK); RooHistPdf apdfEWK (("aewk"+iName).c_str(),("aewk"+iName).c_str(), pfmet,aewkMet, 1); // QCD Pdfs CPepeModel0 qcd0 (("qcd0" +iName).c_str(),pfmet); CPepeModel1 qcd1 (("qcd1" +iName).c_str(),pfmet); CPepeModel2 qcd2 (("qcd2" +iName).c_str(),pfmet); CPepeModel0 aqcd0(("aqcd0"+iName).c_str(),pfmet); CPepeModel1 aqcd1(("aqcd1"+iName).c_str(),pfmet,qcd1.sigma); CPepeModel2 aqcd2(("aqcd2"+iName).c_str(),pfmet); RooGenericPdf *lQCD = qcd0.model; RooGenericPdf *lAQCD = aqcd0.model; if(iDoMu) lQCD = qcd1.model; if(iDoMu) lAQCD = aqcd1.model; if(iAltQCD == 0) lQCD = qcd0.model; if(iAltQCD == 1) lQCD = qcd1.model; if(iAltQCD == 2) lQCD = qcd2.model; if(iAltQCD == 0) lAQCD = aqcd0.model; if(iAltQCD == 1) lAQCD = aqcd1.model; if(iAltQCD == 2) lAQCD = aqcd2.model; // Signal + Background PDFs RooAddPdf pdfMet (("pdfMet"+iName).c_str(), ("pdfMet" +iName).c_str(), RooArgList(pdfW ,pdfEWK ,*lQCD), RooArgList(nSig,nEWK,nQCD)); RooAddPdf apdfMet(("apdfMet"+iName).c_str(),("apdfMet"+iName).c_str(), RooArgList(apdfW,apdfEWK,*lAQCD), RooArgList(nAntiSig,nAntiEWK,nAntiQCD)); // PDF for simultaneous fit RooCategory rooCat("rooCat","rooCat"); rooCat.defineType("Select"); rooCat.defineType("Anti"); RooSimultaneous pdfTotal("pdfTotal","pdfTotal",rooCat); pdfTotal.addPdf(pdfMet, "Select"); if(iDoMu) pdfTotal.addPdf(apdfMet,"Anti"); // Perform fits RooDataHist dataMet (("dataMet"+iName).c_str(),("dataMet"+iName).c_str(), RooArgSet(pfmet),iData); RooDataHist antiMet (("antiMet"+iName).c_str(),("antiMet"+iName).c_str(), RooArgSet(pfmet),iAntiData); RooDataHist dataTotal(("data" +iName).c_str(),("data" +iName).c_str(), RooArgList(pfmet), Index(rooCat), Import("Select", dataMet), Import("Anti", antiMet)); RooFitResult *fitRes = 0; bool runMinos = kTRUE; if(iPlot == 0 || iPlot == 3) runMinos = kFALSE; //Remove Minos when running toys (too damn slow) if(!iDoMu) fitRes = pdfMet .fitTo(dataMet ,Extended(),Minos(runMinos),Save(kTRUE)); if( iDoMu) fitRes = pdfTotal.fitTo(dataTotal,Extended(),Minos(runMinos),Save(kTRUE)); double *lResults = new double[16]; lResults[0] = nSig.getVal(); lResults[1] = nEWK.getVal(); lResults[2] = nQCD.getVal(); lResults[3] = nAntiSig.getVal(); lResults[4] = nAntiEWK.getVal(); lResults[5] = nAntiQCD.getVal(); if(!iDoMu) lResults[6] = double(qcd0.sigma->getVal()); if( iDoMu) lResults[6] = double(qcd1.sigma->getVal()); lResults[7] = 0.; if(!iDoMu) lResults[7] = qcd1.a1->getVal(); lResults[8] = nSig .getPropagatedError(*fitRes); lResults[9] = nEWK .getPropagatedError(*fitRes); lResults[10] = nQCD .getPropagatedError(*fitRes); lResults[11] = nAntiSig.getPropagatedError(*fitRes); lResults[12] = nAntiEWK.getPropagatedError(*fitRes); lResults[13] = nAntiQCD.getPropagatedError(*fitRes); if( iDoMu) lResults[14] = qcd0.sigma->getError(); if(!iDoMu) lResults[14] = qcd1.sigma->getError(); if( iDoMu) lResults[15] = 0; if(!iDoMu) lResults[15] = qcd1.a1 ->getError(); if(iPlot == 0 ) return lResults; // // Use histogram version of fitted PDFs to make ratio plots // (Will also use PDF histograms later for Chi^2 and KS tests) // TH1D *hPdfMet = (TH1D*)(pdfMet.createHistogram(("hPdfMet"+iName).c_str(), pfmet)); hPdfMet->Scale((nSig.getVal()+nEWK.getVal()+nQCD.getVal())/hPdfMet->Integral()); TH1D *hMetDiff = makeDiffHist(iData,hPdfMet,"hMetDiff"+iName); hMetDiff->SetMarkerStyle(kFullCircle); hMetDiff->SetMarkerSize(0.9); TH1D *hPdfAntiMet = (TH1D*)(apdfMet.createHistogram(("hPdfAntiMet"+iName).c_str(), pfmet)); hPdfAntiMet->Scale((nAntiSig.getVal()+nAntiEWK.getVal()+nAntiQCD.getVal())/hPdfAntiMet->Integral()); TH1D *hAntiMetDiff = makeDiffHist(iAntiData,hPdfAntiMet,"hAntiMetDiff"+iName); hAntiMetDiff->SetMarkerStyle(kFullCircle); hAntiMetDiff->SetMarkerSize(0.9); if(iPlot == 3 ) { //Build best fit QCD with default W and EWK Shap TH1D *hPdfMetQCD = (TH1D*)(lQCD ->createHistogram(("hPdfMetQCD" +iName).c_str(), pfmet)); TH1D *hPdfAMetQCD = (TH1D*)(lAQCD->createHistogram(("hPdfAntiMetQCD"+iName).c_str(), pfmet)); hPdfMetQCD ->Scale(nQCD .getVal()/hPdfMetQCD ->Integral()); hPdfAMetQCD->Scale(nAntiQCD.getVal()/hPdfAMetQCD->Integral()); TH1D *pW = (TH1D*) iW ->Clone("WForToys"); pW ->Scale(nSig .getVal()/pW ->Integral()); TH1D *pEWK = (TH1D*) iEWK ->Clone("EWKForToys"); pEWK ->Scale(nEWK .getVal()/pEWK ->Integral()); TH1D *pAW = (TH1D*) iAntiW ->Clone("AWForToys"); pAW ->Scale(nAntiSig.getVal()/pAW ->Integral()); TH1D *pAEWK = (TH1D*) iAntiEWK->Clone("AEWKForToys"); pAEWK->Scale(nAntiEWK.getVal()/pAEWK->Integral()); hPdfMetQCD ->Add(pW); hPdfMetQCD ->Add(pEWK); hPdfAMetQCD->Add(pAW); hPdfAMetQCD->Add(pAEWK); fBestFit = hPdfMetQCD; fAntiBestFit = hPdfAMetQCD; return lResults; } //-------------------------------------------------------------------------------------------------------------- // Make plots //============================================================================================================== char ylabel[100]; // string buffer for y-axis label // file format for output plots const TString format("png"); // label for lumi char lumitext[100]; if(lumi<0.1) sprintf(lumitext,"%.1f pb^{-1} at #sqrt{s} = %i TeV",lumi*1000.,Ecm); else sprintf(lumitext,"%.2f fb^{-1} at #sqrt{s} = %i TeV",lumi ,Ecm); // plot colors Int_t linecolorW = kOrange-3; Int_t fillcolorW = kOrange-2; Int_t linecolorEWK = kOrange+10; Int_t fillcolorEWK = kOrange+7; Int_t linecolorQCD = kViolet+2; Int_t fillcolorQCD = kViolet-5; Int_t ratioColor = kGray+2; // // Dummy histograms for TLegend // (Nobody can figure out how to properly pass RooFit objects...) // TH1D *hDummyData = new TH1D("hDummyData","",0,0,10); hDummyData->SetMarkerStyle(kFullCircle); hDummyData->SetMarkerSize(0.9); TH1D *hDummyW = new TH1D("hDummyW","",0,0,10); hDummyW->SetLineColor(linecolorW); hDummyW->SetFillColor(fillcolorW); hDummyW->SetFillStyle(1001); TH1D *hDummyEWK = new TH1D("hDummyEWK","",0,0,10); hDummyEWK->SetLineColor(linecolorEWK); hDummyEWK->SetFillColor(fillcolorEWK); hDummyEWK->SetFillStyle(1001); TH1D *hDummyQCD = new TH1D("hDummyQCD","",0,0,10); hDummyQCD->SetLineColor(linecolorQCD); hDummyQCD->SetFillColor(fillcolorQCD); hDummyQCD->SetFillStyle(1001); // // W MET plot // RooPlot *wmframe = pfmet.frame(Bins(NBINS)); dataMet.plotOn(wmframe,MarkerStyle(kFullCircle),MarkerSize(0.9),DrawOption("ZP")); pdfMet.plotOn(wmframe,FillColor(fillcolorW),DrawOption("F")); pdfMet.plotOn(wmframe,LineColor(linecolorW)); pdfMet.plotOn(wmframe,Components(RooArgSet(pdfEWK,*lQCD)),FillColor(fillcolorEWK),DrawOption("F")); pdfMet.plotOn(wmframe,Components(RooArgSet(pdfEWK,*lQCD)),LineColor(linecolorEWK)); pdfMet.plotOn(wmframe,Components(RooArgSet(*lQCD)),FillColor(fillcolorQCD),DrawOption("F")); pdfMet.plotOn(wmframe,Components(RooArgSet(*lQCD)),LineColor(linecolorQCD)); pdfMet.plotOn(wmframe,Components(RooArgSet(pdfW)),LineColor(linecolorW),LineStyle(2)); dataMet.plotOn(wmframe,MarkerStyle(kFullCircle),MarkerSize(0.9),DrawOption("ZP")); sprintf(ylabel,"Events / %.1f GeV",iData->GetBinWidth(1)); CPlot plotMet(("fitmet"+iName).c_str(),wmframe,"","",ylabel); plotMet.SetLegend(0.68,0.57,0.93,0.77); plotMet.GetLegend()->AddEntry(hDummyData,"data","PL"); plotMet.GetLegend()->AddEntry(hDummyW,"W#rightarrow#mu#nu","F"); plotMet.GetLegend()->AddEntry(hDummyEWK,"EWK+t#bar{t}","F"); plotMet.GetLegend()->AddEntry(hDummyQCD,"QCD","F"); plotMet.AddTextBox(lumitext,0.55,0.80,0.90,0.86,0); plotMet.AddTextBox("CMS Preliminary",0.63,0.92,0.95,0.99,0); plotMet.SetYRange(0.1,1.1*(iData->GetMaximum())); plotMet.Draw(iC,kFALSE,format,1); CPlot plotMetDiff(("fitmet"+iName).c_str(),"","#slash{E}_{T} [GeV]","#chi"); plotMetDiff.AddHist1D(hMetDiff,"EX0",ratioColor); plotMetDiff.SetYRange(-8,8); plotMetDiff.AddLine(0, 0,METMAX, 0,kBlack,1); plotMetDiff.AddLine(0, 5,METMAX, 5,kBlack,3); plotMetDiff.AddLine(0,-5,METMAX,-5,kBlack,3); plotMetDiff.Draw(iC,kTRUE,format,2); plotMet.Draw(iC,kTRUE,format,1); plotMet.SetName(("fitmetlog"+iName).c_str()); plotMet.SetLogy(); plotMet.SetYRange(1e-3*(iData->GetMaximum()),10*(iData->GetMaximum())); plotMet.Draw(iC,kTRUE,format,1); if(iDoMu) { RooPlot *awmframe = pfmet.frame(Bins(NBINS)); antiMet.plotOn(awmframe,MarkerStyle(kFullCircle),MarkerSize(0.9),DrawOption("ZP")); apdfMet.plotOn(awmframe,FillColor(fillcolorW),DrawOption("F")); apdfMet.plotOn(awmframe,LineColor(linecolorW)); apdfMet.plotOn(awmframe,Components(RooArgSet(apdfEWK,*lQCD)),FillColor(fillcolorEWK),DrawOption("F")); apdfMet.plotOn(awmframe,Components(RooArgSet(apdfEWK,*lQCD)),LineColor(linecolorEWK)); apdfMet.plotOn(awmframe,Components(RooArgSet(*lQCD)),FillColor(fillcolorQCD),DrawOption("F")); apdfMet.plotOn(awmframe,Components(RooArgSet(*lQCD)),LineColor(linecolorQCD)); apdfMet.plotOn(awmframe,Components(RooArgSet(apdfW)),LineColor(linecolorW),LineStyle(2)); antiMet.plotOn(awmframe,MarkerStyle(kFullCircle),MarkerSize(0.9),DrawOption("ZP")); sprintf(ylabel,"Events / %.1f GeV",iAntiData->GetBinWidth(1)); CPlot plotAntiMet(("fitantimet"+iName).c_str(),awmframe,"","",ylabel); plotAntiMet.SetLegend(0.68,0.57,0.93,0.77); plotAntiMet.GetLegend()->AddEntry(hDummyData,"data","PL"); plotAntiMet.GetLegend()->AddEntry(hDummyW,"W#rightarrow#mu#nu","F"); plotAntiMet.GetLegend()->AddEntry(hDummyEWK,"EWK+t#bar{t}","F"); plotAntiMet.GetLegend()->AddEntry(hDummyQCD,"QCD","F"); plotAntiMet.AddTextBox(lumitext,0.55,0.80,0.90,0.86,0); plotAntiMet.AddTextBox("CMS Preliminary",0.63,0.92,0.95,0.99,0); plotAntiMet.SetYRange(0.1,1.1*(iAntiData->GetMaximum())); plotAntiMet.Draw(iC,kFALSE,format,1); CPlot plotAntiMetDiff(("fitantimet"+iName).c_str(),"","#slash{E}_{T} [GeV]","#chi"); plotAntiMetDiff.AddHist1D(hMetDiff,"EX0",ratioColor); plotAntiMetDiff.SetYRange(-8,8); plotAntiMetDiff.AddLine(0, 0,METMAX, 0,kBlack,1); plotAntiMetDiff.AddLine(0, 5,METMAX, 5,kBlack,3); plotAntiMetDiff.AddLine(0,-5,METMAX,-5,kBlack,3); plotAntiMetDiff.Draw(iC,kTRUE,format,2); plotAntiMet.SetName(("fitantimetlog"+iName).c_str()); plotAntiMet.SetLogy(); plotAntiMet.SetYRange(1e-3*(iAntiData->GetMaximum()),10*(iAntiData->GetMaximum())); plotAntiMet.Draw(iC,kTRUE,format,1); } if(iPlot == 1) return lResults; ofstream txtfile; std::string txtfName = "fitres"+iName; if( iDoMu) txtfName + "Mu.txt"; if(!iDoMu) txtfName + "Mu.txt"; ios_base::fmtflags flags; cout << " --- test " << iData->Integral() << " -- " << hPdfMet->Integral() << endl; Double_t chi2prob = iData->Chi2Test(hPdfMet,"PUW"); Double_t chi2ndf = iData->Chi2Test(hPdfMet,"CHI2/NDFUW"); Double_t ksprob = iData->KolmogorovTest(hPdfMet); Double_t ksprobpe = 1;//iData->KolmogorovTest(hPdfMet,"DX"); txtfile.open(txtfName.c_str()); assert(txtfile.is_open()); flags = txtfile.flags(); txtfile << setprecision(10); txtfile << " *** Yields *** " << endl; txtfile << "Selected: " << iData->Integral() << endl; txtfile << " Signal: " << nSig.getVal() << " +/- " << nSig.getPropagatedError(*fitRes) << endl; txtfile << " QCD: " << nQCD.getVal() << " +/- " << nQCD.getPropagatedError(*fitRes) << endl; txtfile << " Other: " << nEWK.getVal() << " +/- " << nEWK.getPropagatedError(*fitRes) << endl; txtfile << endl; txtfile.flags(flags); fitRes->printStream(txtfile,RooPrintable::kValue,RooPrintable::kVerbose); txtfile << endl; printCorrelations(txtfile, fitRes); txtfile << endl; printChi2AndKSResults(txtfile, chi2prob, chi2ndf, ksprob, ksprobpe); txtfile.close(); return lResults; }
void toyMC( int collId = kAADATA, float ptLow=0, float ptHigh=5, float yLow=0, float yHigh=2.4, int cLow=0, int cHigh=200, float muPtCut=4.0, int inputOption=kChPol4, //kChPol3, int nGen = 10000, int useCentIntBkgShape = 1, int nToys = 1000 ) { using namespace RooFit; RooRandom::randomGenerator()->SetSeed(111); gStyle->SetEndErrorSize(0); float Val_2S_1S_nom = 0; float Val_2S_1S_alt = 0; float Dev_2S_1S = 0; TString fcoll; TString finput; if(collId == kAADATA) fcoll = "AA"; else if(collId == kPPDATA) fcoll = "PP"; if(inputOption == 3) finput = "4th poly"; else if(inputOption == 4) finput = "Nominal+Exp"; TFile *wf = new TFile(Form("%s_fit_pt%.1f-%.1f_rap%.1f-%.1f_cent%d-%d_Gen%d_input%d_useCentBkg%d_nToys%d.root",fcoll.Data(),ptLow,ptHigh,yLow,yHigh,cLow,cHigh,nGen,inputOption,useCentIntBkgShape,nToys),"recreate"); TH1D *h1 = new TH1D("h1",Form("SR Nominal, %d toys, %d events, cent %d-%d;2S/1S nom;Counts",nToys,nGen,cLow,cHigh),100,0,1); TH1D *h2 = new TH1D("h2",Form("SR %s, %d toys, %d events, cent %d-%d;2S/1S nom;Counts",finput.Data(),nToys,nGen,cLow,cHigh),100,0,1); TH1D *h3 = new TH1D("h3","Deviation;2S/1S dev;Counts",1000,0,100); //----****************--------for loop -----*******************----------------- //----****************--------for loop -----*******************----------------- //----****************--------for loop -----*******************----------------- //----****************--------for loop -----*******************----------------- //----****************--------for loop -----*******************----------------- for(int i=0;i<nToys;i++){ float massLow = 8. ; float massHigh = 14.; int nMassBin = (massHigh-massLow)*10; RooWorkspace *ws = new RooWorkspace("ws"); RooWorkspace *wsinp = new RooWorkspace("wsinp"); RooRealVar mass("mass","mass", massLow, massHigh); ws->import(mass); wsinp->import(mass); mass.Print(); RooRealVar mRatio21("mRatio21","mRatio21",pdgMass.Y2S / pdgMass.Y1S ); RooRealVar mRatio31("mRatio31","mRatio31",pdgMass.Y3S / pdgMass.Y1S ); RooRealVar mean1s("m_{#Upsilon(1S)}","mean of the signal gaussian mass PDF",pdgMass.Y1S, pdgMass.Y1S -0.1, pdgMass.Y1S + 0.1 ) ; PSet3SingleCB InitialSetUpsilons = getUpsilonPsets( collId, ptLow, ptHigh, yLow, yHigh, cLow, cHigh, muPtCut) ; RooRealVar sigma1s_1("sigma1s_1","width/sigma of the signal gaussian mass PDF",0.05, 0.05, 0.14); RooRealVar sigma2s_1("sigma2s_1","width/sigma of the signal gaussian mass PDF",0.05, 0.05, 0.14); RooRealVar sigma1s_2("sigma1s_2","width/sigma of the signal gaussian mass PDF",0.05, 0.05, 0.14); RooRealVar sigma2s_2("sigma2s_2","width/sigma of the signal gaussian mass PDF",0.05, 0.05, 0.14); RooRealVar alpha1s_1("alpha1s_1","tail shift", 5. , 1.0, 9.8); RooRealVar alpha2s_1("alpha2s_1","tail shift", 5. , 1.15, 9.2); RooRealVar alpha1s_2("alpha1s_2","tail shift", 5. , 1.0, 9.2); RooRealVar alpha2s_2("alpha2s_2","tail shift", 2.5, 1.10, 10.); RooRealVar n1s_1("n1s_1","power order", 5. , 1.4, 10.); RooRealVar n2s_1("n2s_1","power order", 6. , 1.1, 9.5); RooRealVar n1s_2("n1s_2","power order", 5. , 1.4, 10.); RooRealVar n2s_2("n2s_2","power order", 6. , 1.1, 9.5); RooRealVar *f1S = new RooRealVar("f1S","1S CB fraction", InitialSetUpsilons.MCf, InitialSetUpsilons.MCf*0.9, InitialSetUpsilons.MCf*1.1); f1S->setVal(InitialSetUpsilons.MCf); f1S->setConstant(); RooRealVar X1S("X1S","sigma fraction 1S 2nd CB", InitialSetUpsilons.MCX, InitialSetUpsilons.MCX*0.9, InitialSetUpsilons.MCX*1.1); // Fix the parameters n1s_1.setVal(InitialSetUpsilons.MCN); n1s_1.setConstant(); n1s_2.setVal(InitialSetUpsilons.MCN); n1s_2.setConstant(); n2s_1.setVal(InitialSetUpsilons.MCN); n2s_1.setConstant(); n2s_2.setVal(InitialSetUpsilons.MCN); n2s_2.setConstant(); alpha1s_1.setVal(InitialSetUpsilons.MCAlpha); alpha1s_1.setConstant(); alpha1s_2.setVal(InitialSetUpsilons.MCAlpha); alpha1s_2.setConstant(); alpha2s_1.setVal(InitialSetUpsilons.MCAlpha); alpha2s_1.setConstant(); alpha2s_2.setVal(InitialSetUpsilons.MCAlpha); alpha2s_2.setConstant(); sigma1s_1.setVal(InitialSetUpsilons.MCSigma1S); sigma1s_1.setConstant(); sigma1s_2.setVal(InitialSetUpsilons.MCSigma1S); sigma1s_2.setConstant(); sigma2s_1.setVal(InitialSetUpsilons.MCSigma1S * InitialSetUpsilons.MCX ); sigma2s_1.setConstant(); sigma2s_2.setVal(InitialSetUpsilons.MCSigma1S * InitialSetUpsilons.MCX ); sigma2s_2.setConstant(); mean1s.setVal(InitialSetUpsilons.bkg_mass_res); mean1s.setConstant(); RooFormulaVar mean2s("mean2s","m_{#Upsilon(1S)}*mRatio21", RooArgSet(mean1s,mRatio21) ); RooFormulaVar mean3s("mean3s","m_{#Upsilon(1S)}*mRatio31", RooArgSet(mean1s,mRatio31) ); RooCBShape* cb1s_1 = new RooCBShape("cball1s_1", "cystal Ball", mass, mean1s, sigma1s_1, alpha1s_1, n1s_1); RooCBShape* cb2s_1 = new RooCBShape("cball2s_1", "cystal Ball", mass, mean2s, sigma2s_1, alpha2s_1, n2s_1); RooCBShape* cb1s_2 = new RooCBShape("cball1s_2", "cystal Ball", mass, mean1s, sigma1s_2, alpha1s_2, n1s_2); RooCBShape* cb2s_2 = new RooCBShape("cball2s_2", "cystal Ball", mass, mean2s, sigma2s_2, alpha2s_2, n2s_2); RooAddPdf* cb1s = new RooAddPdf(); RooAddPdf* cb2s = new RooAddPdf(); cb1s = new RooAddPdf("cb1s","Signal 1S",RooArgList(*cb1s_1,*cb1s_2), RooArgList(*f1S) ); cb2s = new RooAddPdf("cb2s","Signal 2S",RooArgList(*cb2s_1,*cb2s_2), RooArgList(*f1S) ); // Input model PSet3SingleCB bkgParm = getUpsilonPsets( collId, ptLow, ptHigh, yLow, yHigh, cLow, cHigh, muPtCut) ; PSet3SingleCB bkgParmCentInt; if ( !( (cLow==0) && (cHigh==200) ) && (collId==kAADATA) ) { bkgParmCentInt = getUpsilonPsets( collId, ptLow, ptHigh, yLow, yHigh, 0, 200, muPtCut) ; cout << " ok done " << endl; } // if ( inputOption == kErrExp ) RooRealVar err_mu1("#mu1","err_mu1", bkgParm.bkg_mu1 ) ; RooRealVar err_sigma1("#sigma1","err_sigma1", bkgParm.bkg_sigma1); RooRealVar m_decay1("#lambda1","m_decay1", bkgParm.bkg_lambda1); RooRealVar err_mu2("#mu2","err_mu2", bkgParm.bkg_mu2 ) ; RooRealVar err_sigma2("#sigma2","err_sigma2", bkgParm.bkg_sigma2); RooRealVar m_decay2("#lambda2","m_decay2", bkgParm.bkg_lambda2); float the_ch3_k1 = bkgParm.ch3_k1 ; float the_ch3_k2 = bkgParm.ch3_k2 ; float the_ch3_k3 = bkgParm.ch3_k3 ; float the_ch4_k1 = bkgParm.ch4_k1 ; float the_ch4_k2 = bkgParm.ch4_k2 ; float the_ch4_k3 = bkgParm.ch4_k3 ; float the_ch4_k4 = bkgParm.ch4_k4 ; float the_bkg4_mu = bkgParm.bkg4_mu ; float the_bkg4_sigma = bkgParm.bkg4_sigma; float the_bkg4_lambda = bkgParm.bkg4_lambda ; float the_bkg4_lambda2 = bkgParm.bkg4_lambda2 ; if ( !( (cLow==0) && (cHigh==200) ) && (collId==kAADATA) && useCentIntBkgShape ) { the_ch3_k1 = bkgParmCentInt.ch3_k1 ; the_ch3_k2 = bkgParmCentInt.ch3_k2 ; the_ch3_k3 = bkgParmCentInt.ch3_k3 ; the_ch4_k1 = bkgParmCentInt.ch4_k1 ; the_ch4_k2 = bkgParmCentInt.ch4_k2 ; the_ch4_k3 = bkgParmCentInt.ch4_k3 ; the_ch4_k4 = bkgParmCentInt.ch4_k4 ; the_bkg4_mu = bkgParmCentInt.bkg4_mu ; bkgParmCentInt.bkg4_sigma =bkgParmCentInt.bkg4_sigma; the_bkg4_lambda = bkgParmCentInt.bkg4_lambda ; the_bkg4_lambda2 = bkgParmCentInt.bkg4_lambda2 ; } // if ( inputOption == kChPol3 ) RooRealVar ch3_k1("pol3_k1","pol3_k1", the_ch3_k1 ) ; RooRealVar ch3_k2("pol3_k2","pol3_k2", the_ch3_k2 ) ; RooRealVar ch3_k3("pol3_k3","pol3_k3", the_ch3_k3 ) ; // if ( inputOption == kChPol4 ) RooRealVar ch4_k1("pol4_k1","pol4_k1", the_ch4_k1 , the_ch4_k1*0.3, the_ch4_k1*1.6) ; RooRealVar ch4_k2("pol4_k2","pol4_k2", the_ch4_k2 , the_ch4_k2*0.3, the_ch4_k2*1.6) ; RooRealVar ch4_k3("pol4_k3","pol4_k3", the_ch4_k3 , the_ch4_k3*0.3, the_ch4_k3*1.6) ; RooRealVar ch4_k4("pol4_k4","pol4_k4", the_ch4_k4 , the_ch4_k4*0.3, the_ch4_k4*1.6) ; // if (inputOption == kErrExpExp ) RooRealVar err4_mu("err4_mu","err4_mu", the_bkg4_mu , the_bkg4_mu*0.4,the_bkg4_mu*1.4) ; RooRealVar err4_sigma("err4_sigma","err4_sigma", the_bkg4_sigma, the_bkg4_sigma*0.4, the_bkg4_sigma*1.4); RooRealVar m4_decay("err4_lambda","m4_decay", the_bkg4_lambda, the_bkg4_lambda*0.4, the_bkg4_lambda*1.4); RooRealVar m4_decay2("err4_lambda2","m4_decay2", the_bkg4_lambda2, the_bkg4_lambda2*0.4, the_bkg4_lambda2*1.4); RooGenericPdf *bkgErrExp1; RooGenericPdf *bkgErrExp2; RooGenericPdf *bkg4ErrExp ; // kErrExpExp RooGenericPdf *bkg4Exp = new RooGenericPdf("bkg4Exp","bkg4Exp","TMath::Exp(-@0/@1)",RooArgList(mass,m4_decay2)); if ( ptLow == 0) { bkg4ErrExp = new RooGenericPdf("bkg4ErrExp","bkg4ErrExp","(TMath::Erf((@0-@1)/(TMath::Sqrt(2)*@2))+1)*0.5*TMath::Exp(-@0/@3)",RooArgList(mass,err4_mu,err4_sigma,m4_decay)); bkgErrExp1 = new RooGenericPdf("bkgErrExp1","Background1","(TMath::Erf((@0-@1)/(TMath::Sqrt(2)*@2))+1)*0.5*TMath::Exp(-@0/@3)",RooArgList(mass,err_mu1,err_sigma1,m_decay1)); bkgErrExp2 = new RooGenericPdf("bkgErrExp2","Background2","(TMath::Erf((@0-@1)/(TMath::Sqrt(2)*@2))+1)*0.5*TMath::Exp(-@0/@3)",RooArgList(mass,err_mu2,err_sigma2,m_decay2)); } else { // if ptLow >= 5 bkg4ErrExp = new RooGenericPdf("bkg4ErrExp","bkg4ErrExp", "TMath::Exp(-@0/@1)",RooArgList(mass,m4_decay)); bkgErrExp1 = new RooGenericPdf("bkgErrExp1","Background1","TMath::Exp(-@0/@1)",RooArgList(mass,m_decay1)); bkgErrExp2 = new RooGenericPdf("bkgErrExp2","Background2","TMath::Exp(-@0/@1)",RooArgList(mass,m_decay2)); } RooRealVar* rBkg2nd = new RooRealVar("rBkg2over1","rBkg2over1", bkgParm.rBkg42over1); // bkgParm.rBkgErr2over1 RooAddPdf* bkgDblErr = new RooAddPdf("bkgDblErrExp","Bkg Only",RooArgList(*bkgErrExp2, *bkgErrExp1),RooArgList(*rBkg2nd)); // if ( inputOption == kErrExp ) RooAddPdf* bkgComp4 = new RooAddPdf("bkgComp4","bkgComp4",RooArgList(*bkg4Exp, *bkg4ErrExp),RooArgList(*rBkg2nd)); // if ( inputOption == kErrExp ) RooChebychev * bkgChPol3 = new RooChebychev("cPolBkg","Background1",mass,RooArgSet(ch3_k1,ch3_k2,ch3_k3)); // if ( inputOption == kChPol3 ) RooChebychev * bkgChPol4 = new RooChebychev("cPol4Bkg","Background4",mass,RooArgSet(ch4_k1,ch4_k2,ch4_k3,ch4_k4)); // if ( inputOption == kChPol3 ) float r1S_overTot = bkgParm.nSignal1s / ( bkgParm.nSignal1s + bkgParm.nSignal2s + bkgParm.nBkg ) ; // Numbers obtained from the real data float r2S_overTot = bkgParm.nSignal2s / ( bkgParm.nSignal1s + bkgParm.nSignal2s + bkgParm.nBkg ) ; float rBkg_overTot = bkgParm.nBkg / ( bkgParm.nSignal1s + bkgParm.nSignal2s + bkgParm.nBkg ) ; RooRealVar *nSig1sInp = new RooRealVar("nSig1sInp","nSig1sInp", nGen * r1S_overTot, 0, nGen); RooRealVar *nSig2sInp = new RooRealVar("nSig2sInp","nSig2sInp", nGen * r2S_overTot, 0, nGen); RooRealVar *nBkgInp = new RooRealVar("nBkgInp","n_bkgInp", nGen * rBkg_overTot, 0, nGen); //---------------------------------------------------------------------------------------- //Generating function from nominal fit RooRealVar err_mu_gen("err_mu_gen","err_mu_gen", bkgParm.bkg_mu_res) ; RooRealVar err_sigma_gen("err_sigma_gen","err_sigma_gen", bkgParm.bkg_sigma_res); RooRealVar m_decay_gen("err_lambda_gen","m_decay_gen", bkgParm.bkg_lambda_res); err_mu_gen.setVal(bkgParm.bkg_mu_res); err_mu_gen.setConstant(); err_sigma_gen.setVal(bkgParm.bkg_sigma_res); err_sigma_gen.setConstant(); m_decay_gen.setVal(bkgParm.bkg_lambda_res); m_decay_gen.setConstant(); RooGenericPdf* bkgInp_gen; RooGenericPdf *bkgInp_in; if ( ptLow == 0) { bkgInp_in = new RooGenericPdf("bkgInp_gen","Background Gen","(TMath::Erf((@0-@1)/(TMath::Sqrt(2)*@2))+1)*0.5*TMath::Exp(-@0/@3)",RooArgList(mass,err_mu_gen,err_sigma_gen,m_decay_gen)); } else { bkgInp_in = new RooGenericPdf("bkgInp_gen","Background Gen","TMath::Exp(-@0/@1)",RooArgList(mass,m_decay_gen)); } bkgInp_gen = bkgInp_in; RooAddPdf* modelInput_gen; modelInput_gen = new RooAddPdf("modelInput_gen","1S+2S + Bkg",RooArgList(*cb1s, *cb2s, *bkgInp_gen),RooArgList(*nSig1sInp,*nSig2sInp,*nBkgInp)); //---------------------------------------------------------------------------------------- //---------------------------------------------------------------------------------------- RooAddPdf* modelInput; RooGenericPdf* bkgInp; if ( inputOption == kErrExp ) { bkgInp = (RooGenericPdf*) bkgDblErr; } else if ( inputOption == kChPol3 ) { bkgInp = (RooGenericPdf*) bkgChPol3; } else if ( inputOption == kChPol4 ) { bkgInp = (RooGenericPdf*) bkgChPol4; } else if ( inputOption == kErrExpExp ) { bkgInp = (RooGenericPdf*) bkgComp4; } modelInput = new RooAddPdf("modelInput","1S+2S + Bkg",RooArgList(*cb1s, *cb2s, *bkgInp),RooArgList(*nSig1sInp,*nSig2sInp,*nBkgInp)); wsinp->import(*modelInput); Val_2S_1S_nom=0; Val_2S_1S_alt=0; Dev_2S_1S=0; RooDataSet *data = modelInput_gen->generate(mass,nGen) ; RooPlot* xframe = ws->var("mass")->frame(nMassBin); // bins xframe->SetXTitle("mass (Gev/c^{2})"); xframe->GetXaxis()->CenterTitle(); xframe->GetYaxis()->CenterTitle(); RooPlot* xframe2 = (RooPlot*)xframe->Clone("xframe2"); RooFitResult* fitResInput = wsinp->pdf("modelInput")->fitTo(*data,Save(), Hesse(kTRUE),Range(massLow, massHigh),Minos(0), SumW2Error(kTRUE)); data->plotOn(xframe,Name("dataHist"),MarkerSize(0.7)) ; wsinp->pdf("modelInput")->plotOn(xframe, Name("inputModelHist")); wsinp->pdf("modelInput")->plotOn(xframe, Components(RooArgSet(*bkgInp)),LineColor(kBlack),LineStyle(kDashed)); if ( inputOption == kErrExp ) { modelInput->plotOn(xframe,Components(RooArgSet(*bkgDblErr)),LineColor(kRed),LineStyle(kDashed)); modelInput->plotOn(xframe,Components(RooArgSet(*bkgErrExp1)),LineColor(kBlack),LineStyle(kDashed)); modelInput->plotOn(xframe,Components(RooArgSet(*bkgErrExp2)),LineColor(kBlack),LineStyle(kDashed)); } else if ( inputOption == kChPol3 ) modelInput->plotOn(xframe,Components(RooArgSet(*bkgChPol3)),LineColor(kBlack),LineStyle(kDashed)); else if ( inputOption == kChPol4 ) modelInput->plotOn(xframe,Components(RooArgSet(*bkgChPol4)),LineColor(kBlack),LineStyle(kDashed)); else if (inputOption == kErrExpExp ) { modelInput->plotOn(xframe,Components(RooArgSet(*bkgComp4)),LineColor(kBlack),LineStyle(kDashed)); modelInput->plotOn(xframe,Components(RooArgSet(*bkg4ErrExp)),LineColor(kBlack),LineStyle(kDashed)); modelInput->plotOn(xframe,Components(RooArgSet(*bkg4Exp)),LineColor(kBlack),LineStyle(kDashed)); } // New fit float the_bkg_mu = bkgParm.bkg_mu ; float the_bkg_sigma = bkgParm.bkg_sigma ; float the_bkg_lambda = bkgParm.bkg_lambda ; if ( !( (cLow==0) && (cHigh==200) ) && (collId==kAADATA) && useCentIntBkgShape ) { the_bkg_mu = bkgParmCentInt.bkg_mu ; the_bkg_sigma = bkgParmCentInt.bkg_sigma ; the_bkg_lambda = bkgParmCentInt.bkg_lambda ; } //RooRealVar err_mu("err_mu","err_mu", the_bkg_mu, 0.0, 40); RooRealVar err_mu("err_mu","err_mu", the_bkg_mu, the_bkg_mu*0.4, the_bkg_mu*1.4); //RooRealVar err_mu("err_mu","err_mu", 1., 0.0, 30); //RooRealVar err_sigma("err_sigma","err_sigma", 1.2, 1.1,55); //RooRealVar err_sigma("err_sigma","err_sigma", 10.,0,20); RooRealVar err_sigma("err_sigma","err_sigma", the_bkg_sigma, the_bkg_sigma*0.4, the_bkg_sigma*1.4); //RooRealVar m_decay("m_decay","m_decay", 10., 6.5, 30); RooRealVar m_decay("m_decay","m_decay",the_bkg_lambda, the_bkg_lambda*0.4, the_bkg_lambda*1.4); if( ( ptLow == (float)0 ) && (ptHigh == (float)30 ) && (yLow == (float)0 ) && (yHigh == (float)2.4) && collId==kPPDATA) { err_sigma.setVal(1.055); err_sigma.setConstant(); } if( ( ptLow == (float)0 ) && (ptHigh == (float)30 ) && (yLow == (float)0 ) && (yHigh == (float)2.4) && collId==kAADATA) { err_sigma.setVal(1.103); err_sigma.setConstant(); } RooGenericPdf *bkgFitOut; if ( ptLow == 0) { bkgFitOut = new RooGenericPdf("bkgFitOut","BackgroundOut","(TMath::Erf((@0-@1)/(TMath::Sqrt(2)*@2))+1)*0.5*TMath::Exp(-@0/@3)",RooArgList(mass,err_mu,err_sigma,m_decay)); } else { bkgFitOut = new RooGenericPdf("bkgFitOut","BackgroundOut","TMath::Exp(-@0/@1)",RooArgList(mass,m_decay)); } RooRealVar *nSig1sOut = new RooRealVar("nSig1sOut","nSig1sOut", r1S_overTot*nGen, 0, r1S_overTot*2.*nGen); RooRealVar *nSig2sOut = new RooRealVar("nSig2sOut","nSig2sOut", r2S_overTot*nGen, 0, r2S_overTot*2.*nGen); RooRealVar *nBkgOut = new RooRealVar("nBkgOut","n_bkgOut",nGen * rBkg_overTot, 0, nGen); RooAddPdf* cb1sOut = (RooAddPdf*)cb1s->Clone("cb1sOutput"); RooAddPdf* cb2sOut = (RooAddPdf*)cb2s->Clone("cb2sOutput"); RooAddPdf* modelOutput = new RooAddPdf("modelOutput","1S+2S + Bkg",RooArgList(*cb1sOut, *cb2sOut, *bkgFitOut),RooArgList(*nSig1sOut,*nSig2sOut,*nBkgOut)); ws->import(*modelOutput); RooFitResult* fitRes = ws->pdf("modelOutput")->fitTo(*data,Save(), Hesse(kTRUE),Range(massLow, massHigh),Minos(0), SumW2Error(kTRUE)); data->plotOn(xframe2,Name("dataHist2"),MarkerSize(0.7)) ; ws->pdf("modelOutput")->plotOn(xframe2, Name("outputModelHist")); ws->pdf("modelOutput")->plotOn(xframe2, Components(RooArgSet(*bkgFitOut)),LineColor(kBlack),LineStyle(kDashed)); Val_2S_1S_nom = (float)(ws->var("nSig2sOut")->getVal() / ws->var("nSig1sOut")->getVal()); Val_2S_1S_alt = (float)(wsinp->var("nSig2sInp")->getVal() / wsinp->var("nSig1sInp")->getVal()); Dev_2S_1S = (Val_2S_1S_alt/Val_2S_1S_nom - 1) * 100; h1->Fill(Val_2S_1S_nom); h2->Fill(Val_2S_1S_alt); h3->Fill(Dev_2S_1S); // DRAW! if(i == 0){ TCanvas* c1 = new TCanvas("canvas2","My plots",4,45,800,400); c1->cd(); TPad *pad1 = new TPad("pad1", "pad1", 0, 0.25, 0.49, 1.0); pad1->SetTicks(1,1); pad1->Draw(); pad1->cd(); pad1->SetBottomMargin(0); // Upper and lower plot are joined xframe->GetYaxis()->SetTitleOffset(1.4) ; xframe->Draw() ; drawText(Form("#Upsilon(2S)/#Upsilon(1S) = %.5f",(float)(wsinp->var("nSig2sInp")->getVal() / wsinp->var("nSig1sInp")->getVal())),0.2,0.54,1,16) ; if (inputOption==kChPol4 ) drawText("4th order poly. Bkg.",0.2,0.62,2,15) ; if (inputOption==kErrExpExp ) drawText("Erf*exp + exp Bkg.",0.2,0.62,2,15) ; if(collId == kAADATA) drawText("PbPb",0.4,0.45,1,15); if(collId == kPPDATA) drawText("pp", 0.4,0.45,1,15); drawText(Form("%.1f < p_{T}^{#mu#mu} < %.1f GeV",ptLow,ptHigh ),0.5,0.60,1,12); drawText(Form("%.1f < y^{#mu#mu} < %.1f",yLow,yHigh ), 0.5,0.55,1,12); TString perc = "%"; if(collId == kAADATA) drawText(Form("Cent %d-%d%s",cLow/2,cHigh/2,perc.Data()),0.5,0.5,4,12); TLatex *tex = new TLatex(0.4,0.88,"Toy MC generated"); tex->SetTextFont(43); tex->SetTextSize(15); tex->SetNDC(); // tex->SetTextAngle(180); tex->Draw(); RooArgList paramListinp = fitResInput->floatParsFinal(); paramListinp.Print("v"); RooPlot* legFrameinp = wsinp->var("mass")->frame(Name("Fit Results"), Title("Fit Results")); wsinp->pdf("modelInput")->paramOn(legFrameinp,Layout(.6,.9, .5),Parameters(paramListinp)); legFrameinp->getAttText()->SetTextAlign(11); legFrameinp->getAttText()->SetTextSize(0.028); TPaveText* hhinp = (TPaveText*)legFrameinp->findObject(Form("%s_paramBox",wsinp->pdf("modelInput")->GetName())); hhinp->SetY1(0.35); hhinp->SetY2(0.83); hhinp->Draw(); // PULL TPad *pad2 = new TPad("pad2", "pad2", 0, 0.05, 0.49, 0.25); c1->cd(); pad2->Draw(); pad2->cd(); RooHist* hpull = xframe->pullHist("dataHist","inputModelHist"); RooPlot* pullFrame = wsinp->var("mass")->frame(Title("Pull Distribution")) ; pullFrame->addPlotable(hpull,"P") ; pullFrame->SetTitleSize(2.57); pullFrame->GetYaxis()->SetTitleOffset(1.8) ; pullFrame->GetYaxis()->SetLabelSize(0.16) ; pullFrame->GetYaxis()->SetRange(-10,10) ; pullFrame->GetXaxis()->SetTitleOffset(0.7) ; pullFrame->GetXaxis()->SetLabelSize(0.1) ; pullFrame->GetXaxis()->SetTitleSize(0.13) ; pullFrame->Draw() ; TPad *pad3 = new TPad("pad3", "pad3", 0.51, 0.25, 0.99, 1); pad3->SetTicks(1,1); pad3->SetBottomMargin(0); // Upper and lower plot are joined c1->cd(); pad3->Draw(); pad3->cd(); xframe2->GetYaxis()->SetTitleOffset(1.4) ; xframe2->Draw() ; TLatex *tex2 = new TLatex(0.4,0.9,"Fitted by Nominal function"); tex2->SetTextFont(43); tex2->SetTextSize(15); tex2->SetTextColor(2); tex2->SetNDC(); tex2->Draw(); drawText(Form("#Upsilon(2S)/#Upsilon(1S) = %.5f",(float)(ws->var("nSig2sOut")->getVal() / ws->var("nSig1sOut")->getVal())), 0.4,0.85,1,16 ); // *~*~*~*~*~*~*~* Draw the parameters in the plot *~*~*~*~*~*~*~* // RooArgList paramList = fitRes->floatParsFinal(); paramList.Print("v"); RooPlot* legFrame = ws->var("mass")->frame(Name("Fit Results"), Title("Fit Results")); ws->pdf("modelOutput")->paramOn(legFrame,Layout(.6,.9, .5),Parameters(paramList)); legFrame->getAttText()->SetTextAlign(11); legFrame->getAttText()->SetTextSize(0.028); TPaveText* hh = (TPaveText*)legFrame->findObject(Form("%s_paramBox",ws->pdf("modelOutput")->GetName())); hh->SetY1(0.35); hh->SetY2(0.83); hh->Draw(); TPad *pad4 = new TPad("pad4", "pad4", 0.51, 0.05, 0.99, 0.25); // pad4->SetBottomMargin(0); // Upper and lower plot are joined c1->cd(); pad4->Draw(); pad4->cd(); RooHist* hpullOut = xframe2->pullHist("dataHist2","outputModelHist"); RooPlot* pullOutFrm = ws->var("mass")->frame(Title("Pull Distribution")) ; pullOutFrm->addPlotable(hpullOut,"P") ; pullOutFrm->SetTitleSize(2.57); pullOutFrm->GetYaxis()->SetTitleOffset(1.8) ; pullOutFrm->GetYaxis()->SetLabelSize(0.16) ; pullOutFrm->GetYaxis()->SetRange(-10,10) ; pullOutFrm->GetXaxis()->SetTitleOffset(0.7) ; pullOutFrm->GetXaxis()->SetLabelSize(0.1) ; pullOutFrm->GetXaxis()->SetTitleSize(0.13) ; pullOutFrm->Draw() ; // *~*~*~*~*~*~*~* Print the results *~*~*~*~*~*~*~* // //cout << "nSig2sInp/nSig1sInp = " << nSig2sInp->getVal() / nSig1sInp->getVal() << endl; cout << "input fit ratio = " << wsinp->var("nSig2sInp")->getVal() / wsinp->var("nSig1sInp")->getVal() << endl; cout << "output fit ratio = " << ws->var("nSig2sOut")->getVal() / ws->var("nSig1sOut")->getVal() << endl; c1->SaveAs(Form( "toyMCFit_collId%d_pt%.0f-%.0fGeV_y%.0f-%.0f_cBin%d-%d_muPtCut%.0fGeV_BkgPDFOpt%d_nGen%d_useCentIntBkgShape%d.png", collId, ptLow, ptHigh, yLow*10, yHigh*10, cLow, cHigh, muPtCut, inputOption, nGen,useCentIntBkgShape) ); float r1 = wsinp->var("nSig2sInp")->getVal() / wsinp->var("nSig1sInp")->getVal() ; float r2 = ws->var("nSig2sOut")->getVal() / ws->var("nSig1sOut")->getVal() ; cout << Form( "collId: %d, pt: %.0f - %.0fGeV, y: %.1f - %.1f, cBin: %d - %d", collId, ptLow, ptHigh, yLow, yHigh, cLow, cHigh ) << endl; cout << "Uncertainty = " << (r2 - r1 ) / r1 << endl; } } wf->cd(); h1->Write(); h2->Write(); h3->Write(); }
int main (int argc, char **argv) { TFile *tf = TFile::Open("tmp/DataSets.root"); RooWorkspace *w = (RooWorkspace*)tf->Get("w"); RooDataSet *Data = (RooDataSet*)w->data("Data2011")->Clone("Data"); Data->append( *((RooDataSet*)w->data("Data2012")) ); RooDataSet *Bs2Kst0Kst0_MC = (RooDataSet*)w->data("Bs2Kst0Kst0_MC2011")->Clone("Bs2KstKst0_MC"); Bs2Kst0Kst0_MC->append( *((RooDataSet*)w->data("Bs2Kst0Kst0_MC2012")) ); RooDataSet *Bs2Kst0Kst01430_MC = (RooDataSet*)w->data("Bs2Kst0Kst01430_MC2011")->Clone("Bs2KstKst0_MC"); Bs2Kst0Kst01430_MC->append( *((RooDataSet*)w->data("Bs2Kst0Kst01430_MC2012")) ); RooDataSet *Bs2Kst01430Kst01430_MC = (RooDataSet*)w->data("Bs2Kst01430Kst01430_MC2011")->Clone("Bs2KstKst0_MC"); Bs2Kst01430Kst01430_MC->append( *((RooDataSet*)w->data("Bs2Kst01430Kst01430_MC2012")) ); RooDataSet *Bd2Kst0Kst0_MC = (RooDataSet*)w->data("Bd2Kst0Kst0_MC2011")->Clone("Bs2KstKst0_MC"); Bd2Kst0Kst0_MC->append( *((RooDataSet*)w->data("Bd2Kst0Kst0_MC2012")) ); RooDataSet *Bd2PhiKst0_MC = (RooDataSet*)w->data("Bd2PhiKst0_MC2011")->Clone("Bs2KstKst0_MC"); Bd2PhiKst0_MC->append( *((RooDataSet*)w->data("Bd2PhiKst0_MC2012")) ); RooDataSet *Bs2PhiKst0_MC = (RooDataSet*)w->data("Bs2PhiKst0_MC2011")->Clone("Bs2KstKst0_MC"); Bs2PhiKst0_MC->append( *((RooDataSet*)w->data("Bs2PhiKst0_MC2012")) ); RooDataSet *Bd2RhoKst0_MC = (RooDataSet*)w->data("Bd2RhoKst0_MC2011")->Clone("Bs2KstKst0_MC"); Bd2RhoKst0_MC->append( *((RooDataSet*)w->data("Bd2RhoKst0_MC2012")) ); RooDataSet *Lb2ppipipi_MC = (RooDataSet*)w->data("Lb2ppipipi_MC2011")->Clone("Bs2KstKst0_MC"); Lb2ppipipi_MC->append( *((RooDataSet*)w->data("Lb2ppipipi_MC2012")) ); RooDataSet *Lb2pKpipi_MC = (RooDataSet*)w->data("Lb2pKpipi_MC2011")->Clone("Bs2KstKst0_MC"); Lb2pKpipi_MC->append( *((RooDataSet*)w->data("Lb2pKpipi_MC2012")) ); w->import(*Data); w->import(*Bs2Kst0Kst0_MC); w->import(*Bs2Kst0Kst01430_MC); w->import(*Bs2Kst01430Kst01430_MC); w->import(*Bd2Kst0Kst0_MC); w->import(*Bd2PhiKst0_MC); w->import(*Bs2PhiKst0_MC); w->import(*Bd2RhoKst0_MC); w->import(*Lb2ppipipi_MC); w->import(*Lb2pKpipi_MC); RooRealVar *mass = (RooRealVar*)w->var("B_s0_DTF_B_s0_M"); fitIpatia( w, "bs2kstkst_mc", "Bs2KstKst0_MC"); // Make the PDF here RooRealVar *p1 = new RooRealVar("p1","p1",-0.002,-0.004,0.); RooExponential *exp = new RooExponential("exp","exp",*mass,*p1); //RooRealVar *m1 = new RooRealVar("m1","m1",5320,5380); //RooRealVar *s1 = new RooRealVar("s1","s1",1,20); //RooGaussian *sig = new RooGaussian("sig","sig",*mass,*m1,*s1); RooRealVar *m2 = new RooRealVar("m2","m2",5320,5380); RooRealVar *s2 = new RooRealVar("s2","s2",1,20); RooGaussian *sig_bd = new RooGaussian("sig_bd","sig_bd",*mass,*m2,*s2); // RooRealVar *bs2kstkst_l = new RooRealVar( "bs2kstkst_l" ,"", -5, -20, -1.); RooConstVar *bs2kstkst_zeta = new RooConstVar( "bs2kstkst_zeta","",0. ); RooConstVar *bs2kstkst_fb = new RooConstVar( "bs2kstkst_fb" ,"",0. ); RooRealVar *bs2kstkst_sigma = new RooRealVar( "bs2kstkst_sigma","",15 ,10 ,20 ); RooRealVar *bs2kstkst_mu = new RooRealVar( "bs2kstkst_mu" ,"",5350 ,5380 ); RooRealVar *bs2kstkst_a = new RooRealVar( "bs2kstkst_a" ,"",2.5 , 0 ,10 ); RooRealVar *bs2kstkst_n = new RooRealVar( "bs2kstkst_n" ,"",2.5 , 0 ,10 ); RooRealVar *bs2kstkst_a2 = new RooRealVar( "bs2kstkst_a2" ,"",2.5 , 0 ,10 ); RooRealVar *bs2kstkst_n2 = new RooRealVar( "bs2kstkst_n2" ,"",2.5 , 0 ,10 ); RooIpatia2 *sig = new RooIpatia2("sig","sig",*mass,*bs2kstkst_l,*bs2kstkst_zeta,*bs2kstkst_fb,*bs2kstkst_sigma,*bs2kstkst_mu,*bs2kstkst_a,*bs2kstkst_n,*bs2kstkst_a2,*bs2kstkst_n2); RooRealVar *bkg_y = new RooRealVar("bkg_y","bkg_y",10e3,10e5); RooRealVar *sig_y = new RooRealVar("sig_y","sig_y",0,20e3); RooRealVar *sig_bd_y = new RooRealVar("sig_bd_y","sig_bd_y",0,3000); RooArgList *pdfs = new RooArgList(); RooArgList *yields = new RooArgList(); pdfs->add( *exp ); pdfs->add( *sig ); pdfs->add( *sig_bd ); yields->add( *bkg_y ); yields->add( *sig_y ); yields->add( *sig_bd_y ); RooAddPdf *pdf = new RooAddPdf("pdf","pdf",*pdfs,*yields); pdf->fitTo(*Data, Extended() ); RooPlot *plot = mass->frame(); Data->plotOn(plot); // set fit params constant; pdf->plotOn(plot); TCanvas *c = new TCanvas(); plot->Draw(); c->Print("tmp/mass.pdf"); // Plots Kst Ms with no sweights TCanvas *c1 = new TCanvas("c1","c1",800,1200); c1->Divide(1,2); c1->cd(1); RooPlot *c1p1 = w->var("B_s0_DTF_KST1_M")->frame(); Data->plotOn(c1p1); c1p1->Draw(); c1->cd(2); RooPlot *c1p2 = w->var("B_s0_DTF_KST2_M")->frame(); Data->plotOn(c1p2); c1p2->Draw(); c1->Print("tmp/nosw.pdf"); // set fit params constant p1->setConstant(true); //m1->setConstant(true); //s1->setConstant(true); bs2kstkst_l->setConstant(true); //bs2kstkst_zeta->setConstant(true); //bs2kstkst_fb->setConstant(true); bs2kstkst_sigma->setConstant(true); bs2kstkst_mu->setConstant(true); bs2kstkst_a->setConstant(true); bs2kstkst_n->setConstant(true); bs2kstkst_a2->setConstant(true); bs2kstkst_n2->setConstant(true); m2->setConstant(true); s2->setConstant(true); RooStats::SPlot *sData = new RooStats::SPlot("sData","sData", *Data, pdf, *yields); w->import(*sData); w->import(*Data,Rename("Data_wsweights")); RooDataSet *swdata = new RooDataSet("Data_wsweights", "Data", Data, *Data->get(), 0 , "sig_y_sw"); // Plots Kst Ms with no sweights TCanvas *c2 = new TCanvas("c2","c2",800,1200); c2->Divide(1,2); c2->cd(1); RooPlot *c2p1 = w->var("B_s0_DTF_KST1_M")->frame(); swdata->plotOn(c2p1); c2p1->Draw(); c2->cd(2); RooPlot *c2p2 = w->var("B_s0_DTF_KST2_M")->frame(); swdata->plotOn(c2p2); c2p2->Draw(); c2->Print("tmp/withsw.pdf"); tf->Close(); return 0; }
int main(int argc, char** argv){ gROOT->SetStyle("Plain"); double fMin , fMax, lumi, scaleLumi =1; int seed; Bool_t toy = kFALSE; Bool_t fitFromData = kFALSE; string infile, outfile; int rebinZMuMu =1, rebinZMuSa = 1, rebinZMuTk = 1, rebinZMuMuNoIso=1, rebinZMuMuHlt = 1; po::options_description desc("Allowed options"); desc.add_options() ("help,h", "produce help message") ("toy,t", "toy enabled") ("seed,s", po::value<int>(&seed)->default_value(34567), "seed value for toy") ("luminosity,l", po::value<double>(&lumi)->default_value(45.), "luminosity value for toy ") ("fit,f", "fit from data enabled") ("rebin,r", po::value< vector<int> > (), "rebin value: r_mutrk r mumuNotIso r_musa r _muhlt") ("input-file,i", po::value< string> (&infile), "input file") ("output-file,o", po::value< string> (&outfile), "output file with fit results") ("min,m", po::value<double>(&fMin)->default_value(60), "minimum value for fit range") ("max,M", po::value<double>(&fMax)->default_value(120), "maximum value for fit range"); po::positional_options_description p; p.add("rebin", -1); po::variables_map vm; po::store(po::command_line_parser(argc, argv). options(desc).positional(p).run(), vm); po::notify(vm); if (vm.count("help")) { cout << "Usage: options_description [options]\n"; cout << desc; return 0; } if (vm.count("toy")) { cout << "toy enabled with seed " << seed << "\n"; toy = kTRUE; //RooRandom::randomGenerator()->SetSeed(seed) ; // lumi should be intented as pb-1 and passed from outside scaleLumi= lumi / 45.0 ; // 45 is the current lumi correspondent to the histogram..... } if (vm.count("fit")) { cout << "fit from data enabled \n"; fitFromData = kTRUE; } if (!vm.count("toy") && !vm.count("fit")) { cerr << "Choose one beetween fitting form data or with a toy MC \n"; return 1; } if ( toy == fitFromData ){ cerr << "Choose if fit from data or with a toy MC \n"; return 1; } if (vm.count("rebin") ) { vector<int> v_rebin = vm["rebin"].as< vector<int> >(); if (v_rebin.size()!=4){ cerr << " please provide 4 numbers in the given order:r_mutrk r mumuNotIso r_musa r _muhlt \n"; return 1; } rebinZMuTk = v_rebin[0]; rebinZMuMuNoIso=v_rebin[1]; rebinZMuSa = v_rebin[2];rebinZMuMuHlt = v_rebin[3]; } RooRealVar * mass = new RooRealVar("mass", "mass (GeV/c^{2})", fMin, fMax ); TFile * root_file = new TFile(infile.c_str(), "read"); int range = (int)(fMax - fMin); int numberOfBins = range/rebinZMuSa + range/rebinZMuTk + range/rebinZMuMuNoIso + 2* range/rebinZMuMuHlt ; // zmm histograms used for pdf TH1F * zmm = getHisto(root_file, "goodZToMuMuPlots/zMass",fMin, fMax, rebinZMuMu ); // zmsta used for pdf TH1F *zmsta = getHisto(root_file, "zmumuSaMassHistogram/zMass",fMin, fMax, 1); // histogramms to fit..... TH1F *zmmsta = getHisto(root_file, "goodZToMuMuOneStandAloneMuonPlots/zMass",fMin, fMax, rebinZMuSa/rebinZMuMu); TH1F *zmt = getHisto(root_file, "goodZToMuMuOneTrackPlots/zMass", fMin, fMax, rebinZMuTk / rebinZMuMu); TH1F *zmmNotIso = getHisto(root_file,"nonIsolatedZToMuMuPlots/zMass", fMin, fMax, rebinZMuMuNoIso / rebinZMuMu); TH1F *zmm1hlt = getHisto(root_file, "goodZToMuMu1HLTPlots/zMass", fMin, fMax, rebinZMuMuHlt / rebinZMuMu); TH1F *zmm2hlt = getHisto(root_file, "goodZToMuMu2HLTPlots/zMass", fMin, fMax, rebinZMuMuHlt / rebinZMuMu); // creating a pdf for Zmt RooHistPdf * ZmtPdf = createHistPdf( "ZmtPdf", zmm, mass, rebinZMuTk/ rebinZMuMu ); // creating a pdf for Zmm not iso RooHistPdf * ZmmNoIsoPdf = createHistPdf( "ZmmNoIsoPdf", zmm, mass, rebinZMuMuNoIso/ rebinZMuMu ); // creating a pdf for Zms from zmsta!!! RooHistPdf * ZmsPdf = createHistPdf( "ZmsPdf", zmsta, mass, rebinZMuSa/ rebinZMuMu ); // creating a pdf for Zmmhlt RooHistPdf * ZmmHltPdf = createHistPdf( "ZmmHltPdf", zmm, mass, rebinZMuMuHlt/ rebinZMuMu ); // creating the variable with random init values RooRealVar Yield("Yield","Yield", 15000.,345.,3567890.) ; RooRealVar nbkg_mutrk("nbkg_mutrk","background _mutrk fraction",500,0.,100000.) ; RooRealVar nbkg_mumuNotIso("nbkg_mumuNotIso","background fraction",500,0.,100000.) ; RooRealVar nbkg_musa("nbkg_musa","background fraction",50,0.,100000.) ; RooRealVar eff_tk("eff_tk","signal _mutrk fraction",.99,0.8,1.0) ; RooRealVar eff_sa("eff_sa","eff musta",0.99,0.8,1.0) ; RooRealVar eff_iso("eff_iso","eff mumuNotIso",.99,0.8,1.0) ; RooRealVar eff_hlt("eff_hlt","eff 1hlt",0.99, 0.8,1.0) ; RooRealVar alpha ("alpha","coefficient alpha", -0.01 , -1000, 1000.) ; RooRealVar a0 ("a0","coefficient 0", 1,-1000.,1000.) ; RooRealVar a1 ("a1","coefficient 1", -0.001,-1000,1000.) ; RooRealVar a2 ("a2","coefficient 2", 0.0,-1000.,1000.) ; RooRealVar beta ("beta","coefficient beta", -0.01,-1000 , 1000. ) ; RooRealVar b0 ("b0","coefficient 0", 1,-1000.,1000.) ; RooRealVar b1 ("b1","coefficient 1", -0.001,-1000,1000.) ; RooRealVar b2("b2","coefficient 2", 0.0,-1000.,1000.) ; RooRealVar gamma ("gamma","coefficient gamma", -0.01,-1000 , 1000. ) ; RooRealVar c0 ("c0","coefficient 0", 1,-1000.,1000.) ; RooRealVar c1 ("c1","coefficient 1", -0.001,-1000,1000.) ; // fit parameters setted from datacard filebuf fb; fb.open ("zMuMuRooFit.txt",ios::in); istream is(&fb); char line[1000]; Yield.readFromStream(is.getline(line, 1000), kFALSE); nbkg_mutrk.readFromStream(is.getline(line,1000), kFALSE); nbkg_mumuNotIso.readFromStream(is.getline(line,1000), kFALSE); nbkg_musa.readFromStream(is.getline(line,1000), kFALSE); eff_tk.readFromStream(is.getline(line,1000), kFALSE); eff_sa.readFromStream(is.getline(line,1000), kFALSE); eff_iso.readFromStream(is.getline(line,1000), kFALSE); eff_hlt.readFromStream(is.getline(line,1000), kFALSE); alpha.readFromStream(is.getline(line,1000), kFALSE); a0.readFromStream(is.getline(line,1000), kFALSE); a1.readFromStream(is.getline(line,1000), kFALSE ); a2.readFromStream(is.getline(line,1000), kFALSE); beta.readFromStream(is.getline(line,1000), kFALSE); b0.readFromStream(is.getline(line,1000), kFALSE); b1.readFromStream(is.getline(line,1000), kFALSE); b2.readFromStream(is.getline(line,1000), kFALSE); gamma.readFromStream(is.getline(line,1000), kFALSE); c0.readFromStream(is.getline(line,1000), kFALSE); c1.readFromStream(is.getline(line,1000), kFALSE); fb.close(); // scaling to lumi if toy is enabled... if (vm.count("toy")) { Yield.setVal(scaleLumi * (Yield.getVal())); nbkg_mutrk.setVal(scaleLumi * (nbkg_mutrk.getVal())); nbkg_mumuNotIso.setVal(scaleLumi * (nbkg_mumuNotIso.getVal())); } //efficiency term //zMuMuEff1HLTTerm = _2 * (effTk ^ _2) * (effSa ^ _2) * (effIso ^ _2) * effHLT * (_1 - effHLT); RooFormulaVar zMuMu1HLTEffTerm("zMuMu1HLTEffTerm", "Yield * (2.* (eff_tk)^2 * (eff_sa)^2 * (eff_iso)^2 * eff_hlt *(1.- eff_hlt))", RooArgList(eff_tk, eff_sa,eff_iso, eff_hlt, Yield)); //zMuMuEff2HLTTerm = (effTk ^ _2) * (effSa ^ _2) * (effIso ^ _2) * (effHLT ^ _2) ; RooFormulaVar zMuMu2HLTEffTerm("zMuMu2HLTEffTerm", "Yield * ((eff_tk)^2 * (eff_sa)^2 * (eff_iso)^2 * (eff_hlt)^2)", RooArgList(eff_tk, eff_sa,eff_iso, eff_hlt, Yield)); //zMuMuNoIsoEffTerm = (effTk ^ _2) * (effSa ^ _2) * (_1 - (effIso ^ _2)) * (_1 - ((_1 - effHLT)^_2)); RooFormulaVar zMuMuNoIsoEffTerm("zMuMuNoIsoEffTerm", "Yield * ((eff_tk)^2 * (eff_sa)^2 * (1.- (eff_iso)^2) * (1.- ((1.-eff_hlt)^2)))", RooArgList(eff_tk, eff_sa,eff_iso, eff_hlt, Yield)); //zMuTkEffTerm = _2 * (effTk ^ _2) * effSa * (_1 - effSa) * (effIso ^ _2) * effHLT; RooFormulaVar zMuTkEffTerm("zMuTkEffTerm", "Yield * (2. *(eff_tk)^2 * eff_sa * (1.-eff_sa)* (eff_iso)^2 * eff_hlt)", RooArgList(eff_tk, eff_sa,eff_iso, eff_hlt, Yield)); //zMuSaEffTerm = _2 * (effSa ^ _2) * effTk * (_1 - effTk) * (effIso ^ _2) * effHLT; RooFormulaVar zMuSaEffTerm("zMuSaEffTerm", "Yield * (2. *(eff_sa)^2 * eff_tk * (1.-eff_tk)* (eff_iso)^2 * eff_hlt)", RooArgList(eff_tk, eff_sa,eff_iso, eff_hlt, Yield)); // creating model for the fit // z mu track RooGenericPdf *bkg_mutrk = new RooGenericPdf("bkg_mutrk","zmt bkg_model", "exp(alpha*mass) * ( a0 + a1 * mass + a2 * mass^2 )", RooArgSet( *mass, alpha, a0, a1,a2) ); // RooFormulaVar fracSigMutrk("fracSigMutrk", "@0 / (@0 + @1)", RooArgList(zMuTkEffTerm, nbkg_mutrk )); RooAddPdf * model_mutrk= new RooAddPdf("model_mutrk","model_mutrk",RooArgList(*ZmtPdf,*bkg_mutrk),RooArgList(zMuTkEffTerm , nbkg_mutrk)) ; // z mu mu not Iso // creating background pdf for zmu mu not Iso RooGenericPdf *bkg_mumuNotIso = new RooGenericPdf("bkg_mumuNotIso","zmumuNotIso bkg_model", "exp(beta * mass) * (b0 + b1 * mass + b2 * mass^2)", RooArgSet( *mass, beta, b0, b1,b2) ); // RooFormulaVar fracSigMuMuNoIso("fracSigMuMuNoIso", "@0 / (@0 + @1)", RooArgList(zMuMuNoIsoEffTerm, nbkg_mumuNotIso )); RooAddPdf * model_mumuNotIso= new RooAddPdf("model_mumuNotIso","model_mumuNotIso",RooArgList(*ZmmNoIsoPdf,*bkg_mumuNotIso), RooArgList(zMuMuNoIsoEffTerm, nbkg_mumuNotIso)); // z mu sta // RooGenericPdf model_musta("model_musta", " ZmsPdf * zMuSaEffTerm ", RooArgSet( *ZmsPdf, zMuSaEffTerm)) ; RooGenericPdf *bkg_musa = new RooGenericPdf("bkg_musa","zmusa bkg_model", "exp(gamma * mass) * (c0 + c1 * mass )", RooArgSet( *mass, gamma, c0, c1) ); // RooAddPdf * eZmsSig= new RooAddPdf("eZmsSig","eZmsSig",RooArgList(*,*bkg_mumuNotIso), RooArgList(zMuMuNoIsoEffTerm, nbkg_mumuNotIso)); RooAddPdf *eZmsSig = new RooAddPdf("eZmsSig","eZmsSig",RooArgList(*ZmsPdf,*bkg_musa),RooArgList(zMuSaEffTerm , nbkg_musa)) ; //RooExtendPdf * eZmsSig= new RooExtendPdf("eZmsSig","extended signal p.d.f for zms ",*ZmsPdf, zMuSaEffTerm ) ; // z mu mu HLT // count ZMuMu Yield double nZMuMu = 0.; double nZMuMu1HLT = 0.; double nZMuMu2HLT = 0.; unsigned int nBins = zmm->GetNbinsX(); double xMin = zmm->GetXaxis()->GetXmin(); double xMax = zmm->GetXaxis()->GetXmax(); double deltaX =(xMax - xMin) / nBins; for(unsigned int i = 0; i < nBins; ++i) { double x = xMin + (i +.5) * deltaX; if(x > fMin && x < fMax){ nZMuMu += zmm->GetBinContent(i+1); nZMuMu1HLT += zmm1hlt->GetBinContent(i+1); nZMuMu2HLT += zmm2hlt->GetBinContent(i+1); } } cout << ">>> count of ZMuMu yield in the range [" << fMin << ", " << fMax << "]: " << nZMuMu << endl; cout << ">>> count of ZMuMu (1HLT) yield in the range [" << fMin << ", " << fMax << "]: " << nZMuMu1HLT << endl; cout << ">>> count of ZMuMu (2HLT) yield in the range [" << fMin << ", " << fMax << "]: " << nZMuMu2HLT << endl; // we set eff_hlt //eff_hlt.setVal( 1. / (1. + (nZMuMu1HLT/ (2 * nZMuMu2HLT))) ) ; // creating the pdf for z mu mu 1hlt RooExtendPdf * eZmm1hltSig= new RooExtendPdf("eZmm1hltSig","extended signal p.d.f for zmm 1hlt",*ZmmHltPdf, zMuMu1HLTEffTerm ) ; // creating the pdf for z mu mu 2hlt RooExtendPdf * eZmm2hltSig= new RooExtendPdf("eZmm2hltSig","extended signal p.d.f for zmm 2hlt",*ZmmHltPdf, zMuMu2HLTEffTerm ) ; // getting the data if fit otherwise constructed the data for model if toy.... RooDataHist *zmtMass, * zmmNotIsoMass, *zmsMass, *zmm1hltMass, *zmm2hltMass; if (toy){ zmtMass = genHistFromModelPdf("zmtMass", model_mutrk, mass, scaleLumi, range,rebinZMuTk, seed); zmmNotIsoMass = genHistFromModelPdf("zmmNotIsoMass", model_mumuNotIso, mass, scaleLumi, range,rebinZMuMuNoIso, seed); zmsMass = genHistFromModelPdf("zmsMass", eZmsSig, mass, scaleLumi, range,rebinZMuSa , seed); zmm1hltMass = genHistFromModelPdf("zmm1hltMass", eZmm1hltSig, mass, scaleLumi, range,rebinZMuMuHlt, seed ); zmm2hltMass = genHistFromModelPdf("zmm2hltMass", eZmm2hltSig, mass, scaleLumi, range,rebinZMuMuHlt, seed); } else {// if fit from data.... zmtMass = new RooDataHist("zmtMass", "good z mu track" , RooArgList(*mass), zmt ); zmmNotIsoMass = new RooDataHist("ZmmNotIso", "good z mu mu not isolated" , RooArgList(*mass), zmmNotIso ); zmsMass = new RooDataHist("zmsMass", "good z mu sta mass" , RooArgList(*mass), zmmsta ); zmm1hltMass = new RooDataHist("zmm1hltMass", "good Z mu mu 1hlt" , RooArgList(*mass), zmm1hlt ); zmm2hltMass = new RooDataHist("zmm2hltMass", "good Z mu mu 2hlt" , RooArgList(*mass), zmm2hlt ); } // creting the chi2s RooChi2Var *chi2_mutrk = new RooChi2Var("chi2_mutrk","chi2_mutrk",*model_mutrk,*zmtMass, Extended(kTRUE),DataError(RooAbsData::SumW2) ) ; RooChi2Var *chi2_mumuNotIso = new RooChi2Var("chi2_mumuNotIso","chi2_mumuNotIso",*model_mumuNotIso,*zmmNotIsoMass,Extended(kTRUE), DataError(RooAbsData::SumW2)) ; RooChi2Var *chi2_musta = new RooChi2Var("chi2_musta","chi2_musta",*eZmsSig, *zmsMass, Extended(kTRUE) ,DataError(RooAbsData::SumW2) ) ; // uncomment this line if you want to use logLik for mu sta // RooNLLVar *chi2_musta = new RooNLLVar("chi2_musta","chi2_musta",*eZmsSig, *zmsMass, Extended(kTRUE), DataError(RooAbsData::SumW2) ) ; RooChi2Var *chi2_mu1hlt = new RooChi2Var("chi2_mu1hlt","chi2_mu1hlt", *eZmm1hltSig, *zmm1hltMass, Extended(kTRUE) , DataError(RooAbsData::SumW2)) ; RooChi2Var *chi2_mu2hlt = new RooChi2Var("chi2_mu2hlt","chi2_mu2hlt", *eZmm2hltSig, *zmm2hltMass, Extended(kTRUE), DataError(RooAbsData::SumW2) ) ; // adding the chi2 RooAddition totChi2("totChi2","chi2_mutrk + chi2_mumuNotIso + chi2_musta + chi2_mu1hlt + chi2_mu2hlt " , RooArgSet(*chi2_mutrk ,*chi2_mumuNotIso , *chi2_musta , *chi2_mu1hlt , *chi2_mu2hlt )) ; // printing out the model integral befor fitting double N_zMuMu1hlt = eZmm1hltSig->expectedEvents(*mass); double N_bkgTk = bkg_mutrk->expectedEvents(*mass); double N_bkgIso = bkg_mumuNotIso->expectedEvents(*mass); double N_zMuTk = zMuTkEffTerm.getVal(); double e_hlt = eff_hlt.getVal(); double e_tk = eff_tk.getVal(); double e_sa = eff_sa.getVal(); double e_iso = eff_iso.getVal(); double Y_hlt = N_zMuMu1hlt / ((2.* (e_tk * e_tk) * (e_sa * e_sa) * (e_iso* e_iso) * e_hlt *(1.- e_hlt))) ; double Y_mutk = N_zMuTk / ((2.* (e_tk * e_tk) * e_sa *(1.- e_sa) * (e_iso* e_iso) * e_hlt )) ; cout << "Yield prediction from mumu1hlt integral befor fitting: " << Y_hlt << endl ; cout << "Yield prediction from mutk integral befor fitting: " << Y_mutk << endl; cout << "Bkg for mutk prediction from mutk integral after fitting: " << N_bkgTk << endl; cout << "Bkg for mumuNotIso prediction from mumuNotIso integral after fitting: " << N_bkgIso << endl; fit( totChi2, numberOfBins, outfile.c_str()); N_zMuMu1hlt = eZmm1hltSig->expectedEvents(*mass); N_zMuTk = zMuTkEffTerm.getVal(); double N_zMuMuNoIso = zMuMuNoIsoEffTerm.getVal(); double N_Tk = model_mutrk->expectedEvents(*mass); double N_Iso = model_mumuNotIso->expectedEvents(*mass); e_hlt = eff_hlt.getVal(); e_tk = eff_tk.getVal(); e_sa = eff_sa.getVal(); e_iso = eff_iso.getVal(); Y_hlt = N_zMuMu1hlt / ((2.* (e_tk * e_tk) * (e_sa * e_sa) * (e_iso* e_iso) * e_hlt *(1.- e_hlt))) ; Y_mutk = N_zMuTk / ((2.* (e_tk * e_tk) * e_sa *(1.- e_sa) * (e_iso* e_iso) * e_hlt )) ; cout << "Yield prediction from mumu1hlt integral after fitting: " << Y_hlt << endl; //cout << "Yield prediction from mutk integral after fitting: " << Y_mutk << endl; cout << "N + B prediction from mutk integral after fitting: " << N_Tk << endl; cout << "zMuTkEffTerm " << N_zMuTk << endl; cout << "N + B prediction from mumuNotIso integral after fitting: " << N_Iso << endl; cout << "zMuMuNoIsoEffTerm " << N_zMuMuNoIso << endl; cout << "chi2_mutrk:" << chi2_mutrk->getVal()<< endl; cout << "chi2_mumuNotIso:" << chi2_mumuNotIso->getVal() << endl; cout << "chi2_musta:" << chi2_musta->getVal() << endl; cout << "chi2_mumu1hlt:" << chi2_mu1hlt->getVal()<< endl; cout << "chi2_mumu2hlt:" << chi2_mu2hlt->getVal()<< endl; //plotting RooPlot * massFrame_mutrk = mass->frame() ; RooPlot * massFrame_mumuNotIso = mass->frame() ; RooPlot * massFrame_musta = mass->frame() ; RooPlot * massFrame_mumu1hlt = mass->frame() ; RooPlot * massFrame_mumu2hlt = mass->frame() ; TCanvas * canv1 = new TCanvas("canvas"); TCanvas * canv2 = new TCanvas("new_canvas"); canv1->Divide(2,3); canv1->cd(1); canv1->SetLogy(kTRUE); zmtMass->plotOn(massFrame_mutrk, LineColor(kBlue)) ; model_mutrk->plotOn(massFrame_mutrk,LineColor(kRed)) ; model_mutrk->plotOn(massFrame_mutrk,Components(*bkg_mutrk),LineColor(kGreen)) ; massFrame_mutrk->SetTitle("Z -> #mu track"); // massFrame_mutrk->GetYaxis()->SetLogScale(); massFrame_mutrk->Draw(); gPad->SetLogy(1); canv2->cd(); canv2->SetLogy(kTRUE); massFrame_mutrk->Draw(); canv2->SaveAs("LogZMuTk.eps"); canv2->SetLogy(kFALSE); canv2->SaveAs("LinZMuTk.eps"); canv1->cd(2); zmmNotIsoMass->plotOn(massFrame_mumuNotIso, LineColor(kBlue)) ; model_mumuNotIso->plotOn(massFrame_mumuNotIso,LineColor(kRed)) ; model_mumuNotIso->plotOn(massFrame_mumuNotIso,Components(*bkg_mumuNotIso), LineColor(kGreen)) ; massFrame_mumuNotIso->SetTitle("Z -> #mu #mu not isolated"); massFrame_mumuNotIso->Draw(); gPad->SetLogy(1); canv2->cd(); canv2->Clear(); canv2->SetLogy(kTRUE); massFrame_mumuNotIso->Draw(); canv2->SaveAs("LogZMuMuNotIso.eps"); canv2->SetLogy(kFALSE); canv2->SaveAs("LinZMuMuNotIso.eps"); canv1->cd(3); zmsMass->plotOn(massFrame_musta, LineColor(kBlue)) ; eZmsSig->plotOn(massFrame_musta,Components(*bkg_musa), LineColor(kGreen)) ; eZmsSig->plotOn(massFrame_musta,LineColor(kRed)) ; massFrame_musta->SetTitle("Z -> #mu sta"); massFrame_musta->Draw(); canv2->cd(); canv2->Clear(); canv2->SetLogy(kTRUE); massFrame_musta->Draw(); canv2->SaveAs("LogZMuSa.eps"); canv2->SetLogy(kFALSE); canv2->SaveAs("LinZMuSa.eps"); canv1->cd(4); zmm1hltMass->plotOn(massFrame_mumu1hlt, LineColor(kBlue)) ; eZmm1hltSig->plotOn(massFrame_mumu1hlt,LineColor(kRed)) ; massFrame_mumu1hlt->SetTitle("Z -> #mu #mu 1hlt"); massFrame_mumu1hlt->Draw(); canv2->cd(); canv2->Clear(); canv2->SetLogy(kTRUE); massFrame_mumu1hlt->Draw(); canv2->SaveAs("LogZMuMu1Hlt.eps"); canv2->SetLogy(kFALSE); canv2->SaveAs("LinZMuMu1Hlt.eps"); canv1->cd(5); zmm2hltMass->plotOn(massFrame_mumu2hlt, LineColor(kBlue)) ; eZmm2hltSig->plotOn(massFrame_mumu2hlt,LineColor(kRed)) ; massFrame_mumu2hlt->SetTitle("Z -> #mu #mu 2hlt"); massFrame_mumu2hlt->Draw(); canv1->SaveAs("mass.eps"); canv2->cd(); canv2->Clear(); canv2->SetLogy(kTRUE); massFrame_mumu2hlt->Draw(); canv2->SaveAs("LogZMuMu2Hlt.eps"); canv2->SetLogy(kFALSE); canv2->SaveAs("LinZMuMu2Hlt.eps"); /* how to read the fit result in root TH1D h_Yield("h_Yield", "h_Yield", 100, 10000, 30000) for (int i =0: i < 100; i++){ RooFitResult* r = gDirectory->Get(Form("toy_totChi2;%d)",i) //r->floatParsFinal().Print("s"); // without s return a list, can we get the number? RooFitResult* r = gDirectory->Get("toy_totChi2;1") // chi2 r->minNll(); //distamce form chi2..... //r->edm(); // yield r->floatParsFinal()[0]->Print(); //RooAbsReal * l = r->floatParsFinal()->first() RooAbsReal * y = r->floatParsFinal()->find("Yield"); h_Yield->Fill(y->getVal()); } */ delete root_file; //delete out_root_file; return 0; }
void addNuisanceWithToys(std::string iFileName,std::string iChannel,std::string iBkg,std::string iEnergy,std::string iName,std::string iDir,bool iRebin=true,bool iVarBin=false,int iFitModel=1,int iFitModel1=1,double iFirst=150,double iLast=1500,std::string iSigMass="800",double iSigScale=0.1,int iNToys=1000) { std::cout << "======> " << iDir << "/" << iBkg << " -- " << iFileName << std::endl; if(iVarBin) std::cout << "option not implemented yet!"; if(iVarBin) return; //double lFirst = 200; //double lLast = 1500; double lFirst = iFirst; double lLast = iLast; std::cout << "===================================================================================================================================================" <<std::endl; std::cout << "Using Initial fit model: " << iFitModel << ", fitting range: " << iFirst << "-" << iLast << " , using alternative fit model: " << iFitModel1 << std::endl; std::cout << "===================================================================================================================================================" <<std::endl; TFile *lFile = new TFile(iFileName.c_str()); TH1F *lH0 = (TH1F*) lFile->Get((iDir+"/"+iBkg).c_str()); TH1F *lData = (TH1F*) lFile->Get((iDir+"/data_obs").c_str()); TH1F *lSig = 0; // for now, use bbH signal for testing in b-tag and ggH in no-btag if(iDir.find("_btag") != std::string::npos) lSig = (TH1F*)lFile->Get((iDir+"/bbH"+iSigMass+"_fine_binning").c_str()); else lSig = (TH1F*)lFile->Get((iDir+"/ggH"+iSigMass+"_fine_binning").c_str()); TH1F *lH0Clone = (TH1F*)lH0->Clone("lH0Clone"); // binning too fine as of now? start by rebinning TH1F *lDataClone = (TH1F*)lData->Clone("lDataClone"); TH1F *lSigClone = (TH1F*)lSig->Clone("lSigClone"); // lH0Clone->Rebin(2); // lDataClone->Rebin(2); // lSigClone->Rebin(2); lSig->Rebin(10); //Define the fit function RooRealVar lM("m","m" ,0,5000); lM.setRange(lFirst,lLast); RooRealVar lA("a","a" ,50, 0.1,200); RooRealVar lB("b","b" ,0.0 , -10.5,10.5); RooRealVar lA1("a1","a1" ,50, 0.1,1000); RooRealVar lB1("b1","b1" ,0.0 , -10.5,10.5); RooDataHist *pH0 = new RooDataHist("Data","Data" ,RooArgList(lM),lH0); double lNB0 = lH0->Integral(lH0->FindBin(lFirst),lH0->FindBin(lLast)); double lNSig0 = lSig->Integral(lSig->FindBin(lFirst),lSig->FindBin(lLast)); //lNB0=500; // lNSig0=500; lSig->Scale(iSigScale*lNB0/lNSig0); // scale signal to iSigScale*(Background yield), could try other options lNSig0 = lSig->Integral(lSig->FindBin(lFirst),lSig->FindBin(lLast)); // readjust norm of signal hist //Generate the "default" fit model RooGenericPdf *lFit = 0; lFit = new RooGenericPdf("genPdf","exp(-m/(a+b*m))",RooArgList(lM,lA,lB)); if(iFitModel == 1) lFit = new RooGenericPdf("genPdf","exp(-a*pow(m,b))",RooArgList(lM,lA,lB)); if(iFitModel == 1) {lA.setVal(0.3); lB.setVal(0.5);} if(iFitModel == 2) lFit = new RooGenericPdf("genPdf","a*exp(b*m)",RooArgList(lM,lA,lB)); if(iFitModel == 2) {lA.setVal(0.01); lA.setRange(0,10); } if(iFitModel == 3) lFit = new RooGenericPdf("genPdf","a/pow(m,b)",RooArgList(lM,lA,lB)); // Generate the alternative model RooGenericPdf *lFit1 = 0; lFit1 = new RooGenericPdf("genPdf","exp(-m/(a1+b1*m))",RooArgList(lM,lA1,lB1)); if(iFitModel1 == 1) lFit1 = new RooGenericPdf("genPdf","exp(-a1*pow(m,b1))",RooArgList(lM,lA1,lB1)); if(iFitModel1 == 1) {lA1.setVal(0.3); lB1.setVal(0.5);} if(iFitModel1 == 2) lFit1 = new RooGenericPdf("genPdf","a1*exp(b1*m)",RooArgList(lM,lA1,lB1)); if(iFitModel1 == 2) {lA1.setVal(0.01); lA1.setRange(0,10); } if(iFitModel1 == 3) lFit1 = new RooGenericPdf("genPdf","a1/pow(m,b1)",RooArgList(lM,lA1,lB1)); //============================================================================================================================================= //Perform the tail fit and generate the shift up and down histograms //============================================================================================================================================= RooFitResult *lRFit = 0; lRFit = lFit->fitTo(*pH0,RooFit::Save(kTRUE),RooFit::Range(lFirst,lLast),RooFit::Strategy(0)); TMatrixDSym lCovMatrix = lRFit->covarianceMatrix(); TMatrixD lEigVecs(2,2); lEigVecs = TMatrixDSymEigen(lCovMatrix).GetEigenVectors(); TVectorD lEigVals(2); lEigVals = TMatrixDSymEigen(lCovMatrix).GetEigenValues(); cout << " Ve---> " << lEigVecs(0,0) << " -- " << lEigVecs(1,0) << " -- " << lEigVecs(0,1) << " -- " << lEigVecs(1,1) << endl; cout << " Co---> " << lCovMatrix(0,0) << " -- " << lCovMatrix(1,0) << " -- " << lCovMatrix(0,1) << " -- " << lCovMatrix(1,1) << endl; double lACentral = lA.getVal(); double lBCentral = lB.getVal(); lEigVals(0) = sqrt(lEigVals(0)); lEigVals(1) = sqrt(lEigVals(1)); cout << "===> " << lEigVals(0) << " -- " << lEigVals(1) << endl; TH1F* lH = (TH1F*) lFit->createHistogram("fit" ,lM,RooFit::Binning(lH0->GetNbinsX(),lH0->GetXaxis()->GetXmin(),lH0->GetXaxis()->GetXmax())); lA.setVal(lACentral + lEigVals(0)*lEigVecs(0,0)); lB.setVal(lBCentral + lEigVals(0)*lEigVecs(1,0)); TH1F* lHUp = (TH1F*) lFit->createHistogram("Up" ,lM,RooFit::Binning(lH0->GetNbinsX(),lH0->GetXaxis()->GetXmin(),lH0->GetXaxis()->GetXmax())); lA.setVal(lACentral - lEigVals(0)*lEigVecs(0,0)); lB.setVal(lBCentral - lEigVals(0)*lEigVecs(1,0)); TH1F* lHDown = (TH1F*) lFit->createHistogram("Down",lM,RooFit::Binning(lH0->GetNbinsX(),lH0->GetXaxis()->GetXmin(),lH0->GetXaxis()->GetXmax())); lA.setVal(lACentral + lEigVals(1)*lEigVecs(0,1)); lB.setVal(lBCentral + lEigVals(1)*lEigVecs(1,1)); TH1F* lHUp1 = (TH1F*) lFit->createHistogram("Up1",lM,RooFit::Binning(lH0->GetNbinsX(),lH0->GetXaxis()->GetXmin(),lH0->GetXaxis()->GetXmax())); lA.setVal(lACentral - lEigVals(1)*lEigVecs(0,1)); lB.setVal(lBCentral - lEigVals(1)*lEigVecs(1,1)); TH1F* lHDown1 = (TH1F*) lFit->createHistogram("Down1",lM,RooFit::Binning(lH0->GetNbinsX(),lH0->GetXaxis()->GetXmin(),lH0->GetXaxis()->GetXmax())); std::string lNuisance1 = iBkg+"_"+"CMS_"+iName+"1_" + iChannel + "_" + iEnergy; std::string lNuisance2 = iBkg+"_"+"CMS_"+iName+"2_" + iChannel + "_" + iEnergy; lHUp = merge(lNuisance1 + "Up" ,lFirst,lH0,lHUp); lHDown = merge(lNuisance1 + "Down" ,lFirst,lH0,lHDown); lHUp1 = merge(lNuisance2 + "Up" ,lFirst,lH0,lHUp1); lHDown1 = merge(lNuisance2 + "Down" ,lFirst,lH0,lHDown1); lH = merge(lH0->GetName() ,lFirst,lH0,lH); //============================================================================================================================================= //============================================================================================================================================= //Set the variables A and B to the final central values from the tail fit lA.setVal(lACentral); lB.setVal(lBCentral); // lA.removeRange(); // lB.removeRange(); //Generate the background pdf corresponding to the final result of the tail fit RooGenericPdf *lFitFinal = 0; lFitFinal = new RooGenericPdf("genPdf","exp(-m/(a+b*m))",RooArgList(lM,lA,lB)); if(iFitModel == 1) lFitFinal = new RooGenericPdf("genPdf","exp(-a*pow(m,b))",RooArgList(lM,lA,lB)); if(iFitModel == 2) lFitFinal = new RooGenericPdf("genPdf","a*exp(b*m)",RooArgList(lM,lA,lB)); if(iFitModel == 3) lFitFinal = new RooGenericPdf("genPdf","a/pow(m,b)",RooArgList(lM,lA,lB)); //============================================================================================================================================= //Perform the tail fit with the alternative fit function (once initially, before allowing tail fit to float in toy fit). //============================================================================================================================================= RooFitResult *lRFit1 = 0; //lRFit1=lFit1->fitTo(*pH0,RooFit::Save(kTRUE),RooFit::Range(iFirst,iLast),RooFit::Strategy(0)); lRFit1=lFit1->fitTo(*pH0,RooFit::Save(kTRUE),RooFit::Range(200,1500),RooFit::Strategy(0)); //Generate the background pdf corresponding to the result of the alternative tail fit RooGenericPdf *lFit1Final = 0; lFit1Final = new RooGenericPdf("genPdf","exp(-m/(a1+b1*m))",RooArgList(lM,lA1,lB1)); if(iFitModel1 == 1) lFit1Final = new RooGenericPdf("genPdf","exp(-a1*pow(m,b1))",RooArgList(lM,lA1,lB1)); if(iFitModel1 == 2) lFit1Final = new RooGenericPdf("genPdf","a1*exp(b1*m)",RooArgList(lM,lA1,lB1)); if(iFitModel1 == 3) lFit1Final = new RooGenericPdf("genPdf","a1/pow(m,b1)",RooArgList(lM,lA1,lB1)); // lA1.removeRange(); // lB1.removeRange(); //============================================================================================================================================= //Define RooRealVar for the normalization of the signal and background, starting from the initial integral of the input histograms lM.setRange(300,1500); RooRealVar lNB("nb","nb",lNB0,0,10000); RooRealVar lNSig("nsig","nsig",lNSig0,-1000,1000); //Define a PDF for the signal histogram lSig RooDataHist *pS = new RooDataHist("sigH","sigH",RooArgList(lM),lSig); RooHistPdf *lSPdf = new RooHistPdf ("sigPdf","sigPdf",lM,*pS); //Define generator and fit functions for the RooMCStudy RooAddPdf *lGenMod = new RooAddPdf ("genmod","genmod",RooArgList(*lFitFinal ,*lSPdf),RooArgList(lNB,lNSig)); RooAddPdf *lFitMod = new RooAddPdf ("fitmod","fitmod",RooArgList(*lFit1Final,*lSPdf),RooArgList(lNB,lNSig)); //Generate plot of the signal and background models going into the toy generation RooPlot* plot=lM.frame(); lGenMod->plotOn(plot); lGenMod->plotOn(plot,RooFit::Components(*lSPdf),RooFit::LineColor(2)); TCanvas* lC11 = new TCanvas("pdf","pdf",600,600) ; lC11->cd(); plot->Draw(); lC11->SaveAs(("SBModel_"+iBkg+"_" + iDir + "_" + iEnergy+".pdf").c_str()); std::cout << "===================================================================================================================================================" <<std::endl; std::cout << "FIT PARAMETERS BEFORE ROOMCSTUDY: lA: " << lA.getVal() << " lB: " << lB.getVal() << " lA1: " << lA1.getVal() << " lB1: " << lB1.getVal() << std::endl; std::cout << "===================================================================================================================================================" <<std::endl; RooMCStudy *lToy = new RooMCStudy(*lGenMod,lM,RooFit::FitModel(*lFitMod),RooFit::Binned(kTRUE),RooFit::Silence(),RooFit::Extended(kTRUE),RooFit::Verbose(kTRUE),RooFit::FitOptions(RooFit::Save(kTRUE),RooFit::Strategy(0))); // Generate and fit iNToys toy samples std::cout << "Number of background events: " << lNB0 << " Number of signal events: " << lNSig0 << " Sum: " << lNB0+lNSig0 << std::endl; //============================================================================================================================================= // Generate and fit toys //============================================================================================================================================= lToy->generateAndFit(iNToys,lNB0+lNSig0,kTRUE); std::cout << "===================================================================================================================================================" <<std::endl; std::cout << "FIT PARAMETERS AFTER ROOMCSTUDY: lA: " << lA.getVal() << " lB: " << lB.getVal() << " lA1: " << lA1.getVal() << " lB1: " << lB1.getVal() << std::endl; std::cout << "===================================================================================================================================================" <<std::endl; //============================================================================================================================================= // Generate plots relevant to the toy fit //============================================================================================================================================= RooPlot* lFrame1 = lToy->plotPull(lNSig,-5,5,100,kTRUE); lFrame1->SetTitle("distribution of pulls on signal yield from toys"); lFrame1->SetXTitle("N_{sig} pull"); TCanvas* lC00 = new TCanvas("pulls","pulls",600,600) ; lC00->cd(); lFrame1->GetYaxis()->SetTitleOffset(1.2); lFrame1->GetXaxis()->SetTitleOffset(1.0); lFrame1->Draw() ; lC00->SaveAs(("sig_pulls_toyfits_"+iBkg+"_" + iDir + "_" + iEnergy+".png").c_str()); RooPlot* lFrame2 = lToy->plotParam(lA1); lFrame2->SetTitle("distribution of values of parameter 1 (a) after toy fit"); lFrame2->SetXTitle("Parameter 1 (a)"); TCanvas* lC01 = new TCanvas("valA","valA",600,600) ; lFrame2->Draw() ; lC01->SaveAs(("valA_toyfits_"+iBkg+"_" + iDir + "_" + iEnergy+".png").c_str()); RooPlot* lFrame3 = lToy->plotParam(lB1); lFrame3->SetTitle("distribution of values of parameter 2 (b) after toy fit"); lFrame3->SetXTitle("Parameter 2 (b)"); TCanvas* lC02 = new TCanvas("valB","valB",600,600) ; lFrame3->Draw() ; lC02->SaveAs(("valB_toyfits_"+iBkg+"_" + iDir + "_" + iEnergy+".png").c_str()); RooPlot* lFrame6 = lToy->plotNLL(0,1000,100); lFrame6->SetTitle("-log(L)"); lFrame6->SetXTitle("-log(L)"); TCanvas* lC05 = new TCanvas("logl","logl",600,600) ; lFrame6->Draw() ; lC05->SaveAs(("logL_toyfits_"+iBkg+"_" + iDir + "_" + iEnergy+".png").c_str()); RooPlot* lFrame7 = lToy->plotParam(lNSig); lFrame7->SetTitle("distribution of values of N_{sig} after toy fit"); lFrame7->SetXTitle("N_{sig}"); TCanvas* lC06 = new TCanvas("Nsig","Nsig",600,600) ; lFrame7->Draw() ; lC06->SaveAs(("NSig_toyfits_"+iBkg+"_" + iDir + "_" + iEnergy+".png").c_str()); RooPlot* lFrame8 = lToy->plotParam(lNB); lFrame8->SetTitle("distribution of values of N_{bkg} after toy fit"); lFrame8->SetXTitle("N_{bkg}"); TCanvas* lC07 = new TCanvas("Nbkg","Nbkg",600,600) ; lFrame8->Draw() ; lC07->SaveAs(("Nbkg_toyfits_"+iBkg+"_" + iDir + "_" + iEnergy+".png").c_str()); if(iRebin) { const int lNBins = lData->GetNbinsX(); double *lAxis = getAxis(lData); lH0 = rebin(lH0 ,lNBins,lAxis); lH = rebin(lH ,lNBins,lAxis); lHUp = rebin(lHUp ,lNBins,lAxis); lHDown = rebin(lHDown ,lNBins,lAxis); lHUp1 = rebin(lHUp1 ,lNBins,lAxis); lHDown1 = rebin(lHDown1,lNBins,lAxis); } // we dont need this bin errors since we do not use them (fit tails replaces bin-by-bin error!), therefore i set all errors to 0, this also saves us from modifying the add_bbb_error.py script in which I otherwise would have to include a option for adding bbb only in specific ranges int lMergeBin = lH->GetXaxis()->FindBin(iFirst); for(int i0 = lMergeBin; i0 < lH->GetNbinsX()+1; i0++){ lH->SetBinError (i0,0); lHUp->SetBinError (i0,0); lHDown->SetBinError (i0,0); lHUp1->SetBinError (i0,0); lHDown1->SetBinError (i0,0); } TFile *lOutFile =new TFile("Output.root","RECREATE"); cloneFile(lOutFile,lFile,iDir+"/"+iBkg); lOutFile->cd(iDir.c_str()); lH ->Write(); lHUp ->Write(); lHDown ->Write(); lHUp1 ->Write(); lHDown1->Write(); // Debug Plots lH0->SetStats(0); lH->SetStats(0); lHUp->SetStats(0); lHDown->SetStats(0); lHUp1->SetStats(0); lHDown1->SetStats(0); lH0 ->SetLineWidth(1); lH0->SetMarkerStyle(kFullCircle); lH ->SetLineColor(kGreen); lHUp ->SetLineColor(kRed); lHDown ->SetLineColor(kRed); lHUp1 ->SetLineColor(kBlue); lHDown1->SetLineColor(kBlue); TCanvas *lC0 = new TCanvas("Can","Can",800,600); lC0->Divide(1,2); lC0->cd(); lC0->cd(1)->SetPad(0,0.2,1.0,1.0); gPad->SetLeftMargin(0.2) ; lH0->Draw(); lH ->Draw("hist sames"); lHUp ->Draw("hist sames"); lHDown ->Draw("hist sames"); lHUp1 ->Draw("hist sames"); lHDown1->Draw("hist sames"); gPad->SetLogy(); TLegend* leg1; /// setup the CMS Preliminary leg1 = new TLegend(0.7, 0.80, 1, 1); leg1->SetBorderSize( 0 ); leg1->SetFillStyle ( 1001 ); leg1->SetFillColor (kWhite); leg1->AddEntry( lH0 , "orignal", "PL" ); leg1->AddEntry( lH , "cental fit", "L" ); leg1->AddEntry( lHUp , "shift1 up", "L" ); leg1->AddEntry( lHDown , "shift1 down", "L" ); leg1->AddEntry( lHUp1 , "shift2 up", "L" ); leg1->AddEntry( lHDown1 , "shift2 down", "L" ); leg1->Draw("same"); lC0->cd(2)->SetPad(0,0,1.0,0.2); gPad->SetLeftMargin(0.2) ; drawDifference(lH0,lH,lHUp,lHDown,lHUp1,lHDown1); lH0->SetStats(0); lC0->Update(); lC0->SaveAs((iBkg+"_"+"CMS_"+iName+"1_" + iDir + "_" + iEnergy+".png").c_str()); //lFile->Close(); return; }
double RunHypoTest(char *smwwFileName, char *ttbarFileName, char *wp3jetsFileName, char *wp4jetsFileName, char *opsFileName, char *outputFileName, double lambda) { TFile *smwwFile = new TFile(smwwFileName); TFile *ttbarFile = new TFile(ttbarFileName); TFile *wp3jetsFile = new TFile(wp3jetsFileName); TFile *wp4jetsFile = new TFile(wp4jetsFileName); TFile *opsFile = new TFile(opsFileName); TFile *outputFile = new TFile(outputFileName, "UPDATE"); TH1F *smww = (TH1F*)smwwFile->Get(WW_MASS_HISTOGRAM_NAME); TH1F *ttbar = (TH1F*)ttbarFile->Get(WW_MASS_HISTOGRAM_NAME); TH1F *wp3jets = (TH1F*)wp3jetsFile->Get(WW_MASS_HISTOGRAM_NAME); TH1F *wp4jets = (TH1F*)wp4jetsFile->Get(WW_MASS_HISTOGRAM_NAME); //Histogram of ww-scattering with effective operator contributions TH1F *ops = (TH1F*)opsFile->Get(WW_MASS_HISTOGRAM_NAME); RooRealVar *mww = new RooRealVar("mww", "M_{WW}", 600, 2500, "GeV"); RooDataHist smData("smData", "smData", RooArgList(*mww), smww); RooDataHist opsData("opsData", "opsData", RooArgList(*mww), ops); RooDataHist ttbarData("ttbarData", "ttbarData", RooArgList(*mww), ttbar); RooDataHist wp3jetsData("wp3jetsData", "wp3jetsData", RooArgList(*mww), wp3jets); RooDataHist wp4jetsData("wp4jetsData", "wp4jetsData", RooArgList(*mww), wp4jets); /* RooAbsPdf *opsModel; if (lambda == 400) { opsModel = SpecialCaseModel(&opsData, mww, (char*)"ops"); } else { opsModel = MakeModel(&opsData, mww, (char*)"ops"); }*/ RooAbsPdf *opsModel = MakeModel(&opsData, mww, (char*)"ops"); //RooPlot *xframe = mww->frame(); //opsData.plotOn(xframe); //opsModel->plotOn(xframe); //printf("Chi-squared for lambda = %f: = %f\n", lambda, xframe->chiSquare("opsModel", "opsData", 3)); RooAbsPdf *smModel = MakeModelNoSignal(&smData, mww, (char*)"sm"); RooAbsPdf *ttbarModel = MakeModelNoSignal(&ttbarData, mww, (char*)"ttbar"); RooAbsPdf *wp3jetsModel = MakeModelNoSignal(&wp3jetsData, mww, (char*)"wp3jets"); RooAbsPdf *wp4jetsModel = MakeModelNoSignal(&wp4jetsData, mww, (char*)"wp4jets"); TCanvas *canvas = new TCanvas(opsFileName); RooPlot *frame = mww->frame(); frame->SetTitle(""); //smData.plotOn(frame, RooFit::LineColor(kBlack), RooFit::Name("smData")); //smModel->plotOn(frame, RooFit::LineColor(kBlue), RooFit::Name("smModel")); //ttbarModel->plotOn(frame, RooFit::LineColor(kRed), RooFit::Name("ttbarModel")); //wp3jetsModel->plotOn(frame, RooFit::LineColor(kYellow), RooFit::Name("wpjetsModel")); opsData.plotOn(frame); opsModel->plotOn(frame, RooFit::LineColor(kBlue), RooFit::Name("opsModel")); //leg->AddEntry(frame->findObject("smModel"), "SM Model", "lep"); //leg->AddEntry(frame->findObject("ttbarModel"), "TTBar Model", "lep"); //leg->AddEntry(frame->findObject("wp3jetsModel"), "WP3Jets Model", "lep"); //leg->AddEntry(frame->findObject("opsModel"), "Effective Operator Model", "lep"); frame->Draw(); canvas->Write(); Double_t ww_x = WW_CROSS_SECTION * smww->GetEntries(); Double_t ttbar_x = TTBAR_CROSS_SECTION * ttbar->GetEntries(); Double_t wp3jets_x = WP3JETS_CROSS_SECTION * wp3jets->GetEntries(); Double_t wp4jets_x = WP4JETS_CROSS_SECTION * wp4jets->GetEntries(); Double_t ttbar_weight = ttbar_x/(ttbar_x + wp3jets_x + wp4jets_x + ww_x); Double_t wp3jets_weight = wp3jets_x/(wp3jets_x + ttbar_x + ww_x); Double_t wp4jets_weight = wp4jets_x/(wp4jets_x + ttbar_x + ww_x); RooRealVar *ttbarWeight = new RooRealVar("ttbarWeight", "ttbarWeight", 0.0, 1.0, ttbar_weight); RooRealVar *wp3jetsWeight = new RooRealVar("wp3jetsWeight", "wp3jetsWeight", 0.0, 1.0, wp3jets_weight); RooRealVar *wp4jetsWeight = new RooRealVar("wp4jetsWeight", "wp4jetsWeight", 0.0, 1.0, wp4jets_weight); ttbarWeight->setConstant(); wp3jetsWeight->setConstant(); wp4jetsWeight->setConstant(); RooRealVar *mu = new RooRealVar("mu", "mu", 0.0, 1.0, ""); RooAddPdf *wwModel = new RooAddPdf("wwModel", "u*effective_ww + (1-u)*SM_WW", RooArgList(*opsModel, *smModel), RooArgList(*mu), kTRUE); RooAddPdf *model = new RooAddPdf("model", "Full model", RooArgList(*ttbarModel, *wp3jetsModel, *wp4jetsModel, *wwModel), RooArgList(*ttbarWeight, *wp3jetsWeight, *wp4jetsWeight), kTRUE); //Generate data under the alternate hypothesis mu->setVal(1.0); int nTestSetEvents = WW_CROSS_SECTION * TOTAL_INTEGRATED_LUMINOSITY; RooAbsData *generatedData = model->generate(*mww, nTestSetEvents); TCanvas *canvas2 = new TCanvas("CombinedModels"); RooPlot *frame2 = mww->frame(); //wwModel->plotOn(frame2, RooFit::LineColor(kRed), RooFit::Name("wwModel")); //generatedData->plotOn(frame2); mu->setVal(0.0); model->plotOn(frame2, RooFit::LineColor(kBlue), RooFit::Name("nullModel")); mu->setVal(1.0); model->plotOn(frame2, RooFit::LineColor(kRed), RooFit::Name("altModel")); TLegend *leg2 = new TLegend(0.65,0.73,0.86,0.87); //leg->AddEntry(frame2->findObject("wwModel"), "SM WW Scattering model with background", // "lep"); leg2->AddEntry(frame2->findObject("nullModel"), "SM + Background", "lep"); leg2->AddEntry(frame2->findObject("altModel"), "Effective Operator + Background", "lep"); frame2->SetTitle(""); frame2->GetXaxis()->SetTitle("M_{WW} (GeV)"); frame2->GetYaxis()->SetTitle(""); frame2->Draw(); leg2->Draw(); canvas2->Write(); outputFile->Close(); RooArgSet poi(*mu); RooArgSet *nullParams = (RooArgSet*) poi.snapshot(); nullParams->setRealValue("mu", 0.0); RooStats::ProfileLikelihoodCalculator plc(*generatedData, *model, poi, 0.05, nullParams); RooStats::HypoTestResult* htr = plc.GetHypoTest(); std::cerr << "P Value = " << htr->NullPValue() << "\n"; return htr->Significance(); }
void fitWe(const TString outputDir="test", // output directory const Double_t lumi=18.7, // integrated luminosity (/fb) const Int_t Ecm=8, // center-of-mass energy const Int_t doPU=1 // option for PU-reweighting ) { gBenchmark->Start("fitWe"); //-------------------------------------------------------------------------------------------------------------- // Settings //============================================================================================================== // MET histogram binning and range const Int_t NBINS = 50; const Double_t METMAX = 100; const Double_t PT_CUT = 25; const Double_t ETA_CUT = 2.5; // file format for output plots const TString format("png"); // file name with recoil correction TString recoilfname("../RecoilSyst/ZeeData/fits.root"); // file name(s) with PU weights TString pufname(""); if(doPU>0) { if(doPU==1) { pufname = "Utils/PileupReweighting.Summer11DYmm_To_Run2011A.root"; } else { cout << "Invalid option for PU re-weighting! Aborting..." << endl; assert(0); } } // // input ntuple file names // enum { eData, eWenu, eEWK }; // data type enum vector<TString> fnamev; vector<Int_t> typev; fnamev.push_back("../Selection/Wenu/ntuples/data_m23_select.root"); typev.push_back(eData); fnamev.push_back("../Selection/Wenu/ntuples/we_select.root"); typev.push_back(eWenu); fnamev.push_back("../Selection/Wenu/ntuples/ewk_select.root"); typev.push_back(eEWK); fnamev.push_back("../Selection/Wenu/ntuples/top_select.root"); typev.push_back(eEWK); //-------------------------------------------------------------------------------------------------------------- // Main analysis code //============================================================================================================== // Create output directory gSystem->mkdir(outputDir,kTRUE); CPlot::sOutDir = outputDir; // Get pile-up weights TFile *pufile = 0; TH1D *puWeights = 0; if(doPU>0) { pufile = new TFile(pufname); assert(pufile); puWeights = (TH1D*)pufile->Get("puWeights"); assert(puWeights); } // Access recoil corrections //RecoilCorrector recoilCorr(recoilfname); // // Declare MET histograms // TH1D *hDataMet = new TH1D("hDataMet", "",NBINS,0,METMAX); hDataMet->Sumw2(); TH1D *hDataMetm = new TH1D("hDataMetm","",NBINS,0,METMAX); hDataMetm->Sumw2(); TH1D *hDataMetp = new TH1D("hDataMetp","",NBINS,0,METMAX); hDataMetp->Sumw2(); TH1D *hWenuMet = new TH1D("hWenuMet", "",NBINS,0,METMAX); hWenuMet->Sumw2(); TH1D *hWenuMetp = new TH1D("hWenuMetp","",NBINS,0,METMAX); hWenuMetp->Sumw2(); TH1D *hWenuMetm = new TH1D("hWenuMetm","",NBINS,0,METMAX); hWenuMetm->Sumw2(); TH1D *hEWKMet = new TH1D("hEWKMet", "",NBINS,0,METMAX); hEWKMet->Sumw2(); TH1D *hEWKMetp = new TH1D("hEWKMetp", "",NBINS,0,METMAX); hEWKMetp->Sumw2(); TH1D *hEWKMetm = new TH1D("hEWKMetm", "",NBINS,0,METMAX); hEWKMetm->Sumw2(); // // Declare variables to read in ntuple // UInt_t runNum, lumiSec, evtNum; UInt_t npv, npu; Float_t genWPt, genWPhi; Float_t scale1fb; Float_t met, metPhi, sumEt, mt, u1, u2; Int_t q; LorentzVector *lep=0; LorentzVector *sc=0; TFile *infile=0; TTree *intree=0; // // Loop over files // for(UInt_t ifile=0; ifile<fnamev.size(); ifile++) { // Read input file and get the TTrees cout << "Processing " << fnamev[ifile] << "..." << endl; infile = new TFile(fnamev[ifile]); assert(infile); intree = (TTree*)infile->Get("Events"); assert(intree); intree->SetBranchAddress("runNum", &runNum); // event run number intree->SetBranchAddress("lumiSec", &lumiSec); // event lumi section intree->SetBranchAddress("evtNum", &evtNum); // event number intree->SetBranchAddress("npv", &npv); // number of primary vertices intree->SetBranchAddress("npu", &npu); // number of in-time PU events (MC) intree->SetBranchAddress("genVPt", &genWPt); // GEN W boson pT (signal MC) intree->SetBranchAddress("genVPhi", &genWPhi); // GEN W boson phi (signal MC) intree->SetBranchAddress("scale1fb", &scale1fb); // event weight per 1/fb (MC) intree->SetBranchAddress("met", &met); // MET intree->SetBranchAddress("metPhi", &metPhi); // phi(MET) intree->SetBranchAddress("sumEt", &sumEt); // Sum ET intree->SetBranchAddress("mt", &mt); // transverse mass intree->SetBranchAddress("u1", &u1); // parallel component of recoil intree->SetBranchAddress("u2", &u2); // perpendicular component of recoil intree->SetBranchAddress("q", &q); // lepton charge intree->SetBranchAddress("lep", &lep); // lepton 4-vector intree->SetBranchAddress("sc", &sc); // electron Supercluster 4-vector // // loop over events // for(UInt_t ientry=0; ientry<intree->GetEntries(); ientry++) { intree->GetEntry(ientry); if(mt< 40) continue; // LUCA ADD TLorentzVector muPosP, muNegP, JpsiP; muPosP.SetPtEtaPhiM(lep->Pt(),lep->Eta(),lep->Phi(),lep->M()); // always use the muon muNegP.SetPtEtaPhiM(met,0,metPhi,0); // always use the neutrino JpsiP = muPosP + muNegP; // if(JpsiP.Pt() < 15 // || JpsiP.Pt() > 25 ) continue; if(sc->Pt() < PT_CUT) continue; if(fabs(sc->Eta()) > ETA_CUT) continue; if(typev[ifile]==eData) { hDataMet->Fill(met); if(q>0) { hDataMetp->Fill(met); } else { hDataMetm->Fill(met); } } else { Double_t weight = 1; weight *= scale1fb*lumi; if(puWeights) weight *= puWeights->GetBinContent(npu+1); if(typev[ifile]==eWenu) { Double_t corrMet=met, corrMetPhi=metPhi; // apply recoil corrections to W MC //recoilCorr.Correct(corrMet,corrMetPhi,genWPt,genWPhi,lep->Pt(),lep->Phi()); hWenuMet->Fill(corrMet,weight); if(q>0) { hWenuMetp->Fill(corrMet,weight); } else { hWenuMetm->Fill(corrMet,weight); } } if(typev[ifile]==eEWK) { hEWKMet->Fill(met,weight); if(q>0) { hEWKMetp->Fill(met,weight); } else { hEWKMetm->Fill(met,weight); } } } } } delete infile; infile=0, intree=0; // // Declare fit parameters for signal and background yields // Note: W signal and EWK+top PDFs are constrained to the ratio described in MC // RooRealVar nSig("nSig","nSig",0.7*(hDataMet->Integral()),0,hDataMet->Integral()); RooRealVar nQCD("nQCD","nQCD",0.3*(hDataMet->Integral()),0,hDataMet->Integral()); RooRealVar cewk("cewk","cewk",0.1,0,5) ; cewk.setVal(hEWKMet->Integral()/hWenuMet->Integral()); cewk.setConstant(kTRUE); RooFormulaVar nEWK("nEWK","nEWK","cewk*nSig",RooArgList(nSig,cewk)); RooRealVar nSigp("nSigp","nSigp",0.7*(hDataMetp->Integral()),0,hDataMetp->Integral()); RooRealVar nQCDp("nQCDp","nQCDp",0.3*(hDataMetp->Integral()),0,hDataMetp->Integral()); RooRealVar cewkp("cewkp","cewkp",0.1,0,5) ; cewkp.setVal(hEWKMetp->Integral()/hWenuMetp->Integral()); cewkp.setConstant(kTRUE); RooFormulaVar nEWKp("nEWKp","nEWKp","cewkp*nSigp",RooArgList(nSigp,cewkp)); RooRealVar nSigm("nSigm","nSigm",0.7*(hDataMetm->Integral()),0,hDataMetm->Integral()); RooRealVar nQCDm("nQCDm","nQCDm",0.3*(hDataMetm->Integral()),0,hDataMetm->Integral()); RooRealVar cewkm("cewkm","cewkm",0.1,0,5) ; cewkm.setVal(hEWKMetm->Integral()/hWenuMetm->Integral()); cewkm.setConstant(kTRUE); RooFormulaVar nEWKm("nEWKm","nEWKm","cewkm*nSigm",RooArgList(nSigm,cewkm)); // // Construct PDFs for fitting // RooRealVar pfmet("pfmet","pfmet",0,METMAX); pfmet.setBins(NBINS); // Signal PDFs RooDataHist wenuMet ("wenuMET", "wenuMET", RooArgSet(pfmet),hWenuMet); RooHistPdf pdfWe ("we", "we", pfmet,wenuMet, 1); RooDataHist wenuMetp("wenuMETp","wenuMETp",RooArgSet(pfmet),hWenuMetp); RooHistPdf pdfWep("wep","wep",pfmet,wenuMetp,1); RooDataHist wenuMetm("wenuMETm","wenuMETm",RooArgSet(pfmet),hWenuMetm); RooHistPdf pdfWem("wem","wem",pfmet,wenuMetm,1); // EWK+top PDFs RooDataHist ewkMet ("ewkMET", "ewkMET", RooArgSet(pfmet),hEWKMet); RooHistPdf pdfEWK ("ewk", "ewk", pfmet,ewkMet, 1); RooDataHist ewkMetp("ewkMETp","ewkMETp",RooArgSet(pfmet),hEWKMetp); RooHistPdf pdfEWKp("ewkp","ewkp",pfmet,ewkMetp,1); RooDataHist ewkMetm("ewkMETm","ewkMETm",RooArgSet(pfmet),hEWKMetm); RooHistPdf pdfEWKm("ewkm","ewkm",pfmet,ewkMetm,1); // QCD Pdfs CPepeModel1 qcd("qcd",pfmet); CPepeModel1 qcdp("qcdp",pfmet); CPepeModel1 qcdm("qcdm",pfmet); // Signal + Background PDFs RooAddPdf pdfMet ("pdfMet", "pdfMet", RooArgList(pdfWe,pdfEWK,*(qcd.model)), RooArgList(nSig,nEWK,nQCD)); RooAddPdf pdfMetp("pdfMetp","pdfMetp",RooArgList(pdfWep,pdfEWKp,*(qcdp.model)),RooArgList(nSigp,nEWKp,nQCDp)); RooAddPdf pdfMetm("pdfMetm","pdfMetm",RooArgList(pdfWem,pdfEWKm,*(qcdm.model)),RooArgList(nSigm,nEWKm,nQCDm)); // // Perform fits // RooDataHist dataMet("dataMet", "dataMet", RooArgSet(pfmet),hDataMet); RooFitResult *fitRes = pdfMet.fitTo(dataMet,Extended(),Minos(kTRUE),Save(kTRUE)); RooDataHist dataMetp("dataMetp","dataMetp",RooArgSet(pfmet),hDataMetp); RooFitResult *fitResp = pdfMetp.fitTo(dataMetp,Extended(),Minos(kTRUE),Save(kTRUE)); RooDataHist dataMetm("dataMetm","dataMetm",RooArgSet(pfmet),hDataMetm); RooFitResult *fitResm = pdfMetm.fitTo(dataMetm,Extended(),Minos(kTRUE),Save(kTRUE)); // // Use histogram version of fitted PDFs to make ratio plots // (Will also use PDF histograms later for Chi^2 and KS tests) // TH1D *hPdfMet = (TH1D*)(pdfMet.createHistogram("hPdfMet", pfmet)); hPdfMet->Scale((nSig.getVal()+nEWK.getVal()+nQCD.getVal())/hPdfMet->Integral()); TH1D *hMetDiff = makeDiffHist(hDataMet,hPdfMet,"hMetDiff"); hMetDiff->SetMarkerStyle(kFullCircle); hMetDiff->SetMarkerSize(0.9); TH1D *hPdfMetp = (TH1D*)(pdfMetp.createHistogram("hPdfMetp", pfmet)); hPdfMetp->Scale((nSigp.getVal()+nEWKp.getVal()+nQCDp.getVal())/hPdfMetp->Integral()); TH1D *hMetpDiff = makeDiffHist(hDataMetp,hPdfMetp,"hMetpDiff"); hMetpDiff->SetMarkerStyle(kFullCircle); hMetpDiff->SetMarkerSize(0.9); TH1D *hPdfMetm = (TH1D*)(pdfMetm.createHistogram("hPdfMetm", pfmet)); hPdfMetm->Scale((nSigm.getVal()+nEWKm.getVal()+nQCDm.getVal())/hPdfMetm->Integral()); TH1D *hMetmDiff = makeDiffHist(hDataMetm,hPdfMetm,"hMetmDiff"); hMetmDiff->SetMarkerStyle(kFullCircle); hMetmDiff->SetMarkerSize(0.9); //-------------------------------------------------------------------------------------------------------------- // Make plots //============================================================================================================== TCanvas *c = MakeCanvas("c","c",800,800); c->Divide(1,2,0,0); c->cd(1)->SetPad(0,0.3,1.0,1.0); c->cd(1)->SetTopMargin(0.1); c->cd(1)->SetBottomMargin(0.01); c->cd(1)->SetLeftMargin(0.18); c->cd(1)->SetRightMargin(0.07); c->cd(1)->SetTickx(1); c->cd(1)->SetTicky(1); c->cd(2)->SetPad(0,0,1.0,0.3); c->cd(2)->SetTopMargin(0.05); c->cd(2)->SetBottomMargin(0.45); c->cd(2)->SetLeftMargin(0.18); c->cd(2)->SetRightMargin(0.07); c->cd(2)->SetTickx(1); c->cd(2)->SetTicky(1); gStyle->SetTitleOffset(1.400,"Y"); char ylabel[100]; // string buffer for y-axis label // label for lumi char lumitext[100]; if(lumi<0.1) sprintf(lumitext,"%.1f pb^{-1} at #sqrt{s} = %i TeV",lumi*1000.,Ecm); else sprintf(lumitext,"%.2f fb^{-1} at #sqrt{s} = %i TeV",lumi,Ecm); // plot colors Int_t linecolorW = kOrange-3; Int_t fillcolorW = kOrange-2; Int_t linecolorEWK = kOrange+10; Int_t fillcolorEWK = kOrange+7; Int_t linecolorQCD = kViolet+2; Int_t fillcolorQCD = kViolet-5; Int_t ratioColor = kGray+2; // // Dummy histograms for TLegend // (I can't figure out how to properly pass RooFit objects...) // TH1D *hDummyData = new TH1D("hDummyData","",0,0,10); hDummyData->SetMarkerStyle(kFullCircle); hDummyData->SetMarkerSize(0.9); TH1D *hDummyW = new TH1D("hDummyW","",0,0,10); hDummyW->SetLineColor(linecolorW); hDummyW->SetFillColor(fillcolorW); hDummyW->SetFillStyle(1001); TH1D *hDummyEWK = new TH1D("hDummyEWK","",0,0,10); hDummyEWK->SetLineColor(linecolorEWK); hDummyEWK->SetFillColor(fillcolorEWK); hDummyEWK->SetFillStyle(1001); TH1D *hDummyQCD = new TH1D("hDummyQCD","",0,0,10); hDummyQCD->SetLineColor(linecolorQCD); hDummyQCD->SetFillColor(fillcolorQCD); hDummyQCD->SetFillStyle(1001); // // W MET plot // RooPlot *weframe = pfmet.frame(Bins(NBINS)); dataMet.plotOn(weframe,MarkerStyle(kFullCircle),MarkerSize(0.9),DrawOption("ZP")); pdfMet.plotOn(weframe,FillColor(fillcolorW),DrawOption("F")); pdfMet.plotOn(weframe,LineColor(linecolorW)); pdfMet.plotOn(weframe,Components(RooArgSet(pdfEWK,*(qcd.model))),FillColor(fillcolorEWK),DrawOption("F")); pdfMet.plotOn(weframe,Components(RooArgSet(pdfEWK,*(qcd.model))),LineColor(linecolorEWK)); pdfMet.plotOn(weframe,Components(RooArgSet(*(qcd.model))),FillColor(fillcolorQCD),DrawOption("F")); pdfMet.plotOn(weframe,Components(RooArgSet(*(qcd.model))),LineColor(linecolorQCD)); pdfMet.plotOn(weframe,Components(RooArgSet(pdfWe)),LineColor(linecolorW),LineStyle(2)); dataMet.plotOn(weframe,MarkerStyle(kFullCircle),MarkerSize(0.9),DrawOption("ZP")); sprintf(ylabel,"Events / %.1f GeV",hDataMet->GetBinWidth(1)); CPlot plotMet("fitmet",weframe,"","",ylabel); plotMet.SetLegend(0.68,0.57,0.93,0.77); plotMet.GetLegend()->AddEntry(hDummyData,"data","PL"); plotMet.GetLegend()->AddEntry(hDummyW,"W#rightarrowe#nu","F"); plotMet.GetLegend()->AddEntry(hDummyEWK,"EWK+t#bar{t}","F"); plotMet.GetLegend()->AddEntry(hDummyQCD,"QCD","F"); plotMet.AddTextBox(lumitext,0.55,0.80,0.90,0.86,0); plotMet.AddTextBox("CMS Preliminary",0.63,0.92,0.95,0.99,0); plotMet.SetYRange(0.1,1.1*(hDataMet->GetMaximum())); // plotMet.Draw(c,kFALSE,format,1); plotMet.Draw(c,kTRUE,format,1); CPlot plotMetDiff("fitmet","","#slash{E}_{T} [GeV]","#chi"); plotMetDiff.AddHist1D(hMetDiff,"EX0",ratioColor); plotMetDiff.SetYRange(-8,8); plotMetDiff.AddLine(0, 0,METMAX, 0,kBlack,1); plotMetDiff.AddLine(0, 5,METMAX, 5,kBlack,3); plotMetDiff.AddLine(0,-5,METMAX,-5,kBlack,3); plotMetDiff.Draw(c,kTRUE,format,2); plotMet.SetName("fitmetlog"); plotMet.SetLogy(); plotMet.SetYRange(1e-3*(hDataMet->GetMaximum()),10*(hDataMet->GetMaximum())); plotMet.Draw(c,kTRUE,format,1); // // W+ MET plot // RooPlot *wepframe = pfmet.frame(Bins(NBINS)); dataMetp.plotOn(wepframe,MarkerStyle(kFullCircle),MarkerSize(0.9),DrawOption("ZP")); pdfMetp.plotOn(wepframe,FillColor(fillcolorW),DrawOption("F")); pdfMetp.plotOn(wepframe,LineColor(linecolorW)); pdfMetp.plotOn(wepframe,Components(RooArgSet(pdfEWKp,*(qcdp.model))),FillColor(fillcolorEWK),DrawOption("F")); pdfMetp.plotOn(wepframe,Components(RooArgSet(pdfEWKp,*(qcdp.model))),LineColor(linecolorEWK)); pdfMetp.plotOn(wepframe,Components(RooArgSet(*(qcdp.model))),FillColor(fillcolorQCD),DrawOption("F")); pdfMetp.plotOn(wepframe,Components(RooArgSet(*(qcdp.model))),LineColor(linecolorQCD)); pdfMetp.plotOn(wepframe,Components(RooArgSet(pdfWep)),LineColor(linecolorW),LineStyle(2)); dataMetp.plotOn(wepframe,MarkerStyle(kFullCircle),MarkerSize(0.9),DrawOption("ZP")); sprintf(ylabel,"Events / %.1f GeV",hDataMetp->GetBinWidth(1)); CPlot plotMetp("fitmetp",wepframe,"","",ylabel); plotMetp.SetLegend(0.68,0.57,0.93,0.77); plotMetp.GetLegend()->AddEntry(hDummyData,"data","PL"); plotMetp.GetLegend()->AddEntry(hDummyW,"W^{+}#rightarrowe^{+}#nu","F"); plotMetp.GetLegend()->AddEntry(hDummyEWK,"EWK+t#bar{t}","F"); plotMetp.GetLegend()->AddEntry(hDummyQCD,"QCD","F"); plotMetp.AddTextBox(lumitext,0.55,0.80,0.90,0.86,0); plotMetp.AddTextBox("CMS Preliminary",0.63,0.92,0.95,0.99,0); plotMetp.SetYRange(0.1,1.1*(hDataMetp->GetMaximum())); plotMetp.Draw(c,kFALSE,format,1); CPlot plotMetpDiff("fitmetp","","#slash{E}_{T} [GeV]","#chi"); plotMetpDiff.AddHist1D(hMetpDiff,"EX0",ratioColor); plotMetpDiff.SetYRange(-8,8); plotMetpDiff.AddLine(0, 0,METMAX, 0,kBlack,1); plotMetpDiff.AddLine(0, 5,METMAX, 5,kBlack,3); plotMetpDiff.AddLine(0,-5,METMAX,-5,kBlack,3); plotMetpDiff.Draw(c,kTRUE,format,2); plotMetp.SetName("fitmetplog"); plotMetp.SetLogy(); plotMetp.SetYRange(1e-3*(hDataMetp->GetMaximum()),10*(hDataMetp->GetMaximum())); plotMetp.Draw(c,kTRUE,format,1); // // W- MET plot // RooPlot *wemframe = pfmet.frame(Bins(NBINS)); dataMetm.plotOn(wemframe,MarkerStyle(kFullCircle),MarkerSize(0.9),DrawOption("ZP")); pdfMetm.plotOn(wemframe,FillColor(fillcolorW),DrawOption("F")); pdfMetm.plotOn(wemframe,LineColor(linecolorW)); pdfMetm.plotOn(wemframe,Components(RooArgSet(pdfEWKm,*(qcdm.model))),FillColor(fillcolorEWK),DrawOption("F")); pdfMetm.plotOn(wemframe,Components(RooArgSet(pdfEWKm,*(qcdm.model))),LineColor(linecolorEWK)); pdfMetm.plotOn(wemframe,Components(RooArgSet(*(qcdm.model))),FillColor(fillcolorQCD),DrawOption("F")); pdfMetm.plotOn(wemframe,Components(RooArgSet(*(qcdm.model))),LineColor(linecolorQCD)); pdfMetm.plotOn(wemframe,Components(RooArgSet(pdfWem)),LineColor(linecolorW),LineStyle(2)); dataMetm.plotOn(wemframe,MarkerStyle(kFullCircle),MarkerSize(0.9),DrawOption("ZP")); sprintf(ylabel,"Events / %.1f GeV",hDataMetm->GetBinWidth(1)); CPlot plotMetm("fitmetm",wemframe,"","",ylabel); plotMetm.SetLegend(0.68,0.57,0.93,0.77); plotMetm.GetLegend()->AddEntry(hDummyData,"data","PL"); plotMetm.GetLegend()->AddEntry(hDummyW,"W^{-}#rightarrowe^{-}#bar{#nu}","F"); plotMetm.GetLegend()->AddEntry(hDummyEWK,"EWK+t#bar{t}","F"); plotMetm.GetLegend()->AddEntry(hDummyQCD,"QCD","F"); plotMetm.AddTextBox(lumitext,0.55,0.80,0.90,0.86,0); plotMetm.AddTextBox("CMS Preliminary",0.63,0.92,0.95,0.99,0); plotMetm.SetYRange(0.1,1.1*(hDataMetm->GetMaximum())); plotMetm.Draw(c,kFALSE,format,1); CPlot plotMetmDiff("fitmetm","","#slash{E}_{T} [GeV]","#chi"); plotMetmDiff.AddHist1D(hMetmDiff,"EX0",ratioColor); plotMetmDiff.SetYRange(-8,8); plotMetmDiff.AddLine(0, 0,METMAX, 0,kBlack,1); plotMetmDiff.AddLine(0, 5,METMAX, 5,kBlack,3); plotMetmDiff.AddLine(0,-5,METMAX,-5,kBlack,3); plotMetmDiff.Draw(c,kTRUE,format,2); plotMetm.SetName("fitmetmlog"); plotMetm.SetLogy(); plotMetm.SetYRange(1e-3*(hDataMetm->GetMaximum()),10*(hDataMetm->GetMaximum())); plotMetm.Draw(c,kTRUE,format,1); //-------------------------------------------------------------------------------------------------------------- // Output //============================================================================================================== cout << "*" << endl; cout << "* SUMMARY" << endl; cout << "*--------------------------------------------------" << endl; // // Write fit results // ofstream txtfile; char txtfname[100]; ios_base::fmtflags flags; Double_t chi2prob, chi2ndf; Double_t ksprob, ksprobpe; chi2prob = hDataMet->Chi2Test(hPdfMet,"PUW"); chi2ndf = hDataMet->Chi2Test(hPdfMet,"CHI2/NDFUW"); ksprob = hDataMet->KolmogorovTest(hPdfMet); ksprobpe = hDataMet->KolmogorovTest(hPdfMet,"DX"); sprintf(txtfname,"%s/fitresWe.txt",CPlot::sOutDir.Data()); txtfile.open(txtfname); assert(txtfile.is_open()); flags = txtfile.flags(); txtfile << setprecision(10); txtfile << " *** Yields *** " << endl; txtfile << "Selected: " << hDataMet->Integral() << endl; txtfile << " Signal: " << nSig.getVal() << " +/- " << nSig.getPropagatedError(*fitRes) << endl; txtfile << " QCD: " << nQCD.getVal() << " +/- " << nQCD.getPropagatedError(*fitRes) << endl; txtfile << " Other: " << nEWK.getVal() << " +/- " << nEWK.getPropagatedError(*fitRes) << endl; txtfile << endl; txtfile.flags(flags); fitRes->printStream(txtfile,RooPrintable::kValue,RooPrintable::kVerbose); txtfile << endl; printCorrelations(txtfile, fitRes); txtfile << endl; printChi2AndKSResults(txtfile, chi2prob, chi2ndf, ksprob, ksprobpe); txtfile.close(); chi2prob = hDataMetp->Chi2Test(hPdfMetp,"PUW"); chi2ndf = hDataMetp->Chi2Test(hPdfMetp,"CHI2/NDFUW"); ksprob = hDataMetp->KolmogorovTest(hPdfMetp); ksprobpe = hDataMetp->KolmogorovTest(hPdfMetp,"DX"); sprintf(txtfname,"%s/fitresWep.txt",CPlot::sOutDir.Data()); txtfile.open(txtfname); assert(txtfile.is_open()); flags = txtfile.flags(); txtfile << setprecision(10); txtfile << " *** Yields *** " << endl; txtfile << "Selected: " << hDataMetp->Integral() << endl; txtfile << " Signal: " << nSigp.getVal() << " +/- " << nSigp.getPropagatedError(*fitResp) << endl; txtfile << " QCD: " << nQCDp.getVal() << " +/- " << nQCDp.getPropagatedError(*fitResp) << endl; txtfile << " Other: " << nEWKp.getVal() << " +/- " << nEWKp.getPropagatedError(*fitResp) << endl; txtfile << endl; txtfile.flags(flags); fitResp->printStream(txtfile,RooPrintable::kValue,RooPrintable::kVerbose); txtfile << endl; printCorrelations(txtfile, fitResp); txtfile << endl; printChi2AndKSResults(txtfile, chi2prob, chi2ndf, ksprob, ksprobpe); txtfile.close(); chi2prob = hDataMetm->Chi2Test(hPdfMetm,"PUW"); chi2ndf = hDataMetm->Chi2Test(hPdfMetm,"CHI2/NDFUW"); ksprob = hDataMetm->KolmogorovTest(hPdfMetm); ksprobpe = hDataMetm->KolmogorovTest(hPdfMetm,"DX"); sprintf(txtfname,"%s/fitresWem.txt",CPlot::sOutDir.Data()); txtfile.open(txtfname); assert(txtfile.is_open()); flags = txtfile.flags(); txtfile << setprecision(10); txtfile << " *** Yields *** " << endl; txtfile << "Selected: " << hDataMetm->Integral() << endl; txtfile << " Signal: " << nSigm.getVal() << " +/- " << nSigm.getPropagatedError(*fitResm) << endl; txtfile << " QCD: " << nQCDm.getVal() << " +/- " << nQCDm.getPropagatedError(*fitResm) << endl; txtfile << " Other: " << nEWKm.getVal() << " +/- " << nEWKm.getPropagatedError(*fitResm) << endl; txtfile << endl; txtfile.flags(flags); fitResm->printStream(txtfile,RooPrintable::kValue,RooPrintable::kVerbose); txtfile << endl; printCorrelations(txtfile, fitResm); txtfile << endl; printChi2AndKSResults(txtfile, chi2prob, chi2ndf, ksprob, ksprobpe); txtfile.close(); makeHTML(outputDir); cout << endl; cout << " <> Output saved in " << outputDir << "/" << endl; cout << endl; gBenchmark->Show("fitWe"); }
void drawPlot(string workspaceFilename, string inputFilename, string outFilename, Int_t EnergyType, Int_t CategoryBin, double minMass, double maxMass, double mean_bw, double gamma_bw, double cutoff_cb, double power_cb, const char* plotOpt, const int nbins) { TFile *workspaceFile = new TFile(workspaceFilename.c_str(), "read"); RooWorkspace* w = (RooWorkspace*)workspaceFile->Get("ZeeMassScaleAndResolutionFit"); //Create Data Set RooRealVar *mass = (RooRealVar*)w->var("mass"); // Reading everything from root tree instead citana::ZeeEventTree *zeeTree = new citana::ZeeEventTree(); zeeTree->LoadTree(inputFilename.c_str(), citana::ZeeEventTree::kCITZeeEvent); RooArgSet zMassArgSet(*mass); RooDataSet* data = new RooDataSet("data", "ntuple parameters", zMassArgSet); for (int i = 0; i < zeeTree->tree_->GetEntries(); i++) { zeeTree->tree_->GetEntry(i); //************************************************************************* //Electron Selection //************************************************************************* if (!(zeeTree->fEle1PassHZZICHEP2012 == 1 && zeeTree->fEle2PassHZZICHEP2012 == 1)) continue; //************************************************************************* //Compute electron four vector; //************************************************************************* double ele1pt = zeeTree->fEle1Pt; double ele2pt = zeeTree->fEle2Pt; if (EnergyType == 1) { ele1pt = zeeTree->fEle1EnergyRegressionWithTrkVarTwoPtBins / TMath::CosH(zeeTree->fEle1Eta); ele2pt = zeeTree->fEle2EnergyRegressionWithTrkVarTwoPtBins / TMath::CosH(zeeTree->fEle2Eta); } else if (EnergyType == 2) { ele1pt = zeeTree->fEle1EnergyRegressionWithTrkVar / TMath::CosH(zeeTree->fEle1Eta); ele2pt = zeeTree->fEle2EnergyRegressionWithTrkVar / TMath::CosH(zeeTree->fEle2Eta); } else if (EnergyType == 3) { ele1pt = zeeTree->fEle1EnergyRegressionNoTrkVarTwoPtBins / TMath::CosH(zeeTree->fEle1Eta); ele2pt = zeeTree->fEle2EnergyRegressionNoTrkVarTwoPtBins / TMath::CosH(zeeTree->fEle2Eta); } else if (EnergyType == 4) { ele1pt = zeeTree->fEle1EnergyRegressionNoTrkVar / TMath::CosH(zeeTree->fEle1Eta); ele2pt = zeeTree->fEle2EnergyRegressionNoTrkVar / TMath::CosH(zeeTree->fEle2Eta); } TLorentzVector ele1FourVector; ele1FourVector.SetPtEtaPhiM(ele1pt, zeeTree->fEle1Eta, zeeTree->fEle1Phi, ELECTRONMASS); TLorentzVector ele2FourVector; ele2FourVector.SetPtEtaPhiM(ele2pt, zeeTree->fEle2Eta, zeeTree->fEle2Phi, ELECTRONMASS); //************************************************************************* //pt and eta cuts on electron //************************************************************************* if (! (ele1pt > 7 && ele2pt > 7 && fabs( zeeTree->fEle1Eta) < 2.5 && fabs( zeeTree->fEle2Eta) < 2.5 )) continue; //************************************************************************* //pt bins and eta bins //************************************************************************* Int_t Ele1PtBin = -1; Int_t Ele1EtaBin = -1; Int_t Ele2PtBin = -1; Int_t Ele2EtaBin = -1; if (ele1pt > 10 && ele1pt < 20) Ele1PtBin = 0; else if (ele1pt < 30) Ele1PtBin = 1; else if (ele1pt < 40) Ele1PtBin = 2; else Ele1PtBin = 3; if (ele2pt > 10 && ele2pt < 20) Ele2PtBin = 0; else if (ele2pt < 30) Ele2PtBin = 1; else if (ele2pt < 40) Ele2PtBin = 2; else Ele2PtBin = 3; if (fabs(zeeTree->fEle1SCEta) < 1.0) Ele1EtaBin = 0; else if (fabs(zeeTree->fEle1SCEta) < 1.479) Ele1EtaBin = 1; else Ele1EtaBin = 2; if (fabs(zeeTree->fEle2SCEta) < 1.0) Ele2EtaBin = 0; else if (fabs(zeeTree->fEle2SCEta) < 1.479) Ele2EtaBin = 1; else Ele2EtaBin = 2; if (CategoryBin == 0) { if (!(Ele1EtaBin == 0 && Ele2EtaBin == 0)) continue; } else if (CategoryBin == 1) { if (!(Ele1EtaBin == 1 && Ele2EtaBin == 1)) continue; } else if (CategoryBin == 2) { if (!(Ele1EtaBin == 2 && Ele2EtaBin == 2)) continue; } //************************************************************************* // restrict range of mass //************************************************************************* double zMass = (ele1FourVector+ele2FourVector).M(); if (zMass < minMass || zMass > maxMass) continue; //************************************************************************* //set mass variable //************************************************************************* zMassArgSet.setRealValue("mass", zMass); data->add(zMassArgSet); } cout << "dataset size: " << data->numEntries() << endl; RooRealVar *cbBias = (RooRealVar*)w->var("#Deltam_{CB}"); RooRealVar *cbSigma = (RooRealVar*)w->var("sigma_{CB}"); RooRealVar *cbCut = (RooRealVar*)w->var("a_{CB}"); RooRealVar *cbPower = (RooRealVar*)w->var("n_{CB}"); // // Now if it's a restricted fit, fix values of cbCut and cbPower to MC values. // if (isRestricted) { // cbCut.setConstant(kTRUE); // cbPower.setConstant(kTRUE); // } // Mass model for signal electrons p.d.f. RooAddPdf *model = (RooAddPdf*)w->pdf("model"); TCanvas* c = new TCanvas("c","c", 0,0,800,600); //========================== Plotting ============================ //Create a frame RooPlot* plot = mass->frame(Range(minMass,maxMass),Bins(nbins)); // Add data and model to canvas plot->SetTitle(""); plot->GetYaxis()->SetTitleOffset(1.4); plot->GetXaxis()->SetTitle("m_{ee} (GeV/c^{2})"); data->plotOn(plot); model->plotOn(plot); // model->paramOn(plot, Format(plotOpt, AutoPrecision(1)), Parameters(RooArgSet(*cbBias, *cbSigma, *cbCut, *cbPower)), Layout(0.60,0.90,0.90)); model->paramOn(plot, Format(plotOpt, AutoPrecision(1)), Parameters(RooArgSet(*cbBias, *cbSigma, *cbCut, *cbPower)), Layout(0.12,0.38,0.60)); plot->getAttText()->SetTextSize(.025); plot->Draw(); // Print Fit Values TLatex *tex = new TLatex(); tex->SetNDC(); tex->SetTextSize(.04); tex->SetTextFont(2); tex->DrawLatex(0.195,0.775, "Run 2012A/B"); tex->Draw(); // tex->SetTextSize(0.022); // tex->DrawLatex(0.195, 0.75, "Z #rightarrow ee^{+}"); // tex->SetTextSize(0.024); // tex->DrawLatex(0.645, 0.59, Form("BW Mean = %.2f GeV/c^{2}", bwMean.getVal())); // tex->DrawLatex(0.645, 0.54, Form("BW #sigma = %.2f GeV/c^{2}", bwWidth.getVal())); c->Update(); c->SaveAs((outFilename + ".gif").c_str()); }
void Fitter::finalModel(){ // -- Save final model // final model uses splines to get the values of the multigaussians // it will also include nuisances variables if necessary // for( int cat=0;cat<int(inputMasks.size()) ;++cat) { RooArgList *coeffs = new RooArgList(); RooArgList *pdfs = new RooArgList(); if(nBernstein >0 ) { RooArgList *pars=new RooArgList(); for(int b=0;b<nBernstein; b++) { RooAbsReal *p = splines_ [ Form("spline_cat%d_par%d_bern",cat,b) ] ; if (p == NULL ) cout<<"[Fitter]::[finalModel]::[ERROR] bern parameter"<<b<<"for cat"<<cat<<"is NULL "<<endl; pars -> add( *p ); } RooAbsPdf* pdf; if (nBernstein==1) pdf=new RooBernsteinFast<1>(Form("bern_%d",nBernstein), Form("bern_%d",nBernstein), *x_, *pars); if (nBernstein==2) pdf=new RooBernsteinFast<2>(Form("bern_%d",nBernstein), Form("bern_%d",nBernstein), *x_, *pars); if (nBernstein==3) pdf=new RooBernsteinFast<3>(Form("bern_%d",nBernstein), Form("bern_%d",nBernstein), *x_, *pars); if (nBernstein==4) pdf=new RooBernsteinFast<4>(Form("bern_%d",nBernstein), Form("bern_%d",nBernstein), *x_, *pars); if (nBernstein==5) pdf=new RooBernsteinFast<5>(Form("bern_%d",nBernstein), Form("bern_%d",nBernstein), *x_, *pars); if (nBernstein==6) pdf=new RooBernsteinFast<6>(Form("bern_%d",nBernstein), Form("bern_%d",nBernstein), *x_, *pars); if (nBernstein==7) pdf=new RooBernsteinFast<7>(Form("bern_%d",nBernstein), Form("bern_%d",nBernstein), *x_, *pars); pdfs ->add( *pdf ); if (nGaussians >0 ) coeffs -> add( *splines_[Form("spline_cat%d_bern_frac",cat)] ); } for( int i=0;i< nGaussians ;++i) { RooAbsReal *m = splines_[ Form("spline_cat%d_g%d_mean",cat,i) ] ; RooAbsReal *s = splines_[ Form("spline_cat%d_g%d_sigma",cat,i) ] ; if( m== NULL ) cout<<"[Fitter]::[finalModel]::[ERROR] mean spline is NULL"<< Form("spline_cat%d_g%d_mean",cat,i)<<endl; if( s== NULL ) cout<<"[Fitter]::[finalModel]::[ERROR] sigma spline is NULL"<< Form("spline_cat%d_g%d_sigma",cat,i)<<endl; if (m== NULL or s==NULL) for(auto& p: splines_) cout<<"[Fitter]::[finalModel]::[DEBUG] splines_["<<p.first<<"] = "<<p.second<<endl; RooGaussian *gaus = new RooGaussian(Form("gaus_g%d",i),Form("gaus_g%d",i),*x_, *m, *s); pdfs -> add( *gaus ); if (i != nGaussians-1) // sum to 1 { RooAbsReal *f = splines_ [ Form("spline_cat%d_g%d_frac",cat,i) ]; coeffs -> add( *f ) ; } } string name = Form("pdf_sigmodel_cat%d",cat); // ------------------------------------------------------------------------------\/recursive RooAddPdf *sigModel = new RooAddPdf(name.c_str(),name.c_str(),*pdfs,*coeffs,true); w_ -> import( *sigModel ); // -- Plot if (plot ) { TCanvas *c = new TCanvas(); RooPlot *p = x_ -> frame(); for(float mh=200;mh<1000;mh+= 50) { mh_ -> setVal(mh); sigModel->plotOn(p); } p -> Draw(); c -> SaveAs( Form("%s/interpolation_cat%d.pdf",plotDir.c_str(),cat) ); c -> SaveAs( Form("%s/interpolation_cat%d.png",plotDir.c_str(),cat) ); delete p; delete c; } // end plot } //end cat }
int fitHisto(int siteNum,string dataVer) { //===>initialize variable bool anaLiHe=true;//He8/Li9 bg int ADNumOfSite[3]={0}; int daqHistNum=5; if( dataVer.find("13")!=-1 || dataVer.find("14")!=-1 || dataVer.find("15")!=-1 || dataVer.find("16")!=-1) { ADNumOfSite[0]=2; ADNumOfSite[1]=2; ADNumOfSite[2]=4; daqHistNum=5; } else { if( dataVer.find("11")!=-1 || dataVer.find("12")!=-1 ) { ADNumOfSite[0]=2; ADNumOfSite[1]=1; ADNumOfSite[2]=3; daqHistNum=4; } } string site; if( siteNum==1 ) { site="EH1"; } else if(siteNum==2) { site="EH2"; }else if (siteNum==3) { site="EH3"; }else { site="EH1"; } //===>initialize histograms //livetime string runnum; TH1F* h[daqHistNum];//the fifth is for daqtime Double_t totalTime[5]={0.}; //Li9 He8 double n98total=0.; //double in98total=0.; double ifitn98total=0.; double n98Rate=0.; double in98Rate=0.; double tlivetime=0.; TH1F* showermuonNum[6]; TH1F* time2lastshowermuon[6]; TH1F* hh[6]; //===>get histograms from .root file for analyse string filename; filename=site; filename+="mergedHist_"; filename+=dataVer; filename+=".root"; TFile* f=new TFile(filename.c_str()); //livetime for( int i=0 ; i<daqHistNum ; i++ ) { stringstream hname; if( i==daqHistNum-1 ) { hname<<"LiveTime/DaqTime"; } else { hname<<"LiveTime/AD"; hname<<i+1; hname<<"LiveTime"; } h[i] = (TH1F*)f->Get(hname.str().c_str()); if( !(h[i]) ) { cout<<"Can not get Hist : "<<hname.str()<<" from "<<site<<"/"<<runnum<<" ."<<endl; //return true; continue; } } //Li9 He8 if(anaLiHe) { for( int i=0 ; i<6 ; i++ ) { TString hnameLi; hnameLi="lidj/showermuonNum"; hnameLi+=i+1; showermuonNum[i]=(TH1F*)f->Get(hnameLi); hnameLi="lidj/time2lastshowermuon"; hnameLi+=i+1; hnameLi+="4Li"; time2lastshowermuon[i]=(TH1F*)f->Get(hnameLi); } } //===>analyse TAxis *xaxis = h[0]->GetXaxis(); int binNum = xaxis->GetNbins(); int BinBound=h[0]->FindBin(1346428800);//2012.9.1 0:0:0 //livetime if( BinBound!=0 ) { if( site=="EH2" ) { for(int j=1 ; j<=BinBound ; j++ ) { h[1]->SetBinContent(j,0); } } if( site=="EH3" ) { for(int j=1 ; j<=BinBound ; j++ ) { h[3]->SetBinContent(j,0); } } } double totalTimeSpecical=0.; for( int j=BinBound ; j<=binNum ; j++ ) { totalTimeSpecical+=h[4]->GetBinContent(j); } for( int i=0 ; i<5 ; i++ ) { totalTime[i]=0.; for( int j=1 ; j<=binNum ; j++ ) { totalTime[i]+=h[i]->GetBinContent(j); } } double totalDaqtime=0.; if( site=="EH2" ) { totalDaqtime=totalTime[4]+totalTimeSpecical; }else if( site=="EH3" ) { totalDaqtime=totalTime[4]*3+totalTimeSpecical; } else { totalDaqtime=totalTime[4]*2; } //Li He std::cout<<"begin to analyse Li "<<endl; if(anaLiHe) { int hnum=time2lastshowermuon[0]->FindBin(100); //std::cout<<"0.001 : "<<time2lastshowermuon[0]->FindBin(0.001)<<endl; //std::cout<<"100 : "<<time2lastshowermuon[0]->FindBin(100)<<endl; //std::cout<<"hnum : "<<hnum<<endl; for( int k=0 ; k<6 ; k++ ) { TString hhname="slice"; hhname+=k+1; hh[k]=new TH1F(hhname,"hh",hnum-2,0.001,100); for( int i=1 ; i<hnum-2 ; i++ ) { hh[k]->SetBinContent(i,time2lastshowermuon[k]->GetBinContent(i+1)); } hh[k]->SetOption("E1"); } double showerTh[7] = {0.02, 0.5, 1.5, 2.5, 3.5, 4.5, 5.0}; TH1F* LiResult[5]; LiResult[0]= new TH1F("LiResult", "All", 6, showerTh); LiResult[1]= new TH1F("LiResult", "AD1", 6, showerTh); LiResult[2]= new TH1F("LiResult", "AD2", 6, showerTh); LiResult[3]= new TH1F("LiResult", "AD3", 6, showerTh); LiResult[4]= new TH1F("LiResult", "AD4", 6, showerTh); double NumMuon[6]={0.}; double RateMuon[6]={0.}; double NumIbd[6]={0.}; RooRealVar x("x","x",0.001,40., "s"); RooRealVar tauLi9("tauLi9", "tauLi9", -0.257, "s"); RooRealVar tauHe8("tauHe8", "tauHe8", -0.172, "s"); RooRealVar rateMu("rateMu","rate of showermuon",-0.1,-10., 0.,"Hz"); RooRealVar Li9Frac("Li9Frac","Li9's Frac", 0.0);//R RooRealVar N98("N98","total number of Li9 and He8",500.,0.,1.e5); //RooRealVar N98("N98","total number of Li9 and He8",3e2, 1e1, 2.e5); RooFormulaVar lambdaLi9("lambdaLi9","lambdaLi9","1/@0 + @1",RooArgList(tauLi9, rateMu)); RooFormulaVar lambdaHe8("lambdaHe8","lambdaHe8","1/@0 + @1",RooArgList(tauHe8, rateMu)); RooFormulaVar coeLi9("coeLi9","coeLi9","@0 * @1 ",RooArgList(N98,Li9Frac)); RooFormulaVar coeHe8("coeHe8","coeHe8","@0 * ( 1 - @1 )",RooArgList(N98,Li9Frac)); RooRealVar NIbd("NIbd","number of background",3e2, 1e1, 2.e6); RooExponential expLi9("expLi9", "Li9 distribution", x, lambdaLi9); RooExponential expHe8("expHe8", "He8 distribution", x, lambdaHe8); double Ibdrate[3]={0.0076,0.0067,0.00082}; RooRealVar rateIbd("rateIbd","rateIbd",-Ibdrate[siteNum-1],-10,0.,"Hz"); RooFormulaVar lambdaIbd("lambdaIbd","lambdaIbd","@0 + @1",RooArgList(rateIbd, rateMu)); RooExponential expIbd("expIbd","Ibd distribution",x,rateMu); //RooExponential expIbd("expIbd","Ibd distribution",x,lambdaIbd); RooFitResult* fitres; RooAddPdf* sum; RooDataHist* data; RooPlot* mesframe[6]; double n98[41]={0.}; double in98[41]={0.}; double nIbd[41]={0.}; double inIbd[41]={0.}; double minNLL[41]={0.}; double rateMuValue[41]={0.}; double rateMuErr[41]={0.}; //double minNl[6]={0.}; int minindex[6]={0}; double n98fit[6]={0.}; double in98fit[6]={0.}; double rateMufit[6]={0.}; double binwidth=0.; TH1F* lh[5][6]; TString lname[5]={"","AD1","AD2","AD3","AD4"}; int lcolor[5]={4,3,2,6,5}; bool draw6slice=false; TCanvas* c; TString xTitle[6]={"slice 1 : 0.02~0.5GeV","slice 2 : 0.5~1.5GeV","slice 3 : 1.5~2.5GeV","slice 4 : 2.5~3.5GeV","slice 5 : 3.5~4.5GeV","slice 6 : >4.5GeV"}; if( draw6slice ) { c = new TCanvas("c","c",2000,800) ; c->Divide(3,2); gStyle->SetEndErrorSize(5.0); gStyle->SetMarkerSize(0.1); //gStyle->SetHistLineWidth(1); if( 0 ) { // it's strange ,if you can't draw following six figs in the big 3*2 pad,you can fist use these code,run once,don't exit the ROOT,then you can draw six figs!!! data = new RooDataHist("data", "data", x, time2lastshowermuon[0]); sum = new RooAddPdf("sum","sum",RooArgList(expLi9, expHe8, expIbd),RooArgList(coeLi9, coeHe8, NIbd)); RooPlot* mesframe = x.frame() ; data->plotOn(mesframe) ; c->cd(1); mesframe->Draw(); return true; } } for( int ihist=0 ; ihist<1 ; ihist++ ) { double minNl[6]={0.}; for( int j=0 ; j<6 ; j++ ) { std::cout<<"now is "<< j+1<<endl; NumIbd[j]=hh[j]->Integral(1,hh[j]->FindBin(40)); hh[j]->Rebin(100); data = new RooDataHist("data", "data", x, hh[j]); sum = new RooAddPdf("sum","sum",RooArgList(expLi9, expHe8, expIbd),RooArgList(coeLi9, coeHe8, NIbd)); for( int i=0 ; i<41 ; i++ ) { Li9Frac.setVal(i*0.025); fitres = sum->fitTo((*data),Save(),PrintLevel(-1),Extended(kTRUE)); //fitres->Print(); n98[i]=N98.getVal(0); in98[i]=N98.getError(); nIbd[i]=NIbd.getVal(0); inIbd[i]=NIbd.getError(); rateMuValue[i]=rateMu.getVal(0); rateMuErr[i]=rateMu.getError(); minNLL[i] = fitres->minNll(); if( minNLL[i]<minNl[j] ) { minNl[j]=minNLL[i]; minindex[j]=i; } } n98fit[j]=n98[minindex[j]]; in98fit[j]=in98[minindex[j]]; rateMufit[j]=rateMuValue[minindex[j]]; if( draw6slice ) { //for drawing fit figure Li9Frac.setVal(minindex[j]*0.025); fitres = sum->fitTo((*data),Save(),PrintLevel(-1),Extended(kTRUE)); //fitres->Print(); mesframe[j] = x.frame() ; data->plotOn(mesframe[j]) ; sum->plotOn(mesframe[j]); sum->plotOn(mesframe[j],Components(expIbd),LineStyle(kDashed),LineColor(kGreen)) ; sum->plotOn(mesframe[j],Components(RooArgSet(expLi9,expHe8)),LineStyle(kDashed),LineColor(kRed)) ; xTitle[j]+=" time since last muon (s)"; mesframe[j]->GetXaxis()->SetTitle(xTitle[j]); mesframe[j]->GetYaxis()->SetTitle("Entries"); c->cd(j+1); mesframe[j]->Draw(); //gPad->SetLogy(); } } n98total=(n98fit[0]+n98fit[1]+n98fit[2]+(n98fit[3]+n98fit[4]+n98fit[5])*exp(-1/0.257))/0.678; ifitn98total=sqrt(in98fit[0]*in98fit[0]+in98fit[1]*in98fit[1]+in98fit[2]*in98fit[2]+((in98fit[3]+in98fit[4]+in98fit[5])*exp(-1/0.257)*(in98fit[3]+in98fit[4]+in98fit[5])*exp(-1/0.257)))/0.678; if( ihist==0 ) { for( int i=0 ; i<ADNumOfSite[siteNum-1] ; i++ ) { tlivetime+=totalTime[i]; } }else { tlivetime=totalTime[ihist-1]; } n98Rate=n98total/(tlivetime/(24*3600)); in98Rate=sqrt((ifitn98total/(tlivetime/(24*3600)))*(ifitn98total/(tlivetime/(24*3600)))+(n98total/(tlivetime/(24*3600))/2)*(n98total/(tlivetime/(24*3600))/2)); for( int j=0 ; j<6 ; j++ ) { LiResult[ihist]->SetBinContent(j+1,n98fit[j]); LiResult[ihist]->SetBinError(j+1,in98fit[j]); for( int jbin=0 ; jbin<binNum ; jbin++ ) { NumMuon[j]+=showermuonNum[j]->GetBinContent(jbin); } RateMuon[j]=NumMuon[j]/totalDaqtime; //std::cout<<"RateMuon[j] : "<<RateMuon[j]<<endl; //std::cout<<"RateMuon0[j] : "<<RateMuon0[j]<<endl; std::cout<<" R "<<minindex[j]*0.025<<" n98["<<minindex[j]<<"] "<<n98fit[j]<<" in98["<<minindex[j]<<"] "<< in98fit[j]<<" fitRateMu["<<minindex[j]<<"] "<<rateMufit[j]<<" realRateMu "<<RateMuon[j]<<" NumTol "<<NumIbd[j]<<endl; } std::cout<<"n98Num : "<<n98total<<" +- "<<ifitn98total<<" Rate : "<<n98Rate<<" +- "<< in98Rate<<endl; } /* //TCanvas* c4 = new TCanvas("c4", "c4", 600, 400); //gStyle->SetEndErrorSize(0.0); LiResult[0]->SetMarkerStyle(20); LiResult[0]->SetMarkerColor(lcolor[0]); LiResult[0]->SetLineColor(lcolor[0]); LiResult[0]->SetMarkerSize(1.0); LiResult[0]->SetMinimum(0); LiResult[0]->SetMaximum(LiResult[0]->GetMaximum()*1.5); LiResult[0]->GetXaxis()->SetTitle("Muon visible energy (GeV)"); LiResult[0]->GetYaxis()->SetTitle("Fitted ^{9}Li events"); LiResult[0]->SetTitle(""); LiResult[0]->SetStats(kFALSE); LiResult[0]->Draw("EP"); TLegend *legend=new TLegend(.6,.65,.79,.89); TString legendLabel=dataVer+" "+site+" "+"All"; legend->AddEntry(LiResult[0],legendLabel,"lp"); for( int ihist=1 ; ihist<ADNumOfSite[siteNum-1]+1; ihist++ ) { LiResult[ihist]->SetMarkerStyle(20); LiResult[ihist]->SetMarkerColor(lcolor[ihist]); LiResult[ihist]->SetLineColor(lcolor[ihist]); LiResult[ihist]->SetMarkerSize(1.0); LiResult[ihist]->SetStats(kFALSE); LiResult[ihist]->Draw("EPsame"); legend->AddEntry(LiResult[ihist],lname[ihist],"lp"); } legend->SetFillColor(0); legend->Draw(); */ } //f->Close(); //===>print result std::cout<<""<<endl; std::cout<<site <<"'s infomation : "<<endl; std::cout<<""<<endl; for( int i=0 ; i<ADNumOfSite[siteNum-1] ; i++ ) { std::cout<<"Total AD"<<i+1<<"LiveTime : "<<totalTime[i]/(24*3600)<<endl; } std::cout<<"Total DaqTime : "<<totalTime[daqHistNum-1]/(24*3600)<<" day" <<endl; std::cout<<""<<endl; if(anaLiHe) { std::cout<<" "<<endl; /* std::cout<<"Li9/He8 "<<endl; std::cout<<"n98total : "<<n98total <<" +- "<<in98total <<" Rate:"<<n98total/totalTime[0]*24*3600 <<" +- "<<in98total/totalTime[0]*24*3600 <<endl; std::cout<<"n98total0(without rpc) : "<<n98total0 <<" +- "<<in98total0 <<" Rate:"<<n98total0/totalTime0[0]*24*3600 <<" +- "<<in98total0/totalTime0[0]*24*3600 <<endl; */ } //===>write into .root file string rootname=site; rootname+="FitResult_"+dataVer+".root"; TFile* file = new TFile(rootname.c_str(),"RECREATE"); file->cd(); for( int i=0 ; i<daqHistNum ; i++ ) { h[i]->Write(); } if( anaLiHe ) { //for( int i=0 ; i<ADNumOfSite[siteNum-1] ; i++ ) for( int i=0 ; i<6 ; i++ ) { hh[i]->Write(); } } file->Close(); f->Close(); return 0; }
void FitBias(TString CAT,TString CUT,float SIG,float BKG,int NTOYS) { gROOT->ForceStyle(); RooMsgService::instance().setSilentMode(kTRUE); RooMsgService::instance().setStreamStatus(0,kFALSE); RooMsgService::instance().setStreamStatus(1,kFALSE); // ----------------------------------------- TFile *fTemplates = TFile::Open("templates_"+CUT+"_"+CAT+"_workspace.root"); RooWorkspace *wTemplates = (RooWorkspace*)fTemplates->Get("w"); RooRealVar *x = (RooRealVar*)wTemplates->var("mTop"); RooAbsPdf *pdf_signal = (RooAbsPdf*)wTemplates->pdf("ttbar_pdf_Nominal"); RooAbsPdf *pdf_bkg = (RooAbsPdf*)wTemplates->pdf("qcdCor_pdf"); TRandom *rnd = new TRandom(); rnd->SetSeed(0); x->setBins(250); RooPlot *frame; TFile *outf; if (NTOYS > 1) { outf = TFile::Open("FitBiasToys_"+CUT+"_"+CAT+".root","RECREATE"); } float nSigInj,nBkgInj,nSigFit,nBkgFit,eSigFit,eBkgFit,nll; TTree *tr = new TTree("toys","toys"); tr->Branch("nSigInj",&nSigInj,"nSigInj/F"); tr->Branch("nSigFit",&nSigFit,"nSigFit/F"); tr->Branch("nBkgInj",&nBkgInj,"nBkgInj/F"); tr->Branch("nBkgFit",&nBkgFit,"nBkgFit/F"); tr->Branch("eSigFit",&eSigFit,"eSigFit/F"); tr->Branch("eBkgFit",&eBkgFit,"eBkgFit/F"); tr->Branch("nll" ,&nll ,"nll/F"); for(int itoy=0;itoy<NTOYS;itoy++) { // generate pseudodataset nSigInj = rnd->Poisson(SIG); nBkgInj = rnd->Poisson(BKG); RooRealVar *nSig = new RooRealVar("nSig","nSig",nSigInj); RooRealVar *nBkg = new RooRealVar("nBkg","nBkg",nBkgInj); RooAddPdf *model = new RooAddPdf("model","model",RooArgList(*pdf_signal,*pdf_bkg),RooArgList(*nSig,*nBkg)); RooDataSet *data = model->generate(*x,nSigInj+nBkgInj); RooDataHist *roohist = new RooDataHist("roohist","roohist",RooArgList(*x),*data); // build fit model RooRealVar *nFitSig = new RooRealVar("nFitSig","nFitSig",SIG,0,10*SIG); RooRealVar *nFitBkg = new RooRealVar("nFitBkg","nFitBkg",BKG,0,10*BKG); RooAddPdf *modelFit = new RooAddPdf("modelFit","modelFit",RooArgList(*pdf_signal,*pdf_bkg),RooArgList(*nFitSig,*nFitBkg)); // fit the pseudo dataset RooFitResult *res = modelFit->fitTo(*roohist,RooFit::Save(),RooFit::Extended(kTRUE)); //res->Print(); nSigFit = nFitSig->getVal(); nBkgFit = nFitBkg->getVal(); eSigFit = nFitSig->getError(); eBkgFit = nFitBkg->getError(); nll = res->minNll(); tr->Fill(); if (itoy % 100 == 0) { cout<<"Toy #"<<itoy<<": injected = "<<nSigInj<<", fitted = "<<nSigFit<<", error = "<<eSigFit<<endl; } if (NTOYS == 1) { frame = x->frame(); roohist->plotOn(frame); model->plotOn(frame); } } if (NTOYS == 1) { TCanvas *can = new TCanvas("Toy","Toy",900,600); frame->Draw(); } else { outf->cd(); tr->Write(); outf->Close(); fTemplates->Close(); } }
void fitTF1(TCanvas *canvas, TH1F h, double XMIN_, double XMAX_, double dX_, double params[], Color_t LC_=kBlack) { //double& FWHM_, double& x0_, double& x1_, double& x2_, double& y0_, double& y1_, double& INT_, double& YIELD_) { //TCanvas* fitTF1(TH1F h, double HSCALE_, double XMIN_, double XMAX_) { //TF1* fitTF1(TH1F h, double HSCALE_, double XMIN_, double XMAX_) { gROOT->ForceStyle(); RooMsgService::instance().setSilentMode(kTRUE); for(int i=0;i<2;i++) RooMsgService::instance().setStreamStatus(i,kFALSE); //TCanvas *canvas = new TCanvas(TString::Format("canvas_%s",h.GetName()),TString::Format("canvas_%s",h.GetName()),1800,1200); RooDataHist *RooHistFit = 0; RooAddPdf *model = 0; RooWorkspace w = RooWorkspace("w","workspace"); RooRealVar x("mbbReg","mbbReg",XMIN_,XMAX_); RooRealVar kJES("CMS_scale_j","CMS_scale_j",1,0.9,1.1); RooRealVar kJER("CMS_res_j","CMS_res_j",1,0.8,1.2); kJES.setConstant(kTRUE); kJER.setConstant(kTRUE); TString hname = h.GetName(); RooHistFit = new RooDataHist("fit_"+hname,"fit_"+hname,x,&h); RooRealVar YieldVBF = RooRealVar("yield_"+hname,"yield_"+hname,h.Integral()); RooRealVar m("mean_"+hname,"mean_"+hname,125,100,150); RooRealVar s("sigma_"+hname,"sigma_"+hname,12,3,30); RooFormulaVar mShift("mShift_"+hname,"@0*@1",RooArgList(m,kJES)); RooFormulaVar sShift("sShift_"+hname,"@0*@1",RooArgList(m,kJER)); RooRealVar a("alpha_"+hname,"alpha_"+hname,1,-10,10); RooRealVar n("exp_"+hname,"exp_"+hname,1,0,100); RooRealVar b0("b0_"+hname,"b0_"+hname,0.5,0.,1.); RooRealVar b1("b1_"+hname,"b1_"+hname,0.5,0.,1.); RooRealVar b2("b2_"+hname,"b2_"+hname,0.5,0.,1.); RooRealVar b3("b3_"+hname,"b3_"+hname,0.5,0.,1.); RooBernstein bkg("signal_bkg_"+hname,"signal_bkg_"+hname,x,RooArgSet(b0,b1,b2)); RooRealVar fsig("fsig_"+hname,"fsig_"+hname,0.7,0.0,1.0); RooCBShape sig("signal_gauss_"+hname,"signal_gauss_"+hname,x,mShift,sShift,a,n); model = new RooAddPdf("signal_model_"+hname,"signal_model_"+hname,RooArgList(sig,bkg),fsig); //RooFitResult *res = model->fitTo(*RooHistFit,RooFit::Save(),RooFit::SumW2Error(kFALSE),"q"); model->fitTo(*RooHistFit,RooFit::Save(),RooFit::SumW2Error(kFALSE),"q"); //res->Print(); //model->Print(); canvas->cd(); canvas->SetTopMargin(0.1); RooPlot *frame = x.frame(); // no scale RooHistFit->plotOn(frame); model->plotOn(frame,RooFit::LineColor(LC_),RooFit::LineWidth(2));//,RooFit::LineStyle(kDotted)); model->plotOn(frame,RooFit::Components(bkg),RooFit::LineColor(LC_),RooFit::LineWidth(2),RooFit::LineStyle(kDashed)); // with scale // RooHistFit->plotOn(frame,RooFit::Normalization(HSCALE_,RooAbsReal::NumEvent)); // model->plotOn(frame,RooFit::Normalization(HSCALE_,RooAbsReal::NumEvent),RooFit::LineWidth(1)); // model->plotOn(frame,RooFit::Components(bkg),RooFit::LineColor(kBlue),RooFit::LineWidth(1),RooFit::LineStyle(kDashed),RooFit::Normalization(HSCALE_,RooAbsReal::NumEvent)); frame->GetXaxis()->SetLimits(50,200); frame->GetXaxis()->SetNdivisions(505); frame->GetXaxis()->SetTitle("M_{b#bar{b}} (GeV)"); frame->GetYaxis()->SetTitle("Events"); frame->Draw(); h.SetFillColor(kGray); h.Draw("hist,same"); frame->Draw("same"); gPad->RedrawAxis(); TF1 *tmp = model->asTF(x,fsig,x); //tmp->Print(); double y0_ = tmp->GetMaximum(); double x0_ = tmp->GetMaximumX(); double x1_ = tmp->GetX(y0_/2.,XMIN_,x0_); double x2_ = tmp->GetX(y0_/2.,x0_,XMAX_); double FWHM_ = x2_-x1_; double INT_ = tmp->Integral(XMIN_,XMAX_); double YIELD_= YieldVBF.getVal(); double y1_ = dX_*0.5*y0_*(YieldVBF.getVal()/tmp->Integral(XMIN_,XMAX_)); params[0] = x0_; params[1] = x1_; params[2] = x2_; params[3] = y0_; params[4] = y1_; params[5] = FWHM_; params[6] = INT_; params[7] = YIELD_; //cout<<"Int = "<<tmp->Integral(XMIN_,XMAX_)<<", Yield = "<<YieldVBF.getVal()<<", y0 = "<<y0_<<", y1 = "<<y1_ <<", x0 = "<< x0_ << ", x1 = "<<x1_<<", x2 = "<<x2_<<", FWHM = "<<FWHM_<<endl; TLine ln = TLine(x1_,y1_,x2_,y1_); ln.SetLineColor(kMagenta+3); ln.SetLineStyle(7); ln.SetLineWidth(2); ln.Draw(); canvas->Update(); canvas->SaveAs("testC.png"); // tmp->Delete(); // frame->Delete(); // res->Delete(); // TF1 *f1 = model->asTF(x,fsig,x); // return f1; ////tmp->Delete(); ////ln->Delete(); ////model->Delete(); ////RooHistFit->Delete(); ////w->Delete(); ////YieldVBF->Delete(); ////frame->Delete(); ////res->Delete(); //delete tmp; //delete ln; //delete model; //delete RooHistFit; //delete w; //delete YieldVBF; //delete frame; //delete res; // return canvas; }
void fitWm(const TString outputDir, // output directory const Double_t lumi, // integrated luminosity (/fb) const Double_t nsigma=0 // vary MET corrections by n-sigmas (nsigma=0 means nominal correction) ) { gBenchmark->Start("fitWm"); //-------------------------------------------------------------------------------------------------------------- // Settings //============================================================================================================== // MET histogram binning and range const Int_t NBINS = 50; const Double_t METMAX = 100; const Double_t PT_CUT = 25; const Double_t ETA_CUT = 2.1; // file format for output plots const TString format("png"); // recoil correction RecoilCorrector recoilCorr("../Recoil/ZmmData/fits.root");//, (!) uncomment to perform corrections to recoil from W-MC/Z-MC //"../Recoil/WmpMC/fits.root", //"../Recoil/WmmMC/fits.root", //"../Recoil/ZmmMC/fits.root"); // NNLO boson pT k-factors TFile nnloCorrFile("/data/blue/ksung/EWKAna/8TeV/Utils/Ratio.root"); TH1D *hNNLOCorr = (TH1D*)nnloCorrFile.Get("RpT_B"); // // input ntuple file names // enum { eData, eWmunu, eEWK, eAntiData, eAntiWmunu, eAntiEWK }; // data type enum vector<TString> fnamev; vector<Int_t> typev; fnamev.push_back("/data/blue/ksung/EWKAna/8TeV/Selection/Wmunu/ntuples/data_select.root"); typev.push_back(eData); fnamev.push_back("/data/blue/ksung/EWKAna/8TeV/Selection/Wmunu/ntuples/wm_select.root"); typev.push_back(eWmunu); fnamev.push_back("/data/blue/ksung/EWKAna/8TeV/Selection/Wmunu/ntuples/ewk_select.root"); typev.push_back(eEWK); fnamev.push_back("/data/blue/ksung/EWKAna/8TeV/Selection/Wmunu/ntuples/top_select.root"); typev.push_back(eEWK); fnamev.push_back("/data/blue/ksung/EWKAna/8TeV/Selection/AntiWmunu/ntuples/data_select.root"); typev.push_back(eAntiData); fnamev.push_back("/data/blue/ksung/EWKAna/8TeV/Selection/AntiWmunu/ntuples/wm_select.root"); typev.push_back(eAntiWmunu); fnamev.push_back("/data/blue/ksung/EWKAna/8TeV/Selection/AntiWmunu/ntuples/ewk_select.root"); typev.push_back(eAntiEWK); fnamev.push_back("/data/blue/ksung/EWKAna/8TeV/Selection/AntiWmunu/ntuples/top_select.root"); typev.push_back(eAntiEWK); //-------------------------------------------------------------------------------------------------------------- // Main analysis code //============================================================================================================== // Create output directory gSystem->mkdir(outputDir,kTRUE); CPlot::sOutDir = outputDir; // // Declare MET histograms // TH1D *hDataMet = new TH1D("hDataMet","", NBINS,0,METMAX); hDataMet->Sumw2(); TH1D *hDataMetm = new TH1D("hDataMetm","", NBINS,0,METMAX); hDataMetm->Sumw2(); TH1D *hDataMetp = new TH1D("hDataMetp","", NBINS,0,METMAX); hDataMetp->Sumw2(); TH1D *hWmunuMet = new TH1D("hWmunuMet","", NBINS,0,METMAX); hWmunuMet->Sumw2(); TH1D *hWmunuMetp = new TH1D("hWmunuMetp","",NBINS,0,METMAX); hWmunuMetp->Sumw2(); TH1D *hWmunuMetm = new TH1D("hWmunuMetm","",NBINS,0,METMAX); hWmunuMetm->Sumw2(); TH1D *hEWKMet = new TH1D("hEWKMet", "", NBINS,0,METMAX); hEWKMet->Sumw2(); TH1D *hEWKMetp = new TH1D("hEWKMetp", "", NBINS,0,METMAX); hEWKMetp->Sumw2(); TH1D *hEWKMetm = new TH1D("hEWKMetm", "", NBINS,0,METMAX); hEWKMetm->Sumw2(); TH1D *hAntiDataMet = new TH1D("hAntiDataMet","", NBINS,0,METMAX); hAntiDataMet->Sumw2(); TH1D *hAntiDataMetm = new TH1D("hAntiDataMetm","", NBINS,0,METMAX); hAntiDataMetm->Sumw2(); TH1D *hAntiDataMetp = new TH1D("hAntiDataMetp","", NBINS,0,METMAX); hAntiDataMetp->Sumw2(); TH1D *hAntiWmunuMet = new TH1D("hAntiWmunuMet","", NBINS,0,METMAX); hAntiWmunuMet->Sumw2(); TH1D *hAntiWmunuMetp = new TH1D("hAntiWmunuMetp","",NBINS,0,METMAX); hAntiWmunuMetp->Sumw2(); TH1D *hAntiWmunuMetm = new TH1D("hAntiWmunuMetm","",NBINS,0,METMAX); hAntiWmunuMetm->Sumw2(); TH1D *hAntiEWKMet = new TH1D("hAntiEWKMet", "", NBINS,0,METMAX); hAntiEWKMet->Sumw2(); TH1D *hAntiEWKMetp = new TH1D("hAntiEWKMetp", "", NBINS,0,METMAX); hAntiEWKMetp->Sumw2(); TH1D *hAntiEWKMetm = new TH1D("hAntiEWKMetm", "", NBINS,0,METMAX); hAntiEWKMetm->Sumw2(); // // Declare variables to read in ntuple // UInt_t runNum, lumiSec, evtNum; UInt_t npv, npu; Float_t genVPt, genVPhi; Float_t scale1fb; Float_t met, metPhi, sumEt, mt, u1, u2; Int_t q; LorentzVector *lep=0; Float_t pfChIso, pfGamIso, pfNeuIso; TFile *infile=0; TTree *intree=0; // // Loop over files // for(UInt_t ifile=0; ifile<fnamev.size(); ifile++) { // Read input file and get the TTrees cout << "Processing " << fnamev[ifile] << "..." << endl; infile = new TFile(fnamev[ifile]); assert(infile); intree = (TTree*)infile->Get("Events"); assert(intree); intree->SetBranchAddress("runNum", &runNum); // event run number intree->SetBranchAddress("lumiSec", &lumiSec); // event lumi section intree->SetBranchAddress("evtNum", &evtNum); // event number intree->SetBranchAddress("npv", &npv); // number of primary vertices intree->SetBranchAddress("npu", &npu); // number of in-time PU events (MC) intree->SetBranchAddress("genVPt", &genVPt); // GEN W boson pT (signal MC) intree->SetBranchAddress("genVPhi", &genVPhi); // GEN W boson phi (signal MC) intree->SetBranchAddress("scale1fb", &scale1fb); // event weight per 1/fb (MC) intree->SetBranchAddress("met", &met); // MET intree->SetBranchAddress("metPhi", &metPhi); // phi(MET) intree->SetBranchAddress("sumEt", &sumEt); // Sum ET intree->SetBranchAddress("mt", &mt); // transverse mass intree->SetBranchAddress("u1", &u1); // parallel component of recoil intree->SetBranchAddress("u2", &u2); // perpendicular component of recoil intree->SetBranchAddress("q", &q); // lepton charge intree->SetBranchAddress("lep", &lep); // lepton 4-vector intree->SetBranchAddress("pfChIso", &pfChIso); intree->SetBranchAddress("pfGamIso", &pfGamIso); intree->SetBranchAddress("pfNeuIso", &pfNeuIso); // // loop over events // for(UInt_t ientry=0; ientry<intree->GetEntries(); ientry++) { intree->GetEntry(ientry); if(lep->Pt() < PT_CUT) continue; if(fabs(lep->Eta()) > ETA_CUT) continue; if( (typev[ifile]==eAntiData || typev[ifile]==eAntiWmunu || typev[ifile]==eAntiEWK) && (pfChIso+pfGamIso+pfNeuIso)>0.5*(lep->Pt()) ) continue; if(typev[ifile]==eData) { hDataMet->Fill(met); if(q>0) { hDataMetp->Fill(met); } else { hDataMetm->Fill(met); } } else if(typev[ifile]==eAntiData) { hAntiDataMet->Fill(met); if(q>0) { hAntiDataMetp->Fill(met); } else { hAntiDataMetm->Fill(met); } } else { Double_t weight = 1; weight *= scale1fb*lumi; if(typev[ifile]==eWmunu) { Double_t corrMet=met, corrMetPhi=metPhi; // apply recoil corrections to W MC Double_t lepPt = lep->Pt(); //Double_t lepPt = gRandom->Gaus(lep->Pt(),0.5); // (!) uncomment to apply scale/res corrections to MC recoilCorr.Correct(corrMet,corrMetPhi,genVPt,genVPhi,lepPt,lep->Phi(),nsigma,q); Double_t nnlocorr=1; for(Int_t ibin=1; ibin<=hNNLOCorr->GetNbinsX(); ibin++) { if(genVPt >= hNNLOCorr->GetBinLowEdge(ibin) && genVPt < (hNNLOCorr->GetBinLowEdge(ibin)+hNNLOCorr->GetBinWidth(ibin))) nnlocorr = hNNLOCorr->GetBinContent(ibin); } //weight *= nnlocorr; // (!) uncomment to apply NNLO corrections hWmunuMet->Fill(corrMet,weight); if(q>0) { hWmunuMetp->Fill(corrMet,weight); } else { hWmunuMetm->Fill(corrMet,weight); } } if(typev[ifile]==eAntiWmunu) { Double_t corrMet=met, corrMetPhi=metPhi; // apply recoil corrections to W MC Double_t lepPt = lep->Pt();//gRandom->Gaus(lep->Pt(),0.5); //Double_t lepPt = gRandom->Gaus(lep->Pt(),0.5); // (!) uncomment to apply scale/res corrections to MC recoilCorr.Correct(corrMet,corrMetPhi,genVPt,genVPhi,lepPt,lep->Phi(),nsigma,q); Double_t nnlocorr=1; for(Int_t ibin=1; ibin<=hNNLOCorr->GetNbinsX(); ibin++) { if(genVPt >= hNNLOCorr->GetBinLowEdge(ibin) && genVPt < (hNNLOCorr->GetBinLowEdge(ibin)+hNNLOCorr->GetBinWidth(ibin))) nnlocorr = hNNLOCorr->GetBinContent(ibin); } //weight *= nnlocorr; // (!) uncomment to apply NNLO corrections hAntiWmunuMet->Fill(corrMet,weight); if(q>0) { hAntiWmunuMetp->Fill(corrMet,weight); } else { hAntiWmunuMetm->Fill(corrMet,weight); } } if(typev[ifile]==eEWK) { hEWKMet->Fill(met,weight); if(q>0) { hEWKMetp->Fill(met,weight); } else { hEWKMetm->Fill(met,weight); } } if(typev[ifile]==eAntiEWK) { hAntiEWKMet->Fill(met,weight); if(q>0) { hAntiEWKMetp->Fill(met,weight); } else { hAntiEWKMetm->Fill(met,weight); } } } } } delete infile; infile=0, intree=0; // // Declare fit parameters for signal and background yields // Note: W signal and EWK+top PDFs are constrained to the ratio described in MC // RooRealVar nSig("nSig","nSig",0.7*(hDataMet->Integral()),0,hDataMet->Integral()); RooRealVar nQCD("nQCD","nQCD",0.3*(hDataMet->Integral()),0,hDataMet->Integral()); RooRealVar cewk("cewk","cewk",0.1,0,5) ; cewk.setVal(hEWKMet->Integral()/hWmunuMet->Integral()); cewk.setConstant(kTRUE); RooFormulaVar nEWK("nEWK","nEWK","cewk*nSig",RooArgList(nSig,cewk)); RooRealVar nAntiSig("nAntiSig","nAntiSig",0.05*(hAntiDataMet->Integral()),0,hAntiDataMet->Integral()); RooRealVar nAntiQCD("nAntiQCD","nAntiQCD",0.9*(hDataMet->Integral()),0,hDataMet->Integral()); RooRealVar dewk("dewk","dewk",0.1,0,5) ; dewk.setVal(hAntiEWKMet->Integral()/hAntiWmunuMet->Integral()); dewk.setConstant(kTRUE); RooFormulaVar nAntiEWK("nAntiEWK","nAntiEWK","dewk*nAntiSig",RooArgList(nAntiSig,dewk)); RooRealVar nSigp("nSigp","nSigp",0.7*(hDataMetp->Integral()),0,hDataMetp->Integral()); RooRealVar nQCDp("nQCDp","nQCDp",0.3*(hDataMetp->Integral()),0,hDataMetp->Integral()); RooRealVar cewkp("cewkp","cewkp",0.1,0,5) ; cewkp.setVal(hEWKMetp->Integral()/hWmunuMetp->Integral()); cewkp.setConstant(kTRUE); RooFormulaVar nEWKp("nEWKp","nEWKp","cewkp*nSigp",RooArgList(nSigp,cewkp)); RooRealVar nAntiSigp("nAntiSigp","nAntiSigp",0.05*(hAntiDataMetp->Integral()),0,hAntiDataMetp->Integral()); RooRealVar nAntiQCDp("nAntiQCDp","nAntiQCDp",0.9*(hAntiDataMetp->Integral()),0,hAntiDataMetp->Integral()); RooRealVar dewkp("dewkp","dewkp",0.1,0,5) ; dewkp.setVal(hAntiEWKMetp->Integral()/hAntiWmunuMetp->Integral()); dewkp.setConstant(kTRUE); RooFormulaVar nAntiEWKp("nAntiEWKp","nAntiEWKp","dewkp*nAntiSigp",RooArgList(nAntiSigp,dewkp)); RooRealVar nSigm("nSigm","nSigm",0.7*(hDataMetm->Integral()),0,hDataMetm->Integral()); RooRealVar nQCDm("nQCDm","nQCDm",0.3*(hDataMetm->Integral()),0,hDataMetm->Integral()); RooRealVar cewkm("cewkm","cewkm",0.1,0,5) ; cewkm.setVal(hEWKMetm->Integral()/hWmunuMetm->Integral()); cewkm.setConstant(kTRUE); RooFormulaVar nEWKm("nEWKm","nEWKm","cewkm*nSigm",RooArgList(nSigm,cewkm)); RooRealVar nAntiSigm("nAntiSigm","nAntiSigm",0.05*(hAntiDataMetm->Integral()),0,hAntiDataMetm->Integral()); RooRealVar nAntiQCDm("nAntiQCDm","nAntiQCDm",0.9*(hAntiDataMetm->Integral()),0,hAntiDataMetm->Integral()); RooRealVar dewkm("dewkm","dewkm",0.1,0,5) ; dewkm.setVal(hAntiEWKMetm->Integral()/hAntiWmunuMetm->Integral()); dewkm.setConstant(kTRUE); RooFormulaVar nAntiEWKm("nAntiEWKm","nAntiEWKm","dewkm*nAntiSigm",RooArgList(nAntiSigm,dewkm)); // // Construct PDFs for fitting // RooRealVar pfmet("pfmet","pfmet",0,METMAX); pfmet.setBins(NBINS); // Signal PDFs RooDataHist wmunuMet ("wmunuMET", "wmunuMET", RooArgSet(pfmet),hWmunuMet); RooHistPdf pdfWm ("wm", "wm", pfmet,wmunuMet, 1); RooDataHist wmunuMetp("wmunuMETp","wmunuMETp",RooArgSet(pfmet),hWmunuMetp); RooHistPdf pdfWmp("wmp","wmp",pfmet,wmunuMetp,1); RooDataHist wmunuMetm("wmunuMETm","wmunuMETm",RooArgSet(pfmet),hWmunuMetm); RooHistPdf pdfWmm("wmm","wmm",pfmet,wmunuMetm,1); // EWK+top PDFs RooDataHist ewkMet ("ewkMET", "ewkMET", RooArgSet(pfmet),hEWKMet); RooHistPdf pdfEWK ("ewk", "ewk", pfmet,ewkMet, 1); RooDataHist ewkMetp("ewkMETp","ewkMETp",RooArgSet(pfmet),hEWKMetp); RooHistPdf pdfEWKp("ewkp","ewkp",pfmet,ewkMetp,1); RooDataHist ewkMetm("ewkMETm","ewkMETm",RooArgSet(pfmet),hEWKMetm); RooHistPdf pdfEWKm("ewkm","ewkm",pfmet,ewkMetm,1); // QCD Pdfs CPepeModel1 qcd("qcd",pfmet); CPepeModel1 qcdp("qcdp",pfmet); CPepeModel1 qcdm("qcdm",pfmet); // Signal + Background PDFs RooAddPdf pdfMet ("pdfMet", "pdfMet", RooArgList(pdfWm,pdfEWK,*(qcd.model)), RooArgList(nSig,nEWK,nQCD)); RooAddPdf pdfMetp("pdfMetp","pdfMetp",RooArgList(pdfWmp,pdfEWKp,*(qcdp.model)),RooArgList(nSigp,nEWKp,nQCDp)); RooAddPdf pdfMetm("pdfMetm","pdfMetm",RooArgList(pdfWmm,pdfEWKm,*(qcdm.model)),RooArgList(nSigm,nEWKm,nQCDm)); // Anti-Signal PDFs RooDataHist awmunuMet ("awmunuMET", "awmunuMET", RooArgSet(pfmet),hAntiWmunuMet); RooHistPdf apdfWm ("awm", "awm", pfmet,awmunuMet, 1); RooDataHist awmunuMetp("awmunuMETp","awmunuMETp",RooArgSet(pfmet),hAntiWmunuMetp); RooHistPdf apdfWmp("awmp","awmp",pfmet,awmunuMetp,1); RooDataHist awmunuMetm("awmunuMETm","awmunuMETm",RooArgSet(pfmet),hAntiWmunuMetm); RooHistPdf apdfWmm("awmm","awmm",pfmet,awmunuMetm,1); // Anti-EWK+top PDFs RooDataHist aewkMet ("aewkMET", "aewkMET", RooArgSet(pfmet),hAntiEWKMet); RooHistPdf apdfEWK ("aewk", "aewk", pfmet,aewkMet, 1); RooDataHist aewkMetp("aewkMETp","aewkMETp",RooArgSet(pfmet),hAntiEWKMetp); RooHistPdf apdfEWKp("aewkp","aewkp",pfmet,aewkMetp,1); RooDataHist aewkMetm("aewkMETm","aewkMETm",RooArgSet(pfmet),hAntiEWKMetm); RooHistPdf apdfEWKm("aewkm","aewkm",pfmet,aewkMetm,1); // Anti-QCD Pdfs CPepeModel1 aqcd("aqcd",pfmet,qcd.a1); CPepeModel1 aqcdp("aqcdp",pfmet,qcdp.a1); CPepeModel1 aqcdm("aqcdm",pfmet,qcdm.a1); // Anti-selection PDFs RooAddPdf apdfMet ("apdfMet", "apdfMet", RooArgList(apdfWm,apdfEWK,*(aqcd.model)), RooArgList(nAntiSig,nAntiEWK,nAntiQCD)); RooAddPdf apdfMetp("apdfMetp","apdfMetp",RooArgList(apdfWmp,apdfEWKp,*(aqcdp.model)),RooArgList(nAntiSigp,nAntiEWKp,nAntiQCDp)); RooAddPdf apdfMetm("apdfMetm","apdfMetm",RooArgList(apdfWmm,apdfEWKm,*(aqcdm.model)),RooArgList(nAntiSigm,nAntiEWKm,nAntiQCDm)); // PDF for simultaneous fit RooCategory rooCat("rooCat","rooCat"); rooCat.defineType("Select"); rooCat.defineType("Anti"); RooSimultaneous pdfTotal("pdfTotal","pdfTotal",rooCat); pdfTotal.addPdf(pdfMet, "Select"); pdfTotal.addPdf(apdfMet,"Anti"); RooSimultaneous pdfTotalp("pdfTotalp","pdfTotalp",rooCat); pdfTotalp.addPdf(pdfMetp, "Select"); pdfTotalp.addPdf(apdfMetp,"Anti"); RooSimultaneous pdfTotalm("pdfTotalm","pdfTotalm",rooCat); pdfTotalm.addPdf(pdfMetm, "Select"); pdfTotalm.addPdf(apdfMetm,"Anti"); // // Perform fits // RooDataHist dataMet("dataMet", "dataMet", RooArgSet(pfmet), hDataMet); RooDataHist antiMet("antiMet", "antiMet", RooArgSet(pfmet), hAntiDataMet); RooDataHist dataTotal("dataTotal","dataTotal", RooArgList(pfmet), Index(rooCat), Import("Select", dataMet), Import("Anti", antiMet)); RooFitResult *fitRes = pdfTotal.fitTo(dataTotal,Extended(),Minos(kTRUE),Save(kTRUE)); RooDataHist dataMetp("dataMetp", "dataMetp", RooArgSet(pfmet), hDataMetp); RooDataHist antiMetp("antiMetp", "antiMetp", RooArgSet(pfmet), hAntiDataMetp); RooDataHist dataTotalp("dataTotalp","dataTotalp", RooArgList(pfmet), Index(rooCat), Import("Select", dataMetp), Import("Anti", antiMetp)); RooFitResult *fitResp = pdfTotalp.fitTo(dataTotalp,Extended(),Minos(kTRUE),Save(kTRUE)); RooDataHist dataMetm("dataMetm", "dataMetm", RooArgSet(pfmet), hDataMetm); RooDataHist antiMetm("antiMetm", "antiMetm", RooArgSet(pfmet), hAntiDataMetm); RooDataHist dataTotalm("dataTotalm","dataTotalm", RooArgList(pfmet), Index(rooCat), Import("Select", dataMetm), Import("Anti", antiMetm)); RooFitResult *fitResm = pdfTotalm.fitTo(dataTotalm,Extended(),Minos(kTRUE),Save(kTRUE)); // // Use histogram version of fitted PDFs to make ratio plots // (Will also use PDF histograms later for Chi^2 and KS tests) // TH1D *hPdfMet = (TH1D*)(pdfMet.createHistogram("hPdfMet", pfmet)); hPdfMet->Scale((nSig.getVal()+nEWK.getVal()+nQCD.getVal())/hPdfMet->Integral()); TH1D *hMetDiff = makeDiffHist(hDataMet,hPdfMet,"hMetDiff"); hMetDiff->SetMarkerStyle(kFullCircle); hMetDiff->SetMarkerSize(0.9); TH1D *hPdfMetp = (TH1D*)(pdfMetp.createHistogram("hPdfMetp", pfmet)); hPdfMetp->Scale((nSigp.getVal()+nEWKp.getVal()+nQCDp.getVal())/hPdfMetp->Integral()); TH1D *hMetpDiff = makeDiffHist(hDataMetp,hPdfMetp,"hMetpDiff"); hMetpDiff->SetMarkerStyle(kFullCircle); hMetpDiff->SetMarkerSize(0.9); TH1D *hPdfMetm = (TH1D*)(pdfMetm.createHistogram("hPdfMetm", pfmet)); hPdfMetm->Scale((nSigm.getVal()+nEWKm.getVal()+nQCDm.getVal())/hPdfMetm->Integral()); TH1D *hMetmDiff = makeDiffHist(hDataMetm,hPdfMetm,"hMetmDiff"); hMetmDiff->SetMarkerStyle(kFullCircle); hMetmDiff->SetMarkerSize(0.9); TH1D *hPdfAntiMet = (TH1D*)(apdfMet.createHistogram("hPdfAntiMet", pfmet)); hPdfAntiMet->Scale((nAntiSig.getVal()+nAntiEWK.getVal()+nAntiQCD.getVal())/hPdfAntiMet->Integral()); TH1D *hAntiMetDiff = makeDiffHist(hAntiDataMet,hPdfAntiMet,"hAntiMetDiff"); hAntiMetDiff->SetMarkerStyle(kFullCircle); hAntiMetDiff->SetMarkerSize(0.9); TH1D *hPdfAntiMetp = (TH1D*)(apdfMetp.createHistogram("hPdfAntiMetp", pfmet)); hPdfAntiMetp->Scale((nAntiSigp.getVal()+nAntiEWKp.getVal()+nAntiQCDp.getVal())/hPdfAntiMetp->Integral()); TH1D *hAntiMetpDiff = makeDiffHist(hAntiDataMetp,hPdfAntiMetp,"hAntiMetpDiff"); hAntiMetpDiff->SetMarkerStyle(kFullCircle); hAntiMetpDiff->SetMarkerSize(0.9); TH1D *hPdfAntiMetm = (TH1D*)(apdfMetm.createHistogram("hPdfAntiMetm", pfmet)); hPdfAntiMetm->Scale((nAntiSigm.getVal()+nAntiEWKm.getVal()+nAntiQCDm.getVal())/hPdfAntiMetm->Integral()); TH1D *hAntiMetmDiff = makeDiffHist(hAntiDataMetm,hPdfAntiMetm,"hAntiMetmDiff"); hAntiMetmDiff->SetMarkerStyle(kFullCircle); hAntiMetmDiff->SetMarkerSize(0.9); //-------------------------------------------------------------------------------------------------------------- // Make plots //============================================================================================================== TCanvas *c = MakeCanvas("c","c",800,800); c->Divide(1,2,0,0); c->cd(1)->SetPad(0,0.3,1.0,1.0); c->cd(1)->SetTopMargin(0.1); c->cd(1)->SetBottomMargin(0.01); c->cd(1)->SetLeftMargin(0.15); c->cd(1)->SetRightMargin(0.07); c->cd(1)->SetTickx(1); c->cd(1)->SetTicky(1); c->cd(2)->SetPad(0,0,1.0,0.3); c->cd(2)->SetTopMargin(0.05); c->cd(2)->SetBottomMargin(0.45); c->cd(2)->SetLeftMargin(0.15); c->cd(2)->SetRightMargin(0.07); c->cd(2)->SetTickx(1); c->cd(2)->SetTicky(1); gStyle->SetTitleOffset(1.100,"Y"); TGaxis::SetMaxDigits(3); char ylabel[100]; // string buffer for y-axis label // label for lumi char lumitext[100]; if(lumi<0.1) sprintf(lumitext,"%.1f pb^{-1} at #sqrt{s} = 8 TeV",lumi*1000.); else sprintf(lumitext,"%.2f fb^{-1} at #sqrt{s} = 8 TeV",lumi); // plot colors Int_t linecolorW = kOrange-3; Int_t fillcolorW = kOrange-2; Int_t linecolorEWK = kOrange+10; Int_t fillcolorEWK = kOrange+7; Int_t linecolorQCD = kViolet+2; Int_t fillcolorQCD = kViolet-5; Int_t ratioColor = kGray+2; // // Dummy histograms for TLegend // (I can't figure out how to properly pass RooFit objects...) // TH1D *hDummyData = new TH1D("hDummyData","",0,0,10); hDummyData->SetMarkerStyle(kFullCircle); hDummyData->SetMarkerSize(0.9); TH1D *hDummyW = new TH1D("hDummyW","",0,0,10); hDummyW->SetLineColor(linecolorW); hDummyW->SetFillColor(fillcolorW); hDummyW->SetFillStyle(1001); TH1D *hDummyEWK = new TH1D("hDummyEWK","",0,0,10); hDummyEWK->SetLineColor(linecolorEWK); hDummyEWK->SetFillColor(fillcolorEWK); hDummyEWK->SetFillStyle(1001); TH1D *hDummyQCD = new TH1D("hDummyQCD","",0,0,10); hDummyQCD->SetLineColor(linecolorQCD); hDummyQCD->SetFillColor(fillcolorQCD); hDummyQCD->SetFillStyle(1001); // // W MET plot // RooPlot *wmframe = pfmet.frame(Bins(NBINS)); wmframe->GetYaxis()->SetNdivisions(505); dataMet.plotOn(wmframe,MarkerStyle(kFullCircle),MarkerSize(0.9),DrawOption("ZP")); pdfMet.plotOn(wmframe,FillColor(fillcolorW),DrawOption("F")); pdfMet.plotOn(wmframe,LineColor(linecolorW)); pdfMet.plotOn(wmframe,Components(RooArgSet(pdfEWK,*(qcd.model))),FillColor(fillcolorEWK),DrawOption("F")); pdfMet.plotOn(wmframe,Components(RooArgSet(pdfEWK,*(qcd.model))),LineColor(linecolorEWK)); pdfMet.plotOn(wmframe,Components(RooArgSet(*(qcd.model))),FillColor(fillcolorQCD),DrawOption("F")); pdfMet.plotOn(wmframe,Components(RooArgSet(*(qcd.model))),LineColor(linecolorQCD)); pdfMet.plotOn(wmframe,Components(RooArgSet(pdfWm)),LineColor(linecolorW),LineStyle(2)); dataMet.plotOn(wmframe,MarkerStyle(kFullCircle),MarkerSize(0.9),DrawOption("ZP")); sprintf(ylabel,"Events / %.1f GeV",hDataMet->GetBinWidth(1)); CPlot plotMet("fitmet",wmframe,"","",ylabel); plotMet.SetLegend(0.68,0.57,0.93,0.77); plotMet.GetLegend()->AddEntry(hDummyData,"data","PL"); plotMet.GetLegend()->AddEntry(hDummyW,"W#rightarrow#mu#nu","F"); plotMet.GetLegend()->AddEntry(hDummyEWK,"EWK+t#bar{t}","F"); plotMet.GetLegend()->AddEntry(hDummyQCD,"QCD","F"); plotMet.AddTextBox(lumitext,0.55,0.80,0.90,0.86,0); plotMet.AddTextBox("CMS Preliminary",0.63,0.92,0.95,0.99,0); plotMet.SetYRange(0.1,1.1*(hDataMet->GetMaximum())); plotMet.Draw(c,kFALSE,format,1); CPlot plotMetDiff("fitmet","","#slash{E}_{T} [GeV]","#chi"); plotMetDiff.AddHist1D(hMetDiff,"EX0",ratioColor); plotMetDiff.SetYRange(-8,8); plotMetDiff.AddLine(0, 0,METMAX, 0,kBlack,1); plotMetDiff.AddLine(0, 5,METMAX, 5,kBlack,3); plotMetDiff.AddLine(0,-5,METMAX,-5,kBlack,3); plotMetDiff.Draw(c,kTRUE,format,2); plotMet.SetName("fitmetlog"); plotMet.SetLogy(); plotMet.SetYRange(1e-3*(hDataMet->GetMaximum()),10*(hDataMet->GetMaximum())); plotMet.Draw(c,kTRUE,format,1); RooPlot *awmframe = pfmet.frame(Bins(NBINS)); antiMet.plotOn(awmframe,MarkerStyle(kFullCircle),MarkerSize(0.9),DrawOption("ZP")); apdfMet.plotOn(awmframe,FillColor(fillcolorW),DrawOption("F")); apdfMet.plotOn(awmframe,LineColor(linecolorW)); apdfMet.plotOn(awmframe,Components(RooArgSet(apdfEWK,*(aqcd.model))),FillColor(fillcolorEWK),DrawOption("F")); apdfMet.plotOn(awmframe,Components(RooArgSet(apdfEWK,*(aqcd.model))),LineColor(linecolorEWK)); apdfMet.plotOn(awmframe,Components(RooArgSet(*(aqcd.model))),FillColor(fillcolorQCD),DrawOption("F")); apdfMet.plotOn(awmframe,Components(RooArgSet(*(aqcd.model))),LineColor(linecolorQCD)); apdfMet.plotOn(awmframe,Components(RooArgSet(apdfWm)),LineColor(linecolorW),LineStyle(2)); antiMet.plotOn(awmframe,MarkerStyle(kFullCircle),MarkerSize(0.9),DrawOption("ZP")); sprintf(ylabel,"Events / %.1f GeV",hAntiDataMet->GetBinWidth(1)); CPlot plotAntiMet("fitantimet",awmframe,"","",ylabel); plotAntiMet.SetLegend(0.68,0.57,0.93,0.77); plotAntiMet.GetLegend()->AddEntry(hDummyData,"data","PL"); plotAntiMet.GetLegend()->AddEntry(hDummyW,"W#rightarrow#mu#nu","F"); plotAntiMet.GetLegend()->AddEntry(hDummyEWK,"EWK+t#bar{t}","F"); plotAntiMet.GetLegend()->AddEntry(hDummyQCD,"QCD","F"); plotAntiMet.AddTextBox(lumitext,0.55,0.80,0.90,0.86,0); plotAntiMet.AddTextBox("CMS Preliminary",0.63,0.92,0.95,0.99,0); plotAntiMet.SetYRange(0.1,1.1*(hAntiDataMet->GetMaximum())); plotAntiMet.Draw(c,kFALSE,format,1); CPlot plotAntiMetDiff("fitantimet","","#slash{E}_{T} [GeV]","#chi"); plotAntiMetDiff.AddHist1D(hMetDiff,"EX0",ratioColor); plotAntiMetDiff.SetYRange(-8,8); plotAntiMetDiff.AddLine(0, 0,METMAX, 0,kBlack,1); plotAntiMetDiff.AddLine(0, 5,METMAX, 5,kBlack,3); plotAntiMetDiff.AddLine(0,-5,METMAX,-5,kBlack,3); plotAntiMetDiff.Draw(c,kTRUE,format,2); plotAntiMet.SetName("fitantimetlog"); plotAntiMet.SetLogy(); plotAntiMet.SetYRange(1e-3*(hAntiDataMet->GetMaximum()),10*(hAntiDataMet->GetMaximum())); plotAntiMet.Draw(c,kTRUE,format,1); // // W+ MET plot // RooPlot *wmpframe = pfmet.frame(Bins(NBINS)); wmpframe->GetYaxis()->SetNdivisions(505); dataMetp.plotOn(wmpframe,MarkerStyle(kFullCircle),MarkerSize(0.9),DrawOption("ZP")); pdfMetp.plotOn(wmpframe,FillColor(fillcolorW),DrawOption("F")); pdfMetp.plotOn(wmpframe,LineColor(linecolorW)); pdfMetp.plotOn(wmpframe,Components(RooArgSet(pdfEWKp,*(qcdp.model))),FillColor(fillcolorEWK),DrawOption("F")); pdfMetp.plotOn(wmpframe,Components(RooArgSet(pdfEWKp,*(qcdp.model))),LineColor(linecolorEWK)); pdfMetp.plotOn(wmpframe,Components(RooArgSet(*(qcdp.model))),FillColor(fillcolorQCD),DrawOption("F")); pdfMetp.plotOn(wmpframe,Components(RooArgSet(*(qcdp.model))),LineColor(linecolorQCD)); pdfMetp.plotOn(wmpframe,Components(RooArgSet(pdfWmp)),LineColor(linecolorW),LineStyle(2)); dataMetp.plotOn(wmpframe,MarkerStyle(kFullCircle),MarkerSize(0.9),DrawOption("ZP")); sprintf(ylabel,"Events / %.1f GeV",hDataMetp->GetBinWidth(1)); CPlot plotMetp("fitmetp",wmpframe,"","",ylabel); plotMetp.SetLegend(0.68,0.57,0.93,0.77); plotMetp.GetLegend()->AddEntry(hDummyData,"data","PL"); plotMetp.GetLegend()->AddEntry(hDummyW,"W^{+}#rightarrow#mu^{+}#nu","F"); plotMetp.GetLegend()->AddEntry(hDummyEWK,"EWK+t#bar{t}","F"); plotMetp.GetLegend()->AddEntry(hDummyQCD,"QCD","F"); plotMetp.AddTextBox(lumitext,0.55,0.80,0.90,0.86,0); plotMetp.AddTextBox("CMS Preliminary",0.63,0.92,0.95,0.99,0); // plotMetp.SetYRange(0.1,1.1*(hDataMetp->GetMaximum())); plotMetp.SetYRange(0.1,4100); plotMetp.Draw(c,kFALSE,format,1); CPlot plotMetpDiff("fitmetp","","#slash{E}_{T} [GeV]","#chi"); plotMetpDiff.AddHist1D(hMetpDiff,"EX0",ratioColor); plotMetpDiff.SetYRange(-8,8); plotMetpDiff.AddLine(0, 0,METMAX, 0,kBlack,1); plotMetpDiff.AddLine(0, 5,METMAX, 5,kBlack,3); plotMetpDiff.AddLine(0,-5,METMAX,-5,kBlack,3); plotMetpDiff.Draw(c,kTRUE,format,2); plotMetp.SetName("fitmetplog"); plotMetp.SetLogy(); plotMetp.SetYRange(1e-3*(hDataMetp->GetMaximum()),10*(hDataMetp->GetMaximum())); plotMetp.Draw(c,kTRUE,format,1); RooPlot *awmpframe = pfmet.frame(Bins(NBINS)); antiMetp.plotOn(awmpframe,MarkerStyle(kFullCircle),MarkerSize(0.9),DrawOption("ZP")); apdfMetp.plotOn(awmpframe,FillColor(fillcolorW),DrawOption("F")); apdfMetp.plotOn(awmpframe,LineColor(linecolorW)); apdfMetp.plotOn(awmpframe,Components(RooArgSet(apdfEWKp,*(aqcdp.model))),FillColor(fillcolorEWK),DrawOption("F")); apdfMetp.plotOn(awmpframe,Components(RooArgSet(apdfEWKp,*(aqcdp.model))),LineColor(linecolorEWK)); apdfMetp.plotOn(awmpframe,Components(RooArgSet(*(aqcdp.model))),FillColor(fillcolorQCD),DrawOption("F")); apdfMetp.plotOn(awmpframe,Components(RooArgSet(*(aqcdp.model))),LineColor(linecolorQCD)); apdfMetp.plotOn(awmpframe,Components(RooArgSet(apdfWmp)),LineColor(linecolorW),LineStyle(2)); antiMetp.plotOn(awmpframe,MarkerStyle(kFullCircle),MarkerSize(0.9),DrawOption("ZP")); sprintf(ylabel,"Events / %.1f GeV",hAntiDataMetp->GetBinWidth(1)); CPlot plotAntiMetp("fitantimetp",awmpframe,"","",ylabel); plotAntiMetp.SetLegend(0.68,0.57,0.93,0.77); plotAntiMetp.GetLegend()->AddEntry(hDummyData,"data","PL"); plotAntiMetp.GetLegend()->AddEntry(hDummyW,"W^{+}#rightarrow#mu^{+}#nu","F"); plotAntiMetp.GetLegend()->AddEntry(hDummyEWK,"EWK+t#bar{t}","F"); plotAntiMetp.GetLegend()->AddEntry(hDummyQCD,"QCD","F"); plotAntiMetp.AddTextBox(lumitext,0.55,0.80,0.90,0.86,0); plotAntiMetp.AddTextBox("CMS Preliminary",0.63,0.92,0.95,0.99,0); // plotAntiMetp.SetYRange(0.1,1.1*(hAntiDataMetp->GetMaximum())); plotAntiMetp.SetYRange(0.1,1500); plotAntiMetp.Draw(c,kFALSE,format,1); CPlot plotAntiMetpDiff("fitantimetp","","#slash{E}_{T} [GeV]","#chi"); plotAntiMetpDiff.AddHist1D(hAntiMetpDiff,"EX0",ratioColor); plotAntiMetpDiff.SetYRange(-8,8); plotAntiMetpDiff.AddLine(0, 0,METMAX, 0,kBlack,1); plotAntiMetpDiff.AddLine(0, 5,METMAX, 5,kBlack,3); plotAntiMetpDiff.AddLine(0,-5,METMAX,-5,kBlack,3); plotAntiMetpDiff.Draw(c,kTRUE,format,2); plotAntiMetp.SetName("fitantimetplog"); plotAntiMetp.SetLogy(); plotAntiMetp.SetYRange(1e-3*(hAntiDataMetp->GetMaximum()),10*(hAntiDataMetp->GetMaximum())); plotAntiMetp.Draw(c,kTRUE,format,1); // // W- MET plot // RooPlot *wmmframe = pfmet.frame(Bins(NBINS)); wmmframe->GetYaxis()->SetNdivisions(505); dataMetm.plotOn(wmmframe,MarkerStyle(kFullCircle),MarkerSize(0.9),DrawOption("ZP")); pdfMetm.plotOn(wmmframe,FillColor(fillcolorW),DrawOption("F")); pdfMetm.plotOn(wmmframe,LineColor(linecolorW)); pdfMetm.plotOn(wmmframe,Components(RooArgSet(pdfEWKm,*(qcdm.model))),FillColor(fillcolorEWK),DrawOption("F")); pdfMetm.plotOn(wmmframe,Components(RooArgSet(pdfEWKm,*(qcdm.model))),LineColor(linecolorEWK)); pdfMetm.plotOn(wmmframe,Components(RooArgSet(*(qcdm.model))),FillColor(fillcolorQCD),DrawOption("F")); pdfMetm.plotOn(wmmframe,Components(RooArgSet(*(qcdm.model))),LineColor(linecolorQCD)); pdfMetm.plotOn(wmmframe,Components(RooArgSet(pdfWmm)),LineColor(linecolorW),LineStyle(2)); dataMetm.plotOn(wmmframe,MarkerStyle(kFullCircle),MarkerSize(0.9),DrawOption("ZP")); sprintf(ylabel,"Events / %.1f GeV",hDataMetm->GetBinWidth(1)); CPlot plotMetm("fitmetm",wmmframe,"","",ylabel); plotMetm.SetLegend(0.68,0.57,0.93,0.77); plotMetm.GetLegend()->AddEntry(hDummyData,"data","PL"); plotMetm.GetLegend()->AddEntry(hDummyW,"W^{-}#rightarrow#mu^{-}#bar{#nu}","F"); plotMetm.GetLegend()->AddEntry(hDummyEWK,"EWK+t#bar{t}","F"); plotMetm.GetLegend()->AddEntry(hDummyQCD,"QCD","F"); plotMetm.AddTextBox(lumitext,0.55,0.80,0.90,0.86,0); plotMetm.AddTextBox("CMS Preliminary",0.63,0.92,0.95,0.99,0); // plotMetm.SetYRange(0.1,1.1*(hDataMetm->GetMaximum())); plotMetm.SetYRange(0.1,4100); plotMetm.Draw(c,kFALSE,format,1); CPlot plotMetmDiff("fitmetm","","#slash{E}_{T} [GeV]","#chi"); plotMetmDiff.AddHist1D(hMetmDiff,"EX0",ratioColor); plotMetmDiff.SetYRange(-8,8); plotMetmDiff.AddLine(0, 0,METMAX, 0,kBlack,1); plotMetmDiff.AddLine(0, 5,METMAX, 5,kBlack,3); plotMetmDiff.AddLine(0,-5,METMAX,-5,kBlack,3); plotMetmDiff.Draw(c,kTRUE,format,2); plotMetm.SetName("fitmetmlog"); plotMetm.SetLogy(); plotMetm.SetYRange(1e-3*(hDataMetm->GetMaximum()),10*(hDataMetm->GetMaximum())); plotMetm.Draw(c,kTRUE,format,1); RooPlot *awmmframe = pfmet.frame(Bins(NBINS)); antiMetm.plotOn(awmmframe,MarkerStyle(kFullCircle),MarkerSize(0.9),DrawOption("ZP")); apdfMetm.plotOn(awmmframe,FillColor(fillcolorW),DrawOption("F")); apdfMetm.plotOn(awmmframe,LineColor(linecolorW)); apdfMetm.plotOn(awmmframe,Components(RooArgSet(apdfEWKm,*(aqcdm.model))),FillColor(fillcolorEWK),DrawOption("F")); apdfMetm.plotOn(awmmframe,Components(RooArgSet(apdfEWKm,*(aqcdm.model))),LineColor(linecolorEWK)); apdfMetm.plotOn(awmmframe,Components(RooArgSet(*(aqcdm.model))),FillColor(fillcolorQCD),DrawOption("F")); apdfMetm.plotOn(awmmframe,Components(RooArgSet(*(aqcdm.model))),LineColor(linecolorQCD)); apdfMetm.plotOn(awmmframe,Components(RooArgSet(apdfWmm)),LineColor(linecolorW),LineStyle(2)); antiMetm.plotOn(awmmframe,MarkerStyle(kFullCircle),MarkerSize(0.9),DrawOption("ZP")); sprintf(ylabel,"Events / %.1f GeV",hDataMetm->GetBinWidth(1)); CPlot plotAntiMetm("fitantimetm",awmmframe,"","",ylabel); plotAntiMetm.SetLegend(0.68,0.57,0.93,0.77); plotAntiMetm.GetLegend()->AddEntry(hDummyData,"data","PL"); plotAntiMetm.GetLegend()->AddEntry(hDummyW,"W^{-}#rightarrow#mu^{-}#bar{#nu}","F"); plotAntiMetm.GetLegend()->AddEntry(hDummyEWK,"EWK+t#bar{t}","F"); plotAntiMetm.GetLegend()->AddEntry(hDummyQCD,"QCD","F"); plotAntiMetm.AddTextBox(lumitext,0.55,0.80,0.90,0.86,0); plotAntiMetm.AddTextBox("CMS Preliminary",0.63,0.92,0.95,0.99,0); // plotAntiMetm.SetYRange(0.1,1.1*(hAntiDataMetm->GetMaximum())); plotAntiMetm.SetYRange(0.1,1500); plotAntiMetm.Draw(c,kFALSE,format,1); CPlot plotAntiMetmDiff("fitantimetm","","#slash{E}_{T} [GeV]","#chi"); plotAntiMetmDiff.AddHist1D(hAntiMetmDiff,"EX0",ratioColor); plotAntiMetmDiff.SetYRange(-8,8); plotAntiMetmDiff.AddLine(0, 0,METMAX, 0,kBlack,1); plotAntiMetmDiff.AddLine(0, 5,METMAX, 5,kBlack,3); plotAntiMetmDiff.AddLine(0,-5,METMAX,-5,kBlack,3); plotAntiMetmDiff.Draw(c,kTRUE,format,2); plotAntiMetm.SetName("fitantimetmlog"); plotAntiMetm.SetLogy(); plotAntiMetm.SetYRange(1e-3*(hAntiDataMetm->GetMaximum()),10*(hAntiDataMetm->GetMaximum())); plotAntiMetm.Draw(c,kTRUE,format,1); //-------------------------------------------------------------------------------------------------------------- // Output //============================================================================================================== cout << "*" << endl; cout << "* SUMMARY" << endl; cout << "*--------------------------------------------------" << endl; // // Write fit results // ofstream txtfile; char txtfname[100]; ios_base::fmtflags flags; Double_t chi2prob, chi2ndf; Double_t ksprob, ksprobpe; chi2prob = hDataMet->Chi2Test(hPdfMet,"PUW"); chi2ndf = hDataMet->Chi2Test(hPdfMet,"CHI2/NDFUW"); ksprob = hDataMet->KolmogorovTest(hPdfMet); ksprobpe = hDataMet->KolmogorovTest(hPdfMet,"DX"); sprintf(txtfname,"%s/fitresWm.txt",CPlot::sOutDir.Data()); txtfile.open(txtfname); assert(txtfile.is_open()); flags = txtfile.flags(); txtfile << setprecision(10); txtfile << " *** Yields *** " << endl; txtfile << "Selected: " << hDataMet->Integral() << endl; txtfile << " Signal: " << nSig.getVal() << " +/- " << nSig.getPropagatedError(*fitRes) << endl; txtfile << " QCD: " << nQCD.getVal() << " +/- " << nQCD.getPropagatedError(*fitRes) << endl; txtfile << " Other: " << nEWK.getVal() << " +/- " << nEWK.getPropagatedError(*fitRes) << endl; txtfile << endl; txtfile.flags(flags); fitRes->printStream(txtfile,RooPrintable::kValue,RooPrintable::kVerbose); txtfile << endl; printCorrelations(txtfile, fitRes); txtfile << endl; printChi2AndKSResults(txtfile, chi2prob, chi2ndf, ksprob, ksprobpe); txtfile.close(); chi2prob = hDataMetp->Chi2Test(hPdfMetp,"PUW"); chi2ndf = hDataMetp->Chi2Test(hPdfMetp,"CHI2/NDFUW"); ksprob = hDataMetp->KolmogorovTest(hPdfMetp); ksprobpe = hDataMetp->KolmogorovTest(hPdfMetp,"DX"); sprintf(txtfname,"%s/fitresWmp.txt",CPlot::sOutDir.Data()); txtfile.open(txtfname); assert(txtfile.is_open()); flags = txtfile.flags(); txtfile << setprecision(10); txtfile << " *** Yields *** " << endl; txtfile << "Selected: " << hDataMetp->Integral() << endl; txtfile << " Signal: " << nSigp.getVal() << " +/- " << nSigp.getPropagatedError(*fitResp) << endl; txtfile << " QCD: " << nQCDp.getVal() << " +/- " << nQCDp.getPropagatedError(*fitResp) << endl; txtfile << " Other: " << nEWKp.getVal() << " +/- " << nEWKp.getPropagatedError(*fitResp) << endl; txtfile << endl; txtfile.flags(flags); fitResp->printStream(txtfile,RooPrintable::kValue,RooPrintable::kVerbose); txtfile << endl; printCorrelations(txtfile, fitResp); txtfile << endl; printChi2AndKSResults(txtfile, chi2prob, chi2ndf, ksprob, ksprobpe); txtfile.close(); chi2prob = hDataMetm->Chi2Test(hPdfMetm,"PUW"); chi2ndf = hDataMetm->Chi2Test(hPdfMetm,"CHI2/NDFUW"); ksprob = hDataMetm->KolmogorovTest(hPdfMetm); ksprobpe = hDataMetm->KolmogorovTest(hPdfMetm,"DX"); sprintf(txtfname,"%s/fitresWmm.txt",CPlot::sOutDir.Data()); txtfile.open(txtfname); assert(txtfile.is_open()); flags = txtfile.flags(); txtfile << setprecision(10); txtfile << " *** Yields *** " << endl; txtfile << "Selected: " << hDataMetm->Integral() << endl; txtfile << " Signal: " << nSigm.getVal() << " +/- " << nSigm.getPropagatedError(*fitResm) << endl; txtfile << " QCD: " << nQCDm.getVal() << " +/- " << nQCDm.getPropagatedError(*fitResm) << endl; txtfile << " Other: " << nEWKm.getVal() << " +/- " << nEWKm.getPropagatedError(*fitResm) << endl; txtfile << endl; txtfile.flags(flags); fitResm->printStream(txtfile,RooPrintable::kValue,RooPrintable::kVerbose); txtfile << endl; printCorrelations(txtfile, fitResm); txtfile << endl; printChi2AndKSResults(txtfile, chi2prob, chi2ndf, ksprob, ksprobpe); txtfile.close(); makeHTML(outputDir); cout << endl; cout << " <> Output saved in " << outputDir << "/" << endl; cout << endl; gBenchmark->Show("fitWm"); }
RooRealVar bfractionFit(char *var = "discr_csvSimple",double minX = 0,double maxX = 1,double ptMin = 60, double ptMax = 500, bool floatC = 0) { // Prepare a canvas TCanvas *c = new TCanvas("c","",600,600); c->SetLogy(); // MC shape file TFile *infQCD = new TFile("histos/ppMC_hiReco_jetTrigQCD.root"); TTree *tQCD = (TTree*) infQCD->Get("nt"); TFile *infB = new TFile("histos/ppMC_hiReco_jetTrigB.root"); TTree *tB = (TTree*) infB->Get("nt"); TFile *infC = new TFile("histos/ppMC_hiReco_jetTrigC.root"); TTree *tC = (TTree*) infC->Get("nt"); // b-jet signal shape TH1D *hB = new TH1D("hB","",20,minX,maxX); hB->Sumw2(); tB->Draw(Form("%s>>hB",var),Form("weight*(abs(refparton_flavorForB)==5&&jtpt>%f&&jtpt<%f&&pthat>80)",ptMin,ptMax)); fixEmpty(hB); TH1D *hC = new TH1D("hC","",20,minX,maxX); hC->Sumw2(); tC->Draw(Form("%s>>hC",var),Form("weight*(abs(refparton_flavorForB)==4&&jtpt>%f&&jtpt<%f&&pthat>80)",ptMin,ptMax)); fixEmpty(hC); // b-jet background shape TH1D *hOtherFlavor = new TH1D("hOtherFlavor","",20,minX,maxX); TH1D *hQCDC = new TH1D("hQCDC","",20,minX,maxX); hOtherFlavor->Sumw2(); hC->Sumw2(); tQCD->Draw(Form("%s>>hOtherFlavor",var),Form("weight*(abs(refparton_flavorForB)!=5&&abs(refparton_flavorForB)!=4&&jtpt>%f&&jtpt<%f&&pthat>80)",ptMin,ptMax)); tQCD->Draw(Form("%s>>hQCDC",var),Form("weight*(abs(refparton_flavorForB)==4&&jtpt>%f&&jtpt<%f&&pthat>80)",ptMin,ptMax)); fixEmpty(hOtherFlavor); if (!floatC) { hC->Scale(1./hC->Integral(0,100)*hQCDC->Integral(0,100)); hOtherFlavor->Add(hC); cout <<"fracC = " <<hC->Integral(0,100)/hOtherFlavor->Integral(0,100)<<endl; } // data sample TFile *infData = new TFile("histos/ppdata_hiReco_jetTrig.root"); TTree *tData = (TTree*) infData->Get("nt"); // --- Observable --- RooRealVar s(var,var,0,minX,maxX); RooRealVar jtpt("jtpt","jtpt",0,ptMin,ptMax); // --- Parameters --- // --- Build Histogram PDF --- RooDataHist xB("xB","xB",s,hB); RooDataHist xC("xC","xC",s,hC); // not used if doesn't float C RooHistPdf signal("signal","signal PDF",s,xB); RooHistPdf signalC("signalC","signalC PDF",s,xC); // not used if doesn't float C RooDataHist xOtherFlavor("xOtherFlavor","xOtherFlavor",s,hOtherFlavor); RooHistPdf background("background","Background PDF",s,xOtherFlavor); // --- Construct signal+background PDF --- // signal = bjets // background = all the other flavors // RooRealVar nsig("nsig","#signal events",6000,0.,1e7) ; // RooRealVar nbkg("nbkg","#background events",1e5,0.,1e7) ; // RooAddPdf model("model","g+a",RooArgList(signal,background),RooArgList(nsig,nbkg)) ; RooRealVar frac("frac","#background events",0.1,0.,1) ; RooRealVar fracC("fracC","#background events",0.1,0.,1) ; // not sured if doesn't float C RooAddPdf modelBck("modelBck","g+a",signalC,background,fracC) ; RooAddPdf *model; if (!floatC) { model = new RooAddPdf("model","g+a",signal,background,frac) ; } else { model = new RooAddPdf("model","g+a",signal,modelBck,frac) ; } // data sample //RooDataSet *data = new RooDataSet("data","data",RooArgSet(s),Import(*tData)); RooDataSet *data = new RooDataSet("data","data",tData,RooArgSet(s,jtpt),Form("jtpt>%f&&jtpt<%f",ptMin,ptMax)); // --- Perform extended ML fit of composite PDF to data --- model->fitTo(*data) ; // --- Plot data and composite PDF overlaid --- RooPlot* sframe = s.frame() ; TH2D *htemp = new TH2D("htemp","",100,minX,maxX,100,1,1e6) ; htemp->SetXTitle(Form("%s %.0f < p_{T} < %.0f GeV/c",var,ptMin,ptMax)); htemp->SetYTitle("Entries"); htemp->Draw(); cout <<"Min "<<sframe->GetMinimum()<<endl; data->plotOn(sframe,Binning(20)) ; sframe->SetTitle(""); model->plotOn(sframe,Components(background),LineStyle(kDashed),LineColor(kBlue)) ; model->plotOn(sframe,Components(signalC),LineStyle(kDashed),LineColor(kGreen)) ; model->plotOn(sframe) ; model->plotOn(sframe,Components(signal),LineStyle(kDashed),LineColor(kRed),FillColor(kRed),FillStyle(1)) ; cout <<"b jet fraction = "<<frac.getVal()<<endl; sframe->Draw("same"); c->SaveAs(Form("fit/%s-%.0f-%.0f.gif",var,ptMin,ptMax)); delete model; return frac; }