Пример #1
0
void THSRooFit::PlotDataModel(){
  //Function to plot the data and fitted model for each variable

  TCanvas *canvas=0;
  if(!fCanvases){fCanvases=new TList();fCanvases->SetOwner();fCanvases->SetName(TString("RFPlots")+GetName());}
  //Loop over variables
  for(Int_t idr=0;idr<fVariables.getSize();idr++){
    cout<<"Plotting versus "<<fVariables[idr].GetName()<<endl;
    RooRealVar* var=fWS->var(fVariables[idr].GetName());//get variable
    
    if(!var) continue;
    fCanvases->Add(canvas=new TCanvas(TString(GetName())+fVariables[idr].GetName()+Form("%d",fFiti),TString(GetName())+fVariables[idr].GetName()));//create new canvas for drawing on
    RooPlot* frame = var->frame(); // RooFit frame 
    fData->plotOn(frame, DataError(RooAbsData::SumW2) ) ; //plot the data
    fModel->plotOn(frame,LineColor(kRed)) ; //model = signal + back fit result 
    //Get the chi2
    fChi2=frame->chiSquare();
    cout<<fFiti<<" THSRooFit::PlotDataModel() chi2 = "<<fChi2<<endl;
    fModel->paramOn(frame,
		    Layout(0.1, 0.4, 0.9),
		    Format("NEU",AutoPrecision(2)),
		    ShowConstants()); //show fit parameters
    frame->SetTitle(TString("Fit components for ")+fVariables[idr].GetName());
    //Loop over components
    for(Int_t ic=0;ic<fPDFs.getSize();ic++)
      fModel->plotOn(frame,Components(fPDFs[ic]),LineStyle(kDashed),LineColor(ic%8+1)) ; //just the back fit result  
    frame->Draw() ;
    canvas->Modified();
    canvas->Update();
  }
}
Пример #2
0
void scigraphics::drawer::eraseRectangle( const wrectangle& Rectangle )
{
  color Color = color::White;
  brushStyle BrushStyle( Color );
  lineStyle LineStyle( Color );

  setBrushStyle( BrushStyle );
  setLineStyle( LineStyle );
  drawRectangle( Rectangle ); 
}
Пример #3
0
void MainWindow::on_pushButton_4_clicked()
{
    Serie *seria = new Serie;
    seria->setAxisId(ui->eOs->text().toInt());
    seria->setLength(20);
    seria->setLineStyle(LineStyle(2, kolor));
    ch.addSerie(seria);
    ch.drawBackground();
    ui->label->setPixmap(ch.draw());
}
Пример #4
0
// Search for specified LineStyle data in list
LineStyle EditState::lineStyleData(QString name, const List<EditStateData>& dataList, bool& result)
{
	result = true;
	for (EditStateData* data = dataList.first(); data != NULL; data = data->next)
	{
		if (data->type() != EditStateData::LineStyleData) continue;
		if (data->isName(name)) return data->asLineStyle();
	}
	printf("Internal Error: No stored LineStyle data exists named '%s'.\n", qPrintable(name));
	result = false;
	return LineStyle();
}
Пример #5
0
void THSRooFit::PlotModel(TString varName,TString pdfName){
  TCanvas *canvas=0;
  if(!fCanvases){fCanvases=new TList();fCanvases->SetOwner();}
  RooRealVar* var=fWS->var(varName);//get variable
  fCanvases->Add(canvas=new TCanvas(TString(GetName())+varName+pdfName,TString(GetName())+varName+pdfName));//create new canvas for drawing on
  RooPlot* frame = var->frame(); // RooFit frame
  fWS->pdf(pdfName)->plotOn(frame,LineStyle(kSolid), LineColor(kRed));
  frame->SetTitle(pdfName+TString(" versus ")+varName);
  frame->Draw();
  canvas->Modified();
  canvas->Update();

}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
RimAnnotationLineAppearance::RimAnnotationLineAppearance()
{
    CAF_PDM_InitObject("AnnotationLineAppearance", ":/WellCollection.png", "", "");

    CAF_PDM_InitField(&m_lineFieldsHidden, "LineFieldsHidden", false, "Line Fields Hidden", "", "", "");
    CAF_PDM_InitField(&m_color,     "Color",     cvf::Color3f(cvf::Color3f::BLACK),  "Line Color", "", "", "");
    CAF_PDM_InitField(&m_thickness, "Thickness", 2,                                  "Line Thickness", "", "", "");

    // Stippling not yet supported. Needs new stuff in VizFwk
    CAF_PDM_InitField(&m_style,     "Style",     LineStyle(),                        "Style", "", "", "");
    m_style.uiCapability()->setUiHidden(true);
    m_style.xmlCapability()->disableIO();

    m_lineFieldsHidden.uiCapability()->setUiHidden(true);
}
Пример #7
0
   void GenericModel::plotOn(RooPlot* frame)
   {
      // Add the pseudo-PDF to the RooPlot
      // We plot:
      //    - the fit result with a 1-sigma error band;
      //    - each of the individual kernel PDF's

      //plot fit result with 1-sigma error band
      fModelPseudoPDF->plotOn(frame, VisualizeError(*fLastFit, 1), FillColor(kMagenta));
      fModelPseudoPDF->plotOn(frame);
      //plot individual kernels
      for (int i = 0; i < GetNumberOfDataSets(); i++) {
         fModelPseudoPDF->plotOn(frame, Components(*GetKernel(i)), LineStyle(kDashed), LineColor(kBlue + 4 * i));
      }
   }
Пример #8
0
/**
 * @brief Axis::Axis
 *tworzy oś z paramterami:
 *czcionka: Verdana, 8pt
 *wartość minimalna: 0
 *wartość maksymalna: 100
 *odstęp wartości: 10
 *podziałka: 4px skierowana do wewnątrz
 *pusta etykieta
 *bez jednostki
 *domyślny styl linii
 */
Axis::Axis()
{
    //this->autoscale = false;
    this->font = QFont("verdana", 8);
    this->geometry = Geometry();
    this->max = 100;
    this->min = 0;
    this->tick = 10;
    this->tickDirection = inside;
    this->tickSize = 4;
    this->position = left;
    this->showUnit = false;
    this->label = Label();
    this->unit = "";
    this->lineStyle = LineStyle();
}
Пример #9
0
void scigraphics::painter::drawRectangleF( const frectangle &Rect, const brushStyle &BrushStyle )
{
  lineStyle LineStyle( BrushStyle.getColor() );
  LineStyle.setWidth(0);
  drawRectangleF( Rect, BrushStyle, LineStyle );
}
Пример #10
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();
};
Пример #11
0
int main(int argc, const char** argv){
  bool ReDoCuts=false;

  TCut TwelveCut = "gamma_CL>0.1&&BDT_response>0.36&&piplus_MC12TuneV3_ProbNNpi>0.2&&piminus_MC12TuneV3_ProbNNpi>0.2&&Kaon_MC12TuneV3_ProbNNk>0.4";
  TCut ElevenCut = "gamma_CL>0.1&&BDT_response>0.30&&piplus_MC12TuneV3_ProbNNpi>0.2&&piminus_MC12TuneV3_ProbNNpi>0.2&&Kaon_MC12TuneV3_ProbNNk>0.4";
  
  //______________________________MAKE CUT FILE FOR 2012___________________________________
  if(ReDoCuts){
    DataFile MCA(std::getenv("BUKETAPMCBDTRESPROOT"),MC,Twel,MagAll,buketap,"BDTApplied_SampleA");
    
    DataFile MCB(std::getenv("BUKETAPMCBDTRESPROOT"),MC,Twel,MagAll,buketap,"BDTApplied_SampleB");
  
    TreeReader* MC12Reader=  new TreeReader("DecayTree");
    MC12Reader->AddFile(MCA);
    MC12Reader->AddFile(MCB);
    MC12Reader->Initialize();
    
    TFile* MC12Cut = new TFile("CutFile12.root","RECREATE");
    TTree* MC12CutTree=MC12Reader->CopyTree(TwelveCut,-1,"DecayTree");
    TRandom3 *MCRand = new TRandom3(224);
    TH1I * MCnCands12= new TH1I("MCnCands12","MCnCands12",10,0,10);
    TTree*MC12SingleTree=HandyFunctions::GetSingleTree(MCRand,MC12CutTree,MCnCands12,NULL);
    MCnCands12->Write();
    MC12SingleTree->Write();
    MC12Cut->Close();
    
    //________________________________MAKE CUT FILE FOR 2011__________________________________
    
    DataFile MC11A(std::getenv("BUKETAPMCBDTRESPROOT"),MC,Elev,MagAll,buketap,"BDTApplied_SampleA");
    
    DataFile MC11B(std::getenv("BUKETAPMCBDTRESPROOT"),MC,Elev,MagAll,buketap,"BDTApplied_SampleB");
    
    TreeReader* MC11Reader= new TreeReader("DecayTree");
    MC11Reader->AddFile(MC11A);
    MC11Reader->AddFile(MC11B);
    MC11Reader->Initialize();
    
    TFile* MC11Cut = new TFile("CutFile11.root","RECREATE");
    TTree* MC11CutTree=MC11Reader->CopyTree(ElevenCut,-1,"DecayTree");

    TH1I * MCnCands11= new TH1I("MCnCands11","MCnCands11",10,0,10);
    TTree* MC11SingleTree=HandyFunctions::GetSingleTree(MCRand,MC11CutTree,MCnCands11,NULL);
    MCnCands11->Write();
    MC11SingleTree->Write();
    MC11Cut->Close();
  //_________________________________ MAKE FLAT TREES  ____________________________________
  
    TFile* MC12Input = new TFile("CutFile12.root");
    TTree* MC12InputTree=(TTree*)MC12Input->Get("DecayTree");
    Float_t MCEta_Mass12[20]; MC12InputTree->SetBranchAddress("Bu_DTFNoFix_eta_prime_M",&MCEta_Mass12);
    Int_t isSingle12; MC12InputTree->SetBranchAddress("isSingle",&isSingle12);
    
    TFile* MC12FlatOut = new TFile("MCMinimalFile12.root","RECREATE");
    TTree* MC12FlatTree = MC12InputTree->CloneTree(0);
    Double_t MCBu_DTFNoFix_eta_Prime_MF12; MC12FlatTree->Branch("Bu_DTFNoFix_eta_prime_MF",&MCBu_DTFNoFix_eta_Prime_MF12,"Bu_DTFNoFix_eta_prime_MF/D");
    
    Long64_t Entries12=MC12InputTree->GetEntries();
    
    for(int i=0;i<Entries12;++i){
      MC12InputTree->GetEntry(i);
      if(isSingle12==0)continue;
      MCBu_DTFNoFix_eta_Prime_MF12=MCEta_Mass12[0];
      MC12FlatTree->Fill();
    }
    
    MC12FlatTree->Write();
    MC12FlatOut->Close();
    
    TFile* MC11Input = new TFile("CutFile11.root");
    TTree* MC11InputTree=(TTree*)MC11Input->Get("DecayTree");
    Float_t MCEta_Mass11[20]; MC11InputTree->SetBranchAddress("Bu_DTFNoFix_eta_prime_M",&MCEta_Mass11);
    Int_t isSingle11; MC11InputTree->SetBranchAddress("isSingle",&isSingle11);
    
    TFile* MC11FlatOut = new TFile("MCMinimalFile11.root","RECREATE");
    TTree* MC11FlatTree = MC11InputTree->CloneTree(0);
    Double_t MCBu_DTFNoFix_eta_Prime_MF11; MC11FlatTree->Branch("Bu_DTFNoFix_eta_prime_MF",&MCBu_DTFNoFix_eta_Prime_MF11,"Bu_DTFNoFix_eta_prime_MF/D");
    
    Long64_t Entries11=MC11InputTree->GetEntries();
    
    for(int i=0;i<Entries11;++i){
      MC11InputTree->GetEntry(i);
      if(isSingle11==0)continue;
      MCBu_DTFNoFix_eta_Prime_MF11=MCEta_Mass11[0];
      MC11FlatTree->Fill();
    }
    
    MC11FlatTree->Write();
    MC11FlatOut->Close();
  }
  
  //_____________________________________________LOAD ROODATASETS___________________________________

  TFile* MCFlatInput12= new TFile("MCMinimalFile12.root");
  TTree* MCFlatInputTree12=(TTree*)MCFlatInput12->Get("DecayTree");

  TFile* MCFlatInput11= new TFile("MCMinimalFile11.root");
  TTree* MCFlatInputTree11=(TTree*)MCFlatInput11->Get("DecayTree");

  RooRealVar MCBMass("Bu_DTF_MF","Bu_DTF_MF",5000.0,5600.0);
  RooRealVar MCEtaMass("eta_prime_MM","eta_prime_MM",700.0,1200.0);
  RooRealVar BDT_response("BDT_response","BDT_response",-1.0,1.0);
  RooRealVar gamma_CL("gamma_CL","gamma_CL",0.1,1.0);
  RooArgSet Args(MCBMass,MCEtaMass,BDT_response,gamma_CL);

  RooDataSet* MCData12 = new RooDataSet("MCData12","MCData12",Args,Import(*MCFlatInputTree12));
  
  std::cout <<" Data File 12 Loaded"<<std::endl;
  
  RooDataSet* MCData11 = new RooDataSet("MCData11","MCData11",Args,Import(*MCFlatInputTree11));

  std::cout<<" Data File 11 loaded"<<std::endl;

  RooDataSet* MCDataAll= new RooDataSet("MCDataAll","MCDataAll",Args);

  MCDataAll->append(*MCData12);
  MCDataAll->append(*MCData11);
  
  RooPlot* massFrame = MCBMass.frame(Title("Data Import Check"),Bins(50));
  MCDataAll->plotOn(massFrame);
  
  RooPlot *BDTFrame = BDT_response.frame(Title("BDT Cut Check"),Bins(50));
  MCDataAll->plotOn(BDTFrame);
  TCanvas C;
  C.Divide(2,1);
  C.cd(1);
  massFrame->Draw();
  C.cd(2);
  BDTFrame->Draw();
  C.SaveAs("ImportChecks.eps");

  //________________________________MAKE MCROODATACATEGORIES__________________________________

  RooDataSet* MCBData=(RooDataSet*)MCDataAll->reduce(RooArgSet(MCBMass));
  MCBData->Print("v");
  
  RooDataSet* MCEtaData=(RooDataSet*)MCDataAll->reduce(RooArgSet(MCEtaMass));
  MCEtaData->Print("v");

  RooCategory MCMassType("MCMassType","MCMassType") ;
  MCMassType.defineType("B") ;
  MCMassType.defineType("Eta") ;
  
  // Construct combined dataset in (x,sample)
  RooDataSet MCcombData("MCcombData","MC combined data",Args,Index(MCMassType),Import("B",*MCBData),Import("Eta",*MCEtaData));

  
  //=============================================== MC FIT MODEL===================================
  
  RooRealVar Mean("Mean","Mean",5279.29,5276.0,5284.00);
  RooRealVar Sigma("Sigma","Sigma",20.54,17.0,24.8);
  RooRealVar LAlpha("LAlpha","LAlpha",-1.064,-2.5,0.0);
  RooRealVar RAlpha("RAlpha","RAlpha",1.88,0.0,5.0);
  RooRealVar LN("LN","LN",13.0,0.0,40.0);
  RooRealVar RN("RN","RN",2.56,0.0,6.0);

  RooCBShape CBLeft("CBLeft","CBLeft",MCBMass,Mean,Sigma,LAlpha,LN);
  
  RooCBShape CBRight("CBRight","CBRight",MCBMass,Mean,Sigma,RAlpha,RN);

  RooRealVar FitFraction("FitFraction","FitFraction",0.5,0.0,1.0);
  RooAddPdf DCB("DCB","DCB",RooArgList(CBRight,CBLeft),FitFraction);

  RooRealVar SignalYield("SignalYield","SignalYield",4338.0,500.0,10000.0);
  //  RooExtendPdf ExtDCB("ExtDCB","ExtDCB",DCB,SignalYield);
  
  //==============================ETA DCB ++++++++++++++++++++++++++++++
  
  RooRealVar MCEtamean("MCEtamean","MCEtamean",958.0,955.0,960.0);
  RooRealVar MCEtasigma("MCEtasigma","MCEtasigma",9.16,8.0,14.0);
  RooRealVar EtaLAlpha("EtaLAlpha","EtaLAlpha",-1.45,-5.0,1.0);
  RooRealVar EtaRAlpha("EtaRAlpha","EtaRAlpha",1.76,0.0,4.0);
  RooRealVar EtaLN("EtaLN","EtaLN",0.1,0.0,20.0);
  RooRealVar EtaRN("EtaRN","EtaRN",0.1,0.0,20.0);

  RooCBShape EtaCBLeft("EtaCBLeft","EtaCBLeft",MCEtaMass,MCEtamean,MCEtasigma,EtaLAlpha,EtaLN);
  
  RooCBShape EtaCBRight("EtaCBRight","EtaCBRight",MCEtaMass,MCEtamean,MCEtasigma,EtaRAlpha,EtaRN);

  RooRealVar EtaFitFraction("EtaFitFraction","EtaFitFraction",0.22,0.1,1.0);
  RooAddPdf EtaDCB("EteaDCB","EtaDCB",RooArgList(EtaCBRight,EtaCBLeft),EtaFitFraction);

  RooProdPdf MCSignalPdf("MCSignalPdf","MCSignalPdf",RooArgSet(EtaDCB,DCB));
  
  RooExtendPdf ExtendedMCSignalPdf("ExtendedMCSignalPdf","ExtendedMCSignalPdf",MCSignalPdf,SignalYield);

  RooSimultaneous MCsimPdf("MCsimPdf","MC simultaneous pdf",MCMassType) ;
  //  MCsimPdf.addPdf(ExtDCB,"B");
  //  MCsimPdf.addPdf(ExtendedMCEtaDCB,"Eta"); 

  //============================== DO the MC FIT =======================================
  //MCsimPdf.fitTo(MCcombData,Extended(kTRUE),Minos(kTRUE));
  //ExtendedMCEtaDCB.fitTo(*MCEtaData,Extended(kTRUE),Minos(kTRUE));
  //ExtDCB.fitTo(*MCBData,Extended(
  ExtendedMCSignalPdf.fitTo(*MCDataAll,Extended(kTRUE),Minos(kTRUE));
  
  RooPlot* MCframe1 = MCBMass.frame(Range(5100.0,5500.0),Bins(50),Title("B mass projection"));
  MCDataAll->plotOn(MCframe1);
  ExtendedMCSignalPdf.plotOn(MCframe1);
  ExtendedMCSignalPdf.paramOn(MCframe1);
  
  RooPlot* MCframe2 = MCEtaMass.frame(Range(880.0,1020.0),Bins(50),Title("Eta mass projection")) ;
  MCDataAll->plotOn(MCframe2);
  ExtendedMCSignalPdf.plotOn(MCframe2);
  ExtendedMCSignalPdf.paramOn(MCframe2);
  
  TCanvas* MCc = new TCanvas("rf501_simultaneouspdf","rf403_simultaneouspdf",1200,1000) ;
  gPad->SetLeftMargin(0.15) ; MCframe1->GetYaxis()->SetTitleOffset(1.4) ; MCframe1->Draw() ;
  MCc->SaveAs("MCSimulCanvas.pdf");

  TCanvas* MCcEta = new TCanvas(" Eta Canvas","Eta Canvas",1200,1000);
  gPad->SetLeftMargin(0.15) ; MCframe2->GetYaxis()->SetTitleOffset(1.4) ; MCframe2->Draw() ;
  MCcEta->SaveAs("MCEtaCanvas.pdf");

  TFile* MCFits= new TFile("MCFitResult.root","RECREATE");
  //  TCanvas* DecMCB=HandyFunctions::DecoratePlot(MCframe1);
  //  TCanvas* DecMCEta=HandyFunctions::DecoratePlot(MCframe2);
  //DecMCEta->Write();
  //  DecMCB->Write();
  MCc->Write();
  MCcEta->Write();

  std::cout<<"MC Eta Chi2 = "<<MCframe2->chiSquare()<<std::endl;
  std::cout<<"MC B Chi2 = "<<MCframe1->chiSquare()<<std::endl;

  //___________________________________ CUT DOWN COLLISION DATA ______________________________
  if(ReDoCuts){
    DataFile TwelveA(std::getenv("BUKETAPDATABDTRESPROOT"),Data,Twel,MagAll,buketap,"BDTApplied_SampleA");

    DataFile TwelveB(std::getenv("BUKETAPDATABDTRESPROOT"),Data,Twel,MagAll,buketap,"BDTApplied_SampleB");
  
    DataFile ElevenA(std::getenv("BUKETAPDATABDTRESPROOT"),Data,Elev,MagAll,buketap,"BDTApplied_SampleA");

    DataFile ElevenB(std::getenv("BUKETAPDATABDTRESPROOT"),Data,Elev,MagAll,buketap,"BDTApplied_SampleB");		

    TRandom3* DataRand= new TRandom3(224);
    TH1I* DataNCand12= new TH1I("DataNCand12","DataNCand12",10,0,10);
    TH1I* DataNCand11= new TH1I("DataNCand11","DataNCand11",10,0,10);
    
    TreeReader* UncutDataReader12= new TreeReader("DecayTree");
    UncutDataReader12->AddFile(TwelveA);
    UncutDataReader12->AddFile(TwelveB);
    UncutDataReader12->Initialize();
    
    TFile* CutDataFile12 = new TFile("CutDataFile12.root","RECREATE");
    TTree* CutDataTree12 = UncutDataReader12->CopyTree(TwelveCut,-1,"DecayTree");
    TTree* SingleCutDataTree12=HandyFunctions::GetSingleTree(DataRand,CutDataTree12,DataNCand12,NULL);
    SingleCutDataTree12->Write();
    CutDataFile12->Close();
    
    TreeReader* UncutDataReader11= new TreeReader("DecayTree");
    UncutDataReader11->AddFile(ElevenB);
    UncutDataReader11->AddFile(ElevenA);
    UncutDataReader11->Initialize();
    
    TFile* CutDataFile11 = new TFile("CutDataFile11.root","RECREATE");
    TTree* CutDataTree11 = UncutDataReader11->CopyTree(ElevenCut,-1,"DecayTree");
    TTree* SingleCutDataTree11=HandyFunctions::GetSingleTree(DataRand,CutDataTree11,DataNCand11,NULL);
    SingleCutDataTree11->Write();
    CutDataFile11->Close();
  

    TFile* DataInput12 = new TFile("CutDataFile12.root");
    TTree* DataInputTree12=(TTree*)DataInput12->Get("DecayTree");
    DataInputTree12->SetBranchStatus("*",0);
    DataInputTree12->SetBranchStatus("Bu_DTF_MF",1);
    DataInputTree12->SetBranchStatus("Bu_DTFNoFix_eta_prime_M",1);
    DataInputTree12->SetBranchStatus("eta_prime_MM",1);
    DataInputTree12->SetBranchStatus("isSingle",1);
    Float_t Eta_Mass12[20]; DataInputTree12->SetBranchAddress("Bu_DTFNoFix_eta_prime_M",&Eta_Mass12);
    Int_t isSingle12; DataInputTree12->SetBranchAddress("isSingle",&isSingle12);
    
    TFile* MinimalDataFile12 = new TFile("MinimalDataFile12.root","RECREATE");
    TTree* MinimalDataTree12= DataInputTree12->CloneTree(0);
    Double_t Bu_DTFNoFix_eta_prime_MF12; MinimalDataTree12->Branch("Bu_DTFNoFix_eta_prime_MF",&Bu_DTFNoFix_eta_prime_MF12,"Bu_DTFNoFix_eta_prime_MF/D");
    
    Long64_t Entries12=DataInputTree12->GetEntries();
    
    for(int i=0;i<Entries12;++i){
      DataInputTree12->GetEntry(i);
      if(isSingle12==0)continue;
      Bu_DTFNoFix_eta_prime_MF12=Eta_Mass12[0];
      MinimalDataTree12->Fill();
    }
    
    MinimalDataTree12->Write();
    MinimalDataFile12->Close();
    
    TFile* DataInput11 = new TFile("CutDataFile11.root");
    TTree* DataInputTree11=(TTree*)DataInput11->Get("DecayTree");
    DataInputTree11->SetBranchStatus("*",0);
    DataInputTree11->SetBranchStatus("Bu_DTF_MF",1);
    DataInputTree11->SetBranchStatus("Bu_DTFNoFix_eta_prime_M",1);
    DataInputTree11->SetBranchStatus("eta_prime_MM",1);
    DataInputTree11->SetBranchStatus("isSingle",1);
    Float_t Eta_Mass11[20]; DataInputTree11->SetBranchAddress("Bu_DTFNoFix_eta_prime_M",&Eta_Mass11);
    Int_t isSingle11; DataInputTree11->SetBranchAddress("isSingle",&isSingle11);
    
    TFile* MinimalDataFile11 = new TFile("MinimalDataFile11.root","RECREATE");
    TTree* MinimalDataTree11= DataInputTree11->CloneTree(0);
    Double_t Bu_DTFNoFix_eta_prime_MF11; MinimalDataTree11->Branch("Bu_DTFNoFix_eta_prime_MF",&Bu_DTFNoFix_eta_prime_MF11,"Bu_DTFNoFix_eta_prime_MF/D");
    
    Long64_t Entries11=DataInputTree11->GetEntries();
    
    for(int i=0;i<Entries11;++i){
    DataInputTree11->GetEntry(i);
    if(isSingle11==0)continue;
    Bu_DTFNoFix_eta_prime_MF11=Eta_Mass11[0];
    MinimalDataTree11->Fill();
    }
    MinimalDataTree11->Write();
    MinimalDataFile11->Close();
  }

  //___________________________________ LOAD DATA TO ROODATASET____________________________________
  
  RooRealVar BMass("Bu_DTF_MF","Bu_DTF_MF",5000.0,5600.0);
  RooRealVar EtaMass("eta_prime_MM","eta_prime_MM",870.0,1050.0);
  RooArgSet MassArgs(BMass,EtaMass);

  TFile* Data12File = new TFile("MinimalDataFile12.root");
  TTree* DataTree12=(TTree*)Data12File->Get("DecayTree");

  RooDataSet* Data12 = new RooDataSet("Data12","Data12",MassArgs,Import(*DataTree12));

  TFile* Data11File = new TFile("MinimalDataFile11.root");
  TTree* DataTree11=(TTree*)Data11File->Get("DecayTree");

  RooDataSet* Data11 = new RooDataSet("Data11","Data11",MassArgs,Import(*DataTree11));
  
  RooDataSet* AllData = new RooDataSet("AllData","AllData",MassArgs);
  AllData->append(*Data12);
  AllData->append(*Data11);
  TCanvas ImportC;
  RooPlot* ImportCheck = BMass.frame(Title("ImportCheck"),Bins(50));
  AllData->plotOn(ImportCheck);
  ImportCheck->Draw();
  ImportC.SaveAs("Alldataimport.pdf");

  std::cout<<" Data Loaded, Total Entries = "<<AllData->numEntries()<<std::endl;

  AllData->Print("v");

  RooDataSet* BData=(RooDataSet*)AllData->reduce(RooArgSet(BMass));
  BData->Print("v");

  RooDataSet* EtaData=(RooDataSet*)AllData->reduce(RooArgSet(EtaMass));
  EtaData->Print("v");

  //___________________________________Fit to Eta_Prime in BMass Sidebands______________________

  RooDataSet* BSidebands=(RooDataSet*)AllData->reduce(Cut("(Bu_DTF_MF>5000.0&&Bu_DTF_MF<5179.0)||(Bu_DTF_MF>5379.0&&Bu_DTF_MF<5800.0)"));

  TCanvas BSidebandCanvas;
  RooPlot* BSidebandPlot = EtaMass.frame(Title("B sidebands"),Bins(30));
  BSidebands->plotOn(BSidebandPlot);
  BSidebandPlot->Draw();
  BSidebandCanvas.SaveAs("BSidebandDataCheck.pdf");

  
  RooRealVar BsbMean(" Mean","BsbMean",958.0,900.0,1020.0);
  RooRealVar BsbSigma(" Sigma","BsbSigma",19.8,10.0,40.8);
  RooRealVar BsbLAlpha(" Alpha","BsbLAlpha",-1.63,-10.0,0.0);
  //  RooRealVar BsbRAlpha("BsbRAlpha","BsbRAlpha",1.47,0.0,10.0);
  RooRealVar BsbLN(" N","BsbLN",0.1,0.0,20.0);
  //  RooRealVar BsbRN("BsbRN","BsbRN",0.1,0.0,20.0);

  RooCBShape BsbCBLeft("BsbCBLeft","BsbCBLeft",EtaMass,BsbMean,BsbSigma,BsbLAlpha,BsbLN);
  
  //  RooCBShape BsbCBRight("BsbCBRight","BsbCBRight",EtaMass,BsbMean,BsbSigma,BsbRAlpha,BsbRN);

  //  RooRealVar BsbFitFraction("BsbFitFraction","BsbFitFraction",0.5,0.0,1.0);
  //  RooAddPdf BsbDCB("BsbDCB","BsbDCB",RooArgList(BsbCBRight,BsbCBLeft),BsbFitFraction);
  RooRealVar Bsbslope("Bsbslope","Bsbslope",0.5,0.0,1.0);
  RooRealVar BsbP2("BsbP2","BsbP2",-0.5,-1.0,0.0);
  RooChebychev BsbLinear("BsbLinear","BsbLinear",EtaMass,RooArgSet(Bsbslope,BsbP2));

  RooRealVar BsbFitFraction("BsbFitFraction","BsbFitFraction",0.2,0.0,1.0);

  RooAddPdf BsbBackground("BsbBackground","BsbBackground",RooArgList(BsbLinear,BsbCBLeft),BsbFitFraction);
  
  RooRealVar BsbYield(" Yield","BsbYield",500.0,0.0,1000.0);
  RooExtendPdf BsbExtDCB("BsbExtDCB","BsbExtDCB",BsbCBLeft,BsbYield);

  BsbExtDCB.fitTo(*BSidebands,Extended(kTRUE),Minos(kTRUE));
  TCanvas BSBFitCanvas;
  RooPlot* BSBFitPlot = EtaMass.frame(Title("Eta fit in B Sidebands"),Bins(30));
  BSidebands->plotOn(BSBFitPlot);
  BsbExtDCB.plotOn(BSBFitPlot);
  BsbExtDCB.paramOn(BSBFitPlot);
  BSBFitPlot->Draw();
  BSBFitCanvas.SaveAs("BSidebandFit.pdf");
  TFile * SidebandFitFile= new TFile("SidebandFit.root","RECREATE");
  BSBFitCanvas.Write();
  SidebandFitFile->Close();
  
  //___________________________________DO THE 2D FIT TO DATA___________________________________


  const double PDGBMass= 5279.26;
  BMass.setRange("SignalWindow",PDGBMass-(3*Sigma.getVal()),PDGBMass+(3*Sigma.getVal()));
  RooRealVar DSignalYield("DSignalYield","DSignalYield",4000.0,0.0,10000.0);

  //================================= B MASS SIGNAL PDF==============================
  RooRealVar DMean("Mean","DMean",5279.29,5270.0,5290.00);
  RooRealVar DSigma("Sigma","DSigma",19.8,10.0,40.8);
  RooRealVar DLAlpha("DLAlpha","DLAlpha",LAlpha.getVal());
  RooRealVar DRAlpha("DRAlpha","DRAlpha",RAlpha.getVal());
  RooRealVar DLN("DLN","DLN",LN.getVal());
  RooRealVar DRN("DRN","DRN",RN.getVal());

  RooCBShape DCBLeft("DCBLeft","DCBLeft",BMass,DMean,DSigma,DLAlpha,DLN);
  
  RooCBShape DCBRight("DCBRight","DCBRight",BMass,DMean,DSigma,DRAlpha,DRN);

  RooRealVar DFitFraction("FitFraction","DFitFraction",0.5,0.0,1.0);
  RooAddPdf DDCB("DDCB","DDCB",RooArgList(DCBRight,DCBLeft),DFitFraction);
  
  //==============================B MASS BKG PDF==============================
  RooRealVar slope("slope","slope",-0.5,-1.0,0.0);
  RooChebychev bkg("bkg","Background",BMass,RooArgSet(slope));
  
  //==============================Eta mass signal pdf================================
  RooRealVar DEtamean("Etamean","DEtamean",958.0,945.0,980.0) ;
  RooRealVar DEtasigma("Etasigma","DEtasigma",15.0,5.0,65.0) ;
  RooRealVar DEtaLAlpha("DEtaLAlpha","DEtaLAlpha",EtaLAlpha.getVal());
  RooRealVar DEtaRAlpha("DEtaRAlpha","DEtaRAlpha",EtaRAlpha.getVal());
  RooRealVar DEtaLN("DEtaLN","DEtaLN",EtaLN.getVal());
  RooRealVar DEtaRN("DEtaRN","DEtaRN",EtaRN.getVal());
  
  RooCBShape EtaDCBLeft("EtaDCBLeft","EtaDCBLeft",EtaMass,DEtamean,DEtasigma,DEtaLAlpha,DEtaLN);
  
  RooCBShape EtaDCBRight("EtaDCBRight","EtaDCBRight",EtaMass,DEtamean,DEtasigma,DEtaRAlpha,DEtaRN);
  
  RooRealVar DEtaFitFraction("EtaFitFraction","DEtaFitFraction",0.5,0.0,1.0);
  RooAddPdf EtaDDCB("EtaDDCB","EtaDDCB",RooArgList(EtaDCBRight,EtaDCBLeft),DEtaFitFraction);

  RooProdPdf DSignalPdf("DSignalPdf","DSignalPdf",RooArgList(EtaDDCB,DDCB));
  
  RooExtendPdf DExtSignalPdf("DExtSignalPdf","DExtSignalPdf",DSignalPdf,DSignalYield);

  //=============================== Eta mass bkg pdf==================================
  
  RooRealVar EtaBkgMean("EtaBkgMean","EtaBkgMean",958.0,900.0,1020.0);
  RooRealVar EtaBkgSigma("EtaBkgSigma","EtaBkgSigma",19.8,10.0,40.8);
  RooRealVar EtaBkgLAlpha("EtaBkgLAlpha","EtaBkgLAlpha",BsbLAlpha.getVal());
  //  RooRealVar EtaBkgRAlpha("EtaBkgRAlpha","EtaBkgRAlpha",BsbRAlpha.getVal());
  RooRealVar EtaBkgLN("EtaBkgLN","EtaBkgLN",BsbLN.getVal());
  //  RooRealVar EtaBkgRN("EtaBkgRN","EtaBkgRN",BsbRN.getVal());

  RooCBShape EtaBkgCBLeft("EtaBkgCBLeft","EtaBkgCBLeft",EtaMass,DEtamean,EtaBkgSigma,EtaBkgLAlpha,EtaBkgLN);
  
  //  RooCBShape EtaBkgCBRight("EtaBkgCBRight","EtaBkgCBRight",EtaMass,DEtamean,EtaBkgSigma,EtaBkgRAlpha,EtaBkgRN);
  
  //  RooRealVar EtaBkgFitFraction("EtaBkgFitFraction","EtaBkgFitFraction",0.5,0.0,1.0);
  //  RooAddPdf EtaBkgDCB("EtaBkgDCB","EtaBkgDCB",RooArgList(EtaBkgCBRight,EtaBkgCBLeft),EtaBkgFitFraction);
  
  RooProdPdf DataBackgroundPDF("DataBackgroundPDF","DataBackgroundPDF",RooArgList(EtaBkgCBLeft,bkg));
  
  RooRealVar DataBackgroundYield("BackgroundYield","DataBackgroundYield",500.0,0.0,10000.0);
  
  RooExtendPdf ExtDataBackgroundPDF("ExtDataBackgroundPDF","ExtDataBackgroundPDF",DataBackgroundPDF,DataBackgroundYield);

  RooAddPdf TotalPDF("TotalPDF","TotalPDF",RooArgList(ExtDataBackgroundPDF,DExtSignalPdf));
  std::cout<<"Dependents = "<<std::endl;
  RooArgSet* Dependents=TotalPDF.getDependents(AllData);
  Dependents->Print("v");
  std::cout<<"parameters= "<<std::endl;
  RooArgSet* parameters=TotalPDF.getParameters(AllData);
  parameters->Print("v");
  RooCategory MassType("MassType","MassType") ;
  MassType.defineType("B") ;
  MassType.defineType("Eta") ;
  
  // Construct combined dataset in (x,sample)
  RooDataSet combData("combData","combined data",MassArgs,Index(MassType),Import("B",*BData),Import("Eta",*EtaData));

  RooSimultaneous simPdf("simPdf","simultaneous pdf",MassType) ;

  // Associate model with the physics state and model_ctl with the control state
  //  simPdf.addPdf(WholeFit,"B");
  //  simPdf.addPdf(WholeEtaFit,"Eta"); 

  //  simPdf.fitTo(combData,Extended(kTRUE)/*,Minos(kTRUE)*/);
  
  TotalPDF.fitTo(*AllData,Extended(kTRUE),Minos(kTRUE));

  RooPlot* frame1 = BMass.frame(Bins(50),Title("B mass projection"));
  AllData->plotOn(frame1);
  TotalPDF.plotOn(frame1,Components(ExtDataBackgroundPDF),LineStyle(kDashed),LineColor(kRed));
  TotalPDF.plotOn(frame1);
  TotalPDF.paramOn(frame1);
  
  // The same plot for the control sample slice
  RooPlot* frame2 = EtaMass.frame(Bins(50),Title("Eta mass projection")) ;
  AllData->plotOn(frame2);
  TotalPDF.plotOn(frame2,Components(ExtDataBackgroundPDF),LineStyle(kDashed),LineColor(kRed));
  TotalPDF.plotOn(frame2);
  TotalPDF.paramOn(frame2);
  TCanvas* DecoratedCanvas =HandyFunctions::DecoratePlot(frame2);

  
  TCanvas* DataBC= new TCanvas("BCanvas","BCanvas",1200,1000) ;
  gPad->SetLeftMargin(0.15) ; frame1->GetYaxis()->SetTitleOffset(1.4) ; frame1->Draw() ;
  TCanvas* EtaBC= new TCanvas("EtaCanvas","EtaCanvas",1200,1000) ;
  gPad->SetLeftMargin(0.15) ; frame2->GetYaxis()->SetTitleOffset(1.4) ; frame2->Draw() ;
  DataBC->SaveAs("DataBC.pdf");
  EtaBC->SaveAs("EtaBC.pdf");
  
  TFile * DataSimulFit = new TFile("DataSimulFit.root","RECREATE");
  DataBC->Write();
  EtaBC->Write();
  DecoratedCanvas->Write();

  
		 
		  

  
}
void ZeeGammaMassFitSystematicStudy(string workspaceFile, const Int_t seed = 1234, 
                                    Int_t Option = 0, Int_t NToys = 1) {


  //--------------------------------------------------------------------------------------------------------------
  // Settings 
  //==============================================================================================================    
  TRandom3 *randomnumber = new TRandom3(seed);
//   RooRealVar m("m","mass",60,130);

  RooCategory sample("sample","");
  sample.defineType("Pass",1);
  sample.defineType("Fail",2);

  //--------------------------------------------------------------------------------------------------------------
  //Load Workspace
  //==============================================================================================================    
  TFile *f = new TFile (workspaceFile.c_str(), "READ");
  RooWorkspace *w = (RooWorkspace*)f->Get("MassFitWorkspace");

  //--------------------------------------------------------------------------------------------------------------
  //Setup output tree
  //==============================================================================================================    
  TFile *outputfile = new TFile (Form("EffToyResults_Option%d_Seed%d.root",Option, seed), "RECREATE");
  float varEff = 0;
  float varEffErrL = 0;
  float varEffErrH = 0;
  TTree *outTree = new TTree("eff","eff");
  outTree->Branch("eff",&varEff, "eff/F");
  outTree->Branch("efferrl",&varEffErrL, "efferrl/F");
  outTree->Branch("efferrh",&varEffErrH, "efferrh/F");
  
  //--------------------------------------------------------------------------------------------------------------
  //Load Model
  //==============================================================================================================    
  RooSimultaneous *totalPdf = (RooSimultaneous*)w->pdf("totalPdf");
  RooRealVar *m_default = (RooRealVar*)w->var("m");
  m_default->setRange("signalRange",85, 95);
  
  //get default models
  RooAddPdf *modelPass_default = (RooAddPdf*)w->pdf("modelPass");
  RooAddPdf *modelFail_default = (RooAddPdf*)w->pdf("modelFail");

  //get variables
  RooRealVar *Nsig = (RooRealVar*)w->var("Nsig");
  RooRealVar *eff = (RooRealVar*)w->var("eff");
  RooRealVar *NbkgFail = (RooRealVar*)w->var("NbkgFail");

  RooFormulaVar NsigPass("NsigPass","eff*Nsig",RooArgList(*eff,*Nsig));	 
  RooFormulaVar NsigFail("NsigFail","(1.0-eff)*Nsig",RooArgList(*eff,*Nsig));

  //get number of expected events
  Double_t npass = 100;
  Double_t nfail = 169;

  //*************************************************************************************
  //make alternative model
  //*************************************************************************************
  RooRealVar *tFail_default = (RooRealVar*)w->var("tFail");
  RooRealVar *fracFail_default = (RooRealVar*)w->var("fracFail");
 

  RooRealVar *meanFail_default = (RooRealVar*)w->var("meanFail");
  RooRealVar *sigmaFail_default = (RooRealVar*)w->var("sigmaFail");
  RooHistPdf *bkgFailTemplate_default = (RooHistPdf*)w->pdf("bkgHistPdfFail");
  RooFFTConvPdf *sigFail_default = (RooFFTConvPdf*)w->pdf("signalFail");
  RooFFTConvPdf *bkgFail_default = (RooFFTConvPdf*)w->pdf("bkgConvPdfFail");
  RooExtendPdf *esignalFail_default = (RooExtendPdf *)w->pdf("esignalFail");
  RooExtendPdf *ebackgroundFail_default = (RooExtendPdf *)w->pdf("ebackgroundFail");
  RooExponential *bkgexpFail_default = (RooExponential*)w->pdf("bkgexpFail");
  RooAddPdf *backgroundFail_default = (RooAddPdf*)w->pdf("backgroundFail");
  RooGaussian *bkggausFail_default = (RooGaussian*)w->pdf("bkggausFail");

  //shifted mean
  RooRealVar *meanFail_shifted = new RooRealVar("meanFail_shifted","meanFail_shifted", 0, -5, 5);
  meanFail_shifted->setVal(meanFail_default->getVal());
  if (Option == 1) meanFail_shifted->setVal(meanFail_default->getVal()-1.0);
  else if (Option == 2) meanFail_shifted->setVal(meanFail_default->getVal()+1.0);  
  else if (Option == 11) meanFail_shifted->setVal(meanFail_default->getVal()-2.0);
  else if (Option == 12) meanFail_shifted->setVal(meanFail_default->getVal()+2.0);  

  RooRealVar *sigmaFail_shifted = new RooRealVar("sigmaFail_shifted","sigmaFail_shifted", 0, -5, 5);
  sigmaFail_shifted->setVal(sigmaFail_default->getVal());
  if (Option == 3) sigmaFail_shifted->setVal(sigmaFail_default->getVal()*1.2);
  else if (Option == 4) sigmaFail_shifted->setVal(sigmaFail_default->getVal()*0.8);

  CMCBkgTemplateConvGaussianPlusExp *bkgFailModel = new CMCBkgTemplateConvGaussianPlusExp(*m_default,bkgFailTemplate_default,false,meanFail_shifted,sigmaFail_shifted, "shifted");
  bkgFailModel->t->setVal(tFail_default->getVal());
  bkgFailModel->frac->setVal(fracFail_default->getVal());

  cout << "mean : " << meanFail_default->getVal() << " - " << meanFail_shifted->getVal() << endl;
  cout << "sigma : " << sigmaFail_default->getVal() << " - " << sigmaFail_shifted->getVal() << endl;
  cout << "t: " << tFail_default->getVal() << " - " << bkgFailModel->t->getVal() << endl;
  cout << "frac: " << fracFail_default->getVal() << " - " << bkgFailModel->frac->getVal() << endl;
  
  cout << "eff: " << eff->getVal() << " : " << NsigPass.getVal() << " / " << (NsigPass.getVal() + NsigFail.getVal()) << endl;
  cout << "NbkgFail: " << NbkgFail->getVal() << endl;


  //make alternative fail model
  RooAddPdf *modelFail=0;
  RooExtendPdf *esignalFail=0, *ebackgroundFail=0;
  ebackgroundFail = new RooExtendPdf("ebackgroundFail_shifted","ebackgroundFail_shifted",*(bkgFailModel->model),*NbkgFail,"signalRange");
  modelFail       = new RooAddPdf("modelFail","Model for FAIL sample", RooArgList(*esignalFail_default,*ebackgroundFail));



  cout << "*************************************\n";
  ebackgroundFail->Print();
  cout << "*************************************\n";
  ebackgroundFail_default->Print();
  cout << "*************************************\n";
  modelFail->Print();
  cout << "*************************************\n";
  modelFail_default->Print();
  cout << "*************************************\n";

  TCanvas *cv = new TCanvas("cv","cv",800,600);

  RooPlot *mframeFail_default = m_default->frame(Bins(Int_t(130-60)/2));
  modelFail_default->plotOn(mframeFail_default);
  modelFail_default->plotOn(mframeFail_default,Components("ebackgroundFail"),LineStyle(kDashed),LineColor(kRed));
  modelFail_default->plotOn(mframeFail_default,Components("bkgexpFail"),LineStyle(kDashed),LineColor(kGreen+2));
  mframeFail_default->GetYaxis()->SetTitle("");
  mframeFail_default->GetYaxis()->SetTitleOffset(1.2);
  mframeFail_default->GetXaxis()->SetTitle("m_{ee#gamma} [GeV/c^{2}]");
  mframeFail_default->GetXaxis()->SetTitleOffset(1.05);
  mframeFail_default->SetTitle("");
  mframeFail_default->Draw();

  cv->SaveAs("DefaultModel.gif");

  RooPlot *mframeFail = m_default->frame(Bins(Int_t(130-60)/2));
  modelFail->plotOn(mframeFail);
  modelFail->plotOn(mframeFail,Components("ebackgroundFail_shifted"),LineStyle(kDashed),LineColor(kRed));
  modelFail->plotOn(mframeFail,Components("bkgexpFail_shifted"),LineStyle(kDashed),LineColor(kGreen+2));
  mframeFail->GetYaxis()->SetTitle("");
  mframeFail->GetYaxis()->SetTitleOffset(1.2);
  mframeFail->GetXaxis()->SetTitle("m_{ee#gamma} [GeV/c^{2}]");
  mframeFail->GetXaxis()->SetTitleOffset(1.05);
  mframeFail->SetTitle("");
  mframeFail->Draw();
  cv->SaveAs(Form("ShiftedModel_%d.gif",Option));


  //*************************************************************************************
  //Do Toys
  //*************************************************************************************
  for(uint t=0; t < NToys; ++t) {

    RooDataSet *pseudoData_pass    = modelPass_default->generate(*m_default, randomnumber->Poisson(npass));
    RooDataSet *pseudoData_fail  = 0;
    pseudoData_fail    = modelFail->generate(*m_default, randomnumber->Poisson(nfail));
    RooDataSet *pseudoDataCombined = new RooDataSet("pseudoDataCombined","pseudoDataCombined",RooArgList(*m_default),
                                                    RooFit::Index(sample),
                                                    RooFit::Import("Pass",*pseudoData_pass),
                                                    RooFit::Import("Fail",*pseudoData_fail));

    pseudoDataCombined->write(Form("toy%d.txt",t));

    RooFitResult *fitResult=0;
    fitResult = totalPdf->fitTo(*pseudoDataCombined,
                                RooFit::Extended(),
                                RooFit::Strategy(2),
                                //RooFit::Minos(RooArgSet(eff)),
                                RooFit::Save());

    cout << "\n\n";
    cout << "Eff Fit: " << eff->getVal() << " -" << fabs(eff->getErrorLo()) << " +" << eff->getErrorHi() << endl;

    //Fill Tree
    varEff = eff->getVal();
    varEffErrL = fabs(eff->getErrorLo());
    varEffErrH = eff->getErrorHi();
    outTree->Fill();


//   //*************************************************************************************
//   //Plot Toys
//   //*************************************************************************************
//   TCanvas *cv = new TCanvas("cv","cv",800,600);
//   char pname[50];
//   char binlabelx[100];
//   char binlabely[100];
//   char yield[50];
//   char effstr[100];
//   char nsigstr[100];
//   char nbkgstr[100];
//   char chi2str[100];

//   //
//   // Plot passing probes
//   //

//   RooPlot *mframeFail_default = m.frame(Bins(Int_t(130-60)/2));
//   modelFail_default->plotOn(mframeFail_default);
//   modelFail_default->plotOn(mframeFail_default,Components("ebackgroundFail"),LineStyle(kDashed),LineColor(kRed));
//   modelFail_default->plotOn(mframeFail_default,Components("bkgexpFail"),LineStyle(kDashed),LineColor(kGreen+2));
//   mframeFail_default->Draw();
//   cv->SaveAs("DefaultModel.gif");





//   RooPlot *mframeFail = m.frame(Bins(Int_t(130-60)/2));
//   modelFail->plotOn(mframeFail);
//   modelFail->plotOn(mframeFail,Components("ebackgroundFail_shifted"),LineStyle(kDashed),LineColor(kRed));
//   modelFail->plotOn(mframeFail,Components("bkgexpFail_shifted"),LineStyle(kDashed),LineColor(kGreen+2));

//   sprintf(yield,"%u Events",(Int_t)passTree->GetEntries());
//   sprintf(nsigstr,"N_{sig} = %.1f #pm %.1f",NsigPass.getVal(),NsigPass.getPropagatedError(*fitResult));
//     plotPass.AddTextBox(yield,0.21,0.76,0.51,0.80,0,kBlack,-1);    
//   plotPass.AddTextBox(effstr,0.70,0.85,0.94,0.90,0,kBlack,-1);
//     plotPass.AddTextBox(0.70,0.73,0.94,0.83,0,kBlack,-1,1,nsigstr);//,chi2str);

//   mframeFail->Draw();
//   cv->SaveAs(Form("ShiftedModel_%d.gif",Option));


 
//   //
//   // Plot failing probes
//   //
//   sprintf(pname,"fail%s_%i",name.Data(),ibin);
//   sprintf(yield,"%u Events",(Int_t)failTree->GetEntries());
//   sprintf(nsigstr,"N_{sig} = %.1f #pm %.1f",NsigFail.getVal(),NsigFail.getPropagatedError(*fitResult));
//   sprintf(nbkgstr,"N_{bkg} = %.1f #pm %.1f",NbkgFail.getVal(),NbkgFail.getPropagatedError(*fitResult));
//   sprintf(chi2str,"#chi^{2}/DOF = %.3f",mframePass->chiSquare(nflfail));
//   CPlot plotFail(pname,mframeFail,"Failing probes","tag-probe mass [GeV/c^{2}]","Events / 2.0 GeV/c^{2}");
//   plotFail.AddTextBox(binlabelx,0.21,0.85,0.51,0.90,0,kBlack,-1);
//   if((name.CompareTo("etapt")==0) || (name.CompareTo("etaphi")==0)) {
//     plotFail.AddTextBox(binlabely,0.21,0.80,0.51,0.85,0,kBlack,-1);    
//     plotFail.AddTextBox(yield,0.21,0.76,0.51,0.80,0,kBlack,-1);    
//   } else {
//     plotFail.AddTextBox(yield,0.21,0.81,0.51,0.85,0,kBlack,-1);
//   }
//   plotFail.AddTextBox(effstr,0.70,0.85,0.94,0.90,0,kBlack,-1);  
//   plotFail.AddTextBox(0.70,0.68,0.94,0.83,0,kBlack,-1,2,nsigstr,nbkgstr);//,chi2str);
//   plotFail.Draw(cfail,kTRUE,format);  




  } //for loop over all toys
  



  //*************************************************************************************
  //Save To File
  //*************************************************************************************
  outputfile->WriteTObject(outTree, outTree->GetName(), "WriteDelete");

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




}
Пример #14
0
LineStyle LineStyle::defaultGraphCurve (int /* index */)
{
  return LineStyle (DEFAULT_LINE_WIDTH,
                    COLOR_PALETTE_BLUE,
                    CONNECT_AS_FUNCTION_SMOOTH); // Same default color as used for PointStyle graph curves default
}
Пример #15
0
void fitWe(const TString  outputDir="test",   // output directory
           const Double_t lumi=18.7,        // integrated luminosity (/fb)
	   const Int_t    Ecm=8,         // center-of-mass energy
	   const Int_t    doPU=1         // option for PU-reweighting
) {
  gBenchmark->Start("fitWe");

  //--------------------------------------------------------------------------------------------------------------
  // Settings 
  //==============================================================================================================   
  
  // MET histogram binning and range
  const Int_t    NBINS  = 50;
  const Double_t METMAX = 100;

  const Double_t PT_CUT  = 25;
  const Double_t ETA_CUT = 2.5;

  // file format for output plots
  const TString format("png"); 
    
  // file name with recoil correction
  TString recoilfname("../RecoilSyst/ZeeData/fits.root");
  
  // file name(s) with PU weights
  TString pufname("");
  if(doPU>0) {
    if(doPU==1) { pufname = "Utils/PileupReweighting.Summer11DYmm_To_Run2011A.root"; }
    else        { cout << "Invalid option for PU re-weighting! Aborting..." << endl; assert(0); }
  }
  
  //
  // input ntuple file names
  //
  enum { eData, eWenu, eEWK };  // data type enum
  vector<TString> fnamev;
  vector<Int_t>   typev;
  
  fnamev.push_back("../Selection/Wenu/ntuples/data_m23_select.root");   typev.push_back(eData);
  fnamev.push_back("../Selection/Wenu/ntuples/we_select.root");         typev.push_back(eWenu);
  fnamev.push_back("../Selection/Wenu/ntuples/ewk_select.root");        typev.push_back(eEWK);
  fnamev.push_back("../Selection/Wenu/ntuples/top_select.root");        typev.push_back(eEWK);


  //--------------------------------------------------------------------------------------------------------------
  // Main analysis code 
  //==============================================================================================================  
  
  // Create output directory
  gSystem->mkdir(outputDir,kTRUE);
  CPlot::sOutDir = outputDir;  
  
  // Get pile-up weights
  TFile *pufile    = 0;
  TH1D  *puWeights = 0;
  if(doPU>0) {
    pufile = new TFile(pufname);
    assert(pufile);
    puWeights = (TH1D*)pufile->Get("puWeights");
    assert(puWeights);
  }
  
  // Access recoil corrections
  //RecoilCorrector recoilCorr(recoilfname);
  
  //
  // Declare MET histograms
  //
  TH1D *hDataMet  = new TH1D("hDataMet", "",NBINS,0,METMAX); hDataMet->Sumw2();
  TH1D *hDataMetm = new TH1D("hDataMetm","",NBINS,0,METMAX); hDataMetm->Sumw2();  
  TH1D *hDataMetp = new TH1D("hDataMetp","",NBINS,0,METMAX); hDataMetp->Sumw2();
  TH1D *hWenuMet  = new TH1D("hWenuMet", "",NBINS,0,METMAX); hWenuMet->Sumw2();
  TH1D *hWenuMetp = new TH1D("hWenuMetp","",NBINS,0,METMAX); hWenuMetp->Sumw2();
  TH1D *hWenuMetm = new TH1D("hWenuMetm","",NBINS,0,METMAX); hWenuMetm->Sumw2();
  TH1D *hEWKMet   = new TH1D("hEWKMet",  "",NBINS,0,METMAX); hEWKMet->Sumw2();
  TH1D *hEWKMetp  = new TH1D("hEWKMetp", "",NBINS,0,METMAX); hEWKMetp->Sumw2();
  TH1D *hEWKMetm  = new TH1D("hEWKMetm", "",NBINS,0,METMAX); hEWKMetm->Sumw2();

  //
  // Declare variables to read in ntuple
  //
  UInt_t  runNum, lumiSec, evtNum;
  UInt_t  npv, npu;
  Float_t genWPt, genWPhi;
  Float_t scale1fb;
  Float_t met, metPhi, sumEt, mt, u1, u2;
  Int_t   q;
  LorentzVector *lep=0;
  LorentzVector *sc=0;
    
  TFile *infile=0;
  TTree *intree=0;

  //
  // Loop over files
  //
  for(UInt_t ifile=0; ifile<fnamev.size(); ifile++) {
    
    // Read input file and get the TTrees
    cout << "Processing " << fnamev[ifile] << "..." << endl;
    infile = new TFile(fnamev[ifile]);	  assert(infile);
    intree = (TTree*)infile->Get("Events"); assert(intree);

    intree->SetBranchAddress("runNum",   &runNum);    // event run number
    intree->SetBranchAddress("lumiSec",  &lumiSec);   // event lumi section
    intree->SetBranchAddress("evtNum",   &evtNum);    // event number
    intree->SetBranchAddress("npv",      &npv);       // number of primary vertices
    intree->SetBranchAddress("npu",      &npu);       // number of in-time PU events (MC)
    intree->SetBranchAddress("genVPt",   &genWPt);    // GEN W boson pT (signal MC)
    intree->SetBranchAddress("genVPhi",  &genWPhi);   // GEN W boson phi (signal MC)
    intree->SetBranchAddress("scale1fb", &scale1fb);  // event weight per 1/fb (MC)
    intree->SetBranchAddress("met",      &met);       // MET
    intree->SetBranchAddress("metPhi",   &metPhi);    // phi(MET)
    intree->SetBranchAddress("sumEt",    &sumEt);     // Sum ET
    intree->SetBranchAddress("mt",       &mt);        // transverse mass
    intree->SetBranchAddress("u1",       &u1);        // parallel component of recoil
    intree->SetBranchAddress("u2",       &u2);        // perpendicular component of recoil
    intree->SetBranchAddress("q",        &q);         // lepton charge
    intree->SetBranchAddress("lep",      &lep);       // lepton 4-vector
    intree->SetBranchAddress("sc",       &sc);        // electron Supercluster 4-vector
  
    //
    // loop over events
    //
    for(UInt_t ientry=0; ientry<intree->GetEntries(); ientry++) {
      intree->GetEntry(ientry);
      
      if(mt< 40)  continue;	// LUCA ADD
      TLorentzVector muPosP, muNegP, JpsiP;
      muPosP.SetPtEtaPhiM(lep->Pt(),lep->Eta(),lep->Phi(),lep->M()); // always use the muon
      muNegP.SetPtEtaPhiM(met,0,metPhi,0); // always use the neutrino
      JpsiP = muPosP + muNegP;
      
      // if(JpsiP.Pt() < 15 
      // || JpsiP.Pt() > 25 )  continue;	

      
      if(sc->Pt()        < PT_CUT)  continue;	
      if(fabs(sc->Eta()) > ETA_CUT) continue;
   
      if(typev[ifile]==eData) {
        hDataMet->Fill(met);
	if(q>0) { hDataMetp->Fill(met); } 
	else    { hDataMetm->Fill(met); }
      
      } else {
        Double_t weight = 1;
        weight *= scale1fb*lumi;
        if(puWeights)
	  weight *= puWeights->GetBinContent(npu+1);
	
	if(typev[ifile]==eWenu) {
          Double_t corrMet=met, corrMetPhi=metPhi;
        
	  // apply recoil corrections to W MC
	  //recoilCorr.Correct(corrMet,corrMetPhi,genWPt,genWPhi,lep->Pt(),lep->Phi());
	
          hWenuMet->Fill(corrMet,weight);
	  if(q>0) { hWenuMetp->Fill(corrMet,weight); } 
	  else    { hWenuMetm->Fill(corrMet,weight); }
        }
        if(typev[ifile]==eEWK) {
          hEWKMet->Fill(met,weight);
	  if(q>0) { hEWKMetp->Fill(met,weight); }
	  else    { hEWKMetm->Fill(met,weight); }
        }
      }
    }
  }  
  delete infile;
  infile=0, intree=0;   
  
  //
  // Declare fit parameters for signal and background yields
  // Note: W signal and EWK+top PDFs are constrained to the ratio described in MC
  //
  RooRealVar nSig("nSig","nSig",0.7*(hDataMet->Integral()),0,hDataMet->Integral());
  RooRealVar nQCD("nQCD","nQCD",0.3*(hDataMet->Integral()),0,hDataMet->Integral());
  RooRealVar cewk("cewk","cewk",0.1,0,5) ;
  cewk.setVal(hEWKMet->Integral()/hWenuMet->Integral());
  cewk.setConstant(kTRUE);
  RooFormulaVar nEWK("nEWK","nEWK","cewk*nSig",RooArgList(nSig,cewk));
  
  RooRealVar nSigp("nSigp","nSigp",0.7*(hDataMetp->Integral()),0,hDataMetp->Integral());
  RooRealVar nQCDp("nQCDp","nQCDp",0.3*(hDataMetp->Integral()),0,hDataMetp->Integral());
  RooRealVar cewkp("cewkp","cewkp",0.1,0,5) ;
  cewkp.setVal(hEWKMetp->Integral()/hWenuMetp->Integral());
  cewkp.setConstant(kTRUE);
  RooFormulaVar nEWKp("nEWKp","nEWKp","cewkp*nSigp",RooArgList(nSigp,cewkp));
  
  RooRealVar nSigm("nSigm","nSigm",0.7*(hDataMetm->Integral()),0,hDataMetm->Integral());
  RooRealVar nQCDm("nQCDm","nQCDm",0.3*(hDataMetm->Integral()),0,hDataMetm->Integral());
  RooRealVar cewkm("cewkm","cewkm",0.1,0,5) ;
  cewkm.setVal(hEWKMetm->Integral()/hWenuMetm->Integral());
  cewkm.setConstant(kTRUE);
  RooFormulaVar nEWKm("nEWKm","nEWKm","cewkm*nSigm",RooArgList(nSigm,cewkm));  
  
  //
  // Construct PDFs for fitting
  //
  RooRealVar pfmet("pfmet","pfmet",0,METMAX);
  pfmet.setBins(NBINS);
   
  // Signal PDFs
  RooDataHist wenuMet ("wenuMET", "wenuMET", RooArgSet(pfmet),hWenuMet);  RooHistPdf pdfWe ("we", "we", pfmet,wenuMet, 1);
  RooDataHist wenuMetp("wenuMETp","wenuMETp",RooArgSet(pfmet),hWenuMetp); RooHistPdf pdfWep("wep","wep",pfmet,wenuMetp,1);
  RooDataHist wenuMetm("wenuMETm","wenuMETm",RooArgSet(pfmet),hWenuMetm); RooHistPdf pdfWem("wem","wem",pfmet,wenuMetm,1); 
  
  // EWK+top PDFs
  RooDataHist ewkMet ("ewkMET", "ewkMET", RooArgSet(pfmet),hEWKMet);  RooHistPdf pdfEWK ("ewk", "ewk", pfmet,ewkMet, 1);
  RooDataHist ewkMetp("ewkMETp","ewkMETp",RooArgSet(pfmet),hEWKMetp); RooHistPdf pdfEWKp("ewkp","ewkp",pfmet,ewkMetp,1); 
  RooDataHist ewkMetm("ewkMETm","ewkMETm",RooArgSet(pfmet),hEWKMetm); RooHistPdf pdfEWKm("ewkm","ewkm",pfmet,ewkMetm,1); 
  
  // QCD Pdfs
  CPepeModel1 qcd("qcd",pfmet);
  CPepeModel1 qcdp("qcdp",pfmet);
  CPepeModel1 qcdm("qcdm",pfmet);
  
  // Signal + Background PDFs
  RooAddPdf pdfMet ("pdfMet", "pdfMet", RooArgList(pdfWe,pdfEWK,*(qcd.model)),   RooArgList(nSig,nEWK,nQCD));  
  RooAddPdf pdfMetp("pdfMetp","pdfMetp",RooArgList(pdfWep,pdfEWKp,*(qcdp.model)),RooArgList(nSigp,nEWKp,nQCDp));
  RooAddPdf pdfMetm("pdfMetm","pdfMetm",RooArgList(pdfWem,pdfEWKm,*(qcdm.model)),RooArgList(nSigm,nEWKm,nQCDm));
    
  //
  // Perform fits
  //
  RooDataHist dataMet("dataMet", "dataMet", RooArgSet(pfmet),hDataMet);
  RooFitResult *fitRes = pdfMet.fitTo(dataMet,Extended(),Minos(kTRUE),Save(kTRUE));
  
  RooDataHist dataMetp("dataMetp","dataMetp",RooArgSet(pfmet),hDataMetp);
  RooFitResult *fitResp = pdfMetp.fitTo(dataMetp,Extended(),Minos(kTRUE),Save(kTRUE));
  
  RooDataHist dataMetm("dataMetm","dataMetm",RooArgSet(pfmet),hDataMetm);
  RooFitResult *fitResm = pdfMetm.fitTo(dataMetm,Extended(),Minos(kTRUE),Save(kTRUE));
    
  //
  // Use histogram version of fitted PDFs to make ratio plots
  // (Will also use PDF histograms later for Chi^2 and KS tests)
  //
  TH1D *hPdfMet = (TH1D*)(pdfMet.createHistogram("hPdfMet", pfmet));
  hPdfMet->Scale((nSig.getVal()+nEWK.getVal()+nQCD.getVal())/hPdfMet->Integral());
  TH1D *hMetDiff = makeDiffHist(hDataMet,hPdfMet,"hMetDiff");
  hMetDiff->SetMarkerStyle(kFullCircle);
  hMetDiff->SetMarkerSize(0.9);
   
  TH1D *hPdfMetp = (TH1D*)(pdfMetp.createHistogram("hPdfMetp", pfmet));
  hPdfMetp->Scale((nSigp.getVal()+nEWKp.getVal()+nQCDp.getVal())/hPdfMetp->Integral());
  TH1D *hMetpDiff = makeDiffHist(hDataMetp,hPdfMetp,"hMetpDiff");
  hMetpDiff->SetMarkerStyle(kFullCircle);
  hMetpDiff->SetMarkerSize(0.9);
    
  TH1D *hPdfMetm = (TH1D*)(pdfMetm.createHistogram("hPdfMetm", pfmet));
  hPdfMetm->Scale((nSigm.getVal()+nEWKm.getVal()+nQCDm.getVal())/hPdfMetm->Integral());
  TH1D *hMetmDiff = makeDiffHist(hDataMetm,hPdfMetm,"hMetmDiff");
  hMetmDiff->SetMarkerStyle(kFullCircle); 
  hMetmDiff->SetMarkerSize(0.9);
   
  
  //--------------------------------------------------------------------------------------------------------------
  // Make plots 
  //==============================================================================================================  
  
  TCanvas *c = MakeCanvas("c","c",800,800);
  c->Divide(1,2,0,0);
  c->cd(1)->SetPad(0,0.3,1.0,1.0);
  c->cd(1)->SetTopMargin(0.1);
  c->cd(1)->SetBottomMargin(0.01);
  c->cd(1)->SetLeftMargin(0.18);  
  c->cd(1)->SetRightMargin(0.07);  
  c->cd(1)->SetTickx(1);
  c->cd(1)->SetTicky(1);  
  c->cd(2)->SetPad(0,0,1.0,0.3);
  c->cd(2)->SetTopMargin(0.05);
  c->cd(2)->SetBottomMargin(0.45);
  c->cd(2)->SetLeftMargin(0.18);
  c->cd(2)->SetRightMargin(0.07);
  c->cd(2)->SetTickx(1);
  c->cd(2)->SetTicky(1);
  gStyle->SetTitleOffset(1.400,"Y");
  
  char ylabel[100];  // string buffer for y-axis label
  
  // label for lumi
  char lumitext[100];
  if(lumi<0.1) sprintf(lumitext,"%.1f pb^{-1}  at  #sqrt{s} = %i TeV",lumi*1000.,Ecm);
  else         sprintf(lumitext,"%.2f fb^{-1}  at  #sqrt{s} = %i TeV",lumi,Ecm);
  
  // plot colors
  Int_t linecolorW   = kOrange-3;
  Int_t fillcolorW   = kOrange-2;
  Int_t linecolorEWK = kOrange+10;
  Int_t fillcolorEWK = kOrange+7;
  Int_t linecolorQCD = kViolet+2;
  Int_t fillcolorQCD = kViolet-5;
  Int_t ratioColor   = kGray+2;
  
  //
  // Dummy histograms for TLegend
  // (I can't figure out how to properly pass RooFit objects...)
  //
  TH1D *hDummyData = new TH1D("hDummyData","",0,0,10);
  hDummyData->SetMarkerStyle(kFullCircle);
  hDummyData->SetMarkerSize(0.9);
  
  TH1D *hDummyW = new TH1D("hDummyW","",0,0,10);
  hDummyW->SetLineColor(linecolorW);
  hDummyW->SetFillColor(fillcolorW);
  hDummyW->SetFillStyle(1001);
  
  TH1D *hDummyEWK = new TH1D("hDummyEWK","",0,0,10);
  hDummyEWK->SetLineColor(linecolorEWK);
  hDummyEWK->SetFillColor(fillcolorEWK);
  hDummyEWK->SetFillStyle(1001);
  
  TH1D *hDummyQCD = new TH1D("hDummyQCD","",0,0,10);
  hDummyQCD->SetLineColor(linecolorQCD);
  hDummyQCD->SetFillColor(fillcolorQCD);
  hDummyQCD->SetFillStyle(1001);
   
  //
  // W MET plot
  //
  RooPlot *weframe = pfmet.frame(Bins(NBINS));    
  dataMet.plotOn(weframe,MarkerStyle(kFullCircle),MarkerSize(0.9),DrawOption("ZP"));
  pdfMet.plotOn(weframe,FillColor(fillcolorW),DrawOption("F"));
  pdfMet.plotOn(weframe,LineColor(linecolorW));
  pdfMet.plotOn(weframe,Components(RooArgSet(pdfEWK,*(qcd.model))),FillColor(fillcolorEWK),DrawOption("F"));
  pdfMet.plotOn(weframe,Components(RooArgSet(pdfEWK,*(qcd.model))),LineColor(linecolorEWK));
  pdfMet.plotOn(weframe,Components(RooArgSet(*(qcd.model))),FillColor(fillcolorQCD),DrawOption("F"));
  pdfMet.plotOn(weframe,Components(RooArgSet(*(qcd.model))),LineColor(linecolorQCD));
  pdfMet.plotOn(weframe,Components(RooArgSet(pdfWe)),LineColor(linecolorW),LineStyle(2));
  dataMet.plotOn(weframe,MarkerStyle(kFullCircle),MarkerSize(0.9),DrawOption("ZP"));  
  
  sprintf(ylabel,"Events / %.1f GeV",hDataMet->GetBinWidth(1));
  CPlot plotMet("fitmet",weframe,"","",ylabel);
  plotMet.SetLegend(0.68,0.57,0.93,0.77);
  plotMet.GetLegend()->AddEntry(hDummyData,"data","PL");
  plotMet.GetLegend()->AddEntry(hDummyW,"W#rightarrowe#nu","F");
  plotMet.GetLegend()->AddEntry(hDummyEWK,"EWK+t#bar{t}","F");
  plotMet.GetLegend()->AddEntry(hDummyQCD,"QCD","F");
  plotMet.AddTextBox(lumitext,0.55,0.80,0.90,0.86,0);
  plotMet.AddTextBox("CMS Preliminary",0.63,0.92,0.95,0.99,0);
  plotMet.SetYRange(0.1,1.1*(hDataMet->GetMaximum()));
//  plotMet.Draw(c,kFALSE,format,1);
  plotMet.Draw(c,kTRUE,format,1);

  CPlot plotMetDiff("fitmet","","#slash{E}_{T} [GeV]","#chi");
  plotMetDiff.AddHist1D(hMetDiff,"EX0",ratioColor);
  plotMetDiff.SetYRange(-8,8);
  plotMetDiff.AddLine(0, 0,METMAX, 0,kBlack,1);
  plotMetDiff.AddLine(0, 5,METMAX, 5,kBlack,3);
  plotMetDiff.AddLine(0,-5,METMAX,-5,kBlack,3);
  plotMetDiff.Draw(c,kTRUE,format,2);
  
  plotMet.SetName("fitmetlog");
  plotMet.SetLogy();
  plotMet.SetYRange(1e-3*(hDataMet->GetMaximum()),10*(hDataMet->GetMaximum()));
  plotMet.Draw(c,kTRUE,format,1);
    
  //
  // W+ MET plot
  //
  RooPlot *wepframe = pfmet.frame(Bins(NBINS));    
  dataMetp.plotOn(wepframe,MarkerStyle(kFullCircle),MarkerSize(0.9),DrawOption("ZP"));
  pdfMetp.plotOn(wepframe,FillColor(fillcolorW),DrawOption("F"));
  pdfMetp.plotOn(wepframe,LineColor(linecolorW));
  pdfMetp.plotOn(wepframe,Components(RooArgSet(pdfEWKp,*(qcdp.model))),FillColor(fillcolorEWK),DrawOption("F"));
  pdfMetp.plotOn(wepframe,Components(RooArgSet(pdfEWKp,*(qcdp.model))),LineColor(linecolorEWK));
  pdfMetp.plotOn(wepframe,Components(RooArgSet(*(qcdp.model))),FillColor(fillcolorQCD),DrawOption("F"));
  pdfMetp.plotOn(wepframe,Components(RooArgSet(*(qcdp.model))),LineColor(linecolorQCD));
  pdfMetp.plotOn(wepframe,Components(RooArgSet(pdfWep)),LineColor(linecolorW),LineStyle(2));
  dataMetp.plotOn(wepframe,MarkerStyle(kFullCircle),MarkerSize(0.9),DrawOption("ZP"));  
  
  sprintf(ylabel,"Events / %.1f GeV",hDataMetp->GetBinWidth(1));
  CPlot plotMetp("fitmetp",wepframe,"","",ylabel);
  plotMetp.SetLegend(0.68,0.57,0.93,0.77);
  plotMetp.GetLegend()->AddEntry(hDummyData,"data","PL");
  plotMetp.GetLegend()->AddEntry(hDummyW,"W^{+}#rightarrowe^{+}#nu","F");
  plotMetp.GetLegend()->AddEntry(hDummyEWK,"EWK+t#bar{t}","F");
  plotMetp.GetLegend()->AddEntry(hDummyQCD,"QCD","F");
  plotMetp.AddTextBox(lumitext,0.55,0.80,0.90,0.86,0);
  plotMetp.AddTextBox("CMS Preliminary",0.63,0.92,0.95,0.99,0);
  plotMetp.SetYRange(0.1,1.1*(hDataMetp->GetMaximum()));
  plotMetp.Draw(c,kFALSE,format,1);

  CPlot plotMetpDiff("fitmetp","","#slash{E}_{T} [GeV]","#chi");
  plotMetpDiff.AddHist1D(hMetpDiff,"EX0",ratioColor);
  plotMetpDiff.SetYRange(-8,8);
  plotMetpDiff.AddLine(0, 0,METMAX, 0,kBlack,1);
  plotMetpDiff.AddLine(0, 5,METMAX, 5,kBlack,3);
  plotMetpDiff.AddLine(0,-5,METMAX,-5,kBlack,3);
  plotMetpDiff.Draw(c,kTRUE,format,2);
  
  plotMetp.SetName("fitmetplog");
  plotMetp.SetLogy();
  plotMetp.SetYRange(1e-3*(hDataMetp->GetMaximum()),10*(hDataMetp->GetMaximum()));
  plotMetp.Draw(c,kTRUE,format,1);
  
  //
  // W- MET plot
  //
  RooPlot *wemframe = pfmet.frame(Bins(NBINS)); 
  dataMetm.plotOn(wemframe,MarkerStyle(kFullCircle),MarkerSize(0.9),DrawOption("ZP"));
  pdfMetm.plotOn(wemframe,FillColor(fillcolorW),DrawOption("F"));
  pdfMetm.plotOn(wemframe,LineColor(linecolorW));
  pdfMetm.plotOn(wemframe,Components(RooArgSet(pdfEWKm,*(qcdm.model))),FillColor(fillcolorEWK),DrawOption("F"));
  pdfMetm.plotOn(wemframe,Components(RooArgSet(pdfEWKm,*(qcdm.model))),LineColor(linecolorEWK));
  pdfMetm.plotOn(wemframe,Components(RooArgSet(*(qcdm.model))),FillColor(fillcolorQCD),DrawOption("F"));
  pdfMetm.plotOn(wemframe,Components(RooArgSet(*(qcdm.model))),LineColor(linecolorQCD));
  pdfMetm.plotOn(wemframe,Components(RooArgSet(pdfWem)),LineColor(linecolorW),LineStyle(2));
  dataMetm.plotOn(wemframe,MarkerStyle(kFullCircle),MarkerSize(0.9),DrawOption("ZP"));
  
  sprintf(ylabel,"Events / %.1f GeV",hDataMetm->GetBinWidth(1));
  CPlot plotMetm("fitmetm",wemframe,"","",ylabel);
  plotMetm.SetLegend(0.68,0.57,0.93,0.77);
  plotMetm.GetLegend()->AddEntry(hDummyData,"data","PL");
  plotMetm.GetLegend()->AddEntry(hDummyW,"W^{-}#rightarrowe^{-}#bar{#nu}","F");
  plotMetm.GetLegend()->AddEntry(hDummyEWK,"EWK+t#bar{t}","F");
  plotMetm.GetLegend()->AddEntry(hDummyQCD,"QCD","F");
  plotMetm.AddTextBox(lumitext,0.55,0.80,0.90,0.86,0);
  plotMetm.AddTextBox("CMS Preliminary",0.63,0.92,0.95,0.99,0);
  plotMetm.SetYRange(0.1,1.1*(hDataMetm->GetMaximum()));
  plotMetm.Draw(c,kFALSE,format,1);

  CPlot plotMetmDiff("fitmetm","","#slash{E}_{T} [GeV]","#chi");
  plotMetmDiff.AddHist1D(hMetmDiff,"EX0",ratioColor);
  plotMetmDiff.SetYRange(-8,8);
  plotMetmDiff.AddLine(0, 0,METMAX, 0,kBlack,1);
  plotMetmDiff.AddLine(0, 5,METMAX, 5,kBlack,3);
  plotMetmDiff.AddLine(0,-5,METMAX,-5,kBlack,3);
  plotMetmDiff.Draw(c,kTRUE,format,2);
  
  plotMetm.SetName("fitmetmlog");
  plotMetm.SetLogy();
  plotMetm.SetYRange(1e-3*(hDataMetm->GetMaximum()),10*(hDataMetm->GetMaximum()));
  plotMetm.Draw(c,kTRUE,format,1);

    
  //--------------------------------------------------------------------------------------------------------------
  // Output
  //==============================================================================================================
   
  cout << "*" << endl;
  cout << "* SUMMARY" << endl;
  cout << "*--------------------------------------------------" << endl;  
  
  //
  // Write fit results
  //
  ofstream txtfile;
  char txtfname[100];    
  
  ios_base::fmtflags flags;
  
  Double_t chi2prob, chi2ndf;
  Double_t ksprob, ksprobpe;
  
  chi2prob = hDataMet->Chi2Test(hPdfMet,"PUW");
  chi2ndf  = hDataMet->Chi2Test(hPdfMet,"CHI2/NDFUW");
  ksprob   = hDataMet->KolmogorovTest(hPdfMet);
  ksprobpe = hDataMet->KolmogorovTest(hPdfMet,"DX");
  sprintf(txtfname,"%s/fitresWe.txt",CPlot::sOutDir.Data());
  txtfile.open(txtfname);
  assert(txtfile.is_open());
  
  flags = txtfile.flags();
  txtfile << setprecision(10);
  txtfile << " *** Yields *** " << endl;
  txtfile << "Selected: " << hDataMet->Integral() << endl;
  txtfile << "  Signal: " << nSig.getVal() << " +/- " << nSig.getPropagatedError(*fitRes) << endl;
  txtfile << "     QCD: " << nQCD.getVal() << " +/- " << nQCD.getPropagatedError(*fitRes) << endl;
  txtfile << "   Other: " << nEWK.getVal() << " +/- " << nEWK.getPropagatedError(*fitRes) << endl;
  txtfile << endl; 
  txtfile.flags(flags);
  
  fitRes->printStream(txtfile,RooPrintable::kValue,RooPrintable::kVerbose);
  txtfile << endl;
  printCorrelations(txtfile, fitRes);
  txtfile << endl;
  printChi2AndKSResults(txtfile, chi2prob, chi2ndf, ksprob, ksprobpe);
  txtfile.close();
  
  chi2prob = hDataMetp->Chi2Test(hPdfMetp,"PUW");
  chi2ndf  = hDataMetp->Chi2Test(hPdfMetp,"CHI2/NDFUW");
  ksprob   = hDataMetp->KolmogorovTest(hPdfMetp);
  ksprobpe = hDataMetp->KolmogorovTest(hPdfMetp,"DX");  
  sprintf(txtfname,"%s/fitresWep.txt",CPlot::sOutDir.Data());
  txtfile.open(txtfname);
  assert(txtfile.is_open());
  
  flags = txtfile.flags();
  txtfile << setprecision(10);
  txtfile << " *** Yields *** " << endl;
  txtfile << "Selected: " << hDataMetp->Integral() << endl;
  txtfile << "  Signal: " << nSigp.getVal() << " +/- " << nSigp.getPropagatedError(*fitResp) << endl;
  txtfile << "     QCD: " << nQCDp.getVal() << " +/- " << nQCDp.getPropagatedError(*fitResp) << endl;
  txtfile << "   Other: " << nEWKp.getVal() << " +/- " << nEWKp.getPropagatedError(*fitResp) << endl;
  txtfile << endl;  
  txtfile.flags(flags);
  
  fitResp->printStream(txtfile,RooPrintable::kValue,RooPrintable::kVerbose);
  txtfile << endl;
  printCorrelations(txtfile, fitResp);
  txtfile << endl;
  printChi2AndKSResults(txtfile, chi2prob, chi2ndf, ksprob, ksprobpe);
  txtfile.close();

  chi2prob = hDataMetm->Chi2Test(hPdfMetm,"PUW");
  chi2ndf  = hDataMetm->Chi2Test(hPdfMetm,"CHI2/NDFUW");
  ksprob   = hDataMetm->KolmogorovTest(hPdfMetm);
  ksprobpe = hDataMetm->KolmogorovTest(hPdfMetm,"DX");  
  sprintf(txtfname,"%s/fitresWem.txt",CPlot::sOutDir.Data());
  txtfile.open(txtfname);
  assert(txtfile.is_open());
  
  flags = txtfile.flags();
  txtfile << setprecision(10);
  txtfile << " *** Yields *** " << endl;
  txtfile << "Selected: " << hDataMetm->Integral() << endl;
  txtfile << "  Signal: " << nSigm.getVal() << " +/- " << nSigm.getPropagatedError(*fitResm) << endl;
  txtfile << "     QCD: " << nQCDm.getVal() << " +/- " << nQCDm.getPropagatedError(*fitResm) << endl;
  txtfile << "   Other: " << nEWKm.getVal() << " +/- " << nEWKm.getPropagatedError(*fitResm) << endl;
  txtfile << endl;
  txtfile.flags(flags);
  
  fitResm->printStream(txtfile,RooPrintable::kValue,RooPrintable::kVerbose);
  txtfile << endl;
  printCorrelations(txtfile, fitResm);
  txtfile << endl;
  printChi2AndKSResults(txtfile, chi2prob, chi2ndf, ksprob, ksprobpe);
  txtfile.close();

  makeHTML(outputDir);
  
  cout << endl;
  cout << "  <> Output saved in " << outputDir << "/" << endl;    
  cout << endl;     
  
  gBenchmark->Show("fitWe");
}
Пример #16
0
void MainWindow::on_LineStyleChooser_currentIndexChanged(int index)
{
    ui->canvas->changeLineStyle(LineStyle(index));
}
Пример #17
0
void fitWm(const TString  outputDir,   // output directory
           const Double_t lumi,        // integrated luminosity (/fb)
	   const Double_t nsigma=0     // vary MET corrections by n-sigmas (nsigma=0 means nominal correction)
) {
  gBenchmark->Start("fitWm");

  //--------------------------------------------------------------------------------------------------------------
  // Settings 
  //==============================================================================================================   
  
  // MET histogram binning and range
  const Int_t    NBINS   = 50;
  const Double_t METMAX  = 100;
  
  const Double_t PT_CUT  = 25;
  const Double_t ETA_CUT = 2.1;

  // file format for output plots
  const TString format("png"); 

    
  // recoil correction
  RecoilCorrector recoilCorr("../Recoil/ZmmData/fits.root");//, (!) uncomment to perform corrections to recoil from W-MC/Z-MC
                             //"../Recoil/WmpMC/fits.root",
			     //"../Recoil/WmmMC/fits.root",
			     //"../Recoil/ZmmMC/fits.root");
   
  // NNLO boson pT k-factors
  TFile nnloCorrFile("/data/blue/ksung/EWKAna/8TeV/Utils/Ratio.root");
  TH1D *hNNLOCorr = (TH1D*)nnloCorrFile.Get("RpT_B");
  
  //
  // input ntuple file names
  //
  enum { eData, eWmunu, eEWK, eAntiData, eAntiWmunu, eAntiEWK };  // data type enum
  vector<TString> fnamev;
  vector<Int_t>   typev;
  
  fnamev.push_back("/data/blue/ksung/EWKAna/8TeV/Selection/Wmunu/ntuples/data_select.root"); typev.push_back(eData);
  fnamev.push_back("/data/blue/ksung/EWKAna/8TeV/Selection/Wmunu/ntuples/wm_select.root");   typev.push_back(eWmunu);
  fnamev.push_back("/data/blue/ksung/EWKAna/8TeV/Selection/Wmunu/ntuples/ewk_select.root");  typev.push_back(eEWK);
  fnamev.push_back("/data/blue/ksung/EWKAna/8TeV/Selection/Wmunu/ntuples/top_select.root");  typev.push_back(eEWK);
  
  fnamev.push_back("/data/blue/ksung/EWKAna/8TeV/Selection/AntiWmunu/ntuples/data_select.root"); typev.push_back(eAntiData);
  fnamev.push_back("/data/blue/ksung/EWKAna/8TeV/Selection/AntiWmunu/ntuples/wm_select.root");   typev.push_back(eAntiWmunu);
  fnamev.push_back("/data/blue/ksung/EWKAna/8TeV/Selection/AntiWmunu/ntuples/ewk_select.root");  typev.push_back(eAntiEWK);
  fnamev.push_back("/data/blue/ksung/EWKAna/8TeV/Selection/AntiWmunu/ntuples/top_select.root");  typev.push_back(eAntiEWK);


  //--------------------------------------------------------------------------------------------------------------
  // Main analysis code 
  //==============================================================================================================  
  
  // Create output directory
  gSystem->mkdir(outputDir,kTRUE);
  CPlot::sOutDir = outputDir;  
  
  //
  // Declare MET histograms
  //
  TH1D *hDataMet   = new TH1D("hDataMet","",  NBINS,0,METMAX); hDataMet->Sumw2();
  TH1D *hDataMetm  = new TH1D("hDataMetm","", NBINS,0,METMAX); hDataMetm->Sumw2();  
  TH1D *hDataMetp  = new TH1D("hDataMetp","", NBINS,0,METMAX); hDataMetp->Sumw2();
  TH1D *hWmunuMet  = new TH1D("hWmunuMet","", NBINS,0,METMAX); hWmunuMet->Sumw2();
  TH1D *hWmunuMetp = new TH1D("hWmunuMetp","",NBINS,0,METMAX); hWmunuMetp->Sumw2();
  TH1D *hWmunuMetm = new TH1D("hWmunuMetm","",NBINS,0,METMAX); hWmunuMetm->Sumw2();
  TH1D *hEWKMet    = new TH1D("hEWKMet", "",  NBINS,0,METMAX); hEWKMet->Sumw2();
  TH1D *hEWKMetp   = new TH1D("hEWKMetp", "", NBINS,0,METMAX); hEWKMetp->Sumw2();
  TH1D *hEWKMetm   = new TH1D("hEWKMetm", "", NBINS,0,METMAX); hEWKMetm->Sumw2();

  TH1D *hAntiDataMet   = new TH1D("hAntiDataMet","",  NBINS,0,METMAX); hAntiDataMet->Sumw2();
  TH1D *hAntiDataMetm  = new TH1D("hAntiDataMetm","", NBINS,0,METMAX); hAntiDataMetm->Sumw2();  
  TH1D *hAntiDataMetp  = new TH1D("hAntiDataMetp","", NBINS,0,METMAX); hAntiDataMetp->Sumw2();
  TH1D *hAntiWmunuMet  = new TH1D("hAntiWmunuMet","", NBINS,0,METMAX); hAntiWmunuMet->Sumw2();
  TH1D *hAntiWmunuMetp = new TH1D("hAntiWmunuMetp","",NBINS,0,METMAX); hAntiWmunuMetp->Sumw2();
  TH1D *hAntiWmunuMetm = new TH1D("hAntiWmunuMetm","",NBINS,0,METMAX); hAntiWmunuMetm->Sumw2();
  TH1D *hAntiEWKMet    = new TH1D("hAntiEWKMet", "",  NBINS,0,METMAX); hAntiEWKMet->Sumw2();
  TH1D *hAntiEWKMetp   = new TH1D("hAntiEWKMetp", "", NBINS,0,METMAX); hAntiEWKMetp->Sumw2();
  TH1D *hAntiEWKMetm   = new TH1D("hAntiEWKMetm", "", NBINS,0,METMAX); hAntiEWKMetm->Sumw2();

  //
  // Declare variables to read in ntuple
  //
  UInt_t  runNum, lumiSec, evtNum;
  UInt_t  npv, npu;
  Float_t genVPt, genVPhi;
  Float_t scale1fb;
  Float_t met, metPhi, sumEt, mt, u1, u2;
  Int_t   q;
  LorentzVector *lep=0;
  Float_t pfChIso, pfGamIso, pfNeuIso;
    
  TFile *infile=0;
  TTree *intree=0;

  //
  // Loop over files
  //
  for(UInt_t ifile=0; ifile<fnamev.size(); ifile++) {
    
    // Read input file and get the TTrees
    cout << "Processing " << fnamev[ifile] << "..." << endl;
    infile = new TFile(fnamev[ifile]);	  assert(infile);
    intree = (TTree*)infile->Get("Events"); assert(intree);

    intree->SetBranchAddress("runNum",   &runNum);    // event run number
    intree->SetBranchAddress("lumiSec",  &lumiSec);   // event lumi section
    intree->SetBranchAddress("evtNum",   &evtNum);    // event number
    intree->SetBranchAddress("npv",      &npv);       // number of primary vertices
    intree->SetBranchAddress("npu",      &npu);       // number of in-time PU events (MC)
    intree->SetBranchAddress("genVPt",   &genVPt);    // GEN W boson pT (signal MC)
    intree->SetBranchAddress("genVPhi",  &genVPhi);   // GEN W boson phi (signal MC)   
    intree->SetBranchAddress("scale1fb", &scale1fb);  // event weight per 1/fb (MC)
    intree->SetBranchAddress("met",      &met);       // MET
    intree->SetBranchAddress("metPhi",   &metPhi);    // phi(MET)
    intree->SetBranchAddress("sumEt",    &sumEt);     // Sum ET
    intree->SetBranchAddress("mt",       &mt);        // transverse mass
    intree->SetBranchAddress("u1",       &u1);        // parallel component of recoil
    intree->SetBranchAddress("u2",       &u2);        // perpendicular component of recoil
    intree->SetBranchAddress("q",        &q);	      // lepton charge
    intree->SetBranchAddress("lep",      &lep);       // lepton 4-vector
    intree->SetBranchAddress("pfChIso",  &pfChIso);
    intree->SetBranchAddress("pfGamIso", &pfGamIso);
    intree->SetBranchAddress("pfNeuIso", &pfNeuIso);
  
    //
    // loop over events
    //
    for(UInt_t ientry=0; ientry<intree->GetEntries(); ientry++) {
      intree->GetEntry(ientry);
      
      if(lep->Pt()        < PT_CUT)  continue;	
      if(fabs(lep->Eta()) > ETA_CUT) continue;
      
      if( (typev[ifile]==eAntiData || typev[ifile]==eAntiWmunu || typev[ifile]==eAntiEWK) &&
          (pfChIso+pfGamIso+pfNeuIso)>0.5*(lep->Pt()) ) 
	  continue;
      
      if(typev[ifile]==eData) {
        hDataMet->Fill(met);
	if(q>0) { hDataMetp->Fill(met); } 
	else    { hDataMetm->Fill(met); }
      
      } else if(typev[ifile]==eAntiData) {
        hAntiDataMet->Fill(met);
	if(q>0) { hAntiDataMetp->Fill(met); } 
	else    { hAntiDataMetm->Fill(met); }      
      
      } else {
        Double_t weight = 1;
        weight *= scale1fb*lumi;
	
	if(typev[ifile]==eWmunu) {
          Double_t corrMet=met, corrMetPhi=metPhi;
        
	  // apply recoil corrections to W MC
	  Double_t lepPt = lep->Pt();
	  //Double_t lepPt = gRandom->Gaus(lep->Pt(),0.5);  // (!) uncomment to apply scale/res corrections to MC
	  recoilCorr.Correct(corrMet,corrMetPhi,genVPt,genVPhi,lepPt,lep->Phi(),nsigma,q);
	
          Double_t nnlocorr=1;
          for(Int_t ibin=1; ibin<=hNNLOCorr->GetNbinsX(); ibin++) {
            if(genVPt >= hNNLOCorr->GetBinLowEdge(ibin) &&
               genVPt < (hNNLOCorr->GetBinLowEdge(ibin)+hNNLOCorr->GetBinWidth(ibin)))
              nnlocorr = hNNLOCorr->GetBinContent(ibin);
          }
	  //weight *= nnlocorr;  // (!) uncomment to apply NNLO corrections
	  
          hWmunuMet->Fill(corrMet,weight);
	  if(q>0) { hWmunuMetp->Fill(corrMet,weight); } 
	  else    { hWmunuMetm->Fill(corrMet,weight); }
        }
	if(typev[ifile]==eAntiWmunu) {
          Double_t corrMet=met, corrMetPhi=metPhi;
        
	  // apply recoil corrections to W MC
	  Double_t lepPt = lep->Pt();//gRandom->Gaus(lep->Pt(),0.5);
	  //Double_t lepPt = gRandom->Gaus(lep->Pt(),0.5);  // (!) uncomment to apply scale/res corrections to MC
	  recoilCorr.Correct(corrMet,corrMetPhi,genVPt,genVPhi,lepPt,lep->Phi(),nsigma,q);
          
	  Double_t nnlocorr=1;
          for(Int_t ibin=1; ibin<=hNNLOCorr->GetNbinsX(); ibin++) {
            if(genVPt >= hNNLOCorr->GetBinLowEdge(ibin) &&
               genVPt < (hNNLOCorr->GetBinLowEdge(ibin)+hNNLOCorr->GetBinWidth(ibin)))
              nnlocorr = hNNLOCorr->GetBinContent(ibin);
          }
	  //weight *= nnlocorr;  // (!) uncomment to apply NNLO corrections
          
	  hAntiWmunuMet->Fill(corrMet,weight);
	  if(q>0) { hAntiWmunuMetp->Fill(corrMet,weight); } 
	  else    { hAntiWmunuMetm->Fill(corrMet,weight); }
        }
        if(typev[ifile]==eEWK) {
          hEWKMet->Fill(met,weight);
	  if(q>0) { hEWKMetp->Fill(met,weight); }
	  else    { hEWKMetm->Fill(met,weight); }
        }
        if(typev[ifile]==eAntiEWK) {
          hAntiEWKMet->Fill(met,weight);
	  if(q>0) { hAntiEWKMetp->Fill(met,weight); }
	  else    { hAntiEWKMetm->Fill(met,weight); }
        }
      }
    }
  }  
  delete infile;
  infile=0, intree=0;   
  
  //
  // Declare fit parameters for signal and background yields
  // Note: W signal and EWK+top PDFs are constrained to the ratio described in MC
  //
  RooRealVar nSig("nSig","nSig",0.7*(hDataMet->Integral()),0,hDataMet->Integral());
  RooRealVar nQCD("nQCD","nQCD",0.3*(hDataMet->Integral()),0,hDataMet->Integral());
  RooRealVar cewk("cewk","cewk",0.1,0,5) ;
  cewk.setVal(hEWKMet->Integral()/hWmunuMet->Integral());
  cewk.setConstant(kTRUE);
  RooFormulaVar nEWK("nEWK","nEWK","cewk*nSig",RooArgList(nSig,cewk));
  RooRealVar nAntiSig("nAntiSig","nAntiSig",0.05*(hAntiDataMet->Integral()),0,hAntiDataMet->Integral());
  RooRealVar nAntiQCD("nAntiQCD","nAntiQCD",0.9*(hDataMet->Integral()),0,hDataMet->Integral());
  RooRealVar dewk("dewk","dewk",0.1,0,5) ;
  dewk.setVal(hAntiEWKMet->Integral()/hAntiWmunuMet->Integral());
  dewk.setConstant(kTRUE);
  RooFormulaVar nAntiEWK("nAntiEWK","nAntiEWK","dewk*nAntiSig",RooArgList(nAntiSig,dewk));
  
  RooRealVar nSigp("nSigp","nSigp",0.7*(hDataMetp->Integral()),0,hDataMetp->Integral());
  RooRealVar nQCDp("nQCDp","nQCDp",0.3*(hDataMetp->Integral()),0,hDataMetp->Integral());
  RooRealVar cewkp("cewkp","cewkp",0.1,0,5) ;
  cewkp.setVal(hEWKMetp->Integral()/hWmunuMetp->Integral());
  cewkp.setConstant(kTRUE);
  RooFormulaVar nEWKp("nEWKp","nEWKp","cewkp*nSigp",RooArgList(nSigp,cewkp));
  RooRealVar nAntiSigp("nAntiSigp","nAntiSigp",0.05*(hAntiDataMetp->Integral()),0,hAntiDataMetp->Integral());
  RooRealVar nAntiQCDp("nAntiQCDp","nAntiQCDp",0.9*(hAntiDataMetp->Integral()),0,hAntiDataMetp->Integral());
  RooRealVar dewkp("dewkp","dewkp",0.1,0,5) ;
  dewkp.setVal(hAntiEWKMetp->Integral()/hAntiWmunuMetp->Integral());
  dewkp.setConstant(kTRUE);
  RooFormulaVar nAntiEWKp("nAntiEWKp","nAntiEWKp","dewkp*nAntiSigp",RooArgList(nAntiSigp,dewkp));
  
  RooRealVar nSigm("nSigm","nSigm",0.7*(hDataMetm->Integral()),0,hDataMetm->Integral());
  RooRealVar nQCDm("nQCDm","nQCDm",0.3*(hDataMetm->Integral()),0,hDataMetm->Integral());
  RooRealVar cewkm("cewkm","cewkm",0.1,0,5) ;
  cewkm.setVal(hEWKMetm->Integral()/hWmunuMetm->Integral());
  cewkm.setConstant(kTRUE);
  RooFormulaVar nEWKm("nEWKm","nEWKm","cewkm*nSigm",RooArgList(nSigm,cewkm));  
  RooRealVar nAntiSigm("nAntiSigm","nAntiSigm",0.05*(hAntiDataMetm->Integral()),0,hAntiDataMetm->Integral());
  RooRealVar nAntiQCDm("nAntiQCDm","nAntiQCDm",0.9*(hAntiDataMetm->Integral()),0,hAntiDataMetm->Integral());
  RooRealVar dewkm("dewkm","dewkm",0.1,0,5) ;
  dewkm.setVal(hAntiEWKMetm->Integral()/hAntiWmunuMetm->Integral());
  dewkm.setConstant(kTRUE);
  RooFormulaVar nAntiEWKm("nAntiEWKm","nAntiEWKm","dewkm*nAntiSigm",RooArgList(nAntiSigm,dewkm));

  //
  // Construct PDFs for fitting
  //
  RooRealVar pfmet("pfmet","pfmet",0,METMAX);
  pfmet.setBins(NBINS);
   
  // Signal PDFs
  RooDataHist wmunuMet ("wmunuMET", "wmunuMET", RooArgSet(pfmet),hWmunuMet);  RooHistPdf pdfWm ("wm", "wm", pfmet,wmunuMet, 1);
  RooDataHist wmunuMetp("wmunuMETp","wmunuMETp",RooArgSet(pfmet),hWmunuMetp); RooHistPdf pdfWmp("wmp","wmp",pfmet,wmunuMetp,1);
  RooDataHist wmunuMetm("wmunuMETm","wmunuMETm",RooArgSet(pfmet),hWmunuMetm); RooHistPdf pdfWmm("wmm","wmm",pfmet,wmunuMetm,1); 
  
  // EWK+top PDFs
  RooDataHist ewkMet ("ewkMET", "ewkMET", RooArgSet(pfmet),hEWKMet);  RooHistPdf pdfEWK ("ewk", "ewk", pfmet,ewkMet, 1);
  RooDataHist ewkMetp("ewkMETp","ewkMETp",RooArgSet(pfmet),hEWKMetp); RooHistPdf pdfEWKp("ewkp","ewkp",pfmet,ewkMetp,1); 
  RooDataHist ewkMetm("ewkMETm","ewkMETm",RooArgSet(pfmet),hEWKMetm); RooHistPdf pdfEWKm("ewkm","ewkm",pfmet,ewkMetm,1); 
  
  // QCD Pdfs
  CPepeModel1 qcd("qcd",pfmet);
  CPepeModel1 qcdp("qcdp",pfmet);
  CPepeModel1 qcdm("qcdm",pfmet);
  
  // Signal + Background PDFs
  RooAddPdf pdfMet ("pdfMet", "pdfMet", RooArgList(pdfWm,pdfEWK,*(qcd.model)),   RooArgList(nSig,nEWK,nQCD));  
  RooAddPdf pdfMetp("pdfMetp","pdfMetp",RooArgList(pdfWmp,pdfEWKp,*(qcdp.model)),RooArgList(nSigp,nEWKp,nQCDp));
  RooAddPdf pdfMetm("pdfMetm","pdfMetm",RooArgList(pdfWmm,pdfEWKm,*(qcdm.model)),RooArgList(nSigm,nEWKm,nQCDm));
    
  
  // Anti-Signal PDFs
  RooDataHist awmunuMet ("awmunuMET", "awmunuMET", RooArgSet(pfmet),hAntiWmunuMet);  RooHistPdf apdfWm ("awm", "awm", pfmet,awmunuMet, 1);
  RooDataHist awmunuMetp("awmunuMETp","awmunuMETp",RooArgSet(pfmet),hAntiWmunuMetp); RooHistPdf apdfWmp("awmp","awmp",pfmet,awmunuMetp,1);
  RooDataHist awmunuMetm("awmunuMETm","awmunuMETm",RooArgSet(pfmet),hAntiWmunuMetm); RooHistPdf apdfWmm("awmm","awmm",pfmet,awmunuMetm,1); 
  
  // Anti-EWK+top PDFs
  RooDataHist aewkMet ("aewkMET", "aewkMET", RooArgSet(pfmet),hAntiEWKMet);  RooHistPdf apdfEWK ("aewk", "aewk", pfmet,aewkMet, 1);
  RooDataHist aewkMetp("aewkMETp","aewkMETp",RooArgSet(pfmet),hAntiEWKMetp); RooHistPdf apdfEWKp("aewkp","aewkp",pfmet,aewkMetp,1); 
  RooDataHist aewkMetm("aewkMETm","aewkMETm",RooArgSet(pfmet),hAntiEWKMetm); RooHistPdf apdfEWKm("aewkm","aewkm",pfmet,aewkMetm,1); 
  
  // Anti-QCD Pdfs
  CPepeModel1 aqcd("aqcd",pfmet,qcd.a1);
  CPepeModel1 aqcdp("aqcdp",pfmet,qcdp.a1);
  CPepeModel1 aqcdm("aqcdm",pfmet,qcdm.a1);
  
  // Anti-selection PDFs
  RooAddPdf apdfMet ("apdfMet", "apdfMet", RooArgList(apdfWm,apdfEWK,*(aqcd.model)),   RooArgList(nAntiSig,nAntiEWK,nAntiQCD));  
  RooAddPdf apdfMetp("apdfMetp","apdfMetp",RooArgList(apdfWmp,apdfEWKp,*(aqcdp.model)),RooArgList(nAntiSigp,nAntiEWKp,nAntiQCDp));
  RooAddPdf apdfMetm("apdfMetm","apdfMetm",RooArgList(apdfWmm,apdfEWKm,*(aqcdm.model)),RooArgList(nAntiSigm,nAntiEWKm,nAntiQCDm));
  
  // PDF for simultaneous fit
  RooCategory rooCat("rooCat","rooCat");
  rooCat.defineType("Select");
  rooCat.defineType("Anti");
  
  RooSimultaneous pdfTotal("pdfTotal","pdfTotal",rooCat);
  pdfTotal.addPdf(pdfMet, "Select");
  pdfTotal.addPdf(apdfMet,"Anti");
  
  RooSimultaneous pdfTotalp("pdfTotalp","pdfTotalp",rooCat);
  pdfTotalp.addPdf(pdfMetp, "Select");
  pdfTotalp.addPdf(apdfMetp,"Anti");
  
  RooSimultaneous pdfTotalm("pdfTotalm","pdfTotalm",rooCat);
  pdfTotalm.addPdf(pdfMetm, "Select");
  pdfTotalm.addPdf(apdfMetm,"Anti");
  
  //
  // Perform fits
  //

  RooDataHist dataMet("dataMet", "dataMet", RooArgSet(pfmet), hDataMet);
  RooDataHist antiMet("antiMet", "antiMet", RooArgSet(pfmet), hAntiDataMet);
  RooDataHist dataTotal("dataTotal","dataTotal", RooArgList(pfmet), Index(rooCat),
                        Import("Select", dataMet),
                        Import("Anti",   antiMet));
  RooFitResult *fitRes = pdfTotal.fitTo(dataTotal,Extended(),Minos(kTRUE),Save(kTRUE));
  
  RooDataHist dataMetp("dataMetp", "dataMetp", RooArgSet(pfmet), hDataMetp);
  RooDataHist antiMetp("antiMetp", "antiMetp", RooArgSet(pfmet), hAntiDataMetp);
  RooDataHist dataTotalp("dataTotalp","dataTotalp", RooArgList(pfmet), Index(rooCat),
                         Import("Select", dataMetp),
                         Import("Anti",   antiMetp));
  RooFitResult *fitResp = pdfTotalp.fitTo(dataTotalp,Extended(),Minos(kTRUE),Save(kTRUE));
  
  RooDataHist dataMetm("dataMetm", "dataMetm", RooArgSet(pfmet), hDataMetm);
  RooDataHist antiMetm("antiMetm", "antiMetm", RooArgSet(pfmet), hAntiDataMetm);
  RooDataHist dataTotalm("dataTotalm","dataTotalm", RooArgList(pfmet), Index(rooCat),
                         Import("Select", dataMetm),
                         Import("Anti",   antiMetm));
  RooFitResult *fitResm = pdfTotalm.fitTo(dataTotalm,Extended(),Minos(kTRUE),Save(kTRUE));
    
  //
  // Use histogram version of fitted PDFs to make ratio plots
  // (Will also use PDF histograms later for Chi^2 and KS tests)
  //
  TH1D *hPdfMet = (TH1D*)(pdfMet.createHistogram("hPdfMet", pfmet));
  hPdfMet->Scale((nSig.getVal()+nEWK.getVal()+nQCD.getVal())/hPdfMet->Integral());
  TH1D *hMetDiff = makeDiffHist(hDataMet,hPdfMet,"hMetDiff");
  hMetDiff->SetMarkerStyle(kFullCircle);
  hMetDiff->SetMarkerSize(0.9);
   
  TH1D *hPdfMetp = (TH1D*)(pdfMetp.createHistogram("hPdfMetp", pfmet));
  hPdfMetp->Scale((nSigp.getVal()+nEWKp.getVal()+nQCDp.getVal())/hPdfMetp->Integral());
  TH1D *hMetpDiff = makeDiffHist(hDataMetp,hPdfMetp,"hMetpDiff");
  hMetpDiff->SetMarkerStyle(kFullCircle);
  hMetpDiff->SetMarkerSize(0.9);
    
  TH1D *hPdfMetm = (TH1D*)(pdfMetm.createHistogram("hPdfMetm", pfmet));
  hPdfMetm->Scale((nSigm.getVal()+nEWKm.getVal()+nQCDm.getVal())/hPdfMetm->Integral());
  TH1D *hMetmDiff = makeDiffHist(hDataMetm,hPdfMetm,"hMetmDiff");
  hMetmDiff->SetMarkerStyle(kFullCircle); 
  hMetmDiff->SetMarkerSize(0.9);
   
  TH1D *hPdfAntiMet = (TH1D*)(apdfMet.createHistogram("hPdfAntiMet", pfmet));
  hPdfAntiMet->Scale((nAntiSig.getVal()+nAntiEWK.getVal()+nAntiQCD.getVal())/hPdfAntiMet->Integral());
  TH1D *hAntiMetDiff = makeDiffHist(hAntiDataMet,hPdfAntiMet,"hAntiMetDiff");
  hAntiMetDiff->SetMarkerStyle(kFullCircle);
  hAntiMetDiff->SetMarkerSize(0.9);
   
  TH1D *hPdfAntiMetp = (TH1D*)(apdfMetp.createHistogram("hPdfAntiMetp", pfmet));
  hPdfAntiMetp->Scale((nAntiSigp.getVal()+nAntiEWKp.getVal()+nAntiQCDp.getVal())/hPdfAntiMetp->Integral());
  TH1D *hAntiMetpDiff = makeDiffHist(hAntiDataMetp,hPdfAntiMetp,"hAntiMetpDiff");
  hAntiMetpDiff->SetMarkerStyle(kFullCircle);
  hAntiMetpDiff->SetMarkerSize(0.9);
    
  TH1D *hPdfAntiMetm = (TH1D*)(apdfMetm.createHistogram("hPdfAntiMetm", pfmet));
  hPdfAntiMetm->Scale((nAntiSigm.getVal()+nAntiEWKm.getVal()+nAntiQCDm.getVal())/hPdfAntiMetm->Integral());
  TH1D *hAntiMetmDiff = makeDiffHist(hAntiDataMetm,hPdfAntiMetm,"hAntiMetmDiff");
  hAntiMetmDiff->SetMarkerStyle(kFullCircle); 
  hAntiMetmDiff->SetMarkerSize(0.9);
   
  
  //--------------------------------------------------------------------------------------------------------------
  // Make plots 
  //==============================================================================================================  
  
  TCanvas *c = MakeCanvas("c","c",800,800);
  c->Divide(1,2,0,0);
  c->cd(1)->SetPad(0,0.3,1.0,1.0);
  c->cd(1)->SetTopMargin(0.1);
  c->cd(1)->SetBottomMargin(0.01);
  c->cd(1)->SetLeftMargin(0.15);  
  c->cd(1)->SetRightMargin(0.07);  
  c->cd(1)->SetTickx(1);
  c->cd(1)->SetTicky(1);  
  c->cd(2)->SetPad(0,0,1.0,0.3);
  c->cd(2)->SetTopMargin(0.05);
  c->cd(2)->SetBottomMargin(0.45);
  c->cd(2)->SetLeftMargin(0.15);
  c->cd(2)->SetRightMargin(0.07);
  c->cd(2)->SetTickx(1);
  c->cd(2)->SetTicky(1);
  gStyle->SetTitleOffset(1.100,"Y");
  TGaxis::SetMaxDigits(3);
  
  char ylabel[100];  // string buffer for y-axis label
  
  // label for lumi
  char lumitext[100];
  if(lumi<0.1) sprintf(lumitext,"%.1f pb^{-1}  at  #sqrt{s} = 8 TeV",lumi*1000.);
  else         sprintf(lumitext,"%.2f fb^{-1}  at  #sqrt{s} = 8 TeV",lumi);
  
  // plot colors
  Int_t linecolorW   = kOrange-3;
  Int_t fillcolorW   = kOrange-2;
  Int_t linecolorEWK = kOrange+10;
  Int_t fillcolorEWK = kOrange+7;
  Int_t linecolorQCD = kViolet+2;
  Int_t fillcolorQCD = kViolet-5;
  Int_t ratioColor   = kGray+2;
  
  //
  // Dummy histograms for TLegend
  // (I can't figure out how to properly pass RooFit objects...)
  //
  TH1D *hDummyData = new TH1D("hDummyData","",0,0,10);
  hDummyData->SetMarkerStyle(kFullCircle);
  hDummyData->SetMarkerSize(0.9);
  
  TH1D *hDummyW = new TH1D("hDummyW","",0,0,10);
  hDummyW->SetLineColor(linecolorW);
  hDummyW->SetFillColor(fillcolorW);
  hDummyW->SetFillStyle(1001);
  
  TH1D *hDummyEWK = new TH1D("hDummyEWK","",0,0,10);
  hDummyEWK->SetLineColor(linecolorEWK);
  hDummyEWK->SetFillColor(fillcolorEWK);
  hDummyEWK->SetFillStyle(1001);
  
  TH1D *hDummyQCD = new TH1D("hDummyQCD","",0,0,10);
  hDummyQCD->SetLineColor(linecolorQCD);
  hDummyQCD->SetFillColor(fillcolorQCD);
  hDummyQCD->SetFillStyle(1001);
   
  //
  // W MET plot
  //
  RooPlot *wmframe = pfmet.frame(Bins(NBINS)); 
  wmframe->GetYaxis()->SetNdivisions(505);
  dataMet.plotOn(wmframe,MarkerStyle(kFullCircle),MarkerSize(0.9),DrawOption("ZP"));
  pdfMet.plotOn(wmframe,FillColor(fillcolorW),DrawOption("F"));
  pdfMet.plotOn(wmframe,LineColor(linecolorW));
  pdfMet.plotOn(wmframe,Components(RooArgSet(pdfEWK,*(qcd.model))),FillColor(fillcolorEWK),DrawOption("F"));
  pdfMet.plotOn(wmframe,Components(RooArgSet(pdfEWK,*(qcd.model))),LineColor(linecolorEWK));
  pdfMet.plotOn(wmframe,Components(RooArgSet(*(qcd.model))),FillColor(fillcolorQCD),DrawOption("F"));
  pdfMet.plotOn(wmframe,Components(RooArgSet(*(qcd.model))),LineColor(linecolorQCD));
  pdfMet.plotOn(wmframe,Components(RooArgSet(pdfWm)),LineColor(linecolorW),LineStyle(2));
  dataMet.plotOn(wmframe,MarkerStyle(kFullCircle),MarkerSize(0.9),DrawOption("ZP"));  
  
  sprintf(ylabel,"Events / %.1f GeV",hDataMet->GetBinWidth(1));
  CPlot plotMet("fitmet",wmframe,"","",ylabel);
  plotMet.SetLegend(0.68,0.57,0.93,0.77);
  plotMet.GetLegend()->AddEntry(hDummyData,"data","PL");
  plotMet.GetLegend()->AddEntry(hDummyW,"W#rightarrow#mu#nu","F");
  plotMet.GetLegend()->AddEntry(hDummyEWK,"EWK+t#bar{t}","F");
  plotMet.GetLegend()->AddEntry(hDummyQCD,"QCD","F");
  plotMet.AddTextBox(lumitext,0.55,0.80,0.90,0.86,0);
  plotMet.AddTextBox("CMS Preliminary",0.63,0.92,0.95,0.99,0);
  plotMet.SetYRange(0.1,1.1*(hDataMet->GetMaximum()));
  plotMet.Draw(c,kFALSE,format,1);

  CPlot plotMetDiff("fitmet","","#slash{E}_{T} [GeV]","#chi");
  plotMetDiff.AddHist1D(hMetDiff,"EX0",ratioColor);
  plotMetDiff.SetYRange(-8,8);
  plotMetDiff.AddLine(0, 0,METMAX, 0,kBlack,1);
  plotMetDiff.AddLine(0, 5,METMAX, 5,kBlack,3);
  plotMetDiff.AddLine(0,-5,METMAX,-5,kBlack,3);
  plotMetDiff.Draw(c,kTRUE,format,2);
  
  plotMet.SetName("fitmetlog");
  plotMet.SetLogy();
  plotMet.SetYRange(1e-3*(hDataMet->GetMaximum()),10*(hDataMet->GetMaximum()));
  plotMet.Draw(c,kTRUE,format,1);
    
  RooPlot *awmframe = pfmet.frame(Bins(NBINS));    
  antiMet.plotOn(awmframe,MarkerStyle(kFullCircle),MarkerSize(0.9),DrawOption("ZP"));
  apdfMet.plotOn(awmframe,FillColor(fillcolorW),DrawOption("F"));
  apdfMet.plotOn(awmframe,LineColor(linecolorW));
  apdfMet.plotOn(awmframe,Components(RooArgSet(apdfEWK,*(aqcd.model))),FillColor(fillcolorEWK),DrawOption("F"));
  apdfMet.plotOn(awmframe,Components(RooArgSet(apdfEWK,*(aqcd.model))),LineColor(linecolorEWK));
  apdfMet.plotOn(awmframe,Components(RooArgSet(*(aqcd.model))),FillColor(fillcolorQCD),DrawOption("F"));
  apdfMet.plotOn(awmframe,Components(RooArgSet(*(aqcd.model))),LineColor(linecolorQCD));
  apdfMet.plotOn(awmframe,Components(RooArgSet(apdfWm)),LineColor(linecolorW),LineStyle(2));
  antiMet.plotOn(awmframe,MarkerStyle(kFullCircle),MarkerSize(0.9),DrawOption("ZP"));  
  
  sprintf(ylabel,"Events / %.1f GeV",hAntiDataMet->GetBinWidth(1));
  CPlot plotAntiMet("fitantimet",awmframe,"","",ylabel);
  plotAntiMet.SetLegend(0.68,0.57,0.93,0.77);
  plotAntiMet.GetLegend()->AddEntry(hDummyData,"data","PL");
  plotAntiMet.GetLegend()->AddEntry(hDummyW,"W#rightarrow#mu#nu","F");
  plotAntiMet.GetLegend()->AddEntry(hDummyEWK,"EWK+t#bar{t}","F");
  plotAntiMet.GetLegend()->AddEntry(hDummyQCD,"QCD","F");
  plotAntiMet.AddTextBox(lumitext,0.55,0.80,0.90,0.86,0);
  plotAntiMet.AddTextBox("CMS Preliminary",0.63,0.92,0.95,0.99,0);
  plotAntiMet.SetYRange(0.1,1.1*(hAntiDataMet->GetMaximum())); 
  plotAntiMet.Draw(c,kFALSE,format,1);

  CPlot plotAntiMetDiff("fitantimet","","#slash{E}_{T} [GeV]","#chi");
  plotAntiMetDiff.AddHist1D(hMetDiff,"EX0",ratioColor);
  plotAntiMetDiff.SetYRange(-8,8);
  plotAntiMetDiff.AddLine(0, 0,METMAX, 0,kBlack,1);
  plotAntiMetDiff.AddLine(0, 5,METMAX, 5,kBlack,3);
  plotAntiMetDiff.AddLine(0,-5,METMAX,-5,kBlack,3);
  plotAntiMetDiff.Draw(c,kTRUE,format,2);
  
  plotAntiMet.SetName("fitantimetlog");
  plotAntiMet.SetLogy();
  plotAntiMet.SetYRange(1e-3*(hAntiDataMet->GetMaximum()),10*(hAntiDataMet->GetMaximum()));
  plotAntiMet.Draw(c,kTRUE,format,1);
    
  //
  // W+ MET plot
  //
  RooPlot *wmpframe = pfmet.frame(Bins(NBINS));
  wmpframe->GetYaxis()->SetNdivisions(505);
  dataMetp.plotOn(wmpframe,MarkerStyle(kFullCircle),MarkerSize(0.9),DrawOption("ZP"));
  pdfMetp.plotOn(wmpframe,FillColor(fillcolorW),DrawOption("F"));
  pdfMetp.plotOn(wmpframe,LineColor(linecolorW));
  pdfMetp.plotOn(wmpframe,Components(RooArgSet(pdfEWKp,*(qcdp.model))),FillColor(fillcolorEWK),DrawOption("F"));
  pdfMetp.plotOn(wmpframe,Components(RooArgSet(pdfEWKp,*(qcdp.model))),LineColor(linecolorEWK));
  pdfMetp.plotOn(wmpframe,Components(RooArgSet(*(qcdp.model))),FillColor(fillcolorQCD),DrawOption("F"));
  pdfMetp.plotOn(wmpframe,Components(RooArgSet(*(qcdp.model))),LineColor(linecolorQCD));
  pdfMetp.plotOn(wmpframe,Components(RooArgSet(pdfWmp)),LineColor(linecolorW),LineStyle(2));
  dataMetp.plotOn(wmpframe,MarkerStyle(kFullCircle),MarkerSize(0.9),DrawOption("ZP"));  
  
  sprintf(ylabel,"Events / %.1f GeV",hDataMetp->GetBinWidth(1));
  CPlot plotMetp("fitmetp",wmpframe,"","",ylabel);
  plotMetp.SetLegend(0.68,0.57,0.93,0.77);
  plotMetp.GetLegend()->AddEntry(hDummyData,"data","PL");
  plotMetp.GetLegend()->AddEntry(hDummyW,"W^{+}#rightarrow#mu^{+}#nu","F");
  plotMetp.GetLegend()->AddEntry(hDummyEWK,"EWK+t#bar{t}","F");
  plotMetp.GetLegend()->AddEntry(hDummyQCD,"QCD","F");
  plotMetp.AddTextBox(lumitext,0.55,0.80,0.90,0.86,0);
  plotMetp.AddTextBox("CMS Preliminary",0.63,0.92,0.95,0.99,0);
//  plotMetp.SetYRange(0.1,1.1*(hDataMetp->GetMaximum()));
plotMetp.SetYRange(0.1,4100);
  plotMetp.Draw(c,kFALSE,format,1);

  CPlot plotMetpDiff("fitmetp","","#slash{E}_{T} [GeV]","#chi");
  plotMetpDiff.AddHist1D(hMetpDiff,"EX0",ratioColor);
  plotMetpDiff.SetYRange(-8,8);
  plotMetpDiff.AddLine(0, 0,METMAX, 0,kBlack,1);
  plotMetpDiff.AddLine(0, 5,METMAX, 5,kBlack,3);
  plotMetpDiff.AddLine(0,-5,METMAX,-5,kBlack,3);
  plotMetpDiff.Draw(c,kTRUE,format,2);
  
  plotMetp.SetName("fitmetplog");
  plotMetp.SetLogy();
  plotMetp.SetYRange(1e-3*(hDataMetp->GetMaximum()),10*(hDataMetp->GetMaximum()));
  plotMetp.Draw(c,kTRUE,format,1);

  RooPlot *awmpframe = pfmet.frame(Bins(NBINS));    
  antiMetp.plotOn(awmpframe,MarkerStyle(kFullCircle),MarkerSize(0.9),DrawOption("ZP"));
  apdfMetp.plotOn(awmpframe,FillColor(fillcolorW),DrawOption("F"));
  apdfMetp.plotOn(awmpframe,LineColor(linecolorW));
  apdfMetp.plotOn(awmpframe,Components(RooArgSet(apdfEWKp,*(aqcdp.model))),FillColor(fillcolorEWK),DrawOption("F"));
  apdfMetp.plotOn(awmpframe,Components(RooArgSet(apdfEWKp,*(aqcdp.model))),LineColor(linecolorEWK));
  apdfMetp.plotOn(awmpframe,Components(RooArgSet(*(aqcdp.model))),FillColor(fillcolorQCD),DrawOption("F"));
  apdfMetp.plotOn(awmpframe,Components(RooArgSet(*(aqcdp.model))),LineColor(linecolorQCD));
  apdfMetp.plotOn(awmpframe,Components(RooArgSet(apdfWmp)),LineColor(linecolorW),LineStyle(2));
  antiMetp.plotOn(awmpframe,MarkerStyle(kFullCircle),MarkerSize(0.9),DrawOption("ZP"));  
  
  sprintf(ylabel,"Events / %.1f GeV",hAntiDataMetp->GetBinWidth(1));
  CPlot plotAntiMetp("fitantimetp",awmpframe,"","",ylabel);
  plotAntiMetp.SetLegend(0.68,0.57,0.93,0.77);
  plotAntiMetp.GetLegend()->AddEntry(hDummyData,"data","PL");
  plotAntiMetp.GetLegend()->AddEntry(hDummyW,"W^{+}#rightarrow#mu^{+}#nu","F");
  plotAntiMetp.GetLegend()->AddEntry(hDummyEWK,"EWK+t#bar{t}","F");
  plotAntiMetp.GetLegend()->AddEntry(hDummyQCD,"QCD","F");
  plotAntiMetp.AddTextBox(lumitext,0.55,0.80,0.90,0.86,0);
  plotAntiMetp.AddTextBox("CMS Preliminary",0.63,0.92,0.95,0.99,0);
//  plotAntiMetp.SetYRange(0.1,1.1*(hAntiDataMetp->GetMaximum()));
plotAntiMetp.SetYRange(0.1,1500);
  plotAntiMetp.Draw(c,kFALSE,format,1);

  CPlot plotAntiMetpDiff("fitantimetp","","#slash{E}_{T} [GeV]","#chi");
  plotAntiMetpDiff.AddHist1D(hAntiMetpDiff,"EX0",ratioColor);
  plotAntiMetpDiff.SetYRange(-8,8);
  plotAntiMetpDiff.AddLine(0, 0,METMAX, 0,kBlack,1);
  plotAntiMetpDiff.AddLine(0, 5,METMAX, 5,kBlack,3);
  plotAntiMetpDiff.AddLine(0,-5,METMAX,-5,kBlack,3);
  plotAntiMetpDiff.Draw(c,kTRUE,format,2);
  
  plotAntiMetp.SetName("fitantimetplog");
  plotAntiMetp.SetLogy();
  plotAntiMetp.SetYRange(1e-3*(hAntiDataMetp->GetMaximum()),10*(hAntiDataMetp->GetMaximum()));
  plotAntiMetp.Draw(c,kTRUE,format,1);
  
  //
  // W- MET plot
  //
  RooPlot *wmmframe = pfmet.frame(Bins(NBINS)); 
  wmmframe->GetYaxis()->SetNdivisions(505);
  dataMetm.plotOn(wmmframe,MarkerStyle(kFullCircle),MarkerSize(0.9),DrawOption("ZP"));
  pdfMetm.plotOn(wmmframe,FillColor(fillcolorW),DrawOption("F"));
  pdfMetm.plotOn(wmmframe,LineColor(linecolorW));
  pdfMetm.plotOn(wmmframe,Components(RooArgSet(pdfEWKm,*(qcdm.model))),FillColor(fillcolorEWK),DrawOption("F"));
  pdfMetm.plotOn(wmmframe,Components(RooArgSet(pdfEWKm,*(qcdm.model))),LineColor(linecolorEWK));
  pdfMetm.plotOn(wmmframe,Components(RooArgSet(*(qcdm.model))),FillColor(fillcolorQCD),DrawOption("F"));
  pdfMetm.plotOn(wmmframe,Components(RooArgSet(*(qcdm.model))),LineColor(linecolorQCD));
  pdfMetm.plotOn(wmmframe,Components(RooArgSet(pdfWmm)),LineColor(linecolorW),LineStyle(2));
  dataMetm.plotOn(wmmframe,MarkerStyle(kFullCircle),MarkerSize(0.9),DrawOption("ZP"));
  
  sprintf(ylabel,"Events / %.1f GeV",hDataMetm->GetBinWidth(1));
  CPlot plotMetm("fitmetm",wmmframe,"","",ylabel);
  plotMetm.SetLegend(0.68,0.57,0.93,0.77);
  plotMetm.GetLegend()->AddEntry(hDummyData,"data","PL");
  plotMetm.GetLegend()->AddEntry(hDummyW,"W^{-}#rightarrow#mu^{-}#bar{#nu}","F");
  plotMetm.GetLegend()->AddEntry(hDummyEWK,"EWK+t#bar{t}","F");
  plotMetm.GetLegend()->AddEntry(hDummyQCD,"QCD","F");
  plotMetm.AddTextBox(lumitext,0.55,0.80,0.90,0.86,0);
  plotMetm.AddTextBox("CMS Preliminary",0.63,0.92,0.95,0.99,0);
//  plotMetm.SetYRange(0.1,1.1*(hDataMetm->GetMaximum()));
plotMetm.SetYRange(0.1,4100);
  plotMetm.Draw(c,kFALSE,format,1);

  CPlot plotMetmDiff("fitmetm","","#slash{E}_{T} [GeV]","#chi");
  plotMetmDiff.AddHist1D(hMetmDiff,"EX0",ratioColor);
  plotMetmDiff.SetYRange(-8,8);
  plotMetmDiff.AddLine(0, 0,METMAX, 0,kBlack,1);
  plotMetmDiff.AddLine(0, 5,METMAX, 5,kBlack,3);
  plotMetmDiff.AddLine(0,-5,METMAX,-5,kBlack,3);
  plotMetmDiff.Draw(c,kTRUE,format,2);
  
  plotMetm.SetName("fitmetmlog");
  plotMetm.SetLogy();
  plotMetm.SetYRange(1e-3*(hDataMetm->GetMaximum()),10*(hDataMetm->GetMaximum()));
  plotMetm.Draw(c,kTRUE,format,1);

  RooPlot *awmmframe = pfmet.frame(Bins(NBINS)); 
  antiMetm.plotOn(awmmframe,MarkerStyle(kFullCircle),MarkerSize(0.9),DrawOption("ZP"));
  apdfMetm.plotOn(awmmframe,FillColor(fillcolorW),DrawOption("F"));
  apdfMetm.plotOn(awmmframe,LineColor(linecolorW));
  apdfMetm.plotOn(awmmframe,Components(RooArgSet(apdfEWKm,*(aqcdm.model))),FillColor(fillcolorEWK),DrawOption("F"));
  apdfMetm.plotOn(awmmframe,Components(RooArgSet(apdfEWKm,*(aqcdm.model))),LineColor(linecolorEWK));
  apdfMetm.plotOn(awmmframe,Components(RooArgSet(*(aqcdm.model))),FillColor(fillcolorQCD),DrawOption("F"));
  apdfMetm.plotOn(awmmframe,Components(RooArgSet(*(aqcdm.model))),LineColor(linecolorQCD));
  apdfMetm.plotOn(awmmframe,Components(RooArgSet(apdfWmm)),LineColor(linecolorW),LineStyle(2));
  antiMetm.plotOn(awmmframe,MarkerStyle(kFullCircle),MarkerSize(0.9),DrawOption("ZP"));
  
  sprintf(ylabel,"Events / %.1f GeV",hDataMetm->GetBinWidth(1));
  CPlot plotAntiMetm("fitantimetm",awmmframe,"","",ylabel);
  plotAntiMetm.SetLegend(0.68,0.57,0.93,0.77);
  plotAntiMetm.GetLegend()->AddEntry(hDummyData,"data","PL");
  plotAntiMetm.GetLegend()->AddEntry(hDummyW,"W^{-}#rightarrow#mu^{-}#bar{#nu}","F");
  plotAntiMetm.GetLegend()->AddEntry(hDummyEWK,"EWK+t#bar{t}","F");
  plotAntiMetm.GetLegend()->AddEntry(hDummyQCD,"QCD","F");
  plotAntiMetm.AddTextBox(lumitext,0.55,0.80,0.90,0.86,0);
  plotAntiMetm.AddTextBox("CMS Preliminary",0.63,0.92,0.95,0.99,0);
//  plotAntiMetm.SetYRange(0.1,1.1*(hAntiDataMetm->GetMaximum()));
plotAntiMetm.SetYRange(0.1,1500);
  plotAntiMetm.Draw(c,kFALSE,format,1);

  CPlot plotAntiMetmDiff("fitantimetm","","#slash{E}_{T} [GeV]","#chi");
  plotAntiMetmDiff.AddHist1D(hAntiMetmDiff,"EX0",ratioColor);
  plotAntiMetmDiff.SetYRange(-8,8);
  plotAntiMetmDiff.AddLine(0, 0,METMAX, 0,kBlack,1);
  plotAntiMetmDiff.AddLine(0, 5,METMAX, 5,kBlack,3);
  plotAntiMetmDiff.AddLine(0,-5,METMAX,-5,kBlack,3);
  plotAntiMetmDiff.Draw(c,kTRUE,format,2);
  
  plotAntiMetm.SetName("fitantimetmlog");
  plotAntiMetm.SetLogy();
  plotAntiMetm.SetYRange(1e-3*(hAntiDataMetm->GetMaximum()),10*(hAntiDataMetm->GetMaximum()));
  plotAntiMetm.Draw(c,kTRUE,format,1);

    
  //--------------------------------------------------------------------------------------------------------------
  // Output
  //==============================================================================================================
   
  cout << "*" << endl;
  cout << "* SUMMARY" << endl;
  cout << "*--------------------------------------------------" << endl;  
  
  //
  // Write fit results
  //
  ofstream txtfile;
  char txtfname[100];    
  
  ios_base::fmtflags flags;
  
  Double_t chi2prob, chi2ndf;
  Double_t ksprob, ksprobpe;
  
  chi2prob = hDataMet->Chi2Test(hPdfMet,"PUW");
  chi2ndf  = hDataMet->Chi2Test(hPdfMet,"CHI2/NDFUW");
  ksprob   = hDataMet->KolmogorovTest(hPdfMet);
  ksprobpe = hDataMet->KolmogorovTest(hPdfMet,"DX");
  sprintf(txtfname,"%s/fitresWm.txt",CPlot::sOutDir.Data());
  txtfile.open(txtfname);
  assert(txtfile.is_open());
  
  flags = txtfile.flags();
  txtfile << setprecision(10);
  txtfile << " *** Yields *** " << endl;
  txtfile << "Selected: " << hDataMet->Integral() << endl;
  txtfile << "  Signal: " << nSig.getVal() << " +/- " << nSig.getPropagatedError(*fitRes) << endl;
  txtfile << "     QCD: " << nQCD.getVal() << " +/- " << nQCD.getPropagatedError(*fitRes) << endl;
  txtfile << "   Other: " << nEWK.getVal() << " +/- " << nEWK.getPropagatedError(*fitRes) << endl;
  txtfile << endl;
  txtfile.flags(flags);
  
  fitRes->printStream(txtfile,RooPrintable::kValue,RooPrintable::kVerbose);
  txtfile << endl;
  printCorrelations(txtfile, fitRes);
  txtfile << endl;
  printChi2AndKSResults(txtfile, chi2prob, chi2ndf, ksprob, ksprobpe);
  txtfile.close();
  
  chi2prob = hDataMetp->Chi2Test(hPdfMetp,"PUW");
  chi2ndf  = hDataMetp->Chi2Test(hPdfMetp,"CHI2/NDFUW");
  ksprob   = hDataMetp->KolmogorovTest(hPdfMetp);
  ksprobpe = hDataMetp->KolmogorovTest(hPdfMetp,"DX");  
  sprintf(txtfname,"%s/fitresWmp.txt",CPlot::sOutDir.Data());
  txtfile.open(txtfname);
  assert(txtfile.is_open());
  
  flags = txtfile.flags();
  txtfile << setprecision(10);
  txtfile << " *** Yields *** " << endl;
  txtfile << "Selected: " << hDataMetp->Integral() << endl;
  txtfile << "  Signal: " << nSigp.getVal() << " +/- " << nSigp.getPropagatedError(*fitResp) << endl;
  txtfile << "     QCD: " << nQCDp.getVal() << " +/- " << nQCDp.getPropagatedError(*fitResp) << endl;
  txtfile << "   Other: " << nEWKp.getVal() << " +/- " << nEWKp.getPropagatedError(*fitResp) << endl;
  txtfile << endl; 
  txtfile.flags(flags);
  
  fitResp->printStream(txtfile,RooPrintable::kValue,RooPrintable::kVerbose);
  txtfile << endl;
  printCorrelations(txtfile, fitResp);
  txtfile << endl;
  printChi2AndKSResults(txtfile, chi2prob, chi2ndf, ksprob, ksprobpe);
  txtfile.close();

  chi2prob = hDataMetm->Chi2Test(hPdfMetm,"PUW");
  chi2ndf  = hDataMetm->Chi2Test(hPdfMetm,"CHI2/NDFUW");
  ksprob   = hDataMetm->KolmogorovTest(hPdfMetm);
  ksprobpe = hDataMetm->KolmogorovTest(hPdfMetm,"DX");  
  sprintf(txtfname,"%s/fitresWmm.txt",CPlot::sOutDir.Data());
  txtfile.open(txtfname);
  assert(txtfile.is_open());
  
  flags = txtfile.flags();
  txtfile << setprecision(10);
  txtfile << " *** Yields *** " << endl;
  txtfile << "Selected: " << hDataMetm->Integral() << endl;
  txtfile << "  Signal: " << nSigm.getVal() << " +/- " << nSigm.getPropagatedError(*fitResm) << endl;
  txtfile << "     QCD: " << nQCDm.getVal() << " +/- " << nQCDm.getPropagatedError(*fitResm) << endl;
  txtfile << "   Other: " << nEWKm.getVal() << " +/- " << nEWKm.getPropagatedError(*fitResm) << endl;
  txtfile << endl;
  txtfile.flags(flags);
  
  fitResm->printStream(txtfile,RooPrintable::kValue,RooPrintable::kVerbose);
  txtfile << endl;
  printCorrelations(txtfile, fitResm);
  txtfile << endl;
  printChi2AndKSResults(txtfile, chi2prob, chi2ndf, ksprob, ksprobpe);
  txtfile.close();

  makeHTML(outputDir);
  
  cout << endl;
  cout << "  <> Output saved in " << outputDir << "/" << endl;    
  cout << endl;     
  
  gBenchmark->Show("fitWm");
}
Пример #18
0
LineStyle LineStyle::defaultAxesCurve ()
{
  return LineStyle (DEFAULT_LINE_WIDTH,
                    COLOR_PALETTE_TRANSPARENT,
                    CONNECT_AS_FUNCTION_SMOOTH); // Same default color as used for PointStyle axes curve default
}