Exemple #1
0
void plotGlauberCenVars(Float_t eff=1., const Char_t* file="ZNA_ntuple_195483.root")
{
  TFile *f = TFile::Open(file);
  TNtuple* ntuple = dynamic_cast<TNtuple*> (f->Get("gnt"));
   
  TGraphErrors *gNpart=new TGraphErrors(0);
  gNpart->SetName("gNpart"); 
  TGraphErrors *gNcoll=new TGraphErrors(0);
  gNcoll->SetName("gNcoll"); 
  TGraphErrors *gtAA=new TGraphErrors(0);
  gtAA->SetName("gtAA"); 
  
  /*TFile *ffd = TFile::Open("hZNAcalibRUN195483.root");
  TH1F * hd = dynamic_cast<TH1F*> (ffd->Get(("hZNA")));
  hd->Sumw2();*/
  //
  TFile *ff = TFile::Open("ZNA_fit_195483.root");
  TH1F * hd = dynamic_cast<TH1F*> (ff->Get(("hZNA")));
  hd->Sumw2();
  TH1F * hg = dynamic_cast<TH1F*> (ff->Get(("hZNA_GLAU")));
  hd->SetMarkerColor(kBlue+3);
  hd->SetMarkerSize(1.);
  hd->SetLineColor(kBlue+3);
  hd->SetLineWidth(2);
  hd->SetMarkerStyle(20);
  hd->SetLineWidth(2);
//  hg->Scale(1./hd->GetEntries());
//  hd->Scale(1./hd->GetEntries());
  hd->SetMinimum(1.e-01);
  hd->SetXTitle("E_{ZNA} (TeV)");
  hg->SetLineColor(kPink-2);
  hg->SetLineWidth(2);
  
  TH1F* hist = (TH1F*) hg->Clone("hist");

  //---------------------------------------------------
  getCentrality(hist, eff);
  //---------------------------------------------------

  TCanvas* canvas = new TCanvas("canvas","Multiplicity",200,200,600,600);
  canvas->cd();
  canvas->SetLogy();
  hd->Draw("pe");
  //hd->GetXaxis()->SetRangeUser(0.,130.);
  hd->SetMinimum(0.01);
  hg->Draw("SAME");

  float low = 0;
  float high = hist->GetNbinsX();
  for(int i=0; i<binUp->GetSize(); i++){
      low = binUp->At(i);
      hist->GetXaxis()->SetRange(low+1, high);
      hist->SetFillColor((i%2==0)?0:kAzure+6);
      hist->SetLineColor((i%2==0)?0:kAzure+6);
      printf(" bin %d  low %f  high %f\n",i,low,high);
      hist->DrawCopy("h same");
      high=low;
  }
  hd->Draw("esame");
  hg->Draw("SAME");
  canvas->Print("plotGlauber.gif");   
  
  TCanvas* canvas2 = new TCanvas("canvas2","NPart");
  canvas2->cd();
  canvas2->SetLogy();
  TH1F *hist2 = new TH1F("hist2","N_{part}",35,0.,35);
  ntuple->Project("hist2","fNpart");
  //hist2->SetStats(0);
  hist2->SetTitle("");
  hist2->GetXaxis()->SetTitle("NPart");
  hist2->GetXaxis()->SetTitleSize(0.05);
  hist2->GetXaxis()->SetLabelSize(0.04);
  hist2->GetXaxis()->SetTitleOffset(1.2);
  hist2->GetYaxis()->SetTitle("");
  hist2->GetYaxis()->SetTitleOffset(1.3);
  hist2->GetYaxis()->SetTitleSize(0.05);
  hist2->GetYaxis()->SetLabelSize(0.04);
  hist2->DrawCopy();
  
  float lownp=0;
  float highnp=5000;
  TH1F *htemp10[nbins];
  printf("\n ***** N_part \n");
  for(int i=0; i<Multbin->GetSize(); i++){
      lownp = Multbin->At(i);
      char cuts[120];
      char histname[20];
      sprintf(cuts,"Etot>%f && Etot<=%f",lownp,highnp);
      sprintf(histname,"htemp10[%i]",i);
      htemp10[i] = new TH1F(histname,"N_{part}",35,0.,35);
      //printf(" cut: %s\n", cuts);
      ntuple->Project(histname,"fNpart",cuts);
      htemp10[i]->SetLineColor(i+1);
      htemp10[i]->Draw("same");
      cout  << i << " | " << lownp << " | " << highnp << " | " << setprecision(3) << 
      htemp10[i]->GetMean() << " | " << htemp10[i]->GetRMS() << " | " << endl;
      gNpart->SetPoint(i,Float_t(i),htemp10[i]->GetMean());
      gNpart->SetPointError(i,0,htemp10[i]->GetRMS());
      highnp = lownp;
  }
  cout << endl;
  
  TCanvas* canvas3 = new TCanvas("canvas3","NColl");
  canvas3->SetLogy();
  TH1F *hist3 = new TH1F("hist3","N_{coll}",35,0.,35);
  ntuple->Project("hist3","fNcoll");
  //hist3->SetStats(0);
  hist3->SetTitle("");
  hist3->GetXaxis()->SetTitle("NColl");
  hist3->GetXaxis()->SetTitleSize(0.05);
  hist3->GetXaxis()->SetLabelSize(0.04);
  hist3->GetXaxis()->SetTitleOffset(1.2);
  hist3->GetXaxis()->SetTitle("");
  hist3->GetXaxis()->SetTitleOffset(1.3);
  hist3->GetXaxis()->SetTitleSize(0.05);
  hist3->GetXaxis()->SetLabelSize(0.04);
  hist3->DrawCopy();
  
  float lownc = 0;
  float highnc = 5000;
  TH1F *htemp11[nbins];
  printf("\n ***** N_coll \n");
  for(int i=0; i<Multbin->GetSize(); i++){
      lownc = Multbin->At(i);
      char cuts[120];
      char histname[20];
      sprintf(cuts,"Etot>%f && Etot<=%f",lownc,highnc);
      sprintf(histname,"htemp11[%i]",i);
      htemp11[i] = new TH1F(histname,"N_{coll}",35,0.,35.);
      ntuple->Project(histname,"fNcoll",cuts);
      htemp11[i]->SetLineColor(i+1);
      htemp11[i]->Draw("same");
      cout << setprecision(3) << htemp11[i]->GetMean() << " | " << htemp11[i]->GetRMS() << " | " << endl;
      gNcoll->SetPoint(i,Float_t(i),htemp11[i]->GetMean());
      gNcoll->SetPointError(i,0,htemp11[i]->GetRMS());
      highnc = lownc;
  }
  cout << endl;
  
  TCanvas* canvas4 = new TCanvas("canvas4","Impact Parameter");
  canvas4->cd();
  TH1F *hist4 = new TH1F("hist4","b",100,0.,16.);
  ntuple->Project("hist4","fB");
  //hist4->SetStats(0);
  hist4->SetTitle("");
  hist4->GetXaxis()->SetTitle("b");
  hist4->GetXaxis()->SetTitleSize(0.05);
  hist4->GetXaxis()->SetLabelSize(0.04);
  hist4->GetXaxis()->SetTitleOffset(1.2);
  hist4->GetYaxis()->SetTitle("");
  hist4->GetYaxis()->SetTitleOffset(1.3);
  hist4->GetYaxis()->SetTitleSize(0.05);
  hist4->GetYaxis()->SetLabelSize(0.04);
  hist4->DrawCopy();
  
  float lowb = 0;
  float highb = 5000;
  TH1F *htemp12[nbins];
  printf("\n ***** b \n");
  for(int i=0; i<Multbin->GetSize(); i++){
      lowb = Multbin->At(i);
      char cuts[100];
      char histname[25];
      sprintf(cuts,"Etot>%f && Etot<=%f",lowb,highb);
      sprintf(histname,"htemp12[%i]",i);
      htemp12[i] = new TH1F(histname,"b",100,0.,16.);
      //printf(" cut: %s\n", cuts);
      ntuple->Project(histname,"fB",cuts);
      htemp12[i]->SetLineColor(i+1);
      htemp12[i]->DrawCopy("same");
      cout << i << " | " << lowb << " | " << highb << " | " << setprecision(3) << htemp12[i]->GetMean() << " | " << htemp12[i]->GetRMS() << " | " << endl;
      highb = lowb;
  }
  
  TCanvas* canvas5 = new TCanvas("canvas5","Taa");
  canvas5->SetLogy();
  TH1F *hist5 = new TH1F("hist5","T_{AA}",100,0.,0.5);
  ntuple->Project("hist5","fTaa");
  //hist5->SetStats(0);
  hist5->SetTitle("");
  hist5->GetXaxis()->SetTitle("tAA");
  hist5->GetXaxis()->SetTitleSize(0.05);
  hist5->GetXaxis()->SetLabelSize(0.04);
  hist5->GetXaxis()->SetTitleOffset(1.2);
  hist5->GetYaxis()->SetTitle("");
  hist5->GetYaxis()->SetTitleOffset(1.3);
  hist5->GetYaxis()->SetTitleSize(0.05);
  hist5->GetYaxis()->SetLabelSize(0.04);
  hist5->DrawCopy();
  
  float lowtaa = 0;
  float hightaa = 5000;
  TH1F *htemp13[nbins];
  printf("\n ***** T_AA \n");
  for (int i=0; i<Multbin->GetSize(); i++){
      lowtaa = Multbin->At(i);
      char cuts[100];
      char histname[100];
      sprintf(cuts,"Etot>%f && Etot<%f",lowtaa,hightaa);
      //printf(" cut: %s\n", cuts);
      sprintf(histname,"htemp13[%i]",i);
      htemp13[i] = new TH1F(histname,"b",100,0.,0.5);
      ntuple->Project(histname,"fTaa",cuts);
      htemp13[i]->SetLineColor(i+1);
      htemp13[i]->DrawCopy("same");
      cout << setprecision(3) << htemp13[i]->GetMean() << " | " << htemp13[i]->GetRMS() << " | " << endl;  
      gtAA->SetPoint(i,Float_t(i),htemp13[i]->GetMean());
      gtAA->SetPointError(i,0,htemp13[i]->GetRMS());
      hightaa = lowtaa;
  }

  /*TCanvas* canvas6 = new TCanvas("canvas6","Mean Mult");
  canvas6->SetLogy();
  //ntuple->Draw("ntot/Npart/23.867>>hmultperanc");
  ntuple->Draw("Etot/(0.801*Npart+(1-0.801)*Ncoll)/3.9>>hmultperanc");
  TH1F* hmultperanc = (TH1F*)gPad->GetPrimitive("hmultperanc");
  TH1F* hist6 = (TH1F*)hmultperanc->Clone();
  hist6->SetStats(0);
  hist6->SetTitle("");
  hist6->GetXaxis()->SetTitle("Mult/NPart");
  hist6->GetXaxis()->SetTitleSize(0.05);
  hist6->GetXaxis()->SetLabelSize(0.04);
  hist6->GetXaxis()->SetTitleOffset(1.);
  hist6->GetYaxis()->SetTitle("");
  hist6->GetYaxis()->SetTitleOffset(1.);
  hist6->GetYaxis()->SetTitleSize(0.05);
  hist6->GetYaxis()->SetLabelSize(0.04);
  hist6->DrawCopy();
  
  low=0;
  high=50000;
  for (int i=0; i<Multbin->GetSize(); i++)
    {
      low=Multbin->At(i);
      char cuts[100];
      char histtitle1[100];
      char histtitle[100];
      sprintf(cuts,"Etot>%i && Etot<%i",low,high);
      //sprintf(histtitle,"ntot/Npart/23.867>>htemp%i(100)",80+i);
      sprintf(histtitle,"Etot/(0.801*Npart+(1-0.801)*Ncoll)/3.9>>htemp%i(100)",80+i);
      sprintf(histtitle1,"htemp%i",80+i);
      ntuple->Draw(histtitle,cuts,"same");
      TH1F* htemp14 = (TH1F*)gPad->GetPrimitive(histtitle1);
      htemp14 = (TH1F*)gPad->GetPrimitive(histtitle1);
      htemp14->SetFillColor(i+1);
      htemp14->DrawCopy("same");
      //cout  << i << " | " << low << " | " << high << " | " << setprecision(3) << htemp14->GetMean() << " | " << htemp14->GetRMS() << " | " << endl;
      high=low;
      
      h->SetBinContent(i+1,htemp14->GetMean());
      h->SetBinError(i+1,0.01*htemp14->GetRMS());  
    }
  
  TCanvas* c7 = new TCanvas("c7","c7");
  c7->cd();
  h->Draw();
  */
  
  //TFile *outrootfile = new TFile("OutGlauber_Hijing.root","RECREATE");
  TFile *outrootfile = new TFile("test.root","RECREATE");
  outrootfile->cd();
  //h->Write();
  gNpart->Write();
  gNcoll->Write();
  gtAA->Write();
  hd->Write();
  outrootfile->Close();


}
void drawGraphs(TGraphErrors* data, TGraphErrors* mc, const std::string& method, const std::string& xTitle, const std::string& yTitle, const std::string& legendTitle, double lumi, const std::string& outputName, int dataMarkerStyle = 20, int dataMarkerColor = kBlack, int mcMarkerStyle = 29, int mcMarkerColor = kBlue) {

  data->SetMarkerSize(1.5);
  data->SetMarkerStyle(dataMarkerStyle);
  data->SetMarkerColor(dataMarkerColor);
  data->SetLineColor(dataMarkerColor);

  mc->SetMarkerSize(1.5);
  mc->SetMarkerStyle(mcMarkerStyle);
  mc->SetMarkerColor(mcMarkerColor);
  mc->SetLineColor(mcMarkerColor);

  // Fit
  TF1* data_fct = nullptr;
  TF1* mc_fct = nullptr;

  TH1D* errors_data = new TH1D("errors_data", "errors", 100, 0, 1);
  errors_data->SetStats(false);
  errors_data->SetFillColor(LIGHT_GRAY);
  //errors_data->SetLineColor(kRed);
  errors_data->SetFillStyle(1001);

  TH1D* errors_mc = (TH1D*) errors_data->Clone("errors_mc");
  errors_mc->SetFillColor(LIGHT_BLUE);

  if (method == "Balancing") {
    data_fct = new TF1("data_fct", "[0] - x*x*[1]", 0, 1);
    data_fct->SetLineColor(dataMarkerColor);
    data_fct->SetLineWidth(1);
    data_fct->SetLineStyle(2);

    data->Fit(data_fct, "RQN");
    (TVirtualFitter::GetFitter())->GetConfidenceIntervals(errors_data, 0.68);

    mc_fct = new TF1("mc_fct", "[0] - x*x*[1]", 0, 1);
    mc_fct->SetLineColor(mcMarkerColor);
    mc_fct->SetLineWidth(1);
    mc_fct->SetLineStyle(2);

    mc->Fit(mc_fct, "RQN");
    (TVirtualFitter::GetFitter())->GetConfidenceIntervals(errors_mc, 0.68);
  } else {
    data_fct = new TF1("data_fct", "[0] + x*[1]", 0, 1);
    data_fct->SetLineColor(dataMarkerColor);
    data_fct->SetLineWidth(1);
    data_fct->SetLineStyle(2);

    data->Fit(data_fct, "RQN");
    (TVirtualFitter::GetFitter())->GetConfidenceIntervals(errors_data, 0.68);

    mc_fct = new TF1("mc_fct", "[0] + x*[1]", 0, 1);
    mc_fct->SetLineColor(mcMarkerColor);
    mc_fct->SetLineWidth(1);
    mc_fct->SetLineStyle(2);

    mc->Fit(mc_fct, "RQN");
    (TVirtualFitter::GetFitter())->GetConfidenceIntervals(errors_mc, 0.68);

  }

  data_fct->SetRange(0, 1);
  mc_fct->SetRange(0, 1);

  TMultiGraph* mg = new TMultiGraph();
  mg->Add(data);
  mg->Add(mc);

  TString title = TString::Format(";%s;%s", xTitle.c_str(), yTitle.c_str());
  mg->SetTitle(title);

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

  mg->Draw("ap");

  errors_data->Draw("e3 same");
  errors_mc->Draw("e3 same");

  data_fct->Draw("same");
  mc_fct->Draw("same");

  mg->Draw("ap same");


  TLegend* legend = new TLegend(0.18, 0.18, 0.55, 0.35);
  legend->SetTextFont(42);
  legend->SetFillColor(kWhite);
  legend->SetFillStyle(0);
  legend->SetTextSize(0.035);
  legend->SetBorderSize(1);

  TString legendTitleWithPtCut = TString::Format("%s, p_{T}^{#gamma} #geq 170 GeV", legendTitle.c_str());

  legend->SetHeader(legendTitleWithPtCut);
  legend->AddEntry(data, TString::Format("%s (data)", method.c_str()), "p");
  legend->AddEntry(mc, TString::Format("%s (MC)", method.c_str()), "p");
  legend->Draw();

  TLatex tl;
  tl.SetNDC();
  tl.SetTextSize(0.035);
  tl.SetTextFont(42);

  // Luminosity
  TString sLumi = TString::Format("L = %.02f fb^{-1}", lumi);
  tl.DrawLatex(0.18, 0.96, sLumi);

  // Energy
  tl.DrawLatex(0.80, 0.96, "#sqrt{s} = 8 TeV");

  canvas->Print(outputName.c_str());

  delete canvas;
  delete mg;

  delete errors_data;
  delete errors_mc;
}
void BasePlotter::writeStacked(string filename, const HistogramContainer& histContainer, string extension) const
{
    // Check histContainer consistency
    if( ! histContainer.check() ) 
        throw 1;

    if( extension[0] == '.' )
        extension.erase(0,1);
    
    if( filename.find(".root") == string::npos )
    filename.append( ".root" );
    
    system(("mkdir -p " + configContainer.outputDir).c_str()); 
    TFile* f = new TFile((configContainer.outputDir + filename).c_str(), "UPDATE");
    
    unsigned int nSamples = histContainer.reducedNames.size();
    TCanvas *c = new TCanvas(("Canv_stacked_" + histContainer.containerName).c_str(), "", 600, 600 + (120 * configContainer.plotRatio));
    TPad *histPad=nullptr, *ratioPad=nullptr;
    if( configContainer.plotRatio || configContainer.plotSignificance )
    {
        histPad = new TPad("pad1", "pad1", 0, 0.25, 1, 1);
        histPad->Draw();     
        ratioPad = new TPad("pad2", "pad2", 0, 0, 1, 0.3); 
        ratioPad->Draw();
        histPad->cd();
    }    
    
    TLegend* leg = nullptr;
    vector<TLatex*> latexVector;
    setCanvasAttributes( nSamples, leg, latexVector);
    
    vector<TH1F*> hStack;
    TH1* hData = nullptr, *hSignal = nullptr;
    // Add backgrounds to stack
    for( int iSample = nSamples-1; iSample > -1; --iSample )
    {
        if( histContainer.sampleType[iSample] == SampleType::MC || histContainer.sampleType[iSample] == SampleType::FAKELEPTON || histContainer.sampleType[iSample] == SampleType::MCFAKELEPTON )
        {
            TH1F *temp = (TH1F*) histContainer.histograms[iSample]->Clone(("stack_hist_"+histContainer.reducedNames[iSample]).c_str());
            if( hStack.size() > 0 ) temp->Add(hStack[hStack.size()-1]);
            temp->SetLineColor(histContainer.color[iSample]);
            temp->SetFillColor(histContainer.color[iSample]);
            temp->SetFillStyle(1001);
            hStack.push_back(temp);
            string legendEntry = histContainer.reducedNames[iSample];
            replace(legendEntry.begin(), legendEntry.end(), '_', ' ');
            leg->AddEntry(temp,legendEntry.c_str(),"f");
        }
    }
    
    // Add signal to stack
    for( unsigned int iSample = 0; iSample < nSamples; ++iSample )
    {
        if( histContainer.sampleType[iSample] == SampleType::SIGNAL )
        {
            hSignal = histContainer.histograms[iSample];
            hSignal->SetLineColor(histContainer.color[iSample]);
            string legendEntry = histContainer.reducedNames[iSample];
            replace(legendEntry.begin(), legendEntry.end(), '_', ' ');
            if( configContainer.signalStacked )
            {
                TH1F *temp = (TH1F*) histContainer.histograms[iSample]->Clone(("stack_hist_"+histContainer.reducedNames[iSample]).c_str());
                if( hStack.size() > 0 ) temp->Add(hStack[hStack.size()-1]);
                temp->SetFillColor(histContainer.color[iSample]);
                temp->SetFillStyle(1001);
                hStack.push_back(temp);
                leg->AddEntry(temp,legendEntry.c_str(),"f");
            }
            else
            {
                hSignal->SetLineWidth(2);
                leg->AddEntry(hSignal,legendEntry.c_str(),"l");
            }
        }
    }
    
    // Add data
    for( unsigned int iSample = 0; iSample < nSamples; ++iSample )
    {
        if( histContainer.sampleType[iSample] == SampleType::DATA && configContainer.unblind )
        {
            histContainer.histograms[iSample]->SetLineColor(histContainer.color[iSample]);
            histContainer.histograms[iSample]->SetMarkerColor(histContainer.color[iSample]);
            histContainer.histograms[iSample]->SetMarkerSize(1);
            histContainer.histograms[iSample]->SetMarkerStyle(20);
            histContainer.histograms[iSample]->SetLineWidth(2);
            string legendEntry = histContainer.reducedNames[iSample];
            replace(legendEntry.begin(), legendEntry.end(), '_', ' ');
            leg->AddEntry(histContainer.histograms[iSample],legendEntry.c_str(),"lp");
            hData = histContainer.histograms[iSample];
        }
    }

    // Set y-range
    float hMax = 0.;
    float hMin = 0.;
    bool maxMakesSense = true;
    if( configContainer.drawNormalized )
        hMax = 1;
    else
    {
        if ( hStack.size() > 0 ) 
            hMax = getMaximumIncludingErrors(hStack[hStack.size()-1]);
        if ( hData ) 
            hMax = max( getMaximumIncludingErrors(hData) , hMax ); 
        if ( hSignal ) 
            hMax = max( getMaximumIncludingErrors(hSignal) , hMax ); 
    }
    
    // Check consistency (for efficiency plot with fixed axis)
    if( histContainer.axisRanges.size() > 0 && hMax > histContainer.axisRanges[1] )
        maxMakesSense = false;
    
    if( configContainer.logY ) 
    {
        c->SetLogy(1);
        hMin = 0.05;
        hMax *= 500;
    }
    else
        hMax *= 1.55;
    if( histContainer.axisRanges.size() > 0 )
    {
        if( maxMakesSense && (!configContainer.drawNormalized) )
        {
            hMin = histContainer.axisRanges[0];
            hMax = histContainer.axisRanges[1];
        }
        else 
        {
            cout << "Maximum range is too small for: " << histContainer.containerName << ". Set to default.\n";
        }
    }
    
        
    // Draw stack
    for( int iHist = hStack.size()-1; iHist > -1; --iHist )
    {
        if( configContainer.drawNormalized )
        {
            hStack[iHist]->Scale(1./hStack[iHist]->Integral());
            hStack[iHist]->GetYaxis()->SetRangeUser(hMin, getMaximumIncludingErrors(hStack[iHist])*1.5);
        }
        else
            hStack[iHist]->GetYaxis()->SetRangeUser(hMin, hMax);
        hStack[iHist]->Draw("hist same");
    }
    
    // Draw uncertainty
    TH1F* hErr;
    if( configContainer.drawUncertainty && hStack.size() > 0 )
    {
        hErr = (TH1F*) hStack[hStack.size()-1]->Clone("uncertainty") ;
        hErr->SetFillColor(15);
        hErr->SetLineColor( 0);
        hErr->SetFillStyle(3445);
        hErr->SetMarkerSize(0);
//         hErr->SetMarkerColor(kBlack);
        hErr->Draw("e2 same");
//         leg->AddEntry( hErr , TString(" stat.#oplussyst.") , "f");
        leg->AddEntry( hErr , TString("stat. error") , "f");
    }
    
    // Draw signal
    if( hSignal && !configContainer.signalStacked ) 
    {
        if( configContainer.drawNormalized )
        {
            hSignal->Scale(1./hSignal->Integral());
            hSignal->GetYaxis()->SetRangeUser(hMin, getMaximumIncludingErrors(hSignal)*1.5);
        }
        else
            hSignal->GetYaxis()->SetRangeUser(hMin, hMax);
        hSignal->Draw("e same");
    }
    
    // Draw data
    if( hData ) 
    {
        if( configContainer.drawNormalized )
        {
            hData->Scale(1./hData->Integral());
            hData->GetYaxis()->SetRangeUser(hMin, getMaximumIncludingErrors(hData)*1.5);
        }
        else
            hData->GetYaxis()->SetRangeUser(hMin, hMax);
        hData->Draw("e same");
    }
   
    // Draw legend
    leg->Draw(); 
    for( auto* text : latexVector )
    {
        text->Draw("same");
    }
    
    // Redraw axis
    gPad->RedrawAxis();
    
    // Draw Ratio plot
    if( configContainer.plotRatio && hStack.size() > 0 && (hData || (hSignal && !configContainer.signalStacked)) ) {
        ratioPad->cd();

        TH1F* hRatio;
        if( hData ) 
        {
           hRatio = (TH1F*) hData->Clone("ratio");
           hRatio->GetYaxis()->SetTitle("Data / MC"); 
        }
        else
        {
            hRatio = (TH1F*) hSignal->Clone("ratio");
            hRatio->GetYaxis()->SetTitle("Signal / Background"); 
        }
        
//         if( configContainer.signalStacked || !hData )
//             hRatio->Divide(hStack[hStack.size()-1]);
//         else
//         {
            TH1F* hAllMC = (TH1F*) hStack[hStack.size()-1]->Clone("allMC");
//             hAllMC->Add( hSignal );
            hRatio->Divide(hAllMC);
//         }

        hRatio->GetYaxis()->SetRangeUser(0, 2); 
        hRatio->Draw("ep");
        hRatio->GetXaxis()->SetTitle(""); 
                        
        TLine *line = new TLine(hRatio->GetXaxis()->GetXmin(),1,hRatio->GetXaxis()->GetXmax(),1);
        line->SetLineStyle(3);
        line->Draw();
        
        // Print global ratio
        if( hData )
            cout << "Data / MC: " << hData->Integral()/hStack[hStack.size()-1]->Integral() << endl;
        else
            cout << "Signal / Background: " << hSignal->Integral()/hStack[hStack.size()-1]->Integral() << endl;
    }
    
    //Draw significance plot
    if( configContainer.plotSignificance && !configContainer.plotRatio && hStack.size() > 0 && hSignal && !configContainer.signalStacked ) {
        ratioPad->cd();
        TH1F* hRatio = (TH1F*) hSignal->Clone("ratio");
        hRatio->GetYaxis()->UnZoom();
        unsigned int nBins = hRatio->GetNbinsX();
        for( unsigned int iBin = 1; iBin <= nBins; ++iBin ) 
        {
            float denom = sqrt(hRatio->GetBinContent(iBin)+hStack[hStack.size()-1]->GetBinContent(iBin));
            if( denom > 0 ) 
            {
                hRatio->SetBinContent(iBin, hRatio->GetBinContent(iBin)/denom);
                float S = hSignal->GetBinContent(iBin), B = hStack[hStack.size()-1]->GetBinContent(iBin);
                hRatio->SetBinError(iBin, sqrt( pow(S/2./pow(B+S,1.5),2) * pow(hSignal->GetBinError(iBin),2) + pow((B+S/2.)/pow(B+S,1.5),2) * pow(hStack[hStack.size()-1]->GetBinError(iBin),2)) );
            }
            else
            {
                hRatio->SetBinContent(iBin, 0);
                hRatio->SetBinError(iBin, 0);
            }
        }

//         hRatio->GetYaxis()->SetRangeUser(0, 2); 
        hRatio->Draw("ep");
        hRatio->GetYaxis()->SetTitle("S / #sqrt{S+B}"); 
        hRatio->GetXaxis()->SetTitle(""); 
    }
    
    // Redraw axis
    gPad->RedrawAxis();
    
    c->Print((configContainer.outputDir + histContainer.containerName + "." + extension).c_str(), extension.c_str());
    cout << "Wrote plot " << (histContainer.containerName + "." + extension) << endl;
    c->Write();
    f->Close();
}
Exemple #4
0
void view()
{
  TFile* f = TFile::Open("result.root");

  int signalColorTable[20], backgroundColorTable[20];

  for ( int i=0; i<20; ++i )
  {
    signalColorTable[i] = kAzure+10-i;
    backgroundColorTable[i] = kOrange+10-i;
  }

  TList* signalPlots = makePlots((TDirectory*)f->Get("MC_Signal_EMEM"), signalColorTable);
  TList* backgroundPlots = makePlots((TDirectory*)f->Get("MC_Background_EMEM"), backgroundColorTable, true);

  if ( signalPlots == 0 || backgroundPlots == 0 ) return;

  const int nPlots = signalPlots->GetSize();
  for ( int i=0; i<nPlots; ++i )
  {
    THStack* hSignal = (THStack*)signalPlots->At(i);
    THStack* hBackground = (THStack*)backgroundPlots->At(i);

    TString histName = hSignal->GetName();
    bool doLog = histName.Contains("Pt");// || histName.Contains("RelIso");

    TCanvas* c = new TCanvas(TString("c")+hSignal->GetName(), hSignal->GetTitle(), 1200, 600);
    TPad* pad;

    c->Divide(2,1);

    TString xTitle, yTitle;

    pad = (TPad*)c->cd(1);
    if ( doLog ) pad->SetLogy();
    pad->SetBorderSize(0);
    pad->SetBorderMode(0);
    hBackground->Draw();

    xTitle = ((TH1*)hBackground->GetHists()->At(0))->GetXaxis()->GetTitle();
    yTitle = ((TH1*)hBackground->GetHists()->At(0))->GetYaxis()->GetTitle();
    hBackground->GetXaxis()->SetTitle(xTitle);
    hBackground->GetYaxis()->SetTitle(yTitle);

    pad->BuildLegend(0.6, 0.6, 0.98, 0.98);

    pad = (TPad*)c->cd(2);
    if ( doLog ) pad->SetLogy();
    pad->SetBorderSize(0);
    pad->SetBorderMode(0);
    hSignal->Draw("nostack");

    xTitle = ((TH1*)hSignal->GetHists()->At(0))->GetXaxis()->GetTitle();
    yTitle = ((TH1*)hSignal->GetHists()->At(0))->GetYaxis()->GetTitle();
    hSignal->GetXaxis()->SetTitle(xTitle);
    hSignal->GetYaxis()->SetTitle(yTitle);

    pad->BuildLegend(0.6, 0.7, 0.98, 0.98);

    c->Print(TString(c->GetName())+".png");
  }
}
void tagAndProbePlotsRun2012_MCdataCom_IsoMu24eta2p1(bool save=false, bool saveRoot=false)
{
  /// decide whether to do 1D or 2D plots or both
  bool do1D = true;
  bool do2D = true;
  
  /// set style
  // ============================
  //  Set ROOT Style
  // ============================
 
  gROOT->Reset();
//   gROOT->SetStyle("Plain");
//   
//   TStyle myStyle("HHStyle","HHStyle");
//   setHHStyle(myStyle);
//   TGaxis::SetMaxDigits(2);
//   myStyle.cd();
//   gROOT->SetStyle("HHStyle");
//   gROOT->ForceStyle();  
  
//   gStyle->SetLineScalePS(1);
  
  gStyle->SetOptStat(0);
  gStyle->SetTitleBorderSize(0);
  gStyle->SetLegendBorderSize(0);
  gStyle->SetPadBottomMargin(0.11);
  gStyle->SetLabelSize(0.05,"XY");
  gStyle->SetTitleSize(0.05,"XY");
  gStyle->SetFillColor(0);
  gStyle->SetPadTickX(1);  // To get tick marks on the opposite side of the frame
  gStyle->SetPadTickY(1);
  
//   const int fontstyle1=62;
  const int fontstyle1=42;
  gStyle->SetTitleFont(fontstyle1);
  gStyle->SetTitleFont(fontstyle1, "XYZ");
  gStyle->SetLabelFont(fontstyle1, "XYZ");
  gStyle->SetTextFont(fontstyle1);
  
  // for 2D histo text
  gStyle->SetPaintTextFormat("3.3f");
  gStyle->SetPalette(1);
  
  /// path where input files are stored
  TString inputPathScratch  ="/afs/naf.desy.de/group/cms/scratch/tophh/efficiencies";
  TString inputPath535      ="/afs/naf.desy.de/user/j/jlange/nafscratch/top/CMSSW_5_3_5/src/TopAnalysis/Configuration/analysis/fullLeptonic";
  TString inputPathDust     ="/scratch/hh/dust/naf/cms/user/jlange/output_5_3";
  
  TString outputFolder   = "/afs/desy.de/user/j/jlange/analysis/tagAndProbe/plots/2012/singleMu";
//  TString outputFolder   = "/afs/desy.de/user/j/jlange/analysis/tagAndProbe/plots/2011/singleMu/Fall11/DataMCcomp_IsoMu17-24_relIsoL0p2";
  
   TString outputFileName = "/DataMCcomp_IsoMu24eta2p1_";
//  TString outputFileName = "/DataMCcomp_IsoMu17-24_relIsoL0p2_";

  TString fileFormatArr []= {"root", "png", "eps"};
  std::vector<TString> fileFormat(fileFormatArr, fileFormatArr + sizeof(fileFormatArr)/sizeof(TString));
  
  /// if set to 0: all plots (probe, test, eff) are drawn; to 1: only eff plots
  int onlyEffPlots =1;
  /// method ID of MC file to normalise scale factors to
  TString mIDnorm = "m1";
  std::cout<< "Efficiency wrt. which SF is supposed to be normalized " <<  mIDnorm << std::endl;

  
   /// map with structure that keeps features of methods, like file, filename, legend etc.
  std::map<TString, method*> method_;

  /// standard for nice plots:
//   TString mIDarr []= {"m1","m2"};
  /// for different PU scenarios: (also savable in root file)
  TString mIDarr []= {"m1", "m1PUup", "m1PUdown", "m2", "m2PUup", "m2PUdown"};

  std::vector<TString> mID(mIDarr, mIDarr + sizeof(mIDarr)/sizeof(TString));
  int mIDNum = mID.size();
  std::cout<< "Number of considered methods (i.e. files): " <<  mIDNum << std::endl;
  
  // check if mIDnorm is in vector and give error if not
  bool inVector=false;
  for(int i=0; i< mIDNum; i++) if(mID[i]==mIDnorm) inVector=true;
  if(!inVector) {
    std::cout<<"ERROR!!!! Efficiency wrt. which SF is supposed to be normalized is not in mID vector!!! "<<std::endl; 
    return;
  }
  
  TString fileName ;
  
    /// Define histo and legend styles and options
//   int lineStyle   []= {1,1,1,1,1,1};
//   int lineColor   []= {2,1,4,kGreen+2,kGray+2,3};
//   int markerStyle []={1,21,22,20,22,23};
//   int markerColor []= {2,1,4,kGreen+2,kGray+2,3};
//   TString drawOpt []= {"","E X0 P same","E X0 P same","E X0 same","E X0 same","E same"};
//   TString legOpt  []= {"L","P","P","P","P","P"};
//   bool legOnPlot = false;
  
  /// Define pt and eta cuts for TH2 
  /// TCut does not work for TH2
  double cutPt2D  = 33.;
  double cutEta2D = 2.1;
  
  /// Constructor for struct method(TString iniFileName, TString iniLegName, int iniLineStyle, int iniLineColor, int iniMarkerStyle, int iniMarkerColor, TString iniDrawOpt, TString iniLepOpt, TString source)
  
   /// Summer12 MC
  fileName=inputPathScratch+"/analyzeZMuMuTagAndProbeMCSummer12_HLT_IsoMu24_eta2p1.root";
  method_["m1"] = new method(fileName, "Simulation IsoMu24eta2p1", 1, 2, 1, 1, "E", "L", "treeV2","probePt>33. && TMath::Abs(probeEta)<2.1","eventWeightPUeventWeightPU","m1");
  
  method_["m1PUup"] = new method(fileName, "Simulation IsoMu24eta2p1 PUrew UP", 1, 2, 1, 1, "E", "L", "treeV2","probePt>33. && TMath::Abs(probeEta)<2.1","eventWeightPUsysUpeventWeightPUUp","m1PUup");
  
  method_["m1PUdown"] = new method(fileName, "Simulation IsoMu24eta2p1 PUrew DOWN", 1, 2, 1, 1, "E", "L", "treeV2","probePt>33. && TMath::Abs(probeEta)<2.1","eventWeightPUsysDowneventWeightPUDown","m1PUdown");
  
  /// data
  fileName=inputPathScratch+"/analyzeZMuMuTagAndProbeRun2012ABCDJan22ReReco_HLT_IsoMu24eta2p1.root";
  method_["m2"] = new method(fileName, "Data IsoMu24eta2p1", 1, 1, 21, 1, "E", "L", "treeV2","probePt>33. && TMath::Abs(probeEta)<2.1","","m1");
  
  method_["m2PUup"] = new method(fileName, "Data IsoMu24eta2p1 PU up", 1, 1, 24, 1, "E", "LP", "treeV2","probePt>33. && TMath::Abs(probeEta)<2.1","","m1PUup");
  
  method_["m2PUdown"] = new method(fileName, "Data IsoMu24eta2p1 PU down", 1, 1, 26, 1, "E", "LP", "treeV2","probePt>33. && TMath::Abs(probeEta)<2.1","","m1PUdown");
  

  
  /// different tap studies (different efficiencies)
//    const int folderNum=4;
//    TString folderID[]={"tapTrkQ", "tapIso", "tapTotalSelection", "tapTrigger"};
//    TString foldersTitle[]={"Muon ID", "Muon Isolation", "Muon Selection", "Muon Trigger"};
  
//   const int folderNum=3;
//   TString folderID[]={"tapTotalSelection", "tapTrigger", "tapAll"};
//   TString foldersTitle[]={"Muon Selection", "Muon Trigger", "Combined Muon Selection and Trigger"};
  
 /// to combine selection and trigger efficiencies use tapAll:
  const int folderNum=1;
  TString folderID[]={"tapAll"};
  TString foldersTitle[]={"Combined Selection and Trigger"};
  
//   const int folderNum=1;
//   TString folderID[]={"tapTrigger"};
//   TString foldersTitle[]={"Muon Trigger"};
  
//   const int folderNum=2;
//   TString folderID[]={"tapTotalSelection", "tapTrigger"};
//   TString foldersTitle[]={"Muon Selection", "Muon Trigger"};
  
//     const int folderNum=1;
//     TString folderID[]={"tapIso"};
//     TString foldersTitle[]={"Isolation"};


  /// effName = name of the effHisto; variables: corresponding variable to effName; cuts: corresponding cut to effName

//     TString effIDarr[]      = {"Control", "Pt", "Eta", "RelIso", "PVMult", "Mult", "MinDR","Pt_inclLegend"};
  TString effIDarr[]      = {"Control", "Pt", "Eta", "PVMult", "MinDR", "EtaPt33to40", "EtaPt40to50", "EtaPtGreater50"};
//  TString effIDarr[]      = {"Control", "Pt", "Eta", "EtaPt33to45", "EtaPtGreater45"};
   //TString effIDarr[]      = {"Pt_inclLegend"};
   //TString effIDarr[]      = {"Control", "Pt", "Eta", "RelIso", "PVMult", "Mult", "MinDR","lepLepMass"};
  //TString effIDarr[]      = {"Control", "Pt", "Eta", "RelIso", "PVMult", "Mult", "PtEta0to1p5", "PtEta1p5to2p1"};
  //TString effIDarr[]      = {"Pt", "Eta", "RelIso", "PVMult", "Mult", "MinDR"};
//   TString effIDarr[]      = {"Pt"};
  std::vector<TString> effID(effIDarr, effIDarr + sizeof(effIDarr)/sizeof(TString));
  int effIDNum = effID.size();
  std::cout<< "Number of considered plots: " <<  effIDNum << std::endl;
  
  
  TString effIDarr2[]      = {};
  //TString effIDarr2[]      = {"PtEta0to1p2", "PtEta1p2to2p1", "EtaPt33to45", "EtaPt45to60", "EtaPtGreater60", "PtMedian", "Pt3bins"};
  std::vector<TString> effID2(effIDarr2, effIDarr2 + sizeof(effIDarr2)/sizeof(TString));
  int effIDNum2 = effID2.size();
  std::cout<< "Number of considered plots 2: " <<  effIDNum2 << std::endl;
    
  /// map with structure that keeps features of histograms
  std::map<TString, std::map<TString, eff*> > eff_;
  std::map<TString, eff2D*> eff2DPtEta_;
  
  /// title for histo, x and y axis (separated by "/")
  TString title0 ="";
  TString title ="";
  
  /// axis range
  //double yLo = 0.5, yHi = 1.1;
  double yLo = 0.45, yHi = 1.;
  double yLoSF = 0.9, yHiSF = 1.1-0.0001;
  
  /// Constructor for struct eff(TString iniVar, T  iniCuts, TString iniBins, TString iniTitles, double iniYLo=-9999., double iniYHi=-9999., double iniXLo=-9999., double iniXHi=-9999.)
  TCut cutPt  = "probePt>33."; // && probeRelIso<0.2 "; /*"(probePt>33. || testPt>33. )";*/
  TCut cutEta = "TMath::Abs(probeEta)<2.1"; // && probeRelIso<0.2 "; /*"(TMath::Abs(probeEta)<2.1 || TMath::Abs(testEta)<2.1)";*/
  TCut cutPtEta = cutPt && cutEta;
  for(int iFolder=0; iFolder < folderNum; iFolder++){
    title = foldersTitle[iFolder]+" Efficiency/ / ";
    eff_["Control"][folderID[iFolder]]        =new eff("Control", cutPtEta, mBinsControl, binsControl_, title, yLo, yHi, -9999.,-9999.);
    title = foldersTitle[iFolder]+" Efficiency/p_{T} [GeV]/ ";
    eff_["Pt"][folderID[iFolder]]             =new eff("Pt", cutEta, mBinsPt, binsPtAN_, title, yLo, yHi, 33.,200.);
    title = foldersTitle[iFolder]+" Efficiency/p_{T} [GeV]/ ";
    eff_["Pt_inclLegend"][folderID[iFolder]]             =new eff("Pt", cutEta, mBinsPt, binsPtAN_, title, yLo, yHi, 33.,200.,true);
    title = foldersTitle[iFolder]+" Efficiency/#eta/ ";
    eff_["Eta"][folderID[iFolder]]             =new eff("Eta", cutPt, mBinsEta, binsEta_, title, yLo, yHi,-2.1,2.1);
    title = foldersTitle[iFolder]+" Efficiency/relIso/ ";
    eff_["RelIso"][folderID[iFolder]]          =new eff("RelIso", cutPtEta, mBinsRelIso, binsRelIso_, title, yLo, yHi);
    title = foldersTitle[iFolder]+" Efficiency/absIso/ ";
    eff_["AbsIso"][folderID[iFolder]]          =new eff("AbsIso", cutPtEta, mBinsAbsIso, binsAbsIso_, title, yLo, yHi);
    title = foldersTitle[iFolder]+" Efficiency/N_{PV}/ ";
    eff_["PVMult"][folderID[iFolder]]          =new eff("PVMult", cutPtEta, mBinsPVMult, binsPVMult_, title, yLo, yHi,0.,40.);
    title = foldersTitle[iFolder]+" Efficiency/N_{jet}/ ";
    eff_["Mult"][folderID[iFolder]]            =new eff("Mult", cutPtEta, mBinsMult, binsMult_, title, yLo, yHi);
    title = foldersTitle[iFolder]+" Efficiency/Minimum #DeltaR(#mu,jet)/ ";
    eff_["MinDR"][folderID[iFolder]]            =new eff("MinDR", cutPtEta&& "probeRelIso<0.2", mBinsMinDR, binsMinDR_, title, yLo, yHi, 0., 5.);
    title = foldersTitle[iFolder]+" Efficiency/Minimum M_{lep,lep}/ ";
    eff_["lepLepMass"][folderID[iFolder]]            =new eff("lepLepMass", cutPtEta, mBinsLepLepMass, binsLepLepMass_, title, yLo, yHi);
    
    title = foldersTitle[iFolder]+" Efficiency, 0<#eta<1.2/p_{T} [GeV]/ ";
    eff_["PtEta0to1p2"][folderID[iFolder]]             =new eff("Pt", "TMath::Abs(probeEta)<1.2", mBinsPt, binsPt_, title, yLo, yHi, 33.,200.);
    
    title = foldersTitle[iFolder]+" Efficiency 1.2<#eta<2.1/p_{T} [GeV]/ ";
    eff_["PtEta1p2to2p1"][folderID[iFolder]]             =new eff("Pt", "TMath::Abs(probeEta)>1.2 && TMath::Abs(probeEta)<2.1", mBinsPt, binsPt_, title, yLo, yHi, 33.,200.,true);
    
    title = foldersTitle[iFolder]+" Efficiency, 33<p_{T}<40/#eta/ ";
    eff_["EtaPt33to40"][folderID[iFolder]]             =new eff("Eta", "probePt>33. && probePt<45.", mBinsEta, binsEta_, title, yLo, yHi);
    
    
    title = foldersTitle[iFolder]+" Efficiency, 40<p_{T}<50/#eta/ ";
    eff_["EtaPt40to50"][folderID[iFolder]]             =new eff("Eta", "probePt>40. && probePt<50.", mBinsEta, binsEta_, title, yLo, yHi);
    
    title = foldersTitle[iFolder]+" Efficiency, 50<p_{T}/#eta/ ";
    eff_["EtaPtGreater50"][folderID[iFolder]]             =new eff("Eta", "probePt>50.", mBinsEta, binsEta_, title, yLo, yHi);
    
    title = foldersTitle[iFolder]+" Efficiency AN/p_{T} [GeV]/ ";
    eff_["PtAN"][folderID[iFolder]]             =new eff("Pt", cutEta, mBinsPt, binsPtAN_, title, yLo, yHi, 33.,200.);
    
    title = foldersTitle[iFolder]+" Efficiency Median/p_{T} [GeV]/ ";
    eff_["PtMedian"][folderID[iFolder]]             =new eff("Pt", cutEta, mBinsPt, binsPtMedian_, title, yLo, yHi, 33.,200.);
    
    title = foldersTitle[iFolder]+" Efficiency 3 bins/p_{T} [GeV]/ ";
    eff_["Pt3bins"][folderID[iFolder]]             =new eff("Pt", cutEta, mBinsPt, binsPt3bins_, title, yLo, yHi, 33.,200.);
    
    /// 2D pt:eta
    title = foldersTitle[iFolder]+" Efficiency/p_{T} [GeV]/#eta/ ";
    eff2DPtEta_[folderID[iFolder]]             =new eff2D("Pt", "Eta", cutPtEta, mBinsPtMu2D, binsPtMu2D_, mBinsEtaMu2D, binsEtaMu2D_, title, yLo, yHi, 33.+0.001,200.-0.001, -2.1+0.001, 2.1-0.001);
  }

  /// ---
  /// get efficiencies from tree or histo
  ///  ---
  for(int iMethod=0; iMethod<mIDNum; iMethod++){
    /// 1D
    if(do1D){
      for(int iEff=0; iEff<effIDNum; iEff++){
	for(int iFolder=0; iFolder<folderNum; iFolder++){
	  getEfficiencies(eff_[effID[iEff]][folderID[iFolder]], method_[mID[iMethod]], mID[iMethod], folderID[iFolder], folderID[iFolder]);
	}
      }
      for(int iEff=0; iEff<effIDNum2; iEff++){
	for(int iFolder=0; iFolder<folderNum; iFolder++){
	  getEfficiencies(eff_[effID2[iEff]][folderID[iFolder]], method_[mID[iMethod]], mID[iMethod], folderID[iFolder], folderID[iFolder]);
	}
      }
    }
    /// 2D
    if(do2D){
      for(int iFolder=0; iFolder<folderNum; iFolder++){
	getEfficiencies2D(eff2DPtEta_[folderID[iFolder]], method_[mID[iMethod]], mID[iMethod], folderID[iFolder], folderID[iFolder], cutPt2D, cutEta2D);
      }
    }
  }

 /// Draw one Canvas for each folder comparing different methods.
 /// Each canvas shows test (1st row) and probe collection (2nd) and efficiency (3rd) for different variables (columns)
  TCanvas* CanvComp [folderNum];
  TCanvas* CanvSFComp [folderNum];
  TCanvas* CanvEffAndSFComp [folderNum];
  TCanvas* CanvEvtsComp [folderNum];
  TCanvas* CanvEvtsNormComp [folderNum];
  TCanvas* CanvLeg = new TCanvas("CanvLeg", "CanvLeg", 350,200);
  
  TCanvas* CanvComp2 [folderNum];
  TCanvas* CanvSFComp2 [folderNum];
  
  TCanvas* CanvComp2DPtEta [folderNum];
  TCanvas* CanvComp2DPtEtaSF [folderNum];
  TCanvas* CanvComp2DPtEtaSFerr [folderNum];
  TCanvas* CanvComp2DPtEtaPass [folderNum];
  TCanvas* CanvComp2DPtEtaAll [folderNum];

  std::cout<< "Drawing eff. and SF"<<std::endl;
  for(int iFolder=0; iFolder<folderNum; iFolder++) {

    CanvComp[iFolder] = new TCanvas("Comparison"+folderID[iFolder], "Comparison"+folderID[iFolder], 1700,1000);
    CanvSFComp[iFolder] = new TCanvas("ComparisonSF"+folderID[iFolder], "ComparisonSF"+folderID[iFolder], 1700,1000);
    CanvEffAndSFComp[iFolder] = new TCanvas("ComparisonEffAndSF"+folderID[iFolder], "ComparisonEffAndSF"+folderID[iFolder], 1700,1000);
    CanvEvtsComp[iFolder] = new TCanvas("ComparisonEvts"+folderID[iFolder], "ComparisonEvts"+folderID[iFolder], 1700,1000);
    CanvEvtsNormComp[iFolder] = new TCanvas("ComparisonEvtsNorm"+folderID[iFolder], "ComparisonEvtsNorm"+folderID[iFolder], 1700,1000);
    
    CanvComp2[iFolder] = new TCanvas("Comparison2"+folderID[iFolder], "Comparison2"+folderID[iFolder], 1700,1000);
    CanvSFComp2[iFolder] = new TCanvas("ComparisonSF2"+folderID[iFolder], "ComparisonSF2"+folderID[iFolder], 1700,1000);
    
    CanvComp[iFolder]->Divide(4,2);
    CanvSFComp[iFolder]->Divide(4,2);
    CanvEffAndSFComp[iFolder]->Divide(4,2);
    CanvEvtsComp[iFolder]->Divide(4,2);
    CanvEvtsNormComp[iFolder]->Divide(4,2);
    
    CanvComp2[iFolder]->Divide(4,2);
    CanvSFComp2[iFolder]->Divide(4,2);
    
    /// 1D
    if(do1D){
      for(int iEff=0; iEff<effIDNum; iEff++){
	CanvComp[iFolder]->cd(iEff+1);
// 	std::cout<< "Drawing eff."<<std::endl;
// 	drawEfficiencies(eff_[effID[iEff]][folderID[iFolder]], method_, mID, 0.12,0.15,1.0,0.45,eff_[effID[iEff]][folderID[iFolder]]->drawLegend);
// 	CanvSFComp[iFolder]->cd(iEff+1);
// 	std::cout<< "Drawing SF"<<std::endl;
// 	drawSF          (eff_[effID[iEff]][folderID[iFolder]], method_, mID, mIDnorm, 0.12,0.15,1.0,0.45,eff_[effID[iEff]][folderID[iFolder]]->drawLegend, yLoSF, yHiSF, eff_[effID[iEff]][folderID[iFolder]]->xLo, eff_[effID[iEff]][folderID[iFolder]]->xHi);
	
	std::cout<< "Drawing Eff. and SF"<<std::endl;
	CanvEffAndSFComp[iFolder]->cd(iEff+1);
	drawEffAndSFinOne (eff_[effID[iEff]][folderID[iFolder]], method_, mID, mIDnorm, 0.12,0.15,1.0,0.45,eff_[effID[iEff]][folderID[iFolder]]->drawLegend, yLoSF, yHiSF, eff_[effID[iEff]][folderID[iFolder]]->xLo, eff_[effID[iEff]][folderID[iFolder]]->xHi);
        /// if desired plot also raw event number histos
	if(onlyEffPlots!=1) {
	  std::cout<< "Drawing event numbers"<<std::endl;
	  CanvEvtsComp[iFolder]->cd(iEff+1);
	  drawEventHistos(eff_[effID[iEff]][folderID[iFolder]], method_, mID, 0.12,0.15,1.0,0.45,eff_[effID[iEff]][folderID[iFolder]]->drawLegend);
	  CanvEvtsNormComp[iFolder]->cd(iEff+1);
	  drawEventHistos(eff_[effID[iEff]][folderID[iFolder]], method_, mID, 0.12,0.15,1.0,0.45,eff_[effID[iEff]][folderID[iFolder]]->drawLegend,"normInt");
	}
      }
      for(int iEff=0; iEff<effIDNum2; iEff++){
	CanvComp2[iFolder]->cd(iEff+1);
        // CanvComp[iFolder]->cd(iEff+1)->SetGrid(1,1);
	std::cout<< "Drawing eff. 2"<<std::endl;
	drawEfficiencies(eff_[effID2[iEff]][folderID[iFolder]], method_, mID, 0.12,0.15,1.0,0.45,eff_[effID2[iEff]][folderID[iFolder]]->drawLegend);
	CanvSFComp2[iFolder]->cd(iEff+1);
	std::cout<< "Drawing SF"<<std::endl;
	drawSF          (eff_[effID2[iEff]][folderID[iFolder]], method_, mID, mIDnorm, 0.12,0.15,1.0,0.45,eff_[effID2[iEff]][folderID[iFolder]]->drawLegend, yLoSF, yHiSF, eff_[effID2[iEff]][folderID[iFolder]]->xLo, eff_[effID2[iEff]][folderID[iFolder]]->xHi);
      }
    }
    /// draw 2D efficiencies
    if(do2D){

      CanvComp2DPtEta[iFolder] = new TCanvas("Comparison2DPtEta"+folderID[iFolder], "Comparison2DPtEta"+folderID[iFolder], 1700,1000);
      CanvComp2DPtEta[iFolder]->Divide((mIDNum+1)/2,2);
      
      CanvComp2DPtEtaSF[iFolder] = new TCanvas("Comparison2DPtEtaSF"+folderID[iFolder], "Comparison2DPtEtaSF"+folderID[iFolder], 1700,1000);
      CanvComp2DPtEtaSF[iFolder]->Divide((mIDNum+1)/2,2);
      
      CanvComp2DPtEtaSFerr[iFolder] = new TCanvas("Comparison2DPtEtaSFerr"+folderID[iFolder], "Comparison2DPtEtaSFerr"+folderID[iFolder], 1700,1000);
      CanvComp2DPtEtaSFerr[iFolder]->Divide((mIDNum+1)/2,2);
      
      CanvComp2DPtEtaPass[iFolder] = new TCanvas("Comparison2DPtEtaPass"+folderID[iFolder], "Comparison2DPtEtaPass"+folderID[iFolder], 1700,1000);
      CanvComp2DPtEtaPass[iFolder]->Divide((mIDNum+1)/2,2);
      
      CanvComp2DPtEtaAll[iFolder] = new TCanvas("Comparison2DPtEtaAll"+folderID[iFolder], "Comparison2DPtEtaAll"+folderID[iFolder], 1700,1000);
      CanvComp2DPtEtaAll[iFolder]->Divide((mIDNum+1)/2,2);
      
      std::cout<< "Drawing 2D Pt Eta Eff."<<std::endl;
      for(unsigned int iMethod=0; iMethod<mID.size(); iMethod++){
	CanvComp2DPtEta[iFolder]->cd(iMethod+1);
	eff2DPtEta_[folderID[iFolder]]->his[mID[iMethod]]->Draw("colz text");
	
	CanvComp2DPtEtaPass[iFolder]->cd(iMethod+1);
	eff2DPtEta_[folderID[iFolder]]->hisPass[mID[iMethod]]->Draw("colz text");
	
	CanvComp2DPtEtaAll[iFolder]->cd(iMethod+1);
	eff2DPtEta_[folderID[iFolder]]->hisAll[mID[iMethod]]->Draw("colz text");

	/// 2D SF!!!
	std::cout<< "Drawing 2D SF"<<std::endl;
	
	CanvComp2DPtEtaSF[iFolder]->cd(iMethod+1);
	getSF2D (eff2DPtEta_[folderID[iFolder]], method_, mID, mIDnorm, 0.8, 1.2);
	eff2DPtEta_[folderID[iFolder]]->hisSF[mID[iMethod]]->Draw("colz text");
	
	CanvComp2DPtEtaSFerr[iFolder]->cd(iMethod+1);
	eff2DPtEta_[folderID[iFolder]]->hisSFerr[mID[iMethod]]->Draw("colz text");
      }
    }
    
  // draw legend
    CanvLeg->cd();
    if(iFolder==0) drawLegend(eff_[effID[0]][folderID[0]], method_, mID, 0.,0.,1.,1.);
  
//   effControl[iMethod][iFolder]->GetXaxis()->SetNdivisions(0);
//   effRelIso[iMethod][iFolder]->GetXaxis()->SetNdivisions(505);
 
    if(save){
      for(unsigned int iFileFormat=0; iFileFormat < fileFormat.size(); iFileFormat++){
	if(do1D){
	  CanvComp[iFolder]->Print(outputFolder+outputFileName+folderID[iFolder]+"_overview."+fileFormat[iFileFormat]);
	  for(int iEff=0; iEff<effIDNum; iEff++){
	    //CanvComp  [iFolder]->cd(iEff+1)->Print(outputFolder+outputFileName+folderID[iFolder]+"_"+effID[iEff]+"."+fileFormat[iFileFormat]);
	    //CanvSFComp[iFolder]->cd(iEff+1)->Print(outputFolder+outputFileName+folderID[iFolder]+"_SF_"+effID[iEff]+"."+fileFormat[iFileFormat]);
	    CanvEffAndSFComp[iFolder]->cd(iEff+1)->Print(outputFolder+outputFileName+folderID[iFolder]+"_EffAndSF_"+effID[iEff]+"."+fileFormat[iFileFormat]);
	  }
	  for(int iEff=0; iEff<effIDNum2; iEff++){
	    CanvComp  [iFolder]->cd(iEff+1)->Print(outputFolder+outputFileName+folderID[iFolder]+"_"+effID2[iEff]+"."+fileFormat[iFileFormat]);
	    CanvSFComp[iFolder]->cd(iEff+1)->Print(outputFolder+outputFileName+folderID[iFolder]+"_SF_"+effID2[iEff]+"."+fileFormat[iFileFormat]);
	  }
	}
	/// 2D
	if(do2D){
	  CanvComp2DPtEta[iFolder]->Print(outputFolder+outputFileName+folderID[iFolder]+"_"+"Eff2DPtEta."+fileFormat[iFileFormat]);
	  CanvComp2DPtEtaSF[iFolder]->Print(outputFolder+outputFileName+folderID[iFolder]+"_"+"SF2DPtEta."+fileFormat[iFileFormat]);
	}
	if(iFolder==0) CanvLeg->Print(outputFolder+outputFileName+"_Legend."+fileFormat[iFileFormat]);
	std::cout<<"Canvas with plots is saved in "<<outputFolder<<std::endl;
      }
    }
    /// save graph in root file
    /// 1D
    if(saveRoot && do1D){
      TFile f("MuonEffSF2012.root", "recreate");
      eff_["Eta"]["tapAll"]->graphSF["m2"]->SetName("tapAllSFeta");
      eff_["Eta"]["tapAll"]->graphSF["m2"]->Write();
      eff_["Eta"]["tapAll"]->graphSF["m2PUup"]->SetName("tapAllSFetaPUup");
      eff_["Eta"]["tapAll"]->graphSF["m2PUup"]->Write();
      eff_["Eta"]["tapAll"]->graphSF["m2PUdown"]->SetName("tapAllSFetaPUdown");
      eff_["Eta"]["tapAll"]->graphSF["m2PUdown"]->Write();
      std::cout<<"MuonEffSF2012.root with TGraphErrors is saved "<<std::endl;
    }
    /// 2D
    if(saveRoot && do2D){
      TFile f("MuonEffSF2D2012.root", "recreate");
      eff2DPtEta_[ "tapAll"]->hisSF["m2"]->SetName("tapAllSFeta");
      eff2DPtEta_[ "tapAll"]->hisSF["m2"]->Write();
      eff2DPtEta_[ "tapAll"]->hisSF["m2PUup"]->SetName("tapAllSFetaPUup");
      eff2DPtEta_[ "tapAll"]->hisSF["m2PUup"]->Write();
      eff2DPtEta_[ "tapAll"]->hisSF["m2PUdown"]->SetName("tapAllSFetaPUdown");
      eff2DPtEta_[ "tapAll"]->hisSF["m2PUdown"]->Write();
      std::cout<<"MuonEffSF2D2012.root with 2D SF Histos is saved in "<<std::endl;
    }
  }
  std::cout<< "Done"<<std::endl;
}
void makeSplitQCDhist_PythiaBinned()
{
	vector<string> folders, htbinlabels, hists;
	folders.push_back("Hist/HT0to500MHT0to7000");
	folders.push_back("Hist/HT500to900MHT0to7000");
	folders.push_back("Hist/HT900to1300MHT0to7000");
	folders.push_back("Hist/HT1300to7000MHT0to7000");

	vector<string> jetcoll;
	jetcoll.push_back("reco");
	jetcoll.push_back("gen");
	jetcoll.push_back("smeared");

	vector<hist_t> histlist;
	for (unsigned j=0; j< jetcoll.size(); ++j)
	{
		for (int i=0; ;++i)
		{
			hist_t h;
			h.name = jetcoll.at(j);
			h.normalizeByBinWidth = 0;
			if (i==0) {
				h.name += "_mht";
				h.title = "MHT;Events";
				h.rebin = 10;
			} else if (i==1) {
				h.name += "_ht";
				h.title = "HT;Events";
				h.rebin = 2;
			} else if (i==2) {
				h.name += "jet1_pt";
				h.title = "P_{T} [Jet1^{E_{T}>30, |#eta |<5.0}];Events;";
				h.rebin = 1;
			} else if (i==3) {
				h.name += "jet2_pt";
				h.title = "P_{T} [Jet2^{E_{T}>30, |#eta |<5.0}];Events;";
				h.rebin = 1;
			} else if (i==4) {
				h.name += "jet3_pt";
				h.title = "P_{T} [Jet3^{E_{T}>30, |#eta |<5.0}];Events;";
				h.rebin = 1;
			} else if (i==5) {
				h.name += "jet1_eta";
				h.title = "#eta [Jet1^{E_{T}>30, |#eta |<5.0}];Events;";
				h.rebin = 2;
			} else if (i==6) {
				h.name += "jet2_eta";
				h.title = "#eta [Jet2^{E_{T}>30, |#eta |<5.0}];Events;";
				h.rebin = 2;
			} else if (i==7) {
				h.name += "jet3_eta";
				h.title = "#eta [Jet3^{E_{T}>30, |#eta |<5.0}];Events;";
				h.rebin = 2;
			} else if (i==8) {
				h.name += "_njet50eta2p5";
				h.title = "N Jets [E_{T}>50 GeV && |#eta |<2.5];Events";
				h.rebin = 1;
			} else if (i==9) {
				h.name += "_dphimin";
				h.title = "#Delta #Phi_{min};Events";
				h.rebin = 1;
				h.normalizeByBinWidth = 1;
			} else if (i==10) {
				h.name = "pass0";
				h.title = "MHT;Events with #Delta #Phi_{min}>0.15";
				h.rebin = 1;
				h.normalizeByBinWidth = 1;
			} else if (i==11) {
				h.name = "pass1";
				h.title = "MHT;Events with #Delta #Phi_{min}>0.20";
				h.rebin = 1;
				h.normalizeByBinWidth = 1;
			} else if (i==12) {
				h.name = "pass3";
				h.title = "MHT;Events with #Delta #Phi_{min}>0.30";
				h.rebin = 1;
				h.normalizeByBinWidth = 1;
			} else if (i==13) {
				h.name = "fail0";
				h.title = "MHT;Events with #Delta #Phi_{min}<0.15";
				h.rebin = 1;
				h.normalizeByBinWidth = 1;
			} else if (i==14) {
				h.name = "fail1";
				h.title = "MHT;Events with #Delta #Phi_{min}<0.20";
				h.rebin = 1;
				h.normalizeByBinWidth = 1;
			} else if (i==15) {
				h.name = "fail3";
				h.title = "MHT;Events with #Delta #Phi_{min}<0.30";
				h.rebin = 1;
				h.normalizeByBinWidth = 1;
			} else if (i==16) {
				h.name = "signal";
				h.title = "MHT;Events Passing RA2 #Delta #Phi cut";
				h.rebin = 1;
				h.normalizeByBinWidth = 1;
			} else if (i==17) {
				h.name += "_njet30eta5p0";
				h.title = "N Jets [E_{T}>30 GeV && |#eta |<5.0];Events";
				h.rebin = 1;
			} else { break; }
			histlist.push_back(h);
		}
	}

	OpenFiles();
	TCanvas *c = new TCanvas("print");	
	c->Draw();
	c->Print("fundamental.eps[");

	for (unsigned h = 0; h < histlist.size(); ++h)
	{
	//	if (h!=0) continue;
		cout << histlist.at(h).name << endl;

		for (unsigned j = 0; j < folders.size(); ++j)
		{
			string htrange("");
			if (j==0) htrange += "0<HT<500 GeV";
			else if (j==1) htrange += "500<HT<900 GeV";
			else if (j==2) htrange += "900<HT<1300 GeV";
			else if (j==3) htrange += "1300<HT<7000 GeV";


			stringstream histName;
			histName << folders.at(j) << "/" << histlist.at(h).name;;
			//histName << histlist.at(h).name;;
			cout << "hist name = " << histName.str() << endl;
			makeSplitQCDhist_PythiaBinned(folders, histName.str(), htrange, folders.at(j), histlist.at(h)); 
			gPad->Print("fundamental.eps");
		}
	}
	c->Print("fundamental.eps]");
}
void gluinoMass(double lumi=-1., double maxInstLumi=-1.) {
	
  if (lumi<0)
    lumi=877.;
  if (maxInstLumi<0)
    maxInstLumi=1300.;
  LimitPlots plots(lumi);
  
  //mchamp index 0 is used, corresponds to 0th mass point = 100 GeV
  plots.calculateCrossSections(7,4,0,39,9);
	
  // expected limit (1 and 2 sigma bands)
  TGraph* g_exp = plots.getExpMassLimitGluino();
  TGraphAsymmErrors* g_exp1 = plots.getExpMassLimitGluino1Sig();
  TGraphAsymmErrors* g_exp2 = plots.getExpMassLimitGluino2Sig();
  
  // three points on counting expt curve
  TGraph* g_gluino = plots.getMassLimitGluino();
  TGraph* g_stop = plots.getMassLimitStop();
  
  // one point from lifetime fit
  TGraph* g_tp = plots.getMassLimitGluinoTP();
  
  // theory prediction
  TGraph* g_thGluino = plots.getGluinoTheory();
  TGraph* g_thStop = plots.getStopTheory();
  
  TCanvas* canvas = new TCanvas("canvas");
  
  //canvas->SetGrid();
  canvas->SetLogy();
  
  TH1 * h;
  h = canvas->DrawFrame(300., .02, 1000., 1e2);
  //h->SetTitle("Beamgap Expt;m_{#tilde{g}} [GeV/c^{2}]; Stopped HSCP Cross Section #times BR [pb]");
  h->SetTitle("Beamgap Expt;m_{#tilde{g}} [GeV/c^{2}]; #sigma(pp #rightarrow #tilde{g}#tilde{g}) #times BR(#tilde{g} #rightarrow g#tilde{#chi}^{0}) [pb]");
  
  // not covered region
  TBox* nc = new TBox(100., .1, 150., 5e2);
  nc->SetFillStyle(3354);
  nc->SetFillColor(kRed-4);
  //nc->Draw();
  
  // details
  TPaveText* blurb = new TPaveText(300., 2, 550., 1e2);
  blurb->AddText("CMS Preliminary 2012");

  std::stringstream label;
  label<<"#int L dt = "<<lumi<<" fb^{-1}";
  blurb->AddText(label.str().c_str());
  label.str("");
  double peakInstLumi=maxInstLumi;
  int exponent=30;
  while (peakInstLumi>10) {
    peakInstLumi/=10.;
    ++exponent;
  }
  label<<"L^{max}_{inst} = "<<peakInstLumi<<" x 10^{"<<exponent<<"} cm^{-2}s^{-1}";
  blurb->AddText(label.str().c_str());
  label.str("");
  label << "#sqrt{s} = " << ENERGY << " TeV";
  blurb->AddText(label.str().c_str());
  blurb->AddText("m_{#tilde{g}} - m_{#tilde{#chi}^{0}} = 100 GeV/c^{2}");
  //blurb->AddText("m_{#tilde{t}} - m_{#tilde{#chi}^{0}} = 200 GeV/c^{2}");	
  blurb->SetTextFont(42);
  blurb->SetBorderSize(0);
  blurb->SetFillColor(0);
  blurb->SetShadowColor(0);
  blurb->SetTextAlign(12);
  blurb->SetTextSize(0.032);

  
  // legend
  TBox *legbg = new TBox(600., 2., 900., 1e2);
  legbg->Draw();
  TLegend *leg = new TLegend(600., 2., 900., 1e2,"95% C.L. Limits","");
  leg->SetTextSize(0.028);
  leg->SetBorderSize(0);
  leg->SetTextFont(42);
  leg->SetFillColor(0);
  leg->AddEntry(g_exp, "Expected: 10 #mus - 1000 s Counting Exp. ", "l");
  leg->AddEntry(g_exp1, "Expected #pm1#sigma: 10 #mus - 1000 s Counting Exp. ", "f");
  leg->AddEntry(g_exp2, "Expected #pm2#sigma: 10 #mus - 1000 s Counting Exp. ", "f");
  //	  leg->AddEntry(graph3, "Obs.: 10^{6} s Counting Exp.", "l");
  leg->AddEntry(g_gluino, "Obs.: 10 #mus - 1000 s Counting Exp. ", "l");
  leg->AddEntry(g_tp, "Obs.: 10 #mus Timing Profile ", "l");
  //leg->AddEntry(g_stop, "Obs.: 10 #mus - 1000 s Counting Exp. (#tilde{t})", "l");
  //leg->AddEntry(graph_em, "Obs.: 10 #mus - 1000 s Counting Exp. (EM only)", "l");
  //  leg->AddEntry(graph1, "Obs.: 570 ns Counting Exp.", "l");
  leg->Draw();
  
  
  
  // 2 sigma expected band
  g_exp2->SetLineColor(0);
  g_exp2->SetLineStyle(0);
  g_exp2->SetLineWidth(0);
  g_exp2->SetFillColor(5);
  g_exp2->SetFillStyle(1001);
  g_exp2->Draw("3");
  
  // 1 sigma expected band
  g_exp1->SetLineColor(0);
  g_exp1->SetLineStyle(0);
  g_exp1->SetLineWidth(0);
  g_exp1->SetFillColor(3);
  g_exp1->SetFillStyle(1001);
  g_exp1->Draw("3");  
  
  // expected line
  g_exp->SetLineStyle(2);
  g_exp->SetLineWidth(1);
  g_exp->Draw("l");
  
 
  // plateau limit - 1 ms
  g_gluino->SetLineColor(1);
  g_gluino->SetLineStyle(1);
  g_gluino->SetLineWidth(2);
  g_gluino->Draw("l");
  
  // stop curve
  g_stop->SetLineColor(1);
  g_stop->SetLineStyle(5);
  g_stop->SetLineWidth(2);
  //g_stop->Draw("l");
 

  // 1 mus lifetime fit limit
  g_tp->SetLineColor(kRed);
  g_tp->SetLineStyle(1);
  g_tp->SetLineWidth(2);
  g_tp->Draw("l");
  
  // theory line
  g_thGluino->SetLineColor(kBlue);
  g_thGluino->SetLineStyle(1);
  g_thGluino->SetLineWidth(2);
  g_thGluino->SetFillStyle(3001);
  g_thGluino->SetFillColor(kBlue-4);
  g_thGluino->Draw("l3");
  
  g_thStop->SetLineColor(kRed);
  g_thStop->SetLineStyle(1);
  g_thStop->SetLineWidth(2);
  g_thStop->SetFillStyle(3001);
  g_thStop->SetFillColor(kRed-4);
  //g_thStop->Draw("l3");


  // theory line label
  TLatex* th = new TLatex(600., .3, "NLO+NLL #tilde{g}");
  th->SetTextColor(kBlue);
  th->SetTextFont(42);
  th->SetTextSize(0.035);
  th->Draw();

  TLatex* ths = new TLatex(330., 2., "NLO+NLL #tilde{t}");
  ths->SetTextColor(kRed);
  ths->SetTextFont(42);
  ths->SetTextSize(0.035);
  //ths->Draw();

  // not explored label
  TText* ne = new TText(125., .2, "Not Sensitive");
  ne->SetTextColor(kRed+1);
  ne->SetTextFont(42);
  ne->SetTextAngle(90);
  ne->SetTextSize(0.035);
  //ne->Draw();

  blurb->Draw();

  canvas->RedrawAxis();

  canvas->Print("gluinoMassLimit.pdf");
  canvas->Print("gluinoMassLimit.C");

  plots.calculateIntercepts();
  
}
Exemple #8
0
int frameStack2_Mall(char* arg){
	//Take the arguments and save them into respective strings
	std::string infileName, outfileName0, outAllfileName0, outfileName1, outAllfileName1;
	std::string inF, outF0, outF1, outAll0, outAll1;
	std::string inPrefix, outPrefix;
	std::string runs, layers;
	std::string runCount;
	std::istringstream stm(arg);

	inPrefix = "/home/p180f/Do_Jo_Ol_Ma/Analysis/MainProcedure/testMain/rawRoot/";
	outPrefix = "/home/p180f/Do_Jo_Ol_Ma/Analysis/MainProcedure/testMain/images/";

	outAll0 = "sliceXCuts_allLayers.png";
	outAllfileName0 = outPrefix + outAll0;
	std::cout << outAll0 << " created\n";
	outAll1 = "projYCuts_allLayers.png";
	outAllfileName1 = outPrefix + outAll1;
	std::cout << outAll1 << " created\n";

	const int width=480;	//width of the raw image
	const int height=640;	//height of the raw image
	
	TH2I *frameHistoAll = new TH2I("frameHistoAll","Stacked Frames After Edge Cuts",width/4,0,width,height/4,0,height);	//histogram for the stacked images
	TH1I *chamber1All = new TH1I("chamber1All","Chamber 1 After Edge Cuts",width/4,0,width);//histogram for chamber 1 (the top one)
	TH1I *chamber2All = new TH1I("chamber2All","Chamber 2 After Edge Cuts",width/4,0,width);//histogram for chamber 2
	TH1I *chamber3All = new TH1I("chamber3All","Chamber 3 After Edge Cuts",width/4,0,width);//histogram for chamber 3
	TH1I *chamber4All = new TH1I("chamber4All","Chamber 4 After Edge Cuts",width/4,0,width);//histogram for chamber 4 (the bottom one)

	TCanvas *projCAll = new TCanvas("projCAll","",0,0,800,600);
	TCanvas *pc2All = new TCanvas("pc2All", "Stack of 4 Layer Runs", 0, 0, 800, 600);
	
	while (true) {	
		if (std::getline(stm, layers, ' ')) {

			//create the output root file
			outF0 = "sliceXCuts_" + layers + "layers.png";
			outfileName0 = outPrefix + outF0;
			std::cout << outF0 << " created\n";
			outF1 = "projYCuts_" + layers + "layers.png";
			outfileName1 = outPrefix + outF1;
			std::cout << outF1 << " created\n";
			
			//load the input root files
			TChain *chain = new TChain("fourChamTree");

			for (int i=0; ; i++) {
				runCount = std::to_string(i);
				inF = "run" + runCount + "_" + layers + "layers.root";
				infileName = inPrefix + inF;
				ifstream fin;
				fin.open(infileName.c_str());
				if (!fin.fail()) {
					fin.close();
					chain->Add(infileName.c_str());
					std::cout << "Got " << inF << std::endl;
				} else break;
			}


			int x=-10;	//x from file
			int y=-10;	//y from file
			int intensity=-10;	//pixle intensity from file
			int pNum=0;//the order in which the frame was processed

			//the 2d array which will store each frame of image data.
			int frame[480][640]={0};

			//variables
			int UNIXtime=0;
			float tdc[2]={-10,-10};

			//TTree *T = new TTree("T","TTree of muplus data");
			//add the 'branches' to the tree we will now read in
			chain->SetBranchAddress("pNum",&pNum);	//branch for the frame number
			chain->SetBranchAddress("frame",&frame);	//branch for frame data


			TH2I *frameHisto = new TH2I("frameHisto","Stacked Frames After Edge Cuts",width/4,0,width,height/4,0,height);	//histogram for the stacked images
			TH1I *chamber1 = new TH1I("chamber1","Chamber 1 After Edge Cuts",width/4,0,width);//histogram for chamber 1 (the top one)
			TH1I *chamber2 = new TH1I("chamber2","Chamber 2 After Edge Cuts",width/4,0,width);//histogram for chamber 2
			TH1I *chamber3 = new TH1I("chamber3","Chamber 3 After Edge Cuts",width/4,0,width);//histogram for chamber 3
			TH1I *chamber4 = new TH1I("chamber4","Chamber 4 After Edge Cuts",width/4,0,width);//histogram for chamber 4 (the bottom one)

			//loop over all data in chain
			Int_t nevent = chain->GetEntries();	//get the number of entries in the TChain
			for (Int_t i=0;i<nevent;i++) {
				chain->GetEntry(i);
				for(int x=0;x<width;x++){
					for(int y=0;y<height;y++){
						if(frame[x][y]>0){
							frameHisto->Fill(x,y,frame[x][y]);
							frameHistoAll->Fill(x,y,frame[x][y]);
							if(y>580 && y<610){
								chamber1->Fill(x,frame[x][y]);
								chamber1All->Fill(x,frame[x][y]);
							}
							else if(y>400 && y<440){
								chamber2->Fill(x,frame[x][y]);
								chamber2All->Fill(x,frame[x][y]);
							}
							else if(y>240 && y<280){
								chamber3->Fill(x,frame[x][y]);
								chamber3All->Fill(x,frame[x][y]);
							}
							else if(y>50 && y<100){
								chamber4->Fill(x,frame[x][y]);
								chamber4All->Fill(x,frame[x][y]);
							}

						}

					}
				}
				cout << "Stacking frame number " << pNum << "\r";//this overwrites the line every time
			}
			cout << endl;

			//output the plot of the stacked images
			TCanvas *pc2 = new TCanvas("pc2","Stacked Frames",0,0,600,800);
			pc2->cd();
			frameHisto->SetStats(false);
			frameHisto->Draw("colz");
			frameHisto->GetXaxis()->SetTitle("X position (px)");
			//frameHisto->GetXaxis()->SetTitleSize(0.055);
			//frameHisto->GetXaxis()->SetTitleOffset(1.0);
			//frameHisto->GetXaxis()->SetLabelSize(0.055);
			frameHisto->GetXaxis()->CenterTitle();

			frameHisto->GetYaxis()->SetTitle("Y position (px)");
			//frameHisto->GetYaxis()->SetTitleSize(0.055);
			//frameHisto->GetYaxis()->SetTitleOffset(0.9);
			//frameHisto->GetYaxis()->SetLabelSize(0.055);
			frameHisto->GetYaxis()->CenterTitle();
			gPad->Update();
//			pc2->Print("chamberStack.png");//output to a graphics file 

			//plot the projection onto the Y axis (so we can find our cuts in Y to select each chamber)
			TCanvas *projC = new TCanvas("projC","",0,0,800,600);
			projC->cd();
			TH1D *ydist = frameHisto->ProjectionY("ydist");
			ydist->Draw();
			ydist->GetYaxis()->SetTitle("Entries");
			ydist->GetYaxis()->CenterTitle();

			TCanvas *sliceX = new TCanvas("sliceX","",0,0,800,600);

			sliceX->Divide(2,2);
			
			sliceX->cd(1);
			chamber1->Draw();
			chamber1->GetXaxis()->SetTitle("X position (px)");
			chamber1->GetXaxis()->CenterTitle();
			chamber1->GetYaxis()->SetTitle("Y position (px)");
			chamber1->GetYaxis()->CenterTitle();
		//	chamber1->GetYaxis()->SetMaxDigits(2);
			
			sliceX->cd(2);
			chamber2->Draw();
			chamber2->GetXaxis()->SetTitle("X position (px)");
			chamber2->GetXaxis()->CenterTitle();
			chamber2->GetYaxis()->SetTitle("Y position (px)");
			chamber2->GetYaxis()->CenterTitle();
		//	chamber2->GetYaxis()->SetMaxDigits(2);
			
			sliceX->cd(3);
			chamber3->Draw();
			chamber3->GetXaxis()->SetTitle("X position (px)");
			chamber3->GetXaxis()->CenterTitle();
			chamber3->GetYaxis()->SetTitle("Y position (px)");
			chamber3->GetYaxis()->CenterTitle();
		//	chamber3->GetYaxis()->SetMaxDigits(2);
			
			sliceX->cd(4);
			chamber4->Draw();
			chamber4->GetXaxis()->SetTitle("X position (px)");
			chamber4->GetXaxis()->CenterTitle();
			chamber4->GetYaxis()->SetTitle("Y position (px)");
			chamber4->GetYaxis()->CenterTitle();
		//	chamber4->GetYaxis()->SetMaxDigits(2);

			gPad->Update();
			
			projC->Print(outfileName1.c_str());
			sliceX->Print(outfileName0.c_str());

			frameHisto->Reset();	
			chamber1->Reset();
			chamber2->Reset();
			chamber3->Reset();
			chamber4->Reset();
		} else break;
	}
	
	projCAll->cd();
	TH1D *ydistAll = frameHistoAll->ProjectionY("ydist");
	ydistAll->Draw();
	ydistAll->GetYaxis()->SetTitle("Entries");
	ydistAll->GetYaxis()->CenterTitle();
	
	TCanvas *sliceXAll = new TCanvas("sliceXAll","",0,0,800,600);

	sliceXAll->Divide(2,2);
	
	sliceXAll->cd(1);
	chamber1All->Draw();
	chamber1All->GetXaxis()->SetTitle("X position (px)");
	chamber1All->GetXaxis()->CenterTitle();
	chamber1All->GetYaxis()->SetTitle("Y position (px)");
	chamber1All->GetYaxis()->CenterTitle();
//	chamber1->GetYaxis()->SetMaxDigits(2);
	
	sliceXAll->cd(2);
	chamber2All->Draw();
	chamber2All->GetXaxis()->SetTitle("X position (px)");
	chamber2All->GetXaxis()->CenterTitle();
	chamber2All->GetYaxis()->SetTitle("Y position (px)");
	chamber2All->GetYaxis()->CenterTitle();
//	chamber2->GetYaxis()->SetMaxDigits(2);
	
	sliceXAll->cd(3);
	chamber3All->Draw();
	chamber3All->GetXaxis()->SetTitle("X position (px)");
	chamber3All->GetXaxis()->CenterTitle();
	chamber3All->GetYaxis()->SetTitle("Y position (px)");
	chamber3All->GetYaxis()->CenterTitle();
//	chamber3->GetYaxis()->SetMaxDigits(2);
	
	sliceXAll->cd(4);
	chamber4All->Draw();
	chamber4All->GetXaxis()->SetTitle("X position (px)");
	chamber4All->GetXaxis()->CenterTitle();
	chamber4All->GetYaxis()->SetTitle("Y position (px)");
	chamber4All->GetYaxis()->CenterTitle();
//	chamber4->GetYaxis()->SetMaxDigits(2);

	gPad->Update();
	
	projCAll->Print(outAllfileName1.c_str());
	sliceXAll->Print(outAllfileName0.c_str());
	
	pc2All->cd();
	frameHistoAll->SetStats(false);
	frameHistoAll->Draw("colz");
	frameHistoAll->GetXaxis()->SetTitle("X position (px)");
	//frameHisto->GetXaxis()->SetTitleSize(0.055);
	//frameHisto->GetXaxis()->SetTitleOffset(1.0);
	//frameHisto->GetXaxis()->SetLabelSize(0.055);
	frameHistoAll->GetXaxis()->CenterTitle();

	frameHistoAll->GetYaxis()->SetTitle("Y position (px)");
	//frameHisto->GetYaxis()->SetTitleSize(0.055);
	//frameHisto->GetYaxis()->SetTitleOffset(0.9);
	//frameHisto->GetYaxis()->SetLabelSize(0.055);
	frameHistoAll->GetYaxis()->CenterTitle();
	gPad->Update();

	return 0;  
}
int main(int argc, char* argv[]) {

  TH1::SetDefaultSumw2();

  ProgramOptions options(argc, argv);

  double lumi = options.lumi;

  // input datasets
  Datasets datasets(options.iDir);
  datasets.readFile(options.datasetFile);
 
  // output file
  TFile* ofile = TFile::Open( (options.oDir+std::string("/ZMuMufromW.root")).c_str(), "RECREATE");
  std::string oDir = options.oDir + std::string("/ZmumuFromW");

  if (oDir!="") {
    boost::filesystem::path opath(oDir);
    if (!exists(opath)) {
      std::cout << "Creating output directory : " << oDir << std::endl;
      boost::filesystem::create_directory(opath);
    }
    std::cout << "Writing results to " << oDir << std::endl;
  }

  // cuts
  Cuts cuts;
  unsigned nCutsZMuMu = cuts.nCutsZMuMu();

  TCut puWeight("puWeight");
  TCut trigCorr( "(trigCorrWeight>0) ? trigCorrWeight : 1." );

  // For lepton weights
  TCut muTightWeight    = cuts.muTightWeight(options.leptCorr);
  TCut lVetoWeight  	= cuts.elVetoWeight(options.leptCorr) * cuts.muVetoWeight(options.leptCorr);

  TCut METNo2Muon130("metNo2Muon>130.");
  TCut cutLoDPhi = cuts.cut("dPhiJJ");
  TCut cutHiDPhi("vbfDPhi>2.6");
  TCut cutMe1DPhi("vbfDPhi>1.0 && vbfDPhi<=1.8");
  TCut cutMe2DPhi("vbfDPhi>1.8 && vbfDPhi<=2.6");

  // histograms
  double dphiEdges[5] = { 0., 1.0, 1.8, 2.6, TMath::Pi() };

  // Observed signal MET>130
  TH1D* hZ_DY_C_DPhi 	= new TH1D("hZ_DY_C_DPhi", "", 4, dphiEdges);  // Z+jets MC ctrl region
  TH1D* hZ_BG_ZC_DPhi 	= new TH1D("hZ_BG_ZC_DPhi", "", 4, dphiEdges);  // background MC ctrl region
  TH1D* hZ_Data_ZC_DPhi = new TH1D("hZ_Data_ZC_DPhi", "", 4, dphiEdges);  // Data ctrl region
  // Predicted from Wmunu
  TH1D* hZ_W_C_DPhi 	= new TH1D("hZ_W_C_DPhi", "", 4, dphiEdges);  	// W+jets MC ctrl region
  TH1D* hZ_BG_WC_DPhi 	= new TH1D("hZ_BG_WC_DPhi", "", 4, dphiEdges);  	// background MC ctrl region
  TH1D* hZ_Data_WC_DPhi = new TH1D("hZ_Data_WC_DPhi", "", 4, dphiEdges);  // Data W ctrl region

  TH1D* hZ_W_EffMu_D 	= new TH1D("hZ_W_EffMu_D", "", 1, 0., 1.);	// denominator of MuMu efficiency from DY(pT<100) + DY(pT>100) + DY_EWK samples
  TH1D* hZ_W_EffMu_N 	= new TH1D("hZ_W_EffMu_N", "", 1, 0., 1.);	// numerator of MuMu efficiency from DY(pT<100) + DY(pT>100) + DY_EWK samples

  TH1D* hZ_DY_EffMuMu_D = new TH1D("hZ_DY_EffMuMu_D", "", 1, 0., 1.);   // denominator of MuMu efficiency from DY + DY_EWK samples
  TH1D* hZ_DY_EffMuMu_N = new TH1D("hZ_DY_EffMuMu_N", "", 1, 0., 1.);   // numerator of MuMu efficiency from DY + DY_EWK samples 
  
  TH1D* hZ_DY_EffVBFS_D = new TH1D("hZ_DY_EffVBFS_D", "", 1, 0., 1.);   // denominator of VBF(S) efficiency from DY(pT<100) + DY(pT>100) + DY_EWK samples
  //TH1D* hZ_DY_EffVBFS_N  = new TH1D("hZ_DY_EffVBFS_N", "", 1, 0., 1.);   // numerator of VBF(S) efficiency from DY(pT<100) + DY(pT>100) + DY_EWK samples  
  TH1D* hZ_DY_EffVBFS_NLo  = new TH1D("hZ_DY_EffVBFS_NLo", "", 1, 0., 1.);   
  TH1D* hZ_DY_EffVBFS_NHi  = new TH1D("hZ_DY_EffVBFS_NHi", "", 1, 0., 1.);
  TH1D* hZ_DY_EffVBFS_NMe1 = new TH1D("hZ_DY_EffVBFS_NMe1", "", 1, 0., 1.); 
  TH1D* hZ_DY_EffVBFS_NMe2 = new TH1D("hZ_DY_EffVBFS_NMe2", "", 1, 0., 1.);  

  TH1D* hZ_W_EffVBFC_D 	   = new TH1D("hZ_W_EffVBFC_D", "", 1, 0., 1.);   // denominator of VBF(C) efficiency from DY(pT<100) + DY(pT>100) + DY_EWK samples
  //TH1D* hZ_W_EffVBFC_N   = new TH1D("hZ_W_EffVBFC_N", "", 1, 0., 1.);   // numerator of VBF(C) efficiency from DY(pT<100) + DY(pT>100) + DY_EWK samples 
  TH1D* hZ_W_EffVBFC_NLo   = new TH1D("hZ_W_EffVBFC_NLo", "", 1, 0., 1.);  
  TH1D* hZ_W_EffVBFC_NHi   = new TH1D("hZ_W_EffVBFC_NHi", "", 1, 0., 1.);
  TH1D* hZ_W_EffVBFC_NMe1  = new TH1D("hZ_W_EffVBFC_NMe1", "", 1, 0., 1.);
  TH1D* hZ_W_EffVBFC_NMe2  = new TH1D("hZ_W_EffVBFC_NMe2", "", 1, 0., 1.);

  // loop over MC datasets
  for (unsigned i=0; i<datasets.size(); ++i) {

    Dataset dataset = datasets.getDataset(i);
    
    TCut cutD = cuts.cutDataset(dataset.name);
    TCut wWeight("");

    // bit of a fudge for mutight weight - data doesn't have the var in it, so need to add an exception (see below)
    // and then restore it for all other MC
    muTightWeight=cuts.muTightWeight(options.leptCorr);

    // check if it's DYJets
    bool isDY = false;
    bool isWJets = false;
    bool isQCD = false;
    bool isEwkW = false;
    if (dataset.name.compare(0,2,"DY")==0) {
      isDY = true;
      std::cout << "Analysing DY->ll MC : " << dataset.name << std::endl;
    }
    else if (dataset.name == "WJets" ||
        dataset.name == "W1Jets" ||
        dataset.name == "W2Jets" ||
        dataset.name == "W3Jets" ||
        dataset.name == "W4Jets" ||
        dataset.name == "EWK_Wp2Jets" ||
        dataset.name == "EWK_Wm2Jets") {

      if (dataset.name == "EWK_Wp2Jets" || dataset.name == "EWK_Wm2Jets") isEwkW = true;
      else isWJets = true;

      if(isWJets) wWeight =  cuts.wWeight();
      std::cout << "Analysing W MC     : " << dataset.name << std::endl;
    }
    else if (dataset.name.compare(0,3,"QCD")==0) {
      isQCD = true;
      std::cout << "Analysing QCD : " << dataset.name << std::endl;
    }
    else if (dataset.isData) {
      muTightWeight="";
      std::cout << "Analysing Data      : " << dataset.name << std::endl;
    }
    else {
      std::cout << "Analysing BG MC     : " << dataset.name << std::endl;
    }

    // get file & tree
    TFile* file = datasets.getTFile(dataset.name);
    TTree* tree = (TTree*) file->Get("invHiggsInfo/InvHiggsInfo");

    // set up cuts
    TCut otherCuts = puWeight * trigCorr * wWeight;

    TCut cutZMuMu_C    	      = otherCuts * muTightWeight * (cutD + cuts.zMuMuVBF() + METNo2Muon130);
    TCut cutWMuNu_C    	      = otherCuts * muTightWeight * (cutD + cuts.wMuVBF() + cuts.cutWMu("MET"));
    // eps_mu from W trigger samples
    TCut cutEfficiencyMu_D    = otherCuts * (cutD + cuts.HLTandMETFilters() + cuts.wMuGen());
    TCut cutEfficiencyMu_N    = otherCuts * muTightWeight * (cutD + cuts.HLTandMETFilters() + cuts.wMuGen() + cuts.cutWMu("wMu"));

    TCut cutEfficiencyMuMu_D    = otherCuts * (cutD + cuts.HLTandMETFilters() + cuts.zMuMuGen());
    TCut cutEfficiencyMuMu_N    = otherCuts * muTightWeight * (cutD + cuts.HLTandMETFilters() + cuts.zMuMuGen() + cuts.zMuMuReco());
    // eps_VBFS from DY-Trig
    TCut cutEfficiencyVBFS_D    = otherCuts * muTightWeight * (cutD + cuts.HLTandMETFilters() + cuts.zMuMuGen() + cuts.zMuMuReco());
    //TCut cutEfficiencyVBFS_N  = otherCuts * (cutD + cuts.HLTandMETFilters() + cuts.zMuMuGen() + cuts.zMuMuReco() + cuts.vbf() + METNo2Muon130);
    TCut cutEfficiencyVBFS_NLoDPhi  = otherCuts * muTightWeight * (cutD + cuts.HLTandMETFilters() + cuts.zMuMuGen() + cuts.zMuMuReco() + cuts.vbf() + METNo2Muon130 + cutLoDPhi);
    TCut cutEfficiencyVBFS_NHiDPhi  = otherCuts * muTightWeight * (cutD + cuts.HLTandMETFilters() + cuts.zMuMuGen() + cuts.zMuMuReco() + cuts.vbf() + METNo2Muon130 + cutHiDPhi);
    TCut cutEfficiencyVBFS_NMe1DPhi = otherCuts * muTightWeight * (cutD + cuts.HLTandMETFilters() + cuts.zMuMuGen() + cuts.zMuMuReco() + cuts.vbf() + METNo2Muon130 + cutMe1DPhi);
    TCut cutEfficiencyVBFS_NMe2DPhi = otherCuts * muTightWeight * (cutD + cuts.HLTandMETFilters() + cuts.zMuMuGen() + cuts.zMuMuReco() + cuts.vbf() + METNo2Muon130 + cutMe2DPhi);

    // eps_VBFC from W
    TCut cutEfficiencyVBFC_D    = otherCuts * muTightWeight * (cutD + cuts.HLTandMETFilters() + cuts.wMuGen() + cuts.cutWMu("wMu"));
    //TCut cutEfficiencyVBFC_N  = otherCuts * (cutD + cuts.HLTandMETFilters() + cuts.wMuGen() + cuts.cutWMu("wMu") + cuts.vbf() + cuts.cutWMu("MET")); 
    TCut cutEfficiencyVBFC_NLoDPhi  = otherCuts * muTightWeight * (cutD + cuts.HLTandMETFilters() + cuts.wMuGen() + cuts.cutWMu("wMu") + cuts.vbf() + cuts.cutWMu("MET") + cutLoDPhi);
    TCut cutEfficiencyVBFC_NHiDPhi  = otherCuts * muTightWeight * (cutD + cuts.HLTandMETFilters() + cuts.wMuGen() + cuts.cutWMu("wMu") + cuts.vbf() + cuts.cutWMu("MET") + cutHiDPhi);
    TCut cutEfficiencyVBFC_NMe1DPhi = otherCuts * muTightWeight * (cutD + cuts.HLTandMETFilters() + cuts.wMuGen() + cuts.cutWMu("wMu") + cuts.vbf() + cuts.cutWMu("MET") + cutMe1DPhi);
    TCut cutEfficiencyVBFC_NMe2DPhi = otherCuts * muTightWeight * (cutD + cuts.HLTandMETFilters() + cuts.wMuGen() + cuts.cutWMu("wMu") + cuts.vbf() + cuts.cutWMu("MET") + cutMe2DPhi);

    // fill tmp histograms for BG estimation
    //observed
    //TH1D* hZ_ZC_noDPhi  	= new TH1D("hZ_ZC_noDPhi", "", 1, 0., 1.);
    TH1D* hZ_ZC_DPhi  		= new TH1D("hZ_ZC_DPhi", "", 4, dphiEdges);  
    //predicted
    //TH1D* hZ_WC_noDPhi  	= new TH1D("hZ_WC_noDPhi", "", 1, 0., 1.);
    TH1D* hZ_WC_DPhi  		= new TH1D("hZ_WC_DPhi", "", 4, dphiEdges);  // this is for the actual BG estimation
    // fill tmp histograms for efficiency calculation
    TH1D* hZ_EffMuMu_D  	= new TH1D("hZ_EffMuMu_D",   "", 1, 0., 1.);
    TH1D* hZ_EffMuMu_N  	= new TH1D("hZ_EffMuMu_N",   "", 1, 0., 1.);
    TH1D* hZ_EffMu_D  		= new TH1D("hZ_EffMu_D",     "", 1, 0., 1.);
    TH1D* hZ_EffMu_N  		= new TH1D("hZ_EffMu_N",     "", 1, 0., 1.);
    TH1D* hZ_EffVBFS_D  	= new TH1D("hZ_EffVBFS_D",   "", 1, 0., 1.);
    //TH1D* hZ_EffVBFS_N  	= new TH1D("hZ_EffVBFS_N",   "", 1, 0., 1.);
    TH1D* hZ_EffVBFS_NLo  	= new TH1D("hZ_EffVBFS_NLo", "", 1, 0., 1.);
    TH1D* hZ_EffVBFS_NHi  	= new TH1D("hZ_EffVBFS_NHi", "", 1, 0., 1.);
    TH1D* hZ_EffVBFS_NMe1  	= new TH1D("hZ_EffVBFS_NMe1","", 1, 0., 1.);
    TH1D* hZ_EffVBFS_NMe2  	= new TH1D("hZ_EffVBFS_NMe2","", 1, 0., 1.);

    TH1D* hZ_EffVBFC_D  	= new TH1D("hZ_EffVBFC_D",   "", 1, 0., 1.);
    //TH1D* hZ_EffVBFC_N  	= new TH1D("hZ_EffVBFC_N",   "", 1, 0., 1.);
    TH1D* hZ_EffVBFC_NLo  	= new TH1D("hZ_EffVBFC_NLo", "", 1, 0., 1.);
    TH1D* hZ_EffVBFC_NHi  	= new TH1D("hZ_EffVBFC_NHi", "", 1, 0., 1.);
    TH1D* hZ_EffVBFC_NMe1  	= new TH1D("hZ_EffVBFC_NMe1","", 1, 0., 1.);
    TH1D* hZ_EffVBFC_NMe2  	= new TH1D("hZ_EffVBFC_NMe2","", 1, 0., 1.);

    // W control region DY is BG
    if (isDY) { 
      //tree->Draw("0.5>>hZ_ZC_noDPhi",    cutZMuMu_C);
      tree->Draw("vbfDPhi>>hZ_ZC_DPhi",    cutZMuMu_C);

      //tree->Draw("0.5>>hZ_WC_noDPhi",    cutWMuNu_C);
      tree->Draw("vbfDPhi>>hZ_WC_DPhi",    cutWMuNu_C);
      tree->Draw("0.5>>hZ_EffMuMu_D",      cutEfficiencyMuMu_D);
      tree->Draw("0.5>>hZ_EffMuMu_N",      cutEfficiencyMuMu_N);
      tree->Draw("0.5>>hZ_EffVBFS_D",      cutEfficiencyVBFS_D);
      //tree->Draw("0.5>>hZ_EffVBFS_N",    cutEfficiencyVBFS_N);
      tree->Draw("0.5>>hZ_EffVBFS_NLo",    cutEfficiencyVBFS_NLoDPhi);
      tree->Draw("0.5>>hZ_EffVBFS_NHi",    cutEfficiencyVBFS_NHiDPhi);
      tree->Draw("0.5>>hZ_EffVBFS_NMe1",   cutEfficiencyVBFS_NMe1DPhi);
      tree->Draw("0.5>>hZ_EffVBFS_NMe2",   cutEfficiencyVBFS_NMe2DPhi);
    }
    else if(isWJets || isEwkW) {
      //tree->Draw("0.5>>hZ_WC_noDPhi",    cutWMuNu_C);
      tree->Draw("vbfDPhi>>hZ_WC_DPhi",    cutWMuNu_C);
      tree->Draw("0.5>>hZ_EffMu_D",        cutEfficiencyMu_D);  
      tree->Draw("0.5>>hZ_EffMu_N",        cutEfficiencyMu_N);    
      tree->Draw("0.5>>hZ_EffVBFC_D",      cutEfficiencyVBFC_D);
      //tree->Draw("0.5>>hZ_EffVBFC_N",    cutEfficiencyVBFC_N);
      tree->Draw("0.5>>hZ_EffVBFC_NLo",    cutEfficiencyVBFC_NLoDPhi);
      tree->Draw("0.5>>hZ_EffVBFC_NHi",    cutEfficiencyVBFC_NHiDPhi);
      tree->Draw("0.5>>hZ_EffVBFC_NMe1",   cutEfficiencyVBFC_NMe1DPhi);
      tree->Draw("0.5>>hZ_EffVBFC_NMe2",   cutEfficiencyVBFC_NMe2DPhi);
    }
    else if(isQCD) {
      //tree->Draw("0.5>>hZ_C_noDPhi",     cutWMuNu_C);
      tree->Draw("vbfDPhi>>hZ_WC_DPhi",    cutWMuNu_C);
    }
    else {
      tree->Draw("vbfDPhi>>hZ_ZC_DPhi",    cutZMuMu_C);
      tree->Draw("vbfDPhi>>hZ_WC_DPhi",    cutWMuNu_C);
    }

    // weight  to lumi
    double weight = (dataset.isData) ? 1. : lumi * dataset.sigma / dataset.nEvents;

    hZ_ZC_DPhi->Scale(weight);
    hZ_WC_DPhi->Scale(weight);
    hZ_EffVBFS_D->Scale(weight);
    //hZ_EffVBFS_N->Scale(weight);
    hZ_EffVBFS_NLo->Scale(weight);
    hZ_EffVBFS_NHi->Scale(weight);
    hZ_EffVBFS_NMe1->Scale(weight);
    hZ_EffVBFS_NMe2->Scale(weight);
    hZ_EffVBFC_D->Scale(weight);
    //hZ_EffVBFC_N->Scale(weight);
    hZ_EffVBFC_NLo->Scale(weight);
    hZ_EffVBFC_NHi->Scale(weight);
    hZ_EffVBFC_NMe1->Scale(weight);
    hZ_EffVBFC_NMe2->Scale(weight);
    hZ_EffMu_D->Scale(weight);
    hZ_EffMu_N->Scale(weight);
    hZ_EffMuMu_D->Scale(weight);
    hZ_EffMuMu_N->Scale(weight);

    // add to output histograms
    if (dataset.isData) {
      hZ_Data_ZC_DPhi->Add(hZ_ZC_DPhi);
      hZ_Data_WC_DPhi->Add(hZ_WC_DPhi);
    }
    else if (isWJets || isEwkW) {
      //hZ_W_C_noDPhi->Add(hZ_C_noDPhi);
      hZ_W_C_DPhi->Add(hZ_WC_DPhi);
      hZ_W_EffMu_D->Add(hZ_EffMu_D);
      hZ_W_EffMu_N->Add(hZ_EffMu_N);
      hZ_W_EffVBFC_D->Add(hZ_EffVBFC_D);
      //hZ_W_EffVBFC_N->Add(hZ_EffVBFC_N);
      hZ_W_EffVBFC_NLo->Add(hZ_EffVBFC_NLo);
      hZ_W_EffVBFC_NHi->Add(hZ_EffVBFC_NHi);
      hZ_W_EffVBFC_NMe1->Add(hZ_EffVBFC_NMe1);
      hZ_W_EffVBFC_NMe2->Add(hZ_EffVBFC_NMe2);
    }
    else if (isDY) {
      hZ_DY_C_DPhi->Add(hZ_ZC_DPhi);
      hZ_BG_WC_DPhi->Add(hZ_WC_DPhi);

      hZ_DY_EffMuMu_D->Add(hZ_EffMuMu_D);
      hZ_DY_EffMuMu_N->Add(hZ_EffMuMu_N);
      hZ_DY_EffVBFS_D->Add(hZ_EffVBFS_D);
      //hZ_DY_EffVBFS_N->Add(hZ_EffVBFS_N);
      hZ_DY_EffVBFS_NLo->Add(hZ_EffVBFS_NLo);
      hZ_DY_EffVBFS_NHi->Add(hZ_EffVBFS_NHi);
      hZ_DY_EffVBFS_NMe1->Add(hZ_EffVBFS_NMe1);
      hZ_DY_EffVBFS_NMe2->Add(hZ_EffVBFS_NMe2);
    }
    else if (isQCD) {
      //hZ_BG_WC_DPhi->Add(hZ_WC_DPhi);
    }
    else {
      hZ_BG_WC_DPhi->Add(hZ_WC_DPhi);
      hZ_BG_ZC_DPhi->Add(hZ_ZC_DPhi);
    }

    std::cout << "  N_Z ctrl (dphi<1.0) : " << hZ_ZC_DPhi->GetBinContent(1) << " +/- " << hZ_ZC_DPhi->GetBinError(1) << std::endl;
    std::cout << "  N_W ctrl (dphi<1.0) : " << hZ_WC_DPhi->GetBinContent(1) << " +/- " << hZ_WC_DPhi->GetBinError(1) << std::endl;
    
    delete hZ_WC_DPhi;
    delete hZ_ZC_DPhi;
    delete hZ_EffMuMu_D;
    delete hZ_EffMuMu_N;
    delete hZ_EffMu_D;
    delete hZ_EffMu_N;
    delete hZ_EffVBFS_D;
    //delete hZ_EffVBFS_N;
    delete hZ_EffVBFS_NLo;
    delete hZ_EffVBFS_NMe1;
    delete hZ_EffVBFS_NMe2;
    delete hZ_EffVBFS_NHi;
    delete hZ_EffVBFC_D;
    //delete hZ_EffVBFC_N;
    delete hZ_EffVBFC_NLo;
    delete hZ_EffVBFC_NMe1;
    delete hZ_EffVBFC_NMe2;
    delete hZ_EffVBFC_NHi;

    // clean up
    delete tree;
    file->Close();
   
  }

  // numbers - calculate these from MC in this program later!
  //double ratioBF = 5.626;  //  MCFM + NLO
  double ratioBF = 1144./14428.;

  TH1D* hZ_Est_ZC_DPhi = new TH1D("hZ_Est_ZC_DPhi", "", 4, dphiEdges); 

  // bins dPhi
  TH1D* hZ_Est_WC_DPhi = new TH1D("hZ_Est_WC_DPhi", "", 4, dphiEdges); 
  TH1D* hZ_Est_WS_DPhi = new TH1D("hZ_Est_WS_DPhi", "", 4, dphiEdges); 
  TH1D* hZ_Eff_WS_DPhi = new TH1D("hZ_Eff_WS_DPhi", "", 4, dphiEdges);
 
  TH1D* hZ_W_EffMu    = new TH1D("hZ_W_EffMu", "", 1, 0., 1.);     	// epsilon mumu
  hZ_W_EffMu->Add(hZ_W_EffMu_N);
  hZ_W_EffMu->Divide(hZ_W_EffMu_D);
  //double mu_syst = 0.025*hZ_W_EffMu->GetBinContent(1);      //2.5% Muon ID/Iso efficiency uncertainty from EWK-10-002
  //hZ_W_EffMu->SetBinError(1,TMath::Sqrt(hZ_W_EffMu->GetBinError(1)*hZ_W_EffMu->GetBinError(1) + mu_syst*mu_syst));

  TH1D* hZ_DY_EffMuMu = new TH1D("hZ_DY_EffMuMu", "", 1, 0., 1.);       // epsilon mumu
  hZ_DY_EffMuMu->Add(hZ_DY_EffMuMu_N);
  hZ_DY_EffMuMu->Divide(hZ_DY_EffMuMu_D);
  //mu_syst = 0.025*hZ_DY_EffMuMu->GetBinContent(1);      //2.5% Muon ID/Iso efficiency uncertainty from EWK-10-002
  //hZ_DY_EffMuMu->SetBinError(1,TMath::Sqrt(hZ_DY_EffMuMu->GetBinError(1)*hZ_DY_EffMuMu->GetBinError(1) + mu_syst*mu_syst));

  //TH1D* hZ_DY_EffVBFS  = new TH1D("hZ_DY_EffVBFS", "", 1, 0., 1.);  	// epsilon_s_vbf
  TH1D* hZ_DY_EffVBFSLo  = new TH1D("hZ_DY_EffVBFSLo", "", 1, 0., 1.);
  TH1D* hZ_DY_EffVBFSHi  = new TH1D("hZ_DY_EffVBFSHi", "", 1, 0., 1.);
  TH1D* hZ_DY_EffVBFSMe1 = new TH1D("hZ_DY_EffVBFSMe1", "", 1, 0., 1.);
  TH1D* hZ_DY_EffVBFSMe2 = new TH1D("hZ_DY_EffVBFSMe2", "", 1, 0., 1.);

  //TH1D* hZ_W_EffVBFC   = new TH1D("hZ_W_EffVBFC", "", 1, 0., 1.);       // epsilon_c_vbf
  TH1D* hZ_W_EffVBFCLo   = new TH1D("hZ_W_EffVBFCLo", "", 1, 0., 1.);
  TH1D* hZ_W_EffVBFCHi   = new TH1D("hZ_W_EffVBFCHi", "", 1, 0., 1.);
  TH1D* hZ_W_EffVBFCMe1  = new TH1D("hZ_W_EffVBFCMe1", "", 1, 0., 1.);
  TH1D* hZ_W_EffVBFCMe2  = new TH1D("hZ_W_EffVBFCMe2", "", 1, 0., 1.);

  //TH1D* hZ_W_RatioVBF  = new TH1D("hZ_W_RatioVBF", "", 1, 0., 1.);	// epsilon_s_vbf/epsilon_c_vbf
  TH1D* hZ_W_RatioVBFLo  = new TH1D("hZ_W_RatioVBFLo", "", 1, 0., 1.); 
  TH1D* hZ_W_RatioVBFHi  = new TH1D("hZ_W_RatioVBFHi", "", 1, 0., 1.); 
  TH1D* hZ_W_RatioVBFMe1 = new TH1D("hZ_W_RatioVBFMe1", "", 1, 0., 1.); 
  TH1D* hZ_W_RatioVBFMe2 = new TH1D("hZ_W_RatioVBFMe2", "", 1, 0., 1.); 

  //TH1D* hZ_W_TotalEff  = new TH1D("hZ_W_TotalEff", "", 1, 0., 1.); 
  TH1D* hZ_W_TotalEffLo  = new TH1D("hZ_W_TotalEffLo", "", 1, 0., 1.);
  TH1D* hZ_W_TotalEffMe1 = new TH1D("hZ_W_TotalEffMe1", "", 1, 0., 1.);
  TH1D* hZ_W_TotalEffMe2 = new TH1D("hZ_W_TotalEffMe2", "", 1, 0., 1.);
  TH1D* hZ_W_TotalEffHi  = new TH1D("hZ_W_TotalEffHi", "", 1, 0., 1.);
  
  //hZ_DY_EffVBFS->Add(hZ_DY_EffVBFS_N);
  //hZ_DY_EffVBFS->Divide(hZ_DY_EffVBFS_D);
  hZ_DY_EffVBFSLo->Add(hZ_DY_EffVBFS_NLo);
  hZ_DY_EffVBFSLo->Divide(hZ_DY_EffVBFS_D);
  hZ_DY_EffVBFSHi->Add(hZ_DY_EffVBFS_NHi);
  hZ_DY_EffVBFSHi->Divide(hZ_DY_EffVBFS_D);
  hZ_DY_EffVBFSMe1->Add(hZ_DY_EffVBFS_NMe1);
  hZ_DY_EffVBFSMe1->Divide(hZ_DY_EffVBFS_D);
  hZ_DY_EffVBFSMe2->Add(hZ_DY_EffVBFS_NMe2);
  hZ_DY_EffVBFSMe2->Divide(hZ_DY_EffVBFS_D);

  //hZ_W_EffVBFC->Add(hZ_W_EffVBFC_N);
  //hZ_W_EffVBFC->Divide(hZ_W_EffVBFC_D);
  hZ_W_EffVBFCLo->Add(hZ_W_EffVBFC_NLo);
  hZ_W_EffVBFCLo->Divide(hZ_W_EffVBFC_D);
  hZ_W_EffVBFCMe1->Add(hZ_W_EffVBFC_NMe1);
  hZ_W_EffVBFCMe1->Divide(hZ_W_EffVBFC_D);
  hZ_W_EffVBFCMe2->Add(hZ_W_EffVBFC_NMe2);
  hZ_W_EffVBFCMe2->Divide(hZ_W_EffVBFC_D);
  hZ_W_EffVBFCHi->Add(hZ_W_EffVBFC_NHi);
  hZ_W_EffVBFCHi->Divide(hZ_W_EffVBFC_D);

  //hZ_W_RatioVBF->Add(hZ_DY_EffVBFS);
  //hZ_W_RatioVBF->Divide(hZ_W_EffVBFC);
  hZ_W_RatioVBFLo->Add(hZ_DY_EffVBFSLo);
  hZ_W_RatioVBFLo->Divide(hZ_W_EffVBFCLo);
  hZ_W_RatioVBFMe1->Add(hZ_DY_EffVBFSMe1);
  hZ_W_RatioVBFMe1->Divide(hZ_W_EffVBFCMe1);
  hZ_W_RatioVBFMe2->Add(hZ_DY_EffVBFSMe2);
  hZ_W_RatioVBFMe2->Divide(hZ_W_EffVBFCMe2);
  hZ_W_RatioVBFHi->Add(hZ_DY_EffVBFSHi);
  hZ_W_RatioVBFHi->Divide(hZ_W_EffVBFCHi);

  hZ_W_TotalEffLo->Add(hZ_W_RatioVBFLo);
  hZ_W_TotalEffLo->Multiply(hZ_DY_EffMuMu);
  hZ_W_TotalEffLo->Divide(hZ_W_EffMu);
  hZ_W_TotalEffMe1->Add(hZ_W_RatioVBFMe1);
  hZ_W_TotalEffMe1->Multiply(hZ_DY_EffMuMu);
  hZ_W_TotalEffMe1->Divide(hZ_W_EffMu);
  hZ_W_TotalEffMe2->Add(hZ_W_RatioVBFMe2);
  hZ_W_TotalEffMe2->Multiply(hZ_DY_EffMuMu);
  hZ_W_TotalEffMe2->Divide(hZ_W_EffMu);
  hZ_W_TotalEffHi->Add(hZ_W_RatioVBFHi);
  hZ_W_TotalEffHi->Multiply(hZ_DY_EffMuMu);
  hZ_W_TotalEffHi->Divide(hZ_W_EffMu);

  //hZ_Eff_S_noDPhi->Add(hZ_W_RatioVBF);  
  //hZ_Eff_S_noDPhi->Divide(hZ_W_EffMu);
  hZ_Eff_WS_DPhi->SetBinContent(1,hZ_W_TotalEffLo->GetBinContent(1));
  hZ_Eff_WS_DPhi->SetBinError(1,hZ_W_TotalEffLo->GetBinError(1));
  hZ_Eff_WS_DPhi->SetBinContent(2,hZ_W_TotalEffMe1->GetBinContent(1));  
  hZ_Eff_WS_DPhi->SetBinError(2,hZ_W_TotalEffMe1->GetBinError(1));
  hZ_Eff_WS_DPhi->SetBinContent(3,hZ_W_TotalEffMe2->GetBinContent(1));
  hZ_Eff_WS_DPhi->SetBinError(3,hZ_W_TotalEffMe2->GetBinError(1));
  hZ_Eff_WS_DPhi->SetBinContent(4,hZ_W_TotalEffHi->GetBinContent(1));
  hZ_Eff_WS_DPhi->SetBinError(4,hZ_W_TotalEffHi->GetBinError(1));

  //for(int ibin = 1; ibin <= hZ_Eff_S_DPhi->GetNbinsX(); ++ibin) {
  //  hZ_Eff_S_DPhi->SetBinContent(ibin,hZ_W_TotalEff->GetBinContent(1));
  //  hZ_Eff_S_DPhi->SetBinError  (ibin,hZ_W_TotalEff->GetBinError(1));
  //}
  // Observed 
  hZ_Est_ZC_DPhi->Add(hZ_Data_ZC_DPhi, hZ_BG_ZC_DPhi, 1., -1.);
  // Predicted
  hZ_Est_WC_DPhi->Add(hZ_Data_WC_DPhi, hZ_BG_WC_DPhi, 1., -1.);
  hZ_Est_WS_DPhi->Add(hZ_Est_WC_DPhi,ratioBF);
  hZ_Est_WS_DPhi->Multiply(hZ_Eff_WS_DPhi);

  // print out

  std::cout << std::endl;
  std::cout << "##################################### Cross-check with W mu ctrl region #####################################" << std::endl;
  std::cout << std::endl;
  std::cout << "  eps_mumu by histogram  : " << hZ_DY_EffMuMu->GetBinContent(1) << " +/- " << hZ_DY_EffMuMu->GetBinError(1) << std::endl;
  std::cout << "  eps_mu by histogram    : " << hZ_W_EffMu->GetBinContent(1) << " +/- " << hZ_W_EffMu->GetBinError(1) << std::endl;
  std::cout << std::endl;
  std::cout << "dphi < 1.0" << std::endl;
  std::cout << std::endl;
  std::cout << "  eps_s_vbf by histogram : " << hZ_DY_EffVBFSLo->GetBinContent(1) << " +/- " << hZ_DY_EffVBFSLo->GetBinError(1) << std::endl;
  std::cout << "  eps_c_vbf by histogram : " << hZ_W_EffVBFCLo->GetBinContent(1) << " +/- " << hZ_W_EffVBFCLo->GetBinError(1) << std::endl;
  std::cout << "  ratio_vbf by histogram : " << hZ_W_RatioVBFLo->GetBinContent(1) << " +/- " << hZ_W_RatioVBFLo->GetBinError(1) << std::endl;
  std::cout << "  total eff by histogram : " << hZ_Eff_WS_DPhi->GetBinContent(1) << " +/- " << hZ_Eff_WS_DPhi->GetBinError(1) << std::endl;
  std::cout << std::endl;
  std::cout << "  W+jets MC ctrl region  : " << hZ_W_C_DPhi->GetBinContent(1) << " +/- " << hZ_W_C_DPhi->GetBinError(1) << std::endl;
  std::cout << "  Background ctrl region : " << hZ_BG_WC_DPhi->GetBinContent(1) << " +/- " << hZ_BG_WC_DPhi->GetBinError(1) << std::endl;
  std::cout << "  Data ctrl region       : " << hZ_Data_WC_DPhi->GetBinContent(1) << " +/- " << hZ_Data_WC_DPhi->GetBinError(1) << std::endl;
  std::cout << "  Data - BG              : " << hZ_Est_WC_DPhi->GetBinContent(1) << " +/- " << hZ_Est_WC_DPhi->GetBinError(1) << std::endl;
  std::cout << std::endl;
  std::cout << "  Predicted Zmumu        : " << hZ_Est_WS_DPhi->GetBinContent(1) << " +/- " << hZ_Est_WS_DPhi->GetBinError(1) << std::endl;
  std::cout << "  Observed Zmumu         : " << hZ_Est_ZC_DPhi->GetBinContent(1) << " +/- " << hZ_Est_ZC_DPhi->GetBinError(1) << std::endl;
  std::cout << std::endl;
  std::cout << "dphi > 1.0 dphi < 1.8" << std::endl;
  std::cout << std::endl;
  std::cout << "  eps_s_vbf by histogram : " << hZ_DY_EffVBFSMe1->GetBinContent(1) << " +/- " << hZ_DY_EffVBFSMe1->GetBinError(1) << std::endl;
  std::cout << "  eps_c_vbf by histogram : " << hZ_W_EffVBFCMe1->GetBinContent(1) << " +/- " << hZ_W_EffVBFCMe1->GetBinError(1) << std::endl;
  std::cout << "  ratio_vbf by histogram : " << hZ_W_RatioVBFMe1->GetBinContent(1) << " +/- " << hZ_W_RatioVBFMe1->GetBinError(1) << std::endl;
  std::cout << "  total eff by histogram : " << hZ_Eff_WS_DPhi->GetBinContent(2) << " +/- " << hZ_Eff_WS_DPhi->GetBinError(2) << std::endl;
  std::cout << std::endl;
  std::cout << "  W+jets MC ctrl region  : " << hZ_W_C_DPhi->GetBinContent(2) << " +/- " << hZ_W_C_DPhi->GetBinError(2) << std::endl;
  std::cout << "  Background ctrl region : " << hZ_BG_WC_DPhi->GetBinContent(2) << " +/- " << hZ_BG_WC_DPhi->GetBinError(2) << std::endl;
  std::cout << "  Data ctrl region       : " << hZ_Data_WC_DPhi->GetBinContent(2) << " +/- " << hZ_Data_WC_DPhi->GetBinError(2) << std::endl;
  std::cout << "  Data - BG     	 : " << hZ_Est_WC_DPhi->GetBinContent(2) << " +/- " << hZ_Est_WC_DPhi->GetBinError(2) << std::endl;
  std::cout << std::endl;
  std::cout << "  Predicted Zmumu        : " << hZ_Est_WS_DPhi->GetBinContent(2) << " +/- " << hZ_Est_WS_DPhi->GetBinError(2) << std::endl;
  std::cout << "  Observed Zmumu         : " << hZ_Est_ZC_DPhi->GetBinContent(2) << " +/- " << hZ_Est_ZC_DPhi->GetBinError(2) << std::endl;
  std::cout << std::endl;
  std::cout << "dphi > 1.8 dphi < 2.6" << std::endl;
  std::cout << std::endl;
  std::cout << "  eps_s_vbf by histogram : " << hZ_DY_EffVBFSMe2->GetBinContent(1) << " +/- " << hZ_DY_EffVBFSMe2->GetBinError(1) << std::endl;
  std::cout << "  eps_c_vbf by histogram : " << hZ_W_EffVBFCMe2->GetBinContent(1) << " +/- " << hZ_W_EffVBFCMe2->GetBinError(1) << std::endl;
  std::cout << "  ratio_vbf by histogram : " << hZ_W_RatioVBFMe2->GetBinContent(1) << " +/- " << hZ_W_RatioVBFMe2->GetBinError(1) << std::endl;
  std::cout << "  total eff by histogram : " << hZ_Eff_WS_DPhi->GetBinContent(3) << " +/- " << hZ_Eff_WS_DPhi->GetBinError(3) << std::endl;
  std::cout << std::endl;
  std::cout << "  W+jets MC ctrl region  : " << hZ_W_C_DPhi->GetBinContent(3) << " +/- " << hZ_W_C_DPhi->GetBinError(3) << std::endl;
  std::cout << "  Background ctrl region : " << hZ_BG_WC_DPhi->GetBinContent(3) << " +/- " << hZ_BG_WC_DPhi->GetBinError(3) << std::endl;
  std::cout << "  Data ctrl region       : " << hZ_Data_WC_DPhi->GetBinContent(3) << " +/- " << hZ_Data_WC_DPhi->GetBinError(3) << std::endl;
  std::cout << "  Data - BG       	 : " << hZ_Est_WC_DPhi->GetBinContent(3) << " +/- " << hZ_Est_WC_DPhi->GetBinError(3) << std::endl;
  std::cout << std::endl;
  std::cout << "  Predicted Zmumu        : " << hZ_Est_WS_DPhi->GetBinContent(3) << " +/- " << hZ_Est_WS_DPhi->GetBinError(3) << std::endl;
  std::cout << "  Observed Zmumu       	 : " << hZ_Est_ZC_DPhi->GetBinContent(3) << " +/- " << hZ_Est_ZC_DPhi->GetBinError(3) << std::endl;
  std::cout << std::endl;
  std::cout << "dphi > 2.6" << std::endl;
  std::cout << std::endl;
  std::cout << "  eps_s_vbf by histogram : " << hZ_DY_EffVBFSHi->GetBinContent(1) << " +/- " << hZ_DY_EffVBFSHi->GetBinError(1) << std::endl;
  std::cout << "  eps_c_vbf by histogram : " << hZ_W_EffVBFCHi->GetBinContent(1) << " +/- " << hZ_W_EffVBFCHi->GetBinError(1) << std::endl;
  std::cout << "  ratio_vbf by histogram : " << hZ_W_RatioVBFHi->GetBinContent(1) << " +/- " << hZ_W_RatioVBFHi->GetBinError(1) << std::endl;
  std::cout << "  total eff by histogram : " << hZ_Eff_WS_DPhi->GetBinContent(4) << " +/- " << hZ_Eff_WS_DPhi->GetBinError(4) << std::endl;
  std::cout << std::endl;
  std::cout << "  W+jets MC ctrl region  : " << hZ_W_C_DPhi->GetBinContent(4) << " +/- " << hZ_W_C_DPhi->GetBinError(4) << std::endl;
  std::cout << "  Background ctrl region : " << hZ_BG_WC_DPhi->GetBinContent(4) << " +/- " << hZ_BG_WC_DPhi->GetBinError(4) << std::endl;
  std::cout << "  Data ctrl region       : " << hZ_Data_WC_DPhi->GetBinContent(4) << " +/- " << hZ_Data_WC_DPhi->GetBinError(4) << std::endl;
  std::cout << "  Data - BG region       : " << hZ_Est_WC_DPhi->GetBinContent(4) << " +/- " << hZ_Est_WC_DPhi->GetBinError(4) << std::endl;
  std::cout << std::endl;
  std::cout << "  Predicted Zmumu        : " << hZ_Est_WS_DPhi->GetBinContent(4) << " +/- " << hZ_Est_WS_DPhi->GetBinError(4) << std::endl;
  std::cout << "  Observed Zmumu         : " << hZ_Est_ZC_DPhi->GetBinContent(4) << " +/- " << hZ_Est_ZC_DPhi->GetBinError(4) << std::endl;
  std::cout << std::endl;
  std::cout << "#####################################################################################" << std::endl;
  std::cout << std::endl;

  // draw control plots
  std::string pdfName;

  gStyle->SetOptStat(0);
  gStyle->SetOptFit(111111111);

  double x1[4]  = {0.5, 1.4, 2.2, 2.6 + (TMath::Pi()-2.6)/2};
  double ex1[4] = {0.5, 0.4, 0.4, (TMath::Pi()-2.6)/2};
  double y1[4],ey1[4],y2[4],ey2[4],y3[4],ey3[4];
  double diff[4],ediff[4];
  double frac[4],efrac[4];
  double y_syst[4],e_syst[4];

  for(int i=0; i<4; ++i) {
        y1[i]  = hZ_Est_WS_DPhi->GetBinContent(i+1);     //Prediction
        ey1[i] = hZ_Est_WS_DPhi->GetBinError(i+1);
        y2[i]  = hZ_Est_ZC_DPhi->GetBinContent(i+1);     //Observation
        ey2[i] = hZ_Est_ZC_DPhi->GetBinError(i+1); 
	y3[i]  = hZ_DY_C_DPhi->GetBinContent(i+1);       //MC Prediction
        ey3[i] = hZ_DY_C_DPhi->GetBinError(i+1);

	diff[i]  = y1[i]-y2[i];
	ediff[i] = sqrt(ey1[i]*ey1[i] + ey2[i]*ey2[i]);
        y_syst[i] = 0.;
        e_syst[i] = 0.21;

	if(y1[i] > 0) frac[i]  = (y1[i]-y2[i])/y2[i];
	efrac[i] = (y1[i]/y2[i])*sqrt(pow(ey1[i]/y1[i],2) + pow(ey2[i]/y2[i],2));
  }

  TGraphErrors *graph1 = new TGraphErrors(4,x1,y1,ex1,ey1);
  TGraphErrors *graph2 = new TGraphErrors(4,x1,y2,ex1,ey2);
  TGraphErrors *graph6 = new TGraphErrors(4,x1,y3,ex1,ey3);
  TGraphErrors *graph3 = new TGraphErrors(4,x1,diff,ex1,ediff);
  TGraphErrors *graph4 = new TGraphErrors(4,x1,frac,ex1,efrac);
  TGraphErrors *graph5 = new TGraphErrors(4,x1,y_syst,ex1,e_syst);
  TH1D *h = new TH1D("h", "", 1, 0, TMath::Pi());

  TCanvas canvas;
  canvas.SetCanvasSize(canvas.GetWindowWidth(), 1.2*canvas.GetWindowHeight());

  graph1->SetTitle("");
  graph1->SetMarkerStyle(20);
  graph1->SetMarkerSize(0.9);
  graph1->SetLineColor(kRed);
  graph1->SetMarkerColor(kRed);  
  graph1->GetXaxis()->SetTitle("#Delta #phi_{jj}");
  graph1->GetXaxis()->SetRangeUser(0,TMath::Pi());
  graph1->GetYaxis()->SetTitle("N(Z#rightarrow #mu#mu)");
  graph1->GetYaxis()->SetRangeUser(0,45);
  graph1->Draw("AP");  
  graph2->SetMarkerStyle(20);
  graph2->SetMarkerSize(0.9);
  graph2->SetLineColor(kBlue);
  graph2->SetMarkerColor(kBlue);
  graph2->Draw("P same");
  graph6->SetMarkerStyle(20);
  graph6->SetMarkerSize(0.9);
  graph6->SetLineColor(kViolet);
  graph6->SetMarkerColor(kViolet);
  graph6->Draw("P same");

  TLegend leg(0.12,0.67,0.37,0.88);
  leg.SetBorderSize(0);
  leg.SetFillColor(0);
  leg.AddEntry(graph1,"predicted (data)","P");
  leg.AddEntry(graph2,"observed (data)","P");
  leg.AddEntry(graph6,"predicted (MC)","P");
  leg.Draw();

  pdfName= oDir + std::string("/Zmumu_num.pdf");
  canvas.Print(pdfName.c_str());

  h->GetXaxis()->SetTitle("#Delta #phi_{jj}");
  h->GetYaxis()->SetTitle("Predicted - Observed");
  h->GetYaxis()->SetRangeUser(-20,20);
  h->SetLineColor(kBlue);
  h->Draw();
  graph3->SetMarkerStyle(20);
  graph3->SetMarkerSize(0.9);
  graph3->SetMarkerColor(kGreen-2);
  TF1 *f1 = new TF1("f1","pol0",0,TMath::Pi());
  graph3->Fit("f1","R");
  h->Draw();
  graph3->Draw("SAMEP");

  pdfName= oDir + std::string("/Zmumu_diff.pdf");
  canvas.Print(pdfName.c_str());

  h->GetXaxis()->SetTitle("#Delta #phi_{jj}");
  h->GetYaxis()->SetTitle("#frac{Predicted - Observed}{Observed}");
  h->GetYaxis()->SetTitleOffset(1.2);
  h->GetYaxis()->SetRangeUser(-2,2);
  h->SetLineColor(kBlue);
  h->SetLineWidth(2);
  h->Draw();
  graph5->SetLineColor(kGray+2);
  graph5->SetLineWidth(0);
  graph5->SetFillColor(kGray+2);
  graph5->SetFillStyle(3002);
  graph4->SetMarkerStyle(20);
  graph4->SetMarkerSize(1.2);
  graph4->SetMarkerColor(kGreen-2);
  graph4->Fit("f1","R");
  h->Draw();
  graph5->Draw("2 same");
  graph4->Draw("P same");

  TLegend leg2(0.12,0.67,0.40,0.87);
  leg2.SetBorderSize(0);
  leg2.SetFillColor(0);
  leg2.AddEntry(f1,"pol0 fit (0 < #Delta #phi_{jj} < #pi)","l");
  leg2.AddEntry(graph5,"Systematic error","f");
  leg2.Draw();
  pdfName= oDir + std::string("/Zmumu_frac.pdf");
  canvas.Print(pdfName.c_str());

  //store histograms
  ofile->cd();
  hZ_DY_C_DPhi->Write("",TObject::kOverwrite);
  hZ_BG_ZC_DPhi->Write("",TObject::kOverwrite);
  hZ_Data_ZC_DPhi->Write("",TObject::kOverwrite);
  hZ_W_C_DPhi->Write("",TObject::kOverwrite);
  hZ_BG_WC_DPhi->Write("",TObject::kOverwrite);
  hZ_Data_WC_DPhi->Write("",TObject::kOverwrite);
  hZ_Est_ZC_DPhi->Write("",TObject::kOverwrite);
  hZ_Est_WC_DPhi->Write("",TObject::kOverwrite);
  hZ_Est_WS_DPhi->Write("",TObject::kOverwrite);
  hZ_Eff_WS_DPhi->Write("",TObject::kOverwrite);
  hZ_DY_EffMuMu_D->Write("",TObject::kOverwrite);
  hZ_DY_EffMuMu_N->Write("",TObject::kOverwrite);
  hZ_W_EffMu_D->Write("",TObject::kOverwrite);
  hZ_W_EffMu_N->Write("",TObject::kOverwrite);
  hZ_DY_EffVBFS_D->Write("",TObject::kOverwrite);
  hZ_DY_EffVBFS_NLo->Write("",TObject::kOverwrite);
  hZ_DY_EffVBFS_NMe1->Write("",TObject::kOverwrite);
  hZ_DY_EffVBFS_NMe2->Write("",TObject::kOverwrite);
  hZ_DY_EffVBFS_NHi->Write("",TObject::kOverwrite);
  hZ_W_EffVBFC_D->Write("",TObject::kOverwrite);
  hZ_W_EffVBFC_NLo->Write("",TObject::kOverwrite);
  hZ_W_EffVBFC_NMe1->Write("",TObject::kOverwrite);
  hZ_W_EffVBFC_NMe2->Write("",TObject::kOverwrite);
  hZ_W_EffVBFC_NHi->Write("",TObject::kOverwrite);
  hZ_W_EffMu->Write("",TObject::kOverwrite);
  //hZ_DY_EffVBFS->Write("",TObject::kOverwrite);
  //hZ_W_EffVBFC->Write("",TObject::kOverwrite);
  //hZ_W_RatioVBF->Write("",TObject::kOverwrite);
  //hZ_W_TotalEff->Write("",TObject::kOverwrite);
 
  ofile->Close();    

}
//---------------------------------------------------------------------------
//function to plot res vs. energy for pions (uses current dir, etc. settings)
//qty: 0 = response, 1 = resolution, 2 = sampling factor
TGraphErrors* g4_plot_res(int snum, int qty, bool do_pion, bool use_f_pion, bool do_fit, bool do_show, bool do_print=false){
	Sample* sp = sample_map[snum];
	if(!sp) { std::cout << "Sample " << snum << " is not loaded." << std::endl; return 0; }

	//store values from get_res
	Double_t* vals = new Double_t[maxHDe]; //sigma or mean
	Double_t* xvals = new Double_t[maxHDe]; //sigma or mean
	Double_t* y_errors = new Double_t[maxHDe]; //errors on pars
	Double_t* logxvals = new Double_t[maxHDe]; //sigma or mean

	//for storage of output info
	energyRes* res_temp;

	for (int i = 0; i < maxHDe; i++){
		double energy = energies[i];
	
		Double_t v, ve;
	
		if(qty==2){
			//get sampling factor for energy without setting value
			std::pair<Double_t,Double_t> f_temp = g4_sample(snum,energy,do_pion,0);
			v = f_temp.first;
			ve = f_temp.second;
		}
		else {
			res_temp = get_res(snum,energy,do_pion,use_f_pion,do_fit,0,0,1);

			Double_t m, me, s, se;
			if(do_fit){
				TF1* fit = res_temp->getFit();
				m = fit->GetParameter(1);
				me = fit->GetParError(1);
				s = fit->GetParameter(2);
				se = fit->GetParError(2);
			}
			else{
				m = res_temp->getStat(1);
				me = res_temp->getStatErr(1);
				s = res_temp->getStat(2);
				se = res_temp->getStatErr(2);
			}
			
			if(qty==1){
				v = s/m;
				ve = v*sqrt(se*se/(s*s)+me*me/(m*m));
			}
			else if(qty==0){
				v = m/energy;
				ve = me/energy;
			}
		}
		
		xvals[i] = energy;
		logxvals[i] = log(energy);
		vals[i] = v;
		y_errors[i] = ve;
	}

	TCanvas* can;
	TPaveText* pave;
	TGraphErrors* val_graph;
	TGraphErrors* fit_graph;

	Int_t col, mrk;
	col = kBlue; mrk = 21;

	//graph values
	std::string qtyaxes[] = {"Response (#mu/E_{true})","Resolution (#sigma/#mu)","sampling factor"};
	if(do_pion) qtyaxes[0] = sp->name_rat + " #pi^{-} Response (R_{cal}/E_{gen})";
	else qtyaxes[0] = sp->name_rat + " e^{-} Response (R_{cal}/E_{gen})";
	fit_graph = new TGraphErrors(maxHDe,logxvals,vals,0,y_errors);
	val_graph = new TGraphErrors(maxHDe,xvals,vals,0,y_errors);
	val_graph->GetXaxis()->SetTitle("Energy [GeV]");
	val_graph->GetYaxis()->SetTitle(qtyaxes[qty].c_str());
	val_graph->SetTitle("");
	val_graph->SetMarkerStyle(mrk);
	val_graph->SetMarkerColor(col);
	val_graph->SetMarkerSize(1.5);
	val_graph->SetLineColor(col);
	val_graph->SetFillColor(0);

	//fit response for e/pi from pions
	TF1* gfit = 0;
	TF1* gline = 0;
	double c, ce, k, ke;
	std::stringstream epiname, ehname, kname;
	if(qty==0 && do_pion){
		gfit = new TF1("epi_fit","pol1",fit_graph->GetXaxis()->GetXmin(),fit_graph->GetXaxis()->GetXmax());
		//gfit = new TF1("epi_fit","(1+([0]-1)*([1]*x))/[0]",val_graph->GetXaxis()->GetXmin(),val_graph->GetXaxis()->GetXmax());
		//gfit = new TF1("epi","(1+([0]-1)*([1]*x^[2]))/[0]",val_graph->GetXaxis()->GetXmin(),val_graph->GetXaxis()->GetXmax());
		gfit->SetParameter(0,0.9);
		gfit->SetParameter(1,0.01);
		//gfit->SetParameter(2,-2.8);
		fit_graph->Fit(gfit,"NR");
		
		//results
		double a, ae, b, be;
		a = gfit->GetParameter(0);
		ae = gfit->GetParError(0);
		b = gfit->GetParameter(1);
		be = gfit->GetParError(1);
		
		//transform to desired params
		c = 1./a;
		ce = ae/(a*a);
		k = b/(1.-a);
		ke = sqrt(pow(be/(1.-a),2) + pow(ae*b/pow(1-a,2),2));
		std::cout.precision(2);
		std::cout << "e/h = " << c << " +/- " << ce << ", k = " << k << " +/- " << ke << std::endl;
		
		//store params in sample
		sp->eh = c;
		sp->eh_err = ce;
		sp->k = k;
		sp->k_err = ke;

		epiname.precision(2);
		epiname << "#frac{R}{E} = #frac{#pi}{e}(E) = #frac{1 + (e/h - 1) #upoint k ln(E)}{e/h}";
		ehname.precision(2);
		ehname << "e/h = " << c << " #pm " << ce;
		kname.precision(2);
		kname << "k = " << k << " #pm " << ke;
		
		//line for E instead of log(E)
		gline = new TF1("epi","(1+([0]-1)*([1]*log(x)))/[0]",val_graph->GetXaxis()->GetXmin(),val_graph->GetXaxis()->GetXmax());
		gline->SetParameter(0,c);
		gline->SetParameter(1,k);
		//formatting
		gline->SetLineColor(kRed);
		gline->SetMarkerColor(kRed);
		gline->SetLineWidth(2);
	}
	
	if(do_show){
		std::string cname;
		cname = "res";
		can = new TCanvas(cname.c_str(),cname.c_str(),700,500);
		can->cd();
		//can->SetLogx();

		//if(qty) val_graph->GetYaxis()->SetRangeUser(0,0.4);
		//else val_graph->GetYaxis()->SetRangeUser(0,1.1);
		val_graph->Draw("APZ");

		//legend, pave coords
		double y1;
		if(qty) y1 = 0.5;
		else y1 = 0.2;
		
		std::string pavename = sp->name;
		if(do_pion) pavename += " #pi^{-}";
		else pavename += " e^{-}";
		
		pave = new TPaveText(0.5,y1,0.95,y1+0.2,"NDC");
		if(qty==0 && do_pion){
			pave->AddText((epiname.str()).c_str());
			pave->AddText((ehname.str()).c_str());
			pave->AddText((kname.str()).c_str());
		}
		else{
			pave->AddText(pavename.c_str());
		}
		pave->SetFillColor(0);
		pave->SetBorderSize(0);
		pave->SetTextFont(42);
		pave->SetTextSize(0.05);
		pave->Draw("same");
		
		if(gline) gline->Draw("same");
		
		if(do_print){
			std::string fpre = sp->fpre;
			if(do_pion) fpre += "_pion";
			else fpre += "_elec";
		
			//names
			std::string ofit;
			if(do_fit) ofit = "fit";
			else ofit = "nofit";
			std::string qtyname[] = {"mu","sigma","sam"};
			std::stringstream oname;
			oname << pdir << "/" << fpre;
			if(use_f_pion) oname << "_fpion";
			oname << "_" << qtyname[qty] << "_" << ofit;
			oname << "." << pformat;
			can->Print((oname.str()).c_str(),pformat.c_str());
		}
	}

	return val_graph;
}
Exemple #11
0
void plotDistribution( TChain* data , TChain *mc , TCut sel , TCut vtxweight , char* var , int nbins , float xmin , float xmax , char* xtitle , char* plottitle = "" , bool printplot = false , bool residual = false , bool log = false ){

  //--------------------------------------
  // define histograms and TGraphs
  //--------------------------------------

  TH1F* hdata      = new TH1F(Form("hdata_%i"     , iplot),Form("hdata_%i"    , iplot),nbins,xmin,xmax);
  TH1F* hmc        = new TH1F(Form("hmc_%i"       , iplot),Form("hmc_%i"      , iplot),nbins,xmin,xmax);
  TH1F* hmc_novtx  = new TH1F(Form("hmc_novtx_%i" , iplot),Form("hmc_novtx%i" , iplot),nbins,xmin,xmax);

  hdata->Sumw2();
  hmc->Sumw2();

  TGraphAsymmErrors* grdata = new TGraphAsymmErrors();
  TGraphAsymmErrors* grmc   = new TGraphAsymmErrors();

  TH1F* hdata_denom = new TH1F(Form("hdata_denom_%i",iplot),"",nbins,xmin,xmax);
  TH1F* hmc_denom   = new TH1F(Form("hmc_denom_%i"  ,iplot),"",nbins,xmin,xmax);

  //--------------------------------------
  // set up canvas and pads
  //--------------------------------------

  TCanvas *can = new TCanvas(Form("can_%i",iplot),Form("can_%i",iplot),600,600);
  can->cd();
  if( log ) gPad->SetLogy();

  TPad *mainpad = new TPad("mainpad","mainpad",0.0,0.0,1.0,0.8);

  if( residual ){
    mainpad->Draw();
    mainpad->cd();
    if( log ) mainpad->SetLogy();
  }

  //--------------------------------------
  // fill histos and TGraphs
  //--------------------------------------

  data->Draw(Form("min(%s,%f)>>hdata_%i"     , var,xmax-0.0001,iplot),sel);
  mc  ->Draw(Form("min(%s,%f)>>hmc_%i"       , var,xmax-0.0001,iplot),sel*vtxweight);
  mc  ->Draw(Form("min(%s,%f)>>hmc_novtx_%i" , var,xmax-0.0001,iplot),sel);

  for( int ibin = 1 ; ibin <= nbins ; ibin++ ){
    hdata_denom->SetBinContent(ibin,hdata->Integral());
    hmc_denom->SetBinContent(ibin,hmc->Integral());
  }

  grdata->BayesDivide(hdata,hdata_denom);
  grmc->BayesDivide(hmc_novtx,hmc_denom);

  //--------------------------------------
  // get efficiencies and errors
  //--------------------------------------

  /*
  float ndata1     = (float) hdata->GetBinContent(1);
  float ndata      = (float) hdata->Integral();
  float effdata    = 1-ndata1 / ndata;

  // TGraphAsymmErrors* grdata_temp = new TGraphAsymmErrors();
  // TH1F* hdata_num_temp = new TH1F(Form("hdata_num_temp_%i",iplot),"",1,0,1);
  // TH1F* hdata_den_temp = new TH1F(Form("hdata_den_temp_%i",iplot),"",1,0,1);
  // hdata_num_temp->SetBinContent(1,ndata-ndata1);
  // hdata_den_temp->SetBinContent(1,ndata);
  // grdata_temp->BayesDivide(hdata_num_temp,hdata_den_temp);

  //float effdataerr = sqrt(ndata1) / ndata;
  float effdataerr = 0.5 * ( grdata->GetErrorYlow(0) + grdata->GetErrorYhigh(0) );
  //float effdataerr = 0.5 * ( grdata_temp->GetErrorYlow(0) + grdata_temp->GetErrorYhigh(0) );

  float nmc1       = (float) hmc->GetBinContent(1);
  float nmc        = (float) hmc->Integral();
  float effmc      = 1-nmc1 / nmc;
  //float effmcerr   = hmc->GetBinError(1) / nmc;
  float effmcerr   = 0.5 * ( grmc->GetErrorYlow(0) + grmc->GetErrorYhigh(0) );


  float datatot = hdata->Integral();
  float mctot   = hmc->Integral();
  
  cout << endl;
  cout << plottitle << endl;

  cout << "Data eff  " << Form("%.2f +/- %.3f",effdata,effdataerr) << endl;
  cout << "MC   eff  " << Form("%.2f +/- %.3f",effmc  ,effmcerr)   << endl;
  cout << "Data/MC   " << Form("%.2f +/- %.2f",ratio  ,ratioerr)   << endl;
  */

  float ndata    = hdata->Integral();
  float ndata1   = hdata->Integral(2,20);
  float ndata2   = hdata->Integral(3,20);
  float ndata3   = hdata->Integral(4,20);
  float ndata4   = hdata->Integral(5,20);
  float ndata5   = hdata->Integral(6,20);

  float nmc      = hmc->Integral();
  float nmc1     = hmc->Integral(2,20);
  float nmc2     = hmc->Integral(3,20);
  float nmc3     = hmc->Integral(4,20);
  float nmc4     = hmc->Integral(5,20);
  float nmc5     = hmc->Integral(6,20);

  float effdata1 = ndata1/ndata;
  float effdata2 = ndata2/ndata;
  float effdata3 = ndata3/ndata;
  float effdata4 = ndata4/ndata;
  float effdata5 = ndata5/ndata;

  float effmc1   = nmc1/nmc;
  float effmc2   = nmc2/nmc;
  float effmc3   = nmc3/nmc;
  float effmc4   = nmc4/nmc;
  float effmc5   = nmc5/nmc;

  float effdata1err = getBinomialError(ndata1,ndata);
  float effdata2err = getBinomialError(ndata2,ndata);
  float effdata3err = getBinomialError(ndata3,ndata);
  float effdata4err = getBinomialError(ndata4,ndata);
  float effdata5err = getBinomialError(ndata5,ndata);

  float effmc1err   = getBinomialError(nmc1,nmc);
  float effmc2err   = getBinomialError(nmc2,nmc);
  float effmc3err   = getBinomialError(nmc3,nmc);
  float effmc4err   = getBinomialError(nmc4,nmc);
  float effmc5err   = getBinomialError(nmc5,nmc);

  float ratio1      = effdata1/effmc1;
  float ratio2      = effdata2/effmc2;
  float ratio3      = effdata3/effmc3;
  float ratio4      = effdata4/effmc4;
  float ratio5      = effdata5/effmc5;

  float ratio1err   = ratio1 * sqrt(pow(effdata1err/effdata1,2)+pow(effmc1err/effmc1,2));
  float ratio2err   = ratio2 * sqrt(pow(effdata2err/effdata2,2)+pow(effmc2err/effmc2,2));
  float ratio3err   = ratio3 * sqrt(pow(effdata3err/effdata3,2)+pow(effmc3err/effmc3,2));
  float ratio4err   = ratio4 * sqrt(pow(effdata4err/effdata4,2)+pow(effmc4err/effmc4,2));
  float ratio5err   = ratio5 * sqrt(pow(effdata5err/effdata5,2)+pow(effmc5err/effmc5,2));

  cout << endl << endl << plottitle << endl;

  int left = 20;


  // char* delimstart = "|";
  // char* delim      = "|";
  // char* delimend   = "|";
  // char* pm         = "+/-";

  char* delimstart = "";
  char* delim      = "&";
  char* delimend   = "\\\\";
  char* pm         = "$\\pm$";

  cout << delimstart << setw(10) << "" << setw(4)
       << delim << setw(left) << "$>$ 1 GeV" << setw(4)
       << delim << setw(left) << "$>$ 2 GeV" << setw(4)
       << delim << setw(left) << "$>$ 3 GeV" << setw(4) 
       << delim << setw(left) << "$>$ 4 GeV" << setw(4)
       << delim << setw(left) << "$>$ 5 GeV" << setw(4) 
       << delimend << endl;

  cout << delimstart << setw(10) << "data" << setw(4)
       << delim << setw(left) << Form("%.3f %s %.4f",effdata1,pm,effdata1err) << setw(4)
       << delim << setw(left) << Form("%.3f %s %.4f",effdata2,pm,effdata2err) << setw(4)
       << delim << setw(left) << Form("%.3f %s %.4f",effdata3,pm,effdata3err) << setw(4) 
       << delim << setw(left) << Form("%.3f %s %.4f",effdata4,pm,effdata4err) << setw(4)
       << delim << setw(left) << Form("%.3f %s %.4f",effdata5,pm,effdata5err) << setw(4) 
       << delimend << endl;

  cout << delimstart << setw(10) << "mc" << setw(4)
       << delim << setw(left) << Form("%.3f %s %.4f",effmc1,pm,effmc1err) << setw(4)
       << delim << setw(left) << Form("%.3f %s %.4f",effmc2,pm,effmc2err) << setw(4)
       << delim << setw(left) << Form("%.3f %s %.4f",effmc3,pm,effmc3err) << setw(4) 
       << delim << setw(left) << Form("%.3f %s %.4f",effmc4,pm,effmc4err) << setw(4)
       << delim << setw(left) << Form("%.3f %s %.4f",effmc5,pm,effmc5err) << setw(4) 
       << delimend << endl;

  cout << delimstart << setw(10) << "data/mc" << setw(4)
       << delim << setw(left) << Form("%.2f %s %.2f",ratio1,pm,ratio1err) << setw(4)
       << delim << setw(left) << Form("%.2f %s %.2f",ratio2,pm,ratio2err) << setw(4)
       << delim << setw(left) << Form("%.2f %s %.2f",ratio3,pm,ratio3err) << setw(4) 
       << delim << setw(left) << Form("%.2f %s %.2f",ratio4,pm,ratio4err) << setw(4)
       << delim << setw(left) << Form("%.2f %s %.2f",ratio5,pm,ratio5err) << setw(4) 
       << delimend << endl;

  //--------------------------------------
  // draw stuff
  //--------------------------------------

  hdata->Scale(1.0/hdata->Integral());
  hmc->Scale(1.0/hmc->Integral());

  if( log ) hmc->GetYaxis()->SetRangeUser(0.0001,5);  
  else      hmc->GetYaxis()->SetRangeUser(0.0,1);  

  hmc->GetXaxis()->SetTitle(xtitle);
  hmc->SetLineColor(2);
  hmc->SetMarkerColor(2);
  hmc->DrawNormalized("hist");
  hmc->DrawNormalized("sameE1");
  hdata->SetLineColor(4);
  hdata->SetMarkerColor(4);
  hdata->Draw("sameE1");

  grdata->SetLineColor(6);
  grmc->SetLineColor(7);
  //grdata->Draw("sameP");
  //grmc->Draw("sameP");

  TLegend *leg = new TLegend(0.6,0.7,0.8,0.9);
  leg->AddEntry(hdata , "data" , "lp");
  leg->AddEntry(hmc   , "MC"   , "lp");
  leg->SetBorderSize(0);
  leg->SetFillColor(0);			       
  leg->Draw();

  TLatex *t = new TLatex();
  t->SetNDC();

  if( TString(plottitle).Contains("el") ) t->DrawLatex(0.6,0.6,"electrons");
  if( TString(plottitle).Contains("mu") ) t->DrawLatex(0.6,0.6,"muons");

  if( TString(plottitle).Contains("0j") ) t->DrawLatex(0.6,0.5,"n_{jets} #geq 0");
  if( TString(plottitle).Contains("1j") ) t->DrawLatex(0.6,0.5,"n_{jets} #geq 1");
  if( TString(plottitle).Contains("2j") ) t->DrawLatex(0.6,0.5,"n_{jets} #geq 2");
  if( TString(plottitle).Contains("3j") ) t->DrawLatex(0.6,0.5,"n_{jets} #geq 3");
  if( TString(plottitle).Contains("4j") ) t->DrawLatex(0.6,0.5,"n_{jets} #geq 4");

  //--------------------------------------
  // draw residual plots
  //--------------------------------------

  if( residual ){
    can->cd();
  
    TPad *respad = new TPad("respad","respad",0.0,0.8,1.0,1.0);
    respad->Draw();
    respad->cd();
    respad->SetGridy();

    TH1F* hratio = (TH1F*) hdata->Clone(Form("hratio_%i",iplot));
    hratio->Divide(hmc);

    hratio->SetMarkerColor(1);
    hratio->SetLineColor(1);
    hratio->Draw();
    hratio->GetYaxis()->SetRangeUser(0.5,1.5);
    hratio->GetYaxis()->SetNdivisions(5);
    hratio->GetYaxis()->SetLabelSize(0.2);
    hratio->GetXaxis()->SetLabelSize(0.0);
  
    TLine line;
    line.DrawLine(xmin,1.0,xmax,1.0);
  }
  
  //data->Scan("run:lumi:event:probe->pt():probe->eta():tkisonew:met:mt:njets:nbl:nbm",sel+"tkisonew>20");
  //data->Scan("run:lumi:event:probe->pt():probe->eta():tkisonew:met:mt:njets:nbl:nbm",sel);

  if( printplot ) can->Print(Form("plots/%s.pdf",plottitle));

  iplot++;

  // TCanvas *c2 = new TCanvas();
  // c2->cd();
  // grdata->Draw("AP");

}
//------------------------------------
//function to fit energy distributions
energyRes* get_res(int snum, Double_t energy, bool do_pion, bool use_f_pion, bool do_fit, bool do_show, bool do_print=false, bool do_batch=false){
	Sample* sp = sample_map[snum];
	if(!sp) { std::cout << "Sample " << snum << " is not loaded." << std::endl; energyRes* theRes = new energyRes(0,0); return theRes; }
	
	//select correct file
	std::string fpre = sp->fpre;
	if(do_pion) fpre += "_pion";
	else fpre += "_elec";

	//make filenames
	std::stringstream drawname, fname, piname;
	fname << sp->dir << "/" << fpre << "_" << energy << "gev_10k.root";
	if(do_pion) piname << "#pi^{-} " << energy << " GeV";
	else piname << "e^{-} " << energy << " GeV";

	//open file and tree
	TFile* _file;
	_file = TFile::Open((fname.str()).c_str());
	TTree* totalTree = (TTree*)_file->Get("Total");

	//default histo settings
	//double Emin = 0.1*energies[num]; //lower cut to remove weird peaks near E=zero
	double Emin = 0;
	double Emax = 2*energy;
	int nbins = 100;
	
	//ecal & hcal energies need to be calibrated
	get_sampling_factors(snum);

	//make tree drawing expressions
	//define mip as ecal < 1 gev = 1000 mev
	if(use_f_pion) drawname << sp->sam_pion;
	else drawname << sp->sam_elec;
	
	if(sp->det==Hcal) drawname << "*(hcal+" << sp->zeroWt << "*zero)/1000";
	else drawname << "*ecal/1000";

	drawname << ">>htemp(" << nbins << "," << Emin << "," << Emax << ")";
	//std::cout << drawname.str() << std::endl;

	TH1F* h_res; //to store histos drawn from tree
	TF1* gfit;
	TF1* gsnL;
	TF1* gsnR;

	//plotting variables
	TCanvas* can;
	TPad* pad;
	TLegend* leg;
	TPaveText* pave;
	TPaveText* pave_par;
	TLine *aLline;
	TLine *aRline;

	//create instance of energyRes object
	energyRes* theRes = new energyRes(energy,2);

	//draw w/ appropriate cut
	totalTree->Draw((drawname.str()).c_str(),"","hist goff");
	h_res = (TH1F*)gDirectory->Get("htemp");
	h_res->SetTitle("");
	h_res->GetXaxis()->SetTitle("Energy [GeV]");
	h_res->SetLineWidth(2);
	h_res->SetLineColor(kBlack);

	//names
	std::string ofit;
	if(do_fit) ofit = "fit";
	else ofit = "nofit";
	std::stringstream oname;
	oname << pdir << "/" << fpre;
	if(use_f_pion) oname << "_fpion";
	oname << "_response_" << ofit << "_" << energy << "gev";
	
	//get values from histo
	Double_t m = h_res->GetMean();
	Double_t me = h_res->GetMeanError();
	//Double_t m = h_res->GetBinCenter(h_res->GetMaximumBin()); //peak
	Double_t s = h_res->GetRMS();
	Double_t se = h_res->GetRMSError();
	Int_t N = h_res->GetEntries();
	
	std::vector<Double_t> stats(3,0);
	std::vector<Double_t> stat_err(3,0);
	stats[0] = N;
	stat_err[0] = 0;
	stats[1] = m;
	stat_err[1] = me;
	stats[2] = s;
	stat_err[2] = se;

	//find peak
	TSpectrum *spec = new TSpectrum(5);
	if(nbins < 100) spec->Search(h_res,6,"nobackground nodraw goff"); //turn off background removal when nbins too small
	else spec->Search(h_res,6,"nodraw goff");
	Float_t* xpos = spec->GetPositionX();
	Float_t* ypos = spec->GetPositionY();
	Double_t p = xpos[0];
	Double_t ph = ypos[0];
	if(do_show) std::cout << "peak: " << p << std::endl;
	
	//setup fitting function & do fit
	if (do_fit){
		gfit = new TF1("resp","gaus",0,h_res->GetXaxis()->GetXmax());
		//if(do_jet){
		//	gfit->SetParameters(ph,p,s);
		//	if(m > p) gfit->SetRange(p-1.5*s,p+1.0*s); //high tail
		//	else gfit->SetRange(p-1.0*s,p+1.5*s); //low tail
		//}
		//else{
			gfit->SetParameters((Double_t)N,m,s);
			gfit->SetRange(m-2*s,m+1*s); //fit within 2 std devs
			//if(m > p) gfit->SetRange(p-2*s,p+1*s); //high tail
			//else gfit->SetRange(p-1*s,p+2*s); //low tail
		//}
		
		//formatting
		gfit->SetLineColor(kRed);
		gfit->SetMarkerColor(kRed);
		gfit->SetLineWidth(2);
		//fit
		h_res->Fit(gfit,"LNQR");
	}
	
	//store parameters
	theRes->setStats(stats,stat_err);
	if(do_fit) theRes->setFit(gfit);
	//store histo
	h_res->SetDirectory(0);
	theRes->setHist(h_res);
	
	std::stringstream muname, signame, musigname, aLname, nLname, aRname, nRname, Nname, chiname;
	muname.precision(2);
	signame.precision(2);
	musigname.precision(3);
	aLname.precision(2);
	nLname.precision(2);
	aRname.precision(2);
	nRname.precision(2);
	chiname.precision(5);
	if (do_fit) {
		muname << fixed << "#mu = " << gfit->GetParameter(1) << " #pm " << gfit->GetParError(1);
		signame << fixed << "#sigma = " << gfit->GetParameter(2) << " #pm " << gfit->GetParError(2);
		musigname << fixed << "#sigma/#mu = " << gfit->GetParameter(2)/gfit->GetParameter(1) << " #pm " << 
		gfit->GetParameter(2)/gfit->GetParameter(1) * sqrt( Power(gfit->GetParError(1),2)/Power(gfit->GetParameter(1),2) +  Power(gfit->GetParError(2),2)/Power(gfit->GetParameter(2),2) );
		//aLname << fixed << "a_{L} = " << gfit->GetParameter(3) << " #pm " << gfit->GetParError(3);
		//nLname << fixed << "n_{L} = " << gfit->GetParameter(4) << " #pm " << gfit->GetParError(4);
		//aRname << fixed << "a_{R} = " << gfit->GetParameter(5) << " #pm " << gfit->GetParError(5);
		//nRname << fixed << "n_{R} = " << gfit->GetParameter(6) << " #pm " << gfit->GetParError(6);
		chiname << fixed << "#chi^{2}/ndf = " << gfit->GetChisquare()/gfit->GetNDF();
	}
	else {
		muname << fixed << "Mean = " << m << " #pm " << me;
		signame << fixed << "RMS = " << s << " #pm " << se;
		musigname << fixed << "RMS/Mean = " << s/m << " #pm " << s/m*sqrt((me*me)/(m*m)+(se*se)/(s*s));
	}
	Nname << "N = " << N; 

	//plotting
	if (do_show){
		can = new TCanvas((oname.str()).c_str(),(oname.str()).c_str(),700,500);
		can->cd();
		pad = new TPad("graph","",0,0,1,1);
		pad->SetMargin(0.12,0.05,0.15,0.05);
		pad->Draw();
		pad->cd();
		
		//formatting
		h_res->SetStats(kTRUE);
		gStyle->SetOptStat("mr");
		h_res->GetYaxis()->SetTitleSize(32/(pad->GetWh()*pad->GetAbsHNDC()));
		h_res->GetYaxis()->SetLabelSize(28/(pad->GetWh()*pad->GetAbsHNDC()));
		h_res->GetXaxis()->SetTitleSize(32/(pad->GetWh()*pad->GetAbsHNDC()));
		h_res->GetXaxis()->SetLabelSize(28/(pad->GetWh()*pad->GetAbsHNDC()));
		h_res->GetYaxis()->SetTickLength(12/(pad->GetWh()*pad->GetAbsHNDC()));
		h_res->GetXaxis()->SetTickLength(12/(pad->GetWh()*pad->GetAbsHNDC()));
		
		//plot histo and fit
		h_res->Draw("hist");
		if(do_fit) gfit->Draw("same");	
	
		//determine placing of legend and paves - par pave goes on side with more space
		Double_t xmin;
		if (m/((h_res->GetXaxis()->GetXmax() + h_res->GetXaxis()->GetXmin())/2) < 1) xmin = 0.65;
		else xmin = 0.2;
	
		if(do_fit) { //legend
			leg = new TLegend(xmin,0.78,xmin+0.2,0.88);
			leg->AddEntry(h_res,"Standalone");
			leg->AddEntry(gfit,"Fit");
			leg->SetFillColor(0);
			leg->SetBorderSize(0);
			leg->SetTextSize(0.05);
			leg->SetTextFont(42);
			leg->Draw("same");
			
			can->Update();
			/*
			//left line
			Double_t bndL = gfit->GetParameter(1) - gfit->GetParameter(2)*gfit->GetParameter(3);
			aLline = new TLine(bndL,pad->GetUymin(),bndL,pad->GetUymax());
			aLline->SetLineStyle(2);
			aLline->SetLineWidth(3);
			aLline->SetLineColor(kBlue);
			aLline->Draw("same");
			
			//left gaussian
			gsnL = new TF1("gsn","gaus",Emin,bndL);
			gsnL->SetParameters(gfit->GetParameter(0),gfit->GetParameter(1),gfit->GetParameter(2));
			gsnL->SetLineColor(kRed);
			gsnL->SetMarkerColor(kRed);
			gsnL->SetLineWidth(2);
			gsnL->SetLineStyle(2);
			gsnL->Draw("same");

			//line
			Double_t bndR = gfit->GetParameter(1) + gfit->GetParameter(2)*gfit->GetParameter(5);
			aRline = new TLine(bndR,pad->GetUymin(),bndR,pad->GetUymax());
			aRline->SetLineStyle(2);
			aRline->SetLineWidth(3);
			aRline->SetLineColor(kBlue);
			aRline->Draw("same");
			
			//right gaussian
			gsnR = new TF1("gsn","gaus",bndR,Emax);
			gsnR->SetParameters(gfit->GetParameter(0),gfit->GetParameter(1),gfit->GetParameter(2));
			gsnR->SetLineColor(kRed);
			gsnR->SetMarkerColor(kRed);
			gsnR->SetLineWidth(2);
			gsnR->SetLineStyle(2);
			gsnR->Draw("same");			
			*/
		}
		
		//pave
		pave = new TPaveText(xmin,0.68,xmin+0.2,0.78,"NDC");
		pave->AddText(sp->name.c_str());
		pave->AddText((piname.str()).c_str());
		pave->SetFillColor(0);
		pave->SetBorderSize(0);
		pave->SetTextFont(42);
		pave->SetTextSize(0.05);
		pave->Draw("same");

		//par pave
		Double_t ymin1;
		//if(do_fit) ymin1 = 0.26;
		//else ymin1 = 0.51;
		ymin1 = 0.47;
		pave_par = new TPaveText(xmin,ymin1,xmin+0.2,ymin1+0.05*4,"NDC");
		pave_par->AddText((Nname.str()).c_str());
		pave_par->AddText((muname.str()).c_str());
		pave_par->AddText((signame.str()).c_str());
		pave_par->AddText((musigname.str()).c_str());
		//if(do_fit){
		//	pave_par->AddText((aLname.str()).c_str());
		//	pave_par->AddText((nLname.str()).c_str());
		//	pave_par->AddText((aRname.str()).c_str());
		//	pave_par->AddText((nRname.str()).c_str());
		//	pave_par->AddText((chiname.str()).c_str());
		//}
		pave_par->SetFillColor(0);
		pave_par->SetBorderSize(0);
		pave_par->SetTextFont(42);
		pave_par->SetTextSize(0.05);
		pave_par->Draw("same");
		
		std::cout << "response:" << std::endl;
		
		std::cout << Nname.str() << std::endl;
		std::cout << muname.str() << std::endl;
		std::cout << signame.str() << std::endl;
		std::cout << musigname.str() << std::endl;
		if(do_fit){
		//	std::cout << "aL = " << gfit->GetParameter(3) << " +/- " << gfit->GetParError(3) << std::endl;
		//	std::cout << "nL = " << gfit->GetParameter(4) << " +/- " << gfit->GetParError(4) << std::endl;
		//	std::cout << "aR = " << gfit->GetParameter(5) << " +/- " << gfit->GetParError(5) << std::endl;
		//	std::cout << "nR = " << gfit->GetParameter(6) << " +/- " << gfit->GetParError(6) << std::endl;
			std::cout << "chi^2/ndf = " << gfit->GetChisquare()/gfit->GetNDF() << std::endl;
		}
		
		if(do_print) can->Print((oname.str()+"."+pformat).c_str(),pformat.c_str());
		if(do_batch) _file->Close();
	}
	else { _file->Close(); }
	
	//return data structure with relevant info
	return theRes;
}
//--------------------------------------
//function to calculate sampling factors
std::pair<Double_t,Double_t> g4_sample(int snum, Double_t energy, bool do_pion, bool do_show, bool do_print=false, bool set_val=true){
	Sample* sp = sample_map[snum];
	if(!sp) { std::cout << "Sample " << snum << " is not loaded." << std::endl; return std::pair<Double_t,Double_t>(0.,0.); }

	//select correct file
	std::string fpre = sp->fpre;
	if(do_pion) fpre += "_pion";
	else fpre += "_elec";

	//make filenames
	std::stringstream drawname, fname, piname;
	fname << sp->dir << "/" << fpre << "_" << energy << "gev_10k.root";
	if(do_pion) piname << "#pi^{-} " << energy << " GeV";
	else piname << "e^{-} " << energy << " GeV";

	//open file and tree
	TFile* _file;
	_file = TFile::Open((fname.str()).c_str());
	TTree* totalTree = (TTree*)_file->Get("Total");

	//get histo from tree (no display)
	//define mip as sam_ecal*ecal < 1 gev = 1000 mev (for pions in HCAL)
	if(sp->det==Hcal) drawname << "(hcal+" << sp->zeroWt << "*zero)/1000>>hsam(200)";
	else drawname << "(ecal)/1000>>hsam(200)";
	
	totalTree->Draw((drawname.str()).c_str(),"","hist goff");
	TH1F* hsam = (TH1F*)gDirectory->Get("hsam");
	
	//use parameters from histo to start fit
	TSpectrum* spec = new TSpectrum(5);
	spec->Search(hsam,5,"nodraw goff");
	Float_t* xpos = spec->GetPositionX();
	Float_t* ypos = spec->GetPositionY();

	Double_t m = xpos[0];
	Double_t me = hsam->GetMeanError();
	Double_t N = hsam->GetEntries();
	std::stringstream s_mean;
	s_mean.precision(3);
	Double_t f = energy/m;
	Double_t f_err = energy*(me/(m*m));
	s_mean << f << " #pm " << f_err;

	TPolyMarker* pm = new TPolyMarker(1, xpos, ypos);
	hsam->GetListOfFunctions()->Add(pm);
	pm->SetMarkerStyle(23);
	pm->SetMarkerColor(kRed);
	pm->SetMarkerSize(1.3);

	std::cout.precision(6);
	std::cout << "f_" << (do_pion ? "pion" : "elec") << " = " << f << " +/- " << f_err << std::endl;
	
	//plotting and printing
	if (do_show){
		TCanvas* can = new TCanvas("sample","sample",700,500);
		can->cd();
		TPad* pad = new TPad("graph","",0,0,1,1);
		pad->SetMargin(0.12,0.05,0.15,0.05);
		pad->Draw();
		pad->cd();
		
		//formatting
		hsam->SetTitle("");
		hsam->GetXaxis()->SetTitle("Energy [GeV]");
		//hsam->SetStats(kTRUE);
		//gStyle->SetOptStat("mr");
		hsam->SetLineWidth(2);
		hsam->SetLineColor(kBlack);
		hsam->GetYaxis()->SetTitleSize(32/(pad->GetWh()*pad->GetAbsHNDC()));
		hsam->GetYaxis()->SetLabelSize(28/(pad->GetWh()*pad->GetAbsHNDC()));
		hsam->GetXaxis()->SetTitleSize(32/(pad->GetWh()*pad->GetAbsHNDC()));
		hsam->GetXaxis()->SetLabelSize(28/(pad->GetWh()*pad->GetAbsHNDC()));
		hsam->GetYaxis()->SetTickLength(12/(pad->GetWh()*pad->GetAbsHNDC()));
		hsam->GetXaxis()->SetTickLength(12/(pad->GetWh()*pad->GetAbsHNDC()));
		
		hsam->Draw();
		
		std::stringstream Nname;
		Nname << "N = " << N;
		
		//determine placing of pave
		Double_t xmin;
		if (m/((hsam->GetXaxis()->GetXmax() + hsam->GetXaxis()->GetXmin())/2) < 1) xmin = 0.65;
		else xmin = 0.2;
		
		//legend
		TPaveText *pave = new TPaveText(xmin,0.65,xmin+0.2,0.85,"NDC");
		pave->AddText((piname.str()).c_str());
		pave->AddText((Nname.str()).c_str());
		pave->AddText("Peak sampling factor:");
		pave->AddText((s_mean.str()).c_str());
		pave->SetFillColor(0);
		pave->SetBorderSize(0);
		pave->SetTextFont(42);
		pave->SetTextSize(0.05);
		pave->Draw("same");

		if(do_print) {
			std::stringstream oname;
			oname << pdir << "/" << fpre << "_sample_" << energy << "gev_peak.png";
			can->Print((oname.str()).c_str(),"png");
		}
	}
	else _file->Close();

	//store value in sample
	if(set_val){
		if(do_pion) sp->sam_pion = f;
		else sp->sam_elec = f;
	}

	return std::pair<Double_t,Double_t>(f,f_err);
}
Exemple #14
0
void makeHTPlots(){

  gStyle->SetOptFit(0);

  TChain *ch = new TChain("t");
  //ch->Add("../output/V00-02-09/highpt/LM6v2_smallTree.root");
  //ch->Add("../output/V00-02-10/highpt/LM6v2_smallTree.root");
  //ch->Add("../output/V00-02-15/highpt/LM6v2_smallTree.root");
  //ch->Add("../output/V00-02-16/highpt/LM6v2_smallTree_gen_TEMP.root");
  ch->Add("../output/V00-02-18/highpt/LM6v2_smallTree_gen.root");

  vector<TCut> metcuts;
  vector<float> metcutvals;

  metcuts.push_back(TCut("ht>125")); metcutvals.push_back(125);
  metcuts.push_back(TCut("ht>300")); metcutvals.push_back(300);
  metcuts.push_back(TCut("ht>600")); metcutvals.push_back(600);

  //TCut sel("njets>=2 && pfmet>50 && !passz");
  TCut sel("foundPair==1 && reco1==1 && reco2==1 && genmet>50 && pfmet>50");

  const unsigned int n = metcuts.size();

  TH1F* hpass[n];
  TH1F* hall[n];

  for( unsigned int i = 0 ; i < metcuts.size() ; ++i){

    hpass[i]   = new TH1F(Form("hpass_%i",i),Form("hpass_%i",i),25,0,1000);
    hall[i]    = new TH1F(Form("hall_%i",i), Form("hall_%i",i) ,25,0,1000);

    //ch->Draw(Form("htgen>>hpass_%i",i),sel+metcuts.at(i));
    //ch->Draw(Form("htgen>>hall_%i",i)  ,sel);
    ch->Draw(Form("htgen2>>hpass_%i",i),sel+metcuts.at(i));
    ch->Draw(Form("htgen2>>hall_%i",i)  ,sel);

  }




  TCanvas *can = new TCanvas();
  can->cd();

  gPad->SetRightMargin(0.1);
  gPad->SetTopMargin(0.1);
  gPad->SetGridx();
  gPad->SetGridy();
  
  gStyle->SetOptFit(0);


  TGraphAsymmErrors* gr[n];  
  TLegend *leg = new TLegend(0.63,0.2,0.88,0.4);
  leg->SetFillColor(0);
  leg->SetBorderSize(1);
  leg->SetTextSize(0.03);

  TF1* erf[n];

  TLine line;
  line.SetLineWidth(2);
  line.SetLineStyle(2);

  float norm[n];
  float offset[n];
  float width[n];

  for( unsigned int i = 0 ; i < metcuts.size() ; ++i){

    //can[i] = new TCanvas(Form("can_%i",i),Form("can_%i",i),500,500);
    //can[i]->cd();
    
    // TF1* efunc = new TF1("efitf", fitf, 0, 500, 3);
    // efunc->SetParameters(1, 100, 10);
    // efunc->SetParNames("norm", "offset", "width");

    erf[i] = new TF1("efitf", fitf, 0, 1000, 3);
    erf[i]->SetParameters(1, metcutvals.at(i), 30);
    erf[i]->SetParNames("norm", "offset", "width");
    erf[i]->SetLineWidth(2);
    //erf[i]->FixParameter(0,1);

    //erf[i] = new TF1(Form("erf_%i",i),mfitf,0,400);

    //erf[i]->SetParameter(0,100*(i+1));
    //erf[i]->SetParameter(1,10);

    gr[i] = new TGraphAsymmErrors();
    if( i==0 ){
      erf[i]->SetLineColor(1);
      line.SetLineColor(1);
    }

    if( i==1 ){
      line.SetLineColor(2);
      gr[i]->SetLineColor(2);
      gr[i]->SetMarkerColor(2);
      gr[i]->SetMarkerStyle(21);
      erf[i]->SetLineColor(2);
    }
    if( i==2 ){
      line.SetLineColor(4);
      gr[i]->SetLineColor(4);
      gr[i]->SetMarkerColor(4);
      gr[i]->SetMarkerStyle(25);
      erf[i]->SetLineColor(4);
    }

    leg->AddEntry(gr[i],Form("H_{T} > %.0f GeV",metcutvals.at(i)),"p");

    gr[i]->GetXaxis()->SetRangeUser(0,1000);
    gr[i]->GetXaxis()->SetTitle("generator-level H_{T} (GeV)");
    gr[i]->GetYaxis()->SetTitle("efficiency");
    gr[i]->SetMaximum(1);
    gr[i]->SetMinimum(0);
    gr[i]->BayesDivide(hpass[i],hall[i]);

    //gr[i]->Fit(efunc,"R");
    gr[i]->Fit(erf[i],"R");

    norm[i]   = erf[i]->GetParameter(0);
    offset[i] = erf[i]->GetParameter(1);
    width[i]  = erf[i]->GetParameter(2);

    if( i==0 ) gr[i]->Draw("AP");
    else       gr[i]->Draw("sameP");

    gr[i]->GetXaxis()->SetRangeUser(0,1000);
    gr[i]->GetXaxis()->SetTitle("generator-level H_{T} (GeV)");
    gr[i]->GetYaxis()->SetTitle("efficiency");

    line.DrawLine(metcutvals.at(i),0,metcutvals.at(i),1);
    //erf[i]->Draw("same");
  }

  leg->Draw();

  TLatex *t = new TLatex();
  t->SetNDC();
  t->SetTextSize(0.05);
  t->DrawLatex(0.25,0.92,"CMS Simulation, #sqrt{s} = 7 TeV");

  can->Print("../plots/ht_turnon_LM6.pdf");

  cout << endl << endl;
  for( int i = 0 ; i < 3 ; ++i ){
    cout << "norm width offset " << Form("%.2f  %.0f  %.0f",norm[i],width[i],offset[i]) << endl;
  }
}
void makePlot(double canvasSizeX, double canvasSizeY,
	      TH1* histogramTTH, 
	      TH1* histogramData, 
	      TH1* histogramTT,
	      TH1* histogramTTV,
	      TH1* histogramEWK,
	      TH1* histogramRares,
	      TH1* histogramBgrSum,
	      TH1* histogramBgrUncertainty,		
	      const std::string& xAxisTitle, double xAxisOffset,
	      bool useLogScale, double yMin, double yMax, const std::string& yAxisTitle, double yAxisOffset,
	      const std::string& outputFileName)
{
  TH1* histogramTTH_density = 0;
  if ( histogramTTH ) {
    if ( histogramData ) checkCompatibleBinning(histogramTTH, histogramData);
    histogramTTH_density = divideHistogramByBinWidth(histogramTTH);
  }
  TH1* histogramData_density = 0;
  if ( histogramData ) {
    histogramData_density = divideHistogramByBinWidth(histogramData);      
  }
  TH1* histogramTT_density = 0;
  if ( histogramTT ) {
    if ( histogramData ) checkCompatibleBinning(histogramTT, histogramData);
    histogramTT_density = divideHistogramByBinWidth(histogramTT);
  } 
  TH1* histogramTTV_density = 0;
  if ( histogramTTV ) {
    if ( histogramData ) checkCompatibleBinning(histogramTTV, histogramData);
    histogramTTV_density = divideHistogramByBinWidth(histogramTTV);
  }    
  TH1* histogramEWK_density = 0;
  if ( histogramEWK ) {
    if ( histogramData ) checkCompatibleBinning(histogramEWK, histogramData);
    histogramEWK_density = divideHistogramByBinWidth(histogramEWK);
  }
  TH1* histogramRares_density = 0;
  if ( histogramRares ) {
    if ( histogramData ) checkCompatibleBinning(histogramRares, histogramData);
    histogramRares_density = divideHistogramByBinWidth(histogramRares);
  }    
  TH1* histogramBgrSum_density = 0;
  if ( histogramBgrSum ) {
    if ( histogramData ) checkCompatibleBinning(histogramBgrSum, histogramData);
    histogramBgrSum_density = divideHistogramByBinWidth(histogramBgrSum); 
  }
  TH1* histogramBgrUncertainty_density = 0;
  if ( histogramBgrUncertainty ) {
    if ( histogramData ) checkCompatibleBinning(histogramBgrUncertainty, histogramData);
    histogramBgrUncertainty_density = divideHistogramByBinWidth(histogramBgrUncertainty);
  }
  
  TCanvas* canvas = new TCanvas("canvas", "", canvasSizeX, canvasSizeY);
  canvas->SetFillColor(10);
  canvas->SetFillStyle(4000);
  canvas->SetFillColor(10);
  canvas->SetTicky();
  canvas->SetBorderSize(2);  
  canvas->SetLeftMargin(0.12);
  canvas->SetBottomMargin(0.12);
  
  TPad* topPad = new TPad("topPad", "topPad", 0.00, 0.35, 1.00, 1.00);
  topPad->SetFillColor(10);
  topPad->SetTopMargin(0.065);
  topPad->SetLeftMargin(0.15);
  topPad->SetBottomMargin(0.03);
  topPad->SetRightMargin(0.05);
  topPad->SetLogy(useLogScale);
  
  TPad* bottomPad = new TPad("bottomPad", "bottomPad", 0.00, 0.00, 1.00, 0.35);
  bottomPad->SetFillColor(10);
  bottomPad->SetTopMargin(0.02);
  bottomPad->SetLeftMargin(0.15);
  bottomPad->SetBottomMargin(0.31);
  bottomPad->SetRightMargin(0.05);
  bottomPad->SetLogy(false);
  
  canvas->cd();
  topPad->Draw();
  topPad->cd();
  
  TAxis* xAxis_top = histogramData_density->GetXaxis();
  xAxis_top->SetTitle(xAxisTitle.data());
  xAxis_top->SetTitleOffset(xAxisOffset);
  xAxis_top->SetLabelColor(10);
  xAxis_top->SetTitleColor(10);
    
  TAxis* yAxis_top = histogramData_density->GetYaxis();
  yAxis_top->SetTitle(yAxisTitle.data());
  yAxis_top->SetTitleOffset(yAxisOffset);
  yAxis_top->SetTitleSize(0.085);
  yAxis_top->SetLabelSize(0.05);
  yAxis_top->SetTickLength(0.04);  
  
  TLegend* legend = new TLegend(0.66, 0.45, 0.94, 0.92, NULL, "brNDC");
  legend->SetFillStyle(0);
  legend->SetBorderSize(0);
  legend->SetFillColor(10);
  legend->SetTextSize(0.055);
  
  histogramData_density->SetTitle("");
  histogramData_density->SetStats(false);
  histogramData_density->SetMaximum(yMax);
  histogramData_density->SetMinimum(yMin);
  histogramData_density->SetMarkerStyle(20);
  histogramData_density->SetMarkerSize(2);
  histogramData_density->SetMarkerColor(kBlack);
  histogramData_density->SetLineColor(kBlack);
  legend->AddEntry(histogramData_density, "Observed", "p");    
  
  histogramData_density->Draw("ep");
  
  legend->AddEntry(histogramTTH_density, "t#bar{t}H", "l");

  histogramTT_density->SetTitle("");
  histogramTT_density->SetStats(false);
  histogramTT_density->SetMaximum(yMax);
  histogramTT_density->SetMinimum(yMin);
  histogramTT_density->SetFillColor(kMagenta - 10); 
  legend->AddEntry(histogramTT_density, "t#bar{t}+jets", "f");

  histogramTTV_density->SetFillColor(kOrange - 4);
  legend->AddEntry(histogramTTV_density, "t#bar{t}+V", "f");

  histogramEWK_density->SetFillColor(kRed + 2); 
  legend->AddEntry(histogramEWK_density, "EWK", "f");

  histogramRares_density->SetFillColor(kBlue - 8); 
  legend->AddEntry(histogramRares_density, "Rares", "f");

  THStack* histogramStack_density = new THStack("stack", "");
  histogramStack_density->Add(histogramRares_density);
  histogramStack_density->Add(histogramEWK_density);
  histogramStack_density->Add(histogramTTV_density);
  histogramStack_density->Add(histogramTT_density);
  histogramStack_density->Draw("histsame");
  
  histogramBgrUncertainty_density->SetFillColor(kBlack);
  histogramBgrUncertainty_density->SetFillStyle(3344);    
  histogramBgrUncertainty_density->Draw("e2same");
  legend->AddEntry(histogramBgrUncertainty_density, "Uncertainty", "f");

  histogramTTH_density->SetLineWidth(2);
  histogramTTH_density->SetLineStyle(1);
  histogramTTH_density->SetLineColor(kBlue);
  histogramTTH_density->Draw("histsame");
  
  histogramData_density->Draw("epsame");
  histogramData_density->Draw("axissame");
  
  legend->Draw();
  
  addLabel_CMS_luminosity(0.2050, 0.9225, 0.6850);
  
  canvas->cd();
  bottomPad->Draw();
  bottomPad->cd();
  
  TH1* histogramRatio = (TH1*)histogramData->Clone("histogramRatio");
  histogramRatio->Reset();
  if ( !histogramRatio->GetSumw2N() ) histogramRatio->Sumw2();
  checkCompatibleBinning(histogramRatio, histogramBgrSum);
  histogramRatio->Divide(histogramData, histogramBgrSum);
  int numBins_bottom = histogramRatio->GetNbinsX();
  for ( int iBin = 1; iBin <= numBins_bottom; ++iBin ) {
    double binContent = histogramRatio->GetBinContent(iBin);
    if ( histogramData && histogramData->GetBinContent(iBin) >= 0. ) histogramRatio->SetBinContent(iBin, binContent - 1.0);
    else histogramRatio->SetBinContent(iBin, -10.);
  }
  histogramRatio->SetTitle("");
  histogramRatio->SetStats(false);
  histogramRatio->SetMinimum(-0.50);
  histogramRatio->SetMaximum(+0.50);
  histogramRatio->SetMarkerStyle(histogramData_density->GetMarkerStyle());
  histogramRatio->SetMarkerSize(histogramData_density->GetMarkerSize());
  histogramRatio->SetMarkerColor(histogramData_density->GetMarkerColor());
  histogramRatio->SetLineColor(histogramData_density->GetLineColor());
  histogramRatio->Draw("ep");
  
  TAxis* xAxis_bottom = histogramRatio->GetXaxis();
  xAxis_bottom->SetTitle(xAxis_top->GetTitle());
  xAxis_bottom->SetLabelColor(1);
  xAxis_bottom->SetTitleColor(1);
  xAxis_bottom->SetTitleOffset(1.20);
  xAxis_bottom->SetTitleSize(0.13);
  xAxis_bottom->SetLabelOffset(0.02);
  xAxis_bottom->SetLabelSize(0.10);
  xAxis_bottom->SetTickLength(0.055);
  
  TAxis* yAxis_bottom = histogramRatio->GetYaxis();
  yAxis_bottom->SetTitle("#frac{Data - Simulation}{Simulation}");
  yAxis_bottom->SetTitleOffset(0.80);
  yAxis_bottom->SetNdivisions(505);
  yAxis_bottom->CenterTitle();
  yAxis_bottom->SetTitleSize(0.09);
  yAxis_bottom->SetLabelSize(0.10);
  yAxis_bottom->SetTickLength(0.04);  
  
  TH1* histogramRatioUncertainty = (TH1*)histogramBgrUncertainty->Clone("histogramRatioUncertainty");
  if ( !histogramRatioUncertainty->GetSumw2N() ) histogramRatioUncertainty->Sumw2();
  checkCompatibleBinning(histogramRatioUncertainty, histogramBgrUncertainty);
  histogramRatioUncertainty->Divide(histogramBgrSum);
  int numBins = histogramRatioUncertainty->GetNbinsX();
  for ( int iBin = 1; iBin <= numBins; ++iBin ) {
    double binContent = histogramRatioUncertainty->GetBinContent(iBin);
    histogramRatioUncertainty->SetBinContent(iBin, binContent - 1.0);
  }
  histogramRatioUncertainty->SetFillColor(histogramBgrUncertainty_density->GetFillColor());
  //histogramRatioUncertainty->SetFillStyle(histogramBgrUncertainty_density->GetFillStyle());    
  histogramRatioUncertainty->SetFillStyle(3644);    
  
  TF1* line = new TF1("line","0", xAxis_bottom->GetXmin(), xAxis_bottom->GetXmax());
  line->SetLineStyle(3);
  line->SetLineWidth(1);
  line->SetLineColor(kBlack);
  line->Draw("same");
  
  histogramRatioUncertainty->Draw("e2same");
  
  histogramRatio->Draw("epsame");
  
  canvas->Update();
  size_t idx = outputFileName.find(".");
  std::string outputFileName_plot(outputFileName, 0, idx);
  if ( useLogScale ) outputFileName_plot.append("_log");
  else outputFileName_plot.append("_linear");
  if ( idx != std::string::npos ) canvas->Print(std::string(outputFileName_plot).append(std::string(outputFileName, idx)).data());
  canvas->Print(std::string(outputFileName_plot).append(".png").data());
  canvas->Print(std::string(outputFileName_plot).append(".pdf").data());
  canvas->Print(std::string(outputFileName_plot).append(".root").data());
  
  delete histogramTTH_density;
  delete histogramData_density;
  delete histogramTT_density;
  delete histogramTTV_density;
  delete histogramEWK_density;
  delete histogramRares_density;
  delete histogramBgrSum_density;
  //delete histogramBgrUncertainty_density;
  delete histogramStack_density;
  delete legend;
  delete topPad;
  delete histogramRatio;
  delete histogramRatioUncertainty;
  delete line;
  delete bottomPad;    
  delete canvas;
}
Exemple #16
0
Int_t DrawTrendingTOFQA(TString mergedTrendFile = "trending.root", // trending tree file 
			Bool_t displayAll = kFALSE) //set to kTRUE to display trending for expert plots
{
  //
  //reads merged trending.root file and draws trending plots from tree
  //
  if (!mergedTrendFile) {
    Printf("Cannot open merged trend file with TOF QA");
    return 1;
  }
  
  char  outfilename[200]= "ProductionQA.hist.root";
  TString plotDir(".");
  // TString plotDir(Form("PlotsTrending"));
  // gSystem->Exec(Form("mkdir %s",plotDir.Data()));

  Int_t runNumber=0;
  Double_t avTime=0., peakTime=0., spreadTime=0., peakTimeErr=0., spreadTimeErr=0.,negTimeRatio=0.,
    avRawTime=0., peakRawTime=0., spreadRawTime=0., peakRawTimeErr=0., spreadRawTimeErr=0., 
    avTot=0., peakTot=0.,spreadTot=0.,  peakTotErr=0.,spreadTotErr=0.,
    meanResTOF=0., spreadResTOF=0., meanResTOFerr=0., spreadResTOFerr=0.,
    orphansRatio=0., avL=0., negLratio=0.,
    matchEffIntegratedErr=-9999., matchEffIntegrated=-9999., matchEffLinFit1Gev=0.,matchEffLinFit1GevErr=0.;
  Double_t avDiffTime=0.,peakDiffTime=0., spreadDiffTime=0.,peakDiffTimeErr=0., spreadDiffTimeErr=0.,avT0fillRes=0.;
   
  Double_t avT0A=0.,peakT0A=0., spreadT0A=0.,peakT0AErr=0., spreadT0AErr=0.;
  Double_t avT0C=0.,peakT0C=0., spreadT0C=0.,peakT0CErr=0., spreadT0CErr=0.;
  Double_t avT0AC=0.,peakT0AC=0., spreadT0AC=0.,peakT0ACErr=0., spreadT0ACErr=0.;
  Double_t avT0res=0.,peakT0res=0., spreadT0res=0.,peakT0resErr=0., spreadT0resErr=0.;

  Double_t StartTime_pBestT0 = 0.0, StartTime_pBestT0Err = 0.0, StartTime_pFillT0 = 0.0, StartTime_pFillT0Err = 0.0, StartTime_pTOFT0 = 0.0, StartTime_pTOFT0Err = 0.0, StartTime_pT0ACT0 = 0.0, StartTime_pT0ACT0Err = 0.0, StartTime_pT0AT0 = 0.0, StartTime_pT0AT0Err = 0.0, StartTime_pT0CT0 = 0.0, StartTime_pT0CT0Err = 0.0;
  Double_t StartTime_pBestT0_Res = 0.0, StartTime_pFillT0_Res = 0.0, StartTime_pTOFT0_Res = 0.0, StartTime_pT0ACT0_Res = 0.0, StartTime_pT0AT0_Res = 0.0, StartTime_pT0CT0_Res = 0.0;

  Float_t avMulti=0;
  Float_t fractionEventsWHits=0.0;
  Double_t goodChannelRatio=0.0;
  Double_t goodChannelRatioInAcc=0.0;

  
  TFile * fin = TFile::Open(mergedTrendFile.Data());
  TTree * ttree = (TTree*) fin->Get("trending");
  if (!ttree){
    fin->ls();
    Printf("Invalid trending tree.");
    return 2;
  }
  ttree->SetBranchAddress("run",&runNumber);
  ttree->SetBranchAddress("avMulti",&avMulti);
  ttree->SetBranchAddress("goodChannelsRatio",&goodChannelRatio);   
  ttree->SetBranchAddress("goodChannelsRatioInAcc",&goodChannelRatioInAcc);   
  ttree->SetBranchAddress("avTime",&avTime); //mean time
  ttree->SetBranchAddress("peakTime",&peakTime); //main peak time after fit
  ttree->SetBranchAddress("spreadTime",&spreadTime); //spread of main peak of time after fit
  ttree->SetBranchAddress("peakTimeErr",&peakTimeErr); //main peak time after fit error
  ttree->SetBranchAddress("spreadTimeErr",&spreadTimeErr); //spread of main peak of time after fit error
  ttree->SetBranchAddress("negTimeRatio",&negTimeRatio); //negative time ratio
  ttree->SetBranchAddress("avRawTime",&avRawTime); //mean raw time
  ttree->SetBranchAddress("peakRawTime",&peakRawTime); //mean peak of raw time after fit
  ttree->SetBranchAddress("spreadRawTime",&spreadRawTime); //spread of main peak of raw time after fit
  ttree->SetBranchAddress("peakRawTimeErr",&peakRawTimeErr); //main peak raw  time after fit error
  ttree->SetBranchAddress("spreadRawTimeErr",&spreadRawTimeErr); //spread of  raw main peak of time after fit error
  ttree->SetBranchAddress("avTot",&avTot); //main peak tot
  ttree->SetBranchAddress("peakTot",&peakTot); // main peak of tot after fit
  ttree->SetBranchAddress("spreadTot",&spreadTot); //spread of main peak of tot after fit
  ttree->SetBranchAddress("peakTotErr",&peakTotErr); // main peak of tot after fit
  ttree->SetBranchAddress("spreadTotErr",&spreadTotErr); //spread of main peak of tot after fit
  ttree->SetBranchAddress("orphansRatio",&orphansRatio); //orphans ratio
  ttree->SetBranchAddress("avL",&avL); //mean track length
  ttree->SetBranchAddress("negLratio",&negLratio);//ratio of tracks with track length <350 cm
  if(0 != ttree->SetBranchAddress("matchEffIntegrated",&matchEffIntegrated)) //matching eff integrated in pt (1-10GeV/c)
    matchEffIntegrated = 0;
  if(0 != ttree->SetBranchAddress("matchEffIntegratedErr",&matchEffIntegratedErr)) //matching eff integrated in pt (1-10GeV/c)
    matchEffIntegratedErr = 0;
  ttree->SetBranchAddress("matchEffLinFit1Gev",&matchEffLinFit1Gev);//matching eff fit param 
  ttree->SetBranchAddress("matchEffLinFit1GevErr",&matchEffLinFit1GevErr);////matching eff fit param error
  ttree->SetBranchAddress("avPiDiffTime",&avDiffTime); //mean t-texp
  ttree->SetBranchAddress("peakPiDiffTime",&peakDiffTime); //main peak t-texp after fit
  ttree->SetBranchAddress("spreadPiDiffTime",&spreadDiffTime); //spread of main peak t-texp after fit
  ttree->SetBranchAddress("peakPiDiffTimeErr",&peakDiffTimeErr); //main peak t-texp after fit error
  ttree->SetBranchAddress("spreadPiDiffTimeErr",&spreadDiffTimeErr); //spread of main peak of t-texp after fit error
  ttree->SetBranchAddress("meanResTOF",&meanResTOF); //mean of t-texp_pi-t0_TOF
  ttree->SetBranchAddress("spreadResTOF",&spreadResTOF); //spread of t-texp_pi-t0_TOF, ie. resolution
  ttree->SetBranchAddress("meanResTOFerr",&meanResTOFerr); //error on mean of t-texp_pi-t0_TOF
  ttree->SetBranchAddress("spreadResTOFerr",&spreadResTOFerr); //error on the spread of t-texp_pi-t0_TOF
  ttree->SetBranchAddress("avT0A",&avT0A); //main peak t0A
  ttree->SetBranchAddress("peakT0A",&peakT0A); // main peak of t0A after fit
  ttree->SetBranchAddress("spreadT0A",&spreadT0A); //spread of main peak of t0A after fit
  ttree->SetBranchAddress("peakT0AErr",&peakT0AErr); // main peak of t0A after fit
  ttree->SetBranchAddress("spreadT0AErr",&spreadT0AErr); //spread of main peak of t0A after fit
  ttree->SetBranchAddress("avT0C",&avT0C); //main peak t0C
  ttree->SetBranchAddress("peakT0C",&peakT0C); // main peak of t0C after fit
  ttree->SetBranchAddress("spreadT0C",&spreadT0C); //spread of main peak of t0C after fit
  ttree->SetBranchAddress("peakT0CErr",&peakT0CErr); // main peak of t0C after fit
  ttree->SetBranchAddress("spreadT0CErr",&spreadT0CErr); //spread of main peak of t0C after fit
  ttree->SetBranchAddress("avT0AC",&avT0AC); //main peak t0AC
  ttree->SetBranchAddress("peakT0AC",&peakT0AC); // main peak of t0AC after fit
  ttree->SetBranchAddress("spreadT0AC",&spreadT0AC); //spread of main peak of t0AC after fit
  ttree->SetBranchAddress("peakT0ACErr",&peakT0ACErr); // main peak of t0AC after fit
  ttree->SetBranchAddress("spreadT0ACErr",&spreadT0ACErr); //spread of main peak of t0AC after fit
  ttree->SetBranchAddress("avT0res",&avT0res); //main peak t0AC
  ttree->SetBranchAddress("peakT0res",&peakT0res); // main peak of t0AC after fit
  ttree->SetBranchAddress("spreadT0res",&spreadT0res); //spread of main peak of t0AC after fit
  ttree->SetBranchAddress("peakT0resErr",&peakT0resErr); // main peak of t0AC after fit
  ttree->SetBranchAddress("spreadT0resErr",&spreadT0resErr); //spread of main peak of t0AC after fit
  ttree->SetBranchAddress("avT0fillRes",&avT0fillRes); //t0 fill res

  ttree->SetBranchAddress("StartTime_pBestT0",&StartTime_pBestT0); //T0Best                                  
  ttree->SetBranchAddress("StartTime_pFillT0",&StartTime_pFillT0); //T0Fill
  ttree->SetBranchAddress("StartTime_pTOFT0",&StartTime_pTOFT0); //T0TOF
  ttree->SetBranchAddress("StartTime_pT0ACT0",&StartTime_pT0ACT0); //T0AC
  ttree->SetBranchAddress("StartTime_pT0AT0",&StartTime_pT0AT0); //T0A
  ttree->SetBranchAddress("StartTime_pT0CT0",&StartTime_pT0CT0); //T0C
  ttree->SetBranchAddress("StartTime_pBestT0_Res",&StartTime_pBestT0_Res); //T0Best                      
  ttree->SetBranchAddress("StartTime_pFillT0_Res",&StartTime_pFillT0_Res); //T0Fill res
  ttree->SetBranchAddress("StartTime_pTOFT0_Res",&StartTime_pTOFT0_Res); //T0TOF res
  ttree->SetBranchAddress("StartTime_pT0ACT0_Res",&StartTime_pT0ACT0_Res); //T0AC res
  ttree->SetBranchAddress("StartTime_pT0AT0_Res",&StartTime_pT0AT0_Res); //T0A res
  ttree->SetBranchAddress("StartTime_pT0CT0_Res",&StartTime_pT0CT0_Res); //T0C res

  ttree->SetBranchAddress("StartTime_pBestT0Err",&StartTime_pBestT0Err); //T0Best                                  
  ttree->SetBranchAddress("StartTime_pFillT0Err",&StartTime_pFillT0Err); //T0Fill
  ttree->SetBranchAddress("StartTime_pTOFT0Err",&StartTime_pTOFT0Err); //T0TOF
  ttree->SetBranchAddress("StartTime_pT0ACT0Err",&StartTime_pT0ACT0Err); //T0AC
  ttree->SetBranchAddress("StartTime_pT0AT0Err",&StartTime_pT0AT0Err); //T0A
  ttree->SetBranchAddress("StartTime_pT0CT0Err",&StartTime_pT0CT0Err); //T0C

  //Fetch period-integrated PID plots
  //Pions
  TH2F * hDiffTimePi=(TH2F*)fin->Get("hExpTimePiVsP_all");  
  hDiffTimePi->SetTitle("PIONS t-t_{exp,#pi} (from tracking) vs. P");
  //Kaon
  TH2F * hDiffTimeKa=(TH2F*)fin->Get("hExpTimeKaVsP_all");  
  hDiffTimeKa->SetTitle("KAONS t-t_{exp,K} (from tracking) vs. P");
  //Protons
  TH2F * hDiffTimePro=(TH2F*)fin->Get("hExpTimeProVsP_all"); 
  hDiffTimePro->SetTitle("PROTONS t-t_{exp,p} (from tracking) vs. P");

  //Create trending plots
  Int_t nRuns=ttree->GetEntries();
  TList lista;
   
  TH1F * hAvMulti=new TH1F("hAvMulti","Average multiplicity of matched tracks <N_{TOF}>;; <N_{TOF}>", nRuns,0., nRuns);//, 600, 0. , 600.);
  hAvMulti->SetDrawOption("E1");
  hAvMulti->SetMarkerStyle(20);
  hAvMulti->SetMarkerColor(kBlue);
	
  TH1F * hAvDiffTimeVsRun=new TH1F("hAvDiffTimeVsRun","Mean t-t_{exp} (no fit);run;<t^{TOF}-t_{exp,#pi}> (ps)",nRuns,0., nRuns);//, 600, 0. , 600.);
  hAvDiffTimeVsRun->SetDrawOption("E1");
  hAvDiffTimeVsRun->SetMarkerStyle(20);
  hAvDiffTimeVsRun->SetMarkerColor(kBlue);
  //   hAvTimeVsRun->GetYaxis()->SetRangeUser(0.0, 50.0);

  TH1F * hPeakDiffTimeVsRun=new TH1F("hPeakDiffTimeVsRun","t-t_{exp} (gaussian fit) ;; <t^{TOF}-t_{exp,#pi}> (ps)",nRuns,0., nRuns);//,600, 0. , 600. );
  hPeakDiffTimeVsRun->SetDrawOption("E1");
  hPeakDiffTimeVsRun->SetMarkerStyle(20);
  hPeakDiffTimeVsRun->SetMarkerColor(kBlue);
   
  TH1F * hSpreadDiffTimeVsRun=new TH1F("hSpreadDiffTimeVsRun","#sigma(t-t_{exp}) (gaussian fit);; #sigma(t^{TOF}-t_{exp,#pi}) (ns)",nRuns,0., nRuns);//, 100, 0. , 100.);
  hSpreadDiffTimeVsRun->SetDrawOption("E1");
  hSpreadDiffTimeVsRun->SetMarkerStyle(20);
  hSpreadDiffTimeVsRun->SetMarkerColor(kBlue);

  TH1F * hMeanTOFResVsRun=new TH1F("hMeanTOFResVsRun","Mean value of t-t_{exp,#pi}-t0_{TOF} (ps);;<t^{TOF}-t_{exp,#pi}-t_{0,TOF}> (ps)",nRuns,0., nRuns);
  hMeanTOFResVsRun->SetDrawOption("E1");
  hMeanTOFResVsRun->SetMarkerStyle(20);
  hMeanTOFResVsRun->SetMarkerColor(kBlue);

  TH1F * hSigmaTOFResVsRun=new TH1F("hSigmaTOFResVsRun","Spread of t-t_{exp,#pi}-t0_{TOF} (ps);;#sigma(t^{TOF}-t_{exp,#pi}-t_{0,TOF}) (ps)",nRuns,0., nRuns);
  hSigmaTOFResVsRun->SetDrawOption("E1");
  hSigmaTOFResVsRun->SetMarkerStyle(20);
  hSigmaTOFResVsRun->SetMarkerColor(kBlue);

  TH1F * hAvTimeVsRun=new TH1F("hAvTimeVsRun","<t^{TOF}>;;<t^{TOF}> (ns)",nRuns,0., nRuns);//, 600, 0. , 600.);
  hAvTimeVsRun->SetDrawOption("E1");
  hAvTimeVsRun->SetMarkerStyle(20);
  hAvTimeVsRun->SetMarkerColor(kBlue);
  //   hAvTimeVsRun->GetYaxis()->SetRangeUser(0.0, 50.0);

  TH1F * hPeakTimeVsRun=new TH1F("hPeakTimeVsRun","Peak value of t^{TOF} (landau fit);;t_{peak}^{TOF} (ns)",nRuns,0., nRuns);//,600, 0. , 600. );
  hPeakTimeVsRun->SetDrawOption("E1");
  hPeakTimeVsRun->SetMarkerStyle(20);
  hPeakTimeVsRun->SetMarkerColor(kBlue);
   
  TH1F * hSpreadTimeVsRun=new TH1F("hSpreadTimeVsRun","Spread of t^{TOF} (landau fit);; #sigma(t^{TOF}) (ns)",nRuns,0., nRuns);//, 100, 0. , 100.);
  hSpreadTimeVsRun->SetDrawOption("E1");
  hSpreadTimeVsRun->SetMarkerStyle(20);
  hSpreadTimeVsRun->SetMarkerColor(kBlue);
  
  TH1F * hAvRawTimeVsRun=new TH1F("hAvRawTimeVsRun","Peak value of raw t^{TOF};;<t_{raw}^{TOF}> (ns)",nRuns,0., nRuns);//, 600, 0. , 600.);
  hAvRawTimeVsRun->SetDrawOption("E1");
  hAvRawTimeVsRun->SetMarkerStyle(21);
  hAvRawTimeVsRun->SetMarkerColor(kGreen);

  TH1F * hPeakRawTimeVsRun=new TH1F("hPeakRawTimeVsRun","Peak value of raw t^{TOF} (landau fit);;t_{peak,raw}^{TOF} (ns)",nRuns,0., nRuns);//, 600, 0. , 600.);
  hPeakRawTimeVsRun->SetDrawOption("E1");
  hPeakRawTimeVsRun->SetMarkerStyle(21);
  hPeakRawTimeVsRun->SetMarkerColor(kGreen);

  TH1F * hSpreadRawTimeVsRun=new TH1F("hSpreadRawTimeVsRun","Spread of raw t^{TOF} (landau fit);;#sigma(t_{raw}^{TOF}) (ns)",nRuns,0., nRuns);//, 100, 0. , 100.);
  hSpreadRawTimeVsRun->SetDrawOption("E1");
  hSpreadRawTimeVsRun->SetMarkerStyle(21);
  hSpreadRawTimeVsRun->SetMarkerColor(kGreen);
   
  TH1F * hAvTotVsRun=new TH1F("hAvTotVsRun","<ToT> (no fit);run;<ToT> (ns)",nRuns,0., nRuns);//, 50, 0. , 50.);
  hAvTotVsRun->SetDrawOption("E1");
  hAvTotVsRun->SetMarkerStyle(22);
   
  TH1F * hPeakTotVsRun=new TH1F("hPeakTotVsRun","<ToT> (gaussian fit);;ToT_{peak} (ns)",nRuns,0., nRuns);//, 50, 0. , 50.);
  hPeakTotVsRun->SetDrawOption("E1");
  hPeakTotVsRun->SetMarkerStyle(22);
   
  TH1F * hSpreadTotVsRun=new TH1F("hSpreadTotVsRun","#sigma(ToT) (gaussian fit);#sigma(ToT) (ns)",nRuns,0., nRuns);//, 50, 0. , 50.);
  hSpreadTotVsRun->SetDrawOption("E1");
  hSpreadTotVsRun->SetMarkerStyle(22);
   
  TH1F * hNegTimeRatioVsRun=new TH1F("hNegTimeRatioVsRun","Ratio of tracks with t^{TOF}<12.5 ns; ; ratio of tracks with t^{TOF}<12.5 ns (%)",nRuns, 0., nRuns);//, 100, 0. , 100.);
  hNegTimeRatioVsRun->SetDrawOption("E");

  TH1F * hOrphansRatioVsRun=new TH1F("hOrphansRatioVsRun","Ratio of orphans (hits with ToT=0); ; ratio of orphans (%)",nRuns, 0., nRuns);//, 1000, 0. , 100.);
  hOrphansRatioVsRun->SetDrawOption("E");

  TH1F * hMeanLVsRun=new TH1F("hMeanLVsRun","Average track length;; <L> (cm)",nRuns, 0., nRuns);//, 350, 350. , 700.);
  hMeanLVsRun->SetDrawOption("E");
  TH1F * hNegLRatioVsRun=new TH1F("hNegLRatioVsRun","Ratio of tracks with L<350 cm;; ratio of tracks with L<350 cm (%)",nRuns, 0., nRuns);//, 1000, 0. , 100.);
  hNegLRatioVsRun->SetDrawOption("E");
  TH1F * hMatchEffVsRun=new TH1F("hMatchEffVsRun","#epsilon_{match} (linear fit for p_{T}>1.0 GeV/c);;#epsilon_{match} (p_{T}>1.0 GeV/c)",nRuns, 0., nRuns);//, 100, 0. , 1.);
  hMatchEffVsRun->SetDrawOption("E");
  TH1F * hMatchEffVsRunNormToGoodCh=new TH1F("hMatchEffVsRunNormToGoodCh","#epsilon_{match} normalized to percentage of TOF good channels;;#epsilon_{match}(p_{T}>1.0 GeV/c,|#eta|<0.8)/f_{all good}",nRuns, 0., nRuns);//, 100, 0. , 1.);
  hMatchEffVsRunNormToGoodCh->SetDrawOption("E");
	
  TH1F * hMatchEffVsRunNormToGoodChInAcc=new TH1F("hMatchEffVsRunNormToGoodChInAcc","#epsilon_{match} normalized to TOF good channels in |#eta|<0.8;;#epsilon_{match}(p_{T}>1.0 GeV/c,|#eta|<0.8/f_{good}(|#eta|<0.8)",nRuns, 0., nRuns);//, 100, 0. , 1.);
  hMatchEffVsRunNormToGoodChInAcc->SetDrawOption("E");

  TH1F * hMatchEffIntegratedVsRun=new TH1F("hMatchEffVsRun1hMatchEffIntegratedVsRun","#it{p}_{T} integrated #epsilon_{match}; ; #epsilon_{match} (1 < p_{T} < 10 GeV/c)",nRuns, 0., nRuns);
  hMatchEffIntegratedVsRun->SetDrawOption("E");

  TH1F * hPeakT0AVsRun=new TH1F("hPeakT0AVsRun","Peak value of T0A (gaussian fit);;t0A (ps)",nRuns,0., nRuns);
  TH1F * hPeakT0CVsRun=new TH1F("hPeakT0CVsRun","Peak value of T0C (gaussian fit);;t0AC (ps)",nRuns,0., nRuns);
  TH1F * hPeakT0ACVsRun=new TH1F("hPeakT0ACVsRun","Peak value of T0AC (gaussian fit);;t0AC (ps)",nRuns,0., nRuns);
  TH1F * hT0fillResVsRun=new TH1F("hT0fillResVsRun","t0_fill spread;;t0_spread (ps)",nRuns,0., nRuns);

  TH1F * hT0BestVsRun=new TH1F("hT0BestVsRun","start time by best_t0;;t0 Best (ps)",nRuns,0., nRuns);
  hT0BestVsRun->SetDrawOption("E1");
  hT0BestVsRun->SetLineColor(kOrange);
  hT0BestVsRun->SetLineWidth(2);
  hT0BestVsRun->SetMarkerStyle(20);
  hT0BestVsRun->SetMarkerColor(kOrange);

  TH1F * hT0FillVsRun=new TH1F("hT0FillVsRun","start time by fill_t0;;t0 Fill (ps)",nRuns,0., nRuns);
  hT0FillVsRun->SetDrawOption("E1");
  hT0FillVsRun->SetLineColor(kBlue);
  hT0FillVsRun->SetLineWidth(2);
  hT0FillVsRun->SetMarkerStyle(20);
  hT0FillVsRun->SetMarkerColor(kBlue);

  TH1F * hT0TOFVsRun=new TH1F("hT0TOFVsRun","start time by TOF_t0;;t0 TOF (ps)",nRuns,0., nRuns);
  hT0TOFVsRun->SetDrawOption("E1");
  hT0TOFVsRun->SetLineColor(kBlue);
  hT0TOFVsRun->SetLineWidth(2);
  hT0TOFVsRun->SetMarkerStyle(20);
  hT0TOFVsRun->SetMarkerColor(kBlue);

  TH1F * hT0T0ACVsRun=new TH1F("hT0T0ACVsRun","start time by T0AC;;t0 T0AC (ps)",nRuns,0., nRuns);
  hT0T0ACVsRun->SetDrawOption("E1");
  hT0T0ACVsRun->SetLineColor(kRed);
  hT0T0ACVsRun->SetLineWidth(2);
  hT0T0ACVsRun->SetMarkerStyle(20);
  hT0T0ACVsRun->SetMarkerColor(kRed);

  TH1F * hT0T0AVsRun=new TH1F("hT0T0AtVsRun","start time by T0A;;t0 T0A (ps)",nRuns,0., nRuns);
  hT0T0AVsRun->SetDrawOption("E1");
  hT0T0AVsRun->SetLineColor(kGreen+2);
  hT0T0AVsRun->SetLineWidth(2);
  hT0T0AVsRun->SetMarkerStyle(20);
  hT0T0AVsRun->SetMarkerColor(kGreen+2);

  TH1F * hT0T0CVsRun=new TH1F("hT0T0CVsRun","start time by T0C;;t0 T0C (ps)",nRuns,0., nRuns);
  hT0T0CVsRun->SetDrawOption("E1");
  hT0T0CVsRun->SetLineColor(kMagenta);
  hT0T0CVsRun->SetLineWidth(2);
  hT0T0CVsRun->SetMarkerStyle(20);
  hT0T0CVsRun->SetMarkerColor(kMagenta);

  TH1F * hT0BestVsRunRes=new TH1F("hT0BestVsRunRes","#sigma of best_t0;; #sigma t0 Best (ps)",nRuns,0., nRuns);
  hT0BestVsRunRes->SetDrawOption("E1");
  hT0BestVsRunRes->SetLineColor(kOrange);
  hT0BestVsRunRes->SetLineWidth(2);
  hT0BestVsRunRes->SetMarkerStyle(20);
  hT0BestVsRunRes->SetMarkerColor(kOrange);

  TH1F * hT0FillVsRunRes=new TH1F("hT0FillVsRunRes","fill_t0;; #sigmat0 Fill (ps)",nRuns,0., nRuns);
  hT0FillVsRunRes->SetDrawOption("E1");
  hT0FillVsRunRes->SetLineColor(kBlue);
  hT0FillVsRunRes->SetLineWidth(2);
  hT0FillVsRunRes->SetMarkerStyle(20);
  hT0FillVsRunRes->SetMarkerColor(kBlue);
  
  TH1F * hT0TOFVsRunRes=new TH1F("hT0T0FVsRunRes","TOF_t0;; #sigma t0 TOF (ps)",nRuns,0., nRuns);
  hT0TOFVsRunRes->SetDrawOption("E1");
  hT0TOFVsRunRes->SetLineColor(kBlue);
  hT0TOFVsRunRes->SetLineWidth(2);
  hT0TOFVsRunRes->SetMarkerStyle(20);
  hT0TOFVsRunRes->SetMarkerColor(kBlue);
  
  TH1F * hT0T0ACVsRunRes=new TH1F("hT0T0ACVsRunRes","T0AC_t0;; #sigma t0 T0AC (ps)",nRuns,0., nRuns);
  hT0T0ACVsRunRes->SetDrawOption("E1");
  hT0T0ACVsRunRes->SetLineColor(kRed);
  hT0T0ACVsRunRes->SetLineWidth(2);
  hT0T0ACVsRunRes->SetMarkerStyle(20);
  hT0T0ACVsRunRes->SetMarkerColor(kRed);
  
  TH1F * hT0T0AVsRunRes=new TH1F("hT0T0AVsRunRes","T0A_t0;; #sigma t0 T0A (ps)",nRuns,0., nRuns);
  hT0T0AVsRunRes->SetDrawOption("E1");
  hT0T0AVsRunRes->SetLineColor(kGreen+2);
  hT0T0AVsRunRes->SetLineWidth(2);
  hT0T0AVsRunRes->SetMarkerStyle(20);
  hT0T0AVsRunRes->SetMarkerColor(kGreen+2);
  
  TH1F * hT0T0CVsRunRes=new TH1F("hT0T0CVsRunRes","T0C_t0;; #sigma t0 T0C (ps)",nRuns,0., nRuns);
  hT0T0CVsRunRes->SetDrawOption("E1");
  hT0T0CVsRunRes->SetLineColor(kMagenta);
  hT0T0CVsRunRes->SetLineWidth(2);
  hT0T0CVsRunRes->SetMarkerStyle(20);
  hT0T0CVsRunRes->SetMarkerColor(kMagenta);
	
  TH1F * hGoodChannelsRatio=new TH1F("hGoodChannelsRatio","Fraction of TOF good channels;;fraction of good channels",nRuns, 0., nRuns);//, 100, 0. , 1.);
  hGoodChannelsRatio->SetDrawOption("E");

  TH1F * hGoodChannelsRatioInAcc=new TH1F("hGoodChannelsRatioInAcc","Fraction of TOF good channels in |#eta|<0.8;;fraction of good channels in |#eta|<0.8",nRuns, 0., nRuns);//, 100, 0. , 1.);
  hGoodChannelsRatioInAcc->SetDrawOption("E");
	
  lista.Add(hAvMulti);
  lista.Add(hAvDiffTimeVsRun);
  lista.Add(hPeakDiffTimeVsRun);
  lista.Add(hSpreadDiffTimeVsRun);
  lista.Add(hAvTimeVsRun);
  lista.Add(hPeakTimeVsRun);
  lista.Add(hMeanTOFResVsRun);
  lista.Add(hSigmaTOFResVsRun);
  lista.Add(hSpreadTimeVsRun);
  lista.Add(hAvRawTimeVsRun);
  lista.Add(hPeakRawTimeVsRun);
  lista.Add(hSpreadRawTimeVsRun); 
  lista.Add(hAvTotVsRun);
  lista.Add(hPeakTotVsRun);
  lista.Add(hSpreadTotVsRun);
  lista.Add(hNegTimeRatioVsRun);
  lista.Add(hOrphansRatioVsRun);
  lista.Add(hMeanLVsRun);
  lista.Add(hNegLRatioVsRun);
  lista.Add(hMatchEffVsRun);
  lista.Add(hMatchEffVsRunNormToGoodCh);
  lista.Add(hMatchEffVsRunNormToGoodChInAcc);
  lista.Add(hPeakT0AVsRun);
  lista.Add(hPeakT0CVsRun);
  lista.Add(hPeakT0ACVsRun);
  lista.Add(hT0fillResVsRun);
  lista.Add(hGoodChannelsRatio);
  lista.Add(hGoodChannelsRatioInAcc);
  lista.Add(hT0BestVsRun);
  lista.Add(hT0FillVsRun);
  lista.Add(hT0TOFVsRun);
  lista.Add(hT0T0ACVsRun);
  lista.Add(hT0T0AVsRun);
  lista.Add(hT0T0CVsRun);
  lista.Add(hT0BestVsRunRes);
  lista.Add(hT0FillVsRunRes);
  lista.Add(hT0TOFVsRunRes);
  lista.Add(hT0T0ACVsRunRes);
  lista.Add(hT0T0AVsRunRes);
  lista.Add(hT0T0CVsRunRes);
 
  char runlabel[6];
   
  for (Int_t irun=0;irun<nRuns;irun++){
    ttree->GetEntry(irun);
    
    sprintf(runlabel,"%i",runNumber);
    
    hAvMulti->SetBinContent(irun+1, avMulti);
    hAvMulti->GetXaxis()->SetBinLabel(irun+1,runlabel);

    hAvDiffTimeVsRun->SetBinContent(irun+1, avDiffTime);
    hAvDiffTimeVsRun->GetXaxis()->SetBinLabel(irun+1,runlabel);

    hPeakDiffTimeVsRun->SetBinContent(irun+1,peakDiffTime);
    hPeakDiffTimeVsRun->SetBinError(irun+1,peakDiffTimeErr);
    hPeakDiffTimeVsRun->GetXaxis()->SetBinLabel(irun+1,runlabel);

    hSpreadDiffTimeVsRun->SetBinContent(irun+1,spreadDiffTime);
    hSpreadDiffTimeVsRun->SetBinError(irun+1,spreadDiffTimeErr);
    hSpreadDiffTimeVsRun->GetXaxis()->SetBinLabel(irun+1,runlabel);

    hMeanTOFResVsRun->SetBinContent(irun+1,meanResTOF);
    hMeanTOFResVsRun->SetBinError(irun+1,meanResTOFerr);
    hMeanTOFResVsRun->GetXaxis()->SetBinLabel(irun+1,runlabel);

    hSigmaTOFResVsRun->SetBinContent(irun+1,spreadResTOF);
    hSigmaTOFResVsRun->SetBinError(irun+1,spreadResTOFerr);
    hSigmaTOFResVsRun->GetXaxis()->SetBinLabel(irun+1,runlabel);


    hAvTimeVsRun->SetBinContent(irun+1, avTime);
    hAvTimeVsRun->GetXaxis()->SetBinLabel(irun+1,runlabel);

    hPeakTimeVsRun->SetBinContent(irun+1,peakTime);
    hPeakTimeVsRun->SetBinError(irun+1,peakTimeErr);
    hPeakTimeVsRun->GetXaxis()->SetBinLabel(irun+1,runlabel);

    hSpreadTimeVsRun->SetBinContent(irun+1,spreadTime);
    hSpreadTimeVsRun->SetBinError(irun+1,spreadTimeErr);
    hSpreadTimeVsRun->GetXaxis()->SetBinLabel(irun+1,runlabel);

    hAvRawTimeVsRun->SetBinContent(irun+1, avRawTime);
    hAvRawTimeVsRun->GetXaxis()->SetBinLabel(irun+1,runlabel);
    
    hPeakRawTimeVsRun->SetBinContent(irun+1,peakRawTime);
    hPeakRawTimeVsRun->SetBinError(irun+1,peakRawTimeErr);
    hPeakRawTimeVsRun->GetXaxis()->SetBinLabel(irun+1,runlabel);

    hSpreadRawTimeVsRun->SetBinContent(irun+1,spreadRawTime);
    hSpreadRawTimeVsRun->SetBinError(irun+1,spreadRawTimeErr);
    hSpreadRawTimeVsRun->GetXaxis()->SetBinLabel(irun+1,runlabel);

    hAvTotVsRun->SetBinContent(irun+1,avTot);
    hAvTotVsRun->GetXaxis()->SetBinLabel(irun+1,runlabel);

    hPeakTotVsRun->SetBinContent(irun+1,peakTot);
    hPeakTotVsRun->SetBinError(irun+1,peakTotErr);
    hPeakTotVsRun->GetXaxis()->SetBinLabel(irun+1,runlabel);

    hSpreadTotVsRun->SetBinContent(irun+1,spreadTot);
    hSpreadTotVsRun->SetBinError(irun+1,spreadTotErr);
    hSpreadTotVsRun->GetXaxis()->SetBinLabel(irun+1,runlabel);
    
    hNegTimeRatioVsRun->SetBinContent(irun+1,negTimeRatio);
    hNegTimeRatioVsRun->GetXaxis()->SetBinLabel(irun+1,runlabel);
    
    hOrphansRatioVsRun->SetBinContent(irun+1,orphansRatio);
    hOrphansRatioVsRun->GetXaxis()->SetBinLabel(irun+1,runlabel);
    
    hMeanLVsRun->SetBinContent(irun+1,avL);
    hMeanLVsRun->GetXaxis()->SetBinLabel(irun+1,runlabel);
    
    hNegLRatioVsRun->SetBinContent(irun+1,negLratio);
    hNegLRatioVsRun->GetXaxis()->SetBinLabel(irun+1,runlabel);

    hMatchEffVsRun->SetBinContent(irun+1,matchEffLinFit1Gev);
    hMatchEffVsRun->SetBinError(irun+1,matchEffLinFit1GevErr);
    hMatchEffVsRun->GetXaxis()->SetBinLabel(irun+1,runlabel);
    hMatchEffVsRun->SetLineColor(kRed);
    hMatchEffVsRun->SetLineWidth(2);

    hMatchEffIntegratedVsRun->SetBinContent(irun+1, matchEffIntegrated);
    hMatchEffIntegratedVsRun->SetBinError(irun+1, matchEffIntegratedErr);
    hMatchEffIntegratedVsRun->GetXaxis()->SetBinLabel(irun+1,runlabel);
    hMatchEffIntegratedVsRun->SetLineColor(kOrange);
    hMatchEffIntegratedVsRun->SetLineStyle(7);
    hMatchEffIntegratedVsRun->SetLineWidth(2);
  
    if (goodChannelRatio>0)
      hMatchEffVsRunNormToGoodCh->SetBinContent(irun+1,matchEffLinFit1Gev/goodChannelRatio);
    else 
      hMatchEffVsRunNormToGoodCh->SetBinContent(irun+1, 0.0);
    hMatchEffVsRunNormToGoodCh->SetBinError(irun+1,matchEffLinFit1GevErr);
    hMatchEffVsRunNormToGoodCh->GetXaxis()->SetBinLabel(irun+1,runlabel);
    hMatchEffVsRunNormToGoodCh->SetLineColor(kCyan+2);
    hMatchEffVsRunNormToGoodCh->SetLineWidth(2);
     
    hGoodChannelsRatio->SetBinContent(irun+1, goodChannelRatio);
    hGoodChannelsRatio->SetLineColor(kCyan-1);
    hGoodChannelsRatio->SetLineWidth(2);
    hGoodChannelsRatio->GetXaxis()->SetBinLabel(irun+1,runlabel);

    if (goodChannelRatioInAcc>0)
      hMatchEffVsRunNormToGoodChInAcc->SetBinContent(irun+1,matchEffLinFit1Gev/goodChannelRatioInAcc);
    else 
      hMatchEffVsRunNormToGoodChInAcc->SetBinContent(irun+1, 0.0);
    hMatchEffVsRunNormToGoodChInAcc->SetBinError(irun+1,matchEffLinFit1GevErr);
    hMatchEffVsRunNormToGoodChInAcc->GetXaxis()->SetBinLabel(irun+1,runlabel);
    hMatchEffVsRunNormToGoodChInAcc->SetLineColor(kBlue);
    hMatchEffVsRunNormToGoodChInAcc->SetLineWidth(2);

    hGoodChannelsRatioInAcc->SetBinContent(irun+1, goodChannelRatioInAcc);
    hGoodChannelsRatioInAcc->SetLineColor(kBlue+2);
    hGoodChannelsRatioInAcc->SetLineWidth(2);
    hGoodChannelsRatioInAcc->GetXaxis()->SetBinLabel(irun+1,runlabel);

    hPeakT0AVsRun->SetBinContent(irun+1,peakT0A);
    hPeakT0AVsRun->SetBinError(irun+1,spreadT0A);
    hPeakT0AVsRun->GetXaxis()->SetBinLabel(irun+1,runlabel);

    hPeakT0CVsRun->SetBinContent(irun+1,peakT0C);
    hPeakT0CVsRun->SetBinError(irun+1,spreadT0C);
    hPeakT0CVsRun->GetXaxis()->SetBinLabel(irun+1,runlabel);
    
    hPeakT0ACVsRun->SetBinContent(irun+1,peakT0AC);
    hPeakT0ACVsRun->SetBinError(irun+1,spreadT0AC);
    hPeakT0ACVsRun->GetXaxis()->SetBinLabel(irun+1,runlabel);

    hT0fillResVsRun->SetBinContent(irun+1,avT0fillRes);
    hT0fillResVsRun->GetXaxis()->SetBinLabel(irun+1,runlabel);

    hT0BestVsRun->SetBinContent(irun+1,StartTime_pBestT0);
    hT0BestVsRun->SetBinError(irun+1,StartTime_pBestT0Err);
    hT0BestVsRun->GetXaxis()->SetBinLabel(irun+1,runlabel);

    hT0FillVsRun->SetBinContent(irun+1,StartTime_pFillT0);
    hT0FillVsRun->SetBinError(irun+1,StartTime_pFillT0Err);
    hT0FillVsRun->GetXaxis()->SetBinLabel(irun+1,runlabel);

    hT0TOFVsRun->SetBinContent(irun+1,StartTime_pTOFT0);
    hT0TOFVsRun->SetBinError(irun+1,StartTime_pTOFT0Err);
    hT0TOFVsRun->GetXaxis()->SetBinLabel(irun+1,runlabel);

    hT0T0ACVsRun->SetBinContent(irun+1,StartTime_pT0ACT0);
    hT0T0ACVsRun->SetBinError(irun+1,StartTime_pT0ACT0Err);
    hT0T0ACVsRun->GetXaxis()->SetBinLabel(irun+1,runlabel);

    hT0T0AVsRun->SetBinContent(irun+1,StartTime_pT0AT0);
    hT0T0AVsRun->SetBinError(irun+1,StartTime_pT0AT0Err);
    hT0T0AVsRun->GetXaxis()->SetBinLabel(irun+1,runlabel);

    hT0T0CVsRun->SetBinContent(irun+1,StartTime_pT0CT0);
    hT0T0CVsRun->SetBinError(irun+1,StartTime_pT0CT0Err);
    hT0T0CVsRun->GetXaxis()->SetBinLabel(irun+1,runlabel);
    
    hT0BestVsRunRes->SetBinContent(irun+1,StartTime_pBestT0_Res);
    hT0BestVsRunRes->SetBinError(irun+1, 1.e-5);
    hT0BestVsRunRes->GetXaxis()->SetBinLabel(irun+1,runlabel);

    hT0FillVsRunRes->SetBinContent(irun+1,StartTime_pFillT0_Res);
    hT0FillVsRunRes->SetBinError(irun+1, 1.e-5);   
    hT0FillVsRunRes->GetXaxis()->SetBinLabel(irun+1,runlabel);

    hT0TOFVsRunRes->SetBinContent(irun+1,StartTime_pTOFT0_Res);
    hT0TOFVsRunRes->SetBinError(irun+1, 1.e-5);
    hT0TOFVsRunRes->GetXaxis()->SetBinLabel(irun+1,runlabel);

    hT0T0ACVsRunRes->SetBinContent(irun+1,StartTime_pT0ACT0_Res);
    hT0T0ACVsRunRes->SetBinError(irun+1, 1.e-5);
    hT0T0ACVsRunRes->GetXaxis()->SetBinLabel(irun+1,runlabel);

    hT0T0AVsRunRes->SetBinContent(irun+1,StartTime_pT0AT0_Res);
    hT0T0AVsRunRes->SetBinError(irun+1, 1.e-5);
    hT0T0AVsRunRes->GetXaxis()->SetBinLabel(irun+1,runlabel);

    hT0T0CVsRunRes->SetBinContent(irun+1,StartTime_pT0CT0_Res);
    hT0T0CVsRunRes->SetBinError(irun+1, 1.e-5);
    hT0T0CVsRunRes->GetXaxis()->SetBinLabel(irun+1,runlabel);

  }
  
  TFile * fout=new TFile(outfilename,"recreate");
  fout->cd();
  lista.Write();
  fout->Close();
    
  gStyle->SetOptStat(10);

  TString plotext = "png";
  const TString desiredext = gSystem->Getenv("TOFQAPLOTEXTENSION");
  if(desiredext.EqualTo("pdf") || desiredext.EqualTo("root")) plotext = desiredext; 
  else if(!desiredext.IsNull()) cout<<"Unrecognized extension: '"<<desiredext<<"'"<<endl;
  
  //Plot t-texp trend
  TCanvas* cPeakDiffTimeVsRun = new TCanvas("cPeakDiffTimeVsRun","cPeakDiffTimeVsRun", 50,50,1050, 550);
  hPeakDiffTimeVsRun->GetYaxis()->SetRangeUser(-50.,50.);
  hPeakDiffTimeVsRun->Draw();
  cPeakDiffTimeVsRun->Print(Form("%s/cPeakDiffTimeVsRun.%s", plotDir.Data(), plotext.Data()));
	
  TCanvas* cSpreadDiffTimeVsRun = new TCanvas("cSpreadDiffTimeVsRun","cSpreadDiffTimeVsRun", 50,50,1050, 550);
  hSpreadDiffTimeVsRun->GetYaxis()->SetRangeUser(0.,400.);
  hSpreadDiffTimeVsRun->Draw();
  cSpreadDiffTimeVsRun->Print(Form("%s/cSpreadDiffTimeVsRun.%s", plotDir.Data(), plotext.Data()));

  //Plot average of t-texp-t0tof and resolution trend
  TCanvas* cMeanTOFResVsRun = new TCanvas("cMeanTOFResVsRun","cMeanTOFResVsRun", 50,50,1050, 550);
  hMeanTOFResVsRun->GetYaxis()->SetRangeUser(-50.,50.);
  hMeanTOFResVsRun->Draw();
  cMeanTOFResVsRun->Print(Form("%s/cMeanTOFResVsRun.%s", plotDir.Data(), plotext.Data()));
       
  TCanvas* cSigmaTOFResVsRun = new TCanvas("cSigmaTOFResVsRun","cSigmaTOFResVsRun", 50,50,1050, 550);
  hSigmaTOFResVsRun->GetYaxis()->SetRangeUser(0.,200.);
  hSigmaTOFResVsRun->Draw();
  cSigmaTOFResVsRun->Print(Form("%s/cSigmaTOFResVsRun.%s", plotDir.Data(), plotext.Data()));

  //Plot matching efficiency trend
  TCanvas* cMatchEffVsRun = new TCanvas("cMatchEffVsRun","cMatchEffVsRun",50, 50, 1050, 550);
  hMatchEffVsRun->GetYaxis()->SetRangeUser(0.,1.);
  hMatchEffVsRun->Draw();
  hMatchEffIntegratedVsRun->Draw("same");
  cMatchEffVsRun->Print(Form("%s/cMatchEffVsRun.%s", plotDir.Data(), plotext.Data()));
  
  TCanvas* cMatchEffNormToGoodChInAcc = new TCanvas("cMatchEffNormToGoodChInAcc","cMatchEffNormToGoodChInAcc",50, 50,1050, 550);
  hMatchEffVsRunNormToGoodChInAcc->GetYaxis()->SetRangeUser(0.,1.);
  hMatchEffVsRunNormToGoodChInAcc->Draw();
  cMatchEffNormToGoodChInAcc->Print(Form("%s/cMatchEffNormToGoodChInAcc.%s", plotDir.Data(), plotext.Data()));

  TCanvas* cMatchEffNormToGoodCh = new TCanvas("cMatchEffNormToGoodCh","cMatchEffNormToGoodCh",50, 50,1050, 550);
  hMatchEffVsRunNormToGoodCh->GetYaxis()->SetRangeUser(0.,1.);
  hMatchEffVsRunNormToGoodCh->Draw();
  cMatchEffNormToGoodCh->Print(Form("%s/cMatchEffNormToGoodCh.%s", plotDir.Data(), plotext.Data()));

   TLegend *leg = new TLegend(0.5095602,0.1206897,0.8891013,0.3314176,NULL,"brNDC");
   leg->SetBorderSize(1);
   leg->SetLineColor(1);
   leg->SetLineStyle(1);
   leg->SetLineWidth(1);
   leg->SetFillColor(0);
   leg->SetFillStyle(1001);
   
   TLegendEntry *entry=leg->AddEntry("hMatchEffVsRun","#epsilon_{match} (linear fit for p_{T}>1.0 GeV/c)","lpf");
   entry->SetFillStyle(1001);

   Int_t ci = TColor::GetColor("#ff0000");
   entry->SetLineColor(ci);
   entry->SetLineStyle(1);
   entry->SetLineWidth(2);
   entry->SetMarkerColor(1);
   entry->SetMarkerStyle(1);
   entry->SetMarkerSize(1);
   entry->SetTextFont(42);
   entry=leg->AddEntry("hMatchEffVsRunNormToGoodCh","#epsilon_{match} norm. to fraction of TOF good channels","lpf");
   entry->SetFillStyle(1001);

   ci = TColor::GetColor("#009999");
   entry->SetLineColor(ci);
   entry->SetLineStyle(1);
   entry->SetLineWidth(2);
   entry->SetMarkerColor(1);
   entry->SetMarkerStyle(1);
   entry->SetMarkerSize(1);
   entry->SetTextFont(42);
   entry=leg->AddEntry("hMatchEffVsRunNormToGoodChInAcc","#epsilon_{match} norm. to fraction of TOF good channels in |#eta|<0.8","lpf");
   entry->SetFillStyle(1001);

   ci = TColor::GetColor("#0000ff");
   entry->SetLineColor(ci);
   entry->SetLineStyle(1);
   entry->SetLineWidth(2);
   entry->SetMarkerColor(1);
   entry->SetMarkerStyle(1);
   entry->SetMarkerSize(1);
   entry->SetTextFont(42);

  TCanvas* cMatchEffSummary = new TCanvas("cMatchEffSummary","cMatchEffSummary",50, 50,1050, 550);
  hMatchEffVsRun->GetYaxis()->SetRangeUser(0.4,0.8);
  hMatchEffVsRun->Draw();
  hMatchEffVsRunNormToGoodCh->Draw("same");
  hMatchEffVsRunNormToGoodChInAcc->Draw("same");
  leg->Draw("same");
  cMatchEffSummary->Print(Form("%s/cMatchEffSummary.%s", plotDir.Data(), plotext.Data()));
  
  //Plot start time trend
  TCanvas* cStartTimeSummary = new TCanvas("cStartTimeSummary","cStartTimeSummary",50, 50,1050, 550);
  hT0TOFVsRun->GetYaxis()->SetRangeUser(-100.,100.);
  hT0TOFVsRun->GetYaxis()->SetTitle("Start Time (ps)");
  hT0TOFVsRun->Draw();
  hT0T0ACVsRun->Draw("same");
  hT0T0AVsRun->Draw("same");
  hT0T0CVsRun->Draw("same");
  hT0BestVsRun->Draw("same");
  gPad->SetGridy();
  gPad->SetTitle("Start Time by different methods");
  TLegend * cLegSTS = new TLegend(0.6,0.7,0.9,0.9);
  cLegSTS->SetFillStyle(1001);
  cLegSTS->SetFillColor(kWhite);
  cLegSTS->SetNColumns(2);
  cLegSTS->SetBorderSize(1);
  cLegSTS->AddEntry(hT0TOFVsRun,"TOF_T0","lp");
  cLegSTS->AddEntry(hT0T0ACVsRun,"T0AC_T0","lp");
  cLegSTS->AddEntry(hT0T0AVsRun,"T0A_T0","lp");
  cLegSTS->AddEntry(hT0T0CVsRun,"T0C_T0","lp");
  cLegSTS->AddEntry(hT0BestVsRun, "Best_T0","lp");
  cLegSTS->Draw();
  cStartTimeSummary->Print(Form("%s/cStartTimeSummary.%s", plotDir.Data(), plotext.Data()));

  TCanvas* cStartTimeResolutionSummary = new TCanvas("cStartTimeResolutionSummary","cStartTimeResolutionSummary",50, 50,1050, 550);
  hT0TOFVsRunRes->GetYaxis()->SetRangeUser(0.,200.);
  hT0TOFVsRunRes->GetYaxis()->SetTitle("#sigma Start Time (ps)");
  hT0TOFVsRunRes->Draw();
  hT0T0ACVsRunRes->Draw("same");
  hT0T0AVsRunRes->Draw("same");
  hT0T0CVsRunRes->Draw("same");
  hT0BestVsRunRes->Draw("same");
  TLegend * cLegSTRS = new TLegend(0.6,0.7,0.9,0.9);
  cLegSTRS->SetFillStyle(1001);
  cLegSTRS->SetFillColor(kWhite);
  cLegSTRS->SetNColumns(2);
  cLegSTRS->SetBorderSize(1);
  cLegSTRS->AddEntry(hT0TOFVsRunRes,"TOF_T0 res.","lp");
  cLegSTRS->AddEntry(hT0T0ACVsRunRes,"T0AC_T0 res.","lp");
  cLegSTRS->AddEntry(hT0T0AVsRunRes,"T0A_T0 res.","lp");
  cLegSTRS->AddEntry(hT0T0CVsRunRes,"T0C_T0 res.","lp");
  cLegSTRS->AddEntry(hT0BestVsRunRes, "Best_T0 res.","lp");
    
  cLegSTRS->Draw();
  cStartTimeResolutionSummary->Print(Form("%s/cStartTimeResolutionSummary.%s", plotDir.Data(), plotext.Data()));

  TCanvas* cGoodCh = new TCanvas("cGoodCh","cGoodCh",50, 50,1050, 550);
  hGoodChannelsRatio->GetYaxis()->SetRangeUser(0.75,1.);
  hGoodChannelsRatio->Draw();
  cGoodCh->Print(Form("%s/cGoodCh.%s", plotDir.Data(), plotext.Data()));

  TCanvas* cGoodChInAcc = new TCanvas("cGoodChInAcc","cGoodChInAcc",50, 50,1050, 550);
  hGoodChannelsRatioInAcc->GetYaxis()->SetRangeUser(0.75,1.);
  hGoodChannelsRatioInAcc->Draw();
  cGoodChInAcc->Print(Form("%s/cGoodChInAcc.%s", plotDir.Data(), plotext.Data()));

  TCanvas* cPidPerformance= new TCanvas("cPidPerformance","summary of PID performance", 1200, 500);
  cPidPerformance->Divide(3,1);
  cPidPerformance->cd(1);
  gPad->SetLogz();
  hDiffTimePi->Draw("colz");
  cPidPerformance->cd(2);
  gPad->SetLogz();
  hDiffTimeKa->Draw("colz");
  cPidPerformance->cd(3);
  gPad->SetLogz();
  hDiffTimePro->Draw("colz");
  cPidPerformance->Print(Form("%s/cPIDExpTimes.%s", plotDir.Data(), plotext.Data()));
  
  if (displayAll) {	
    TCanvas* cPeakT0AVsRun = new TCanvas("cPeakT0AVsRun","cPeakT0AVsRun", 50,50,1050, 550);
    hPeakT0AVsRun->Draw();
    cPeakT0AVsRun->Print(Form("%s/cPeakT0AVsRun.png",plotDir.Data()));
  
    TCanvas* cPeakT0CVsRun = new TCanvas("cPeakT0CVsRun","cPeakT0CVsRun", 50,50,1050, 550);
    hPeakT0CVsRun->Draw();
    cPeakT0CVsRun->Print(Form("%s/cPeakT0CVsRun.png",plotDir.Data()));
  
    TCanvas* cPeakT0ACVsRun = new TCanvas("cPeakT0ACVsRun","cPeakT0ACVsRun", 50,50,1050, 550);
    hPeakT0ACVsRun->Draw();
    cPeakT0ACVsRun->Print(Form("%s/cPeakT0ACVsRun.png",plotDir.Data()));
  
    TCanvas* cT0fillResVsRun = new TCanvas("cT0fillResVsRun","cT0fillResVsRun", 50,50,1050, 550);
    hT0fillResVsRun->Draw();
    cT0fillResVsRun->Print(Form("%s/cT0fillResVsRun.png",plotDir.Data()));

    //Plot TOF signal trend
    TCanvas* cAvDiffTimeVsRun = new TCanvas("cAvDiffTimeVsRun","cAvDiffTimeVsRun",50,50,1050, 550);
    gPad->SetGridx();
    gPad->SetGridy();
    hAvDiffTimeVsRun->Draw();
    cAvDiffTimeVsRun->Print(Form("%s/cAvDiffTimeVsRun.png",plotDir.Data()));
	  
    TCanvas* cAvTimeVsRun = new TCanvas("cAvTimeVsRun","cAvTimeVsRun", 50,50,1050, 550);
    hAvTimeVsRun->Draw();
    cAvTimeVsRun->Print(Form("%s/cAvTimeVsRun.png",plotDir.Data()));
	  
    TCanvas* cPeakTimeVsRun = new TCanvas("cPeakTimeVsRun","cPeakTimeVsRun", 50,50,1050, 550);
    hPeakTimeVsRun->Draw();
    cPeakTimeVsRun->Print(Form("%s/cPeakTimeVsRun.png",plotDir.Data()));
	  
    TCanvas* cSpreadTimeVsRun = new TCanvas("cSpreadTimeVsRun","cSpreadTimeVsRun", 50,50,1050, 550);
    hSpreadTimeVsRun->Draw();
    cSpreadTimeVsRun->Print(Form("%s/cSpreadTimeVsRun.png",plotDir.Data()));
	  
    TCanvas* cAvRawTimeVsRun = new TCanvas("cAvRawTimeVsRun","cAvRawTimeVsRun", 50,50,1050, 550);
    hAvRawTimeVsRun->Draw();
    cAvRawTimeVsRun->Print(Form("%s/cAvRawTimeVsRun.png",plotDir.Data()));
	  
    TCanvas* cPeakRawTimeVsRun = new TCanvas("cPeakRawTimeVsRun","cPeakRawTimeVsRun", 50,50,1050, 550);
    hPeakRawTimeVsRun->Draw();
    cPeakRawTimeVsRun->Print(Form("%s/cPeakRawTimeVsRun.png",plotDir.Data()));
	  
    TCanvas* cSpreadRawTimeVsRun = new TCanvas("cSpreadRawTimeVsRun","cSpreadRawTimeVsRun", 50,50,1050, 550);
    hSpreadRawTimeVsRun->Draw();
    cSpreadRawTimeVsRun->Print(Form("%s/cSpreadRawTimeVsRun.png",plotDir.Data()));
	  
    TCanvas* cAvTotVsRun = new TCanvas("cAvTotVsRun","cAvTotVsRun", 50,50,1050, 550);
    hAvTotVsRun->Draw();
    cAvTotVsRun->Print(Form("%s/cAvTotVsRun.png",plotDir.Data()));
	  
    TCanvas* cPeakTotVsRun = new TCanvas("cPeakTotVsRun","cPeakTotVsRun", 50,50,1050, 550);
    hPeakTotVsRun->Draw();
    cPeakTotVsRun->Print(Form("%s/cPeakTotVsRun.png",plotDir.Data()));
	  
    TCanvas* cSpreadTotVsRun = new TCanvas("cSpreadTotVsRun","cSpreadTotVsRun", 50,50,1050, 550);
    hSpreadTotVsRun->Draw();
    cSpreadTotVsRun->Print(Form("%s/cSpreadTotVsRun.png",plotDir.Data()));
	  
    TCanvas* cNegTimeRatioVsRun = new TCanvas("cNegTimeRatioVsRun","cNegTimeRatioVsRun", 50,50,1050, 550);
    hNegTimeRatioVsRun->Draw();
    cNegTimeRatioVsRun->Print(Form("%s/cNegTimeRatioVsRun.png",plotDir.Data()));
	  
    TCanvas* cOrphansRatioVsRun = new TCanvas("cOrphansRatioVsRun","cOrphansRatioVsRun", 50,50,1050, 550);
    hOrphansRatioVsRun->Draw();
    cOrphansRatioVsRun->Print(Form("%s/cOrphansRatioVsRun.png",plotDir.Data()));
	  
    TCanvas* cMeanLVsRun = new TCanvas("cMeanLVsRun","cMeanLVsRun", 50,50,1050, 550);
    hMeanLVsRun->Draw();
    cMeanLVsRun->Print(Form("%s/cMeanLVsRun.png",plotDir.Data()));
	  
    TCanvas* cNegLRatioVsRun = new TCanvas("cNegLRatioVsRun","cNegLRatioVsRun", 50,50,1050, 550);
    hNegLRatioVsRun->Draw();
    cNegLRatioVsRun->Print(Form("%s/cNegLRatioVsRun.png",plotDir.Data()));
  }
	
  return 0;
}
Exemple #17
0
void binary( string inFile = "allSim.root", int cSpecies = 1, bool cutDedx = false ){

	TCanvas * c = new TCanvas( "c", "c", 800, 800 );
	string outName = "rpBinaryPid.pdf";
	c->Print( (outName+"[").c_str() );

	TFile * f = new TFile( inFile.c_str(), "READ" );

	string rOutName = "rootBinaryPid.root";
	TFile * fOut = new TFile( rOutName.c_str(), "RECREATE" );

	vector<double>effVsP;
	vector<double>pureVsP;

	c->Divide( 2, 2 );
	for ( int i = 0; i < 70; i++ ){

		stringstream sstr;
		sstr << "h_dedx_tof_p3_b" << i;
		TH2* sum = (TH2*)f->Get( sstr.str().c_str() );
		
		sstr.str("");
		sstr << "h_dedx_tof_p0_b" << i;

		TH2* p0 = (TH2*)f->Get( sstr.str().c_str() );
		sstr.str("");
		sstr << "h_dedx_tof_p1_b" << i;
		TH2* p1 = (TH2*)f->Get( sstr.str().c_str() );
		sstr.str("");
		sstr << "h_dedx_tof_p2_b" << i;
		TH2* p2 = (TH2*)f->Get( sstr.str().c_str() );

		pidBinary * pid = new pidBinary( sum, cSpecies, p0, p1, p2 );
		pid->cutDedx( cutDedx );

		c->cd( 3 );
		gPad->SetLogz(1);
		sum->Draw("colz");
		

		c->cd( 4 );
		gPad->SetLogx(1);
		TH1* pX = sum->ProjectionX();
		TH1* pY = sum->ProjectionY();
		pY->SetFillColor( kBlue );
		pY->SetLineColor( kBlue );
		pY->Draw("hbar");


		c->cd(1);
		gPad->SetLogy(1);
		pX->SetFillColor( kBlue );
		pX->SetLineColor( kBlue );
		pX->Draw("h");
		c->cd(2);
		
		sstr.str("");
		sstr << "eff_" << i;
		TH1D* eff = pid->efficiency( sstr.str(), 0.0, 5.0, 0.1 );
		sstr.str("");
		sstr << "pure_" << i;
		TH1D* pure = pid->purity( sstr.str(), 0.0, 5.0, 0.1 );

		gStyle->SetOptStat( 0 );
		eff->SetTitle( "Efficiecy (Blue), Purity (Red)" );
		eff->GetYaxis()->SetRangeUser(0, 1.05);
		eff->SetLineWidth( 2 );
		eff->Draw();
		pure->SetLineColor( kRed );
		pure->SetLineWidth( 2 );
		pure->Draw("same");

		effVsP.push_back( pid->efficiency() );
		pureVsP.push_back( pid->purity( ) );

		c->Print( outName.c_str());
	}

	int nBins = (3.7 - 0.2) / 0.05;
	TH1D * hEffVsP = new TH1D( "hEffVsP", "Efficiency Vs. P; P [GeV]", nBins, 0.2, 3.7 );
	for ( int i = 0; i < effVsP.size(); i++ ){
		hEffVsP->SetBinContent( i, effVsP[ i ] );
	}
	TH1D * hPureVsP = new TH1D( "hPureVsP", "Purity Vs. P; P [GeV]", nBins, 0.2, 3.7 );
	for ( int i = 0; i < pureVsP.size(); i++ ){
		hPureVsP->SetBinContent( i, pureVsP[ i ] );
	}

	c->Divide( 1 );
	c->cd( 0 );
	hEffVsP->GetYaxis()->SetRangeUser( 0.0, 1.05);
	hEffVsP->SetLineWidth( 2 );
	hEffVsP->SetTitle( "Efficiency (Blue), Purity (Red)" );
	hEffVsP->Draw( "");
	hPureVsP->SetLineColor( kRed );
	hPureVsP->SetLineWidth( 2 );
	hPureVsP->Draw( "same" );

	c->Print( outName.c_str());



	c->Print( (outName+"]").c_str() );

	fOut->Write();

}
Int_t DrawPerformanceZDCQAMatch(TString inFile="trending.root"){

// Draw control histograms and generate output pictures

gSystem->Load("libSTAT");
gSystem->Load("libANALYSIS");
gSystem->Load("libANALYSISalice");
gSystem->Load("libANALYSIScalib");
gSystem->Load("libCORRFW");
gSystem->Load("libANALYSISalice");
gSystem->Load("libANALYSIScalib");
gSystem->Load("libTender");
gSystem->Load("libPWGPP");

gROOT->Reset();
gROOT->SetStyle("Plain");
gStyle->SetPalette(1);
gStyle->SetOptStat(0);
gStyle->SetTitleSize(0.025);
TH1::AddDirectory(kFALSE);

TFile * fin = TFile::Open(inFile.Data());
if (!fin){
  Printf("File not found !!!");
  return -1;
}
TTree * ttree = (TTree*) fin->Get("trending");  //in

TTree * tree = new TTree("tree","tree");        //out (to be summed)

if (!ttree){
  Printf("Invalid trending tree!!!!!!!!!!!!!!");
  return -2;
}

Int_t nRuns = ttree->GetEntries();
TList list;
printf(" nRuns %d\n", nRuns);

/*set graphic style*/
gStyle->SetCanvasColor(kWhite);
gStyle->SetFrameFillColor(kWhite);
gStyle->SetFrameBorderMode(0);
gStyle->SetCanvasBorderMode(0);
gStyle->SetTitleFillColor(kWhite);
gStyle->SetTitleBorderSize(0);
gStyle->SetTitleFont(42);
gStyle->SetTitleX(0.5);
gStyle->SetTitleAlign(23);
gStyle->SetTextFont(42);
gStyle->SetStatColor(kWhite);
gStyle->SetStatBorderSize(1);
gStyle->SetOptStat(0);
gStyle->SetTickLength(0.02,"y");
gStyle->SetLabelSize(0.02,"xyz");
gStyle->SetLabelOffset(0.03,"xyz");

TString plotDir(".");

TLegend *legend = new TLegend(0.9,0.1,1.0,0.9);
legend->SetFillColor(kWhite);

Int_t runNumber=0;
Double_t ZNC_mean=0;
Double_t ZNA_mean=0;
Double_t ZPA_mean=0;
Double_t ZPC_mean=0;
Double_t ZNCuncalib_mean=0;
Double_t ZNAuncalib_mean=0;
Double_t ZPAuncalib_mean=0;
Double_t ZPCuncalib_mean=0;
Double_t ZEM1_mean=0;
Double_t ZEM2_mean=0;
Double_t ZNC_XCent=0;
Double_t ZNC_YCent=0;
Double_t ZNA_XCent=0;
Double_t ZNA_YCent=0;
Double_t ZNC_XCent_err=0;
Double_t ZNC_YCent_err=0;
Double_t ZNA_XCent_err=0;
Double_t ZNA_YCent_err=0;
Double_t ZN_TDC_Sum=0;
Double_t ZN_TDC_Diff=0;
Double_t ZN_TDC_Sum_err=0;
Double_t ZN_TDC_Diff_err=0;
Double_t ZNC_TDC=0;
Double_t ZNA_TDC=0;

TH1F *hZNCpmcUncalib = new TH1F("hZNCpmcUncalib","hZNCpmcUncalib",200.,0.,2000.);
TH1F *hZNApmcUncalib = new TH1F("hZNApmcUncalib","hZNApmcUncalib",200.,0.,2000.);
TH1F *hZPCpmcUncalib = new TH1F("hZPCpmcUncalib","hZPCpmcUncalib",200.,0.,2000.);
TH1F *hZPApmcUncalib = new TH1F("hZPApmcUncalib","hZPApmcUncalib",200.,0.,2000.);
TH1F *hZEM1 = new TH1F("hZEM1","hZEM1",200.,0.,2000.);
TH1F *hZEM2 = new TH1F("hZEM2","hZEM2",200.,0.,2000.);

ttree->SetBranchAddress("run",&runNumber);
ttree->SetBranchAddress("ZNC_mean_value",&ZNC_mean);
ttree->SetBranchAddress("ZNA_mean_value",&ZNA_mean);
ttree->SetBranchAddress("ZPC_mean_value",&ZPC_mean);
ttree->SetBranchAddress("ZPA_mean_value",&ZPA_mean);
ttree->SetBranchAddress("ZNCuncalib_mean",&ZNCuncalib_mean);
ttree->SetBranchAddress("ZNAuncalib_mean",&ZNAuncalib_mean);
ttree->SetBranchAddress("ZPCuncalib_mean",&ZPCuncalib_mean);
ttree->SetBranchAddress("ZPAuncalib_mean",&ZPAuncalib_mean);
ttree->SetBranchAddress("ZEM1_mean_value",&ZEM1_mean);
ttree->SetBranchAddress("ZEM2_mean_value",&ZEM2_mean);
ttree->SetBranchAddress("ZNC_X_Centroid",&ZNC_XCent);
ttree->SetBranchAddress("ZNC_Y_Centroid",&ZNC_YCent);
ttree->SetBranchAddress("ZNA_X_Centroid",&ZNA_XCent);
ttree->SetBranchAddress("ZNA_Y_Centroid",&ZNA_YCent);
ttree->SetBranchAddress("ZNC_X_Centroid_Err",&ZNC_XCent_err);
ttree->SetBranchAddress("ZNC_Y_Centroid_Err",&ZNC_YCent_err);
ttree->SetBranchAddress("ZNA_X_Centroid_Err",&ZNA_XCent_err);
ttree->SetBranchAddress("ZNA_Y_Centroid_Err",&ZNA_YCent_err);
ttree->SetBranchAddress("ZN_TDC_Sum",&ZN_TDC_Sum);
ttree->SetBranchAddress("ZN_TDC_Diff",&ZN_TDC_Diff);
ttree->SetBranchAddress("ZN_TDC_Sum_Err",&ZN_TDC_Sum_err);
ttree->SetBranchAddress("ZN_TDC_Diff_Err",&ZN_TDC_Diff_err);
//ttree->SetBranchAddress("ZNC_TDC",&ZNC_TDC);
//ttree->SetBranchAddress("ZNA_TDC",&ZNA_TDC);

printf(" branch addresses set\n");

TH1F *hznc = new TH1F("hznc","ZNC average signal",3,-1,1);
hznc->GetXaxis()->SetRangeUser(-1.,1.);
hznc->SetDrawOption("EP");
hznc->SetMarkerStyle(20);
hznc->SetMarkerColor(kRed);
hznc->SetLineColor(kRed);

TH1F *hzna = new TH1F("hzna","ZNA average signal",3,-1,1);
hzna->GetXaxis()->SetRangeUser(-1.,1.);
hzna->SetDrawOption("EP");
hzna->SetMarkerStyle(20);
hzna->SetMarkerColor(kRed);
hzna->SetLineColor(kRed);

TH1F *hzpc = new TH1F("hzpc","ZPC average signal",3,-1,1);
hzpc->GetXaxis()->SetRangeUser(-1.,1.);
hzpc->SetDrawOption("EP");
hzpc->SetMarkerStyle(20);
hzpc->SetMarkerColor(kRed);
hzpc->SetLineColor(kRed);

TH1F *hzpa = new TH1F("hzpa","ZPA average signal",3,-1,1);
hzpa->GetXaxis()->SetRangeUser(-1.,1.);
hzpa->SetDrawOption("EP");
hzpa->SetMarkerStyle(20);
hzpa->SetMarkerColor(kRed);
hzpa->SetLineColor(kRed);

TH1F *hzncUncalib = new TH1F("hzncUncalib","ZNC uncalibrated average signal",3,-1,1);
hzncUncalib->GetXaxis()->SetRangeUser(-1.,1.);
hzncUncalib->SetDrawOption("EP");
hzncUncalib->SetMarkerStyle(20);
hzncUncalib->SetMarkerColor(kAzure+10);
hzncUncalib->SetLineColor(kAzure+10);

TH1F *hznaUncalib = new TH1F("hznaUncalib","ZNA uncalibrated average signal",3,-1,1);
hznaUncalib->GetXaxis()->SetRangeUser(-1.,1.);
hznaUncalib->SetDrawOption("EP");
hznaUncalib->SetMarkerStyle(20);
hznaUncalib->SetMarkerColor(kAzure+10);
hznaUncalib->SetLineColor(kAzure+10);

TH1F *hzpcUncalib = new TH1F("hzpcUncalib","ZPC uncalibrated average signal",3,-1,1);
hzpcUncalib->GetXaxis()->SetRangeUser(-1.,1.);
hzpcUncalib->SetDrawOption("EP");
hzpcUncalib->SetMarkerStyle(20);
hzpcUncalib->SetMarkerColor(kAzure+10);
hzpcUncalib->SetLineColor(kAzure+10);

TH1F *hzpaUncalib = new TH1F("hzpaUncalib","ZPA uncalibrated average signal",3,-1,1);
hzpaUncalib->GetXaxis()->SetRangeUser(-1.,1.);
hzpaUncalib->SetDrawOption("EP");
hzpaUncalib->SetMarkerStyle(20);
hzpaUncalib->SetMarkerColor(kAzure+10);
hzpaUncalib->SetLineColor(kAzure+10);

TH1F *hzem1 = new TH1F("hzem1","ZEM1 average signal",3,-1,1);
hzem1->GetXaxis()->SetRangeUser(-1.,1.);
hzem1->SetDrawOption("EP");
hzem1->SetMarkerStyle(20);
hzem1->SetMarkerColor(kRed);
hzem1->SetLineColor(kRed);

TH1F *hzem2 = new TH1F("hzem2","ZEM2 average signal",3,-1,1);
hzem2->GetXaxis()->SetRangeUser(-1.,1.);
hzem2->SetDrawOption("EP");
hzem2->SetMarkerStyle(20);
hzem2->SetMarkerColor(kRed);
hzem2->SetLineColor(kRed);

TH1F *hzna_Xcentroid = new TH1F("hzna_Xcentroid","ZNA X centroid",3,-1,1);
hzna_Xcentroid->GetXaxis()->SetRangeUser(-1.,1.);
hzna_Xcentroid->SetDrawOption("EP");
hzna_Xcentroid->SetMarkerStyle(20);
hzna_Xcentroid->SetMarkerColor(kRed);
hzna_Xcentroid->SetLineColor(kRed);

TH1F *hzna_Ycentroid = new TH1F("hzna_Ycentroid","ZNA Y centroid",3,-1,1);
hzna_Ycentroid->GetXaxis()->SetRangeUser(-1.,1.);
hzna_Ycentroid->SetDrawOption("EP");
hzna_Ycentroid->SetMarkerStyle(20);
hzna_Ycentroid->SetMarkerColor(kRed);
hzna_Ycentroid->SetLineColor(kRed);

TH1F *hznc_Xcentroid = new TH1F("hznc_Xcentroid","ZNC X centroid",3,-1,1);
hznc_Xcentroid->GetXaxis()->SetRangeUser(-1.,1.);
hznc_Xcentroid->SetDrawOption("EP");
hznc_Xcentroid->SetMarkerStyle(20);
hznc_Xcentroid->SetMarkerColor(kRed);
hznc_Xcentroid->SetLineColor(kRed);

TH1F *hznc_Ycentroid = new TH1F("hznc_Ycentroid","ZNC Y centroid",3,-1,1);
hznc_Ycentroid->GetXaxis()->SetRangeUser(-1.,1.);
hznc_Ycentroid->SetDrawOption("EP");
hznc_Ycentroid->SetMarkerStyle(20);
hznc_Ycentroid->SetMarkerColor(kRed);
hznc_Ycentroid->SetLineColor(kRed);

TH1F *hzn_TDC_Sum = new TH1F("hzn_TDC_Sum","ZNC TDC + ZNA TDC",3,-1,1);
hzn_TDC_Sum->GetXaxis()->SetRangeUser(-1.,1.);
hzn_TDC_Sum->SetDrawOption("EP");
hzn_TDC_Sum->SetMarkerStyle(20);
hzn_TDC_Sum->SetMarkerColor(kRed);
hzn_TDC_Sum->SetLineColor(kRed);

TH1F *hzn_TDC_Diff = new TH1F("hzn_TDC_Diff","ZNC TDC - ZNA TDC",3,-1,1);
hzn_TDC_Diff->GetXaxis()->SetRangeUser(-1.,1.);
hzn_TDC_Diff->SetDrawOption("EP");
hzn_TDC_Diff->SetMarkerStyle(20);
hzn_TDC_Diff->SetMarkerColor(kRed);
hzn_TDC_Diff->SetLineColor(kRed);

TH1F *hznc_TDC = new TH1F("hznc_TDC","ZNC TDC",3,-1,1);
hznc_TDC->GetXaxis()->SetRangeUser(-1.,1.);
hznc_TDC->SetDrawOption("EP");
hznc_TDC->SetMarkerStyle(20);
hznc_TDC->SetMarkerColor(kRed);
hznc_TDC->SetLineColor(kRed);

TH1F *hzna_TDC = new TH1F("hzna_TDC","ZNA TDC",3,-1,1);
hzna_TDC->GetXaxis()->SetRangeUser(-1.,1.);
hzna_TDC->SetDrawOption("EP");
hzna_TDC->SetMarkerStyle(20);
hzna_TDC->SetMarkerColor(kRed);
hzna_TDC->SetLineColor(kRed);

char runlabel[40];

for (Int_t irun=0;irun<nRuns;irun++){
  ttree->GetEntry(irun);
 }

sprintf(runlabel,"%i",runNumber);

//----------------------------------------------------------------------
//spectrum vs run
//----------------------------------------------------------------------

hZNCpmcUncalib = dynamic_cast<TH1F*> (fin->Get("fhZNCpmcUncalib"));
if(hZNCpmcUncalib){
if(hZNCpmcUncalib->GetEntries()>0. ) hZNCpmcUncalib->Scale(1./hZNCpmcUncalib->GetEntries());
hZNCpmcUncalib->SetLineColor(kRed);
hZNCpmcUncalib->SetLineWidth(2);
hZNCpmcUncalib->SetTitle("ZNC spectrum");
hZNCpmcUncalib->SetXTitle("ZNC signal ");
}

hZNApmcUncalib = dynamic_cast<TH1F*> (fin->Get("fhZNApmcUncalib"));
if(hZNApmcUncalib){
if(hZNApmcUncalib->GetEntries()>0. ) hZNApmcUncalib->Scale(1./hZNApmcUncalib->GetEntries());
hZNApmcUncalib->SetLineColor(kRed);
hZNApmcUncalib->SetLineWidth(2);
hZNApmcUncalib->SetTitle("ZNA spectrum");
hZNApmcUncalib->SetXTitle("ZNA signal ");
}

hZPCpmcUncalib = dynamic_cast<TH1F*> (fin->Get("fhZPCpmcUncalib"));
if(hZPCpmcUncalib){
  if(hZPCpmcUncalib->GetEntries()>0. ) hZPCpmcUncalib->Scale(1./hZPCpmcUncalib->GetEntries());
hZPCpmcUncalib->SetLineColor(kRed);
hZPCpmcUncalib->SetLineWidth(2);
hZPCpmcUncalib->SetTitle("ZPC spectrum");
hZPCpmcUncalib->SetXTitle("ZPC signal ");
}

hZPApmcUncalib = dynamic_cast<TH1F*> (fin->Get("fhZPApmcUncalib"));
if(hZPApmcUncalib){
if(hZPApmcUncalib->GetEntries()>0. ) hZPApmcUncalib->Scale(1./hZPApmcUncalib->GetEntries());
hZPApmcUncalib->SetLineColor(kRed);
hZPApmcUncalib->SetLineWidth(2);
hZPApmcUncalib->SetTitle("ZPA spectrum");
hZPApmcUncalib->SetXTitle("ZPA signal ");
}

hZEM1 = dynamic_cast<TH1F*> (fin->Get("fhZEM1Spectrum"));
if(hZEM1){
if(hZEM1->GetEntries()>0.) hZEM1->Scale(1./hZEM1->GetEntries());
hZEM1->SetLineColor(kRed);
hZEM1->SetLineWidth(2);
hZEM1->SetTitle("ZEM1 spectrum");
hZEM1->SetXTitle("ZEM1 signal (ADC ch.)");
}

hZEM2 = dynamic_cast<TH1F*> (fin->Get("fhZEM2Spectrum"));
if(hZEM2){
if(hZEM2->GetEntries()>0.) hZEM2->Scale(1./hZEM2->GetEntries());
hZEM2->SetLineColor(kRed);
hZEM2->SetLineWidth(2);
hZEM2->SetTitle("ZEM2 spectrum");
hZEM2->SetXTitle("ZEM2 signal (ADC ch.)");
}

//----------------------------------------------------------------------
//variables vs run
//----------------------------------------------------------------------
hzna->SetBinContent(2,ZNA_mean);
hzna->GetXaxis()->SetBinLabel(2,runlabel);
hzna->GetXaxis()->SetLabelSize(0.05);

hzpc->SetBinContent(2,ZPC_mean);
hzpc->GetXaxis()->SetBinLabel(2,runlabel);
hzpc->GetXaxis()->SetLabelSize(0.05);

hznc->SetBinContent(2,ZNC_mean);
hznc->GetXaxis()->SetBinLabel(2,runlabel);
hznc->GetXaxis()->SetLabelSize(0.05);

hzpa->SetBinContent(2,ZPA_mean);
hzpa->GetXaxis()->SetBinLabel(2,runlabel);
hzpa->GetXaxis()->SetLabelSize(0.05);

hznaUncalib->SetBinContent(2,ZNAuncalib_mean);
hznaUncalib->GetXaxis()->SetBinLabel(2,runlabel);
hznaUncalib->GetXaxis()->SetLabelSize(0.05);

hzpcUncalib->SetBinContent(2,ZPCuncalib_mean);
hzpcUncalib->GetXaxis()->SetBinLabel(2,runlabel);
hzpcUncalib->GetXaxis()->SetLabelSize(0.05);

hzncUncalib->SetBinContent(2,ZNCuncalib_mean);
hzncUncalib->GetXaxis()->SetBinLabel(2,runlabel);
hzncUncalib->GetXaxis()->SetLabelSize(0.05);

hzpaUncalib->SetBinContent(2,ZPAuncalib_mean);
hzpaUncalib->GetXaxis()->SetBinLabel(2,runlabel);
hzpaUncalib->GetXaxis()->SetLabelSize(0.05);

hzem1->SetBinContent(2,ZEM1_mean);
hzem1->GetXaxis()->SetBinLabel(2,runlabel);
hzem1->GetXaxis()->SetLabelSize(0.05);

hzem2->SetBinContent(2,ZEM2_mean);
hzem2->GetXaxis()->SetBinLabel(2,runlabel);
hzem2->GetXaxis()->SetLabelSize(0.05);

hzna_Xcentroid->SetBinContent(2,ZNA_XCent);
hzna_Xcentroid->SetBinError(2,ZNA_XCent_err);
hzna_Xcentroid->GetXaxis()->SetBinLabel(2,runlabel);
hzna_Xcentroid->GetXaxis()->SetLabelSize(0.05);
hzna_Xcentroid->GetYaxis()->SetTitle("(cm)");

hzna_Ycentroid->SetBinContent(2,ZNA_YCent);
hzna_Ycentroid->SetBinError(2,ZNA_YCent_err);
hzna_Ycentroid->GetXaxis()->SetBinLabel(2,runlabel);
hzna_Ycentroid->GetXaxis()->SetLabelSize(0.05);
hzna_Ycentroid->GetYaxis()->SetTitle("(cm)");

hznc_Xcentroid->SetBinContent(2,ZNC_XCent);
hznc_Xcentroid->SetBinError(2,ZNC_XCent_err);
hznc_Xcentroid->GetXaxis()->SetBinLabel(2,runlabel);
hznc_Xcentroid->GetXaxis()->SetLabelSize(0.05);
hznc_Xcentroid->GetYaxis()->SetTitle("(cm)");

hznc_Ycentroid->SetBinContent(2,ZNC_YCent);
hznc_Ycentroid->SetBinError(2,ZNC_YCent_err);
hznc_Ycentroid->GetXaxis()->SetBinLabel(2,runlabel);
hznc_Ycentroid->GetXaxis()->SetLabelSize(0.05);
hznc_Ycentroid->GetYaxis()->SetTitle("(cm)");

hzn_TDC_Sum->SetBinContent(2,ZN_TDC_Sum);
hzn_TDC_Sum->SetBinError(2,ZN_TDC_Sum_err);
hzn_TDC_Sum->GetXaxis()->SetBinLabel(2,runlabel);
hzn_TDC_Sum->GetXaxis()->SetLabelSize(0.05);
hzn_TDC_Sum->GetYaxis()->SetTitle("(ns)");

hzn_TDC_Diff->SetBinContent(2,ZN_TDC_Diff);
hzn_TDC_Diff->SetBinError(2,ZN_TDC_Diff_err);
hzn_TDC_Diff->GetXaxis()->SetBinLabel(2,runlabel);
hzn_TDC_Diff->GetXaxis()->SetLabelSize(0.05);
hzn_TDC_Diff->GetYaxis()->SetTitle("(ns)");

hznc_TDC->SetBinContent(2,ZNC_TDC);
//hznc_TDC->SetBinError(2,ZNC_TDC_err);
hznc_TDC->GetXaxis()->SetBinLabel(2,runlabel);
hznc_TDC->GetXaxis()->SetLabelSize(0.05);
hznc_TDC->GetYaxis()->SetTitle("(ns)");

hzna_TDC->SetBinContent(2,ZNA_TDC);
//hzna_TDC->SetBinError(2,ZNA_TDC_err);
hzna_TDC->GetXaxis()->SetBinLabel(2,runlabel);
hzna_TDC->GetXaxis()->SetLabelSize(0.05);
hzna_TDC->GetYaxis()->SetTitle("(ns)");

//----------------------------------------------------------------------
//spectra
//----------------------------------------------------------------------

TCanvas* cZNC_Spectra_Uncal = new TCanvas("cZNC_Spectra_Uncal","cZNC_Spectra_Uncal",0,0,1200,900);
if(hZNCpmcUncalib){
  gPad->SetLogy();
  hZNCpmcUncalib->Draw();
  cZNC_Spectra_Uncal->Print(Form("%s/cZNC_Spectra_Uncal.png",plotDir.Data()));
}

TCanvas* cZNA_Spectra_Uncal = new TCanvas("cZNA_Spectra_Uncal","cZNA_Spectra_Uncal",0,0,1200,900);
if(hZNApmcUncalib){
gPad->SetLogy();
hZNApmcUncalib->Draw();
cZNA_Spectra_Uncal->Print(Form("%s/cZNA_Spectra_Uncal.png",plotDir.Data()));
}

TCanvas* cZPC_Spectra_Uncal = new TCanvas("cZPC_Spectra_Uncal","cZPC_Spectra_Uncal",0,0,1200,900);
if(hZPCpmcUncalib){
gPad->SetLogy();
hZPCpmcUncalib->Draw();
cZPC_Spectra_Uncal->Print(Form("%s/cZPC_Spectra_Uncal.png",plotDir.Data()));
}

TCanvas* cZPA_Spectra_Uncal = new TCanvas("cZPA_Spectra_Uncal","cZPA_Spectra_Uncal",0,0,1200,900);
if(hZPApmcUncalib){
gPad->SetLogy();
hZPApmcUncalib->Draw();
cZPA_Spectra_Uncal->Print(Form("%s/cZPA_Spectra_Uncal.png",plotDir.Data()));
}

TCanvas* cZEM1_Spectra = new TCanvas("cZEM1_Spectra","cZEM1_Spectra",0,0,1200,900);
if(hZEM1){
gPad->SetLogy();
hZEM1->Draw();
cZEM1_Spectra->Print(Form("%s/cZEM1_Spectra.png",plotDir.Data()));
}

TCanvas* cZEM2_Spectra = new TCanvas("cZEM2_Spectra","cZEM2_Spectra",0,0,1200,900);
if(hZEM2){
gPad->SetLogy();
hZEM2->Draw();
cZEM2_Spectra->Print(Form("%s/cZEM2_Spectra.png",plotDir.Data()));
}

//---------------------------------------------------------------------------------------------------
//means
//---------------------------------------------------------------------------------------------------
TCanvas* cZNC_Mean_Values = new TCanvas("cZNC_Mean_Values","cZNC_Mean_Values", 0,0,750,900);
hznc->Draw("ep");
cZNC_Mean_Values->Print(Form("%s/cZNC_Mean_Values.png",plotDir.Data()));

TCanvas* cZNA_Mean_Values = new TCanvas("cZNA_Mean_Values","cZNA_Mean_Values", 0,0,750,900);
hzna->Draw("ep");
cZNA_Mean_Values->Print(Form("%s/cZNA_Mean_Values.png",plotDir.Data()));

TCanvas* cZPC_Mean_Values = new TCanvas("cZPC_Mean_Values","cZPC_Mean_Values", 0,0,750,900);
hzpc->Draw("ep");
cZPC_Mean_Values->Print(Form("%s/cZPC_Mean_Values.png",plotDir.Data()));

TCanvas* cZPA_Mean_Values = new TCanvas("cZPA_Mean_Values","cZPA_Mean_Values", 0,0,750,900);
hzpa->Draw("ep");
cZPA_Mean_Values->Print(Form("%s/cZPA_Mean_Values.png",plotDir.Data()));

TCanvas* cZNC_Mean_Uncalib = new TCanvas("cZNC_Mean_Uncalib","cZNC_Mean_Uncalib", 0,0,750,900);
hzncUncalib->Draw("ep");
cZNC_Mean_Uncalib->Print(Form("%s/cZNC_Mean_Uncalib.png",plotDir.Data()));

TCanvas* cZNA_Mean_Uncalib = new TCanvas("cZNA_Mean_Uncalib","cZNA_Mean_Uncalib", 0,0,750,900);
hznaUncalib->Draw("ep");
cZNA_Mean_Uncalib->Print(Form("%s/cZNA_Mean_Uncalib.png",plotDir.Data()));

TCanvas* cZPC_Mean_Uncalib = new TCanvas("cZPC_Mean_Uncalib","cZPC_Mean_Uncalib", 0,0,750,900);
hzpcUncalib->Draw("ep");
cZPC_Mean_Uncalib->Print(Form("%s/cZPC_Mean_Uncalib.png",plotDir.Data()));

TCanvas* cZPA_Mean_Uncalib = new TCanvas("cZPA_Mean_Uncalib","cZPA_Mean_Uncalib", 0,0,750,900);
hzpaUncalib->Draw("ep");
cZPA_Mean_Uncalib->Print(Form("%s/cZPA_Mean_Uncalib.png",plotDir.Data()));

TCanvas* cZEM1_Mean_Values = new TCanvas("cZEM1_Mean_Values","cZEM1_Mean_Values", 0,0,750,900);
hzem1->Draw("ep");
cZEM1_Mean_Values->Print(Form("%s/cZEM1_Mean_Values.png",plotDir.Data()));

TCanvas* cZEM2_Mean_Values = new TCanvas("cZEM2_Mean_Values","cZEM2_Mean_Values", 0,0,750,900);
hzem2->Draw("ep");
cZEM2_Mean_Values->Print(Form("%s/cZEM2_Mean_Values.png",plotDir.Data()));

//---------------------------------------------------------------------------------------------------
//centroids
//---------------------------------------------------------------------------------------------------
TCanvas* cZNA_X_centroid = new TCanvas("cZNA_X_centroid","cZNA_X_centroid", 0,0,750,900);
hzna_Xcentroid->Draw();
cZNA_X_centroid->Print(Form("%s/cZNA_X_centroid.png",plotDir.Data()));

TCanvas* cZNA_Y_centroid = new TCanvas("cZNA_Y_centroid","cZNA_Y_centroid", 0,0,750,900);
hzna_Ycentroid->Draw();
cZNA_Y_centroid->Print(Form("%s/cZNA_Y_centroid.png",plotDir.Data()));

TCanvas* cZNC_X_centroid = new TCanvas("cZNC_X_centroid","cZNC_X_centroid", 0,0,750,900);
hznc_Xcentroid->Draw();
cZNC_X_centroid->Print(Form("%s/cZNC_X_centroid.png",plotDir.Data()));

TCanvas* cZNC_Y_centroid = new TCanvas("cZNC_Y_centroid","cZNC_Y_centroid", 0,0,750,900);
hznc_Ycentroid->Draw();
cZNC_Y_centroid->Print(Form("%s/cZNC_Y_centroid.png",plotDir.Data()));

//---------------------------------------------------------------------------------
//timing
//---------------------------------------------------------------------------------
TCanvas* cTimingSum = new TCanvas("cTimingSum","cTimingSum",0,0,750,900);
hzn_TDC_Sum->Draw();
cTimingSum->Print(Form("%s/cTimingSum.png",plotDir.Data()));

TCanvas* cTimingDiff = new TCanvas("cTimingDiff","cTimingDiff",0,0,750,900);
hzn_TDC_Diff->Draw();
cTimingDiff->Print(Form("%s/cTimingDiff.png",plotDir.Data()));

//----------------------------------------------------------------------
//out
//----------------------------------------------------------------------
printf(" preparing output tree\n");
tree->Branch("run",&runNumber,"runNumber/I");
tree->Branch("ZNC_mean_value",&ZNC_mean,"ZNC_mean/D");
tree->Branch("ZNA_mean_value",&ZNA_mean,"ZNA_mean/D");
tree->Branch("ZPC_mean_value",&ZPC_mean,"ZPC_mean/D");
tree->Branch("ZPA_mean_value",&ZPA_mean,"ZPA_mean/D");
tree->Branch("ZNC_mean_uncalib",&ZNCuncalib_mean,"ZNCuncalib_mean/D");
tree->Branch("ZNA_mean_uncalib",&ZNAuncalib_mean,"ZNAuncalib_mean/D");
tree->Branch("ZPC_mean_uncalib",&ZPCuncalib_mean,"ZPCuncalib_mean/D");
tree->Branch("ZPA_mean_uncalib",&ZPAuncalib_mean,"ZPAuncalib_mean/D");
tree->Branch("ZEM1_mean_value",&ZEM1_mean,"ZEM1_mean/D");
tree->Branch("ZEM2_mean_value",&ZEM2_mean,"ZEM2_mean/D");
tree->Branch("ZNC_X_Centroid",&ZNC_XCent,"ZNC_XCent/D");
tree->Branch("ZNC_Y_Centroid",&ZNC_YCent,"ZNC_YCent/D");
tree->Branch("ZNA_X_Centroid",&ZNA_XCent,"ZNA_XCent/D");
tree->Branch("ZNA_Y_Centroid",&ZNA_YCent,"ZNA_YCent/D");
tree->Branch("ZNC_X_Centroid_Err",&ZNC_XCent_err,"ZNC_XCent_err/D");
tree->Branch("ZNC_Y_Centroid_Err",&ZNC_YCent_err,"ZNC_YCent_err/D");
tree->Branch("ZNA_X_Centroid_Err",&ZNA_XCent_err,"ZNA_XCent_err/D");
tree->Branch("ZNA_Y_Centroid_Err",&ZNA_YCent_err,"ZNA_YCent_err/D");
tree->Branch("ZN_TDC_Sum",&ZN_TDC_Sum,"ZN_TDC_Sum/D");
tree->Branch("ZN_TDC_Diff",&ZN_TDC_Diff,"ZN_TDC_Diff/D");
tree->Branch("ZN_TDC_Sum_Err",&ZN_TDC_Sum_err,"ZN_TDC_Sum_err/D");
tree->Branch("ZN_TDC_Diff_Err",&ZN_TDC_Diff_err,"ZN_TDC_Diff_err/D");
tree->Fill();

if(hZNCpmcUncalib) list.Add(cZNC_Spectra_Uncal);
if(hZNApmcUncalib) list.Add(cZNA_Spectra_Uncal);
if(hZPCpmcUncalib) list.Add(cZPC_Spectra_Uncal);
if(hZPApmcUncalib) list.Add(cZPA_Spectra_Uncal);
list.Add(cZEM1_Spectra);
list.Add(cZEM2_Spectra);
list.Add(cTimingSum);
list.Add(cTimingDiff);
list.Add(cZNA_X_centroid);
list.Add(cZNA_Y_centroid);
list.Add(cZNC_X_centroid);
list.Add(cZNC_Y_centroid);

TFile *fout;
fout = TFile::Open("prodQAhistos.root", "update");
if(!fout) fout = new TFile("prodQAhistos.root");
fout->cd();
list.Write();
tree->Write();
fout->Close();

return 0;

}
Exemple #19
0
MakeAICFits::MakeAICFits() {
  //RooRandom::randomGenerator()->SetSeed(314159);
  // Create Toy Data Set
  // Single Exponential
  RooRealVar *mass   = new RooRealVar("mass","mass", 50., 35., 65.); 
  //RooRealVar *alpha1 = new RooRealVar("Exp_alpha","Exp_alpha",-0.1,-1.,0.);                     
  //alpha1->setVal(-0.1);
  RooRealVar *alpha1 = new RooRealVar("Exp_alpha","Exp_alpha", -0.1);
  RooExponential expon("exp","Background Exponential",*mass,*alpha1);             
  // KPower 
  //RooRealVar *alpha2 = new RooRealVar("Power_alpha","Power_alpha",-3.,-10.,0.);                             
  //alpha2->setVal(-3.);
  RooRealVar *alpha2 = new RooRealVar("Power_alpha", "Power_alpha", -3);
  RooGenericPdf bkg("pow","Background Power","@0^@1",RooArgList(*mass,*alpha2));           
  //RooRealVar ratio("ratio","Background Ratio", 0.5, 0., 1.);
  //ratio.setVal(0.5);
  RooRealVar ratio("ratio", "Background Ratio", 0.5);


  //Create Background pdf
  //  RooAddPdf bkg("bkg","bkg",RooArgList(pow,expon),ratio);

  std::cout<<"==========  Data Model Made  ==========="<<std::endl;

  const Int_t nToys = 1;
  //ratio.setVal(0);
  RooDataSet* data = bkg.generate(RooArgSet(*mass), 1000000);
  //ratio.setVal(0.20);


  std::cout<<"==========  Data Set Made    ==========="<<std::endl;
  
  // Make plain projection of data and pdf on mass
  //bkg.fitTo(*data);
  
  RooFitResult* bkg_data = bkg.fitTo(*data, RooFit::Save(kTRUE), RooFit::Optimize(0));
  Double_t bkg_data_Nll = bkg_data->minNll();
  std::cout<<" ======== Data fitted ==========="<<std::endl;
  RooArgSet* bkgParams = bkg.getParameters(*data);
  const RooArgList& fitbkgParams = bkg_data->floatParsFinal();
  std::cout<< "=======================  parameters done  ========================"<<std::endl;   

  Double_t LogLikelihood[8] = {0,0,0,0,0,0,0,0};
  Double_t AIC_bkg_array[8] = {0,0,0,0,0,0,0,0};
  Double_t AICc_bkg_array[8] = {0,0,0,0,0,0,0,0};
  //Double_t BIC_bkg_array[7] = {0,0,0,0,0,0,0};
  
  Double_t LogLikelihood_data = bkg_data_Nll;
  Int_t avgcov[8] = {0,0,0,0,0,0,0};
  std::cout<<"======================   Starting Toys  ==============="<<std::endl;
  for (Int_t i=0; i<nToys; i++) {
    if (i%10==0) {
      std::cout<<">> Processing Toy Trial " << i << "/" << nToys << std::endl;
    }

    RooPlot* frame = mass->frame();
    leg = new TLegend(0.55,0.55,0.9,0.9);
    mass->setConstant(kFALSE);
    alpha1->setConstant(kFALSE);
    alpha2->setConstant(kFALSE);
    ratio.setConstant(kFALSE);
    const RooArgList ranbkgParams = bkg_data->randomizePars();
    *bkgParams = ranbkgParams;
    
    Int_t SampleSize = 100000;
    RooDataSet* toybkg = bkg.generate(RooArgSet(*mass),SampleSize);
    toybkg->plotOn(frame);
    leg->AddEntry(toybkg,"Toy Background", "lep");
    *bkgParams = fitbkgParams;
    mass->setConstant(kTRUE);
    alpha1->setConstant(kTRUE);
    alpha2->setConstant(kTRUE);
    ratio.setConstant(kTRUE);
    for (int type=0; type<7; type++) {
      std::cout<<type<<endl;
    }
    int display = 8;
    for (int type=0; type<display; type++) {
      if (type<7) {
	//std::cout<<"Model Shape:    "<<type<<std::endl;
	RooAbsPdf* ModelShape = MakeAICFits::getBackgroundPdf(type,mass);
	//std::cout<<"Model Shape made"<<std::endl;
	int k = MakeAICFits::Num_Params(type);
	//std::cout<<"Params counted"<<std::endl;
      }
      if (type==7) {
	RooAbsPdf* Model1 = MakeAICFits::getBackgroundPdf(5,mass);
	RooAbsPdf* Model2 = MakeAICFits::getBackgroundPdf(6,mass);
	RooAbsPdf* Model3 = MakeAICFits::getBackgroundPdf(2,mass);
	RooAbsPdf* Model4 = MakeAICFits::getBackgroundPdf(3,mass);
	RooAbsPdf* Model5 = MakeAICFits::getBackgroundPdf(4,mass);
	int k = MakeAICFits::Num_Params(5);
	k+= MakeAICFits::Num_Params(6);
	//k+= MakeAICFits::Num_Params(0);
	//k+= MakeAICFits::Num_Params(3);
	//k+= MakeAICFits::Num_Params(4);
	RooRealVar* modratio1 = new RooRealVar("modrat1", "modrat1", 0.82, 0.81, 0.83);
	RooRealVar* modratio2 = new RooRealVar("modrat2", "modrat2", 0.17, 0.25, 0.35);
	RooRealVar* modratio3 = new RooRealVar("modrat3", "modrat3", 0.01);
	//RooRealVar* modratio4 = new RooRealVar("modrat4", "modrat4", 0.25);
	RooAbsPdf* ModelShape = new RooAddPdf("Composite", "Background Model", RooArgList(*Model1, *Model2), RooArgList(*modratio1));
	//RooAbsPdf* ModelShape = new RooAddPdf("Composite", "Background Model", RooArgList(*Model1, *Model4), *modratio1);
      }
      assert(ModelShape!=0);
      RooRealVar *Nbkg = new RooRealVar("Nbkg","N Background Events", SampleSize,0,1e9);
      RooExtendPdf *BkgModel = new RooExtendPdf("BKGFIT_bkgModel", "Background Model", *ModelShape, *Nbkg);
      TH1F* Model = new TH1F("Model", "Model", 100,0,100);
      //BkgModel->fitTo(*toybkg, RooFit::Strategy(0), RooFit::NumCPU(NUM_CPU), RooFit::Minos(kFALSE), RooFit::Extended(kTRUE));
      //RooFitResult *bkg_toybkg = BkgModel->fitTo(*toybkg,RooFit::Save(kTRUE), RooFit::Strategy(2), RooFit::NumCPU(NUM_CPU), RooFit::Minos(kFALSE), RooFit::Extended(kTRUE));
      RooFitResult *bkg_toybkg = BkgModel->fitTo(*toybkg, RooFit::Save(kTRUE), RooFit::Optimize(0));
      if (type == 0) {
	BkgModel->plotOn(frame, RooFit::LineColor(kBlue));
	Model->RooFit::SetLineColor(kBlue);
	leg->AddEntry(Model, "Exponential Model", "l");
      }
      if (type == 4) { 
	BkgModel->plotOn(frame, RooFit::LineColor(kRed));
	Model->RooFit::SetLineColor(kRed);
	leg->AddEntry(Model, "Polynomial Model", "l");
      }
      if (type == 5) { 
	BkgModel->plotOn(frame, RooFit::LineColor(kGreen));
	Model->RooFit::SetLineColor("kGreen");
	leg->AddEntry(Model, "Power Model", "l");
      }
      if (type == 7) {
	BkgModel->plotOn(frame, RooFit::LineColor(kMagenta));
	Model->RooFit::SetLineColor("kMagenta");
	leg->AddEntry(Model, "Composite Model", "l");
      }
      Double_t bkg_toybkg_Nll = bkg_toybkg->minNll();
      Int_t covariance = bkg_toybkg->covQual();
      avgcov[type] += covariance;
      //assert (covariance == 3);
      // Calculate AIC for each model
      LogLikelihood[type] += -bkg_toybkg_Nll;
      AICc_bkg_array[type] += 2.*(k + k*(k + 1.)/(SampleSize - (k + 1.)) + bkg_toybkg_Nll);
      //BIC_bkg_array[type]  += 2.*(k*log(SampleSize)/2. + bkg_toybkg_Nll);
      AIC_bkg_array[type] += 2.*(k + bkg_toybkg_Nll);
      // Clean up objects
      delete bkg_toybkg;
      bkg_toybkg_Nll = 0.;
    }
    delete toybkg;
    TCanvas *c = new TCanvas("", "", 800, 600);
    frame->Draw();
    leg->Draw();
    c->Update();
    c->Print("pow_plot_combined.pdf");
  }
  
  std::cout<<"Printing AIC Values" << std::endl;
  std::cout<<"Log Likelihood Data :    " << LogLikelihood_data <<std::endl;
  for (int type = 0; type<display; type++) {
    avgcov[type] = avgcov[type]/nToys;
    LogLikelihood[type] = LogLikelihood[type]/nToys;
    AIC_bkg_array[type] = AIC_bkg_array[type]/nToys;
    AICc_bkg_array[type] = AICc_bkg_array[type]/nToys;
    //BIC_bkg_array[type] = BIC_bkg_array[type]/nToys;
    std::cout<<"average covariance quality" << type <<" ===" << avgcov[type] <<std::endl;
    std::cout<<"Log Likelihood for Model " << type << " ==== " << LogLikelihood[type] <<std::endl;
    std::cout<<"AICc Value for Model: " << type << " ==== " << AICc_bkg_array[type] <<std::endl;
    std::cout<<"AIC Value for Model: " << type << " ==== " << AIC_bkg_array[type]  << std::endl;
    //std::cout<<"BIC Value for Model: " << type << " ==== " << BIC_bkg_array[type] <<std::endl;
  }
  double minAIC = 10000000000.;
  //double minBIC = 10000000000.;
  for (int type = 0; type<display; type++) {
    if (AICc_bkg_array[type] < minAIC) {
      minAIC = AICc_bkg_array[type];
    }
    //if (BIC_bkg_array[type] < minBIC) {
    //  minBIC = BIC_bkg_array[type];
    //}
  }
  std::cout<<"Minimum AIC: " << minAIC << std::endl;
  double DeltaIA[8];
  //double DeltaIB[7];
  double sumExpA=0;
  //double sumExpB=0;
  int bestmodelA;
  //int bestmodelB;
  for (int type = 0; type<display; type++) {
    DeltaIA[type] = AICc_bkg_array[type] - minAIC;
    //DeltaIB[type] = BIC_bkg_array[type] - minBIC;
    if (DeltaIA[type] == 0) {
      bestmodelA = type;
    }
    //if (DeltaIB[type] == 0) {
    //  bestmodelB = type;
    //}
    std::cout<<"Delta AIC values : " << type << " ====" << DeltaIA[type] <<std::endl;
    //std::cout<<"Delta BIC values : " << type << " ====" << DeltaIB[type] <<std::endl;
    sumExpA+= exp(-DeltaIA[type]/2);
    //sumExpB+= exp(-DeltaIB[type]/2);
  }
  double AICweights[8];
  //double BICweights[7];
  for (int type = 0; type<display; type++) {
    AICweights[type] = exp(-DeltaIA[type]/2)/sumExpA;
    //BICweights[type] = exp(-DeltaIB[type]/2)/sumExpB;
    std::cout<<"Relative Likelihood AIC " << type << " ==== " <<exp(-DeltaIA[type]/2)<<std::endl;
    std::cout<<"AIC Weights  : " << type << " =====" << AICweights[type] <<std::endl;
    //std::cout<<"Relative Likelihood BIC " << type << " ==== " <<exp(-DeltaIB[type]/2)<<std::endl;
    //std::cout<<"BIC Weights  : " << type << " =====" << BICweights[type] <<std::endl;
  }
  for (int type2 = 0; type2<display; type2++) {
    std::cout<< "AIC Ratio for:  " << "Model " << bestmodelA << " / " << "Model " << type2 << "  =  " << AICweights[bestmodelA]/AICweights[type2] <<std::endl;
    //std::cout<< "BIC Ratio for:  " << "Model " << bestmodelB << " / " << "Model " << type2 << "  =  " << BICweights[bestmodelB]/BICweights[type2] <<std::endl;
  }
}
void drawtorroidmollers_rings_compare(TString infilename1="0", TString infilename2="0", 
									  TString outfilenamestem="0", TString usercut="1")
{
	if (infilename1=="0" || infilename2=="0" || outfilenamestem=="0") {
		printf("Usage:\n\t.x drawtorroidmollers_rings_stamps.C(infilename1, infilename2, outfilename, [cut])\n\n");
		printf("Where infilenames is a .root file \n");
		printf("      outfilenamestem is the base name of an image file, and\n");
		printf("      cut is a cut string applied to the tree.\n");
		return;
	}  

	gROOT->Reset();
	Bool_t debug=1;
	Double_t deltaZwindowsize=25; //in mm

	const Int_t totplots=4;
	Double_t distance[totplots]={14500,20000,24000,28250};

// 	const Int_t totplots=1;
// 	Double_t distance[totplots]={28479};

	char pstitle[200];

	printf("Using data files %s\n             and %s \n\n",infilename1.Data(), infilename2.Data());
	gROOT->SetStyle("Plain");
	gStyle->SetPalette(1);
	gStyle->SetOptStat(kFALSE);
	TFile *file1 = TFile::Open(infilename1.Data());
	TTree *tree1 = (TTree*)file1->Get("geant");
	TFile *file2 = TFile::Open(infilename2.Data());
	TTree *tree2 = (TTree*)file2->Get("geant");
	TH2F* file1histos[totplots];
	TH2F* file2histos[totplots];

	Int_t Palette1[100],Palette2[100];
	UInt_t Number = 2;
	Int_t nb=20;

	Double_t Red[]    = { 1.00, 1.00};
	Double_t Green[]  = { 0.00, 0.00};
	Double_t Blue[]   = { 1.00, 0.00};
	Double_t Length[] = { 0.00, 1.00};
	Int_t FI = TColor::CreateGradientColorTable(Number,Length,Red,Green,Blue,nb);
	for (int i=0;i<nb;i++) Palette1[i] = FI+i;
	
	Double_t Red[]    = { 0.00, 0.00};
	Double_t Green[]  = { 1.00, 0.00};
	Double_t Blue[]   = { 1.00, 1.00};
	TColor::CreateGradientColorTable(Number,Length,Red,Green,Blue,nb);
	Int_t FI = TColor::CreateGradientColorTable(Number,Length,Red,Green,Blue,nb);
	for (int i=0;i<nb;i++) Palette2[i] = FI+i;
	
	TCanvas *canvas = new TCanvas("canvas","Moller plots",800,800);
	char title[100];
	char weight[200];
	TGraph* scat[totplots];
	TLine line;
	TArc arc;
	arc.SetFillStyle(4000);
	arc.SetNoEdges(kFALSE);
	Double_t pi=3.14159265358979323846;
	Double_t ymin, ymax, xmin, xmax;

	tree1->SetMarkerStyle(20);
	tree1->SetMarkerSize(0.15);
	tree2->SetMarkerStyle(20);
	tree2->SetMarkerSize(0.15);
	for (int i=0; i<totplots; i++) {
		char drawstring[400];
		gStyle->SetPalette(nb, Palette1);
		sprintf(drawstring,"y/1000:x/1000:1000*acos(pz2/sqrt(px2*px2+py2*py2+pz2*pz2))>>file1hist%i",i);
//		sprintf(drawstring,"y/1000:x/1000:5>>file1hist%i",i);
		sprintf(weight,"(z>(%.0f)&&z<(%.0f)&&type==0)&&(%s)",distance[i]-deltaZwindowsize,distance[i]+deltaZwindowsize,usercut.Data());
		if (debug) printf("%s\n%s\n",drawstring,weight);
		Int_t num1 = tree2->Draw(drawstring,weight,"col");
		file1histos[i]=(TH2F*)gPad->GetPrimitive(Form("file1hist%i",i));

		gStyle->SetPalette(nb, Palette2);
		sprintf(drawstring,"y/1000:x/1000:1000*acos(pz2/sqrt(px2*px2+py2*py2+pz2*pz2))>>file2hist%i",i);
//		sprintf(drawstring,"y/1000:x/1000:3>>file2hist%i",i);
		if (debug) printf("%s\n%s\n",drawstring,weight);
		Int_t num2 = tree1->Draw(drawstring,weight,"col");
		file2histos[i]=(TH2F*)gPad->GetPrimitive(Form("file2hist%i",i));

		if (num1<=0 || num2<=0) {
			printf("%i and %i successful events\n",num1,num2);
			printf("\n%.0f doesn't seem to be a good choice!\n\n",distance[i]);
		} else {
			if (debug) printf("%i and %i successful events\n",num1,num2);
			gPad->SetRightMargin(0.1);
			gPad->SetLeftMargin(0.1);
			gPad->SetTopMargin(0.1);
			gPad->SetBottomMargin(0.1);
			canvas->Update();
			ymin=gPad->GetUymin();
			ymax=gPad->GetUymax();
			xmin=gPad->GetUxmin();
			xmax=gPad->GetUxmax();
			printf("xmin %f, xmax %f, ymin %f, ymax %f, deltax %f, deltay %f\n",xmin,xmax,ymin,ymax,xmax-xmin,ymax-ymin);
// 			if (xmin>0) {
// // 				file1histos[i]->SetAxisRange(0,xmax,"X");
// // 				file2histos[i]->SetAxisRange(0,xmax,"X");
// 				file1histos[i]->GetXaxis()->SetRangeUser(0,xmax);
// 				file2histos[i]->GetXaxis()->SetRangeUser(0,xmax);
// 			}
			sprintf(title,"z=%.2f m;x  (m);y   (m)", distance[i]/1000.);
			file1histos[i]->SetTitle(title);
			file2histos[i]->SetTitle(title);
			canvas->Clear();
			file1histos[i]->Draw("colz");
// 			if (xmin>0) //file1histos[i]->GetXaxis()->SetRangeUser(0,xmax);
// 				gPad->SetUxmin(0);//file1histos[i]->SetAxisRange(0,xmax,"X");
			canvas->Update();
			canvas->Print(Form("%s_%.2fm_1.png",outfilenamestem.Data(),distance[i]/1000.));
			file2histos[i]->Draw("col,same");
			canvas->Update();
			canvas->Print(Form("%s_%.2fm.png",outfilenamestem.Data(),distance[i]/1000.));
			canvas->Clear();
			file2histos[i]->Draw("colz");
// 			if (xmin>0) //file2histos[i]->GetXaxis()->SetRangeUser(0,xmax);
// 				gPad->SetUxmin(0);//file1histos[i]->SetAxisRange(0,xmax,"X");
			canvas->Update();
			canvas->Print(Form("%s_%.2fm_2.png",outfilenamestem.Data(),distance[i]/1000.));
		}
	}	
}
void combine_mistag_rates_2d( )
{

  const char * names [] = {
    "mistag_parameterization_qcd_230.root", 
    "mistag_parameterization_qcd_300.root", 
    "mistag_parameterization_qcd_380.root", 
    "mistag_parameterization_qcd_470.root", 
    "mistag_parameterization_qcd_600.root", 
    "mistag_parameterization_qcd_800.root", 
    "mistag_parameterization_qcd_1000.root", 
    "mistag_parameterization_qcd_1400.root", 
    "mistag_parameterization_qcd_1800.root", 
    "mistag_parameterization_qcd_2200.root", 
    "mistag_parameterization_qcd_2600.root", 
    "mistag_parameterization_qcd_3000.root", 
    "mistag_parameterization_qcd_3500.root"
  };


  double xs[] = {
    10623.2,
    2634.94,
    722.099,
    240.983,
    62.4923,
    9.42062,
    2.34357,
    0.1568550,
    0.013811,
    0.00129608,
    0.00011404,
    0.0000084318,
    0.00000018146
  };


  int nevents[] = {
    54000,
    54000,
    51840,
    27648,
    28620,
    20880,
    24640,
    27744,
    22848,
    22560,
    22800,
    20880,
    34320
  };


  const char * filetitles[] = {
    "QCD Dijets, #hat{pt} = 230-300",
    "QCD Dijets, #hat{pt} = 300-380",
    "QCD Dijets, #hat{pt} = 380-470",
    "QCD Dijets, #hat{pt} = 470-600",
    "QCD Dijets, #hat{pt} = 600-800",
    "QCD Dijets, #hat{pt} = 800-1000",
    "QCD Dijets, #hat{pt} = 1000-1400",
    "QCD Dijets, #hat{pt} = 1400-1800",
    "QCD Dijets, #hat{pt} = 1800-2200",
    "QCD Dijets, #hat{pt} = 2200-2600",
    "QCD Dijets, #hat{pt} = 2600-3000",
    "QCD Dijets, #hat{pt} = 3000-3500",
    "QCD Dijets, #hat{pt} = 3500-Inf"
  };


  static const int N = sizeof( names ) / sizeof ( const char * );

//   palette(N);

  TFile * output = new TFile("mistag_parameterization2d.root", "RECREATE");
  TH2D * numerator_sum = 0;
  TH2D * denominator_sum = 0;

  for ( int i = 0; i < N; ++i ) {
    TFile * f = new TFile(names[i]);
    TH2D * numerator = (TH2D*) f->Get("numerator2d");
    TH2D * denominator = (TH2D*) f->Get("denominator2d");

    char buff[1000];
    sprintf(buff, "%30s & %6.0f & %6.0f ", names[i], denominator->GetEntries(), numerator->GetEntries() );
    cout << buff << endl;

    if ( i == 0 ) {
      output->cd();
      numerator_sum = new TH2D(*numerator);
      denominator_sum = new TH2D(*denominator);
    } else {
      numerator_sum->Add( numerator );
      denominator_sum->Add( denominator );
    }
  }




  TH2D * mistag_rate = new TH2D(*numerator_sum);
  mistag_rate->SetName("mistag_rate");
  mistag_rate->SetTitle("Fake Tag Parameterization");
  
  mistag_rate->Divide( numerator_sum, denominator_sum, 1.0, 1.0, "b");

  gStyle->SetOptStat(000000);

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


  c->Divide(1,3);
  c->cd(1);
  numerator_sum->SetMinimum(1e-15);
  numerator_sum->Draw("colz");
  gPad->SetLogz();
  gPad->SetRightMargin(0.2);
  c->cd(2);
  denominator_sum->SetMinimum(1e-15);
  denominator_sum->Draw("colz");
  gPad->SetLogz();
  gPad->SetRightMargin(0.2);
  c->cd(3);
  mistag_rate->Draw("colz");
  gPad->SetRightMargin(0.2);
  

  output->cd();
  numerator_sum->Write();
  denominator_sum->Write();
  mistag_rate->Write();

  c->Print("mistag_param2d.gif", "gif");
  c->Print("mistag_param2d.eps", "eps");

}
Exemple #22
0
void fitTT_experf(){

    gSystem->Load("libRooFit");
    using namespace RooFit;
    gROOT->ProcessLine(".L ./PDFs/HWWLVJRooPdfs_cxx.so");

    //TFile * file = new TFile("TTBarDataSet/el_PKUTree_pdata.root");
    TFile * file = new TFile("TTBarDataSet/el_out_TTJets_MSDecaysCKM_central_Tune4C_13TeV-madgraph-tauola.root");
    TTree * t = (TTree *)file->Get("PKUTree");

    float jet_tau2tau1,  jet_mass_softdrop;
    double massVhad;
    double isMatch;

    t->SetBranchAddress("massVhad", &massVhad);
    t->SetBranchAddress("jet_mass_softdrop", & jet_mass_softdrop);
    t->SetBranchAddress("jet_tau2tau1", &jet_tau2tau1);
    t->SetBranchAddress("isMatch", &isMatch);

    RooRealVar x("massVhad","massVhad", 40, 130);
    RooRealVar c_ErfExp("c_ErfExp", "c_ErfExp", -0.1, -10., 0.);
    RooRealVar off_ErfExp("off_ErfExp", "off_ErfExp", 50., 10., 100.);
    RooRealVar sigma_ErfExp("sigma_ErfExp", "sigma_ErfExp", 10., 0., 100.);
    RooErfExpPdf erfExp("erfExp", "erfExp", x, c_ErfExp, off_ErfExp, sigma_ErfExp);
     
    RooRealVar mean1("mean1", "mean1", 75, 60, 90);
    RooRealVar sigma1("sigma1", "sigma1", 16., 1., 40);
    RooGaussian gaus("gaus", "gaus", x, mean1, sigma1);

    RooRealVar  f("f", "f", 0.5, 0., 1.);
    //RooAddPdf model("model", "model", RooArgList(erfExp, gaus), f);
    RooAddPdf model("model", "model", RooArgList(erfExp, gaus), f);

    //RooDataSet data("data", "data", t, x);
    RooDataSet data("data", "data",  x);
    for(Int_t i=0; i< t->GetEntries(); i++){
	t->GetEntry(i);
	//if( jet_tau2tau1>0.5 && isMatch>0){
	//if(isMatch>0 && jet_tau2tau1<0.5){
	//if(isMatch>0 && jet_tau2tau1>0.5){
	//if(isMatch<0 && jet_tau2tau1<0.5){
	if(isMatch<0 && jet_tau2tau1>0.5){
	    x = massVhad;
            data.add(x);
	}
    }

//    model.fitTo(data);
    model.fitTo(data);

    RooPlot * frame = x.frame();
    data.plotOn(frame);
    model.plotOn(frame);
    model.plotOn(frame, Components(erfExp), LineStyle(kDashed), LineColor(kRed));
    model.plotOn(frame, Components(gaus), LineStyle(kDashed), LineColor(kBlue));

    TCanvas * c = new TCanvas("c","c");
    frame->Draw();
    //c->Print("TT_pass_nomatch.png");
    c->Print("TT_fail_nomatch.png");
}
Exemple #23
0
/// plots the beam profiles in (x1,x2) and (x,x') planes
void display_beamprofile(float s, string filename="data/LHCB1IR5_v6.500.tfs", char * ipname = "IP5", int side = 1, char * title ="", unsigned int NParticle=1000, const int crang_sign=-1, const bool save=false, char * outfilename="") {
	/// @param s : distance from IP [m]
	/// @param filename : optics source file
	/// @param ipname : string identifier for the IP position
	/// @param side : direction of propagation (forward 1, backward -1)
	/// @param title : for the graph
	/// @param NParticle : beam content
	/// @param crang_sign : direction for the (half) crossing angle at IP
	/// @param save : boolean
	/// @param outfilename: file to be written


// note : beam 1 forward  : side = 1  crang_sign =-1
// note : beam 1 backward : side = -1 crang_sign = 1
// note : beam 2 forward  : side = -1 crang_sign =-1
// note : beam 2 backward : side = 1  crang_sign = 1

	extern bool relative_energy;
	relative_energy = false;
	if(relative_energy) {
		cout << "You should be in absolute energy" << endl;
		return;
	}

        extern int kickers_on;
        kickers_on = 1;

	
	int max = (crang_sign>0)?100:-95;
	int min = (crang_sign<0)?-100:95;
	TH2F * hp  = new TH2F("Positions","",100,min,max,100,-2.5,2.5);
	TH2F * ha  = new TH2F("Angles","",100,-50,50,100,-50,50);
	TH2F * hax  = new TH2F("Phase_x","",100,min,max,100,-50,50);
	TH2F * hay  = new TH2F("Phase_y","",100,-2.5,2.5,100,-50,50);
	float draftx[NParticle], drafty[NParticle], drafttx[NParticle], draftty[NParticle];
//	float rmsx=0, rmsy=0, angle=0;
	TMultiGraph * profile = new TMultiGraph("prof","");

        H_BeamLine* beamline = new H_BeamLine(side,s+0.1);
        beamline->fill(filename,-1*side*crang_sign,ipname);
	beamline->offsetElements(120,0.097*crang_sign);

//	extern int kickers_on;
//	kickers_on = 1;

	for (unsigned int i=0; i<NParticle ; i++) {
		H_BeamParticle p1;
		p1.smearPos();
		p1.smearAng();
		p1.setPosition(p1.getX()-500.,p1.getY(),p1.getTX()+crang_sign*CRANG,p1.getTY(),0);
		p1.computePath(beamline);
		p1.propagate(beamline);
		p1.propagate(s);
		hp->Fill(p1.getX()/1000.,p1.getY()/1000.);
		ha->Fill(p1.getTX(),p1.getTY());
		hax->Fill(p1.getX()/1000.,p1.getTX());
		hay->Fill(p1.getY()/1000.,p1.getTY());
		draftx[i]=p1.getX()/1000.;
		drafty[i]=p1.getY()/1000.;
		drafttx[i]=p1.getTX();
		draftty[i]=p1.getTY();
		TGraph * path = p1.getPath(0,1);
		profile->Add(path);
	}

	TCanvas * can = new TCanvas;
	can->cd();
	hp->SetTitle(title);
	hp->Draw();	
	hp->GetXaxis()->SetTitle("x (mm)");
	hp->GetYaxis()->SetTitleOffset(1.2);
	hp->GetYaxis()->SetTitle("y (mm)");
	TEllipse * ellipse = new TEllipse(hp->GetMean(1),hp->GetMean(2),3*(hp->GetRMS(1)),3*(hp->GetRMS(2)));
	cout << "mean = " << hp->GetMean(1) << " " << hp->GetMean(2) << endl;
	ellipse->SetLineColor(kRed);
	ellipse->Draw();
	
	TCanvas * ca2 = new TCanvas;
	ca2->cd();
	profile->Draw("ACP");

	TCanvas *ca3 = new TCanvas;
	ca3->cd();
	ha->SetTitle(title);
	ha->Draw();
	ha->GetXaxis()->SetTitle("#theta_{x} (#murad)");
	ha->GetYaxis()->SetTitle("#theta_{y} (#murad)");
	TEllipse * ellips2 = new TEllipse(ha->GetMean(1),ha->GetMean(2),3*(ha->GetRMS(1)),3*(ha->GetRMS(2)));
	ellips2->SetLineColor(kRed);
	ellips2->Draw();

	TCanvas *ca4 = new TCanvas;
	ca4->cd();
	hax->SetTitle(title);
	hax->Draw();
	hax->SetStats(0);
	hax->GetXaxis()->SetTitle("x (mm)");
	hax->GetYaxis()->SetTitle("#theta_{x} (#murad)");
//	getEllipseParameters(draftx,drafttx,NParticle,rmsx,rmsy,angle);
//	ca4->cd();
//	cout << rmsx << " " << rmsy << " " << angle << endl;
//	TEllipse * ellips3 = new TEllipse(hp->GetMean(1),ha->GetMean(1),3*rmsx,3*rmsy);
//	ellips3->SetTheta(angle);
//	ellips3->SetLineColor(kRed);
//	ellips3->Draw();

	TCanvas *ca5 = new TCanvas;
	ca5->cd();
	hay->SetTitle(title);
	hay->Draw();
	hay->SetStats(0);
	hay->GetXaxis()->SetTitle("y (mm)");
	hay->GetYaxis()->SetTitle("#theta_{y} (#murad)");
//	getEllipseParameters(drafty,draftty,NParticle,rmsx,rmsy,angle);
//	ca5->cd();
//	cout << rmsx << " " << rmsy << " " << angle << endl;
//	TEllipse * ellips4 = new TEllipse(hp->GetMean(2),ha->GetMean(2),3*rmsx,3*rmsy);
//	ellips4->SetTheta(angle);
//	ellips4->SetLineColor(kRed);
//	ellips4->Draw();

	if(save) {
		char filetitle_pos[50], filetitle_ang[50], filetitle_phasex[50], filetitle_phasey[50];
		sprintf(filetitle_pos,"%s_pos.eps",outfilename);
		cout << filetitle_pos << endl;
		can->Print(filetitle_pos,"eps");
		sprintf(filetitle_ang,"%s_ang.eps",outfilename);
		cout << filetitle_ang << endl;
		ca3->Print(filetitle_ang,"eps");
		sprintf(filetitle_phasex,"%s_px.eps",outfilename);
		cout << filetitle_phasex << endl;
		ca4->Print(filetitle_phasex,"eps");
		sprintf(filetitle_phasey,"%s_py.eps",outfilename);
		cout << filetitle_phasey << endl;
		ca5->Print(filetitle_phasey,"eps");
		delete can;
		delete ca2;
		delete ca3;
		delete ca4;
		delete ca5;
		delete hp;
		delete ha;
		delete hax;
		delete hay;
		delete profile;
		delete beamline;
		delete ellipse;
		delete ellips2;
//		delete ellips3;
//		delete ellips4;
	}

}
void triggerEfficiency()
{
  //=== General CMS Style ===

  gROOT->ForceStyle();

  //gROOT->LoadMacro("tdrstyle.C");
  setTDRStyle();

  //gROOT->LoadMacro("CMS_lumi.C");
  extraText  = "Preliminary";  // default extra text is "Preliminary"
  writeExtraText = true;       // remove or keep "Preliminary"

  lumi_13TeV  = "2015";  // for trigger
  //lumi_13TeV  = "65 pb^{-1}, 50ns";  // for trigger
  //lumi_13TeV  = "15.5 pb^{-1}, 25ns";  // for trigger

  //lumi_13TeV  = "65 pb^{-1}";  // default is ""
  //lumi_8TeV  = "19.1 fb^{-1}"; // default is "19.7 fb^{-1}"
  //lumi_7TeV  = "4.9 fb^{-1}";  // default is "5.1 fb^{-1}"
  lumi_sqrtS = "13 TeV";       // used with iPeriod = 0, e.g. for simulation-only plots (default is an empty string)

  int iPeriod = 4;    // 1=7TeV, 2=8TeV, 3=7+8TeV, 4=13TeV, 7=7+8+13TeV, 0=free form (uses lumi_sqrtS)
  int iPos = 11;     // 0=out , 11=left, 22=center, 33=right


  //====================================================================================
  // Style

  int W = 600;
  int H = 600;

  // 
  // Simple example of macro: plot with CMS name and lumi text
  //  (this script does not pretend to work in all configurations)
  // iPeriod = 1*(0/1 7 TeV) + 2*(0/1 8 TeV)  + 4*(0/1 13 TeV) 
  // For instance: 
  //               iPeriod = 3 means: 7 TeV + 8 TeV
  //               iPeriod = 7 means: 7 TeV + 8 TeV + 13 TeV 
  // Initiated by: Gautier Hamel de Monchenault (Saclay)
  // Updated by:   Dinko Ferencek (Rutgers)
  //
  int H_ref = 600; 
  int W_ref = 600; 

  // references for T, B, L, R
  float T = 0.08*H_ref;
  float B = 0.12*H_ref; 
  float L = 0.15*W_ref;
  float R = 0.04*W_ref;

  TString canvName = "trigger";
  canvName += W;
  canvName += "-";
  canvName += H;
  canvName += "_";  
  canvName += iPeriod;
  if( writeExtraText ) canvName += "-prelim";
  if( iPos%10==0 ) canvName += "-out";
  else if( iPos%10==1 ) canvName += "-left";
  else if( iPos%10==2 )  canvName += "-center";
  else if( iPos%10==3 )  canvName += "-right";

  TCanvas* canv = new TCanvas(canvName,canvName,50,50,W,H);
  canv->SetFillColor(0);
  canv->SetBorderMode(0);
  canv->SetFrameFillStyle(0);
  canv->SetFrameBorderMode(0);
  canv->SetLeftMargin( L/W );
  canv->SetRightMargin( R/W );
  canv->SetTopMargin( T/H );
  canv->SetBottomMargin( B/H );
  canv->SetTickx(0);
  canv->SetTicky(0);

  canv->SetGridx(true);
  canv->SetGridy(true);

  //====================================================================================
  // Efficiency

  TFile *fileInput = TFile::Open(myinputFile);

  fileInput->ls();

  TEfficiency* h_efficiency = 0;

  TH1F *h_denominator;
  TH1F *h_numerator;
  if(histoFromFile==1)
    {
      //== taking histo from file       
      h_denominator = (TH1F*)fileInput->Get(mydenominator);
      h_numerator   = (TH1F*)fileInput->Get(mynumerator);
    }
  else
    {
      //== creating histo from tree   
      TTree *thistree = (TTree*)fileInput->Get("rootTupleTree/tree");
      thistree->Print();
      TH1F *h_denominator_tmp = (TH1F*)fileInput->Get(mydenominator);
      h_denominator = (TH1F*)h_denominator_tmp->Clone();
      h_numerator = (TH1F*)h_denominator_tmp->Clone();
      h_denominator->Reset();
      h_numerator->Reset();
      h_denominator->SetName("h_denominator");
      h_numerator->SetName("h_numerator");
      //fill histograms
      //--
      //thistree->Draw("mjj >> h_denominator","fabs(deltaETAjj)<1.3 && passHLT_PFHT475==1"); //signal region
      //thistree->Draw("mjj >> h_denominator","fabs(deltaETAjj)<1.3 && passHLT_Mu45==1"); //signal region
      thistree->Draw("mjj >> h_denominator","fabs(deltaETAjj)>1.3 && fabs(deltaETAjj)<2.6 && passHLT_Mu45==1"); //control region
      //--
      //thistree->Draw("mjj >> h_numerator","fabs(deltaETAjj)<1.3 && passHLT_PFHT475==1 && passHLT_PFHT800==1");
      //thistree->Draw("mjj >> h_numerator","fabs(deltaETAjj)<1.3 && passHLT_Mu45==1 && passHLT_PFHT800==1");
      //thistree->Draw("mjj >> h_numerator","fabs(deltaETAjj)<1.3 && passHLT_Mu45==1 && (passHLT_PFHT800==1 || passHLT_PFJET500==1)");
      thistree->Draw("mjj >> h_numerator","fabs(deltaETAjj)>1.3 && fabs(deltaETAjj)<2.6 && passHLT_Mu45==1 && (passHLT_PFHT800==1 || passHLT_PFJET500==1)");
      //thistree->Draw("mjj >> h_numerator","fabs(deltaETAjj)>1.3 && fabs(deltaETAjj)<2.6 && passHLT_Mu45==1 && (passHLT_PFHT800==1 || passHLT_PFJET500==1 || passHLT_PFHT650MJJ950==1 || passHLT_PFHT650MJJ900==1 || passHLT_AK8DiPFJet280200TrimMass30Btag==1 || passHLT_AK8PFHT600TriMass50Btag==1 || passHLT_AK8PFHT700TriMass50==1 || passHLT_AK8PFJet360TrimMass50==1 || passHLT_CaloJet500NoJetID==1 || passHLT_DiPFJetAve300HFJEC==1 || passHLT_DiPFJetAve500==1 || passHLT_PFHT400SixJet30Btag==1 || passHLT_PFHT450SixJet40Btag==1 || passHLT_PFHT750FourJetPt50==1 || passHLT_QuadPFJetVBF==1 || passHLT_PFHT650==1 || passHLT_PFHT475==1 || passHLT_PFHT200==1 || passHLT_PFJET450==1)");
      //-- option placeholder 
      //thistree->Draw("mjj >> h_denominator","fabs(deltaETAjj)<1.3 && passHLT_Mu45==1","",10000);
      //--  
    }

  //==========================

  if(TEfficiency::CheckConsistency(*h_numerator,*h_denominator))
    {
      h_efficiency = new TEfficiency(*h_numerator,*h_denominator);    
      //stat option, see https://root.cern.ch/root/html/TEfficiency.html#TEfficiency:SetStatisticOption
      h_efficiency->SetStatisticOption(TEfficiency::kFWilson);  
      //h_efficiency->SetStatisticOption(TEfficiency::kFCP); //default  
      h_efficiency->SetTitle(mytitle);
      h_efficiency->Draw();
      gPad->Update();
      h_efficiency->GetPaintedGraph()->GetXaxis()->SetRangeUser(xmin,xmax);
      h_efficiency->GetPaintedGraph()->GetXaxis()->SetNdivisions(505);
      h_efficiency->GetPaintedGraph()->GetYaxis()->SetRangeUser(ymin,ymax);
      //h_efficiency->GetPaintedGraph()->GetYaxis()->SetTitleOffset(0.9);
      // h_efficiency->GetPaintedGraph()->GetYaxis()->SetLabelSize(0.04);

      for (int bin=0;bin<h_efficiency->GetPaintedGraph()->GetN();bin++)
	{
	  double x=-1; 
	  double y=-1;
	  double eyh=-1;
	  double eyl=-1;

	  h_efficiency->GetPaintedGraph()->GetPoint(bin,x,y);
	  eyh = h_efficiency->GetPaintedGraph()->GetErrorYhigh(bin);
	  eyl = h_efficiency->GetPaintedGraph()->GetErrorYlow(bin);
	  cout << "bin = " << bin << ": x= " << x << " , y = " << y << " + " << eyh << " - " << eyl << endl;       
	}

      // draw the legend
      TLegend *legend=new TLegend(0.35,0.22,0.89,0.32);
      //legend->SetTextFont(72);
      //legend->SetTextSize(0.04);
      legend->SetFillStyle(0);
      legend->SetLineColor(0);
      legend->SetShadowColor(0);
      legend->AddEntry(h_efficiency,mytitlelegend,"lpe");
      legend->Draw();
    }

  //====================================================================================
  //Draw

  //## Trigger Efficiency plot ##
  // writing the lumi information and the CMS "logo"
  CMS_lumi( canv, iPeriod, iPos ); 
  canv->Update();
  canv->RedrawAxis();
  canv->GetFrame()->Draw();
  gPad->SetTickx(1);
  gPad->SetTicky(1);
  canv->Print(myoutputfilename+".pdf",".pdf");
  canv->Print(myoutputfilename+".png",".png");
  canv->Print(myoutputfilename+".root",".root");
  
  //## Trigger Efficiency plot (zoom) ## 
  h_efficiency->GetPaintedGraph()->GetXaxis()->SetRangeUser(xminZoom,xmaxZoom);
  h_efficiency->GetPaintedGraph()->GetYaxis()->SetRangeUser(yminZoom,ymaxZoom);

  CMS_lumi( canv, iPeriod, iPos ); 
  canv->Update();
  canv->RedrawAxis();
  canv->GetFrame()->Draw();
  gPad->SetTickx(1);
  gPad->SetTicky(1);
  canv->Print(myoutputfilename+"_zoom.pdf",".pdf");
  canv->Print(myoutputfilename+"_zoom.png",".png");
  
  //Integral above threshold
  int totalNev =  h_denominator->Integral(h_denominator->FindFixBin(threshold),h_denominator->GetNbinsX());
  int passedNev =  h_numerator->Integral(h_numerator->FindFixBin(threshold),h_numerator->GetNbinsX());
  //int totalNev =  h_denominator->Integral(h_denominator->FindFixBin(threshold),h_denominator->FindFixBin(threshold));
  //int passedNev =  h_numerator->Integral(h_numerator->FindFixBin(threshold),h_numerator->FindFixBin(threshold));
  float effIntegrated = float(passedNev)/float(totalNev);
  cout << "totalNev = " << totalNev <<  " , passedNev=" << passedNev << " , efficiency=" << effIntegrated << endl;       
  TEfficiency* pEff = 0;
  float effIntegrated_errUp = pEff->Wilson(totalNev,passedNev,0.683,true) - effIntegrated;
  float effIntegrated_errDown = pEff->Wilson(totalNev,passedNev,0.683,false) - effIntegrated;
  cout << "efficiency integrated above threshold of "<< threshold <<" = " << effIntegrated << " + " << effIntegrated_errUp << " - " << effIntegrated_errDown << endl;


  //## Mjj Spectra ##
  canv->SetGridx(false);
  canv->SetGridy(false);
  canv->SetLogy(true);
  h_denominator->UseCurrentStyle();  
  h_denominator->SetLineColor(2);
  h_numerator->SetLineColor(1);
  h_denominator->Draw();
  h_numerator->Draw("same");
  h_denominator->GetXaxis()->SetRangeUser(xmin,xmax);
  h_denominator->GetXaxis()->SetTitle(xAxisTitle);
  h_denominator->GetYaxis()->SetTitle(yAxisTitle);
  h_denominator->GetYaxis()->SetTitleOffset(1.3);

  CMS_lumi( canv, iPeriod, iPos ); 
  canv->Update();
  canv->RedrawAxis();
  canv->GetFrame()->Draw();
  gPad->SetTickx(1);
  gPad->SetTicky(1);

  // draw the legend
  TLegend *legend1=new TLegend(0.4,0.65,0.91,0.83);
  //legend->SetTextFont(72);
  //legend->SetTextSize(0.06);
  legend1->SetFillStyle(0);
  legend1->SetLineColor(0);
  legend1->SetShadowColor(0);
  legend1->AddEntry(h_denominator,mytitlelegendDen,"l");
  legend1->AddEntry(h_numerator,mytitlelegendNum,"l");
  legend1->Draw();

  canv->Print(myoutputfilename+"_histo.pdf",".pdf");
  canv->Print(myoutputfilename+"_histo.png",".png");
  



  //-----------------------------------------------------------------------------

}
void drawCombinedGraphs(TGraphErrors* balancingData, TGraphErrors* balancingMC, TGraphErrors* mpfData, TGraphErrors* mpfMC, const std::string& xTitle, const std::string& yTitle, const std::string& legendTitle, double lumi, const std::string& outputName) {

  balancingData->SetMarkerSize(1.5);
  balancingData->SetMarkerStyle(20);
  balancingData->SetMarkerColor(kBlack);
  balancingData->SetLineColor(kBlack);

  mpfData->SetMarkerSize(1.5);
  mpfData->SetMarkerStyle(20);
  mpfData->SetMarkerColor(kRed);
  mpfData->SetLineColor(kRed);

  balancingMC->SetMarkerSize(1.5);
  balancingMC->SetMarkerStyle(29);
  balancingMC->SetMarkerColor(kBlue);
  balancingMC->SetLineColor(kBlue);

  mpfMC->SetMarkerSize(1.5);
  mpfMC->SetMarkerStyle(29);
  mpfMC->SetMarkerColor(46);
  mpfMC->SetLineColor(46);
  
  TH1D* errors_bal_data = new TH1D("errors_bal_data", "errors", 100, 0, 1);
  errors_bal_data->SetStats(false);
  errors_bal_data->SetFillColor(LIGHT_GRAY);
  errors_bal_data->SetFillStyle(1001);

  TH1D* errors_bal_mc = (TH1D*) errors_bal_data->Clone("errors_bal_mc");
  errors_bal_mc->SetFillColor(LIGHT_BLUE);

  TH1D* errors_mpf_data = new TH1D("errors_mpf_data", "errors", 100, 0, 1);
  errors_mpf_data->SetStats(false);
  errors_mpf_data->SetFillColor(LIGHT_RED);
  errors_mpf_data->SetFillStyle(1001);

  TH1D* errors_mpf_mc = (TH1D*) errors_bal_data->Clone("errors_mpf_mc");
  errors_mpf_mc->SetFillColor(LIGHT_MARRON);

  TF1* balancingData_fct = new TF1("balancingData_fct", "[0] - x*x*[1]", 0, 1);
  balancingData_fct->SetLineColor(kBlack);
  balancingData_fct->SetLineWidth(1);
  balancingData_fct->SetLineStyle(2);

  balancingData->Fit(balancingData_fct, "QRN");
  (TVirtualFitter::GetFitter())->GetConfidenceIntervals(errors_bal_data, 0.68);

  TF1* balancingMC_fct = new TF1("mc_fct", "[0] - x*x*[1]", 0, 1);
  balancingMC_fct->SetLineColor(kBlue);
  balancingMC_fct->SetLineWidth(1);
  balancingMC_fct->SetLineStyle(2);

  balancingMC->Fit(balancingMC_fct, "QRN");
  (TVirtualFitter::GetFitter())->GetConfidenceIntervals(errors_bal_mc, 0.68);

  TF1* mpfData_fct = new TF1("mpfData_fct", "[0] + x*[1]", 0, 1);
  mpfData_fct->SetLineColor(kRed);
  mpfData_fct->SetLineWidth(1);
  mpfData_fct->SetLineStyle(2);

  mpfData->Fit(mpfData_fct, "QRN");
  (TVirtualFitter::GetFitter())->GetConfidenceIntervals(errors_mpf_data, 0.68);

  TF1* mpfMC_fct = new TF1("mc_fct", "[0] + x*[1]", 0, 1);
  mpfMC_fct->SetLineColor(46);
  mpfMC_fct->SetLineWidth(1);
  mpfMC_fct->SetLineStyle(2);

  mpfMC->Fit(mpfMC_fct, "QRN");
  (TVirtualFitter::GetFitter())->GetConfidenceIntervals(errors_mpf_mc, 0.68);

  TString balancing_ratio_legend = TString::Format("#color[4]{#scale[1]{r_{bal} = %.03f #pm %.03f}}", balancingData_fct->GetParameter(0) / balancingMC_fct->GetParameter(0), sqrt(pow(balancingData_fct->GetParError(0), 2) + pow(balancingMC_fct->GetParError(0), 2)));

  TString mpf_ratio_legend = TString::Format("#color[2]{#scale[1]{r_{MPF} = %.03f #pm %.03f}}", mpfData_fct->GetParameter(0) / mpfMC_fct->GetParameter(0), sqrt(pow(mpfData_fct->GetParError(0), 2) + pow(mpfMC_fct->GetParError(0), 2)));

  TMultiGraph* mg = new TMultiGraph();
  mg->Add(balancingData);
  mg->Add(balancingMC);
  mg->Add(mpfData);
  mg->Add(mpfMC);

  TString title = TString::Format(";%s;%s", xTitle.c_str(), yTitle.c_str());
  mg->SetTitle(title);

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

  mg->Draw("ap");

  balancingData_fct->SetRange(0, 1);
  balancingMC_fct->SetRange(0, 1);
  mpfData_fct->SetRange(0, 1);
  mpfMC_fct->SetRange(0, 1);

  errors_bal_data->Draw("e3 same");
  errors_bal_mc->Draw("e3 same");

  errors_mpf_data->Draw("e3 same");
  errors_mpf_mc->Draw("e3 same");

  mg->Draw("ap same");

  balancingData_fct->Draw("same");
  balancingMC_fct->Draw("same");
  mpfData_fct->Draw("same");
  mpfMC_fct->Draw("same");

  TLegend* legend = new TLegend(0.18, 0.18, 0.55, 0.45);
  legend->SetTextFont(42);
  legend->SetFillColor(kWhite);
  legend->SetFillStyle(0);
  legend->SetTextSize(0.035);
  legend->SetBorderSize(1);

  TString legendTitleWithPtCut = TString::Format("%s, p_{T}^{#gamma} #geq 170 GeV", legendTitle.c_str());

  legend->SetHeader(legendTitleWithPtCut);
  legend->AddEntry(balancingData, "Balancing (data)", "p");
  legend->AddEntry(balancingMC, "Balancing (MC)", "p");
  legend->AddEntry(mpfData, "MPF (data)", "p");
  legend->AddEntry(mpfMC, "MPF (MC)", "p");
  legend->Draw();

  TLatex tl;
  tl.SetNDC();
  tl.SetTextSize(0.035);
  tl.SetTextFont(42);

  // Luminosity
  TString sLumi = TString::Format("L = %.02f fb^{-1}", lumi);
  tl.DrawLatex(0.18, 0.96, sLumi);

  // Energy
  tl.DrawLatex(0.80, 0.96, "#sqrt{s} = 8 TeV");

  // Ratios
  tl.DrawLatex(0.18, 0.515, balancing_ratio_legend);
  tl.DrawLatex(0.18, 0.47, mpf_ratio_legend);

  canvas->Print((outputName + ".pdf").c_str());

  delete legend;
  delete canvas;

  delete errors_bal_data;
  delete errors_bal_mc;

  delete errors_mpf_data;
  delete errors_mpf_mc;

  // Do now data / MC plots

  TH1D* errors_bal = new TH1D("errors_bal", "errors", 100, 0, 1);
  errors_bal->SetStats(false);
  errors_bal->SetFillColor(LIGHT_BLUE);
  errors_bal->SetFillStyle(1001);

  TH1D* errors_mpf = (TH1D*) errors_bal->Clone("errors_mpf");
  errors_mpf->SetFillColor(LIGHT_RED);

  TGraphErrors* balancing_ratio = fitTools::get_graphRatio(balancingData, balancingMC);
  balancing_ratio->SetMarkerSize(1.5);
  balancing_ratio->SetMarkerColor(kBlue);
  balancing_ratio->SetLineColor(kBlue);
  balancing_ratio->SetMarkerStyle(20);

  TGraphErrors* mpf_ratio = fitTools::get_graphRatio(mpfData, mpfMC);
  mpf_ratio->SetMarkerSize(1.5);
  mpf_ratio->SetMarkerColor(kRed);
  mpf_ratio->SetLineColor(kRed);
  mpf_ratio->SetMarkerStyle(20);

  TF1* balancingRatio_fct = new TF1("balancingRatio_fct", "[0] + x*[1]", 0, 1);
  balancingRatio_fct->SetLineColor(kBlue);
  balancingRatio_fct->SetLineWidth(1);
  balancingRatio_fct->SetLineStyle(2);

  balancing_ratio->Fit(balancingRatio_fct, "QRN");
  (TVirtualFitter::GetFitter())->GetConfidenceIntervals(errors_bal, 0.68);
  balancing_ratio_legend = TString::Format("#color[4]{#splitline{#scale[1.2]{r = %.03f #pm %.03f}}{#scale[0.8]{#chi^{2} / NDF: %.02f / %d}}}", balancingRatio_fct->GetParameter(0), balancingRatio_fct->GetParError(0), balancingRatio_fct->GetChisquare(), balancingRatio_fct->GetNDF());

  TF1* mpfRatio_fct = new TF1("mpfRatio_fct", "[0] + x*[1]", 0, 1);
  mpfRatio_fct->SetLineColor(kRed);
  mpfRatio_fct->SetLineWidth(1);
  mpfRatio_fct->SetLineStyle(2);

  mpf_ratio->Fit(mpfRatio_fct, "QRN");
  (TVirtualFitter::GetFitter())->GetConfidenceIntervals(errors_mpf, 0.68);
  mpf_ratio_legend = TString::Format("#color[2]{#splitline{#scale[1.2]{r = %.03f #pm %.03f}}{#scale[0.8]{#chi^{2} / NDF: %.02f / %d}}}", mpfRatio_fct->GetParameter(0), mpfRatio_fct->GetParError(0), mpfRatio_fct->GetChisquare(), mpfRatio_fct->GetNDF());

  TMultiGraph* mg2 = new TMultiGraph();
  mg2->Add(balancing_ratio);
  mg2->Add(mpf_ratio);

  title = TString::Format(";%s;Data / MC ratio", xTitle.c_str());
  mg2->SetTitle(title);

  canvas = new TCanvas("canvas", "", 800, 800);

  mg2->Draw("ap");

  balancingRatio_fct->SetRange(0, 1);
  mpfRatio_fct->SetRange(0, 1);

  errors_bal->Draw("e3 same");
  errors_mpf->Draw("e3 same");

  mg2->Draw("ap same");

  balancingRatio_fct->Draw("same");
  mpfRatio_fct->Draw("same");

  legend = new TLegend(0.18, 0.18, 0.50, 0.35);
  legend->SetTextFont(42);
  legend->SetFillColor(kWhite);
  legend->SetFillStyle(0);
  legend->SetTextSize(0.035);
  legend->SetBorderSize(1);

  legend->SetHeader(legendTitleWithPtCut);
  legend->AddEntry(balancing_ratio, "Balancing", "p");
  legend->AddEntry(mpf_ratio, "MPF", "p");
  legend->Draw();

  // Luminosity
  tl.DrawLatex(0.18, 0.96, sLumi);

  // Energy
  tl.DrawLatex(0.80, 0.96, "#sqrt{s} = 8 TeV");

  // Fit
  tl.DrawLatex(0.18, 0.47, balancing_ratio_legend);
  tl.DrawLatex(0.18, 0.38, mpf_ratio_legend);

  canvas->Print((outputName + "_ratio.pdf").c_str());

  delete legend;
  delete canvas;

  
  delete mg;
  delete mg2;

  delete errors_bal;
  delete errors_mpf;
}
Exemple #26
0
void makeMETPlots( bool printplot = false ){

  gStyle->SetOptFit(0);

  TChain *ch = new TChain("T1");
  ch->Add("../../output/V00-02-21/wz_summer11_madgraph_gen_baby.root");

  vector<TCut> metcuts;
  vector<float> metcutvals;

  metcuts.push_back(TCut("pfmet>100")); metcutvals.push_back(100);
  metcuts.push_back(TCut("pfmet>200")); metcutvals.push_back(200);
  metcuts.push_back(TCut("pfmet>300")); metcutvals.push_back(300);

  TCut sel("dilmass>81&&dilmass<101&&njets>=2");

  const unsigned int n = metcuts.size();

  TH1F* hpass[n];
  TH1F* hall[n];

  for( unsigned int i = 0 ; i < metcuts.size() ; ++i){

    hpass[i]   = new TH1F(Form("hpass_%i",i),Form("hpass_%i",i),30,0,600);
    hall[i]    = new TH1F(Form("hall_%i",i), Form("hall_%i",i) ,30,0,600);

    ch->Draw(Form("genmet>>hpass_%i",i),sel+metcuts.at(i));
    ch->Draw(Form("genmet>>hall_%i",i)  ,sel);

  }

  TCanvas *can = new TCanvas();
  can->cd();
  gPad->SetGridx();
  gPad->SetGridy();
  gPad->SetTopMargin(0.08);

  TGraphAsymmErrors* gr[n];  
  TLegend *leg = new TLegend(0.6,0.2,0.95,0.4);
  leg->SetFillColor(0);
  leg->SetBorderSize(1);
  leg->SetTextSize(0.035);

  TF1* erf[n];

  for( unsigned int i = 0 ; i < metcuts.size() ; ++i){

    //can[i] = new TCanvas(Form("can_%i",i),Form("can_%i",i),600,600);
    //can[i]->cd();
    
    TF1* efunc = new TF1("efitf", fitf, 0, 600, 3);
    efunc->SetParameters(1, 100, 10);
    efunc->SetParNames("norm", "offset", "width");

    erf[i] = new TF1("efitf", fitf, 0, 600, 3);
    erf[i]->SetParameters(1, 100, 10);
    erf[i]->SetParNames("norm", "offset", "width");
    erf[i]->SetLineWidth(2);
    //erf[i]->FixParameter(0,1);

    //erf[i] = new TF1(Form("erf_%i",i),mfitf,0,400);

    //erf[i]->SetParameter(0,100*(i+1));
    //erf[i]->SetParameter(1,10);

    gr[i] = new TGraphAsymmErrors();
    if( i==0 ){
      erf[i]->SetLineColor(1);
    }

    if( i==1 ){
      gr[i]->SetLineColor(2);
      gr[i]->SetMarkerColor(2);
      gr[i]->SetMarkerStyle(21);
      erf[i]->SetLineColor(2);
    }
    if( i==2 ){
      gr[i]->SetLineColor(4);
      gr[i]->SetMarkerColor(4);
      gr[i]->SetMarkerStyle(25);
      erf[i]->SetLineColor(4);
    }

    leg->AddEntry(gr[i],Form("E_{T}^{miss}>%.0f GeV",metcutvals.at(i)),"p");

    gr[i]->GetXaxis()->SetTitle("generator-level E_{T}^{miss} (GeV)");
    gr[i]->GetYaxis()->SetTitle("efficiency");
    gr[i]->SetMaximum(1.05);
    gr[i]->BayesDivide(hpass[i],hall[i]);

    //gr[i]->Fit(efunc,"R");
    gr[i]->Fit(erf[i],"R");


    if( i==0 ) gr[i]->Draw("AP");
    else       gr[i]->Draw("sameP");

    gr[i]->GetXaxis()->SetTitle("generator E_{T}^{miss} [GeV]");
    gr[i]->GetYaxis()->SetTitle("efficiency");

    //erf[i]->Draw("same");
  }

  leg->Draw();

  TLatex *t = new TLatex();
  t->SetNDC();
  t->SetTextSize(0.04);
  t->DrawLatex(0.28,0.95,"CMS Simulation,  #sqrt{s} = 7 TeV");


  if (printplot) can->Print("../plots/met_turnon_LM4.pdf");





}
void BasePlotter::writeEfficiency(const HistogramContainer& numeratorContainer, const vector<TH1*>& denominatorHistograms, string extension, const vector<string>& binNames) const
{
    // Check numeratorContainer consistency
    if( ! numeratorContainer.check() ) 
        throw 1;
    if(  numeratorContainer.histograms.size() != denominatorHistograms.size() )
    {
        cerr << "Inconsistency found between histogramContainer \"" <<  numeratorContainer.containerName << "\" and denominatorHistograms, vectors don't have the same lenght." << endl;
        throw 1;
    }
    
    if( extension[0] == '.' )
        extension.erase(0,1);
    
    system(("mkdir -p " + configContainer.outputDir).c_str());  
    TFile* f = new TFile((configContainer.outputDir + "Efficiency.root").c_str(), "UPDATE");
    
    unsigned int nSamples = numeratorContainer.histograms.size();
    TCanvas *c = new TCanvas("Cut_eff_canv", "", 600, 600);
    TLegend* leg = nullptr;
    vector<TLatex*> latexVector;
    setCanvasAttributes( nSamples, leg, latexVector);
    
    // Calculate efficiencies
    TGraphAsymmErrors* hEff[nSamples];   
    for( unsigned int iSample = 0; iSample < nSamples; ++iSample )
    {
//         unsigned int nBins = numeratorContainer.histograms[iSample]->GetNcells();
//         for( unsigned int i = 0; i <= nBins; ++i )
//         {
//             cout << "bin " << i << "\t numerator: " << numeratorContainer.histograms[iSample]->GetBinContent(i) << "\t denominator: " << denominatorHistograms[iSample]->GetBinContent(i) << endl;
//         }
        
        
        hEff[iSample] = new TGraphAsymmErrors(numeratorContainer.histograms[iSample], denominatorHistograms[iSample], "cl=0.683 b(1,1) mode");
        hEff[iSample]->GetYaxis()->SetTitle("Efficiency");
        
        unsigned int binNamesSize = binNames.size();
        if( binNamesSize > 0 )
        {
            for( unsigned int iCut = 0; iCut < binNamesSize; ++iCut ) 
            {
                hEff[iSample]->GetXaxis()->SetBinLabel( hEff[iSample]->GetXaxis()->FindBin(iCut+0.5), (binNames[iCut]).c_str() );
            }
        }
        else
        {
            hEff[iSample]->GetXaxis()->SetTitle(numeratorContainer.histograms[iSample]->GetXaxis()->GetTitle());
        }
    }
    
    // Set y-range
    float hMax = 0.;
    float hMin = 0.;
    if( numeratorContainer.axisRanges.size() > 0 )
    {
        hMin = numeratorContainer.axisRanges[0];
        hMax = numeratorContainer.axisRanges[1];
    }
    else
    {
        for( unsigned int iSample = 0; iSample < nSamples; ++iSample )
        {
            float tempMax = hEff[iSample]->GetHistogram()->GetMaximum();
            if (tempMax > hMax)
                hMax = tempMax;
        }     
        if( configContainer.logY ) 
        {
            c->SetLogy(1);
            hMin = 0.05;
            hMax *= 500;
        }
        else
            hMax *= 1.55;
    }
    
    for( unsigned int iSample = 0; iSample < nSamples; ++iSample )
    {
        if( numeratorContainer.sampleType[iSample] == SampleType::DATA && ! configContainer.unblind ) continue;
        
        hEff[iSample]->SetLineColor(numeratorContainer.color[iSample]);
        hEff[iSample]->SetFillColor(numeratorContainer.color[iSample]);
        string legendEntry = numeratorContainer.reducedNames[iSample];
        replace(legendEntry.begin(), legendEntry.end(), '_', ' ');
            
        if( numeratorContainer.sampleType[iSample] == SampleType::DATA ) 
        {
            hEff[iSample]->SetMarkerSize(1);
            hEff[iSample]->SetMarkerStyle(20);
            hEff[iSample]->SetMarkerColor(numeratorContainer.color[iSample]);
            hEff[iSample]->SetLineWidth(2);
            leg->AddEntry(hEff[iSample],legendEntry.c_str(),"lp");
        }
        else
        {
            hEff[iSample]->SetFillStyle(1001);
            leg->AddEntry(hEff[iSample],legendEntry.c_str(),"f");
        }
    }
    
    // Draw TGraphs
    for( unsigned int iSample = 0; iSample < nSamples; ++iSample )
    {
        hEff[iSample]->GetYaxis()->SetRangeUser(hMin, hMax);
        
        if( iSample == 0) 
            hEff[iSample]->Draw("APZ");
        else
            hEff[iSample]->Draw("PZ");
    }

    leg->Draw();
    for( auto* text : latexVector )
    {
        text->Draw("same");
    }
    
    c->Print((configContainer.outputDir + numeratorContainer.containerName + "." + extension).c_str(), extension.c_str());
    cout << "Wrote plot " << (numeratorContainer.containerName + "." + extension) << endl;
    c->Write();
    f->Close();
}
Exemple #28
0
void plotDataCard(TString file, Int_t channel, Int_t cat=-1){

  TString ChannelName;
  if(channel==1)ChannelName="muTau";
  else if(channel==2)ChannelName="eleTau";
  else return;
  
  TFile nominal(file+".root","read");
  gROOT->cd();

  //TString fname=TString("plotDataCard_")+file+".ps";
  TString fname=file+".ps";

  TCanvas C;
  C.Print(fname+"[");

  for(long sm=0;sm<NCAT;sm++){//
    if(cat==13 && (sm==2 || sm==4))continue;//skip boost_low and vbf
    if(cat==20 && (sm==3 || sm==4))continue;//skip boost_high and vbf
    if(cat==23 && (sm==4))continue;//skip vbf
    if(cat==15 && (sm==2 || sm==3))continue;//skip boost_low and boost_high

    TH1F* ZTT = (TH1F*)nominal.Get(ChannelName+"_"+catdirname[sm]+"/ZTT");
    if(!ZTT)continue;
    TH1F* QCD = (TH1F*)nominal.Get(ChannelName+"_"+catdirname[sm]+"/QCD");
    TH1F* W = (TH1F*)nominal.Get(ChannelName+"_"+catdirname[sm]+"/W");
    TH1F* TT = (TH1F*)nominal.Get(ChannelName+"_"+catdirname[sm]+"/TT");
    TH1F* ZL = (TH1F*)nominal.Get(ChannelName+"_"+catdirname[sm]+"/ZL");
    TH1F* ZJ = (TH1F*)nominal.Get(ChannelName+"_"+catdirname[sm]+"/ZJ");
    TH1F* VV = (TH1F*)nominal.Get(ChannelName+"_"+catdirname[sm]+"/VV");
    TH1F* data_obs = (TH1F*)nominal.Get(ChannelName+"_"+catdirname[sm]+"/data_obs");

    //plot
    TH1F*MC=(TH1F*)ZTT->Clone("MC");
    MC->Add(ZL);
    MC->Add(ZJ);
    MC->Add(TT);
    MC->Add(W);
    MC->Add(TT);
    MC->Add(VV);
    MC->Add(QCD);
    MC->SetTitle(ChannelName+"_"+catdirname[sm]);


    THStack hMCStack("hBkgStack","BkgStack");//dont't set any of the regular histogram properties on the THStack will crash.
    QCD->SetFillColor(kMagenta-10);
    hMCStack.Add(QCD,"hist");
    TH1F*hEWK=(TH1F*)W->Clone("EWK");
    hEWK->Add(ZL);
    hEWK->Add(ZJ);
    hEWK->Add(VV);
    hEWK->SetFillColor(kRed+2);
    hMCStack.Add(hEWK,"hist");
    TT->SetFillColor(kBlue-8);
    hMCStack.Add(TT,"hist");
    ZTT->SetFillColor(kOrange-4);
    hMCStack.Add(ZTT,"hist");


    ////////////
    C.Clear();
    if(MC->GetMaximum()>data_obs->GetMaximum())
      data_obs->GetYaxis()->SetRangeUser(0,1.2*MC->GetMaximum());
    else
      data_obs->GetYaxis()->SetRangeUser(0,1.2*data_obs->GetMaximum());
    data_obs->SetTitle(catdirname[sm]);
    data_obs->Draw("histpe");
    hMCStack.Draw("histsame");
    data_obs->Draw("histpesame");
    C.Print(fname);
    delete MC;

    ////////Draw the first and last Higgs signal
    C.Clear();
    TH1F * SM1=0;
    TH1F * SM2=0;
    for(Int_t m=0;m<NMASS;m++){
      long ma=massValues[m];
      TH1F* SM = (TH1F*)nominal.Get(ChannelName+"_"+catdirname[sm]+"/ggH"+ma);
      TH1F* VBF = (TH1F*)nominal.Get(ChannelName+"_"+catdirname[sm]+"/qqH"+ma);
      TH1F* VH = (TH1F*)nominal.Get(ChannelName+"_"+catdirname[sm]+"/VH"+ma);
      if(massValues[m]==110){SM1=(TH1F*)SM->Clone("SM1"); SM1->Add(VBF); SM1->Add(VH);}
      if(massValues[m]==145){SM2=(TH1F*)SM->Clone("SM2");SM2->Add(VBF);SM2->Add(VH);}
    }
    if(SM1->GetMaximum()>SM2->GetMaximum())
      SM1->GetYaxis()->SetRangeUser(0,1.2*SM1->GetMaximum());
    if(SM1->GetMaximum()<SM2->GetMaximum())
      SM1->GetYaxis()->SetRangeUser(0,1.2*SM2->GetMaximum());

    SM1->SetTitle(catdirname[sm]);
    SM1->Draw("hist");
    SM2->Draw("histsame");
    C.Print(fname);
 
  }
  
  C.Print(fname+"]");
 
  nominal.Close();
}
int main() {
  bool do_ratio = true;
  bool do_logy = true;

  TH1::AddDirectory(0);
  ModTDRStyle();
  gStyle->SetLineStyleString(11,"20 10");


  string file = "parametric/plots_asimov.root";

  string bin = "htt_mt_8_8TeV_postfit";
  string bin_hm = "htt_mt_8_8TeV_hm_postfit";
  TCanvas* canv = new TCanvas(bin.c_str(), bin.c_str());
  canv->cd();


  map<string, vector<BkgComponent>> bkg_schemes;
  bkg_schemes["mt"] = {
    BkgComponent("QCD",                   {"QCD"},      TColor::GetColor(250,202,255)),
    BkgComponent("t#bar{t}",              {"TT"},       TColor::GetColor(155,152,204)),
    BkgComponent("Electroweak",           {"W","VV"},   TColor::GetColor(222, 90,106)),
    BkgComponent("Z#rightarrow#mu#mu",    {"ZL","ZJ"},  TColor::GetColor(100,182,232)),
    BkgComponent("Z#rightarrow#tau#tau",  {"ZTT"} ,     TColor::GetColor(248,206,104))};

  vector<BkgComponent> & bkg_scheme = bkg_schemes["mt"];

  TFile file_(file.c_str(), "READ");

  TH1F data = ch::OpenFromTFile<TH1F>(&file_, bin + "/data_obs");
  data.Scale(1., "width");

  unsigned hm_rebin = 4;

  TH1F data_hm = ch::OpenFromTFile<TH1F>(&file_, bin_hm + "/data_obs");

  double max = data_hm.GetXaxis()->GetXmax();
  TH1F axis_hist("axis", "axis", static_cast<int>(max), 0, max);

  TH1F total_bkg = ch::OpenFromTFile<TH1F>(&file_, bin + "/TotalBkg");
  total_bkg.Scale(1., "width");

  TH1F total_sig = ch::OpenFromTFile<TH1F>(&file_, bin + "/TotalSig");
  total_sig.Scale(1., "width");


  TH1F total_bkg_hm = ch::RestoreBinning(ch::OpenFromTFile<TH1F>(&file_, bin_hm + "/TotalBkg"), data_hm);
  total_bkg_hm.SetLineWidth(2);

  TH1F total_sig_hm = ch::OpenFromTFile<TH1F>(&file_, bin_hm + "/TotalSig");

  data_hm.Rebin(hm_rebin);
  total_bkg_hm.Rebin(hm_rebin);
  total_sig_hm.Rebin(hm_rebin);

  data_hm.Scale(1., "width");
  total_bkg_hm.Scale(1., "width");
  total_sig_hm.Scale(1., "width");

  TH1F total_bkg_hm_err = total_bkg_hm;
  total_bkg_hm.SetLineColor(8);

  total_sig.SetLineColor(TColor::GetColor(0,18,255));
  total_sig_hm.SetLineColor(TColor::GetColor(0,18,255));
  total_sig.SetFillStyle(1001);
  total_sig_hm.SetFillStyle(1001);
  total_sig.SetLineStyle(11);
  total_sig_hm.SetLineStyle(11);
  total_sig.SetLineWidth(2);
  total_sig_hm.SetLineWidth(2);
  total_sig.Scale(0.01);
  total_sig_hm.Scale(0.01);


  for (auto & comp : bkg_scheme) {
    comp.hist = ch::OpenFromTFile<TH1F>(&file_, bin + "/" + comp.plots.at(0));
    for (unsigned i = 1; i < comp.plots.size(); ++i) {
      TH1F tmp = ch::OpenFromTFile<TH1F>(&file_, bin + "/" + comp.plots.at(i));
      comp.hist.Add(&tmp);
    }
    comp.hist.SetTitle(comp.legend.c_str());
    comp.hist.SetFillColor(comp.color);
    comp.hist.Scale(1., "width");
  }

  std::vector<TPad*> pads =
      do_ratio ? TwoPadSplit(0.29, 0.008, 0.008) : OnePad();

  pads[0]->SetLogy(do_logy);

  // Source histograms
  file_.Close();

  // Derived histograms

  // Axis histogram
  std::vector<TH1*> h = CreateAxisHists(2, &axis_hist);
  if (do_ratio) {
    SetupTwoPadSplitAsRatio(pads, h[0], h[1], "Obs/Exp", true, 0.25, 1.75);
    UnitAxes(h[1]->GetXaxis(), h[0]->GetYaxis(), "m_{#tau#tau}", "GeV");
  } else {
    // h[0]->GetXaxis()->SetTitleOffset(1.0);
    UnitAxes(h[0]->GetXaxis(), h[0]->GetYaxis(), "m_{#tau#tau}", "GeV");
  }

  // Can draw main axis now
  h[0]->Draw("axis");


  int new_idx = CreateTransparentColor(12, 0.4);
  total_bkg.SetFillColor(new_idx);
  total_bkg.SetMarkerSize(0);
  total_bkg_hm_err.SetFillColor(new_idx);
  total_bkg_hm_err.SetMarkerSize(0);

  THStack stack("stack", "stack");
  for (auto & comp : bkg_scheme) {
    stack.Add(new TH1F(comp.hist), "hist");
  }

  stack.Draw("histsame");
  // canv->Update();

  total_sig.Draw("histsame");

  total_bkg.Draw("e2same");

  total_bkg_hm_err.Draw("e3same");
  total_bkg_hm.Draw("histlsame");

  total_sig_hm.Draw("histsame");
  data.Draw("esamex0");
  data_hm.Draw("esamex0");

  TH1F *ratio = reinterpret_cast<TH1F *>(
      MakeRatioHist(&data, &total_bkg, true, false));
  TH1F *ratio_hm = reinterpret_cast<TH1F *>(
      MakeRatioHist(&data_hm, &total_bkg_hm, true, false));
  TH1F *ratio_err = reinterpret_cast<TH1F *>(
      MakeRatioHist(&total_bkg, &total_bkg, true, false));
  TH1F *ratio_err_hm = reinterpret_cast<TH1F *>(
      MakeRatioHist(&total_bkg_hm_err, &total_bkg_hm_err, true, false));
  if (pads[0]->GetLogy()) h[0]->SetMinimum(1E-3);

  FixTopRange(pads[0], GetPadYMax(pads[0]), 0.25);
  DrawCMSLogo(pads[0], "CMS", "Preliminary", 11, 0.045, 0.035, 1.2);
  DrawTitle(pads[0], "19.7 fb^{-1} (8 TeV)", 3);
  DrawTitle(pads[0], "H#rightarrow#tau#tau, #mu_{}#tau_{h}, No B-Tag", 1);

  if (do_ratio) {
    pads[1]->cd();
    h[1]->Draw("axis");
    ratio_err->Draw("e2same");
    ratio_err_hm->Draw("e3same");
    TLine line;
    line.SetLineStyle(2);
    DrawHorizontalLine(pads[1], &line, 1.0);
    ratio->Draw("esamex0");
    ratio_hm->Draw("esamex0");
  }

  pads[0]->cd();
  // pos = 1, 2, 3
  TLegend *legend = PositionedLegend(0.35, 0.35, 3, 0.03);
  legend->SetTextFont(42);
  FixBoxPadding(pads[0], legend, 0.05);
  legend->AddEntry(&data, "Observed", "pe");
  legend->AddEntry(&total_sig, "#Phi(800 GeV)#rightarrow#tau#tau", "l");
  for (auto & comp : boost::adaptors::reverse(bkg_scheme)) {
    legend->AddEntry(&comp.hist, comp.legend.c_str(), "f");
  }
  legend->AddEntry(&total_bkg_hm, "Parametric Bkg.", "l");
  legend->AddEntry(&total_bkg, "Bkg. Uncertainty", "f");
  legend->Draw();

  pads[0]->RedrawAxis();

  pads[0]->GetFrame()->Draw();

  if (do_ratio) {
    pads[1]->cd();
    pads[1]->RedrawAxis();
    pads[1]->GetFrame()->Draw();
  }

  canv->Print(".pdf");
  canv->Print(".png");

  delete legend;

  return 0;
}
Exemple #30
0
void 
postfit(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"     )){ 
	if (std::string(extra) == std::string("#mu#mu") ) dataset = "MS Preliminary,  H#rightarrow#tau#tau, 18.7 fb^{-1} at 8 TeV"; 
	else dataset = "MS Preliminary,  H#rightarrow#tau#tau, 19.4 fb^{-1} at 8 TeV";
  }
  if (std::string(dataset) == std::string("2011+2012")){ 
	if (std::string(extra) == std::string("#mu#mu") ) dataset = "CMS Preliminary,  H#rightarrow#tau#tau,  4.9 fb^{-1} at 7 TeV, 18.6 fb^{-1} at 8 TeV"; 
 	else dataset = "CMS Preliminary,  H#rightarrow#tau#tau,  4.9 fb^{-1} at 7 TeV, 19.4 fb^{-1} at 8 TeV";
	if (MSSM) dataset = "CMS Preliminary,  H#rightarrow#tau#tau,  4.9 fb^{-1} at 7 TeV, 12.1 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("boost_low" )){ category_extra = "1 jet, low p_{T}";  }
  if(std::string(extra2) == std::string("boost_high")){ category_extra = "1 jet, high p_{T}"; }
  if(std::string(extra2) == std::string("boost"     )){ 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* 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* 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(350)); } else{ data->GetXaxis()->SetRange(0, data->FindBin(490)); };
  if(!MSSM){ data->GetXaxis()->SetRange(0, data->FindBin(350)); }

  data->SetNdivisions(505);
  data->SetMinimum(min);
  if(Zmm){
    data->SetMaximum(max>0 ? max : std::max(maximum(data, log), maximum(EWK, log)));
  }
  else{
    data->SetMaximum(max>0 ? max : std::max(maximum(data, log), maximum(Ztt, log)));
  }
  data->Draw("e");

  if(log){
    if(Zmm){
      EWK  ->Draw("same");
      ttbar->Draw("same");
      Fakes->Draw("same");
      Zmm  ->Draw("same");
      Ztt  ->Draw("same");
    }
    else{
      Ztt  ->Draw("same");
      ttbar->Draw("same");
      EWK  ->Draw("same");
      if(EWK1){
	EWK1->Draw("same");
      }
      if(Fakes){ Fakes->Draw("same"); }
    }
    if(ggH) ggH  ->Draw("histsame");
  }
  else{
    if(ggH) ggH  ->Draw("histsame");
    if(Zmm){
      EWK->Draw("same");
      Fakes->Draw("same");
      ttbar->Draw("same");
      Zmm->Draw("same");
      Ztt->Draw("same");
    }
    else{
      Ztt  ->Draw("same");
      ttbar->Draw("same");
      EWK  ->Draw("same");
      if(EWK1){
	EWK1->Draw("same");
      }
      if(Fakes){ 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){
    TPaveText* massA      = new TPaveText(0.75, 0.48+0.061, 0.85, 0.48+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_{A}=160GeV");
    massA->Draw();
    
    TPaveText* tanb      = new TPaveText(0.75, 0.44+0.061, 0.85, 0.44+0.161, "NDC");
    tanb->SetBorderSize(   0 );
    tanb->SetFillStyle(    0 );
    tanb->SetTextAlign(   12 );
    tanb->SetTextSize ( 0.03 );
    tanb->SetTextColor(    1 );
    tanb->SetTextFont (   62 );
    tanb->AddText("tan#beta=20");
    tanb->Draw();
    
    TPaveText* scen      = new TPaveText(0.75, 0.40+0.061, 0.85, 0.40+0.161, "NDC");
    scen->SetBorderSize(   0 );
    scen->SetFillStyle(    0 );
    scen->SetTextAlign(   12 );
    scen->SetTextSize ( 0.03 );
    scen->SetTextColor(    1 );
    scen->SetTextFont (   62 );
    scen->AddText("mhmax");
    scen->Draw();
  }
  
  
  float lower_bound = EWK1 ? 0.60 : 0.65;
  TLegend* leg = new TLegend(MSSM ? 0.45 : 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");
  leg->AddEntry(Ztt  , "Z#rightarrow#tau#tau"           , "F" );
  if(Zmm){ leg->AddEntry(Zmm  , "Z#rightarrow#mu#mu"    , "F" ); }
  if(EWK1){
    leg->AddEntry(EWK  , "Z#rightarrow ee"              , "F" );
    leg->AddEntry(EWK1 , "electroweak"                  , "F" );
  }
  else{
    leg->AddEntry(EWK  , "electroweak"                  , "F" );
  }
  leg->AddEntry(ttbar, "t#bar{t}"                       , "F" );
  if(Fakes){ leg->AddEntry(Fakes, "QCD"                 , "F" ); }
  if(errorBand){
    leg->AddEntry(errorBand, "bkg. uncertainty" , "F" );
  }
  leg->Draw();

  /*
  TPaveText* ext0     = new TPaveText(0.50, lower_bound-0.08, 0.70, lower_bound-0.03, "NDC");
  ext0->SetBorderSize(   0 );
  ext0->SetFillStyle(    0 );
  ext0->SetTextAlign(   12 );
  ext0->SetTextSize ( 0.035 );
  ext0->SetTextColor(    1 );
  ext0->SetTextFont (   42 );
  ext0->AddText("CMS Preliminary");
  ext0->Draw();

  TPaveText* ext1     = new TPaveText(0.50, lower_bound-0.13, 0.70, lower_bound-0.08, "NDC");
  ext1->SetBorderSize(   0 );
  ext1->SetFillStyle(    0 );
  ext1->SetTextAlign(   12 );
  ext1->SetTextSize ( 0.035 );
  ext1->SetTextColor(    1 );
  ext1->SetTextFont (   42 );
  ext1->AddText("#sqrt{s} = 7 TeV, L = 4.9 fb^{-1}");
  ext1->Draw();

  TPaveText* ext2     = new TPaveText(0.50, lower_bound-0.18, 0.70, lower_bound-0.13, "NDC");
  ext2->SetBorderSize(   0 );
  ext2->SetFillStyle(    0 );
  ext2->SetTextAlign(   12 );
  ext2->SetTextSize ( 0.035 );
  ext2->SetTextColor(    1 );
  ext2->SetTextFont (   42 );
  ext2->AddText("#sqrt{s} = 8 TeV, L = 19.4 fb^{-1}");
  ext2->Draw();
  
  TPaveText* ext3     = new TPaveText(0.50, lower_bound-0.23, 0.70, lower_bound-0.18, "NDC");
  ext3->SetBorderSize(   0 );
  ext3->SetFillStyle(    0 );
  ext3->SetTextAlign(   12 );
  ext3->SetTextSize ( 0.035 );
  ext3->SetTextColor(    1 );
  ext3->SetTextFont (   42 );
  ext3->AddText("H#rightarrow#tau#tau");
  ext3->Draw();
  */

  /*
    prepare output
  */
  std::string newName = std::string(inputfile).substr(0, std::string(inputfile).find(".root"));
  //canv->Print(TString::Format("%s%s.png", newName.c_str(), log ? "_LOG" : "")); 
  //canv->Print(TString::Format("%s%s.pdf", newName.c_str(), log ? "_LOG" : "")); 
  //canv->Print(TString::Format("%s%s.eps", newName.c_str(), log ? "_LOG" : "")); 
  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())); 
}