void dominik()
{
  TH1* matHistogramRoman = static_cast<TH1*>(extractObjectFromFile("lyRoman.root", "lightYieldProjectionY")->At(0));
  TList* objects = extractObjectFromFile("c.root", "chargeBins");
  TH1* matHistogramDominik = new TH1D("matHistogramDominik", ";channel;light yield / pixels", 512, -0.5, 512-0.5);
  int sipmIt = 0;
  for (int i = 0; i < objects->GetSize(); ++i) {
    TH1* h = static_cast<TH1*>(objects->At(i));
    if (h->GetLineColor() == 8) {
      for (int bin = 1; bin <= 128; ++bin) {
        matHistogramDominik->SetBinContent(512 - (sipmIt * 128 + bin - 1), h->GetBinContent(bin));
        if (h->GetBinError(bin) > 0)
          matHistogramDominik->SetBinError(512 - (sipmIt * 128 + bin - 1), h->GetBinError(bin));
      }
      ++sipmIt;
    }
  }
  TCanvas* c = new TCanvas;
  c->Divide(1, 2);
  c->cd(1);
  matHistogramDominik->Draw();
  matHistogramRoman->Draw("SAME");
  c->cd(2);
  TH1* h = static_cast<TH1*>(matHistogramDominik->Clone());
  h->Add(matHistogramRoman, -1);
  h->Draw();
}
Beispiel #2
0
// ===  FUNCTION  ============================================================
//         Name:  TPlot::GetEffHist
//  Description:  
// ===========================================================================
TH1* TPlot::GetEffHist(std::string Eff, std::string det, std::string algo)
{

  TH1* hNum = GetHist1D(listEff[Eff].first, det, algo);

  TH1* hDem = GetHist1D(listEff[Eff].second, det, algo);

  TH1* temp = (TH1*)hNum->Clone(Eff.c_str());

  assert(hNum->GetNbinsX() == hDem->GetNbinsX());
  for (int i = 0; i < hNum->GetNbinsX(); ++i)
  {
    double val = hNum->GetBinContent(i) / hDem->GetBinContent(i);
    double valerr = val * sqrt( pow(hNum->GetBinError(i)/hNum->GetBinContent(i), 2) +
        pow(hDem->GetBinError(i)/hDem->GetBinContent(i), 2) );
    if (isnan(val)) { val = 0; valerr = 0; }
    temp->SetBinContent(i, val);
    temp->SetBinError(i, valerr);
    std::cout << " bin " <<i <<" val " << val << std::endl;
  }

  //temp->Divide(hDem);
  temp->GetYaxis()->SetTitle("Efficiency");

  return temp;
}       // -----  end of function TPlot::GetEffHist  -----
Beispiel #3
0
void fit() {
  FILE *ofile;
  ofile = fopen("xsect-integrated-me.txt","w");
  TFile *_file0 = TFile::Open("h3maker-hn.root","update");
  _file0->Delete("*_f;*");
  TH2 *h2xsect = new TH2("hq2wXsect","Q^2:W",32,1.6,3.2,7,1.5,5.1);
  Double_t qbinedges[] = { 1.5, 1.6, 1.8, 2.1, 2.4, 2.76, 3.3, 5.1 };
  h2xsect->GetYaxis()->Set(7,qbinedges);
  TH3 *h3 = (TH3*)_file0->Get("hq2wmmp");
  int qbins = h3->GetZaxis()->GetNbins();
  int wbins = h3->GetYaxis()->GetNbins();
  fprintf(ofile, "W\tQ2\txsect\terror\tpol4p0\tpol4p1\tpol4p2\tpol4p3\tpol4p4\tgN\tgM\tgS\n");
  for (int iq = 0; iq < qbins; iq++) {
    TString hsn = TString::Format("hs%d",iq);
    THStack *hs = (THStack*)_file0->Get(hsn.Data());
    TIter next(hs->GetHists());
    //while (TObject *obj = next()) {
    //TH1 *h = (TH1*)obj;
    while (TH1 *h = (TH1*)next()) {
      float *wq = getwq(h);
      float wval = wq[0];
      float qval = wq[1];
      fitmmp(h);
      TH1 *htmp = (TH1*)h->Clone("hbgsubtracted");
      TF1 *fbg = (TF1*)h->GetListOfFunctions()->FindObject("fbg");
      htmp->Add(fbg,-1);
      double N = htmp->Integral(34,43);
      double qwidth = h3->GetZaxis()->GetBinWidth(iq+1);
      int wbin = h3->GetYaxis()->FindBin(wval);
      double wwidth = h3->GetYaxis()->GetBinWidth(wbin);
      double xsect = N/(0.891*wwidth*qwidth*19.844);
      double err2 = 0;
      for (int immp = 34; immp < 44; immp++) err2 += htmp->GetBinError(immp)*htmp->GetBinError(immp);
      //fprintf(ofile, "%.3f\t%.3f\t%.0f\t%.0f",wval,qval,xsect/(1e6), sqrt(err2)/(1e6));
      fprintf(ofile, "%.3f\t%.3f\t%.3e\t%.3e",wval,qval,xsect/(1e6), sqrt(err2)/(1e6));
      TF1 *ftmp = (TF1*)h->GetListOfFunctions()->At(0);
      int npar = ftmp->GetNpar();
      for (int ipar = 0; ipar < npar; ipar++) fprintf(ofile, "\t%.3e", ftmp->GetParameter(ipar));
      fprintf(ofile, "\n");
    }
    hsn.Append("_f");
    _file0->WriteObject(hs,hsn.Data());
    delete hs;
  }
  fclose(ofile);
  delete _file0;
}
Beispiel #4
0
  /** 
   * Create ratios to other data 
   * 
   * @param ib      Bin number  
   * @param res     Result
   * @param alice   ALICE result if any
   * @param cms     CMS result if any
   * @param all     Stack to add ratio to 
   */
  void Ratio2Stack(Int_t ib, TH1* res, TGraph* alice, TGraph* cms, THStack* all)
  {
    if (!all || !res || !(alice || cms)) return;

    Int_t        off  = 5*ib;
    TGraph*      gs[] = { (alice ? alice : cms), (alice ? cms : 0), 0 };
    TGraph**     pg   = gs;
    while (*pg) { 
      TGraph*     g = *pg;
      const char* n = (g == alice ? "ALICE" : "CMS");

      TH1*    r = static_cast<TH1*>(res->Clone(Form("ratio%s", n)));
      TString tit(r->GetTitle());
      tit.ReplaceAll("Corrected", Form("Ratio to %s", n));
      r->SetTitle(tit);
      r->SetMarkerColor(g->GetMarkerColor());
      r->SetLineColor(g->GetLineColor());

      TObject* tst = r->FindObject("legend");
      if (tst) r->GetListOfFunctions()->Remove(tst);

      for (Int_t i = 1; i <= r->GetNbinsX(); i++) {
	Double_t c = r->GetBinContent(i);
	Double_t e = r->GetBinError(i);
	Double_t o = g->Eval(r->GetBinCenter(i));
	if (o < 1e-12) { 
	  r->SetBinContent(i, 0);
	  r->SetBinError(i, 0);
	  continue;
	}
	r->SetBinContent(i, (c - o) / o + off);
	r->SetBinError(i, e / o);
      }
      all->Add(r);
      pg++;
    }
    TLegend* leg = StackLegend(all);
    if (!leg) return;
      
    TString   txt      = res->GetTitle();
    txt.ReplaceAll("Corrected P(#it{N}_{ch}) in ", "");
    if      (ib == 0) txt.Append(" "); // (#times1)");
    // else if (ib == 1) txt.Append(" (#times10)");
    else              txt.Append(Form(" (+%d)", off));

    TObject* dummy = 0;
    TLegendEntry* e = leg->AddEntry(dummy, txt, "p");
    e->SetMarkerStyle(res->GetMarkerStyle());
    e->SetMarkerSize(res->GetMarkerSize());
    e->SetMarkerColor(kBlack);
    e->SetFillColor(0);
    e->SetFillStyle(0);
    e->SetLineColor(kBlack);
  }
Beispiel #5
0
void ScaleTo10pb( TH1& hist) {

  int bins = hist.GetNbinsX();
  double error = 0;

  for(int i=1; i<= bins; i++) {
    error = 8.0 * hist.GetBinError(i);
    // if( error > 1.0 ) error = 1.0;
    hist.SetBinError(i, error);
  }

}
RooHistN::RooHistN(const TH1 &data, Double_t nominalBinWidth, Double_t nSigma, RooAbsData::ErrorType etype, Double_t xErrorFrac) :
  TGraphAsymmErrors(), _nominalBinWidth(nominalBinWidth), _nSigma(nSigma), _rawEntries(-1)
{
  // Create a histogram from the contents of the specified TH1 object
  // which may have fixed or variable bin widths. Error bars are
  // calculated using Poisson statistics. Prints a warning and rounds
  // any bins with non-integer contents. Use the optional parameter to
  // specify the confidence level in units of sigma to use for
  // calculating error bars. The nominal bin width specifies the
  // default used by addBin(), and is used to set the relative
  // normalization of bins with different widths. If not set, the
  // nominal bin width is calculated as range/nbins.

  initialize();
  // copy the input histogram's name and title
  SetName(data.GetName());
  SetTitle(data.GetTitle());
  // calculate our nominal bin width if necessary
  if(_nominalBinWidth == 0) {
    const TAxis *axis= ((TH1&)data).GetXaxis();
    if(axis->GetNbins() > 0) _nominalBinWidth= (axis->GetXmax() - axis->GetXmin())/axis->GetNbins();
  }
  // TH1::GetYaxis() is not const (why!?)
  setYAxisLabel(const_cast<TH1&>(data).GetYaxis()->GetTitle());
  
  // initialize our contents from the input histogram's contents
  Int_t nbin= data.GetNbinsX();
  for(Int_t bin= 1; bin <= nbin; bin++) {
    Axis_t x= data.GetBinCenter(bin);
    Stat_t y= data.GetBinContent(bin);
    Stat_t dy = data.GetBinError(bin) ;
    if (etype==RooAbsData::Poisson) {
      addBin(x,roundBin(y),data.GetBinWidth(bin),xErrorFrac);
    } else {
      addBinWithError(x,y,dy,dy,data.GetBinWidth(bin),xErrorFrac);
    }
  }
  // add over/underflow bins to our event count
  _entries+= data.GetBinContent(0) + data.GetBinContent(nbin+1);
}
Beispiel #7
0
void writeFile(const char* inRootFile)
{
  TFile inRoot(inRootFile);
  if(!inRoot.IsOpen()){
    cout << "Cannot open " << inRootFile << endl;
    return;
  }
  TIterator* iterator = inRoot.GetListOfKeys()->MakeIterator();
  TKey* key;

  TString outText = inRootFile;
  outText.Replace(0,outText.Last('/')+1,"");

  ofstream os(outText.Data());

  char buf[500];

  int count(0);
  while( (key=dynamic_cast<TKey*>(iterator->Next())) != 0){
    cout << key->GetName() << endl;
    TH1* h = (TH1*)inRoot.Get(key->GetName());
    if(h->GetDimension()!=1) continue;

    if(++count>1) break;

    int nBin = h->GetNbinsX();
    os << "name: " << h->GetName() << endl
       << "title: " << h->GetTitle() << endl
       << "bins: " << h->GetNbinsX() << endl
       << "min: " << h->GetXaxis()->GetBinLowEdge(1) 
       << ", max: " << h->GetXaxis()->GetBinUpEdge(h->GetNbinsX()) << endl;

    for(int i=1; i<=nBin; i++){
      os << "bin: " << i << " value: " << (float)h->GetBinContent(i)
	 << " error: " << (float)h->GetBinError(i) << endl;
    }
  }
   
}
Beispiel #8
0
void Template::makeResidualsControlPlot(const string& tag, unsigned int rebin)
/*****************************************************************/
{
    if(numberOfDimensions()>0 && m_template->GetNbinsX()%rebin!=0) return;
    if(numberOfDimensions()>1 && m_template->GetNbinsY()%rebin!=0) return;
    if(numberOfDimensions()>2 && m_template->GetNbinsZ()%rebin!=0) return;

    stringstream cpName, cpRawName, resMapName, resDistName, relErrDistName;
    cpName << m_name << "_cp";
    cpRawName << m_name << "_rawcp";
    resMapName << m_name << "_resmap_" << tag << "_rebin" << rebin;
    resDistName << m_name << "_resdist_" << tag << "_rebin" << rebin;
    relErrDistName << m_name << "_relerrdist_" << tag << "_rebin" << rebin;
    TH1* cpTmp = NULL;
    TH1* cpRawTmp = NULL;
    if(rebin==1)
    {
        cpTmp = dynamic_cast<TH1*>(m_template->Clone(cpName.str().c_str()));
        cpRawTmp = dynamic_cast<TH1*>(m_rawTemplate->Clone(cpRawName.str().c_str()));
    }
    else
    {
        if(numberOfDimensions()==2)
        {
            cpTmp = dynamic_cast<TH2F*>(m_template)->Rebin2D(rebin, rebin, cpName.str().c_str());
            cpRawTmp = dynamic_cast<TH2F*>(m_rawTemplate)->Rebin2D(rebin, rebin, cpName.str().c_str());
        }
        else if(numberOfDimensions()==3)
        {
            cpTmp = dynamic_cast<TH3F*>(m_template)->Rebin3D(rebin, rebin, rebin, cpName.str().c_str());
            cpRawTmp = dynamic_cast<TH3F*>(m_rawTemplate)->Rebin3D(rebin, rebin, rebin, cpName.str().c_str());
        }
    }
    TH1* resMap = dynamic_cast<TH1*>(cpTmp->Clone(resMapName.str().c_str()));
    TH1D* resDist = new TH1D(resDistName.str().c_str(), resDistName.str().c_str(), 30, -3, 3);
    resDist->StatOverflows();
    TH1D* relErrDist = new TH1D(relErrDistName.str().c_str(), relErrDistName.str().c_str(), 200, -1, 1);
    relErrDist->StatOverflows();
    unsigned int nbins1 = cpTmp->GetNbinsX();
    unsigned int nbins2 = cpTmp->GetNbinsY();
    unsigned int nbins3 = cpTmp->GetNbinsZ();
    for(unsigned int b1=1;b1<=nbins1;b1++)
    {
        for(unsigned int b2=1;b2<=nbins2;b2++)
        {
            for(unsigned int b3=1;b3<=nbins3;b3++)
            {
                double tmpValue = cpTmp->GetBinContent(b1,b2,b3);
                double tmpRawValue = cpRawTmp->GetBinContent(b1,b2,b3);
                double tmpRawError = cpRawTmp->GetBinError(b1,b2,b3);
                if(tmpValue>0. && tmpRawValue>0. && tmpRawError>0.)
                {
                    double res = (tmpRawValue-tmpValue)/tmpRawError;
                    double relErr = (tmpRawValue-tmpValue)/tmpRawValue;
                    if(numberOfDimensions()==2)
                    {
                        resMap->SetBinContent(b1,b2,b3, res);
                        resMap->SetBinError(b1,b2,b3, 0.);
                    }
                    resDist->Fill(res);
                    relErrDist->Fill(relErr);
                }
            }
        }
    }
    stringstream plotMapName, plotDistName, plotErrDistName;
    plotMapName << "control_" << getName() << "_resMap" << "_" << tag << "_rebin" << rebin;
    plotDistName << "control_" << getName() << "_resDist" << "_" << tag << "_rebin" << rebin;
    plotErrDistName << "control_" << getName() << "_relErrDist" << "_" << tag << "_rebin" << rebin;
    if(numberOfDimensions()==2)
    {
        TCanvas* c = new TCanvas(plotMapName.str().c_str(),plotMapName.str().c_str(), 700,700);
        resMap->SetContour(99);
        resMap->SetAxisRange(-3., 3., "z");
        resMap->Draw("color z");
        resMap->SetXTitle(getVariable(0).c_str());
        resMap->SetYTitle(getVariable(1).c_str());
        addControlPlot(c);
    }
    TCanvas* c2 = new TCanvas(plotDistName.str().c_str(),plotDistName.str().c_str(), 700,700);
    resDist->SetLineColor(kBlack);
    resDist->SetLineWidth(2);
    resDist->SetMarkerColor(kBlack);
    resDist->SetMarkerStyle(20);
    resDist->SetXTitle("(raw-template)/error_{raw}");
    resDist->Draw();
    addControlPlot(c2);

    TCanvas* c3 = new TCanvas(plotErrDistName.str().c_str(),plotErrDistName.str().c_str(), 700,700);
    relErrDist->SetLineColor(kBlack);
    relErrDist->SetLineWidth(2);
    relErrDist->SetMarkerColor(kBlack);
    relErrDist->SetMarkerStyle(20);
    relErrDist->SetXTitle("(raw-template)/raw");
    relErrDist->Draw();
    addControlPlot(c3);

    if(cpTmp) delete cpTmp;
    if(cpRawTmp) delete cpRawTmp;
}
Beispiel #9
0
void Fit(TString SIGNAL,TString HISTO,double scaleSGN)
{
  gROOT->ForceStyle();
  TFile *fDat = TFile::Open("Histo_flatTree_data_tmva"+SIGNAL+".root");
  TFile *fBkg = TFile::Open("Histo_flatTree_qcd_weights_tmva"+SIGNAL+".root");
  TFile *fSgn = TFile::Open("Histo_flatTree_"+SIGNAL+"_weights_tmva"+SIGNAL+".root");
  
  TH1 *hDat = (TH1*)fDat->Get(HISTO);
  TH1 *hBkgRaw = (TH1*)fBkg->Get(HISTO);
  TH1 *hSgn = (TH1*)fSgn->Get(HISTO);
  TH1 *hDat_JESlo = (TH1*)fDat->Get(HISTO+"_JESlo");
  TH1 *hBkgRaw_JESlo = (TH1*)fBkg->Get(HISTO+"_JESlo");
  TH1 *hSgn_JESlo = (TH1*)fSgn->Get(HISTO+"_JESlo");
  TH1 *hDat_JESup = (TH1*)fDat->Get(HISTO+"_JESup");
  TH1 *hBkgRaw_JESup = (TH1*)fBkg->Get(HISTO+"_JESup");
  TH1 *hSgn_JESup = (TH1*)fSgn->Get(HISTO+"_JESup");
  
  TH1F *hBkg = (TH1F*)hBkgRaw->Clone("Bkg");
  TH1F *hBkg_JESlo = (TH1F*)hBkgRaw_JESlo->Clone("Bkg_JESlo");
  TH1F *hBkg_JESup = (TH1F*)hBkgRaw_JESup->Clone("Bkg_JESup");
  
  hBkg->Smooth(2);
  hBkg_JESlo->Smooth(2);
  hBkg_JESup->Smooth(2);
  hSgn->Smooth(2);
  hSgn_JESlo->Smooth(2);
  hSgn_JESup->Smooth(2);
  
  double lumi = 4967;
  hBkg->Scale(lumi);
  hBkg_JESlo->Scale(lumi);
  hBkg_JESup->Scale(lumi);
  double k_factor = hDat->Integral()/hBkg->Integral();
  double k_factor_JESlo = hDat->Integral()/hBkg_JESlo->Integral();
  double k_factor_JESup = hDat->Integral()/hBkg_JESup->Integral();
  hBkg->Scale(k_factor);
  cout<<"Signal entries = "<<hSgn->GetEntries()<<endl;
  hSgn->Scale(lumi/scaleSGN);
  hBkg_JESlo->Scale(k_factor_JESlo);
  hSgn_JESlo->Scale(lumi/scaleSGN);
  hBkg_JESup->Scale(k_factor_JESup);
  hSgn_JESup->Scale(lumi/scaleSGN);
  hSgn_JESlo->Scale(hSgn->Integral()/hSgn_JESlo->Integral());
  hSgn_JESup->Scale(hSgn->Integral()/hSgn_JESup->Integral());
  
  TH1 *hBkg_STATlo = (TH1*)hBkg->Clone(HISTO+"_STATlo");
  TH1 *hSgn_STATlo = (TH1*)hSgn->Clone(HISTO+"_STATlo");
  TH1 *hBkg_STATup = (TH1*)hBkg->Clone(HISTO+"_STATup");
  TH1 *hSgn_STATup = (TH1*)hSgn->Clone(HISTO+"_STATup");
  
  float y1,e1;
  for(int i=0;i<hBkg->GetNbinsX();i++) {
    y1 = hBkg->GetBinContent(i+1);
    e1 = hBkg->GetBinError(i+1);
    hBkg_STATlo->SetBinContent(i+1,y1-e1);
    hBkg_STATup->SetBinContent(i+1,y1+e1);
    y1 = hSgn->GetBinContent(i+1);
    e1 = hSgn->GetBinError(i+1);
    hSgn_STATlo->SetBinContent(i+1,y1-e1);
    hSgn_STATup->SetBinContent(i+1,y1+e1);
  }
  hBkg_STATlo->Scale(hBkg->Integral()/hBkg_STATlo->Integral());
  hBkg_STATup->Scale(hBkg->Integral()/hBkg_STATup->Integral());
  hSgn_STATlo->Scale(hSgn->Integral()/hSgn_STATlo->Integral());
  hSgn_STATup->Scale(hSgn->Integral()/hSgn_STATup->Integral());
  
  double xMIN = hBkg->GetBinLowEdge(1);
  double xMAX = hBkg->GetBinLowEdge(hBkg->GetNbinsX()+1);
  double xMIN2 = hDat->GetBinLowEdge(hDat->FindFirstBinAbove(0.5));
  double xMAX2 = hDat->GetBinLowEdge(hDat->FindLastBinAbove(0.5)+1);
  RooRealVar x("x","x",xMIN2,xMAX2);
  
  RooDataHist data("data","dataset with x",x,hDat);
  RooDataHist bkg("qcd","bkg with x",x,hBkg);
  RooDataHist sgn("signal","sgn with x",x,hSgn);
  
  RooHistPdf bkgPDF("bkgPDF","bkgPDF",x,bkg,0);
  RooHistPdf sgnPDF("sgnPDF","sgnPDF",x,sgn,0);
  
  RooRealVar f("f","f",0,0.,1.);
  
  RooAddPdf model("model","model",RooArgList(sgnPDF,bkgPDF),RooArgList(f));
  
  RooFitResult* r = model.fitTo(data,Save());
  r->Print("v");
  double N = hDat->Integral();
  double B = hBkg->Integral();
  double S = hSgn->Integral();
  double m = f.getVal();
  double e = f.getError();
  cout<<"k-factor = "<<k_factor<<endl;
  cout<<N<<" "<<B<<" "<<S<<endl;
  cout<<"Total cross section =       "<<N/lumi<<" pb"<<endl;
  cout<<"Model cross section =       "<<S/lumi<<" pb"<<endl;
  cout<<"Fitted signal strength =    "<<m*N/S<<endl;
  cout<<"Fitted signal error =       "<<e*N/S<<endl;
  double p = 0.95;
  double xup = (N/S)*(m+sqrt(2.)*e*TMath::ErfInverse((1-p)*TMath::Erf(m/e)+p));
  cout<<"Bayesian Upper limit =      "<<xup<<endl;
  RooPlot* frame1 = x.frame();  
  data.plotOn(frame1);
  model.plotOn(frame1,Components("sgnPDF*"),LineStyle(1),LineWidth(2),LineColor(kGreen+1));
  model.plotOn(frame1,Components("bkgPDF*"),LineStyle(1),LineWidth(2),LineColor(kRed));
  model.plotOn(frame1,LineStyle(1),LineWidth(2),LineColor(kBlue));
  
  //cout<<frame1->chiSquare()<<endl;
  RooHist* hresid = frame1->residHist();
  RooHist* hpull = frame1->pullHist();
  RooPlot* frame2 = x.frame(Title("Residual Distribution"));
  frame2->addPlotable(hresid,"P") ;
  
  // Create a new frame to draw the pull distribution and add the distribution to the frame
  RooPlot* frame3 = x.frame(Title("Pull Distribution"));
  frame3->addPlotable(hpull,"P");
  
  TCanvas* cFit = new TCanvas("fitANN_"+SIGNAL,"fitANN_"+SIGNAL,900,600);
  gPad->SetLogy();
  frame1->SetMaximum(1e+4);
  frame1->SetMinimum(0.5);
  frame1->GetXaxis()->SetTitle("ANN Output");
  frame1->GetYaxis()->SetTitle("Events");
  frame1->Draw();
  cout<<frame1->nameOf(3)<<endl;
  TLegend *leg = new TLegend(0.7,0.65,0.9,0.9);
  leg->SetHeader(SIGNAL);
  leg->AddEntry(frame1->findObject("h_data"),"data","P");
  leg->AddEntry(frame1->findObject("model_Norm[x]"),"QCD+Signal","L");
  leg->AddEntry(frame1->findObject("model_Norm[x]_Comp[bkgPDF*]"),"QCD","L");
  leg->AddEntry(frame1->findObject("model_Norm[x]_Comp[sgnPDF*]"),"Signal","L");
  leg->SetFillColor(0);
  leg->SetBorderSize(0);
  leg->SetTextFont(42);
  leg->SetTextSize(0.04);
  leg->Draw();

  TCanvas* cPull = new TCanvas("pullANN_"+SIGNAL,"pullANN_"+SIGNAL,900,400); 
  frame3->GetXaxis()->SetTitle("ANN Output");
  frame3->GetYaxis()->SetTitle("Pull");
  frame3->Draw();
  
  cout<<"Creating datacard"<<endl;
  ofstream datacard;
  datacard.open("datacard_"+SIGNAL+"_"+HISTO+".txt");
  datacard.setf(ios::right);
  datacard<<"imax 1"<<"\n";
  datacard<<"jmax 1"<<"\n";
  datacard<<"kmax *"<<"\n";
  datacard<<"----------------"<<"\n";
  datacard<<"shapes * * "<<SIGNAL+"_"+HISTO+"_input.root $PROCESS $PROCESS_$SYSTEMATIC"<<"\n";
  datacard<<"----------------"<<"\n";
  datacard<<"bin         1"<<"\n";
  datacard<<"observation "<<N<<"\n";
  datacard<<"----------------"<<"\n";
  datacard<<"bin         1       1"<<"\n";
  datacard<<"process     signal  background  "<<"\n";
  datacard<<"process     0       1"<<"\n";
  datacard<<"rate       "<<S<<"    "<<B<<"\n";
  datacard<<"----------------"<<"\n";
  datacard<<"lumi        lnN       1.022    1.022"<<"\n";
  datacard<<"jes         shape     1        1"<<"\n";
  datacard<<"mcstat      shape     1        1"<<"\n";
  datacard<<"jer         shape     0        0"<<"\n";
  datacard.close();
  
  TFile *out = new TFile(SIGNAL+"_"+HISTO+"_input.root","RECREATE");
  out->cd();
  hDat->Write("data_obs");
  hBkg->Write("background");
  hSgn->Write("signal");
  hDat_JESlo->Write("data_obs_jesDown");
  hBkg_JESlo->Write("background_jesDown");
  hBkg_STATlo->Write("background_mcstatDown");
  hSgn_STATlo->Write("signal_mcstatDown");
  hSgn_JESlo->Write("signal_jesDown");
  hDat_JESup->Write("data_obs_jesUp");
  hBkg_JESup->Write("background_jesUp");
  hBkg_STATup->Write("background_mcstatUp");
  hSgn_JESup->Write("signal_jesUp");
  hSgn_STATup->Write("signal_mcstatUp");
  //----- JER placeholder ----------------
  hBkg_JESlo->Write("background_jerDown");
  hSgn_JESlo->Write("signal_jerDown"); 
  hBkg_JESup->Write("background_jerUp");
  hSgn_JESup->Write("signal_jerUp");
}
Beispiel #10
0
/** 
 * Make a GraphSysErr object
 * 
 * @param d  Directory
 * @param c1 Least centrality 
 * @param c2 Largest centrality 
 * 
 * @return Newly created GraphSysErr
 */
TObject* MakeGSE(TDirectory* d, Double_t c1, Double_t c2)
{
  if (!gROOT->GetClass("GraphSysErr")) return 0;
  TString  bin; bin.Form("%03dd%02d_%03dd%02d",
			 Int_t(c1), Int_t(c1*100)%100, 
			 Int_t(c2), Int_t(c2*100)%100);
  TString sub(bin); sub.Prepend("cent"); sub.Append("/dndeta");
  TString nme(bin); nme.Prepend("CENT_");
  TH1*    g = GetH1(d, sub);
  if (!g) return 0;
  
  Color_t  col     = g->GetMarkerColor();
  // Double_t bg      = (1-c1/100)*(2-0.1)+0.1;
  // Double_t c       = TMath::Power(c1/100,2)*(6.2-0.4)+0.4;
  Double_t bg      = CSysEval(c2, 0.02, 0.001);
  Double_t c       = CSysEval(c2, 0.005, 0.075);
  GraphSysErr* gse = new GraphSysErr(g->GetNbinsX());
  gse->SetName(nme);
  gse->SetTitle(Form("%5.1f - %5.1f%%", c1, c2));
  gse->SetKey("author", "PREGHENELLA : 20150");
  gse->SetKey("title", "dNch/deta in PbPb at 5023 GeV");
  gse->SetKey("obskey", "DN/DETARAP");
  gse->SetKey("reackey", "PB PB --> CHARGED X");
  gse->SetKey("laboratory", "CERN");
  gse->SetKey("accelerator", "LHC");
  gse->SetKey("detector", "TRACKLETS");
  gse->SetKey("reference", "ALICE-AN-2830");
  gse->AddQualifier("CENTRALITY IN PCT", Form("%.1f TO %.1f",c1,c2));
  gse->AddQualifier("SQRT(S)/NUCLEON IN GEV", "5023");
  gse->SetXTitle("ETARAP");
  gse->SetYTitle("DN/DETARAP");
  gse->SetMarkerStyle(g->GetMarkerStyle());
  gse->SetMarkerSize(g->GetMarkerSize());
  gse->SetDataOption(GraphSysErr::kNoTick);
  gse->SetMarkerColor(col);
  gse->SetLineColor(col);
  gse->SetFillColor(col);
  gse->SetSumFillColor(col);
  gse->SetSumLineColor(col);
  gse->SetSumOption(GraphSysErr::kBox);
  gse->SetCommonSumFillColor(col);
  gse->SetCommonSumLineColor(col);
  gse->SetCommonSumOption(GraphSysErr::kBox);
  MakeCommon(gse, "Particle composition",	0.01,   col);
  MakeCommon(gse, "Weak decay",			0.01,   col);
  MakeCommon(gse, "pT extrapolation",		0.02,   col);
  MakeCommon(gse, "EG dependence",		0.02,   col);
  MakeCommon(gse, "Background subrtaction",	bg,     col);
  MakeCommon(gse, "Centrality",			c,      col);
  Int_t acc = MakeP2P(gse, "Acceptance", col);

  Int_t j =  0;
  for (Int_t i = 1; i <= g->GetNbinsX(); i++) {
    Double_t eta  = g->GetXaxis()->GetBinCenter(i);
    Double_t eEta = g->GetXaxis()->GetBinWidth(i)/2;
    Double_t xo   = TMath::Abs(eta)+eEta;
    if (xo > 2) continue;
    Double_t ea  = 0.02*TMath::Power(xo/2,2);
    gse->SetPoint(j, eta, g->GetBinContent(i));
    gse->SetPointError(j, eEta, eEta);
    gse->SetStatError(j, g->GetBinError(i),g->GetBinError(i));
    gse->SetSysError(acc, j, eEta, eEta, ea/100, ea/100);
    j++;
  }
  return gse;
    
  
}
TList* readHistos(vector<string> inputRootFiles, bool fillNameStrings){
  TList* thelistHistos = new TList();
  for (int j=0; j< inputRootFiles.size(); j++) 
    {
      int numMax = 0;
      //cout <<"inputProcess: "<<inputProcess.at(j)<<endl;
      // Access input ROOT file (can access over secure shell)
      cout <<"inputRootFiles.at(j) "<<inputRootFiles.at(j)<<endl; 
      TFile *rootTFile = new TFile((inputRootFiles.at(j)).c_str()); // open root file
      TDirectory *current_sourcedir = gDirectory;
      TIter nextkey( current_sourcedir->GetListOfKeys() );
      TKey *key;
      
      // loop over keys(ROOT objects) within the root file
      while ((key = (TKey*)nextkey())) 
        {
	  TObject *obj = key->ReadObj();
	  
	  TH1 *histoObj = (TH1*)obj;
	  TH1* h1 = 0; //points to the new copied hist we will make
          int totalbins = 0;
	  // rename histogram
          if ( obj->IsA()->InheritsFrom( "TH1" ) ) 
            {
              string histname = obj->GetName();
	      size_t found = histname.find("lumi");
              string theProcess = "lumi";

              string new_theProcess = "_" + theProcess;
              histname.erase(found-1, new_theProcess.size());
              string histName = histname;
              cout << histName << endl;
              for (int o = 0; o < inputHistoName.size(); o++)
                {   
                  if ( histName == inputHistoName.at(o) )
		    {
                      int numBins = histoObj->GetXaxis()->GetNbins();
		      double lowerEdge = histoObj->GetXaxis()->GetXmin();
		      double upperEdge = histoObj->GetXaxis()->GetXmax();
		      
		      h1 = new TH1F (histName.c_str(), histName.c_str(),
			             numBins, lowerEdge, upperEdge);
                      
                      TH1F* tmp2 = static_cast<TH1F*>(h1);
                      totalbins = tmp2->GetSize();

                      for (int k=0; k <= totalbins; k++)
                        {
                          h1->SetBinContent(k,(histoObj->GetBinContent(k)));
                          h1->SetBinError(k,(histoObj->GetBinError(k)));
                        }

                      h1 = Rebinh(h1);
                      //cout<<"h1 "<<h1->GetName()<<"   Integral  "<<h1->Integral()<<endl; 
		      thelistHistos->Add(h1);
		      if(fillNameStrings) nHistList++;
		      if(fillNameStrings) theHistNameStrings.push_back(histName);
		      numMax++;
		    } // close if loop on selected histograms
		} // close for loop on selected histograms
	    } // close if loop InheritsFrom("TH1")
	} // close while loop
      // If first input ROOT file (Data), store total number of histograms
      if (j == 0)
          numHistos = numMax;
      // Else exit the code if a ROOT file has a different number of histograms
      else
        {
          if (numMax != numHistos)
            {
              cerr << "ERROR: Input Root Files DO NOT have the same number"
                   << " of histograms." << endl;
              exit (1);
            }
        }
    } // close for loop over root files

    return thelistHistos;
}
Beispiel #12
0
void getHistoInfo ()
{
 
  listHistos = new TList();    // Histograms normalized to one
  nHistList = 0;
  
  // loop over root files
  for (int j=0; j< inputRootFile.size(); j++) 
    {
      int numMax = 0;

      // Access input ROOT file (can access over secure shell)
      
      TFile *rootTFile = new TFile((inputRootFile.at(j)).c_str()); // open root file
      std::cout <<"inputRootFile.at(j)).c_str()  "<<inputRootFile.at(j).c_str()<<std::endl;
      TDirectory *current_sourcedir = gDirectory;
      TIter nextkey( current_sourcedir->GetListOfKeys() );
      TKey *key;
      
      // loop over keys(ROOT objects) within the root file
      while ((key = (TKey*)nextkey())) 
        {
	  TObject *obj = key->ReadObj();
	  
	  TH1 *histoObj = (TH1*)obj;
	  TH1* h1 = 0; //points to the new copied hist we will make
	  int totalbins = 0;
	  // rename histogram
          if ( obj->IsA()->InheritsFrom( "TH1" ) ) 
            {

              string histname = obj->GetName();
              
              size_t found = histname.find("lumi");
              string theProcess = "lumi";

              string new_theProcess = "_" + theProcess;
              histname.erase(found-1, new_theProcess.size());
              string histName = histname;
 
	      int numBins = histoObj->GetXaxis()->GetNbins();
	      double lowerEdge = histoObj->GetXaxis()->GetXmin();
	      double upperEdge = histoObj->GetXaxis()->GetXmax();

	      if ( obj->IsA()->InheritsFrom( "TH2" ) ) 
		{
		  int numBinsY = histoObj->GetYaxis()->GetNbins();
		  double lowerEdgeY = histoObj->GetYaxis()->GetXmin();
		  double upperEdgeY = histoObj->GetYaxis()->GetXmax();
		  h1 = new TH2F (histName.c_str(), histName.c_str(),
				 numBins, lowerEdge, upperEdge,
				 numBinsY, lowerEdgeY, upperEdgeY);
	      
		  //here (and below) GetSize() will allow us to
		  //iterate over 1 or 2d hists.  We pick up overflow
		  //bins too, but that's fine
		  TH2F* tmp1 = static_cast<TH2F*>(h1);
		  totalbins = tmp1->GetSize();
		} else {
	      h1 = new TH1F (histName.c_str(), histName.c_str(),
				   numBins, lowerEdge, upperEdge);
	      TH1F* tmp2 = static_cast<TH1F*>(h1);
	      totalbins = tmp2->GetSize();
	      }

	      // Apply scale factor?
	      if (inputApplyScaleFactor.at(j) == "True")
		{
		  for (int k=0; k <= totalbins; k++)
		    {
		      double scf = inputScaleFactor.at(j);
		      h1->SetBinContent(k,(histoObj->GetBinContent(k)*scf));
		      h1->SetBinError(k,(histoObj->GetBinError(k))*scf);
		    }
		} else
		{
		  for (int k=0; k <= totalbins; k++)
		    {
		      h1->SetBinContent(k,(histoObj->GetBinContent(k)));
		      h1->SetBinError(k,(histoObj->GetBinError(k)));
		    }
		}
              h1 = Rebinh(h1);
	      listHistos->Add(h1);
	      nHistList++;
	      theHistNameStrings.push_back(histName);
	      numMax++;
	    } // close if loop InheritsFrom("TH1")
	} // close while loop
      // If first input ROOT file (Data), store total number of histograms
      if (j == 0)
        numHistos = numMax;
      // Else exit the code if a ROOT file has a different number of histograms
      else
        {
          if (numMax != numHistos)
            {
              cerr << "ERROR: Input Root Files DO NOT have the same number"
                   << " of histograms." << endl;
              exit (1);
            }
        }
    } // close for loop over root files
} // close getHistoInfo function
Beispiel #13
0
void
Example(Bool_t fit=true)
{
  // Load the class - if not already done 
  if (!gROOT->GetClass("GraphSysErr"))
    gROOT->LoadMacro("GraphSysErr.C+g");

  // Adjust size along X of common errors 
  gStyle->SetErrorX(.2);
  // Adjust size of hat, cap, ... - depends on canvas size!
  gStyle->SetEndErrorSize(10);

  // Make our object 
  GraphSysErr* gse = new GraphSysErr("foo", "Gaussian");
  // Draw data with-out ticks 
  gse->SetDataOption(GraphSysErr::kNoTick);
  gse->SetXTitle("X");
  gse->SetYTitle("Y");
  // Set some key/value pairs 
  gse->SetKey("laboratory", "The Center");
  gse->SetKey("accelerator", "Mega Collider");
  gse->SetKey("detector", "Huge Experiment");
  gse->SetKey("author", "Christensen");
  gse->SetKey("reference","Jour.All.Things A1,999");
  gse->SetKey("doi","9999-9999-9999-9999");
  gse->SetKey("abstract", "The data");
  gse->SetKey("location", "In the paper");
  gse->SetKey("reackey", "graviton -> tachyons");
  gse->SetKey("obskey", "GUT");
  // Adding qualifiers 
  gse->AddQualifier("question", "Life, universe, and everything");
  
  // Two sources of common errors one relative, one absolue
  UInt_t cm1 = gse->DefineCommon("Common 0.05", false, .05);
  UInt_t cm2 = gse->DefineCommon("Common 10%", true, .1);
  
  // Two sources of point-to-point errors, one relative, one absolute
  UInt_t pp1 = gse->DeclarePoint2Point("Point-to-Point 0.1-0.2", true);
  UInt_t pp2 = gse->DeclarePoint2Point("Point-to-Point 5-10%", false);
  
  // Set options on summed errors (in case of option COMBINED)
  gse->SetSumLineColor(kRed+2);
  gse->SetSumLineWidth(2);
  gse->SetSumTitle("All errors");
  gse->SetSumOption(GraphSysErr::kHat);
  
  // Set attributes of common errors 
  gse->SetSysFillColor(cm1, kRed+2);
  gse->SetSysFillStyle(cm1, 3001);
  gse->SetSysLineColor(cm1, kRed+2);
  gse->SetSysFillColor(cm2, kCyan+2);
  gse->SetSysFillStyle(cm2, 3001);
  gse->SetSysOption(cm1, GraphSysErr::kBox);
  gse->SetSysOption(cm2, GraphSysErr::kRect);
  
  // Set attributes of other errors 
  gse->SetSysLineColor(pp1, kBlue+2);
  gse->SetSysLineWidth(pp1, 2);
  gse->SetSysLineColor(pp2, kGreen+2);
  gse->SetSysLineWidth(pp2, 3);
  gse->SetSysOption(pp1, GraphSysErr::kBar);
  gse->SetSysOption(pp2, GraphSysErr::kHat);
  
  // Fill a histogram with a Guassian random deviate 
  TH1* h = new TH1F("h", "h", 30, -3, 3);
  h->Sumw2();
  h->SetDirectory(0);
  h->FillRandom("gaus",1000);
  h->Scale(1./1000, "width");
  
  // Fill in the data points 
  for (Int_t i = 0; i < h->GetNbinsX(); i++) { 
    Int_t    bin = i+1;
    Double_t x   = h->GetXaxis()->GetBinCenter(bin);
    Double_t y   = h->GetBinContent(bin);
    Double_t sta = h->GetBinError(bin);
    Double_t w   = h->GetXaxis()->GetBinWidth(bin);
    
    // Set data 
    gse->SetPoint(i, x, y);
    gse->SetPointError(i, w/2, w/2);
    gse->SetStatError(i, sta);
    
    // Set point-to-point errors 
    gse->SetSysError(pp1, i, 0., gRandom->Uniform(0.1, 0.2));
    gse->SetSysError(pp2, i, 0., 0., 
		     gRandom->Uniform(0.05, 0.1),
		     gRandom->Uniform(0.05, 0.1));
  } 
  // Remove temporary histogram
  delete h;

  // Build our canvas 
  TCanvas* c = new TCanvas("c","c", 1400, 1000);
  c->SetFillColor(0);
  c->SetFillStyle(0);
  c->SetTopMargin(0.01);
  c->SetRightMargin(0.01);
  
  // Draw or fit (and draw) a Guassian to the data
  const char* option = "STACK stat axis quad split max west";
  if (!fit) 
    gse->Draw(option);
  else 
    gse->Fit("gaus", "SQ", option, -3, 3);

  // Make a legend 
  TLegend* l = c->BuildLegend(0.7,0.7,0.97,0.97);
  l->SetFillColor(0);
  l->SetFillStyle(0);
  l->SetBorderSize(0);

  // update the canvas and print
  c->Modified();
  c->Update();
  c->cd();
  c->Print("Example.png");
}
Beispiel #14
0
void DrawTwoInPad(TVirtualPad* p,
                  Int_t        sub,
                  TH1*         h1,
                  TH1*         h2,
		  Bool_t       ratio,
		  Bool_t       logy=false,
		  Bool_t       legend=false)
{
  TVirtualPad* pp = p->cd(sub);
  pp->SetRightMargin(0.02);
  pp->SetLeftMargin(0.10);
  TVirtualPad* ppp = pp;
  if (ratio) {
    pp->Divide(1,2,0,0);
    ppp = pp->cd(1);				
    ppp->SetRightMargin(0.02);
  }
  if (logy) ppp->SetLogy();
  TH1* hs[] = { h1, h2, 0 };
  if (h1->GetMaximum() < h2->GetMaximum()) {
    hs[0] = h2;
    hs[1] = h1;
  }
  TH1** ph = hs;
  Double_t size = (ratio ? 0.1 : 0.05);
  Double_t off  = (ratio ? 0.6 : 0.5);
  h1->SetFillStyle(3004);
  h2->SetFillStyle(3005);
  while (*ph) {
    TString opt("hist");
    if (ph != hs) opt.Append(" same");

    TH1* copy = (*ph)->DrawCopy(opt);
    copy->GetXaxis()->SetLabelSize(2*size);
    copy->GetYaxis()->SetLabelSize(size);
    copy->GetYaxis()->SetTitleSize(size);
    copy->GetYaxis()->SetTitleOffset(off);
    copy->SetYTitle(copy->GetTitle());
    copy->SetTitle("");
    copy->SetDirectory(0);
    ph++;
  }
  TString s1 = h1->GetYaxis()->GetTitle();
  TString s2 = h2->GetYaxis()->GetTitle();
  
  if (legend) { 
    TLegend* l = new TLegend(0.6, 0.1, 0.9, 0.9);
    l->SetBorderSize(0);
    TLegendEntry* e = l->AddEntry("dummy", s1, "lf");
    l->SetFillColor(kWhite);
    e->SetFillColor(kBlack);
    e->SetFillStyle(h1->GetFillStyle());
    e = l->AddEntry("dummy", s2, "lf");
    e->SetFillColor(kBlack);
    e->SetFillStyle(h2->GetFillStyle());
    l->Draw();
  }
  if (!ratio) return;
  ppp = pp->cd(2);
  ppp->SetRightMargin(0.02);
  TH1* r = static_cast<TH1*>(h1->Clone(Form("ratio%s", h1->GetName())));
  r->SetDirectory(0);
  r->SetTitle("");
  r->GetXaxis()->SetLabelSize(size);
  r->GetYaxis()->SetLabelSize(size);
  r->GetYaxis()->SetTitleSize(0.9*size);
  r->GetYaxis()->SetTitleOffset(0.9*off);
  r->SetMarkerStyle(20);
  r->SetMarkerColor(h1->GetFillColor()+1);
  r->SetFillStyle(3007);
  r->SetYTitle(Form("#frac{%s}{%s}", s1.Data(), s2.Data()));

  // r->Add(h2, -1);
  // r->Divide(h1);
  if (!r->IsA()->InheritsFrom(TProfile::Class())) {
    r->GetSumw2()->Set(0); // r->Sumw2(false);
    h2->GetSumw2()->Set(0); // h2->Sumw2(false);
  }
  r->Divide(h2);
  Printf("%s", r->GetName());
  for (UShort_t bin = 1; bin <= r->GetNbinsX(); bin++) {
    Printf("  bin # %2d: Diff=%g+/-%g", bin, r->GetBinContent(bin),
	   r->GetBinError(bin));
    r->SetBinError(bin, 0);
  }
  r->GetSumw2()->Set(0); //r->Sumw2(false);
  r->SetMarkerSize(4);
  r->SetMaximum(r->GetMaximum()*1.2);
  r->SetMinimum(r->GetMinimum()*0.8);
  r->Draw("hist text30");  
  p->Modified();
  p->Update();
  p->cd();
}
Beispiel #15
0
void makeStack(TString myVar, TString myCut, TString myName, TString myAxisNameX, TString myAxisNameY, 
               vector<const Sample*>& listOfSignals, vector<const Sample*>& listOfSamples, vector<const Sample*> listOfDatasets, 
               TString inFileName,
               bool isBlind, bool isLog, bool drawSignal, bool drawLegend,
               int nBins, float xLow, float xHigh,
               float* xlowVec)
{
  // prepare the input file
  TFile* infile = new TFile(inFileName, "READ"); 
  infile -> cd();
  
  // prepare the stack
  THStack *hs = new THStack("hs","");
  // prepare the histos pointers
  TH1F*   hist[20];
  // prepare the tree pointers
  TTree*  tree[20];
  // prepare the legend
  TLegend* leg = new TLegend(.7485,.7225,.9597,.9604);
  leg->SetFillColor(0);
  // prepare the colors
  Int_t col[20] = {46,2,12,5,3,4,9,7,47,49,49,50,51,52,53,54,55,56,57,58};
  // prepare the cut
  if (isBlind) myCut += "*(phoMetDeltaPhi < 2.9)";        
  // prepare the Y axis lable
  if (xlowVec != 0) myAxisNameY = "Events/" + myAxisNameY;
  else {
    float binWidth = (xHigh-xLow)/nBins;
    TString tempString;
    tempString.Form("%.2f ",binWidth); 
    myAxisNameY = "Events/" + tempString + myAxisNameY;
  }
  // prepare the legend strings
  vector<TString> theLegends;
  
  // loop through the datasets and produce the plots
  TH1F* hdata;
  TH1F* hsignal;
  //prepare data and signal histos
  if (xlowVec != 0) hdata   = new TH1F("hdata","",nBins,xlowVec);
  else hdata = new TH1F("hdata","",nBins,xLow,xHigh);
  if (xlowVec != 0) hsignal = new TH1F("hsignal","",nBins,xlowVec);
  else hsignal = new TH1F("hsignal","",nBins,xLow,xHigh);

  TTree*  treedata[20];
  for (UInt_t iDatas=0; iDatas < listOfDatasets.size(); iDatas++) {
    //get the tree
    treedata[iDatas] = (TTree*) infile -> Get(listOfDatasets.at(iDatas)->Name()->Data());

    //fill the histogram
    if ( iDatas == 0 ) treedata[iDatas] -> Draw(myVar + " >> hdata","evt_weight*kf_weight*pu_weight" + myCut);
    else treedata[iDatas] -> Draw(myVar + " >>+ hdata","evt_weight*kf_weight*pu_weight" + myCut);
    
    if ( isBlind && iDatas == 0 ) leg -> AddEntry(hdata, "DATA (19.8 fb^{-1})", "pl");    
    
  }//end loop on datasets
  if (xlowVec != 0) {
    for (int iBin = 1; iBin <= nBins; iBin++) hdata->SetBinError  (iBin,hdata->GetBinError(iBin)/hdata->GetBinWidth(iBin));
    for (int iBin = 1; iBin <= nBins; iBin++) hdata->SetBinContent(iBin,hdata->GetBinContent(iBin)/hdata->GetBinWidth(iBin));
  }

  TTree*  treesignal[20];
  for (UInt_t iSignal=0; iSignal < listOfSignals.size(); iSignal++) {
    //get the tree
    treesignal[iSignal] = (TTree*) infile -> Get(listOfSignals.at(iSignal)->Name()->Data());

    //fill the histogram
    TString thisScale = Form("%f *", *(listOfSignals.at(iSignal)->Scale()));
    if ( iSignal == 0 ) treesignal[iSignal] -> Draw(myVar + " >> hsignal",thisScale + "evt_weight*kf_weight*pu_weight" + myCut);
    else treesignal[iSignal] -> Draw(myVar + " >>+ hsignal",thisScale + "evt_weight*kf_weight*pu_weight" + myCut);
    
    if ( drawSignal && iSignal == 0 ) leg -> AddEntry(hsignal, "Signal", "l");    
    
  }//end loop on signals
  if (xlowVec != 0) {
    for (int iBin = 1; iBin <= nBins; iBin++) hsignal->SetBinError  (iBin,hsignal->GetBinError(iBin)/hsignal->GetBinWidth(iBin));
    for (int iBin = 1; iBin <= nBins; iBin++) hsignal->SetBinContent(iBin,hsignal->GetBinContent(iBin)/hsignal->GetBinWidth(iBin));
  }
  hsignal -> SetLineColor(49);
  hsignal -> SetLineWidth(4.0);
       
  int theHistCounter = 0;
  // loop through the samples and produce the plots
  for (UInt_t iSample=0; iSample < listOfSamples.size(); iSample++) {

    //determine if the histo is first of the series
    bool isFirstOfSerie = (*listOfSamples.at(iSample)->Legend()).CompareTo(" ");
    bool isLastOfSerie = false;
    if (iSample == listOfSamples.size() - 1) isLastOfSerie = true;
    if (iSample < listOfSamples.size() - 1 && (*listOfSamples.at(iSample+1)->Legend()).CompareTo(" ") != 0) isLastOfSerie = true;
    
    //get the tree
    tree[iSample] = (TTree*) infile -> Get(listOfSamples.at(iSample)->Name()->Data());
    //if sample first of the list create a new histogram
    if (isFirstOfSerie) {
       TString thisHistName = "h_" + *(listOfSamples.at(iSample)->Name());
       //variable bin histo
       if (xlowVec != 0) hist[theHistCounter] = new TH1F(thisHistName,thisHistName,nBins,xlowVec);
       //fixed bin histo
       else hist[theHistCounter] = new TH1F(thisHistName,thisHistName,nBins,xLow,xHigh);
       hist[theHistCounter] -> Sumw2();
       hist[theHistCounter] -> SetFillColor(col[theHistCounter]);
       hist[theHistCounter] -> SetFillStyle(1001);
       theLegends.push_back(*listOfSamples.at(iSample)->Legend());
    }

    //fill the histogram
    TString thisScale = Form("%f *", *(listOfSamples.at(iSample)->Scale()));
    if (isFirstOfSerie) tree[iSample] -> Draw(myVar + " >> " + TString(hist[theHistCounter] -> GetName()),thisScale + "evt_weight*kf_weight*pu_weight" + myCut);
    else tree[iSample] -> Draw(myVar + " >>+ " + TString(hist[theHistCounter] -> GetName()),thisScale + "evt_weight*kf_weight*pu_weight" + myCut);
    
    //add the histogram to the stack if the last of the series:
    //either last sample or ~ sample followed by non ~ sample
    if (isLastOfSerie) {
       if (xlowVec != 0) {
         for (int iBin = 1; iBin <= nBins; iBin++) hist[theHistCounter]->SetBinError  (iBin,hist[theHistCounter]->GetBinError(iBin)/hist[theHistCounter]->GetBinWidth(iBin));
         for (int iBin = 1; iBin <= nBins; iBin++) hist[theHistCounter]->SetBinContent(iBin,hist[theHistCounter]->GetBinContent(iBin)/hist[theHistCounter]->GetBinWidth(iBin));
       }
       hs -> Add(hist[theHistCounter]);
       theHistCounter++;
    }
    
  }//end loop on samples

  //Fix the legend
  for (int iHisto = theHistCounter-1; iHisto >= 0; iHisto--) {
    leg -> AddEntry(hist[iHisto], theLegends[iHisto], "f");   
  }
  
  //get the maximum to properly set the frame
  float theMax = hdata -> GetBinContent(hdata -> GetMaximumBin()) + hdata -> GetBinError(hdata -> GetMaximumBin());
  TH1* theMCSum = (TH1*) hs->GetStack()->Last();
  float theMaxMC = theMCSum->GetBinContent(theMCSum->GetMaximumBin()) + theMCSum->GetBinError(theMCSum->GetMaximumBin());
  if (theMaxMC > theMax) theMax = theMaxMC;
  
  //prepare the ratio band and plot
  TH1* theMCRatioBand = makeRatioBand(theMCSum);
  TH1* theRatioPlot = makeRatioPlot(hdata,theMCSum);
    
  TCanvas* can = new TCanvas();
  can -> SetLogy(isLog);
  
  TPad *pad1 = new TPad("pad1","top pad",0,0.30,1,1);
  pad1->SetBottomMargin(0.02);
  pad1->SetLeftMargin(0.13);
  pad1->Draw();
  TPad *pad2 = new TPad("pad2","bottom pad",0,0.0,1,0.30);
  pad2->SetTopMargin(0.02);
  pad2->SetLeftMargin(0.13);
  pad2->SetBottomMargin(0.4);
  pad2->SetGridy();
  pad2->Draw();
  
  pad1->cd();
  hs->Draw("hist");
  hdata->Draw("same,pe");
  if (drawSignal) hsignal->Draw("same,hist");
  if (drawLegend) leg->Draw("same");
  //hs->GetXaxis()->SetTitle(myAxisNameX);
  hs->GetYaxis()->SetTitle(myAxisNameY);
  hs->GetXaxis()->SetLabelSize(0.04);
  hs->GetYaxis()->SetLabelSize(0.04);
  hs->GetXaxis()->SetLabelOffset(0.025);
  hs->GetYaxis()->SetLabelOffset(0.035);
  //hs->GetXaxis()->SetTitleOffset(1.1);
  hs->GetYaxis()->SetTitleOffset(1.1);
  hs->SetMaximum(theMax);
  if (isLog) hs->SetMinimum(0.01);
  
  pad2->cd();
  theMCRatioBand->GetXaxis()->SetTitle(myAxisNameX);
  theMCRatioBand->GetXaxis()->SetTitleSize(0.16);
  theMCRatioBand->GetXaxis()->SetTitleOffset(1.1);
  theMCRatioBand->GetXaxis()->SetLabelSize(0.12);
  theMCRatioBand->GetXaxis()->SetLabelOffset(0.07);
  theMCRatioBand->GetYaxis()->SetTitle("Data/MC");
  theMCRatioBand->GetYaxis()->SetTitleSize(0.10);
  theMCRatioBand->GetYaxis()->SetTitleOffset(0.6);
  theMCRatioBand->GetYaxis()->SetLabelSize(0.06);
  theMCRatioBand->GetYaxis()->SetLabelOffset(0.03);
  theMCRatioBand->SetFillStyle(3001);
  theMCRatioBand->SetFillColor(kBlue);
  theMCRatioBand->SetLineWidth(1);
  theMCRatioBand->SetLineColor(kBlack);
  theMCRatioBand->SetMarkerSize(0.1);
  theMCRatioBand->SetMaximum(4.);
  theMCRatioBand->SetMinimum(0.);
  theMCRatioBand->Draw("E2");
  TLine *line = new TLine(xLow,1,xHigh,1);
  line->SetLineColor(kBlack);
  line->Draw("same");
  theRatioPlot->Draw("same,pe");
  
  can->cd();
  can->Modified();
  can -> SaveAs(myName + ".pdf","pdf");
  
  //cleanup the memory allocation
  delete theMCSum;
  delete hs;
  delete leg;
  delete hdata;
  delete pad1;
  delete pad2;
  delete can;
  delete theMCRatioBand;
  delete theRatioPlot;
  infile -> Close();
  delete infile;
  
  return;
}
void Process(TString fname, TString oldFolder, int toMass, int fromMass)
{




  std::string channels[] = {"data_obs", "WH", "TT",  "WjLF", "WjHF", "ZjLF", "ZjHF" , "VV" , "s_Top"};
  std::string systs[] = {"eff_b", "fake_b", "res_j", "scale_j" , "stat" };

  kount = 0;  

  gROOT->SetStyle("Plain");
  setTDRStyle();

  TFile * file = new TFile(fname.Data(), "READ");
  std::cout << "reading " << fname.Data() << std::endl;
  TString outname(massS[toMass]);
  outname.Append("_June8.root");
  fname.ReplaceAll(".root",outname.Data());
 
///BEGIN CHECK RBIN
  int addRightBin = 0, addRightBinm1 = 0 , rightBinNo = 0;
  float a,overflow;
  RooWorkspace *mytempWS =  (RooWorkspace*) file->Get(oldFolder.Data());
  RooRealVar BDT("CMS_vhbb_BDT_Wln", "BDT", -1, 1);

  float Signal = 0;
  float Background = 0;
  float Backgroundm1 = 0;
  float Data = 0;

  RooDataHist* tempRooDataHistNomS = (RooDataHist*)  mytempWS->data(channels[1].c_str());
  TH1 *tempHistNomS = tempRooDataHistNomS->createHistogram(channels[1].c_str(),BDT,RooFit::Binning(bins));
  tempHistNomS->Rebin(rebin);


  TH1 *tempHistNomD = tempRooDataHistNomS->createHistogram(channels[0].c_str(),BDT,RooFit::Binning(bins));
  tempHistNomD->Rebin(rebin);



  for(int i = 1; i <= tempHistNomS->GetNbinsX(); i++)
  { 
    if(tempHistNomS->GetBinContent(i) > 0)
      { rightBinNo = i; Signal = tempHistNomS->GetBinContent(i); Data = tempHistNomS->GetBinError(i); }
  }

  for(int i = 2; i < 9; i++)
  {
   RooDataHist* tempRooDataHistNom = (RooDataHist*)  mytempWS->data(channels[i].c_str());
   TH1 *tempHistNom = tempRooDataHistNom->createHistogram(channels[i].c_str(),BDT,RooFit::Binning(bins));
   tempHistNom->Rebin(rebin);
   Background += tempHistNom->GetBinContent(rightBinNo);
   

   //   if(tempHistNom->GetBinContent(rightBinNo-1) == 0)
   // {
   // Backgroundm1 = 0;  
   //std::cout << "ARGHGHGHGHGH bkg is 0 still at left" << std::endl;
   //   std::cin >> ;
   // }

   Backgroundm1+=  tempHistNom->GetBinContent(rightBinNo-1); 

   overflow = tempHistNom->GetBinContent(rightBinNo+1) ;
   
   if(tempHistNom->GetBinContent(rightBinNo+1) > 0)
   {
   std::cout << "ARGHGHGHGHGH overflow at right" << std::endl;
   //   std::cin >> ;
   }
   a+= overflow;
  }

  if( (Background ==0) ) addRightBin = 1;
else  addRightBin = 0;


std::cout << "################# folder" << oldFolder << std::endl;
 std::cout<< "################# CHECK RBIN:: right bin n  " << rightBinNo << " signal: " << Signal << " bkg: " << Background << " bkgm1: " <<  Backgroundm1  << " Data:  " << Data <<  " at right there is an overflow of: "<< a << std::endl;
std::cout << "########################### CHECK RBIN:: REBINNING: " << addRightBin << std::endl;  
 if ( (Backgroundm1 == 0)  ) 
   { addRightBinm1 =1 ;
     std::cout << "ARGHGHGHGHGH " << Backgroundm1 << " at left" << std::endl;
    
   }

std::cout << "########################### need to rebin further? " << addRightBinm1  << std::endl;  
///END CHECK RBIN



  TFile * outfile = new TFile(fname.Data(), "RECREATE");
  using namespace RooFit;
  RooWorkspace *myWS = new RooWorkspace(oldFolder.Data(),oldFolder.Data());
  myWS->factory("CMS_vhbb_BDT_Wln[-1.,1.]"); ///NEW VARIABLE NAME HERE 

  TString oldFolder2(oldFolder.Data());
  oldFolder2.Append("2");
  RooWorkspace *myWS2 = new RooWorkspace(oldFolder2.Data(),oldFolder2.Data());
  myWS2->factory("CMS_vhbb_BDT_Wln[-1.,1.]"); ///NEW VARIABLE NAME HERE 

///BEGIN CHECK RBIN
  int addRightBin2=0, rightBinNo2=0, addRightBin2m1=0;
  float a2,overflow2;
  RooWorkspace *mytempWS2 =  (RooWorkspace*) file->Get(oldFolder2.Data());
   RooRealVar BDT2("CMS_vhbb_BDT_Wln", "BDT", -1, 1);

  float Signal2 = 0;
  float Background2 = 0;
  float Background2m1 = 0;
  float Data2 = 0;
  RooDataHist* tempRooDataHistNomS2 = (RooDataHist*)  mytempWS2->data(channels[1].c_str());
  RooDataHist* tempRooDataHistNomD2 = (RooDataHist*)  mytempWS2->data(channels[0].c_str());

  TH1 *tempHistNomS2 = tempRooDataHistNomS2->createHistogram(channels[1].c_str(),BDT2,RooFit::Binning(bins));
  tempHistNomS2->Rebin(rebin);

  TH1 *tempHistNomD2 = tempRooDataHistNomD2->createHistogram(channels[0].c_str(),BDT2,RooFit::Binning(bins));
  tempHistNomD2->Rebin(rebin);


  for(int i = 1; i <= tempHistNomS2->GetNbinsX(); i++)
  { 
    //    std::cout << "############    signal in bin " << i << " is " << tempHistNomS2->GetBinContent(i) << std::endl;
    // std::cout << "############    data in bin " << i << " is " << tempHistNomD2->GetBinContent(i) << std::endl;
    if(tempHistNomS2->GetBinContent(i) > 0)
      { rightBinNo2 = i; Signal2 = tempHistNomS2->GetBinContent(i); Data2 = tempHistNomD2->GetBinContent(i) ;}

  }


  

  for(int i = 2; i < 9; i++)
  {
   RooDataHist* tempRooDataHistNom2 = (RooDataHist*)  mytempWS2->data(channels[i].c_str());
   TH1 *tempHistNom2 = tempRooDataHistNom2->createHistogram(channels[i].c_str(),BDT2,RooFit::Binning(bins));
   tempHistNom2->Rebin(rebin);
   Background2 += tempHistNom2->GetBinContent(rightBinNo2);
   
   overflow2 = tempHistNom2->GetBinContent(rightBinNo2+1) ;

    Background2m1+=  tempHistNom2->GetBinContent(rightBinNo2-1); 


 
   if(tempHistNom2->GetBinContent(rightBinNo2+1) > 0)
   {
   std::cout << "ARGHGHGHGHGH" << std::endl;
   //   std::cin >> ;
   }
   a2+= overflow2;
  }

  if( (Background2 ==0) ) addRightBin2 = 1;
else  addRightBin2 = 0;
    if( (Background2m1 ==0) ) addRightBin2m1 = 1;
std::cout << "################# folder" << oldFolder2 << std::endl;
 std::cout << "################# CHECK RBIN:: right bin n  " << rightBinNo2 << " signal: " << Signal2 << " bkg: " << Background2 <<   " bkgm1: " <<  Background2m1  << " Data:  " << Data2 <<   " at right there is an overflow of: "<< a2 << std::endl;
std::cout << "########################### CHECK RBIN:: REBINNING: " << addRightBin2 << std::endl;  
std::cout << "########################### need to rebin further? " << addRightBin2m1 << std::endl;  
///END CHECK RBIN

  
  
  for (int c =0; c<9; c++)
  {
     kount2 = 0;  
    for (int s =0; s<5 ; s++ ){
      makeSystPlot( file, oldFolder, myWS,  channels[c], systs[s], toMass, fromMass,  rightBinNo, addRightBin, addRightBinm1  );
      makeSystPlot( file, oldFolder2, myWS2,  channels[c], systs[s] , toMass, fromMass,  rightBinNo2, addRightBin2, addRightBin2m1 );
    }
  }


  if(!(IFILE.Contains("8TeV")))
  {
    makeSystPlot(file, oldFolder, myWS, "WjLF", "WModel",toMass, fromMass, rightBinNo, addRightBin ,addRightBinm1 );
    makeSystPlot(file, oldFolder, myWS, "WjHF", "WModel",toMass, fromMass, rightBinNo, addRightBin, addRightBinm1  );


    makeSystPlot(file, oldFolder2, myWS2, "WjLF", "WModel",toMass, fromMass, rightBinNo2, addRightBin2 , addRightBin2m1);
    makeSystPlot(file, oldFolder2, myWS2, "WjHF", "WModel",toMass, fromMass, rightBinNo2, addRightBin2, addRightBin2m1 );
  }

  myWS->writeToFile(fname.Data());  
  std::cout << std::endl << std::endl << std::endl << std::endl << "///////////////////////////" << std::endl;
  std::cout << fname.Data() << " written" << std::endl;
  std::cout << "///////////////////////////" << std::endl << std::endl << std::endl;


  outfile->Write();
  outfile->Close();
  fname.ReplaceAll("June8","June82");
  TFile * outfile2 = new TFile(fname.Data(), "RECREATE");
  myWS2->writeToFile(fname.Data());  
  std::cout << std::endl << std::endl << std::endl << std::endl << "///////////////////////////" << std::endl;
  std::cout << fname.Data() << " written" << std::endl;
  std::cout << "///////////////////////////" << std::endl << std::endl << std::endl;


}
void makeTable(TString myVar, TString myCut, TString myName, TString myAxisNameX, TString myAxisNameY, 
               vector<const Sample*>& listOfSamples, vector<const Sample*> listOfDatasets, TString inFileName,
               bool isBlind, bool isLog, 
               int nBins, float xLow, float xHigh,
               float* xlowVec)
{
  // prepare the input file
  TFile* infile = new TFile(inFileName, "READ"); 
  infile -> cd();

  // prepare the necessary for the scale factor estimation
  float defScaleFactor = 1.3;
  float newScaleFactor = 1.;
  float varScaleFactor = 1.;
  float nBkg = 0;
  float nBkgErrSq = 0;
  float nSig = 0;
  float nSigErrSq = 0;
    
  // prepare the stack
  THStack *hs = new THStack("hs","");
  // prepare the histos pointers
  TH1F*   hist[20];
  // prepare the tree pointers
  TTree*  tree[20];
  // prepare the legend
  TLegend* leg = new TLegend(.7485,.7225,.9597,.9604);
  leg->SetFillColor(0);
  // prepare the colors
  Int_t col[20] = {46,2,12,5,3,4,9,7,47,49,49,50,51,52,53,54,55,56,57,58};
  // prepare the Y axis lable
  if (xlowVec != 0) myAxisNameY = "Events/" + myAxisNameY;
  else {
    float binWidth = (xHigh-xLow)/nBins;
    TString tempString;
    tempString.Form("%.2f ",binWidth); 
    myAxisNameY = "Events/" + tempString + myAxisNameY;
  }
  // prepare the legend strings
  vector<TString> theLegends;
  
  // loop through the datasets and produce the plots
  TH1F* hdata;
  //variable bin histo
  if (xlowVec != 0) hdata = new TH1F("hdata","",nBins,xlowVec);
  //fixed bin histo
  else hdata = new TH1F("hdata","",nBins,xLow,xHigh);
  
  TTree*  treedata[20];
  for (UInt_t iDatas=0; iDatas < listOfDatasets.size(); iDatas++) {
    //get the tree
    treedata[iDatas] = (TTree*) infile -> Get(listOfDatasets.at(iDatas)->Name()->Data());

    //fill the histogram
    if ( iDatas == 0 ) treedata[iDatas] -> Draw(myVar + " >> hdata","hlt_weight*evt_weight*kf_weight*pu_weight" + myCut,"goff");
    else treedata[iDatas] -> Draw(myVar + " >>+ hdata","hlt_weight*evt_weight*kf_weight*pu_weight" + myCut,"goff");
    
    if ( iDatas == 0 ) leg -> AddEntry(hdata, "DATA (19.8 fb^{-1})", "pl");    
    
  }//end loop on datasets
  if (xlowVec != 0) {
    for (int iBin = 1; iBin <= nBins; iBin++) hdata->SetBinError  (iBin,hdata->GetBinError(iBin)/hdata->GetBinWidth(iBin));
    for (int iBin = 1; iBin <= nBins; iBin++) hdata->SetBinContent(iBin,hdata->GetBinContent(iBin)/hdata->GetBinWidth(iBin));
  }
       
  int theHistCounter = 0;
  // loop through the samples and produce the plots
  for (UInt_t iSample=0; iSample < listOfSamples.size(); iSample++) {

    //determine if the histo is first of the series
    bool isFirstOfSerie = (*listOfSamples.at(iSample)->Legend()).CompareTo(" ");
    bool isLastOfSerie = false;
    if (iSample == listOfSamples.size() - 1) isLastOfSerie = true;
    if (iSample < listOfSamples.size() - 1 && (*listOfSamples.at(iSample+1)->Legend()).CompareTo(" ") != 0) isLastOfSerie = true;
    
    //get the tree
    tree[iSample] = (TTree*) infile -> Get(listOfSamples.at(iSample)->Name()->Data());
    //if sample first of the list create a new histogram
    if (isFirstOfSerie) {
       TString thisHistName = "h_" + *(listOfSamples.at(iSample)->Name());
       //variable bin histo
       if (xlowVec != 0) hist[theHistCounter] = new TH1F(thisHistName,thisHistName,nBins,xlowVec);
       //fixed bin histo
       else hist[theHistCounter] = new TH1F(thisHistName,thisHistName,nBins,xLow,xHigh);
       hist[theHistCounter] -> Sumw2();
       hist[theHistCounter] -> SetFillColor(col[theHistCounter]);
       hist[theHistCounter] -> SetFillStyle(1001);
       theLegends.push_back(*listOfSamples.at(iSample)->Legend());
       cout << *listOfSamples.at(iSample)->Legend() << " ";
    }

    //fill the histogram
    
    TString thisScale = Form("%f *", *(listOfSamples.at(iSample)->Scale()));
    if (isFirstOfSerie) tree[iSample] -> Draw(myVar + " >> " + TString(hist[theHistCounter] -> GetName()),thisScale + "hlt_weight*evt_weight*kf_weight*pu_weight" + myCut,"goff");
    else tree[iSample] -> Draw(myVar + " >>+ " + TString(hist[theHistCounter] -> GetName()),thisScale + "hlt_weight*evt_weight*kf_weight*pu_weight" + myCut,"goff");
        
    //add the histogram to the stack if the last of the series:
    //either last sample or ~ sample followed by non ~ sample
    if (isLastOfSerie) {
       if (xlowVec != 0) {
         for (int iBin = 1; iBin <= nBins; iBin++) hist[theHistCounter]->SetBinError  (iBin,hist[theHistCounter]->GetBinError(iBin)/hist[theHistCounter]->GetBinWidth(iBin));
         for (int iBin = 1; iBin <= nBins; iBin++) hist[theHistCounter]->SetBinContent(iBin,hist[theHistCounter]->GetBinContent(iBin)/hist[theHistCounter]->GetBinWidth(iBin));
       }
       hs -> Add(hist[theHistCounter]);
       cout << hist[theHistCounter] -> GetBinContent(1) << " +/- " <<  hist[theHistCounter] -> GetBinError(1) << endl;
       if ( listOfSamples.at(iSample)->Name()->Contains("wgptg130") ) {
         nSig +=  hist[theHistCounter] -> GetBinContent(1) ;
         nSigErrSq +=  pow(hist[theHistCounter] -> GetBinError(1),2) ;
       }
       else {
         nBkg +=  hist[theHistCounter] -> GetBinContent(1) ;
         nBkgErrSq +=  pow(hist[theHistCounter] -> GetBinError(1),2) ;
       }
       theHistCounter++;
    }
    
  }//end loop on samples

  //Fix the legend
  for (int iHisto = theHistCounter-1; iHisto >= 0; iHisto--) {
    leg -> AddEntry(hist[iHisto], theLegends[iHisto], "f");   
  }
  
  //get the maximum to properly set the frame
  float theMax = hdata -> GetBinContent(hdata -> GetMaximumBin()) + hdata -> GetBinError(hdata -> GetMaximumBin());
  TH1* theMCSum = (TH1*) hs->GetStack()->Last();
  cout << "total MC " << theMCSum -> GetBinContent(1) << " +/- " << theMCSum -> GetBinError(1) << endl;
  float theMaxMC = theMCSum->GetBinContent(theMCSum->GetMaximumBin()) + theMCSum->GetBinError(theMCSum->GetMaximumBin());
  if (theMaxMC > theMax) theMax = theMaxMC;
  
    
  if (isBlind) cout << "total DATA " << hdata -> GetBinContent(1) << " +/- " <<  hdata -> GetBinError(1) << endl;

  //compute the scale factor
  float nData =  hdata -> GetBinContent(1);
  float nDataErr =  hdata -> GetBinError(1);
  newScaleFactor = (nData - nBkg)/(nSig/defScaleFactor);
  float newScaleFactorErr = sqrt( (pow(nDataErr,2) + nBkgErrSq)/(nData - nBkg)/(nData - nBkg) + nSigErrSq/nSig/nSig ) * newScaleFactor;
  cout << "\n The scale factor is " << newScaleFactor << " +/- " << newScaleFactorErr << endl;
  
  //cleanup the memory allocation
  delete theMCSum;
  delete hs;
  delete leg;
  delete hdata;
  infile -> Close();
  delete infile;
  
  return;
}
Beispiel #18
0
void plot(int mass) {
  double myQCDRelUncert = 0.038;
  double myEWKRelUncert = 0.131;
  double myFakesRelUncert = 0.238;
  double delta = 1.4;
  double br = 0.05;
  bool debug = false;
  bool log = false;
  double ymin = 0.001;
  double ymax = 48;
  
  static bool bMessage = false;
  if (!bMessage) {
    cout << "Values used as relative uncertainty (please check):" << endl;
    cout << "  QCD: " << myQCDRelUncert << endl;
    cout << "  EWK genuine tau: " << myEWKRelUncert << endl;
    cout << "  EWK fake tau: " << myFakesRelUncert << endl << endl;
    bMessage = true;
  }
  cout << "Processing mass point: " << mass << " GeV/c2" << endl;
  
  gStyle->SetOptFit(1);
  gStyle->SetOptStat(0);
  gStyle->SetOptTitle(0);
  gStyle->SetTitleFont(43, "xyz");
  gStyle->SetTitleSize(33, "xyz");
  gStyle->SetLabelFont(43, "xyz");
  gStyle->SetLabelSize(27, "xyz");
  
  //std::string infile = "EPS_data_nodeltaphi/hplus_100.root";
  //std::string infile = "EPS_data_deltaphi160/hplus_100.root";
  std::stringstream s;
  s << "lands_histograms_hplushadronic_m" << mass << ".root";

  std::string infile = s.str();
  
 // Canvas
  TCanvas *myCanvas = new TCanvas("myCanvas", "",0,0,600,600);
  myCanvas->SetHighLightColor(2);
  myCanvas->Range(0,0,1,1);
  myCanvas->SetFillColor(0);
  myCanvas->SetBorderMode(0);
  myCanvas->SetBorderSize(2);
  if (log)
    myCanvas->SetLogy();
  myCanvas->SetTickx(1);
  myCanvas->SetTicky(1);
  myCanvas->SetLeftMargin(0.16);
  myCanvas->SetRightMargin(0.05);
  myCanvas->SetTopMargin(0.05);
  myCanvas->SetBottomMargin(0.08);
  myCanvas->SetFrameFillStyle(0);
  myCanvas->SetFrameBorderMode(0);
  myCanvas->SetFrameFillStyle(0);
  myCanvas->SetFrameBorderMode(0);
  myCanvas->cd();

  Int_t ci;

  TFile* f = TFile::Open(infile.c_str());
  s.str("");
  s << "HW" << mass << "_1";
  TH1* hw = (TH1*)f->Get(s.str().c_str());
  s.str("");
  s << "HH" << mass << "_1";
  TH1* hh = (TH1*)f->Get(s.str().c_str());
  TH1* data = (TH1*)f->Get("data_obs");
  data->SetLineWidth(2);
  data->SetMarkerStyle(20);
  data->SetMarkerSize(1.2);

  TH1* ewktau = (TH1*)f->Get("EWK_Tau");
  ci = TColor::GetColor("#993399");
  ewktau->SetFillColor(ci);
  ewktau->SetLineWidth(0);
  TH1* ewkDY = (TH1*)f->Get("EWK_DYx");
  TH1* ewkVV = (TH1*)f->Get("EWK_VVx");
  ewktau->Add(ewkDY);
  ewktau->Add(ewkVV);
  
  //TH1* qcd = (TH1*)f->Get("QCDInv");
  TH1* qcd = (TH1*)f->Get("QCD");
  ci = TColor::GetColor("#ffcc33");
  qcd->SetFillColor(ci);
  qcd->SetLineWidth(0);
  TH1* fakett = (TH1*)f->Get("fake_tt");
  ci = TColor::GetColor("#669900");
  fakett->SetFillColor(ci);
  fakett->SetLineWidth(0);
  TH1* fakeW = (TH1*)f->Get("fake_W");
  ci = TColor::GetColor("#cc3300");
  fakeW->SetFillColor(ci);
  fakeW->SetLineWidth(0);
  TH1* faket = (TH1*)f->Get("fake_t");

  TH1F *hFrame = new TH1F("hFrame","",20,0,400);
  hFrame->SetMinimum(ymin);
  if (log)
    hFrame->SetMaximum(ymax*1.5);
  else
    hFrame->SetMaximum(ymax);
  hFrame->SetDirectory(0);
  hFrame->SetStats(0);
  hFrame->SetLineStyle(0);
  hFrame->SetMarkerStyle(20);
  hFrame->SetXTitle("Transverse mass (#tau jet, E_{T}^{miss}), (GeV/c^{2})");
  if (paperStatus)
    hFrame->SetXTitle("Transverse mass (#tau_{h}, E_{T}^{miss}), (GeV/c^{2})");
  hFrame->SetYTitle("Events / 20 GeV/c^{2}");
  hFrame->GetXaxis()->SetTitleSize(0);
  hFrame->GetXaxis()->SetLabelSize(0);
  hFrame->GetYaxis()->SetTitleFont(43);
  hFrame->GetYaxis()->SetTitleSize(27);
  hFrame->GetYaxis()->SetTitleOffset(1.3);
  

  // signal
  hh->Scale(br*br);
  hw->Scale(2*br*(1.0-br));
  TH1* signal = (TH1*)hh->Clone();
  signal->Add(hw);

  ci = TColor::GetColor("#ff3399");
  signal->SetLineColor(ci);
  signal->SetLineStyle(2);
  signal->SetLineWidth(2);

  // Fakes
  TH1* fakes = (TH1*)(fakett->Clone());
  fakes->Add(fakeW);
  fakes->Add(faket);

  // stacked backgrounds
  THStack *exp = new THStack();
  exp->SetName("exp");
  exp->SetTitle("exp");
  exp->Add(fakes);
  exp->Add(ewktau);
  exp->Add(qcd);
  exp->Add(signal);
  
  TH1* hExpBkg = (TH1*)fakes->Clone();
  hExpBkg->Add(ewktau);
  hExpBkg->Add(qcd);
  
  // uncertainty
  TH1* uncert = (TH1*)fakeW->Clone();
  uncert->Add(fakett);
  uncert->Add(ewktau);
  uncert->Add(qcd);
  uncert->SetFillColor(1);
  uncert->SetFillStyle(3344);
  uncert->SetLineColor(0);
  uncert->SetLineStyle(0);
  uncert->SetLineWidth(0);

  TH1* hExpBkgTotalUncert = (TH1*)uncert->Clone();
  hExpBkgTotalUncert->SetFillStyle(3354);

  TH1* hAgreement = (TH1*)data->Clone();
  hAgreement->Divide(hExpBkg);
  TGraphErrors* hAgreementRelUncert = new TGraphErrors(hAgreement->GetNbinsX());
  hAgreementRelUncert->SetLineWidth(2);
  hAgreementRelUncert->SetLineColor(kBlack);
  for (int i = 1; i <= hFrame->GetNbinsX(); ++i) {
    double myQCDTotalUncert = TMath::Power(qcd->GetBinError(i), 2)
      + TMath::Power(qcd->GetBinContent(i)*myQCDRelUncert, 2);
    double myEWKTotalUncert = TMath::Power(ewktau->GetBinError(i), 2)
      + TMath::Power(ewktau->GetBinContent(i)*myEWKRelUncert, 2);
    double myFakesTotalUncert = TMath::Power(fakes->GetBinError(i), 2)
      + TMath::Power(fakes->GetBinContent(i)*myFakesRelUncert, 2);
    hExpBkgTotalUncert->SetBinError(i, TMath::Sqrt(myQCDTotalUncert + myEWKTotalUncert + myFakesTotalUncert));

    if (hExpBkg->GetBinContent(i) > 0) {
      hAgreementRelUncert->SetPoint(i-1, hExpBkg->GetBinCenter(i), data->GetBinContent(i) / hExpBkg->GetBinContent(i));
      double myUncertData = 0;
      if (data->GetBinContent(i) > 0)
        myUncertData = TMath::Power(data->GetBinError(i) / data->GetBinContent(i), 2);
      double myUncertBkg = (myQCDTotalUncert + myEWKTotalUncert + myFakesTotalUncert) / TMath::Power(hExpBkg->GetBinContent(i), 2);
      hAgreementRelUncert->SetPointError(i-1, 0,  data->GetBinContent(i) / hExpBkg->GetBinContent(i) * TMath::Sqrt(myUncertData + myUncertBkg));
    } else {
      hAgreementRelUncert->SetPoint(i-1, hExpBkg->GetBinCenter(i), 0);
      hAgreementRelUncert->SetPointError(i-1, 0, 0);
    }
    if (debug) {
      cout << "Point: " << hAgreementRelUncert->GetX()[i-1]-10 << "-" << hAgreementRelUncert->GetX()[i-1]+10
          << " GeV/c2, agreement: " << hAgreementRelUncert->GetY()[i-1] << ", uncert: " << hAgreement->GetBinError(i) << ", " << hAgreementRelUncert->GetErrorY(i-1) << endl;
      cout << "  bkg. stat. uncert. " << hExpBkg->GetBinError(i) << " (i.e. " << hExpBkg->GetBinError(i) / hExpBkg->GetBinContent(i) * 100.0 << " %)"
          << ", stat+syst uncert. " << TMath::Sqrt(myQCDTotalUncert + myEWKTotalUncert + myFakesTotalUncert) 
          << " (i.e. " << TMath::Sqrt(myQCDTotalUncert + myEWKTotalUncert + myFakesTotalUncert) / hExpBkg->GetBinContent(i) * 100.0 << " %)" << endl;
    }
  }

  // Agreement pad
  TPad* pad = new TPad("ratiopad","ratiopad",0.,0.,1.,.3);
  pad->Draw();
  pad->cd();
  pad->Range(0,0,1,1);
  pad->SetFillColor(0);
  pad->SetFillStyle(4000);
  pad->SetBorderMode(0);
  pad->SetBorderSize(2);
  pad->SetTickx(1);
  pad->SetTicky(1);
  pad->SetLeftMargin(0.16);
  pad->SetRightMargin(0.05);
  pad->SetTopMargin(0);
  pad->SetBottomMargin(0.34);
  pad->SetFrameFillStyle(0);
  pad->SetFrameBorderMode(0);
  // Plot here ratio
  if (1.0-delta > 0)
    hAgreement->SetMinimum(1.0-delta);
  else
    hAgreement->SetMinimum(0.);
  hAgreement->SetMaximum(1.0+delta);
  hAgreement->GetXaxis()->SetLabelOffset(0.007);
  hAgreement->GetXaxis()->SetLabelFont(43);
  hAgreement->GetXaxis()->SetLabelSize(27);
  hAgreement->GetYaxis()->SetLabelFont(43);
  hAgreement->GetYaxis()->SetLabelSize(27);
  hAgreement->GetYaxis()->SetLabelOffset(0.007);
  hAgreement->GetYaxis()->SetNdivisions(505);
  hAgreement->GetXaxis()->SetTitleFont(43);
  hAgreement->GetYaxis()->SetTitleFont(43);
  hAgreement->GetXaxis()->SetTitleSize(33);
  hAgreement->GetYaxis()->SetTitleSize(33);
  hAgreement->SetTitleSize(27, "xyz");
  hAgreement->GetXaxis()->SetTitleOffset(3.2);
  hAgreement->GetYaxis()->SetTitleOffset(1.3);
  hAgreement->SetXTitle(hFrame->GetXaxis()->GetTitle());
  hAgreement->SetYTitle("Data/#Sigmabkg");
  hAgreement->Draw("e2");
  // Plot line at zero
  TH1* hAgreementLine = dynamic_cast<TH1*>(hAgreement->Clone());
  for (int i = 1; i <= hAgreementLine->GetNbinsX(); ++i) {
    hAgreementLine->SetBinContent(i,1.0);
    hAgreementLine->SetBinError(i,0.0);
  }
  hAgreementLine->SetLineColor(kRed);
  hAgreementLine->SetLineWidth(2);
  hAgreementLine->SetLineStyle(3);
  hAgreementLine->Draw("hist same");
  hAgreement->Draw("same");
  hAgreementRelUncert->Draw("[]");
  pad->RedrawAxis();

  myCanvas->cd();
  
  TPad* plotpad = new TPad("plotpad", "plotpad",0,0.3,1.,1.);
  plotpad->Draw();
  plotpad->cd();
  plotpad->Range(0,0,1,1);
  plotpad->SetFillColor(0);
  plotpad->SetFillStyle(4000);
  plotpad->SetBorderMode(0);
  plotpad->SetBorderSize(2);
  //if (logy)
  //  plotpad->SetLogy();
  plotpad->SetTickx(1);
  plotpad->SetTicky(1);
  plotpad->SetLeftMargin(0.16);
  plotpad->SetRightMargin(0.05);
  plotpad->SetTopMargin(0.065);
  plotpad->SetBottomMargin(0.0);
  plotpad->SetFrameFillStyle(0);
  plotpad->SetFrameBorderMode(0);
  
  hFrame->GetXaxis()->SetTitleSize(0);
  hFrame->GetXaxis()->SetLabelSize(0);
  hFrame->GetYaxis()->SetTitleFont(43);
  hFrame->GetYaxis()->SetTitleSize(33);
  hFrame->GetYaxis()->SetTitleOffset(1.3);
  
  // Draw objects
  hFrame->Draw();
  exp->Draw("hist same");
  uncert->Draw("E2 same");
  hExpBkgTotalUncert->Draw("E2 same");
  // Data
  data->Draw("same");
  
  //signal->Draw("same");
  TLegend *leg = new TLegend(0.53,0.6,0.87,0.91,NULL,"brNDC");
  leg->SetBorderSize(0);
  leg->SetTextFont(63);
  leg->SetTextSize(18);
  leg->SetLineColor(1);
  leg->SetLineStyle(1);
  leg->SetLineWidth(1);
  leg->SetFillColor(kWhite);
  //leg->SetFillStyle(4000); // enabling this will cause the plot to be erased from the pad
  TLegendEntry* entry = leg->AddEntry(data, "Data", "P");
  s.str("");
  s << "with H^{#pm}#rightarrow#tau^{#pm}#nu";
  entry = leg->AddEntry(signal, s.str().c_str(), "L");
  entry = leg->AddEntry(qcd, "QCD (meas.)", "F");
  entry = leg->AddEntry(ewktau, "EWK genuine #tau (meas.)", "F");
  entry = leg->AddEntry(fakes, "EWK fake #tau (MC)", "F");
  entry = leg->AddEntry(uncert, "stat. uncert.", "F");
  entry = leg->AddEntry(hExpBkgTotalUncert, "stat. #oplus syst. uncert.", "F");
  leg->Draw();
  
  string myTitle = "CMS Preliminary";
  if (paperStatus)
    myTitle = "CMS";

  TLatex *tex = new TLatex(0.62,0.945,myTitle.c_str());
  tex->SetNDC();
  tex->SetTextFont(43);
  tex->SetTextSize(27);
  tex->SetLineWidth(2);
  tex->Draw();
  tex = new TLatex(0.2,0.945,"#sqrt{s} = 7 TeV");
  tex->SetNDC();
  tex->SetTextFont(43);
  tex->SetTextSize(27);
  tex->SetLineWidth(2);
  tex->Draw();
  tex = new TLatex(0.43,0.945,"2.2 fb^{-1}");
  tex->SetNDC();
  tex->SetTextFont(43);
  tex->SetTextSize(27);
  tex->SetLineWidth(2);
  tex->Draw();

  s.str("");
  s << "m_{H^{#pm}} = " << mass << " GeV/c^{2}";
  tex = new TLatex(0.28,0.865,s.str().c_str());
  tex->SetNDC();
  tex->SetTextFont(63);
  tex->SetTextSize(20);
  tex->SetLineWidth(2);
  tex->Draw();
  s.str("");
  s << "BR(t#rightarrowbH^{#pm})=" << setprecision(2) << br;
  tex = new TLatex(0.28,0.805,s.str().c_str());
  tex->SetNDC();
  tex->SetTextFont(63);
  tex->SetTextSize(20);
  tex->SetLineWidth(2);
  tex->Draw();

  
  plotpad->RedrawAxis();
  plotpad->Modified();

  s.str("");
  s << "mT_datadriven_m" << mass << ".png";
  myCanvas->Print(s.str().c_str());
  s.str("");
  s << "mT_datadriven_m" << mass << ".C";
  myCanvas->Print(s.str().c_str());
  s.str("");
  s << "mT_datadriven_m" << mass << ".eps";
  myCanvas->Print(s.str().c_str());
   

}
void fit(float bgpar2smudge=1.0) {
  TF1 *fsig = new TF1("fsig",&d_sig,0.4,2,5);
  FILE *ofile;
  ofile = fopen("xsect-integrated-me.txt","w");
  TFile *_file0 = TFile::Open("h3maker-hn.root","update");
  _file0->Delete("*_f;*");
  TH2 *h2xsect = new TH2("hq2wXsect","Q^2:W",32,1.6,3.2,7,1.5,5.1);
  Double_t qbinedges[] = { 1.5, 1.6, 1.8, 2.1, 2.4, 2.76, 3.3, 5.1 };
  h2xsect->GetYaxis()->Set(7,qbinedges);
  TH3 *h3 = (TH3*)_file0->Get("hq2wmmp");
  int qbins = h3->GetZaxis()->GetNbins();
  //int wbins = h3->GetYaxis()->GetNbins();
  fprintf(ofile, "W\tQ2\txsect\terror\tpol4p0\tpol4p1\tpol4p2\tpol4p3\tpol4p4\tgN\tgM\tgS\tstepx0\tstepx1\txsectFn\n");
  for (int iq = 0; iq < qbins; iq++) {
    TString hsn = TString::Format("hs%d",iq);
    THStack *hs = (THStack*)_file0->Get(hsn.Data());
    TIter next(hs->GetHists());
    //while (TObject *obj = next()) {
    //TH1 *h = (TH1*)obj;
    while (TH1 *h = (TH1*)next()) {
      float *wq = getwq(h);
      float wval = wq[0];
      float qval = wq[1];
      delete [] wq;
      int wbin = h3->GetYaxis()->FindBin(wval);
      float wlow = h3->GetYaxis()->GetBinLowEdge(wbin);
      float step_x0 = sqrt(wlow*wlow+MASS_P*MASS_P-2*wlow*MASS_P);
      float whigh = h3->GetYaxis()->GetBinLowEdge(wbin+1);
      float step_x1 = sqrt(whigh*whigh+MASS_P*MASS_P-2*whigh*MASS_P);
      fitmmp(h,step_x0,step_x1,wval);
      TH1 *htmp = (TH1*)h->Clone("hbgsubtracted");
      TF1 *fbg = (TF1*)h->GetListOfFunctions()->FindObject("fbg");
      htmp->Add(fbg,-1);
      double N = htmp->Integral(34,43);
      double qwidth = h3->GetZaxis()->GetBinWidth(iq+1);
      //int wbin = h3->GetYaxis()->FindBin(wval);
      double wwidth = h3->GetYaxis()->GetBinWidth(wbin);

      TF1 *ftmp = (TF1*)h->GetListOfFunctions()->At(0);
      fsig->SetParameter(0,ftmp->GetParameter(5));
      fsig->SetParameter(1,ftmp->GetParameter(6));
      fsig->SetParameter(2,ftmp->GetParameter(7));
      fsig->SetParameter(3,step_x0);
      fsig->SetParameter(4,step_x1);
      fsig->SetLineWidth(2);
      fsig->SetLineColor(kBlue+1);
      h->GetListOfFunctions()->Add((TF1*)fsig->Clone("fsig"));
      //fsig->Print();
      double Nfn = 0;
      for (int b = 1; b < h->GetNbinsX(); b++) {
        double x = h->GetXaxis()->GetBinCenter(b);
        Nfn += fsig->Eval(x);
      }
      //printf("**** %.3e\t\%.3e\n",Nfn,N);
      double xsect = N/(0.891*wwidth*qwidth*19.844);
      double xsectFn = Nfn/(0.891*wwidth*qwidth*19.844);
      double err2 = 0;
      for (int immp = 34; immp < 44; immp++) err2 += htmp->GetBinError(immp)*htmp->GetBinError(immp);
      //fprintf(ofile, "%.3f\t%.3f\t%.0f\t%.0f",wval,qval,xsect/(1e6), sqrt(err2)/(1e6));
      fprintf(ofile, "%.3f\t%.3f\t%.3e\t%.3e",wval,qval,xsect/(1e6), sqrt(err2)/(1e6));
      int npar = ftmp->GetNpar();
      for (int ipar = 0; ipar < npar; ipar++) fprintf(ofile, "\t%.3e", ftmp->GetParameter(ipar));
      fprintf(ofile,"\t%.3e",xsectFn/(1e6));
      fprintf(ofile, "\n");
    }
    hsn.Append("_f");
    _file0->WriteObject(hs,hsn.Data());
    delete hs;
  }
  fclose(ofile);
  delete _file0;
}
void makeSystPlot( TFile * f, TString oldFolder, RooWorkspace *WS,  string channel, string syst, int toMassNo, int fromMassNo, int rightBinNo, int addRightBin,  int addRightBinm1) //massNo 0-51, see xSec7TeV.h 
{


  std::cout << "oldFolder,  channel , addRightBin, addRightBinm1: " << oldFolder << " , " <<channel << " , " << addRightBin  << " , "<< addRightBinm1 << std::endl;

  RooArgList  * hobs = new RooArgList("hobs");
  //  RooRealVar BDT("BDT", "BDT", -1, 1);///OLD VARIABLE NAME HERE
  RooRealVar BDT("CMS_vhbb_BDT_Wln", "CMS_vhbb_BDT_Wln", -1, 1);///OLD VARIABLE NAME HERE
  hobs->add(*WS->var("CMS_vhbb_BDT_Wln"));  ///NEW VARIABLE NAME HERE
  RooWorkspace *tempWS =  (RooWorkspace*) f->Get(oldFolder.Data());
  TString systT(syst);
  TString chanT(channel);

  if((kount < 3) && (channel=="data_obs"))
  {
    kount++;
    std::string namen  = channel;
    
    std::cout << oldFolder.Data() << std::endl;
    std::cout << namen << std::endl;
    RooDataHist* tempRooDataHistNom = (RooDataHist*)  tempWS->data(namen.c_str());
    TH1 *tempHistNom = tempRooDataHistNom->createHistogram(namen.c_str(),BDT,RooFit::Binning(bins));

   tempHistNom->Rebin(rebin);

 if(addRightBin == 1)
    {
     float  err0 = tempHistNom->GetBinError(rightBinNo);
     float  con0 = tempHistNom->GetBinContent(rightBinNo);
 
     float  err1 = tempHistNom->GetBinError(rightBinNo-1);
     float  con1 = tempHistNom->GetBinContent(rightBinNo-1);
       
     tempHistNom->SetBinContent(rightBinNo,0);
     tempHistNom->SetBinError(rightBinNo,0);
     tempHistNom->SetBinContent(rightBinNo-1,con0+con1);
     tempHistNom->SetBinError(rightBinNo-1,sqrt(err0*err0+err1*err1));
    }


 if(addRightBinm1 == 1)
    {
     float  err0 = tempHistNom->GetBinError(rightBinNo-1);
     float  con0 = tempHistNom->GetBinContent(rightBinNo-1);
 
     float  err1 = tempHistNom->GetBinError(rightBinNo-2);
     float  con1 = tempHistNom->GetBinContent(rightBinNo-2);
       
     tempHistNom->SetBinContent(rightBinNo-1,0);
     tempHistNom->SetBinError(rightBinNo-1,0);
     tempHistNom->SetBinContent(rightBinNo-2,con0+con1);
     tempHistNom->SetBinError(rightBinNo-2,sqrt(err0*err0+err1*err1));
    }





    RooDataHist *DHnom = new RooDataHist(channel.c_str(),"",*hobs,tempHistNom);  
    WS->import(*(new RooHistPdf(channel.c_str(),"",*hobs,*DHnom)));
 
 }

 if (channel!="data_obs")
{
  std::string nameUp; 
  std::string namen; 
  std::string nameDown;


  if(syst == "stat")
  {
   if(oldFolder.Contains("Wenu"))
   { 
     nameUp  = channel + "_CMS_vhbb_stat" + channel + "_WenuUp";
     namen  = channel;
     nameDown  = channel + "_CMS_vhbb_stat" + channel + "_WenuDown";

     if(channel == "s_Top")
     {
     nameUp  = channel + "_CMS_vhbb_statsTop_WenuUp";
     namen  = channel;
     nameDown  = channel + "_CMS_vhbb_statsTop_WenuDown";
     }

   }
   else
   {
     nameUp  = channel + "_CMS_vhbb_stat" + channel + "_WmunuUp";
     namen  = channel;
     nameDown  = channel + "_CMS_vhbb_stat" + channel + "_WmunuDown";

     if(channel == "s_Top")
     {
     nameUp  = channel + "_CMS_vhbb_statsTop_WmunuUp";
     namen  = channel;
     nameDown  = channel + "_CMS_vhbb_statsTop_WmunuDown";
     }


   }
  }
  else
  {
  nameUp  = channel + "_CMS_" + syst + "Up";
  namen  = channel;
  nameDown = channel + "_CMS_" + syst + "Down";
  }
 
  if((syst == "stat") && (oldFolder.Contains("2")))
  {
   if(oldFolder.Contains("Wenu"))
   { 
     nameUp  = channel + "_CMS_vhbb_stat" + channel + "_Wenu2Up";
     namen  = channel;
     nameDown  = channel + "_CMS_vhbb_stat" + channel + "_Wenu2Down";

     if(channel == "s_Top")
     {
     nameUp  = channel + "_CMS_vhbb_statsTop_Wenu2Up";
     namen  = channel;
     nameDown  = channel + "_CMS_vhbb_statsTop_Wenu2Down";
     }

   }
   else
   {
     nameUp  = channel + "_CMS_vhbb_stat" + channel +  "_Wmunu2Up";
     namen  = channel;
     nameDown  = channel + "_CMS_vhbb_stat" + channel + "_Wmunu2Down";

     if(channel == "s_Top")
     {
     nameUp  = channel + "_CMS_vhbb_statsTop_Wmunu2Up";
     namen  = channel;
     nameDown  = channel + "_CMS_vhbb_statsTop_Wmunu2Down";
     }


   }
  }

  if(systT.Contains("Model"))
  {
     nameUp  = channel + "_CMS_vhbb_WModelUp";
     namen  = channel;
     nameDown  = channel + "_CMS_vhbb_WModelDown";
  }

  if( systT.Contains("stat") && (oldFolder.Contains("Wenu")) && IFILE.Contains("8TeV") && !(oldFolder.Contains("2")))
  { 
     nameUp  = channel + "_CMS_vhbb_stat" + channel + "_Wenu_8TeVUp";
     namen  = channel;
     nameDown  = channel + "_CMS_vhbb_stat" + channel + "_Wenu_8TeVDown";

   if(channel == "s_Top")
     {
     nameUp  = channel + "_CMS_vhbb_statsTop_Wenu_8TeVUp";
     namen  = channel;
     nameDown  = channel + "_CMS_vhbb_statsTop_Wenu_8TeVDown";
     }


  }

  if( systT.Contains("stat") && (oldFolder.Contains("Wmunu")) && IFILE.Contains("8TeV") && !(oldFolder.Contains("2")))
  { 
     nameUp  = channel + "_CMS_vhbb_stat" + channel + "_Wmnu_8TeVUp";
     namen  = channel;
     nameDown  = channel + "_CMS_vhbb_stat" + channel + "_Wmnu_8TeVDown";

   if(channel == "s_Top")
     {
     nameUp  = channel + "_CMS_vhbb_statsTop_Wmnu_8TeVUp";
     namen  = channel;
     nameDown  = channel + "_CMS_vhbb_statsTop_Wmnu_8TeVDown";
     }


  }


  if( systT.Contains("stat") && (oldFolder.Contains("Wenu")) && IFILE.Contains("8TeV") && (oldFolder.Contains("2")))
  { 
     nameUp  = channel + "_CMS_vhbb_stat" + channel + "_Wenu2_8TeVUp";
     namen  = channel;
     nameDown  = channel + "_CMS_vhbb_stat" + channel + "_Wenu2_8TeVDown";

   if(channel == "s_Top")
     {
     nameUp  = channel + "_CMS_vhbb_statsTop_Wenu2_8TeVUp";
     namen  = channel;
     nameDown  = channel + "_CMS_vhbb_statsTop_Wenu2_8TeVDown";
     }


  }

  if( systT.Contains("stat") && (oldFolder.Contains("Wmunu")) && IFILE.Contains("8TeV") && (oldFolder.Contains("2")))
  { 
     nameUp  = channel + "_CMS_vhbb_stat" + channel + "_Wmnu2_8TeVUp";
     namen  = channel;
     nameDown  = channel + "_CMS_vhbb_stat" + channel + "_Wmnu2_8TeVDown";

   if(channel == "s_Top")
     {
     nameUp  = channel + "_CMS_vhbb_statsTop_Wmnu2_8TeVUp";
     namen  = channel;
     nameDown  = channel + "_CMS_vhbb_statsTop_Wmnu2_8TeVDown";
     }


  }







  RooDataHist* tempRooDataHistUp = (RooDataHist*)  tempWS->data(nameUp.c_str());
  RooDataHist* tempRooDataHistDown = (RooDataHist*)  tempWS->data(nameDown.c_str());
  RooDataHist* tempRooDataHistNom = (RooDataHist*)  tempWS->data(namen.c_str());


  std::cout << oldFolder.Data() << std::endl; 
  std::cout << nameUp.c_str() << std::endl; 
  

  


  TH1 *tempHistUp = tempRooDataHistUp->createHistogram(nameUp.c_str(),BDT,RooFit::Binning(bins));
  TH1 *tempHistDown = tempRooDataHistDown->createHistogram(nameDown.c_str(),BDT,RooFit::Binning(bins));
  TH1 *tempHistNom = tempRooDataHistNom->createHistogram(namen.c_str(),BDT,RooFit::Binning(bins));
  
  if(chanT.Contains("WH") && IFILE.Contains("7TeV"))
  {
     tempHistUp->Scale(xSec7WH[toMassNo]/xSec7WH[fromMassNo]);
     tempHistDown->Scale(xSec7WH[toMassNo]/xSec7WH[fromMassNo]);
     tempHistNom->Scale(xSec7WH[toMassNo]/xSec7WH[fromMassNo]);
  }  
 
  if(chanT.Contains("WH") && IFILE.Contains("8TeV"))
  {
     tempHistUp->Scale(xSec8WH[toMassNo]/xSec8WH[fromMassNo]);
     tempHistDown->Scale(xSec8WH[toMassNo]/xSec8WH[fromMassNo]);
     tempHistNom->Scale(xSec8WH[toMassNo]/xSec8WH[fromMassNo]);
  }  
  
  std::cout<< "channel--> " << channel << std::endl;


    
  tempHistUp->SetLineColor(kRed);
  tempHistUp->SetLineWidth(3);
  tempHistUp->SetFillColor(0);
  
  tempHistDown->SetLineColor(kBlue);
  tempHistDown->SetFillColor(0);
  tempHistDown->SetLineWidth(3);
  
  tempHistNom->SetFillColor(0);
  tempHistNom->SetMarkerStyle(20);
    
  tempHistUp->SetTitle((channel + syst).c_str());
 
  tempHistNom->Rebin(rebin);
  tempHistUp->Rebin(rebin);
  tempHistDown->Rebin(rebin);


 if(addRightBin == 1)
    {
     float  err0 = tempHistNom->GetBinError(rightBinNo);
     float  con0 = tempHistNom->GetBinContent(rightBinNo);
 
     float  err1 = tempHistNom->GetBinError(rightBinNo-1);
     float  con1 = tempHistNom->GetBinContent(rightBinNo-1);
       
     tempHistNom->SetBinContent(rightBinNo,0);
     tempHistNom->SetBinError(rightBinNo,0);
     tempHistNom->SetBinContent(rightBinNo-1,con0+con1);
     tempHistNom->SetBinError(rightBinNo-1,sqrt(err0*err0+err1*err1));


     err0 = tempHistUp->GetBinError(rightBinNo);
     con0 = tempHistUp->GetBinContent(rightBinNo);
 
     err1 = tempHistUp->GetBinError(rightBinNo-1);
     con1 = tempHistUp->GetBinContent(rightBinNo-1);
       
     tempHistUp->SetBinContent(rightBinNo,0);
     tempHistUp->SetBinError(rightBinNo,0);
     tempHistUp->SetBinContent(rightBinNo-1,con0+con1);
     tempHistUp->SetBinError(rightBinNo-1,sqrt(err0*err0+err1*err1));



     err0 = tempHistDown->GetBinError(rightBinNo);
     con0 = tempHistDown->GetBinContent(rightBinNo);
 
     err1 = tempHistDown->GetBinError(rightBinNo-1);
     con1 = tempHistDown->GetBinContent(rightBinNo-1);
       
     tempHistDown->SetBinContent(rightBinNo,0);
     tempHistDown->SetBinError(rightBinNo,0);
     tempHistDown->SetBinContent(rightBinNo-1,con0+con1);
     tempHistDown->SetBinError(rightBinNo-1,sqrt(err0*err0+err1*err1));

    }



 if(addRightBinm1 == 1)
    {
     float  err0 = tempHistNom->GetBinError(rightBinNo-1);
     float  con0 = tempHistNom->GetBinContent(rightBinNo-1);
 
     float  err1 = tempHistNom->GetBinError(rightBinNo-2);
     float  con1 = tempHistNom->GetBinContent(rightBinNo-2);
       
     tempHistNom->SetBinContent(rightBinNo-1,0);
     tempHistNom->SetBinError(rightBinNo-1,0);
     tempHistNom->SetBinContent(rightBinNo-2,con0+con1);
     tempHistNom->SetBinError(rightBinNo-2,sqrt(err0*err0+err1*err1));


     err0 = tempHistUp->GetBinError(rightBinNo-1);
     con0 = tempHistUp->GetBinContent(rightBinNo-1);
 
     err1 = tempHistUp->GetBinError(rightBinNo-2);
     con1 = tempHistUp->GetBinContent(rightBinNo-2);
       
     tempHistUp->SetBinContent(rightBinNo-1,0);
     tempHistUp->SetBinError(rightBinNo-1,0);
     tempHistUp->SetBinContent(rightBinNo-2,con0+con1);
     tempHistUp->SetBinError(rightBinNo-2,sqrt(err0*err0+err1*err1));



     err0 = tempHistDown->GetBinError(rightBinNo-1);
     con0 = tempHistDown->GetBinContent(rightBinNo-1);
 
     err1 = tempHistDown->GetBinError(rightBinNo-2);
     con1 = tempHistDown->GetBinContent(rightBinNo-2);
       
     tempHistDown->SetBinContent(rightBinNo-1,0);
     tempHistDown->SetBinError(rightBinNo-1,0);
     tempHistDown->SetBinContent(rightBinNo-2,con0+con1);
     tempHistDown->SetBinError(rightBinNo-2,sqrt(err0*err0+err1*err1));

    }




  RooDataHist *DHnom;
  RooDataHist *DHup = new RooDataHist(nameUp.c_str(),"",*hobs,tempHistUp);  
  if(kount2 < 3) DHnom = new RooDataHist(namen.c_str(),"",*hobs,tempHistNom);
  RooDataHist *DHdown = new RooDataHist(nameDown.c_str(),"",*hobs,tempHistDown);  

  WS->import(*(new RooHistPdf(nameUp.c_str(),"",*hobs,*DHup)));
  WS->import(*(new RooHistPdf(nameDown.c_str(),"",*hobs,*DHdown)));
  if(kount2 < 3){ WS->import(*(new RooHistPdf(namen.c_str(),"",*hobs,*DHnom))); kount2++;}

 }


}
void myControlPlots(const char *cuttablefilename,
		    const char *qcdcuttablefilename,
		    const char *samplefilename,
		    const plotVar_t plotvars[])
{
  //gROOT->ProcessLine(".L tdrstyle.C");

  TString unwtcutstring, qcdcutstring;

  loadCutString(cuttablefilename, unwtcutstring);
  if (strlen(qcdcuttablefilename))
    loadCutString(qcdcuttablefilename, qcdcutstring);

  //  const char* the_cut = "1";
  //  double BINWIDTH = ((MAXRange-MINRange)/NBINS);

 // Get the input trees:

  vector<Sample *> samples;

  loadSamples(samplefilename,samples);

 // Data

  Sample *sdata = samples[0];
  cout << "ndata =" << sdata->Tree()->GetEntries() <<endl;

  TFile f("plotvar_histo.root", "RECREATE");

  //============================================================
  //  VARIABLE LOOP
  //============================================================

  for (int ivar=0; ; ivar++) {

    plotVar_t pv = plotvars[ivar];
 
    if ( !pv.plotvar.Length() ) break;

    cout << pv.plotvar << "\t"<<pv.MINRange<<"\t" << pv.MAXRange<<"\t" << pv.NBINS<<"\tTHE CUT " << endl;

    if ( sdata->Tree()->Draw(pv.plotvar,"","goff",1) == -1 ) { // check if the variable exists in the tree
      cout << "\t...can't be plotted!" << endl;
      continue;
    }

    TCut the_cut(TString("effwt*puwt*")+unwtcutstring);
    TCut the_cutE(TString("effwt*puwt*puwt*")+unwtcutstring);
    TCut qcd_cut;
    if (qcdcutstring.Length())
      qcd_cut = TCut(TString("effwt*puwt*")+qcdcutstring);

    TCut nullcut("");

    const double BINWIDTH = ((pv.MAXRange-pv.MINRange)/pv.NBINS);

    map<TString, TH1 *> m_histos;
    map<TString, bool> m_stacked;

    double totevents = 0.;
    TH1 * th1qcd = NULL;
    double qcdfrac = 0.;

    //============================================================
    // DRAW THE VARIABLE FOR ALL SAMPLES, CREATE HISTOS
    //============================================================

    for (size_t isamp=0; isamp<samples.size(); isamp++) {
      Sample *s = samples[isamp];

      m_stacked[s->name()] = false;

      TH1 *h;

      if (s->name().EqualTo("data"))            h = s->Draw(pv, the_cut, nullcut); // effwt*puwt==1 for data!
      else if (s->filename().Contains("QCD")) { h = s->Draw(pv, qcd_cut, nullcut);
	th1qcd = h;
	qcdfrac = s->otherscale();
      } else {                                  h = s->Draw(pv, the_cut, the_cutE);
	if (s->stackit()) {
	  totevents += h->Integral();
	}
      }

      map<TString, TH1 *>::iterator mit = m_histos.find(s->name());
      if (mit == m_histos.end()) {
	if (s->stackit()) {
	  h->SetFillColor(s->colorcode());
	  h->SetLineColor(s->colorcode());
	  h->SetLineWidth(0);
	}
	m_histos[s->name()] = h;
      } else {
	mit->second->Add(h);
      }
    }

    //============================================================
    // COUNT EVENTS, RENORM TO DATA, CONSTRUCT THE TSTACK & LEGEND
    //============================================================

    TH1 *th1data = m_histos["data"];

    assert(th1data);

    double ndata = th1data->Integral();

    if (th1qcd) {
      // QCD = qcdfrac * data, QCD + Sum(MC) = data, ergo...
      //th1qcd->Scale(qcdfrac*totevents/((1-qcdfrac)*th1qcd->Integral()));

      th1qcd->Scale(qcdfrac*ndata/th1qcd->Integral()); // matches previous script

      totevents += th1qcd->Integral();
    }

    double renorm = ndata/totevents;

    cout << "den = " << totevents << endl;
    cout << "data = " << ndata  <<endl;
    cout  << "data/den = " << renorm << endl;


    // Setup the stack and total
    THStack* hs = new THStack("hs","MC contribution");
    TH1D *th1tot = new TH1D("th1tot", "th1tot", pv.NBINS, pv.MINRange, pv.MAXRange);

    // Set up the legend

    float  legX0=0.65, legX1=0.99, legY0=0.4, legY1=0.88;
    // float  legX0=0.35, legX1=0.85, legY0=0.4, legY1=0.88;
    // float  legX0=0.18, legX1=0.52, legY0=0.4, legY1=0.88;
    TLegend * Leg = new TLegend( legX0, legY0, legX1, legY1);
    Leg->SetFillColor(0);
    Leg->SetFillStyle(0);
    Leg->SetTextSize(0.04);

    if (TString(cuttablefilename).Contains("Mu"))
      Leg->AddEntry(th1data,  "Muon Data",  "PLE");
    else
      Leg->AddEntry(th1data,  "Electron Data",  "PLE");

    vector<double> binErrSQ(pv.NBINS,0.);

    vector<pair<TString, TH1 *> > v_legentries;

    for (size_t isamp=1; isamp<samples.size(); isamp++) {
      Sample *s = samples[isamp];
      if (m_stacked[s->name()]) continue;

      map<TString, TH1 *>::iterator mit = m_histos.find(s->name());
      TH1 *h = mit->second;
      h->Scale(renorm);

      cout << s->name() << " = " << h->Integral() << endl;

      if(s->stackit()) {
	hs->Add(h);
	th1tot->Add(h);
	m_stacked[s->name()] = true;
	v_legentries.push_back(*mit);
	for (int ibin=1; ibin <= pv.NBINS; ibin++)
	  binErrSQ[ibin-1] += h->GetBinError(ibin)*h->GetBinError(ibin);
      }
    }

    // Reverse the order for the legend
    for (vector<pair<TString, TH1 *> >::reverse_iterator
	   rit = v_legentries.rbegin();
	 rit != v_legentries.rend();
	 rit++)
      Leg->AddEntry(rit->second, rit->first, "F");

    TH1D* th1totClone = ( TH1D*) th1tot->Clone("th1totClone");
    th1totClone->SetMarkerStyle(0);
    th1totClone->SetFillStyle(3003);
    th1totClone->SetFillColor(11);
    th1totClone->SetLineColor(0);

    for(int ibin=1; ibin<=th1totClone->GetNbinsX(); ++ibin) {
      th1totClone->SetBinError(ibin, sqrt(binErrSQ[ibin-1]));
    }

    //============================================================
    // SETUP THE CANVAS
    //============================================================

//    gROOT->ProcessLine(".L tdrstyle.C");
    setTDRStyle();
    tdrStyle->SetErrorX(0.5);
    tdrStyle->SetPadRightMargin(0.05);

    tdrStyle->SetLegendBorderSize(0);

    TCanvas* c1 = new TCanvas(pv.plotvar,pv.plotvar,10,10, 800, 800);
    TPad *d1, *d2;

    c1->Divide(1,2,0,0);
    d1 = (TPad*)c1->GetPad(1);
    d1->SetPad(0.01,0.30,0.95,0.99);
    d2 = (TPad*)c1->GetPad(2);
    d2->SetPad(0.01,0.02,0.95,0.30);

    // Compose the stack

    d1->cd();
    gPad->SetBottomMargin(0.0);
    gPad->SetTopMargin(0.1);
    gPad->SetRightMargin(0.05);
    gPad->SetLeftMargin(0.14);

    Leg->AddEntry(th1tot,  "MC Uncertainty",  "f");

    Leg->SetFillColor(0);

    TH1* th1totempty = new TH1D("th1totempty", "th1totempty", pv.ANBINS, pv.AMINRange, pv.AMAXRange);
    th1data->SetMarkerStyle(20);
    th1data->SetMarkerSize(1.25);
    th1data->SetLineWidth(2);

    th1tot->SetFillStyle(3001);
    th1tot->SetFillColor(1);
    th1tot->SetLineColor(1);
    th1tot->SetMarkerStyle(0);

    char tmpc[100];    sprintf(tmpc,"Events / %.1f GeV",BINWIDTH);
    if (pv.slog==1)    sprintf(tmpc,"Events/ %.1f",BINWIDTH);
    if (pv.slog==2)    sprintf(tmpc,"Events/ %.2f",BINWIDTH);
    if (pv.slog==3)    sprintf(tmpc,"Events/ %.0f GeV",BINWIDTH);
    if (pv.slog==6)    sprintf(tmpc,"Events/ %.1f rad",BINWIDTH);
    th1totempty->SetYTitle(tmpc);
    //  th1totempty->GetYaxis()->SetTitleSize(0.1);
    th1totempty->GetYaxis()->SetTitleOffset(1.2);
    th1totempty->GetYaxis()->SetLabelOffset(0.01);
    //  th1totempty->GetYaxis()->CenterTitle(true);
    th1totempty->GetYaxis()->SetLabelSize(0.04);
    // th1totClone->Draw("e3");   

    th1tot->SetMinimum(0.01);
    int maxbin = th1data->GetMaximumBin();
    float maxval = th1data->GetBinContent(maxbin);
    cout << "maxval " <<maxval <<endl;
//    th1totempty->SetMaximum(2.5*maxval);
    th1totempty->SetMaximum(1.6*maxval);
    th1totempty->SetMinimum(0.01);
    if(pv.slog==1) th1totempty->SetMaximum(1.6*maxval);
    th1data->SetMinimum(0.01);

    // Draw it all

    th1totempty->Draw();
    //th1tot->Draw("e2same");
    th1data->Draw("esame");
    hs->Draw("samehist");

    th1tot->Draw("e2same");

    th1data->Draw("esame");
    cmspre(intLUMIinvpb/1000.0);    
    if (pv.drawleg ==1)  Leg->Draw();  
    // th1data->Draw("Axissame");
    gPad->RedrawAxis();
    d2->cd();

    TH1F    * hhratio    = (TH1F*) th1data->Clone("hhratio")  ;
    hhratio->Sumw2();
    hhratio->SetStats(0);

    gPad->SetLeftMargin(0.14);
    gPad->SetTopMargin(0);
    gPad->SetRightMargin(0.05);
    gPad->SetFrameBorderSize(0);
    gPad->SetBottomMargin(0.3);
    gPad->SetTickx();

    hhratio->SetMarkerSize(1.25);
    //  hhratio->GetYaxis()->SetRangeUser(0.48,1.52);
    hhratio->GetYaxis()->SetRangeUser(0.3,1.7);
    hhratio->GetXaxis()->SetTitle(pv.xlabel);
    hhratio->GetXaxis()->SetTitleOffset(0.9);
    hhratio->GetXaxis()->SetTitleSize(0.15);
    hhratio->GetXaxis()->SetLabelSize(0.15);
    hhratio->GetYaxis()->SetTitleSize(0.1);
    hhratio->GetYaxis()->SetTitleOffset(0.5);
    hhratio->GetYaxis()->CenterTitle(true);
    hhratio->GetYaxis()->SetLabelSize(0.1);
    cout << hhratio->GetNbinsX() << endl;
    cout << th1tot->GetNbinsX() << endl;
    hhratio->Divide(th1tot);
    double binError(0.0), mcbinentry(0.0), mcerror(0.0);
    for(int i=0; i<hhratio->GetNbinsX(); ++i) {
      binError = hhratio->GetBinError(i);
      mcerror = th1tot->GetBinError(i);
      mcbinentry = th1tot->GetBinContent(i);
      if(mcbinentry>0.) mcerror /= mcbinentry;
      else mcerror = 0.0;
      binError = sqrt(binError*binError + mcerror*mcerror);
      hhratio->SetBinError(i, binError);
    }
    TH1D *th1emptyclone = new TH1D("th1emptyclone", "th1emptyclone", pv.ANBINS, pv.AMINRange, pv.AMAXRange);
    th1emptyclone->GetYaxis()->SetRangeUser(0.6,1.3999);
    th1emptyclone->GetXaxis()->SetTitle(pv.xlabel);
    th1emptyclone->GetXaxis()->SetTitleOffset(0.9);
    th1emptyclone->GetXaxis()->SetTitleSize(0.15);
    th1emptyclone->GetXaxis()->SetLabelSize(0.15);
    th1emptyclone->SetYTitle("Ratio Data/MC");
    th1emptyclone->GetYaxis()->SetTitleSize(0.1);
    th1emptyclone->GetXaxis()->SetNdivisions(505);
    th1emptyclone->GetYaxis()->SetNdivisions(505);
    th1emptyclone->GetYaxis()->SetTitleOffset(0.5);
    th1emptyclone->GetYaxis()->CenterTitle(true);
    th1emptyclone->GetYaxis()->SetLabelSize(0.1);
    th1emptyclone->Draw();

    TBox *errbox = new TBox(pv.AMINRange,0.974,pv.AMAXRange,1.026); // lumi systematic uncertainty
    errbox->SetFillColor(kGray);
    errbox->Draw();

#if 0
 	TF1 *f1 = new TF1("f1", "pol1",  pv.AMINRange, pv.AMAXRange);
	//f1->SetParameters(1.0,0.0);
       // f1->SetParameters(1,0.0);
	f1->FixParameter(0,1);
	f1->FixParameter(1,0);
	//cout<<" par1   "f1->GetParameter(0)<<endl;
	//cout<<" par2   "f1->GetParameter(1)<<endl;

        TFitResultPtr r =  hhratio->Fit("f1", "RBS");
	//TFitResultPtr r = hhratio->Fit(myFunc,"S");
       	    r->Print("V");     // print full information of fit including covariance matrix
#endif

    hhratio->Draw("esame");
    TLine *line; line = new TLine(pv.AMINRange,1.0,pv.AMAXRange,1.0);
    line->SetLineStyle(1);
    line->SetLineWidth(1);
    line->SetLineColor(1);
    line->Draw();

    TString outfile = TString("OutDir/")+TString(gSystem->BaseName(cuttablefilename)).ReplaceAll(".txt","")+TString("_")+pv.outfile;

    c1->Print(outfile+".png");
    c1->Print(outfile+".C");
    //gPad->WaitPrimitive();
    c1->Modified();
    c1->Update();
    c1->SaveAs(outfile+".pdf"); 

  } // var loop

  f.Write();

}                                                                // myControlPlots
Beispiel #22
0
TH1* VariableSizeRebin(TH1* inhisto, unsigned int nbinsx,
		       double *xbins, TString axisname="x",
		       TString newhistoname="newhist")
{
  if ( nbinsx == 0 ) {
    cout << "Error! nbinsx must be non-zero." << endl; return 0; }

  if ( inhisto == 0 ) {
    cout << "Error! Input histogram pointer is null." << endl; return 0; }

  if ( axisname == "y"  &&  !inhisto->InheritsFrom("TH2") ) {
    cout << "No y-axis defined for " << inhisto->GetName() << endl; return 0; }

  if ( newhistoname == "" ) {
    cout << "Error! Output histogram name is null."<< endl; return 0; }

  double *edgeArr = new double[nbinsx+2]; // an extra bin for safety

  TAxis *axis = (axisname=="y" ? inhisto->GetYaxis() : inhisto->GetXaxis());

  unsigned int nbins = 0; // number of bins for the new histogram
  unsigned int j = 0; // dummy bin index (to be used as a pointer)

  for ( unsigned int i=0; i<=axis->GetNbins()+1; ++i ) {

    if ( j > nbinsx ) break;

    double ble = axis->GetBinLowEdge(i);

    if ( xbins[j] > ble ) continue;

    edgeArr[nbins] = ble; j++; nbins++;

    if ( xbins[j-1] < ble ) {
      cout << "Warning! Bin edge at " << xbins[j-1] << " does not align with"
	   << " input histo. Realigning at " << ble << ".\n";
      // check if the upcoming bin edges become obsolete after realigning.
      while ( j<=nbinsx && xbins[j] <= ble ) j++;
    }

  }

  // if we finished the loop normally, ie. not 'break'ing out, it must be
  // that the input histogram xrange is shorter than what the new binning
  // tried to get. So handle that.
  if ( j <= nbinsx ) {
    double xmax = axis->GetBinLowEdge(axis->GetNbins()+1);
    if ( xmax>edgeArr[nbins-1] ) {
      edgeArr[nbins]=xmax;
      cout << "Warning! Input histo reached max value of its x-range. "
	   << "Last bin to be closed at " << edgeArr[nbins] << "." << endl;
      nbins++; }
  }

  // we go out of the loop when index j overshoots. So our nbins is
  // always one more than actual number of bins. Fix that.
  nbins--;

  if ( nbinsx != nbins )
    cout << "Warning! nbinsx set to " << nbins
	 << " instead of " << nbinsx << "." << endl;

  //for ( unsigned int i=0; i<=nbins; i++ )
  //  cout << "For bin " << i+1 << "\tlowedge= " << edgeArr[i] << endl;

  // Now generate the new histogram
  TH1 *newhist = 0;

  if ( !inhisto->InheritsFrom("TH2") )
    newhist = inhisto->Rebin(nbins,newhistoname.Data(),edgeArr);

  else {

    // Copy the perpendicular axis as it is.
    TAxis *axisp = (axisname=="y" ? inhisto->GetXaxis() : inhisto->GetYaxis());
    unsigned int nbinsp = axisp->GetNbins();
    double *edgeArrp = new double[nbinsp+1];
    for ( unsigned int i=1; i<=nbinsp+1; ++i )
      edgeArrp[i] = axisp->GetBinLowEdge(i);

    if ( axisname == "y" ) {

      if ( axisp->IsVariableBinSize() )
	newhist = new TH2D(newhistoname, inhisto->GetTitle(),
			   nbinsp, edgeArrp, nbins, edgeArr);
      else
	newhist = new TH2D(newhistoname, inhisto->GetTitle(),
			   nbinsp, edgeArrp[0], edgeArrp[nbinsp+1],
			   nbins, edgeArr);

      if ( axisp->GetLabels() )
	for ( unsigned int i=1; i<=nbinsp; ++i )
	newhist->GetXaxis()->SetBinLabel(i, axisp->GetBinLabel(i));

    }
    else
      // ToDo: Have not yet implemented the above nice stuff for axisname=="x"
      newhist = new TH2D(newhistoname, inhisto->GetTitle(),
			 nbins, edgeArr, nbinsp, edgeArrp);

    newhist->GetYaxis()->SetTitle(inhisto->GetYaxis()->GetTitle());
    newhist->GetXaxis()->SetTitle(inhisto->GetXaxis()->GetTitle());
    bool sw2 = ( inhisto->GetSumw2N() != 0 );

    // Fill the new histogram from the input histogram
    j=0; // reset the dummy bin index
    for ( unsigned int i=0; i<=axis->GetNbins()+1; ++i ) {

      double ble = axis->GetBinLowEdge(i);
      if ( edgeArr[j] == ble ) j++; 

      for ( unsigned int k=0; k<=nbinsp+1; ++k ) {

	int newbin(0), oldbin(0);
	// Equivalent 1D bin number = binx + (fXaxis.GetNbins()+2)*biny
	if ( axisname == "y" ) {
	  newbin = k+j*(nbinsp+2); oldbin = k+i*(nbinsp+2); }
	else {
	  newbin = j+k*(nbins+2); oldbin = i+k*(axis->GetNbins()+2); }

	newhist->SetBinContent( newbin, newhist->GetBinContent(newbin)
				+ inhisto->GetBinContent(oldbin) );
	if ( sw2 )
	  newhist->SetBinError( newbin,
			        sqrt(pow(newhist->GetBinError(newbin),2) +
				     pow(inhisto->GetBinError(oldbin),2)) );
      }
    }

    newhist->SetEntries(inhisto->GetEntries());

  }

  //newhist->Draw();
  delete [] edgeArr;
  return newhist;
}
Beispiel #23
0
Bool_t fitsHere(TLegend *l,Double_t x1, Double_t y1, Double_t x2, Double_t y2)
{
    Bool_t fits = true;
    TList *list = l->GetListOfPrimitives();
    for (Int_t k = 0; list->At(k) != 0 && fits; k++)
    {
        TObject *obj = ((TLegendEntry*)(list->At(k)))->GetObject();
        if (obj == 0) continue;
        TClass *cl = obj->IsA();

        //Histogram, drawn as a histogram
        if (cl->InheritsFrom("TH1") && !cl->InheritsFrom("TH2") && !cl->InheritsFrom("TH3")
         && cl != TProfile::Class() && ((TH1*)obj)->GetMarkerColor() == kWhite)
        {
            Int_t where = 0;
            TH1 *h = (TH1*)obj;
            for (Int_t i = 1; i <= h->GetNbinsX() && fits; i++)
            {
                if (h->GetBinLowEdge(i) + h->GetBinWidth(i) < x1) continue;   //to the left of the legend
                if (h->GetBinLowEdge(i)                     > x2) continue;   //to the right of the legend
                if (h->GetBinContent(i) > y1 && h->GetBinContent(i) < y2) fits = false;   //inside the legend
                if (h->GetBinContent(i) < y1)
                {
                    if (where == 0) where = -1;             //below the legend
                    if (where == 1) fits = false;           //a previous bin was above it so there's a vertical line through it
                }
                if (h->GetBinContent(i) > y2)
                {
                    if (where == 0) where = 1;              //above the legend
                    if (where == -1) fits = false;          //a previous bin was below it so there's a vertical line through it
                }
            }
            continue;
        }
        //Histogram, drawn with Draw("P")
        else if (cl->InheritsFrom("TH1") && !cl->InheritsFrom("TH2") && !cl->InheritsFrom("TH3")
              && cl != TProfile::Class())
        //Probably TProfile would be the same but I haven't tested it
        {
            TH1 *h = (TH1*)obj;
            for (Int_t i = 1; i <= h->GetNbinsX() && fits; i++)
            {
                if (h->GetBinLowEdge(i) + h->GetBinWidth(i)/2 < x1) continue;
                if (h->GetBinLowEdge(i)                       > x2) continue;
                if (h->GetBinContent(i) > y1 && h->GetBinContent(i) < y2) fits = false;
                if (h->GetBinContent(i) + h->GetBinError(i) > y2 && h->GetBinContent(i) - h->GetBinError(i) < y2) fits = false;
                if (h->GetBinContent(i) + h->GetBinError(i) > y1 && h->GetBinContent(i) - h->GetBinError(i) < y1) fits = false;
            }
        }
        else if (cl->InheritsFrom("TF1") && !cl->InheritsFrom("TF2"))
        {
            //TF1 *f = (TF1*)obj;
            //Double_t max = f->GetMaximum(x1,x2);
            //Double_t min = f->GetMinimum(x1,x2);
            //if (min < y2 && max > y1) fits = false;
        }
        // else if (cl->InheritsFrom(...... add more objects here
        else
        {
            cout << "Don't know how to place the legend around objects of type " << obj->ClassName() << "." << endl
                 << "Add this class into placeLegend.C if you want it to work properly." << endl
                 << "The legend will still be placed around any other objects." << endl;
        }
    }
    return fits;
}