Example #1
0
void compnclusts(Int_t run)
{
  TFile* f = new TFile(Form("hodtest_%d.root",run));
  cout << "hcana root file " << Form("hodtest_%d.root",run) << endl;
  TH1F* h = nclust;

  TFile* f1 = new TFile(Form("%d_hbk.root",run));
  cout << "Engine root file " << Form("%d_hbk.root",run) << endl;
  TH1F* h1;
  switch (run) {
  case 50017 :
  //    h1 = h212;   //A+
    break;
  default :
    h1 = h412;   //hnclusters
  }

  TCanvas *c1 = new TCanvas("c1", "Shower Cluster Map", 1000, 667);

  gPad->SetLogy();

  h1->SetFillColor(kGreen);
  h1->SetLineColor(kGreen);
  h1->SetFillStyle(1111);
  h1->Draw();

  h->SetFillColor(kBlue);
  h->SetLineWidth(2);
  h->SetFillStyle(0);
  h->Draw("same");

  TLatex l;
  l.SetTextSize(0.04);
  Float_t maxy = h1->GetBinContent(h1->GetMaximumBin());
  Float_t xmin = h1->GetXaxis()->GetXmin();
  Float_t xmax = h1->GetXaxis()->GetXmax();
  Float_t xt = xmin + 0.67*(xmax-xmin);

  l.SetTextColor(kGreen);
  l.DrawLatex(xt,0.095*maxy,"Engine");
  l.SetTextColor(kBlue);
  l.DrawLatex(xt,0.045*maxy,"hcana");

  // Difference between the histograms.

  TCanvas *c2 = new TCanvas("c2", "Cluster differences", 1000, 667);

  TH1F* dif = h->Clone();

  dif->Add(h,h1,1.,-1.);

  dif->SetTitle("Difference");
  dif->SetFillColor(kRed);
  dif->SetLineColor(kRed);
  dif->SetLineWidth(1);
  dif->SetFillStyle(1111);
  dif->Draw();

}
Example #2
0
//_____________________________________________________________________________
void ProofEventProc::Terminate()
{
   // The Terminate() function is the last function to be called during
   // a query. It always runs on the client, it can be used to present
   // the results graphically or save the results to file.

   // Check ranges
   CheckRanges();

   if (gROOT->IsBatch()) return;
   
   TCanvas* canvas = new TCanvas("event","event",800,10,700,780);
   canvas->Divide(2,2);
   TPad *pad1 = (TPad *) canvas->GetPad(1);
   TPad *pad2 = (TPad *) canvas->GetPad(2);
   TPad *pad3 = (TPad *) canvas->GetPad(3);
   TPad *pad4 = (TPad *) canvas->GetPad(4);

   // The number of tracks
   pad1->cd();
   pad1->SetLogy();
   TH1F *hi = dynamic_cast<TH1F*>(fOutput->FindObject("pz_dist"));
   if (hi) {
      hi->SetFillColor(30);
      hi->SetLineColor(9);
      hi->SetLineWidth(2);
      hi->DrawCopy();
   } else { Warning("Terminate", "no pz dist found"); }

   // The Pt distribution
   pad2->cd();
   pad2->SetLogy();
   TH1F *hf = dynamic_cast<TH1F*>(fOutput->FindObject("pt_dist"));
   if (hf) {
      hf->SetFillColor(30);
      hf->SetLineColor(9);
      hf->SetLineWidth(2);
      hf->DrawCopy();
   } else { Warning("Terminate", "no pt dist found"); }

   // The Px,Py distribution, color surface
   TH2F *h2f = dynamic_cast<TH2F*>(fOutput->FindObject("px_py"));
   if (h2f) {
      // Color surface
      pad3->cd();
      h2f->DrawCopy("SURF1 ");
      // Lego
      pad4->cd();
      h2f->DrawCopy("CONT2COL");
   } else {
      Warning("Terminate", "no px py found");
   }

   // Final update
   canvas->cd();
   canvas->Update();
}
Example #3
0
void dataMC() {

    double xmin  =  60.0;
    double xmax  = 160.0;
    int    nbins = 200;

    TCanvas* c = new TCanvas("c", "c", 600, 600);

    std::string hfile = "/home/avartak/CMS/HMuMu/CMSSW_8_0_26_patch1/src/HMuMuAnalysis/AnalysisStep/trees/GluGlu_HToMuMu_M125_13TeV_powheg_pythia8/trim.root";
    std::string zfile = "/home/avartak/CMS/HMuMu/CMSSW_8_0_26_patch1/src/HMuMuAnalysis/AnalysisStep/trees/DYJetsToLL_M-50_TuneCUETP8M1_13TeV-amcatnloFXFX-pythia8/trim.root";
    std::string tfile = "/home/avartak/CMS/HMuMu/CMSSW_8_0_26_patch1/src/HMuMuAnalysis/AnalysisStep/trees/TTJets_Dilept_TuneCUETP8M2T4_13TeV-amcatnloFXFX-pythia8/trim.root";
    std::string dfile = "/home/avartak/CMS/HMuMu/CMSSW_8_0_26_patch1/src/HMuMuAnalysis/AnalysisStep/trees/SingleMuon/trim.root";

    TFile* fileh = new TFile(hfile.c_str());
    TFile* filez = new TFile(zfile.c_str());
    TFile* filet = new TFile(tfile.c_str());
    TFile* filed = new TFile(dfile.c_str());

    TH1F* histh = new TH1F("histh", "", nbins, xmin, xmax);
    TH1F* histz = new TH1F("histz", "", nbins, xmin, xmax);
    TH1F* histt = new TH1F("histt", "", nbins, xmin, xmax);
    TH1F* histd = new TH1F("histd", "", nbins, xmin, xmax);

    TTree* treeh = (TTree*)fileh->Get("tree");
    TTree* treez = (TTree*)filez->Get("tree");
    TTree* treet = (TTree*)filet->Get("tree");
    TTree* treed = (TTree*)filed->Get("tree");

    treez->Draw("mass>>histz", "(cat > 0) * wgt");
    treet->Draw("mass>>histt", "(cat > 0) * wgt");
    treed->Draw("mass>>histd", "(cat > 0 && (mass < 120 || mass > 130))");

    histz->SetFillColor(kCyan+1);
    histt->SetFillColor(kOrange+1);

    histz->SetLineWidth(2);
    histt->SetLineWidth(2);
    histh->SetLineWidth(2);

    histz->Add(histt);

    histz->Draw("HIST");
    histt->Draw("HIST SAME");
    histd->Draw("PE SAME");

    c->RedrawAxis();

}
Example #4
0
TH1F * DrawOverflow(TH1F *h)
{
      // This function paint the histogram h with an extra bin for overflows
   UInt_t nx    = h->GetNbinsX()+1;
   Double_t *xbins= new Double_t[nx+1];
   for (UInt_t i=0;i<nx;i++)
     xbins[i]=h->GetBinLowEdge(i+1);
   xbins[nx]=xbins[nx-1]+h->GetBinWidth(nx);
   char *tempName= new char[strlen(h->GetName())+10];
   sprintf(tempName,"%swtOverFlow",h->GetName());
   // Book a temporary histogram having ab extra bin for overflows
   TH1F *htmp = new TH1F(tempName, h->GetTitle(), nx, xbins);
   // Reset the axis labels
   htmp->SetXTitle(h->GetXaxis()->GetTitle());
   htmp->SetYTitle(h->GetYaxis()->GetTitle());
   // Fill the new hitogram including the extra bin for overflows
   for (UInt_t i=1; i<=nx; i++)
     htmp->Fill(htmp->GetBinCenter(i), h->GetBinContent(i));
   // Fill the underflows
   htmp->Fill(h->GetBinLowEdge(1)-1, h->GetBinContent(0));
   // Restore the number of entries
   htmp->SetEntries(h->GetEntries());
   // FillStyle and color
   htmp->SetFillStyle(h->GetFillStyle());
   htmp->SetFillColor(h->GetFillColor());
   return htmp;
}
Example #5
0
void transp()
{
   //1. Try to find free indices for our custom colors.
   //We can use hard-coded indices like 1001, 1002, 1003, ... but
   //I prefer to find free indices in a ROOT's color table
   //to avoid possible conflicts with other tutorials.
   Int_t indices[2] = {};
   if (ROOT::GLTutorials::FindFreeCustomColorIndices(indices) != 2) {
      Error("transp", "failed to create new custom colors");
      return;
   }
   
   //2. Now that we have indices, create our custom colors.
   const Int_t redIndex = indices[0], greeIndex = indices[1];
   
   new TColor(redIndex, 1., 0., 0., "red", 0.85);
   new TColor(greeIndex, 0., 1., 0., "green", 0.5);

   gStyle->SetCanvasPreferGL(kTRUE);
   TCanvas * const cnv = new TCanvas("trasnparency", "transparency demo", 600, 400);

   TH1F * hist = new TH1F("a5", "b5", 10, -2., 3.);
   TH1F * hist2 = new TH1F("c6", "d6", 10, -3., 3.);
   hist->FillRandom("landau", 100000);
   hist2->FillRandom("gaus", 100000);

   hist->SetFillColor(redIndex);
   hist2->SetFillColor(greeIndex);
   
   cnv->cd();
   hist2->Draw();
   hist->Draw("SAME");
}
Example #6
0
// 1-D histograms with alphanumeric labels
// author; Rene Brun
TCanvas *hlabels1()
{
   const Int_t nx = 20;
   const char *people[nx] = {"Jean","Pierre","Marie","Odile","Sebastien",
      "Fons","Rene","Nicolas","Xavier","Greg","Bjarne","Anton","Otto",
      "Eddy","Peter","Pasha","Philippe","Suzanne","Jeff","Valery"};
   TCanvas *c1 = new TCanvas("c1","demo bin labels",10,10,900,500);
   c1->SetGrid();
   c1->SetTopMargin(0.15);
   TH1F *h = new TH1F("h","test",3,0,3);
   h->SetStats(0);
   h->SetFillColor(38);
   h->SetCanExtend(TH1::kAllAxes);
   for (Int_t i=0;i<5000;i++) {
      Int_t r = gRandom->Rndm()*20;
      h->Fill(people[r],1);
   }
   h->LabelsDeflate();
   h->Draw();
   TPaveText *pt = new TPaveText(0.7,0.85,0.98,0.98,"brNDC");
   pt->SetFillColor(18);
   pt->SetTextAlign(12);
   pt->AddText("Use the axis Context Menu LabelsOption");
   pt->AddText(" \"a\"   to sort by alphabetic order");
   pt->AddText(" \">\"   to sort by decreasing values");
   pt->AddText(" \"<\"   to sort by increasing values");
   pt->Draw();
   return c1;
}
Example #7
0
File: labels1.C Project: Y--/root
void labels1()
{
   Int_t i;
   const Int_t nx = 20;
   const char *people[nx] = {"Jean","Pierre","Marie","Odile",
      "Sebastien","Fons","Rene","Nicolas","Xavier","Greg",
      "Bjarne","Anton","Otto","Eddy","Peter","Pasha",
      "Philippe","Suzanne","Jeff","Valery"};
   TCanvas *c1 = new TCanvas("c1","demo bin labels",10,10,900,500);
   c1->SetGrid();
   c1->SetBottomMargin(0.15);
   TH1F *h = new TH1F("h","test",nx,0,nx);
   h->SetFillColor(38);
   for (i=0;i<5000;i++) h->Fill(gRandom->Gaus(0.5*nx,0.2*nx));
   h->SetStats(0);
   for (i=1;i<=nx;i++) h->GetXaxis()->SetBinLabel(i,people[i-1]);
   h->Draw();
   TPaveText *pt = new TPaveText(0.6,0.7,0.98,0.98,"brNDC");
   pt->SetFillColor(18);
   pt->SetTextAlign(12);
   pt->AddText("Use the axis Context Menu LabelsOption");
   pt->AddText(" \"a\"   to sort by alphabetic order");
   pt->AddText(" \">\"   to sort by decreasing values");
   pt->AddText(" \"<\"   to sort by increasing values");
   pt->Draw();
}
Example #8
0
void Difference(TH1* iH0,TH1 *iH1) {
  std::string lName = std::string(iH0->GetName());
  //TH1F *lHDiff  = new TH1F((lName+"Diff").c_str(),(lName+"Diff").c_str(),50,0,300); lHDiff->Sumw2();
  TH1F *lHDiff  = new TH1F((lName+"Diff").c_str(),(lName+"Diff").c_str(),iH0->GetNbinsX(),iH0->GetXaxis()->GetXmin(),iH0->GetXaxis()->GetXmax()); lHDiff->Sumw2();
  lHDiff->SetFillColor(kViolet); lHDiff->SetFillStyle(1001); lHDiff->SetLineWidth(1);
  TH1F *lXHDiff1 = new TH1F((lName+"XDiff1").c_str(),(lName+"XDiff1").c_str(),iH0->GetNbinsX(),iH0->GetXaxis()->GetXmin(),iH0->GetXaxis()->GetXmax());
  int i1 = 0;
  lXHDiff1->SetLineStyle(2); lXHDiff1->SetLineWidth(2); lXHDiff1->SetLineColor(kRed);

  lHDiff->GetYaxis()->SetRangeUser(0,2);
  lHDiff->GetYaxis()->SetTitleOffset(0.6);
  lHDiff->GetYaxis()->SetTitleSize(0.08);
  lHDiff->GetYaxis()->SetLabelSize(0.08);
  lHDiff->GetYaxis()->CenterTitle();
  lHDiff->GetXaxis()->SetTitleOffset(1.2);
  lHDiff->GetXaxis()->SetTitleSize(0.10);
  lHDiff->GetXaxis()->SetLabelSize(0.08);
  lHDiff->GetXaxis()->SetTitle("#slash{E}_{T} [GeV]");
  //lHDiff->GetXaxis()->CenterTitle();
  //lHDiff->GetYaxis()->SetTitle(YLabel);

  for(int i0 = 0; i0 < lHDiff->GetNbinsX()+1; i0++) {
    double lXCenter = lHDiff->GetBinCenter(i0);
    double lXVal     = iH0   ->GetBinContent(i0);
    lXHDiff1->SetBinContent(i0, 1.0);
    while(iH1->GetBinCenter(i1) < lXCenter) {i1++;}
    if(iH1->GetBinContent(i0) > 0) lHDiff->SetBinContent(i0,(lXVal-iH1->GetBinContent(i0))/(iH1->GetBinContent(i0)));
    if(iH1->GetBinContent(i0) > 0) lHDiff->SetBinError  (i0,iH0->GetBinError(i0)/(iH1->GetBinContent(i0)));
  }
  lHDiff->SetMarkerStyle(kFullCircle); lHDiff->SetLineColor(kBlack); lHDiff->SetMarkerColor(kBlack);
  lHDiff->Draw("E1");
  lXHDiff1->Draw("hist sames");
}
void GetTreeSize(TString FileName, TString TreeName)
{
  TFile *inf          = TFile::Open(FileName);
  TTree *tr           = (TTree*)inf->Get(TreeName);
  TObjArray *branches = (TObjArray*)tr->GetListOfBranches();
  int size(0);
  cout.setf(ios::right);
  int N(branches->GetEntries());
  TH1F *hSize = new TH1F("size","size",N,0,N);
  for(int ib=0;ib<N;ib++) {
    TString name(branches->At(ib)->GetName());
    TBranch *br = (TBranch*)tr->GetBranch(name);
    hSize->Fill(name,br->GetZipBytes()/1e+3); 
    size += br->GetZipBytes();
  } 
  cout<<"Total size: "<<size<<endl;
  for(int ib=0;ib<N;ib++) {
    TString name(branches->At(ib)->GetName());
    TBranch *br = (TBranch*)tr->GetBranch(name);
    float percent = TMath::Ceil(1000*float(br->GetZipBytes())/float(size))/10;
    cout<<ib<<setw(20)<<name<<setw(15)<<br->GetZipBytes()<<" "<<percent<<"%"<<endl;
  }

  TCanvas *can = new TCanvas("TreeSize","TreeSize",1000,400);
  hSize->GetXaxis()->SetTitle("Branch Name");
  hSize->GetXaxis()->SetLabelSize(0.04);
  hSize->GetYaxis()->SetTitle("Size (KB)");
  hSize->SetFillColor(kGray);
  hSize->Draw();
}
Example #10
0
void SetSignalStyle(TH1F & ele, unsigned color) {
  ele.SetFillStyle(1001);
  ele.SetLineStyle(11);
  ele.SetFillColor(0);
  ele.SetLineColor(color);
  ele.SetLineWidth(2);
  return;
}
Example #11
0
void PlotHistsNhitsPerModule(TFile* f, TTree* tr, TString strMillepedeRes, TString strOutdir)
{
  TString canvName="c_";
  canvName+=strMillepedeRes;
  canvName+="_";
  canvName+=StrPlotType(NHITS);
  canvName.ReplaceAll(".res","");


  //enum {PXB,PXF,TIB,TID,TOB,TEC};
  int colors[6]={1,2,3,4,6,7};
//  TString labels[6]={"PXB","PXF","TIB","TID","TOB","TEC"};

  f->cd();
  TCanvas* canv = new TCanvas(canvName,canvName,600,600);
  canv->SetLogx();
  canv->SetLogy();

  for (int ind=1; ind<=1; ind++){
    TString strHist = "hNhits_";
    strHist+=StrPar(ind);
    TString strCut="label<700000 && ((label%20-1)%9+1)==";
    strCut+=ind;
    TStyle style; 
    style.SetTitleFontSize(0.2);
    THStack *hSt = new THStack("hNhits","# of derivatives (~tracks or hits) per module");
    TLegend *leg = new TLegend(0.75,0.65,0.95,0.95);
    for (int inv=0; inv<6; inv++){
      std::cout<<"- - - - - -"<<std::endl;
      std::cout<<subdLabels[inv]<<":"<<std::endl;
      std::cout<<StrCutSubd(inv)<<": "<<tr->GetEntries(StrCutSubd(inv))<<" parameters"<<std::endl;
      TString strHist1=strHist;
      strHist1+=ind;
      strHist1+=inv;
      TH1F* hValInt = new TH1F(strHist1,strHist1,300,10,15000);  
      TString strCut1 = strCut+TString(" && ")+StrCutSubd(inv);
      tr->Draw(TString("Nhits>>")+strHist1,strCut1,"goff");
      std::cout<<"# hits = "<<(int)hValInt->GetMean()<<"+-"<<(int)hValInt->GetRMS()<<std::endl;
      hValInt->SetLineColor(1);
      hValInt->SetFillColor(colors[inv]);
      hValInt->SetLineWidth(2);
      hSt->Add(hValInt);
      leg->AddEntry(hValInt,subdLabels[inv],"f");
      leg->SetFillColor(0);
    }
    hSt->Draw();
    leg->Draw("same");
    
  }//end of loop over ind

  canvName+=".png";
  TString saveName=strOutdir+canvName;
  canv->SaveAs(saveName);
  saveName.ReplaceAll(".png",".pdf");
  canv->SaveAs(saveName);
}//end of PlotHistsNhitsPerModule
Example #12
0
void SetDataStyle(TH1F & ele) {
  ele.SetMarkerColor(1);
  ele.SetLineColor(1);
  ele.SetFillColor(1);
  ele.SetFillStyle(0);
  ele.SetLineWidth(2);
  ele.SetMarkerStyle(20);
  ele.SetMarkerSize(1.1);
  return;
}
Example #13
0
TCanvas * plot (TH1F* histoDataIn, TString legendData, TH1F* histoSimulationIn, TString legendSimulation,
                TString & canvasName, Float_t maximum = 0.15, TString xAxisTitle = "#eta",
                TString yAxisTitle = "Number of Clusters", TString error = "", bool useLegend = true,
                TString text = "", Float_t textX = 0.7, Float_t textY = 0.4, Float_t rebin = 0 ) {

  TH1F * histoData = (TH1F*)histoDataIn->Clone();
  TH1F * histoSimulation = (TH1F*)histoSimulationIn->Clone();

  // histoData->Sumw2();
  histoData->Scale(1/(histoData->Integral()));
  histoSimulation->Scale(1/(histoSimulation->Integral()));

  // Create also the legend and add the histograms
  TLegend * legend = new TLegend( 0.55, 0.65, 0.76, 0.82 );
  legend->AddEntry( histoData, xAxisTitle );
  legend->AddEntry( histoSimulation, yAxisTitle, "F" );

  cout << "histoData = " << histoData << endl;
  cout << "histoSimulation = " << histoSimulation << endl;

  TCanvas * c = new TCanvas( canvasName, canvasName, 1000, 800 );
  c->Draw();

  histoSimulation->SetMaximum(maximum);

  histoSimulation->SetFillColor(kRed);
  // histoSimulation->SetLineWidth(0);
  histoSimulation->SetLineColor(kRed);
  histoSimulation->SetXTitle(xAxisTitle);
  histoSimulation->SetYTitle(yAxisTitle);
  histoSimulation->SetTitleOffset(1.6,"Y");
  histoSimulation->SetTitle();

  histoData->SetLineStyle(1);
  histoData->SetLineWidth(2.5);

  histoSimulation->Draw();
  histoData->Draw("same");

  legend->SetFillColor(kWhite);
  if (useLegend) legend->Draw("same");

  if ( text != "" ) {
    TPaveText * pt = new TPaveText(textX, textY, textX+0.2, textY+0.17, "NDC" ); // "NDC" option sets coords relative to pad dimensions
    pt->SetFillColor(0); // text is black on white
    pt->SetTextSize(0.08); 
    pt->SetBorderSize(0);
    pt->SetTextAlign(12);
    pt->AddText(text);
    pt->Draw("same");       //to draw your text object
  }

  return c;
};
Example #14
0
void superimposeHistos()
{
  TFile* bFile = TFile::Open("Electron_In_Jets_900GeV_bJets.root");
  TFile* cFile = TFile::Open("Electron_In_Jets_900GeV_cJets.root");
  TFile* udsgFile = TFile::Open("Electron_In_Jets_900GeV_udsgJets.root");
  
  TIter next(bFile->GetListOfKeys());
  TFile* newFile = new TFile("testFile.root", "RECREATE");
  while(TKey* key = (TKey*)next())
  {
    TH1F* bHist = (TH1F*)bFile->Get(key->GetName());
    bHist->SetFillColor(2);
    
    TH1F* cHist = (TH1F*)cFile->Get(key->GetName());
    cHist->SetFillColor(3);
    
    TH1F* udsgHist = (TH1F*)udsgFile->Get(key->GetName());
    udsgHist->SetFillColor(4);
    
    THStack* stack = new THStack(bHist->GetName(), bHist->GetTitle());
    stack->Add(udsgHist, "hist ][");
    stack->Add(cHist, "hist ][");
    stack->Add(bHist, "hist ][");
    
    TLegend* legend = new TLegend(0.5, 0.68, 0.88, 0.88);
    legend->AddEntry(bHist, "b-Jets");
    legend->AddEntry(cHist, "c-Jets");
    legend->AddEntry(udsgHist, "udsg-Jets");
    
    TCanvas* canvas = new TCanvas(bHist->GetName());
    stack->Draw();
    stack->GetXaxis()->SetTitle(bHist->GetXaxis()->GetTitle());
    legend->Draw();
    canvas->Write(canvas->GetName());
  }
  
  newFile->Close();
  bFile->Close();
  cFile->Close();
  udsgFile->Close();
}
Example #15
0
TH1F * AddHist(THStack *stack, TLegend * leg,  TFile *f, const char * name, const char * sample, const char * legsamp, int style, int color){
   char full_name[200];
   sprintf(full_name, "%s_%s", name, sample);
   TH1F * h = (TH1F *)f->Get(full_name);
   if (h){
      h->SetFillStyle(style);
      h->SetLineColor(color);
      h->SetFillColor(color);
      if (leg) { leg->AddEntry(h, legsamp, "f"); }
      stack->Add(h);
   }
   return h;
}
void performClosure(RooRealVar *mass, RooAbsPdf *pdf, RooDataSet *data, string closurename, double wmin=110., double wmax=130., double slow=110., double shigh=130., double step=0.002) {
  
  // plot to perform closure test
  cout << "Performing closure test..." << endl; 
  double nbins = (wmax-wmin)/step;
  TH1F *h = new TH1F("h","h",int(floor(nbins+0.5)),wmin,wmax);
  if (data){
    pdf->fillHistogram(h,RooArgList(*mass),data->sumEntries());
    h->Scale(2*h->GetNbinsX()/double(binning_));
  }
  else {
    pdf->fillHistogram(h,RooArgList(*mass));
  }
  int binLow = h->FindBin(slow);
  int binHigh = h->FindBin(shigh)-1;
  TH1F *copy = new TH1F("copy","c",binHigh-binLow,h->GetBinLowEdge(binLow),h->GetBinLowEdge(binHigh+1));
  for (int b=0; b<copy->GetNbinsX(); b++) copy->SetBinContent(b+1,h->GetBinContent(b+1+binLow));
  double areaCov = 100*h->Integral(binLow,binHigh)/h->Integral();
 
  // style
  h->SetLineColor(kBlue);
  h->SetLineWidth(3);
  h->SetLineStyle(7);
  copy->SetLineWidth(3);
  copy->SetFillColor(kGray);
  
  TCanvas *c = new TCanvas();
  if (data){
    RooPlot *plot = mass->frame(Bins(binning_),Range("higgsRange"));
    plot->addTH1(h,"hist");
    plot->addTH1(copy,"same f");
    if (data) data->plotOn(plot);
    pdf->plotOn(plot,Normalization(h->Integral(),RooAbsReal::NumEvent),NormRange("higgsRange"),Range("higgsRange"),LineWidth(1),LineColor(kRed),LineStyle(kDashed));
    plot->Draw();
    c->Print(closurename.c_str());
  }
  else {
    RooPlot *plot = mass->frame(Bins(binning_),Range("higgsRange"));
    h->Scale(plot->getFitRangeBinW()/h->GetBinWidth(1));
    copy->Scale(plot->getFitRangeBinW()/h->GetBinWidth(1));
    pdf->plotOn(plot,LineColor(kRed),LineWidth(3));
    plot->Draw();
    h->Draw("hist same");
    copy->Draw("same f");
    c->Print(closurename.c_str());
  }
  cout << "IntH: [" << h->GetBinLowEdge(binLow) << "-" << h->GetBinLowEdge(binHigh+1) << "] Area = " << areaCov << endl;
  delete c;
  delete copy;
  delete h;
}
Example #17
0
TH1F * GetSigHist(TFile *f, const char * name, const char * tag, int color, int lstyle, TLegend * leg, const char * legtag){
   char full_name[200];

   sprintf(full_name, "%s_%s", name, tag);
   TH1F * h = (TH1F *)f->Get(full_name);

   h->SetFillStyle(0);
   h->SetFillColor(color);
   h->SetLineColor(color);   
   h->SetLineStyle(lstyle);   
   if (leg) { leg->AddEntry(h, legtag, "l"); }  

   return h;
}
Example #18
0
void plot(){

TFile* f1 = TFile::Open("prunedmass_cv.root");
TFile* f2 = TFile::Open("prunedmass_up.root");
TFile* f3 = TFile::Open("prunedmass_down.root");

TH1F* cv = (TH1F*)f1->Get("AK8jetPrunedMass");
TH1F* up = (TH1F*)f2->Get("AK8jetPrunedMass");
TH1F* down = (TH1F*)f3->Get("AK8jetPrunedMass");

TLegend* l = new TLegend(0.6645729,0.701049,0.8743719,0.8706294,"","NDC");
l->SetLineWidth(2);
l->SetBorderSize(0);
l->SetFillColor(0);
l->SetFillStyle(0);
l->SetTextFont(42);
l->SetTextSize(0.035);
l->SetTextAlign(12);

cv->SetLineColor(kRed);
cv->SetLineWidth(2);
up->SetLineColor(kBlack);
up->SetFillColor(kBlack);
up->SetFillStyle(3018);
down->SetLineColor(kBlue);
down->SetFillColor(kBlue);

l->AddEntry(cv,"central value","L");
l->AddEntry(up,"scale up","F");
l->AddEntry(down,"scale down","F");

down->Draw("HIST");
cv->Draw("HISTsame");
up->Draw("HISTsame");
l->Draw();

}
Example #19
0
void addPlot(TObject* obj, TString title, int color, THStack* hStack, bool doFillColor)
{
  TH1F* h = (TH1F*)obj;
  h->SetTitle(title);
  if ( doFillColor )
  {
    h->SetFillColor(color);
    //h->SetLineWidth(2);
  }
  else
  {
    h->SetLineColor(color);
    h->SetLineWidth(2);
  }
  hStack->Add(h);
}
Example #20
0
TH1F* newDumHistForLegend(const Plot_t* hist) {
   // caller is responsible for deleting the hist
   TH1F* h = 0;
   if (hist!=0) {
      TString hn(Form("%s_leg%s",hist->GetName(),
                      (gPad!=0) ? gPad->GetName() : ""));
      h = new TH1F(hn.Data(), "", 1, 0, 1);
      h->SetFillColor(hist->GetLineColor());
      h->SetLineColor(kWhite);
      h->SetMarkerColor(kWhite);
      h->SetMarkerStyle(hist->GetMarkerStyle());
      h->SetMarkerSize(1);
      h->SetBit(TObject::kCanDelete);
   }
   return h;
}
Example #21
0
// Add a histogram to top of a stack
double addHistogram(const TString & fileName, const TString & histoName, const int color, THStack & hs,
    const TString & leg, TLegend *legend, const float lumi, int minIntegral=1, int maxIntegral=-1 )
{
  TFile * inputFile= new TFile (fileName, "READ");
  TH1F * histo = (TH1F*)inputFile->Get(histoName);
  TH1::SetDefaultSumw2();
  histo->Scale(lumi);

  histo->SetFillColor(color);
  hs.Add(histo);

  legend->AddEntry(histo, leg, "f");

  if ( maxIntegral==-1 ) maxIntegral=histo->GetNbinsX();

  return histo->Integral( minIntegral, maxIntegral );
}
Example #22
0
void plotMttResolution() {

  setTDRStyle();

  TCanvas *c = new TCanvas("c", "c", 800, 800);

  TH1F *mtt = (TH1F*) _file0->Get("mtt_resolution_mva");
  mtt->SetTitle("");
  mtt->SetName("m_{t#bar{t}}");
  mtt->GetXaxis()->SetTitle("m_{t#bar{t}} - m_{t#bar{t}}^{gen} (GeV)");
  mtt->SetLineColor(TColor::GetColor("#542437"));
  mtt->SetLineColor(TColor::GetColor("#8A9B0F"));
  mtt->SetLineColor(TColor::GetColor("#C02942"));
  mtt->SetFillColor(mtt->GetLineColor());
  mtt->SetFillStyle(3004);
  mtt->GetXaxis()->SetTitleOffset(1.2);

  TF1 *voigt = new TF1("voigt", "gaus", -100, 100);
	voigt->SetParName(0, "amp");
	voigt->SetParName(2, "mean");
	voigt->SetParName(1, "sigma");

  voigt->SetParameter(0, mtt->GetMaximum());
	voigt->SetParameter(2, 0);
	voigt->SetParameter(1, 100);

  mtt->Fit(voigt, "RVN");

  voigt->SetLineColor(TColor::GetColor("#8A9B0F"));
  voigt->SetLineWidth(2);

  mtt->Draw();
  voigt->Draw("same");

  TLatex* latex = new TLatex();
  latex->SetTextFont(42);
  latex->SetTextSize(0.033);
  latex->DrawLatexNDC(0.25, 0.84, TString::Format("mean = %.2f", voigt->GetParameter(1)));
  latex->DrawLatexNDC(0.25, 0.8, TString::Format("#sigma = %.2f", voigt->GetParameter(2)));

  gPad->Modified();
  gPad->Update();

  c->Print("mtt_resolution.pdf");
}
Example #23
0
void comphh(Int_t run, TH1F* h1, TH1F* h2)
{
  TFile* f = new TFile(Form("hodtest_%d.root",run));
  cout << "hcana root file " << Form("hodtest_%d.root",run) << endl;

  TCanvas *c1 = new TCanvas("c1", "h1 vs h2", 1000, 667); 

  //  gPad->SetLogy();

  h1->SetFillColor(kGreen);
  h1->SetLineColor(kGreen);
  h1->Draw();

  h2->SetLineColor(kBlue);
  h2->SetFillStyle(0);
  h2->SetLineWidth(2);
  h2->Draw("same");

  TLatex l;
  l.SetTextSize(0.04);
  Float_t maxy = h1->GetBinContent(h1->GetMaximumBin());
  Float_t xmin = h1->GetXaxis()->GetXmin();
  Float_t xmax = h1->GetXaxis()->GetXmax();
  Float_t xt = xmin + 0.75*(xmax-xmin);

  l.SetTextColor(kGreen);
  l.DrawLatex(xt,0.65*maxy,"h1");
  l.SetTextColor(kBlue);
  l.DrawLatex(xt,0.75*maxy,"h2");
    
  // Difference between the histograms.

  TCanvas *c2 = new TCanvas("c2", "Epr differences", 1000, 667); 

  TH1F* dif = h2->Clone();

  dif->Add(h2,h1,1.,-1.);

  dif->SetTitle("Difference");
  dif->SetFillColor(kRed);
  dif->SetLineColor(kRed);
  dif->SetLineWidth(1);
  dif->SetFillStyle(1111);
  dif->Draw();
} 
Example #24
0
void tree2ar()
{
   //read the Tree generated by tree2w and fill one histogram
   //we are only interested by the destep branch.
     
   //note that we use "new" to create the TFile and TTree objects !
   //because we want to keep these objects alive when we leave 
   //this function.
   TFile *f = new TFile("tree2.root");
   TTree *t2 = (TTree*)f->Get("t2");
   Gctrak *gstep = 0;
   t2->SetBranchAddress("track",&gstep);
   TBranch *b_destep = t2->GetBranch("destep");
   
   //create one histogram
   TH1F *hdestep   = new TH1F("hdestep","destep in Mev",100,1e-5,3e-5);
   
   //read only the destep branch for all entries
   Long64_t nentries = t2->GetEntries();
   for (Long64_t i=0;i<nentries;i++) {
      b_destep->GetEntry(i); 
      hdestep->Fill(gstep->destep);
   }
  
   //we do not close the file. 
   //We want to keep the generated histograms
   //We fill a 3-d scatter plot with the particle step coordinates
   TCanvas *c1 = new TCanvas("c1","c1",600,800);
   c1->SetFillColor(42);
   c1->Divide(1,2);
   c1->cd(1);
   hdestep->SetFillColor(45);
   hdestep->Fit("gaus");
   c1->cd(2);
   gPad->SetFillColor(37);
   t2->SetMarkerColor(kRed);
   t2->Draw("vect[0]:vect[1]:vect[2]");
   if (gROOT->IsBatch()) return;
   
   // invoke the x3d viewer
   gPad->GetViewer3D("x3d");
}   
Example #25
0
void sigHist(TChain & EventsVBF, TChain & EventsGF, string variable, string title, int nBins, float min, float max, float GF, float VBF ){

  TCanvas c("");
  TH1F *hVBF = new TH1F("hVBF","hVBF", nBins, min, max);
  TH1F *hGF = new TH1F("hGF","hGF", nBins, min, max);
  EventsVBF.Project("hVBF",variable.c_str() );
  EventsGF.Project("hGF",variable.c_str() );
  //hVBF->Draw();
  EventsVBF.Draw("h.mass()");
  TH1F * h = new TH1F(title.c_str(),title.c_str(), nBins, min,max);

  
  h->Add(hVBF,hGF,VBF,GF);

    h->SetLineColor(kBlue+1);
    h->SetFillColor(kAzure+7);

  //h->SetLineColor(kMagenta+3);
  //h->SetFillColor(kMagenta-3);

  //    h->SetLineColor(kTeal+3);
  //  h->SetFillColor(kTeal+2);

  //  h->SetLineColor(kOrange+7);
  //  h->SetFillColor(kYellow-9);

  h->SetMarkerStyle(0);
  h->SetTitle( ("H350, "+title).c_str() );
  h->SetXTitle("m_{H} (GeV/c^{2})");
  //h->hGF->GetXaxis()->SeXmin();
  //h->Scale(1/h->GetEntries());
  h->Draw("HIST");

  h->Write();
  //c.SaveAs( (title+".eps").c_str() );
  delete hVBF;
  delete hGF;
  delete h;

}
Example #26
0
void transp()
{
   //1. Try to find free indices for our custom colors.
   //We can use hard-coded indices like 1001, 1002, 1003, ... but
   //I prefer to find free indices in a ROOT's color table
   //to avoid possible conflicts with other tutorials.
   Int_t indices[2] = {};
   if (ROOT::CocoaTutorials::FindFreeCustomColorIndices(indices) != 2) {
      Error("transp", "failed to create new custom colors");
      return;
   }
   
   //2. Now that we have indices, create our custom colors.
   const Int_t redIndex = indices[0], greeIndex = indices[1];
   
   new TColor(redIndex, 1., 0., 0., "red", 0.85);
   new TColor(greeIndex, 0., 1., 0., "green", 0.5);

   //3. Test that back-end is TGCocoa.
   TCanvas * const cnv = new TCanvas("trasnparency", "transparency demo", 600, 400);
   //After we created a canvas, gVirtualX in principle should be initialized
   //and we can check its type:
   if (gVirtualX && !gVirtualX->InheritsFrom("TGCocoa")) {
      Warning("transp", "You can see the transparency ONLY in a pdf or png output (\"File\"->\"Save As\" ->...)\n"
                        "To have transparency in a canvas graphics, you need MacOSX version with cocoa enabled");
   }

   TH1F * hist = new TH1F("a5", "b5", 10, -2., 3.);
   TH1F * hist2 = new TH1F("c6", "d6", 10, -3., 3.);
   hist->FillRandom("landau", 100000);
   hist2->FillRandom("gaus", 100000);

   hist->SetFillColor(redIndex);
   hist2->SetFillColor(greeIndex);
   
   cnv->cd();
   hist2->Draw();
   hist->Draw("SAME");
}
Example #27
0
TCanvas* plotting36GS( bool logScale=false ) 
{

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

      }

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


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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

  roohist = new RooHist((*hdata));

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

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

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

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

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

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

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

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

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

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

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

  h_->Draw();

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

  totalHisto->Draw("same");

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

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

  // redraw axis
  p_->RedrawAxis();

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

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

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

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

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

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

  p_->Draw();

  p_->cd();

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

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

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

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

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

  p_->RedrawAxis();

  c_->cd();

  return c_;
}
Example #28
0
void plotComparison( TH1F* h_dt , TH1F* h_mc , TH1F *h_extra, char* label, bool dolog, bool drawbkg) {

  TPad* fullpad = new TPad();
  TPad* plotpad = new TPad();
  TPad* respad  = new TPad();
  fullpad = new TPad("fullpad","fullpad",0,0,1,1);
  fullpad->Draw();
  fullpad->cd();
  plotpad = new TPad("plotpad","plotpad",0,0,1,0.8);
  plotpad->Draw();
  plotpad->cd();
  if (dolog) plotpad->SetLogy();

  h_dt->GetYaxis()->SetTitle("Entries");
  h_dt->GetXaxis()->SetTitle(Form("%s", label));
  h_dt->GetYaxis()->SetTitleSize(0.05);
  h_dt->GetXaxis()->SetTitleSize(0.05);
  h_dt->GetYaxis()->SetTitleOffset(1.5);
  h_dt->GetXaxis()->SetTitleOffset(1.3);
  if (!dolog) h_dt->GetYaxis()->SetRangeUser(0., 1.4*h_dt->GetMaximum());
  h_dt->SetLineColor(kBlack);
  h_dt->SetMarkerColor(kBlack);
  h_mc->SetLineColor(kBlue);
  h_mc->SetMarkerColor(kBlue);
  h_extra->SetLineColor(kRed);
  h_extra->SetLineWidth(2);
  h_mc->SetLineWidth(2);
  h_dt->Draw();
  h_mc->Draw("HISTSAME");
  if (drawbkg) h_extra->Draw("HISTSAME");
  h_dt->Draw("ESAME");

  TLegend *legComp = new TLegend( 0.653, 0.663, 0.944, 0.870);
  legComp->AddEntry(h_dt, "Data", "lp");
  legComp->AddEntry(h_mc, "MC", "l");
  if (drawbkg) legComp->AddEntry(h_extra, "MC Bkg", "l");
  legComp->SetFillColor(0);
  legComp->SetBorderSize(0);
  legComp->Draw();
  
  TLatex *text = new TLatex();
  text->SetNDC();
  text->SetTextSize(0.04);
  //  float xtex = 0.65;
  //  text->DrawLatex(xtex,0.88,"1 lepton + jets Sample");
  
  fullpad->cd();
  
  respad = new TPad("respad","respad",0,0.8,1,1);
  respad->Draw();
  respad->cd();
  
  //gPad->SetGridy();
  
  TH1F* ratio = (TH1F*) h_dt->Clone("ratio");
  ratio->Divide(h_mc);

  ratio->GetYaxis()->SetTitleOffset(0.3);
  ratio->GetYaxis()->SetTitleSize(0.2);
  ratio->GetYaxis()->SetNdivisions(5);
  ratio->GetYaxis()->SetLabelSize(0.2);
  if (dolog) ratio->GetYaxis()->SetRangeUser(0.5,1.5);
  else ratio->GetYaxis()->SetRangeUser(0.7,1.3);
  ratio->GetYaxis()->SetTitle("Ratio    ");
  ratio->GetXaxis()->SetLabelSize(0);
  ratio->GetXaxis()->SetTitleSize(0);
  ratio->SetMarkerSize(1);
  ratio->SetLineWidth(2);
  ratio->SetLineColor(kBlue);
  ratio->SetMarkerColor(kBlue);
  ratio->SetFillColor(kBlue);
  ratio->SetFillStyle(3002);
  ratio->Draw("E2");
  
  TLine line;
  line.SetLineWidth(2);
  line.DrawLine(h_dt->GetXaxis()->GetXmin(),1,h_dt->GetXaxis()->GetXmax(),1);

}
void 
postfit_use(const char* inputfile, const char* analysis = "SM", const char* dataset = "2011+2012", const char* extra="", const char* extra2="", float min=0.1, float max=-1., bool log=true)
{
  // defining the common canvas, axes pad styles
  SetStyle(); gStyle->SetLineStyleString(11,"20 10");
  // switch for MSSM/SM
  bool MSSM = std::string(analysis) == std::string("MSSM");
  // determine label
  if (std::string(dataset) == std::string("2011"     )){ dataset = "CMS Preliminary,  H#rightarrow#tau#tau, 4.9 fb^{-1} at 7 TeV"; }
  if (std::string(dataset) == std::string("2012"     )){ dataset = "CMS Preliminary,  H#rightarrow#tau#tau, 19.8 fb^{-1} at 8 TeV"; }
  if (std::string(dataset) == std::string("2011+2012")){ dataset = "CMS Preliminary,  H#rightarrow#tau#tau, 4.9 fb^{-1} at 7 TeV, 19.8 fb^{-1} at 8 TeV"; }
  // determine category tag
  const char* category_extra = "";
  if(std::string(extra2) == std::string("0jet_low"  )){ category_extra = "0 jet, low p_{T}";  }
  if(std::string(extra2) == std::string("0jet_high" )){ category_extra = "0 jet, high p_{T}"; }
  if(std::string(extra2) == std::string("0jet"      )){ category_extra = "0 jet";             }
  if(std::string(extra2) == std::string("1jet_low"  )){ category_extra = "1 jet, low p_{T}";  }
  if(std::string(extra2) == std::string("1jet_high" )){ category_extra = "1 jet, high p_{T}"; }
  if(std::string(extra2) == std::string("1jet"      )){ category_extra = "1 jet";             }
  if(std::string(extra2) == std::string("vbf"       )){ category_extra = "2 jet (VBF)";       }
  if(std::string(extra2) == std::string("nobtag"    )){ category_extra = "No B-Tag";          }
  if(std::string(extra2) == std::string("btag"      )){ category_extra = "B-Tag";             }

  TFile* input = new TFile(inputfile);
  TH1F* Fakes  = refill((TH1F*)input->Get("Fakes"   ), "Fakes/QCD"); 
  TH1F* EWK    = refill((TH1F*)input->Get("EWK"     ), "EWK"      ); 
  TH1F* ttbar  = refill((TH1F*)input->Get("ttbar"   ), "ttbar"    ); 
  TH1F* Ztt    = refill((TH1F*)input->Get("Ztt"     ), "Ztt"      ); 
  TH1F* Zmm    = refill((TH1F*)input->Get("Zmm"     ), "Zmm"      ); 
  TH1F* Zee    = refill((TH1F*)input->Get("Zee"     ), "Zee"      ); 
  TH1F* ggH    = refill((TH1F*)input->Get("ggH"     ), "ggH"      ); 
  TH1F* data   = (TH1F*)input->Get("data_obs"); 
  // determine channel for etau Z->ee (EWK) will be shown separated from the rest (EWK1)
  TH1F* EWK1   = 0;
  if(std::string(extra) == std::string("e#tau_{h}")){
    EWK1 = refill((TH1F*)input->Get("EWK1"),  "EWK1");
  }
  TH1F* ggH_hww = 0;
  if(std::string(extra) == std::string("e#mu") and HWWBG){
    ggH_hww= refill((TH1F*)input->Get("ggH_hww" ), "ggH_hww"  ); 
  }
  TH1F* errorBand = (TH1F*)input->Get("errorBand");

  /* 
    mass plot before and after fit
  */
  TCanvas *canv = MakeCanvas("canv", "histograms", 600, 600);
  if(log) canv->SetLogy(1);
  // reduce the axis range if necessary for linea plots and SM
  if(MSSM && !log){ data->GetXaxis()->SetRange(0, data->FindBin(345)); } else{ data->GetXaxis()->SetRange(0, data->FindBin(UPPER_EDGE)); };
  if(!MSSM){ data->GetXaxis()->SetRange(0, data->FindBin(345)); }
  data->SetNdivisions(505);
  data->SetMinimum(min);
  if(std::string(extra) == std::string("#mu#mu")){
    data->SetMaximum(max>0 ? max : std::max(maximum(data, log), maximum(Zmm, log)));
    data->Draw("e");
    if(log){
      Zmm  ->Draw("same");
      Ztt  ->Draw("same");
      ttbar->Draw("same");
      Fakes->Draw("same");
      EWK  ->Draw("same");
      if(ggH) ggH  ->Draw("histsame");
    }
  }
  else if(std::string(extra) == std::string("ee")){
    data->SetMaximum(max>0 ? max : std::max(maximum(data, log), maximum(Zee, log)));
    data->Draw("e");
    if(log){
      Zee  ->Draw("same");
      Ztt  ->Draw("same");
      ttbar->Draw("same");
      Fakes->Draw("same");
      EWK  ->Draw("same");
      if(ggH) ggH  ->Draw("histsame");
    }
  }
  else if(std::string(extra) == std::string("e#tau_{h}")){
    data->SetMaximum(max>0 ? max : std::max(maximum(data, log), maximum(Ztt, log)));
    data->Draw("e");
    if(log){
      Ztt  ->Draw("same");
      ttbar->Draw("same");
      EWK  ->Draw("same");
      EWK1 ->Draw("same");
      Fakes->Draw("same");
      if(ggH) ggH  ->Draw("histsame");
    }
    else{
      if(ggH) ggH  ->Draw("histsame");
      Ztt  ->Draw("same");
      ttbar->Draw("same");
      EWK  ->Draw("same");
      EWK1 ->Draw("same");
      Fakes->Draw("same");
    } 
  }
  else if(std::string(extra) == std::string("e#mu") && HWWBG){
    data->SetMaximum(max>0 ? max : std::max(maximum(data, log), maximum(ggH_hww, log)));
    data->Draw("e");
    if(log){
      ggH_hww -> Draw("same");
      Ztt  ->Draw("same");
      ttbar->Draw("same");
      EWK  ->Draw("same");
      Fakes->Draw("same");
      if(ggH) ggH  ->Draw("histsame");
    }
    else{
      if(ggH) ggH  ->Draw("histsame");
      ggH_hww -> Draw("same");
      Ztt  ->Draw("same");
      ttbar->Draw("same");
      EWK  ->Draw("same");
      Fakes->Draw("same");
    } 
  }
  else{
    data->SetMaximum(max>0 ? max : std::max(maximum(data, log), maximum(Ztt, log)));
    data->Draw("e");
    if(log){
      Ztt  ->Draw("same");
      ttbar->Draw("same");
      EWK  ->Draw("same");
      Fakes->Draw("same");
      if(ggH) ggH  ->Draw("histsame");
    }
    else{
      if(ggH) ggH  ->Draw("histsame");
      Ztt  ->Draw("same");
      ttbar->Draw("same");
      EWK  ->Draw("same");
      Fakes->Draw("same");
    } 
  }
  if(errorBand){
    errorBand->Draw("e2same");
  }
  data->Draw("esame");
  canv->RedrawAxis();




  //CMSPrelim(dataset, extra, 0.17, 0.835);
  CMSPrelim(dataset, "", 0.18, 0.835);  
  TPaveText* chan     = new TPaveText(0.20, 0.74+0.061, 0.32, 0.74+0.161, "NDC");
  chan->SetBorderSize(   0 );
  chan->SetFillStyle(    0 );
  chan->SetTextAlign(   12 );
  chan->SetTextSize ( 0.05 );
  chan->SetTextColor(    1 );
  chan->SetTextFont (   62 );
  chan->AddText(extra);
  chan->Draw();

  TPaveText* cat      = new TPaveText(0.20, 0.68+0.061, 0.32, 0.68+0.161, "NDC");
  cat->SetBorderSize(   0 );
  cat->SetFillStyle(    0 );
  cat->SetTextAlign(   12 );
  cat->SetTextSize ( 0.05 );
  cat->SetTextColor(    1 );
  cat->SetTextFont (   62 );
  cat->AddText(category_extra);
  cat->Draw();

  if(MSSM){
    float lower_bound = EWK1 ? 0.45 : 0.50;
    TPaveText* massA      = new TPaveText(0.55, lower_bound+0.061, 0.95, lower_bound+0.161, "NDC");
    massA->SetBorderSize(   0 );
    massA->SetFillStyle(    0 );
    massA->SetTextAlign(   12 );
    massA->SetTextSize ( 0.03 );
    massA->SetTextColor(    1 );
    massA->SetTextFont (   62 );
    massA->AddText("m^{h}_{max} (m_{A}=$MA GeV, tan#beta=$TANB)");
    massA->Draw();
  }    
  float lower_bound = EWK1 ? 0.60 : 0.65;
  TLegend* leg = new TLegend(MSSM ? 0.55 : 0.50, lower_bound, 0.93, 0.90);
  SetLegendStyle(leg);
  if(MSSM){
    leg->AddEntry(ggH  , "#phi#rightarrow#tau#tau", "L" );
  }
  else{
    if(ggH){
      if(SIGNAL_SCALE!=1){
	leg->AddEntry(ggH  , TString::Format("%.0f#timesH(125 GeV)#rightarrow#tau#tau", SIGNAL_SCALE) , "L" );
      }
      else{
	leg->AddEntry(ggH  , "H(125 GeV)#rightarrow#tau#tau" , "L" );
      }
    }
  }
  leg->AddEntry(data , "observed"                       , "LP");
  
  if(std::string(extra) == std::string("#mu#mu")){
    leg->AddEntry(Zmm  , "Z#rightarrow#mu#mu"    , "F" );
    leg->AddEntry(Ztt  , "Z#rightarrow#tau#tau"           , "F" );
    leg->AddEntry(ttbar, "t#bar{t}"                       , "F" );
    leg->AddEntry(Fakes, "QCD"                 , "F" );
    leg->AddEntry(EWK  , "electroweak"                  , "F" );
  }
  else if(std::string(extra) == std::string("ee")){
    leg->AddEntry(Zee  , "Z#rightarrowee"        , "F" );
    leg->AddEntry(Ztt  , "Z#rightarrow#tau#tau"           , "F" );
    leg->AddEntry(ttbar, "t#bar{t}"                       , "F" );
    leg->AddEntry(Fakes, "QCD"                 , "F" );
    leg->AddEntry(EWK  , "electroweak"                  , "F" );
  }
  else if(std::string(extra) == std::string("e#tau_{h}")){
    leg->AddEntry(Ztt  , "Z#rightarrow#tau#tau"           , "F" );
    leg->AddEntry(EWK  , "Z#rightarrow ee"              , "F" );
    leg->AddEntry(EWK1 , "electroweak"                  , "F" );
    leg->AddEntry(ttbar, "t#bar{t}"                       , "F" );
    leg->AddEntry(Fakes, "QCD"                 , "F" );
  }
  else if(std::string(extra) == std::string("e#mu") && HWWBG){
    leg->AddEntry(ggH_hww  , "H(125 GeV)#rightarrowWW" , "F" );
    leg->AddEntry(Ztt  , "Z#rightarrow#tau#tau"           , "F" );
    leg->AddEntry(ttbar, "t#bar{t}"                       , "F" );
    leg->AddEntry(EWK  , "electroweak"                  , "F" );
    leg->AddEntry(Fakes, "QCD"                 , "F" );
  }
  else{
    leg->AddEntry(Ztt  , "Z#rightarrow#tau#tau"           , "F" );
    leg->AddEntry(ttbar, "t#bar{t}"                       , "F" );
    leg->AddEntry(EWK  , "electroweak"                  , "F" );
    leg->AddEntry(Fakes, "QCD"                 , "F" );
  }
  if(errorBand){
    leg->AddEntry(errorBand, "bkg. uncertainty" , "F" );
  }
  leg->Draw();

  /*
    prepare output
  */
  std::string newName = std::string(inputfile).substr(0, std::string(inputfile).find(".root"));
  canv->Print(TString::Format("%s.png", newName.c_str())); 
  canv->Print(TString::Format("%s.pdf", newName.c_str())); 
  canv->Print(TString::Format("%s.eps", newName.c_str())); 

  /*
    Ratio Data over MC
  */
  TCanvas *canv0 = MakeCanvas("canv0", "histograms", 600, 400);
  canv0->SetGridx();
  canv0->SetGridy();
  canv0->cd(); 
  TH1F* model;
  if(CONSERVATIVE_CHI2){
    if(std::string(extra) == std::string("#mu#mu")){
      model = (TH1F*)Zmm ->Clone("model");
    }
    else if(std::string(extra) == std::string("ee")){
      model = (TH1F*)Zee ->Clone("model");
    }
    else if(std::string(extra) == std::string("e#mu") && HWWBG){
      model = (TH1F*)ggH_hww ->Clone("model");
    }
    else{  
      model = (TH1F*)Ztt ->Clone("model");
    }
  }
  else{
    model = (TH1F*)errorBand->Clone("model");
  }
  TH1F* test1 = (TH1F*)data->Clone("test1"); 
  for(int ibin=0; ibin<test1->GetNbinsX(); ++ibin){
    //the small value in case of 0 entries in the model is added to prevent the chis2 test from failing
    model->SetBinContent(ibin+1, model->GetBinContent(ibin+1)>0 ? model->GetBinContent(ibin+1)*model->GetBinWidth(ibin+1) : 0.01);
    model->SetBinError  (ibin+1, CONSERVATIVE_CHI2 ? 0. : model->GetBinError  (ibin+1)*model->GetBinWidth(ibin+1));
    test1->SetBinContent(ibin+1, test1->GetBinContent(ibin+1)*test1->GetBinWidth(ibin+1));
    test1->SetBinError  (ibin+1, test1->GetBinError  (ibin+1)*test1->GetBinWidth(ibin+1));
  }
  double chi2prob = test1->Chi2Test      (model,"PUW");        std::cout << "chi2prob:" << chi2prob << std::endl;
  double chi2ndof = test1->Chi2Test      (model,"CHI2/NDFUW"); std::cout << "chi2ndf :" << chi2ndof << std::endl;
  double ksprob   = test1->KolmogorovTest(model);              std::cout << "ksprob  :" << ksprob   << std::endl;
  double ksprobpe = test1->KolmogorovTest(model,"DX");         std::cout << "ksprobpe:" << ksprobpe << std::endl;  

  std::vector<double> edges;
  TH1F* zero = (TH1F*)Ztt->Clone("zero"); zero->Clear();
  TH1F* rat1 = (TH1F*)data->Clone("rat"); 
  for(int ibin=0; ibin<rat1->GetNbinsX(); ++ibin){
    rat1->SetBinContent(ibin+1, errorBand->GetBinContent(ibin+1)>0 ? data->GetBinContent(ibin+1)/errorBand->GetBinContent(ibin+1) : 0);
    rat1->SetBinError  (ibin+1, errorBand->GetBinContent(ibin+1)>0 ? data->GetBinError  (ibin+1)/errorBand->GetBinContent(ibin+1) : 0);
    zero->SetBinContent(ibin+1, 0.);
    zero->SetBinError  (ibin+1, errorBand->GetBinContent(ibin+1)>0 ? errorBand ->GetBinError  (ibin+1)/errorBand->GetBinContent(ibin+1) : 0);
  }
  for(int ibin=0; ibin<rat1->GetNbinsX(); ++ibin){
    if(rat1->GetBinContent(ibin+1)>0){
      edges.push_back(TMath::Abs(rat1->GetBinContent(ibin+1)-1.)+TMath::Abs(rat1->GetBinError(ibin+1)));
      // catch cases of 0 bins, which would lead to 0-alpha*0-1
      rat1->SetBinContent(ibin+1, rat1->GetBinContent(ibin+1)-1.);
    }
    zero->SetBinContent(ibin+1, 0.);
  }
  float range = 0.1;
  std::sort(edges.begin(), edges.end());
  if (edges[edges.size()-2]>0.1) { range = 0.2; }
  if (edges[edges.size()-2]>0.2) { range = 0.5; }
  if (edges[edges.size()-2]>0.5) { range = 1.0; }
  if (edges[edges.size()-2]>1.0) { range = 1.5; }
  if (edges[edges.size()-2]>1.5) { range = 2.0; }
  rat1->SetLineColor(kBlack);
  rat1->SetFillColor(kGray );
  rat1->SetMaximum(+range);
  rat1->SetMinimum(-range);
  rat1->GetYaxis()->CenterTitle();
  rat1->GetYaxis()->SetTitle("#bf{Data/MC-1}");
  if((std::string(extra) == std::string("#mu#mu") || std::string(extra) == std::string("ee")) && !MSSM){
    rat1->GetXaxis()->SetTitle("#bf{D}");
  }
  else{
    rat1->GetXaxis()->SetTitle("#bf{m_{#tau#tau} [GeV]}");
  }
  rat1->Draw();
  zero->SetFillStyle(  3013);
  zero->SetFillColor(kBlack);
  zero->SetLineColor(kBlack);
  zero->SetMarkerSize(0.1);
  zero->Draw("e2histsame");
  canv0->RedrawAxis();

  TPaveText* stat1 = new TPaveText(0.20, 0.76+0.061, 0.32, 0.76+0.161, "NDC");
  stat1->SetBorderSize(   0 );
  stat1->SetFillStyle(    0 );
  stat1->SetTextAlign(   12 );
  stat1->SetTextSize ( 0.05 );
  stat1->SetTextColor(    1 );
  stat1->SetTextFont (   62 );
  stat1->AddText(TString::Format("#chi^{2}/ndf=%.3f,  P(#chi^{2})=%.3f", chi2ndof, chi2prob));
  //stat1->AddText(TString::Format("#chi^{2}/ndf=%.3f,  P(#chi^{2})=%.3f,  P(KS)=%.3f", chi2ndof, chi2prob, ksprob));
  stat1->Draw();

  /*
    prepare output
  */
  newName = std::string(inputfile).substr(0, std::string(inputfile).find(".root")) + "_datamc";
  canv0->Print(TString::Format("%s.png", newName.c_str())); 
  canv0->Print(TString::Format("%s.pdf", newName.c_str())); 
  canv0->Print(TString::Format("%s.eps", newName.c_str())); 
}
Example #30
0
void plottingmacro_IVF()
{


  double fa = 0.46502;
  double fb = 0.53498;
  bool debug_ = true;

  //  std::string path("Nov10thFall11Plots/");
  //  std::string path("Nov10Fall1160MTopSlimPlots/");
  std::string path("Nov10Fall1160MTopIVFPlots_b/");

  if(debug_)
    std::cout << "Init the style form setTDRStyle" << std::endl;
  setTDRStyle();
  gStyle->SetErrorX(0.5);
  gROOT->ForceStyle();
  initOptions();
  

  if(debug_)
    std::cout << "Init the sample" << std::endl;
  //  std::vector<Sample> s = Nov10thDiJetPtUpdatedSlimHistos();
  //std::vector<Sample> s = Nov10Fall1160MTopSlimHistos();
  std::vector<Sample> s = Nov10Fall1160MTopIVFHistos();

  Sample data(1,"fake data","S1.root",0,true,1000);

  if(debug_)
    std::cout << "Init the data sample" << std::endl;
  for(size_t i=0;i< s.size();i++) if(s[i].data) {data=s[i];break;}

  if(debug_)
    std::cout << "Ls data sample" << std::endl;
  data.file()->ls(); 

  if(debug_)
    std::cout << "Init the mc sample" << std::endl;
  for(size_t i=0;i< s.size();i++) s[i].dump(1,fa,fb);

  std::vector<std::string> names;

  if(debug_)
    std::cout << "Get List of Keys" << std::endl;
  TList * subs = data.file()->GetListOfKeys();
  for(size_t i=0;i< subs->GetSize();i++)
    {
      TString nn = subs->At(i)->GetName();
      if( nn.Contains(TRegexp("Count*")) )
	continue;
      if(debug_)
	std::cout << "Get List of Keys in subdirs" << std::endl;
      TList * objs = ((TDirectoryFile *)data.file()->Get(subs->At(i)->GetName()))->GetListOfKeys();
      for(size_t j=0;j< objs->GetSize();j++)
	{
	  if(debug_)
	    std::cout << "Name = " << subs->At(i)->GetName()+std::string("/")  + objs->At(j)->GetName() << std::endl;
	  names.push_back(subs->At(i)->GetName()+std::string("/")  + objs->At(j)->GetName());
	  //      std::cout << subs->At(i)->GetName() << "/"  << objs->At(j)->GetName() << std::endl;
	  //TODO: select plots via regexp
	}
    }


  if(debug_)
    std::cout << "Starting plotting" << std::endl;

  std::string process;

  for(size_t i = 0 ; i < names.size() ; i++) 
    {
      
      std::map<std::string,TH1F *> grouped;
      TString n=names[i];
      //      if(!n.Contains(TRegexp("VlightRegionHZee/HiggsPtVlightRegionHZee"))) continue;
      //      if(!n.Contains(TRegexp("VlightRegionHZee/ZPtVlightRegionHZee"))) continue;
      //      if(!n.Contains(TRegexp("VlightRegionHZee"))) continue;
      //      if(!n.Contains(TRegexp("ZSVRegionZmmSV"))) continue;
      //      if(!n.Contains(TRegexp("ZSVRegionZeeSV"))) continue;
      //      if(!n.Contains(TRegexp("ZSVRegionZcombSV"))) continue;
      //      if(!n.Contains(TRegexp("ZSVPureRegionZcombSV"))) continue;
      //      if(!n.Contains(TRegexp("ZSVTTbarPureRegionZcombSV"))) continue;
      if(!n.Contains(TRegexp("TTbarRegionZeeSVJets"))) continue;

      if(n.Contains(TRegexp("RegionHZcomb")))
	process = "Z(l^{+}l^{-})H(b#bar{b})";
      if(n.Contains(TRegexp("RegionHZmm")))
	process = "Z(#mu^{+}#mu^{-})H(b#bar{b})";
      if(n.Contains(TRegexp("RegionHZee")))
	process = "Z(e^{+}e^{-})H(b#bar{b})";

      if(debug_)
	std::cout << "Creating the Canvas" << std::endl;

      TCanvas *c = new TCanvas();
      c->SetLogy(false);
      c->SetTitle(names[i].c_str());

      if(debug_)
	std::cout << "Creating histograms" << std::endl;
  
      TH1F *hd = ((TH1F*)data.file()->Get(names[i].c_str()));
      hd->Sumw2();
      Options o=options[names[i]];
      //      hd->Rebin(o.rebin);
      hd->SetMarkerStyle(20);
      hd->GetXaxis()->SetLabelOffset(99);
      hd->SetYTitle(o.yaxis.c_str());
      double nbin = hd->GetNbinsX();
      double min_bin = hd->GetXaxis()->GetXmin();
      double max_bin = hd->GetXaxis()->GetXmax();
      TH1F *hmc = new TH1F("hmc","hmc", nbin, min_bin, max_bin);
      hmc->SetFillColor(kWhite);
      hmc->Sumw2();
      //      hmc->Rebin(o.rebin);

      if(debug_)
	std::cout << "Creating the THStack and Legend" << std::endl;
      THStack * sta = new THStack("sta",hd->GetTitle());
      TLegend * l = new TLegend(o.legendx1,o.legendy1,o.legendx2,o.legendy2); //0.7,0.1,0.9,0.6);
      l->SetFillColor(kWhite);
      l->SetBorderSize(0);
      l->SetTextFont(62);
      l->SetTextSize(0.03);
      if(debug_)
	std::cout << "Adding data to the legend" << std::endl;  
      l->AddEntry(hd, "Data","P");
      if(debug_)
	std::cout << "Adding MC to the THStack" << std::endl;  

      //with the proper trigger eff
      //      double SF[] = {1.01,1.03,1.00};
      //      double SF[] = {1.03,1.054,1.032};
      double SF[] = {1.0,1.0,1.0};

      if(debug_){
	for(int i = 0; i< 3; ++i)
	  std::cout << "SF [" << i << "] = " << SF[i] << std::endl;
      }

      double mcIntegral=0;
      for(size_t j=0;j< s.size() ;j++) 
	{ 
	  if(!s[j].data) 
	    {
	      if(debug_)
		std::cout << "Creating TH1F from file " << s[j].name << std::endl;  
	      TH1F * h = ((TH1F*)s[j].file()->Get(names[i].c_str()));
	      h->Sumw2();
	      if(debug_){
		std::cout << "TH1F created from file " << s[j].name << std::endl;  
		std::cout << "Scaling : " << s[j].scale(data.lumi(),fa,fb) << std::endl;  
		std::cout << "Scaling with SF : " << s[j].scale(data.lumi(),fa,fb,SF) << std::endl;  
		std::cout << "Histo integral before scaling = " << h->Integral() << std::endl;
	      }
	      h->Scale(s[j].scale(data.lumi(),fa,fb,SF));
	      if(debug_){
		std::cout << "Histo integral after scaling = " << h->Integral() << std::endl;
		std::cout << "Managing style... " << std::endl;  
	      }
	      h->SetLineWidth(1.);
	      h->SetFillColor(s[j].color);
	      h->SetLineColor(s[j].color);
	      //	      h->Rebin(options[names[i]].rebin);
	      if(debug_)
		std::cout << "Cloning and update legend " << std::endl;  
	      if(grouped.find(s[j].name) == grouped.end()){
		l->AddEntry(h,s[j].name.c_str(),"F");
	      }
	      std::cout << "Sample : " << s[j].name << " - Integral for plot " << names[i] << " = " << h->Integral(-10000,10000) << std::endl;
	      mcIntegral += h->Integral();
	      sta->Add(h);
	      hmc->Add(h);	      
	      //TO FIX grouped map
	      // sovrascrive histo con lo stesso nome tipo VV o ST etc...
	      grouped[s[j].name]=(TH1F *)h->Clone(("_"+names[i]).c_str());
	    }
	}

      if(debug_){
	std::cout << "Data total = " << hd->Integral() << std::endl;
	std::cout << "MC = " << mcIntegral << std::endl;
	std::cout << "Data/MC = " << hd->Integral()/mcIntegral << std::endl;
      }

      TPad * TopPad = new TPad("TopPad","Top Pad",0.,0.3,1.,1. ) ;
      TPad * BtmPad = new TPad("BtmPad","Bottom Pad",0.,0.,1.,0.313 ) ;
      TopPad->SetBottomMargin(0.02);
      BtmPad->SetTopMargin(0.0);
      BtmPad->SetFillStyle(4000);
      TopPad->SetFillStyle(4000);
      BtmPad->SetFillColor(0);
      BtmPad->SetBottomMargin(0.35);
      TopPad->Draw() ;
      BtmPad->Draw() ;
      std::cout << "hd maximum = " << hd->GetMaximum() << "  sta maximum = " << sta->GetMaximum() << std::endl;
      double maxY;
      if(hd->GetMaximum() > sta->GetMaximum()) maxY = (hd->GetMaximum())*1.5;
      else maxY = (sta->GetMaximum())*1.5;
      TopPad->cd();
      hd->Draw("E1X0");
      sta->Draw("sameHIST");
      hmc->Draw("sameE2");
      hmc->SetFillColor(2);
      hmc->SetMarkerSize(0);
      hmc->SetFillStyle(3013);
      hd->Draw("E1X0same");
      l->Draw("same");
      std::cout << "Set Maximum to = " << maxY << std::endl;
      hd->GetYaxis()->SetRangeUser(0.,maxY);
      hd->GetXaxis()->SetRangeUser(options[names[i]].min,options[names[i]].max);

      BtmPad->cd();
      std::cout << "Division" << std::endl;

      TH1D * divisionErrorBand = (TH1D*)(hmc)->Clone("divisionErrorBand");
      divisionErrorBand->Sumw2();
      divisionErrorBand->Divide(hmc);
      divisionErrorBand->Draw("E2");      
      divisionErrorBand->SetMaximum(2.49);
      divisionErrorBand->SetMinimum(0);
      divisionErrorBand->SetMarkerStyle(20);
      divisionErrorBand->SetMarkerSize(0.55);
      divisionErrorBand->GetXaxis()->SetTitleOffset(1.12);
      divisionErrorBand->GetXaxis()->SetLabelSize(0.12);
      divisionErrorBand->GetXaxis()->SetTitleSize(0.5);
      divisionErrorBand->GetYaxis()->SetTitle("Data/MC");
      divisionErrorBand->GetYaxis()->SetLabelSize(0.12);
      divisionErrorBand->GetYaxis()->SetTitleSize(0.12);
      divisionErrorBand->GetYaxis()->SetTitleOffset(0.40);
      divisionErrorBand->GetYaxis()->SetNdivisions(505);
      //divisionErrorBand->UseCurrentStyle();
      divisionErrorBand->SetFillColor(2);
      divisionErrorBand->SetFillStyle(3001);
      divisionErrorBand->SetMarkerSize(0.);

      TH1D * division = (TH1D*)(hd)->Clone("division");
      division->Sumw2();
      division->Divide(hmc);
//       division->SetMaximum(2.5);
//       division->SetMinimum(0);
//       division->SetMarkerStyle(20);
//       division->SetMarkerSize(0.55);
//       division->GetXaxis()->SetLabelSize(0.12);
//       division->GetXaxis()->SetTitleSize(0.14);
//       division->GetYaxis()->SetLabelSize(0.10);
//       division->GetYaxis()->SetTitleSize(0.10);
//      division->GetYaxis()->SetTitle("Data/MC");
      Double_t min = division->GetXaxis()->GetXmin();
      Double_t max = division->GetXaxis()->GetXmax();
      division->Draw("E1X0same");

      TLine *line = new TLine(min, 1.0, max, 1.0);
      line->SetLineColor(kRed);
      line->Draw("same");
      
      TLegend * leg3 =new TLegend(0.50,0.86,0.69,0.96);
      leg3->AddEntry(divisionErrorBand,"MC uncert. (stat.)","f");
      leg3->SetFillColor(0);
      leg3->SetLineColor(0);
      leg3->SetShadowColor(0);
      leg3->SetTextFont(62);
      leg3->SetTextSize(0.06);
      leg3->Draw();

      TPaveText *pave = new TPaveText(0.15,0.85,0.32,0.96,"brNDC");
      pave->SetTextAlign(12);
      pave->SetLineColor(0);
      pave->SetFillColor(0);
      pave->SetShadowColor(0);
      //TText *text = pave->AddText(Form("#chi_{#nu}^{2} = %.3f, K_{s} = %.3f",histDt->Chi2Test(histCopyMC5,"UWCHI2/NDF"),histDt->KolmogorovTest(histCopyMC5))); // stat + sys
      TText *text = pave->AddText(Form("#chi_{#nu}^{2} = %.3f, K_{s} = %.3f",hd->Chi2Test(hmc,"UWCHI2/NDF"),hd->KolmogorovTest(hmc))); // stat only
      text->SetTextFont(62);
      text->SetTextSize(0.08);
      pave->Draw();

      TopPad->cd();
      TLatex latex;
      latex.SetNDC();
      latex.SetTextAlign(12);
      latex.SetTextSize(0.052);
      latex.DrawLatex(0.17,0.89,"CMS Preliminary");
      latex.SetTextSize(0.04);
      latex.DrawLatex(0.17,0.84,"#sqrt{s} = 7 TeV, L = 4.7 fb^{-1}");
      //      latex.DrawLatex(0.17,0.79,"Z(e^{+}e^{-})H(b#bar{b})");
      latex.DrawLatex(0.17,0.79,process.c_str());
      c->Update();
      std::string cName= hd->GetName();
      cName += "_bare.pdf";
      cName = path+cName;
      c->Print(cName.c_str(),"pdf");

//       std::cout << names[i] << " d: " <<  hd->Integral() << " ";
//       THStack * sta2 = new THStack("sta2",hd->GetTitle());
//       float tot=0;
//       float toterr2=0;

//       if(debug_)
// 	std::cout << "Putting the iterator in the for loop" << std::endl;
//       for(std::map<std::string,TH1F *>::reverse_iterator it=grouped.rbegin(); it!=grouped.rend();++it)
//  	{
// 	  if(debug_)
// 	    std::cout << "Using the iterator" << std::endl;
// 	  std::cout << (*it).first << " " << (*it).second->Integral() << " | " << std::endl ;
// 	  if((*it).second->GetEntries() > 0) {
// 	    float er=1.*sqrt((*it).second->GetEntries())/(*it).second->GetEntries()*(*it).second->Integral();
// 	    toterr2+=er*er;
// 	  }
// 	  tot+=(*it).second->Integral();
// 	  sta2->Add(it->second);
//  	}
//       std::cout << " Tot: " << tot << "+-" << sqrt(toterr2) <<  " SF: " << hd->Integral()/tot << std::endl;
//       TCanvas *c2 = new TCanvas();
//       c2->SetTitle(names[i].c_str());
//       std::cout << "hd maximum = " << hd->GetMaximum() << "  sta2 maximum = " << sta2->GetMaximum() << std::endl;
//       if(hd->GetMaximum() > sta2->GetMaximum()) maxY =  hd->GetBinContent(hd->GetMaximumBin()) * 1.5;
//       else maxY = ( sta2->GetMaximum())*1.5;
//       //      hd->Draw("E1"); 
//       sta2->Draw("PADSHIST");
//       //    hd->Draw("E1same");
//       //      l->Draw("same");
//       std::cout << "Set Maximum to = " << maxY << std::endl;
//       hd->GetYaxis()->SetRangeUser(0.,maxY);
//       hd->GetXaxis()->SetRangeUser(options[names[i]].min,options[names[i]].max);
//       c2->Update();

//       std::string c2Name = hd->GetName();
//       c2Name = path+c2Name;
//       c2Name += "_norm.pdf";
//       c2->Print(c2Name.c_str(),"pdf");  

    }

}