Esempio n. 1
0
TCanvas* plotting36GS( bool logScale=false ) 
{

  std::cout << "plotting mu + standalone " << std::endl;
  TGaxis::SetMaxDigits(3);

  // channels, ordered as in the legend
  vector<TString> channels;  
  vector<TString> hnames; 
  vector<TString> type;

  map<TString,int> fillColor_;
  map<TString,int> lineColor_;
  int lineWidth1(2);
  int lineWidth2(1);

  bool salamanderStyle=true;
  if( salamanderStyle )
    {
      fillColor_["Signal"] = kOrange-2;
      lineColor_["Signal"] = kOrange+3;
      
      fillColor_["EWK"] = kOrange+7;
      lineColor_["EWK"] = kOrange+3;
      
      fillColor_["QCD"] = kViolet-5;
      lineColor_["QCD"] = kViolet+3;
      
      fillColor_["ttbar"] = kRed+2;
      lineColor_["ttbar"] = kRed+4;
      
      fillColor_["gamma+jet"] = kMagenta+4;
      lineColor_["gamma+jet"] = kViolet+3;
    }
  else
    {
      lineWidth1 = 2;
      lineWidth2 = 2;

      fillColor_["Signal"] = kPink+6;
      lineColor_["Signal"] = kMagenta+3;
      
      fillColor_["EWK"] = kAzure+8;
      lineColor_["EWK"] = kAzure+4;
      
      fillColor_["QCD"] = kYellow-7;
      lineColor_["QCD"] = kYellow+4;
      
      fillColor_["ttbar"] = kGreen;
      lineColor_["ttbar"] = kGreen+2;
      
      fillColor_["gamma+jet"] = kOrange;
      lineColor_["gamma+jet"] = kOrange+2;
    }

  // root file, where the data is
  TString fname("root/");

  // histogram limits, in linear and logarithmic
  int nbin_(100);
  float xmin_(0.), xmax_(0.); 
  float ymin_(0.), ymax_(0.); 
  float yminl_(0.), ymaxl_(0.); 

  // titles and axis, marker size
  TString xtitle;
  TString ytitle;
  int ndivx(510);
  int ndivy(510);
  float markerSize(0.);
  float titleOffset(1.);

  float r0_ = 1.;
  float dr_ = 0.3;
  if( use_chi )
    {
      r0_ = 0.;
      dr_ = 7.5;
      //dr_ = 3.0;
    }

  // canvas name
  TString cname("");
  TString ctitle;

  // legend position and scale;
  float xl_  = 0.;
  float yl_  = 0.; 	   
  float scalel_ = 0.0;

  {
    if( logScale )
      //      fname += "Zmumu_40-200_36pb";
      fname += "Zmusta_36pb";
    else
      fname += "Zmusta_36pb";

    if( logScale )
      {
	lineWidth1 = 1;
	lineWidth2 = 1;
      }
    
    channels.push_back("Zmumu"); 
    hnames.push_back("   Z #rightarrow #mu^{+}#mu^{-}"); 
    type.push_back("Signal"); 
    
    bool revert(false);
    if( logScale )
      {
 	if( revert )
 	  {
 	    channels.push_back("EWK");          
 	    hnames.push_back("   EWK");                
	    type.push_back("EWK"); 
	    
 	    channels.push_back("tt");              
 	    hnames.push_back("   t#bar{t}");         
	    type.push_back("ttbar"); 

	     	    channels.push_back("QCD");              
	     	    hnames.push_back("   QCD");              
	    	    type.push_back("QCD"); 
 	  }
 	else
 	  {
 	    channels.push_back("EWK");          
 	    hnames.push_back("   EWK");                
	    type.push_back("EWK"); 
	    
 	    channels.push_back("tt");              
 	    hnames.push_back("   t#bar{t}");         
	    type.push_back("ttbar"); 
	    
	    channels.push_back("QCD");              
	     	    hnames.push_back("   QCD");              
	    	    type.push_back("QCD"); 	  
	      
 	  }
       }
    
    if( !logScale )
      {
	// lin scale
	xmin_ = 60;
	xmax_ = 120;
	ymin_ = 0.01;
	ymax_ = 2100;

  }
    else
      {	
	// log scale
	xmin_ = 40;
	xmax_ = 200;
	yminl_ = 0.08;
	ymaxl_ = 3000;

      }

    xtitle = "M(#mu^{+}#mu^{-})    [GeV]";
    ytitle = "number of events /";    


    ndivx = 504;
    if( logScale )
      {
	ytitle += "5 GeV";
	ndivy = 510;
      }
    else
      {
	ytitle += " GeV";
	ndivy = 506;
      }
    
    if( logScale )
      {
	markerSize = 0.48;
      }
    else
      {	
	markerSize = 0.75;
      }
    
    cname += "Zmusta";
    ctitle = "Z to mu sta analysis";
    
    if( logScale )
      {
	xl_ = 0.60;
	yl_ = 0.50;
	scalel_ = 0.065;
      }
    else
      {
	xl_ = 0.22;
	yl_ = 0.50;
	scalel_ = 0.072;
      }
  }

  if( logScale ) cname += "MuSta_log";
  else           cname += "MuStaNotInThePAPER_lin";

  //Open the root file containing histograms and graphs
  fname += ".root";
  TFile* f_ = TFile::Open(fname,"READ");

  TCanvas* c_ = new TCanvas(cname,ctitle,300,300,479,510);
  c_->SetLeftMargin(  87./479 );
  c_->SetRightMargin( 42./479 );
  c_->SetTopMargin(  30./510 );
  c_->SetBottomMargin( 80./510 ); 
  c_->SetFillColor(0);
  c_->SetTickx(1);
  c_->SetTicky(1);
  c_->SetFrameFillStyle(0);
  c_->SetFrameLineWidth(2);
  c_->SetFrameBorderMode(0);
  Double_t scale = 4;
  Double_t wbin = 42*scale;
  Double_t left  = 8*scale;
  Double_t right = 5*scale;
  Double_t h1 = 135*scale;
  Double_t h2 = 45*scale;
  Double_t top1 = 15*scale;
  Double_t bot1 = 3*scale;
  Double_t top2 = 3*scale;
  //  Double_t bot1 = 0*scale;
  //  Double_t top2 = 0*scale;
  Double_t bot2 = 80*scale;
  Double_t W = left + wbin + right;
  Double_t H = h1 + h2;
  Double_t s[2] = {1, h1/h2 };

  TPad* pad[2];
  pad[0] = new TPad( "top", "top", 
		     0, h2/H, 1, 1,
		     kWhite,0,0);
  pad[0]->SetLeftMargin(  left/W );
  pad[0]->SetRightMargin( right/W );
  pad[0]->SetTopMargin(  top1/H );
  pad[0]->SetBottomMargin( bot1/H );

  pad[1] = new TPad( "bottom", "bottom", 
		     0, 0, 1, h2/H,
		     kWhite,0,0);
  pad[1]->SetLeftMargin(  left/W );
  pad[1]->SetRightMargin( right/W );
  pad[1]->SetTopMargin(  top2/H );
  pad[1]->SetBottomMargin( bot2/H );
  pad[1]->SetGridy();

  for( int ii=0; ii<2; ii++ )
    {
      pad[ii]->SetFillColor(0);
      pad[ii]->SetTickx(1);
      pad[ii]->SetTicky(1);
      pad[ii]->SetFrameFillStyle(0);
      pad[ii]->SetFrameLineWidth(2);
      pad[ii]->SetFrameBorderMode(0);
      pad[ii]->SetFrameFillStyle(0);
      pad[ii]->SetFrameLineWidth(2);
      pad[ii]->SetFrameBorderMode(0);
    }

  // a dummy histogram with the correct x axis
  // Warning: setTDRstyle() must be called before
  TH1F* h_= new TH1F( "bidon", "bidon", nbin_, xmin_, xmax_ );
  TAxis* ax_ = h_->GetXaxis();
  TAxis* ay_ = h_->GetYaxis();

  ax_->SetTitle(xtitle);
  ax_->CenterTitle();
  ax_->SetTitleOffset(1.0);
  ax_->SetNdivisions(ndivx);

  ay_->SetTitle(ytitle);
  ay_->CenterTitle();
  ay_->SetNdivisions(ndivy);
  ay_->SetTitleOffset(titleOffset);
  ay_->SetLabelOffset(0.015);

  // fetch histograms and dress them
  vector<TH1F*> histos;

  size_t nChan=channels.size();   
  for( size_t ii=0;ii<nChan;ii++)
    {
      TH1F* tmp = (TH1F*)f_->Get(channels[ii]);      
      tmp->SetFillColor( fillColor_[type[ii]] );
      tmp->SetLineColor( lineColor_[type[ii]] );
      tmp->SetLineWidth( lineWidth2 );
      histos.push_back(tmp);
    }

  //
  // stack histograms
  //
  TH1* h_stack = (TH1*) histos[nChan-1]->Clone();
  h_stack -> Reset();

  TString stackName_ = TString("Mll");
  vector<TH1*> listOfStackedHists;
  for( size_t ii=0; ii<nChan; ii++ )
    {
      TH1* hh_ = (TH1*) histos[nChan-ii-1]->Clone();

      stackName_ += "_";
      stackName_ += hh_->GetName();	  	  

      TAxis* xaxis = h_stack->GetXaxis();
      for( int iBin=1; iBin<=xaxis->GetNbins(); iBin++ )
	{
	  hh_ -> AddBinContent( iBin, h_stack->GetBinContent( iBin ) );
	}        

      hh_->SetName( stackName_ );
      delete h_stack;
      h_stack = hh_;
      listOfStackedHists.push_back( (TH1*)hh_->Clone() );
    }
  delete h_stack;
  
  TH1* totalHisto = listOfStackedHists[nChan-1];

  // colors the stacked histogram
  totalHisto->SetLineColor( lineColor_["Signal"] );
  totalHisto->SetLineWidth( lineWidth1 );
  
  // The data points are presented as a TGraph 
  // - error bars indicate the Poisson confidence interval at 68%
  // - bins with zero entry are removed
  TH1* hdata = (TH1*) f_->Get("hdata");
  // hdata->Sumw2();
  //hdata->Rebin(2);
  RooHist* roohist;
  TGraphAsymmErrors* dataGraph;

  roohist = new RooHist((*hdata));

  int Nn0=0;
  vector<double> vY;
  vector<double> vX;
  vector<double > veY;
  vector<double > veX;
  vector<double> tmp(0,2);

  for(int ip=0;ip<roohist->GetN();ip++) 
    {
      double Y,X;
      roohist->GetPoint(ip,X,Y);
      
      if(Y!=0) 
	{
	  Nn0++;
	  
	  vY.push_back(Y);
	  vX.push_back(X);
	  veX.push_back( roohist->GetErrorXlow(ip) );
	  veX.push_back( roohist->GetErrorXhigh(ip) );
	  veY.push_back( roohist->GetErrorYlow(ip) );
	  veY.push_back( roohist->GetErrorYhigh(ip) );
	}
    }
  dataGraph=new TGraphAsymmErrors(Nn0);
  for(int ip=0;ip<Nn0;ip++) 
    {
      dataGraph->SetPoint(ip,vX[ip],vY[ip]);      
      dataGraph->SetPointError(ip,veX[ip*2],veX[ip*2+1],veY[ip*2],veY[ip*2+1]);
    }
  dataGraph->SetName("data");

  dataGraph->SetMarkerStyle(kFullCircle);
  dataGraph->SetMarkerColor(kBlack);
  dataGraph->SetMarkerSize(markerSize);

  TGraph* dummyGraph = (TGraph*) dataGraph->Clone("dummyGraph");
  dummyGraph->SetLineColor(0);
  dummyGraph->SetMarkerSize(1.5*markerSize);

  // Remove the horizontal bars (at Michael's request)
  double x_(0), y_(0);
  for( int ii=0; ii<dataGraph->GetN(); ii++ )
    {
      dataGraph->SetPointEXlow(ii,0);
      dataGraph->SetPointEXhigh(ii,0);
      dataGraph->GetPoint(ii,x_,y_ );
      if( y_==0 )
	{
	  dataGraph->RemovePoint( ii );
	  ii--;
	}	  
    }

  // get the ratio data/fit
  TGraphAsymmErrors* ratioGraph = (TGraphAsymmErrors*) dataGraph->Clone("ratio");
  TH1* hfit = totalHisto;
  for( int ii=0; ii<dataGraph->GetN(); ii++ )
    {
      dataGraph->GetPoint(ii,x_,y_ );
      ratioGraph->SetPointEYlow(ii,0);
      ratioGraph->SetPointEYhigh(ii,0);
      ratioGraph->SetPoint(ii,x_,0 );
      double eyl_ = dataGraph->GetErrorYlow(ii);
      double eyh_ = dataGraph->GetErrorYhigh(ii);
      int jj = hfit->FindBin(x_);
      float fit_ = hfit->GetBinContent( jj );
      if( fit_>0 )
	{
	  if( use_chi )
	    {
	      ratioGraph->SetPointEYlow(ii,eyl_/sqrt(fit_));
	      ratioGraph->SetPointEYhigh(ii,eyh_/sqrt(fit_));
	      ratioGraph->SetPoint(ii,x_,(y_-fit_)/sqrt(fit_) );
	    }
	  else
	    {
	      ratioGraph->SetPointEYlow(ii,eyl_/fit_);
	      ratioGraph->SetPointEYhigh(ii,eyh_/fit_);
	      ratioGraph->SetPoint(ii,x_,y_/fit_ );
	    }
	}
      //      cout << ii << " ratio=" << ratioGraph->GetY()[ii] 
      //       	   << "+" << ratioGraph->GetEYhigh()[ii] 
      //	   << "-" << ratioGraph->GetEYlow()[ii] << endl;
    }

  TH1* hratio_ = (TH1*) h_->Clone("hratio");
  ax_->SetLabelOffset(99);
  ax_->SetTitleOffset(99);

  //
  // now plotting
  //  
  c_->Draw();
  c_->cd();

  TPad* p_ = pad[0];
  p_->Draw();
  p_->cd();

  if( logScale )
    {
      p_->SetLogy(true);
    }
  else
    {
      p_->SetLogy(false);
    }

  if( !logScale )
    {
      h_->GetYaxis()->SetRangeUser(ymin_+0.001*(ymax_-ymin_),ymax_);
    }
  else
    {
      h_->GetYaxis()->SetRangeUser(yminl_,ymaxl_);
    }

  h_->Draw();

  float dxl_ = scalel_*3.5;
  float dyl_ = scalel_*1.8;
  if( logScale )
    {
      dxl_ = scalel_*4;
      dyl_ = scalel_*3.4;
    }
  TLegend* legend=new TLegend(xl_,yl_,xl_+dxl_,yl_+dyl_);
  legend->SetLineColor(0);
  legend->SetFillColor(0);
  legend->SetTextFont(42);
  legend->SetTextSize(0.048);
  
  legend->AddEntry(dummyGraph,"   data","pl");      
  if( logScale )
    {
      legend->AddEntry(dummyGraph,"       ","0");
    }
  for(size_t ii=0;ii<nChan;ii++) 
    {
      legend->AddEntry(histos[ii],hnames[ii],"f");
    }
  legend->Draw("same");

  totalHisto->Draw("same");

  for( size_t ii=0; ii<nChan; ii++ )
    {
      //  listOfStackedHists[nChan-ii-1]->Sumw2();   
      listOfStackedHists[nChan-ii-1]->Rebin(1.);
      listOfStackedHists[nChan-ii-1]->Scale(1.);
      listOfStackedHists[nChan-ii-1]->Draw("Same");
    }

  // draw the data points
  dataGraph->Draw("PE");

  // redraw axis
  p_->RedrawAxis();

  //lumi pad, cms prelim pad etc..
  {
    int txtFont = 42;  // bold is 62
    float txtSize1 = 0.055;
    float txtX1 = 0.91;
    float txtY1 = 0.935;

    float txtSize2 = 0.05;
    float txtX2 = 0.85;
    float txtY2 = 0.83;
    
    // TEST FOR THE NAME ZMT, ZMMNONISO, ZMS
    float txtSize3 = 0.055;
    float txtX3 = 0.3;
    float txtY3 = 0.935;

    TLatex latex;
    latex.SetNDC();
    latex.SetTextFont(txtFont);
    
    latex.SetTextSize(txtSize1);    
    latex.SetTextAlign(31); // align right
    latex.DrawLatex(txtX1,txtY1,"CMS");

    latex.SetTextAlign(31); // align right
    latex.SetTextSize(txtSize2);
    latex.DrawLatex(txtX2,txtY2,"36 pb^{-1}  at  #sqrt{s} = 7 TeV");

    latex.SetTextAlign(21); // align left???
    latex.SetTextSize(txtSize3);
    latex.DrawLatex(txtX3,txtY3,"global plus standalone muon");
  }

  c_->cd();
  
  p_ = pad[1];

  p_->Draw();

  p_->cd();

  TAxis* xratio_ = hratio_->GetXaxis();
  TAxis* yratio_ = hratio_->GetYaxis();

  yratio_->SetRangeUser(r0_-0.9999*dr_,r0_+0.9999*dr_);
  yratio_->SetLabelSize( s[1]*yratio_->GetLabelSize() );
  yratio_->SetTitleSize( s[1]*yratio_->GetTitleSize() );
  yratio_->SetLabelOffset( yratio_->GetLabelOffset() );
  yratio_->SetTitleOffset( yratio_->GetTitleOffset()/s[1] );
  if( use_chi )
    {
      yratio_->SetTitle("#chi");
      yratio_->SetNdivisions(4);
    }
  else
    {
      yratio_->SetTitle("data/fit");
      yratio_->SetNdivisions(3);
    }

  xratio_->SetLabelSize( s[1]*xratio_->GetLabelSize() );
  xratio_->SetTitleSize( s[1]*xratio_->GetTitleSize() );
  xratio_->SetTitleOffset( 1.0 );
  xratio_->CenterTitle();
  xratio_->SetLabelOffset( xratio_->GetLabelOffset()*s[1] );
  xratio_->SetTickLength( xratio_->GetTickLength()*s[1] );

  hratio_->Draw();
  ratioGraph->SetMarkerSize( ratioGraph->GetMarkerSize()*1. );
  ratioGraph->SetLineColor( kBlack );

  ratioGraph->SetMarkerColor( kGray+2 );
  ratioGraph->SetMarkerStyle( kFullCircle );
  ratioGraph->DrawClone("PE");
  ratioGraph->SetMarkerColor( kBlack );
  ratioGraph->SetMarkerStyle( kOpenCircle );
  ratioGraph->DrawClone("PE");

  p_->RedrawAxis();

  c_->cd();

  return c_;
}
Esempio n. 2
0
void BackgroundPrediction(std::string pname,int rebin_factor,int model_number = 0,int imass=750, bool plotBands = false)
{
    rebin = rebin_factor;
    std::string fname = std::string("../fitFilesMETPT34/") + pname + std::string("/histos_bkg.root");
    
    stringstream iimass ;
    iimass << imass;
    std::string dirName = "info_"+iimass.str()+"_"+pname;
    
    
    gStyle->SetOptStat(000000000);
    gStyle->SetPadGridX(0);
    gStyle->SetPadGridY(0);
    
    setTDRStyle();
    gStyle->SetPadGridX(0);
    gStyle->SetPadGridY(0);
    gStyle->SetOptStat(0000);
    
    writeExtraText = true;       // if extra text
    extraText  = "Preliminary";  // default extra text is "Preliminary"
    lumi_13TeV  = "2.7 fb^{-1}"; // default is "19.7 fb^{-1}"
    lumi_7TeV  = "4.9 fb^{-1}";  // default is "5.1 fb^{-1}"
    
    
    double ratio_tau=-1;
    
    TFile *f=new TFile(fname.c_str());
    TH1F *h_mX_CR_tau=(TH1F*)f->Get("distribs_18_10_1")->Clone("CR_tau");
    TH1F *h_mX_SR=(TH1F*)f->Get("distribs_18_10_0")->Clone("The_SR");
    double maxdata = h_mX_SR->GetMaximum();
    double nEventsSR = h_mX_SR->Integral(600,4000);
    ratio_tau=(h_mX_SR->GetSumOfWeights()/(h_mX_CR_tau->GetSumOfWeights()));
    //double nEventsSR = h_mX_SR->Integral(600,4000);
    
    std::cout<<"ratio tau "<<ratio_tau<<std::endl;
    
    TH1F *h_SR_Prediction;
    TH1F *h_SR_Prediction2;
    
    if(blind) {
        h_SR_Prediction2 = (TH1F*)h_mX_CR_tau->Clone("h_SR_Prediction2");
        h_mX_CR_tau->Rebin(rebin);
        h_mX_CR_tau->SetLineColor(kBlack);
        h_SR_Prediction=(TH1F*)h_mX_CR_tau->Clone("h_SR_Prediction");
    } else {
        h_SR_Prediction2=(TH1F*)h_mX_SR->Clone("h_SR_Prediction2");
        h_mX_SR->Rebin(rebin);
        h_mX_SR->SetLineColor(kBlack);
        h_SR_Prediction=(TH1F*)h_mX_SR->Clone("h_SR_Prediction");
        
    }
    h_SR_Prediction->SetMarkerSize(0.7);
    h_SR_Prediction->GetYaxis()->SetTitleOffset(1.2);
    h_SR_Prediction->Sumw2();
    
    /*TFile *f_sig = new TFile((dirName+"/w_signal_"+iimass.str()+".root").c_str());
    RooWorkspace* xf_sig = (RooWorkspace*)f_sig->Get("Vg");
    RooAbsPdf *xf_sig_pdf = (RooAbsPdf *)xf_sig->pdf((std::string("signal_fixed_")+pname).c_str());
    
    RooWorkspace w_sig("w");
    w_sig.import(*xf_sig_pdf,RooFit::RenameVariable((std::string("signal_fixed_")+pname).c_str(),(std::string("signal_fixed_")+pname+std::string("low")).c_str()),RooFit::RenameAllVariablesExcept("low","x"));
    xf_sig_pdf = w_sig.pdf((std::string("signal_fixed_")+pname+std::string("low")).c_str());
   
    RooArgSet* biasVars = xf_sig_pdf->getVariables();
    TIterator *it = biasVars->createIterator();
    RooRealVar* var = (RooRealVar*)it->Next();
    while (var) {
        var->setConstant(kTRUE);
        var = (RooRealVar*)it->Next();
    }
    */
    RooRealVar x("x", "m_{X} (GeV)", SR_lo, SR_hi);
    
    RooRealVar nBackground((std::string("bg_")+pname+std::string("_norm")).c_str(),"nbkg",h_mX_SR->GetSumOfWeights());
    RooRealVar nBackground2((std::string("alt_bg_")+pname+std::string("_norm")).c_str(),"nbkg",h_mX_SR->GetSumOfWeights());
    std::string blah = pname;
    //pname=""; //Antibtag=tag to constrain b-tag to the anti-btag shape
    
    
    /* RooRealVar bg_p0((std::string("bg_p0_")+pname).c_str(), "bg_p0", 4.2, 0, 200.);
     RooRealVar bg_p1((std::string("bg_p1_")+pname).c_str(), "bg_p1", 4.5, 0, 300.);
     RooRealVar bg_p2((std::string("bg_p2_")+pname).c_str(), "bg_p2", 0.000047, 0, 10.1);
     RooGenericPdf bg_pure = RooGenericPdf((std::string("bg_pure_")+blah).c_str(),"(pow(1-@0/13000,@1)/pow(@0/13000,@2+@3*log(@0/13000)))",RooArgList(x,bg_p0,bg_p1,bg_p2));
   */
    RooRealVar bg_p0((std::string("bg_p0_")+pname).c_str(), "bg_p0", 0., -1000, 200.);
    RooRealVar bg_p1((std::string("bg_p1_")+pname).c_str(), "bg_p1", -13, -1000, 1000.);
    RooRealVar bg_p2((std::string("bg_p2_")+pname).c_str(), "bg_p2", -1.4, -1000, 1000.);
    bg_p0.setConstant(kTRUE);
    //RooGenericPdf bg_pure = RooGenericPdf((std::string("bg_pure_")+blah).c_str(),"(pow(@0/13000,@1+@2*log(@0/13000)))",RooArgList(x,bg_p1,bg_p2));
    RooGenericPdf bg = RooGenericPdf((std::string("bg_")+blah).c_str(),"(pow(@0/13000,@1+@2*log(@0/13000)))",RooArgList(x,bg_p1,bg_p2));
  

    /*TF1* biasFunc = new TF1("biasFunc","(0.63*x/1000-1.45)",1350,3600);
    TF1* biasFunc2 = new TF1("biasFunc2","TMath::Min(2.,2.3*x/1000-3.8)",1350,3600);
    double bias_term_s = 0;
    if ((imass > 2450 && blah == "antibtag") || (imass > 1640 && blah == "btag")) {
        if (blah == "antibtag") {
            bias_term_s = 2.7*biasFunc->Eval(imass);
        } else {
            bias_term_s = 2.7*biasFunc2->Eval(imass);
        }
       bias_term_s/=nEventsSR;
    }
    
    RooRealVar bias_term((std::string("bias_term_")+blah).c_str(), "bias_term", 0., -bias_term_s, bias_term_s);
    //bias_term.setConstant(kTRUE);
    RooAddPdf bg((std::string("bg_")+blah).c_str(), "bg_all", RooArgList(*xf_sig_pdf, bg_pure), bias_term);
    */
    string name_output = "CR_RooFit_Exp";
    
    std::cout<<"Nevents "<<nEventsSR<<std::endl;
    RooDataHist pred("pred", "Prediction from SB", RooArgList(x), h_SR_Prediction);
    RooFitResult *r_bg=bg.fitTo(pred, RooFit::Minimizer("Minuit2"), RooFit::Range(SR_lo, SR_hi), RooFit::SumW2Error(kTRUE), RooFit::Save());
    //RooFitResult *r_bg=bg.fitTo(pred, RooFit::Range(SR_lo, SR_hi), RooFit::Save());
    //RooFitResult *r_bg=bg.fitTo(pred, RooFit::Range(SR_lo, SR_hi), RooFit::Save(),RooFit::SumW2Error(kTRUE));
    std::cout<<" --------------------- Building Envelope --------------------- "<<std::endl;
    //std::cout<< "bg_p0_"<< pname << "   param   "<<bg_p0.getVal() <<  " "<<bg_p0.getError()<<std::endl;
    std::cout<< "bg_p1_"<< pname << "   param   "<<bg_p1.getVal() <<  " "<<100*bg_p1.getError()<<std::endl;
    std::cout<< "bg_p2_"<< pname << "   param   "<<bg_p2.getVal() <<  " "<<100*bg_p2.getError()<<std::endl;
    //std::cout<< "bias_term_"<< blah << "   param   0 "<<bias_term_s<<std::endl;
    
    RooPlot *aC_plot=x.frame();
    pred.plotOn(aC_plot, RooFit::MarkerColor(kPink+2));
    if (!plotBands) {
        bg.plotOn(aC_plot, RooFit::VisualizeError(*r_bg, 2), RooFit::FillColor(kYellow));
        bg.plotOn(aC_plot, RooFit::VisualizeError(*r_bg, 1), RooFit::FillColor(kGreen));
    }
    bg.plotOn(aC_plot, RooFit::LineColor(kBlue));
    //pred.plotOn(aC_plot, RooFit::LineColor(kBlack), RooFit::MarkerColor(kBlack));
    
    TGraph* error_curve[5]; //correct error bands
    TGraphAsymmErrors* dataGr = new TGraphAsymmErrors(h_SR_Prediction->GetNbinsX()); //data w/o 0 entries

    for (int i=2; i!=5; ++i) {
        error_curve[i] = new TGraph();
    }
    error_curve[2] = (TGraph*)aC_plot->getObject(1)->Clone("errs");
    int nPoints = error_curve[2]->GetN();
    
    error_curve[0] = new TGraph(2*nPoints);
    error_curve[1] = new TGraph(2*nPoints);
    
    error_curve[0]->SetFillStyle(1001);
    error_curve[1]->SetFillStyle(1001);
    
    error_curve[0]->SetFillColor(kGreen);
    error_curve[1]->SetFillColor(kYellow);
    
    error_curve[0]->SetLineColor(kGreen);
    error_curve[1]->SetLineColor(kYellow);
    
    if (plotBands) {
        RooDataHist pred2("pred2", "Prediction from SB", RooArgList(x), h_SR_Prediction2);

        error_curve[3]->SetFillStyle(1001);
        error_curve[4]->SetFillStyle(1001);
        
        error_curve[3]->SetFillColor(kGreen);
        error_curve[4]->SetFillColor(kYellow);
        
        error_curve[3]->SetLineColor(kGreen);
        error_curve[4]->SetLineColor(kYellow);
        
        error_curve[2]->SetLineColor(kBlue);
        error_curve[2]->SetLineWidth(3);
        
        double binSize = rebin;
        
        for (int i=0; i!=nPoints; ++i) {
            double x0,y0, x1,y1;
            error_curve[2]->GetPoint(i,x0,y0);
            
            RooAbsReal* nlim = new RooRealVar("nlim","y0",y0,-100000,100000);
            //double lowedge = x0 - (SR_hi - SR_lo)/double(2*nPoints);
            //double upedge = x0 + (SR_hi - SR_lo)/double(2*nPoints);
            
            double lowedge = x0 - binSize/2.;
            double upedge = x0 + binSize/2.;
            
            x.setRange("errRange",lowedge,upedge);
            
            RooExtendPdf* epdf = new RooExtendPdf("epdf","extpdf",bg, *nlim,"errRange");
            
            // Construct unbinned likelihood
            RooAbsReal* nll = epdf->createNLL(pred2,NumCPU(2));
            // Minimize likelihood w.r.t all parameters before making plots
            RooMinimizer* minim = new RooMinimizer(*nll);
            minim->setMinimizerType("Minuit2");
            minim->setStrategy(2);
            minim->setPrintLevel(-1);
            minim->migrad();
            
            minim->hesse();
            RooFitResult* result = minim->lastMinuitFit();
            double errm = nlim->getPropagatedError(*result);
            
            //std::cout<<x0<<" "<<lowedge<<" "<<upedge<<" "<<y0<<" "<<nlim->getVal()<<" "<<errm<<std::endl;
            
            error_curve[0]->SetPoint(i,x0,(y0-errm));
            error_curve[0]->SetPoint(2*nPoints-i-1,x0,y0+errm);
            
            error_curve[1]->SetPoint(i,x0,(y0-2*errm));
            error_curve[1]->SetPoint(2*nPoints-i-1,x0,(y0+2*errm));
            
            error_curve[3]->SetPoint(i,x0,-errm/sqrt(y0));
            error_curve[3]->SetPoint(2*nPoints-i-1,x0,errm/sqrt(y0));
            
            error_curve[4]->SetPoint(i,x0,-2*errm/sqrt(y0));
            error_curve[4]->SetPoint(2*nPoints-i-1,x0,2*errm/sqrt(y0));
            
        }
        
        int npois = 0;
        dataGr->SetMarkerSize(1.0);
        dataGr->SetMarkerStyle (20);
        
        const double alpha = 1 - 0.6827;
        
        for (int i=0; i!=h_SR_Prediction->GetNbinsX(); ++i){
            if (h_SR_Prediction->GetBinContent(i+1) > 0) {
                
                int N = h_SR_Prediction->GetBinContent(i+1);
                double L =  (N==0) ? 0  : (ROOT::Math::gamma_quantile(alpha/2,N,1.));
                double U =  ROOT::Math::gamma_quantile_c(alpha/2,N+1,1) ;
                
                dataGr->SetPoint(npois,h_SR_Prediction->GetBinCenter(i+1),h_SR_Prediction->GetBinContent(i+1));
                dataGr->SetPointEYlow(npois, N-L);
                dataGr->SetPointEYhigh(npois, U-N);
                npois++;
            }
        }
    }
    
    double xG[2] = {-10,4000};
    double yG[2] = {0.0,0.0};
    TGraph* unityG = new TGraph(2, xG, yG);
    unityG->SetLineColor(kBlue);
    unityG->SetLineWidth(1);

    double xPad = 0.3;
    TCanvas *c_rooFit=new TCanvas("c_rooFit", "c_rooFit", 800*(1.-xPad), 600);
    c_rooFit->SetFillStyle(4000);
    c_rooFit->SetFrameFillColor(0);
    
    TPad *p_1=new TPad("p_1", "p_1", 0, xPad, 1, 1);
    p_1->SetFillStyle(4000);
    p_1->SetFrameFillColor(0);
    p_1->SetBottomMargin(0.02);
    TPad* p_2 = new TPad("p_2", "p_2",0,0,1,xPad);
    p_2->SetBottomMargin((1.-xPad)/xPad*0.13);
    p_2->SetTopMargin(0.03);
    p_2->SetFillColor(0);
    p_2->SetBorderMode(0);
    p_2->SetBorderSize(2);
    p_2->SetFrameBorderMode(0);
    p_2->SetFrameBorderMode(0);
    
    p_1->Draw();
    p_2->Draw();
    p_1->cd();
    
    int nbins = (int) (SR_hi- SR_lo)/rebin;
    x.setBins(nbins);
    
    std::cout << "chi2(data) " <<  aC_plot->chiSquare()<<std::endl;
    
    //std::cout << "p-value: data     under hypothesis H0:  " << TMath::Prob(chi2_data->getVal(), nbins - 1) << std::endl;
    
    aC_plot->GetXaxis()->SetRangeUser(SR_lo, SR_hi);
    aC_plot->GetXaxis()->SetLabelOffset(0.02);
    aC_plot->GetYaxis()->SetRangeUser(0.1, 1000.);
    h_SR_Prediction->GetXaxis()->SetRangeUser(SR_lo, SR_hi);
    string rebin_ = itoa(rebin);
    
    aC_plot->GetXaxis()->SetTitle("M_{Z#gamma} [GeV] ");
    aC_plot->GetYaxis()->SetTitle(("Events / "+rebin_+" GeV ").c_str());
    aC_plot->SetMarkerSize(0.7);
    aC_plot->GetYaxis()->SetTitleOffset(1.2);
    aC_plot->Draw();
    
    if (plotBands) {
        error_curve[1]->Draw("Fsame");
        error_curve[0]->Draw("Fsame");
        error_curve[2]->Draw("Lsame");
        dataGr->Draw("p e1 same");
    }
    
    aC_plot->SetTitle("");
    TPaveText *pave = new TPaveText(0.85,0.4,0.67,0.5,"NDC");
    pave->SetBorderSize(0);
    pave->SetTextSize(0.05);
    pave->SetTextFont(42);
    pave->SetLineColor(1);
    pave->SetLineStyle(1);
    pave->SetLineWidth(2);
    pave->SetFillColor(0);
    pave->SetFillStyle(0);
    char name[1000];
    sprintf(name,"#chi^{2}/n = %.2f",aC_plot->chiSquare());
    pave->AddText(name);
    //pave->Draw();
    
    TLegend *leg = new TLegend(0.88,0.65,0.55,0.90,NULL,"brNDC");
    leg->SetBorderSize(0);
    leg->SetTextSize(0.05);
    leg->SetTextFont(42);
    leg->SetLineColor(1);
    leg->SetLineStyle(1);
    leg->SetLineWidth(2);
    leg->SetFillColor(0);
    leg->SetFillStyle(0);
    h_SR_Prediction->SetMarkerColor(kBlack);
    h_SR_Prediction->SetLineColor(kBlack);
    h_SR_Prediction->SetMarkerStyle(20);
    h_SR_Prediction->SetMarkerSize(1.0);
    //h_mMMMMa_3Tag_SR->GetXaxis()->SetTitleSize(0.09);
    if (blind)
        leg->AddEntry(h_SR_Prediction, "Data: sideband", "ep");
    else {
        if (blah == "antibtag" )
            leg->AddEntry(h_SR_Prediction, "Data: anti-b-tag SR", "ep");
        else
            leg->AddEntry(h_SR_Prediction, "Data: b-tag SR", "ep");
        
    }
    
    leg->AddEntry(error_curve[2], "Fit model", "l");
    leg->AddEntry(error_curve[0], "Fit #pm1#sigma", "f");
    leg->AddEntry(error_curve[1], "Fit #pm2#sigma", "f");
    leg->Draw();
    
    aC_plot->Draw("axis same");
    
    
    CMS_lumi( p_1, iPeriod, iPos );
    
    p_2->cd();
    RooHist* hpull;
    hpull = aC_plot->pullHist();
    RooPlot* frameP = x.frame() ;
    frameP->SetTitle("");
    frameP->GetXaxis()->SetRangeUser(SR_lo, SR_hi);
    
    frameP->addPlotable(hpull,"P");
    frameP->GetYaxis()->SetRangeUser(-7,7);
    frameP->GetYaxis()->SetNdivisions(505);
    frameP->GetYaxis()->SetTitle("#frac{(data-fit)}{#sigma_{stat}}");
    
    frameP->GetYaxis()->SetTitleSize((1.-xPad)/xPad*0.06);
    frameP->GetYaxis()->SetTitleOffset(1.0/((1.-xPad)/xPad));
    frameP->GetXaxis()->SetTitleSize((1.-xPad)/xPad*0.06);
    //frameP->GetXaxis()->SetTitleOffset(1.0);
    frameP->GetXaxis()->SetLabelSize((1.-xPad)/xPad*0.05);
    frameP->GetYaxis()->SetLabelSize((1.-xPad)/xPad*0.05);
    
    
    frameP->Draw();
    if (plotBands) {
        error_curve[4]->Draw("Fsame");
        error_curve[3]->Draw("Fsame");
        unityG->Draw("same");
        hpull->Draw("psame");
        
        frameP->Draw("axis same");
    }
    
    
    c_rooFit->SaveAs((dirName+"/"+name_output+".pdf").c_str());
    
    const int nModels = 9;
    TString models[nModels] = {
        "env_pdf_0_13TeV_dijet2", //0
        "env_pdf_0_13TeV_exp1", //1
        "env_pdf_0_13TeV_expow1", //2
        "env_pdf_0_13TeV_expow2", //3 => skip
        "env_pdf_0_13TeV_pow1", //4
        "env_pdf_0_13TeV_lau1", //5
        "env_pdf_0_13TeV_atlas1", //6
        "env_pdf_0_13TeV_atlas2", //7 => skip
        "env_pdf_0_13TeV_vvdijet1" //8
    };
    
    int nPars[nModels] = {
        2, 1, 2, 3, 1, 1, 2, 3, 2
    };
    
    TString parNames[nModels][3] = {
        "env_pdf_0_13TeV_dijet2_log1","env_pdf_0_13TeV_dijet2_log2","",
        "env_pdf_0_13TeV_exp1_p1","","",
        "env_pdf_0_13TeV_expow1_exp1","env_pdf_0_13TeV_expow1_pow1","",
        "env_pdf_0_13TeV_expow2_exp1","env_pdf_0_13TeV_expow2_pow1","env_pdf_0_13TeV_expow2_exp2",
        "env_pdf_0_13TeV_pow1_p1","","",
        "env_pdf_0_13TeV_lau1_l1","","",
        "env_pdf_0_13TeV_atlas1_coeff1","env_pdf_0_13TeV_atlas1_log1","",
        "env_pdf_0_13TeV_atlas2_coeff1","env_pdf_0_13TeV_atlas2_log1","env_pdf_0_13TeV_atlas2_log2",
        "env_pdf_0_13TeV_vvdijet1_coeff1","env_pdf_0_13TeV_vvdijet1_log1",""
    }
    
    if(bias){
        //alternative model
        gSystem->Load("libHiggsAnalysisCombinedLimit");
        gSystem->Load("libdiphotonsUtils");
        
        TFile *f = new TFile("antibtag_multipdf.root");
        RooWorkspace* xf = (RooWorkspace*)f->Get("wtemplates");
        RooWorkspace *w_alt=new RooWorkspace("Vg");
        for(int i=model_number; i<=model_number; i++){
            RooMultiPdf *alternative = (RooMultiPdf *)xf->pdf("model_bkg_AntiBtag");
            std::cout<<"Number of pdfs "<<alternative->getNumPdfs()<<std::endl;
            for (int j=0; j!=alternative->getNumPdfs(); ++j){
                std::cout<<alternative->getPdf(j)->GetName()<<std::endl;
            }
            RooAbsPdf *alt_bg = alternative->getPdf(alternative->getCurrentIndex()+i);//->clone();
            w_alt->import(*alt_bg, RooFit::RenameVariable(alt_bg->GetName(),("alt_bg_"+blah).c_str()));
            w_alt->Print("V");
            std::cerr<<w_alt->var("x")<<std::endl;
            RooRealVar * range_ = w_alt->var("x");
            range_->setRange(SR_lo,SR_hi);
            char* asd = ("alt_bg_"+blah).c_str()	;
            w_alt->import(nBackground2);
            std::cout<<alt_bg->getVal() <<std::endl;
            w_alt->pdf(asd)->fitTo(pred, RooFit::Minimizer("Minuit2"), RooFit::Range(SR_lo, SR_hi), RooFit::SumW2Error(kTRUE), RooFit::Save());

    	    RooArgSet* altVars = w_alt->pdf(asd)->getVariables();
            TIterator *it2 = altVars->createIterator();
            RooRealVar* varAlt = (RooRealVar*)it2->Next();
            while (varAlt) {
               varAlt->setConstant(kTRUE);
               varAlt = (RooRealVar*)it2->Next();
            }



            alt_bg->plotOn(aC_plot, RooFit::LineColor(i+1), RooFit::LineStyle(i+2));
            p_1->cd();
            aC_plot->GetYaxis()->SetRangeUser(0.01, maxdata*50.);
            aC_plot->Draw("same");
            TH1F *h=new TH1F();
            h->SetLineColor(1+i);
            h->SetLineStyle(i+2);
            leg->AddEntry(h, alt_bg->GetName(), "l");
            
            
            w_alt->SaveAs((dirName+"/w_background_alternative.root").c_str());
        }
        leg->Draw();
        p_1->SetLogy();
        c_rooFit->Update();
        c_rooFit->SaveAs((dirName+"/"+name_output+blah+"_multipdf.pdf").c_str());
        
        for (int i=0; i!=nPars[model_number]; ++i) {
            std::cout<<parNames[model_number][i]<<" param "<< w_alt->var(parNames[model_number][i])->getVal()<<"   "<<w_alt->var(parNames[model_number][i])->getError()<<std::endl;
        }
        
        
    } else {
        p_1->SetLogy();
        c_rooFit->Update();
        c_rooFit->SaveAs((dirName+"/"+name_output+"_log.pdf").c_str());
    }
    
    RooWorkspace *w=new RooWorkspace("Vg");
    w->import(bg);
    w->import(nBackground);
    w->SaveAs((dirName+"/w_background_GaussExp.root").c_str());
    
    TH1F *h_mX_SR_fakeData=(TH1F*)h_mX_SR->Clone("h_mX_SR_fakeData");
    h_mX_SR_fakeData->Scale(nEventsSR/h_mX_SR_fakeData->GetSumOfWeights());
    RooDataHist data_obs("data_obs", "Data", RooArgList(x), h_mX_SR_fakeData);
    std::cout<<" Background number of events = "<<nEventsSR<<std::endl;
    RooWorkspace *w_data=new RooWorkspace("Vg");
    w_data->import(data_obs);
    w_data->SaveAs((dirName+"/w_data.root").c_str());
    
}
Esempio n. 3
0
TCanvas* comparePlots2(RooPlot *plot_bC, RooPlot *plot_bS, TH1F *data, TH1F *qcd, std::string title)
{
    
    RooRealVar x("x", "m_{X} (GeV)", SR_lo, SR_hi);
    TCanvas *c=new TCanvas(("c_RooFit_"+title).c_str(), "c", 700, 700);
    TPad *p_1=new TPad("p_1", "p_1", 0, 0.35, 1, 1);
    gStyle->SetPadGridX(0);
    gStyle->SetPadGridY(0);
    gROOT->SetStyle("Plain");
    p_1->SetFrameFillColor(0);
    TPad *p_2 = new TPad("p_2", "p_2",0,0.003740648,0.9975278,0.3391022);
    p_2->Range(160.1237,-0.8717948,1008.284,2.051282);
    p_2->SetFillColor(0);
    p_2->SetBorderMode(0);
    p_2->SetBorderSize(2);
    p_2->SetTopMargin(0.02);
    p_2->SetBottomMargin(0.3);
    p_2->SetFrameBorderMode(0);
    p_2->SetFrameBorderMode(0);
    
    p_1->Draw();
    p_2->Draw();
    p_1->cd();
    double maxdata=data->GetMaximum();
    double maxqcd=qcd->GetMaximum();
    double maxy=(maxdata>maxqcd) ? maxdata : maxqcd;
    
    title=";m_{X} (GeV); Events / "+itoa(data->GetBinWidth(1))+" GeV";
    p_1->DrawFrame(SR_lo, 0, SR_hi, maxy*1., title.c_str());
    plot_bS->SetMarkerStyle(20);
    plot_bS->Draw("same");
    // plot_bS->Draw("same");
    CMS_lumi( p_1, iPeriod, iPos );
    p_2->cd();
    /* TH1F *h_ratio=(TH1F*)data->Clone("h_ratio");
     h_ratio->GetYaxis()->SetTitle("VR/VSB Ratio");
     h_ratio->GetXaxis()->SetTitle("m_{X} (GeV)");
     h_ratio->SetTitle("");//("VR/VR-SB Ratio "+title+" ; VR/VR-SB Ratio").c_str());
     h_ratio->GetYaxis()->SetTitleSize(0.07);
     h_ratio->GetYaxis()->SetTitleOffset(0.5);
     h_ratio->GetXaxis()->SetTitleSize(0.09);
     h_ratio->GetXaxis()->SetTitleOffset(1.0);
     h_ratio->GetXaxis()->SetLabelSize(0.07);
     h_ratio->GetYaxis()->SetLabelSize(0.06);
     
     h_ratio->Divide(qcd);
     h_ratio->SetLineColor(1);
     h_ratio->SetMarkerStyle(20);
     h_ratio->GetXaxis()->SetRangeUser(SR_lo, SR_hi-10);
     h_ratio->GetYaxis()->SetRangeUser(0.,2.);
     */
    RooHist* hpull;
    hpull = plot_bS->pullHist();
    hpull->GetXaxis()->SetRangeUser(SR_lo, SR_hi);
    RooPlot* frameP = x.frame() ;
    frameP->SetTitle("");
    frameP->GetYaxis()->SetTitle("Pull");
    frameP->GetXaxis()->SetRangeUser(SR_lo, SR_hi);
    
    frameP->addPlotable(hpull,"P");
    frameP->GetYaxis()->SetTitle("Pull");
    
    frameP->GetYaxis()->SetTitleSize(0.07);
    frameP->GetYaxis()->SetTitleOffset(0.5);
    frameP->GetXaxis()->SetTitleSize(0.09);
    frameP->GetXaxis()->SetTitleOffset(1.0);
    frameP->GetXaxis()->SetLabelSize(0.07);
    frameP->GetYaxis()->SetLabelSize(0.06);
    
    frameP->Draw();
    
    
    //  TLine *m_one_line = new TLine(SR_lo,1,SR_hi,1);
    
    
    // h_ratio->Draw("");
    // m_one_line->Draw("same");
    p_1->cd();
    return c;
}
Esempio n. 4
0
void fit_mass(TString fileN="") {//suffix added before file extension, e.g., '.pdf'
  TString placeholder;//to add strings before using them, e.g., for saving text files
  gROOT->SetBatch(kTRUE);
  gROOT->ProcessLine(".x /afs/cern.ch/user/m/mwilkins/cmtuser/src/lhcbStyle.C");
  
  // gStyle->SetPadTickX(1);
  // gStyle->SetPadTickY(1);
  // gStyle->SetPadLeftMargin(0.15);
  // gStyle->SetTextSize(0.3);

  // //open file and get histogram
  // TFile *inHistos = new TFile("/afs/cern.ch/work/m/mwilkins/Lb2JpsiLtr/data/histos_data.root", "READ");
  // TH1F * h100 = (TH1F*)inHistos->Get("h70");
  // cout<<"data histogram gotten"<<endl;
  //unbinned
  TFile *hastree = new TFile("/afs/cern.ch/work/m/mwilkins/Lb2JpsiLtr/data/cutfile_Optimized.root", "READ");
  TTree * h100 = (TTree*)hastree->Get("mytree");
  cout<<"tree gotten"<<endl;
  TFile *SMChistos= new TFile("/afs/cern.ch/work/m/mwilkins/Lb2JpsiLtr/MC/withKScut/histos_SMCfile_fullMC.root", "READ");
  cout<<"SMC file opened"<<endl;
  TH1F *SMCh = (TH1F*)SMChistos->Get("h00");
  cout<<"SMC hist gotten"<<endl;

  RooRealVar *mass = new RooRealVar("Bs_LOKI_MASS_JpsiConstr","m(J/#psi #Lambda)",4100,6100,"MeV");
  mass->setRange("bkg1",4300,4800);
  mass->setRange("bkg2",5700,5950);
  mass->setRange("bkg3",4300,5500);
  mass->setRange("bkg4",5100,5500);
  mass->setRange("L",5350,5950);
  mass->setRange("tot",4300,5950);
  cout<<"mass declared"<<endl;
  // RooDataHist *data = new RooDataHist("data","1D",RooArgList(*mass),h100);
  //unbinned
  RooDataSet *data = new RooDataSet("data","1D",h100,*mass);
  cout<<"data declared"<<endl;

  RooDataHist *SMC = new RooDataHist("SMC","1D",RooArgList(*mass),SMCh);
  cout<<"SMC hist assigned to RooDataHist"<<endl;
  
  // Construct Pdf Model
  // /\0
  //gaussian
  RooRealVar mean1L("mean1L","/\\ gaus 1: mean",5621.103095,5525,5700);
  RooRealVar sig1L("sig1L","/\\ gaus 1: sigma",6.898126,0,100);
  RooGaussian gau1L("gau1L","#Lambda signal: gaussian 1",*mass,mean1L,sig1L);
  RooFormulaVar mean2L("mean2L","@0",mean1L);
  RooRealVar sig2L("sig2L","/\\ gaus 2: sigma",14.693117,0,100);
  RooGaussian gau2L("gau2L","#Lambda signal: gaussian 2",*mass,mean2L,sig2L);
  RooRealVar f1L("f1L","/\\ signal: fraction gaussian 1",0.748776,0,1);
  RooAddPdf sigL("sigL","#Lambda signal",RooArgList(gau1L,gau2L),RooArgList(f1L));
  // //CB
  // RooRealVar mean3L("mean3L","/\\ CB: mean",5621.001,5525,5700);
  // RooRealVar sig3L("sig3L","/\\ CB: sigma",5.161,0,100);
  // RooRealVar alphaL3("alphaL3","/\\ CB: alpha",2.077,0,1000);
  // RooRealVar nL3("nL1","/\\ CB: n",0.286,0,1000);
  // RooCBShape CBL("CBL","#Lambda signal: CB",*mass,mean3L,sig3L,alphaL3,nL3);
  // RooRealVar mean4L("mean4L","/\\ gaus: mean",5621.804,5525,5700);
  // RooRealVar sig4L("sig4L","/\\ gaus: sigma",10.819,0,100);
  // RooGaussian gauL("gauL","#Lambda signal: gaussian",*mass,mean4L,sig4L);
  // RooRealVar f1L("f1L","/\\ signal: fraction CB",0.578,0,1);
  // RooAddPdf sigL("sigL","#Lambda signal",RooArgList(CBL,gauL),RooArgList(f1L));

  // sigma0
  //using RooHistPdf from MC--no need to build pdf here
  RooHistPdf sigS = makeroohistpdf(SMC,mass,"sigS","#Sigma^{0} signal (RooHistPdf)");
  // /\*
  cout<<"Lst stuff"<<endl;
  RooRealVar meanLst1("meanLst1","/\\*(misc.): mean1",5011.031237,4900,5100);
  RooRealVar sigLst1("sigLst1","/\\*(misc.): sigma1",70.522092,0,100);
  RooRealVar meanLst2("mean5Lst2","/\\*(1405): mean2",5245.261703,5100,5350);
  RooRealVar sigLst2("sigLst2","/\\*(1405): sigma2",64.564763,0,100);
  RooRealVar alphaLst2("alphaLst2","/\\*(1405): alpha2",29.150301);
  RooRealVar nLst2("nLst2","/\\*(1405): n2",4.615817,0,50);
  RooGaussian gauLst1("gauLst1","#Lambda*(misc.), gaus",*mass,meanLst1,sigLst1);
  RooCBShape gauLst2("gauLst2","#Lambda*(1405), CB",*mass,meanLst2,sigLst2,alphaLst2,nLst2);
  // RooRealVar fLst1("fLst1","/\\* bkg: fraction gaus 1",0.743,0,1);
  // RooAddPdf bkgLst("bkgLst","#Lambda* signal",RooArgList(gauLst1,gauLst2),RooArgList(fLst1));
  
  //Poly func BKG mass
  // RooRealVar b0("b0","Background: Chebychev b0",-1.071,-10000,10000);
  RooRealVar b1("b1","Background: Chebychev b1",-1.323004,-10,-0.00000000000000000000001);
  RooRealVar b2("b2","Background: Chebychev b2",0.145494,0,10);
  RooRealVar b3("b3","Background: Chebychev b3",-0.316,-10000,10000);
  RooRealVar b4("b4","Background: Chebychev b4",0.102,-10000,10000);
  RooRealVar b5("b5","Background: Chebychev b5",0.014,-10000,10000);
  RooRealVar b6("b6","Background: Chebychev b6",-0.015,-10000,10000);
  RooRealVar b7("b7","Background: Chebychev b7",0.012,-10000,10000);
  RooArgList bList(b1,b2);
  RooChebychev bkg("bkg","Background", *mass, bList);
  // TF1 *ep = new TF1("ep","[2]*exp([0]*x+[1]*x*x)",4300,5950);
  // ep->SetParameter(0,1);
  // ep->SetParameter(1,-1);
  // ep->SetParameter(2,2000);
  // ep->SetParName(0,"a");
  // ep->SetParName(1,"b");
  // ep->SetParName(2,"c");
  // RooRealVar a("a","Background: Coefficent of x",1,-10000,10000);
  // RooRealVar b("b","Background: Coefficent of x*x",-1,-10000,10000);
  // RooRealVar c("c","Background: Coefficent of exp()",2000,-10000,10000);
  // RooTFnPdfBinding bkg("ep","ep",ep,RooArgList(*mass,a,b));
  
  //number of each shape  
  RooRealVar nbkg("nbkg","N bkg",2165.490249,0,100000000);
  RooRealVar nsigL("nsigL","N /\\",1689.637290,0,1000000000);
  RooRealVar nsigS("nsigS","N sigma",0.000002,0,10000000000);
  RooRealVar ngauLst1("ngauLst1","N /\\*(misc.)",439.812103,0,10000000000);
  RooRealVar ngauLst2("ngauLst2","N /\\*(1405)",152.061617,0,10000000000);
  RooRealVar nbkgLst("nbkgLst","N /\\*",591.828,0,1000000000);

  //add shapes and their number to a totalPdf
  RooArgList shapes;
  RooArgList yields;
  shapes.add(sigL);    yields.add(nsigL);
  shapes.add(sigS);    yields.add(nsigS);
  // shapes.add(bkgLst);  yields.add(nbkgLst);
  shapes.add(gauLst1); yields.add(ngauLst1);
  shapes.add(gauLst2); yields.add(ngauLst2);
  shapes.add(bkg);     yields.add(nbkg);
  RooAddPdf totalPdf("totalPdf","totalPdf",shapes,yields);

  //fit the totalPdf
  RooAbsReal * nll = totalPdf.createNLL(*data,Extended(kTRUE),Range("tot"));
  RooMinuit m(*nll);
  m.setVerbose(kFALSE);
  m.migrad();
  m.minos();
  m.minos();

  //display and save information
  ofstream textfile;//create text file to hold data
  placeholder = "plots/fit"+fileN+".txt";
  textfile.open(placeholder);
  TString outputtext;//for useful text

  //plot things  
  RooPlot *framex = mass->frame();
  framex->GetYaxis()->SetTitle("Events/(5 MeV)");
  data->plotOn(framex,Name("Hist"),MarkerColor(kBlack),LineColor(kBlack),DataError(RooAbsData::SumW2));
  totalPdf.plotOn(framex,Name("curvetot"),LineColor(kBlue));
  RooArgSet* totalPdfComponents = totalPdf.getComponents();
  TIterator* itertPC = totalPdfComponents->createIterator();
  RooAddPdf* vartPC = (RooAddPdf*) itertPC->Next();
  vartPC = (RooAddPdf*) itertPC->Next();//skip totalPdf
  int i=0;//color index
  TLegend *leg = new TLegend(0.2, 0.02, .4, .42);  
  leg->SetTextSize(0.06);
  leg->AddEntry(framex->findObject("curvetot"),"Total PDF","l");
  while(vartPC){//loop over compotents of totalPdf
    TString vartPCtitle = vartPC->GetTitle();
    TIterator* itercompPars;//forward declare so it persists outside the if statement
    RooRealVar* varcompPars;
    if(!(vartPCtitle.Contains(":")||vartPCtitle.Contains("@"))){//only for non-sub-shapes
      while(i==0||i==10||i==4||i==1||i==5||(i>=10&&i<=27))i++;//avoid white and blue and black and yellow and horribleness
      RooArgSet* compPars = vartPC->getParameters(data);//set of the parameters of the component the loop is on
      itercompPars = compPars->createIterator();
      varcompPars = (RooRealVar*) itercompPars->Next();
    
      while(varcompPars){//write and print mean, sig, etc. of sub-shapes
        TString vartitle = varcompPars->GetTitle();
        double varval = varcompPars->getVal();
        TString varvalstring = Form("%f",varval);
        double hi = varcompPars->getErrorHi();
        
        TString varerrorstring = "[exact]";
        if(hi!=-1){
          double lo = varcompPars->getErrorLo();
          double varerror = TMath::Max(fabs(lo),hi);
          varerrorstring = Form("%E",varerror);
        }
        
        outputtext = vartitle+" = "+varvalstring+" +/- "+varerrorstring;
        textfile<<outputtext<<endl;
        cout<<outputtext<<endl;
        
        varcompPars = (RooRealVar*) itercompPars->Next(); 
      }
      totalPdf.plotOn(framex,Name(vartPC->GetName()),LineStyle(kDashed),LineColor(i),Components(vartPC->GetName()));
      leg->AddEntry(framex->findObject(vartPC->GetName()),vartPCtitle,"l");
    
      i++;
    }
    vartPC = (RooAddPdf*) itertPC->Next();
    itercompPars->Reset();//make sure it's ready for the next vartPC
  }
  
  // Calculate chi2/ndf
  RooArgSet *floatpar = totalPdf.getParameters(data);
  int floatpars = (floatpar->selectByAttrib("Constant",kFALSE))->getSize();
  Double_t chi2 = framex->chiSquare("curvetot","Hist",floatpars);
  TString chi2string = Form("%f",chi2);
  //create text box to list important parameters on the plot
  // TPaveText* txt = new TPaveText(0.1,0.5,0.7,0.9,"NBNDC");
  // txt->SetTextSize(0.06);
  // txt->SetTextColor(kBlack);
  // txt->SetBorderSize(0);
  // txt->SetFillColor(0);
  // txt->SetFillStyle(0);
  outputtext = "#chi^{2}/N_{DoF} = "+chi2string;
  cout<<outputtext<<endl;
  textfile<<outputtext<<endl;
  // txt->AddText(outputtext);
  
  // Print stuff
  TIterator* iteryields =  yields.createIterator();
  RooRealVar* varyields = (RooRealVar*) iteryields->Next();//only inherits things from TObject unless class specified
  vector<double> Y, E;//holds yields and associated errors
  vector<TString> YS, ES;//holds strings of the corresponding yields
  int j=0;//count vector position
  int jS=0, jL=0;//these hold the position of the S and L results;initialized in case there is no nsigS or nsigL
  while(varyields){//loop over yields
    TString varname = varyields->GetName();
    TString vartitle = varyields->GetTitle();
    double varval = varyields->getVal();
    Y.push_back(varval);
    double lo = varyields->getErrorLo();
    double hi = varyields->getErrorHi();
    E.push_back(TMath::Max(fabs(lo),hi));
    YS.push_back(Form("%f",Y[j]));
    ES.push_back(Form("%f",E[j]));
    
    if(varname=="nsigS") jS=j;
    if(varname=="nsigL") jL=j;
    
    outputtext = vartitle+" = "+YS[j]+" +/- "+ES[j];
    cout<<outputtext<<endl;
    textfile<<outputtext<<endl;
    //txt->AddText(outputtext);
    
    varyields = (RooRealVar*) iteryields->Next();
    j++;
  }
  //S/L
  double result = Y[jS]/Y[jL];
  cout<<"result declared"<<endl;
  double E_result = TMath::Abs(result)*sqrt(pow(E[jS]/Y[jS],2)+pow(E[jL]/Y[jL],2));
  cout<<"E_result declared"<<endl;
  TString resultstring = Form("%E",result);
  TString E_resultstring = Form("%E",E_result);
  outputtext = "Y_{#Sigma^{0}}/Y_{#Lambda} = "+resultstring+" +/- "+E_resultstring;
  cout<<outputtext<<endl;
  textfile<<outputtext<<endl;
  //txt->AddText(outputtext);
  double resultlimit = (Y[jS]+E[jS])/(Y[jL]-E[jL]);
  outputtext = Form("%E",resultlimit);
  outputtext = "limit = "+outputtext;
  cout<<outputtext<<endl;
  textfile<<outputtext<<endl;
  //txt->AddText(outputtext);
  
  // Create canvas and pads, set style
  TCanvas *c1 = new TCanvas("c1","data fits",1200,800);
  TPad *pad1 = new TPad("pad1","pad1",0.0,0.3,1.0,1.0);
  TPad *pad2 = new TPad("pad2","pad2",0.0,0.0,1.0,0.3);
  pad1->SetBottomMargin(0);
  pad2->SetTopMargin(0);
  pad2->SetBottomMargin(0.5);
  pad2->SetBorderMode(0);
  pad1->SetBorderMode(0);
  c1->SetBorderMode(0);
  pad2->Draw();
  pad1->Draw();
  pad1->cd();
  framex->SetMinimum(1);
  framex->SetMaximum(3000);
  
  framex->addObject(leg);//add legend to frame
  //framex->addObject(txt);//add text to frame

  gPad->SetTopMargin(0.06);
  pad1->SetLogy();
  // pad1->Range(4100,0,6100,0.0005);
  pad1->Update();
  framex->Draw();

  // Pull distribution
  RooPlot *framex2 = mass->frame();
  RooHist* hpull = framex->pullHist("Hist","curvetot");
  framex2->addPlotable(hpull,"P");
  hpull->SetLineColor(kBlack);
  hpull->SetMarkerColor(kBlack);
  framex2->SetTitle(0);
  framex2->GetYaxis()->SetTitle("Pull");
  framex2->GetYaxis()->SetTitleSize(0.15);
  framex2->GetYaxis()->SetLabelSize(0.15);
  framex2->GetXaxis()->SetTitleSize(0.2);
  framex2->GetXaxis()->SetLabelSize(0.15);
  framex2->GetYaxis()->CenterTitle();
  framex2->GetYaxis()->SetTitleOffset(0.45);
  framex2->GetXaxis()->SetTitleOffset(1.1);
  framex2->GetYaxis()->SetNdivisions(505);
  framex2->GetYaxis()->SetRangeUser(-8.8,8.8);
  pad2->cd();
  framex2->Draw();

  c1->cd();

  placeholder = "plots/fit"+fileN+".eps";
  c1->Print(placeholder);
  placeholder = "plots/fit"+fileN+".C";
  c1->SaveAs(placeholder);
  textfile.close();
}
Esempio n. 5
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();
};
Esempio n. 6
0
void results2tree(
      const char* workDirName, 
      bool isMC=false,
      const char* thePoiNames="RFrac2Svs1S,N_Jpsi,f_Jpsi,m_Jpsi,sigma1_Jpsi,alpha_Jpsi,n_Jpsi,sigma2_Jpsi,MassRatio,rSigma21_Jpsi,lambda1_Bkg,lambda2_Bkg,lambda3_Bkg,lambda4_Bkg,lambda5__Bkg,N_Bkg"
      ) {
   // workDirName: usual tag where to look for files in Output
   // thePoiNames: comma-separated list of parameters to store ("par1,par2,par3"). Default: all

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


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

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

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

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

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

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

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

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

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

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

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

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

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

   f->Write();
   f->Close();
}
void plot( TString var, TString data, TString pdf, double low=-1, double high=-1 ) {

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

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

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

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

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

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

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

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

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

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

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

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

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

}
Esempio n. 8
0
void drawCtauFrom2DPlot(RooWorkspace& myws,   // Local workspace
                        string outputDir,     // Output directory
                        struct InputOpt opt,  // Variable with run information (kept for legacy purpose)
                        struct KinCuts cut,   // Variable with current kinematic cuts
                        map<string, string>  parIni,   // Variable containing all initial parameters
                        string plotLabel,     // The label used to define the output file name
                        // Select the type of datasets to fit
                        string DSTAG,         // Specifies the type of datasets: i.e, DATA, MCJPSINP, ...
                        bool isPbPb,          // Define if it is PbPb (True) or PP (False)
                        // Select the type of object to fit
                        bool incJpsi,         // Includes Jpsi model
                        bool incPsi2S,        // Includes Psi(2S) model
                        bool incBkg,          // Includes Background model     
                        // Select the fitting options
                        // Select the drawing options
                        bool setLogScale,     // Draw plot with log scale
                        bool incSS,           // Include Same Sign data
                        double binWidth       // Bin width
                        ) 
{

  RooMsgService::instance().getStream(0).removeTopic(Caching);  
  RooMsgService::instance().getStream(1).removeTopic(Caching);
  RooMsgService::instance().getStream(0).removeTopic(Plotting);
  RooMsgService::instance().getStream(1).removeTopic(Plotting);
  RooMsgService::instance().getStream(0).removeTopic(Integration);
  RooMsgService::instance().getStream(1).removeTopic(Integration);
  RooMsgService::instance().setGlobalKillBelow(RooFit::WARNING) ;

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

  string pdfTotName  = Form("pdfCTAUMASS_Tot_%s", (isPbPb?"PbPb":"PP"));
  string dsOSName = Form("dOS_%s_%s", DSTAG.c_str(), (isPbPb?"PbPb":"PP"));
  string dsOSNameCut = dsOSName+"_CTAUCUT";
  string hOSName = Form("dhCTAUERRTot_Tot_%s", (isPbPb?"PbPb":"PP"));
  string hOSNameBkg  = Form("dhCTAUERR_Bkg_%s", (isPbPb?"PbPb":"PP"));
  string hOSNameJpsi = Form("dhCTAUERR_Jpsi_%s", (isPbPb?"PbPb":"PP"));
  string hOSNamePsi2S = Form("dhCTAUERR_Psi2S_%s", (isPbPb?"PbPb":"PP"));
  string dsSSName = Form("dSS_%s_%s", DSTAG.c_str(), (isPbPb?"PbPb":"PP"));

  bool isWeighted = myws.data(dsOSName.c_str())->isWeighted();
  vector<double> range; range.push_back(cut.dMuon.ctau.Min); range.push_back(cut.dMuon.ctau.Max);

  double minRange = -4.0;
  double maxRange = 7.0;
  Double_t outTot = myws.data(dsOSName.c_str())->numEntries();
  Double_t outErr = myws.data(dsOSName.c_str())->reduce(Form("(ctau>%.6f || ctau<%.6f)", range[1], range[0]))->numEntries();
  int nBins = min(int( round((maxRange - minRange)/binWidth) ), 1000);

  double normDSTot   = 1.0;  if (myws.data(dsOSNameCut.c_str()))  { normDSTot   = myws.data(dsOSName.c_str())->sumEntries()/myws.data(dsOSNameCut.c_str())->sumEntries();  }
  double normJpsi  = 1.0;  if (myws.data(hOSNameJpsi.c_str()))  { normJpsi  = myws.data(dsOSName.c_str())->sumEntries()*normDSTot/myws.data(hOSNameJpsi.c_str())->sumEntries();  }
  double normPsi2S = 1.0;  if (myws.data(hOSNamePsi2S.c_str())) { normPsi2S = myws.data(dsOSName.c_str())->sumEntries()*normDSTot/myws.data(hOSNamePsi2S.c_str())->sumEntries(); }
  double normBkg   = 1.0;  if (myws.data(hOSNameBkg.c_str()))   { normBkg   = myws.data(dsOSName.c_str())->sumEntries()*normDSTot/myws.data(hOSNameBkg.c_str())->sumEntries();   }
  double normTot   = 1.0;  if (myws.data(hOSName.c_str()))  { normTot   = myws.data(dsOSName.c_str())->sumEntries()*normDSTot/myws.data(hOSName.c_str())->sumEntries();  }

  // Create the main plot of the fit
  RooPlot*   frame     = myws.var("ctau")->frame(Bins(nBins), Range(minRange, maxRange));
  frame->updateNormVars(RooArgSet(*myws.var("invMass"), *myws.var("ctau"), *myws.var("ctauErr"))) ;
  myws.data(dsOSName.c_str())->plotOn(frame, Name("dOS"), DataError(RooAbsData::SumW2), XErrorSize(0), MarkerColor(kBlack), LineColor(kBlack), MarkerSize(1.2));
  
  myws.pdf(pdfTotName.c_str())->plotOn(frame,Name("PDF"),
                                       ProjWData(RooArgSet(*myws.var("ctauErr")), *myws.data(dsOSNameCut.c_str()), kTRUE),
                                       Normalization(normDSTot, RooAbsReal::NumEvent),
                                       FillStyle(1001), FillColor(kViolet+6), VLines(), DrawOption("LF"), NumCPU(32), LineColor(kBlack)
                                       );
  myws.pdf(pdfTotName.c_str())->plotOn(frame,Name("BKG"),Components(RooArgSet( *myws.pdf(Form("pdfCTAUMASS_Bkg_%s", (isPbPb?"PbPb":"PP"))) )),
                                       ProjWData(RooArgSet(*myws.var("ctauErr")), *myws.data(dsOSName.c_str()), kTRUE),
                                       Normalization(normDSTot, RooAbsReal::NumEvent),
                                       FillStyle(1001), FillColor(kAzure-9), VLines(), DrawOption("LF"), NumCPU(32)
                                       );
  if (incJpsi) {
    myws.pdf(pdfTotName.c_str())->plotOn(frame,Name("JPSIPR"),Components(RooArgSet( *myws.pdf(Form("pdfCTAUMASS_JpsiPR_%s", (isPbPb?"PbPb":"PP"))) )),
                                         ProjWData(RooArgSet(*myws.var("ctauErr")), *myws.data(dsOSName.c_str()), kTRUE),
                                         Normalization(normDSTot, RooAbsReal::NumEvent),
                                         LineColor(kRed+3), Precision(1e-5), NumCPU(32)
                                         );
    myws.pdf(pdfTotName.c_str())->plotOn(frame,Name("JPSINOPR"),Components(RooArgSet( *myws.pdf(Form("pdfCTAUMASS_JpsiNoPR_%s", (isPbPb?"PbPb":"PP"))) )),
                                         ProjWData(RooArgSet(*myws.var("ctauErr")), *myws.data(dsOSName.c_str()), kTRUE),
                                         Normalization(normDSTot, RooAbsReal::NumEvent),
                                         LineColor(kGreen+3), Precision(1e-5), NumCPU(32)
                                         );
  }
  if (incPsi2S) {
    myws.pdf(pdfTotName.c_str())->plotOn(frame,Name("PSI2SPR"),Components(RooArgSet( *myws.pdf(Form("pdfCTAUMASS_Psi2SPR_%s", (isPbPb?"PbPb":"PP"))) )),
                                         ProjWData(RooArgSet(*myws.var("ctauErr")), *myws.data(dsOSName.c_str()), kTRUE),
                                         Normalization(normDSTot, RooAbsReal::NumEvent),
                                         LineColor(kRed+3), Precision(1e-5), NumCPU(32)
                                         );
    myws.pdf(pdfTotName.c_str())->plotOn(frame,Name("PSI2SNOPR"),Components(RooArgSet( *myws.pdf(Form("pdfCTAUMASS_Psi2SNo_%s", (isPbPb?"PbPb":"PP"))) )),
                                         ProjWData(RooArgSet(*myws.var("ctauErr")), *myws.data(dsOSName.c_str()), kTRUE),
                                         Normalization(normDSTot, RooAbsReal::NumEvent),
                                         LineColor(kGreen+3), Precision(1e-5), NumCPU(32)
                                         );
  }  
  if (incSS) { 
    myws.data(dsSSName.c_str())->plotOn(frame, Name("dSS"), MarkerColor(kRed), LineColor(kRed), MarkerSize(1.2)); 
  }
  myws.data(dsOSName.c_str())->plotOn(frame, Name("dOS"), DataError(RooAbsData::SumW2), XErrorSize(0), MarkerColor(kBlack), LineColor(kBlack), MarkerSize(1.2));
  myws.pdf(pdfTotName.c_str())->plotOn(frame,Name("PDFLINE"),
                                       ProjWData(RooArgSet(*myws.var("ctauErr")), *myws.data(dsOSNameCut.c_str()), kTRUE),
                                       Normalization(normDSTot, RooAbsReal::NumEvent), 
                                       LineColor(kBlack), NumCPU(32)
                                       );
  
  
  // set the CMS style
  setTDRStyle();

  // Create the pull distribution of the fit 
  RooHist *hpull = frame->pullHist(0, "PDF", true);
  hpull->SetName("hpull");
  RooPlot* frame2 = myws.var("ctau")->frame(Title("Pull Distribution"), Bins(nBins), Range(minRange, maxRange));
  frame2->addPlotable(hpull, "PX"); 
  
  // Create the main canvas
  TCanvas *cFig  = new TCanvas(Form("cCtauFig_%s", (isPbPb?"PbPb":"PP")), "cCtauFig",800,800);
  TPad    *pad1  = new TPad(Form("pad1_%s", (isPbPb?"PbPb":"PP")),"",0,0.23,1,1);
  TPad    *pad2  = new TPad(Form("pad2_%s", (isPbPb?"PbPb":"PP")),"",0,0,1,.228);
  TLine   *pline = new TLine(minRange, 0.0, maxRange, 0.0);
  
  TPad *pad4 = new TPad("pad4","This is pad4",0.55,0.46,0.97,0.87);
  pad4->SetFillStyle(0);
  pad4->SetLeftMargin(0.28);
  pad4->SetRightMargin(0.10);
  pad4->SetBottomMargin(0.21);
  pad4->SetTopMargin(0.072);

  frame->SetTitle("");
  frame->GetXaxis()->SetTitle("");
  frame->GetXaxis()->CenterTitle(kTRUE);
  frame->GetXaxis()->SetTitleSize(0.045);
  frame->GetXaxis()->SetTitleFont(42);
  frame->GetXaxis()->SetTitleOffset(3);
  frame->GetXaxis()->SetLabelOffset(3);
  frame->GetYaxis()->SetLabelSize(0.04);
  frame->GetYaxis()->SetTitleSize(0.04);
  frame->GetYaxis()->SetTitleOffset(1.7);
  frame->GetYaxis()->SetTitleFont(42);
  setCtauFrom2DRange(myws, frame, dsOSNameCut, setLogScale, range, outErr);
 
  cFig->cd();
  pad2->SetTopMargin(0.02);
  pad2->SetBottomMargin(0.4);
  pad2->SetFillStyle(4000); 
  pad2->SetFrameFillStyle(4000); 
  pad1->SetBottomMargin(0.015); 
  //plot fit
  pad1->Draw();
  pad1->cd(); 
  frame->Draw();

  printCtauFrom2DParameters(myws, pad1, isPbPb, pdfTotName, isWeighted);
  pad1->SetLogy(setLogScale);

  // Drawing the text in the plot
  TLatex *t = new TLatex(); t->SetNDC(); t->SetTextSize(0.032);
  float dy = 0; 
  
  t->SetTextSize(0.03);
  t->DrawLatex(0.21, 0.86-dy, "2015 HI Soft Muon ID"); dy+=0.045;
  if (isPbPb) {
    t->DrawLatex(0.21, 0.86-dy, "HLT_HIL1DoubleMu0_v1"); dy+=0.045;
  } else {
    t->DrawLatex(0.21, 0.86-dy, "HLT_HIL1DoubleMu0_v1"); dy+=0.045;
  } 
  t->DrawLatex(0.21, 0.86-dy, Form("%.1f #leq p_{T}^{#mu#mu} < %.1f GeV/c",cut.dMuon.Pt.Min,cut.dMuon.Pt.Max)); dy+=0.045;
  t->DrawLatex(0.21, 0.86-dy, Form("%.1f #leq |y^{#mu#mu}| < %.1f",cut.dMuon.AbsRap.Min,cut.dMuon.AbsRap.Max)); dy+=0.045;
  if (isPbPb) {t->DrawLatex(0.21, 0.86-dy, Form("Cent. %d-%d%%", (int)(cut.Centrality.Start/2), (int)(cut.Centrality.End/2))); dy+=0.045;}
  if (outErr>0.0) {
    t->DrawLatex(0.21, 0.86-dy, Form("Excl: (%.4f%%) %.0f evts", (outErr*100.0/outTot), outErr)); dy+=1.5*0.045;
  }

  // Drawing the Legend
  double ymin = 0.7602;
  if (incPsi2S && incJpsi && incSS)  { ymin = 0.7202; } 
  if (incPsi2S && incJpsi && !incSS) { ymin = 0.7452; }
  TLegend* leg = new TLegend(0.5175, ymin, 0.7180, 0.8809); leg->SetTextSize(0.03);
  leg->AddEntry(frame->findObject("dOS"), (incSS?"Opposite Charge":"Data"),"pe");
  if (incSS) { leg->AddEntry(frame->findObject("dSS"),"Same Charge","pe"); }
  if(frame->findObject("PDF")) { leg->AddEntry(frame->findObject("PDF"),"Total fit","fl"); }
  if((incBkg && (incJpsi || incPsi2S)) && frame->findObject("BKG")) { leg->AddEntry(frame->findObject("BKG"),"Background","fl");  }
  if(incBkg && incJpsi && frame->findObject("JPSIPR")) { leg->AddEntry(frame->findObject("JPSIPR"),"J/#psi Prompt","l"); }
  if(incBkg && incJpsi && frame->findObject("JPSINOPR")) { leg->AddEntry(frame->findObject("JPSINOPR"),"J/#psi Non-Prompt","l"); }
  if(incBkg && incPsi2S && frame->findObject("PSI2SPR")) { leg->AddEntry(frame->findObject("PSI2SPR"),"#psi(2S) Prompt","l"); }
  if(incBkg && incPsi2S && frame->findObject("PSI2SNOPR")) { leg->AddEntry(frame->findObject("PSI2SNOPR"),"#psi(2S) Non-Prompt","l"); }
  leg->Draw("same");

  //Drawing the title
  TString label;
  if (isPbPb) {
    if (opt.PbPb.RunNb.Start==opt.PbPb.RunNb.End){
      label = Form("PbPb Run %d", opt.PbPb.RunNb.Start);
    } else {
      label = Form("%s [%s %d-%d]", "PbPb", "HIOniaL1DoubleMu0", opt.PbPb.RunNb.Start, opt.PbPb.RunNb.End);
    }
  } else {
    if (opt.pp.RunNb.Start==opt.pp.RunNb.End){
      label = Form("PP Run %d", opt.pp.RunNb.Start);
    } else {
      label = Form("%s [%s %d-%d]", "PP", "DoubleMu0", opt.pp.RunNb.Start, opt.pp.RunNb.End);
    }
  }
  
  //CMS_lumi(pad1, isPbPb ? 105 : 104, 33, label);
  CMS_lumi(pad1, isPbPb ? 108 : 107, 33, "");
  gStyle->SetTitleFontSize(0.05);
  
  pad1->Update();
  cFig->cd(); 

  //---plot pull
  pad2->Draw();
  pad2->cd();
    
  frame2->SetTitle("");
  frame2->GetYaxis()->CenterTitle(kTRUE);
  frame2->GetYaxis()->SetTitleOffset(0.4);
  frame2->GetYaxis()->SetTitleSize(0.1);
  frame2->GetYaxis()->SetLabelSize(0.1);
  frame2->GetYaxis()->SetTitle("Pull");
  frame2->GetXaxis()->CenterTitle(kTRUE);
  frame2->GetXaxis()->SetTitleOffset(1);
  frame2->GetXaxis()->SetTitleSize(0.12);
  frame2->GetXaxis()->SetLabelSize(0.1);
  frame2->GetXaxis()->SetTitle("#font[12]{l}_{J/#psi} (mm)");
  frame2->GetYaxis()->SetRangeUser(-7.0, 7.0);

  frame2->Draw(); 
  
  // *** Print chi2/ndof 
  printChi2(myws, pad2, frame, "ctau", dsOSName.c_str(), pdfTotName.c_str(), nBins, false);
  
  pline->Draw("same");
  pad2->Update();
  
  // Save the plot in different formats
  gSystem->mkdir(Form("%sctauMass/%s/plot/root/", outputDir.c_str(), DSTAG.c_str()), kTRUE); 
  cFig->SaveAs(Form("%sctauMass/%s/plot/root/PLOT_%s_%s_%s%s_pt%.0f%.0f_rap%.0f%.0f_cent%d%d.root", outputDir.c_str(), DSTAG.c_str(), "CTAU", DSTAG.c_str(), (isPbPb?"PbPb":"PP"), plotLabel.c_str(), (cut.dMuon.Pt.Min*10.0), (cut.dMuon.Pt.Max*10.0), (cut.dMuon.AbsRap.Min*10.0), (cut.dMuon.AbsRap.Max*10.0), cut.Centrality.Start, cut.Centrality.End));
  gSystem->mkdir(Form("%sctauMass/%s/plot/png/", outputDir.c_str(), DSTAG.c_str()), kTRUE);
  cFig->SaveAs(Form("%sctauMass/%s/plot/png/PLOT_%s_%s_%s%s_pt%.0f%.0f_rap%.0f%.0f_cent%d%d.png", outputDir.c_str(), DSTAG.c_str(), "CTAU", DSTAG.c_str(), (isPbPb?"PbPb":"PP"), plotLabel.c_str(), (cut.dMuon.Pt.Min*10.0), (cut.dMuon.Pt.Max*10.0), (cut.dMuon.AbsRap.Min*10.0), (cut.dMuon.AbsRap.Max*10.0), cut.Centrality.Start, cut.Centrality.End));
  gSystem->mkdir(Form("%sctauMass/%s/plot/pdf/", outputDir.c_str(), DSTAG.c_str()), kTRUE);
  cFig->SaveAs(Form("%sctauMass/%s/plot/pdf/PLOT_%s_%s_%s%s_pt%.0f%.0f_rap%.0f%.0f_cent%d%d.pdf", outputDir.c_str(), DSTAG.c_str(), "CTAU", DSTAG.c_str(), (isPbPb?"PbPb":"PP"), plotLabel.c_str(), (cut.dMuon.Pt.Min*10.0), (cut.dMuon.Pt.Max*10.0), (cut.dMuon.AbsRap.Min*10.0), (cut.dMuon.AbsRap.Max*10.0), cut.Centrality.Start, cut.Centrality.End));
  

  cFig->Clear();
  cFig->Close();

}
void checkGoodness(TString scenario, TH1D* dummyThis,TString varType, TString shapeComb, TString INPUTDIR_PREFIX, TString SCEN_TRIG) {

      cout << "Inside the checkGoodness we have " << scenario << " histo " << dummyThis->GetName() << " " << varType << " " << shapeComb << " " <<  INPUTDIR_PREFIX << " " <<  SCEN_TRIG << endl;

   //for each bin, for each type get 3 histos
      TH1D* hpulls_sig_pass = (TH1D*)dummyThis->Clone();
      hpulls_sig_pass->SetName("hpulls_sig_pass");
      TH1D* hpulls_sig_fail = (TH1D*)dummyThis->Clone();
      hpulls_sig_fail->SetName("hpulls_sig_fail");
      //TH1D* hpulls_bkg_pass = (TH1D*)dummyThis->Clone();
      //hpulls_bkg_pass->SetName("hpulls_bkg_pass");
      //TH1D* hpulls_bkg_fail = (TH1D*)dummyThis->Clone();
      //hpulls_bkg_fail->SetName("hpulls_bkg_fail");

      for (int ibin = 0; ibin < getNbin(varType)-1; ibin++) {
 
        //int to string
        std::ostringstream pprint;
        pprint.str("");
        pprint<<ibin;
        string bin = pprint.str();

        //for each bin for each type
        cout << "get data from canvas" << endl;
        RooHist* thisDataPass        = getFitHist(INPUTDIR_PREFIX, scenario, "datalike_mc", varType, SCEN_TRIG,shapeComb, "1",TString(bin), "data");
        RooCurve* thisSignalPass     = getFitCurve(INPUTDIR_PREFIX,scenario, "datalike_mc", varType, SCEN_TRIG,shapeComb, "1",TString(bin), "sig");
        RooCurve* thisBackgroundPass = getFitCurve(INPUTDIR_PREFIX,scenario, "datalike_mc", varType, SCEN_TRIG,shapeComb,"1",TString(bin), "bkg");
        RooHist* thisDataFail        = getFitHist(INPUTDIR_PREFIX, scenario, "datalike_mc", varType, SCEN_TRIG,shapeComb,"2",TString(bin), "data");
        RooCurve* thisSignalFail     = getFitCurve(INPUTDIR_PREFIX,scenario, "datalike_mc", varType, SCEN_TRIG,shapeComb,"2",TString(bin), "sig");
        RooCurve* thisBackgroundFail = getFitCurve(INPUTDIR_PREFIX,scenario, "datalike_mc", varType, SCEN_TRIG,shapeComb,"2",TString(bin), "bkg");

//        RooCurve* thisBackgroundFail = getFitCurve(INPUTDIR_PREFIX,scenario, "datalike_mc", varType, SCEN_TRIG,getShapeUtility(shapeComb, ibin,"datalike_mc"),"2",TString(bin), "bkg");

        //Plot and save
        //RooPlot* ctmp_pass = getFitPlot(INPUTDIR_PREFIX, scenario, "datalike_mc", varType, SCEN_TRIG,getShapeUtility(shapeComb, ibin,"datalike_mc"),"1",TString(bin), "data");
//new RooPlot(); 
        TCanvas* ctmp_pass = new TCanvas("PASS"+TString(bin)+"_view_"+getShapeUtility(shapeComb, ibin,"datalike_mc"),"PASS"+TString(bin)+"_view_"+getShapeUtility(shapeComb, ibin,"datalike_mc"));
        ctmp_pass->cd();
        //ctmp_pass->Draw();
        thisDataPass->Draw("ap");
        thisSignalPass->Draw("same");
        thisBackgroundPass->Draw("same");
        ctmp_pass->SaveAs(INPUTDIR_PREFIX+"/PASS"+TString(bin)+"_view_"+getShapeUtility(shapeComb, ibin,"datalike_mc")+".png");

        TCanvas* ctmp_fail = new TCanvas("FAIL"+TString(bin)+"_view_"+getShapeUtility(shapeComb, ibin,"datalike_mc"),"FAIL"+TString(bin)+"_view_"+getShapeUtility(shapeComb, ibin,"datalike_mc"));
        //RooPlot* ctmp_fail = getFitPlot(INPUTDIR_PREFIX, scenario, "datalike_mc", varType, SCEN_TRIG,getShapeUtility(shapeComb, ibin,"datalike_mc"),"1",TString(bin), "data");

        ctmp_fail->cd();
        thisDataFail->Draw("ap");
        thisSignalFail->Draw("same");
        thisBackgroundFail->Draw("same");
        ctmp_fail->SaveAs(INPUTDIR_PREFIX+"/FAIL"+TString(bin)+"_view_"+getShapeUtility(shapeComb, ibin,"datalike_mc")+".png");

        //calculate and draw pulls
        //PASS
        TCanvas* cpull_pass_sig_tmp = new TCanvas("pulls_"+TString(bin)+"_PASS_SIG_"+getShapeUtility(shapeComb, ibin,"datalike_mc"),"pulls_"+TString(bin)+"_PASS_SIG_"+getShapeUtility(shapeComb, ibin,"datalike_mc"));
        cpull_pass_sig_tmp->cd();
        thisDataPass->makeResidHist(*thisSignalPass,kTRUE)->Draw("ap"); 
        cpull_pass_sig_tmp->SaveAs(INPUTDIR_PREFIX+"/SIG"+TString(bin)+"_PULL_PASS_"+getShapeUtility(shapeComb, ibin,"datalike_mc")+".png");
        //get mean pulls for a given canvas
        hpulls_sig_pass->SetBinContent(ibin+1,fabs(getRooMean(thisDataPass->makeResidHist(*thisSignalPass,kTRUE))));
        hpulls_sig_pass->SetBinError(ibin+1,0.000001);

/*        TCanvas* cpull_pass_bkg_tmp = new TCanvas("pulls_"+TString(bin)+"_PASS_BKG_"+getShapeUtility(shapeComb, ibin,"datalike_mc","pulls_"+TString(bin)+"_PASS_BKG_"+getShapeUtility(shapeComb, ibin,"datalike_mc");
        cpull_pass_bkg_tmp->cd();
        thisDataPass->makeResidHist(*thisBackgroundPass,kTRUE)->Draw("ap");
        cpull_pass_bkg_tmp->SaveAs("BKG"+TString(bin)+"_PULL_PASS_"+getShapeUtility(shapeComb, ibin,"datalike_mc"+".png");
        //get mean pulls for a given canvas
        hpulls_bkg_pass->SetBinContent(ibin+1,getRooMean(thisDataPass->makeResidHist(*thisBackgroundPass,kTRUE)));
        hpulls_bkg_pass->SetBinError(ibin+1,0.000001);
*/
       //FAIL 
        TCanvas* cpull_fail_sig_tmp = new TCanvas("pulls_"+TString(bin)+"_FAIL_SIG_"+getShapeUtility(shapeComb, ibin,"datalike_mc"),"pulls_"+TString(bin)+"_FAIL_SIG_"+getShapeUtility(shapeComb, ibin,"datalike_mc"));
        cpull_fail_sig_tmp->cd();
        thisDataFail->makeResidHist(*thisSignalFail,kTRUE)->Draw("ap");
        cpull_fail_sig_tmp->SaveAs( INPUTDIR_PREFIX+"/SIG"+TString(bin)+"_PULL_FAIL_"+getShapeUtility(shapeComb, ibin,"datalike_mc")+".png");
        cout << "get mean pulls for a given canvas" << endl;
        hpulls_sig_fail->SetBinContent(ibin+1,fabs(getRooMean(thisDataFail->makeResidHist(*thisSignalFail,kTRUE))));
        hpulls_sig_fail->SetBinError(ibin+1,0.000001);

/*        TCanvas* cpull_fail_bkg_tmp = new TCanvas("pulls_"+TString(bin)+"_FAIL_BKG_"+getShapeUtility(shapeComb, ibin,"datalike_mc","pulls_"+TString(bin)+"_FAIL_BKG_"+getShapeUtility(shapeComb,
 ibin));
        cpull_fail_bkg_tmp->cd();
        thisDataFail->makeResidHist(*thisBackgroundFail,kTRUE)->Draw("ap");
        cpull_fail_bkg_tmp->SaveAs("BKG"+TString(bin)+"_PULL_FAIL_"+getShapeUtility(shapeComb, ibin,"datalike_mc"+".png");
        cout << "get mean pulls for a given canvas" << endl;
        hpulls_bkg_fail->SetBinContent(ibin+1,getRooMean(thisDataFail->makeResidHist(*thisBackgroundFail,kTRUE)));
        hpulls_bkg_fail->SetBinError(ibin+1,0.000001);
*/
      }
      cout << "OUT PULLS FILL LOOP XXX" << endl;
      //PLOT pull means distributions
      TCanvas* cpullf_sig = new TCanvas("SIG"+scenario+varType,"SIG"+scenario+varType);
      cpullf_sig->cd();
      cpullf_sig->SetLogx();
      cpullf_sig->SetLogy();
      hpulls_sig_pass->SetMarkerStyle(22);
      hpulls_sig_pass->SetMarkerSize(1.1);
      hpulls_sig_pass->SetMarkerColor(kBlack);
      hpulls_sig_pass->Draw("P");      
      hpulls_sig_fail->SetMarkerStyle(24);
      hpulls_sig_fail->SetMarkerSize(1.1);
      hpulls_sig_fail->SetMarkerColor(kRed);
      hpulls_sig_fail->Draw("Psame");
      cpullf_sig->SaveAs(INPUTDIR_PREFIX+"/SIG"+scenario+varType+".png");
/*
      TCanvas* cpullf_bkg = new TCanvas("BKG"+scenario+varType,"BKG"+scenario+varType);
      cpullf_bkg->cd();
      hpulls_bkg_pass->SetMarkerStyle(22);
      hpulls_bkg_pass->SetMarkerSize(1.1);
      hpulls_bkg_pass->SetMarkerColor(kBlack);
      hpulls_bkg_pass->Draw("P");      
      hpulls_bkg_fail->SetMarkerStyle(24);
      hpulls_bkg_fail->SetMarkerSize(1.1);
      hpulls_bkg_fail->SetMarkerColor(kRed);
      hpulls_bkg_fail->Draw("Psame");
      cpullf_bkg->SaveAs("BKG"+scenario+varType+".png");
*/
}
void BackgroundPrediction_Kinematic_GaussExp_ttbarSubtracted()
{

  gROOT->SetStyle("Plain");
  gStyle->SetOptStat(000000000);
  
  if (bReg) tags=tags+"_bReg";
  
  const unsigned int nPoints=4;
  double mass[nPoints]={90., 107.5, 142.5, 160.};
  double n_SB[nPoints], n_SR[nPoints];
  double ratio[nPoints];
  double errorsY[nPoints], errorsX[nPoints];
  double ratioAt125=-1, errorAt125=-1;
  
  // TFile *f_MMMM_a=new TFile((tags+"/a/Histograms_8TeVData2012BCD_Skim.root").c_str());
  // TFile *f_MMMM_a=new TFile((tags+"/a/Histograms_BJetPlusX_Run2012BCD_Skim.root").c_str());
  TFile *f_MMMM_a=new TFile((tags+"/a_KinFit/Histograms_BJetPlusX_Run2012BCD_Skim.root").c_str());
  // TFile *f_MMMM_a=new TFile((tags+"/a_KinFit/Histograms_BJetPlusX_Run2012BCD_Skim_selected_bTagged_.root").c_str());
  TH1F *h_mX_CR2_a=(TH1F*)f_MMMM_a->Get("h_mX_CR2");
  TH1F *h_mX_CR4_a=(TH1F*)f_MMMM_a->Get("h_mX_CR4");
  TH1F *h_mX_SR_a=(TH1F*)f_MMMM_a->Get("h_mX_SR");
  ratioAt125=h_mX_SR_a->GetSumOfWeights()/(h_mX_CR2_a->GetSumOfWeights()+h_mX_CR4_a->GetSumOfWeights());
  
  // === MMMM/b ===
  // TFile *f_MMMM_b=new TFile((tags+"/b/Histograms_8TeVData2012BCD_Skim.root").c_str());
  // TFile *f_MMMM_b=new TFile((tags+"/b/Histograms_BJetPlusX_Run2012BCD_Skim.root").c_str());
  TFile *f_MMMM_b=new TFile((tags+"/b_KinFit/Histograms_BJetPlusX_Run2012BCD_Skim.root").c_str());
  // TFile *f_MMMM_b=new TFile((tags+"/b_KinFit/Histograms_BJetPlusX_Run2012BCD_Skim_selected_bTagged_.root").c_str());
  TH1F *h_mX_CR2_b=(TH1F*)f_MMMM_b->Get("h_mX_CR2");
  TH1F *h_mX_CR4_b=(TH1F*)f_MMMM_b->Get("h_mX_CR4");
  TH1F *h_mX_SR_b=(TH1F*)f_MMMM_b->Get("h_mX_SR");
  n_SB[0]=(h_mX_CR2_b->GetSumOfWeights()+h_mX_CR4_b->GetSumOfWeights());
  n_SR[0]=h_mX_SR_b->GetSumOfWeights();
  
  if (useRatioFit)
  {
    // === MMMM/d ===
    // TFile *f_MMMM_d=new TFile((tags+"/d/Histograms_8TeVData2012BCD_Skim.root").c_str());
    TFile *f_MMMM_d=new TFile((tags+"/d/Histograms_BJetPlusX_Run2012BCD_Skim.root").c_str());
    // TFile *f_MMMM_d=new TFile((tags+"/d/Histograms_BJetPlusX_Run2012BCD_Skim_selected_bTagged_.root").c_str());
    TH1F *h_mX_CR2_d=(TH1F*)f_MMMM_d->Get("h_mX_CR2");
    TH1F *h_mX_CR4_d=(TH1F*)f_MMMM_d->Get("h_mX_CR4");
    TH1F *h_mX_SR_d=(TH1F*)f_MMMM_d->Get("h_mX_SR");
    n_SB[1]=(h_mX_CR2_d->GetSumOfWeights()+h_mX_CR4_d->GetSumOfWeights());
    n_SR[1]=h_mX_SR_d->GetSumOfWeights();
  
    // === MMMM/e ===
    // TFile *f_MMMM_e=new TFile((tags+"/e/Histograms_8TeVData2012BCD_Skim.root").c_str());
    TFile *f_MMMM_e=new TFile((tags+"/e/Histograms_BJetPlusX_Run2012BCD_Skim.root").c_str());
    // TFile *f_MMMM_e=new TFile((tags+"/e/Histograms_BJetPlusX_Run2012BCD_Skim_selected_bTagged_.root").c_str());
    TH1F *h_mX_CR2_e=(TH1F*)f_MMMM_e->Get("h_mX_CR2");
    TH1F *h_mX_CR4_e=(TH1F*)f_MMMM_e->Get("h_mX_CR4");
    TH1F *h_mX_SR_e=(TH1F*)f_MMMM_e->Get("h_mX_SR");
    n_SB[2]=(h_mX_CR2_e->GetSumOfWeights()+h_mX_CR4_e->GetSumOfWeights());
    n_SR[2]=h_mX_SR_e->GetSumOfWeights();
  
    // === MMMM/c ===
    // TFile *f_MMMM_c=new TFile((tags+"/c/Histograms_8TeVData2012BCD_Skim.root").c_str());
    TFile *f_MMMM_c=new TFile((tags+"/c/Histograms_BJetPlusX_Run2012BCD_Skim.root").c_str());
    // TFile *f_MMMM_c=new TFile((tags+"/c/Histograms_BJetPlusX_Run2012BCD_Skim_selected_bTagged_.root").c_str());
    TH1F *h_mX_CR2_c=(TH1F*)f_MMMM_c->Get("h_mX_CR2");
    TH1F *h_mX_CR4_c=(TH1F*)f_MMMM_c->Get("h_mX_CR4");
    TH1F *h_mX_SR_c=(TH1F*)f_MMMM_c->Get("h_mX_SR");
    n_SB[3]=(h_mX_CR2_c->GetSumOfWeights()+h_mX_CR4_c->GetSumOfWeights());
    n_SR[3]=h_mX_SR_c->GetSumOfWeights();
  
    for (unsigned int i=0; i<nPoints; ++i)
    {
      ratio[i]=n_SR[i]/n_SB[i];
      errorsY[i]=ratio[i]*pow(1./n_SR[i]+1./n_SB[i], 0.5);
      errorsX[i]=0.;
    }
  
    TGraphErrors *g_ratio=new TGraphErrors(nPoints, mass, ratio, errorsX, errorsY);
    g_ratio->SetTitle("SR/SB ratio");
    TCanvas *c_ratio=new TCanvas("c_ratio", "c_ratio", 700, 700);
    g_ratio->SetMinimum(0.); g_ratio->SetMaximum(2.);
    g_ratio->Draw("A*");
    TF1 *f_ratio=new TF1("f_ratio", "pol1");
    g_ratio->Fit(f_ratio);
    c_ratio->SaveAs(("c_ratio_"+tags+".png").c_str());
  
    ratioAt125=f_ratio->Eval(125.);
    errorAt125=(errorsY[0]+errorsY[1]+errorsY[2]+errorsY[3])/4.;
  }
  
  std::cout<<"ratioAt125 = "<<ratioAt125<<" +- "<<errorAt125<<std::endl;
  std::cout<<"bgFloat   lnN     -   "<<1.+errorAt125/ratioAt125<<std::endl;
  
  // Get the ttbar
  double totalLuminosity=17928; // /pb
  double xsec_ttbar_fulllept=24.56;
  double xsec_ttbar_semilept=103.12;
  double xsec_ttbar_hadronic=106.32;
  
  TFile *ttbar_fulllept_b=new TFile("MMMM_nominal/b_KinFit/Histograms_TTJets_FullLeptMGDecays_8TeV-madgraph_Skim.root");
  TFile *ttbar_semilept_b=new TFile("MMMM_nominal/b_KinFit/Histograms_TTJets_SemiLeptMGDecays_8TeV-madgraph_Skim.root");
  TFile *ttbar_hadronic_b=new TFile("MMMM_nominal/b_KinFit/Histograms_TTJets_HadronicMGDecays_8TeV-madgraph_Skim.root");
  
  TFile *ttbar_fulllept_a=new TFile("MMMM_nominal/a_KinFit/Histograms_TTJets_FullLeptMGDecays_8TeV-madgraph_Skim.root");
  TFile *ttbar_semilept_a=new TFile("MMMM_nominal/a_KinFit/Histograms_TTJets_SemiLeptMGDecays_8TeV-madgraph_Skim.root");
  TFile *ttbar_hadronic_a=new TFile("MMMM_nominal/a_KinFit/Histograms_TTJets_HadronicMGDecays_8TeV-madgraph_Skim.root");
  
  double init_ttbar_fulllept=((TH1F*)ttbar_fulllept_a->Get("CountWithPU"))->GetBinContent(1);
  double init_ttbar_semilept=((TH1F*)ttbar_semilept_a->Get("CountWithPU"))->GetBinContent(1);
  double init_ttbar_hadronic=((TH1F*)ttbar_hadronic_a->Get("CountWithPU"))->GetBinContent(1);
  
  double scale_ttbar_fulllept=totalLuminosity*xsec_ttbar_fulllept/init_ttbar_fulllept;
  double scale_ttbar_semilept=totalLuminosity*xsec_ttbar_semilept/init_ttbar_semilept;
  double scale_ttbar_hadronic=totalLuminosity*xsec_ttbar_hadronic/init_ttbar_hadronic;
  
  TH1F *h_mX_VR_ttbar_fulllept=(TH1F*)ttbar_fulllept_b->Get("h_mX_SR");
  TH1F *h_mX_VR_ttbar_semilept=(TH1F*)ttbar_semilept_b->Get("h_mX_SR");
  TH1F *h_mX_VR_ttbar_hadronic=(TH1F*)ttbar_hadronic_b->Get("h_mX_SR");
  
  TH1F *h_mX_VB_ttbar_fulllept=(TH1F*)ttbar_fulllept_b->Get("h_mX_CR2"); h_mX_VB_ttbar_fulllept->Add((TH1F*)ttbar_fulllept_b->Get("h_mX_CR4"));
  TH1F *h_mX_VB_ttbar_semilept=(TH1F*)ttbar_semilept_b->Get("h_mX_CR2"); h_mX_VB_ttbar_semilept->Add((TH1F*)ttbar_semilept_b->Get("h_mX_CR4"));
  TH1F *h_mX_VB_ttbar_hadronic=(TH1F*)ttbar_hadronic_b->Get("h_mX_CR2"); h_mX_VB_ttbar_hadronic->Add((TH1F*)ttbar_hadronic_b->Get("h_mX_CR4"));
  
  TH1F *h_mX_SR_ttbar_fulllept=(TH1F*)ttbar_fulllept_a->Get("h_mX_SR");
  TH1F *h_mX_SR_ttbar_semilept=(TH1F*)ttbar_semilept_a->Get("h_mX_SR");
  TH1F *h_mX_SR_ttbar_hadronic=(TH1F*)ttbar_hadronic_a->Get("h_mX_SR");
  
  TH1F *h_mX_SB_ttbar_fulllept=(TH1F*)ttbar_fulllept_a->Get("h_mX_CR2"); h_mX_SB_ttbar_fulllept->Add((TH1F*)ttbar_fulllept_a->Get("h_mX_CR4"));
  TH1F *h_mX_SB_ttbar_semilept=(TH1F*)ttbar_semilept_a->Get("h_mX_CR2"); h_mX_SB_ttbar_semilept->Add((TH1F*)ttbar_semilept_a->Get("h_mX_CR4"));
  TH1F *h_mX_SB_ttbar_hadronic=(TH1F*)ttbar_hadronic_a->Get("h_mX_CR2"); h_mX_SB_ttbar_hadronic->Add((TH1F*)ttbar_hadronic_a->Get("h_mX_CR4"));
  
  h_mX_VR_ttbar_fulllept->Scale(scale_ttbar_fulllept);
  h_mX_VR_ttbar_semilept->Scale(scale_ttbar_semilept);
  h_mX_VR_ttbar_hadronic->Scale(scale_ttbar_hadronic);
  TH1F *h_mX_VR_ttbar=h_mX_VR_ttbar_fulllept->Clone("h_mX_VR_ttbar");
  h_mX_VR_ttbar->Add(h_mX_VR_ttbar_semilept);
  h_mX_VR_ttbar->Add(h_mX_VR_ttbar_hadronic);
  h_mX_VR_ttbar->Rebin(rebin);
  
  h_mX_VB_ttbar_fulllept->Scale(scale_ttbar_fulllept);
  h_mX_VB_ttbar_semilept->Scale(scale_ttbar_semilept);
  h_mX_VB_ttbar_hadronic->Scale(scale_ttbar_hadronic);
  TH1F *h_mX_VB_ttbar=h_mX_VB_ttbar_fulllept->Clone("h_mX_VB_ttbar");
  h_mX_VB_ttbar->Add(h_mX_VB_ttbar_semilept);
  h_mX_VB_ttbar->Add(h_mX_VB_ttbar_hadronic);
  h_mX_VB_ttbar->Rebin(rebin);
  
  h_mX_SR_ttbar_fulllept->Scale(scale_ttbar_fulllept);
  h_mX_SR_ttbar_semilept->Scale(scale_ttbar_semilept);
  h_mX_SR_ttbar_hadronic->Scale(scale_ttbar_hadronic);
  TH1F *h_mX_SR_ttbar=h_mX_SR_ttbar_fulllept->Clone("h_mX_SR_ttbar");
  h_mX_SR_ttbar->Add(h_mX_SR_ttbar_semilept);
  h_mX_SR_ttbar->Add(h_mX_SR_ttbar_hadronic);
  h_mX_SR_ttbar->Rebin(rebin);
  
  h_mX_SB_ttbar_fulllept->Scale(scale_ttbar_fulllept);
  h_mX_SB_ttbar_semilept->Scale(scale_ttbar_semilept);
  h_mX_SB_ttbar_hadronic->Scale(scale_ttbar_hadronic);
  TH1F *h_mX_SB_ttbar=h_mX_SB_ttbar_fulllept->Clone("h_mX_SB_ttbar");
  h_mX_SB_ttbar->Add(h_mX_SB_ttbar_semilept);
  h_mX_SB_ttbar->Add(h_mX_SB_ttbar_hadronic);
  h_mX_SB_ttbar->Rebin(rebin);
  // //
  
  
  std::cout<<" = MMMM b ======================================== "<<std::endl;
  TH1F *h_mMMMMb_3Tag_CR2=(TH1F*)f_MMMM_b->Get("h_mX_CR2");
  TH1F *h_mMMMMb_3Tag_CR4=(TH1F*)f_MMMM_b->Get("h_mX_CR4");
  TH1F *h_mMMMMb_3Tag_SR=(TH1F*)f_MMMM_b->Get("h_mX_SR");
  h_mMMMMb_3Tag_SR->Rebin(rebin);
  h_mMMMMb_3Tag_SR->Add(h_mX_VR_ttbar, -1);
  double bS=h_mMMMMb_3Tag_SR->GetSumOfWeights();
  std::cout<<"Number of events in MMMM b signal region = "<<bS<<std::endl;
  TH1F *h_mMMMMb_3Tag_CR24=(TH1F*)h_mMMMMb_3Tag_CR2->Clone("h_mX_CR24");
  h_mMMMMb_3Tag_CR24->Add(h_mMMMMb_3Tag_CR4);
  h_mMMMMb_3Tag_CR24->Rebin(rebin);
  h_mMMMMb_3Tag_CR24->SetLineColor(kRed);
  h_mMMMMb_3Tag_SR->SetLineColor(kBlue);
  h_mMMMMb_3Tag_CR24->Add(h_mX_VB_ttbar, -1);
  double bC=h_mMMMMb_3Tag_CR24->GetSumOfWeights();
  std::cout<<"bC = "<<bC<<", bS = "<<bS<<std::endl;
  h_mMMMMb_3Tag_CR24->SetMaximum(h_mMMMMb_3Tag_CR24->GetMaximum()*1.3);
  h_mMMMMb_3Tag_CR24->SetTitle(("Kinematic Extrapolation in "+tags+" Validation Region; m_{X} GeV").c_str());
  h_mMMMMb_3Tag_SR->Scale(bC/bS);
  // Do the fits using RooFit
  gSystem->Load("../PDFs/GaussExp_cxx.so");
  RooRealVar x("x", "m_{X} (GeV)", VR_lo-100., VR_hi+100.);
  // bC
  RooRealVar bC_p0("bC_p0", "bC_p0", 300., 500.);
  RooRealVar bC_p1("bC_p1", "bC_p1", 40., 100.1);
  RooRealVar bC_p2("bC_p2", "bC_p2", 0.1, 10.1);
  GaussExp bC_fit("bC_fit", "bC Fit", x, bC_p0, bC_p1, bC_p2);
  h_mMMMMb_3Tag_CR24->GetXaxis()->SetRangeUser(VR_lo-100., VR_hi+100.);
  RooDataHist bC_data("bC_data", "bC Data", RooArgList(x), h_mMMMMb_3Tag_CR24);
  RooFitResult *r_bC_fit=bC_fit.fitTo(bC_data, RooFit::Range(VR_lo, VR_hi), RooFit::Save());
  RooPlot *bC_plot=x.frame();
  bC_data.plotOn(bC_plot);
  bC_fit.plotOn(bC_plot, RooFit::VisualizeError(*r_bC_fit, sigmaVisual), RooFit::FillColor(kOrange));
  bC_fit.plotOn(bC_plot, RooFit::LineColor(kRed));
  bC_data.plotOn(bC_plot, RooFit::LineColor(kRed), RooFit::MarkerColor(kRed));
  // bS
  RooRealVar bS_p0("bS_p0", "bS_p0", 300., 500.);
  RooRealVar bS_p1("bS_p1", "bS_p1", 40., 100.1);
  RooRealVar bS_p2("bS_p2", "bS_p2", 0.1, 10.1);
  GaussExp bS_fit("bS_fit", "bS Fit", x, bS_p0, bS_p1, bS_p2);
  h_mMMMMb_3Tag_SR->GetXaxis()->SetRangeUser(VR_lo-100., VR_hi+100.);
  RooDataHist bS_data("bS_data", "bS Data", RooArgList(x), h_mMMMMb_3Tag_SR);
  RooFitResult *r_bS_fit=bS_fit.fitTo(bS_data, RooFit::Range(VR_lo, VR_hi), RooFit::Save()); // RooFit::SumW2Error(kTRUE), 
  RooPlot *bS_plot=x.frame();
  bS_data.plotOn(bS_plot);
  bS_fit.plotOn(bS_plot,RooFit::VisualizeError(*r_bS_fit, sigmaVisual), RooFit::FillColor(kCyan));
  bS_fit.plotOn(bS_plot, RooFit::LineColor(kBlue));
  bS_data.plotOn(bS_plot, RooFit::LineColor(kBlue), RooFit::MarkerColor(kBlue));
  std::cout<<" === === "<<std::endl;
  // std::cout<<"chi^2/ndof of bC = "<<bC_plot->chiSquare()<<std::endl;
  // std::cout<<"chi^2/ndof of bS = "<<bS_plot->chiSquare()<<std::endl;
  std::cout<<" === === "<<std::endl;
  TCanvas *c_bC=comparePlots2(bC_plot, bS_plot, h_mMMMMb_3Tag_SR, h_mMMMMb_3Tag_CR24, "Kinematic Extrapolation in "+tags+" Validation Region of Data; m_{X} GeV");
  double x_mean_bC=bC_p0.getVal();
  double x_k_bC=bC_p0.getVal()+bC_p2.getVal()*bC_p1.getVal();
  TLine *l_mean_bC=new TLine(x_mean_bC, 0, x_mean_bC, h_mMMMMb_3Tag_CR24->GetMaximum()*0.8); l_mean_bC->SetLineColor(kRed); l_mean_bC->Draw();
  TLine *l_k_bC=new TLine(x_k_bC, 0, x_k_bC, h_mMMMMb_3Tag_CR24->GetMaximum()*0.8); l_k_bC->SetLineColor(kRed); l_k_bC->SetLineStyle(9); l_k_bC->Draw();
  double x_mean_bS=bS_p0.getVal();
  double x_k_bS=bS_p0.getVal()+bS_p2.getVal()*bS_p1.getVal();
  TLine *l_mean_bS=new TLine(x_mean_bS, 0, x_mean_bS, h_mMMMMb_3Tag_SR->GetMaximum()); l_mean_bS->SetLineColor(kBlue); l_mean_bS->Draw();
  TLine *l_k_bS=new TLine(x_k_bS, 0, x_k_bS, h_mMMMMb_3Tag_SR->GetMaximum()); l_k_bS->SetLineColor(kBlue); l_k_bS->SetLineStyle(9); l_k_bS->Draw();
  if (logPlot) c_bC->SaveAs(("c_compareData_"+tags+"_VR_RooFit_GaussExp_LOG.png").c_str());
  else c_bC->SaveAs(("c_compareData_"+tags+"_VR_RooFit_GaussExp.png").c_str());
  
  // Calculate Pi and DPi and dPi -- for shape systematics
  double PbC_0=bC_p0.getVal();
  double PbC_1=bC_p1.getVal();
  double PbC_2=bC_p2.getVal();
  double dPbC_0=bC_p0.getError();
  double dPbC_1=bC_p1.getError();
  double dPbC_2=bC_p2.getError();
  double PbS_0=bS_p0.getVal();
  double PbS_1=bS_p1.getVal();
  double PbS_2=bS_p2.getVal();
  double dPbS_0=bS_p0.getError();
  double dPbS_1=bS_p1.getError();
  double dPbS_2=bS_p2.getError();
  /*double DPb_0=PbS_0-PbC_0;
  double DPb_1=PbS_1-PbC_1;
  double DPb_2=PbS_2-PbC_2;
  double dPb_0=quad(dPbC_0, dPbS_0);
  double dPb_1=quad(dPbC_1, dPbS_1);
  double dPb_2=quad(dPbC_2, dPbS_2);*/
  
  std::cout<<" = MMMM Background Prediction ==== "<<std::endl;
  TH1F *h_mMMMMa_3Tag_CR2=(TH1F*)f_MMMM_a->Get("h_mX_CR2");
  TH1F *h_mMMMMa_3Tag_CR4=(TH1F*)f_MMMM_a->Get("h_mX_CR4");
  TH1F *h_mMMMMa_3Tag_SR;
  if (tags!="MMMM_nominal") h_mMMMMa_3Tag_SR=(TH1F*)f_MMMM_a->Get("h_mX_SR");
  TH1F *h_mMMMMa_3Tag_CR24=(TH1F*)h_mMMMMa_3Tag_CR2->Clone("h_mX_CR24");
  h_mMMMMa_3Tag_CR24->Add(h_mMMMMa_3Tag_CR4);
  h_mMMMMa_3Tag_CR24->Rebin(rebin);
  h_mMMMMa_3Tag_CR24->SetLineColor(kBlack);
  h_mMMMMa_3Tag_CR24->Add(h_mX_SB_ttbar, -1);
  if (tags!="MMMM_nominal") h_mMMMMa_3Tag_SR->Rebin(rebin);
  if (tags!="MMMM_nominal") h_mMMMMa_3Tag_SR->SetLineColor(kBlue);
  if (tags!="MMMM_nominal") h_mMMMMa_3Tag_SR->Add(h_mX_SR_ttbar, -1);
  TH1F *h_mMMMMa_3Tag_SR_Prediction=(TH1F*)h_mMMMMa_3Tag_CR24->Clone("h_mMMMMa_3Tag_SR_Prediction");
  if (logPlot) h_mMMMMa_3Tag_SR_Prediction->SetMinimum(1);
  // double aC=h_mMMMMa_3Tag_CR24->GetSumOfWeights();
  // Get the scale of the prediction right
  std::cout<<"bS/bC = "<<bS/bC<<std::endl;
  std::cout<<"(bC) bgFloat   lnN     -    "<<1.+sqrt(1./bC)<<std::endl;
  std::cout<<"(bC + bS) bgFloat   lnN     -    "<<1.+sqrt(1./bC+1./bS)<<std::endl;
  // std::cout<<"ratioAt125 = "<<ratioAt125<<", +- "<<errorAt125<<" (fract unc.) = "<<1.+errorAt125/ratioAt125<<std::endl;
  // h_mMMMMa_3Tag_SR_Prediction->Scale(ratioAt125);
  std::cout<<"Number of predicted events in 17.928 /fb = "<<h_mMMMMa_3Tag_SR_Prediction->GetSumOfWeights()*ratioAt125<<std::endl;
  std::cout<<"Number of predicted events in 17.928 /fb around mX=509(+-26) GeV = "<<(h_mMMMMa_3Tag_SR_Prediction->Integral(h_mMMMMa_3Tag_SR_Prediction->FindBin(509.-26.), h_mMMMMa_3Tag_SR_Prediction->FindBin(509.+26.)))*249./h_mMMMMa_3Tag_SR_Prediction->GetSumOfWeights()<<std::endl;
  std::cout<<"Number of predicted events in 17.928 /fb around mX=714(+-40) GeV = "<<(h_mMMMMa_3Tag_SR_Prediction->Integral(h_mMMMMa_3Tag_SR_Prediction->FindBin(714.-40.), h_mMMMMa_3Tag_SR_Prediction->FindBin(714.+40.)))*249./h_mMMMMa_3Tag_SR_Prediction->GetSumOfWeights()<<std::endl;
  std::cout<<"Number of predicted events in 17.928 /fb around mX=450-550 GeV = "<<(h_mMMMMa_3Tag_SR_Prediction->Integral(h_mMMMMa_3Tag_SR_Prediction->FindBin(450.), h_mMMMMa_3Tag_SR_Prediction->FindBin(550.)))*249./h_mMMMMa_3Tag_SR_Prediction->GetSumOfWeights()<<std::endl;
  std::cout<<"Number of predicted events in 17.928 /fb around mX=600-800 GeV = "<<(h_mMMMMa_3Tag_SR_Prediction->Integral(h_mMMMMa_3Tag_SR_Prediction->FindBin(600.), h_mMMMMa_3Tag_SR_Prediction->FindBin(800.)))*249./h_mMMMMa_3Tag_SR_Prediction->GetSumOfWeights()<<std::endl;
  // RooFit fit to background prediction
  // RooRealVar bg_p0("bg_p0", "bg_p0", 400., 600.);
  // RooRealVar bg_p1("bg_p1", "bg_p1", 50., 100.1);
  // RooRealVar bg_p2("bg_p2", "bg_p2", 0.1, 10.1);
  // For mX300
  RooRealVar bg_p0("bg_p0", "bg_p0", 350., 600.);
  RooRealVar bg_p1("bg_p1", "bg_p1", 30., 100.1);
  RooRealVar bg_p2("bg_p2", "bg_p2", 0.01, 10.1);
  GaussExp bg("bg", "Background Prediction PDF", x, bg_p0, bg_p1, bg_p2);
  RooDataHist pred("pred", "Prediction from SB", RooArgList(x), h_mMMMMa_3Tag_SR_Prediction);
  RooFitResult *r_bg=bg.fitTo(pred, RooFit::Range(SR_lo, SR_hi), RooFit::Save());
  // ---------------------
  // Envelope of functions
  // RooRealVar bg_p0_p("bg_p0_p", "bg_p0_p", bg_p0.getVal()+bg_p0.getError()/2.);
  // RooRealVar bg_p0_m("bg_p0_m", "bg_p0_m", bg_p0.getVal()-bg_p0.getError()/2.);
  // RooRealVar bg_p1_p("bg_p1_p", "bg_p1_p", bg_p1.getVal()+bg_p1.getError()/2.);
  // RooRealVar bg_p1_m("bg_p1_m", "bg_p1_m", bg_p1.getVal()-bg_p1.getError()/2.);
  // RooRealVar bg_p2_p("bg_p2_p", "bg_p2_p", bg_p2.getVal()+bg_p2.getError()/2.);
  // RooRealVar bg_p2_m("bg_p2_m", "bg_p2_m", bg_p2.getVal()-bg_p2.getError()/2.);
  // GaussExp bgEnv_p0_p("bgEnv_p0_p", "bgEnv_p0_p", x, bg_p0_p, bg_p1, bg_p2);
  // GaussExp bgEnv_p0_m("bgEnv_p0_m", "bgEnv_p0_m", x, bg_p0_m, bg_p1, bg_p2);
  // GaussExp bgEnv_p1_p("bgEnv_p1_p", "bgEnv_p1_p", x, bg_p0, bg_p1_p, bg_p2);
  // GaussExp bgEnv_p1_m("bgEnv_p1_m", "bgEnv_p1_m", x, bg_p0, bg_p1_m, bg_p2);
  // GaussExp bgEnv_p2_p("bgEnv_p2_p", "bgEnv_p2_p", x, bg_p0, bg_p1, bg_p2_p);
  // GaussExp bgEnv_p2_m("bgEnv_p2_m", "bgEnv_p2_m", x, bg_p0, bg_p1, bg_p2_m);
  // ---------------------
  // Multiplicative Polynomials
  RooRealVar bg_p3("bg_p3", "bg_p3", -10, 10);
  RooRealVar bg_p4("bg_p4", "bg_p4", -10, 10);
  RooRealVar bg_p5("bg_p5", "bg_p5", -10, 10);
  RooPlot *aC_plot=x.frame();
  pred.plotOn(aC_plot, RooFit::MarkerColor(kRed));
  bg.plotOn(aC_plot, RooFit::VisualizeError(*r_bg, sigmaVisual), RooFit::FillColor(kOrange));
  bg.plotOn(aC_plot, RooFit::LineColor(kRed));
  pred.plotOn(aC_plot, RooFit::LineColor(kRed), RooFit::MarkerColor(kRed));
  
  TCanvas *c_rooFit=new TCanvas("c_rooFit", "c_rooFit", 700, 700);
  TPad *p_2=new TPad("p_2", "p_2", 0, 0, 1, 0.35);
  TPad *p_1=new TPad("p_1", "p_1", 0, 0.35, 1, 1);
  p_1->SetBottomMargin(0.05);
  p_1->SetFillStyle(4000);
  p_1->SetFrameFillColor(0);
  p_2->SetFillStyle(4000);
  p_2->SetFrameFillColor(0);
  p_1->Draw();
  p_2->Draw();
  p_1->cd();
  if (tags!="MMMM_nominal") h_mMMMMa_3Tag_SR->Draw("Ep9 SAME");
  aC_plot->SetTitle("; m_{X} (GeV); Events / (10 GeV)");
  aC_plot->Draw();
  double x_mean_aC=bg_p0.getVal();
  double x_k_aC=bg_p0.getVal()+bg_p2.getVal()*bg_p1.getVal();
  TLine *l_mean_aC=new TLine(x_mean_aC, 0, x_mean_aC, h_mMMMMa_3Tag_SR_Prediction->GetMaximum()); l_mean_aC->SetLineColor(kRed); l_mean_aC->Draw();
  TLine *l_k_aC=new TLine(x_k_aC, 0, x_k_aC, h_mMMMMa_3Tag_SR_Prediction->GetMaximum()); l_k_aC->SetLineColor(kRed); l_k_aC->SetLineStyle(9); l_k_aC->Draw();
  
  // Prediction Curve with Shape Systematics
  double PaC_0=bg_p0.getVal();
  double PaC_1=bg_p1.getVal();
  double PaC_2=bg_p2.getVal();
  double dPaC_0=bg_p0.getError();
  double dPaC_1=bg_p1.getError();
  double dPaC_2=bg_p2.getError();
  double PaS_0, PaS_1, PaS_2;
  double dPaS_0, dPaS_1, dPaS_2;
  if (externalParameterPrediction)
  {
    PaS_0=externalPrediction_p0(PaC_0, dPaC_0, dPaS_0);
    PaS_1=externalPrediction_p1(PaC_1, dPaC_1, dPaS_1);
    PaS_2=externalPrediction_p2(PaC_2, dPaC_2, dPaS_2);
  }
  else
  {
    PaS_0=PaC_0*PbS_0/PbC_0;
    PaS_1=PaC_1*PbS_1/PbC_1;
    PaS_2=PaC_2*PbS_2/PbC_2;
    dPaS_0=PaS_0*quad((dPaC_0/PaC_0), (dPbS_0/PbS_0), (dPbC_0/PbC_0));
    dPaS_1=PaS_1*quad((dPaC_1/PaC_1), (dPbS_1/PbS_1), (dPbC_1/PbC_1));
    dPaS_2=PaS_2*quad((dPaC_2/PaC_2), (dPbS_2/PbS_2), (dPbC_2/PbC_2));
  }
  std::cout<<"(dPaC_0/PaC_0) = ("<<dPaC_0<<"/"<<PaC_0<<") = "<<(dPaC_0/PaC_0)<<"; (dPbS_0/PbS_0) = ("<<dPbS_0<<"/"<<PbS_0<<") = "<<(dPbS_0/PbS_0)<<"; (dPbC_0/PbC_0) = ("<<dPbC_0<<"/"<<PbC_0<<") = "<<(dPbC_0/PbC_0)<<std::endl;
  std::cout<<"(dPaC_1/PaC_1) = ("<<dPaC_1<<"/"<<PaC_1<<") = "<<(dPaC_1/PaC_1)<<"; (dPbS_1/PbS_1) = ("<<dPbS_1<<"/"<<PbS_1<<") = "<<(dPbS_1/PbS_1)<<"; (dPbC_1/PbC_1) = ("<<dPbC_1<<"/"<<PbC_1<<") = "<<(dPbC_1/PbC_1)<<std::endl; 
  std::cout<<"(dPaC_2/PaC_2) = ("<<dPaC_2<<"/"<<PaC_2<<") = "<<(dPaC_2/PaC_2)<<"; (dPbS_2/PbS_2) = ("<<dPbS_2<<"/"<<PbS_2<<") = "<<(dPbS_2/PbS_2)<<"; (dPbC_2/PbC_2) = ("<<dPbC_2<<"/"<<PbC_2<<") = "<<(dPbC_2/PbC_2)<<std::endl; 
  std::cout<<" Predicted PaS_0 = "<<PaS_0<<" +- "<<dPaS_0<<std::endl;
  std::cout<<" Predicted PaS_1 = "<<PaS_1<<" +- "<<dPaS_1<<std::endl;
  std::cout<<" Predicted PaS_2 = "<<PaS_2<<" +- "<<dPaS_2<<std::endl;
  RooRealVar *bg_pred0;
  RooRealVar *bg_pred1;
  RooRealVar *bg_pred2;
  // Let the mean and std dev float a bit
  // dPaS_0=dPaS_0*5.;
  // dPaS_1=dPaS_1*5.;
  // dPaS_2=dPaS_2*5.;
  std::cout<<"Parameter Ranges:"<<std::endl;
  std::cout<<" Predicted PaS_0 = "<<PaS_0<<" +- "<<dPaS_0<<std::endl;
  std::cout<<" Predicted PaS_1 = "<<PaS_1<<" +- "<<dPaS_1<<std::endl;
  std::cout<<" Predicted PaS_2 = "<<PaS_2<<" +- "<<dPaS_2<<std::endl;
  if (tags!="MMMM_nominal")
  { 
    bg_pred0=(new RooRealVar("bg_pred0", "bg_pred0", PaS_0-dPaS_0/2., PaS_0+dPaS_0/2.));
    bg_pred1=(new RooRealVar("bg_pred1", "bg_pred1", PaS_1-dPaS_1/2., PaS_1+dPaS_1/2.));
    bg_pred2=(new RooRealVar("bg_pred2", "bg_pred2", PaS_2-dPaS_2/2., PaS_2+dPaS_2/2.));
  }
  else
  {
    bg_pred0=(new RooRealVar("bg_pred0", "bg_pred0", PaS_0));  bg_pred0->setError(dPaS_0);
    bg_pred1=(new RooRealVar("bg_pred1", "bg_pred1", PaS_1));  bg_pred1->setError(dPaS_1);
    bg_pred2=(new RooRealVar("bg_pred2", "bg_pred2", PaS_2));  bg_pred2->setError(dPaS_2);
  }
  GaussExp bg_pred_init("background_init", "Background Predicted for Signal Region", x, *bg_pred0, *bg_pred1, *bg_pred2);
  GaussExp bg_pred("background", "Background Predicted for Signal Region", x, *bg_pred0, *bg_pred1, *bg_pred2);
  RooPlot *aS_plot=x.frame();
  if (tags!="MMMM_nominal")
  {
    RooDataHist unblind("unblind", "Signal Region", RooArgList(x), h_mMMMMa_3Tag_SR);
    unblind.plotOn(aS_plot, RooFit::LineColor(kBlue), RooFit::MarkerColor(kBlue));
    // bg_pred_init.plotOn(aS_plot, RooFit::LineColor(kGreen), RooFit::Range(SR_lo, SR_hi));
    RooFitResult *r_bg_pred=bg_pred.fitTo(unblind, RooFit::Range(SR_lo, SR_hi), RooFit::Save());
    bg_pred.plotOn(aS_plot, RooFit::VisualizeError(*r_bg_pred, sigmaVisual), RooFit::FillColor(kCyan));
    bg_pred.plotOn(aS_plot, RooFit::LineColor(kBlue));
    bg_pred.plotOn(aS_plot, RooFit::Name("r_bg_prediction"));
    unblind.plotOn(aS_plot, RooFit::LineColor(kBlue), RooFit::MarkerColor(kBlue));
    aS_plot->Draw("same");
  }
  else
  {
    bg_pred.plotOn(aC_plot, RooFit::LineColor(kGreen), RooFit::Range(SR_lo, SR_hi));
    aC_plot->Draw("same");
  }
  double x_mean_aS=bg_pred0->getVal();
  double x_k_aS=bg_pred0->getVal()+bg_pred2->getVal()*bg_pred1->getVal();
  TLine *l_mean_aS=new TLine(x_mean_aS, 0, x_mean_aS, h_mMMMMa_3Tag_SR_Prediction->GetMaximum()); l_mean_aS->SetLineColor(kBlue); l_mean_aS->Draw();
  TLine *l_k_aS=new TLine(x_k_aS, 0, x_k_aS, h_mMMMMa_3Tag_SR_Prediction->GetMaximum()); l_k_aS->SetLineColor(kBlue); l_k_aS->SetLineStyle(9); l_k_aS->Draw();
  
  std::cout<<" === === "<<std::endl;
  // std::cout<<"chi^2/ndof of bC = "<<bC_plot->chiSquare()<<std::endl;
  // std::cout<<"chi^2/ndof of bS = "<<bS_plot->chiSquare()<<std::endl;
  // std::cout<<"chi^2/ndof of aC = "<<aC_plot->chiSquare()<<std::endl;
  // std::cout<<"chi^2/ndof of aS = "<<aS_plot->chiSquare()<<std::endl;
  std::cout<<" === === "<<std::endl;
  // if (logPlot) p_1->SetLogy();
  
  TLatex * tPrel = new TLatex();
  tPrel->SetNDC();
  tPrel->SetTextColor(kBlack);
  tPrel->SetTextSize(0.04);
  tPrel->DrawLatex(0.1,0.95,"CMS Preliminary; #sqrt{s} =  8 TeV, L=17.928 fb^{-1}");
  
  p_2->cd();
  p_2->SetGridy();
  RooHist *hpull;
  hpull=aC_plot->pullHist();
  hpull->SetMinimum(-4); hpull->SetMaximum(6);
  RooPlot *frameP=x->frame();
  frameP->SetTitle("; m_{X} (GeV); (data-fit)/fit");
  frameP->addPlotable(hpull, "P");
  frameP->Draw();
  TLine *m_one_line=new TLine(SR_lo, 0, SR_hi, 0); m_one_line->Draw();
  
  if (logPlot) c_rooFit->SaveAs(("c_compareData_"+tags+"_SR_RooFit_GaussExp_LOG.png").c_str());
  else c_rooFit->SaveAs(("c_compareData_"+tags+"_SR_RooFit_GaussExp.png").c_str());
  // --- Ratio of function to data points ---
  /*
  RooCurve *f_bg_pred=(RooCurve*)aS_plot->findObject("r_bg_prediction");
  TH1F *h_ratio=(TH1F*)h_mMMMMa_3Tag_SR->Clone("h_ratio");
  for (unsigned int i=0; i<h_ratio->GetNbinsX(); ++i)
  {
    double fEval=f_bg_pred->Eval(h_mMMMMa_3Tag_SR->GetBinCenter(i));
    double data=h_mMMMMa_3Tag_SR->GetBinContent(i);
    // std::cout<<"i = "<<i<<", fEval = "<<fEval<<", data = "<<data<<std::endl;
    double binContent=(h_mMMMMa_3Tag_SR->GetBinContent(i))/(f_bg_pred->Eval(h_mMMMMa_3Tag_SR->GetBinCenter(i)));
    double binError=(h_mMMMMa_3Tag_SR->GetBinError(i))/(f_bg_pred->Eval(h_mMMMMa_3Tag_SR->GetBinCenter(i)));
    h_ratio->SetBinContent(i, binContent);
    h_ratio->SetBinError(i, binError);
  }
  h_ratio->GetXaxis()->SetRangeUser(SR_lo, SR_hi);
  h_ratio->SetMaximum(2.5); h_ratio->SetMinimum(-0.5);
  h_ratio->SetTitle("Data/Fit in SR; m_{X} (GeV); Data/Fit");
  h_ratio->Fit("pol1", "", "", SR_lo, SR_hi);
  TCanvas *c_DataFit=new TCanvas("c_DataFit", "c_DataFit", 1000, 700);
  h_ratio->Draw();
  c_DataFit->SaveAs(("c_DataFit_"+tags+"SR.png").c_str());
  */
  // ------------------------------------------
  
  RooWorkspace *w=new RooWorkspace("HbbHbb");
  w->import(bg_pred);
  w->SaveAs("w_background_GaussExp.root");
  
}
void grabDataSubtractedHistograms(int nJet, int massRange) {
  TFile f("Histograms_data_and_template.root", "update");


  // Figure out the plot directory name first
  TString dir2jet = "./plots_10172011_2jetsample";
  TString dir3jet = "./plots_10172011_3jetsample";
  TString dirName = "";
  if(nJet==2) dirName = dir2jet;
  if(nJet==3) dirName = dir3jet;

  TString massStr = "";
  if(nJet==2 && massRange==1) massStr = "150-230";
  else if(nJet==2 && massRange==2) massStr = "200-400";
  else if(nJet==2 && massRange==3) massStr = "360-500";
  else if(nJet==2 && massRange==4) massStr = "450-800";
  else if(nJet==3 && massRange==1) massStr = "150-230";
  else if(nJet==3 && massRange==2) massStr = "200-400";
  else if(nJet==3 && massRange==3) massStr = "360-800";

  TString ConnectorStr = "";
  if( !(massStr=="") ) ConnectorStr = "-";
  TString fitFileName = TString("mLnuJJ-") + massStr + ConnectorStr + TString("combined-fit");


  TFile* fitFile = new TFile( dirName + TString("/") + fitFileName+".root", "read");
  TCanvas* fitCan = (TCanvas*) fitFile->Get( fitFileName );
  RooHist* data = (RooHist*) fitCan->FindObject( "h_data" );
  RooCurve* fit = (RooCurve*) fitCan->FindObject( "h_total" );
  RooCurve* fit_wjj = (RooCurve*) fitCan->FindObject( "h_Wjets" );
  RooCurve* fit_diboson = (RooCurve*) fitCan->FindObject( "h_diboson" );
  RooCurve* fit_Top = (RooCurve*) fitCan->FindObject( "h_Top" );
  RooCurve* fit_QCD = (RooCurve*) fitCan->FindObject( "h_QCD" );
  RooCurve* fit_Zjets = (RooCurve*) fitCan->FindObject( "h_Zjets" );


  TFile* systFileUp = new TFile( dirName + TString("SystUp/") + fitFileName+".root", "read");
  TCanvas* systFileUpCan = (TCanvas*) systFileUp->Get( fitFileName );
  RooCurve* fit_wjj_systUp = (RooCurve*) systFileUpCan->FindObject( "h_Wjets" );
  RooCurve* fit_systUp = (RooCurve*) systFileUpCan->FindObject( "h_total" );

  TFile* systFileDown = new TFile( dirName + TString("SystDown/") + fitFileName+".root", "read");
  TCanvas* systFileDownCan = (TCanvas*) systFileDown->Get( fitFileName );
  RooCurve* fit_wjj_systDown = (RooCurve*) systFileDownCan->FindObject( "h_Wjets" );
  RooCurve* fit_systDown = (RooCurve*) systFileDownCan->FindObject("h_total");


  ///// Now save everything ///////////////
  TString outPrefix = TString("2jet_MassRange_") + massStr + TString("_");
  if(nJet==3) outPrefix = TString("3jet_MassRange_") + massStr + TString("_");


  data->SetName( outPrefix+"hist_data" );
  fit->SetName( outPrefix+"curve_fitTotal" );
  fit_wjj->SetName( outPrefix+"curve_WJets" );
  fit_diboson->SetName( outPrefix+"curve_diboson" );
  fit_Top->SetName(  outPrefix+"curve_Top" );
  fit_QCD->SetName(  outPrefix+"curve_QCD" );
  fit_Zjets->SetName(  outPrefix+"curve_Zjets" );
  fit_wjj_systUp->SetName( outPrefix+"curve_WJets_SystUp" );
  fit_wjj_systDown->SetName( outPrefix+"curve_WJets_SystDown" );
  fit_systUp->SetName( outPrefix+"curve_fitTotal_SystUp" );
  fit_systDown->SetName( outPrefix+"curve_fitTotal_SystDown" );

  
  f.cd();
  data->Write();
  fit->Write();
  fit_wjj->Write();
  fit_diboson->Write();
  fit_Top->Write();
  fit_QCD->Write();
  fit_Zjets->Write();
  fit_wjj_systUp->Write();
  fit_wjj_systDown->Write();
  fit_systUp->Write();
  fit_systDown->Write();

  f.Close();
  delete fitFile;
  delete systFileUp;
  delete systFileDown;
}
Esempio n. 12
0
TCanvas* WmunuOthers( int iV=0 )
{
  gStyle->SetOptStat(0);
  gStyle->SetOptTitle(0);

  TGaxis::SetMaxDigits(3);
  double intLumi(36);

  // channels, ordered as in the legend
  vector<TString> channels;  
  vector<TString> hnames;
  vector<TString> type;

  map<TString,int> fillColor_;
  map<TString,int> lineColor_;
  int lineWidth1(2);
  int lineWidth2(1);

  bool salamanderStyle=true; 
  if( salamanderStyle )
    {
      lineWidth1 = 2;
      lineWidth2 = 1;

      fillColor_["Signal"] = kOrange-2;
      lineColor_["Signal"] = kOrange+3;
      
      fillColor_["EWK"] = kOrange+7;
      lineColor_["EWK"] = kOrange+3;
      
      fillColor_["QCD"] = kViolet-5;
      lineColor_["QCD"] = kViolet+3;
      
      fillColor_["ttbar"] = kRed+2;
      lineColor_["ttbar"] = kRed+4;
      
      fillColor_["gamma+jet"] = kMagenta+4;
      lineColor_["gamma+jet"] = kViolet+3;
    }
  else
    {
      lineWidth1 = 2;
      lineWidth2 = 2;

      fillColor_["Signal"] = kPink+6;
      lineColor_["Signal"] = kMagenta+3;
      
      fillColor_["EWK"] = kAzure+8;
      lineColor_["EWK"] = kAzure+4;
      
      fillColor_["QCD"] = kYellow-7;
      lineColor_["QCD"] = kYellow+4;
      
      fillColor_["ttbar"] = kGreen;
      lineColor_["ttbar"] = kGreen+2;
      
      fillColor_["gamma+jet"] = kOrange;
      lineColor_["gamma+jet"] = kOrange+2;
    }

  // log scale?
  bool logScaleY=false;
  bool logScaleX=false;

  // rebin?
  int rb = 1; 

  // histogram limits, in linear and logarithmic
  int nbin_(0);
  float xmin_(0.), xmax_(0.); 
  float ymin_(0.), ymax_(0.); 
  float yminl_(0.), ymaxl_(0.); 

  // titles and axis, marker size
  TString xtitle;
  TString ytitle;
  int ndivx(510);
  int ndivy(510);
  float markerSize(1.);
  float titleOffset(1.00);

  float r0_ = 1.;
  float dr_ = 0.3;
  if( use_chi )
    {
      r0_ = 0.;
      dr_ = 7.5;
    }

  // canvas name
  TString cname;
  TString ctitle;

  // legend position and scale;
  float xl_  = 0.;
  float yl_  = 0.;
  float scalel_ = 0.075;

  // root file, where the data is
  //  TString fname("../Results/");
  TString fname = "./Wmunu_Fit_pfMet";
  TString dataHistName("data");
  double factor;
  // ***
  // Only the following is specific 
  if( iV==6 || iV==7 || iV==20 || iV ==22 || iV==21 || iV==23)
    {  
      if( iV==6 || iV==20 || iV==22)
	{
	  // MET plots in linear scale (inclusive)
	  if(iV==20) fname = "./Wmunu_PLUS_pfMet";
	  else if(iV==22) fname = "./Wmunu_MINUS_pfMet";
	  logScaleY = false;
	  
	  ctitle = "W to mu-nu analysis - MET linear scale";
	  
	  dataHistName = "DataMET";
	  
	  channels.push_back("WTemplateMET"); 
	  if(iV==6) {cname="Wmn_MET";hnames.push_back("  W #rightarrow #mu#nu"); factor=1;}
	  else if(iV==20) {cname="Wmn_MET_plus";hnames.push_back("  W^{+} #rightarrow #mu^{+}#nu"); factor=3./5.;}
	  else {cname="Wmn_MET_minus";hnames.push_back("  W^{-} #rightarrow #mu^{-}#nu");factor=2./5.;}
	  type.push_back("Signal"); 
      
	  channels.push_back("NonQCDMET");                  
	  hnames.push_back("  EWK+t#bar{t}"); 
	  type.push_back("EWK"); 

	  channels.push_back("QCDMET");                  
	  hnames.push_back("  QCD"); 
	  type.push_back("QCD"); 

	  nbin_ = 100;
	  xmin_ = 0.;
	  xmax_ = 100.;

	  xtitle = "#slash{E}_{T} [GeV]";
	  ytitle = "number of events / 2 GeV";
	  ndivx = 506;
	  ndivy = 506;

	  markerSize = 1.1;

	  ymin_ = 0.;
	  xl_ = 0.6;
	  yl_ = 0.53;
	  
	  //ymax_ = 500.*intLumi*factor;
	  if(iV==6) ymax_ = 14e3;
	  else ymax_ = 8e3;
	}
      else if( iV==7 || iV==21 || iV==23)
	{
	  // MET plots in log scale (inclusive)
	  
	  logScaleY = true;
	  if(iV==21) fname = "./Wmunu_PLUS_pfMet";
	  else if(iV==23) fname = "./Wmunu_MINUS_pfMet";
	  
	  ctitle = "W to mu-nu analysis - MET log scale";

	  dataHistName = "DataMET";

	  channels.push_back("WTemplateMET"); 
	  if(iV==7) {cname="Wmn_MET";hnames.push_back("  W #rightarrow #mu#nu");}
	  else if(iV==21) {cname="Wmn_MET_plus";hnames.push_back("  W^{+} #rightarrow #mu^{+}#nu");}
	  else {cname="Wmn_MET_minus";hnames.push_back("  W^{-} #rightarrow #mu^{-}#nu");}
	  type.push_back("Signal"); 
      
	  channels.push_back("EWKMET");                  
	  hnames.push_back("  EWK"); 
	  type.push_back("EWK"); 

	  channels.push_back("TTbar_MCMET");                  
	  hnames.push_back("  t#bar{t}"); 
	  type.push_back("ttbar"); 
	  
	  channels.push_back("QCDMET");                  
	  hnames.push_back("  QCD"); 
	  type.push_back("QCD"); 

	  nbin_ = 200;
	  xmin_ = 0.;
	  xmax_ = 200.;

	  xtitle = "#slash{E}_{T} [GeV]";
	  ytitle = "number of events / 2 GeV";
	  ndivx = 506;
	  ndivy = 506;

	  markerSize = 0.9;

	  yminl_ = 0.05;
	  ymaxl_ = 800.*intLumi;
	  xl_ = 0.6;
	  yl_ = 0.43;
	  
	}
    }
  else if( iV==8 || iV==9 )
    {
      if( iV==8 )
	{cname="pt";
	  // pT plots in linear scale (inclusive)
	  
	  logScaleY = false;
	  
	  ctitle = "W to mu-nu analysis - pT linear scale";

	  dataHistName = "DataPT";

	  channels.push_back("WTemplatePT"); 
	  hnames.push_back("  W #rightarrow #mu#nu"); 
	  type.push_back("Signal"); 
      
	  channels.push_back("NonQCDPT");                  
	  hnames.push_back("  EWK+t#bar{t}"); 
	  type.push_back("EWK"); 

	  channels.push_back("QCDPT");                  
	  hnames.push_back("  QCD"); 
	  type.push_back("QCD"); 

	  nbin_ = 60;
	  xmin_ = 20.;
	  xmax_ = 80.;

	  xtitle = "p_{T}(#mu) [GeV]";
	  ytitle = "number of events / 2 GeV";
	  ndivx = 506;
	  ndivy = 506;

	  markerSize = 1.1;

	  ymin_ = 0.;
	  ymax_ = 500.*intLumi;
	  xl_ = 0.6;
	  yl_ = 0.53;

	}
      else if( iV==9 )
	{cname="pt";
	  // pT plots in log scale (inclusive)

	  logScaleY = true;

	  ctitle = "W to mu-nu analysis - pT log scale";

	  dataHistName = "DataPT";

	  channels.push_back("WTemplatePT"); 
	  hnames.push_back("  W #rightarrow #mu#nu"); 
	  type.push_back("Signal"); 
      
	  channels.push_back("EWKPT");                  
	  hnames.push_back("  EWK"); 
	  type.push_back("EWK"); 

	  channels.push_back("TTbar_MCPT");                  
	  hnames.push_back("  t#bar{t}"); 
	  type.push_back("ttbar"); 

	  channels.push_back("QCDPT");                  
	  hnames.push_back("  QCD"); 
	  type.push_back("QCD"); 

	  nbin_ = 80;
	  xmin_ = 20.;
	  xmax_ = 100.;

	  xtitle = "p_{T}(#mu) [GeV]";
	  ytitle = "number of events / 2 GeV";
	  ndivx = 506;
	  ndivy = 506;

	  markerSize = 0.9;

	  yminl_ = 0.1;
	  ymaxl_ = 30000.*intLumi;
	  xl_ = 0.6;
	  yl_ = 0.45;

	}
    }
  else if( iV==13 || iV==14 )
    {
      if( iV==13 )
	{cname="ptw";
	  // pT plots in linear scale (inclusive)

	  logScaleY = false;

	  ctitle = "W to mu-nu analysis - W pT linear scale";

	  dataHistName = "DataPTW";

	  channels.push_back("WTemplatePTW"); 
	  hnames.push_back("  W #rightarrow #mu#nu"); 
	  type.push_back("Signal"); 
      
	  channels.push_back("NonQCDPTW");                  
	  hnames.push_back("  EWK+t#bar{t}"); 
	  type.push_back("EWK"); 

	  channels.push_back("QCDPTW");                  
	  hnames.push_back("  QCD"); 
	  type.push_back("QCD"); 

	  nbin_ = 100;
	  xmin_ = 0.;
	  xmax_ = 100.;

	  xtitle = "p_{T}(W) [GeV]";
	  ytitle = "number of events / 2 GeV";
	  ndivx = 506;
	  ndivy = 506;

	  markerSize = 1.1;

	  ymin_ = 0.;
	  ymax_ = 500.*intLumi;
	  xl_ = 0.6;
	  yl_ = 0.53;

	}
      else if( iV==14 )
	{cname="ptw";
	  // pT plots in log scale (inclusive)
	  
	  logScaleY = true;

	  ctitle = "W to mu-nu analysis - pT log scale";

	  dataHistName = "DataPTW";

	  channels.push_back("WTemplatePTW"); 
	  hnames.push_back("  W #rightarrow #mu#nu"); 
	  type.push_back("Signal"); 
      
	  channels.push_back("EWKPTW");                  
	  hnames.push_back("  EWK"); 
	  type.push_back("EWK"); 

	  channels.push_back("TTbar_MCPTW");                  
	  hnames.push_back("  t#bar{t}"); 
	  type.push_back("ttbar"); 

	  channels.push_back("QCDPTW");                  
	  hnames.push_back("  QCD"); 
	  type.push_back("QCD"); 

	  nbin_ = 100;
	  xmin_ = 0.;
	  xmax_ = 100.;

	  xtitle = "p_{T}(W) [GeV]";
	  ytitle = "number of events / 2 GeV";
	  ndivx = 506;
	  ndivy = 506;

	  markerSize = 0.9;

	  yminl_ = 0.1;
	  ymaxl_ = 45000.*intLumi;
	  xl_ = 0.6;
	  yl_ = 0.48;
	  
	}
    }
  else if( iV==10 || iV==11 || iV==12 )
    {
      if( iV==10 )
	{cname="iso";
	  // isolation plot in linear scale 
	  
	  logScaleY = false;

	  ctitle = "W to mu-nu analysis - isolation, linear scale";

	  dataHistName = "DataISO";

	  channels.push_back("WTemplateISO"); 
	  hnames.push_back("  W #rightarrow #mu#nu"); 
	  type.push_back("Signal"); 
      
	  channels.push_back("NonQCDISO");                  
	  hnames.push_back("  EWK+t#bar{t}"); 
	  type.push_back("EWK"); 

	  channels.push_back("QCDISO");                  
	  hnames.push_back("  QCD"); 
	  type.push_back("QCD"); 

	  nbin_ = 25;
	  xmin_ = 0.;
	  xmax_ = 0.5;

	  xtitle = "I^{rel}_{comb}";
	  ytitle = "number of events";
      //ytitle = "CMS preliminary";
	  ndivx = 506;
	  ndivy = 506;

	  markerSize = 1.1;

	  titleOffset = 1.25;

	  ymin_ = 0.;
	  ymax_ = 5000.*intLumi;
	  xl_ = 0.6;
	  yl_ = 0.53;

	}
      else if( iV==11 )
	{cname="iso";
	  // isolation plot in log scale 
	  
	  logScaleY = true;

	  ctitle = "W to mu-nu analysis - isolation, log scale";

	  dataHistName = "DataISO";

	  channels.push_back("WTemplateISO"); 
	  hnames.push_back("  W #rightarrow #mu#nu"); 
	  type.push_back("Signal"); 
      
	  channels.push_back("EWKISO");                  
	  hnames.push_back("  EWK"); 
	  type.push_back("EWK"); 

	  channels.push_back("TTbar_MCISO");                  
	  hnames.push_back("  t#bar{t}"); 
	  type.push_back("ttbar"); 

	  channels.push_back("QCDISO");                  
	  hnames.push_back("  QCD"); 
	  type.push_back("QCD"); 

	  nbin_ = 25;
	  xmin_ = 0.;
	  xmax_ = 0.5;

	  xtitle = "I^{rel}_{comb}";
	  ytitle = "number of events";
      //ytitle = "CMS preliminary";
	  ndivx = 506;
	  ndivy = 506;

	  markerSize = 0.9;

	  yminl_ = 50;
	  ymaxl_ = 30000.*intLumi;
	  xl_ = 0.6;
	  yl_ = 0.45;

	}
      else if( iV==12 )
	{cname="iso2";
	  // isolation plot in log scale 
	  
	  logScaleX = true;
	  logScaleY = true;

	  ctitle = "W to mu-nu analysis - isolation, log scale";
	  dataHistName = "DataISO";

	  channels.push_back("WTemplateISO"); 
	  hnames.push_back("  W #rightarrow #mu#nu"); 
	  type.push_back("Signal"); 
      
	  channels.push_back("EWKISO");                  
	  hnames.push_back("  EWK"); 
	  type.push_back("EWK"); 

	  channels.push_back("TTbar_MCISO");                  
	  hnames.push_back("  t#bar{t}"); 
	  type.push_back("ttbar"); 

	  channels.push_back("QCDISO");                  
	  hnames.push_back("  QCD"); 
	  type.push_back("QCD"); 
	  
	  nbin_ = 200;
	  xmin_ = 0.;
	  xmax_ = 0.5;
	  
	  xtitle = "I^{rel}_{comb}";
	  ytitle = "number of events";
	  ndivx = 506;
	  ndivy = 506;
	  
	  markerSize = 0.9;
	  
	  yminl_ = 1;
	  ymaxl_ = 4000000.*intLumi;
	  xl_ = 0.6;
	  yl_ = 0.45;
	  
	}
      
      
      
    }
  else if( iV==15 )
    {cname="acop";
      // pT plots in linear scale (inclusive)
      
      logScaleY = false;
      
      ctitle = "W to mu-nu analysis - acop linear scale";
      
      dataHistName = "DataACOP";
      
      channels.push_back("WTemplateACOP"); 
      hnames.push_back("  W #rightarrow #mu#nu"); 
      type.push_back("Signal"); 
      
      channels.push_back("NonQCDACOP");                  
      hnames.push_back("  EWK+t#bar{t}"); 
      type.push_back("EWK"); 
      
      channels.push_back("QCDACOP");                  
      hnames.push_back("  QCD"); 
      type.push_back("QCD"); 
      
      nbin_ = 60;
      xmin_ = 0;
      xmax_ = 3.14;
      
      xtitle = "acop";
      ytitle = "number of events";
      ndivx = 506;
      ndivy = 506;
      
      markerSize = 1.1;
      
      ymin_ = 0.;
      ymax_ = 400.*intLumi;
      xl_ = 0.6;
      yl_ = 0.53;
      
    }
  else if( iV==16 )
    {cname="eta";
      
      // pT plots in linear scale (inclusive)
      
      logScaleY = false;
      
      ctitle = "W to mu-nu analysis - eta linear scale";
      
      dataHistName = "DataETA";
      
      channels.push_back("WTemplateETA"); 
      hnames.push_back("  W #rightarrow #mu#nu"); 
      type.push_back("Signal"); 
      
      channels.push_back("NonQCDETA");                  
      hnames.push_back("  EWK+t#bar{t}"); 
      type.push_back("EWK"); 
      
      channels.push_back("QCDETA");                  
      hnames.push_back("  QCD"); 
      type.push_back("QCD"); 
      
      nbin_ = 60;
      xmin_ = -3;
      xmax_ = 3;
      
      xtitle = "eta";
      ytitle = "number of events";
      ndivx = 506;
      ndivy = 506;
      
      markerSize = 1.1;
      
      ymin_ = 0.;
      ymax_ = 120.*intLumi;
      xl_ = 0.25;
      yl_ = 0.63;
      
    }
  else if( iV==17 )
    {cname="ptw_minus";
      fname = "./Wmunu_MINUS_pfMet";
      // pT plots in linear scale (inclusive)
      
      logScaleY = false;
      
      ctitle = "W to mu-nu analysis - eta linear scale";
      
      dataHistName = "DataPTW";
      
      channels.push_back("WTemplatePTW"); 
      hnames.push_back("  W^{-} #rightarrow #mu^{-}#nu"); 
      type.push_back("Signal"); 
      
      channels.push_back("NonQCDPTW");                  
      hnames.push_back("  EWK+t#bar{t}"); 
      type.push_back("EWK"); 
      
      channels.push_back("QCDPTW");                  
      hnames.push_back("  QCD"); 
      type.push_back("QCD"); 
      
      nbin_ = 100;
      xmin_ = 0;
      xmax_ = 100;
      
      xtitle = "W pt (GeV)";
      ytitle = "number of events / 2 GeV";
      ndivx = 506;
      ndivy = 506;
      
      markerSize = 1.1;
      
      ymin_ = 0.;
      ymax_ = 200.*intLumi;
      xl_ = 0.6;
      yl_ = 0.53;
      
    }
  else if( iV==18 )
    {cname="ptw_plus";
      fname = "./Wmunu_PLUS_pfMet";
      // pT plots in linear scale (inclusive)
      
      logScaleY = false;
      
      ctitle = "W to mu-nu analysis - eta linear scale";
      
      dataHistName = "DataPTW";
      
      channels.push_back("WTemplatePTW"); 
      hnames.push_back("  W^{+} #rightarrow #mu^{+}#nu"); 
      type.push_back("Signal"); 
      
      channels.push_back("NonQCDPTW");                  
      hnames.push_back("  EWK+t#bar{t}"); 
      type.push_back("EWK"); 
      
      channels.push_back("QCDPTW");                  
      hnames.push_back("  QCD"); 
      type.push_back("QCD"); 
      
      nbin_ = 100;
      xmin_ = 0;
      xmax_ = 100;
      
      xtitle = "W pt (GeV)";
      ytitle = "number of events / 2 GeV";
      ndivx = 506;
      ndivy = 506;
      
      markerSize = 1.1;
      
      ymin_ = 0.;
      ymax_ = 300.*intLumi;
      xl_ = 0.6;
      yl_ = 0.53;
      
    }
  else if( iV==19 )
    {cname="phi";
      //fname = "../Results/Wmunu__pfMet.root";
      // pT plots in linear scale (inclusive)
      
      logScaleY = false;
      
      ctitle = "W to mu-nu analysis - phi linear scale";
      
      dataHistName = "DataPHI";
      
      channels.push_back("WTemplatePHI"); 
      hnames.push_back("  W #rightarrow #mu#nu"); 
      type.push_back("Signal"); 
      
      channels.push_back("NonQCDPHI");                  
      hnames.push_back("  EWK+t#bar{t}"); 
      type.push_back("EWK"); 
      
      channels.push_back("QCDPHI");                  
      hnames.push_back("  QCD"); 
      type.push_back("QCD"); 
      
      nbin_ = 60;
      xmin_ = -3.5;
      xmax_ = 3.5;
      
      xtitle = "Phi";
      ytitle = "number of events";
      ndivx = 506;
      ndivy = 506;
      
      markerSize = 1.1;
      
      ymin_ = 0.;
      ymax_ = 100.*intLumi;
      xl_ = 0.25;
      yl_ = 0.63;
      
    }
   
  int nChan=channels.size();
  
  // open the root file containing histograms and graphs
  fname += ".root";
  TFile* f_ = TFile::Open(fname,"READ");
  
  // the canvas
  if( logScaleY ) cname += "_log";
//else            cname += "_lin";
  TCanvas* c_=new TCanvas(cname,ctitle,300,300,479,510);
  c_->SetLeftMargin(  87./479 );
  c_->SetRightMargin( 42./479 );
  c_->SetTopMargin(  30./510 );
  c_->SetBottomMargin( 80./510 ); 
  c_->SetFillColor(0);
  c_->SetTickx(1);
  c_->SetTicky(1);
  c_->SetFrameFillStyle(0);
  c_->SetFrameLineWidth(2);
  c_->SetFrameBorderMode(0);
  Double_t scale = 4;
  Double_t wbin = 42*scale;
  Double_t left  = 8*scale;
  Double_t right = 5*scale;
  Double_t h1 = 135*scale;
  Double_t h2 = 45*scale;
  Double_t top1 = 15*scale;
  Double_t bot1 = 3*scale;
  Double_t top2 = 3*scale;
  //  Double_t bot1 = 0*scale;
  //  Double_t top2 = 0*scale;
  Double_t bot2 = 80*scale;
  Double_t W = left + wbin + right;
  Double_t H = h1 + h2;
  Double_t s[2] = {1, h1/h2 };

  TPad* pad[2];
  pad[0] = new TPad( "top", "top", 
		     0, h2/H, 1, 1,
		     kWhite,0,0);
  pad[0]->SetLeftMargin(  left/W );
  pad[0]->SetRightMargin( right/W );
  pad[0]->SetTopMargin(  top1/H );
  pad[0]->SetBottomMargin( bot1/H );

  pad[1] = new TPad( "bottom", "bottom", 
		     0, 0, 1, h2/H,
		     kWhite,0,0);
  pad[1]->SetLeftMargin(  left/W );
  pad[1]->SetRightMargin( right/W );
  pad[1]->SetTopMargin(  top2/H );
  pad[1]->SetBottomMargin( bot2/H );
  pad[1]->SetGridy();

  for( int ii=0; ii<2; ii++ )
    {
      pad[ii]->SetFillColor(0);
      pad[ii]->SetTickx(1);
      pad[ii]->SetTicky(1);
      pad[ii]->SetFrameFillStyle(0);
      pad[ii]->SetFrameLineWidth(2);
      pad[ii]->SetFrameBorderMode(0);
      pad[ii]->SetFrameFillStyle(0);
      pad[ii]->SetFrameLineWidth(2);
      pad[ii]->SetFrameBorderMode(0);
    }

  // a dummy histogram with the correct x axis
  // Warning: setTDRstyle() must be called before
  cout << nbin_<<endl;
  TH1F* h_= new TH1F( "bidon", "bidon", nbin_, xmin_, xmax_ );
  TAxis* ax_ = h_->GetXaxis();
  TAxis* ay_ = h_->GetYaxis();
  
  ax_->SetTitle(xtitle);
  ax_->CenterTitle();
  ax_->SetNdivisions(ndivx);
  ax_->SetTitleOffset(1.0);
  ax_->SetTitleSize( 1.4*ax_->GetTitleSize() );
  ax_->SetLabelSize( 1.2*ax_->GetLabelSize() );


  ay_->SetTitle(ytitle);
  ay_->CenterTitle();
  ay_->SetNdivisions(ndivy);
  /*if(logScaleY) */ titleOffset *=1.1;
  ay_->SetTitleOffset(titleOffset);
  ay_->SetLabelOffset(0.015);
  ay_->SetLabelSize( 1.2*ay_->GetLabelSize() );
  ay_->SetTitleSize( 1.4*ay_->GetTitleSize() );


  // fetch histograms and dress them
  vector<TH1F*> histos;
  for( int ii=0; ii<nChan; ii++ )
    {
      TH1F* tmp = (TH1F*)f_->Get(channels[ii]);
      tmp->Rebin(rb);
      tmp->SetStats(kFALSE);
      //      tmp->UseCurrentStyle();
      tmp->SetFillStyle( 1001 );
      tmp->SetFillColor( fillColor_[type[ii]] );
      tmp->SetLineColor( lineColor_[type[ii]] );
      tmp->SetLineWidth( lineWidth2 );
      histos.push_back(tmp);
    }

  TH1* h_sig = (TH1*) histos[0]->Clone();
  h_sig->SetFillStyle(0);
  h_sig->SetLineColor(lineColor_["Signal"]);
  h_sig->SetLineWidth( 2 );
  h_sig->SetLineStyle( kDashed );
  TH1* h_tot = (TH1*) histos[0]->Clone();
  h_tot->SetFillStyle(0);

  //
  // stack histogram
  //
  THStack* stackedHisto=new THStack("stackedHisto","XXX");
  TH1F* totalHisto(0);
  for(int ii=0;ii<nChan;ii++) 
    {
      stackedHisto->Add(histos[nChan-ii-1],"ah");
      
      if(ii==0)
	{
	  totalHisto = (TH1F*)histos[ii]->Clone();
	}
      else
	{
	  totalHisto->Add(histos[ii]);
	}
    }
  
  // colors the stacked histogram
  totalHisto->SetLineColor( lineColor_["Signal"] );
  totalHisto->SetFillColor( 0 );
  totalHisto->SetLineWidth( lineWidth1 );
  
  // The data points are presented as a TGraph 
  // possibly a TGraph with asymmetric errors where
  // - error bars indicate the Poisson confidence interval at 68%
  // - bins with zero entry are removed
  //  TGraphAsymmErrors* dataGraph = (TGraphAsymmErrors*)f_->Get("data");
  // The data points are presented as a TGraph 
  // possibly a TGraph with asymmetric errors where
  // - error bars indicate the Poisson confidence interval at 68%
  // - bins with zero entry are removed
  TH1* hdata = (TH1*) f_->Get( dataHistName );  
  assert( hdata );
  hdata->Rebin(rb);

  RooHist* roohist;
  TGraphAsymmErrors* dataGraph;

  roohist = new RooHist((*hdata));

  int Nn0=0;
  vector<double> vY;
  vector<double> vX;
  vector<double > veY;
  vector<double > veX;
  vector<double> tmp(0,2);

  for(int ip=0;ip<roohist->GetN();ip++) {
    double Y,X;
    //    double eY[2],eX[2];
    roohist->GetPoint(ip,X,Y);

    if(Y!=0) 
      {
	Nn0++;
	
	vY.push_back(Y);
	vX.push_back(X);
	veX.push_back( roohist->GetErrorXlow(ip) );
	veX.push_back( roohist->GetErrorXhigh(ip) );
	veY.push_back( roohist->GetErrorYlow(ip) );
	veY.push_back( roohist->GetErrorYhigh(ip) );
      }
  }
  dataGraph=new TGraphAsymmErrors(Nn0);
  for(int ip=0;ip<Nn0;ip++) 
    {
      dataGraph->SetPoint(ip,vX[ip],vY[ip]);
      dataGraph->SetPointError(ip,veX[ip*2],veX[ip*2+1],veY[ip*2],veY[ip*2+1]);
    }
  
  dataGraph->SetName("data");
  dataGraph->SetMarkerStyle(kFullCircle);
  dataGraph->SetMarkerColor(kBlack);
  if(logScaleY) markerSize *= 0.45;
  else markerSize *= 0.7;
  dataGraph->SetMarkerSize(markerSize);
  
  TGraph* dummyGraph = (TGraph*) dataGraph->Clone("dummyGraph");
  dummyGraph->SetLineColor(0);
  dummyGraph->SetMarkerSize(1.5*markerSize);

  // Remove the null bins
  double x_(0), y_(0);
  for( int ii=0; ii<dataGraph->GetN(); ii++ )
    {
      dataGraph->SetPointEXlow(ii,0);
      dataGraph->SetPointEXhigh(ii,0);
      dataGraph->GetPoint(ii,x_,y_ );
      if( y_==0 )
	{
	  dataGraph->RemovePoint( ii );
	  ii--;
	}	  
    }

  // get the ratio data/fit
  TGraphAsymmErrors* ratioGraph = (TGraphAsymmErrors*) dataGraph->Clone("ratio");
  TH1* hfit = totalHisto;
  for( int ii=0; ii<dataGraph->GetN(); ii++ )
    {
      dataGraph->GetPoint(ii,x_,y_ );
      ratioGraph->SetPointEYlow(ii,0);
      ratioGraph->SetPointEYhigh(ii,0);
      ratioGraph->SetPoint(ii,x_,0 );
      double eyl_ = dataGraph->GetErrorYlow(ii);
      double eyh_ = dataGraph->GetErrorYhigh(ii);
      int jj = hfit->FindBin(x_);
      float fit_ = hfit->GetBinContent( jj );
      if( fit_>0 )
	{
	  if( use_chi )
	    {
	      ratioGraph->SetPointEYlow(ii,eyl_/sqrt(fit_));
	      ratioGraph->SetPointEYhigh(ii,eyh_/sqrt(fit_));
	      ratioGraph->SetPoint(ii,x_,(y_-fit_)/sqrt(fit_) );
	    }
	  else
	    {
	      ratioGraph->SetPointEYlow(ii,eyl_/fit_);
	      ratioGraph->SetPointEYhigh(ii,eyh_/fit_);
	      ratioGraph->SetPoint(ii,x_,y_/fit_ );
	    }
	}
      //      cout << ii << " ratio=" << ratioGraph->GetY()[ii] 
      //       	   << "+" << ratioGraph->GetEYhigh()[ii] 
      //	   << "-" << ratioGraph->GetEYlow()[ii] << endl;
    }
  
  TH1* hratio_ = (TH1*) h_->Clone("hratio");
  ax_->SetLabelOffset(99);
  ax_->SetTitleOffset(99);

  //
  // now plotting
  //  
  c_->Draw();
  c_->cd();

  TPad* p_ = pad[0];
  p_->Draw();
  p_->cd();

  if( logScaleY )
    {
      p_->SetLogy(true);
    }
  else
    {
      p_->SetLogy(false);
    }
  
  if( !logScaleY )
    {
      h_->GetYaxis()->SetRangeUser(ymin_+0.001*(ymax_-ymin_),rb*ymax_);
    }
  else
    {
      h_->GetYaxis()->SetRangeUser(yminl_,rb*ymaxl_);
    }

  h_->Draw("hist");
  
  float dxl_ = scalel_*3.5;
  float dyl_ = scalel_*(nChan+0.5);
  TLegend* legend=new TLegend(xl_,yl_,xl_+dxl_,yl_+dyl_);
  legend->SetTextFont(42);
  legend->SetTextSize(0.045);
  legend->SetLineColor(0);
  legend->SetFillColor(0);
  
  legend->AddEntry(dummyGraph,"  data","pl");
  legend->AddEntry(dummyGraph,"      ","0"); // skip a line

  for( int ii=0; ii<nChan; ii++ ) 
    {
      legend->AddEntry(histos[ii],hnames[ii],"f");
    }
  legend->Draw("same");

  stackedHisto->Draw("samehist");
  h_sig->Draw("samehist");
  totalHisto->Draw("samehist");

  // draw the data points
  dataGraph->Draw("PE");

  // redraw axis
  p_->RedrawAxis();

  //lumi pad, cms prelim pad etc..
  {
    int txtFont = 42;
    float txtSize1 = 0.055;
    float txtX1 = 0.91;
    float txtY1 = 0.935;

    float txtSize2 = 0.05;
    float txtX2 = 0.85;
    float txtY2 = 0.83;
    
    TLatex latex;
    latex.SetNDC();
    latex.SetTextFont(txtFont);
    
    latex.SetTextSize(txtSize1);    
    latex.SetTextAlign(31); // align right
//  latex.DrawLatex(txtX1,txtY1,"CMS preliminary");
    latex.DrawLatex(txtX1,txtY1,"CMS");

    latex.SetTextAlign(31); // align right
    latex.SetTextSize(txtSize2);
    latex.DrawLatex(txtX2,txtY2,"36 pb^{-1}  at  #sqrt{s} = 7 TeV");
  }

  c_->cd();
  
  p_ = pad[1];
  p_->Draw();
  p_->cd();

  TAxis* xratio_ = hratio_->GetXaxis();
  TAxis* yratio_ = hratio_->GetYaxis();

  yratio_->SetRangeUser(r0_-0.9999*dr_,r0_+0.9999*dr_);
  yratio_->SetLabelSize( s[1]*yratio_->GetLabelSize() );
  yratio_->SetTitleSize( s[1]*yratio_->GetTitleSize() );
  yratio_->SetLabelOffset( yratio_->GetLabelOffset() );
  yratio_->SetTitleOffset( yratio_->GetTitleOffset()/s[1] );
  if( use_chi )
    {
      yratio_->SetTitle("#chi");
      yratio_->SetNdivisions(4);
    }
  else
    {
      yratio_->SetTitle("data/fit");
      yratio_->SetNdivisions(3);
    }

  xratio_->SetLabelSize( s[1]*xratio_->GetLabelSize() );
  xratio_->SetTitleSize( s[1]*xratio_->GetTitleSize() );
  xratio_->SetTitleOffset( 1.0 );
  xratio_->CenterTitle();
  xratio_->SetLabelOffset( xratio_->GetLabelOffset()*s[1] );
  xratio_->SetTickLength( xratio_->GetTickLength()*s[1] );

  hratio_->Draw();
  ratioGraph->SetMarkerSize( ratioGraph->GetMarkerSize()*1. );
  ratioGraph->SetLineColor( kBlack );

  ratioGraph->SetMarkerColor( kGray+2 );
  ratioGraph->SetMarkerStyle( kFullCircle );
  ratioGraph->DrawClone("PE");
  ratioGraph->SetMarkerColor( kBlack );
  ratioGraph->SetMarkerStyle( kOpenCircle );
  ratioGraph->DrawClone("PE");

  p_->RedrawAxis();

  c_->cd();
  c_->SaveAs("plot.pdf");

  return c_;
}
void grabDataSubtractedHistograms() {
  TFile f("Histograms_Mjj_data_and_template.root", "update");


  TFile* fitFile = new TFile( plots_dir + "/mJJ-combined-fit.root", "read");
  TCanvas* fitCan = (TCanvas*) fitFile->Get( "mJJ-combined-fit" );
  RooHist* data = (RooHist*) fitCan->FindObject( "h_data" );
  RooCurve* fit_total = (RooCurve*) fitCan->FindObject( "h_total" );
  RooCurve* fit_diboson = (RooCurve*) fitCan->FindObject( "h_diboson" );
  RooCurve* fit_Wjets = (RooCurve*) fitCan->FindObject( "h_Wjets" );

  RooCurve* fit_Top = (RooCurve*) fitCan->FindObject( "h_Top" );
  RooCurve* fit_QCD = (RooCurve*) fitCan->FindObject( "h_QCD" );
  RooCurve* fit_Zjets = (RooCurve*) fitCan->FindObject( "h_Zjets" );
//   RooCurve* fit_Ztautau = (RooCurve*) fitCan->FindObject( "h_Ztautau" );

  TFile* subtrFile = new TFile( plots_dir + "/mJJ-combined-fit-subtracted.root", "read");
  TCanvas* subtrCan = (TCanvas*) subtrFile->Get( "mJJ-combined-fit-subtracted" );
  RooHist* subtrHist = (RooHist*) subtrCan->FindObject( "resid_h_data_h_Background" );
  RooCurve* Diboson = (RooCurve*) subtrCan->FindObject( "h_diboson" );



//   TFile* fitFile1 = new TFile( plots_dir + "/mJJ-mu-fit.root", "read");
//   TCanvas* fitCan1 = (TCanvas*) fitFile1->Get( "mJJ-mu-fit" );
//   RooHist* data1 = (RooHist*) fitCan1->FindObject( "h_data" );
//   RooCurve* fit1 = (RooCurve*) fitCan1->FindObject( "h_total" );

//   TFile* subtrFile1 = new TFile( plots_dir + "/mJJ-mu-fit-subtracted.root", "read");
//   TCanvas* subtrCan1 = (TCanvas*) subtrFile1->Get( "mJJ-mu-fit-subtracted" );
//   RooHist* subtrHist1 = (RooHist*) subtrCan1->FindObject( "resid_h_data_h_Background" );
//   RooCurve* Diboson1 = (RooCurve*) subtrCan1->FindObject( "h_diboson" );



//   TFile* fitFile2 = new TFile( plots_dir + "/mJJ-ele-fit.root", "read");
//   TCanvas* fitCan2 = (TCanvas*) fitFile2->Get( "mJJ-ele-fit" );
//   RooHist* data2 = (RooHist*) fitCan2->FindObject( "h_data" );
//   RooCurve* fit2 = (RooCurve*) fitCan2->FindObject( "h_total" );

//   TFile* subtrFile2 = new TFile( plots_dir + "/mJJ-ele-fit-subtracted.root", "read");
//   TCanvas* subtrCan2 = (TCanvas*) subtrFile2->Get( "mJJ-ele-fit-subtracted" );
//   RooHist* subtrHist2 = (RooHist*) subtrCan2->FindObject( "resid_h_data_h_Background" );
//   RooCurve* Diboson2 = (RooCurve*) subtrCan2->FindObject( "h_diboson" );


  // --------- Now save everything in the output file -------
 f.cd();
 data->Write("hist_data");
 fit_total->Write("fit_total");
 fit_diboson->Write("fit_diboson");
 fit_Wjets->Write("fit_Wjets");
 fit_Top->Write("fit_Top");
 fit_QCD->Write("fit_QCD");
 fit_Zjets->Write("fit_Zjets");
//  fit_Ztautau->Write("fit_Ztautau");

 subtrHist->Write("hist_data_subtracted");
 Diboson->Write("curve_diboson");

//  data1->Write("hist_data_muon");
//  fit1->Write("curve_fit_muon");
//  subtrHist1->Write("hist_data_subtracted_muon");
//  Diboson1->Write("curve_diboson_muon");

//  data2->Write("hist_data_electron");
//  fit2->Write("curve_fit_electron");
//  subtrHist2->Write("hist_data_subtracted_electron");
//  Diboson2->Write("curve_diboson_electron");

 f.Close();
}
void estimateSignalFitPerformance()
{
  //open the ROOT efficiency file
  TFile ROOTFile(efficiencyFile.c_str());
  if (!ROOTFile.IsOpen()) {
    cerr << "Error opening file " << efficiencyFile << ".\n";
    return;
  }

  //get numBackgroundFail, numBackgroundPass, numSignalAll, and efficiency
  RooFitResult* fitResult = NULL;
  ROOTFile.GetObject("PhotonToIDEB/unbinned/probe_eta_bin0__probe_nJets05_bin0__gaussPlusLinear/fitresults", fitResult);
  Double_t efficiency = 0.0;
  Double_t efficiencyError = 0.0;
  Double_t numBackgroundFail = 0.0;
  Double_t numBackgroundFailError = 0.0;
  Double_t numBackgroundPass = 0.0;
  Double_t numBackgroundPassError = 0.0;
  Double_t numSignalAll = 0.0;
  Double_t numSignalAllError = 0.0;
  if (fitResult != NULL) {
    RooRealVar* theEfficiency = (RooRealVar*)fitResult->floatParsFinal().find("efficiency");
    efficiency = theEfficiency->getVal();
    efficiencyError = theEfficiency->getError();
    RooRealVar* theNumBackgroundFail = (RooRealVar*)fitResult->floatParsFinal().find("numBackgroundFail");
    numBackgroundFail = theNumBackgroundFail->getVal();
    numBackgroundFailError = theNumBackgroundFail->getError();
    RooRealVar* theNumBackgroundPass = (RooRealVar*)fitResult->floatParsFinal().find("numBackgroundPass");
    numBackgroundPass = theNumBackgroundPass->getVal();
    numBackgroundPassError = theNumBackgroundPass->getError();
    RooRealVar* theNumSignalAll = (RooRealVar*)fitResult->floatParsFinal().find("numSignalAll");
    numSignalAll = theNumSignalAll->getVal();
    numSignalAllError = theNumSignalAll->getError();
  }
  else {
    cerr << "Error getting RooFitResult PhotonToIDEB/unbinned/probe_eta_bin0__probe_nJets05_bin0__gaussPlusLinear/fitresults from file ";
    cerr << efficiencyFile << ".\n";
  }

  //get integrals of tag-pass and tag-fail distributions
  TCanvas* fitCanvas = NULL;
  ROOTFile.GetObject("PhotonToIDEB/unbinned/probe_eta_bin0__probe_nJets05_bin0__gaussPlusLinear/fit_canvas", fitCanvas);
  Double_t tagPassIntegral = 0;
  Double_t tagFailIntegral = 0;
  if (fitCanvas != NULL) {
    fitCanvas->cd(1);
    RooHist* tagPassDistribution = NULL;
    tagPassDistribution = (RooHist*)((TCanvas*)fitCanvas->GetPrimitive("fit_canvas_1"))->GetPrimitive("h_data");
    fitCanvas->cd(2);
    RooHist* tagFailDistribution = NULL;
    tagFailDistribution = (RooHist*)((TCanvas*)fitCanvas->GetPrimitive("fit_canvas_2"))->GetPrimitive("h_data");
    RooHist* blah = NULL;
    blah = (RooHist*)((TCanvas*)fitCanvas->GetPrimitive("fit_canvas_3"))->GetPrimitive("h_data");
    cerr << blah->Integral() << endl;
    if ((tagPassDistribution != NULL) && (tagFailDistribution != NULL)) {
      tagPassIntegral = tagPassDistribution->Integral()*/*1.796*/1.844;
      tagFailIntegral = tagFailDistribution->Integral()*/*1.796*/1.844;
    }
    else cerr << "Error: could not get RooPlots.\n";
  }
  else {
    cerr << "Error getting TCanvas PhotonToIDEB/unbinned/probe_eta_bin0__probe_nJets05_bin0__gaussPlusLinear/fit_canvas from file ";
    cerr << efficiencyFile << ".\n";
  }

  //close file
  ROOTFile.Close();

  //subtract fitted background from integral
  Double_t tagPassNumBkgSubtractedEvts = tagPassIntegral - numBackgroundPass;
  Double_t tagPassNumBkgSubtractedEvtsError = numBackgroundPassError;
  Double_t tagFailNumBkgSubtractedEvts = tagFailIntegral - numBackgroundFail;
  Double_t tagFailNumBkgSubtractedEvtsError = numBackgroundFailError;

  //calculate fitted signal
  Double_t tagPassNumFittedSignal = efficiency*numSignalAll;
  Double_t tagPassNumFittedSignalError = tagPassNumFittedSignal*sqrt(((efficiencyError*efficiencyError)/(efficiency*efficiency)) + 
								     ((numSignalAllError*numSignalAllError)/(numSignalAll*numSignalAll)));
  Double_t tagFailNumFittedSignal = (1.0 - efficiency)*numSignalAll;
  Double_t tagFailNumFittedSignalError = tagFailNumFittedSignal*
    sqrt(((efficiencyError*efficiencyError)/((1.0 - efficiency)*(1.0 - efficiency))) + 
	 ((numSignalAllError*numSignalAllError)/(numSignalAll*numSignalAll)));

  //calculate difference between signal fit result and background subtracted integral
  Double_t tagPassDifference = tagPassNumBkgSubtractedEvts - tagPassNumFittedSignal;
  Double_t tagPassDifferenceError = sqrt(tagPassNumBkgSubtractedEvtsError*tagPassNumBkgSubtractedEvtsError + 
					 tagPassNumFittedSignalError*tagPassNumFittedSignalError);
  Double_t tagFailDifference = tagFailNumBkgSubtractedEvts - tagFailNumFittedSignal;
  Double_t tagFailDifferenceError = sqrt(tagFailNumBkgSubtractedEvtsError*tagFailNumBkgSubtractedEvtsError + 
					 tagFailNumFittedSignalError*tagFailNumFittedSignalError);

  //compare signal fit result to background subtracted integral
  cout << "Tag pass signal fit: " << tagPassNumFittedSignal << " +/- " << tagPassNumFittedSignalError << endl;
  cout << "Tag pass background subtracted integral: " <<  tagPassNumBkgSubtractedEvts << " +/- " << tagPassNumBkgSubtractedEvtsError;
  cout << endl;
  cout << "Difference: " << tagPassDifference << " +/- " << tagPassDifferenceError << endl;
  cout << "Tag fail signal fit: " << tagFailNumFittedSignal << " +/- " << tagFailNumFittedSignalError << endl;
  cout << "Tag fail background subtracted integral: " <<  tagFailNumBkgSubtractedEvts << " +/- " << tagFailNumBkgSubtractedEvtsError;
  cout << endl;
  cout << "Difference: " << tagFailDifference << " +/- " << tagFailDifferenceError << endl;
}