void drawMassFrom2DPlot(RooWorkspace& myws, // Local workspace string outputDir, // Output directory struct InputOpt opt, // Variable with run information (kept for legacy purpose) struct KinCuts cut, // Variable with current kinematic cuts map<string, string> parIni, // Variable containing all initial parameters string plotLabel, // The label used to define the output file name // Select the type of datasets to fit string DSTAG, // Specifies the type of datasets: i.e, DATA, MCJPSINP, ... bool isPbPb, // Define if it is PbPb (True) or PP (False) // Select the type of object to fit bool incJpsi, // Includes Jpsi model bool incPsi2S, // Includes Psi(2S) model bool incBkg, // Includes Background model // Select the fitting options // Select the drawing options bool setLogScale, // Draw plot with log scale bool incSS, // Include Same Sign data double binWidth, // Bin width bool paperStyle=false // if true, print less info ) { RooMsgService::instance().getStream(0).removeTopic(Caching); RooMsgService::instance().getStream(1).removeTopic(Caching); RooMsgService::instance().getStream(0).removeTopic(Plotting); RooMsgService::instance().getStream(1).removeTopic(Plotting); RooMsgService::instance().getStream(0).removeTopic(Integration); RooMsgService::instance().getStream(1).removeTopic(Integration); RooMsgService::instance().setGlobalKillBelow(RooFit::WARNING) ; if (DSTAG.find("_")!=std::string::npos) DSTAG.erase(DSTAG.find("_")); int nBins = min(int( round((cut.dMuon.M.Max - cut.dMuon.M.Min)/binWidth) ), 1000); string pdfTotName = Form("pdfCTAUMASS_Tot_%s", (isPbPb?"PbPb":"PP")); string pdfJpsiPRName = Form("pdfCTAUMASS_JpsiPR_%s", (isPbPb?"PbPb":"PP")); string pdfJpsiNoPRName = Form("pdfCTAUMASS_JpsiNoPR_%s", (isPbPb?"PbPb":"PP")); string pdfPsi2SPRName = Form("pdfCTAUMASS_Psi2SPR_%s", (isPbPb?"PbPb":"PP")); string pdfPsi2SNoPRName = Form("pdfCTAUMASS_Psi2SNoPR_%s", (isPbPb?"PbPb":"PP")); string dsOSName = Form("dOS_%s_%s", DSTAG.c_str(), (isPbPb?"PbPb":"PP")); string dsOSNameCut = dsOSName+"_CTAUCUT"; string dsSSName = Form("dSS_%s_%s", DSTAG.c_str(), (isPbPb?"PbPb":"PP")); bool isWeighted = myws.data(dsOSName.c_str())->isWeighted(); bool isMC = (DSTAG.find("MC")!=std::string::npos); double normDSTot = 1.0; if (myws.data(dsOSNameCut.c_str())) { normDSTot = myws.data(dsOSName.c_str())->sumEntries()/myws.data(dsOSNameCut.c_str())->sumEntries(); } // Create the main plot of the fit RooPlot* frame = myws.var("invMass")->frame(Bins(nBins), Range(cut.dMuon.M.Min, cut.dMuon.M.Max)); myws.data(dsOSName.c_str())->plotOn(frame, Name("dOS"), DataError(RooAbsData::SumW2), XErrorSize(0), MarkerColor(kBlack), LineColor(kBlack), MarkerSize(1.2)); if (paperStyle) TGaxis::SetMaxDigits(3); // to display powers of 10 myws.pdf(pdfTotName.c_str())->plotOn(frame,Name("BKG"),Components(RooArgSet(*myws.pdf(Form("pdfMASS_Bkg_%s", (isPbPb?"PbPb":"PP"))))), FillStyle(paperStyle ? 0 : 1001), FillColor(kAzure-9), VLines(), DrawOption("LCF"), LineColor(kBlue), LineStyle(kDashed) ); if (!paperStyle) { if (incJpsi) { if ( myws.pdf(Form("pdfCTAUMASS_JpsiPR_%s", (isPbPb?"PbPb":"PP"))) ) { myws.pdf(pdfTotName.c_str())->plotOn(frame,Name("JPSIPR"),Components(RooArgSet(*myws.pdf(Form("pdfCTAUMASS_JpsiPR_%s", (isPbPb?"PbPb":"PP"))), *myws.pdf(Form("pdfCTAUMASS_Bkg_%s", (isPbPb?"PbPb":"PP"))))), ProjWData(RooArgSet(*myws.var("ctauErr")), *myws.data(dsOSName.c_str()), kTRUE), Normalization(normDSTot, RooAbsReal::NumEvent), LineColor(kRed+3), LineStyle(1), Precision(1e-4), NumCPU(32) ); } if ( myws.pdf(Form("pdfCTAUMASS_JpsiNoPR_%s", (isPbPb?"PbPb":"PP"))) ) { myws.pdf(pdfTotName.c_str())->plotOn(frame,Name("JPSINOPR"),Components(RooArgSet(*myws.pdf(Form("pdfCTAUMASS_JpsiNoPR_%s", (isPbPb?"PbPb":"PP"))), *myws.pdf(Form("pdfCTAUMASS_Bkg_%s", (isPbPb?"PbPb":"PP"))))), ProjWData(RooArgSet(*myws.var("ctauErr")), *myws.data(dsOSName.c_str()), kTRUE), Normalization(normDSTot, RooAbsReal::NumEvent), LineColor(kGreen+3), LineStyle(1), Precision(1e-4), NumCPU(32) ); } } if (incPsi2S) { if ( myws.pdf(Form("pdfCTAUMASS_Psi2SPR_%s", (isPbPb?"PbPb":"PP"))) ) { myws.pdf(pdfTotName.c_str())->plotOn(frame,Name("PSI2SPR"),Components(RooArgSet(*myws.pdf(Form("pdfCTAUMASS_Psi2SPR_%s", (isPbPb?"PbPb":"PP"))))), ProjWData(RooArgSet(*myws.var("ctauErr")), *myws.data(dsOSName.c_str()), kTRUE), Normalization(normDSTot, RooAbsReal::NumEvent), LineColor(kRed+3), LineStyle(1), Precision(1e-4), NumCPU(32) ); } if ( myws.pdf(Form("pdfCTAUMASS_Psi2SNoPR_%s", (isPbPb?"PbPb":"PP"))) ) { myws.pdf(pdfTotName.c_str())->plotOn(frame,Name("PSI2SNOPR"),Components(RooArgSet(*myws.pdf(Form("pdfCTAUMASS_Psi2SNoPR_%s", (isPbPb?"PbPb":"PP"))))), ProjWData(RooArgSet(*myws.var("ctauErr")), *myws.data(dsOSName.c_str()), kTRUE), Normalization(normDSTot, RooAbsReal::NumEvent), LineColor(kGreen+3), LineStyle(1), Precision(1e-4), NumCPU(32) ); } } } if (incSS) { myws.data(dsSSName.c_str())->plotOn(frame, Name("dSS"), MarkerColor(kRed), LineColor(kRed), MarkerSize(1.2)); } myws.data(dsOSName.c_str())->plotOn(frame, Name("dOS"), DataError(RooAbsData::SumW2), XErrorSize(0), MarkerColor(kBlack), LineColor(kBlack), MarkerSize(1.2)); myws.pdf(pdfTotName.c_str())->plotOn(frame,Name("PDF"), ProjWData(RooArgSet(*myws.var("ctauErr")), *myws.data(dsOSName.c_str()), kTRUE), Normalization(normDSTot, RooAbsReal::NumEvent), LineColor(kBlack), NumCPU(32) ); // Create the pull distribution of the fit RooPlot* frameTMP = (RooPlot*)frame->Clone("TMP"); int nBinsTMP = nBins; RooHist *hpull = frameTMP->pullHist(0, 0, true); hpull->SetName("hpull"); RooPlot* frame2 = myws.var("invMass")->frame(Title("Pull Distribution"), Bins(nBins), Range(cut.dMuon.M.Min, cut.dMuon.M.Max)); frame2->addPlotable(hpull, "PX"); // set the CMS style setTDRStyle(); // Create the main canvas TCanvas *cFig = new TCanvas(Form("cMassFig_%s", (isPbPb?"PbPb":"PP")), "cMassFig",800,800); TPad *pad1 = new TPad(Form("pad1_%s", (isPbPb?"PbPb":"PP")),"",0,paperStyle ? 0 : 0.23,1,1); TPad *pad2 = new TPad(Form("pad2_%s", (isPbPb?"PbPb":"PP")),"",0,0,1,.228); TLine *pline = new TLine(cut.dMuon.M.Min, 0.0, cut.dMuon.M.Max, 0.0); // TPad *pad4 = new TPad("pad4","This is pad4",0.55,0.46,0.97,0.87); TPad *pad4 = new TPad("pad4","This is pad4",0.55,paperStyle ? 0.29 : 0.36,0.97,paperStyle ? 0.70 : 0.77); pad4->SetFillStyle(0); pad4->SetLeftMargin(0.28); pad4->SetRightMargin(0.10); pad4->SetBottomMargin(0.21); pad4->SetTopMargin(0.072); frame->SetTitle(""); frame->GetXaxis()->CenterTitle(kTRUE); if (!paperStyle) { frame->GetXaxis()->SetTitle(""); frame->GetXaxis()->SetTitleSize(0.045); frame->GetXaxis()->SetTitleFont(42); frame->GetXaxis()->SetTitleOffset(3); frame->GetXaxis()->SetLabelOffset(3); frame->GetYaxis()->SetLabelSize(0.04); frame->GetYaxis()->SetTitleSize(0.04); frame->GetYaxis()->SetTitleOffset(1.7); frame->GetYaxis()->SetTitleFont(42); } else { frame->GetXaxis()->SetTitle("m_{#mu^{+}#mu^{-}} (GeV/c^{2})"); frame->GetXaxis()->SetTitleOffset(1.1); frame->GetYaxis()->SetTitleOffset(1.45); frame->GetXaxis()->SetTitleSize(0.05); frame->GetYaxis()->SetTitleSize(0.05); } setMassFrom2DRange(myws, frame, dsOSName, setLogScale); if (paperStyle) { double Ydown = 0.;//frame->GetMinimum(); double Yup = 0.9*frame->GetMaximum(); frame->GetYaxis()->SetRangeUser(Ydown,Yup); } cFig->cd(); pad2->SetTopMargin(0.02); pad2->SetBottomMargin(0.4); pad2->SetFillStyle(4000); pad2->SetFrameFillStyle(4000); if (!paperStyle) pad1->SetBottomMargin(0.015); //plot fit pad1->Draw(); pad1->cd(); frame->Draw(); printMassFrom2DParameters(myws, pad1, isPbPb, pdfTotName, isWeighted); pad1->SetLogy(setLogScale); // Drawing the text in the plot TLatex *t = new TLatex(); t->SetNDC(); t->SetTextSize(0.032); float dy = 0; t->SetTextSize(0.03); if (!paperStyle) { // do not print selection details for paper style t->DrawLatex(0.20, 0.86-dy, "2015 HI Soft Muon ID"); dy+=0.045; if (isPbPb) { t->DrawLatex(0.20, 0.86-dy, "HLT_HIL1DoubleMu0_v1"); dy+=2.0*0.045; } else { t->DrawLatex(0.20, 0.86-dy, "HLT_HIL1DoubleMu0_v1"); dy+=2.0*0.045; } } if (cut.dMuon.AbsRap.Min>0.1) {t->DrawLatex(0.5175, 0.86-dy, Form("%.1f < |y^{#mu#mu}| < %.1f",cut.dMuon.AbsRap.Min,cut.dMuon.AbsRap.Max)); dy+=0.045;} else {t->DrawLatex(0.5175, 0.86-dy, Form("|y^{#mu#mu}| < %.1f",cut.dMuon.AbsRap.Max)); dy+=0.045;} t->DrawLatex(0.5175, 0.86-dy, Form("%g < p_{T}^{#mu#mu} < %g GeV/c",cut.dMuon.Pt.Min,cut.dMuon.Pt.Max)); dy+=0.045; if (isPbPb) {t->DrawLatex(0.5175, 0.86-dy, Form("Cent. %d-%d%%", (int)(cut.Centrality.Start/2), (int)(cut.Centrality.End/2))); dy+=0.045;} // Drawing the Legend double ymin = 0.7602; if (incPsi2S && incJpsi && incSS) { ymin = 0.7202; } if (incPsi2S && incJpsi && !incSS) { ymin = 0.7452; } if (paperStyle) { ymin = 0.72; } TLegend* leg = new TLegend(0.5175, ymin, 0.7180, 0.8809); leg->SetTextSize(0.03); if (frame->findObject("dOS")) { leg->AddEntry(frame->findObject("dOS"), (incSS?"Opposite Charge":"Data"),"pe"); } if (incSS) { leg->AddEntry(frame->findObject("dSS"),"Same Charge","pe"); } if (frame->findObject("PDF")) { leg->AddEntry(frame->findObject("PDF"),"Total fit","l"); } if (frame->findObject("JPSIPR")) { leg->AddEntry(frame->findObject("JPSIPR"),"Prompt J/#psi","l"); } if (frame->findObject("JPSINOPR")) { leg->AddEntry(frame->findObject("JPSINOPR"),"Non-Prompt J/#psi","l"); } if (incBkg && frame->findObject("BKG")) { leg->AddEntry(frame->findObject("BKG"),"Background",paperStyle ? "l" : "fl"); } leg->Draw("same"); //Drawing the title TString label; if (isPbPb) { if (opt.PbPb.RunNb.Start==opt.PbPb.RunNb.End){ label = Form("PbPb Run %d", opt.PbPb.RunNb.Start); } else { label = Form("%s [%s %d-%d]", "PbPb", "HIOniaL1DoubleMu0", opt.PbPb.RunNb.Start, opt.PbPb.RunNb.End); } } else { if (opt.pp.RunNb.Start==opt.pp.RunNb.End){ label = Form("PP Run %d", opt.pp.RunNb.Start); } else { label = Form("%s [%s %d-%d]", "PP", "DoubleMu0", opt.pp.RunNb.Start, opt.pp.RunNb.End); } } // CMS_lumi(pad1, isPbPb ? 105 : 104, 33, label); CMS_lumi(pad1, isPbPb ? 108 : 107, 33, ""); if (!paperStyle) gStyle->SetTitleFontSize(0.05); pad1->Update(); cFig->cd(); if (!paperStyle) { //---plot pull pad2->Draw(); pad2->cd(); frame2->SetTitle(""); frame2->GetYaxis()->CenterTitle(kTRUE); frame2->GetYaxis()->SetTitleOffset(0.4); frame2->GetYaxis()->SetTitleSize(0.1); frame2->GetYaxis()->SetLabelSize(0.1); frame2->GetYaxis()->SetTitle("Pull"); frame2->GetXaxis()->CenterTitle(kTRUE); frame2->GetXaxis()->SetTitleOffset(1); frame2->GetXaxis()->SetTitleSize(0.12); frame2->GetXaxis()->SetLabelSize(0.1); frame2->GetXaxis()->SetTitle("m_{#mu^{+}#mu^{-}} (GeV/c^{2})"); frame2->GetYaxis()->SetRangeUser(-7.0, 7.0); frame2->Draw(); // *** Print chi2/ndof printChi2(myws, pad2, frameTMP, "invMass", dsOSName.c_str(), pdfTotName.c_str(), nBinsTMP, false); pline->Draw("same"); pad2->Update(); } // Save the plot in different formats gSystem->mkdir(Form("%sctauMass/%s/plot/root/", outputDir.c_str(), DSTAG.c_str()), kTRUE); cFig->SaveAs(Form("%sctauMass/%s/plot/root/PLOT_%s_%s_%s%s_pt%.0f%.0f_rap%.0f%.0f_cent%d%d.root", outputDir.c_str(), DSTAG.c_str(), "MASS", DSTAG.c_str(), (isPbPb?"PbPb":"PP"), plotLabel.c_str(), (cut.dMuon.Pt.Min*10.0), (cut.dMuon.Pt.Max*10.0), (cut.dMuon.AbsRap.Min*10.0), (cut.dMuon.AbsRap.Max*10.0), cut.Centrality.Start, cut.Centrality.End)); gSystem->mkdir(Form("%sctauMass/%s/plot/png/", outputDir.c_str(), DSTAG.c_str()), kTRUE); cFig->SaveAs(Form("%sctauMass/%s/plot/png/PLOT_%s_%s_%s%s_pt%.0f%.0f_rap%.0f%.0f_cent%d%d.png", outputDir.c_str(), DSTAG.c_str(), "MASS", DSTAG.c_str(), (isPbPb?"PbPb":"PP"), plotLabel.c_str(), (cut.dMuon.Pt.Min*10.0), (cut.dMuon.Pt.Max*10.0), (cut.dMuon.AbsRap.Min*10.0), (cut.dMuon.AbsRap.Max*10.0), cut.Centrality.Start, cut.Centrality.End)); gSystem->mkdir(Form("%sctauMass/%s/plot/pdf/", outputDir.c_str(), DSTAG.c_str()), kTRUE); cFig->SaveAs(Form("%sctauMass/%s/plot/pdf/PLOT_%s_%s_%s%s_pt%.0f%.0f_rap%.0f%.0f_cent%d%d.pdf", outputDir.c_str(), DSTAG.c_str(), "MASS", DSTAG.c_str(), (isPbPb?"PbPb":"PP"), plotLabel.c_str(), (cut.dMuon.Pt.Min*10.0), (cut.dMuon.Pt.Max*10.0), (cut.dMuon.AbsRap.Min*10.0), (cut.dMuon.AbsRap.Max*10.0), cut.Centrality.Start, cut.Centrality.End)); cFig->Clear(); cFig->Close(); };
int main(){ RooRealVar zero("zero","",0,0,150); //input parameters for the distribution double alpha_double = 2.38; double beta_double = 0.092; double lambda_double = 2.21; double theta_double = 1.12; double c_frac = 0.5; //RooRealVar fsig("fsig","signal fraction",0.3) ; string epsname = "plots/gamma_pion20"; hit_info multi_shower("fullsim/example_pi20Gev.root"); //hit_info multi_shower("fullsim/example_ele_20GeV.root"); double beta_gflash_factor = 1.49; double theta_gflash_factor = 16.42; beta_double = beta_double/beta_gflash_factor; theta_double = theta_double/theta_gflash_factor; // --- Observable --- RooRealVar depth("depth","depth [cm]",0,800); depth.removeMax(); // set infinite range // --- Weight --- RooRealVar* weight = new RooRealVar("weight","1/E dE/dr", 0.0, 1.0); // --- Gamma pdf --- //if one of the Values is set to const you can not ask for it in RooFitModel, otherwise the program will crash //RooRealVar alpha("alpha","alpha",alpha_double,0.0,4); RooRealVar alpha("alpha","alpha",0.0,20.); //alpha.removeMax(); // set infinite range //RooRealVar beta("beta","beta",1./beta_double,0.0,100.); RooRealVar beta("beta","beta",0.1,.1,3.5); //beta.removeMax(); // set infinite range RooRealVar mu("mu","mu",0); // no ranges means variable is fixed in fit RooRealVar nu("nu","nu",0); // no ranges means variable is fixed in fit //RooRealVar lambda("lambda","lambda",lambda_double,0.0,6.); RooRealVar lambda("lambda","lambda",0.0,40.); //lambda.removeMax(); // set infinite range //RooRealVar theta("theta","theta",1./theta_double,0.0,100.) ; RooRealVar theta("theta","theta",1.,47) ; //theta.removeMax(); // set infinite range RooGamma gamma_one("gamma_one","gamma_one pdf",depth,alpha,beta,mu) ; RooGamma gamma_two("gamma_two","gamma_two pdf",depth,lambda,theta,nu) ; RooRealVar fsig("fsig","signal fraction",c_frac,0.0,1.); //RooRealVar fsig("fsig","signal fraction",c_frac); RooAddPdf model("model","model",RooArgList(gamma_two,gamma_one),fsig) ; RooDataSet mean("mean","mean",RooArgSet(depth,weight),"weight"); TH1F* mean_fithist = new TH1F("mean_fithist"," mean fit hist",50,0,150); TH1F* log_alpha1 = new TH1F("log_alpha1"," log(#alpha_{1})",20,-1,3); TH1F* log_beta1 = new TH1F("log_beta1"," log(#beta_{1})",20,-1,3); TH2F* log_corr1 = new TH2F("log_corr1"," correlation #alpha_{1} #beta_{1}",20,-1,3,20,-1,3); TH1F* log_alpha2 = new TH1F("log_alpha2"," log(#alpha_{2})",20,-1,3); TH1F* log_beta2 = new TH1F("log_beta2"," log(#beta_{2})",20,-1,3); TH2F* log_corr2 = new TH2F("log_corr2"," correlation #alpha_{2} #beta_{2}",20,-1,3,20,-1,3); TH2F* mean_hist = new TH2F("mean_hist"," mean hist",100,0,150,100.,0.,.0015); TCanvas * can = new TCanvas("can", "can", 600, 500); can->cd(); set_style(); //can->Print(epsname+"["); double c_tot =0; unsigned int n_part =100; for(unsigned int p = 0; p<n_part ; ++p){ TLegend * legend = new TLegend(0.5,0.65,.88,0.88); legend->SetTextFont(72); legend->SetTextSize(0.04); legend->SetFillColor(kWhite); legend->SetBorderSize(0); one_shower shower = multi_shower.all_shower.at(p); //DataSet I am looking at RooDataSet full_sim_data("full_sim_data","full_sim_data",RooArgSet(depth,weight),"weight"); TH1F* datahisto = new TH1F("datahist","datahist",15,0,120); double sumHCAL=0; double deltar =-1; for(unsigned int i = 0; i < shower.mytype.size(); ++i){ sumHCAL += shower.myenergy.at(i); double x_val = shower.myz.at(i); double y_val = shower.myy.at(i); double z_val = shower.myz.at(i); z_val = z_val - shower.interactPoint; double distance=-1; if(sqrt(x_val*x_val+y_val*y_val+z_val*z_val)/10 < 200) distance = sqrt(x_val*x_val+y_val*y_val+z_val*z_val)/10; if(deltar < distance) deltar = z_val; } deltar=deltar/shower.mytype.size(); c_tot += shower.ePi0first_energy/n_part; fsig.setVal(shower.ePi0first_energy); fsig.setRange(shower.ePi0first_energy-0.05 > 0 ? shower.ePi0first_energy-0.05: 0,shower.ePi0first_energy+0.05<1?shower.ePi0first_energy+0.05:1); //fsig.setRange(1-shower.ePi0first_energy-0.05 > 0 ? 1-shower.ePi0first_energy-0.05: 0,1-shower.ePi0first_energy+0.05<1 ? 1-shower.ePi0first_energy+0.05:1); for(unsigned int i = 0; i < shower.mytype.size(); ++i){ double x_val = shower.myx.at(i); double y_val = shower.myy.at(i); double z_val = shower.myz.at(i); // if(shower.mytype.at(i) !=2)continue; z_val = z_val - shower.interactPoint; //if(z_val<=0) continue; depth.setVal(sqrt(x_val*x_val+y_val*y_val+z_val*z_val)/10); //depth.setVal(z_val); //cout <<depth.getVal()<<endl; datahisto->Fill(depth.getVal(),shower.myenergy.at(i)/sumHCAL/deltar); mean_fithist->Fill(depth.getVal(),shower.myenergy.at(i)/sumHCAL/deltar/n_part); mean_hist->Fill(depth.getVal(),shower.myenergy.at(i)/sumHCAL/deltar); full_sim_data.add(depth,shower.myenergy.at(i)/sumHCAL/deltar,0); mean.add(depth,shower.myenergy.at(i)/sumHCAL/deltar,0); } RooDataHist roodatahist("roodatahist","roodatahist",depth,Import(*datahisto)) ; //model.fitTo(roodatahist, Strategy(2) ); model.fitTo(full_sim_data); RooDataHist* full_sim_binned = full_sim_data.binnedClone("full_sim_binned","full sim binned"); //prepare to plot fits RooPlot * depthFrame = depth.frame(0,120,100); depthFrame->SetTitle(""); depthFrame->SetTitleOffset(1.2,"Y"); depthFrame->SetLabelSize(0.02,"Y"); depthFrame->SetYTitle("1/E dE/dr"); //zero.plotOn(depthFrame,LineStyle(kDashed),LineColor(kBlack)); //full_sim_data.plotOn(depthFrame); roodatahist.plotOn(depthFrame); //full_sim_binned->plotOn(depthFrame); model.plotOn(depthFrame,Components(gamma_one),LineStyle(kDashed),LineColor(kGreen),Name("gamma_one")); model.plotOn(depthFrame,Components(gamma_two),LineStyle(kDashed),LineColor(kRed),Name("gamma_two")); model.plotOn(depthFrame,Name("model")); stringstream gamma_one_text; gamma_one_text.precision(3); gamma_one_text << "#Gamma_{1} ("<<alpha.getVal()<<","<<(1/beta.getVal()*beta_gflash_factor)<<")"<<endl; stringstream gamma_two_text; gamma_two_text.precision(3); gamma_two_text << "#Gamma_{2} (" <<lambda.getVal()<<","<<(1/theta.getVal()*theta_gflash_factor)<< ")"<<endl; stringstream gamma_text; gamma_text.precision(2); gamma_text << "#Gamma_{1/2} c=" <<fsig.getVal() <<"("<<shower.ePi0first_energy<<")"<<endl; stringstream chi2; chi2.precision(2); chi2 << "#chi^{2} prob. = " << TMath::Prob(depthFrame->chiSquare(),14) <<endl; legend->AddEntry(depthFrame->findObject("gamma_one"),gamma_one_text.str().c_str(),"L"); legend->AddEntry(depthFrame->findObject("gamma_two"),gamma_two_text.str().c_str(),"L"); legend->AddEntry(depthFrame->findObject("model"),gamma_text.str().c_str(),"L"); legend->AddEntry((TObject*)0, chi2.str().c_str(), ""); cout << "alpha, beta "<< alpha.getVal() << " " << 1/beta.getVal()*beta_gflash_factor << std::endl; cout << "lambda, theta "<<lambda.getVal() << " " << 1/theta.getVal()*theta_gflash_factor << std::endl; cout <<"c, chi2 "<< fsig.getVal() << " "<<depthFrame->chiSquare()<< std::endl; cout <<"starting , interacting Points "<<shower.startingPoint<<" "<<shower.interactPoint <<endl; cout<< "pi0first, pi0tot "<<shower.ePi0first_energy <<" "<<shower.ePi0tot_energy<<endl; /* log_alpha1->Fill(log10(alpha.getVal())); log_alpha2->Fill(log10(lambda.getVal())); //cout<<log(1/beta.getVal()*beta_gflash_factor)<<endl; log_beta1 ->Fill(log10(1/beta.getVal()*beta_gflash_factor)); log_beta2 ->Fill(log10(1/theta.getVal()*theta_gflash_factor)); log_corr1 ->Fill(log10(alpha.getVal()),log10(1/beta.getVal()*beta_gflash_factor)); log_corr2 ->Fill(log10(lambda.getVal()),log10(1/theta.getVal()*theta_gflash_factor)); */ if(fsig.getVal()>0.1)log_alpha1->Fill(log(alpha.getVal())); if(fsig.getVal()<0.9)log_alpha2->Fill(log(lambda.getVal())); //cout<<log(1/beta.getVal()*beta_gflash_factor)<<endl; if(fsig.getVal()>0.1)log_beta1 ->Fill(log(1/beta.getVal()*beta_gflash_factor)); if(fsig.getVal()<0.9)log_beta2 ->Fill(log(1/theta.getVal()*theta_gflash_factor)); if(fsig.getVal()>0.1)log_corr1 ->Fill(log(alpha.getVal()),log(1/beta.getVal()*beta_gflash_factor)); if(fsig.getVal()<0.9)log_corr2 ->Fill(log(lambda.getVal()),log(1/theta.getVal()*theta_gflash_factor)); //prepare to dump all the plots in the ps file // one data sample and its fit is drawn /* datahisto->Draw(); datahisto0->SetLineColor(kRed); datahisto0->Draw("same"); datahisto1->SetLineColor(kGreen); datahisto1->Draw("same"); datahisto2->SetLineColor(kBlue); datahisto2->Draw("same"); can->Print(epsname); */ //if(depthFrame->chiSquare()>5) continue; depthFrame->Draw("HIST p"); legend->Draw(); stringstream particle_number; particle_number.precision(1); particle_number << p <<endl; can->Print((epsname+"_"+particle_number.str()+".pdf").c_str()); } RooDataHist roomeandatahist("roomeandatahist","roomeandatahist",depth,Import(*mean_fithist)) ; fsig.setVal(c_tot); alpha.removeMax(); // set infinite range beta.removeMax(); // set infinite range lambda.removeMax(); // set infinite range theta.removeMax(); // set infinite range //model.fitTo(roomeandatahist); //model.fitTo(mean,SumW2Error(kTRUE)); TLegend * mean_legend = new TLegend(0.5,0.65,.9,0.9); mean_legend->SetTextFont(72); mean_legend->SetTextSize(0.04); mean_legend->SetFillColor(kWhite); mean_legend->SetBorderSize(0); stringstream mean_gamma_one_text; mean_gamma_one_text.precision(3); mean_gamma_one_text << "#Gamma_{1} ("<<alpha.getVal()<<","<<(1/beta.getVal()*beta_gflash_factor)<<")"<<endl; stringstream mean_gamma_two_text; mean_gamma_two_text.precision(3); mean_gamma_two_text << "#Gamma_{2} (" <<lambda.getVal()<<","<<(1/theta.getVal()*theta_gflash_factor)<< ")"<<endl; stringstream mean_gamma_text; mean_gamma_text.precision(2); mean_gamma_text << "#Gamma_{1/2} c=" <<fsig.getVal() <<"("<< c_tot<<")"<<endl; stringstream mean_chi2; mean_chi2.precision(2); //mean_chi2 << "#chi^{2} " <<depthFrame->chiSquare() <<endl; RooPlot * meanFrame = depth.frame(0,120,200); //meanFrame->SetMaximum(1); meanFrame->SetTitle("Mean Fit"); meanFrame->SetYTitle("1/E dE/dr"); model.plotOn(meanFrame,Components(gamma_one),LineStyle(kDashed),LineColor(kGreen),Name("gamma_one")); model.plotOn(meanFrame,Components(gamma_two),LineStyle(kDashed),LineColor(kRed),Name("gamma_two")); model.plotOn(meanFrame,Name("model")); //mean.plotOn(meanFrame); //roomeandatahist.plotOn(meanFrame); mean_legend->AddEntry(meanFrame->findObject("gamma_one"),mean_gamma_one_text.str().c_str(),"L"); mean_legend->AddEntry(meanFrame->findObject("gamma_two"),mean_gamma_two_text.str().c_str(),"L"); mean_legend->AddEntry(meanFrame->findObject("model"),mean_gamma_text.str().c_str(),"L"); meanFrame->Draw(); mean_legend->Draw(); //datahisto->Draw(); //can->Print(epsname); //mean_hist->Draw("box"); //can->Print(epsname); can->Print((epsname+"_mean.pdf").c_str()); log_alpha1->Draw(); can->Print((epsname+"_alpha1_log.pdf").c_str()); log_beta1->Draw(); can->Print((epsname+"_beta1_log.pdf").c_str()); log_corr1->Draw("colz"); can->Print((epsname+"corr1_log.pdf").c_str()); log_alpha2->Draw(); can->Print((epsname+"apha2_log.pdf").c_str()); log_beta2->Draw(); can->Print((epsname+"beta2_log.pdf").c_str()); log_corr2->Draw("colz"); can->Print((epsname+"corr2_log.pdf").c_str()); ///can->Print(epsname+"]"); return 0; }
void RegressionPlottingAll(bool doEBEE=true, bool doEB=false, bool doEE=false){ TString name1; TString name2; TString name3; string dir; if (doEBEE){ name1="results_noPU_new.root"; name2="results_bx50_new.root"; name3="results_bx25_new.root"; dir="plots"; } if (doEB){ name1="resultsEB_noPU_new.root"; name2="resultsEB_bx50_new.root"; name3="resultsEB_bx25_new.root"; dir="plotsEB"; } if (doEE){ name1="resultsEE_noPU_new.root"; name2="resultsEE_bx50_new.root"; name3="resultsEE_bx25_new.root"; dir="plotsEE"; } TFile *fResults1 = TFile::Open(name1); TFile *fResults2 = TFile::Open(name2); TFile *fResults3 = TFile::Open(name3); //Plot eraw/etrue and ecor/etrue to quantify regression performance //Get Histograms TH1 *hecor1 = (TH1*)fResults1->Get("hCor_true"); TH1 *heraw1 = (TH1*)fResults1->Get("hRaw_true"); TH1 *hecor2 = (TH1*)fResults2->Get("hCor_true"); TH1 *heraw2 = (TH1*)fResults2->Get("hRaw_true"); TH1 *hecor3 = (TH1*)fResults3->Get("hCor_true"); TH1 *heraw3 = (TH1*)fResults3->Get("hRaw_true"); hecor1->Scale(1./hecor1->Integral()); heraw1->Scale(1./heraw1->Integral()); hecor2->Scale(1./hecor2->Integral()); heraw2->Scale(1./heraw2->Integral()); hecor3->Scale(1./hecor3->Integral()); heraw3->Scale(1./heraw3->Integral()); //Compute peak of the distributions by fitting histograms with double Crystal Ball double PeakRaw1,PeakRawErr1,PeakCor1,PeakCorErr1; double PeakRaw2,PeakRawErr2,PeakCor2,PeakCorErr2; double PeakRaw3,PeakRawErr3,PeakCor3,PeakCorErr3; RooRealVar *bias=new RooRealVar("Ecor/Etrue","Ecor/Etrue",0.8,1.2); const RooArgList *var=new RooArgList(*bias,""); RooPlot *plot = bias->frame(Range(0.9,1.07)); plot->SetTitle(""); plot->GetYaxis()->SetTitle(""); RooDataHist *Hraw1=new RooDataHist("","",*var,heraw1); RooDoubleCBFast *DoubleCBraw1=FitWithDCB(Hraw1,bias,PeakRaw1,PeakRawErr1); Hraw1->plotOn(plot,MarkerSize(0.8),MarkerColor(kBlue+2),MarkerStyle(24)); DoubleCBraw1->plotOn(plot,LineColor(kBlue+2),LineStyle(2),LineWidth(2),Name("hraw1")); RooDataHist *Hcor1=new RooDataHist("","",*var,hecor1); RooDoubleCBFast *DoubleCBcor1=FitWithDCB(Hcor1,bias,PeakCor1,PeakCorErr1); Hcor1->plotOn(plot,MarkerSize(0.6),MarkerColor(kBlue+2)); DoubleCBcor1->plotOn(plot,LineColor(kBlue+2),LineWidth(2),Name("hcor1")); RooDataHist *Hraw2=new RooDataHist("","",*var,heraw2); RooDoubleCBFast *DoubleCBraw2=FitWithDCB(Hraw2,bias,PeakRaw2,PeakRawErr2); Hraw2->plotOn(plot,MarkerSize(0.8),MarkerColor(kRed+1),MarkerStyle(24)); DoubleCBraw2->plotOn(plot,LineColor(kRed+1),LineStyle(2),LineWidth(2),Name("hraw2")); RooDataHist *Hcor2=new RooDataHist("","",*var,hecor2); RooDoubleCBFast *DoubleCBcor2=FitWithDCB(Hcor2,bias,PeakCor2,PeakCorErr2); Hcor2->plotOn(plot,MarkerSize(0.6),MarkerColor(kRed+1)); DoubleCBcor2->plotOn(plot,LineColor(kRed+1),LineWidth(2),Name("hcor2")); RooDataHist *Hraw3=new RooDataHist("","",*var,heraw3); RooDoubleCBFast *DoubleCBraw3=FitWithDCB(Hraw3,bias,PeakRaw3,PeakRawErr3); Hraw3->plotOn(plot,MarkerSize(0.8),MarkerColor(kOrange+1),MarkerStyle(24)); DoubleCBraw3->plotOn(plot,LineColor(kOrange+1),LineStyle(2),LineWidth(2),Name("hraw3")); RooDataHist *Hcor3=new RooDataHist("","",*var,hecor3); RooDoubleCBFast *DoubleCBcor3=FitWithDCB(Hcor3,bias,PeakCor3,PeakCorErr3); Hcor3->plotOn(plot,MarkerSize(0.6),MarkerColor(kOrange+1)); DoubleCBcor3->plotOn(plot,LineColor(kOrange+1),LineWidth(2),Name("hcor3")); //Compute Effective Sigma of the distributions /*double SigEffRaw1=effSigma(heraw1); double SigEffCor1=effSigma(hecor1); double SigEffRaw2=effSigma(heraw2); double SigEffCor2=effSigma(hecor2); double SigEffRaw3=effSigma(heraw3); double SigEffCor3=effSigma(hecor3); double SigEffErr=0.001;*/ //Legend and StatBox TLegend *leg = new TLegend(0.11,0.39,0.4,0.89); leg->SetBorderSize(0); leg->SetFillColor(0); leg->AddEntry(plot->findObject("hraw1"),"Eraw/Etrue, no PU","l"); leg->AddEntry(plot->findObject("hcor1"),"Ecor/Etrue, no PU","l"); leg->AddEntry(plot->findObject("hraw2"),"Eraw/Etrue, bx 50","l"); leg->AddEntry(plot->findObject("hcor2"),"Ecor/Etrue, bx 50","l"); leg->AddEntry(plot->findObject("hraw3"),"Eraw/Etrue, bx 25","l"); leg->AddEntry(plot->findObject("hcor3"),"Ecor/Etrue, bx 25","l"); //leg->SetTextFont(62); //leg->SetTextSize(0.06); plot->addObject(leg); /*TPaveText *stats = new TPaveText(0.58,0.39,0.89,0.89,"NDC"); stats->SetBorderSize(0); stats->SetFillColor(0); stats->AddText(Form("Peak Raw = %.4f +/- %.0e",PeakRaw,PeakRawErr)); stats->AddText(Form("Peak Cor = %.4f +/- %.0e",PeakCor,PeakCorErr)); stats->AddText(Form("Sigma Eff Raw = %.3f +/- %.3f",SigEffRaw,SigEffErr)); stats->AddText(Form("Sigma Eff Cor = %.3f +/- %.3f",SigEffCor,SigEffErr)); stats->SetTextSize(0.035); plot->addObject(stats);*/ //Plot TCanvas *cresponse=new TCanvas; plot->Draw(); cresponse->SaveAs(Form("plotsAll/%s/Performance.pdf",dir.c_str())); cresponse->SaveAs(Form("plotsAll/%s/Performance.png",dir.c_str())); //Plot ecor/eraw /* TH1 *hecor_raw = (TH1*)fResults->Get("hCor_raw"); TCanvas *canCor=new TCanvas; hecor_raw->Draw("HIST"); hecor_raw->SetLineWidth(2); hecor_raw->GetXaxis()->SetTitle("Ecor/Eraw"); hecor_raw->SetTitle("Ecor/Eraw"); canCor->SaveAs(Form("plotsAll/%s/Correction.png",dir.c_str())); */ //Plot |ecor-etrue|/eraw and |eraw-etrue|/eraw TH1 *hres1 = (TH1*)fResults1->Get("hRes"); TH1 *hres2 = (TH1*)fResults2->Get("hRes"); TH1 *hres3 = (TH1*)fResults3->Get("hRes"); hres1->Scale(1./hres1->Integral()); hres2->Scale(1./hres2->Integral()); hres3->Scale(1./hres3->Integral()); TCanvas *canR=new TCanvas; canR->SetLogy(); hres1->Draw("HIST,SAME"); hres1->SetLineWidth(2); hres1->SetLineColor(kBlue+2); hres1->GetXaxis()->SetRangeUser(0,0.05); hres2->Draw("HIST,SAME"); hres2->SetLineWidth(2); hres2->SetLineColor(kRed+1); hres2->GetXaxis()->SetRangeUser(0,0.05); hres3->Draw("HIST,SAME"); hres3->SetLineWidth(2); hres3->SetLineColor(kOrange+1); hres3->GetXaxis()->SetRangeUser(0,0.05); hres1->GetXaxis()->SetTitle("#sigma(E)/E"); hres1->SetTitle(""); hres1->GetYaxis()->SetTitle(""); hres1->SetStats(0); TLegend *leg2 = new TLegend(0.59,0.11,0.89,0.41); leg2->SetBorderSize(0); leg2->SetFillColor(0); leg2->AddEntry(hres1,"#sigma(E)/E, no PU","l"); leg2->AddEntry(hres2,"#sigma(E)/E, bx 50","l"); leg2->AddEntry(hres3,"#sigma(E)/E, bx 25","l"); leg2->Draw(); canR->SaveAs(Form("plotsAll/%s/Resolution.pdf",dir.c_str())); canR->SaveAs(Form("plotsAll/%s/Resolution.png",dir.c_str())); // Plot Correction vs input variables /* TCanvas *canCoreta=new TCanvas; gStyle->SetOptStat(0); TProfile *profCorEta=(TProfile*)fResults->Get("profEta"); TProfile *profRawEta=(TProfile*)fResults->Get("profEta0"); profRawEta->Draw(); profCorEta->Draw("same"); profRawEta->GetXaxis()->SetTitle("Eta"); profRawEta->GetYaxis()->SetTitle("E/Eraw"); profRawEta->SetTitle("Profile of E/Eraw vs Eta"); profCorEta->SetMarkerStyle(8); profCorEta->SetLineColor(kRed); profCorEta->SetMarkerColor(kRed); profRawEta->SetMarkerStyle(4); profRawEta->SetLineColor(kBlue); profRawEta->SetMarkerColor(kBlue); TLegend *leg2 = new TLegend(0.68,0.12,0.88,0.27); leg2->SetBorderSize(0); leg2->SetFillColor(0); leg2->AddEntry(profRawEta,"Eraw/Etrue","lp"); leg2->AddEntry(profCorEta,"Ecor/Etrue","lp"); leg2->SetTextFont(62); //leg2->SetTextSize(0.06); leg2->Draw(); canCoreta->SaveAs(Form("plotsAll/%s/CorEta.png",dir.c_str())); TCanvas *canCorPhi=new TCanvas; gStyle->SetOptStat(0); TProfile *profCorPhi=(TProfile*)fResults->Get("profPhi"); TProfile *profRawPhi=(TProfile*)fResults->Get("profPhi0"); profRawPhi->Draw(); profCorPhi->Draw("same"); profRawPhi->GetXaxis()->SetTitle("Phi"); profRawPhi->GetYaxis()->SetTitle("E/Eraw"); profRawPhi->SetTitle("Profile of E/Eraw vs Phi"); profCorPhi->SetMarkerStyle(8); profCorPhi->SetLineColor(kRed); profCorPhi->SetMarkerColor(kRed); profRawPhi->SetMarkerStyle(4); profRawPhi->SetLineColor(kBlue); profRawPhi->SetMarkerColor(kBlue); leg2->Draw(); canCorPhi->SaveAs(Form("plotsAll/%s/CorPhi.png",dir.c_str())); TCanvas *canCorEtaWidth=new TCanvas; gStyle->SetOptStat(0); TProfile *profCorEtaWidth=(TProfile*)fResults->Get("profEtaWidth"); TProfile *profRawEtaWidth=(TProfile*)fResults->Get("profEtaWidth0"); profRawEtaWidth->Draw(); profCorEtaWidth->Draw("same"); profRawEtaWidth->GetXaxis()->SetTitle("EtaWidth"); profRawEtaWidth->GetYaxis()->SetTitle("E/Eraw"); profRawEtaWidth->SetTitle("Profile of E/Eraw vs EtaWidth"); profCorEtaWidth->SetMarkerStyle(8); profCorEtaWidth->SetLineColor(kRed); profCorEtaWidth->SetMarkerColor(kRed); profRawEtaWidth->SetMarkerStyle(4); profRawEtaWidth->SetLineColor(kBlue); profRawEtaWidth->SetMarkerColor(kBlue); leg2->Draw(); canCorEtaWidth->SaveAs(Form("plotsAll/%s/CorEtaWidth.png",dir.c_str())); TCanvas *canCorPhiWidth=new TCanvas; gStyle->SetOptStat(0); TProfile *profCorPhiWidth=(TProfile*)fResults->Get("profPhiWidth"); TProfile *profRawPhiWidth=(TProfile*)fResults->Get("profPhiWidth0"); profRawPhiWidth->Draw(); profCorPhiWidth->Draw("same"); profRawPhiWidth->GetXaxis()->SetTitle("PhiWidth"); profRawPhiWidth->GetYaxis()->SetTitle("E/Eraw"); profRawPhiWidth->SetTitle("Profile of E/Eraw vs PhiWidth"); profCorPhiWidth->SetMarkerStyle(8); profCorPhiWidth->SetLineColor(kRed); profCorPhiWidth->SetMarkerColor(kRed); profRawPhiWidth->SetMarkerStyle(4); profRawPhiWidth->SetLineColor(kBlue); profRawPhiWidth->SetMarkerColor(kBlue); leg2->Draw(); canCorPhiWidth->SaveAs(Form("plotsAll/%s/CorPhiWidth.png",dir.c_str())); TCanvas *canCorR9=new TCanvas; gStyle->SetOptStat(0); TProfile *profCorR9=(TProfile*)fResults->Get("profR9"); TProfile *profRawR9=(TProfile*)fResults->Get("profR90"); profRawR9->Draw(); profCorR9->Draw("same"); profRawR9->GetXaxis()->SetTitle("R9"); profRawR9->GetYaxis()->SetTitle("E/Eraw"); profRawR9->SetTitle("Profile of E/Eraw vs R9"); profCorR9->SetMarkerStyle(8); profCorR9->SetLineColor(kRed); profCorR9->SetMarkerColor(kRed); profRawR9->SetMarkerStyle(4); profRawR9->SetLineColor(kBlue); profRawR9->SetMarkerColor(kBlue); leg2->Draw(); canCorR9->SaveAs(Form("plotsAll/%s/CorR9.png",dir.c_str())); TCanvas *canCorNvtx=new TCanvas; gStyle->SetOptStat(0); TProfile *profCorNvtx=(TProfile*)fResults->Get("profNvtx"); TProfile *profRawNvtx=(TProfile*)fResults->Get("profNvtx0"); profRawNvtx->Draw(); profCorNvtx->Draw("same"); profRawNvtx->GetXaxis()->SetTitle("Nvtx"); profRawNvtx->GetYaxis()->SetTitle("E/Eraw"); profRawNvtx->SetTitle("Profile of E/Eraw vs Nvtx"); profCorNvtx->SetMarkerStyle(8); profCorNvtx->SetLineColor(kRed); profCorNvtx->SetMarkerColor(kRed); profRawNvtx->SetMarkerStyle(4); profRawNvtx->SetLineColor(kBlue); profRawNvtx->SetMarkerColor(kBlue); leg2->Draw(); canCorNvtx->SaveAs(Form("plotsAll/%s/CorNvtx.png",dir.c_str())); TCanvas *canCorPt=new TCanvas; gStyle->SetOptStat(0); TProfile *profCorPt=(TProfile*)fResults->Get("profPt"); TProfile *profRawPt=(TProfile*)fResults->Get("profPt0"); profRawPt->Draw(); profCorPt->Draw("same"); profRawPt->GetXaxis()->SetTitle("Pt"); profRawPt->GetYaxis()->SetTitle("E/Eraw"); profRawPt->SetTitle("Profile of E/Eraw vs Pt"); profCorPt->SetMarkerStyle(8); profCorPt->SetLineColor(kRed); profCorPt->SetMarkerColor(kRed); profRawPt->SetMarkerStyle(4); profRawPt->SetLineColor(kBlue); profRawPt->SetMarkerColor(kBlue); leg2->Draw(); canCorPt->SaveAs(Form("plotsAll/%s/CorPt.png",dir.c_str())); */ //Plot Bias and Resolution vs Pt /* TCanvas *canResPt=new TCanvas; TProfile *profResPt=(TProfile*)fResults->Get("profPtRes"); profResPt->Draw(); profResPt->GetXaxis()->SetTitle("Pt"); profResPt->GetYaxis()->SetTitle("|Ecor-Etrue|/Eraw"); profResPt->SetTitle("Profile of SigmaE/E vs Pt"); profResPt->SetMarkerStyle(3); profResPt->SetLineColor(kRed); canResPt->SaveAs(Form("plotsAll/%s/ResPt.png",dir.c_str())); */ //Plot Bias and resolution in bins of Pt and eta double errpt[9]; double pt[9]; double sigeff11[9]; double errsigeff11[9]; double sigeff12[9]; double errsigeff12[9]; double sigeff13[9]; double errsigeff13[9]; double sigeff14[9]; double errsigeff14[9]; double mean11[9]; double errmean11[9]; double mean12[9]; double errmean12[9]; double mean13[9]; double errmean13[9]; double mean14[9]; double errmean14[9]; double sigeff21[9]; double errsigeff21[9]; double sigeff22[9]; double errsigeff22[9]; double sigeff23[9]; double errsigeff23[9]; double sigeff24[9]; double errsigeff24[9]; double mean21[9]; double errmean21[9]; double mean22[9]; double errmean22[9]; double mean23[9]; double errmean23[9]; double mean24[9]; double errmean24[9]; double sigeff31[9]; double errsigeff31[9]; double sigeff32[9]; double errsigeff32[9]; double sigeff33[9]; double errsigeff33[9]; double sigeff34[9]; double errsigeff34[9]; double mean31[9]; double errmean31[9]; double mean32[9]; double errmean32[9]; double mean33[9]; double errmean33[9]; double mean34[9]; double errmean34[9]; /* TCanvas *can10 = new TCanvas("can7","can7",1200,700); can10->Divide(5,4); TCanvas *can11 = new TCanvas("can8","can8",1200,700); can11->Divide(5,4); TCanvas *can12 = new TCanvas("can9","can9",1200,700); can12->Divide(5,4); TCanvas *can13 = new TCanvas("can10","can10",1200,700); can13->Divide(5,4); */ for (int i=1;i<10;i++){ pt[i-1]=(i+1)*20.; errpt[i-1]=20; TH1 *HistPt11=(TH1*)fResults1->Get(Form("hBias_Pt%i_eta1",(i+1)*20)); //RooDataHist *HistPtclone11=new RooDataHist("","",*var,HistPt11); //RooDoubleCBFast *CB11=FitWithDCB(HistPtclone11,bias,mean11[i-1],errmean11[i-1]); sigeff11[i-1]=effSigma(HistPt11); errsigeff11[i-1]=0.4/199; TH1 *HistPt12=(TH1*)fResults1->Get(Form("hBias_Pt%i_eta2",(i+1)*20)); //RooDataHist *HistPtclone12=new RooDataHist("","",*var,HistPt12); //RooDoubleCBFast *CB12=FitWithDCB(HistPtclone12,bias,mean12[i-1],errmean12[i-1]); sigeff12[i-1]=effSigma(HistPt12); errsigeff12[i-1]=0.4/99; TH1 *HistPt13=(TH1*)fResults1->Get(Form("hBias_Pt%i_eta3",(i+1)*20)); //RooDataHist *HistPtclone13=new RooDataHist("","",*var,HistPt13); //RooDoubleCBFast *CB13=FitWithDCB(HistPtclone13,bias,mean13[i-1],errmean13[i-1]); sigeff13[i-1]=effSigma(HistPt13); errsigeff13[i-1]=0.4/99; TH1 *HistPt14=(TH1*)fResults1->Get(Form("hBias_Pt%i_eta4",(i+1)*20)); //RooDataHist *HistPtclone14=new RooDataHist("","",*var,HistPt14); //RooDoubleCBFast *CB14=FitWithDCB(HistPtclone14,bias,mean14[i-1],errmean14[i-1]); sigeff14[i-1]=effSigma(HistPt14); errsigeff14[i-1]=0.4/99; TH1 *HistPt21=(TH1*)fResults2->Get(Form("hBias_Pt%i_eta1",(i+1)*20)); //RooDataHist *HistPtclone21=new RooDataHist("","",*var,HistPt21); //RooDoubleCBFast *CB21=FitWithDCB(HistPtclone21,bias,mean21[i-1],errmean21[i-1]); sigeff21[i-1]=effSigma(HistPt21); errsigeff21[i-1]=0.4/199; TH1 *HistPt22=(TH1*)fResults2->Get(Form("hBias_Pt%i_eta2",(i+1)*20)); //RooDataHist *HistPtclone22=new RooDataHist("","",*var,HistPt22); //RooDoubleCBFast *CB22=FitWithDCB(HistPtclone22,bias,mean22[i-1],errmean22[i-1]); sigeff22[i-1]=effSigma(HistPt22); errsigeff22[i-1]=0.4/99; TH1 *HistPt23=(TH1*)fResults2->Get(Form("hBias_Pt%i_eta3",(i+1)*20)); //RooDataHist *HistPtclone23=new RooDataHist("","",*var,HistPt23); //RooDoubleCBFast *CB23=FitWithDCB(HistPtclone23,bias,mean23[i-1],errmean23[i-1]); sigeff23[i-1]=effSigma(HistPt23); errsigeff23[i-1]=0.4/99; TH1 *HistPt24=(TH1*)fResults2->Get(Form("hBias_Pt%i_eta4",(i+1)*20)); //RooDataHist *HistPtclone24=new RooDataHist("","",*var,HistPt24); //RooDoubleCBFast *CB24=FitWithDCB(HistPtclone24,bias,mean24[i-1],errmean24[i-1]); sigeff24[i-1]=effSigma(HistPt24); errsigeff24[i-1]=0.4/99; TH1 *HistPt31=(TH1*)fResults3->Get(Form("hBias_Pt%i_eta1",(i+1)*20)); //RooDataHist *HistPtclone31=new RooDataHist("","",*var,HistPt31); //RooDoubleCBFast *CB31=FitWithDCB(HistPtclone31,bias,mean31[i-1],errmean31[i-1]); sigeff31[i-1]=effSigma(HistPt31); errsigeff31[i-1]=0.4/199; TH1 *HistPt32=(TH1*)fResults3->Get(Form("hBias_Pt%i_eta2",(i+1)*20)); //RooDataHist *HistPtclone32=new RooDataHist("","",*var,HistPt32); //RooDoubleCBFast *CB32=FitWithDCB(HistPtclone32,bias,mean32[i-1],errmean32[i-1]); sigeff32[i-1]=effSigma(HistPt32); errsigeff32[i-1]=0.4/99; TH1 *HistPt33=(TH1*)fResults3->Get(Form("hBias_Pt%i_eta3",(i+1)*20)); //RooDataHist *HistPtclone33=new RooDataHist("","",*var,HistPt33); //RooDoubleCBFast *CB33=FitWithDCB(HistPtclone33,bias,mean33[i-1],errmean33[i-1]); sigeff33[i-1]=effSigma(HistPt33); errsigeff33[i-1]=0.4/99; TH1 *HistPt34=(TH1*)fResults3->Get(Form("hBias_Pt%i_eta4",(i+1)*20)); //RooDataHist *HistPtclone34=new RooDataHist("","",*var,HistPt34); //RooDoubleCBFast *CB34=FitWithDCB(HistPtclone34,bias,mean34[i-1],errmean34[i-1]); sigeff34[i-1]=effSigma(HistPt34); errsigeff34[i-1]=0.4/99; } TCanvas *can15=new TCanvas; can15->Divide(2,2); can15->cd(1); TGraphErrors *graphRes_Pt11 = new TGraphErrors(9,pt,sigeff11,errpt,errsigeff11); graphRes_Pt11->SetMarkerStyle(8); graphRes_Pt11->SetMarkerColor(kBlue+2); graphRes_Pt11->SetLineColor(kBlue+2); TGraphErrors *graphRes_Pt21 = new TGraphErrors(9,pt,sigeff21,errpt,errsigeff21); graphRes_Pt21->SetMarkerStyle(8); graphRes_Pt21->SetMarkerColor(kRed+1); graphRes_Pt21->SetLineColor(kRed+1); TGraphErrors *graphRes_Pt31 = new TGraphErrors(9,pt,sigeff31,errpt,errsigeff31); graphRes_Pt31->SetMarkerStyle(8); graphRes_Pt31->SetMarkerColor(kOrange+1); graphRes_Pt31->SetLineColor(kOrange+1); TMultiGraph *graphRes_Pt1=new TMultiGraph(); graphRes_Pt1->Add(graphRes_Pt11); graphRes_Pt1->Add(graphRes_Pt21); graphRes_Pt1->Add(graphRes_Pt31); graphRes_Pt1->Draw("AP"); //graphRes_Pt1->GetXaxis()->SetTitle("pt"); //graphRes_Pt1->GetYaxis()->SetTitle("Ecor/Etrue effective width"); graphRes_Pt1->SetTitle("Ecor/Etrue effective width vs Pt for |#eta|<1;pt;Ecor/Etrue effective width"); TLegend *leg3 = new TLegend(0.69,0.69,0.89,0.89); leg3->SetBorderSize(0); leg3->SetFillColor(0); leg3->AddEntry(graphRes_Pt11, "no PU","lp"); leg3->AddEntry(graphRes_Pt21, "bx 50","lp"); leg3->AddEntry(graphRes_Pt31, "bx 25","lp"); leg3->Draw(); can15->cd(2); TGraphErrors *graphRes_Pt12 = new TGraphErrors(9,pt,sigeff12,errpt,errsigeff12); graphRes_Pt12->SetMarkerStyle(8); graphRes_Pt12->SetMarkerColor(kBlue+2); graphRes_Pt12->SetLineColor(kBlue+2); TGraphErrors *graphRes_Pt22 = new TGraphErrors(9,pt,sigeff22,errpt,errsigeff22); graphRes_Pt22->SetMarkerStyle(8); graphRes_Pt22->SetMarkerColor(kRed+1); graphRes_Pt22->SetLineColor(kRed+1); TGraphErrors *graphRes_Pt32 = new TGraphErrors(9,pt,sigeff32,errpt,errsigeff32); graphRes_Pt32->SetMarkerStyle(8); graphRes_Pt32->SetMarkerColor(kOrange+1); graphRes_Pt32->SetLineColor(kOrange+1); TMultiGraph *graphRes_Pt2=new TMultiGraph(); graphRes_Pt2->Add(graphRes_Pt12); graphRes_Pt2->Add(graphRes_Pt22); graphRes_Pt2->Add(graphRes_Pt32); graphRes_Pt2->Draw("AP"); //graphRes_Pt2->GetXaxis()->SetTitle("pt"); //graphRes_Pt2->GetYaxis()->SetTitle("Ecor/Etrue effective width"); graphRes_Pt2->SetTitle("Ecor/Etrue effective width vs Pt for 1<|#eta|<1.5;pt;Ecor/Etrue effective width"); leg3->Draw(); can15->cd(3); TGraphErrors *graphRes_Pt13 = new TGraphErrors(9,pt,sigeff13,errpt,errsigeff13); graphRes_Pt13->SetMarkerStyle(8); graphRes_Pt13->SetMarkerColor(kBlue+2); graphRes_Pt13->SetLineColor(kBlue+2); TGraphErrors *graphRes_Pt23 = new TGraphErrors(9,pt,sigeff23,errpt,errsigeff23); graphRes_Pt23->SetMarkerStyle(8); graphRes_Pt23->SetMarkerColor(kRed+1); graphRes_Pt23->SetLineColor(kRed+1); TGraphErrors *graphRes_Pt33 = new TGraphErrors(9,pt,sigeff33,errpt,errsigeff33); graphRes_Pt33->SetMarkerStyle(8); graphRes_Pt33->SetMarkerColor(kOrange+1); graphRes_Pt33->SetLineColor(kOrange+1); TMultiGraph *graphRes_Pt3=new TMultiGraph(); graphRes_Pt3->Add(graphRes_Pt13); graphRes_Pt3->Add(graphRes_Pt23); graphRes_Pt3->Add(graphRes_Pt33); graphRes_Pt3->Draw("AP"); //graphRes_Pt3->GetXaxis()->SetTitle("pt"); //graphRes_Pt3->GetYaxis()->SetTitle("Ecor/Etrue effective width"); graphRes_Pt3->SetTitle("Ecor/Etrue effective width vs Pt for 1.5<|#eta|<2;pt;Ecor/Etrue effective width"); leg3->Draw(); can15->cd(4); TGraphErrors *graphRes_Pt14 = new TGraphErrors(9,pt,sigeff14,errpt,errsigeff14); graphRes_Pt14->SetMarkerStyle(8); graphRes_Pt14->SetMarkerColor(kBlue+2); graphRes_Pt14->SetLineColor(kBlue+2); TGraphErrors *graphRes_Pt24 = new TGraphErrors(9,pt,sigeff24,errpt,errsigeff24); graphRes_Pt24->SetMarkerStyle(8); graphRes_Pt24->SetMarkerColor(kRed+1); graphRes_Pt24->SetLineColor(kRed+1); TGraphErrors *graphRes_Pt34 = new TGraphErrors(9,pt,sigeff34,errpt,errsigeff34); graphRes_Pt34->SetMarkerStyle(8); graphRes_Pt34->SetMarkerColor(kOrange+1); graphRes_Pt34->SetLineColor(kOrange+1); TMultiGraph *graphRes_Pt4=new TMultiGraph(); graphRes_Pt4->Add(graphRes_Pt14); graphRes_Pt4->Add(graphRes_Pt24); graphRes_Pt4->Add(graphRes_Pt34); graphRes_Pt4->Draw("AP"); //graphRes_Pt4->GetXaxis()->SetTitle("pt"); //graphRes_Pt4->GetYaxis()->SetTitle("Ecor/Etrue effective width"); graphRes_Pt4->SetTitle("Ecor/Etrue effective width vs Pt for 1.5<|#eta|;pt;Ecor/Etrue effective width"); leg3->Draw(); can15->SaveAs(Form("plotsAll/%s/Res_Pt_Eta.pdf",dir.c_str())); can15->SaveAs(Form("plotsAll/%s/Res_Pt_Eta.png",dir.c_str())); /* TCanvas *can14=new TCanvas; can14->Divide(2,2); can14->cd(1); TGraphErrors *graphCor_Pt1 = new TGraphErrors(9,pt,mean1,errpt,errmean1); graphCor_Pt1->Draw("AL*"); graphCor_Pt1->SetMarkerStyle(8); graphCor_Pt1->GetXaxis()->SetTitle("pt"); graphCor_Pt1->GetYaxis()->SetTitle("Ecor/Etrue mean"); graphCor_Pt1->SetTitle("Ecor/Etrue peak value vs Pt for 0<|eta|<1"); can14->cd(2); TGraphErrors *graphCor_Pt2 = new TGraphErrors(9,pt,mean2,errpt,errmean2); graphCor_Pt2->Draw("AL*"); graphCor_Pt2->SetMarkerStyle(8); graphCor_Pt2->GetXaxis()->SetTitle("pt"); graphCor_Pt2->GetYaxis()->SetTitle("Ecor/Etrue mean"); graphCor_Pt2->SetTitle("Ecor/Etrue peak value vs Pt for 1<|eta|<1.48"); can14->cd(3); TGraphErrors *graphCor_Pt3 = new TGraphErrors(9,pt,mean3,errpt,errmean3); graphCor_Pt3->Draw("AL*"); graphCor_Pt3->SetMarkerStyle(8); graphCor_Pt3->GetXaxis()->SetTitle("pt"); graphCor_Pt3->GetYaxis()->SetTitle("Ecor/Etrue mean"); graphCor_Pt3->SetTitle("Ecor/Etrue peak value vs Pt for 1.48<|eta|<2"); can14->cd(4); TGraphErrors *graphCor_Pt4 = new TGraphErrors(9,pt,mean4,errpt,errmean4); graphCor_Pt4->Draw("AL*"); graphCor_Pt4->SetMarkerStyle(8); graphCor_Pt4->GetXaxis()->SetTitle("pt"); graphCor_Pt4->GetYaxis()->SetTitle("Ecor/Etrue mean"); graphCor_Pt4->SetTitle("Ecor/Etrue peak value vs Pt for 2<|eta|<2.5"); can14->SaveAs(Form("plotsAll/%s/Bias_Pt_Eta.png",dir.c_str())); */ }
void fit_mass(TString fileN="") {//suffix added before file extension, e.g., '.pdf' TString placeholder;//to add strings before using them, e.g., for saving text files gROOT->SetBatch(kTRUE); gROOT->ProcessLine(".x /afs/cern.ch/user/m/mwilkins/cmtuser/src/lhcbStyle.C"); // gStyle->SetPadTickX(1); // gStyle->SetPadTickY(1); // gStyle->SetPadLeftMargin(0.15); // gStyle->SetTextSize(0.3); // //open file and get histogram // TFile *inHistos = new TFile("/afs/cern.ch/work/m/mwilkins/Lb2JpsiLtr/data/histos_data.root", "READ"); // TH1F * h100 = (TH1F*)inHistos->Get("h70"); // cout<<"data histogram gotten"<<endl; //unbinned TFile *hastree = new TFile("/afs/cern.ch/work/m/mwilkins/Lb2JpsiLtr/data/cutfile_Optimized.root", "READ"); TTree * h100 = (TTree*)hastree->Get("mytree"); cout<<"tree gotten"<<endl; TFile *SMChistos= new TFile("/afs/cern.ch/work/m/mwilkins/Lb2JpsiLtr/MC/withKScut/histos_SMCfile_fullMC.root", "READ"); cout<<"SMC file opened"<<endl; TH1F *SMCh = (TH1F*)SMChistos->Get("h00"); cout<<"SMC hist gotten"<<endl; RooRealVar *mass = new RooRealVar("Bs_LOKI_MASS_JpsiConstr","m(J/#psi #Lambda)",4100,6100,"MeV"); mass->setRange("bkg1",4300,4800); mass->setRange("bkg2",5700,5950); mass->setRange("bkg3",4300,5500); mass->setRange("bkg4",5100,5500); mass->setRange("L",5350,5950); mass->setRange("tot",4300,5950); cout<<"mass declared"<<endl; // RooDataHist *data = new RooDataHist("data","1D",RooArgList(*mass),h100); //unbinned RooDataSet *data = new RooDataSet("data","1D",h100,*mass); cout<<"data declared"<<endl; RooDataHist *SMC = new RooDataHist("SMC","1D",RooArgList(*mass),SMCh); cout<<"SMC hist assigned to RooDataHist"<<endl; // Construct Pdf Model // /\0 //gaussian RooRealVar mean1L("mean1L","/\\ gaus 1: mean",5621.103095,5525,5700); RooRealVar sig1L("sig1L","/\\ gaus 1: sigma",6.898126,0,100); RooGaussian gau1L("gau1L","#Lambda signal: gaussian 1",*mass,mean1L,sig1L); RooFormulaVar mean2L("mean2L","@0",mean1L); RooRealVar sig2L("sig2L","/\\ gaus 2: sigma",14.693117,0,100); RooGaussian gau2L("gau2L","#Lambda signal: gaussian 2",*mass,mean2L,sig2L); RooRealVar f1L("f1L","/\\ signal: fraction gaussian 1",0.748776,0,1); RooAddPdf sigL("sigL","#Lambda signal",RooArgList(gau1L,gau2L),RooArgList(f1L)); // //CB // RooRealVar mean3L("mean3L","/\\ CB: mean",5621.001,5525,5700); // RooRealVar sig3L("sig3L","/\\ CB: sigma",5.161,0,100); // RooRealVar alphaL3("alphaL3","/\\ CB: alpha",2.077,0,1000); // RooRealVar nL3("nL1","/\\ CB: n",0.286,0,1000); // RooCBShape CBL("CBL","#Lambda signal: CB",*mass,mean3L,sig3L,alphaL3,nL3); // RooRealVar mean4L("mean4L","/\\ gaus: mean",5621.804,5525,5700); // RooRealVar sig4L("sig4L","/\\ gaus: sigma",10.819,0,100); // RooGaussian gauL("gauL","#Lambda signal: gaussian",*mass,mean4L,sig4L); // RooRealVar f1L("f1L","/\\ signal: fraction CB",0.578,0,1); // RooAddPdf sigL("sigL","#Lambda signal",RooArgList(CBL,gauL),RooArgList(f1L)); // sigma0 //using RooHistPdf from MC--no need to build pdf here RooHistPdf sigS = makeroohistpdf(SMC,mass,"sigS","#Sigma^{0} signal (RooHistPdf)"); // /\* cout<<"Lst stuff"<<endl; RooRealVar meanLst1("meanLst1","/\\*(misc.): mean1",5011.031237,4900,5100); RooRealVar sigLst1("sigLst1","/\\*(misc.): sigma1",70.522092,0,100); RooRealVar meanLst2("mean5Lst2","/\\*(1405): mean2",5245.261703,5100,5350); RooRealVar sigLst2("sigLst2","/\\*(1405): sigma2",64.564763,0,100); RooRealVar alphaLst2("alphaLst2","/\\*(1405): alpha2",29.150301); RooRealVar nLst2("nLst2","/\\*(1405): n2",4.615817,0,50); RooGaussian gauLst1("gauLst1","#Lambda*(misc.), gaus",*mass,meanLst1,sigLst1); RooCBShape gauLst2("gauLst2","#Lambda*(1405), CB",*mass,meanLst2,sigLst2,alphaLst2,nLst2); // RooRealVar fLst1("fLst1","/\\* bkg: fraction gaus 1",0.743,0,1); // RooAddPdf bkgLst("bkgLst","#Lambda* signal",RooArgList(gauLst1,gauLst2),RooArgList(fLst1)); //Poly func BKG mass // RooRealVar b0("b0","Background: Chebychev b0",-1.071,-10000,10000); RooRealVar b1("b1","Background: Chebychev b1",-1.323004,-10,-0.00000000000000000000001); RooRealVar b2("b2","Background: Chebychev b2",0.145494,0,10); RooRealVar b3("b3","Background: Chebychev b3",-0.316,-10000,10000); RooRealVar b4("b4","Background: Chebychev b4",0.102,-10000,10000); RooRealVar b5("b5","Background: Chebychev b5",0.014,-10000,10000); RooRealVar b6("b6","Background: Chebychev b6",-0.015,-10000,10000); RooRealVar b7("b7","Background: Chebychev b7",0.012,-10000,10000); RooArgList bList(b1,b2); RooChebychev bkg("bkg","Background", *mass, bList); // TF1 *ep = new TF1("ep","[2]*exp([0]*x+[1]*x*x)",4300,5950); // ep->SetParameter(0,1); // ep->SetParameter(1,-1); // ep->SetParameter(2,2000); // ep->SetParName(0,"a"); // ep->SetParName(1,"b"); // ep->SetParName(2,"c"); // RooRealVar a("a","Background: Coefficent of x",1,-10000,10000); // RooRealVar b("b","Background: Coefficent of x*x",-1,-10000,10000); // RooRealVar c("c","Background: Coefficent of exp()",2000,-10000,10000); // RooTFnPdfBinding bkg("ep","ep",ep,RooArgList(*mass,a,b)); //number of each shape RooRealVar nbkg("nbkg","N bkg",2165.490249,0,100000000); RooRealVar nsigL("nsigL","N /\\",1689.637290,0,1000000000); RooRealVar nsigS("nsigS","N sigma",0.000002,0,10000000000); RooRealVar ngauLst1("ngauLst1","N /\\*(misc.)",439.812103,0,10000000000); RooRealVar ngauLst2("ngauLst2","N /\\*(1405)",152.061617,0,10000000000); RooRealVar nbkgLst("nbkgLst","N /\\*",591.828,0,1000000000); //add shapes and their number to a totalPdf RooArgList shapes; RooArgList yields; shapes.add(sigL); yields.add(nsigL); shapes.add(sigS); yields.add(nsigS); // shapes.add(bkgLst); yields.add(nbkgLst); shapes.add(gauLst1); yields.add(ngauLst1); shapes.add(gauLst2); yields.add(ngauLst2); shapes.add(bkg); yields.add(nbkg); RooAddPdf totalPdf("totalPdf","totalPdf",shapes,yields); //fit the totalPdf RooAbsReal * nll = totalPdf.createNLL(*data,Extended(kTRUE),Range("tot")); RooMinuit m(*nll); m.setVerbose(kFALSE); m.migrad(); m.minos(); m.minos(); //display and save information ofstream textfile;//create text file to hold data placeholder = "plots/fit"+fileN+".txt"; textfile.open(placeholder); TString outputtext;//for useful text //plot things RooPlot *framex = mass->frame(); framex->GetYaxis()->SetTitle("Events/(5 MeV)"); data->plotOn(framex,Name("Hist"),MarkerColor(kBlack),LineColor(kBlack),DataError(RooAbsData::SumW2)); totalPdf.plotOn(framex,Name("curvetot"),LineColor(kBlue)); RooArgSet* totalPdfComponents = totalPdf.getComponents(); TIterator* itertPC = totalPdfComponents->createIterator(); RooAddPdf* vartPC = (RooAddPdf*) itertPC->Next(); vartPC = (RooAddPdf*) itertPC->Next();//skip totalPdf int i=0;//color index TLegend *leg = new TLegend(0.2, 0.02, .4, .42); leg->SetTextSize(0.06); leg->AddEntry(framex->findObject("curvetot"),"Total PDF","l"); while(vartPC){//loop over compotents of totalPdf TString vartPCtitle = vartPC->GetTitle(); TIterator* itercompPars;//forward declare so it persists outside the if statement RooRealVar* varcompPars; if(!(vartPCtitle.Contains(":")||vartPCtitle.Contains("@"))){//only for non-sub-shapes while(i==0||i==10||i==4||i==1||i==5||(i>=10&&i<=27))i++;//avoid white and blue and black and yellow and horribleness RooArgSet* compPars = vartPC->getParameters(data);//set of the parameters of the component the loop is on itercompPars = compPars->createIterator(); varcompPars = (RooRealVar*) itercompPars->Next(); while(varcompPars){//write and print mean, sig, etc. of sub-shapes TString vartitle = varcompPars->GetTitle(); double varval = varcompPars->getVal(); TString varvalstring = Form("%f",varval); double hi = varcompPars->getErrorHi(); TString varerrorstring = "[exact]"; if(hi!=-1){ double lo = varcompPars->getErrorLo(); double varerror = TMath::Max(fabs(lo),hi); varerrorstring = Form("%E",varerror); } outputtext = vartitle+" = "+varvalstring+" +/- "+varerrorstring; textfile<<outputtext<<endl; cout<<outputtext<<endl; varcompPars = (RooRealVar*) itercompPars->Next(); } totalPdf.plotOn(framex,Name(vartPC->GetName()),LineStyle(kDashed),LineColor(i),Components(vartPC->GetName())); leg->AddEntry(framex->findObject(vartPC->GetName()),vartPCtitle,"l"); i++; } vartPC = (RooAddPdf*) itertPC->Next(); itercompPars->Reset();//make sure it's ready for the next vartPC } // Calculate chi2/ndf RooArgSet *floatpar = totalPdf.getParameters(data); int floatpars = (floatpar->selectByAttrib("Constant",kFALSE))->getSize(); Double_t chi2 = framex->chiSquare("curvetot","Hist",floatpars); TString chi2string = Form("%f",chi2); //create text box to list important parameters on the plot // TPaveText* txt = new TPaveText(0.1,0.5,0.7,0.9,"NBNDC"); // txt->SetTextSize(0.06); // txt->SetTextColor(kBlack); // txt->SetBorderSize(0); // txt->SetFillColor(0); // txt->SetFillStyle(0); outputtext = "#chi^{2}/N_{DoF} = "+chi2string; cout<<outputtext<<endl; textfile<<outputtext<<endl; // txt->AddText(outputtext); // Print stuff TIterator* iteryields = yields.createIterator(); RooRealVar* varyields = (RooRealVar*) iteryields->Next();//only inherits things from TObject unless class specified vector<double> Y, E;//holds yields and associated errors vector<TString> YS, ES;//holds strings of the corresponding yields int j=0;//count vector position int jS=0, jL=0;//these hold the position of the S and L results;initialized in case there is no nsigS or nsigL while(varyields){//loop over yields TString varname = varyields->GetName(); TString vartitle = varyields->GetTitle(); double varval = varyields->getVal(); Y.push_back(varval); double lo = varyields->getErrorLo(); double hi = varyields->getErrorHi(); E.push_back(TMath::Max(fabs(lo),hi)); YS.push_back(Form("%f",Y[j])); ES.push_back(Form("%f",E[j])); if(varname=="nsigS") jS=j; if(varname=="nsigL") jL=j; outputtext = vartitle+" = "+YS[j]+" +/- "+ES[j]; cout<<outputtext<<endl; textfile<<outputtext<<endl; //txt->AddText(outputtext); varyields = (RooRealVar*) iteryields->Next(); j++; } //S/L double result = Y[jS]/Y[jL]; cout<<"result declared"<<endl; double E_result = TMath::Abs(result)*sqrt(pow(E[jS]/Y[jS],2)+pow(E[jL]/Y[jL],2)); cout<<"E_result declared"<<endl; TString resultstring = Form("%E",result); TString E_resultstring = Form("%E",E_result); outputtext = "Y_{#Sigma^{0}}/Y_{#Lambda} = "+resultstring+" +/- "+E_resultstring; cout<<outputtext<<endl; textfile<<outputtext<<endl; //txt->AddText(outputtext); double resultlimit = (Y[jS]+E[jS])/(Y[jL]-E[jL]); outputtext = Form("%E",resultlimit); outputtext = "limit = "+outputtext; cout<<outputtext<<endl; textfile<<outputtext<<endl; //txt->AddText(outputtext); // Create canvas and pads, set style TCanvas *c1 = new TCanvas("c1","data fits",1200,800); TPad *pad1 = new TPad("pad1","pad1",0.0,0.3,1.0,1.0); TPad *pad2 = new TPad("pad2","pad2",0.0,0.0,1.0,0.3); pad1->SetBottomMargin(0); pad2->SetTopMargin(0); pad2->SetBottomMargin(0.5); pad2->SetBorderMode(0); pad1->SetBorderMode(0); c1->SetBorderMode(0); pad2->Draw(); pad1->Draw(); pad1->cd(); framex->SetMinimum(1); framex->SetMaximum(3000); framex->addObject(leg);//add legend to frame //framex->addObject(txt);//add text to frame gPad->SetTopMargin(0.06); pad1->SetLogy(); // pad1->Range(4100,0,6100,0.0005); pad1->Update(); framex->Draw(); // Pull distribution RooPlot *framex2 = mass->frame(); RooHist* hpull = framex->pullHist("Hist","curvetot"); framex2->addPlotable(hpull,"P"); hpull->SetLineColor(kBlack); hpull->SetMarkerColor(kBlack); framex2->SetTitle(0); framex2->GetYaxis()->SetTitle("Pull"); framex2->GetYaxis()->SetTitleSize(0.15); framex2->GetYaxis()->SetLabelSize(0.15); framex2->GetXaxis()->SetTitleSize(0.2); framex2->GetXaxis()->SetLabelSize(0.15); framex2->GetYaxis()->CenterTitle(); framex2->GetYaxis()->SetTitleOffset(0.45); framex2->GetXaxis()->SetTitleOffset(1.1); framex2->GetYaxis()->SetNdivisions(505); framex2->GetYaxis()->SetRangeUser(-8.8,8.8); pad2->cd(); framex2->Draw(); c1->cd(); placeholder = "plots/fit"+fileN+".eps"; c1->Print(placeholder); placeholder = "plots/fit"+fileN+".C"; c1->SaveAs(placeholder); textfile.close(); }
void plot_pll(TString fname="monoh_withsm_SRCR_bg11.7_bgslop-0.0_nsig0.0.root") { SetAtlasStyle(); TFile* file = TFile::Open(fname); RooWorkspace* wspace = (RooWorkspace*) file->Get("wspace"); cout << "\n\ncheck that eff and reco terms included in BSM component to make fiducial cross-section" <<endl; wspace->function("nsig")->Print(); RooRealVar* reco = wspace->var("reco"); if( wspace->function("nsig")->dependsOn(*reco) ) { cout << "all good." <<endl; } else { cout << "need to rerun fit_withsm using DO_FIDUCIAL_LIMIT true" <<endl; return; } /* // DANGER // TEST WITH EXAGGERATED UNCERTAINTY wspace->var("unc_theory")->setMax(1); wspace->var("unc_theory")->setVal(1); wspace->var("unc_theory")->Print(); */ // this was for making plot about decoupling/recoupling approach TCanvas* tc = new TCanvas("tc","",400,400); RooPlot *frame = wspace->var("xsec_bsm")->frame(); RooAbsPdf* pdfc = wspace->pdf("jointModeld"); RooAbsData* data = wspace->data("data"); RooAbsReal *nllJoint = pdfc->createNLL(*data, RooFit::Constrained()); // slice with fixed xsec_bsm RooAbsReal *profileJoint = nllJoint->createProfile(*wspace->var("xsec_bsm")); wspace->allVars().Print("v"); pdfc->fitTo(*data); wspace->allVars().Print("v"); wspace->var("xsec_bsm")->Print(); double nllmin = 2*nllJoint->getVal(); wspace->var("xsec_bsm")->setVal(0); double nll0 = 2*nllJoint->getVal(); cout << Form("nllmin = %f, nll0 = %f, Z=%f", nllmin, nll0, sqrt(nll0-nllmin)) << endl; nllJoint->plotOn(frame, RooFit::LineColor(kGreen), RooFit::LineStyle(kDotted), RooFit::ShiftToZero(), RooFit::Name("nll_statonly")); // no error profileJoint->plotOn(frame,RooFit::Name("pll") ); wspace->var("xsec_sm")->Print(); wspace->var("theory")->Print(); wspace->var("theory")->setConstant(); profileJoint->plotOn(frame, RooFit::LineColor(kRed), RooFit::LineStyle(kDashed), RooFit::Name("pll_smfixed") ); frame->GetXaxis()->SetTitle("#sigma_{BSM, fid} [fb]"); frame->GetYaxis()->SetTitle("-log #lambda ( #sigma_{BSM, fid} )"); double temp = frame->GetYaxis()->GetTitleOffset(); frame->GetYaxis()->SetTitleOffset( 1.1* temp ); frame->SetMinimum(1e-7); frame->SetMaximum(4); // Legend double x1,y1,x2,y2; GetX1Y1X2Y2(tc,x1,y1,x2,y2); TLegend *legend_sr=FastLegend(x2-0.75,y2-0.3,x2-0.25,y2-0.5,0.045); legend_sr->AddEntry(frame->findObject("pll"),"with #sigma_{SM} uncertainty","L"); legend_sr->AddEntry(frame->findObject("pll_smfixed"),"with #sigma_{SM} constant","L"); legend_sr->AddEntry(frame->findObject("nll_statonly"),"no systematics","L"); frame->Draw(); legend_sr->Draw("SAME"); // descriptive text vector<TString> pavetext11; pavetext11.push_back("#bf{#it{ATLAS Internal}}"); pavetext11.push_back("#sqrt{#it{s}} = 8 TeV #scale[0.6]{#int}Ldt = 20.3 fb^{-1}"); pavetext11.push_back("#it{H}+#it{E}_{T}^{miss} , #it{H #rightarrow #gamma#gamma}, #it{m}_{#it{H}} = 125.4 GeV"); TPaveText* text11=CreatePaveText(x2-0.75,y2-0.25,x2-0.25,y2-0.05,pavetext11,0.045); text11->Draw(); tc->SaveAs("pll.pdf"); /* wspace->var("xsec_bsm")->setConstant(true); wspace->var("eff" )->setConstant(true); wspace->var("mh" )->setConstant(true); wspace->var("sigma_h" )->setConstant(true); wspace->var("lumi" )->setConstant(true); wspace->var("xsec_sm" )->setVal(v_xsec_sm); wspace->var("eff" )->setVal(1.0); wspace->var("lumi" )->setVal(v_lumi); TH1* nllHist = profileJoint->createHistogram("xsec_bsm",100); TFile* out = new TFile("nllHist.root","REPLACE"); nllHist->Write() out->Write(); out->Close(); */ }
void test(int numbersigmas = 0, Bool_t debugtest = true) { using namespace RooFit; using namespace std; TCanvas *canvas = new TCanvas("canvas","canvas",900,100,500,500); gSystem->Load("libRooFit"); gSystem->AddIncludePath("-I$ROOFITSYS/include"); float ptbinsarray[] = {20.,40.,60.,80.,100.,120.,200.,600.}; std::vector<float> ptbins(ptbinsarray,ptbinsarray+sizeof(ptbinsarray)/sizeof(ptbinsarray[0])); std::vector<std::vector<float> > allbins; allbins.push_back(ptbins); std::vector<TString> VarString; VarString.push_back("VsPt"); std::vector<TString> HistoNameString; HistoNameString.push_back("ptbin"); std::vector<TString> GraphXTitleString; GraphXTitleString.push_back("p_{t} (GeV)"); std::vector<TString> SideBandDefinitions; SideBandDefinitions.push_back("SideBand5_10"); // ------------FOR TESTING---------------- unsigned int sidebandloopmax = 1;//5_10, 5_20, ... unsigned int templatevarsloopmax = 1;//sinin with conv safe veto, sinin, ch isol unsigned int binsloopmax = 1;//pt, eta, phi, pu //----------Open .root Templates //All the Jet Templates TFile *histojetfile = TFile::Open("/afs/cern.ch/user/c/ciperez/CMSSW_7_4_5/src/TemplateHistosJetCheckBinsEndcapsLoose.root"); //TFile *histojetdenfile = TFile::Open("/afs/cern.ch/user/c/ciperez/CMSSW_7_4_5/src/Denominator_FREndCaps.root"); // TFile *histojetdatafile = TFile::Open("/afs/cern.ch/user/c/ciperez/CMSSW_7_4_5/src/Num_Templates.root"); //Real Photon Templates TFile *historealmcfile = TFile::Open("/afs/cern.ch/user/c/ciperez/CMSSW_7_4_5/src/RealPhotonTemplatesEndCaps.root"); //--- Write NEW .root Historams for Fake Rate TFile *FRhistosfile = new TFile("FakeRatePlotsCheckBins.root","recreate"); //loop on error systematics for(unsigned int m = 0; m<templatevarsloopmax; m++) { for(unsigned int l = 0; l<binsloopmax; l++) { TMultiGraph *mg = new TMultiGraph(); TLegend *legendAllGraphs = new TLegend(0.37,0.59,0.57,0.79); legendAllGraphs->SetTextSize(0.02); legendAllGraphs->SetFillColor(kWhite); legendAllGraphs->SetLineColor(kWhite); std::vector<float> fakeratevalues; std::vector<float> fakerateptvalues; std::vector<float> fakerateerrorvalues; for(unsigned int k = 0; k<allbins[0].size()-1; k++) { // for(unsigned int k = 0;k<1;k++){ float binlow = allbins[0][k]; float binmax = allbins[0][k+1]; TString binstring = TString::Format("%4.2f_%4.2f",binlow,binmax); binstring.ReplaceAll(".00",""); binstring.ReplaceAll("-","m"); binstring.ReplaceAll(".","p"); binstring.ReplaceAll("10000","Inf"); cout<<binstring.Data()<<endl; //Histograms for templates //Get histograms from each of the histojetfiles declared earlier //Numerator Fakes - FakePhotonNumEndCaps.root - FakePhoton_num2040... TH1F *h1 = (TH1F*)histojetfile->Get(("histoSininWithPixelSeedFakeJetptbin"+binstring).Data());// .Data() changes to char* h1->Print(); //Numerator Real Photons - RealPhotonTemplatesEndCaps.root - EndCapsMCReal_20_40 TH1F *h2 = (TH1F*)historealmcfile->Get(("EndCapsMCReal_"+binstring).Data()); h2->Print(); //Numerator Templates - Num_Templates.root - num2040... TH1F *hData = (TH1F*)histojetfile->Get(("histoSininWithPixelSeedDataJetptbin"+binstring).Data()); hData->Print(); //Denominator Templates - Denominator_FREndCaps.root -FakePhoton_den2040... TH1F *hnum = (TH1F*)histojetfile->Get(("histoSininWithPixelSeedTightAndFakeJetptbin"+binstring).Data()); hnum->Print(); //avoiding 0 entries in the histograms //fake and real mc histos are the most critical for(int bincount = 1; bincount <= h1->GetNbinsX(); bincount++) { if(h1->GetBinContent(bincount) == 0.) h1->SetBinContent(bincount,1.e-6); } for(int bincount = 1; bincount <= h2->GetNbinsX(); bincount++) { if(h2->GetBinContent(bincount) == 0.) h2->SetBinContent(bincount,1.e-6); } int ndataentries = hData->GetEntries(); float sininmin = 0.; //? sigmaIetaIeta float sininmax = 0.1; //? sigmaIetaIeta // ----------------- Probability Density Function TString roofitvartitle = "#sigma_{i #eta i #eta}"; RooRealVar sinin("sinin",roofitvartitle.Data(),sininmin,sininmax); sinin.setRange("sigrange",0.018,0.06); //? this is the range because? Need to recall. //sinin.setRange("sigrange",0.005, 0.011); //Fake Template pdf RooDataHist faketemplate("faketemplate","fake template",sinin,h1); RooHistPdf fakepdf("fakepdf","test hist fake pdf",sinin,faketemplate); //Real Template pdf RooDataHist realtemplate("realtemplate","real template",sinin,h2); RooHistPdf realpdf("realpdf","test hist real pdf",sinin,realtemplate); //Data to be fitted to RooDataHist data("data","data to be fitted to",sinin,hData); //Declaration of Variables for Fake Rate RooRealVar fsig("fsig","signal fraction",0.1,0,1);// RooRealVar signum("signum","signum",0,ndataentries);// #of real contamination RooRealVar fakenum("fakenum","fakenum",0,ndataentries); //# of fake //Extend RooExtendPdf extpdfsig("Signal","extpdfsig",realpdf,signum,"sigrange"); RooExtendPdf extpdffake("Background","extpdffake",fakepdf,fakenum,"sigrange"); RooAddPdf model("model","sig + background",RooArgList(extpdfsig,extpdffake)); //----------- FITTING TO DATA ------------------- model.fitTo(data,RooFit::Minos()); //Define Plot Frame RooPlot *xframe = sinin.frame(); xframe->SetTitle(""); data.plotOn(xframe); model.plotOn(xframe); model.plotOn(xframe,Components(extpdfsig),LineColor(2),LineStyle(2)); model.plotOn(xframe,Components(extpdffake),LineColor(8),LineStyle(2)); canvas->cd(); canvas->SetGridx(true); canvas->SetGridy(true); xframe->GetXaxis()->SetRangeUser(0.,0.1); float xframemax = xframe->GetMaximum(); xframe->GetYaxis()->SetRangeUser(1.e-1,1.1*xframemax); xframe->Draw(); // ----- DEFINE LEGENDS and their position TLegend *legend = new TLegend(0.62,0.65,0.82,0.85); //Why these values? legend->SetTextSize(0.02); legend->SetFillColor(kWhite); legend->SetLineColor(kWhite); //Legend Header which tells the bin TString legendheader = "Pt (GeV):["+ binstring; legendheader.ReplaceAll("_",","); legendheader.ReplaceAll("m","-"); legendheader.ReplaceAll("p","."); legendheader.Append("]"); cout<<"legend "<<legendheader.Data()<<endl; legend->SetHeader(legendheader.Data()); TObject *objdata; //What is TObect? TObject *objmodel; TObject *objsignal; TObject *objfake; for(int i=0; i<xframe->numItems(); i++) { cout<<xframe->nameOf(i)<<endl; TString objname = xframe->nameOf(i); if(objname.Contains("data")) objdata = (TObject*)xframe->findObject(objname.Data()); if(objname.Contains("model") && !objname.Contains("Comp")) objmodel = (TObject*)xframe->findObject(objname.Data()); if(objname.Contains("model") && objname.Contains("Signal")) objsignal = (TObject*)xframe->findObject(objname.Data()); if(objname.Contains("model") && objname.Contains("Background")) objfake = (TObject*)xframe->findObject(objname.Data()); } //------ LEGEND -------- legend->AddEntry(objdata,"Data","lp"); legend->AddEntry(objsignal,"Signal","l"); legend->AddEntry(objfake,"Background","l"); legend->AddEntry(objmodel,"Signal + Background","l"); legend->Draw("same");//make them overlap for comparison canvas->Print(("Endcapfits"+binstring+".png").Data()); canvas->Print(("TemplateFitResultEndcap"+binstring+".C").Data()); float fakevalue = fakenum.getValV(); float fakeerrorhi = fakenum.getErrorHi(); float fakeerrorlo = fakenum.getErrorLo(); float fakeerrormax = max(fabs(fakeerrorhi),fabs(fakeerrorlo)); TString fakeresults = TString::Format("Fake results %f +%f %f",fakevalue,fakeerrorhi,fakeerrorlo); canvas->SetLogy(0); float sigvalue = signum.getValV(); float sigerrorhi = signum.getErrorHi(); float sigerrorlo = signum.getErrorLo(); float sigerrormax = max(fabs(sigerrorhi),fabs(sigerrorlo)); TString sigresults = TString::Format("Signal results %f +%f %f",sigvalue,sigerrorhi,sigerrorlo); cout<<"sigvalue "<<sigvalue<<" sigerrormax "<<sigerrormax<<" sigerrormax/sigvalue "<<sigerrormax/sigvalue<<endl; cout<<"fakevalue "<<fakevalue<<" fakeerrormax "<<fakeerrormax<<" fakeerrormax/fakevalue "<<fakeerrormax/fakevalue<<endl; cout<<fakeresults.Data()<<endl; cout<<sigresults.Data()<<endl; float Ratio = (fakevalue/(fakevalue+sigvalue)); float RatioError = Ratio*sqrt( ((fakeerrormax/fakevalue)*(fakeerrormax/fakevalue) + (sigerrormax/sigvalue)*(sigerrormax/sigvalue)) ); cout<<"Ratio "<<Ratio<<" +- "<<RatioError<<endl; //---------------------- FAKE RATE CALCULATOR ------------------------- //find the bin corresponding to 0.011 //int binnr = 22; int binnr = 34; //compute the integral of tight and fake in that range float numerator = hData->Integral(0,binnr); //Is the Integral function part of RooFit? float denominator = hnum->Integral(); float contamination = sigvalue; cout<<numerator<<" "<<denominator<<" "<<contamination<<endl; float fakerate = (numerator-contamination)/denominator; float fakerateerror = fakerate * sqrt( (1./numerator) + (1./denominator) + ((sigerrormax/sigvalue)*(sigerrormax/sigvalue)) ); cout<<"Here: "<<fakerate<<" "<<fakerateerror<<endl; //fakerateptvalues.push_back(hnumvspt->GetMean()); fakeratevalues.push_back(fakerate); fakerateerrorvalues.push_back(fakerateerror); cout<<""<<endl; cout<<"***********************************************************"<<endl; cout<<"So in sigmaietaieta < 0.011 there are "<<contamination<<" to subtract from "<<numerator<<endl; cout<<"and thus there are "<<(numerator-contamination)<<" total tight entries "<<endl; cout<<"and there are "<<denominator<<" entries in the tight and fake sample "<<endl; cout<<"and so the fake rate for the pt range "<<binlow<<"-"<<binmax<<" is "<<fakerate<<"+-"<<fakerateerror<<endl; cout<<"***********************************************************"<<endl; cout<<""<<endl; }//loop on all bins /* cout<<fakeratevalues.size()<<endl; for(int k=0;k<fakeratevalues.size();k++){ cout<<"Range: ["<<allbins[l][k]<<"-"<<allbins[l][k+1]<<"] --> fake rate: ("<<fakeratevalues[k]*100<<" +- "<<fakerateerrorvalues[k]*100<<")%"<<endl; }//end of loop over all fake rate values // *************************************************************-// // TGraphErrors *FRgraph = new TGraphErrors(fakeratevalues.size()); for(int k=0;k<fakeratevalues.size();k++){ cout<<(allbins[l][k+1]+allbins[l][k])/2.<<endl; FRgraph->SetPoint(k,(allbins[l][k+1]+allbins[l][k])/2.,fakeratevalues[k]); FRgraph->SetPointError(k,(allbins[l][k+1]-allbins[l][k])/2.,fakerateerrorvalues[k]); }//end of filling TGraph //// FRGraph->SetName(FakeRate.Data()); FRgraph->SetTitle(""); canvas->cd(); canvas->SetLogy(0); FRgraph->Draw("a*"); // **********************************************************-// // ***************************************** //float maxFRvalue = max_element(fakeratevalues.begin(),fakeratevalues.end()); FRgraph->GetYaxis()->SetRangeUser(0.,0.2); FRgraph->GetYaxis()->SetTitle("#epsilon_{FR}"); FRgraph->GetXaxis()->SetTitle((GraphXTitleString[l]).Data()); TString FakeRateFunctionName = " TF1 *FRfunc = new TF1(FakeRateFunctionName.Data(),"[0]+[1]/pow(x,[2])", allbins[l][0],allbins[l][fakeratevalues.size()]); FRfunc->SetParameters(1.,1.,1.); if(l==0){ FRgraph->Fit(FakeRateFunctionName.Data(),"R"); FRgraph->Fit(FakeRateFunctionName.Data()); FRfunc->Draw("same"); } // ******************************************** cout<<"***** Fit function parameters *****"<<endl; cout<<FRfunc->GetParameter(0)<<" " <<FRfunc->GetParameter(1)<<" " <<FRfunc->GetParameter(2)<<" " <<endl; cout<<"***** Fit function errors *****"<<endl; cout<<FRfunc->GetParError(0)<<" " <<FRfunc->GetParError(1)<<" " <<FRfunc->GetParError(2)<<" " <<endl; if(!debugtest){ canvas->Print(("FakeRateJetRun2012ABCD13JulLoose.png").Data(),"png"); canvas->Print(("FakeRateJetRun2012ABCD13JulLoose.gif").Data(),"gif"); canvas->Print(("FakeRateJetRun2012ABCD13JulLoose.eps").Data(),"eps"); canvas->Print(("FakeRateJetRun2012ABCD13JulLoos.pdf").Data(),"pdf"); canvas->Print(("FakeRateJetRun2012ABCD13JulLoose.C").Data(),"cxx"); } canvas->Print(("FakeRateEndCaps.png").Data(),"png"); canvas->Print(("FakeRateEndCaps.C").Data(),"cxx"); // ************************************************ if(!debugtest){ if(count == 0){ FRhistosfile->cd(); FRgraph->Write(); FRfunc->Write(); } } if(numbersigmas != 0){ FRgraph->SetLineColor(count+numbersigmas+1); FRgraph->SetMarkerColor(count+numbersigmas+1); TString numsigmastring = TString::Format("%d #sigma",count); legendAllGraphs->AddEntry(FRgraph,numsigmastring.Data(),"lep"); } mg->Add(FRgraph);*/ // }//end of loop over systematic errors if(numbersigmas != 0) { mg->Draw(); legendAllGraphs->Draw("same"); } }//end of loop over all variables (pt, eta, phi, pu) }//end of loop over template variables histojetfile->cd(); histojetfile->Close(); historealmcfile->cd(); historealmcfile->Close(); FRhistosfile->cd(); FRhistosfile->Close(); // }//end of loop over sideband definitions }//end of method
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(); }
void paper_fit_plot() { SetAtlasStyle(); // get the stuff from the file char fname_postfit[200] = "monoh_withsm_SRCR_bg11.7_bgslop-0.0_nsig0.0.root"; TFile *tf = new TFile(fname_postfit); RooWorkspace *ws_post = (RooWorkspace*)tf->Get("wspace"); // data and pdf RooAbsData *data = ws_post->data("data"); RooAbsPdf *pdfc = ws_post->pdf("jointModeld"); // variables to be constrained RooRealVar *mh = ws_post->var("mh"); RooRealVar *sigma_h = ws_post->var("sigma_h"); RooRealVar *eff = ws_post->var("eff"); RooRealVar *theory = ws_post->var("theory"); RooRealVar *lumi = ws_post->var("lumi"); RooRealVar *x_mgg = ws_post->var("mgg"); RooArgSet cas(*mh,*sigma_h,*eff,*theory,*lumi); // redo the fit RooFitResult *r = pdfc->fitTo(*data,RooFit::Constrain(cas),RooFit::Save(true)); // make the frame RooPlot *frame = x_mgg->frame(); TCanvas *tc = new TCanvas("tc","",700,500); frame->GetXaxis()->SetTitle("m_{#gamma#gamma} [GeV]"); frame->GetYaxis()->SetTitle("Events / 1 GeV"); // add the data data->plotOn(frame,RooFit::Binning(55),RooFit::Name("xdata"),RooFit::DataError(RooAbsData::Poisson)); //data->plotOn(frame,RooFit::Binning(11),RooFit::Name("xdata"),RooFit::DataError(RooAbsData::Poisson)); /// PDFs pdfc->plotOn(frame, RooFit::Components("E"), RooFit::LineColor(kRed), RooFit::Name("xbackground")); pdfc->plotOn(frame, RooFit::Components("S"), RooFit::LineColor(kBlue),RooFit::LineStyle(kDotted), RooFit::Name("xsm")); pdfc->plotOn(frame, RooFit::Components("G"), RooFit::LineColor(kGreen),RooFit::LineStyle(kDotted), RooFit::Name("xbsm")); pdfc->plotOn(frame, RooFit::LineColor(kRed), RooFit::LineStyle(kDashed),RooFit::Name("xtotal")); frame->SetMinimum(1e-7); frame->SetMaximum(9); // Legend double x1,y1,x2,y2; GetX1Y1X2Y2(tc,x1,y1,x2,y2); TLegend *legend_sr=FastLegend(x1+0.02,y2-0.3,x1+0.35,y2-0.02,0.045); legend_sr->AddEntry(frame->findObject("xdata"),"Data","LEP"); legend_sr->AddEntry(frame->findObject("xbackground"),"Background fit","L"); legend_sr->AddEntry(frame->findObject("xsm"),"SM H","L"); legend_sr->AddEntry(frame->findObject("xbsm"),"Best-fit BSM H","L"); legend_sr->AddEntry(frame->findObject("xtotal"),"Total","L"); frame->Draw(); legend_sr->Draw("SAME"); // descriptive text vector<TString> pavetext11; pavetext11.push_back("#bf{#it{ATLAS Internal}}"); pavetext11.push_back("#sqrt{#it{s}} = 8 TeV #scale[0.6]{#int}#it{L} dt = 20.3 fb^{-1}"); pavetext11.push_back("#it{H + E}_{T}^{miss} , #it{H #rightarrow #gamma#gamma}, #it{m}_{#it{H}} = 125.4 GeV"); TPaveText* text11=CreatePaveText(x2-0.47,y2-0.25,x2-0.05,y2-0.05,pavetext11,0.045); text11->Draw(); tc->Print("paper_fit_plot.pdf"); }
void drawCtauFrom2DPlot(RooWorkspace& myws, // Local workspace string outputDir, // Output directory struct InputOpt opt, // Variable with run information (kept for legacy purpose) struct KinCuts cut, // Variable with current kinematic cuts map<string, string> parIni, // Variable containing all initial parameters string plotLabel, // The label used to define the output file name // Select the type of datasets to fit string DSTAG, // Specifies the type of datasets: i.e, DATA, MCJPSINP, ... bool isPbPb, // Define if it is PbPb (True) or PP (False) // Select the type of object to fit bool incJpsi, // Includes Jpsi model bool incPsi2S, // Includes Psi(2S) model bool incBkg, // Includes Background model // Select the fitting options // Select the drawing options bool setLogScale, // Draw plot with log scale bool incSS, // Include Same Sign data double binWidth // Bin width ) { RooMsgService::instance().getStream(0).removeTopic(Caching); RooMsgService::instance().getStream(1).removeTopic(Caching); RooMsgService::instance().getStream(0).removeTopic(Plotting); RooMsgService::instance().getStream(1).removeTopic(Plotting); RooMsgService::instance().getStream(0).removeTopic(Integration); RooMsgService::instance().getStream(1).removeTopic(Integration); RooMsgService::instance().setGlobalKillBelow(RooFit::WARNING) ; if (DSTAG.find("_")!=std::string::npos) DSTAG.erase(DSTAG.find("_")); string pdfTotName = Form("pdfCTAUMASS_Tot_%s", (isPbPb?"PbPb":"PP")); string dsOSName = Form("dOS_%s_%s", DSTAG.c_str(), (isPbPb?"PbPb":"PP")); string dsOSNameCut = dsOSName+"_CTAUCUT"; string hOSName = Form("dhCTAUERRTot_Tot_%s", (isPbPb?"PbPb":"PP")); string hOSNameBkg = Form("dhCTAUERR_Bkg_%s", (isPbPb?"PbPb":"PP")); string hOSNameJpsi = Form("dhCTAUERR_Jpsi_%s", (isPbPb?"PbPb":"PP")); string hOSNamePsi2S = Form("dhCTAUERR_Psi2S_%s", (isPbPb?"PbPb":"PP")); string dsSSName = Form("dSS_%s_%s", DSTAG.c_str(), (isPbPb?"PbPb":"PP")); bool isWeighted = myws.data(dsOSName.c_str())->isWeighted(); vector<double> range; range.push_back(cut.dMuon.ctau.Min); range.push_back(cut.dMuon.ctau.Max); double minRange = -4.0; double maxRange = 7.0; Double_t outTot = myws.data(dsOSName.c_str())->numEntries(); Double_t outErr = myws.data(dsOSName.c_str())->reduce(Form("(ctau>%.6f || ctau<%.6f)", range[1], range[0]))->numEntries(); int nBins = min(int( round((maxRange - minRange)/binWidth) ), 1000); double normDSTot = 1.0; if (myws.data(dsOSNameCut.c_str())) { normDSTot = myws.data(dsOSName.c_str())->sumEntries()/myws.data(dsOSNameCut.c_str())->sumEntries(); } double normJpsi = 1.0; if (myws.data(hOSNameJpsi.c_str())) { normJpsi = myws.data(dsOSName.c_str())->sumEntries()*normDSTot/myws.data(hOSNameJpsi.c_str())->sumEntries(); } double normPsi2S = 1.0; if (myws.data(hOSNamePsi2S.c_str())) { normPsi2S = myws.data(dsOSName.c_str())->sumEntries()*normDSTot/myws.data(hOSNamePsi2S.c_str())->sumEntries(); } double normBkg = 1.0; if (myws.data(hOSNameBkg.c_str())) { normBkg = myws.data(dsOSName.c_str())->sumEntries()*normDSTot/myws.data(hOSNameBkg.c_str())->sumEntries(); } double normTot = 1.0; if (myws.data(hOSName.c_str())) { normTot = myws.data(dsOSName.c_str())->sumEntries()*normDSTot/myws.data(hOSName.c_str())->sumEntries(); } // Create the main plot of the fit RooPlot* frame = myws.var("ctau")->frame(Bins(nBins), Range(minRange, maxRange)); frame->updateNormVars(RooArgSet(*myws.var("invMass"), *myws.var("ctau"), *myws.var("ctauErr"))) ; myws.data(dsOSName.c_str())->plotOn(frame, Name("dOS"), DataError(RooAbsData::SumW2), XErrorSize(0), MarkerColor(kBlack), LineColor(kBlack), MarkerSize(1.2)); myws.pdf(pdfTotName.c_str())->plotOn(frame,Name("PDF"), ProjWData(RooArgSet(*myws.var("ctauErr")), *myws.data(dsOSNameCut.c_str()), kTRUE), Normalization(normDSTot, RooAbsReal::NumEvent), FillStyle(1001), FillColor(kViolet+6), VLines(), DrawOption("LF"), NumCPU(32), LineColor(kBlack) ); myws.pdf(pdfTotName.c_str())->plotOn(frame,Name("BKG"),Components(RooArgSet( *myws.pdf(Form("pdfCTAUMASS_Bkg_%s", (isPbPb?"PbPb":"PP"))) )), ProjWData(RooArgSet(*myws.var("ctauErr")), *myws.data(dsOSName.c_str()), kTRUE), Normalization(normDSTot, RooAbsReal::NumEvent), FillStyle(1001), FillColor(kAzure-9), VLines(), DrawOption("LF"), NumCPU(32) ); if (incJpsi) { myws.pdf(pdfTotName.c_str())->plotOn(frame,Name("JPSIPR"),Components(RooArgSet( *myws.pdf(Form("pdfCTAUMASS_JpsiPR_%s", (isPbPb?"PbPb":"PP"))) )), ProjWData(RooArgSet(*myws.var("ctauErr")), *myws.data(dsOSName.c_str()), kTRUE), Normalization(normDSTot, RooAbsReal::NumEvent), LineColor(kRed+3), Precision(1e-5), NumCPU(32) ); myws.pdf(pdfTotName.c_str())->plotOn(frame,Name("JPSINOPR"),Components(RooArgSet( *myws.pdf(Form("pdfCTAUMASS_JpsiNoPR_%s", (isPbPb?"PbPb":"PP"))) )), ProjWData(RooArgSet(*myws.var("ctauErr")), *myws.data(dsOSName.c_str()), kTRUE), Normalization(normDSTot, RooAbsReal::NumEvent), LineColor(kGreen+3), Precision(1e-5), NumCPU(32) ); } if (incPsi2S) { myws.pdf(pdfTotName.c_str())->plotOn(frame,Name("PSI2SPR"),Components(RooArgSet( *myws.pdf(Form("pdfCTAUMASS_Psi2SPR_%s", (isPbPb?"PbPb":"PP"))) )), ProjWData(RooArgSet(*myws.var("ctauErr")), *myws.data(dsOSName.c_str()), kTRUE), Normalization(normDSTot, RooAbsReal::NumEvent), LineColor(kRed+3), Precision(1e-5), NumCPU(32) ); myws.pdf(pdfTotName.c_str())->plotOn(frame,Name("PSI2SNOPR"),Components(RooArgSet( *myws.pdf(Form("pdfCTAUMASS_Psi2SNo_%s", (isPbPb?"PbPb":"PP"))) )), ProjWData(RooArgSet(*myws.var("ctauErr")), *myws.data(dsOSName.c_str()), kTRUE), Normalization(normDSTot, RooAbsReal::NumEvent), LineColor(kGreen+3), Precision(1e-5), NumCPU(32) ); } if (incSS) { myws.data(dsSSName.c_str())->plotOn(frame, Name("dSS"), MarkerColor(kRed), LineColor(kRed), MarkerSize(1.2)); } myws.data(dsOSName.c_str())->plotOn(frame, Name("dOS"), DataError(RooAbsData::SumW2), XErrorSize(0), MarkerColor(kBlack), LineColor(kBlack), MarkerSize(1.2)); myws.pdf(pdfTotName.c_str())->plotOn(frame,Name("PDFLINE"), ProjWData(RooArgSet(*myws.var("ctauErr")), *myws.data(dsOSNameCut.c_str()), kTRUE), Normalization(normDSTot, RooAbsReal::NumEvent), LineColor(kBlack), NumCPU(32) ); // set the CMS style setTDRStyle(); // Create the pull distribution of the fit RooHist *hpull = frame->pullHist(0, "PDF", true); hpull->SetName("hpull"); RooPlot* frame2 = myws.var("ctau")->frame(Title("Pull Distribution"), Bins(nBins), Range(minRange, maxRange)); frame2->addPlotable(hpull, "PX"); // Create the main canvas TCanvas *cFig = new TCanvas(Form("cCtauFig_%s", (isPbPb?"PbPb":"PP")), "cCtauFig",800,800); TPad *pad1 = new TPad(Form("pad1_%s", (isPbPb?"PbPb":"PP")),"",0,0.23,1,1); TPad *pad2 = new TPad(Form("pad2_%s", (isPbPb?"PbPb":"PP")),"",0,0,1,.228); TLine *pline = new TLine(minRange, 0.0, maxRange, 0.0); TPad *pad4 = new TPad("pad4","This is pad4",0.55,0.46,0.97,0.87); pad4->SetFillStyle(0); pad4->SetLeftMargin(0.28); pad4->SetRightMargin(0.10); pad4->SetBottomMargin(0.21); pad4->SetTopMargin(0.072); frame->SetTitle(""); frame->GetXaxis()->SetTitle(""); frame->GetXaxis()->CenterTitle(kTRUE); frame->GetXaxis()->SetTitleSize(0.045); frame->GetXaxis()->SetTitleFont(42); frame->GetXaxis()->SetTitleOffset(3); frame->GetXaxis()->SetLabelOffset(3); frame->GetYaxis()->SetLabelSize(0.04); frame->GetYaxis()->SetTitleSize(0.04); frame->GetYaxis()->SetTitleOffset(1.7); frame->GetYaxis()->SetTitleFont(42); setCtauFrom2DRange(myws, frame, dsOSNameCut, setLogScale, range, outErr); cFig->cd(); pad2->SetTopMargin(0.02); pad2->SetBottomMargin(0.4); pad2->SetFillStyle(4000); pad2->SetFrameFillStyle(4000); pad1->SetBottomMargin(0.015); //plot fit pad1->Draw(); pad1->cd(); frame->Draw(); printCtauFrom2DParameters(myws, pad1, isPbPb, pdfTotName, isWeighted); pad1->SetLogy(setLogScale); // Drawing the text in the plot TLatex *t = new TLatex(); t->SetNDC(); t->SetTextSize(0.032); float dy = 0; t->SetTextSize(0.03); t->DrawLatex(0.21, 0.86-dy, "2015 HI Soft Muon ID"); dy+=0.045; if (isPbPb) { t->DrawLatex(0.21, 0.86-dy, "HLT_HIL1DoubleMu0_v1"); dy+=0.045; } else { t->DrawLatex(0.21, 0.86-dy, "HLT_HIL1DoubleMu0_v1"); dy+=0.045; } t->DrawLatex(0.21, 0.86-dy, Form("%.1f #leq p_{T}^{#mu#mu} < %.1f GeV/c",cut.dMuon.Pt.Min,cut.dMuon.Pt.Max)); dy+=0.045; t->DrawLatex(0.21, 0.86-dy, Form("%.1f #leq |y^{#mu#mu}| < %.1f",cut.dMuon.AbsRap.Min,cut.dMuon.AbsRap.Max)); dy+=0.045; if (isPbPb) {t->DrawLatex(0.21, 0.86-dy, Form("Cent. %d-%d%%", (int)(cut.Centrality.Start/2), (int)(cut.Centrality.End/2))); dy+=0.045;} if (outErr>0.0) { t->DrawLatex(0.21, 0.86-dy, Form("Excl: (%.4f%%) %.0f evts", (outErr*100.0/outTot), outErr)); dy+=1.5*0.045; } // Drawing the Legend double ymin = 0.7602; if (incPsi2S && incJpsi && incSS) { ymin = 0.7202; } if (incPsi2S && incJpsi && !incSS) { ymin = 0.7452; } TLegend* leg = new TLegend(0.5175, ymin, 0.7180, 0.8809); leg->SetTextSize(0.03); leg->AddEntry(frame->findObject("dOS"), (incSS?"Opposite Charge":"Data"),"pe"); if (incSS) { leg->AddEntry(frame->findObject("dSS"),"Same Charge","pe"); } if(frame->findObject("PDF")) { leg->AddEntry(frame->findObject("PDF"),"Total fit","fl"); } if((incBkg && (incJpsi || incPsi2S)) && frame->findObject("BKG")) { leg->AddEntry(frame->findObject("BKG"),"Background","fl"); } if(incBkg && incJpsi && frame->findObject("JPSIPR")) { leg->AddEntry(frame->findObject("JPSIPR"),"J/#psi Prompt","l"); } if(incBkg && incJpsi && frame->findObject("JPSINOPR")) { leg->AddEntry(frame->findObject("JPSINOPR"),"J/#psi Non-Prompt","l"); } if(incBkg && incPsi2S && frame->findObject("PSI2SPR")) { leg->AddEntry(frame->findObject("PSI2SPR"),"#psi(2S) Prompt","l"); } if(incBkg && incPsi2S && frame->findObject("PSI2SNOPR")) { leg->AddEntry(frame->findObject("PSI2SNOPR"),"#psi(2S) Non-Prompt","l"); } leg->Draw("same"); //Drawing the title TString label; if (isPbPb) { if (opt.PbPb.RunNb.Start==opt.PbPb.RunNb.End){ label = Form("PbPb Run %d", opt.PbPb.RunNb.Start); } else { label = Form("%s [%s %d-%d]", "PbPb", "HIOniaL1DoubleMu0", opt.PbPb.RunNb.Start, opt.PbPb.RunNb.End); } } else { if (opt.pp.RunNb.Start==opt.pp.RunNb.End){ label = Form("PP Run %d", opt.pp.RunNb.Start); } else { label = Form("%s [%s %d-%d]", "PP", "DoubleMu0", opt.pp.RunNb.Start, opt.pp.RunNb.End); } } //CMS_lumi(pad1, isPbPb ? 105 : 104, 33, label); CMS_lumi(pad1, isPbPb ? 108 : 107, 33, ""); gStyle->SetTitleFontSize(0.05); pad1->Update(); cFig->cd(); //---plot pull pad2->Draw(); pad2->cd(); frame2->SetTitle(""); frame2->GetYaxis()->CenterTitle(kTRUE); frame2->GetYaxis()->SetTitleOffset(0.4); frame2->GetYaxis()->SetTitleSize(0.1); frame2->GetYaxis()->SetLabelSize(0.1); frame2->GetYaxis()->SetTitle("Pull"); frame2->GetXaxis()->CenterTitle(kTRUE); frame2->GetXaxis()->SetTitleOffset(1); frame2->GetXaxis()->SetTitleSize(0.12); frame2->GetXaxis()->SetLabelSize(0.1); frame2->GetXaxis()->SetTitle("#font[12]{l}_{J/#psi} (mm)"); frame2->GetYaxis()->SetRangeUser(-7.0, 7.0); frame2->Draw(); // *** Print chi2/ndof printChi2(myws, pad2, frame, "ctau", dsOSName.c_str(), pdfTotName.c_str(), nBins, false); pline->Draw("same"); pad2->Update(); // Save the plot in different formats gSystem->mkdir(Form("%sctauMass/%s/plot/root/", outputDir.c_str(), DSTAG.c_str()), kTRUE); cFig->SaveAs(Form("%sctauMass/%s/plot/root/PLOT_%s_%s_%s%s_pt%.0f%.0f_rap%.0f%.0f_cent%d%d.root", outputDir.c_str(), DSTAG.c_str(), "CTAU", DSTAG.c_str(), (isPbPb?"PbPb":"PP"), plotLabel.c_str(), (cut.dMuon.Pt.Min*10.0), (cut.dMuon.Pt.Max*10.0), (cut.dMuon.AbsRap.Min*10.0), (cut.dMuon.AbsRap.Max*10.0), cut.Centrality.Start, cut.Centrality.End)); gSystem->mkdir(Form("%sctauMass/%s/plot/png/", outputDir.c_str(), DSTAG.c_str()), kTRUE); cFig->SaveAs(Form("%sctauMass/%s/plot/png/PLOT_%s_%s_%s%s_pt%.0f%.0f_rap%.0f%.0f_cent%d%d.png", outputDir.c_str(), DSTAG.c_str(), "CTAU", DSTAG.c_str(), (isPbPb?"PbPb":"PP"), plotLabel.c_str(), (cut.dMuon.Pt.Min*10.0), (cut.dMuon.Pt.Max*10.0), (cut.dMuon.AbsRap.Min*10.0), (cut.dMuon.AbsRap.Max*10.0), cut.Centrality.Start, cut.Centrality.End)); gSystem->mkdir(Form("%sctauMass/%s/plot/pdf/", outputDir.c_str(), DSTAG.c_str()), kTRUE); cFig->SaveAs(Form("%sctauMass/%s/plot/pdf/PLOT_%s_%s_%s%s_pt%.0f%.0f_rap%.0f%.0f_cent%d%d.pdf", outputDir.c_str(), DSTAG.c_str(), "CTAU", DSTAG.c_str(), (isPbPb?"PbPb":"PP"), plotLabel.c_str(), (cut.dMuon.Pt.Min*10.0), (cut.dMuon.Pt.Max*10.0), (cut.dMuon.AbsRap.Min*10.0), (cut.dMuon.AbsRap.Max*10.0), cut.Centrality.Start, cut.Centrality.End)); cFig->Clear(); cFig->Close(); }
void drawCtauPlot(RooWorkspace& myws, // Local workspace string outputDir, // Output directory struct InputOpt opt, // Variable with run information (kept for legacy purpose) struct KinCuts cut, // Variable with current kinematic cuts string plotLabel, // The label used to define the output file name // Select the type of datasets to fit string DSTAG, // Specifies the type of datasets: i.e, DATA, MCJPSINP, ... bool isPbPb, // Define if it is PbPb (True) or PP (False) // Select the drawing options bool setLogScale, // Draw plot with log scale bool incSS, // Include Same Sign data int nBins, // Number of bins used for plotting bool paperStyle=false,// if true, print less info bool saveWS=true // save the workspace into a file ) { if (DSTAG.find("_")!=std::string::npos) DSTAG.erase(DSTAG.find("_")); string dsOSName = Form("dOS_%s_%s", DSTAG.c_str(), (isPbPb?"PbPb":"PP")); string dsSSName = Form("dSS_%s_%s", DSTAG.c_str(), (isPbPb?"PbPb":"PP")); // Create the main plot of the fit // RooPlot* frame = myws.var("invMass")->frame(Bins(nBins), Range(cut.dMuon.M.Min, cut.dMuon.M.Max)); RooPlot* frame = myws.var("ctau")->frame(Bins(nBins), Range(-1,3)); myws.data(dsOSName.c_str())->plotOn(frame, Name("dOS"), DataError(RooAbsData::SumW2), XErrorSize(0), MarkerColor(kBlack), LineColor(kBlack), MarkerSize(1.2)); if (paperStyle) TGaxis::SetMaxDigits(3); // to display powers of 10 if (incSS) { myws.data(dsSSName.c_str())->plotOn(frame, Name("dSS"), MarkerColor(kRed), LineColor(kRed), MarkerSize(1.2)); } myws.data(dsOSName.c_str())->plotOn(frame, Name("dOS"), DataError(RooAbsData::SumW2), XErrorSize(0), MarkerColor(kBlack), LineColor(kBlack), MarkerSize(1.2)); // set the CMS style setTDRStyle(); // Create the main canvas TCanvas *cFig = new TCanvas(Form("cMassFig_%s", (isPbPb?"PbPb":"PP")), "cMassFig",800,800); TPad *pad1 = new TPad(Form("pad1_%s", (isPbPb?"PbPb":"PP")),"",0,paperStyle ? 0 : 0.23,1,1); TPad *pad2 = new TPad(Form("pad2_%s", (isPbPb?"PbPb":"PP")),"",0,0,1,.228); TLine *pline = new TLine(cut.dMuon.M.Min, 0.0, cut.dMuon.M.Max, 0.0); // TPad *pad4 = new TPad("pad4","This is pad4",0.55,0.46,0.97,0.87); TPad *pad4 = new TPad("pad4","This is pad4",0.55,paperStyle ? 0.29 : 0.36,0.97,paperStyle ? 0.70 : 0.77); pad4->SetFillStyle(0); pad4->SetLeftMargin(0.28); pad4->SetRightMargin(0.10); pad4->SetBottomMargin(0.21); pad4->SetTopMargin(0.072); frame->SetTitle(""); frame->GetXaxis()->CenterTitle(kTRUE); if (!paperStyle) { frame->GetXaxis()->SetTitle(""); frame->GetXaxis()->SetTitleSize(0.045); frame->GetXaxis()->SetTitleFont(42); frame->GetXaxis()->SetTitleOffset(3); frame->GetXaxis()->SetLabelOffset(3); frame->GetYaxis()->SetLabelSize(0.04); frame->GetYaxis()->SetTitleSize(0.04); frame->GetYaxis()->SetTitleOffset(1.7); frame->GetYaxis()->SetTitleFont(42); } else { frame->GetXaxis()->SetTitle("#font[12]{l}_{J/#psi} (mm)"); frame->GetXaxis()->SetTitleOffset(1.1); frame->GetYaxis()->SetTitleOffset(1.45); frame->GetXaxis()->SetTitleSize(0.05); frame->GetYaxis()->SetTitleSize(0.05); } setRange(myws, frame, dsOSName, setLogScale, cut.dMuon.AbsRap.Min); if (paperStyle) { double Ydown = 0.1;//frame->GetMinimum(); double Yup = 0.9*frame->GetMaximum(); frame->GetYaxis()->SetRangeUser(Ydown,Yup); } cFig->cd(); pad2->SetTopMargin(0.02); pad2->SetBottomMargin(0.4); pad2->SetFillStyle(4000); pad2->SetFrameFillStyle(4000); if (!paperStyle) pad1->SetBottomMargin(0.015); //plot fit pad1->Draw(); pad1->cd(); frame->Draw(); pad1->SetLogy(setLogScale); // Drawing the text in the plot TLatex *t = new TLatex(); t->SetNDC(); t->SetTextSize(0.032); float dy = 0; t->SetTextSize(0.03); if (!paperStyle) { // do not print selection details for paper style t->DrawLatex(0.21, 0.86-dy, "2015 HI Soft Muon ID"); dy+=0.045; if (isPbPb) { t->DrawLatex(0.21, 0.86-dy, "HLT_HIL1DoubleMu0_v1"); dy+=0.045; } else { t->DrawLatex(0.21, 0.86-dy, "HLT_HIL1DoubleMu0_v1"); dy+=0.045; } } if (cut.dMuon.AbsRap.Min>0.1) {t->DrawLatex(0.20, 0.86-dy, Form("%.1f < |y^{#mu#mu}| < %.1f",cut.dMuon.AbsRap.Min,cut.dMuon.AbsRap.Max)); dy+=1.5*0.045;} else {t->DrawLatex(0.20, 0.86-dy, Form("|y^{#mu#mu}| < %.1f",cut.dMuon.AbsRap.Max)); dy+=1.5*0.045;} t->DrawLatex(0.20, 0.86-dy, Form("%g < p_{T}^{#mu#mu} < %g GeV/c",cut.dMuon.Pt.Min,cut.dMuon.Pt.Max)); dy+=0.045; t->DrawLatex(0.20, 0.86-dy, Form("%g < M^{#mu#mu} < %g GeV/c^{2}",cut.dMuon.M.Min,cut.dMuon.M.Max)); dy+=0.045; if (isPbPb) {t->DrawLatex(0.20, 0.86-dy, Form("Cent. %d-%d%%", (int)(cut.Centrality.Start/2), (int)(cut.Centrality.End/2))); dy+=0.045;} dy+=0.5*0.045; t->DrawLatex(0.20, 0.86-dy, "#mu in acceptance"); dy+=0.045; // Drawing the Legend double ymin = 0.7802; if (paperStyle) { ymin = 0.72; } TLegend* leg = new TLegend(0.5175, ymin, 0.7180, 0.8809); leg->SetTextSize(0.03); leg->AddEntry(frame->findObject("dOS"), (incSS?"Opposite Charge":"Data"),"pe"); if (incSS) { leg->AddEntry(frame->findObject("dSS"),"Same Charge","pe"); } leg->Draw("same"); //Drawing the title TString label; if (isPbPb) { if (opt.PbPb.RunNb.Start==opt.PbPb.RunNb.End){ label = Form("PbPb Run %d", opt.PbPb.RunNb.Start); } else { label = Form("%s [%s %d-%d]", "PbPb", "HIOniaL1DoubleMu0", opt.PbPb.RunNb.Start, opt.PbPb.RunNb.End); } } else { if (opt.pp.RunNb.Start==opt.pp.RunNb.End){ label = Form("PP Run %d", opt.pp.RunNb.Start); } else { label = Form("%s [%s %d-%d]", "PP", "DoubleMu0", opt.pp.RunNb.Start, opt.pp.RunNb.End); } } // CMS_lumi(pad1, isPbPb ? 105 : 104, 33, label); CMS_lumi(pad1, isPbPb ? 108 : 107, 33, ""); if (!paperStyle) gStyle->SetTitleFontSize(0.05); pad1->Update(); cFig->cd(); // Save the plot in different formats gSystem->mkdir(Form("%splot/%s/root/", outputDir.c_str(), DSTAG.c_str()), kTRUE); cFig->SaveAs(Form("%splot/%s/root/%s_%s_%s%s_pt%.0f%.0f_rap%.0f%.0f_cent%d%d.root", outputDir.c_str(), DSTAG.c_str(), DSTAG.c_str(), "Psi2SJpsi", (isPbPb?"PbPb":"PP"), plotLabel.c_str(), (cut.dMuon.Pt.Min*10.0), (cut.dMuon.Pt.Max*10.0), (cut.dMuon.AbsRap.Min*10.0), (cut.dMuon.AbsRap.Max*10.0), cut.Centrality.Start, cut.Centrality.End)); gSystem->mkdir(Form("%splot/%s/png/", outputDir.c_str(), DSTAG.c_str()), kTRUE); cFig->SaveAs(Form("%splot/%s/png/%s_%s_%s%s_pt%.0f%.0f_rap%.0f%.0f_cent%d%d.png", outputDir.c_str(), DSTAG.c_str(), DSTAG.c_str(), "Psi2SJpsi", (isPbPb?"PbPb":"PP"), plotLabel.c_str(), (cut.dMuon.Pt.Min*10.0), (cut.dMuon.Pt.Max*10.0), (cut.dMuon.AbsRap.Min*10.0), (cut.dMuon.AbsRap.Max*10.0), cut.Centrality.Start, cut.Centrality.End)); gSystem->mkdir(Form("%splot/%s/pdf/", outputDir.c_str(), DSTAG.c_str()), kTRUE); cFig->SaveAs(Form("%splot/%s/pdf/%s_%s_%s%s_pt%.0f%.0f_rap%.0f%.0f_cent%d%d.pdf", outputDir.c_str(), DSTAG.c_str(), DSTAG.c_str(), "Psi2SJpsi", (isPbPb?"PbPb":"PP"), plotLabel.c_str(), (cut.dMuon.Pt.Min*10.0), (cut.dMuon.Pt.Max*10.0), (cut.dMuon.AbsRap.Min*10.0), (cut.dMuon.AbsRap.Max*10.0), cut.Centrality.Start, cut.Centrality.End)); cFig->Clear(); cFig->Close(); // Save the workspace if (saveWS) { gSystem->mkdir(Form("%sresult/%s/", outputDir.c_str(), DSTAG.c_str()), kTRUE); TFile *file = NULL; file = new TFile(Form("%sresult/%s/FIT_%s_%s_%s%s_pt%.0f%.0f_rap%.0f%.0f_cent%d%d.root", outputDir.c_str(), DSTAG.c_str(), DSTAG.c_str(), "Psi2SJpsi", (isPbPb?"PbPb":"PP"), plotLabel.c_str(), (cut.dMuon.Pt.Min*10.0), (cut.dMuon.Pt.Max*10.0), (cut.dMuon.AbsRap.Min*10.0), (cut.dMuon.AbsRap.Max*10.0), cut.Centrality.Start, cut.Centrality.End), "RECREATE"); if (!file) { cout << "[ERROR] Output root file with fit results could not be created!" << endl; } else { file->cd(); myws.Write("workspace"); file->Write(); file->Close(); delete file; } } }
void forData(string channel, string catcut, bool removeMinor=true){ // Suppress all the INFO message RooMsgService::instance().setGlobalKillBelow(RooFit::WARNING); // Input files and sum all backgrounds TChain* treeData = new TChain("tree"); TChain* treeZjets = new TChain("tree"); if( channel == "ele" ){ treeData->Add(Form("%s/data/SingleElectron-Run2015D-05Oct2015-v1_toyMCnew.root", channel.data())); treeData->Add(Form("%s/data/SingleElectron-Run2015D-PromptReco-V4_toyMCnew.root", channel.data())); } else if( channel == "mu" ){ treeData->Add(Form("%s/data/SingleMuon-Run2015D-05Oct2015-v1_toyMCnew.root", channel.data())); treeData->Add(Form("%s/data/SingleMuon-Run2015D-PromptReco-V4_toyMCnew.root", channel.data())); } else return; treeZjets->Add(Form("%s/Zjets/DYJetsToLL_M-50_HT-100to200_13TeV_toyMCnew.root", channel.data())); treeZjets->Add(Form("%s/Zjets/DYJetsToLL_M-50_HT-200to400_13TeV_toyMCnew.root", channel.data())); treeZjets->Add(Form("%s/Zjets/DYJetsToLL_M-50_HT-400to600_13TeV_toyMCnew.root", channel.data())); treeZjets->Add(Form("%s/Zjets/DYJetsToLL_M-50_HT-600toInf_13TeV_toyMCnew.root", channel.data())); // To remove minor background contribution in data set (weight is -1) if( removeMinor ){ treeData->Add(Form("%s/VV/WW_TuneCUETP8M1_13TeV_toyMCnew.root", channel.data())); treeData->Add(Form("%s/VV/WZ_TuneCUETP8M1_13TeV_toyMCnew.root", channel.data())); treeData->Add(Form("%s/VV/ZZ_TuneCUETP8M1_13TeV_toyMCnew.root", channel.data())); treeData->Add(Form("%s/TT/TT_TuneCUETP8M1_13TeV_toyMCnew.root", channel.data())); } // Define all the variables from the trees RooRealVar cat ("cat", "", 0, 2); RooRealVar mJet("prmass", "M_{jet}", 30., 300., "GeV"); RooRealVar mZH ("mllbb", "M_{ZH}", 900., 3000., "GeV"); RooRealVar evWeight("evweight", "", -1.e3, 1.e3); // Set the range in jet mass mJet.setRange("allRange", 30., 300.); mJet.setRange("lowSB", 30., 65.); mJet.setRange("highSB", 135., 300.); mJet.setRange("signal", 105., 135.); RooBinning binsmJet(54, 30, 300); RooArgSet variables(cat, mJet, mZH, evWeight); TCut catCut = Form("cat==%s", catcut.c_str()); TCut sbCut = "prmass>30 && !(prmass>65 && prmass<135) && prmass<300"; TCut sigCut = "prmass>105 && prmass<135"; // Create a dataset from a tree -> to process an unbinned likelihood fitting RooDataSet dataSetData ("dataSetData", "dataSetData", variables, Cut(catCut), WeightVar(evWeight), Import(*treeData)); RooDataSet dataSetDataSB ("dataSetDataSB", "dataSetDataSB", variables, Cut(catCut && sbCut), WeightVar(evWeight), Import(*treeData)); RooDataSet dataSetZjets ("dataSetZjets", "dataSetZjets", variables, Cut(catCut), WeightVar(evWeight), Import(*treeZjets)); RooDataSet dataSetZjetsSB("dataSetZjetsSB", "dataSetZjetsSB", variables, Cut(catCut && sbCut), WeightVar(evWeight), Import(*treeZjets)); RooDataSet dataSetZjetsSG("dataSetZjetsSG", "dataSetZjetsSG", variables, Cut(catCut && sigCut), WeightVar(evWeight), Import(*treeZjets)); // Total events number float totalMcEv = dataSetZjetsSB.sumEntries() + dataSetZjetsSG.sumEntries(); float totalDataEv = dataSetData.sumEntries(); RooRealVar nMcEvents("nMcEvents", "nMcEvents", 0., 99999.); RooRealVar nDataEvents("nDataEvents", "nDataEvents", 0., 99999.); nMcEvents.setVal(totalMcEv); nMcEvents.setConstant(true); nDataEvents.setVal(totalDataEv); nDataEvents.setConstant(true); // Signal region jet mass RooRealVar constant("constant", "constant", -0.02, -1., 0.); RooRealVar offset ("offset", "offset", 30., -50., 200.); RooRealVar width ("width", "width", 100., 0., 200.); if( catcut == "1" ) offset.setConstant(true); RooErfExpPdf model_mJet("model_mJet", "model_mJet", mJet, constant, offset, width); RooExtendPdf ext_model_mJet("ext_model_mJet", "ext_model_mJet", model_mJet, nMcEvents); RooFitResult* mJet_result = ext_model_mJet.fitTo(dataSetZjets, SumW2Error(true), Extended(true), Range("allRange"), Strategy(2), Minimizer("Minuit2"), Save(1)); // Side band jet mass RooRealVar constantSB("constantSB", "constantSB", constant.getVal(), -1., 0.); RooRealVar offsetSB ("offsetSB", "offsetSB", offset.getVal(), -50., 200.); RooRealVar widthSB ("widthSB", "widthSB", width.getVal(), 0., 200.); offsetSB.setConstant(true); RooErfExpPdf model_mJetSB("model_mJetSB", "model_mJetSB", mJet, constantSB, offsetSB, widthSB); RooExtendPdf ext_model_mJetSB("ext_model_mJetSB", "ext_model_mJetSB", model_mJetSB, nMcEvents); RooFitResult* mJetSB_result = ext_model_mJetSB.fitTo(dataSetZjetsSB, SumW2Error(true), Extended(true), Range("lowSB,highSB"), Strategy(2), Minimizer("Minuit2"), Save(1)); RooAbsReal* nSIGFit = ext_model_mJetSB.createIntegral(RooArgSet(mJet), NormSet(mJet), Range("signal")); float normFactor = nSIGFit->getVal() * totalMcEv; // Plot the results on a frame RooPlot* mJetFrame = mJet.frame(); dataSetZjetsSB. plotOn(mJetFrame, Binning(binsmJet)); ext_model_mJetSB.plotOn(mJetFrame, Range("allRange"), VisualizeError(*mJetSB_result), FillColor(kYellow)); dataSetZjetsSB. plotOn(mJetFrame, Binning(binsmJet)); ext_model_mJetSB.plotOn(mJetFrame, Range("allRange")); mJetFrame->SetTitle("M_{jet} distribution in Z+jets MC"); // Alpha ratio part mZH.setRange("fullRange", 900., 3000.); RooBinning binsmZH(21, 900, 3000); RooRealVar a("a", "a", 0., -1., 1.); RooRealVar b("b", "b", 1000, 0., 4000.); RooGenericPdf model_ZHSB("model_ZHSB", "model_ZHSB", "TMath::Exp(@1*@0+@2/@0)", RooArgSet(mZH,a,b)); RooGenericPdf model_ZHSG("model_ZHSG", "model_ZHSG", "TMath::Exp(@1*@0+@2/@0)", RooArgSet(mZH,a,b)); RooGenericPdf model_ZH ("model_ZH", "model_ZH", "TMath::Exp(@1*@0+@2/@0)", RooArgSet(mZH,a,b)); RooExtendPdf ext_model_ZHSB("ext_model_ZHSB", "ext_model_ZHSB", model_ZHSB, nMcEvents); RooExtendPdf ext_model_ZHSG("ext_model_ZHSG", "ext_model_ZHSG", model_ZHSG, nMcEvents); RooExtendPdf ext_model_ZH ("ext_model_ZH", "ext_model_ZH", model_ZH, nDataEvents); // Fit ZH mass in side band RooFitResult* mZHSB_result = ext_model_ZHSB.fitTo(dataSetZjetsSB, SumW2Error(true), Extended(true), Range("fullRange"), Strategy(2), Minimizer("Minuit2"), Save(1)); float p0 = a.getVal(); float p1 = b.getVal(); // Fit ZH mass in signal region RooFitResult* mZHSG_result = ext_model_ZHSG.fitTo(dataSetZjetsSG, SumW2Error(true), Extended(true), Range("fullRange"), Strategy(2), Minimizer("Minuit2"), Save(1)); float p2 = a.getVal(); float p3 = b.getVal(); // Fit ZH mass in side band region (data) RooFitResult* mZH_result = ext_model_ZH.fitTo(dataSetDataSB, SumW2Error(true), Extended(true), Range("fullRange"), Strategy(2), Minimizer("Minuit2"), Save(1)); // Draw the model of alpha ratio // Multiply the model of background in data side band with the model of alpha ratio to the a model of background in data signal region RooGenericPdf model_alpha("model_alpha", "model_alpha", Form("TMath::Exp(%f*@0+%f/@0)/TMath::Exp(%f*@0+%f/@0)", p2,p3,p0,p1), RooArgSet(mZH)); RooProdPdf model_sigData("model_sigData", "ext_model_ZH*model_alpha", RooArgList(ext_model_ZH,model_alpha)); // Plot the results to a frame RooPlot* mZHFrameMC = mZH.frame(); dataSetZjetsSB.plotOn(mZHFrameMC, Binning(binsmZH)); ext_model_ZHSB.plotOn(mZHFrameMC, VisualizeError(*mZHSB_result), FillColor(kYellow)); dataSetZjetsSB.plotOn(mZHFrameMC, Binning(binsmZH)); ext_model_ZHSB.plotOn(mZHFrameMC, LineStyle(7), LineColor(kBlue)); dataSetZjetsSG.plotOn(mZHFrameMC, Binning(binsmZH)); ext_model_ZHSG.plotOn(mZHFrameMC, VisualizeError(*mZHSG_result), FillColor(kYellow)); dataSetZjetsSG.plotOn(mZHFrameMC, Binning(binsmZH)); ext_model_ZHSG.plotOn(mZHFrameMC, LineStyle(7), LineColor(kRed)); TLegend* leg = new TLegend(0.65,0.77,0.85,0.85); leg->AddEntry(mZHFrameMC->findObject(mZHFrameMC->nameOf(3)), "side band", "l"); leg->AddEntry(mZHFrameMC->findObject(mZHFrameMC->nameOf(7)), "signal region", "l"); leg->Draw(); mZHFrameMC->addObject(leg); mZHFrameMC->SetTitle("M_{ZH} distribution in MC"); RooPlot* mZHFrame = mZH.frame(); dataSetDataSB.plotOn(mZHFrame, Binning(binsmZH)); ext_model_ZH .plotOn(mZHFrame, VisualizeError(*mZH_result), FillColor(kYellow)); dataSetDataSB.plotOn(mZHFrame, Binning(binsmZH)); ext_model_ZH .plotOn(mZHFrame, LineStyle(7), LineColor(kBlue)); model_sigData.plotOn(mZHFrame, Normalization(normFactor, RooAbsReal::NumEvent), LineStyle(7), LineColor(kRed)); TLegend* leg1 = new TLegend(0.65,0.77,0.85,0.85); leg1->AddEntry(mZHFrame->findObject(mZHFrame->nameOf(3)), "side band", "l"); leg1->AddEntry(mZHFrame->findObject(mZHFrame->nameOf(4)), "signal region", "l"); leg1->Draw(); mZHFrame->addObject(leg1); mZHFrame->SetTitle("M_{ZH} distribution in Data"); TCanvas* c = new TCanvas("c","",0,0,1000,800); c->cd(); mZHFrameMC->Draw(); c->Print(Form("rooFit_forData_%s_cat%s.pdf(", channel.data(), catcut.data())); c->cd(); mZHFrame->Draw(); c->Print(Form("rooFit_forData_%s_cat%s.pdf", channel.data(), catcut.data())); c->cd(); mJetFrame->Draw(); c->Print(Form("rooFit_forData_%s_cat%s.pdf)", channel.data(), catcut.data())); }
int main() { float min_logL1 = 5986.94; float min_logL0 = 5987.16; string filepath="FINAL_RESULT_AB.root_RESULT__RESULT"; filepath="/shome/buchmann/KillerKoala/CBAF/Development/exchange/RooFit__WorkSpace__Exchange_201417_175622__RNSG_46692.4.root__RESULT__RESULT"; // final MCwS filepath="/shome/buchmann/KillerKoala/CBAF/Development/exchange/RooFit__WorkSpace__Exchange_201417_175622__RNSG_46692.4.root__RESULT__RESULT"; filepath="/shome/buchmann/KillerKoala/CBAF/Development/exchange/RooFit__WorkSpace__Exchange_201417_141126__RNSG_97048.1.root__RESULT__RESULT"; // ************************************************************************************* setlumi(PlottingSetup::luminosity); setessentialcut(PlottingSetup::essential); // this sets the essential cut; this one is used in the draw command so it is AUTOMATICALLY applied everywhere. IMPORTANT: Do NOT store weights here! stringstream resultsummary; // write_analysis_type(PlottingSetup::RestrictToMassPeak,PlottingSetup::DoBTag); do_png(true); do_pdf(true); do_eps(false); do_C(true); do_root(false); PlottingSetup::directoryname = "pValuePlot"; gROOT->SetStyle("Plain"); bool do_fat_line = false; // if you want to have HistLineWidth=1 and FuncWidth=1 as it was before instead of 2 setTDRStyle(do_fat_line); gStyle->SetTextFont(42); bool showList = true; set_directory(PlottingSetup::directoryname); // Indicate the directory name where you'd like to save the output files in Setup.C set_treename("events"); // you can set the treename here to be used; options are "events" (for reco) for "PFevents" (for particle flow) TFile *f = new TFile(filepath.c_str()); if(f->IsZombie()) { cout << "Seems to be a zombie. goodbye." << endl; return -1; } RooWorkspace *wa = (RooWorkspace*)f->Get("transferSpace"); RooPlot *plot = (RooPlot*) wa->obj("frame_mlledge_109fde50"); // cout << plot << endl; wa->Print("v"); TCanvas *can = new TCanvas("can","can"); cout << "Address of plot : " << plot << endl; // plot->Draw(); float pVal_mllmin=35; float pVal_mllmax=90; int is_data=PlottingSetup::data; vector < std::pair < float, float> > loglikelihoods; string function=""; for(int i=0; i< plot->numItems();i++){ string name = plot->getObject(i)->GetName(); if (plot->getObject(i)->IsA()->InheritsFrom( "RooCurve" ))function=name; } RooCurve* curve = (RooCurve*) plot->findObject(function.c_str(),RooCurve::Class()) ; if (!curve) { dout << "RooPlot::residHist(" << plot->GetName() << ") cannot find curve" << endl ; return 0 ; } int iMinimum=0; float min=1e7; for(int i=0;i<curve->GetN();i++) { double x,y; curve->GetPoint(i,x,y); if(y<min & y>=0) { min=y; iMinimum=i; } } double x,y; curve->GetPoint(iMinimum,x,y); cout << "Minimum is at " << x << " : " << y << endl; loglikelihoods.push_back(make_pair(x,y+min_logL1)); //move right starting from the minimum for(int i=iMinimum+1;i<curve->GetN();i++) { float yold=y; curve->GetPoint(i,x,y); //if(abs((y-yold)/yold)>0.5) continue; loglikelihoods.push_back(make_pair(x,y+min_logL1)); } /* for(int i=0;i<curve->GetN();i++) { double x,y; curve->GetPoint(i,x,y); loglikelihoods.push_back(make_pair(x,y+min_logL1)); }*/ cout << "The whole thing contains " << loglikelihoods.size() << " points " << endl; ProduceSignificancePlots(min_logL0, loglikelihoods, pVal_mllmin, pVal_mllmax, is_data, "", ""); can->SaveAs("Crap.png"); delete can; delete plot; delete wa; f->Close(); return 0; }
void checkFitCBBW(float mass,float width,string channel, string modelName,double Ymax,bool testGeneratedKinematics=0,bool testKinematicsWithoutSelection =0) { float gamma = width*mass; std::ostringstream s; s<< mass; std::string Mass(s.str()); std::ostringstream ss; int temp_width = width*10; ss<<temp_width; std::string swidth(ss.str()); string sMCname = "MC sample, m_{VV}="+Mass+", width=0."+swidth; string suffix ="#"+channel; if(channel.find("mu")==string::npos) { suffix = "e"; } string name= modelName+" #rightarrow "+suffix+", m_{WW} = "+Mass; string soutput_pdf_name = "/usr/users/dschaefer/root/results/testFit/M"+Mass+"/"+modelName+"_M"+Mass+"_"+"width0p"+swidth+"_"+channel+"_matchedJet.pdf"; if(testGeneratedKinematics) { soutput_pdf_name = "/usr/users/dschaefer/root/results/testFit/M"+Mass+"/"+modelName+"_M"+Mass+"_"+"width0p"+swidth+"_"+channel+"_matchedJet_gen.pdf"; } if(testKinematicsWithoutSelection) { soutput_pdf_name = "/usr/users/dschaefer/root/results/testFit/M"+Mass+"/"+modelName+"_M"+Mass+"_"+"width0p"+swidth+"_"+channel+"_withoutSelections.pdf"; } string sfile_narrow; if(mass == 800 or mass ==1600) { sfile_narrow ="/usr/users/dschaefer/root/results/BulkGrav/BulkGrav_M"+Mass+"_width0p0_mWW_"+channel+".root"; if(testKinematicsWithoutSelection) { sfile_narrow ="/usr/users/dschaefer/root/results/BulkGrav/BulkGrav_M"+Mass+"_width0p0_mWW_"+channel+"_withoutSelection.root"; } } else { sfile_narrow ="/usr/users/dschaefer/root/results/Wprime/Wprime_M"+Mass+"_width0p0_mWW_"+channel+".root"; } string sfile_width ="/usr/users/dschaefer/root/results/"+modelName+"/"+modelName+"_M"+Mass+"_width0p"+swidth+"_mWW_"+channel+".root"; if(testGeneratedKinematics) { sfile_width ="/usr/users/dschaefer/root/results/"+modelName+"/"+modelName+"_M"+Mass+"_width0p"+swidth+"_mWW_"+channel+"_gen.root"; } if(testKinematicsWithoutSelection) { sfile_width ="/usr/users/dschaefer/root/results/"+modelName+"/"+modelName+"_M"+Mass+"_width0p"+swidth+"_mWW_"+channel+"_withoutSelection.root"; } const char* file_width = sfile_width.c_str(); const char* file_narrow = sfile_narrow.c_str(); const char* MCname= sMCname.c_str(); const char* title = name.c_str(); const char* output_pdf_name = soutput_pdf_name.c_str(); TFile *f = new TFile(file_width,"READ"); TFile *f_narrow = new TFile(file_narrow,"READ"); TH1F* h = (TH1F*) f->Get("hmWW"); TH1F* h_narrow = (TH1F*) f_narrow->Get("hmWW"); int tmp = h_narrow->GetSize()-2; double massMax_narrow = h_narrow->GetBinLowEdge(h_narrow->GetBin(tmp)); double massMin_narrow = h_narrow->GetBinLowEdge(0); tmp = h->GetSize()-2; double massMax_width = h->GetBinLowEdge(h->GetBin(tmp)); double massMin_width = h->GetBinLowEdge(0); RooRealVar m_narrow("m","m",massMin_narrow, massMax_narrow); RooRealVar m_width("m_w","m_w",massMin_width,massMax_width); float mCBMin; float mCBMax; float sCB; float sCBMin; float sCBMax; float n1; float n1Max; float n1Min; float n2Max; float n2Min; float n2; float alpha1; float alpha11Min; float alpha1Max; float alpha1Min; float alpha2Max; float alpha2Min; float alpha2; if(mass == 800) { sCB =50; sCBMin =40; sCBMax=70; n1 = 15.; n1Min=5.;n1Max =25.; n2 = 15.; n2Min=5.;n2Max =25.; alpha1 =1.5;alpha1Min=1.;alpha1Max=1.9; alpha2 =1.64;alpha2Min=1.;alpha2Max=1.9; } if(mass == 1200) { sCB =50; sCBMin =40; sCBMax=70; n1 = 15.; n1Min=5.;n1Max =25.; n2 = 15.; n2Min=5.;n2Max =25.; alpha1 =1.5;alpha1Min=1.;alpha1Max=1.9; alpha2 =1.64;alpha2Min=1.;alpha2Max=1.9; } if(mass == 2000) { sCB =150; sCBMin =110; sCBMax=175; n1 = 10.; n1Min=0.01;n1Max =35.; n2 = 20; n2Min=0.01;n2Max =35.; alpha1 =1.5;alpha1Min=0.5;alpha1Max=3.; alpha2 =1.5;alpha2Min=0.5;alpha2Max=3.0; } if(mass == 3000) { sCB =150; sCBMin =110; sCBMax=175; n1 = 10.; n1Min=0.01;n1Max =35.; n2 = 20; n2Min=0.01;n2Max =35.; alpha1 =1.5;alpha1Min=0.5;alpha1Max=3.; alpha2 =1.5;alpha2Min=0.5;alpha2Max=3.0; } if(mass==4000) { sCB =200; sCBMin =140; sCBMax=230; n1 = 10.; n1Min=0.01;n1Max =35.; n2 = 20; n2Min=0.01;n2Max =35.; alpha1 =1.5;alpha1Min=0.5;alpha1Max=3.; alpha2 =1.5;alpha2Min=0.5;alpha2Max=3.0; } RooRealVar m_new = m_width; m_new.setBins(1000,"cache"); RooRealVar mean_CB("mean_CB","mean_CB",mass+90,mass-20,mass+100); RooRealVar sigma_CB("sigma_CB","sigma_CB",sCB,sCBMin,sCBMax); RooRealVar n1_CB("n1_CB","n1_CB",n1,n1Min,n1Max); RooRealVar alpha2_CB("alpha2_CB","alpha2_CB",alpha2,alpha2Min,alpha2Max); RooRealVar n2_CB("n2_CB","n2_CB",n2,n2Min,n2Max); RooRealVar alpha1_CB("alpha1_CB","alpha1_CB",alpha1,alpha1Min,alpha1Max); RooRealVar mean_conv("mean_conv","mean_conv",0); RooRealVar width_BW("width_BW","width_BW",gamma); RooDoubleCrystalBall CB("CB","CB",m_narrow,mean_CB,sigma_CB,alpha1_CB,n1_CB,alpha2_CB,n2_CB); RooDataHist dh_narrow("dh_narrow","dh_narrow",m_narrow,Import(*h_narrow)); CB.fitTo(dh_narrow); mean_CB.getVal(); sigma_CB.getVal(); n1_CB.getVal(); n2_CB.getVal(); alpha1_CB.getVal(); alpha2_CB.getVal(); RooBWRunPdf BW("BW","BW",m_new,mean_CB,width_BW); RooDoubleCrystalBall CB_fitted("CB_fitted","CB_fitted",m_new,mean_conv,sigma_CB,alpha1_CB,n1_CB,alpha2_CB,n2_CB); RooDataHist dh("dh","dh",m_width,Import(*h)); RooPlot* frame = m_width.frame(); frame->GetXaxis()->SetTitle("m_{VV} [GeV]"); frame->SetTitle(title); frame->GetYaxis()->SetTitleOffset(1.4); frame->setPadFactor(1); dh.plotOn(frame,"name_dh"); if(testKinematicsWithoutSelection) { RooBWRunPdf BW_withoutSelection("BW_wS","BW_wS",m_width,mean_CB,width_BW); BW_withoutSelection.plotOn(frame,"name_model_pdf"); } else { RooFFTConvPdf model_pdf("conv","conv",m_new,BW,CB_fitted); model_pdf.setBufferFraction(5.0); model_pdf.plotOn(frame,"name_model_pdf"); } //BW.plotOn(frame,MarkerColor(kRed),LineColor(kRed)); //CB.plotOn(frame,MarkerColor(kGreen),LineColor(kGreen)); //model_pdf.fitTo(dh); RooPlot* frame_narrow_fit = m_narrow.frame(); frame_narrow_fit->GetXaxis()->SetTitle("m_{VV} [GeV]"); frame_narrow_fit->SetTitle("Double Crystall Ball"); dh_narrow.plotOn(frame_narrow_fit); CB.plotOn(frame_narrow_fit); TCanvas* canvas1 = new TCanvas("canvas1","canvas1",400,600); gPad->SetLeftMargin(0.15); TPad* pad1 = new TPad("pad1","pad1",0.,0.2,1.,1.0); TPad* pad2 = new TPad("pad2","pad2",0.,0.,1.0,0.2); pad1->SetLeftMargin(0.15); pad2->SetLeftMargin(0.15); pad1->Draw(); pad2->Draw(); pad1->cd(); frame->GetYaxis()->SetTitleOffset(2.0); //double Ymax = 400; frame->SetMaximum(Ymax); frame->Draw(); TString dh_name = frame->nameOf(0); TString model_pdf_name = frame->nameOf(1); TLegend* leg = new TLegend(0.48,0.89,0.89,0.8);//0.48,0.89,0.9,0.8) leg->SetBorderSize(0); leg->SetFillColor(0); leg->AddEntry(frame->findObject(dh_name),MCname,"lep"); if(testKinematicsWithoutSelection) { leg->AddEntry(frame->findObject(model_pdf_name),"Breit-Wigner ","L"); } else { leg->AddEntry(frame->findObject(model_pdf_name),"(CB*BW)(m) ","L"); } leg->Draw(); double chi2 = frame->chiSquare(); string schi2 = "X^{2} ="+std::to_string(chi2); const char* textChi2 = schi2.c_str(); TLatex text; text.SetTextFont(43); text.SetTextSize(16); text.DrawLatex(massMin_width+(massMax_width-massMin_width)/10.,Ymax-Ymax/10.,textChi2); RooPlot* frame2 = m_width.frame(); frame2->addObject(frame->pullHist()); frame2->SetMinimum(-25); frame2->SetMaximum(15); frame2->SetTitle("pulls"); pad2->cd(); frame2->Draw(); canvas1->SaveAs(output_pdf_name); TCanvas* canvas2 = new TCanvas("canvas2","canvas2",400,400); canvas2->cd(); frame_narrow_fit->Draw(); }