Ejemplo n.º 1
0
TH2F* loadHistogram2D(
    const std::vector<std::string>& fileList, 
    const std::string& histName, 
    const std::string& sys, 
    double scale,
    int rebinX,
    int rebinY
    )
{
    TH2F* result = nullptr;
    for (const std::string& file: fileList)
    {
        TFile input(file.c_str(),"r");
        
        TH2F* hist=nullptr;
        if ((sys=="") and input.FindKey(histName.c_str()))
        {
            hist = static_cast<TH2F*>(input.Get(histName.c_str()));
        }
        else if (input.FindKey((histName+"__"+sys).c_str()))
        {
            hist = static_cast<TH2F*>(input.Get((histName+"__"+sys).c_str()));
        }
        else if (input.FindKey((histName+"__nominal").c_str()))
        {
            log(WARNING,"using fallback '%s' for '%s'\n",(histName+"__nominal").c_str(),(histName+"__"+sys).c_str());
            hist = static_cast<TH2F*>(input.Get((histName+"__nominal").c_str()));
        }
        else
        {
            log(ERROR,"neither '%s', '%s' nor '%s' found in file '%s'\n",histName.c_str(),(histName+"__nominal").c_str(),(histName+"__"+sys).c_str(),file.c_str());
            continue;
        }
        hist->Scale(scale);
        
        hist->Rebin2D(hist->GetNbinsX()/rebinX,hist->GetNbinsY()/rebinY);
        if (!result)
        {
            result = new TH2F(*hist);
            result->Sumw2();
            result->SetDirectory(0);
        }
        else
        {
            result->Add(hist);
        }
    }
    if (!result)
    {
        log(CRITICAL,"Error while finding histogram '"+histName+"' with sys '"+sys+"' in given files");
        throw std::string("Error while finding histogram '"+histName+"' with sys '"+sys+"' in given files");
    }
    return result;
}
TGraph* ContourGraph( TH2F* hist,double xmin=16, double xmax=90) {

    //temporary canvas
    TCanvas* MOO = new TCanvas( TString::Format("dummy_canvas_%s", hist->GetName()), "A scan of m_{0} versus m_{12}", 0, 0, 650,640);
    MOO->cd();

    TGraph* gr0 = new TGraph();
    TH2F* h = (TH2F*)hist->Clone();
    TGraph* gr = (TGraph*)gr0->Clone(TString::Format("gr_%s", h->GetName()));

    cout << "==> Will dumb histogram: " << h->GetName() << " into a graph" <<endl;

    h->SetContour( 1 );
    //h->GetXaxis()->SetRangeUser(250,1200);
    h->GetXaxis()->SetRangeUser(xmin, xmax);
    //h->GetYaxis()->SetRangeUser(2,50);

    double pval = CombinationGlob::cl_percent[1];
    std::cout << pval << std::endl; 
    double signif = TMath::NormQuantile(1-pval);
    h->SetContourLevel( 0, signif );
    h->Draw("CONT LIST");
    h->SetDirectory(0);
    gPad->Update();

    TObjArray *contours = (TObjArray*) gROOT->GetListOfSpecials()->FindObject("contours");
    Int_t ncontours     = contours->GetSize();
    cout << "Found " << ncontours << " contours " << endl;

    TList *list = (TList*)contours->At(0);
    contours->Print("v");
    if(!list) return NULL;

    gr = (TGraph*)list->First();
    if(!gr) return NULL;

    gr->SetName(TString::Format("gr_%s", hist->GetName()));
    //gr->SetName(hist->GetName());
    int N = gr->GetN();
    double x0, y0;
    for(int j=0; j<N; j++) {
        gr->GetPoint(j,x0,y0);
        cout << j << " : " << x0 << " : "<<y0 << endl;
    }
    //  //  gr->SetMarkerSize(2.0);    
    //gr->Draw("ALP");

    delete MOO;

    cout << "Generated graph " << gr << " with name " << gr->GetName() << endl;
    return gr;
}
void make(TDirectory & out, TObject * o) {
  TDirectory * dir;
  TH1F * th1f;
  TH1D * th1d;
  TH2F * th2f;
  TH2D * th2d;
  out.cd();
  if((dir = dynamic_cast<TDirectory*>(o)) != 0) {
    TDirectory * outDir = out.mkdir(dir->GetName(), dir->GetTitle());
    TIter next(dir->GetListOfKeys());
    TKey *key;
    while( (key = dynamic_cast<TKey*>(next())) ) {
      string className(key->GetClassName());
      string name(key->GetName());
      TObject * obj = dir->Get(name.c_str());
      if(obj == 0) {
	cerr <<"error: key " << name << " not found in directory " << dir->GetName() << endl;
	exit(-1);
      }
      make(*outDir, obj);
    }
  } else if((th1f = dynamic_cast<TH1F*>(o)) != 0) {
    TH1F *h = (TH1F*) th1f->Clone();
    h->Reset();
    h->Sumw2();
    h->SetDirectory(&out);
  } else if((th1d = dynamic_cast<TH1D*>(o)) != 0) {
    TH1D *h = (TH1D*) th1d->Clone();
    h->Reset();
    h->Sumw2();
    h->SetDirectory(&out);
  } else if((th2f = dynamic_cast<TH2F*>(o)) != 0) {
    TH2F *h = (TH2F*) th2f->Clone();
    h->Reset();   
    h->Sumw2();
    h->SetDirectory(&out);
  } else if((th2d = dynamic_cast<TH2D*>(o)) != 0) {
    TH2D *h = (TH2D*) th2d->Clone();
    h->Reset();   
    h->Sumw2();
    h->SetDirectory(&out);
  }
}
    TGraph*
ContourGraph( TH2F* hist)
{
    TGraph* gr0 = new TGraph();
    TH2F* h = (TH2F*)hist->Clone();
    gr = (TGraph*)gr0->Clone(h->GetName());
    //  cout << "==> Will dumb histogram: " << h->GetName() << " into a graph" <<endl;
    h->SetContour( 1 );
    double pval = CombinationGlob::cl_percent[1];
    double signif = TMath::NormQuantile(1-pval);
    h->SetContourLevel( 0, signif );
    h->Draw("CONT LIST");
    h->SetDirectory(0);
    gPad->Update();
    TObjArray *contours = gROOT->GetListOfSpecials()->FindObject("contours");
    Int_t ncontours     = contours->GetSize();
    TList *list = (TList*)contours->At(0);
    Int_t number_of_lists = list->GetSize();
    gr = (TGraph*)list->At(0);
    TGraph* grTmp = new TGraph();
    for (int k = 0 ; k<number_of_lists ; k++){
        grTmp = (TGraph*)list->At(k);
        Int_t N = gr->GetN();
        Int_t N_tmp = grTmp->GetN();
        if(N < N_tmp) gr = grTmp;
        //    mg->Add((TGraph*)list->At(k));
    }

    gr->SetName(hist->GetName());
    int N = gr->GetN();
    double x0, y0;

    //  for(int j=0; j<N; j++) {
    //    gr->GetPoint(j,x0,y0);
    //    cout << j << " : " << x0 << " : "<<y0 << endl;
    //  }
    //  //  gr->SetMarkerSize(2.0);
    //  gr->SetMarkerSize(2.0);
    //  gr->SetMarkerStyle(21);
    //  gr->Draw("LP");
    //  cout << "Generated graph " << gr << " with name " << gr->GetName() << endl;
    return gr;
}
Ejemplo n.º 5
0
TH2F* SusyLeptonSF::GetHistogramFromFileF(const char* filename, 
				      const char* histoname, 
				      const char* newhname) const {
  TFile* file  = TFile::Open(filename);
  if (!file) {
      std::cerr << "ERROR[SusyLeptonSF]: Could not load file" << std::endl
		<< "                 " << filename << std::endl;
      return 0;
  }
  TH2F* h = (TH2F*) file->Get(histoname)->Clone(newhname);
  if (!h) {
    std::cerr << "ERROR[SusyLeptonSF]: Could not find histogram " 
	      << histoname << std::endl;
    return 0;
    }
  h->SetDirectory(0);
  file->Close();
 
  return h;
}
Ejemplo n.º 6
0
//------------------------------------------------------------------------------
// DrawIt
//------------------------------------------------------------------------------
void DrawIt(TString filename,
	    TString hname,
	    TString cname,
	    TString title)
{
  TFile* inputfile = TFile::Open("../AuxiliaryFilesWZXS8TeV/" + filename + ".root");

  TH2F* h = (TH2F*)inputfile->Get(hname)->Clone(cname);

  h->SetDirectory(0);

  inputfile->Close();

  TString name = h->GetName();

  TCanvas* canvas = new TCanvas(name, name, 600, 600);

  if (name.Contains("PR")) canvas->SetLogx();
  if (name.Contains("SF")) canvas->SetLogx();

  canvas->SetLeftMargin (0.9 * canvas->GetLeftMargin());
  canvas->SetRightMargin(3.5 * canvas->GetRightMargin());
  canvas->SetTopMargin  (1.2 * canvas->GetTopMargin());

  TH2FAxisFonts(h, "x", "p_{T} [GeV]");
  TH2FAxisFonts(h, "y", "#eta");

  h->Draw("colz");

  h->SetTitle("");

  DrawTLatex(42, 0.940, 0.976, _bigLabelSize, 33, title);

  if (!title.Contains("trigger")) {

    Double_t hmin = h->GetMinimum();
    Double_t hmax = h->GetMaximum();

    for (Int_t i=1; i<=h->GetNbinsX(); i++) {
      for (Int_t j=1; j<=h->GetNbinsY(); j++) {

	Double_t value = h->GetBinContent(i,j);

	Double_t ypos = h->GetYaxis()->GetBinCenter(j);
	Double_t xpos = h->GetXaxis()->GetBinCenter(i);
      
	if (gPad->GetLogx()) xpos = h->GetXaxis()->GetBinCenterLog(i);

	TLatex* latex = new TLatex(xpos, ypos, Form("%.2f", value));

	latex->SetTextAlign(   22);
	latex->SetTextFont (   42);
	latex->SetTextSize (0.027);

	if (value < hmin + 0.3*(hmax - hmin)) latex->SetTextColor(kWhite);
	
	latex->Draw();
      }
    }
  }


  // Set the palette font
  //----------------------------------------------------------------------------
  canvas->Update();

  TPaletteAxis* palette = (TPaletteAxis*)h->GetListOfFunctions()->FindObject("palette");

  palette->SetLabelFont(42);


  // Save the plot
  //----------------------------------------------------------------------------
  canvas->Update();
  
  canvas->Modified();

  canvas->GetFrame()->DrawClone();

  canvas->SaveAs("pdf/scale_factors/" + name + ".pdf");
  canvas->SaveAs("png/scale_factors/" + name + ".png");
}
//*************************************************************************************************
//Main part of the macro
//*************************************************************************************************
void NormalizeElectronNtuple(const string InputFilename, const string datasetName, 
                             const string OutputFilename, Int_t sampleType, 
                             const string normalizationFile = "") {


  Double_t normalizationWeight = 0;
  Bool_t useReweightFactor = kFALSE;
  TH2F *PtEtaReweightFactor = 0;
  Double_t overallWJetsNormalizationFactor = 0;

  //For Normalizing each sample individually
  if (sampleType == 0 || sampleType >= 10) {
    TTree* electronTree = getTreeFromFile(InputFilename.c_str());
    assert(electronTree);    
    MitNtupleElectron ele(electronTree);
    
    normalizationWeight = getNormalizationWeight(InputFilename, datasetName);
    //*************************************************************************************************
    //Create new normalized tree
    //*************************************************************************************************
    TFile *outputFile = new TFile(OutputFilename.c_str(), "RECREATE");
    outputFile->cd();    
    TTree *normalizedTree = electronTree->CloneTree(0);
    
    for (int n=0;n<electronTree->GetEntries();n++) { 
      ele.GetEntry(n);

      if (sampleType == 10) {
        if (ele.electron_branch_passedSelectionCut == 1) {
          if (datasetName == "s09-wwll10-mc3" || datasetName == "s09-ttbar-mc3") {
            //for mu-e there should be only 1 electron candidate
            ele.electron_branch_weight = normalizationWeight; 
            normalizedTree->Fill(); 
          } else if (datasetName == "s09-we-mc3" || datasetName == "s09-wm-mc3" || datasetName == "s09-wt-mc3") {
            //For the W->enu sample, fill only the fake electron candidates.
            ele.electron_branch_weight = normalizationWeight; 
            if (ele.electron_branch_electronType < 100) {
              normalizedTree->Fill(); 
            }
          } else {
            cout << "Warning: The specified dataset " << datasetName 
                 << " is not recognized to be one of the selection cut samples.\n";
          }
        }        
      } else {
        //For regular samples just fill all electrons
        ele.electron_branch_weight = normalizationWeight; 
        normalizedTree->Fill(); 
      }      
    }
    normalizedTree->Write();
    cout << "Original Tree Entries: " << electronTree->GetEntries() << "  Normalized Tree Entries: " << normalizedTree->GetEntries() << endl;
    outputFile->Close();     
  }
  //For Normalization of Background sample
  else if (sampleType == 1) {
    TTree* electronTree = getTreeFromFile(InputFilename.c_str(), kFALSE);
    assert(electronTree);     
    MitNtupleElectron ele(electronTree);

    //*************************************************************************************************
    //Create new reweighted tree
    //*************************************************************************************************
    TFile *outputFile = new TFile(OutputFilename.c_str(), "RECREATE");
    TTree *reweightedTree = electronTree->CloneTree(0);    

    if (normalizationFile == "") {
      //normalize according to total number of electrons expected in W+Jets/W+gamma bkg
      Double_t totalWeight = 0;
      for (int n=0;n<electronTree->GetEntries();n++) { 
        ele.GetEntry(n);
        totalWeight += ele.electron_branch_weight;
      }

      cout << "Input Bkg Ntuple Total Weight = " << totalWeight << endl;
      normalizationWeight = 1126.5 / totalWeight;
    } else {
      //do pt/eta Reweighting

      TFile *reweightInputFile = new TFile(normalizationFile.c_str(), "READ");
      assert(reweightInputFile);

      TH2F *WJetsFakeElectronPtEta = (TH2F*)reweightInputFile->Get("hWJetsFakeElectronPtEta");
      assert(WJetsFakeElectronPtEta);      
      WJetsFakeElectronPtEta = (TH2F*)(WJetsFakeElectronPtEta->Clone());
      WJetsFakeElectronPtEta->SetDirectory(0);
      reweightInputFile->Close();

      //Create histogram for reweighting factor
      PtEtaReweightFactor = (TH2F*)WJetsFakeElectronPtEta->Clone();
      PtEtaReweightFactor->SetName("PtEtaReweightFactor");
      PtEtaReweightFactor->SetDirectory(0);

      TH2F *BkgFakeElectronPtEta = new TH2F("BkgFakeElectronPtEta", ";Pt [GeV/c];#eta;" , WJetsFakeElectronPtEta->GetXaxis()->GetNbins(), WJetsFakeElectronPtEta->GetXaxis()->GetBinLowEdge(1), WJetsFakeElectronPtEta->GetXaxis()->GetBinUpEdge(WJetsFakeElectronPtEta->GetXaxis()->GetNbins()), WJetsFakeElectronPtEta->GetYaxis()->GetNbins(), WJetsFakeElectronPtEta->GetYaxis()->GetBinLowEdge(1), WJetsFakeElectronPtEta->GetYaxis()->GetBinUpEdge(WJetsFakeElectronPtEta->GetYaxis()->GetNbins()));
      BkgFakeElectronPtEta->SetDirectory(0);
      for (int n=0;n<electronTree->GetEntries();n++) { 
        ele.GetEntry(n);
        BkgFakeElectronPtEta->Fill(ele.electron_branch_pt, ele.electron_branch_eta, ele.electron_branch_weight);        
      }
      PtEtaReweightFactor->Divide(WJetsFakeElectronPtEta, BkgFakeElectronPtEta, 1.0,1.0,"B");

      useReweightFactor = kTRUE;    
    }

    cout << "Reweighting Background Ntuple\n";
    outputFile->cd();    

    //check Reweighting
    TH2F *ReweightedBkgFakeElectronPtEta = new TH2F("BkgFakeElectronPtEta", ";Pt [GeV/c];#eta;" , 200, 0, 200, 200, -3.0, 3.0);    
    ReweightedBkgFakeElectronPtEta->SetDirectory(0);
    for (int n=0;n<electronTree->GetEntries();n++) { 
      if (n%250000 == 0) cout << "Entry " << n << endl;
      ele.GetEntry(n);
      if (useReweightFactor) {
        Double_t reweightFactor = PtEtaReweightFactor->GetBinContent(PtEtaReweightFactor->GetXaxis()->FindFixBin(ele.electron_branch_pt),PtEtaReweightFactor->GetYaxis()->FindFixBin(ele.electron_branch_eta));
        ele.electron_branch_weight = ele.electron_branch_weight*reweightFactor;//*overallWJetsNormalizationFactor;
      } else {
        ele.electron_branch_weight = normalizationWeight;
      }
      reweightedTree->Fill(); 

      ReweightedBkgFakeElectronPtEta->Fill(ele.electron_branch_pt, ele.electron_branch_eta, ele.electron_branch_weight);
    }
    reweightedTree->Write();
    cout << "Original Tree Entries: " << electronTree->GetEntries() << "  Normalized Tree Entries: " << reweightedTree->GetEntries() << endl;
    outputFile->Close();
  
    TCanvas *cv = new TCanvas("BkgReweightedFakeElectronPtEta", "BkgReweightedFakeElectronPtEta", 0,0,800,600);
    ReweightedBkgFakeElectronPtEta->ProjectionX()->DrawCopy("E1");
    cv->SaveAs("BkgReweightedFakeElectronPt.gif");
    ReweightedBkgFakeElectronPtEta->ProjectionY()->DrawCopy("E1");
    cv->SaveAs("BkgReweightedFakeElectronEta.gif");
  } 
  
  //For Normalization of Signal sample
  else if (sampleType == 2) {
    TTree* electronTree = getTreeFromFile(InputFilename.c_str(), kFALSE);
    assert(electronTree);     
    MitNtupleElectron ele(electronTree);

    //*************************************************************************************************
    //Create new reweighted tree
    //*************************************************************************************************
    TFile *outputFile = new TFile(OutputFilename.c_str(), "RECREATE");
    TTree *reweightedTree = electronTree->CloneTree(0);    

    if (normalizationFile == "") {
      //normalize according to total number of electrons expected in WW -> ee nunu signal
      Double_t totalWeight = 0;
      for (int n=0;n<electronTree->GetEntries();n++) { 
        ele.GetEntry(n);
        totalWeight += ele.electron_branch_weight;
      }

      cout << "Input Bkg Ntuple Total Weight = " << totalWeight << endl;
      normalizationWeight = 1126.5 / totalWeight;
    } else {
      //do pt/eta Reweighting

      TFile *reweightInputFile = new TFile(normalizationFile.c_str(), "READ");
      assert(reweightInputFile);
      TH2F *WWSigElectronPtEta = (TH2F*)reweightInputFile->Get("hWWRealElectronPtEta");
      assert(WWSigElectronPtEta);      
      WWSigElectronPtEta = (TH2F*)(WWSigElectronPtEta->Clone());
      WWSigElectronPtEta->SetDirectory(0);
      reweightInputFile->Close();

      //Create histogram for reweighting factor
      PtEtaReweightFactor = (TH2F*)WWSigElectronPtEta->Clone();
      PtEtaReweightFactor->SetName("PtEtaReweightFactor");
      PtEtaReweightFactor->SetDirectory(0);

      TH2F *SigSampleElectronPtEta = new TH2F("SigSampleElectronPtEta", ";Pt [GeV/c];#eta;" , WWSigElectronPtEta->GetXaxis()->GetNbins(), WWSigElectronPtEta->GetXaxis()->GetBinLowEdge(1), WWSigElectronPtEta->GetXaxis()->GetBinUpEdge(WWSigElectronPtEta->GetXaxis()->GetNbins()), WWSigElectronPtEta->GetYaxis()->GetNbins(), WWSigElectronPtEta->GetYaxis()->GetBinLowEdge(1), WWSigElectronPtEta->GetYaxis()->GetBinUpEdge(WWSigElectronPtEta->GetYaxis()->GetNbins()));
      SigSampleElectronPtEta->SetDirectory(0);
      for (int n=0;n<electronTree->GetEntries();n++) { 
        ele.GetEntry(n);
        SigSampleElectronPtEta->Fill(ele.electron_branch_pt, ele.electron_branch_eta, ele.electron_branch_weight);        
      }
      PtEtaReweightFactor->Divide(WWSigElectronPtEta, SigSampleElectronPtEta, 1.0,1.0,"B");

      useReweightFactor = kTRUE;    
    }

    cout << "Reweighting Signal Ntuple\n";
    outputFile->cd();    

    //check Reweighting
    TH2F *ReweightedSigRealElectronPtEta = new TH2F("ReweightedSigRealElectronPtEta", ";Pt [GeV/c];#eta;" , 200, 0, 200, 200, -3.0, 3.0);    
    ReweightedSigRealElectronPtEta->SetDirectory(0);
    for (int n=0;n<electronTree->GetEntries();n++) { 
      if (n%250000 == 0) cout << "Entry " << n << endl;
      ele.GetEntry(n);
      if (useReweightFactor) {
        Double_t reweightFactor = PtEtaReweightFactor->GetBinContent(PtEtaReweightFactor->GetXaxis()->FindFixBin(ele.electron_branch_pt),PtEtaReweightFactor->GetYaxis()->FindFixBin(ele.electron_branch_eta));
        ele.electron_branch_weight = ele.electron_branch_weight*reweightFactor;//*overallWJetsNormalizationFactor;
      } else {
        ele.electron_branch_weight = normalizationWeight;
      }
      reweightedTree->Fill(); 
      ReweightedSigRealElectronPtEta->Fill(ele.electron_branch_pt, ele.electron_branch_eta, ele.electron_branch_weight);
    }
    reweightedTree->Write();
    cout << "Original Tree Entries: " << electronTree->GetEntries() << "  Normalized Tree Entries: " << reweightedTree->GetEntries() << endl;
    outputFile->Close();
  
    TCanvas *cv = new TCanvas("BkgReweightedFakeElectronPtEta", "BkgReweightedFakeElectronPtEta", 0,0,800,600);
    ReweightedSigRealElectronPtEta->ProjectionX()->DrawCopy("E1");
    cv->SaveAs("SigReweightedRealElectronPt.gif");
    ReweightedSigRealElectronPtEta->ProjectionY()->DrawCopy("E1");
    cv->SaveAs("SigReweightedRealElectronEta.gif");
  } 
  else {
    cout << "Warning: Specified sampleType " << sampleType << " is not recognized.\n";
  }



}
void SUSY_bRPV_m0_vs_m12_all_withBand_cls( TString fname0="", TString fname1="",
        TString fname2="",
        TString gridname="",
        const char* prefix="test",
        const float& lumi = 20.3,
        bool showsig = true,
        int discexcl = 1,
        int showtevatron = 0,
        int showcms = 0,
        int showOneSigmaExpBand = 0,
        bool showSR = false,
        bool useShape = false,
        int channel = -1,
        TString hname0 = "sigp1clsf",
        TString hname1 = "sigp1expclsf",
        TString hname3 = "sigclsu1s",
        TString hname5 = "sigclsd1s",
        TString hname6 = "sigp1ref",
        TString fnameMass= "contourmacros/mSugraGridtanbeta10_gluinoSquarkMasses.root")
{
    // set style and remove existing canvas'
    CombinationGlob::Initialize();

    cout << "--- Plotting m0 versus m12 " << endl;

    // --- prepare
    // open reference files, and retrieve histogram
    cout << "--- Reading root base file: " << fname0 << endl;
    TFile* f0 = TFile::Open( fname0, "READ" );
    if (!f0) {
        cout << "*** Error: could not retrieve histogram: " << hname0 << " in file: " << f0->GetName() 
            << " ==> abort macro execution" << endl;
        return;
    }
    
    TFile *f1; TFile *f2;

    if(fname1 != "")
        f1 = TFile::Open( fname1, "READ" );
        if(!f1) cout << "Warning: could not open " << fname1 << endl;
    if(fname2 != "")
        f2 = TFile::Open( fname2, "READ" );
        if(!f2) cout << "Warning: could not open " << fname2 << endl;

    TH2F* histecls = (TH2F*)f0->Get( "sigp1expclsf" ); 
    TH2F* histocls = (TH2F*)f0->Get( "sigp1clsf" ); 
    if (histecls!=0) histecls->SetDirectory(0);
    if (histocls!=0) histocls->SetDirectory(0);

    TH2F* histe_esigxsp1s;
    if (fname1 != "" && f1)  {
        histe_esigxsp1s = (TH2F*)f1->Get( hname0 );
        cout << "Read up histogram " << histe_esigxsp1s << endl;
    }

    TH2F* histe_esigxsm1s;
    if (fname2 != "" && f2) { 
        histe_esigxsm1s = (TH2F*)f2->Get( hname0 ); 
        cout << "Read down histogram " << histe_esigxsm1s << endl;
    }

    if (histe_esigxsp1s!=0) histe_esigxsp1s->SetDirectory(0);
    if (histe_esigxsm1s!=0) histe_esigxsm1s->SetDirectory(0);

    TH2F* contour_esigxsp1s
        = ( histe_esigxsp1s!=0 ? FixAndSetBorders( *histe_esigxsp1s, "contour_esigxsp1s", "contour_esigxsp1s", 0 ) : 0);
    TH2F* contour_esigxsm1s
        = ( histe_esigxsm1s!=0 ? FixAndSetBorders( *histe_esigxsm1s, "contour_esigxsm1s", "contour_esigxsm1s", 0 ) : 0);

    //    TFile* f3 = TFile::Open( fname3, "READ" );
    TH2F* histe(0);
    TH2F* histe_u1s(0);
    TH2F* histe_d1s(0);

    //    TFile* f4 = TFile::Open( fname4, "READ" );

    bool extExpectation = 0;

    TH2F* hist0 = (TH2F*)f0->Get( hname0 );
    TH2F* hist1 = (TH2F*)f0->Get( hname1 );
    TH2F* hist3 = (TH2F*)f0->Get( hname3 );
    TH2F* hist5 = (TH2F*)f0->Get( hname5 );
    TH2F* hist6 = (TH2F*)f0->Get( hname6 );



    if (hist0!=0) hist0->SetDirectory(0);
    if (hist1!=0) hist1->SetDirectory(0);
    if (hist3!=0) hist3->SetDirectory(0);
    if (hist5!=0) hist5->SetDirectory(0);
    if (hist6!=0) hist6->SetDirectory(0);
    f0->Close();

    TH2F* histe_esigxsp1s; 
    if (fname1!="" && f1) histe_esigxsp1s  = (TH2F*)f1->Get( hname0 ); 
    TH2F* histe_esigxsm1s; 
    if (fname2!="" && f2) histe_esigxsm1s  = (TH2F*)f2->Get( hname0 ); 

    if (fname1!="" &&histe_esigxsp1s!=0) histe_esigxsp1s->SetDirectory(0);
    if (fname2!="" && histe_esigxsm1s!=0) histe_esigxsm1s->SetDirectory(0);

    TH2F* contour_esigxsp1s
        = ( histe_esigxsp1s!=0 ? FixAndSetBorders( *histe_esigxsp1s, "contour_esigxsp1s", "contour_esigxsp1s", 0 ) : 0);
    TH2F* contour_esigxsm1s
        = ( histe_esigxsm1s!=0 ? FixAndSetBorders( *histe_esigxsm1s, "contour_esigxsm1s", "contour_esigxsm1s", 0 ) : 0);

    TH2F* contour         = ( hist1!=0 ? FixAndSetBorders( *hist1, "contour", "contour", 0 ) : 0);
    TH2F* contour_obs     = ( hist0!=0 ? FixAndSetBorders( *hist0, "contour_obs", "contour_obs") : 0 );

    TH2F* contour_ep1s    = ( hist3!=0 ? FixAndSetBorders( *hist3, "contour", "contour", 0 ) : 0 );
    TH2F* contour_em1s    = ( hist5!=0 ? FixAndSetBorders( *hist5, "contour", "contour", 0 ) : 0 );

    // For Band
    if (showOneSigmaExpBand){
        TGraph* gr_contour_ep1s = ContourGraph( contour_ep1s )->Clone(); 
        TGraph* gr_contour_em1s= ContourGraph( contour_em1s )->Clone(); 
    }
    TH2F* contour_exp(0);
    if (histe!=0)     { contour_exp     = FixAndSetBorders( *histe, "contour_exp", "contour_exp", 0 ); } 
    TH2F* contour_au1s(0);
    if (histe_u1s!=0) {  contour_au1s   = FixAndSetBorders( *histe_u1s, "contour", "contour", 0 ); }
    TH2F* contour_ad1s(0);
    if (histe_d1s!=0) {  contour_ad1s   = FixAndSetBorders( *histe_d1s, "contour", "contour", 0 ); }


    TH2F* contour_expcls(0);
    if (histecls!=0)     { contour_expcls     = FixAndSetBorders( *histecls, "contour_expcls", "contour_expcls", 0 ); }
    TH2F* contour_obscls(0);
    if (histocls!=0)     { contour_obscls     = FixAndSetBorders( *histocls, "contour_obscls", "contour_obscls", 0 ); }


    if (contour_obs==0) { 
        cout << "contour is zero" << endl;
        return;
    }

    // set text style
    gStyle->SetPaintTextFormat(".2g");
    if (hist1!=0) hist1->SetMarkerStyle(21);
    if (hist1!=0) hist1->SetMarkerSize(1.5);
    Float_t nsigmax(0)
        if (hist1!=0) nsigmax = hist1->GetMaximum();

    // --- draw

    // create canvas
    TCanvas* c = new TCanvas( "c", "A scan of "+gridname, 0, 0, 
            CombinationGlob::StandardCanvas[0], CombinationGlob::StandardCanvas[1] );  
    //c->SetGrayscale();

    // create and draw the frame
    double plotrange=2250.;
    TH2F *frame = new TH2F("frame", "m_{gluino} vs. m_{lsp} - ATLAS work in progress", 100, 350.,plotrange, 100, 200., 900. );
    // set common frame style
    CombinationGlob::SetFrameStyle2D( frame, 1.0 ); // the size (scale) is 1.0
    
    frame->SetXTitle( "m_{0} [GeV]" );
    frame->SetYTitle( "m_{1/2} [GeV]" );
    frame->GetYaxis()->SetTitleOffset(1.35);

    //frame->SetTextFont( 42 );
    frame->GetXaxis()->SetTitleFont( 42 );
    frame->GetYaxis()->SetTitleFont( 42 );
    frame->GetXaxis()->SetLabelFont( 42 );
    frame->GetYaxis()->SetLabelFont( 42 );

    frame->GetXaxis()->SetTitleSize( 0.04 );
    frame->GetYaxis()->SetTitleSize( 0.04 );
    frame->GetXaxis()->SetLabelSize( 0.04 );
    frame->GetYaxis()->SetLabelSize( 0.04 );

    frame->Draw();

    const int nsig(3);
    //TH2F *chist[3];
    // draw contours
    //!instead of printing sigma in 68% 95% 98% levels now printing +1 sigma deviations 
    //for (Int_t nsigma=1; nsigma<=nsig; nsigma++)
    //  DrawContourSameColor( contour, nsigma, "blue", kFALSE, (nsigma==1?inverse:0) ) ;

    TString basecolor="yellow";
    Int_t nsigma=2;

    TLegend *leg = new TLegend(0.6,0.7,0.92,0.9);

    leg->SetTextSize( CombinationGlob::DescriptionTextSize );
    leg->SetTextSize( 0.03 );
    leg->SetTextFont( 42 );
    leg->SetFillColor( 0 );
    leg->SetFillStyle(1001);

    if (false && channel==1) { // electron

        cout << "removing islands in electron channel ..." << endl;
        // contour line is drawn for values at 1.64485
        TAxis* ax = contour_obs->GetXaxis();
        TAxis* ay = contour_obs->GetYaxis();
        /*     
               contour_em1s

               for (int xbin = 1; xbin <= contour_obs->GetNbinsX(); xbin++) {
               for (int ybin = 1; ybin <= contour_obs->GetNbinsY(); ybin++) {
        // island 2
        if ( ax->GetBinCenter( xbin) > 420. && ax->GetBinCenter( xbin) < 480. &&
        ay->GetBinCenter( ybin) > 140. && ay->GetBinCenter( ybin) < 160. ) {
        cout << "Found spot here: " << xbin << " (" << ax->GetBinCenter( xbin)  << "), "
        << ybin << " (" << ay->GetBinCenter( ybin) << "), "
        << " value: " << contour->GetBinContent(xbin,ybin) <<   endl;
        cout << "   HACK : Setting above point by hand to 1.50 (!)" << endl;
        contour->SetBinContent(xbin, ybin, 1.50);
        }
        }
        }
        */

    }

    if (false && channel==2) { // combined
        cout << "removing islands in combined channel ..." << endl;
    }


    /////////////////////////////////////////////////////////
    //// add 2011 results 


    Int_t c_myYellow   = TColor::GetColor("#ffe938");
    Int_t c_myRed      = TColor::GetColor("#aa000");

    // turn off yellow band    
    if (showOneSigmaExpBand) TGraph* grshadeExp= DrawExpectedBand( gr_contour_ep1s, gr_contour_em1s, CombinationGlob::c_DarkYellow , 1001 , 0)->Clone();


    if (discexcl==1) {
        DrawContourLine95( leg, contour_obs,     "Observed limit (#pm1 #sigma^{SUSY}_{theory})", c_myRed, 1, 4 );   // 95% CL_{S}
        
        
        if (contour_esigxsp1s)
            DrawContourLine95( leg, contour_esigxsp1s, "", c_myRed, 3, 2 );    // Observed limit #pm 1 #sigma^{SUSY}_{theory}
        if (contour_esigxsm1s)
            DrawContourLine95( leg, contour_esigxsm1s, "", c_myRed, 3, 2 );    // Observed limit #pm 1 #sigma^{SUSY}_{theory}
        
        if (!extExpectation) { 
            // Compare the expected limits!
            if (contour_expcls!=0) { 
                //DrawContourLine95( leg, contour_expcls, fname0, CombinationGlob::c_DarkGray, 6 );
                DrawContourLine95( leg, contour_expcls, fname0, CombinationGlob::c_DarkBlueT3, 6 );
            }
            
            if (showOneSigmaExpBand) {
                if (contour_ep1s!=0) {	   
                    DrawContourLine95( leg, contour_ep1s, "", c_myYellow, 1 ); 
                }

                if (contour_em1s!=0)  {	   
                    DrawContourLine95( leg, contour_em1s, "", c_myYellow, 1 );
                }
                DummyLegendExpected(leg, "Expected limit (#pm1 #sigma_{exp})", c_myYellow, 1001, CombinationGlob::c_DarkBlueT3, 6, 2);

            } else {
                //if (contour!=0) DrawContourLine68( leg, contour, "exp. limit 68% CL", CombinationGlob::c_DarkBlueT3, 2 );
                //if (contour!=0) DrawContourLine99( leg, contour, "exp. limit 99% CL", CombinationGlob::c_DarkBlueT3, 3 );
            }

        } else { // expectation from asimov
            if (contour_exp!=0) DrawContourLine95( leg, contour_exp, "Median expected limit", CombinationGlob::c_DarkBlueT3, 6);
            if (showOneSigmaExpBand) {
                if (contour_au1s!=0) DrawContourLine95( leg, contour_au1s, "Expected limit #pm1#sigma", CombinationGlob::c_DarkBlueT3, 3 );
                if (contour_ad1s!=0) DrawContourLine95( leg, contour_ad1s, "", CombinationGlob::c_DarkBlueT3, 3 );
            }
        }
    }


    // plot tevatron limits
    TGraph* lep2slep(0);
    TGraph* lep2char(0);
    TGraph* d0o(0);
    TGraph* d0graph(0);
    TGraph* cdfgraph(0);
    TGraph* atlas(0);
    TGraph* atlasexp(0);

    if (showtevatron==1 && discexcl==1) {
        lep2char = ol1();
        d0graph = d0tanb3muneg();
        cdfgraph = cdftanb5();
        //atlas = ATLAS10_1lepton();
        //atlasexp = ATLAS10_1leptonexp();
    }

    //:w(void) stautanb3();

    TGraph* cmscurve(0);
    if (showcms==1) { 
        //cmscurve = cmsoff();
        cmscurve = cms();
    }


    // legend
    Float_t textSizeOffset = +0.000;
    Double_t xmax = frame->GetXaxis()->GetXmax();
    Double_t xmin = frame->GetXaxis()->GetXmin();
    Double_t ymax = frame->GetYaxis()->GetXmax();
    Double_t ymin = frame->GetYaxis()->GetXmin();
    Double_t dx   = xmax - xmin;
    Double_t dy   = ymax - ymin;

    //TString t1a = "99%, 95%, 68% CL fit contour (excluded)" ;
    // TString t1a = "-1#sigma, central, +1#sigma  fit contour (excluded)" ;
    TString t1b = "tan#beta = 3, A_{0}= 0, #mu < 0" ;
    Float_t nbkg(0);
    if( hist5!=0) nbkg = hist5->GetMaximum();
    TString t1c = Form("MC: n_{bkg}= %.1f", nbkg) ;

    // TLatex* text1a = new TLatex( 70, 260, t1a );
    TLatex* text1b = new TLatex( 150, ymax + dy*0.025, t1b );
    TLatex* text1c = new TLatex( 70, 280, t1c );

    // text1a->SetTextColor( 1 ); //CombinationGlob::c_VDarkGreen );
    text1b->SetTextColor( 1 ); //CombinationGlob::c_VDarkGreen );
    text1c->SetTextColor( 1 );
    text1b->SetTextFont( 42 ); //CombinationGlob::c_VDarkGreen );

    // text1a->SetTextAlign( 11 );
    text1b->SetTextAlign( 11 );
    text1c->SetTextAlign( 11 );

    //  text1a->SetTextSize( CombinationGlob::DescriptionTextSize + textSizeOffset );
    text1b->SetTextSize( CombinationGlob::DescriptionTextSize  );
    text1c->SetTextSize( CombinationGlob::DescriptionTextSize  );
    
    TString plottitle="bRPV-MSUGRA: tan #beta = 30, A_{0}= -2m_{0}, #mu>0";
    
    if(showSR){
        std::cout << "--- printing best SRs" << std::endl;
        Show_SR(fname0, c, xmin, xmax, ymin, ymax, useShape, leg);
        
    } 
    
    TLatex *Leg0 = new TLatex( xmin, ymax + dy*0.025,plottitle );
    Leg0->SetTextAlign( 11 );
    Leg0->SetTextFont( 42 );
    Leg0->SetTextSize( CombinationGlob::DescriptionTextSize);
    Leg0->SetTextColor( 1 );
    Leg0->AppendPad();


    TLatex *Leg1 = new TLatex();
    Leg1->SetNDC();
    Leg1->SetTextAlign( 11 );
    Leg1->SetTextFont( 42 );
    Leg1->SetTextSize( CombinationGlob::DescriptionTextSize );
    Leg1->SetTextColor( 1 );
    Leg1->DrawLatex(0.15,0.78, Form("#int L dt = %1.1f fb^{-1},  #sqrt{s}=8 TeV",lumi));  // 0.32,0.87
    if(useShape){
        Leg1->DrawLatex(0.15,0.72, "0 leptons, 2-6 jets, 5-bin");  // 0.32,0.87
    } else {
        Leg1->DrawLatex(0.15,0.72, "0 leptons, 2-6 jets");  // 0.32,0.87
    }    

    Leg1->AppendPad();

    TLatex *Leg2 = new TLatex();
    Leg2->SetNDC();
    Leg2->SetTextAlign( 11 );
    Leg2->SetTextSize( CombinationGlob::DescriptionTextSize );
    Leg2->SetTextColor( 1 );
    Leg2->SetTextFont(70);
    if (prefix!=0) { 
        Leg2->DrawLatex(0.7,0.85,prefix); // 0.15,0.81
        Leg2->AppendPad(); 
    }

    TLatex *atlasLabel = new TLatex();
    atlasLabel->SetNDC();
    atlasLabel->SetTextFont( 42 );
    atlasLabel->SetTextColor( 1 );
    atlasLabel->SetTextSize( 0.05 );
    atlasLabel->DrawLatex(0.15,0.87, "#bf{#it{ATLAS}} Internal"); // 0.15,0.87

    atlasLabel->AppendPad();

    //// draw number of signal events
    if (nsigmax>0 && showsig) {  hist1->Draw("textsame"); }
    //else {
    //  // draw grid for clarity
    //  c->SetGrid();
    //}
    //reddraw cahnnel label
    //  c->SetGrid();

    if (prefix!=0) { Leg2->AppendPad(); }

    // redraw axes
    frame->Draw( "sameaxis" );


    //  leg->Draw("same");


    // update the canvas
    double xline=1000.;
    double yline=1000.;
    if (fname0.Contains("SS")) {
        xline=800.; 
        yline=800.;
    }
    TLine *line=new TLine(200.,200.,xline,yline);
    line->SetLineStyle(3);
    //line->Draw();
    c->Update();


    gPad->RedrawAxis("same");
    c->Update();
    gPad->Update();

    ////////////////////////////////////////////////////////////////////////////////////////////

    //gROOT->GetListOfSpecials()->Print();

    TObjArray *contours = (TObjArray*)gROOT->GetListOfSpecials()->FindObject("contours");
    if (contours!=0) {
        //contours->Print("v");

        TList *lcontour1 = (TList*)contours->At(0);
        //lcontour1->Print();
        if (lcontour1!=0) {
            TGraph *gc1 = (TGraph*)lcontour1->First();
            if (gc1!=0) { 
                //gc1->Print();
                //if (gc1->GetN() < 10) return;
                //gc1->SetMarkerStyle(21);
                //gc1->Draw("alp");
            }
        }
    }

    ////////////////////////////////////////////////////////////////////////////////////////////

    // create plots
    // store histograms to output file
    TObjArray* arr = fname0.Tokenize("/");
    TObjString* objstring = (TObjString*)arr->At( arr->GetEntries()-1 );
    TString outfile = TString(Form("%1.2finvfb_",lumi)) + TString(Form("wband%d_",showOneSigmaExpBand)) + TString(Form("showcms%d_",showcms)) + objstring->GetString().ReplaceAll(".root","");
    delete arr;
    
    if(!showSR) outfile += TString("_noLabel");
    TString prefixsave = TString(prefix).ReplaceAll(" ","_") + Form("%1.2finvfb_",lumi) + Form("wband%d_",showOneSigmaExpBand);
    CombinationGlob::imgconv( c, Form("plots/atlascls_m0m12_%s",outfile.Data()) );   

}
void SUSY_m0_vs_m12_all_withBand_cls( TString fname0 = "mudat_list.root",// nominal
                                      TString fname1 = "",               // Up
                                      TString fname2 = "",               // Down  
                                      TString fname3 = "", // external expection
                                      const char* prefix="test",
                                      const float& lumi = 20,
                                      bool showsig = true,
                                      int discexcl = 1,
                                      int showtevatron = 0,
                                      int showcms = 0,
                                      int showOneSigmaExpBand = 0,
                                      int showfixSigXSecBand = 0,
                                      int channel = -1,
                                      TString hname0 = "sigp1clsf",
                                      TString hname1 = "sigp1expclsf",
                                      TString hname3 = "sigclsu1s",
                                      TString hname5 = "sigclsd1s",
                                      TString hname6 = "sigp1ref",
                                      TString fnameMass= "../../../HistFitterUser/common/mSugraGridtanbeta10_gluinoSquarkMasses.root")
{
   // set style and remove existing canvas'
   CombinationGlob::Initialize();
   
   cout << "--- Plotting m0 versus m12 " << endl;
   
   // --- prepare
   // open reference files, and retrieve histogram
   cout << "--- Reading root base file: " << fname0 << endl;
   TFile* f0 = TFile::Open( fname0, "READ" );
   if (!f0) {
      cout << "*** Error: could not retrieve histogram: " << hname0 << " in file: " << f0->GetName() 
           << " ==> abort macro execution" << endl;
      return;
   }
   
   TFile* f1;
   TFile* f2;
   if(showfixSigXSecBand){
      cout << "--- Reading root base file: " << fname1 << endl;
      f1 = TFile::Open( fname1, "READ" );
      cout << "--- Reading root base file: " << fname2 << endl;
      f2 = TFile::Open( fname2, "READ" );

      if(!f1 || !f2){
         cout << "*** Error: could not open in files: " << f1->GetName() <<" or "<< f2->GetName() 
              << " ==> abort macro execution" << endl;
         return;
      }
   }
   
   TH2F* histecls = (TH2F*)f0->Get( "sigp1expclsf" ); 
   TH2F* histocls = (TH2F*)f0->Get( "sigp1clsf" ); 
   if (histecls!=0) histecls->SetDirectory(0);
   if (histocls!=0) histocls->SetDirectory(0);
   
   // in case we use external expectation!
   TFile* f3 = TFile::Open( fname3, "READ" );
   TH2F* histe(0);
   if (f3) { histe = (TH2F*)f3->Get( hname0 ); }
   TH2F* histe_u1s(0);
   if (f3) { histe_u1s = (TH2F*)f3->Get( hname3 ); }
   TH2F* histe_d1s(0);
   if (f3) { histe_d1s = (TH2F*)f3->Get( hname5 ); }
   
   if (f3) {
      if (histecls!=0) { delete histecls; histecls=0; }
      histecls = (TH2F*)f3->Get( "sigp1expcls" );
      if (histecls!=0) histecls->SetDirectory(0);
      else {
        histecls = (TH2F*)f3->Get( "sigp1expclsf" );
        if (histecls!=0) histecls->SetDirectory(0);
      }
   }
   
   bool extExpectation = (f3!=0) ;
   
   TH2F* hist0 = (TH2F*)f0->Get( hname0 );
   TH2F* hist1 = (TH2F*)f0->Get( hname1 );
   TH2F* hist3 = (TH2F*)f0->Get( hname3 );
   TH2F* hist5 = (TH2F*)f0->Get( hname5 );
   TH2F* hist6 = (TH2F*)f0->Get( hname6 );
   
   if (hist0!=0) hist0->SetDirectory(0);
   if (hist1!=0) hist1->SetDirectory(0);
   if (hist3!=0) hist3->SetDirectory(0);
   if (hist5!=0) hist5->SetDirectory(0);
   if (hist6!=0) hist6->SetDirectory(0);
   f0->Close();

   TH2F* histe_esigxsp1s = (TH2F*)f1->Get( hname0 ); 
   TH2F* histe_esigxsm1s = (TH2F*)f2->Get( hname0 ); 

   if (histe_esigxsp1s!=0) histe_esigxsp1s->SetDirectory(0);
   if (histe_esigxsm1s!=0) histe_esigxsm1s->SetDirectory(0);

   TH2F* contour_esigxsp1s
      = ( histe_esigxsp1s!=0 ? FixAndSetBorders( *histe_esigxsp1s, "contour_esigxsp1s", "contour_esigxsp1s", 0 ) : 0);
   TH2F* contour_esigxsm1s
      = ( histe_esigxsm1s!=0 ? FixAndSetBorders( *histe_esigxsm1s, "contour_esigxsm1s", "contour_esigxsm1s", 0 ) : 0);
   
   TH2F* contour         = ( hist1!=0 ? FixAndSetBorders( *hist1, "contour", "contour", 0 ) : 0);
   TH2F* contour_obs     = ( hist0!=0 ? FixAndSetBorders( *hist0, "contour_obs", "contour_obs") : 0 );
   
   TH2F* contour_ep1s    = ( hist3!=0 ? FixAndSetBorders( *hist3, "contour", "contour", 0 ) : 0 );
   TH2F* contour_em1s    = ( hist5!=0 ? FixAndSetBorders( *hist5, "contour", "contour", 0 ) : 0 );

   // For Band
   TGraph* gr_contour_ep1s = ( contour_ep1s!=0 ? ContourGraph( contour_ep1s ) : 0 ); //ContourGraph( contour_ep1s )->Clone(); 
   TGraph* gr_contour_em1s = ( contour_em1s!=0 ? ContourGraph( contour_em1s ) : 0 ); //ContourGraph( contour_em1s )->Clone(); 
   
   TH2F* contour_exp(0);
   if (histe!=0)     { contour_exp     = FixAndSetBorders( *histe, "contour_exp", "contour_exp", 0 ); } 
   TH2F* contour_au1s(0);
   if (histe_u1s!=0) {  contour_au1s   = FixAndSetBorders( *histe_u1s, "contour", "contour", 0 ); }
   TH2F* contour_ad1s(0);
   if (histe_d1s!=0) {  contour_ad1s   = FixAndSetBorders( *histe_d1s, "contour", "contour", 0 ); }
   
   
   TH2F* contour_expcls(0);
   if (histecls!=0)     { contour_expcls     = FixAndSetBorders( *histecls, "contour_expcls", "contour_expcls", 0 ); }
   TH2F* contour_obscls(0);
   if (histocls!=0)     { contour_obscls     = FixAndSetBorders( *histocls, "contour_obscls", "contour_obscls", 0 ); }

   if (contour_obs==0) { 
      cout << "contour is zero" << endl;
      return;
   }


   
   // set text style
   gStyle->SetPaintTextFormat(".2g");
   if (hist1!=0) hist1->SetMarkerStyle(21);
   if (hist1!=0) hist1->SetMarkerSize(1.5);
   Float_t nsigmax(0)
      if (hist1!=0) nsigmax = hist1->GetMaximum();
   
   // --- draw
   
   // create canvas
   TCanvas* c = new TCanvas( "c", "A scan of m_{0} versus m_{12}", 0, 0, 
                             CombinationGlob::StandardCanvas[0], CombinationGlob::StandardCanvas[1] );  
  //c->SetGrayscale();
  
  // create and draw the frame
  //TH2F *frame = new TH2F("frame", "m_{0} vs m_{12} - ATLAS work in progress", 100, 100., 1400., 100, 115., 500. );
  TH2F *frame = new TH2F("frame", "m_{0} vs m_{12} - ATLAS work in progress", 100, 100., 3750., 100, 115., 700. );
  //TH2F *frame = new TH2F("frame", "m_{0} vs m_{12} - ATLAS work in progress", 100, 100., 600., 100, 240., 500. );
  
  // set common frame style
  CombinationGlob::SetFrameStyle2D( frame, 1.0 ); // the size (scale) is 1.0
  
  frame->SetXTitle( "m_{0} [GeV]" );
  frame->SetYTitle( "m_{1/2} [GeV]" );
  frame->GetYaxis()->SetTitleOffset(1.35);

  //frame->SetTextFont( 42 );
  frame->GetXaxis()->SetTitleFont( 42 );
  frame->GetYaxis()->SetTitleFont( 42 );
  frame->GetXaxis()->SetLabelFont( 42 );
  frame->GetYaxis()->SetLabelFont( 42 );

  frame->GetXaxis()->SetTitleSize( 0.04 );
  frame->GetYaxis()->SetTitleSize( 0.04 );
  frame->GetXaxis()->SetLabelSize( 0.04 );
  frame->GetYaxis()->SetLabelSize( 0.04 );

  frame->Draw();
    
  const int nsig(3);
  //TH2F *chist[3];
  // draw contours
  //!instead of printing sigma in 68% 95% 98% levels now printing +1 sigma deviations 
  //for (Int_t nsigma=1; nsigma<=nsig; nsigma++)
  //  DrawContourSameColor( contour, nsigma, "blue", kFALSE, (nsigma==1?inverse:0) ) ;

  TString basecolor="yellow";
  Int_t nsigma=2;

  //  TLegend *leg = new TLegend(0.7,0.77,0.95,0.915);
  TLegend *leg = new TLegend(0.57,0.52,0.85,0.915);//(0.565,0.47,0.925,0.915);//(0.59,0.47,0.92,0.915);

  leg->SetTextSize( CombinationGlob::DescriptionTextSize );
  leg->SetTextSize( 0.03 );
  leg->SetTextFont( 42 );
  leg->SetFillColor( 0 );
  leg->SetFillStyle(1001);
  
  // add squark, gluino mass contour lines HERE (TILL)
  TFile* f4 = TFile::Open( fnameMass, "READ" );
  TH2F* histSq = (TH2F*)f4->Get( "mSugraGrid_squarkMasses" );
  TH2F* histGl = (TH2F*)f4->Get( "mSugraGrid_gluinoMasses" );
  histSq->SetDirectory(0);
  histGl->SetDirectory(0);
  f4->Close();

  TH2F* histSquarkMass   = FixAndSetBorders( *histSq, "SquarkMass", "SquarkMass", 10000 );
  TH2F* histGluinoMass   = FixAndSetBorders( *histGl, "GluinoMass", "GluinoMass", 10000 );
  
//  DrawContourMassLine( histSquarkMass, 400.0 );
//  DrawContourMassLine( histSquarkMass, 500.0 );
  DrawContourMassLine( histSquarkMass, 600.0 );
//  DrawContourMassLine( histSquarkMass, 700.0 );
  DrawContourMassLine( histSquarkMass, 800.0 , 17);
//  DrawContourMassLine( histSquarkMass, 900.0 );
  DrawContourMassLine( histSquarkMass, 1000.0 );  
//  DrawContourMassLine( histSquarkMass, 1100.0 ); 
  DrawContourMassLine( histSquarkMass, 1200.0 , 17);
//  DrawContourMassLine( histSquarkMass, 1300.0 );    
  DrawContourMassLine( histSquarkMass, 1400.0 );
//  DrawContourMassLine( histSquarkMass, 1500.0 );
  DrawContourMassLine( histSquarkMass, 1600.0 , 17);
//  DrawContourMassLine( histSquarkMass, 1700.0 );
  DrawContourMassLine( histSquarkMass, 1800.0 );
//  DrawContourMassLine( histSquarkMass, 1900.0 );
  DrawContourMassLine( histSquarkMass, 2000.0 , 17);  
//  DrawContourMassLine( histSquarkMass, 2100.0 ); 
  DrawContourMassLine( histSquarkMass, 2200.0 );  
//  DrawContourMassLine( histSquarkMass, 2300.0 );     
  DrawContourMassLine( histSquarkMass, 2400.0 , 17);
//  DrawContourMassLine( histSquarkMass, 2500.0 );
  DrawContourMassLine( histSquarkMass, 2600.0 );
//  DrawContourMassLine( histSquarkMass, 2700.0 );
  DrawContourMassLine( histSquarkMass, 2800.0 , 17);
//  DrawContourMassLine( histSquarkMass, 2900.0 );
  DrawContourMassLine( histSquarkMass, 3000.0 );   
//  DrawContourMassLine( histSquarkMass, 3100.0 ); 
  DrawContourMassLine( histSquarkMass, 3200.0 , 17);  
//  DrawContourMassLine( histSquarkMass, 2300.0 );     
  DrawContourMassLine( histSquarkMass, 3400.0 );
//  DrawContourMassLine( histSquarkMass, 3500.0 );
//  DrawContourMassLine( histSquarkMass, 3600.0 , 17);
//  DrawContourMassLine( histSquarkMass, 3700.0 );
//  DrawContourMassLine( histSquarkMass, 3800.0 );
//  DrawContourMassLine( histSquarkMass, 3900.0 );
//  DrawContourMassLine( histSquarkMass, 4000.0 );        

  DrawContourMassLine( histGluinoMass, 400.0 );
  DrawContourMassLine( histGluinoMass, 500.0 , 17);
  DrawContourMassLine( histGluinoMass, 600.0 );
  DrawContourMassLine( histGluinoMass, 700.0 , 17);
  DrawContourMassLine( histGluinoMass, 800.0 );
  DrawContourMassLine( histGluinoMass, 900.0 , 17);
  DrawContourMassLine( histGluinoMass, 1000.0 );  
  DrawContourMassLine( histGluinoMass, 1100.0 , 17);  
  DrawContourMassLine( histGluinoMass, 1200.0 );  
  DrawContourMassLine( histGluinoMass, 1300.0 , 17);      
  DrawContourMassLine( histGluinoMass, 1400.0 );
  DrawContourMassLine( histGluinoMass, 1500.0 , 17);
  DrawContourMassLine( histGluinoMass, 1600.0 );
//  DrawContourMassLine( histGluinoMass, 1700.0 );
//  DrawContourMassLine( histGluinoMass, 1800.0 );
//  DrawContourMassLine( histGluinoMass, 1900.0 );
//  DrawContourMassLine( histGluinoMass, 2000.0 );  
//  DrawContourMassLine( histGluinoMass, 2100.0 ); 

  // find gluino ~ squark mass exclusion limit
  //DrawContourMassLine( histSquarkMass, 820.0 );
  //DrawContourMassLine( histGluinoMass, 820.0 );

/*  TLatex * s400 = new TLatex( 140, 167 , "#tilde{q} (400 GeV)" );
  s400->SetTextAlign( 11 );
  s400->SetTextSize( 0.025 );
  s400->SetTextColor( TColor::GetColor("#dddddd") );
  s400->Draw();*/
/*  TLatex * s500 = new TLatex( 150, 220, "#tilde{q} (500 GeV)" );
  s500->SetTextAlign( 11 );
  s500->SetTextSize( 0.025 );
  s500->SetTextColor( TColor::GetColor("#dddddd") );
  s500->Draw();*/
  TLatex * s600 = new TLatex( 340, 230, "#tilde{q} (600 GeV)" );
  s600->SetTextAlign( 11 );
  s600->SetTextAngle(-60);
  s600->SetTextSize( 0.025 );
  s600->SetTextColor( 16 ); //12
  s600->Draw();
  /*TLatex * s700 = new TLatex( 545, 315, "#tilde{q} (700 GeV)" );
  s700->SetTextAlign( 11 );
  s700->SetTextSize( 0.025 );
  s700->SetTextColor( TColor::GetColor("#dddddd") );
  s700->Draw();*/
  /*TLatex * s800 = new TLatex( 250, 270, "#tilde{q} (800 GeV)" );
  s800->SetTextAlign( 11 );
  s800->SetTextSize( 0.025 );
  s800->SetTextColor( 203 );
  s800->Draw();*/
  /*
  TLatex * s900 = new TLatex( 330, 400, "#tilde{q} (900 GeV)" );
  s900->SetTextAlign( 11 );
  s900->SetTextSize( 0.025 );
  s900->SetTextColor( TColor::GetColor("#dddddd") );
  s900->Draw();*/
   TLatex * s1000 = new TLatex( 550, 408, "#tilde{q} (1000 GeV)" );
  s1000->SetTextAlign( 11 );
  s1000->SetTextAngle(-60);
  s1000->SetTextSize( 0.025 );
  s1000->SetTextColor( 16 );
  s1000->Draw(); 
   TLatex * s1400 = new TLatex( 790, 580, "#tilde{q} (1400 GeV)" );
  s1400->SetTextAlign( 11 );
  s1400->SetTextAngle(-60);
  s1400->SetTextSize( 0.025 );
  s1400->SetTextColor( 16 );
  s1400->Draw();   

  /*TLatex * g400 = new TLatex( 1100, 140, "#tilde{g} (400 GeV)" );
  g400->SetTextAlign( 11 );
  g400->SetTextSize( 0.025 );
  g400->SetTextColor( 203 );
  g400->Draw();*/
  /*TLatex * g500 = new TLatex( 1000, 185, "#tilde{g} (500 GeV)" );
  g500->SetTextAlign( 11 );
  g500->SetTextSize( 0.025 );
  g500->SetTextColor( TColor::GetColor("#dddddd") );
  g500->Draw();*/
  TLatex * g600 = new TLatex( 1100, 225, "#tilde{g} (600 GeV)" );
  g600->SetTextAlign( 11 );
  g600->SetTextAngle(-4);
  g600->SetTextSize( 0.025 );
  g600->SetTextColor( 16 );
  g600->Draw();
  /*TLatex * g900 = new TLatex( 550, 380, "#tilde{g} (900 GeV)" );
  g900->SetTextAlign( 11 );
  g900->SetTextSize( 0.025 );
  g900->SetTextColor( TColor::GetColor("#dddddd") );
  g900->Draw();*/
  TLatex * g800 = new TLatex( 690, 330, "#tilde{g} (800 GeV)" );
  g800->SetTextAlign( 11 );
  g800->SetTextSize( 0.025 );
  g800->SetTextColor( 16 );
  //g800->Draw();
  TLatex * g1000 = new TLatex( 1400, 399, "#tilde{g} (1000 GeV)" );
  g1000->SetTextAlign( 11 );
  g1000->SetTextAngle(-5); 
  g1000->SetTextSize( 0.025 );
  g1000->SetTextColor( 16 );
  g1000->Draw();
  TLatex * g1200 = new TLatex( 1550, 489, "#tilde{g} (1200 GeV)" );
  g1200->SetTextAlign( 11 );
  g1200->SetTextAngle(-6); 
  g1200->SetTextSize( 0.025 );
  g1200->SetTextColor( 16 );
  //g1200->Draw();  
  TLatex * g1400 = new TLatex( 1650, 582, "#tilde{g} (1400 GeV)" );
  g1400->SetTextAlign( 11 );
  g1400->SetTextAngle(-6); 
  g1400->SetTextSize( 0.025 );
  g1400->SetTextColor( 16 );
  g1400->Draw();
  
  // island hacks
  if (true && channel==4) { // muon fixes 
    cout << "removing islands in muon channel ..." << endl;
    // contour line is drawn for values at 1.64485
    TAxis* ax = contour_obs->GetXaxis();
    TAxis* ay = contour_obs->GetYaxis();

    TH2F* contour_fix = contour_em1s;

    for (int xbin = 1; xbin <= contour_fix->GetNbinsX(); xbin++) {
      for (int ybin = 1; ybin <= contour_fix->GetNbinsY(); ybin++) {
	// island 1
	if ( ax->GetBinCenter( xbin) > 1350.  && ax->GetBinCenter( xbin) < 1500. && ay->GetBinCenter( ybin) < 130. && ay->GetBinCenter( ybin) > 89. ) {
	  cout << "Found spot here: " << xbin << " (" << ax->GetBinCenter( xbin)  << "), "
	       << ybin << " (" << ay->GetBinCenter( ybin) << "), "
	       << " value: " << contour_fix->GetBinContent(xbin,ybin) <<   endl;
	  cout << "   HACK : Setting above point by hand to 1.65 (!)" << endl;
	  if (contour_fix->GetBinContent(xbin,ybin)<1.65) contour_fix->SetBinContent(xbin, ybin, 1.66);
	}

      }
    }

  } 
  if (false && channel==1) { // electron

    cout << "removing islands in electron channel ..." << endl;
    // contour line is drawn for values at 1.64485
    TAxis* ax = contour_obs->GetXaxis();
    TAxis* ay = contour_obs->GetYaxis();

    contour_em1s

    for (int xbin = 1; xbin <= contour_obs->GetNbinsX(); xbin++) {
      for (int ybin = 1; ybin <= contour_obs->GetNbinsY(); ybin++) {
	// island 2
	if ( ax->GetBinCenter( xbin) > 420. && ax->GetBinCenter( xbin) < 480. &&
	     ay->GetBinCenter( ybin) > 140. && ay->GetBinCenter( ybin) < 160. ) {
	  cout << "Found spot here: " << xbin << " (" << ax->GetBinCenter( xbin)  << "), "
	       << ybin << " (" << ay->GetBinCenter( ybin) << "), "
	       << " value: " << contour->GetBinContent(xbin,ybin) <<   endl;
	  cout << "   HACK : Setting above point by hand to 1.50 (!)" << endl;
	  contour->SetBinContent(xbin, ybin, 1.50);
	}
      }
    }

  }
Ejemplo n.º 10
0
void HHToBBGGSelection_BBHGG(const string inputfile,          // input file
                             const string outputfile,         // output directory
                             Int_t SampleType = 4,
                             Bool_t applyExtrapWeightTo140PU = kFALSE                             
  ) {
  
  //--------------------------------------------------------------------------------------------------------------
  // Settings 
  //============================================================================================================== 
  bool printdebug = false;


  //*****************************************************************************************
  //Setup
  //*****************************************************************************************
  TFile *photonEffFile = new TFile("/afs/cern.ch/work/s/sixie/public/releases/analysis/CMSSW_5_3_9_patch3/src/CMSAna/HHToBBGG/data/PhotonEfficiency_PromptPhoton.root","READ"); 
  TH2F* photonEffHist = (TH2F*)photonEffFile->Get("Efficiency_PtEta");
  photonEffHist->SetDirectory(0);
  photonEffFile->Close(); delete photonEffFile;

  TFile *btagEffFile = new TFile("/afs/cern.ch/work/s/sixie/public/releases/analysis/CMSSW_5_3_9_patch3/src/CMSAna/HHToBBGG/data/BTaggingEfficiency_BJetEfficiency.root","READ"); 
  TH2F* btagEffHist = (TH2F*)btagEffFile->Get("Efficiency_PtEta");
  btagEffHist->SetDirectory(0);
  btagEffFile->Close(); delete btagEffFile;

  //load photon response functions
  TFile *photonResponseFunctionFile = new TFile("/afs/cern.ch/work/s/sixie/public/releases/analysis/CMSSW_5_3_9_patch3/src/CMSAna/HHToBBGG/data/PhotonResolution.root","READ"); 
  vector<vector<TH1F* > > photonResponseFunctions;
  vector<double> PtBins;
  PtBins.push_back(25);
  PtBins.push_back(35);
  PtBins.push_back(45);
  PtBins.push_back(55);
  PtBins.push_back(65);
  PtBins.push_back(75);
  vector<double> EtaBins;
  EtaBins.push_back(0.0);
  EtaBins.push_back(0.25);
  EtaBins.push_back(0.50);
  EtaBins.push_back(0.75);
  EtaBins.push_back(1.00);
  EtaBins.push_back(1.25);
  EtaBins.push_back(1.50);
  EtaBins.push_back(1.75);
  EtaBins.push_back(2.00);
  EtaBins.push_back(2.25);
  for (int ipt = 0; ipt < PtBins.size(); ++ipt) {
    vector<TH1F*> tmpPhotonResponseFunctions;
    for (int ieta = 0; ieta < EtaBins.size(); ++ieta) {      
      tmpPhotonResponseFunctions.push_back( (TH1F*)photonResponseFunctionFile->Get( Form("PhotonResponseFunction_PtBin%d_EtaBin%d",ipt,ieta)));
    }
    photonResponseFunctions.push_back(tmpPhotonResponseFunctions);
  }
  //check histogram loading
  for (int ipt = 0; ipt < PtBins.size(); ++ipt) {
    for (int ieta = 0; ieta < EtaBins.size(); ++ieta) {   
      assert( photonResponseFunctions[ipt][ieta] );
    }
  }
  
  TRandom3 *MyRandom = new TRandom3( time(NULL) );


  //--------------------------------------------------------------------------------------------------------------
  // Main analysis code 
  //==============================================================================================================  
  Double_t nEvents = 0;

  
  //*****************************************************************************************
  // Set up output ntuple
  //*****************************************************************************************
  TFile *outFile = new TFile(outputfile.c_str(),"RECREATE"); 
  TH1F *NEvents =  new TH1F("NEvents",";;",1,-0.5,0.5);
  TH1F *NPUMean = new TH1F("NPUMean",";NPUMean;Number of Events", 100, -0.5, 99.5);
  cmsana::HHToBBGGEventTree *outputEventTree = new cmsana::HHToBBGGEventTree;
  outputEventTree->CreateTree();


  //*****************************************************************************************
  // Set up input
  //*****************************************************************************************
  TFile *infile=0;
  TTree *eventTree=0;
  
  // Data structures to store info from TTrees
  cmsana::TEventInfo *info  = new cmsana::TEventInfo();
  TClonesArray *genparticleArr = new TClonesArray("cmsana::TGenParticle");
  TClonesArray *genjetArr = new TClonesArray("cmsana::TGenJet");

  // Read input file and get the TTrees
  cout << "Processing " << inputfile << "..." << endl;
  infile = TFile::Open(inputfile.c_str(),"read");
  assert(infile);

    
  eventTree = (TTree*)infile->Get("Events"); assert(eventTree);  
  eventTree->SetBranchAddress("Info",     &info);        TBranch *infoBr     = eventTree->GetBranch("Info");
  eventTree->SetBranchAddress("GenParticle", &genparticleArr); TBranch *genparticleBr = eventTree->GetBranch("GenParticle");
  eventTree->SetBranchAddress("GenJet", &genjetArr); TBranch *genjetBr = eventTree->GetBranch("GenJet");
  cout << "NEvents = " << eventTree->GetEntries() << endl;

  
  //Double_t weight = 1;

  // null vector for default four vectors
  cmsana::FourVector null(0.0,0.0,0.0,0.0);

  // loop over events
  for(UInt_t ientry=0; ientry<eventTree->GetEntries(); ientry++) {
    printdebug = false;
    if (ientry % 1000 == 0) cout << "Processed Event " << ientry << endl;
    infoBr->GetEntry(ientry);

    NEvents->Fill(0);
    NPUMean->Fill(info->nPUMean);

    //***********************************************************
    // Definition of Pileup Energy density
    //***********************************************************
    Double_t rho = info->RhoKt6PFJets;

    genparticleArr->Clear(); 
    genjetArr->Clear(); 
    genparticleBr->GetEntry(ientry);
    genjetBr->GetEntry(ientry);

    //***********************************************************
    // Find Gen-Level particles
    //***********************************************************
    const cmsana::TGenParticle *genPhoton1 = 0;
    const cmsana::TGenParticle *genPhoton2 = 0;
    const cmsana::TGenParticle *genB1 = 0;
    const cmsana::TGenParticle *genB2 = 0;
    const cmsana::TGenJet *genBJet1 = 0;
    const cmsana::TGenJet *genBJet2 = 0;
    int NBGenJets = 0;
    int NNonBGenJets = 0;
    int NBJets = 0;

    
    //***********************************************************
    // Find B Partons
    //***********************************************************    
    for(Int_t i=0; i<genparticleArr->GetEntriesFast(); i++) {
      const cmsana::TGenParticle *p = (cmsana::TGenParticle*)((*genparticleArr)[i]);

      if (abs(p->pdgid) == 5 && p->status == 3 && ( ( abs(p->motherPdgID) >= 1 && abs(p->motherPdgID) <= 5 ) || abs(p->motherPdgID) == 21) ) {
        if (!genB1) {
          genB1 = p;
        } else {
          if (!genB2 && ( p->pdgid != genB1->pdgid || cmsana::deltaR(genB1->eta,genB1->phi,p->eta,p->phi) > 0.5) ) genB2 = p;
        }
      }
    }
    

    //***********************************************************
    // Find B Gen-Jets
    //***********************************************************    
    for(Int_t i=0; i<genjetArr->GetEntriesFast(); i++) {
      const cmsana::TGenJet *genjet = (cmsana::TGenJet*)((*genjetArr)[i]);  
      if (!(genjet->pt > 30)) continue;

      if (abs(genjet->matchedPdgId) == 5) {
        NBGenJets++;
        if (abs(genjet->eta) < 2.4) {
          if(!genBJet1) genBJet1 = genjet;
          else if (!genBJet2) genBJet2 = genjet;
        }
      } else {
        NNonBGenJets++;
      }
    }

    //***********************************************************
    //Filter for events with 2 b genjets
    //***********************************************************
    if ( NBGenJets < 2 ) {
      continue;
    }



    //***********************************************************
    // Find Gen Photons
    //***********************************************************    
    for(Int_t i=0; i<genparticleArr->GetEntriesFast(); i++) {
      const cmsana::TGenParticle *p = (cmsana::TGenParticle*)((*genparticleArr)[i]);
      if ( SampleType == cmsana::HHToBBGGEventTree::bbHgg) {
        if (p->pdgid == 22 && ( p->motherPdgID == 25 ) && p->status == 3 ) {
          if (!genPhoton1) {
            genPhoton1 = p;
          } else if (!genPhoton2) {
            genPhoton2 = p;
          }
        }
      }
    }
    
    //***********************************************************
    // Count Jets
    //***********************************************************    
    int NJets = 0;
    int NCentralJets = 0;
    double jetSumPt = 0;
    for(Int_t i=0; i<genjetArr->GetEntriesFast(); i++) {
      const cmsana::TGenJet *genjet = (cmsana::TGenJet*)((*genjetArr)[i]);  
      if (!(genjet->pt > 30)) continue;

      //Si Note: need to implement jet efficiency too
      if (abs(genjet->eta) < 5.0) {
        jetSumPt += genjet->pt;
        NJets++;
        if (abs(genjet->eta) < 2.5) {
          NCentralJets++;
        }
      }

    }



    //sampleType
    cmsana::HHToBBGGEventTree::SampleType stype = cmsana::HHToBBGGEventTree::none;
    if (SampleType == 4) stype = cmsana::HHToBBGGEventTree::bbHgg;
    else {
      cout << "Warning: sample type not diphoton jets. Unintended use of this macro. \n";
    }

    outputEventTree->sampletype = stype;
    outputEventTree->run = info->runNum;
    outputEventTree->lumi = info->lumiSec;
    outputEventTree->event = info->evtNum;
    outputEventTree->npu = info->nPU;
    outputEventTree->rho = info->RhoKt6PFJets;
    outputEventTree->nvtx = info->nGoodPV;
    
    cmsana::FourVectorM genpho1v;
    cmsana::FourVectorM genpho2v;
    outputEventTree->genpho1 = null;
    outputEventTree->genpho2 = null;
    if (genPhoton1) {
      genpho1v.SetPt(genPhoton1->pt);
      genpho1v.SetEta(genPhoton1->eta);
      genpho1v.SetPhi(genPhoton1->phi);
      genpho1v.SetM(0);
      outputEventTree->genpho1 = genpho1v;
    }
    if (genPhoton2) {
      genpho2v.SetPt(genPhoton2->pt);
      genpho2v.SetEta(genPhoton2->eta);
      genpho2v.SetPhi(genPhoton2->phi);
      genpho2v.SetM(0);   
      outputEventTree->genpho2 = genpho2v;    
    }
    
    cmsana::FourVectorM genb1v;
    cmsana::FourVectorM genb2v;
    outputEventTree->genb1 = null;
    outputEventTree->genb2 = null;
    if (genB1) {
      genb1v.SetPt(genB1->pt);
      genb1v.SetEta(genB1->eta);
      genb1v.SetPhi(genB1->phi);
      genb1v.SetM(0);
      outputEventTree->genb1 = genb1v;
    }
    if (genB2) {
      genb2v.SetPt(genB2->pt);
      genb2v.SetEta(genB2->eta);
      genb2v.SetPhi(genB2->phi);
      genb2v.SetM(0);   
      outputEventTree->genb2 = genb2v;
    }

    cmsana::FourVectorM genbjet1v;
    cmsana::FourVectorM genbjet2v;
    outputEventTree->genbjet1 = null;    
    outputEventTree->genbjet2 = null;    
    if (genBJet1) {
      genbjet1v.SetPt(genBJet1->pt);
      genbjet1v.SetEta(genBJet1->eta);
      genbjet1v.SetPhi(genBJet1->phi);
      genbjet1v.SetM(genBJet1->mass);
      outputEventTree->genbjet1 = genbjet1v;
    }
    if (genBJet2) {
      genbjet2v.SetPt(genBJet2->pt);
      genbjet2v.SetEta(genBJet2->eta);
      genbjet2v.SetPhi(genBJet2->phi);
      genbjet2v.SetM(genBJet2->mass);   
      outputEventTree->genbjet2 = genbjet2v;    
    }


    //********************************************************
    //Select photons
    //********************************************************
    cmsana::FourVectorM photon1v;
    cmsana::FourVectorM photon2v;
    cmsana::FourVectorM diphotonv;
    double pho1eff = 0;
    double pho2eff = 0;
    outputEventTree->pho1 = null;      //default 4-vector
    outputEventTree->pho2 = null;
    outputEventTree->diphoton = null;    

    if (genPhoton1) {      
      photon1v.SetPt(GetSmearedPhotonPt( genPhoton1->pt, genPhoton1->eta, PtBins, EtaBins, photonResponseFunctions ) );
      photon1v.SetEta(genPhoton1->eta);
      photon1v.SetPhi(genPhoton1->phi);
      photon1v.SetM(0);
      outputEventTree->pho1 = photon1v;
      pho1eff = photonEffHist->GetBinContent( 
        photonEffHist->GetXaxis()->FindFixBin( fmax( fmin( genPhoton1->pt, 99.9), 0.01) ),
        photonEffHist->GetYaxis()->FindFixBin( fmax( fmin (genPhoton1->eta, 2.99), -2.99))
        );
      
      if (pho1eff > 1) {
        cout << "ERROR: " << genPhoton1->pt << " " << genPhoton1->eta << " | " << photonEffHist->GetXaxis()->FindFixBin( genPhoton1->pt) << " " << photonEffHist->GetYaxis()->FindFixBin( genPhoton1->eta) << " | " << pho1eff << "\n";
      }

    } 

    if (genPhoton2) {
      photon2v.SetPt(GetSmearedPhotonPt( genPhoton2->pt, genPhoton2->eta, PtBins, EtaBins, photonResponseFunctions ));
      photon2v.SetEta(genPhoton2->eta);
      photon2v.SetPhi(genPhoton2->phi);
      photon2v.SetM(0);
      outputEventTree->pho2 = photon2v;
      pho2eff = photonEffHist->GetBinContent( 
        photonEffHist->GetXaxis()->FindFixBin( fmax( fmin( genPhoton2->pt, 99.9), 0.01) ),
        photonEffHist->GetYaxis()->FindFixBin( fmax( fmin (genPhoton2->eta, 2.99), -2.99))
        );
    }
    
    if (genPhoton1 && genPhoton2) {
      diphotonv = photon1v + photon2v;
      outputEventTree->diphoton = diphotonv;
    }
   

    //********************************************************
    //Select b-jets
    //********************************************************
    cmsana::FourVectorM bjet1v;
    cmsana::FourVectorM bjet2v;
    cmsana::FourVectorM dibjetv;
    double bjet1eff = 0;
    double bjet2eff = 0;
    outputEventTree->bjet1 = null;      //default 4-vector
    outputEventTree->bjet2 = null;
    outputEventTree->dibjet = null;    

    if (genBJet1) {
      bjet1v.SetPt(genBJet1->pt);
      bjet1v.SetEta(genBJet1->eta);
      bjet1v.SetPhi(genBJet1->phi);
      bjet1v.SetM(genBJet1->mass);
      bjet1eff = btagEffHist->GetBinContent( 
        btagEffHist->GetXaxis()->FindFixBin( fmax( fmin( genBJet1->pt, 199.9), 0.01) ),
        btagEffHist->GetYaxis()->FindFixBin( fmax( fmin (genBJet1->eta, 2.49), -2.49))
        );
      outputEventTree->bjet1 = bjet1v;
    } else {

    }

    if (genBJet2) {
      bjet2v.SetPt(genBJet2->pt);
      bjet2v.SetEta(genBJet2->eta);
      bjet2v.SetPhi(genBJet2->phi);
      bjet2v.SetM(genBJet2->mass);
      bjet2eff = btagEffHist->GetBinContent( 
        btagEffHist->GetXaxis()->FindFixBin( fmax( fmin( genBJet2->pt, 199.9), 0.01) ),
        btagEffHist->GetYaxis()->FindFixBin( fmax( fmin (genBJet2->eta, 2.49), -2.49))
        );
      outputEventTree->bjet2 = bjet2v;
    }

    if (genBJet1 && genBJet2) {
      dibjetv = bjet1v + bjet2v;
      outputEventTree->dibjet = dibjetv;
    }


    //********************************************************
    //implement efficiency weights
    //********************************************************    
    outputEventTree->weight = pho1eff*pho2eff*bjet1eff*bjet2eff;

    //********************************************************
    //bbgg system
    //********************************************************    
    cmsana::FourVectorM bbggSystemv;
    outputEventTree->bbgg = null;
    if (genBJet1 && genBJet2 && genPhoton1 && genPhoton2) {
      bbggSystemv = (photon1v + photon2v + bjet1v + bjet2v);
      outputEventTree->bbgg = bbggSystemv;
    }



    //********************************************************
    //NJets
    //********************************************************    
    outputEventTree->njets = NJets;
    outputEventTree->ncentraljets = NCentralJets;

    outputEventTree->nlep = 0;

    //********************************************************
    //Some kinematic variables
    //********************************************************
    outputEventTree->DRgg = -1;
    outputEventTree->DRbb = -1;
    outputEventTree->minDRgb = -1;
    if (genBJet1 && genBJet2 && genPhoton1 && genPhoton2) {
      outputEventTree->DRgg = cmsana::deltaR(genPhoton1->eta, genPhoton1->phi, genPhoton2->eta, genPhoton2->phi);
      outputEventTree->DRbb = cmsana::deltaR(genBJet1->eta, genBJet1->phi, genBJet2->eta, genBJet2->phi);
      outputEventTree->minDRgb = fmin(fmin(fmin( cmsana::deltaR(genPhoton1->eta, genPhoton1->phi, genBJet1->eta, genBJet1->phi), 
                                                 cmsana::deltaR(genPhoton1->eta, genPhoton1->phi, genBJet2->eta, genBJet2->phi)),
                                           cmsana::deltaR(genPhoton2->eta, genPhoton2->phi, genBJet1->eta, genBJet1->phi)),
                                      cmsana::deltaR(genPhoton2->eta, genPhoton2->phi, genBJet2->eta, genBJet2->phi));      
    }

    outputEventTree->pfmet = sqrt( info->pfMEx*info->pfMEx + info->pfMEy*info->pfMEy);
    outputEventTree->pfTrackMET = sqrt( info->pfTrackMEx*info->pfTrackMEx + info->pfTrackMEy*info->pfTrackMEy);
    
    outputEventTree->HT = jetSumPt;
    if (genPhoton1) outputEventTree->HT += genPhoton1->pt;
    if (genPhoton2) outputEventTree->HT += genPhoton2->pt;
    

    //************************************
    //Extrapolation to 140 Pileup
    //************************************
    double pho1EffScalingForPU140 = 1.0;
    double pho2EffScalingForPU140 = 1.0;
    double bjet1EffScalingForPU140 = 1.0;
    double bjet2EffScalingForPU140 = 1.0;
    pho1EffScalingForPU140 = (0.85/0.95)*(0.85/0.95);
    pho2EffScalingForPU140 = (0.85/0.95)*(0.85/0.95);
    bjet1EffScalingForPU140 = (0.55/0.65);
    bjet2EffScalingForPU140 = (0.55/0.65);
    if (applyExtrapWeightTo140PU) {
      outputEventTree->weight = outputEventTree->weight * pho1EffScalingForPU140*pho2EffScalingForPU140*bjet1EffScalingForPU140*bjet2EffScalingForPU140;
    }




    //********************************************************
    //Fill Output Tree
    //********************************************************
    outputEventTree->tree_->Fill();
    nEvents++;


    //********************************************************
    //Debug
    //********************************************************    
    if (printdebug) {
      cout << "\n\nDebug Event: " << info->runNum << " " << info->lumiSec << " " << info->evtNum << "\n";
      if (genB1) cout << "GenB1: " << genB1->pt << " " << genB1->eta << " " << genB1->phi << "\n";
      if (genB2) cout << "GenB2: " << genB2->pt << " " << genB2->eta << " " << genB2->phi << "\n";
      if (genPhoton1) cout << "GenPho1: " << genPhoton1->pt << " " << genPhoton1->eta << " " << genPhoton1->phi << "\n";
      if (genPhoton2) cout << "GenPho2: " << genPhoton2->pt << " " << genPhoton2->eta << " " << genPhoton2->phi << "\n";
      cout << "NBGenJets = " << NBGenJets << "\n";

      for(Int_t i=0; i<genparticleArr->GetEntriesFast(); i++) {
        const cmsana::TGenParticle *p = (cmsana::TGenParticle*)((*genparticleArr)[i]);
        if ( (abs(p->pdgid) == 5 && p->pt > 0)
            || 
            ( p->pdgid == 22 && p->status==3 && ( p->motherPdgID == 21 || (abs(p->motherPdgID) >= 1 && abs(p->motherPdgID) <= 6) ) )
          ) {
          cout << p->pdgid << " " << p->status << " " << p->pt << " " << p->eta << " " << p->phi 
               << " | " << p->motherPdgID << "\n";
        }
      }

      for(Int_t i=0; i<genjetArr->GetEntriesFast(); i++) {
        const cmsana::TGenJet *genjet = (cmsana::TGenJet*)((*genjetArr)[i]);
        
        bool isStablePhoton = false;
        bool isTruthB = false;
        for(Int_t j=0; j<genparticleArr->GetEntriesFast(); j++) {
          const cmsana::TGenParticle *p = (cmsana::TGenParticle*)((*genparticleArr)[j]);

          if (p->pdgid == 22 && ( p->motherPdgID == 21 || (abs(p->motherPdgID) >= 1 && abs(p->motherPdgID) <= 6) ) 
              && cmsana::deltaR(p->eta,p->phi,genjet->eta,genjet->phi) < 0.5
            ) {
            //genjet matches to a stable photon. don't consider these
            isStablePhoton = true;
            break;
          }
        }

        if (abs(genjet->matchedPdgId) == 5) isTruthB = true;

        cout << "genjet " << i << " : " << genjet->pt << " " << genjet->eta << " " << genjet->phi << " " << genjet->mass << " | ";
        if (isStablePhoton) cout << " matched photon";
        if (isTruthB) cout << " matched b";
        cout << "\n";

      }
      
 
      cout << "All Gen Particles\n";
      for(Int_t i=0; i<genparticleArr->GetEntriesFast(); i++) {
        const cmsana::TGenParticle *p = (cmsana::TGenParticle*)((*genparticleArr)[i]);
        cout << p->pdgid << " " << p->status << " " << p->pt << " " << p->eta << " " << p->phi 
             << " | " << p->motherPdgID << "\n";
      }
      cout << "\n\n";

    }
    //********************************************************
    //End Debug
    //********************************************************



    //********************************************************
    //Clean up Memory
    //********************************************************

  }

  delete infile;
  infile=0, eventTree=0;      
  delete info;
  delete genparticleArr;
  delete genjetArr;
  
     
  //--------------------------------------------------------------------------------------------------------------
  // Output
  //==============================================================================================================
   
  
  outFile->Write();
  outFile->Close();
  delete outFile;
  
  cout << " Number of events selected: " << nEvents << endl;
  cout << endl;
  cout << "  <> Output saved in " << outputfile << endl;    
  cout << endl;  
      

}
Ejemplo n.º 11
0
int ScanChain( TChain* chain, bool fast = true, int nEvents = -1, string skimFilePrefix = "test") {

  //load PUweights
  TFile *fPU = new TFile("puWeights.root","READ");
  TH1D *puWeight     = (TH1D*)fPU->Get("puWeight");
  TH1D *puWeightUp   = (TH1D*)fPU->Get("puWeightUp");
  TH1D *puWeightDown = (TH1D*)fPU->Get("puWeightDown");

  TFile *fxsec = new TFile("xsec_stop_13TeV.root","READ");
  TH1D *hxsec     = (TH1D*)fxsec->Get("stop");

  TFile *f_el_SF       = new TFile("lepsf/kinematicBinSFele.root", "read");
  TFile *f_mu_SF_id    = new TFile("lepsf/TnP_MuonID_NUM_MediumID_DENOM_generalTracks_VAR_map_pt_eta.root", "read");
  TFile *f_mu_SF_iso   = new TFile("lepsf/TnP_MuonID_NUM_MiniIsoTight_DENOM_LooseID_VAR_map_pt_eta.root");
  TFile *f_mu_SF_veto_id  = new TFile("lepsf/TnP_MuonID_NUM_LooseID_DENOM_generalTracks_VAR_map_pt_eta.root", "read");
  TFile *f_mu_SF_veto_iso = new TFile("lepsf/TnP_MuonID_NUM_MiniIsoTight_DENOM_LooseID_VAR_map_pt_eta.root");
  //TFile *f_mu_SF_veto_iso = new TFile("lepsf/TnP_MuonID_NUM_MiniIsoLoose_DENOM_LooseID_VAR_map_pt_eta.root");
  //TFile *f_vetoLep_eff = new TFile("lepsf/lepeff__ttbar_powheg_pythia8_25ns.root", "read");
  TFile *f_vetoLep_eff = new TFile("lepsf/lepeff__ttbar_powheg_pythia8_25ns__SRcuts.root", "read");  
  TH2D *h_el_SF_id_temp      = (TH2D*)f_el_SF->Get("CutBasedMedium");
  TH2D *h_el_SF_iso_temp     = (TH2D*)f_el_SF->Get("MiniIso0p1_vs_AbsEta");
  TH2D *h_el_SF_veto_id_temp  = (TH2D*)f_el_SF->Get("CutBasedVeto");
  TH2D *h_el_SF_veto_iso_temp = (TH2D*)f_el_SF->Get("MiniIso0p4_vs_AbsEta");
  TH2D *h_mu_SF_id_temp      = (TH2D*)f_mu_SF_id->Get("pt_abseta_PLOT_pair_probeMultiplicity_bin0_&_tag_combRelIsoPF04dBeta_bin0_&_tag_pt_bin0_&_tag_IsoMu20_pass");
  TH2D *h_mu_SF_iso_temp     = (TH2D*)f_mu_SF_iso->Get("pt_abseta_PLOT_pair_probeMultiplicity_bin0_&_tag_combRelIsoPF04dBeta_bin0_&_tag_pt_bin0_&_PF_pass_&_tag_IsoMu20_pass");
  TH2D *h_mu_SF_veto_id_temp  = (TH2D*)f_mu_SF_veto_id->Get("pt_abseta_PLOT_pair_probeMultiplicity_bin0_&_tag_combRelIsoPF04dBeta_bin0_&_tag_pt_bin0_&_tag_IsoMu20_pass");
  TH2D *h_mu_SF_veto_iso_temp = (TH2D*)f_mu_SF_veto_iso->Get("pt_abseta_PLOT_pair_probeMultiplicity_bin0_&_tag_combRelIsoPF04dBeta_bin0_&_tag_pt_bin0_&_PF_pass_&_tag_IsoMu20_pass");
  //TH2D *h_el_vetoLepEff_temp = (TH2D*)f_vetoLep_eff->Get("h2_lepEff_vetoSel_Eff_el");
  //TH2D *h_mu_vetoLepEff_temp = (TH2D*)f_vetoLep_eff->Get("h2_lepEff_vetoSel_Eff_mu");
  TH2D *h_el_vetoLepEff_temp = (TH2D*)f_vetoLep_eff->Get("h2_lepEff_vetoSel_rebin_Eff_el");
  TH2D *h_mu_vetoLepEff_temp = (TH2D*)f_vetoLep_eff->Get("h2_lepEff_vetoSel_rebin_Eff_mu");
  TH2D *h_el_SF_id  = (TH2D*)h_el_SF_id_temp->Clone("h_el_SF_id");
  TH2D *h_el_SF_iso = (TH2D*)h_el_SF_iso_temp->Clone("h_el_SF_iso");
  TH2D *h_mu_SF_id  = (TH2D*)h_mu_SF_id_temp->Clone("h_mu_SF_id");
  TH2D *h_mu_SF_iso = (TH2D*)h_mu_SF_iso_temp->Clone("h_mu_SF_iso");
  TH2D *h_el_SF_veto_id  = (TH2D*)h_el_SF_veto_id_temp->Clone("h_el_SF_veto_id");
  TH2D *h_el_SF_veto_iso = (TH2D*)h_el_SF_veto_iso_temp->Clone("h_el_SF_veto_iso");
  TH2D *h_mu_SF_veto_id  = (TH2D*)h_mu_SF_veto_id_temp->Clone("h_mu_SF_veto_id");
  TH2D *h_mu_SF_veto_iso = (TH2D*)h_mu_SF_veto_iso_temp->Clone("h_mu_SF_veto_iso");
  //This is are the important ones
  TH2D *h_el_vetoLepEff = (TH2D*)h_el_vetoLepEff_temp->Clone("h_el_vetoLepEff");
  TH2D *h_mu_vetoLepEff = (TH2D*)h_mu_vetoLepEff_temp->Clone("h_mu_vetoLepEff");
  TH2D *h_el_SF = (TH2D*)h_el_SF_id->Clone("h_el_SF");
  h_el_SF->Multiply(h_el_SF_iso);
  TH2D *h_el_SF_veto = (TH2D*)h_el_SF_veto_id->Clone("h_el_SF_veto");
  TH2D *h_mu_SF = (TH2D*)h_mu_SF_id->Clone("h_mu_SF");
  h_mu_SF->Multiply(h_mu_SF_iso);
  TH2D *h_mu_SF_veto = (TH2D*)h_mu_SF_veto_id->Clone("h_mu_SF_veto");
  h_mu_SF_veto->Multiply(h_mu_SF_veto_iso);
  TFile *f_el_FS_ID       = new TFile("lepsf/sf_el_mediumCB.root", "read");
  TFile *f_el_FS_Iso      = new TFile("lepsf/sf_el_mini01.root", "read");
  TFile *f_mu_FS_ID       = new TFile("lepsf/sf_mu_mediumID.root", "read");
  TFile *f_mu_FS_Iso      = new TFile("lepsf/sf_mu_mini02.root", "read");
  TH2D *h_el_FS_ID_temp  = (TH2D*)f_el_FS_ID ->Get("histo2D");
  //TH2D *h_el_FS_ID       = (TH2D*)h_el_FS_ID_temp ->Clone("h_el_FS_ID");
  TH2D *h_el_FS          = (TH2D*)h_el_FS_ID_temp ->Clone("h_el_FS");
  TH2D *h_el_FS_Iso_temp = (TH2D*)f_el_FS_Iso->Get("histo2D");
  //TH2D *h_el_FS_Iso      = (TH2D*)h_el_FS_Iso_temp->Clone("h_el_FS_Iso");
  h_el_FS->Multiply(h_el_FS_Iso_temp);
  TH2D *h_mu_FS_ID_temp  = (TH2D*)f_mu_FS_ID ->Get("histo2D");
  //TH2D *h_mu_FS_ID       = (TH2D*)h_mu_FS_ID_temp ->Clone("h_mu_FS_ID");
  TH2D *h_mu_FS          = (TH2D*)h_mu_FS_ID_temp ->Clone("h_mu_FS");
  TH2D *h_mu_FS_Iso_temp = (TH2D*)f_mu_FS_Iso->Get("histo2D");
  //TH2D *h_mu_FS_Iso      = (TH2D*)h_mu_FS_Iso_temp->Clone("h_mu_FS_ID");
  h_mu_FS->Multiply(h_mu_FS_Iso_temp);

  
  // Benchmark
  TBenchmark *bmark = new TBenchmark();
  bmark->Start("benchmark");

  // Example Histograms
  TDirectory *rootdir = gDirectory->GetDirectory("Rint:");


  map<string, TH3D*> histos;//use D histos as weights can vary a lot among the signal
  vector<string> histonames; histonames.clear();
  //  vector<int> hbins; hbins.clear();
  //  vector<float> hlow; hlow.clear();
  //  vector<float> hup; hup.clear();

  //lumi, trigger, stats done
  histonames.push_back("SRyield");
  histonames.push_back("SR_Bup_HF");//done
  histonames.push_back("SR_Bdown_HF");
  histonames.push_back("SR_Bup_LF");//done
  histonames.push_back("SR_Bdown_LF");
  histonames.push_back("SR_JESup");
  histonames.push_back("SR_JESdown");
  histonames.push_back("SR_muRFup");
  histonames.push_back("SR_muRFdown");
  //histonames.push_back("SR_PDFup");
  //histonames.push_back("SR_PDFdown");
  histonames.push_back("SR_ISRup");//done preliminary
  histonames.push_back("SR_ISRdown");
  histonames.push_back("SR_PUup");//done preliminary
  histonames.push_back("SR_PUdown");
  histonames.push_back("SR_LepEffup");//done - I guess we need no renormalization - no fastsim in, no vetoSF
  histonames.push_back("SR_LepEffdown");
  histonames.push_back("SR_LepEffFSup");//done - I guess we need no renormalization - no fastsim in, no vetoSF
  histonames.push_back("SR_LepEffFSdown");
  histonames.push_back("SR_Xsecup");//done
  histonames.push_back("SR_Xsecdown");
  histonames.push_back("CR1l_sigcontamination");//scaled to signalreg yield
  histonames.push_back("CR2l_sigcontamination");//scaled to signalreg yield
  /*
  histonames.push_back("eventsum");
  histonames.push_back("rawweightsum");
  histonames.push_back("totweightsum");
  histonames.push_back("ISRsum");
  histonames.push_back("BSFsum");
  histonames.push_back("PUweightsum");
  histonames.push_back("xsecsum");
  histonames.push_back("nevtsum");
  histonames.push_back("lepsum");
  histonames.push_back("lepSFsum");
  */
  for(unsigned int i = 0; i<histonames.size(); ++i){
    string mapname = histonames[i];
    if(histos.count(mapname) == 0 ) histos[mapname] = new TH3D(mapname.c_str(), "", 37,99,1024, 19,-1,474, 13, -0.5,12.5);
    //mStop 100-1000, mLSP 0-450, SR 1-12, 9200 bins, SR 0 is non-SR - in case it it needed!!
      histos[mapname]->Sumw2(); histos[mapname]->SetDirectory(rootdir);
    }

  
  
  // Loop over events to Analyze
  unsigned int nEventsTotal = 0;
  unsigned int nEventsChain = chain->GetEntries();
  if( nEvents >= 0 ) nEventsChain = nEvents;
  TObjArray *listOfFiles = chain->GetListOfFiles();
  TIter fileIter(listOfFiles);
  TFile *currentFile = 0;

  //get the reweighting histograms
  TIter fileIterFirst(listOfFiles);
  TFile *currentFileFirst = 0;
  TH3D* counterhistSig;
  TH2F* histNEvts;
  bool thisisfirst = true;
  // File Loop for adding correct histograms
  while ( (currentFileFirst = (TFile*)fileIterFirst.Next()) ) {
    TFile *file = new TFile( currentFileFirst->GetTitle() );
    file->cd();
    if(thisisfirst){
      counterhistSig = (TH3D*)file->Get("h_counterSMS");
      counterhistSig->SetDirectory(0); 
      histNEvts = (TH2F*)file->Get("histNEvts");
      histNEvts->SetDirectory(0);
      thisisfirst = false;
    } else {
      TH3D *tempcounterhistSig = (TH3D*)file->Get("h_counterSMS");
      tempcounterhistSig->SetDirectory(0); 
      TH2F *temphistNEvts = (TH2F*)file->Get("histNEvts");
      temphistNEvts->SetDirectory(0);
      counterhistSig->Add(tempcounterhistSig);
      histNEvts->Add(temphistNEvts);
      tempcounterhistSig->Delete();
      temphistNEvts->Delete();
    }
    file->Close();
    delete file;
  }

  // File Loop
  while ( (currentFile = (TFile*)fileIter.Next()) ) {

    // Get File Content
    TFile *file = new TFile( currentFile->GetTitle() );
    TTree *tree = (TTree*)file->Get("t");
    if(fast) TTreeCache::SetLearnEntries(10);
    if(fast) tree->SetCacheSize(128*1024*1024);
    cms3.Init(tree);
    
    // Loop over Events in current file
    if( nEventsTotal >= nEventsChain ) continue;
    unsigned int nEventsTree = tree->GetEntriesFast();
    for( unsigned int event = 0; event < nEventsTree; ++event) {
 
      // Get Event Content
      if( nEventsTotal >= nEventsChain ) continue;
      if(fast) tree->LoadTree(event);
      cms3.GetEntry(event);
      ++nEventsTotal;
    
      // Progress
      CMS3::progress( nEventsTotal, nEventsChain );

      // Analysis Code

      float mStop = mass_stop();
      float mLSP = mass_lsp();
      float mCharg = mass_chargino();
      //float xVal = mass_lsp();
      int Nevts = histNEvts->GetBinContent(histNEvts->FindBin(mStop,mLSP));
      double nevts = double(Nevts);
      //float weight = cms3.scale1fb()*2.11;
      double PUweight     = puWeight    ->GetBinContent(puWeight    ->FindBin(pu_ntrue() ) );
      double PUweightUp   = puWeightUp  ->GetBinContent(puWeightUp  ->FindBin(pu_ntrue() ) );
      double PUweightDown = puWeightDown->GetBinContent(puWeightDown->FindBin(pu_ntrue() ) );
      PUweightUp = 1; PUweightDown = PUweight; PUweight = 1; //now PU syst is applying vs not applying
     double ISRnorm = counterhistSig->GetBinContent(counterhistSig->FindBin(mStop,mLSP,19));
      double ISRnormup = counterhistSig->GetBinContent(counterhistSig->FindBin(mStop,mLSP,20));
      double ISRnormdown = counterhistSig->GetBinContent(counterhistSig->FindBin(mStop,mLSP,21));
      double ISRweight = weight_ISR();
      double BSFnorm = counterhistSig->GetBinContent(counterhistSig->FindBin(mStop,mLSP,14));
      double BSFnormHup = counterhistSig->GetBinContent(counterhistSig->FindBin(mStop,mLSP,15));
      double BSFnormLup = counterhistSig->GetBinContent(counterhistSig->FindBin(mStop,mLSP,16));
      double BSFnormHdown = counterhistSig->GetBinContent(counterhistSig->FindBin(mStop,mLSP,17));
      double BSFnormLdown = counterhistSig->GetBinContent(counterhistSig->FindBin(mStop,mLSP,18));
      double BSFweight = weight_btagsf();
      double muRFnorm = counterhistSig->GetBinContent(counterhistSig->FindBin(mStop,mLSP,1));
      double muRFnormup = counterhistSig->GetBinContent(counterhistSig->FindBin(mStop,mLSP,5));
      double muRFnormdown = counterhistSig->GetBinContent(counterhistSig->FindBin(mStop,mLSP,9));
      if(ISRnorm>0) ISRweight*=nevts/ISRnorm;
      if(ISRnorm<=0||ISRnormup<=0||ISRnormdown<=0){ ISRnormdown=1.; ISRnormup=1.; ISRnorm=1.;}
      if(ISRweight!=weight_ISR()) cout << "ISRw " << ISRweight << " wISR " << weight_ISR() << " nevts " << nevts << " ISRn " << ISRnorm << endl;
      if(BSFnorm>0) BSFweight *=nevts/BSFnorm;
      if(BSFnorm<=0||BSFnormHup<=0||BSFnormLup<=0||BSFnormHdown<=0||BSFnormLdown<=0){
	BSFnorm=1; BSFnormHup=1; BSFnormLup=1; BSFnormHdown=1; BSFnormLdown=1;
      }
      if(muRFnorm<=0||muRFnormup<=0||muRFnormdown<=0){ muRFnormdown=1; muRFnormup=1; muRFnorm=1; }
      //lepSF is done below
      double xsection = hxsec->GetBinContent(hxsec->FindBin(mStop));
      double xsectionerr = hxsec->GetBinError(hxsec->FindBin(mStop));
      //double rawweight = xsec()*2260./nevts;
      //double weight = xsec()*2260./nevts*PUweight*ISRweight*BSFweight;//xsec given in pb
      double rawweight = xsection*2260./nevts;
      double weight = xsection*2260./nevts*PUweight*ISRweight*BSFweight;//xsec given in pb
      //did put ISRweight which should be ==1
      if(ISRweight!=1) cout << "ISRw " << ISRweight << endl;
      if(event==0) cout << "weight " << weight << " nEvents " << nEventsTree << " filename " << currentFile->GetTitle() << endl;

      int NSLeps = 0;
      int NAddVetoLeps = 0;
      if(lep1_is_mu()){
	if(lep1_pt()>20&&fabs(lep1_eta())<2.4) {++NSLeps;}
      } else if (lep1_is_el()){
	if(lep1_pt()>20&&fabs(lep1_eta())<1.4442) {++NSLeps; }
      } if(lep2_is_mu()){
	if(lep2_pt()>20&&fabs(lep2_eta())<2.4) {++NSLeps;}
      } else if (lep2_is_el()){
	if(lep2_pt()>20&&fabs(lep2_eta())<1.4442) {++NSLeps; }
      }
      if(lep2_is_mu()){
	if(lep2_pt()>10&&fabs(lep2_eta())<2.4) {++NAddVetoLeps;}
      } else if (lep2_is_el()){
	if(lep2_pt()>10&&fabs(lep2_eta())<2.4) {++NAddVetoLeps; }
      }
      if(NSLeps<1) continue;//temp
      float lepSF_pt_cutoff = 100.0;
      float lepSF_pt_min    = 10.0;
      double lepSF    = 1.0;
      double lepSF_Up = 1.0;
      double lepSF_Dn = 1.0;
      float lepSF_FS_pt_cutoff = 200.0;
      double lepSF_FS    = 1.0;
      double lepSF_FS_Up = 1.0;
      double lepSF_FS_Dn = 1.0;	
      if(lep1_is_el()){
	int binX = h_el_SF->GetXaxis()->FindBin( std::min(lepSF_pt_cutoff, (float)lep1_p4().Pt()) );
	int binY = h_el_SF->GetYaxis()->FindBin( fabs(lep1_p4().Eta()) );
	lepSF    = h_el_SF->GetBinContent( binX, binY );
	lepSF_Up = lepSF + h_el_SF->GetBinError( binX, binY );
	lepSF_Dn = lepSF - h_el_SF->GetBinError( binX, binY );
	int bin = h_el_FS->FindBin(  std::min(lepSF_FS_pt_cutoff, (float)lep1_p4().Pt()), fabs(lep1_p4().Eta()) );
	lepSF_FS = h_el_FS->GetBinContent(bin);
	lepSF_FS_Up = lepSF_FS + h_el_FS->GetBinError(bin);
	lepSF_FS_Dn = lepSF_FS + h_el_FS->GetBinError(bin);
      }
      if(lep1_is_mu()){
	int binX = h_mu_SF->GetXaxis()->FindBin( std::min(lepSF_pt_cutoff, (float)lep1_p4().Pt()) );
	int binY = h_mu_SF->GetYaxis()->FindBin( fabs(lep1_p4().Eta()) );
	lepSF    = h_mu_SF->GetBinContent( binX, binY );
	lepSF_Up = lepSF + h_mu_SF->GetBinError( binX, binY );
	lepSF_Dn = lepSF - h_mu_SF->GetBinError( binX, binY );
	int bin = h_mu_FS->FindBin(  std::min(lepSF_FS_pt_cutoff, (float)lep1_p4().Pt()), fabs(lep1_p4().Eta()) );
	lepSF_FS = h_mu_FS->GetBinContent(bin);
	lepSF_FS_Up = lepSF_FS + h_mu_FS->GetBinError(bin);
	lepSF_FS_Dn = lepSF_FS + h_mu_FS->GetBinError(bin);
      }
      weight *= (lepSF*lepSF_FS);

      
      if(nvtxs()<0)               continue;
      if(ngoodleps()<1)           continue;//accomodate 2l-CR
      if(nvetoleps()<1)           continue;//accomodate 2l-CR
    //if(!PassTrackVeto_v3())     continue;//accomodate 2l-CR
    //if(!PassTauVeto())          continue;//accomodate 2l-CR
      if(ngoodjets()<2)           continue;
      if(ngoodbtags()<0)          continue;//accomodate 1l-CR
      if(pfmet()<250)             continue;
      if(mt_met_lep()<150)        continue;
      if(mindphi_met_j1_j2()<0.8) continue;


      int SR = -1;
      int compressedSR = -1;
      if(ngoodleps()==1&&nvetoleps()==1&&PassTrackVeto_v3()&&PassTauVeto()&&ngoodbtags()>=1){//basis for SR 1l, >=1b
	if(ngoodjets()>=4){
	  if(MT2W()<=200){
	    if(pfmet()>325) SR = 2;
	    else SR = 1;
	  } else { //high MT2W
	    if(pfmet()>450) SR = 5;
	    else if(pfmet()>350) SR = 4;
	    else SR = 3;
	  }
	} else if(ngoodjets()==3 && MT2W()>200 && pfmet()>350) {
	  SR = 6;
	} else if(MT2W()>200&&topnessMod()>(-3)) { //2 or 3 jets
	  if(ngoodbtags()==1){
	    if(pfmet()>400) SR = 8;
	    else SR = 7;
	  } else {//ge2 jets
	    if(pfmet()>400) SR = 10;
	    else SR = 9;
	  }
	}
	//compressed region (jets are sorted by pt
	if(ngoodjets()>=5&&ak4pfjets_passMEDbtag()[0]==false&&ak4pfjets_pt()[0]>200.){
	  if(MT2W()<=200) compressedSR = 11;
	  else compressedSR = 12;
	}
      }

      //CR-1l
      int CR1l = -1;
      if(ngoodleps()==1&&nvetoleps()==1&&PassTrackVeto_v3()&&PassTauVeto()&&ngoodbtags()==0&&ngoodjets()>=3&&MT2W()>200){
	if(ngoodjets()==3){
	  CR1l = 1;
	} else {
	  CR1l = 2;
	}
      }
      //CR1l  1 --> SR  6
      //CR1l  2 --> SR  3-5
      float CR1l_1_6 = 0.37*0.18;
      float CR1l_2_3 = 0.55*0.15;
      float CR1l_2_4 = 0.25*0.29;
      float CR1l_2_5 = 0.20*0.40;

      //CR2l = -1;
      int lepind = -1;
      if(ngoodleps()>=2&&NSLeps==2) lepind = 5;
      else if(ngoodleps()==2&&NSLeps==2) lepind = 4;//exactly two leptons,CR4
      else if(ngoodleps()==1&&NSLeps==1&&NAddVetoLeps>=1) lepind = 3;//one lepton, but more than 1 add. loose,1l,>2l
      //else if(ngoodleps()==1&&NSLeps==1&&nvetoleps()==2) lepind = 2;//one lepton + 1 add. loose,CR5
      else if(ngoodleps()==1&&NSLeps==1&&nvetoleps()==0&&(!PassTrackVeto_v3()||!PassTauVeto())) lepind = 1;//exactly one lepton, but do not pass track/tau veto - i.e. one additional track or tau, CR6
      int CR2l = -1;
      if((lepind==4||lepind==3||lepind==1)&&ngoodjets()>=3&&ngoodbtags()>=1){
	if(MT2W()<=200) CR2l = 1;
	else CR2l = 2;
      }
      float CR2l_1_1 = 0.61*0.48;
      float CR2l_1_2 = 0.61*0.19;
      float CR2l_2_3 = 0.44*0.39;
      float CR2l_2_4 = 0.44*0.11;
      float CR2l_2_5 = 0.44*0.07;
      float CR2l_2_6 = 0.44*0.11;

      if(SR==(-1)&&CR1l==(-1)&&CR2l==(-1)&&compressedSR==(-1)) continue;
      //implement some sanity checks
      if(CR1l!=(-1)&&CR2l!=(-1)) cout << "WTF CR1l " << CR1l << " CR2l " << CR2l << endl;
      if(SR!=(-1)&&CR1l!=(-1)) cout << "WTF SR " << SR << " CR1l " << CR1l << endl;
      if(SR!=(-1)&&CR2l!=(-1)) cout << "WTF SR " << SR << " CR2l " << CR2l << endl;

      //ISR reweighting, get stop pair using last copy:
      double ISRup = weight_ISRup()/weight_ISR()*ISRnorm/ISRnormup;
      double ISRdown = weight_ISRdown()/weight_ISR()*ISRnorm/ISRnormdown;
      //double XSup = (xsec()+xsec_uncert())/xsec();
      //double XSdown = (xsec()-xsec_uncert())/xsec();
      double XSup = (xsection+xsectionerr)/xsection;
      double XSdown = (xsection-xsectionerr)/xsection;
      double PUup = PUweightUp/PUweight;
      double PUdown = PUweightDown/PUweight;
      double lEffup = lepSF_Up/lepSF;
      double lEffdown = lepSF_Dn/lepSF;
      double lEffFSup = lepSF_FS_Up/lepSF_FS;
      double lEffFSdown = lepSF_FS_Dn/lepSF_FS;
      double BSFHup = weight_btagsf_heavy_UP()/weight_btagsf()*BSFnorm/BSFnormHup;
      double BSFLup = weight_btagsf_light_UP()/weight_btagsf()*BSFnorm/BSFnormHup;
      double BSFHdown = weight_btagsf_heavy_DN()/weight_btagsf()*BSFnorm/BSFnormHup;
      double BSFLdown = weight_btagsf_light_DN()/weight_btagsf()*BSFnorm/BSFnormHup;
      double muRFup = genweights().at(4)/genweights().at(0)*muRFnorm/muRFnormup;
      double muRFdown = genweights().at(8)/genweights().at(0)*muRFnorm/muRFnormdown;
      //cout << genweights().at(0) << " " << genweights().at(4) << " " << genweights().at(8) << " " << mStop << " " << mLSP << endl;

      if(CR1l>0){
	if(ngoodleps()!=1) cout << __LINE__ << " " << ngoodleps() << endl;
	if(NSLeps!=1) cout << __LINE__ << " " << NSLeps << endl;
	if(nvetoleps()!=1) cout << __LINE__ << " " << nvetoleps() << endl;
	if(ngoodbtags()>=1) cout << __LINE__ << " " << ngoodbtags() << endl;
	//signal contamination in 0b control region, do correlations later during datacard making
	if(CR1l==1){
	  histos["CR1l_sigcontamination"]->Fill(mStop,mLSP,6,weight*CR1l_1_6);
	} else if(CR1l==2){
	  histos["CR1l_sigcontamination"]->Fill(mStop,mLSP,3,weight*CR1l_2_3);
	  histos["CR1l_sigcontamination"]->Fill(mStop,mLSP,4,weight*CR1l_2_4);
	  histos["CR1l_sigcontamination"]->Fill(mStop,mLSP,5,weight*CR1l_2_5);
	}
      } else if(CR2l>0){
	if(nvetoleps()<=1||(nvetoleps()==1&&(!PassTrackVeto_v3()||!PassTauVeto()))) cout << __LINE__ << " " << nvetoleps() << " " << PassTrackVeto_v3() << " " << PassTauVeto() << endl;
	if(ngoodbtags()<1) cout << __LINE__ << " " << ngoodbtags() << endl;
	//signal contamination in 2l control region, do correlations later during datacard making
	if(CR2l==1){
	  histos["CR2l_sigcontamination"]->Fill(mStop,mLSP,1,weight*CR2l_1_1);
	  histos["CR2l_sigcontamination"]->Fill(mStop,mLSP,2,weight*CR2l_1_2);
	} else if(CR2l==2){
	  histos["CR2l_sigcontamination"]->Fill(mStop,mLSP,3,weight*CR2l_2_3);
	  histos["CR2l_sigcontamination"]->Fill(mStop,mLSP,4,weight*CR2l_2_4);
	  histos["CR2l_sigcontamination"]->Fill(mStop,mLSP,5,weight*CR2l_2_5);
	  histos["CR2l_sigcontamination"]->Fill(mStop,mLSP,6,weight*CR2l_2_6);

	}
      } else if(SR>0){
	if(ngoodleps()!=1) cout << __LINE__ << " " << ngoodleps() << endl;
	if(NSLeps!=1) cout << __LINE__ << " " << NSLeps << endl;
	if(nvetoleps()!=1) cout << __LINE__ << " " << nvetoleps() << endl;
	if(!PassTrackVeto_v3())  cout << __LINE__ << endl;
	if(!PassTauVeto())  cout << __LINE__ << endl;
	if(SR<=6&&ngoodjets()<3) cout << __LINE__ << " " << ngoodjets() << endl;
	if(ngoodbtags()<1) cout << __LINE__ << " " << ngoodbtags() << endl;
	/*
	histos["eventsum"]->Fill(mStop,mLSP,SR,1.);
	histos["rawweightsum"]->Fill(mStop,mLSP,SR,rawweight);
	histos["totweightsum"]->Fill(mStop,mLSP,SR,weight);
	histos["ISRsum"]->Fill(mStop,mLSP,SR,ISRweight);
	histos["BSFsum"]->Fill(mStop,mLSP,SR,BSFweight);
	histos["PUweightsum"]->Fill(mStop,mLSP,SR,PUweight);
	histos["xsecsum"]->Fill(mStop,mLSP,SR,xsection);
	histos["nevtsum"]->Fill(mStop,mLSP,SR,nevts);
	histos["lepsum"]->Fill(mStop,mLSP,SR,lepSF);
	histos["lepSFsum"]->Fill(mStop,mLSP,SR,lepSF_FS);
	*/
	//finally - do signal regions!
	histos["SRyield"]->Fill(mStop,mLSP,SR,weight);
	histos["SR_ISRup"]->Fill(mStop,mLSP,SR,weight*ISRup);
	histos["SR_ISRdown"]->Fill(mStop,mLSP,SR,weight*ISRdown);
	histos["SR_Xsecup"]->Fill(mStop,mLSP,SR,weight*XSup);
	histos["SR_Xsecdown"]->Fill(mStop,mLSP,SR,weight*XSdown);
	histos["SR_PUup"]->Fill(mStop,mLSP,SR,weight*PUup);
	histos["SR_PUdown"]->Fill(mStop,mLSP,SR,weight*PUdown);
	histos["SR_Bup_HF"]->Fill(mStop,mLSP,SR,weight*BSFHup);
	histos["SR_Bup_LF"]->Fill(mStop,mLSP,SR,weight*BSFLup);
	histos["SR_Bdown_HF"]->Fill(mStop,mLSP,SR,weight*BSFHdown);
	histos["SR_Bdown_LF"]->Fill(mStop,mLSP,SR,weight*BSFLdown);
	histos["SR_LepEffup"]->Fill(mStop,mLSP,SR,weight*lEffup);
	histos["SR_LepEffdown"]->Fill(mStop,mLSP,SR,weight*lEffdown);
	histos["SR_LepEffFSup"]->Fill(mStop,mLSP,SR,weight*lEffFSup);
	histos["SR_LepEffFSdown"]->Fill(mStop,mLSP,SR,weight*lEffFSdown);
	histos["SR_muRFup"]->Fill(mStop,mLSP,SR,weight*muRFup);
	histos["SR_muRFdown"]->Fill(mStop,mLSP,SR,weight*muRFdown);
      }
      if(compressedSR>0){
	if(compressedSR<=6) cout << __LINE__ << " " << compressedSR << endl;
	//compressedSR is defined to not overlap with SR - can use same histogram!
	histos["SRyield"]->Fill(mStop,mLSP,compressedSR,weight);
	histos["SR_ISRup"]->Fill(mStop,mLSP,compressedSR,weight*ISRup);
	histos["SR_ISRdown"]->Fill(mStop,mLSP,compressedSR,weight*ISRdown);
	histos["SR_Xsecup"]->Fill(mStop,mLSP,compressedSR,weight*XSup);
	histos["SR_Xsecdown"]->Fill(mStop,mLSP,compressedSR,weight*XSdown);
	histos["SR_PUup"]->Fill(mStop,mLSP,compressedSR,weight*PUup);
	histos["SR_PUdown"]->Fill(mStop,mLSP,compressedSR,weight*PUdown);
	histos["SR_Bup_HF"]->Fill(mStop,mLSP,compressedSR,weight*BSFHup);
	histos["SR_Bup_LF"]->Fill(mStop,mLSP,compressedSR,weight*BSFLup);
	histos["SR_Bdown_HF"]->Fill(mStop,mLSP,compressedSR,weight*BSFHdown);
	histos["SR_Bdown_LF"]->Fill(mStop,mLSP,compressedSR,weight*BSFLdown);
	histos["SR_LepEffup"]->Fill(mStop,mLSP,compressedSR,weight*lEffup);
	histos["SR_LepEffdown"]->Fill(mStop,mLSP,compressedSR,weight*lEffdown);
	histos["SR_LepEffFSup"]->Fill(mStop,mLSP,compressedSR,weight*lEffFSup);
	histos["SR_LepEffFSdown"]->Fill(mStop,mLSP,compressedSR,weight*lEffFSdown);
	histos["SR_muRFup"]->Fill(mStop,mLSP,compressedSR,weight*muRFup);
	histos["SR_muRFdown"]->Fill(mStop,mLSP,compressedSR,weight*muRFdown);
      }

    }//event loop
  
    // Clean Up
    delete tree;
    file->Close();
    delete file;
  }//file loop
  if ( nEventsChain != nEventsTotal ) {
    cout << Form( "ERROR: number of events from files (%d) is not equal to total number of events (%d)", nEventsChain, nEventsTotal ) << endl;
  }
  
  // Example Histograms
  // samplehisto->Draw();

  /*
  for(map<string,TH3D*>::iterator h=histos.begin(); h!=histos.end();++h){
    //add overflow
    //h->second->SetBinContent(h->second->GetNbinsX(), h->second->GetBinContent(h->second->GetNbinsX() )+ h->second->GetBinContent(h->second->GetNbinsX()+1) );
    //h->second->SetBinError(h->second->GetNbinsX(), sqrt(pow(h->second->GetBinError(h->second->GetNbinsX() ),2)+pow(h->second->GetBinError(h->second->GetNbinsX()+1),2) ) );
    //add underfloe
    //h->second->SetBinContent(1, h->second->GetBinContent(1)+ h->second->GetBinContent(0) );
    //h->second->SetBinError(1, sqrt(pow(h->second->GetBinError(1),2)+pow(h->second->GetBinError(0),2) ) );
  }
  */
  string filename = "rootfiles/signalyields/Histos_"+skimFilePrefix+".root";
  TFile *f = new TFile(filename.c_str(),"RECREATE");
  f->cd();
  for(map<string,TH3D*>::iterator h=    histos.begin(); h!=    histos.end();++h) h->second->Write();
  f->Close();
  cout << "Saved histos in " << f->GetName() << endl;

  f_el_SF->Close();
  f_mu_SF_id->Close();
  f_mu_SF_iso->Close();
  f_mu_SF_veto_id->Close();
  f_mu_SF_veto_iso->Close();
  f_vetoLep_eff->Close();
  f_el_FS_ID->Close();
  f_el_FS_Iso->Close();
  f_mu_FS_ID->Close();
  f_mu_FS_Iso->Close();
  // return
  bmark->Stop("benchmark");
  cout << endl;
  cout << nEventsTotal << " Events Processed" << endl;
  cout << "------------------------------" << endl;
  cout << "CPU  Time:	" << Form( "%.01f", bmark->GetCpuTime("benchmark")  ) << endl;
  cout << "Real Time:	" << Form( "%.01f", bmark->GetRealTime("benchmark") ) << endl;
  cout << endl;
  delete bmark;
  delete fPU;//delete PU file
  delete f_el_SF;
  delete f_mu_SF_id;
  delete f_mu_SF_iso;
  delete f_mu_SF_veto_id;
  delete f_mu_SF_veto_iso;
  delete f_vetoLep_eff;
  delete f_el_FS_ID;
  delete f_el_FS_Iso;
  delete f_mu_FS_ID;
  delete f_mu_FS_Iso;
  return 0;
}