Esempio n. 1
0
void combineBins(int mass, double scale_factor = 1.0){ //mass = mass of tprime quark

  //define some parameters
  //char fname[100]={"data/mujets_821/tprime_mujets_2D_821ipb.root"}; //input file name
  char fname[100]={"data/ejets_3560/tprime_ejets_2D_3560ipb.root"}; //input file name
  char oname[256]; //output file name
  char sname[100]; //name of signal histogram
  //sprintf(oname,"data/mujets_821/tprime_%i_mujets_2D_821ipb_merged_15jul2011test.root",mass);
  sprintf(oname,"data/mujets_821/tprime_%i_mujets_2D_821ipb_merged_test.root",mass);
  sprintf(sname,"TPrime%i_HtvsMfit",mass);
  char bname[20][100]={ //array of data and background histograms
    "Data_HtvsMfit", //data histogram must be first in this list
    "TTjets_HtvsMfit",
    "Ewk_HtvsMfit",
    "TPrime%i_HtvsMfit_JESup",
    "TPrime%i_HtvsMfit_JESdown",
    "TTjets_HtvsMfit_JESup",
    "TTjets_HtvsMfit_JESdown",
    "Ewk_HtvsMfit_JESup",
    "Ewk_HtvsMfit_JESdown"
  };
  
  int nb=9; //number of histograms in list
  int n_skip=3; // starting with this index, do not consider for background normalization
  float femax=0.20; //max fractional error in each bin of background histogram

  TFile *f = TFile::Open(fname);
  if (f==NULL) {
    printf("Cannot open file '%s'\n",fname);
    return;
  }

  TH2F* hs; f->GetObject(sname,hs); 
  // Gena: scale signal template to proper cross section
  hs->Scale(scale_factor);
  if (hs==NULL) {
    printf("Cannot find histogram '%s' in '%s'\n",sname,fname);
    return;
  }

  //figure out the binning
  int nx = hs->GetNbinsX()+2;
  int ny = hs->GetNbinsY()+2;

  // cross check printout
  std::cout << "2D hist name: " << hs->GetName() << std::endl;
  std::cout << "Integral with overflow: " << hs->Integral(0,nx-1,0,ny-1) << std::endl;
  std::cout << "Integral no overflow: " << hs->Integral(1,nx-2,1,ny-2) << std::endl << std::endl;

  TH2F *hb = (TH2F*)hs->Clone(); 
  hb->SetName("hb");
  hb->Reset();
  TH2F *hX[20];
  for (int i=0;i<nb;i++){
    std::string sBName(bname[i]);
    // GENA: get names for signal JES histos
    if (sBName.find("TPrime")!=std::string::npos ||
	sBName.find("Tprime")!=std::string::npos ||
	sBName.find("tprime")!=std::string::npos){

      sprintf(bname[i],sBName.c_str(),mass);
      std::cout << bname[i] << std::endl;
    }

    f->GetObject(bname[i],hX[i]); 

    // GENA: scale JES signal templates to proper cross section
    if (sBName.find("TPrime")!=std::string::npos ||
	sBName.find("Tprime")!=std::string::npos ||
	sBName.find("tprime")!=std::string::npos){
      hX[i]->Scale(scale_factor);      
    }
    if (hX[i]==NULL) {
      printf("Cannot find histogram '%s' in '%s'\n",bname[i],fname);
      return;
    }
    //hX[i]->Print("base");
    std::cout << "2D hist name: " << hX[i]->GetName() << std::endl;
    std::cout << "Integral with overflow: " << hX[i]->Integral(0,nx-1,0,ny-1) << std::endl;
    std::cout << "Integral no overflow: " << hX[i]->Integral(1,nx-2,1,ny-2) << std::endl << std::endl;
    //sum all background histograms into hb; do not add the data histogram
    if (i>0 && i<n_skip) hb->Add(hX[i]); 
  }

  //figure out the binning
  //int nx = hs->GetNbinsX()+2;
  //int ny = hs->GetNbinsY()+2;
  int nbin=nx*ny;
  std::cout << "number of bins: x="<<nx<<", y="<<ny<<std::endl;
  
  //book some 1d histograms with the same number of bins for diagnostics
  TH1F *h1sb = new TH1F("h1sb","h1sb",nbin,0,nbin);
  TH1F *h1s = new TH1F("h1s","h1s",nbin,0,nbin);
  TH1F *h1b = new TH1F("h1b","h1b",nbin,0,nbin);
  // GENA: vector to create 2D->1D bin map
  std::vector<std::vector<int> > vMap(nbin);

  float xs,xb;
  //xsb holds the s/b values for each bin
  //xx are the histogram contents 
  //(0=signal, 1=total background, 2=data, 3...nb-1=individual backgrounds) GENA: nb+1 ?
  float xsb[30000],xx[30000][20],xe[30000][20];
  int ibin; 
  double _sum = 0.0;
  for (int i=0;i<nx;i++){
    for (int j=0;j<ny;j++){

      ibin=hs->GetBin(i,j);

      // GENA: Will fill each bin with its original index
      vMap[ibin].push_back(ibin);

      xs=hs->GetBinContent(ibin);
      xb=hb->GetBinContent(ibin);
      //compute signal/background
      if (xb>0) {
	xsb[ibin]=xs/xb;
      }else{
	if (xs>0){
	  xsb[ibin]=999;
	}else{
	  xsb[ibin]=0;
	}
      }
      xx[ibin][0]=xs;
      xe[ibin][0]=hs->GetBinError(ibin);
      xx[ibin][1]=xb;
      xe[ibin][1]=hb->GetBinError(ibin);
      for (int k=0;k<nb;k++){
	xx[ibin][k+2]=hX[k]->GetBinContent(ibin);
	xe[ibin][k+2]=hX[k]->GetBinError(ibin);
      }
      if (xb>0) h1sb->SetBinContent(ibin,xs/xb);
      h1s->SetBinContent(ibin,xx[ibin][0]);
      h1s->SetBinError(ibin,xe[ibin][0]);
      h1b->SetBinContent(ibin,xx[ibin][1]);
      h1b->SetBinError(ibin,xe[ibin][1]);
      
      _sum += xx[ibin][0];
    }
  }

  std::cout << "SUM: " << _sum << std::endl;

  //sort all histogram bins in decreasing s/b
  int nswap=1;
  float xtmp;

  // GENA: for bin map
  int ibin_tmp;

  while (nswap>0) {
    nswap=0;
    for (int i=0;i<nbin-1;i++) {
      if (xsb[i]<xsb[i+1]){
	xtmp=xsb[i];
	xsb[i]=xsb[i+1];
	xsb[i+1]=xtmp;

	// GENA: for bin map
	ibin_tmp = vMap[i][0];
	vMap[i][0] = vMap[i+1][0];
	vMap[i+1][0] = ibin_tmp;

	for (int j=0;j<nb+2;j++){
	  xtmp=xx[i][j];
	  xx[i][j]=xx[i+1][j];
	  xx[i+1][j]=xtmp;

	  xtmp=xe[i][j];
	  xe[i][j]=xe[i+1][j];
	  xe[i+1][j]=xtmp;
	}
	nswap=nswap+1;
      }
    }
  }

  //these histograms have the bins ordered in decrerasing s/b for diagnostics
  TH1F *h1sb1 = new TH1F("h1sb1","h1sb1",nbin,0,nbin);
  TH1F *h1fe1 = new TH1F("h1fe1","h1fe1",nbin,0,nbin);
  TH1F *h1s1 = new TH1F("h1s1","h1s1",nbin,0,nbin);
  TH1F *h1b1 = new TH1F("h1b1","h1b1",nbin,0,nbin);
  for (int i=0;i<nbin;i++){
    h1sb1->SetBinContent(i+1,xsb[i]);
    if (xx[i][1]>0) h1fe1->SetBinContent(i+1,xe[i][1]/xx[i][1]);
    h1s1->SetBinContent(i+1,xx[i][0]);
    h1s1->SetBinError(i+1,xe[i][0]);
    h1b1->SetBinContent(i+1,xx[i][1]);
    h1b1->SetBinError(i+1,xe[i][1]);
  }


  //combine bins starting with the highest s/b until the fractional error in
  //the total backround in every bin is smaller than femax
  int ncomb=1;
  //float xtmp;
  float fe=0;
  while (ncomb>0) {
    ncomb=0;
    for (int i=0;i<nbin-1;i++){

      if (xx[i][1]>0){
	fe=xe[i][1]/xx[i][1]; //fractional error in background
      }else{
	fe=1;
      }
      if (fe>femax){

	// GENA: write down bin
	for (std::vector<int>::const_iterator vi=vMap[i+1].begin();
	     vi != vMap[i+1].end(); ++vi){
	  vMap[i].push_back(*vi);
	}
	//move all successive bins up
	vMap.erase(vMap.begin()+i+1);

	for (int k=0;k<nb+2;k++){ //add the next bin
	  xx[i][k]=xx[i][k]+xx[i+1][k];
	  xe[i][k]=sqrt(xe[i][k]*xe[i][k]+xe[i+1][k]*xe[i+1][k]);
	  for (int j=i+1;j<nbin-1;j++){ //move all successive bins up
	    xx[j][k]=xx[j+1][k];
	    xe[j][k]=xe[j+1][k];
	  }
	}
	ncomb++;
	nbin=nbin-1; //decrease the total number of bins

      }
    }
  }


  //GENA: open the map file
  std::ofstream mapFile;
  mapFile.open("bin.map");
  int bin_count = 0;
  for (std::vector<std::vector<int> >::const_iterator i=vMap.begin();
       i != vMap.end(); ++i){

    mapFile << " " << i-vMap.begin()+1 << ":";

    for(std::vector<int>::const_iterator j=i->begin();
	j != i->end(); ++j){
      mapFile << " " << *j;
      ++bin_count;
    }

    mapFile << std::endl;

  }
  //GENA: close the map file
  mapFile.close();

  //these are the output histograms
  TFile *f2 = TFile::Open(oname,"recreate");
  TH1F *h1feb2 = new TH1F("h1fe2","h1fe2",nbin,0,nbin);
  TH1F *h1s2 = new TH1F(sname,sname,nbin,0,nbin);
  TH1F *h1b2 = new TH1F("h1b2","h1b2",nbin,0,nbin);
  TH1F *h1X2[20];
  for (int i=0;i<nb;i++){
    h1X2[i] = new TH1F(bname[i],bname[i],nbin,0,nbin);
  }
  for (int i=0;i<nbin;i++){
    h1feb2->SetBinContent(i+1,xe[i][1]/xx[i][1]);
    h1s2->SetBinContent(i+1,xx[i][0]);
    h1s2->SetBinError(i+1,xe[i][0]);
    h1b2->SetBinContent(i+1,xx[i][1]);
    h1b2->SetBinError(i+1,xe[i][1]);
    for (int j=0;j<nb;j++){
      h1X2[j]->SetBinContent(i+1,xx[i][j+2]);
      h1X2[j]->SetBinError(i+1,xe[i][j+2]);
    }
  }
  
  std::cout << "Merged 1D hist name: " << h1s2->GetName() << std::endl;
  std::cout << "Integral with overflow: " << h1s2->Integral(0,nbin+1) << std::endl;
  std::cout << "Integral no overflow: " << h1s2->Integral(1,nbin) << std::endl << std::endl;
  h1s2->Write();
  for (int j=0;j<nb;j++){
    std::cout << "Merged 1D hist name: " << h1X2[j]->GetName() << std::endl;
    std::cout << "Integral with overflow: " << h1X2[j]->Integral(0,nbin+1) << std::endl;
    std::cout << "Integral no overflow: " << h1X2[j]->Integral(1,nbin) << std::endl << std::endl;
    h1X2[j]->Write();
  }
  
  h1s2->Print("base");

  f2->Close();
  f->Close();

  std::cout << "map size: " << vMap.size() << " combined bins" << std::endl;
  std::cout << "total bins merged: " << bin_count << std::endl;
}
Esempio n. 2
0
void offline(const char* FileName="test")
{
    TH1F::SetDefaultSumw2();
    // Set Style parameters for this macro
    gStyle->SetOptTitle(1); // Show Title (off by default for cleanliness)
    gErrorIgnoreLevel = kError; // Set Verbosity Level (kPrint shows all)

    // Set Output options
    Int_t number;
    Bool_t fPaintAll = checkPaintAllTrigs();
    checkBatchMode();
    Bool_t makePDF = checkMakePDF();
    Bool_t makeROOT= checkMakeRoot();

    // Open ROOT File
    char name[1000];
    sprintf(name,"/Users/zach/Research/rootFiles/run12NPEhPhi/%s.root",FileName);
    TFile *f = new TFile(name,"READ");
    if (f->IsOpen()==kFALSE)
    {   std::cout << "!!! File Not Found !!!" << std::endl;
        exit(1);
    }
    // f->ls(); // - DEBUG by printing all objects in ROOT file

    char fname[100];
    TFile* file;
    if(makeROOT) {
        sprintf(fname,"/Users/zach/Research/rootFiles/run12NPEhPhi/%s_processed.root",FileName);
        file = new TFile(fname,"RECREATE");
        if (file->IsOpen()==kFALSE)
        {
            std::cout << "!!! Outfile Not Opened !!!" << std::endl;
            makeROOT = kFALSE;
        }
    }

    const Int_t numPtBins = anaConst::nPtBins;
    Float_t lowpt[numPtBins],highpt[numPtBins];
    for(Int_t c=0; c< numPtBins; c++) {
        lowpt[c] = anaConst::lpt[c];
        highpt[c] = anaConst::hpt[c];
    }
    Float_t hptCut=anaConst::hptCut;
    const Int_t numTrigs = 4;
    Double_t epsilon[numPtBins] = {0.593164, 0.626663, 0.655916, 0.674654, 0.685596, 0.700600, 0.716682, 0.724638, 0.713977, 0.730550, 0.735204, 0.744336, 0.761323, 0.758423};
    Float_t hptMax=25; // Set max above range to allow overflow
    Float_t lowPhi=anaConst::lowPhi, highPhi=anaConst::highPhi;
    Double_t pu[2][numPtBins][numTrigs]; // To store fit parameters for later use
    Double_t hhNorm, HHScale, hadPur;

    TH1D * LSIM[numPtBins][numTrigs];
    TH1D * USIM[numPtBins][numTrigs];
    TH1D * USIMNP[numPtBins][numTrigs];
    TH1D * LSIMNP[numPtBins][numTrigs];
    TH1D * INCLNP[numPtBins][numTrigs];
    TH1D * INCL[numPtBins][numTrigs];
    TH1D * LSIM2[numPtBins][numTrigs];
    TH1D * USIM2[numPtBins][numTrigs];
    TH1D * INCL2[numPtBins][numTrigs];
    TH1D * LSMM[numPtBins][numTrigs];
    TH1D * USMM[numPtBins][numTrigs];
    TH1D * HHDP[numPtBins][numTrigs];
    TH1D * NSPI[numPtBins][numTrigs];
    TH2F * MON[numTrigs];
    TH1F * AVGTRKS[numTrigs];
    TH2F * MON2[numTrigs];
    TH1F * AVGTRKS2[numTrigs];
    TH2F* mh2PhiQPt[numTrigs];
    TH2F* mh2nSigmaEPt[numTrigs];
    TH2F* mh2nSigmaEPt_eID[numTrigs];
    TH3F* mh3DelPhiIncl[numTrigs];
    TH3F* mh3DelPhiPhotLS[numTrigs];
    TH3F* mh3DelPhiPhotUS[numTrigs];
    TH3F* mh3DelPhiPhotUSNP[numTrigs];
    TH3F* mh3DelPhiPhotLSNP[numTrigs];
    TH3F* mh3DelPhiInclNP[numTrigs];
    TH3F* mh3DelPhiInclWt[numTrigs];
    TH3F* mh3DelPhiPhotLSWt[numTrigs];
    TH3F* mh3DelPhiPhotUSWt[numTrigs];
    TH2F* mh2InvMassPtLS[numTrigs];
    TH2F* mh2InvMassPtUS[numTrigs];
    TH2F* mh2PtEZdcx[numTrigs];
    TH2F* mh2PtEZdcxUS[numTrigs];
    TH2F* mh2PtEZdcxLS[numTrigs];
    TH2F* mh2PtEZdcxHad[numTrigs];
    TH3F* mh3nTracksZdcx[numTrigs];
    TH3F* mh3nTracksZdcxUS[numTrigs];
    TH3F* mh3nTracksZdcxLS[numTrigs];
    TH3F* mh3nTracksZdcxHad[numTrigs];
    TH3F* mh3MixedDelPhi;
    TH3F* mh3MixedDelEta;
    TH3F* mh3MixedEtaPhi;
    TH3F* mh3DelPhiHadHad[numTrigs];
    TH2F* mh2nSigmaPion[numTrigs];
    TH1F* mh1PtHadTracks[numTrigs];
    TH1F* mh1PtETracks[numTrigs];
    TH1D* projHPhi[numPtBins][numTrigs];
    TH1D* projnSigmaE[numPtBins][numTrigs];
    TH1D* projnSigmaE_eID[numPtBins][numTrigs];
    TH1D* projDelPhiIncl[numPtBins][numTrigs];
    TH1D* projDelPhiPhotLS[numPtBins][numTrigs];
    TH1D* projDelPhiPhotUS[numPtBins][numTrigs];
    TH1D* projDelPhiPhotUSNP[numPtBins][numTrigs];
    TH1D* projDelPhiPhotLSNP[numPtBins][numTrigs];
    TH1D* projDelPhiInclNP[numPtBins][numTrigs];
    TH1D* projDelPhiInclWt[numPtBins][numTrigs];
    TH1D* projDelPhiPhotLSWt[numPtBins][numTrigs];
    TH1D* projDelPhiPhotUSWt[numPtBins][numTrigs];
    TH1D* projDelPhiHadHad[numPtBins][numTrigs];
    TH1D* projInvMassLS[numPtBins][numTrigs];
    TH1D* projInvMassUS[numPtBins][numTrigs];
    TH1D* projnSigmaPion[numPtBins][numTrigs];
    TH1D* projEMixedEtaPhi;
    TH1D* projPMixedEtaPhi;
    TH2D* proj2DMixedEtaPhi;
    TH2D* proj2DMixedEvent[numPtBins];
    TH1D* projMixedDelPhi[numPtBins];
    TH1D* projMixedDelEta[numPtBins];
    TH2F* histoNorms;
    TH1D* projZDCxHad[numPtBins][numTrigs];
    TH1D* projZDCxTrig[numPtBins][numTrigs];
    TH1D* projZDCxHadUS[numPtBins][numTrigs];
    TH1D* projZDCxTrigUS[numPtBins][numTrigs];
    TH1D* projZDCxHadLS[numPtBins][numTrigs];
    TH1D* projZDCxTrigLS[numPtBins][numTrigs];
    TH1D* projZDCxHadHad[numPtBins][numTrigs];
    TH1D* projZDCxTrigHad[numPtBins][numTrigs];
    TProfile2D* profileZDCx[numTrigs];
    TCanvas * c[numTrigs];
    TCanvas * c2[numTrigs];
    TCanvas * IN[numTrigs];
    TCanvas * IN2[numTrigs];
    TCanvas * pile[numTrigs];
    TCanvas * pileHad[numTrigs];
    TCanvas * result[numTrigs];
    TCanvas * result2[numTrigs];
    TCanvas * inMass[numTrigs];
    TCanvas * USComp[numTrigs];
    TCanvas * LSComp[numTrigs];
    TCanvas * InclComp[numTrigs];
    TCanvas * cHH[numTrigs];
    TCanvas * nSigPi[numTrigs];
    TCanvas * allDist[numTrigs];
    TCanvas * mixedC;
    TCanvas * mixedCbinEta;
    TCanvas * mixedCbinPhi;
    TCanvas * mixedCbin;
    TCanvas * singlePlot;

    TPaveText* lbl[numPtBins];
    TPaveText* stat[numPtBins];
    char textLabel[100];
    singlePlot =  new TCanvas("singlePlot","Single Plot",150,0,1150,1000);

    // Trigger Independent Hists
    mixedC     = new TCanvas("mixedC","Mixed Events",150,0,1150,1000);
    mixedCbinEta = new TCanvas("mixedCbinEta","Mixed Events Eta",150,0,1150,1000);
    mixedCbinPhi = new TCanvas("mixedCbinPhi","Mixed Events Phi",150,0,1150,1000);
    mixedCbin = new TCanvas("mixedCbin","Mixed Events 2D",150,0,1150,1000);

    mixedC       -> Divide(2,2);
    mixedCbinEta -> Divide(4,3);
    mixedCbinPhi -> Divide(4,3);

    mh3MixedDelPhi = (TH3F*)f->Get("mh3MixedDelPhi");
    mh3MixedDelEta = (TH3F*)f->Get("mh3MixedDelEta");
    mh3MixedEtaPhi = (TH3F*)f->Get("mh3MixedEtaPhi");

    ///////////////////////////
    projPMixedEtaPhi  = mh3MixedEtaPhi -> ProjectionX("projPMixedEtaPhi");
    projEMixedEtaPhi  = mh3MixedEtaPhi -> ProjectionY("projEMixedEtaPhi");
    proj2DMixedEtaPhi = (TH2D*)mh3MixedEtaPhi -> Project3D("yx");
    Int_t RB2 = 2;
    projEMixedEtaPhi->Rebin(RB2);
    projPMixedEtaPhi->Rebin(RB2);

    mixedC->cd(1);
    mh3MixedEtaPhi->GetXaxis()->SetTitle("#Delta#phi");
    mh3MixedEtaPhi->GetXaxis()->SetRangeUser(lowPhi,highPhi);
    mh3MixedEtaPhi->GetYaxis()->SetTitle("#Delta#eta");
    mh3MixedEtaPhi->GetYaxis()->SetRangeUser(-1.5,1.5);
    mh3MixedEtaPhi->GetZaxis()->SetTitle("P_{t,e}");
    mh3MixedEtaPhi->Draw();
    mixedC->cd(2);
    projPMixedEtaPhi->GetXaxis()->SetRangeUser(lowPhi,highPhi);
    projPMixedEtaPhi->GetXaxis()->SetTitle("#Delta#phi");
    projPMixedEtaPhi->GetYaxis()->SetRangeUser(0,20000);
    projPMixedEtaPhi->SetTitle("Mixed Event #Delta#phi");
    projPMixedEtaPhi->Draw();
    mixedC->cd(3);
    projEMixedEtaPhi->GetXaxis()->SetRangeUser(-2.5,2.5);
    projEMixedEtaPhi->GetXaxis()->SetTitle("#Delta#eta");
    projEMixedEtaPhi->SetTitle("Mixed Event #Delta#eta");
    projEMixedEtaPhi->Draw();
    mixedC->cd(4);
    mixedC->SetLogz(1);
    proj2DMixedEtaPhi->GetXaxis()->SetTitle("#Delta#phi");
    proj2DMixedEtaPhi->GetXaxis()->SetRangeUser(lowPhi,highPhi);
    proj2DMixedEtaPhi->GetYaxis()->SetTitle("#Delta#eta");
    proj2DMixedEtaPhi->GetYaxis()->SetRangeUser(-1.5,1.5);
    proj2DMixedEtaPhi->Draw("colz");

    TH3F* temp3D[numPtBins];
    // PtBins for Mixed Event
    for(Int_t ptbin = 0; ptbin < numPtBins; ptbin++) {

        // Init necessary plotting tools
        lbl[ptbin] = new TPaveText(.2,.8,.5,.85,Form("NB NDC%i",ptbin));
        sprintf(textLabel,"%.1f < P_{T,e} < %.1f",lowpt[ptbin],highpt[ptbin]);
        lbl[ptbin]->AddText(textLabel);
        lbl[ptbin]->SetFillColor(kWhite);

        projMixedDelPhi[ptbin] = mh3MixedEtaPhi->ProjectionX(Form("projMixedDelPhi_%i",ptbin),0,-1,mh3MixedEtaPhi->GetZaxis()->FindBin(lowpt[ptbin]),mh3MixedEtaPhi->GetZaxis()->FindBin(highpt[ptbin])-1);
        projMixedDelEta[ptbin] = mh3MixedEtaPhi->ProjectionY(Form("projMixedDelEta_%i",ptbin),0,-1,mh3MixedEtaPhi->GetZaxis()->FindBin(lowpt[ptbin]),mh3MixedEtaPhi->GetZaxis()->FindBin(highpt[ptbin])-1);

        mixedCbinEta->cd(ptbin+1);
        projMixedDelEta[ptbin]->GetXaxis()->SetRangeUser(-2.5,2.5);
        projMixedDelEta[ptbin]->GetXaxis()->SetTitle("#Delta#eta");
        projMixedDelEta[ptbin]->Draw();

        mixedCbinPhi->cd(ptbin+1);
        projMixedDelPhi[ptbin]->GetXaxis()->SetRangeUser(lowPhi-.5,highPhi+.5);
        // projMixedDelPhi[ptbin]->GetYaxis()->SetRangeUser(0,2000);
        projMixedDelPhi[ptbin]->GetXaxis()->SetTitle("#Delta#phi");
        projMixedDelPhi[ptbin]->Draw();

        /*   temp3D[ptbin] = (TH3F*)mh3MixedEtaPhi->Clone(); // make a clone to set axis range on for 3D to 2D projection
        temp3D[ptbin]->GetZaxis()->SetRangeUser(lowpt[ptbin],highpt[ptbin]); // project3d only projects active range
        proj2DMixedEvent[ptbin] = (TH2D*)temp3D[ptbin] -> Project3D("yx");
        proj2DMixedEvent[ptbin]->SetName(Form("proj2DMixedEvent_%i",ptbin));

        mixedCbin->cd(ptbin+1);
        proj2DMixedEvent[ptbin]->GetXaxis()->SetTitle("#Delta#phi");
        proj2DMixedEvent[ptbin]->GetXaxis()->SetRangeUser(lowPhi,highPhi);
        proj2DMixedEvent[ptbin]->GetYaxis()->SetTitle("#Delta#eta");
        proj2DMixedEvent[ptbin]->GetYaxis()->SetRangeUser(-1.5,1.5);
        proj2DMixedEvent[ptbin]->Draw("colz");*/

    }

    /// TRIGGER LOOP
    histoNorms = new TH2F("histoNorms","",4,0,12,20,0,20); // Fill normalization in a single histogram for accessing later

    for(Int_t trig = 0; trig < numTrigs; trig++) {

        if(!fPaintAll && (trig == 1 || trig == 3)) continue;
        // Create and Segment Canvas
        c[trig]        = new TCanvas(Form("c%i",trig),"Photonic Hists",150,0,1150,1000);
        IN[trig]       = new TCanvas(Form("IN%i",trig),"Inclusive Hists",150,0,1150,1000);
        pile[trig]     = new TCanvas(Form("pile%i",trig),"Pileup Monitor",150,0,1150,1000);
        pileHad[trig]  = new TCanvas(Form("pileHad%i",trig),"Pileup Monitor",150,0,1150,1000);
        //  pileTrig[trig] = new TCanvas(Form("pileTrig%i",trig),"Pileup Monitor",150,0,1150,1000);
        inMass[trig]   = new TCanvas(Form("inMass%i",trig),"Invariant Mass",150,0,1150,1000);
        result[trig]   = new TCanvas(Form("result%i",trig),"Inclusive - Photonic",150,0,1150,1000);
        USComp[trig]   = new TCanvas(Form("USComp%i",trig),"Unlike Sign Distributions",150,0,1150,1000);
        LSComp[trig]   = new TCanvas(Form("LSComp%i",trig),"Like Sign Distributions",150,0,1150,1000);
        InclComp[trig] = new TCanvas(Form("InclComp%i",trig),"Inclusive Distributions",150,0,1150,1000);
        cHH[trig]      = new TCanvas(Form("cHH%i",trig),"Hadron-Hadron Distributions",150,0,1150,1000);
        nSigPi[trig]   = new TCanvas(Form("nSigPi_%i",trig),"n#sigma#pi QA",150,0,1150,1000);
        allDist[trig]  = new TCanvas(Form("allDist_%i",trig),"Distribution Comparison",150,0,1150,1000);
        c[trig]        -> Divide(4,3);
        inMass[trig]   -> Divide(4,3);
        IN[trig]       -> Divide(4,3);
        pile[trig]     -> Divide(4,3);
        result[trig]   -> Divide(4,3);
        USComp[trig]   -> Divide(4,3);
        LSComp[trig]   -> Divide(4,3);
        InclComp[trig] -> Divide(4,3);
        cHH[trig]      -> Divide(4,3);
        nSigPi[trig]   -> Divide(4,3);
        allDist[trig]  -> Divide(4,3);

        // Make Projections (first get 2d/3d hists, then project)
        mh2PhiQPt[trig]         = (TH2F*)f->Get(Form("mh2PhiQPt_%i",trig));
        mh2nSigmaEPt[trig]      = (TH2F*)f->Get(Form("mh2nSigmaEPt_%i",trig));
        mh2nSigmaEPt_eID[trig]  = (TH2F*)f->Get(Form("mh2nSigmaEPt_eID_%i",trig));
        mh3DelPhiIncl[trig]     = (TH3F*)f->Get(Form("mh3DelPhiIncl_%i",trig));
        mh3DelPhiPhotLS[trig]   = (TH3F*)f->Get(Form("mh3DelPhiPhotLS_%i",trig));
        mh3DelPhiPhotUS[trig]   = (TH3F*)f->Get(Form("mh3DelPhiPhotUS_%i",trig));
        mh3DelPhiPhotUSNP[trig] = (TH3F*)f->Get(Form("mh3DelPhiPhotUSNP_%i",trig));
        mh3DelPhiPhotLSNP[trig] = (TH3F*)f->Get(Form("mh3DelPhiPhotLSNP_%i",trig));
        mh3DelPhiInclNP[trig]   = (TH3F*)f->Get(Form("mh3DelPhiPhotInclNP_%i",trig));
        mh3DelPhiInclWt[trig]   = (TH3F*)f->Get(Form("mh3DelPhiInclWt_%i",trig));
        mh3DelPhiPhotLSWt[trig] = (TH3F*)f->Get(Form("mh3DelPhiPhotLSWt_%i",trig));
        mh3DelPhiPhotUSWt[trig] = (TH3F*)f->Get(Form("mh3DelPhiPhotUSWt_%i",trig));
        mh2InvMassPtLS[trig]    = (TH2F*)f->Get(Form("mh2InvMassPtLS_%i",trig));
        mh2InvMassPtUS[trig]    = (TH2F*)f->Get(Form("mh2InvMassPtUS_%i",trig));
        mh3DelPhiHadHad[trig]   = (TH3F*)f->Get(Form("mh3DelPhiHadHad_%i",trig));
        mh1PtHadTracks[trig]    = (TH1F*)f->Get(Form("mh1PtHadTracks_%i",trig));
        mh1PtETracks[trig]      = (TH1F*)f->Get(Form("mh1PtETracks_%i",trig));
        mh2nSigmaPion[trig]     = (TH2F*)f->Get(Form("mh2nSigmaPionPt_%i",trig));

        for(Int_t ptbin=0; ptbin<numPtBins; ptbin++)
        {
            // - Make projections into electron ptbins
            projHPhi[ptbin][trig] = mh2PhiQPt[trig]->ProjectionX(Form("projHPhi_%i_%i",ptbin,trig),mh2PhiQPt[trig]->GetYaxis()->FindBin(lowpt[ptbin]),mh2PhiQPt[trig]->GetYaxis()->FindBin(highpt[ptbin])-1);

            projnSigmaE[ptbin][trig] = mh2nSigmaEPt[trig]->ProjectionX(Form("projnSigmaE_%i_%i",ptbin,trig),mh2nSigmaEPt[trig]->GetYaxis()->FindBin(lowpt[ptbin]),mh2nSigmaEPt[trig]->GetYaxis()->FindBin(highpt[ptbin])-1);

            projnSigmaE_eID[ptbin][trig] = mh2nSigmaEPt_eID[trig]->ProjectionX(Form("projnSigmaE_eID_%i_%i",ptbin,trig),mh2nSigmaEPt_eID[trig]->GetYaxis()->FindBin(lowpt[ptbin]),mh2nSigmaEPt_eID[trig]->GetYaxis()->FindBin(highpt[ptbin])-1);

            projDelPhiIncl[ptbin][trig] = mh3DelPhiIncl[trig]->ProjectionX(Form("projDelPhiIncl_%i_%i",ptbin,trig),mh3DelPhiIncl[trig]->GetYaxis()->FindBin(lowpt[ptbin]),mh3DelPhiIncl[trig]->GetYaxis()->FindBin(highpt[ptbin])-1,mh3DelPhiIncl[trig]->GetZaxis()->FindBin(hptCut),mh3DelPhiIncl[trig]->GetZaxis()->FindBin(hptMax));

            projDelPhiPhotUS[ptbin][trig] = mh3DelPhiPhotUS[trig]->ProjectionX(Form("projDelPhiPhotUS_%i_%i",ptbin,trig),mh3DelPhiPhotUS[trig]->GetYaxis()->FindBin(lowpt[ptbin]),mh3DelPhiPhotUS[trig]->GetYaxis()->FindBin(highpt[ptbin])-1,mh3DelPhiPhotUS[trig]->GetZaxis()->FindBin(hptCut),mh3DelPhiInclNP[trig]->GetZaxis()->FindBin(hptMax));

            projDelPhiPhotUSNP[ptbin][trig] = mh3DelPhiPhotUSNP[trig]->ProjectionX(Form("projDelPhiPhotUSNP_%i_%i",ptbin,trig),mh3DelPhiPhotUSNP[trig]->GetYaxis()->FindBin(lowpt[ptbin]),mh3DelPhiPhotUSNP[trig]->GetYaxis()->FindBin(highpt[ptbin])-1,mh3DelPhiPhotUSNP[trig]->GetZaxis()->FindBin(hptCut),mh3DelPhiInclNP[trig]->GetZaxis()->FindBin(hptMax));

            projDelPhiPhotLS[ptbin][trig] = mh3DelPhiPhotLS[trig]->ProjectionX(Form("projDelPhiPhotLS_%i_%i",ptbin,trig),mh3DelPhiPhotLS[trig]->GetYaxis()->FindBin(lowpt[ptbin]),mh3DelPhiPhotLS[trig]->GetYaxis()->FindBin(highpt[ptbin])-1,mh3DelPhiPhotLS[trig]->GetZaxis()->FindBin(hptCut),mh3DelPhiInclNP[trig]->GetZaxis()->FindBin(hptMax));

            projDelPhiPhotLSNP[ptbin][trig] = mh3DelPhiPhotLSNP[trig]->ProjectionX(Form("projDelPhiPhotLSNP_%i_%i",ptbin,trig),mh3DelPhiPhotLSNP[trig]->GetYaxis()->FindBin(lowpt[ptbin]),mh3DelPhiPhotLSNP[trig]->GetYaxis()->FindBin(highpt[ptbin])-1,mh3DelPhiPhotLSNP[trig]->GetZaxis()->FindBin(hptCut),mh3DelPhiInclNP[trig]->GetZaxis()->FindBin(hptMax));

            projDelPhiInclNP[ptbin][trig] = mh3DelPhiInclNP[trig]->ProjectionX(Form("projDelPhiInclNP_%i_%i",ptbin,trig),mh3DelPhiInclNP[trig]->GetYaxis()->FindBin(lowpt[ptbin]),mh3DelPhiInclNP[trig]->GetYaxis()->FindBin(highpt[ptbin])-1,mh3DelPhiInclNP[trig]->GetZaxis()->FindBin(hptCut),mh3DelPhiInclNP[trig]->GetZaxis()->FindBin(hptMax));

            projDelPhiPhotLS[ptbin][trig] = mh3DelPhiPhotLS[trig]->ProjectionX(Form("projDelPhiPhotLS_%i_%i",ptbin,trig),mh3DelPhiPhotLS[trig]->GetYaxis()->FindBin(lowpt[ptbin]),mh3DelPhiPhotLS[trig]->GetYaxis()->FindBin(highpt[ptbin])-1,mh3DelPhiPhotLS[trig]->GetZaxis()->FindBin(hptCut),mh3DelPhiInclNP[trig]->GetZaxis()->FindBin(hptMax));

            projDelPhiPhotLS[ptbin][trig] = mh3DelPhiPhotLS[trig]->ProjectionX(Form("projDelPhiPhotLS_%i_%i",ptbin,trig),mh3DelPhiPhotLS[trig]->GetYaxis()->FindBin(lowpt[ptbin]),mh3DelPhiPhotLS[trig]->GetYaxis()->FindBin(highpt[ptbin])-1,mh3DelPhiPhotLS[trig]->GetZaxis()->FindBin(hptCut),mh3DelPhiInclNP[trig]->GetZaxis()->FindBin(hptMax));

            projDelPhiInclWt[ptbin][trig] = mh3DelPhiInclWt[trig]->ProjectionX(Form("projDelPhiInclWt_%i_%i",ptbin,trig),mh3DelPhiInclWt[trig]->GetYaxis()->FindBin(lowpt[ptbin]),mh3DelPhiInclWt[trig]->GetYaxis()->FindBin(highpt[ptbin])-1,mh3DelPhiInclWt[trig]->GetZaxis()->FindBin(hptCut),mh3DelPhiInclNP[trig]->GetZaxis()->FindBin(hptMax));

            projDelPhiPhotUSWt[ptbin][trig] = mh3DelPhiPhotUSWt[trig]->ProjectionX(Form("projDelPhiPhotUSWt_%i_%i",ptbin,trig),mh3DelPhiPhotUSWt[trig]->GetYaxis()->FindBin(lowpt[ptbin]),mh3DelPhiPhotUSWt[trig]->GetYaxis()->FindBin(highpt[ptbin])-1,mh3DelPhiPhotUSWt[trig]->GetZaxis()->FindBin(hptCut),mh3DelPhiInclNP[trig]->GetZaxis()->FindBin(hptMax));

            projDelPhiPhotLSWt[ptbin][trig] = mh3DelPhiPhotLSWt[trig]->ProjectionX(Form("projDelPhiPhotLSWt_%i_%i",ptbin,trig),mh3DelPhiPhotLSWt[trig]->GetYaxis()->FindBin(lowpt[ptbin]),mh3DelPhiPhotLSWt[trig]->GetYaxis()->FindBin(highpt[ptbin])-1,mh3DelPhiPhotLSWt[trig]->GetZaxis()->FindBin(hptCut),mh3DelPhiInclNP[trig]->GetZaxis()->FindBin(hptMax));

            projInvMassUS[ptbin][trig] = mh2InvMassPtUS[trig]->ProjectionX(Form("projInvMassUS_%i_%i",ptbin,trig),mh2InvMassPtUS[trig]->GetYaxis()->FindBin(lowpt[ptbin]),mh2InvMassPtUS[trig]->GetYaxis()->FindBin(highpt[ptbin])-1);

            projInvMassLS[ptbin][trig] = mh2InvMassPtLS[trig]->ProjectionX(Form("projInvMassLS_%i_%i",ptbin,trig),mh2InvMassPtLS[trig]->GetYaxis()->FindBin(lowpt[ptbin]),mh2InvMassPtLS[trig]->GetYaxis()->FindBin(highpt[ptbin])-1);

            projDelPhiHadHad[ptbin][trig] = mh3DelPhiHadHad[trig]->ProjectionX(Form("projDelPhiHadHad_%i_%i",ptbin,trig),mh3DelPhiHadHad[trig]->GetYaxis()->FindBin(lowpt[ptbin]),mh3DelPhiHadHad[trig]->GetYaxis()->FindBin(highpt[ptbin])-1,mh3DelPhiHadHad[trig]->GetZaxis()->FindBin(hptCut),mh3DelPhiInclNP[trig]->GetZaxis()->FindBin(hptMax));

            projnSigmaPion[ptbin][trig] = mh2nSigmaPion[trig]->ProjectionX(Form("projnSigmaPion_%i_%i",ptbin,trig),mh2nSigmaPion[trig]->GetYaxis()->FindBin(lowpt[ptbin]),mh2nSigmaPion[trig]->GetYaxis()->FindBin(highpt[ptbin])-1);
        }

        for(Int_t ptbin = 0; ptbin < numPtBins; ptbin++) {

            // Init necessary plotting tools
            lbl[ptbin] = new TPaveText(.15,.15,.35,.23,Form("NB NDC%i",ptbin));
            sprintf(textLabel,"%.1f < P_{T,e} < %.1f",lowpt[ptbin],highpt[ptbin]);
            lbl[ptbin]->AddText(textLabel);
            lbl[ptbin]->SetFillColor(kWhite);

            // Calculate electron purity from pol3 fit of xiaozhi data
            Float_t ptAv = (lowpt[ptbin]+highpt[ptbin])/2.;
            Float_t p[3] = {0.9743, 0.02128, -0.00438};
            Float_t purity = p[0] + (p[1]*ptAv)+(p[2]*ptAv*ptAv);
            hadPur = 1-purity;

            // Calculate PHe Reconstruction Eff from Xiaozhi embedding (fit)
            Float_t par[5] = {.26214, 4.75137, .526075, .0276979, .00054599};
            Float_t x = ptAv;
            Float_t eps = par[0]*TMath::Log(par[1]*x - par[2]*x*x + par[3]*x*x*x - par[4]*x*x*x*x);
            epsilon[ptbin] = eps;

            // Make stats label with purity and effeciency
            char statLabel[100];
            stat[ptbin] = new TPaveText(.4,.3,.85,.35,Form("NB NDC%i",ptbin));
            sprintf(statLabel,"Eff: %.2f; ePure:%.2f",epsilon[ptbin],purity);
            stat[ptbin]->InsertText(statLabel);
            stat[ptbin]->SetFillColor(kWhite);

            // Calculate Normalization for NPE delPhi
            Int_t inclNorm = mh1PtETracks[trig]->Integral(mh1PtETracks[trig]->GetXaxis()->FindBin(lowpt[ptbin]),mh1PtETracks[trig]->GetXaxis()->FindBin(highpt[ptbin])-1);
            Int_t LSNorm   = projInvMassLS[ptbin][trig]->Integral();
            Int_t USNorm   = projInvMassUS[ptbin][trig]->Integral();
            hhNorm   = mh1PtHadTracks[trig]->Integral(mh1PtHadTracks[trig]->GetXaxis()->FindBin(lowpt[ptbin]),mh1PtHadTracks[trig]->GetXaxis()->FindBin(highpt[ptbin])-1);
            HHScale = (Float_t)inclNorm/(Float_t)hhNorm; // so the purity comparison is 1:1
            Float_t Norm = (Float_t)inclNorm - (1/epsilon[ptbin] - 1.)*(Float_t)USNorm + (1/epsilon[ptbin])*(Float_t)LSNorm - HHScale*hadPur*hhNorm; // Use the number of "signal" counts
            histoNorms->SetBinContent(histoNorms->GetBin(trig+1,ptbin+1), Norm); // Find the bin and fill with the Normalization
            //cout << trig << "; " << ptbin << ": " << Norm << endl;

            Int_t counter = numPtBins*trig+ptbin;
            // DEBUG cout << counter << endl;
            c[trig]->cd(ptbin+1);
            // Assign to a single, simpler name for manip
            LSIM[ptbin][trig]  = projDelPhiPhotLS[ptbin][trig];
            USIM[ptbin][trig]  = projDelPhiPhotUS[ptbin][trig];
            USIMNP[ptbin][trig]= projDelPhiPhotUSNP[ptbin][trig];
            LSIMNP[ptbin][trig]= projDelPhiPhotLSNP[ptbin][trig];
            INCLNP[ptbin][trig]= projDelPhiInclNP[ptbin][trig];
            INCL[ptbin][trig]  = projDelPhiIncl[ptbin][trig];
            INCL2[ptbin][trig] = projDelPhiInclWt[ptbin][trig];
            LSIM2[ptbin][trig] = projDelPhiPhotLSWt[ptbin][trig];
            USIM2[ptbin][trig] = projDelPhiPhotUSWt[ptbin][trig];
            LSMM[ptbin][trig]  = projInvMassLS[ptbin][trig];
            USMM[ptbin][trig]  = projInvMassUS[ptbin][trig];
            HHDP[ptbin][trig]  = projDelPhiHadHad[ptbin][trig];
            NSPI[ptbin][trig]  = projnSigmaPion[ptbin][trig];
            // Rebin all as necessary
            Int_t RB = 1;
            LSIM[ptbin][trig]  -> Rebin(RB);
            USIM[ptbin][trig]  -> Rebin(RB);
            USIMNP[ptbin][trig]-> Rebin(RB);
            LSIMNP[ptbin][trig]-> Rebin(RB);
            INCLNP[ptbin][trig]-> Rebin(RB);
            INCL[ptbin][trig]  -> Rebin(RB);
            INCL2[ptbin][trig] -> Rebin(RB);
            LSIM2[ptbin][trig] -> Rebin(RB);
            USIM2[ptbin][trig] -> Rebin(RB);
            HHDP[ptbin][trig]  -> Rebin(RB);
            NSPI[ptbin][trig]  -> Rebin(10);

            // Actually manipulate histos and plot (photnic del Phi)

            USIMNP[ptbin][trig]->SetLineColor(kRed);
            USIMNP[ptbin][trig]->SetLineWidth(1);
            USIMNP[ptbin][trig]->GetXaxis()->SetTitle("#Delta#phi_{eh}");
            USIMNP[ptbin][trig]->GetXaxis()->SetRangeUser(lowPhi,highPhi);
            if(ptbin == 0)
                USIMNP[ptbin][trig]->SetTitle("Photonic Electron Reconstruction (No Partner Track)");
            else if (ptbin == 1 && trig !=3)
                USIMNP[ptbin][trig]->SetTitle(Form("HT%i",trig));
            else if (trig == 3 && ptbin == 1)
                USIMNP[ptbin][trig]->SetTitle("MB");
            else
                USIMNP[ptbin][trig]->SetTitle("");
            USIMNP[ptbin][trig]->Draw("");

            LSIMNP[ptbin][trig]->SetLineColor(kBlack);
            LSIMNP[ptbin][trig]->SetLineWidth(1);
            LSIMNP[ptbin][trig]->Draw(" same");
            lbl[ptbin]->Draw("same");

            // Subtraction of (USNP-LS)
            TH1F *SUB = (TH1F*)USIMNP[ptbin][trig]->Clone(); //
            SUB->SetName("Subtraction");      // Create SUB as a clone of USIMNP
            SUB->Add(LSIMNP[ptbin][trig],-1);
            SUB->SetLineColor(kBlue);
            SUB->SetLineWidth(1);
            SUB->SetFillStyle(3001);
            SUB->SetFillColor(kBlue);
            SUB->Draw("same");
            lbl[ptbin]->Draw("same");
            TLegend* leg = new TLegend(0.2,0.73,0.55,0.85);
            leg->AddEntry(USIMNP[ptbin][trig],"Unlike Sign","lpe");
            leg->AddEntry(LSIM[ptbin][trig],"Like Sign", "lpe");
            leg->AddEntry(SUB,"Unlike - Like", "lpe");
            leg->Draw();

            // Plot different US (w/wo partner)
            USComp[trig]->cd(ptbin+1);
            TH1F *USwP = (TH1F*)USIM[ptbin][trig]->Clone();
            USwP->SetLineColor(kRed); //with partner tracks
            USwP->GetXaxis()->SetTitle("#Delta#phi_{eh}");
            USwP->GetXaxis()->SetRangeUser(lowPhi,highPhi);
            if(ptbin == 0)
                USwP->SetTitle("Photonic Unlike Sign Distributions");
            else if (ptbin == 1 && trig !=3)
                USwP->SetTitle(Form("HT%i",trig));
            else if (trig == 3 && ptbin == 1)
                USwP->SetTitle("MB");
            else
                USwP->SetTitle("");
            USwP->Draw("");
            TH1F *USnP = (TH1F*)USIMNP[ptbin][trig]->Clone();
            USnP->SetLineColor(kBlack);
            USnP->Draw("same");
            lbl[ptbin]->Draw("same");
            TLegend* legUS = new TLegend(0.35,0.8,0.77,0.87);
            legUS->AddEntry(USwP,"With Partner Track","lpe");
            legUS->AddEntry(USnP,"Partner Track Removed", "lpe");
            legUS->Draw();

            // Plot different LS (w/wo partner)
            LSComp[trig]->cd(ptbin+1);
            TH1F *LSwP = (TH1F*)LSIM[ptbin][trig]->Clone();
            LSwP->SetLineColor(kRed); //with partner tracks
            LSwP->GetXaxis()->SetTitle("#Delta#phi_{eh}");
            LSwP->GetXaxis()->SetRangeUser(lowPhi,highPhi);
            if(ptbin == 0)
                LSwP->SetTitle("Photonic Like Sign Distributions");
            else if (ptbin == 1 && trig !=3)
                LSwP->SetTitle(Form("HT%i",trig));
            else if (trig == 3 && ptbin == 1)
                LSwP->SetTitle("MB");
            else
                LSwP->SetTitle("");
            LSwP->Draw("");
            TH1F *LSnP = (TH1F*)LSIMNP[ptbin][trig]->Clone();
            LSnP->SetLineColor(kBlack);
            LSnP->Draw("same");
            lbl[ptbin]->Draw("same");
            TLegend* legLS = new TLegend(0.35,0.8,0.77,0.87);
            legLS->AddEntry(LSwP,"With Partner Track","lpe");
            legLS->AddEntry(LSnP,"Partner Track Removed", "lpe");
            legLS->Draw();

            // Plot different Incl (w/wo partner)
            InclComp[trig]->cd(ptbin+1);
            TH1F *InclwP = (TH1F*)INCL[ptbin][trig]->Clone();
            InclwP->SetLineColor(kRed); //with partner tracks
            InclwP->GetXaxis()->SetTitle("#Delta#phi_{eh}");
            InclwP->GetXaxis()->SetRangeUser(lowPhi,highPhi);
            if(ptbin == 0)
                InclwP->SetTitle("Inclusive Distributions");
            else if (ptbin == 1 && trig !=3)
                InclwP->SetTitle(Form("HT%i",trig));
            else if (trig == 3 && ptbin == 1)
                InclwP->SetTitle("MB");
            else
                InclwP->SetTitle("");
            InclwP->Draw("");
            TH1F *InclnP = (TH1F*)INCLNP[ptbin][trig]->Clone();
            InclnP->SetLineColor(kBlack);
            InclnP->Draw("same");
            lbl[ptbin]->Draw("same");
            TLegend* legIncl = new TLegend(0.35,0.8,0.77,0.87);
            legIncl->AddEntry(InclwP,"Inclusive","lpe");
            legIncl->AddEntry(InclnP,"Semi-Inclusive", "lpe");
            legIncl->Draw();

            // Actually manipulate histos and plot (photonic InvMass)
            inMass[trig]->cd(ptbin+1);
            USMM[ptbin][trig]->SetLineColor(kRed);
            USMM[ptbin][trig]->SetLineWidth(1);
            USMM[ptbin][trig]->GetXaxis()->SetTitle("InvMass (GeV/c^{2})");
            USMM[ptbin][trig]->GetXaxis()->SetRangeUser(0,0.4);
            if(ptbin == 0)
                USMM[ptbin][trig]->SetTitle("Photonic Electron Reconstruction");
            else if (ptbin == 1 && trig !=3)
                USMM[ptbin][trig]->SetTitle(Form("HT%i",trig));
            else if (trig == 3 && ptbin == 1)
                USMM[ptbin][trig]->SetTitle("MB");
            else
                USMM[ptbin][trig]->SetTitle("");
            USMM[ptbin][trig]->Draw("");

            LSMM[ptbin][trig]->SetLineColor(kBlack);
            LSMM[ptbin][trig]->SetLineWidth(1);
            LSMM[ptbin][trig]->Draw("same");
            lbl[ptbin]->Draw("same");

            // Subtraction of (US-LS)
            TH1F *SUB4 = (TH1F*)USMM[ptbin][trig]->Clone(); //
            SUB4->SetName("Subtraction");      // Create SUB as a clone of USIM
            SUB4->Add(LSMM[ptbin][trig],-1);
            SUB4->SetLineColor(kBlue);
            SUB4->SetLineWidth(1);
            SUB4->SetFillStyle(3001);
            SUB4->SetFillColor(kBlue);
            SUB4->Draw("same");
            TLegend* leg2 = new TLegend(0.45,0.6,0.85,0.75);
            leg2->AddEntry(USMM[ptbin][trig],"Unlike Sign","lpe");
            leg2->AddEntry(LSMM[ptbin][trig],"Like Sign", "lpe");
            leg2->AddEntry(SUB4,"Unlike - Like", "lpe");
            leg2->Draw();

            // Handle Inclusive Hists
            IN[trig]->cd(ptbin+1);
            INCL[ptbin][trig]->SetLineColor(kBlue);
            INCL[ptbin][trig]->SetLineWidth(1);
            INCL[ptbin][trig]->GetXaxis()->SetTitle("#Delta#phi_{eh}");
            INCL[ptbin][trig]->GetXaxis()->SetRangeUser(lowPhi,highPhi);
            if(ptbin == 0)
                INCL[ptbin][trig]->SetTitle("Inclusive Electrons");
            else if (ptbin == 1 && trig !=3)
                INCL[ptbin][trig]->SetTitle(Form("HT%i",trig));
            else if (trig == 3 && ptbin == 1)
                INCL[ptbin][trig]->SetTitle("MB");
            else
                INCL[ptbin][trig]->SetTitle("");
            INCL[ptbin][trig]->Draw("");
            lbl[ptbin]->Draw("same");

            IN[trig]->Update();

            // Plot Had-Had correlations
            cHH[trig]->cd(ptbin+1);
            HHDP[ptbin][trig]->SetLineColor(kGreen+3);
            HHDP[ptbin][trig]->SetLineWidth(1);
            HHDP[ptbin][trig]->GetXaxis()->SetTitle("#Delta#phi_{eh}");
            HHDP[ptbin][trig]->GetXaxis()->SetRangeUser(lowPhi,highPhi);
            if(ptbin == 0)
                HHDP[ptbin][trig]->SetTitle("Hadron-Hadron Correlations");
            else if (ptbin == 1 && trig !=3)
                HHDP[ptbin][trig]->SetTitle(Form("HT%i",trig));
            else if (trig == 3 && ptbin == 1)
                HHDP[ptbin][trig]->SetTitle("MB");
            else
                HHDP[ptbin][trig]->SetTitle("");
            HHDP[ptbin][trig]->Draw("");
            lbl[ptbin]->Draw("same");


            // Subtraction of Inclusive - (1/e - 1)US + (1/e)LS - (1-purity)HadHad
            result[trig]->cd(ptbin+1);
            TH1F *INCDP = (TH1F*)INCLNP[ptbin][trig]->Clone();
            TH1F *ULDP  = (TH1F*)USIMNP[ptbin][trig]->Clone();
            TH1F *LSDP  = (TH1F*)LSIMNP[ptbin][trig]->Clone();
            TH1F *HADDP = (TH1F*)HHDP[ptbin][trig]->Clone();
            INCDP->SetName(Form("scaleNPEhDelPhi_%i_%i",trig,ptbin));
            ULDP->Scale(1./epsilon[ptbin] - 1.); // Scale each distribution by associated factors
            LSDP->Scale(1./epsilon[ptbin]);
            HADDP->Scale(HHScale*hadPur);
            INCDP->Add(ULDP,-1);
            INCDP->Add(LSDP,1);
            INCDP->Add(HADDP,-1);
            TH1F *unscaleINCDP = (TH1F*)INCDP->Clone();   //
            unscaleINCDP->SetName(Form("NPEhDelPhi_%i_%i",trig,ptbin)); // Make a clone before normalization, to pass to fit program
            INCDP->Scale(1./((Double_t)Norm));//*INCDP->GetBinWidth(1)));
            INCDP->SetLineColor(kBlack);
            INCDP->SetLineWidth(1);
            INCDP->SetFillStyle(3001);
            INCDP->SetFillColor(kYellow);
            INCDP->GetXaxis()->SetRangeUser(lowPhi,highPhi);
            INCDP->GetXaxis()->SetTitle("#Delta#phi_{eh}");
            INCDP->GetYaxis()->SetTitle("1/N_{NPE} #upoint dN/d(#Delta)#phi");
            INCDP->GetYaxis()->SetTitleOffset(1.55);
            if(ptbin == 0)
                INCDP->SetTitle("#Delta#phi Non-Photonic Electrons and Hadrons");
            else if (ptbin == 1 && trig !=3)
                INCDP->SetTitle(Form("HT%i",trig));
            else if (trig == 3 && ptbin == 1)
                INCDP->SetTitle("MB");
            else
                INCDP->SetTitle("");
            INCDP->Draw("");
            lbl[ptbin]->Draw("same");

            // Setup unscaled for fractionFit (don't normalize here!)
            unscaleINCDP->SetLineColor(kBlack);
            unscaleINCDP->SetLineWidth(1);
            unscaleINCDP->SetFillStyle(3001);
            unscaleINCDP->SetFillColor(kYellow);
            unscaleINCDP->GetXaxis()->SetRangeUser(lowPhi,highPhi);
            unscaleINCDP->GetXaxis()->SetTitle("#Delta#phi_{eh}");
            unscaleINCDP->GetYaxis()->SetTitle("1/N_{NPE} #upoint dN/d(#Delta)#phi");
            unscaleINCDP->GetYaxis()->SetTitleOffset(1.55);
            if(ptbin == 0)
                unscaleINCDP->SetTitle("#Delta#phi Non-Photonic Electrons and Hadrons");
            else if (ptbin == 1 && trig !=3)
                unscaleINCDP->SetTitle(Form("HT%i",trig));
            else if (trig == 3 && ptbin == 1)
                unscaleINCDP->SetTitle("MB");
            else
                unscaleINCDP->SetTitle("");

            // nSigmaPion QA
            nSigPi[trig]->cd(ptbin+1);
            NSPI[ptbin][trig]->SetLineColor(kGreen+3);
            NSPI[ptbin][trig]->SetLineWidth(1);
            NSPI[ptbin][trig]->GetXaxis()->SetTitle("n#sigma_{#pi}");
            NSPI[ptbin][trig]->GetXaxis()->SetRangeUser(-2.,2.);
            if(ptbin == 0)
                NSPI[ptbin][trig]->SetTitle("n Sigma Pion (n#sigma_{#pi})");
            else if (ptbin == 1 && trig !=3)
                NSPI[ptbin][trig]->SetTitle(Form("HT%i",trig));
            else if (trig == 3 && ptbin == 1)
                NSPI[ptbin][trig]->SetTitle("MB");
            else
                NSPI[ptbin][trig]->SetTitle("");
            NSPI[ptbin][trig]->Draw("");
            lbl[ptbin]->Draw("same");

            // All Distributions
            allDist[trig]->cd(ptbin+1);
            TH1F *INCLUSIVE = (TH1F*)INCLNP[ptbin][trig]->Clone();
            TH1F *UNLIKE  = (TH1F*)USIMNP[ptbin][trig]->Clone();
            TH1F *LIKE  = (TH1F*)LSIMNP[ptbin][trig]->Clone();
            TH1F *HADRON = (TH1F*)HHDP[ptbin][trig]->Clone();
            TH1F *USmLS  = (TH1F*)USIMNP[ptbin][trig]->Clone();
            USmLS->Add(LIKE,-1);
            USmLS->Scale(1./(USNorm-LSNorm));
            INCLUSIVE->Scale(1./inclNorm);
            UNLIKE->Scale(1./USNorm);
            LIKE->Scale(1./LSNorm);
            HADRON->Scale(1./hhNorm);
            INCLUSIVE->SetLineColor(7);
            LIKE->SetLineColor(kBlue);
            INCLUSIVE->GetYaxis()->SetRangeUser(0.01,2);
            gPad->SetLogy(1);
            INCLUSIVE->GetXaxis()->SetRangeUser(lowPhi,highPhi);
            INCLUSIVE->SetMarkerStyle(20);
            UNLIKE->SetMarkerStyle(21);
            LIKE->SetMarkerStyle(22);
            HADRON->SetMarkerStyle(23);
            USmLS->SetMarkerStyle(34);
            INCLUSIVE->SetMarkerColor(7);
            INCLUSIVE->SetMarkerSize(0.3);
            UNLIKE->SetMarkerSize(0.3);
            LIKE->SetMarkerSize(0.3);
            HADRON->SetMarkerSize(0.3);
            USmLS->SetMarkerSize(0.3);
            INCLUSIVE->SetMarkerColor(7);
            UNLIKE->SetMarkerColor(kRed);
            LIKE->SetMarkerColor(kBlue);
            HADRON->SetMarkerColor(kGreen+3);
            INCLUSIVE->Draw("");
            UNLIKE->Draw("same");
            LIKE->Draw("same");
            HADRON->Draw("same");
            USmLS->Draw("same");
            INCDP->Draw("same");
            lbl[ptbin]->Draw("same");
            stat[ptbin]->Draw("same");
            TLegend* legAll = new TLegend(0.45,0.11,0.85,0.3);
            legAll->AddEntry(INCLUSIVE,"Inclusive","lpe");
            legAll->AddEntry(UNLIKE,"Unlike Sign","lpe");
            legAll->AddEntry(LIKE,"Like Sign", "lpe");
            legAll->AddEntry(HADRON,"Hadron-Hadron", "lpe");
            legAll->AddEntry(USmLS,"Unlike-Like","lpe");
            legAll->AddEntry(INCDP,"NPE-h","lpe");
            legAll->Draw("same");

        }

        // Pileup Calculation (using just the hPtCut in the anaConst.h)
        /* mh3nTracksZdcx[trig]    = (TH3F*)f->Get(Form("mh3nTracksZdcx_%i_%i",trig,0));   // originally filled for various hpT cuts, use 0 which starts at hpt > 0.3
        mh3nTracksZdcxUS[trig]  = (TH3F*)f->Get(Form("mh3nTracksZdcxUS_%i_%i",trig,0)); // These histos are (epT,hpT,ZDCx), get nHadrons vs ZDCx
        mh3nTracksZdcxLS[trig]  = (TH3F*)f->Get(Form("mh3nTracksZdcxLS_%i_%i",trig,0));
        mh3nTracksZdcxHad[trig] = (TH3F*)f->Get(Form("mh3nTracksZdcxHad_%i_%i",trig,0));
        mh3nTracksZdcx[trig]->Sumw2(); mh3nTracksZdcxUS[trig]->Sumw2(); mh3nTracksZdcxLS[trig]->Sumw2();  mh3nTracksZdcxHad[trig]->Sumw2();

        mh2PtEZdcx[trig]       = (TH2F*)f->Get(Form("mh2PtEZdcx_%i",trig));            // Filled (epT,ZDCx). Get nTrigs vs ZDCx
        mh2PtEZdcxUS[trig]     = (TH2F*)f->Get(Form("mh2PtEZdcxUS_%i",trig));
        mh2PtEZdcxLS[trig]     = (TH2F*)f->Get(Form("mh2PtEZdcxLS_%i",trig));
        mh2PtEZdcxHad[trig]     = (TH2F*)f->Get(Form("mh2PtEZdcxHad_%i",trig));
        mh2PtEZdcx[trig]->Sumw2(); mh2PtEZdcxUS[trig]->Sumw2(); mh2PtEZdcxLS[trig]->Sumw2(); mh2PtEZdcxHad[trig]->Sumw2();

        for(Int_t ptbin=0; ptbin<numPtBins; ptbin++)// cut in to trigger pt slices
          {
        projZDCxHad[ptbin][trig] = mh3nTracksZdcx[trig]->ProjectionZ(Form("projZDCxHad_%i_%i",ptbin,trig),mh3nTracksZdcx[trig]->GetXaxis()->FindBin(lowpt[ptbin]),mh3nTracksZdcx[trig]->GetXaxis()->FindBin(highpt[ptbin])-1,mh3nTracksZdcx[trig]->GetYaxis()->FindBin(hptCut),mh3nTracksZdcx[trig]->GetYaxis()->FindBin(hptMax));
        projZDCxHadUS[ptbin][trig] = mh3nTracksZdcxUS[trig]->ProjectionZ(Form("projZDCxHadUS_%i_%i",ptbin,trig),mh3nTracksZdcxUS[trig]->GetXaxis()->FindBin(lowpt[ptbin]),mh3nTracksZdcxUS[trig]->GetXaxis()->FindBin(highpt[ptbin])-1,mh3nTracksZdcxUS[trig]->GetYaxis()->FindBin(hptCut),mh3nTracksZdcxUS[trig]->GetYaxis()->FindBin(hptMax));
        projZDCxHadLS[ptbin][trig] = mh3nTracksZdcxLS[trig]->ProjectionZ(Form("projZDCxHadLS_%i_%i",ptbin,trig),mh3nTracksZdcxLS[trig]->GetXaxis()->FindBin(lowpt[ptbin]),mh3nTracksZdcxLS[trig]->GetXaxis()->FindBin(highpt[ptbin])-1,mh3nTracksZdcxLS[trig]->GetYaxis()->FindBin(hptCut),mh3nTracksZdcxLS[trig]->GetYaxis()->FindBin(hptMax));
        projZDCxHadHad[ptbin][trig] = mh3nTracksZdcxHad[trig]->ProjectionZ(Form("projZDCxHadHad_%i_%i",ptbin,trig),mh3nTracksZdcxHad[trig]->GetXaxis()->FindBin(lowpt[ptbin]),mh3nTracksZdcxHad[trig]->GetXaxis()->FindBin(highpt[ptbin])-1,mh3nTracksZdcxHad[trig]->GetYaxis()->FindBin(hptCut),mh3nTracksZdcxHad[trig]->GetYaxis()->FindBin(hptMax));

        projZDCxTrig[ptbin][trig] = mh2PtEZdcx[trig]->ProjectionY(Form("projZDCxTrig_%i_%i",ptbin,trig),mh2PtEZdcx[trig]->GetXaxis()->FindBin(lowpt[ptbin]),mh2PtEZdcx[trig]->GetXaxis()->FindBin(highpt[ptbin])-1);
        projZDCxTrigUS[ptbin][trig] = mh2PtEZdcxUS[trig]->ProjectionY(Form("projZDCxTrigUS_%i_%i",ptbin,trig),mh2PtEZdcxUS[trig]->GetXaxis()->FindBin(lowpt[ptbin]),mh2PtEZdcxUS[trig]->GetXaxis()->FindBin(highpt[ptbin])-1);
        projZDCxTrigLS[ptbin][trig] = mh2PtEZdcxLS[trig]->ProjectionY(Form("projZDCxTrigLS_%i_%i",ptbin,trig),mh2PtEZdcxLS[trig]->GetXaxis()->FindBin(lowpt[ptbin]),mh2PtEZdcxLS[trig]->GetXaxis()->FindBin(highpt[ptbin])-1);
        projZDCxTrigHad[ptbin][trig] = mh2PtEZdcxHad[trig]->ProjectionY(Form("projZDCxTrigHad_%i_%i",ptbin,trig),mh2PtEZdcxHad[trig]->GetXaxis()->FindBin(lowpt[ptbin]),mh2PtEZdcxHad[trig]->GetXaxis()->FindBin(highpt[ptbin])-1);

        // Get Total number of hadrons in pileup (first scale each distribution by efficiency, just like data)
        projZDCxHadUS[ptbin][trig] -> Scale(1./epsilon[ptbin] - 1.);
        projZDCxHadLS[ptbin][trig] -> Scale(1./epsilon[ptbin]);
        projZDCxHadHad[ptbin][trig]-> Scale(HHScale*hadPur);
        projZDCxHad[ptbin][trig] -> Add(projZDCxHadUS[ptbin][trig], -1.);
        projZDCxHad[ptbin][trig] -> Add(projZDCxHadLS[ptbin][trig], 1.);
        projZDCxHad[ptbin][trig] -> Add(projZDCxHadHad[ptbin][trig], -1.);

        // Get Total number of trigs in pileup (first scale each distribution by efficiency, just like data)
        projZDCxTrigUS[ptbin][trig] -> Scale(1./epsilon[ptbin] - 1.);
        projZDCxTrigLS[ptbin][trig] -> Scale(1./epsilon[ptbin]);
        projZDCxTrigHad[ptbin][trig]-> Scale(HHScale*hadPur);
        projZDCxTrig[ptbin][trig] -> Add(projZDCxTrigUS[ptbin][trig], -1.);
        projZDCxTrig[ptbin][trig] -> Add(projZDCxTrigLS[ptbin][trig], 1.);
        projZDCxTrig[ptbin][trig] -> Add(projZDCxTrigHad[ptbin][trig], -1.);

        // Actually do the division of total hadrons/total trigs
        projZDCxHad[ptbin][trig]->Divide(projZDCxTrig[ptbin][trig]);

        // plot projections
        pile[trig]->cd(ptbin+1);
        projZDCxHad[ptbin][trig]->SetLineColor(kBlack);
        projZDCxHad[ptbin][trig]->GetXaxis()->SetTitle("ZDCx");
        projZDCxHad[ptbin][trig]->GetYaxis()->SetTitle("<nHadrons>/<nTracks>");
        projZDCxHad[ptbin][trig]->GetYaxis()->SetRangeUser(0,20);
        //
        gStyle->SetOptFit(1111);
        projZDCxHad[ptbin][trig]->Fit("pol1");
        projZDCxHad[ptbin][trig]->GetFunction("pol1")->SetLineColor(kRed);
        TPaveStats *st = ((TPaveStats*)(projZDCxHad[ptbin][trig]->GetListOfFunctions()->FindObject("stats")));
        if (st) {
          st->SetTextColor(projZDCxHad[ptbin][trig]->GetFunction("pol1")->GetLineColor());
          st->SetX1NDC(0.64); st->SetX2NDC(0.99);
          st->SetY1NDC(0.4); st->SetY2NDC(0.6);
        }
        pile[trig]->Modified();pile[trig]->Update();
        projZDCxHad[ptbin][trig]->Draw("");

        // Get Fit information and store to use in corrections
        TF1 *fitResult = projZDCxHad[ptbin][trig]->GetFunction("pol1");
        pu[0][ptbin][trig] = fitResult->GetParameter(0);
        pu[1][ptbin][trig] = fitResult->GetParameter(1);
           	cout << trig << " " << ptbin << ": " << pu[0][ptbin][trig] << " " << pu[1][ptbin][trig] << endl;
        }*/
    }

    // Draw on "SinglePlot" canvas for saving single plots from grid
    TPad* pNew = (TPad*)result[2]->GetPad(4)->Clone();
    singlePlot->cd();
    pNew->ResizePad();
    pNew->Draw();

    // Make PDF with output canvases
    if(makePDF)
    {
        //Set front page
        TCanvas* fp = new TCanvas("fp","Front Page",100,0,1000,900);
        fp->cd();
        TBox *bLabel = new TBox(0.01, 0.88, 0.99, 0.99);
        bLabel->SetFillColor(38);
        bLabel->Draw();
        TLatex tl;
        tl.SetNDC();
        tl.SetTextColor(kWhite);
        tl.SetTextSize(0.033);
        char tlName[100];
        char tlName2[100];

        TString titlename = FileName;
        int found = titlename.Last('/');
        if(found >= 0) {
            titlename.Replace(0, found+1, "");
        }
        sprintf(tlName, "RUN 12 pp 200 GeV NPE-h    #Delta#phi Analysis");
        tl.SetTextSize(0.05);
        tl.SetTextColor(kWhite);
        tl.DrawLatex(0.05, 0.92,tlName);

        TBox *bFoot = new TBox(0.01, 0.01, 0.99, 0.12);
        bFoot->SetFillColor(38);
        bFoot->Draw();
        tl.SetTextColor(kWhite);
        tl.SetTextSize(0.05);
        tl.DrawLatex(0.05, 0.05, (new TDatime())->AsString());
        tl.SetTextColor(kBlack);
        tl.SetTextSize(0.03);
        tl.DrawLatex(0.1, 0.14, titlename);
        sprintf(tlName,"eID: -1 < n  #sigma_{e TPC} < 3;  #left|gDCA #right| < 1 cm; 0.3 < p/E < 1.5;");
        tl.DrawLatex(0.1, 0.8,tlName);
        sprintf(tlName,"       nHitsFit > 20; nHits   #frac{dE}{dx} > 15; nHitFit/Max > 0.52;    #left|#eta#right| < 0.7;");
        tl.DrawLatex(0.1, 0.75,tlName);
        sprintf(tlName,"       n #phi > 1; n #eta > 1;  #left|dZ#right| < 3 cm;  #left|d#phi#right| < 0.015;");
        tl.DrawLatex(0.1, 0.7,tlName);
        sprintf(tlName,"hID: p_{T} > 0.5;  #left|#eta#right| < 1; nHitsFit > 15; nHits   #frac{dE}{dx} > 10; DCA < 1 cm;");
        tl.DrawLatex(0.1, 0.6,tlName);
        sprintf(tlName,"Event:  #left|V_{z}#right| < 35 cm;");
        tl.DrawLatex(0.1, 0.5,tlName);
        sprintf(tlName,"Triggers:  BHT0; BHT2;");
        tl.DrawLatex(0.1, 0.4,tlName);


        // Place canvases in order
        TCanvas* temp = new TCanvas();
        sprintf(name, "%s.pdf[", FileName);
        temp->Print(name);
        sprintf(name, "%s.pdf", FileName);
        temp = fp; // print front page
        temp->Print(name);
        temp = mixedC;
        temp->Print(name);
        temp = mixedCbinEta;
        temp->Print(name);
        temp = mixedCbinPhi;
        temp->Print(name);
        temp = mixedCbin;
        temp->Print(name);
        for(Int_t ii=0; ii<numTrigs; ii++)
        {
            if(!fPaintAll && (ii==1 || ii==3))
                continue;
            temp = IN[ii];
            temp->Print(name);
            temp = c[ii];
            temp->Print(name);
            temp = cHH[ii];
            temp->Print(name);
            temp = result[ii];
            temp->Print(name);
            temp = pile[ii];
            temp->Print(name);
            /*temp = inMass[ii];
            temp->Print(name);
            temp = USComp[ii];
            temp->Print(name);
            temp = LSComp[ii];
            temp->Print(name);
            temp = InclComp[ii];
            temp->Print(name);*/
            temp = nSigPi[ii];
            temp->Print(name);
            temp = allDist[ii];
            temp->Print(name);

        }
        sprintf(name, "%s.pdf]", FileName);
        temp->Print(name);
    }

    if(makeROOT)
    {
        file->Write();
        file->Close();
    }
}
Esempio n. 3
0
void jpsiAnalize(TFile* f)
{
	TH2F* h = (TH2F*)f->Get("runLumi");
	std::map<int, std::vector < int > > runs;	
	std::map<int, std::vector < int > >::iterator runsIt;
	int nBinY = h->GetNbinsY();
	int nBinX = h->GetNbinsX();
		
	std::vector <int> lumis;
	double x, y;
	//std::cout << "{";
	double prevY=0;
	double lumicount=0;
	double lumMax = 0;
	for(int i = 0; i < nBinX + 4 ;++i)
	{
		prevY=0.0;
		double runcounter = 0;
		//x = h->GetXaxis()->GetBinCenter(i);
		//std::cout << "\""<<x<<"\":[";
		double candcounter=0.;
		for(int j = 0; j< nBinY + 4; ++j)
			{
			
				int bin = h->GetBin(i,j);
				double cont = h->GetBinContent(bin);
			
				x = h->GetXaxis()->GetBinCenter(i);
				candcounter +=cont;
			
				if(cont>0.0)
				{	
					runcounter++;					
					runs[int(x)] = lumis; 
					y = h->GetYaxis()->GetBinCenter(j);	
					if(prevY<y-1 && prevY!=0.0)
					std::cout << x << " " << y << " " << prevY <<std::endl;
					prevY=y;
				}
							
			}
		//std::cout<<"], ";
		if(runcounter >0.0)		
		std::cout << x <<" -> run counter " << runcounter << " -> cand counter :" << candcounter <<std::endl; 
		lumMax = std::max(lumMax,runcounter);
	}
	//std::cout<<"}";
	
	for(int i = 0; i < nBinX + 4 ;++i)
	{
		 for(int j = 0; j< nBinY + 4; ++j)
		 {
			 x = h->GetXaxis()->GetBinCenter(i) ;
			 int bin = h->GetBin(i,j);
			 double cont = h->GetBinContent(bin);
		 	 if(cont>0.0)
			 {
				 y = h->GetYaxis()->GetBinCenter(j);  
				 runs[int(x)].push_back(int(y));
				 ++lumicount;
			 }

		 }
	}

	std::cout << "{";	
	for(runsIt=runs.begin();runsIt!=runs.end();runsIt++)
	{

		std::cout << "\""<<runsIt->first<<"\":[";
		int prevLum=0;
		for(int k = 0; k<runsIt->second.size();k++)
		{
			if(k==0)
			{
				std::cout<<"[";
				std::cout<<(runsIt->second)[k]<<", ";	
			
				if(k==runsIt->second.size()-1)
			                        {
					                                std::cout<<(runsIt->second)[k]<<"]";
							                        }

			}
			else
			if(!((runsIt->second)[k]==prevLum+1))
			{
				std::cout<<prevLum<<"], ["<<(runsIt->second)[k]<<", ";		
				if(k==runsIt->second.size()-1)
				{
					std::cout<<(runsIt->second)[k]<<"]";
				}
				
			}
			else
			{
				if(k==runsIt->second.size()-1)
					                                {
										                                        std::cout<<(runsIt->second)[k]<<"]";
															                                }
			}

			

			prevLum = (runsIt->second)[k];
		}	
			
		
		std::cout << "], ";
	}
	std::cout<<"}";
	std::cout<<std::endl;
	std::cout<<lumicount<<std::endl;
	std::cout<<lumMax<<std::endl;
}
Esempio n. 4
0
void
CalcFakeRate(string infile, bool useData=true, bool doSystematics=false){  
  cout<<" UseData="<<useData<<" dosystematics="<<doSystematics<<endl;

  TFile *f = TFile::Open(infile.c_str(), "read"); assert(f);
  TH2F* hFakeRateNum = NULL;
  TH2F* hFakeRateAll = NULL;
  gStyle->SetOptStat(0);
  gStyle->SetPalette(1);
  gStyle->SetTextFont(132);
  gStyle->SetTextSize(1.2);
  //gROOT->ForceStyle();

  bool useElectrons = infile.find("Muon") == string::npos;
  bool doWLep = infile.find("-TT") == string::npos;

  vector<string> allsamples;
  if(!useData){
    allsamples.push_back("WJetsToLNu");
    if(!doSystematics){
    allsamples.push_back("TTJets");
    allsamples.push_back("ZZ");
    allsamples.push_back("GVJets");
    allsamples.push_back("WWTo2L2Nu");
    allsamples.push_back("WZJetsTo3LNu");
    allsamples.push_back("DYJetsToLL");
    }
  }else{
    allsamples.push_back("data");
  }
  
  float offset = 0.01;
  float eta[] = {0., 1.5, 2.5}; int neta = 3;
  if(!useElectrons){
    eta[1] = 2.4;
    neta = 2;//eta[2] = 2.4;
  }

  //float pt [] = {0., 20., 40., 1000}; const int npt  = 4;
  //float pt [] = {0., 10., 20., 30., 1000}; const int npt  = 5;

  //float pt [] = {0., 10., 15., 25., 1000}; const int npt  = 5;
  //float pt [] = {0., 10., 15., 20., 30., 1000}; const int npt  = 6;
  float pt [] = {10., 15., 20., 30., 40., 100}; const int npt  = 6;

  //float pt [] = {0., 20., 25., 30., 50., 1000}; const int npt  = 6;
  hFakeRateNum = new TH2F("hFakeRateNum", "hFakeRateNum;p_{T} (GeV);#eta", npt-1, pt, neta-1, eta);
  hFakeRateAll = new TH2F("hFakeRateAll", "hFakeRateAll;p_{T} (GeV);#eta", npt-1, pt, neta-1, eta);
  string title = useElectrons ? "Electron Fake Rate" : "Muon Fake Rate";
  title += useData ? " from Data" : " from MC";
  title += !useData && doSystematics ? " Systematics" : "";
  title += " using W+Jets method";
  title += doWLep ? " on W lepton" : " on Z lepton";
  hFakeRateNum->SetTitle(title.c_str());

/////////This is for eta, pt agnotistic Fake Rate Calc
  float in_tot(0), out_tot(0);
  for(unsigned i=0; i<allsamples.size(); ++i){
    string hist_name = allsamples[i] + "/hNumEvts";
    TH1F* hist = (TH1F*) f->Get(hist_name.c_str()); assert(hist);
    int lastbin = hist->GetNbinsX();
    float in(0), out(0);

    in  = hist->GetBinContent(lastbin);
    out = hist->GetBinContent(lastbin-1);

    in_tot += in;
    out_tot += out;

    //cout<<"Sample: "<<allsamples[i]<<" = "<<in/out<<" = pass/total = "<<in<<"/"<<out<<endl;
    printf("  Sample: %s = %.2f%% : pass/total = %.2f / %.2f \n",allsamples[i].c_str(), in/out*100, in, out);
  }
  float  eff = in_tot/out_tot;
  float deff = TMath::Sqrt(eff * (1-eff)/out_tot);
  //cout<<"Total: "<<eff*100<<"% +/- "<<deff*100<<"% = in_tot/out_tot*100% = "<<in_tot<<"/"<<out_tot<<"*100%\n";
  printf("Total: %.2f%% +/- %.2f%% = in_tot/out_tot*100%% = %.2f/%.2f\n", eff*100, deff*100, in_tot, out_tot);


/////////This is for 2D Fake Rate Calc
  for(unsigned i=0; i<allsamples.size(); ++i){
    string hist_name = allsamples[i] + "/hNumEvts";
    TH1F* hist = (TH1F*) f->Get(hist_name.c_str()); assert(hist);
    int lastbin = hist->GetNbinsX();
    float in(0), out(0);
    string binNameNum   = hist->GetXaxis()->GetBinLabel(lastbin);
    string binNameDenom = hist->GetXaxis()->GetBinLabel(lastbin-1);
      
    string hist_nameNum = allsamples[i] + "/hEtaVsPt_" + binNameNum;
    TH2F* histNum = (TH2F*) f->Get(hist_nameNum.c_str()); assert(histNum);
      
    string hist_nameDenom = allsamples[i] + "/hEtaVsPt_" + binNameDenom;
    TH2F* histDenom = (TH2F*) f->Get(hist_nameDenom.c_str()); assert(histDenom);
/*
    cout<<" Total from 2D Plot is "<<histNum->Integral()<<" / "<<histDenom->Integral()<<endl; //By default, integral doesn't count over/underflow
    cout<<" Total from 2D Plot is "<<histNum->GetEntries()<<" / "<<histDenom->GetEntries()<<endl;

    float sUnder(0), sOver(0);
    for(int ybin = 0; ybin<= histDenom->GetYaxis()->GetNbins() + 1; ++ybin){
      for(int xbin = 0; xbin<= histDenom->GetXaxis()->GetNbins() +1; ++xbin){
        int bin = histDenom->GetBin(xbin, ybin);
        if(histDenom->IsBinOverflow(bin)) sOver += histDenom->GetBinContent(bin);
        if(histDenom->IsBinUnderflow(bin)) sUnder += histDenom->GetBinContent(bin);
      }
    }
    printf("Total overflow, underflow in denom histo is %.2f , %.2f\n", sOver, sUnder);
*/
    for(int ieta=0; ieta<neta-1; ++ieta){
      float ymin = eta[ieta]; 
      float ymax = eta[ieta+1]-offset;
      for(int ipt=0; ipt<npt-1; ++ipt){
        float xmin = pt[ipt]; 
        float xmax = pt[ipt+1];
          
        int xminbin,xmaxbin,yminbin,ymaxbin;
        xminbin = histNum->GetXaxis()->FindBin(xmin); //+ (ipt!=0);//Avoid overlap except for first bin
        xmaxbin = histNum->GetXaxis()->FindBin(xmax)-1 + (ipt == npt-1-1);
        yminbin = histNum->GetYaxis()->FindBin(ymin);
        ymaxbin = histNum->GetYaxis()->FindBin(ymax);
        
        /*
        cout<<"("<<pt[ipt]<<", "<<eta[ieta]<<")\t"
            <<xmin<<"-"<<xmax<<":"
            <<ymin<<"-"<<ymax<<":"
            <<"\t";
        cout<<"("<<ipt<<", "<<ieta<<")\t"
            <<xminbin<<"-"<<xmaxbin<<":"
            <<yminbin<<"-"<<ymaxbin
            <<endl;
        */      
        in  = histNum  ->Integral(xminbin, xmaxbin, yminbin, ymaxbin);
        out = histDenom->Integral(xminbin, xmaxbin, yminbin, ymaxbin);
          
        //Cory: Deal with negative eta (Y axis)
        yminbin = histNum->GetYaxis()->FindBin(-1*ymax);
        ymaxbin = histNum->GetYaxis()->FindBin(-1*ymin)-1;//avoid overlap
        /*
        cout<<"("<<pt[ipt]<<", "<<eta[ieta]<<")\t"
            <<xmin<<"-"<<xmax<<":"
            <<ymin<<"-"<<ymax<<":"
            <<"\t";
        cout<<"("<<ipt<<", "<<ieta<<")\t"
            <<xminbin<<"-"<<xmaxbin<<":"
            <<yminbin<<"-"<<ymaxbin
            <<endl;
        */
        in  += histNum  ->Integral(xminbin, xmaxbin, yminbin, ymaxbin);
        out += histDenom->Integral(xminbin, xmaxbin, yminbin, ymaxbin);

        //cout<<"("<<pt[ipt]<<","<<eta[ieta]<<") "<<in<<"/"<<out<<endl;
        //cout<<"("<<(pt[ipt]+pt[ipt+1])/2<<","<<(eta[ieta]+eta[ieta+1])/2<<") "<<in<<"/"<<out<<endl;
        hFakeRateNum   ->Fill( (pt[ipt]+pt[ipt+1])/2, (eta[ieta]+eta[ieta+1])/2, in);
        hFakeRateAll->Fill( (pt[ipt]+pt[ipt+1])/2, (eta[ieta]+eta[ieta+1])/2, out);

      }
    }

  }

  if(hFakeRateNum){
    //TGraphAsymmErrors* hFakeRateEff = new TGraphAsymmErrors(hFakeRateNum->GetArray(), hFakeRateAll->GetArray(), "");
    //TGraphAsymmErrors* hFakeRateEff = new TGraphAsymmErrors(hFakeRateNum, hFakeRateAll, "");
    TH2F* hFakeRate = (TH2F*) hFakeRateNum->Clone("hFakeRate");
    //hFakeRate->Divide(hFakeRateAll);
    //hFakeRate->Scale(100.); //make is a percent
    TCanvas c1;
    c1.SetLogx(1);


    //gStyle->SetTextFont(132);
    //gStyle->SetTextSize(1.2);
    hFakeRate->SetMarkerSize(3);
    //gStyle->SetPaintTextFormat("3.0f m");
    gStyle->SetPaintTextFormat("4.0f");
    hFakeRate->Draw("colz");

    TLatex latexLabel;
    latexLabel.SetNDC();
    latexLabel.SetTextSize(0.04);
    latexLabel.SetTextFont(42);
    latexLabel.SetTextAngle(90);
    latexLabel.SetTextAlign(22);
    for(int ybin = 1; ybin<= hFakeRate->GetYaxis()->GetNbins(); ++ybin){
      int nx = hFakeRate->GetXaxis()->GetNbins();
      TGraphAsymmErrors* gFakeRatePt = new TGraphAsymmErrors(nx);
      gFakeRatePt->SetMaximum(1.1);
      gFakeRatePt->SetMinimum(0.);
      gFakeRatePt->SetTitle((title + ";p_{T} (GeV);Rate").c_str());
      for(int xbin = nx; xbin >= 1; --xbin){
        float xcen = hFakeRate->GetXaxis()->GetBinCenter(xbin);
        float ycen = hFakeRate->GetYaxis()->GetBinCenter(ybin);
        
        double xpos, ypos;
        GetNDC(c1, xcen, ycen, xpos, ypos);
        int bin = hFakeRate->GetBin(xbin, ybin);
        float pass = hFakeRateNum->GetBinContent(bin);
        float tot  = hFakeRateAll->GetBinContent(bin);
        float mean    = tot>0 ? pass / tot : 0.;
        float errUp   = TEfficiency::ClopperPearson(tot, pass, 0.68, true) - mean;//hFakeRateEff->GetErrorYhigh(bin-1);
        float errDown = mean - TEfficiency::ClopperPearson(tot, pass, 0.68, false);//hFakeRateEff->GetErrorYlow(bin-1);
        errDown = max(errDown, (float) 0.);
        hFakeRate->SetBinContent(bin, mean);
        //hFakeRate->SetBinError(bin, err);
        float err = (errUp + errDown)/2;
        printf("if(pt > %.0f) return Value(%.4f, %.4f); //pt %3.0f eta %.1f, bin %2i, (mean, err)= (%.4f, %.4f) (%.2f / %.2f) +%.4f -%.4f\n", 
               hFakeRate->GetXaxis()->GetBinLowEdge(xbin), mean, err, 
               hFakeRate->GetXaxis()->GetBinLowEdge(xbin), hFakeRate->GetYaxis()->GetBinLowEdge(ybin), bin, mean, err, pass, tot, errUp, errDown);
        if(xbin != 1) latexLabel.DrawLatex(xpos, ypos, Form("%.0f^{+%.0f}_{-%.0f}%% (%.0f/%.0f)(%.f-%.f)GeV",mean*100, errUp*100, errDown*100, pass, tot, pt[xbin-1],pt[xbin]));
        

        gFakeRatePt->SetPoint      (xbin-1, xcen, mean);
        gFakeRatePt->SetPointEYhigh(xbin-1, errUp);
        gFakeRatePt->SetPointEYlow (xbin-1, errDown);
        gFakeRatePt->SetPointEXhigh(xbin-1, hFakeRate->GetXaxis()->GetBinLowEdge(xbin+1) - xcen);
        gFakeRatePt->SetPointEXlow (xbin-1, xcen - hFakeRate->GetXaxis()->GetBinLowEdge(xbin));

      }//pt loop
      c1.Clear();
      c1.SetLogx(1);
      //c1.SetGrid();
      gFakeRatePt->Draw("ap*");
      string outName = Form("WJetsFakeRatePt-Eta%.1fto%.1f-", hFakeRate->GetYaxis()->GetBinLowEdge(ybin), hFakeRate->GetYaxis()->GetBinLowEdge(ybin+1));
      replace(outName.begin(), outName.end(), '.', 'p');
      outName += useElectrons ? "Elec" : "Muon";
      outName += useData ? "Data" : "MC";
      outName += !useData && doSystematics ? "Sys" : "";
      outName += doWLep ? "WLep" : "ZLep";
      outName += ".pdf";
      c1.Print(outName.c_str());
      
    }//eta loop
    
    c1.Clear();
    c1.SetLogx(1);
    string outName = "FakeRate";
    outName += useElectrons ? "Elec" : "Muon";
    outName += useData ? "Data" : "MC";
    outName += !useData && doSystematics ? "Sys" : "";
    outName += doWLep ? "WLep" : "ZLep";
    outName += ".pdf";
    c1.Print(outName.c_str());

    //Now make profiles
    c1.Clear();
    c1.SetLogx(0);
    //c1.SetGrid();

    TH1D* hFakeRateNumEta = hFakeRateNum->ProjectionY("hFakeRateNumEta", 0, -1, "e");
    TH1D* hFakeRateAllEta = hFakeRateAll->ProjectionY("hFakeRateAllEta", 0, -1, "e");
    //TH1D* hFakeRateEta = (TH1D*) hFakeRateNumEta->Clone("hFakeRateEta");

    int n = hFakeRateAllEta->GetXaxis()->GetNbins();
    TGraphAsymmErrors* hFakeRateEta = new TGraphAsymmErrors(n);//hFakeRateNumEta, hFakeRateAllEta);
    hFakeRateEta->SetMaximum(1.);
    hFakeRateEta->SetMinimum(0.);
    hFakeRateEta->SetTitle((title + ";#eta;Rate").c_str());

    //hFakeRateEta->SetMarkerStyle(21);    
    for(int xbin = 1; xbin <= n; ++xbin){
      float x = hFakeRateAllEta->GetXaxis()->GetBinCenter(xbin);
      float pass = hFakeRateNumEta->GetBinContent(xbin);
      float tot  = hFakeRateAllEta->GetBinContent(xbin);
      float mean    = tot>0 ? pass / tot : 0.;
      float errUp   = TEfficiency::ClopperPearson(tot, pass, 0.68, true) - mean;//hFakeRateEff->GetErrorYhigh(bin-1);
      float errDown = mean - TEfficiency::ClopperPearson(tot, pass, 0.68, false);//hFakeRateEff->GetErrorYlow(bin-1);
      errDown = max(errDown, (float) 0.);
      hFakeRateEta->SetPoint      (xbin, x, mean);
      hFakeRateEta->SetPointEYhigh(xbin, errUp);
      hFakeRateEta->SetPointEYlow (xbin, errDown);
      //printf("bin: %i, x=%.0f, %.0f/%.0f = %.0f +%.0f -%.0f\n", xbin, x, pass, tot, mean*100, errUp*100, errDown*100);
    }
    
    //hFakeRateEta->Divide(hFakeRateAllEta);
    //hFakeRateEta->Scale(100.);
    hFakeRateEta->Draw("ap*");
    outName = "FakeRateEta";
    outName += useElectrons ? "Elec" : "Muon";
    outName += useData ? "Data" : "MC";
    outName += !useData && doSystematics ? "Sys" : "";
    outName += doWLep ? "WLep" : "ZLep";
    outName += ".pdf";
    c1.Print(outName.c_str());

    //Pt projections (split these by eta?)
    c1.Clear();
    c1.SetLogx(1);
    //c1.SetGrid();

    TH1D* hFakeRateNumPt = hFakeRateNum->ProjectionX("hFakeRateNumPt", 0, -1, "e");
    TH1D* hFakeRateAllPt = hFakeRateAll->ProjectionX("hFakeRateAllPt", 0, -1, "e");
    //TH1D* hFakeRatePt = (TH1D*) hFakeRateNumPt->Clone("hFakeRatePt");

    n = hFakeRateAllPt->GetXaxis()->GetNbins();
    TGraphAsymmErrors* hFakeRatePt = new TGraphAsymmErrors(n);//hFakeRateNumPt, hFakeRateAllPt);
    hFakeRatePt->SetMaximum(1.);
    hFakeRatePt->SetMinimum(0.);
    hFakeRatePt->SetTitle((title + ";p_{T} (GeV);Rate").c_str());

    for(int xbin = 1; xbin <= n; ++xbin){
      float x = hFakeRateAllPt->GetXaxis()->GetBinCenter(xbin);
      float pass = hFakeRateNumPt->GetBinContent(xbin);
      float tot  = hFakeRateAllPt->GetBinContent(xbin);
      float mean    = tot>0 ? pass / tot : 0.;
      float errUp   = TEfficiency::ClopperPearson(tot, pass, 0.68, true) - mean;//hFakeRateEff->GetErrorYhigh(bin-1);
      float errDown = mean - TEfficiency::ClopperPearson(tot, pass, 0.68, false);//hFakeRateEff->GetErrorYlow(bin-1);
      errDown = max(errDown, (float) 0.);
      hFakeRatePt->SetPoint      (xbin, x, mean);
      hFakeRatePt->SetPointEYhigh(xbin, errUp);
      hFakeRatePt->SetPointEYlow (xbin, errDown);
      //cout<<"low edge is "<<hFakeRateAllPt->GetXaxis()->GetBinLowEdge(xbin)<<" up edge is "
      //    <<hFakeRateAllPt->GetXaxis()->GetBinLowEdge(xbin+1)<<endl;
      hFakeRatePt->SetPointEXhigh(xbin, hFakeRateAllPt->GetXaxis()->GetBinLowEdge(xbin+1) - x);
      hFakeRatePt->SetPointEXlow (xbin, x - hFakeRateAllPt->GetXaxis()->GetBinLowEdge(xbin));
      printf("bin: %i, x=%.0f, %.0f/%.0f = %.0f +%.0f -%.0f\n", xbin, x, pass, tot, mean*100, errUp*100, errDown*100);
    }
    


    //hFakeRatePt->Divide(hFakeRateAllPt);
    //hFakeRatePt->Scale(100.);
    hFakeRatePt->Draw("ap*");
    outName = "FakeRatePt";
    outName += useElectrons ? "Elec" : "Muon";
    outName += useData ? "Data" : "MC";
    outName += !useData && doSystematics ? "Sys" : "";
    outName += doWLep ? "WLep" : "ZLep";
    outName += ".pdf";
    c1.Print(outName.c_str());

    
  }


}