std::pair<TH1F*,TH1F*> GetPMSyst(TH1F* trueHist, TH1F* intHist, std::string name){
  TH1F *diff = (TH1F*)trueHist->Clone();
  diff->Add(intHist,-1);
  diff->Divide(intHist);
  diff->Scale(3.);
  TH1F *up = (TH1F*)intHist->Clone();
  up->Add(diff,1);
  up->SetName((name+"Up01_sigma").c_str());
  TH1F *down = (TH1F*)intHist->Clone();
  down->Add(diff,-1);
  down->SetName((name+"Down01_sigma").c_str());

  std::pair<TH1F*,TH1F*> result(up,down);
  return result; 
}
Ejemplo n.º 2
0
TF1 * iterateFitter(TH1F * histo, int i, TF1 * previousResiduals = 0, TCanvas * inputCanvas = 0)
{
  TCanvas * canvas = inputCanvas;
  std::stringstream ss;
  int iCanvas = i;
  ss << i;

  int nBins = histo->GetNbinsX();

  TF1 * functionToFit;
  if( previousResiduals == 0 ) {
    // functionToFit = relativisticBWFit(ss.str());
    // functionToFit = relativisticBWintFit(ss.str());
    // functionToFit = relativisticBWintPhotFit(ss.str());
    functionToFit = expRelativisticBWintPhotFit(ss.str());
    // functionToFit = crystalBallFit();
    // functionToFit = reversedCrystalBallFit();
    // functionToFit = lorentzianFit();
    // functionToFit = relativisticBWFit();
  }
  else {
    functionToFit = combinedFit(previousResiduals->GetParameters(), ss.str());
  }
  histo->Fit(functionToFit, "MN", "", 60, 120);


  double xMin = histo->GetXaxis()->GetXmin();
  double xMax = histo->GetXaxis()->GetXmax();
  double step = (xMax-xMin)/(double(nBins));
  TH1F * functionHisto = new TH1F(("functionHisto"+ss.str()).c_str(), "functionHisto", nBins, xMin, xMax);
  for( int i=0; i<nBins; ++i ) {
    functionHisto->SetBinContent( i+1, functionToFit->Eval(xMin + (i+0.5)*step) );
  }

  if( canvas == 0 ) {
    canvas = new TCanvas(("canvasResiduals"+ss.str()).c_str(), ("canvasResiduals"+ss.str()).c_str(), 1000, 800);
    canvas->Divide(2,1);
    canvas->Draw();
    iCanvas = 0;
  }
  canvas->cd(1+2*iCanvas);
  histo->Draw();
  functionToFit->SetLineColor(kRed);
  functionToFit->Draw("same");
  // functionHisto->Draw("same");
  // functionHisto->SetLineColor(kGreen);
  canvas->cd(2+2*iCanvas);
  TH1F * residuals = (TH1F*)histo->Clone();
  residuals->Add(functionHisto, -1);
  residuals->SetName("Residuals");

  // TF1 * residualFit = new TF1("residualFit", "-[0] + [1]*x+sqrt( ([1]-1)*([1]-1)*x*x + [0]*[0] )", 0., 1000. );
  // TF1 * residualFit = new TF1("residualFit", "[0]*(x - [1])/([2]*x*x + [3]*x + [4])", 0., 1000. );
  TF1 * residualFitFunction = residualFit(ss.str());
  residuals->Fit(residualFitFunction, "ME", "", 90.56, 120);

  residuals->Draw();

  return residualFitFunction;
}
Ejemplo n.º 3
0
void real_emission_jackknife(TString dir="real_aajj_splitted_for_jackknife", TString nameroot="outphoton_aajj_effunf_mu1", int N=20){

  TFile *outfile = new TFile(Form("%s/%s_jackknifed.root",dir.Data(),nameroot.Data()),"recreate");
  outfile->mkdir("effunf");

  vector<TFile*> files;
  for (int i=1; i<=N; i++){
    files.push_back(new TFile(Form("%s/%s_splitted_%d.root",dir.Data(),nameroot.Data(),i),"read"));
  }

  for (std::vector<TString>::const_iterator it = diffvariables_list.begin(); it!=diffvariables_list.end(); it++){
    for (int reg=0; reg<3; reg++)
      {
	TString diffvar = *it;
	vector<TH1F*> histos;
	TString thisname = Form("htruth_%s_%d",diffvar.Data(),reg);
	TString thisnamedir = Form("effunf/%s",thisname.Data());
	for (uint i=0; i<files.size(); i++){
	  histos.push_back((TH1F*)(files.at(i)->Get(thisnamedir.Data())));
	}
	TH1F *out = JackknifammiStiHistos(histos);
	out->SetName(thisname.Data());
	out->Print();
	outfile->cd("effunf");
	out->Write();
#ifdef DEBUG
	return;
#endif
      } 
  }
  
  outfile->Close();
};
Ejemplo n.º 4
0
TH1F* fixrange(TH1F* old, int numB) {

  float x1, x2;
  string name = old->GetName();

  if (name.find("Ht")!=string::npos) {
    x1 = 30.;
    x2 = 500.;
    if (numB==2) x2 = 400.;
  } else if (name.find("jet_pt")!=string::npos) {
    x1 = 30.;
    x2 = 300.;
    if (numB==2) {
      if (name.find("first")!=string::npos) x2 = 200.;
      if (name.find("second")!=string::npos) x2 = 120.;
    }
  } else if (name.find("pt_Z")!=string::npos) {
    x1 = 0.;
    x2 = 300.;
    if (numB==2) x2 = 230.;
  } else {
    x1 = old->GetXaxis()->GetBinCenter(1);
    x2 = old->GetXaxis()->GetBinCenter(old->GetNbinsX());
  }

  int nx = old->GetXaxis()->FindBin(x2)-old->GetXaxis()->FindBin(x1)+1;

  x1 = old->GetXaxis()->GetBinLowEdge(old->GetXaxis()->FindBin(x1));
  x2 = old->GetXaxis()->GetBinUpEdge(old->GetXaxis()->FindBin(x2));

  TH1F* tmp = new TH1F("tmp",old->GetTitle(),nx,x1,x2);
  tmp->Sumw2();

  tmp->GetXaxis()->SetTitle(old->GetXaxis()->GetTitle());
  tmp->GetYaxis()->SetTitle(old->GetYaxis()->GetTitle());

  for (int i=0;i<=old->GetNbinsX()+1;i++) {
    int ii = tmp->GetXaxis()->FindBin(old->GetXaxis()->GetBinCenter(i));
    float c1 = tmp->GetBinContent(ii);
    float e1 = tmp->GetBinError(ii);
    float c2 = old->GetBinContent(i);
    float e2 = old->GetBinError(i);

    tmp->SetBinContent(ii,c1+c2);
    tmp->SetBinError(ii,TMath::Sqrt(e1*e1+e2*e2));
  }

  tmp->SetEntries(old->GetEntries());

  old->Delete();
  tmp->SetName(name.c_str());

  return tmp;
}
Ejemplo n.º 5
0
void makePlot(vector<TTree*> sigTree,vector<double> sigWeight,
	      vector<int> ptHatLo, vector<int> ptHatHi,
              std::string var,TCut cut,TH1F* h,bool norm)
{
   TH1F *hRes = (TH1F*)h->Clone();
   hRes->SetName("hRes");
   hRes->Sumw2();
  
   char tmp[300];
   for (unsigned int i=0; i<sigTree.size(); i++)
     {
       // first determine the pthat cut
       
       sprintf(tmp, "ptHat >= %d && ptHat <= %d",ptHatLo[i], ptHatHi[i]);
       TCut ptHatCut = tmp;
       TCut allCut = cut + ptHatCut;
       cout << "Current cut = " << allCut.GetTitle() << endl;
       TH1F *htmp = (TH1F*)h->Clone();
       htmp->SetName("htmp");
       sigTree[i]->Draw(Form("%s>>htmp",var.data()),allCut);
       htmp->Sumw2();
       htmp->Scale(sigWeight[i]);
       cout << "scale = " << sigWeight[i] << endl;
       cout << "After scaling htmp -> entries() " << htmp->GetEntries() << endl;
       cout << "After scaling htmp -> Integral() " << htmp->Integral() << endl;
       cout << "After scaling htmp -> GetMean()  " << htmp->GetMean() << endl;
       cout << "After scaling htmp -> GetRMS()  " << htmp->GetRMS() << endl;
       hRes->Add(htmp);
       delete htmp;
   }
   h->Sumw2();
   h->Add(hRes);
   if(norm)h->Scale(1.0/(double)h->Integral(0,1000));
   cout << "After scaling h-> entries() " << h->GetEntries() << endl;
   cout << "After scaling h-> Integral() " << h->Integral() << endl;
   cout << "After scaling h -> GetMean()  " << h->GetMean() << endl;
   cout << "After scaling h -> GetRMS()  " << h->GetRMS() << endl;
   
   delete hRes;
}
//Merge Histogram with function histogram
TH1F * merge(std::string iName,double iMergePoint,TH1F *iH,TH1F *iFunc) {
  cout << "====> Name " << iName << " -- " << iFunc << " -- " << iH << endl;
  TH1F *lH = (TH1F*) iH->Clone(iName.c_str());
  lH->SetFillStyle(0);
  int lMergeBin = iH->GetXaxis()->FindBin(iMergePoint);
  double lVal  = iH->GetBinContent(lMergeBin);
  //iFunc->Scale(lVal/iFunc->GetBinContent(lMergeBin));
  iFunc->Scale( (iH->Integral(lMergeBin, iH->GetXaxis()->FindBin(1500))) / (iFunc->Integral(lMergeBin, iFunc->GetXaxis()->FindBin(1500)) )); // felix - last fit bin = 1500; this approach seems to work much better
  for(int i0 = 0;         i0 < lMergeBin;         i0++) lH->SetBinContent(i0,iH->GetBinContent(i0));
  for(int i0 = lMergeBin; i0 < iH->GetNbinsX()+1; i0++) lH->SetBinContent(i0,iFunc->GetBinContent(iFunc->GetXaxis()->FindBin(lH->GetXaxis()->GetBinCenter(i0))));
  lH->SetName(iName.c_str());
  return lH;
}
void storePUHisto(TString inputfilepath, TString outputfilepath, TString histoname = "MCPileUpHisto"){

  TFile *inputFile = TFile::Open(inputfilepath.Data());
  //This should have always the same name
  TH1F *histo = (TH1F*)inputFile->Get("diphotonSignalMCAnalyzer/fpu_n_BeforeCuts");
  //set the name according to the name provided in cfg for crab
  histo->SetName(histoname.Data());
  histo->SetBins(80,0,80);
  //Open a new file to store this histo to
  TFile *outputFile = new TFile(outputfilepath.Data(),"recreate");
  outputFile->cd();
  histo->Write();
  outputFile->cd();
  outputFile->Close();
}
Ejemplo n.º 8
0
// rebin the spectra
TH1F *rebin_yaxian(TH1F *h, char *histName)
{
  TH1F *hRebin = new TH1F(Form("%s_rebin",h->GetName()),Form("rebin %s",h->GetTitle()),nbins_jetPtBin,boundaries_jetPtBin);
  for (int i=1;i<=h->GetNbinsX();i++)
    {
      double val=h->GetBinContent(i);
      double valErr=h->GetBinError(i);
      int binNum = hRebin->FindBin(h->GetBinCenter(i));
      double val1 = hRebin->GetBinContent(binNum);
      double valErr1 = hRebin->GetBinError(binNum);
      hRebin->SetBinContent(binNum,val+val1);
      hRebin->SetBinError(binNum,sqrt(valErr1*valErr1+valErr*valErr));
    }
  cleanup(hRebin);
  hRebin->SetName(histName);
  return hRebin;
}
Ejemplo n.º 9
0
std::vector<GaussFitInfo> saveGaussians(TH2F* hp, TList* l, TString savedir)
{
  // Each xbin of the TH2F can be viewed as a 1D histogram of the y info.
  // Fit the histograms in each xbin with a gaussian and save them into a tlist. 
  // Save the histograms as png files as well.

  // Get the title info from the mother histogram.
  TString title = hp->GetTitle();

  // This is only used to align the statboxes.
  DiMuPlottingSystem* dps = new DiMuPlottingSystem();

  // Do the fitting and gather the histos into the tlist.
  std::vector<GaussFitInfo> gfis = std::vector<GaussFitInfo>();
  gfis = dps->plotVarVsGaussFit(hp, l, 1);

  TCanvas* c = new TCanvas();
  c->SetGridx(kTRUE);
  c->SetGridy(kTRUE);

  // Iterate through the list and save the histos as pictures. 
  TIter next(l);
  TObject* obj = 0;
  int i = 0;
  int total = 0;
  while( (obj = next()) )
    {
      TH1F* h = (TH1F*) obj;
      h->SetName(Form("%s_%d_%s", title.Data(), i, hp->GetName()));
      c->cd();
      h->Draw("");
      total+=h->GetEntries();
      std::cout << "    " << i << " num: "<< h->GetEntries() << std::endl;
      dps->arrangeStatBox(c);
      c->Print(savedir+Form("%s_%s_gauss_bins_%d.png", hp->GetName(), title.Data(), i));
      //        c->Print(savedir+Form("%s_%s_gauss_bins.gif+500", hp->GetName(), title.Data()));
      i++;
    }
  c->cd();
  //    c->Print(savedir+Form("%s_%s_gauss_bins.gif++", hp->GetName(), title.Data()));
  std::cout << "nentries total: " << total << std::endl;

  delete c;
  //    delete dps;
  return gfis;
}
Ejemplo n.º 10
0
void plotMttResolution() {

  setTDRStyle();

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

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

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

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

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

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

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

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

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

  c->Print("mtt_resolution.pdf");
}
Ejemplo n.º 11
0
void CreateFile(const char *fname)
{
   TFile *example = (TFile*)gROOT->ProcessLineFast("hsimple(1)");
   if (!example) return;
   TH1F *hpx = (TH1F*)example->Get("hpx");
   hpx->SetName("hpx1");
   TFile::Cp(example->GetName(), fname);
   TFile *file = TFile::Open(fname, "UPDATE");
   file->mkdir("folder")->cd();
   hpx->Write();
   file->Close();
   example->Close();
   TString sname(fname);
   if (sname.Contains("000")) {
      TFile::Cp(fname, "original.root");
      TFile::Open("original.root");
   }
}
Ejemplo n.º 12
0
void efficiencies(){
  //TFile * f_ttbar= new TFile("ttbar-output-2014-06-22.root");
  TFile * f_ttbar= new TFile("/afs/cern.ch/work/m/mcitron/public/TTBAR/140622/ttbar_output.root");
  TFile * f_out= new TFile("./effTest.root","recreate");
  TTree * tree_ttbar = f_ttbar->Get("demo/L1Tree");
  std::vector<TString> jetnum;
  jetnum.push_back("0");
  jetnum.push_back("1");
  jetnum.push_back("2");
  jetnum.push_back("3");
  std::vector<TString> jetType;
  jetType.push_back("5400_calib_nopus");
  jetType.push_back("5450_calib_nopus");
  jetType.push_back("5450_calib_donut");
  jetType.push_back("5400_calib_donut");
  jetType.push_back("5400_calib_global");
  //jetType.push_back("calib_gct");
  TString bins = "(1000,0,1000)";
  for (iNum = jetnum.begin();iNum != jetnum.end(); iNum++)
  {
    TDirectory * jnum = f_out->mkdir("jetNumber_"+*iNum);
    jnum->cd();
    TCut genptcut = "jetPt_ak4_gen["+*iNum+"]>50";
    tree_ttbar->Draw("jetPt_ak4_gen["+*iNum+"]>>overall_"+*iNum,genptcut,"");
    TH1F *overall = (TH1F*)gPad->GetPrimitive("overall_"+*iNum);
    double overallNorm = overall->GetEntries();
    for (iType = jetType.begin();iType != jetType.end(); iType++)
    {

      TCut matchedcut = "jetMatchedPt_"+*iType+"["+*iNum+"]!=-1";


      tree_ttbar->Draw("jetPt_"+*iType+"["+*iNum+"]>>"+*iType+"_"+*iNum+bins,genptcut&&matchedcut,"");
      TH1F *test = (TH1F*)gPad->GetPrimitive(*iType+"_"+*iNum);
      test->Write();
      test->SetName(*iType+"_"+*iNum+"_"+"Efficiency");

      TH1F* cumuplot = makeCumu(test,overallNorm);
      cumuplot->Write();
    }
  }
  f_out->Close();
  return;
}
//Rebin the histogram
TH1F* rebin(TH1F* iH,int iNBins,double *iAxis) { 
  std::string lTmp = "tmp"; //Added to avoid Root output errors
  TH1F *lH = new TH1F(lTmp.c_str(),lTmp.c_str(),iNBins,iAxis);
  for(int i0 = 0; i0 < iH->GetNbinsX()+1; i0++) {
    int    lNBin = lH->GetXaxis()->FindBin(iH->GetXaxis()->GetBinCenter(i0));
    double lVal  = iH->GetBinContent(i0);
    double lErr  = iH->GetBinError  (i0);
    double lOldV = lH->GetBinContent(lNBin);
    double lOldE = lH->GetBinError  (lNBin);
    lH->SetBinContent(lNBin,lVal+lOldV);
    lH->SetBinError  (lNBin,sqrt(lOldE*lOldE+lErr*lErr));
  }
  std::string lName2 = iH->GetName();
  std::string fine_binning = "_fine_binning";
  lName2.replace(lName2.find(fine_binning),fine_binning.length(),"");
  lH->SetName (lName2.c_str());
  lH->SetTitle(lName2.c_str());
  delete iH;
  return lH;
}
void billtw(Int_t compress) {
   //write N histograms to a Tree
   timer.Start();
   TFile f("billt.root","recreate","bill benchmark with trees",compress);
   TH1F *h = new TH1F("h","h",1000,-3,3);
   h->FillRandom("gaus",50000);
   TTree *T = new TTree("T","test bill");
   T->Branch("event","TH1F",&h,64000,0);
   for (Int_t i=0;i<N;i++) {
      char name[20];
      sprintf(name,"h%d",i);
      h->SetName(name);
      h->Fill(2*gRandom->Rndm());
      T->Fill();
   }
   T->Write();
   delete T;
   timer.Stop();
   printf("billtw%d : RT=%7.3f s, Cpu=%7.3f s, File size= %9d bytes, CX= %g\n",compress,timer.RealTime(),timer.CpuTime(),
                    (Int_t)f.GetBytesWritten(),f.GetCompressionFactor());
}
Ejemplo n.º 15
0
TH1F* Interpolate(double massLow, TH1F* low, double massHigh, TH1F* high, double massInt){

  if (low->GetNbinsX()!=high->GetNbinsX()) std::cout << "Cannot interpolate differently binned histograms" << std::endl;
  assert(low->GetNbinsX()==high->GetNbinsX());

  TH1F *interp = (TH1F*)low->Clone();
  for (int i=0; i<interp->GetNbinsX(); i++){
    double OutLow = low->GetBinContent(i+1);
    double OutHigh = high->GetBinContent(i+1);
    double OutInt = (OutHigh*(massInt-massLow)-OutLow*(massInt-massHigh))/(massHigh-massLow);
    interp->SetBinContent(i+1,OutInt);
  }

  std::string name = low->GetName();
  std::string strLow = Form("%3.1f",massLow);
  std::string strInt = Form("%3.1f",massInt);
  int ind = name.rfind(strLow);
  name.replace(ind-6,11,strInt);
  interp->SetName(name.c_str());

  return interp;
   
}
Ejemplo n.º 16
0
void Unfold2(int algo= 3,bool useSpectraFromFile=0, bool useMatrixFromFile=0, int doToy = 0, int isMC = 0,char *spectraFileName = (char*)"pbpb_spectra_akPu3PF.root",double recoJetPtCut = 60.,double trackMaxPtCut = 0, int nBayesianIter = 4, int doBjets=1, int doTrigEffCorr=1) // algo 2 =akpu2 ; 3 =akpu3 ; 4 =akpu4 ;1 = icpu5
{
  
  gStyle->SetErrorX(0.);
  gStyle->SetPaintTextFormat("3.2f");
  gStyle->SetOptLogz(1);
  gStyle->SetPadRightMargin(0.13);	
  gStyle->SetOptTitle(0);
  gStyle->SetOptStat(0);


  TH1::SetDefaultSumw2();
  TH2::SetDefaultSumw2();
  
  // input files
  char *fileNamePP_mc = NULL;
  char *fileNamePbPb_mc = NULL;
  char *fileNamePP_data = NULL;
  char *fileNamePbPb_data = NULL;
  

  // pp file needs replacing
  if(doBjets)fileNamePP_data = (char*)"~/Work/bTagging/outputTowardsFinal/NewFormatV5_bFractionMCTemplate_pppp1_SSVHEat2.0FixCL0_bin_0_40_eta_0_2.root";
  //else fileNamePP_data = (char*)"../spectra/rawIncSpectra_MB_fixedBinSize_v4.root";
  else fileNamePP_data = (char*)"../spectra/rawIncSpectra_MB_varBinSize_v4.root";
  //if(doBjets)fileNamePbPb_data = (char*)"~/Work/bTagging/outputTowardsFinal/AltBinningV6_bFractionMCTemplate_ppPbPb1_SSVHEat2.0FixCL0_bin_0_40_eta_0_2.root";
  if(doBjets)fileNamePbPb_data = (char*)"~/Work/bTagging/outputTowardsFinal/bFractionMCTemplate_ppPbPb1_SSVHEat2.0FixCL0_bin_0_40_eta_0_2_binomErrors_jet55_wideBin_v2.root";
  //else fileNamePbPb_data = (char*)"../spectra/rawIncSpectra_MB_fixedBinSize_v4.root";
  else fileNamePbPb_data = (char*)"../spectra/rawIncSpectra_MB_varBinSize_v4.root";
  if(doBjets) fileNamePP_mc = (char*)"~/Work/bTagging/histos/ppMC_ppReco_ak3PF_BjetTrig_noIPupperCut.root";
  else fileNamePP_mc = (char*)"~/Work/bTagging/histos/ppMC_ppReco_ak3PF_QCDjetTrig_noIPupperCut.root";
  if(doBjets)fileNamePbPb_mc = (char*) "~/Work/bTagging/histos/PbPbBMC_pt30by3_ipHICalibCentWeight_noTrig.root";
  else fileNamePbPb_mc = (char*) "~/Work/bTagging/histos/PbPbQCDMC_pt30by3_ipHICalibCentWeight_noTrig.root";


  // grab ntuples
  TFile *infPbPb_mc = new TFile(fileNamePbPb_mc);
  TFile *infPP_mc = new TFile(fileNamePP_mc);
  

  string bJetString = "Inc";
  if(doBjets) bJetString = "bJets";

  // Output file
  TFile *pbpb_Unfo;
  if (isMC) pbpb_Unfo = new TFile(Form("pbpb_Unfo_%s_MC_v2.root",algoName[algo]),"RECREATE");
  else pbpb_Unfo  = new TFile(Form("pbpb_Unfo_%s_jtpt%.0f_%s_v4.root",algoName[algo],recoJetPtCut,bJetString.c_str()),"RECREATE");

  // Histograms used by RooUnfold
  UnfoldingHistos *uhist[nbins_cent+1];
		
  // Initialize Histograms   
	
  for (int i=0;i<=nbins_cent;i++) uhist[i] = new UnfoldingHistos(i);
	
  // Initialize reweighting functions
  /*
  TCut dataSelection;
  TCut dataSelectionPP;
  TCut TriggerSelectionPP;
  TCut TriggerSelectionPbPb80;

  if(doBjets)dataSelection = "weight*(abs(refparton_flavorForB)==5&&abs(jteta)<2)";
  else dataSelection = "weight*(abs(jteta)<2)";
  */

  if (isMC) cout<<"This is a MC closure test"<<endl;
  else cout<< "This is a data analysis"<<endl;    		     
	     	
  // Setup jet data branches, basically the jet tree branches are assigned to this object when we loop over the events
	
  JetDataPbPb *dataPbPb   = new JetDataPbPb(fileNamePbPb_mc,(char*)"nt"); // PbPb data	
  JetDataPP *dataPP = new JetDataPP(fileNamePP_mc,(char*)"nt");	// pp data
	
  TFile *fSpectra(0);		
  if (useSpectraFromFile||useMatrixFromFile){
    fSpectra = new TFile(spectraFileName,"read");
  }
  
  // Come back to the output file dir
  pbpb_Unfo->cd();

  cout <<"MC..."<<endl;	
  
  TH1F *hCent = new TH1F("hCent","",nbins_cent,boundaries_cent);
 

  // if you change the binning you have to change these, too
  // inclusive trig eff
  /*
    float trigEffInc[6]={0.777265,
			 0.95765,
			 0.998357,
			 0.999941,
			 1.,
			 1.};
  */

    // b-jet trig eff
    /*
    float trigEffbJet[6]={0.660276,
		      0.908997,
		      0.980793,
		      0.998767,
		      0.999442,
		      1.};
    */



 
		
  // Fill PbPb MC   
  if (!useMatrixFromFile) {
    for (Long64_t jentry2=0; jentry2<dataPbPb->tJet->GetEntries();jentry2++) {
      dataPbPb->tJet->GetEntry(jentry2);
      
      // change when we switch to centrality binning
      int cBin = 0;
            
      if ( dataPbPb->refpt  < 0. ) continue;
      if ( dataPbPb->jteta  > 2. || dataPbPb->jteta < -2. ) continue;
      if ( dataPbPb->refpt<0) dataPbPb->refpt=0;
      if (doBjets && fabs(dataPbPb->refparton_flavorForB)!=5) continue;
      //if (doBjets&& dataPbPb->discr_ssvHighEff<2) continue;
      if (doBjets && dataPbPb->jtptB < recoJetPtCut) continue;
      if (!doBjets && dataPbPb->jtptA < recoJetPtCut) continue;
      //if (!doTrigEffCorr && dataPbPb->isTrig <1) continue;
      if ( dataPbPb->isTrig <1) continue;
      
      //if(!doBjets)if(dataPbPb->refpt < 50 && dataPbPb->jtptA>120) continue;
      //if(doBjets)if(dataPbPb->refpt < 50 && dataPbPb->jtptB>120) continue;

      float weight = dataPbPb->weight;

      if(doTrigEffCorr){
	for(int iBin = 0; iBin<nbins_rec; iBin++){
	  float myJtPt = 0.;
	  if(doBjets) myJtPt = dataPbPb->jtptB;
	  else myJtPt = dataPbPb->jtptA;
	  if(myJtPt > boundaries_rec[iBin] && myJtPt < boundaries_rec[iBin+1]){
	    if(doBjets) weight/= trigEffbJet[iBin];
	    else weight/= trigEffInc[iBin];
	  }							  
	}
      }
      if (!isMC||jentry2 % 2 == 1) {
	if(doBjets)uhist[cBin]-> hMatrix->Fill(dataPbPb->refpt,dataPbPb->jtptB,weight);
	else uhist[cBin]-> hMatrix->Fill(dataPbPb->refpt,dataPbPb->jtptA,weight);
      }	  
      if (jentry2 % 2 == 0) {
	uhist[cBin]-> hGen->Fill(dataPbPb->refpt,weight);   
	if(doBjets)uhist[cBin]-> hMeas->Fill(dataPbPb->jtptB,weight);  	 
	else uhist[cBin]-> hMeas->Fill(dataPbPb->jtptA,weight);  	 
	//uhist[cBin]-> hMeasJECSys->Fill(dataPbPb->jtpt*(1.+0.02/nbins_cent*(nbins_cent-i)),weight); 
	// FIXME!!!!!!  i is supposed to be a loop over centrality !!!!
	if(doBjets)uhist[cBin]-> hMeasJECSys->Fill(dataPbPb->jtptB*(1.+0.02/nbins_cent*(nbins_cent-0)),weight); 
	else uhist[cBin]-> hMeasJECSys->Fill(dataPbPb->jtptA*(1.+0.02/nbins_cent*(nbins_cent-0)),weight); 
      }
    }

    //pp will just fill the last index of the centrality array

    // fill pp MC
    for (Long64_t jentry2=0; jentry2<dataPP->tJet->GetEntries();jentry2++) {
      dataPP->tJet->GetEntry(jentry2);
      
      if ( dataPP->refpt<0) continue;
      if ( dataPP->jteta  > 2. || dataPP->jteta < -2. ) continue;
      if ( dataPP->refpt<0) dataPP->refpt=0;
      if ( doBjets && fabs(dataPP->refparton_flavorForB)!=5) continue;
      //if ( doBjets && dataPP->discr_ssvHighEff<2) continue;
      if ( dataPP->jtpt < recoJetPtCut) continue;
      
      if (!isMC||jentry2 % 2 == 1) {
	uhist[nbins_cent]-> hMatrix->Fill(dataPP->refpt,dataPP->jtpt,dataPP->weight);
      }	  
      if (jentry2 % 2 == 0) {
	uhist[nbins_cent]-> hGen->Fill(dataPP->refpt,dataPP->weight);   
	uhist[nbins_cent]-> hMeas->Fill(dataPP->jtpt,dataPP->weight); 
      }           
    }
  }
  /*
  for (int i=0;i<=nbins_cent;i++){
    for (int x=1;x<=uhist[i]->hMatrix->GetNbinsX();x++) {
	float binContent = uhist[i]->hGen->GetBinContent(x);
	float binError = uhist[i]->hGen->GetBinError(x);
	float binWidth =  uhist[i]->hGen->GetXaxis()->GetBinWidth(x);
	uhist[i]->hGen->SetBinContent(x,binContent/binWidth);
	uhist[i]->hGen->SetBinError(x,binError/binWidth);
    }
  }

<<<<<<< HEAD
  for (int i=0;i<=nbins_cent;i++){
    for (int x=1;x<=uhist[i]->hMatrix->GetNbinsX();x++) {
	float binContent = uhist[i]->hMeas->GetBinContent(x);
	float binError = uhist[i]->hMeas->GetBinError(x);
	float binWidth =  uhist[i]->hMeas->GetXaxis()->GetBinWidth(x);
	uhist[i]->hMeas->SetBinContent(x,binContent/binWidth);
	uhist[i]->hMeas->SetBinError(x,binError/binWidth);
    }
  }

  for (int i=0;i<=nbins_cent;i++){
    for (int x=1;x<=uhist[i]->hMatrix->GetNbinsX();x++) {
      for (int y=1;y<=uhist[i]->hMatrix->GetNbinsY();y++) {
	float binContent = uhist[i]->hMatrix->GetBinContent(x,y);
	float binError = uhist[i]->hMatrix->GetBinError(x,y);
	float binWidth2 =  uhist[i]->hMatrix->GetXaxis()->GetBinWidth(x)*uhist[i]->hMatrix->GetYaxis()->GetBinWidth(y);
	uhist[i]->hMatrix->SetBinContent(x,y,binContent/binWidth2);
	uhist[i]->hMatrix->SetBinError(x,y,binError/binWidth2);
      }      
    }
  }	
  */


  if (isMC==0) {
    // Use measured histogram from Matt & Kurt's file
	   
    // PbPb file:

    TFile *infMatt = new TFile(fileNamePbPb_data);
    TH1F *hMattPbPb = NULL;
    TH1F *hTagEffPbPb = NULL;

    if(doBjets){
      hMattPbPb = (TH1F*) infMatt->Get("hRawBData");
      hTagEffPbPb = (TH1F*) infMatt->Get("hBEfficiencyMC");
    }
    else hMattPbPb = (TH1F*) infMatt->Get("hPbPb");
    //divideBinWidth(hMattPbPb);
           
    // Need to match the binning carefully, please double check whenever you change the binning
    for (int i=1;i<=hMattPbPb->GetNbinsX();i++)
      {
     	float binContent = hMattPbPb->GetBinContent(i);  
	float binError = hMattPbPb->GetBinError(i); 

	if(doBjets){
	  float tagEff =hTagEffPbPb->GetBinContent(i);
	  float tagEffErr =     hTagEffPbPb->GetBinError(i);   
	  
	  if(tagEff>0){
	    // careful of the order here!
	    binError=binContent/tagEff *sqrt(tagEffErr*tagEffErr/tagEff/tagEff + binError*binError/binContent/binContent);
	    binContent /= tagEff;
	  }
	  else cout<<" TAGEFF = 0"<<endl;	  
	}

	float binCenter = hMattPbPb->GetBinCenter(i);  
	if(binCenter - hMattPbPb->GetBinWidth(i)/2.  < recoJetPtCut) continue;
	
	int ibin=0;
	
	for(ibin=1;ibin<=uhist[0]->hMeas->GetNbinsX();ibin++){
	  float testLowEdge = uhist[0]->hMeas->GetBinLowEdge(ibin);
	  float testBinWidth = uhist[0]->hMeas->GetBinWidth(ibin);
	  if(binCenter>testLowEdge && binCenter < testLowEdge+testBinWidth) break;
	}
	
	
	if(doTrigEffCorr){
	  float trigEff = 0;
	  if(doBjets) trigEff = trigEffbJet[ibin-1];
	  else  trigEff = trigEffInc[ibin-1];

	  cout<<" binCenter = "<<binCenter<<" trigEff "<<trigEff<<endl;

	  if(trigEff>0){
	    // careful of the order here!
	    binContent /= trigEff;
	    binError /= trigEff;
	  }
	  else cout<<" TRIGEFF = 0"<<endl;	  
	}


     
	uhist[0]->hMeas->SetBinContent(ibin,binContent);  
	uhist[0]->hMeas->SetBinError(ibin,binError);  

      }

    // pp file:
    TFile *infMattPP = new TFile(fileNamePP_data);
    TH1F *hMattPP = NULL;
    TH1F *hTagEffPP = NULL;
    if(doBjets){
      hMattPP = (TH1F*) infMattPP->Get("hRawBData");
      hTagEffPP = (TH1F*) infMattPP->Get("hBEfficiencyMC");
    }
    else hMattPP = (TH1F*) infMattPP->Get("hpp");
    //divideBinWidth(hMattPP);	   
    for (int i=1;i<=hMattPP->GetNbinsX();i++)
      {
      	float binContent = hMattPP->GetBinContent(i);  
	float binError = hMattPP->GetBinError(i);  
	
	if(doBjets){
	  float tagEff =hTagEffPP->GetBinContent(i);
	  float tagEffErr =     hTagEffPP->GetBinError(i);   
	  if(tagEff>0){
	    // careful of the order here!
	    binError=binContent/tagEff *sqrt(tagEffErr*tagEffErr/tagEff/tagEff + binError*binError/binContent/binContent);
	    binContent /= tagEff;
	  }
	  else cout<<" TAGEFF = 0"<<endl;	  
	}
	
     	float binCenter = hMattPP->GetBinCenter(i);  
	if(binCenter - hMattPP->GetBinWidth(i)/2.  < recoJetPtCut) continue;

	int ibin=0;

	for(ibin=1;ibin<=uhist[nbins_cent]->hMeas->GetNbinsX();ibin++){
	  float testLowEdge = uhist[nbins_cent]->hMeas->GetBinLowEdge(ibin);
	  float testBinWidth = uhist[nbins_cent]->hMeas->GetBinWidth(ibin);
	  if(binCenter>testLowEdge && binCenter < testLowEdge+testBinWidth) break;
	}
	uhist[nbins_cent]->hMeas->SetBinContent(ibin,binContent);  
	uhist[nbins_cent]->hMeas->SetBinError(ibin,binError);  

    
	/*
	cout<<" i "<<i<<endl;
	int newBin = i+uhist[nbins_cent]->hMeas->FindBin(61)-1;

	cout<<" newBin "<<newBin<<endl;
	cout<<"hMattPP->GetBinCenter(i) "<<hMattPP->GetBinCenter(i)<<endl;
	cout<<"uhist[nbins_cent]->hMeas->GetBinCenter(newBin) "<<uhist[nbins_cent]->hMeas->GetBinCenter(newBin)<<endl;
	*/
      }

  }



   //=========================================Response Matrix========================================================= 

  cout <<"Response Matrix..."<<endl;
	
  TCanvas * cMatrix = new TCanvas("cMatrix","Matrix",800,400);
  cMatrix->Divide(2,1);

  for (int i=0;i<=nbins_cent;i++){
    cMatrix->cd(i+1);
    if (!useMatrixFromFile) {
      TF1 *f = new TF1("f","[0]*pow(x+[2],[1])");
      f->SetParameters(1e10,-8.8,40);
      for (int y=1;y<=uhist[i]->hMatrix->GetNbinsY();y++) {
	double sum=0;
	for (int x=1;x<=uhist[i]->hMatrix->GetNbinsX();x++) {
	  if (uhist[i]->hMatrix->GetBinContent(x,y)<=1*uhist[i]->hMatrix->GetBinError(x,y)) {
	    uhist[i]->hMatrix->SetBinContent(x,y,0);
	    uhist[i]->hMatrix->SetBinError(x,y,0);
	  }
	  sum+=uhist[i]->hMatrix->GetBinContent(x,y);
	}
				
	for (int x=1;x<=uhist[i]->hMatrix->GetNbinsX();x++) {	   
	  double ratio = 1;
	  uhist[i]->hMatrix->SetBinContent(x,y,uhist[i]->hMatrix->GetBinContent(x,y)*ratio);
	  uhist[i]->hMatrix->SetBinError(x,y,uhist[i]->hMatrix->GetBinError(x,y)*ratio);
	}
      }
    }
    uhist[i]->hResponse = (TH2F*)uhist[i]->hMatrix->Clone(Form("hResponse_cent%d",i));

    for (int y=1;y<=uhist[i]->hResponse->GetNbinsY();y++) {
      double sum=0;
      for (int x=1;x<=uhist[i]->hResponse->GetNbinsX();x++) {
	if (uhist[i]->hResponse->GetBinContent(x,y)<=0*uhist[i]->hResponse->GetBinError(x,y)) {
	  uhist[i]->hResponse->SetBinContent(x,y,0);
	  uhist[i]->hResponse->SetBinError(x,y,0);
	}
	sum+=uhist[i]->hResponse->GetBinContent(x,y);
      }
			
      for (int x=1;x<=uhist[i]->hResponse->GetNbinsX();x++) {  	
	if (sum==0) continue;
	double ratio = uhist[i]->hMeas->GetBinContent(y)/sum;
	if (uhist[i]->hMeas->GetBinContent(y)==0) ratio = 1e-100/sum;
      }
    }
		
    TH1F *hProj = (TH1F*)uhist[i]->hResponse->ProjectionY(Form("hProj_cent%d",i));
    
    for (int y=1;y<=uhist[i]->hResponse->GetNbinsY();y++) {
      for (int x=1;x<=uhist[i]->hResponse->GetNbinsX();x++) {  	
	double sum=hProj->GetBinContent(y);
	cout <<y<<" "<<x<<" "<<sum<<endl;
	if (sum==0) continue;
	double ratio = uhist[i]->hMeas->GetBinContent(y)/sum;
	if (uhist[i]->hMeas->GetBinContent(y)==0) ratio = 1e-100/sum;
        uhist[i]->hResponse->SetBinContent(x,y,uhist[i]->hResponse->GetBinContent(x,y)*ratio);
	uhist[i]->hResponse->SetBinError(x,y,uhist[i]->hResponse->GetBinError(x,y)*ratio);
      }
    }

    uhist[i]->hResponseNorm = (TH2F*)uhist[i]->hMatrix->Clone(Form("hResponseNorm_cent%d",i));
    for (int x=1;x<=uhist[i]->hResponseNorm->GetNbinsX();x++) {
      double sum=0;
      for (int y=1;y<=uhist[i]->hResponseNorm->GetNbinsY();y++) {
	if (uhist[i]->hResponseNorm->GetBinContent(x,y)<=0*uhist[i]->hResponseNorm->GetBinError(x,y)) {
	  uhist[i]->hResponseNorm->SetBinContent(x,y,0);
	  uhist[i]->hResponseNorm->SetBinError(x,y,0);
	}
	sum+=uhist[i]->hResponseNorm->GetBinContent(x,y);
      }
			
      for (int y=1;y<=uhist[i]->hResponseNorm->GetNbinsY();y++) {  	
	if (sum==0) continue;
	double ratio = 1./sum;
	uhist[i]->hResponseNorm->SetBinContent(x,y,uhist[i]->hResponseNorm->GetBinContent(x,y)*ratio);
	uhist[i]->hResponseNorm->SetBinError(x,y,uhist[i]->hResponseNorm->GetBinError(x,y)*ratio);
      }
    }
		
    uhist[i]->hResponse->Draw("colz");
		
    if (!useMatrixFromFile) uhist[i]->hMatrixFit = uhist[i]->hMatrix;
    uhist[i]->hMatrixFit->SetName(Form("hMatrixFit_cent%d",i));
  }

  pbpb_Unfo->cd();
	
  cout << "==================================== UNFOLD ===================================" << endl;
	
  //char chmet[100]; 
	
  // ======================= Reconstructed pp and PbPb spectra =========================================================
  TCanvas * cPbPb = new TCanvas("cPbPb","Comparison",1200,600);
  cPbPb->Divide(2,1); 
  cPbPb->cd(1);
	
  TH1F *hRecoBW[nbins_cent+1], *hRecoBinByBinBW[nbins_cent+1], *hMeasBW[nbins_cent+1], *hGenBW[nbins_cent+1];


  TCanvas * cPbPbMeas = new TCanvas("cPbPbMeas","Measurement",1200,600);
  cPbPbMeas->Divide(2,1); 
  cPbPbMeas->cd(1);
	

  for (int i=0;i<=nbins_cent;i++) {
    cPbPb->cd(i+1)->SetLogy();   
    // Do Bin-by-bin
    TH1F *hBinByBinCorRaw = (TH1F*)uhist[i]->hResponse->ProjectionY(); 
    TH1F *hMCGen           = (TH1F*)uhist[i]->hResponse->ProjectionX(); // gen
    hBinByBinCorRaw->Divide(hMCGen);
    TF1 *f = new TF1("f","[0]+[1]*x");
    hBinByBinCorRaw->Fit("f","LL ","",90,300);
    TH1F* hBinByBinCor = (TH1F*)hBinByBinCorRaw->Clone();//functionHist(f,hBinByBinCorRaw,Form("hBinByBinCor_cent%d",i));
    uhist[i]->hRecoBinByBin = (TH1F*) uhist[i]->hMeas->Clone(Form("hRecoBinByBin_cent%d",i));
    uhist[i]->hRecoBinByBin->Divide(hBinByBinCor);
		
    // Do unfolding
    //if (isMC) uhist[i]->hMeas = (TH1F*)uhist[i]->hMatrix->ProjectionY()->Clone(Form("hMeas_cent%d",i));
    prior myPrior(uhist[i]->hMatrixFit,uhist[i]->hMeas,0);
    myPrior.unfold(uhist[i]->hMeas,1);
    TH1F *hPrior;//=(TH1F*) functionHist(fPow,uhist[i]->hMeas,Form("hPrior_cent%d",i));
//    hPrior = (TH1F*)uhist[i]->hGen->Clone("hPrior");
//    hPrior = (TH1F*)uhist[i]->hMeas->Clone(Form("hPrior_cent%d",i));
    hPrior=(TH1F*)hMCGen->Clone("hPrior");
    removeZero(hPrior);
    TH1F *hReweighted = (TH1F*)(TH1F*)uhist[i]->hResponse->ProjectionY(Form("hReweighted_cent%d",i));
		
    bayesianUnfold myUnfoldingJECSys(uhist[i]->hMatrixFit,hPrior,0);
    myUnfoldingJECSys.unfold(uhist[i]->hMeasJECSys,nBayesianIter);
    bayesianUnfold myUnfoldingSmearSys(uhist[i]->hMatrixFit,hPrior,0);
    myUnfoldingSmearSys.unfold(uhist[i]->hMeasSmearSys,nBayesianIter);
    bayesianUnfold myUnfolding(uhist[i]->hMatrixFit,myPrior.hPrior,0);
    myUnfolding.unfold(uhist[i]->hMeas,nBayesianIter);
    cout <<"Unfolding bin "<<i<<endl;

    delete hBinByBinCorRaw;
    delete hMCGen;

    // Iteration Systematics
    for (int j=2;j<=7;j++)
      {

	bayesianUnfold myUnfoldingSys(uhist[i]->hMatrixFit,hPrior,0);
	myUnfoldingSys.unfold(uhist[i]->hMeas,j);
	uhist[i]->hRecoIterSys[j]  = (TH1F*) myUnfoldingSys.hPrior->Clone(Form("hRecoRAA_IterSys%d_cent%d",j,i));
      }
    
    
    uhist[i]->hReco         = (TH1F*) uhist[i]->hRecoIterSys[nBayesianIter]->Clone(Form("Unfolded_cent%i",i));
    uhist[i]->hRecoJECSys   = (TH1F*) myUnfoldingJECSys.hPrior->Clone(Form("UnfoldedJeCSys_cent%i",i));
    uhist[i]->hRecoSmearSys   = (TH1F*) myUnfoldingSmearSys.hPrior->Clone(Form("UnfoldedSmearSys_cent%i",i));
    uhist[i]->hRecoBinByBin->SetName(Form("UnfoldedBinByBin_cent%i",i));
    
    if (doToy) {
      TCanvas *cToy = new TCanvas("cToy","toy",600,600);
      cToy->cd();
      int nExp=1000;
      TH1F *hTmp[nbins_truth+1];
      TH1F *hTmp2[nbins_truth+1];
      for (int j=1;j<=nbins_truth;j++) {
	hTmp[j] = new TH1F(Form("hTmp%d",j),"",200,0,10.+uhist[i]->hReco->GetBinContent(j)*2);
	hTmp2[j] = new TH1F(Form("hTmp2%d",j),"",200,0,10.+uhist[i]->hRecoBinByBin->GetBinContent(j)*2);
      }
      for (int exp =0; exp<nExp; exp++) {
	TH1F *hToy = (TH1F*)uhist[i]->hMeas->Clone();   
	TH2F *hMatrixToy = (TH2F*)uhist[i]->hMatrixFit->Clone();
	hToy->SetName("hToy");
	if (exp%100==0) cout <<"Pseudo-experiment "<<exp<<endl;
	for (int j=1;j<=hToy->GetNbinsX();j++) {
	  double value = gRandom->Poisson(uhist[i]->hMeas->GetBinContent(j));
	  hToy->SetBinContent(j,value);
	}
				
	for (int j=1;j<=hMatrixToy->GetNbinsX();j++) {
	  for (int k=1;k<=hMatrixToy->GetNbinsY();k++) {
	    double value = gRandom->Gaus(uhist[i]->hMatrixFit->GetBinContent(j,k),uhist[i]->hMatrixFit->GetBinError(j,k));
	    hMatrixToy->SetBinContent(j,k,value);
	  }
	}

	prior myPriorToy(hMatrixToy,hToy,0.0);
	myPriorToy.unfold(hToy,1);
	bayesianUnfold myUnfoldingToy(hMatrixToy,myPriorToy.hPrior,0.0);
	myUnfoldingToy.unfold(hToy,nBayesianIter);
	TH1F *hRecoTmp = (TH1F*) myUnfoldingToy.hPrior->Clone();
				
	for (int j=1;j<=hRecoTmp->GetNbinsX();j++) {
	  hTmp[j]->Fill(hRecoTmp->GetBinContent(j));
	}
	delete hToy;
	delete hRecoTmp;
	delete hMatrixToy;
      }
      TF1 *fGaus = new TF1("fGaus","[0]*TMath::Gaus(x,[1],[2])");
      for (int j=1;j<=nbins_truth;j++)
	{

	  f->SetParameters(hTmp[j]->GetMaximum(),hTmp[j]->GetMean(),hTmp[j]->GetRMS());
				
	  if (hTmp[j]->GetMean()>0) {
	    hTmp[j]->Fit(fGaus,"LL Q ");
	    hTmp[j]->Fit(fGaus,"LL Q ");
	    uhist[i]->hReco->SetBinError(j,f->GetParameter(2));
	  }	       
	  f->SetParameters(hTmp2[j]->GetMaximum(),hTmp2[j]->GetMean(),hTmp2[j]->GetRMS());
	  if (hTmp2[j]->GetMean()>0) {
	    hTmp2[j]->Fit(fGaus,"LL Q ");
	    hTmp2[j]->Fit(fGaus,"LL Q ");
	    uhist[i]->hRecoBinByBin->SetBinError(j,f->GetParameter(2));
	  }	       
	  delete hTmp[j];
	  delete hTmp2[j];
	}
      cPbPb->cd(i+1);
    }

    uhist[i]->hMeas->SetMarkerStyle(20);
    uhist[i]->hMeas->SetMarkerColor(2);
    uhist[i]->hReco->SetMarkerStyle(25);
    uhist[i]->hReco->SetName(Form("hReco_cent%d",i));
    
    uhist[i]->hReco->SetXTitle("p_{T} (GeV/c)");    
    uhist[i]->hReco->SetYTitle("Counts");    
    uhist[i]->hReco->GetXaxis()->SetNdivisions(505);
    //uhist[i]->hReco->Draw("");    
    uhist[i]->hReco->SetAxisRange(0,250,"X");
    uhist[i]->hReco->Draw("");   
     
    uhist[i]->hGen->SetLineWidth(2);
    uhist[i]->hGen->SetLineColor(2);
    //if(isMC)uhist[i]->hGen->Draw("hist same");
    //uhist[i]->hReco->Draw("same");    
    uhist[i]->hRecoBinByBin->SetMarkerStyle(28);
    uhist[i]->hRecoBinByBin->Draw("same");    

    uhist[i]->hReco->SetAxisRange(recoJetPtCut,300);
    TH1F *hReproduced = (TH1F*)myUnfolding.hReproduced->Clone(Form("hReproduced_cent%d",i));
    hReproduced->SetMarkerColor(4);
    hReproduced->SetMarkerStyle(24);
    //uhist[i]->hMeas->Draw("same");    

    hRecoBW[i] = (TH1F*)uhist[i]->hReco->Clone(Form("hReco%d",i));
    hRecoBinByBinBW[i] = (TH1F*)uhist[i]->hRecoBinByBin->Clone(Form("hRecoBinByBin%d",i));
    hMeasBW[i] = (TH1F*)uhist[i]->hMeas->Clone(Form("hMeas%d",i));
    if(isMC)hGenBW[i] = (TH1F*)uhist[i]->hGen->Clone(Form("hGen%d",i));

    divideBinWidth(hRecoBW[i]);    
    if(isMC)divideBinWidth(hGenBW[i]);    
    divideBinWidth(hRecoBinByBinBW[i]);    
    divideBinWidth(hMeasBW[i]);    

    hRecoBW[i]->Draw();
    if(isMC)hGenBW[i]->Draw("hist,same");
    hRecoBinByBinBW[i]->Draw("same");
    hMeasBW[i]->Draw("same");
    

    uhist[i]->hReco->SetTitle("Baysian Unfolded");
    uhist[i]->hRecoBinByBin->SetTitle("Bin-by-bin Unfolded");

    TLegend *leg = new TLegend(0.45,0.65,0.85,0.95);
    leg->SetBorderSize(0);
    leg->SetFillStyle(0);
    leg->AddEntry(uhist[i]->hMeas,"Measured","pl");
    leg->AddEntry(uhist[i]->hReco,"Bayesian unfolded","pl");
    leg->AddEntry(uhist[i]->hRecoBinByBin,"Bin-by-bin unfolded","pl");
    if(isMC)leg->AddEntry(uhist[i]->hGen,"Generator level truth","l");
    leg->Draw();

    cPbPbMeas->cd(i+1)->SetLogy();   
    uhist[i]->hMeas->SetAxisRange(0,240,"X");
    uhist[i]->hMeas->Draw();
    hReproduced->Draw("same");

    TLegend *leg2 = new TLegend(0.5,0.5,0.85,0.9);
    leg2->SetBorderSize(0);
    leg2->SetFillStyle(0);
    leg2->AddEntry(uhist[i]->hMeas,"Measured","pl");
    leg2->AddEntry(hReproduced,"Reproduced","pl");

    leg2->Draw();
  }	     
  
 
  pbpb_Unfo->Write();

  SysData systematics;
  TLine *line = new TLine(60,1,250,1);

  // Iteration systematics
  TCanvas *cIterSys = new TCanvas("cIterSys","cIterSys",1200,600);
  cIterSys->Divide(2,1);
  cIterSys->cd(2);
  TH1F *hRecoIterSysPP[100];
  TH1F *hRebinPP_tmp         = rebin(uhist[nbins_cent]->hReco, (char*)"hRebinPP_tmp");
  TLegend *legBayesianIterPP = myLegend(0.4,0.7,0.9,0.9);
  legBayesianIterPP->AddEntry("","PP","");
         
  for (int j=2;j<7;j++) {
    hRecoIterSysPP[j] = rebin(uhist[nbins_cent]->hRecoIterSys[j],Form("hRecoIterSysPP_IterSys%d",j));
    hRecoIterSysPP[j]->SetLineColor(colorCode[j-2]);
    hRecoIterSysPP[j]->SetMarkerColor(colorCode[j-2]);
    hRecoIterSysPP[j]->Divide(hRebinPP_tmp);
    if (j==2){
      makeHistTitle(hRecoIterSysPP[j],(char*)"",(char*)"Jet p_{T} (GeV/c)",(char*)"Ratio (Unfolded / Nominal)");
      hRecoIterSysPP[j]->SetTitleOffset(1.4,"Y");
      hRecoIterSysPP[j]->SetTitleOffset(1.2,"X");
      hRecoIterSysPP[j]->SetAxisRange(0.5,1.5,"Y");
      hRecoIterSysPP[j]->Draw(); 
    } else {
      hRecoIterSysPP[j]->Draw("same");
    }
         
    checkMaximumSys(systematics.hSysIter[nbins_cent],hRecoIterSysPP[j],0,1.1);
    legBayesianIterPP->AddEntry(hRecoIterSysPP[j],Form("Iteration %d",j),"pl");     
  }

  legBayesianIterPP->Draw();
  line->Draw();
  drawEnvelope(systematics.hSysIter[nbins_cent],(char*)"hist same");


  cIterSys->cd(1);
  TH1F *hRecoIterSysPbPb[100];
  TH1F *hRebinPbPb_tmp         = rebin(uhist[0]->hReco, (char*)"hRebinPbPb_tmp");
  TLegend *legBayesianIterPbPb = myLegend(0.4,0.7,0.9,0.9);
  legBayesianIterPbPb->AddEntry("","PbPb","");
  for (int j=2;j<7;j++) {
    hRecoIterSysPbPb[j] = rebin(uhist[0]->hRecoIterSys[j],Form("hRecoIterSysPbPb_IterSys%d",j));
    hRecoIterSysPbPb[j]->SetLineColor(colorCode[j-2]);
    hRecoIterSysPbPb[j]->SetMarkerColor(colorCode[j-2]);
    hRecoIterSysPbPb[j]->Divide(hRebinPbPb_tmp);
    if (j==2){
      makeHistTitle(hRecoIterSysPbPb[j],(char*)"",(char*)"Jet p_{T} (GeV/c)",(char*)"Ratio (Unfolded / Nominal)");
      hRecoIterSysPbPb[j]->SetTitleOffset(1.4,"Y");
      hRecoIterSysPbPb[j]->SetTitleOffset(1.2,"X");
      hRecoIterSysPbPb[j]->SetAxisRange(0.5,1.5,"Y");
      hRecoIterSysPbPb[j]->Draw(); 
    } else {
      hRecoIterSysPbPb[j]->Draw("same");
    }
         
    checkMaximumSys(systematics.hSysIter[0],hRecoIterSysPbPb[j],0,1.1);
    legBayesianIterPbPb->AddEntry(hRecoIterSysPbPb[j],Form("Iteration %d",j),"pl");     
  }
  legBayesianIterPbPb->Draw();
  line->Draw();
  drawEnvelope(systematics.hSysIter[0],(char*)"hist same");
}
Ejemplo n.º 17
0
void Analyzer::ComputeMinFast(){
	g2=new TGraph2D(); 
	
	alpha=1.0;beta=0;
	Loop(t_data,1);
	for(int j=0;j<=h_data->GetNbinsX()+1;j++)if(h_data->GetBinError(j)==0)h_data->SetBinError(j,1);
	if(varName=="QGLMLP")
		Loop(t_mc,4);
	//scan
	//reset Fast
	ResetFast();
	
	alpha=1.0;beta=0;
	for(float ai=aMin; ai<=aMax; ai+=0.02)
		{
		Reset(h_mc);	
		alphaFast.push_back(ai);	
		betaFast.push_back(0);	
		h_mcFast.push_back(new TH1F( Form("hmc_%d",int(h_mcFast.size())),"hmc",nBins,xMin,xMax) );
		}
	alpha=1.0;beta=0;
	for(float bi=bMin; bi<=bMax; bi+=0.01)
		{
		Reset(h_mc);	
		alphaFast.push_back(1.0);	
		betaFast.push_back(bi);	
		h_mcFast.push_back(new TH1F( Form("hmc_%d",int(h_mcFast.size())),"hmc",nBins,xMin,xMax) );
		}

	for(int j=0;j< int(h_mcFast.size());j++) h_mcFast[j]->Sumw2();	
	Loop(t_mc,16);
		for(int i=0 ;i<int(alphaFast.size());i++)
			{
			for(int j=0;j<=h_mcFast[i]->GetNbinsX()+1;j++)if(h_mcFast[i]->GetBinError(j)==0)h_mcFast[i]->SetBinError(j,1);
			h_mcFast[i]->Scale(h_data->Integral()/h_mcFast[i]->Integral());
			g2->SetPoint(g2->GetN(),alphaFast[i],betaFast[i], h_data->Chi2Test(h_mcFast[i],opt.c_str())  );
			}
	//Find min0;min1
	float min0=1,min1=0;
	pair<float,float> R=MinG(g2);
	min0=R.first;min1=R.second;
		
	ResetFast();

	delete g2;
	g2=new TGraph2D();

	for(int i=-nstep;i<=nstep;i++)
	for(int j=-nstep;j<=nstep;j++)
        	{
        	alphaFast.push_back(min0+i*stp0 );
        	betaFast.push_back(min1+j*stp1 );
		h_mcFast.push_back(new TH1F( Form("hmc_%d",int(h_mcFast.size())),"hmc",nBins,xMin,xMax) );
		//g2->SetPoint(g2->GetN(),alpha,beta, h_data->Chi2Test(h_mc,opt.c_str())  );
		}
	alphaFast.push_back(min0);
	betaFast.push_back(0);
	h_mcFast.push_back(new TH1F( Form("hmc_%d",int(h_mcFast.size())),"hmc",nBins,xMin,xMax) );

	alphaFast.push_back(min1);
	betaFast.push_back(bMax);
	h_mcFast.push_back(new TH1F( Form("hmc_%d",int(h_mcFast.size())),"hmc",nBins,xMin,xMax) );
	
	alphaFast.push_back(1);
	betaFast.push_back(0);
	h_mcFast.push_back(new TH1F( Form("hmc_%d",int(h_mcFast.size())),"hmc",nBins,xMin,xMax) );
	
	for(int j=0;j<int(h_mcFast.size());j++) h_mcFast[j]->Sumw2();	
	Loop(t_mc,16);
		for(int i=0 ;i<int(alphaFast.size());i++)
			{
			for(int j=0;j<=h_mcFast[i]->GetNbinsX()+1;j++)if(h_mcFast[i]->GetBinError(j)==0)h_mcFast[i]->SetBinError(j,1);
			h_mcFast[i]->Scale(h_data->Integral()/h_mcFast[i]->Integral());
			g2->SetPoint(g2->GetN(),alphaFast[i],betaFast[i], h_data->Chi2Test(h_mcFast[i],opt.c_str())  );
			}
	double m0,m1;
	R=MinG(g2,&m0,&m1);
	printf("a=%.3f;b=%.3f;lmin=%.3f;lmax=%.3f;break;//chi2=%.3lf; chi2_0=%.3lf\n",R.first,R.second,lmin,lmax,m0,m1);
	{
	TFile *out=TFile::Open("output.root","UPDATE");out->cd();
	for(int i=0;i<int(h_mcFast.size());i++)
		{
		h_mcFast[i]->SetName(Form("%s_alpha%.2f_beta%.2f_lmin%.3f_lmax%.3f_pt%0f_%.0f_rho%.0f_%.0f_eta%.0f_%.0f",varName.c_str(),alphaFast[i],betaFast[i],lmin,lmax,PtMin,PtMax,RhoMin,RhoMax,EtaMin,EtaMax));
		h_mcFast[i]->Write();
		}
	h_data->SetName(Form("%s_data_pt%0f_%.0f_rho%.0f_%.0f_eta%.0f_%.0f",varName.c_str(),PtMin,PtMax,RhoMin,RhoMax,EtaMin,EtaMax));
	h_data->Write();
	}
	return;
}
Ejemplo n.º 18
0
bool plot_tree(char* quantity,char* plotdim="(100,0.,3.)",bool log=true)
{
  char tmp1[250];
  char tmp2[300];
  char tmp3[100];
  sprintf(tmp2,"pythia.root");

  TFile* file;
  file=new TFile(tmp2);
  if(!file->IsOpen()) {
    cout << "No file "<<tmp2<<endl;
    return false;
  }
  file->cd();

  gROOT->SetStyle("Plain");
  const int maxjets=1+4;
  TH1F* hists[maxjets];
  sprintf(tmp3,"%s",quantity);
  TCanvas* c1=new TCanvas(tmp3,tmp3);
  c1->SetLogy();
  TLegend* leg=new TLegend(0.99,0.7,0.7,0.95);
  sprintf(tmp3,"l%s",quantity);
  leg->SetName(tmp3);
  int color[5]={2,4,3,5,6};
  int style[5]={2,3,4,3,4};

  //  bool ptw=false;
  TLeaf *leaf_Xsec = xsecs->FindLeaf("Xsecfact");
  Float_t Xsecfact;
  leaf_Xsec->SetAddress(&Xsecfact);
  xsecs->GetEntry(0);
  if (events->GetEntries()>0) {
  for(int i=0;i<maxjets;i++){
    events->SetLineWidth(2);
    events->SetLineColor(i+2);
    events->SetLineStyle(i+2);
    
    if(log) 
      sprintf(tmp1,"log10(%s)>>%s%i%s",quantity,quantity,i,plotdim);
    else 
      sprintf(tmp1,"%s>>%s%i%s",quantity,quantity,i,plotdim);
    sprintf(tmp2,"%e*(Npart==%i)",Xsecfact,i);

    cout << "events->Draw("<<tmp1<<","<<tmp2<<");"<<endl;
    events->Draw(tmp1,tmp2);

    sprintf(tmp3,"%s%i",quantity,i);
    hists[i]=(TH1F*)gROOT->FindObject(tmp3);
    if(!hists[i]){
      cout << "Failed to get object "<<tmp3<<endl;
      return false;
    }
  }
  }

  TH1F *hsum = (TH1F*)hists[0]->Clone();
  sprintf(tmp3,"%ssum",quantity);
  hsum->SetName(tmp3);
  for(int i=1;i<maxjets;i++)
    hsum->Add(hists[i]);
  cout << "Integral of "<<quantity<<": "<<hsum->Integral()<<endl;
  hsum->SetLineWidth(2);
  hsum->SetLineColor(1);
  hsum->SetLineStyle(1);
  //  hsum->SetMinimum(hsum->GetMaximum()*1e-3);
  hsum->SetStats(kFALSE);
  sprintf(tmp3,"%s",quantity);
  hsum->SetTitle(tmp3);
  sprintf(tmp3,"log10(%s)",quantity);
  hsum->GetXaxis()->SetTitle(tmp3);
  hsum->GetYaxis()->SetTitle("Cross section (pb/bin)");
  hsum->Draw();
  leg->AddEntry(hsum->GetName(),"Sum of contributions");

  for(int i=0;i<maxjets;i++){
    hists[i]->Draw("same");
    sprintf(tmp3,"%i-jet sample",i);
    leg->AddEntry(hists[i]->GetName(),tmp3);
  }

  leg->Draw();

  sprintf(tmp2,"%s.eps",quantity);
  cout << "Saving plot as " << tmp2 << endl;
  c1->SaveAs(tmp2);
  return true;
}
Ejemplo n.º 19
0
//================================================
void makeHistoData(const int savePlot, const int saveHisto)
{
  int year = 2014;
  if(year!=2014)
    {
      printf("[e] Not suitable for %d\n",year);
      return;
    }
  const char *run_type = "Run14_AuAu200";
  const char *trigName = "VPD-ZDC-novtx-mon";
  const int max_vz = 100;
  const int max_dz = 3;
  const int max_vr = 2;

  const char *wName[2] = {"","_w"};
  const char *setupName[5] = {"all","prod","prod_low","prod_mid","prod_high"};
  const char *trgSetupName[4] = {"production","production_low","production_mid","production_high"};
  const int nCentBins = 17;
  const int centBins_low[nCentBins]  = {5,  13, 9,  5, 15, 11, 5,  13, 11, 9,  7, 5, 1,  1, 3, 1, 1};
  const int centBins_high[nCentBins] = {16, 16, 12, 8, 16, 14, 10, 14, 12, 10, 8, 6, 16, 4, 4, 2, 1};
  const char *cent_Name[nCentBins] = {"0-60","0-20","20-40","40-60","0-10","10-30","30-60","10-20","20-30","30-40","40-50","50-60","0-80","60-80","60-70","70-80","75-80"};
  const char *cent_Title[nCentBins] = {"0060","0020","2040","4060","0010","1030","3060","1020","2030","3040","4050","5060","0080","6080","6070","7080","7580"};
  TH1F *hNEvents[5][2];
  TH1F *hTpcVz[5][nCentBins];
  TH1F *hDiffVz[5][nCentBins];
  TH1F *hTpcVr[5][nCentBins];
  TH1F *hNEventsAll[5][nCentBins][2];
  TH1F *hNEventsVr[5][nCentBins][2];
  TH1F *hNEventsVz[5][nCentBins][2];
  TH1F *hNEventsAcc[5][nCentBins][2];
  TH1F *hCent[5][2];

  TH2F *hTpcVzVsRun[nCentBins];
  TH2F *hTpcVrVsRun[nCentBins];
  TH2F *hDiffVzVsRun[nCentBins];
  TH2F *hCentVsRun[2];

  TFile *fMB = TFile::Open(Form("./output/Run14_AuAu200.MB.VtxEff.root"),"read");
  THnSparseF *hn[2];
  hn[0] = (THnSparseF*)fMB->Get("mhMbEvtEff");
  hn[1] = (THnSparseF*)fMB->Get("mhMbEvtEffWeight");

  // Assign the prod_high to MB
  TFile *fhigh = TFile::Open(Form("./output/Run14_AuAu200.MB.VtxEff.prod_high.root"),"read");
  THnSparseF *hn_high[2];
  hn_high[0] = (THnSparseF*)fhigh->Get("mhMbEvtEff");
  hn_high[1] = (THnSparseF*)fhigh->Get("mhMbEvtEffWeight");
  for(int i=0; i<2; i++)
    {
      hn_high[i]->SetName(Form("%s_high",hn_high[i]->GetName()));
      const int nAxis = 6;
      int axisNbins[nAxis];
      for(int iaxis=0; iaxis<nAxis; iaxis++)
	{
	  axisNbins[iaxis] = hn_high[i]->GetAxis(iaxis)->GetNbins();
	}

      // the index correspond to bin number starting from 1
      TH1F *hRunStat = (TH1F*)hn_high[i]->Projection(0);
      hRunStat->SetName(Form("hRunStat%s_prod_high",wName[i]));
      for(int ibin=1; ibin<=axisNbins[0]; ibin++)
	{
	  if(hRunStat->GetBinContent(ibin)<=0) continue;
	  cout << "Haha: " << ibin << endl;
	  for(int jbin=1; jbin<=axisNbins[1]; jbin++)
	    {
	      for(int kbin=1; kbin<=axisNbins[2]; kbin++)
		{
		  for(int lbin=1; lbin<=axisNbins[3]; lbin++)
		    {
		      for(int mbin=1; mbin<=axisNbins[4]; mbin++)
			{
			  for(int nbin=1; nbin<=axisNbins[5]; nbin++)
			    {
			      int idx[6] = {ibin, jbin, kbin, lbin, mbin, nbin};
			      hn[i]->SetBinContent(idx, hn_high[i]->GetBinContent(idx));
			      hn[i]->SetBinError(idx, hn_high[i]->GetBinError(idx));
			    }
			}
		    }
		}
	    }
	}
    }
  return;
  

  for(int i=0; i<2; i++)
    {
      hNEvents[0][i] = (TH1F*)hn[i]->Projection(0);
      hNEvents[0][i]->SetName(Form("NEvents_%s%s",setupName[0],wName[i]));

      for(int j=0; j<nCentBins; j++)
	{
	  hn[i]->GetAxis(5)->SetRange(centBins_low[j],centBins_high[j]);
	  hNEventsAll[0][j][i] = (TH1F*)hn[i]->Projection(0);
	  hNEventsAll[0][j][i]->SetName(Form("NEvents_cent%s_%s%s",cent_Title[j],setupName[0],wName[i]));
	  if(i==0)
	    {
	      hTpcVz[0][j] = (TH1F*)hn[i]->Projection(1);
	      hTpcVz[0][j]->SetName(Form("TpcVz_cent%s_%s%s",cent_Title[j],setupName[0],wName[i]));
	      hTpcVzVsRun[j] = (TH2F*)hn[i]->Projection(1,0);
	      hTpcVzVsRun[j]->SetName(Form("TpcVzVsRun_cent%s_%s%s",cent_Title[j],setupName[0],wName[i]));
	      //draw2D(hTpcVzVsRun[j]);

	      hTpcVr[0][j] = (TH1F*)hn[i]->Projection(3);
	      hTpcVr[0][j]->SetName(Form("TpcVr_cent%s_%s%s",cent_Title[j],setupName[0],wName[i]));
	      hTpcVrVsRun[j] = (TH2F*)hn[i]->Projection(3,0);
	      hTpcVrVsRun[j]->SetName(Form("TpcVrVsRun_cent%s_%s%s",cent_Title[j],setupName[0],wName[i]));

	      hDiffVz[0][j] = (TH1F*)hn[i]->Projection(2);
	      hDiffVz[0][j]->SetName(Form("TpcVpdDz_cent%s_%s%s",cent_Title[j],setupName[0],wName[i]));
	      hDiffVzVsRun[j] = (TH2F*)hn[i]->Projection(2,0);
	      hDiffVzVsRun[j]->SetName(Form("DiffVzVsRun_cent%s_%s%s",cent_Title[j],setupName[0],wName[i]));
	    }

	  hn[i]->GetAxis(3)->SetRangeUser(-1,max_vr-1e-4);
	  hNEventsVr[0][j][i] = (TH1F*)hn[i]->Projection(0);
	  hNEventsVr[0][j][i]->SetName(Form("NEvents_VrCut_cent%s_%s%s",cent_Title[j],setupName[0],wName[i]));

	  hn[i]->GetAxis(1)->SetRangeUser(-1*max_vz+1e-4,max_vz-1e-4);
	  hNEventsVz[0][j][i] = (TH1F*)hn[i]->Projection(0);
	  hNEventsVz[0][j][i]->SetName(Form("NEvents_VrVzCut_cent%s_%s%s",cent_Title[j],setupName[0],wName[i]));

	  hn[i]->GetAxis(2)->SetRangeUser(-1*max_dz+1e-4,max_dz-1e-4);
	  hNEventsAcc[0][j][i] = (TH1F*)hn[i]->Projection(0);
	  hNEventsAcc[0][j][i]->SetName(Form("NEvents_VrVzDzCut_cent%s_%s%s",cent_Title[j],setupName[0],wName[i]));

	  hn[i]->GetAxis(5)->SetRange(0,-1);
	  if(j==0)
	    {
	      hCent[0][i] = (TH1F*)hn[i]->Projection(5);
	      hCent[0][i]->SetName(Form("Cent_%s%s",setupName[0],wName[i]));
	      hCentVsRun[i] = (TH2F*)hn[i]->Projection(5,0);
	      hCentVsRun[i]->SetName(Form("CentVsRun_%s%s",setupName[0],wName[i]));
	    }

	  hn[i]->GetAxis(1)->SetRange(0,-1);
	  hn[i]->GetAxis(2)->SetRange(0,-1);
	  hn[i]->GetAxis(3)->SetRange(0,-1);

	}
    }


  for(int k=0; k<4; k++)
    {
      for(int i=0; i<2; i++)
	{
	  hNEvents[k+1][i] = (TH1F*)hNEvents[0][i]->Clone(Form("NEvents_%s%s",setupName[k+1],wName[i]));
	  hNEvents[k+1][i]->Reset();
	  for(int j=0; j<nCentBins; j++)
	    {
	      if(i==0)
		{
		  hTpcVz[k+1][j] = (TH1F*)hTpcVz[0][j]->Clone(Form("TpcVz_cent%s_%s%s",cent_Title[j],setupName[k+1],wName[i]));
		  hTpcVz[k+1][j]->Reset();

		  hTpcVr[k+1][j] = (TH1F*)hTpcVr[0][j]->Clone(Form("TpcVr_cent%s_%s%s",cent_Title[j],setupName[k+1],wName[i]));
		  hTpcVr[k+1][j]->Reset();

		  hDiffVz[k+1][j] = (TH1F*)hDiffVz[0][j]->Clone(Form("TpcVpdDz_cent%s_%s%s",cent_Title[j],setupName[k+1],wName[i]));
		  hDiffVz[k+1][j]->Reset();
		}
	      hNEventsAll[k+1][j][i] = (TH1F*)hNEventsAll[0][j][i]->Clone(Form("NEvents_cent%s_%s%s",cent_Title[j],setupName[k+1],wName[i]));
	      hNEventsAll[k+1][j][i]->Reset();

	      hNEventsVr[k+1][j][i] = (TH1F*)hNEventsVr[0][j][i]->Clone(Form("NEvents_VrCut_cent%s_%s%s",cent_Title[j],setupName[k+1],wName[i]));
	      hNEventsVr[k+1][j][i]->Reset();

	      hNEventsVz[k+1][j][i] = (TH1F*)hNEventsVz[0][j][i]->Clone(Form("NEvents_VrVzCut_cent%s_%s%s",cent_Title[j],setupName[k+1],wName[i]));
	      hNEventsVz[k+1][j][i]->Reset();

	      hNEventsAcc[k+1][j][i] = (TH1F*)hNEventsAcc[0][j][i]->Clone(Form("NEvents_VrVzDzCut_cent%s_%s%s",cent_Title[j],setupName[k+1],wName[i]));
	      hNEventsAcc[k+1][j][i]->Reset();

	      if(j==0)
		{
		  hCent[k+1][i] = (TH1F*)hCent[0][i]->Clone(Form("Cent_%s%s",setupName[k+1],wName[i]));
		  hCent[k+1][i]->Reset();
		}
	    }
	}
    }

  for(int k=0; k<4; k++)
    {
      ifstream fruns;
      fruns.open(Form("Rootfiles/Luminosity/%s/AuAu_200_%s_2014.list",run_type,trgSetupName[k]));
      int runnumber;
      while(!fruns.eof())
	{
	  fruns >> runnumber;
	  int bin = hNEvents[0][0]->FindFixBin(runnumber);

	  for(int i=0; i<2; i++)
	    {
	      hNEvents[k+1][i]->SetBinContent(bin,hNEvents[0][i]->GetBinContent(bin));
	      hNEvents[k+1][i]->SetBinError(bin,hNEvents[0][i]->GetBinError(bin));
	      for(int j=0; j<nCentBins; j++)
		{
		  if(i==0)
		    {
		      TH1F *htmp = (TH1F*)hTpcVzVsRun[j]->ProjectionY(Form("%s_%d",hTpcVzVsRun[j]->GetName(),bin),bin,bin);
		      hTpcVz[k+1][j]->Add(htmp);

		      htmp = (TH1F*)hTpcVrVsRun[j]->ProjectionY(Form("%s_%d",hTpcVrVsRun[j]->GetName(),bin),bin,bin);
		      hTpcVr[k+1][j]->Add(htmp);

		      htmp = (TH1F*)hDiffVzVsRun[j]->ProjectionY(Form("%s_%d",hDiffVzVsRun[j]->GetName(),bin),bin,bin);
		      hDiffVz[k+1][j]->Add(htmp);
		    }
	  
		  hNEventsAll[k+1][j][i]->SetBinContent(bin,hNEventsAll[0][j][i]->GetBinContent(bin));
		  hNEventsAll[k+1][j][i]->SetBinError(bin,hNEventsAll[0][j][i]->GetBinError(bin));

		  hNEventsVr[k+1][j][i]->SetBinContent(bin,hNEventsVr[0][j][i]->GetBinContent(bin));
		  hNEventsVr[k+1][j][i]->SetBinError(bin,hNEventsVr[0][j][i]->GetBinError(bin));

		  hNEventsVz[k+1][j][i]->SetBinContent(bin,hNEventsVz[0][j][i]->GetBinContent(bin));
		  hNEventsVz[k+1][j][i]->SetBinError(bin,hNEventsVz[0][j][i]->GetBinError(bin));

		  hNEventsAcc[k+1][j][i]->SetBinContent(bin,hNEventsAcc[0][j][i]->GetBinContent(bin));
		  hNEventsAcc[k+1][j][i]->SetBinError(bin,hNEventsAcc[0][j][i]->GetBinError(bin));
		  if(j==0)
		    {
		      TH1F *htmp = (TH1F*)hCentVsRun[i]->ProjectionY(Form("%s_%d",hCentVsRun[i]->GetName(),bin),bin,bin);
		      hCent[k+1][i]->Add(htmp);
		    }
		}
	    }
	}
    }


  if(saveHisto)
    {
      TFile *fout = TFile::Open(Form("Rootfiles/%s.Luminosity.root",run_type),"update");
      for(int k=0; k<5; k++)
	{
	  for(int i=0; i<2; i++)
	    {
	      hNEvents[k][i]->SetTitle("");
	      hNEvents[k][i]->Write("",TObject::kOverwrite);
	      for(int j=0; j<nCentBins; j++)
		{
		  hNEventsAll[k][j][i]->SetTitle("");
		  hNEventsVr[k][j][i]->SetTitle("");
		  hNEventsVz[k][j][i]->SetTitle("");
		  hNEventsAcc[k][j][i]->SetTitle("");
		  hNEventsAll[k][j][i]->Write("",TObject::kOverwrite);
		  hNEventsVr[k][j][i]->Write("",TObject::kOverwrite);
		  hNEventsVz[k][j][i]->Write("",TObject::kOverwrite);
		  hNEventsAcc[k][j][i]->Write("",TObject::kOverwrite);
		  if(j==0)
		    {
		      hCent[k][i]->SetTitle("");
		      hCent[k][i]->Write("",TObject::kOverwrite);
		    }
		  if(i==0)
		    {
		      hTpcVz[k][j]->SetTitle("");
		      hTpcVr[k][j]->SetTitle("");
		      hDiffVz[k][j]->SetTitle("");
		      hTpcVz[k][j]->Write("",TObject::kOverwrite);
		      hTpcVr[k][j]->Write("",TObject::kOverwrite);
		      hDiffVz[k][j]->Write("",TObject::kOverwrite);
		    }
		}
	    }
	}
    }
}
Ejemplo n.º 20
0
void AllInOne_combineLepton(const std::string& dataset,int btag=0, double timesX=1, bool useNewShape=false){

  std::string useNewShapeText = (useNewShape) ? "_newshape" : "";

  char wsFileName[700];
  sprintf(wsFileName,"datacards/400/hzz2l2q_ee%db.input.root",btag);
  //sprintf(wsFileName,"PROVA/datacards_%s%s/hzz2l2q_ee%db.input.root",dataset.c_str(), useNewShapeText.c_str(),btag);

  gSystem->Load("libRooFit");
  gSystem->Load("libFFTW");

  string histoName[3];
  histoName[0]="mZZ_kinfit_hiMass_0btag";
  histoName[1]="mZZ_kinfit_hiMass_1btag";
  histoName[2]="mZZ_kinfit_hiMass_2btag";
  string btagName[3]={"0b","1b","2b"};

  double LumiScale=0.;
  if( dataset=="Run2011A_FULL" ) LumiScale = 2100.;
  else if( dataset=="LP11" ) LumiScale = 1600.;
  else {
    std::cout << "Unknown dataset '" << dataset << "'. Exiting." << std::endl;
  }

  RooDataSet *data_bkg;  
  RooDataSet *data_temp;
  TFile *file;

  string cutString[3];
  cutString[0]="nBTags==0 && (mZjj>75 && mZjj<105) && mZZ>183";
  cutString[1]="nBTags==1 && (mZjj>75 && mZjj<105) && mZZ>183";
  cutString[2]="nBTags==2 && (mZjj>75 && mZjj<105) && mZZ>183";

  int binWidth=20;
  int highBin=750;
  int lowBin=150;

//double muonEff[3]={.576,.548,.489};

//double expSig[3];
//expSig[0]=5.65*LumiScale ;
//expSig[1]=4.89*LumiScale ;
//expSig[2]=2.37*LumiScale ;

  char alphaFileName[200];
  sprintf( alphaFileName, "alphaFile_%s_%dbtag_ALL.root", dataset.c_str(), btag);
  TFile* alphaFile = TFile::Open(alphaFileName);
  TTree* treeSidebandsDATA_alphaCorr = (TTree*)alphaFile->Get("sidebandsDATA_alpha");
  TH1D* h1_mZZ_sidebands_alpha = new TH1D("mZZ_sidebands_alpha", "", 65, 150., 800.);
  char sidebandsCut_alpha[500];
  sprintf(sidebandsCut_alpha, "eventWeight_alpha*(isSidebands && nBTags==%d)", btag);
  treeSidebandsDATA_alphaCorr->Project("mZZ_sidebands_alpha", "mZZ", sidebandsCut_alpha);
  float expBkg = h1_mZZ_sidebands_alpha->Integral();
  std::cout <<  "++++ expBkg: " << expBkg << std::endl;



  stringstream convert;

  // --------------------- measurable (ZZ invariant mass) ----------------
  string temp;
  temp="m_{ZZ}";
  RooRealVar mZZ("mZZ",temp.c_str(),lowBin,highBin);
  RooRealVar nBTags("nBTags","nBTags",-1.,3.);
  RooRealVar leptType("leptType","leptType",0,1);
  RooRealVar mZjj("mZjj","mZjj",0,200.);

  // ----------------- get parameters from data cards! -----------------
  
  TFile *wsFile = new TFile(wsFileName);
  RooWorkspace *ws = (RooWorkspace*) wsFile->Get("w");

  // ==================== defining bkg PDF ==========================
  // ------------------------ fermi ------------------------------
  RooRealVar cutOff("cutOff","position of fermi",ws->var("cutOff_BKG")->getVal());
  cutOff.setConstant(kTRUE);
  RooRealVar beta("beta","width of fermi",ws->var("beta_BKG")->getVal());
  beta.setConstant(kTRUE);
	     		       
  RooFermi fermi("fermi","fermi function",mZZ,cutOff,beta);
  // -------------------- double gauss ---------------------------
  temp="CMS_hzz2l2q_bkg"+btagName[btag]+"p1";
  RooRealVar m("m","m",ws->var(temp.c_str())->getVal());
  m.setConstant(kTRUE);
  temp="CMS_hzz2l2q_bkg"+btagName[btag]+"p2";
  RooRealVar wdth("wdth","wdth",ws->var(temp.c_str())->getVal());
  wdth.setConstant(kTRUE);
  temp="CMS_hzz2l2q_bkg"+btagName[btag]+"p3";
  RooRealVar n("n","n",ws->var(temp.c_str())->getVal());
  n.setConstant(kTRUE);
  temp="CMS_hzz2l2q_bkg"+btagName[btag]+"p4";
  RooRealVar alpha("alpha","alpha",ws->var(temp.c_str())->getVal());
  alpha.setConstant(kTRUE);
  temp="CMS_hzz2l2q_bkg"+btagName[btag]+"p5";
  RooRealVar theta("theta","theta",ws->var(temp.c_str())->getVal());
  theta.setConstant(kTRUE);

  RooCB CB("CB","Crystal ball",mZZ,m,wdth,alpha,n,theta);
  
  RooProdPdf background("background","background",RooArgSet(fermi,CB));


  // ------------------ get data --------------------------
  // for reading sideband extrapolated data...
  std::string fileName = "HZZlljjRM_DATA_" + dataset + "_optLD_looseBTags_v2_ALL.root";
  file = new TFile(fileName.c_str());
  //file = new TFile("../HZZlljjRM_DATA_Run2011A_FULL_optLD_looseBTags_v2_ALL.root");
  TTree* t=(TTree*)file->Get("tree_passedEvents");
  data_bkg=new RooDataSet("data_bkg","data_bkg",t,
			  RooArgSet(mZZ,leptType,nBTags,mZjj),
			  cutString[btag].c_str());

  // --------- draw MC data -------------------
  RooPlot *plot_MCbkg = mZZ.frame(lowBin,highBin,(int)(highBin-lowBin)/binWidth);

  //-----------------------------------------------------------------------
  TCanvas *c2 = new TCanvas("c2","c2",600,600);

  TPaveText* cmslabel = new TPaveText( 0.145, 0.953, 0.6, 0.975, "brNDC" );
  cmslabel->SetFillColor(kWhite);
  cmslabel->SetTextSize(0.038);
  cmslabel->SetTextAlign(11);
  cmslabel->SetTextFont(62);
  cmslabel->SetBorderSize(0);
  char lumilabel[500];
  sprintf( lumilabel, "CMS Preliminary 2011, %.1f fb^{-1}", LumiScale/1000.);
  cmslabel->AddText(lumilabel);

  TPaveText* label_sqrt = new TPaveText(0.7,0.953,0.96,0.975, "brNDC");
  label_sqrt->SetFillColor(kWhite);
  label_sqrt->SetTextSize(0.038);
  label_sqrt->SetTextFont(42);
  label_sqrt->SetTextAlign(31); // align right
  label_sqrt->SetBorderSize(0);
  label_sqrt->AddText("#sqrt{s} = 7 TeV");
  //-----------------------------------------------------------------------

  background.plotOn(plot_MCbkg,Normalization(expBkg));
  data_bkg->plotOn(plot_MCbkg,Binning((int)(highBin-lowBin)/binWidth));
  // -------------------- get histograms -----------------
  
  TFile *ZjetsFile = new TFile("HZZlljjRM_DYJetsToLL_TuneZ2_M-50_7TeV-madgraph-tauola_Summer11-PU_S4_START42_V11-v1_optLD_looseBTags_v2_ALL.root");
  TFile *TTFile = new TFile("HZZlljjRM_TT_TW_TuneZ2_7TeV-powheg-tauola_Summer11-PU_S4_START42_V11-v1_optLD_looseBTags_v2_ALL.root");
  TFile *VVFile = new TFile("HZZlljjRM_VV_TuneZ2_7TeV-pythia6-tauola_Summer11-PU_S4_START42_V11-v1_optLD_looseBTags_v2_ALL.root");
  TFile *H400File = new TFile("HZZlljjRM_GluGluToHToZZTo2L2Q_M-400_7TeV-powheg-pythia6_Summer11-PU_S4_START42_V11-v1_optLD_looseBTags_v2_ALL.root");

  TH1F *hZjets =(TH1F*)ZjetsFile->Get(histoName[btag].c_str());
  hZjets->SetName("hZjets");
  hZjets->Scale(LumiScale);
  hZjets->Rebin(binWidth);
  hZjets->SetFillColor(30);

  TH1F *hTT =(TH1F*)TTFile->Get(histoName[btag].c_str());
  hTT->SetName("hTT");
  convert << binWidth;
  temp=";m_{ZZ} [GeV]; Events / "+convert.str()+" GeV";
  hTT->SetTitle(temp.c_str());
  hTT->Scale(LumiScale);
  hTT->Rebin(binWidth);
  hTT->SetFillColor(39);
  gStyle->SetOptStat(0);

  //if(btag==0)
  //  hTT->GetYaxis()->SetRangeUser(0.0001,245);
  //if(btag==1)
  //  hTT->GetYaxis()->SetRangeUser(0.0001,245);
  //if(btag==2)
  //  hTT->GetYaxis()->SetRangeUser(0.0001,25);

  //hTT->Draw();


  TH1F *hVV =(TH1F*)VVFile->Get(histoName[btag].c_str());
  hVV->SetName("hVV");
  hVV->Scale(LumiScale);
  hVV->Rebin(binWidth);
  hVV->SetFillColor(38);

  TH1F* hH400 = (TH1F*)H400File->Get(histoName[btag].c_str());
  hH400->SetName("hH400");
  hH400->Scale(LumiScale*timesX);
  cout << "SIGNAL NORMALIZATION: " << hH400->Integral() << endl;
  hH400->Rebin(binWidth);
  hH400->SetFillColor(kYellow);//kRed+3);

  temp = ";m_{ZZ} [GeV];Events / "+convert.str()+" GeV";
  THStack *hBkg = new THStack("hBkg",temp.c_str());
  convert.str("");

  hBkg->Add(hVV);
  hBkg->Add(hTT);
  hBkg->Add(hZjets);
  hBkg->Add(hH400);

  float xMin = 150.;
  float xMax = 750.;
  float yMin = 0.;
  float yMax = 1.3*hBkg->GetMaximum();

  char yAxisName[500];
  sprintf( yAxisName, "Events / %.0f GeV", hVV->GetXaxis()->GetBinWidth(1) );
  //std::string yAxisName = "Events / "+convert.str()+" GeV";
  convert.str("");

//char xAxisName[400];
//sprintf( xAxisName, "m_{%s%sjj} [GeV]", leptType_forLegend.c_str(), leptType_forLegend.c_str() );

  TH2D* h2_axes = new TH2D("axes", "", 10, xMin, xMax, 10, yMin, yMax);
  h2_axes->SetXTitle("m_{lljj} [GeV]");
  h2_axes->SetYTitle(yAxisName);
  h2_axes->Draw();

  hBkg->Draw("SAMEHIST");
  plot_MCbkg->Draw("SAME");
  cmslabel->Draw();
  label_sqrt->Draw();
  // ---------------legend ---------------------------

  TLegend *leg = new TLegend(.4,.5,.8,.9);
  leg->SetTextSize(0.036);
  leg->SetFillColor(0);
  leg->SetBorderSize(0);
  convert.str("");
  convert << LumiScale/1000;
  temp="CMS Preliminary #sqrt{s}=7 TeV "+convert.str()+" fb^{-1}";
  //leg->SetHeader(temp.c_str());
  leg->AddEntry("background_Norm[mZZ]","Sideband Extrapolated Fit","l");
  //leg->AddEntry("model_Norm[mZZ]","Background+10#timesSignal","l");

  if(btag==0)
    temp="0 b-tag 2l2q data";
  if(btag==1)
    temp="1 b-tag 2l2q data";
  if(btag==2)
    temp="2 b-tag 2l2q data";

  leg->AddEntry("h_data_bkg",temp.c_str(),"p");
  leg->AddEntry("hZjets","Z + Jets","f");
  leg->AddEntry("hTT","tt/tW","f");
  leg->AddEntry("hVV","ZZ/WZ/WW","f");
  convert.str("");
  convert << timesX;
  temp="400 GeV SM Higgs#times"+convert.str();
  leg->AddEntry("hH400",temp.c_str(),"f");
  leg->Draw();

  string saveFileName="AllInOne_"+dataset + "_"+btagName[btag]+"tag_ll_LIMIT" + useNewShapeText + ".eps";

  c2->SaveAs(saveFileName.c_str()); 

}
//void pi0_mfitpeak(char *FileName, char *HistName, Int_t etapi0flag) 
void pi0_mfitpeak(TH1F *mh1, Int_t etapi0flag, float xmin, float xmax, int npol,float res[],int posFlag, const char *dirName, const char *histName, float text_x, float text_y, const char *texName) 
  
{
  TGaxis::SetMaxDigits(3);


  // TVirtualFitter::SetDefaultFitter("Minuit");
  


  // This script attempts to fit any pi0 peak so that the freaking fit function would converge
  // currently background is fitted to a pol4 function and the peak by a gaussian;
  // results are not very nice
  // usage  .x pi0_mfitpeak.C++ ("pi0calib.root","minv_spb")
  // or eg.  .x pi0_mfitpeak.C ("../pi0anal/pi0ana_punorm.root","minv_spb",0)

  gROOT->Reset();
  //  gStyle->SetOptFit();
  //  gStyle->SetOptFit(0);
  //  gStyle->SetOptStat(0);
  //  gStyle->SetOptTitle(0);
Bool_t NOTE=1;
  if(NOTE) gStyle->SetCanvasBorderMode(0);

  gStyle->SetPadTopMargin(0.08);
  gStyle->SetPadBottomMargin(0.12);
  gStyle->SetPadLeftMargin(0.15);
  gStyle->SetPadRightMargin(0.08);

  mh1->GetXaxis()->SetRangeUser(xmin,xmax);
  
  Int_t highx=500;
  TCanvas *c2 = new TCanvas("c2","",200,10,highx,500);


    // cout<<FileName<<" "<<HistName<<endl;

  //     TFile f(FileName);
  //   TH1F *mh1 = (TH1F*) f.Get(HistName);
      mh1->SetMarkerStyle(20);
      mh1->SetMarkerSize(1.);
      mh1->SetStats(0); // 1/0 to set the stat box

   mh1->GetXaxis()->SetTitle("Invariant Mass of Photon Pairs (GeV/c^{2})");


   float binwidth = mh1->GetBinWidth(1);
   
   char *ytitle = new char[100];

   sprintf(ytitle,"Photon Pairs / %4.3f GeV/c^{2}",binwidth);
   

   mh1->GetYaxis()->SetTitle(ytitle);


   mh1->GetXaxis()->SetTitleSize(0.055);
   mh1->GetYaxis()->SetTitleSize(0.055);
   mh1->GetXaxis()->SetLabelSize(0.045);
   mh1->GetYaxis()->SetLabelSize(0.045);
   mh1->GetXaxis()->SetTitleOffset(0.90);
   mh1->GetXaxis()->CenterTitle();
   mh1->GetYaxis()->SetTitleOffset(1.32);
   

   // First work with the histogram and find the peak and fit ranges
   TAxis *xaxis = mh1->GetXaxis();
   Float_t binsiz= xaxis->GetBinCenter(3) - xaxis->GetBinCenter(2);
   Int_t nbins = xaxis->GetNbins(); 
   Float_t nevtperbin0[10000];
   Float_t errorbin0[10000];
   Float_t nevttot;
   Float_t maxbin=0; Int_t nmaxbin=0, nminbord=0, nmaxbord=nbins;
   
   for (Int_t nn=1; nn <= nbins; nn++)
     {
       nevtperbin0[nn] = mh1->GetBinContent(nn); 
       if(nevtperbin0[nn] > maxbin) { maxbin=nevtperbin0[nn]; nmaxbin=nn; }
       errorbin0[nn] = mh1->GetBinError(nn); 
       nevttot+=nevtperbin0[nn];
       if(nevtperbin0[nn] > 0 && nminbord == 0) nminbord=nn; 
       if(nevtperbin0[nn] == 0 && (nn > nminbord +10) && nmaxbord==0 && nminbord > 0) nmaxbord=nn; 
     }
   cout<<"Minbordl "<<nminbord<<" with events: "<<nevtperbin0[nminbord]<<endl;
   cout<<"Maxbordl "<<nmaxbord<<" with events: "<<nevtperbin0[nmaxbord]<<endl;
   nminbord+=0;
   nmaxbord-=0;
   Int_t nmin0=nminbord;
   while(nevtperbin0[nminbord] < nevtperbin0[nmaxbin]*0.025) nminbord++;
   while(nevtperbin0[nmaxbord] < nevtperbin0[nmaxbin]*0.025) nmaxbord--;
   // the above was just to get the info and low/high bins

   // Set the fit range ! This is for total fit !	 
   Float_t fitl=xmin;
     float fith=xmax;
   //     Float_t fitl=0.07, fith=0.2;// this works better for pileup
   //         Float_t fitl=0.08, fith=0.18;// this works even better for pileup
     //  if(etapi0flag == 1)
     // {
     //  fitl=0.35; fith=0.75;
     //}
     

     //   if(fitl < xaxis->GetBinCenter(nmin0)) fitl = xaxis->GetBinCenter(nmin0);
   //if(fith > xaxis->GetBinCenter(nmaxbord)) fith = xaxis->GetBinCenter(nmaxbord);
 
   


   cout<<" fit range "<<fitl<<" -- "<<fith<<endl;

   cout <<"Bin size "<<binsiz<<endl;
   cout<<"Total events "<<nevttot<<endl;
   cout<<"MaxBin "<<nmaxbin<<" with events: "<<nevtperbin0[nmaxbin]<<endl;
   cout<<"Minbord "<<nminbord<<" with events: "<<nevtperbin0[nminbord]<<endl;
   cout<<"Maxbord "<<nmaxbord<<" with events: "<<nevtperbin0[nmaxbord]<<endl;
      mh1->DrawCopy("sep");

      Float_t lowgauss=0.135-4.*0.010;
      Float_t highgauss=0.135+4.*0.010;
      if(etapi0flag == 1)
	{
	  lowgauss=0.55-5.*0.025;
              highgauss=0.55+5.*0.025;
	}
      Int_t nlowgauss=Int_t((lowgauss-xaxis->GetBinCenter(1))/Float_t(binsiz)+0.5);
      Int_t nhighgauss=Int_t((highgauss-xaxis->GetBinCenter(1))/Float_t(binsiz)+0.5);
      cout <<xaxis->GetBinCenter(nlowgauss)<<" "<<xaxis->GetBinCenter(nhighgauss)<<endl;
   // now make the "background" histogram and fit it with p4
      Float_t lowvalgauss=nevtperbin0[nlowgauss];
      Float_t increm=(nevtperbin0[nhighgauss]-nevtperbin0[nlowgauss])/Float_t(nhighgauss-nlowgauss);
      TH1F *hbkg = (TH1F*)mh1->Clone();
      hbkg->SetName("bkg_clone");
      for (Int_t nn=nlowgauss; nn<=nhighgauss; nn++)
	{
	  hbkg->SetBinContent(nn,Float_t(lowvalgauss+(nn-nlowgauss)*increm));
	  hbkg->SetBinError(nn,sqrt(lowvalgauss+(nn-nlowgauss)*increm));
	}
      hbkg->DrawCopy("samesep");
      //      break;
      // Now define the "gaussian" histogram
      TH1F *hgauss = (TH1F*)mh1->Clone();
      hgauss->SetName("gauss_clone");
      hgauss->Sumw2();
      hgauss->Add(mh1,hbkg,1,-1); // if errors are independent Add needs to be used !
       for (Int_t nn=1; nn <= nbins; nn++)
	 {
	   if(hgauss->GetBinContent(nn) < 0.) hgauss->SetBinContent(nn,0.001*nevtperbin0[nmaxbin]);
	   hgauss->SetBinError(nn,sqrt(hgauss->GetBinContent(nn)));
	 }

   // Declare function with wich to fit
       TF1 *g1 = new TF1("g1","gaus",lowgauss,highgauss);
   hgauss->Fit(g1,"R0");
   hgauss->DrawCopy("sep");
   g1->Draw("same");
   //  break;

   char *polff = new char[20];

   sprintf(polff,"pol%d",npol);
   
   TF1 *p4bkg; 
   if(etapi0flag != 1)
     p4bkg   = new TF1("pm2",polff, xaxis->GetBinCenter(nminbord),xaxis->GetBinCenter(nmaxbord));
   else
     p4bkg   = new TF1("pm2",polff, 0.35,0.75);
   
   

   hbkg->Fit(p4bkg,"R0");
   hbkg->DrawCopy("sep");
   p4bkg->SetLineStyle(kDashed);
   p4bkg->Draw("same");
   // break;
   
   
   Double_t par[20],parf[20],errparf[20];
   g1->GetParameters(&par[0]);
   p4bkg->GetParameters(&par[3]);

   char *totff = new char[20];
   
   sprintf(totff,"gaus(0)+pol%d(3)",npol);
   
   
   TF1 *total = new TF1("total",totff,fitl,fith);
   TF1 *p4bkgfin   = new TF1("pm2",polff,fitl,fith);
   total->SetParameters(par);

   if(etapi0flag==0){
     total->SetParLimits(1,0.10,0.15);
     total->SetParLimits(2,0.135*0.06,0.135*0.3);
     
   }else{
     total->SetParLimits(1,0.35,0.65);
   }
   
   
   //  total->FixParameter(1,1.21340e-01); 
   // total->FixParameter(2,2.69780e-02);
   
   
   

   

   mh1->Fit(total,"R0");
   
   cout<<" yield.. "<< total->GetParameter(0) <<"+/- " << total->GetParError(0)<<endl;
   

     total->GetParameters(parf);


     for( Int_t nn=0; nn < 3+npol+1; nn++) errparf[nn]=total->GetParError(nn);
     g1->SetParameters(&parf[0]);
     p4bkgfin->SetParameters(&parf[3]);
     cout <<" Piz Mass = "<<parf[1]*1000.<<" +- "<<errparf[1]*1000.<<
       " Sigma ="<<parf[2]*1000.<<" +- "<<errparf[2]*1000.<<endl;
      cout << " Sigma Rel. = "<< parf[2]/parf[1]<<" +- "
	   << errparf[2]/parf[1] <<endl;

    Float_t int_min=parf[1]-3.*parf[2];
    Float_t int_max=parf[1]+3.*parf[2];
    Float_t sig_peak=g1->Integral(int_min,int_max)/binsiz;
    Float_t bkgd_peak=p4bkgfin->Integral(int_min,int_max)/binsiz;
    cout<<" In +-3. sigma window: Signal="<<sig_peak<<" Bkgd="<<bkgd_peak<<endl;
    Float_t SB=sig_peak/bkgd_peak; Float_t SBerr=SB*(sqrt(1./sig_peak+1./bkgd_peak));
    cout<<" Signal/Bkgd "<<SB<<" +- "<<SBerr<<endl;   

    int_min=parf[1]-2.*parf[2];
    int_max=parf[1]+2.*parf[2];
    sig_peak=g1->Integral(int_min,int_max)/binsiz;
    bkgd_peak=p4bkgfin->Integral(int_min,int_max)/binsiz;
    cout<<" In +-2.sigma window: Signal="<<sig_peak<<" Bkgd="<<bkgd_peak<<endl;
    SB=sig_peak/bkgd_peak; SBerr=SB*(sqrt(1./sig_peak+1./bkgd_peak));
    cout<<" Signal/Bkgd "<<SB<<" +- "<<SBerr<<endl;   
 			

    float S = sig_peak; 
    float B = bkgd_peak; 
    
    int_min=parf[1]-20.*parf[2];
    int_max=parf[1]+20.*parf[2];
    float S_all = g1->Integral(int_min,int_max)/binsiz;
    
    

    float test_sall =  parf[0] * parf[2] * sqrt(acos(-1)) / binsiz; 
    
    cout<<"signal all: "<< S_all << " "<< test_sall <<endl; 
    
    float Serr_all = errparf[0]/ parf[0] * S_all; 
    


    res[0] = S_all; 
    res[1] = Serr_all; 

    res[2] = parf[1]; 
    res[3] = errparf[1];
    
    res[4] = parf[2]; 
    res[5] = errparf[2];

    res[6] = SB; 
    res[7] = SBerr; 
    


    total->SetLineWidth(3);
    
   total->SetLineColor(kBlue);

   p4bkgfin->SetLineWidth(3);
   
   p4bkgfin->SetLineColor(kRed);
   mh1->DrawCopy("sep");

   //   total->SetRange(0.07,0.185);
   //    p4bkgfin->SetRange(0.07,0.185);
   total->Draw("same");
   p4bkgfin->SetLineStyle(kDashed);
   p4bkgfin->Draw("same");   

   TLatex l;
   
   //   l.SetTextSize(0.06);
   l.SetTextSize(0.05);
   
   
   l.SetTextColor(1);
   l.SetNDC();
   
  
   float sigma = parf[2]/ parf[1]*100; 
   float sigmaerr = errparf[2]/ parf[1]*100; 
   char *sigma_name = new char[50]; 
   if(sigmaerr>0.005)
     sprintf(sigma_name,"#sigma = %3.2f #pm %3.2f %% ",sigma,sigmaerr);
   else sprintf(sigma_name,"#sigma = %3.2f %% ",sigma);
   
   if(posFlag==1){
     l.DrawLatex(0.54,0.75,sigma_name);
   }else if( posFlag==2){
     l.DrawLatex(0.54,0.3,sigma_name);

   }
      
      //  sprintf(sigma_name,"S/B = %3.2f #pm %3.2f ",SB,SBerr);
      //
      sprintf(sigma_name,"S = %2.1f #pm %2.1f",S_all,Serr_all);
	      //
      
      // l.DrawLatex(0.5,0.5,sigma_name);
      
      sprintf(sigma_name,"M = %3.1f #pm %3.1f MeV",parf[1]*1000.,errparf[1]*1000);
      if(posFlag==1){
      l.DrawLatex(0.54,0.82,sigma_name);
      }else if( posFlag==2){
	l.DrawLatex(0.54,0.37,sigma_name);

      }
      ///l.DrawLatex(0.169,470.,"d)");


      c2->Modified();
   c2->Update();
   //   c2->SaveAs("nice_pi0.gif");

   
   
   if( text_x >0 && text_y >0){
    TLatex *   tex = new TLatex(text_x, text_y, texName);
    tex->SetNDC();
    tex->SetTextSize(0.06);
    tex->SetLineWidth(2);
    tex->Draw();
  }
  

   char *filename = new char[1000];

   
   sprintf(filename,"%s/%s.gif",dirName,histName);
   c2->Print(filename);
   sprintf(filename,"%s/%s.C",dirName,histName);
   c2->Print(filename);
   
   // .x pi0_mfitpeak.C ("pi0ana_508030.root","minv_spb",0)
   // .x pi0_mfitpeak.C ("pi0ana_npu.root","minv_bkg",0)  
   // .x pi0_mfitpeak.C ("pi0ana_punormv2.root","minv_spb",0)
}
Ejemplo n.º 22
0
bool PlotManager::saveFakeRate(const string& histName, const string& histTitle,
                               const string& numeHistName, const string& denoHistName)
{
  if ( ! isSetup_ ) return false;
  
  TH1F* numeHist = (TH1F*)(theSrcFile_->Get(numeHistName.c_str()));
  TH1F* denoHist = (TH1F*)(theSrcFile_->Get(denoHistName.c_str()));
  
  // Check validity of objects
  if ( numeHist == 0 || denoHist == 0 ) {
    cerr << "Cannot get object : " << histName << endl;
    return false;
  }

  if ( ! numeHist->IsA()->InheritsFrom("TH1") || 
       ! denoHist->IsA()->InheritsFrom("TH1") ||
       numeHist->IsA()->InheritsFrom("TH2") ||
       denoHist->IsA()->InheritsFrom("TH2") ) {
    return false;
  }
  
  // Check bin size
  if ( numeHist->GetNbinsX() != denoHist->GetNbinsX() ) {
    cerr << "Bin size of two histograms are not same" << endl;
    return false;
  }
  
  // Push to base directory
  string pwd(gDirectory->GetPath());
  
  string newHistPath = dirname(histName);
  string newHistName = basename(histName);

  if ( newHistPath.empty() ) {
    theOutFile_->cd();
  }
  else if ( theOutFile_->cd(newHistPath.c_str()) == kFALSE ) {
    cout << "Cannot find directory, do mkdirs" << endl;
    mkdirs(theOutFile_, newHistPath)->cd();
  }

  // Create new histogram
  TH1F* fakeHist = dynamic_cast<TH1F*>(numeHist->Clone());
  
  // effHist->Divide(denoHist);
  // Set the error to binomial statistics
  int nBinsX = fakeHist->GetNbinsX();
  for(int bin = 1; bin <= nBinsX; bin++) {
    float nNume = numeHist->GetBinContent(bin);
    float nDeno = denoHist->GetBinContent(bin);
    float fakeRate = nDeno==0 ? 0 : 1.0 - nNume/nDeno;
    float err = 0;
    if ( nDeno != 0 && fakeRate <= 1 ) {
      err = sqrt(fakeRate*(1-fakeRate)/nDeno);
    }
    fakeHist->SetBinContent(bin, fakeRate);
    fakeHist->SetBinError(bin, err);
  }

  // Cosmetics
  fakeHist->SetName(newHistName.c_str());
  fakeHist->SetTitle(histTitle.c_str());
  fakeHist->SetMinimum(0.8);
  fakeHist->SetMaximum(1.0);
  fakeHist->GetXaxis()->SetTitle(numeHist->GetXaxis()->GetTitle());
  fakeHist->GetYaxis()->SetTitle("Efficiency");

  // Save histogram
  fakeHist->Write();

  // Pop directory
  gDirectory->cd(pwd.c_str());
                           
  return true;
}
void pbpbEffJpsiSFSysSTA__idx_(double minPt = 6.5, double maxPt = 30.0)   
{
  int Prompt =1; int PutWeight = 1;

  int JpsiCat_ = 1; // 1 : prompt, 2 : non-prompt

  double minRap = 1.6; double maxRap = 2.4;
  minPt = 3.0; maxPt = 30.0;

  bool bDefault = true; // true : default, false : sailor or cowboy

  char cCd[512];
  if(bDefault) sprintf(cCd, "default");

  gROOT->SetStyle("Plain");
  gStyle->SetPalette(1);
  gStyle->SetFrameBorderMode(0);
  gStyle->SetFrameFillColor(0);
  gStyle->SetCanvasColor(0);
  gStyle->SetTitleFillColor(0);
  gStyle->SetStatColor(0);
  gStyle->SetPadBorderSize(0);
  gStyle->SetCanvasBorderSize(0);
  gStyle->SetOptTitle(0); // at least most of the time
  gStyle->SetOptStat(0); // most of the time, sometimes "nemriou" might be useful to display name, 
  //number of entries, mean, rms, integral, overflow and underflow
  gStyle->SetOptFit(0); // set to 1 only if you want to display fit results
  //==================================== Define Histograms====================================================

  //==============================================Define Acc Eff Stuff here===========================================
  // Pt bin sizes
  // 0-1.5, 1.5-3, 3-4.5, 4.5-6, 6-7.5...

  const char *cTrg[5] = {"Bit1", "L1DM0HighQ", "L2Mu3NHitQ", "L3Mu3", "L3DMOpen"};
  //int iTrg = 0;
  TFile *outfile;
  char tmp_output[512];
  if(JpsiCat_ == 1) sprintf(tmp_output,"pbpbPrJpsi_y_%0.1f_%0.1f_pT_%0.1f_%0.1f_HighQ_tnpWgt_pr2.root", minRap, maxRap, minPt, maxPt);
  if(JpsiCat_ == 2) sprintf(tmp_output,"pbpbPrJpsi_y_%0.1f_%0.1f_pT_%0.1f_%0.1f_HighQ_tnpWgt_npr2.root", minRap, maxRap, minPt, maxPt);
  outfile =new TFile(tmp_output, "Recreate");
  TH1F *hGenCent = new TH1F("hGenCent",";Centrality (%);Weighted Counts",40,0,40);
  TH1F *hRecCent = new TH1F("hRecCent",";Centrality (%);Weighted Counts",40,0,40);
  hGenCent->Sumw2();
  hRecCent->Sumw2();

  for(int iSpec = 1; iSpec < 2; iSpec++){

    ////const int nCentBins = 11; // Non-prompt 
    ////const int nCentBins = 14; // Prompt
    const int nCentBins = 10; // Non-prompt (60-100)
    //const int nCentBins = 13; // Prompt (60-100)
    const int nPtBins = 3;
    const int nRapBins = 6;
    const int ndPhiBins = 8;
    //const int ndPhiBins = 4;
    const int ndPhi2Bins = 8;
    const int nPhiBins = 8;
    const int nFiles = 6;
    //if(JpsiCat_ == 2) nCentBins = 11;
    // more bins 0-10,10-20,20-30,30-40,40-50,50-70,70-100
    // cent bins : 0-5, 5-10, 10-15, 15-20, 20-25, 25-30, 30-35, 35-40, 40-45, 45-50, 50-55, 55-60, 60-70, 70-100
    ////double ct_bound[nCentBins+1] = {0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 28, 40};
    //double ct_bound[nCentBins+1] = {0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 40}; // Prompt (60-100)
    double ct_bound[nCentBins+1] = {0, 2, 4, 6, 8, 10, 12, 16, 20, 24, 40}; // NonPrompt (60-100)
    double ct_bound2[nCentBins+1] = {0.0};
    for(int ict = 0; ict < nCentBins+1; ict++){
      ct_bound2[ict] = ct_bound[ict]*2.5;
    }
    double xct_bound[nCentBins] = {0.0};
    //double pt_bound[nPtBins+1] = {0.0, 3.0, 6.5};
    // pT bins : 6.5-7.5, 7.5-8.5, 8.5-9.5, 9.5-10.5, 10.5-11.5, 11.5-12.5, 12.5-14.5, 14.5-16.5, 16.5-20.0, 20.0-30.0
    double pt_bound[nPtBins+1] = {3.0, 4.5, 5.5, 6.5};
    double xpt_bound[nPtBins] = {0.0};
    // rap bins : 0.0-0.3, 0.3-0.6, 0.6-0.9, 0.9-1.2, 1.2-1.5, 1.5-1.8, 1.8-2.1, 2.1-2.4
    double rap_bound[nRapBins+1] = {0.0, 0.4, 0.8, 1.2, 1.6, 2.0, 2.4};
    double xrap_bound[nRapBins] = {0.0};
    double dphi_bound[ndPhiBins+1] = {0.0, TMath::Pi()/16, 2*TMath::Pi()/16, 3*TMath::Pi()/16, 4*TMath::Pi()/16, 5*TMath::Pi()/16, 6*TMath::Pi()/16, 7*TMath::Pi()/16, 8*TMath::Pi()/16};
    double xdphi_bound[ndPhiBins] = {0.0};
    double phi_bound[nPhiBins+1] = {-4*TMath::Pi()/4, -3*TMath::Pi()/4, -2*TMath::Pi()/4, -1*TMath::Pi()/4,0.0, TMath::Pi()/4, 2*TMath::Pi()/4, 3*TMath::Pi()/4, TMath::Pi()};
    double xphi_bound[nPhiBins] = {0.0};
    double dphi2_bound[ndPhi2Bins+1] = {0.0, TMath::Pi()/16, 2*TMath::Pi()/16, 3*TMath::Pi()/16, 4*TMath::Pi()/16, 5*TMath::Pi()/16, 6*TMath::Pi()/16, 7*TMath::Pi()/16, 8*TMath::Pi()/16};
    double xdphi2_bound[ndPhi2Bins] = {0.0};

    const char *cSp[6] = {"Cents","Pts","Raps","Phi","dPhi","gdPhi"};
    char OutTextFile[100];
    if(JpsiCat_ == 1) sprintf(OutTextFile,"eff_HighPt_%s_%s_%s_y_%0.1f_%0.1f_pT_%0.1f_%0.1f_pr.tex", cSp[iSpec], cCd, cTrg[0], minRap, maxRap, minPt, maxPt);
    if(JpsiCat_ == 2) sprintf(OutTextFile,"eff_HighPt_%s_%s_%s_y_%0.1f_%0.1f_pT_%0.1f_%0.1f_npr.tex", cSp[iSpec], cCd, cTrg[0], minRap, maxRap, minPt, maxPt);
    //sprintf(OutTextFile,"eff_HighPt_%s_%s_%s.tex", cSp[iSpec], cCd, cTrg[iCat]);
    ofstream dataFile(Form(OutTextFile));

    char tmp_start[512];
    sprintf(tmp_start,"%%%% Getting Efficiency starts, Category : %s !!!!! %%%%%", cCd);  
    cout<< tmp_start << endl;
    //dataFile<< tmp_start << endl;

    // x, y, z - axis 
    //dataFile<<""<<endl;
    //dataFile<<"xaxis of Cent"<<endl;
    for(int i = 0; i < nCentBins; i++){
      if(i == (nCentBins-1)){
        xct_bound[i] = ct_bound[i-4] + (ct_bound[i-1]-ct_bound[i-4])/2;
        //cout<<"xct_bound["<<i<<"] : "<<xct_bound[i]<<endl;
        //dataFile<<"xct_bound["<<i<<"] : "<<xct_bound[i]<<endl;
      }else{
        xct_bound[i] = ct_bound[i] + (ct_bound[i+1]-ct_bound[i])/2;
        //cout<<"xct_bound["<<i<<"] : "<<xct_bound[i]<<endl;
        //dataFile<<"xct_bound["<<i<<"] : "<<xct_bound[i]<<endl;
      }
    }
    //dataFile<<""<<endl;
    //dataFile<<"xaxis of pT"<<endl;
    for(int i = 0; i < nPtBins; i++){
      xpt_bound[i] = pt_bound[i] + (pt_bound[i+1]-pt_bound[i])/2;
      //cout<<"xpt_bound["<<i<<"] : "<<xpt_bound[i]<<endl;
      //dataFile<<"xpt_bound["<<i<<"] : "<<xpt_bound[i]<<endl;
    }
    //dataFile<<""<<endl;
    //dataFile<<"xaxis of rap"<<endl;
    for(int i = 0; i < nRapBins; i++){
      xrap_bound[i] = rap_bound[i] + (rap_bound[i+1]-rap_bound[i])/2;
      //cout<<"xrap_bound["<<i<<"] : "<<xrap_bound[i]<<endl;
      //dataFile<<"xrap_bound["<<i<<"] : "<<xrap_bound[i]<<endl;
    }
    //dataFile<<""<<endl;
    //dataFile<<"xaxis of dphi"<<endl;
    for(int i = 0; i < ndPhiBins; i++){
      xdphi_bound[i] = dphi_bound[i] + (dphi_bound[i+1]-dphi_bound[i])/2;
      //cout<<"xdphi_bound["<<i<<"] : "<<xdphi_bound[i]<<endl;
      //dataFile<<"xdphi_bound["<<i<<"] : "<<xdphi_bound[i]<<endl;
    }
    //dataFile<<""<<endl;
    //dataFile<<"xaxis of phi"<<endl;
    for(int i = 0; i < nPhiBins; i++){
      xphi_bound[i] = phi_bound[i] + (phi_bound[i+1]-phi_bound[i])/2;
      //cout<<"xphi_bound["<<i<<"] : "<<xphi_bound[i]<<endl;
      //dataFile<<"xphi_bound["<<i<<"] : "<<xphi_bound[i]<<endl;
    }
    //dataFile<<""<<endl;
    //dataFile<<"xaxis of dphi2"<<endl;
    for(int i = 0; i < ndPhi2Bins; i++){
      xdphi2_bound[i] = dphi2_bound[i] + (dphi2_bound[i+1]-dphi2_bound[i])/2;
      //cout<<"xdphi2_bound["<<i<<"] : "<<xdphi2_bound[i]<<endl;
      //dataFile<<"xdphi2_bound["<<i<<"] : "<<xdphi2_bound[i]<<endl;
    }

    int nBins_tmp = 0;
    if(iSpec == 0) { nBins_tmp = nCentBins; }
    if(iSpec == 1) { nBins_tmp = nPtBins; }
    if(iSpec == 2) { nBins_tmp = nRapBins; }
    if(iSpec == 3) { nBins_tmp = nPhiBins; }
    if(iSpec == 4) { nBins_tmp = ndPhiBins; }
    if(iSpec == 5) { nBins_tmp = ndPhi2Bins; }
    const int nBins = nBins_tmp;

    TH1F *hTempMass = new TH1F("hTempMass","",100, 2.0, 4.0);
    TH1F *hGenDiMuonf[nFiles][nBins];
    TH1F *hRecoDiMuonf[nFiles][nBins];
    TH1F *hGenDiMuon[nBins];
    TH1F *hRecoDiMuon[nBins];
    double genNo[nBins];
    double genErr[nBins];
    double recoNo[nBins];
    double recoErr[nBins];
    double eff[nBins];
    double effErr[nBins];
    for(int fl = 0; fl < nFiles; fl++){
      for(int i = 0; i < nBins; i++){
        hGenDiMuonf[fl][i] = (TH1F*)hTempMass->Clone();
        hRecoDiMuonf[fl][i] = (TH1F*)hTempMass->Clone();
        hGenDiMuon[i] = (TH1F*)hTempMass->Clone();
        hRecoDiMuon[i] = (TH1F*)hTempMass->Clone();
        hGenDiMuonf[fl][i]->Sumw2();
        hRecoDiMuonf[fl][i]->Sumw2();
        hGenDiMuon[i]->Sumw2();
        hRecoDiMuon[i]->Sumw2();
      }
    }

    char fileName[10][512];
    //scales for different pT bins
    double scale[6]={1.758e-07, 1.46074e-07, 2.58269e-08, 5.4948e-09, 1.63265e-09, 7.70795e-10};
    if(PutWeight==0){scale[0]=(1);scale[1]=(1);scale[2]=(1);scale[3]=(1);scale[4]=(1);scale[5]=(1);}

    // loop for pT
    cout<<"================================="<<endl;
    sprintf(fileName[0],"/Users/dmoon/Dropbox/Analysis/HiMC/EffStudy/gRpAngRootFiles_Regit_Pro2/HiDiMuonAna_Prompt_RegIt_MC_20131006_Pt_0003.root");
    sprintf(fileName[1],"/Users/dmoon/Dropbox/Analysis/HiMC/EffStudy/gRpAngRootFiles_Regit_Pro2/HiDiMuonAna_Prompt_RegIt_MC_20131006_Pt_0306.root");
    sprintf(fileName[2],"/Users/dmoon/Dropbox/Analysis/HiMC/EffStudy/gRpAngRootFiles_Regit_Pro2/HiDiMuonAna_Prompt_RegIt_MC_20131006_Pt_0609.root");
    sprintf(fileName[3],"/Users/dmoon/Dropbox/Analysis/HiMC/EffStudy/gRpAngRootFiles_Regit_Pro2/HiDiMuonAna_Prompt_RegIt_MC_20131006_Pt_0912.root");
    sprintf(fileName[4],"/Users/dmoon/Dropbox/Analysis/HiMC/EffStudy/gRpAngRootFiles_Regit_Pro2/HiDiMuonAna_Prompt_RegIt_MC_20131006_Pt_1215.root");
    sprintf(fileName[5],"/Users/dmoon/Dropbox/Analysis/HiMC/EffStudy/gRpAngRootFiles_Regit_Pro2/HiDiMuonAna_Prompt_RegIt_MC_20131006_Pt_1530.root");

    TFile *infile;
    TTree *tree;
    TTree *gentree;

    for(int ifile = 0; ifile < nFiles; ifile++){
      infile=new TFile(fileName[ifile],"R");
      tree=(TTree*)infile->Get("SingleMuonTree");
      gentree=(TTree*)infile->Get("SingleGenMuonTree");
      //Event variables
      int eventNb,runNb,lumiBlock, gbin, rbin;
      int hbit1;
      double zVtx;
      //Jpsi Variables
      Double_t JpsiMass,JpsiPt,JpsiRap, JpsiCharge;
      Double_t JpsiVprob;
      Double_t JpsiPhi;
      Double_t JpsiEta;
      Double_t JpsiPsi[38];
      Double_t JpsiGenPsi;
      //2.) muon variables RECO                                                                       
      double muPosPx, muPosPy, muPosPz,  muPosEta, muPosPt, muPosP, muPosPhi;
      double muNegPx, muNegPy, muNegPz,  muNegEta, muNegPt, muNegP, muNegPhi;
      //(1).Positive Muon                                     
      double muPos_nchi2In, muPos_dxy, muPos_dz, muPos_nchi2Gl;
      int muPos_found, muPos_pixeLayers, muPos_nValidMuHits,muPos_arbitrated,muPos_TMOneST,muPos_trkLayMeas;
      bool muPos_matches,muPos_tracker;
      int muPos_Trigger2, muPos_Trigger10;
      int muPos_Trigger4, muPos_Trigger12, muPos_Trigger13;
      int muPos_Trigger21, muPos_Trigger22;
      //(2).Negative Muon                                     
      double muNeg_nchi2In, muNeg_dxy, muNeg_dz, muNeg_nchi2Gl;
      int muNeg_found, muNeg_pixeLayers, muNeg_nValidMuHits,muNeg_arbitrated,muNeg_TMOneST,muNeg_trkLayMeas;
      bool muNeg_matches,muNeg_tracker;
      int muNeg_Trigger2, muNeg_Trigger10;
      int muNeg_Trigger4, muNeg_Trigger12, muNeg_Trigger13;
      int muNeg_Trigger21, muNeg_Trigger22;

      //Gen Level variables
      //Gen PrJpsi Variables
      double GenJpsiMass, GenJpsiPt, GenJpsiRap;
      double GenJpsiPx, GenJpsiPy, GenJpsiPz;
      double GenJpsiPhi;
      double GenJpsiEta;
      double GenJpsiPsi;
      //2.) Gen muon variables 
      double GenmuPosPx, GenmuPosPy, GenmuPosPz,  GenmuPosEta, GenmuPosPt, GenmuPosPhi;
      double GenmuNegPx, GenmuNegPy, GenmuNegPz,  GenmuNegEta, GenmuNegPt, GenmuNegPhi;

      //Event variables
      tree->SetBranchAddress("eventNb",&eventNb);
      tree->SetBranchAddress("runNb",&runNb);
      tree->SetBranchAddress("lumiBlock",&lumiBlock);
      tree->SetBranchAddress("hbit1",&hbit1);
      tree->SetBranchAddress("zVtx",&zVtx);

      //Jpsi Variables
      tree->SetBranchAddress("JpsiCharge",&JpsiCharge);
      tree->SetBranchAddress("JpsiMass",&JpsiMass);
      tree->SetBranchAddress("JpsiPt",&JpsiPt);
      tree->SetBranchAddress("JpsiPhi",&JpsiPhi);
      tree->SetBranchAddress("JpsiEta",&JpsiEta);
      tree->SetBranchAddress("JpsiPsi",&JpsiPsi);
      tree->SetBranchAddress("JpsiGenPsi",&JpsiGenPsi);
      tree->SetBranchAddress("JpsiRap",&JpsiRap);
      tree->SetBranchAddress("JpsiVprob",&JpsiVprob);
      tree->SetBranchAddress("rbin",&rbin);

      //muon variable
      tree->SetBranchAddress("muPosPx",&muPosPx);
      tree->SetBranchAddress("muPosPy",&muPosPy);
      tree->SetBranchAddress("muPosPz",&muPosPz);
      tree->SetBranchAddress("muPosEta",&muPosEta);
      tree->SetBranchAddress("muPosPhi",&muPosPhi);
      tree->SetBranchAddress("muNegPx", &muNegPx);
      tree->SetBranchAddress("muNegPy", &muNegPy);
      tree->SetBranchAddress("muNegPz", &muNegPz);
      tree->SetBranchAddress("muNegEta", &muNegEta);
      tree->SetBranchAddress("muNegPhi", &muNegPhi);


      //1). Positive Muon
      tree->SetBranchAddress("muPos_nchi2In", &muPos_nchi2In);
      tree->SetBranchAddress("muPos_dxy", &muPos_dxy);
      tree->SetBranchAddress("muPos_dz", &muPos_dz);
      tree->SetBranchAddress("muPos_nchi2Gl", &muPos_nchi2Gl);
      tree->SetBranchAddress("muPos_found", &muPos_found);
      tree->SetBranchAddress("muPos_pixeLayers", &muPos_pixeLayers);
      tree->SetBranchAddress("muPos_nValidMuHits", &muPos_nValidMuHits);
      tree->SetBranchAddress("muPos_matches", &muPos_matches);
      tree->SetBranchAddress("muPos_tracker", &muPos_tracker);
      tree->SetBranchAddress("muPos_arbitrated", &muPos_arbitrated);
      tree->SetBranchAddress("muPos_TMOneST", &muPos_TMOneST);
      tree->SetBranchAddress("muPos_trkLayMeas", &muPos_trkLayMeas);
      tree->SetBranchAddress("muPos_Trigger2", &muPos_Trigger2);
      tree->SetBranchAddress("muPos_Trigger21", &muPos_Trigger21);
      tree->SetBranchAddress("muPos_Trigger22", &muPos_Trigger22);
      tree->SetBranchAddress("muPos_Trigger4", &muPos_Trigger4);
      tree->SetBranchAddress("muPos_Trigger10", &muPos_Trigger10);
      tree->SetBranchAddress("muPos_Trigger12", &muPos_Trigger12);
      tree->SetBranchAddress("muPos_Trigger13", &muPos_Trigger13);

      //2). Negative Muon                                                                            
      tree->SetBranchAddress("muNeg_nchi2In", &muNeg_nchi2In);
      tree->SetBranchAddress("muNeg_dxy", &muNeg_dxy);
      tree->SetBranchAddress("muNeg_dz", &muNeg_dz);
      tree->SetBranchAddress("muNeg_nchi2Gl", &muNeg_nchi2Gl);
      tree->SetBranchAddress("muNeg_found", &muNeg_found);
      tree->SetBranchAddress("muNeg_pixeLayers", &muNeg_pixeLayers);
      tree->SetBranchAddress("muNeg_nValidMuHits", &muNeg_nValidMuHits);
      tree->SetBranchAddress("muNeg_matches", &muNeg_matches);
      tree->SetBranchAddress("muNeg_tracker", &muNeg_tracker);
      tree->SetBranchAddress("muNeg_arbitrated", &muNeg_arbitrated);
      tree->SetBranchAddress("muNeg_TMOneST", &muNeg_TMOneST);
      tree->SetBranchAddress("muNeg_trkLayMeas", &muNeg_trkLayMeas);
      tree->SetBranchAddress("muNeg_Trigger2", &muNeg_Trigger2);
      tree->SetBranchAddress("muNeg_Trigger21", &muNeg_Trigger21);
      tree->SetBranchAddress("muNeg_Trigger22", &muNeg_Trigger22);
      tree->SetBranchAddress("muNeg_Trigger4", &muNeg_Trigger4);
      tree->SetBranchAddress("muNeg_Trigger10", &muNeg_Trigger10);
      tree->SetBranchAddress("muNeg_Trigger12", &muNeg_Trigger12);
      tree->SetBranchAddress("muNeg_Trigger13", &muNeg_Trigger13);
      //====================================Gen Variables=========================================================
      //Gen Jpsi Variables
      gentree->SetBranchAddress("GenJpsiMass",   &GenJpsiMass);
      gentree->SetBranchAddress("GenJpsiPt",     &GenJpsiPt);
      gentree->SetBranchAddress("GenJpsiPhi",    &GenJpsiPhi);
      gentree->SetBranchAddress("GenJpsiPsi",    &GenJpsiPsi);
      gentree->SetBranchAddress("GenJpsiRap",    &GenJpsiRap);
      gentree->SetBranchAddress("GenJpsiEta",    &GenJpsiEta);
      gentree->SetBranchAddress("GenJpsiPx",     &GenJpsiPx);
      gentree->SetBranchAddress("GenJpsiPy",     &GenJpsiPy);
      gentree->SetBranchAddress("GenJpsiPz",     &GenJpsiPz);
      gentree->SetBranchAddress("gbin",          &gbin);
      //muon variable
      gentree->SetBranchAddress("GenmuPosPx",    &GenmuPosPx);
      gentree->SetBranchAddress("GenmuPosPy",    &GenmuPosPy);
      gentree->SetBranchAddress("GenmuPosPz",    &GenmuPosPz);
      gentree->SetBranchAddress("GenmuPosEta",   &GenmuPosEta);
      gentree->SetBranchAddress("GenmuPosPhi",   &GenmuPosPhi);
      gentree->SetBranchAddress("GenmuNegPx",    &GenmuNegPx);
      gentree->SetBranchAddress("GenmuNegPy",    &GenmuNegPy);
      gentree->SetBranchAddress("GenmuNegPz",    &GenmuNegPz);
      gentree->SetBranchAddress("GenmuNegEta",   &GenmuNegEta);
      gentree->SetBranchAddress("GenmuNegPhi",   &GenmuNegPhi);

      //====================================================== Gen tree loop ================================================
      int NAccep=0;
      int nGenEntries=gentree->GetEntries();
      cout<<" Total Entries in GenLevel Tree for pT range: "<<fileName[ifile]<<"  "<<   nGenEntries<< " ==============="<<endl;

      for(int iGen=0; iGen< nGenEntries; iGen++)  {        
        //cout<<"i : "<<i<<endl;
        if(!(gentree->GetEntry(iGen))) continue;
        //cout<<" gentree ("<<i<<")"<<endl;
        //Only printing 
        if(iGen%10000==0){
          //cout<<" processing record "<<iGen<<"/"<<nGenEntries<<endl;
          //cout<<" Mass "<< GenJpsiMass<< " pT "<< GenJpsiPt << " Y " <<GenJpsiRap<<endl;
        }

        bool GenPosIn=0, GenNegIn=0;
        GenmuPosPt= TMath::Sqrt(GenmuPosPx*GenmuPosPx + GenmuPosPy*GenmuPosPy); 
        GenmuNegPt= TMath::Sqrt(GenmuNegPx*GenmuNegPx + GenmuNegPy*GenmuNegPy); 

        if(IsAccept(GenmuPosPt, GenmuPosEta)) {GenPosIn=1;}
        if(IsAccept(GenmuNegPt, GenmuNegEta)) {GenNegIn=1;}

        double GenCenWeight =0, GenWeight =0;
        GenCenWeight=FindCenWeight(gbin);   
        GenWeight=GenCenWeight*scale[ifile];

        hGenCent->Fill(gbin,GenWeight);

        int AccJpsi = 0;
        //if(GenJpsiPt < 6.5) continue;
        if((GenJpsiPt >= minPt && GenJpsiPt <= maxPt && fabs(GenJpsiRap) >= minRap && fabs(GenJpsiRap) <= maxRap && 
              GenPosIn == 1 && GenNegIn == 1 && GenJpsiMass > 2.0 && GenJpsiMass < 4.0)) {AccJpsi = 1;}

        if((GenPosIn ==1 && GenNegIn==1)) NAccep++;

        if(PutWeight==0) GenWeight=1; 

        //adding pT of all pt bins to see diss is cont

        //cout<<"1. GenJpsiPt : "<<GenJpsiPt<<", GenJpsiEta : "<<GenJpsiEta<<", GenJpsiRap : "<<GenJpsiRap<<", |GenJpsiPsi| : "<<TMath::Abs(GenJpsiPsi)<<endl;
        //cout<<"1. GenPosIn : "<<GenPosIn<<", GenNegIn : "<<GenNegIn<<endl;
        double vars = 0.0, bin1 = 0.0, bin2 = 0.0;
        if(iSpec == 0) vars = gbin;
        if(iSpec == 1) vars = GenJpsiPt;
        if(iSpec == 2) vars = fabs(GenJpsiRap);
        if(iSpec == 3) vars = GenJpsiPhi;
        if(iSpec == 4) vars = fabs(GenJpsiPsi);
        if(iSpec == 5) vars = fabs(GenJpsiPsi);
        for(int i = 0; i < nBins; i++){
          if(iSpec == 0){
            bin1 = ct_bound[i]; bin2 = ct_bound[i+1];
            if( (AccJpsi==1) && (vars >= bin1 && vars < bin2) && GenJpsiPt >= minPt && GenJpsiPt <= maxPt && fabs(GenJpsiRap) >= minRap && fabs(GenJpsiRap) < maxRap ) {
              hGenDiMuonf[ifile][i]->Fill(GenJpsiMass,GenWeight);
            }
          }
          if(iSpec == 1){
            bin1 = pt_bound[i]; bin2 = pt_bound[i+1];
            if( (AccJpsi==1) && (vars >= bin1 && vars < bin2) && gbin >= 0 && gbin <= 40 && fabs(GenJpsiRap) >= minRap && fabs(GenJpsiRap) < maxRap ) {
              hGenDiMuonf[ifile][i]->Fill(GenJpsiMass,GenWeight);
            }
          }
          if(iSpec == 2){
            bin1 = rap_bound[i]; bin2 = rap_bound[i+1];
            if( (AccJpsi==1) && (vars >= bin1 && vars < bin2) && gbin >= 0 && gbin <= 40 && GenJpsiPt >= minPt && GenJpsiPt < maxPt) {
              hGenDiMuonf[ifile][i]->Fill(GenJpsiMass,GenWeight);
            }
          }
          if(iSpec == 3){
            bin1 = phi_bound[i]; bin2 = phi_bound[i+1];
            if( (AccJpsi==1) && (vars >= bin1 && vars < bin2) && gbin >= 0 && gbin <= 40 && GenJpsiPt >= minPt && GenJpsiPt < maxPt && fabs(GenJpsiRap) < maxRap) {
              hGenDiMuonf[ifile][i]->Fill(GenJpsiMass,GenWeight);
            }
          }
          if(iSpec == 4){
            bin1 = dphi_bound[i]; bin2 = dphi_bound[i+1];
            if( (AccJpsi==1) && (vars >= bin1 && vars < bin2) && gbin >= 0 && gbin <= 40 && GenJpsiPt >= minPt && GenJpsiPt < maxPt && fabs(GenJpsiRap) < maxRap) {
              hGenDiMuonf[ifile][i]->Fill(GenJpsiMass,GenWeight);
            }
          }
          if(iSpec == 5){
            bin1 = dphi2_bound[i]; bin2 = dphi2_bound[i+1];
            if( (AccJpsi==1) && (vars >= bin1 && vars < bin2) && gbin >= 0 && gbin <= 40 && GenJpsiPt >= minPt && GenJpsiPt < maxPt && fabs(GenJpsiRap) < maxRap) {
              hGenDiMuonf[ifile][i]->Fill(GenJpsiMass,GenWeight);
            }
          }
        }
      }//gen loop end

      //cout<<" accepted no "<< NAccep<<endl;

      //=============== Rec Tree Loop ==============================================================================

      int nRecEntries=tree->GetEntries();
      cout<<"Total Entries in reconstructed Tree for pT range "<<fileName[ifile]<<"  "<<nRecEntries<< "====="<<endl;
      for(int iRec=0; iRec<nRecEntries; iRec++)  {     
        tree->GetEntry(iRec);
        //Only printing 
        if(iRec%10000==0){
          //cout<<" processing record "<<iRec<<"/"<<nRecEntries<<endl;
          //cout<<" processing Run  " <<runNb <<" event "<<eventNb<<" lum block "<<lumiBlock<<endl;    
          //cout<<" Mass "<< JpsiMass<< " pT "<< JpsiPt << " Y " <<JpsiRap<<"  "<<JpsiVprob<<" charge "<<JpsiCharge<<" rbin "<<rbin<<endl; 
        }
        bool PosPass=0, NegPass=0, AllCut=0 ,PosIn=0, NegIn=0;
        muPosPt= TMath::Sqrt(muPosPx*muPosPx + muPosPy*muPosPy); 
        muPosP = TMath::Sqrt(muPosPx*muPosPx + muPosPy*muPosPy+ muPosPz*muPosPz); 
        muNegPt= TMath::Sqrt(muNegPx*muNegPx + muNegPy*muNegPy); 
        muNegP = TMath::Sqrt(muNegPx*muNegPx + muNegPy*muNegPy +muNegPz*muNegPz); 


        double tnpWgt1 = 0.0, tnpWgt2 = 0.0;
        double staWgt1 = 0.0, staWgt2 = 0.0;

        double x = 0.0;
        if(fabs(muPosEta) < 0.9){
          x = muPosPt;
          tnpWgt1 = tnpSF1->Eval(x);
        }else if(fabs(muPosEta) < 1.6){
          x = muPosPt;
          tnpWgt1 = tnpSF2->Eval(x);
        }else if(fabs(muPosEta) < 2.1){
          x = muPosPt;
          tnpWgt1 = tnpSF3->Eval(x);
        }else{
          x = muPosPt;
          tnpWgt1 = tnpSF4->Eval(x);
        }

        if(fabs(muNegEta) < 0.9){
          x = muNegPt;
          tnpWgt2 = tnpSF1->Eval(x);
        }else if(fabs(muNegEta) < 1.6){
          x = muNegPt;
          tnpWgt2 = tnpSF2->Eval(x);
        }else if(fabs(muNegEta) < 2.1){
          x = muNegPt;
          tnpWgt2 = tnpSF3->Eval(x);
        }else{
          x = muNegPt;
          tnpWgt2 = tnpSF4->Eval(x);
        }

        double xta = 0.0;
        if(fabs(muPosEta) < 1.6){
          xta = muPosPt;
          staWgt1 = fun1->Eval(xta);
        }else{
          xta = muPosPt;
          staWgt1 = fun2->Eval(xta);
        }

        if(fabs(muNegEta) < 1.6){
          xta = muNegPt;
          staWgt2 = fun1->Eval(xta);
        }else{
          xta = muNegPt;
          staWgt2 = fun2->Eval(xta);
        }

        double RecCenWeight=0,RecWeight=0;
        RecCenWeight=FindCenWeight(rbin);   
        RecWeight=RecCenWeight*scale[ifile]*tnpWgt1*tnpWgt2*staWgt1*staWgt2;


        hRecCent->Fill(gbin,RecWeight);

        if(IsAccept(muPosPt, muPosEta)){PosIn=1;}
        if(IsAccept(muNegPt, muNegEta)){NegIn=1;}

        int AccJpsi = 0;
        if((JpsiPt >= minPt && JpsiPt <= maxPt && fabs(JpsiRap) >= minRap && fabs(JpsiRap) <= maxRap && PosIn == 1 && NegIn == 1)) {AccJpsi = 1;}

        /*
           cout<<"muPos_pixeLayers : "<<muPos_pixeLayers<<" muPos_nchi2In : "<<muPos_nchi2In
           <<" TMath::Abs(muPos_dxy) : "<<TMath::Abs(muPos_dxy)<<" TMath::Abs(muPos_dz) : "<<TMath::Abs(muPos_dz)
           <<" muPos_trkLayMeas : "<<muPos_trkLayMeas
           <<" muPos_arbitrated : "<<muPos_arbitrated<<" muPos_TMOneST : "<<muPos_TMOneST<<" muPos_tracker : "<<muPos_tracker<<endl;
           cout<<"muNeg_pixeLayers : "<<muNeg_pixeLayers<<" muNeg_nchi2In : "<<muNeg_nchi2In
           <<" TMath::Abs(muNeg_dxy) : "<<TMath::Abs(muNeg_dxy)<<" TMath::Abs(muNeg_dz) : "<<TMath::Abs(muNeg_dz)
           <<" muNeg_trkLayMeas : "<<muNeg_trkLayMeas
           <<" muNeg_arbitrated : "<<muNeg_arbitrated<<" muNeg_TMOneST : "<<muNeg_TMOneST<<" muNeg_tracker : "<<muNeg_tracker<<endl;
           */
        bool mu_Global = ((muPos_nchi2Gl >=0) && (muNeg_nchi2Gl >=0));
        bool mu_Tracker = ((muPos_tracker==1) && (muNeg_tracker==1));

        if(muPos_found > 10 &&
            muPos_pixeLayers > 0 &&
            muPos_nchi2In < 4.0 &&
            TMath::Abs(muPos_dxy) < 3 &&
            TMath::Abs(muPos_dz) < 15 && muPos_nchi2Gl < 20 &&
            muPos_arbitrated==1 &&
            muPos_tracker==1){
          PosPass=1;
        }

        if(muNeg_found > 10 &&
            muNeg_pixeLayers > 0 &&
            muNeg_nchi2In < 4.0 &&
            TMath::Abs(muNeg_dxy) < 3 &&
            TMath::Abs(muNeg_dz) < 15 &&
            muNeg_nchi2Gl < 20 &&
            muNeg_arbitrated==1 &&
            muNeg_tracker==1){
          NegPass=1;
        }

        if(hbit1 == 1 && (muPos_Trigger22==1 && muNeg_Trigger22==1) && (PosIn==1 && NegIn==1) && (PosPass==1 && NegPass==1) && mu_Global && mu_Tracker ){AllCut=1;}

        if(PutWeight==0)RecWeight=1;

        double JpsidPhi = JpsiGenPsi;

        //Eff loop for reco
        double vars = 0.0, bin1 = 0.0, bin2 = 0.0;
        if(iSpec == 0) vars = rbin;
        if(iSpec == 1) vars = JpsiPt;
        if(iSpec == 2) vars = fabs(JpsiRap);
        if(iSpec == 3) vars = JpsiPhi;
        if(iSpec == 4) vars = fabs(JpsidPhi);
        if(iSpec == 5) vars = fabs(JpsiGenPsi);
        if((JpsiCharge == 0) && (JpsiVprob > 0.01) && (JpsiMass >= 2.95 && JpsiMass < 3.25)) {     
          for(int i = 0; i < nBins; i++){
            if(iSpec == 0){
              bin1 = ct_bound[i]; bin2 = ct_bound[i+1];
              if( AccJpsi == 1 && (AllCut == 1) && (vars >= bin1 && vars < bin2) && JpsiPt >= minPt && JpsiPt <= maxPt && fabs(JpsiRap) >= minRap && fabs(JpsiRap) <= maxRap ) {
                hRecoDiMuonf[ifile][i]->Fill(JpsiMass,RecWeight);
              }
            }
            if(iSpec == 1){
              bin1 = pt_bound[i]; bin2 = pt_bound[i+1];
              if( AccJpsi == 1 && (AllCut == 1) && (vars >= bin1 && vars < bin2) && rbin >= 0 && rbin <= 40 && fabs(JpsiRap) >= minRap && fabs(JpsiRap) <= maxRap ) {
                hRecoDiMuonf[ifile][i]->Fill(JpsiMass,RecWeight);
              }
            }
            if(iSpec == 2){ 
              bin1 = rap_bound[i]; bin2 = rap_bound[i+1];
              if( AccJpsi == 1 && (AllCut == 1) && (vars >= bin1 && vars < bin2) && rbin >= 0 && rbin <= 40 && JpsiPt >= minPt && JpsiPt <= maxPt) {
                hRecoDiMuonf[ifile][i]->Fill(JpsiMass,RecWeight);
              }
            }
            if(iSpec == 3){ 
              bin1 = phi_bound[i]; bin2 = phi_bound[i+1];
              if( AccJpsi == 1 && (AllCut == 1) && (vars >= bin1 && vars < bin2) && rbin >= 0 && rbin <= 40 && JpsiPt >= minPt && JpsiPt <= maxPt && fabs(JpsiRap) <=maxRap) {
                hRecoDiMuonf[ifile][i]->Fill(JpsiMass,RecWeight);
              }
            }
            if(iSpec == 4){ 
              bin1 = dphi_bound[i]; bin2 = dphi_bound[i+1];
              if( AccJpsi == 1 && (AllCut == 1) && (vars >= bin1 && vars < bin2) && rbin >= 0 && rbin <= 40 && JpsiPt >= minPt && JpsiPt <= maxPt && fabs(JpsiRap) <=maxRap) {
                hRecoDiMuonf[ifile][i]->Fill(JpsiMass,RecWeight);
              }
            }
            if(iSpec == 5){ 
              bin1 = dphi2_bound[i]; bin2 = dphi2_bound[i+1];
              if( AccJpsi == 1 && (AllCut == 1) && (vars >= bin1 && vars < bin2) && rbin >= 0 && rbin <= 40 && JpsiPt >= minPt && JpsiPt <= maxPt && fabs(JpsiRap) <=maxRap) {
                hRecoDiMuonf[ifile][i]->Fill(JpsiMass,RecWeight);
              }
            }
          }
        }
      } //rec tree loop ends
    }  // file loop ends

    //======================  File loop Starts ============================

    ///////////////////////////////////////////////////////////////////
    cout<< " adding "<<endl;
    TCanvas *c1 = new TCanvas();
    char gtmp[512], gtmp1[512];
    char rtmp[512], rtmp1[512];

    for(int i = 0; i < nBins; i++){
      for(int ifile = 0; ifile < nFiles; ifile++){
        hGenDiMuon[i]->Add(hGenDiMuonf[ifile][i],1);
        hRecoDiMuon[i]->Add(hRecoDiMuonf[ifile][i],1);
      }
      if(iSpec == 0) sprintf(gtmp,"hGenDiMuon_Cent_%1.f_%1.f",ct_bound[i],ct_bound[i+1]);
      if(iSpec == 1) sprintf(gtmp,"hGenDiMuon_Pt_%0.1f_%0.1f",pt_bound[i],pt_bound[i+1]);
      if(iSpec == 2) sprintf(gtmp,"hGenDiMuon_Rap_%0.1f_%0.1f",rap_bound[i],rap_bound[i+1]);
      if(iSpec == 0) sprintf(gtmp1,"plots/Gen/hGenDiMuon_Cent_%1.f_%1.f_%s.png",ct_bound[i],ct_bound[i+1],cCd);
      if(iSpec == 1) sprintf(gtmp1,"plots/Gen/hGenDiMuon_Pt_%0.1f_%0.1f_%s.png",pt_bound[i],pt_bound[i+1],cCd);
      if(iSpec == 2) sprintf(gtmp1,"plots/Gen/hGenDiMuon_Rap_%0.1f_%0.1f_%s.png",rap_bound[i],rap_bound[i+1],cCd);
      if(iSpec == 0) sprintf(rtmp,"hRecDiMuon_Cent_%1.f_%1.f",ct_bound[i],ct_bound[i+1]);
      if(iSpec == 1) sprintf(rtmp,"hRecDiMuon_Pt_%0.1f_%0.1f",pt_bound[i],pt_bound[i+1]);
      if(iSpec == 2) sprintf(rtmp,"hRecDiMuon_Rap_%0.1f_%0.1f",rap_bound[i],rap_bound[i+1]);
      if(iSpec == 0) sprintf(rtmp1,"plots/Rec/hRecDiMuon_Cent_%1.f_%1.f_%s.png",ct_bound[i],ct_bound[i+1],cCd);
      if(iSpec == 1) sprintf(rtmp1,"plots/Rec/hRecDiMuon_Pt_%0.1f_%0.1f_%s.png",pt_bound[i],pt_bound[i+1],cCd);
      if(iSpec == 2) sprintf(rtmp1,"plots/Rec/hRecDiMuon_Rap_%0.1f_%0.1f_%s.png",rap_bound[i],rap_bound[i+1],cCd);
      hGenDiMuon[i]->SetName(gtmp);
      //hGenDiMuon[i]->Write();
      //hGenDiMuon[ipt][irap][idphi]->Draw();
      //c1->SaveAs(gtmp1);
      hRecoDiMuon[i]->SetName(rtmp);
      //hRecoDiMuon[i]->Write();
      //hRecoDiMuon[ipt][irap][idphi]->Draw();
      //c1->SaveAs(rtmp1);
    }

    TH1F *hReco = new TH1F();
    TH1F *hGen = new TH1F();
    hReco->Sumw2();
    hGen->Sumw2();
    int nRecoBins;
    int nGenBins;
    if(iSpec == 0) {hReco = new TH1F("hReco","hReco;Centrality (%);Weighted Yields",nCentBins,ct_bound2); nRecoBins = nCentBins;}
    if(iSpec == 1) {hReco = new TH1F("hReco","hReco;p_{T} GeV/c;Weighted Yields",nPtBins,pt_bound); nRecoBins = nPtBins;}
    if(iSpec == 2) {hReco = new TH1F("hReco","hReco;y;Weighted Yields",nRapBins,rap_bound); nRecoBins = nRapBins;}
    if(iSpec == 3) {hReco = new TH1F("hReco","hReco;#phi;Weighted Yields",nPhiBins,phi_bound); nRecoBins = nPhiBins;}
    if(iSpec == 4) {hReco = new TH1F("hReco","hReco;d#phi;Weighted Yields",ndPhiBins,dphi_bound); nRecoBins = ndPhiBins;}
    if(iSpec == 5) {hReco = new TH1F("hReco","hReco;d#phi;Weighted Yields",ndPhi2Bins,dphi2_bound); nRecoBins = ndPhi2Bins;}

    if(iSpec == 0) {hGen = new TH1F("hGen","hGen;Centrality (%);Weighted Yields",nCentBins,ct_bound2); nGenBins = nCentBins;}
    if(iSpec == 1) {hGen = new TH1F("hGen","hGen;p_{T} GeV/c;Weighted Yields",nPtBins,pt_bound); nGenBins = nPtBins;}
    if(iSpec == 2) {hGen = new TH1F("hGen","hGen;y;Weighted Yields",nRapBins,rap_bound); nGenBins = nRapBins;}
    if(iSpec == 3) {hGen = new TH1F("hGen","hGen;#phi;Weighted Yields",nPhiBins,phi_bound); nGenBins = nPhiBins;}
    if(iSpec == 4) {hGen = new TH1F("hGen","hGen;d#phi;Weighted Yields",ndPhiBins,dphi_bound); nGenBins = ndPhiBins;}
    if(iSpec == 5) {hGen = new TH1F("hGen","hGen;d#phi;Weighted Yields",ndPhi2Bins,dphi2_bound); nGenBins = ndPhi2Bins;}

    cout<<"Starts to calculate efficiency"<<endl;
    //dataFile<<""<<endl;
    //=====================Loop for eff========================================================================================//
    //define stuff here for error on weighted samples
    for(int i = 0; i < nBins; i++){
      int Gbinlow =hGenDiMuon[i]->GetXaxis()->FindBin(2.0);//2.95
      int Gbinhi=hGenDiMuon[i]->GetXaxis()->FindBin(4.0);//2.95
      //int Gbinlow =hGenDiMuon[i]->GetXaxis()->FindBin(2.95);//2.95
      //int Gbinhi=hGenDiMuon[i]->GetXaxis()->FindBin(3.25);//2.95

      int Rbinlow =hRecoDiMuon[i]->GetXaxis()->FindBin(2.95);//2.95
      int Rbinhi=hRecoDiMuon[i]->GetXaxis()->FindBin(3.25);//2.95

      cout<<"Gbinlow : "<<Gbinlow<<", Gbinhi : "<<Gbinhi<<endl;
      cout<<"Rbinlow : "<<Rbinlow<<", Rbinhi : "<<Rbinhi<<endl;

      genNo[i] = hGenDiMuon[i]->IntegralAndError(Gbinlow, Gbinhi, genErr[i]);
      recoNo[i] = hRecoDiMuon[i]->IntegralAndError(Rbinlow, Rbinhi, recoErr[i]);

      //calculate Eff         
      if(genNo[i] == 0 || recoNo[i] == 0) {
        cout<<"No Gen or Reco, # of Gen : "<<genNo[i] <<", # of Reco : "<<recoNo[i]<<endl;
        eff[i] = 0;
        effErr[i] = 0;
      }else{
        eff[i] = recoNo[i]/genNo[i]; 

        double tmpGenNo = genNo[i];
        double tmpGenErr = genErr[i];
        double tmpRecNo = recoNo[i];
        double tmpRecErr = recoErr[i];
        double tmpEff = eff[i];
        double tmpEffErr = 0.0;

        hReco->SetBinContent(i+1,tmpRecNo);
        hReco->SetBinError(i+1,tmpRecErr);
        hGen->SetBinContent(i+1,tmpGenNo);
        hGen->SetBinError(i+1,tmpGenErr);

        //error    
        double tmp_err_s1_1 = (tmpEff * tmpEff)/(tmpGenNo * tmpGenNo);
        double tmp_err_s1_2 = (tmpRecErr * tmpRecErr);
        double tmp_err_cat_s1 = tmp_err_s1_1 * tmp_err_s1_2;


        double tmp_err_s2_1 = ( (1 - tmpEff)*(1 - tmpEff) ) / (tmpGenNo * tmpGenNo);
        double tmp_err_s2_2 = TMath::Abs(( tmpGenErr*tmpGenErr ) - ( tmpRecErr * tmpRecErr));
        double tmp_err_cat_s2 = tmp_err_s2_1 * tmp_err_s2_2;
        tmpEffErr = sqrt( tmp_err_cat_s1 + tmp_err_cat_s2 );

        effErr[i] = tmpEffErr;

        //error without weight
        //dataFile<<" Bin ["<<i<<"] - "<< " Reco Jpsi : "<< tmpRecNo  <<", Gen Jpsi : "<< tmpGenNo <<endl;
        //dataFile<<" Eff ["<<i<<"] - "<< tmpEff <<" Error "<< tmpEffErr <<endl;
        cout<<" Bin ["<<i<<"] - "<< " Reco Jpsi : "<< tmpRecNo  <<", Gen Jpsi : "<< tmpGenNo <<endl;
        cout<<" Eff ["<<i<<"] - "<< tmpEff <<" Error "<< tmpEffErr <<endl;
      }
    }
    TH1F *hEff = new TH1F();
    hEff->Sumw2();
    int nEffBins = 0;
    if(iSpec == 0) {hEff = new TH1F("hEff","hEff;Centrality (%);Efficiency",nCentBins,ct_bound2); nEffBins = nCentBins;}
    if(iSpec == 1) {hEff = new TH1F("hEff","hEff;p_{T} GeV/c;Efficiency",nPtBins,pt_bound); nEffBins = nPtBins;}
    if(iSpec == 2) {hEff = new TH1F("hEff","hEff;y;Efficiency",nRapBins,rap_bound); nEffBins = nRapBins;}
    if(iSpec == 3) {hEff = new TH1F("hEff","hEff;#phi;Efficiency",nPhiBins,phi_bound); nEffBins = nPhiBins;}
    if(iSpec == 4) {hEff = new TH1F("hEff","hEff;d#phi;Efficiency",ndPhiBins,dphi_bound); nEffBins = ndPhiBins;}
    if(iSpec == 5) {hEff = new TH1F("hEff","hEff;d#phi;Efficiency",ndPhi2Bins,dphi2_bound); nEffBins = ndPhi2Bins;}

    for(int i = 0; i < nEffBins; i++){
      hEff->SetBinContent(i+1,eff[i]);
      hEff->SetBinError(i+1,effErr[i]);
      cout<<"Trying to measure Reconstruction eff vs "<<cSp[iSpec]<<endl;
      cout<<"Eff : "<<eff[i]<<", err : "<<effErr[i]<<endl;
      dataFile<<eff[i]<<endl;//", err : "<<effErr[i]<<endl;
      //dataFile<<"Eff : "<<eff[i]<<", err : "<<effErr[i]<<endl;
    }

    outfile->cd();
    hEff->Draw();
    char tmp_histo[512];
    sprintf(tmp_histo,"hEff_%s",cSp[iSpec]);
    char tmp_histo_reco[512];
    sprintf(tmp_histo_reco,"hReco_%s",cSp[iSpec]);
    char tmp_histo_gen[512];
    sprintf(tmp_histo_gen,"hGen_%s",cSp[iSpec]);
    hEff->SetName(tmp_histo);
    hEff->Write();
    hReco->SetName(tmp_histo_reco);
    hReco->Write();
    hGen->SetName(tmp_histo_gen);
    hGen->Write();
    //c1->SaveAs("eff_3D_default_etHFm.png");
    //outfile->Close();
    dataFile<<""<<endl;
    dataFile.close();
  }
  hGenCent->Write();
  hRecCent->Write();
  outfile->Write();
}
void ppEffJpsiSysSFsSTA__idx_()   
{
  double minRap = 0.0;
  double maxRap = 2.4;
  double minPt = 6.5;
  double maxPt = 30.0;

  // if you want to measure low pT, you can set up minRap = 1.6 and minPt = 3.0, maxPt = 6.5;

  gROOT->SetStyle("Plain");
  gStyle->SetPalette(1);
  gStyle->SetFrameBorderMode(0);
  gStyle->SetFrameFillColor(0);
  gStyle->SetCanvasColor(0);
  gStyle->SetTitleFillColor(0);
  gStyle->SetStatColor(0);
  gStyle->SetPadBorderSize(0);
  gStyle->SetCanvasBorderSize(0);
  gStyle->SetOptTitle(0); // at least most of the time
  gStyle->SetOptStat(0); // most of the time, sometimes "nemriou" might be useful to display name, 
  //number of entries, mean, rms, integral, overflow and underflow
  gStyle->SetOptFit(0); // set to 1 only if you want to display fit results
  //==================================== Define Histograms====================================================

  //==============================================Define Acc Eff Stuff here===========================================
  // Pt bin sizes
  // 0-1.5, 1.5-3, 3-4.5, 4.5-6, 6-7.5...

  TFile *outfile;
  char tmp_output[512];
  sprintf(tmp_output,"ppPrJpsi_pT_%0.1f_%0.1f_y_%0.1f_%0.1f_HighQ_tnpWgt.root", minPt, maxPt, minRap, maxRap);
  outfile =new TFile(tmp_output, "Recreate");

  for(int iSpec = 0; iSpec < 2; iSpec++){

    const int nPtBins = 7;
    const int nRapBins = 6; // 6
    const int ndPhiBins = 4;
    double pt_bound[nPtBins+1] = {6.5, 7.5, 8.5, 9.5, 11.0, 13.0, 16.0, 30.0};
    double xpt_bound[nPtBins] = {0.0};
    //double rap_bound[nRapBins+1] = {0.0, 0.3, 0.6, 0.9, 1.2, 1.5, 1.8, 2.1, 2.4};
    double rap_bound[nRapBins+1] = {0.0, 0.4, 0.8, 1.2, 1.6, 2.0, 2.4};
    double xrap_bound[nRapBins] = {0.0};
    double dphi_bound[ndPhiBins+1] = {0.0, TMath::Pi()/8, TMath::Pi()/4, 3*TMath::Pi()/8, TMath::Pi()/2};
    double xdphi_bound[ndPhiBins] = {0.0};

    const char *cSp[2] = {"Pts","Raps"};
    char OutTextFile[100];
    sprintf(OutTextFile,"ppPromp_eff_%s_pT_%0.1f_%0.1f_y_%0.1f_%0.1f_HighQ.tex", cSp[iSpec], minPt, maxPt, minRap, maxRap);
    ofstream dataFile(OutTextFile);
    //ofstream dataFile(Form(OutTextFile));

    cout<< "%%%% Getting Efficiency starts : %s !!!!! %%%%%" << endl;
    //dataFile<< "%%%% Getting Efficiency starts : %s !!!!! %%%%%" << endl;

    // x, y, z - axis 
    //dataFile<<""<<endl;
    //dataFile<<"xaxis of pT"<<endl;
    for(int i = 0; i < nPtBins; i++){
      xpt_bound[i] = pt_bound[i] + (pt_bound[i+1]-pt_bound[i])/2;
      cout<<"xpt_bound["<<i<<"] : "<<xpt_bound[i]<<endl;
      //dataFile<<"xpt_bound["<<i<<"] : "<<xpt_bound[i]<<endl;
    }
    //dataFile<<""<<endl;
    //dataFile<<"xaxis of rap"<<endl;
    for(int i = 0; i < nRapBins; i++){
      xrap_bound[i] = rap_bound[i] + (rap_bound[i+1]-rap_bound[i])/2;
      cout<<"xrap_bound["<<i<<"] : "<<xrap_bound[i]<<endl;
      //dataFile<<"xrap_bound["<<i<<"] : "<<xrap_bound[i]<<endl;
    }
    //dataFile<<""<<endl;
    //dataFile<<"xaxis of dphi"<<endl;
    for(int i = 0; i < ndPhiBins; i++){
      xdphi_bound[i] = dphi_bound[i] + (dphi_bound[i+1]-dphi_bound[i])/2;
      cout<<"xdphi_bound["<<i<<"] : "<<xdphi_bound[i]<<endl;
      //dataFile<<"xdphi_bound["<<i<<"] : "<<xdphi_bound[i]<<endl;
    }

    int nBins_tmp = 0;
    if(iSpec == 0) { nBins_tmp = nPtBins; }
    if(iSpec == 1) { nBins_tmp = nRapBins; }
    const int nBins = nBins_tmp;

    TH1F *hTempMass = new TH1F("hTempMass","",100, 2.0, 4.0);
    TH1F *hGenDiMuon[nBins];
    TH1F *hRecoDiMuon[nBins];
    double genNo[nBins];
    double genErr[nBins];
    double recoNo[nBins];
    double recoErr[nBins];
    double eff[nBins];
    double effErr[nBins];
    for(int i = 0; i < nBins; i++){
      hGenDiMuon[i] = (TH1F*)hTempMass->Clone();
      hRecoDiMuon[i] = (TH1F*)hTempMass->Clone();
      hGenDiMuon[i]->Sumw2();
      hRecoDiMuon[i]->Sumw2();
    }

    char fileName[10][512];

    // loop for pT
    cout<<"==================Prompt PrJpsi================================================"<<endl;

    sprintf(fileName[0],"/Users/dmoon/Dropbox/Analysis/HiMC/EffStudy/gRpAngRootFiles_538_pp/HiDiMuonAna_538_pp_NonPromptJpsi_20140317_Trg21.root");


    TFile *infile;
    TTree *tree;
    TTree *gentree;
    TTree *evttree;

    infile=new TFile(fileName[0],"R");
    tree=(TTree*)infile->Get("SingleMuonTree");
    gentree=(TTree*)infile->Get("SingleGenMuonTree");
    evttree=(TTree*)infile->Get("EventTree");
    //Event variables
    int eventNb,runNb,lumiBlock;
    int hbit1;
    //double vertexZ;
    //double GenvertexZ;
    //Jpsi Variables
    Double_t JpsiMass,JpsiPt,JpsiRap, JpsiCharge;
    Double_t JpsiVprob;
    Double_t JpsiPhi;
    Double_t JpsiEta;
    //2.) muon variables RECO                                                                       
    double muPosPx, muPosPy, muPosPz,  muPosEta, muPosPt, muPosP, muPosPhi;
    double muNegPx, muNegPy, muNegPz,  muNegEta, muNegPt, muNegP, muNegPhi;
    //(1).Positive Muon                                     
    double muPos_nchi2In, muPos_dxy, muPos_dz, muPos_nchi2Gl;
    int muPos_found, muPos_pixeLayers, muPos_nValidMuHits,muPos_arbitrated;
    bool muPos_matches,muPos_tracker;
    int muPos_Trigger10, muPos_Trigger2, muPos_Trigger21, muPos_Trigger22;
    //(2).Negative Muon                                     
    double muNeg_nchi2In, muNeg_dxy, muNeg_dz, muNeg_nchi2Gl;
    int muNeg_found, muNeg_pixeLayers, muNeg_nValidMuHits,muNeg_arbitrated;
    bool muNeg_matches,muNeg_tracker;
    int muNeg_Trigger10, muNeg_Trigger2, muNeg_Trigger21, muNeg_Trigger22;

    //Gen Level variables
    //Gen PrJpsi Variables
    double GenJpsiMass, GenJpsiPt, GenJpsiRap;
    double GenJpsiPx, GenJpsiPy, GenJpsiPz;
    double GenJpsiPhi;
    double GenJpsiEta;
    //2.) Gen muon variables 
    double GenmuPosPx, GenmuPosPy, GenmuPosPz,  GenmuPosEta, GenmuPosPt, GenmuPosPhi;
    double GenmuNegPx, GenmuNegPy, GenmuNegPz,  GenmuNegEta, GenmuNegPt, GenmuNegPhi;
    double zVtx;

    //Event variables
    tree->SetBranchAddress("eventNb",&eventNb);
    tree->SetBranchAddress("runNb",&runNb);
    tree->SetBranchAddress("lumiBlock",&lumiBlock);
    tree->SetBranchAddress("hbit1",&hbit1);
    tree->SetBranchAddress("zVtx",&zVtx);
    //tree->SetBranchAddress("vertexZ",&vertexZ);

    //Jpsi Variables
    tree->SetBranchAddress("JpsiCharge",&JpsiCharge);
    tree->SetBranchAddress("JpsiMass",&JpsiMass);
    tree->SetBranchAddress("JpsiPt",&JpsiPt);
    tree->SetBranchAddress("JpsiPhi",&JpsiPhi);
    tree->SetBranchAddress("JpsiEta",&JpsiEta);
    tree->SetBranchAddress("JpsiRap",&JpsiRap);
    tree->SetBranchAddress("JpsiVprob",&JpsiVprob);

    //muon variable
    tree->SetBranchAddress("muPosPx",&muPosPx);
    tree->SetBranchAddress("muPosPy",&muPosPy);
    tree->SetBranchAddress("muPosPz",&muPosPz);
    tree->SetBranchAddress("muPosEta",&muPosEta);
    tree->SetBranchAddress("muPosPhi",&muPosPhi);
    tree->SetBranchAddress("muNegPx", &muNegPx);
    tree->SetBranchAddress("muNegPy", &muNegPy);
    tree->SetBranchAddress("muNegPz", &muNegPz);
    tree->SetBranchAddress("muNegEta", &muNegEta);
    tree->SetBranchAddress("muNegPhi", &muNegPhi);


    //1). Positive Muon
    tree->SetBranchAddress("muPos_nchi2In", &muPos_nchi2In);
    tree->SetBranchAddress("muPos_dxy", &muPos_dxy);
    tree->SetBranchAddress("muPos_dz", &muPos_dz);
    tree->SetBranchAddress("muPos_nchi2Gl", &muPos_nchi2Gl);
    tree->SetBranchAddress("muPos_found", &muPos_found);
    tree->SetBranchAddress("muPos_pixeLayers", &muPos_pixeLayers);
    tree->SetBranchAddress("muPos_nValidMuHits", &muPos_nValidMuHits);
    tree->SetBranchAddress("muPos_matches", &muPos_matches);
    tree->SetBranchAddress("muPos_tracker", &muPos_tracker);
    tree->SetBranchAddress("muPos_arbitrated", &muPos_arbitrated);
    tree->SetBranchAddress("muPos_Trigger10", &muPos_Trigger10);
    tree->SetBranchAddress("muPos_Trigger2", &muPos_Trigger2);
    tree->SetBranchAddress("muPos_Trigger21", &muPos_Trigger21);
    tree->SetBranchAddress("muPos_Trigger22", &muPos_Trigger22);

    //2). Negative Muon                                                                            
    tree->SetBranchAddress("muNeg_nchi2In", &muNeg_nchi2In);
    tree->SetBranchAddress("muNeg_dxy", &muNeg_dxy);
    tree->SetBranchAddress("muNeg_dz", &muNeg_dz);
    tree->SetBranchAddress("muNeg_nchi2Gl", &muNeg_nchi2Gl);
    tree->SetBranchAddress("muNeg_found", &muNeg_found);
    tree->SetBranchAddress("muNeg_pixeLayers", &muNeg_pixeLayers);
    tree->SetBranchAddress("muNeg_nValidMuHits", &muNeg_nValidMuHits);
    tree->SetBranchAddress("muNeg_matches", &muNeg_matches);
    tree->SetBranchAddress("muNeg_tracker", &muNeg_tracker);
    tree->SetBranchAddress("muNeg_arbitrated", &muNeg_arbitrated);
    tree->SetBranchAddress("muNeg_Trigger10", &muNeg_Trigger10);
    tree->SetBranchAddress("muNeg_Trigger2", &muNeg_Trigger2);
    tree->SetBranchAddress("muNeg_Trigger21", &muNeg_Trigger21);
    tree->SetBranchAddress("muNeg_Trigger22", &muNeg_Trigger22);
    //====================================Gen Variables=========================================================
    //Gen Jpsi Variables
    gentree->SetBranchAddress("GenJpsiMass",   &GenJpsiMass);
    gentree->SetBranchAddress("GenJpsiPt",     &GenJpsiPt);
    gentree->SetBranchAddress("GenJpsiPhi",    &GenJpsiPhi);
    gentree->SetBranchAddress("GenJpsiRap",    &GenJpsiRap);
    gentree->SetBranchAddress("GenJpsiEta",    &GenJpsiEta);
    gentree->SetBranchAddress("GenJpsiPx",     &GenJpsiPx);
    gentree->SetBranchAddress("GenJpsiPy",     &GenJpsiPy);
    gentree->SetBranchAddress("GenJpsiPz",     &GenJpsiPz);
    //muon variable
    gentree->SetBranchAddress("GenmuPosPx",    &GenmuPosPx);
    gentree->SetBranchAddress("GenmuPosPy",    &GenmuPosPy);
    gentree->SetBranchAddress("GenmuPosPz",    &GenmuPosPz);
    gentree->SetBranchAddress("GenmuPosEta",   &GenmuPosEta);
    gentree->SetBranchAddress("GenmuPosPhi",   &GenmuPosPhi);
    gentree->SetBranchAddress("GenmuNegPx",    &GenmuNegPx);
    gentree->SetBranchAddress("GenmuNegPy",    &GenmuNegPy);
    gentree->SetBranchAddress("GenmuNegPz",    &GenmuNegPz);
    gentree->SetBranchAddress("GenmuNegEta",   &GenmuNegEta);
    gentree->SetBranchAddress("GenmuNegPhi",   &GenmuNegPhi);
    //gentree->SetBranchAddress("GenvertexZ",&GenvertexZ);

    //====================================================== Gen tree loop ================================================
    int NAccep=0;
    int nGenEntries=gentree->GetEntries();
    cout<<" Total Entries in GenLevel Tree for pT range: "<<fileName[0]<<"  "<<   nGenEntries<< " ==============="<<endl;

    for(int i=0; i< nGenEntries; i++)  {        
      //cout<<"i : "<<i<<endl;
      if(!(gentree->GetEntry(i))) continue;
      //cout<<" gentree ("<<i<<")"<<endl;
      //Only printing 
      if(i%1000000==0){
        cout<<" processing record "<<i<<"/"<<nGenEntries<<endl;
        //cout<<" Mass "<< GenJpsiMass<< " pT "<< GenJpsiPt << " Y " <<GenJpsiRap<<endl;
      }

      bool GenPosIn=0, GenNegIn=0;
      GenmuPosPt= TMath::Sqrt(GenmuPosPx*GenmuPosPx + GenmuPosPy*GenmuPosPy); 
      GenmuNegPt= TMath::Sqrt(GenmuNegPx*GenmuNegPx + GenmuNegPy*GenmuNegPy); 

      if(IsAccept(GenmuPosPt, GenmuPosEta)) {GenPosIn=1;}
      if(IsAccept(GenmuNegPt, GenmuNegEta)) {GenNegIn=1;}

      int AccJpsi = 0;
      //if(GenJpsiPt < 6.5) continue;
      if((GenJpsiPt >= minPt && GenJpsiPt <= maxPt && fabs(GenJpsiRap) >= minRap && TMath::Abs(GenJpsiRap) <= maxRap && GenPosIn == 1 && GenNegIn == 1)
          && GenJpsiMass > 2.0 && GenJpsiMass < 4.0
          ) {AccJpsi = 1;}

      if((GenPosIn ==1 && GenNegIn==1)) NAccep++;

      //cout<<"1. GenJpsiPt : "<<GenJpsiPt<<", GenJpsiEta : "<<GenJpsiEta<<", GenJpsiRap : "<<GenJpsiRap<<", |GenJpsiPsi| : "<<TMath::Abs(GenJpsiPsi)<<endl;
      //cout<<"1. GenPosIn : "<<GenPosIn<<", GenNegIn : "<<GenNegIn<<endl;
      double vars = 0.0, bin1 = 0.0, bin2 = 0.0;
      if(iSpec == 0) vars = GenJpsiPt;
      if(iSpec == 1) vars = fabs(GenJpsiRap);
      for(int j = 0; j < nBins; j++){
        if(iSpec == 0){
          bin1 = pt_bound[j]; bin2 = pt_bound[j+1];
          if( (AccJpsi==1) && (vars >= bin1 && vars < bin2) && fabs(GenJpsiRap) >= minRap && TMath::Abs(GenJpsiRap) <= maxRap && TMath::Abs(GenJpsiRap) >= minRap) {
            hGenDiMuon[j]->Fill(GenJpsiMass);
          }
        }
        if(iSpec == 1){
          bin1 = rap_bound[j]; bin2 = rap_bound[j+1];
          if( (AccJpsi==1) && (vars >= bin1 && vars < bin2) && GenJpsiPt >= minPt && GenJpsiPt <= maxPt) {
            hGenDiMuon[j]->Fill(GenJpsiMass);
          }
        }
      }
    }//gen loop end

    //cout<<" accepted no "<< NAccep<<endl;

    //=============== Rec Tree Loop ==============================================================================

    int nRecEntries=tree->GetEntries();
    cout<<"Total Entries in reconstructed Tree for pT range "<<fileName[0]<<"  "<<nRecEntries<< "====="<<endl;
    for(int i=0; i<nRecEntries; i++)  {     
      tree->GetEntry(i);
      //Only printing 
      if(i%1000000==0){
        cout<<" processing record "<<i<<"/"<<nRecEntries<<endl;
        //cout<<" processing Run  " <<runNb <<" event "<<eventNb<<" lum block "<<lumiBlock<<endl;    
        //cout<<" Mass "<< JpsiMass<< " pT "<< JpsiPt << " Y " <<JpsiRap<<"  "<<JpsiVprob<<" charge "<<JpsiCharge<<" rbin "<<rbin<<endl; 
      }
      bool PosPass=0, NegPass=0, AllCut=0 ,PosIn=0, NegIn=0;
      muPosPt= TMath::Sqrt(muPosPx*muPosPx + muPosPy*muPosPy); 
      muPosP = TMath::Sqrt(muPosPx*muPosPx + muPosPy*muPosPy+ muPosPz*muPosPz); 
      muNegPt= TMath::Sqrt(muNegPx*muNegPx + muNegPy*muNegPy); 
      muNegP = TMath::Sqrt(muNegPx*muNegPx + muNegPy*muNegPy +muNegPz*muNegPz); 

      double tnpWgt1 = 0.0, tnpWgt2 = 0.0;
      double staWgt1 = 0.0, staWgt2 = 0.0;

      double x = 0.0;
      double xta = 0.0;
      // tnp MuonID X Trg
      if(fabs(muPosEta) < 0.9){
        x = muPosPt;
        tnpWgt1 = tnpSF1->Eval(x);
      }else if(fabs(muPosEta) < 1.6){
        x = muPosPt;
        tnpWgt1 = tnpSF2->Eval(x);
      }else if(fabs(muPosEta) < 2.1){
        x = muPosPt;
        tnpWgt1 = tnpSF3->Eval(x);
      }else{
        x = muPosPt;
        tnpWgt1 = tnpSF4->Eval(x);
      }

      if(fabs(muNegEta) < 0.9){
        x = muNegPt;
        tnpWgt2 = tnpSF1->Eval(x);
      }else if(fabs(muNegEta) < 1.6){
        x = muNegPt;
        tnpWgt2 = tnpSF2->Eval(x);
      }else if(fabs(muNegEta) < 2.1){
        x = muNegPt;
        tnpWgt2 = tnpSF3->Eval(x);
      }else{
        x = muNegPt;
        tnpWgt2 = tnpSF4->Eval(x);
      }

      // tnp STA 
      if(fabs(muPosEta) < 1.6){
        xta = muPosPt;
        staWgt1 = fun1->Eval(xta);
      }else{
        xta = muPosPt;
        staWgt1 = fun2->Eval(xta);
      }

      if(fabs(muNegEta) < 1.6){
        xta = muNegPt;
        staWgt2 = fun1->Eval(xta);
      }else{
        xta = muNegPt;
        staWgt2 = fun2->Eval(xta);
      }

      double RecWeight = 1.0;
      RecWeight = tnpWgt1*tnpWgt2*staWgt1*staWgt2;

      if(IsAccept(muPosPt, muPosEta)){PosIn=1;}
      if(IsAccept(muNegPt, muNegEta)){NegIn=1;}

      int AccJpsi = 0;
      //if(JpsiPt < 6.5) continue;
      if((JpsiPt >= minPt && JpsiPt <= maxPt && fabs(JpsiRap) >= minRap && TMath::Abs(JpsiRap) <= maxRap && PosIn == 1 && NegIn == 1)
          && (JpsiMass >= 2.95 && JpsiMass < 3.25)
          ) {AccJpsi = 1;}

      bool mu_Global = ((muPos_nchi2Gl >=0) && (muNeg_nchi2Gl >=0));
      bool mu_Tracker = ((muPos_tracker==1) && (muNeg_tracker==1));

      if(muPos_found > 10 
          && muPos_pixeLayers > 0 
          && muPos_nchi2In < 4.0 
          && TMath::Abs(muPos_dxy) < 3 
          && TMath::Abs(muPos_dz) < 15 
          && muPos_nchi2Gl < 20 
          && muPos_arbitrated==1 
          && muPos_tracker==1){PosPass=1;}     

      if(muNeg_found > 10 
          && muNeg_pixeLayers > 0 
          && muNeg_nchi2In < 4.0 
          && TMath::Abs(muNeg_dxy) < 3 
          && TMath::Abs(muNeg_dz) < 15 
          && muNeg_nchi2Gl < 20 
          && muNeg_arbitrated==1 
          && muNeg_tracker==1){NegPass=1;}


      // Trigger10 : HLT_PAL2DoubleMu3_v1, Trigger 2 : HLT_PAL1DoubleMu0_HighQ_v1, Trigger 1 : HLT_PAL1DoubleMu0_v1
      // muPos_matches : HLT_PAL1DoubleMuOpen_v1
      //if((muPos_Trigger21==1 && muNeg_Trigger21==1) && (PosIn==1 && NegIn==1) && (PosPass==1 && NegPass==1)&& mu_Global && mu_Tracker){AllCut=1;}
      if(hbit1 == 1 && (muPos_Trigger22==1 && muNeg_Trigger22==1) && (PosIn==1 && NegIn==1) && (PosPass==1 && NegPass==1)&& mu_Global && mu_Tracker){AllCut=1;}
      //if(hbit1 == 1 && (muPos_Trigger2==1 && muNeg_Trigger2==1) && (PosIn==1 && NegIn==1) && (PosPass==1 && NegPass==1)&& mu_Global && mu_Tracker){AllCut=1;}
      //if((muPos_matches==1 && muNeg_matches==1) && (PosIn==1 && NegIn==1) && (PosPass==1 && NegPass==1)&& mu_Global && mu_Tracker){AllCut=1;}
      //if((muPos_Trigger10==1 && muNeg_Trigger10==1) && (PosIn==1 && NegIn==1) && (PosPass==1 && NegPass==1)&& mu_Global && mu_Tracker){AllCut=1;}

      // without trigger matched
      // if((PosIn==1 && NegIn==1) && (PosPass==1 && NegPass==1)&& mu_Global && mu_Tracker){AllCut=1;}

      //Eff loop for reco
      double vars = 0.0, bin1 = 0.0, bin2 = 0.0;
      if(iSpec == 0) vars = JpsiPt;
      if(iSpec == 1) vars = fabs(JpsiRap);
      if((JpsiCharge == 0) && (JpsiVprob > 0.01)) {     
        for(int j = 0; j < nBins; j++){
          if(iSpec == 0){
            bin1 = pt_bound[j]; bin2 = pt_bound[j+1];
            if( AccJpsi == 1 && (AllCut == 1) && (vars >= bin1 && vars < bin2) && TMath::Abs(JpsiRap) <= maxRap && TMath::Abs(JpsiRap) >= minRap) {
              hRecoDiMuon[j]->Fill(JpsiMass,RecWeight);
            }
          }
          if(iSpec == 1){ 
            bin1 = rap_bound[j]; bin2 = rap_bound[j+1];
            if( AccJpsi == 1 && (AllCut == 1) && (vars >= bin1 && vars < bin2) && JpsiPt >= minPt && JpsiPt <= maxPt) {
              hRecoDiMuon[j]->Fill(JpsiMass,RecWeight);
            }
          }
        }
      }
    } //rec tree loop ends

    //======================  File loop Starts ============================

    ///////////////////////////////////////////////////////////////////
    cout<< " adding "<<endl;
    char gtmp[512], gtmp1[512];
    char rtmp[512], rtmp1[512];

    for(int i = 0; i < nBins; i++){
      if(iSpec == 1) sprintf(gtmp,"hGenDiMuon_Pt_%0.1f_%0.1f",pt_bound[i],pt_bound[i+1]);
      if(iSpec == 2) sprintf(gtmp,"hGenDiMuon_Rap_%0.1f_%0.1f",rap_bound[i],rap_bound[i+1]);
      if(iSpec == 1) sprintf(gtmp1,"plots/Gen/hGenDiMuon_Pt_%0.1f_%0.1f.png",pt_bound[i],pt_bound[i+1]);
      if(iSpec == 2) sprintf(gtmp1,"plots/Gen/hGenDiMuon_Rap_%0.1f_%0.1f.png",rap_bound[i],rap_bound[i+1]);
      if(iSpec == 1) sprintf(rtmp,"hRecDiMuon_Pt_%0.1f_%0.1f",pt_bound[i],pt_bound[i+1]);
      if(iSpec == 2) sprintf(rtmp,"hRecDiMuon_Rap_%0.1f_%0.1f",rap_bound[i],rap_bound[i+1]);
      if(iSpec == 1) sprintf(rtmp1,"plots/Rec/hRecDiMuon_Pt_%0.1f_%0.1f.png",pt_bound[i],pt_bound[i+1]);
      if(iSpec == 2) sprintf(rtmp1,"plots/Rec/hRecDiMuon_Rap_%0.1f_%0.1f.png",rap_bound[i],rap_bound[i+1]);
      hGenDiMuon[i]->SetName(gtmp);
      hRecoDiMuon[i]->SetName(rtmp);
    }

    cout<<"Starts to calculate efficiency"<<endl;
    //dataFile<<""<<endl;
    //=====================Loop for eff========================================================================================//
    //define stuff here for error on weighted samples
    for(int i = 0; i < nBins; i++){
      int Gbinlow =hGenDiMuon[i]->GetXaxis()->FindBin(2.0);//2.95
      int Gbinhi=hGenDiMuon[i]->GetXaxis()->FindBin(4.0);//2.95

      int Rbinlow =hRecoDiMuon[i]->GetXaxis()->FindBin(2.95);//2.95
      int Rbinhi=hRecoDiMuon[i]->GetXaxis()->FindBin(3.25);//2.95

      genNo[i] = hGenDiMuon[i]->IntegralAndError(Gbinlow, Gbinhi, genErr[i]); 
      recoNo[i] = hRecoDiMuon[i]->IntegralAndError(Rbinlow, Rbinhi, recoErr[i]);
      //calculate Eff         
      if(genNo[i] == 0 || recoNo[i] == 0) {
        eff[i] = 0;
        effErr[i] = 0;
      }else{
        eff[i] = recoNo[i]/genNo[i]; 

        effErr[i] = recoNo[i]/genNo[i]*TMath::Sqrt(genErr[i]*genErr[i]/(genNo[i]*genNo[i]) + recoErr[i]*recoErr[i]/(recoNo[i]*recoNo[i]));

        //error without weight
        //dataFile<<" Bin ["<<i<<"] - "<< " Reco Jpsi : "<< recoNo[i]  <<", Gen Jpsi : "<< genNo[i] <<endl;
        //dataFile<<" Eff ["<<i<<"] - "<< eff[i] <<" Error "<< effErr[i] <<endl;
        cout<<" Bin ["<<i<<"] - "<< " Reco Jpsi : "<< recoNo[i]  <<", Gen Jpsi : "<< genNo[i] <<endl;
        cout<<" Eff ["<<i<<"] - "<< eff[i] <<" Error "<< effErr[i] <<endl;
      }
    }
    TH1F *hEff = new TH1F();
    int nEffBins = 0;
    if(iSpec == 0) {hEff = new TH1F("hEff","hEff;p_{T} GeV/c;Efficiency",nPtBins,pt_bound); nEffBins = nPtBins;}
    if(iSpec == 1) {hEff = new TH1F("hEff","hEff;y;Efficiency",nRapBins,rap_bound); nEffBins = nRapBins;}

    //dataFile<<"Efficiency"<<endl;
    for(int i = 0; i < nEffBins; i++){
      hEff->SetBinContent(i+1,eff[i]);
      hEff->SetBinError(i+1,effErr[i]);
      cout<<"Trying to measure eff vs "<<cSp[iSpec]<<endl;
      cout<<"Eff : "<<eff[i]<<", err : "<<effErr[i]<<endl;
      dataFile<<eff[i]<<endl;
    }

    //dataFile<<""<<endl;
    //dataFile<<"Errors"<<endl;
    for(int i = 0; i < nEffBins; i++){
      hEff->SetBinContent(i+1,eff[i]);
      hEff->SetBinError(i+1,effErr[i]);
      cout<<"Trying to measure eff vs "<<cSp[iSpec]<<endl;
      cout<<"Eff : "<<eff[i]<<", err : "<<effErr[i]<<endl;
      //dataFile<<effErr[i]<<endl;
    }


    outfile->cd();
    hEff->Draw();
    char tmp_histo[512];
    sprintf(tmp_histo,"hEff_%s",cSp[iSpec]);
    hEff->SetName(tmp_histo);
    hEff->Write();
    //dataFile<<""<<endl;
    //dataFile.close();
  }
  outfile->Write();
}
Ejemplo n.º 25
0
void produceHisto(std::string outputName="", std::string var="0.692-9.240*ecalIso/pt-11.117*hcalIso/pt",double genIsoCut=5.0,bool normalize=false )
{
   if(outputName=="")outputName = var;
   vector<string> mixFile;
   vector<double> mixWeight;
   vector<TTree*> mixTree;
   vector<int> mixPtHatLo;
   vector<int> mixPtHatHi;

   vector<string> phoFile;
   vector<double> phoWeight;
   vector<TTree*> phoTree;
   vector<int> phoPtHatLo;
   vector<int> phoPtHatHi;

   vector<string> jetFile;
   vector<double> jetWeight;
   vector<TTree*> jetTree;
   vector<int> jetPtHatLo;
   vector<int> jetPtHatHi;


   double lumi = 1.0;
   FILE *fTable = fopen("inputFile.txt","r");
   
   int flag=1;   
   int nfile=0;
   while (flag!=-1){
     // first reading input file
     char filename[100];
     flag=fscanf(fTable,"%s",filename);
     std::string tempFile = filename;

     bool isPhotonJet = false;
     if(tempFile.find("PhotonJet") != std::string::npos)isPhotonJet=true;
     char tmp[1000];
     // read in x-section
     flag=fscanf(fTable,"%s",tmp);
     double cross=atof(tmp);
     // read in number of events
     flag=fscanf(fTable,"%s",tmp);
     double nevt=atof(tmp);
     double scale =lumi*cross/nevt;

     flag=fscanf(fTable,"%s",tmp);
     int ptHatLo=atof(tmp);
     
     flag=fscanf(fTable,"%s",tmp);
     int ptHatHi=atof(tmp);

    if (flag!=-1) {
      cout <<filename<<" "<<cross<<" "<<nevt<< " " << ptHatLo << " " << ptHatHi << endl;
      if(isPhotonJet)
	{
	  cout << "filling photon jet" << endl;
	  phoFile.push_back(tempFile);
	  phoWeight.push_back(scale);
	  phoPtHatLo.push_back(ptHatLo);
	  phoPtHatHi.push_back(ptHatHi);      
	}
      else
	{
	  cout << "filling dijet" << endl;
	  jetFile.push_back(tempFile);
	  jetWeight.push_back(scale);
	  jetPtHatLo.push_back(ptHatLo);
	  jetPtHatHi.push_back(ptHatHi);      
	}
      
      cout << "filling mixture" << endl;
      mixFile.push_back(tempFile);
      mixWeight.push_back(scale);
      mixPtHatLo.push_back(ptHatLo);
      mixPtHatHi.push_back(ptHatHi);      

      nfile++; 
    }	 
	
   } 

   std::string treeName = "Analysis";

   // first photon trees
   fillTrees(phoFile,phoTree,treeName);
   const unsigned int nSize_pho = phoFile.size();
   if(phoTree.size()!= nSize_pho){cout << "error 1"<< endl; return;}
   if(phoWeight.size()!= nSize_pho){cout << "error 2"<< endl; return;}
   if(phoPtHatLo.size()!= nSize_pho){cout << "error 3"<< endl; return;}
   if(phoPtHatHi.size()!= nSize_pho){cout << "error 4"<< endl; return;}

   // second fill background trees
   fillTrees(jetFile,jetTree,treeName);
   const unsigned int nSize_jet = jetFile.size();
   if(jetTree.size()!= nSize_jet){cout << "error 1"<< endl; return;}
   if(jetWeight.size()!= nSize_jet){cout << "error 2"<< endl; return;}
   if(jetPtHatLo.size()!= nSize_jet){cout << "error 3"<< endl; return;}
   if(jetPtHatHi.size()!= nSize_jet){cout << "error 4"<< endl; return;}


   // last fill mix trees
   fillTrees(mixFile,mixTree,treeName);
   const unsigned int nSize_mix = mixFile.size();
   if(mixTree.size()!= nSize_mix){cout << "error 1"<< endl; return;}
   if(mixWeight.size()!= nSize_mix){cout << "error 2"<< endl; return;}
   if(mixPtHatLo.size()!= nSize_mix){cout << "error 3"<< endl; return;}
   if(mixPtHatHi.size()!= nSize_mix){cout << "error 4"<< endl; return;}
   
   TH1F *hTemplate = new TH1F("hTemplate","",70,-5,2);
   TH1F* hEcalIsoPho = (TH1F*)hTemplate->Clone();
   std::string histoName = outputName + "Pho";
   hEcalIsoPho->SetName(histoName.data());

   TH1F* hEcalIsoJet = (TH1F*)hTemplate->Clone();
   histoName = outputName + "Jet";
   hEcalIsoJet->SetName(histoName.data());

   TH1F* hEcalIsoMixSig = (TH1F*)hTemplate->Clone();
   histoName = outputName + "MixSig";
   hEcalIsoMixSig->SetName(histoName.data());

   TH1F* hEcalIsoMixBkg = (TH1F*)hTemplate->Clone();
   histoName = outputName + "MixBkg";
   hEcalIsoMixBkg->SetName(histoName.data());


   TH1F* hEcalIsoMixData = (TH1F*)hTemplate->Clone();
   histoName = outputName + "MixData";
   hEcalIsoMixData->SetName(histoName.data());
   
   cout << "making histograms from photon+jet MC samples" << endl;
   TCut allCut = basicCut + sigCut;
//    makePlot(phoTree,phoWeight,Form("%s",var.data()),hardScatterCut,hEcalIsoPho,normalize);
   makePlot(phoTree,phoWeight,phoPtHatLo,phoPtHatHi,Form("%s",var.data()),allCut,hEcalIsoPho,normalize);

   cout << "making histograms from dijet MC samples" << endl;
   allCut = basicCut + decayCut;
   makePlot(jetTree,jetWeight,jetPtHatLo,jetPtHatHi,Form("%s",var.data()),allCut,hEcalIsoJet,normalize);

   cout << "making histograms from mixed MC signal samples" << endl;     
   allCut = basicCut + sigCut;
   makePlot(mixTree,mixWeight,mixPtHatLo,mixPtHatHi,Form("%s",var.data()),allCut,hEcalIsoMixSig,normalize);

   cout << "making histograms from mixed MC background samples" << endl;     
   allCut = basicCut + bkgCut;
   makePlot(mixTree,mixWeight,mixPtHatLo,mixPtHatHi,Form("%s",var.data()),allCut,hEcalIsoMixBkg,normalize);
   
   hEcalIsoPho->SetMarkerColor(2);
   hEcalIsoPho->SetLineColor(2);
   hEcalIsoJet->SetMarkerColor(1);
   hEcalIsoJet->SetLineColor(1);
   hEcalIsoMixSig->SetMarkerColor(5);
   hEcalIsoMixSig->SetLineColor(5);
   hEcalIsoMixBkg->SetMarkerColor(4);
   hEcalIsoMixBkg->SetLineColor(4);


   cout << "hEcalIsoPho->Integral()  = " << hEcalIsoPho->Integral() << endl;
   cout << "hEcalIsoJet->Integral()  = " << hEcalIsoJet->Integral() << endl;
   cout << "hEcalIsoMixSig->Integral()  = " << hEcalIsoMixSig->Integral() << endl;
   cout << "hEcalIsoMixBkg->Integral()  = " << hEcalIsoMixBkg->Integral() << endl;

   hEcalIsoMixData->Reset();
   hEcalIsoMixData->Sumw2();
   hEcalIsoMixData->Add(hEcalIsoMixSig,hEcalIsoMixBkg,1.0,1.0);
   cout << "hEcalIsoMixData->Integral()  = " << hEcalIsoMixData->Integral() << endl;
   

   hEcalIsoPho->SetXTitle(var.data());
   hEcalIsoPho->Draw("hist");
   hEcalIsoJet->Draw("histesame");
   hEcalIsoMixSig->Draw("histesame");
   hEcalIsoMixBkg->Draw("histesame");
   TLegend* leg = new TLegend(0.5,0.6,0.7,0.9);
   leg->SetFillColor(0);
   leg->SetFillStyle(0);
   leg->SetTextSize(0.03);
   leg->SetBorderSize(0);
   leg->AddEntry(hEcalIsoPho,"#gamma+jet MC");
   leg->AddEntry(hEcalIsoJet,"Dijet MC");
   leg->AddEntry(hEcalIsoMixSig,"Mixed MC: signal");
   leg->AddEntry(hEcalIsoMixBkg,"Mixed MC: background");
   leg->Draw("same");

   // dump histogram to a root file
   std::string histoFile = outputName + "_histo.root";

   TFile* outFile = new TFile(histoFile.data(),"recreate");
   hEcalIsoPho->Write();
   hEcalIsoJet->Write();
   hEcalIsoMixSig->Write();
   hEcalIsoMixBkg->Write();
   hEcalIsoMixData->Write();
   outFile->Close();


}
Ejemplo n.º 26
0
int BDTInterpolation(std::string inFileName,bool Diagnose=false, bool doNorm=true, bool doSidebands=false){

  std::cout << getTime() << std::endl;

  system("rm -r plots");
  system("mkdir plots");

  //gROOT->SetBatch();
  gStyle->SetOptStat(0);

  // input flags
  bool all=0;
 
  if (Diagnose) {
    std::cout << "Diagnostics turned on \n Output plots available in \"plots\" directory \n Diagnostic log available in \"plots/BDTInterpolationDiagnostics.txt\"" << std::endl;
    all = true;
  }
  else std::cout << "Diagnostics turned off" << std::endl;
  if (doNorm) std::cout << "Normalization turned on" << std::endl;
  else std::cout << "Normalization turned off" << std::endl;
  if (doSidebands) std::cout << "Background model from sidebands turned on" << std::endl;
  else std::cout << "Background model from sidebands turned off" << std::endl;

  TFile *inFile = new TFile(inFileName.c_str());
  //TFile *inFile = new TFile("/vols/cms02/nw709/hgg/src_cvs/oct13/CMSSW_4_2_8/src/HiggsAnalysis/HiggsTo2photons/h2gglobe/Macros/CMS-HGG_1658pb_mva.root");
  //TFile *inFile = new TFile("RefWorkspaces/CMS-HGG_1658pb_mva.root");
  TFile *outFile = new TFile(Form("%s_interpolated.root",inFileName.c_str()),"RECREATE");
  TFile *systTestF = new TFile("systTest.root","RECREATE");
  ofstream diagFile("plots/BDTInterpolationDiagnostics.txt");

  const int nBDTs=2;
  const int nMasses=8;
  const int nProds=4;
  std::string BDTtype[nBDTs] = {"ada","grad"};
  std::string BDTmasses[nMasses] = {"110.0","115.0","120.0","125.0","130.0","135.0","140.0","150.0"};
  std::string productionTypes[nProds] = {"ggh","vbf","wzh","tth"};
// ----- else can just get rebinned histograms straight out of workspace

  std::cout << "Extracting histograms from workspace........." << std::endl;

  diagFile << "Diagnostics for Signal Interpolation run at " << getTime() << std::endl;
  diagFile << "---------------------------------------------------------------------" << std::endl;
  diagFile << "Following orginal histograms rewritten into new workspace: " << std::endl;
  
  // ------ stuff for interpolation systematic -------
  TH1F *systHists120[2][3];
  TH1F *systHists135[2][3];

  std::string syst120mass[3] = {"120.0","115.0","125.0"};
  std::string syst135mass[3] = {"135.0","130.0","140.0"};
  // ---------------------------------------------------
  
  // make plots of background model from sidebands
  if (doSidebands){
    for (int bdt=0; bdt<nBDTs; bdt++){
      for (double mass=110.; mass<=150.0; mass+=0.5){
        TList *bkgModelList = new TList();
        TH1F *bkgModel[7];
        bkgModel[0] = (TH1F*)inFile->Get(Form("th1f_bkg_%s_%3.1f_cat0",BDTtype[bdt].c_str(),mass));
        bkgModel[1] = (TH1F*)inFile->Get(Form("th1f_bkg_3low_%s_%3.1f_cat0",BDTtype[bdt].c_str(),mass));
        bkgModel[2] = (TH1F*)inFile->Get(Form("th1f_bkg_2low_%s_%3.1f_cat0",BDTtype[bdt].c_str(),mass));
        bkgModel[3] = (TH1F*)inFile->Get(Form("th1f_bkg_1low_%s_%3.1f_cat0",BDTtype[bdt].c_str(),mass));
        bkgModel[4] = (TH1F*)inFile->Get(Form("th1f_bkg_1high_%s_%3.1f_cat0",BDTtype[bdt].c_str(),mass));
        bkgModel[5] = (TH1F*)inFile->Get(Form("th1f_bkg_2high_%s_%3.1f_cat0",BDTtype[bdt].c_str(),mass));
        bkgModel[6] = (TH1F*)inFile->Get(Form("th1f_bkg_3high_%s_%3.1f_cat0",BDTtype[bdt].c_str(),mass));
        for (int i=0; i<7; i++) {
          bkgModelList->Add(bkgModel[i]);
        }
        std::string name(Form("%3.1f",mass));
        plotBkgModel(bkgModelList,name);
      }
    }
  }
  
  // write original histograms in out file
  TList *HistList = inFile->GetListOfKeys();
  for (int j=0; j<HistList->GetSize(); j++){
    TH1F *temp = (TH1F*)inFile->Get(HistList->At(j)->GetName());
    TString name = temp->GetName();

    // store stuff for interpolation systematic
    for (int bdt=0; bdt<nBDTs; bdt++){
      for (int syst=0; syst<3; syst++){
        if (name.Contains(("th1f_sig_"+BDTtype[bdt]+"_"+productionTypes[0]+"_"+syst120mass[0]+"_"+syst120mass[syst]).c_str()) && !name.Contains("sigma")){
          systHists120[bdt][syst] = (TH1F*)inFile->Get(name.Data());
          systHists120[bdt][syst]->SetLineColor(syst+2);
        }
        if (name.Contains(("th1f_sig_"+BDTtype[bdt]+"_"+productionTypes[0]+"_"+syst135mass[0]+"_"+syst135mass[syst]).c_str()) && !name.Contains("sigma")){
          systHists135[bdt][syst] = (TH1F*)inFile->Get(name.Data());
          systHists135[bdt][syst]->SetLineColor(syst+2);
        }
      }
    }
    // ---------------------------------------------
    std::string tName = temp->GetName();
    for (int i=0; i<nMasses; i++){
      int ind = tName.find(BDTmasses[i]+"_"+BDTmasses[i]);
      if (ind>0) tName.replace(ind,11,BDTmasses[i]);
    }
    temp->SetName(tName.c_str());
      
    outFile->cd();
    temp->Write();
    diagFile << "Histo written: " << temp->GetName() << std::endl;
  }

  // ----------- Do stuff for interpolation systematic ------------
  std::cout << "Creating interpolation systematic templates......." << std::endl;

  diagFile << "---------------------------------------------------------------------" << std::endl;
  diagFile << "Writing following interpolation systematic templates: " << std::endl;
  
  for (int bdt=0; bdt<nBDTs; bdt++){
    double norm120 = GetNorm(115.0,systHists120[bdt][1],125.0,systHists120[bdt][2],120.0);
    double norm135 = GetNorm(130.0,systHists135[bdt][1],140.0,systHists135[bdt][2],135.0);
    if (doNorm) {
      systHists120[bdt][1]->Scale(1./(GetXsection(115.0)*GetBR(115.0)));
      systHists120[bdt][2]->Scale(1./(GetXsection(125.0)*GetBR(125.0)));
      systHists135[bdt][1]->Scale(1./(GetXsection(130.0)*GetBR(130.0)));
      systHists135[bdt][2]->Scale(1./(GetXsection(140.0)*GetBR(140.0)));
    }
    TH1F *int120 = Interpolate(115.0,systHists120[bdt][1],125.0,systHists120[bdt][2],120.0);
    TH1F *int135 = Interpolate(130.0,systHists135[bdt][1],140.0,systHists135[bdt][2],135.0);
    if (doNorm) {
      systHists120[bdt][1]->Scale(GetXsection(115.0)*GetBR(115.0));
      systHists120[bdt][2]->Scale(GetXsection(125.0)*GetBR(125.0));
      systHists135[bdt][1]->Scale(GetXsection(130.0)*GetBR(130.0));
      systHists135[bdt][2]->Scale(GetXsection(140.0)*GetBR(140.0));
    }
    if (doNorm) {
      int120->Scale(norm120/int120->Integral());
      int135->Scale(norm135/int135->Integral());
    }
    
    TList *int120list = new TList();
    int120list->Add(systHists120[bdt][1]);
    int120list->Add(systHists120[bdt][2]);
    int120list->Add(int120);
    plotFrac(int120list,systHists120[bdt][0],"syst120",false);
    
    TList *int135list = new TList();
    int135list->Add(systHists135[bdt][1]);
    int135list->Add(systHists135[bdt][2]);
    int135list->Add(int135);
    plotFrac(int135list,systHists135[bdt][0],"syst135",false);
    TH1F *frac=(TH1F*)systHists135[bdt][0]->Clone();
    frac->Add(int135,-1);
    frac->Divide(int135);
    TH1F *linFrac = (TH1F*)linearBin(frac);
    linFrac->GetYaxis()->SetRangeUser(-0.4,0.4);
    TCanvas *c = new TCanvas();
    systTestF->cd();
    linFrac->Write();
    linFrac->Draw();
    TF1 *fit = new TF1("fit","[0]*(x-36.)^2",0.,36.);
    linFrac->Fit(fit,"q");
    fit->DrawCopy("same");
    fit->SetLineColor(kGray);
    fit->SetLineStyle(2);
    double var = fit->GetParameter(0);
    double err = fit->GetParError(0);
    fit->SetParameter(0,var+err);
    fit->DrawCopy("same");
    fit->SetParameter(0,var-err);
    fit->DrawCopy("same");

    c->Print(Form("plots/%s/fracs/systTest135.png",BDTtype[bdt].c_str()),"png");

    // get plus and minus templates
    std::pair<TH1F*,TH1F*> result135 = GetPMSyst(systHists135[bdt][0],int135,"th1f_sig_"+BDTtype[bdt]+"_ggh_135.0_cat0_sigInt");
    TH1F* sigIntDown = (TH1F*)linearBin(result135.first);
    TH1F* sigIntUp = (TH1F*)linearBin(result135.second);
    TH1F* sigIntCent = (TH1F*)linearBin(int135);
    diagFile << (result135.first)->GetName() << std::endl;
    diagFile << (result135.second)->GetName() << std::endl;
    
    TCanvas *test = new TCanvas();
    sigIntDown->SetLineColor(2);
    sigIntUp->SetLineColor(4);
    sigIntDown->Draw();
    sigIntUp->Draw("same");
    sigIntCent->Draw("same'");
    test->Print(("plots/"+BDTtype[bdt]+"/fracs/PMsysts135.png").c_str(),"png");
   
    outFile->cd();
    (result135.first)->Write();
    (result135.second)->Write();
   
  }

    // -------------------- systematic stuff done ----------------------

  // get lists of middle, upper and lower templates for each mass
  TList *orgHistList[nBDTs][nProds][nMasses];
  TList *orgHistListBelow[nBDTs][nProds][nMasses];
  TList *orgHistListAbove[nBDTs][nProds][nMasses];
  for (int i=0; i<nBDTs; i++) {
   for (int pT=0;pT<nProds;pT++){
    for (int j=0; j<nMasses; j++) {
      orgHistList[i][pT][j]=new TList();
      orgHistListBelow[i][pT][j]=new TList();
      orgHistListAbove[i][pT][j]=new TList();
    }
   }
  }

  for (int j=0; j<HistList->GetSize(); j++){
    TString HistName(HistList->At(j)->GetName());
    for (int bdt=0; bdt<nBDTs; bdt++){
     for (int pT=0;pT<nProds;pT++){
      for (int bdtmass=0; bdtmass<nMasses; bdtmass++){
        for (int k=-1; k<2; k++){
          if ((bdtmass==0 && k==-1) || (bdtmass==nMasses-1 && k==1)) continue;
          if (HistName.Contains(("sig_"+BDTtype[bdt]+"_"+productionTypes[pT]+"_"+BDTmasses[bdtmass]+"_"+BDTmasses[bdtmass+k]).c_str())){
            TH1F *temp = (TH1F*)inFile->Get(HistName.Data());
            cout << temp->GetName() << " " << temp->GetEntries() << endl;
            if (k==-1) orgHistListBelow[bdt][pT][bdtmass]->Add(temp);
            if (k==0) orgHistList[bdt][pT][bdtmass]->Add(temp);
            if (k==1) orgHistListAbove[bdt][pT][bdtmass]->Add(temp);
          }
        }
       }
      }
    }
  }
  diagFile << "---------------------------------------------------------------------" << std::endl;
  diagFile << "Following histo's being used for interpolation: " << std::endl;
  for (int bdt=0; bdt<nBDTs; bdt++){
   for (int pT=0;pT<nProds;pT++){
    for (int mass=0; mass<nMasses; mass++){
      diagFile << "BDT: " << BDTtype[bdt] << std::endl;
      diagFile << "Production : " << productionTypes[pT] << std::endl;
      diagFile << "Mass: " << BDTmasses[mass] << std::endl;
      for (int syst=0; syst<orgHistList[bdt][pT][mass]->GetSize(); syst++){
        diagFile << "   Central: " << orgHistList[bdt][pT][mass]->At(syst)->GetName() << std::endl;
        if (mass!=0) diagFile << "   Lower:   " << orgHistListBelow[bdt][pT][mass]->At(syst)->GetName() << std::endl;
        if (mass!=nMasses-1) diagFile << "   Upper:   " << orgHistListAbove[bdt][pT][mass]->At(syst)->GetName() << std::endl;
      }
    }
   }
  }

  // now have orgHistList for each BDT and above and below signals.
  // the contain 17 histos - 1 for actual sig and 8 up and down for each systematic

  // ---------- at this points have signal hists for each mass points as well as +- models all rebinned at mass points --------

  std::cout << "Calculating interpolated signal templates........" << std::endl;
  diagFile << "---------------------------------------------------------------------" << std::endl;
  diagFile << "Interpolating intermediate signals from following lower and upper templates" << std::endl;

  const int nGlobalMs=81; // no of mass points between lowMass and highMass with 0.5 GeV steps
  TList *orgHistListInt[nBDTs][nProds][nGlobalMs];
  for (int i=0; i<nBDTs; i++) for (int pT=0; pT<nProds; pT++) for (int j=0; j<nGlobalMs; j++) orgHistListInt[i][pT][j] = new TList();
  TH1F *systUp, *systDown, *systTrue;
  TH1F *background, *data, *signal, *sig_ggh, *sig_vbf, *sig_wzh, *sig_tth;

  int i=0;
  // loop over mass points etc.
  for (double mass=110.; mass<=150.; mass+=0.5){
    if (int(mass)%2==0) std::cout << Form("%3.0f",((mass-110.)/40.)*100.) << "% done" << std::endl;
    //points we have signal for
    if (int(mass*2)%10==0 && mass!=145.0) {
     for (int pT=0;pT<nProds;pT++){
      for (int bdt=0; bdt<nBDTs; bdt++){  
        background = (TH1F*)inFile->Get(Form("th1f_bkg_%s_%3.1f_cat0_fitsb_biascorr",BDTtype[bdt].c_str(),mass));
      //  background = (TH1F*)inFile->Get(Form("th1f_bkg_%s_%3.1f_cat0",BDTtype[bdt].c_str(),mass));
        data = (TH1F*)inFile->Get(Form("th1f_data_%s_%3.1f_cat0",BDTtype[bdt].c_str(),mass));
        sig_ggh = (TH1F*)inFile->Get(Form("th1f_sig_%s_ggh_%3.1f_%3.1f_cat0",BDTtype[bdt].c_str(),mass,mass));
        sig_vbf = (TH1F*)inFile->Get(Form("th1f_sig_%s_vbf_%3.1f_%3.1f_cat0",BDTtype[bdt].c_str(),mass,mass));
        sig_wzh = (TH1F*)inFile->Get(Form("th1f_sig_%s_wzh_%3.1f_%3.1f_cat0",BDTtype[bdt].c_str(),mass,mass));
        sig_tth = (TH1F*)inFile->Get(Form("th1f_sig_%s_tth_%3.1f_%3.1f_cat0",BDTtype[bdt].c_str(),mass,mass));
	
        signal = (TH1F*)sig_ggh->Clone();
        signal->Add(sig_vbf);
        signal->Add(sig_wzh);
        signal->Add(sig_tth);

        std::string name = Form("%3.1f",mass);
        if (Diagnose) {
          plotDavid(background,signal,data,name);
          TList *systList = new TList();
          TH1F *central;
          int bdtmass = getIndex((findNearest(mass).first));
          for (int syst=0; syst<orgHistList[bdt][pT][bdtmass]->GetSize(); syst++){
            if (syst==0) central = (TH1F*)orgHistList[bdt][pT][bdtmass]->At(syst);
            else {
              TH1F *tempSig = (TH1F*)orgHistList[bdt][pT][bdtmass]->At(syst);
              systList->Add(tempSig);
            }
          }
          plotSystFracs(systList,central,Form("%3.1f_systFracs",mass));
        }
        // store some systematic histograms
        if (int(mass)>110 && int(mass)<150){
          int bdtmass = getIndex(int(mass));
          systTrue = (TH1F*)orgHistList[bdt][pT][bdtmass]->At(0)->Clone();
          systUp = (TH1F*)orgHistListAbove[bdt][pT][bdtmass]->At(0)->Clone();
          systDown = (TH1F*)orgHistListBelow[bdt][pT][bdtmass]->At(0)->Clone();

          double trueNorm = systTrue->Integral();
          systUp->Scale(trueNorm/systUp->Integral());
          systDown->Scale(trueNorm/systDown->Integral());
          systUp->SetName(Form("th1f_sig_%s_%s_%3.1f_cat0_sigIntNewUp01_sigma",BDTtype[bdt].c_str(),productionTypes[pT].c_str(),mass));
          systDown->SetName(Form("th1f_sig_%s_%s_%3.1f_cat0_sigIntNewDown01_sigma",BDTtype[bdt].c_str(),productionTypes[pT].c_str(),mass));
          
          outFile->cd();
          systUp->Write();
          systDown->Write();
          TCanvas *lil = new TCanvas();
          systUp->SetLineColor(kRed);
          systDown->SetLineColor(kBlue);
          systDown->Draw("e");
          systUp->Draw("same e");
          systTrue->Draw("same e");
          lil->Print(Form("plots/%s/systNew_%s_%3.1f.png",BDTtype[bdt].c_str(),productionTypes[pT].c_str(),mass),"png");
          delete lil;
        }
      }
     }
      continue;
    }
    std::pair<int,int> nearestPair = findNearest(mass);
    bool above;
    int nearest = nearestPair.first;
    int nextNear =nearestPair.second;
    if (nearest-nextNear < 0) above = true;
    else above = false;
    
    //std::cout << mass << " bracketed by: " << nearestPair.first << " " << nearestPair.second << " " << above << std::endl;

    int bdtmass = getIndex(nearest); // gives index of bdt to use

    // loop bdt type
    for (int bdt=0; bdt<nBDTs; bdt++){
     TH1F *combSignal;
     for (int pT=0;pT<nProds;pT++){
      diagFile << "Mass: " << mass << std::endl;
      diagFile << "BDT: " << BDTtype[bdt] << std::endl;
      // loop different histos in list (signal and systematics)
      background = (TH1F*)inFile->Get(Form("th1f_bkg_%s_%3.1f_cat0_fitsb_biascorr",BDTtype[bdt].c_str(),mass));
     // background = (TH1F*)inFile->Get(Form("th1f_bkg_%s_%3.1f_cat0",BDTtype[bdt].c_str(),mass));
      data = (TH1F*)inFile->Get(Form("th1f_data_%s_%3.1f_cat0",BDTtype[bdt].c_str(),mass));
      TList *systList = new TList();
      TH1F *central;
      for (int syst=0; syst<orgHistList[bdt][pT][bdtmass]->GetSize(); syst++){
        TH1F *tempSig = (TH1F*)orgHistList[bdt][pT][bdtmass]->At(syst);
        central = (TH1F*)tempSig->Clone();
        TH1F *tempAbove = (TH1F*)orgHistListAbove[bdt][pT][bdtmass]->At(syst);
        TH1F *tempBelow = (TH1F*)orgHistListBelow[bdt][pT][bdtmass]->At(syst);
        TH1F* tempInt;
        TList* plotList = new TList();
        if (above){
          if (doNorm) tempSig->Scale(1./(GetXsection(double(nearest))*GetBR(double(nearest))));
          if (doNorm) tempAbove->Scale(1./(GetXsection(double(nextNear))*GetBR(double(nextNear))));
          tempInt = Interpolate(double(nearest),tempSig,double(nextNear),tempAbove,mass);
          if (doNorm) tempSig->Scale(GetXsection(double(nearest))*GetBR(double(nearest)));
          if (doNorm) tempAbove->Scale(GetXsection(double(nextNear))*GetBR(double(nextNear)));
          double norm = GetNorm(double(nearest),tempSig,double(nextNear),tempAbove,mass);
          if (doNorm) tempInt->Scale(norm/tempInt->Integral());
          // diagnostic stuff
          diagFile << "   Interpolated:     " << tempInt->GetName() << std::endl;
          diagFile << "   from:             " << tempSig->GetName() << std::endl;
          diagFile << "   and:              " << tempAbove->GetName() << std::endl;
          std::string histName = tempSig->GetName();
          std::string systName = histName.substr(histName.rfind("cat0"),histName.size());
          plotList->Add(tempSig);
          plotList->Add(tempAbove);
          if (Diagnose){
            if (syst==0) plotFrac(plotList,tempInt,Form("%3.1f_%s",mass,systName.c_str()),true);
            else systList->Add(tempInt);
          }
        }
        else{
          if (doNorm) tempSig->Scale(1./(GetXsection(double(nearest))*GetBR(double(nearest))));
          if (doNorm) tempBelow->Scale(1./(GetXsection(double(nextNear))*GetBR(double(nextNear))));
          tempInt = Interpolate(double(nextNear),tempBelow,double(nearest),tempSig,mass);
          if (doNorm) tempSig->Scale(GetXsection(double(nearest))*GetBR(double(nearest)));
          if (doNorm) tempBelow->Scale(GetXsection(double(nextNear))*GetBR(double(nextNear)));
          double norm = GetNorm(double(nextNear),tempBelow,double(nearest),tempSig,mass);
          if (doNorm) tempInt->Scale(norm/tempInt->Integral());
          // diagnostic stuff
          diagFile << "   Interpolated:     " << tempInt->GetName() << std::endl;
          diagFile << "   from:             " << tempBelow->GetName() << std::endl;
          diagFile << "   and:              " << tempSig->GetName() << std::endl;
          std::string histName = tempSig->GetName();
          std::string systName = histName.substr(histName.rfind("cat0"),histName.size());
          plotList->Add(tempBelow);
          plotList->Add(tempSig);
          if (Diagnose){
            if (syst==0) plotFrac(plotList,tempInt,Form("%3.1f_%s",mass,systName.c_str()),true);
            else systList->Add(tempInt);
          }
        }
        orgHistListInt[bdt][pT][i]->Add(tempInt);
        if (syst==0 && Diagnose){
          if (pT==0) combSignal = (TH1F*)tempInt->Clone();
          else combSignal->Add(tempInt,1.);
          std::string name = Form("%3.1f",mass);
          if (pT==3) plotDavid(background,combSignal,data,name);
        }
        delete plotList;
      }
      if (Diagnose) plotSystFracs(systList,central,Form("%3.1f_systFracs",mass));
     }
    }
    i++;
  }
 
  outFile->cd();

  diagFile << "---------------------------------------------------------------------" << std::endl;
  diagFile << "Writing following interpolated histograms to file: " << std::endl;
  for (int l=0; l<nBDTs; l++) for (int pT=0; pT<nProds; pT++)for (int j=0; j<nGlobalMs; j++) for (int k=0; k<orgHistListInt[l][pT][j]->GetSize(); k++) {
    orgHistListInt[l][pT][j]->At(k)->Write();
    diagFile << orgHistListInt[l][pT][j]->At(k)->GetName() << std::endl;
  }
  
  TList* endList = outFile->GetListOfKeys();
  for (double mass=110.0; mass<=150.; mass+=0.5){
    diagFile << mass << std::endl;
    std::pair<int,int> nearestPair = findNearest(mass);
    double nearest = nearestPair.first;
    double nextNear = nearestPair.second;
    for (int k=0; k<endList->GetSize(); k++){
      TString hName = endList->At(k)->GetName();
      if (hName.Contains("sigma") || !hName.Contains("sig")) continue;
      if (hName.Contains(Form("a_%3.1f_cat0",nearest)) || hName.Contains(Form("d_%3.1f_cat0",nearest)) || hName.Contains(Form("%3.1f_%3.1f_cat0",nearest,nextNear)) || hName.Contains(Form("%3.1f_cat0",mass))) {
        TH1F *temp = (TH1F*)outFile->Get(hName);
        diagFile << "    " << setw(30) << temp->GetName();
        diagFile << "    " << setw(8) << temp->GetEntries();
        diagFile << "    " << setw(8) << temp->Integral() << std::endl;
      }
    }
  }
    
  outFile->Close();

  std::cout << "Diagnostics log written to \"BDTInterpolationDiagnostics.txt\"" << std::endl;
  if (davidCalls>0) std::cout << davidCalls << " plots written to: plots/ada/david/ \n                    plots/grad/david/ " << std::endl;
  if (davidCalls>0) std::cout << davidCalls << " plots written to: plots/ada/diff/ \n                    plots/grad/diff/ " << std::endl;
  if (fracCalls>0) std::cout << fracCalls << " plots written to: plots/ada/frac/ \n                      plots/grad/frac/" << std::endl;
  if (systCalls>0) std::cout << systCalls << " plots written to: plots/ada/syst/ \n                    plots/grad/syst/ " << std::endl;
  if (bkgCalls>0) std::cout << bkgCalls << " plots written to: plots/ada/bkgMod/ \n                    plots/grad/bkgMod/ " << std::endl;

  std::string TIME_DATE = getTime();
  if (Diagnose){
    /*
    system("whoami > temp.txt");
    std::ifstream temp("temp.txt");
    std::string result;
    temp >> result;
    temp.close();
    system("rm temp.txt");
    system(("python make_html.py "+result+" "+TIME_DATE+" "+inFileName).c_str());
    system(("mkdir -p ~/public_html/h2g/MVA/SigInt/Diagnostics/"+TIME_DATE+"/").c_str());
    system(("cp -r plots ~/public_html/h2g/MVA/SigInt/Diagnostics/"+TIME_DATE+"/").c_str());
    system(("rm ~/public_html/h2g/MVA/SigInt/Diagnostics/Current"));
    system(("ln -s ~/public_html/h2g/MVA/SigInt/Diagnostics/"+TIME_DATE+" ~/public_html/h2g/MVA/SigInt/Diagnostics/Current").c_str());
    std::cout << ("Plots avaiable to view in ~/public_html/h2g/MVA/SigInt/Diagnostics/"+TIME_DATE+"/").c_str() << std::endl;
    std::cout << "If working on /vols/ at IC plots avaliable to view at www.hep.ph.ic.ac.uk/~"+result+"/h2g/MVA/SigInt/Diagnostics/Current/plots/plots.html" << std::endl;
    */
  }
  std::cout << "Checking all relevant histograms have been written to workspace......" << std::endl;
  //system(("python checkOK.py "+string(outFile->GetName())).c_str());
  std::cout << "New workspace written to " << outFile->GetName() << std::endl;
  return 0;
}
Ejemplo n.º 27
0
void unfoldPt(int mode=0)
{

   // Matched Tracklets
   TFile *inf = new TFile("match-10TeV-12.root");
   TNtuple *nt = (TNtuple*)inf->FindObjectAny("nt");

   // Test sample
   TFile *infTest = new TFile("./TrackletTree-Run123596.root");
   TNtuple *ntTest = (TNtuple*)infTest->FindObjectAny("TrackletTree12");
   
   TFile *pdfFile;
   if (mode==0) pdfFile = new TFile("pdf.root","recreate");
           else pdfFile = new TFile("pdf.root");

   double nPtBin=15;
   double minPt=log(0.05);
   double maxPt=log(10);
   double nDphiBin=600;
   double maxDphi=0.4;
   
   char* mycut = Form("abs(eta)<2&&log(pt)>%f&&log(pt)<%f",minPt,maxPt);
   char* mycut1=Form("abs(eta)<2&&log(pt)>%f&&log(pt)<%f&&abs(eta-eta1)<0.01&&abs(deta)<0.01",minPt,maxPt);

   TH2F *h;
   TH1F *hdphi = new TH1F("hdphi","",nDphiBin,0,maxDphi);
   TH1F *hdphi2;
   TH1F *hpt;
   TH1F *hptH = new TH1F("hptH","",nPtBin,minPt,maxPt);
   
   TH1F *hptUnfold = new TH1F("hptUnfold","",nPtBin,minPt,maxPt);
   TH1F *hptMC = new TH1F("hptMC","",nPtBin,minPt,maxPt);
   TH1F *hptTemp = new TH1F("hptTemp","",nPtBin,minPt,maxPt);

   // Delta phi as a function of matched genparticle transverse momentum
   TCanvas *c = new TCanvas("c","",600,600);
   
   if (mode == 0) {
      h = new TH2F("h","",nPtBin,minPt,maxPt,nDphiBin,0,maxDphi);
      hdphi2 = new TH1F("hdphiMC","",nDphiBin,0,maxDphi);
      hpt = new TH1F("hpt","",nPtBin,minPt,maxPt);      
      h->SetXTitle("ln(P_{T}) GeV/c");
      h->SetYTitle("|#Delta#phi|");
      nt->Draw("abs(dphi):log(pt)>>h",mycut1,"col");
      // used to generate pdf
      nt->Draw("abs(dphi)>>hdphiMC",mycut,"");
      nt->Draw("log(pt)>>hpt",mycut,"");
      h->Write();      
      hpt->Write();      
      hdphi2->Write();      
   } else {
      h = (TH2F*) pdfFile->FindObjectAny("h");
      hdphi2 = (TH1F*) pdfFile->FindObjectAny("hdphiMC");
      hpt = (TH1F*) pdfFile->FindObjectAny("hpt");
   }
   // Delta phi fit
   TCanvas *c2 = new TCanvas("c2","",600,600);
   c2->SetLogy();
   c2->SetLogx();

 
   // dphi for unfolding and MC truth:  
   ntTest->Draw("abs(dphi)>>hdphi","abs(eta1)<2&&abs(deta)<0.1","",200000);
   ntTest->Draw("log(pt)>>hptH",mycut,"",200000);
   
   histFunction2D *myfun = new histFunction2D(h);
   
   TF1 *test = new TF1("histFun",myfun,&histFunction2D::evaluate,0,maxDphi,nPtBin+1);
   TF1 *test2 = new TF1("histFunMC",myfun,&histFunction2D::evaluate,0,maxDphi,nPtBin+1);

   for (int i=0;i<nPtBin+1;i++)
   {  
      test->SetParameter(i,1);   
   }


   hdphi2->SetXTitle("|#Delta#phi|");
   hdphi2->SetYTitle("Arbitrary Normalization");
   hdphi2->Fit("histFunMC","M");

   hdphi->SetXTitle("|#Delta#phi|");
   hdphi->SetYTitle("Arbitrary Normalization");
   hdphi->Fit("histFun","M");
   hdphi->SetStats(0);
   hdphi->Draw();

   
   for (int i=0;i<nPtBin+1;i++) {
      TF1 *testPlot = new TF1(Form("histFun%d",i),myfun,&histFunction2D::evaluate,0,maxDphi,nPtBin+1);

      testPlot->SetParameter(i,test->GetParameter(i));
      testPlot->SetLineColor(i+2);
      testPlot->Draw("same");
   }
   
   int total=0,totalMC=0;


   for (int i=0;i<nPtBin;i++){
      if (test->GetParameter(i)==0) continue;
      hptUnfold->SetBinContent(i+1,fabs(test->GetParameter(i)));
      hptUnfold->SetBinError(i+1,test->GetParError(i));

      hptMC->SetBinContent(i+1,fabs(test2->GetParameter(i)));
      hptMC->SetBinError(i+1,test2->GetParError(i));

      total+=fabs(test->GetParameter(i));
      totalMC+=fabs(test2->GetParameter(i));
   }

   hptUnfold->SetEntries(total);
   hptMC->SetEntries(totalMC);
   
   TCanvas *c3 = new TCanvas("c3","",600,600);
   hpt->Sumw2();
   hptH->Sumw2();
   //hptMC->Sumw2();
   
   double normMC=0;
   double norm=0;
   double normTruth=0;
   

   hptUnfold->SetMarkerColor(2);
   hptUnfold->SetMarkerStyle(4);
//   hptUnfold->Scale(1./hptUnfold->GetEntries());
   TH1F *hptCorrected = (TH1F*)hptUnfold->Clone();
   hptCorrected->SetName("hptCorrected");
   hptMC->Divide(hpt);
   hptCorrected->Divide(hptMC);
   
   for (int i=0;i<nPtBin;i++){
      if (hptMC->GetBinContent(i)<=0.001)hptCorrected->SetBinContent(i,0);
   }
   hptCorrected->Scale(1./(hptCorrected->GetSum()));
   hptCorrected->SetMarkerStyle(20);

   hpt->Scale(1./hpt->GetEntries());
   if (hptH->GetEntries())hptH->Scale(1./hptH->GetEntries());

   hptTemp->SetXTitle("ln(P_{T}) GeV/c");
   hptTemp->SetYTitle("Arbitrary Normalization");
   hptTemp->Draw();
   

   hptH->SetXTitle("ln(P_{T}) GeV/c");
   hptH->SetYTitle("Arbitrary Normalization");
   hptH->Draw("hist");
   hptH->SetLineColor(4);
   
   hpt->Draw("hist same ");
   
   hptCorrected->Draw("same");
   
   TH1F *hptUnfoldRatio = (TH1F*)hptUnfold->Clone();
   hptUnfoldRatio->SetName("hptUnfoldRatio");
   hptUnfoldRatio->Scale(1./hptUnfoldRatio->GetSum());
   //hptUnfoldRatio->Divide(hptH);

   TH1F *hptCorrectedRatio = (TH1F*)hptCorrected->Clone();
   hptCorrectedRatio->SetName("hptCorrectedRatio");
   hptCorrectedRatio->SetMarkerColor(2);
   //hptCorrectedRatio->Divide(hptH);

   TCanvas *c4 = new TCanvas("c4","",600,600);
   TLine *l = new TLine(-2.5,1,2.5,1);
   hptUnfoldRatio->Draw();
   hptMC->Draw("same");
   hptCorrectedRatio->Draw("same");
   l->Draw("same");
}
Ejemplo n.º 28
0
bool PlotManager::saveResolution(const string& histName, const string& histTitle, 
                                   const string& srcHistName, const char sliceDirection)
{
  if ( ! isSetup_ ) return false;
  
  TH2F* srcHist = dynamic_cast<TH2F*>(theSrcFile_->Get(srcHistName.c_str()));

  // Check validity of objects
  if ( srcHist == NULL ) {
    cerr << "Cannot get object : " << histName << endl;
    return false;
  }
  
  if ( srcHist->IsA()->InheritsFrom("TH2") ) return false;

  // Push to base directory
  string pwd(gDirectory->GetPath());

  string newHistPath = dirname(histName);
  string newHistName = basename(histName);

  if ( newHistPath.empty() ) {
    theOutFile_->cd();
  }
  else if ( theOutFile_->cd(newHistPath.c_str()) == kFALSE ) {
    cout << "Cannot find directory, do mkdirs" << endl;
    mkdirs(theOutFile_, newHistPath)->cd();
  }

  // Create a function for resolution model
  TF1 gaus("gaus", "gaus");
  gaus.SetParameters(1.0, 0.0, 0.1);
  //gaus.SetRange(yMin, yMax);

  // Do FitSlices.
  if ( sliceDirection == 'X' ) srcHist->FitSlicesX(&gaus);
  else srcHist->FitSlicesY(&gaus);

  TH1F* meanHist  = dynamic_cast<TH1F*>(theOutFile_->Get((srcHistName+"_1").c_str()));
  TH1F* widthHist = dynamic_cast<TH1F*>(theOutFile_->Get((srcHistName+"_2").c_str()));
  TH1F* chi2Hist  = dynamic_cast<TH1F*>(theOutFile_->Get((srcHistName+"_chi2").c_str()));

  // Cosmetics
  meanHist ->SetName((newHistName+"_Mean" ).c_str());
  widthHist->SetName((newHistName+"_Width").c_str());
  chi2Hist ->SetName((newHistName+"_Chi2" ).c_str());

  meanHist ->SetTitle((histTitle+" Mean" ).c_str());
  widthHist->SetTitle((histTitle+" Width").c_str());
  chi2Hist ->SetTitle((histTitle+" Chi2" ).c_str());

  meanHist ->GetYaxis()->SetTitle("Gaussian mean"        );
  widthHist->GetYaxis()->SetTitle("Gaussian width"       );
  chi2Hist ->GetYaxis()->SetTitle("Gaussian fit #Chi^{2}");

  // Save histograms
  meanHist ->Write();
  widthHist->Write();
  chi2Hist ->Write();

  // Pop directory
  gDirectory->cd(pwd.c_str());

  return true;
}
Ejemplo n.º 29
0
void newhistos(int cem = 8, int iPlot = 0){
  
  gStyle->SetOptStat(0);
  gStyle->SetOptTitle(0);
  gStyle->SetErrorX(0);
  
  gStyle->SetOptStat(0);
  gStyle->SetPalette(1);
  gROOT->SetBatch(1);
    
  gStyle->SetCanvasBorderMode(0);
  gStyle->SetCanvasColor(kWhite);
  gStyle->SetCanvasDefH(600);
  gStyle->SetCanvasDefW(600);
  gStyle->SetLabelFont(18,"");
  
  labelcms  = new TPaveText(0.12,0.88,0.5,0.94,"NDCBR");
  labelcms->SetTextAlign(12);
  labelcms->SetTextSize(0.045);
  labelcms->SetFillColor(kWhite);
  if (cem !=8) labelcms->AddText("CMS Preliminary, #sqrt{s} = 7 TeV");
  else labelcms->AddText("CMS Preliminary, #sqrt{s} = 8 TeV");
  labelcms->SetBorderSize(0);
    
  
  
  char myRootFile[300];
  if (cem !=8) sprintf(myRootFile,"rootfiles/signal_study_7TeV.root");
  else sprintf(myRootFile,"rootfiles/signal_study.root");
  
  TFile *_file0 = TFile::Open(myRootFile);
  
  const int nProcess = 4;
  TString processName[nProcess] =  { "wz", "www", "fakes","zz"};
  TString processTitle[nProcess] = { "WZ", "tri-boson", "fakes", "ZZ"};
  Color_t color[nProcess] =        { kBlue+2, kBlue-9, kGray, kGray+2};
 
  const int nPlots = 17;
  TString cutLabel[nPlots] =     { "mH_2d", "dphiljj", "dphilmjj", "met", "mllz", "mt", "ptjet", "mjj", "dRll", "tmet", "minmet", "njets", "minmll", "id", "mlll", "mH", "njets"};
  int rebinHisto[nPlots] =       { 20, 10, 10, 0, 10, 10, 10, 10, 10, 10, 10, 1, 10, 1, 10, 10, 1};
  TString cutTitle[nPlots] =     { "Reconstructed mass m_{H}", "#Delta#Phi_{jjl}", "#Delta#Phi_{jjlMET}", "MET", "m_{ll} Z", "m_{T}", "P_{T} of the leading jet",
                                   "m_{jj}", "#DeltaR_{ll}", "tracker MET", "min(MET, tracker MET)", "# of jets", "|m_{jj} - m{Z}|", "lepton content", "m_{lll}", "Reconstructed mass m_{H}", 
				   "Number of jets"  }; 

 TString cm[2] = {"8TeV", "7TeV"};
 
  TFile f_var("rootfiles/ZH_histos_" + cm[8 - cem]  +  ".root", "RECREATE");
  
  
  TH1D*  h [nPlots][nProcess];
  TH1D*  h0 [nPlots];
  TH1D*  h1 [nPlots];
  THStack* hStack[nPlots];
  
 
    h0[iPlot] = (TH1D*) _file0->Get("sig_" + cutLabel[iPlot]);
       
   // h0[iPlot]->SetLineColor(kMagenta-4);
    //h0[iPlot]->SetLineWidth(2);
    h0[iPlot]->Rebin(rebinHisto[iPlot]);

    
    for (int iProcess = 0; iProcess < nProcess; iProcess++){
      h[iPlot][iProcess] = (TH1D*) _file0->Get("bck_" + cutLabel[iPlot]+ "_" + processName[iProcess]);
      h[iPlot][iProcess]->Rebin(rebinHisto[iPlot]);
     // h[iPlot][iProcess]->SetFillColor(color[iProcess]);
     // h[iPlot][iProcess]->SetLineColor(kBlack);
     // h[iPlot][iProcess]->SetLineWidth(1);
     
    }
    
    hStack[iPlot] = new THStack(cutLabel[iPlot],cutLabel[iPlot]);
    for (int iProcess = nProcess-1; iProcess > -1; iProcess--){
      hStack[iPlot]->Add(h[iPlot][iProcess]);
    }
  
    h1[iPlot] = (TH1D*) _file0->Get("data_" + cutLabel[iPlot]);
    h1[iPlot]->Rebin(rebinHisto[iPlot]);
    //h1[iPlot]->SetMarkerStyle(20);
    //h1[iPlot]->SetMarkerSize(1.2);
    //h1[iPlot]->SetLineWidth(1);
    //h1[iPlot]->SetMarkerColor(kBlack);
    //h1[iPlot]->SetLineColor(kBlack);
 
    
    TH1F* histo2 = h[iPlot][3]->Clone(); //ZZ
    histo2->SetName("ZZ");
    TH1F* histo3 = h[iPlot][0]->Clone(); //WZ 
    histo3->Add(h[iPlot][1]); // VVV
    histo3->SetName("WZ");
    TH1F* histo4 = h[iPlot][2]->Clone(); //fakes
    histo4->SetName("fakes");
    TH1F* histo5 = h1[iPlot]->Clone(); //data
     histo5->SetName("Data");
    
    
    TH1F* histos = h0[iPlot]->Clone(); //signal
     histos->SetName("VH");
  
  f_var.Write();
  f_var.Close();
  
}
Ejemplo n.º 30
0
void bbtt_upg_em(std::string var,int nbins, double xmin, double xmax,std::string xtitle, std::string ytitle, double sigscale=1)
{

  TFile *outDC = new TFile("hh_em_inputs.root","RECREATE");

  SetStyle(); gStyle->SetLineStyleString(11,"20 10");
  TH1::SetDefaultSumw2(1);
 
  //std::string dir = "/data/blue/Bacon/029a/Upgrade/merged_talk_jun30/";
  std::string dir = "/afs/cern.ch/work/j/jlawhorn/public/ntuples/";
  
  std::stringstream scale; scale << sigscale;
  
  //Cut definitions
  double luminosity = 3000;
  std::stringstream lumi; lumi << luminosity;
  std::string objcut = "(tauCat1==3 && tauCat2==2 && ptTau1>20 && ptTau2>20 && tauIso2<0.4 && tauIso1<0.4 && (bTag1==2||bTag1==3||bTag1==6||bTag1==7) && (bTag2==1||bTag2==3||bTag2==6||bTag2==7) && ptB1>20 && ptB2>20 && sqrt( (etaTau1-etaTau2)**2 + (phiTau1-phiTau2)**2 )>0.4)";
  std::string jetcut = objcut+"*(mTT>20 && mTT<90)*(mBB1>70 && mBB1<140)*(mt2pileup>100)*(bdtVal>-0.05)";
  //signal region
  std::string mccut = jetcut+"*eventWeight*"+lumi.str();
  std::string sigcut = jetcut+"*eventWeight*"+lumi.str();
  std::string zjetcut = jetcut+"*eventWeight*(eventType==4)*"+lumi.str();
  std::string wjetcut = jetcut+"*eventWeight*(eventType==3)*"+lumi.str();
  std::string ewkcut = jetcut+"*eventWeight*(eventType!=1)*"+lumi.str();
  //--------------------------------------------------------------------------
  
  //Get the trees
  TTree *hhtree = load(dir+"HHToTTBB_14TeV.root"); 
  TTree *tttree = load(dir+"tt.root"); 
  //TTree *vbfhtree = load(dir+"VBFToTT_14TeV_phase2.root");
  //TTree *gfhtree = load(dir+"H.root");
  //TTree *vjettree = load(dir+"Vjets.root");
  //TTree *ewktree = load(dir+"diboson.root");
  
  //-------------------------------------------------------------------------
  
  //Get histograms
  TCanvas *canv0 = MakeCanvas("canv", "histograms", 600, 600);
  canv0->cd();
  std::string vardraw;
  /*  TH1F *Ztt = new TH1F("DY","",nbins,xmin,xmax);
  vardraw = var+">>"+"DY";
  vjettree->Draw(vardraw.c_str(),zjetcut.c_str());
  InitHist(Ztt  , xtitle.c_str(), ytitle.c_str(), TColor::GetColor(248,206,104), 1001);*/
  TH1F *ttbar = new TH1F("TTbar","",nbins,xmin,xmax);
  vardraw = var+">>"+"TTbar";
  tttree->Draw(vardraw.c_str(),mccut.c_str());
  InitHist(ttbar, xtitle.c_str(), ytitle.c_str(), TColor::GetColor(155,152,204), 1001);
  /*  TH1F *wjets = new TH1F("Wjets","",nbins,xmin,xmax);
  vardraw = var+">>"+"Wjets";
  vjettree->Draw(vardraw.c_str(),wjetcut.c_str());
  InitHist(wjets, xtitle.c_str(), ytitle.c_str(), TColor::GetColor(222,90,106), 1001);
  TH1F *ewk = new TH1F("Ewk","",nbins,xmin,xmax);
  vardraw = var+">>"+"Ewk";
  ewktree->Draw(vardraw.c_str(),ewkcut.c_str());
  InitHist(ewk, xtitle.c_str(), ytitle.c_str(),  TColor::GetColor(222,90,106), 1001);
  TH1F *vbfh = new TH1F("VBFH","",nbins,xmin,xmax);
  vardraw = var+">>"+"VBFH";
  vbfhtree->Draw(vardraw.c_str(),mccut.c_str());
  InitHist(vbfh, xtitle.c_str(), ytitle.c_str(),  TColor::GetColor(250,202,255), 1001);
  TH1F *ggh = new TH1F("GGH","",nbins,xmin,xmax);
  vardraw = var+">>"+"GGH";
  gfhtree->Draw(vardraw.c_str(),mccut.c_str());
  InitHist(ggh, xtitle.c_str(), ytitle.c_str(),  TColor::GetColor(250,202,255), 1001);*/
  TH1F *smhh = new TH1F("SMhh","",nbins,xmin,xmax);
  vardraw = var+">>"+"SMhh";
  hhtree->Draw(vardraw.c_str(),sigcut.c_str());
  InitSignal(smhh);
  smhh->SetLineColor(kBlack);
  delete canv0;
  //---------------------------------------------------------------------------
  //Print out the yields
  Double_t error=999;
  //ofstream outfile;
  //outfile.open("yields.txt");
  //outfile << "Yields for the signal region." << std::endl;
  cout << "SM hh   "  << smhh->IntegralAndError(0,smhh->GetNbinsX(),error) << "+/-";
  cout << error << endl; error=999;
  /*  outfile << "SM h   "  << smhh->IntegralAndError(0,smhh->GetNbinsX(),error) << "+/-" << error << endl;
      outfile << "Ztt    "  << Ztt->IntegralAndError(0,Ztt->GetNbinsX(),error) << "+/-" << error << endl;*/
  cout << "ttbar    "  << ttbar->IntegralAndError(0,ttbar->GetNbinsX(),error) << "+/-";
  cout << error << endl; error=999;
  /*  outfile << "ewk    "  << ewk->IntegralAndError(0,ewk->GetNbinsX(),error) << "+/-" << error << endl;
      outfile << "wjets    "  << wjets->IntegralAndError(0,wjets->GetNbinsX(),error) << "+/-" << error << endl;*/
  //--------------------------------------------------------------------------
  //outfile.close();
  outDC->cd();
  TDirectory* lTD = outDC->mkdir("emu");
  outDC->cd(lTD->GetPath());
  ttbar->SetName("data_obs");
  ttbar->SetTitle("data_obs");
  ttbar->Write();
  /*Ztt->SetName("ZTT");
  Ztt->SetTitle("ZTT");
  Ztt->Write();*/
  ttbar->SetName("TT");
  ttbar->SetTitle("TT");
  ttbar->Write();
  /*wjets->SetName("W");
  wjets->SetTitle("W");
  wjets->Write();
  ewk->SetName("VV");
  ewk->SetTitle("VV");
  ewk->Write();
  vbfh->SetName("qqH");
  vbfh->SetTitle("qqH");
  vbfh->Write();
  ggh->SetName("ggH");
  ggh->SetTitle("ggH");
  ggh->Write();*/
  smhh->SetName("ggHH");
  smhh->SetTitle("ggHH");
  smhh->Write();
  outDC->Close();
  //stack some  histtograms together
  //vbfh->Add(ggh); 
  //wjets->Add(ewk); 
  //-----------------------------------------------------------------------
  smhh->Scale(sigscale);
  //Draw the histograms
  TCanvas *canv = MakeCanvas("canv", "histograms", 600, 600);
  canv->cd();
  //wjets->Add(ttbar);  //Ztt->Add(wjets); 
  //vbfh->Add(Ztt);
  //Error band stat
  //TH1F* errorBand = (TH1F*)vbfh ->Clone("errorBand");
  TH1F* errorBand = (TH1F*)ttbar ->Clone("errorBand");
  errorBand  ->SetMarkerSize(0);
  errorBand  ->SetFillColor(13);
  errorBand  ->SetFillStyle(3013);
  errorBand  ->SetLineWidth(1);
  //  for(int idx=0; idx<errorBand->GetNbinsX(); ++idx){
  //     if(errorBand->GetBinContent(idx)>0){
  //       std::cout << "Uncertainties on summed background samples: " << errorBand->GetBinError(idx)/errorBand->GetBinContent(idx) << std::endl;
  //       break;
  //     }
  //}
  ttbar->SetMaximum(1.1*std::max(maximum(ttbar, 0), maximum(smhh, 0)));
  //blind(data,75,150);
  //data->Draw("e");
  //vbfh->Draw("hist");
  //Ztt->Draw("histsame");
  //wjets->Draw("histsame");
  //ttbar->Draw("histsame");
  ttbar->SetTitle("");
  ttbar->Draw("hist"); 
  //data->Draw("esame");
  errorBand->Draw("e2same");
  smhh->Draw("histsame");
  canv->RedrawAxis();
  //canv->SetLogy(1);
  //---------------------------------------------------------------------------
  //Adding a legend
  TLegend* leg = new TLegend(0.53, 0.65, 0.95, 0.90);
  SetLegendStyle(leg);
  leg->AddEntry(smhh  , TString::Format("%.0f#timeshh#rightarrow#tau#tau bb", sigscale) , "L" );
  //leg->AddEntry(smhh , TString::Format("%.0f#timeshh#rightarrow#tau#tau bb", sigscale1) , "L" );
  //leg->AddEntry(data , "Observed"                       , "LP");
  //leg->AddEntry(vbfh  , "SM H#rightarrow#tau#tau"   , "F" );
  //leg->AddEntry(Ztt  , "Z#rightarrow#tau#tau"           , "F" );
  leg->AddEntry(ttbar, "t#bar{t}"                       , "F" );
  //leg->AddEntry(wjets  , "Electroweak"                    , "F" );
  leg->AddEntry(errorBand,"bkg. uncertainty","F");
  leg->Draw();
  //---------------------------------------------------------------------------
   
  //CMS preliminary 
  const char* dataset = "CMS Simulation, 3000 fb^{-1} at 14 TeV";
  const char* category = "";
  CMSPrelim(dataset, "#tau_{e}#tau_{#mu}", 0.17, 0.835);
  //CMSPrelim(dataset, "", 0.16, 0.835);
  TPaveText* chan     = new TPaveText(0.52, 0.35, 0.91, 0.55, "tlbrNDC");
  chan->SetBorderSize(   0 );
  chan->SetFillStyle(    0 );
  chan->SetTextAlign(   12 );
  chan->SetTextSize ( 0.05 );
  chan->SetTextColor(    1 );
  chan->SetTextFont (   62 );
  chan->AddText(category);
  chan->Draw();
  //-------------------------------------------------------------------------
  //Save histograms
  canv->Print((var+"_em.png").c_str());
  
  /*
    Ratio Data over MC
  */
  /*
  TCanvas *canv1 = MakeCanvas("canv0", "histograms", 600, 400);
  canv1->SetGridx();
  canv1->SetGridy();
  canv1->cd();

  TH1F* model = (TH1F*)Ztt ->Clone("model");
  TH1F* test1 = (TH1F*)vbfh->Clone("test1"); 
  for(int ibin=0; ibin<test1->GetNbinsX(); ++ibin){
    //the small value in case of 0 entries in the model is added to prevent the chis2 test from failing
    model->SetBinContent(ibin+1, model->GetBinContent(ibin+1)>0 ? model->GetBinContent(ibin+1)*model->GetBinWidth(ibin+1) : 0.01);
    //model->SetBinError  (ibin+1, CONVERVATIVE_CHI2 ? 0. : model->GetBinError  (ibin+1)*model->GetBinWidth(ibin+1));
    model->SetBinError  (ibin+1, 0);
    test1->SetBinContent(ibin+1, test1->GetBinContent(ibin+1)*test1->GetBinWidth(ibin+1));
    test1->SetBinError  (ibin+1, test1->GetBinError  (ibin+1)*test1->GetBinWidth(ibin+1));
  }
  double chi2prob = test1->Chi2Test      (model,"PUW");        std::cout << "chi2prob:" << chi2prob << std::endl;
  double chi2ndof = test1->Chi2Test      (model,"CHI2/NDFUW"); std::cout << "chi2ndf :" << chi2ndof << std::endl;
  double ksprob   = test1->KolmogorovTest(model);              std::cout << "ksprob  :" << ksprob   << std::endl;
  double ksprobpe = test1->KolmogorovTest(model,"DX");         std::cout << "ksprobpe:" << ksprobpe << std::endl;  

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

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