void LATcorr::UpdateErrorbars()
{

   if(afterR)	 afterR->Sumw2();
   if(beforeR)	 beforeR->Sumw2(); 

}
Exemple #2
0
TH1* subtractHistograms(const std::string& newHistogramName, const TH1* histogram_central, const TH1* histogram_shift, int mode)
{
  const TH1* histogramMinuend = 0;
  const TH1* histogramSubtrahend = 0;
  if ( compIntegral(histogram_central) >= compIntegral(histogram_shift) ) {
    histogramMinuend    = histogram_central;
    histogramSubtrahend = histogram_shift;
  } else {
    histogramMinuend    = histogram_shift;
    histogramSubtrahend = histogram_central;
  }
  if ( !(histogramMinuend && histogramSubtrahend) ) return 0;
  TH1* newHistogram = (TH1*)histogramMinuend->Clone(newHistogramName.data());
  newHistogram->Reset();
  if ( !newHistogram->GetSumw2N() ) newHistogram->Sumw2();
  int numBins = newHistogram->GetNbinsX();
  for ( int iBin = 0; iBin <= (numBins + 1); ++iBin ) {
    double newBinContent = histogramMinuend->GetBinContent(iBin) - histogramSubtrahend->GetBinContent(iBin);
    double newBinError2 = square(histogramMinuend->GetBinError(iBin)) + square(histogramSubtrahend->GetBinError(iBin));
    if ( mode == kRelative ) {
      if ( histogram_central->GetBinContent(iBin) > 0. ) {
	newBinContent /= histogram_central->GetBinContent(iBin);
	newBinError2 /= square(histogram_central->GetBinContent(iBin));
      } else {
	newBinContent = 0.;
	newBinError2 = 0.;
      }
    }
    newHistogram->SetBinContent(iBin, newBinContent);
    assert(newBinError2 >= 0.);
    newHistogram->SetBinError(iBin, TMath::Sqrt(newBinError2));
  }
  return newHistogram;
}
TH1* getHistogram(TFile* inputFile, const std::string& channel, double massPoint, 
		  const std::string& directory, const std::string& histogramName, double metResolution)
{
  std::string process = "";
  if   ( massPoint <  95. ) process = "ZToTauTau";
  else                      process = Form("HToTauTau_M-%1.0f", massPoint);
  
  std::string metResolution_label = "";
  if ( metResolution > 0. ) metResolution_label = Form("pfMEtRes%1.0f", metResolution);
  else metResolution_label = "pfMEtResMC";

  std::vector<TH1*> histograms;
  std::string directory_process = 
    //Form("DQMData/%s/%s/%s/%s/plotEntryType1", process.data(), channel.data(), metResolution_label.data(), directory.data());
    Form("DQMData/%s/%s/%s/plotEntryType1", process.data(), channel.data(), directory.data());
  histograms.push_back(getHistogram(inputFile, directory_process, histogramName));
  TH1* histogramSum = NULL;
  for ( std::vector<TH1*>::const_iterator histogram = histograms.begin();
	histogram != histograms.end(); ++histogram ) {
    if ( !histogramSum ) {
      std::string histogramSumName = std::string((*histogram)->GetName()).append("_summed");
      histogramSum = (TH1*)(*histogram)->Clone(histogramSumName.data());
    } else {
      histogramSum->Add(*histogram);
    }
  }

  assert(histogramSum);

  if ( !histogramSum->GetSumw2N() ) histogramSum->Sumw2();
  if ( histogramSum->Integral() > 0. ) histogramSum->Scale(1./histogramSum->Integral());
  
  return histogramSum;
}
TH1* loadHistogram(TFile* inputFile, const std::string& directory, const std::string& histogramName)
{
  std::string histogramName_full = Form("%s/%s", directory.data(), histogramName.data());
  TH1* histogram = dynamic_cast<TH1*>(inputFile->Get(histogramName_full.data()));
  if ( !histogram ) {
    std::cerr << "Failed to load histogram = " << histogramName_full << " from file = " << inputFile->GetName() << " !!" << std::endl;
    assert(0);
  }
  if ( !histogram->GetSumw2N() ) histogram->Sumw2();
  histogram->Rebin(4);
  return histogram;
}
TH1* fillHistogram(TTree* testTree, const std::string& varName, const std::string& selection, const std::string& frWeightName,
		   const std::string& histogramName, unsigned numBinsX, double xMin, double xMax)
{
  std::cout << "<fillHistogram>:" << std::endl;
  std::cout << " testTree = " << testTree << std::endl;
  std::cout << " varName = " << varName << std::endl;
  std::cout << " selection = " << selection << std::endl;
  std::cout << " frWeightName = " << frWeightName << std::endl;
  std::cout << " histogramName = " << histogramName << std::endl;

  TH1* histogram = new TH1F(histogramName.data(), histogramName.data(), numBinsX, xMin, xMax);
  histogram->Sumw2();

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

  TTree* selTree = ( selection != "" ) ? testTree->CopyTree(selection.data()) : testTree;
  std::cout << " selTree = " << selTree << std::endl;

  Float_t eventWeight = 1.;
  selTree->SetBranchAddress("weight", &eventWeight);

  Float_t var = 0.;
  selTree->SetBranchAddress(varName.data(), &var);
  
  Float_t frWeight = 1.;
  if ( frWeightName != "" ) {
    std::cout << "--> setting branch-address of fake-rate weight..." << std::endl;
    selTree->SetBranchAddress(frWeightName.data(), &frWeight);
  }

  int numEntries = selTree->GetEntries();
  std::cout << "--> numEntries = " << numEntries << std::endl;
  //if ( maxEntriesToProcess != -1 ) numEntries = TMath::Min(numEntries, maxEntriesToProcess);
  for ( int iEntry = 0 ; iEntry < numEntries; ++iEntry ) {
    selTree->GetEvent(iEntry);  

    //std::cout << "iEntry = " << iEntry << ": var = " << var << ", frWeight = " << frWeight << std::endl;

    if ( frWeightName != "" ) {
      if ( TMath::Abs(frWeight) < 1. ) // some entries have weight O(-100)
                                       // --> indication of technical problem with k-NearestNeighbour tree ?
	histogram->Fill(var, frWeight*eventWeight);
    } else {
      histogram->Fill(var, eventWeight);
    }
  }

  delete dummyOutputFile;

  return histogram;
}
Exemple #6
0
TH1* loadHistogram(TFile* inputFile, const std::string& histogramName)
{
  std::cout << "loading histogram = " << histogramName << " from file = " << inputFile->GetName() << std::endl;
  TH1* histogram = dynamic_cast<TH1*>(inputFile->Get(histogramName.data()));
  std::cout << "histogram = " << histogram << std::endl;
  if ( !histogram ) {
    std::cerr << "Failed to load histogram = " << histogramName << " from file = " << inputFile->GetName() << " --> skipping !!" << std::endl;
    return 0;
  }
  if ( !histogram->GetSumw2N() ) histogram->Sumw2();
  if ( dynamic_cast<TH2*>(histogram) ) histogram = linearizeHistogram(histogram);
  //else if ( histogram->GetNbinsX() >= 100 ) histogram->Rebin(5);
  return histogram;
}
TH1* getHistogram(TFile* inputFile, const TString& directory, const TString& histogramName)
{  
  TString histogramName_full = TString("DQMData").Append("/").Append(directory);
  if ( !histogramName_full.EndsWith("/") ) histogramName_full.Append("/");
  histogramName_full.Append(histogramName);

  TH1* histogram = (TH1*)inputFile->Get(histogramName_full.Data());

  if ( histogram && !histogram->GetSumw2N() ) histogram->Sumw2();
  else if ( !histogram) 
    std::cerr << "Failed to load histogram = " << histogramName_full << " from file = " << inputFile->GetName() << " !!" << std::endl;

  return histogram;
}
TH1* GetHist(const string histname)
{
	//hists are already scaled to 10fb-1
	TH1* h = dynamic_cast<TH1*> (files[0]->Get(histname.c_str()));
	if (h == NULL)
	{
		cout << "hist " << histname << " not found in " <<  "!" << endl;
		assert (false);
	}
	TH1* hist = dynamic_cast<TH1*> (h->Clone());
	hist->Sumw2();
	hist->SetLineWidth(2);

	return hist;
}
TH1 *computeEffVsCut(TH1 *discrShape, double total)
{
	TH1 *h = discrShape->Clone(Form("%s_effVsCut", discrShape->GetName()));
	h->Sumw2();
	h->SetMaximum(1.5);
	h->SetMinimum(1e-3);

	unsigned int n = h->GetNbinsX();
	for(unsigned int bin = 1; bin <= n; bin++) {
		double efficiency = h->Integral(bin, n + 1) / total;
		double error = sqrt(efficiency * (1 - efficiency) / total);
		h->SetBinContent(bin, efficiency);
		h->SetBinError(bin, error);
	}

	return h;
}
TH1* getHistogram(TFile* inputFile, const TString& dqmDirectory, const TString& meName)
{  
  TString histogramName = dqmDirectory;
  if ( histogramName.Length() > 0 && !histogramName.EndsWith("/") ) histogramName.Append("/");
  histogramName.Append(meName);

  TH1* histogram = (TH1*)inputFile->Get(histogramName.Data());
  std::cout << "histogramName = " << histogramName.Data() << ": histogram = " << histogram;
  if ( histogram ) std::cout << ", integral = " << histogram->Integral();
  std::cout << std::endl; 

  if ( !histogram->GetSumw2N() ) histogram->Sumw2();

  if ( histogram->GetDimension() == 1 ) histogram->Rebin(5);

  return histogram;
}
TH1* loadHistogram(TFile* inputFile, const std::string& directory, const std::string& histogramName)
{
  std::string histogramName_full = Form("%s/%s", directory.data(), histogramName.data());
  TH1* histogram = dynamic_cast<TH1*>(inputFile->Get(histogramName_full.data()));
  if ( !histogram ) {
    std::cerr << "Failed to load histogram = " << histogramName_full << " from file = " << inputFile->GetName() << " !!" << std::endl;
    assert(0);
  }
  if ( !histogram->GetSumw2N() ) histogram->Sumw2();

  //int numBins = histogram->GetNbinsX();
  //for ( int iBin = 0; iBin <= (numBins + 1); ++iBin ) {
  //  histogram->SetBinError(iBin, 0.);
  //}
  //histogram->SetBinContent(0, 0.);
  //histogram->SetBinContent(numBins + 1, 0.);
  return histogram;
}
vector<TH1*> GetHist(const string histname)
{
	//hists are already scaled to 10fb-1
	vector<TH1*> hists;
	for (int i=0; i< nBins; ++i)
	{
		TH1* h = dynamic_cast<TH1*> (files[i]->Get(histname.c_str()));
		if (h == NULL)
		{
			cout << "hist " << histname << " not found in file # " << i <<  " !" << endl;
			assert (false);
		}
		TH1* hist = dynamic_cast<TH1*> (h->Clone());
		hist->Sumw2();
		hist->SetLineWidth(2);
		hists.push_back(hist);
	}

	return hists;
}
  // Do the loop here, so that we can use options like "errors"
  void Draw( const TString & xTitle = "", const TString & yTitle = "", const bool errors = false ) {

    // Create a new THStack so that it handle tha maximum
    // THStack stack(name_, title_);
    THStack * stack = new THStack(name_, title_);

    int colorIndex = 0;
    if( !(histoList_.empty()) ) {
      std::vector<TH1*>::iterator histoIter = histoList_.begin();
      for( ; histoIter != histoList_.end(); ++histoIter, ++colorIndex ) {
        TH1 * histo = *histoIter;
        if(errors) histo->Sumw2();
        // histo->SetNormFactor(1);
        if( colorIndex < 4 ) histo->SetLineColor(colors_[colorIndex]);
        else histo->SetLineColor(colorIndex);
        // Draw and get the maximum value
        TString normalizedHistoName(histo->GetName());
        TH1 * normalizedHisto = (TH1*)histo->Clone(normalizedHistoName+"clone");
        normalizedHisto->Scale(1/normalizedHisto->Integral());
        stack->Add(normalizedHisto);
      }
      // Take the maximum of all the drawed histograms
      // First we need to draw the histogram, or getAxis() will return 0... (see root code...)
      canvas_->Draw();
      canvas_->cd();
      stack->Draw("nostack");
      stack->GetYaxis()->SetTitleOffset(1.2);
      stack->GetYaxis()->SetTitle(yTitle);
      stack->GetXaxis()->SetTitle(xTitle);
      stack->GetXaxis()->SetTitleColor(kBlack);
      stack->Draw("nostack");
      legend_->Draw("same");

      canvas_->Update();
      canvas_->Draw();
      canvas_->ForceUpdate();
      //canvas_->Print("test.pdf");
      canvas_->Write();

    }
  }
TH1* getMonitorElement(TFile* inputFile, const TString& dqmDirectory, const char* dqmSubDirectory, const TString& meName)
{
  TString meName_full = TString("DQMData").Append("/");
  if ( dqmDirectory != "") meName_full.Append(dqmDirectory).Append("/");
  meName_full.Append(dqmSubDirectory).Append("/").Append(meName);
  std::cout << "meName_full = " << meName_full << std::endl;
  
  TH1* me = (TH1*)inputFile->Get(meName_full);
  std::cout << "me = " << me <<  std::endl;
  
  //if ( !me->GetSumw2() ) me->Sumw2();
  me->Sumw2();

  me->Rebin(2);

  me->Scale(1./me->Integral());

  me->SetMaximum(1.);
  me->SetStats(false);

  return me;
}
  TH1 *Draw(const plotVar_t& pv, const TCut& cut, const TCut& cutSQ ) {
    cout << "\tDrawing " << pv.plotvar << " for sample = " << info_.samplename << " ... ";
    TString hname = TString("th1")+ pv.outfile + Form("%d",info_.index);
    TH1 *histo = new TH1D(hname, hname, pv.NBINS, pv.MINRange, pv.MAXRange);
    assert(histo);
    histo->Sumw2();
    assert(tree_);
    cout << tree_->Draw(pv.plotvar+TString(">>")+hname, cut, "goff") << " events" << endl;

    if (strlen((const char *)cutSQ)) {
      hname = TString("th1") + pv.outfile + Form("%d",info_.index) + TString("SQ");
      TH1 *histoSQ = new TH1D(hname, hname, pv.NBINS, pv.MINRange, pv.MAXRange);
      tree_->Draw(pv.plotvar+TString(">>")+hname, cutSQ, "goff");
      for(int hi=1;hi<=pv.NBINS;hi++) {
	histo->SetBinError(hi,sqrt(histoSQ->GetBinContent(hi)));
      }
      delete histoSQ;
    }
    if (info_.nMCevents)
      histo->Scale(info_.xsecpblumi*info_.otherscale/(double)info_.nMCevents);

    return histo;
  }
Exemple #16
0
///////////////////////////////////////////////////////////////////
//////// Go4 GUI example script addhistos.C
//          J.Adamczewski, gsi, May 2006
//          JAM May 2015: added support for 2d histograms
// NOTE: to be run in Go4 GUI local command line only!
//       NEVER call this script in remote analysis process!!!
/////// Functionality:
// adds histogram of name2 to histogram of name1
/////// Usage:
// histogram name2 will be scaled by factor.
// (e.g. if factor==-1, his2 is substracted from his1)
// The draw flag switches if the results are displayed each time this makro is called
// if display is switched off, the result histogram is just updated in browser and existing displays
///////
Bool_t addhistos(const char* name1, const char* name2, Double_t factor, Bool_t draw)
{
   if(TGo4AbstractInterface::Instance()==0 || go4!=TGo4AbstractInterface::Instance()) {
      std::cout <<"FATAL: Go4 gui macro executed outside Go4 GUI!! returning." << std::endl;
      return kFALSE;
   }
   TString fullname1 = go4->FindItem(name1);
   TObject* ob1=go4->GetObject(fullname1,1000); // 1000=timeout to get object from analysis in ms
   TH1 *his1(0), *his2(0);
   if(ob1 && ob1->InheritsFrom("TH1"))
      his1 = (TH1*) ob1;
   if(his1==0) {
      std::cout <<"addhistos could not get histogram "<<fullname1 << std::endl;
      return kFALSE;
   }

   TString fullname2 = go4->FindItem(name2);
   TObject* ob2=go4->GetObject(fullname2,1000); // 1000=timeout to get object from analysis in ms
   if(ob2 && ob2->InheritsFrom("TH1"))
      his2 = (TH1*)ob2;
   if(his2==0) {
      std::cout <<"addhistos could not get histogram "<<fullname2 << std::endl;
      return kFALSE;
   }
   if((his1->GetDimension()) != (his2->GetDimension()))
   {
       std::cout <<"addhistos could not add histograms of different dimensions "<< std::endl;
       return kFALSE;
   }
   TH1* result = (TH1*) his1->Clone();
   TString n1 = his1->GetName();
   TString n2 = his2->GetName();
   TString t1 = his1->GetTitle();
   TString t2 = his2->GetTitle();
   TString soper;
   if(factor>0)
      soper.Form(") + %4.1E * (",factor);
   else
      soper.Form(") - %4.1E * (",-1*factor);
   TString finalname = TString("(")+n1+soper+n2+")";
   TString finaltitle = TString("(")+t1+soper+t2+")";
   result->SetName(finalname);
   result->SetTitle(finaltitle);
   result->Sumw2();
   result->Add(his2,factor);
   result->SetDirectory(0);
   TString rname = go4->SaveToMemory("Sums", result, kTRUE);
   std::cout<< "Saved result histogram to " << rname.Data() <<std::endl;
   if(draw) {
      ViewPanelHandle vpanel = go4->StartViewPanel();
      if(result->GetDimension()>1)
      {
          // superimpose mode is not supported for 2d histograms
          go4->DrawItem(rname, vpanel);
      }
      else
      {
        go4->SetSuperimpose(vpanel,kTRUE);
        go4->DrawItem(fullname1, vpanel);
        go4->DrawItem(fullname2, vpanel);
        go4->DrawItem(rname, vpanel);
      }
   }
   return kTRUE;
}
Exemple #17
0
void
GetEccenNpart_new(char* xname = "ile")
{
  gStyle->SetOptStat(0);
  gStyle->SetTitle(0);

  char name[100];

  TChain* ch = new TChain("t");
  int n;

  //you need a file list of root ntuple: fxxxx.lis
  //
  sprintf(name,"f%s.lis",xname);
  cout << "open the filelist : " << name << endl;
  ifstream fin(name);

  string filename;
  while(!fin.eof()){
    fin >> filename;
    if(filename.empty()) continue;
    cout << filename << endl;

    ch->AddFile(filename.c_str());
  }
  fin.close();

  double b;
  int ncoll;
  int npart;
  int nHitBbc_n, nHitBbc_s;
  double qBBC_n, qBBC_s;
  double vertex, ecc_std, ecc_rp, ecc_part,e4;
  double r_oll,r_geo,r_arith;
  ch->SetBranchAddress("b",            &b        );
  ch->SetBranchAddress("vertex",       &vertex   );
  ch->SetBranchAddress("ncoll",        &ncoll    );
  ch->SetBranchAddress("npart",        &npart    );
  ch->SetBranchAddress("ecc_std",      &ecc_std  );
  ch->SetBranchAddress("ecc_rp",       &ecc_rp  );
  ch->SetBranchAddress("ecc_part",     &ecc_part );
  ch->SetBranchAddress("r_ollitra",    &r_oll );
  ch->SetBranchAddress("r_geo",        &r_geo );
  ch->SetBranchAddress("r_arith",      &r_arith );
  ch->SetBranchAddress("e4",           &e4       );
  ch->SetBranchAddress("qBBC_n",       &qBBC_n   );
  ch->SetBranchAddress("qBBC_s",       &qBBC_s   );
  ch->SetBranchAddress("nHitBbc_n",    &nHitBbc_n);
  ch->SetBranchAddress("nHitBbc_s",    &nHitBbc_s);

  char fname[100];
  sprintf(fname,"rootfile/g%s_cent.root",xname);
  TFile* fout = new TFile(fname,"recreate");//rootfile to save distributions

  TH1* hbbcq    = new TH1D("hbbcq","hbbcq",12000,-0.5,2999.5);      hbbcq->Sumw2();
  TH1* hbbcqall = new TH1D("hbbcqall","hbbcqall",12000,-0.5,2999.5);hbbcqall->Sumw2();
  TH1* hbbcqeff = new TH1D("hbbcqeff","hbbcqeff",12000,-0.5,2999.5);hbbcqeff->Sumw2();

  n = ch->GetEntries();
  cout << "events: "<< n << endl;

  //First loop determines the BBC trigger efficiency
  //as function of bbcq;
  for(int i=0; i<n; i++){
    ch->GetEntry(i);

    if(nHitBbc_n>=2&&nHitBbc_s>=2){
      hbbcq->Fill( (qBBC_n+qBBC_s)/100. );//divide by 100 to fit in 0-3000 range
    }

    hbbcqall->Fill( (qBBC_n+qBBC_s)/100. );
  }
  hbbcqeff->Divide(hbbcq,hbbcqall);

  efficiency = hbbcq->Integral()/hbbcqall->Integral();
  cout << "efficiency : " << efficiency << endl;

  //hbin contains the integrated fraction starting from 0 bbc charge, including the BBC trigger efficiency
  TH1* hbin = new TH1D("hbin","hbin",hbbcq->GetNbinsX(),-0.5,2999.5);
  TH1* hbbcqscale = (TH1*)hbbcq->Clone("hbbcqscale");
  hbbcqscale->Scale(1.0/hbbcq->Integral());
  for(int i=1; i<=hbbcqscale->GetNbinsX(); i++){
    hbin->SetBinContent(i,hbbcqscale->Integral(1,i));
  }
  //Following two lines defines the array of cuts and average bbc charge
  //for centrality percentitle in 5%, 10% and 20% steps
  double bbcq5[21],bbcq10[11],bbcq20[6];
  double abbcq5[20],abbcq10[10],abbcq20[5];

  //calculate the various variables for 5% step
  GetCentrality(hbin,20,bbcq5,hbbcq,abbcq5);
  cout << endl << endl;

  //calculate the various variables for 10% step
  GetCentrality(hbin,10,bbcq10,hbbcq,abbcq10);
  cout << endl << endl;

  //calculate the various variables for 20% step
  GetCentrality(hbin,5,bbcq20,hbbcq,abbcq20);
  cout << endl << endl;

  cout << " Find cuts for all the centralities " << endl << endl;

  const int nval=9;//number of variables to fill
  char* centname[3] = {"5pStep","10pStep","20pStep"};
  char* varname[nval] = {"npart","ncoll","b","standard_ecc","reactionplane_ecc","participant_ecc","R_Ollitraut","R_Geo", "R_arith"};
  double vup[nval] = {499.5,2999.5,19.995,1,1,1,4,4,4};
  double vlo[nval] = {-0.5,-0.5,-0.005,-1,-1,-1,0,0,0};
  int vNb[nval] = {500,3000,2000,200,200,200,400,400,400};

  //initialize the histograms which are used to fill the distribution of variables for each centrality
  TH1* hvar[3][nval][20];
  for(int i=0; i<3; i++){
    int NC = 0;
    if(i==0) NC = 20;
    else if(i==1) NC = 10;
    else if(i==2) NC = 5;
    for(int ivar=0; ivar<nval; ivar++){
      for(int icen=0; icen<NC; icen++){
	sprintf(name,"hvar_%s_%s_cent%d",centname[i],varname[ivar],icen);
	hvar[i][ivar][icen] = new TH1D(name,name,vNb[ivar],vlo[ivar],vup[ivar]);
      }
    }
  }

  double qbbcsum;
  for(int i=0; i<n; i++){
    if(i%1000000==0) cout << i << endl;
    ch->GetEntry(i);

    if(!(nHitBbc_n>=2&&nHitBbc_s>=2)) continue;//BBC trigger condition

    qbbcsum = (qBBC_n+qBBC_s)/100.;

    int centbin5  = FindBin(20,bbcq5,qbbcsum);
    int centbin10 = FindBin(10,bbcq10,qbbcsum);
    int centbin20 = FindBin(5,bbcq20,qbbcsum);

    if(centbin5==-1) continue;
    if(centbin10==-1) continue;
    if(centbin20==-1) continue;

    //find the weight according to the corresponding average efficiency.
    double weight = hbbcqeff->GetBinContent(hbbcqeff->FindBin(qbbcsum));
    //5 percent step
    //
    hvar[0][0][centbin5]->Fill(npart,weight);
    hvar[0][1][centbin5]->Fill(ncoll,weight);
    hvar[0][2][centbin5]->Fill(b,weight);
    hvar[0][3][centbin5]->Fill(ecc_std,weight);
    hvar[0][4][centbin5]->Fill(ecc_rp,weight);
    hvar[0][5][centbin5]->Fill(ecc_part,weight);
    hvar[0][6][centbin5]->Fill(r_oll,weight);
    hvar[0][7][centbin5]->Fill(r_geo,weight);
    hvar[0][8][centbin5]->Fill(r_arith,weight);

    //10 percent step
    //
    hvar[1][0][centbin10]->Fill(npart,weight);
    hvar[1][1][centbin10]->Fill(ncoll,weight);
    hvar[1][2][centbin10]->Fill(b,weight);
    hvar[1][3][centbin10]->Fill(ecc_std,weight);
    hvar[1][4][centbin10]->Fill(ecc_rp,weight);
    hvar[1][5][centbin10]->Fill(ecc_part,weight);
    hvar[1][6][centbin10]->Fill(r_oll,weight);
    hvar[1][7][centbin10]->Fill(r_geo,weight);
    hvar[1][8][centbin10]->Fill(r_arith,weight);


    //20 percent step
    //
    hvar[2][0][centbin20]->Fill(npart,weight);
    hvar[2][1][centbin20]->Fill(ncoll,weight);
    hvar[2][2][centbin20]->Fill(b,weight);
    hvar[2][3][centbin20]->Fill(ecc_std,weight);
    hvar[2][4][centbin20]->Fill(ecc_rp,weight);
    hvar[2][5][centbin20]->Fill(ecc_part,weight);
    hvar[2][6][centbin20]->Fill(r_oll,weight);
    hvar[2][7][centbin20]->Fill(r_geo,weight);
    hvar[2][8][centbin20]->Fill(r_arith,weight);
  }

  //get mean and RMS values for the variables
  float var[3][nval+1][20];
  float rms[3][nval+1][20];
  for(int i=0; i<3; i++){
    int NC = 0;
    if(i==0) NC = 20;
    else if(i==1) NC = 10;
    else if(i==2) NC = 5;
    for(int icen=0; icen<NC; icen++){
      for(int ivar=0; ivar<nval; ivar++){
	var[i][ivar][icen] = hvar[i][ivar][icen]->GetMean();
	rms[i][ivar][icen] = hvar[i][ivar][icen]->GetRMS();
      }
      var[i][nval][icen] = var[i][1][icen]/sigmann;
      rms[i][nval][icen] = rms[i][1][icen]/sigmann;
    }
  }
  //save to file
  for(int ivar=0; ivar<4; ivar++){
    for(int icen=0; icen<16; icen++){
      cout<<var[0][ivar][icen]<<",";
    }
    cout<<var[2][ivar][4]<<",";
    cout<<endl;
  }

  cout.precision(4);

  sprintf(name,"5pstepresults/t%s.txt",xname);
  ofstream f5(name);
  cout << " Bin % &  npart &  ncoll &  b & ecc_std & ecc_rp & ecc_part & r_ollitrau & T_{AB}\\\\\\hline" << endl;
  for(int icen=0; icen<19; icen++){
    for(int ivar=0; ivar<7; ivar++){
      f5 << var[0][ivar][icen] << " ";
    }
    f5 << var[0][nval][icen] << " ";
    f5 <<endl<<  " (";
    /* for(int ivar=0; ivar<7; ivar++){
      f5 << rms[0][ivar][icen] << " ";
    }
    f5 << rms[0][nval][icen] << " ";
    f5 <<  ")"<< endl;
    */
    cout << icen*5 << "-" << icen*5+5;
    for(int ivar=0; ivar<7; ivar++){
      cout <<" & " <<var[0][ivar][icen] ;
    }
    cout <<" & " <<var[0][nval][icen] ;
    cout <<"\\\\"<<endl;
    for(int ivar=0; ivar<7; ivar++){
      if(ivar==0)cout <<" & ("<<rms[0][ivar][icen];
      else cout <<" & "<<rms[0][ivar][icen];
    }
    cout <<" & "<<rms[0][nval][icen];
    cout <<  ")\\\\\\hline" << endl;

    // printf(" & %3.1f & %4.1f & %2.2f & %1.3f & %1.3f & %1.3f & %1.3f \\\\\n",
    //	   var[0][0][icen],var[0][1][icen],var[0][2][icen],var[0][3][icen],var[0][4][icen],var[0][5][icen],var[0][6][icen]);
    //printf(" (& %3.1f & %4.1f & %2.2f & %1.3f & %1.3f & %1.3f & %1.3f) \\\\\\hline\n",
    //       rms[0][0][icen],rms[0][1][icen],rms[0][2][icen],rms[0][3][icen],rms[0][4][icen],rms[0][5][icen],rms[0][6][icen]);
  }
  f5.close();

  cout << endl << endl;
  sprintf(name,"10pstepresults/t%s.txt",xname);
  ofstream f10(name);
  cout <<endl<< " Bin % &  npart &  ncoll &  b & ecc_std & ecc_rp & ecc_part & r_ollitrau & T_{AB}\\\\\\hline" << endl;
  for(int icen=0; icen<10; icen++){
    for(int ivar=0; ivar<7; ivar++){
      f10 << var[1][ivar][icen] << " ";
    }
    f10 << var[1][nval][icen] << " ";
    f10 <<endl<<" (";
    /*for(int ivar=0; ivar<7; ivar++){
      f10 << rms[1][ivar][icen] << " ";
    }
    f10 << rms[1][nval][icen] << " ";
    f10 <<  ")" << endl;
    */
    cout << icen*10 << "-" << icen*10+10;
    for(int ivar=0; ivar<7; ivar++){
      cout <<" & " <<var[1][ivar][icen] ;
    }
    cout <<" & " <<var[1][nval][icen] ;
    cout <<"\\\\"<<endl;
    for(int ivar=0; ivar<7; ivar++){
      if(ivar==0)cout <<" & ("<<rms[1][ivar][icen];
      else cout <<" & "<<rms[1][ivar][icen];
    }
    cout <<" & "<<rms[1][nval][icen];
    cout <<  ")\\\\\\hline" << endl;

    //printf(" & %3.1f & %4.1f & %2.2f & %1.3f & %1.3f & %1.3f & %1.3f \\\\\n",
    //       var[1][0][icen],var[1][1][icen],var[1][2][icen],var[1][3][icen],var[1][4][icen],var[1][5][icen],var[1][6][icen]);
    //printf(" (& %3.1f & %4.1f & %2.2f & %1.3f & %1.3f & %1.3f & %1.3f) \\\\\\hline\n",
    //       rms[1][0][icen],rms[1][1][icen],rms[1][2][icen],rms[1][3][icen],rms[1][4][icen],rms[1][5][icen],rms[1][6][icen]);

  }
  f10.close();

  cout << endl << endl;
  sprintf(name,"20pstepresults/t%s.txt",xname);
  ofstream f20(name);
  cout <<endl<< " Bin % &  npart &  ncoll &  b & ecc_std & ecc_rp & ecc_part & r_ollitrau & T_{AB}\\\\\\hline" << endl;
  for(int icen=0; icen<5; icen++){
    for(int ivar=0; ivar<7; ivar++){
      f20 << var[2][ivar][icen] << " ";
    }
    f20 << var[2][nval][icen] << " ";
    f20 << endl<<  " (";

    /*for(int ivar=0; ivar<7; ivar++){
      f20 << rms[2][ivar][icen] << " ";
    }
    f20 << rms[2][nval][icen] << " ";
    f20 <<  ")"<< endl;
    */
    cout << icen*20 << "-" << icen*20+20;
    for(int ivar=0; ivar<7; ivar++){
      cout <<" & " <<var[2][ivar][icen] ;
    }
    cout <<" & " <<var[2][nval][icen] ;
    cout <<"\\\\"<<endl;
    for(int ivar=0; ivar<7; ivar++){
      if(ivar==0)cout <<" & ("<<rms[2][ivar][icen];
      else cout <<" & "<<rms[2][ivar][icen];
    }
    cout <<" & "<<rms[2][nval][icen];
    cout <<  ")\\\\\\hline" << endl;
    //printf(" & %3.1f & %4.1f & %2.2f & %1.3f & %1.3f & %1.3f & %1.3f \\\\\n",
    //       var[2][0][icen],var[2][1][icen],var[2][2][icen],var[2][3][icen],var[2][4][icen],var[2][5][icen],var[2][6][icen]);
    //printf(" (& %3.1f & %4.1f & %2.2f & %1.3f & %1.3f & %1.3f & %1.3f) \\\\\\hline\n",
    //       rms[2][0][icen],rms[2][1][icen],rms[2][2][icen],rms[2][3][icen],rms[2][4][icen],rms[2][5][icen],rms[2][6][icen]);

  }
  f20.close();

  fout->Write();
  fout->Close();

  return;
}
Exemple #18
0
TH1 *
UnfoldMe_MB2(const Char_t *data, const Char_t *mc, const Char_t *anatag, Int_t bin, Bool_t useMBcorr , Bool_t usecorrfit , Bool_t ismc , Float_t smooth , Int_t iter , Int_t regul , Float_t weight , Bool_t bayesian , Int_t nloop )
{

  // MF comments:
  // usedMBcorr: changes the matrix used for unfonding, from effMatrix to bin matrix (I think this is just to use mult dependent v s mb correction_)
  // usecorrfit: if I understand correctly, fits the response matrix and uses fit to extrapolate it

  
  TFile *fdt =0;
  if (ismc)
    fdt =  TFile::Open(data);
  else
    fdt = TFile::Open(data);
  TFile *fmc = TFile::Open(mc);

  TList *ldt = (TList *)fdt->Get(Form("%s", anatag));
  TList *lmc = (TList *)fmc->Get(Form("%s", anatag));
  
  TH2 *hmatdt = (TH2 *)ldt->FindObject(Form(responseMatrix, bin));
  TH2 *hmatmc = 0;
  if (useMBcorr){
     hmatmc = (TH2 *)lmc->FindObject("effMatrix");
     std::cout << "USING MB" << std::endl;
     
  }
  else {
    hmatmc = (TH2 *)lmc->FindObject(Form(responseMatrix, bin));
  }

  TH1 *hdata = hmatdt->ProjectionY("hdata");
//  TH1 *hdata = hmatdt->ProjectionY("htrue");  // For truth Only Calculations

  hdata->Sumw2();
  hdata->SetBinContent(1, 0.);
  hdata->SetBinError(1, 0.);
  //  hdata->Scale(1. / hdata->Integral());
  hdata->SetMarkerStyle(25);
  TH1 *htrue = hmatdt->ProjectionX("htrue");
  htrue->Sumw2();
  //  htrue->Scale(1. / htrue->Integral());
  htrue->SetMarkerStyle(7);
  htrue->SetMarkerColor(2);
  htrue->SetBinContent(1, 0.);
  htrue->SetBinError(1, 0.);

  TH2 *hcorr = (TH2 *)hmatmc->Clone("hcorr");
  TH1 *hinit = (TH1 *)hdata->Clone("hinit");
  TH1 *hresu = (TH1 *)hdata->Clone("hresu");
  TH1 *hbias = (TH1 *)hdata->Clone("hbias");
  hresu->SetMarkerStyle(20);
  hresu->SetMarkerColor(4);
  hresu->Reset();

  TH1 *hnum = hcorr->ProjectionY("hnum");
  TH1 *hden = hcorr->ProjectionY("hden");
  TH1 *heff = hcorr->ProjectionY("heff");
  hnum->Reset();
  hnum->Sumw2();
  hden->Reset();
  hden->Sumw2();
  heff->Reset();
  for (Int_t i = 0; i < heff->GetNbinsX(); i++) {
    Float_t int1 = hcorr->Integral(i + 1, i + 1, 0, -1);
    if (int1 <= 0.) continue;
    Float_t int2 = hcorr->Integral(i + 1, i + 1, 2, -1);
    hnum->SetBinContent(i + 1, int2);
    hnum->SetBinError(i + 1, TMath::Sqrt(int2));
    hden->SetBinContent(i + 1, int1);
    hden->SetBinError(i + 1, TMath::Sqrt(int1));
  }
  TCanvas *cEfficiency = new TCanvas("cEfficiency", "cEfficiency");
  cEfficiency->SetLogx();
  cEfficiency->SetLogy();

  heff->Divide(hnum, hden, 1., 1., "B");
  heff->Draw();
#if 0
  for (Int_t ii = 0; ii < heff->GetNbinsX(); ii++) {
    heff->SetBinContent(ii + 1, 1.);
    heff->SetBinError(ii + 1, 0.);
  }
#endif

  for (Int_t i = 0; i < hcorr->GetNbinsX(); i++) {
    hcorr->SetBinContent(i + 1, 1, 0.);
    hcorr->SetBinError(i + 1, 1, 0.);
  }
  for (Int_t i = 0; i < hcorr->GetNbinsY(); i++) {
    hcorr->SetBinContent(1, i + 1, 0.);
    hcorr->SetBinError(1, i + 1, 0.);
  }
  TH2 *hcorrfit = ReturnCorrFromFit(hcorr);
  // Docs from AliUnfolding
  //Int_t AliUnfolding::Unfold(TH2* correlation, TH1* efficiency, TH1* measured, TH1* initialConditions, TH1* result, Bool_t check)
  // unfolds with unfolding method fgMethodType
  //
  // parameters:
  //  correlation: response matrix as measured vs. generated
  //  efficiency:  (optional) efficiency that is applied on the unfolded spectrum, i.e. it has to be in unfolded variables. If 0 no efficiency is applied.
  //  measured:    the measured spectrum
  //  initialConditions: (optional) initial conditions for the unfolding. if 0 the measured spectrum is used as initial conditions.
  //  result:      target for the unfolded result
  //  check:       depends on the unfolding method, see comments in specific functions

  for (Int_t iloop = 0; iloop < nloop; iloop++) {
    if (bayesian) {
      AliUnfolding::SetUnfoldingMethod(AliUnfolding::kBayesian);
      AliUnfolding::SetBayesianParameters(smooth, iter);
    } else {
      AliUnfolding::SetUnfoldingMethod(AliUnfolding::kChi2Minimization);
      AliUnfolding::SetChi2Regularization(AliUnfolding::RegularizationType(regul), weight);
    }
    AliUnfolding::SetSkip0BinInChi2(kTRUE);
    AliUnfolding::SetSkipBinsBegin(1);
    AliUnfolding::SetNbins(150, 150);
    AliUnfolding::Unfold(usecorrfit ? hcorrfit : hcorr, heff, hdata, hinit, hresu);
    hinit = (TH1 *)hresu->Clone(Form("hinit_%d", iloop));
  }

  printf("hdata->Integral(2, -1) = %f\n", hdata->Integral(2, -1));
  printf("hresu->Integral(2, -1) = %f\n", hresu->Integral(2, -1));


  TCanvas *cUnfolded = new TCanvas ("cUnfolded", "cUnfolded", 400, 800);
  cUnfolded->Divide(1, 2);
  cUnfolded->cd(1)->SetLogx();
  cUnfolded->cd(1)->SetLogy();
  hdata->Draw();
  hresu->Draw("same");
  htrue->Draw("same");
  cUnfolded->cd(2)->SetLogx();
  cUnfolded->cd(2)->DrawFrame(1., 0, 300., 10);
  TH1 *hrat = (TH1 *)hresu->Clone("hrat");
  hrat->Divide(htrue);
  hrat->Draw("same");

  TH1 *htrig = (TH1 *)hresu->Clone("htrig");
  htrig->Multiply(heff); 
  

  Float_t dndeta_resu = 0.;
  Float_t integr_resu = 0.;
  Float_t dndeta_trig = 0.;
  Float_t integr_trig = 0.;
  for (Int_t i = 1; i < hresu->GetNbinsX(); i++) {
    dndeta_resu += hresu->GetBinContent(i + 1) * hresu->GetBinLowEdge(i + 1);
    integr_resu += hresu->GetBinContent(i + 1);
    dndeta_trig += htrig->GetBinContent(i + 1) * htrig->GetBinLowEdge(i + 1);
    integr_trig += htrig->GetBinContent(i + 1);
  }

  cUnfolded->SaveAs("unfold_efficiency.pdf");

  integr_eff = integr_trig / integr_resu;
  integr_eff_err = TMath::Sqrt(integr_eff * (1. - integr_eff) / integr_resu);
  dndeta_eff = dndeta_trig / dndeta_resu;
  dndeta_eff_err = TMath::Sqrt(dndeta_eff * (1. - dndeta_eff) / dndeta_resu);

  printf("INEL > 0 efficiency: %.3f +- %.3f\n", integr_eff, integr_eff_err);
  printf("dN/dEta correction:  %.3f +- %.3f\n", dndeta_eff, dndeta_eff_err);

  return hresu;
}
Exemple #19
0
TH1 *
UnfoldMe(Char_t *data, Char_t *mc, Char_t *anatag, Int_t bin, Bool_t useMBcorr = kTRUE, Bool_t usecorrfit = kFALSE, Bool_t ismc = kFALSE, Float_t smooth = 0.001, Int_t iter = 50, Int_t regul = AliUnfolding::kPowerLaw, Float_t weight = 100., Bool_t bayesian = kTRUE, Int_t nloop = 1)
{

  if (ismc)
    TFile *fdt = TFile::Open(data);
  else
    TFile *fdt = TFile::Open(data);
  TFile *fmc = TFile::Open(mc);
  
  TList *ldt = (TList *)fdt->Get(Form("clist_%s", anatag));
  TList *lmc = (TList *)fmc->Get(Form("clist_%s", anatag));
  
  TH2 *hmatdt = (TH2 *)ldt->FindObject(Form("b%d_corrMatrix", bin));
  if (useMBcorr)
    TH2 *hmatmc = (TH2 *)lmc->FindObject("effMatrix");
  else
    TH2 *hmatmc = (TH2 *)lmc->FindObject(Form("b%d_corrMatrix", bin));
 
  TH1 *hdata = hmatdt->ProjectionY("hdata");
  hdata->Sumw2();
  hdata->SetBinContent(1, 0.);
  hdata->SetBinError(1, 0.);
  //  hdata->Scale(1. / hdata->Integral());
  hdata->SetMarkerStyle(25);
  TH1 *htrue = hmatdt->ProjectionX("htrue");
  htrue->Sumw2();
  //  htrue->Scale(1. / htrue->Integral());
  htrue->SetMarkerStyle(7);
  htrue->SetMarkerColor(2);
  htrue->SetBinContent(1, 0.);
  htrue->SetBinError(1, 0.);
  TH2 *hcorr = (TH2 *)hmatmc->Clone("hcorr");
  TH1 *hinit = (TH1 *)hdata->Clone("hinit");
  TH1 *hresu = (TH1 *)hdata->Clone("hresu");
  TH1 *hbias = (TH1 *)hdata->Clone("hbias");
  hresu->SetMarkerStyle(20);
  hresu->SetMarkerColor(4);
  hresu->Reset();

  TH1 *hnum = hcorr->ProjectionY("hnum");
  TH1 *hden = hcorr->ProjectionY("hden");
  TH1 *heff = hcorr->ProjectionY("heff");
  hnum->Reset();
  hnum->Sumw2();
  hden->Reset();
  hden->Sumw2();
  heff->Reset();
  for (Int_t i = 0; i < heff->GetNbinsX(); i++) {
    Float_t int1 = hcorr->Integral(i + 1, i + 1, 0, -1);
    if (int1 <= 0.) continue;
    Float_t int2 = hcorr->Integral(i + 1, i + 1, 2, -1);
    hnum->SetBinContent(i + 1, int2);
    hnum->SetBinError(i + 1, TMath::Sqrt(int2));
    hden->SetBinContent(i + 1, int1);
    hden->SetBinError(i + 1, TMath::Sqrt(int1));
  }
  new TCanvas("cEfficiency");
  heff->Divide(hnum, hden, 1., 1., "B");
  heff->Draw();
#if 0
  for (Int_t ii = 0; ii < heff->GetNbinsX(); ii++) {
    heff->SetBinContent(ii + 1, 1.);
    heff->SetBinError(ii + 1, 0.);
  }
#endif
  
  for (Int_t i = 0; i < hcorr->GetNbinsX(); i++) {
    hcorr->SetBinContent(i + 1, 1, 0.);
    hcorr->SetBinError(i + 1, 1, 0.);
  }
  for (Int_t i = 0; i < hcorr->GetNbinsY(); i++) {
    hcorr->SetBinContent(1, i + 1, 0.);
    hcorr->SetBinError(1, i + 1, 0.);
  }
  TH2 *hcorrfit = ReturnCorrFromFit(hcorr);

  for (Int_t iloop = 0; iloop < nloop; iloop++) {
    if (bayesian) {
      AliUnfolding::SetUnfoldingMethod(AliUnfolding::kBayesian);
      AliUnfolding::SetBayesianParameters(smooth, iter);
    } else {
      AliUnfolding::SetUnfoldingMethod(AliUnfolding::kChi2Minimization);
      AliUnfolding::SetChi2Regularization(regul, weight);
    }
    AliUnfolding::SetSkip0BinInChi2(kTRUE);
    AliUnfolding::SetSkipBinsBegin(1);
    AliUnfolding::SetNbins(150, 150);
    AliUnfolding::Unfold(usecorrfit ? hcorrfit : hcorr, heff, hdata, hinit, hresu);
    hinit = (TH1 *)hresu->Clone(Form("hinit_%d", iloop));
  }

  printf("hdata->Integral(2, -1) = %f\n", hdata->Integral(2, -1));
  printf("hresu->Integral(2, -1) = %f\n", hresu->Integral(2, -1));
  
  
  TCanvas *cUnfolded = new TCanvas ("cUnfolded", "", 400, 800);
  cUnfolded->Divide(1, 2);
  cUnfolded->cd(1)->SetLogx();
  cUnfolded->cd(1)->SetLogy();
  hdata->Draw();
  hresu->Draw("same");
  htrue->Draw("same");
  cUnfolded->cd(2)->SetLogx();
  cUnfolded->cd(2)->DrawFrame(1., 0.75, 300., 1.25);
  TH1 *hrat = (TH1 *)hresu->Clone("hrat");
  hrat->Divide(htrue);
  hrat->Draw("same");

  TH1 *htrig = (TH1 *)hresu->Clone("htrig");
  htrig->Multiply(heff);

  Float_t dndeta_resu = 0.;
  Float_t integr_resu = 0.;
  Float_t dndeta_trig = 0.;
  Float_t integr_trig = 0.;
  for (Int_t i = 1; i < hresu->GetNbinsX(); i++) {
    dndeta_resu += hresu->GetBinContent(i + 1) * hresu->GetBinLowEdge(i + 1);
    integr_resu += hresu->GetBinContent(i + 1);
    dndeta_trig += htrig->GetBinContent(i + 1) * htrig->GetBinLowEdge(i + 1);
    integr_trig += htrig->GetBinContent(i + 1);
  }
  //  dndeta_resu /= integr_resu;
  //  dndeta_trig /= integr_trig;

  integr_eff = integr_trig / integr_resu;
  integr_eff_err = TMath::Sqrt(integr_eff * (1. - integr_eff) / integr_resu);
  dndeta_eff = dndeta_trig / dndeta_resu;
  dndeta_eff_err = TMath::Sqrt(dndeta_eff * (1. - dndeta_eff) / dndeta_resu);
  
  printf("INEL > 0 efficiency: %.3f +- %.3f\n", integr_eff, integr_eff_err);
  printf("dN/dEta correction:  %.3f +- %.3f\n", dndeta_eff, dndeta_eff_err);

  return hresu;
}
Exemple #20
0
// === Main Function ===================================================
void hadTau1(unsigned int id = 11, int nEvts = -1) {

  // --- Declare the Output Histograms ---------------------------------

  // The tau response templates
  // They are filled for different bins in generated tau-lepton pt.
  // The binning is encapsulated in ../Utils/TauResponse.h
  std::vector<TH1*> hTauResp(TauResponse::nBins());
  for(unsigned int i = 0; i < TauResponse::nBins(); ++i) {
    hTauResp.at(i) = new TH1D(TauResponse::name(i),";p_{T}(visible) / p_{T}(generated);Probability",50,0.,2.5);
    hTauResp.at(i)->Sumw2();
  }

  // Control histograms for the jet-tau matching efficiency
  TH1* hNJetAll = new TH1D("hNJetAll",";N(jets)",10,0,10);
  hNJetAll->Sumw2();
  TH1* hNJetPass = static_cast<TH1*>(hNJetAll->Clone("hNJetPass"));

  TH1* hHtAll = new TH1D("hHtAll",";H_{T} [GeV]",30,0,3000);
  hHtAll->Sumw2();
  TH1* hHtPass = static_cast<TH1*>(hHtAll->Clone("hHtPass"));

  TH1* hMhtAll = new TH1D("hMhtAll",";#slash{H}_{T} [GeV]",20,0,2000);
  hMhtAll->Sumw2();
  TH1* hMhtPass = static_cast<TH1*>(hMhtAll->Clone("hMhtPass"));



  // --- Analyse the events --------------------------------------------

  // Interface to the event content
  Event* evt = new Event(Sample::fileNameFullSample(id),nEvts);

  // Loop over the events (tree entries)
  while( evt->loadNext() ) {

    // Select only events where the W decayed into a hadronically
    // decaying tau
    if( !(evt->flgW() == 15 && evt->flgTau() == 1) ) continue;

    // Kinematic variables of generator-level tau
    const float genTauPt = evt->genLeptonPt();
    const float genTauEta = evt->genLeptonEta();
    const float genTauPhi = evt->genLeptonPhi();

    // Use only events where the tau is inside the muon acceptance
    // because lateron we will apply the response to muon+jet events
    if( genTauPt < TauResponse::ptMin() ) continue;
    if( std::abs(genTauEta) > TauResponse::etaMax() ) continue;


    // "Cross cleaning": find the jet that originates in the
    // hadronic tau-decay. Associate the jet that is closest in
    // deltaR to the tau. The distance has to be smaller than deltaRMax.

    // First, fill counters before jet-tau matching
    hNJetAll->Fill(evt->nJets());
    hHtAll->Fill(evt->ht());
    hMhtAll->Fill(evt->mht());

    // Do the matching
    int tauJetIdx = -1;		// Will store the index of the jet matched to the tau
    const float deltaRMax = genTauPt < 50. ? 0.2 : 0.1; // Increase deltaRMax at low pt to maintain high-enought matching efficiency
    if( !utils::findMatchedObject(tauJetIdx,genTauEta,genTauPhi,evt->jetsEta(),evt->jetsPhi(),evt->jetsN(),deltaRMax) ) continue;

    // Then, fill counters after matching
    hNJetPass->Fill(evt->nJets());
    hHtPass->Fill(evt->ht());
    hMhtPass->Fill(evt->mht());


    // Calculate RA2 selection-variables from "cleaned" jets,
    // i.e. jets withouth the tau-jet
    int selNJet = 0; // Number of HT jets (jets pt > 50 GeV and |eta| < 2.5)

    for(int jetIdx = 0; jetIdx < evt->jetsN(); ++jetIdx) {	// Loop over reco jets
      // Skip this jet if it is the tau
      if( jetIdx == tauJetIdx ) continue;

      // Calculate NJet 
      if( evt->jetsPt()[jetIdx] > Selection::htJetPtMin() && std::abs(evt->jetsEta()[jetIdx]) < Selection::htJetEtaMax() ) selNJet++;
    } // End of loop over reco jets
    
    
    // Select only events with at least 2 HT jets
    if( selNJet < 2 ) continue;
    

    // Fill histogram with relative visible energy of the tau
    // ("tau response template") for hadronically decaying taus
    for(int jetIdx = 0; jetIdx < evt->jetsN(); ++jetIdx) {	// Loop over reco jets
      // Select tau jet
      if( jetIdx == tauJetIdx ) {
	// Get the response pt bin for the tau
	const unsigned int ptBin = TauResponse::ptBin(genTauPt);
	// Fill the corresponding response template
	const double tauJetPt = evt->jetsPt()[jetIdx];
	hTauResp.at(ptBin)->Fill( tauJetPt / genTauPt );
	break;		// End the jet loop once the tau jet has been found
      }
    }	// End of loop over reco jets
  } // End of loop over tree entries


  // Normalize the response distributions to get the probability density
  for(unsigned int i = 0; i < hTauResp.size(); ++i) {
    if( hTauResp.at(i)->Integral("width") > 0. ) {
      hTauResp.at(i)->Scale(1./hTauResp.at(i)->Integral("width"));
    }
  }

  // Get the jet-tau matching efficiency
  TH1* hMatchEffNJet = static_cast<TH1*>(hNJetPass->Clone("hMatchEffNJet"));
  hMatchEffNJet->Divide(hNJetAll);
  TH1* hMatchEffHt = static_cast<TH1*>(hHtPass->Clone("hMatchEffHt"));
  hMatchEffHt->Divide(hHtAll);
  TH1* hMatchEffMht = static_cast<TH1*>(hMhtPass->Clone("hMatchEffMht"));
  hMatchEffMht->Divide(hMhtAll);


  // --- Save the Histograms to File -----------------------------------
  TFile outFile("../data/HadTau_TauResponseTemplates.root","RECREATE");
  for(unsigned int i = 0; i < hTauResp.size(); ++i) {
    hTauResp.at(i)->Write();
  }
  hMatchEffNJet->Write();
  hMatchEffHt->Write();
  hMatchEffMht->Write();
  outFile.Close();
}
Exemple #21
0
// === Main Function ===================================================
void hadTau2(unsigned int id = 11,
	     const TString &effName = "../data/LostLepton_MuonEfficienciesFromWJetMC.root",
	     const TString &respTempl = "../data/HadTau_TauResponseTemplates.root",
	     int nEvts = -1) {

  const bool isMC = ( id >= 10 );


  // --- Declare the Output Histograms ---------------------------------
  const TString title = isMC ? "Hadronic-Tau Closure Test" : "Hadronic-Tau Prediction";

  // Control plot: muon pt in the control sample
  TH1* hMuonPt = new TH1D("hMuonPt",title+";p_{T}(#mu^{gen}) [GeV];N(events)",50,0.,500.);
  hMuonPt->Sumw2();

  // Predicted distributions
  TH1* hPredHt = new TH1D("hPredHt",title+";H_{T} [GeV];N(events)",25,500.,3000.);
  hPredHt->Sumw2();
  TH1* hPredMht = new TH1D("hPredMht",title+";#slash{H}_{T} [GeV];N(events)",20,200.,1200.);   
  hPredMht->Sumw2();
  TH1* hPredNJets = new TH1D("hPredNJets",title+";N(jets);N(events)",9,3,12);   
  hPredNJets->Sumw2();

  // In case of MC: true distributions
  TH1* hTrueHt = static_cast<TH1*>(hPredHt->Clone("hTrueHt"));
  TH1* hTrueMht = static_cast<TH1*>(hPredMht->Clone("hTrueMht"));
  TH1* hTrueNJets = static_cast<TH1*>(hPredNJets->Clone("hTrueNJets"));

  // Event yields in the different RA2 search bins
  // First bin (around 0) is baseline selection
  TH1* hPredYields = new TH1D("hPredYields",title+";;N(events)",37,-0.5,36.5);
  hPredYields->Sumw2();
  hPredYields->GetXaxis()->SetBinLabel(1,"baseline");
  for(int bin = 2; bin <= hPredYields->GetNbinsX(); ++bin) {
    TString label = "Bin ";
    label += bin-1;
    hPredYields->GetXaxis()->SetBinLabel(bin,label);
  }
  TH1* hTrueYields = static_cast<TH1*>(hPredYields->Clone("hTrueYields"));



  // --- Tau Templates and Muon Efficiencies ---------------------------

  // Interface to the tau response templates
  TauResponse tauResp(respTempl);

  // Interfaces to the muon acceptance as well as reconstruction and 
  // isolation efficiencies
  LeptonAcceptance muonAcc(effName,LeptonAcceptance::nameMuonAcc());
  LeptonEfficiency muonRecoEff(effName,LeptonEfficiency::nameMuonRecoEff());
  LeptonEfficiency muonIsoEff(effName,LeptonEfficiency::nameMuonIsoEff());



  // --- Analyse the events --------------------------------------------

  // Interface to the event content
  Event* evt = new Event(Sample::fileNameFullSample(id),nEvts);

  // Loop over the events (tree entries)
  while( evt->loadNext() ) {

    // Select the control sample: 
    // - select events with exactly one well-reconstructed, isolated muon
    // Use the muon to predict the energy deposits of the 
    // hadronically decaying tau:
    // - scale the muon pt by a random factor drawn from the
    //   tau-reponse template to simulate the tau measurement
    // - use the simulated tau-pt to predict HT, MHT, and N(jets)
    if( evt->isoMuonsN() == 1 && evt->isoElectronsN() == 0 ) {

      // The kinematic properties of the well-reconstructed, isolated muon
      const float muPt = evt->isoMuonsPt()[0];
      const float muEta = evt->isoMuonsEta()[0];
      const float muPhi = evt->isoMuonsPhi()[0];
      
      // Use only events where the muon is inside acceptance
      if( muPt < TauResponse::ptMin() ) continue;
      if( std::abs( muEta ) > TauResponse::etaMax() ) continue;

      // "Cross cleaning": find the jet that corresponds to
      // the muon. Associate the jet that is closest in
      // in eta-phi space to the lepton
      int muJetIdx = -1;
      const float deltaRMax = 0.2;
      if( !utils::findMatchedObject(muJetIdx,muEta,muPhi,evt->jetsEta(),evt->jetsPhi(),evt->jetsN(),deltaRMax) ) continue;

      // Calculate RA2 selection-variables from "cleaned" jets
      int selNJet = 0;
      float selHt   = 0.;
      float selMhtX = 0.;
      float selMhtY = 0.;
      for(int jetIdx = 0; jetIdx < evt->jetsN(); ++jetIdx) {	// Loop over reco jets
	// Skip this jet if it is the muon
	if( jetIdx == muJetIdx ) continue;
	
	// Calculate NJet and HT
	if( evt->jetsPt()[jetIdx] > Selection::htJetPtMin() && std::abs(evt->jetsEta()[jetIdx]) < Selection::htJetEtaMax() ) {
	  selNJet++;
	  selHt += evt->jetsPt()[jetIdx];
	}
	// Calculate MHT
	if( evt->jetsPt()[jetIdx] > Selection::mhtJetPtMin() && std::abs(evt->jetsEta()[jetIdx]) < Selection::mhtJetEtaMax() ) {
	  selMhtX -= evt->jetsPt()[jetIdx]*cos(evt->jetsPhi()[jetIdx]);
	  selMhtY -= evt->jetsPt()[jetIdx]*sin(evt->jetsPhi()[jetIdx]);
	}
      } // End of loop over reco jets
      
      // Select only events with at least 2 HT jets
      if( selNJet < 2 ) continue;

      // Plot the muon pt as control plot
      hMuonPt->Fill(muPt);
      
      // Get random number from tau-response template
      // The template is chosen according to the muon pt
      const float scale = tauResp.getRandom(muPt);
      // Scale muon pt with tau response --> simulate tau jet pt
      const float simTauJetPt = scale * muPt;
      const float simTauJetEta = muEta;
      const float simTauJetPhi = muPhi;

      // Taking into account the simulated tau jet, recompute
      // HT, MHT, and N(jets)
      int simNJet = selNJet;
      float simHt = selHt;
      float simMhtX = selMhtX;
      float simMhtY = selMhtY;
      
      // If simulted tau-jet meets same criteria as as HT jets,
      // recompute NJets and HT
      if( simTauJetPt > Selection::htJetPtMin() && std::abs(muEta) < Selection::htJetEtaMax() ) {
	simNJet++;
	simHt += simTauJetPt;
      }
      // If simulated tau-jet meets same criteria as MHT jets,
      // recompute MHT
      if( simTauJetPt > Selection::mhtJetPtMin() && std::abs(muEta) < Selection::mhtJetEtaMax() ) {
	simMhtX -= simTauJetPt*cos(muPhi);
	simMhtY -= simTauJetPt*sin(muPhi);
      }

      const float simMht = sqrt( simMhtX*simMhtX + simMhtY*simMhtY );
      const float simMhtPhi = std::atan2(simMhtY,simMhtX);

      // Apply baseline selection
      if( !Selection::nJets(simNJet) ) continue;
      if( !Selection::ht(simHt) ) continue;
      if( !Selection::mht(simMht) ) continue;
      if( !deltaPhi(simMhtPhi,evt->jetsN(),evt->jetsPt(),evt->jetsEta(),evt->jetsPhi(),muJetIdx,simTauJetPt,simTauJetEta,simTauJetPhi) ) continue;

      // Corrections to control sample
      const double corrBRWToTauHad = 0.65;  // Correction for the BR of hadronic tau decays
      const double corrBRTauToMu = 1./1.15; // Correction for the fact that some muons could come from leptonic decays of taus from W decays
      const double acc = muonAcc(evt->mht(),evt->nJets());
      const double recoEff = muonRecoEff(evt->ht(),evt->mht(),evt->nJets());
      const double isoEff = muonIsoEff(evt->ht(),evt->mht(),evt->nJets());
      if( !( acc > 0. && recoEff > 0. && isoEff > 0. ) ) continue;
      const double corrMuAcc = 1./acc; // Correction for muon acceptance
      const double corrMuRecoEff = 1./recoEff; // Correction for muon reconstruction efficiency
      const double corrMuIsoEff = 1./isoEff; // Correction for muon isolation efficiency

      // The overall correction factor
      const double corr = corrBRTauToMu * corrBRWToTauHad * corrMuAcc * corrMuRecoEff * corrMuIsoEff;

      // Fill the prediction
      hPredHt->Fill(simHt,corr);
      hPredMht->Fill(simMht,corr);
      hPredNJets->Fill(simNJet,corr);

      // Predicted event yields
      hPredYields->Fill(0.,corr);
      const unsigned int searchBin = Selection::searchBin(simHt,simMht,simNJet);
      if( searchBin > 0 ) {
	hPredYields->Fill(searchBin,corr);
      }

    } // End if exactly one muon


    if( isMC ) {
      // Fill the 'truth' for comparison with the prediction
      // Select only events where the W decayed into a hadronically
      // decaying tau
      if( !( evt->flgW() == 15 && evt->flgTau() == 1 ) ) continue;
      
      // Apply baseline selection
      if( !Selection::nJets(evt->nJets()) ) continue;
      if( !Selection::ht(evt->ht()) ) continue;
      if( !Selection::mht(evt->mht()) ) continue;
      if( !Selection::deltaPhi(evt->deltaPhi1(),evt->deltaPhi2(),evt->deltaPhi3()) ) continue;

      hTrueHt->Fill(evt->ht());
      hTrueMht->Fill(evt->mht());
      hTrueNJets->Fill(evt->nJets());

      // True event yields
      hTrueYields->Fill(0.);
      const unsigned int searchBin = Selection::searchBin(evt->ht(),evt->mht(),evt->nJets());
      if( searchBin > 0 ) {
	hTrueYields->Fill(searchBin);
      }

    } // End isMC

  } // End of loop over events
  

  // --- Save the Histograms to File -----------------------------------
  const TString outFileName = isMC ? "HadTau_WJetMC_Closure.root" : "HadTau_Data_Prediction.root";
  TFile outFile(outFileName,"RECREATE");
  hMuonPt->Write();
  hTrueHt->Write();
  hTrueMht->Write();
  hTrueNJets->Write();
  hTrueYields->Write();
  hPredHt->Write();
  hPredMht->Write();
  hPredNJets->Write();
  hPredYields->Write();
  outFile.Close();
}
Exemple #22
0
int main(int argc, char** argv) {

  if( argc<2 ) {
     std::cout << " storehist_fullmc:     " << std::endl ;
     std::cout << " Author : Hengne Li @ LPSC 2010 " << std::endl ;
     std::cout << " Functionality: store hists for track match efficiency."  << std::endl;
     std::cout << "                 "  << std::endl;
     std::cout << " usage: storehist storehist.config" << std::endl ;
     exit(1) ;
  }

  std::cout << " storehist:     " << std::endl ;
  std::cout << " Author : Hengne Li @ LPSC 2010 " << std::endl ;

  // readme:

  // open steering file names
  config  steer(std::string((const char*)argv[1]));
  
  // output root file name
  std::string OutRootFile = steer.getString("OutRootFile");
  // input file name
  std::string InRootFile = steer.getString("InRootFile");
  // Electron Basis, if true, it will draw twice for each electron
  bool ElectronBasis = steer.getBool("ElectronBasis");
  // Dimension of efficiency dependece vars: e.g. elecPt 1D , SET-Lumi 2D
  int DepVarDimension = steer.getInt("DepVarDimension");
  if (DepVarDimension>3) {
    std::cout << " Error:: DepVarDimension maximum to be 3 dimintion, no more, modify me if needed! " << std::endl;
    abort();
  }
  if (DepVarDimension==0) {
    std::cout << " Warning:: DepVarDimension should at least be 1 -- set it to be 1 " << std::endl;
    DepVarDimension = 1;
  }

  // Dependence Variable is of electrons?  
  //  For SET or Lumi these Event based variable, it should be set to false, binning
  //   will be written as "set>0&&set<20" ;
  //  For elecPt these electron based variable, it should be set to true, because the binning should be written as 
  //   "elecPt[0]>0&&elecPt[0]<20".
  bool ElectronDepVar1(false), ElectronDepVar2(false), ElectronDepVar3(false);
  ElectronDepVar1 = steer.getBool("ElectronDepVar");
  // only if DepVarDimension above 1, the following will be read 
  if (DepVarDimension>1) ElectronDepVar2 = steer.getBool("ElectronDepVar2");
  // Tree name
  std::string TreeName = steer.getString("TreeName");
  // histogram names : e.g. hnum hdeno or htrk0, htrk1, htrk2
  std::vector<std::string> HistNames = steer.getStringArray("HistNames");
  // efficiency dependence variable name
  std::string DepVarName1, DepVarName2, DepVarName3;
  DepVarName1 = steer.getString("DepVarName");
  // only if DepVarDimension above 1, the following will be read 
  if (DepVarDimension>1) DepVarName2 = steer.getString("DepVarName2");
  if (DepVarDimension>2) DepVarName3 = steer.getString("DepVarName3");
  // dependence variable bins
  std::vector<double> DepVarBins1, DepVarBins2, DepVarBins3;
  DepVarBins1 = steer.getDoubleArray("DepVarBins");
  // only if DepVarDimension above 1, the following will be read 
  if (DepVarDimension>1) DepVarBins2 = steer.getDoubleArray("DepVarBins2");
  if (DepVarDimension>2) DepVarBins3 = steer.getDoubleArray("DepVarBins3");
  // base selection string to be applied everywhere 
  std::string BaseSelection = steer.getString("BaseSelection");
  // First electron selection array for the corresponding histnames 
  std::vector<std::string> SelectionVecE1 = steer.getStringArray("SelectionVecE1");
  // Second electron selection array for the corresponding histnames 
  std::vector<std::string> SelectionVecE2 = steer.getStringArray("SelectionVecE2");

  // initialize
  // root files
  TFile* finput = new TFile(InRootFile.c_str());
  TFile* foutput = new TFile(OutRootFile.c_str(), "recreate");

  // tree
  TTree* tree = (TTree*)finput->Get(TreeName.c_str());

  // Dep variable binning
  int Nbins1 = DepVarBins1.size()-1;
  int Nbins2(1), Nbins3(1);
  if (DepVarDimension>1) Nbins2 = DepVarBins2.size()-1;
  if (DepVarDimension>2) Nbins3 = DepVarBins3.size()-1;

  double Bins1[ (const int)(Nbins1+1) ];
  double Bins2[ (const int)(Nbins2+1) ];
  double Bins3[ (const int)(Nbins3+1) ];

  for (int i=0; i<(int)DepVarBins1.size(); i++){
    Bins1[i] = DepVarBins1.at(i);
  }
  if (DepVarDimension>1) {
    for (int i=0; i<(int)DepVarBins2.size(); i++){
      Bins2[i] = DepVarBins2.at(i);
    }
  }
  if (DepVarDimension>2) {
    for (int i=0; i<(int)DepVarBins3.size(); i++){
      Bins3[i] = DepVarBins3.at(i);
    }
  }

 
  // dependence histograms
  const int Nhists = HistNames.size();
  std::vector<TH1*> Hists;
  for (int i=0; i<Nhists; i++){
      char hname[100];
      TH1* hist;
      sprintf(hname, "%s", HistNames.at(i).c_str());
      if (DepVarDimension==1) {
        hist = new TH1D(hname, hname, Nbins1, Bins1);
      }
      else if (DepVarDimension==2) {
        hist = new TH2D(hname, hname, Nbins1, Bins1, Nbins2, Bins2);
      }
      else if (DepVarDimension==3) {
        hist = new TH3D(hname, hname, Nbins1, Bins1, Nbins2, Bins2, Nbins3, Bins3);
      }
      else{
        std::cout << "Error:: DepVarDimension can be 1 to 3, no more. Modify me if needed!" << std::endl;
        abort();
      }
      hist->Sumw2();
      Hists.push_back(hist);
  }

  // Draw hists
  for (int i=0; i<Nhists; i++){
    char draw[100], sele[500];
    
    // if variables are of electrons
    char str_elecdep1[5], str_elecdep2[5], str_elecdep3[5];
    sprintf(str_elecdep1, "");
    sprintf(str_elecdep2, "");
    sprintf(str_elecdep3, "");

    if (ElectronDepVar1) sprintf(str_elecdep1, "[0]");
    if (DepVarDimension>1 && ElectronDepVar2) sprintf(str_elecdep2, "[0]");
    if (DepVarDimension>2 && ElectronDepVar3) sprintf(str_elecdep2, "[0]");

    // print draw string
    if (DepVarDimension==1) {
      sprintf(draw, "%s%s>>%s", DepVarName1.c_str(), str_elecdep1, HistNames.at(i).c_str());
    }
    else if (DepVarDimension==2) {
      sprintf(draw, "%s%s:%s%s>>%s", DepVarName2.c_str(), str_elecdep2, DepVarName1.c_str(), str_elecdep1, HistNames.at(i).c_str());
    }
    else if (DepVarDimension==3) {
      sprintf(draw, "%s%s:%s%s:%s%s>>%s", DepVarName3.c_str(), str_elecdep3, DepVarName2.c_str(), str_elecdep2, DepVarName1.c_str(), str_elecdep1, HistNames.at(i).c_str());
    }
    else {
      std::cout << " Error::  DepVarDimension can be 1 to 3, no more. Modify me if needed!" << std::endl;
      abort();
    }

    // print sele string
    sprintf(sele, "(%s)&&(%s)", BaseSelection.c_str(), SelectionVecE1.at(i).c_str());
    std::cout << " -- draw = "  << draw << std::endl;
    std::cout << " -- sele = "  << sele << std::endl;
   
    // draw
    tree->Draw(draw, sele);

    // if electron basis, draw for the 2nd electron
    if (ElectronBasis) {

      // if variables are of electrons
      sprintf(str_elecdep1, "");
      sprintf(str_elecdep2, "");
      sprintf(str_elecdep3, "");
      if (ElectronDepVar1) sprintf(str_elecdep1, "[1]");
      if (DepVarDimension>1 && ElectronDepVar2) sprintf(str_elecdep2, "[1]");
      if (DepVarDimension>2 && ElectronDepVar3) sprintf(str_elecdep2, "[1]");

      // print draw string
      if (DepVarDimension==1) {
        sprintf(draw, "%s%s>>+%s", DepVarName1.c_str(), str_elecdep1, HistNames.at(i).c_str());
      }
      else if (DepVarDimension==2) {
        sprintf(draw, "%s%s:%s%s>>+%s", DepVarName2.c_str(), str_elecdep2, DepVarName1.c_str(), str_elecdep1, HistNames.at(i).c_str());
      }
      else if (DepVarDimension==3) {
        sprintf(draw, "%s%s:%s%s:%s%s>>+%s", DepVarName3.c_str(), str_elecdep3, DepVarName2.c_str(), str_elecdep2, DepVarName1.c_str(), str_elecdep1, HistNames.at(i).c_str());
      }
      else {
        std::cout << " Error::  DepVarDimension can be 1 to 3, no more. Modify me if needed!" << std::endl;
        abort();
      }

      // print sele string
      sprintf(sele, "(%s)&&(%s)", BaseSelection.c_str(), SelectionVecE2.at(i).c_str());    
      std::cout << " -- draw = "  << draw << std::endl;
      std::cout << " -- sele = "  << sele << std::endl;

      // draw
      tree->Draw(draw, sele);    
    }
  }

  foutput->cd();
  for (int i=0; i<Nhists; i++){
    Hists.at(i)->Write();
  }
  foutput->Close();
  return 0;
}
Exemple #23
0
int main(int argc, char** argv) {
    TH1* data;
    std::vector<TH2*> signalIID; // for munub t-processes
    std::vector<TH3*> signalIIID; // for munub t-processes
    TH1* bkginsignal = 0; //for t-processes other than munub
    TH1* bkg = 0; // for non-t processes
    TH1* wtemplate = 0;
    bool do3D = true;
    int nReBin = 10;
    TFile * file = 0;
    std::vector<double> pars;
    double nTop7 = 1.;
    double nW8 = 0;
    double nW7 = 0;
    //    cout << pars[0] << "\t" << pars[1] << "\t" << pars[2] << "\t" << pars[3] << "\t" << endl;
    double delStatF0 = 0;
    double delStatFL = 0;

    double delSystF0 = 0;
    double delSystFL = 0;
    double F0_ = 0;
    double FL_ = 0;
    double delTotF0 = 0;
    double delTotFL = 0;
    string channel = "";
    std::vector<string> namings;
    std::map<string, double> sampleinfo;
    double iRandom = 0;
    string addname = "";
    for (int f = 1; f < argc; f++) {
        std::string arg_fth(*(argv + f));
        cout << f << " ---- " << arg_fth << endl;
        if (arg_fth == "channel") {
            f++;
            std::string out(*(argv + f));
            channel = out; //e-mu
            namings.push_back(string("di") + channel);
            namings.push_back(channel + string("had"));
            namings.push_back(channel + string("tau"));
            namings.push_back("mue");
        } else if (arg_fth == "FL") {
            f++;
            std::string out(*(argv + f));
            FL_ = atof(out.c_str());
        } else if (arg_fth == "F0") {
            f++;
            std::string out(*(argv + f));
            F0_ = atof(out.c_str());
        } else if (arg_fth == "F0Stat") {
            f++;
            std::string out(*(argv + f));
            delStatF0 = atof(out.c_str());
        } else if (arg_fth == "FLStat") {
            f++;
            std::string out(*(argv + f));
            delStatFL = atof(out.c_str());
        } else if (arg_fth == "F0Syst") {
            f++;
            std::string out(*(argv + f));
            delSystF0 = atof(out.c_str());
        } else if (arg_fth == "FLSyst") {
            f++;
            std::string out(*(argv + f));
            delSystFL = atof(out.c_str());
        } else if (arg_fth == "F0Tot") {
            f++;
            std::string out(*(argv + f));
            delTotF0 = atof(out.c_str());
        } else if (arg_fth == "FLTot") {
            f++;
            std::string out(*(argv + f));
            delTotFL = atof(out.c_str());
        } else if (arg_fth == "nW7") {
            f++;
            std::string out(*(argv + f));
            nW7 = atof(out.c_str());
        } else if (arg_fth == "ntop7") {
            f++;
            std::string out(*(argv + f));
            nTop7 = atof(out.c_str());
        } else if (arg_fth == "signal") {
            f++;
            std::string out(*(argv + f));
            file = new TFile(out.c_str(), "read");
            bool muonfile = false;
            for (unsigned int i = 0; i < namings.size(); i++) {
                int pos = string(file->GetName()).find(namings[i].c_str());
                muonfile = (pos >= 0 && pos < string(file->GetName()).size());
                if (muonfile) {
                    if (iRandom == 0) {
                        cout << "I am in " << channel << " channel and I accept ";
                        cout << file->GetName() << " as signal" << endl;
                    }
                    break;
                }
            }

            if (!do3D || (do3D && !muonfile)) {
                signalIID.push_back(((TH2*) file->Get("Default_allW/Default_allWcosTheta2D"))->RebinY(nReBin));
                //                signalIID.at(signalIID.size() - 1)->Scale(ratio);
                //                cout << signalIID.at(signalIID.size() - 1)->GetName() << endl;
            }//                else
            //                signalIID.push_back(((TH2*) ((TH3D*) file->Get("Default_allW/Default_allWcosTheta3D"))->Project3D("yx"))->Rebin2D(1,1));
            if (do3D && muonfile) {
                //                cout << " in 3D :-)" << endl;
                signalIIID.push_back(((TH3D*) file->Get("Default_allW/Default_allWcosTheta3D"))->Rebin3D(1, nReBin, 1, "newname"));
                //                cout << signalIIID.at(signalIIID.size() - 1) << endl;
                //                signalIIID.at(signalIIID.size() - 1)->Scale(ratio);
            }
            if (bkginsignal == 0)
                bkginsignal = (((TH1*) file->Get("Default_allW/Default_allWcosTheta"))->Rebin(nReBin));
            else
                bkginsignal->Add(((TH1*) file->Get("Default_allW/Default_allWcosTheta"))->Rebin(nReBin));

            TH1 * myTemp = (TH1*) (((TH1*) file->Get("Default_allW/Default_allWcosTheta")))->Clone("myTemp");
            if (iRandom == 0) {
                if (!muonfile) {
                    cout << " : " << signalIID.at(signalIID.size() - 1)->Integral() << " + " << myTemp->Integral()
                            << " = " << signalIID.at(signalIID.size() - 1)->Integral() + myTemp->Integral() << endl;
                    sampleinfo[out] = signalIID.at(signalIID.size() - 1)->Integral() + myTemp->Integral();
                } else if (do3D) {
                    cout << " : " << signalIIID.at(signalIIID.size() - 1)->Integral() << " + " << myTemp->Integral()
                            << " = " << signalIIID.at(signalIIID.size() - 1)->Integral() + myTemp->Integral() << endl;
                    sampleinfo[out] = signalIIID.at(signalIIID.size() - 1)->Integral() + myTemp->Integral();
                }
            }
            delete myTemp;

        } else if (arg_fth == "data") {
            f++;
            std::string out(*(argv + f));
            cout << "data" << endl;
            file = new TFile(out.c_str(), "read");
            data = ((TH1*) file->Get("Default_allW/Default_allWcosTheta"))->Rebin(nReBin);
            cout << data << endl;
        } else if (arg_fth == "bkg") {
            f++;
            std::string out(*(argv + f));
            cout << "bkg" << endl;
            file = new TFile(out.c_str(), "read");
            if (bkg == NULL) {
                cout << "here .." << endl;
                bkg = ((TH1*) file->Get("Default_allW/Default_allWcosTheta"))->Rebin(nReBin);
            } else {
                bkg->Add(((TH1*) file->Get("Default_allW/Default_allWcosTheta"))->Rebin(nReBin));
            }
        } else if (arg_fth == "wtemplate") {
            f++;
            std::string out(*(argv + f));
            cout << "w template" << endl;
            file = new TFile(out.c_str(), "read");
            cout << out << "\t";
            wtemplate = ((TH1*) file->Get("Default_allW/Default_allWcosTheta"));
            cout << wtemplate << endl;
            wtemplate->Rebin(nReBin);
        } else if (arg_fth == "name") {
            f++;
            std::string out(*(argv + f));
            addname = out;
        }
    }
    cout << bkg << "\t" << data << "\t" << wtemplate << endl;
    wtemplate->Sumw2();
    wtemplate->Scale((double) 1. / (double) wtemplate->Integral());
    data->Print();

    cout << "In Bias fit: \n\tsize of 2D signal is " << signalIID.size() <<
            "\n\tsize of 3D signal is " << signalIIID.size() << endl;
    cout << "bkginsignal: " << bkginsignal->Integral() << " bkg: " << bkg->Integral() << endl;
    if (bkg != NULL && bkginsignal != NULL) {
        bkg->Add(bkginsignal);
    } else if (bkg == NULL && bkginsignal != NULL) {
        bkg = (TH1*) bkginsignal->Clone("myBkg");
    }
    //        bkg->Scale(ratio);
    cout << "bkg: " << bkg->Integral() << " data: " << data->Integral() << " signal: ";
    double nSignal = 0;
    for (unsigned int p = 0; p < signalIID.size(); p++) {
        nSignal += signalIID[p]->Integral();
        //            cout << signalIID[p]->Integral() << endl;
    }
    for (unsigned int p = 0; p < signalIIID.size(); p++) {
        nSignal += signalIIID[p]->Integral();
        //            cout << signalIIID[p]->Integral() << endl;
    }
    cout << nSignal << endl;
    WTempForCombination3D my3DInput;
    my3DInput.Wtemplate = (TH1*) wtemplate->Clone("Wtemp_Syst"); //normal
    my3DInput.rest.data = data;
    my3DInput.rest.nonRWs = bkg;
    my3DInput.rest.signalIID = signalIID;
    my3DInput.rest.signalIIID = signalIIID;


    pars.push_back(F0_);
    pars.push_back(FL_);
    pars.push_back(nTop7);
    pars.push_back(nW7);

    ChiSquaredCaculatorAndPlotter myChi2Syst(channel + string("_Chi2Syst_") + addname, pars, my3DInput, delSystF0, delSystFL);
    myChi2Syst.PrintOut();
    cout << "ChiSquared: " << myChi2Syst.GetChiSquared() << endl;
    cout << "NormalChiSquared: " << myChi2Syst.GetNormalizedChiSquared() << endl;
    myChi2Syst.WriteInfo();

    my3DInput.Wtemplate = (TH1*) wtemplate->Clone("Wtemp_Stat"); //normal
    ChiSquaredCaculatorAndPlotter myChi2Stat(channel + string("_Chi2Stat_") + addname, pars, my3DInput, delStatF0, delStatFL);
    myChi2Stat.PrintOut();
    cout << "ChiSquared: " << myChi2Stat.GetChiSquared() << endl;
    cout << "NormalChiSquared: " << myChi2Stat.GetNormalizedChiSquared() << endl;
    myChi2Stat.WriteInfo();

    my3DInput.Wtemplate = (TH1*) wtemplate->Clone("Wtemp_total"); //normal
    ChiSquaredCaculatorAndPlotter myChi2total(channel + string("_Chi2total_") + addname, pars, my3DInput, delTotF0, delTotFL);
    myChi2total.PrintOut();
    cout << "ChiSquared: " << myChi2total.GetChiSquared() << endl;
    cout << "NormalChiSquared: " << myChi2total.GetNormalizedChiSquared() << endl;
    myChi2total.WriteInfo();



    return 0;
}
Exemple #24
0
//void makeHist(const int sample, const int dataset=1)
void makeHist(const string title="")
{
	vector<Hist> hist2print;
	TPaveText *tx = new TPaveText(.05,.1,.95,.8);
//	tx->AddText("Using Deafult JERs for all jets");
//	tx->AddText("Using b-Jet JERs");

/*	string title("QCD MG:");

	//if (sample==1) title += "NJet(70/50/30>=2/4/5), #slash{E}_{T}>175, Triplet>1, 80<TopMass<270, TOP+0.5*BJET>500, MT2>300, #Delta#Phi(.5,.5,.3), BJets>=1";
	if (sample==1)      title += "All Stop cuts applied (use default JERs for all jets)";
	else if (sample==2) title += "All Stop cuts applied + Inverted #Delta#Phi (use default JERs for all jets)";
	else if (sample==3) title += "All Stop cuts applied (use b-Jet JERs)";
	else if (sample==4) title += "All Stop cuts applied + Inverted #Delta#Phi (use b-Jet JERs)";
	else if (sample==5) title += "No cuts applied";
*/
	unsigned bitMaskArray[] = {0,1,2,3,129,130,131,195,257,258,269,323};
	vector<unsigned> vBitMaskArray(bitMaskArray, bitMaskArray + sizeof(bitMaskArray) / sizeof(unsigned));



	stringstream unclmet_title;
	unclmet_title << title << "Unclutered MET";
	hist2print.push_back(Hist("met",title,2,0.0, 400.0,1));
	hist2print.push_back(Hist("unclmet",unclmet_title.str().c_str(),2,0.0, 100.0,1));
	hist2print.push_back(Hist("mht",title,2,0.0, 400.0,1));
	hist2print.push_back(Hist("ht",title,2,0,2000,1));
	hist2print.push_back(Hist("njet30eta5p0",title,1,0,15,1));
	hist2print.push_back(Hist("nbjets",title,1,0,10,1));
//	hist2print.push_back(Hist("bjetPt",title,2));
	hist2print.push_back(Hist("M123",title,2));
//	hist2print.push_back(Hist("M23overM123",title));
	hist2print.push_back(Hist("MT2",title,2));
	hist2print.push_back(Hist("MTb",title,4));
	hist2print.push_back(Hist("MTt",title,4));
	hist2print.push_back(Hist("MTb_p_MTt",title,2,400,1000,1));
	//hist2print.push_back(Hist("jet1_pt",title,2));
	//hist2print.push_back("bjetPt");
//	hist2print.push_back(Hist("bjetMass",title,2,0,200));
//	hist2print.push_back(Hist("dphimin",title,4));


	TFile *outRootFile = new TFile("Merged.root");

	/*TPad *c1=0, *c2=0;
	TCanvas *c = GetCanvas(c1, c2);
	if (c ==NULL|| c1 == 0 ||c2 == 0)
	{
		cout << " A drawing pad is null !"<< endl;
		cout << "c = " << c << endl;
		cout << "c1 = " << c1 << endl;
		cout << "c2 = " << c2 << endl;
		assert(false);
	}*/
   TCanvas *c = new TCanvas("c1");
   c->Range(0,0,1,1);
   c->SetBorderSize(2);
   c->SetFrameFillColor(0);
  
// ------------>Primitives in pad: c1_1
   TPad *c1_1 = new TPad("c1_1", "c1_1",0.01,0.30,0.99,0.99);
   c1_1->Draw();
   c1_1->cd();
   c1_1->SetBorderSize(2);
   c1_1->SetTickx(1);
   c1_1->SetTicky(1);
   c1_1->SetTopMargin(0.1);
   c1_1->SetBottomMargin(0.0);
   //c1_1->SetFrameFillColor(3);
	//c1_1->SetLogy();
  
  c->cd();
// ------------>Primitives in pad: c1_2
   TPad *c1_2 = new TPad("c1_2", "c1_2",0.01,0.01,0.99,0.30);
   c1_2->Draw();
   c1_2->cd();
   c1_2->SetBorderSize(2);
   c1_2->SetTickx(1);
   c1_2->SetTicky(1);
   c1_2->SetTopMargin(0.0);
   c1_2->SetBottomMargin(0.24);
   c1_2->SetFrameFillColor(0);
	c1_2->SetGridx();
	c1_2->SetGridy();
	c->cd();
	gStyle->SetOptStat(0);
	gPad->Print("samples.eps[");

	for (unsigned i=0;i<vBitMaskArray.size(); ++i)
	{
		unsigned mask = vBitMaskArray.at(i);
		for (unsigned ihist=0; ihist < hist2print.size(); ++ihist)
		{
			stringstream path, reco_hist_name, gen_hist_name, smear_hist_name;
			stringstream reco_hist, gen_hist, smear_hist;
			stringstream folder;
			folder << "Hist/Mask"<< mask << "HT0to8000MHT0to8000/";
			//cout << "folder = " << folder.str() << endl;

			/*	if ((hist2print.at(ihist).Name()).find("Jet"))
				{
				reco_hist_name << folder.str() << "reco" << hist2print.at(ihist).Name() << "_copy";
				reco_hist << folder.str() << "reco" << hist2print.at(ihist).Name();
				smear_hist_name << folder.str() << "smeared" << hist2print.at(ihist).Name() << "_copy";
				smear_hist << folder.str() << "smeared" << hist2print.at(ihist).Name();
				gen_hist_name << folder.str() << "gen" << hist2print.at(ihist).Name() << "_copy";
				gen_hist << folder.str() << "gen" << hist2print.at(ihist).Name();
				} else
				*/	{
					reco_hist_name << folder.str() << "reco_" << hist2print.at(ihist).Name() << "_copy";
					reco_hist << folder.str() << "reco_" << hist2print.at(ihist).Name();
					smear_hist_name << folder.str() << "smeared_" << hist2print.at(ihist).Name() << "_copy";
					smear_hist << folder.str() << "smeared_" << hist2print.at(ihist).Name();
					gen_hist_name << folder.str() << "gen_" << hist2print.at(ihist).Name() << "_copy";
					gen_hist << folder.str() << "gen_" << hist2print.at(ihist).Name();
				}

				TH1* hreco = (TH1*) (outRootFile->Get(reco_hist.str().c_str()));
				if (hreco == NULL) { cout << "hreco = " << reco_hist.str() << " was not found!" << endl; assert(false); } 
				hreco->SetDirectory(0);
				TH1* hsmear = (TH1*) (outRootFile->Get(smear_hist.str().c_str()));
				if (hsmear == NULL) { cout << "hsmear = " << smear_hist.str() << " was not found!" << endl; assert(false); } 
				hsmear->SetDirectory(0);
				TH1* hgen = (TH1*) (outRootFile->Get(gen_hist.str().c_str()));
				//->Clone(gen_hist_name.str().c_str()));
				if (hgen == NULL) { cout << "hgen = " << gen_hist.str() << " was not found!" << endl; assert(false); } 
				hgen->SetDirectory(0);

				hreco->Sumw2();
				hsmear->Sumw2();
				hgen->Sumw2();

				const int rebin = hist2print.at(ihist).Rebin();
				const string title = hist2print.at(ihist).Title();
				const double xmin = hist2print.at(ihist).Xmin();
				const double xmax = hist2print.at(ihist).Xmax();

				if (rebin>1)
				{
					hreco->Rebin(rebin);
					hsmear->Rebin(rebin);
					hgen->Rebin(rebin);
				}
				if (title.length()>0)
				{
					hreco->SetTitle(title.c_str());
					hsmear->SetTitle(title.c_str());
					hgen->SetTitle(title.c_str());
				}
				if (xmin != LargeNegNum || xmax != LargeNegNum)
				{
					hreco->GetXaxis()->SetRangeUser(xmin,xmax);
					hsmear->GetXaxis()->SetRangeUser(xmin,xmax);
					hgen->GetXaxis()->SetRangeUser(xmin,xmax);
				}

				const double reco_max_y  = hreco->GetBinContent(hreco->GetMaximumBin());
				const double smear_max_y = hsmear->GetBinContent(hsmear->GetMaximumBin());
				const double y_max = max(reco_max_y, smear_max_y);
				double y_min = 9999.0;
				for (unsigned bin=1; bin<hreco->GetNbinsX(); ++bin)
				{
					const double v1 = hreco->GetBinContent(bin);
					const double v2 = hsmear->GetBinContent(bin);
					const double minv = min(v1,v2);
					if (minv != 0 && minv < y_min) y_min = minv;
					
				}

				cout << hreco->GetName() << "->ymin/max = " << y_min << "(" << y_min/2.0 << ")/" << y_max << "(" << y_max*2.0 << ")" << endl;
				hreco->GetYaxis()->SetRangeUser(y_min/2.0, y_max*2.0);
				hsmear->GetYaxis()->SetRangeUser(y_min/2.0, y_max*2.0);


				hgen->SetLineColor(kBlue);
				hgen->SetMarkerColor(kBlue);
				hgen->SetMarkerStyle(24);
				hgen->SetLineWidth(2);
				hsmear->SetLineColor(kRed);
				hsmear->SetMarkerColor(kRed);
				hsmear->SetMarkerStyle(24);
				hsmear->SetLineWidth(2);
				hreco->SetLineWidth(2);
				hreco->SetMarkerStyle(kDot);
				hreco->SetLineColor(kBlack);
				hreco->SetMarkerColor(kBlack);
				//hreco->GetXaxis()->SetRangeUser(0,300);
				//hsmear->GetXaxis()->SetRangeUser(0,300);


				hreco->GetYaxis()->CenterTitle(1);
				hreco->SetLabelFont(42,"XYZ");
				hreco->SetTitleFont(42,"XYZ");
				hreco->GetYaxis()->SetTitleOffset(0.8);
				hreco->SetLabelSize(0.05,"XYZ");
				hreco->SetTitleSize(0.06,"XYZ");


				TH1 *hsmeartoreco_ratio = (TH1*) (hsmear->Clone("hsmear_copy"));
				hsmeartoreco_ratio->Divide(hreco);
				hsmeartoreco_ratio->SetTitle("");
				hsmeartoreco_ratio->GetYaxis()->SetTitle("Smear/Reco");
				hsmeartoreco_ratio->GetYaxis()->SetRangeUser(0,2.);

				hsmeartoreco_ratio->GetYaxis()->SetTitleOffset(0.4);
				hsmeartoreco_ratio->GetXaxis()->SetTitleOffset(0.9);
				hsmeartoreco_ratio->GetYaxis()->CenterTitle(1);
				hsmeartoreco_ratio->GetXaxis()->CenterTitle(1);
				hsmeartoreco_ratio->SetLabelSize(0.125,"XYZ");
				hsmeartoreco_ratio->SetTitleSize(0.125,"XYZ");
				//	hsmeartoreco_ratio->SetLabelFont(labelfont,"XYZ");
				//	hsmeartoreco_ratio->SetTitleFont(titlefont,"XYZ");
				hsmeartoreco_ratio->GetXaxis()->SetTickLength(0.07);



				stringstream recoleg,smearleg, genleg;
				const double sum_reco  = hreco->Integral(1, hreco->GetNbinsX()+1);
				const double sum_smear = hsmear->Integral(1, hsmear->GetNbinsX()+1);
				const double sum_gen   = hgen->Integral(1, hgen->GetNbinsX()+1);
				const double err_reco  = StatErr(hreco);
				const double err_smear = StatErr(hsmear);


				cout << setprecision(1) << fixed;

				recoleg << "Reco (" << sum_reco << "#pm" << err_reco << ")";
				smearleg << "Smear (" << sum_smear << "#pm" << err_smear << ")";
				genleg << "Gen (" << sum_gen << ")";
				cout <<  smear_hist_name.str() << "::reco/smear = " << sum_reco << "/" << sum_smear << endl;

				TLegend *l2 = new TLegend(0.6,0.6,0.9,0.9);
				l2->AddEntry(hreco, recoleg.str().c_str());
				//l2->AddEntry(hgen, genleg.str().c_str());
				l2->AddEntry(hsmear, smearleg.str().c_str());

				c1_1->cd();
				gPad->SetLogy(hist2print.at(ihist).LogY());

				hreco->DrawCopy();
				//hgen->DrawCopy("same");
				hsmear->DrawCopy("same");
				l2->Draw();
				//tx->Draw();
				c1_2->cd();
				hsmeartoreco_ratio->DrawCopy();
				c->cd();
				gPad->Print("samples.eps");

		}
	}

	gPad->Print("samples.eps]");
}
void MakeIndividualPDFhists(const std::string name)
{
	const int nfiles = 6;
	
	TFile* f[nfiles];
	f[0] = new TFile("~/RESULTS/10222009_PDFsystFullMCDataset/10272009_Result3/PDFsyst1.root");
	f[1] = new TFile("~/RESULTS/10222009_PDFsystFullMCDataset/10272009_Result3/PDFsyst2.root");
	f[2] = new TFile("~/RESULTS/10222009_PDFsystFullMCDataset/10272009_Result3/PDFsyst3.root");
	f[3] = new TFile("~/RESULTS/10222009_PDFsystFullMCDataset/10272009_Result3/PDFsyst4.root");
	f[4] = new TFile("~/RESULTS/10222009_PDFsystFullMCDataset/10272009_Result3/PDFsyst5.root");
	f[5] = new TFile("~/RESULTS/10222009_PDFsystFullMCDataset/10272009_Result3/PDFsyst6.root");


	assert (f[0] !=NULL && "FILE 1 NOT FOUND!");
	assert (f[1] !=NULL && "FILE 2 NOT FOUND!");
	assert (f[2] !=NULL && "FILE 3 NOT FOUND!");
	assert (f[3] !=NULL && "FILE 4 NOT FOUND!");
	assert (f[4] !=NULL && "FILE 5 NOT FOUND!");
	assert (f[5] !=NULL && "FILE 6 NOT FOUND!");

	TH1* h[41];
	
	float xmin = 0;
	float xpoint1 = 200;
	float xpoint2 = 250;
	float xpoint3 = 300;
	float xpoint4 = 650;
	float width1 = 10;
	float width2 = 10;
	float width3 = 50;
	float width4 = 250;
	
	//0th hist is the reference. other 40 are the variants.
	for (int i=0; i < 41; ++i)
	{
		std::stringstream hist;
		hist << "Ana/PhoJetsTemp/Hist/1Jet/PDFSyst/PDFSystPara"<< i << "_" << name;
		std::cout << "looking for hist " << hist.str() << std::endl;
		h[i] = dynamic_cast<TH1*> (f[0]->Get(hist.str().c_str()));
		assert (h[i] != NULL && "hist is null");
		//Sumw2() for these hists are called at creation
		
		//add the other 2 jobs resutls
		for (int nf=1;nf< nfiles;++nf)
		{
			TH1* temp = dynamic_cast<TH1*> (f[nf]->Get(hist.str().c_str()));
			assert (temp != NULL && "hist is null");
			h[i]->Add(temp);
		}
		

		h[i] = (TH1F*) MakeVariableBins (h[i], xmin, xpoint1, xpoint2, xpoint3, xpoint4, width1, width2, width3, width4, false);
		if (i>0)
		{
			h[i]->Scale(h[0]->Integral()/(1. * h[i]->Integral()));
			h[i]->Divide(h[0]);
			int marker = 22, color=2;
			if (i%2)
			{
				marker = 23;
				color = 4;
			}
				
			h[i]->SetMarkerColor(color);
			h[i]->SetLineColor(color);
			h[i]->SetMarkerStyle(marker);
			h[i]->SetMarkerSize(1);
		}
	}


			gStyle->SetOptStat(0);
		new TCanvas();
		gPad->SetGridx();
		gPad->SetGridy();
		gPad->SetTickx();
		gPad->SetTicky();



	//make a plot for each PDF parameter wrt to reference
	for (int ipdf = 1; ipdf <41; ipdf=ipdf+2)
	{
		//h[ipdf]->Scale(h[0]->Integral()/(1. * h[ipdf]->Integral()));
		//h[ipdf+1]->Scale(h[0]->Integral()/(1. * h[ipdf+1]->Integral()));
		std::string xtitle, ytitle;
		if (name == "PhoEt") xtitle = "E_{T}^{#gamma}";
		ytitle = "Ratio wrt base (Parameter 0)";
		
		std::stringstream title, le1,le2, file;
		int jpdf = ipdf+1;
		title << "PDF parameter " << ipdf << " & "<< jpdf << "(normalized to base and ratio wrt to base)"
				<< ";" << xtitle << ";" << ytitle;
		le1 << "Parameter " << ipdf;
		le2 << "Parameter " << jpdf;
		file << "PDFpara_"<< ipdf << "_" << jpdf << ".eps";

		
		//h[ipdf]->SetMinimum(0.9);
		//h[ipdf]->SetMaximum(1.1);
		//h[ipdf]->SetTitle(title.str().c_str());
		h[ipdf]->GetXaxis()->CenterTitle(1);
		h[ipdf]->GetYaxis()->CenterTitle(1);

		if (ipdf==1) 
		{
			h[ipdf]->Draw();
			h[ipdf+1]->Draw("SAME");
		} else 
		{
			h[ipdf]->Draw("SAME");
			h[ipdf+1]->Draw("SAME");
		}

		TLegend *leg = new TLegend (0.7,0.8,0.9,0.9);
		leg->SetTextFont(42);
		leg->SetTextSize(0.03);


		leg->AddEntry(h[ipdf],le1.str().c_str());
		leg->AddEntry(h[ipdf+1],le2.str().c_str());
		//leg->Draw();
		//gPad->Print(file.str().c_str());
		
	}



	return;

	
	for (int i=1; i < 40; ++i)
	{
		if (i==1)
		{
			h[i]->Draw("P");
			h[i]->SetTitle("PDF: 40 variants wrt to CTEQ6;E_{T}^{#gamma};Ratio");
			//h[i]->SetTitle("PDF: 40 variants wrt to CTEQ6;E_{T}^{jet};Ratio");
		}
		else h[i]->Draw("P same");
	}

	//no make a plot with max/min values
	//exclude the 0th hist which is the reference
	
	for (int bin=0; bin<= h[1]->GetNbinsX(); ++bin)
	{
		if (h[1]->GetBinContent(bin))
		{
			float max=1,min=1;
			float maxer=0,miner=0;
			for (int nh=2; nh<41; ++nh)
			{
				if (h[nh]->GetBinContent(bin) > max )
				{
					max = h[nh]->GetBinContent(bin);
					maxer = h[nh]->GetBinError(bin);
				}
				if (h[nh]->GetBinContent(bin) < min )
				{
					min = h[nh]->GetBinContent(bin);
					miner = h[nh]->GetBinError(bin);
				}
			}
			
			h[1]->SetBinContent(bin,max);
			h[1]->SetBinError(bin,maxer);
			h[2]->SetBinContent(bin,min);
			h[2]->SetBinError(bin,miner);
		}

	}

	new TCanvas();
	gPad->SetGridx();
	gPad->SetGridy();
	gPad->SetTickx(2);
	gPad->SetTicky(2);
	h[1]->SetTitle("Max/Min of 40 PDF variants");
	h[1]->Draw("PE1");
	h[2]->Draw("SAME PE1");
	
	

return;

	TH1* ph = dynamic_cast<TH1*> (f[0]->Get("Ana/PhoJetsTemp/Hist/1Jet/Photon/EtCorr"));
	assert (ph != NULL && " photon hist is null");
	for (int nf=1;nf< nfiles;++nf)
	{
		TH1* temp = dynamic_cast<TH1*> (f[nf]->Get("Ana/PhoJetsTemp/Hist/1Jet/Photon/EtCorr"));
		assert (temp != NULL && "photon jobs hist is null");
		temp->Sumw2();
		ph->Add(temp);
	}

	ph = (TH1F*) MakeVariableBins (ph, xmin, xpoint1, xpoint2, xpoint3, xpoint4, width1, width2, width3, width4, false);

	new TCanvas();
	ph->Draw();
	return;
	
	TH1* final = dynamic_cast<TH1*> (ph->Clone("copy"));
	assert (final != NULL && " photon hist is null");
	for (int bin =0; bin <= ph->GetNbinsX()+1; ++bin)
	{
		final->SetBinError(bin,0);
		final->SetBinContent(bin,0);
void EMCDistribution_SUM_RawADC(TString sTOWER = "Energy_Sum_col1_row2_5x5",
                                TString CherenkovSignal = "C2_Inner")
{
  TH1 *EnergySum_LG_full = new TH1F("EnergySum_LG_full",
                                    ";Tower Energy Sum (ADC);Count / bin", 260, -100, 2500);
  TH1 *EnergySum_LG = new TH1F("EnergySum_LG",
                               ";Tower Energy Sum (ADC);Count / bin", 260, -100, 2500);
  //  TH1 * EnergySum_HG = new TH1F("EnergySum_HG",
  //      ";Low range Tower Energy Sum (ADC);Count / bin", 50, 0, 500);

  TH1 *C2_Inner_full = new TH1F("C2_Inner_full",
                                CherenkovSignal + ";Cherenkov Signal (ADC);Count / bin", 1000, 0, 2000);
  TH1 *C2_Inner = new TH1F("C2_Inner",
                           CherenkovSignal + ";Cherenkov Inner Signal (ADC);Count / bin", 1000, 0, 2000);

  EnergySum_LG_full->SetLineColor(kBlue + 3);
  EnergySum_LG_full->SetLineWidth(2);

  EnergySum_LG->SetLineColor(kGreen + 3);
  EnergySum_LG->SetLineWidth(3);
  EnergySum_LG->SetMarkerColor(kGreen + 3);

  C2_Inner_full->SetLineColor(kBlue + 3);
  C2_Inner_full->SetLineWidth(2);

  C2_Inner->SetLineColor(kGreen + 3);
  C2_Inner->SetLineWidth(3);
  C2_Inner->SetMarkerColor(kGreen + 3);

  TCut c2 = CherenkovSignal + ">240";

  T->Draw(sTOWER + ">>EnergySum_LG_full", "", "goff");
  T->Draw(sTOWER + ">>EnergySum_LG", c2, "goff");
  T->Draw(CherenkovSignal + ">>C2_Inner_full", "", "goff");
  T->Draw(CherenkovSignal + ">>C2_Inner", c2, "goff");

  TText *t;
  TCanvas *c1 = new TCanvas(
      "EMCDistribution_SUM_RawADC_" + sTOWER + "_" + CherenkovSignal + cuts,
      "EMCDistribution_SUM_RawADC_" + sTOWER + "_" + CherenkovSignal + cuts, 1800,
      600);
  c1->Divide(3, 1);
  int idx = 1;
  TPad *p;

  p = (TPad *) c1->cd(idx++);
  c1->Update();
  p->SetLogy();
  p->SetGridx(0);
  p->SetGridy(0);

  C2_Inner_full->DrawClone();
  C2_Inner->DrawClone("same");

  p = (TPad *) c1->cd(idx++);
  c1->Update();
  p->SetLogy();
  p->SetGridx(0);
  p->SetGridy(0);

  TH1 *h = (TH1 *) EnergySum_LG_full->DrawClone();
  //  h->GetXaxis()->SetRangeUser(0, h->GetMean() + 5 * h->GetRMS());
  (TH1 *) EnergySum_LG->DrawClone("same");

  p = (TPad *) c1->cd(idx++);
  c1->Update();
  //  p->SetLogy();
  p->SetGridx(0);
  p->SetGridy(0);

  TH1 *h_full = (TH1 *) EnergySum_LG_full->DrawClone();
  TH1 *h = (TH1 *) EnergySum_LG->DrawClone("same");

  TF1 *fgaus_g = new TF1("fgaus_LG_g", "gaus", h->GetMean() - 1 * h->GetRMS(),
                         h->GetMean() + 4 * h->GetRMS());
  fgaus_g->SetParameters(1, h->GetMean() - 2 * h->GetRMS(),
                         h->GetMean() + 2 * h->GetRMS());
  h->Fit(fgaus_g, "MR0N");

  TF1 *fgaus = new TF1("fgaus_LG", "gaus",
                       fgaus_g->GetParameter(1) - 1 * fgaus_g->GetParameter(2),
                       fgaus_g->GetParameter(1) + 4 * fgaus_g->GetParameter(2));
  fgaus->SetParameters(fgaus_g->GetParameter(0), fgaus_g->GetParameter(1),
                       fgaus_g->GetParameter(2));
  h->Fit(fgaus, "MR");

  h->Sumw2();
  h_full->Sumw2();
  h_full->GetXaxis()->SetRangeUser(h->GetMean() - 4 * h->GetRMS(),
                                   h->GetMean() + 4 * h->GetRMS());

  h->SetLineWidth(2);
  h->SetMarkerStyle(kFullCircle);

  h_full->SetTitle(
      Form("#DeltaE/<E> = %.1f%%",
           100 * fgaus->GetParameter(2) / fgaus->GetParameter(1)));

  //  p = (TPad *) c1->cd(idx++);
  //  c1->Update();
  //  p->SetLogy();
  //  p->SetGridx(0);
  //  p->SetGridy(0);
  //
  //  TH1 * h = (TH1 *) EnergySum_LG->DrawClone();
  //  h->GetXaxis()->SetRangeUser(0,500);
  //  h->SetLineWidth(2);
  //  h->SetLineColor(kBlue + 3);
  ////  h->Sumw2();
  //  h->GetXaxis()->SetRangeUser(0, h->GetMean() + 5 * h->GetRMS());
  //
  //  p = (TPad *) c1->cd(idx++);
  //  c1->Update();
  ////  p->SetLogy();
  //  p->SetGridx(0);
  //  p->SetGridy(0);
  //
  //  TH1 * h = (TH1 *) EnergySum_LG->DrawClone();
  //  h->GetXaxis()->SetRangeUser(0,500);
  //
  //  TF1 * fgaus = new TF1("fgaus_HG", "gaus", 0, 100);
  //  fgaus->SetParameters(1, h->GetMean() - 2 * h->GetRMS(),
  //      h->GetMean() + 2 * h->GetRMS());
  //  h->Fit(fgaus, "M");
  //
  //  h->Sumw2();
  //  h->GetXaxis()->SetRangeUser(h->GetMean() - 4 * h->GetRMS(),
  //      h->GetMean() + 4 * h->GetRMS());
  //
  //  h->SetLineWidth(2);
  //  h->SetMarkerStyle(kFullCircle);
  //
  //  h->SetTitle(
  //      Form("#DeltaE/<E> = %.1f%%",
  //          100 * fgaus->GetParameter(2) / fgaus->GetParameter(1)));

  SaveCanvas(c1,
             TString(_file0->GetName()) + TString("_DrawPrototype3EMCalTower_") + TString(c1->GetName()), false);
}
  int main(int argc, char *argv[]){
    /////////////////////////////////////
    if (argc != 6)
    {
      std::cout << "Please enter something like: ./run \"filelist_WJets_PU20bx25_100_200.txt\" \"WJets_PU20bx25_100_200\" \"Results\" \"00\" \"0\" " << std::endl;
      return EXIT_FAILURE;
    }
    //get the inputs from user
    const string InRootList = argv[1];
    const string subSampleKey = argv[2];
    const string Outdir = argv[3];
    const string inputnumber = argv[4];
    const string verbosity = argv[5];
    //////////////////////////////////////
    int verbose = atoi(verbosity.c_str());

     //some varaibles
    char filenames[500];
    vector<string> filesVec;
    ifstream fin(InRootList.c_str());
    TChain *sample_AUX = new TChain("TreeMaker2/PreSelection");
    char tempname[200];
    char histname[200];
    const double deltaRMax = 0.1;
    const double deltaPtMax = 0.2;

    map<string,int> binMap = utils2::BinMap_NoB();
    int totNbins=binMap.size();
    map<string,int> binMap_mht_nj = utils2::BinMap_mht_nj();
    int totNbins_mht_nj=binMap_mht_nj.size();
    TH1* hAccAll = new TH1D("hAccAll","Acceptance -- All",totNbins_mht_nj,1,totNbins_mht_nj+1);
    TH1* hIsoRecoAll = new TH1D("hIsoRecoAll","Efficiency -- All",totNbins,1,totNbins+1);
    TH1* hAccPass = new TH1D("hAccPass","Acceptance -- Pass",totNbins_mht_nj,1,totNbins_mht_nj+1);
    TH1* hIsoRecoPass = new TH1D("hIsoRecoPass","Efficiency -- Pass",totNbins,1,totNbins+1);
    hAccAll->Sumw2();
    hIsoRecoAll->Sumw2();
    hAccPass->Sumw2();
    hIsoRecoPass->Sumw2();

    int TauResponse_nBins=4;
    vector<TH1*> vec_resp;
        TFile * resp_file = new TFile("TauHad/HadTau_TauResponseTemplates_TTbar_Elog195WithDirectionalTemplates.root","R");
    for(int i=0; i<TauResponse_nBins; i++){
      sprintf(histname,"hTauResp_%d",i);
      vec_resp.push_back( (TH1D*) resp_file->Get( histname )->Clone() );
    }

    ///read the file names from the .txt files and load them to a vector.
    while(fin.getline(filenames, 500) ){filesVec.push_back(filenames);}
    cout<< "\nProcessing " << subSampleKey << " ... " << endl;
    for(unsigned int in=0; in<filesVec.size(); in++){ sample_AUX->Add(filesVec.at(in).c_str()); }


    // --- Analyse the events --------------------------------------------
    Selection * sel = new Selection();
    Utils * utils = new Utils();

    // Interface to the event content
    Events * evt = new Events(sample_AUX, subSampleKey,verbose);

    // Loop over the events (tree entries)
    int eventN=0;
    while( evt->loadNext() ){
//      if(eventN>10000)break;
      eventN++;

      // Through out an event that contains HTjets with bad id
      if(evt->JetId()==0)continue;

//printf("\n@@@@@@@@@@@@@@@@@@@@@@@@@@  \n event: %d \n Njet: %d HT: %g MHT: %g dphi1: %g dphi2: %g dphi3: %g  \n ",eventN-1,evt->nJets(),evt->ht(),evt->mht(),evt->deltaPhi1(),evt->deltaPhi2(),evt->deltaPhi3()); //Ahmad3

      // Apply the NJets baseline-cut
      if( !sel->Njet_4(evt->nJets()) ) continue;
      // Apply the HT and MHT baseline-cuts
      if( !sel->ht_500(evt->ht()) ) continue;
      if( !sel->mht_200(evt->mht()) ) continue;
      // Apply the delta-phi cuts
//      if( !sel->dphi(evt->nJets(),evt->minDeltaPhiN()) ) continue;
      if( !sel->dphi(evt->nJets(),evt->deltaPhi1(),evt->deltaPhi2(),evt->deltaPhi3(),evt->deltaPhi4()) ) continue;

      if(verbose!=0)printf("\n############ \n event: %d \n ",eventN-1);

      double genMuPt=0.;
      double genMuEta=-99.;
      double genMuPhi=-99.;
      int firstMuId=0;
      vector<TVector3> genMuonVec;
      TVector3 temp3vec;
      genMuonVec.clear();
      bool isMuon = false;

      for(int i=0; i< evt->GenMuPtVec_().size(); i++){
        if(evt->GenMuFromTauVec_()[i]==0){
          genMuPt = evt->GenMuPtVec_().at(i);
          genMuEta = evt->GenMuEtaVec_().at(i);
          genMuPhi = evt->GenMuPhiVec_().at(i);
          isMuon=true;
          temp3vec.SetPtEtaPhi(genMuPt,genMuEta,genMuPhi);
          genMuonVec.push_back(temp3vec);
        }
        
        if(verbose!=0){
          printf("Muon # %d, pt: %g, eta: %g, phi: %g \n ",i,genMuPt,genMuEta,genMuPhi);
        }

        break; // if more than one muon exist, pick the energetic one. 
      }

      // ask for exactly one muon
      if( evt->GenMuPtVec_().size() > 1 ) continue;

      if( !( isMuon ) ) continue;

      // recompute ht mht njet
      double scale;
      if(genMuPt >=20.)scale = utils->getRandom(genMuPt,vec_resp );
      else scale = utils->getRandom(20.,vec_resp );
      double simTauJetPt = scale * genMuPt;
      double simTauJetEta = genMuEta;
      double simTauJetPhi = genMuPhi;

        // 3Vec of muon and scaledMu
        TVector3 SimTauJet3Vec,NewTauJet3Vec,Muon3Vec;
        SimTauJet3Vec.SetPtEtaPhi(simTauJetPt,simTauJetEta,simTauJetPhi);
        Muon3Vec.SetPtEtaPhi(genMuPt,genMuEta,genMuPhi);

        // New ht and mht
        vector<TVector3> HT3JetVec,MHT3JetVec;
        HT3JetVec.clear();
        MHT3JetVec.clear();
        TVector3 temp3Vec;
        int slimJetIdx=-1;
        utils->findMatchedObject(slimJetIdx,genMuEta,genMuPhi,evt->slimJetPtVec_(),evt->slimJetEtaVec_(), evt->slimJetPhiVec_(),deltaRMax,verbose);
        // If there is no match, add the tau jet as a new one
        if(slimJetIdx==-1){
          NewTauJet3Vec=SimTauJet3Vec;
          if(NewTauJet3Vec.Pt()>30. && fabs(NewTauJet3Vec.Eta())<2.4)HT3JetVec.push_back(NewTauJet3Vec);
          if(NewTauJet3Vec.Pt()>30. && fabs(NewTauJet3Vec.Eta())<5.)MHT3JetVec.push_back(NewTauJet3Vec);
        }
        for(int i=0;i<evt->slimJetPtVec_().size();i++){
          if(i!=slimJetIdx){
            temp3Vec.SetPtEtaPhi(evt->slimJetPtVec_()[i],evt->slimJetEtaVec_()[i],evt->slimJetPhiVec_()[i]);
            if(evt->slimJetPtVec_()[i]>30. && fabs(evt->slimJetEtaVec_()[i])<2.4)HT3JetVec.push_back(temp3Vec);
            if(evt->slimJetPtVec_()[i]>30. && fabs(evt->slimJetEtaVec_()[i])<5.)MHT3JetVec.push_back(temp3Vec);
          }
          else if(i==slimJetIdx){
            temp3Vec.SetPtEtaPhi(evt->slimJetPtVec_()[i],evt->slimJetEtaVec_()[i],evt->slimJetPhiVec_()[i]);
            NewTauJet3Vec=temp3Vec-Muon3Vec+SimTauJet3Vec;
            if(NewTauJet3Vec.Pt()>30. && fabs(NewTauJet3Vec.Eta())<2.4)HT3JetVec.push_back(NewTauJet3Vec);
            if(NewTauJet3Vec.Pt()>30. && fabs(NewTauJet3Vec.Eta())<5.)MHT3JetVec.push_back(NewTauJet3Vec);
          }

        }

        // Order the HT3JetVec and MHT3JetVec based on their pT
        HT3JetVec = utils->Order_the_Vec(HT3JetVec);
        MHT3JetVec = utils->Order_the_Vec(MHT3JetVec);


        double newHT=0,newMHT=0,newMHTPhi=-1;
        TVector3 newMHT3Vec;
        for(int i=0;i<HT3JetVec.size();i++){
          newHT+=HT3JetVec[i].Pt();
        }
        for(int i=0;i<MHT3JetVec.size();i++){
          newMHT3Vec-=MHT3JetVec[i];
        }
        newMHT=newMHT3Vec.Pt();
        newMHTPhi=newMHT3Vec.Phi();

        //New #Jet
        int newNJet = HT3JetVec.size();
        if(verbose==1)printf("newNJet: %d \n ",newNJet);



      // Acceptance determination 1: Counter for all events
      // with muons at generator level
      hAccAll->Fill( binMap_mht_nj[utils2::findBin_mht_nj(evt->nJets(),evt->mht()).c_str()] );
//      hAccAll->Fill( binMap_mht_nj[utils2::findBin_mht_nj(newNJet,newMHT).c_str()] ); // this doesn't work good

      // Check if generator-level muon is in acceptance
      if( genMuPt > LeptonAcceptance::muonPtMin() && std::abs(genMuEta) < LeptonAcceptance::muonEtaMax() ) {
        if(verbose!=0)printf("Muon is in acceptance \n ");
        // Acceptance determination 2: Counter for only those events
        // with generator-level muons inside acceptance
        // hAccPass->Fill( binMap[utils2::findBin(cntNJetsPt30Eta24,nbtag,HT,template_mht).c_str()] );
        hAccPass->Fill( binMap_mht_nj[utils2::findBin_mht_nj(evt->nJets(),evt->mht()).c_str()] );
//        hAccPass->Fill( binMap_mht_nj[utils2::findBin_mht_nj(newNJet,newMHT).c_str()] );

        // Reconstruction-efficiency determination 1: Counter for all events
        // with generator-level muons inside acceptance, regardless of whether
        // the muon has also been reconstructed or not.
        // hIsoRecoAll->Fill( binMap[utils2::findBin(cntNJetsPt30Eta24,nbtag,HT,template_mht).c_str()]);
        hIsoRecoAll->Fill( binMap[utils2::findBin_NoB(evt->nJets(),evt->ht(),evt->mht()).c_str()]);

        // Check if the muon has been reconstructed: check if a reconstructed
        // muon is present in the event that matches the generator-level muon
        // Isolation-efficiency determination 1: Counter for all events with a
        // reconstructed muon that has a generator-level muon match inside the
        // the acceptance, regardless of whether the reconstructed muon is also
        // isolated or not.

//if( evt->MuPtVec_().size()>0 )printf(" RecoMu--> Pt: %g eta: %g phi: %g deltaRMax: %g ",evt->MuPtVec_()[0],evt->MuEtaVec_()[0],evt->MuPhiVec_()[0],deltaRMax); // Ahmad3
//else cout << " Muon size is 0 \n " ;
        // in R and in pt
        int matchedMuonIdx = -1;
        if(evt->MuPtVec_().size()>0 && utils->findMatchedObject(matchedMuonIdx,genMuEta,genMuPhi,evt->MuPtVec_(),evt->MuEtaVec_(),evt->MuPhiVec_(),deltaRMax,verbose) ) {
          // Muon is reconstructed
          const double relDeltaPtMu = std::abs(genMuPt - evt->MuPtVec_().at(matchedMuonIdx) ) / evt->MuPtVec_().at(matchedMuonIdx) ;
          if(verbose!=0)printf(" relDeltaPtMu: %g \n ",relDeltaPtMu);
          if( relDeltaPtMu < deltaPtMax ) {
            // and matches generated pt
            if(verbose!=0)printf("Muon is reconstructed \n ");
            // Check if the muon is also isolated: check if an isolated muon is present
            // in the event that matches the reconstructed muon in R
            if( /*muonsRelIso->at(matchedMuonIdx) <= Selection::muIso()*/ true ){
                //.................//.................//
                // Currently muons are picked if they are isolated.
                // So we don't need to put a cut here.     
                //.................//.................//
              // Muon is isolated
              if(verbose!=0)printf("Muon is isolated \n ");
              // Reconstruction-efficiency determination 2: Counter for those events
              // with generator-level muons inside acceptance where the muon has also
              // been reconstructed.
              // Isolation-efficiency determination 2: Counter for those events where
              // the muon is also isolated.
              // hIsoRecoPass->Fill( binMap[utils2::findBin(cntNJetsPt30Eta24,nbtag,HT,template_mht).c_str()] );
              hIsoRecoPass->Fill( binMap[utils2::findBin_NoB(evt->nJets(),evt->ht(),evt->mht()).c_str()] );
            } // End of muon is isolated
          } // End of pt matching
        } // End of reconstructed muon
      } // End of muon in acceptance



    } // end of loop over events


     // Compute acceptance
    TH1* hAcc = static_cast<TH1*>(hAccPass->Clone("hAcc"));
    hAcc->Divide(hAccPass,hAccAll,1,1,"B");// we use B option here because the two histograms are correlated. see TH1 page in the root manual.

    // Compute efficiencies
    TH1* hEff = static_cast<TH1*>(hIsoRecoPass->Clone("hEff"));
    hEff->Divide(hIsoRecoPass,hIsoRecoAll,1,1,"B");

    if(verbose!=0){
      for(int j=1; j<= totNbins; j++){
        printf("hAccAll: %g hAccPass: %g hAcc: %g hIsoRecoAll: %g hIsoRecoPass: %g hEff: %g \n ",hAccAll->GetBinContent(j),hAccPass->GetBinContent(j),hAcc->GetBinContent(j),hIsoRecoAll->GetBinContent(j),hIsoRecoPass->GetBinContent(j),hEff->GetBinContent(j));
      }
    }


    // --- Save the Histograms to File -----------------------------------
    sprintf(tempname,"LostLepton/LostLepton2_MuonEfficienciesFrom%s_%s.root",subSampleKey.c_str(),inputnumber.c_str());
    TFile outFile(tempname,"RECREATE");
    hAcc->Write();
    hEff->Write();
    hAccAll->Write();
    hAccPass->Write();
    hIsoRecoAll->Write();
    hIsoRecoPass->Write();
    outFile.Close();




  } // end of main
void ttreesToHistograms() {
//********************************************************************
//****                      Variables                           ****//
cout << "Loading variables into vectors..." << endl;

vector<TString> fileName;
fileName.push_back( "rootfiles0/PhotonJetPt15_Summer09.root"  );//file0
fileName.push_back( "rootfiles0/PhotonJetPt30_Summer09.root"  );//file1
fileName.push_back( "rootfiles0/PhotonJetPt80_Summer09.root"  );//file2
fileName.push_back( "rootfiles0/PhotonJetPt170_Summer09.root" );//file3
fileName.push_back( "rootfiles0/PhotonJetPt300_Summer09.root" );//file4
fileName.push_back( "rootfiles0/PhotonJetPt470_Summer09.root" );//file5
fileName.push_back( "rootfiles0/PhotonJetPt800_Summer09.root" );//file6

TString treeName = "TreePhotonJet";

TString outputFileName = "PhotonJetHists-2009-09-02-matchesReco.root";


//*********************************
//**** Set Scale
// The following 4 number set the scale
// example:
//   scale = (integrated luminosity (1/pb))*(cross section (pb))*(filter eff)/(events analyzed)
float invLuminosityToScaleTo = 200; // in pb-1

vector<float> crossSection;
crossSection.push_back( 2.887E5 -3.222E4 );  // in pb
crossSection.push_back( 3.222E4 -1.010E3 );
crossSection.push_back( 1.010E3 -5.143E1 );
crossSection.push_back( 5.143E1 -4.193E0 );
crossSection.push_back( 4.193E0 -4.515E-1 );
crossSection.push_back( 4.515E-1 -2.003E-2 );
crossSection.push_back( 2.003E-2 );

vector<float> filterEffeciency;
filterEffeciency.push_back( 1.0 );
filterEffeciency.push_back( 1.0 );
filterEffeciency.push_back( 1.0 );
filterEffeciency.push_back( 1.0 );
filterEffeciency.push_back( 1.0 );
filterEffeciency.push_back( 1.0 );
filterEffeciency.push_back( 1.0 );

vector<float> eventsAnalyzied;
eventsAnalyzied.push_back( 1073270 );
eventsAnalyzied.push_back( 1088546 );
eventsAnalyzied.push_back(  993509 );
eventsAnalyzied.push_back( 1483940 );
eventsAnalyzied.push_back( 1024589 );
eventsAnalyzied.push_back( 1014413 );
eventsAnalyzied.push_back( 1216320 );
// END of setting scale
//*********************************


//*********************************
//****         Set Cuts      ****//
// Variables will be plotted for each "location"
vector<TString> locationCut;
locationCut.push_back( "abs(hardGenPhoton_eta)>1.55&&abs(hardGenPhoton_eta)<2.5" );
locationCut.push_back( "abs(hardGenPhoton_eta)<1.45" );

vector<TString> locationName;
locationName.push_back( "Endcap" );
locationName.push_back( "Barrel" );

// These cuts will be merged into one giant cut, applied to all plots for all files
vector<TString> cuts;
cuts.push_back( "hardGenPhoton_et>15.0&&photon_et>15.0&&photon_matches_hardGen>0.5" );

// These cuts will be applied only to corresponding file
vector<TString> fileCuts;
fileCuts.push_back( "event_genEventScale>15&&event_genEventScale<30"    ); //file0
fileCuts.push_back( "event_genEventScale>30&&event_genEventScale<80"    ); //file1
fileCuts.push_back( "event_genEventScale>80&&event_genEventScale<170"   ); //file2
fileCuts.push_back( "event_genEventScale>170&&event_genEventScale<300"  ); //file3
fileCuts.push_back( "event_genEventScale>300&&event_genEventScale<470"  ); //file4
fileCuts.push_back( "event_genEventScale>470&&event_genEventScale<800"  ); //file5
fileCuts.push_back( "event_genEventScale>800&&event_genEventScale<1400" ); //file6
//**** END of setting cuts
//*********************************


//*********************************
int locationVariablesToPlot[2][2]; // [a][b], a=number of locations, b=2 (for min,max range of variables to plot)
locationVariablesToPlot[0][0] = 16; // Endcap
locationVariablesToPlot[0][1] = 35;
locationVariablesToPlot[1][0] = 16; // Barrel
locationVariablesToPlot[1][1] = 35;
/*locationVariablesToPlot[2][0] = 0;
locationVariablesToPlot[2][1] = 4;
locationVariablesToPlot[3][0] = 0;
locationVariablesToPlot[3][1] = 4;
locationVariablesToPlot[4][0] = 0;
locationVariablesToPlot[4][1] = 4;
locationVariablesToPlot[5][0] = 0;
locationVariablesToPlot[5][1] = 4;
locationVariablesToPlot[6][0] = 0;
locationVariablesToPlot[6][1] = 4;
locationVariablesToPlot[7][0] = 0;
locationVariablesToPlot[7][1] = 4;*/

// Variables you want plotted
vector<TString> variableToPlot;
// --- the following require gen level info
variableToPlot.push_back( "hardGenPhoton_et"  );  // 0
variableToPlot.push_back( "hardGenPhoton_eta" );
variableToPlot.push_back( "hardGenPhoton_phi" );
variableToPlot.push_back( "fmod(hardGenPhoton_phi+3.141592,20.0*3.141592/180.0)-10.0*3.141592/180.0" );
variableToPlot.push_back( "abs(hardGenPhoton_eta)" ); // 4
variableToPlot.push_back( "(recPhoton.energy-hardGenPhoton_energy)/hardGenPhoton_energy" );
variableToPlot.push_back( "(recPhoton.energy-hardGenPhoton_energy)/hardGenPhoton_energy:hardGenPhoton_energy"   );
variableToPlot.push_back( "(recPhoton.energy-hardGenPhoton_energy)/hardGenPhoton_energy:abs(hardGenPhoton_eta)" );
variableToPlot.push_back( "(recPhoton.energy-hardGenPhoton_energy)/hardGenPhoton_energy:hardGenPhoton_phiMod"   );
variableToPlot.push_back( "photon_hadronicOverEm:hardGenPhoton_et"       );
variableToPlot.push_back( "photon_hadronicOverEm:abs(hardGenPhoton_eta)" ); // 10
variableToPlot.push_back( "photon_hadronicOverEm:hardGenPhoton_phiMod"   );
variableToPlot.push_back( "photon_eta-hardGenPhoton_eta" );
variableToPlot.push_back( "photon_eta-hardGenPhoton_eta:hardGenPhoton_et" );
variableToPlot.push_back( "photon_eta-hardGenPhoton_eta:abs(hardGenPhoton_eta)" );
variableToPlot.push_back( "deltaPhiGenRecPhoton" );  // 15
// --- the following require only rec photons
variableToPlot.push_back( "photon_et"  );         // 16
variableToPlot.push_back( "photon_eta" );
variableToPlot.push_back( "photon_phi" );
variableToPlot.push_back( "fmod(photon_phi+3.141592,20.0*3.141592/180.0)-10.0*3.141592/180.0" );
variableToPlot.push_back( "abs(photon_eta)" );    // 20
variableToPlot.push_back( "photon_r9" );
variableToPlot.push_back( "photon_ecalRecHitSumEtConeDR03" );
variableToPlot.push_back( "photon_hcalTowerSumEtConeDR03"  );
variableToPlot.push_back( "photon_trkSumPtSolidConeDR03"   );
variableToPlot.push_back( "photon_trkSumPtHollowConeDR03"  ); //25
variableToPlot.push_back( "photon_nTrkSolidConeDR03"  );
variableToPlot.push_back( "photon_nTrkHollowConeDR03" );
variableToPlot.push_back( "photon_hadronicOverEm"     );
variableToPlot.push_back( "photon_r2x5" );
variableToPlot.push_back( "photon_ecalRecHitSumEtConeDR03/photon_et" ); // 30
variableToPlot.push_back( "photon_hcalTowerSumEtConeDR03/photon_et"  );
variableToPlot.push_back( "photon_trkSumPtSolidConeDR03/photon_et"   );
variableToPlot.push_back( "photon_trkSumPtHollowConeDR03/photon_et"  );
// --- the following require jets
/*variableToPlot.push_back( "calcDeltaPhi(photon_phi,jet_phi)"  );
variableToPlot.push_back( "calcDeltaPhi(photon_phi,jet2_phi)" ); // 35
variableToPlot.push_back( "calcDeltaPhi(jet_phi,jet2_phi)"    );*/
variableToPlot.push_back( "(photon_et-jet_et)/photon_et"      );
variableToPlot.push_back( "jet2_et/photon_et"                 );

// Histograms for the above variables
vector<TH1*> histogram;
// --- the following require gen level info
histogram.push_back( new TH1F("photonGenEt",     "Photon E_{T} ;E_{T} (GeV);entries per 15 GeV",  50,  0, 750)  );  // 0
histogram.push_back( new TH1F("photonGenEta",    "Photon #eta ;#eta;entries per 0.1 bin",   61, -3.05,   3.05) );
histogram.push_back( new TH1F("photonGenPhi",    "Photon #phi ;#phi;entries per bin",   62, (-1.-1./30.)*TMath::Pi(), (1.+1./30.)*TMath::Pi()) );
histogram.push_back( new TH1F("photonGenPhiMod", "Photon #phi_{mod} ", 42, (-1.-1./20)*0.1745329, (1.+1./20.)*0.1745329) );
histogram.push_back( new TH1F("photonGenAbsEta", "Photon |#eta| ", 51, 0.00,   2.55) );
histogram.push_back( new TH1F("photonDeltaE",    "(E(#gamma_{rec})-E(#gamma_{gen}))/E(#gamma_{gen}) ", 50, -0.8, 0.3) );
histogram.push_back( new TH2F("photonDeltaE_vs_E","(E(#gamma_{rec})-E(#gamma_{gen}))/E(#gamma_{gen}) vs E(#gamma_{gen}) ", 50, 0, 3000, 50, -0.8, 0.3) );
histogram.push_back( new TH2F("photonDeltaE_vs_AbsEta","(E(#gamma_{rec})-E(#gamma_{gen}))/E(#gamma_{gen}) vs |#eta(#gamma_{gen}|) ", 51, 0.0, 2.5, 50, -0.8, 0.3) );
histogram.push_back( new TH2F("photonDeltaE_vs_PhiMod","(E(#gamma_{rec})-E(#gamma_{gen}))/E(#gamma_{gen}) vs #phi_{mod}(#gamma_{gen}) ", 42, (-1.-1./20)*0.1745329, (1.+1./20.)*0.1745329, 50, -0.9, 0.2) );
histogram.push_back( new TH2F("photonHoverE_vs_Et",     "H/E vs E_{T}(#gamma_{gen}) ", 50, 0, 1000, 50, 0.0, 0.2) );
histogram.push_back( new TH2F("photonHoverE_vs_AbsEta", "H/E vs |#eta(#gamma_{gen})| ", 51, 0.0, 2.5, 50, 0.0, 0.2) );
histogram.push_back( new TH2F("photonHoverE_vs_PhiMod", "H/E vs #phi_{mod}(#gamma_{gen}) ", 42, (-1.-1./20)*0.1745329, (1.+1./20.)*0.1745329, 50, 0.0, 0.2) );
histogram.push_back( new TH1F("photonDeltaEta", "#Delta#eta(#gamma_{rec},#gamma_{gen}) ;#Delta#eta(#gamma_{rec},#gamma_{gen});entries/bin", 41, -0.01, 0.01) );
histogram.push_back( new TH2F("photonDeltaEta_vs_Et",    "#Delta#eta(#gamma_{rec},#gamma_{gen}) vs E_{T}(#gamma_{gen}) ", 50, 0, 1000, 41, -0.1, 0.1) );
histogram.push_back( new TH2F("photonDeltaEta_vs_AbsEta","#Delta#eta(#gamma_{rec},#gamma_{gen}) vs #eta(#gamma_{gen})", 51, 0.0, 2.55, 41, -0.1, 0.1) );
histogram.push_back( new TH1F("photonDeltaPhi",          "#Delta#phi(#gamma_{rec},#gamma_{gen}) ;#Delta#phi(#gamma_{rec},#gamma_{gen});entries/bin", 41, 0.0, 0.01) ); // 15
// --- the following require only rec photons
histogram.push_back( new TH1F("photonEt",        "Photon E_{T} ;E_{T} (GeV);entries per 15 GeV", 50,  0,    750   ) ); // 16
histogram.push_back( new TH1F("photonEta",       "Photon #eta ;#eta;entries per 0.1"           , 61, -3.05,   3.05) );
histogram.push_back( new TH1F("photonPhi",       "Photon #phi ;#phi;entries per bin"           , 62, (-1.-1./30.)*TMath::Pi(), (1.+1./30.)*TMath::Pi()) );
histogram.push_back( new TH1F("photonPhiMod",    "Photon #phi_{mod} "                          , 42, (-1.-1./20)*0.1745329, (1.+1./20.)*0.1745329) );
histogram.push_back( new TH1F("photonAbsEta",    "Photon |#eta| "                              , 51, 0.00,  2.55) );  // 20
histogram.push_back( new TH1F("photonR9",        "R9 = E(3x3) / E(SuperCluster)  ;R9;entries/bin"   , 50, 0.6, 1.0) );
histogram.push_back( new TH1F("photonEcalIso",   "#SigmaEcal Rec Hit E_{T} in Hollow #DeltaR cone " , 50, 0  , 15) );
histogram.push_back( new TH1F("photonHcalIso",   "#SigmaHcal Rec Hit E_{T} in Hollow #DeltaR cone " , 50, 0  , 15) );
histogram.push_back( new TH1F("photonTrackSolidIso",     "#Sigmatrack p_{T} in Solid #DeltaR cone " , 50, 0  , 15) );
histogram.push_back( new TH1F("photonTrackHollowIso",    "#Sigmatrack p{T} in Hollow #DeltaR cone " , 50, 0  , 15) );  // 25
histogram.push_back( new TH1F("photonTrackCountSolid",   "Number of tracks in Solid #DeltaR cone ;Number of Tracks;entries/bin" , 25, -0.5, 24.5) );
histogram.push_back( new TH1F("photonTrackCountHollow",  "Number of tracks in Hollow #DeltaR cone ;Number of Tracks;entries/bin", 25, -0.5, 24.5) );
histogram.push_back( new TH1F("photonHoverE",            "Hadronic / EM ", 50, 0.0, 0.2) );
histogram.push_back( new TH1F("photonScSeedE2x5over5x5", "E2x5/E5x5  "   , 50, 0.6, 1.0) );
histogram.push_back( new TH1F("photonEcalIsoOverE",        "#SigmaEcal Rec Hit E_{T} in #DeltaR cone / Photon E_{T} " , 50, -0.1, 1.0) ); // 30
histogram.push_back( new TH1F("photonHcalIsoOverE",        "#SigmaHcal Rec Hit E_{T} in #DeltaR cone / Photon E_{T} " , 50, -0.1, 1.0) );
histogram.push_back( new TH1F("photonTrackSolidIsoOverE" , "#SigmaTrack p_{T} in #DeltaR cone / Photon E_{T} "        , 50, -0.1, 1.0) );
histogram.push_back( new TH1F("photonTrackHollowIsoOverE", "#SigmaTrack p_{T} in Hollow #DeltaR cone / Photon E_{T} " , 50, -0.1, 1.0) );
// --- the following require jets
/*histogram.push_back( new TH1F("h_deltaPhi_photon_jet", "#Delta#phi between Highest E_{T} #gamma and jet;#Delta#phi(#gamma,1^{st} jet)"               , 50, 0, 3.1415926) );
histogram.push_back( new TH1F("h_deltaPhi_photon_jet2","#Delta#phi between Highest E_{T} #gamma and 2^{nd} highest jet;#Delta#phi(#gamma,2^{nd} jet)", 50, 0, 3.1415926) );
histogram.push_back( new TH1F("h_deltaPhi_jet_jet2"  , "#Delta#phi between Highest E_{T} jet and 2^{nd} jet;#Delta#phi(1^{st} jet,2^{nd} jet)"       , 50, 0, 3.1415926) );*/
histogram.push_back( new TH1F("h_deltaEt_photon_jet" , "(E_{T}(#gamma)-E_{T}(jet))/E_{T}(#gamma) when #Delta#phi(#gamma,1^{st} jet) > 2.8;#DeltaE_{T}(#gamma,1^{st} jet)/E_{T}(#gamma)", 20, -1.0, 1.0) );
histogram.push_back( new TH1F("h_jet2_etOverPhotonEt", "E_{T}(2^{nd} highest jet) / E_{T}(#gamma);E_{T}(2^{nd} Jet)/E_{T}(#gamma)", 20, 0.0, 4.0) );
//****                  END of Variables                        ****//
//********************************************************************




//********************************************************************
//****                Main part of Program                      ****//

 // Human error checking
 if (variableToPlot.size() != histogram.size() ) {
   cout << "Should have equal entries in histogram and variableToPlot vector." << endl;
   return;
 }
 if (fileName.size() > crossSection.size() ) {
   cout << "Should have equal entries in fileName and crossSection vetor." << endl;
   return;
 }
 if (fileName.size() > fileCuts.size() ) {
   cout << "Should have equal entries in fileName and fileCuts vector." << endl;
   return;
 }

 // Combine all the cuts into one
 cout << endl << "Cuts that will be applied to everything: " << endl << "  ";
 TCut allCuts = "";
 for (int i =0; i<cuts.size(); i++) {
   allCuts += cuts[i];
   if (i>0) cout << "&&";
   cout << "(" << cuts[i] << ")";
 }
 cout << endl << endl;


 // Open the files & set their scales
 cout << endl << "Histograms will be scaled to " << invLuminosityToScaleTo << "pb-1 " << endl;
 cout << "Looking for TTree named \"" << treeName << "\" in files..." << endl;
 vector<float> fileScale;
 TList *fileList = new TList();
 for (int i=0; i < fileName.size(); i++) {

   TFile* currentFile = TFile::Open(fileName[i]);
   fileList->Add(currentFile);
   float currentScale = crossSection[i]*invLuminosityToScaleTo*filterEffeciency[i]/eventsAnalyzied[i];
   fileScale.push_back( currentScale );

   // Display entries in that file's TTree
   TTree* tree;
   currentFile->GetObject(treeName, tree);
   cout << "file" << i <<": " << fileName[i] << " contains " << tree->GetEntries(allCuts) << " entries, and will be scaled by " << 
currentScale << endl;
 }
 cout << endl << endl;


 //Create output file
 TFile *outputFile = TFile::Open( outputFileName, "RECREATE" );


 //************************************************************
 //                 Core of the Script                       //
 // Loop over locations
 for (int l=0; l<locationName.size(); l++) {
   TString currentLocation = locationName[l];
   TCut currentCuts = allCuts;
   currentCuts += locationCut[l];
   cout << "Creating plots for " << currentLocation << ", " << locationCut[l] << endl;
  
   // Loop over variables to plot
   for (int i=0; i<variableToPlot.size(); i++) {
     // should we plot this variable for this location?
     if (i<locationVariablesToPlot[l][0] || i>locationVariablesToPlot[l][1]) continue;

     TString currentHistType  = histogram[i]->IsA()->GetName();
     TString currentHistName  = TString(histogram[i]->GetName())  + "_" + currentLocation;
     TString currentHistTitle = TString(histogram[i]->GetTitle()) + "(" + currentLocation + ")";
     cout << "  " << variableToPlot[i] << " >> " << currentHistName;
     TString currentHistDrawOpt;
     if (currentHistType=="TH2F") {
       currentHistDrawOpt="goffbox";
     } else {
       currentHistDrawOpt="egoff";
     }
     TH1* currentHist = (TH1*)histogram[i]->Clone(currentHistName);  // Creates clone with name currentHistName
     currentHist->Sumw2(); // store errors
     currentHist->SetTitle(currentHistTitle);
     //cout << " from file";

     // Plot from the first file
     int f = 0;
     //cout << f;
     TTree *tree;
     TFile *current_file = (TFile*)fileList->First();
     current_file->cd();
     current_file->GetObject(treeName, tree);
     tree->Draw(variableToPlot[i]+">>"+currentHistName,currentCuts+TCut(fileCuts[f]),currentHistDrawOpt);
     currentHist->Scale(fileScale[f]);
     f++;

     // Loop over files
     current_file = (TFile*)fileList->After( current_file );
     while ( current_file ) {
       current_file->cd();
       //cout << ", file" << f;
       current_file->GetObject(treeName, tree);

       TString tempHistName = currentHistName+"Temp";
       TH1* tempHist = (TH1*)currentHist->Clone(tempHistName);
       tree->Draw(variableToPlot[i]+">>"+tempHistName,currentCuts+TCut(fileCuts[f]),currentHistDrawOpt);
       tempHist->Scale(fileScale[f]);
       currentHist->Add(tempHist);
       tempHist->Delete();

       current_file = (TFile*)fileList->After( current_file );
       f++;
     } // End of loop over files

     outputFile->cd();
     currentHist->Write();
     cout << endl;
   } // End of loop over variabls to plot
 } // End of loop over locations
 //                  END of Core of Script                   //
 //************************************************************

 cout << endl;
 cout << "Wrote file " << outputFileName << endl;
 cout << endl;
 outputFile->Close();
}
void comparisonJetMCData(string plot,int rebin){
  string tmp;

  string dir="/gpfs/cms/data/2011/Observables/Approval/";
	
  if (isAngularAnalysis){
    mcfile=dir+"MC_zjets"+version;
    back_w=dir+"MC_wjets"+version;
    back_ttbar=dir+"MC_ttbar"+version;
    WW=dir+"MC_diW"+version;
    ZZ=dir+"MC_siZ"+version;
    WZ=dir+"MC_diWZ"+version;
    datafile=dir+"DATA"+version;
    mcfiletau=dir+"MC_zjetstau"+version;
  }
  // List of files

  TFile *dataf = TFile::Open(datafile.c_str()); //data file
  TFile *mcf = TFile::Open(mcfile.c_str()); //MC file
  TFile *mcftau = TFile::Open(mcfiletau.c_str()); //MC file
  TFile *ttbarf = TFile::Open(back_ttbar.c_str()); //MC background file
  TFile *wf = TFile::Open(back_w.c_str());


  TFile *qcd23emf = TFile::Open(qcd23em.c_str());
  TFile *qcd38emf = TFile::Open(qcd38em.c_str());
  TFile *qcd817emf = TFile::Open(qcd817em.c_str());

  TFile *qcd23bcf = TFile::Open(qcd23bc.c_str());
  TFile *qcd38bcf = TFile::Open(qcd38bc.c_str());
  TFile *qcd817bcf = TFile::Open(qcd817bc.c_str());

  TFile *WZf = TFile::Open(WZ.c_str());
  TFile *ZZf = TFile::Open(ZZ.c_str());
  TFile *WWf = TFile::Open(WW.c_str());


  // Canvas
  if (CanvPlot) delete CanvPlot;
  CanvPlot = new TCanvas("CanvPlot","CanvPlot",0,0,800,600);

  // Getting, defining ...
  dataf->cd("validationJEC");
  if (isMu && isAngularAnalysis) dataf->cd("validationJECmu");
	
  TObject * obj;
  gDirectory->GetObject(plot.c_str(),obj);

  TH1 *data;
  TH2F *data2; 
  TH1D *data3; 

  THStack *hs = new THStack("hs","Total MC");


  int flag=-1;
  if ((data = dynamic_cast<TH1F *>(obj)) ){
    flag=1;
    gROOT->Reset();
    gROOT->ForceStyle();
    gStyle->SetPadRightMargin(0.03);
    gPad->SetLogy(1);
    gPad->Modified();
    gPad->Update();
  }
  if ((data2 = dynamic_cast<TH2F *>(obj)) ){
    flag=2;
    gStyle->SetPalette(1);
    gStyle->SetPadRightMargin(0.15);
    gPad->Modified();
  }



  //===================
  // Dirty jobs :)
  if (flag==1){
    CanvPlot->cd();
    TPad *pad1 = new TPad("pad1","pad1",0.01,0.33,0.99,0.99);
    pad1->Draw();
    pad1->cd();
    pad1->SetTopMargin(0.1);
    pad1->SetBottomMargin(0.01);
    pad1->SetRightMargin(0.1);
    pad1->SetFillStyle(0);
    pad1->SetLogy(1);
    TString str=data->GetTitle();
    if (str.Contains("jet") && !str.Contains("zMass") && !str.Contains("Num") && !str.Contains("Eta") && !str.Contains("Phi") && !str.Contains("eld") && !str.Contains("meanPtZVsNjet")) {
      if (!isAngularAnalysis) rebin=1;
    }

    //======================
    // DATA
    Double_t dataint = data->Integral();
    data->SetLineColor(kBlack);
    data->Rebin(rebin);
    if(str.Contains("nJetVtx")) data->GetXaxis()->SetRangeUser(0,10);	
    if(str.Contains("zMass")) data->GetXaxis()->SetRangeUser(70,110);	
    data->SetMinimum(1.);
    data->Sumw2();

    //Canvas style copied from plotsHistsRatio.C
    data->SetLabelSize(0.0);
    data->GetXaxis()->SetTitleSize(0.00);
    data->GetYaxis()->SetLabelSize(0.07);
    data->GetYaxis()->SetTitleSize(0.08);
    data->GetYaxis()->SetTitleOffset(0.76);
    data->SetTitle("");
    gStyle->SetOptStat(0);

    data->GetYaxis()->SetLabelSize(0.06);
    data->GetYaxis()->SetTitleSize(0.06);
    data->GetYaxis()->SetTitleOffset(0.8);

    data->Draw("E1");


    TLegend* legend = new TLegend(0.725,0.27,0.85,0.72);
    legend->SetFillColor(0);
    legend->SetFillStyle(0);
    legend->SetBorderSize(0);
    legend->SetTextSize(0.060);
    legend->AddEntry(data,"data","p");

    // hack to calculate some yields in restricted regions...
    int num1=0, num2=0, num3=0, num4=0, num5=0;
    if(str.Contains("invMass") && !str.Contains("PF")){
      for(int j=1;j<=data->GetNbinsX();j++){
	num1 += data->GetBinContent(j); 		//conto quante Z ci sono tra 60 e 120 GeV
	if(j>10&&j<=50) num2 += data->GetBinContent(j); // ... tra 70 e 110
	if(j>15&&j<=45) num3 += data->GetBinContent(j); // ... tra 75 e 105
      }
      cout << "\n";
      cout << data->GetNbinsX() <<" Number of bins of the invmass histo\n";
      printf("Number of Z in 60-120 %i --- 70-110 %i --- 75-105 %i \n",num1,num2,num3);
      cout << "\n";
    }
    if(str.Contains("zYieldVsjets") && !str.Contains("Vtx")){
      for(int j=1;j<=data->GetNbinsX();j++){
	num1 += data->GetBinContent(j); 		//conto quante Z
	if(j>1) num2 += data->GetBinContent(j); // ... +1,2,3,4... jets
	if(j>2) num3 += data->GetBinContent(j); // ... +2,3,4... jets
	if(j>3) num4 += data->GetBinContent(j); // ..    if(str=="jet_pT"){
	if(j>4) num5 += data->GetBinContent(j); // ... +4... jets
      }
      cout << "\n";
      cout << data->GetNbinsX() <<" Number of bins of the zYieldVsjets histo\n";
      printf("Number of Z+n jet %i --- >1 %i --- >2 %i --- >3 %i --- >4 %i \n",num1,num2,num3,num4,num5);
      cout << "\n";
    }    

    //======================
    // Z + jets signal
    mcf->cd("validationJEC");
    if (isMu) mcf->cd("validationJECmu/");

    if (isAngularAnalysis) {
      mcf->cd("validationJEC/");
      if (isMu) mcf->cd("validationJECmu/");
    }

    TH1F* mc;
    gDirectory->GetObject(plot.c_str(),mc);
    TH1F * hsum;
    if(mc){
      hsum =  (TH1F*) mc->Clone();
      hsum->SetTitle("hsum");
      hsum->SetName("hsum");
      hsum->Reset();

      Double_t mcint = mc->Integral();
      mc->SetFillColor(kRed);
      mc->Sumw2();
      if(lumiweights==0) mc->Scale(dataint/mcint);
		
      // Blocco da propagare negli altri MC
      if(zNumEvents>0.){
	if(lumiweights==1) {
	  if (WholeStat){
	    if (lumiPixel) mc->Scale( dataLumi2011pix / (zNumEvents / zjetsXsect));
	    else mc->Scale( dataLumi2011 / (zNumEvents / zjetsXsect));
	  }
	  else{
	    if (RunA){
	      if (lumiPixel) mc->Scale( dataLumi2011Apix / (zNumEvents / zjetsXsect));
	      else mc->Scale( dataLumi2011A / (zNumEvents / zjetsXsect));
	    }
	    if (!RunA){
	      if (lumiPixel) mc->Scale( dataLumi2011Bpix / (zNumEvents / zjetsXsect));
	      else mc->Scale( dataLumi2011B / (zNumEvents / zjetsXsect));
	    }
	  }
	}
      }
      else {
	if(lumiweights==1) mc->Scale(zjetsScale);
      }

      // fin qui
      if(lumiweights==1) mc->Scale(1./zwemean);  // perche' i Weights non fanno 1...
      mc->Rebin(rebin);
      if(lumiweights==0) mc->Draw("HISTO SAMES");
      hsum->Rebin(rebin);
      hsum->Add(mc);
      legend->AddEntry(mc,"Z+jets","f");
    }

    //======================
    // ttbar
    ttbarf->cd("validationJEC");
    if (isMu) ttbarf->cd("validationJECmu/");

    if (isAngularAnalysis) {
      ttbarf->cd("validationJEC/");
      if (isMu) ttbarf->cd("validationJECmu/");
    }

    TH1F* ttbar;
    gDirectory->GetObject(plot.c_str(),ttbar);
	
    if(ttbar){
      ttbar->SetFillColor(kBlue);
      ttbar->Sumw2();

      if(ttNumEvents>0.){
	if(lumiweights==1) {
	  if (WholeStat){
	    if (lumiPixel) ttbar->Scale( dataLumi2011pix / (ttNumEvents / ttbarXsect));
	    else ttbar->Scale( dataLumi2011 / (ttNumEvents / ttbarXsect));
	  }
	  else{
	    if (RunA){
	      if (lumiPixel) ttbar->Scale( dataLumi2011Apix / (ttNumEvents / ttbarXsect));
	      else ttbar->Scale( dataLumi2011A / (ttNumEvents / ttbarXsect));
	    }
	    if (!RunA){
	      if (lumiPixel) ttbar->Scale( dataLumi2011Bpix / (ttNumEvents / ttbarXsect));
	      else ttbar->Scale( dataLumi2011B / (ttNumEvents / ttbarXsect));
	    }
	  }
	}
      }
      else {
	if(lumiweights==1) ttbar->Scale(ttwemean);
      }
      // fin qui
		
      if(lumiweights==1) ttbar->Scale(1./ttwemean);  // perche' i Weights non fanno 1...
      ttbar->Rebin(rebin);
      if(lumiweights==0) ttbar->Draw("HISTO SAMES");
      hsum->Rebin(rebin);
      hsum->Add(ttbar);
      if(lumiweights==1)legend->AddEntry(ttbar,"ttbar","f");

      //////////
      //Storing the bckgrounds!
      //////////
      cout<<str<<endl;
      if (isAngularAnalysis){
      if(str=="jet_pT") evaluateAndFillBackgrounds(ttbar,"jet_pT");
      if(str=="jet_pT2") evaluateAndFillBackgrounds(ttbar,"jet_pT2");
      if(str=="jet_pT3") evaluateAndFillBackgrounds(ttbar,"jet_pT3");
      if(str=="jet_pT4") evaluateAndFillBackgrounds(ttbar,"jet_pT4");
      if(str=="Jet_multi") evaluateAndFillBackgrounds(ttbar,"jet_Multiplicity");
      if(str=="jet_eta") evaluateAndFillBackgrounds(ttbar,"jet_eta");
      if(str=="jet_eta2") evaluateAndFillBackgrounds(ttbar,"jet_eta2");
      if(str=="jet_eta3") evaluateAndFillBackgrounds(ttbar,"jet_eta3");
      if(str=="jet_eta4") evaluateAndFillBackgrounds(ttbar,"jet_eta4");
      if(str=="HT") evaluateAndFillBackgrounds(ttbar,"HT");
      if(str=="HT_1j") evaluateAndFillBackgrounds(ttbar,"HT1");
      if(str=="HT_2j") evaluateAndFillBackgrounds(ttbar,"HT2");
      if(str=="HT_3j") evaluateAndFillBackgrounds(ttbar,"HT3");
      if(str=="HT_4j") evaluateAndFillBackgrounds(ttbar,"HT4");
      if(str=="Phi_star") evaluateAndFillBackgrounds(ttbar,"PhiStar");
      }
    }

    //======================
    // w+jets
    wf->cd("validationJEC");
    if (isMu) wf->cd("validationJECmu/");
    if (isAngularAnalysis) {
      wf->cd("validationJEC/");
      if (isMu) wf->cd("validationJECmu/");      
    }

    TH1F* w;
    gDirectory->GetObject(plot.c_str(),w);
    if(w){

      w->SetFillColor(kViolet+2);
      w->Sumw2();

      if(wNumEvents>0.){
	if(lumiweights==1) {
	  if (WholeStat){
	    if (lumiPixel) w->Scale( dataLumi2011pix / (wNumEvents / wjetsXsect));
	    else w->Scale( dataLumi2011 / (wNumEvents / wjetsXsect));
	  }
	  else{
	    if (RunA){
	      if (lumiPixel) w->Scale( dataLumi2011Apix / (wNumEvents / wjetsXsect));
	      else w->Scale( dataLumi2011A / (wNumEvents / wjetsXsect));
	    }
	    if (!RunA){
	      if (lumiPixel) w->Scale( dataLumi2011Bpix / (wNumEvents / wjetsXsect));
	      else w->Scale( dataLumi2011B / (wNumEvents / wjetsXsect));
	    }
	  }
	}
      }
      else {
	if(lumiweights==1) w->Scale(wwemean);
      }
      // fin qui
		
      if(lumiweights==1) w->Scale(1./wwemean);  // perche' i Weights non fanno 1...
      w->Rebin(rebin);
      if(lumiweights==0) w->Draw("HISTO SAMES");
      hsum->Rebin(rebin);
      hsum->Add(w);
      if(lumiweights==1)legend->AddEntry(w,"W+jets","f");
    }

    //======================
    // wz+jets
    WZf->cd("validationJEC");
    if (isMu) WZf->cd("validationJECmu/");

    if (isAngularAnalysis) {
      WZf->cd("validationJEC/");
      if (isMu) WZf->cd("validationJECmu/");
    }

    TH1F* wz;
    gDirectory->GetObject(plot.c_str(),wz);
    if(wz){
      wz->SetFillColor(kYellow+2);
      wz->Sumw2();

      if(wzEvents>0.){
	if(lumiweights==1) {
	  if (WholeStat){
	    if (lumiPixel) wz->Scale( dataLumi2011pix / (wzEvents / WZXsect));
	    else wz->Scale( dataLumi2011 / (wzEvents / WZXsect));
	  }
	  else{
	    if (RunA){
	      if (lumiPixel) wz->Scale( dataLumi2011Apix / (wzEvents / WZXsect));
	      else wz->Scale( dataLumi2011A / (wzEvents / WZXsect));
	    }
	    if (!RunA){
	      if (lumiPixel) wz->Scale( dataLumi2011Bpix / (wzEvents / WZXsect));
	      else wz->Scale( dataLumi2011B / (wzEvents / WZXsect));
	    }
	  }
	}
      }
      else {
	if(lumiweights==1) wz->Scale(wzjetsScale);
      }
      // fin qui
		
      if(lumiweights==1) wz->Scale(1./wzwemean);  // perche' i Weights non fanno 1...
      wz->Rebin(rebin);
      if(lumiweights==0) wz->Draw("HISTO SAMES");
      hsum->Rebin(rebin);
      hsum->Add(wz);
      legend->AddEntry(wz,"WZ+jets","f");


      //////////
      //Storing the bckgrounds!
      //////////
     if (isAngularAnalysis){
      if(str=="jet_pT") evaluateAndFillBackgrounds(wz,"jet_pT");
      if(str=="jet_pT2") evaluateAndFillBackgrounds(wz,"jet_pT2");
      if(str=="jet_pT3") evaluateAndFillBackgrounds(wz,"jet_pT3");
      if(str=="jet_pT4") evaluateAndFillBackgrounds(wz,"jet_pT4");
      if(str=="jet_eta") evaluateAndFillBackgrounds(wz,"jet_eta");
      if(str=="jet_eta2") evaluateAndFillBackgrounds(wz,"jet_eta2");
      if(str=="jet_eta3") evaluateAndFillBackgrounds(wz,"jet_eta3");
      if(str=="jet_eta4") evaluateAndFillBackgrounds(wz,"jet_eta4");
      if(str=="Jet_multi") evaluateAndFillBackgrounds(wz,"jet_Multiplicity");
      if(str=="HT") evaluateAndFillBackgrounds(wz,"HT");
      if(str=="HT_1j") evaluateAndFillBackgrounds(wz,"HT1");
      if(str=="HT_2j") evaluateAndFillBackgrounds(wz,"HT2");
      if(str=="HT_3j") evaluateAndFillBackgrounds(wz,"HT3");
      if(str=="HT_4j") evaluateAndFillBackgrounds(wz,"HT4");
      if(str=="Phi_star") evaluateAndFillBackgrounds(wz,"PhiStar");
     }
    }
    
		
    //======================
    // zz+jets
    ZZf->cd("validationJEC");
    if (isMu) ZZf->cd("validationJECmu/");

    if (isAngularAnalysis) {
      ZZf->cd("validationJEC/");
      if (isMu) ZZf->cd("validationJECmu/");
    }

    TH1F* zz;
    gDirectory->GetObject(plot.c_str(),zz);
    if(zz){
      zz->SetFillColor(kOrange+2);
      zz->Sumw2();

      if(zzEvents>0.){
	if(lumiweights==1) {
	  if (WholeStat){
	    if (lumiPixel) zz->Scale( dataLumi2011pix / (zzEvents / ZZXsect));
	    else zz->Scale( dataLumi2011 / (zzEvents / ZZXsect));
	  }
	  else{
	    if (RunA){
	      if (lumiPixel) zz->Scale( dataLumi2011Apix / (zzEvents / ZZXsect));
	      else zz->Scale( dataLumi2011A / (zzEvents / ZZXsect));
	    }
	    if (!RunA){
	      if (lumiPixel) zz->Scale( dataLumi2011Bpix / (zzEvents / ZZXsect));
	      else zz->Scale( dataLumi2011B / (zzEvents / ZZXsect));
	    }
	  }
	}
      }
      else {
	if(lumiweights==1) zz->Scale(zzjetsScale);
      }
      // fin qui
		
      if(lumiweights==1) zz->Scale(1./zzwemean);  // perche' i Weights non fanno 1...
      zz->Rebin(rebin);
      if(lumiweights==0) zz->Draw("HISTO SAMES");
      hsum->Rebin(rebin);
      hsum->Add(zz);
      legend->AddEntry(zz,"ZZ+jets","f");

      //////////
      //Storing the bckgrounds!
      //////////
     if (isAngularAnalysis){
      if(str=="jet_pT") evaluateAndFillBackgrounds(zz,"jet_pT");
      if(str=="jet_pT2") evaluateAndFillBackgrounds(zz,"jet_pT2");
      if(str=="jet_pT3") evaluateAndFillBackgrounds(zz,"jet_pT3");
      if(str=="jet_pT4") evaluateAndFillBackgrounds(zz,"jet_pT4");
      if(str=="jet_eta") evaluateAndFillBackgrounds(zz,"jet_eta");
      if(str=="jet_eta2") evaluateAndFillBackgrounds(zz,"jet_eta2");
      if(str=="jet_eta3") evaluateAndFillBackgrounds(zz,"jet_eta3");
      if(str=="jet_eta4") evaluateAndFillBackgrounds(zz,"jet_eta4");
      if(str=="Jet_multi") evaluateAndFillBackgrounds(zz,"jet_Multiplicity");
      if(str=="HT") evaluateAndFillBackgrounds(zz,"HT");
      if(str=="HT_1j") evaluateAndFillBackgrounds(zz,"HT1");
      if(str=="HT_2j") evaluateAndFillBackgrounds(zz,"HT2");
      if(str=="HT_3j") evaluateAndFillBackgrounds(zz,"HT3");
      if(str=="HT_4j") evaluateAndFillBackgrounds(zz,"HT4");
      if(str=="Phi_star") evaluateAndFillBackgrounds(zz,"PhiStar");
     }  
    }
    
    //======================
    // ww+jets
    WWf->cd("validationJEC");
    if (isMu) WWf->cd("validationJECmu/");

    if (isAngularAnalysis) {
      WWf->cd("validationJEC/");
      if (isMu) WWf->cd("validationJECmu/");
    }

    TH1F* ww;
    gDirectory->GetObject(plot.c_str(),ww);
    if(ww){
      ww->SetFillColor(kBlack);
      ww->Sumw2();

      if(wwEvents>0.){
	if(lumiweights==1) {
	  if (WholeStat){
	    if (lumiPixel) ww->Scale( dataLumi2011pix / (wwEvents / WWXsect));
	    else ww->Scale( dataLumi2011 / (wwEvents / WWXsect));
	  }
	  else{
	    if (RunA){
	      if (lumiPixel) ww->Scale( dataLumi2011Apix / (wwEvents / WWXsect));
	      else ww->Scale( dataLumi2011A / (wwEvents / WWXsect));
	    }
	    if (!RunA){
	      if (lumiPixel) ww->Scale( dataLumi2011Bpix / (wwEvents / WWXsect));
	      else ww->Scale( dataLumi2011B / (wwEvents / WWXsect));
	    }
	  }
	}
      }
      else {
	if(lumiweights==1) ww->Scale(wwjetsScale);
      }
      // fin qui
		
      if(lumiweights==1) ww->Scale(1./wwwemean);  // perche' i Weights non fanno 1...
      ww->Rebin(rebin);
      if(lumiweights==0) ww->Draw("HISTO SAMES");
      hsum->Rebin(rebin);
      hsum->Add(ww);
      legend->AddEntry(ww,"WW+jets","f");

      //////////
      //Storing the bckgrounds!
      //////////
     if (isAngularAnalysis){
      if(str=="jet_pT") evaluateAndFillBackgrounds(ww,"jet_pT");
      if(str=="jet_pT2") evaluateAndFillBackgrounds(ww,"jet_pT2");
      if(str=="jet_pT3") evaluateAndFillBackgrounds(ww,"jet_pT3");
      if(str=="jet_pT4") evaluateAndFillBackgrounds(ww,"jet_pT4");
      if(str=="jet_eta") evaluateAndFillBackgrounds(ww,"jet_eta");
      if(str=="jet_eta2") evaluateAndFillBackgrounds(ww,"jet_eta2");
      if(str=="jet_eta3") evaluateAndFillBackgrounds(ww,"jet_eta3");
      if(str=="jet_eta4") evaluateAndFillBackgrounds(ww,"jet_eta4");
      if(str=="Jet_multi") evaluateAndFillBackgrounds(ww,"jet_Multiplicity");
      if(str=="HT") evaluateAndFillBackgrounds(ww,"HT");
      if(str=="HT_1j") evaluateAndFillBackgrounds(ww,"HT1");
      if(str=="HT_2j") evaluateAndFillBackgrounds(ww,"HT2");
      if(str=="HT_3j") evaluateAndFillBackgrounds(ww,"HT3");
      if(str=="HT_4j") evaluateAndFillBackgrounds(ww,"HT4");
      if(str=="Phi_star") evaluateAndFillBackgrounds(ww,"PhiStar");
     }
    }

    /// Tau 

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

    mcftau->cd("validationJEC");
    if (isMu) mcftau->cd("validationJECmu/");

    if (isAngularAnalysis) {
      mcftau->cd("validationJEC/");
      if (isMu) mcftau->cd("validationJECmu/");
    }

    TH1F* tau;
    gDirectory->GetObject(plot.c_str(),tau);
    if(tau){
      tau->SetFillColor(kGreen);
      tau->Sumw2();

      if(zNumEvents>0.){
	if(lumiweights==1) {
	  if (WholeStat){
	    if (lumiPixel) tau->Scale( dataLumi2011pix / (zNumEvents / zjetsXsect));
	    else tau->Scale( dataLumi2011 / (zNumEvents / zjetsXsect));
	  }
	  else{
	    if (RunA){
	      if (lumiPixel) tau->Scale( dataLumi2011Apix / (zNumEvents / zjetsXsect));
	      else tau->Scale( dataLumi2011A / (zNumEvents / zjetsXsect));
	    }
	    if (!RunA){
	      if (lumiPixel) tau->Scale( dataLumi2011Bpix / (zNumEvents / zjetsXsect));
	      else tau->Scale( dataLumi2011B / (zNumEvents / zjetsXsect));
	    }
	  }
	}
      }
      else {
	if(lumiweights==1) tau->Scale(zjetsScale);
      }
      // fin qui
		
      if(lumiweights==1) tau->Scale(1./zwemean);  // perche' i Weights non fanno 1...
      tau->Rebin(rebin);
      if(lumiweights==0) tau->Draw("HISTO SAMES");
      hsum->Rebin(rebin);
      tau->Scale(1./1000.); //aaaaaaa
      hsum->Add(tau);
      legend->AddEntry(tau,"#tau#tau+jets","f");

      //////////
      //Storing the bckgrounds!
      //////////
     if (isAngularAnalysis){
      if(str=="jet_pT") evaluateAndFillBackgrounds(tau,"jet_pT");
      if(str=="jet_pT2") evaluateAndFillBackgrounds(tau,"jet_pT2");
      if(str=="jet_pT3") evaluateAndFillBackgrounds(tau,"jet_pT3");
      if(str=="jet_pT4") evaluateAndFillBackgrounds(tau,"jet_pT4");
      if(str=="jet_eta") evaluateAndFillBackgrounds(tau,"jet_eta");
      if(str=="jet_eta2") evaluateAndFillBackgrounds(tau,"jet_eta2");
      if(str=="jet_eta3") evaluateAndFillBackgrounds(tau,"jet_eta3");
      if(str=="jet_eta4") evaluateAndFillBackgrounds(tau,"jet_eta4");
      if(str=="Jet_multi") evaluateAndFillBackgrounds(tau,"jet_Multiplicity");
      if(str=="HT") evaluateAndFillBackgrounds(tau,"HT");
      if(str=="HT_1j") evaluateAndFillBackgrounds(tau,"HT1");
      if(str=="HT_2j") evaluateAndFillBackgrounds(tau,"HT2");
      if(str=="HT_3j") evaluateAndFillBackgrounds(tau,"HT3");
      if(str=="HT_4j") evaluateAndFillBackgrounds(tau,"HT4");
      if(str=="Phi_star") evaluateAndFillBackgrounds(tau,"PhiStar");
     }
    }


    /////////
    // Print the bkg contributions
    ////////

    for(int j=0;j<bckg_leadingJetPt.size();j++){      
      cout<<bckg_leadingJetPt[j]<<endl;
    }	

    //======================
    // QCD EM enriched
    qcd23emf->cd("validationJEC");
    TH1F* qcd23emp;
    gDirectory->GetObject(plot.c_str(),qcd23emp);

    if(qcd23emp){
      TH1D * qcdTotEM =  (TH1D*) qcd23emp->Clone(); 
      qcdTotEM->SetTitle("qcd em");
      qcdTotEM->SetName("qcd em");
      qcdTotEM->Reset();
      qcdTotEM->Rebin(rebin);

      qcd38emf->cd("validationJEC");
      TH1F* qcd38emp;
      gDirectory->GetObject(plot.c_str(),qcd38emp);


      qcd817emf->cd("validationJEC");
      TH1F* qcd817emp;
      gDirectory->GetObject(plot.c_str(),qcd817emp);

      qcd23emp->Rebin(rebin);
      qcd23emp->Sumw2();
      qcd23emp->Scale(qcd23emScale); 
      qcd38emp->Rebin(rebin);
      qcd38emp->Sumw2();
      qcd38emp->Scale(qcd38emScale); 
      qcd817emp->Rebin(rebin);
      qcd817emp->Sumw2();
      qcd817emp->Scale(qcd817emScale); 

      qcdTotEM->SetFillColor(kOrange+1);
      qcdTotEM->Add(qcd23emp);
      qcdTotEM->Add(qcd38emp);
      qcdTotEM->Add(qcd817emp);

      hsum->Add(qcdTotEM);

      //if(lumiweights==1)legend->AddEntry(qcdTotEM,"QCD em","f");
    }

    //======================
    // QCD bc
    qcd23bcf->cd("validationJEC");
    TH1F* qcd23bcp;
    TH1D * qcdTotBC;
    bool  qcdbcempty=true;
    gDirectory->GetObject(plot.c_str(),qcd23bcp);

    if(qcd23bcp){
      qcdTotBC =  (TH1D*) qcd23bcp->Clone(); 
      qcdTotBC->SetTitle("qcd bc");
      qcdTotBC->SetName("qcd bc");
      qcdTotBC->Reset();
      qcdTotBC->Rebin(rebin);

      qcd38bcf->cd("validationJEC");
      TH1F* qcd38bcp;
      gDirectory->GetObject(plot.c_str(),qcd38bcp);

      qcd817bcf->cd("validationJEC");
      TH1F* qcd817bcp;
      gDirectory->GetObject(plot.c_str(),qcd817bcp);

      qcd23bcp->Rebin(rebin);
      qcd23bcp->Sumw2();
      qcd23bcp->Scale(qcd23bcScale); 
      qcd38bcp->Rebin(rebin);
      qcd38bcp->Sumw2();
      qcd38bcp->Scale(qcd38bcScale); 
      qcd817bcp->Rebin(rebin);
      qcd817bcp->Sumw2();
      qcd817bcp->Scale(qcd817bcScale); 

      qcdTotBC->SetFillColor(kGreen+2);
      qcdTotBC->Add(qcd23bcp);
      qcdTotBC->Add(qcd38bcp);
      qcdTotBC->Add(qcd817bcp);

      hsum->Add(qcdTotBC);
      if (qcdTotBC->GetEntries()>0) qcdbcempty=false; 

      //if(lumiweights==1)legend->AddEntry(qcdTotBC,"QCD bc","f");
    }

    //======================
    // Add here other backgrounds


    //======================
    // Stacked Histogram
    //if(qcd23em) 	hs->Add(qcdTotEM);
    if(!qcdbcempty) 	hs->Add(qcdTotBC);
    if(w)  	        hs->Add(w);
    if (ww)         hs->Add(ww);
    if(tau)		hs->Add(tau); //Z+Jets
    if (zz)         hs->Add(zz);
    if (wz)         hs->Add(wz);
    if (ttbar)	hs->Add(ttbar);
    if(mc)		hs->Add(mc); //Z+Jets

    // per avere le statistiche
    if(lumiweights==1) hsum->Draw("HISTO SAME");


    //======================
    // Setting the stats
    //pad1->Update(); // altrimenti non becchi la stat
    
    //TPaveStats *r2;
    //if(lumiweights==0) r2 = (TPaveStats*)mc->FindObject("stats");
    //if(lumiweights==1) r2 = (TPaveStats*)hsum->FindObject("stats");
    //r2->SetY1NDC(0.875);     //Uncomment if you wonna add your statistics in the top right corner
    //r2->SetY2NDC(0.75); 
    //r2->SetTextColor(kRed);
		
    if(lumiweights==1) hs->Draw("HISTO SAME");
    gPad->RedrawAxis();
    data->Draw("E1 SAME");
    //r2->Draw(); //here to reactivate the stats
    legend->Draw();
    TLegend* lumi = new TLegend(0.45,0.3,0.75,0.2);
    lumi->SetFillColor(0);
    lumi->SetFillStyle(0);
    lumi->SetBorderSize(0);
    //lumi->AddEntry((TObject*)0,"#int L dt =4.9 1/fb","");
    lumi->Draw();
    string channel;
    if (isMu) channel="Z#rightarrow#mu#mu";
    if (!isMu) channel="Z#rightarrow ee";
    TLatex *latexLabel=CMSPrel(4.890,channel,0.55,0.85); // make fancy label
    latexLabel->Draw("same");

    CanvPlot->Update();

	


    //===============//
    // RATIO DATA MC //
    //===============//
    CanvPlot->cd();
    TPad *pad2 = new TPad("pad2","pad2",0.01,0.01,0.99,0.32);
    pad2->Draw();
    pad2->cd();
    pad2->SetTopMargin(0.01);
    pad2->SetBottomMargin(0.3);
    pad2->SetRightMargin(0.1);
    pad2->SetFillStyle(0);

    TH1D * ratio =  (TH1D*) data->Clone();
    ratio->SetTitle("");
    ratio->SetName("ratio");
    ratio->Reset();

    ratio->Sumw2();
    //data->Sumw2();
    hsum->Sumw2(); // FIXME controlla che sia corretto questo... 
    ratio->SetMarkerSize(.5);
    ratio->SetLineColor(kBlack);
    ratio->SetMarkerColor(kBlack);
    //gStyle->SetOptStat("m");
    TH1F* sumMC;

    hs->Draw("nostack"); 
 
   sumMC=(TH1F*) hs->GetHistogram();
    cout<<sumMC->GetEntries()<<endl;
    ratio->Divide(data,hsum,1.,1.);
    ratio->GetYaxis()->SetRangeUser(0.5,1.5);
    ratio->SetMarkerSize(0.8);
    //pad2->SetTopMargin(1);

   //Canvas style copied from plotsHistsRatio.C
    ratio->GetYaxis()->SetNdivisions(5);
    ratio->GetXaxis()->SetTitleSize(0.14);
    ratio->GetXaxis()->SetLabelSize(0.14);
    ratio->GetYaxis()->SetLabelSize(0.11);
    ratio->GetYaxis()->SetTitleSize(0.11);
    ratio->GetYaxis()->SetTitleOffset(0.43);
    ratio->GetYaxis()->SetTitle("ratio data/MC");   

    ratio->Draw("E1");
		
    TLine *OLine = new TLine(ratio->GetXaxis()->GetXmin(),1.,ratio->GetXaxis()->GetXmax(),1.);
    OLine->SetLineColor(kBlack);
    OLine->SetLineStyle(2);
    OLine->Draw();
 
    TLegend* label = new TLegend(0.60,0.9,0.50,0.95);
    label->SetFillColor(0);
    label->SetFillStyle(0);
    label->SetBorderSize(0);
    //horrible mess
    double binContent = 0;
    double binSum = 0;
    double weightSum = 0;
    double binError = 1;
    double totalbins = ratio->GetSize() -2;
    for(unsigned int bin=1;bin<=totalbins;bin++){
      binContent = ratio->GetBinContent(bin);
      binError = ratio->GetBinError(bin);
      if(binError!=0){
	binSum += binContent/binError;
	weightSum += 1./binError;
      }
    }
    double ymean = binSum / weightSum;
    //double ymean = ratio->GetMean(2);
    stringstream sYmean;
    sYmean << ymean;
    string labeltext=sYmean.str()+" mean Y";
    //label->AddEntry((TObject*)0,labeltext.c_str(),""); // mean on Y
    //label->Draw();
		
    //TPaveStats *r3 = (TPaveStats*)ratio->FindObject("stats");
    //r3->SetX1NDC(0.01);
    //r3->SetX2NDC(0.10); 
    //r3->SetY1NDC(0.20);
    //r3->SetY2NDC(0.50); 
    //gStyle->SetOptStat("mr");
    //r3->SetTextColor(kWhite);
    //r3->SetLineColor(kWhite);
    //r3->Draw();
    CanvPlot->Update();

    tmp=plotpath+plot+".png";
    CanvPlot->Print(tmp.c_str());

  }
  else if (flag==2){
    //CanvPlot.Divide(2,1);
    //CanvPlot.cd(1);

    // data
    dataf->cd("validationJEC");
    if (isMu && isAngularAnalysis) dataf->cd("validationJECmu");

    gDirectory->GetObject(plot.c_str(),data2);
    data2->Draw("COLZ");

    gPad->Update(); // altrimenti non becchi la stat
    TPaveStats *r1 = (TPaveStats*)data2->FindObject("stats");
    //r1->SetX1NDC(0.70); Uncomment if you wonna draw your stat in the top right corner
    //r1->SetX2NDC(0.85); 
    //r1->Draw();
    CanvPlot->Update();

    tmp=plotpath+plot+"data.png";
    CanvPlot->Print(tmp.c_str());


    //CanvPlot.cd(2);
    // montecarlo
    mcf->cd("validationJEC");
    if (isMu) mcf->cd("validationJECmu/");

    if (isAngularAnalysis) {
      mcf->cd("validationJEC/");
      if (isMu) mcf->cd("validationJECmu/");
    }

    gDirectory->GetObject(plot.c_str(),data2);

    data2->SetMinimum(1);
    data2->Draw("COLZ");

    gPad->Update(); // altrimenti non becchi la stat
    //TPaveStats *r2 = (TPaveStats*)data2->FindObject("stats");
    //r2->SetX1NDC(0.70);
    //r2->SetX2NDC(0.85); 
    //r2->Draw();
    CanvPlot->Update();

    tmp=plotpath+plot+"mc.png";
    CanvPlot->Print(tmp.c_str());
  }
  //	else { cout << "You're getting an exception! Most likely there's no histogram here... \n"; }

  delete data;
  delete data2;
  delete hs;
  //delete CanvPlot;

  dataf->Close();
  mcf->Close();
  ttbarf->Close();
  wf->Close();
  qcd23emf->Close();
  qcd38emf->Close();
  qcd817emf->Close();
  qcd23bcf->Close();
  qcd38bcf->Close();
  qcd817bcf->Close();
  WZf->Close();
  ZZf->Close();
  
  if (isAngularAnalysis){
    if (bckg_leadingJetPt.size()>0 && bckg_2leadingJetPt.size()>0 && bckg_3leadingJetPt.size()>0 && bckg_4leadingJetPt.size()>0  && bckg_JetMultiplicity.size()>0 && bckg_HT.size()>0 && bckg_leadingJetEta.size()>0 && bckg_PhiStar.size()>0 && cold){
      fzj->cd();
      treeBKG_->Fill();
      treeBKG_->Write();
      TH1F *leadhisto=new TH1F("leadhisto","leading jet background contribution",bckg_leadingJetPt.size(),0,bckg_leadingJetPt.size());
      TH1F *leadhisto2=new TH1F("leadhisto2","subleading jet background contribution",bckg_leadingJetPt.size(),0,bckg_leadingJetPt.size());
      TH1F *leadhisto3=new TH1F("leadhisto3","subsubleading jet background contribution",bckg_leadingJetPt.size(),0,bckg_leadingJetPt.size());
      TH1F *leadhisto4=new TH1F("leadhisto4","subsubsubleading jet background contribution",bckg_leadingJetPt.size(),0,bckg_leadingJetPt.size());
      TH1F *multiphisto=new TH1F("multiphisto","jet multiplicity background contribution",bckg_JetMultiplicity.size(),0,bckg_JetMultiplicity.size());

      TH1F *HT=new TH1F("HT","HT background contribution",bckg_HT.size(),0,bckg_HT.size());
      TH1F *HT1=new TH1F("HT1","HT background contribution when >= 1 jet",bckg_HT1.size(),0,bckg_HT1.size());
      TH1F *HT2=new TH1F("HT2","HT background contribution when >= 2 jets",bckg_HT2.size(),0,bckg_HT2.size());
      TH1F *HT3=new TH1F("HT3","HT background contribution when >= 3 jets",bckg_HT3.size(),0,bckg_HT3.size());
      TH1F *HT4=new TH1F("HT4","HT background contribution when >= 4 jets",bckg_HT4.size(),0,bckg_HT4.size());

      TH1F *leadhistoeta=new TH1F("leadhistoeta","leading jet background contribution",bckg_leadingJetEta.size(),0,bckg_leadingJetEta.size());
      TH1F *leadhistoeta2=new TH1F("leadhistoeta2","subleading jet background contribution",bckg_leadingJetEta.size(),0,bckg_leadingJetEta.size());
      TH1F *leadhistoeta3=new TH1F("leadhistoeta3","subsubleading jet background contribution",bckg_leadingJetEta.size(),0,bckg_leadingJetEta.size());
      TH1F *leadhistoeta4=new TH1F("leadhistoeta4","subsubsubleading jet background contribution",bckg_leadingJetEta.size(),0,bckg_leadingJetEta.size());

      TH1F *PhiStar=new TH1F("PhiStar","PhiStar background contribution",bckg_PhiStar.size(),0,bckg_PhiStar.size());

      for (int i=0; i< bckg_leadingJetPt.size(); i++){
	leadhisto->Fill(i,bckg_leadingJetPt[i]);
	leadhisto2->Fill(i,bckg_2leadingJetPt[i]);
	leadhisto3->Fill(i,bckg_3leadingJetPt[i]);
	leadhisto4->Fill(i,bckg_4leadingJetPt[i]);
      }
      leadhisto->Write();
      leadhisto2->Write();
      leadhisto3->Write();
      leadhisto4->Write();

      for (int i=0; i< bckg_leadingJetEta.size(); i++){
	leadhistoeta->Fill(i,bckg_leadingJetEta[i]);
	leadhistoeta2->Fill(i,bckg_2leadingJetEta[i]);
	leadhistoeta3->Fill(i,bckg_3leadingJetEta[i]);
	leadhistoeta4->Fill(i,bckg_4leadingJetEta[i]);
      }
      leadhistoeta->Write();
      leadhistoeta2->Write();
      leadhistoeta3->Write();
      leadhistoeta4->Write();
      //fzj->Close();

      for (int i=0; i< bckg_JetMultiplicity.size(); i++){
	multiphisto->Fill(i,bckg_JetMultiplicity[i]);
      }
      multiphisto->Write();
      
      ///////////////

      for (int i=0; i< bckg_HT.size(); i++){
	HT->Fill(i,bckg_HT[i]);
      }
      HT->Write();
      
      for (int i=0; i< bckg_HT1.size(); i++){
	HT1->Fill(i,bckg_HT1[i]);
      }
      HT1->Write();
      
      for (int i=0; i< bckg_HT2.size(); i++){
	HT2->Fill(i,bckg_HT2[i]);
      }
      HT2->Write();
      
      for (int i=0; i< bckg_HT3.size(); i++){
	HT3->Fill(i,bckg_HT3[i]);
      }
      HT3->Write();
      
      for (int i=0; i< bckg_HT4.size(); i++){
	HT4->Fill(i,bckg_HT4[i]);
      }
      HT4->Write();

      //Phi star
      for (int i=0; i< bckg_PhiStar.size(); i++){
	PhiStar->Fill(i,bckg_PhiStar[i]);
      }
      PhiStar->Write();

    cold=false;
    }
  }
  return;
}
Exemple #30
0
// === Main Function ===================================================
void general1(int sampleId) {
  std::cout << "Analysing the " << sampleLabel(sampleId) << " sample" << std::endl;


  // --- Declare the Output Histograms ---------------------------------
  TH1* hNJets = new TH1F("hNJets",";N(jets);N(events)",12,0,12);
  hNJets->Sumw2();
  TH1* hHt = new TH1F("hHt",";H_{T} [GeV]",30,0,3000);
  hHt->Sumw2();
  hHt->GetXaxis()->SetNdivisions(505);
  TH1* hMht = new TH1F("hMht",";#slash{H}_{T} [GeV]",30,0,1500);
  hMht->Sumw2();
  hMht->GetXaxis()->SetNdivisions(505);
  TH1* hMEff = new TH1F("hMEff",";M_{eff} [GeV]",50,0,5000);
  hMEff->Sumw2();
  hMEff->GetXaxis()->SetNdivisions(505);
  std::vector<TH1*> hJetPt(6);
  std::vector<TH1*> hJetPhi(6);
  std::vector<TH1*> hJetEta(6);
  for(unsigned int i = 0; i < hJetEta.size(); ++i) {
    TString name = "hJetPt_";
    name += i;
    TString title = ";p_{T}(jet ";
    title += i+1;
    title += ") [GeV];N(events)";
    hJetPt.at(i) = new TH1F(name,title,30,0,1500);
    hJetPt.at(i)->Sumw2();

    name = "hJetPhi_";
    name += i;
    title = ";#phi(jet ";
    title += i+1;
    title += ");N(events)";
    hJetPhi.at(i) = new TH1F(name,title,24,-4,4);
    hJetPhi.at(i)->Sumw2();

    name = "hJetEta_";
    name += i;
    title = ";#eta(jet ";
    title += i+1;
    title += ");N(events)";
    hJetEta.at(i) = new TH1F(name,title,25,-5,5);
    hJetEta.at(i)->Sumw2();
  }



  // --- Declare the Variables Read from the Tree ----------------------
  // Reco-level jets
  int nRecoJets = 0;
  float recoJetPt[kRecoJetColSize];
  float recoJetPhi[kRecoJetColSize];
  float recoJetEta[kRecoJetColSize];

  // Number of reco-level muons and electrons
  int nRecoMus = 0;
  int nRecoEle = 0;

  // MC Event weight
  float evtWgt = 1.;



  // --- Set Up the Tree -----------------------------------------------

  // Get the tree from file
  TChain* tr = new TChain("AnaTree");
  tr->Add("/nfs/dust/test/cmsdas/school61/susy/ntuple/2013-v1/"+fileName(sampleId)+"_0.root");

  // Set the branches
  tr->SetBranchAddress("NrecoJet",&nRecoJets);
  tr->SetBranchAddress("recoJetPt",recoJetPt);
  tr->SetBranchAddress("recoJetPhi",recoJetPhi);
  tr->SetBranchAddress("recoJetEta",recoJetEta);
  tr->SetBranchAddress("NrecoMu",&nRecoMus);
  tr->SetBranchAddress("NrecoEle",&nRecoEle);
  if( sampleId > 0 ) tr->SetBranchAddress("EvtWgt",&evtWgt);



  // --- Process the Events in the Tree --------------------------------
  int nEvtsToProcess = tr->GetEntries();
  std::cout << "Processing " << nEvtsToProcess << " events" << std::endl;

  // Loop over the tree entries
  for(int evtIdx = 0; evtIdx < nEvtsToProcess; ++evtIdx) {
    if( evtIdx%100000 == 0 ) std::cout<<"  Event: " << evtIdx << std::endl;

    // Get the variables' values for this event
    tr->GetEntry(evtIdx);
    if( nRecoJets > kRecoJetColSize ) {
      std::cerr << "ERROR: more than " << kRecoJetColSize << " reco jets in event " << evtIdx << std::endl;
      exit(-1);
    }


    // Apply the lepton veto
    if( nRecoEle > 0 ) continue;
    if( nRecoMus > 0 ) continue;


    // Calculate RA2 selection-variables from jets
    float selNJet = 0; // Number of jets with pt > 50 GeV and |eta| < 2.5 (HT jets)
    float selHt   = 0.;
    float selMhtX = 0.;
    float selMhtY = 0.;
    // Loop over reco jets: they are ordered in pt
    for(int jetIdx = 0; jetIdx < nRecoJets; ++jetIdx) {
      // Calculate NJet and HT
      if( recoJetPt[jetIdx] > kHtJetPtMin && TMath::Abs(recoJetEta[jetIdx]) < kHtJetEtaMax ) {
	selNJet++;
	selHt += recoJetPt[jetIdx];
      }
      // Calculate MHT components
      if( recoJetPt[jetIdx] > kMhtJetPtMin && TMath::Abs(recoJetEta[jetIdx]) < kMhtJetEtaMax ) {
	selMhtX -= recoJetPt[jetIdx]*TMath::Cos(recoJetPhi[jetIdx]);
	selMhtY -= recoJetPt[jetIdx]*TMath::Sin(recoJetPhi[jetIdx]);
      }
    } // End of loop over reco jets
    float selMht = sqrt( selMhtX*selMhtX + selMhtY*selMhtY );
    

    // Select only events with at least 2 HT jets
    if( selNJet < 3 ) continue;



    //>>> PLACE OTHER RA2 CUTS HERE




    
    // Event weight in plots
    float weight = 1.;
    if( sampleId == 1 ) weight = evtWgt; // In case of the flat QCD-MC, reweight to physical spectrum

    
    // Fill histogram
    hNJets->Fill(selNJet,weight);
    hHt->Fill(selHt,weight);
    hMht->Fill(selMht,weight);
    hMEff->Fill(selHt+selMht,weight);
    for(int i = 0; i < static_cast<int>(hJetPt.size()); ++i) {
      if( i == nRecoJets ) break;
      hJetPt.at(i)->Fill(recoJetPt[i],weight);
      hJetPhi.at(i)->Fill(recoJetPhi[i],weight);
      hJetEta.at(i)->Fill(recoJetEta[i],weight);
    }
  } // End of loop over events



  // --- Save the Histograms to File -----------------------------------
  TFile outFile("General_"+fileName(sampleId)+".root","RECREATE");
  hNJets->Write();
  hHt->Write();
  hMht->Write();
  hMEff->Write();
  for(unsigned int i = 0; i < hJetPt.size(); ++i) {
    hJetPt[i]->Write();
    hJetEta[i]->Write();
    hJetPhi[i]->Write();
  }  
}