Пример #1
0
RooFitResult * fitTo(RooAbsPdf * pdf, RooDataSet * data, RooArgSet * cons = NULL, string opt = "" )
{
	//freopen ("tmp.txt","w",stdout);

	RooFitResult * res = NULL;
	if(cons!=NULL) 
		res = pdf->fitTo(*data,PrintLevel(-1),Save(),NumCPU(2),
			ExternalConstraints(*cons),Warnings(false), Verbose(kFALSE), Minos(true));
	else
		res = pdf->fitTo(*data,PrintLevel(-1),Save(),Warnings(false),NumCPU(2), Minos(true));
	
	//freopen ("/dev/tty", "a", stdout);
	return res;
}
Пример #2
0
   RooFitResult* GenericModel::fitTo(RooDataSet* data)
   {
      // Perform fit of the pseudo-PDF to the data
      // On multi-core machines, this automatically uses all available processor cores

      SafeDelete(fLastFit);
#ifdef WITH_MULTICORE_CPU
      fLastFit = fModelPseudoPDF->fitTo(*data, Save(), NumCPU(WITH_MULTICORE_CPU));
#else
      fLastFit = fModelPseudoPDF->fitTo(*data, Save());
#endif

      SafeDelete(fParamDataHist);
      fParamDataHist = new RooDataHist("params", "params", GetParameters());

      // store weights of component pdfs => distribution of parameters
      fWeights.removeAll();
      const RooArgList& coefs = fModelPseudoPDF->coefList();
      for (int i = 0; i < GetNumberOfDataSets(); i++) {
         RooAbsReal* coef = (RooAbsReal*)coefs.at(i);
         RooRealVar w(Form("w%d", i), Form("Fitted weight of kernel#%d", i), coef->getVal());
         if (coef->InheritsFrom(RooRealVar::Class())) {
            w.setError(((RooRealVar*)coef)->getError());
         } else {
            w.setError(coef->getPropagatedError(*fLastFit));
         }
         fWeights.addClone(w);
         fParamDataHist->set(*GetParametersForDataset(i), w.getVal(), w.getError());
      }

      SafeDelete(fParameterPDF);
      fParameterPDF = new RooHistPdf("paramPDF", "paramPDF", GetParameters(), *fParamDataHist);

      return fLastFit;
   }
Пример #3
0
bool ThreadManager::InitDefault()
{
	int lCpu = NumCPU();
	std::cout << __FILE__ << __LINE__ << " Value of NumCPU :" << lCpu << std::endl;

	if(lCpu <= 0)
	{
		assert(0);
		return false ;
	}

	for(int i= 0 ; i < lCpu ; i++)
	{
		//mListThreadObject.push_back(new ThreadObject()) ;
		AddObject(new ThreadObject());
	}

	return true;
};
Пример #4
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();
};
Пример #5
0
int main() {
    const double PDGLbMass=5619.51;
    const double RareUpperBlind=PDGLbMass+125.0;
    const double RareLowerBlind=PDGLbMass-125.0;
    const double Rare2UpperBlind=PDGLbMass+175.0;
    const double Rare2LowerBlind=PDGLbMass-175.0;
    bool blind=true;
    bool remakecc=false;
    bool remakerare=false;
    bool remakerare2=false;
    bool sweight=false;
    TRandom3* MultiCandRand=new TRandom3(224); //dont change seed
    TH1I* ControlChannelMultiCands= new TH1I("ControlChannelMultiCands","ControlChannelMultiCands",10,0,10);
    TH1I* RareChannelMultiCands= new TH1I("RareChannelMultiCands","RareChannelMultiCands",10,0,10);
    TH1I* Rare2ChannelMultiCands= new TH1I("RareChannel2MultiCands","RareChannel2MultiCands",10,0,10);

    //_______________________________________ MAKE CONTROL CHANNEL ROODATASET______________________________________
    if(remakecc) {
        std::string ControlDataPath=std::getenv("BUKETAPDATABDTRESPROOT");
        DataFile CC12A(ControlDataPath,Data,Twel,MagAll,buketap,"BDTApplied_SampleA");
        DataFile CC12B(ControlDataPath,Data,Twel,MagAll,buketap,"BDTApplied_SampleB");
        DataFile CC11A(ControlDataPath,Data,Elev,MagAll,buketap,"BDTApplied_SampleA");
        DataFile CC11B(ControlDataPath,Data,Elev,MagAll,buketap,"BDTApplied_SampleB");

        TreeReader* CC12Reader= new TreeReader("DecayTree");
        CC12Reader->AddFile(CC12A);
        CC12Reader->AddFile(CC12B);
        CC12Reader->Initialize(ControlCuts::BranchesToKeep,"contains");
        TFile* Minimal12File= new TFile("MinimalCC12.root","RECREATE");
        TTree* Minimal12Tree=CC12Reader->CopyTree(ControlCuts::AllCuts12,-1,"DecayTree");
        TTree* MinimalFlagged12Tree=HandyFunctions::GetSingleTree(MultiCandRand,Minimal12Tree,ControlChannelMultiCands,NULL);
        MinimalFlagged12Tree->Write();
        Minimal12File->Close();

        TreeReader* CC11Reader= new TreeReader("DecayTree");
        CC11Reader->AddFile(CC11A);
        CC11Reader->AddFile(CC11B);
        CC11Reader->Initialize(ControlCuts::BranchesToKeep,"contains");
        TFile* Minimal11File= new TFile("MinimalCC11.root","RECREATE");
        TTree* Minimal11Tree=CC11Reader->CopyTree(ControlCuts::AllCuts11,-1,"DecayTree");
        TTree* MinimalFlagged11Tree=HandyFunctions::GetSingleTree(MultiCandRand,Minimal11Tree,ControlChannelMultiCands,NULL);
        MinimalFlagged11Tree->Write();
        Minimal11File->Close();

        TreeReader* FlaggedReader= new TreeReader("DecayTree");
        FlaggedReader->AddFile("MinimalCC12.root");
        FlaggedReader->AddFile("MinimalCC11.root");
        FlaggedReader->Initialize();
        TFile* CCSingleFile= new TFile("CCSingleFile.root","RECREATE");
        TTree* SingleTree=FlaggedReader->CopyTree("isSingle==1",-1,"DecayTree");
        SingleTree->Write();
        CCSingleFile->Close();
    }

    //_____________________________________Make Rare Mode One Data__________________________________________________
    if(remakerare) {
        std::string RareDataPath=std::getenv("LBPKETAPPIPIGDATABDTRESPROOT");
        DataFile Rare12A(RareDataPath,Data,Twel,MagAll,lbpketappipig,"BDTApplied_SampleA_NB");
        DataFile Rare12B(RareDataPath,Data,Twel,MagAll,lbpketappipig,"BDTApplied_SampleB_NB");
        DataFile Rare11A(RareDataPath,Data,Elev,MagAll,lbpketappipig,"BDTApplied_SampleA_NB");
        DataFile Rare11B(RareDataPath,Data,Elev,MagAll,lbpketappipig,"BDTApplied_SampleB_NB");

        TreeReader* Rare12Reader= new TreeReader("DecayTree");
        Rare12Reader->AddFile(Rare12A);
        Rare12Reader->AddFile(Rare12B);
        Rare12Reader->Initialize(pipigCuts::BranchesToKeep,"contains");
        TFile* Minimal12File= new TFile("MinimalRare12.root","RECREATE");
        TTree* Minimal12Tree=Rare12Reader->CopyTree(pipigCuts::AllCuts12,-1,"DecayTree");
        TTree* MinimalFlagged12Tree=HandyFunctions::GetSingleTree(MultiCandRand,Minimal12Tree,RareChannelMultiCands,NULL);
        MinimalFlagged12Tree->Write();
        Minimal12File->Close();

        TreeReader* Rare11Reader= new TreeReader("DecayTree");
        Rare11Reader->AddFile(Rare11A);
        Rare11Reader->AddFile(Rare11B);
        Rare11Reader->Initialize(pipigCuts::BranchesToKeep,"contains");
        TFile* Minimal11File= new TFile("MinimalRare11.root","RECREATE");
        TTree* Minimal11Tree=Rare11Reader->CopyTree(pipigCuts::AllCuts11,-1,"DecayTree");
        TTree* MinimalFlagged11Tree=HandyFunctions::GetSingleTree(MultiCandRand,Minimal11Tree,RareChannelMultiCands,NULL);
        MinimalFlagged11Tree->Write();
        Minimal11File->Close();

        TreeReader* FlaggedReader= new TreeReader("DecayTree");
        FlaggedReader->AddFile("MinimalRare12.root");
        FlaggedReader->AddFile("MinimalRare11.root");
        FlaggedReader->Initialize();
        TFile* RareSingleFile= new TFile("RareSingleFile.root","RECREATE");
        TTree* SingleTree=FlaggedReader->CopyTree("isSingle==1",-1,"DecayTree");
        SingleTree->Write();
        RareSingleFile->Close();

    }
    //___________________________________ Make Rare mode Two Data________________________________________________
    if(remakerare2) {
        std::string Rare2DataPath=std::getenv("LBPKETAPETADATABDTRESPROOT");
        DataFile Rare212A(Rare2DataPath,Data,Twel,MagAll,lbpketapeta,"BDTApplied_SampleA_NB");
        DataFile Rare212B(Rare2DataPath,Data,Twel,MagAll,lbpketapeta,"BDTApplied_SampleB_NB");
        DataFile Rare211A(Rare2DataPath,Data,Elev,MagAll,lbpketapeta,"BDTApplied_SampleA_NB");
        DataFile Rare211B(Rare2DataPath,Data,Elev,MagAll,lbpketapeta,"BDTApplied_SampleB_NB");

        TreeReader* Rare212Reader= new TreeReader("DecayTree");
        Rare212Reader->AddFile(Rare212A);
        Rare212Reader->AddFile(Rare212B);
        Rare212Reader->Initialize(etapetaCuts::BranchesToKeep,"contains");
        TFile* Minimal12File= new TFile("MinimalRare212.root","RECREATE");
        TTree* Minimal12Tree=Rare212Reader->CopyTree(etapetaCuts::AllCuts12,-1,"DecayTree");
        TTree* MinimalFlagged12Tree=HandyFunctions::GetSingleTree(MultiCandRand,Minimal12Tree,Rare2ChannelMultiCands,NULL);
        MinimalFlagged12Tree->Write();
        Minimal12File->Close();

        TreeReader* Rare211Reader= new TreeReader("DecayTree");
        Rare211Reader->AddFile(Rare211A);
        Rare211Reader->AddFile(Rare211B);
        Rare211Reader->Initialize(etapetaCuts::BranchesToKeep,"contains");
        TFile* Minimal11File= new TFile("MinimalRare211.root","RECREATE");
        TTree* Minimal11Tree=Rare211Reader->CopyTree(etapetaCuts::AllCuts11,-1,"DecayTree");
        TTree* MinimalFlagged11Tree=HandyFunctions::GetSingleTree(MultiCandRand,Minimal11Tree,Rare2ChannelMultiCands,NULL);
        MinimalFlagged11Tree->Write();
        Minimal11File->Close();

        TreeReader* FlaggedReader= new TreeReader("DecayTree");
        FlaggedReader->AddFile("MinimalRare212.root");
        FlaggedReader->AddFile("MinimalRare211.root");
        FlaggedReader->Initialize();
        TFile* Rare2SingleFile= new TFile("Rare2SingleFile.root","RECREATE");
        TTree* SingleTree=FlaggedReader->CopyTree("isSingle==1",-1,"DecayTree");
        SingleTree->Write();
        Rare2SingleFile->Close();
    }
    //____________________________________ Shared Parameters_______________________________________________________

    RooRealVar DataMCRatio("DataMCRatio","DataMCRatio",1.0,0.5,1.5);
    RooRealVar CCMean("CCMean","CCMean",5279.0,5250.0,5310.0);
    RooFormulaVar LambdabMean("LambdabMean","LambdabMean","@0+339.72",RooArgList(CCMean));
    //RooRealVar LambdabMean("LambdabMean","LambdabMean",5619.0,5615.0,5630.0);
    // RooFormulaVar CCMean("CCMean","CCMean","@0 - 339.72",RooArgList(LambdabMean));

    std::vector<RooRealVar*> FreeParameters;
    FreeParameters.push_back(&DataMCRatio);
    //  FreeParameters.push_back(&LambdabMean);

    //____________________________________ Control Channel PDF______________________________________________________

    TFile* CCInputFile = new TFile("CCSingleFile.root");
    TTree* CCInputTree=(TTree*)CCInputFile->Get("DecayTree");
    RooRealVar CCBMass("Bu_DTF_MF","Bu_DTF_MF",5000.0,5550.0);
    RooRealVar CCEtaMass("eta_prime_MM","eta_prime_MM",880.0,1040.0);
    RooArgSet CCArgs(CCBMass,CCEtaMass);
    RooDataSet* CCData=new RooDataSet("CCData","CCData",CCArgs,Import(*CCInputTree));


    //++++++++++++++++++++++++++++++Signal PDF+++++++++++++++++++++++++++++++++


    TFile *CCMCFitResultFile = new TFile("CCFitResult.root");
    RooFitResult* CCMCFitResult=NULL;
    try {
        CCMCFitResult=SafeGetFitResult(CCMCFitResultFile,"CCFitResult");
    } catch(std::exception &e) {
        std::cout<<e.what()<<std::endl;
        return 1;
    }
    CCMCFitResult->Print("v");
    RooRealVar* CCMCSigma=NULL;
    RooRealVar* CCMCLAlphaFix=NULL;
    RooRealVar* CCMCRAlphaFix=NULL;
    RooRealVar* CCMCLNFix=NULL;
    RooRealVar* CCMCRNFix=NULL;

    try {
        CCMCSigma=SafeGetVar(CCMCFitResult,"CCSigma");
        CCMCLAlphaFix=SafeGetVar(CCMCFitResult,"CCLAlpha");
        CCMCRAlphaFix=SafeGetVar(CCMCFitResult,"CCRAlpha");
        CCMCLNFix=SafeGetVar(CCMCFitResult,"CCLN");
        CCMCRNFix=SafeGetVar(CCMCFitResult,"CCRN");
    } catch(std::exception &e) {
        std::cout<<e.what()<<std::endl;
        return 1;
    }
    RooRealVar CCMCSigmaFix("CCMCSigmaFix","CCMCSigmaFix",CCMCSigma->getVal());
    CCMCSigmaFix.setConstant(kTRUE);
    RooFormulaVar CCSigma("CCSigma","CCSigma","@0*@1",RooArgList(DataMCRatio,CCMCSigmaFix));

    RooRealVar CCLAlpha("CCLAlpha","CCLAlpha",CCMCLAlphaFix->getVal());

    RooRealVar CCRAlpha("CCRAlpha","CCRAlpha",CCMCRAlphaFix->getVal());

    RooRealVar CCLN("CCLN","CCLN",CCMCLNFix->getVal());

    RooRealVar CCRN("CCRN","CCRN",CCMCRNFix->getVal());

    RooCBShape CCDCBLeft("CCDCBLeft","CCDCBLeft",CCBMass,CCMean,CCSigma,CCLAlpha,CCLN);

    RooCBShape CCDCBRight("CCDCBRight","CCDCBRight",CCBMass,CCMean,CCSigma,CCRAlpha,CCRN);

    RooRealVar CCFitFraction("CCFitFraction","CCFitFraction",0.5,0.0,1.0);
    FreeParameters.push_back(&CCFitFraction);
    RooAddPdf CCDCB("CCDCB","CCDCB",RooArgList(CCDCBRight,CCDCBLeft),CCFitFraction);

    RooRealVar CCEtamean("CCEtamean","CCEtamean",958.0,955.0,960.0);
    RooRealVar CCEtasigma("CCEtasigma","CCEtasigma",9.16,9.0,15.0);

    RooRealVar* CCMCEtaLAlpha=NULL;
    RooRealVar* CCMCEtaRAlpha=NULL;
    RooRealVar* CCMCEtaLN=NULL;
    RooRealVar* CCMCEtaRN=NULL;

    try {
        CCMCEtaLAlpha=SafeGetVar(CCMCFitResult,"CCEtaLAlpha");
        CCMCEtaRAlpha=SafeGetVar(CCMCFitResult,"CCEtaRAlpha");
        CCMCEtaLN=SafeGetVar(CCMCFitResult,"CCEtaLN");
        CCMCEtaRN=SafeGetVar(CCMCFitResult,"CCEtaRN");
    } catch(std::exception &e) {
        std::cout<<e.what()<<std::endl;
        return 1;
    }
    RooRealVar CCEtaLAlpha("CCEtaLAlpha","CCEtaLAlpha",CCMCEtaLAlpha->getVal());

    RooRealVar CCEtaRAlpha("CCEtaRAlpha","CCEtaRAlpha",CCMCEtaRAlpha->getVal());

    RooRealVar CCEtaLN("CCEtaLN","CCEtaLN",CCMCEtaLN->getVal());

    RooRealVar CCEtaRN("CCEtaRN","CCEtaRN",CCMCEtaRN->getVal());

    RooCBShape CCEtaDCBLeft("CCEtaCBLeft","CCEtaCBLeft",CCEtaMass,CCEtamean,CCEtasigma,CCEtaLAlpha,CCEtaLN);

    RooCBShape CCEtaDCBRight("CCEtaCBRight","CCEtaCBRight",CCEtaMass,CCEtamean,CCEtasigma,CCEtaRAlpha,CCEtaRN);

    RooRealVar CCEtaFitFraction("CCEtaFitFraction","CCEtaFitFraction",0.22,0.1,1.0);
    FreeParameters.push_back(&CCEtaFitFraction);

    RooAddPdf CCEtaDCB("CCEteaDCB","CCEtaDCB",RooArgList(CCEtaDCBRight,CCEtaDCBLeft),CCEtaFitFraction);

    RooProdPdf CCSignalPdf("CCSignalPdf","CCSignalPdf",RooArgSet(CCEtaDCB,CCDCB));
    RooRealVar CCSignalYield("CCSignalYield","CCSignalYield",10000.0,1000.0,20000.0);

    RooExtendPdf CCExtendedSignalPdf("CCExtendedSignalPdf","CCExtendedSignalPdf",CCSignalPdf,CCSignalYield);

    //+++++++++++++++++++++++++++++++++ COMB NO ETAP PDF++++++++++++++++++++++++++++++++++++++++

    RooRealVar CCNoEtaBSlope("CCNoEtaBSlope","CCNoEtaBSlope",-0.6,-0.8,-0.4);
    FreeParameters.push_back(&CCNoEtaBSlope);

    RooRealVar CCNoEtaBCurve("CCNoEtaBCurve","CCNoEtaBCurve",-0.1,-0.30,-0.05);
    FreeParameters.push_back(&CCNoEtaBCurve);

    RooChebychev CCNoEtaBLine("CCNoEtaBLine","CCNoEtaBLine",CCBMass,RooArgList(CCNoEtaBSlope,CCNoEtaBCurve));

    RooRealVar CCNoEtaEtaP1("CCNoEtaEtaP1","CCNoEtaEtaP1",-0.1,-1.0,0.0);
    FreeParameters.push_back(&CCNoEtaEtaP1);

    RooRealVar CCNoEtaEtaP2("CCNoEtaEtaP2","CCNoEtaEtaP2",-0.1,-0.8,0.0);
    FreeParameters.push_back(&CCNoEtaEtaP2);

    RooChebychev CCNoEtaQuad("CCNoEtaQuad","CCNoEtaQuad",CCEtaMass,RooArgList(CCNoEtaEtaP1,CCNoEtaEtaP2));

    RooProdPdf CCNoEtaBkgPdf("CCNoEtaBkgPdf","CCNoEtaBkgPdf",RooArgSet(CCNoEtaQuad,CCNoEtaBLine));
    RooRealVar CCNoEtaBkgYield("CCNoEtaBkgYield","CCNoEtaBkgYield",2400.0,500.0,15000.0);

    RooExtendPdf ExtCCNoEtaBkgPdf("ExtCCNoEtaBkgPdf","ExtCCNoEtaBkgPdf",CCNoEtaBkgPdf,CCNoEtaBkgYield);


    //++++++++++++++++++++++++++++++++++ COMB TRUE ETAP PDF++++++++++++++++++++++++++++++++++

    RooRealVar CCTrueEtaBSlope("CCTrueEtaBSlope","CCTrueEtaBSlope",-0.1,-1.0,0.0);
    FreeParameters.push_back(&CCTrueEtaBSlope);

    RooChebychev CCTrueEtaBLine("CCTrueEtaBLine","CCTrueEtaBLine",CCBMass,RooArgList(CCTrueEtaBSlope));

    RooRealVar CCTrueEtaEtaLAlpha("CCTrueEtaEtaLAlpha","CCTrueEtaEtaLAlpha",CCMCEtaLAlpha->getVal());
    RooRealVar CCTrueEtaEtaRAlpha("CCTrueEtaEtaRAlpha","CCTrueEtaEtaRAlpha",CCMCEtaRAlpha->getVal());
    RooRealVar CCTrueEtaEtaLN("CCTrueEtaEtaLN","CCTrueEtaEtaLN",CCMCEtaLN->getVal());
    RooRealVar CCTrueEtaEtaRN("CCTrueEtaEtaRN","CCTrueEtaEtaRN",CCMCEtaRN->getVal());

    //RooCBShape CCTrueEtaEtaCBLeft("CCTrueEtaEtaCBLeft","CCTrueEtaEtaCBLeft",CCEtaMass,CCEtamean,CCEtasigma,CCTrueEtaEtaLAlpha,CCTrueEtaEtaLN);

    RooCBShape CCTrueEtaEtaCBRight("CCTrueEtaEtaCBRight","CCTrueEtaEtaCBRight",CCEtaMass,CCEtamean,CCEtasigma,CCTrueEtaEtaRAlpha,CCTrueEtaEtaRN);

    //  RooRealVar CCTrueEtaEtaFitFraction("CCTrueEtaEtaFitFraction","CCTrueEtaEtaFitFraction",0.4,0.0,1.0);
    //RooAddPdf CCTrueEtaEtaDCB("CCTrueEtaEtaDCB","CCTrueEtaEtaDCB",RooArgList(CCTrueEtaEtaCBRight,CCTrueEtaEtaCBLeft),CCTrueEtaEtaFitFraction);

    RooProdPdf CCTrueEtaEtaBkgPdf("CCTrueEtaEtaBkgPdf","CCTrueEtaEtaBkgPdf",RooArgSet(CCTrueEtaEtaCBRight,CCTrueEtaBLine));

    RooRealVar CCTrueEtaBkgYield("CCTrueEtaBkgYield","CCTrueEtaBkgYield",800.0,20.0,10000.0);

    RooExtendPdf ExtCCTrueEtaBkgPdf("ExtCCTrueEtaBkgPdf","ExtCCTrueEtaBkgPdf",CCTrueEtaEtaBkgPdf,CCTrueEtaBkgYield);

    RooAddPdf CCTotalPdf("CCTotalPdf","CCTotalPdf",RooArgList(ExtCCTrueEtaBkgPdf,ExtCCNoEtaBkgPdf,CCExtendedSignalPdf));



    //_________________________________Rare1 Fit_____________________________

    TFile * RareInputFile = new TFile("RareSingleFile.root");
    TTree* RareInputTree=NULL;
    try {
        RareInputTree=SafeGetTree(RareInputFile,"DecayTree");
    } catch(std::exception &e) {
        std::cout<<e.what()<<std::endl;
        return 1;
    }
    RooRealVar LbMass("Lambda_b0_DTF_MF","Lambda_b0_DTF_MF",5200.0,6000.0);
    RooRealVar RareLambda_b0_PE("Lambda_b0_PE","Lambda_b0_PE",-RooNumber::infinity(),RooNumber::infinity());
    RooRealVar RareLambda_b0_PX("Lambda_b0_PX","Lambda_b0_PX",-RooNumber::infinity(),RooNumber::infinity());
    RooRealVar RareLambda_b0_PY("Lambda_b0_PY","Lambda_b0_PY",-RooNumber::infinity(),RooNumber::infinity());
    RooRealVar RareLambda_b0_PZ("Lambda_b0_PZ","Lambda_b0_PZ",-RooNumber::infinity(),RooNumber::infinity());
    RooRealVar RareProton_PE("Proton_PE","Proton_PE",-RooNumber::infinity(),RooNumber::infinity());
    RooRealVar RareProton_PX("Proton_PX","Proton_PX",-RooNumber::infinity(),RooNumber::infinity());
    RooRealVar RareProton_PY("Proton_PY","Proton_PY",-RooNumber::infinity(),RooNumber::infinity());
    RooRealVar RareProton_PZ("Proton_PZ","Proton_PZ",-RooNumber::infinity(),RooNumber::infinity());
    RooRealVar RareKaon_PE("Kaon_PE","Kaon_PE",-RooNumber::infinity(),RooNumber::infinity());
    RooRealVar RareKaon_PX("Kaon_PX","Kaon_PX",-RooNumber::infinity(),RooNumber::infinity());
    RooRealVar RareKaon_PY("Kaon_PY","Kaon_PY",-RooNumber::infinity(),RooNumber::infinity());
    RooRealVar RareKaon_PZ("Kaon_PZ","Kaon_PZ",-RooNumber::infinity(),RooNumber::infinity());
    RooRealVar Rareeta_prime_PE("eta_prime_PE","eta_prime_PE",-RooNumber::infinity(),RooNumber::infinity());
    RooRealVar Rareeta_prime_PX("eta_prime_PX","eta_prime_PX",-RooNumber::infinity(),RooNumber::infinity());
    RooRealVar Rareeta_prime_PY("eta_prime_PY","eta_prime_PY",-RooNumber::infinity(),RooNumber::infinity());
    RooRealVar Rareeta_prime_PZ("eta_prime_PZ","eta_prime_PZ",-RooNumber::infinity(),RooNumber::infinity());
    RooArgSet RareArgs(LbMass,RareLambda_b0_PE,RareLambda_b0_PX,RareLambda_b0_PY,RareLambda_b0_PZ,RareProton_PE,RareProton_PX,RareProton_PY,RareProton_PZ);
    RareArgs.add(RareKaon_PE);
    RareArgs.add(RareKaon_PX);
    RareArgs.add(RareKaon_PY);
    RareArgs.add(RareKaon_PZ);
    RareArgs.add(Rareeta_prime_PE);
    RareArgs.add(Rareeta_prime_PX);
    RareArgs.add(Rareeta_prime_PY);
    RareArgs.add(Rareeta_prime_PZ);
    RooDataSet* RareData= new RooDataSet("RareData","RareData",RareArgs,Import(*RareInputTree));


    TFile * RareFitResultFile = new TFile("RareFitResult.root");
    RooFitResult* RareMCFitResult=NULL;
    try {
        RareMCFitResult=SafeGetFitResult(RareFitResultFile,"RareFitResult");
    } catch(std::exception &e) {
        std::cout<<e.what()<<std::endl;
        return 1;
    }
    RareMCFitResult->Print("v");
    RooRealVar* RareMCRAlpha=NULL;
    RooRealVar* RareMCFitFraction=NULL;
    RooRealVar* RareMCLAlpha=NULL;
    RooRealVar* RareMCLN=NULL;
    RooRealVar* RareMCRN=NULL;
    RooRealVar* RareMCSigma=NULL;
    try {
        RareMCRAlpha=SafeGetVar(RareMCFitResult,"RareAlpha");
        RareMCFitFraction=SafeGetVar(RareMCFitResult,"RareFitFraction");
        RareMCLAlpha=SafeGetVar(RareMCFitResult,"RareLAlpha");
        RareMCLN=SafeGetVar(RareMCFitResult,"RareLN");
        RareMCRN=SafeGetVar(RareMCFitResult,"RareRN");
        RareMCSigma=SafeGetVar(RareMCFitResult,"RareSigma");
    } catch(std::exception &e) {
        std::cout<<e.what()<<std::endl;
        return 1;
    }

    //++++++++++++++++++++++++++++++Rare Signal PDF++++++++++++++++++++++++++++
    RooRealVar RareMCSigmaFix("RareMCSigmaFix","RareMCSigmaFix",RareMCSigma->getVal());
    RareMCSigmaFix.setConstant();

    RooFormulaVar RareSigma("RareSigma","RareSigma","@0*@1",RooArgSet(RareMCSigmaFix,DataMCRatio));
    RooRealVar RareLAlpha("RareLAlpha","RareLAlpha",RareMCLAlpha->getVal());
    RooRealVar RareRAlpha("RareRAlpha","RareRAlpha",RareMCRAlpha->getVal());
    RooRealVar RareRN("RareRN","RareRN",RareMCRN->getVal());
    RooRealVar RareLN("RareLN","RareLN",RareMCLN->getVal());
    RooRealVar RareFitFraction("RareFitFraction","RareFitFraction",RareMCFitFraction->getVal());

    RooCBShape RareDCBLeft("DCBLeft","DCBLeft",LbMass,LambdabMean,RareSigma,RareLAlpha,RareLN);

    RooCBShape RareDCBRight("DCBRight","DCBRight",LbMass,LambdabMean,RareSigma,RareRAlpha,RareRN);

    RooAddPdf RareDCB("RareDCB","RareDCB",RooArgList(RareDCBLeft,RareDCBRight),RareFitFraction);

    RooRealVar RareYield("RareYield","RareYield",40.0,-100.0,1000.0);
    RooExtendPdf RareSignalPdf("RareSignalPdf","RareSignalPdf",RareDCB,RareYield);
    //++++++++++++++++++++++++++++++Rare Combinatorial Bkg+++++++++++++++++++++++++++++++++++
    RooRealVar Rarep1("Rarep1","Rarep1",-1.1,-5.0,-0.1);
    FreeParameters.push_back(&Rarep1);

    RooRealVar Rarep2("Rarep2","Rarep2",0.5,0.001,10.0);
    FreeParameters.push_back(&Rarep2);

    RooChebychev RarePoly("RarePoly","RarePoly",LbMass,RooArgList(Rarep1,Rarep2));

    RooRealVar RareBkgYield("RareBkgYield","RareBkgYield",2000.0,0.0,10000.0);
    RooExtendPdf RareBkgPdf("RareBkgPdf","RareBkgPdf",RarePoly,RareBkgYield);

    //++++++++++++++++++++++++++++Rare PKPhi Bkg+++++++++++++++++++++++++++++++++
    TFile* PKPhiMCFitresultFile= new TFile("PkPhiFitResultFile.root");
    RooFitResult* PKPhiMCFitResult=NULL;
    try {
        PKPhiMCFitResult=SafeGetFitResult(PKPhiMCFitresultFile,"PkPhiFitResult");
    } catch(std::exception &e) {
        std::cout<<e.what()<<std::endl;
        return 1;
    }
    PKPhiMCFitResult->Print("v");
    RooRealVar* PkPhiMean=NULL;
    RooRealVar* PkPhiSigma=NULL;
    RooRealVar* PkPhiLAlpha=NULL;
    RooRealVar* PkPhiRAlpha=NULL;
    RooRealVar* PkPhiLN=NULL;
    RooRealVar* PkPhiRN=NULL;
    try {
        PkPhiMean=SafeGetVar(PKPhiMCFitResult,"PkPhiMean");
        PkPhiSigma=SafeGetVar(PKPhiMCFitResult,"PkPhiSigma");
        PkPhiLAlpha=SafeGetVar(PKPhiMCFitResult,"PkPhiLAlpha");
        PkPhiLN=SafeGetVar(PKPhiMCFitResult,"PkPhiLN");
    } catch(std::exception &e) {
        std::cout<<e.what()<<std::endl;
        return 1;
    }

    RooRealVar RarePkPhiMean("RarePkPhiMean","RarePkPhiMean",PkPhiMean->getVal());
    RooRealVar RarePkPhiSigma("RarePkPhiSigma","RarePkPhiSigma",PkPhiSigma->getVal());
    RooRealVar RarePkPhiLN("RarePkPhiLN","RarePkPhiLN",PkPhiLN->getVal());
    RooRealVar RarePkPhiLAlpha("RarePkPhiLAlpha","RarePkPhiLAlpha",PkPhiLAlpha->getVal());

    RooCBShape RarePkPhiModel("RarePkPhiModel","RarePkPhiModel",LbMass,RarePkPhiMean,RarePkPhiSigma,RarePkPhiLAlpha,RarePkPhiLN);

    RooRealVar RarePkPhiYield("RarePkPhiYield","RarePkPhiYield",50.0,1.0,150.0);
    RooExtendPdf RarePkPhiPdf("RarePkPhiPdf","RarePkPhiPdf",RarePkPhiModel,RarePkPhiYield);

    RooAddPdf RarePdf("RarePdf","RarePdf",RooArgList(RarePkPhiPdf,RareBkgPdf,RareSignalPdf));

    /*RarePdf.fitTo(*RareData,Extended(kTRUE));
    RooPlot* RareFrame=LbMass.frame(Bins(35),Range(5200.0,6100.0));
    TCanvas RareCanvas;
    RareData->plotOn(RareFrame);
    RarePdf.plotOn(RareFrame);
    RareFrame->Draw();
    RareCanvas.SaveAs("RareCanvas.pdf");*/

    //________________________________ Fit Rare 2_______________________________
    TFile* Rare2InputFile = new TFile("Rare2SingleFile.root");
    TTree* Rare2InputTree=NULL;
    try {
        Rare2InputTree=SafeGetTree(Rare2InputFile,"DecayTree");
    } catch(std::exception &e) {
        std::cout<<e.what()<<std::endl;
        return 1;
    }
    RooRealVar Rare2Lambda_b0_PE("Lambda_b0_PE","Lambda_b0_PE",-RooNumber::infinity(),RooNumber::infinity());
    RooRealVar Rare2Lambda_b0_PX("Lambda_b0_PX","Lambda_b0_PX",-RooNumber::infinity(),RooNumber::infinity());
    RooRealVar Rare2Lambda_b0_PY("Lambda_b0_PY","Lambda_b0_PY",-RooNumber::infinity(),RooNumber::infinity());
    RooRealVar Rare2Lambda_b0_PZ("Lambda_b0_PZ","Lambda_b0_PZ",-RooNumber::infinity(),RooNumber::infinity());
    RooRealVar Rare2Proton_PE("Proton_PE","Proton_PE",-RooNumber::infinity(),RooNumber::infinity());
    RooRealVar Rare2Proton_PX("Proton_PX","Proton_PX",-RooNumber::infinity(),RooNumber::infinity());
    RooRealVar Rare2Proton_PY("Proton_PY","Proton_PY",-RooNumber::infinity(),RooNumber::infinity());
    RooRealVar Rare2Proton_PZ("Proton_PZ","Proton_PZ",-RooNumber::infinity(),RooNumber::infinity());
    RooRealVar Rare2Kaon_PE("Kaon_PE","Kaon_PE",-RooNumber::infinity(),RooNumber::infinity());
    RooRealVar Rare2Kaon_PX("Kaon_PX","Kaon_PX",-RooNumber::infinity(),RooNumber::infinity());
    RooRealVar Rare2Kaon_PY("Kaon_PY","Kaon_PY",-RooNumber::infinity(),RooNumber::infinity());
    RooRealVar Rare2Kaon_PZ("Kaon_PZ","Kaon_PZ",-RooNumber::infinity(),RooNumber::infinity());
    RooRealVar Rare2eta_prime_PE("eta_prime_PE","eta_prime_PE",-RooNumber::infinity(),RooNumber::infinity());
    RooRealVar Rare2eta_prime_PX("eta_prime_PX","eta_prime_PX",-RooNumber::infinity(),RooNumber::infinity());
    RooRealVar Rare2eta_prime_PY("eta_prime_PY","eta_prime_PY",-RooNumber::infinity(),RooNumber::infinity());
    RooRealVar Rare2eta_prime_PZ("eta_prime_PZ","eta_prime_PZ",-RooNumber::infinity(),RooNumber::infinity());
    RooArgSet Rare2Args(LbMass,Rare2Lambda_b0_PE,Rare2Lambda_b0_PX,Rare2Lambda_b0_PY,Rare2Lambda_b0_PZ,Rare2Proton_PE,Rare2Proton_PX,Rare2Proton_PY,Rare2Proton_PZ);
    Rare2Args.add(Rare2Kaon_PE);
    Rare2Args.add(Rare2Kaon_PX);
    Rare2Args.add(Rare2Kaon_PY);
    Rare2Args.add(Rare2Kaon_PZ);
    Rare2Args.add(Rare2eta_prime_PE);
    Rare2Args.add(Rare2eta_prime_PX);
    Rare2Args.add(Rare2eta_prime_PY);
    Rare2Args.add(Rare2eta_prime_PZ);

    RooDataSet* Rare2Data=new RooDataSet("Rare2Data","Rare2Data",Rare2Args,Import(*Rare2InputTree));

    TFile* Rare2MCFitResultFile= new TFile("RareTwoFitResult.root");
    RooFitResult* Rare2MCFitResult=NULL;
    try {
        Rare2MCFitResult=SafeGetFitResult(Rare2MCFitResultFile,"RareTwoFitResult");
    } catch(std::exception &e) {
        std::cout<<e.what()<<std::endl;
        return 1;
    }

    //++++++++++++++++++++++++++++++Signal PDF++++++++++++++++++++++++++++++++
    RooRealVar* Rare2MCFitFraction=NULL;
    RooRealVar* Rare2MCLAlpha=NULL;
    RooRealVar* Rare2MCLN=NULL;
    RooRealVar* Rare2MCRN=NULL;
    RooRealVar* Rare2MCRAlpha=NULL;
    RooRealVar* Rare2MCSigma=NULL;

    try {
        Rare2MCFitFraction=SafeGetVar(Rare2MCFitResult,"Rare2FitFraction");
        Rare2MCLAlpha=SafeGetVar(Rare2MCFitResult,"Rare2LAlpha");
        Rare2MCLN=SafeGetVar(Rare2MCFitResult,"Rare2LN");
        Rare2MCRN=SafeGetVar(Rare2MCFitResult,"Rare2RN");
        Rare2MCRAlpha=SafeGetVar(Rare2MCFitResult,"Rare2RAlpha");
        Rare2MCSigma=SafeGetVar(Rare2MCFitResult,"Rare2Sigma");
    } catch(std::exception &e) {
        std::cout<<e.what()<<std::endl;
        return 1;
    }

    RooRealVar Rare2SigmaFix("Rare2SigmaFix","Rare2SigmaFix",Rare2MCSigma->getVal());
    RooFormulaVar Rare2Sigma("Rare2Sigma","Rare2Sigma","@0*@1",RooArgList(Rare2SigmaFix,DataMCRatio));

    RooRealVar Rare2LN("Rare2LN","Rare2LN",Rare2MCLN->getVal());
    RooRealVar Rare2RN("Rare2RN","Rare2RN",Rare2MCRN->getVal());
    RooRealVar Rare2RAlpha("Rare2RAlpha","Rare2RAlpha",Rare2MCRAlpha->getVal());
    RooRealVar Rare2LAlpha("Rare2LAlpha","Rare2LAlpha",Rare2MCLAlpha->getVal());
    RooRealVar Rare2FitFraction("Rare2FitFraction","Rare2FitFraction",Rare2MCFitFraction->getVal());

    RooCBShape Rare2CBLeft("Rare2CBLeft","Rare2CBLeft",LbMass,LambdabMean,Rare2Sigma,Rare2LAlpha,Rare2LN);

    RooCBShape Rare2CBRight("Rare2CBRight","Rare2CBRight",LbMass,LambdabMean,Rare2Sigma,Rare2RAlpha,Rare2RN);

    RooAddPdf Rare2DCB("Rare2DCB","Rare2DCB",RooArgList(Rare2CBLeft,Rare2CBRight),Rare2FitFraction);

    RooRealVar Rare2SignalYield("Rare2SignalYield","Rare2SignalYield",100.0,-100.0,1000.0);
    RooExtendPdf Rare2SignalPdf("Rare2SignalPdf","Rare2SignalPdf",Rare2DCB,Rare2SignalYield);

    //++++++++++++++++++++++++++++++Rare 2 Bkg pdf++++++++++++++++++++++++++++++
    RooRealVar Rare2K("K","K",-0.003,-0.1,0.0);
    RooExponential Rare2BkgExp("Rare2BkgExp","Rare2BkgExp",LbMass,Rare2K);
    RooRealVar Rare2BkgYield("Rare2BkgYield","Rare2BkgYield",2000.0,0.0,100000.0);
    RooExtendPdf Rare2BkgPdf("Rare2BkgPdf","Rare2BkgPdf",Rare2BkgExp,Rare2BkgYield);

    RooAddPdf Rare2Pdf("Rare2Pdf","Rare2Pdf",RooArgList(Rare2SignalPdf,Rare2BkgPdf));

    //___________________________________ SImultaneous Part ________________________________________________________

    RooCategory Channel("Channel","Channel");
    Channel.defineType("Rare");
    Channel.defineType("Rare2");
    Channel.defineType("Control");

    RooDataSet* AllData = new RooDataSet("AllData","AllData",RooArgSet(LbMass,CCBMass,CCEtaMass),Index(Channel),Import("Rare",*RareData),Import("Rare2",*Rare2Data),Import("Control",*CCData));

    RooSimultaneous SimPdf("SimPdf","SimPdf",Channel);
    SimPdf.addPdf(Rare2Pdf,"Rare2");
    SimPdf.addPdf(RarePdf,"Rare");
    SimPdf.addPdf(CCTotalPdf,"Control");

    RooDataSet* BlindedData=NULL;
    RooFitResult* SimResult=NULL;
    if(blind) {
        LbMass.setRange("RLSB",5200.0,RareLowerBlind);
        LbMass.setRange("RUSB",RareUpperBlind,6000.0);
        LbMass.setRange("R2LSB",5200.0,Rare2LowerBlind);
        LbMass.setRange("R2USB",Rare2UpperBlind,6000.0);
        LbMass.setRange("RDLSB",5200.0,5493.33333);
        LbMass.setRange("RDUSB",RareUpperBlind,6000.0);

        std::string CutString="Lambda_b0_DTF_MF<"+std::to_string(RareLowerBlind)+"||Lambda_b0_DTF_MF>"+std::to_string(Rare2UpperBlind);
        BlindedData=(RooDataSet*)AllData->reduce(CutString.data());
        RooMsgService::instance().setSilentMode(kTRUE);
        RooMsgService::instance().setGlobalKillBelow(RooFit::FATAL) ;
    }

    RooArgSet MinosPars(Rare2SignalYield,RareYield,CCSignalYield);
    SimResult = SimPdf.fitTo(*AllData,Save(kTRUE),Extended(kTRUE),Minos(MinosPars));
    SimPdf.Print("v");
    RooPlot* NominalLikelihoodRareYield=RareYield.frame(Title("Likelihood scan of RareYield"),Range(50,150));
    RooAbsReal* nll = SimPdf.createNLL(*AllData,NumCPU(2),Extended(kTRUE));
    TCanvas C;
    nll->plotOn(NominalLikelihoodRareYield,ShiftToZero());
    NominalLikelihoodRareYield->Draw();
    C.SaveAs("NominalLikelihood.pdf");
    //  HandyFunctions::SetlhcbStyle();
    //_______________________________ Plot B+ Canvas_____________________________________________________________
    RooPlot* CCBFrame= CCBMass.frame(Bins(50),Range(5000.0,5500.0),Title("Control Channel B+ Mass Projection"));
    AllData->plotOn(CCBFrame,Cut("Channel==Channel::Control"));
    SimPdf.plotOn(CCBFrame,Slice(Channel,"Control"),Components("ExtCCTrueEtaBkgPdf"),LineColor(kMagenta),LineStyle(kDashed),ProjWData(Channel,*AllData));
    SimPdf.plotOn(CCBFrame,Slice(Channel,"Control"),Components("ExtCCNoEtaBkgPdf"),LineColor(kGreen),LineStyle(kDashed),ProjWData(Channel,*AllData));
    SimPdf.plotOn(CCBFrame,Slice(Channel,"Control"),Components("CCExtendedSignalPdf"),LineColor(kRed),LineStyle(kDashed),ProjWData(Channel,*AllData));
    SimPdf.plotOn(CCBFrame,Slice(Channel,"Control"),ProjWData(Channel,*AllData));
    TCanvas* CCBCanvas=HandyFunctions::DecoratePlot(CCBFrame);
    /*(TCanvas* CCBCanvas= new TCanvas("CCBCanvas","CCBCanvas",1600,900);
    CCBFrame->Draw();
    CCBCanvas->SaveAs("CCBCanvas.eps");*/

    //________________________________Plot Eta Canvas_____________________________________________________________
    RooPlot* CCEtaFrame=CCEtaMass.frame(Bins(50),Range(880.0,1040.0),Title("Control Channel Eta' Projection"));
    AllData->plotOn(CCEtaFrame,Cut("Channel==Channel::Control"));
    SimPdf.plotOn(CCEtaFrame,Slice(Channel,"Control"),Components("ExtCCTrueEtaBkgPdf"),LineColor(kMagenta),LineStyle(kDashed),ProjWData(Channel,*AllData));
    SimPdf.plotOn(CCEtaFrame,Slice(Channel,"Control"),Components("ExtCCNoEtaBkgPdf"),LineColor(kGreen),LineStyle(kDashed),ProjWData(Channel,*AllData));
    SimPdf.plotOn(CCEtaFrame,Slice(Channel,"Control"),Components("CCExtendedSignalPdf"),LineColor(kRed),LineStyle(kDashed),ProjWData(Channel,*AllData));
    SimPdf.plotOn(CCEtaFrame,Slice(Channel,"Control"),ProjWData(Channel,*AllData));
    TCanvas* CCEtaCanvas=HandyFunctions::DecoratePlot(CCEtaFrame);
    /*TCanvas* CCEtaCanvas=new TCanvas("CCEtaCanvas","CCEtaCanvas",1600,900);
    CCEtaFrame->Draw();
    CCEtaCanvas->Print("CCEtaCanvas.eps");*/


    //________________________________Plot Rare Canvas_____________________________________________________________
    RooPlot* RareFrame=LbMass.frame(Bins(30),Range(5200.0,6000.0),Title("#Lambda_{b} -> p K (#eta' -> #pi #pi #gamma) ;M(#Lambda_{b})"));
    if(blind) {
        double sidebandsN = RareData ->sumEntries("1","RLSB,RUSB");
        double LowsidebandsN = RareData ->sumEntries("1","RLSB");
        RareData->plotOn(RareFrame,CutRange("RDLSB,RDUSB"),Name("RareDataPlotted"));
        RarePdf.plotOn(RareFrame,Range("RLSB,RUSB"),Components("RarePkPhiPdf"),Name("RarePkPhiBkg"),LineColor(kMagenta),LineStyle(kDashed),Normalization(sidebandsN,RooAbsReal::NumEvent));
        RarePdf.plotOn(RareFrame,Range("RLSB,RUSB"),Components("RareBkgPdf"),Name("RareCombBkg"),LineColor(kGreen),LineStyle(kDashed),Normalization(sidebandsN,RooAbsReal::NumEvent));
        RarePdf.plotOn(RareFrame,Range("RLSB,RUSB"),Normalization(sidebandsN,RooAbsReal::NumEvent));
    } else {
        AllData->plotOn(RareFrame,Cut("Channel==Channel::Rare"));
        SimPdf.plotOn(RareFrame,Slice(Channel,"Rare"),Components("RarePkPhiPdf"),LineColor(kMagenta),LineStyle(kDashed),ProjWData(Channel,*AllData));
        SimPdf.plotOn(RareFrame,Slice(Channel,"Rare"),Components("RareBkgPdf"),LineColor(kGreen),LineStyle(kDashed),ProjWData(Channel,*AllData));
        SimPdf.plotOn(RareFrame,Slice(Channel,"Rare"),Components("RareSignalPdf"),LineColor(kRed),LineStyle(kDashed),ProjWData(Channel,*AllData));
        SimPdf.plotOn(RareFrame,Slice(Channel,"Rare"),ProjWData(Channel,*AllData));
    }
    int i=RareFrame->numItems();
    std::cout<<"_________________________________________"<<std::endl;
    for(int j=0; j<i; j++) {
        std::cout<<RareFrame->nameOf(j)<<std::endl;
    }
    TLegend * RareLegend = new TLegend(0.66,0.7,0.9,0.9);
    RareLegend->AddEntry(RareFrame->findObject("RarePkPhiBkg"),"#Lambda_{b} -> p K #phi bkg","l");
    RareLegend->AddEntry(RareFrame->findObject("RareCombBkg"),"Combinatorial Background","l");
    std::cout<<"++++++++++++++++++++++++++++++++++++++++++++"<<std::endl;
    RooHist* Pulls=RareFrame->pullHist(0,"RarePdf_Norm[Lambda_b0_DTF_MF]");
    TCanvas* RareCanvas=HandyFunctions::DecoratePlot(RareFrame,"DecoratedRareCanvas");
    RareCanvas->Print("RareCanvas.pdf");
    TCanvas * PullCanvas=new TCanvas("RarePullCanvas","RarePullCanvas",1200,1000);
    Pulls->Draw("AP");
    PullCanvas->SaveAs("RarePulls.pdf");
    TCanvas *RareNoPullCanvas = new TCanvas("RareFitCanvas","RareFitCanvas",1600,900);
    RareFrame->Draw();
    RareLegend->Draw();
    RareNoPullCanvas->Print("RareNoPullCanvasPrinted.eps");


    //_______________________________Plot Rare2 Canvas_____________________________________________________________
    RooPlot* Rare2Frame=LbMass.frame(Bins(25),Range(5200.0,6000.),Title("#Lambda_{b} -> p K (#eta' -> #pi #pi #eta);M(#Lambda_{b})"));
    if(blind) {
        double Rare2sidebandsN= Rare2Data->sumEntries("1","R2LSB,R2USB");
        Rare2Data->plotOn(Rare2Frame,CutRange("R2LSB,R2USB"));
        Rare2Pdf.plotOn(Rare2Frame,Range("R2LSB,R2USB"),Normalization(Rare2sidebandsN,RooAbsReal::NumEvent));
    } else {
        AllData->plotOn(Rare2Frame,Cut("Channel==Channel::Rare2"));
        SimPdf.plotOn(Rare2Frame,Slice(Channel,"Rare2"),Components("Rare2BkgPdf"),LineColor(kGreen),LineStyle(kDashed),ProjWData(Channel,*AllData));
        SimPdf.plotOn(Rare2Frame,Slice(Channel,"Rare2"),Components("Rare2SignalPdf"),LineColor(kRed),LineStyle(kDashed),ProjWData(Channel,*AllData));
        SimPdf.plotOn(Rare2Frame,Slice(Channel,"Rare2"),ProjWData(Channel,*AllData));
    }
    TCanvas* NoPullRare2= new TCanvas("NoPullRare2","NoPullRare2",1800,1000);
    Rare2Frame->Draw();
    NoPullRare2->SaveAs("PiPiEtaFit.eps");
    TCanvas* Rare2Canvas=HandyFunctions::DecoratePlot(Rare2Frame,"DecoratedRare2Canvas");
    Rare2Canvas->SaveAs("Rare2Canvas.pdf");

    if(blind) {
        RooArgSet NotBlind(CCEtamean,CCSignalYield,DataMCRatio,CCNoEtaBkgYield,CCTrueEtaBkgYield,CCMean,RareBkgYield,Rare2BkgYield,RarePkPhiYield);
        cout << "Fit complete" << endl;
        cout << "covQual:" << SimResult->covQual() << endl;
        cout << "EDM:" << SimResult->edm() << endl;
        cout << "FCN at min:" << SimResult->minNll() << endl;
        NotBlind.Print("s");
    }


    TFile* DataFitResults= new TFile("DataFitResults.root","RECREATE");
    RareNoPullCanvas->Write();
    CCBCanvas->Write();
    CCEtaCanvas->Write();
    RareCanvas->Write();
    Rare2Canvas->Write();
    SimResult->Write("DataFitResult");
    DataFitResults->Close();

    RooWorkspace* Wkspc= new RooWorkspace("w","workspace");
    Wkspc->import(SimPdf);
    //  Wkspc->writeToFile("BigFitWorkspace.root");
    Wkspc->writeToFile("TestBigFitWorkspace.root");

    for(auto Var : FreeParameters) {
        Var->setConstant();
    }

    RooStats::SPlot* sDataMass;
    if(sweight) {
        sDataMass = new RooStats::SPlot("sData","An SPlot",*RareData,&RarePdf,RooArgList(RarePkPhiYield,RareYield,RareBkgYield));
        std::cout<<" Check SWeights: "<<std::endl;
        std::cout<<" BkgYield= "<<RareBkgYield.getVal()<<std::endl;
        std::cout<<" Bkg yield from sweights = "<<sDataMass->GetYieldFromSWeight("RareBkgYield")<<std::endl;
    }




}
Пример #6
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();

}
Пример #7
0
bool fitCharmoniaMassModel( RooWorkspace& myws,            // Local Workspace
                            const RooWorkspace& inputWorkspace,  // Workspace with all the input RooDatasets
                            struct KinCuts& cut,           // Variable containing all kinematic cuts
                            map<string, string>&  parIni,  // Variable containing all initial parameters
                            struct InputOpt& opt,          // Variable with run information (kept for legacy purpose)
                            string outputDir,              // Path to output directory
                            // Select the type of datasets to fit
                            string DSTAG,                  // Specifies the type of datasets: i.e, DATA, MCJPSINP, ...
                            bool isPbPb      = false,      // isPbPb = false for pp, true for PbPb
                            bool importDS    = true,       // Select if the dataset is imported in the local workspace
                            // Select the type of object to fit
                            bool incJpsi     = true,       // Includes Jpsi model
                            bool incPsi2S    = true,       // Includes Psi(2S) model
                            bool incBkg      = true,       // Includes Background model
                            // Select the fitting options
                            bool doFit       = true,       // Flag to indicate if we want to perform the fit
                            bool cutCtau     = false,      // Apply prompt ctau cuts
                            bool doConstrFit   = false,    // Do constrained fit
                            bool doSimulFit  = false,      // Do simultaneous fit
                            bool wantPureSMC = false,      // Flag to indicate if we want to fit pure signal MC
                            const char* applyCorr ="",     // Flag to indicate if we want corrected dataset and which correction
                            uint loadFitResult = false,    // Load previous fit results
                            string inputFitDir = "",       // Location of the fit results
                            int  numCores    = 2,          // Number of cores used for fitting
                            // Select the drawing options
                            bool setLogScale = true,       // Draw plot with log scale
                            bool incSS       = false,      // Include Same Sign data
                            bool zoomPsi     = false,      // Zoom Psi(2S) peak on extra pad
                            double  binWidth = 0.05,       // Bin width used for plotting
                            bool getMeanPT   = false       // Compute the mean PT (NEED TO FIX)
                            )  
{

  if (DSTAG.find("_")!=std::string::npos) DSTAG.erase(DSTAG.find("_"));

  // Check if input dataset is MC
  bool isMC = false;
  if (DSTAG.find("MC")!=std::string::npos) {
    if (incJpsi && incPsi2S) { 
      cout << "[ERROR] We can only fit one type of signal using MC" << endl; return false; 
    }
    isMC = true;
  }
  wantPureSMC = (isMC && wantPureSMC);
  bool cutSideBand = (incBkg && (!incPsi2S && !incJpsi));
  bool applyWeight_Corr = ( strcmp(applyCorr,"") );
  
  // Define the mass range
  setMassCutParameters(cut, incJpsi, incPsi2S, isMC);
  parIni["invMassNorm"] = Form("RooFormulaVar::%s('( -1.0 + 2.0*( @0 - @1 )/( @2 - @1) )', {%s, mMin[%.6f], mMax[%.6f]})", "invMassNorm", "invMass", cut.dMuon.M.Min, cut.dMuon.M.Max );
  // Apply the ctau cuts to reject non-prompt charmonia
  if (cutCtau) { setCtauCuts(cut, isPbPb); }
  
  string COLL = (isPbPb ? "PbPb" : "PP" );
  string plotLabelPbPb,  plotLabelPP;

  if (doSimulFit || !isPbPb) {
    // Set models based on initial parameters
    struct OniaModel model;
    if (!setMassModel(model, parIni, false, incJpsi, incPsi2S, incBkg)) { return false; }

    // Import the local datasets
    double numEntries = 1000000;
    string label = ((DSTAG.find("PP")!=std::string::npos) ? DSTAG.c_str() : Form("%s_%s", DSTAG.c_str(), "PP"));
    if (wantPureSMC) label += "_NoBkg";
    if (applyWeight_Corr) label += Form("_%s",applyCorr);
    string dsName = Form("dOS_%s", label.c_str());
    if (importDS) {
      if ( !(myws.data(dsName.c_str())) ) {
        int importID = importDataset(myws, inputWorkspace, cut, label, cutSideBand);
        if (importID<0) { return false; }
        else if (importID==0) { doFit = false; }
      }
      numEntries = myws.data(dsName.c_str())->sumEntries(); if (numEntries<=0) { doFit = false; }
    }
    else if (doFit && !(myws.data(dsName.c_str()))) { cout << "[ERROR] No local dataset was found to perform the fit!" << endl; return false; }
    if (myws.data(dsName.c_str())) numEntries = myws.data(dsName.c_str())->sumEntries();

    // Set global parameters
    setMassGlobalParameterRange(myws, parIni, cut, incJpsi, incPsi2S, incBkg, wantPureSMC);

    // Build the Fit Model
    if (!buildCharmoniaMassModel(myws, model.PP, parIni, false, doConstrFit, doSimulFit, incBkg, incJpsi, incPsi2S, numEntries))  { return false; }

    // Define plot names
    if (incJpsi)  { plotLabelPP += Form("_Jpsi_%s", parIni["Model_Jpsi_PP"].c_str());   } 
    if (incPsi2S) { plotLabelPP += Form("_Psi2S_%s", parIni["Model_Psi2S_PP"].c_str()); }
    if (incBkg)   { plotLabelPP += Form("_Bkg_%s", parIni["Model_Bkg_PP"].c_str());     }
    if (wantPureSMC) plotLabelPP +="_NoBkg";
    if (applyWeight_Corr) plotLabelPP +=Form("_%s",applyCorr);
  }

  if (doSimulFit || isPbPb) {
    // Set models based on initial parameters
    struct OniaModel model;
    if (!setMassModel(model, parIni, true, incJpsi, incPsi2S, incBkg)) { return false; }

    // Import the local datasets
    double numEntries = 1000000;
    string label = ((DSTAG.find("PbPb")!=std::string::npos) ? DSTAG.c_str() : Form("%s_%s", DSTAG.c_str(), "PbPb"));
    if (wantPureSMC) label += "_NoBkg";
    if (applyWeight_Corr) label += Form("_%s",applyCorr);
    string dsName = Form("dOS_%s", label.c_str());
    if (importDS) {
      if ( !(myws.data(dsName.c_str())) ) {
        int importID = importDataset(myws, inputWorkspace, cut, label, cutSideBand);
        if (importID<0) { return false; }
        else if (importID==0) { doFit = false; }
      }
      numEntries = myws.data(dsName.c_str())->sumEntries(); if (numEntries<=0) { doFit = false; }
    }
    else if (doFit && !(myws.data(dsName.c_str()))) { cout << "[ERROR] No local dataset was found to perform the fit!" << endl; return false; }
    if (myws.data(dsName.c_str())) numEntries = myws.data(dsName.c_str())->sumEntries();
      
    // Set global parameters
    setMassGlobalParameterRange(myws, parIni, cut, incJpsi, incPsi2S, incBkg, wantPureSMC);

    // Build the Fit Model
    if (!buildCharmoniaMassModel(myws, model.PbPb, parIni, true, doConstrFit, doSimulFit, incBkg, incJpsi, incPsi2S, numEntries))  { return false; }

    // Define plot names
    if (incJpsi)  { plotLabelPbPb += Form("_Jpsi_%s", parIni["Model_Jpsi_PbPb"].c_str());   } 
    if (incPsi2S) { plotLabelPbPb += Form("_Psi2S_%s", parIni["Model_Psi2S_PbPb"].c_str()); }
    if (incBkg)   { plotLabelPbPb += Form("_Bkg_%s", parIni["Model_Bkg_PbPb"].c_str());     }
    if (wantPureSMC) plotLabelPbPb += "_NoBkg";
    if (applyWeight_Corr) plotLabelPbPb += Form("_%s",applyCorr);
  }

  if (doSimulFit) {
    // Create the combided datasets
    RooCategory* sample = new RooCategory("sample","sample"); sample->defineType("PbPb"); sample->defineType("PP");
    RooDataSet*  combData = new RooDataSet("combData","combined data", *myws.var("invMass"), Index(*sample),
                                           Import("PbPb", *((RooDataSet*)myws.data("dOS_DATA_PbPb"))),
                                           Import("PP",   *((RooDataSet*)myws.data("dOS_DATA_PP")))
                                           );
    myws.import(*sample);

    // Create the combided models
    RooSimultaneous* simPdf = new RooSimultaneous("simPdf", "simultaneous pdf", *sample);
    simPdf->addPdf(*myws.pdf("pdfMASS_Tot_PbPb"), "PbPb"); simPdf->addPdf(*myws.pdf("pdfMASS_Tot_PP"), "PP");
    myws.import(*simPdf);

    // check if we have already done this fit. If yes, do nothing and return true.
    string FileName = "";
    setMassFileName(FileName, (inputFitDir=="" ? outputDir : inputFitDir), DSTAG, (plotLabelPP + plotLabelPbPb), cut, isPbPb, cutSideBand, doSimulFit);
    if (gSystem->AccessPathName(FileName.c_str()) && inputFitDir!="") {
      cout << "[WARNING] User Input File : " << FileName << " was not found!" << endl;
      if (loadFitResult) return false;
      setMassFileName(FileName, outputDir, DSTAG, (plotLabelPP + plotLabelPbPb), cut, isPbPb, cutSideBand, doSimulFit);
    }
    bool found =  true; bool skipFit = !doFit;
    RooArgSet *newpars = myws.pdf("simPdf")->getParameters(*(myws.var("invMass")));
    myws.saveSnapshot("simPdf_parIni", *newpars, kTRUE);
    found = found && isFitAlreadyFound(newpars, FileName, "simPdf");
    if (loadFitResult) {
      if ( loadPreviousFitResult(myws, FileName, DSTAG, false, (!isMC && !cutSideBand && loadFitResult==1), loadFitResult==1) ) { skipFit = true; } else { skipFit = false; }
      if ( loadPreviousFitResult(myws, FileName, DSTAG, true, (!isMC && !cutSideBand && loadFitResult==1), loadFitResult==1)  ) { skipFit = true; } else { skipFit = false; }
      if (skipFit) { cout << "[INFO] This simultaneous mass fit was already done, so I'll load the fit results." << endl; }
      myws.saveSnapshot("simPdf_parLoad", *newpars, kTRUE);
    } else if (found) {
      cout << "[INFO] This simultaneous mass fit was already done, so I'll just go to the next one." << endl;
      return true;
    }

    // Do the simultaneous fit
    if (skipFit==false) {
      RooFitResult* fitResult = simPdf->fitTo(*combData, Offset(kTRUE), Extended(kTRUE), NumCPU(numCores), Range("MassWindow"), Save()); //, Minimizer("Minuit2","Migrad")
      fitResult->Print("v");
      myws.import(*fitResult, "fitResult_simPdf"); 
      // Create the output files
      int nBins = min(int( round((cut.dMuon.M.Max - cut.dMuon.M.Min)/binWidth) ), 1000);
      drawMassPlot(myws, outputDir, opt, cut, parIni, plotLabelPP, DSTAG, false, incJpsi, incPsi2S, incBkg, cutCtau, doSimulFit, false, setLogScale, incSS, zoomPsi, nBins, getMeanPT);
      drawMassPlot(myws, outputDir, opt, cut, parIni, plotLabelPbPb, DSTAG, true, incJpsi, incPsi2S, incBkg, cutCtau, doSimulFit, false, setLogScale, incSS, zoomPsi, nBins, getMeanPT);
      // Save the results
      string FileName = ""; setMassFileName(FileName, outputDir, DSTAG, (plotLabelPP + plotLabelPbPb), cut, isPbPb, cutSideBand, doSimulFit);
      myws.saveSnapshot("simPdf_parFit", *newpars, kTRUE);
      saveWorkSpace(myws, Form("%smass%s/%s/result", outputDir.c_str(), (cutSideBand?"SB":""), DSTAG.c_str()), FileName);
      // Delete the objects used during the simultaneous fit
      delete sample; delete combData; delete simPdf;
    }
  }
  else {
    // Define pdf and plot names
    string pdfName = Form("pdfMASS_Tot_%s", COLL.c_str());
    string plotLabel = (isPbPb ? plotLabelPbPb : plotLabelPP);

    // Import the local datasets
    string label = ((DSTAG.find(COLL.c_str())!=std::string::npos) ? DSTAG.c_str() : Form("%s_%s", DSTAG.c_str(), COLL.c_str()));
    if (wantPureSMC) label += "_NoBkg";
    if (applyWeight_Corr) label += Form("_%s",applyCorr);
    string dsName = Form("dOS_%s", label.c_str());
      
    // check if we have already done this fit. If yes, do nothing and return true.
    string FileName = "";
    setMassFileName(FileName, (inputFitDir=="" ? outputDir : inputFitDir), DSTAG, plotLabel, cut, isPbPb, cutSideBand);
    if (gSystem->AccessPathName(FileName.c_str()) && inputFitDir!="") {
      cout << "[WARNING] User Input File : " << FileName << " was not found!" << endl;
      if (loadFitResult) return false;
      setMassFileName(FileName, outputDir, DSTAG, plotLabel, cut, isPbPb, cutSideBand);
    }
    bool found =  true; bool skipFit = !doFit;
    RooArgSet *newpars = myws.pdf(pdfName.c_str())->getParameters(*(myws.var("invMass")));
    found = found && isFitAlreadyFound(newpars, FileName, pdfName.c_str());
    if (loadFitResult) {
      if ( loadPreviousFitResult(myws, FileName, DSTAG, isPbPb, (!isMC && !cutSideBand && loadFitResult==1), loadFitResult==1) ) { skipFit = true; } else { skipFit = false; } 
      if (skipFit) { cout << "[INFO] This mass fit was already done, so I'll load the fit results." << endl; }
      myws.saveSnapshot(Form("%s_parLoad", pdfName.c_str()), *newpars, kTRUE);
    } else if (found) {
      cout << "[INFO] This mass fit was already done, so I'll just go to the next one." << endl;
      return true;
    }

    // Fit the Datasets
    if (skipFit==false) {
      bool isWeighted = myws.data(dsName.c_str())->isWeighted();
      RooFitResult* fitResult(0x0);
      if (doConstrFit)
      {
        cout << "[INFO] Performing constrained fit" << endl;
        
        if (isPbPb) {
          cout << "[INFO] Constrained variables: alpha, n, ratio of sigmas" << endl;
          fitResult = myws.pdf(pdfName.c_str())->fitTo(*myws.data(dsName.c_str()), Extended(kTRUE), SumW2Error(isWeighted), Range(cutSideBand ? parIni["BkgMassRange_FULL_Label"].c_str() : "MassWindow"), ExternalConstraints(RooArgSet(*(myws.pdf("sigmaAlphaConstr")),*(myws.pdf("sigmaNConstr")),*(myws.pdf("sigmaRSigmaConstr")))), NumCPU(numCores), Save());
        }
        else {
          cout << "[INFO] Constrained variables: alpha, n, ratio of sigmas" << endl;
          fitResult = myws.pdf(pdfName.c_str())->fitTo(*myws.data(dsName.c_str()), Extended(kTRUE), SumW2Error(isWeighted), Range(cutSideBand ? parIni["BkgMassRange_FULL_Label"].c_str() : "MassWindow"), ExternalConstraints(RooArgSet(*(myws.pdf("sigmaAlphaConstr")),*(myws.pdf("sigmaNConstr")))), NumCPU(numCores), Save());
        }
      }
      else
      {
       fitResult = myws.pdf(pdfName.c_str())->fitTo(*myws.data(dsName.c_str()), Extended(kTRUE), SumW2Error(isWeighted), Range(cutSideBand ? parIni["BkgMassRange_FULL_Label"].c_str() : "MassWindow"), NumCPU(numCores), Save());
      }
      fitResult->Print("v"); 
      myws.import(*fitResult, Form("fitResult_%s", pdfName.c_str())); 
      // Create the output files
      int nBins = min(int( round((cut.dMuon.M.Max - cut.dMuon.M.Min)/binWidth) ), 1000);
      drawMassPlot(myws, outputDir, opt, cut, parIni, plotLabel, DSTAG, isPbPb, incJpsi, incPsi2S, incBkg, cutCtau, doSimulFit, wantPureSMC, setLogScale, incSS, zoomPsi, nBins, getMeanPT);
      // Save the results
      string FileName = ""; setMassFileName(FileName, outputDir, DSTAG, plotLabel, cut, isPbPb, cutSideBand);
      myws.saveSnapshot(Form("%s_parFit", pdfName.c_str()), *newpars, kTRUE);
      saveWorkSpace(myws, Form("%smass%s/%s/result", outputDir.c_str(), (cutSideBand?"SB":""), DSTAG.c_str()), FileName);
    }
  }

  return true;
};
Пример #8
0
void buildModel(RooWorkspace& w,int chooseFitParams, int chooseSample,int whatBin, int signalModel, int bkgdModel, int doRap, int doPt,int doCent,int useRef,float muonPtMin, int fixFSR){
// C r e a t e   m o d e l  
  int nt=100000;
  // cout << "you're building a model for the quarkonium resonance of mass = "<< M1S <<" GeV/c^{2},"endl;
  RooRealVar *nsig1f   = new RooRealVar("N_{ #varUpsilon(1S)}","nsig1S",0,nt*10);
  RooRealVar* mass       = new RooRealVar("invariantMass","#mu#mu mass",mass_l,mass_h,"GeV/c^{2}");

  RooRealVar *nsig2f = NULL;
  RooRealVar *nsig3f = NULL;

 switch (chooseFitParams)
    {
    case 0://use the YIELDs of 2S and 3S as free parameters
      //minor modif here: 3S forced positive.
      nsig2f  = new RooRealVar("N_{ #varUpsilon(2S)}","nsig2S",   nt*0.25,-200,10*nt);
      nsig3f  = new RooRealVar("N_{ #varUpsilon(3S)}","nsig3S",   nt*0.25,-200,10*nt);
      cout << "you're fitting to extract yields, "<< endl;
      break;
    default:
      cout<<"Make a pick from chooseFitParams!!!"<<endl;
      break;
    }  

      RooRealVar  *mean = new RooRealVar("m_{ #varUpsilon(1S)}","#Upsilon mean",M1S,M1S-0.2,M1S+0.2);
      RooConstVar *rat2 = new RooConstVar("rat2", "rat2", M2S/M1S);
      RooConstVar *rat3 = new RooConstVar("rat3", "rat3", M3S/M1S);
      // scale mean and resolution by mass ratio
      RooFormulaVar *mean1S = new RooFormulaVar("mean1S","@0",RooArgList(*mean));
      RooFormulaVar *mean2S = new RooFormulaVar("mean2S","@0*@1", RooArgList(*mean,*rat2));
      RooFormulaVar *mean3S = new RooFormulaVar("mean3S","@0*@1", RooArgList(*mean,*rat3));

      // //detector resolution ?? where is this coming from?
      RooRealVar    *sigma1  = new RooRealVar("#sigma_{CB1}","#sigma_{CB1}",sigma_min[whatBin],sigma_max[whatBin]); // 
      RooFormulaVar *sigma1S = new RooFormulaVar("sigma1S","@0"   ,RooArgList(*sigma1));
      RooFormulaVar *sigma2S = new RooFormulaVar("sigma2S","@0*@1",RooArgList(*sigma1,*rat2));
      RooFormulaVar *sigma3S = new RooFormulaVar("sigma3S","@0*@1",RooArgList(*sigma1,*rat3));
      RooRealVar *alpha  = new RooRealVar("#alpha_{CB}","tail shift",alpha_min[whatBin],alpha_max[whatBin]);    // MC 5tev 1S pol2 
      RooRealVar *npow   = new RooRealVar("n_{CB}","power order",npow_min[whatBin],npow_max[whatBin]);    // MC 5tev 1S pol2 
      RooRealVar *sigmaFraction = new RooRealVar("sigmaFraction","Sigma Fraction",0.,1.);
      // scale the sigmaGaus with sigma1S*scale=sigmaGaus now.
      RooRealVar    *scaleWidth = new RooRealVar("#sigma_{CB2}/#sigma_{CB1}","scaleWidth",1.,2.5);
      RooFormulaVar *sigmaGaus = new RooFormulaVar("sigmaGaus","@0*@1", RooArgList(*sigma1,*scaleWidth));
      RooFormulaVar *sigmaGaus2 = new RooFormulaVar("sigmaGaus","@0*@1*@2", RooArgList(*sigma1,*scaleWidth,*rat2));
      RooFormulaVar *sigmaGaus3 = new RooFormulaVar("sigmaGaus","@0*@1*@2", RooArgList(*sigma1,*scaleWidth,*rat3));
      RooGaussian* gauss1 = new RooGaussian("gaus1s","gaus1s",
      					    *nsig1f,
      					    *mass,    //mean
      					    *sigmaGaus); //sigma
      // RooGaussian* gauss1b = new RooGaussian("gaus1sb","gaus1sb",
      // 					     *nsig1f,
      // 					     *m,    //mean
      // 					     *sigma1); //sigma
      switch(signalModel){    
      case 1: //crystal boule
	RooCBShape  *sig1S   = new RooCBShape ("cb1S_1", "FSR cb 1s",
					       *mass,*mean1S,*sigma1,*alpha,*npow);

	RooCBShape  *sig2S   = new RooCBShape ("cb2S_1", "FSR cb 1s",
					       *mass,*mean2S,*sigma2S,*alpha,*npow);
	RooCBShape  *sig3S   = new RooCBShape ("cb3S_1", "FSR cb 1s",
					       *mass,*mean3S,*sigma3S,*alpha,*npow);
	cout << "you're fitting each signal peak with a Crystal Ball function"<< endl;
	break;
      case 2: //Gaussein
	RooAbsPdf      *sig1S  = new RooGaussian ("g1", "gaus 1s",
						  *mass,*mean1S,*sigma1);
	cout << "you're fitting 1 signal peak with a Gaussian function"<< endl;
	break;
      case 3: //Gaussein + crystal boule
	RooCBShape  *cb1S_1    = new RooCBShape ("cb1S_1", "FSR cb 1s",
						 *mass,*mean1S,*sigma1,*alpha,*npow);
	RooAddPdf      *sig1S  = new RooAddPdf ("cbg", "cbgaus 1s",
						RooArgList(*gauss1,*cb1S_1),*sigmaFraction);
	cout << "you're fitting 1 signal peak with a sum of a Gaussian and a Crystal Ball function"<< endl;
	break;
      case 4: //crystal boules
	RooCBShape  *cb1S_1    = new RooCBShape ("cb1S_1", "FSR cb 1s",
						 *mass,*mean1S,*sigma1,*alpha,*npow);
       
	RooCBShape  *cb1S_2    = new RooCBShape ("cb1S_2", "FSR cb 1s",
						 *mass,*mean1S,*sigmaGaus,*alpha,*npow);
	RooAddPdf      *sig1S  = new RooAddPdf  ("cbcb","1S mass pdf",
						 RooArgList(*cb1S_1,*cb1S_2),*sigmaFraction);
	// /// Upsilon 2S
	RooCBShape  *cb2S_1    = new RooCBShape ("cb2S_1", "FSR cb 2s", 
						 *mass,*mean2S,*sigma2S,*alpha,*npow); 
	RooCBShape  *cb2S_2    = new RooCBShape ("cb2S_2", "FSR cb 2s", 
						 *mass,*mean2S,*sigmaGaus2,*alpha,*npow); 
	RooAddPdf      *sig2S  = new RooAddPdf  ("sig2S","2S mass pdf",
						 RooArgList(*cb2S_1,*cb2S_2),*sigmaFraction);
      
	// /// Upsilon 3S
	RooCBShape  *cb3S_1    = new RooCBShape ("cb3S_1", "FSR cb 3s", 
						 *mass,*mean3S,*sigma3S,*alpha,*npow); 
	RooCBShape  *cb3S_2    = new RooCBShape ("cb3S_2", "FSR cb 3s", 
						 *mass,*mean3S,*sigmaGaus3,*alpha,*npow); 
	RooAddPdf      *sig3S  = new RooAddPdf  ("sig3S","3S mass pdf",
						 RooArgList(*cb3S_1,*cb3S_2),*sigmaFraction); // = cb3S1*sigmaFrac + cb3S2*(1-sigmaFrac)
	cout << "you're fitting each signal peak with a Double Crystal Ball function"<< endl;
	break;
      
      case 5: //deux Gausseins
	RooAddPdf      *sig1S  = new RooAddPdf ("cb1S_1", "cbgaus 1s",
						RooArgList(*gauss1,*gauss1b),*sigmaFraction);
	cout << "you're fitting each signal peak with a Double Gaussian function"<< endl;
	break;
      }
      // bkg Chebychev
      RooRealVar *nbkgd   = new RooRealVar("n_{Bkgd}","nbkgd",0,nt);
      RooRealVar *bkg_a1  = new RooRealVar("a1_bkg", "bkg_{a1}", 0, -5, 5);
      RooRealVar *bkg_a2  = new RooRealVar("a2_Bkg", "bkg_{a2}", 0, -2, 2);
      RooRealVar *bkg_a3  = new RooRealVar("a3_Bkg", "bkg_{a3}", 0, -0.9, 2);

      //  likesign
      RooRealVar *nLikesignbkgd = new RooRealVar("NLikesignBkg","nlikesignbkgd",nt*0.75,0,10*nt);
      // *************************************************** bkgModel
      
      RooRealVar turnOn("turnOn","turnOn", turnOn_minCent[whatBin],turnOn_maxCent[whatBin]);
      RooRealVar width("width","width",width_minCent[whatBin],width_maxCent[whatBin]);// MB 2.63
      RooRealVar decay("decay","decay",decay_minCent[whatBin],decay_maxCent[whatBin]);// MB: 3.39
      if (doRap && !doPt)
	{
	  RooRealVar turnOn("turnOn","turnOn", turnOn_minRap[whatBin],turnOn_maxRap[whatBin]);
	  RooRealVar width("width","width",width_minRap[whatBin],width_maxRap[whatBin]);// MB 2.63
	  RooRealVar decay("decay","decay",decay_minRap[whatBin],decay_maxRap[whatBin]);// MB: 3.39
	}
      if (doPt && !doRap)
	{
	  RooRealVar turnOn("turnOn","turnOn", turnOn_minPt[whatBin],turnOn_maxPt[whatBin]);
	  RooRealVar width("width","width",width_minPt[whatBin],width_maxPt[whatBin]);// MB 2.63
	  RooRealVar decay("decay","decay",decay_minPt[whatBin],decay_maxPt[whatBin]);// MB: 3.39
	}
      
  
      width.setConstant(false);
      decay.setConstant(false);
      turnOn.setConstant(false);
 
  switch (useRef)// no reference
    {
    case 0: // forcing sigma and fsr to be left free.
      fixSigma1 = 0;
      fixFSR    = 0;
      break;
    case 1:
      //using data-driven estimates
      int dataRef=1;
      cout<<"You're using the debug mode based on data parameters. So you must not take this result as the central one."<<endl;
      break;
    case 2:
      
      cout << "doCent="<<doCent << endl;
      //using MC-driven estimates
      int dataRef=2;
      if(doCent)   //MB values, assumed to be the same with all centralities...
     	{
	  if(muonPtMin <4){
	    gROOT->LoadMacro("dataTable_loose.h");
	  }else if(muonPtMin > 3.5){
	    gROOT->LoadMacro("dataTable_tight.h");
	  }
	  npow->setVal(npow_rapBins[8]);
	  alpha->setVal(alpha_rapBins[8]);
	  sigma1->setVal(sigma1_rapBins[8]);
	  scaleWidth->setVal(scale_rapBins[8]);
	  sigmaFraction->setVal(pdFrac_rapBins[8]);
	  cout<< whatBin << endl;
	}
      if(doRap && !doPt)
	{
	  if(muonPtMin <4){
	    gROOT->LoadMacro("dataTable_loose.h");
	  }else if(muonPtMin > 3.5){
	    gROOT->LoadMacro("dataTable_tight.h");
	  }
	  npow->setVal(npow_rapBins[whatBin]);
	  alpha->setVal(alpha_rapBins[whatBin]);
	  sigma1->setVal(sigma1_rapBins[whatBin]);
	  scaleWidth->setVal(scale_rapBins[whatBin]);
	  sigmaFraction->setVal(pdFrac_rapBins[whatBin]);
	  cout<< whatBin << endl;
	}
      if(doPt && !doRap)
	{
	  // cout << "we're here" << endl;
	  if(muonPtMin <4){
	    gROOT->LoadMacro("dataTable_loose.h");
	  }else if(muonPtMin > 3.5){
	    gROOT->LoadMacro("dataTable_tight.h");
	  }
	  cout << " ok ... " <<endl;
	  npow->setVal(npow_ptBins[whatBin]);
	  alpha->setVal(alpha_ptBins[whatBin]);
	  sigma1->setVal(sigma1_ptBins[whatBin]);
	  scaleWidth->setVal(scale_ptBins[whatBin]);
	  sigmaFraction->setVal(pdFrac_ptBins[whatBin]);
	}
     
      cout<<"You're using MC parameters. So you may use this result as the central one, according to the LLR test outcome."<<endl;
      break;
    default: break;
    }

  //
  cout << "npow tried=" << npow->getVal(); 
  if(fixFSR==3 || fixFSR==1) cout << "   constant!" << endl;   else cout << "   floating!" << endl;
  cout << "alpha tried=" << alpha->getVal(); 
  if(fixFSR==2 || fixFSR==1) cout << "   constant!" << endl;   else cout << "   floating!" << endl;
  cout << "sigma1 tried=" << sigma1->getVal(); 
  if(fixFSR==4 || fixFSR==1) cout << "   constant!" << endl;   else cout << "   floating!" << endl;
  cout << "scale tried=" << scaleWidth->getVal(); 
  if(fixFSR==4 || fixFSR==1) cout << "   constant!" << endl;   else cout << "   floating!" << endl;
  cout << "normalisation tried=" << sigmaFraction->getVal();
  if(fixFSR==5 || fixFSR==1) cout << "   constant!" << endl;   else cout << "   floating!" << endl;
  
  switch (fixFSR) // 0: free;  1: both fixed 2: alpha fixed 3: npow fixed
    {      
    case 0:// all free
      alpha->setConstant(false);
      npow->setConstant(false);
      sigma1->setConstant(false);
      scaleWidth->setConstant(false);
      sigmaFraction->setConstant(false);
      break;
    case 1:// all fixed
      alpha->setConstant(true);
      npow ->setConstant(true);
      sigma1->setConstant(true);
      scaleWidth->setConstant(true);
      sigmaFraction->setConstant(true);
      break;
    case 2: // release alpha
      alpha->setConstant(false);
      npow ->setConstant(true);
      sigma1->setConstant(true);
      scaleWidth->setConstant(true);
      sigmaFraction->setConstant(true);
      break;
    case 3:// npow released
      alpha->setConstant(true);
      npow->setConstant(false);
      sigma1->setConstant(true);
      scaleWidth->setConstant(true);
      sigmaFraction->setConstant(true);
      break;
    case 4:// width+ sF +scale released
      alpha->setConstant(true);
      npow->setConstant(true);
      sigma1->setConstant(false);
      scaleWidth->setConstant(true);
      sigmaFraction->setConstant(true);
      break;
    case 5:// scale +sF
      alpha->setConstant(true);
      npow->setConstant(true);
      sigma1->setConstant(true);
      scaleWidth->setConstant(false);
      sigmaFraction->setConstant(true);
      break;
   case 6:// scale +sF
      alpha->setConstant(true);
      npow->setConstant(true);
      sigma1->setConstant(true);
      scaleWidth->setConstant(true);
      sigmaFraction->setConstant(false);
      break;
    default:
      cout<<"Donno this choice! Pick somehting for FSR parameters that I know"<<endl;
      break;
    }
   //thisPdf: form of the bkg pdf
  //pdf_combinedbkgd; // total bkg pdf. usually form*normalization  (so that you can do extended ML fits)
  switch (bkgdModel) 
    {
    case 1 :  //(erf*exp ) to fit the SS, then fix the shape and fit OS, in case of constrain option
      bkg_a3->setConstant(true);
      RooGenericPdf *ErrPdf = new  RooGenericPdf("ErrPdf","ErrPdf",
						 "exp(-@0/decay)*(TMath::Erf((@0-turnOn)/width)+1)",
					       RooArgList(*mass,turnOn,width,decay));
      RooFitResult* fit_1st  = ErrPdf->fitTo(*likesignData,Save(),NumCPU(4)) ; // likesign data
      if (doTrkRot) fit_1st  = thisPdf->fitTo(*TrkRotData,Save(),NumCPU(4)) ;
      
      if (doConstrainFit) 
	{ // allow parameters to vary within cenral value from above fit + their sigma
	  turnOn_constr = new RooGaussian("turnOn_constr","turnOn_constr",
					  turnOn,
					  RooConst(turnOn.getVal()),
					  RooConst(turnOn.getError()));
	  width_constr   = new RooGaussian("width_constr","width_constr",
					   width,					   RooConst(width.getVal()),
					   RooConst(width.getError()));
	  decay_constr    = new RooGaussian("decay_constr","decay_constr",
					    decay,
					    RooConst(decay.getVal()),
					    RooConst(decay.getError()));
	}
      else 
	{
	  turnOn.setConstant(kTRUE);
	  width.setConstant(kTRUE);
	  decay.setConstant(kTRUE);
	}
      RooRealVar *fLS =new RooRealVar("R_{SS/OS}","Empiric LS/SS ratio",0.,1.);
      RooAbsPdf  *ChebPdf  = new RooChebychev("ChebPdf","ChebPdf",
					      *mass, RooArgList(*bkg_a1,*bkg_a2));
      RooAbsPdf  *pdf_combinedbkgd   = new RooAddPdf ("bkgPdf","total combined background pdf",
						      RooArgList(*ErrPdf,*ChebPdf),
						      RooArgList(*fLS));
      
      break;
    case 2 : //us eRooKeysPdf to smooth the SS, then fit OS with pol+keys
      bkg_a3->setConstant(true);
      RooRealVar *fLS =new RooRealVar("R_{SS/OS}","Empiric LS/SS ratio",0.,1.);
      RooKeysPdf *KeysPdf        = new RooKeysPdf("KeysPdf","KeysPdf",*mass,*likesignData,
						  RooKeysPdf::MirrorBoth, 1.4);
      RooAbsPdf  *ChebPdf  = new RooChebychev("ChebPdf","ChebPdf",
					      *mass, RooArgList(*bkg_a1,*bkg_a2));
      if (doTrkRot) thisPdf     = new RooKeysPdf("thisPdf","thisPdf",*mass,*TrkRotData,
						 RooKeysPdf::MirrorBoth, 1.4);
      RooAbsPdf  *pdf_combinedbkgd   = new RooAddPdf ("bkgPdf","total combined background pdf",
						      RooArgList(*KeysPdf,*ChebPdf),
						      RooArgList(*fLS));
      break;
    case 3 : //use error function to fit the OS directly
      bkg_a3->setConstant(true);
      RooAbsPdf *pdf_combinedbkgd            = new  RooGenericPdf("bkgPdf","bkgPdf",
								  "exp(-@0/decay)*(TMath::Erf((@0-turnOn)/width)+1)",
								  RooArgList(*mass,turnOn,width,decay));
      break;
      
    case 4 : //use pol 2+ErfExp to fit the OS directly

      RooRealVar *fPol   = new RooRealVar("F_{pol}","fraction of polynomial distribution",0.0,1);
      RooAbsPdf  *ChebPdf  = new RooChebychev("ChebPdf","ChebPdf",
					      *mass, RooArgList(*bkg_a1,*bkg_a2));
      RooGenericPdf *ErrPdf     = new  RooGenericPdf("ErrPdf","ErrPdf",
						     "exp(-@0/decay)*(TMath::Erf((@0-turnOn)/width)+1)",
						     RooArgList(*mass,turnOn,width,decay));
      RooAbsPdf  *pdf_combinedbkgd   = new RooAddPdf ("bkgPdf","total combined background pdf",
						      RooArgList(*ChebPdf,*ErrPdf),
						      RooArgList(*fPol));

      break;
    case 5 : //use ( error function + polynomial 1) to fit the OS directly
      
      bkg_a3->setConstant(true);
      bkg_a2->setConstant(true);
      RooRealVar *fPol   = new RooRealVar("F_{pol}","fraction of polynomial distribution",0.0,1);
      RooAbsPdf  *ChebPdf  = new RooChebychev("ChebPdf","ChebPdf",
					      *mass, RooArgList(*bkg_a1,*bkg_a2,*bkg_a3));
      RooGenericPdf *ErrPdf     = new  RooGenericPdf("ErrPdf","ErrPdf",
						     "exp(-@0/decay)*(TMath::Erf((@0-turnOn)/width)+1)",
						   RooArgList(*mass,turnOn,width,decay));
      RooAbsPdf  *pdf_combinedbkgd   = new RooAddPdf ("bkgPdf","total combined background pdf",
						      RooArgList(*ChebPdf,*ErrPdf),
						      RooArgList(*fPol));
      break;
    case 6: // NOT WORKING
      RooRealVar *fPol   = new RooRealVar("F_{pol}","fraction of polynomial distribution",0.0,1);
      RooAbsPdf  *ChebPdf  = new RooChebychev("ChebPdf","ChebPdf",
					      *mass, RooArgList(*bkg_a1,*bkg_a2));
      RooGenericPdf *ExpPdf     = new  RooGenericPdf("ExpPdf","ExpPdf",
						     "exp(-@0/decay)",
						     RooArgList(*mass,decay));
      RooAbsPdf  *pdf_combinedbkgd  =  new RooAddPdf ("bkgPdf","total combined background pdf",
						      RooArgList(*ChebPdf,*ExpPdf),
						      RooArgList(*fPol));
      break;
    default :
      cout<<"Donno what you are talking about! Pick another fit option!"<<endl;
      break;
    }
  
  //###### the nominal fit with default pdf 
 
  // RooAbsPdf  *pdf; // nominal PDF
  if(chooseSample==8)
   {     
     // bkg_a1->setVal(0);// can be turned on at convenience
     // bkg_a1->setConstant();
     // bkg_a2->setVal(0);
     // bkg_a2->setConstant();
     // bkg_a3->setVal(0);
     // bkg_a3->setConstant();
     // RooAbsPdf  *pdf             = new RooAddPdf ("pdf","total p.d.f.",
     // 						  RooArgList(*sig1S,*pdf_combinedbkgd),
     // 						  RooArgList(*nsig1f,*nbkgd));
        RooAbsPdf  *pdf             = new RooAddPdf ("pdf","total p.d.f.",*sig1S,*nsig1f);
   } else if(chooseSample!=8)
    {
      // can remove the double crystal ball in pbpb: just commenting out and copying an appropriate version
      RooAbsPdf  *pdf             = new RooAddPdf ("pdf","total p.d.f.",
						   RooArgList(*sig1S,*sig2S,*sig3S,*pdf_combinedbkgd),
						   RooArgList(*nsig1f,*nsig2f,*nsig3f,*nbkgd));
      //  nsig3f->setVal(0); nsig3f->setConstant();
      
    }
  w.import(*pdf);
  w.Print();
}
void fitEfficiency(float thres,
		   float mLow=45, float mHigh=70,
		   TString cutdef="pt_HLT>=20", TString cut_choice="HLT",
		   TString dirIn="/data_CMS/cms/ndaci/ndaci_2012/HTauTau/TriggerStudy/SingleMu/MuMu/Run2012A_PRV1/Pairs/", 
		   TString dirResults="/home//llr/cms/ndaci/SKWork/macro/HTauTau/results/TriggerStudies/MuMu/Run2012A_PRV1/",
		   TString lumi="200 pb", int nCPU=4, 
		   int color1=kBlack, int style1=kFullCircle, int color2=kRed, int style2=kOpenSquare,
		   TString fileIn="*.root", TString image="eff_HLT_MuTau")
{
  // STYLE //
  gROOT->Reset();
  loadPresentationStyle();  
  gROOT->ForceStyle();

  // OUTPUT //
  TString name_image = dirResults+"/"+image;
  ofstream fichier(name_image+".txt", ios::out);

  // BINNING //
  const int nbinsEB = 14;
  Double_t binsEB[nbinsEB] = {10., 14., 18., 20., 22., 26., 30., 40., 50., 60., 70., 80, 90, 100};
  RooBinning binningEB = RooBinning(nbinsEB-1, binsEB, "binningEB");

  const int nbinsEE = 14;
  Double_t binsEE[nbinsEE] = {10., 14., 18., 20., 22., 26., 30., 40., 50., 60., 70., 80, 90, 100};
  RooBinning binningEE = RooBinning(nbinsEE-1, binsEE, "binningEE");

  // EB/EE eta cuts //
  TString etacutEB="eta>-1.479 && eta<1.479", etacutEE="eta<=-1.479 || eta>=1.479";
  TString cutdefEB, cutdefEE;
  if(cutdef=="") { 
    cutdefEB=etacutEB;
    cutdefEE=etacutEE;
  }
  else {
    cutdefEB=cutdef+" && "+etacutEB ;
    cutdefEB=cutdef+" && "+etacutEE ;
  }

  // INPUT DATA //
  TChain* treeTnP = new TChain("treeTnP");
  treeTnP->Add(dirIn+"/"+fileIn);

  RooRealVar xaxis("pt","P_{T} [GeV]",0,150) ;
  RooRealVar mass("mass","mass",mLow,mHigh) ;// consider only this mass range when importing data                                      
  RooRealVar eta("eta","eta",-3., 3) ;
  RooRealVar weight("weight","weight",-1,1000) ;
  RooRealVar pt_HLT_tag("pt_HLT_tag","P_{T} [GeV]",0,150) ;
  RooRealVar pt_HLT_tag_sanity("pt_HLT_tag_sanity","P_{T} [GeV]",0,150) ;
  RooRealVar pt_L3("pt_L3","P_{T} [GeV]",0,150) ;
  RooRealVar pt_L25("pt_L25","P_{T} [GeV]",0,150) ;
  RooRealVar pt_L2("pt_L2","P_{T} [GeV]",0,150) ;
  RooRealVar et_L1jet("et_L1_jet","P_{T} [GeV]",0,150) ;
  RooRealVar et_L1tau("et_L1_tau","P_{T} [GeV]",0,150) ;

  // DEFINE EFFICIENCY CUT //
  RooCategory cutHLT("match","") ;
  cutHLT.defineType("accept",1) ;
  cutHLT.defineType("reject",0) ;

  RooCategory cutL1("L1match","") ;
  cutL1.defineType("accept",1) ;
  cutL1.defineType("reject",0) ;

  RooCategory cutL1L2("L1L2match","") ;
  cutL1L2.defineType("accept",1) ;
  cutL1L2.defineType("reject",0) ;

  RooCategory cutL1L2L25("L1L2L25match","") ;
  cutL1L2L25.defineType("accept",1) ;
  cutL1L2L25.defineType("reject",0) ;

  RooCategory cutL1L2L25L3("L1L2L25L3match","") ;
  cutL1L2L25L3.defineType("accept",1) ;
  cutL1L2L25L3.defineType("reject",0) ;

  RooCategory *cut;
  if(cut_choice=="HLT") cut = &cutHLT;
  if(cut_choice=="L1") cut = &cutL1;
  if(cut_choice=="L1L2") cut = &cutL1L2;
  if(cut_choice=="L1L2L25") cut = &cutL1L2L25;
  if(cut_choice=="L1L2L25L3") cut = &cutL1L2L25L3;

  RooDataSet dataSetEB("data","data from tree",
		       RooArgSet(xaxis, *cut,
				 pt_HLT_tag, pt_L3, pt_L25, pt_L2,
				 mass, weight, eta),
		       WeightVar(weight), Import(*treeTnP), Cut(cutdefEB) );
  
  RooDataSet dataSetEE("data","data from tree",
		       RooArgSet(xaxis, *cut,
				 pt_HLT_tag, pt_L3, pt_L25, pt_L2,
				 mass, weight, eta),
		       WeightVar(weight), Import(*treeTnP), Cut(cutdefEE) );
  
  dataSetEB.Print();
  dataSetEE.Print();

  // PLOT //
  RooPlot* frame = xaxis.frame(Bins(18000),Title("Fitted efficiency")) ;
  dataSetEB.plotOn(frame, Binning(binningEB), Efficiency(*cut), MarkerColor(color1), LineColor(color1), MarkerStyle(style1) );
  dataSetEE.plotOn(frame, Binning(binningEE), Efficiency(*cut), MarkerColor(color2), LineColor(color2), MarkerStyle(style2) );

  // PARAMETRES ROOFIT CRYSTAL BALL //
  RooRealVar norm("norm","N",0.95,0.6,1);
  RooRealVar alpha("alpha","#alpha",0.2,0.01,8);
  RooRealVar n("n","n",2,1.1,35);
  RooRealVar mean("mean","mean",10,5,30);
  mean.setVal(thres);
  RooRealVar sigma("sigma","#sigma",0.23,0.01,5);
  RooRealVar pedestal("pedestal","pedestal",0.01,0,0.4);

  FuncCB cb_EB("cb_EB","Fit function EB (cb)",xaxis,mean,sigma,alpha,n,norm) ;
  FuncCB cb_EE("cb_EE","Fit function EE (cb)",xaxis,mean,sigma,alpha,n,norm) ;
  
  RooEfficiency eff_EB("eff_EB","efficiency EB", cb_EB, *cut, "accept");
  RooEfficiency eff_EE("eff_EE","efficiency EE", cb_EE, *cut, "accept");  

  // FIT //
  double fit_cuts_min = thres-1.5 ;
  double fit_cuts_max = 150;
  xaxis.setRange("interesting",fit_cuts_min,fit_cuts_max);

  fichier << "Fit characteristics :" << endl
	  << "Threshold : "          << thres << endl 
	  << "Fit Range : ["         << fit_cuts_min << "," << fit_cuts_max << "]" << endl 
	  << endl << endl;

  RooFitResult* roofitres_EB = new RooFitResult("roofitres_EB","roofitres_EB");
  RooFitResult* roofitres_EE = new RooFitResult("roofitres_EE","roofitres_EE");

  // Fit #1 //
  roofitres_EB = eff_EB.fitTo(dataSetEB,ConditionalObservables(xaxis),Range("interesting"),Minos(kTRUE),Warnings(kFALSE),NumCPU(nCPU),Save(kTRUE),SumW2Error(kTRUE));
  cb_EB.plotOn(frame,LineColor(color1),LineWidth(2));

  fichier << "<----------------- EB ----------------->" << endl
	  << "double res_mean="  << mean.getVal()   << "; "
	  << "double res_sigma=" << sigma.getVal()  << "; "
          << "double res_alpha=" << alpha.getVal()  << "; "
          << "double res_n="     << n.getVal()      << "; "
          << "double res_norm="  << norm.getVal()   << "; "
	  << endl
	  << "double err_mean="  << mean.getError()  << "; "
	  << "double err_sigma=" << sigma.getError() << "; "
          << "double err_alpha=" << alpha.getError() << "; "
          << "double err_n="     << n.getError()     << "; "
          << "double err_norm="  << norm.getErrorLo()<< "; "
	  << endl;

  // Fit #2 //
  roofitres_EE = eff_EE.fitTo(dataSetEE,ConditionalObservables(xaxis),Range("interesting"),Minos(kTRUE),Warnings(kFALSE),NumCPU(nCPU),Save(kTRUE),SumW2Error(kTRUE));
  cb_EE.plotOn(frame,LineColor(color2),LineWidth(2));

  fichier << "<----------------- EE ----------------->" << endl
	  << "double res_mean="  << mean.getVal()   << "; "
	  << "double res_sigma=" << sigma.getVal()  << "; "
          << "double res_alpha=" << alpha.getVal()  << "; "
          << "double res_n="     << n.getVal()      << "; "
          << "double res_norm="  << norm.getVal()   << "; "
	  << endl
	  << "double err_mean="  << mean.getError()  << "; "
	  << "double err_sigma=" << sigma.getError() << "; "
          << "double err_alpha=" << alpha.getError() << "; "
          << "double err_n="     << n.getError()     << "; "
          << "double err_norm="  << norm.getErrorLo()<< "; "
	  << endl;


  ////////////////////////////  DRAWING PLOTS AND LEGENDS /////////////////////////////////
  TCanvas* ca = new TCanvas("ca","Trigger Efficiency") ;

  ca->SetGridx();
  ca->SetGridy();
  ca->cd();
  
  //gPad->SetLogx();
  gPad->SetObjectStat(1);

  frame->GetYaxis()->SetRangeUser(0,1.05);
  frame->GetXaxis()->SetRangeUser(1,150.);
  frame->GetYaxis()->SetTitle("Efficiency");
  frame->GetXaxis()->SetTitle("E_{T} [GeV]");
  frame->Draw() ;

  TH1F *SCeta_EB = new TH1F("SCeta_EB","SCeta_EB",50,-2.5,2.5);
  TH1F *SCeta_EE = new TH1F("SCeta_EE","SCeta_EE",50,-2.5,2.5);

  SCeta_EB->SetLineColor(color1) ;
  SCeta_EB->SetMarkerColor(color1);
  SCeta_EB->SetMarkerStyle(style1);

  SCeta_EE->SetLineColor(color2) ;
  SCeta_EE->SetMarkerColor(color2);
  SCeta_EE->SetMarkerStyle(style2);

  TLegend *leg = new TLegend(0.40, 0.14, 0.63, 0.34, NULL, "brNDC");
  leg->SetLineColor(1);
  leg->SetTextColor(1);
  leg->SetTextFont(42);
  leg->SetTextSize(0.0244755);
  leg->SetShadowColor(kWhite);
  leg->SetFillColor(kWhite);  
  leg->AddEntry("NULL","e #tau electrons efficiency","h");
  //    entry->SetLineColor(1);
  //    entry->SetLineStyle(1);
  //    entry->SetLineWidth(1);
  //    entry->SetMarkerColor(1);
  //    entry->SetMarkerStyle(21);
  //    entry->SetMarkerSize(1);
  //    entry->SetTextFont(62);
  leg->AddEntry(SCeta_EB,"Barrel","p");
  leg->AddEntry(SCeta_EE,"Endcaps","p");
  leg->Draw(); 
  
  ostringstream ossi("");
  ossi << thres;
  TString tossi = ossi.str();

  leg = new TLegend(0.40, 0.30, 0.50, 0.50, NULL, "brNDC");
  leg->SetBorderSize(0);
  leg->SetTextFont(62);
  leg->SetTextSize(0.0297203);
  leg->SetLineColor(0);
  leg->SetLineStyle(1);
  leg->SetLineWidth(1);
  leg->SetFillColor(0);
  leg->SetFillStyle(0);
  leg->AddEntry("NULL","CMS Preliminary 2012 pp  #sqrt{s}=8 TeV","h");
  leg->AddEntry("NULL","#int L dt = "+lumi+"^{-1}","h");
  leg->AddEntry("NULL","Threshold : "+tossi+" GeV","h");
  leg->Draw();
  
  ca->Print(name_image+".C","C");
  ca->Print(name_image+".cxx","cxx");
  ca->Print(name_image+".png","png");
  ca->Print(name_image+".gif","gif");
  ca->Print(name_image+".pdf","pdf");
  ca->Print(name_image+".ps","ps");

  /////////////////////////////
  // SAVE THE ROO FIT RESULT //
  /////////////////////////////

  RooWorkspace *w = new RooWorkspace("workspace","workspace") ;

  w->import(dataSetEB);
  w->import(dataSetEE);
  
  w->import(*roofitres_EB,"roofitres_EB");
  w->import(*roofitres_EE,"roofitres_EE");

  cout << "CREATES WORKSPACE : " << endl;
  w->Print();
  
  w->writeToFile(name_image+"_fitres.root") ;
  //gDirectory->Add(w) ;

  // DELETE POINTERS
  // int a=0;
//   cin >> a;
//   delete treeTnP; delete cut; delete frame; delete roofitres_EB; delete roofitres_EE; delete ca; delete SCeta_EB; delete SCeta_EE; delete leg; delete w;

}