void Fitter::Plot() { // Make the plots RooPlot* pFrame = NULL; RooPlot* pFramePull = NULL; MakePlots("tot_pdf", plotTitle, pFrame, pFramePull); // Save the plots ChangeDirectory("raw"); pFrame->Write(); pFramePull->Write(); // Put Them in a canvas PlotCanvas pc; CombinePlots("tot_pdf", pc, pFrame, pFramePull); // Save the canvas ChangeDirectory(); pc.pCanvas->Write(); delete pFrame; delete pFramePull; return; }
void ComputeUpperLimit(RooAbsData *data, RooStats::ModelConfig *model, float &UpperLimit, float &signif, RooRealVar *mu, RooArgSet *nullParams,RooWorkspace *ws,REGION region,const char* tag) { bool StoreEverything=false; // activate if you want to store frames and all RooStats::ProfileLikelihoodCalculator *plc = new RooStats::ProfileLikelihoodCalculator(*data, *model); plc->SetParameters(*mu); plc->SetNullParameters(*nullParams); plc->SetTestSize(0.05); RooStats::LikelihoodInterval *interval = plc->GetInterval(); bool ComputationSuccessful=false; UpperLimit = interval->UpperLimit(*mu,ComputationSuccessful); signif = 0.0; // plc->GetHypoTest()->Significance(); // deactivated significance (to make algorithm faster) if(!ComputationSuccessful) { cout << "There seems to have been a problem. Returned upper limit is " << UpperLimit << " but it will be set to -999" << endl; UpperLimit=-999; signif=-999; } if(StoreEverything) { // Store it all RooRealVar* minv = (RooRealVar*)model->GetObservables()->first(); minv->setBins(static_cast<int>((minv->getMax()-minv->getMin())/5.)); RooPlot* frameEE = minv->frame(RooFit::Title("ee sample")); frameEE->GetXaxis()->CenterTitle(1); frameEE->GetYaxis()->CenterTitle(1); RooPlot* frameMM = minv->frame(RooFit::Title("mm sample")); frameMM->GetXaxis()->CenterTitle(1); frameMM->GetYaxis()->CenterTitle(1); RooPlot* frameOF = minv->frame(RooFit::Title("OF sample")); frameOF->GetXaxis()->CenterTitle(1); frameOF->GetYaxis()->CenterTitle(1); data->plotOn(frameMM,RooFit::Cut("catCentral==catCentral::MMCentral")); model->GetPdf()->plotOn(frameMM,RooFit::Slice(*ws->cat("catCentral"), "MMCentral"),RooFit::ProjWData(*data)); data->plotOn(frameEE,RooFit::Cut("catCentral==catCentral::EECentral")); model->GetPdf()->plotOn(frameEE,RooFit::Slice(*ws->cat("catCentral"), "EECentral"),RooFit::ProjWData(*data)); data->plotOn(frameOF,RooFit::Cut("catCentral==catCentral::OFOSCentral")); model->GetPdf()->plotOn(frameOF,RooFit::Slice(*ws->cat("catCentral"), "OFOSCentral"),RooFit::ProjWData(*data)); TFile *fout = new TFile("fout.root","UPDATE"); frameMM->Write(Concatenate(Concatenate(data->GetName(),"_MM"),tag),TObject::kOverwrite); frameEE->Write(Concatenate(Concatenate(data->GetName(),"_EE"),tag),TObject::kOverwrite); frameOF->Write(Concatenate(Concatenate(data->GetName(),"_OF"),tag),TObject::kOverwrite); fout->Close(); } delete plc; plc=0; }
void Fitter::Plot_sWeighted() { for(auto& pVec_pdfs : {&sigPdfs, &bkgPdfs}) for(auto& pdf : *pVec_pdfs) { //TFile* pFile = new TFile(outputFilename.c_str(), "UPDATE"); RooDataSet* pDataSig = new RooDataSet("data_sWeighted", "data_sWeighted", pData, *pData->get(), 0, (pdf.GetYld().GetName() + string("_sw")).c_str()); //RooDataSet* pDataBkg = new RooDataSet("data_bkg", "data_bkg", pData, *pData->get(), 0, "bkg0_yield_sw"); RooPlot* pFrameData = NULL; RooPlot* pFramePull = NULL; //TCanvas* pCanvas = NULL; MakePlots(pdf.GetPdf().GetName() + string("_sWeighted"), plotTitle+" ("+pdf.GetPdf().GetName()+" sWeighted)", pFrameData, pFramePull, &(pdf.GetPdf()), pDataSig); //MakePlots("_weighted", plotTitle+" weighted", pFrameData, pFramePull, &(bkgPdfs[0].GetPdf()), pDataBkg); ChangeDirectory("raw"); pFrameData->Write(); pFramePull->Write(); ChangeDirectory(); PlotCanvas pc; CombinePlots(pdf.GetPdf().GetName() + string("_sWeighted"), pc, pFrameData, pFramePull); pc.pCanvas->Write(); //CombinePlots(branchName+"_weighted", pCanvas, pFrameData, pFramePull); //TDirectory* pPlotDir = pFile->GetDirectory("plots_sWeighted"); //if(!pPlotDir) pPlotDir = pFile->mkdir("plots_sWeighted"); //pPlotDir->cd(); //pCanvas->Write(); //delete pCanvas; //delete pFrameData; //delete pFramePull; delete pDataSig; //delete pDataBkg; } }
void fitSignalShapeW(int massBin,int id, int channels,int categ, int sample, /* float lumi, bool doSfLepton, */double rangeLow, double rangeHigh, double bwSigma, double fitValues[9], double fitErrors[9], double covQual[1]){ // ------ root settings --------- gROOT->Reset(); gROOT->SetStyle("Plain"); gStyle->SetPadGridX(kFALSE); gStyle->SetPadGridY(kFALSE); //gStyle->SetOptStat("kKsSiourRmMen"); gStyle->SetOptStat("iourme"); //gStyle->SetOptStat("rme"); //gStyle->SetOptStat(""); gStyle->SetOptFit(11); gStyle->SetPadLeftMargin(0.14); gStyle->SetPadRightMargin(0.06); // ------------------------------ ROOT::Math::MinimizerOptions::SetDefaultTolerance( 1.E-7); stringstream FileName; //Insert the file here if(sample==1) FileName <<"root://lxcms03//data3/Higgs/150915/ZH125/ZZ4lAnalysis.root" ; else if(sample==2) FileName << "root://lxcms03//data3/Higgs/150915/WplusH125/ZZ4lAnalysis.root"; else if(sample==3) FileName << "root://lxcms03//data3/Higgs/150915/WminusH125/ZZ4lAnalysis.root"; else if(sample==4) FileName << "root://lxcms03//data3/Higgs/150915/ttH125/ZZ4lAnalysis.root"; else { cout << "Wrong sample." << endl; return; } cout << "Using " << FileName.str() << endl; TFile* ggFile = TFile::Open(FileName.str().c_str()); TTree* ggTree = (TTree*) ggFile->Get("ZZTree/candTree"); float m4l; Short_t z1flav, z2flav; float weight; Short_t nExtraLeptons; float ZZPt; Short_t nJets; Short_t nBTaggedJets; std::vector<float> * jetpt = 0; std::vector<float> * jeteta = 0; std::vector<float> * jetphi = 0; std::vector<float> * jetmass = 0; float jet30pt[10]; float jet30eta[10]; float jet30phi[10]; float jet30mass[10]; float Fisher; int nentries = ggTree->GetEntries(); //--- ggTree part ggTree->SetBranchAddress("ZZMass",&m4l); ggTree->SetBranchAddress("Z1Flav",&z1flav); ggTree->SetBranchAddress("Z2Flav",&z2flav); ggTree->SetBranchAddress("genHEPMCweight",&weight); ggTree->SetBranchAddress("nExtraLep",&nExtraLeptons); ggTree->SetBranchAddress("nCleanedJets",&nJets); ggTree->SetBranchAddress("nCleanedJetsPt30BTagged",&nBTaggedJets); ggTree->SetBranchAddress("DiJetFisher",&Fisher); ggTree->SetBranchAddress("JetPt",&jetpt); ggTree->SetBranchAddress("JetEta",&jeteta); ggTree->SetBranchAddress("JetPhi",&jetphi); ggTree->SetBranchAddress("JetMass",&jetmass); ggTree->SetBranchAddress("ZZPt",&ZZPt); //--- rooFit part double xMin,xMax,xInit; xInit = (double) massBin; xMin = rangeLow; xMax = rangeHigh ; cout << "Fit range: [" << xMin << " , " << xMax << "]. Init value = " << xInit << endl; TH1F *hmass = new TH1F("hmass","hmass",200,xMin,xMax); //--------- RooRealVar x("mass","m_{4l}",xInit,xMin,xMax,"GeV"); RooRealVar w("myW","myW",1.0,0.,1000.); RooArgSet ntupleVarSet(x,w); RooDataSet dataset("mass4l","mass4l",ntupleVarSet,WeightVar("myW")); for(int k=0; k<nentries; k++){ ggTree->GetEvent(k); int njet30 = 0; for (unsigned int ijet = 0; ijet < jetpt->size(); ijet++) { if ( (*jetpt)[ijet] > 30. ) { jet30pt[njet30] = (*jetpt)[ijet]; jet30eta[njet30] = (*jeteta)[ijet]; jet30phi[njet30] = (*jetphi)[ijet]; jet30mass[njet30] = (*jetmass)[ijet]; njet30++; } } int Cat = category(nExtraLeptons, ZZPt, m4l, njet30, nBTaggedJets, jet30pt, jet30eta, jet30phi,jet30mass, Fisher); if (categ >= 0 && categ != Cat ) continue; if(channels==0 && z1flav*z2flav != 28561) continue; if(channels==1 && z1flav*z2flav != 14641) continue; if (weight <= 0 ) cout << "Warning! Negative weight events" << endl; if(channels==2 && z1flav*z2flav != 20449) continue; ntupleVarSet.setRealValue("mass",m4l); ntupleVarSet.setRealValue("myW",weight); if(x.getVal()>xMin && x.getVal()<xMax) dataset.add(ntupleVarSet, weight); hmass->Fill(m4l); } //--------- cout << "dataset n entries: " << dataset.sumEntries() << endl; TCanvas *c1 = new TCanvas("c1","c1",725,725); c1->cd(); TPad *pad1 = new TPad("pad1","This is pad1",0.05,0.35,0.95,0.97); pad1->Draw(); TPad *pad2 = new TPad("pad2","This is pad2",0.05,0.02,0.95,0.35); pad2->Draw(); //--- double CrystalBall RooRealVar mean("bias","mean of gaussian",0,-5.,5.) ; RooRealVar sigma("sigma","width of gaussian",1.5,0.,30.); RooRealVar a1("a1","a1",1.46,0.5,5.); RooRealVar n1("n1","n1",1.92,0.,10.); RooRealVar a2("a2","a2",1.46,1.,10.); RooRealVar n2("n2","n2",20,1.,50.); RooDoubleCB DCBall("DCBall","Double Crystal ball",x,mean,sigma,a1,n1,a2,n2); if (channels== 1) mean.setVal(-1.); //--- Breit-Wigner float bwSigmaMax,bwSigmaMin; if(massBin<400) bwSigmaMin=bwSigmaMax=bwSigma; else { bwSigmaMin=bwSigma-20.; bwSigmaMax=bwSigma+20.; } RooRealVar mean3("mean3","mean3",xInit) ; RooRealVar sigma3("sigma3","width3",bwSigma,bwSigmaMin,bwSigmaMax); RooRealVar scale3("scale3","scale3 ",1.); RooRelBWUFParam bw("bw","bw",x,mean3,scale3); //Chebyshev-Polynomial RooRealVar A1("A1","A1",-1,-3,3.); RooRealVar A2("A2","A2",0.5,-3.,3.); RooChebychev BkgPDF("BkgPDF","BkgPDF",x ,RooArgList(A1,A2)); //Fraction RooRealVar frac("frac","Fraction for PDF",0.5,0.,1.); x.setBins(10000,"fft"); RooFFTConvPdf model("model","model",x,bw,DCBall); RooAddPdf totPDF("totPDF","Total PDF ",RooArgList(model,BkgPDF),RooArgList(frac)); RooArgSet* params = totPDF.getParameters(x); if(sample!=1 && categ!=0 && id!=125){ if(channels==0 ){params->readFromFile("Ch0_Cat0_paraT.txt");}// Read the Parameter for the Resonance + Bkg(ChebyChev) if(channels==1 ){params->readFromFile("Ch1_Cat0_paraT.txt");}// Read the Parameter for the Resonance + Bkg(ChebyChev) if(channels==2 ){params->readFromFile("Ch2_Cat0_paraT.txt");}// Read the Parameter for the Resonance + Bkg(ChebyChev) } RooFitResult *fitres = (RooFitResult*)totPDF.fitTo(dataset,SumW2Error(1),Range(xMin,xMax),Strategy(2),NumCPU(8),Save(true)); if (sample==1 && categ==0 && id==125){ mean.setConstant(kTRUE); sigma.setConstant(kTRUE); a1.setConstant(kTRUE); n1.setConstant(kTRUE); a2.setConstant(kTRUE); n2.setConstant(kTRUE); mean3.setConstant(kTRUE); sigma3.setConstant(kTRUE); scale3.setConstant(kTRUE); A1.setConstant(kTRUE); A2.setConstant(kTRUE); frac.setConstant(kTRUE); if(channels==0 ){ params->readFromFile("Ch0_Cat0_para.txt"); // Read the Parameter for the Resonance as ggH sample params->writeToFile("Ch0_Cat0_paraT.txt");} // Writing the Parameter for Full PDF including the Chebyshev-Polynomial if(channels==1 ) {params->readFromFile("Ch1_Cat0_para.txt"); // Read the Parameter for the Resonance as in ggH sample params->writeToFile("Ch1_Cat0_paraT.txt");}// Writing the Parameter for Full PDF including the Chebyshev-Polynomial if(channels==2 ){ params->readFromFile("Ch2_Cat0_para.txt"); // Read the Parameter for the Resonance as ggH sample params->writeToFile("Ch2_Cat0_paraT.txt");}// Writing the Parameter for Full PDF including the Chebyshev-Polynomial } stringstream frameTitle; if(channels==0){frameTitle << "4#mu, m_{H} = "; } if(channels==1){frameTitle << "4e, m_{H} = ";} if(channels==2){frameTitle << "2e2#mu, m_{H} = ";} frameTitle << massBin << " GeV"; stringstream nameFileRoot; nameFileRoot << "fitM" << massBin << ".root"; TFile *fileplot = TFile::Open(nameFileRoot.str().c_str(), "recreate"); RooPlot* xframe = x.frame() ; xframe->SetTitle(""); xframe->SetName("m4lplot"); dataset.plotOn(xframe,DataError(RooAbsData::SumW2), MarkerStyle(kOpenCircle), MarkerSize(1.1) ); int col; if(channels==0) col=kOrange+7; if(channels==1) col=kAzure+2; if(channels==2) col=kGreen+3; totPDF.plotOn(xframe,LineColor(col)); RooHist* hpull = xframe->pullHist(); RooPlot* frame3 = x.frame(Title("Pull Distribution")) ; frame3->addPlotable(hpull,"P"); // cosmetics TLegend *legend = new TLegend(0.20,0.45,0.45,0.60,NULL,"brNDC"); legend->SetBorderSize(0); legend->SetFillColor(0); legend->SetTextAlign(12); legend->SetTextFont (42); legend->SetTextSize (0.03); TH1F *dummyPoints = new TH1F("dummyP","dummyP",1,0,1); TH1F *dummyLine = new TH1F("dummyL","dummyL",1,0,1); dummyPoints->SetMarkerStyle(kOpenCircle); dummyPoints->SetMarkerSize(1.1); dummyLine->SetLineColor(col); legend->AddEntry(dummyPoints, "Simulation", "pe"); legend->AddEntry(dummyLine, "Parametric Model", "l"); TPaveText *text = new TPaveText(0.15,0.90,0.77,0.98,"brNDC"); text->AddText("CMS Simulation"); text->SetBorderSize(0); text->SetFillStyle(0); text->SetTextAlign(12); text->SetTextFont(42); text->SetTextSize(0.03); TPaveText *titlet = new TPaveText(0.15,0.80,0.60,0.85,"brNDC"); titlet->AddText(frameTitle.str().c_str()); titlet->SetBorderSize(0); titlet->SetFillStyle(0); titlet->SetTextAlign(12); titlet->SetTextFont(132); titlet->SetTextSize(0.045); TPaveText *sigmat = new TPaveText(0.15,0.65,0.77,0.78,"brNDC"); stringstream sigmaval0, sigmaval1, sigmaval2; sigmaval0 << fixed; sigmaval0 << setprecision(1); sigmaval0 << "m_{dCB} = " << mean.getVal() + massBin << " GeV"; sigmaval1 << fixed; sigmaval1 << setprecision(1); sigmaval1 << "#sigma_{dCB} = " << sigma.getVal() << " GeV"; sigmaval2 << fixed; sigmaval2 << setprecision(1); sigmaval2 << "RMS_{eff} = " << effSigma(hmass) << " GeV"; sigmat->AddText(sigmaval1.str().c_str()); sigmat->AddText(sigmaval2.str().c_str()); sigmat->SetBorderSize(0); sigmat->SetFillStyle(0); sigmat->SetTextAlign(12); sigmat->SetTextFont(132); sigmat->SetTextSize(0.04); xframe->GetYaxis()->SetTitleOffset(1.5); cout << "EFF RMS = " << effSigma(hmass) << " RMS = " << hmass->GetRMS() << endl; pad1->cd(); stringstream nameFile, nameFileC, nameFilePng; nameFile << "fitM" << massBin << "_channel" << channels<< "_category"<< categ << ".pdf"; nameFileC << "fitM" << massBin << "_channel" << channels << "_category"<< categ << ".C"; nameFilePng << "fitM" << massBin << "_channel" << channels << "_category"<< categ << ".png"; xframe->Draw(); gPad->Update(); legend->Draw(); text->Draw(); sigmat->Draw(); titlet->Draw(); pad2->cd() ; frame3->Draw() ; frame3->SetMinimum(-3); frame3->SetMaximum(3); TLine *line1 = new TLine(105,0,140,0); line1->SetLineColor(kRed); line1->Draw(); c1->Print(nameFile.str().c_str()); c1->SaveAs(nameFileC.str().c_str()); c1->SaveAs(nameFilePng.str().c_str()); fileplot->cd(); xframe->Write(); sigmat->Write(); hmass->Write(); fileplot->Close(); if(fitValues!=0){ fitValues[0] = a1.getVal(); fitValues[1] = a2.getVal(); fitValues[2] = mean.getVal(); fitValues[3] = mean3.getVal(); fitValues[4] = n1.getVal(); fitValues[5] = n2.getVal(); fitValues[6] = sigma.getVal(); fitValues[7] = A1.getVal(); fitValues[8] = A2.getVal(); } if(fitErrors!=0){ fitErrors[0] = a1.getError(); fitErrors[1] = a2.getError(); fitErrors[2] = mean.getError(); fitErrors[3] = mean3.getError(); fitErrors[4] = n1.getError(); fitErrors[5] = n2.getError(); fitErrors[6] = sigma.getError(); fitErrors[7] = A1.getError(); fitErrors[8] = A2.getError(); } covQual[0] = fitres->covQual(); }
vector<double> FitBkg(TH1D* histo, TString _bkg ){ setTDRStyle(); vector<double> vec; int n = histo->GetEntries(); double w = histo->GetXaxis()->GetBinWidth(1); int ndf; RooPlot* frame; double hmin0 = histo->GetXaxis()->GetXmin(); double hmax0 = histo->GetXaxis()->GetXmax(); histo->GetXaxis()->SetRangeUser(hmin0,hmax0); // Declare observable x RooRealVar x("x","x",hmin0,hmax0) ; RooDataHist dh("dh","dh",x,Import(*histo,kFALSE)) ; frame = x.frame(Title(histo->GetName())) ; dh.plotOn(frame,DataError(RooAbsData::SumW2), MarkerColor(1),MarkerSize(0.9),MarkerStyle(7)); dh.statOn(frame); x.setRange("R0",0,200) ; //Defining the fitting functions if(_bkg == "Novo"){ //Novo RooRealVar peak("peak","peak",45.,0.,100.); RooRealVar width("width","width",20.,0.,40.) ; RooRealVar tail("tail","tail",0.01,0.,1.) ; RooNovosibirsk bkg("bkg","Background",x,peak,width,tail); //Fitting RooFitResult* filters = bkg.fitTo(dh/*,Range("R0"),"qr"*/); bkg.plotOn(frame,LineColor(2)); bkg.paramOn(frame); vec.push_back(peak.getVal()); vec.push_back(width.getVal()); vec.push_back(tail.getVal()); } if(_bkg == "Cheb"){ //Chebychev RooRealVar a0("a0","a0",-1,-5.,0.) ; RooRealVar a1("a1","a1",0,-2,1.2) ; RooRealVar a2("a2","a2",0,-1.,1.) ; RooRealVar a3("a3","a3",0,-2.5,0.) ; RooRealVar a4("a4","a4",0,-1.,1.) ; RooRealVar a5("a5","a5",0,-1.,1.) ; RooRealVar a6("a6","a6",0,-1.,1.) ; RooChebychev bkg("bkg","Background",x,RooArgSet(a0,a1,a2,a3,a4,a5,a6)); //Fitting RooFitResult* filters = bkg.fitTo(dh,Range("R0"),"qr"); bkg.plotOn(frame,LineColor(2)); bkg.paramOn(frame); vec.push_back(a0.getVal()); vec.push_back(a1.getVal()); vec.push_back(a2.getVal()); vec.push_back(a3.getVal()); vec.push_back(a4.getVal()); vec.push_back(a5.getVal()); vec.push_back(a6.getVal()); } if(_bkg == "Land"){ //Background fitting function //Landau (X) Gauss RooRealVar resp_mean("resp_mean","resp_mean",1,0.,20) ; RooRealVar resp_sigma("resp_sigma","resp_sigma",20,5,30) ; RooGaussian resp_bkg("resp","gauss",x,resp_mean,resp_sigma) ; RooRealVar mean_bkg("mean_bkg","mean",40,30,70) ; RooRealVar sigma_bkg("sigma_bkg","sigma",10,0,20) ; RooLandau Land_bkg("Land","Background",x,mean_bkg,sigma_bkg); sigma_bkg.setRange(30,50); resp_sigma.setRange(5,10); x.setBins(10000,"cache") ; RooFFTConvPdf bkg("bkg","Background",x,Land_bkg,resp_bkg); //Fitting RooFitResult* filters = bkg.fitTo(dh,Range("R0"),"qr"); frame->Draw(); bkg.plotOn(frame,LineColor(2)); bkg.paramOn(frame); vec.push_back(0); vec.push_back(0); vec.push_back(0); } frame->GetXaxis()->SetTitle("Z mass (in GeV/c^{2})"); frame->GetXaxis()->SetTitleOffset(1.2); float binsize = histo->GetBinWidth(1); //Store result in .root file frame->Write(histo->GetName()); return vec; }
int FitInvMassBkg(TH1D* histo, TH1D* histo_bkg, TString signal,TString _bkg){ //Set Style setTDRStyle(); cout<<"21"<<endl; //Path for input and output file. Written in FitDataPath.txt ifstream file("FitDataPath.txt"); string str; getline(file,str); TString _path = str; //Rebin(histo); //Getting info about the histogram to fit int n = histo->GetEntries(); double w = histo->GetXaxis()->GetBinWidth(1); int ndf; double hmin0 = histo->GetXaxis()->GetXmin(); double hmax0 = histo->GetXaxis()->GetXmax(); histo->GetXaxis()->SetRangeUser(hmin0,hmax0); //Declare observable x //Try to rebin using this. Doesn't work for now //RooBinning xbins = Rebin2(histo); RooRealVar x("x","x",hmin0,hmax0) ; RooDataHist dh("dh","dh",x,Import(*histo)) ; //Define the frame RooPlot* frame; frame = x.frame(); dh.plotOn(frame,DataError(RooAbsData::SumW2), MarkerColor(1),MarkerSize(0.9),MarkerStyle(7)); //this will show histogram data points on canvas //x.setRange("R0",0,200) ; x.setRange("R1",55,200) ; ///////////////////// //Define fit function ///////////////////// //fsig for adding two funciton i.e. F(x) = fsig*sig(x) + (1-fsig)*bkg(x) RooRealVar fsig("fsig","sigal fraction",0.5, 0., 1.);//before 0.9 //Various parameters //True mean RooRealVar mean("mean","PDG mean of Z",91.186);//, 70.0, 120.0); //For the BW RooRealVar width("width","PDG width of Z",2.4952);//, 0., 5.); //For the Gauss and the CB alone RooRealVar sigma("sigma","sigma",1, 0., 10.); RooRealVar alpha("alpha","alpha",0.7, 0., 7); RooRealVar ncb("ncb","ncb",7, 0, 150); //For the CB used for convolution, i.e. CBxBW RooRealVar cb_bias("cb_bias","bias",0, -3.,3.); RooRealVar cb_sigma("cb_sigma","response",1, 0.,5); RooRealVar cb_alpha("cb_alpha","alpha",1.,0.,7); RooRealVar cb_ncb("cb_ncb","ncb",2, 0, 10); mean.setRange(88,94); width.setRange(0,20); sigma.setRange(0.5,10); //fsig.setConstant(kTRUE); //alpha.setConstant(kTRUE); RooVoigtian sig_bwgau("sig_bwgau","BWxgauss",x,mean,width,sigma); RooBreitWigner sig_bw("sig_bw","BW",x,mean,width); RooGaussian sig_gau("sig_gau","gauss",x,mean,sigma); RooCBShape sig_cb("sig_cb", "Crystal Ball",x,mean,sigma,alpha,ncb); RooCBShape sig_cb_resp("sig_cb_resp", "Crystal Ball for conv.",x,cb_bias,cb_sigma,cb_alpha,cb_ncb); x.setBins(10000,"cache"); RooFFTConvPdf sig_cbbw("sig_cbbw","CBxBW",x,sig_cb_resp,sig_bw); //NB: The CrystalBall shape is Gaussian that is 'connected' to an exponential taill at 'alpha' sigma of the Gaussian. The sign determines if it happens on the left or right side. The 'n' parameter control the slope of the exponential part. RooAbsPdf* sig; if(signal == "BWxGau"){sig = &sig_bwgau;} else if(signal == "BW"){sig = &sig_bw;} else if(signal == "Gau"){sig = &sig_gau;} else if(signal == "CB"){sig = &sig_cb;} else if(signal == "CBxBW"){ sig = &sig_cbbw;} else{ cout<<"Wrong signal function name"<<endl; return 1; } ///////////////////////////// //Background fitting function ///////////////////////////// //Get the initial parameter of the background // vector<double> vec = FitBkg(histo_bkg,_bkg); //Chebychev RooRealVar a0("a0","a0",vec[0],-5.,0.) ; RooRealVar a1("a1","a1",vec[1],-2,1.2) ; RooRealVar a2("a2","a2",vec[2],-1.,1.) ; RooRealVar a3("a3","a3",vec[3],-2.5,0.) ; RooRealVar a4("a4","a4",vec[4],-1.,1.) ; RooRealVar a5("a5","a5",vec[5],-1.,1.) ; RooRealVar a6("a6","a6",vec[6],-1.,1.) ; RooChebychev bkg_cheb("bkg","Background",x,RooArgSet(a0,a1,a2,a3,a4,a5,a6)); //Novo RooRealVar peak_bkg("peak_bkg","peak",vec[0],0,250); RooRealVar width_bkg("width_bkg","width",vec[1],0,1) ; RooRealVar tail_bkg("tail_bkg","tail",vec[2],0,10) ; RooNovosibirsk bkg_nov("bkg","Background",x,peak_bkg,width_bkg,tail_bkg); RooAbsPdf* bkg; if(_bkg == "Cheb"){bkg = &bkg_cheb;} if(_bkg == "Novo"){bkg = &bkg_nov;} ////////////////////////// //Adding the two functions ////////////////////////// RooAddPdf model("model","Signal+Background", RooArgList(*sig,*bkg),fsig); //Perform the fit RooAbsPdf* fit_func; fit_func = &model; RooFitResult* filters = fit_func->fitTo(dh,Range("R1"),"qr"); fit_func->plotOn(frame); fit_func->plotOn(frame,Components(*sig),LineStyle(kDashed),LineColor(kRed)); fit_func->plotOn(frame,Components(*bkg),LineStyle(kDashed),LineColor(kGreen)); frame->Draw(); fit_func->paramOn(frame); dh.statOn(frame); //this will display hist stat on canvas frame->SetTitle(histo->GetTitle()); frame->GetXaxis()->SetTitle("m (in GeV/c^{2})"); frame->GetXaxis()->SetTitleOffset(1.2); float binsize = histo->GetBinWidth(1); //Store result in .root file frame->SetName(histo->GetName()); frame->Write(); return 0; }
double FitInvMassBkg_v3(TH1D* histo, TH1D* histo_bkg, TString signal = "CBxBW",TString _bkg = "Cheb", TString option = ""){ //Set Style setTDRStyle(); if(option.Contains("nentries")){return histo->GetEntries()-histo_bkg->GetEntries();} else{ //Getting info about the histogram to fit int n = histo->GetEntries(); double w = histo->GetXaxis()->GetBinWidth(1); int ndf; double hmin0 = histo->GetXaxis()->GetXmin(); double hmax0 = histo->GetXaxis()->GetXmax(); histo->GetXaxis()->SetRangeUser(hmin0,hmax0); //Declare observable x //Try to rebin using this. Doesn't work for now //RooBinning xbins = Rebin2(histo); RooRealVar x("x","x",hmin0,hmax0) ; RooDataHist dh("dh","dh",x,Import(*histo)) ; //Define the frame RooPlot* frame; frame = x.frame(); dh.plotOn(frame,DataError(RooAbsData::SumW2), MarkerColor(1),MarkerSize(0.9),MarkerStyle(7)); //this will show histogram data points on canvas //x.setRange("R0",0,200) ; x.setRange("R1",55,200) ; x.setRange("D",55,120) ; ///////////////////// //Define fit function ///////////////////// cout<<"Debug4"<<endl; //fsig for adding two funciton i.e. F(x) = fsig*sig(x) + (1-fsig)*bkg(x) //RooRealVar fsig("fsig","sigal fraction",0.5, 0., 1.); RooRealVar nsig("nsig","signal events",histo->GetEntries()/2., 1,histo->GetEntries()); RooRealVar nbkg("nbkg","background events",histo_bkg->GetEntries()/2.,1,histo_bkg->GetEntries()); RooArgList pdfval(nsig,nbkg); //Various parameters //True mean RooRealVar mean("mean","PDG mean of Z",91.186);//, 70.0, 120.0); //For the BW RooRealVar width("width","PDG width of Z",2.4952);//, 0., 5.); //For the Gauss and the CB alone RooRealVar sigma("sigma","sigma",1, 0., 10.); RooRealVar alpha("alpha","alpha",0.7, 0., 7); RooRealVar ncb("ncb","ncb",7, 0, 150); //For the CB used for convolution, i.e. CBxBW RooRealVar cb_bias("cb_bias","bias",0, -3.,3.); RooRealVar cb_sigma("cb_sigma","response",1, 0.,5); RooRealVar cb_alpha("cb_alpha","alpha",1.,0.,7); RooRealVar cb_ncb("cb_ncb","ncb",2, 0, 10); //Gauss used for convolution RooRealVar gau_bias("gau_bias","alpha",0, -3., 3.); RooRealVar gau_sigma("gau_sigma","bias",1, 0., 7.); cout<<"Debug5"<<endl; mean.setRange(88,94); width.setRange(0,20); sigma.setRange(0.5,10); //fsig.setConstant(kTRUE); //alpha.setConstant(kTRUE); RooVoigtian sig_voigtian("sig_voigtian","Voigtian",x,mean,width,sigma); RooBreitWigner sig_bw("sig_bw","BW",x,mean,width); //RooGaussian sig_gau("sig_gau","gauss",x,mean,sigma); RooCBShape sig_cb("sig_cb", "Crystal Ball",x,mean,sigma,alpha,ncb); RooCBShape sig_cb_resp("sig_cb_resp", "Crystal Ball for conv.",x,cb_bias,cb_sigma,cb_alpha,cb_ncb); RooGaussian sig_gau_resp("sig_gau_resp", "Gaussian for conv.",x,gau_bias,gau_sigma); x.setBins(10000,"cache"); RooFFTConvPdf sig_cbbw("sig_cbbw","CBxBW",x,sig_cb_resp,sig_bw); RooFFTConvPdf sig_bwgau("sig_bwgau","BWxGau",x,sig_bw,sig_gau_resp); //NB: The CrystalBall shape is Gaussian that is 'connected' to an exponential taill at 'alpha' sigma of the Gaussian. The sign determines if it happens on the left or right side. The 'n' parameter control the slope of the exponential part. cout<<"Debug6"<<endl; RooAbsPdf* sig; if(signal == "Vo"){sig = &sig_bwgau;} else if(signal == "BW"){sig = &sig_bw;} //else if(signal == "Gau"){sig = &sig_gau;} else if(signal == "CB"){sig = &sig_cb;} else if(signal == "CBxBW"){ sig = &sig_cbbw;} else if(signal == "BWxGau"){ sig = &sig_bwgau;} else{ cout<<"Wrong signal function name"<<endl; return 1; } ///////////////////////////// //Background fitting function ///////////////////////////// //Get the initial parameter of the background // cout<<"Debug7"<<endl; vector<double> vec = FitBkg(histo_bkg,_bkg); //Chebychev RooRealVar a0("a0","a0",vec[0],-5.,0.) ; RooRealVar a1("a1","a1",vec[1],-2.5,1.2) ; RooRealVar a2("a2","a2",vec[2],-1.5,1.) ; RooRealVar a3("a3","a3",vec[3],-3,1.) ; RooRealVar a4("a4","a4",vec[4],-1.5,1.) ; RooRealVar a5("a5","a5",vec[5],-1.,1.) ; RooRealVar a6("a6","a6",vec[6],-1.,1.) ; RooChebychev bkg_cheb("bkg","Background",x,RooArgSet(a0,a1,a2,a3,a4,a5,a6)); //Novo RooRealVar peak_bkg("peak_bkg","peak",vec[0],0,250); RooRealVar width_bkg("width_bkg","width",vec[1],0,1) ; RooRealVar tail_bkg("tail_bkg","tail",vec[2],0,10) ; RooNovosibirsk bkg_nov("bkg","Background",x,peak_bkg,width_bkg,tail_bkg); RooAbsPdf* bkg; if(_bkg == "Cheb"){bkg = &bkg_cheb;} if(_bkg == "Novo"){bkg = &bkg_nov;} ////////////////////////// //Adding the two functions ////////////////////////// //RooAddPdf model("model","Signal+Background", RooArgList(*sig,*bkg),fsig); RooAddPdf model("model","Signal+Background", RooArgList(*sig,*bkg),pdfval); //Perform the fit RooAbsPdf* fit_func; fit_func = &model; RooFitResult* filters = fit_func->fitTo(dh,Range("R1"),"qr"); fit_func->plotOn(frame); fit_func->plotOn(frame,Components(*sig),LineStyle(kDashed),LineColor(kRed)); fit_func->plotOn(frame,Components(*bkg),LineStyle(kDashed),LineColor(kGreen)); frame->SetAxisRange(50,120); frame->Draw(); fit_func->paramOn(frame); dh.statOn(frame); //this will display hist stat on canvas frame->SetTitle(histo->GetTitle()); frame->GetXaxis()->SetTitle("m (in GeV/c^{2})"); frame->GetXaxis()->SetTitleOffset(1.2); float binsize = histo->GetBinWidth(1); //Store result in .root file frame->SetName(histo->GetName()); frame->Write(); /////////////////////// //Plot the efficiency// /////////////////////// //Old stuff //ofstream myfile; //myfile.open("/Users/GLP/Desktop/integrals.txt"); //This one doesn't take the normalisation into account ! //myfile<<"integral 1 "<<histo->GetName()<<endl; ////Integral of sig //RooAbsReal* integral_sig = sig->createIntegral(x,x,"D") ; //myfile<<fsig.getVal()*integral_sig->getVal()<<endl; //Integral of sig+bkg //RooAbsReal* total = fit_func->createIntegral(x, NormSet(x), Range("D")) ; //Integral of sig only //RooAbsReal* background = bkg->createIntegral(x, NormSet(x), Range("D")); //cout<<"The total integral is"<<n*total->getVal(); //cout<<"The bkg integral is"<<n*bkg->getVal(); //cout<<"The bkg with the fsig is"<<fsig.getVal()*n*bkg->getVal(); //cout<<"The returned value is"<<n*(total->getVal()-fsig.getVal()*background->getVal()); //myfile<<"integral 2 "<<endl; //myfile<<n*(total->getVal()-(1-fsig.getVal())*background->getVal())<<endl; //myfile.close(); //return n*(total->getVal()-(1-fsig.getVal())*background->getVal()); return nsig.getVal(); } }
vector<double> FitInvMass(TH1D* histo){ vector<double> vec; gROOT->ProcessLine(".x ~/rootlogon.C"); int n = histo->GetEntries(); double w = histo->GetXaxis()->GetBinWidth(1); int ndf; RooPlot* frame; double hmin0 = histo->GetXaxis()->GetXmin(); double hmax0 = histo->GetXaxis()->GetXmax(); histo->GetXaxis()->SetRangeUser(hmin0,hmax0); // Declare observable x RooRealVar x("x","x",hmin0,hmax0) ; RooDataHist dh("dh","dh",x,Import(*histo)) ; frame = x.frame(Title(histo->GetName())) ; dh.plotOn(frame,DataError(RooAbsData::SumW2), MarkerColor(1),MarkerSize(0.9),MarkerStyle(7)); //this will show histogram data points on canvas dh.statOn(frame); //this will display hist stat on canvas x.setRange("R0",90.5,91) ; x.setRange("R1",70,110) ; x.setRange("R2",60,120) ; x.setRange("R3",50,130) ; RooRealVar mean("mean","mean",91.186/*histo->GetMean()*/, 70.0, 120.0); RooRealVar width("width","width",7.5, 0, 30.0); RooRealVar sigma("sigma","sigma",0, 0.0, 120.0); mean.setRange(88,94); width.setRange(0,20); sigma.setRange(0,10); //Choose the fitting here //RooGaussian gauss("gauss","gauss",x,mean,sigma);ndf = 2; RooBreitWigner gauss("gauss","gauss",x,mean,width);ndf = 2; //RooVoigtian gauss("gauss","gauss",x,mean,width,sigma); ndf = 3; RooFitResult* filters = gauss.fitTo(dh,Range("R1"),"qr"); gauss.plotOn(frame,LineColor(4));//this will show fit overlay on canvas gauss.paramOn(frame); //this will display the fit parameters on canvas //TCanvas* b1 = new TCanvas("b1","b1",1200,800); //gPad->SetLeftMargin(0.15); //frame->GetXaxis()->SetTitle("Z mass (in GeV/c^{2})"); //frame->GetXaxis()->SetTitleOffset(1.2); //float binsize = histo->GetBinWidth(1); //frame->Draw() ; cout<<"The chi2 is:"<<endl; cout<<frame->chiSquare(ndf)<<endl; cout<<" "<<endl; //Do the integral //Store result in .root file frame->Write(histo->GetTitle()); RooAbsReal* integral = gauss.createIntegral(x, NormSet(x), Range("R1")) ; vec.push_back(n*integral->getVal()); //vec.push_back((double)n); vec.push_back((double)frame->chiSquare(ndf)); return vec; }
void rf106_plotdecoration() { // S e t u p m o d e l // --------------------- // Create observables RooRealVar x("x","x",-10,10) ; // Create Gaussian RooRealVar sigma("sigma","sigma",1,0.1,10) ; RooRealVar mean("mean","mean",-3,-10,10) ; RooGaussian gauss("gauss","gauss",x,mean,sigma) ; // Generate a sample of 1000 events with sigma=3 RooDataSet* data = gauss.generate(x,1000) ; // Fit pdf to data gauss.fitTo(*data) ; // P l o t p . d . f a n d d a t a // ------------------------------------- // Overlay projection of gauss on data RooPlot* frame = x.frame(Name("xframe"),Title("RooPlot with decorations"),Bins(40)) ; data->plotOn(frame) ; gauss.plotOn(frame) ; // A d d b o x w i t h p d f p a r a m e t e r s // ----------------------------------------------------- // Left edge of box starts at 55% of Xaxis) gauss.paramOn(frame,Layout(0.55)) ; // A d d b o x w i t h d a t a s t a t i s t i c s // ------------------------------------------------------- // X size of box is from 55% to 99% of Xaxis range, top of box is at 80% of Yaxis range) data->statOn(frame,Layout(0.55,0.99,0.8)) ; // A d d t e x t a n d a r r o w // ----------------------------------- // Add text to frame TText* txt = new TText(2,100,"Signal") ; txt->SetTextSize(0.04) ; txt->SetTextColor(kRed) ; frame->addObject(txt) ; // Add arrow to frame TArrow* arrow = new TArrow(2,100,-1,50,0.01,"|>") ; arrow->SetLineColor(kRed) ; arrow->SetFillColor(kRed) ; arrow->SetLineWidth(3) ; frame->addObject(arrow) ; // P e r s i s t f r a m e w i t h a l l d e c o r a t i o n s i n R O O T f i l e // --------------------------------------------------------------------------------------------- TFile f("rf106_plotdecoration.root","RECREATE") ; frame->Write() ; f.Close() ; // To read back and plot frame with all decorations in clean root session do // root> TFile f("rf106_plotdecoration.root") ; // root> xframe->Draw() ; new TCanvas("rf106_plotdecoration","rf106_plotdecoration",600,600) ; gPad->SetLeftMargin(0.15) ; frame->GetYaxis()->SetTitleOffset(1.6) ; frame->Draw() ; }