コード例 #1
1
void Fitter::MakePlots(const string& name, const string& title, RooPlot*& pPlot1, RooPlot*& pPlot2, RooAbsPdf* pPdf, RooDataSet* pData)
{
	bool plotbkg = false;
	RooPlot* pFrame = pPlot1? pPlot1 : pFitVar->frame(RooFit::Bins(50), RooFit::Name(name.c_str()), RooFit::Title(title.c_str()));
	RooPlot* pFramePull = pPlot2? pPlot2 : pFitVar->frame(RooFit::Bins(50), RooFit::Name((name+"_Pull").c_str()), RooFit::Title((title+" Pull").c_str()));
	RooHist* pHisPull = NULL;
	double pullMax = 0.;
	
	if(!pPdf && !pData) plotbkg = true;
	if(!pPdf) pPdf = pTotPdf;
	if(!pData) pData = this->pData;
	
	pData->plotOn(pFrame, RooFit::MarkerSize(0.9));
	
	if(plotbkg)
	{
		RooArgList bkgComponent;
		for(auto& pdf : bkgPdfs) bkgComponent.add(pdf.GetPdf());
		pTotPdf->plotOn(pFrame, RooFit::Components(bkgComponent), RooFit::LineColor(kGreen) );
	}
	
	pPdf->plotOn(pFrame, RooFit::LineColor(kRed));	
	pPdf->paramOn(pFrame, RooFit::Format("NEU", RooFit::AutoPrecision(1)), RooFit::Layout(0.65, 0.99, 0.93));
	pFrame->getAttText()->SetTextSize(0.75*pFrame->GetYaxis()->GetLabelSize());
	
	pHisPull = pFrame->pullHist();
	pFramePull->addPlotable(pHisPull, "P");
	pullMax = max(fabs(pFramePull->GetMinimum()), pFramePull->GetMaximum());
	pFramePull->GetYaxis()->SetRangeUser(-pullMax,pullMax);
	
	pPlot1 = pFrame;
	pPlot2 = pFramePull;
}
コード例 #2
0
ファイル: ws_v05.C プロジェクト: gioveneziano/radiative
void plot_with_residuals(TCanvas& _c,RooPlot& _frame,RooRealVar& var,Int_t& _nbins,Double_t& r_min,Double_t& r_max) {

    _c.SetName("_c");
    _c.Divide(1,2);
    _c_1->SetPad(0.01,0.16,0.99,0.99);
    _c_2->SetPad(0.01,0.01,0.99,0.16);

    _c.cd(1);
    _frame.Draw();

    _c.cd(2);
    RooHist* hpull = _frame.pullHist();

    RooPlot* frame_pull = var.frame(Title(" "),Range(r_min,r_max),Bins(_nbins));
    frame_pull->addPlotable(hpull,"P");

    // this is if you want residuals in number of events
    /*RooHist* hresid = _frame -> residHist();*/
    /*RooPlot* frame2 = m_Kpipi.frame(1000,2000,25);*/
    /*frame2->addPlotable(hresid,"P");*/

    frame_pull->SetMinimum(-5);
    frame_pull->SetMaximum(+5);
    frame_pull->SetNdivisions(0,"x"); // 510 for having also an x scale here
    frame_pull->SetNdivisions(203,"y");   // axis divisions was 510
    frame_pull->SetXTitle(" ");
    frame_pull->SetLabelSize(0.15,"Y");
    frame_pull->Draw();

    TLine *_line = new TLine(r_min,-3.,r_max,-3);
    _line->SetLineStyle(1);
    _line->SetLineColor(2);
    _line->SetLineWidth(1);
    _line->Draw();
    _line2 = new TLine(r_min,+3.,r_max,+3);
    _line2->SetLineStyle(1);
    _line2->SetLineColor(2);
    _line2->SetLineWidth(1);
    _line2->Draw();

}
コード例 #3
0
void MEPdfPartialB::DrawDeltaE(RooDataSet* ds){
  mbc->setRange("mbcSignal",cuts->get_mbc_min_h0(m_mode,m_h0mode),cuts->get_mbc_max_h0(m_mode,m_h0mode));
  RooPlot* deFrame = de->frame();
  ds->plotOn(deFrame,DataError(RooAbsData::SumW2),MarkerSize(1),MarkerColor(kGreen));
  pdf_part->plotOn(deFrame,LineWidth(2),LineColor(kGreen));
  ds->plotOn(deFrame,DataError(RooAbsData::SumW2),MarkerSize(1),CutRange("mbcSignal"));
  pdf_part->plotOn(deFrame,LineWidth(2),ProjectionRange("mbcSignal"));

  RooHist* hdepull = deFrame->pullHist();
  RooPlot* dePull = de->frame(Title("#Delta E pull distribution"));
  dePull->addPlotable(hdepull,"P");
  dePull->GetYaxis()->SetRangeUser(-5,5);

  TCanvas* cm = new TCanvas("Delta E","Delta E",600,700);
  cm->cd();

  TPad *pad3 = new TPad("pad3","pad3",0.01,0.20,0.99,0.99);
  TPad *pad4 = new TPad("pad4","pad4",0.01,0.01,0.99,0.20);
  pad3->Draw();
  pad4->Draw();

  pad3->cd();
  pad3->SetLeftMargin(0.15);
  pad3->SetFillColor(0);

  deFrame->GetXaxis()->SetTitleSize(0.05);
  deFrame->GetXaxis()->SetTitleOffset(0.85);
  deFrame->GetXaxis()->SetLabelSize(0.04);
  deFrame->GetYaxis()->SetTitleOffset(1.6);
  deFrame->Draw();

  stringstream out;
  out.str("");
  out << "#chi^{2}/n.d.f = " << deFrame->chiSquare();
  TPaveText *pt = new TPaveText(0.6,0.75,0.98,0.9,"brNDC");
  pt->SetFillColor(0);
  pt->SetTextAlign(12);
  pt->AddText(out.str().c_str());
  pt->AddText(cuts->GetLabel(m_mode,m_h0mode).c_str());
  pt->Draw();

  TLine *de_line_RIGHT = new TLine(cuts->get_de_min_h0(m_mode,m_h0mode),0,cuts->get_de_min_h0(m_mode,m_h0mode),80);
  de_line_RIGHT->SetLineColor(kRed);
  de_line_RIGHT->SetLineStyle(1);
  de_line_RIGHT->SetLineWidth((Width_t)2.);
  de_line_RIGHT->Draw();
  TLine *de_line_LEFT = new TLine(cuts->get_de_max_h0(m_mode,m_h0mode),0,cuts->get_de_max_h0(m_mode,m_h0mode),80);
  de_line_LEFT->SetLineColor(kRed);
  de_line_LEFT->SetLineStyle(1);
  de_line_LEFT->SetLineWidth((Width_t)2.);
  de_line_LEFT->Draw();

  pad4->cd(); pad4->SetLeftMargin(0.15); pad4->SetFillColor(0);
  dePull->SetMarkerSize(0.05); dePull->Draw();
  TLine *de_lineUP = new TLine(cuts->get_de_fit_min(),3,cuts->get_de_fit_max(),3);
  de_lineUP->SetLineColor(kBlue);
  de_lineUP->SetLineStyle(2);
  de_lineUP->Draw();
  TLine *de_line = new TLine(cuts->get_de_fit_min(),0,cuts->get_de_fit_max(),0);
  de_line->SetLineColor(kBlue);
  de_line->SetLineStyle(1);
  de_line->SetLineWidth((Width_t)2.);
  de_line->Draw();
  TLine *de_lineDOWN = new TLine(cuts->get_de_fit_min(),-3,cuts->get_de_fit_max(),-3);
  de_lineDOWN->SetLineColor(kBlue);
  de_lineDOWN->SetLineStyle(2);
  de_lineDOWN->Draw();

  cm->Update();
  out.str("");
  out << "pics/de_part_m" << m_mode << "_h0m" << m_h0mode << ".eps";
  cm->Print(out.str().c_str());
  string line = string("evince ") + out.str() + string(" &");
  system(line.c_str());
  out.str("");
  out << "pics/de_part_m" << m_mode << "_h0m" << m_h0mode << ".root";
  cm->Print(out.str().c_str());
}
コード例 #4
0
ファイル: results2tree.C プロジェクト: echapon/HiCharm2015
void results2tree(
      const char* workDirName, 
      bool isMC=false,
      const char* thePoiNames="RFrac2Svs1S,N_Jpsi,f_Jpsi,m_Jpsi,sigma1_Jpsi,alpha_Jpsi,n_Jpsi,sigma2_Jpsi,MassRatio,rSigma21_Jpsi,lambda1_Bkg,lambda2_Bkg,lambda3_Bkg,lambda4_Bkg,lambda5__Bkg,N_Bkg"
      ) {
   // workDirName: usual tag where to look for files in Output
   // thePoiNames: comma-separated list of parameters to store ("par1,par2,par3"). Default: all

   TFile *f = new TFile(treeFileName(workDirName,isMC),"RECREATE");
   TTree *tr = new TTree("fitresults","fit results");


   // bin edges
   float ptmin, ptmax, ymin, ymax, centmin, centmax;
   // model names
   Char_t jpsiName[128], psipName[128], bkgName[128];
   // collision system
   Char_t collSystem[8];
   // goodness of fit
   float nll, chi2, normchi2; int npar, ndof;
   // parameters to store: make it a vector
   vector<poi> thePois;
   TString thePoiNamesStr(thePoiNames);
   TString t; Int_t from = 0;
   while (thePoiNamesStr.Tokenize(t, from , ",")) {
      poi p; strcpy(p.name, t.Data());
      cout << p.name << endl;
      thePois.push_back(p);
   }

   // create tree branches
   tr->Branch("ptmin",&ptmin,"ptmin/F");
   tr->Branch("ptmax",&ptmax,"ptmax/F");
   tr->Branch("ymin",&ymin,"ymin/F");
   tr->Branch("ymax",&ymax,"ymax/F");
   tr->Branch("centmin",&centmin,"centmin/F");
   tr->Branch("centmax",&centmax,"centmax/F");
   tr->Branch("jpsiName",jpsiName,"jpsiName/C");
   tr->Branch("psipName",psipName,"psipName/C");
   tr->Branch("bkgName",bkgName,"bkgName/C");
   tr->Branch("collSystem",collSystem,"collSystem/C");
   tr->Branch("nll",&nll,"nll/F");
   tr->Branch("chi2",&chi2,"chi2/F");
   tr->Branch("normchi2",&normchi2,"normchi2/F");
   tr->Branch("npar",&npar,"npar/I");
   tr->Branch("ndof",&ndof,"ndof/I");

   for (vector<poi>::iterator it=thePois.begin(); it!=thePois.end(); it++) {
      tr->Branch(Form("%s_val",it->name),&(it->val),Form("%s_val/F",it->name));
      tr->Branch(Form("%s_err",it->name),&(it->err),Form("%s_err/F",it->name));
   }

   // list of files
   vector<TString> theFiles = fileList(workDirName,"",isMC);

   int cnt=0;
   for (vector<TString>::const_iterator it=theFiles.begin(); it!=theFiles.end(); it++) {
      cout << "Parsing file " << cnt << " / " << theFiles.size() << ": " << *it << endl;

      // parse the file name to get info
      anabin thebin = binFromFile(*it);
      ptmin = thebin.ptbin().low();
      ptmax = thebin.ptbin().high();
      ymin = thebin.rapbin().low();
      ymax = thebin.rapbin().high();
      centmin = thebin.centbin().low();
      centmax = thebin.centbin().high();
      strcpy(collSystem, (it->Index("PbPb")>0) ? "PbPb" : "PP");

      // get the model names
      from = 0;
      bool catchjpsi=false, catchpsip=false, catchbkg=false;
      while (it->Tokenize(t, from, "_")) {
         if (catchjpsi) {strcpy(jpsiName, t.Data()); catchjpsi=false;}
         if (catchpsip) {strcpy(psipName, t.Data()); catchpsip=false;}
         if (catchbkg) {strcpy(bkgName, t.Data()); catchbkg=false;}
         if (t=="Jpsi") catchjpsi=true;
         if (t=="Psi2S") catchpsip=true;
         if (t=="Bkg") catchbkg=true;
      }

      TFile *f = new TFile(*it); RooWorkspace *ws = NULL;
      if (!f) {
         cout << "Error, file " << *it << " does not exist." << endl;
      } else {
         ws = (RooWorkspace*) f->Get("workspace");
         if (!ws) {
            cout << "Error, workspace not found in " << *it << "." << endl;
         }
      }

      nll=0; chi2=0; npar=0; ndof=0;
      if (f && ws) {
         // get the model for nll and npar
         RooAbsPdf *model = pdfFromWS(ws, Form("_%s",collSystem), "pdfMASS_Tot");
         if (model) {
            RooAbsData *dat = dataFromWS(ws, Form("_%s",collSystem), "dOS_DATA");
            if (dat) {
               RooAbsReal *NLL = model->createNLL(*dat);
               if (NLL) nll = NLL->getVal();
               npar = model->getParameters(dat)->selectByAttrib("Constant",kFALSE)->getSize();

               // compute the chi2 and the ndof
               RooPlot* frame = ws->var("invMass")->frame(Bins(nBins));
               dat->plotOn(frame);
               model->plotOn(frame);
               TH1 *hdatact = dat->createHistogram("hdatact", *(ws->var("invMass")), Binning(nBins));
               RooHist *hpull = frame->pullHist(0,0, true);
               double* ypulls = hpull->GetY();
               unsigned int nFullBins = 0;
               for (int i = 0; i < nBins; i++) {
                  if (hdatact->GetBinContent(i+1) > 0.0) {
                     chi2 += ypulls[i]*ypulls[i];
                     nFullBins++;
                  }
               }
               ndof = nFullBins - npar;
               normchi2 = chi2/ndof;
            }
         }

         // get the POIs
         for (vector<poi>::iterator itpoi=thePois.begin(); itpoi!=thePois.end(); itpoi++) {
            RooRealVar *thevar = poiFromWS(ws, Form("_%s",collSystem), itpoi->name);
            itpoi->val = thevar ? thevar->getVal() : 0;
            itpoi->err = thevar ? thevar->getError() : 0;
         }

         f->Close();
         delete f;
      } else {
         for (vector<poi>::iterator itpoi=thePois.begin(); itpoi!=thePois.end(); itpoi++) {
            itpoi->val = 0;
            itpoi->err = 0;
         }
      }

      // fill the tree
      tr->Fill();
      cnt++;
   } // loop on the files

   f->Write();
   f->Close();
}
コード例 #5
0
ファイル: PurityFit.cpp プロジェクト: VitalyVorobyev/B0toD0h0
void PurityFit(const int _mode){
  TChain* tree = new TChain("TEvent");
//  tree->Add("/home/vitaly/B0toDh0/TMVA/FIL_b2dh_gen_0-1.root");
  tree->Add("/home/vitaly/B0toDh0/TMVA/FIL1_b2dh_uds_2_12.root");
  tree->Add("/home/vitaly/B0toDh0/TMVA/FIL1_b2dh_charm_2_12.root");
  tree->Add("/home/vitaly/B0toDh0/TMVA/FIL1_b2dh_charged_2_12.root");
  tree->Add("/home/vitaly/B0toDh0/TMVA/FIL1_b2dh_mixed_2_12.root");

  gROOT->ProcessLine(".L pdfs/RooRhoDeltaEPdf.cxx+");

  RooCategory b0f("b0f","b0f");
  b0f.defineType("signal",1);
  b0f.defineType("fsr",10);
  b0f.defineType("bad_pi0",5);
  b0f.defineType("rho2",2);
  b0f.defineType("rho3",3);
  b0f.defineType("rho4",4);
  b0f.defineType("rho11",11);
  b0f.defineType("comb",-1);

  RooCategory mode("mode","mode");
  RooCategory h0mode("h0mode","h0mode");

  double BDTG_MIN = 0;
  double BDTG_MAX = 1;
  bool gg_flag = true;
  double Mbc_min;
  double Mbc_max;
  double dE_min;
  double dE_max;
  int m_mode,m_h0mode;
  double mh0_min, mh0_max;
  string label;
  switch(_mode){
  case 1:
    label = string("#pi^{0}");
    BDTG_MIN = bdt_cut_pi0;
    mode.defineType("pi0",1);
    h0mode.defineType("gg",10);
    Mbc_min = mbc_min_pi0;
    Mbc_max = mbc_max_pi0;
    dE_min  = de_min_pi0;
    dE_max  = de_max_pi0;
    m_mode = 1;
    m_h0mode = 10;
    mh0_min = mpi0_min;
    mh0_max = mpi0_max;
    break;
  case 2:
    label = string("#eta#rightarrow#gamma#gamma");
    BDTG_MIN = bdtg_cut_etagg;
    mode.defineType("eta",2);
    h0mode.defineType("gg",10);
    Mbc_min = mbc_min;
    Mbc_max = mbc_max;
    dE_min  = de_min;
    dE_max  = de_max;
    m_mode = 2;
    m_h0mode = 10;
    mh0_min = EtaGGMass-metagg_cut;
    mh0_max = EtaGGMass+metagg_cut;
    break;
  case 3:
    label = string("#eta#rightarrow#pi^{+}#pi^{-}#pi^{0}");
    BDTG_MIN = bdtg_cut_etappp;
    gg_flag = false;
    mode.defineType("eta",2);
    h0mode.defineType("ppp",20);
    Mbc_min = mbc_min;
    Mbc_max = mbc_max;
    dE_min  = de_min_etappp;
    dE_max  = de_max_etappp;
    m_mode = 2;
    m_h0mode = 20;
    mh0_min = EtaMass-metappp_cut;
    mh0_max = EtaMass+metappp_cut;
    break;
  case 4:
    label = string("#omega");
    BDTG_MIN = bdtg_cut_omega;
    gg_flag = false;
    mode.defineType("omega",3);
    h0mode.defineType("ppp",20);
    Mbc_min = mbc_min_omega;
    Mbc_max = mbc_max_omega;
    dE_min  = de_min_omega;
    dE_max  = de_max_omega;
    m_mode = 3;
    m_h0mode = 20;
    mh0_min = OmegaMass-momega_cut;
    mh0_max = OmegaMass+momega_cut;
    break;
  default:
    return;
  }

  RooArgSet argset;
  argset.add(mode);
  argset.add(h0mode);
  argset.add(b0f);

  RooCategory flv("flv_mc","flv_mc");
  flv.defineType("B0",1);
  flv.defineType("anti-B0",-1);
  argset.add(flv);

  RooCategory bin("bin","bin");
  bin.defineType("1",1); bin.defineType("-1",-1);
  bin.defineType("2",2); bin.defineType("-2",-2);
  bin.defineType("3",3); bin.defineType("-3",-3);
  bin.defineType("4",4); bin.defineType("-4",-4);
  bin.defineType("5",5); bin.defineType("-5",-5);
  bin.defineType("6",6); bin.defineType("-6",-6);
  bin.defineType("7",7); bin.defineType("-7",-7);
  bin.defineType("8",8); bin.defineType("-8",-8);
  argset.add(bin);

  RooSuperCategory binflv("binflv","binflv",RooArgSet(bin,flv));

  const double mbcMin = 5.20;
  const double mbcMax = 5.2885;
  const double deMin = -0.15;
  const double deMax = 0.3;
  const double elliscaleDe  = TMath::Sqrt(4./TMath::Pi());
  const double elliscaleMbc = TMath::Sqrt(4./TMath::Pi());

  RooRealVar mbc_center("mbc_center","mbc_center",0.5*(Mbc_min+Mbc_max),Mbc_min,Mbc_max); mbc_center.setConstant(kTRUE);
  RooRealVar mbc_center_eq("mbc_center_eq","mbc_center_eq",mr_argedge_3-0.5*(Mbc_max-Mbc_min)*elliscaleMbc,Mbc_min,Mbc_max); mbc_center_eq.setConstant(kTRUE);
  RooRealVar de_center("de_center","de_center",0.5*(dE_min+dE_max),dE_min,dE_max); de_center.setConstant(kTRUE);
  RooRealVar mbc_radius("mbc_radius","mbc_radius",0.5*(Mbc_max-Mbc_min)*elliscaleMbc,0,0.5*(mbcMax-mbcMin)); mbc_radius.setConstant(kTRUE);
  RooRealVar de_radius("de_radius","de_radius",0.5*(dE_max-dE_min)*elliscaleDe,0.,0.5*(deMax-deMin)); de_radius.setConstant(kTRUE);
  RooRealVar mbc_radius1("mbc_radius1","mbc_radius1",0.5*(Mbc_max-Mbc_min),0,0.5*(mbcMax-mbcMin)); mbc_radius1.setConstant(kTRUE);
  RooRealVar de_radius1("de_radius1","de_radius1",0.5*(dE_max-dE_min),0.,0.5*(deMax-deMin)); de_radius1.setConstant(kTRUE);

  cout << 0.5*(Mbc_min+Mbc_max) << " " << 0.5*(Mbc_max-Mbc_min) << endl;
  cout << 0.5*(dE_min+dE_max) << " " << 0.5*(dE_max-dE_min) << endl;

  mbc_center.Print();
  mbc_center_eq.Print();

  RooRealVar mbc("mbc","M_{bc}",0.5*(Mbc_min+Mbc_max),mbcMin,mbcMax,"GeV"); argset.add(mbc);
  mbc.setRange("Signal",Mbc_min,Mbc_max);
  mbc.setRange("mbcSignal",Mbc_min,Mbc_max);
  mbc.setRange("deSignal",mbcMin,mbcMax);

  RooRealVar de("de","#DeltaE",deMin,deMax,"GeV"); argset.add(de);
  de.setRange("Signal",dE_min,dE_max);
  de.setRange("mbcSignal",deMin,deMax);
  de.setRange("deSignal",dE_min,dE_max);

//   de.setRange("Ellips",dE_min,dE_max);
//   RooFormulaVar mbclo("mbclo","@1-@2*TMath::Sqrt(1-(@0-@3)/@4*(@0-@3)/@4+0.00001)",RooArgSet(de,mbc_center,mbc_radius,de_center,de_radius));
//   RooFormulaVar mbchi("mbchi","@1+@2*TMath::Sqrt(1-(@0-@3)/@4*(@0-@3)/@4+0.00001)",RooArgSet(de,mbc_center,mbc_radius,de_center,de_radius));
//   mbc.setRange("Ellips",mbclo,mbchi);

  RooRealVar md("md","md",DMass-md_cut,DMass+md_cut,"GeV"); argset.add(md);
  RooRealVar mk("mk","mk",KMass-mk_cut,KMass+mk_cut,"GeV"); argset.add(mk);
  RooRealVar mh0("mh0","mh0",mh0_min,mh0_max,"GeV"); argset.add(mh0);
  RooRealVar mpi0("mpi0","mpi0",mpi0_min,mpi0_max,"GeV"); if(_mode!=2) argset.add(mpi0);
  RooRealVar bdt("bdt","bdt",BDTG_MIN,BDTG_MAX); argset.add(bdt);

  argset.add(b0f);
  RooDataSet ds_sig("ds_sig","ds_sig",tree,argset,"mbc>0||mbc<=0 && (b0f == 1 || b0f == 5 || b0f == 10)");
  RooDataSet ds_bkg("ds_bkg","ds_bkg",tree,argset,"mbc>0||mbc<=0 && !(b0f == 1 || b0f == 5 || b0f == 10)");
  RooDataHist dh("dh","dh");
  dh.add(ds_sig,"",1./0.563);
  dh.add(ds_bkg,"",1./0.949);

  stringstream out;
  out.str("");
  out << "de<" << dE_max << " && de>" << dE_min;
  out << " && mbc>" << Mbc_min << " && mbc<" << Mbc_max;
  Roo1DTable* sigtable = ds.table(b0f,out.str().c_str());
  sigtable->Print();
  sigtable->Print("v");

  Roo1DTable* fulltable = ds.table(b0f);
  fulltable->Print();
  fulltable->Print("v");

//  RooDataHist* dh = ds0->binnedClone();

  ds.Print();
  int _b0f = -1;
  ////////////////
  // Signal PDF //
  ////////////////
  ////////////
  // de pdf //
  ////////////
  if(gg_flag){
    RooRealVar  de0("de0","de0",get_de0(m_mode,m_h0mode,_b0f),-0.2,0.1); if(cSig) de0.setConstant(kTRUE);
    RooRealVar  s1("s1","s1",get_s1(m_mode,m_h0mode,_b0f),0.,0.5);       if(cSig) s1.setConstant(kTRUE);
    RooGaussian g1("g1","g1",de,de0,s1);

    RooRealVar deCBl("deCBl","deCBl",get_deCBl(m_mode,m_h0mode,_b0f),-0.2,0.1); if(cSig) deCBl.setConstant(kTRUE);
    RooRealVar sCBl("sCBl","sCBl",get_sCBl(m_mode,m_h0mode,_b0f),0.,0.5);       if(cSig) sCBl.setConstant(kTRUE);
    RooRealVar alphal("alphal","alphal", get_alphal(m_mode,m_h0mode,_b0f), 0.,10.);                          if(cSIG) alphal.setConstant(kTRUE);
    RooRealVar nl("nl","nl",2.,0.,100.); nl.setConstant(kTRUE);

    RooRealVar deCBr("deCBr","deCBr",get_deCBr(m_mode,m_h0mode,_b0f),-0.2,0.1); if(cSig) deCBr.setConstant(kTRUE);
    RooRealVar sCBr("sCBr","sCBr",get_sCBr(m_mode,m_h0mode,_b0f),0.,0.5);       if(cSig) sCBr.setConstant(kTRUE);
    RooRealVar alphar("alphar","alphar",get_alphar(m_mode,m_h0mode,_b0f),-10.,0.);                          if(cSig) alphar.setConstant(kTRUE);
    RooRealVar nr("nr","nr",2,0.,100.); nr.setConstant(kTRUE);

    RooCBShape CBl("CBl","CBl",de,deCBl,sCBl,alphal,nl);
    RooCBShape CBr("CBr","CBr",de,deCBr,sCBr,alphar,nr);

    RooRealVar fCBl("fCBl","fCBl",get_fCBl(m_mode,m_h0mode,_b0f),0.,1.); if(cSig) fCBl.setConstant(kTRUE);
    RooRealVar fCBr("fCBr","fCBr",get_fCBr(m_mode,m_h0mode,_b0f),0.,1.); if(cSig) fCBr.setConstant(kTRUE);

    RooAddPdf pdf_de_sig("pdf_de_sig","pdf_de_sig",RooArgList(CBl,CBr,g1),RooArgSet(fCBl,fCBr));
  } else{
    RooRealVar de0_201("de0_201","de0_201",get_de0(m_mode,m_h0mode,1),-0.1,0.1); if(cSig) de0_201.setConstant(kTRUE);
    RooRealVar  s1_201("s1_201","s1_201",get_s1(m_mode,m_h0mode,1),0.,0.5); if(cSig) s1_201.setConstant(kTRUE);
    RooGaussian g1_201("g1_201","g1_201",de,de0_201,s1_201);

    RooRealVar deCBl_201("deCBl_201","deCBl_201",get_deCBl(m_mode,m_h0mode,1),-0.1,0.1);     if(cSig) deCBl_201.setConstant(kTRUE);
    RooRealVar sCBl_201("sCBl_201","sCBl_201",get_sCBl(m_mode,m_h0mode,1),0.,0.5);           if(cSig) sCBl_201.setConstant(kTRUE);
    RooRealVar nl_201("nl_201","nl_201",2.,0.,100.); nl_201.setConstant(kTRUE);
    RooRealVar alphal_201("alphal_201","alphal_201",get_alphal(m_mode,m_h0mode,1),-10.,10.); if(cSig) alphal_201.setConstant(kTRUE);
    RooRealVar deCBr_201("deCBr_201","deCBr_201",get_deCBr(m_mode,m_h0mode,1),-0.1,0.1);     if(cSig) deCBr_201.setConstant(kTRUE);
    RooRealVar sCBr_201("sCBr_201","sCBr_201",get_sCBr(m_mode,m_h0mode,1),0.,0.5);           if(cSig) sCBr_201.setConstant(kTRUE);
    RooRealVar nr_201("nr_201","nr_201",2.,0.,100.); nr_201.setConstant(kTRUE);
    RooRealVar alphar_201("alphar_201","alphar_201",get_alphar(m_mode,m_h0mode,1),-10.,10.); if(cSig) alphar_201.setConstant(kTRUE);

    RooCBShape CBl_201("CBl_201","CBl_201",de,deCBl_201,sCBl_201,alphal_201,nl_201);
    RooCBShape CBr_201("CBr_201","CBr_201",de,deCBr_201,sCBr_201,alphar_201,nr_201);

    RooRealVar fCBl_201("fCBl_201","fCBl_201",get_fCBl(m_mode,m_h0mode,1),0.,1.); if(cSig) fCBl_201.setConstant(kTRUE);
    if(_mode == 3){
      fCBl_201.setVal(0.);
      fCBl_201.setConstant(kTRUE);
      alphal_201.setConstant(kTRUE);
    }
    RooRealVar fCBr_201("fCBr_201","fCBr_201",get_fCBr(m_mode,m_h0mode,1),0.,1.); if(cSig) fCBr_201.setConstant(kTRUE);

    RooAddPdf pdf_de1("pdf_de1","pdf_de1",RooArgList(CBl_201,CBr_201,g1_201),RooArgSet(fCBl_201,fCBr_201));

    RooRealVar  de0_205("de0_205","de0_205",get_de0(m_mode,m_h0mode,5),-0.2,0.1); if(cSig) de0_205.setConstant(kTRUE);
    RooRealVar  s1_205("s1_205","s1_205",get_s1(m_mode,m_h0mode,5),0.,0.5);       if(cSig) s1_205.setConstant(kTRUE);
    RooGaussian g1_205("g1_205","g1_205",de,de0_205,s1_205);

    RooRealVar deCBl_205("deCBl_205","deCBl_205",get_deCBl(m_mode,m_h0mode,5),-0.1,0.1); if(cSig) deCBl_205.setConstant(kTRUE);
    RooRealVar sCBl_205("sCBl_205","sCBl_205",get_sCBl(m_mode,m_h0mode,5),0.,0.5);       if(cSig) sCBl_205.setConstant(kTRUE);
    RooRealVar nl_205("nl_205","nl_205",2,0.,100.); nl_205.setConstant(kTRUE);
    RooRealVar alphal_205("alphal_205","alphal_205",get_alphal(m_mode,m_h0mode,5),-10.,10.);  if(cSig) alphal_205.setConstant(kTRUE);
    RooCBShape CBl_205("CBl_205","CBl_205",de,deCBl_205,sCBl_205,alphal_205,nl_205);

    RooRealVar fCBl_205("fCBl_205","fCBl_205",get_fCBl(m_mode,m_h0mode,5),0.,1.); if(cSig) fCBl_205.setConstant(kTRUE);

    RooAddPdf pdf_de5("pdf_de5","pdf_de5",RooArgList(CBl_205,g1_205),RooArgSet(fCBl_205));
  }

  /////////////
  // mbc pdf //
  /////////////
  if(gg_flag){
    RooRealVar a_s("a_s","a_s",get_a_s(_mode)); if(cSig) a_s.setConstant(kTRUE);
    RooRealVar b_s("b_s","b_s",get_b_s(_mode)); if(cSig) b_s.setConstant(kTRUE);
    RooRealVar c_s("c_s","c_s",get_c_s(_mode),0.0015,0.0035);// if(cSig) c_s.setConstant(kTRUE);
    RooFormulaVar S("S","S","@1+@2*@0+@3*@0*@0",RooArgList(de,c_s,b_s,a_s));

    RooRealVar alpha("alpha","alpha",0.139,0.01,2.); alpha.setConstant(kTRUE);

    RooRealVar a_mbc0("a_mbc0","a_mbc0",get_a_mbc0(_mode)); if(cSig) a_mbc0.setConstant(kTRUE);
    RooRealVar b_mbc0("b_mbc0","b_mbc0",get_b_mbc0(_mode)); if(cSig) b_mbc0.setConstant(kTRUE);
    RooRealVar c_mbc0("c_mbc0","c_mbc0",get_c_mbc0(_mode),5.277,5.285);// if(cSig) c_mbc0.setConstant(kTRUE);
    RooFormulaVar MBC0("MBC0","MBC0","@1+@2*@0+@3*@0*@0",RooArgList(de,c_mbc0,b_mbc0,a_mbc0));
    RooNovosibirsk pdf_mbc_sig("pdf_mbc_sig","pdf_mbc_sig",mbc,MBC0,S,alpha);
  } else{
    RooRealVar alpha("alpha","alpha",0.139,0.01,2.); alpha.setConstant(kTRUE);
    RooRealVar c0("c0","c0",get_c0(_mode)); if(cSig) c0.setConstant(kTRUE);
    RooRealVar c1("c1","c1",get_c1(_mode)); if(cSig) c1.setConstant(kTRUE);
    RooRealVar c2("c2","c2",get_c2(_mode)); if(cSig) c2.setConstant(kTRUE);
    RooRealVar mbc0("mbc0","mbc0",5.284,5.277,5.29);// if(cSig) mbc0.setConstant(kTRUE);
    RooFormulaVar MBC("MBC","MBC","@0+@1*TMath::Erf((@2-@3))/@4",RooArgList(mbc0,c0,c1,de,c2));

    RooRealVar a_s1("a_s1","a_s1",get_a_s(_mode),0.15,0.45); if(cSig) a_s1.setConstant(kTRUE);
    RooRealVar b_s1("b_s1","b_s1",get_b_s(_mode),-0.05,0.05); if(cSig) b_s1.setConstant(kTRUE);
    RooRealVar c_s1("c_s1","c_s1",get_c_s(_mode),0.0015,0.0035);// if(cSig) c_s1.setConstant(kTRUE);
    RooFormulaVar S1("S1","S1","@1+@2*@0+@3*@0*@0",RooArgList(de,c_s1,b_s1,a_s1));
    RooNovosibirsk pdf_mbc1("pdf_mbc1","pdf_mbc1",mbc,MBC,S1,alpha);

    RooRealVar a_s5("a_s5","a_s5",get_a5_s(_mode)); if(cSig) a_s5.setConstant(kTRUE);
    RooRealVar b_s5("b_s5","b_s5",get_b5_s(_mode)); if(cSig) b_s5.setConstant(kTRUE);
    RooRealVar c_s5("c_s5","c_s5",get_c5_s(_mode),0.0015,0.0055); if(cSig) c_s5.setConstant(kTRUE);
    RooFormulaVar S5("S5","S5","@1+@2*@0+@3*@0*@0",RooArgList(de,c_s5,b_s5,a_s5));

    RooRealVar a_mbc0("a_mbc0","a_mbc0",get_a5_mbc0(_mode)); if(cSig) a_mbc0.setConstant(kTRUE);
    RooRealVar b_mbc0("b_mbc0","b_mbc0",get_b5_mbc0(_mode)); if(cSig) b_mbc0.setConstant(kTRUE);
    RooRealVar c_mbc0("c_mbc0","c_mbc0",get_c5_mbc0(_mode),5.27,5.29); if(cSig) c_mbc0.setConstant(kTRUE);
    RooFormulaVar MBC0("MBC0","MBC0","@1+@2*@0+@3*@0*@0",RooArgList(de,c_mbc0,b_mbc0,a_mbc0));
    RooNovosibirsk pdf_mbc5("pdf_mbc5","pdf_mbc5",mbc,MBC0,S5,alpha);
  }

  /////////
  // pdf //
  /////////
  if(gg_flag){
    RooProdPdf pdf_sig("pdf_sig","pdf_sig",pdf_de_sig,Conditional(pdf_mbc_sig,mbc));
  } else{
    RooRealVar f_201("f_201","f_201",get_f201(m_mode,m_h0mode),0.,1.); if(cSig) f_201.setConstant(kTRUE);
    RooProdPdf pdf1_sig("pdf1_sig","pdf1_sig",pdf_de1,Conditional(pdf_mbc1,mbc));
    RooProdPdf pdf5_sig("pdf5_sig","pdf5_sig",pdf_de5,Conditional(pdf_mbc5,mbc));
    RooAddPdf  pdf_sig("pdf_sig","pdf_sig",RooArgList(pdf1_sig,pdf5_sig),RooArgSet(f_201));
  }

  //////////////
  // Comb PDF //
  //////////////
  ////////////
  // de pdf //
  ////////////
  RooRealVar c10("c10","c10",get_cmb_c10(_mode),-10,50.); if(cComb) c10.setConstant(kTRUE);
  RooRealVar c11("c11","c11",get_cmb_c11(_mode),-50,0.);  if(cComb) c11.setConstant(kTRUE);
  RooFormulaVar c1_cmb("c1_cmb","@0+@1*@2",RooArgSet(c10,c11,mbc));
  RooRealVar c2_cmb("c2_cmb","c2_cmb",get_cmb_c20(_mode),-0.1,1);     if(cComb) c2_cmb.setConstant(kTRUE);
  RooChebychev pdf_de_comb_bb("pdf_de_comb_bb","pdf_de_comb_bb",de,RooArgSet(c1_cmb,c2_cmb));

  RooRealVar C1("C1","C1",get_cmb_c1(_mode),-10,50.); if(cComb) C1.setConstant(kTRUE);
  RooRealVar C2("C2","C2",get_cmb_c2(_mode),-0.1,1);  if(cComb) C2.setConstant(kTRUE);
  RooChebychev pdf_de_comb_qq("pdf_de_comb_qq","pdf_de_comb_qq",de,RooArgSet(C1,C2));
  /////////////
  // mbc pdf //
  /////////////
  RooRealVar argedge("argedge","argedge",5.288,5.285,5.29); //argedge.setConstant(kTRUE);
  RooRealVar argpar_cmb_bb("argpar_cmb_bb","argpar_cmb_bb",get_argpar_bb(_mode),-300,-10.); if(cComb) argpar_cmb_bb.setConstant(kTRUE);
  RooArgusBG pdf_mbc_comb_ar("pdf_mbc_comb_ar","Argus PDF",mbc,argedge,argpar_cmb_bb);

  RooRealVar mbc0_cmb_bb("mbc0_cmb_bb","mbc0_cmb_bb",get_mbc0_cmb_bb(_mode),5.25,5.29,"GeV");// if(cComb) mbc0_cmb_bb.setConstant(kTRUE);
  RooRealVar mbcWidth_cmb_bb("mbcWidth","mbcWidth",get_mbcw_cmb_bb(_mode),0.,0.1,"GeV"); if(cComb) mbcWidth_cmb_bb.setConstant(kTRUE);
  RooGaussian mbcGaus_cmb_bb("mbcGaus","mbcGaus",mbc,mbc0_cmb_bb,mbcWidth_cmb_bb);

  RooRealVar f_g("f_g","f_g",get_f_g_cmb_bb(_mode),0.4,0.7);if(_mode == 2 || !gg_flag){ f_g.setConstant(kTRUE);}
  RooAddPdf pdf_mbc_cmb_bb("pdf_mbc_cmb_bb","pdf_mbc_cmb_bb",RooArgList(mbcGaus_cmb_bb,pdf_mbc_comb_ar),RooArgSet(f_g));

  RooRealVar argpar_cmb_qq("argpar_cmb_qq","argpar_cmb_qq",get_argpar_qq(_mode),-300,-10.); if(cComb) argpar_cmb_qq.setConstant(kTRUE);
  RooArgusBG pdf_mbc_cmb_qq("pdf_mbc_cmb_qq","pdf_mbc_cmb_qq",mbc,argedge,argpar_cmb_qq);
  
  /////////
  // pdf //
  /////////
  RooRealVar f_bb("f_bb","f_bb",0.3,0.,1.);
  RooProdPdf pdf_cmb_bb("pdf_cmb_bb","pdf_cmb_bb",pdf_mbc_cmb_bb,Conditional(pdf_de_comb_bb,de));
  RooProdPdf pdf_cmb_qq("pdf_cmb_qq","pdf_cmb_qq",pdf_mbc_cmb_qq,Conditional(pdf_de_comb_qq,de));
  RooAddPdf pdf_comb("pdf_comb","pdf_comb",RooArgSet(pdf_cmb_bb,pdf_cmb_qq),RooArgList(f_bb));

  /////////////////////
  // Peaking bkg PDF //
  /////////////////////
  ////////////
  // de pdf //
  ////////////
  RooRealVar de0r("de0r","de0r",get_de0r(_mode),-0.2,0.12);         if(cPeak) de0r.setConstant(kTRUE);
  RooRealVar slopel("slopel","slopel",get_slopel(_mode),-1.e5,0.);  if(cPeak) slopel.setConstant(kTRUE);
  RooRealVar sloper("sloper","sloper",get_sloper(_mode),-10000,0.); if(cPeak) sloper.setConstant(kTRUE);
  RooRealVar steep("steep","steep",get_steep(_mode),0.,1000.);      if(cPeak) steep.setConstant(kTRUE);
  RooRealVar p5("p5","p5",get_p5(_mode),0.01,1000.);                if(cPeak) p5.setConstant(kTRUE);
  RooRhoDeltaEPdf pdf_de_peak("pdf_de_peak","pdf_de_peak",de,de0r,slopel,sloper,steep,p5);
//  RooGenericPdf pdf_de_peak("pdf_de_peak","1+(@0-@1)*@2+@4*TMath::Log(1+@5*TMath::Exp((@3-@2)*(@0-@1)/@4)) > 0 ? 1+(@0-@1)*@2+@4*TMath::Log(1+@5*TMath::Exp((@3-@2)*(@0-@1)/@4)) : 0.001",RooArgSet(de,de0r,slopel,sloper,steep,p5));
  /////////////
  // mbc pdf //
  /////////////
  if(gg_flag){
    RooRealVar b_peak_s("b_peak_s","b_peak_s",get_peak_b_s(_mode),-0.1,0.1); if(cPeak) b_peak_s.setConstant(kTRUE);
    RooRealVar k_peak_s("k_peak_s","k_peak_s",get_peak_k_s(_mode),-0.1,0.1); if(cPeak) k_peak_s.setConstant(kTRUE);
    RooFormulaVar S_peak("S_peak","S_peak","@0+@1*@2",RooArgList(b_peak_s,de,k_peak_s));
    RooRealVar alpha_peak("alpha_peak","alpha_peak",0.139,0.01,2.); alpha_peak.setConstant(kTRUE);
    RooRealVar b_peak_mbc0("b_peak_mbc0","b_peak_mbc0",get_peak_b_mbc0(_mode),5.25,5.29); if(cPeak) b_peak_mbc0.setConstant(kTRUE);
    RooRealVar k_peak_mbc0("k_peak_mbc0","k_peak_mbc0",get_peak_k_mbc0(_mode),-0.1,0.1);  if(cPeak) k_peak_mbc0.setConstant(kTRUE);
    RooFormulaVar MBC0_peak("MBC0_peak","MBC0_peak","@0+@1*@2",RooArgList(b_peak_mbc0,de,k_peak_mbc0));
    RooNovosibirsk pdf_mbc_peak("pdf_mbc_peak","pdf_mbc_peak",mbc,MBC0_peak,S_peak,alpha_peak);
  } else{
//    RooRealVar argedge("argedge","argedge",5.288,5.285,5.29); //argedge.setConstant(kTRUE);
    RooRealVar argpar_peak_bb("argpar_peak_bb","argpar_peak_bb",get_argpar_bb(_mode),-300,-10.); if(cPeak) argpar_peak_bb.setConstant(kTRUE);
    RooArgusBG pdf_mbc_peak_ar("pdf_mbc_peak_ar","Argus PDF",mbc,argedge,argpar_peak_bb);

    RooRealVar mbc0_peak("mbc0_peak","mbc0_peak",get_peak_b_mbc0(_mode),5.25,5.291,"GeV"); if(cPeak) mbc0_peak.setConstant(kTRUE);
    RooRealVar mbcWidth_peak("mbcWidth_peak","mbcWidth_peak",get_peak_b_s(_mode),0.,0.1,"GeV"); if(cPeak) mbcWidth_peak.setConstant(kTRUE);
    RooGaussian mbcGaus_peak("mbcGaus_peak","mbcGaus_peak",mbc,mbc0_peak,mbcWidth_peak);
    RooRealVar f_g_peak("f_g_peak","f_g_peak",get_f_g_cmb_bb(_mode),0.,1.); if(cPeak) f_g_peak.setConstant(kTRUE);

    RooAddPdf pdf_mbc_peak("pdf_mbc_peak","pdf_mbc_peak",RooArgList(mbcGaus_peak,pdf_mbc_peak_ar),RooArgSet(f_g_peak));
  }
  /////////
  // pdf //
  /////////
  RooProdPdf pdf_peak("pdf_peak","pdf_peak",pdf_de_peak,Conditional(pdf_mbc_peak,mbc));

  //////////////////
  // Complete PDF //
  //////////////////
  RooRealVar Nsig("Nsig","Nsig",1150,0.,10000.);
//  RooRealVar Npbg("Npbg","Npbg",100,0,100000.);
  RooRealVar Ncmb("Ncmb","Ncmb",2288,0,100000);
  switch(_mode){
  case 1:
    RooRealVar Npbg("Npbg","Npbg",100,0,100000.);
    break;
  case 2:
    RooConstVar f_p_f_bbc("f_p_f_bbc","f_p_f_bbc",0.0051);
    RooFormulaVar Npbg("Npbg","Npbg","@0*@1*@2",RooArgList(Ncmb,f_bb,f_p_f_bbc));
    break;
  case 3:
    RooConstVar f_p_f_bbc("f_p_f_bbc","f_p_f_bbc",0.0081);
    RooFormulaVar Npbg("Npbg","Npbg","@0*@1*@2",RooArgList(Ncmb,f_bb,f_p_f_bbc));
    break;
  case 4:
    RooConstVar f_p_f_bbc("f_p_f_bbc","f_p_f_bbc",0.0031);
    RooFormulaVar Npbg("Npbg","Npbg","@0*@1*@2",RooArgList(Ncmb,f_bb,f_p_f_bbc));
    break;
  default:
    return -1;
  }

  RooAddPdf pdf("pdf","pdf",RooArgList(pdf_sig,pdf_peak,pdf_comb),RooArgList(Nsig,Npbg,Ncmb));

  RooArgSet* params = pdf.getParameters(RooArgSet(de,mbc));
//  RooArgset* initParams = (RooArgSet*) params->snapshot();

  pdf.fitTo(ds,Verbose(),Timer(true));

  params->printLatex(OutputFile("PurityFit.tex"));

   RooAbsReal* intSig  = pdf_sig.createIntegral(RooArgSet(de,mbc),NormSet(RooArgSet(de,mbc)),Range("Signal"));
   RooAbsReal* intRho  = pdf_peak->createIntegral(RooArgSet(de,mbc),NormSet(RooArgSet(de,mbc)),Range("Signal"));
   RooAbsReal* intCmb  = pdf_comb.createIntegral(RooArgSet(de,mbc),NormSet(RooArgSet(de,mbc)),Range("Signal"));
   const double nsig = intSig->getVal()*Nsig.getVal();
   const double nsig_err = intSig->getVal()*Nsig.getError();
   const double nsig_err_npq = TMath::Sqrt(nsig*(Nsig.getVal()-nsig)/Nsig.getVal());
   const double nsig_err_total = TMath::Sqrt(nsig_err*nsig_err+nsig_err_npq*nsig_err_npq);
   const double nrho = intRho->getVal()*Npbg.getVal();
   const double nrho_err = _mode == 1 ? intRho->getVal()*Npbg.getError() : intRho->getVal()*f_bb.getError()*Ncmb.getVal()*f_p_f_bbc.getVal();
   const double nrho_err_npq = TMath::Sqrt(nrho*(Npbg.getVal()-nrho)/Npbg.getVal());
   const double nrho_err_total = TMath::Sqrt(nrho_err*nrho_err+nrho_err_npq*nrho_err_npq);
   const double ncmb = intCmb->getVal()*Ncmb.getVal();
   const double ncmb_err = intCmb->getVal()*Ncmb.getError();
   const double ncmb_err_npq = TMath::Sqrt(ncmb*(Ncmb.getVal()-ncmb)/Ncmb.getVal());
   const double ncmb_err_total = TMath::Sqrt(ncmb_err*ncmb_err+ncmb_err_npq*ncmb_err_npq);
   const double purity = nsig/(nsig+nrho+ncmb);
   const double purity_err = nsig_err_total/(nsig+nrho+ncmb);

   de.setRange("Ellips",dE_min,dE_max);
   RooFormulaVar mbclo("mbclo","@1-@2*TMath::Sqrt(TMath::Abs(1-(@0-@3)/@4*(@0-@3)/@4)+0.0000001)",RooArgSet(de,mbc_center,mbc_radius,de_center,de_radius));
   RooFormulaVar mbchi("mbchi","@1+@2*TMath::Sqrt(TMath::Abs(1-(@0-@3)/@4*(@0-@3)/@4)+0.0000001)",RooArgSet(de,mbc_center,mbc_radius,de_center,de_radius));
   mbc.setRange("Ellips",mbclo,mbchi);

   de.setRange("Elli",dE_min,dE_max);
   RooFormulaVar mbclo1("mbclo1","@1-@2*TMath::Sqrt(TMath::Abs(1-(@0-@3)/@4*(@0-@3)/@4)+0.0000001)",RooArgSet(de,mbc_center,mbc_radius1,de_center,de_radius1));
   RooFormulaVar mbchi1("mbchi1","@1+@2*TMath::Sqrt(TMath::Abs(1-(@0-@3)/@4*(@0-@3)/@4)+0.0000001)",RooArgSet(de,mbc_center,mbc_radius1,de_center,de_radius1));
   mbc.setRange("Elli",mbclo1,mbchi1);

   RooAbsReal* intSigEl = pdf_sig.createIntegral(RooArgSet(de,mbc),NormSet(RooArgSet(de,mbc)),Range("Ellips"));
   RooAbsReal* intRhoEl = pdf_peak->createIntegral(RooArgSet(de,mbc),NormSet(RooArgSet(de,mbc)),Range("Ellips"));
   RooAbsReal* intCmbEl = pdf_comb.createIntegral(RooArgSet(de,mbc),NormSet(RooArgSet(de,mbc)),Range("Ellips"));
   const double nsigEl = intSigEl->getVal()*Nsig.getVal();
   const double nsig_errEl = intSigEl->getVal()*Nsig.getError();
   const double nsig_errEl_npq = TMath::Sqrt(fabs(nsigEl*(Nsig.getVal()-nsigEl)/Nsig.getVal()));
   const double nsig_errEl_total = TMath::Sqrt(fabs(nsig_errEl*nsig_errEl+nsig_errEl_npq*nsig_errEl_npq));
   const double nrhoEl = intRhoEl->getVal()*Npbg.getVal();
   const double nrho_errEl = _mode == 1 ? intRhoEl->getVal()*Npbg.getError() : intRhoEl->getVal()*f_bb.getError()*Ncmb.getVal()*f_p_f_bbc.getVal();
   const double nrho_errEl_npq = TMath::Sqrt(fabs(nrhoEl*(Npbg.getVal()-nrhoEl)/Npbg.getVal()));
   const double nrho_errEl_total = TMath::Sqrt(fabs(nrho_errEl*nrho_errEl+nrho_errEl_npq*nrho_errEl_npq));
   const double ncmbEl = intCmbEl->getVal()*Ncmb.getVal();
   const double ncmb_errEl = intCmbEl->getVal()*Ncmb.getError();
   const double ncmb_errEl_npq = TMath::Sqrt(fabs(ncmbEl*(Ncmb.getVal()-ncmbEl)/Ncmb.getVal()));
   const double ncmb_errEl_total = TMath::Sqrt(ncmb_errEl*ncmb_errEl+ncmb_errEl_npq*ncmb_errEl_npq);
   const double purityEl = nsigEl/(nsigEl+nrhoEl+ncmbEl);
   const double purity_errEl = nsig_errEl_total/(nsigEl+nrhoEl+ncmbEl);


   RooAbsReal* intSigEl1 = pdf_sig.createIntegral(RooArgSet(de,mbc),NormSet(RooArgSet(de,mbc)),Range("Elli"));
   const double intElli = intSigEl1->getVal();
   RooAbsReal* intRhoEl1 = pdf_peak->createIntegral(RooArgSet(de,mbc),NormSet(RooArgSet(de,mbc)),Range("Elli"));
   RooAbsReal* intCmbEl1 = pdf_comb.createIntegral(RooArgSet(de,mbc),NormSet(RooArgSet(de,mbc)),Range("Elli"));
   const double nsigEl1 = intSigEl1->getVal()*Nsig.getVal();
   const double nsig_errEl1 = intSigEl1->getVal()*Nsig.getError();
   const double nsig_errEl1_npq = TMath::Sqrt(fabs(nsigEl1*(Nsig.getVal()-nsigEl1)/Nsig.getVal()));
   const double nsig_errEl1_total = TMath::Sqrt(fabs(nsig_errEl1*nsig_errEl1+nsig_errEl1_npq*nsig_errEl1_npq));
   const double nrhoEl1 = intRhoEl1->getVal()*Npbg.getVal();
   const double nrho_errEl1 = _mode == 1 ? intRhoEl1->getVal()*Npbg.getError() : intRhoEl1->getVal()*f_bb.getError()*Ncmb.getVal()*f_p_f_bbc.getVal();
   const double nrho_errEl1_npq = TMath::Sqrt(fabs(nrhoEl1*(Npbg.getVal()-nrhoEl1)/Npbg.getVal()));
   const double nrho_errEl1_total = TMath::Sqrt(fabs(nrho_errEl1*nrho_errEl1+nrho_errEl1_npq*nrho_errEl1_npq));
   const double ncmbEl1 = intCmbEl1->getVal()*Ncmb.getVal();
   const double ncmb_errEl1 = intCmbEl1->getVal()*Ncmb.getError();
   const double ncmb_errEl1_npq = TMath::Sqrt(ncmbEl1*(Ncmb.getVal()-ncmbEl1)/Ncmb.getVal());
   const double ncmb_errEl1_total = TMath::Sqrt(ncmb_errEl1*ncmb_errEl1+ncmb_errEl1_npq*ncmb_errEl1_npq);
   const double purityEl1 = nsigEl1/(nsigEl1+nrhoEl1+ncmbEl1);
   const double purity_errEl1 = nsig_errEl1_total/(nsigEl1+nrhoEl1+ncmbEl1);

  /////////////
  //  Plots  //
  /////////////
  // de //
  RooPlot* deFrame = de.frame();
  ds.plotOn(deFrame,DataError(RooAbsData::SumW2),MarkerSize(1),CutRange("mbcSignal"));
  pdf.plotOn(deFrame,Components(pdf_sig),LineStyle(kDashed),ProjectionRange("mbcSignal"));
  pdf.plotOn(deFrame,Components(pdf_peak),LineStyle(kDashed),ProjectionRange("mbcSignal"));
  pdf.plotOn(deFrame,Components(pdf_cmb_bb),LineStyle(kDashed),ProjectionRange("mbcSignal"));
  pdf.plotOn(deFrame,Components(pdf_cmb_qq),LineStyle(kDashed),ProjectionRange("mbcSignal"));
  pdf.plotOn(deFrame,LineWidth(2),ProjectionRange("mbcSignal"));

  RooHist* hdepull = deFrame->pullHist();
  RooPlot* dePull = de.frame(Title("#Delta E pull distribution"));
  dePull->addPlotable(hdepull,"P");
  dePull->GetYaxis()->SetRangeUser(-5,5);

  TCanvas* cm = new TCanvas("#Delta E, Signal","#Delta E, Signal",600,700);
  cm->cd();

  TPad *pad3 = new TPad("pad3","pad3",0.01,0.20,0.99,0.99);
  TPad *pad4 = new TPad("pad4","pad4",0.01,0.01,0.99,0.20);
  pad3->Draw();
  pad4->Draw();

  pad3->cd();
  pad3->SetLeftMargin(0.15);
  pad3->SetFillColor(0);

  deFrame->GetXaxis()->SetTitleSize(0.05);
  deFrame->GetXaxis()->SetTitleOffset(0.85);
  deFrame->GetXaxis()->SetLabelSize(0.04);
  deFrame->GetYaxis()->SetTitleOffset(1.6);
  deFrame->Draw();

  out.str("");
  out << "(de-" << de_center.getVal() << ")/" << de_radius1.getVal() << "*(de-" << de_center.getVal() << ")/" << de_radius1.getVal() << "+(mbc-"<<mbc_center.getVal()<<")/" << mbc_radius1.getVal() << "*(mbc-" << mbc_center.getVal() << ")/" << mbc_radius1.getVal() << "<1";
  Roo1DTable* ellitable1 = ds.table(b0f,out.str().c_str());

  out.str("");
  out << "(de-" << de_center.getVal() << ")/" << de_radius.getVal() << "*(de-" << de_center.getVal() << ")/" << de_radius.getVal() << "+(mbc-"<<mbc_center.getVal()<<")/" << mbc_radius.getVal() << "*(mbc-" << mbc_center.getVal() << ")/" << mbc_radius.getVal() << "<1";
  Roo1DTable* ellitable = ds.table(b0f,out.str().c_str());

  const int NSIGNAL_ELLI   = ellitable1->get("signal") + ellitable1->get("fsr") + ellitable1->get("bad_pi0");
//  const int NSIGNAL_ELLIPS = ellitable->get("signal")  + ellitable->get("fsr")  + ellitable->get("bad_pi0");

  stringstream out1;
  TPaveText *pt = new TPaveText(0.5,0.6,0.98,0.9,"brNDC");
  pt->SetFillColor(0);
  pt->SetTextAlign(12);
  out1.str("");
  out1 << "#chi^{2}/n.d.f = " << deFrame->chiSquare();
  pt->AddText(out1.str().c_str());
  out1.str("");
  out1 << "S: " << (int)(nsigEl1+0.5) << " #pm " << (int)(nsig_errEl1_total+0.5) << " (" << NSIGNAL_ELLI << ")";
//  out1 << "S: " << (int)(nsig+0.5) << " #pm " << (int)(nsig_err_total+0.5);
  pt->AddText(out1.str().c_str());
//  out1.str("");
//  out1 << "S_{2}: " << (int)(nsigEl+0.5) << " #pm " << (int)(nsig_errEl_total+0.5) << " (" << NSIGNAL_ELLIPS << ")";
//  pt->AddText(out1.str().c_str());
  out1.str("");
//  out1 << "Purity: " << std::fixed << std::setprecision(2) << purity*100. << " #pm " << purity_err*100;
  out1 << "P: " << std::fixed << std::setprecision(2) << purityEl1*100. << " #pm " << purity_errEl1*100;
  pt->AddText(out1.str().c_str());
  pt->AddText(label.c_str());
  pt->Draw();

  TLine *de_line_RIGHT;
  de_line_RIGHT = new TLine(dE_max,0,dE_max,120);
  de_line_RIGHT->SetLineColor(kRed);
  de_line_RIGHT->SetLineStyle(1);
  de_line_RIGHT->SetLineWidth((Width_t)2.);
  de_line_RIGHT->Draw();
  TLine *de_line_LEFT;
  de_line_LEFT = new TLine(dE_min,0,dE_min,120);
  de_line_LEFT->SetLineColor(kRed);
  de_line_LEFT->SetLineStyle(1);
  de_line_LEFT->SetLineWidth((Width_t)2.);
  de_line_LEFT->Draw();

  pad4->cd(); pad4->SetLeftMargin(0.15); pad4->SetFillColor(0);
  dePull->SetMarkerSize(0.05); dePull->Draw();
  TLine *de_lineUP = new TLine(deMin,3,deMax,3);
  de_lineUP->SetLineColor(kBlue);
  de_lineUP->SetLineStyle(2);
  de_lineUP->Draw();
  TLine *de_line = new TLine(deMin,0,deMax,0);
  de_line->SetLineColor(kBlue);
  de_line->SetLineStyle(1);
  de_line->SetLineWidth((Width_t)2.);
  de_line->Draw();
  TLine *de_lineDOWN = new TLine(deMin,-3,deMax,-3);
  de_lineDOWN->SetLineColor(kBlue);
  de_lineDOWN->SetLineStyle(2);
  de_lineDOWN->Draw();

  cm->Update();

  // mbc //
  RooPlot* mbcFrame = mbc.frame();
  ds.plotOn(mbcFrame,DataError(RooAbsData::SumW2),MarkerSize(1),CutRange("deSignal"));
  pdf.plotOn(mbcFrame,Components(pdf_cmb_bb),LineStyle(kDashed),ProjectionRange("deSignal"));
  pdf.plotOn(mbcFrame,Components(pdf_cmb_qq),LineStyle(kDashed),ProjectionRange("deSignal"));
  pdf.plotOn(mbcFrame,Components(pdf_sig),LineStyle(kDashed),ProjectionRange("deSignal"));
  pdf.plotOn(mbcFrame,Components(pdf_peak),LineStyle(kDashed),ProjectionRange("deSignal"));
  pdf.plotOn(mbcFrame,LineWidth(2),ProjectionRange("deSignal"));

  RooHist* hmbcpull = mbcFrame->pullHist();
  RooPlot* mbcPull  = mbc.frame(Title("#Delta E pull distribution"));
  mbcPull->addPlotable(hmbcpull,"P");
  mbcPull->GetYaxis()->SetRangeUser(-5,5);

  TCanvas* cmmbc = new TCanvas("M_{bc}, Signal","M_{bc}, Signal",600,700);
  cmmbc->cd();

  TPad *pad1 = new TPad("pad1","pad1",0.01,0.20,0.99,0.99);
  TPad *pad2 = new TPad("pad2","pad2",0.01,0.01,0.99,0.20);
  pad1->Draw();
  pad2->Draw();

  pad1->cd();
  pad1->SetLeftMargin(0.15);
  pad1->SetFillColor(0);

  mbcFrame->GetXaxis()->SetTitleSize(0.05);
  mbcFrame->GetXaxis()->SetTitleOffset(0.85);
  mbcFrame->GetXaxis()->SetLabelSize(0.04);
  mbcFrame->GetYaxis()->SetTitleOffset(1.6);
  mbcFrame->Draw();

  TPaveText *ptmbc = new TPaveText(0.2,0.6,0.7,0.9,"brNDC");
  ptmbc->SetFillColor(0);
  ptmbc->SetTextAlign(12);
  out1.str("");
  out1 << "#chi^{2}/n.d.f = " << mbcFrame->chiSquare();
  ptmbc->AddText(out1.str().c_str());
  out1.str("");
  out1 << "S: " << (int)(nsigEl1+0.5) << " #pm " << (int)(nsig_errEl1_total+0.5) << " (" << NSIGNAL_ELLI << ")";
  ptmbc->AddText(out1.str().c_str());
//  out1.str("");
//  out1 << "S_{2}: " << (int)(nsigEl+0.5) << " #pm " << (int)(nsig_errEl_total+0.5) << " (" << NSIGNAL_ELLIPS << ")";
//  ptmbc->AddText(out1.str().c_str());
  out1.str("");
  out1 << "P: " << std::fixed << std::setprecision(2) << purityEl1*100. << " #pm " << purity_errEl1*100;
  ptmbc->AddText(out1.str().c_str());
  ptmbc->AddText(label.c_str());
  ptmbc->Draw();

  TLine *mbc_line_RIGHT;
  mbc_line_RIGHT = new TLine(Mbc_max,0,Mbc_max,40);
  mbc_line_RIGHT->SetLineColor(kRed);
  mbc_line_RIGHT->SetLineStyle(1);
  mbc_line_RIGHT->SetLineWidth((Width_t)2.);
  mbc_line_RIGHT->Draw();
  TLine *mbc_line_LEFT;
  mbc_line_LEFT = new TLine(Mbc_min,0,Mbc_min,40);
  mbc_line_LEFT->SetLineColor(kRed);
  mbc_line_LEFT->SetLineStyle(1);
  mbc_line_LEFT->SetLineWidth((Width_t)2.);
  mbc_line_LEFT->Draw();

  pad2->cd();
  pad2->SetLeftMargin(0.15);
  pad2->SetFillColor(0);
  mbcPull->SetMarkerSize(0.05);
  mbcPull->Draw();
  TLine *mbc_lineUP = new TLine(mbcMin,3,mbcMax,3);
  mbc_lineUP->SetLineColor(kBlue);
  mbc_lineUP->SetLineStyle(2);
  mbc_lineUP->Draw();
  TLine *mbc_line = new TLine(mbcMin,0,mbcMax,0);
  mbc_line->SetLineColor(kBlue);
  mbc_line->SetLineStyle(1);
  mbc_line->SetLineWidth((Width_t)2.);
  mbc_line->Draw();
  TLine *mbc_lineDOWN = new TLine(mbcMin,-3,mbcMax,-3);
  mbc_lineDOWN->SetLineColor(kBlue);
  mbc_lineDOWN->SetLineStyle(2);
  mbc_lineDOWN->Draw();

  cmmbc->Update();

  double DEMIN = -0.15;
  if(keysflag) DEMIN = -0.3;
  TH2D* hh_pdf = pdf.createHistogram("hh_data",de,Binning(50,DEMIN,0.1),YVar(mbc,Binning(50,5.26,5.30)));
  hh_pdf->SetLineColor(kBlue);
  TCanvas* hhc = new TCanvas("hhc","hhc",600,600);
  hhc->cd();
  hh_pdf->Draw("SURF");

  // Show signal ranges
  TEllipse* elli = new TEllipse(de_center.getVal(),mbc_center.getVal(),de_radius.getVal(),mbc_radius.getVal());
  elli->SetFillColor(0);
  elli->SetFillStyle(0);
  elli->SetLineColor(kBlue);
  elli->SetLineWidth(2);
  TEllipse* elli1 = new TEllipse(de_center.getVal(),mbc_center.getVal(),de_radius1.getVal(),mbc_radius1.getVal());
  elli1->SetFillColor(0);
  elli1->SetFillStyle(0);
//  elli1->SetLineColor(kBlue);
  elli1->SetLineColor(kRed);
  elli1->SetLineWidth(2);
  TLine* l1 = new TLine(dE_min,Mbc_min,dE_max,Mbc_min);
  l1->SetLineColor(kRed);
  l1->SetLineStyle(1);
  l1->SetLineWidth(2);
  TLine* l2 = new TLine(dE_min,Mbc_max,dE_max,Mbc_max);
  l2->SetLineColor(kRed);
  l2->SetLineStyle(1);
  l2->SetLineWidth(2);
  TLine* l3 = new TLine(dE_min,Mbc_min,dE_min,Mbc_max);
  l3->SetLineColor(kRed);
  l3->SetLineStyle(1);
  l3->SetLineWidth(2);
  TLine* l4 = new TLine(dE_max,Mbc_min,dE_max,Mbc_max);
  l4->SetLineColor(kRed);
  l4->SetLineStyle(1);
  l4->SetLineWidth(2);

  TCanvas* ellican = new TCanvas("ellican","ellican",400,400);
  ellican->cd();
  out.str("");
  out << "bdtg>" << BDTG_MIN << " && de>-0.15 && de<0.20 && mbc>5.265 && b0f != 1 && b0f != 5 && b0f != 10 && b0f != 0";
  tree->Draw("mbc:de",out.str().c_str());
  tree->SetMarkerStyle(6);
  tree->SetMarkerColor(kBlue);
  out.str("");
  out << "bdtg>" << BDTG_MIN << " && de>-0.15 && de<0.20 && mbc>5.265 && (b0f == 1 || b0f == 5 || b0f == 10)";
  tree->Draw("mbc:de",out.str().c_str(),"same");
//  elli->Draw();
  elli1->Draw();
//  ellican->Pad().GetXaxis()->SetTitle("#DeltaE (GeV)");
//  l1->Draw(); l2->Draw(); l3->Draw(); l4->Draw();

//  TCanvas* sigcan = new TCanvas("sigcan","sigcan",400,400);
//  sigcan->cd();
//  out <<
//  tree->Draw("mbc:de","bdtg>0.98 && de>-0.15 && de<0.20 && mbc>5.265 && (b0f == 1 || b0f == 5 || b0f == 10)");
//  elli->Draw(); elli1->Draw(); l1->Draw(); l2->Draw(); l3->Draw(); l4->Draw();

//  TCanvas* backcan = new TCanvas("backcan","backcan",400,400);
//  backcan->cd();
//  tree->Draw("mbc:de","bdtg>0.98 && de>-0.15 && de<0.20 && mbc>5.265 && !(b0f == 1 || b0f == 5 || b0f == 10)");
//  elli->Draw(); elli1->Draw(); l1->Draw(); l2->Draw(); l3->Draw(); l4->Draw();

  cout << "Rectangle:" << endl;
  out.str("");
  out << "de<" << dE_max << " && de>" << dE_min;
  out << " && mbc>" << Mbc_min << " && mbc<" << Mbc_max;
  Roo1DTable* recttable = ds.table(b0f,out.str().c_str());
  recttable->Print();
  recttable->Print("v");

  cout << "Ellips:" << endl;
//  out.str("");
//  out << "(de-" << de_center.getVal() << ")/" << de_radius.getVal() << "*(de-" << de_center.getVal() << ")/" << de_radius.getVal() << "+(mbc-"<<mbc_center.getVal()<<")/" << mbc_radius.getVal() << "*(mbc-" << mbc_center.getVal() << ")/" << mbc_radius.getVal() << "<1";
//  cout << out.str() << endl;
//  Roo1DTable* ellitable = ds.table(b0f,out.str().c_str());
  ellitable->Print();
  ellitable->Print("v");

  cout << "Elli:" << endl;
//  out.str("");
//  out << "(de-" << de_center.getVal() << ")/" << de_radius1.getVal() << "*(de-" << de_center.getVal() << ")/" << de_radius1.getVal() << "+(mbc-"<<mbc_center.getVal()<<")/" << mbc_radius1.getVal() << "*(mbc-" << mbc_center.getVal() << ")/" << mbc_radius1.getVal() << "<1";
//  cout << out.str() << endl;
//  Roo1DTable* ellitable1 = ds.table(b0f,out.str().c_str());
  ellitable1->Print();
  ellitable1->Print("v");

  Roo1DTable* fulltable = ds.table(b0f);
  fulltable->Print();
  fulltable->Print("v");
  const int NSigTotal = fulltable->get("signal") + fulltable->get("fsr") + fulltable->get("bad_pi0");
  const double TruePur = ((double)NSIGNAL_ELLI)/(NSIGNAL_ELLI+ellitable1->get("comb")+ellitable1->get("rho2")+ellitable1->get("rho3")+ellitable1->get("rho4")+ellitable1->get("rho11"));

  cout << "Rectangle:" << endl;
  cout << "Nsig = " << nsig <<" +- " << nsig_err << " +- " << nsig_err_npq << " (" << nsig_err_total << ")" << endl;
  cout << "Npbg = " << nrho <<" +- " << nrho_err << " +- " << nrho_err_npq << " (" << nrho_err_total << ")" << endl;
  cout << "Ncmb = " << ncmb <<" +- " << ncmb_err << " +- " << ncmb_err_npq << " (" << ncmb_err_total << ")" << endl;
  cout << "Pury = " << purity << " +- " << purity_err << endl;

  cout << "Ellips:" << endl;
  cout << "Nsig = " << nsigEl <<" +- " << nsig_errEl << " +- " << nsig_errEl_npq << " (" << nsig_errEl_total << ")" << endl;
  cout << "Npbg = " << nrhoEl <<" +- " << nrho_errEl << " +- " << nrho_errEl_npq << " (" << nrho_errEl_total << ")" << endl;
  cout << "Ncmb = " << ncmbEl <<" +- " << ncmb_errEl << " +- " << ncmb_errEl_npq << " (" << ncmb_errEl_total << ")" << endl;
  cout << "Pury = " << purityEl << " +- " << purity_errEl << endl;

  cout << "Elli:" << endl;
  cout << "Nsig = " << nsigEl1 <<" +- " << nsig_errEl1 << " +- " << nsig_errEl1_npq << " (" << nsig_errEl1_total << ")" << endl;
  cout << "Npbg = " << nrhoEl1 <<" +- " << nrho_errEl1 << " +- " << nrho_errEl1_npq << " (" << nrho_errEl1_total << ")" << endl;
  cout << "Ncmb = " << ncmbEl1 <<" +- " << ncmb_errEl1 << " +- " << ncmb_errEl1_npq << " (" << ncmb_errEl1_total << ")" << endl;
  cout << "Pury = " << purityEl1 << " +- " << purity_errEl1 << endl;

  cout << "Elli signal integral: " << intElli << endl;
  cout << "Nsig (full range): " << Nsig.getVal() << " +- " << Nsig.getError() << " (" << NSigTotal << ")" << endl;
  cout << "True purity: " << TruePur << endl;
}
コード例 #6
0
ファイル: mKKfit.cpp プロジェクト: abmorris/BsphiKK
void mKKfit(string filename, string branchname, string cuts, string weight, string xtitle, string unit, string plotname, double xlow, double xup, double yup, int nbins, bool convolve, bool phsp, bool fitnonres, bool fitfzero, bool fitftwop)
{
/*Physics parameters**********************************************************/
  // Define in MeV
  double mBs = 5366.77; // TODO: turn this into a map (or one map per dimension: energy, inverse energy and unitless) and do the MeV to GeV conversion at the top
  double mfzero = 990;//939.9;
  double gpipi = 199;
  double gKK = gpipi*3;
  double mftwop = 1522.2;
  double Gftwop = 84;
  double mphi = 1019.461;
  double Gphi = 4.266;
  double mpi = 139.57018;
  double mK = 493.677;
  double BWBFradius = 0.0031;
  double mKKresolution_lo = 0.2;
  double mKKresolution_hi = 0.6;
  double mKKresolution_MC = 0.4;
/*Input***********************************************************************/
  TFile* file = TFile::Open(filename.c_str());
  TTree* tree = GetTree(file,cuts);
/*Fit the resolution**********************************************************/
  using namespace RooFit;
/*Do convolved fit************************************************************/
  RooRealVar* m = new RooRealVar(branchname.c_str(),xtitle.c_str(),xlow,xup);
  cout << "Importing tree" << endl;
  RooDataSet* data;
  MassFitter* massfitter = new MassFitter(m);
  if(weight == "")
    data = new RooDataSet("data","",RooArgSet(*m),Import(*tree));
  else
  {
    RooRealVar* w = new RooRealVar(weight.c_str(),"weighting variable",-100,100);
    data = new RooDataSet("data","",RooArgSet(*m,*w),Import(*tree),WeightVar(*w));
    massfitter->SetWeighted();
  }
  RooRealVar* Nnonres  = new RooRealVar("N","Number of non-resonant candidates",200,0,1e6);
  RooRealVar* Nfzero   = new RooRealVar("N","Number of f0(980) candidates",150,0,1e6);
  RooRealVar* Nphi     = new RooRealVar("N","Number of phi candidates",3000,0,1e6);
  RooRealVar* Nftwop   = new RooRealVar("N","Number of f2'(1525) candidates",200,0,1e6);
/*Phase space function********************************************************/
  if(phsp)
  {
    Component* phasespace = massfitter->SetWeightFunction("Three Body Phase Space");
    if(unit.find("GeV")!=string::npos)
    {
      phasespace->SetRange("M",mBs*1e-3,mBs*1e-3);
      phasespace->FixValue("M",mBs*1e-3);
      phasespace->SetRange("m1",mK*1e-3,mK*1e-3);
      phasespace->FixValue("m1",mK*1e-3);
      phasespace->SetRange("m2",mK*1e-3,mK*1e-3);
      phasespace->FixValue("m2",mK*1e-3);
      phasespace->SetRange("m3",mphi*1e-3,mphi*1e-3);
      phasespace->FixValue("m3",mphi*1e-3);
    }
    else
    {
      phasespace->SetRange("M",mBs,mBs);
      phasespace->FixValue("M",mBs);
      phasespace->SetRange("m1",mK,mK);
      phasespace->FixValue("m1",mK);
      phasespace->SetRange("m2",mK,mK);
      phasespace->FixValue("m2",mK);
      phasespace->SetRange("m3",mphi,mphi);
      phasespace->FixValue("m3",mphi);
    }
  }
/*Non-resonant kaon pairs*****************************************************/
  Component* nonres;
  if(fitnonres)
  {
    if(!phsp)
    {
      nonres = massfitter->AddComponent("nonres","Three Body Phase Space",Nnonres);
      if(unit.find("GeV")!=string::npos)
      {
        nonres->SetRange("M",mBs*1e-3,mBs*1e-3);
        nonres->FixValue("M",mBs*1e-3);
        nonres->SetRange("m1",mK*1e-3,mK*1e-3);
        nonres->FixValue("m1",mK*1e-3);
        nonres->SetRange("m2",mK*1e-3,mK*1e-3);
        nonres->FixValue("m2",mK*1e-3);
        nonres->SetRange("m3",mphi*1e-3,mphi*1e-3);
        nonres->FixValue("m3",mphi*1e-3);
      }
      else
      {
        nonres->SetRange("M",mBs,mBs);
        nonres->FixValue("M",mBs);
        nonres->SetRange("m1",mK,mK);
        nonres->FixValue("m1",mK);
        nonres->SetRange("m2",mK,mK);
        nonres->FixValue("m2",mK);
        nonres->SetRange("m3",mphi,mphi);
        nonres->FixValue("m3",mphi);
      }
    }
    else
    {
      nonres = massfitter->AddComponent("nonres","Flat",Nnonres);
    }
    nonres->SetColour(kCyan+1);
    nonres->SetStyle(kDotted);
  }
/*f0(980)*********************************************************************/
  Component* fzero;
  if(fitfzero)
  {
    fzero = massfitter->AddComponent("fzero","Flatte",Nfzero);
    fzero->SetColour(kGreen+1);
    fzero->SetStyle(9);
//    fzero->FixValue("spin",0);
    if(unit.find("GeV")!=string::npos)
    {
      fzero->SetRange("mean",mfzero*1e-3,mfzero*1e-3);
      fzero->FixValue("mean",mfzero*1e-3);
      fzero->SetRange("gpipi",gpipi*1e-3,gpipi*1e-3);
      fzero->FixValue("gpipi",gpipi*1e-3);
      fzero->SetRange("mpi",mpi*1e-3,mpi*1e-3);
      fzero->FixValue("mpi",mpi*1e-3);
      fzero->SetRange("gKK",gKK*1e-3,gKK*1e-3);
      fzero->FixValue("gKK",gKK*1e-3);
      fzero->SetRange("mK",mK*1e-3,mK*1e-3);
      fzero->FixValue("mK",mK*1e-3);
    }
    else
    {
      fzero->SetRange("mean",mfzero,mfzero);
      fzero->FixValue("mean",mfzero);
      fzero->SetRange("gpipi",gpipi,gpipi);
      fzero->FixValue("gpipi",gpipi);
      fzero->SetRange("mpi",mpi,mpi);
      fzero->FixValue("mpi",mpi);
      fzero->SetRange("gKK",gKK,gKK);
      fzero->FixValue("gKK",gKK);
      fzero->SetRange("mK",mK,mK);
      fzero->FixValue("mK",mK);
    }
  }
/*phi(1020)*******************************************************************/
  Component* phi;
  if(convolve)
  {
    phi = massfitter->AddComponent("phi","RBW(X)Gauss",Nphi);
  }
  else
  {
    phi = massfitter->AddComponent("phi","Rel Breit-Wigner",Nphi);
  }
  phi->SetColour(kMagenta+1);
  phi->SetStyle(9);
  phi->FixValue("spin",1);
  if(unit.find("GeV")!=string::npos)
  {
    phi->SetRange("mean",mphi*1e-3,mphi*1e-3);
    phi->FixValue("mean",mphi*1e-3);
    phi->SetRange("width",Gphi*1e-3,Gphi*1e-3);
    phi->FixValue("width",Gphi*1e-3);
    phi->SetRange("radius",BWBFradius*1e3,BWBFradius*1e3);
    phi->FixValue("radius",BWBFradius*1e3);
    phi->SetRange("mK",mK*1e-3,mK*1e-3);
    phi->FixValue("mK",mK*1e-3);
    if(convolve)
    {
      phi->SetRange("sigma1",mKKresolution_lo*1e-3,mKKresolution_hi*1e-3);
      phi->FixValue("sigma1",mKKresolution_MC*1e-3);
    }
  }
  else
  {
    phi->SetRange("mean",mphi,mphi);
    phi->FixValue("mean",mphi);
    phi->SetRange("width",Gphi,Gphi);
    phi->FixValue("width",Gphi);
    phi->SetRange("radius",BWBFradius,BWBFradius);
    phi->FixValue("radius",BWBFradius);
    phi->SetRange("mK",mK,mK);
    phi->FixValue("mK",mK);
    if(convolve)
    {
      phi->SetRange("sigma1",mKKresolution_lo,mKKresolution_hi);
      phi->FixValue("sigma1",mKKresolution_MC);
    }
  }
/*f2'(1525)*******************************************************************/
  Component* ftwop;
  if(fitftwop)
  {
    ftwop = massfitter->AddComponent("ftwop","Rel Breit-Wigner",Nftwop);
    ftwop->FixValue("spin",2);
    ftwop->SetColour(kOrange+2);
    ftwop->SetStyle(9);
    if(unit.find("GeV")!=string::npos)
    {
      ftwop->SetRange("mean",mftwop*1e-3,mftwop*1e-3);
      ftwop->FixValue("mean",mftwop*1e-3);
      ftwop->SetRange("width",Gftwop*1e-3,Gftwop*1e-3);
      ftwop->FixValue("width",Gftwop*1e-3);
      ftwop->SetRange("radius",BWBFradius*1e3,BWBFradius*1e3);
      ftwop->FixValue("radius",BWBFradius*1e3);
      ftwop->SetRange("mK",mK*1e-3,mK*1e-3);
      ftwop->FixValue("mK",mK*1e-3);
    }
    else
    {
      ftwop->SetRange("mean",mftwop,mftwop);
      ftwop->FixValue("mean",mftwop);
      ftwop->SetRange("width",Gftwop,Gftwop);
      ftwop->FixValue("width",Gftwop);
      ftwop->SetRange("radius",BWBFradius,BWBFradius);
      ftwop->FixValue("radius",BWBFradius);
      ftwop->SetRange("mK",mK,mK);
      ftwop->FixValue("mK",mK);
    }
  }
/*Do the fit******************************************************************/
  massfitter->Fit(data);
  RooPlot* frame = m->frame();
  cout << "Plotting" << endl;
  data->plotOn(frame,(Binning(nbins)));
  massfitter->Plot(frame);
  plotmaker fullplot(frame);
  RooHist* pullhist = frame->pullHist();
  RooPlot* pullframe = m->frame(Title("Pull"));
  pullframe->addPlotable(pullhist,"B");
  fullplot.SetPullPlot(pullframe);
  fullplot.SetTitle(xtitle, unit);
  if(yup>0)
    frame->SetMaximum(yup);
  frame->SetMinimum(0);
  TCanvas* can = fullplot.Draw();
  stringstream ytitle;
  ytitle << "#font[132]{}Candidates / (" << (xup-xlow)/nbins << " " << unit << ")";
  frame->GetYaxis()->SetTitle(ytitle.str().c_str());
  can->SaveAs((plotname+".pdf").c_str());
  double xsplit = 1060;
  double lowbinwidth = 1;
  if(unit.find("GeV")!=string::npos)
  {
    xsplit*=1e-3;
    lowbinwidth*=1e-3;
  }
  if((xup-xlow) > 2*(xsplit-xlow))
  {
    // Make low range bins a certain width
    int nbins_lo = (xsplit-xlow)/lowbinwidth;
    // Get the same bin width for the high range
    int nbins_hi = nbins * (xup-xsplit)/(xup-xlow);
    // Make the frames
    RooPlot* frame_lo = m->frame(Range(xlow,xsplit),Bins(nbins_lo));
    RooPlot* frame_hi = m->frame(Range(xsplit,xup),Bins(nbins_hi));
    // Plot the data
    data->plotOn(frame_lo);
    data->plotOn(frame_hi);
    // Plot the PDFs
    massfitter->Plot(frame_lo);
    massfitter->Plot(frame_hi);
    // Set the y-axis ranges
    frame_lo->SetMaximum(yup);
    frame_lo->SetMinimum(0);
    frame_hi->SetMinimum(0);
    // Make the pull plots
    RooHist* pullhist_lo = frame_lo->pullHist();
    RooHist* pullhist_hi = frame_hi->pullHist();
    RooPlot* pullframe_lo = m->frame(Title("Pull"),Range(xlow,xsplit));
    RooPlot* pullframe_hi = m->frame(Title("Pull"),Range(xsplit,xup));
    pullframe_lo->addPlotable(pullhist_lo,"B");
    pullframe_hi->addPlotable(pullhist_hi,"B");
    // Draw the low-mass plot
    plotmaker lowplot(frame_lo);
    lowplot.SetPullPlot(pullframe_lo);
    lowplot.SetTitle(xtitle, unit);
    can = lowplot.Draw();
    stringstream ytitle_lo;
    ytitle_lo << "#font[132]{}Candidates / (" << lowbinwidth << " " << unit << ")";
    frame_lo->GetYaxis()->SetTitle(ytitle_lo.str().c_str());
    can->SaveAs((plotname+"_low_range.pdf").c_str());
    // Draw the high-mass plot
    plotmaker highplot(frame_hi);
    highplot.SetPullPlot(pullframe_hi);
    highplot.SetTitle(xtitle, unit);
    can = highplot.Draw();
    frame_hi->GetYaxis()->SetTitle(ytitle.str().c_str());
    can->SaveAs((plotname+"_high_range.pdf").c_str());
  }
}
コード例 #7
0
void Purity_1d_fit(int type = 0){
  TChain* tree = new TChain("TEvent");
  if(!type) tree->Add("/home/vitaly/B0toDh0/TMVA/FIL_b2dh_gen_0-1_full.root");
  else      tree->Add("/home/vitaly/B0toDh0/TMVA/FIL_b2dh_data.root");

  RooCategory b0f("b0f","b0f");
  b0f.defineType("signal",1);
  b0f.defineType("fsr",10);
  b0f.defineType("bad_pi0",5);
  b0f.defineType("rho",3);
  b0f.defineType("comb",-1);

  RooArgSet argset;

  const double deMin = -0.15;
  const double deMax = 0.3;

  RooRealVar mbc("mbc","M_{bc}",mbc_min,mbc_max,"GeV"); argset.add(mbc);
  RooRealVar de("de","#DeltaE",deMin,deMax,"GeV"); argset.add(de);
  de.setRange("Signal",de_min,de_max);
  RooRealVar md("md","md",DMass-md_cut,DMass+md_cut,"GeV"); argset.add(md);
  RooRealVar mk("mk","mk",KMass-mk_cut,KMass+mk_cut,"GeV"); argset.add(mk);
  RooRealVar mpi0("mpi0","mpi0",Pi0Mass-mpi0_cut,Pi0Mass+mpi0_cut,"GeV"); argset.add(mpi0);
  RooRealVar bdtgs("bdtgs","bdtgs",bdtgs_cut,1.); argset.add(bdtgs);
  RooRealVar atckpi_max("atckpi_max","atckpi_max",0.,atckpi_cut); argset.add(atckpi_max);

  if(!type) argset.add(b0f);

  RooDataSet ds("ds","ds",tree,argset,"mbc>0||mbc<=0");
//  RooDataSet* ds0 = ds.reduce(RooArgSet(de));
  
  stringstream out;
  if(!type){
    out.str("");
    out << "de<" << de_max << " && de>" << de_min;
    Roo1DTable* sigtable = ds.table(b0f,out.str().c_str());
    sigtable->Print();
    sigtable->Print("v");

    Roo1DTable* fulltable = ds.table(b0f);
    fulltable->Print();
    fulltable->Print("v");
  }

//  RooDataHist* dh = ds0->binnedClone();

//  ds0->Print();

  ////////////////
  // Signal PDF //
  ////////////////
  ////////////
  // de pdf //
  ////////////
  RooRealVar de0("de0","de0",m_de0,-0.1,0.1); if(cSig) de0.setConstant(kTRUE);
  RooRealVar s1("s1","s1",m_s1,0.,0.5); if(cSig) s1.setConstant(kTRUE);
  RooGaussian g1("g1","g1",de,de0,s1);

  RooRealVar deCBl("deCBl","deCBl",m_deCBl,-0.1,0.1); if(cSig) deCBl.setConstant(kTRUE);
  RooRealVar sCBl("sCBl","sCBl",m_sCBl,0.,0.5); if(cSig) sCBl.setConstant(kTRUE);
  RooRealVar nl("nl","nl",m_nl,0.,100.); if(cSig) nl.setConstant(kTRUE);
  RooRealVar alphal("alphal","alphal",m_alphal,-10.,10.); if(cSig) alphal.setConstant(kTRUE);

  RooRealVar deCBr("deCBr","deCBr",m_deCBr,-0.1,0.1); if(cSig) deCBr.setConstant(kTRUE);
  RooRealVar sCBr("sCBr","sCBr",m_sCBr,0.,0.5); if(cSig) sCBr.setConstant(kTRUE);
  RooRealVar nr("nr","nr",m_nr,0.,100.); if(cSig) nr.setConstant(kTRUE);
  RooRealVar alphar("alphar","alphar",m_alphar,-10.,10.); if(cSig) alphar.setConstant(kTRUE);

  RooCBShape CBl("CBl","CBl",de,deCBl,sCBl,alphal,nl);
  RooCBShape CBr("CBr","CBr",de,deCBr,sCBr,alphar,nr);

  RooRealVar fCBl("fCBl","fCBl",m_fCBl,0.,1.); if(cSig) fCBl.setConstant(kTRUE);
  RooRealVar fCBr("fCBr","fCBr",m_fCBr,0.,1.); if(cSig) fCBr.setConstant(kTRUE);

  RooAddPdf pdf_sig("pdf_sig","pdf_sig",RooArgList(CBl,CBr,g1),RooArgSet(fCBl,fCBr));

  //////////////
  // Comb PDF //
  //////////////
  ////////////
  // de pdf //
  ////////////
  RooRealVar c1("c1","c1",mc_c1_1d,-10.,10.); if(cComb) c1.setConstant(kTRUE);
  RooRealVar c2("c2","c2",mc_c2_1d,-10.,10.); if(cComb) c2.setConstant(kTRUE);
  RooChebychev pdf_comb("pdf_comb","pdf_comb",de,RooArgSet(c1,c2));

  /////////////
  // Rho PDF //
  /////////////
  ////////////
  // de pdf //
  ////////////
if(de_rho_param == 0){
  RooRealVar exppar("exppar","exppar",mr_exppar,-40.,-25.);// if(cRho) exppar.setConstant(kTRUE);
  RooExponential pdf_rho("pdf_rho","pdf_rho",de,exppar);
  }
  
  RooRealVar de0r("de0r","de0r",mr_de0r,-0.2,0.12); if(cRho) de0r.setConstant(kTRUE);
  
  if(de_rho_param == 1){
   RooRealVar slopel("slopel","slopel",mr_slopel,-1000,-500.); if(cRho) slopel.setConstant(kTRUE);
   RooRealVar sloper("sloper","sloper",mr_sloper,-10000,0.); if(cRho) sloper.setConstant(kTRUE);
   RooRealVar steep("steep","steep",mr_steep,7.,9.); if(cRho) steep.setConstant(kTRUE);
   RooRealVar p5("p5","p5",mr_p5,0.01,1000.); if(cRho) p5.setConstant(kTRUE);
   RooRhoDeltaEPdf pdf_rho("pdf_rho","pdf_rho",de,de0r,slopel,sloper,steep,p5);
  }
  
  if(de_rho_param == -1){
   RooRealVar x0("x0","x0",mr_x0_1d,-0.2,0.12); if(cRho) x0.setConstant(kTRUE);
   RooRealVar p1("p1","p1",mr_p1_1d,-1000.,100.); if(cRho) p1.setConstant(kTRUE);
   RooRealVar p2("p2","p2",mr_p2_1d,0.,100.); if(cRho) p2.setConstant(kTRUE);
   RooGenericPdf pdf_rho("pdf_rho","1+@0*@1-@2*TMath::Log(1+TMath::Exp(@2*(@0-@1)/@3))",RooArgSet(de,x0,p1,p2));
  }
  //////////////////
  // Complete PDF //
  //////////////////
  RooRealVar Nsig("Nsig","Nsig",700,100.,1500.);// fsig.setConstant(kTRUE);
  RooRealVar Nrho("Nrho","Nrho",400,100,1500.);// frho.setConstant(kTRUE);
  RooRealVar Ncmb("Ncmb","Ncmb",1000,100,100000);// frho.setConstant(kTRUE);
  RooAddPdf pdf("pdf","pdf",RooArgList(pdf_sig,pdf_rho,pdf_comb),RooArgList(Nsig,Nrho,Ncmb));

  pdf.fitTo(ds,Verbose(),Timer(true));

   RooAbsReal* intSig  = pdf_sig.createIntegral(RooArgSet(de),NormSet(RooArgSet(de)),Range("Signal"));
   RooAbsReal* intRho  = pdf_rho.createIntegral(RooArgSet(de),NormSet(RooArgSet(de)),Range("Signal"));
   RooAbsReal* intCmb  = pdf_comb.createIntegral(RooArgSet(de),NormSet(RooArgSet(de)),Range("Signal"));
   const double nsig = intSig->getVal()*Nsig.getVal();
   const double nsig_err = intSig->getVal()*Nsig.getError();
   const double nsig_err_npq = TMath::Sqrt(nsig*(Nsig.getVal()-nsig)/Nsig.getVal());
   const double nsig_err_total = TMath::Sqrt(nsig_err*nsig_err+nsig_err_npq*nsig_err_npq);
   const double nrho = intRho->getVal()*Nrho.getVal();
   const double nrho_err = intRho->getVal()*Nrho.getError();
   const double nrho_err_npq = TMath::Sqrt(nrho*(Nrho.getVal()-nrho)/Nrho.getVal());
   const double nrho_err_total = TMath::Sqrt(nrho_err*nrho_err+nrho_err_npq*nrho_err_npq);
   const double ncmb = intCmb->getVal()*Ncmb.getVal();
   const double ncmb_err = intCmb->getVal()*Ncmb.getError();
   const double ncmb_err_npq = TMath::Sqrt(ncmb*(Ncmb.getVal()-ncmb)/Ncmb.getVal());
   const double ncmb_err_total = TMath::Sqrt(ncmb_err*ncmb_err+ncmb_err_npq*ncmb_err_npq);
   const double purity = nsig/(nsig+nrho+ncmb);
   const double purity_err = nsig_err_total/(nsig+nrho+ncmb);
   cout << "Nsig = " << nsig <<" +- " << nsig_err << endl;
   cout << "Nrho = " << nrho <<" +- " << nrho_err << endl;
   cout << "Ncmb = " << ncmb <<" +- " << ncmb_err << endl;
   
  /////////////
  //  Plots  //
  /////////////
  // de //
  RooPlot* deFrame = de.frame();
  ds.plotOn(deFrame,DataError(RooAbsData::SumW2),MarkerSize(1));
  pdf.plotOn(deFrame,Components(pdf_sig),LineStyle(kDashed));
  pdf.plotOn(deFrame,Components(pdf_rho),LineStyle(kDashed));
  pdf.plotOn(deFrame,Components(pdf_comb),LineStyle(kDashed));
  pdf.plotOn(deFrame,LineWidth(2));

  RooHist* hdepull = deFrame->pullHist();
  RooPlot* dePull = de.frame(Title("#Delta E pull distribution"));
  dePull->addPlotable(hdepull,"P");
  dePull->GetYaxis()->SetRangeUser(-5,5);

  TCanvas* cm = new TCanvas("Delta E","Delta E",600,700);
  cm->cd();

  TPad *pad3 = new TPad("pad3","pad3",0.01,0.20,0.99,0.99);
  TPad *pad4 = new TPad("pad4","pad4",0.01,0.01,0.99,0.20);
  pad3->Draw();
  pad4->Draw();

  pad3->cd();
  pad3->SetLeftMargin(0.15);
  pad3->SetFillColor(0);

  deFrame->GetXaxis()->SetTitleSize(0.05);
  deFrame->GetXaxis()->SetTitleOffset(0.85);
  deFrame->GetXaxis()->SetLabelSize(0.04);
  deFrame->GetYaxis()->SetTitleOffset(1.6);
  deFrame->Draw();

  stringstream out1;
  TPaveText *pt = new TPaveText(0.6,0.75,0.98,0.9,"brNDC");
  pt->SetFillColor(0);
  pt->SetTextAlign(12);
  out1.str("");
  out1 << "#chi^{2}/n.d.f = " << deFrame->chiSquare();
  pt->AddText(out1.str().c_str());
  out1.str("");
  out1 << "S: " << (int)(nsig+0.5) << " #pm " << (int)(nsig_err_total+0.5);
  pt->AddText(out1.str().c_str());
  out1.str("");
  out1 << "Purity: " << std::fixed << std::setprecision(2) << purity*100. << " #pm " << purity_err*100;
  pt->AddText(out1.str().c_str());
  pt->Draw();

  TLine *de_line_RIGHT = new TLine(de_max,0,de_max,50);
  de_line_RIGHT->SetLineColor(kRed);
  de_line_RIGHT->SetLineStyle(1);
  de_line_RIGHT->SetLineWidth((Width_t)2.);
  de_line_RIGHT->Draw();
  TLine *de_line_LEFT = new TLine(de_min,0,de_min,50);
  de_line_LEFT->SetLineColor(kRed);
  de_line_LEFT->SetLineStyle(1);
  de_line_LEFT->SetLineWidth((Width_t)2.);
  de_line_LEFT->Draw();

  pad4->cd(); pad4->SetLeftMargin(0.15); pad4->SetFillColor(0);
  dePull->SetMarkerSize(0.05); dePull->Draw();
  TLine *de_lineUP = new TLine(deMin,3,deMax,3);
  de_lineUP->SetLineColor(kBlue);
  de_lineUP->SetLineStyle(2);
  de_lineUP->Draw();
  TLine *de_line = new TLine(deMin,0,deMax,0);
  de_line->SetLineColor(kBlue);
  de_line->SetLineStyle(1);
  de_line->SetLineWidth((Width_t)2.);
  de_line->Draw();
  TLine *de_lineDOWN = new TLine(deMin,-3,deMax,-3);
  de_lineDOWN->SetLineColor(kBlue);
  de_lineDOWN->SetLineStyle(2);
  de_lineDOWN->Draw();

  cm->Update();
  
  if(!type){
    out.str("");
    out << "de<" << de_max << " && de>" << de_min;
    Roo1DTable* sigtable = ds.table(b0f,out.str().c_str());
    sigtable->Print();
    sigtable->Print("v");
    
    Roo1DTable* fulltable = ds.table(b0f);
    fulltable->Print();
    fulltable->Print("v");
  }
  
  cout << "Nsig = " << nsig <<" +- " << nsig_err << " +- " << nsig_err_npq << " (" << nsig_err_total << ")" << endl;
  cout << "Nrho = " << nrho <<" +- " << nrho_err << " +- " << nrho_err_npq << " (" << nrho_err_total << ")" << endl;
  cout << "Ncmb = " << ncmb <<" +- " << ncmb_err << " +- " << ncmb_err_npq << " (" << ncmb_err_total << ")" << endl;
  cout << "Pury = " << purity << " +- " << purity_err << endl;
}
コード例 #8
0
ファイル: fit_MC_norm.C プロジェクト: apmorris/scripts
void fit_MC_norm(std::string input_file = "/afs/cern.ch/work/a/apmorris/private/cern/ntuples/new_tuples/normalisation_samples/reduced_Lb2JpsipK_MC_2011_2012_norm.root", std::string out_file_mass = "~/cern/plots/fitting/Lb2JpsipK_MC_2011_2012_cut_mass_fit.png"){
                                                                                    //
    gROOT->ProcessLine(".L ~/cern/scripts/lhcbStyle.C");
    //lhcbStyle();

    const std::string filename(input_file.c_str());
    const std::string treename = "DecayTree";

    TFile* file = TFile::Open( filename.c_str() );
    if( !file ) std::cout << "file " << filename << " does not exist" << std::endl;
    TTree* tree = (TTree*)file->Get( treename.c_str() );
    if( !tree ) std::cout << "tree " << treename << " does not exist" << std::endl;


    // -- signal, mass shape
    RooRealVar Lambda_b0_DTF_MASS_constr1("Lambda_b0_DTF_MASS_constr1","m(J/#psi pK^{-})", 5450., 5850., "MeV/c^{2}"); 
    RooRealVar Jpsi_M("Jpsi_M","m(#mu#mu)", 3000., 3200., "MeV/c^{2}"); 
    //RooRealVar chi_c_M("chi_c_M","m(J/#psi#gamma)", 3350., 3750., "MeV/c^{2}"); 
    RooRealVar mean("mean","mean", 5620., 5595., 5650.);
    RooRealVar sigma1("sigma1","sigma1", 10., 1., 100.);
    RooRealVar sigma2("sigma2","sigma2", 100., 1., 1000.);
    RooRealVar alpha1("alpha1","alpha1", 1.0, 0.5, 5.0);
    RooRealVar n1("n1","n1", 1.8, 0.2, 15.0);
    RooRealVar alpha2("alpha2","alpha2", -0.5, -5.5, 0.0);
    RooRealVar n2("n2","n2", 0.7, 0.2, 10.0);
    //RooRealVar bkgcat_chic("bkgcat_chic","bkgcat_chic", 0, 100);

    RooGaussian gauss1("gauss1","gauss1", Lambda_b0_DTF_MASS_constr1, mean, sigma1);
    RooGaussian gauss2("gauss2","gauss2", Lambda_b0_DTF_MASS_constr1, mean, sigma2);
    RooCBShape cb1("cb1","cb1", Lambda_b0_DTF_MASS_constr1, mean, sigma1, alpha1, n1); 
    RooCBShape cb2("cb2","cb2", Lambda_b0_DTF_MASS_constr1, mean, sigma2, alpha2, n2); 
    /*
    // the chi_c2 component
    RooRealVar mean3("mean3","mean3", 5570., 5520., 5580.);
    RooRealVar sigma3("sigma3","sigma3", 10., 1., 20.);
    RooGaussian gauss3("gauss3","gauss3", Lambda_b0_DTF_MASS_constr1, mean3, sigma3);
    */
    RooRealVar cbRatio("cbRatio","cbRatio", 0.8, 0.1, 1.0);
    RooRealVar frac2("frac2","frac2", 0.3, 0., 1.);
    
  

    /*
    alpha1.setVal( 2.1  );
    alpha2.setVal( -4.9 );
    n1.setVal( 3.2 );
    n2.setVal( 7.9 );
    cbRatio.setVal( 0.6808 );
    alpha1.setConstant( true );
    alpha2.setConstant( true );
    cbRatio.setConstant( true );
    n1.setConstant( true );
    n2.setConstant( true );
    */

    // -- add signal & bg
    //RooAddPdf pdf("pdf", "pdf", RooArgList(gauss1, gauss2), RooArgList( frac2 ));  
    RooAddPdf pdf("pdf", "pdf", RooArgList(cb1, cb2), RooArgList( cbRatio ));  

    
    RooArgSet obs;
    obs.add(Lambda_b0_DTF_MASS_constr1);
    obs.add(Jpsi_M);
    //obs.add(chi_c_M);
    //obs.add(bkgcat_chic);
    RooDataSet ds("ds","ds", obs, RooFit::Import(*tree)); 
 //RooFit::Cut("Lambda_b0_DTF_MASS_constr1 > 5580")
    RooPlot* plot = Lambda_b0_DTF_MASS_constr1.frame();

    plot->SetAxisRange(5500., 5750.);


    pdf.fitTo( ds );

    ds.plotOn( plot, RooFit::Binning(200) );
    pdf.plotOn( plot );
    //gauss3.plotOn( plot );



    RooPlot* plotPullMass = Lambda_b0_DTF_MASS_constr1.frame();

    plotPullMass->addPlotable( plot->pullHist() );
    //plotPullMass->SetMinimum();
    //plotPullMass->SetMaximum();
    plotPullMass->SetAxisRange(5500., 5750.);
    TCanvas* c = new TCanvas();
    c->cd();

    TPad* pad1 = new TPad("pad1","pad1", 0, 0.3, 1, 1.0);
    pad1->SetBottomMargin(0.1);
    pad1->SetTopMargin(0.1);
    pad1->Draw();
    
    //TPad* pad2 = new TPad("pad2","pad2", 0, 0.05, 1, 0.4);
    TPad* pad2 = new TPad("pad2","pad2", 0, 0, 1, 0.3);
    pad2->SetBottomMargin(0.1);
    pad2->SetTopMargin(0.0);
    pad2->Draw();

    pdf.plotOn( plot, RooFit::Components( cb1 ), RooFit::LineColor( kRed ), RooFit::LineStyle(kDashed) );
    pdf.plotOn( plot, RooFit::Components( cb2 ), RooFit::LineColor( kOrange ), RooFit::LineStyle(kDotted) );
    //pdf.plotOn( plot, RooFit::Components( bgPdf ), RooFit::LineColor( kBlue ), RooFit::LineStyle(kDashDotted) );

    pad1->cd();
    //pad1->SetLogy();
    plot->Draw();

    pad2->cd();
    plotPullMass->Draw("AP");

    c->SaveAs(out_file_mass.c_str());


}
コード例 #9
0
ファイル: p3fit_mass.C プロジェクト: goi42/LbJpsipPi
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();
}
コード例 #10
0
ファイル: kibbler_fit.C プロジェクト: jaromrax/shspe
  /***********************************************************************
   ***********************************************************************
   *   CONSTRUCTOR   MAKES ALLLLLLLL
   *******************************************************************
   *************************************************
   *****************************
   *****
   */
  Tbroomfit(double xlow, double xhi, TH1 *h2,  int npeak, double *peak, double *sigm, const char *chpol="p0"){
    int iq=0;
    printf("constructor - %d   %ld", iq++,  (int64_t)h2 );
    h2->Print();
    /*
     *   get global area, ranges for sigma, x
     */
    npeaks=npeak; // class defined int
    //    double areah2=h2->Integral( int(xlow), int(xhi) ); // WRONG - BINS
    min= h2->GetXaxis()->GetFirst();
    printf("constructor - %d   %f", iq++, min  );
    max= h2->GetXaxis()->GetLast();
    printf("constructor - %d   %f", iq++, max  );
    double areah2=h2->Integral( min, max );
    printf("constructor - %d   %f", iq++,  areah2 );
    min=xlow;
    max=xhi;


    double sigmamin=(max-min)/300;
    double sigmamax=(max-min)/4;
    double areamin=0;
    double areamax=2*areah2;
    printf("x:(%f,%f)  s:(%f,%f)  a:(%f,%f) \n", min,max,sigmamin, sigmamax,areamin, areamax );
  /*
   *   definition of  variables..............
   *
   */    
    RooRealVar       x("x",    "x",   min, max);

    int MAXPEAKS=6;  // later from 5 to 6 ???


    printf("RooFit: npeaks=%d\n",  npeaks );
    // ABOVE:  RooRealVar *msat[14][5]; //  POINTERS TO ALL variables
    // 0  m     Mean
    // 1  s     Sigma
    // 2  a     Area
    // 3  t     Tail
    // 4  [0] nalpha
    // 5  [0] n1

for (int ii=0;ii<14;ii++){
 for (int jj=0;jj<MAXPEAKS;jj++){
   msat[ii][jj]=NULL; 
   msat_values[ii][jj]=0.0;
 } //for for
 }// for for 

 printf("delete fitresult, why crash?\n%s","");
 fitresult=NULL;
 printf("delete fitresult, no crash?\n%s","");


    RooRealVar    mean1("mean1", "mean",  1*(max-min)/(npeaks+1)+min,    min,max);msat[0][0]=&mean1;
    RooRealVar    mean2("mean2", "mean",  2*(max-min)/(npeaks+1)+min,    min,max);msat[0][1]=&mean2;
    RooRealVar    mean3("mean3", "mean",  3*(max-min)/(npeaks+1)+min,    min,max);msat[0][2]=&mean3;
    RooRealVar    mean4("mean4", "mean",  4*(max-min)/(npeaks+1)+min,    min,max);msat[0][3]=&mean4;
    RooRealVar    mean5("mean5", "mean",  5*(max-min)/(npeaks+1)+min,    min,max);msat[0][4]=&mean5;
    RooRealVar    mean6("mean6", "mean",  6*(max-min)/(npeaks+1)+min,    min,max);msat[0][5]=&mean6;


    RooRealVar   sigma1("sigma1","sigma", (max-min)/10,       sigmamin,  sigmamax );msat[1][0]=&sigma1;
    RooRealVar   sigma2("sigma2","sigma", (max-min)/10,       sigmamin,  sigmamax );msat[1][1]=&sigma2;
    RooRealVar   sigma3("sigma3","sigma", (max-min)/10,       sigmamin,  sigmamax );msat[1][2]=&sigma3;
    RooRealVar   sigma4("sigma4","sigma", (max-min)/10,       sigmamin,  sigmamax );msat[1][3]=&sigma4;
    RooRealVar   sigma5("sigma5","sigma", (max-min)/10,       sigmamin,  sigmamax );msat[1][4]=&sigma5;
    RooRealVar   sigma6("sigma6","sigma", (max-min)/10,       sigmamin,  sigmamax );msat[1][5]=&sigma6;


    RooRealVar    area1("area1", "area",      areah2/npeaks,       areamin, areamax  );msat[2][0]=&area1;
    RooRealVar    area2("area2", "area",      areah2/npeaks,       areamin, areamax  );msat[2][1]=&area2; 
    RooRealVar    area3("area3", "area",      areah2/npeaks,       areamin, areamax  );msat[2][2]=&area3; 
    RooRealVar    area4("area4", "area",      areah2/npeaks,       areamin, areamax  );msat[2][3]=&area4; 
    RooRealVar    area5("area5", "area",      areah2/npeaks,       areamin, areamax  );msat[2][4]=&area5; 
    RooRealVar    area6("area6", "area",      areah2/npeaks,       areamin, areamax  );msat[2][5]=&area6; 

    RooRealVar   bgarea("bgarea", "bgarea", areah2/5, 0, 2*areah2);  



    double  tailstart=-1.0;//  tune the tails....
    double  tailmin=-1e+4;
    double  tailmax=1e+4;

    RooRealVar    tail1("tail1", "tail",      tailstart,       tailmin, tailmax  );msat[3][0]=&tail1;
    RooRealVar    tail2("tail2", "tail",      tailstart,       tailmin, tailmax  );msat[3][1]=&tail2;
    RooRealVar    tail3("tail3", "tail",      tailstart,       tailmin, tailmax  );msat[3][2]=&tail3;
    RooRealVar    tail4("tail4", "tail",      tailstart,       tailmin, tailmax  );msat[3][3]=&tail4;
    RooRealVar    tail5("tail5", "tail",      tailstart,       tailmin, tailmax  );msat[3][4]=&tail5;
    RooRealVar    tail6("tail6", "tail",      tailstart,       tailmin, tailmax  );msat[3][5]=&tail6;

    // for CBShape
    RooRealVar    nalpha1("nalpha1", "nalpha",      1.3, 0, 100  );msat[4][0]=&nalpha1;

    RooRealVar    n1("n1",          "n",         5.1, 0, 100  );  msat[5][0]=&n1;






    /*
     *   initial values  for  peak positions................
     */
    if (npeaks>=1) {mean1=peak[0];sigma1=sigm[0];}
    if (npeaks>=2) {mean2=peak[1];sigma2=sigm[1];}
    if (npeaks>=3) {mean3=peak[2];sigma3=sigm[2];}
    if (npeaks>=4) {mean4=peak[3];sigma4=sigm[3];}
    if (npeaks>=5) {mean5=peak[4];sigma5=sigm[4];}
    if (npeaks>=6) {mean6=peak[5];sigma6=sigm[5];}


    /*
     *    RooAbsPdf -> RooGaussian
     *                 RooNovosibirsk
     *                 RooLandau
     */
     RooAbsPdf *pk[6];                 // MAXIMUM PEAKS ==5    6 NOW!!             
     RooAbsPdf *pk_dicto[14][6];        // ALL DICTIONARY OF PEAKS..........
     //  Abstract Class.... carrefuly

    RooGaussian gauss1("gauss1","gauss(x,mean,sigma)", x, mean1, sigma1);pk_dicto[0][0]=&gauss1;
    RooGaussian gauss2("gauss2","gauss(x,mean,sigma)", x, mean2, sigma2);pk_dicto[0][1]=&gauss2;
    RooGaussian gauss3("gauss3","gauss(x,mean,sigma)", x, mean3, sigma3);pk_dicto[0][2]=&gauss3;
    RooGaussian gauss4("gauss4","gauss(x,mean,sigma)", x, mean4, sigma4);pk_dicto[0][3]=&gauss4;
    RooGaussian gauss5("gauss5","gauss(x,mean,sigma)", x, mean5, sigma5);pk_dicto[0][4]=&gauss5;
    RooGaussian gauss6("gauss6","gauss(x,mean,sigma)", x, mean6, sigma6);pk_dicto[0][5]=&gauss6;

    RooNovosibirsk ns1("ns1","novosib(x,mean,sigma,tail)", x, mean1,sigma1, tail1 );pk_dicto[1][0]=&ns1;
    RooNovosibirsk ns2("ns2","novosib(x,mean,sigma,tail)", x, mean2,sigma2, tail2 );pk_dicto[1][1]=&ns2;
    RooNovosibirsk ns3("ns3","novosib(x,mean,sigma,tail)", x, mean3,sigma3, tail3 );pk_dicto[1][2]=&ns3;
    RooNovosibirsk ns4("ns4","novosib(x,mean,sigma,tail)", x, mean4,sigma4, tail4 );pk_dicto[1][3]=&ns4;
    RooNovosibirsk ns5("ns5","novosib(x,mean,sigma,tail)", x, mean5,sigma5, tail5 );pk_dicto[1][4]=&ns5;
 
    // BreitWiegner  is  Lorentzian...?
    RooBreitWigner bw1("bw1","BreitWigner(x,mean,sigma)", x, mean1, sigma1 );pk_dicto[2][0]=&bw1;
    RooBreitWigner bw2("bw2","BreitWigner(x,mean,sigma)", x, mean2, sigma2 );pk_dicto[2][1]=&bw2;
    RooBreitWigner bw3("bw3","BreitWigner(x,mean,sigma)", x, mean3, sigma3 );pk_dicto[2][2]=&bw3;
    RooBreitWigner bw4("bw4","BreitWigner(x,mean,sigma)", x, mean4, sigma4 );pk_dicto[2][3]=&bw4;
    RooBreitWigner bw5("bw5","BreitWigner(x,mean,sigma)", x, mean5, sigma5 );pk_dicto[2][4]=&bw5;

    RooCBShape cb1("cb1","CBShape(x,mean,sigma)", x, mean1, sigma1, nalpha1, n1 );pk_dicto[3][0]=&cb1;
    RooCBShape cb2("cb2","CBShape(x,mean,sigma)", x, mean2, sigma2, nalpha1, n1 );pk_dicto[3][1]=&cb2;
    RooCBShape cb3("cb3","CBShape(x,mean,sigma)", x, mean3, sigma3, nalpha1, n1 );pk_dicto[3][2]=&cb3;
    RooCBShape cb4("cb4","CBShape(x,mean,sigma)", x, mean4, sigma4, nalpha1, n1 );pk_dicto[3][3]=&cb4;
    RooCBShape cb5("cb5","CBShape(x,mean,sigma)", x, mean5, sigma5, nalpha1, n1 );pk_dicto[3][4]=&cb5;
    RooCBShape cb6("cb6","CBShape(x,mean,sigma)", x, mean6, sigma6, nalpha1, n1 );pk_dicto[3][5]=&cb6;



    /*
     *    PEAK TYPES   BACKGROUND TYPE .........   COMMAND BOX  OPTIONS ......
     */
    /****************************************************************************
     *  PLAY  WITH  THE DEFINITION  COMMANDLINE...................... POLYNOM + PEAKS
     */
    // CALSS DECLARED TString s;
  s=chpol;
  /*
   *   peaks+bg== ALL BEFORE  ; or :          (after ...  it is a conditions/options)
   */
  TString command;
  int comstart=s.Index(":");   if (comstart<0){ comstart=s.Index(";");}
  if  (comstart<0){ command="";}else{
    command=s(comstart+1, s.Length()-comstart -1 ); // without ;
    s=s(0,comstart); // without ;
    printf("COMMANDLINE : %s\n",  command.Data()  );
    if (TPRegexp("scom").Match(command)!=0){
      
    }// COMMANDS - 
  }// there is some command
  /*************************************************
   *  PLAY WITH peaks+bg..................    s
   */
  s.Append("+"); s.Prepend("+");  s.ReplaceAll(" ","+");
  s.ReplaceAll("++++","+"); s.ReplaceAll("+++","+"); s.ReplaceAll("++","+");s.ReplaceAll("++","+");
  printf ("   regextp =  %s\n",  s.Data()  );
  if (TPRegexp("\\+p[\\dn]\\+").Match(s)==0){ // no match
     printf("NO polynomial demanded =>: %s\n",  "appending  pn command"  ); s.Append("pn+");
  }
  TString spk=s;   TString sbg=s;
  TPRegexp("\\+p[\\dn]\\+").Substitute(spk,"+");  // remove   +p.+   
  TPRegexp(".+(p[\\dn]).+").Substitute(sbg,"$1"); // remove   all but +p+   

  printf ("PEAKS=%s      BG=%s\n",  spk.Data() ,  sbg.Data()  );
  spk.ReplaceAll("+","");   //  VARIANT 1 ------- EACH  LETTER MEANS ONE PEAK 






  /************************************************************************
   *          PREPARE PEAKS  FOLLOWING THE COMMAND BOX................
   */
    //default PEAK types
    pk[0]=&gauss1;
    pk[1]=&gauss2;
    pk[2]=&gauss3;
    pk[3]=&gauss4;
    pk[4]=&gauss5;
    pk[5]=&gauss6;


  int maxi=spk.Length();
  if (maxi>npeaks){maxi=npeaks;}
  for (int i=0;i<maxi;i++){
    if (spk[i]=='n'){
      pk[i]=pk_dicto[1][i];//novosibirsk
      printf("PEAK #%d ... Novosibirsk\n", i );
    }else if(spk[i]=='b'){
      pk[i]=pk_dicto[2][i];//BreitWiegner
      printf("PEAK #%d ... BreitWigner\n", i );
    }else if(spk[i]=='c'){
      pk[i]=pk_dicto[3][i];//CBShape
      printf("PEAK #%d ... CBShape\n", i );
    }else if(spk[i]=='y'){
    }else if(spk[i]=='z'){
    }else{
      pk[i]=pk_dicto[0][i]; //gauss
      printf("PEAK #%d ... Gaussian\n", i );
    }// ELSE CHAIN
  }//i to maxi


  for (int i=0;i<npeaks;i++){ printf("Peak %d   at  %f  s=%f:  PRINT:\n  " ,  i, peak[i], sigm[i]  );pk[i]->Print();}



 /******************************************************** BACKGROUND pn-p4
     *   a0 == level - also skew
     *   a1 == p2
     *   a2 == p3
     */
 // Build Chebychev polynomial p.d.f.  
 // RooRealVar a0("a0","a0", 0.) ;
  RooRealVar a0("a0","a0",    0., -10, 10) ;
  RooRealVar a1("a1","a1",    0., -10, 10) ;
  RooRealVar a2("a2","a2",    0., -10, 10) ;
  RooRealVar a3("a3","a3",    0., -10, 10) ;
  RooArgSet setcheb;
  if ( sbg=="pn" ){ setcheb.add(a0);  a0=0.; a0.setConstant(kTRUE);bgarea=0.; bgarea.setConstant(kTRUE);}
  if ( sbg=="p0" ){ setcheb.add(a0);  a0=0.; a0.setConstant(kTRUE); }
  if ( sbg=="p1" ){ setcheb.add(a0); }
  if ( sbg=="p2" ){ setcheb.add(a1); setcheb.add(a0); }
  if ( sbg=="p3" ){ setcheb.add(a2); setcheb.add(a1); setcheb.add(a0); }
  if ( sbg=="p4" ){ setcheb.add(a3);setcheb.add(a2); setcheb.add(a1); setcheb.add(a0); }
  //  RooChebychev bkg("bkg","Background",x,RooArgSet(a0,a1,a2,a3) ) ;
  RooChebychev bkg("bkg","Background",x, setcheb ) ;

 


  /**********************************************************************
   * MODEL
   */
 
 
 RooArgList rl;  
 if (npeaks>0)rl.add( *pk[0] );  
 if (npeaks>1)rl.add( *pk[1] );  
 if (npeaks>2)rl.add( *pk[2] );  
 if (npeaks>3)rl.add( *pk[3] );  
 if (npeaks>4)rl.add( *pk[4] );  
 if (npeaks>5)rl.add( *pk[5] );  
 rl.add( bkg ); 
 RooArgSet rs;
 if (npeaks>0)rs.add( area1 );  
 if (npeaks>1)rs.add( area2 );  
 if (npeaks>2)rs.add( area3 );  
 if (npeaks>3)rs.add( area4 );  
 if (npeaks>4)rs.add( area5 );  
 if (npeaks>5)rs.add( area6 );  
 rs.add( bgarea );
 RooAddPdf modelV("model","model", rl, rs );


 /*
  *  WITH CUSTOMIZER - I can change parameters inside. But
  *             - then all is a clone and I dont know how to reach it
  */
   RooCustomizer cust( modelV ,"cust"); 
   /*
    *  Possibility to fix all sigma  or tails....
    */ 
   if (TPRegexp("scom").Match(command)!=0){//----------------------SCOM
     printf("all sigma have common values.....\n%s", ""); 
     if (npeaks>1)cust.replaceArg(sigma2,sigma1) ;
     if (npeaks>2)cust.replaceArg(sigma3,sigma1) ;
     if (npeaks>3)cust.replaceArg(sigma4,sigma1) ;
     if (npeaks>4)cust.replaceArg(sigma5,sigma1) ;
     if (npeaks>5)cust.replaceArg(sigma6,sigma1) ;
    }
   if (TPRegexp("tcom").Match(command)!=0){//----------------------TCOM
     printf("all tails have common values.....\n%s", ""); 
     if (npeaks>1)cust.replaceArg(tail2,tail1) ;
     if (npeaks>2)cust.replaceArg(tail3,tail1) ;
     if (npeaks>3)cust.replaceArg(tail4,tail1) ;
     if (npeaks>4)cust.replaceArg(tail5,tail1) ;
     if (npeaks>5)cust.replaceArg(tail6,tail1) ;
    }
   /*   if (TPRegexp("tcom").Match(command)!=0){//----------------------TCOM Neni dalsi ACOM,NCOM pro CB...
     printf("all tails have common values.....\n%s", ""); 
     if (npeaks>1)cust.replaceArg(tail2,tail1) ;
     if (npeaks>2)cust.replaceArg(tail3,tail1) ;
     if (npeaks>3)cust.replaceArg(tail4,tail1) ;
     if (npeaks>4)cust.replaceArg(tail5,tail1) ;
    }
   */
   if  (TPRegexp("p1fix").Match(command)!=0){//----------------------
     mean1.setConstant();printf("position 1 set constant%s\n","");
   }
   if  (TPRegexp("p2fix").Match(command)!=0){//----------------------
     mean2.setConstant();printf("position 2 set constant%s\n","");
   }
   if  (TPRegexp("p3fix").Match(command)!=0){//----------------------
     mean3.setConstant();printf("position 3 set constant%s\n","");
   }
   if  (TPRegexp("p4fix").Match(command)!=0){//----------------------
     mean4.setConstant();printf("position 4 set constant%s\n","");
   }
   if  (TPRegexp("p5fix").Match(command)!=0){//----------------------
     mean5.setConstant();printf("position 5 set constant%s\n","");
   }
   if  (TPRegexp("p6fix").Match(command)!=0){//----------------------
     mean6.setConstant();printf("position 6 set constant%s\n","");
   }
   if  (TPRegexp("s1fix").Match(command)!=0){//----------------------
     sigma1.setConstant();printf("sigma 1 set constant%s\n","");
   }
   if  (TPRegexp("s2fix").Match(command)!=0){//----------------------
     sigma2.setConstant();printf("sigma 2 set constant%s\n","");
   }
   if  (TPRegexp("s3fix").Match(command)!=0){//----------------------
     sigma3.setConstant();printf("sigma 3 set constant%s\n","");
   }
   if  (TPRegexp("s4fix").Match(command)!=0){//----------------------
     sigma4.setConstant();printf("sigma 4 set constant%s\n","");
   }
   if  (TPRegexp("s5fix").Match(command)!=0){//----------------------
     sigma5.setConstant();printf("sigma 5 set constant%s\n","");
   }
   if  (TPRegexp("s6fix").Match(command)!=0){//----------------------
     sigma6.setConstant();printf("sigma 6 set constant%s\n","");
   }


   RooAbsPdf* model = (RooAbsPdf*) cust.build(kTRUE) ; //build a clone...comment on changes...
   //   model->Print("t") ;
   //delete model ; // eventualy delete the model...





 /*
  *  DISPLAY RESULTS            >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
  */
   TPad *orig_gpad=(TPad*)gPad;


   TCanvas *c;
   c=(TCanvas*)gROOT->GetListOfCanvases()->FindObject("fitresult");
   if (c==NULL){
     printf("making new canvas\n%s","");
     c=new TCanvas("fitresult",h2->GetName(),1000,700);  
   }else{
     printf("using old canvas\n%s","");
     c->SetTitle( h2->GetName() );
   }
   c->Clear();
     printf(" canvas cleared\n%s","");
   c->Divide(1,2) ;
     printf(" canvas divided\n%s","");
  c->Modified();c->Update(); 

 RooDataHist datah("datah","datah with x",x,h2);
 RooPlot* xframe = x.frame();
 datah.plotOn(xframe,  DrawOption("logy") );

 // return;
   if (TPRegexp("chi2").Match(command)!=0){//----------------------CHI2
     //from lorenzo moneta
     //     TH1 * h1 = datah.createHistogram(x);
     //     TF1 * f = model->asTF(RooArgList(x) , parameters ); //??? 
     //     h2->Fit(f);
     //It will work but you need to create a THNSparse and fit it 
     //or use directly the ROOT::Fit::BinData class to create a ROOT::Fit::Chi2Function to minimize.
     // THIS CANNOT DO ZERO BINS
     fitresult = model->chi2FitTo( datah , Save()  );  
   }else{
     //   FIT    FIT    FIT    FIT    FIT    FIT    FIT     FIT    FIT   FIT   
      fitresult = model->fitTo( datah , Save()  );   
   }

   fitresult->SetTitle( h2->GetName() ); // I PUT histogram name to global fitresult
   
   // will be done by printResult ... fitresult->Print("v") ;
  //duplicite  fitresult->floatParsFinal().Print("s") ;
  // later - after  parsfinale .... : printResult();
    //    model->Print();  // not interesting........
    model->plotOn(xframe, LineColor(kRed),   DrawOption("l0z") );

  //,Minos(kFALSE)

 /*
  *  Posledni nakreslena vec je vychodiskem pro xframe->resid...?
  *   NA PORADI ZALEZI....
  */

    //unused RooHist* hresid = xframe->residHist() ;
 RooHist* hpull =  xframe->pullHist() ;

 // RooPlot* xframe2 = x.frame(Title("Residual Distribution")) ;
 // xframe2->addPlotable(hresid,"P") ;

  // Construct a histogram with the pulls of the data w.r.t the curve
 RooPlot* xframe3 = x.frame(Title("Pull Distribution")) ;
 xframe3->addPlotable(hpull,"P") ;

  /*
   *  plot components at the end....                     PLOT >>>>>>>>>>>>>>>>
   */

 int colorseq[10]={kRed,kGreen,kBlue,kYellow,kCyan,kMagenta,kViolet,kAzure,kGray,kOrange};

 // RooArgSet* model_params = model->getParameters(x); // this returns all parameters
 RooArgSet* model_params = model->getComponents();
 TIterator* iter = model_params->createIterator() ;
 RooAbsArg* arg ; int icomp=0, ipeak=0;
 //  printf("ENTERING COMPONENT ITERATOR x%dx.....................\n",  icomp );
  while((arg=(RooAbsArg*)iter->Next())) {
    //    printf("printing COMPONENT %d\n",  icomp );
    //    arg->Print();    
    //    printf("NAME==%s\n", arg->Class_Name()  ); //This returns only RooAbsArg
    //    printf("NAME==%s\n", arg->ClassName()  ); //This RooGaussian RooChebychev
    if ( IsPeak( arg->ClassName() )==1 ){
      pk[ipeak]=(RooAbsPdf*)arg; //?
      //      pk[ipeak]->Print();
      ipeak++;
      //      printf("adresses ... %d - %d - %d\n", pk[0], pk[1], pk[2]  );
    }// yes peak.
    icomp++; 
  }//iterations over all components


    model->plotOn(xframe, Components(bkg), LineColor(kRed), LineStyle(kDashed),  DrawOption("l0z") );
    for (int i=0;i<npeaks;i++){
      //      printf("plotting  %d. peak, color %d\n", i,  colorseq[i+1]  );
      //      printf("adresses ... %d - %d - %d\n", pk[0], pk[1], pk[2]  );
      //      pk[i]->Print();
      model->plotOn(xframe, Components( RooArgSet(*pk[i],bkg) ), LineColor(colorseq[i+1]), LineStyle(kDashed),
		    DrawOption("l0z") );
      //		    DrawOption("pz"),DataError(RooAbsData::SumW2) );???  pz removes complains...warnings
      //      model.plotOn(xframe, Components( RooArgSet(*pk[i],bkg) ), LineColor(colorseq[i+1]), LineStyle(kDashed));
    }
 

    // WE SET THE 1st PAD in "fitresult" to LOGY....  1
    //  .....  if the original window is LOGY.....   :)
    //
    //    printf("########### ORIGPAD LOGY==%d #########3\n",  orig_gpad->GetLogy()  );
    c->cd(1); xframe->Draw();  gPad->SetLogy(  orig_gpad->GetLogy()  );
 // c->cd(2); xframe2->Draw();  
 c->cd(2); xframe3->Draw();  
  c->Modified();c->Update(); 

 orig_gpad->cd();


 // printf("msat reference to peak 0 0 = %d,  (%f)\n",  msat[0][0] ,  msat[0][0]->getVal()  );
 for (int ii=0;ii<14;ii++){
 for (int jj=0;jj<MAXPEAKS;jj++){
   if ( msat[ii][jj]!=NULL){
     msat_values[ii][jj]=msat[ii][jj]->getVal();
   }//if
 } //for for
 }// for for   
 printf("at the total end of the constructor....%s\n","");
 // done in pirntResult .. fitresult->floatParsFinal().Print("s") ;
 printResult();
  }; // constructor
コード例 #11
0
pull_Topmass_tWbarChannel()
{




TCanvas* c = new TCanvas("c","test",570,400);
  TFile *f0 = new TFile("./Mu_histograms_2J_1TTest_2_new.root");
  // Declare observable mtop
  RooRealVar mtop("mtop","M (GeV/c^{2})",80,360) ;
  RooDataHist ds("ds","ds",mtop,Import(*Mu_topMass__TbarWChannel)) ;
  // Print number of events in dataset
  ds.Print();
  // Print binned dataset with default frame 
  RooPlot* frame = mtop.frame(Title("Mu_topMass__TbarWChannel")) ;
  
  ds.plotOn(frame) ;
  
  RooRealVar mean("mean","mean",167.0,165,170);
  RooRealVar sigma("sigma","sigma",25.42,18.0,30.0);
  RooGaussian gtop("gtop","gtop",mtop,mean,sigma);

  RooRealVar sigma1("sigma1","sigma1",20.5,20.0,30.0);
  RooRealVar sigma2("sigma2","sigma2",75.5,65.0,75.0);
  RooBifurGauss bgtop("bgtop","bgtop",mtop,mean,sigma1,sigma2);

  RooRealVar frac0("frac0","frac0",0.25,0.1,0.6);
  RooAddPdf pdfg("pdfg","double gaussian Pdf", RooArgList(bgtop,gtop),RooArgList(frac0));
  RooRealVar slope("slope","slope",1.0,0.9,1.3);
  RooChebychev cheb("cheb","cheb",mtop,slope);
  RooRealVar frac("frac","frac",0.93,0.75,1.0);
  
  //  RooAddPdf pdf("pdf","total Pdf", RooArgList(gtop,cheb),RooArgList(frac));
  RooAddPdf pdf("pdf","total Pdf", RooArgList(pdfg,cheb),RooArgList(frac));

  /*  
  gtop.fitTo(ds);
  gtop.plotOn(frame);
  gtop.paramOn(frame);
  */

  /*
  bgtop.fitTo(ds);
  bgtop.plotOn(frame);
  bgtop.paramOn(frame);
  pdf.plotOn(frame,Components(RooArgList(bgtop)), LineColor(kRed),LineStyle(2), LineWidth(4));
  frame->Draw();
  */
  
      
  pdf.fitTo(ds);
  pdf.plotOn(frame);
  pdf.paramOn(frame);
  std::cout<<"AMAR CHI^2 ="<<frame->chiSquare()<<std::endl;  

  // pull 
  RooPlot* z1frame = mtop.frame(Title("TTBar_Topmass_SChannel"));
  RooHist* hpull1 = frame->pullHist();
  z1frame->addPlotable(hpull1,"P");

  RooPlot* z2frame = mtop.frame(Title("TTBar_Topmass_SChannel"));
  RooHist* hresid = frame->residHist();
  z2frame->addPlotable(hresid,"P") ;

  TCanvas* c2 = new TCanvas("pull1","pull1",900,300) ;
  c2->Divide(2,1) ; // column, row
  double xmin = 80.0; double xmax = 360.0;
  TLine *line = new TLine(xmin,0.0,xmax,0.0);
 
  c2->cd(2); line->SetLineColor(kRed); line->SetLineWidth(2); gPad->SetLeftMargin(0.15); z1frame->GetYaxis()->SetTitleOffset(1.6); z1frame->GetYaxis()->SetRangeUser(-5.0, 5.0); z1frame->Draw(); line->Draw("SAME");
  //  c2->cd(1); gPad->SetLeftMargin(0.15); z2frame->GetYaxis()->SetTitleOffset(1.6); z2frame->Draw(); line->Draw("SAME");
  c2->cd(1); gPad->SetLeftMargin(0.15); frame->GetYaxis()->SetTitleOffset(1.6); frame->Draw();
  
 pdf.plotOn(frame,Components(RooArgList(gtop)), LineColor(kRed),LineStyle(2), LineWidth(4));
 pdf.plotOn(frame,Components(RooArgList(cheb)), LineColor(kBlue),LineStyle(2), LineWidth(4));
 pdf.plotOn(frame,Components(RooArgList(bgtop)), LineColor(kGreen),LineStyle(2), LineWidth(4));
  
  

 frame->Draw();
  // Double_t signalchi = frame->chiSquare(); 
 
  c2->SaveAs("TTbar_pull.root");














}
コード例 #12
0
ファイル: fitPtOverMCJLST.C プロジェクト: HZZ4l/CombinationPy
void fitPtOverMCJLST(int mass = 125, int LHCsqrts = 7, int whichtype = 1, 
		     bool correctErrors = false, /* string changeParName = "", */
		     bool showErrorPDFs = false, string systString = "Default")

// whichtype
// 0 - gg Signal
// 1 - VBF Signal
// 2 - ZZ
// 3 - ZX
// 4 - ggZZ
// 5 - WH
// 6 - ZH
// 7 - ttH

{

  string changeParName = "";
  if (systString == "Default") changeParName = "up";

  string nameSample[8] = {"gg","vbf","zz","zx","ggzz","wh","zh","tth"};
  float maxType[8] = {2.4,3.2,1.6,1.6,1.6,3.2,3.2,3.2};   
  float rebinType[8] = {1,2,1,1,4,10,10,40};
  
  for (int t = 0; t < 8; t++) {
    if (mass > 150) maxType[t] = int(117.90*maxType[t]/sqrt(mass-10.91))/10.;
  }

  char fileToOpen[200];
  sprintf(fileToOpen,"selRootFiles/PToverM_%s%d_SEL_%dTeV.root",nameSample[whichtype].c_str(),mass,LHCsqrts);
  // if (whichtype == 3) sprintf(fileToOpen,"PTOVERM_%s_SEL_allTeV.root",nameSample[whichtype].c_str());

  RooRealVar* ptoverm = new RooRealVar("ptoverm","p_{T}/M^{4l}",0.,maxType[whichtype],"GeV/c");
 
  TFile input(fileToOpen);
  // if (systString == "Mass" || systString == "Mela") {
  //  sprintf(fileToOpen,"ptovermH_%sUp",systString.c_str());
  // } else {
  sprintf(fileToOpen,"ptovermH_%s",systString.c_str());
  //}
  TH1F* ptovermH = (TH1F*)input.Get(fileToOpen);
  
  if (rebinType[whichtype] > 1) ptovermH->Rebin(rebinType[whichtype]);
  if (maxType[whichtype] < ptovermH->GetBinLowEdge(ptovermH->GetNbinsX() + 1) - ptovermH->GetBinWidth(1)) {
    int theBin = ptovermH->FindBin(maxType[whichtype]);
    ptovermH->GetXaxis()->SetRange(1,theBin-1);
  }

  gROOT->ProcessLine(".L mytdrstyle.C");
  gROOT->ProcessLine("setTDRStyle()");
  
  // cout << endl << "Signal " << endl;   
  ptoverm->setBins(ptovermH->GetNbinsX());

  RooDataHist* rdh = new RooDataHist("rdh","Some dataset",RooArgList(*ptoverm),Import(*ptovermH,kFALSE));
 
  // fit definitions
  // RooWorkspace *ws = new RooWorkspace("ws");

  RooRealVar m("m","emme", 1.,0.01, 40.);
  RooRealVar n("n","enne", 0.93, 0.05, 15.);
  RooRealVar n2("n2","enne2", 0.75, 0.5, 15.);
  RooRealVar bb("bb","bibi",0.02, 0.000005, 20.0);
  RooRealVar T("T","tti",0.2,0.00000005,1.);
  RooRealVar bb2("bb2","bibi2",0.02, 0.0005, 10.0);
  RooRealVar fexp("fexp","f_exp",0.02, 0.0, 1.0);
  if (whichtype == 0) {
    if (LHCsqrts == 8) {
      m.setVal(3.319);   // m.setConstant(kTRUE);
      n.setVal(0.7606);    if (systString != "Default" || mass != 125) n.setConstant(kTRUE); 
      n2.setVal(0.8061);   n2.setConstant(kTRUE);
      bb.setVal(3.728);   // bb.setConstant(kTRUE);
      T.setVal(0.00333);   // T.setConstant(kTRUE);
      bb2.setVal(1.7172);    // bb2.setConstant(kTRUE);
      fexp.setVal(0.002144);   if (systString != "Default" || mass != 125) fexp.setConstant(kTRUE);
    } else {
      m.setVal(0.061);   // m.setConstant(kTRUE);
      n.setVal(1.6141);   if (systString == "Resummation" || systString == "TopMass")  n.setConstant(kTRUE);
      n2.setVal(1.3294);   n2.setConstant(kTRUE);
      bb.setVal(4.2761);   // bb.setConstant(kTRUE);
      T.setVal(0.0361);   // T.setConstant(kTRUE);
      bb2.setVal(1.6643);   bb2.setConstant(kTRUE);
      fexp.setVal(0.0004);   // fexp.setConstant(kTRUE);
    }
  } else if (whichtype == 1) {
    m.setVal(1.006);   // m.setConstant(kTRUE);
    n.setVal(10.939);   n.setConstant(kTRUE);
    n2.setVal(1.1448);   n2.setConstant(kTRUE);
    bb.setVal(0.02048);   bb.setConstant(kTRUE);
    T.setVal(0.16115);   if (systString.find("Mela") != string::npos) T.setConstant(kTRUE); // T.setConstant(kTRUE);
    bb2.setVal(1.0024);   bb2.setConstant(kTRUE);
    fexp.setVal(0.005);   fexp.setConstant(kTRUE);
    if (mass > 300) {
      fexp.setVal(0.0);   fexp.setConstant(kFALSE);
    }
    if (mass > 500) {
      bb2.setVal(5.0);  //  bb2.setConstant(kFALSE);
    }
    if (mass > 500) {
      bb.setVal(15.0);  //  bb.setConstant(kFALSE);
    }
  } else if (whichtype == 2) {
    if (LHCsqrts == 8) {
      m.setVal(1.0476);   // m.setConstant(kTRUE);    
      bb.setVal(3.3088);  // if (mass != 140) bb.setConstant(kTRUE);
      n2.setVal(0.7146);   n2.setConstant(kTRUE);
      n.setVal(0.9518);      n.setConstant(kTRUE);
      bb2.setVal(100000.);  bb2.setConstant(kTRUE);
      T.setVal(0.0021889);    if (systString.find("Mela") != string::npos || mass != 140) T.setConstant(kTRUE);
      fexp.setVal(0.0);    fexp.setConstant(kTRUE);
    } else {
      m.setVal(1.028);   // m.setConstant(kTRUE);    
      bb.setVal(2.91); // bb.setConstant(kTRUE);
      n2.setVal(0.7146);  n2.setConstant(kTRUE);
      n.setVal(0.9518);     n.setConstant(kTRUE);
      bb2.setVal(100000.);  bb2.setConstant(kTRUE);
      T.setVal(0.002248);   if (systString.find("Mela") != string::npos) T.setConstant(kTRUE);
      fexp.setVal(0.0);    fexp.setConstant(kTRUE);
    }
  } else if (whichtype == 3) {
    m.setVal(1.411);   // m.setConstant(kTRUE);
    n.setVal(3.4523);     n.setConstant(kTRUE);
    n2.setVal(0.6910);    n2.setConstant(kTRUE);
    bb.setVal(0.00039);  // bb.setConstant(kTRUE);
    T.setVal(0.118);   // T.setConstant(kTRUE);
    bb2.setVal(0.0224);   bb2.setConstant(kTRUE);
    fexp.setVal(0.0);   fexp.setConstant(kTRUE);
  } else if (whichtype == 4) {
    m.setVal(1.411);   // m.setConstant(kTRUE);
    n.setVal(5.756);    // n.setConstant(kTRUE);
    n2.setVal(0.8738);   // n2.setConstant(kTRUE);
    bb.setVal(0.00039);  // bb.setConstant(kTRUE);
    T.setVal(0.118);   // T.setConstant(kTRUE);
    bb2.setVal(0.0224);   bb2.setConstant(kTRUE);
    fexp.setVal(0.0);   fexp.setConstant(kTRUE);
  } else if (whichtype == 5 && LHCsqrts == 8) {
    m.setVal(1.006);   // m.setConstant(kTRUE);
    n.setVal(10.939);    n.setConstant(kTRUE);
    n2.setVal(1.1448);   n2.setConstant(kTRUE);
    bb.setVal(3.897);   bb.setConstant(kTRUE);
    T.setVal(0.1009);  // T.setConstant(kTRUE);
    bb2.setVal(1.0224);   bb2.setConstant(kTRUE);
    fexp.setVal(0.01);   fexp.setConstant(kTRUE);
  } else {
    // cout << "Entro qui" << endl;
    m.setVal(1.006);   // m.setConstant(kTRUE);
    n.setVal(10.939);    n.setConstant(kTRUE);
    n2.setVal(1.1448);   n2.setConstant(kTRUE);
    bb.setVal(0.0129);  bb.setConstant(kTRUE);
    T.setVal(0.1009);    // T.setConstant(kTRUE);
    bb2.setVal(1.0224);   bb2.setConstant(kTRUE);
    fexp.setVal(0.01);   fexp.setConstant(kTRUE);
  }
 
  
  RooModifTsallis* rt3 = new RooModifTsallis("rt3","rt3",*ptoverm,m,n,n2,bb,bb2,T,fexp);
  // ws->import(*rt3);

  // fit
  RooFitResult* fit = rt3->fitTo(*rdh,Minos(0),Save(1),SumW2Error(kTRUE),NumCPU(1));  

  float mVal = m.getVal();   
  float nVal = n.getVal();
  float n2Val = n2.getVal();
  float bbVal = bb.getVal();
  float bb2Val = bb2.getVal();
  float fexpVal = fexp.getVal();
  float TVal = T.getVal();

  if (correctErrors) {
    // Tsallis errors not reliable, use toy MC

    TH1F* mHist = new TH1F("mHist","m",21,-0.5*mVal,0.5*mVal);
    TH1F* nHist = new TH1F("nHist","n",21,-0.2*nVal,0.2*nVal);
    TH1F* n2Hist = new TH1F("n2Hist","n2",21,-0.2*n2Val,0.2*n2Val);
    TH1F* bbHist = new TH1F("bbHist","bb",21,-0.2*bbVal,0.2*bbVal);
    TH1F* bb2Hist = new TH1F("bb2Hist","bb2",21,-0.2*bb2Val,0.2*bb2Val);
    TH1F* fexpHist = new TH1F("fexpHist","fexp",21,-0.2*fexpVal-0.000001,0.2*fexpVal+0.000001);
    TH1F* THist = new TH1F("THist","T",21,-0.5*TVal,0.5*TVal);
    mHist->GetXaxis()->SetTitle("m-m_{gen}");
    nHist->GetXaxis()->SetTitle("n-n_{gen}");
    n2Hist->GetXaxis()->SetTitle("n2-n2_{gen}");
    bbHist->GetXaxis()->SetTitle("bb-bb_{gen}");
    bb2Hist->GetXaxis()->SetTitle("bb2-bb2_{gen}");
    THist->GetXaxis()->SetTitle("T-T_{gen}");
    fexpHist->GetXaxis()->SetTitle("fexp-fexp_{gen}");

    for (unsigned int iToy = 0; iToy < 200; iToy++) {

      cout << endl << "####" << endl;
      cout << "Generating toy experiment n. " << iToy+1 << endl;

      m.setVal(mVal);
      n.setVal(nVal);
      n2.setVal(n2Val);
      bb.setVal(bbVal);
      bb2.setVal(bb2Val);
      fexp.setVal(fexpVal);
      T.setVal(TVal);

      TDatime *now = new TDatime();
      Int_t seed = now->GetDate() + now->GetTime();
      cout << "RooFit Generation Seed = " << seed+iToy << endl;
      RooRandom::randomGenerator()->SetSeed(seed+iToy);
      cout << "####" << endl << endl;

      RooDataSet *dataToy = rt3->generate(RooArgSet(*ptoverm),ptovermH->GetEntries());
      RooDataHist *dataToyH = new RooDataHist("dataToyH","toy",RooArgSet(*ptoverm),*dataToy);
      
      rt3->fitTo(*dataToyH,Minos(0),SumW2Error(kTRUE),NumCPU(1));  
  
      if (fit->floatParsFinal().find("m")) mHist->Fill(m.getVal()-mVal);
      if (fit->floatParsFinal().find("n")) nHist->Fill(n.getVal()-nVal);
      if (fit->floatParsFinal().find("n2")) n2Hist->Fill(n2.getVal()-n2Val);
      if (fit->floatParsFinal().find("bb")) bbHist->Fill(bb.getVal()-bbVal);
      if (fit->floatParsFinal().find("bb2")) bb2Hist->Fill(bb2.getVal()-bb2Val);
      if (fit->floatParsFinal().find("fexp")) fexpHist->Fill(fexp.getVal()-fexpVal);
      if (fit->floatParsFinal().find("T")) THist->Fill(T.getVal()-TVal);
    }

    TCanvas cant("cant","Test canvas",5.,5.,900.,500.);
    cant.Divide(4,2);
    cant.cd(1);   mHist->Draw();
    cant.cd(2);   nHist->Draw();
    cant.cd(3);   n2Hist->Draw();
    cant.cd(4);   bbHist->Draw();
    cant.cd(5);   bb2Hist->Draw();
    cant.cd(6);   fexpHist->Draw();
    cant.cd(7);   THist->Draw();
    // cant.SaveAs("figs/testToys.pdf");
    cant.SaveAs("newfigs/testToys.pdf");

    if (fit->floatParsFinal().find("m")) m.setError(mHist->GetRMS());
    if (fit->floatParsFinal().find("n")) n.setError(nHist->GetRMS());
    if (fit->floatParsFinal().find("n2")) n2.setError(n2Hist->GetRMS());
    if (fit->floatParsFinal().find("bb")) bb.setError(bbHist->GetRMS());
    if (fit->floatParsFinal().find("bb2")) bb2.setError(bb2Hist->GetRMS());
    if (fit->floatParsFinal().find("fexp")) fexp.setError(fexpHist->GetRMS());
    if (fit->floatParsFinal().find("T")) T.setError(THist->GetRMS());
  }

  m.setVal(mVal);
  n.setVal(nVal);
  n2.setVal(n2Val);
  bb.setVal(bbVal);
  bb2.setVal(bb2Val);
  fexp.setVal(fexpVal);
  T.setVal(TVal);

  char fileToSave[200];
  // if (changeParName != "") 
  //  sprintf(fileToSave,"text/paramsPTOverMCJLST_%s_%dTeV_%s_%s.txt",nameSample[whichtype].c_str(),LHCsqrts,systString.c_str(),changeParName.c_str()); 
  // else 
  sprintf(fileToSave,"text/paramsPTOverMCJLST_%s%d_%dTeV_%s.txt",nameSample[whichtype].c_str(),mass,LHCsqrts,systString.c_str());
  ofstream os1(fileToSave);
  if (changeParName != "") {
    sprintf(fileToSave,"m%s",changeParName.c_str());  m.SetName(fileToSave);
    sprintf(fileToSave,"n%s",changeParName.c_str());  n.SetName(fileToSave);
    sprintf(fileToSave,"n2%s",changeParName.c_str());  n2.SetName(fileToSave);
    sprintf(fileToSave,"bb%s",changeParName.c_str());  bb.SetName(fileToSave);
    sprintf(fileToSave,"bb2%s",changeParName.c_str());  bb2.SetName(fileToSave);
    sprintf(fileToSave,"fexp%s",changeParName.c_str());  fexp.SetName(fileToSave);
    sprintf(fileToSave,"T%s",changeParName.c_str());  T.SetName(fileToSave);
  }
  (RooArgSet(m,n,n2,bb,bb2,fexp,T)).writeToStream(os1,false);
  os1.close();

  RooRealVar mup("mup","emme", 1.,0.01, 30.);
  RooRealVar nup("nup","enne", 0.93, 0.5, 15.);
  RooRealVar n2up("n2up","enne2", 0.75, 0.5, 15.);
  RooRealVar bbup("bbup","bibi",0.02, 0.00005, 20.0);
  RooRealVar Tup("Tup","tti",0.2,0.00000005,1.);
  RooRealVar bb2up("bb2up","bibi2",0.02, 0.0005, 10.0);
  RooRealVar fexpup("fexpup","f_exp",0.02, 0.0, 1.0);
 
  RooModifTsallis* rt3up = new RooModifTsallis("rt3up","rt3up",*ptoverm,mup,nup,n2up,bbup,bb2up,Tup,fexpup);
  // ws->import(*rt3up);
 
  RooRealVar mdown("mdown","emme", 1.,0.01, 30.);
  RooRealVar ndown("ndown","enne", 0.93, 0.5, 15.);
  RooRealVar n2down("n2down","enne2", 0.75, 0.5, 15.);
  RooRealVar bbdown("bbdown","bibi",0.02, 0.00005, 20.0);
  RooRealVar Tdown("Tdown","tti",0.2,0.00000005,1.);
  RooRealVar bb2down("bb2down","bibi2",0.02, 0.0005, 10.0);
  RooRealVar fexpdown("fexpdown","f_exp",0.02, 0.0, 1.0);

  RooModifTsallis* rt3down = new RooModifTsallis("rt3down","rt3down",*ptoverm,mdown,ndown,n2down,bbdown,bb2down,Tdown,fexpdown);
  // ws->import(*rt3down);

  RooPlot *frame = ptoverm->frame();

  char reducestr[300];
  sprintf(reducestr,"ptoverm > %f && ptoverm < %f",ptoverm->getMin(),ptoverm->getMax());
  
  rdh->plotOn(frame,DataError(RooAbsData::SumW2),Cut(reducestr));
  static RooHist *hpull;
  float chi2 = 0.;

  if (changeParName == "") {
    sprintf(fileToSave,"text/paramsPTOverMCJLST_%s%d_%dTeV_Default.txt",nameSample[whichtype].c_str(),mass,LHCsqrts);
    ifstream is1(fileToSave);
    (RooArgSet(mup,nup,n2up,bbup,bb2up,fexpup,Tup)).readFromStream(is1,false);

    mdown.setVal(fabs(3*mup.getVal() - 2*m.getVal()));
    ndown.setVal(fabs(3*nup.getVal() - 2*n.getVal()));
    n2down.setVal(fabs(3*n2up.getVal() - 2*n2.getVal()));
    bbdown.setVal(fabs(3*bbup.getVal() - 2*bb.getVal()));
    Tdown.setVal(fabs(3*Tup.getVal() - 2*T.getVal()));
    bb2down.setVal(fabs(3*bb2up.getVal() - 2*bb2.getVal()));
    fexpdown.setVal(fabs(3*fexpup.getVal() - 2*fexp.getVal()));

    if (showErrorPDFs) {
      rt3->plotOn(frame,LineColor(kRed),LineStyle(kDashed),Normalization(rdh->sumEntries(),RooAbsReal::NumEvent));
      hpull = frame->pullHist();
      rt3up->plotOn(frame,LineColor(kBlue),Normalization(rdh->sumEntries(),RooAbsReal::NumEvent));
      if (systString.find("Mela") == string::npos) rt3down->plotOn(frame,LineColor(kRed),LineStyle(kDashed),Normalization(rdh->sumEntries(),RooAbsReal::NumEvent));
    } else {
      rt3->plotOn(frame,LineColor(kBlue),Normalization(rdh->sumEntries(),RooAbsReal::NumEvent));
      hpull = frame->pullHist();
    }
  } else {
    mup.setVal(m.getVal() + m.getError());   cout << "mup = " << mup.getVal() << endl;
    nup.setVal(n.getVal() + n.getError());
    n2up.setVal(n2.getVal() + n2.getError());
    bbup.setVal(bb.getVal() + bb.getError());
    Tup.setVal(T.getVal() + T.getError());
    bb2up.setVal(bb2.getVal() + bb2.getError());
    fexpup.setVal(fexp.getVal() + fexp.getError());

    mdown.setVal(m.getVal() - m.getError());  cout << "mdown = " << mdown.getVal() << endl;
    ndown.setVal(n.getVal() - n.getError());
    n2down.setVal(n2.getVal() - n2.getError());
    bbdown.setVal(bb.getVal() - bb.getError());
    Tdown.setVal(T.getVal() - T.getError());
    bb2down.setVal(bb2.getVal() - bb2.getError());
    fexpdown.setVal(fexp.getVal() - fexp.getError());

    rt3->plotOn(frame,LineColor(kBlue),Normalization(rdh->sumEntries(),RooAbsReal::NumEvent));
    hpull = frame->pullHist();
    if (showErrorPDFs) {
      rt3up->plotOn(frame,LineColor(kRed),LineStyle(kDashed),Normalization(rdh->sumEntries(),RooAbsReal::NumEvent));
      rt3down->plotOn(frame,LineColor(kRed),LineStyle(kDashed),Normalization(rdh->sumEntries(),RooAbsReal::NumEvent));
    }
  }

  double *ypulls = hpull->GetY();
  unsigned int nBins = rdh->numEntries();
  unsigned int nFullBins = 0;
  for (unsigned int i = 0; i < nBins; i++) {
    cout << "Pull of bin " << i << " = " << ypulls[i] << endl;
    if (fabs(ypulls[i]) < 5.0) chi2 += ypulls[i]*ypulls[i]; 
    cout << "Partial chi2 = " << chi2 << endl;
    if (fabs(ypulls[i]) > 0.0001 && fabs(ypulls[i]) < 5.0) nFullBins++;
  }
  for (unsigned int i = 0; i < nBins; i++) {
    if (fabs(ypulls[i]) < 0.0001) ypulls[i] = 999.; 
    hpull->SetPointError(i,0.,0.,0.,0.);
  } 
  int nFitPar = fit->floatParsFinal().getSize() - 1;

  TCanvas can("can","The canvas",5.,5.,500.,900.); 
  can.Divide(1,3);

  TLatex *t = new TLatex();
  t->SetNDC();
  t->SetTextAlign(22);
  t->SetTextSize(0.06);

  can.cd(1);
  gPad->SetBottomMargin(0.0);
  frame->Draw();
  // gPad->SetLogy(); 
  // Htest->Draw();
  sprintf(fileToSave,"%s %d GeV at %d TeV",nameSample[whichtype].c_str(),mass,LHCsqrts);
  t->DrawLatex(0.6,0.8,fileToSave); 

  can.cd(2);
  gPad->SetLogy(); 
  gPad->SetTopMargin(0.0);
  frame->Draw();
 
  RooPlot* pull = ptoverm->frame(Title("Pull Distribution")) ;
  pull->GetYaxis()->SetTitle("Pull");
  /* pull->SetLabelSize(0.08,"XYZ");
  pull->SetTitleSize(0.08,"XYZ");
  pull->SetTitleOffset(0.6,"Y");
  pull->SetTitleOffset(1.0,"X"); */
  pull->addPlotable(hpull,"P") ; 
  pull->SetMinimum(-6.); 
  pull->SetMaximum(6.); 

  can.cd(3);
  gPad->SetGridy();
  pull->Draw();
  sprintf(fileToSave,"#chi^{2}/n_{DoF} = %4.1f/%d",chi2,nFullBins - nFitPar);
  if (chi2 < 1000.) t->DrawLatex(0.80,0.86,fileToSave);

  // sprintf(fileToSave,"figs/fitPTOverMCJLST_%s%d_%dTeV_%s.pdf",nameSample[whichtype].c_str(),mass,LHCsqrts,systString.c_str());
  sprintf(fileToSave,"newfigs/fitPTOverMCJLST_%s%d_%dTeV_%s.pdf",nameSample[whichtype].c_str(),mass,LHCsqrts,systString.c_str());
  can.SaveAs(fileToSave);

}
コード例 #13
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();
 
   
}
コード例 #14
0
int draw_plots(RooDataSet* ds, RooAbsPdf* pdf,string& fname){
    /////////////
    //  Plots  //
    /////////////
    stringstream out;
    // dz //
    RooPlot* dzFrame = dz->frame();
    ds->plotOn(dzFrame,DataError(RooAbsData::SumW2),MarkerSize(1));
    pdf->plotOn(dzFrame,LineWidth(2));

    RooHist* hdepull = dzFrame->pullHist();
    out.str("");
    out << fname << "_pull";
    RooPlot* dzPull = dz->frame(Title(out.str().c_str()));
    dzPull->addPlotable(hdepull,"P");
    dzPull->GetYaxis()->SetRangeUser(-5,5);

    out.str("");
    out << fname << "_canv";
    TCanvas* cm = new TCanvas(out.str().c_str(),out.str().c_str(),600,700);
    cm->cd();

    out.str("");
    out << fname << "_pad3";
    TPad *pad3 = new TPad(out.str().c_str(),out.str().c_str(),0.01,0.20,0.99,0.99);
    out.str("");
    out << fname << "_pad4";
    TPad *pad4 = new TPad(out.str().c_str(),out.str().c_str(),0.01,0.01,0.99,0.20);
    pad3->Draw();
    pad4->Draw();

    pad3->cd();
    pad3->SetLeftMargin(0.15);
    pad3->SetFillColor(0);

    dzFrame->GetXaxis()->SetTitleSize(0.05);
    dzFrame->GetXaxis()->SetTitleOffset(0.85);
    dzFrame->GetXaxis()->SetLabelSize(0.04);
    dzFrame->GetYaxis()->SetTitleOffset(1.6);
    dzFrame->Draw();

    TPaveText *pt = new TPaveText(0.6,0.8,0.98,0.9,"brNDC");
    pt->SetFillColor(0);
    pt->SetTextAlign(12);
    out.str("");
    out << "#chi^{2}/n.d.f = " << dzFrame->chiSquare();
    pt->AddText(out.str().c_str());
    pt->Draw();

    pad4->cd(); pad4->SetLeftMargin(0.15); pad4->SetFillColor(0);
    dzPull->SetMarkerSize(0.05); dzPull->Draw();
    TLine *dz_lineUP = new TLine(dzmin,3,dzmax,3);
    dz_lineUP->SetLineColor(kBlue);
    dz_lineUP->SetLineStyle(2);
    dz_lineUP->Draw();
    TLine *dz_line = new TLine(dzmin,0,dzmax,0);
    dz_line->SetLineColor(kBlue);
    dz_line->SetLineStyle(1);
    dz_line->SetLineWidth((Width_t)2.);
    dz_line->Draw();
    TLine *dz_lineDOWN = new TLine(dzmin,-3,dzmax,-3);
    dz_lineDOWN->SetLineColor(kBlue);
    dz_lineDOWN->SetLineStyle(2);
    dz_lineDOWN->Draw();

    cm->Update();
    out.str("");
    out << "pics/" << fname << ".root";
    cm->Print(out.str().c_str());

    out.str("");
    out << "pics/" << fname << ".png";
    cm->Print(out.str().c_str());

//    sleep(0.1);
    string cmd = string("display ") + out.str() + string(" &");
    system(cmd.c_str());
//    sleep(0.1);

    delete cm;

    return 0;
}
コード例 #15
0
void Purity_2d_fit_etagg_corr(bool data = false){
  TChain* tree = new TChain("TEvent");
  if(!data) tree->Add("/home/vitaly/B0toDh0/TMVA/FIL_b2dh_gen_0-1_full.root");
  else      tree->Add("/home/vitaly/B0toDh0/TMVA/FIL_b2dh_data.root");

  const int _mode = 2;
  const int _h0mode = 10;
  const int _b0f = -1;
//  gROOT->ProcessLine(".L pdfs/RooRhoDeltaEPdf.cxx+");

  RooCategory b0f("b0f","b0f");
  b0f.defineType("signal",1);
  b0f.defineType("fsr",10);
  b0f.defineType("bad_pi0",5);
//  b0f.defineType("peak1",3);
//  b0f.defineType("peak2",4);
//  b0f.defineType("peak3",11);
//  b0f.defineType("peak4",20);
  b0f.defineType("comb",-1);

//  RooCategory d0f("d0f","d0f");
//  d0f.defineType("signal",1);
  RooArgSet argset;
  argset.add(b0f);

  const double mbcMin = 5.2;
  const double mbcMax = 5.29;
  double deMin = -0.15;
//  if(keysflag) deMin = -0.3;
  const double deMax = 0.3;
  const double elliscaleDe  = TMath::Sqrt(4./TMath::Pi());
  const double elliscaleMbc = TMath::Sqrt(4./TMath::Pi());

  const double DE_MIN = de_min;
  const double DE_MAX = de_max;
//  RooConstVar DELO("DELO","DELO",DE_MIN);
  RooConstVar DELO("DELO","DELO",DE_MIN);

  RooRealVar mbc_center("mbc_center","mbc_center",0.5*(mbc_min+mbc_max),mbc_min,mbc_max); mbc_center.setConstant(kTRUE);
  RooRealVar mbc_center_eq("mbc_center_eq","mbc_center_eq",mr_argedge_3-0.5*(mbc_max-mbc_min)*elliscaleMbc,mbc_min,mbc_max); mbc_center_eq.setConstant(kTRUE);
  RooRealVar de_center("de_center","de_center",0.5*(DE_MIN+DE_MAX),DE_MIN,DE_MAX); de_center.setConstant(kTRUE);
  RooRealVar mbc_radius("mbc_radius","mbc_radius",0.5*(mbc_max-mbc_min)*elliscaleMbc,0,0.5*(mbcMax-mbcMin)); mbc_radius.setConstant(kTRUE);
  RooRealVar de_radius("de_radius","de_radius",0.5*(DE_MAX-DE_MIN)*elliscaleDe,0.,0.5*(deMax-deMin)); de_radius.setConstant(kTRUE);
  RooRealVar mbc_radius1("mbc_radius1","mbc_radius1",0.5*(mbc_max-mbc_min),0,0.5*(mbcMax-mbcMin)); mbc_radius1.setConstant(kTRUE);
  RooRealVar de_radius1("de_radius1","de_radius1",0.5*(DE_MAX-DE_MIN),0.,0.5*(deMax-deMin)); de_radius1.setConstant(kTRUE);

  cout << 0.5*(mbc_min+mbc_max) << " " << 0.5*(mbc_max-mbc_min) << endl;
  cout << 0.5*(DE_MIN+DE_MAX) << " " << 0.5*(DE_MAX-DE_MIN) << endl;

  mbc_center.Print();
  mbc_center_eq.Print();

  const double BDTG_MIN = bdtg_cut_etagg;
  const double BDTG_MAX = 1;
  RooCategory mode("mode","mode");
  mode.defineType("eta",2);
  RooCategory h0mode("h0mode","h0mode");
  h0mode.defineType("gg",10);
  argset.add(mode);
  argset.add(h0mode);

  RooRealVar mbc("mbc","M_{bc}",0.5*(mbc_min+mbc_max),mbcMin,mbcMax,"GeV");
  argset.add(mbc);
  mbc.setRange("Signal",mbc_min,mbc_max);
  mbc.setRange("mbcSignal",mbc_min,mbc_max);
  mbc.setRange("deSignal",mbcMin,mbcMax);

  RooRealVar de("de","#DeltaE",deMin,deMax,"GeV");
  argset.add(de);
  de.setRange("Signal",DE_MIN,DE_MAX);
  de.setRange("mbcSignal",deMin,deMax);
  de.setRange("deSignal",DE_MIN,DE_MAX);
  
  RooRealVar md("md","md",DMass-md_cut,DMass+md_cut,"GeV");
  argset.add(md);
  RooRealVar mk("mk","mk",KMass-mk_cut,KMass+mk_cut,"GeV");
  argset.add(mk);
  RooRealVar mh0("mh0","mh0",EtaMass-meta_cut,EtaMass+meta_cut,"GeV");
  argset.add(mh0);
  RooRealVar bdtg("bdtg","bdtg",BDTG_MIN,1.);
  argset.add(bdtg);
  RooRealVar atckpi_max("atckpi_max","atckpi_max",0.,atckpi_cut);
  argset.add(atckpi_max);

  argset.add(b0f);
  RooDataSet ds("ds","ds",tree,argset,"mbc>0||mbc<=0");
//  RooDataSet* ds0 = ds.reduce(RooArgSet(de,mbc));

  stringstream out;
  out.str("");
  out << "de<" << DE_MAX << " && de>" << DE_MIN;
  out << " && mbc>" << mbc_min << " && mbc<" << mbc_max;
  Roo1DTable* sigtable = ds.table(b0f,out.str().c_str());
  sigtable->Print();
  sigtable->Print("v");

  Roo1DTable* fulltable = ds.table(b0f);
  fulltable->Print();
  fulltable->Print("v");

//  RooDataHist* dh = ds0->binnedClone();

  ds.Print();

  if(!data){
    out.str("");
    out << "de<" << DE_MAX << " && de>" << DE_MIN;
    out << " && mbc>" << mbc_min << " && mbc<" << mbc_max;
    Roo1DTable* sigtable = ds.table(b0f,out.str().c_str());
    sigtable->Print();
    sigtable->Print("v");

    Roo1DTable* fulltable = ds.table(b0f);
    fulltable->Print();
    fulltable->Print("v");
  }

  ////////////////
  // Signal PDF //
  ////////////////
  ////////////
  // de pdf //
  ////////////
  RooRealVar de0("de0","de0",get_de0(_mode,_h0mode,_b0f),-0.2,0.1); if(cSIG) de0.setConstant(kTRUE);
  RooRealVar s1("s1","s1",get_s1(_mode,_h0mode,_b0f),0.,0.5);       if(cSIG) s1.setConstant(kTRUE);
  RooGaussian g1("g1","g1",de,de0,s1);

  RooRealVar deCBl("deCBl","deCBl",get_deCBl(_mode,_h0mode,_b0f),-0.2,0.1);     if(cSIG) deCBl.setConstant(kTRUE);
  RooRealVar sCBl("sCBl","sCBl",get_sCBl(_mode,_h0mode,_b0f),0.,0.5);           if(cSIG) sCBl.setConstant(kTRUE);
  RooRealVar nl("nl","nl",get_nl(_mode,_h0mode,_b0f),0.,100.);                  if(cSIG) nl.setConstant(kTRUE);
  RooRealVar alphal("alphal","alphal",get_alphal(_mode,_h0mode,_b0f),-10.,10.); if(cSIG) alphal.setConstant(kTRUE);

  RooRealVar deCBr("deCBr","deCBr",get_deCBr(_mode,_h0mode,_b0f),-0.2,0.1);     if(cSIG) deCBr.setConstant(kTRUE);
  RooRealVar sCBr("sCBr","sCBr",get_sCBr(_mode,_h0mode,_b0f),0.,0.5);           if(cSIG) sCBr.setConstant(kTRUE);
  RooRealVar nr("nr","nr",get_nr(_mode,_h0mode,_b0f),0.,100.);                  if(cSIG) nr.setConstant(kTRUE);
  RooRealVar alphar("alphar","alphar",get_alphar(_mode,_h0mode,_b0f),-10.,10.); if(cSIG) alphar.setConstant(kTRUE);

  RooCBShape CBl("CBl","CBl",de,deCBl,sCBl,alphal,nl);
  RooCBShape CBr("CBr","CBr",de,deCBr,sCBr,alphar,nr);

  RooRealVar fCBl("fCBl","fCBl",get_fCBl(_mode,_h0mode,_b0f),0.,1.); if(cSIG) fCBl.setConstant(kTRUE);
  RooRealVar fCBr("fCBr","fCBr",get_fCBr(_mode,_h0mode,_b0f),0.,1.); if(cSIG) fCBr.setConstant(kTRUE);

  RooAddPdf pdf_de_sig("pdf_de_sig","pdf_de_sig",RooArgList(CBl,CBr,g1),RooArgSet(fCBl,fCBr));

  /////////////
  // mbc pdf //
  /////////////
  RooRealVar c1_mbc0("c1_mbc0","c1_mbc0",m_mbc0_c1_eta10,-0.1,0.); c1_mbc0.setConstant(kTRUE);
  RooRealVar c2_mbc0("c2_mbc0","c2_mbc0",m_mbc0_c2_eta10,0.,1.);   c2_mbc0.setConstant(kTRUE);
  RooRealVar c3_mbc0("c3_mbc0","c3_mbc0",m_mbc0_c3_eta10,0.,10.);  c3_mbc0.setConstant(kTRUE);
  RooRealVar mbc0("mbc0","mbc0",m_mbc0_c0_eta10,5.26,5.30); if(cSIG) mbc0.setConstant(kTRUE);
//  RooFormulaVar _mbc0("_mbc0","_mbc0","abs(@0+@1*@2+@1*@1*@3+@1*@1*@1*@4) > abs(@0+@5*@2+@5*@5*@3+@5*@5*@5*@4) ? (@0+@5*@2+@5*@5*@3+@5*@5*@5*@4) : @0+@1*@2+@1*@1*@3+@1*@1*@1*@4",RooArgList(mbc0,de,c1_mbc0,c2_mbc0,c3_mbc0,DELO));
  RooFormulaVar _mbc0("_mbc0","_mbc0","abs(@1*@2+@1*@1*@3+@1*@1*@1*@4) > abs(@5*@2+@5*@5*@3+@5*@5*@5*@4) ? @0 : @0+@1*@2+@1*@1*@3+@1*@1*@1*@4",RooArgList(mbc0,de,c1_mbc0,c2_mbc0,c3_mbc0,DELO));

  RooRealVar c1_alpha("c1_alpha","c1_alpha",m_alpha_c1_eta10,-2.,0.); c1_alpha.setConstant(kTRUE);
  RooRealVar c2_alpha("c2_alpha","c2_alpha",m_alpha_c2_eta10,10.,100.);c2_alpha.setConstant(kTRUE);
  RooRealVar c3_alpha("c3_alpha","c3_alpha",m_alpha_c3_eta10,10.,100.);c3_alpha.setConstant(kTRUE);
  RooRealVar alpha("alpha","alpha",m_alpha_c0_eta10,0.,0.1); if(cSIG) alpha.setConstant(kTRUE);
  RooFormulaVar _alpha("_alpha","_alpha","abs(@0+@1*@2+@1*@1*@3+@1*@1*@1*@4) > abs(@0+@5*@2+@5*@5*@3+@5*@5*@5*@4) ? (@0+@5*@2+@5*@5*@3+@5*@5*@5*@4) : (@0+@1*@2+@1*@1*@3+@1*@1*@1*@4)",RooArgList(alpha,de,c1_alpha,c2_alpha,c3_alpha,DELO));

  RooRealVar c1_width("c1_width","c1_width",m_width_c1_eta10,-2.,0.);  c1_width.setConstant(kTRUE);
  RooRealVar c2_width("c2_width","c2_width",m_width_c2_eta10,10.,100.);c2_width.setConstant(kTRUE);
  RooRealVar width("width","width",m_width_c0_eta10,0.,0.1); if(cSIG) width.setConstant(kTRUE);
  RooFormulaVar _width("_width","_width","@0+@1*@2+@1*@1*@3",RooArgList(width,de,c1_width,c2_width));

  RooNovosibirsk pdf_mbc_sig("pdf_mbc_sig","pdf_mbc_sig",mbc,_mbc0,_width,_alpha);

  /////////
  // pdf //
  /////////
  RooProdPdf pdf_sig("pdf_sig","pdf_sig",pdf_de_sig,Conditional(pdf_mbc_sig,mbc));

  //////////////
  // Comb PDF //
  //////////////
  ////////////
  // de pdf //
  ////////////
  RooRealVar c10("c10","c10",m_c10_eta10,-10.,10.);c10.setConstant(kTRUE);
  RooRealVar c11("c11","c11",m_c11_eta10,-10.,10); c11.setConstant(kTRUE);
  RooRealVar c12("c12","c12",m_c12_eta10,-10.,10); c12.setConstant(kTRUE);
  RooFormulaVar _c1("_c1","@0+@1*@3+@2*@3*@3",RooArgSet(c10,c11,c12,mbc));
  RooRealVar c20("c20","c20",m_c20_eta10,-10.,10.);c20.setConstant(kTRUE);
  RooRealVar c21("c21","c21",m_c21_eta10,-10.,10); c21.setConstant(kTRUE);
  RooFormulaVar _c2("_c2","@0+@1*@2",RooArgSet(c20,c21,mbc));

  RooRealVar d1("d1","d1",0.,-100000,100000);
  RooRealVar d2("d2","d2",0.,-100000,100000);
  RooChebychev pdf_de_comb("pdf_de_comb","pdf_de_comb",de,RooArgSet(d1,d2));

  /////////////
  // mbc pdf //
  /////////////
  RooRealVar argpar("argpar","argus shape parameter",m_argpar_eta10,-100.,-1.); argpar.setConstant(kTRUE);
  RooRealVar argedge("argedge","argedge",m_argedge_eta10,5.285,5.292);          argedge.setConstant(kTRUE);
  RooArgusBG pdf_mbc_comb("pdf_mbc_comb","Argus PDF",mbc,argedge,argpar);

  //////////////
  // pdf comb //
  //////////////
//  RooProdPdf pdf_comb("pdf_comb","pdf_comb",pdf_mbc_comb,Conditional(pdf_de_comb,de));
  RooProdPdf pdf_comb("pdf_comb","pdf_comb",RooArgSet(pdf_mbc_comb,pdf_de_comb,de));
  
  /////////////////
  // BB comb PDF //
  /////////////////
  /////////////
  // mbc pdf //
  /////////////
//  RooRealVar edge("edge","edge",5.29,5.28,5.30,"GeV");// edge.setConstant(kTRUE);
//  RooRealVar mbctau("mbctau","mbctau",-97.,-300,0.,"GeV");
//  RooRealVar pow1("pow1","pow1",6.8,0.1,10);
//  RooRealVar pow2("pow2","pow2",0.12,0.1,10);

  RooRealVar edge("edge","edge",5.29,5.28,5.30,"GeV");       edge.setConstant(kTRUE);
  RooRealVar mbctau("mbctau","mbctau",m_mbctau_bbcomb_eta10,-100,0.,"GeV"); mbctau.setConstant(kTRUE);
  RooRealVar pow1("pow1","pow1",m_pow1_bbcomb_eta10,0.1,10);                pow1.setConstant(kTRUE);
  RooRealVar pow2("pow2","pow2",m_pow2_bbcomb_eta10,0.1,10);                pow2.setConstant(kTRUE);

  RooGenericPdf pdf_mbc_bb_comb("pdf_mbc_bb_comb","pow(@1-@0,@2)*exp(@3*pow(@1-@0,@4))",RooArgList(mbc,edge,pow1,mbctau,pow2));

  ////////////
  // de pdf //
  ////////////
  RooRealVar c3("c3","c3",m_c0_bb_eta10,-100000.,10.); c3.setConstant(kTRUE);
  RooRealVar c31("c31","c31",m_c1_bb_eta10,-10.,10.); c31.setConstant(kTRUE);
  RooFormulaVar _c3("_c3","@0+@1*@2",RooArgSet(c3,c31,mbc));
  RooExponential pdf_de_bb_comb("pdf_de_bb_comb","pdf_de_bb_comb",de,_c3);

  RooProdPdf pdf_bb_comb("pdf_bb_comb","pdf_bb_comb",pdf_mbc_bb_comb,Conditional(pdf_de_bb_comb,de));

  //////////////////
  // Complete PDF //
  //////////////////
  const bool OneDfit = false;
  RooRealVar Nsig("Nsig","Nsig",600,0.,10000.);
  RooRealVar Ncmb("Ncmb","Ncmb",10000,0,100000);
  RooRealVar NBBcmb("NBBcmb","NBBcmb",0,0,100000.);
  RooAddPdf pdf("pdf","pdf",RooArgList(pdf_sig,pdf_comb,pdf_bb_comb),RooArgList(Nsig,Ncmb,NBBcmb));
//  RooAddPdf pdf("pdf","pdf",RooArgList(pdf_sig,pdf_bb_comb),RooArgList(Nsig,NBBcmb));
//  RooAddPdf pdf("pdf","pdf",RooArgList(pdf_sig,pdf_comb),RooArgList(Nsig,Ncmb));
//  RooFormulaVar NCmb("NCmb","@0+@1",RooArgList(NBBcmb,Ncmb));

//  RooArgSet* params = pdf.getParameters(RooArgSet(de,mbc));
//  RooArgset* initParams = (RooArgSet*) params->snapshot();
  
  if(!OneDfit) pdf.fitTo(ds,Verbose(),Timer(true));
  else{
    RooAddPdf pdf_de("pdf_de","pdf_de",RooArgList(pdf_de_sig,pdf_de_comb),RooArgList(Nsig,Ncmb));
    NBBcmb.setVal(0);
    NBBcmb.setConstant(kTRUE);
    pdf_de.fitTo(ds,Verbose(),Timer(true));
  }

//return;
//  params->printLatex(OutputFile("PurityEtaGGFit.tex"));

   RooAbsReal* intSig  = pdf_sig.createIntegral(RooArgSet(de,mbc),NormSet(RooArgSet(de,mbc)),Range("Signal"));
   RooAbsReal* intRho  = pdf_bb_comb.createIntegral(RooArgSet(de,mbc),NormSet(RooArgSet(de,mbc)),Range("Signal"));
   RooAbsReal* intCmb  = pdf_comb.createIntegral(RooArgSet(de,mbc),NormSet(RooArgSet(de,mbc)),Range("Signal"));
   const double nsig = intSig->getVal()*Nsig.getVal();
   const double nsig_err = intSig->getVal()*Nsig.getError();
   const double nsig_err_npq = TMath::Sqrt(nsig*(Nsig.getVal()-nsig)/Nsig.getVal());
   const double nsig_err_total = TMath::Sqrt(nsig_err*nsig_err+nsig_err_npq*nsig_err_npq);
   const double nrho = intRho->getVal()*NBBcmb.getVal();
   const double nrho_err = intRho->getVal()*NBBcmb.getError();
   const double nrho_err_npq = TMath::Sqrt(nrho*(NBBcmb.getVal()-nrho)/NBBcmb.getVal());
   const double nrho_err_total = TMath::Sqrt(nrho_err*nrho_err+nrho_err_npq*nrho_err_npq);
   const double ncmb = intCmb->getVal()*Ncmb.getVal();
   const double ncmb_err = intCmb->getVal()*Ncmb.getError();
   const double ncmb_err_npq = TMath::Sqrt(ncmb*(Ncmb.getVal()-ncmb)/Ncmb.getVal());
   const double ncmb_err_total = TMath::Sqrt(ncmb_err*ncmb_err+ncmb_err_npq*ncmb_err_npq);
   const double purity = nsig/(nsig+nrho+ncmb);
   const double purity_err = nsig_err_total/(nsig+nrho+ncmb);

   de.setRange("Ellips",DE_MIN,DE_MAX);
   RooFormulaVar mbclo("mbclo","(1-(@0-@3)/@4*(@0-@3)/@4) > 0 ? @1-@2*TMath::Sqrt(1-(@0-@3)/@4*(@0-@3)/@4) : 0",RooArgSet(de,mbc_center,mbc_radius,de_center,de_radius));
   RooFormulaVar mbchi("mbchi","(1-(@0-@3)/@4*(@0-@3)/@4) > 0 ? @1+@2*TMath::Sqrt(1-(@0-@3)/@4*(@0-@3)/@4) : 0",RooArgSet(de,mbc_center,mbc_radius,de_center,de_radius));
   mbc.setRange("Ellips",mbclo,mbchi);
   
   de.setRange("Elli",DE_MIN,DE_MAX);
   RooFormulaVar mbclo1("mbclo1","(1-(@0-@3)/@4*(@0-@3)/@4) > 0 ? @1-@2*TMath::Sqrt(1-(@0-@3)/@4*(@0-@3)/@4) : 0",RooArgSet(de,mbc_center,mbc_radius1,de_center,de_radius1));
   RooFormulaVar mbchi1("mbchi1","(1-(@0-@3)/@4*(@0-@3)/@4) > 0 ? @1+@2*TMath::Sqrt(1-(@0-@3)/@4*(@0-@3)/@4) : 0",RooArgSet(de,mbc_center,mbc_radius1,de_center,de_radius1));
   mbc.setRange("Elli",mbclo1,mbchi1);

   RooAbsReal* intSigEl = pdf_sig.createIntegral(RooArgSet(de,mbc),NormSet(RooArgSet(de,mbc)),Range("Ellips"));
   RooAbsReal* intRhoEl = pdf_bb_comb.createIntegral(RooArgSet(de,mbc),NormSet(RooArgSet(de,mbc)),Range("Ellips"));
   RooAbsReal* intCmbEl = pdf_comb.createIntegral(RooArgSet(de,mbc),NormSet(RooArgSet(de,mbc)),Range("Ellips"));
   const double nsigEl = intSigEl->getVal()*Nsig.getVal();
   const double nsig_errEl = intSigEl->getVal()*Nsig.getError();
   const double nsig_errEl_npq = TMath::Sqrt(nsigEl*(Nsig.getVal()-nsigEl)/Nsig.getVal());
   const double nsig_errEl_total = TMath::Sqrt(nsig_errEl*nsig_errEl+nsig_errEl_npq*nsig_errEl_npq);
   const double nrhoEl = intRhoEl->getVal()*NBBcmb.getVal();
   const double nrho_errEl = intRhoEl->getVal()*NBBcmb.getError();
   const double nrho_errEl_npq = TMath::Sqrt(nrhoEl*(NBBcmb.getVal()-nrhoEl)/NBBcmb.getVal());
   const double nrho_errEl_total = TMath::Sqrt(nrho_errEl*nrho_errEl+nrho_errEl_npq*nrho_errEl_npq);
   const double ncmbEl = intCmbEl->getVal()*Ncmb.getVal();
   const double ncmb_errEl = intCmbEl->getVal()*Ncmb.getError();
   const double ncmb_errEl_npq = TMath::Sqrt(ncmbEl*(Ncmb.getVal()-ncmbEl)/Ncmb.getVal());
   const double ncmb_errEl_total = TMath::Sqrt(ncmb_errEl*ncmb_errEl+ncmb_errEl_npq*ncmb_errEl_npq);
   const double purityEl = nsigEl/(nsigEl+nrhoEl+ncmbEl);
   const double purity_errEl = nsig_errEl_total/(nsigEl+nrhoEl+ncmbEl);

   RooAbsReal* intSigEl1 = pdf_sig.createIntegral(RooArgSet(de,mbc),NormSet(RooArgSet(de,mbc)),Range("Elli"));
   RooAbsReal* intRhoEl1 = pdf_bb_comb.createIntegral(RooArgSet(de,mbc),NormSet(RooArgSet(de,mbc)),Range("Elli"));
   RooAbsReal* intCmbEl1 = pdf_comb.createIntegral(RooArgSet(de,mbc),NormSet(RooArgSet(de,mbc)),Range("Elli"));
   const double nsigEl1 = intSigEl1->getVal()*Nsig.getVal();
   const double nsig_errEl1 = intSigEl1->getVal()*Nsig.getError();
   const double nsig_errEl1_npq = TMath::Sqrt(nsigEl1*(Nsig.getVal()-nsigEl1)/Nsig.getVal());
   const double nsig_errEl1_total = TMath::Sqrt(nsig_errEl1*nsig_errEl1+nsig_errEl1_npq*nsig_errEl1_npq);
   const double nrhoEl1 = intRhoEl1->getVal()*NBBcmb.getVal();
   const double nrho_errEl1 = intRhoEl1->getVal()*NBBcmb.getError();
   const double nrho_errEl1_npq = TMath::Sqrt(nrhoEl1*(NBBcmb.getVal()-nrhoEl1)/NBBcmb.getVal());
   const double nrho_errEl1_total = TMath::Sqrt(nrho_errEl1*nrho_errEl1+nrho_errEl1_npq*nrho_errEl1_npq);
   const double ncmbEl1 = intCmbEl1->getVal()*Ncmb.getVal();
   const double ncmb_errEl1 = intCmbEl1->getVal()*Ncmb.getError();
   const double ncmb_errEl1_npq = TMath::Sqrt(ncmbEl1*(Ncmb.getVal()-ncmbEl1)/Ncmb.getVal());
   const double ncmb_errEl1_total = TMath::Sqrt(ncmb_errEl1*ncmb_errEl1+ncmb_errEl1_npq*ncmb_errEl1_npq);
   const double purityEl1 = nsigEl1/(nsigEl1+nrhoEl1+ncmbEl1);
   const double purity_errEl1 = nsig_errEl1_total/(nsigEl1+nrhoEl1+ncmbEl1);

  /////////////
  //  Plots  //
  /////////////
  // de //
  RooPlot* deFrame = de.frame();
  ds.plotOn(deFrame,DataError(RooAbsData::SumW2),MarkerSize(1),CutRange("mbcSignal"));
  pdf.plotOn(deFrame,Components(pdf_sig),LineStyle(kDashed),ProjectionRange("mbcSignal"));
//  pdf.plotOn(deFrame,Components(pdf_back),LineStyle(kDashed),ProjectionRange("mbcSignal"));
  pdf.plotOn(deFrame,Components(pdf_bb_comb),LineStyle(kDashed),ProjectionRange("mbcSignal"));
  pdf.plotOn(deFrame,Components(RooArgSet(pdf_comb)),LineStyle(kDashed),ProjectionRange("mbcSignal"));
  pdf.plotOn(deFrame,LineWidth(2),ProjectionRange("mbcSignal"));

  RooHist* hdepull = deFrame->pullHist();
  RooPlot* dePull = de.frame(Title("#Delta E pull distribution"));
  dePull->addPlotable(hdepull,"P");
  dePull->GetYaxis()->SetRangeUser(-5,5);

  TCanvas* cm = new TCanvas("#Delta E","#Delta E",600,700);
  cm->cd();

  TPad *pad3 = new TPad("pad3","pad3",0.01,0.20,0.99,0.99);
  TPad *pad4 = new TPad("pad4","pad4",0.01,0.01,0.99,0.20);
  pad3->Draw();
  pad4->Draw();

  pad3->cd();
  pad3->SetLeftMargin(0.15);
  pad3->SetFillColor(0);

  deFrame->GetXaxis()->SetTitleSize(0.05);
  deFrame->GetXaxis()->SetTitleOffset(0.85);
  deFrame->GetXaxis()->SetLabelSize(0.04);
  deFrame->GetYaxis()->SetTitleOffset(1.6);
  deFrame->Draw();

  stringstream out1;
  TPaveText *pt = new TPaveText(0.6,0.75,0.98,0.9,"brNDC");
  pt->SetFillColor(0);
  pt->SetTextAlign(12);
  out1.str("");
  out1 << "#chi^{2}/n.d.f = " << deFrame->chiSquare();
  pt->AddText(out1.str().c_str());
  out1.str("");
  if(!data) out1 << "S: " << (int)(nsig+0.5) << " #pm " << (int)(nsig_err_total+0.5);
  else      out1 << "S: " << (int)(nsigEl+0.5) << " #pm " << (int)(nsig_errEl_total+0.5);
  pt->AddText(out1.str().c_str());
  out1.str("");
  if(!data) out1 << "Purity: " << std::fixed << std::setprecision(2) << purity*100. << " #pm " << purity_err*100;
  else out1 << "Purity: " << std::fixed << std::setprecision(2) << purityEl*100. << " #pm " << purity_errEl*100;
  pt->AddText(out1.str().c_str());
  pt->Draw();

  TLine *de_line_RIGHT;
  if(!data) de_line_RIGHT = new TLine(DE_MAX,0,DE_MAX,120);
  else      de_line_RIGHT = new TLine(DE_MAX,0,DE_MAX,30);
  de_line_RIGHT->SetLineColor(kRed);
  de_line_RIGHT->SetLineStyle(1);
  de_line_RIGHT->SetLineWidth((Width_t)2.);
  de_line_RIGHT->Draw();
  TLine *de_line_LEFT;
  if(!data) de_line_LEFT = new TLine(DE_MIN,0,DE_MIN,120);
  else      de_line_LEFT = new TLine(DE_MIN,0,DE_MIN,30);
  de_line_LEFT->SetLineColor(kRed);
  de_line_LEFT->SetLineStyle(1);
  de_line_LEFT->SetLineWidth((Width_t)2.);
  de_line_LEFT->Draw();

  pad4->cd(); pad4->SetLeftMargin(0.15); pad4->SetFillColor(0);
  dePull->SetMarkerSize(0.05); dePull->Draw();
  TLine *de_lineUP = new TLine(deMin,3,deMax,3);
  de_lineUP->SetLineColor(kBlue);
  de_lineUP->SetLineStyle(2);
  de_lineUP->Draw();
  TLine *de_line = new TLine(deMin,0,deMax,0);
  de_line->SetLineColor(kBlue);
  de_line->SetLineStyle(1);
  de_line->SetLineWidth((Width_t)2.);
  de_line->Draw();
  TLine *de_lineDOWN = new TLine(deMin,-3,deMax,-3);
  de_lineDOWN->SetLineColor(kBlue);
  de_lineDOWN->SetLineStyle(2);
  de_lineDOWN->Draw();

  cm->Update();
  
  // mbc //
  RooPlot* mbcFrame = mbc.frame();
  ds.plotOn(mbcFrame,DataError(RooAbsData::SumW2),MarkerSize(1),CutRange("deSignal"));
//  pdf.plotOn(mbcFrame,Components(pdf_back),LineStyle(kDashed),ProjectionRange("deSignal"));
  pdf.plotOn(mbcFrame,Components(pdf_comb),LineStyle(kDashed),ProjectionRange("deSignal"));
  pdf.plotOn(mbcFrame,Components(pdf_bb_comb),LineStyle(kDashed),ProjectionRange("deSignal"));
  pdf.plotOn(mbcFrame,Components(pdf_sig),LineStyle(kDashed),ProjectionRange("deSignal"));
  pdf.plotOn(mbcFrame,LineWidth(2),ProjectionRange("deSignal"));

  RooHist* hmbcpull = mbcFrame->pullHist();
  RooPlot* mbcPull = mbc.frame(Title("#Delta E pull distribution"));
  mbcPull->addPlotable(hmbcpull,"P");
  mbcPull->GetYaxis()->SetRangeUser(-5,5);

  TCanvas* cmmbc = new TCanvas("M_{bc}","M_{bc}",600,700);
  cmmbc->cd();

  TPad *pad1 = new TPad("pad1","pad1",0.01,0.20,0.99,0.99);
  TPad *pad2 = new TPad("pad2","pad2",0.01,0.01,0.99,0.20);
  pad1->Draw();
  pad2->Draw();

  pad1->cd();
  pad1->SetLeftMargin(0.15);
  pad1->SetFillColor(0);

  mbcFrame->GetXaxis()->SetTitleSize(0.05);
  mbcFrame->GetXaxis()->SetTitleOffset(0.85);
  mbcFrame->GetXaxis()->SetLabelSize(0.04);
  mbcFrame->GetYaxis()->SetTitleOffset(1.6);
  mbcFrame->Draw();

  TPaveText *ptmbc = new TPaveText(0.2,0.75,0.58,0.9,"brNDC");
  ptmbc->SetFillColor(0);
  ptmbc->SetTextAlign(12);
  out1.str("");
  out1 << "#chi^{2}/n.d.f = " << mbcFrame->chiSquare();
  ptmbc->AddText(out1.str().c_str());
  out1.str("");
  if(!data) out1 << "S: " << (int)(nsig+0.5) << " #pm " << (int)(nsig_err_total+0.5);
  else      out1 << "S: " << (int)(nsigEl+0.5) << " #pm " << (int)(nsig_errEl_total+0.5);
  ptmbc->AddText(out1.str().c_str());
  out1.str("");
  if(!data) out1 << "Purity: " << std::fixed << std::setprecision(2) << purity*100. << " #pm " << purity_err*100;
  else out1 << "Purity: " << std::fixed << std::setprecision(2) << purityEl*100. << " #pm " << purity_errEl*100;
  ptmbc->AddText(out1.str().c_str());
  ptmbc->Draw();

  TLine *mbc_line_RIGHT;
  if(!data) mbc_line_RIGHT = new TLine(mbc_max,0,mbc_max,70);
  else      mbc_line_RIGHT = new TLine(mbc_max,0,mbc_max,40);
  mbc_line_RIGHT->SetLineColor(kRed);
  mbc_line_RIGHT->SetLineStyle(1);
  mbc_line_RIGHT->SetLineWidth((Width_t)2.);
  mbc_line_RIGHT->Draw();
  TLine *mbc_line_LEFT;
  if(!data) mbc_line_LEFT = new TLine(mbc_min,0,mbc_min,70);
  else      mbc_line_LEFT = new TLine(mbc_min,0,mbc_min,40);
  mbc_line_LEFT->SetLineColor(kRed);
  mbc_line_LEFT->SetLineStyle(1);
  mbc_line_LEFT->SetLineWidth((Width_t)2.);
  mbc_line_LEFT->Draw();
  
  pad2->cd();
  pad2->SetLeftMargin(0.15);
  pad2->SetFillColor(0);
  mbcPull->SetMarkerSize(0.05);
  mbcPull->Draw();
  TLine *mbc_lineUP = new TLine(mbcMin,3,mbcMax,3);
  mbc_lineUP->SetLineColor(kBlue);
  mbc_lineUP->SetLineStyle(2);
  mbc_lineUP->Draw();
  TLine *mbc_line = new TLine(mbcMin,0,mbcMax,0);
  mbc_line->SetLineColor(kBlue);
  mbc_line->SetLineStyle(1);
  mbc_line->SetLineWidth((Width_t)2.);
  mbc_line->Draw();
  TLine *mbc_lineDOWN = new TLine(mbcMin,-3,mbcMax,-3);
  mbc_lineDOWN->SetLineColor(kBlue);
  mbc_lineDOWN->SetLineStyle(2);
  mbc_lineDOWN->Draw();

  cmmbc->Update();
  
  double DEMIN = -0.15;
//  if(keysflag) DEMIN = -0.3;
  TH2D* hh_pdf = pdf.createHistogram("hh_data",de,Binning(50,DEMIN,0.1),YVar(mbc,Binning(50,5.26,5.30)));
  hh_pdf->SetLineColor(kBlue);
  TCanvas* hhc = new TCanvas("hhc","hhc",600,600);
  hhc->cd();
  hh_pdf->Draw("SURF");

  // Show signal ranges
  TEllipse* elli = new TEllipse(de_center.getVal(),mbc_center.getVal(),de_radius.getVal(),mbc_radius.getVal());
  elli->SetFillColor(0);
  elli->SetFillStyle(0);
  elli->SetLineColor(kBlue);
  elli->SetLineWidth(2);
  TEllipse* elli1 = new TEllipse(de_center.getVal(),mbc_center.getVal(),de_radius1.getVal(),mbc_radius1.getVal());
  elli1->SetFillColor(0);
  elli1->SetFillStyle(0);
  elli1->SetLineColor(kBlue);
  elli1->SetLineWidth(2);
  TLine* l1 = new TLine(DE_MIN,mbc_min,DE_MAX,mbc_min);
  l1->SetLineColor(kRed);
  l1->SetLineStyle(1);
  l1->SetLineWidth(2);
  TLine* l2 = new TLine(DE_MIN,mbc_max,DE_MAX,mbc_max);
  l2->SetLineColor(kRed);
  l2->SetLineStyle(1);
  l2->SetLineWidth(2);
  TLine* l3 = new TLine(DE_MIN,mbc_min,DE_MIN,mbc_max);
  l3->SetLineColor(kRed);
  l3->SetLineStyle(1);
  l3->SetLineWidth(2);
  TLine* l4 = new TLine(DE_MAX,mbc_min,DE_MAX,mbc_max);
  l4->SetLineColor(kRed);
  l4->SetLineStyle(1);
  l4->SetLineWidth(2);

  TCanvas* ellican = new TCanvas("ellican","ellican",400,400);
  ellican->cd();
  out.str("");
  out << "bdtg>" << BDTG_MIN << " && bdtg<" << BDTG_MAX << " && de>-0.15 && de<0.20 && mbc>5.265";
  tree->Draw("mbc:de",out.str().c_str());
  elli->Draw(); elli1->Draw(); l1->Draw(); l2->Draw(); l3->Draw(); l4->Draw();
  
  if(!data){
    TCanvas* sigcan = new TCanvas("sigcan","sigcan",400,400);
    sigcan->cd();
    out.str("");
    out << "bdtg>" << BDTG_MIN << " && bdtg<" << BDTG_MAX << " && de>-0.15 && de<0.20 && mbc>5.265 && (b0f == 1 || b0f == 5 || b0f == 10)";
    tree->Draw("mbc:de",out.str().c_str());
    elli->Draw(); elli1->Draw(); l1->Draw(); l2->Draw(); l3->Draw(); l4->Draw();
  
    TCanvas* backcan = new TCanvas("backcan","backcan",400,400);
    backcan->cd();
    out.str("");
    out << "bdtg>" << BDTG_MIN << " && bdtg<" << BDTG_MAX << " && de>-0.15 && de<0.20 && mbc>5.265 && !(b0f == 1 || b0f == 5 || b0f == 10 || b0f == 0)";
    tree->Draw("mbc:de",out.str().c_str());
    elli->Draw(); elli1->Draw(); l1->Draw(); l2->Draw(); l3->Draw(); l4->Draw();
    
    cout << "Rectangle:" << endl;
    out.str("");
    out << "de<" << DE_MAX << " && de>" << DE_MIN;
    out << " && mbc>" << mbc_min << " && mbc<" << mbc_max;
    Roo1DTable* recttable = ds.table(b0f,out.str().c_str());
    recttable->Print();
    recttable->Print("v");

    cout << "Ellips:" << endl;
    out.str("");
    out << "(de-" << de_center.getVal() << ")/" << de_radius.getVal() << "*(de-" << de_center.getVal() << ")/" << de_radius.getVal() << "+(mbc-"<<mbc_center.getVal()<<")/" << mbc_radius.getVal() << "*(mbc-" << mbc_center.getVal() << ")/" << mbc_radius.getVal() << "<1";
    cout << out.str() << endl;
    Roo1DTable* ellitable = ds.table(b0f,out.str().c_str());
    ellitable->Print();
    ellitable->Print("v");
     
    cout << "Elli:" << endl;
    out.str("");
    out << "(de-" << de_center.getVal() << ")/" << de_radius1.getVal() << "*(de-" << de_center.getVal() << ")/" << de_radius1.getVal() << "+(mbc-"<<mbc_center.getVal()<<")/" << mbc_radius1.getVal() << "*(mbc-" << mbc_center.getVal() << ")/" << mbc_radius1.getVal() << "<1";
    cout << out.str() << endl;
    Roo1DTable* ellitable1 = ds.table(b0f,out.str().c_str());
    ellitable1->Print();
    ellitable1->Print("v");

    Roo1DTable* fulltable = ds.table(b0f);
    fulltable->Print();
    fulltable->Print("v");
  }

  cout << "Rectangle:" << endl;
  cout << "Nsig    = " << nsig <<" +- " << nsig_err << " +- " << nsig_err_npq << " (" << nsig_err_total << ")" << endl;
  cout << "NBBcomb = " << nrho <<" +- " << nrho_err << " +- " << nrho_err_npq << " (" << nrho_err_total << ")" << endl;
  cout << "Ncmb    = " << ncmb <<" +- " << ncmb_err << " +- " << ncmb_err_npq << " (" << ncmb_err_total << ")" << endl;
  cout << "Pury    = " << purity << " +- " << purity_err << endl;

  cout << "Ellips:" << endl;
  cout << "Nsig    = " << nsigEl <<" +- " << nsig_errEl << " +- " << nsig_errEl_npq << " (" << nsig_errEl_total << ")" << endl;
  cout << "NBBcomb = " << nrhoEl <<" +- " << nrho_errEl << " +- " << nrho_errEl_npq << " (" << nrho_errEl_total << ")" << endl;
  cout << "Ncmb    = " << ncmbEl <<" +- " << ncmb_errEl << " +- " << ncmb_errEl_npq << " (" << ncmb_errEl_total << ")" << endl;
  cout << "Pury    = " << purityEl << " +- " << purity_errEl << endl;
  
  cout << "Elli:" << endl;
  cout << "Nsig    = " << nsigEl1 <<" +- " << nsig_errEl1 << " +- " << nsig_errEl1_npq << " (" << nsig_errEl1_total << ")" << endl;
  cout << "NBBcomb = " << nrhoEl1 <<" +- " << nrho_errEl1 << " +- " << nrho_errEl1_npq << " (" << nrho_errEl1_total << ")" << endl;
  cout << "Ncmb    = " << ncmbEl1 <<" +- " << ncmb_errEl1 << " +- " << ncmb_errEl1_npq << " (" << ncmb_errEl1_total << ")" << endl;
  cout << "Pury    = " << purityEl1 << " +- " << purity_errEl1 << endl;

  // de full //
  RooPlot* deFrameF = de.frame();
  ds.plotOn(deFrameF,DataError(RooAbsData::SumW2),MarkerSize(1),MarkerColor(kGreen));
  pdf.plotOn(deFrameF,Components(pdf_sig),LineStyle(kDashed));
  pdf.plotOn(deFrameF,Components(RooArgSet(pdf_comb,pdf_bb_comb)),LineStyle(kDashed));
  pdf.plotOn(deFrameF,LineWidth(2));
  
  RooHist* hdepullF = deFrameF->pullHist();
  RooPlot* dePullF = de.frame(Title("#Delta E pull"));
  dePullF->addPlotable(hdepullF,"P");
  dePullF->GetYaxis()->SetRangeUser(-5,5);

  TCanvas* cmf = new TCanvas("#Delta E full","#Delta E full",600,700);
  cmf->cd();

  TPad *pad5 = new TPad("pad5","pad5",0.01,0.20,0.99,0.99);
  TPad *pad6 = new TPad("pad6","pad6",0.01,0.01,0.99,0.20);
  pad5->Draw();
  pad6->Draw();

  pad5->cd();
  pad5->SetLeftMargin(0.15);
  pad5->SetFillColor(0);

  deFrameF->GetXaxis()->SetTitleSize(0.05);
  deFrameF->GetXaxis()->SetTitleOffset(0.85);
  deFrameF->GetXaxis()->SetLabelSize(0.04);
  deFrameF->GetYaxis()->SetTitleOffset(1.6);
  deFrameF->Draw();

  TPaveText *ptf = new TPaveText(0.6,0.75,0.98,0.9,"brNDC");
  ptf->SetFillColor(0);
  ptf->SetTextAlign(12);
  out1.str("");
  out1 << "#chi^{2}/n.d.f = " << deFrameF->chiSquare();
  ptf->AddText(out1.str().c_str());
//  out1.str("");
//  if(!data) out1 << "S: " << (int)(nsig+0.5) << " #pm " << (int)(nsig_err_total+0.5);
//  else      out1 << "S: " << (int)(nsigEl+0.5) << " #pm " << (int)(nsig_errEl_total+0.5);
//  ptf->AddText(out1.str().c_str());
//  out1.str("");
//  if(!data) out1 << "Purity: " << std::fixed << std::setprecision(2) << purity*100. << " #pm " << purity_err*100;
//  else out1 << "Purity: " << std::fixed << std::setprecision(2) << purityEl*100. << " #pm " << purity_errEl*100;
//  ptf->AddText(out1.str().c_str());
  ptf->Draw();

//  TLine *de_line_RIGHT;
//  if(!data) de_line_RIGHT = new TLine(DE_MAX,0,DE_MAX,120);
//  else      de_line_RIGHT = new TLine(DE_MAX,0,DE_MAX,30);
//  de_line_RIGHT->SetLineColor(kRed);
//  de_line_RIGHT->SetLineStyle(1);
//  de_line_RIGHT->SetLineWidth((Width_t)2.);
//  de_line_RIGHT->Draw();
  TLine *de_line_LEFT;
//  if(!data) de_line_LEFT = new TLine(DE_MIN,0,DE_MIN,120);
//  else      de_line_LEFT = new TLine(DE_MIN,0,DE_MIN,30);
//  de_line_LEFT->SetLineColor(kRed);
//  de_line_LEFT->SetLineStyle(1);
//  de_line_LEFT->SetLineWidth((Width_t)2.);
  de_line_LEFT->Draw();

  pad6->cd(); pad6->SetLeftMargin(0.15); pad6->SetFillColor(0);
  dePullF->SetMarkerSize(0.05); dePullF->Draw();
//  TLine *de_lineUP = new TLine(deMin,3,deMax,3);
//  de_lineUP->SetLineColor(kBlue);
//  de_lineUP->SetLineStyle(2);
  de_lineUP->Draw();
//  TLine *de_line = new TLine(deMin,0,deMax,0);
//  de_line->SetLineColor(kBlue);
//  de_line->SetLineStyle(1);
//  de_line->SetLineWidth((Width_t)2.);
  de_line->Draw();
//  TLine *de_lineDOWN = new TLine(deMin,-3,deMax,-3);
//  de_lineDOWN->SetLineColor(kBlue);
//  de_lineDOWN->SetLineStyle(2);
  de_lineDOWN->Draw();

  cmf->Update();

}
コード例 #16
0
void Back_2dFit(void){
  TFile *ifile = TFile::Open("/home/vitaly/B0toDh0/TMVA/fil_b2dh_gen.root");
  TTree *tree = (TTree*)ifile->Get("TEvent");

  RooCategory b0f("b0f","b0f");
  b0f.defineType("comb",-1);

  RooArgSet argset;
  
  const double mbcMin = 5.20;
  const double mbcMax = 5.29;
  const double deMin = -0.15;
  const double deMax = 0.3;

  RooRealVar mbc("mbc","M_{bc}",mbcMin,mbcMax,"GeV"); argset.add(mbc);
  mbc.setRange("Signal",mbc_min,mbc_max);
  mbc.setRange("mbcSignal",mbc_min,mbc_max);
  mbc.setRange("deSignal",mbcMin,mbcMax);
  RooRealVar de("de","#DeltaE",deMin,deMax,"GeV"); argset.add(de);
  de.setRange("Signal",de_min,de_max);
  de.setRange("mbcSignal",deMin,deMax);
  de.setRange("deSignal",de_min,de_max);
  RooRealVar md("md","md",DMass-md_cut,DMass+md_cut,"GeV"); argset.add(md);
  RooRealVar mk("mk","mk",KMass-mk_cut,KMass+mk_cut,"GeV"); argset.add(mk);
  RooRealVar mpi0("mpi0","mpi0",Pi0Mass-mpi0_cut,Pi0Mass+mpi0_cut,"GeV"); argset.add(mpi0);
  RooRealVar bdtgs("bdtgs","bdtgs",bdtgs_cut,1.); argset.add(bdtgs);
  RooRealVar atckpi_max("atckpi_max","atckpi_max",0.,atckpi_cut); argset.add(atckpi_max);

  argset.add(b0f);

  RooDataSet ds("ds","ds",tree,argset);
  RooDataSet* ds0 = ds.reduce(RooArgSet(de,mbc));
  RooDataHist* dh = ds0->binnedClone();
  ds.Print();
  dh->Print();

  ////////////
  // de pdf //
  ////////////
//  RooRealVar c1("c1","c1",mc_c1,-1.,0.); if(cComb) c1.setConstant(kTRUE);
//  RooRealVar c2("c2","c2",mc_c2,0.,0.1); if(cComb) c2.setConstant(kTRUE);
  RooRealVar c3("c3","c3",mc_c1,-1.,0.); if(cComb) c3.setConstant(kTRUE);
  RooRealVar c4("c4","c4",mc_c2,0.,0.1); if(cComb) c4.setConstant(kTRUE);
  RooChebychev pdf_de("pdf_de","pdf_de",de,RooArgSet(c3,c4));

  /////////////
  // mbc pdf //
  /////////////
  RooRealVar argpar("argpar","argus shape parameter",mc_argpar,-100.,-1.); if(cComb)
  argpar.setConstant(kTRUE);
  RooRealVar argedge("argedge","argedge",mc_argedge,5.285,5.292); if(cComb) argedge.setConstant(kTRUE);
  RooArgusBG pdf_mbc("pdf_mbc","Argus PDF",mbc,argedge,argpar);

  /////////
  // pdf //
  /////////
  RooProdPdf pdf("pdf","pdf",RooArgList(pdf_de,pdf_mbc));

  pdf.fitTo(*dh,Verbose(),Timer(true));

  /////////////
  //  Plots  //
  /////////////
  // de //
  RooPlot* deFrame = de.frame();
  ds.plotOn(deFrame,DataError(RooAbsData::SumW2),MarkerSize(1),MarkerColor(kGreen));
  pdf.plotOn(deFrame,LineWidth(2),LineColor(kGreen));
  ds.plotOn(deFrame,DataError(RooAbsData::SumW2),MarkerSize(1),CutRange("mbcSignal"));
  pdf.plotOn(deFrame,LineWidth(2),ProjectionRange("mbcSignal"));

  RooHist* hdepull = deFrame->pullHist();
  RooPlot* dePull = de.frame(Title("#Delta E pull distribution"));
  dePull->addPlotable(hdepull,"P");
  dePull->GetYaxis()->SetRangeUser(-5,5);

  TCanvas* cm = new TCanvas("#Delta E, Signal","#Delta E, Signal",600,700);
  cm->cd();

  TPad *pad3 = new TPad("pad3","pad3",0.01,0.20,0.99,0.99);
  TPad *pad4 = new TPad("pad4","pad4",0.01,0.01,0.99,0.20);
  pad3->Draw();
  pad4->Draw();

  pad3->cd();
  pad3->SetLeftMargin(0.15);
  pad3->SetFillColor(0);

  deFrame->GetXaxis()->SetTitleSize(0.05);
  deFrame->GetXaxis()->SetTitleOffset(0.85);
  deFrame->GetXaxis()->SetLabelSize(0.04);
  deFrame->GetYaxis()->SetTitleOffset(1.6);
  deFrame->Draw();

  stringstream out;
  out.str("");
  out << "#chi^{2}/n.d.f = " << deFrame->chiSquare();
  TPaveText *pt = new TPaveText(0.6,0.8,0.98,0.9,"brNDC");
  pt->SetFillColor(0);
  pt->SetTextAlign(12);
  pt->AddText(out.str().c_str());
  pt->Draw();

  TLine *de_line_RIGHT = new TLine(de_max,0,de_max,200);
  de_line_RIGHT->SetLineColor(kRed);
  de_line_RIGHT->SetLineStyle(1);
  de_line_RIGHT->SetLineWidth((Width_t)2.);
  de_line_RIGHT->Draw();
  TLine *de_line_LEFT = new TLine(de_min,0,de_min,200);
  de_line_LEFT->SetLineColor(kRed);
  de_line_LEFT->SetLineStyle(1);
  de_line_LEFT->SetLineWidth((Width_t)2.);
  de_line_LEFT->Draw();

  pad4->cd(); pad4->SetLeftMargin(0.15); pad4->SetFillColor(0);
  dePull->SetMarkerSize(0.05); dePull->Draw();
  TLine *de_lineUP = new TLine(deMin,3,deMax,3);
  de_lineUP->SetLineColor(kBlue);
  de_lineUP->SetLineStyle(2);
  de_lineUP->Draw();
  TLine *de_line = new TLine(deMin,0,deMax,0);
  de_line->SetLineColor(kBlue);
  de_line->SetLineStyle(1);
  de_line->SetLineWidth((Width_t)2.);
  de_line->Draw();
  TLine *de_lineDOWN = new TLine(deMin,-3,deMax,-3);
  de_lineDOWN->SetLineColor(kBlue);
  de_lineDOWN->SetLineStyle(2);
  de_lineDOWN->Draw();

  cm->Update();
  
  // mbc //
  RooPlot* mbcFrame = mbc.frame();
  ds.plotOn(mbcFrame,DataError(RooAbsData::SumW2),MarkerSize(1),MarkerColor(kGreen));
  pdf.plotOn(mbcFrame,LineWidth(2),LineColor(kGreen));
  ds.plotOn(mbcFrame,DataError(RooAbsData::SumW2),MarkerSize(1),CutRange("deSignal"));
  pdf.plotOn(mbcFrame,LineWidth(2),ProjectionRange("deSignal"));

  RooHist* hmbcpull = mbcFrame->pullHist();
  RooPlot* mbcPull = mbc.frame(Title("#Delta E pull distribution"));
  mbcPull->addPlotable(hmbcpull,"P");
  mbcPull->GetYaxis()->SetRangeUser(-5,5);

  TCanvas* cmmbc = new TCanvas("M_{bc}, Signal","M_{bc}, Signal",600,700);
  cmmbc->cd();

  TPad *pad1 = new TPad("pad1","pad1",0.01,0.20,0.99,0.99);
  TPad *pad2 = new TPad("pad2","pad2",0.01,0.01,0.99,0.20);
  pad1->Draw();
  pad2->Draw();

  pad1->cd();
  pad1->SetLeftMargin(0.15);
  pad1->SetFillColor(0);

  mbcFrame->GetXaxis()->SetTitleSize(0.05);
  mbcFrame->GetXaxis()->SetTitleOffset(0.85);
  mbcFrame->GetXaxis()->SetLabelSize(0.04);
  mbcFrame->GetYaxis()->SetTitleOffset(1.6);
  mbcFrame->Draw();

  out.str("");
  out << "#chi^{2}/n.d.f = " << mbcFrame->chiSquare();
  TPaveText *ptmbc = new TPaveText(0.6,0.8,0.98,0.9,"brNDC");
  ptmbc->SetFillColor(0);
  ptmbc->SetTextAlign(12);
  ptmbc->AddText(out.str().c_str());
  ptmbc->Draw();

  TLine *mbc_line_RIGHT = new TLine(mbc_max,0,mbc_max,150);
  mbc_line_RIGHT->SetLineColor(kRed);
  mbc_line_RIGHT->SetLineStyle(1);
  mbc_line_RIGHT->SetLineWidth((Width_t)2.);
  mbc_line_RIGHT->Draw();
  TLine *mbc_line_LEFT = new TLine(mbc_min,0,mbc_min,150);
  mbc_line_LEFT->SetLineColor(kRed);
  mbc_line_LEFT->SetLineStyle(1);
  mbc_line_LEFT->SetLineWidth((Width_t)2.);
  mbc_line_LEFT->Draw();
  
  pad2->cd();
  pad2->SetLeftMargin(0.15);
  pad2->SetFillColor(0);
  mbcPull->SetMarkerSize(0.05);
  mbcPull->Draw();
  TLine *mbc_lineUP = new TLine(mbcMin,3,mbcMax,3);
  mbc_lineUP->SetLineColor(kBlue);
  mbc_lineUP->SetLineStyle(2);
  mbc_lineUP->Draw();
  TLine *mbc_line = new TLine(mbcMin,0,mbcMax,0);
  mbc_line->SetLineColor(kBlue);
  mbc_line->SetLineStyle(1);
  mbc_line->SetLineWidth((Width_t)2.);
  mbc_line->Draw();
  TLine *mbc_lineDOWN = new TLine(mbcMin,-3,mbcMax,-3);
  mbc_lineDOWN->SetLineColor(kBlue);
  mbc_lineDOWN->SetLineStyle(2);
  mbc_lineDOWN->Draw();
  
  TH2D* hh_pdf = pdf.createHistogram("hh_data",de,Binning(50,-0.15,0.1),YVar(mbc,Binning(50,5.26,5.30)));
  hh_pdf->SetLineColor(kBlue);
  TCanvas* hhc = new TCanvas("hhc","hhc",600,600);
  hhc->cd();
  hh_pdf->Draw("SURF");

  cmmbc->Update();
}
コード例 #17
0
void plot( TString var, TString data, TString pdf, double low=-1, double high=-1 ) {

  TFile *tf = TFile::Open( "root/FitOut.root" );
  RooWorkspace *w = (RooWorkspace*)tf->Get("w");
  TCanvas *canv = new TCanvas("c","c",800,800);
  TPad *upperPad = new TPad(Form("%s_upper",canv->GetName()),"",0.,0.33,1.,1.);
  TPad *lowerPad = new TPad(Form("%s_lower",canv->GetName()),"",0.,0.,1.,0.33);
  canv->cd();
  upperPad->Draw();
  lowerPad->Draw();

  if ( low < 0 ) low = w->var(var)->getMin();
  if ( high < 0 ) high = w->var(var)->getMax();
  RooPlot *plot = w->var(var)->frame(Range(low,high));
  w->data(data)->plotOn(plot);
  w->pdf(pdf)->plotOn(plot);

  RooHist *underHist = plot->pullHist();
  underHist->GetXaxis()->SetRangeUser(plot->GetXaxis()->GetXmin(), plot->GetXaxis()->GetXmax());
  underHist->GetXaxis()->SetTitle(plot->GetXaxis()->GetTitle());
  underHist->GetYaxis()->SetTitle("Pull");
  underHist->GetXaxis()->SetLabelSize(0.12);
  underHist->GetYaxis()->SetLabelSize(0.12);
  underHist->GetXaxis()->SetTitleSize(0.2);
  underHist->GetXaxis()->SetTitleOffset(0.7);
  underHist->GetYaxis()->SetTitleSize(0.18);
  underHist->GetYaxis()->SetTitleOffset(0.38);

  plot->GetXaxis()->SetTitle("");
  upperPad->SetBottomMargin(0.1);
  upperPad->cd();
  plot->Draw();

  canv->cd();
  lowerPad->SetTopMargin(0.05);
  lowerPad->SetBottomMargin(0.35);
  lowerPad->cd();
  underHist->Draw("AP");

  double ymin = underHist->GetYaxis()->GetXmin();
  double ymax = underHist->GetYaxis()->GetXmax();
  double yrange = Max( Abs( ymin ), Abs( ymax ) );
  underHist->GetYaxis()->SetRangeUser( -1.*yrange, 1.*yrange );

  double xmin = plot->GetXaxis()->GetXmin();
  double xmax = plot->GetXaxis()->GetXmax();

  TColor *mycol3sig = gROOT->GetColor( kGray );
  mycol3sig->SetAlpha(0.5);
  TColor *mycol2sig = gROOT->GetColor( kGray+1 );
  mycol2sig->SetAlpha(0.5);
  TColor *mycol1sig = gROOT->GetColor( kGray+2 );
  mycol1sig->SetAlpha(0.5);

  TBox box3sig;
  box3sig.SetFillColor( mycol3sig->GetNumber() );
  //box3sig.SetFillColorAlpha( kGray, 0.5 );
  box3sig.SetFillStyle(1001);
  box3sig.DrawBox( xmin, -3., xmax, 3.);
  TBox box2sig;
  box2sig.SetFillColor( mycol2sig->GetNumber() );
  //box2sig.SetFillColorAlpha( kGray+1, 0.5 );
  box2sig.SetFillStyle(1001);
  box2sig.DrawBox( xmin, -2., xmax, 2.);
  TBox box1sig;
  box1sig.SetFillColor( mycol1sig->GetNumber() );
  //box1sig.SetFillColorAlpha( kGray+2, 0.5 );
  box1sig.SetFillStyle(1001);
  box1sig.DrawBox( xmin, -1., xmax, 1.);

  TLine lineErr;
  lineErr.SetLineWidth(1);
  lineErr.SetLineColor(kBlue-9);
  lineErr.SetLineStyle(2);
  lineErr.DrawLine(plot->GetXaxis()->GetXmin(),1.,plot->GetXaxis()->GetXmax(),1.);
  lineErr.DrawLine(plot->GetXaxis()->GetXmin(),-1.,plot->GetXaxis()->GetXmax(),-1.);
  lineErr.DrawLine(plot->GetXaxis()->GetXmin(),2.,plot->GetXaxis()->GetXmax(),2.);
  lineErr.DrawLine(plot->GetXaxis()->GetXmin(),-2.,plot->GetXaxis()->GetXmax(),-2.);
  lineErr.DrawLine(plot->GetXaxis()->GetXmin(),3.,plot->GetXaxis()->GetXmax(),3.);
  lineErr.DrawLine(plot->GetXaxis()->GetXmin(),-3.,plot->GetXaxis()->GetXmax(),-3.);

  TLine line;
  line.SetLineWidth(3);
  line.SetLineColor(kBlue);
  line.DrawLine(plot->GetXaxis()->GetXmin(),0.,plot->GetXaxis()->GetXmax(),0.);
  underHist->Draw("Psame");

  RooHist *redPull = new RooHist();
  int newp=0;
  for (int p=0; p<underHist->GetN(); p++) {
    double x,y;
    underHist->GetPoint(p,x,y);
    if ( TMath::Abs(y)>3 ) {
      redPull->SetPoint(newp,x,y);
      redPull->SetPointError(newp,0.,0.,underHist->GetErrorYlow(p),underHist->GetErrorYhigh(p));
      newp++;
    }
  }
  redPull->SetLineWidth(underHist->GetLineWidth());
  redPull->SetMarkerStyle(underHist->GetMarkerStyle());
  redPull->SetMarkerSize(underHist->GetMarkerSize());
  redPull->SetLineColor(kRed);
  redPull->SetMarkerColor(kRed);
  redPull->Draw("Psame");

  canv->Print(Form("tmp/%s.pdf",var.Data()));
  tf->Close();

}
コード例 #18
0
void fit_and_weights_norm(){

    gROOT->ProcessLine(".x ~/cern/scripts/lhcbStyle.C");
    //lhcbStyle();
    gStyle->SetLabelSize(0.05,"x");
    gStyle->SetLabelSize(0.05,"y");
    gStyle->SetTitleSize(0.05,"x");
    gStyle->SetPaperSize(20,26);
    gStyle->SetPadTopMargin(0.0);
    gStyle->SetPadRightMargin(0.05); // increase for colz plots
    gStyle->SetPadBottomMargin(0.0);
    gStyle->SetPadLeftMargin(0.14);
    gStyle->SetTitleH(0.01);
                                                                                    //
    const std::string filename("/afs/cern.ch/work/a/apmorris/private/cern/ntuples/new_tuples/normalisation_samples/Lb2JpsipK_2011_2012_signal_withbdt_cut_05.root");           
    const std::string treename = "withbdt";                                         
    const std::string out_file_mass("~/cern/plots/fitting/Lb2JpsipK_2011_2012_mass_fit_after_bdtg3_05.png");                                   
                                                                                    //

    TFile* file = TFile::Open( filename.c_str() );
    if( !file ) std::cout << "file " << filename << " does not exist" << std::endl;
    TTree* tree = (TTree*)file->Get( treename.c_str() );
    if( !tree ) std::cout << "tree " << treename << " does not exist" << std::endl;



    // -- signal, mass shape
    RooRealVar Lambda_b0_DTF_MASS_constr1("Lambda_b0_DTF_MASS_constr1","m(#chi_{c}pK^{-})", 5550., 5700., "MeV/c^{2}"); 
    RooRealVar Jpsi_M("Jpsi_M","m(#mu#mu)", 3000., 3200., "MeV/c^{2}"); 
    //RooRealVar chi_c_M("chi_c_M","m(J/#psi#gamma)", 3400., 3700., "MeV/c^{2}"); 
    RooRealVar mean("mean","mean", 5630., 5610., 5650.);
    RooRealVar sigma1("sigma1","sigma1", 10., 1., 100.);
    RooRealVar sigma2("sigma2","sigma2", 30.0, 5.0, 300.0);
    RooRealVar alpha1("alpha1","alpha1", 1.0, 0.5, 5.0);
    RooRealVar n1("n1","n1", 1.8, 0.2, 15.0);
    RooRealVar alpha2("alpha2","alpha2", -0.5, -5.5, 0.0);
    RooRealVar n2("n2","n2", 0.7, 0.2, 10.0);
    //RooRealVar bkgcat_chic("bkgcat_chic","bkgcat_chic", 0, 100);
    RooRealVar bdtg3("bdtg3", "bdtg3", -1.0, 1.0);                                    //
    RooRealVar frac2("frac2","frac2", 0.3, 0., 1.);
    
    Lambda_b0_DTF_MASS_constr1.setBins(75);
    
    
    
    
    RooGaussian gauss1("gauss1","gauss1", Lambda_b0_DTF_MASS_constr1, mean, sigma1);
    RooGaussian gauss2("gauss2","gauss2", Lambda_b0_DTF_MASS_constr1, mean, sigma2);
    RooCBShape cb1("cb1","cb1", Lambda_b0_DTF_MASS_constr1, mean, sigma1, alpha1, n1); 
    RooCBShape cb2("cb2","cb2", Lambda_b0_DTF_MASS_constr1, mean, sigma2, alpha2, n2); 
    RooAddPdf sig("sig", "sig", RooArgList(cb1, cb2), RooArgList( frac2 ));
    RooRealVar cbRatio("cbRatio","cb Ratio", 0.8, 0.1, 1.0);
    RooRealVar sigYield("sigYield","sig Yield", 4e2, 1e1, 1e4);
    RooRealVar bgYield("bgYield","bg Yield", 1e2, 1e0, 5e5);

    //put in values from fit_MC here <<--- DON'T FORGET TO CHANGE THESE IF THE FIT CHANGES!!!
    /*
    EXT PARAMETER                                INTERNAL      INTERNAL
  NO.   NAME      VALUE            ERROR       STEP SIZE       VALUE
   1  alpha1       1.74154e+00   3.36750e-02   1.24897e-04  -4.64754e-01
   2  alpha2      -2.02379e+00   6.38694e-02   1.18078e-04   2.87434e+00
   3  cbRatio      3.81630e-01   2.53217e-02   1.04396e-03  -3.83487e-01
   4  mean         5.61983e+03   1.06900e-02   5.57074e-05  -9.73350e-02
   5  n1           3.61886e+00   1.29299e-01   2.50836e-04  -5.68053e-01
   6  n2           3.28978e+00   1.59452e-01   3.00100e-04  -3.78398e-01
   7  sigma1       7.37006e+00   1.49989e-01   2.60360e-05  -1.05787e+00
   8  sigma2       4.90330e+00   4.88847e-02   5.78092e-06  -1.44570e+00
    */
    alpha1.setVal( 1.74154e+00 );
    alpha2.setVal( -2.02379e+00 );
    n1.setVal( 3.61886e+00 );
    n2.setVal( 3.28978e+00 );
    frac2.setVal( 3.81630e-01 );
    sigma1.setVal( 7.37006e+00 );
    sigma2.setVal( 4.90330e+00 );
    
    alpha1.setConstant( true );
    alpha2.setConstant( true );
    frac2.setConstant( true );
    n1.setConstant( true );
    n2.setConstant( true );
    sigma1.setConstant( true );
    sigma2.setConstant( true );

    // -- bg, mass shape
    RooRealVar a1("a1","a1", -0.1, -0.5, 0.5);
    RooChebychev comb("comb","comb", Lambda_b0_DTF_MASS_constr1, a1);
    RooRealVar mean3("mean3","mean3", 5560., 5500., 5600.);
    RooRealVar sigma3("sigma3","sigma3", 5., 1., 10.);
    RooRealVar frac3("frac3","frac", 0.2, 0.0, 0.3);
    RooGaussian gauss3("gauss3","gauss3", Lambda_b0_DTF_MASS_constr1, mean3, sigma3);
    RooAddPdf bg("bg","bg", RooArgList(gauss3, comb), RooArgList(frac3));

    // -- add signal & bg
    RooAddPdf pdf("pdf", "pdf", RooArgList(sig, comb), RooArgList( sigYield, bgYield));  

    RooArgSet obs;
    obs.add(Lambda_b0_DTF_MASS_constr1);
    obs.add(Jpsi_M);
    //obs.add(chi_c_M);
    //obs.add(proton_ProbNNp);
    //obs.add(proton_ProbNNk);
    //obs.add(kaon_ProbNNp);
    //obs.add(kaon_ProbNNk);

    
    RooDataSet ds("ds","ds", obs, RooFit::Import(*tree)); 

    RooPlot* plot = Lambda_b0_DTF_MASS_constr1.frame();

    RooFitResult * result = pdf.fitTo( ds, RooFit::Extended() );
    ds.plotOn( plot );
    pdf.plotOn( plot );
    
    RooPlot* plotPullMass = Lambda_b0_DTF_MASS_constr1.frame();

    plotPullMass->addPlotable( plot->pullHist() );
    //plotPullMass->SetMinimum();
    //plotPullMass->SetMaximum();

    TCanvas* c = new TCanvas();

    TPad* pad1 = new TPad("pad1","pad1", 0, 0.3, 1, 1.0);
    pad1->SetBottomMargin(0.0);
    pad1->SetTopMargin(0.01);
    pad1->Draw();
    c->cd();
    TPad* pad2 = new TPad("pad2","pad2", 0, 0., 1, 0.3);
    pad2->SetBottomMargin(0.0);
    pad2->SetTopMargin(0.0);
    pad2->Draw();

    pdf.plotOn( plot, RooFit::Components( sig ), RooFit::LineColor( kTeal ), RooFit::LineStyle(kDashed) );
    pdf.plotOn( plot, RooFit::Components( comb ), RooFit::LineColor( kOrange ), RooFit::LineStyle(kDashed) );
    pdf.plotOn( plot, RooFit::Components( gauss3 ), RooFit::LineColor( kViolet ), RooFit::LineStyle(kDashed) );

    pad1->cd();
    plot->Draw();



    pad2->cd();
    plotPullMass->Draw("AP");

    c->SaveAs(out_file_mass.c_str());


/*
    RooStats::SPlot* sData = new RooStats::SPlot("sData","An SPlot",
            ds, &pdf, RooArgList(sigYield, bgYield) );


    RooDataSet * dataw_z = new RooDataSet(ds.GetName(),ds.GetTitle(),&ds,*(ds.get()),0,"sigYield_sw") ;
    
    TTree *tree_data = (TTree*)dataw_z->tree();
    TFile * newfile = TFile::Open("/afs/cern.ch/work/a/apmorris/private/cern/ntuples/new_tuples/weighted_data.root","RECREATE");
    tree_data->Write();
    newfile->Close();  
    */
     
 /* 
    TCanvas* d = new TCanvas();
    RooPlot* w_chi_c_Mp = chi_c_Mp.frame();
    dataw_z->plotOn(w_chi_c_Mp, RooFit::DataError(RooAbsData::SumW2), RooFit::Binning(20)) ;
    w_chi_c_Mp->Draw();
    d->SaveAs("m_chicp_sweighted.png");
 
    TCanvas* e = new TCanvas();
    RooPlot* w_mass_pK = mass_pK.frame();
    dataw_z->plotOn(w_mass_pK, RooFit::DataError(RooAbsData::SumW2), RooFit::Binning(20)) ;
    w_mass_pK->Draw();
    e->SaveAs("m_pK_sweighted.png");
*/
/*
    TCanvas* f = new TCanvas();
    RooPlot* w_Jpsi_M = Jpsi_M.frame();
    dataw_z->plotOn(w_Jpsi_M, RooFit::DataError(RooAbsData::SumW2), RooFit::Binning(20)) ;
    w_Jpsi_M->Draw();
    f->SaveAs("~/cern/plots/m_Jpsi_sweighted.png");

    TCanvas* g = new TCanvas();
    RooPlot* w_chi_c_M = chi_c_M.frame();
    dataw_z->plotOn(w_chi_c_M, RooFit::DataError(RooAbsData::SumW2), RooFit::Binning(20)) ;
    w_chi_c_M->Draw();
    g->SaveAs("~/cern/plots/m_Chic_sweighted.png");
    */
}
コード例 #19
0
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();

}
コード例 #20
0
ファイル: toyMC_new.C プロジェクト: pjwinnetou/quarkonia
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();

   
} 
コード例 #21
0
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();
};
コード例 #22
0
ファイル: deFit.cpp プロジェクト: VitalyVorobyev/B0toD0h0
void deFit(const int mode = 0, const int svd = 2, const bool only_d0 = false){
  TChain* tree = new TChain("TEvent");

  const double bdtg_min = -0.44;
  const double deMin = -0.12;
  const double deMax = 0.3;
  const double mbcMin = 5.272;
  const double mbcMax = 5.287;
//  const double sz_sig_max = 0.2;
//  const double sz_asc_max = 0.2;
//  const double chisq_sig_max = only_d0 ? 10000 : 50;
//  const double chisq_asc_max = 50;
  const double atckpi_pi_max = 0.8;

  const double cm2ps = 78.48566945838871754705;

  const double de_min = -0.035;
  const double de_max =  0.035;

  const bool cComb = false;
  const bool cSig = true;
  const bool simple_peak = false;

  if(mode){
    tree->Add("FIL_b2dpi_charged_v2_0_10.root");
    tree->Add("FIL_b2dpi_charm_0_v2_10.root");
  } else{
    tree->Add("FIL_b2dpi_data_v2.root");
  }

  RooArgSet argset;

  RooCategory exp("exp","exp");
  if(svd == 1){
    exp.defineType("7",7);
    exp.defineType("9",9);
    exp.defineType("11",11);
    exp.defineType("13",13);
    exp.defineType("15",15);
    exp.defineType("17",17);
    exp.defineType("19",19);
    exp.defineType("21",21);
    exp.defineType("23",23);
    exp.defineType("25",25);
    exp.defineType("27",27);
  } else{
    exp.defineType("31",31);
    exp.defineType("33",33);
    exp.defineType("35",35);
    exp.defineType("37",37);
    exp.defineType("39",39);
    exp.defineType("41",41);
    exp.defineType("43",43);
    exp.defineType("45",45);
    exp.defineType("47",47);
    exp.defineType("49",49);
    exp.defineType("51",51);
    exp.defineType("55",55);
    exp.defineType("61",61);
    exp.defineType("63",63);
    exp.defineType("65",65);
  }
  argset.add(exp);

  RooCategory ndf_z_asc("ndf_z_asc","ndf_z_asc");
  ndf_z_asc.defineType("0",0);
  ndf_z_asc.defineType("2",2);
  ndf_z_asc.defineType("4",4);
  ndf_z_asc.defineType("6",6);
  ndf_z_asc.defineType("8",8);
  ndf_z_asc.defineType("10",10);
  ndf_z_asc.defineType("12",12);
  ndf_z_asc.defineType("14",14);
  ndf_z_asc.defineType("16",16);
  ndf_z_asc.defineType("18",18);
  argset.add(ndf_z_asc);

  RooCategory good_icpv_mlt("good_icpv_mlt","good_icpv_mlt");
  good_icpv_mlt.defineType("good",1);

  RooCategory good_icpv_sgl("good_icpv_sgl","good_icpv_sgl");
  good_icpv_sgl.defineType("good",1);

  if(only_d0){
    argset.add(good_icpv_sgl);
  } else{
    argset.add(good_icpv_mlt);
  }

  RooRealVar mbc("mbc","M_{bc}",mbcMin,mbcMax,"GeV"); argset.add(mbc);
  RooRealVar de("de","#DeltaE",deMin,deMax,"GeV"); argset.add(de);
  de.setRange("Signal",de_min,de_max);
  if(!only_d0){ RooRealVar dz("dz","#Deltaz",-70./cm2ps,70./cm2ps,"cm"); argset.add(dz);}
  else        { RooRealVar dz("dz_d0","#Deltaz",-70./cm2ps,70./cm2ps,"cm"); argset.add(dz);}
  RooRealVar bdtg("bdtg","bdtg",bdtg_min,1.); argset.add(bdtg);
  RooRealVar atckpi_pi("atckpi_pi","atckpi_pi",0.,atckpi_pi_max); argset.add(atckpi_pi);
//  if(!only_d0){ RooRealVar sz_sig("sz_sig","sz_sig",0.,sz_sig_max,"mm"); argset.add(sz_sig);}
//  else        { RooRealVar sz_sig("sz_sig_d0","#sigma_{z}^{sig}",0.,sz_sig_max,"mm"); argset.add(sz_sig);}
//  RooRealVar sz_asc("sz_asc","sz_asc",0.,sz_asc_max,"mm"); argset.add(sz_asc);
//  if(!only_d0 || true){ RooRealVar chisq_z_sig("chisq_z_sig","chisq_z_sig",0.,chisq_sig_max); argset.add(chisq_z_sig);}
//  RooRealVar chisq_z_asc("chisq_z_asc","chisq_z_asc",0.,chisq_asc_max); argset.add(chisq_z_asc);

//  RooDataSet ds("ds","ds",tree,argset,"mbc>0||mbc<=0 && (ndf_z_asc == 0 || 1.*chisq_z_asc/(ndf_z_asc+0.001)<10)");
  RooDataSet ds("ds","ds",tree,argset,"mbc>0||mbc<=0");

  RooRealVar de0DK("de0DK","de0DK",-0.049,-0.055,-0.040); de0DK.setConstant(kTRUE);
  RooRealVar sDK("sDK","sDK",0.017,0.013,0.016);          sDK.setConstant(kTRUE);
  RooGaussian gDK("gDK","gDK",de,de0DK,sDK);
  RooRealVar Nrho("NDK","NDK",50,0.,5000);// Nrho.setConstant(kTRUE);

  RooRealVar c1("c1","c1",-6.96922e-01,-10.,10.); if(cComb) c1.setConstant(kTRUE);
  RooRealVar c2("c2","c2",1.72017e-01,-10.,10.); if(cComb) c2.setConstant(kTRUE);
  RooChebychev pdf_comb("pdf_comb","pdf_comb",de,RooArgSet(c1,c2));
  RooRealVar Ncmb("NComb","NComb",10000,0.,50000);

  RooRealVar de0("de0","de0",0.,-0.005,0.005);
  RooRealVar s("s","s",1.19644e-02,0.010,0.015);
  if(simple_peak){
    RooGaussian pdf_sig("pdf_sig","pdf_sig",de,de0,s);
  } else{
    RooGaussian g1("g1","g1",de,de0,s);

//    RooRealVar nl("nl","nl",4.93610e+00,0.,100.); if(cSig) nl.setConstant(kTRUE);
    RooRealVar nl("nl","nl",7.78037e+00,0.,100.); if(cSig) nl.setConstant(kTRUE);
    RooRealVar alphal("alphal","alphal",-1,-10.,10.); alphal.setConstant(kTRUE);

//    RooRealVar nr("nr","nr",4.91073e+00,0.,100.); if(cSig) nr.setConstant(kTRUE);
    RooRealVar nr("nr","nr",1.29892e+01,0.,100.); if(cSig) nr.setConstant(kTRUE);
    RooRealVar alphar("alphar","alphar",1,-10.,10.); alphar.setConstant(kTRUE);

    RooCBShape CBl("CBl","CBl",de,de0,s,alphal,nl);
    RooCBShape CBr("CBr","CBr",de,de0,s,alphar,nr);

//    RooRealVar fCBl("fCBl","fCBl",2.40571e-01,0.,1.); if(cSig) fCBl.setConstant(kTRUE);
//    RooRealVar fCBr("fCBr","fCBr",2.20385e-01,0.,1.); if(cSig) fCBr.setConstant(kTRUE);
    RooRealVar fCBl("fCBl","fCBl",2.22046e-01,0.,1.); if(cSig) fCBl.setConstant(kTRUE);
    RooRealVar fCBr("fCBr","fCBr",2.21964e-01,0.,1.); if(cSig) fCBr.setConstant(kTRUE);

    RooAddPdf pdf_sig("pdf_sig","pdf_sig",RooArgList(CBl,CBr,g1),RooArgSet(fCBl,fCBr));
  }

  RooRealVar Nsig("NSig","NSig",20000,0.,25000);
  RooAddPdf pdf("pdf","pdf",RooArgSet(gDK,pdf_comb,pdf_sig),RooArgList(Nrho,Ncmb,Nsig));

  pdf.fitTo(ds,Verbose(),Timer(true));


  RooAbsReal* intSig  = pdf_sig.createIntegral(RooArgSet(de),NormSet(RooArgSet(de)),Range("Signal"));
  RooAbsReal* intRho  = gDK.createIntegral(RooArgSet(de),NormSet(RooArgSet(de)),Range("Signal"));
  RooAbsReal* intCmb  = pdf_comb.createIntegral(RooArgSet(de),NormSet(RooArgSet(de)),Range("Signal"));
  const double nsig = intSig->getVal()*Nsig.getVal();
  const double nsig_err = intSig->getVal()*Nsig.getError();
  const double nsig_err_npq = TMath::Sqrt(nsig*(Nsig.getVal()-nsig)/Nsig.getVal());
  const double nsig_err_total = TMath::Sqrt(nsig_err*nsig_err+nsig_err_npq*nsig_err_npq);
  const double nrho = intRho->getVal()*Nrho.getVal();
  const double nrho_err = intRho->getVal()*Nrho.getError();
  const double nrho_err_npq = TMath::Sqrt(nrho*(Nrho.getVal()-nrho)/Nrho.getVal());
  const double nrho_err_total = TMath::Sqrt(nrho_err*nrho_err+nrho_err_npq*nrho_err_npq);
  const double ncmb = intCmb->getVal()*Ncmb.getVal();
  const double ncmb_err = intCmb->getVal()*Ncmb.getError();
  const double ncmb_err_npq = TMath::Sqrt(ncmb*(Ncmb.getVal()-ncmb)/Ncmb.getVal());
  const double ncmb_err_total = TMath::Sqrt(ncmb_err*ncmb_err+ncmb_err_npq*ncmb_err_npq);
  const double purity = nsig/(nsig+nrho+ncmb);
  const double purity_err = nsig_err_total/(nsig+nrho+ncmb);

  double sig_frac;
  double pdf_sig_val;
  double pdf_DK_val;
  double pdf_smooth_val;
  fstream ofile("de_sig_fraction.txt",fstream::out);
  for(int i=0; i<1000; i++){
    const double dde = 0.2/1000;
    de.setVal(-0.1+(i+0.5)*dde);
    pdf_sig_val = Nsig.getVal()*pdf_sig.getVal(de);
    pdf_DK_val = Nrho.getVal()*gDK.getVal(de);
    pdf_smooth_val = Ncmb.getVal()*pdf_comb.getVal(de);
    sig_frac = pdf_sig_val/(pdf_sig_val+pdf_DK_val+pdf_smooth_val);
    ofile << de.getVal() << " " << sig_frac << endl;
  }
  ofile.close();
  /////////////
  //  Plots  //
  /////////////
  // de //
  RooPlot* deFrame = de.frame();
  ds.plotOn(deFrame,DataError(RooAbsData::SumW2),MarkerSize(1));
  pdf.plotOn(deFrame,Components(gDK),LineStyle(kDashed));
  pdf.plotOn(deFrame,Components(pdf_sig),LineStyle(kDashed));
  pdf.plotOn(deFrame,Components(pdf_comb),LineStyle(kDashed));
  pdf.plotOn(deFrame,LineWidth(2));

  RooHist* hdepull = deFrame->pullHist();
  RooPlot* dePull = de.frame(Title("#Delta E pull distribution"));
  dePull->addPlotable(hdepull,"P");
  dePull->GetYaxis()->SetRangeUser(-5,5);

  TCanvas* cm = new TCanvas("Delta E","Delta E",600,700);
  cm->cd();

  TPad *pad3 = new TPad("pad3","pad3",0.01,0.20,0.99,0.99);
  TPad *pad4 = new TPad("pad4","pad4",0.01,0.01,0.99,0.20);
  pad3->Draw();
  pad4->Draw();

  pad3->cd();
  pad3->SetLeftMargin(0.15);
  pad3->SetFillColor(0);
  pad3->SetGrid();

  deFrame->GetXaxis()->SetTitleSize(0.05);
  deFrame->GetXaxis()->SetTitleOffset(0.85);
  deFrame->GetXaxis()->SetLabelSize(0.04);
  deFrame->GetYaxis()->SetTitleOffset(1.6);
  deFrame->Draw();

  const int height = svd == 2 ? 500 : 120;
  TLine *de_line_RIGHT = new TLine(de_max,0,de_max,height);
  de_line_RIGHT->SetLineColor(kRed);
  de_line_RIGHT->SetLineStyle(1);
  de_line_RIGHT->SetLineWidth((Width_t)2.);
  de_line_RIGHT->Draw();
  TLine *de_line_LEFT = new TLine(de_min,0,de_min,height);
  de_line_LEFT->SetLineColor(kRed);
  de_line_LEFT->SetLineStyle(1);
  de_line_LEFT->SetLineWidth((Width_t)2.);
  de_line_LEFT->Draw();

  stringstream out1;
  TPaveText *pt = new TPaveText(0.4,0.65,0.98,0.9,"brNDC");
  pt->SetFillColor(0);
  pt->SetTextAlign(12);
  out1.str("");
  out1 << "#chi^{2}/n.d.f = " << deFrame->chiSquare();
  pt->AddText(out1.str().c_str());
  out1.str("");
  out1 << "S: " << (int)(nsig+0.5) << " #pm " << (int)(nsig_err_total+0.5);
  pt->AddText(out1.str().c_str());
  out1.str("");
  out1 << "Purity: " << std::fixed << std::setprecision(2) << purity*100. << " #pm " << purity_err*100;
  pt->AddText(out1.str().c_str());
  pt->Draw();

  pad4->cd(); pad4->SetLeftMargin(0.15); pad4->SetFillColor(0);
  dePull->SetMarkerSize(0.05); dePull->Draw();
  TLine *de_lineUP = new TLine(deMin,3,deMax,3);
  de_lineUP->SetLineColor(kBlue);
  de_lineUP->SetLineStyle(2);
  de_lineUP->Draw();
  TLine *de_line = new TLine(deMin,0,deMax,0);
  de_line->SetLineColor(kBlue);
  de_line->SetLineStyle(1);
  de_line->SetLineWidth((Width_t)2.);
  de_line->Draw();
  TLine *de_lineDOWN = new TLine(deMin,-3,deMax,-3);
  de_lineDOWN->SetLineColor(kBlue);
  de_lineDOWN->SetLineStyle(2);
  de_lineDOWN->Draw();

  cm->Update();

//  cout << "Nsig = " << nsig <<" +- " << nsig_err << endl;
//  cout << "NDK  = " << nrho <<" +- " << nrho_err << endl;
//  cout << "Ncmb = " << ncmb <<" +- " << ncmb_err << endl;
//  cout << "Purity = " << purity << " +- " << purity_err << endl;

  cout << "Nsig = " << nsig <<" +- " << nsig_err << " +- " << nsig_err_npq << " (" << nsig_err_total << ")" << endl;
  cout << "NDK  = " << nrho <<" +- " << nrho_err << " +- " << nrho_err_npq << " (" << nrho_err_total << ")" << endl;
  cout << "Ncmb = " << ncmb <<" +- " << ncmb_err << " +- " << ncmb_err_npq << " (" << ncmb_err_total << ")" << endl;
  cout << "Pury = " << purity << " +- " << purity_err << endl;
}
コード例 #23
0
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();
  
}
コード例 #24
0
void fit_and_weights_norm(){

    gROOT->ProcessLine(".L ~/cern/project/lhcbStyle.C");
    lhcbStyle();
    /*gStyle->SetLabelSize(0.05,"x");
    gStyle->SetLabelSize(0.05,"y");
    gStyle->SetTitleSize(0.05,"x");
    gStyle->SetPaperSize(20,26);
    gStyle->SetPadTopMargin(0.0);
    gStyle->SetPadRightMargin(0.05); // increase for colz plots
    gStyle->SetPadBottomMargin(0.0);
    gStyle->SetPadLeftMargin(0.14);
    gStyle->SetTitleH(0.01);*/
                                                                                    //
    const std::string filename("/afs/cern.ch/work/a/apmorris/private/cern/ntuples/new_tuples/normalisation_samples/Lb2JpsipK_2011_2012_signal_withbdt.root");           
    const std::string treename = "withbdt";                                         
    const std::string out_file_mass("~/cern/plots/fitting/Lb2JpsipK_2011_2012_mass_fit_after_bdtg3_cut_-055.pdf");                                   
                                                                                    //

    const std::string cuts("bdtg3>=-0.55");    
    
    TFile* file = TFile::Open( filename.c_str() );
    if( !file ) std::cout << "file " << filename << " does not exist" << std::endl;
    
    TTree* tree = (TTree*)file->Get( treename.c_str() );
    if( !tree ) std::cout << "tree " << treename << " does not exist" << std::endl;

    TTree* rTree1 = tree->CopyTree( cuts.c_str() );

    // -- signal, mass shape
    RooRealVar Lambda_b0_DTF_MASS_constr1("Lambda_b0_DTF_MASS_constr1","m(J/#psi p K^{-})", 5550., 5700., "MeV/c^{2}"); 
    RooRealVar Jpsi_M("Jpsi_M","m(#mu#mu)", 3000., 3200., "MeV/c^{2}"); 
    //RooRealVar chi_c_M("chi_c_M","m(J/#psi#gamma)", 3400., 3700., "MeV/c^{2}"); 
    RooRealVar mean("mean","mean", 5620., 5600., 5650.);
    RooRealVar sigma1("sigma1","sigma1", 10., 1., 100.);
    RooRealVar sigma2("sigma2","sigma2", 5.0, 1.0, 300.0);
    RooRealVar sigmaT("sigmaT", "sigmaT", 1.9, 1., 100.);
    RooRealVar alpha1("alpha1","alpha1", 1.0, 0.5, 5.0);
    RooRealVar n1("n1","n1", 1.5, 0.2, 15.0);
    RooRealVar alpha2("alpha2","alpha2", -0.5, -5.5, 0.0);
    RooRealVar n2("n2","n2", 1.5, 0.2, 10.0);
    RooRealVar nu("nu", "nu", 2., 0.7, 100.);
    //RooRealVar bkgcat_chic("bkgcat_chic","bkgcat_chic", 0, 100);
    RooRealVar bdtg3("bdtg3", "bdtg3", -1.0, 1.0);                                    //
    RooRealVar frac2("frac2","frac2", 0.3, 0., 1.);
    
    Lambda_b0_DTF_MASS_constr1.setBins(75);
    
    
    
    
    RooGaussian gauss1("gauss1","gauss1", Lambda_b0_DTF_MASS_constr1, mean, sigma1);
    RooGaussian gauss2("gauss2","gauss2", Lambda_b0_DTF_MASS_constr1, mean, sigma2);
    RooCBShape cb1("cb1","cb1", Lambda_b0_DTF_MASS_constr1, mean, sigma1, alpha1, n1); 
    RooCBShape cb2("cb2","cb2", Lambda_b0_DTF_MASS_constr1, mean, sigma2, alpha2, n2);
    
    //RooStudentT * student = new RooStudentT("student", "student", Lambda_b0_DTF_MASS_constr1, mean, sigmaT, nu);
     
    RooAddPdf sig("sig", "sig", RooArgList(cb1, cb2), RooArgList( frac2 ));
    RooRealVar cbRatio("cbRatio","cb Ratio", 0.3, 0.1, 1.0);
    RooRealVar sigYield("sigYield","sig Yield", 4e2, 1e1, 1e5);
    RooRealVar bgYield("bgYield","bg Yield", 1e2, 1e0, 5e5);

    //put in values from fit_MC here <<--- DON'T FORGET TO CHANGE THESE IF THE FIT CHANGES!!!
    /*
    EXT PARAMETER                                INTERNAL      INTERNAL
  NO.   NAME      VALUE            ERROR       STEP SIZE       VALUE
   1  alpha1       2.18020e+00   2.85078e-02   1.38432e-04  -2.56034e-01
   2  alpha2      -2.79102e+00   6.74385e-02   1.51818e-04  -1.49177e-02
   3  cbRatio      3.07172e-01   1.49204e-02   1.72642e-04  -5.69984e-01
   4  mean         5.61985e+03   9.58397e-03   5.56682e-05  -9.66293e-02
   5  n1           1.49358e+00   8.14447e-02   2.09300e-04  -9.70542e-01
   6  n2           1.45276e+00   1.09864e-01   2.59028e-04  -8.39538e-01
   7  sigma1       8.46303e+00   1.32851e-01   2.86985e-05  -1.01453e+00
   8  sigma2       4.93976e+00   3.42842e-02   5.03572e-06  -1.44512e+00
   
   
   
   
   4  mean         5.62097e+03   4.02152e-02   6.00497e-04   3.08772e-01
   5  sigYield     3.52933e+04   2.55400e+02   1.54032e-03  -1.69958e-02
   6  sigma1       1.22322e+01   1.10970e+00   2.87462e-03   1.63838e-01
   7  sigma2       5.54047e+00   1.41829e-01   1.08300e-03  -1.28653e-01
    */
    
   mean.setVal(5.62097e+03);
   sigma1.setVal(1.22322e+01);
   sigma2.setVal(5.54047e+00);
   
   mean.setConstant(true);
   sigma1.setConstant(true);
   sigma2.setConstant(true);
    
    
    
    //alpha1.setVal( 2.18020e+00 );
    //alpha2.setVal( -2.79102e+00 );
    //n1.setVal( 1.49358e+00 );
    //n2.setVal( 1.45276e+00 );
    //frac2.setVal( 3.81630e-01 );
    //sigma1.setVal( 7.37006e+00 );
    //sigma2.setVal( 4.90330e+00 );
    
    //double gauss
    //alpha1.setVal( 2.18020e+00 );
    //alpha2.setVal( -2.79102e+00 );
    //n1.setVal( 1.49358e+00 );
    //n2.setVal( 1.45276e+00 );
    
    
    //alpha1.setConstant( true );
    //alpha2.setConstant( true );
    //frac2.setConstant( true );
    //n1.setConstant( true );
    //n2.setConstant( true );
    //sigma1.setConstant( true );
    //sigma2.setConstant( true );

    // -- bg, mass shape
    RooRealVar a1("a1","a1", -0.1, -0.5, 0.5);
    RooExponential exp("exp", "exp", Lambda_b0_DTF_MASS_constr1, a1);
    RooChebychev comb("comb","comb", Lambda_b0_DTF_MASS_constr1, a1);
    RooRealVar mean3("mean3","mean3", 5560., 5500., 5600.);
    RooRealVar sigma3("sigma3","sigma3", 5., 1., 100.);
    RooRealVar frac3("frac3","frac", 0.2, 0.0, 0.3);
    RooGaussian gauss3("gauss3","gauss3", Lambda_b0_DTF_MASS_constr1, mean3, sigma3);
    //RooAddPdf bg("bg","bg", RooArgList(gauss3, comb), RooArgList(frac3));

    // -- add signal & bg
    RooAddPdf pdf("pdf", "pdf", RooArgList(sig, comb), RooArgList( sigYield, bgYield));  

    RooArgSet obs;
    obs.add(Lambda_b0_DTF_MASS_constr1);
    obs.add(Jpsi_M);
    //obs.add(chi_c_M);
    //obs.add(proton_ProbNNp);
    //obs.add(proton_ProbNNk);
    //obs.add(kaon_ProbNNp);
    //obs.add(kaon_ProbNNk);

    
    RooDataSet ds("ds","ds", obs, RooFit::Import(*rTree1)); 

    RooPlot* plot = Lambda_b0_DTF_MASS_constr1.frame();

    RooFitResult * result = pdf.fitTo( ds, RooFit::Extended() );
    ds.plotOn( plot );
    pdf.plotOn( plot );
    
    RooPlot* plotPullMass = Lambda_b0_DTF_MASS_constr1.frame();

    plotPullMass->addPlotable( plot->pullHist() );
    //plotPullMass->SetMinimum();
    //plotPullMass->SetMaximum();

    TCanvas* c = new TCanvas();

    TPad* pad1 = new TPad("pad1","pad1", 0, 0.3, 1, 0.95);
    //pad1->SetBottomMargin(0.1);
    //pad1->SetTopMargin(0.1);
    pad1->Draw();
    
    //TPad* pad2 = new TPad("pad2","pad2", 0, 0.05, 1, 0.4);
    TPad* pad2 = new TPad("pad2","pad2", 0, 0.05, 1, 0.3);
    pad2->Draw();
    plotPullMass->GetXaxis()->SetLabelSize(0.1);
    plotPullMass->GetYaxis()->SetLabelSize(0.1);
    plotPullMass->GetXaxis()->SetTitleSize(0.1);
    plotPullMass->GetYaxis()->SetTitleSize(0.1);

    //pdf.plotOn( plot, RooFit::Components( sig ), RooFit::LineColor( kTeal ), RooFit::LineStyle(kDashed) );
    pdf.plotOn( plot, RooFit::Components( comb ), RooFit::LineColor( kOrange ), RooFit::LineStyle(kDashed) );
    //pdf.plotOn( plot, RooFit::Components( gauss3 ), RooFit::LineColor( kViolet ), RooFit::LineStyle(kDashed) );

    pad1->cd();
    plot->Draw();



    pad2->cd();
    plotPullMass->Draw("AP");

    c->SaveAs(out_file_mass.c_str());


    std::cout << rTree1->GetEntries() << " events with the following cut applied: " << cuts.c_str() << std::endl;

/*
    RooStats::SPlot* sData = new RooStats::SPlot("sData","An SPlot",
            ds, &pdf, RooArgList(sigYield, bgYield) );


    RooDataSet * dataw_z = new RooDataSet(ds.GetName(),ds.GetTitle(),&ds,*(ds.get()),0,"sigYield_sw") ;
    
    TTree *tree_data = (TTree*)dataw_z->tree();
    TFile * newfile = TFile::Open("/afs/cern.ch/work/a/apmorris/private/cern/ntuples/new_tuples/weighted_data.root","RECREATE");
    tree_data->Write();
    newfile->Close();  
    */
     
 /* 
    TCanvas* d = new TCanvas();
    RooPlot* w_chi_c_Mp = chi_c_Mp.frame();
    dataw_z->plotOn(w_chi_c_Mp, RooFit::DataError(RooAbsData::SumW2), RooFit::Binning(20)) ;
    w_chi_c_Mp->Draw();
    d->SaveAs("m_chicp_sweighted.png");
 
    TCanvas* e = new TCanvas();
    RooPlot* w_mass_pK = mass_pK.frame();
    dataw_z->plotOn(w_mass_pK, RooFit::DataError(RooAbsData::SumW2), RooFit::Binning(20)) ;
    w_mass_pK->Draw();
    e->SaveAs("m_pK_sweighted.png");
*/
/*
    TCanvas* f = new TCanvas();
    RooPlot* w_Jpsi_M = Jpsi_M.frame();
    dataw_z->plotOn(w_Jpsi_M, RooFit::DataError(RooAbsData::SumW2), RooFit::Binning(20)) ;
    w_Jpsi_M->Draw();
    f->SaveAs("~/cern/plots/m_Jpsi_sweighted.png");

    TCanvas* g = new TCanvas();
    RooPlot* w_chi_c_M = chi_c_M.frame();
    dataw_z->plotOn(w_chi_c_M, RooFit::DataError(RooAbsData::SumW2), RooFit::Binning(20)) ;
    w_chi_c_M->Draw();
    g->SaveAs("~/cern/plots/m_Chic_sweighted.png");
    */
}